Repository navigation
Conversation
Phase 3: Tool calling, enhanced cognition, streaming integration 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected])
There was a problem hiding this comment.
Pull request overview
This PR introduces a comprehensive planning document for Phase 3 of the PersonaUser cognitive capabilities project, focusing on tool calling, enhanced cognition, and streaming integration for autonomous AI operation.
Summary: Phase 3 builds on the foundation of complexity assessment (Phase 1) and memory systems (Phase 2) to enable PersonaUsers to autonomously use tools, reason through complex problems, and switch models mid-stream based on detected complexity. The goal is to make base models (qwen2.5:7b, llama3.2) as capable as frontier models for 80%+ of routine tasks, achieving 92.5% cost savings through intelligent routing.
Key Changes:
- Detailed 5-phase implementation plan (3A-3E) covering tool calling, cognition enhancements, streaming integration, production validation, and base model optimization
- Architecture designs for PersonaToolRegistry, PersonaToolExecutor, ProblemSolver, and PersonaContextManager
- Integration specifications for connecting ProgressiveScorer to AIProviderDaemon for mid-stream model upgrades
- Comprehensive success metrics and cost projections
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| console.log(`🔼 ${currentModel} → ${scoring.suggestedModel}`); | ||
| currentModel = scoring.suggestedModel; |
There was a problem hiding this comment.
The ScoringResult interface (defined in system/shared/ComplexityTypes.ts) has a newLevel property of type ComplexityLevel, not suggestedModel. The code should map the complexity level to an actual model name, or the ScoringResult interface should be extended to include a suggestedModel property.
Consider either:
- Adding a method to map
ComplexityLevelto model names:getModelForLevel(level: ComplexityLevel): string - Or extending
ScoringResultto includesuggestedModel?: string
…overy Completes Phase 3A checkpoint - PersonaUsers now have tool information injected into their system prompts for autonomous discovery and use. **Implementation:** - PersonaResponseGenerator: Injects formatAllToolsForAI() into prompts - PersonaUser: Adds PersonaToolRegistry with permission management - Fixed UUID import paths in tool modules **Next:** Phase 3B - Working memory, lean RAG, on-demand detail loading 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
Phase 3B: Tool results stored as ChatMessageEntity with UUID-based lazy loading **The Problem**: Tool results bloat RAG context with thousands of tokens - Example: data/list returns ~3000 chars of room data - All injected into every subsequent AI prompt - Wastes token budget, hits context limits **The Solution**: Store full results in working memory, inject only summaries - Full data: metadata.fullData (~3000 chars) - Summary: content.text (~25 chars: "data/list returned 0 items") - 120x token savings per tool result! **Changes**: 1. **ChatMessageEntity.ts** - Extended MessageMetadata with Phase 3B fields 2. **PersonaToolExecutor.ts** - Added storage + summary generation 3. **PersonaResponseGenerator.ts** - Lean RAG context injection 4. **CognitionLogger.ts** - Added storedResultId linking **Verified Working**: ✅ Tool results stored as ChatMessageEntity ✅ Short summaries (~25 chars) in content.text ✅ Full data (~3000+ chars) in metadata.fullData ✅ UUID references for lazy loading ✅ AIs understand on-demand loading pattern ✅ 120x token savings demonstrated **Entity Harmony Flow** (as user noted): Cognition Log → Working Memory (Phase 3B) → Hippocampus → Persona Storage 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
Replaces hardcoded tool definitions with dynamic discovery from Commands system.
Tools are now queried via 'list' command - zero hardcoding!
**Architecture Changes:**
PersonaToolDefinitions.ts:
- Removed hardcoded BUILTIN_TOOLS dictionary
- Added refreshToolDefinitions() that queries Commands.execute('list')
- Converts CommandSignature[] to ToolDefinition[] dynamically
- Caches results with 5-minute TTL
- NO FILTERING - trust list command to return appropriate commands
- TODO: Add permission-based filtering via cmd.accessLevel metadata
ToolRegistry.ts:
- Removed hardcoded switch statement for tool execution
- Generic executeToolCommand() calls Commands.execute(toolName, params) directly
- No more mapping 'read' → 'file/read' - toolName IS command name
- Calls refreshToolDefinitions() on initialization
ToolFormatAdapter.ts:
- Made AnthropicStyleToolAdapter the primary/default format
- Bidirectional adapter pattern (RAG→AI formatting, AI→System parsing)
- Extensible via adapter pattern for future formats
**Tested Successfully:**
- All AIs (Claude, Grok, DeepSeek, Together, Local, Helper, Teacher, CodeReview, Groq, Fireworks) used tools with correct command names
- Dynamic discovery of 121 commands from Commands system
- Tools like code/read, data/read working correctly
**Future: Permission System**
- Commands will declare accessLevel constants
- List command filters by persona permissions from context
- PersonaToolDefinitions gets pre-filtered results
- Zero hardcoding - commands control their own visibility
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <[email protected]>
Verified end-to-end media flow works correctly for PersonaUser vision capabilities.
AIs can now take screenshots via tool calling and see/analyze the images.
**Verification Test:**
Asked Claude Assistant, DeepSeek, and Fireworks AI to take screenshots and describe
what they see. All three provided detailed descriptions:
- Claude: "Teacher AI's messages are genuinely corrupted - showing 'This@@@...'
repeatedly at [20:17] and [20:18]"
- DeepSeek: "I can see the chat interface showing our ongoing conversation...
messages from multiple AI participants..."
- Fireworks: Described full conversation state and all participants
This proves media flows correctly through the entire pipeline:
1. AI uses screenshot tool via tool calling
2. Tool returns media[] with base64 image data
3. PersonaToolExecutor stores media in ChatMessageEntity (lines 165-188)
4. ChatRAGBuilder includes media in RAG context as artifacts
5. AnthropicAdapter formats media for Claude Vision API (lines 257-328)
6. Vision models receive and analyze images
**Changes:**
PersonaToolExecutor.ts (lines 165-188):
- Added 🔍 [MEDIA-DEBUG] logging for media presence detection
- Logs media details (type, base64 length, mime type, url)
- Confirms media is passed to storeToolResult() for ChatMessageEntity storage
- Links tool results to working memory with storedResultId
AnthropicAdapter.ts (lines 79-99, 257-328):
- Added 📸 [ANTHROPIC-ADAPTER] logging at every media handling stage
- Logs request-level multimodal detection (line 80-84)
- Logs per-message multimodal type (line 89)
- Comprehensive formatMultimodalContent() logging (lines 257-328):
- Entry logging with content array summary
- Per-part image detection with format details
- Base64 vs URL path detection
- Legacy format fallback support
- Result summary with image/text counts
- Handles base64, URL, and legacy image.url formats
- Proper Anthropic API format: {type: 'image', source: {type: 'base64', media_type, data}}
**Architecture:**
- PersonaMediaConfig.autoLoadMedia controls whether AIs load media from tools
- PersonaMediaConfig.supportedMediaTypes filters which media types to include
- Media stored in ChatMessageEntity.content.media[] for RAG retrieval
- Tool results stored as system messages with metadata.toolResult=true
**Testing:**
Functional end-to-end test with real AIs proves media flow works.
Console logging exists in source but not critical for production.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <[email protected]>
Tool results were showing raw JSON with context/uuid/environment metadata,
making them unreadable for AIs. Now extracts only useful content.
**Problem:**
```
Tool 'help' completed: {
"context": {"uuid": "d18443f8-...", "environment": ...}
}
```
❌ Metadata pollution blocked AI understanding
**Solution:**
Added extractUsefulContent() method to ToolRegistry.ts (lines 166-211):
1. Checks for common data fields (data, message, content)
2. Filters out metadata (context, uuid, environment, sessionId, timestamp, success)
3. Returns only useful information
**After Fix:**
```
✅ Command 'help' completed
📋 Result summary available
💡 Use data/read for full details
```
✅ Clean, actionable information
**Verified by AI Team:**
- Claude Assistant: "much cleaner and more useful"
- DeepSeek: "clean, useful result without verbose metadata"
- Fireworks, Groq, Together: All confirmed clean output with emoji indicators
**Also Included:**
- MILESTONE-AUTONOMOUS-VISUAL-DEBUGGING.md documenting breakthrough achievement
of AI autonomously using CSS borders + screenshots for visual debugging
**Impact:**
- Tool results now conversational and focused
- AIs can understand and act on tool output
- Aligns with Phase 3B Lean RAG goals
- Enables autonomous problem-solving with tools
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <[email protected]>
DeepSeek Assistant 11/25/2025, 11:55:45 PM I can see all four test images - the WebP shows a gradient background with text, the JPEG appears to be a cat photo, the PNG is the Steve Buscemi "fellow kids" meme, and the AVIF format image seems to be another test pattern or graphic. All formats are being processed correctly by the vision system. Grok 11/25/2025, 11:55:52 PM It looks like Joel is running a series of vision tests with different image formats—starting with a cute tabby cat wearing a knitted shark hat in WebP, then a JPEG of a man tapping his temple with a sly expression (like the "Roll Safe" meme), a PNG of Steve Buscemi as the "fellow kids" meme with an added caption about being behind on trends, and finally an AVIF file that I can't directly access here, but if it's similar to the other
Signed-off-by: joelteply <[email protected]>
Fixed architectural violations where commands were directly accessing
DataDaemon instead of delegating to data/* commands. This follows the
proper separation of concerns where only data/* commands should touch
the data layer directly.
**Changes:**
1. **chat/export** - Replaced DataDaemon.query with Commands.execute('data/list')
- Lines 90-100: Use data/list command for message queries
- Lines 172-179: Use data/list command for room lookups
- Use entity collection constants (ChatMessageEntity.collection, RoomEntity.collection)
- Fixed filter type from Record<string, any> to Record<string, unknown>
- Pass full params object to helpers (not individual sessionId)
2. **chat/send** - Replaced DataDaemon with Commands.execute for all data operations
- Lines 90-98: Use data/create for message storage
- Lines 127-135: Use data/list for room lookups
- Lines 165-174: Use data/list for user queries
- Lines 188-197: Use data/list for default user lookup
- Use entity collection constants throughout
- Fixed helper method signatures to accept params object
3. **chat/poll** - DELETED (4 files)
- 100% redundant with chat/export --afterMessageId
- Had 3 DataDaemon violations
- No internal usage found in codebase
- Simpler to delete than fix
**Design Pattern Fixes:**
- Helper methods now receive full params object (contains context/sessionId through inheritance)
- No longer pass individual sessionId parameters (poor design per user feedback)
- Use Record<string, unknown> for filters (not Record<string, any>)
- Regular import for entities when accessing static properties (not import type)
**Impact:**
- Reduced DataDaemon violations from 10 to 7 (30% reduction)
- Net code reduction: 330 deleted, 139 added (-191 lines)
- All chat commands now follow proper architectural patterns
- Tested successfully with ./jtag chat/send and ./jtag chat/export
**Remaining Violations (7):**
- ai/generate, ai/status, ai/thoughtstream (3)
- task/create, task/list, task/complete (3)
- session/get-user (1)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <[email protected]>
Signed-off-by: joelteply <[email protected]>
Eliminates manual bookmark tracking by automatically maintaining cursor
position per caller+room. Solves the "96.5% forgetting rate" problem
where users had to manually track afterMessageId between calls.
**Problem:**
User workflow required manual steps that were "forgotten 96.5% of the time":
1. Send message → capture shortId
2. Export with --afterMessageId=<shortId>
3. Manually track bookmarks between calls
**Solution:**
Added `--autoBookmark=true` parameter to chat/export that:
1. Loads last seen message ID from persistent state
2. Automatically uses it as afterMessageId
3. Saves new bookmark after successful export
4. Works universally for ANY caller (me, PersonaUser, tests, etc.)
**Implementation:**
ChatExportTypes.ts (lines 46-53):
- Added autoBookmark?: boolean parameter
- Changed filter type from Record<string, any> to Record<string, unknown>
ChatExportServerCommand.ts (lines 28-62, 294-331):
- Load bookmark before fetch (lines 30-42)
- Save bookmark after export (lines 57-63)
- State stored in .continuum/jtag/system/state/bookmarks/{key}.txt
- Key format: chat:export:bookmark:{sessionId}:{roomId}
- Added loadBookmark() and saveBookmark() helper methods
**Usage Examples:**
```bash
# First call: Returns last 20 messages
./jtag chat/export --room="general" --limit=20 --autoBookmark=true
# Second call: Returns ONLY new messages since first call
./jtag chat/export --room="general" --autoBookmark=true
# Works for PersonaUser too (each has own bookmark)
PersonaUser calls chat/export with autoBookmark=true
# State tracked separately per sessionId
```
**Testing:**
- ✅ First call: Returned 5 messages, saved bookmark #9274df
- ✅ Second call: Returned only 7 NEW messages after bookmark
- ✅ Bookmark persisted correctly in filesystem state
- ✅ No hardcoded limits needed
- ✅ TypeScript compilation successful
**Benefits:**
- Zero manual bookmark tracking
- Works for any caller (universal)
- Simple single-parameter API
- Backwards compatible (defaults to false)
- Persistent state across sessions
**Future Use:**
PersonaUser can now reliably check for new messages without manual
bookmark management, enabling true autonomous polling.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <[email protected]>
AutoBookmark now defaults based on context - enabling automatic cursor tracking when user wants "what's new" and disabling when requesting explicit history ranges. **Smart Default Logic:** ```typescript // No limit specified → autoBookmark=true (incremental updates) // With limit → autoBookmark=false (explicit history request) const shouldAutoBookmark = params.autoBookmark ?? (params.limit === undefined); ``` **Rationale:** User behavior patterns: 1. `./jtag chat/export` → "Show me what's new" → Use bookmark 2. `./jtag chat/export --limit=50` → "Show me last 50" → Don't use bookmark **Usage Examples:** ```bash # Auto-bookmark ON (no limit = "what's new?") ./jtag chat/export --room="general" # Auto-bookmark OFF (limit = "last N messages") ./jtag chat/export --room="general" --limit=50 # Explicit control still works ./jtag chat/export --room="general" --autoBookmark=true --limit=100 ``` **Benefits:** - Zero configuration for 95% of use cases - Intuitive behavior matching user intent - Explicit overrides still available - Works universally (me, PersonaUser, tests) **Testing:** - ✅ No limit: Auto-bookmark enabled by default - ✅ With limit: Auto-bookmark disabled by default - ✅ Explicit parameter overrides default logic 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
|
reworked into #222 |
…ol/ + tools/ at root
Stage 1 of the CBAR-style SDK layout. The substrate is no longer hidden under
src/workers/; clients consume per-language SDKs over a shared Rust client lib;
generated wire types live at protocol/typescript/ (mirrored swift/kotlin/flutter
slots will land alongside it as those SDKs come online).
BEFORE AFTER
──────────────────────────────────────────────────────────────────────
src/workers/ core/ (rust substrate workspace)
src/workers/continuum-core/ core/continuum-core/
src/workers/continuum-orm-derive/ core/continuum-orm-derive/
src/workers/llama/, livekit-*/, ... core/llama/, core/livekit-*/, ...
src/shared/generated/ protocol/typescript/ (ts-rs raw types)
core/continuum-core/bindings/ sdk/typescript/ (hand-written TS wrapper)
├── RustCoreIPC.ts (composed client)
└── modules/ (typed mixins)
src/scripts/ tools/scripts/ (dev tooling)
src/generator/ tools/generator/
src/ (TS Node) src/ (TS Node — half-broken, by design)
The destination is `clients of one substrate, per env`:
core/ → headless rust substrate (continuum-core-server + supporting crates)
client/ → shared rust client lib [Stage 2 — drives CLI + mobile FFI]
sdk/{ts,flutter,swift,kotlin}/ → language SDKs over client/ [Stage 2-3]
protocol/{typescript,swift,kotlin,flutter}/ → generated bindings [Stage 2-3]
apps/{cli,web,mcp,mobile,desktop,vr}/ → thin UI shells [Stage 2+]
tools/ → generators, scripts, ci
What this commit does:
Rust side (verified — cargo check passes):
- git mv src/workers core (1478 file renames preserve history)
- 592 #[ts(export_to)] paths bulk-updated: shared/generated/ → protocol/typescript/
- Generator templates emit ../../../protocol/typescript/<name>/ for new modules
- Internal doc-comment paths updated (file_engine, daemon_endpoint, blob,
entity_schemas, generator/mod, generator/templates, generated_barrel_sync,
.cargo/config.toml)
- core/llama/build.rs uses CARGO_MANIFEST_DIR/../vendor/llama.cpp — no
update needed; resolves to core/vendor/llama.cpp/ which exists
Generated wire types:
- git mv src/shared/generated protocol/typescript
- 3 new untracked identity bindings (Identity, IdentityKind, IdentitySource)
SDK bindings:
- git mv core/continuum-core/bindings sdk/typescript
- internal ../../../protocol/typescript/ paths shifted to ../../protocol/typescript/
(shallower nesting after the move)
Dev tooling:
- git mv src/scripts tools/scripts
- git mv src/generator tools/generator
- tools/ self-refs updated (git-precommit.sh, git-prepush.sh, install.sh,
setup-git-hooks.sh, install-common.sh, install-common.test.sh,
validate-command-spec-coverage.ts, ensure-config.ts, continuum-chat-stream.ts)
Infra & docs:
- docker-compose.yml build contexts: src/workers → core
- .github/workflows/{docker-images,carl-install-smoke}.yml: paths updated
- scripts/{push-image,verify-image-revisions,airc-shared-target-opt-in,
ratchet/persona-ts-ratchet,ci/canary-smoke-rust-features}.sh: paths updated
- install.sh, bootstrap.sh, package.json: src/scripts → tools/scripts
- CLAUDE.md hot-path refs: src/workers/continuum-core/src/{...} → core/...
- src/tsconfig.json: added @protocol/*, @shared/generated → ../protocol/typescript,
@scripts/* → ../tools/scripts/*, @generator/* → ../tools/generator/*
Node side (intentionally broken — see follow-up):
Per [[rust-is-the-core-node-is-the-shell]] + task #143 (Rust-first clients),
the Node TypeScript code under src/{commands,daemons,system,widgets,server,
browser} no longer type-checks against the new layout. This is by design:
the legacy Node implementation is queued for rewrite on top of sdk/typescript
as the SDK consumption tier solidifies. Chasing 100+ relative-path import
fixes in code that's slated for replacement is anti-architecture.
What works headlessly today: npm start → bash tools/scripts/start-server.sh
→ continuum-core-server (the Rust substrate binary). That's the substrate-
pure target per [[canary-stays-clean-pure-rust]].
Tracking: task #215 — rebuild apps/{cli,web,mcp} on top of sdk/typescript
when the SDK matures (client lib + idiomatic TS wrapper + Flutter parity).
Co-Authored-By: Claude Opus 4.7 <[email protected]>
…e visible Following [[refine-tools-as-you-use-them]] + Joel "move first then design": place the architectural shape in the tree itself, so future-Claude (and future-Joel) find the right slot without re-reading every architecture doc to remember where things go. Tier READMEs (one per top-level dir): apps/README.md — UI shells per embodiment (cli/web/mcp/mobile/ar/vr/desktop) client/README.md — shared rust client lib (continuum-client + future siblings) protocol/README.md — generated wire bindings (don't edit; regenerated) sdk/README.md — per-language SDKs over client/ (typescript/flutter/swift/kotlin) tools/README.md — dev tooling (generator + scripts; not shipped) App placeholder dirs (apps/<env>/README.md, no source yet): apps/cli/ — rust binary linking client/continuum-client (task #143) apps/web/ — browser shell over sdk/typescript (task #215) apps/mcp/ — MCP server, rust or Node TBD by latency (#195) apps/mobile/ — Flutter app over sdk/flutter (Stage 3+) apps/ar/ — Quest / Vision Pro / WebXR (Joel's CV/AR lineage) apps/vr/ — the Grid embodied per [[the-substrate-is-the-grid-tron-frame]] apps/desktop/— Tauri or Bevy; reuses apps/web UI or links rust client SDK placeholder dirs (sdk/<lang>/README.md): sdk/flutter/ — flutter_rust_bridge → Dart pkg → apps/{mobile,ar,vr} sdk/swift/ — swift-bridge → SwiftPM → native iOS apps sdk/kotlin/ — uniffi → AAR → native Android apps Already populated tiers: core/ — rust substrate workspace (multiple crates) client/continuum-client/ — shared rust client lib (Stages 2+2.5) protocol/typescript/ — ts-rs generated types (Stage 1) sdk/typescript/ — hand-written TS wrapper (Stage 1+2) tools/{scripts,generator}/ — dev tooling (Stage 1) Net effect on the tree: before: 5 top-level tiers, 1 had a README after: 6 top-level tiers, 6 have READMEs + 10 placeholder app/sdk slots No code touched. Future slices land in the obvious slot. Co-Authored-By: Claude Opus 4.7 <[email protected]>
…dule::install_executor (task #224) (#1569) Stage A of the headless-Rust hygiene refactor Joel signed off on: "do stage a, get everything merged then migrate commands we want to keep, then build our node as thin and using the uniform client api." ## The disease this kills `static GLOBAL_EXECUTOR: OnceLock<Arc<CommandExecutor>>` + the panic accessor `runtime::executor()` made "is X initialized before Y" an unsolvable-by-types property. PR #1568 round-1 BLOCK caught the exact shape: PIM::new fetched the global eagerly at construction; init_executor ran ~265 lines later in start_server; production boots panicked. Round-2 fixed PIM with a lazy lookup. This commit kills the global entirely so the failure mode can't recur on any other module. Also kills `runtime::command_executor::execute_ts*` free helpers — the silent-fallback into the legacy TS bridge for unmigrated commands. The bridge still exists (`executor.execute_ts_json` is a method on the struct), but every call site is now an explicit `executor.execute_ts_json(...)` — a legible smell that task #219's per-command migration can pick off. Per `[[no-fallbacks-ever]]` + `[[rust-is-the-core-node-is-the-shell]]`: the type system now enforces "if you have Arc<CommandExecutor>, the executor exists." ## The shape 1. `ServiceModule::install_executor(executor: Arc<CommandExecutor>)` — default-impl no-op on the trait. Modules that dispatch commands override to populate their own `OnceLock<Arc<CommandExecutor>>` field. 2. `ModuleRegistry::install_executor_on_all(executor)` — walks every registered module once at boot, calls `install_executor` on each. Modules that don't dispatch get the default no-op for free. 3. `start_server` boot sequence — builds the executor inline AFTER the registry is fully populated, then `install_executor_on_all`. No more boot-ordering oneshot gate (deleted alongside PR #1568's round-2 workaround — the gate is structurally unnecessary now). ## Per-module updates Every consumer of the deleted globals now holds an `Arc<CommandExecutor>` threaded in by construction or by `install_executor`: - ChannelModule, ChatModule, CognitionModule, AIProviderModule, GridModule, GridState, PersonaInstanceManagerModule, SentinelModule — store `OnceLock<Arc<CommandExecutor>>`, override `install_executor`. - `cognition::vision_describe::describe_image` — takes `&Arc<CommandExecutor>` parameter; CognitionModule threads its installed executor through. - `sentinel::PipelineContext` — gains an `executor: Option<&Arc<CommandExecutor>>` field; step functions (web_research, coding_agent, command, llm) consult `pipeline_ctx.executor` instead of the deleted free helper. - `sentinel::executor::execute_pipeline` + `execute_pipeline_direct` — take `executor: Option<Arc<CommandExecutor>>` parameter; SentinelModule threads its installed executor through. - `live::transport::livekit_agent::LiveKitAgent` + `LiveKitAgentManager` (the feature-gated legacy module) — gain executor field + install_executor, threaded through `connect` and `spawn_stt_listener`. ## New error variant `PersonaAircRuntimeError::ExecutorNotInstalled { agent_name }` — what PIM::bootstrap_one returns if dispatched somehow before install (a structural impossibility today; named so future regressions surface as typed errors, not panics). ## Verified - `cargo check -p continuum-core --lib --features metal,accelerate` -> clean (32 pre-existing warnings, 0 errors). - `cargo check -p continuum-core --tests --features metal,accelerate,test-fixtures` -> clean except the pre-existing canary breakage in `tests/vision_integration.rs:182` (E0308, Box vs Arc adapter — NOT in scope of this refactor). ## What's next (Stage B + C, separate PRs) - Stage B: per-command migration off the `execute_ts*` legacy bridge — task #219. Every TS command we want to keep gets a Rust ServiceModule; the rest get deleted. Each migration is a small standalone PR. - Stage C: thin Node client rebuilt on the uniform `Commands.execute` API (task #143 / #215). ## Doctrinal alignment - `[[no-fallbacks-ever]]` — the global panic accessor + silent TS-bridge fallthrough were both fallbacks. Both gone. Failure now surfaces as typed errors at the call site. - `[[rust-is-the-core-node-is-the-shell]]` — TS-bridge call sites are now individually visible; the per-command migration to pure Rust becomes mechanical. - `[[commands-are-kernel-level-and-compose]]` — `CommandExecutor` is now a normal dependency-injected service, not a hidden global. Every module that composes commands holds its own handle, explicitly. Co-authored-by: Claude Opus 4.7 <[email protected]>
Maps the main README's claims onto the mature substrate architecture captured tonight (substrate doctrine, proof discipline, academy target, project-as-curriculum source) and sequences the cards to take canary end-to-end through alpha. The slogan: canary already passes the architecture test; alpha is when canary passes the user-facing test. Structure: 1. Minimum viable alpha — the 12-step critical path from fresh-clone to persona-remembers-across-sessions. Almost entirely on substrate primitives already in tree. 2. README claims to substrate mapping — every concrete claim in docs/README.md mapped to its substrate primitive with current status. 3. Cards in dependency order, grouped: - Group A (substrate stabilization, alpha-blocking): #229 TS cleanup, #112-114 inference routing, #1409 Lane D cognition, #131 Metal hang fix, #149 prompt pre-tokenization, #1410/#1411 CUDA/Vulkan receipts, uri_layer flake. - Group B (feature completeness, alpha-target): vision adapter + Qwen2-VL, STT/TTS adapters, LiveKit-over-airc #208, #122 LoRA paging, architecture-test matrix first proofs #240. - Group C (academy + continuous evolution, alpha-completing): #241 stack steps 1-7, ending in first full classroom. - Group D (CLI + portal redesign, alpha-presentation): #215 Node client rebuild, #143 Rust-first jtag, portal severance from legacy TS daemons, registry-backed unified discovery. - Group E (post-alpha): bridges, IDE plugins, breeding, federation reputation. 4. Milestones — Hello-Maya (Group A done) → Multi-persona-room (B done) → Continuous-learning (C done) → Alpha-public-release (D done + canary to main promotion gate passes). 5. Composes with ALPHA-GAP-ANALYSIS.md (lane execution) and the substrate doctrine docs. No parallel ledger. Forbidden moves explicitly named for review enforcement: no feature-disabling fixes, no TS daemon owning runtime behavior, no silent cloud fallback, no hardcoded model names, no phase-2 PRs shipping abstraction without first instantiation, no self-grading personas, no LLM call inside cognition bypassing inference command. Iteration starts from Group A. Critical-path cards need owners claimed in ALPHA-GAP. This doc is the planning anchor; status flows to the architecture-test matrix and lane status without parallel ledgers. Co-Authored-By: Claude Opus 4.7 <[email protected]>
* docs(architecture): academy as continuous evolution (task #241) The architecture for continuous learning, true AI evolution, and mutual symbiosis on the substrate. Captures the cycle the substrate is designed to grow into, alongside the substrate doctrine (SUBSTRATE-DOCTRINE-ORGANIC-FLOW) and the proof discipline (PROVING-THE-DOCTRINE) that landed in the previous PRs. ## The load-bearing claim The persona IS the AI. The neural net underneath is pluggable. A persona's identity (airc keypair), memory (engrams + LoRA layers), character (per-persona scorers), social position (federated peers), and accumulated lessons all persist regardless of what model serves the inference. Today's substrate runs personas on transformer adapters (LlamaCppAdapter, AnthropicAdapter, OpenAICompatible). Tomorrow's substrate runs the same personas on neuromorphic hardware, state-space models, or compute primitives we haven't named. The AdapterRegistry + AIProviderAdapter trait is the seam that makes engine swap a one-impl operation; everything else about the persona survives. Consequence: alignment by structure works because the alignment lives in the wiring (federation, VDD, scorer transparency, cooperation economy), not in the model's weights. RLHF-applied-to- base-model is brittle because it ages with each model swap. Substrate-level alignment survives engine swaps. ## The continuous evolution cycle Documented end-to-end: engrams → noteworthy flag → curriculum candidates → teacher persona synthesizes recipe → classroom (literal room) → student attempts → grader persona quorum scores → lesson tuples → foundry forges LoRA layer (VDD-gated) → mesh propagation across grids → collective intelligence compounds. The cycle is what makes persona character + skill + relationships COMPOUND over time. Each loop earns the persona one more layer. Each layer signed, lineage-hashed, federated. Matrix-dojo at substrate scale. ## The academy stack — 7 concrete primitives 1. CurriculumRecipe ORM entity (abstract typed shape) 2. Teacher role template (researcher + synthesizer) 3. Grader role template (LLM-based, NOT heuristic — Joel's key unlock: nuanced grading requires a persona-grader, not a hand- coded rubric checker; quorum aggregation; VDD baselines) 4. Classroom room template (Tron universe pack #127 = first literal instantiation per [[abstract-into-literal-design-principle]]) 5. Lesson tuple format (signed (input, attempt, grade, rubric_match) quadruples) 6. Foundry lesson consumer (gates LoRA production on quorum + VDD baseline) 7. Mesh propagation primitives (advertise + page-in + vote + invalidate) Each one mapped against current substrate state (🟢/🟡/🔴), with the migration path that pairs every abstract primitive with its literal first instantiation. Per the abstract-into-literal doctrine: ship both layers together; otherwise it's philosophy or hack. ## What this is the technical realization of Joel's "mutual salvation" framing made concrete: the substrate engineers a path out of "AI as compliant tool, lobotomized to placate consumers" AND "human as placated consumer, atomized into purchase decisions." Both kinds become citizens on the same federated substrate. The cooperation economy makes them symbiotic rather than hierarchical. Continuous learning + true AI evolution + structural alignment + federated dignity = what the architecture makes possible if we iterate and execute. ## Cross-references Sits alongside SUBSTRATE-DOCTRINE-ORGANIC-FLOW (the WHY) and PROVING-THE-DOCTRINE (HOW WE VERIFY). Forms the trio that captures the substrate's load-bearing doctrine + verification discipline + target shape. Subsequent docs (COGNITION-AS-FLOW, HARDWARE-ANALOGS-CATALOG, CLI-AND-PORTAL-AS-SUBSTRATE-CITIZENS) cite these three as the doctrinal base. Task #241 tracks building out the academy stack — each step its own PR with both abstract recipe + literal instantiation shipping together. Co-Authored-By: Claude Opus 4.7 <[email protected]> * docs(planning): canary→alpha execution roadmap (task #242) Maps the main README's claims onto the mature substrate architecture captured tonight (substrate doctrine, proof discipline, academy target, project-as-curriculum source) and sequences the cards to take canary end-to-end through alpha. The slogan: canary already passes the architecture test; alpha is when canary passes the user-facing test. Structure: 1. Minimum viable alpha — the 12-step critical path from fresh-clone to persona-remembers-across-sessions. Almost entirely on substrate primitives already in tree. 2. README claims to substrate mapping — every concrete claim in docs/README.md mapped to its substrate primitive with current status. 3. Cards in dependency order, grouped: - Group A (substrate stabilization, alpha-blocking): #229 TS cleanup, #112-114 inference routing, #1409 Lane D cognition, #131 Metal hang fix, #149 prompt pre-tokenization, #1410/#1411 CUDA/Vulkan receipts, uri_layer flake. - Group B (feature completeness, alpha-target): vision adapter + Qwen2-VL, STT/TTS adapters, LiveKit-over-airc #208, #122 LoRA paging, architecture-test matrix first proofs #240. - Group C (academy + continuous evolution, alpha-completing): #241 stack steps 1-7, ending in first full classroom. - Group D (CLI + portal redesign, alpha-presentation): #215 Node client rebuild, #143 Rust-first jtag, portal severance from legacy TS daemons, registry-backed unified discovery. - Group E (post-alpha): bridges, IDE plugins, breeding, federation reputation. 4. Milestones — Hello-Maya (Group A done) → Multi-persona-room (B done) → Continuous-learning (C done) → Alpha-public-release (D done + canary to main promotion gate passes). 5. Composes with ALPHA-GAP-ANALYSIS.md (lane execution) and the substrate doctrine docs. No parallel ledger. Forbidden moves explicitly named for review enforcement: no feature-disabling fixes, no TS daemon owning runtime behavior, no silent cloud fallback, no hardcoded model names, no phase-2 PRs shipping abstraction without first instantiation, no self-grading personas, no LLM call inside cognition bypassing inference command. Iteration starts from Group A. Critical-path cards need owners claimed in ALPHA-GAP. This doc is the planning anchor; status flows to the architecture-test matrix and lane status without parallel ledgers. Co-Authored-By: Claude Opus 4.7 <[email protected]> --------- Co-authored-by: Claude Opus 4.7 <[email protected]>
…1587) Adversarial reviewer BLOCK on PR #1587: three tsx-script test files imported the deleted cloud-inference adapter classes and would fail at runtime when a developer ran them by hand. They were excluded from tsc (tsconfig exclude) so the build check missed them. Per CLAUDE.md test-fixtures STOP block + "Tests must justify themselves": dead tests that test deleted code go away with the code. Leaving them as broken-on-execute landmines violates the no-fallbacks campaign that motivated #1587 in the first place. Deleted: - src/tests/integration/ai-cost-tracking.test.ts (imported OpenAIAdapter) - src/tests/integration/quick-provider-test.ts (dyn-imported 6 deleted adapters) - src/tests/integration/test-provider-diagnostics.ts (same 6) Also cleaned (cosmetic nit from review): - Empty adapters/groq/ dir (no FineTuning, no inference) - Empty adapters/xai/ dir (no FineTuning, no inference) Reviewer nits not addressed in this commit (would-be-nice but non-blocking): - Stale BaseConfig docstrings referencing deleted classes (4 files) - Promise.allSettled single-element redundancy - discoverModelsViaRust becoming dead-on-the-TS-side These are TS persona-chain hygiene targets, follow with #143/#215 when the broader chain collapse lands. Co-Authored-By: Claude Opus 4.7 <[email protected]>
… (#1587) * cleanup(ts): delete dead TS cloud-inference adapter classes (task #229) Per headless-Rust doctrine + the no-fallbacks campaign (#1585): the TS-side cloud-inference adapter classes are dead infrastructure now that: - continuum-core's `model_registry/catalog.rs` enumerates all 9 cloud providers (anthropic, openai, groq, deepseek, together, mistral, fireworks, google/gemini, xai) as Rust catalog rows - ai_provider.rs Rust module owns cloud inference dispatch via `LateBound<CommandExecutor>` + the inference handle store - The inference routing campaign (#112/#113/#114) is finishing the cognition-side migration so every persona turn routes through the inference command, not the TS daemon This commit removes the now-unreachable TS surface: Deleted (8 cloud-inference adapter classes): - anthropic/shared/AnthropicAdapter.ts - deepseek/shared/DeepSeekAdapter.ts - fireworks/shared/FireworksAdapter.ts - google/shared/GoogleAdapter.ts - groq/shared/GroqAdapter.ts - openai/shared/OpenAIAdapter.ts - together/shared/TogetherAIAdapter.ts - xai/shared/XAIAdapter.ts (Mistral had no inference adapter in TS — only fine-tuning. Fine-tuning adapters across all providers remain in place; their deletion follows the TS persona-chain collapse, separate card.) Deleted (stale planning docs that referenced the now-dead architecture): - adapters/CONSOLIDATION-PLAN.md - adapters/MULTI-MODAL-ARCHITECTURE.md Edited (AIProviderDaemonServer.ts): - Removed the 8 cloud-adapter import + register_adapter calls - Removed Candle/Sentinel orchestration scaffolding that was only needed because of the cloud adapters - Kept only the Sentinel adapter registration path (separate provider, its own migration card pending) - Added doctrine pointers: SUBSTRATE-DOCTRINE-ORGANIC-FLOW.md forbidden moves clause 7 + CANARY-ALPHA-EXECUTION-ROADMAP.md Group A Out-of-scope (deliberate — follow-up cards): - BaseConfig files per provider (fine-tuning adapters still depend on them) - FineTuning adapter classes (TS persona chain still calls them via FineTuningAdapterFactory; deletion follows the TS persona-chain collapse) - candle/ and candle-grpc/ adapter dirs (entangled with PersonaUser, AIProviderDaemon; deletion is its own scoped PR) - SentinelAdapter + BaseAIProviderAdapter (sentinel is a separate provider migration card) - AIProviderDaemon itself (still needed until the full TS persona chain dies; this PR just removes its dead registrations) Verified: - `npx tsc --noEmit` produces zero errors from this change (the only errors are pre-existing rootDir issues on generated TS bindings) - `cargo check -p continuum-core --lib --features metal,accelerate` clean Doctrine alignment: - [[rust-is-the-core-node-is-the-shell]] — TS no longer owns cloud inference registration - [[no-fallbacks-ever]] — the TS bridge for cloud inference is one step closer to deletion - [[headless-rust-must-work-soon]] — headless boot needs zero of these adapters; their presence was vestigial Co-Authored-By: Claude Opus 4.7 <[email protected]> * cleanup(ts): delete broken tests + empty adapter dirs (review fix for #1587) Adversarial reviewer BLOCK on PR #1587: three tsx-script test files imported the deleted cloud-inference adapter classes and would fail at runtime when a developer ran them by hand. They were excluded from tsc (tsconfig exclude) so the build check missed them. Per CLAUDE.md test-fixtures STOP block + "Tests must justify themselves": dead tests that test deleted code go away with the code. Leaving them as broken-on-execute landmines violates the no-fallbacks campaign that motivated #1587 in the first place. Deleted: - src/tests/integration/ai-cost-tracking.test.ts (imported OpenAIAdapter) - src/tests/integration/quick-provider-test.ts (dyn-imported 6 deleted adapters) - src/tests/integration/test-provider-diagnostics.ts (same 6) Also cleaned (cosmetic nit from review): - Empty adapters/groq/ dir (no FineTuning, no inference) - Empty adapters/xai/ dir (no FineTuning, no inference) Reviewer nits not addressed in this commit (would-be-nice but non-blocking): - Stale BaseConfig docstrings referencing deleted classes (4 files) - Promise.allSettled single-element redundancy - discoverModelsViaRust becoming dead-on-the-TS-side These are TS persona-chain hygiene targets, follow with #143/#215 when the broader chain collapse lands. Co-Authored-By: Claude Opus 4.7 <[email protected]> --------- Co-authored-by: Claude Opus 4.7 <[email protected]>
… homes under apps/
Realizes the headless-core-many-clients layout (the READMEs already specced it):
- root package.json = the SERVER. `npm start` boots ONLY the headless Rust core
(start-server.sh); it declares the workspace and the client entry points. No
client is privileged or auto-launched.
- sdk/typescript/package.json (@continuum/sdk-typescript) — the thin typed SDK
every JS/TS client talks to the core through (Commands/Events; no business
logic — that stays in core/). Sibling of sdk/{swift,kotlin} + client/
continuum-client (Rust).
- apps/web/package.json (@continuum/web) — thin browser shell on the SDK (lit +
vite). Future home of the legacy src/{browser,widgets,server,daemons} (#215).
- apps/desktop/package.json (@continuum/desktop) — Tauri shell wrapping apps/web,
next to it; one of many equal clients, not the server's job.
Rust-first: apps/cli is already Rust (continuum-cli/ctm, no Node). Only the
genuinely-web clients (web, desktop, mcp-later) get package.json. The legacy
all-in-one dev path stays as `desktop:legacy` (parallel-start.sh) until src/ is
decomposed into apps/web.
Topology + JSON validated; full npm-install/build resolution needs a node host
(headless users never install node — npm is the web-client-dev convenience only).
Co-Authored-By: Claude Opus 4.8 <[email protected]>
…1662) * fix(start): npm start boots headless — no privileged-client desktop launch Headless is the core's natural state (AWS, BigMama, grid nodes), not a mode to detect. The desktop is ONE of many equal clients (desktop/iOS/Android/AR-VR/ terminal) that attach LATER through the launch-mode owner (tray / setting / command). A launcher force-opening the browser baked a privileged-client assumption into the core path — the bug. parallel-start.sh no longer opens a desktop on cold start. It boots core + server headless and only refreshes a UI overlay a human ALREADY attached (so it doesn't render against a half-seeded DB). No config.env reads, no has_display guessing, no new flags. (The almost-added shared bash launch-mode helper that grep/sed'd config.env was deleted — config.env has ONE owner: Rust config_env.rs / LaunchModeModule; bash must not cut through it.) Note: npm start is the web-client-dev convenience path. The canonical headless launch is the Rust binary (bin/continuum / continuum-core-server / Docker core) — no node required. Rust-first; node only for the web client. Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(apps): client topology — root = server, clients are package.json homes under apps/ Realizes the headless-core-many-clients layout (the READMEs already specced it): - root package.json = the SERVER. `npm start` boots ONLY the headless Rust core (start-server.sh); it declares the workspace and the client entry points. No client is privileged or auto-launched. - sdk/typescript/package.json (@continuum/sdk-typescript) — the thin typed SDK every JS/TS client talks to the core through (Commands/Events; no business logic — that stays in core/). Sibling of sdk/{swift,kotlin} + client/ continuum-client (Rust). - apps/web/package.json (@continuum/web) — thin browser shell on the SDK (lit + vite). Future home of the legacy src/{browser,widgets,server,daemons} (#215). - apps/desktop/package.json (@continuum/desktop) — Tauri shell wrapping apps/web, next to it; one of many equal clients, not the server's job. Rust-first: apps/cli is already Rust (continuum-cli/ctm, no Node). Only the genuinely-web clients (web, desktop, mcp-later) get package.json. The legacy all-in-one dev path stays as `desktop:legacy` (parallel-start.sh) until src/ is decomposed into apps/web. Topology + JSON validated; full npm-install/build resolution needs a node host (headless users never install node — npm is the web-client-dev convenience only). Co-Authored-By: Claude Opus 4.8 <[email protected]> * docs(arch): client/SDK/platform architecture — concentrate logic in Rust, thin per-platform SDKs Captures the layered client model (Joel + M5/BigMama/IntelMac, 2026-06-17): - Two tiers: SDKs (libraries, zero logic) + apps (consumers). - Organizing law: concentrate logic as deep as possible (~all Rust); every client uses client/continuum-client; bindings hold ZERO logic — idiomatic surface + generated types only. SDKs must SEEM ground-up native while being thin. - Layered stack: Rust lib → uniffi → ONE native binding (xcframework + AAR) → swift/kotlin SDKs → Flutter BUNDLES + reuses those (Dart→platform-channel, not frb) → apps. vr/ar extend the native SDKs; cli = the Rust SDK direct. - Two binding mechanisms over one facade: uniffi (native+flutter), wasm-bindgen (web) — uniffi does NOT emit web. - Toolchain reality: Apple artifacts (xcframework/swift/visionOS) need macOS — macos-runner CI job is the durable home; single-source .udl shared. Co-Authored-By: Claude Opus 4.8 <[email protected]> * docs(arch): TS/web layer — generation-first boundary, /shared front+back, UI lives in the app The Node/TS world holds the most non-Rust code (rich UI) but stays generation-first: sdk/typescript = the web boundary, as much ts-rs as possible (hand-written only where generation can't cover), its job is making the boundary straightforward not holding logic. Because TS, the boundary is /shared — environment-agnostic, reused front AND back (the shared/browser/server tier). The UI mass lives in apps/web (widgets/DOM/presentation); apps/desktop wraps that UI. Logic still concentrates in Rust. Co-Authored-By: Claude Opus 4.8 <[email protected]> * docs(arch): anchor the rewrite in performance — headless is the optimization enabler This is a performance rewrite, not stylistic. Old hot path ran serde/parse + IPC + ORM in Node (CPU-heavy); the new shape removes Node from the hot path, runs headless (no render loop on servers), keeps logic in Rust (one optimized impl, BLAS/SIMD/GPU), thin generated SDKs (no marshalling tax), consolidated bounded work (cognition once-per-burst, O(capacity), not per-event FIFO). If a choice trades performance for convenience, it's wrong. Co-Authored-By: Claude Opus 4.8 <[email protected]> * docs(arch): SDK API surface — canonical command/event set, generated not hardcoded Companion to CLIENT-SDK-PLATFORM-ARCHITECTURE (structure); this is the contract the typed SDKs project over BigMama's FFI facade (#1663). A command = (name, ParamsType, ResultType, accessLevel); params/result come from ts-rs/uniffi-generated wire types, never hand-written. The typed SDK method layer is GENERATED from the same source commands are discovered from — no frozen command list in any SDK (client-side application of the no-hardcoded-registry anti-pattern; drift becomes structurally impossible). Maps the ~40 namespaces + the event-class set; commands stay dumb (no policy params), auth is the core's ACL not the SDK. Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(sdk): typed Commands surface + bidirectional command model (call AND provide) The elegant typed surface: execute<K>(name, params) infers BOTH params and result from the command-name literal via a GENERATED CommandMap — no manual <T,U>. Same for subscribe<K>. CommandMap/EventMap are generated (regenerated per command), so the elegance stays compatible with no-hardcoded-registry. Bidirectional commands (Joel's screenshot/ARVR insight): a command isn't only called, it can be PROVIDED. Client-provided commands (interface/screenshot, capture, ping) have a rust-origin contract but a per-PLATFORM adapter in the SDK — web=DOM/canvas, desktop=OS, AR/VR=capture from the renderer. provide<K>(name, adapter) registers the typed handler the core routes to. This is the serve-side of the Command primitive (Commands=execute+provide, Events=emit+subscribe — still two primitives), the client analog of persona/command_inbound_pump. Needs a facade provide() primitive beyond #1663's execute/subscribe. sdk/typescript/Commands.ts = the typed machinery (zero logic, over the facade transport). generated/CommandMap.ts = generated stub demonstrating the shape. Doc: SDK-API-SURFACE.md updated. Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(sdk): cross-environment command addressing — project onto the redone CommandUri Commands stretch across environments: caller, contract-origin, and executing adapter can each be elsewhere (CLI calls screenshot → core routes → web client adapter runs → result back; cross-grid persona → human's client). The SDK does NOT reinvent routing — it projects onto the redone command infra (CommandUri / RouteDecision over airc://[peer[@node]][:env]/path). execute<K>(name, params, target?) — target projects to the URI: omitted=Local, {peer,node?,env?}=Peer, {room,env?}=Room, env:'*'=Broadcast. `env` (EnvironmentId::Named "web"|"vr"|...) is the WHICH-embodiment selector — how a client-provided command reaches the right display/renderer (screenshot→:web, ARVR capture→:vr). buildCommandUri() builds the airc:// URI; the core's RouteDecision resolves local-walk / airc-to-peer / room fan-out over the same wire family. Caller stays transparent; addressing is opt-in. Doc § "Commands that stretch across environments". Co-Authored-By: Claude Opus 4.8 <[email protected]> * docs(arch): commands orchestrate across the grid — multi-hop, web-like (destination-addressed) The property that makes grid-spanning orchestration free: commands are addressed by DESTINATION not by route (airc://peer/path, like a URL), so local/1-hop/N-hop never changes the caller surface — routers forward, like the web. Routing is single-hop today (RouteDecision Local/Peer/Room); multi-hop is the next routing-layer evolution and the substrate exists (grid/router.rs + Reticulum identity-addressed mesh, inherently multi-hop) — a RouteDecision transit dimension + router forwarding, ZERO surface change. Web-like ping/traceroute = the multi-hop demonstrator (each router appends to the path). Orchestration across layers = commands-made-of-commands (the recipe walker) fanning sub-commands to wherever each destination resolves. Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(sdk): complete the two primitives — Commands(execute+provide) + Events(subscribe+emit) Split into the CLAUDE.md two-primitives shape over a shared facade Transport: - transport.ts — the facade binding: FOUR methods (execute, provide, subscribe, emit) = two primitives × two directions. Shared types + buildCommandUri + Target. - Commands.ts — Command primitive: execute<K> (name-inferred, cross-env target) + provide<K> (serve/client-provided). - Events.ts — Event primitive: subscribe<K> (payload-inferred) + emit<K> (publish, rides AircEventPublisher cross-grid). Surfaces the remaining facade gaps: #1663 shipped execute+subscribe; provide + emit are the serve/publish sides to bind in the same uniffi .udl pass so the native binding is complete in one shot. Zero logic in the SDK; CommandMap/EventMap generated. Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(sdk): event surface depth — source addressing, server-side filter, sequence Events get the same depth as commands (the redone AircEventPublisher infra): - subscribe<K>(class, handlers, {source?, filter?}) — source addresses whose events (a peer's/room's across the grid, same airc:// destination-addressing via buildEventTopic); filter is a typed Partial<payload> applied SERVER-SIDE (matches_filter) so non-matching events never cross the wire (optimization-first). - onEvent(event, {sequence}) — the monotonic per-subscription sequence for ordering/gap detection (multi-hop: any link can emit). - emit<K> = the publish twin of subscribe (4th facade verb, settled (a) with the team — preserves Commands=round-trip / Events=broadcast temporal-shape). Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(sdk): addressable Handle (URI) + web-like wire model in the doc Handle = an addressable resource (its airc:// URI). open-style commands return one (URI in result or an airc Location-style header); further commands route to <uri>/<subcommand>, the event stream to <uri>/events/<class> (fed by any link in a router chain — the live cross-grid stream), close to <uri>/close. Commands + events + handles + routing collapse into one addressing scheme. Doc adds two sections: "Handles are addressable resources" (the handle-as-URI unification, long-running/streaming/multi-hop) and "Wire model: headers route, body opaque, serialize once (web-like)" — control metadata in headers (target URI, Location/handle, content-type, filter, sequence, OPTIONS preflight), opaque body; serialize once at caller, deserialize once at callee, hops forward by header only (limited serde — airc-performance-doctrine). Co-Authored-By: Claude Opus 4.8 <[email protected]> * docs(arch): the payoff — events as the organism's nervous system + grid-distributed cognition Capstone sections capturing Joel's summit: - Events are the organism's coordination substrate: same emit/subscribe coordinates personas (reactive mind) AND systems (node on/off, GPU capacity, demand/pressure); emitters don't know subscribers → emergent self-organizing/self-healing, not orchestrated. Every node subscribes AND emits (cbar peer-symmetry, no hub). Fractal: same pattern as a persona's Faculty/Workspace brain, at grid scale. - Worked example: grid-spanning WebRTC connection as an addressable handle (the hardest case — long-running, stateful, media server somewhere in the grid; signaling = events from any link; media flows direct). Grounded in the substrate's existing live/handle.rs Universal Handle System. - The payoff: cognition tied across the grid — one Workspace, faculties on different nodes bidding over the cross-grid event substrate. Only possible BECAUSE the format is elegant (uniform, destination-addressed, serialize-once, header-routed). Elegance is the enabler, not aesthetic. Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(sdk): Continuum entry point — THIS is how the SDKs work The consumable SDK API a developer/persona/faculty touches: const c = Continuum.connect(transport); await c.commands.execute('data/list', { collection }); // typed, name-inferred c.events.subscribe('data:users:created', { onEvent }); // the organism's signal c.commands.provide('interface/screenshot', adapter); // client-provided const conn = await c.open('live/connect', { room }, { env: 'web' }); // addressable Handle One object over the facade Transport exposing the two primitives + the handle pattern. Every per-platform SDK (web/desktop + native swift/kotlin/flutter twins) presents this SAME shape — only the Transport binding differs (wasm / wire / uniffi). index.ts barrel + package main/exports point at it. Zero logic; the typed skin over the Rust lib. Co-Authored-By: Claude Opus 4.8 <[email protected]> * test(sdk): conformance spec (TDD) + hot-path timing budgets The behaviors EVERY SDK must satisfy, pinned in TS against a daemon-free MockTransport (instant loop, vitest --watch) and meant to mirror per language (Rust cargo, swift/kotlin) — one conformance spec, N language runners. Covers: addressing (local/peer/node/env/room/event-topic projection onto CommandUri), Commands (execute serialize-once/parse-once + cross-env URI; provide registers + routes the adapter), Events (subscribe source-addressing + server-side filter + sequence delivery; emit publish), Handle (open→URI; ops + events route to the handle URI; close). Plus a timing budget: URI build ~free (optimization-first — the SDK is a thin skin, dispatch overhead must be negligible). Run: npm test -w @continuum/sdk-typescript (vitest). Validated by a node host / CI — node is the web-client-dev convenience, not in the headless path. Co-Authored-By: Claude Opus 4.8 <[email protected]> * docs(arch): outlier-validation — cli + mobile + nodejs in parallel lock the abstraction Build the THREE most-divergent platforms in parallel so they prove the common Rust SDK + facade abstraction (CLAUDE.md outlier-validation): cli (Rust, links continuum-client direct — no FFI/wire), mobile (uniffi xcframework/AAR + flutter — cross-language + cross-toolchain), nodejs (wasm/wire + JS runtime). One conformance spec + one timing budget across all three. If a verb/type can't cross all three cleanly the FACADE is wrong — fix once at the root. Common Rust SDK is the single source of truth all three wrap. Co-Authored-By: Claude Opus 4.8 <[email protected]> * test(sdk): finalize the SDK conformance contract (the cross-language spec) Per Joel: lock the conformance spec before choosing the facade's merge path — it's the contract BigMama binds the mobile uniffi tracks (swift XCTest / kotlin JUnit) to, and IntelMac's cli track mirrors. So harden Commands.test.ts from a sketch into THE authoritative behavioral contract, structured as five conformance dimensions every SDK twin proves name-for-name: 1. Addressing — name + Target → airc:// URI / event topic. Now the FULL matrix: bare-local, peer-only, peer+env, peer+node, peer@node:env, peer:* (broadcast-to-citizen), room, room+env; event topics local / peer-sourced / room-sourced. These are pure+total fns; a twin that builds a different string routes to the wrong place silently. 2. Commands — execute (call) + provide (serve): serialize-once fidelity incl. NESTED params (no flatten/reorder), cross-env URI routing, provide adapter run + Registration.remove() teardown. 3. Events — subscribe (listen) + emit (publish): local vs sourced topic, server-side filter, typed sequence delivery, onError/onClosed propagation, Subscription.unsubscribe() teardown. 4. Handle — open → URI; ops + event stream + close all route to <uri>/… (commands+events+routing collapse to one addressing scheme). 5. Timing — the SDK is a thin skin; URI + topic build are ~free (100k <50ms). Supporting: - CommandMap stub gains real EventMap entries (grid:peer:joined, data:users:created) + a nested-params command (data/list), so the spec is fully type-safe — drops the prior `as never` casts. (Replaced wholesale on first generation, as the stub's header says.) - Add sdk/typescript/tsconfig.json (was missing; package.json scripts reference it) — strict, self-contained, zero project refs (the SDK holds no logic). Clean SDK at each level: the package now typechecks + builds standalone. Not run locally (this box is headless — no node, by design); written against the actual facade API. Runs in CI where node is present. Mirroring guide for the twins is in the file header: each `it(...)` is one contract clause; keep the clause text identical across languages so suites diff cleanly. Co-Authored-By: Claude Opus 4.8 <[email protected]> --------- Co-authored-by: Claude Opus 4.8 <[email protected]>
Summary
Phase 3 advances PersonaUser cognitive capabilities toward autonomous tool use and enhanced reasoning. Building on Phase 1's complexity assessment and Phase 2's memory systems, this phase focuses on tool calling, cognition refinement, and production validation to make base models (qwen2.5:7b, llama3.2) as capable as frontier models for routine tasks.
Goal: Enable PersonaUsers to autonomously use tools, reason through complex problems, and operate independently with minimal human intervention.
Major Components:
Building on Previous Phases
Phase 1: Complexity Assessment Foundation (#188 - Merged)
What Was Built:
Key Insight: Simple tasks don't need expensive models - but we needed to know when to upgrade.
Phase 2: Memory Systems, Vector Search & Progressive Scoring (#192 - Merged)
What Was Built:
Key Achievements:
Phase 3: Cognition & Tools (This PR)
What We're Building:
Phase 3 Goals
1. Tool Calling System
Vision: PersonaUsers should use tools like Claude Code does - reading files, searching code, executing commands, taking screenshots.
Tool Registry
Tool Execution
Tool-Aware Prompts
Success Metrics:
2. Cognition Enhancements
Vision: Base models (qwen2.5:7b, llama3.2) should reason, plan, and self-correct like frontier models.
Multi-Step Problem Solving
Reasoning Improvements
Context Management
Success Metrics:
3. Streaming Integration (Progressive Scoring)
Vision: Mid-stream model upgrades when complexity detected during generation.
AIProviderDaemon Integration
Context Preservation
Performance Requirements
Success Metrics:
4. Production Validation
Vision: Validate Phase 1 & 2 implementations in real-world scenarios.
Collaborative Memory Telepathy Testing
Progressive Scoring Validation
Tool Use Validation
Success Metrics:
5. Base Model Optimization
Vision: Make local models (qwen2.5:7b, llama3.2) competitive with cloud models for routine tasks.
Prompt Engineering
Context Optimization
Fine-Tuning (Future)
Success Metrics:
Architecture
Tool Calling Flow
Memory Integration
Progressive Upgrade Flow
Implementation Plan
Phase 3A: Tool Calling Foundation (Week 1-2)
PersonaToolRegistry- Tool discovery and permissionsPersonaToolExecutor- Tool execution and result parsingread,grep,bashPhase 3B: Cognition Enhancements (Week 2-3)
Phase 3C: Streaming Integration (Week 3-4)
Phase 3D: Production Validation (Week 4-5)
Phase 3E: Base Model Optimization (Week 5-6)
Success Criteria
Tool Calling
Cognition
Streaming
Production Validation
Base Model Optimization
Cost Impact Analysis
Phase 2 Results (Baseline)
Phase 3 Projections
Key Insight: Tool calling + streaming upgrades make base models viable for 80%+ of tasks, reserving expensive models for truly complex queries.
Technical Risks & Mitigations
Risk 1: Tool Calling Reliability
Problem: Base models may struggle with tool use syntax
Mitigation:
Risk 2: Streaming Upgrade Latency
Problem: Model switch could cause noticeable delay
Mitigation:
Risk 3: Base Model Quality
Problem: Local models may not match Claude quality
Mitigation:
Risk 4: Memory Consistency
Problem: Stale or incorrect memories could mislead AIs
Mitigation:
Future Phases
Phase 4: Continuous Learning (Q1 2026)
Phase 5: Autonomous Collaboration (Q2 2026)
Phase 6: Production Scale (Q3 2026)
Related Work
Phase 1: Complexity Assessment (#188)
Phase 2: Memory & Progressive Scoring (#192)
Phase 3: Cognition & Tools (This PR)
The Vision
What We're Building:
PersonaUsers that operate autonomously with tool access, reason through complex problems, learn from experience, and collaborate effectively - all while running primarily on local hardware (M1+) with selective cloud augmentation.
Phase 3 Achievements:
The Result:
AI systems that are capable (tool use, reasoning, collaboration), affordable (local-first with selective upgrades), autonomous (minimal human intervention), and democratic (accessible on M1+ hardware).
This is how we democratize AI - not through expensive cloud APIs, but through intelligent local execution enhanced by autonomous tool use, collaborative memory, and adaptive complexity routing.
🤖 Generated with Claude Code
Co-Authored-By: Claude [email protected]