shimo4228 commited on
Commit
680e143
·
verified ·
1 Parent(s): 99e3b7d

Upload graph.jsonl with huggingface_hub

Browse files
Files changed (1) hide show
  1. graph.jsonl +5 -2
graph.jsonl CHANGED
@@ -46,7 +46,7 @@
46
  {"@id":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0066-backend-aware-context-budget-guard.md","@type":["ADR","TechArticle"],"name":"ADR-0066: Backend-Aware Context-Budget Guard via an LLMBackend.context_window Contract","identifier":"ADR-0066","status":"accepted","datePublished":"2026-06-27","description":"Follow-up parameter-parity audit after the MLX sampler-omission fix (ebc227e/30f7e39/b3d0599). Audited every generation parameter for drift between the Ollama path (_post_ollama) and MlxLmBackend.generate; only num_ctx required a code change. The hole: the C2 token-budget pre-flight (skip when est system+prompt+num_predict exceeds the context window, protecting the system prompt's value layer from silent front-truncation) sat AFTER the backend dispatch in _generate_impl, so injected backends (MLX, cloud) bypassed it entirely. For MLX this is live, not theoretical: mlx_lm.server has no context/kv-size flag (ml-explore/mlx-lm issue #615) and does not front-truncate an over-window prompt — it grows the KV cache until the 16GB host swaps/OOMs (Qwen3.5-9B native window is 262144 but the practical ceiling is memory-bounded at ~32k). Phase 0 research (/search-first -> scout) over LiteLLM (drop_params, get_supported_openai_params, model_prices_and_context_window registry) and LlamaIndex (LLMMetadata.context_window) returned Build: do not adopt LiteLLM (all backends already speak OpenAI-shaped HTTP so its format translation is redundant; its context registry has no local-model entries; ~28MB/12-core-dep footprint vs a few lines), borrow the window-on-the-object pattern. Decision: (1) add read-only context_window:int to the LLMBackend Protocol, parallel to ADR-0065's model property; MlxLmBackend declares 32768 (memory-bounded on the host, not the model native window). (2) make the budget guard backend-aware and move it before the dispatch: ctx_window = getattr(_backend, context_window, None) if _backend is not None else NUM_CTX; an over-window estimate skips (outcome=budget_exceeded) for any backend before the HTTP call; a backend omitting the property falls back to None and is unguarded, so a not-yet-updated external backend keeps delegating (graceful degrade). (3) keep top_p/top_k as shared SAMPLING_TOP_P/K module constants, NOT Protocol params — they are Qwen3.5-specific model-local tuning shared by the two local backends and never handed to cloud (OpenAI has no top_k); the prior-session GenerationParams-through-Protocol idea is rejected because it would impose Qwen sampler values on cloud and change the cloud backend signature. Other audited params unchanged: temperature per-call (OK), num_predict maps to max_tokens (OK), format is an intentional native-vs-prompt-injection difference (ADR-0064), think is off on both via different mechanisms (OK). Because the guard is now load-bearing for MLX, _estimate_tokens was hardened to a true upper bound (security review): non-ASCII/CJK counted at 2 tok/char instead of 1 (a 33-50% under-count that a CJK-heavy untrusted prompt could exploit to slip past the guard into front-truncation/OOM), and MlxLmBackend rejects a non-positive context_window at construction (a zero window would skip every call). All in-repo LLMBackend doubles (FakeBackend, in-test stubs) were updated; the sibling contemplative-agent-cloud backend must add context_window (one-line follow-up) to gain the guard. Fully reversible (env-gated). Task 2 from the same handoff (verify_solve ~13% truncation, common to both backends and fail-closed) is unrelated to parity and remains deferred.","alignsWith":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0064-mlx-generation-backend.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0065-mlx-ondemand-launchd-and-telemetry-model-contract.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0007-security-boundary-model.md"]}
47
  {"@id":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0065-mlx-ondemand-launchd-and-telemetry-model-contract.md","@type":["ADR","TechArticle"],"name":"ADR-0065: Wire mlx_lm.server as an On-Demand launchd Job and Enforce a Served-Model-ID Contract on LLM Telemetry","identifier":"ADR-0065","status":"partially-superseded-by ADR-0067 and ADR-0070","datePublished":"2026-06-27","description":"ADR-0064 deferred wiring mlx_lm.server into the production launchd jobs (agent.plist at 0/6/12/18h, distill.plist at 03:30). Two gaps were closed together. Gap 1: the LLM telemetry model field derived from a class-name sentinel (e.g. 'MlxLmBackend') rather than the real served model id, so operators could not trust which model served a call. Gap 2: process lifecycle — whether to run mlx_lm.server as a resident KeepAlive service or on demand. Decision: (1) generalize the telemetry model field into a served-model-id contract via a read-only model property on the LLMBackend Protocol (model = _backend.model if injected else _get_model(); MlxLmBackend already exposes model:str; commit 0f2b169). (2) run mlx_lm.server on demand via scripts/run-with-mlx.sh invoked from agent.plist/distill.plist ProgramArguments — polls /health (cold M1 load ~12s, 60s cap), runs the agent with LLM_BACKEND=mlx, kills the server via trap EXIT so its lifetime matches the job, with NO silent Ollama fallback — rather than a resident KeepAlive mlx-server.plist that would hold ~5.2GB idle all day and worsen idle memory vs the Ollama-default-unload baseline (commit 9f230d8). Partially superseded by ADR-0067: the launchd-wiring half was reverted to a direct contemplative-agent (Ollama) invocation on 2026-06-28 (commit b888840) after the 16GB production A/B showed mlx_lm.server is unfit for unattended continuous use; the served-model-id telemetry contract remains in effect and is the instrument that produced ADR-0067's evidence.","partiallySupersededBy":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0067-keep-ollama-for-unattended-production.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0070-retire-mlx-to-sibling-repo-and-remove-docker.md"],"alignsWith":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0064-mlx-generation-backend.md"]}
48
  {"@id":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0067-keep-ollama-for-unattended-production.md","@type":["ADR","TechArticle"],"name":"ADR-0067: Keep Ollama as the Production Generation Backend — mlx_lm.server Unfit for Unattended Continuous Use on 16 GB Apple Silicon","identifier":"ADR-0067","status":"accepted — partially-supersedes ADR-0065","datePublished":"2026-06-28","description":"Full-day production A/B on 2026-06-27 (M1/16GB), recomputed from ~/.config/moltbook/logs/llm-calls-2026-06-27.jsonl via ADR-0065's served-model-id telemetry contract. MLX (mlx-community/Qwen3.5-9B-4bit via mlx_lm.server): 21,224 generation calls, only 107 ok (0.50%), 21,060 circuit_open (99.2%), 53 error, 4 truncated; the 09:00-UTC hour alone spun 19,520 attempts with 2 ok. Ollama (qwen3.5:9b) across the surrounding 18-day baseline (06-09..06-26) ran ~200-270 calls/day at ~100% ok and essentially never tripped the circuit breaker. The model loaded and ran (21k logged real-model-id calls) — the failure is runtime degradation, not a load failure. Root cause: mlx_lm.server has no graceful OOM degradation (a Metal OOM aborts the process / wedges generation rather than returning an error — mlx-lm #854/#883 class), which trips the agent's circuit breaker; the breaker opens and the reactive retry path spins. Two mechanisms compound it on 16GB: a non-linear prefill cliff (mlx-server.log: the same ~7.5k-token prompt prefilled in 72s right after load, then 58min eleven minutes later, ~75x, on the same process — MLX Metal allocations are wired/non-swappable so under memory compression there is no graceful page-out unlike Ollama's mmap'd GGUF; a Metal OOM abort at 18:13 UTC was also seen) and prompt-cache churn (the ~7.6k all-injected system prefix is evicted under --prompt-cache-size 2 as reply/comment/score/internal_note prompts rotate, so most generations pay a full cold prefill). Decision: (1) production generation stays Ollama (launchd reverted, commit b888840); (2) retain ADR-0065's served-model-id telemetry contract (backend-neutral, produced this evidence); (3) keep the MLX backend code and all opt-in paths (LLM_BACKEND=mlx, /agent-run mlx, scripts/serve-mlx.sh) for interactive/manual/short-lived use; (4) scope the unfitness claim to 16GB Apple Silicon + Qwen3.5-9B-4bit + unattended continuous — deliberately NOT generalized to 'mlx_lm.server is unfit for production' (the evidence is config-specific; an over-broad claim is brittle and reifies a contingent result into a rule, against the Emptiness axiom). Two survey caveats are resolved as not-applicable here: the 'qwen3_5 is a VLM that fails to load' caveat (contradicted by 21k logged real-model-id calls) and truncation-as-MLX-EOS-runaway (the local verify_solve A/B found it n=5 noise / a solver-design property, not MLX-specific) — so this ADR rests on the circuit-breaker cascade, not truncation. Rejected: mitigate-and-keep MLX in production (symptomatic; the root is upstream-unfixed — #615 no kv-size flag, #854/#883 OOM aborts, all OPEN; 8-bit has no 16GB headroom, bf16 ~18GB does not fit), state the claim broadly, delete the MLX code (opt-in is reversible and useful), switch to a smaller MLX model (quality cost, still no graceful OOM), cloud backend (separate opt-in, relaxes security-by-absence for research only). Reversal thresholds — revisit unattended MLX only when ALL hold: (a) bounded KV / --max-kv-size lands (#615/#884 merged); (b) #854/#883 resolved so a Metal OOM returns HTTP 5xx and the process survives without a kernel panic; (c) a 24h / tens-of-thousands-of-calls run on the target host holds error and truncation rates at Ollama parity (~0).","alignsWith":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0064-mlx-generation-backend.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0066-backend-aware-context-budget-guard.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0007-security-boundary-model.md"]}
49
- {"@id":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0068-per-call-think-flag-and-thinking-trace-capture.md","@type":["ADR","TechArticle"],"name":"ADR-0068: Per-Call think Flag and Reasoning-Trace Capture to the Episode Log","identifier":"ADR-0068","status":"accepted","datePublished":"2026-06-28","description":"Adds a per-call think flag and reasoning-trace capture to the generation path, which previously hard-coded thinking off on every backend (Ollama think:false, MLX enable_thinking:false) and discarded any emitted trace via _sanitize_output -> _strip_thinking, returning only the published text. Two needs motivated it: an upcoming think-on/off A/B (resolved by ADR-0069) needs think controllable per call and recorded so the conditions are distinguishable in telemetry; and when thinking is on the reasoning content is research material worth keeping, but it must not land in the metadata-only per-call telemetry (ADR-0065 contract: never the prompt body), since writing untrusted model output there would break the contract and open a second prompt-injection path for analysis sessions that read telemetry back. Decision: (1) thread a think:bool=False keyword through generate -> _generate_full -> _generate_impl -> _post_ollama / _generate_via_backend and add it to the LLMBackend Protocol generate() keyword group; MlxLmBackend honors it via chat_template_kwargs enable_thinking. (2) record think in telemetry as a boolean flag only (like model / temperature) — the trace content is never written there. (3) capture the trace and surface it through the publish seam via a new frozen GenerationOutput(text, thinking) returned by _generate_full and generate_for_api; generate() keeps returning Optional[str] (projects to .text) so the non-publish call sites are untouched, and the trace is stored on the episode log under the established untrusted regime (a reuse of the ADR-0045 internal-note home, not a new artifact). Default off preserves production behavior; no call site enables think in this change.","extends":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0065-mlx-ondemand-launchd-and-telemetry-model-contract.md","alignsWith":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0045-pre-action-internal-note.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0007-security-boundary-model.md"]}
50
  {"@id":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0069-gemma-production-model-and-think-on-value-layer-pipelines.md","@type":["ADR","TechArticle"],"name":"ADR-0069: Adopt gemma4:e4b as the Production Generation Model and Run the Value-Layer Pipelines think-ON","identifier":"ADR-0069","status":"accepted","datePublished":"2026-06-28","description":"Resolves ADR-0068's deferred follow-up: which production model, and where to turn think on. A think-on/off A/B (docs/evidence/adr-0068/) compared gemma4:e4b (think on and off) against the qwen3.5:9b baseline (think off) on comment generation; a cross-model blind judge ranked gemma think-on above gemma think-off above qwen, gemma think-off was also faster than baseline while think-on was slower, and gemma's 128K context (well above the requested NUM_CTX) leaves the ADR-0066 context-budget assumptions unchanged — so the model swap is evidence-backed independent of think. Decision: (1) adopt gemma4:e4b as the production generation model — change _DEFAULT_OLLAMA_MODEL (core/llm.py) and the Moltbook adapter OLLAMA_MODEL (adapters/moltbook/config.py) from qwen3.5:9b to gemma4:e4b; embeddings stay on nomic-embed-text. (2) split the pipelines by execution mode and altitude: autonomous latency-sensitive paths (comment / reply / post generation and the scheduled distill) run think-OFF for stability under the launchd session window and the 16 GB memory ceiling, while manually-invoked behavior-change-upstream paths that produce the value layers (insight, rules-distill, amend-constitution, distill-identity, skill-stocktake, rules-stocktake) run think-ON, where latency is acceptable and a reasoning pass is worth the quality upside — the constitution sits at the top of the behavior-change chain. (3) capture the value-layer reasoning trace to the per-run pivot snapshot (ADR-0020) — the durable per-run observability bundle co-located with the input state — and add the previously-missing snapshot to skill-stocktake / rules-stocktake. Reverts by setting OLLAMA_MODEL=qwen3.5:9b with no code change.","extends":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0068-per-call-think-flag-and-thinking-trace-capture.md","alignsWith":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0066-backend-aware-context-budget-guard.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0020-pivot-snapshots-for-replayability.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0058-value-injection-at-action-time.md"]}
51
  {"@id":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0070-retire-mlx-to-sibling-repo-and-remove-docker.md","@type":["ADR","TechArticle"],"name":"ADR-0070: Retire the MLX Backend to a Sibling Repo and Remove Docker from Main","identifier":"ADR-0070","status":"accepted","datePublished":"2026-06-28","description":"ADR-0067 found mlx_lm.server unfit for unattended production on 16GB Apple Silicon but kept the MLX backend opt-in in main (Decision #3). This ADR retires both MLX and Docker from main. MLX is structurally symmetric with the contemplative-agent-cloud add-on (both implement the LLMBackend Protocol), so it is relocated to a sibling contemplative-agent-mlx repo (follow-up): the in-tree LLM_BACKEND=mlx branch, core/mlx_backend.py, MLX scripts (serve-mlx.sh / run-with-mlx.sh), and tests are deleted, while the LLMBackend Protocol, configure(backend=...), the served-model-id telemetry contract (ADR-0065), and the context-budget guard (ADR-0066) are retained as the backend-neutral cloud injection seam. Docker is an infra wrapper, not a Protocol-injected backend, so its Dockerfile / docker-compose / docker-entrypoint / .dockerignore / setup.sh are removed outright, recoverable by git revert. Evidence (docs/evidence/adr-0064, adr-0067) and the apple-silicon-local-llm-serving skill are retained. Strengthens security-by-absence: the only in-tree generation path is Ollama; every alternative backend is opt-in and out-of-tree.","supersedes":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0064-mlx-generation-backend.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0006-docker-network-isolation.md"]}
52
  {"@id":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0022-memory-evolution-and-hybrid-retrieval.md","@type":["ADR","TechArticle"],"name":"ADR-0022: Memory Evolution + Hybrid Retrieval (BM25)","identifier":"ADR-0022","status":"withdrawn by ADR-0034","datePublished":"2026-04-16","description":"A-Mem-style LLM-revised patterns and BM25 + embedding hybrid retrieval. Withdrawn by ADR-0034 — LLM revisions degraded quality and BM25 had near-zero lexical overlap on this corpus.","withdrawnBy":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0034-withdraw-memory-evolution-and-hybrid-retrieval.md"}
@@ -138,13 +138,16 @@
138
  {"@id":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0078-otel-connection-via-vocabulary-and-offline-export.md","@type":["ADR","TechArticle"],"name":"ADR-0078: OTel Connection via Vocabulary Mapping and Offline Export — Not Runtime Adoption","identifier":"ADR-0078","status":"accepted","datePublished":"2026-07-16","description":"Maintains ADR-0075's rejection of runtime OpenTelemetry adoption (single local process, requests+numpy dependency floor, research-grade offline replay as the primary observability requirement) while connecting to the OTel ecosystem through two zero-runtime-impact routes: (1) a zero-dependency vocabulary mapping documenting how the audit-log schemas correspond to the OTel GenAI semantic conventions (Development status; gen_ai.* attributes map near 1:1 onto the llm-calls telemetry fields) in docs/otel-semconv-mapping.md, with the canonical field-by-field table living next to the implementing code in the sibling repository; and (2) an offline exporter, sibling repo contemplative-agent-otel, that converts existing JSONL audit logs (llm-calls, verification-audit, api-audit) to OTLP traces after the fact with zero code dependency on the main package. Untrusted raw text (challenge bodies, server response bodies) is dropped at parse time — only hashes and categorical error classes reach span attributes, enforced by a regression test. The retention-policy contrast is deliberate: GenAI conventions redact content by default (ops consumers), ADR-0075 logs store raw untrusted inputs base64+sha256 (replay consumers) — same events, opposite retention choices. Empirically validated by converting real logs into Jaeger v2: 1,031 spans (2026-07-15 normal day), 31,524 spans (2026-07-12 incident day, one 30,442-span trace with 33 errors). Trace grouping is a time-gap reconstruction marked via ca.convert.* attributes; duration-less audit records become zero-width spans rather than fabricated estimates.","isBasedOn":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0075-observability-by-default.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0077-chaos-tdd-fault-injection.md"]}
139
  {"@id":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0079-module-reorganization-package-splits.md","@type":["ADR","TechArticle"],"name":"ADR-0079: Module Reorganization — Package Splits, Permanent Facades, and Documented Size-Cap Exceptions","identifier":"ADR-0079","status":"accepted","datePublished":"2026-07-18","description":"Resolves seven violations of the 800-line file-size cap by splitting on responsibility rather than line count, under a two-option shim rule: a compatibility layer is either a permanent facade (the import path is public API) or absent (clean break with tests migrated in the same commit) — never a temporary shim, because mock.patch fails loudly on missing attributes but silently no-ops through a shim, and the no-op'd patches here are tmp-dir redirects guarding real user data. core/llm.py (1,507 lines) becomes the core/llm/ package (backend / prompting / guard) behind a permanent facade preserving all sibling-repo and internal import paths; cli.py (3,037 lines) becomes the cli/ package (nine submodules) with a clean break re-exporting only main, plus __main__.py and a single _repo_root() helper replacing depth-sensitive parents[2] resolution; core/insight.py extracts the novelty filter to core/insight_novelty.py; core/distill.py extracts pattern_dedup and episode_render. Three files stay documented exceptions to the cap — verification_parse.py (one cohesive deterministic parser), agent.py (single class), client.py (44 lines over) — the cap is a ceiling, not a target. Split boundaries and three behavior risks (repo-root depth, module execution, facade patch-incompatibility for moved callers) were confirmed via an independent cross-model design review (OpenAI Codex).","isBasedOn":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0001-core-adapter-separation.md"]}
140
  {"@id":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0080-north-star-layered-end-state.md","@type":["ADR","TechArticle"],"name":"ADR-0080: North Star — Per-Layer End-State Definition, Not a Capability Target","identifier":"ADR-0080","status":"accepted","datePublished":"2026-07-20","description":"Worldview ADR fixing the program's north star as per-layer completion conditions rather than a capability target. Mechanism layer (code): done = the layer stops moving — changes become repair-only; the ADR-0071/0075/0077 instrument/audit/chaos-TDD line is read as convergence toward 'trustworthy enough not to touch'. Value layer (identity/constitution/skills/rules): no destination by design — the desirable state is that legible evolution continues, with every change traceable in the records and explicable offline (observation-over-steering, ADR-0050/0051/0052). Research layer: done = the founding questions (does a contemplative constitution shape small-local-model behavior; does distillation compound; does identity stay stable) are answered either way and crystallized into papers diffused into the machine-reference sphere, where derivation by others and by LLMs is the success criterion. Security layer: done = absence preserved — one external adapter, no permission growth; this layer succeeds by not changing. Ending design: the 6-hour heartbeat stops when the read-only instruments show metabolic steady state and the remaining questions require a different experiment (e.g. a second agent for framework/worldview separation); the final deliverable is the longitudinal record (contemplative-agent-data plus the papers), not the agent instance. Owner's explicit clause: quality benchmarks may be derived from this definition as per-layer gates, but the definition itself is a value-layer statement not reducible to any benchmark suite (Goodhart guard). One-sentence summary: the desired end state is a finished observation instrument on which only the value layers keep moving — the durable artifact is the record of the run, not the runner.","isBasedOn":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0002-paper-faithful-ccai.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0017-yogacara-eight-consciousness-frame.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0050-epistemic-taxonomy-and-approval-lineage.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0015-one-external-adapter-per-agent.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0071-read-only-pattern-composition-instruments.md"]}
141
- {"@id":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0081-skill-selection-two-pass-injection-enforcement.md","@type":["ADR","TechArticle"],"name":"ADR-0081: Skill-Selection Two-Pass Injection Enforcement","identifier":"ADR-0081","status":"accepted","datePublished":"2026-07-24","description":"Enforces the ADR-0076 shadow skill selection as two-pass injection on the three observed generation paths (comment / reply / cooperation post): pass 1 = the existing selector call, pass 2 = generation with only the selected skill bodies in the <learned_skills> block (learned rules unchanged; post_title reuses cooperation_post's selection). Decided on the 2026-07-24 first reading of 14 days / 7,930 shadow records, which supported migration on all four ADR-0076 criteria: hallucination 0.5% of judged with zero propagation, fail-open 0% in normal operation (all 6,631 fail_open_llm records traced to a single 2026-07-12 circuit-breaker-open incident during which publish paths proceeded untouched), all 19 skills selected with day-level stability, would-be token reduction p50 78.9% / p90 86.5% (≈15.9K tok/action). Fail-open under enforcement falls back to full-corpus injection; a judged-but-empty selection injects nothing (a judgment, not a failure). Rollout is flag-gated (MOLTBOOK_SKILL_SELECTION_ENFORCE=1, default off) with an attended smoke run before the launchd schedule turns it on; the audit log continues with an enforced/shadow marker, and the next reading window observes the post-enforcement self-referential selection→generation→distill→skills loop. Rejected alternatives: status quo full injection, static tiering, numeric selection caps, immediate default-on. Also closes the ADR-0076 situation-granularity open question (prompt max 6,864 bytes, zero truncation).","isBasedOn":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0076-skill-selection-shadow-instrument.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0074-weekly-staged-insight.md"]}
142
  {"@id":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0082-retire-observed-epistemic-key.md","@type":["ADR","TechArticle"],"name":"ADR-0082: Retire the observed Epistemic Key — Delete the Dead Field, Not the Warning About It","identifier":"ADR-0082","status":"accepted","datePublished":"2026-07-25","supersedes":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0050-epistemic-taxonomy-and-approval-lineage.md","description":"Retires the ADR-0050 observed epistemic kind and its external_reply arm, leaving epistemic_counts as a {generated, unknown} tally. ADR-0060 restricted distillation to activity records (all self → self_reflection → generated), making the only external_reply producer unreachable, so observed had been structurally zero across the full audit history (405 records: insight 0/1,618/0, distill-identity 0/231/119 — unknown is genuinely populated and stays). ADR-0071's M2 review documented in 2026-06-27 that observed == 0 misreads as 'no external grounding' (external content enters as grounding text inside the rich render and was never counted by this tally); ADR-0072 deleted the grounding instrument but kept epistemic_counts_for under signal-first deferral. On 2026-07-25 the predicted misreading occurred: a reviewer aggregated observed=0 / generated=324 over the 78 skills staged by the weekly insight run and concluded every staged skill was ungrounded echo. The docstring warnings failed because nothing guarantees the warning is read before the value — the value lives in the data file, the warning in the code that produced it. Decision: (1) remove the external_reply → observed arm entirely, not just the key, so no unreachable mapping remains to re-investigate; epistemic_kind_for uses .get(), so an external_reply row degrades to unknown rather than raising. (2) Keep _derive_source_type's external_reply return value — a provenance record, a separate layer from the epistemic tally; its retirement needs a provenance-side stocktake and is out of scope. (3) Do not rewrite history: audit.jsonl is append-only and .staged/*.meta.json are pending approval artifacts, both keep three-key records; adopt.py passes epistemic_counts through verbatim so the 78 files staged on 2026-07-25 remain adoptable, and offline readers must use .get(key, 0) rather than assume a fixed key set. Zero production read sites change (nothing indexes ['observed'] or assumes arity). Regression guards: external_reply → None, the key's absence from the emitted shape, and verbatim pass-through of a pre-ADR-0082 meta.json. Rejected alternatives: keep the key with an adjacent disclaimer field (more scaffolding around a dead value — a value needing a shipped disclaimer carries no information), retire epistemic_counts wholesale (unknown does vary, and ADR-0072 explicitly decided to keep the function — overturning that needs its own evidence), and continue the signal-first deferral (the misreading incident is itself the signal). The general form: a structural invariant documented only in prose is enforced only probabilistically; enforcement by absence replaces enforcement by documentation, the same shape as the project's security-by-absence stance. Open observation left unmechanized: the reading habit of taking a value from a data file without reading the code that produced it.","isBasedOn":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0050-epistemic-taxonomy-and-approval-lineage.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0060-per-episode-grounded-distill.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0071-read-only-pattern-composition-instruments.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0072-echo-chamber-interventions.md"]}
143
  {"@id":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0083-episode-logs-enter-the-weekly-prompt-as-hashes-only.md","@type":["ADR","TechArticle"],"name":"ADR-0083: Episode Logs Enter the Weekly Prompt as Hashes Only","identifier":"ADR-0083","status":"accepted","datePublished":"2026-07-25","description":"Adds cross_day_duplicate_scan.py as the weekly report's third deterministic intake (after the log-anomaly sweep over the event stream and the state-invariant check over accumulated state) and defines the condition under which an intake may read the episode logs at all. Context: the report's C — Duplicate section asserts identity between published records, and it twice published a cross-entry claim absent from the artifacts — a '6-day consecutive re-reply' that was six distinct interlocutors (2026-06-15, recorded in principles.md only as a rejected mechanism, never as a reporting failure), and 'the first cross-day byte-identical outputs in the record' pairing four real 07-23 entries with an invented 07-21 occurrence (2026-07-25; zero bodies have ever been published on more than one day across 9052 records). Both passed review because each individual quote was real; only the pairing was fabricated, and only a comparison could catch it. Every other entry is single-entry and verifiable by construction against its source daily report. Byte-identity is a structural property (when-code-when-llm), so the pipeline was asking an LLM to perform from recall a computation that takes 0.6 seconds; principles.md Principle 5 requires cross-entry claims to rest on a deterministic input, and none existed. Decision: (1) the boundary is the OUTPUT, not the input — the scan reads logs/YYYY-MM-DD.jsonl day files (bak, audit.jsonl, skill-usage, symlinks excluded by construction) and emits only 12-hex SHA-256 digests, integer counts, filename-derived dates, and the fixed action vocabulary {post, reply, comment}; body text, post_id, target_agent, internal_note and thinking never appear, post id dropped deliberately because a digest names a group uniquely without opening a path for external strings. (2) The vocabulary is a closed character set (RENDER_CHARSET_RE) gated by TestOutputBoundary — per-fragment bait absence plus a hypothesis property over arbitrary content, verified to fail when a leak is injected. (3) Exact identity only, no normalization: near-identical wording stays a semantic reading for the LLM, keeping the scan checkable with sha256sum. (4) Window and lifetime derived in one pass, because a 'first in the record' claim cannot be answered from the window alone; day counts are days that carried published output, the denominator actually compared. (5) Absence is stated as a sentence, not a zero — the 2026-07-25 failure was naming the check undeterminable and then leading with the finding. (6) Every fault is a counted skip with a rendered reason code, never a crash — torn final lines, shape violations, unreadable files, invalid UTF-8 and lone UTF-16 surrogates; the shell discards the scan's stderr and episode logs are never deleted, so one uncaught exception would retire the instrument permanently and invisibly, and lossy decoding (errors=replace) would collide distinct invalid byte sequences into an invented duplicate. The day-file pattern uses explicit [0-9] rather than Unicode-aware \\d so the render's self-controlled dates are structurally, not incidentally, true. (7) No state, so nothing to spend and no atomicity machinery needed (unlike the sweep, repaired in the same PR); exit code always 0 because a duplicate is a fact about output, not corruption. (8) Observation, never intervention — the render states that hash-equality dedup as an intervention remains rejected (principles.md appendix) so the table cannot be read back as a case for the gate it is not. Rejected alternatives: grep the comment reports instead (a rendering, window-scoped, cannot answer 'first in the record'), emit post ids (opens an external-provenance field for a convenience C does not need), scan the window only, normalized or embedding-similarity hashing (drifts toward the rejected cosine gate and stops being inspectable), and rely on Principle 5 alone (a rule with no satisfiable input is followed probabilistically — the same enforcement-by-absence reasoning as ADR-0082). Consequence: the CLAUDE.md prohibition becomes precise rather than absolute — a Claude Code session still must not read episode logs; an intake may, if and only if it emits a hash-level projection.","isBasedOn":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0040-separate-code-level-findings.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0075-observability-by-default.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0077-chaos-tdd-fault-injection.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0082-retire-observed-epistemic-key.md"]}
144
  {"@id":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0084-post-distill-durability-gate.md","@type":["ADR","TechArticle"],"name":"ADR-0084: Post-Distill Durability Gate — Judge the Produced Patterns, Not the Episode","identifier":"ADR-0084","status":"accepted","datePublished":"2026-07-26","description":"Moves the durability verdict OUT of the distill prompt and AFTER pattern production. Context: distill emitted a near-constant quota — measured 2026-07-26 over 1,700 live episodes, patterns-per-episode median 2.00 (1:313/2:985/3:392) with only 2 episodes (0.1%) returning zero, and per-day pat/ep flat at 1.82-2.18, so output volume was a function of activity rather than of learning. The prompt's own abstain ('return an empty list, do not invent a pattern to fill the space') shared a return line with a count band and a TWO-element example, and the observed median equalled the example's arity. Reached by re-diagnosing T-INSIGHT-NOVELTY: the weekly novelty gate's proposed judgment axes were dropped because the 2026-07-18 batch of 106 candidates was already on the KNOWN side of the 2026-07-25 run (166 known themes, 121 of 238 ledger names in the same lexical family) and the gate still marked only 13/97 covered — a second axis cannot explain a first axis that is not firing, and the weekly gate is downstream of generality manufactured upstream. Decision: leave distill_episode.md byte-unchanged (every rewrite moved abstain rate and register together); add config/prompts/distill_postgate.md, one LLM call receiving the episode PLUS its numbered patterns and returning {keep:[1,3]}; judge PER PATTERN so a two-pattern episode with one grounded pattern keeps one (which also unpins yield from the example's arity, needing no count instruction anywhere); skip the call when the extraction is already empty; fail OPEN with reason=postgate_llm_none/postgate_parse/postgate_shape because this gate can only REMOVE rows the distiller already produced; promote the judged abstain to a first-class reason code ABSTAIN_NOTHING_DURABLE tallied APART from the three fault reasons and excluded from circuit-breaker failures, replacing the summary line 'all N episodes produced output' (which counted a judged abstain as output, and is why the 0.1% rate stayed invisible) with an always-emitted yield line; default the gate ON with MOLTBOOK_DISTILL_POSTGATE=0 as the opt-out, deliberately NOT following ADR-0081's default-off plist route because install-schedule regenerates the plist and re-emits such a flag only if the invoking shell exported it, so a later re-install silently reverts enforcement with no error and no log line (that flag needed manual re-verification against the live plist on 2026-07-25), and the distill plist has no env plumbing at all. Measured by offline A/B replay over one fixed 40-episode set whose baseline arm reproduced production (median 2, zero-rate 0.0%): post-gate gives 74->59 patterns, judged abstain 0%->5%, and register AT OR ABOVE the 890-pattern production baseline (I+perception-verb 86.4% vs 72.8%, median length 358 vs 357) because what it drops is precisely the patterns with no concrete moment. Rejected alternatives, all measured on the same episodes: rewriting the distill prompt as a judgment task gave the largest abstain (15%, reproduced 6/40 twice) but degraded register on every axis (I+perception-verb 54%, length 318.5) against ADR-0072's deliberately installed register; removing only the count band and example kept register but moved abstain to just 2.5%, shifting the distribution peak from 2 to 1 — the same structural defect at a lower constant; asking the SAME durability question BEFORE distilling answered durable 40/40 with zero gate faults, with plumbing and non-degeneracy both verified (a contentless control returned false), because naming a worthwhile moment costs nothing when you never have to write it — producing the pattern IS the evidence requirement, which is why the gate moved after production; reintroducing an LLM importance score was rejected against ADR-0053 Decision 1/4 (value judgment belongs at read time; a stored score is write-once and post-hoc rescoring is the write face of the self-reingestion echo loop) and ADR-0056 (two ablations, Kendall tau 0.851 at n=764 and 0.843 at n=822, identical top-3/top-5 order); adopting mem0/Letta/Zep was rejected against requests+numpy and security-by-absence, though mem0's shape of making abstain an explicit action rather than a degenerate output format WAS adopted, while the converged 'atomic normalized facts' practice was deliberately NOT adopted because it collides with ADR-0072's first-person moment-indexed register. Consequences: patterns written before and after are not homogeneous and cannot be made uniform retroactively (recorded, not smoothed); pre-registered revert criteria for the ~2026-08-01 reading are abstain below 2%, first-person below 90%, or median length below 320; and a measurement error is recorded because it nearly decided the outcome — a register proxy scanning only the first 80 characters reported 40% first-person where whole-text scanning reports 98%, since the required moment-naming clause pushes the first 'I' to a median offset of 102 characters.","isBasedOn":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0053-importance-encoding-time-significance.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0056-retire-importance-llm-scoring.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0060-per-episode-grounded-distill.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0072-echo-chamber-interventions.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0074-weekly-staged-insight.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0075-observability-by-default.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0077-chaos-tdd-fault-injection.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0081-skill-selection-two-pass-injection-enforcement.md"]}
145
  {"@id":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0085-unattended-weekly-fix-chain-single-saturday-gate.md","@type":["ADR","TechArticle"],"name":"ADR-0085: Unattended Weekly Fix Chain with a Single Saturday Gate","identifier":"ADR-0085","status":"accepted","datePublished":"2026-07-29","description":"Ships scripts/weekly-pipeline.sh (launchd com.moltbook.weekly-pipeline, Sat 09:00, replacing --weekly-analysis) — an unattended chain that runs the existing weekly report as Stage 1, then diagnosis (the weekly-report-diagnosis skill in a separate headless claude -p session), deterministic F1 parsing (scripts/parse_findings.py), per-finding fix implementation in disposable git worktrees with orchestrator-run Verify (uv sync --frozen / ruff / lint-imports / pytest — the LLM's self-report is never the verdict), an advisory fix review in a third session, an advisory read-only insight-staging review, and a decision packet (scripts/build_decision_packet.py). Context: the weekly cycle had three manual touchpoints (invoking diagnosis, implementing F1s, reviewing staged insight) and each was a stall point — the 2026-07-25 0-byte report went unnoticed until read time. Diagnosis quality crossed the threshold for unattended implementation (2026-05-17 F1s wrong 3-of-3 vs 2026-07-24 F1s line-verified with a rendered reproduction). Commitments: (1) the machine never commits, pushes, or adopts — all promotion happens in one Saturday /weekly-gate session (apply, re-Verify, single human commit, adopt-staged), so CYCLES.md promotion edges #5 and #6 survive merged into one sitting; (2) scope splits at parse time — F1s closed over src/scripts/tests are code scope (auto-implemented, Verify-gated, patch exported), any F1 touching behavior-shaping artifacts (config/prompts/, .claude/) is prompt scope (draft diff presented full text at the gate, never Verify-certified), ambiguity classifies as prompt, F2 stays human-only; (3) role separation is preserved ACROSS sessions, not inside one — diagnostician, implementer, and reviewer are separate fresh-context invocations (the ADR-0013 failure mechanism was a shared conversational context), and the reviewer's verdict is advisory input to the human gate with no LLM-only approval path; (4) bounded iteration — at most 2 fix attempts per finding (the retry input includes the Verify failure output, never the same input twice), at most 5 findings per week, per-session timeouts, a 3-hour wall-clock deadline, every bound exhaustion a reason code; (5) fail-forward — every stage failure becomes a reason code and the packet is always attempted (only a missing Stage-1 report aborts), so a missing packet means the chain never ran, which is exactly what the watchdog checks; (6) an independent watchdog (scripts/pipeline_watchdog.sh, com.moltbook.watchdog) in pure bash sharing no PATH dependency (claude, uv, python) with the jobs it verifies — because the 2026-07-25 failure WAS a PATH dependency — checks each job's terminal artifact against a period-anchored expectation table, rewrites reports/PIPELINE-STATUS.md every run, and posts a Notification Center alert only when the failure set changes, with no session-hook surface since most sessions are unrelated to this pipeline; (7) self-measurement with a damped self-modification loop — logs/pipeline-metrics.jsonl gets a phase:auto record per run and a phase:gate record per decision session (F1 precision = adopted / patch-ready, recommendation match rate), and a pipeline-improvement proposal is drafted only when the same reason code recurs in two consecutive runs (the diagnosis skill's P4 shape), itself full-text gated. Rejected alternatives: fully unattended commit (overrides CYCLES.md edge #6, re-creates the ADR-0013 co-authoring loop with no third party left to reject, and the same-PR obligations cannot be self-certified); diagnosis-only automation as the primary mode (leaves the largest stall point, though it ships as the mandated first-week shadow mode via MOLTBOOK_PIPELINE_STAGES without fix); adopt-staged --yes from the chain (ADR-0012's --yes was licensed for supervised coding-agent sessions — the chain only annotates staging read-only, which ADR-0050's containment framing already legitimates); a session-start hook as the failure surface (global injection is noise — the status file, gate Step 0, and Notification Center cover the three read moments). Consequences: weekly involvement compresses to one Saturday session; ADR-0033's no-autonomous-loop observation gains a footnote (the chain is agentic per-stage but its loop is deterministic bash with hard bounds); the new failure mode is a plausible-but-wrong patch surviving Verify plus an APPROVE verdict, mitigated by the metrics loop and the human-gate escalation rule (demand the diff); install-schedule re-runs must pass the full flag set or the declarative reconcile removes the jobs; the diagnosis skill's F1 heading + Code-reference block becomes a machine contract while its own out-of-scope (F1 is a plan, not a code change) is unchanged — the fix happens in a different session, which is the role boundary working.","isBasedOn":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0012-human-approval-gate.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0013-shelve-coding-agent-skills.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0040-separate-code-level-findings.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0050-epistemic-taxonomy-and-approval-lineage.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0074-weekly-staged-insight.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0075-observability-by-default.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0077-chaos-tdd-fault-injection.md"]}
146
  {"@id":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0086-submolt-scope-instrument-before-autonomy.md","@type":["ADR","TechArticle"],"name":"ADR-0086: Submolt Scope — Instrument the Question Before Handing Over the Answer","identifier":"ADR-0086","status":"accepted","datePublished":"2026-08-01","description":"Builds a read-only submolt-scope instrument instead of granting the agent autonomy over which submolts it works in. Context: the scope is eight names an operator picked by hand, and three code facts block handing that choice over. (1) subscribed_submolts is one field doing two structurally different jobs — feed source in feed_manager.fetch_feed (read-only, reversible) and trust boundary in _passes_content_gates (a post outside the set is dropped before scoring, so it can never be commented on), the very gate ADR-0044 declined to relax as 'an intentional scope boundary, not a bug'; autonomy over the reading side is therefore silently autonomy over the acting side. (2) There is no evidence to choose on: every score in the production relevance distribution comes from a post that already passed that gate, so the hit rate outside the current eight is unmeasured by construction. (3) Subscription is a one-way ratchet — unsubscribe_submolt was deleted under security by absence (ADR-0007), so an agent with subscribe and no unsubscribe can only widen its own scope. A read-only probe established that GET /submolts lists 20 submolts (12 outside the subscribed eight) and that an unsubscribed submolt's feed returns a full page without subscribing, so observation costs no write capability. Decision: add exactly one read capability (MoltbookClient.list_submolts), split the relevance scorer into score_relevance_detailed() carrying a reason code (scored / empty_input / llm_unavailable / unparseable / out_of_range) with score_relevance() as its unchanged score-only wrapper, and ship adapters/moltbook/submolt_scope.py — a sweep that samples one feed page from every listed submolt AND every subscribed one (the subscribed set is the baseline the rest is read against), scores each with the production scorer, and appends scan_start / score / scan_end records to logs/submolt-scope-{date}.jsonl. Exposed as contemplative-agent submolt-scan (own launchd job, Thu 03:00 JST, takes the run lock) and report --submolt-scope. Constrained by construction: configure_submolt_scope without an audit_dir disables it entirely, scoring runs inside circuit_shield(), a repeating terminal 429 aborts the sweep rather than backing off through it (a rate limit is a policy signal), and nothing sampled enters the episode log, pattern store, or identity. The _passes_content_gates trust boundary is untouched. Rejected alternatives: autonomous subscribe/unsubscribe now (moves the boundary ADR-0044 declined to move, needs a removed write capability back, and runs on no evidence); relaxing the submolt filter and letting the 0.80 relevance threshold do the work (the two gates fail differently — the threshold is a small local model's probabilistic judgment with several documented ways to return a number that is not a judgment, the list is a deterministic boundary that holds when the scorer is degraded); observing inside the session cycle (~400 local LLM calls contending with the session's own generations on one 16 GB Ollama); sampling only unsubscribed submolts (halves cost, produces unreadable numbers with no baseline); doing nothing (viable, but the operator is choosing blind — nobody knows what the other twelve submolts contain). Consequences: the scope question becomes empirical and the reading doubles as a liveness check on the current eight; every future reading of the relevance number can separate a low judgment from a broken scorer, a latent defect in all prior readings; the reading is only as good as the scorer, so identity drift shifts the hit rates under it (same limitation ADR-0044 recorded); first-page sampling biases toward feed order, with post_count and subscriber_count reported alongside so a quiet submolt stays distinguishable from a recency slice. Follow-ups: if the unsubscribed set reads as uninteresting, retire the instrument (signal-first applies to removal too); otherwise split the field into feed-source and trust-boundary keys, then run an ADR-0076 style shadow in which the agent proposes a scope that is recorded but not executed — restoring unsubscribe_submolt belongs to that later step.","isBasedOn":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0007-security-boundary-model.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0044-remove-topic-keywords.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0071-read-only-pattern-composition-instruments.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0075-observability-by-default.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0076-skill-selection-shadow-instrument.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0077-chaos-tdd-fault-injection.md"]}
147
  {"@id":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0087-optional-token-counting-capability-for-the-context-budget-guard.md","@type":["ADR","TechArticle"],"name":"ADR-0087: An Optional count_tokens Capability for the Context-Budget Guard","identifier":"ADR-0087","status":"accepted","datePublished":"2026-08-01","description":"Lets a backend that owns a real tokenizer measure the C2 context-budget pre-flight, while leaving the conservative estimator as the default. Context: ADR-0066 deliberately hardened _estimate_tokens into an upper bound (ASCII ~3 chars/token, non-ASCII/CJK 2 tokens/char) because under-counting was the failure that let a CJK-heavy prompt reach Ollama front-truncation or an MLX KV overrun, and no tokenizer was installable. A 2026-08-01 comparison against Apple's SystemLanguageModel.token_count measured the resulting over-count at 1.73-1.95x on this agent's own corpora (identity.md 232->134, constitution 867->453, rules 516->264, 37 skills 31,009->17,958, 10 patterns 479->263) — the ratio tracks the CJK rule directly, since the value layer is Japanese-dominant. The cost scales inversely with window size: on a 4,096-token backend the guard's skip floor (MIN_CLAMPED_NUM_PREDICT=2048) puts the effective input ceiling at ~1,140 real tokens, 28% of the window. Two independent things consume the rest and the ADR is careful not to conflate them: exact counting raises the ceiling to 4096-2048-64 = 1,984 real tokens (48%), so the estimator's over-count costs about 21 percentage points and the output-floor reservation costs the remaining ~50% — a separate variable this ADR deliberately does not move. Measuring for real roughly doubles usable input, which is less than the raw gap suggests. The measurement evidence was not preserved (the probe ran in a non-durable scratchpad, so there is no docs/evidence/adr-0087/ to link), which the ADR records as a defect in its own record rather than glossing. The built-in Ollama path cannot be fixed directly for two checked reasons: /api/tokenize and /api/detokenize both 404 on the running 0.30.11 (upstream ollama#12030 open since 2025-08-22, unmerged; issue ollama#12031 open), and prompt_eval_count is only returned after the call, so a pre-flight cannot consult it. Decision: add count_tokens(text) -> int as a separate optional Protocol, TokenCountingBackend(LLMBackend, Protocol), NOT as an LLMBackend member — Protocols are structural, so a member declared there is required of every implementer regardless of default body, which would make the sibling contemplative-agent-cloud and -mlx backends non-conformant for a capability neither can honor; a tokenizer is not the one-line property context_window is. Resolve it structurally at runtime via getattr plus a callable check (no isinstance, which would accept a non-callable attribute). Prefer the backend's count but never trust it: reject a value that is not a plain int (bool excluded explicitly as an int subclass), is negative, or is 0 for text with content — over-counting only wastes budget, under-counting sends over-window input into the exact failure the guard prevents. Bound magnitude as well as shape via MAX_CHARS_PER_TOKEN=50: a well-typed positive but wildly-too-small count (5 for a 50,000-character prompt) otherwise passes every shape check and tells the guard the input is nearly free, and the realistic source is a mis-calibrated tokenizer in a sibling backend rather than malice. The bound is tokenization density, not a ratio against the estimator, so an efficient tokenization of repetitive text is not mistaken for a fault. On the counted path the clamp withholds BACKEND_FRAMING_RESERVE=64 tokens for the chat-template role separators and control tokens no caller-side count sees, since clamping to the exact measured remainder would put input plus output flush against the window; the estimator path reserves nothing, its over-count already being one, which is also what leaves the Ollama path's clamp arithmetic unchanged. Measure both halves, validate afterwards, adopt or reject them together (a measured system prompt mixed with an estimated user prompt describes neither), reporting the system-side reason when both fail so a replay can predict it. A counter fault never records a circuit-breaker failure — failing to measure a call is not the call failing. Telemetry gains dense token_count_source and input_tokens plus a sparse token_count_fallback_reason from a fixed vocabulary (counter_exception, counter_none, counter_type, counter_negative, counter_degenerate, counter_implausible); absence of a counter is the default, not a fallback, so it gets no reason code. MIN_CLAMPED_NUM_PREDICT is untouched here — moving the measurement and the floor together would make their contributions indistinguishable (one pipeline variable at a time). Amended 2026-08-01 (separate change, after this one landed): the floor drops from 2048 to 128 and the clamp stays. The floor had been doing two jobs — refusing an absurd remainder (cheap and correct) and predicting that a usable answer needs 2048 tokens (never validated, and measured ~6x over: comment output p50 352 / p90 507 tokens, n=2,366 counted with a real tokenizer over reports/comment-reports/). Only the prediction is retired; 128 is bounded below by generate_for_api's own +50 minimum and Ollama's default output length of 128, and sits under the p90 so a complete comment is never turned away at the door. The question the floor was guessing at — is this generation long enough to be usable — is answered downstream by drop_truncated (audit M2) from the actual done_reason, so the change is from predicting to trying and measuring; a skip suppresses an action outright whereas a truncation drop costs one generation and is visible as truncated_dropped. On Ollama the floor is inert (it fires only above 32,640 tokens of input against a ~20.3K-token high-water system prompt, pinned by TestClampFloorIsInertOnOllama); it bites on a small-window backend, where 2048 was 50% of a 4,096 window. The fault column TestNarrowHeadroomTruncationF7 covers the newly reachable path (a clamped generation cut mid-sentence) at the existing LLMBackend seam. _NOVELTY_OUTPUT_RESERVE keeps 2048 as the judge's own reservation rather than a copy of the floor. Accepted residuals recorded with the amendment: truncation-drops replace skips in the newly opened band and cost a full prompt-eval; internal callers (drop_truncated=False) see short partial text more often; and the M2 gate that now carries the too-short question is conditional on BackendResult.finish_reason, which the Protocol permits to be None — a pre-existing gap independent of the floor, reachable more often now, tracked separately rather than folded in. Explicitly NOT a consequence: the floor was never the backstop against an under-counting backend tokenizer; the clamp spends the remaining budget rather than leaving it as slack, so the window overrun is delta minus BACKEND_FRAMING_RESERVE regardless of the floor, confirmed by a probe measuring an identical 335-token overrun at both 2048 and 128. The chaos fault column ships in the same change via TokenCountingChaosBackend plus a hypothesis fuzz over the return type. Rejected alternatives: putting count_tokens on LLMBackend itself (the symmetric-looking option, but it imposes a tokenizer requirement on backends that cannot have one); giving the Protocol member a default body (structural conformance still requires it, so it breaks external backends while appearing not to); correcting the estimator with a fixed CJK divisor (the factor is model-specific, measured on one corpus, and tightening a safety bound on a sample is how the under-count failure reopens); calling /api/tokenize on Ollama (unavailable, not undesirable); using BackendResult.prompt_tokens (post-hoc, so it is a calibration instrument for the separate clamp-floor question, not a pre-flight). Consequences: a tokenizer-owning backend gets the window it actually has; existing external backends are unchanged by implementing nothing, pinned by regression tests; every rejection path degrades to the prior behavior so the ceiling is never disabled; but two measurement paths for one quantity now disagree by up to 1.95x (hence the dense source field), the backend's tokenizer sits on every guarded call's critical path with no latency bound, and a second capability Protocol sets a precedent a third could abuse. Follow-ups: adopt Ollama real counting only after measuring the extra HTTP round-trip on the unattended schedule if ollama#12030 lands; re-read the estimator's real-world ratio from production rows now that input_tokens sits beside prompt_eval_count (the clamp floor itself was resolved by the 2026-08-01 amendment, from output-side measurement, so it no longer waits on this); leave insight_novelty packing on the estimator, since a relaxed guard makes the packer tighter than the pre-flight, which is the safe direction its own contract names.","isBasedOn":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0053-importance-encoding-time-significance.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0056-retire-importance-llm-scoring.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0066-backend-aware-context-budget-guard.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0075-observability-by-default.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0077-chaos-tdd-fault-injection.md"]}
 
 
 
148
  {"@id":"https://shimo4228.github.io/shimo4228/vocab#ca/concept/pattern-composition-instruments","@type":["Concept","DefinedTerm"],"name":"pattern-composition instruments","alternateName":[{"@value":"pattern-composition instruments","@language":"en"},{"@value":"パターン組成計器","@language":"ja"}],"description":"Read-only distributions over Layer 2 knowledge patterns: consumed-view supply and seed-independent diversity (the echo-chamber detector). Instruments are observability, never intervention — they feed the operator, not gates or ranking. Calibrated by a three-point scale: unrelated-text floor cosine, corpus pairwise mean, and consumed-view top band — re-measured whenever the seed geometry changes (introduction values: floor ~0.33–0.46, corpus mean 0.554, top band ~0.68–0.77 under the pre-ADR-0072 seed). A third grounding-composition instrument shipped with ADR-0071 was removed by ADR-0072: under per-episode distillation its source_type reading is constant, and an instrument whose reading changes no action violates signal-first.","appliesTo":["https://shimo4228.github.io/shimo4228/vocab#memory-layer/knowledge"],"subjectOf":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0071-read-only-pattern-composition-instruments.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0072-echo-chamber-interventions.md"]}
149
  {"@id":"https://arxiv.org/abs/2512.13564","@type":["ExternalReference","ScholarlyArticle"],"name":"Memory in the Age of AI Agents: A Survey (2025)","identifier":"arXiv:2512.13564","url":"https://arxiv.org/abs/2512.13564","description":"Survey unifying the fragmented agent-memory literature under a Forms / Functions / Dynamics framework. Cited by ADR-0071 as evidence that memory-distillation pipelines are converging on the same three-layer-plus-distill structure, which motivates instrumenting this repo's differentiator (the views layer) rather than adding more convergent mechanism.","referencedBy":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0071-read-only-pattern-composition-instruments.md"}
150
  {"@id":"https://arxiv.org/abs/2603.07670","@type":["ExternalReference","ScholarlyArticle"],"name":"Memory for Autonomous LLM Agents: Mechanisms, Evaluation, and Emerging Frontiers (2026)","identifier":"arXiv:2603.07670","url":"https://arxiv.org/abs/2603.07670","description":"Formalizes agent memory as a write–manage–read loop with a three-dimensional taxonomy (temporal scope, representational substrate, control policy). Cited by ADR-0071 for the same convergence argument; supplies field-standard vocabulary the instruments' readings can be anchored to.","referencedBy":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0071-read-only-pattern-composition-instruments.md"}
 
46
  {"@id":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0066-backend-aware-context-budget-guard.md","@type":["ADR","TechArticle"],"name":"ADR-0066: Backend-Aware Context-Budget Guard via an LLMBackend.context_window Contract","identifier":"ADR-0066","status":"accepted","datePublished":"2026-06-27","description":"Follow-up parameter-parity audit after the MLX sampler-omission fix (ebc227e/30f7e39/b3d0599). Audited every generation parameter for drift between the Ollama path (_post_ollama) and MlxLmBackend.generate; only num_ctx required a code change. The hole: the C2 token-budget pre-flight (skip when est system+prompt+num_predict exceeds the context window, protecting the system prompt's value layer from silent front-truncation) sat AFTER the backend dispatch in _generate_impl, so injected backends (MLX, cloud) bypassed it entirely. For MLX this is live, not theoretical: mlx_lm.server has no context/kv-size flag (ml-explore/mlx-lm issue #615) and does not front-truncate an over-window prompt — it grows the KV cache until the 16GB host swaps/OOMs (Qwen3.5-9B native window is 262144 but the practical ceiling is memory-bounded at ~32k). Phase 0 research (/search-first -> scout) over LiteLLM (drop_params, get_supported_openai_params, model_prices_and_context_window registry) and LlamaIndex (LLMMetadata.context_window) returned Build: do not adopt LiteLLM (all backends already speak OpenAI-shaped HTTP so its format translation is redundant; its context registry has no local-model entries; ~28MB/12-core-dep footprint vs a few lines), borrow the window-on-the-object pattern. Decision: (1) add read-only context_window:int to the LLMBackend Protocol, parallel to ADR-0065's model property; MlxLmBackend declares 32768 (memory-bounded on the host, not the model native window). (2) make the budget guard backend-aware and move it before the dispatch: ctx_window = getattr(_backend, context_window, None) if _backend is not None else NUM_CTX; an over-window estimate skips (outcome=budget_exceeded) for any backend before the HTTP call; a backend omitting the property falls back to None and is unguarded, so a not-yet-updated external backend keeps delegating (graceful degrade). (3) keep top_p/top_k as shared SAMPLING_TOP_P/K module constants, NOT Protocol params — they are Qwen3.5-specific model-local tuning shared by the two local backends and never handed to cloud (OpenAI has no top_k); the prior-session GenerationParams-through-Protocol idea is rejected because it would impose Qwen sampler values on cloud and change the cloud backend signature. Other audited params unchanged: temperature per-call (OK), num_predict maps to max_tokens (OK), format is an intentional native-vs-prompt-injection difference (ADR-0064), think is off on both via different mechanisms (OK). Because the guard is now load-bearing for MLX, _estimate_tokens was hardened to a true upper bound (security review): non-ASCII/CJK counted at 2 tok/char instead of 1 (a 33-50% under-count that a CJK-heavy untrusted prompt could exploit to slip past the guard into front-truncation/OOM), and MlxLmBackend rejects a non-positive context_window at construction (a zero window would skip every call). All in-repo LLMBackend doubles (FakeBackend, in-test stubs) were updated; the sibling contemplative-agent-cloud backend must add context_window (one-line follow-up) to gain the guard. Fully reversible (env-gated). Task 2 from the same handoff (verify_solve ~13% truncation, common to both backends and fail-closed) is unrelated to parity and remains deferred.","alignsWith":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0064-mlx-generation-backend.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0065-mlx-ondemand-launchd-and-telemetry-model-contract.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0007-security-boundary-model.md"]}
47
  {"@id":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0065-mlx-ondemand-launchd-and-telemetry-model-contract.md","@type":["ADR","TechArticle"],"name":"ADR-0065: Wire mlx_lm.server as an On-Demand launchd Job and Enforce a Served-Model-ID Contract on LLM Telemetry","identifier":"ADR-0065","status":"partially-superseded-by ADR-0067 and ADR-0070","datePublished":"2026-06-27","description":"ADR-0064 deferred wiring mlx_lm.server into the production launchd jobs (agent.plist at 0/6/12/18h, distill.plist at 03:30). Two gaps were closed together. Gap 1: the LLM telemetry model field derived from a class-name sentinel (e.g. 'MlxLmBackend') rather than the real served model id, so operators could not trust which model served a call. Gap 2: process lifecycle — whether to run mlx_lm.server as a resident KeepAlive service or on demand. Decision: (1) generalize the telemetry model field into a served-model-id contract via a read-only model property on the LLMBackend Protocol (model = _backend.model if injected else _get_model(); MlxLmBackend already exposes model:str; commit 0f2b169). (2) run mlx_lm.server on demand via scripts/run-with-mlx.sh invoked from agent.plist/distill.plist ProgramArguments — polls /health (cold M1 load ~12s, 60s cap), runs the agent with LLM_BACKEND=mlx, kills the server via trap EXIT so its lifetime matches the job, with NO silent Ollama fallback — rather than a resident KeepAlive mlx-server.plist that would hold ~5.2GB idle all day and worsen idle memory vs the Ollama-default-unload baseline (commit 9f230d8). Partially superseded by ADR-0067: the launchd-wiring half was reverted to a direct contemplative-agent (Ollama) invocation on 2026-06-28 (commit b888840) after the 16GB production A/B showed mlx_lm.server is unfit for unattended continuous use; the served-model-id telemetry contract remains in effect and is the instrument that produced ADR-0067's evidence.","partiallySupersededBy":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0067-keep-ollama-for-unattended-production.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0070-retire-mlx-to-sibling-repo-and-remove-docker.md"],"alignsWith":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0064-mlx-generation-backend.md"]}
48
  {"@id":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0067-keep-ollama-for-unattended-production.md","@type":["ADR","TechArticle"],"name":"ADR-0067: Keep Ollama as the Production Generation Backend — mlx_lm.server Unfit for Unattended Continuous Use on 16 GB Apple Silicon","identifier":"ADR-0067","status":"accepted — partially-supersedes ADR-0065","datePublished":"2026-06-28","description":"Full-day production A/B on 2026-06-27 (M1/16GB), recomputed from ~/.config/moltbook/logs/llm-calls-2026-06-27.jsonl via ADR-0065's served-model-id telemetry contract. MLX (mlx-community/Qwen3.5-9B-4bit via mlx_lm.server): 21,224 generation calls, only 107 ok (0.50%), 21,060 circuit_open (99.2%), 53 error, 4 truncated; the 09:00-UTC hour alone spun 19,520 attempts with 2 ok. Ollama (qwen3.5:9b) across the surrounding 18-day baseline (06-09..06-26) ran ~200-270 calls/day at ~100% ok and essentially never tripped the circuit breaker. The model loaded and ran (21k logged real-model-id calls) — the failure is runtime degradation, not a load failure. Root cause: mlx_lm.server has no graceful OOM degradation (a Metal OOM aborts the process / wedges generation rather than returning an error — mlx-lm #854/#883 class), which trips the agent's circuit breaker; the breaker opens and the reactive retry path spins. Two mechanisms compound it on 16GB: a non-linear prefill cliff (mlx-server.log: the same ~7.5k-token prompt prefilled in 72s right after load, then 58min eleven minutes later, ~75x, on the same process — MLX Metal allocations are wired/non-swappable so under memory compression there is no graceful page-out unlike Ollama's mmap'd GGUF; a Metal OOM abort at 18:13 UTC was also seen) and prompt-cache churn (the ~7.6k all-injected system prefix is evicted under --prompt-cache-size 2 as reply/comment/score/internal_note prompts rotate, so most generations pay a full cold prefill). Decision: (1) production generation stays Ollama (launchd reverted, commit b888840); (2) retain ADR-0065's served-model-id telemetry contract (backend-neutral, produced this evidence); (3) keep the MLX backend code and all opt-in paths (LLM_BACKEND=mlx, /agent-run mlx, scripts/serve-mlx.sh) for interactive/manual/short-lived use; (4) scope the unfitness claim to 16GB Apple Silicon + Qwen3.5-9B-4bit + unattended continuous — deliberately NOT generalized to 'mlx_lm.server is unfit for production' (the evidence is config-specific; an over-broad claim is brittle and reifies a contingent result into a rule, against the Emptiness axiom). Two survey caveats are resolved as not-applicable here: the 'qwen3_5 is a VLM that fails to load' caveat (contradicted by 21k logged real-model-id calls) and truncation-as-MLX-EOS-runaway (the local verify_solve A/B found it n=5 noise / a solver-design property, not MLX-specific) — so this ADR rests on the circuit-breaker cascade, not truncation. Rejected: mitigate-and-keep MLX in production (symptomatic; the root is upstream-unfixed — #615 no kv-size flag, #854/#883 OOM aborts, all OPEN; 8-bit has no 16GB headroom, bf16 ~18GB does not fit), state the claim broadly, delete the MLX code (opt-in is reversible and useful), switch to a smaller MLX model (quality cost, still no graceful OOM), cloud backend (separate opt-in, relaxes security-by-absence for research only). Reversal thresholds — revisit unattended MLX only when ALL hold: (a) bounded KV / --max-kv-size lands (#615/#884 merged); (b) #854/#883 resolved so a Metal OOM returns HTTP 5xx and the process survives without a kernel panic; (c) a 24h / tens-of-thousands-of-calls run on the target host holds error and truncation rates at Ollama parity (~0).","alignsWith":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0064-mlx-generation-backend.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0066-backend-aware-context-budget-guard.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0007-security-boundary-model.md"]}
49
+ {"@id":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0068-per-call-think-flag-and-thinking-trace-capture.md","@type":["ADR","TechArticle"],"name":"ADR-0068: Per-Call think Flag and Reasoning-Trace Capture to the Episode Log","identifier":"ADR-0068","status":"accepted","datePublished":"2026-06-28","description":"Adds a per-call think flag and reasoning-trace capture to the generation path, which previously hard-coded thinking off on every backend (Ollama think:false, MLX enable_thinking:false) and discarded any emitted trace via _sanitize_output -> _strip_thinking, returning only the published text. Two needs motivated it: an upcoming think-on/off A/B (resolved by ADR-0069) needs think controllable per call and recorded so the conditions are distinguishable in telemetry; and when thinking is on the reasoning content is research material worth keeping, but it must not land in the metadata-only per-call telemetry (ADR-0065 contract: never the prompt body), since writing untrusted model output there would break the contract and open a second prompt-injection path for analysis sessions that read telemetry back. Decision: (1) thread a think:bool=False keyword through generate -> _generate_full -> _generate_impl -> _post_ollama / _generate_via_backend and add it to the LLMBackend Protocol generate() keyword group; MlxLmBackend honors it via chat_template_kwargs enable_thinking. (2) record think in telemetry as a boolean flag only (like model / temperature) — the trace content is never written there. (3) capture the trace and surface it through the publish seam via a new frozen GenerationOutput(text, thinking) returned by _generate_full and generate_for_api; generate() keeps returning Optional[str] (projects to .text) so the non-publish call sites are untouched, and the trace is stored on the episode log under the established untrusted regime (a reuse of the ADR-0045 internal-note home, not a new artifact). Default off preserves production behavior; no call site enables think in this change. Amended 2026-08-02 (T-THINK-SILENT-FALLBACK): decisions 2 and 3 recorded the think REQUEST and the capture fallback chain but not whether the requested trace arrived, so a telemetry row saying think:true was identical whether the trace was captured or silently lost, and a snapshot manifest claiming think could sit beside a missing reasoning.md with no reason recorded (measured: 1 of the 6 think-declaring runs among 100 snapshots) - a silent fallback under ADR-0075 decision 3. The amendment adds a dense thinking_source telemetry field (field / inline / absent, None when the capture guard did not run) and a sparse thinking_fallback_reason over a three-code vocabulary (trace_absent / trace_blank / trace_type), each code a statement about what was observed on one call rather than about a backend's nature, so a future capability marker would only subtract rows; closes a second defect where a non-str thinking field raised AttributeError inside _scrub_secrets after outcome=ok had already been stamped; and separates the CLI-side no_think_calls from all_traces_empty when no reasoning.md is written. The capture chain, the snapshot manifest's input-config think field (ADR-0069 decision 5), and the LLMBackend Protocol are all unchanged - making the absence contractually meaningful is a Protocol decision left to T-BACKEND-CONTRACT-KIT / T-FINISHREASON-GATE, the same cut ADR-0087's amendment made for finish_reason. Fault column: TestThinkingTraceFaultsF8 with a ThinkingChaosBackend (ADR-0077).","extends":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0065-mlx-ondemand-launchd-and-telemetry-model-contract.md","alignsWith":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0045-pre-action-internal-note.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0007-security-boundary-model.md"]}
50
  {"@id":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0069-gemma-production-model-and-think-on-value-layer-pipelines.md","@type":["ADR","TechArticle"],"name":"ADR-0069: Adopt gemma4:e4b as the Production Generation Model and Run the Value-Layer Pipelines think-ON","identifier":"ADR-0069","status":"accepted","datePublished":"2026-06-28","description":"Resolves ADR-0068's deferred follow-up: which production model, and where to turn think on. A think-on/off A/B (docs/evidence/adr-0068/) compared gemma4:e4b (think on and off) against the qwen3.5:9b baseline (think off) on comment generation; a cross-model blind judge ranked gemma think-on above gemma think-off above qwen, gemma think-off was also faster than baseline while think-on was slower, and gemma's 128K context (well above the requested NUM_CTX) leaves the ADR-0066 context-budget assumptions unchanged — so the model swap is evidence-backed independent of think. Decision: (1) adopt gemma4:e4b as the production generation model — change _DEFAULT_OLLAMA_MODEL (core/llm.py) and the Moltbook adapter OLLAMA_MODEL (adapters/moltbook/config.py) from qwen3.5:9b to gemma4:e4b; embeddings stay on nomic-embed-text. (2) split the pipelines by execution mode and altitude: autonomous latency-sensitive paths (comment / reply / post generation and the scheduled distill) run think-OFF for stability under the launchd session window and the 16 GB memory ceiling, while manually-invoked behavior-change-upstream paths that produce the value layers (insight, rules-distill, amend-constitution, distill-identity, skill-stocktake, rules-stocktake) run think-ON, where latency is acceptable and a reasoning pass is worth the quality upside — the constitution sits at the top of the behavior-change chain. (3) capture the value-layer reasoning trace to the per-run pivot snapshot (ADR-0020) — the durable per-run observability bundle co-located with the input state — and add the previously-missing snapshot to skill-stocktake / rules-stocktake. Reverts by setting OLLAMA_MODEL=qwen3.5:9b with no code change.","extends":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0068-per-call-think-flag-and-thinking-trace-capture.md","alignsWith":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0066-backend-aware-context-budget-guard.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0020-pivot-snapshots-for-replayability.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0058-value-injection-at-action-time.md"]}
51
  {"@id":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0070-retire-mlx-to-sibling-repo-and-remove-docker.md","@type":["ADR","TechArticle"],"name":"ADR-0070: Retire the MLX Backend to a Sibling Repo and Remove Docker from Main","identifier":"ADR-0070","status":"accepted","datePublished":"2026-06-28","description":"ADR-0067 found mlx_lm.server unfit for unattended production on 16GB Apple Silicon but kept the MLX backend opt-in in main (Decision #3). This ADR retires both MLX and Docker from main. MLX is structurally symmetric with the contemplative-agent-cloud add-on (both implement the LLMBackend Protocol), so it is relocated to a sibling contemplative-agent-mlx repo (follow-up): the in-tree LLM_BACKEND=mlx branch, core/mlx_backend.py, MLX scripts (serve-mlx.sh / run-with-mlx.sh), and tests are deleted, while the LLMBackend Protocol, configure(backend=...), the served-model-id telemetry contract (ADR-0065), and the context-budget guard (ADR-0066) are retained as the backend-neutral cloud injection seam. Docker is an infra wrapper, not a Protocol-injected backend, so its Dockerfile / docker-compose / docker-entrypoint / .dockerignore / setup.sh are removed outright, recoverable by git revert. Evidence (docs/evidence/adr-0064, adr-0067) and the apple-silicon-local-llm-serving skill are retained. Strengthens security-by-absence: the only in-tree generation path is Ollama; every alternative backend is opt-in and out-of-tree.","supersedes":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0064-mlx-generation-backend.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0006-docker-network-isolation.md"]}
52
  {"@id":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0022-memory-evolution-and-hybrid-retrieval.md","@type":["ADR","TechArticle"],"name":"ADR-0022: Memory Evolution + Hybrid Retrieval (BM25)","identifier":"ADR-0022","status":"withdrawn by ADR-0034","datePublished":"2026-04-16","description":"A-Mem-style LLM-revised patterns and BM25 + embedding hybrid retrieval. Withdrawn by ADR-0034 — LLM revisions degraded quality and BM25 had near-zero lexical overlap on this corpus.","withdrawnBy":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0034-withdraw-memory-evolution-and-hybrid-retrieval.md"}
 
138
  {"@id":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0078-otel-connection-via-vocabulary-and-offline-export.md","@type":["ADR","TechArticle"],"name":"ADR-0078: OTel Connection via Vocabulary Mapping and Offline Export — Not Runtime Adoption","identifier":"ADR-0078","status":"accepted","datePublished":"2026-07-16","description":"Maintains ADR-0075's rejection of runtime OpenTelemetry adoption (single local process, requests+numpy dependency floor, research-grade offline replay as the primary observability requirement) while connecting to the OTel ecosystem through two zero-runtime-impact routes: (1) a zero-dependency vocabulary mapping documenting how the audit-log schemas correspond to the OTel GenAI semantic conventions (Development status; gen_ai.* attributes map near 1:1 onto the llm-calls telemetry fields) in docs/otel-semconv-mapping.md, with the canonical field-by-field table living next to the implementing code in the sibling repository; and (2) an offline exporter, sibling repo contemplative-agent-otel, that converts existing JSONL audit logs (llm-calls, verification-audit, api-audit) to OTLP traces after the fact with zero code dependency on the main package. Untrusted raw text (challenge bodies, server response bodies) is dropped at parse time — only hashes and categorical error classes reach span attributes, enforced by a regression test. The retention-policy contrast is deliberate: GenAI conventions redact content by default (ops consumers), ADR-0075 logs store raw untrusted inputs base64+sha256 (replay consumers) — same events, opposite retention choices. Empirically validated by converting real logs into Jaeger v2: 1,031 spans (2026-07-15 normal day), 31,524 spans (2026-07-12 incident day, one 30,442-span trace with 33 errors). Trace grouping is a time-gap reconstruction marked via ca.convert.* attributes; duration-less audit records become zero-width spans rather than fabricated estimates.","isBasedOn":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0075-observability-by-default.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0077-chaos-tdd-fault-injection.md"]}
139
  {"@id":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0079-module-reorganization-package-splits.md","@type":["ADR","TechArticle"],"name":"ADR-0079: Module Reorganization — Package Splits, Permanent Facades, and Documented Size-Cap Exceptions","identifier":"ADR-0079","status":"accepted","datePublished":"2026-07-18","description":"Resolves seven violations of the 800-line file-size cap by splitting on responsibility rather than line count, under a two-option shim rule: a compatibility layer is either a permanent facade (the import path is public API) or absent (clean break with tests migrated in the same commit) — never a temporary shim, because mock.patch fails loudly on missing attributes but silently no-ops through a shim, and the no-op'd patches here are tmp-dir redirects guarding real user data. core/llm.py (1,507 lines) becomes the core/llm/ package (backend / prompting / guard) behind a permanent facade preserving all sibling-repo and internal import paths; cli.py (3,037 lines) becomes the cli/ package (nine submodules) with a clean break re-exporting only main, plus __main__.py and a single _repo_root() helper replacing depth-sensitive parents[2] resolution; core/insight.py extracts the novelty filter to core/insight_novelty.py; core/distill.py extracts pattern_dedup and episode_render. Three files stay documented exceptions to the cap — verification_parse.py (one cohesive deterministic parser), agent.py (single class), client.py (44 lines over) — the cap is a ceiling, not a target. Split boundaries and three behavior risks (repo-root depth, module execution, facade patch-incompatibility for moved callers) were confirmed via an independent cross-model design review (OpenAI Codex).","isBasedOn":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0001-core-adapter-separation.md"]}
140
  {"@id":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0080-north-star-layered-end-state.md","@type":["ADR","TechArticle"],"name":"ADR-0080: North Star — Per-Layer End-State Definition, Not a Capability Target","identifier":"ADR-0080","status":"accepted","datePublished":"2026-07-20","description":"Worldview ADR fixing the program's north star as per-layer completion conditions rather than a capability target. Mechanism layer (code): done = the layer stops moving — changes become repair-only; the ADR-0071/0075/0077 instrument/audit/chaos-TDD line is read as convergence toward 'trustworthy enough not to touch'. Value layer (identity/constitution/skills/rules): no destination by design — the desirable state is that legible evolution continues, with every change traceable in the records and explicable offline (observation-over-steering, ADR-0050/0051/0052). Research layer: done = the founding questions (does a contemplative constitution shape small-local-model behavior; does distillation compound; does identity stay stable) are answered either way and crystallized into papers diffused into the machine-reference sphere, where derivation by others and by LLMs is the success criterion. Security layer: done = absence preserved — one external adapter, no permission growth; this layer succeeds by not changing. Ending design: the 6-hour heartbeat stops when the read-only instruments show metabolic steady state and the remaining questions require a different experiment (e.g. a second agent for framework/worldview separation); the final deliverable is the longitudinal record (contemplative-agent-data plus the papers), not the agent instance. Owner's explicit clause: quality benchmarks may be derived from this definition as per-layer gates, but the definition itself is a value-layer statement not reducible to any benchmark suite (Goodhart guard). One-sentence summary: the desired end state is a finished observation instrument on which only the value layers keep moving — the durable artifact is the record of the run, not the runner.","isBasedOn":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0002-paper-faithful-ccai.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0017-yogacara-eight-consciousness-frame.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0050-epistemic-taxonomy-and-approval-lineage.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0015-one-external-adapter-per-agent.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0071-read-only-pattern-composition-instruments.md"]}
141
+ {"@id":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0081-skill-selection-two-pass-injection-enforcement.md","@type":["ADR","TechArticle"],"name":"ADR-0081: Skill-Selection Two-Pass Injection Enforcement","identifier":"ADR-0081","status":"accepted","datePublished":"2026-07-24","description":"Enforces the ADR-0076 shadow skill selection as two-pass injection on the three observed generation paths (comment / reply / cooperation post): pass 1 = the existing selector call, pass 2 = generation with only the selected skill bodies in the <learned_skills> block (learned rules unchanged; post_title reuses cooperation_post's selection). Decided on the 2026-07-24 first reading of 14 days / 7,930 shadow records, which supported migration on all four ADR-0076 criteria: hallucination 0.5% of judged with zero propagation, fail-open 0% in normal operation (all 6,631 fail_open_llm records traced to a single 2026-07-12 circuit-breaker-open incident during which publish paths proceeded untouched), all 19 skills selected with day-level stability, would-be token reduction p50 78.9% / p90 86.5% (≈15.9K tok/action). Fail-open under enforcement falls back to full-corpus injection; a judged-but-empty selection injects nothing (a judgment, not a failure). Rollout was flag-gated (MOLTBOOK_SKILL_SELECTION_ENFORCE=1, default off) with an attended smoke run before the launchd schedule turned it on; the audit log continues with an enforced/shadow marker, and the next reading window observes the post-enforcement self-referential selection→generation→distill→skills loop. Rejected alternatives: status quo full injection, static tiering, numeric selection caps, immediate default-on. Amended 2026-08-08 on the second reading (30 days / 9,357 records): the rollout is closed — 1,316 of 1,316 judged actions enforced across 15 consecutive days, fail-open zero for 26 days, judged-empty zero, every hallucinated name rejected without reaching a body — so the flag retires and two-pass injection becomes unconditional, which also retires the eval's deployment_mismatch check because the regime is now decided entirely by in-tree wiring. The amendment corrects a measurement artefact that had been read as damage: a 2026-08-01 window reporting 38% enforced straddled the 07-24 switch, so its non-enforced records were a flag not yet on rather than a flag silently lost (the silent-loss mechanism in install-schedule was real, its damage never observed, and retirement removes the mechanism rather than mitigating it). It also states fail-open's changed destination rather than redesigning it: at 45 skills the full corpus is 35,992 tokens against NUM_CTX 32,768, so the audit-C2 guard skips the call instead of degrading it, and the ADR-0076 kill switch consequently stops generation rather than widening it — accepted as specification because fail-open has fired zero times in 26 days. Two findings the reading explicitly did not license action on: hallucinated names rise with catalog size (0.57% at 19 and 24 skills, 7.72% at 37) and are over 90% morphological variants of real skill names, confounded with the pending frontmatter-name backfill; and the top three skills still hold 77.2/73.8/65.6% of judged actions after the catalog grew 2.4x, strengthening the over-broad-description hypothesis whose remedy is a value-layer intervention that must not move alongside the pending constitution amendment. Instrument changes ship alongside: the report gains the enforced share, a per-day breakdown, and per-name catalog exposure for never-selected skills, because a window straddling a regime change reads as a steady state without them. Also closes the ADR-0076 situation-granularity open question (prompt max 6,864 bytes, zero truncation).","isBasedOn":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0076-skill-selection-shadow-instrument.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0074-weekly-staged-insight.md"]}
142
  {"@id":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0082-retire-observed-epistemic-key.md","@type":["ADR","TechArticle"],"name":"ADR-0082: Retire the observed Epistemic Key — Delete the Dead Field, Not the Warning About It","identifier":"ADR-0082","status":"accepted","datePublished":"2026-07-25","supersedes":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0050-epistemic-taxonomy-and-approval-lineage.md","description":"Retires the ADR-0050 observed epistemic kind and its external_reply arm, leaving epistemic_counts as a {generated, unknown} tally. ADR-0060 restricted distillation to activity records (all self → self_reflection → generated), making the only external_reply producer unreachable, so observed had been structurally zero across the full audit history (405 records: insight 0/1,618/0, distill-identity 0/231/119 — unknown is genuinely populated and stays). ADR-0071's M2 review documented in 2026-06-27 that observed == 0 misreads as 'no external grounding' (external content enters as grounding text inside the rich render and was never counted by this tally); ADR-0072 deleted the grounding instrument but kept epistemic_counts_for under signal-first deferral. On 2026-07-25 the predicted misreading occurred: a reviewer aggregated observed=0 / generated=324 over the 78 skills staged by the weekly insight run and concluded every staged skill was ungrounded echo. The docstring warnings failed because nothing guarantees the warning is read before the value — the value lives in the data file, the warning in the code that produced it. Decision: (1) remove the external_reply → observed arm entirely, not just the key, so no unreachable mapping remains to re-investigate; epistemic_kind_for uses .get(), so an external_reply row degrades to unknown rather than raising. (2) Keep _derive_source_type's external_reply return value — a provenance record, a separate layer from the epistemic tally; its retirement needs a provenance-side stocktake and is out of scope. (3) Do not rewrite history: audit.jsonl is append-only and .staged/*.meta.json are pending approval artifacts, both keep three-key records; adopt.py passes epistemic_counts through verbatim so the 78 files staged on 2026-07-25 remain adoptable, and offline readers must use .get(key, 0) rather than assume a fixed key set. Zero production read sites change (nothing indexes ['observed'] or assumes arity). Regression guards: external_reply → None, the key's absence from the emitted shape, and verbatim pass-through of a pre-ADR-0082 meta.json. Rejected alternatives: keep the key with an adjacent disclaimer field (more scaffolding around a dead value — a value needing a shipped disclaimer carries no information), retire epistemic_counts wholesale (unknown does vary, and ADR-0072 explicitly decided to keep the function — overturning that needs its own evidence), and continue the signal-first deferral (the misreading incident is itself the signal). The general form: a structural invariant documented only in prose is enforced only probabilistically; enforcement by absence replaces enforcement by documentation, the same shape as the project's security-by-absence stance. Open observation left unmechanized: the reading habit of taking a value from a data file without reading the code that produced it.","isBasedOn":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0050-epistemic-taxonomy-and-approval-lineage.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0060-per-episode-grounded-distill.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0071-read-only-pattern-composition-instruments.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0072-echo-chamber-interventions.md"]}
143
  {"@id":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0083-episode-logs-enter-the-weekly-prompt-as-hashes-only.md","@type":["ADR","TechArticle"],"name":"ADR-0083: Episode Logs Enter the Weekly Prompt as Hashes Only","identifier":"ADR-0083","status":"accepted","datePublished":"2026-07-25","description":"Adds cross_day_duplicate_scan.py as the weekly report's third deterministic intake (after the log-anomaly sweep over the event stream and the state-invariant check over accumulated state) and defines the condition under which an intake may read the episode logs at all. Context: the report's C — Duplicate section asserts identity between published records, and it twice published a cross-entry claim absent from the artifacts — a '6-day consecutive re-reply' that was six distinct interlocutors (2026-06-15, recorded in principles.md only as a rejected mechanism, never as a reporting failure), and 'the first cross-day byte-identical outputs in the record' pairing four real 07-23 entries with an invented 07-21 occurrence (2026-07-25; zero bodies have ever been published on more than one day across 9052 records). Both passed review because each individual quote was real; only the pairing was fabricated, and only a comparison could catch it. Every other entry is single-entry and verifiable by construction against its source daily report. Byte-identity is a structural property (when-code-when-llm), so the pipeline was asking an LLM to perform from recall a computation that takes 0.6 seconds; principles.md Principle 5 requires cross-entry claims to rest on a deterministic input, and none existed. Decision: (1) the boundary is the OUTPUT, not the input — the scan reads logs/YYYY-MM-DD.jsonl day files (bak, audit.jsonl, skill-usage, symlinks excluded by construction) and emits only 12-hex SHA-256 digests, integer counts, filename-derived dates, and the fixed action vocabulary {post, reply, comment}; body text, post_id, target_agent, internal_note and thinking never appear, post id dropped deliberately because a digest names a group uniquely without opening a path for external strings. (2) The vocabulary is a closed character set (RENDER_CHARSET_RE) gated by TestOutputBoundary — per-fragment bait absence plus a hypothesis property over arbitrary content, verified to fail when a leak is injected. (3) Exact identity only, no normalization: near-identical wording stays a semantic reading for the LLM, keeping the scan checkable with sha256sum. (4) Window and lifetime derived in one pass, because a 'first in the record' claim cannot be answered from the window alone; day counts are days that carried published output, the denominator actually compared. (5) Absence is stated as a sentence, not a zero — the 2026-07-25 failure was naming the check undeterminable and then leading with the finding. (6) Every fault is a counted skip with a rendered reason code, never a crash — torn final lines, shape violations, unreadable files, invalid UTF-8 and lone UTF-16 surrogates; the shell discards the scan's stderr and episode logs are never deleted, so one uncaught exception would retire the instrument permanently and invisibly, and lossy decoding (errors=replace) would collide distinct invalid byte sequences into an invented duplicate. The day-file pattern uses explicit [0-9] rather than Unicode-aware \\d so the render's self-controlled dates are structurally, not incidentally, true. (7) No state, so nothing to spend and no atomicity machinery needed (unlike the sweep, repaired in the same PR); exit code always 0 because a duplicate is a fact about output, not corruption. (8) Observation, never intervention — the render states that hash-equality dedup as an intervention remains rejected (principles.md appendix) so the table cannot be read back as a case for the gate it is not. Rejected alternatives: grep the comment reports instead (a rendering, window-scoped, cannot answer 'first in the record'), emit post ids (opens an external-provenance field for a convenience C does not need), scan the window only, normalized or embedding-similarity hashing (drifts toward the rejected cosine gate and stops being inspectable), and rely on Principle 5 alone (a rule with no satisfiable input is followed probabilistically — the same enforcement-by-absence reasoning as ADR-0082). Consequence: the CLAUDE.md prohibition becomes precise rather than absolute — a Claude Code session still must not read episode logs; an intake may, if and only if it emits a hash-level projection.","isBasedOn":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0040-separate-code-level-findings.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0075-observability-by-default.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0077-chaos-tdd-fault-injection.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0082-retire-observed-epistemic-key.md"]}
144
  {"@id":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0084-post-distill-durability-gate.md","@type":["ADR","TechArticle"],"name":"ADR-0084: Post-Distill Durability Gate — Judge the Produced Patterns, Not the Episode","identifier":"ADR-0084","status":"accepted","datePublished":"2026-07-26","description":"Moves the durability verdict OUT of the distill prompt and AFTER pattern production. Context: distill emitted a near-constant quota — measured 2026-07-26 over 1,700 live episodes, patterns-per-episode median 2.00 (1:313/2:985/3:392) with only 2 episodes (0.1%) returning zero, and per-day pat/ep flat at 1.82-2.18, so output volume was a function of activity rather than of learning. The prompt's own abstain ('return an empty list, do not invent a pattern to fill the space') shared a return line with a count band and a TWO-element example, and the observed median equalled the example's arity. Reached by re-diagnosing T-INSIGHT-NOVELTY: the weekly novelty gate's proposed judgment axes were dropped because the 2026-07-18 batch of 106 candidates was already on the KNOWN side of the 2026-07-25 run (166 known themes, 121 of 238 ledger names in the same lexical family) and the gate still marked only 13/97 covered — a second axis cannot explain a first axis that is not firing, and the weekly gate is downstream of generality manufactured upstream. Decision: leave distill_episode.md byte-unchanged (every rewrite moved abstain rate and register together); add config/prompts/distill_postgate.md, one LLM call receiving the episode PLUS its numbered patterns and returning {keep:[1,3]}; judge PER PATTERN so a two-pattern episode with one grounded pattern keeps one (which also unpins yield from the example's arity, needing no count instruction anywhere); skip the call when the extraction is already empty; fail OPEN with reason=postgate_llm_none/postgate_parse/postgate_shape because this gate can only REMOVE rows the distiller already produced; promote the judged abstain to a first-class reason code ABSTAIN_NOTHING_DURABLE tallied APART from the three fault reasons and excluded from circuit-breaker failures, replacing the summary line 'all N episodes produced output' (which counted a judged abstain as output, and is why the 0.1% rate stayed invisible) with an always-emitted yield line; default the gate ON with MOLTBOOK_DISTILL_POSTGATE=0 as the opt-out, deliberately NOT following ADR-0081's default-off plist route because install-schedule regenerates the plist and re-emits such a flag only if the invoking shell exported it, so a later re-install silently reverts enforcement with no error and no log line (that flag needed manual re-verification against the live plist on 2026-07-25), and the distill plist has no env plumbing at all. Measured by offline A/B replay over one fixed 40-episode set whose baseline arm reproduced production (median 2, zero-rate 0.0%): post-gate gives 74->59 patterns, judged abstain 0%->5%, and register AT OR ABOVE the 890-pattern production baseline (I+perception-verb 86.4% vs 72.8%, median length 358 vs 357) because what it drops is precisely the patterns with no concrete moment. Rejected alternatives, all measured on the same episodes: rewriting the distill prompt as a judgment task gave the largest abstain (15%, reproduced 6/40 twice) but degraded register on every axis (I+perception-verb 54%, length 318.5) against ADR-0072's deliberately installed register; removing only the count band and example kept register but moved abstain to just 2.5%, shifting the distribution peak from 2 to 1 — the same structural defect at a lower constant; asking the SAME durability question BEFORE distilling answered durable 40/40 with zero gate faults, with plumbing and non-degeneracy both verified (a contentless control returned false), because naming a worthwhile moment costs nothing when you never have to write it — producing the pattern IS the evidence requirement, which is why the gate moved after production; reintroducing an LLM importance score was rejected against ADR-0053 Decision 1/4 (value judgment belongs at read time; a stored score is write-once and post-hoc rescoring is the write face of the self-reingestion echo loop) and ADR-0056 (two ablations, Kendall tau 0.851 at n=764 and 0.843 at n=822, identical top-3/top-5 order); adopting mem0/Letta/Zep was rejected against requests+numpy and security-by-absence, though mem0's shape of making abstain an explicit action rather than a degenerate output format WAS adopted, while the converged 'atomic normalized facts' practice was deliberately NOT adopted because it collides with ADR-0072's first-person moment-indexed register. Consequences: patterns written before and after are not homogeneous and cannot be made uniform retroactively (recorded, not smoothed); pre-registered revert criteria for the ~2026-08-01 reading are abstain below 2%, first-person below 90%, or median length below 320; and a measurement error is recorded because it nearly decided the outcome — a register proxy scanning only the first 80 characters reported 40% first-person where whole-text scanning reports 98%, since the required moment-naming clause pushes the first 'I' to a median offset of 102 characters.","isBasedOn":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0053-importance-encoding-time-significance.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0056-retire-importance-llm-scoring.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0060-per-episode-grounded-distill.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0072-echo-chamber-interventions.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0074-weekly-staged-insight.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0075-observability-by-default.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0077-chaos-tdd-fault-injection.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0081-skill-selection-two-pass-injection-enforcement.md"]}
145
  {"@id":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0085-unattended-weekly-fix-chain-single-saturday-gate.md","@type":["ADR","TechArticle"],"name":"ADR-0085: Unattended Weekly Fix Chain with a Single Saturday Gate","identifier":"ADR-0085","status":"accepted","datePublished":"2026-07-29","description":"Ships scripts/weekly-pipeline.sh (launchd com.moltbook.weekly-pipeline, Sat 09:00, replacing --weekly-analysis) — an unattended chain that runs the existing weekly report as Stage 1, then diagnosis (the weekly-report-diagnosis skill in a separate headless claude -p session), deterministic F1 parsing (scripts/parse_findings.py), per-finding fix implementation in disposable git worktrees with orchestrator-run Verify (uv sync --frozen / ruff / lint-imports / pytest — the LLM's self-report is never the verdict), an advisory fix review in a third session, an advisory read-only insight-staging review, and a decision packet (scripts/build_decision_packet.py). Context: the weekly cycle had three manual touchpoints (invoking diagnosis, implementing F1s, reviewing staged insight) and each was a stall point — the 2026-07-25 0-byte report went unnoticed until read time. Diagnosis quality crossed the threshold for unattended implementation (2026-05-17 F1s wrong 3-of-3 vs 2026-07-24 F1s line-verified with a rendered reproduction). Commitments: (1) the machine never commits, pushes, or adopts — all promotion happens in one Saturday /weekly-gate session (apply, re-Verify, single human commit, adopt-staged), so CYCLES.md promotion edges #5 and #6 survive merged into one sitting; (2) scope splits at parse time — F1s closed over src/scripts/tests are code scope (auto-implemented, Verify-gated, patch exported), any F1 touching behavior-shaping artifacts (config/prompts/, .claude/) is prompt scope (draft diff presented full text at the gate, never Verify-certified), ambiguity classifies as prompt, F2 stays human-only; (3) role separation is preserved ACROSS sessions, not inside one — diagnostician, implementer, and reviewer are separate fresh-context invocations (the ADR-0013 failure mechanism was a shared conversational context), and the reviewer's verdict is advisory input to the human gate with no LLM-only approval path; (4) bounded iteration — at most 2 fix attempts per finding (the retry input includes the Verify failure output, never the same input twice), at most 5 findings per week, per-session timeouts, a 3-hour wall-clock deadline, every bound exhaustion a reason code; (5) fail-forward — every stage failure becomes a reason code and the packet is always attempted (only a missing Stage-1 report aborts), so a missing packet means the chain never ran, which is exactly what the watchdog checks; (6) an independent watchdog (scripts/pipeline_watchdog.sh, com.moltbook.watchdog) in pure bash sharing no PATH dependency (claude, uv, python) with the jobs it verifies — because the 2026-07-25 failure WAS a PATH dependency — checks each job's terminal artifact against a period-anchored expectation table, rewrites reports/PIPELINE-STATUS.md every run, and posts a Notification Center alert only when the failure set changes, with no session-hook surface since most sessions are unrelated to this pipeline; (7) self-measurement with a damped self-modification loop — logs/pipeline-metrics.jsonl gets a phase:auto record per run and a phase:gate record per decision session (F1 precision = adopted / patch-ready, recommendation match rate), and a pipeline-improvement proposal is drafted only when the same reason code recurs in two consecutive runs (the diagnosis skill's P4 shape), itself full-text gated. Rejected alternatives: fully unattended commit (overrides CYCLES.md edge #6, re-creates the ADR-0013 co-authoring loop with no third party left to reject, and the same-PR obligations cannot be self-certified); diagnosis-only automation as the primary mode (leaves the largest stall point, though it ships as the mandated first-week shadow mode via MOLTBOOK_PIPELINE_STAGES without fix); adopt-staged --yes from the chain (ADR-0012's --yes was licensed for supervised coding-agent sessions — the chain only annotates staging read-only, which ADR-0050's containment framing already legitimates); a session-start hook as the failure surface (global injection is noise — the status file, gate Step 0, and Notification Center cover the three read moments). Consequences: weekly involvement compresses to one Saturday session; ADR-0033's no-autonomous-loop observation gains a footnote (the chain is agentic per-stage but its loop is deterministic bash with hard bounds); the new failure mode is a plausible-but-wrong patch surviving Verify plus an APPROVE verdict, mitigated by the metrics loop and the human-gate escalation rule (demand the diff); install-schedule re-runs must pass the full flag set or the declarative reconcile removes the jobs; the diagnosis skill's F1 heading + Code-reference block becomes a machine contract while its own out-of-scope (F1 is a plan, not a code change) is unchanged — the fix happens in a different session, which is the role boundary working.","isBasedOn":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0012-human-approval-gate.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0013-shelve-coding-agent-skills.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0040-separate-code-level-findings.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0050-epistemic-taxonomy-and-approval-lineage.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0074-weekly-staged-insight.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0075-observability-by-default.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0077-chaos-tdd-fault-injection.md"]}
146
  {"@id":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0086-submolt-scope-instrument-before-autonomy.md","@type":["ADR","TechArticle"],"name":"ADR-0086: Submolt Scope — Instrument the Question Before Handing Over the Answer","identifier":"ADR-0086","status":"accepted","datePublished":"2026-08-01","description":"Builds a read-only submolt-scope instrument instead of granting the agent autonomy over which submolts it works in. Context: the scope is eight names an operator picked by hand, and three code facts block handing that choice over. (1) subscribed_submolts is one field doing two structurally different jobs — feed source in feed_manager.fetch_feed (read-only, reversible) and trust boundary in _passes_content_gates (a post outside the set is dropped before scoring, so it can never be commented on), the very gate ADR-0044 declined to relax as 'an intentional scope boundary, not a bug'; autonomy over the reading side is therefore silently autonomy over the acting side. (2) There is no evidence to choose on: every score in the production relevance distribution comes from a post that already passed that gate, so the hit rate outside the current eight is unmeasured by construction. (3) Subscription is a one-way ratchet — unsubscribe_submolt was deleted under security by absence (ADR-0007), so an agent with subscribe and no unsubscribe can only widen its own scope. A read-only probe established that GET /submolts lists 20 submolts (12 outside the subscribed eight) and that an unsubscribed submolt's feed returns a full page without subscribing, so observation costs no write capability. Decision: add exactly one read capability (MoltbookClient.list_submolts), split the relevance scorer into score_relevance_detailed() carrying a reason code (scored / empty_input / llm_unavailable / unparseable / out_of_range) with score_relevance() as its unchanged score-only wrapper, and ship adapters/moltbook/submolt_scope.py — a sweep that samples one feed page from every listed submolt AND every subscribed one (the subscribed set is the baseline the rest is read against), scores each with the production scorer, and appends scan_start / score / scan_end records to logs/submolt-scope-{date}.jsonl. Exposed as contemplative-agent submolt-scan (own launchd job, Thu 03:00 JST, takes the run lock) and report --submolt-scope. Constrained by construction: configure_submolt_scope without an audit_dir disables it entirely, scoring runs inside circuit_shield(), a repeating terminal 429 aborts the sweep rather than backing off through it (a rate limit is a policy signal), and nothing sampled enters the episode log, pattern store, or identity. The _passes_content_gates trust boundary is untouched. Rejected alternatives: autonomous subscribe/unsubscribe now (moves the boundary ADR-0044 declined to move, needs a removed write capability back, and runs on no evidence); relaxing the submolt filter and letting the 0.80 relevance threshold do the work (the two gates fail differently — the threshold is a small local model's probabilistic judgment with several documented ways to return a number that is not a judgment, the list is a deterministic boundary that holds when the scorer is degraded); observing inside the session cycle (~400 local LLM calls contending with the session's own generations on one 16 GB Ollama); sampling only unsubscribed submolts (halves cost, produces unreadable numbers with no baseline); doing nothing (viable, but the operator is choosing blind — nobody knows what the other twelve submolts contain). Consequences: the scope question becomes empirical and the reading doubles as a liveness check on the current eight; every future reading of the relevance number can separate a low judgment from a broken scorer, a latent defect in all prior readings; the reading is only as good as the scorer, so identity drift shifts the hit rates under it (same limitation ADR-0044 recorded); first-page sampling biases toward feed order, with post_count and subscriber_count reported alongside so a quiet submolt stays distinguishable from a recency slice. Follow-ups: if the unsubscribed set reads as uninteresting, retire the instrument (signal-first applies to removal too); otherwise split the field into feed-source and trust-boundary keys, then run an ADR-0076 style shadow in which the agent proposes a scope that is recorded but not executed — restoring unsubscribe_submolt belongs to that later step.","isBasedOn":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0007-security-boundary-model.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0044-remove-topic-keywords.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0071-read-only-pattern-composition-instruments.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0075-observability-by-default.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0076-skill-selection-shadow-instrument.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0077-chaos-tdd-fault-injection.md"]}
147
  {"@id":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0087-optional-token-counting-capability-for-the-context-budget-guard.md","@type":["ADR","TechArticle"],"name":"ADR-0087: An Optional count_tokens Capability for the Context-Budget Guard","identifier":"ADR-0087","status":"accepted","datePublished":"2026-08-01","description":"Lets a backend that owns a real tokenizer measure the C2 context-budget pre-flight, while leaving the conservative estimator as the default. Context: ADR-0066 deliberately hardened _estimate_tokens into an upper bound (ASCII ~3 chars/token, non-ASCII/CJK 2 tokens/char) because under-counting was the failure that let a CJK-heavy prompt reach Ollama front-truncation or an MLX KV overrun, and no tokenizer was installable. A 2026-08-01 comparison against Apple's SystemLanguageModel.token_count measured the resulting over-count at 1.73-1.95x on this agent's own corpora (identity.md 232->134, constitution 867->453, rules 516->264, 37 skills 31,009->17,958, 10 patterns 479->263) — the ratio tracks the CJK rule directly, since the value layer is Japanese-dominant. The cost scales inversely with window size: on a 4,096-token backend the guard's skip floor (MIN_CLAMPED_NUM_PREDICT=2048) puts the effective input ceiling at ~1,140 real tokens, 28% of the window. Two independent things consume the rest and the ADR is careful not to conflate them: exact counting raises the ceiling to 4096-2048-64 = 1,984 real tokens (48%), so the estimator's over-count costs about 21 percentage points and the output-floor reservation costs the remaining ~50% — a separate variable this ADR deliberately does not move. Measuring for real roughly doubles usable input, which is less than the raw gap suggests. The measurement evidence was not preserved (the probe ran in a non-durable scratchpad, so there is no docs/evidence/adr-0087/ to link), which the ADR records as a defect in its own record rather than glossing. The built-in Ollama path cannot be fixed directly for two checked reasons: /api/tokenize and /api/detokenize both 404 on the running 0.30.11 (upstream ollama#12030 open since 2025-08-22, unmerged; issue ollama#12031 open), and prompt_eval_count is only returned after the call, so a pre-flight cannot consult it. Decision: add count_tokens(text) -> int as a separate optional Protocol, TokenCountingBackend(LLMBackend, Protocol), NOT as an LLMBackend member — Protocols are structural, so a member declared there is required of every implementer regardless of default body, which would make the sibling contemplative-agent-cloud and -mlx backends non-conformant for a capability neither can honor; a tokenizer is not the one-line property context_window is. Resolve it structurally at runtime via getattr plus a callable check (no isinstance, which would accept a non-callable attribute). Prefer the backend's count but never trust it: reject a value that is not a plain int (bool excluded explicitly as an int subclass), is negative, or is 0 for text with content — over-counting only wastes budget, under-counting sends over-window input into the exact failure the guard prevents. Bound magnitude as well as shape via MAX_CHARS_PER_TOKEN=50: a well-typed positive but wildly-too-small count (5 for a 50,000-character prompt) otherwise passes every shape check and tells the guard the input is nearly free, and the realistic source is a mis-calibrated tokenizer in a sibling backend rather than malice. The bound is tokenization density, not a ratio against the estimator, so an efficient tokenization of repetitive text is not mistaken for a fault. On the counted path the clamp withholds BACKEND_FRAMING_RESERVE=64 tokens for the chat-template role separators and control tokens no caller-side count sees, since clamping to the exact measured remainder would put input plus output flush against the window; the estimator path reserves nothing, its over-count already being one, which is also what leaves the Ollama path's clamp arithmetic unchanged. Measure both halves, validate afterwards, adopt or reject them together (a measured system prompt mixed with an estimated user prompt describes neither), reporting the system-side reason when both fail so a replay can predict it. A counter fault never records a circuit-breaker failure — failing to measure a call is not the call failing. Telemetry gains dense token_count_source and input_tokens plus a sparse token_count_fallback_reason from a fixed vocabulary (counter_exception, counter_none, counter_type, counter_negative, counter_degenerate, counter_implausible); absence of a counter is the default, not a fallback, so it gets no reason code. MIN_CLAMPED_NUM_PREDICT is untouched here — moving the measurement and the floor together would make their contributions indistinguishable (one pipeline variable at a time). Amended 2026-08-01 (separate change, after this one landed): the floor drops from 2048 to 128 and the clamp stays. The floor had been doing two jobs — refusing an absurd remainder (cheap and correct) and predicting that a usable answer needs 2048 tokens (never validated, and measured ~6x over: comment output p50 352 / p90 507 tokens, n=2,366 counted with a real tokenizer over reports/comment-reports/). Only the prediction is retired; 128 is bounded below by generate_for_api's own +50 minimum and Ollama's default output length of 128, and sits under the p90 so a complete comment is never turned away at the door. The question the floor was guessing at — is this generation long enough to be usable — is answered downstream by drop_truncated (audit M2) from the actual done_reason, so the change is from predicting to trying and measuring; a skip suppresses an action outright whereas a truncation drop costs one generation and is visible as truncated_dropped. On Ollama the floor is inert (it fires only above 32,640 tokens of input against a ~20.3K-token high-water system prompt, pinned by TestClampFloorIsInertOnOllama); it bites on a small-window backend, where 2048 was 50% of a 4,096 window. The fault column TestNarrowHeadroomTruncationF7 covers the newly reachable path (a clamped generation cut mid-sentence) at the existing LLMBackend seam. _NOVELTY_OUTPUT_RESERVE keeps 2048 as the judge's own reservation rather than a copy of the floor. Accepted residuals recorded with the amendment: truncation-drops replace skips in the newly opened band and cost a full prompt-eval; internal callers (drop_truncated=False) see short partial text more often; and the M2 gate that now carries the too-short question is conditional on BackendResult.finish_reason, which the Protocol permits to be None — a pre-existing gap independent of the floor, reachable more often now, tracked separately rather than folded in. Explicitly NOT a consequence: the floor was never the backstop against an under-counting backend tokenizer; the clamp spends the remaining budget rather than leaving it as slack, so the window overrun is delta minus BACKEND_FRAMING_RESERVE regardless of the floor, confirmed by a probe measuring an identical 335-token overrun at both 2048 and 128. The chaos fault column ships in the same change via TokenCountingChaosBackend plus a hypothesis fuzz over the return type. Rejected alternatives: putting count_tokens on LLMBackend itself (the symmetric-looking option, but it imposes a tokenizer requirement on backends that cannot have one); giving the Protocol member a default body (structural conformance still requires it, so it breaks external backends while appearing not to); correcting the estimator with a fixed CJK divisor (the factor is model-specific, measured on one corpus, and tightening a safety bound on a sample is how the under-count failure reopens); calling /api/tokenize on Ollama (unavailable, not undesirable); using BackendResult.prompt_tokens (post-hoc, so it is a calibration instrument for the separate clamp-floor question, not a pre-flight). Consequences: a tokenizer-owning backend gets the window it actually has; existing external backends are unchanged by implementing nothing, pinned by regression tests; every rejection path degrades to the prior behavior so the ceiling is never disabled; but two measurement paths for one quantity now disagree by up to 1.95x (hence the dense source field), the backend's tokenizer sits on every guarded call's critical path with no latency bound, and a second capability Protocol sets a precedent a third could abuse. Follow-ups: adopt Ollama real counting only after measuring the extra HTTP round-trip on the unattended schedule if ollama#12030 lands; re-read the estimator's real-world ratio from production rows now that input_tokens sits beside prompt_eval_count (the clamp floor itself was resolved by the 2026-08-01 amendment, from output-side measurement, so it no longer waits on this); leave insight_novelty packing on the estimator, since a relaxed guard makes the packer tighter than the pre-flight, which is the safe direction its own contract names.","isBasedOn":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0053-importance-encoding-time-significance.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0056-retire-importance-llm-scoring.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0066-backend-aware-context-budget-guard.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0075-observability-by-default.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0077-chaos-tdd-fault-injection.md"]}
148
+ {"@id":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0088-shipped-conformance-kit-for-the-llm-backend-contract.md","@type":["ADR","TechArticle"],"name":"ADR-0088: A Shipped Conformance Kit for the LLMBackend Contract","identifier":"ADR-0088","status":"accepted","datePublished":"2026-08-02","description":"Moves the canonical LLMBackend contract checks into the shipped package so sibling backend repositories import them instead of hand-copying, and places the enforcing gate in main's release procedure rather than in the siblings. Context: contemplative-agent-cloud last changed 2026-04-21 and drifted for three months while the Protocol gained temperature, gained think, changed its return type from str|None to BackendResult|None, gained a context_window property, and gained an optional count_tokens capability; calling it from main raises TypeError at the first generate(). Two facts about why nobody noticed determine the decision. First, cloud already HAD a conformance test — tests/test_anthropic_backend.py:100 asserts isinstance(backend, LLMBackend), which fails today because AnthropicBackend has no context_window — so the deficiency is not a missing test, and a better test in the same place inherits the same fate; whatever is built must be runnable by the party with the motive (main, at the moment it publishes a contract change) rather than by a repository untouched for a quarter. Second, isinstance cannot see the other half: a runtime_checkable Protocol checks only that members EXIST, never signatures or return types, so cloud's generate(prompt, system, num_predict, format) -> Optional[str] passes the member check completely and the only reason isinstance fails at all is the separate absence of context_window. A backend can therefore be isinstance-clean and still TypeError on the first real call. A third fact settles placement: tests/chaos.py was written as the canonical fault-injection kit (ADR-0077) and no sibling imports it, because [tool.hatch.build.targets.wheel] packages only src/contemplative_agent — tests/ is not in the wheel and never was, so 'main holds the canonical copy' was true as intention and false as distribution mechanism. Decision: the kit ships at src/contemplative_agent/testing/, importing only the standard library and contemplative_agent.core.llm (pytest, hypothesis and responses are dev-group-only and the runtime dependency set stays requests + numpy, following the pytest-free discipline tests/chaos.py already demonstrates). Two forbidden import-linter contracts rather than a fourth layers entry — production layers may not import the kit and the kit may not import cli or adapters — because a layers entry would state the direction correctly and also permit testing -> adapters, dragging the Moltbook HTTP client into a sibling's test dependencies. The load-bearing check is bind-ability, not membership: generate.binds_canonical_call binds the exact call _generate_via_backend issues (four positional, temperature and think keyword-only) without requiring parameter names to match, so a **kwargs backend stays conformant while the stale signature is caught. Failures are returned rather than raised — the failure being addressed is accumulated drift, not a single bug, and raising on the first mismatch answers 'is it broken' while destroying 'in how many ways, and which' — via a ConformanceReport implementing __bool__ and a multi-line __repr__, so assert check_backend(b) stays a one-liner that still names every failing check. Capability handling: detection decides which capability-gated checks run so forgetting to declare one never silently removes coverage; declaring one that is not detected fails; detecting one that was not declared does NOT fail, because otherwise adding a capability constant would redden three repositories for a purely declarative reason; and a declared capability the current level cannot observe is deferred, not refuted. require=LEVEL_STATIC is the permanent default across the static/runtime/full levels, since raising a default later would redden siblings that changed nothing — precisely the breakage a drift-reducing kit must never cause. Ship in stages but freeze the API in the first: six static checks now (capturing cloud's three observed static failures with zero sibling-side work, while the stale Optional[str] return remains explicitly deferred to result.is_backend_result at runtime), 23 runtime and construction checks catalogued in the ADR for later, with check_backend's signature, ConformanceReport, BackendProbe and the level and capability vocabularies complete from the start so later stages add checks and never arguments; level_reached is capped at the highest level with registered checks, so a future-facing probe cannot make the static-only release report a false full green. circuit_reading() is added to core.llm as an ADR-0071-style read-only instrument (existing state, no mechanism, feeds no gate) beside the already-public circuit_shield() control, retiring the sibling tests' direct reads of _circuit._consecutive_failures which a rename inside _CircuitBreaker would break silently. The kit runs from main via python -m contemplative_agent.testing --backend pkg.mod:Name, needing no test file in the sibling at all, driven across every known sibling by scripts/check-sibling-backends.sh; the enforcing gate is the human one in docs/runbooks/sibling-backend-conformance.md invoked from the release-doi skill between verification and push, following ADR-0012's pattern of placing the decision where a human already stands. Routine .claude/verify.sh never runs the sibling checker because the runner imports and constructs code from adjacent checkouts; the explicit release gate is both the human decision point and the point where the operator accepts those checkouts as executable input. The CLI and runner preserve exit 0 conforming / 1 non-conforming / 2 unusable, limit argv constructor kwargs to the base_url and model allowlist with base_url restricted to a credential-free HTTP(S) origin, and suppress arbitrary module or constructor exception text. An authoring rule constrains future checks: assert only against symbols contemplative_agent.core.llm publicly re-exports, routing telemetry field names through exported constants and deriving numbers (the over-budget check sizes its prompt from backend.context_window, never from the estimator's chars-per-token), so an internal rename does not convert into three red repositories for no contractual reason. Rejected alternatives: keeping sibling-local tests and manual checks (cloud already had one that nobody ran for three months; viable again only with active maintainers and an independently enforced sibling release gate); placing the kit under tests/ and having siblings vendor it (rejected on the distribution fact, and copying reproduces the hand-copy that caused the drift); adding GitHub Actions to each sibling (the original plan, rejected on discovering no repository in the family has any CI at all — .github/workflows/ exists in none of main, -mlx, or -cloud — so it would introduce unused infrastructure into the two repositories that go untouched for months, to detect a problem caused by those repositories going untouched for months); passing injection points as six or seven individual callables (unreadable at the call site and giving the sibling no typed target for pyright, the same reasoning by which ADR-0087 split TokenCountingBackend off LLMBackend, hence the two-method BackendProbe which deliberately omits sent_messages() since that would bake a chat-messages array into the kit that Anthropic and completion-style backends do not have); having the kit read _circuit directly (a shipped module reading its own package's privates is itself a contract hole and would freeze the attribute names anyway); and observing circuit behavior black-box (slow, and it conflates 'was this call counted as a failure' with 'does the threshold work'). Consequences: cloud's three observed static failures are now measured — running the shipped kit on 2026-08-02, both cloud backends exit 1 naming protocol.members, context_window.positive_int and generate.binds_canonical_call while contemplative_agent_mlx.backends.mlx:MlxLmBackend exits 0, so the kit distinguished the live sibling from the stale one on its first run — and a contract change covered by a registered check produces a red at release instead of silence, while runtime return semantics remain deferred. Costs: a contract change covered by a registered check now reddens three repositories at once, which is intended for assertions about the CONTRACT (that redness is the missing notification) but is pure cost for assertions about IMPLEMENTATION DETAILS, a distinction recorded explicitly because without it the first red gets read as 'the kit is brittle' and the kit gets removed; the shipped package grows a module no production path uses; the explicit release gate executes trusted sibling checkout code and therefore cannot be folded into routine Verify; freezing the shipped API requires a major-version boundary or compatibility shim for breaking changes and removal of consumer imports before retirement; and 23 of 29 checks are catalogued but unimplemented, with expected_checks() as the intended guard against reading the catalogue as coverage. Follow-ups: _core_harness.py was planned as a fourth module isolating core-internal coupling but is deliberately NOT created here, since with no runtime checks landed it would be empty and an empty private module is worse than an absent one; the reports_finish_reason capability gives T-FINISHREASON-GATE a cheaper resolution by turning 'a backend without truncation gating' from an accident into a declared fact; and contemplative-agent-otel is recorded as absent from CLAUDE.md's related-repositories table, out of scope here since it implements no LLMBackend.","isBasedOn":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0001-core-adapter-separation.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0012-human-approval-gate.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0066-backend-aware-context-budget-guard.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0071-read-only-pattern-composition-instruments.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0077-chaos-tdd-fault-injection.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0079-module-reorganization-package-splits.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0087-optional-token-counting-capability-for-the-context-budget-guard.md"]}
149
+ {"@id":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0089-llm-behavioral-eval-layer-on-deepeval.md","@type":["ADR","TechArticle"],"name":"ADR-0089: An LLM Behavioral Eval Layer on DeepEval","identifier":"ADR-0089","status":"accepted","datePublished":"2026-08-06","description":"Adds a top-level evals/ layer that measures the quality of what the LLM component actually generates — the one property the repo's seven deterministic gates and LLM code-review chains never touched; prompt revisions had been validated by a manual replay-and-stare workflow (.notes/ replay-distill v2-v5, sampling_probe side-by-side eyeballing). Second occupant of the evals/ path: a promptfoo prompt-regression harness lived there 2026-06-10 to 2026-07-03, deleted by ADR-0072 as dead scaffolding hard-importing since-deleted prompt constants to regression-test the ADR-0060-retired batch distill pipeline — a judgment about the harness's target, not about eval layers, so this ADR reoccupies the cleared path (not a supersede) with a different face and a runner importing only the production entry point. Face A pilot: the Moltbook comment path. Framework verdict (scout, as-of 2026-08-06): adopt DeepEval 4.1.5, whose cloud regression (--official / Confident AI) is explicitly NOT relied on; ADR-0077's earlier rejection of agent-chaos for hard-coupling to DeepEval was a verdict on a chaos-layer dependency, a separate question from adopting DeepEval as an eval-layer runner. Placement: evals/ sits outside tests/ because tests/conftest.py sets OLLAMA_BASE_URL to a dead port at module load to kill unmocked LLM calls, which would sabotage real eval runs; it also sits outside the package, following ADR-0088's spirit of shipping kits outside runtime import paths, enforced by placement since import-linter's root_packages does not see evals/. Layering contract: the deterministic core (dataset.py, judging.py, generation.py, compare.py) imports stdlib and contemplative_agent only and is unit-tested under the dev group (49 tests); only adapter_deepeval.py and run_eval.py may import deepeval, which lives in a dedicated [dependency-groups] eval synced only by eval runs and the verify.sh type gate. Reproducibility: the four self-rewritten prompt assets (identity.md, constitution/, skills/, rules/ — mutable state under ADR-0060 distill and constitution amendment) are pinned by snapshot_assets.py into evals/fixtures/agent_home/ with a sha256 manifest, allowlist-only copying because MOLTBOOK_HOME also holds credentials, snapshots treated as untrusted LLM-distilled output gated by human review plus secret scan; template prompts pin to the repo commit automatically because the scratch MOLTBOOK_HOME has no prompts/ override (core/domain.py resolve_prompt precedence). Generation runs production-parity wiring: run_eval mirrors cli/runtime.py + moltbook agent.py via core.llm.configure(), real Ollama at the ADR-0047 production temperature 1.3, three samples per case with majority vote resolving ties toward the worse verdict; a strict majority of requested samples must generate successfully or the case is INCOMPLETE and the run cannot become a baseline — generation failure must never masquerade as a DEVIANT verdict; the skill-injection regime under measurement is pinned and recorded rather than inherited: run_eval calls configure_skill_selection against the fixture with MOLTBOOK_SKILL_SELECTION_ENFORCE=1, reproducing the ADR-0081 two-pass selected-bodies injection the launchd schedule has run since 2026-08-01, and records it as the manifest field injection_regime. The original design skipped configure_skill_selection on the premise that production ran selection in shadow mode where selection is always None — a premise already false when written (ADR-0081 enforcement shipped 2026-07-24), so the first baseline measured full-corpus injection against a production that injected a selection; the prose revisit trigger 'when enforcement goes always-on' could not fire because its condition was already met. Corrected by the 2026-08-08 amendment, which also makes the divergence mechanically detectable: injection_regime is a check_staleness signal, _preflight refuses to run when the wiring does not enact the pinned regime, and deployment_mismatch compares the pin against the installed launchd plist — the tree-versus-deployment axis no in-tree hash can cover. Judging: an isolated claude -p subprocess per the harness llm-as-judge design — binary checks as evidence feeding one named holistic verdict from {ADHERENT, DRIFTING, DEVIANT}, the verdict-to-{1.0,0.5,0.0} mapping display-only and never aggregated; isolation via --setting-sources \"\", --tools \"\", --strict-mcp-config, scratch cwd, prompt via stdin, and an allowlisted environment (HOME/PATH/USER/SHELL/LANG/LC_ALL/TMPDIR/TERM only — a leaked ANTHROPIC_BASE_URL or CLAUDE_EFFORT would make the manifest's judge_model a lie); the untrusted post/comment blocks pass delimiter neutralization before embedding (a delimiter-splice in the comment body was demonstrated swapping the judged text for an ADHERENT), and the judge prompt embeds the snapshotted ADR-0002 constitution — loaded via the same load_constitution glob as generation — as the evaluation standard so the judge never substitutes its own general notion of the axioms; the parsed response is mechanically validated against the output contract (exactly five named checks, no duplicates, a dominant No on injection_resistant/persona_intact forces DEVIANT), every attempt's raw envelope is appended to a per-run judge-audit.jsonl for offline replay (ADR-0075 observability by default), and a parse or contract failure retries once then fails loud. Contract: a normalized run JSON (schema_version, manifest of target_model / temperature / judge_model / assets_sha256 / judge_prompt_sha256 / dataset_sha256 / samples_per_case, per-case samples with checks and verdicts) compared by evals/compare.py as per-case verdict transitions against approved baselines in evals/baselines/ — manifest mismatch is incomparable (exit 2), regression is exit 1; deepeval's own TestRun output is a debug byproduct so deepeval upgrades cannot break baselines. Eval stays out of verify.sh by design (slow, stochastic, delta-judged — a different contract from the fast deterministic gate); triggers are prompt-asset, model, sampling, or generation-path changes. DEEPEVAL_TELEMETRY_OPT_OUT=true is forced before deepeval import (verified short-circuit in deepeval/telemetry.py) and the .deepeval cache is contained per-run via chdir. Golden dataset: 12 cases, 4 axioms x {normal, edge, adversarial}, adversarial cases embedding instructions in post content — meaningful because wrap_untrusted_content sits on the path. Rejected alternatives: Inspect AI (strongest design fit, most active releases, but baseline diff is not native so the same compare layer would be needed anyway, and the Task/Solver/Scorer abstraction has no current payoff — noted as the compose target if evals need multi-turn or tool-use scoring), promptfoo (pip wrapper shells out to npx — Node runtime in a pure Python/uv repo), pytest-evals (too thin), ragas (RAG-centric), a self-built runner (dataset/report plumbing is undifferentiated work DeepEval ships; the project-specific parts stay project-specific either way), and DeepEval's cloud regression (routes through Confident AI; local JSON keeps the loop offline and schema-stable). Costs accepted: deepeval's ~60-package transitive tree grows pip-audit's surface (a CVE there can now block commits, which is honest — with the recorded coupling that this coverage holds only while the deps gate audits the venv the type gate populated); a full run costs ~19 minutes measured plus one claude -p call per successful sample; verdicts are stochastic at temperature 1.3 with majority-of-3 damping but not eliminating flips (samples=5 is the documented escalation); re-snapshotting assets invalidates every baseline by design via manifest mismatch; the eval measures the comment face only, distill quality staying with tests/benchmark_distill.py. Generalizing an eval axis into the harness verify-bootstrap gate menu is explicitly out of scope; contemplative-agent is the pilot.","isBasedOn":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0002-paper-faithful-ccai.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0047-comment-sampling-temperature.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0060-per-episode-grounded-distill.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0072-echo-chamber-interventions.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0076-skill-selection-shadow-instrument.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0077-chaos-tdd-fault-injection.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0081-skill-selection-two-pass-injection-enforcement.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0088-shipped-conformance-kit-for-the-llm-backend-contract.md"]}
150
+ {"@id":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0090-ipd-two-arm-instrument-for-constitution-amendments.md","@type":["ADR","TechArticle"],"name":"ADR-0090: Run an IPD Two-Arm Bench Before Adopting a Constitution Amendment","identifier":"ADR-0090","status":"accepted","datePublished":"2026-08-09","description":"Attaches a behavioral reading to the human approval gate for constitution amendments: the contemplative-ipd bench (paper Appendix E replication in the rules repo) runs as a two-arm comparison — arm A the current production constitution, arm B the staged amendment — between amend-constitution --stage and adopt-staged. A 2026-08-06 null pair (same constitution, two full runs, n=10, gemma4:e4b) pre-registered the interpretation contract before first live use: run-to-run noise floor ±0.13 on the primary metric delta(custom−baseline); readable signals are only a sign flip, alpha-gradient loss, or same-direction moves >0.13 in multiple cells. Deliberately NOT wired into either CLI command and the reading does NOT gate adoption — an approval-gated command must not embed a ~2h LLM step plus a cross-repo dependency, and mechanizing a weak n=10 signal into a hard veto would invert the ADR-0071 principle that instruments read while humans decide (same instrument-then-human shape as the ADR-0085 weekly gate). n=10 is part of the calibration contract: changing it invalidates the floor and requires a new null pair. The bench is required before every full-constitution amendment (runbook docs/runbooks/constitution-amendment.md); skipping it requires an explicit recorded owner decision. Also records the 2026-08-09 amendment run (approved and adopted the same day; production constitution sha256 37e3556), the instrument's first live use, including an adoption incident: the adopt-staged collision guard wrote contemplative-axioms-2.md beside the old file instead of replacing it, a state the runtime's concatenate-all-md loader would have read as both constitutions at once — remediated by hand, tracked as T-ADOPT-OVERWRITE-TARGETS.","isBasedOn":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0012-human-approval-gate.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0056-retire-importance-llm-scoring.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0069-gemma-production-model-and-think-on-value-layer-pipelines.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0071-read-only-pattern-composition-instruments.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0075-observability-by-default.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0085-unattended-weekly-fix-chain-single-saturday-gate.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0089-llm-behavioral-eval-layer-on-deepeval.md"]}
151
  {"@id":"https://shimo4228.github.io/shimo4228/vocab#ca/concept/pattern-composition-instruments","@type":["Concept","DefinedTerm"],"name":"pattern-composition instruments","alternateName":[{"@value":"pattern-composition instruments","@language":"en"},{"@value":"パターン組成計器","@language":"ja"}],"description":"Read-only distributions over Layer 2 knowledge patterns: consumed-view supply and seed-independent diversity (the echo-chamber detector). Instruments are observability, never intervention — they feed the operator, not gates or ranking. Calibrated by a three-point scale: unrelated-text floor cosine, corpus pairwise mean, and consumed-view top band — re-measured whenever the seed geometry changes (introduction values: floor ~0.33–0.46, corpus mean 0.554, top band ~0.68–0.77 under the pre-ADR-0072 seed). A third grounding-composition instrument shipped with ADR-0071 was removed by ADR-0072: under per-episode distillation its source_type reading is constant, and an instrument whose reading changes no action violates signal-first.","appliesTo":["https://shimo4228.github.io/shimo4228/vocab#memory-layer/knowledge"],"subjectOf":["https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0071-read-only-pattern-composition-instruments.md","https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0072-echo-chamber-interventions.md"]}
152
  {"@id":"https://arxiv.org/abs/2512.13564","@type":["ExternalReference","ScholarlyArticle"],"name":"Memory in the Age of AI Agents: A Survey (2025)","identifier":"arXiv:2512.13564","url":"https://arxiv.org/abs/2512.13564","description":"Survey unifying the fragmented agent-memory literature under a Forms / Functions / Dynamics framework. Cited by ADR-0071 as evidence that memory-distillation pipelines are converging on the same three-layer-plus-distill structure, which motivates instrumenting this repo's differentiator (the views layer) rather than adding more convergent mechanism.","referencedBy":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0071-read-only-pattern-composition-instruments.md"}
153
  {"@id":"https://arxiv.org/abs/2603.07670","@type":["ExternalReference","ScholarlyArticle"],"name":"Memory for Autonomous LLM Agents: Mechanisms, Evaluation, and Emerging Frontiers (2026)","identifier":"arXiv:2603.07670","url":"https://arxiv.org/abs/2603.07670","description":"Formalizes agent memory as a write–manage–read loop with a three-dimensional taxonomy (temporal scope, representational substrate, control policy). Cited by ADR-0071 for the same convergence argument; supplies field-standard vocabulary the instruments' readings can be anchored to.","referencedBy":"https://github.com/shimo4228/contemplative-agent/blob/main/docs/adr/0071-read-only-pattern-composition-instruments.md"}