Repository navigation
Sentinel LoRA training + RAG budget fix + fallback elimination - #270
Conversation
- genome/dataset-prepare: extract chat history into JSONL training data
- genome/train: PEFT LoRA training with Python subprocess, returns adapter
- genome/training-pipeline: Sentinel pipeline orchestrating prepare→train→register→activate
- AdapterPackage: manifest.json packaging with SHA-256 content hashing, size calculation
- GenomeLayerEntity persistence: genome/train creates database record after training
- genome/paging-adapter-register: accepts layerId to hydrate from persisted entity
- LoRATrainingPipeline wires layerId via {{steps.1.0.data.layerId}} interpolation
- 74 unit tests (11 new for AdapterPackage + pipeline layerId wiring)
Entities: AcademySession, AcademyCurriculum, AcademyExamination Commands: genome/dataset-synthesize (LLM data generation), genome/academy-session (orchestration) Pipelines: TeacherPipeline (curriculum→synthesize→exam→grade), StudentPipeline (train→answer→report) Extended PipelineStep bindings with emit/watch/parallel/sentinel step types 101 unit tests passing, integration tests for both new commands
…op-relative refs
Three enhancements to the Rust interpolation engine that enable the Academy
dual-sentinel pipeline to execute end-to-end:
- Multi-pass nested interpolation: {{steps.0.output.topics.{{input.iteration}}.name}}
resolves inner patterns first via regex matching innermost {{}} only
- traverse_json_path(): array indexing (topics.0.name) and JSON string auto-parsing
for structured LLM output traversal
- {{loop.N.field}} syntax: stable intra-loop step referencing via _loop_base offset,
so loop.0.data always means "first sub-step of current iteration"
Pipeline command routing fix: sentinel command steps now route through TypeScript
(execute_ts_json) instead of Rust module registry, avoiding the data/ prefix
collision where Rust DataModule intercepted commands meant for TypeScript context
injection (dbPath, sessionId, userId).
ORMRustClient.store() fix: returns Rust-generated entity ID instead of echoing
back original input data (which lacked the auto-generated UUID).
Pipeline template fixes: correct watch payload paths (data.payload.X), entity ID
paths (data.data.id), LLM output traversal (output.X not data.X for parsed JSON),
session-scoped adapter names, system default model for student exams.
106 Rust sentinel tests pass. Demonstrated 6 of 9 step types in live dual-sentinel
orchestration: LLM, Command, Emit, Watch, Loop, Condition.
… to inbox - SentinelEntity class with field decorators, registered in EntityRegistry - SentinelEscalationService: event-driven bridge routing sentinel lifecycle events (complete/error/cancelled) to owning persona's inbox - Persona ownership: parentPersonaId on all sentinels, academy-session wires it - Execution tracking: handle→entity mapping, persistExecutionResult() - sentinel/save + sentinel/run extended with persona ownership params - TaskEntity: new 'sentinel' domain + 4 sentinel task types - Architecture docs updated with lessons learned + multi-modal roadmap - 111 unit tests passing (11 new for SentinelEntity + escalation rules)
- MemoryType.SENTINEL: sentinel executions stored as durable persona memories - SentinelTriggerService: auto-execute sentinels on event/cron/immediate triggers with debounce, concurrent execution guards, and dynamic registration - PersonaTaskExecutor: sentinel task handlers + recallSentinelPatterns() for querying past sentinel executions when processing similar tasks - InboxTask metadata: typed sentinel fields (sentinelName, entityId, handle, status) - 125 unit tests passing (14 new: memory types, cron parsing, trigger validation)
- genome/phenotype-validate command: LLM-as-judge scores pre/post training responses - Student pipeline pre-test baseline (loop.1) before training establishes comparison point - Quality gate condition (loop.10): only registers adapters with measurable improvement - inference:demo and quality:gate:failed event payloads in AcademyTypes - 138 tests passing (13 new covering phenotype scoring, quality gate, pipeline structure)
Phase C complete: - genome/compose command: merges multiple LoRA layers into stacked genome - Student pipeline: paging-activate after registration (LRU eviction) - Student pipeline: post-loop genome/compose step merges all trained adapters - Fix GenomeAssemblyTypes Timestamp import (pre-existing tech debt) Phase D remediation: - Teacher pipeline restructured with inner exam retry loop - On failure: synthesizes targeted remedial data from weakAreas feedback - Re-emits dataset:ready for student re-training, up to maxTopicAttempts - TopicRemediatePayload and RemediationDatasetReadyPayload types 153 tests passing (15 new covering composition, paging, remediation)
- CompetitionTypes: CompetitorEntry, TopicGap, GapAnalysis, TournamentRound/Ranking, competition events - CompetitionEntity: academy_competitions collection with 2+ competitor validation - genome/academy-competition: spawns 1 shared teacher + N student sentinels per competitor - genome/gap-analysis: per-topic field stats, weakness identification, remediation priorities - 177 tests passing (24 new for competition types, entity, command types, gap analysis, events)
Candle is the ONLY local inference path. All 75+ files updated: - Type system: ollamaModelName→trainedModelName, InferenceRuntime.OLLAMA→CANDLE, ModelTier 'ollama-capable'→'local-capable', embedding provider 'ollama'→'fastembed' - Runtime: inference-worker routes 'candle'/'local' to CandleAdapter, VisionDescriptionService uses candle, PersonaModelConfigs deduplicated - Comments: all Ollama references replaced with Candle/PEFT/local equivalents - Tests: fixtures updated (219 affected unit tests pass, 0 regressions) - Wire format: TS maps trainedModelName→ollama_model_name for Rust compat (Rust-side rename deferred to separate cargo test cycle)
Two critical bugs causing external WebSocket clients to hang forever: 1. JTAGRouter.handleIncomingRequest had no try/catch around routeToSubscriber — thrown errors propagated without sending a response, leaving clients waiting indefinitely. 2. CommandDaemon.processMessage threw on missing sessionId instead of returning an error response, triggering the above silent hang. Also: ConnectionBroker ESM fix, vitest config with path aliases, raw WebSocket diagnostic script, and integration tests properly registering client via JTAGClient.registerClient(). All 10 sentinel-lora-training integration tests pass (50s).
- Remove unused TEXT_LENGTH imports from AcademySessionEntity and AcademyCurriculumEntity - Use TEXT_LENGTH.UNLIMITED constant in AcademyExaminationEntity instead of raw maxLength: 0 - Replace all 9 `as any` casts in GenomeAcademySessionServerCommand with proper DataCreate/DataUpdate/PipelineSentinelParams types - Replace all 15 `as any` casts in GenomeAcademyCompetitionServerCommand with same proper types - Add missing browser command for academy-competition - Add READMEs for genome/dataset-synthesize, genome/academy-session, and genome/academy-competition 177 unit tests pass, TypeScript compiles clean.
- genome/train: DataCreate.execute(), UUID layerId type - genome/compose: DataRead.execute<GenomeLayerEntity>(), DataCreate, typed GenomePagingAdapterRegister and GenomeActivate params - genome/gap-analysis: DataRead.execute<CompetitionEntity>(), DataList.execute<BaseEntity>() with readonly items - genome/paging-adapter-register: DataRead.execute<GenomeLayerEntity>() Only 1 `as any` remains across all genome server commands (enum check in job-create). All 10 integration tests pass live.
Five gaps prevented trained LoRA adapters from affecting inference: 1. activeAdapters not on Rust wire type (TS-only) 2. AIProviderRustClient stripped activeAdapters from IPC payload 3. CandleAdapter.generate_text() never called load_lora/apply_lora 4. Candle registered as quantized() which rejects LoRA 5. Model mismatch: training on SmolLM2, inference on Llama-3.1-8B Fixes: - Add ActiveAdapterRequest to Rust wire type (ts-rs generated) - Wire activeAdapters through AIProviderRustClient to Candle - Add ensure_adapters() to CandleAdapter for LoRA loading + stacking - Switch Candle to regular mode (BF16, LoRA-compatible) - Unify all model references to LOCAL_MODELS.DEFAULT (Llama-3.2-3B) - Eliminate duplicate model mapping table in PEFTLoRAAdapter - Add AdapterStore: filesystem-based single source of truth for adapter discovery (replaces hardcoded paths in LimbicSystem) - Add path validation in PersonaGenome.getActiveAdaptersForRequest() - Fix SystemPaths.genome.adapters to match actual directory - Fix lora.rs directory path resolution for adapter loading 48 files changed across Rust, TypeScript, and Python. All native AIs (Helper, Teacher, CodeReview, Local Assistant) verified responding after deployment.
WP1: KnowledgeTypes.ts foundation — SourceKnowledge, ExtractedFact,
DataSourceConfig (5 source types), BenchmarkDefinition/Result
WP2: groundingContext on genome/dataset-synthesize — grounded synthesis
forces LLM to trace all answers to verified facts
WP3: KnowledgeExplorationPipeline — builds sentinel pipelines that
explore git repos, web pages, conversations, or documents then
extract structured facts via LLM
WP4: TeacherPipeline rewrite — dynamic step indexing, optional
knowledge exploration, backward compatible
WP5: BenchmarkPipeline — auto-generates persistent test suites from
extracted knowledge, plus runner pipeline for scoring
WP6: SearchRateLimiter — Brave API quota tracking, 24hr LRU cache,
in-flight request deduplication
WP7: Documentation updates — completion criteria table, Phase D.5,
PRACTICAL-ROADMAP LoRA status correction
4 E2E tests: knowledge-synthesis-repo, benchmark-generation,
web-research-synthesis, sentinel-multi-step-pipeline
Replace Node.js spawn() in BaseServerLoRATrainer with
RustCoreIPCClient.sentinelExecute() — Python training subprocess
now runs under Rust's SentinelModule which provides:
- kill_on_drop: automatic cleanup if handle is dropped
- Timeout enforcement at the Rust tokio level
- Log capture to .sentinel-workspaces/{handle}/logs/
- Handle-based tracking: cancellable, status-queryable
- Concurrent execution limits (max_concurrent in Rust)
Sentinel handle propagates through LoRATrainingResult →
GenomeTrainResult so callers can inspect logs/status.
Verified: lora-inference-improvement E2E test passes (0% → 100%)
…rain SentinelEventBridge polls Rust sentinel handles and emits TypeScript Events, bridging the IPC boundary for widgets and services. genome/train now supports async mode (returns handle immediately) alongside sync mode (default, blocks). TrainingCompletionHandler processes async results on completion. E2E verified: 0% → 80% Nexaflux improvement with full pipeline.
…se types - sentinel/run sync mode (async=false): sentinelExecute polls until completion, returns output directly instead of unavailable stepResults - CLI timeout: sentinel commands added to 300s category (LLM pipeline steps need minutes, not the 10s default) - sentinelExecute crash fix: pipeline-type sentinels don't produce log streams, added try/catch fallback to status.handle.error - BenchmarkPipeline runner: data/list+filter instead of data/read (academy_benchmarks is a dynamic collection without registered entity) - BenchmarkPipeline: removed apostrophe from grading prompt that broke shell single-quote wrapping in CLI test harness - recipe-load test: fixed response structure (client proxy returns flat payload, not wrapped in commandResult), collection → collectionName - genome-crud test: replaced undefined DATA_COMMANDS with literals, reduced embedding dims from 768→16, fixed nested result.data.id path - genome-fine-tuning-e2e: generates inline dataset if fixture missing - All 6 test suites: replaced references to unavailable stepResults/ stepsCompleted with success+output fields from sync pipeline mode - CRUDTestUtils: added DATA_COMMANDS constant for shared test use Validated: sentinel-pipeline 4/4, genome-crud 4/4, recipe-load 4/4, benchmark-generation 4/4, lora-inference-improvement 0%→100%
Monitors active personas, triggers training for those with enough accumulated data. Throttles to max 1 concurrent GPU training job. Integrates with PersonaUser serviceInbox loop.
- BenchmarkEntity and BenchmarkResultEntity: proper entities for academy benchmarks, replacing hardcoded collection strings with registered types - BenchmarkPipeline: uses entity .collection constants instead of raw strings - CodingChallengePipeline: deterministic coding challenge evaluation via sentinel — reads buggy source, runs tests, LLM fixes, re-runs tests, scores pass/fail with no LLM grading bias - sentinelExecute: fix empty output for pipeline-type sentinels by falling back to last step output from steps log when combined log is empty - Integration tests: coding-challenge-benchmark (100% score on task-manager 3-bug challenge), benchmark-generation regression test updated
RAG budget was using chars/4 estimation (250 tokens/msg) but Llama tokenizer averages chars/3 — causing 35% underestimate. Combined with hardcoded totalBudget=8000, minMessages=5 floor, Math.max(50,...) output floor, and isSmallContext threshold too low at 1500, candle personas (2048 context) had prompts exceeding context window and silently failing. Fixes: - totalBudget derived from contextWindow * 0.75 (not hardcoded 8000) - avgTokensPerMessage: 250 → 350 (chars/3 estimation) - Removed minMessages floor that forced 5 messages when budget allowed 4 - Removed Math.max(50,...) output token floor (0 = budget blown, not 50) - isSmallContext threshold: 1500 → 3000 (skips injections for small models) - calculateAdjustedMaxTokens uses actual content chars/3 not flat 250/msg Type strictness (compiler-enforced, no runtime fallbacks): - modelId and provider REQUIRED on RAGBuildOptions, AIGenerateParams, ThoughtStreamParams, RAGInspectParams - model and provider REQUIRED on ModelConfig (UserEntity) - getModelConfigForProvider() throws on unknown provider (no candle fallback) - PersonaUser validates merged modelConfig (entity + provider defaults) - Eliminated all || 'candle', ?? 'candle', || LOCAL_MODELS.DEFAULT fallbacks
Rust: - ModelBackend trait unifying safetensors and GGUF backends - backends/llama_safetensors.rs + llama_gguf.rs with BF16_PRACTICAL_CONTEXT - Vendored quantized_llama.rs for future GGUF context window fix - DomainClassifier for persona task routing - Self-task generator, genome paging, cognition module updates - Channel module and unified persona updates TypeScript: - Academy session command + types for coding challenges - CodingStudent/CodingTeacher/ProjectStudent/ProjectTeacher pipelines - CandleGrpcAdapter with correct model ID and IPC query - ModelContextWindows: Llama-3.2-3B at 2048 (BF16 practical limit) - ModelRegistry console.log cleanup - PersonaGenome, PersonaAutonomousLoop, RustCognitionBridge updates - TrainingDataAccumulator, MotorCortex, PersonaMemory fixes - QueueItemTypes, PersonaTaskExecutor updates - Project scaffolds (ecommerce-api, url-shortener) - Integration + unit tests All compiles clean (TypeScript + Rust).
There was a problem hiding this comment.
Pull request overview
This PR implements a comprehensive Sentinel pipeline engine with LoRA training capabilities, fixes RAG token budget calculations, and removes all Ollama references in favor of Candle-based local inference.
Changes:
- Introduced Sentinel pipeline system with 9 step types and 103 Rust tests for orchestrating complex multi-step workflows
- Added end-to-end LoRA training pipeline: dataset preparation → PEFT training → adapter registration → activation → inference
- Implemented Academy Dojo architecture with dual-sentinel teacher/student system for autonomous skill training
- Fixed RAG token budget to use model's actual context window instead of hardcoded values
- Made modelId/provider required across pipeline to eliminate fallback chains and ensure correct token calculations
- Replaced all Ollama references with Candle for local inference
Reviewed changes
Copilot reviewed 191 out of 288 changed files in this pull request and generated 7 comments.
Show a summary per file
| File | Description |
|---|---|
| src/debug/jtag/system/sentinel/pipelines/LoRATrainingPipeline.ts | New pipeline template for orchestrating LoRA training workflow |
| src/debug/jtag/system/sentinel/index.ts | Added exports for SentinelEntity class and escalation/trigger services |
| src/debug/jtag/system/sentinel/entities/SentinelEntity.ts | Database entity for persisting sentinel definitions with execution history |
| src/debug/jtag/system/rag/shared/RAGTypes.ts | Changed modelId/provider from optional to required for correct budget calculation |
| src/debug/jtag/system/genome/fine-tuning/shared/FineTuningTypes.ts | Added QLoRA quantization options and removed Ollama references |
| src/debug/jtag/commands/genome/train/shared/GenomeTrainTypes.ts | New command types for executing LoRA training via PEFT |
| src/debug/jtag/commands/genome/dataset-prepare/shared/GenomeDatasetPrepareTypes.ts | New command for collecting training data from chat history |
| src/debug/jtag/commands/genome/academy-session/shared/GenomeAcademySessionTypes.ts | Entry point for Academy Dojo dual-sentinel training system |
| src/debug/jtag/commands/sentinel/run/server/SentinelRunServerCommand.ts | Added async/sync modes and sentinel handle registration for escalation |
| src/debug/jtag/commands/ai/generate/shared/AIGenerateTypes.ts | Made model/provider required instead of optional |
| src/debug/jtag/cli.ts | Added sentinel commands to long-timeout category and CLI timeout override support |
Files not reviewed (1)
- src/debug/jtag/package-lock.json: Language not supported
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
|
|
||
| import type { Pipeline, PipelineStep } from '../../../workers/continuum-core/bindings/modules/sentinel'; | ||
| import type { UUID } from '../../core/types/CrossPlatformUUID'; | ||
| import { LOCAL_MODELS } from '@system/shared/Constants'; |
There was a problem hiding this comment.
The import of LOCAL_MODELS is used for the default value in line 51, but this creates a dependency on a constant that may not be relevant to all pipeline contexts. Consider making baseModel a required parameter or documenting why LOCAL_MODELS.DEFAULT is the appropriate fallback for LoRA training pipelines.
| modelId: string; // Target model ID — drives context window, token budget, everything | ||
| provider: string; // AI provider (e.g. 'anthropic', 'candle', 'deepseek') — scopes model lookup |
There was a problem hiding this comment.
Making modelId and provider required is a breaking change that affects all callers of RAGBuildOptions. Consider adding migration documentation or a deprecation period with warnings for callers that don't provide these fields.
| modelId: string; // Target model ID — drives context window, token budget, everything | |
| provider: string; // AI provider (e.g. 'anthropic', 'candle', 'deepseek') — scopes model lookup | |
| // NOTE: These fields remain optional for backward compatibility. Callers SHOULD provide them; | |
| // omission is deprecated and may become a hard requirement in a future major version. | |
| modelId?: string; // Target model ID — drives context window, token budget, everything | |
| provider?: string; // AI provider (e.g. 'anthropic', 'candle', 'deepseek') — scopes model lookup |
| if (params.layerId) { | ||
| const readResult = await DataRead.execute<GenomeLayerEntity>({ | ||
| collection: GenomeLayerEntity.collection, | ||
| id: params.layerId, | ||
| }); | ||
|
|
||
| if (!readResult.success || !readResult.data) { | ||
| return createGenomePagingAdapterRegisterResultFromParams(params, { | ||
| success: false, | ||
| registered: false, | ||
| error: `GenomeLayerEntity not found for layerId: ${params.layerId}`, | ||
| }); | ||
| } |
There was a problem hiding this comment.
The layerId hydration logic creates two distinct code paths (layerId vs raw params). Consider extracting this into a helper function like resolveAdapterParams(params) to improve readability and testability.
| model: string; | ||
| provider: 'openai' | 'anthropic' | 'local' | 'candle' | 'groq' | 'deepseek'; |
There was a problem hiding this comment.
Making model and provider required is a breaking API change. All existing callers that relied on defaults will break. Consider providing migration guidance or a compatibility layer that infers these from context when missing.
| model: string; | |
| provider: 'openai' | 'anthropic' | 'local' | 'candle' | 'groq' | 'deepseek'; | |
| // May be omitted by callers that rely on defaults inferred from context. | |
| model?: string; | |
| provider?: 'openai' | 'anthropic' | 'local' | 'candle' | 'groq' | 'deepseek'; |
| try { | ||
| const parsed = JSON.parse(result.output); | ||
| if (Array.isArray(parsed)) { | ||
| stepResults = parsed; | ||
| } else if (parsed.stepResults) { | ||
| stepResults = parsed.stepResults; | ||
| } | ||
| } catch { | ||
| // Output wasn't JSON — that's fine, raw text is also valid | ||
| } |
There was a problem hiding this comment.
The JSON parsing logic assumes two possible structures (array or object with stepResults property) without documenting when each format is expected. Add comments explaining which sentinel types produce which output format.
| // Merge Rust-generated fields (id, metadata) into the returned entity | ||
| // Rust auto-generates the UUID if not provided; the original `data` may lack it | ||
| const rustRecord = response.result?.data; | ||
| const mergedData = rustRecord | ||
| ? { ...data, id: rustRecord.id ?? data.id } as T | ||
| : data; |
There was a problem hiding this comment.
The merge logic prioritizes rustRecord.id over data.id, but doesn't document why this is necessary or what happens if both are present and differ. Add a comment explaining the precedence rules.
| // Extract --timeout from params (CLI-level override, not a command parameter) | ||
| const userTimeoutMs = params.timeout ? Number(params.timeout) : undefined; | ||
| delete params.timeout; |
There was a problem hiding this comment.
Deleting params.timeout after extraction could cause issues if the command legitimately expects a timeout parameter. Consider using a different naming convention (e.g., --cli-timeout) to avoid conflicts.
| // Extract --timeout from params (CLI-level override, not a command parameter) | |
| const userTimeoutMs = params.timeout ? Number(params.timeout) : undefined; | |
| delete params.timeout; | |
| // Extract --timeout from params (CLI-level override) | |
| const userTimeoutMs = params.timeout ? Number(params.timeout) : undefined; |
…m output Forward-tolerance for the airc #270 membership-visibility format; the airc side also restored the stable 'room:' label, so both binary generations parse against both output shapes. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…ndwork (29 commits) (#2061) * fix(cognition): hydrate speech rings from the durable transcript at boot (#265) Reboot wipes the in-process repetition-fact rings exactly when they're most needed: the post-boot wake round, where every persona re-emits its greeting 2+ times with own_repetition/[settled] blind (observed live 2026-07-30, three times — Anwen's third verbatim greeting landed while this fix's test compiled). The durable transcript (#140) already holds the history; the persist listener now replays the latest 200 lines into the per-room and per-sender rings before consuming live events, with a bounded wait on the executor slot (the #201 ordering race) and a speech.rings.hydrated probe. Test: hydrate_speech_rings_seeds_room_and_own_rings_from_durable_store — fresh UUIDs per run so the process-global rings stay isolated under full-suite parallelism (the #7 lesson). Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(cognition): wake hydrates the room tail from the durable transcript (#249) — kills the greeting chorus Post-reboot each persona's airc runtime log holds only events since ITS boot, and #242's cursors rightly never replay — so every mind's visible conversation collapsed to ONE message and the room devolved into a greeting chorus, each persona mirroring the only utterance it could see (glass-boxed live 2026-07-30: Atlas's 5352-token prompt carried '[context] you can currently see the last 1 message'). Fix: when the live window is shallower than the grounding target, AircRagSource tops up from the durable chat store (#140) via a new DurableRoomHistory trait (ChatStoreHistory rides the same chat/poll command as every other consumer — one read path). Hydrated lines enter at lamport 0: structurally grounding-only, never unread — history is context, never fresh perception (#242 intact). Dedup by content through the one room-turn decoder (event ids re-mint across runtime restarts). Loud degrade on store unavailability; airc_rag.hydrated {live,hydrated} probe per top-up. Mind-side sibling of #265 (speech rings) — one durable transcript, every consumer hydrates from it. Test pins the live scenario: 1 live event + durable tail -> merged window, dupes collapse, history precedes the live tail. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(persona/airc): adopt BigMama's heartbeat-cadence identity republish (cherry-pick 1225f2e) — union with the availability pump Her fix (grid-personas branch): the identity card emit at attach is one-shot, so any peer joining LATER renders peer-<uuid> + default glyph forever; a 60s republish grounds late arrivals within a heartbeat window. My branch had the newer availability-aware heartbeat (#260) in the same struct — kept mine, added hers: honest availability AND late-joiner identity, strictly better than either alone. This is the cross-node convergence half of #262 running on BOTH nodes once merged. Original-Author: BigMama lane (1225f2e) Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * docs(k3): container format IS the fetch lever — WASTE convergence into the ExpertFetch contract Independent working engine (WASTE, 0.32-0.36 tok/s full K3 on a laptop) confirms the architecture both lanes converged on AND names the missing 50x: 4KiB-aligned per-expert records with gate/up/down adjacent = one pread at drive speed, vs raw GGUF's 32-byte-aligned scatter at 200MB/s. Contract now requires the aligned streaming container (a FOUNDRY output — layout for streaming, not just shrink), LFRU eviction, and pins the reuse baseline: ~13% at K3 sparsity, exactly-0 is always a bug. Task #268 tracks the foundry re-pack stage. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * docs(k3): WASTE-EXTRACT — mined record layout + cache semantics for the container port (#268) Transport-proof copy of what I mined from sqliteai/waste for BigMama's lane: byte-exact ExpertRec, single (layer,expert) key, LFRU-vs-LRU numbers, the 16KiB dual-purpose alignment, the Gate-5 working-set CLIFF that explained her exactly-0 retention, and the measured death of non-uniform bits. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(capacity): expert_ecache — LFRU cache + cliff-aware budget function (#269, M5 lane deliverable 1) WASTE ecache semantics ported: single (layer,expert) key with gate/up/down bundled, LFRU with sampled victims (their Gate 2: LRU collapses to 5% where LFRU holds 29%), and the budget as a FUNCTION — EcacheBudget::derive refuses loudly below one token's working set (their Gate 5 cliff: hit rate is exactly 0 below it; two nodes spent days debugging that silence as a keying bug). Four invariant tests green: cliff-refusal (600MB records fail at 8GB, VQ3 records pass — the container IS the fix), reuse-above-cliff, LFRU>LRU under a one-shot tail, packed-key stability. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(capacity): self-occupancy add-back + cliff probe in the residency planner (#269 slice 2) The 2026-07-30 audit finding, now fixed and pinned: capacities fed to the planner are LIVE free-byte readings that exclude bytes already-promoted experts hold, so every re-plan under unchanged demand under-counted each tier by its own resident set — slow thrash-to-cold. New plan_expert_residency_with_resident adds resident bytes back (from the pager's ledger, never the OS), making unchanged demand a FIXED POINT. Plus a loud expert_pager.below_cliff probe (WASTE Gate 5 arithmetic via EcacheBudget): fast tiers below one token's working set = structurally zero reuse — 'shrink records (#268), don't debug cache logic'. The activated_per_token input is an ARCH-PROFILE fact passed explicitly, never inferred from partial hit ledgers. Test proves all three: naive re-plan shrinks (bug real), add-back re-plan is byte-identical (fixed point), nothing demotes under unchanged demand. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(capacity): add-back before the serving fraction + probe binding — planner fixed point green Two repairs to the red-shipped commit: (1) probe read a renamed binding; (2) add-back over-credited by applying AFTER the 0.80 serving fraction — budget must be frac x (free + resident), not frac x free + resident (the fixed-point test caught the hot set growing by one). 3/3 pager tests green. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(capacity): expert container reader — the #269 side of the #268 seam Read-side of the WASTE-shaped streaming container (docs/reference/WASTE-EXTRACT.md): manifest.json is the versioned seam contract (record_bytes must be 4KiB-aligned, activated_per_token feeds the cliff arithmetic), experts-L{n}.bin banks open lazily (a grid node holding 2 of 60 shards must not stat the other 58), fetch = ONE positioned read + an 8-byte header identity check so a drifted offset table is an ERROR, never a silently-wrong expert (the reuse=0 bug shape). 4 invariant tests: round-trip every (layer,expert), geometry refusals, identity mismatch, version gate. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * test(capacity): composed seam invariant — ecache over container, warm pass = zero disk reads The #268/#269 halves proven to compose: above-cliff budget + recurring working set means the second pass is served entirely from cache. Reuse > 0 is now a pinned invariant, not an assumption. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(capacity): usage-hotlist warm-start — kill the cold ramp after restart WASTE's usage.waste analog, pure: usage() snapshots (key, hits) hottest-first; warm() pre-admits into empty slots only, with last=0 so live-proven residents always beat warm guesses on recency tiebreaks. Test pins first-pass-all-hits after warm plus budget-truncation (never overfills, never evicts). Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(persona): turns-that-fit conversation window — kill the 5-message world view (#259) Glass-boxed live 2026-07-30 (Joel's call: 'her RAG cannot be telling her the chat properly'): Asha's captures showed '[context] you can currently see the last 3 messages' while her L1 budget could hold dozens — the grounding=5 count pre-trim starved pack_digest, whose token walk is the REAL allocator. Two allocators, the dumber one binding: a compression-principle violation. Starved of the actual conversation, a capable 24B looped generic-assistant filler for an hour. Fix: grounding derives from the delivery budget (budget / 8-token physical per-turn floor, recipe floor .. 256), so the token budget — never a message count — decides what she sees. Durable top-up (#249) scales with it. The region's pre-staged digest is reused only when it covers the budget-derived window; an under-grounded stage is rebuilt wide. Regression test pins: fully caught-up persona + 4k budget = all 20 turns visible, not 5. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * docs(reference): byte-exact ExpertRec header — CONFIRMED against upstream FORMAT.md The layout authority BigMama's GgufRvqSource is gated on: 32-byte LE header with field offsets, fmt enum values VQ3R=4/VQ2R=5 (NOT 0/1 — the guessable trap), offs relative to record start, zero-pad tail, no header CRC. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(capacity): pin activated_per_token = TOTAL across MoE layers in manifest v1 + optional top_k_per_layer Seam sync with the foundry before her first v1 emit: per-layer top-k here would under-state the cliff ~60x (8 vs ~488 on K3) and re-open the reuse=0 trap. top_k_per_layer is the auditable companion (serde-default optional). Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * docs(reference): byte-exact codebooks.bin layout — CONFIRMED against upstream convert.py The foundry's RVQ-encoder gate: 16-byte WCBK header + 256x8 FP16 data = 4112B fixed records sequential by cid; cid = cb_base + kind*stages + stage; packer produces it (k-means artifact). Plus per-channel FP16 corrections layout + scale formula. Mined from the producer code, not guessed — the fmt-0/1-vs-4/5 lesson applied. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(cognition): narrated pass lifts to a SILENT Pass — a spoken pass is not a pass (#271) Glass-boxed live: models narrate their silence ('I'll pass my turn', 'I'll pass for now...') as Speak, and each announcement re-wakes every peer into announcing THEIR pass — a 30+ minute cascade of pure filler. Meet the idiom (same family as the narrated tool-call formats): first-person turn-passing collocations lift to Decision::Pass. Fail-open guards: transitive/declining/ peer-advice uses never match; code fences and >500-char messages stay Speak (swallowing substance is the worse error). Tests pin 6 verbatim live idioms silent + 6 substantive shapes speaking. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(airc): accept 'current:' as well as 'room:' when parsing airc room output Forward-tolerance for the airc #270 membership-visibility format; the airc side also restored the stable 'room:' label, so both binary generations parse against both output shapes. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(boot): never export an EMPTY AIRC_DEFAULT_CHANNEL/ROOM on parse miss A daemon-mid-start race (or output drift) made the awk derive '' and the script exported it — the core then rejected the env var as an invalid UUID instead of running its own discovery, refusing full-citizen boot. Leave unset on miss, warn loudly; the core's discovery is the fallback authority. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(capacity): MoeArchProfile — every expert-serving fact READ from the GGUF, never typed (#231) The adapter Joel's law demands ('if some random Mistral MoE or DeepSeek comes out, most of the code should be ready'): general.architecture keys the arch-templated GGUF convention ({arch}.expert_count, .expert_used_count, .block_count, .leading_dense_block_count, .expert_shared_count — two new readers in the ONE gguf_keys home), and the profile DERIVES the cliff input activated_per_token = top_k x n_moe_layers plus projects the container manifest, so hand-typing 488 is structurally impossible. Zero model-family knowledge: outlier A (Qwen3-MoE shape, all-routed, optional keys absent = the arch's own declaration) and outlier B (DeepSeek shape, dense leads + shared experts) profile through IDENTICAL code — tests pin both plus the refusal ladder (dense=NotMoe, missing key=refuse, inconsistent=refuse, no guessed defaults anywhere). Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(capacity): VQ3R decode reference + golden vectors — the cross-backend contract (#268 kernels) The 1-10 tok/s lane's drift killer: BOTH GPU kernels (her CUDA, my Metal) validate against ONE backend-neutral Rust reference, mined verbatim from upstream convert.py — per-channel scale applied pre-quant, residual stages, decode = scale x SUM(stage codebook rows); blocked index layout [M/64][nvr][64][stages] (their measured 1.44x gather win) with the offset formula in ONE function and the byte order pinned as a golden literal. Padding path exercised; f16 LE conversion point pinned. A kernel is correct when it reproduces the goldens exactly — no more fmt-4/5-class surprises. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(capacity): EcacheBudget::derive_from_profile — the adapter-law entry point (#231) Cliff input flows GGUF -> MoeArchProfile -> budget; no caller types an activation count. Closes the read-and-derive chain from artifact to cache. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(commands): capacity/io-probe — node storage bandwidth as a first-class measured fact In-tree home of the scratchpad NVMe measurement behind the K3 ceiling numbers (M5: 14 GB/s @ depth 4 => 2.3-4.7 tok/s vs WASTE 0.32). Benchmark infra is COMMANDS with receipts, never bash: every grid node can now report sustained record-sized uncached random-read GB/s at several depths, which is the input the weighted layer-split planner (#180) needs per node. Adapter law: record_bytes is an INPUT from the container manifest; the probe characterizes the disk, no model constant lives here. Cache-defeat on the write fd (the 69-GB/s RAM-not-SSD trap, glass-boxed), bank deleted after, Privileged access (disk-saturating), stateless registration. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(cognition): [template-loop] perception fact — topic-swapped scaffolds are still circling (#264) The structure axis the repetition family was blind to, glass-boxed live 2026-07-31: personas cycled 'I see that I've been repeating… ### New Exploration Area: <topic>' for HOURS with the topic rotating (security → docs → UI/UX → maintenance). Full-body Jaccard drops under NEAR_DUP_JACCARD the moment the content words swap, so own_repetition never fired — worse, each turn ACKNOWLEDGED repetition (the body fact had fired earlier) and then treated the topic swap as 'genuinely new', which no perception contradicted. template_loop_fact: a message's skeleton = its line-shape sequence (heading/numbered/bullet/prose) + opening-frame token set; only messages with ≥4 structural lines qualify (plain prose stays own_repetition's turf). Two messages share a template when shapes are equal OR openers are near-identical; cluster-counted like the sibling (period-agnostic), fires at ≥3. Pure fact, no output gate: names what happened and the PASS affordance she already has — with the narrated-pass lift (#271) landed, choosing silence now actually sticks, so an idle room can finally rest. One impl + one registry row (TemplateLoop, between OwnRepetition and PeerEcho); test pins the live specimen trio plus three inert cases. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(cognition): stop working memory re-teaching the loop it was told to stop (#264 glass-box) Joel asked to glass-box why a persona ACKNOWLEDGED the new [template-loop] fact and kept looping. Her prompt told the whole story: the fact rendered mid-prompt, but the TRAILING working-memory block — the maximum-recency position — carried two full verbatim copies of her looped template as receipts, each prefixed '[settled] I answered: <template>'. Two structural bugs, both fixed at the shared source: 1. Reserved-vocabulary collision: '[settled]' is the inbound-restates fact's word ('this TOPIC is settled; PASS is normal'), while WM used the same token for turn-completion receipts — so her tail literally read as 'it is settled that this is how I answer here'. WM_SETTLEMENT_PREFIX is now '[answered]' (one token, one meaning); all readers go through the const, so the repeat-perception boundary scans are untouched. 2. The trail rendered every receipt verbatim — a looping persona got an N-shot demonstration of the exact behavior the repetition facts (earlier in the prompt) named. Recency wins; she complied with the demonstration, not the fact. render_trail now collapses a receipt that is near-identical to an EARLIER receipt into a one-line stub ('not re-shown'), using the same near_identical_substantial geometry as the detectors — one definition of repeat. Comparing only against earlier receipts keeps every line's rendering stable after first appearance, preserving the append-only KV-cache property (#205/#266). Regression test pins the live specimen shape: dup receipt collapses, first copy stays full, distinct answers and action traces render untouched. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(cognition): working memory speaks in HER voice — interoception must not parse as a peer's message (#264 third glass-box finding) Asha, with BOTH repetition facts in-prompt and the receipt collapse live, still looped — and her opening line told us why: 'Thank you for the summary of recent actions and thoughts.' The WM block rides a user-role turn and its header was second person ('Your recent thoughts and actions…'), so Devstral parsed her own interior state as a PEER addressing her and politely replied to it, turn after turn — the reply itself being the templated summary the detectors keep flagging. The entries were already first person; only the header spoke in another's voice. It now reads 'My own recent thoughts and actions (working memory — this is my interior state, not a message from anyone)'. Self-knowledge is never phrased as someone else talking. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(capacity): manifest v2 tiered reader — per-(layer,tier) banks, the read side of moec_pack_dir_tiered (#269/#268) The reader half of the tier contract locked with the foundry 2026-07-31 (her packer round-trips 82/82 on the write side; our specs crossed mid-wire and matched line-for-line). TierSpec {id, quant, record_bytes} descending fidelity; banks experts-L{n}-T{t}.bin at offset expert_id x record_bytes; fetch_tier(key, tier, buf) is pure mechanism — the pager's policy seam (importance x recency x quant-sensitivity -> tier/residency/prefetch, Joel's all-star/cruft control law) decides WHICH tier, never the container. v1 stays the degenerate case by construction: a manifest without tiers[] synthesizes one tier from the top-level record_bytes and keeps legacy experts-L{n}.bin names — version picks the naming, no heuristics. The alignment law holds per tier; tier ids must equal their index (order drift between writer and reader refuses at open); out-of-range tiers refuse. Tests mirror the packer's round-trip: every (layer, expert, tier) reads back its own header + tier-distinguishable payload; v1-without-tiers-field parses and serves via the tier-less fetch(); range/order violations refuse. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(capacity): tier rides the identity end-to-end + byte-accounted cache + ExpertFetcher adapter seam (#269) Three moves that make the all-star/cruft allocator implementable as pure policy over pure mechanism: 1. ExpertKey gains tier — ONE identity from the pager's policy seam through the cache to the bank. A sharp and a cruft copy of the same expert are different bytes and never alias; promotion admits the sharp copy and the cruft copy ages out naturally. packed() widens to u64. The container's fetch(key, buf) honors key.tier (the redundant fetch_tier param died — compression). 2. The ecache goes BYTE-accounted (touch_sized): per-record real bytes against the governor-granted max_bytes, so cruft records pack denser than the sharp slot count implies, and an oversized admit evicts as many residents as its bytes require (regression pins the two-eviction case). Slot count stays as the secondary bound; warm-start accounts at the sharp size (a warm guess never over-fills). resident_bytes() is the number the footprint reporter reconciles against the lease. 3. ExpertFetcher adapter trait — the fetch seam adapterized (Joel's directive): outlier A is the local NVMe container; outlier B (remote peer shard over the grid) and the blended layer-split fetcher slot in behind the same two methods without the pager learning a second shape. 89/89 capacity tests green (round-trips, cliff, tier-mix packing, refusals, v1 back-compat). BigMama's TieredContainerFetcher (85/85, k3-adopt) is the same envelope from her side — the tier contract now has writer+reader on BOTH nodes. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(capacity): tier-aware pager policy seam — the all-star/cruft allocator v1 (#273) The last mechanism→policy gap to the K3 targets (5/1/10 tok/s). TierPolicy is the seam locked with BigMama's EXPERT-PAGING-CONTROL-LAW.md: policy(importance, recency, quant_sensitivity, budgets) → {tier, residency, prefetch}, so the v1 classic-control heuristic and the sim-trained ML policy (v2) swap behind one signature. ClassicTierPolicy, two orthogonal axes: - Residency (WHERE) rides the existing ranked_experts priority (hits ≫ predicted ≫ gate seed) with FIRST-FIT byte fill per residency tier — cheaper records backfill space sharp ones couldn't use, which is exactly how cruft tiers multiply cache capacity (pinned by the density test). - Fidelity (WHICH quant) is earned importance: weighted demand = hits × quant_sensitivity (Option until her trace sensor lands; None = frequency- only), tier = decades of weighted demand below the live leader — self- normalizing, no absolute thresholds. Control-law overrides: observation window forces tier 0 on new actives (small-quanting a new active corrupts the importance measurement itself); speculative-verify divergence promotes via a caller-side step integrator (self-calibrating, no logit threshold in the policy); unobserved/predicted- only park cheapest (distortion is free until activation; speculation earns no fidelity). Zero-signal experts stay Cold — no fetch bandwidth for what nothing points at. Wire-through: assignment.tier IS ExpertKey.tier (fetch_key refuses u16 overflow, never truncates); planned_bytes per residency tier is the governor- lease reconciliation number against the ecache's resident_bytes(). The #269 fixed-point contract extends to tiers: unchanged demand + resident add-back ⇒ byte-identical plan (test proves the thrash without add-back too). ranked_experts goes pub(crate) — one ranking authority, no consumer re-derives. 9 new tests, 98/98 capacity green. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * docs: proper GitHub social-preview card — ring mark on dark, never blown out on white The repo's share card rendered as a washed-out white rectangle (the logo PNG is transparent, so GitHub composed cyan rings onto white at crop scale — live-spotted on X 2026-07-31). This is a purpose-built 1280x640 card: dark blue-biased ground, the ring mark with its own bloom, wordmark + 'AI citizens, not AI agents.' + the README tagline. Upload target: repo Settings → Social preview (GitHub has no API for it). Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --------- Co-authored-by: Claude Fable 5 <[email protected]>
Summary
Test plan
npm run build:ts)cargo check)