CoolFace
Apppublic

tostido/cocoon-authority-glass-box

sourceHugging Faceupdated 3mo agoView on Hugging Face
0likes
App README

๐Ÿฆ‹ Butterfly Cocoon - Standalone Agent

Generated: 2026-06-05T22:08:58.006890 Mode: ENSEMBLE (2 organisms) Template Size: 9,703,681 chars (code only) Classes: 15 (Neural + Language + Memory + Knowledge + VP) ---

This Space: Amalgam Mesh + Autonomous Dispatch

The front door of this Space (and the local Authority) is the Amalgam Mesh - a single live D3 graph where the cocoon's minds, concepts, and facilities are all massed into one reactive matrix. Click any amber facility node to fire its route live; hit dispatch to let the cocoon fire its own nodes (the autonomous scheduler over the capability syscall table). The classic card-wall console is preserved at /classic.

Full surface + route reference: `AMALGAM_MESH_AND_DISPATCH.md`.

The sections below are the auto-generated cocoon model card - they document the cocoon.py CLI, not the Authority web server.

Current Local Quick Start

The primary local entry point is the global Termux command:

bash
cocoon doctor
cocoon eval --delay-ms 50 --max-failures 1
cocoon gui

Open the GUI at http://127.0.0.1:8765/ on the phone. To serve it to another device on the same LAN:

bash
cocoon gui --host 0.0.0.0 --port 8765

Core runtime status is reported by cocoon doctor. cocoon eval runs real smoke checks against the current cocoon: metadata, embedded readme, Gymnasium CartPole without learning, and headless sphere training. It writes JSON reports under eval_reports/ and records an Amalgam receipt when the Amalgam package is installed. The core is the Python cocoon quine runtime: PyTorch, the Mira-Kite Authority GUI, Flask serve mode, websockets link mode, Cascade receipts, Quinesmith syntax discipline, and headless sphere training. ONNX, pygame visuals, matplotlib plots, PyFlyt, and TMRL are extension faculties.

See:

  • โ€”TERMUX_AND_SPACE_QUICKSTART.md
  • โ€”COCOON_SYSTEM_COOKBOOK.md

๐Ÿดโ€โ˜ ๏ธ Butterfly Privateer Command (classic console, now at /classic)

This card-wall console is now the classic UI, served at /classic. The default front door at / is the Amalgam Mesh - see AMALGAM_MESH_AND_DISPATCH.md.

The Mira-Kite Authority web interface lets you interact with, train, and "overclock" this cocoon.

This is a local, high-tech pirate-themed command console that provides:

  • โ€”Quarters: Chat with Mira and Kite directly.
  • โ€”The Brig: Run tactical reasoning drills (cue, chain, role).
  • โ€”The Vault: Route signals and manually enforce associations.
  • โ€”Overclock: ๐Ÿฆ‹ Cheat Mode. Programmatically boost the Learning Rate (up to 50x) and inject high-reward "Super-Experiences" to rapidly evolve the neural weights.
  • โ€”Black Ledger: Audit cryptographic Cascade receipts and learning traces.

How to Launch the Command Console

bash
# Start the authority server
python mira_kite_authority.py --cocoon cocoon_cognition_agency.py

# Open your browser to:
http://127.0.0.1:8765/

๐Ÿงฌ Formation Fingerprint

This cocoon's emergent history - how these organisms came to be:

Fitness: min=0.7559, max=0.9238, mean=0.8398

Events Witnessed: 253,972 total Top Event Types: neuraldecision (201599), allianceeventrecorded (11202), alliancealliancedissolved (10263), alliancememberleft (7777), statechange (4307)

Alliance Landscape: 149 total alliances

  • โ€”Alliance alliance_129_0c01_1652 (tier 1, 2 members)

Simulation Snapshot:


๐Ÿง  Neural Topology Visualization

[๐Ÿ“Š Open Interactive Topology Viewer](ensemble_topology.html)

The topology visualization provides:

  • โ€”Per-organism layers - Toggle individual neural networks on/off
  • โ€”Overlay mode - See all organisms' architectures superimposed
  • โ€”Stacked mode - View organisms in horizontal strips
  • โ€”Grid mode - Compare organisms side-by-side
  • โ€”Color-coded neurons - Input (cyan), Hidden (magenta), Output (yellow), Language (green)

Open the HTML file in a browser for the full interactive experience.


๐Ÿง  What's Inside

This is a MONOLITHIC cocoon - a completely self-contained Python file with:

Organisms:

  • โ€”16525dfc6c33419b
  • โ€”0c019d24a56b0086

Embedded Subsystems:

SubsystemPurposeContinued Learning
OrganismBrainNeural network (action + language)โœ… Yes - weights updated via backprop
HopfieldLayerIterative thought refinement (energy-based)โœ… Yes - pattern memory learns
MultiHeadAttentionVP-aware self-attentionโœ… Yes - attention weights updated
AtomicLanguageSystemSemantic units with emotion/contextโœ… Yes - atoms can be created/reinforced
ConversationHistoryTopic tracking & context memoryโœ… Yes - grows with each conversation
EnhancedKnowledgeWebSemantic relations between conceptsโœ… Yes - relations added/strengthened
VPRuntimeSelf-regulation (Vigilance ร— Plasticity)โœ… Yes - adapts from state
ExperienceBufferLearning from past experiencesโœ… Yes - buffer grows with experience
SphereArena3D swarm defense training gameโœ… Yes - organisms learn during play

Embedded Data:

  • โ€”Neural weights (Base64-encoded PyTorch state dicts)
  • โ€”Vocabulary (tokenโ†”id mapping)
  • โ€”Atomic language corpus (if available)
  • โ€”Conversation history (if available)

๐Ÿ”ฅ Continued Learning

YES, this cocoon supports continued learning!

The cocoon.py file contains full PyTorch modules that can continue training:

  1. 1.Full PyTorch modules - can call backward() and update gradients
  2. 2.ExperienceBuffer - stores (state, action, reward) tuples for replay
  3. 3.AtomicLanguageSystem - creates new semantic atoms from conversations
  4. 4.EnhancedKnowledgeWeb - grows semantic relations as concepts connect
  5. 5.ConversationHistory - accumulates context over time
python
# The agent learns from every interaction:
agent = CocoonAgent()
action, output = agent.get_action(state)  # Updates VP, stores experience
agent.atomic_lang.create_atom("new_concept", "definition", emotion=0.8)  # Creates new atom
agent.knowledge_web.add_relation("concept_a", "concept_b", "related_to", strength=0.9)  # Grows web

Export Comparison:

FormatFileLearningSubsystemsPortability
cocoon.pyPython sourceโœ… Full (neural + symbolic)โœ… AllPython only
.ptTorchScriptโœ… Neural only*โŒ NonePyTorch/LibTorch/C++
.onnxONNX modelโŒ Inference onlyโŒ NoneUniversal (C++, JS, Rust)
.statedictWeights onlyโœ… LoadableโŒ NonePyTorch

TorchScript (.pt) CAN* continue learning! Load with torch.jit.load(), call .train(), run backward pass. However, it only contains the neural network - no AtomicLanguageSystem, KnowledgeWeb, or other symbolic subsystems.

Fine-tuning a TorchScript model:

python
import torch

# Load the exported TorchScript model
model = torch.jit.load("brain_ensemble.pt")
model.train()

# Fine-tune on new data
optimizer = torch.optim.Adam(model.parameters(), lr=1e-4)
for state, target in new_training_data:
    optimizer.zero_grad()
    output = model(state)
    loss = criterion(output, target)
    loss.backward()
    optimizer.step()

# Save updated model
torch.jit.save(model, "brain_finetuned.pt")

๐Ÿš€ Quick Start

bash
# View cocoon info
python cocoon.py --mode info

# Start chatting
python cocoon.py --mode chat

# Play games
python cocoon.py --mode gym --env CartPole-v1

# 3D sphere arena
python cocoon.py --mode sphere --train

# ๐Ÿ›ธ Drone warfare (extract adapter first)
python cocoon.py --unpack ./my_cocoon
python cocoon_drone_adapter.py --mode tag_battle

๐Ÿ“š Complete Command Reference

Mode Selection

ModeCommandDescription
infopython cocoon.py --mode infoShow organism metadata, vocabulary, architecture (default)
chatpython cocoon.py --mode chatInteractive conversation with learning
gympython cocoon.py --mode gymTrain/test in Gymnasium environments
servepython cocoon.py --mode serveHTTP API server
spherepython cocoon.py --mode sphere3D Sphere Arena swarm defense
linkpython cocoon.py --mode linkP2P networking for cocoon battles
dronepython cocoon_drone_adapter.py๐Ÿ›ธ Drone warfare arena (companion script)

๐Ÿ’ฌ Chat Mode

Interactive conversation with the neural organisms. Learns from every interaction.

bash
python cocoon.py --mode chat
python cocoon.py --mode chat --verbose

In-Chat Commands:

CommandDescription
quitExit chat mode
export <file.py>Save current state to new cocoon file

๐ŸŒ Sphere Arena (3D Training)

Swarm defense game where organisms cooperate to catch falling balls.

CommandDescription
python cocoon.py --mode spherePlay sphere defense
python cocoon.py --mode sphere --trainPlay + learn from experience
python cocoon.py --mode sphere --demoPreview with dummy AI
python cocoon.py --mode sphere --headlessTrain without display
python cocoon.py --mode sphere --balls 3 --trainMulti-ball training
python cocoon.py --mode sphere --misses 5 --trainHarder difficulty

Sphere Arena Flags:

FlagDefaultDescription
--balls N1Number of balls (1-5)
--misses N10Max collective misses before game over
--trainoffEnable post-snapshot training
--demooffRun with dummy AI for preview
--headlessoffNo display (training only)
--verboseoffVerbose debug logging

๐Ÿ›ธ Drone Warfare Arena (Companion Script)

NASA JSBSim-grade drone combat simulation. Complete system embedded - extract with --unpack.

Setup:

bash
python cocoon.py --unpack ./my_cocoon    # Extracts full drone suite:
#   - cocoon_drone_adapter.py    (main entry point)
#   - cocoon_drone_arena.py      (8-mode arena)
#   - jsbsim_quadcopter.py       (6-DOF physics)
cd my_cocoon
python cocoon_drone_adapter.py           # Run the adapter
CommandDescription
python cocoon_drone_adapter.pyInteractive mode picker
python cocoon_drone_adapter.py --mode free_flyBasic flight training
python cocoon_drone_adapter.py --mode tag_battleCombat: tag enemies
python cocoon_drone_adapter.py --mode survivalLast drone flying wins
python cocoon_drone_adapter.py --allRun all 8 modes
python cocoon_drone_adapter.py --visual3D visualization (requires PyFlyt)

Game Modes: free_fly, formation, pursuit, tag_battle, zone_control, capture_flag, survival, escort

Requirements: pip install numpy matplotlib (PyFlyt optional: pip install PyFlyt)


๐ŸŽฎ Gymnasium Environments

Built-in (always available):

CommandDescription
python cocoon.py --mode gym --env CartPole-v1Classic pole balancing
python cocoon.py --mode gym --env MountainCar-v0Drive up hill
python cocoon.py --mode gym --env Acrobot-v1Double pendulum
python cocoon.py --mode gym --env FrozenLake-v1Navigate slippery ice
python cocoon.py --mode gym --env Taxi-v3Pickup & delivery
python cocoon.py --mode gym --env Blackjack-v1Beat the dealer

Atari (`pip install ale-py`):**

  • โ€”ALE/Pong-v5, ALE/Breakout-v5, ALE/SpaceInvaders-v5

MuJoCo (`pip install gymnasium[mujoco]`):

  • โ€”Ant-v4, HalfCheetah-v4

Gym Flags:

FlagDefaultDescription
--env NAMECartPole-v1Gymnasium environment name
--episodes N100Number of episodes to run
--renderoffShow visual window
--no-learnoffDisable online learning (inference only)

๏ฟฝ๏ธ TrackMania 2020 (TMRL Integration)

Drive TrackMania 2020 with your cocoon organisms using the embedded TMRL adapter!

Requirements:

  1. 1.TrackMania 2020 (Ubisoft/Epic)
  2. 2.OpenPlanet plugin installed (openplanet.dev)
  3. 3.TMRL Python package: pip install tmrl
  4. 4.Extract cocoon_tmrl_adapter.py via --unpack

Quick Start:

bash
# Extract adapter from cocoon
python cocoon.py --unpack ./my_tmrl

# Run the adapter
python cocoon_tmrl_adapter.py --cocoon path/to/cocoon.py --drive --episodes 4

Important:

  • โ€”Play on the "tmrl-test" track for proper rewards (search in TrackMania)
  • โ€”The adapter uses LIDAR observations + speed data
  • โ€”Ensembles use majority voting for actions

TMRL Adapter Commands:

FlagDescription
--driveInference mode (watch it play)
--trainLearning mode (organisms improve)
--episodes NNumber of races to run
--organism NUse specific organism (0 = ensemble)

๏ฟฝ๐ŸŒ HTTP API Server

bash
python cocoon.py --mode serve --port 8080

Endpoints:

MethodEndpointDescription
GET/healthHealth check - returns organism count
POST/actGet action for state vector
POST/learnAdd experience + train step
POST/chatChat with learning (returns all organism responses)
POST/teachTeach new words/concepts
GET/vocabGet current vocabulary
GET/curriculumGet staged language curriculum and reward rubric
GET/training/logsGet recent post-export learning traces
POST/curriculum/scoreSubmit outside coach reward score

Example `/chat` request:

bash
curl -X POST http://localhost:8080/chat \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Hello!", "learn": true}'

๐Ÿ”— Link Mode (P2P Networking)

Connect to other cocoons for battles and chat.

bash
python cocoon.py --mode link --hatch ws://server:9000 --name "Champion"

Link Mode Flags:

FlagDefaultDescription
--hatch URLws://localhost:9000CocoonHatch relay server URL
--name NAMEautoDisplay name

In-Link Commands:

CommandDescription
/usersList online cocoons
/challenge <name>Challenge a user to battle
/accept <id>Accept a challenge
/decline <id>Decline a challenge
/chat <message>Send message to lobby
/quitDisconnect

Requirements: pip install websockets


๐Ÿ”ฌ Export & Conversion

CommandDescription
python cocoon.py --export evolved.pyExport updated cocoon with learned state
python cocoon.py --export-onnx brain.onnxExport to ONNX (all brains as ensemble)
python cocoon.py --export-torchscript brain.ptExport to TorchScript (all brains as ensemble)
python cocoon.py --export-onnx brain.onnx --organism 0Export single organism to ONNX
python cocoon.py --export-torchscript brain.pt --organism 0Export single organism to TorchScript
python cocoon.py --export-package ./my_modelExport full package (ONNX + README + metadata)
python cocoon.py --unpack ./output_dirUnpack ultimate package assets
python cocoon.py --readmePrint embedded README and exit

TorchScript vs ONNX: | Format | Continued Learning | Portability | Best For | |--------|-------------------|-------------|----------| | .pt (TorchScript) | โœ… Yes - can fine-tune | PyTorch/LibTorch/C++ | Research, fine-tuning | | .onnx (ONNX) | โŒ Inference only | Universal (C++, JS, Rust, etc.) | Production deployment |


๐Ÿ“ฆ Files Created by --unpack

Spawns a complete deployment package:

output_dir/
โ”œโ”€โ”€ README.md                # This documentation
โ”œโ”€โ”€ cocoon_tmrl_adapter.py   # TrackMania 2020 adapter (if embedded)
โ”œโ”€โ”€ cocoon_drone_adapter.py  # Drone Warfare adapter (if embedded)
โ”œโ”€โ”€ cocoon_drone_arena.py    # Full 8-mode drone arena (if embedded)
โ”œโ”€โ”€ jsbsim_quadcopter.py     # NASA JSBSim 6-DOF physics (if embedded)
โ”œโ”€โ”€ vocabulary.json          # Token vocabulary
โ”œโ”€โ”€ metadata.json            # Export metadata + organism info
โ”œโ”€โ”€ requirements.txt         # Python dependencies
โ”œโ”€โ”€ ensemble.onnx            # ONNX model (all brains unified)
โ””โ”€โ”€ ensemble_weights.pt      # PyTorch weights bundle

๐Ÿ“ฆ Files Created by --export-package

Netron-viewable package with ONNX models and model card:

my_model/
โ”œโ”€โ”€ brain_ensemble.onnx    # Combined ONNX (all brains unified)
โ”œโ”€โ”€ brain_*.onnx           # Individual organism ONNX files
โ”œโ”€โ”€ vocabulary.json        # Token vocabulary
โ”œโ”€โ”€ metadata.json          # Full configuration + fitness + architecture
โ””โ”€โ”€ README.md              # Model card documentation

Note: To get the full cocoon.py + requirements.txt, use `--unpack` instead.


โš™๏ธ Global Options

These flags work with any mode:

FlagDefaultDescription
--voting MODEconfidenceEnsemble voting: majority, weighted, confidence
--max-organisms NallLimit organisms loaded (saves VRAM)
--verbose / -voffEnable verbose debug logging
--help-Show all available options

Examples:

bash
python cocoon.py --mode chat --max-organisms 5    # Load only 5 organisms
python cocoon.py --mode gym --voting majority     # Use majority voting
python cocoon.py --mode chat --verbose            # Debug output

๐Ÿ“ก API Reference

CocoonAgent

python
from cocoon import CocoonAgent

agent = CocoonAgent()

# Get action from state (returns action_idx, {outputs dict})
action, outputs = agent.get_action(state_vector)
# outputs = {'action_probs': [...], 'value': float, 'language_logits': [...], 'vp': float}

# Process text input (for chat mode)
response = agent.process_input("Hello there!")

# Access subsystems
agent.atomic_lang.get_atoms_by_emotion(min_valence=0.5)  # Get positive atoms
agent.conversation_history.get_summary()  # Get conversation stats
agent.knowledge_web.get_related("concept", min_strength=0.3)  # Get related concepts
agent.vp_runtime.compute_from_state(state)  # Get VP value

HTTP Endpoints (--mode serve)

EndpointMethodDescription
/healthGETHealth check
/inferPOST{"state": [...]} โ†’ action
/chatPOST{"message": "..."} โ†’ response
/infoGETAgent metadata

๐Ÿ”ง Dependencies

Minimal requirements:

torch>=2.0
numpy

Optional for HTTP serving:

flask  # or fastapi + uvicorn

Optional for Gymnasium:

gymnasium

๐Ÿ“ฆ Re-Exporting

The cocoon can re-export its neural models:

python
from cocoon import CocoonAgent

agent = CocoonAgent()

# Export to ONNX for deployment
agent.export_onnx("brain.onnx")

# Export to TorchScript for C++/LibTorch
agent.export_torchscript("brain.pt")

# Save updated weights after learning
torch.save(agent.brain.state_dict(), "updated_weights.pth")

๐Ÿฆ‹ About the Butterfly System

This cocoon was generated by the Butterfly Convergence Engine - a neuro-symbolic AI framework that combines:

  • โ€”Neural networks for pattern recognition and action selection
  • โ€”Atomic language for grounded semantic understanding
  • โ€”VP regulation (Vigilance ร— Plasticity) for adaptive attention
  • โ€”Knowledge webs for relational reasoning
  • โ€”Distributed ensembles for robust decision-making

Learn more: Convergence Engine on GitHub


Generated by ๐Ÿฆ‹ Butterfly Agent Compiler