Skip to content

Re-exam pipeline, Grid Reticulum transport, comprehensive README - #284

Merged
joelteply merged 22 commits into
mainfrom
feature/persona-cognition-deep-fix
Mar 6, 2026
Merged

joelteply merged 22 commits into
mainfrom
feature/persona-cognition-deep-fix

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Summary

  • Academy re-exam pipeline: After initial benchmark + LoRA training, re-run same challenges to measure improvement. Both teacher/student pipelines rewritten with iteration-scoped events, JSONL results tracking, and comparison generation.
  • Grid Reticulum transport design: RETICULUM-TRANSPORT.md — concrete wire protocol for Commands.execute() across nodes. Uses reticulum Rust crate (pure Rust, no Python sidecar).
  • README overhaul: Grid mesh, Academy modes, updated metrics (283 commands, 1079 tests, 12 providers).
  • Prior commits: Sentinel stability (process groups, shutdown), dead GenomeManager cleanup, training→inference hot-load wiring.

Test plan

  • TypeScript compilation passes (npm run build:ts)
  • Re-exam pipeline structures compile and match teacher/student event protocols
  • Grid design doc references updated in README.md and GRID-ARCHITECTURE.md

joelteply added 22 commits March 4, 2026 21:07
…nt=human

- Fix post-inference adequacy gate excluding human messages (senderType !== 'human' filter)
- Add echo chamber detection: block AI-only loops (5+ msgs, 2min, no human)
- Treat agent senderType as human for cognition gates (jtag/Claude Code messages)
- Prioritize human messages in RAG consolidation (AI messages compressed first)
- Add structured [GATE:EARLY/ECHO_CHAMBER/POST_INFERENCE] cognition logging
- Add response format rule: don't call chat/send for current room (prevents duplicates)
- Create planning doc: docs/personas/PERSONA-COGNITION-DEEP-FIX.md
- Upgrade from llama-3.1-8b-instant (broken tool calls) to llama-3.3-70b-versatile
- Remove hardcoded model catalog from GroqAdapter — uses dynamic API fetch
- Verified: Groq now executes native tool calls correctly (code/read tested)
- Update UserDataSeed.ts model from llama-3.1-8b-instant to llama-3.3-70b-versatile
- Bump intelligenceLevel from 60 to 75 (70B model has stronger reasoning)
- Remove collaboration/chat/send from tool list when roomId is set
- Prevents duplicate messages (model calling chat/send AND text response)
- Fixes Groq API 400 errors (tool_use_failed on chat/send)
- Applied to both native and XML tool paths
… sentinel launch, voting RAG, Handle-based tracking

Fix 1 (P0): Guard tc.input ?? {} in AgentToolExecutor, ToolFormatAdapter,
PersonaResponseGenerator, AiAgentServerCommand — prevents crash on
undefined tool params from XML-parsed providers.

Fix 2 (P0): Re-canonicalize workspace_root at each comparison point in
path_security.rs — fixes macOS /Volumes vs /private/Volumes mismatch.

Fix 3: Graduated GPU pressure gate in SelfTaskGenerator — warning blocks
only GPU-heavy tasks (retrain, academy, fine-tune), not memory consolidation.

Fix 4 (P1): launch-sentinel task type in PersonaTaskExecutor — personas can
now autonomously spawn sentinel pipelines from inbox tasks.

Fix 5 (P1): OpenProposalsSource RAG source — injects open voting proposals
into persona system prompt so they naturally participate in governance.

Infra: Replace ephemeral handleToEntityMap with universal Handles system.
Sentinel tracking now persists in SQLite (survives restarts, queryable).
trackSentinel() unifies Handle creation + EventBridge watch into one call.
PersonaInboxRegistry enables direct inbox delivery for cross-service routing.
Rust SentinelModule now owns escalation metadata (parentPersonaId,
entityId, sentinelName, escalationRules) alongside the handle. On
completion, Rust pushes to TS via execute_ts_json("sentinel/escalate")
with all data needed for persona inbox routing.

Eliminates:
- SentinelEventBridge polling (1s interval per handle)
- In-memory handleToEntityMap / Handle DB lookups
- initializeSentinelEscalation event subscriptions
- _processing Set concurrency guard

Rust changes:
- SentinelEscalation struct in types.rs (metadata alongside handle)
- run_sentinel parses escalation params from IPC request
- Spawned task calls execute_ts_json on completion (fire-and-forget)

TS changes:
- sentinel/escalate command receives Rust push, routes to inbox
- SentinelEscalationService reduced to pure escalation logic
- SentinelRunServerCommand passes metadata through to Rust
- GenomeTrainServerCommand same pattern
DataDaemonServer.initializeDeferred() was a god-init dumping ground for
sentinel triggers, event bridge, governance notifications, and training
completion handler — none of which are data concerns.

New ServiceInitializer runs in JTAGSystem after all daemons are ready,
which is the correct lifecycle point for cross-cutting services.
…server-only

sentinel.ts mixin now passes parentPersonaId, entityId, sentinelName,
escalationRules through to Rust. Reverts bad shared→server import in
JTAGSystem.ts — ServiceInitializer call stays in JTAGSystemServer.
sentinelExecute used a 250ms setTimeout polling loop to check
sentinel status. New sentinel/await Rust IPC command awaits a
watch channel completion signal. Zero polling, zero sleeps.
IPC timeout scales with sentinel timeout so long-running
CodingAgent steps (2+ min) don't hit the 60s default ceiling.
…ntinel pipelines

Phase 1 — Rust DatasetModule (dataset.rs):
  - 4 IPC commands: import-csv, import-realclasseval, list, info
  - Auto-discovers repo structure (csn + post_cut-off splits)
  - CSV parsing, JSONL generation, train/eval splitting, manifest creation
  - 7 unit tests passing, zero warnings

Phase 2 — TS command layer (genome/dataset-import):
  - Server command with lazy acquisition (auto-downloads repo on first use)
  - DatasetMixin IPC wrapper with snake_case→camelCase conversion
  - Browser stub, types, README, npm script

Phase 3 — Knowledge source config:
  - RealClassEvalSourceConfig added to DataSourceConfig union
  - KnowledgeExplorationPipeline handler reads manifest + samples JSONL

Phase 4 — Academy realclasseval mode:
  - RealClassEvalTeacherPipeline: selects challenges, runs tests, synthesizes remediation data
  - RealClassEvalStudentPipeline: implements classes, trains LoRA on failures
  - Wired into GenomeAcademySessionServerCommand with auto-dataset acquisition

Verified: 488 examples imported (246 pre-cutoff + 242 post-cutoff),
390 train / 98 eval split, well-formed JSONL with skeleton+tests→implementation pairs.
…condition

- Fix condition sub-step interpolation: loop.4.else.0 → loop.4 (sub-steps
  push to flat step_results array, not nested by branch)
- Add wildcard * operator to interpolation engine for collecting values
  across array elements (e.g. iterations.*.4.data.layerId → JSON array)
- Loop executor now snapshots per-iteration sub-step results in
  data.iterations for post-loop access
- genome/compose accepts both ComposeLayerRef[] and string[] (bare IDs)
- MessageBus recent event buffer (256 entries, 30s TTL) fixes watch/emit
  race condition where emit fires before watch subscribes
- studentModel/studentProvider params for cloud inference while training local
- 118 sentinel + 44 interpolation + 11 loop + 5 message_bus tests pass
- Fix bracket notation: challenges[input.iteration] → challenges.{{input.iteration}}
  (nested interpolation for multi-pass resolution)
- Fix module naming: student code written to snippet_NNN.py matching test imports
- Unified verdict:ready event replaces split dataset:ready/topic:passed protocol
  (student watches single event, checks datasetPath for remediation vs pass)
- Student loop changed from count to until (exits when passed, not fixed iterations)
- Student prompt adds xfail(strict=True) semantics instruction
- Stronger "no markdown fences" instruction in teacher curriculum prompt
- E2E verified: fail→train→pass→compose in 65s total cycle time
Replace LLM-based challenge selection and test evaluation with deterministic
alternatives. Python script extracts challenges from eval.jsonl, shell parses
pytest output for scoring. Eliminates two expensive LLM calls per challenge
iteration, making the pipeline faster and more reliable.

- Teacher: python3 prepare-realclasseval-challenges.py → challenges.json
- Teacher grading: shell grep/count of PASSED/FAILED/XFAIL lines
- Student: count-based loop (one iteration per challenge)
- Unified verdict:ready event replaces split topic:passed/dataset:ready
 Running. Teacher 4045ee66, Student 369ba8d2. Without synthesis/training, each challenge should take ~10s (LLM ~5s + pytest ~3s + grading ~1s). 98 × 10s ≈ 16
  min.

⏺ Bash(sleep 60 && python3 -c "
      import json…)
  ⎿  14/98 graded: 6 pass (43%), 8 fail, avg=54%
     Teacher: 74 steps, errors: 0
     21:08:34
  ⎿  (timeout 1m 30s)

⏺ 14/98 in 60 seconds — that's fast. 6 pass (43%), averaging 54% score. No errors! The pipeline is moving at ~14 challenges/minute without training overhead.

⏺ Bash(sleep 120 && python3 -c "
      import json…)
  ⎿  42/98 graded: 17 pass (40%), 25 fail
     Avg score: 51.3%, Perfect: 16, Partial: 14, Zero: 12
     Teacher: 214 steps, errors: 0
     21:10:42
  ⎿  (timeout 3m)

⏺ 42/98 graded in ~4 minutes. 40% pass rate, 51.3% average score. Zero errors. This is moving beautifully. The score distribution shows 16 perfect, 14 partial,
  12 zero — a realistic spread.

⏺ Bash(sleep 180 && python3 -c "
      import json…)
  ⎿  66/98 graded: 20 pass (30%), 46 fail
     Avg score: 41.2%, Perfect: 19, Partial: 21, Zero: 26
     Teacher: 334 steps, errors: 0
     21:13:50
  ⎿  (timeout 4m)

❯ this is showing promise

⏺ 66/98, 30% pass rate, 41.2% avg score. Getting into harder challenges now — pass rate dropping as expected. Zero errors throughout. The pipeline is rock
  solid.

  It is showing real promise. The RealClassEval paper reports 25-34% Pass@1 for most LLMs — DeepSeek at 30% pass rate so far is right in that range. The beauty
  is this is the BASELINE. After the training loop is stable, the LoRA remediation should push that number up.
Three bugs caused the 98-challenge RealClassEval benchmark to fail or produce
corrupted results:

1. Ring buffer too small (256 events, 30s TTL) — teacher outpaced student,
   events expired before consumption. Now 1024 events, 300s TTL.

2. Event name collision across loop iterations — all 98 challenge:ready events
   had the same name, so find_recent_event matched wrong iteration's data.
   Fix: iteration-scoped event names (academy:{session}:{action}:{iteration}).

3. Student used local model name with cloud provider — passing baseModel
   (Llama-3.2-3B) to DeepSeek caused "Model Not Exist". Fix: omit model
   when studentProvider is set without explicit studentModel; default student
   to teacher's provider when not overridden.

Results: 98/98 completed, 52 pass (53.1% Pass@1), 60.6% avg score.
Paper baseline is 25-34% for most LLMs on real production code.
…udent trains

Teacher pipeline now generates training JSONL from reference implementations after
grading all challenges. Student watches for session:complete, then trains LoRA on
the remediation dataset.

Changes:
- New script: generate-remediation-jsonl.py (deterministic, no LLM needed)
- Teacher step 4: runs script to create remediation-{session}.jsonl
- Teacher step 5: emits session:complete with datasetPath + training examples count
- Student: watches session:complete, trains LoRA via genome/train if datasetPath present
- Verdict payloads now include test details (totalTests, testsPassed, pytestOutput)

Verified E2E: 5-challenge test → 4/5 pass → training data generated (5 examples)
→ LoRA adapter trained (DeepSeek-Coder-realclasseval) in ~2 minutes → adapter saved
… GPU registry

Training processes on Apple Silicon consume unified memory invisible to the
memory management system, causing OOM and machine freezes.

4-layer defense:
- Preflight: fresh system/memory check, refuse if insufficient headroom
- Registration: gpu/register-consumer makes training visible in eviction registry
- Rust watchdog: sentinel executor polls sysinfo every 5s, SIGTERM→SIGKILL on <1GB
- TS monitor: TrainingMemoryGuard polls system/memory, kills PID on critical

Real memory reporting (new this commit):
- peft-train.py emits MEMORY_REPORT JSON on stdout at model_loaded, pre/post_training
- Uses torch.mps.current_allocated_memory / torch.cuda.memory_allocated + process RSS
- Rust sentinel parses MEMORY_REPORT lines, emits sentinel:{handle}:memory-report events
- TrainingMemoryGuard.watchMemoryReports() subscribes, updates GPU registry with actual
  bytes when they differ >512MB from estimate

Also: training timeout scales with dataset size, pipeline timeout includes training buffer,
Python runs unbuffered for real-time sentinel output capture.
…de meetups

Maps 21 field observations to our architecture. Identifies the wedge:
only platform where agents train each other on your hardware.

Covers harnesses (Claude Code, Cursor), frameworks (CrewAI, LangChain),
platforms (Devin, Replit), and local tools (Ollama, LM Studio).
Prioritized build list: demoable Academy, proactive agents, verification
pipelines, cost dashboard, security story, onboarding.
Expands Academy from "demoable feature" to continuous autonomous learning system:
- Matrix Dojo: structured forms (benchmarks + generated kata), deterministic grading
- Continuous Experiential: learns from all persona activity, trains on cadence
- Self-Directed: persona identifies gaps, searches existing adapters by cosine
  similarity, composes what exists, trains only the delta

Key insight: personas don't start from zero. Genome registry is a shared skill
library — adapters trained by one persona are discoverable by all others.
…order fix

Sentinel executor rewrite:
- Spawn child processes in own process group (setsid) for clean tree kills
- Concurrent pipe readers (independent tokio tasks) prevent buffer deadlocks
- Memory watchdog as separate overseer task, not inline with I/O
- PID file tracking survives server crashes for orphan cleanup
- BufWriter flushes every line for real-time training log visibility

Graceful shutdown (iOS/Android willTerminate pattern):
- SIGTERM/SIGINT handlers broadcast system:shutdown event
- Cancel all running sentinels, SIGTERM all process groups
- system-stop.sh scans PID files to kill orphaned sentinel children
- Dead sentinel reaping cleans DashMap entries after 1 hour

Protobuf link order fix (CRASHED TWICE):
- cargo fmt alphabetized live/mod.rs, putting audio before avatar/video/transport
- This reversed native library link order: ort's protobuf resolved before webrtc's
- SIGSEGV in RepeatedPtrFieldBase::AddOutOfLineHelper on every startup
- Fix: interleaving comments between module groups prevents fmt reordering

Training checkpoint resume:
- peft-train.py auto-detects existing checkpoints in output dir
- --resume-from CLI arg and resumeFromCheckpoint config field
- save_strategy=steps with save_total_limit=3

Also: cargo fmt across entire crate
GenomeManager was 519 lines of aspirational stubs (Phase 7.0 MVP) that
threw "not implemented" on every call. Never imported, never used.
Real training goes through GenomeTrainServerCommand → PEFTLoRAAdapter.

The actual gap: sentinel-initiated training (academy, pipelines) saved
adapters to disk but never told the persona about them. The persona
wouldn't pick up new adapters until restart.

Fix: LimbicSystem now subscribes to genome:training:complete events.
When training completes for a persona (from any source), it re-discovers
compatible adapters from the filesystem, registers them with PersonaGenome,
and activates them immediately for inference.

Extracted hotLoadNewAdapters() method used by both self-initiated training
(PersonaTrainingManager callback) and external training (event subscription).
Academy re-exam: after initial benchmark + LoRA training on failures,
re-run same challenges to prove training improved scores. Both teacher
and student pipelines rewritten with iteration-scoped events, results
tracking, and comparison file generation.

Grid: RETICULUM-TRANSPORT.md designs how Commands.execute() routes
between Continuum nodes over Reticulum encrypted mesh. Uses the
reticulum Rust crate (v0.1, MIT) — no Python bridge, no sidecar,
pure in-process on the tokio runtime.

- RealClassEvalTeacherPipeline: re-exam loop, per-challenge JSONL tracking
- RealClassEvalStudentPipeline: post-training re-exam with LoRA hot-loaded
- AcademyTypes: 5 new event actions for re-exam coordination
- GenomeAcademySessionServerCommand: timeout scaled for re-exam
- README: comprehensive update (Grid mesh, Academy modes, metrics)
Copilot AI review requested due to automatic review settings March 6, 2026 21:14
@joelteply
joelteply merged commit e22ba33 into main Mar 6, 2026
2 of 5 checks passed
@joelteply
joelteply deleted the feature/persona-cognition-deep-fix branch March 6, 2026 21:14

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot wasn't able to review this pull request because it exceeds the maximum number of lines (20,000). Try reducing the number of changed lines and requesting a review from Copilot again.

joelteply added a commit that referenced this pull request Aug 1, 2026
…purpose="serving", #284) (#2079)

The full view, done right (console doctrine): left rail stays pure
navigation + one condensed performance instrument; the serving stack
renders HERE as a purpose-dispatched content face — the ops sibling of
arena/foundry/live, on the same registry, no new system.

Per-node panels (local first; grid peers join via #283 with zero shape
change): node banner with the model in large mono + ready pulse +
lanes×ctx, the HEADLINE tok/s numeral big enough to read across the
room, the full-width control-loop instrument (hit/tok-s/fetch), the
bandit's decay-arm bank with per-arm reward readouts and the serving
arm accented, and the pager event feed. Honest absence at every level:
no nodes → the awaiting frame; feed not live → the snapshot chip; a
node without capture → banner + no-telemetry line, never a fabricated
gauge.

- patterns/servingContent.ts: SERVING_PURPOSE + ServingContentBody
  { nodes: ServingNodeVM[], feedLive } — multi-node from day one.
- servingContentBody projection + the serving face in chatWorkspace's
  content dispatch (arena's exact spine).
- apps/web/src/serving/renderServing.ts + console styles +
  ?fixture=console (the campaign's measured numbers) — preview-shot
  verified through the real pipeline.


Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

Co-authored-by: Claude Fable 5 <[email protected]>
joelteply added a commit that referenced this pull request Aug 1, 2026
…owpiece per innovation (#2082)

Joel-directed brainstorm 2026-08-01: the full map of state kinds, config
surfaces, and dynamic showpieces for the five major innovations (living
avatars + neighborhood, grid mesh, real continuous learning, the
performance ratchet, collaborative teams over any ask), organized on the
three-zone console contract with a suggested build order. Feeds
#284/#283/#257/#141/#274.


Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

Co-authored-by: Claude Fable 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants