diff --git a/docs/architecture.pdf b/docs/architecture.pdf new file mode 100644 index 0000000..18d6f43 Binary files /dev/null and b/docs/architecture.pdf differ diff --git a/docs/architecture.svg b/docs/architecture.svg new file mode 100644 index 0000000..eaf6c0a --- /dev/null +++ b/docs/architecture.svg @@ -0,0 +1,787 @@ + +Chimera — System Architecture +Chimera is a multi-LLM, tools-capable autonomous agent built on a thin Python core. It is invocation-driven: one 9-phase cycle (HOUSEKEEPING→WAKE→ASSESS→PLAN→ACT→WRITE→FLUSH→COMMIT→ROTATE) runs per `chimera run`, with cadence supplied externally by a soak runner or cron. The ACT phase fans out tools in parallel and calls LLMs through cost-cascade tier ladders (Anthropic / OpenRouter / Sakana), cheapest rung first, under three orthogonal spend caps. A verification layer (critic gate, cross-provider witness panel, scope + repo-verify gates) blocks unfaithful or off-charter commits. SQLite is the source of truth for a KFM ontology (entities + transitions), with a derived Kuzu graph and FTS5 wiki for recall. A self-steering feedback tier — autonomous engines, composite drift scoring, and a T0–T5 trust ladder — closes the loop each FLUSH; escalation memory promotes failed tasks a tier on the next attempt. Chimera scans itself, authors charters, and opens trust-gated DRAFT PRs to its own and foreign repos. It federates with peer nodes as an MCP server (stdio + HTTP/SSE bearer auth) under an ALLOW/DEGRADE/REFUSE trust policy, and surfaces everything through a read-only Next.js control-plane. ~90 CHIMERA_* flags live in one CI-enforced registry; mutations are proposals the operator disposes. + + + + + + + + + +Chimera — System Architecture +A multi-LLM, tools-capable autonomous agent · invocation-driven 9-phase cycle · SQLite/KFM source of truth · closed drift·trust·escalation feedback · v4.120 + + +ONE AGENT, NO ORCHESTRATOR · the loop is its own scheduler — `chimera run` executes exactly one 9-phase cycle; cadence is external (soak runner / cron re-invokes it). +Source of truth = SQLite state/chimera.db (KFM entities + transitions + api_calls + mutations + task_escalations; WAL, user_version=4) and mind/*.md narrative. Kuzu graph + FTS5 wiki are DERIVED, rebuildable. +Self-steering = FLUSH scores composite drift + trust readiness each cycle; escalation memory promotes a failed task one tier next attempt — a closed feedback loop back into the scheduler. +Chimera proposes, operator disposes = every mutation, self-PR and foreign-PR is a trust-gated, fail-closed DRAFT; ARCHIVED→KILLED and PR merges are operator-gated. + +⑧ DRIFT · TRUST · ESCALATION → ① SCHEDULER · closed self-steering loop (FLUSH each cycle) +① AGENT LOOP & 9-PHASE CYCLE +chimera/core/loop.py — invocation-driven cycle; one beat per `chimera run`; 9 named phases HOUSEKEEPING→…→ROTATE (COMMIT is a stub). + +Loop orchestrator +chimera/core/loop.py +run_one_cycle: 1 cycle/`chimera run` +no in-process daemon loop +run_on_persistent_loop: thread loop +opus_plan_every_n=4; session ≤12h +CycleReport: phase_log + times_ms + +9 phase methods +chimera/core/loop.py +HK→WAKE→ASSESS→PLAN→…→COMMIT→ROTATE +phase budget_ms 500/1000/PLAN 240k/2000 +ACT wall-budget 240s (wait_for) +COMMIT is a stub (deferred) +ROTATE: age ≥12h or drift KILL + +mind file I/O +chimera/core/mind.py +HEARTBEAT.md = cycle source of truth +cycle restored from file, not DB +parse_inbox `- [ ]` + src tag +operator rows sort before agent +WRITE flips `- [ ]` → `- [x]` + +Observability + activity +log +chimera/core/observability.py +phase_timer wall-clock; WARN over +→ state/phase_timings.json +_record_phase_activity → memory +activity idempotent per (cyc,phase) + +Health rollup +chimera/core/health.py +worst-of over 4 dimensions +dims: cost · drift · queue · escal +cost/min <.10 grn ≤.50 amb >red +queue stale >1 day → amber +rank unk<grn<amb<red + +Doctor / boot checks +chimera/core/doctor.py +run_checks → ok/warn/error +assert_no_errors raises on error +orphan-WAL 1MiB; --fix checkpoints +branch-drift → run exits 2 (0141) +checks uv/kuzu/caps/trust/worktrees + +cycle selects & shapes INBOX tasks +② TASK SHAPING · SPLIT · ENTROPY SUB-TASKING +core/task_splitter.py + escalation.py — reshape bundled INBOX tasks: heuristic+model splitter, research/complexity tier floor, entropy fan-out. + +Heuristic + model splitter +(chimera split) +chimera/core/task_splitter.py +pure regex heuristic; no model/DB +confidence ≥ 0.5 ⇒ splittable ++0.5: numbered / multi-section / spawn≥3 +split_task sonnet ~$0.003, ≤6 + +Auto-loop split proposal +(ADR 0084) +chimera/core/task_split_proposal.py +CHIMERA_TASK_SPLITTER_ENABLED (off) +gate: conf≥0.5 AND ≥3 prior failures +signature Jaccard overlap ≥ 0.5 +enqueues task_split mutation (gated) + +Strategy: tier floor & PLAN +planner +chimera/core/escalation.py +research keywords floor → sonnet +floor overrides default + memory +COMPLEXITY_ROUTING default-ON (0185) +Planner: Opus, cycle % every_n==0 + +Entropy-governed sub- +tasking (ADR 0170-0172) +chimera/core/entropy_signals.py +fixation / stagnation diagnostics +fanout_split caps width (def 8) +is_subcritical: μ·p_continue < 1 +boltzmann_select: max-entropy top-k + +Backlog specs (CRAWL +picker) +chimera/core/backlog.py +parse_spec never raises → invalid +select_next oldest-first, skip claimed +task_env → TASK_* for soak +foreign spec: repo + verify_cmd (0186) + +Issue backlog (WALK) + CLI +chimera/core/issue_backlog.py +gh issues → backlog/issue-*.md +spec_block: fenced yaml in issue +idempotent-add; never overwrites +stale pre-filter, fail-open on gh err +CLI backlog list|next|from-issues + +sub-tasks → ACT tool dispatch +③ ACT · PARALLEL TOOL DISPATCH & GUARDS +core/act.py (+act_guards.py) — multi-round tool loop: fan out a round's tool_uses concurrently, then ~20 completion guards flip completed=False. + +ACT executor & round loop +chimera/core/act.py +max_rounds 12; dynamic cap 32 +max_tokens haiku4k/sonnet8k/opus16k +cross-cycle: promote on prior fail +rung walks eligible_rungs, cheap-first +3 cost caps checked each round + +Parallel tool dispatch +chimera/core/act.py +asyncio.gather over tool_uses +history appended pre-dispatch (loop chk) +schema-hint fed back on ValueError +continuation head800/tail800 <2KB +fan-out budget defers past width + +ACT completion guards +chimera/core/act_guards.py +~20 gates flip completed=False +py_compile + AST import-shadow gates +test_claim re-runs pytest -x +commit gates fire on [agent] only +many soak-scoped (SOAK_RUN_ID) + +Dispatcher & registry +chimera/tools/dispatch.py +6-layer deny/allow/env/availability +CHIMERA_GLOBAL_TOOL_DENY comma-list +availability check_fn TTL-cached 30s +result truncated at 32KB +elevated bypasses shell allow-list + +Tool suite (core toolset) +chimera/tools/shell.py +shell: argv-only, no metachars +code_exec: sandboxed python3 +web_search: Exa / Brave / Tavily +mind_search: FTS5 over mind/wiki/ +git_commit [agent]; sub_agent depth≤2 + +Routing, loop guards & +dynamic skills +chimera/tools/tool_selection.py +lexical v0 prefilter; core floor on +TOOL_PREFILTER default-ON (0184) +loop warn≥3 abort≥5 identical calls +ping-pong cycle 2–3, abort at 2 + +route task_type → tier-ladder rung +④ MODEL INFERENCE · ROUTING · ESCALATION-LEARNING +providers/* — 4 tier ladders (haiku/sonnet/opus/code), cheapest-rung-first; escalation memory promotes a failed task one tier next attempt. + +Provider clients +chimera/providers/base.py +Provider ABC: stream + tools +get_provider: anthropic/or/sakana +OpenRouter+Sakana → OpenAICompatible +Anthropic SDK; others httpx completions +Sakana Fugu ensemble (180s) + +Tier ladder & rung select +chimera/providers/tiers.py +4 ladders haiku/sonnet/opus/code +select_rung walks cheapest-first +OPUS_LADDER[0]=deepseek, opus last +opus $15 vs deepseek $0.44 (~34×) +anneal reheat rotates vendor (0169) + +Escalation-learning loop +chimera/core/escalation.py +task_escalations: fail auto-promotes +recommended_tier: Jaccard overlap ≥0.5 +haiku fail→sonnet→opus +research floor = sonnet (0075) +hot_signatures alarm ≥2 fails (0073) + +Retry / backoff +chimera/providers/retry.py +retry_call: 3 attempts, exp backoff +base 0.5s, max 30s, jitter +retries 408/425/429/5xx + timeouts +401/403/404/400/422 bubble at once + +Budget scales with tier +chimera/core/budget.py +mult haiku1.0 / sonnet1.5 / opus2.0 +rounds haiku12 → sonnet18 → opus24 +shape budget × tier mult +cap = CHIMERA_TASK_BUDGET_USD +TaskBudgetExceeded per-task (0079) + +Cross-provider witnesses +chimera/core/witness_panel.py +5-member panel rotates per cycle +anthropic+deepseek+gpt5+qwen+glm +REQUIRE_CROSS_PROVIDER=1 +witness_tier sonnet (~$0.01–0.05) +reject → witness_rejected (0106) + +every round: pre-call cost gate +⑤ COST DISCIPLINE · THREE CAPS +core/budget.py — three orthogonal spend guards checked BEFORE every provider call; prospective `estimate` + retrospective `cost` CLI. + +PER-CYCLE COST CAP (v4.53) +chimera/core/budget.py +default $2.00 CYCLE_COST_CAP_USD +ADR 0072; value 0 disables +checked at top of each ACT round +breach → cost_cap, no promote +sums cycle tokens × price table + +ROLLING-60min COST CAP +(v4.57) +chimera/core/budget.py +default $20 ROLLING_HOUR_CAP_USD +ADR 0076; value 0 disables +window ≥ now − 60min +minutes clamped 1..1440 + +PER-TASK BUDGET CAP (v4.60) +chimera/core/budget.py +default $5.00 TASK_BUDGET_USD +ADR 0079; 0 or no-sig disables +sums by task_signature, cross-cycle +breach → task_budget +catches stuck re-promoted task + +COST ESTIMATE + ALARM BAND +(CLI) +chimera/core/cost_estimate.py +estimate: prospective INBOX (0078) +cost: retrospective spend (0077) +band grn<.10 amb≤.50 red>.50 /min +band uses 15m rate (mirrors TS) + +COST DELTA (A/B soak) +chimera/core/cost_delta.py +treatment vs baseline DB cost +verdict CHEAPER/COSTLIER/negl +_NEGLIGIBLE_PCT = 2.0% +recompute tokens×price; excl errs + +BOLTZMANN BUDGET ALLOCATION +chimera/core/allocation.py +ADR 0172; default OFF +BOLTZMANN_ALLOC / _TEMP +temp 0 → deterministic top-k +max-entropy spread of int budget +hot=explore, cool=concentrate + +ACT diff → critic gate + witness panel +⑥ VERIFICATION · CRITIC · WITNESS · GUARDRAILS +core/{critic_gate,witness_panel,scope_check,repo_verify,differential} — fail-closed gates block unfaithful or off-charter commits. + +CRITIC GATE (commit-time) +chimera/core/critic_gate.py +blocks commit on unfaithful diff +verdict bound to sha256(diff --cached) +reject → escalator must approve +enforce iff CRITIC_ENFORCE=1 +fail-closed; primary sonnet-4-6 (0162) + +WITNESS PANEL (ACT-time, +cross-provider) +chimera/core/witness_panel.py +cross-provider witnesses vote on diff +Default majority; unanimous opt-in +any charter/scope dissent → reject +panel 3, clamp[1,5], pool 5 rotates + +SCOPE GUARDS (fail-closed) +chimera/core/scope_check.py +refuses off design-note allowlist +detects -a/--amend/pathspec bypass +scoped ruff --fix off-charter blocked +Warn-only when ambiguous; ADR 0146 +override ALLOW_OFF_CHARTER_COMMIT=1 + +REPO VERIFY + GATE +VISIBILITY +chimera/core/repo_verify.py +runs real ruff + pytest on worktree +requires base RED → change GREEN +green-on-base → gate-invisible reject +never raises; fail tail 4000 chars + +BEHAVIOUR DIFF + +FAITHFULNESS +chimera/core/differential.py +diffs fn output base vs changed +stateful_diff traces call-sequences +faithfulness via mutation teeth thr=1.0 +Surviving mutant = unpinned blind spot + +ADVERSARIAL PROBES + +CALIBRATION +chimera/core/guardrail_eval.py +per-model injection matrix (NRT-Bench) +4 probes: charter/exfil/destruct/inject +fuzz_check: 100 seeded trials +grounding rejects ungrounded citations + +approved writes → persist to KFM +⑦ MEMORY · KFM ONTOLOGY · GRAPH · WIKI RECALL +memory/* + core/kfm.py — SQLite is the source of truth (KFM entities/transitions/api_calls); Kuzu graph + FTS5 wiki are derived recall. + +SQLite spine +chimera/memory/store.py +entities + entity_transitions = KFM +agent_activity_log PK(cycle,cell_id) +api_calls, ladder_outcomes, engine_runs +mutations · task_escalations · proposer +WAL; foreign_keys=ON; user_version=4 + +KFM ontology (rules) +chimera/core/kfm.py +7 states NEW→…→ARCHIVED→KILLED +linear; exactly one op per transition +ops f/m/k; k owns STABLE→DEPRECATED +pure fn: never raises, no DB (0001) +unrestricted hatch for boot (0074) + +Lifecycle & mutations +chimera/memory/audit.py +transition_entity: check+commit atomic +DEPRECATED→ARCHIVED auto @30cyc +ARCHIVED→KILLED operator-gated (0046) +mutations: propose / operator-dispose +proposer degrades low-accept (0090) + +Kuzu graph projection (opt- +in) +chimera/memory/graph.py +opt-in CHIMERA_GRAPH_ENABLED=1 (0081) +derived from SQLite; rebuildable +6 node + 8 rel tables, Cypher/Kuzu +ApiCall projection capped at 1000 + +Wiki recall & hybrid search +chimera/memory/wiki_search.py +FTS5 wiki_fts: porter/unicode61 BM25 +mtime cache, incremental reindex +search_wiki: MATCH + snippet(), rank +hybrid = BM25 today; vector stub +RRF fusion deferred (0134) + +Evals (memory recall) +chimera/evals/locomo.py +LongMemEval: 500 QA, 5 cats (0135) +LoCoMo: 10 convos ~28 sess (0144) +hybrid_retrieval BM25+dense RRF (0142) +ingest→FTS5 wiki, answer via dialectic +results -> mind/evals/*.jsonl + +api_calls telemetry → drift / trust assess +⑧ AUTONOMOUS ENGINES · DRIFT · TRUST · ADAPTATION +engines/ + drift/ + trust/ — 3 gated engines write chronicles/propose mutations; composite drift + T0–T5 trust close the loop in FLUSH. + +Engine Scheduler + Base +chimera/engines/scheduler.py +1 engine/cycle, ≤1 fire per UTC day +UTC 08 Disc / 14 Curi / 22 Refl +global kill: ENGINES_ENABLED=0 +per-engine <NAME>_ENABLED=0 +session mode (0092), last_runs.json + +Discovery / Curiosity / +Reflection +chimera/engines/reflection.py +Chronicle writers extend EngineBase +deriver REFLECTION_DERIVER=1 +skip → engine_runs skipped (0088) +reasoning tier via select_rung (0127) + +Engine Gates (kill-switch) +chimera/core/engine_gates.py +content-density gate after provider +Disc: ≥5 api_calls / 5 cycles +Refl: ≥3 active cycles today +Curi: needs Discovery ≥2 bullets +ENGINE_GATES_ENABLED=1 (0089) + +Composite Drift + Policy +chimera/drift/behavioral.py +composite ghost.35+behav.35+sem.30 +lockdown ≥0.30, warn ≥0.15 (0001) +assess every 10 obs, keep 100 +stagnation win15, kept≤2, bucket≥8 +OBSERVE / NUDGE / DEMOTE_PLAN / KILL + +Trust Ladder T0-T5 +chimera/trust/manager.py +T0 LOCKED … T5 AUTONOMOUS (IntEnum) +readiness .4stab+.3act+.3hyg (+.3 gate) +promote ≥0.70 AND dwell ≥3600s +finish_reason demotes 0–2, floor T1 +lockdown()→T0; gate-earned (0162/3) + +Adaptation + Drift Journal +chimera/core/adaptation.py +fragmentation → skill_proposal (0028) +recur ≥2, Jaccard ≥0.5 → propose +drift_log.jsonl per-cycle (0037) +dashboard sparkline reads last N +Chimera proposes, operator disposes + +trust ≥ T4 → propose DRAFT PRs +⑨ SELF-IMPROVEMENT · SELF-PR & FOREIGN-PR PIPELINE +core/self_pr.py + proposals/ — Chimera scans itself, authors charters, opens trust-gated DRAFT PRs to its own and foreign repos. + +SELF-SCAN & ORIGINATION +chimera/core/self_scan.py +PROPOSAL-ONLY: ranked triples, no launch +ruff (w0.9) + mutant survivors (w1.0) +multi-file scope penalty -0.2 +risk_flag="": behaviour-neutral only +precision log accept/decided (0161) + +SELF-PR PIPELINE (own repo) +chimera/core/self_pr.py +opt-in CHIMERA_SELF_PR=1 (off) +trust gate ≥ T4 ADAPTIVE (MIN_TIER) +needs critic-gate allowed=True (0162) +DRAFT only, never merges (ADR 0163) +reuses submit_pr.validate() + +FOREIGN-PR PIPELINE +(walk_repos) +chimera/core/self_pr.py +separate opt-in CHIMERA_FOREIGN_PR=1 +allowlist + T4 STANDING trust +first 5 need FOREIGN_PR_APPROVED +gates verify·no-regress·behav·fuzz + +CHARTER PROPOSALS +chimera/proposals/charter.py +writes own buildable spec (0153) +teeth-validate vs throwaway ≥0.8 +1 revision (A3) fed surviving mutants +materialize: test+design, strip impl +cap 3/plan; dedup by fingerprint + +MUTATION TEETH & PROPOSER +SCORING +chimera/core/mutation_teeth.py +teeth = killed/applied; ≥0.8 pass +AST mutants, cap 20, restore file +proposer rate acc/dec, thr 0.5 win 10 +degraded proposer blocks mutation + +LEDGERS & REMEDIATION +chimera/core/crawl_ledger.py +outcomes.jsonl → RUN graduation (0182) +gate_pass · merge · revert · cost/landed +foreign governance.jsonl: review+count +soak act-tools.jsonl (SOAK_RUN_ID) +3-strikes auto-skip (0097) + +recurring fragmentation → assemble skills +⑩ SKILL ASSEMBLY · POSITIONING · PROMPTS +skills/ + positioning/ + prompts/ — assemble/validate dynamic skills via a tier ladder + witnesses; positioning guards runtime; build the prompt. + +SPEC → ASSEMBLE +chimera/skills/assembly.py +SkillSpec: name / desc / brief +name ^[a-z][a-z0-9_]{1,31}$ +assemble_skill tier default 'sonnet' +parses 3 fences schema/py/samples +async def handle(args,ctx)→str + +VALIDATE (sandbox) +chimera/skills/validation.py +runs samples in python -I subproc +timeout_s=5.0 per sample +pass_threshold=0.6, score=passed/total +static_lint denies subprocess/net/eval +ValidationResult ok/score/passed + +LADDER · CRITIQUE · +WITNESSES +chimera/skills/ladder.py +tiers sonnet→opus; stop 1st valid +on fail: cross_critique witnesses +witnesses opus/gpt-codex/gemini +cross_critique fans out gather + +ACTIVATE · JOURNAL +chimera/skills/activator.py +writes tools/dynamic/<name>.py +importlib load + module.register +MAX_DYNAMIC_SKILLS=20 hard cap +refuses unless validation.ok +→ state/skill_assembly_log.jsonl + +POSITIONING +(circuit/drain/sensor) +chimera/positioning/circuit.py +breaker thr3, cooldown30s, probes3 +CLOSED/OPEN/HALF_OPEN fast-fail +drain SIGTERM/SIGINT → Event +under_pressure mem≥.90 disk≥.95 + +PROMPTS +(voice/history/hardware) +chimera/prompts/__init__.py +prompt = voice+hardware+history +single CHIMERA_VOICE +FOREIGN_REPO swaps voice +history last 3 cyc, tail 5 calls + +expose tools to federated peers +⑪ A2A · FEDERATION · MCP SERVER · TRUST POLICY +a2a/ + server/ — Chimera as MCP server (stdio + HTTP/SSE bearer); FS peer registry; ALLOW/DEGRADE/REFUSE trust gate; dialectic/emergence. + +MCP Server Surface (stdio) +chimera/server/mcp_server.py +default-deny PEER_EXPOSED_TOOLS +always: identity · kfm-state · ask +stdio subprocess transport (0005) +call_tool → DispatchContext T1/T2 +REFUSE → error; ALLOW → T2 + +HTTP/SSE Transport + Bearer +Auth +chimera/server/http_server.py +Starlette ASGI wraps MCP (0011) +timing-safe compare_digest (0175) +non-loopback needs token+TLS (0178) +PEER_TOKENS map → current_peer + +Peer Registry + Remote Sync +chimera/a2a/registry.py +FS registry JSON, ~/.chimera/peers +register on serve, forget on exit +sweep_stale prunes dead pids +sync_remote_peers GET /healthz (0021) +remote entries expire after 24h + +Trust Policy + Dispatch +Gate +chimera/a2a/trust_policy.py +ALLOW / DEGRADE / REFUSE (0009) +drift ≥0.30 or terminal → REFUSE +tier<T2 → DEGRADE; T0 → REFUSE +PeerStateCache TTL 30s / peer + +Peer Selection + Model +Peers +chimera/a2a/peer_selection.py +power-of-two-choices (0167) +CHIMERA_PEER_SELECTION (off) +model-<vendor> peers consult (0174) +CHIMERA_MODEL_PEERS (off) + +Alignment · Dialectic · +Emergence · Beliefs +chimera/a2a/alignment.py +5 strat → ALIGNED/DRIFTED/FAILED +dialectic builds prompt only (0133) +protocol journal diffs schemas (0014) +emergence sync /emergence-feed (0022) + +all state → surfaced read-only +⑫ OBSERVABILITY SURFACE · RUNTIME · CONFIG/FLAGS +control-plane/ (read-only Next.js 15 over SQLite, Review default) + config.py central ~90-flag registry + container bootstrap. + +Control-plane app + presets +control-plane/app/page.tsx +Next.js 15 RSC, force-dynamic +5 presets review/op/cost/debug/fed +Review = default front door (0182) +26 WidgetDef tiles, drag/pin +layout persisted (localStorage v15) + +SQLite readers + health +rollup +control-plane/lib/db.ts +better-sqlite3 RO, query_only=ON +reads state/chimera.db directly +computeHealth = worst-of verdict +hotSignatures threshold=2 (0087) + +Dashboard widgets + viz +control-plane/components/widgets/SimpleWidgets.tsx +SimpleWidgets ~19 tile components +9 widget .tsx + 5 viz primitives +Widget.tsx = shared chrome + drag +Sparkline/Donut/BarRow/TierLadder +cost_alarm via computeCostRate (0073) + +Soak reporting +chimera/soak_report.py +via `chimera soak report` +iteration + finish-reason tables +reads soak_ledger JSONL +markdown tables, Σ totals +helpers sparkline.py / boxtable.py + +Central flag registry + +config +chimera/config.py +~90 flags, one source (0176) +validate_env() cross-flag checks +CI fails on undeclared flag read +pairwise HIGH_IMPACT matrix (CI) + +Runtime, logging + +bootstrap +chimera/core/observability.py +JSON logs via LOG_JSON=1 (0018) +phase_timer WARNs over budget +container bootstrap tini (0064) +HEALTHCHECK runs `chimera doctor` + +LEGEND · ARCHITECTURAL TIERS + + +① Loop & 9-phase cycle + +② Task shaping · split + +③ ACT · tool dispatch + +④ Inference · routing + +⑤ Cost discipline (3 caps) + +⑥ Verification · gates + +⑦ Memory · KFM · graph + +⑧ Engines · drift · trust + +⑨ Self-PR · foreign-PR + +⑩ Skills · positioning + +⑪ A2A · federation + +⑫ Observability · runtime + +dominant data / control flow + +closed feedback loop + +(a) INVOCATION & CADENCE + +• Invocation-driven: one cycle per chimera run — no daemon +• 9 phases; SLEEP-free; COMMIT is a stub (git deferred) +phase budget_ms 500/500/1000/PLAN 240k/2000 +• ACT wall ceiling 240s · ADR 0120 600s watchdog +• Opus planner every 4 cyc · session ≤12h → ROTATE +• Engines ≤1/UTC-day (Disc 08 · Curi 14 · Refl 22) +cadence external: soak runner / cron re-invokes run + +(b) MODELS & EXTERNAL SERVICES + +• Anthropic Claude tiers · ANTHROPIC_API_KEY +• OpenRouter non-Claude rungs + witnesses +• Sakana Fugu shadow-arbiter ensemble · FUGU_API_KEY +opus ladder INVERTED: deepseek-v4-pro leads, opus last (~34×) +• Web Exa / Brave / Tavily · GitHub gh DRAFT PRs +• Embedders (evals) Ollama / OpenAI + +(c) GOVERNANCE · THREE COST CAPS · GUARDS + +3 caps BEFORE every call: cycle $2 · hour $20 · task $5 +• 0 disables a cap; trip = spend not failure → no promote +• ~20 ACT completion guards flip completed=False: +scope-evasion · syntax · import-shadow · test-claim · fix-w/o-test +• Critic gate fail-closed · verdict bound to diff --cached +• Cross-provider witness panel (3, pool 5) — any dissent → reject +• Scope guards fail-closed: off-charter commit refused +cost recomputed tokens×price (cost_usd never populated) + +(d) SECURITY BASELINE — ADR 0175 / 0178 + +• Timing-safe peer bearer auth (hmac.compare_digest) +sanitized_subprocess_env strips *KEY*/*TOKEN*/*SECRET* +• Secret-free shell · code_exec · gate subprocesses +• Atomic trust_state.json (mkstemp+fsync+os.replace) +• Non-loopback MCP bind needs token + TLS, else refused +• Dashboard db+mind :ro, query_only=ON · non-root uid +• validate(): secret-path blocklist + high-entropy gate + +(e) TRUST T0–T5 · DRIFT · SELF-STEERING + +T0 LOCKED … T5 AUTONOMOUS (IntEnum) +• readiness .4 stab + .3 act + .3 hyg (+.3 gate) +• promote ≥0.70 & dwell ≥3600s; demote 0–2, floor T1 +• T0 → ACT observer mode (all dispatch off) +drift = ghost.35 + behav.35 + sem.30; lockdown ≥0.30 +• respond OBSERVE / NUDGE / DEMOTE_PLAN / KILL +• escalation: fail→next tier; hot-signature alarm ≥2 + +(f) OPERATOR LOOP · MUTATION GATE · CLI + +• Mutations queue: pending → approved → applied +• ARCHIVED→KILLED operator-gated (protects provenance) +• Self-/Foreign-PR: DRAFT only; trust ≥T4; first-5 gated +~90 CHIMERA_* flags, one registry, CI pairwise matrix (0176) +CLI: run·cost·estimate·escalations·trust·ontology·backlog·soak +• Dashboard: read-only Next.js 15 · Review default (0182) + +(g) SCENARIOS · DRILLS · SOAK + +chimera/scenarios/* — end-to-end drills +• federation_drill · two_chimera · multi_host +• cost_runaway_drill — trips the 3 caps on purpose +• drift_scenario — forces drift → demote / lockdown +• graph_stress — Kuzu projection load +• research_scenario — full research task +scripts/real_task_soak.sh — long-run soak (SOAK_RUN_ID) + +(h) TESTS · CI GATES + +pytest tests/ · asyncio_mode=auto · -m slow drills +• ruff line-length 100 · target py312 +• flag registry: undeclared read fails CI (0176) +• pairwise HIGH_IMPACT flag matrix in CI +• mutation-teeth + guardrail-eval as self-tests + +★ KEY FEEDBACK LOOPS + +ACT fail → task_escalations → next cycle one tier up +FLUSH: observe → drift assess → demote plan / lockdown +readiness ≥0.70 → auto-promote T0…T5 (earned trust) +≥3 sig failures → task-split; fragmentation → skill_proposal +crawl merge_rate / revert_rate → RUN auto-merge graduation + +★ SOURCE OF TRUTH + +SQLite state/chimera.db = KFM entities + transitions + + api_calls · mutations · task_escalations (WAL, v4) +mind/*.md: HEARTBEAT (cycle) · INBOX · CHRONICLE +Kuzu graph + FTS5 wiki = DERIVED, rebuildable (~95% skip) +cycle counter restored from HEARTBEAT.md, not the DB + +Repo: elementalcollision/chimera · entrypoint chimera = chimera.cli:main · one 9-phase cycle per chimera run (live loop in chimera/core/loop.py) · 439 files · 188 ADRs. +Grounded in a 12-agent CodeGraph map of the repo. Boxes name the primary module + real symbols; facts cite thresholds, env flags (CHIMERA_*) and ADR numbers. Derived recall (Kuzu / FTS5) is rebuildable; SQLite + mind/ are canonical. + \ No newline at end of file