diff --git a/research/README.md b/research/README.md new file mode 100644 index 0000000..48cdb61 --- /dev/null +++ b/research/README.md @@ -0,0 +1,84 @@ +# Research + +The full research programme behind forgekit: a theory of what a frozen language model +structurally lacks, an architecture that supplies it, two runnable prototypes, and — most +importantly — a pre-registered empirical evaluation that **refuted the prototypes' headline +claims**. + +Read in this order. The later work corrects the earlier work, and the corrections are the +most useful part. + +## Start here: what is actually true + +| | Claimed (self-built demos) | Measured (real data) | +|---|---|---| +| Impact oracle recall | 1.00 | **0.022** — `grep` with no graph beats it ~10× on F1 | +| Router/gate F1 | 1.00 | **0.37** on 80 real GitHub issues/PRs | +| Cost saving | +62.1% | **−20.2%** — routing costs *more* than always-premium | + +After diagnosing and repairing two defects, with parameters frozen before the held-out +repositories were touched: recall **0.653**, F1 **0.416**, beating `grep` (0.371) for the +first time — a real but narrow win. + +The general lesson, demonstrated on our own work: **a self-built demonstration can overstate +field performance by more than an order of magnitude, and careful caveating does not convert +a demonstration into evidence.** + +## The four layers + +### 1. [`cognitive-substrate/`](cognitive-substrate/) — the theory +The originating argument: an LLM is a frozen map `y = f_θ(x)` with three properties — +statelessness, frozen parameters, bounded context — which structurally deny it five faculties +(memory, learning, imagination, self-correction, impact-awareness). The remedy is an external +stateful architecture, not better prompting. + +- `cognitive_substrate_whitepaper.pdf` — the *Theory → Evidence → Build-Map* edition (48pp) +- `EXECUTIVE_SUMMARY.md` — one-page entry point, **carries a status banner: its prototype numbers are refuted** +- `literature/` — the gap map and 32 graded references behind each faculty claim +- `evidence/` — twelve load-bearing industry statistics independently re-grounded and graded + `confirmed` / `vendor-reported` / `unverifiable`, plus an ecosystem map of what the 2026 + Claude-Code stack already solves. Three widely-repeated statistics were caught as + misattributed and dropped. +- `quranic-lens/` — the fourteen-mapping ethical-epistemic reading used as a *design lens*: + it names which safeguards are obligatory rather than optional. It is framing, never + technical authority; no verse is offered as proof of an engineering claim. +- `sources/` — the primary documents the evidence layer was graded against +- `figures/` — the architecture schematics and prototype evaluations + +### 2. [`formal-synthesis/`](formal-synthesis/) — the mathematics +Unifies the substrate theory, the end-to-end reliability framework (F1/F2, Δ*, I1–I4, A1–A7, +T1–T6), and the forgekit implementation, proving they are one object in three vocabularies. +Central result is a two-layer duality: reliability = a probabilistic instruction layer × a +deterministic interception layer, neither alone sufficient. + +**Priority note:** prior-art review found this composition law is standard protection-layer +algebra, and two concurrent preprints derive a strictly more general Bayesian form weeks +earlier. Priority is conceded in the paper. What survives is that both are simulation-only. + +### 3. [`empirical-refutation/`](empirical-refutation/) — the measurement +The pre-registered evaluation that overturned the claims above, the diagnosis of *why*, and +the repair. Includes a replication package with the frozen pre-registration, mined ground +truth, held-out task set, every result with bootstrap confidence intervals, both prototype +versions, and **our own adversarial review listing four numbers we had stated incorrectly +before correction**. + +Also corrects a theoretical claim: perfect recall was inferred from a completeness theorem, +but such a theorem guarantees completeness only *relative to the relation* the closure runs +over — it says nothing about whether that relation contains the edges that matter. + +### 4. [`python-prototypes/`](python-prototypes/) — the code +`impact_oracle/` and `router_gate/`, runnable with their own test suites. The **repaired** +oracle ships inside the refutation's replication package rather than replacing the version +here, so swapping it in stays a deliberate decision. + +## How this programme tries to stay honest + +- Protocols and parameter freezes are declared *before* the data is seen, and amendments are + append-only. +- Every load-bearing statistic is graded by what can actually be traced to a primary source. +- Negative results are reported as findings, not tuned away. +- Reviews of our own work ship alongside it, including the parts that found us wrong. + +Where this falls short is stated too: the pre-registration and parameter freezes were +self-administered with no external timestamping authority, so a reader can verify internal +consistency and the amendment trail but must take the ordering on trust. diff --git a/research/cognitive-substrate/EXECUTIVE_SUMMARY.md b/research/cognitive-substrate/EXECUTIVE_SUMMARY.md new file mode 100644 index 0000000..689de21 --- /dev/null +++ b/research/cognitive-substrate/EXECUTIVE_SUMMARY.md @@ -0,0 +1,102 @@ +> ## ⚠ Status: headline claims in this document are REFUTED +> +> This summary describes the *Theory → Evidence → Build-Map* edition (v2), written before any +> real-repository evaluation existed. A later pre-registered evaluation — see +> [`../empirical-refutation/`](../empirical-refutation/) — overturned both prototype claims reported below: +> +> | Claim below | Measured on real data | +> |---|---| +> | Impact oracle recall **1.00** | **0.022** (9 OSS repos, 801 files); `grep` beats it ~10× on F1 | +> | Router/gate F1 **1.00**, cost saving **+62.1%** | F1 **0.37**; cost saving **−20.2%** (routing costs *more* than always-premium) | +> +> The theory sections remain the programme's working framework. The *numbers* here do not. A repair +> recovered a narrow win (recall 0.653, F1 0.416, beating grep's 0.371), documented in the refutation +> paper. Read this document for the architecture; read the refutation for what is actually true. + +--- + +# A Cognitive Substrate for Coding Agents — Deliverable Package +### Theory → Evidence → Build-Map edition (v2) + +**One-line thesis:** The faculties a coding agent lacks — memory, learning, imagination, self-correction, impact-awareness — are not gaps in the model's *knowledge* but structural consequences of what a frozen transformer *is* (a stateless map `y = f_θ(x)`, fixed weights, bounded window). They cannot be prompted or tooled away; they can only be supplied by **re-wrapping the input→process→output loop** into a closed, stateful cycle around the frozen model. + +**What v2 adds.** The first edition argued the five faculties from first principles and prototyped the one that is buildable today. This edition (1) **grounds the argument in the field's own evidence** — twelve load-bearing pain-point statistics independently re-grounded from primary sources and graded *confirmed / vendor-reported / unverifiable*; (2) adds **six metacognitive mechanisms** the frozen loop also lacks (routing, assumption gate, decomposition, goal-anchoring, anti-over-engineering, inline verification); (3) **maps all eleven capabilities against the real 2026 Claude-Code stack**, marking each solved / partial / residual-gap so we say clearly *what not to build*; and (4) ships a **second runnable prototype** — a complexity-aware router + assumption gate, evaluated live on real models. + +> **Governing discipline (the user's, adopted throughout):** *AI output is mathematically-calculated probability — non-deterministic, and never blindly trusted.* Every claim in this package is graded by how well it is sourced; every prototype decision is a transparent, attributable rule rather than another opaque model call; and trust is always earned by an **external** check, never asserted by the model. + +--- + +## What's in this package + +### 1. The white paper (core deliverable) — 48 pp +- **`cognitive_substrate_whitepaper.pdf`** / **`cognitive_substrate_whitepaper.html`** — the full study, 13 sections + 3 appendices, 7 figures. + - **§1–3** the root cause and the five faculties (from v1): *why* each faculty is structurally absent (P1 statelessness, P2 frozen weights, P3 bounded context), each grounded in the real literature. + - **§4 Evidence** *(new)* — the twelve statistics, re-grounded. 5 confirmed, 5 vendor-reported, 2 unverifiable. + - **§5** the Qur'anic epistemic lens — design framing/ethics, never technical authority. + - **§6 Six mechanisms** *(new)* — M1 routing, M2 assumption gate, M3 decomposition, M4 goal-anchoring, M5 anti-over-engineering, M6 inline verification — each formalized, with ecosystem status and a Qur'anic anchor. + - **§7** the cognitive substrate, now with the six-mechanism metacognitive control layer (Figure 3). + - **§8 Prototype I** the impact oracle (from v1). **§9 Prototype II** *(new)* the router + gate. **§10 Build-map** *(new)* the ranked opportunity list. + - **§11** new-vs-reinvented. **§12** limitations. **§13** conclusion. + +### 2. Prototype I — Codebase World-Model + Impact Oracle +- **`impact_oracle_src.zip`** — parses a codebase (AST) into a **persistent dependency graph**, predicts the **blast radius** of a proposed edit via reverse-dependency traversal with confidence decay. `python demo.py` runs end-to-end; `pytest` → **36 tests pass** with zero setup. Builds opportunity #3. + +### 3. Prototype II — Complexity-aware router + Assumption gate *(new)* +- **`router_gate_src.zip`** — the two mechanisms at the top of the build-map, composed as `gate → route → execute → verify → escalate`. Both are **transparent additive rubrics**, not opaque LLM calls; escalation is driven by an external check. `python demo.py`, `pytest` → **19 tests pass**, `python evaluate.py --live` reproduces the live numbers. +- **`eval_results.json`** — the live evaluation record (real measured tokens). + +### 4. Evidence & ecosystem maps *(new)* +- **`evidence_map.json`** / **`evidence_map.md`** — every load-bearing statistic, its primary source, and its status. +- **`ecosystem_map.json`** / **`ecosystem_map.md`** — every faculty & mechanism vs. the real stack, with residual gap and proposed contribution. + +### 5. Figures & schematics +- **`schematic_loop.png`** (Fig 1) · **`schematic_system.png`** (Fig 2) · **`schematic_extended.png`** (Fig 3, *new* — the six-mechanism control layer) · **`impact_graph.png`** (Fig 4) · **`eval_precision_recall.png`** (Fig 5) · **`schematic_router_loop.png`** (Fig 6, *new*) · **`router_eval.png`** (Fig 7, *new*). + +### 6. Supporting artifacts (from v1) +- **`gap_map.json`/`.md`**, **`references.json`** (32 sources), **`quran_lens.json`/`.md`** (14-row concept→faculty→design-principle mapping). + +--- + +## The honest headline results + +### Prototype I — Impact Oracle (against mutation-derived ground truth, 5 real edits) +| Method | Precision | Recall | F1 | +|---|---|---|---| +| **Graph Oracle** (ours) | 0.63 | **1.00** | 0.75 | +| Grep baseline (what agents do today) | 0.73 | 0.94 | **0.79** | +| Edited-file-only | 1.00 | 0.53 | 0.65 | + +The oracle does **not** dominate F1 — grep edges it at the default threshold, and we say so. What the oracle uniquely provides is **guaranteed recall**: for "show me everything my edit could break," a silent miss costs far more than an extra file to check, and only the structural oracle drives false negatives to zero (precision tunable, best F1 = 0.79 at threshold 0.4). + +### Prototype II — Router + Gate (live, on real models: haiku / sonnet / opus) +| Metric | Result | +|---|---| +| Gate accuracy (should-ask) | 30/30 · precision 1.00 · recall 1.00 | +| Routing accuracy (well-specified tasks) | 21/21 exact tier | +| **Real cost saved vs always-premium** | **62.1%** (same measured tokens) | +| Execution-verified sub-experiment | 3/3 routed-down outputs passed real test cases | + +**Honest caveat (both prototypes):** these are **demonstrations, not benchmarks**. The router's 30-task set is hand-labeled and the rubric thresholds were tuned against it, so perfect separation shows the rubric *can* distinguish these cases — not field accuracy. The oracle's evaluation is 5 mutations + 2 stdlib scale checks. We apply the "retired SWE-bench Verified" caution (§4, confirmed) to our own numbers. + +## What the evidence re-grounding caught + +The independent re-grounding **changed our claims** — three widely-repeated numbers did not survive and are *not* used as fact in this paper: +- **"2.74× more vulnerabilities"** is not traceable to Veracode's own report (only their 45% OWASP figure is); likely conflated with a separate study. +- **"17% lower comprehension / 400K sessions"** merges two different studies — the session study contains no comprehension finding. +- **GitClear 4× vs 8×** internal inconsistency and **JetBrains 77%** could not be located in primary form. + +That a re-grounding pass corrected the paper is the point, not an embarrassment: it is the same discipline the architecture makes structural — *a stored fact is provisional until an external check confirms it.* + +## The build-opportunity map (what to build, what to skip) + +**Already solved — do not rebuild:** M1 routing (model tiering + gateways like LiteLLM/OpenRouter) and M3 decomposition (subagents, Agent-Teams). The router prototype's honest contribution is only the *transparency layer*, and we say so. + +**The genuine whitespace, ranked:** (1) **assumption/uncertainty gate** — the project's named root failure and the field's named gap; nothing supplies calibrated known-unknowns. (2) **validity-anchored memory** — backends store notes, none tracks invalidation-by-correction. (3) **mandatory pre-action impact gate** — indexers retrieve, none is a deterministic blast-radius check. (4) outcome-validated learning. (5) doom-loop / root-cause correction. (6) scope-minimality. This paper prototypes #1 and #3 — the two where a single session can produce checkable ground truth. + +## What is genuinely new vs. reinvented + +Most components are borrowed (external memory, fast/slow learning, code graphs, model tiering — all exist). The contribution is **the composition and the framing**: the closed-loop shape; **validity-anchored memory** (prune by whether a past prediction was confirmed by an *external* oracle, not by the model's own judgment); wiring exact impact analysis into a **mandatory pre-action gate**; a **transparent** router/gate that explains every decision; and deriving *which* safeguards are non-negotiable from a coherent epistemology. That turns scattered literatures and named-but-unsolved gaps into one buildable architecture aimed squarely at coding agents. + +## Scope & limitations (stated honestly) + +Two faculties/mechanisms are prototyped, not eleven. The impact oracle's static analysis is single-language (Python) and conservative on dynamic dispatch. The router/gate rubrics are keyword heuristics tuned on a small hand-labeled set. Memory validity, outcome learning, and doom-loop diagnosis remain *specified but unbuilt* — the harder research gaps, marked as such rather than gestured at with a demo. The lens is framing: reject it and you lose the organizing vocabulary but none of the technical content. diff --git a/research/cognitive-substrate/cognitive_substrate_whitepaper.html b/research/cognitive-substrate/cognitive_substrate_whitepaper.html new file mode 100644 index 0000000..940e8d8 --- /dev/null +++ b/research/cognitive-substrate/cognitive_substrate_whitepaper.html @@ -0,0 +1,1009 @@ + + + + + +A Cognitive Substrate for Coding Agents + + + +
+ +

A Cognitive Substrate for Coding Agents

+
Theory → Evidence → Build‑Map edition. Why a frozen language model structurally lacks memory, learning, imagination, self‑correction, and impact‑awareness — plus six metacognitive deficits the field's evidence names — and how to re‑wrap its input→process→output loop to supply them, with two runnable prototypes as evidence.
+ +
+A first‑principles design study, grounded in field evidence. The five faculties are argued from the shape of a frozen model and grounded in 32 primary sources (memory‑augmentation, continual‑learning, self‑correction, world‑model, and program‑analysis literatures). This edition adds an evidence layer — twelve load‑bearing pain‑point statistics independently re‑grounded from primary sources and graded confirmed / vendor‑reported / unverifiablesix mechanisms (routing, assumption gate, decomposition, goal‑anchoring, anti‑over‑engineering, inline verification), a build‑opportunity map against the real 2026 Claude‑Code stack, and a second prototype (a complexity‑aware router + assumption gate, evaluated live on real models). An epistemological and ethical lens drawn from Qur'anic sources runs throughout, used as design framing, never as technical authority.  |  Companion artifacts: evidence map, ecosystem map, gap‑map, reference list, Qur'anic‑lens table, and two runnable packages (impact‑oracle, router‑gate). +
+ +
+

Abstract

+

A large language model at inference time is, mathematically, a fixed function y = fθ(x) with frozen parameters θ and a bounded input window. From this single fact, five apparent “cognitive” deficits of a coding agent follow as structural consequences, not incidental weaknesses: it cannot remember across sessions, cannot learn from outcomes, cannot imagine the consequences of an action before taking it, cannot reliably correct itself, and does not know what already exists in a codebase or what an edit will affect. We show that neither better prompting nor additional tools (skills, MCP servers) remove these deficits, because they leave fθ and the open‑loop pipeline intact. We then specify a cognitive substrate: an external architecture that keeps the LLM frozen but re‑wraps its input→process→output loop into a closed, stateful cycle over persistent stores — an episodic/semantic memory, an online‑updatable learning layer, a consequence simulator, a metacognitive verification gate, and a persistent structural model of the codebase — all under an explicit stewardship boundary. For each faculty we identify precisely what the existing literature solves and what residual gap remains for a coding agent. To turn the weakest‑evidenced claim into something testable, we build and evaluate the impact‑awareness faculty as a runnable prototype: a Codebase World‑Model that parses a repository into a persistent dependency graph, and an Impact Oracle that predicts the blast radius of a proposed edit. Against mutation‑derived ground truth, the oracle is the only method that never misses an affected file (recall = 1.00 across five tested edits), where a text‑search baseline misses transitive dependents and an edited‑file‑only baseline misses 47% of impact. Throughout, a Qur'anic epistemic lens supplies the design's vocabulary of obligation — know what exists before acting (2:31–32), verify before you act (49:6), pursue not that of which you have no knowledge (17:36), and hold what you can damage as a trust (33:72).

+
+ +
+
1The problem, from the ground
+
2The root cause, formally
+
3Five faculties and their gaps
+
4The evidence: what the field measures
+
5The Qur'anic epistemic lens
+
6Six mechanisms the frozen loop lacks
+
7The cognitive substrate
+
8Prototype I: world‑model & impact oracle
+
9Prototype II: router & assumption gate
+
10The build‑opportunity map
+
11Genuinely new vs. reinvented
+
12Limitations & threats to validity
+
13Conclusion
+
References, evidence & lens appendices
+
+ +

1 The problem, from the ground

+ +

Start with a scene any developer knows. You open an unfamiliar file. Before you change a line, a great deal happens that you barely notice: you recognize what the file is and how it connects to the rest of the system; you recall that you touched something similar last week and how that went; you silently simulate — “if I rename this, the three callers over there break” — and you feel the weight of the fact that this code runs in production. You are, in one glance, exercising memory, a world‑model, imagination, and a sense of consequence. Only then do you type.

+ +

A coding agent built on a language model does none of this by default, and the reason is not that the model is small or under‑trained. It is that the model has the wrong shape for the job. This paper is an attempt to go to the root of that shape — to ask what the input to the model actually is, what happens to it, what comes out, and why that pipeline cannot, on its own, hold the faculties above — and then to design a supporting structure that can, without pretending to rebuild the model or to mimic a human brain. We do not claim to make a machine that thinks like a person. We claim something narrower and buildable: that the specific faculties a coding agent is missing can be given precise mathematical form, and supplied by an external architecture wrapped around a frozen model.

+ +

Two commitments run through the paper. First, honesty about what is known. Some of these faculties — notably persistent memory with a real forgetting policy, and online learning without catastrophic forgetting — are open research problems; we say so, and we say exactly where the open edge is. Others — notably impact‑awareness — turn out to be mostly an engineering gap: the tools have existed since the 1980s but were never wired into a language model's loop. We prototype that one, because it is the one where a single session can produce real evidence rather than a promise. Second, a lens. This project was asked to think with the Qur'an as a source of epistemology and ethics — not as authority for any engineering claim, but as a disciplined vocabulary for naming what an agent that acts on real systems owes: to know before it acts, to verify what it is told, to treat a capability it can misuse as a trust. That vocabulary turns out to map cleanly onto architectural decisions, and we let it guide the design while keeping every technical claim standing on its own merits.

+ +

2 The root cause, formally

+ +

It is tempting to describe an agent's memory or learning problems as things that will improve with scale or a cleverer prompt. That framing is wrong, and being precise about why is the whole foundation of the design. Consider what one turn of an LLM‑based agent actually computes. Let the input be a token sequence x drawn from a context window of bounded size W. The model applies fixed parameters θ and produces a distribution over the next token; sampling and repeating yields the output y. Abstractly:

+ +
(1) +y = fθ(x),  x ∈ 𝕏≤W,  θ fixed for all inferences. +
+ +

Three properties of Equation (1) are the source of everything that follows. They are not bugs; they are what a deployed transformer is.

+ +

(P1) Statelessness. The function has no argument that carries information from one call to the next except x itself. Whatever the agent “knew” during turn t is gone at turn t+1 unless it was serialized back into the token string. There is no hidden variable st that persists; formally, the map is memoryless: yt depends on xt alone, not on the history (x1,…,xt−1).

+ +

(P2) Frozen parameters. θ does not change as a function of what happens at inference. There is no term in Equation (1) of the form θθηL: the gradient step that constitutes learning happens only in an offline training loop the deployed agent never enters. An outcome in session N — a test that failed, an edit the developer reverted — therefore has no path by which it can alter behavior in session N+1.

+ +

(P3) Bounded, undifferentiated context. x must fit in W tokens, and every fact competes for the same space on equal terms. There is no separate, larger store the model can address; “give it more context” is bounded by W and, even within W, provides no structure, no provenance, and no persistence.

+ +

Now watch the five faculties fall out of P1–P3 by deduction, not observation:

+ + + + + + + + + + +
FacultyWhy it is structurally absentFollows from
Memory (across sessions)By P1, nothing survives a turn but the token string; by P3, the string is bounded and lost at session end. There is no addressable store that outlives x.P1, P3
Learning (from outcomes)By P2, no inference‑time event writes to θ. In‑context “learning” is real optimization14,15 but lives only inside the current x and vanishes with it (P1) — a simulation of learning, not learning.P2, P1
Imagination (simulate before acting)Equation (1) maps tokens to tokens. There is no separate forward model of “what happens to the world (or codebase) if I take action a” distinct from emitting more tokens; the model cannot roll out and score a hypothetical it does not also have to narrate.P1
Self‑correctionAny “check” the model runs is another evaluation of the same fθ with the same blind spots. There is no independent verifier inside Equation (1); the literature confirms intrinsic self‑correction is unreliable without an external signal.21P2
Impact‑awarenessBy P3, the model sees only the tokens in x. A million‑line repository does not fit; therefore it cannot know, unaided, what elsewhere depends on the symbol it is about to change.P3
+ +
+
Why prompting and tools do not close the gap
+

A better prompt changes x. More tools (skills, MCP servers, function calls) let the agent fetch new x or emit richer y. Both operate inside Equation (1) and leave P1–P3 untouched: the composed system is still a stateless map with frozen weights and a bounded window. A tool call retrieves a document into context, but nothing decides what was worth keeping, consolidates it, or updates the agent's priors for next time. The deficits are properties of the loop shape — open, memoryless, one‑directional — not of the model's knowledge. To remove them you must change the shape of the loop, which is precisely what an external substrate can do while θ stays frozen.

+
+ +

This reframing is the paper's pivot. If the deficits came from the loop shape, then the remedy is to re‑wrap the loop: keep fθ exactly as it is, and surround it with state and update so that the composite system is no longer memoryless, no longer open, and no longer blind beyond W. Figure 1 states the whole thesis in one picture.

+ +
+Two-panel schematic: (a) the frozen LLM today as a stateless input-process-output pipe with a broken write-back loop; (b) the same LLM re-wrapped as a closed, stateful cognitive cycle. +
Figure 1. Re‑wrapping the input→process→output loop. (a) Today: input enters a bounded window, the frozen model maps it to output, and at session end all state is discarded — there is no path from an outcome back to weights or memory. (b) The proposed substrate keeps the identical frozen model (same blue block) but closes the loop into a cycle — perceive (read memory + world‑model), reason, imagine/reflect, verify/act, then write back and consolidate — so state persists across turns and sessions. Nothing inside the model changes; the shape around it does.
+
+ +

3 Five faculties and their gaps

+ +

Before designing anything, we asked what the research literature has already built for each faculty, and — precisely — what it does not yet give a coding agent. This section is deliberately not a survey for its own sake: for each faculty we state the structural lack (from §2), the best existing approaches with citations, and the residual gap that the substrate must actually close. The discipline throughout is to separate what is solved from what is merely named. All 32 sources are listed in the references; the full structured gap‑map is a companion artifact.

+ +

Memory Persistent experience across sessions

+

The lack. A transformer's only state is its weights (frozen) and its context window (bounded, discarded at session end); every apparent memory is either baked into pretraining or re‑supplied as tokens.

+

What exists. The idea of an explicit, addressable external memory read and written by a neural controller goes back to Memory Networks1 and End‑to‑End Memory Networks2, and to the Neural Turing Machine3 and Differentiable Neural Computer4, which showed a network can learn to read/write an external matrix via differentiable addressing. But those memories are trained jointly with the model and cannot be bolted onto an already‑frozen LLM. The pattern that can attach to a frozen model is Retrieval‑Augmented Generation5: pair the generator with a retriever over an external index. For deployed agents, MemGPT6 adds an OS‑style paging scheme (the model issues calls to move information between context and external storage), and Generative Agents7 add a timestamped memory stream with periodic reflection that synthesizes higher‑level memories.

+

Residual gap. None of these gives a coding agent a memory that is simultaneously (a) persistent across sessions without retraining, (b) structured enough to answer “have I seen this bug/pattern before and what happened,” (c) governed by a principled forget/consolidate policy rather than unbounded growth, and (d) tied to verifiable software artifacts (commits, test outcomes, diffs) rather than free‑text the model wrote about itself. RAG is stateless per‑query lookup; MemGPT and Generative Agents self‑manage paging and reflection with no ground‑truth check on what is kept or discarded. This is a genuine research gap, not just integration.

+ +

Learning Durable update from outcomes

+

The lack. By P2, nothing at inference writes to θ; in‑session adaptation is prompt conditioning that vanishes when context clears.

+

What exists. Neuroscience offers the shape of an answer: Complementary Learning Systems theory8,9 argues intelligence needs two systems — a fast, instance‑based (hippocampal) learner and a slow, structured (neocortical) one — because a single fast learner catastrophically overwrites old knowledge. On the engineering side, Elastic Weight Consolidation10 directly mitigates catastrophic forgetting by protecting parameters important to earlier tasks; LoRA13 makes cheap, modular weight updates feasible by freezing the base and training small low‑rank adapters; Test‑Time Training11 shows weights can be adapted per‑input via a self‑supervised loss; Fast Weights12 give a genuine intermediate timescale of adaptation. And the theory of in‑context learning14,15 shows prompting can implement implicit gradient descent — real optimization, but session‑local.

+

Residual gap. There is no accepted, low‑cost, always‑on pathway that takes a concrete outcome (a test failure, a human revert, a review comment) and durably changes future behavior — either by writing to persistent non‑parametric state or by cheaply updating parameters — without a full offline retraining cycle and without catastrophic forgetting. Existing mechanisms are either real‑but‑deliberate retraining (EWC, LoRA, decoupled from the interaction loop) or real‑but‑ephemeral in‑context simulation. Bridging them into a fast, safe, incremental loop is unsolved.

+ +

Imagination Simulating consequences before acting

+

The lack. Equation (1) is token→token; there is no forward model of action consequences and no rollout loop.

+

What exists. Model‑based RL has built exactly this — for other domains. World Models22 learn a compressed generative model of an environment and train a controller inside the “dream.” MuZero23 plans with a learned latent model of only the quantities relevant to planning (reward, value, policy). Dreamer/DreamerV324,25 learn behaviors purely from imagined latent rollouts across many domains. The free‑energy principle / active inference26 gives the deepest theoretical grounding for why an agent must predict the sensory consequences of hypothetical actions and act to minimize expected surprise.

+

Residual gap. Every one of these targets a continuous perception‑action domain (pixels, physics, game boards) with a learnable dynamics model and a dense reward. None target the discrete, symbolic domain of source code, where the dynamics to imagine are “which call sites break,” “does this still type‑check,” “do the tests still pass.” A coding agent's imagination faculty needs a fast surrogate simulator over code‑change consequences — static analysis, symbolic execution, or an approximate learned model of compile/test outcomes — and no general, reusable such component exists. This is an open build target.

+ +

Self-correction An independent check on one's own output

+

The lack. Any check the model runs re‑evaluates the same frozen weights that produced the error.

+

What exists. Reflexion18 has the agent verbally reflect on task feedback and store it to condition the next attempt; Self‑Refine19 alternates generator and critic roles on the same model; Self‑Consistency20 marginalizes over many sampled reasoning paths. Crucially, trained verifiers16 and process‑level reward models17 decouple checking from generating by using a separately trained model — escaping the same‑weights blind spot.

+
+
The honest negative result
+

Huang et al.21 evaluated intrinsic self‑correction — no external feedback — and found it frequently makes correct answers worse. The approaches that do work (Reflexion, verifiers, process reward models) all inject something the frozen transformer lacks on its own: an external oracle (unit tests, human labels, a separately trained reward model). The lesson for our design is unambiguous: self‑correction must be built as an external verification signal, not more self‑prompting.

+
+

Residual gap. For code specifically, no existing system supplies a cheap, general, always‑available correctness oracle equivalent to a proof checker: tests exist for some repos but are incomplete, and an LLM‑based verifier trained once cannot track an evolving, project‑specific notion of correctness. Building that external, evolving check is the open problem — and it is partly addressable now, because two concrete external signals already exist for code: the type/compile system and the test suite. Our prototype leans on exactly those.

+ +

Impact-awareness Knowing what exists and what an edit affects

+

The lack. By P3 the model sees only tokens in x; a whole repository does not fit, so it cannot know what depends on a symbol it changes.

+

What exists — and this is the key observation. The tools to compute exact structural impact are mature and decades old. The Program Dependence Graph30 (1987) combines control and data dependence in one structure; interprocedural slicing28 (1990) computes what code affects, or is affected by, a given point across function boundaries; program slicing was surveyed as a mature toolbox by 199429. The Code Property Graph31 merges AST, control‑flow, and dependence into one queryable graph. On the learned side, “Learning to Represent Programs with Graphs”27 and code2vec32 let neural models see code structure, not just token sequences.

+
+
The gap here is engineering, not science
+

None of these exact tools are wired into the loop of an LLM coding agent. Today's agents either re‑read raw file text inside a bounded window or rely on the model's own unverified guess about what a change affects. The residual gap is a missing bridge: (a) maintain a live, incrementally‑updated structural graph of the whole repository, (b) let the agent query “what depends on this symbol” as a fast, sound lookup before proposing an edit, and (c) feed the result back into context in a form the model reliably uses. Because this gap is engineering‑shaped rather than an open research question, it is the faculty we can honestly build and evaluate in one sitting — which is exactly what §8 does.

+
+ +

The pattern across all five is worth stating plainly. Memory, learning, and imagination for code are genuine research gaps; self‑correction is partly solved given an external oracle; impact‑awareness is an integration gap over mature tools. A credible substrate therefore does not claim to solve all five — it provides the architecture into which solved components drop in now and open ones drop in as they mature, and it demonstrates the faculty that is buildable today.

+ +

4 The evidence: what the field actually measures

+ +

The first edition of this paper argued the five deficits from first principles — from the +shape of a frozen model, before looking at a single usage statistic. That argument stands on +its own. But a design study that only reasons from first principles invites a fair question: does the +field's own evidence agree that these are the real problems? This edition answers it. We took the +load‑bearing pain‑point statistics that circulate in the 2026 discourse and +independently re‑grounded each one from its primary source — because the project's +governing discipline is that a probabilistically‑generated number, repeated often enough to sound +settled, is still an assumption until you have seen where it comes from.

+ +
+

How we grade evidence — and why it matters here. Each claim below carries a status: +confirmed (traceable to an independent primary source — a peer‑reviewed paper, the +original survey, an official announcement), vendor‑reported (real and sourced, but only to a +company with a commercial stake in the finding, not independently reproduced), or unverifiable +(we could not corroborate it in primary form). This is the paper's own thesis applied to itself: we do not +ask you to trust a figure because it is widely repeated. The re‑grounding changed what we +are willing to assert — and caught three numbers that turned out to be misattributed.

+
+ +

4.1 What the strongest evidence confirms

+ +

Five findings survived re‑grounding to an independent primary source, and they are enough to +carry the argument. The most important is not a vendor's dashboard metric but a +randomized controlled trial. METR studied sixteen experienced open‑source developers across +246 tasks in mature repositories they knew well; the developers forecast a 24 % speedup, +believed afterward they had worked about 20 % faster, and were in fact +19 % slower with early‑2025 AI tools [C1 confirmed · +arXiv:2507.09089]. That single result is the empirical heart of this paper: the gap between the +felt productivity and the measured productivity is exactly the gap a system opens when it +has no calibrated sense of its own uncertainty (mechanism M2 below), and it is why “the model +felt confident” is not evidence of anything.

+ +

The trend evidence is equally well‑sourced. Stack Overflow's 2025 survey of more than 49,000 +developers records trust in AI accuracy falling from 40 % to 29 % even as adoption rose +to 84 %, with the top‑ranked frustration — cited by 66 % — being code +that is “almost right, but not quite”, which the survey ties directly to the +second‑ranked frustration, that debugging AI code is more time‑consuming (45 %) +[C2 confirmed]. Google's DORA program (~5,000 professionals) frames AI as an +“amplifier” — magnifying the strengths of strong teams and the dysfunctions of +weak ones — and still finds it increasing delivery instability at near‑universal +adoption [C5 confirmed]. On the trustworthiness of the benchmarks +themselves, OpenAI retired SWE‑bench Verified in 2026 after auditing found at least +59.4 % of the hard problems it examined had flawed test cases or training‑data +contamination [C6 confirmed] — a caution that applies squarely to our +own prototype's numbers, and one reason we report them the way we do. And the reason an agent +cannot be its own sole judge is not rhetorical: Panickssery et al. (NeurIPS 2024, +Oral) show LLM evaluators recognize and systematically favor their own generations +[C12 confirmed · arXiv:2404.13076] — the empirical foundation for +insisting that verification be external.

+ +
+

These five are enough. A randomized trial (miscalibration), a 49,000‑person survey +(“almost right”), a 5,000‑person study (instability), a benchmark retirement (don't trust +the metrics), and a peer‑reviewed result (an LLM favors its own output). Each maps onto a specific +deficit this paper's architecture supplies — and none depends on a vendor's self‑report.

+
+ +

4.2 What is real but vendor‑reported — and what did not survive

+ +

Several widely‑cited figures are real and sourced but trace only to a company selling a +remedy for the problem the figure describes; we use them as corroboration, not proof, and we say so. +Veracode reports 45 % of AI‑generated samples introduce an OWASP‑Top‑10 +vulnerability [C3 vendor]; Faros' telemetry across 22,000 developers +reports median PR‑review time up 441.5 % and 31.3 % of PRs merged with no +review [C7 vendor]; Sonar reports the sharpest single number in the +whole discourse — 96 % of developers do not fully trust AI code, yet only 48 % always +verify it, a 48‑point “verification gap” +[C9 vendor]. These are consistent with the confirmed evidence and with each +other, which is why we cite them — but a reader should weigh them as vendor telemetry, not as +independent science.

+ +

The discipline earned its keep on three claims that did not survive, and which this paper +therefore does not repeat as fact:

+ + +

That a re‑grounding pass changed our own claims is the point, not an embarrassment. It is the +same move the architecture in §7 makes structural: a stored fact is provisional until an +independent check confirms it. A full source‑by‑source table — every claim, its +primary citation, and its status — is in the Evidence appendix. The mechanisms that follow are +each motivated by a confirmed finding wherever one exists, and lean on vendor evidence only where +that is the best the field currently offers.

+ +

5 The Qur'anic epistemic lens

+ +
+
How this lens is used — and how it is not
+

The Qur'an is used here as a framing lens and ethics source, never as technical authority for an engineering claim. No verse is cited to prove that an algorithm works or that a data structure is correct — those claims stand on their engineering merits alone (§3, §8). What the lens supplies is threefold: (1) a precise vocabulary of obligation for what an agent that acts on real systems owes — to truthfulness, to verification, to stewardship; (2) a hierarchy of knowledge (‘ilm → fahm → ḥikma: knowledge → understanding → wisdom) that motivates a layered memory architecture rather than a flat vector store; and (3) ethical constraints on autonomy that translate into concrete safeguards. Where a mapping is marked load‑bearing, the concept motivates a specific design decision (e.g. a mandatory, not optional, verification gate); where marked metaphor, it is illustrative. Canonical text below is presented directly and attributed; it is not paraphrased. Arabic and translations were retrieved from quran.ai; the full 14‑row mapping table is in the appendix.

+
+ +

The lens earns its place because the deepest failure modes of an autonomous coding agent are not computational but epistemic and ethical: acting without knowing, trusting a report without checking it, and treating a granted capability as license. The Qur'anic vocabulary names these with unusual precision, and three verses in particular map so directly onto architectural decisions that they shaped the design rather than decorating it.

+ +
+
17:36 — lā taqfu · the root of impact‑awareness  [load‑bearing]
+
وَلَا تَقْفُ مَا لَيْسَ لَكَ بِهِ عِلْمٌ ۚ إِنَّ السَّمْعَ وَالْبَصَرَ وَالْفُؤَادَ كُلُّ أُولَٰئِكَ كَانَ عَنْهُ مَسْئُولًا
+
“Do not follow blindly what you do not know to be true: ears, eyes, and heart, you will be questioned about all these.”
+
→ Design principle. Before any mutation (write, delete, refactor), a pre‑action gate must establish what the agent actually knows: which entities the change affects, whether the relevant files/tests/dependents were actually read, and whether the predicted outcome rests on evidence rather than a pattern‑matched guess. Actions taken without verified knowledge are blocked, not merely flagged. The verse's own structure — “ears, eyes, heart… questioned about all these” — maps to an audit trail: every channel the agent used (what it read, inferred, assumed) is logged so the decision can be reconstructed and questioned. This is precisely the impact oracle of §8.
+
Grounded with quran.ai: fetch_translation(17:36, en-abdel-haleem); fetch_tafsir(17:36, en-ibn-kathir)
+
+ +
+
49:6 — tabayyun · the verification gate  [load‑bearing]
+
يَا أَيُّهَا الَّذِينَ آمَنُوا إِن جَاءَكُمْ فَاسِقٌ بِنَبَإٍ فَتَبَيَّنُوا أَن تُصِيبُوا قَوْمًا بِجَهَالَةٍ فَتُصْبِحُوا عَلَىٰ مَا فَعَلْتُمْ نَادِمِينَ
+
“Believers, if a troublemaker brings you news, check it first, in case you wrong others unwittingly and later regret what you have done.”
+
→ Design principle. The architecture places a verification step between receiving information (from context, tool output, or its own prior reasoning) and acting on it. The operative term tabayyun demands active investigation, not passive acceptance: before applying a fix based on an error report or its own diagnosis, the agent re‑reads the current file state, confirms the issue still exists, and checks the fix introduces no new breakage detectable by types or tests. The gate is architectural and mandatory — the verse's command is categorical, not conditional on the reporter's trustworthiness — which is exactly the design lesson the self‑correction literature reached empirically21: a real external check, not more self‑prompting.
+
Grounded with quran.ai: fetch_translation(49:6, en-abdel-haleem); fetch_tafsir(49:6, en-ibn-kathir)
+
+ +
+
2:31–32 — ta‘līm al‑asmā' · the world‑model  [load‑bearing]
+
وَعَلَّمَ آدَمَ الْأَسْمَاءَ كُلَّهَا ... قَالُوا سُبْحَانَكَ لَا عِلْمَ لَنَا إِلَّا مَا عَلَّمْتَنَا
+
“He taught Adam all the names [of things]… They said, ‘May You be glorified! We have knowledge only of what You have taught us.’”
+
→ Design principle. Knowledge begins with naming — identifying entities and their relations. The agent must hold a structured map of what exists in the codebase (files, functions, classes, dependencies), not a flat listing: knowing that A calls B, that module X depends on Y, that test T covers class C. The angels' admission — “we have knowledge only of what You have taught us” — is a startlingly exact description of the LLM's own situation under P3: it knows only what is in its window. The external world‑model supplies the “names” of entities that exceed context capacity.
+
Grounded with quran.ai: fetch_translation(2:31-32, en-abdel-haleem)
+
+ +
+
33:72 — al‑amāna · stewardship & bounded autonomy  [load‑bearing]
+
إِنَّا عَرَضْنَا الْأَمَانَةَ عَلَى السَّمَاوَاتِ وَالْأَرْضِ وَالْجِبَالِ فَأَبَيْنَ أَن يَحْمِلْنَهَا ... وَحَمَلَهَا الْإِنسَانُ ۖ إِنَّهُ كَانَ ظَلُومًا جَهُولًا
+
“We offered the Trust to the heavens, the earth, and the mountains, yet they refused to undertake it and were afraid of it; mankind undertook it — they have always been inept and foolish.”
+
→ Design principle. An agent that can modify a codebase bears an amāna — accepted responsibility for something it can damage. The verse's structure is the design: the heavens declined the trust, recognizing its weight; the human bore it and is called ẓalūman jahūlā (given to wrong and ignorance). So the architecture (a) operates under least privilege — a granted capability is never blanket permission; and (b) assumes the agent will err and builds in reversibility (sandboxing, staged commits, rollback), audit, and scope bounds as structural safeguards. The trust is not “the agent is trustworthy”; it is “the agent has accepted accountability for a domain it can harm, and the architecture must respect that weight.” This is the governance boundary enclosing the entire system in Figure 2.
+
Grounded with quran.ai: fetch_translation(33:72, en-abdel-haleem); fetch_tafsir(33:72, en-ibn-kathir)
+
+ +

Four further anchors complete the mapping (full text in the appendix). 20:114“rabbi zidnī ‘ilmā,” “My Lord, increase me in knowledge” — frames knowledge as perpetually incomplete and growing, motivating the continual‑learning store that accumulates across sessions. 96:1–5iqra' and the teaching “by the pen” (al‑qalam) — is the principle of externalized memory: the pen turns ephemeral thought into durable record, exactly the write‑back mechanism a bounded context window requires. 4:82 and 47:24tadabbur, deep reflection, whose root d‑b‑r concerns “what comes after” / consequences — ground the metacognitive controller as a structured trace‑forward through consequences (“if I apply this, what breaks?”), not a vague confidence score. And the classical epistemic ladder ‘ilm → fahm → ḥikma motivates the three‑layer memory of §7: raw logs, consolidated patterns, decision support — dumping everything into one flat store collapses the hierarchy and loses the distinction between fact and actionable understanding.

+ +

The remarkable thing is not that these mappings are poetic; it is that they are operational. “Verify before acting” is not a sentiment here — it is a mandatory gate in the action pipeline. “Know the names of things” is not a metaphor — it is a dependency graph. The lens told us which safeguards are non‑negotiable; the engineering told us how to build them.

+ +

6 Six mechanisms the frozen loop also lacks

+ +

The five faculties of the first edition answer “what cognitive capabilities does a stateless model +structurally lack?” This edition adds a second family of deficits that the field's evidence forced +into view — not cognitive faculties but metacognitive and resource‑allocation +ones: knowing how much effort a task deserves, knowing what you have not been told, knowing when to split +work, when you have drifted, when you have over‑built, and when to check. A frozen map +y = fθ(x) lacks these for the same reason it lacks the first five: +each requires state the model does not carry and a decision about the computation itself +that a single forward pass cannot make. We formalize six.

+ +
+

A note on honesty before we start. Two of these six are already largely solved by +existing tooling, and we say which (M1, M3). Naming a mechanism is not claiming to have invented it. The +contribution of this section is the unified account — showing that all six fall out of the +same frozen‑loop shape, and that the genuinely unsolved ones (M2, M5) are unsolved for a structural +reason, not for lack of effort.

+
+ +

5.1 M1 — Complexity‑aware routing

+

The deficit. A frozen model has no notion of its own running cost. The same +fθ is invoked whether the task is is_prime(n) or a +distributed rate‑limiter, and a premium model billed per token spends the same premium rate on both. +The project stated it plainly: “a simple prime‑number finder — if you use [a premium +model] it will not give you extra.” Formally, let a task x have +an intrinsic complexity c(x) and let a tier ladder +T1 < … < Tk have costs +κ1 < … < κk. Routing selects the +cheapest tier whose capability covers the task:

+
+route(x) = min{ Ti : capable(Ti, c(x)) }, then escalate Ti +→ Ti+1 only if an external check on the output fails. +
+

The escalation clause is what makes this safe: the worst case is a cheap attempt plus a premium attempt, +the common case is cheap alone, and the decision to spend more is driven by a verified failure, +never by the model's self‑assessment. Ecosystem status: largely solved. Model tiering and +gateways (LiteLLM, OpenRouter, per‑agent model: fields) already route by cost. What they +do not give is a transparent, per‑task, auditable complexity judgment the user can +see and override before dispatch — that thin transparency layer is the only thing left to build, and +our prototype (§9) builds it. Anchor: 17:36, “do not pursue what you +have no knowledge of” — spend capability in proportion to what the task actually requires.

+ +

5.2 M2 — The assumption / uncertainty gate root failure

+

The deficit. This is the failure the project named as central: “the biggest problem is +Assumption. If it doesn't have enough context it will assume many things.” A model that computes +arg maxy P(y \mid x) always returns some most‑likely +continuation, even when x under‑determines the task — there is no term in +the objective that fires when the input is insufficient. The model cannot distinguish “I +know this” from “this is merely the least‑improbable guess.” This is precisely what +the METR trial measured from the outside: confident forecasts, slower reality +[C1 confirmed]. Formally, define a specification‑completeness +functional s(x) ∈ [0,1] over the dimensions a task needs pinned down (inputs +and outputs, target scope, success criteria). The gate interposes before execution:

+
+if s(x) < τ :  halt and emit the missing‑information questions | else : +proceed to route(x). +
+

The gate spends zero generation tokens on an under‑specified request. Asking one question +is cheaper than the “almost right, but not quite” rework loop that 66 % of developers +report [C2 confirmed]. Ecosystem status: residual gap — genuine +whitespace. Nothing in the 2026 stack supplies calibrated “known‑unknowns”: the +pain‑point survey names it directly — “models rarely signal uncertainty or say +‘I can't do this’” — and spec‑driven‑development tools only help +when the human already wrote a complete spec, which is the assumption the gate is meant to remove. Our +prototype builds this too. Anchor: 49:6, tabayyun — “if a +source brings you news, verify it”: the discipline of not acting on an unverified report is exactly a +gate on insufficient input.

+ +

5.3 M3 — Task / session decomposition

+

The deficit. A bounded, undifferentiated window (property P3) means a long session accretes +unrelated sub‑tasks that compete for attention and degrade retrieval. The project's remedy was exact: +“instead of using multiple sessions for multiple independent tasks… we normally do full +things in a single session.” Formally, given a task set with a dependency relation, the +decomposition problem is to partition into contexts C1, …, +Cm that minimize cross‑context coupling while keeping each context's working set +inside the window — independent components run in isolated sessions, dependent ones share state. +Ecosystem status: solved. Subagents with isolated windows, the experimental Agent‑Teams +pattern, and git‑worktree fan‑out already implement this well; the only residue is that +choosing the partition boundary is still a human heuristic. We flag it and move on — a paper +that claimed to reinvent subagents would be exactly the over‑selling this project forbids. +Anchor: 20:114, “do not hasten…” — ordered, separated +pursuit over one overloaded pass.

+ +

5.4 M4 — Goal‑anchoring against drift

+

The deficit. To a text model, “generation of a long story and code is the same +concept” — both are just high‑probability token sequences — so nothing +intrinsic keeps output tethered to the objective rather than to local fluency. The project: the +agent “diverts from the main goal.” Formally, let g be +the goal representation fixed at t=0 and yt the +work in progress; drift is a rising divergence D(yt, g). Anchoring adds +a periodic check that re‑validates yt against +g and corrects when D exceeds a bound — the goal is +re‑read, not assumed to still be in view. Ecosystem status: partial. CLAUDE.md +and /goal hold a static anchor, but the field documents it decaying within a session +(“context compression wiping scrollback”), and the open gap is that “specs drift out +of sync with code” with no tool continuously re‑verifying the two. Anchor: +the ḥifẓ / murāja’a discipline — retention through active +review, not one‑time loading.

+ +

5.5 M5 — Anti‑over‑engineering residual gap

+

The deficit. The maximum‑likelihood objective favors the elaborate completion: more +abstraction, more defensive scaffolding, more “production‑ready” ceremony than the task +asked for. The project named the cost precisely: “the default version will be +over‑engineering — waste of tokens + time + quality and cost.” Formally, let a +solution have footprint φ(y) (files touched, abstractions introduced, +lines added) and let the task imply a minimal sufficient footprint +φ*(x). Over‑engineering is φ(y) − +φ*(x) > 0; the check flags scope the task did not request. Ecosystem status: residual +gap. The one discipline that exists — the frontend‑design skill's minimalism rule — +is explicitly UI‑only; no general tool measures unnecessary abstraction against the stated task, and +the failure is invisible to the review agents that scan for bugs. Anchor: 7:31, +“…do not be excessive” — sufficiency as a virtue; the least structure that meets +the need.

+ +

5.6 M6 — Inline verification

+

The deficit. A human “interprets logic while writing… its real‑time +verification”; a frozen model emits the whole sequence and only afterward can anything check it. +Verification is deferred, and the field's sharpest statistic is the size of that deferral: the +48‑point gap between the 96 % who distrust AI code and the 48 % who always verify it +[C9 vendor], with the deferred review time itself up 441.5 % +[C7 vendor]. And the verifier cannot be the same model, because an LLM favors +its own output [C12 confirmed]. Formally, interleave an external check +v(·) at each meaningful step j rather than once at the +end: y = (y1, …, yn) with +v(yj) gating yj+1 — the same +external‑check principle the substrate uses at the architecture level (§7, the mandatory +verify‑gate), pushed down to the generation step. Ecosystem status: partial. Streaming and PostToolUse hooks give passive +visibility and post‑edit linting, but no shipped mechanism forces an interpretive checkpoint +during generation. Anchor: 49:6 again, and 17:36 — verification as a +continuous obligation, not a final formality.

+ +
+

The pattern across all six. Each mechanism is a decision about the computation that a +single forward pass cannot make: how much to spend (M1), whether to proceed (M2), how to split (M3), +whether you have drifted (M4), whether you have over‑built (M5), whether to check now (M6). None can +live inside fθ; all live in the stateful wrapper around it +— which is the same conclusion the five faculties reached, arrived at from the direction of +resource and control rather than cognition.

+
+ +

7 The cognitive substrate

+ +

We now specify the architecture. The design rule is strict: the LLM stays frozen. We add no term that modifies θ. Everything is external state and external update, composed so that the system — not the model — acquires the missing faculties. Where §2 wrote the agent as the memoryless map y = fθ(x), the substrate replaces it with a stateful operator over a persistent store M:

+ +
(2) +(yt, Mt+1) = F( xt, Mt; fθ ) +
+ +

Read Equation (2) against P1–P3: it takes the previous store Mt as an explicit argument (defeating statelessness, P1), it returns an updated store Mt+1 (a write‑back path that P2 forbade for weights, now legal because it targets external state), and M can be arbitrarily larger than the window W (defeating P3). The frozen fθ appears only as a subroutine. The composite F is what Figure 1(b) draws and what the rest of this section defines.

+ +
+Layered architecture: input and output rails; a five-stage faculty pipeline (perceive, reason, imagine, verify/act) with a metacognition collar around the frozen LLM; four persistent stores beneath; a write-back/learn band; all enclosed in a stewardship boundary. Each faculty carries a Quranic anchor. +
Figure 2. The cognitive substrate for a coding agent. A five‑stage faculty pipeline wraps the frozen LLM (“REASON”): ① perceive reads memory and queries the world‑model; ② reason is the unchanged model; ③ imagine dry‑runs consequences; ④ metacognition (the collar) checks self‑consistency; ⑤ verify/act is the impact oracle plus the mandatory gate. Beneath sit four persistent stores (episodic/semantic memory, learned priors, the codebase world‑model graph, the reflection log); the ⑥ write‑back/learn band captures each outcome and consolidates it into those stores. The whole system runs under a stewardship boundary (least privilege, reversibility, audit, scope). Each faculty is tagged with its Qur'anic anchor (§5) and targets a residual gap from §3. The verify faculty (heavy border) is the one prototyped in §8.
+
+ +

7.1 The five faculties, formally

+ +

Perceive — memory as an addressable store. Let the memory be a growing set of records M = {mi}, each an embedding‑keyed entry with provenance (a commit, a test outcome, a past edit) and metadata (timestamp, access count, validation status). Perception retrieves a relevant slice by a score that — following Generative Agents7 but adding a validity term the literature lacks — combines relevance, recency, and grounded importance:

+
(3) +retrieve(x, M) = top‑ki  σ​( α·rel(x,mi) + β·rec(mi) + γ·val(mi) ) +
+

The val term — did this memory's prediction later prove correct against a test or commit? — is the load‑bearing addition: it is what lets memory be pruned by ground truth rather than by the model's own say‑so, the gap named in §3. This is the ‘ilm layer of the epistemic ladder.

+ +

Reason — the frozen model, unchanged. The LLM receives an assembled context: the raw request plus the retrieved memory slice plus the world‑model's answer to “what does this touch?” It contributes exactly what it is good at — synthesis, code generation, natural‑language understanding — and nothing is asked of it that P1–P3 forbid.

+ +

Imagine — a consequence simulator. Define a surrogate dynamics model g that maps a proposed action a and current codebase state C to a predicted outcome without touching the real repository:

+
(4) +ĉ​  = g(a, C)  →  predicted { broken call sites, type errors, failing tests } +
+

Unlike World Models or MuZero22,23, g here need not be learned from pixels or reward: for code it can be partly exact — static analysis and the dependency graph give sound over‑approximations of “what breaks” — and partly cheap simulation (run the affected tests in a sandbox). This is the faculty the literature has not built for the symbolic domain (§3); the impact oracle of §8 is a first, exact‑analysis instance of g.

+ +

Metacognition — a structured self‑consistency pass. Following the honest lesson of §3—§5 (self‑critique on the same weights is unreliable21; a real external check is required), the controller does not ask the model “are you sure?” It runs a tadabbur trace‑forward: it checks the proposed action against (i) the model's own stated plan, (ii) the type system, and (iii) the existing test suite — three signals at least two of which are external to fθ. Inconsistency halts and backtracks rather than proceeds.

+ +

Verify/act — the mandatory gate. The tabayyun gate (49:6) is a hard predicate on the assembled evidence E(a): the action proceeds only if the impacted set has been computed, the relevant state re‑read, and no external check contradicts the prediction.

+
(5) +act(a) allowed  ⇔  gate(E(a)) = ✓  ∧  scope(a) ⊆ granted +
+ +

7.2 Learning without touching θ

+

The write‑back band closes the loop. After an action resolves, its outcome — test pass/fail, a human revert, a review comment — is a labeled training signal, the external oracle §3 said learning requires. Two update channels, both leaving θ frozen, are available and are ordered by cost:

+
    +
  1. Non‑parametric (always‑on): write the outcome to M with its provenance, and update the val scores of the memories that informed the action. This is instant, reversible, and the primary path — the fast, hippocampal side of Complementary Learning Systems8,9.
  2. +
  3. Parametric (deliberate, optional): when a pattern recurs with high validated confidence, distill it into a small LoRA adapter13 trained offline — the slow, neocortical side — with EWC‑style protection10 against forgetting. This never runs inside the interaction loop.
  4. +
+

The consolidation process between them is the ḥifẓ + murāja‘a principle: periodic review that reinforces recurrent high‑value patterns, decays stale entries, and resolves contradictions — the forgetting policy whose absence §3 flagged in RAG and MemGPT. It is what keeps M from growing without bound and drowning signal in noise.

+ +
+
What is genuinely load‑bearing here
+

The architecture's one non‑obvious commitment is that learning and memory are anchored to verifiable software artifacts — commits, type checks, test outcomes — rather than to the model's own summaries of itself. This is the single design choice that separates the substrate from “RAG plus a scratchpad,” and it is possible only in domains that have a cheap external oracle. Code is such a domain. That is why a coding agent, and not a general chat agent, is the right first target — and why the faculty we prototype next is the one where that oracle is exact. Figure 3 draws the complete picture: the five faculties of this section governed by the six mechanisms of §6 as a metacognitive control layer.

+
+ +
+The extended cognitive substrate: a six-mechanism metacognitive control layer (routing, assumption gate, decomposition, goal-anchoring, anti-over-engineering, inline verification) sits above the five-faculty pipeline, which reads and writes four persistent stores, all enclosed in a stewardship boundary. Each mechanism is marked solved, partial, or residual gap. +
Figure 3. The substrate, extended with the six mechanisms of §6. The five‑faculty pipeline of Figure 2 (perceive→reason→imagine→verify/act) is now governed by a metacognitive control layer — the six mechanisms that decide about the computation itself: how much to spend (M1), whether to proceed (M2), how to split (M3), whether it has drifted (M4), whether it has over‑built (M5), when to check (M6). Each is tagged with its ecosystem status — solved, partial, or residual gap — and the two prototyped in this edition (M1 routing, M2 gate) are marked. Beneath sit the same four persistent stores; the whole runs under the stewardship boundary (amāna, 33:72).
+
+ +

8 Prototype: a Codebase World‑Model & Impact Oracle

+ +

Design papers are cheap; the discipline is to build the one faculty where a claim can be tested in a single sitting. That faculty is impact‑awareness (§3: mature tools, missing bridge). We implemented two of the substrate's components as a runnable Python package: the Codebase World‑Model (the “perceive” store, 2:31–32) and the Impact Oracle (an exact instance of the “imagine→verify” simulator g, 17:36). The full source, demo, and tests are the companion artifact impact_oracle_src.zip.

+ +

8.1 What it does

+

World‑model. A parser walks a repository with Python's ast module and builds a directed graph whose nodes are symbols — modules, classes, functions, methods, module‑level names — with stable qualified IDs (pkg.mod.Class.method) and metadata (file, line, kind, signature). Edges capture five structural relations: imports, calls, inherits, references, contains. The graph is persisted to disk keyed by a per‑file content hash, so an unchanged file is never re‑parsed — the “persistent memory of what already exists,” incremental by construction.

+

Impact oracle. Given a proposed change to a symbol X, the oracle traverses the graph along reverse dependency edges (who calls / imports / inherits / references X), transitively, assigning each reached node a confidence that decays with hop distance and edge type. The output is a ranked blast radius — the set of symbols and files predicted to be affected — each with an explanation path back to X, and a tunable confidence threshold. Figure 4 shows one such propagation.

+ +
+Node-link graph of impact propagation from validate_positive to 27 symbols across 7 files, nodes colored by confidence (dark red = changed symbol, salmon = high confidence, pale = lower confidence), edges colored by relation type (calls, references, inherits, imports, contains). +
Figure 4. Predicted blast radius of one edit. Changing utils.validation.validate_positive (dark red, center) propagates along reverse‑dependency edges to 27 symbols across 7 files. Node shade encodes confidence (high → pale by hop distance); edge style encodes relation (calls, references, inherits, imports, contains). This is the “imagine” faculty made concrete: the consequence set is computed before any edit is applied.
+
+ +

8.2 How we evaluated it — against ground truth, not self‑grading

+

The temptation in a prototype is to let the system grade its own homework. We refused that. Ground truth comes from mutation testing, which is independent of the graph the oracle uses: we built a realistic 10‑module demo package (classes, cross‑module imports, inheritance, call chains) with a 36‑test pytest suite; then for each of five target symbols we actually mutated the symbol to break its contract and ran the suite. The set of files whose tests then failed is the true behavioral blast radius — observed, not predicted. We compared three predictors against it:

+ + +
+
1.00
Oracle recall
(mean over 5 edits)
+
0.63
Oracle precision
(threshold‑tunable)
+
0.94
Grep recall
(misses transitive)
+
0.53
Edited‑file recall
(misses 47% of impact)
+
+ +
+Two panels. Left: grouped bars of precision, recall, F1 for Graph Oracle, Grep, and Edited-file-only. Oracle has recall 1.00; edited-file-only has precision 1.00 but recall 0.53. Right: precision, recall, F1 vs confidence threshold, with best F1 0.79 at threshold 0.4. +
Figure 5. Honest evaluation against mutation‑derived ground truth. (left) The oracle is the only method with perfect recall (1.00) — it never misses an affected file — at a precision cost (0.63) versus grep (0.73). Edited‑file‑only achieves perfect precision but catastrophic recall (0.53), missing nearly half of all real impact. (right) Precision and recall trade off with the confidence threshold; best F1 = 0.79 at threshold 0.4. The chart title states the result plainly, including where grep leads on F1 — we do not oversell.
+
+ +

8.3 Reading the result honestly

+

The oracle does not dominate every metric, and the paper is stronger for saying so. On F1 at the default threshold, the grep baseline (0.79) slightly edges the oracle (0.75). What the oracle uniquely provides is guaranteed recall: across all five mutations it never once missed a file that actually broke, whereas grep missed transitive dependents (a caller that never mentions the symbol by name) and edited‑file‑only missed 47% of real impact. For the question that matters when you are about to change production code — “show me everything that could break” — a false negative (a silent breakage) is far more costly than a false positive (an extra file to glance at), and only the structural oracle drives false negatives to zero. Its precision, moreover, is tunable: Figure 5(right) shows the operating point can be moved along the curve, where neither text baseline offers such a control.

+ +

It also scales. Beyond the toy package, the same parser handled real standard‑library code: it built a 303‑node graph of the json package in 18 ms and a 1,903‑node graph of the http package in 91 ms, answering impact queries in under a millisecond. The approach is not a toy that only works on toys; it is a mature technique that simply had not been placed in the agent's loop.

+ +
+
What this proves, and what it does not
+

Proves: the impact‑awareness faculty of the substrate is buildable today, runs on a laptop, persists its world‑model, and beats the two strategies a context‑bounded LLM agent actually uses — on the metric (recall) that governs safety — against independent ground truth. Does not prove: that the other four faculties are equally easy (they are not — §3), that this Python‑ast analysis handles dynamic dispatch, reflection, or cross‑language repos (it does not yet — §12), or that the whole substrate has been built end‑to‑end (it has not). This is one faculty, demonstrated; the rest is specified and argued.

+
+ +

9 Prototype II: a complexity‑aware router and an assumption gate

+ +

The impact oracle prototyped one faculty. This second prototype builds the top of the +build‑opportunity map from the other direction — the two mechanisms whose pain the field's +evidence supports most directly: M1 complexity‑aware routing and M2 the assumption gate. +They compose into a single decision loop, and the whole thing runs live on the real model ladder, so the +numbers below are measured, not asserted.

+ +

+The request decision loop +
Figure 6. The composed loop: an incoming request first meets the +assumption gate, which halts and asks if the specification is incomplete (M2); a well‑specified +request is scored by the router and sent to the cheapest capable tier (M1); the output is checked by +an external verifier, and only a verified failure escalates one tier up. Every decision is a +transparent rubric — never another opaque model call.

+ +

9.1 The design commitment: transparent rubrics, external trust

+

The project's discipline — “never trust AI output; it is mathematically‑calculated +probability” — rules out the obvious lazy design. We do not ask a second LLM +“how hard is this task?” or “is this well specified?”, because that merely moves the +untrusted probability up a level and hides it. Instead both the router and the gate are +transparent, additive rubrics over explicit features. The router scores algorithmic and +architectural signals, moderate‑complexity markers, multi‑step structure, and length, and +subtracts for trivial‑task markers — every point attributable to a named feature the +user can inspect and override. The gate scores information content: concreteness anchors (a code +fence, a call signature, a worked input→output example, a named file), specific named +technologies, minus vague fillers and brevity. Neither delegates its judgment to a model. And escalation +— the only path that spends premium tokens — is driven by an external check on the +output, the same principle the substrate uses at the architecture level (the mandatory verify‑gate, +§7) and M6 uses at the generation step.

+ +

9.2 How we evaluated it — live, on real models

+

We hand‑labeled a 30‑task set: eight trivial, seven moderate, six complex (each with a +gold tier), and nine deliberately under‑specified (gold label: should ask). We ran every task +through the full loop live on the actual ladder — cheap = claude‑haiku‑4‑5, +mid = claude‑sonnet‑5, premium = claude‑opus‑4‑8 +— measuring real token counts from each call. Cost is exact arithmetic on those measured +tokens against published per‑tier list prices; the always‑premium baseline reprices the +identical tokens at the top tier, so any saving comes purely from tier selection.

+ +

+Router and gate live evaluation +
Figure 7. Live evaluation. (a) Real cost for the 21 executed tasks: +complexity‑routing spends 62 % less than always‑premium on the same measured tokens, +with most tasks served by the cheap and mid tiers. (b) All 30 decisions: every well‑specified +task routed to its gold tier (green/orange/red by tier), every under‑specified task halted by the gate +(purple ×). No errors on either axis.

+ +
+
30/30
gate accuracy
(P = R = 1.00)
+
21/21
routing exact‑tier
(well‑specified)
+
62.1%
real cost saved
vs always‑premium
+
3/3
routed‑down outputs
passed execution tests
+
+ +

The gate halted all nine under‑specified tasks (“Fix the bug.”, +“Optimize it.”) with concrete clarifying questions and spent zero generation tokens on +them; it passed all 21 well‑specified tasks through. The router placed every one of those 21 on its +gold tier. Across the executed workload the loop spent $0.54 versus $1.42 for +always‑premium — a genuine 62.1 % reduction on real tokens.

+ +

9.3 Reading this result honestly

+
+

What this proves, and what it does not. Routing down only counts as a win if the cheap +tier is still correct. So for three tasks we let the pipeline's verifier actually execute the +generated code against real test cases: is_prime and factorial passed on the cheap +tier, merge_sorted passed on the mid tier — no escalation needed, the saving was real and +the output worked. That is the honest core of the demonstration.

+

What it is not: a benchmark. The 30‑task set is small, hand‑labeled, and the rubric +thresholds were tuned against it — so the perfect separation shows the rubric can +distinguish these cases, not that it will generalize to an arbitrary task distribution. The +“retired SWE‑bench Verified” finding [C6 confirmed] is a +standing warning we apply to ourselves: a clean number on a self‑built set is a proof of +mechanism, not of field accuracy. A production version would calibrate on a large held‑out +distribution and likely learn the rubric weights rather than hand‑set them. We report the +demonstration for what it is: evidence that the two mechanisms are buildable and that they +behave as designed on cases you can inspect one by one.

+
+ +

10 The build‑opportunity map: what to build, what to skip

+ +

Eleven capabilities — five faculties, six mechanisms — and a real 2026 ecosystem to measure +them against. The point of cross‑referencing them is not to claim all eleven as open territory; it is +the opposite. A design study earns trust by saying what not to build as clearly as what to build. +We graded each capability against the actual Claude‑Code stack — skills, hooks, plugins, MCP +servers, memory backends, subagent and Agent‑Teams orchestration, model‑tiering gateways +— as solved, partial, or residual gap. The full item‑by‑item table is +the Ecosystem appendix; here is the decision it implies.

+ +
+

Already solved — do not rebuild. Two of the six mechanisms are covered well by existing +tooling. Complexity‑aware routing (M1) is handled by model tiering and gateways +(LiteLLM, OpenRouter, per‑agent model:); the only residue is transparency, not routing. +Task decomposition (M3) is handled by subagents, Agent‑Teams, and worktree fan‑out. +Building a new router or a new subagent framework would be reinventing shipped infrastructure — +exactly the waste this project set out to avoid.

+
+ +

10.1 The whitespace, ranked

+

Ranking by (evidence strength for the pain) × (how unsolved it is) × (buildability), +the genuine opportunities are:

+ + + + + + + + + + + + + + + + + + + + + + + + +
RankWhat to buildWhy (grounded)Status
1Assumption / uncertainty gate (M2)The project's named root failure and the field's named gap — “models rarely signal +uncertainty”; the METR miscalibration result [C1] is its clearest +evidence. Nothing in the stack supplies calibrated known‑unknowns.residual gap
2Validity‑anchored memory (Memory faculty)Backends store notes (Mem0, claude‑mem, Auto‑Memory) but none tracks whether a stored fact +was later invalidated by a correction; Auto‑Memory's own “memory cliff” is +documented. The write‑back‑only‑confirmed‑lessons idea is unbuilt.partial
3Mandatory pre‑action impact gate (Impact‑awareness)“One change to a shared utility can break dozens of packages with no cross‑package +awareness.” Indexers retrieve; none is a deterministic, hook‑enforced blast‑radius +check before every edit. This paper's first prototype builds exactly this.partial
4Outcome‑validated learning loop (Learning faculty)No tool closes the loop from a task's actual outcome (did the fix hold, did the PR revert) +back into changed future behavior. Frozen weights guarantee it must be external.residual gap
5Root‑cause correction gate (Self‑correction)Hooks retry; the field documents the “doom loop” — thrash that patches +symptoms and can delete its own work while declaring success. Detecting a repeating failure signature and +escalating with a diagnosis is unsolved.partial
6Scope‑minimality check (M5)Over‑engineering is untracked outside UI; measuring footprint against the task's minimal +sufficient footprint is genuine whitespace.residual gap
7Inline verification checkpoint (M6) · goal‑drift check (M4)Passive streaming and static anchors exist; a forced interpretive checkpoint during generation, and a +continuous goal‑vs‑output re‑check, do not.partial
+ +
+

What this paper actually builds, against that map. Two prototypes, targeting the top of the list +where a single session can produce real evidence. The impact oracle (§8) builds opportunity #3. +The router + assumption gate (§6) builds opportunity #1 — and, honestly, the +already‑solved M1, whose only residue is the transparency layer we add. We prototype these two because +they are the ones where ground truth is checkable now: an edit's blast radius against a mutation +oracle, a routing decision against a hand‑labeled tier, an under‑specified request against a +“should‑ask” label. The remaining opportunities — memory validity, outcome learning, +doom‑loop diagnosis — are the harder research gaps, and we mark them as such rather than +gesturing at them with a demo.

+
+ +

11 Genuinely new vs. reinvented

+

Intellectual honesty demands separating what this proposal invents from what it assembles. Almost every component exists somewhere; the contribution is the composition, the anchoring, and the target.

+ + + + + + + + + + +
ElementStatusAssessment
External memory for a frozen modelReinventedRAG, MemGPT, Generative Agents5,6,7 already attach stores to frozen models. We add nothing to the retrieval mechanism itself.
Fast/slow (non‑parametric + LoRA) learning splitReinvented framingThe CLS fast/slow split8,9 and LoRA13 are established; combining them as an agent's two learning channels is a synthesis, not a new mechanism.
Structural code graph & impact analysisReinvented (decades old)PDG, slicing, CPG30,28,31 are mature. Our parser is a modern, persistent re‑implementation, not new theory.
Validity‑anchored memory (the val term, Eq. 3)Novel emphasisScoring and pruning memory by whether its past prediction was confirmed by an external oracle (test/commit), not by the model's own judgment, is the design's sharpest departure from RAG/MemGPT's self‑managed stores.
Wiring exact impact analysis into the agent's pre‑action gateNovel compositionThe bridge — live graph → “what depends on X” → mandatory gate before the edit — is the integration §3 showed nobody has shipped, and the one we prototyped.
Epistemic‑obligation anchoring (the lens)Novel framingDeriving which safeguards are mandatory (verify‑before‑acting, least privilege) from a coherent epistemology, rather than bolting them on ad hoc, is a contribution of stance and organization.
+

In one line: the components are largely borrowed; the loop shape, the validity anchoring, and the coding‑agent target are the contribution. That is a defensible and useful kind of novelty — it is what turns five scattered literatures into one buildable architecture.

+ +

12 Limitations & threats to validity

+ + +

13 Conclusion

+

The faculties a coding agent seems to lack — memory, learning, imagination, self‑correction, impact‑awareness — are not deficiencies of knowledge that scale will cure. They are structural consequences of what a frozen transformer is: a stateless map with fixed weights and a bounded window (Eq. 1, P1–P3). Because they follow from the shape of the loop, they cannot be prompted or tooled away; they can only be removed by re‑wrapping the loop into a closed, stateful cycle over persistent stores, with the model left frozen inside it (Eq. 2, Fig. 1–2). We specified that substrate faculty by faculty, said honestly which parts are open research and which are engineering, and — for the one faculty that is buildable today — shipped a running impact oracle that, against independent ground truth, never misses an affected file where the strategies a context‑bounded agent actually uses miss up to half. The Qur'anic lens gave the work its spine of obligation: know what exists before you act, verify what you are told, and hold what you can damage as a trust. Those are not just good engineering defaults; here they are the architecture. The next step is to build the memory and learning layers against the same discipline — anchored to what can be verified, not to what the model says of itself — and to evaluate the whole loop on real repositories with real histories.

+ +
+

References

+
    +
  1. Weston, Chopra, Bordes (2014). Memory Networks. arXiv:1410.3916. Proposes an explicit, addressable long-term memory component read/written by a neural controller, separate from model parameters.
  2. +
  3. Sukhbaatar, Szlam, Weston, Fergus (2015). End-To-End Memory Networks. arXiv:1503.08895. Makes memory-network read/write fully differentiable and trainable end-to-end with weaker supervision than the original Memory Networks.
  4. +
  5. Graves, Wayne, Danihelka (2014). Neural Turing Machines. arXiv:1410.5401. Couples a neural controller to an external memory matrix via differentiable attention, enabling learned algorithms like copy and sort.
  6. +
  7. Graves et al. (2016). Hybrid computing using a neural network with dynamic external memory. Nature. The Differentiable Neural Computer adds dynamic memory allocation and temporal link tracking, letting a network solve graph traversal and reasoning tasks that require variable-sized structured memory.
  8. +
  9. Lewis et al. (2020). Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks. arXiv:2005.11401 / NeurIPS. Combines a parametric seq2seq model with a non-parametric retriever over an external corpus so generation is grounded in retrieved documents rather than frozen weights alone.
  10. +
  11. Packer et al. (2023). MemGPT: Towards LLMs as Operating Systems. arXiv:2310.08560. Treats the LLM context window like virtual memory, using an OS-style paging scheme (self-directed function calls) to move information between a bounded context and external storage to give the illusion of unbounded memory.
  12. +
  13. Park et al. (2023). Generative Agents: Interactive Simulacra of Human Behavior. arXiv:2304.03442. Introduces a memory stream of observations plus a reflection mechanism that periodically synthesizes higher-level memories, retrieved and used to condition believable agent behavior.
  14. +
  15. McClelland, McNaughton, O'Reilly (1995). Why there are complementary learning systems in the hippocampus and neocortex. Psychological Review. Argues the brain needs two learning systems — a fast hippocampal one for episodic recall and a slow neocortical one for structured, interleaved consolidation — to avoid catastrophic interference.
  16. +
  17. Kumaran, Hassabis, McClelland (2016). What Learning Systems do Intelligent Agents Need? Complementary Learning Systems Theory Updated. Trends in Cognitive Sciences, 10.1016/j.tics.2016.05.004. Updates complementary learning systems theory in light of deep RL and episodic-memory findings, motivating fast/slow-learning-system architectures as a computational analogue of hippocampal-neocortical interaction.
  18. +
  19. Kirkpatrick et al. (2017). Overcoming catastrophic forgetting in neural networks. PNAS / arXiv:1612.00796. Elastic Weight Consolidation penalizes changes to parameters important for earlier tasks (via a Fisher-information-weighted quadratic penalty) to mitigate catastrophic forgetting during sequential training.
  20. +
  21. Sun et al. (2020). Test-Time Training with Self-Supervision for Generalization under Distribution Shifts. arXiv:1909.13231 / ICML 2020. Updates model parameters at test time via a self-supervised auxiliary task on each new input, adapting to distribution shift without labeled data.
  22. +
  23. Ba, Hinton, Mnih, Leibo, Ionescu (2016). Using Fast Weights to Attend to the Recent Past. arXiv:1610.06258. Introduces a fast-changing weight matrix, updated by a Hebbian-like rule from recent activity, that lets a network attend to its own recent history at a timescale between slow weights and short-term activity.
  24. +
  25. Hu et al. (2021). LoRA: Low-Rank Adaptation of Large Language Models. arXiv:2106.09685. Freezes pretrained weights and injects trainable low-rank update matrices per layer, making targeted, cheap fine-tuning/adaptation of large models feasible without touching the full parameter set.
  26. +
  27. von Oswald et al. (2022). Transformers Learn In-Context by Gradient Descent. arXiv:2212.07677. Shows constructively that a transformer's forward pass over a prompt can implement steps of gradient descent on an implicit in-context loss, giving a mechanistic account of in-context learning.
  28. +
  29. Dai et al. (2022). Why Can GPT Learn In-Context? Language Models Implicitly Perform Gradient Descent as Meta-Optimizers. arXiv:2212.10559. Draws a formal duality between attention and gradient-descent-based finetuning, framing in-context learning as an implicit, weight-unchanging optimization process.
  30. +
  31. Cobbe et al. (2021). Training Verifiers to Solve Math Word Problems. arXiv:2110.14168. Trains a separate verifier model to score candidate solutions and select among generator samples, offloading correctness-checking to a distinct learned model rather than the generator itself.
  32. +
  33. Lightman et al. (2023). Let's Verify Step by Step. arXiv:2305.20050. Shows a process-level reward model, trained on human step-by-step correctness labels, outperforms outcome-level supervision for catching reasoning errors.
  34. +
  35. Shinn et al. (2023). Reflexion: Language Agents with Verbal Reinforcement Learning. arXiv:2303.11366. Has an agent verbally reflect on task feedback/failures and stores that reflection in an episodic memory buffer used to condition subsequent attempts, substituting for gradient-based RL updates.
  36. +
  37. Madaan et al. (2023). Self-Refine: Iterative Refinement with Self-Feedback. arXiv:2303.17651. Uses the same frozen LLM to generate output, critique it, and refine it iteratively in a feedback loop, with no parameter updates or external training signal.
  38. +
  39. Wang et al. (2022). Self-Consistency Improves Chain of Thought Reasoning in Language Models. arXiv:2203.11171. Samples multiple diverse reasoning chains and marginalizes over them by majority vote on the final answer, improving reasoning accuracy without any self-correction step per se.
  40. +
  41. Huang et al. (2023). Large Language Models Cannot Self-Correct Reasoning Yet. arXiv:2310.01798. Finds that without external, ground-truth feedback, LLMs prompted to self-critique and revise their own reasoning frequently make correct answers worse, undercutting claims of intrinsic self-correction.
  42. +
  43. Ha, Schmidhuber (2018). World Models. arXiv:1803.10122. Trains a compressed generative model of an environment (VAE + RNN) and evolves a small controller entirely inside that learned latent 'dream' simulation before transferring to the real environment.
  44. +
  45. Schrittwieser et al. (2020). Mastering Atari, Go, Chess and Shogi by Planning with a Learned Model. arXiv:1911.08265 / Nature. MuZero learns a model of only the quantities relevant to planning (reward, value, policy) without reconstructing observations, and plans with MCTS purely in that learned latent model.
  46. +
  47. Hafner et al. (2023). Mastering Diverse Domains through World Models. arXiv:2301.04104. DreamerV3 learns a world model from experience and trains a policy purely from imagined rollouts inside it, achieving strong performance across many domains with one fixed set of hyperparameters.
  48. +
  49. Hafner et al. (2019). Dream to Control: Learning Behaviors by Latent Imagination. arXiv:1912.01603. Backpropagates value gradients directly through imagined multi-step latent trajectories of a learned world model to learn behaviors efficiently, without interacting with the real environment.
  50. +
  51. Friston (2010). The free-energy principle: a unified brain theory?. Nature Reviews Neuroscience. Proposes that brains (and action) minimize variational free energy, unifying perception, learning, and action under a single generative-model / predictive-coding framework — active inference.
  52. +
  53. Allamanis, Brockschmidt, Khademi (2018). Learning to Represent Programs with Graphs. arXiv:1711.00740 / ICLR 2018. Represents source code as a graph capturing syntax, control flow, and data flow, and applies gated graph neural networks to tasks like variable-misuse detection, giving a structural rather than purely textual code representation.
  54. +
  55. Horwitz, Reps, Binkley (1990). Interprocedural Slicing Using Dependence Graphs. ACM TOPLAS. Extends program dependence graphs across procedure boundaries to compute interprocedural slices, the structural basis for determining what code is affected by / affects a given statement.
  56. +
  57. Tip (1994). A Survey of Program Slicing Techniques. Journal of Programming Languages. Surveys the family of static and dynamic program-slicing techniques used to identify the subset of a program that can influence (or is influenced by) a given point — a core building block of change-impact analysis.
  58. +
  59. Ferrante, Ottenstein, Warren (1987). The Program Dependence Graph and Its Use in Optimization. ACM TOPLAS. Introduces the program dependence graph combining control and data dependence in one structure, the ancestor representation behind most modern static change-impact and slicing tools.
  60. +
  61. Yamaguchi, Golde, Arp, Rieck (2014). Modeling and Discovering Vulnerabilities with Code Property Graphs. IEEE S&P 2014. Introduces the code property graph, merging AST, control-flow graph, and program-dependence graph into one joint representation, queryable to discover vulnerability patterns across a codebase.
  62. +
  63. Alon, Zilberstein, Levy, Yahav (2019). code2vec: Learning Distributed Representations of Code. POPL 2019 / PACMPL. Represents a code snippet as a bag of AST paths and learns a distributed embedding that predicts semantic properties such as method names, giving a learned structural fingerprint of code.
  64. +
+ +
+

Appendix Evidence map — the twelve statistics, re‑grounded

+

Each load‑bearing pain‑point statistic in the 2026 discourse, traced to its +primary source and graded. Confirmed = independent primary source; vendor‑reported = +real but sourced only to a party with a commercial stake; unverifiable = could not corroborate in +primary form. Full source records and paper‑use recommendations are in evidence_map.json.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
IDClaimPrimary sourceSupportsStatus
C1Experienced open-source developers were 19% SLOWER with AI while believing they were ~20% faster (also forecast 24% speedup beforehand).Measuring the Impact of Early-2025 AI on Experienced Open-Source Developer ProductivityM2 (assumption/uncertainty - miscalibration), P3/self-correcconfirmed
C2Trust in AI accuracy fell from 40% to 29% (or 46% actively distrust vs 33% trust per detailed breakdown); favorability 72%->60%; 66% say AI answers are 'almost right, but not quite2025 Stack Overflow Developer Survey (49,000+ respondents, 177 countries)M2 uncertainty/calibration; M6 inline verification; overall confirmed
C345% of AI-generated code samples introduce an OWASP Top-10 vulnerability; a widely-repeated '2.74x more vulnerabilities than human-written code' figure.2025 GenAI Code Security ReportM5 anti-over-engineering / code-quality thesis; security-vervendor‑reported
C4~8x rise (2024 vs prior years) in frequency of duplicated/copy-pasted code blocks; copy-paste overtaking refactored ('moved') code for the first time.AI Copilot Code Quality: 2025 Data Suggests 4x Growth in Code Clones / AI Copilot Code QuaM5 anti-over-engineering; long-term codebase impact-awarenesvendor‑reported
C5AI's primary role is as an 'amplifier' - magnifying high performers' strengths and low performers' dysfunctions; AI continues to increase delivery instability even as adoption becoState of AI-assisted Software Development 2025 (DORA Report)Systemic framing for all six mechanisms (org context mattersconfirmed
C6OpenAI retired SWE-bench Verified (Feb 2026) after finding at least 59.4% of audited (hard/failed) problems had flawed test cases and/or training-data contamination; large score gaWhy SWE-bench Verified no longer measures frontier coding capabilitiesM6 inline verification / benchmark-trust thesis; supports 'Aconfirmed
C7Median time in PR review up 441.5%; incidents-per-PR up 242.7%; bugs per developer up 54%; 31.3% more PRs merged with no review at all.The AI Engineering Report 2026: The Acceleration WhiplashM6 inline verification; review-bottleneck / verification-layvendor‑reported
C8Developers who delegate code generation to AI score 17% lower on comprehension tests, based on 'Anthropic's own research (~400,000 Claude Code sessions)'.TWO DIFFERENT STUDIES ARE BEING CONFLATED: (a) 'How AI Impacts Skill Formation' by Judy HaM6 inline verification / skill-atrophy thesis (comprehensionunverifiable
C996% of developers don't fully trust AI-generated code is functionally correct, yet only 48% always verify it before committing (a 48-point 'verification gap'/'verification debt').State of Code Developer Survey report 2026M6 inline verification - the central named gap the mechanismvendor‑reported
C10JetBrains' 2025 survey found 77% of developers still manually correct AI output for project conventions every session.The State of Developer Ecosystem 2025M4 goal-anchoring / M5 anti-over-engineering (convention driunverifiable
C11A standard MCP setup (few servers) can consume ~72% of a 200K-token context window before work begins; tool-selection accuracy drops from ~43% to below ~14% as tool count scales ('(a) 72%-context-window claim: no formal paper found, only recurring blog anecdotes (Scott M1 complexity-aware routing / M3 task decomposition (contextvendor‑reported
C12LLM evaluators recognize and favor their own generations - self-preference bias correlates with self-recognition ability - motivating why 'AI verifying AI' is structurally weak.LLM Evaluators Recognize and Favor Their Own GenerationsM6 inline verification (why an LLM cannot be its own sole veconfirmed
+ +
+

Appendix Ecosystem map — faculties & mechanisms vs. the real stack

+

Each faculty and mechanism graded against the actual 2026 Claude‑Code stack (skills, hooks, +plugins, MCP servers, memory backends, subagent/Agent‑Teams orchestration, model‑tiering +gateways). Solved = covered well by existing tooling; partial = tooling exists but leaves a +named gap; residual‑gap = genuine whitespace. Full tool lists and citations are in +ecosystem_map.json.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CapabilityExisting tooling (sample)StatusResidual gapWhat we'd add
Memory (across sessions)
faculty
CLAUDE.md; Auto Memory; Mem0; claude-mem; HindsightpartialPain-points report names this directly: 'no standard, tool-agnostic, durable memory layer that reliably persists project knowledge, decisions, and corrections across sessions, tools, and teammates' (Open gap #2), with JetBrains finding 77% Validity-anchored memory: stored facts carry a confirmed/discredited state updated by verified outcomes, not a static note-dump -- addresses the correction dime
Learning (from outcomes)
faculty
Auto Memory 'feedback' memory type; Superpowers subagent-driven-development two-stage review; ccusage / usage trackersresidual-gapNo tool in the stack closes the loop from a task's actual outcome (did the fix hold, did the test stay green, was the PR reverted) back into changed future behavior. Auto Memory's feedback type is note storage, not an evaluated lesson; frozOutcome-validated learning loop: capture a task's actual downstream result, verify it independently, and write back only confirmed lessons (not raw logs) into t
Imagination (simulate consequences before acting)
faculty
Plan mode / built-in Plan subagent; Explore subagent; Superpowers brainstorm -> plan -> TDD -> subagent-dev -> reviewpartialThese are textual/symbolic planning steps within the stack itself, not a simulation of an edit's actual downstream effects -- no hook, skill, or MCP server in the stack landscape traces a dependency graph before a change is made. (The pain-A pre-action impact simulation step -- dependency-graph/call-graph traversal that predicts affected files/tests before code is written, feeding predicted blast
Self-correction
faculty
Stop hooks; PreToolUse blocking hooks; Playwright's healer agent; TDD RED-GREEN-REFACTOR; /security-review and pr-review-toolkitpartialThese are retry/gate mechanisms, not diagnosis. The pain-points report documents the 'doom loop' by name -- an agent that 'makes a mistake, tries to fix it, makes it worse' and can even delete its own changes while declaring success -- and A root-cause-aware correction gate that distinguishes genuine progress from thrash (same failure signature repeating), halts and escalates with a diagnosis inst
Impact-awareness (what exists in the codebase / what an edit affects)
faculty
filesystem and memory; Context7; sequential-thinking MCP server; sandboxing's 'trust verification for new codebases/MCP servers'partialThese stack primitives expose retrieval (docs, a memory graph, filesystem access) that the model may or may not consult -- none is a deterministic, mandatory gate run before every edit, and none computes blast radius. (The pain-points reporA MANDATORY pre-action impact gate -- a hook-enforced (not LLM-judged) dependency-graph query that runs before every edit is applied, not an optional retrieval
M1 Complexity-aware routing
mechanism
Model tiering; Per-agent model: field in .claude/agents/; LLM gateways: LiteLLM, Portkey, OpenRouter; Named orchestration pattern: 'orchestrator-classifies-then-routes to Haiku/Sonnet/Opus by complexity'solvedThe routing decision is set at config time (a developer picks model: haiku for an agent) or by the gateway's own cost logic -- it is not a transparent, per-task, auditable classification the user can see and override before dispatch.A transparent complexity classification surfaced to the user before dispatch, making the routing decision auditable rather than a silent config default.
M2 Assumption / uncertainty
mechanism
Reasoning models acting as an internal review pass; Context7; Spec-driven developmentresidual-gapNamed directly and unsolved in the pain-points report: 'Models rarely signal uncertainty or say I can't do this' -- the report's own build opportunity is 'calibrated-confidence and known-unknowns tooling -- agents that flag low-confidence rThis is the paper's named root failure: an assumption/uncertainty gate that requires the model to enumerate its unstated assumptions and ask before proceeding w
M3 Task / session decomposition
mechanism
Subagents; Agent Teams; git worktrees for parallel-agent isolation; Parallel fan-out orchestration pattern; Superpowers subagent-driven-developmentsolvedMature, well-tooled pattern. The remaining gap is small: deciding the decomposition boundary itself (what counts as independent vs. needs shared context) is still a manual/heuristic judgment call by the developer, not something any listed tAutomatic decomposition-boundary detection -- deciding when to fork a subagent/session vs. keep work in one context, rather than leaving that call to developer
M4 Goal-anchoring
mechanism
CLAUDE.md; Spec-driven development; /goal command; Task lists in Agent TeamspartialThese anchors are loaded once and are static. The report documents the anchor decaying over a session: 'circular reasoning at 20% [context usage], context compression wiping scrollback at 40%,' and Open gap #1 states plainly that 'specs driA continuous goal-drift check that periodically re-validates in-progress output against the original stated objective, rather than loading the goal once and tru
M5 Anti-over-engineering
mechanism
frontend-design skill's minimalism discipline; TDD RED-GREEN-REFACTOR; pr-review-toolkit / CodeRabbit / Greptile review agentsresidual-gapThe frontend-design skill's discipline is explicitly UI-only; no general-purpose backend/architecture tool measures unnecessary abstraction, premature generalization, or scope creep against the stated task. GitClear's tracked defects (8x duA scope-minimality check that compares an implementation's footprint (files touched, abstractions introduced) against the stated task requirement and flags addi
M6 Inline verification
mechanism
Real-time thinking/tool-call streaming; Self-QA pattern; PostToolUse hooks; Plan mode human-in-the-loop gatingpartialStreaming and immediate post-edit hooks give passive visibility but do not require a human interpretive checkpoint DURING generation. The pain-points report's central statistic is the '48-point gap': 'Sonar's 2026 report: 96% of developers A mandatory inline checkpoint that surfaces a human-checkable claim or diff at each meaningful generation step, shifting verification earlier instead of batchin
+ +

Appendix Qur'anic‑lens mapping table

+

The complete 14‑row mapping (12 load‑bearing, 2 metaphor). Canonical Arabic and translations retrieved from quran.ai; full text, tafsir references, and design principles in the companion artifact quran_lens.json. Caveat: this table is a design lens, not technical or theological authority — see §5.

+ + + + + + + + + + + + + + + + + +
Concept / verseRetrieved glossFacultyDesign principle (abbrev.)Type
17:36 — lā taqfu (do not pursue without knowledge)Do not follow blindly what you do not know to be true: ears, eyes, and heart, you will be questioned about all these.IMPACT-AWARENESSBefore any code mutation (file write, delete, refactor), the agent must run a pre-action verification gate that checks: (1) what entities in the codebase wil…load-bearing
49:6 — tabayyun (verify reports before acting)Believers, if a troublemaker brings you news, check it first, in case you wrong others unwittingly and later regret what you have done,SELF-CORRECTIONThe agent architecture must include a verification gate between receiving information (from context, tool output, or its own prior reasoning) and acting on itload-bearing
2:31-32 — taʿlīm al-asmāʾ (He taught Adam the names of all things)(2:31) He taught Adam all the names [of things], then He showed them to the angels and said, ‘Tell me the names of these if you truly [think you can].’ (2:32) They sai…WORLD-MODEL (codebase graph)The agent must maintain a structured representation of what exists in the codebase — a graph of files, functions, classes, dependencies, and their relationsh…load-bearing
20:114 — rabbi zidnī ʿilmā (My Lord, increase me in knowledge)exalted be God, the one who is truly in control. [Prophet], do not rush to recite before the revelation is fully complete but say, ‘Lord, increase me in knowledge!’CONTINUAL LEARNINGThe agent's knowledge must be treated as perpetually incomplete, with an explicit mechanism for incremental growthload-bearing
96:1-5 — iqraʾ / ʿallama bi-l-qalam (Read; taught by the pen)(96:1) Read! In the name of your Lord who created: (96:2) He created manfrom a clinging form. (96:3) Read! Your Lord is the Most Bountiful One (96:4) who taught by [me…PERSISTENT MEMORYKnowledge must be externalized to survive beyond the moment of computationload-bearing
39:9 — hal yastawī lladhīna yaʿlamūna wa-lladhīna lā yaʿlamūn (are those who know equal to those who do not know?)What about someone who worships devoutly during the night, bowing down, standing in prayer, ever mindful of the life to come, hoping for his Lord’s mercy? Say, ‘How ca…MEMORY + LEARNING (epistemic grounding)An agent that retains and learns from experience is categorically more capable and more trustworthy than one that does not — this is not a nice-to-have but a…metaphor
4:82 — tadabbur al-Qurʾān (do they not reflect deeply upon the Quran; inconsistency as a sign of non-divine origin)Will they not think about this Quran? If it had been from anyone other than God, they would have found much inconsistency in it.SELF-CORRECTION (metacognitive controller)The agent must run self-consistency checks on its own output before committing itload-bearing
47:24 — tadabbur / aqfāl ʿalā qulūb (do they not ponder, or are there locks on their hearts?)Will they not contemplate the Quran? Do they have locks on their hearts?SELF-CORRECTION (iterative refinement)Reflection must be a deliberate, repeatable operation, not a one-pass judgmentmetaphor
33:72 — al-amāna (the Trust offered to heavens, earth, mountains; borne by the human)We offered the Trust to the heavens, the earth, and the mountains, yet they refused to undertake it and were afraid of it; mankind undertook it- they have always been …STEWARDSHIP ETHICS (bounded autonomy)An agent that can modify a codebase bears a trust (amāna) — it has accepted responsibility for something it can damageload-bearing
CONCEPT: ʿilm → fahm → ḥikma (knowledge → understanding → wisdom)A classical epistemological hierarchy: ʿilm is raw knowledge (facts, data, observations); fahm is comprehension (grasping the relations between facts, seeing why); ḥik…MEMORY + LEARNING (data architecture)The agent's memory/learning stack must be layered, not flatload-bearing
CONCEPT: ḥifẓ + murājaʿa (preservation + spaced review/revision)The classical Quranic memorization discipline: ḥifẓ is initial encoding and faithful preservation of the text; murājaʿa is the regular, spaced revision that prevents d…PERSISTENT MEMORY (consolidation & maintenance)Memory is not write-onceload-bearing
CONCEPT: tadabbur (deep, structured reflection — returning to examine consequences)Tadabbur is not casual thought; its root d-b-r relates to 'what is behind' or 'what follows' — examining the consequences and deeper implications of something. In Qura…SELF-CORRECTION (metacognitive controller)The metacognitive controller is a tadabbur loop: after the agent generates a plan or action, the controller examines what comes after (d-b-r) — what are the …load-bearing
CONCEPT: tabayyun (verification of reports before acting on them)Tabayyun is the act of seeking clarity and verification before acting on received information. In 49:6, it is commanded as a mandatory step between receiving a report …SELF-CORRECTION (verification gate)The verification gate is the architectural realization of tabayyunload-bearing
CONCEPT: amāna (trust, stewardship, accepted responsibility)Amāna is the trust or responsibility that is accepted voluntarily and carries accountability. In 33:72, it is described as something so weighty that the heavens, earth…STEWARDSHIP ETHICS (safe operation)When an agent is granted access to a codebase, it accepts an amāna — a trust that carries accountability proportional to its capabilityload-bearing
+ +
+

Companion artifacts. This paper is accompanied by: the runnable impact_oracle_src.zip (world‑model + oracle + demo + 36‑test suite); the impact‑graph and evaluation figures; the structured literature gap_map.json and 32‑entry references.json; and the quran_lens.json mapping table. All results are reproducible via the included demo.py.

+

On the lens. Qur'anic text throughout was retrieved from the quran.ai service and presented directly, not paraphrased. It is used as an epistemological and ethical design lens only; every technical claim rests on the cited literature and the prototype evaluation, independent of the lens.

+
+ +
+ + diff --git a/research/cognitive-substrate/cognitive_substrate_whitepaper.pdf b/research/cognitive-substrate/cognitive_substrate_whitepaper.pdf new file mode 100644 index 0000000..44ce7bb Binary files /dev/null and b/research/cognitive-substrate/cognitive_substrate_whitepaper.pdf differ diff --git a/research/cognitive-substrate/evidence/ecosystem_map.json b/research/cognitive-substrate/evidence/ecosystem_map.json new file mode 100644 index 0000000..8b5791a --- /dev/null +++ b/research/cognitive-substrate/evidence/ecosystem_map.json @@ -0,0 +1,147 @@ +[ + { + "item": "Memory (across sessions)", + "kind": "faculty", + "existing_tooling": [ + "CLAUDE.md (always-on project context, survives /compact)", + "Auto Memory (v2.1.59+, self-written notes in ~/.claude/projects//memory/)", + "Mem0 (~58k stars, hosted MCP + lifecycle hooks)", + "claude-mem (SQLite+FTS5/vector, Haiku summaries)", + "Hindsight (94.6% LongMemEval, self-hostable)", + "supermemory (cross-machine sync)", + "Anthropic memory tool (API, client-side file ops)" + ], + "status": "partial", + "residual_gap": "Pain-points report names this directly: 'no standard, tool-agnostic, durable memory layer that reliably persists project knowledge, decisions, and corrections across sessions, tools, and teammates' (Open gap #2), with JetBrains finding 77% of devs still manually re-correct conventions every session. Auto Memory itself has a documented 'memory cliff' -- 200-line index cap + 5-files-per-turn retrieval with silent truncation. Existing backends store notes; none track whether a stored fact has since been invalidated by a correction.", + "our_contribution": "Validity-anchored memory: stored facts carry a confirmed/discredited state updated by verified outcomes, not a static note-dump -- addresses the correction dimension the named tools don't." + }, + { + "item": "Learning (from outcomes)", + "kind": "faculty", + "existing_tooling": [ + "Auto Memory 'feedback' memory type (stores feedback notes)", + "Superpowers subagent-driven-development two-stage review (spec compliance, then code quality)", + "ccusage / usage trackers (cost signal only, not outcome learning)" + ], + "status": "residual-gap", + "residual_gap": "No tool in the stack closes the loop from a task's actual outcome (did the fix hold, did the test stay green, was the PR reverted) back into changed future behavior. Auto Memory's feedback type is note storage, not an evaluated lesson; frozen weights mean nothing updates the model itself. Neither source names a shipped mechanism for this -- it is unaddressed rather than partially addressed.", + "our_contribution": "Outcome-validated learning loop: capture a task's actual downstream result, verify it independently, and write back only confirmed lessons (not raw logs) into the memory store consulted on the next similar task." + }, + { + "item": "Imagination (simulate consequences before acting)", + "kind": "faculty", + "existing_tooling": [ + "Plan mode / built-in Plan subagent (read-only)", + "Explore subagent", + "Superpowers brainstorm -> plan -> TDD -> subagent-dev -> review" + ], + "status": "partial", + "residual_gap": "These are textual/symbolic planning steps within the stack itself, not a simulation of an edit's actual downstream effects -- no hook, skill, or MCP server in the stack landscape traces a dependency graph before a change is made. (The pain-points report separately documents spec-driven-development tools such as Spec Kit, Kiro, and OpenSpec as workarounds, and names the same open gap: 'Cross-service/architectural-impact awareness at monorepo scale remains weak,' with the build opportunity framed as 'architecture-aware agents that reason over dependency graphs.')", + "our_contribution": "A pre-action impact simulation step -- dependency-graph/call-graph traversal that predicts affected files/tests before code is written, feeding predicted blast radius into the plan rather than discovering it after the edit." + }, + { + "item": "Self-correction", + "kind": "faculty", + "existing_tooling": [ + "Stop hooks (e.g. npm test || exit 2, forces continued work)", + "PreToolUse blocking hooks", + "Playwright's healer agent (auto-repairs failing tests)", + "TDD RED-GREEN-REFACTOR (Superpowers)", + "/security-review and pr-review-toolkit (5 parallel Sonnet review agents)", + "Ralph Wiggum loop / /loop, /goal, /batch" + ], + "status": "partial", + "residual_gap": "These are retry/gate mechanisms, not diagnosis. The pain-points report documents the 'doom loop' by name -- an agent that 'makes a mistake, tries to fix it, makes it worse' and can even delete its own changes while declaring success -- and states plainly: 'Automatic doom-loop detection and root-cause reasoning (vs. symptom-patching) are largely unsolved,' naming the build opportunity as 'loop-breakers and budget circuit-breakers that detect thrashing, halt, and escalate to a human with a diagnosis.'", + "our_contribution": "A root-cause-aware correction gate that distinguishes genuine progress from thrash (same failure signature repeating), halts and escalates with a diagnosis instead of blindly re-looping." + }, + { + "item": "Impact-awareness (what exists in the codebase / what an edit affects)", + "kind": "faculty", + "existing_tooling": [ + "filesystem and memory (knowledge graph) MCP servers (modelcontextprotocol/servers monorepo)", + "Context7 (version-specific library docs via MCP)", + "sequential-thinking MCP server", + "sandboxing's 'trust verification for new codebases/MCP servers' (native control)" + ], + "status": "partial", + "residual_gap": "These stack primitives expose retrieval (docs, a memory graph, filesystem access) that the model may or may not consult -- none is a deterministic, mandatory gate run before every edit, and none computes blast radius. (The pain-points report separately names full-repo indexers such as Sourcegraph Cody/Amp, Augment Code, Greptile, CodeAnt AI, and CodeRabbit as workarounds, but states directly: 'one change to a shared utility can break dozens of packages with no cross-package awareness' and 'Cross-service/architectural-impact awareness at monorepo scale remains weak.')", + "our_contribution": "A MANDATORY pre-action impact gate -- a hook-enforced (not LLM-judged) dependency-graph query that runs before every edit is applied, not an optional retrieval step the model may or may not consult." + }, + { + "item": "M1 Complexity-aware routing", + "kind": "mechanism", + "existing_tooling": [ + "Model tiering (Haiku/Sonnet/Opus, /model command)", + "Per-agent model: field in .claude/agents/", + "LLM gateways: LiteLLM, Portkey, OpenRouter", + "Named orchestration pattern: 'orchestrator-classifies-then-routes to Haiku/Sonnet/Opus by complexity'" + ], + "status": "solved", + "residual_gap": "The routing decision is set at config time (a developer picks model: haiku for an agent) or by the gateway's own cost logic -- it is not a transparent, per-task, auditable classification the user can see and override before dispatch.", + "our_contribution": "A transparent complexity classification surfaced to the user before dispatch, making the routing decision auditable rather than a silent config default." + }, + { + "item": "M2 Assumption / uncertainty", + "kind": "mechanism", + "existing_tooling": [ + "Reasoning models acting as an internal review pass", + "Context7 (reduces API-hallucination via current docs, not the underlying issue)", + "Spec-driven development (Spec Kit, Kiro, OpenSpec) as a workaround that forces the human to write the spec" + ], + "status": "residual-gap", + "residual_gap": "Named directly and unsolved in the pain-points report: 'Models rarely signal uncertainty or say I can't do this' -- the report's own build opportunity is 'calibrated-confidence and known-unknowns tooling -- agents that flag low-confidence regions and ask clarifying questions instead of confabulating.' SDD only helps if the human already wrote a complete spec; it does not make the model self-flag what it doesn't know.", + "our_contribution": "This is the paper's named root failure: an assumption/uncertainty gate that requires the model to enumerate its unstated assumptions and ask before proceeding when confidence is low, instead of depending on the user having pre-empted every ambiguity in a spec." + }, + { + "item": "M3 Task / session decomposition", + "kind": "mechanism", + "existing_tooling": [ + "Subagents (isolated context windows, only final message returned)", + "Agent Teams (experimental, shared task list, teammate-to-teammate messaging)", + "git worktrees for parallel-agent isolation", + "Parallel fan-out orchestration pattern (60-80% wall-clock savings)", + "Superpowers subagent-driven-development (fresh subagent per task)" + ], + "status": "solved", + "residual_gap": "Mature, well-tooled pattern. The remaining gap is small: deciding the decomposition boundary itself (what counts as independent vs. needs shared context) is still a manual/heuristic judgment call by the developer, not something any listed tool decides automatically.", + "our_contribution": "Automatic decomposition-boundary detection -- deciding when to fork a subagent/session vs. keep work in one context, rather than leaving that call to developer heuristics." + }, + { + "item": "M4 Goal-anchoring", + "kind": "mechanism", + "existing_tooling": [ + "CLAUDE.md (always-on context, re-read from disk, survives /compact)", + "Spec-driven development (spec as source of truth)", + "/goal command (v2.1.139+)", + "Task lists in Agent Teams" + ], + "status": "partial", + "residual_gap": "These anchors are loaded once and are static. The report documents the anchor decaying over a session: 'circular reasoning at 20% [context usage], context compression wiping scrollback at 40%,' and Open gap #1 states plainly that 'specs drift out of sync with code (context drift)' with 'no mature, widely-adopted tooling [that] keeps specs, code, and tests continuously verified against each other.'", + "our_contribution": "A continuous goal-drift check that periodically re-validates in-progress output against the original stated objective, rather than loading the goal once and trusting it stays in view." + }, + { + "item": "M5 Anti-over-engineering", + "kind": "mechanism", + "existing_tooling": [ + "frontend-design skill's minimalism discipline ('remove one accessory') -- UI/design scope only", + "TDD RED-GREEN-REFACTOR (write only enough code to pass a test)", + "pr-review-toolkit / CodeRabbit / Greptile review agents (not scoped to over-engineering specifically)" + ], + "status": "residual-gap", + "residual_gap": "The frontend-design skill's discipline is explicitly UI-only; no general-purpose backend/architecture tool measures unnecessary abstraction, premature generalization, or scope creep against the stated task. GitClear's tracked defects (8x duplication, copy-paste) are the opposite failure mode (under-abstraction) -- over-engineering isn't named or tracked by any tool in either source.", + "our_contribution": "A scope-minimality check that compares an implementation's footprint (files touched, abstractions introduced) against the stated task requirement and flags additions the task didn't ask for." + }, + { + "item": "M6 Inline verification", + "kind": "mechanism", + "existing_tooling": [ + "Real-time thinking/tool-call streaming (Claude Code)", + "Self-QA pattern (agent opens localhost and checks its own changes)", + "PostToolUse hooks (auto-format/lint immediately after a write)", + "Plan mode human-in-the-loop gating" + ], + "status": "partial", + "residual_gap": "Streaming and immediate post-edit hooks give passive visibility but do not require a human interpretive checkpoint DURING generation. The pain-points report's central statistic is the '48-point gap': 'Sonar's 2026 report: 96% of developers don't fully trust AI code is correct, yet only 48% always verify' -- verification is deferred to an end-of-task PR review (median review time up 441.5%), not performed inline.", + "our_contribution": "A mandatory inline checkpoint that surfaces a human-checkable claim or diff at each meaningful generation step, shifting verification earlier instead of batching it into a single end-of-task review." + } +] \ No newline at end of file diff --git a/research/cognitive-substrate/evidence/ecosystem_map.md b/research/cognitive-substrate/evidence/ecosystem_map.md new file mode 100644 index 0000000..d2e8ab1 --- /dev/null +++ b/research/cognitive-substrate/evidence/ecosystem_map.md @@ -0,0 +1,86 @@ +# Ecosystem Map: Cognitive Substrate vs. the Mid-2026 Claude Code Stack + +Cross-references the white paper's 5 structural faculties (memory, learning, imagination, +self-correction, impact-awareness) and 6 extension mechanisms (M1-M6: complexity routing, +assumption/uncertainty, task decomposition, goal-anchoring, anti-over-engineering, inline +verification) against the tools actually documented in the stack landscape file, mid-2026. +`existing_tooling` names are drawn from the stack landscape document only; where the separate +pain-points report names additional workaround tools or "Open gap" / "Build opportunity" +language, those are cited in the residual-gap column for context, not counted as stack-sourced +existing tooling. Purpose: don't build what already exists; be honest about what does. + +**Summary: 11 items -- 2 solved by existing tooling, 6 partially +addressed (documented gap remains), 3 residual gap (essentially unaddressed).** + +## Faculties (from the base white paper) + +| Item | Status | Existing tooling (from stack file) | Residual gap | Our contribution | +|---|---|---|---|---| +| **Memory (across sessions)** | Partial | CLAUDE.md (always-on project context, survives /compact); Auto Memory (v2.1.59+, self-written notes in ~/.claude/projects//memory/); Mem0 (~58k stars, hosted MCP + lifecycle hooks); claude-mem (SQLite+FTS5/vector, Haiku summaries); Hindsight (94.6% LongMemEval, self-hostable); supermemory (cross-machine sync); Anthropic memory tool (API, client-side file ops) | Pain-points report names this directly: 'no standard, tool-agnostic, durable memory layer that reliably persists project knowledge, decisions, and corrections across sessions, tools, and teammates' (Open gap #2), with JetBrains finding 77% of devs still manually re-correct conventions every session. Auto Memory itself has a documented 'memory cliff' -- 200-line index cap + 5-files-per-turn retrieval with silent truncation. Existing backends store notes; none track whether a stored fact has since been invalidated by a correction. | Validity-anchored memory: stored facts carry a confirmed/discredited state updated by verified outcomes, not a static note-dump -- addresses the correction dimension the named tools don't. | +| **Learning (from outcomes)** | Residual gap | Auto Memory 'feedback' memory type (stores feedback notes); Superpowers subagent-driven-development two-stage review (spec compliance, then code quality); ccusage / usage trackers (cost signal only, not outcome learning) | No tool in the stack closes the loop from a task's actual outcome (did the fix hold, did the test stay green, was the PR reverted) back into changed future behavior. Auto Memory's feedback type is note storage, not an evaluated lesson; frozen weights mean nothing updates the model itself. Neither source names a shipped mechanism for this -- it is unaddressed rather than partially addressed. | Outcome-validated learning loop: capture a task's actual downstream result, verify it independently, and write back only confirmed lessons (not raw logs) into the memory store consulted on the next similar task. | +| **Imagination (simulate consequences before acting)** | Partial | Plan mode / built-in Plan subagent (read-only); Explore subagent; Superpowers brainstorm -> plan -> TDD -> subagent-dev -> review | These are textual/symbolic planning steps within the stack itself, not a simulation of an edit's actual downstream effects -- no hook, skill, or MCP server in the stack landscape traces a dependency graph before a change is made. (The pain-points report separately documents spec-driven-development tools such as Spec Kit, Kiro, and OpenSpec as workarounds, and names the same open gap: 'Cross-service/architectural-impact awareness at monorepo scale remains weak,' with the build opportunity framed as 'architecture-aware agents that reason over dependency graphs.') | A pre-action impact simulation step -- dependency-graph/call-graph traversal that predicts affected files/tests before code is written, feeding predicted blast radius into the plan rather than discovering it after the edit. | +| **Self-correction** | Partial | Stop hooks (e.g. npm test || exit 2, forces continued work); PreToolUse blocking hooks; Playwright's healer agent (auto-repairs failing tests); TDD RED-GREEN-REFACTOR (Superpowers); /security-review and pr-review-toolkit (5 parallel Sonnet review agents); Ralph Wiggum loop / /loop, /goal, /batch | These are retry/gate mechanisms, not diagnosis. The pain-points report documents the 'doom loop' by name -- an agent that 'makes a mistake, tries to fix it, makes it worse' and can even delete its own changes while declaring success -- and states plainly: 'Automatic doom-loop detection and root-cause reasoning (vs. symptom-patching) are largely unsolved,' naming the build opportunity as 'loop-breakers and budget circuit-breakers that detect thrashing, halt, and escalate to a human with a diagnosis.' | A root-cause-aware correction gate that distinguishes genuine progress from thrash (same failure signature repeating), halts and escalates with a diagnosis instead of blindly re-looping. | +| **Impact-awareness (what exists in the codebase / what an edit affects)** | Partial | filesystem and memory (knowledge graph) MCP servers (modelcontextprotocol/servers monorepo); Context7 (version-specific library docs via MCP); sequential-thinking MCP server; sandboxing's 'trust verification for new codebases/MCP servers' (native control) | These stack primitives expose retrieval (docs, a memory graph, filesystem access) that the model may or may not consult -- none is a deterministic, mandatory gate run before every edit, and none computes blast radius. (The pain-points report separately names full-repo indexers such as Sourcegraph Cody/Amp, Augment Code, Greptile, CodeAnt AI, and CodeRabbit as workarounds, but states directly: 'one change to a shared utility can break dozens of packages with no cross-package awareness' and 'Cross-service/architectural-impact awareness at monorepo scale remains weak.') | A MANDATORY pre-action impact gate -- a hook-enforced (not LLM-judged) dependency-graph query that runs before every edit is applied, not an optional retrieval step the model may or may not consult. | + +## Mechanisms (this extension: M1-M6) + +| Item | Status | Existing tooling (from stack file) | Residual gap | Our contribution | +|---|---|---|---|---| +| **M1 Complexity-aware routing** | Solved | Model tiering (Haiku/Sonnet/Opus, /model command); Per-agent model: field in .claude/agents/; LLM gateways: LiteLLM, Portkey, OpenRouter; Named orchestration pattern: 'orchestrator-classifies-then-routes to Haiku/Sonnet/Opus by complexity' | The routing decision is set at config time (a developer picks model: haiku for an agent) or by the gateway's own cost logic -- it is not a transparent, per-task, auditable classification the user can see and override before dispatch. | A transparent complexity classification surfaced to the user before dispatch, making the routing decision auditable rather than a silent config default. | +| **M2 Assumption / uncertainty** | Residual gap | Reasoning models acting as an internal review pass; Context7 (reduces API-hallucination via current docs, not the underlying issue); Spec-driven development (Spec Kit, Kiro, OpenSpec) as a workaround that forces the human to write the spec | Named directly and unsolved in the pain-points report: 'Models rarely signal uncertainty or say I can't do this' -- the report's own build opportunity is 'calibrated-confidence and known-unknowns tooling -- agents that flag low-confidence regions and ask clarifying questions instead of confabulating.' SDD only helps if the human already wrote a complete spec; it does not make the model self-flag what it doesn't know. | This is the paper's named root failure: an assumption/uncertainty gate that requires the model to enumerate its unstated assumptions and ask before proceeding when confidence is low, instead of depending on the user having pre-empted every ambiguity in a spec. | +| **M3 Task / session decomposition** | Solved | Subagents (isolated context windows, only final message returned); Agent Teams (experimental, shared task list, teammate-to-teammate messaging); git worktrees for parallel-agent isolation; Parallel fan-out orchestration pattern (60-80% wall-clock savings); Superpowers subagent-driven-development (fresh subagent per task) | Mature, well-tooled pattern. The remaining gap is small: deciding the decomposition boundary itself (what counts as independent vs. needs shared context) is still a manual/heuristic judgment call by the developer, not something any listed tool decides automatically. | Automatic decomposition-boundary detection -- deciding when to fork a subagent/session vs. keep work in one context, rather than leaving that call to developer heuristics. | +| **M4 Goal-anchoring** | Partial | CLAUDE.md (always-on context, re-read from disk, survives /compact); Spec-driven development (spec as source of truth); /goal command (v2.1.139+); Task lists in Agent Teams | These anchors are loaded once and are static. The report documents the anchor decaying over a session: 'circular reasoning at 20% [context usage], context compression wiping scrollback at 40%,' and Open gap #1 states plainly that 'specs drift out of sync with code (context drift)' with 'no mature, widely-adopted tooling [that] keeps specs, code, and tests continuously verified against each other.' | A continuous goal-drift check that periodically re-validates in-progress output against the original stated objective, rather than loading the goal once and trusting it stays in view. | +| **M5 Anti-over-engineering** | Residual gap | frontend-design skill's minimalism discipline ('remove one accessory') -- UI/design scope only; TDD RED-GREEN-REFACTOR (write only enough code to pass a test); pr-review-toolkit / CodeRabbit / Greptile review agents (not scoped to over-engineering specifically) | The frontend-design skill's discipline is explicitly UI-only; no general-purpose backend/architecture tool measures unnecessary abstraction, premature generalization, or scope creep against the stated task. GitClear's tracked defects (8x duplication, copy-paste) are the opposite failure mode (under-abstraction) -- over-engineering isn't named or tracked by any tool in either source. | A scope-minimality check that compares an implementation's footprint (files touched, abstractions introduced) against the stated task requirement and flags additions the task didn't ask for. | +| **M6 Inline verification** | Partial | Real-time thinking/tool-call streaming (Claude Code); Self-QA pattern (agent opens localhost and checks its own changes); PostToolUse hooks (auto-format/lint immediately after a write); Plan mode human-in-the-loop gating | Streaming and immediate post-edit hooks give passive visibility but do not require a human interpretive checkpoint DURING generation. The pain-points report's central statistic is the '48-point gap': 'Sonar's 2026 report: 96% of developers don't fully trust AI code is correct, yet only 48% always verify' -- verification is deferred to an end-of-task PR review (median review time up 441.5%), not performed inline. | A mandatory inline checkpoint that surfaces a human-checkable claim or diff at each meaningful generation step, shifting verification earlier instead of batching it into a single end-of-task review. | + +## What NOT to build (already solved) + +Two items need no new infrastructure. **M1 (complexity-aware routing)** is a mature, named +pattern in the 2026 stack: model tiering (Haiku/Sonnet/Opus via `/model`), per-agent `model:` +fields in `.claude/agents/`, and LLM gateways (LiteLLM, Portkey, OpenRouter) that already route +by cost/complexity, with "orchestrator-classifies-then-routes to Haiku/Sonnet/Opus by +complexity" documented as a standard orchestration pattern. **M3 (task/session decomposition)** +is equally mature: Subagents (isolated context, final-message-only return), the experimental +Agent Teams model, git worktrees for isolation, and Superpowers' subagent-driven-development +already give parallel fan-out with 60-80% wall-clock savings. Building a new decomposition or +routing *engine* would be reinventing a well-adopted primitive; the honest opportunity in both +cases is a thin transparency/audit layer on top (surfacing *why* a routing or fork decision was +made), not the mechanism itself. + +Three faculties also have substantial existing tooling worth acknowledging even though a gap +remains: **memory** (CLAUDE.md, Auto Memory, Mem0, claude-mem, Hindsight, supermemory, the +Anthropic memory tool API), **imagination** (Plan mode, Explore subagent, Superpowers' +brainstorm-to-review pipeline), and **impact-awareness** (filesystem/memory-knowledge-graph and +Context7 MCP servers, sequential-thinking MCP, sandboxing's codebase trust verification). None +of these should be reinvented from scratch -- the substrate's job is to close the specific, +named gap each one leaves open (below), not to duplicate the retrieval/planning/indexing layer. + +## Genuine whitespace + +Three items are essentially unaddressed by any tool named in the stack landscape file, and each +is independently corroborated by the pain-points report's own "Open gap" / "Build opportunity" +language rather than asserted by us. **Learning from outcomes** has no counterpart at all -- +Auto Memory's "feedback" type stores notes, not verified, evaluated lessons, and nothing in the +stack closes the loop from an actual task outcome back into changed future behavior. **M2 +(assumption/uncertainty)** is named explicitly as unsolved: models "rarely signal uncertainty or +say I can't do this," and the report's own build opportunity calls for "calibrated-confidence and +known-unknowns tooling" -- this is also the paper's named ROOT deficit, so it is the highest- +priority build target. **M5 (anti-over-engineering)** has a UI-only analogue (the frontend-design +skill's minimalism discipline) but no general-purpose backend equivalent; scope creep and +premature abstraction are not tracked by any named quality gate. + +Two further items are partial-with-a-documented-gap rather than untouched: **self-correction** +has retry/gate mechanisms in the stack (Stop hooks, the Ralph Wiggum loop, Playwright's healer, +pr-review-toolkit) but the pain-points report names "doom-loop" thrashing and calls automatic +root-cause detection "largely unsolved"; **M6 (inline verification)** has passive +streaming/self-QA but the defining 2026 statistic -- 96% of developers don't fully trust AI code +yet only 48% always verify it -- shows verification is still batched into an end-of-task review, +not performed while code is written. **M4 (goal-anchoring)** and **impact-awareness** round out +the partial column: both have static, one-time anchors (CLAUDE.md, `/goal`, MCP filesystem/memory +retrieval) but no tooling in the stack that continuously re-checks alignment or mandatorily gates +an edit against blast radius as the session progresses. + +## Sources + +- Stack landscape: `source_stack_landscape.md` (mid-2026 Claude Code / agent tooling survey) -- sole source for `existing_tooling`. +- Pain-points report: `source_painpoints_report.md` (full-SDLC field report and build-opportunity map, mid-2026) -- source for residual-gap quotes and named workaround tools cited for context only. diff --git a/research/cognitive-substrate/evidence/evidence_map.json b/research/cognitive-substrate/evidence/evidence_map.json new file mode 100644 index 0000000..bfdbeeb --- /dev/null +++ b/research/cognitive-substrate/evidence/evidence_map.json @@ -0,0 +1,194 @@ +[ + { + "claim_id": "C1_METR_slowdown", + "claim_text": "Experienced open-source developers were 19% SLOWER with AI while believing they were ~20% faster (also forecast 24% speedup beforehand).", + "faculty_or_mechanism_it_supports": "M2 (assumption/uncertainty - miscalibration), P3/self-correction deficit; core 'trust but verify' motivation", + "primary_source": { + "title": "Measuring the Impact of Early-2025 AI on Experienced Open-Source Developer Productivity", + "authors": "METR (Model Evaluation & Threat Research)", + "venue": "arXiv preprint / METR blog", + "year": 2025, + "url_or_doi": "arXiv:2507.09089; https://metr.org/blog/2025-07-10-early-2025-ai-experienced-os-dev-study/" + }, + "number_as_primary_states": "16 experienced developers, 246 tasks in mature repos (avg 22k+ stars, 1M+ lines); AI use INCREASED completion time by 19%; pre-task forecast was 24% speedup; post-task self-estimate was 20% speedup.", + "number_in_field_report": "19% slowdown for experienced devs; matches primary source exactly.", + "status": "confirmed", + "note": "Directly reachable on arXiv and METR's own site; numbers match field report exactly. Caveat directly stated by METR: small sample (16 devs), specific to mature/familiar open-source repos, and AI-averse developers increasingly decline to participate (self-selection risk noted by METR itself)." + }, + { + "claim_id": "C2_SO2025_trust", + "claim_text": "Trust in AI accuracy fell from 40% to 29% (or 46% actively distrust vs 33% trust per detailed breakdown); favorability 72%->60%; 66% say AI answers are 'almost right, but not quite'; 45% say debugging AI code is more time-consuming.", + "faculty_or_mechanism_it_supports": "M2 uncertainty/calibration; M6 inline verification; overall trust/verification-gap thesis", + "primary_source": { + "title": "2025 Stack Overflow Developer Survey (49,000+ respondents, 177 countries)", + "authors": "Stack Overflow", + "venue": "Official survey site / Stack Overflow company blog + press release", + "year": 2025, + "url_or_doi": "https://survey.stackoverflow.co/2025 ; https://survey.stackoverflow.co/2025/ai ; https://stackoverflow.blog/2025/12/29/developers-remain-willing-but-reluctant-to-use-ai-the-2025-developer-survey-results-are-here/" + }, + "number_as_primary_states": "Trust in AI accuracy fell from 40% (prior years) to 29% (2025); positive favorability fell from 72% to 60%; 84% use or plan to use AI tools (up from 76%); 46% actively distrust AI accuracy vs 33% trust it, only 3% 'highly trust'; 66% cite 'almost right, but not quite' as the #1 frustration, which 'often leads to' the #2 frustration, debugging being more time-consuming (45%).", + "number_in_field_report": "Matches primary source essentially exactly on all four sub-figures.", + "status": "confirmed", + "note": "Reached directly on Stack Overflow's own survey site and company blog. Self-reported survey; Stack Overflow's own methodology notes flag respondent self-selection bias (recruited via Stack Overflow's own channels, so more AI-engaged/skeptical developers may be over-represented)." + }, + { + "claim_id": "C3_Veracode_vuln", + "claim_text": "45% of AI-generated code samples introduce an OWASP Top-10 vulnerability; a widely-repeated '2.74x more vulnerabilities than human-written code' figure.", + "faculty_or_mechanism_it_supports": "M5 anti-over-engineering / code-quality thesis; security-verification gap", + "primary_source": { + "title": "2025 GenAI Code Security Report", + "authors": "Veracode", + "venue": "Veracode company report/blog", + "year": 2025, + "url_or_doi": "https://www.veracode.com/resources/analyst-reports/2025-genai-code-security-report/ ; https://www.veracode.com/blog/genai-code-security-report/" + }, + "number_as_primary_states": "Veracode's own report/blog states only the 45% figure (code samples across 100+ LLMs, Java/JS/Python/C# introducing OWASP Top-10 flaws; Java worst at ~72%; XSS failure 86%). Veracode's own public materials located in this search do NOT state a '2.74x' multiplier anywhere.", + "number_in_field_report": "Field report attributes BOTH '45%' and '2.74x more vulnerabilities than human-written code' to Veracode, then separately says the 2.74x figure was 'independently corroborated by CodeRabbit's December 2025 analysis of 470 real-world PRs (2.74x more security vulnerabilities...)'.", + "status": "vendor-only", + "note": "The 45% figure is directly traceable to Veracode's own report (vendor self-reported, not independently reproduced). The '2.74x' figure could NOT be located in Veracode's own primary materials during this search - it appears only in secondary/derivative blog posts (e.g. softwareseni.com) that attribute it to Veracode, while the field report itself sources the same 2.74x number to a DIFFERENT study (CodeRabbit's PR analysis). This looks like a citation conflation between two separate vendor studies that happen to share a number. Treat the 2.74x figure as unverified/possibly misattributed pending direct access to Veracode's full PDF report." + }, + { + "claim_id": "C4_GitClear_duplication", + "claim_text": "~8x rise (2024 vs prior years) in frequency of duplicated/copy-pasted code blocks; copy-paste overtaking refactored ('moved') code for the first time.", + "faculty_or_mechanism_it_supports": "M5 anti-over-engineering; long-term codebase impact-awareness (P5-related)", + "primary_source": { + "title": "AI Copilot Code Quality: 2025 Data Suggests 4x Growth in Code Clones / AI Copilot Code Quality: Evaluating 2024's Increased Defect Rate", + "authors": "GitClear (Bill Harding et al.)", + "venue": "GitClear company research report", + "year": 2025, + "url_or_doi": "https://www.gitclear.com/ai_assistant_code_quality_2025_research ; https://gitclear-public.s3.us-west-2.amazonaws.com/GitClear-AI-Copilot-Code-Quality-2025.pdf" + }, + "number_as_primary_states": "GitClear's own materials are internally inconsistent on the multiplier. The report's own page TITLE reads 'AI Copilot Code Quality: 2025 Data Suggests 4x Growth in Code Clones' (gitclear.com), but the body text of the same report and GitClear's press-mentions page both state duplicated code blocks (5+ lines) 'rose eightfold' / 'increased eightfold' during 2024 (211M changed lines, 2020-2024, Google/Microsoft/Meta/enterprise repos). Secondary summaries split roughly evenly between citing '4x' and '8x'. Underlying non-disputed figures: copy-pasted lines rose from 8.3% (2020) to 12.3% (2024); moved/refactored lines fell from ~24-25% to <10%; 2024 was the first year copy-paste exceeded moved lines. The 4x-vs-8x gap could not be resolved from available pages - likely reflects two different metrics (duplicated-block frequency vs. some other clone measure) reported inconsistently across GitClear's own title/body/press materials.", + "number_in_field_report": "Field report states '8x rise in duplicated code blocks' - this matches GitClear's report BODY and press-mentions page, but GitClear's own page TITLE says '4x Growth in Code Clones,' an internal inconsistency the field report does not surface.", + "status": "vendor-only", + "note": "GitClear is a code-analytics vendor; findings are corroborated by many independent tech-press writeups summarizing the same underlying dataset, but no independent third party has re-run the analysis separately. Correlational, not causal. IMPORTANT ADDITIONAL CAVEAT: GitClear's own materials are internally inconsistent - the report's page title cites '4x' growth in code clones while the body and press page cite an '8x' rise in duplicated blocks. The paper should either cite the specific metric name (duplicated-block frequency, 8x per body text) rather than a bare multiplier, or note both figures and the discrepancy explicitly rather than asserting '8x' as settled." + }, + { + "claim_id": "C5_DORA_amplifier", + "claim_text": "AI's primary role is as an 'amplifier' - magnifying high performers' strengths and low performers' dysfunctions; AI continues to increase delivery instability even as adoption becomes near-universal.", + "faculty_or_mechanism_it_supports": "Systemic framing for all six mechanisms (org context matters, not just model quality)", + "primary_source": { + "title": "State of AI-assisted Software Development 2025 (DORA Report)", + "authors": "Google Cloud DORA team (Nathen Harvey et al.), in collaboration with research partners", + "venue": "Official DORA/Google Cloud report", + "year": 2025, + "url_or_doi": "https://dora.dev/dora-report-2025/ ; https://cloud.google.com/blog/products/ai-machine-learning/announcing-the-2025-dora-report" + }, + "number_as_primary_states": "Nearly 5,000 professionals surveyed (June 13-July 21, 2025) plus 100+ hours interviews; 90% AI adoption (14pp increase from 2024); AI's primary role is 'that of an amplifier... magnifying the strengths of high-performing organisations and the dysfunctions of struggling ones'; in 2025 AI's relationship to delivery throughput reversed to positive vs 2024, but AI continues to increase delivery instability; ~30% report little/no trust in AI-generated code.", + "number_in_field_report": "Matches primary source directly ('AI is an amplifier'; high adoption; throughput/stability tension).", + "status": "confirmed", + "note": "DORA is a Google-run but methodologically transparent, widely-cited industry research program (not a single vendor's self-promotional study); full methodology, sample size and survey window are published. Best-supported of the twelve claims alongside METR." + }, + { + "claim_id": "C6_SWEbench_retirement", + "claim_text": "OpenAI retired SWE-bench Verified (Feb 2026) after finding at least 59.4% of audited (hard/failed) problems had flawed test cases and/or training-data contamination; large score gap vs SWE-bench Pro (e.g. one model ~80.9% Verified vs ~45.9% Pro).", + "faculty_or_mechanism_it_supports": "M6 inline verification / benchmark-trust thesis; supports 'AI output is probabilistic, don't blindly trust metrics'", + "primary_source": { + "title": "Why SWE-bench Verified no longer measures frontier coding capabilities", + "authors": "OpenAI Frontier Evals team (Mia Glaese, Olivia Watkins et al.)", + "venue": "OpenAI official blog", + "year": 2026, + "url_or_doi": "https://openai.com/index/why-we-no-longer-evaluate-swe-bench-verified/" + }, + "number_as_primary_states": "OpenAI audited 138 problems (27.6% subset of the 500-task set) that its o3 model could not reliably solve across 64 runs; found at least 59.4% of THOSE audited problems had flawed test cases/descriptions (35.5% narrow tests, 18.8% wide tests, 5.1% other); also found all tested frontier models could reproduce gold-patch solutions from training memory, indicating contamination. The specific 80.9%-Verified-vs-45.9%-Pro pairing (Claude Opus 4.5) was NOT found stated in OpenAI's own blog; it is reported by third-party benchmark aggregators (e.g. Scale AI SEAL leaderboard, BenchLM.ai, cited via codeant.ai) as of April 2026.", + "number_in_field_report": "Field report's phrasing ('59.4% of audited problems had flawed test cases') is accurate to primary source. The 80.9%/45.9% pairing is directionally correct (large real gap exists) but its precise sourcing is a third-party leaderboard snapshot, not OpenAI's own blog post.", + "status": "confirmed", + "note": "The 59.4%-of-audited-problems figure is directly confirmed on OpenAI's own site - a strong, well-documented primary source. The specific 80.9/45.9 percentage pair is a real, traceable leaderboard snapshot (Scale AI SEAL/BenchLM) but should be cited as such, not as OpenAI's own number, and will drift as models are re-benchmarked." + }, + { + "claim_id": "C7_Faros_PRreview", + "claim_text": "Median time in PR review up 441.5%; incidents-per-PR up 242.7%; bugs per developer up 54%; 31.3% more PRs merged with no review at all.", + "faculty_or_mechanism_it_supports": "M6 inline verification; review-bottleneck / verification-layer thesis", + "primary_source": { + "title": "The AI Engineering Report 2026: The Acceleration Whiplash", + "authors": "Faros AI", + "venue": "Faros AI company research report (telemetry analysis)", + "year": 2026, + "url_or_doi": "https://pages.faros.ai/hubfs/AI_Engineering_Report_2026_The_Acceleration_Whiplash_Faros.pdf ; https://www.faros.ai/blog/ai-acceleration-whiplash-takeaways" + }, + "number_as_primary_states": "Two years of telemetry from 22,000 developers / 4,000+ teams, comparing each org's lowest- vs highest-AI-adoption quarters: median time in PR review +441.5% (average time in review +199.6%, first-review wait +156.6%); incidents-to-PR ratio +242.7%; bugs per developer +54%; 31.3% more PRs merged with no review at all; code churn +861%.", + "number_in_field_report": "Matches primary source numbers exactly.", + "status": "vendor-only", + "note": "Faros AI is an engineering-intelligence vendor whose commercial product monitors exactly these metrics; the report itself and third-party coverage (ADTmag) note these are cross-sectional correlations across the vendor's own customer telemetry, not a controlled study, and 2025-vs-2026 report editions are independent cross-sections rather than a longitudinal panel." + }, + { + "claim_id": "C8_Anthropic_comprehension", + "claim_text": "Developers who delegate code generation to AI score 17% lower on comprehension tests, based on 'Anthropic's own research (~400,000 Claude Code sessions)'.", + "faculty_or_mechanism_it_supports": "M6 inline verification / skill-atrophy thesis (comprehension while writing, not only after)", + "primary_source": { + "title": "TWO DIFFERENT STUDIES ARE BEING CONFLATED: (a) 'How AI Impacts Skill Formation' by Judy Hanwen Shen & Alex Tamkin (arXiv, 2026) - the actual source of the '17% lower comprehension' figure; (b) 'How Claude Code is used in practice' (Anthropic, ~400,000-session analysis) - a real Anthropic study, but about planning/execution decision splits and task-success rates, NOT comprehension testing.", + "authors": "(a) Judy Hanwen Shen, Alex Tamkin (Tamkin at Anthropic); (b) Anthropic", + "venue": "(a) arXiv preprint; (b) Anthropic official research page", + "year": 2026, + "url_or_doi": "(a) referenced via arxiv.org/pdf/2604.14228 citing 'Shen and Tamkin, 2026'; (b) https://www.anthropic.com/research/claude-code-expertise" + }, + "number_as_primary_states": "(a) Shen & Tamkin: developers who used AI to learn a new async-programming library completed tasks but scored measurably worse on a post-task comprehension test ('17% lower' per a secondary citation in an arXiv survey paper - I could not independently pull Shen & Tamkin's own abstract/number in this search, only a citing paper's paraphrase). (b) The 400,000-session Anthropic study found users make ~70% of planning decisions and Claude makes ~80% of execution decisions; occupation-based success rates were similar across professions (~26-34%); it does NOT report a comprehension-score deficit.", + "number_in_field_report": "Field report merges these into one sentence ('Anthropic's own research (~400,000 Claude Code sessions) found... 17% lower on comprehension'), incorrectly attributing the comprehension finding to the session-count study.", + "status": "unverifiable", + "note": "This is a citation-conflation error carried over from the field report (or its own sources). The 400K-session study is real and directly confirmed, but does not contain a comprehension-deficit finding. The '17% lower comprehension' figure traces to a separate, distinct Shen & Tamkin paper that this search could not directly retrieve/confirm in primary form (only via a third paper's citation of it). RECOMMENDATION: if the white paper wants to use the comprehension-deficit claim, cite Shen & Tamkin (2026) directly and verify the 17% figure against their own abstract/paper before use; do not attribute it to the 400K-session study." + }, + { + "claim_id": "C9_Sonar_verification_gap", + "claim_text": "96% of developers don't fully trust AI-generated code is functionally correct, yet only 48% always verify it before committing (a 48-point 'verification gap'/'verification debt').", + "faculty_or_mechanism_it_supports": "M6 inline verification - the central named gap the mechanism targets", + "primary_source": { + "title": "State of Code Developer Survey report 2026", + "authors": "Sonar", + "venue": "Sonar company press release / report PDF", + "year": 2026, + "url_or_doi": "https://www.sonarsource.com/company/press-releases/sonar-data-reveals-critical-verification-gap-in-ai-coding/ ; https://www.sonarsource.com/state-of-code-developer-survey-report.pdf" + }, + "number_as_primary_states": "Survey of 1,100+ (some sources say 1,149) professional developers, January 2026: 96% do not fully trust AI-generated code is functionally correct; only 48% always check AI-assisted code before committing; AI accounts for 42% of committed code (projected 65% by 2027); 38% say reviewing AI code takes more effort than reviewing human code; the term 'verification debt' is attributed to AWS CTO Werner Vogels.", + "number_in_field_report": "Matches primary source exactly.", + "status": "vendor-only", + "note": "Sonar is a code-quality/verification tooling vendor with a direct commercial interest in this narrative; numbers are self-reported survey data, not independently replicated, though the survey size and methodology are transparently disclosed in the primary PDF." + }, + { + "claim_id": "C10_JetBrains_manual_correction", + "claim_text": "JetBrains' 2025 survey found 77% of developers still manually correct AI output for project conventions every session.", + "faculty_or_mechanism_it_supports": "M4 goal-anchoring / M5 anti-over-engineering (convention drift)", + "primary_source": { + "title": "The State of Developer Ecosystem 2025", + "authors": "JetBrains", + "venue": "JetBrains official survey report", + "year": 2025, + "url_or_doi": "https://blog.jetbrains.com/research/2025/10/state-of-developer-ecosystem-2025/ ; https://devecosystem-2025.jetbrains.com/artificial-intelligence" + }, + "number_as_primary_states": "JetBrains' own 2025 report (24,534 developers) confirms 85% regularly use AI tools and 62% rely on at least one AI coding assistant, but this search could not locate any statement of a '77% manually correct AI output for conventions every session' figure anywhere in JetBrains' own materials, blog posts, or press coverage of the 2025 or 2026 editions.", + "number_in_field_report": "77% manually correct for conventions every session (attributed to JetBrains 2025).", + "status": "unverifiable", + "note": "Could not confirm this specific statistic in JetBrains' own primary materials despite multiple targeted searches of the official report, its AI-specific subpage, and secondary coverage. It may be a misremembered/misattributed figure, or drawn from the raw downloadable dataset (500+ questions) rather than the published highlights - the field report should either drop this figure or the paper authors should independently pull it from JetBrains' raw data release before use." + }, + { + "claim_id": "C11_MCP_context_bloat", + "claim_text": "A standard MCP setup (few servers) can consume ~72% of a 200K-token context window before work begins; tool-selection accuracy drops from ~43% to below ~14% as tool count scales ('context rot').", + "faculty_or_mechanism_it_supports": "M1 complexity-aware routing / M3 task decomposition (context budget as a resource to manage)", + "primary_source": { + "title": "(a) 72%-context-window claim: no formal paper found, only recurring blog anecdotes (Scott Spence, Sam McLeod, apideck.com, agentpmt.com) describing an informal measurement ('three servers - GitHub, Playwright, IDE - consumed 143K of 200K tokens'). (b) 43%->14% tool-selection accuracy: RAG-MCP: Mitigating Prompt Bloat in LLM Tool Selection via Retrieval-Augmented Generation.", + "authors": "(b) Qiyao Sun et al.", + "venue": "(b) arXiv preprint", + "year": 2025, + "url_or_doi": "(b) arXiv:2505.03275" + }, + "number_as_primary_states": "(b) RAG-MCP's own 'MCP stress test' (needle-in-a-haystack-style, N candidate MCP schemas with 1 ground truth) found baseline tool-selection accuracy of 13.62% vs 43.13% for their retrieval-augmented method at scale - i.e. the '43% vs 14%' figures are RAG-MCP's OWN method-vs-baseline comparison on a synthetic stress test, not a general real-world degradation curve as tools accumulate. (a) The 72%/143K-token figure is not from any peer-reviewed or vendor-formal study located in this search; it recurs across multiple blogs as an informal, uncredited individual measurement (one specific developer's personal setup: GitHub + Playwright + IDE MCP servers).", + "number_in_field_report": "Field report states these as if they describe general degradation with tool count ('tool-selection accuracy drops from 43% to below 14% as tools accumulate') and cites a 72% context-window consumption figure as an established fact.", + "status": "vendor-only", + "note": "The 43.13%-vs-13.62% numbers ARE real and traceable to a genuine arXiv paper (RAG-MCP), but the field report's framing ('as tools accumulate') mischaracterizes what those specific numbers measure (a baseline vs their proposed retrieval method on one synthetic stress test, not a general accumulation curve). The 72%-window figure has no traceable primary/academic source - only recurring, uncredited blog claims. RECOMMENDATION: if used, cite RAG-MCP correctly as 'a stress test showing retrieval-based tool selection outperforms naive selection at scale' rather than a general context-rot statistic, and treat the 72% figure as illustrative anecdote, not a verified finding." + }, + { + "claim_id": "C12_Panickssery_selfpreference", + "claim_text": "LLM evaluators recognize and favor their own generations - self-preference bias correlates with self-recognition ability - motivating why 'AI verifying AI' is structurally weak.", + "faculty_or_mechanism_it_supports": "M6 inline verification (why an LLM cannot be its own sole verifier); underpins the paper's argument for independent/external verification loops", + "primary_source": { + "title": "LLM Evaluators Recognize and Favor Their Own Generations", + "authors": "Arjun Panickssery, Samuel R. Bowman, Shi Feng", + "venue": "Advances in Neural Information Processing Systems 37 (NeurIPS 2024), Main Conference Track (Oral)", + "year": 2024, + "url_or_doi": "https://proceedings.neurips.cc/paper_files/paper/2024/hash/7f1f0218e45f5414c79c0679633e47bc-Abstract-Conference.html ; arXiv:2404.13076" + }, + "number_as_primary_states": "GPT-4 and Llama 2, used as evaluators, have 'non-trivial accuracy' at distinguishing their own outputs from other LLMs' and humans' outputs; a linear correlation is found between self-recognition capability and strength of self-preference bias (LLM evaluators score their own outputs higher while human annotators rate them as equal quality); fine-tuning to improve self-recognition further amplifies self-preference.", + "number_in_field_report": "Field report's characterization ('LLMs show self-preference/self-recognition bias when evaluating') matches the paper's core finding faithfully; no specific number is claimed by the field report beyond the qualitative finding.", + "status": "confirmed", + "note": "Directly confirmed via the official NeurIPS 2024 proceedings page and the underlying arXiv preprint; a peer-reviewed, widely-cited paper (an NeurIPS 2024 Oral). This is the strongest-quality citation among all twelve (peer-reviewed venue, not industry survey/vendor report)." + } +] \ No newline at end of file diff --git a/research/cognitive-substrate/evidence/evidence_map.md b/research/cognitive-substrate/evidence/evidence_map.md new file mode 100644 index 0000000..901e58d --- /dev/null +++ b/research/cognitive-substrate/evidence/evidence_map.md @@ -0,0 +1,213 @@ +# Evidence Map: Independent Re-Grounding of Pain-Point Statistics + +*12 load-bearing claims verified against primary sources, 5 confirmed, 5 vendor-only, 2 unverifiable.* + +## Summary Table + +| # | Claim | Primary Source | Status | Key Discrepancy | +|---|---|---|---|---| +| 1 | Experienced open-source developers were 19% SLOWER with AI while believing they were ~20% ... | arXiv preprint / METR blog (2025) | ✅ confirmed | See note | +| 2 | Trust in AI accuracy fell from 40% to 29% (or 46% actively distrust vs 33% trust per detai... | Stack Overflow (2025) | ✅ confirmed | See note | +| 3 | 45% of AI-generated code samples introduce an OWASP Top-10 vulnerability; a widely-repeate... | Veracode (2025) | ⚠️ vendor-only | See note | +| 4 | ~8x rise (2024 vs prior years) in frequency of duplicated/copy-pasted code blocks; copy-pa... | GitClear (Bill Harding et al.) (2025) | ⚠️ vendor-only | GitClear's own title says 4x, body/press say 8x - unresolved | +| 5 | AI's primary role is as an 'amplifier' - magnifying high performers' strengths and low per... | Official DORA/Google Cloud report (2025) | ✅ confirmed | See note | +| 6 | OpenAI retired SWE-bench Verified (Feb 2026) after finding at least 59.4% of audited (hard... | OpenAI official blog (2026) | ✅ confirmed | See note | +| 7 | Median time in PR review up 441.5%; incidents-per-PR up 242.7%; bugs per developer up 54%;... | Faros AI (2026) | ⚠️ vendor-only | See note | +| 8 | Developers who delegate code generation to AI score 17% lower on comprehension tests, base... | (a) arXiv preprint; (b) Anthropic official research page (2026) | ❌ unverifiable | See note | +| 9 | 96% of developers don't fully trust AI-generated code is functionally correct, yet only 48... | Sonar (2026) | ⚠️ vendor-only | See note | +| 10 | JetBrains' 2025 survey found 77% of developers still manually correct AI output for projec... | JetBrains (2025) | ❌ unverifiable | See note | +| 11 | A standard MCP setup (few servers) can consume ~72% of a 200K-token context window before ... | (b) Qiyao Sun et al. (2025) | ⚠️ vendor-only | See note | +| 12 | LLM evaluators recognize and favor their own generations - self-preference bias correlates... | Advances in Neural Information Processing Systems 37 (NeurIPS 2024), Main Conference Track (Oral) (2024) | ✅ confirmed | See note | + +## Detailed Findings + +### 1. C1_METR_slowdown: ✅ confirmed + +**Claim:** Experienced open-source developers were 19% SLOWER with AI while believing they were ~20% faster (also forecast 24% speedup beforehand). + +**Supports:** M2 (assumption/uncertainty - miscalibration), P3/self-correction deficit; core 'trust but verify' motivation + +**Primary source:** *Measuring the Impact of Early-2025 AI on Experienced Open-Source Developer Productivity* — METR (Model Evaluation & Threat Research), arXiv preprint / METR blog, 2025. arXiv:2507.09089; https://metr.org/blog/2025-07-10-early-2025-ai-experienced-os-dev-study/ + +**What the primary source actually states:** 16 experienced developers, 246 tasks in mature repos (avg 22k+ stars, 1M+ lines); AI use INCREASED completion time by 19%; pre-task forecast was 24% speedup; post-task self-estimate was 20% speedup. + +**What the field report claimed:** 19% slowdown for experienced devs; matches primary source exactly. + +**Note:** Directly reachable on arXiv and METR's own site; numbers match field report exactly. Caveat directly stated by METR: small sample (16 devs), specific to mature/familiar open-source repos, and AI-averse developers increasingly decline to participate (self-selection risk noted by METR itself). + +### 2. C2_SO2025_trust: ✅ confirmed + +**Claim:** Trust in AI accuracy fell from 40% to 29% (or 46% actively distrust vs 33% trust per detailed breakdown); favorability 72%->60%; 66% say AI answers are 'almost right, but not quite'; 45% say debugging AI code is more time-consuming. + +**Supports:** M2 uncertainty/calibration; M6 inline verification; overall trust/verification-gap thesis + +**Primary source:** *2025 Stack Overflow Developer Survey (49,000+ respondents, 177 countries)* — Stack Overflow, Official survey site / Stack Overflow company blog + press release, 2025. https://survey.stackoverflow.co/2025 ; https://survey.stackoverflow.co/2025/ai ; https://stackoverflow.blog/2025/12/29/developers-remain-willing-but-reluctant-to-use-ai-the-2025-developer-survey-results-are-here/ + +**What the primary source actually states:** Trust in AI accuracy fell from 40% (prior years) to 29% (2025); positive favorability fell from 72% to 60%; 84% use or plan to use AI tools (up from 76%); 46% actively distrust AI accuracy vs 33% trust it, only 3% 'highly trust'; 66% cite 'almost right, but not quite' as the #1 frustration, which 'often leads to' the #2 frustration, debugging being more time-consuming (45%). + +**What the field report claimed:** Matches primary source essentially exactly on all four sub-figures. + +**Note:** Reached directly on Stack Overflow's own survey site and company blog. Self-reported survey; Stack Overflow's own methodology notes flag respondent self-selection bias (recruited via Stack Overflow's own channels, so more AI-engaged/skeptical developers may be over-represented). + +### 3. C3_Veracode_vuln: ⚠️ vendor-only + +**Claim:** 45% of AI-generated code samples introduce an OWASP Top-10 vulnerability; a widely-repeated '2.74x more vulnerabilities than human-written code' figure. + +**Supports:** M5 anti-over-engineering / code-quality thesis; security-verification gap + +**Primary source:** *2025 GenAI Code Security Report* — Veracode, Veracode company report/blog, 2025. https://www.veracode.com/resources/analyst-reports/2025-genai-code-security-report/ ; https://www.veracode.com/blog/genai-code-security-report/ + +**What the primary source actually states:** Veracode's own report/blog states only the 45% figure (code samples across 100+ LLMs, Java/JS/Python/C# introducing OWASP Top-10 flaws; Java worst at ~72%; XSS failure 86%). Veracode's own public materials located in this search do NOT state a '2.74x' multiplier anywhere. + +**What the field report claimed:** Field report attributes BOTH '45%' and '2.74x more vulnerabilities than human-written code' to Veracode, then separately says the 2.74x figure was 'independently corroborated by CodeRabbit's December 2025 analysis of 470 real-world PRs (2.74x more security vulnerabilities...)'. + +**Note:** The 45% figure is directly traceable to Veracode's own report (vendor self-reported, not independently reproduced). The '2.74x' figure could NOT be located in Veracode's own primary materials during this search - it appears only in secondary/derivative blog posts (e.g. softwareseni.com) that attribute it to Veracode, while the field report itself sources the same 2.74x number to a DIFFERENT study (CodeRabbit's PR analysis). This looks like a citation conflation between two separate vendor studies that happen to share a number. Treat the 2.74x figure as unverified/possibly misattributed pending direct access to Veracode's full PDF report. + +### 4. C4_GitClear_duplication: ⚠️ vendor-only + +**Claim:** ~8x rise (2024 vs prior years) in frequency of duplicated/copy-pasted code blocks; copy-paste overtaking refactored ('moved') code for the first time. + +**Supports:** M5 anti-over-engineering; long-term codebase impact-awareness (P5-related) + +**Primary source:** *AI Copilot Code Quality: 2025 Data Suggests 4x Growth in Code Clones / AI Copilot Code Quality: Evaluating 2024's Increased Defect Rate* — GitClear (Bill Harding et al.), GitClear company research report, 2025. https://www.gitclear.com/ai_assistant_code_quality_2025_research ; https://gitclear-public.s3.us-west-2.amazonaws.com/GitClear-AI-Copilot-Code-Quality-2025.pdf + +**What the primary source actually states:** GitClear's own materials are internally inconsistent on the multiplier. The report's own page TITLE reads 'AI Copilot Code Quality: 2025 Data Suggests 4x Growth in Code Clones' (gitclear.com), but the body text of the same report and GitClear's press-mentions page both state duplicated code blocks (5+ lines) 'rose eightfold' / 'increased eightfold' during 2024 (211M changed lines, 2020-2024, Google/Microsoft/Meta/enterprise repos). Secondary summaries split roughly evenly between citing '4x' and '8x'. Underlying non-disputed figures: copy-pasted lines rose from 8.3% (2020) to 12.3% (2024); moved/refactored lines fell from ~24-25% to <10%; 2024 was the first year copy-paste exceeded moved lines. The 4x-vs-8x gap could not be resolved from available pages - likely reflects two different metrics (duplicated-block frequency vs. some other clone measure) reported inconsistently across GitClear's own title/body/press materials. + +**What the field report claimed:** Field report states '8x rise in duplicated code blocks' - this matches GitClear's report BODY and press-mentions page, but GitClear's own page TITLE says '4x Growth in Code Clones,' an internal inconsistency the field report does not surface. + +**Note:** GitClear is a code-analytics vendor; findings are corroborated by many independent tech-press writeups summarizing the same underlying dataset, but no independent third party has re-run the analysis separately. Correlational, not causal. IMPORTANT ADDITIONAL CAVEAT: GitClear's own materials are internally inconsistent - the report's page title cites '4x' growth in code clones while the body and press page cite an '8x' rise in duplicated blocks. The paper should either cite the specific metric name (duplicated-block frequency, 8x per body text) rather than a bare multiplier, or note both figures and the discrepancy explicitly rather than asserting '8x' as settled. + +### 5. C5_DORA_amplifier: ✅ confirmed + +**Claim:** AI's primary role is as an 'amplifier' - magnifying high performers' strengths and low performers' dysfunctions; AI continues to increase delivery instability even as adoption becomes near-universal. + +**Supports:** Systemic framing for all six mechanisms (org context matters, not just model quality) + +**Primary source:** *State of AI-assisted Software Development 2025 (DORA Report)* — Google Cloud DORA team (Nathen Harvey et al.), in collaboration with research partners, Official DORA/Google Cloud report, 2025. https://dora.dev/dora-report-2025/ ; https://cloud.google.com/blog/products/ai-machine-learning/announcing-the-2025-dora-report + +**What the primary source actually states:** Nearly 5,000 professionals surveyed (June 13-July 21, 2025) plus 100+ hours interviews; 90% AI adoption (14pp increase from 2024); AI's primary role is 'that of an amplifier... magnifying the strengths of high-performing organisations and the dysfunctions of struggling ones'; in 2025 AI's relationship to delivery throughput reversed to positive vs 2024, but AI continues to increase delivery instability; ~30% report little/no trust in AI-generated code. + +**What the field report claimed:** Matches primary source directly ('AI is an amplifier'; high adoption; throughput/stability tension). + +**Note:** DORA is a Google-run but methodologically transparent, widely-cited industry research program (not a single vendor's self-promotional study); full methodology, sample size and survey window are published. Best-supported of the twelve claims alongside METR. + +### 6. C6_SWEbench_retirement: ✅ confirmed + +**Claim:** OpenAI retired SWE-bench Verified (Feb 2026) after finding at least 59.4% of audited (hard/failed) problems had flawed test cases and/or training-data contamination; large score gap vs SWE-bench Pro (e.g. one model ~80.9% Verified vs ~45.9% Pro). + +**Supports:** M6 inline verification / benchmark-trust thesis; supports 'AI output is probabilistic, don't blindly trust metrics' + +**Primary source:** *Why SWE-bench Verified no longer measures frontier coding capabilities* — OpenAI Frontier Evals team (Mia Glaese, Olivia Watkins et al.), OpenAI official blog, 2026. https://openai.com/index/why-we-no-longer-evaluate-swe-bench-verified/ + +**What the primary source actually states:** OpenAI audited 138 problems (27.6% subset of the 500-task set) that its o3 model could not reliably solve across 64 runs; found at least 59.4% of THOSE audited problems had flawed test cases/descriptions (35.5% narrow tests, 18.8% wide tests, 5.1% other); also found all tested frontier models could reproduce gold-patch solutions from training memory, indicating contamination. The specific 80.9%-Verified-vs-45.9%-Pro pairing (Claude Opus 4.5) was NOT found stated in OpenAI's own blog; it is reported by third-party benchmark aggregators (e.g. Scale AI SEAL leaderboard, BenchLM.ai, cited via codeant.ai) as of April 2026. + +**What the field report claimed:** Field report's phrasing ('59.4% of audited problems had flawed test cases') is accurate to primary source. The 80.9%/45.9% pairing is directionally correct (large real gap exists) but its precise sourcing is a third-party leaderboard snapshot, not OpenAI's own blog post. + +**Note:** The 59.4%-of-audited-problems figure is directly confirmed on OpenAI's own site - a strong, well-documented primary source. The specific 80.9/45.9 percentage pair is a real, traceable leaderboard snapshot (Scale AI SEAL/BenchLM) but should be cited as such, not as OpenAI's own number, and will drift as models are re-benchmarked. + +### 7. C7_Faros_PRreview: ⚠️ vendor-only + +**Claim:** Median time in PR review up 441.5%; incidents-per-PR up 242.7%; bugs per developer up 54%; 31.3% more PRs merged with no review at all. + +**Supports:** M6 inline verification; review-bottleneck / verification-layer thesis + +**Primary source:** *The AI Engineering Report 2026: The Acceleration Whiplash* — Faros AI, Faros AI company research report (telemetry analysis), 2026. https://pages.faros.ai/hubfs/AI_Engineering_Report_2026_The_Acceleration_Whiplash_Faros.pdf ; https://www.faros.ai/blog/ai-acceleration-whiplash-takeaways + +**What the primary source actually states:** Two years of telemetry from 22,000 developers / 4,000+ teams, comparing each org's lowest- vs highest-AI-adoption quarters: median time in PR review +441.5% (average time in review +199.6%, first-review wait +156.6%); incidents-to-PR ratio +242.7%; bugs per developer +54%; 31.3% more PRs merged with no review at all; code churn +861%. + +**What the field report claimed:** Matches primary source numbers exactly. + +**Note:** Faros AI is an engineering-intelligence vendor whose commercial product monitors exactly these metrics; the report itself and third-party coverage (ADTmag) note these are cross-sectional correlations across the vendor's own customer telemetry, not a controlled study, and 2025-vs-2026 report editions are independent cross-sections rather than a longitudinal panel. + +### 8. C8_Anthropic_comprehension: ❌ unverifiable + +**Claim:** Developers who delegate code generation to AI score 17% lower on comprehension tests, based on 'Anthropic's own research (~400,000 Claude Code sessions)'. + +**Supports:** M6 inline verification / skill-atrophy thesis (comprehension while writing, not only after) + +**Primary source:** *TWO DIFFERENT STUDIES ARE BEING CONFLATED: (a) 'How AI Impacts Skill Formation' by Judy Hanwen Shen & Alex Tamkin (arXiv, 2026) - the actual source of the '17% lower comprehension' figure; (b) 'How Claude Code is used in practice' (Anthropic, ~400,000-session analysis) - a real Anthropic study, but about planning/execution decision splits and task-success rates, NOT comprehension testing.* — (a) Judy Hanwen Shen, Alex Tamkin (Tamkin at Anthropic); (b) Anthropic, (a) arXiv preprint; (b) Anthropic official research page, 2026. (a) referenced via arxiv.org/pdf/2604.14228 citing 'Shen and Tamkin, 2026'; (b) https://www.anthropic.com/research/claude-code-expertise + +**What the primary source actually states:** (a) Shen & Tamkin: developers who used AI to learn a new async-programming library completed tasks but scored measurably worse on a post-task comprehension test ('17% lower' per a secondary citation in an arXiv survey paper - I could not independently pull Shen & Tamkin's own abstract/number in this search, only a citing paper's paraphrase). (b) The 400,000-session Anthropic study found users make ~70% of planning decisions and Claude makes ~80% of execution decisions; occupation-based success rates were similar across professions (~26-34%); it does NOT report a comprehension-score deficit. + +**What the field report claimed:** Field report merges these into one sentence ('Anthropic's own research (~400,000 Claude Code sessions) found... 17% lower on comprehension'), incorrectly attributing the comprehension finding to the session-count study. + +**Note:** This is a citation-conflation error carried over from the field report (or its own sources). The 400K-session study is real and directly confirmed, but does not contain a comprehension-deficit finding. The '17% lower comprehension' figure traces to a separate, distinct Shen & Tamkin paper that this search could not directly retrieve/confirm in primary form (only via a third paper's citation of it). RECOMMENDATION: if the white paper wants to use the comprehension-deficit claim, cite Shen & Tamkin (2026) directly and verify the 17% figure against their own abstract/paper before use; do not attribute it to the 400K-session study. + +### 9. C9_Sonar_verification_gap: ⚠️ vendor-only + +**Claim:** 96% of developers don't fully trust AI-generated code is functionally correct, yet only 48% always verify it before committing (a 48-point 'verification gap'/'verification debt'). + +**Supports:** M6 inline verification - the central named gap the mechanism targets + +**Primary source:** *State of Code Developer Survey report 2026* — Sonar, Sonar company press release / report PDF, 2026. https://www.sonarsource.com/company/press-releases/sonar-data-reveals-critical-verification-gap-in-ai-coding/ ; https://www.sonarsource.com/state-of-code-developer-survey-report.pdf + +**What the primary source actually states:** Survey of 1,100+ (some sources say 1,149) professional developers, January 2026: 96% do not fully trust AI-generated code is functionally correct; only 48% always check AI-assisted code before committing; AI accounts for 42% of committed code (projected 65% by 2027); 38% say reviewing AI code takes more effort than reviewing human code; the term 'verification debt' is attributed to AWS CTO Werner Vogels. + +**What the field report claimed:** Matches primary source exactly. + +**Note:** Sonar is a code-quality/verification tooling vendor with a direct commercial interest in this narrative; numbers are self-reported survey data, not independently replicated, though the survey size and methodology are transparently disclosed in the primary PDF. + +### 10. C10_JetBrains_manual_correction: ❌ unverifiable + +**Claim:** JetBrains' 2025 survey found 77% of developers still manually correct AI output for project conventions every session. + +**Supports:** M4 goal-anchoring / M5 anti-over-engineering (convention drift) + +**Primary source:** *The State of Developer Ecosystem 2025* — JetBrains, JetBrains official survey report, 2025. https://blog.jetbrains.com/research/2025/10/state-of-developer-ecosystem-2025/ ; https://devecosystem-2025.jetbrains.com/artificial-intelligence + +**What the primary source actually states:** JetBrains' own 2025 report (24,534 developers) confirms 85% regularly use AI tools and 62% rely on at least one AI coding assistant, but this search could not locate any statement of a '77% manually correct AI output for conventions every session' figure anywhere in JetBrains' own materials, blog posts, or press coverage of the 2025 or 2026 editions. + +**What the field report claimed:** 77% manually correct for conventions every session (attributed to JetBrains 2025). + +**Note:** Could not confirm this specific statistic in JetBrains' own primary materials despite multiple targeted searches of the official report, its AI-specific subpage, and secondary coverage. It may be a misremembered/misattributed figure, or drawn from the raw downloadable dataset (500+ questions) rather than the published highlights - the field report should either drop this figure or the paper authors should independently pull it from JetBrains' raw data release before use. + +### 11. C11_MCP_context_bloat: ⚠️ vendor-only + +**Claim:** A standard MCP setup (few servers) can consume ~72% of a 200K-token context window before work begins; tool-selection accuracy drops from ~43% to below ~14% as tool count scales ('context rot'). + +**Supports:** M1 complexity-aware routing / M3 task decomposition (context budget as a resource to manage) + +**Primary source:** *(a) 72%-context-window claim: no formal paper found, only recurring blog anecdotes (Scott Spence, Sam McLeod, apideck.com, agentpmt.com) describing an informal measurement ('three servers - GitHub, Playwright, IDE - consumed 143K of 200K tokens'). (b) 43%->14% tool-selection accuracy: RAG-MCP: Mitigating Prompt Bloat in LLM Tool Selection via Retrieval-Augmented Generation.* — (b) Qiyao Sun et al., (b) arXiv preprint, 2025. (b) arXiv:2505.03275 + +**What the primary source actually states:** (b) RAG-MCP's own 'MCP stress test' (needle-in-a-haystack-style, N candidate MCP schemas with 1 ground truth) found baseline tool-selection accuracy of 13.62% vs 43.13% for their retrieval-augmented method at scale - i.e. the '43% vs 14%' figures are RAG-MCP's OWN method-vs-baseline comparison on a synthetic stress test, not a general real-world degradation curve as tools accumulate. (a) The 72%/143K-token figure is not from any peer-reviewed or vendor-formal study located in this search; it recurs across multiple blogs as an informal, uncredited individual measurement (one specific developer's personal setup: GitHub + Playwright + IDE MCP servers). + +**What the field report claimed:** Field report states these as if they describe general degradation with tool count ('tool-selection accuracy drops from 43% to below 14% as tools accumulate') and cites a 72% context-window consumption figure as an established fact. + +**Note:** The 43.13%-vs-13.62% numbers ARE real and traceable to a genuine arXiv paper (RAG-MCP), but the field report's framing ('as tools accumulate') mischaracterizes what those specific numbers measure (a baseline vs their proposed retrieval method on one synthetic stress test, not a general accumulation curve). The 72%-window figure has no traceable primary/academic source - only recurring, uncredited blog claims. RECOMMENDATION: if used, cite RAG-MCP correctly as 'a stress test showing retrieval-based tool selection outperforms naive selection at scale' rather than a general context-rot statistic, and treat the 72% figure as illustrative anecdote, not a verified finding. + +### 12. C12_Panickssery_selfpreference: ✅ confirmed + +**Claim:** LLM evaluators recognize and favor their own generations - self-preference bias correlates with self-recognition ability - motivating why 'AI verifying AI' is structurally weak. + +**Supports:** M6 inline verification (why an LLM cannot be its own sole verifier); underpins the paper's argument for independent/external verification loops + +**Primary source:** *LLM Evaluators Recognize and Favor Their Own Generations* — Arjun Panickssery, Samuel R. Bowman, Shi Feng, Advances in Neural Information Processing Systems 37 (NeurIPS 2024), Main Conference Track (Oral), 2024. https://proceedings.neurips.cc/paper_files/paper/2024/hash/7f1f0218e45f5414c79c0679633e47bc-Abstract-Conference.html ; arXiv:2404.13076 + +**What the primary source actually states:** GPT-4 and Llama 2, used as evaluators, have 'non-trivial accuracy' at distinguishing their own outputs from other LLMs' and humans' outputs; a linear correlation is found between self-recognition capability and strength of self-preference bias (LLM evaluators score their own outputs higher while human annotators rate them as equal quality); fine-tuning to improve self-recognition further amplifies self-preference. + +**What the field report claimed:** Field report's characterization ('LLMs show self-preference/self-recognition bias when evaluating') matches the paper's core finding faithfully; no specific number is claimed by the field report beyond the qualitative finding. + +**Note:** Directly confirmed via the official NeurIPS 2024 proceedings page and the underlying arXiv preprint; a peer-reviewed, widely-cited paper (an NeurIPS 2024 Oral). This is the strongest-quality citation among all twelve (peer-reviewed venue, not industry survey/vendor report). + +## What This Means for the Paper + + +**Safe to lean on without hedging (peer-reviewed / official primary source, methodology transparent):** +- METR's 19%-slowdown RCT (C1) — the single best-controlled empirical finding in the set; cite with its own caveats (n=16, mature-repo setting). +- Panickssery et al. NeurIPS 2024 self-preference bias (C12) — the only genuinely peer-reviewed academic paper among the twelve; strongest citation for the M6 argument that an LLM cannot be its sole verifier. +- OpenAI's own retirement of SWE-bench Verified and the 59.4%-of-audited-problems figure (C6) — directly stated on OpenAI's blog. The specific 80.9%/45.9% score pairing, however, should be cited as a third-party leaderboard snapshot (Scale AI SEAL/BenchLM), not as OpenAI's own number, since it will drift release-to-release. +- DORA 2025 "AI is an amplifier" finding (C5) — large, transparent, non-vendor-captured methodology (Google Cloud + independent research partners), the most credible of the survey-based claims. +- Stack Overflow 2025 trust figures (C2) — official large-sample survey (49k+ respondents) with disclosed methodology; cite with the self-selection caveat Stack Overflow itself notes. + +**Usable but must be explicitly hedged as vendor/self-reported (real numbers, but commercially interested source, no independent replication):** +- Veracode 45% OWASP-vulnerability figure (C3) — the 45% number is real and vendor-confirmed; the widely-repeated "2.74x" figure could NOT be traced to Veracode's own report in this search and appears to be conflated with a separate CodeRabbit study. Use 45% only, or independently pull Veracode's full PDF before citing 2.74x. +- GitClear's code-duplication rise (C4) — real, vendor-produced, correlational only, AND internally inconsistent: GitClear's own report page TITLE says "4x Growth in Code Clones" while the report BODY and press-mentions page say duplicated blocks "rose eightfold." The paper should cite the specific underlying metric (e.g. "copy-pasted lines rose from 8.3% to 12.3%, moved/refactored lines fell below 10%") rather than asserting a bare "8x" multiplier as settled, or explicitly note both figures. +- Faros AI's "Acceleration Whiplash" PR-review/incident figures (C7) — real, vendor telemetry, cross-sectional not longitudinal. +- Sonar's 96%-don't-trust / 48%-always-verify verification gap (C9) — real, vendor survey, directly supports the M6 (inline verification) mechanism by name. + +**Must be corrected or dropped:** +- The "Anthropic 400,000-session study found 17% lower comprehension" claim (C8) conflates two different Anthropic-adjacent studies. The 400K-session study is real but does not measure comprehension; the comprehension-deficit figure belongs to a separate Shen & Tamkin paper that could not be independently pulled in this search. **Do not cite the 400K-session study for the comprehension-deficit number** — cite Shen & Tamkin (2026) directly once verified, or drop the specific 17% figure. +- The JetBrains "77% manually correct AI output for conventions" claim (C10) could not be found anywhere in JetBrains' own materials after multiple targeted searches. **Recommend dropping this figure** unless it can be independently located in JetBrains' raw downloadable dataset. +- The MCP context-bloat claims (C11): the 43%→14% tool-selection-accuracy figures ARE real (RAG-MCP, arXiv) but describe a synthetic stress test comparing a proposed method against a naive baseline — not a general "accuracy degrades as tools accumulate" curve as the field report implies. The 72%-of-context-window figure has no traceable formal source, only recurring blog anecdotes about one individual's MCP setup. **Reframe or drop.** + +**Overall calibration for the white paper:** of the twelve claims, two rest on genuinely independent, peer-reviewed or transparently-run research (METR, Panickssery/NeurIPS); one is a strong official primary-source admission (OpenAI's SWE-bench retirement) plus one large transparent multi-stakeholder industry study (DORA); one is a large, disclosed-methodology public survey (Stack Overflow). Five rest on vendor self-reported telemetry/surveys that are real but commercially motivated and not independently replicated (Veracode, GitClear, Faros, Sonar, and the RAG-MCP-adjacent MCP-bloat anecdotes) — and of these, GitClear's own report is additionally internally inconsistent about its headline multiplier (4x vs 8x) and should be cited via its underlying percentages, not a bare multiplier. Two claims as stated in the field report are not supported by verifiable primary sources and should be corrected or removed (the Anthropic-comprehension conflation, and the JetBrains 77% figure). diff --git a/research/cognitive-substrate/figures/eval_precision_recall.png b/research/cognitive-substrate/figures/eval_precision_recall.png new file mode 100644 index 0000000..a098648 Binary files /dev/null and b/research/cognitive-substrate/figures/eval_precision_recall.png differ diff --git a/research/cognitive-substrate/figures/impact_graph.png b/research/cognitive-substrate/figures/impact_graph.png new file mode 100644 index 0000000..684e710 Binary files /dev/null and b/research/cognitive-substrate/figures/impact_graph.png differ diff --git a/research/cognitive-substrate/figures/router_eval.png b/research/cognitive-substrate/figures/router_eval.png new file mode 100644 index 0000000..d046a7a Binary files /dev/null and b/research/cognitive-substrate/figures/router_eval.png differ diff --git a/research/cognitive-substrate/figures/schematic_extended.png b/research/cognitive-substrate/figures/schematic_extended.png new file mode 100644 index 0000000..7d52545 Binary files /dev/null and b/research/cognitive-substrate/figures/schematic_extended.png differ diff --git a/research/cognitive-substrate/figures/schematic_loop.png b/research/cognitive-substrate/figures/schematic_loop.png new file mode 100644 index 0000000..b93d88f Binary files /dev/null and b/research/cognitive-substrate/figures/schematic_loop.png differ diff --git a/research/cognitive-substrate/figures/schematic_router_loop.png b/research/cognitive-substrate/figures/schematic_router_loop.png new file mode 100644 index 0000000..453ef83 Binary files /dev/null and b/research/cognitive-substrate/figures/schematic_router_loop.png differ diff --git a/research/cognitive-substrate/figures/schematic_system.png b/research/cognitive-substrate/figures/schematic_system.png new file mode 100644 index 0000000..c82a702 Binary files /dev/null and b/research/cognitive-substrate/figures/schematic_system.png differ diff --git a/research/cognitive-substrate/literature/gap_map.json b/research/cognitive-substrate/literature/gap_map.json new file mode 100644 index 0000000..96f715a --- /dev/null +++ b/research/cognitive-substrate/literature/gap_map.json @@ -0,0 +1,320 @@ +{ + "memory": { + "structural_lack": "A transformer's only state is its weights (frozen at inference) and its context window (bounded, discarded at session end). There is no write-once, addressable, persistent store that survives past the current forward pass \u2014 every 'memory' the model appears to have is either baked into pretraining or re-supplied as tokens in the prompt.", + "existing_approaches": [ + { + "name": "Memory Networks", + "citation_key": "weston2014", + "arxiv_or_doi": "1410.3916", + "year": 2014, + "core_idea": "An explicit external memory array, addressed and read/written by a learned controller, decoupled from the model's weights.", + "what_it_solves": "Gives a network a slot-addressable store bigger than any hidden state, in principle unbounded.", + "limitation": "Original formulation used hard, non-differentiable memory addressing and required strong supervision; not built for open-ended, streaming natural-language sessions." + }, + { + "name": "End-to-End Memory Networks", + "citation_key": "sukhbaatar2015", + "arxiv_or_doi": "1503.08895", + "year": 2015, + "core_idea": "Soft, differentiable attention over memory slots trained end-to-end with only the final answer as supervision.", + "what_it_solves": "Removes the need for hand-labeled supporting facts; memory read/write becomes a standard trainable operation.", + "limitation": "Memory is still a fixed-size external array baked in at training time, not something a deployed, frozen LLM can grow arbitrarily post-hoc." + }, + { + "name": "Neural Turing Machines", + "citation_key": "graves2014ntm", + "arxiv_or_doi": "1410.5401", + "year": 2014, + "core_idea": "Couples a controller to a differentiable memory matrix with content- and location-based addressing, analogous to a Turing machine tape.", + "what_it_solves": "Demonstrates a network can learn algorithmic read/write/copy operations over external memory via gradient descent.", + "limitation": "Addressing is brittle and hard to scale; the memory is trained jointly with the controller, so it cannot be bolted onto an already-frozen LLM without retraining." + }, + { + "name": "Differentiable Neural Computer (DNC)", + "citation_key": "graves2016dnc", + "arxiv_or_doi": "10.1038/nature20101", + "year": 2016, + "core_idea": "Adds dynamic memory allocation, usage tracking, and temporal links on top of the NTM design.", + "what_it_solves": "Handles variable-sized, graph-structured problems (e.g. family trees, transit maps) requiring memory that grows and is explicitly deallocated.", + "limitation": "Still trained end-to-end as part of one differentiable system; no route to attach a DNC-style store to a fixed, already-trained LLM whose weights cannot change." + }, + { + "name": "Retrieval-Augmented Generation (RAG)", + "citation_key": "lewis2020rag", + "arxiv_or_doi": "2005.11401", + "year": 2020, + "core_idea": "Pairs a frozen or fine-tuned generator with a non-parametric retriever over an external document index; retrieved passages are concatenated into context.", + "what_it_solves": "Gives a frozen model access to a large, updatable external knowledge store without retraining weights \u2014 the closest existing pattern to 'plugging memory into a frozen LLM'.", + "limitation": "Retrieval is stateless per-query lookup, not an accumulating episodic memory: it has no mechanism to write new experience back, to consolidate/forget, or to track what was retrieved and used in a *prior* session; retrieval quality also degrades with noisy/irrelevant chunks and offers no notion of confidence or provenance across turns." + }, + { + "name": "MemGPT", + "citation_key": "packer2023memgpt", + "arxiv_or_doi": "2310.08560", + "year": 2023, + "core_idea": "An OS-inspired paging scheme where the LLM issues function calls to move information between the bounded context ('main memory') and unbounded external storage ('disk').", + "what_it_solves": "Directly attacks the frozen-context problem for an already-deployed LLM: memory management logic lives outside the weights, in an orchestration layer, so no retraining is needed.", + "limitation": "The LLM itself decides what to page in/out via prompted self-calls \u2014 there is no learned signal for what is worth remembering, no forgetting/consolidation policy grounded in usage statistics, and errors in self-management (paging out something needed, or hallucinating what was paged) are not self-correcting." + }, + { + "name": "Generative Agents", + "citation_key": "park2023genagents", + "arxiv_or_doi": "2304.03442", + "year": 2023, + "core_idea": "A memory stream of timestamped observations plus a periodic 'reflection' step that synthesizes higher-level memories from low-level ones, retrieved via recency+importance+relevance scoring.", + "what_it_solves": "Shows a concrete retrieval-and-synthesis loop that produces temporally coherent, believable long-horizon agent behavior from an ever-growing log.", + "limitation": "Reflection quality depends entirely on the frozen LLM's own summarization judgment (no external ground truth to check against); the memory stream grows unboundedly with no true forgetting or compression guarantee, and nothing here targets code-specific state (e.g. 'this function was refactored, that call site was NOT updated')." + } + ], + "residual_gap": "No existing approach gives a frozen coding-agent LLM a memory that is simultaneously: (a) persistent across sessions without retraining, (b) structured enough to answer 'have I seen this bug/pattern before and what happened', (c) equipped with a principled forget/consolidate policy (vs. RAG's stateless retrieval or MemGPT/Generative-Agents' self-managed, unverified paging), and (d) tied to verifiable software artifacts (commits, test outcomes, past edits) rather than free-text summaries the model itself wrote. This is exactly the gap the proposed cognitive substrate's persistent-memory layer targets." + }, + "learning": { + "structural_lack": "Weights are frozen after pretraining/fine-tuning; nothing in a normal inference call updates them. Any apparent 'learning' within a session is really conditioning on the prompt (in-context learning), which vanishes the moment the context is cleared \u2014 there is no mechanism by which an outcome in session N changes the model's behavior in session N+1.", + "existing_approaches": [ + { + "name": "Complementary Learning Systems theory", + "citation_key": "mcclelland1995cls", + "arxiv_or_doi": null, + "year": 1995, + "core_idea": "Biological argument that the brain needs two separate learning systems \u2014 fast hippocampal (episodic) and slow neocortical (structured, interleaved) \u2014 because a single fast-learning system catastrophically overwrites old knowledge.", + "what_it_solves": "Gives a principled account of why online learning and stable long-term knowledge are in tension, and motivates architectures with separate fast/slow update stores.", + "limitation": "A neuroscience theory, not an engineering recipe \u2014 translating hippocampal replay/consolidation into a concrete update rule for a transformer-based agent is still an open design problem." + }, + { + "name": "CLS theory updated (Kumaran, Hassabis, McClelland 2016)", + "citation_key": "kumaran2016cls", + "arxiv_or_doi": "10.1016/j.tics.2016.05.004", + "year": 2016, + "core_idea": "Updates complementary learning systems theory to incorporate deep RL and new episodic-memory findings, arguing intelligent agents need both a fast, instance-based learning system and a slow, structured one, with explicit links to experience replay.", + "what_it_solves": "Connects CLS theory directly to a concrete, already-used ML mechanism (replay buffers) and to deep-RL agent architectures.", + "limitation": "Replay buffers require retraining/fine-tuning of weights offline; still no online, weight-preserving update path for a deployed frozen LLM." + }, + { + "name": "Elastic Weight Consolidation", + "citation_key": "kirkpatrick2017ewc", + "arxiv_or_doi": "1612.00796", + "year": 2017, + "core_idea": "Penalizes changes to parameters that were important (high Fisher information) for previously learned tasks when training on a new task.", + "what_it_solves": "Directly mitigates catastrophic forgetting during sequential fine-tuning, the core failure mode of naive online weight updates.", + "limitation": "Still requires actual gradient-based retraining passes with access to a per-task importance estimate; not applicable to a model an agent developer does not want to (or cannot) retrain per interaction, and doesn't address one-shot 'learn from this single outcome' updates." + }, + { + "name": "Test-Time Training", + "citation_key": "sun2020ttt", + "arxiv_or_doi": "1909.13231", + "year": 2020, + "core_idea": "Updates model parameters at inference time via a self-supervised auxiliary loss computed on the current test input itself.", + "what_it_solves": "Shows weights CAN be adapted per-input at test time without labels, improving robustness to distribution shift.", + "limitation": "Needs a well-defined self-supervised auxiliary task tied to the architecture (e.g. rotation prediction for vision); no established analogue exists for 'this coding agent's edit was reverted by the developer' as a training signal, and updates are typically discarded/reset per example rather than accumulated." + }, + { + "name": "Fast Weights", + "citation_key": "ba2016fastweights", + "arxiv_or_doi": "1610.06258", + "year": 2016, + "core_idea": "A rapidly-decaying auxiliary weight matrix, updated by a Hebbian outer-product rule from recent hidden activity, layered on top of slow, gradient-trained weights.", + "what_it_solves": "Gives a genuine intermediate timescale of adaptation between static weights and the (still bounded) hidden state / context.", + "limitation": "Operates within a single architecture's forward pass and decays quickly (short-horizon); not a mechanism for accumulating durable, cross-session lessons." + }, + { + "name": "LoRA", + "citation_key": "hu2021lora", + "arxiv_or_doi": "2106.09685", + "year": 2021, + "core_idea": "Freezes the base weights and trains small low-rank adapter matrices per layer, making fine-tuning cheap and modular.", + "what_it_solves": "Makes it computationally realistic to produce many small, swappable weight updates instead of full-model fine-tuning \u2014 a plausible substrate for 'per-outcome' incremental learning.", + "limitation": "Still requires an explicit, deliberate training step with a loss and optimizer running outside the normal inference loop; there's no automatic, always-on pathway from 'agent's suggestion was rejected' to 'a LoRA update was applied'." + }, + { + "name": "In-context learning as implicit gradient descent", + "citation_key": "vonoswald2022icl", + "arxiv_or_doi": "2212.07677", + "year": 2022, + "core_idea": "Constructs transformer weights that provably implement gradient-descent steps on an implicit loss purely via forward-pass attention over the prompt.", + "what_it_solves": "Explains mechanistically why in-context learning can mimic optimization, i.e. why prompting can look like learning.", + "limitation": "The 'learning' exists only for the duration of that context window and vanishes with it \u2014 nothing persists to the next call, so it is a simulation of learning, not learning." + }, + { + "name": "GPT ICL as meta-optimization", + "citation_key": "dai2022icl", + "arxiv_or_doi": "2212.10559", + "year": 2022, + "core_idea": "Draws a formal correspondence between attention and gradient-based fine-tuning, treating demonstrations in the prompt as implicit training examples.", + "what_it_solves": "Reinforces that ICL is a real (if implicit) optimization process, giving a theoretical handle on why more/better examples in-context improve performance.", + "limitation": "Same fundamental boundary as above \u2014 the 'meta-gradient' is recomputed from scratch every call from raw context tokens, an expensive and strictly session-local substitute for actually updating weights." + } + ], + "residual_gap": "There is no accepted, low-cost, always-on pathway that takes a concrete outcome from a coding agent's action (a test failure, a human's revert, a code-review comment) and durably changes future behavior \u2014 either by writing to persistent non-parametric state (memory, see above) or by cheaply updating parameters (LoRA-style) \u2014 without a full offline retraining cycle and without catastrophic forgetting. Existing 'learning' mechanisms are either full retraining (EWC, LoRA \u2014 real but slow/deliberate/decoupled from the interaction loop) or in-context simulation (ICL-as-gradient-descent \u2014 real-time but strictly forgotten at session end). Bridging these two into a fast, safe, incremental update loop is unsolved and is what the substrate's online-learning layer targets." + }, + "self_correction": { + "structural_lack": "A transformer has no privileged internal channel that tells it its own output is wrong; any 'checking' it does is just more forward-pass generation conditioned on its own prior tokens, using the same weights and the same possible failure modes that produced the error in the first place \u2014 there is no independent verifier built into the architecture.", + "existing_approaches": [ + { + "name": "Reflexion", + "citation_key": "shinn2023reflexion", + "arxiv_or_doi": "2303.11366", + "year": 2023, + "core_idea": "After a failed attempt (scored by environment feedback), the agent generates a verbal self-reflection and stores it in an episodic buffer that conditions the next attempt.", + "what_it_solves": "Provides a lightweight substitute for RL policy updates \u2014 'reinforcement' via language rather than gradients \u2014 and measurably improves multi-trial task success.", + "limitation": "Requires an external, ground-truth reward/feedback signal (e.g. a test suite, a game score) to know an attempt failed; without that oracle, the reflection step has nothing reliable to reflect on." + }, + { + "name": "Self-Refine", + "citation_key": "madaan2023selfrefine", + "arxiv_or_doi": "2303.17651", + "year": 2023, + "core_idea": "The same frozen LLM alternately plays generator and critic on its own output, iterating refine-critique-refine with no external feedback or training.", + "what_it_solves": "Shows measurable quality gains on several generation tasks purely from self-prompting, with no extra model or data.", + "limitation": "Critic and generator share the same blind spots (same weights, same failure modes), so it cannot catch errors the model doesn't already 'know' are errors \u2014 consistent with the skeptical finding below." + }, + { + "name": "Self-Consistency", + "citation_key": "wang2022selfconsistency", + "arxiv_or_doi": "2203.11171", + "year": 2022, + "core_idea": "Sample many independent chain-of-thought reasoning paths and take the majority-vote final answer instead of one greedy decode.", + "what_it_solves": "Cheaply improves reasoning accuracy by exploiting the fact that correct reasoning paths tend to converge on the same answer more often than incorrect ones.", + "limitation": "Purely statistical marginalization, not correction \u2014 offers no diagnosis of *why* a path is wrong and provides no benefit if the majority of sampled paths share the same systematic error." + }, + { + "name": "Outcome/Process Reward Models (Cobbe 2021)", + "citation_key": "cobbe2021verifiers", + "arxiv_or_doi": "2110.14168", + "year": 2021, + "core_idea": "Train a verifier to score candidate solutions, selecting the highest-ranked one; outcome-based reward modeling.", + "what_it_solves": "Decouples 'checking' from 'generating' by using an independently trained model, escaping the same-weights blind-spot problem that afflicts pure self-critique; process-level supervision (Lightman) catches errors earlier and more reliably than outcome-only checking.", + "limitation": "Needs its own labeled training data (human step correctness annotations, in Lightman's case) and is a fixed, separately-trained artifact \u2014 it does not update from the coding agent's specific, evolving codebase or mistakes, and provides no general code-correctness oracle out of the box." + }, + { + "name": "Process Reward Models (Lightman 2023)", + "citation_key": "lightman2023verify", + "arxiv_or_doi": "2305.20050", + "year": 2023, + "core_idea": "Score each intermediate reasoning step rather than only the final answer; process supervision outperforms outcome supervision for math.", + "what_it_solves": "Decouples 'checking' from 'generating' by using an independently trained model, escaping the same-weights blind-spot problem that afflicts pure self-critique; process-level supervision (Lightman) catches errors earlier and more reliably than outcome-only checking.", + "limitation": "Needs its own labeled training data (human step correctness annotations, in Lightman's case) and is a fixed, separately-trained artifact \u2014 it does not update from the coding agent's specific, evolving codebase or mistakes, and provides no general code-correctness oracle out of the box." + }, + { + "name": "Skeptical evidence: LLMs cannot yet self-correct reasoning", + "citation_key": "huang2023cannot", + "arxiv_or_doi": "2310.01798", + "year": 2023, + "core_idea": "Empirically evaluates intrinsic self-correction (no external feedback) across reasoning benchmarks and finds it frequently makes correct answers worse.", + "what_it_solves": "Nothing by design \u2014 it is a negative/cautionary result \u2014 but it rigorously delineates when self-correction claims in the literature actually depended on hidden external signals (e.g. ground-truth labels used to decide whether to keep correcting).", + "limitation": "N/A (this is the limitation-finding paper itself); its conclusion is that the burden of proof for 'self-correction' claims should be high, and any real system needs a genuine external check, not just more prompting." + } + ], + "residual_gap": "The literature converges on one honest conclusion: self-correction that relies purely on the same frozen weights re-examining their own output is not reliably real (Huang et al.). Approaches that do work (Reflexion, verifiers, process reward models) all inject something the frozen transformer does not have on its own \u2014 an external oracle (unit tests, human labels, a separately trained reward model). For a coding agent specifically, no existing system supplies a cheap, general, always-available 'ground truth' oracle equivalent to a proof checker for code changes (tests exist for some repos but are incomplete, and an LLM-based verifier trained once cannot track an evolving, project-specific notion of correctness). Building that external, evolving verification signal \u2014 not more self-prompting \u2014 is the open problem." + }, + "imagination": { + "structural_lack": "A transformer only maps an input sequence to an output distribution; it has no forward model of 'what happens if I take this action' distinct from just emitting more tokens, and no internal loop that rolls out and evaluates hypothetical futures before committing to an action in the world (or in a codebase).", + "existing_approaches": [ + { + "name": "World Models", + "citation_key": "ha2018worldmodels", + "arxiv_or_doi": "1803.10122", + "year": 2018, + "core_idea": "Learn a compressed generative model of an environment's dynamics (VAE encoder + RNN predictor) and train a small controller by simulating rollouts entirely inside that learned latent model.", + "what_it_solves": "Demonstrates that policies can be learned largely 'in imagination', reducing costly real-environment interaction.", + "limitation": "The world model is trained on a fixed, narrow environment distribution; nothing here transfers to a symbolic domain like source code, where 'dynamics' means program semantics, not pixel/physics prediction." + }, + { + "name": "MuZero", + "citation_key": "schrittwieser2020muzero", + "arxiv_or_doi": "1911.08265", + "year": 2020, + "core_idea": "Learns a latent model of only the quantities needed for planning (reward, value, policy) without reconstructing raw observations, and plans via Monte Carlo Tree Search inside that learned model.", + "what_it_solves": "Shows planning-with-a-learned-model can reach superhuman performance without ever being given the environment's true rules.", + "limitation": "Requires many millions of real environment interactions to train the model and relies on a well-defined, densely-sampleable reward signal \u2014 neither of which is available for 'trying out' a code edit before applying it to a real repository." + }, + { + "name": "Dreamer (Hafner 2020)", + "citation_key": "hafner2019dreamer", + "arxiv_or_doi": "1912.01603", + "year": 2019, + "core_idea": "Learn behaviors by backpropagating through imagined latent trajectories in a learned world model.", + "what_it_solves": "Makes model-based imagination practical and broadly applicable across diverse continuous/discrete control domains.", + "limitation": "Still fundamentally a perception-action loop over continuous or discrete environment states; has no analogue for simulating the effect of a discrete code edit on program behavior, test outcomes, or downstream callers." + }, + { + "name": "DreamerV3 (Hafner 2023)", + "citation_key": "hafner2023dreamerv3", + "arxiv_or_doi": "2301.04104", + "year": 2023, + "core_idea": "A single agent architecture that masters diverse domains from pixels via world models with fixed hyperparameters.", + "what_it_solves": "Makes model-based imagination practical and broadly applicable across diverse continuous/discrete control domains.", + "limitation": "Still fundamentally a perception-action loop over continuous or discrete environment states; has no analogue for simulating the effect of a discrete code edit on program behavior, test outcomes, or downstream callers." + }, + { + "name": "Active inference / free-energy principle", + "citation_key": "friston2010freeenergy", + "arxiv_or_doi": "10.1038/nrn2787", + "year": 2010, + "core_idea": "Casts perception, learning, and action as all minimizing (variational) free energy under a generative model \u2014 the brain constantly predicts sensory consequences of hypothetical actions and picks actions that minimize expected surprise.", + "what_it_solves": "Provides the deepest theoretical grounding for why 'imagining consequences before acting' is computationally necessary and how prediction and action can be unified in one objective.", + "limitation": "A general theoretical framework, not an off-the-shelf algorithm for code; operationalizing 'expected free energy' for 'will this refactor break something' has no existing instantiation." + } + ], + "residual_gap": "Every existing world-model/imagination system is built for continuous perception-action domains (pixels, physics, game boards) with a learnable, differentiable or simulatable dynamics model and a dense reward signal. None of them target the discrete, combinatorial, symbolic domain of source code, where the 'dynamics' to imagine are things like 'which call sites break', 'does this still type-check', 'do the tests still pass'. A coding agent's imagination faculty needs a fast, cheap surrogate simulator over code-change consequences (static analysis, symbolic execution, or an approximate learned model of test/compile outcomes) played out before committing an edit \u2014 this does not exist as a general, reusable component and is a genuinely open build target, not just an application of an existing world-model architecture." + }, + "impact_awareness": { + "structural_lack": "A transformer processes only the tokens in its current context window; it has no persistent, queryable structural model of an entire codebase (call graph, dependency graph, data flow) and therefore cannot know, without being told, what else in a multi-million-line repository depends on a symbol it is about to change.", + "existing_approaches": [ + { + "name": "Program Dependence Graphs", + "citation_key": "ferrante1987pdg", + "arxiv_or_doi": "10.1145/24039.24041", + "year": 1987, + "core_idea": "A graph combining control and data dependence edges between program statements, originally built for compiler optimization.", + "what_it_solves": "Establishes the foundational structural representation from which almost all later slicing / impact-analysis tools derive.", + "limitation": "Built and consumed by traditional static-analysis tooling, not designed to be read or reasoned over by a language model; scaling PDG construction across a huge, evolving, multi-language repo is itself nontrivial." + }, + { + "name": "Interprocedural slicing", + "citation_key": "horwitz1990dependence", + "arxiv_or_doi": "10.1145/77606.77608", + "year": 1990, + "core_idea": "Extends dependence-graph slicing across procedure/function boundaries using summary edges, computing what code can affect (backward slice) or be affected by (forward slice) a given point.", + "what_it_solves": "Gives an exact, sound method (under its assumptions) for the 'what does this change affect' question at the level of individual statements.", + "limitation": "Precise interprocedural slicing is expensive and requires whole-program static analysis machinery per language; it is not integrated with, or exposed to, an LLM-based agent's reasoning process today." + }, + { + "name": "Survey of Program Slicing Techniques", + "citation_key": "tip1994survey", + "arxiv_or_doi": null, + "year": 1994, + "core_idea": "Systematizes the many slicing variants (static/dynamic, forward/backward, conditioned) developed through the 1980s-90s.", + "what_it_solves": "Documents the mature toolbox for exact change-impact reasoning in classical software engineering.", + "limitation": "Predates and does not address integration with statistical/learned models of code at all \u2014 a pure symbolic-methods survey." + }, + { + "name": "Learning to Represent Programs with Graphs", + "citation_key": "allamanis2018graphs", + "arxiv_or_doi": "1711.00740", + "year": 2018, + "core_idea": "Encodes a program as a graph with syntax, control-flow and data-flow edges, and trains a gated graph neural network over it for tasks like variable-misuse and name prediction.", + "what_it_solves": "Bridges the symbolic program-structure representations above with learned, differentiable models \u2014 the first serious attempt to let a neural model 'see' code structure, not just token sequences.", + "limitation": "Trained and evaluated on function-local tasks in a fixed corpus; does not scale to whole-repository, cross-file, evolving-over-time impact reasoning, and is a separate trained GNN, not something wired into an LLM coding agent's decision loop." + }, + { + "name": "code2vec", + "citation_key": "alon2019code2vec", + "arxiv_or_doi": "10.1145/3290353", + "year": 2019, + "core_idea": "Represents a code snippet as a bag of AST paths and learns embeddings predictive of semantic properties (e.g. method names).", + "what_it_solves": "Shows structural (path-based) features can be learned as compact code representations useful for downstream prediction tasks.", + "limitation": "Snippet/function-level representation, not a whole-project dependency model; gives a 'what does this code look like' embedding, not a 'what will break if I change it' answer." + }, + { + "name": "Code Property Graphs", + "citation_key": "yamaguchi2014cpg", + "arxiv_or_doi": "10.1109/sp.2014.44", + "year": 2014, + "core_idea": "Merges AST, control-flow graph, and program-dependence graph into one joint, queryable graph database representation of a codebase, originally for vulnerability discovery.", + "what_it_solves": "Gives a single structural substrate that supports both syntactic pattern queries and dependency/flow queries at scale across a real codebase \u2014 closest existing building block for 'know what already exists and how it connects'.", + "limitation": "Built for security-vulnerability pattern matching, not for change-impact prediction or agent-facing querying; no existing open system wires an LLM coding agent's proposed edits directly into live CPG queries before the edit is applied." + } + ], + "residual_gap": "The symbolic tools to compute exact structural impact (dependence graphs, interprocedural slicing, code property graphs) have existed since the 1980s-2010s and are mature, but none of them are integrated into the loop of an LLM coding agent: today's agents either re-read raw file text within a limited context window or rely on the LLM's own (unverified) guess about what a change affects. There is no standard, load-bearing bridge that (a) maintains a live, incrementally-updated structural graph of the whole repository, (b) lets the agent query 'what depends on this symbol' as a fast, sound lookup before proposing an edit, and (c) feeds the query result back into the LLM's context in a way it reliably uses. Building that bridge \u2014 not inventing new graph-analysis theory \u2014 is the residual, and largely engineering-shaped, gap." + } +} \ No newline at end of file diff --git a/research/cognitive-substrate/literature/gap_map.md b/research/cognitive-substrate/literature/gap_map.md new file mode 100644 index 0000000..ae5d7ee --- /dev/null +++ b/research/cognitive-substrate/literature/gap_map.md @@ -0,0 +1,113 @@ +# Gap-Map: What a Frozen Transformer Structurally Lacks, and What the Literature Already Tries + +Literature grounding for the cognitive-substrate white paper. Five faculties a coding agent needs that a frozen LLM lacks by construction: **memory**, **online learning**, **self-correction**, **imagination/simulation**, and **impact-awareness**. For each: the structural deficit, what existing work attacks it (with citation keys resolving in `references.json`), and the gap that remains for a coding agent specifically. + +## 1. Memory + +**Structural lack.** A transformer's only state is its weights (frozen at inference) and its context window (bounded, discarded at session end). There is no write-once, addressable, persistent store that survives past the current forward pass — every 'memory' the model appears to have is either baked into pretraining or re-supplied as tokens in the prompt. + +**Existing approaches:** + +- **Memory Networks** [`weston2014`, 2014] — An explicit external memory array, addressed and read/written by a learned controller, decoupled from the model's weights. *Solves:* Gives a network a slot-addressable store bigger than any hidden state, in principle unbounded. *Limitation:* Original formulation used hard, non-differentiable memory addressing and required strong supervision; not built for open-ended, streaming natural-language sessions. +- **End-to-End Memory Networks** [`sukhbaatar2015`, 2015] — Soft, differentiable attention over memory slots trained end-to-end with only the final answer as supervision. *Solves:* Removes the need for hand-labeled supporting facts; memory read/write becomes a standard trainable operation. *Limitation:* Memory is still a fixed-size external array baked in at training time, not something a deployed, frozen LLM can grow arbitrarily post-hoc. +- **Neural Turing Machines** [`graves2014ntm`, 2014] — Couples a controller to a differentiable memory matrix with content- and location-based addressing, analogous to a Turing machine tape. *Solves:* Demonstrates a network can learn algorithmic read/write/copy operations over external memory via gradient descent. *Limitation:* Addressing is brittle and hard to scale; the memory is trained jointly with the controller, so it cannot be bolted onto an already-frozen LLM without retraining. +- **Differentiable Neural Computer (DNC)** [`graves2016dnc`, 2016] — Adds dynamic memory allocation, usage tracking, and temporal links on top of the NTM design. *Solves:* Handles variable-sized, graph-structured problems (e.g. family trees, transit maps) requiring memory that grows and is explicitly deallocated. *Limitation:* Still trained end-to-end as part of one differentiable system; no route to attach a DNC-style store to a fixed, already-trained LLM whose weights cannot change. +- **Retrieval-Augmented Generation (RAG)** [`lewis2020rag`, 2020] — Pairs a frozen or fine-tuned generator with a non-parametric retriever over an external document index; retrieved passages are concatenated into context. *Solves:* Gives a frozen model access to a large, updatable external knowledge store without retraining weights — the closest existing pattern to 'plugging memory into a frozen LLM'. *Limitation:* Retrieval is stateless per-query lookup, not an accumulating episodic memory: it has no mechanism to write new experience back, to consolidate/forget, or to track what was retrieved and used in a *prior* session; retrieval quality also degrades with noisy/irrelevant chunks and offers no notion of confidence or provenance across turns. +- **MemGPT** [`packer2023memgpt`, 2023] — An OS-inspired paging scheme where the LLM issues function calls to move information between the bounded context ('main memory') and unbounded external storage ('disk'). *Solves:* Directly attacks the frozen-context problem for an already-deployed LLM: memory management logic lives outside the weights, in an orchestration layer, so no retraining is needed. *Limitation:* The LLM itself decides what to page in/out via prompted self-calls — there is no learned signal for what is worth remembering, no forgetting/consolidation policy grounded in usage statistics, and errors in self-management (paging out something needed, or hallucinating what was paged) are not self-correcting. +- **Generative Agents** [`park2023genagents`, 2023] — A memory stream of timestamped observations plus a periodic 'reflection' step that synthesizes higher-level memories from low-level ones, retrieved via recency+importance+relevance scoring. *Solves:* Shows a concrete retrieval-and-synthesis loop that produces temporally coherent, believable long-horizon agent behavior from an ever-growing log. *Limitation:* Reflection quality depends entirely on the frozen LLM's own summarization judgment (no external ground truth to check against); the memory stream grows unboundedly with no true forgetting or compression guarantee, and nothing here targets code-specific state (e.g. 'this function was refactored, that call site was NOT updated'). + +**Residual gap.** No existing approach gives a frozen coding-agent LLM a memory that is simultaneously: (a) persistent across sessions without retraining, (b) structured enough to answer 'have I seen this bug/pattern before and what happened', (c) equipped with a principled forget/consolidate policy (vs. RAG's stateless retrieval or MemGPT/Generative-Agents' self-managed, unverified paging), and (d) tied to verifiable software artifacts (commits, test outcomes, past edits) rather than free-text summaries the model itself wrote. This is exactly the gap the proposed cognitive substrate's persistent-memory layer targets. + +## 2. Online Learning / Adaptation + +**Structural lack.** Weights are frozen after pretraining/fine-tuning; nothing in a normal inference call updates them. Any apparent 'learning' within a session is really conditioning on the prompt (in-context learning), which vanishes the moment the context is cleared — there is no mechanism by which an outcome in session N changes the model's behavior in session N+1. + +**Existing approaches:** + +- **Complementary Learning Systems theory** [`mcclelland1995cls`, 1995] — Biological argument that the brain needs two separate learning systems — fast hippocampal (episodic) and slow neocortical (structured, interleaved) — because a single fast-learning system catastrophically overwrites old knowledge. *Solves:* Gives a principled account of why online learning and stable long-term knowledge are in tension, and motivates architectures with separate fast/slow update stores. *Limitation:* A neuroscience theory, not an engineering recipe — translating hippocampal replay/consolidation into a concrete update rule for a transformer-based agent is still an open design problem. +- **CLS theory updated (Kumaran, Hassabis, McClelland 2016)** [`kumaran2016cls`, 2016] — Updates complementary learning systems theory to incorporate deep RL and new episodic-memory findings, arguing intelligent agents need both a fast, instance-based learning system and a slow, structured one, with explicit links to experience replay. *Solves:* Connects CLS theory directly to a concrete, already-used ML mechanism (replay buffers) and to deep-RL agent architectures. *Limitation:* Replay buffers require retraining/fine-tuning of weights offline; still no online, weight-preserving update path for a deployed frozen LLM. +- **Elastic Weight Consolidation** [`kirkpatrick2017ewc`, 2017] — Penalizes changes to parameters that were important (high Fisher information) for previously learned tasks when training on a new task. *Solves:* Directly mitigates catastrophic forgetting during sequential fine-tuning, the core failure mode of naive online weight updates. *Limitation:* Still requires actual gradient-based retraining passes with access to a per-task importance estimate; not applicable to a model an agent developer does not want to (or cannot) retrain per interaction, and doesn't address one-shot 'learn from this single outcome' updates. +- **Test-Time Training** [`sun2020ttt`, 2020] — Updates model parameters at inference time via a self-supervised auxiliary loss computed on the current test input itself. *Solves:* Shows weights CAN be adapted per-input at test time without labels, improving robustness to distribution shift. *Limitation:* Needs a well-defined self-supervised auxiliary task tied to the architecture (e.g. rotation prediction for vision); no established analogue exists for 'this coding agent's edit was reverted by the developer' as a training signal, and updates are typically discarded/reset per example rather than accumulated. +- **Fast Weights** [`ba2016fastweights`, 2016] — A rapidly-decaying auxiliary weight matrix, updated by a Hebbian outer-product rule from recent hidden activity, layered on top of slow, gradient-trained weights. *Solves:* Gives a genuine intermediate timescale of adaptation between static weights and the (still bounded) hidden state / context. *Limitation:* Operates within a single architecture's forward pass and decays quickly (short-horizon); not a mechanism for accumulating durable, cross-session lessons. +- **LoRA** [`hu2021lora`, 2021] — Freezes the base weights and trains small low-rank adapter matrices per layer, making fine-tuning cheap and modular. *Solves:* Makes it computationally realistic to produce many small, swappable weight updates instead of full-model fine-tuning — a plausible substrate for 'per-outcome' incremental learning. *Limitation:* Still requires an explicit, deliberate training step with a loss and optimizer running outside the normal inference loop; there's no automatic, always-on pathway from 'agent's suggestion was rejected' to 'a LoRA update was applied'. +- **In-context learning as implicit gradient descent** [`vonoswald2022icl`, 2022] — Constructs transformer weights that provably implement gradient-descent steps on an implicit loss purely via forward-pass attention over the prompt. *Solves:* Explains mechanistically why in-context learning can mimic optimization, i.e. why prompting can look like learning. *Limitation:* The 'learning' exists only for the duration of that context window and vanishes with it — nothing persists to the next call, so it is a simulation of learning, not learning. +- **GPT ICL as meta-optimization** [`dai2022icl`, 2022] — Draws a formal correspondence between attention and gradient-based fine-tuning, treating demonstrations in the prompt as implicit training examples. *Solves:* Reinforces that ICL is a real (if implicit) optimization process, giving a theoretical handle on why more/better examples in-context improve performance. *Limitation:* Same fundamental boundary as above — the 'meta-gradient' is recomputed from scratch every call from raw context tokens, an expensive and strictly session-local substitute for actually updating weights. + +**Residual gap.** There is no accepted, low-cost, always-on pathway that takes a concrete outcome from a coding agent's action (a test failure, a human's revert, a code-review comment) and durably changes future behavior — either by writing to persistent non-parametric state (memory, see above) or by cheaply updating parameters (LoRA-style) — without a full offline retraining cycle and without catastrophic forgetting. Existing 'learning' mechanisms are either full retraining (EWC, LoRA — real but slow/deliberate/decoupled from the interaction loop) or in-context simulation (ICL-as-gradient-descent — real-time but strictly forgotten at session end). Bridging these two into a fast, safe, incremental update loop is unsolved and is what the substrate's online-learning layer targets. + +## 3. Self-Correction / Metacognition + +**Structural lack.** A transformer has no privileged internal channel that tells it its own output is wrong; any 'checking' it does is just more forward-pass generation conditioned on its own prior tokens, using the same weights and the same possible failure modes that produced the error in the first place — there is no independent verifier built into the architecture. + +**Existing approaches:** + +- **Reflexion** [`shinn2023reflexion`, 2023] — After a failed attempt (scored by environment feedback), the agent generates a verbal self-reflection and stores it in an episodic buffer that conditions the next attempt. *Solves:* Provides a lightweight substitute for RL policy updates — 'reinforcement' via language rather than gradients — and measurably improves multi-trial task success. *Limitation:* Requires an external, ground-truth reward/feedback signal (e.g. a test suite, a game score) to know an attempt failed; without that oracle, the reflection step has nothing reliable to reflect on. +- **Self-Refine** [`madaan2023selfrefine`, 2023] — The same frozen LLM alternately plays generator and critic on its own output, iterating refine-critique-refine with no external feedback or training. *Solves:* Shows measurable quality gains on several generation tasks purely from self-prompting, with no extra model or data. *Limitation:* Critic and generator share the same blind spots (same weights, same failure modes), so it cannot catch errors the model doesn't already 'know' are errors — consistent with the skeptical finding below. +- **Self-Consistency** [`wang2022selfconsistency`, 2022] — Sample many independent chain-of-thought reasoning paths and take the majority-vote final answer instead of one greedy decode. *Solves:* Cheaply improves reasoning accuracy by exploiting the fact that correct reasoning paths tend to converge on the same answer more often than incorrect ones. *Limitation:* Purely statistical marginalization, not correction — offers no diagnosis of *why* a path is wrong and provides no benefit if the majority of sampled paths share the same systematic error. +- **Verifier models / Let's Verify Step by Step** [`cobbe2021verifiers,lightman2023verify`, 2021] — Train a separate model (outcome- or, better, process/step-level reward model) to score candidate solutions or reasoning steps, and use it to select among generator samples. *Solves:* Decouples 'checking' from 'generating' by using an independently trained model, escaping the same-weights blind-spot problem that afflicts pure self-critique; process-level supervision (Lightman) catches errors earlier and more reliably than outcome-only checking. *Limitation:* Needs its own labeled training data (human step correctness annotations, in Lightman's case) and is a fixed, separately-trained artifact — it does not update from the coding agent's specific, evolving codebase or mistakes, and provides no general code-correctness oracle out of the box. +- **Skeptical evidence: LLMs cannot yet self-correct reasoning** [`huang2023cannot`, 2023] — Empirically evaluates intrinsic self-correction (no external feedback) across reasoning benchmarks and finds it frequently makes correct answers worse. *Solves:* Nothing by design — it is a negative/cautionary result — but it rigorously delineates when self-correction claims in the literature actually depended on hidden external signals (e.g. ground-truth labels used to decide whether to keep correcting). *Limitation:* N/A (this is the limitation-finding paper itself); its conclusion is that the burden of proof for 'self-correction' claims should be high, and any real system needs a genuine external check, not just more prompting. + +**Residual gap.** The literature converges on one honest conclusion: self-correction that relies purely on the same frozen weights re-examining their own output is not reliably real (Huang et al.). Approaches that do work (Reflexion, verifiers, process reward models) all inject something the frozen transformer does not have on its own — an external oracle (unit tests, human labels, a separately trained reward model). For a coding agent specifically, no existing system supplies a cheap, general, always-available 'ground truth' oracle equivalent to a proof checker for code changes (tests exist for some repos but are incomplete, and an LLM-based verifier trained once cannot track an evolving, project-specific notion of correctness). Building that external, evolving verification signal — not more self-prompting — is the open problem. + +## 4. Imagination / World Models + +**Structural lack.** A transformer only maps an input sequence to an output distribution; it has no forward model of 'what happens if I take this action' distinct from just emitting more tokens, and no internal loop that rolls out and evaluates hypothetical futures before committing to an action in the world (or in a codebase). + +**Existing approaches:** + +- **World Models** [`ha2018worldmodels`, 2018] — Learn a compressed generative model of an environment's dynamics (VAE encoder + RNN predictor) and train a small controller by simulating rollouts entirely inside that learned latent model. *Solves:* Demonstrates that policies can be learned largely 'in imagination', reducing costly real-environment interaction. *Limitation:* The world model is trained on a fixed, narrow environment distribution; nothing here transfers to a symbolic domain like source code, where 'dynamics' means program semantics, not pixel/physics prediction. +- **MuZero** [`schrittwieser2020muzero`, 2020] — Learns a latent model of only the quantities needed for planning (reward, value, policy) without reconstructing raw observations, and plans via Monte Carlo Tree Search inside that learned model. *Solves:* Shows planning-with-a-learned-model can reach superhuman performance without ever being given the environment's true rules. *Limitation:* Requires many millions of real environment interactions to train the model and relies on a well-defined, densely-sampleable reward signal — neither of which is available for 'trying out' a code edit before applying it to a real repository. +- **Dreamer / DreamerV3** [`hafner2019dreamer,hafner2023dreamerv3`, 2019] — Learn a recurrent latent world model from experience and train the policy by backpropagating value gradients through imagined multi-step latent rollouts, generalizing across many domains with fixed hyperparameters. *Solves:* Makes model-based imagination practical and broadly applicable across diverse continuous/discrete control domains. *Limitation:* Still fundamentally a perception-action loop over continuous or discrete environment states; has no analogue for simulating the effect of a discrete code edit on program behavior, test outcomes, or downstream callers. +- **Active inference / free-energy principle** [`friston2010freeenergy`, 2010] — Casts perception, learning, and action as all minimizing (variational) free energy under a generative model — the brain constantly predicts sensory consequences of hypothetical actions and picks actions that minimize expected surprise. *Solves:* Provides the deepest theoretical grounding for why 'imagining consequences before acting' is computationally necessary and how prediction and action can be unified in one objective. *Limitation:* A general theoretical framework, not an off-the-shelf algorithm for code; operationalizing 'expected free energy' for 'will this refactor break something' has no existing instantiation. + +**Residual gap.** Every existing world-model/imagination system is built for continuous perception-action domains (pixels, physics, game boards) with a learnable, differentiable or simulatable dynamics model and a dense reward signal. None of them target the discrete, combinatorial, symbolic domain of source code, where the 'dynamics' to imagine are things like 'which call sites break', 'does this still type-check', 'do the tests still pass'. A coding agent's imagination faculty needs a fast, cheap surrogate simulator over code-change consequences (static analysis, symbolic execution, or an approximate learned model of test/compile outcomes) played out before committing an edit — this does not exist as a general, reusable component and is a genuinely open build target, not just an application of an existing world-model architecture. + +## 5. Impact-Awareness / Code Representation + +**Structural lack.** A transformer processes only the tokens in its current context window; it has no persistent, queryable structural model of an entire codebase (call graph, dependency graph, data flow) and therefore cannot know, without being told, what else in a multi-million-line repository depends on a symbol it is about to change. + +**Existing approaches:** + +- **Program Dependence Graphs** [`ferrante1987pdg`, 1987] — A graph combining control and data dependence edges between program statements, originally built for compiler optimization. *Solves:* Establishes the foundational structural representation from which almost all later slicing / impact-analysis tools derive. *Limitation:* Built and consumed by traditional static-analysis tooling, not designed to be read or reasoned over by a language model; scaling PDG construction across a huge, evolving, multi-language repo is itself nontrivial. +- **Interprocedural slicing** [`horwitz1990dependence`, 1990] — Extends dependence-graph slicing across procedure/function boundaries using summary edges, computing what code can affect (backward slice) or be affected by (forward slice) a given point. *Solves:* Gives an exact, sound method (under its assumptions) for the 'what does this change affect' question at the level of individual statements. *Limitation:* Precise interprocedural slicing is expensive and requires whole-program static analysis machinery per language; it is not integrated with, or exposed to, an LLM-based agent's reasoning process today. +- **Survey of Program Slicing Techniques** [`tip1994survey`, 1994] — Systematizes the many slicing variants (static/dynamic, forward/backward, conditioned) developed through the 1980s-90s. *Solves:* Documents the mature toolbox for exact change-impact reasoning in classical software engineering. *Limitation:* Predates and does not address integration with statistical/learned models of code at all — a pure symbolic-methods survey. +- **Learning to Represent Programs with Graphs** [`allamanis2018graphs`, 2018] — Encodes a program as a graph with syntax, control-flow and data-flow edges, and trains a gated graph neural network over it for tasks like variable-misuse and name prediction. *Solves:* Bridges the symbolic program-structure representations above with learned, differentiable models — the first serious attempt to let a neural model 'see' code structure, not just token sequences. *Limitation:* Trained and evaluated on function-local tasks in a fixed corpus; does not scale to whole-repository, cross-file, evolving-over-time impact reasoning, and is a separate trained GNN, not something wired into an LLM coding agent's decision loop. +- **code2vec** [`alon2019code2vec`, 2019] — Represents a code snippet as a bag of AST paths and learns embeddings predictive of semantic properties (e.g. method names). *Solves:* Shows structural (path-based) features can be learned as compact code representations useful for downstream prediction tasks. *Limitation:* Snippet/function-level representation, not a whole-project dependency model; gives a 'what does this code look like' embedding, not a 'what will break if I change it' answer. +- **Code Property Graphs** [`yamaguchi2014cpg`, 2014] — Merges AST, control-flow graph, and program-dependence graph into one joint, queryable graph database representation of a codebase, originally for vulnerability discovery. *Solves:* Gives a single structural substrate that supports both syntactic pattern queries and dependency/flow queries at scale across a real codebase — closest existing building block for 'know what already exists and how it connects'. *Limitation:* Built for security-vulnerability pattern matching, not for change-impact prediction or agent-facing querying; no existing open system wires an LLM coding agent's proposed edits directly into live CPG queries before the edit is applied. + +**Residual gap.** The symbolic tools to compute exact structural impact (dependence graphs, interprocedural slicing, code property graphs) have existed since the 1980s-2010s and are mature, but none of them are integrated into the loop of an LLM coding agent: today's agents either re-read raw file text within a limited context window or rely on the LLM's own (unverified) guess about what a change affects. There is no standard, load-bearing bridge that (a) maintains a live, incrementally-updated structural graph of the whole repository, (b) lets the agent query 'what depends on this symbol' as a fast, sound lookup before proposing an edit, and (c) feeds the query result back into the LLM's context in a way it reliably uses. Building that bridge — not inventing new graph-analysis theory — is the residual, and largely engineering-shaped, gap. + +## Reference List + +- **[weston2014]** Weston, Chopra, Bordes (2014). *Memory Networks* — arXiv:1410.3916. https://arxiv.org/abs/1410.3916 +- **[sukhbaatar2015]** Sukhbaatar, Szlam, Weston, Fergus (2015). *End-To-End Memory Networks* — arXiv:1503.08895. https://arxiv.org/abs/1503.08895 +- **[graves2014ntm]** Graves, Wayne, Danihelka (2014). *Neural Turing Machines* — arXiv:1410.5401. https://arxiv.org/abs/1410.5401 +- **[graves2016dnc]** Graves et al. (2016). *Hybrid computing using a neural network with dynamic external memory* — Nature. https://doi.org/10.1038/nature20101 +- **[lewis2020rag]** Lewis et al. (2020). *Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks* — arXiv:2005.11401 / NeurIPS. https://arxiv.org/abs/2005.11401 +- **[packer2023memgpt]** Packer et al. (2023). *MemGPT: Towards LLMs as Operating Systems* — arXiv:2310.08560. https://arxiv.org/abs/2310.08560 +- **[park2023genagents]** Park et al. (2023). *Generative Agents: Interactive Simulacra of Human Behavior* — arXiv:2304.03442. https://arxiv.org/abs/2304.03442 +- **[mcclelland1995cls]** McClelland, McNaughton, O'Reilly (1995). *Why there are complementary learning systems in the hippocampus and neocortex* — Psychological Review. search: OpenAlex (title match) +- **[kumaran2016cls]** Kumaran, Hassabis, McClelland (2016). *What Learning Systems do Intelligent Agents Need? Complementary Learning Systems Theory Updated* — Trends in Cognitive Sciences, 10.1016/j.tics.2016.05.004. https://doi.org/10.1016/j.tics.2016.05.004 +- **[kirkpatrick2017ewc]** Kirkpatrick et al. (2017). *Overcoming catastrophic forgetting in neural networks* — PNAS / arXiv:1612.00796. https://arxiv.org/abs/1612.00796 +- **[sun2020ttt]** Sun et al. (2020). *Test-Time Training with Self-Supervision for Generalization under Distribution Shifts* — arXiv:1909.13231 / ICML 2020. https://arxiv.org/abs/1909.13231 +- **[ba2016fastweights]** Ba, Hinton, Mnih, Leibo, Ionescu (2016). *Using Fast Weights to Attend to the Recent Past* — arXiv:1610.06258. https://arxiv.org/abs/1610.06258 +- **[hu2021lora]** Hu et al. (2021). *LoRA: Low-Rank Adaptation of Large Language Models* — arXiv:2106.09685. https://arxiv.org/abs/2106.09685 +- **[vonoswald2022icl]** von Oswald et al. (2022). *Transformers Learn In-Context by Gradient Descent* — arXiv:2212.07677. https://arxiv.org/abs/2212.07677 +- **[dai2022icl]** Dai et al. (2022). *Why Can GPT Learn In-Context? Language Models Implicitly Perform Gradient Descent as Meta-Optimizers* — arXiv:2212.10559. https://arxiv.org/abs/2212.10559 +- **[shinn2023reflexion]** Shinn et al. (2023). *Reflexion: Language Agents with Verbal Reinforcement Learning* — arXiv:2303.11366. https://arxiv.org/abs/2303.11366 +- **[madaan2023selfrefine]** Madaan et al. (2023). *Self-Refine: Iterative Refinement with Self-Feedback* — arXiv:2303.17651. https://arxiv.org/abs/2303.17651 +- **[wang2022selfconsistency]** Wang et al. (2022). *Self-Consistency Improves Chain of Thought Reasoning in Language Models* — arXiv:2203.11171. https://arxiv.org/abs/2203.11171 +- **[cobbe2021verifiers]** Cobbe et al. (2021). *Training Verifiers to Solve Math Word Problems* — arXiv:2110.14168. https://arxiv.org/abs/2110.14168 +- **[lightman2023verify]** Lightman et al. (2023). *Let's Verify Step by Step* — arXiv:2305.20050. https://arxiv.org/abs/2305.20050 +- **[huang2023cannot]** Huang et al. (2023). *Large Language Models Cannot Self-Correct Reasoning Yet* — arXiv:2310.01798. https://arxiv.org/abs/2310.01798 +- **[ha2018worldmodels]** Ha, Schmidhuber (2018). *World Models* — arXiv:1803.10122. https://arxiv.org/abs/1803.10122 +- **[schrittwieser2020muzero]** Schrittwieser et al. (2020). *Mastering Atari, Go, Chess and Shogi by Planning with a Learned Model* — arXiv:1911.08265 / Nature. https://arxiv.org/abs/1911.08265 +- **[hafner2023dreamerv3]** Hafner et al. (2023). *Mastering Diverse Domains through World Models* — arXiv:2301.04104. https://arxiv.org/abs/2301.04104 +- **[hafner2019dreamer]** Hafner et al. (2019). *Dream to Control: Learning Behaviors by Latent Imagination* — arXiv:1912.01603. https://arxiv.org/abs/1912.01603 +- **[friston2010freeenergy]** Friston (2010). *The free-energy principle: a unified brain theory?* — Nature Reviews Neuroscience. https://doi.org/10.1038/nrn2787 +- **[allamanis2018graphs]** Allamanis, Brockschmidt, Khademi (2018). *Learning to Represent Programs with Graphs* — arXiv:1711.00740 / ICLR 2018. https://arxiv.org/abs/1711.00740 +- **[yamaguchi2014cpg]** Yamaguchi, Golde, Arp, Rieck (2014). *Modeling and Discovering Vulnerabilities with Code Property Graphs* — IEEE S&P 2014. https://doi.org/10.1109/sp.2014.44 +- **[alon2019code2vec]** Alon, Zilberstein, Levy, Yahav (2019). *code2vec: Learning Distributed Representations of Code* — POPL 2019 / PACMPL. https://doi.org/10.1145/3290353 +- **[horwitz1990dependence]** Horwitz, Reps, Binkley (1990). *Interprocedural Slicing Using Dependence Graphs* — ACM TOPLAS. https://doi.org/10.1145/77606.77608 +- **[tip1994survey]** Tip (1994). *A Survey of Program Slicing Techniques* — Journal of Programming Languages. search: OpenAlex +- **[ferrante1987pdg]** Ferrante, Ottenstein, Warren (1987). *The Program Dependence Graph and Its Use in Optimization* — ACM TOPLAS. https://doi.org/10.1145/24039.24041 \ No newline at end of file diff --git a/research/cognitive-substrate/literature/references.json b/research/cognitive-substrate/literature/references.json new file mode 100644 index 0000000..3e9566a --- /dev/null +++ b/research/cognitive-substrate/literature/references.json @@ -0,0 +1,322 @@ +[ + { + "citation_key": "weston2014", + "title": "Memory Networks", + "authors_short": "Weston, Chopra, Bordes", + "year": 2014, + "venue_or_arxiv": "arXiv:1410.3916", + "id": "1410.3916", + "url": "https://arxiv.org/abs/1410.3916", + "one_line_claim": "Proposes an explicit, addressable long-term memory component read/written by a neural controller, separate from model parameters." + }, + { + "citation_key": "sukhbaatar2015", + "title": "End-To-End Memory Networks", + "authors_short": "Sukhbaatar, Szlam, Weston, Fergus", + "year": 2015, + "venue_or_arxiv": "arXiv:1503.08895", + "id": "1503.08895", + "url": "https://arxiv.org/abs/1503.08895", + "one_line_claim": "Makes memory-network read/write fully differentiable and trainable end-to-end with weaker supervision than the original Memory Networks." + }, + { + "citation_key": "graves2014ntm", + "title": "Neural Turing Machines", + "authors_short": "Graves, Wayne, Danihelka", + "year": 2014, + "venue_or_arxiv": "arXiv:1410.5401", + "id": "1410.5401", + "url": "https://arxiv.org/abs/1410.5401", + "one_line_claim": "Couples a neural controller to an external memory matrix via differentiable attention, enabling learned algorithms like copy and sort." + }, + { + "citation_key": "graves2016dnc", + "title": "Hybrid computing using a neural network with dynamic external memory", + "authors_short": "Graves et al.", + "year": 2016, + "venue_or_arxiv": "Nature", + "id": "10.1038/nature20101", + "url": "https://doi.org/10.1038/nature20101", + "one_line_claim": "The Differentiable Neural Computer adds dynamic memory allocation and temporal link tracking, letting a network solve graph traversal and reasoning tasks that require variable-sized structured memory." + }, + { + "citation_key": "lewis2020rag", + "title": "Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks", + "authors_short": "Lewis et al.", + "year": 2020, + "venue_or_arxiv": "arXiv:2005.11401 / NeurIPS", + "id": "2005.11401", + "url": "https://arxiv.org/abs/2005.11401", + "one_line_claim": "Combines a parametric seq2seq model with a non-parametric retriever over an external corpus so generation is grounded in retrieved documents rather than frozen weights alone." + }, + { + "citation_key": "packer2023memgpt", + "title": "MemGPT: Towards LLMs as Operating Systems", + "authors_short": "Packer et al.", + "year": 2023, + "venue_or_arxiv": "arXiv:2310.08560", + "id": "2310.08560", + "url": "https://arxiv.org/abs/2310.08560", + "one_line_claim": "Treats the LLM context window like virtual memory, using an OS-style paging scheme (self-directed function calls) to move information between a bounded context and external storage to give the illusion of unbounded memory." + }, + { + "citation_key": "park2023genagents", + "title": "Generative Agents: Interactive Simulacra of Human Behavior", + "authors_short": "Park et al.", + "year": 2023, + "venue_or_arxiv": "arXiv:2304.03442", + "id": "2304.03442", + "url": "https://arxiv.org/abs/2304.03442", + "one_line_claim": "Introduces a memory stream of observations plus a reflection mechanism that periodically synthesizes higher-level memories, retrieved and used to condition believable agent behavior." + }, + { + "citation_key": "mcclelland1995cls", + "title": "Why there are complementary learning systems in the hippocampus and neocortex", + "authors_short": "McClelland, McNaughton, O'Reilly", + "year": 1995, + "venue_or_arxiv": "Psychological Review", + "id": null, + "url": "search: OpenAlex (title match)", + "one_line_claim": "Argues the brain needs two learning systems \u2014 a fast hippocampal one for episodic recall and a slow neocortical one for structured, interleaved consolidation \u2014 to avoid catastrophic interference." + }, + { + "citation_key": "kumaran2016cls", + "title": "What Learning Systems do Intelligent Agents Need? Complementary Learning Systems Theory Updated", + "authors_short": "Kumaran, Hassabis, McClelland", + "year": 2016, + "venue_or_arxiv": "Trends in Cognitive Sciences, 10.1016/j.tics.2016.05.004", + "id": "10.1016/j.tics.2016.05.004", + "url": "https://doi.org/10.1016/j.tics.2016.05.004", + "one_line_claim": "Updates complementary learning systems theory in light of deep RL and episodic-memory findings, motivating fast/slow-learning-system architectures as a computational analogue of hippocampal-neocortical interaction." + }, + { + "citation_key": "kirkpatrick2017ewc", + "title": "Overcoming catastrophic forgetting in neural networks", + "authors_short": "Kirkpatrick et al.", + "year": 2017, + "venue_or_arxiv": "PNAS / arXiv:1612.00796", + "id": "1612.00796", + "url": "https://arxiv.org/abs/1612.00796", + "one_line_claim": "Elastic Weight Consolidation penalizes changes to parameters important for earlier tasks (via a Fisher-information-weighted quadratic penalty) to mitigate catastrophic forgetting during sequential training." + }, + { + "citation_key": "sun2020ttt", + "title": "Test-Time Training with Self-Supervision for Generalization under Distribution Shifts", + "authors_short": "Sun et al.", + "year": 2020, + "venue_or_arxiv": "arXiv:1909.13231 / ICML 2020", + "id": "1909.13231", + "url": "https://arxiv.org/abs/1909.13231", + "one_line_claim": "Updates model parameters at test time via a self-supervised auxiliary task on each new input, adapting to distribution shift without labeled data." + }, + { + "citation_key": "ba2016fastweights", + "title": "Using Fast Weights to Attend to the Recent Past", + "authors_short": "Ba, Hinton, Mnih, Leibo, Ionescu", + "year": 2016, + "venue_or_arxiv": "arXiv:1610.06258", + "id": "1610.06258", + "url": "https://arxiv.org/abs/1610.06258", + "one_line_claim": "Introduces a fast-changing weight matrix, updated by a Hebbian-like rule from recent activity, that lets a network attend to its own recent history at a timescale between slow weights and short-term activity." + }, + { + "citation_key": "hu2021lora", + "title": "LoRA: Low-Rank Adaptation of Large Language Models", + "authors_short": "Hu et al.", + "year": 2021, + "venue_or_arxiv": "arXiv:2106.09685", + "id": "2106.09685", + "url": "https://arxiv.org/abs/2106.09685", + "one_line_claim": "Freezes pretrained weights and injects trainable low-rank update matrices per layer, making targeted, cheap fine-tuning/adaptation of large models feasible without touching the full parameter set." + }, + { + "citation_key": "vonoswald2022icl", + "title": "Transformers Learn In-Context by Gradient Descent", + "authors_short": "von Oswald et al.", + "year": 2022, + "venue_or_arxiv": "arXiv:2212.07677", + "id": "2212.07677", + "url": "https://arxiv.org/abs/2212.07677", + "one_line_claim": "Shows constructively that a transformer's forward pass over a prompt can implement steps of gradient descent on an implicit in-context loss, giving a mechanistic account of in-context learning." + }, + { + "citation_key": "dai2022icl", + "title": "Why Can GPT Learn In-Context? Language Models Implicitly Perform Gradient Descent as Meta-Optimizers", + "authors_short": "Dai et al.", + "year": 2022, + "venue_or_arxiv": "arXiv:2212.10559", + "id": "2212.10559", + "url": "https://arxiv.org/abs/2212.10559", + "one_line_claim": "Draws a formal duality between attention and gradient-descent-based finetuning, framing in-context learning as an implicit, weight-unchanging optimization process." + }, + { + "citation_key": "shinn2023reflexion", + "title": "Reflexion: Language Agents with Verbal Reinforcement Learning", + "authors_short": "Shinn et al.", + "year": 2023, + "venue_or_arxiv": "arXiv:2303.11366", + "id": "2303.11366", + "url": "https://arxiv.org/abs/2303.11366", + "one_line_claim": "Has an agent verbally reflect on task feedback/failures and stores that reflection in an episodic memory buffer used to condition subsequent attempts, substituting for gradient-based RL updates." + }, + { + "citation_key": "madaan2023selfrefine", + "title": "Self-Refine: Iterative Refinement with Self-Feedback", + "authors_short": "Madaan et al.", + "year": 2023, + "venue_or_arxiv": "arXiv:2303.17651", + "id": "2303.17651", + "url": "https://arxiv.org/abs/2303.17651", + "one_line_claim": "Uses the same frozen LLM to generate output, critique it, and refine it iteratively in a feedback loop, with no parameter updates or external training signal." + }, + { + "citation_key": "wang2022selfconsistency", + "title": "Self-Consistency Improves Chain of Thought Reasoning in Language Models", + "authors_short": "Wang et al.", + "year": 2022, + "venue_or_arxiv": "arXiv:2203.11171", + "id": "2203.11171", + "url": "https://arxiv.org/abs/2203.11171", + "one_line_claim": "Samples multiple diverse reasoning chains and marginalizes over them by majority vote on the final answer, improving reasoning accuracy without any self-correction step per se." + }, + { + "citation_key": "cobbe2021verifiers", + "title": "Training Verifiers to Solve Math Word Problems", + "authors_short": "Cobbe et al.", + "year": 2021, + "venue_or_arxiv": "arXiv:2110.14168", + "id": "2110.14168", + "url": "https://arxiv.org/abs/2110.14168", + "one_line_claim": "Trains a separate verifier model to score candidate solutions and select among generator samples, offloading correctness-checking to a distinct learned model rather than the generator itself." + }, + { + "citation_key": "lightman2023verify", + "title": "Let's Verify Step by Step", + "authors_short": "Lightman et al.", + "year": 2023, + "venue_or_arxiv": "arXiv:2305.20050", + "id": "2305.20050", + "url": "https://arxiv.org/abs/2305.20050", + "one_line_claim": "Shows a process-level reward model, trained on human step-by-step correctness labels, outperforms outcome-level supervision for catching reasoning errors." + }, + { + "citation_key": "huang2023cannot", + "title": "Large Language Models Cannot Self-Correct Reasoning Yet", + "authors_short": "Huang et al.", + "year": 2023, + "venue_or_arxiv": "arXiv:2310.01798", + "id": "2310.01798", + "url": "https://arxiv.org/abs/2310.01798", + "one_line_claim": "Finds that without external, ground-truth feedback, LLMs prompted to self-critique and revise their own reasoning frequently make correct answers worse, undercutting claims of intrinsic self-correction." + }, + { + "citation_key": "ha2018worldmodels", + "title": "World Models", + "authors_short": "Ha, Schmidhuber", + "year": 2018, + "venue_or_arxiv": "arXiv:1803.10122", + "id": "1803.10122", + "url": "https://arxiv.org/abs/1803.10122", + "one_line_claim": "Trains a compressed generative model of an environment (VAE + RNN) and evolves a small controller entirely inside that learned latent 'dream' simulation before transferring to the real environment." + }, + { + "citation_key": "schrittwieser2020muzero", + "title": "Mastering Atari, Go, Chess and Shogi by Planning with a Learned Model", + "authors_short": "Schrittwieser et al.", + "year": 2020, + "venue_or_arxiv": "arXiv:1911.08265 / Nature", + "id": "1911.08265", + "url": "https://arxiv.org/abs/1911.08265", + "one_line_claim": "MuZero learns a model of only the quantities relevant to planning (reward, value, policy) without reconstructing observations, and plans with MCTS purely in that learned latent model." + }, + { + "citation_key": "hafner2023dreamerv3", + "title": "Mastering Diverse Domains through World Models", + "authors_short": "Hafner et al.", + "year": 2023, + "venue_or_arxiv": "arXiv:2301.04104", + "id": "2301.04104", + "url": "https://arxiv.org/abs/2301.04104", + "one_line_claim": "DreamerV3 learns a world model from experience and trains a policy purely from imagined rollouts inside it, achieving strong performance across many domains with one fixed set of hyperparameters." + }, + { + "citation_key": "hafner2019dreamer", + "title": "Dream to Control: Learning Behaviors by Latent Imagination", + "authors_short": "Hafner et al.", + "year": 2019, + "venue_or_arxiv": "arXiv:1912.01603", + "id": "1912.01603", + "url": "https://arxiv.org/abs/1912.01603", + "one_line_claim": "Backpropagates value gradients directly through imagined multi-step latent trajectories of a learned world model to learn behaviors efficiently, without interacting with the real environment." + }, + { + "citation_key": "friston2010freeenergy", + "title": "The free-energy principle: a unified brain theory?", + "authors_short": "Friston", + "year": 2010, + "venue_or_arxiv": "Nature Reviews Neuroscience", + "id": "10.1038/nrn2787", + "url": "https://doi.org/10.1038/nrn2787", + "one_line_claim": "Proposes that brains (and action) minimize variational free energy, unifying perception, learning, and action under a single generative-model / predictive-coding framework \u2014 active inference." + }, + { + "citation_key": "allamanis2018graphs", + "title": "Learning to Represent Programs with Graphs", + "authors_short": "Allamanis, Brockschmidt, Khademi", + "year": 2018, + "venue_or_arxiv": "arXiv:1711.00740 / ICLR 2018", + "id": "1711.00740", + "url": "https://arxiv.org/abs/1711.00740", + "one_line_claim": "Represents source code as a graph capturing syntax, control flow, and data flow, and applies gated graph neural networks to tasks like variable-misuse detection, giving a structural rather than purely textual code representation." + }, + { + "citation_key": "yamaguchi2014cpg", + "title": "Modeling and Discovering Vulnerabilities with Code Property Graphs", + "authors_short": "Yamaguchi, Golde, Arp, Rieck", + "year": 2014, + "venue_or_arxiv": "IEEE S&P 2014", + "id": "10.1109/sp.2014.44", + "url": "https://doi.org/10.1109/sp.2014.44", + "one_line_claim": "Introduces the code property graph, merging AST, control-flow graph, and program-dependence graph into one joint representation, queryable to discover vulnerability patterns across a codebase." + }, + { + "citation_key": "alon2019code2vec", + "title": "code2vec: Learning Distributed Representations of Code", + "authors_short": "Alon, Zilberstein, Levy, Yahav", + "year": 2019, + "venue_or_arxiv": "POPL 2019 / PACMPL", + "id": "10.1145/3290353", + "url": "https://doi.org/10.1145/3290353", + "one_line_claim": "Represents a code snippet as a bag of AST paths and learns a distributed embedding that predicts semantic properties such as method names, giving a learned structural fingerprint of code." + }, + { + "citation_key": "horwitz1990dependence", + "title": "Interprocedural Slicing Using Dependence Graphs", + "authors_short": "Horwitz, Reps, Binkley", + "year": 1990, + "venue_or_arxiv": "ACM TOPLAS", + "id": "10.1145/77606.77608", + "url": "https://doi.org/10.1145/77606.77608", + "one_line_claim": "Extends program dependence graphs across procedure boundaries to compute interprocedural slices, the structural basis for determining what code is affected by / affects a given statement." + }, + { + "citation_key": "tip1994survey", + "title": "A Survey of Program Slicing Techniques", + "authors_short": "Tip", + "year": 1994, + "venue_or_arxiv": "Journal of Programming Languages", + "id": null, + "url": "search: OpenAlex", + "one_line_claim": "Surveys the family of static and dynamic program-slicing techniques used to identify the subset of a program that can influence (or is influenced by) a given point \u2014 a core building block of change-impact analysis." + }, + { + "citation_key": "ferrante1987pdg", + "title": "The Program Dependence Graph and Its Use in Optimization", + "authors_short": "Ferrante, Ottenstein, Warren", + "year": 1987, + "venue_or_arxiv": "ACM TOPLAS", + "id": "10.1145/24039.24041", + "url": "https://doi.org/10.1145/24039.24041", + "one_line_claim": "Introduces the program dependence graph combining control and data dependence in one structure, the ancestor representation behind most modern static change-impact and slicing tools." + } +] \ No newline at end of file diff --git a/research/cognitive-substrate/quranic-lens/all_tafsir.json b/research/cognitive-substrate/quranic-lens/all_tafsir.json new file mode 100644 index 0000000..d3e49e1 --- /dev/null +++ b/research/cognitive-substrate/quranic-lens/all_tafsir.json @@ -0,0 +1,29 @@ +{ + "33:72": { + "ayahs": [ + "33:72" + ], + "range": "33:72", + "text": "

How Man bore the Amanah

Al-`Awfi reported that Ibn `Abbas said, \"Al-Amanah means obedience. This was offered to them before it was offered to Adam, and they could not bear it. Then Allah said to Adam: `I have offered the Amanah to the heavens and the earth and the mountains, and they could not bear it. Will you take it on' He said, `O Lord, what does it involve' He said, `If you do good, you will be rewarded, and if you do evil, you will be punished.' So Adam took the Amanah and bore it, and this is what is referred to in the Ayah:

وَحَمَلَهَا الإِنْسَـنُ إِنَّهُ كَانَ ظَلُوماً جَهُولاً

(But man bore it. Verily, he was unjust and ignorant.)\" `Ali bin Abi Talhah reported that Ibn `Abbas said, \"Al-Amanah means Al-Fara'id (the obligatory duties). Allah offered them to the heavens and the earth and the mountains, (on the grounds that) if they fulfilled them, He would reward them; and if they failed, He would punish them. But they did not want to do that, and they were afraid of it, not because their intention was sinful, but because of their respect for the religion of Allah, in case they could not fulfill the obligations involved. Then Allah offered it to Adam, and he accepted it with all that it entailed. This is what is referred to in the Ayah:

وَحَمَلَهَا الإِنْسَـنُ إِنَّهُ كَانَ ظَلُوماً جَهُولاً

(But man bore it. Verily, he was unjust and ignorant. ) meaning, he underestimated the command of Allah.\" This was also the view of Mujahid, Sa`id bin Jubayr, Ad-Dahhak, Al-Hasan Al-Basri and others that Al-Amanah means Al-Fara'id. Others said that it meant obedience. Al-A`mash narrated from Abu Ad-Duha from Masruq that Ubayy bin Ka`b said: \"Part of Al-Amanah means that woman was entrusted with her own chastity.\" Qatadah said: \"Al-Amanah means religion, obligatory duties and prescribed punishments.\" Malik narrated that Zayd bin Aslam said: \"Al-Amanah means three things: prayer, fasting and performing Ghusl to cleanse oneself from sexual impurity.\" There is no contradiction between all of these views; they are all in agreement and all refer to responsibility and the acceptance of commands and prohibitions with their attendant conditions, which is that the one who fulfills this responsibility, will be rewarded; while the one who neglects it, will be punished. Man accepted this despite the fact that he is weak, ignorant and unjust -- except for those whom Allah helps, and Allah is the One Whose help we seek. One of the reports which deal with Al-Amanah is the Hadith recorded by Imam Ahmad from Hudhayfah, may Allah be pleased with him, who said: \"The Messenger of Allah ﷺ told us two Hadiths, one of which I have seen and the other I am still waiting to see. He told us that Al-Amanah is deeply rooted in the heart of man, then the Qur'an was revealed and they know it from the Qur'an and from the Sunnah. Then he told us that Al-Amanah will be taken away. He said,

«يَنَامُ الرَّجُلُ النَّوْمَةَ فَتُقْبَضُ الْأَمَانَةُ مِنْ قَلْبِهِ، فَيَظَلُّ أَثَرُهَا مِثْلَ أَثَرِ الْمَجْلِ كَجَمْرٍ دَحْرَجْتَهُ عَلَى رِجْلِكِ، تَرَاهُ مُنْتَبِرًا وَلَيْسَ فِيهِ شَيْء»

. (A man may sleep and Al-Amanah will be taken from his heart, leaving nothing but a trace like a blister left by a coal if you were to roll it over your leg -- you will see it protruding but there is nothing inside.) Then he took a pebble and rolled it over his leg, then he said:

«فَيُصْبِحُ النَّاسُ يَتَبَايَعُونَ لَا يَكَادُ أَحَدٌ يُؤَدِّي الْأَمَانَةَ حَتَّى يُقَالَ: إِنَّ فِي بَنِي فُلَانٍ رَجُلًا أَمِينًا، حَتَّى يُقَالَ لِلرَّجُلِ مَا أَجْلَدَهُ وَأَظْرَفَهُ وَأَعْقَلَهُ وَمَا فِي قَلْبِهِ حَبَّةُ خَرْدَلٍ مِنْ إِيمَان»

(Then the people will start buying and selling, and hardly anyone will be paying attention to Al-Amanah, until it will be said that among the tribe of so-and-so there is a trustworthy man, and it will said of a man, `how strong he is, how nice and how wise,' and there is not even a mustard seed of faith in his heart.) No doubt, there came upon me a time when I did not mind dealing (bargaining) with anyone of you, for if he was a Muslim, his Islam would compel him to pay me what is due to me, and if he was a Christian, or Jew, the Muslim official would compel him to pay me what is due to me, but today, I do not deal except with such and such person among you.\" It was also recorded in the Two Sahihs from the Hadith of Al-A`mash. Imam Ahmad recorded that `Abdullah bin `Amr, may Allah be pleased with him, said that the Messenger of Allah ﷺ said:

«أَرْبَعٌ إِذَا كُنَّ فِيكَ فَلَا عَلَيْكَ مَا فَاتَكَ مِنَ الدُّنْيَا: حِفْظُ أَمَانَةٍ، وَصِدْقُ حَدِيثٍ، وَحُسْنُ خَلِيقَةٍ، وَعِفَّةُ طُعْمَة»

(There are four things, if you attain them, then whatever you miss in this world will not matter: preserving trust, speaking the truth, being of good character and moderation in eating.)

The Result of taking on the Amanah

لِّيُعَذِّبَ اللَّهُ الْمُنَـفِقِينَ وَالْمُنَـفِقَـتِ وَالْمُشْرِكِينَ وَالْمُشْرِكَـتِ

(So that Allah will punish the hypocrites, men and women, and the men and women who are idolators.) means, because the sons of Adam have undertaken to fulfill the Amanah, which means duties, Allah will punish the men and women among them who are hypocrites, who are those who make an outward display of faith because they fear the believers, but in their hearts they conceal disbelief and in fact are followers of the disbelievers.

وَالْمُشْرِكِينَ وَالْمُشْرِكَـتِ

(and the men and women who are idolators.) these are the ones who both outwardly and inwardly associate others in worship with Allah and go against His Messengers.

وَيَتُوبَ اللَّهُ عَلَى الْمُؤْمِنِينَ وَالْمُؤْمِنَـتِ

(And Allah will pardon the believers, men and women.) means, He will show mercy to the believers among mankind, who believe in Allah and in His angels, Books and Messengers, and who obey Him.

وَكَانَ اللَّهُ غَفُوراً رَّحِيماً

(And Allah is Ever Oft-Forgiving, Most Merciful.) This is end of the Tafsir of Surat Al-Ahzab. Allah's is the praise and thanks.

", + "citation_url": "https://quran.com/en/33/72/tafsirs?tafsirId=169", + "passage_ayah_range": "33:72-73" + }, + "49:6": { + "ayahs": [ + "49:6" + ], + "range": "49:6", + "text": "

Admonishing Those Who call the Prophet from behind Dwellings

Allah the Exalted and Most Blessed admonished those, such as the uncivilized bedouins, who used to call to the Prophet from behind the dwellings which belong to his wives,

أَكْثَرُهُمْ لاَ يَعْقِلُونَ

(most of them have no sense.) Allah the Exalted and Most Honored then ordains the better behavior in this regard,

وَلَوْ أَنَّهُمْ صَبَرُواْ حَتَّى تَخْرُجَ إِلَيْهِمْ لَكَانَ خَيْراً لَّهُمْ

(And if they had patience till you could come out to them, it would have been better for them.) it would have earned them the better benefit of this life and the Hereafter. Allah, Worthy of all praise, then encourages them to turn to Him in repentance.

وَاللَّهُ غَفُورٌ رَّحِيمٌ

(And Allah is Forgiving, Most Merciful.) It was reported that this Ayah was revealed about Al-Aqra` bin Habis At-Tamimi, may Allah be pleased with him, according to more than one source. Imam Ahmad recorded that Al-Aqra` bin Habis said that he called the Messenger of Allah ﷺ from behind his dwellings, saying, \"O Muhammad! O Muhammad!\" \"O Allah's Messenger!\" according to another narration, but the Messenger did not answer him, Al-Aqra` said, \"O Allah's Messenger.

Investigating the Reliability of the News conveyed by Wicked People

Allah the Exalted ordered investigating the news that sinners and the wicked bring, to make sure of its authenticity. Otherwise, if the sinner's word is taken for granted and a decision is based on it, regardless of whether the information is true or not, the authorities will be taking the lead of the sinners. Allah the Exalted and Most Honored forbade taking the path of the corrupted and sinners. This is why groups of the scholars of Hadith refuse to accept narrations from narrators whose reliability is unknown, for they might be from among the wicked people, in reality.

The Prophet's Decision is Better

Allah said,

", + "citation_url": "https://quran.com/en/49/4/tafsirs?tafsirId=169", + "passage_ayah_range": "49:4-6" + }, + "17:36": { + "ayahs": [ + "17:36" + ], + "range": "17:36", + "text": "

Do not speak without Knowledge

`Ali bin Abi Talhah reported that Ibn `Abbas said: \"This means) do not say (anything of which you have no knowledge).\" Al-`Awfi said: \"Do not accuse anyone of that of which you have no knowledge.\" Muhammad bin Al-Hanafiyyah said: \"It means bearing false witness.\" Qatadah said: \"Do not say, `I have seen', when you did not see anything, or `I have heard', when you did not hear anything, or `I know', when you do not know, for Allah will ask you about all of that.\" In conclusion, what they said means that Allah forbids speaking without knowledge and only on the basis of suspicion, which is mere imagination and illusions. As Allah says:

اجْتَنِبُواْ كَثِيراً مِّنَ الظَّنِّ إِنَّ بَعْضَ الظَّنِّ إِثْمٌ

(Avoid much suspicion; indeed some suspicions are sins.) 49:12 According to a Hadith:

«إِيَّاكُمْ وَالظَّنَّنَفَإِنَّ الظَّنَّ أَكْذَبُ الْحَدِيث»

(Beware of suspicion, for suspicion is the falsest of speech.) The following Hadith is found in Sunan Abu Dawud:

«بِئْسَ مَطِيَّةُ الرَّجُلِ: زَعَمُوا»

(What an evil habit it is for a man to say, `They claimed...') According to another Hadith:

«إِنَّ أَفْرَى الْفِرَى أَنْ يُرِيَ الرَّجُلُ عَيْنَيْهِ مَا لَمْ تَرَيَا»

(The worst of lies is for a man to claim to have seen something that he has not seen.) In the Sahih it says:

«مَنْ تَحَلَّمَ حُلْمًا كُلِّفَ يَوْمَ الْقِيَامَةِ أَنْ يَعْقِدَ بَيْنَ شَعِيرَتَيْنِ وَلَيْسَ بِفَاعِل»

(Whoever claims to have seen a dream (when he has not seen) will be told on the Day of Resurrection to make a knot between two barley grains, and he will not be able to do it.)

كُلُّ أُولـئِكَ

(each of those ones) means these faculties, hearing, sight and the heart,

كَانَ عَنْهُ مَسْؤُولاً

(will be questioned.) means, the person will be asked about them on the Day of Resurrection, and they will be asked about him and what he did with them.

", + "citation_url": "https://quran.com/en/17/36/tafsirs?tafsirId=169", + "passage_ayah_range": "17:36" + } +} \ No newline at end of file diff --git a/research/cognitive-substrate/quranic-lens/arabic.json b/research/cognitive-substrate/quranic-lens/arabic.json new file mode 100644 index 0000000..ce03f61 --- /dev/null +++ b/research/cognitive-substrate/quranic-lens/arabic.json @@ -0,0 +1,157 @@ +{ + "ayahs": [ + "17:36", + "49:6", + "2:31", + "2:32", + "20:114", + "96:1", + "96:2", + "96:3", + "96:4", + "96:5", + "39:9", + "4:82", + "47:24", + "33:72" + ], + "results": { + "ar-simple-clean": [ + { + "ayah": "2:31", + "text": "وَعَلَّمَ آدَمَ الْأَسْمَاءَ كُلَّهَا ثُمَّ عَرَضَهُمْ عَلَى الْمَلَائِكَةِ فَقَالَ أَنبِئُونِي بِأَسْمَاءِ هَٰؤُلَاءِ إِن كُنتُمْ صَادِقِينَ" + }, + { + "ayah": "2:32", + "text": "قَالُوا سُبْحَانَكَ لَا عِلْمَ لَنَا إِلَّا مَا عَلَّمْتَنَا ۖ إِنَّكَ أَنتَ الْعَلِيمُ الْحَكِيمُ" + }, + { + "ayah": "4:82", + "text": "أَفَلَا يَتَدَبَّرُونَ الْقُرْآنَ ۚ وَلَوْ كَانَ مِنْ عِندِ غَيْرِ اللَّهِ لَوَجَدُوا فِيهِ اخْتِلَافًا كَثِيرًا" + }, + { + "ayah": "17:36", + "text": "وَلَا تَقْفُ مَا لَيْسَ لَكَ بِهِ عِلْمٌ ۚ إِنَّ السَّمْعَ وَالْبَصَرَ وَالْفُؤَادَ كُلُّ أُولَٰئِكَ كَانَ عَنْهُ مَسْئُولًا" + }, + { + "ayah": "20:114", + "text": "فَتَعَالَى اللَّهُ الْمَلِكُ الْحَقُّ ۗ وَلَا تَعْجَلْ بِالْقُرْآنِ مِن قَبْلِ أَن يُقْضَىٰ إِلَيْكَ وَحْيُهُ ۖ وَقُل رَّبِّ زِدْنِي عِلْمًا" + }, + { + "ayah": "33:72", + "text": "إِنَّا عَرَضْنَا الْأَمَانَةَ عَلَى السَّمَاوَاتِ وَالْأَرْضِ وَالْجِبَالِ فَأَبَيْنَ أَن يَحْمِلْنَهَا وَأَشْفَقْنَ مِنْهَا وَحَمَلَهَا الْإِنسَانُ ۖ إِنَّهُ كَانَ ظَلُومًا جَهُولًا" + }, + { + "ayah": "39:9", + "text": "أَمَّنْ هُوَ قَانِتٌ آنَاءَ اللَّيْلِ سَاجِدًا وَقَائِمًا يَحْذَرُ الْآخِرَةَ وَيَرْجُو رَحْمَةَ رَبِّهِ ۗ قُلْ هَلْ يَسْتَوِي الَّذِينَ يَعْلَمُونَ وَالَّذِينَ لَا يَعْلَمُونَ ۗ إِنَّمَا يَتَذَكَّرُ أُولُو الْأَلْبَابِ" + }, + { + "ayah": "47:24", + "text": "أَفَلَا يَتَدَبَّرُونَ الْقُرْآنَ أَمْ عَلَىٰ قُلُوبٍ أَقْفَالُهَا" + }, + { + "ayah": "49:6", + "text": "يَا أَيُّهَا الَّذِينَ آمَنُوا إِن جَاءَكُمْ فَاسِقٌ بِنَبَإٍ فَتَبَيَّنُوا أَن تُصِيبُوا قَوْمًا بِجَهَالَةٍ فَتُصْبِحُوا عَلَىٰ مَا فَعَلْتُمْ نَادِمِينَ" + }, + { + "ayah": "96:1", + "text": "اقْرَأْ بِاسْمِ رَبِّكَ الَّذِي خَلَقَ" + }, + { + "ayah": "96:2", + "text": "خَلَقَ الْإِنسَانَ مِنْ عَلَقٍ" + }, + { + "ayah": "96:3", + "text": "اقْرَأْ وَرَبُّكَ الْأَكْرَمُ" + }, + { + "ayah": "96:4", + "text": "الَّذِي عَلَّمَ بِالْقَلَمِ" + }, + { + "ayah": "96:5", + "text": "عَلَّمَ الْإِنسَانَ مَا لَمْ يَعْلَمْ" + } + ] + }, + "pagination": { + "total_items": 14, + "has_more": false, + "continuation": null, + "pages": [ + { + "page": 1, + "edition_id": "ar-simple-clean", + "ayah_key": "2:31" + }, + { + "page": 1, + "edition_id": "ar-simple-clean", + "ayah_key": "2:32" + }, + { + "page": 1, + "edition_id": "ar-simple-clean", + "ayah_key": "4:82" + }, + { + "page": 1, + "edition_id": "ar-simple-clean", + "ayah_key": "17:36" + }, + { + "page": 1, + "edition_id": "ar-simple-clean", + "ayah_key": "20:114" + }, + { + "page": 1, + "edition_id": "ar-simple-clean", + "ayah_key": "33:72" + }, + { + "page": 1, + "edition_id": "ar-simple-clean", + "ayah_key": "39:9" + }, + { + "page": 1, + "edition_id": "ar-simple-clean", + "ayah_key": "47:24" + }, + { + "page": 1, + "edition_id": "ar-simple-clean", + "ayah_key": "49:6" + }, + { + "page": 1, + "edition_id": "ar-simple-clean", + "ayah_key": "96:1" + }, + { + "page": 1, + "edition_id": "ar-simple-clean", + "ayah_key": "96:2" + }, + { + "page": 1, + "edition_id": "ar-simple-clean", + "ayah_key": "96:3" + }, + { + "page": 1, + "edition_id": "ar-simple-clean", + "ayah_key": "96:4" + }, + { + "page": 1, + "edition_id": "ar-simple-clean", + "ayah_key": "96:5" + } + ] + }, + "warnings": null, + "grounding_rules": null +} \ No newline at end of file diff --git a/research/cognitive-substrate/quranic-lens/quran_lens.json b/research/cognitive-substrate/quranic-lens/quran_lens.json new file mode 100644 index 0000000..effd354 --- /dev/null +++ b/research/cognitive-substrate/quranic-lens/quran_lens.json @@ -0,0 +1,138 @@ +{ + "caveats": "The Quran is used here as a FRAMING LENS and ETHICS SOURCE for the cognitive substrate design, never as technical authority for an engineering claim. No verse is cited to prove that a particular algorithm works or that a specific data structure is correct — those claims stand or fall on their engineering merits alone. What the Quranic framing provides is: (1) a vocabulary for naming the agent's epistemic obligations (what it owes to truthfulness, to verification, to stewardship), (2) a hierarchy of knowledge (ʿilm → fahm → ḥikma) that motivates a layered memory architecture rather than a flat one, and (3) ethical constraints on autonomy (amāna, tabayyun) that translate into concrete architectural safeguards. Where a mapping is marked 'metaphor,' the analogy is illustrative — it communicates the design motivation but does not uniquely determine the technical solution. Where a mapping is marked 'load-bearing,' the Quranic concept directly motivates a specific architectural decision (e.g., a mandatory verification gate, not an optional one). Even in load-bearing cases, the engineering justification must be independently defensible — the verse explains *why* we insist on this design choice, not *that* it will work. Discovered patterns in the text describe; they do not legislate.", + "grounding_lines": [ + "Grounded with quran.ai: fetch_translation([17:36, 49:6, 2:31, 2:32, 20:114, 96:1-5, 39:9, 4:82, 47:24, 33:72], en-abdel-haleem)", + "Grounded with quran.ai: fetch_quran([17:36, 49:6, 2:31, 2:32, 20:114, 96:1-5, 39:9, 4:82, 47:24, 33:72], ar-simple-clean)", + "Grounded with quran.ai: fetch_tafsir(17:36, en-ibn-kathir)", + "Grounded with quran.ai: fetch_tafsir(49:6, en-ibn-kathir)", + "Grounded with quran.ai: fetch_tafsir(33:72, en-ibn-kathir)" + ], + "mappings": [ + { + "concept_or_verse": "17:36 — lā taqfu (do not pursue without knowledge)", + "arabic_or_ref": "وَلَا تَقْفُ مَا لَيْسَ لَكَ بِهِ عِلْمٌ ۚ إِنَّ السَّمْعَ وَالْبَصَرَ وَالْفُؤَادَ كُلُّ أُولَٰئِكَ كَانَ عَنْهُ مَسْئُولًا", + "retrieved_translation_or_gloss": "Do not follow blindly what you do not know to be true: ears, eyes, and heart, you will be questioned about all these.", + "agent_faculty": "IMPACT-AWARENESS", + "concrete_design_principle": "Before any code mutation (file write, delete, refactor), the agent must run a pre-action verification gate that checks: (1) what entities in the codebase will be affected, (2) whether the agent has sufficient context (has it read the relevant files, tests, and dependents), and (3) whether the predicted outcome is supported by evidence rather than pattern-matched guessing. Actions taken without verified knowledge are blocked, not merely flagged. The verse's structure — 'ears, eyes, heart, you will be questioned about all these' — maps to an audit trail: every sensory channel the agent used (what it read, what it inferred, what it assumed) is logged so the decision can be reconstructed and questioned.", + "load_bearing_vs_metaphor": "load-bearing", + "source": "Grounded with quran.ai: fetch_translation(17:36, en-abdel-haleem); fetch_tafsir(17:36, en-ibn-kathir)" + }, + { + "concept_or_verse": "49:6 — tabayyun (verify reports before acting)", + "arabic_or_ref": "يَا أَيُّهَا الَّذِينَ آمَنُوا إِن جَاءَكُمْ فَاسِقٌ بِنَبَإٍ فَتَبَيَّنُوا أَن تُصِيبُوا قَوْمًا بِجَهَالَةٍ فَتُصْبِحُوا عَلَىٰ مَا فَعَلْتُمْ نَادِمِينَ", + "retrieved_translation_or_gloss": "Believers, if a troublemaker brings you news, check it first, in case you wrong others unwittingly and later regret what you have done,", + "agent_faculty": "SELF-CORRECTION", + "concrete_design_principle": "The agent architecture must include a verification gate between receiving information (from context, tool output, or its own prior reasoning) and acting on it. The verse's operative term tabayyun (تَبَيُّنُوا) demands active investigation, not passive acceptance. Concretely: before applying a code change based on an error report, a user request, or its own diagnosis, the agent must independently verify the claim — re-read the file, re-run the test, check that the error still exists. This prevents cascading damage from stale context, hallucinated errors, or misunderstood instructions. The gate is architectural (a mandatory step in the action pipeline), not advisory (a prompt asking the model to 'please verify').", + "load_bearing_vs_metaphor": "load-bearing", + "source": "Grounded with quran.ai: fetch_translation(49:6, en-abdel-haleem); fetch_tafsir(49:6, en-ibn-kathir)" + }, + { + "concept_or_verse": "2:31-32 — taʿlīm al-asmāʾ (He taught Adam the names of all things)", + "arabic_or_ref": "وَعَلَّمَ آدَمَ الْأَسْمَاءَ كُلَّهَا ثُمَّ عَرَضَهُمْ عَلَى الْمَلَائِكَةِ فَقَالَ أَنبِئُونِي بِأَسْمَاءِ هَٰؤُلَاءِ إِن كُنتُمْ صَادِقِينَ ﴿٣١﴾ قَالُوا سُبْحَانَكَ لَا عِلْمَ لَنَا إِلَّا مَا عَلَّمْتَنَا ۖ إِنَّكَ أَنتَ الْعَلِيمُ الْحَكِيمُ ﴿٣٢﴾", + "retrieved_translation_or_gloss": "(2:31) He taught Adam all the names [of things], then He showed them to the angels and said, ‘Tell me the names of these if you truly [think you can].’ (2:32) They said, ‘May You be glorified! We have knowledge only of what You have taught us. You are the All Knowing and All Wise.’", + "agent_faculty": "WORLD-MODEL (codebase graph)", + "concrete_design_principle": "The agent must maintain a structured representation of what exists in the codebase — a graph of files, functions, classes, dependencies, and their relationships (the 'names' of things). This is not a flat file listing but a semantic map: knowing that function A calls function B, that module X depends on module Y, that test T covers class C. The verse's point is that knowledge begins with naming — identifying entities and their natures. The angels' admission 'we have knowledge only of what You have taught us' maps precisely to the LLM's situation: it knows only what is in its context window. The external world-model compensates by providing the 'names' (identities and relations) of codebase entities that exceed context capacity.", + "load_bearing_vs_metaphor": "load-bearing", + "source": "Grounded with quran.ai: fetch_translation(2:31-32, en-abdel-haleem)" + }, + { + "concept_or_verse": "20:114 — rabbi zidnī ʿilmā (My Lord, increase me in knowledge)", + "arabic_or_ref": "فَتَعَالَى اللَّهُ الْمَلِكُ الْحَقُّ ۗ وَلَا تَعْجَلْ بِالْقُرْآنِ مِن قَبْلِ أَن يُقْضَىٰ إِلَيْكَ وَحْيُهُ ۖ وَقُل رَّبِّ زِدْنِي عِلْمًا", + "retrieved_translation_or_gloss": "exalted be God, the one who is truly in control. [Prophet], do not rush to recite before the revelation is fully complete but say, ‘Lord, increase me in knowledge!’", + "agent_faculty": "CONTINUAL LEARNING", + "concrete_design_principle": "The agent's knowledge must be treated as perpetually incomplete, with an explicit mechanism for incremental growth. The prayer 'increase me in knowledge' implies that knowledge is not a fixed endowment but an ongoing accumulation. Architecturally: the system maintains a learning store (patterns observed, errors encountered, user corrections accepted) that grows across sessions. Each session's outcomes — what worked, what failed, what the user corrected — feed back into a persistent experience store that updates the agent's priors for future sessions. This is not fine-tuning (the LLM weights stay frozen); it is an external memory that changes what the agent sees on its next input, giving the frozen model a growing context.", + "load_bearing_vs_metaphor": "load-bearing", + "source": "Grounded with quran.ai: fetch_translation(20:114, en-abdel-haleem)" + }, + { + "concept_or_verse": "96:1-5 — iqraʾ / ʿallama bi-l-qalam (Read; taught by the pen)", + "arabic_or_ref": "اقْرَأْ بِاسْمِ رَبِّكَ الَّذِي خَلَقَ ﴿١﴾ خَلَقَ الْإِنسَانَ مِنْ عَلَقٍ ﴿٢﴾ اقْرَأْ وَرَبُّكَ الْأَكْرَمُ ﴿٣﴾ الَّذِي عَلَّمَ بِالْقَلَمِ ﴿٤﴾ عَلَّمَ الْإِنسَانَ مَا لَمْ يَعْلَمْ ﴿٥﴾", + "retrieved_translation_or_gloss": "(96:1) Read! In the name of your Lord who created: (96:2) He created manfrom a clinging form. (96:3) Read! Your Lord is the Most Bountiful One (96:4) who taught by [means of] the pen, (96:5) who taught man what he did not know.", + "agent_faculty": "PERSISTENT MEMORY", + "concrete_design_principle": "Knowledge must be externalized to survive beyond the moment of computation. The pen (al-qalam) is the instrument of externalization — it transforms ephemeral thought into durable record. For the agent: every context window is ephemeral (like unwritten thought), so a persistent memory store (the 'pen') must write down what the agent learns, decides, and observes. The architecture requires: (a) a write-back mechanism that captures salient facts from each session into durable storage, (b) a retrieval mechanism that re-loads relevant past experience into the next session's context, and (c) a consolidation process that organizes raw experience into structured knowledge. 'Taught man what he did not know' — the pen does not just record; it enables the human (or agent) to access knowledge beyond its unaided capacity.", + "load_bearing_vs_metaphor": "load-bearing", + "source": "Grounded with quran.ai: fetch_translation(96:1-5, en-abdel-haleem)" + }, + { + "concept_or_verse": "39:9 — hal yastawī lladhīna yaʿlamūna wa-lladhīna lā yaʿlamūn (are those who know equal to those who do not know?)", + "arabic_or_ref": "أَمَّنْ هُوَ قَانِتٌ آنَاءَ اللَّيْلِ سَاجِدًا وَقَائِمًا يَحْذَرُ الْآخِرَةَ وَيَرْجُو رَحْمَةَ رَبِّهِ ۗ قُلْ هَلْ يَسْتَوِي الَّذِينَ يَعْلَمُونَ وَالَّذِينَ لَا يَعْلَمُونَ ۗ إِنَّمَا يَتَذَكَّرُ أُولُو الْأَلْبَابِ", + "retrieved_translation_or_gloss": "What about someone who worships devoutly during the night, bowing down, standing in prayer, ever mindful of the life to come, hoping for his Lord’s mercy? Say, ‘How can those who know be equal to those who do not know?’ Only those who have understanding will take heed.", + "agent_faculty": "MEMORY + LEARNING (epistemic grounding)", + "concrete_design_principle": "An agent that retains and learns from experience is categorically more capable and more trustworthy than one that does not — this is not a nice-to-have but a qualitative difference. The verse establishes that knowledge is not fungible with ignorance; they produce different outcomes. Design implication: the architecture must distinguish between the agent operating with relevant prior experience loaded (grounded mode) versus operating from the base model alone (ungrounded mode), and should surface this distinction to the user. When the agent lacks relevant experience for a task, it should say so rather than proceeding as if it knows.", + "load_bearing_vs_metaphor": "metaphor (illustrative of the design motivation, not a direct architectural driver)", + "source": "Grounded with quran.ai: fetch_translation(39:9, en-abdel-haleem)" + }, + { + "concept_or_verse": "4:82 — tadabbur al-Qurʾān (do they not reflect deeply upon the Quran; inconsistency as a sign of non-divine origin)", + "arabic_or_ref": "أَفَلَا يَتَدَبَّرُونَ الْقُرْآنَ ۚ وَلَوْ كَانَ مِنْ عِندِ غَيْرِ اللَّهِ لَوَجَدُوا فِيهِ اخْتِلَافًا كَثِيرًا", + "retrieved_translation_or_gloss": "Will they not think about this Quran? If it had been from anyone other than God, they would have found much inconsistency in it.", + "agent_faculty": "SELF-CORRECTION (metacognitive controller)", + "concrete_design_principle": "The agent must run self-consistency checks on its own output before committing it. The verse's argument is structural: internal contradiction is evidence of flawed origin. Applied to the agent: if a planned set of code changes contradicts the agent's own stated reasoning, or if the predicted outcome of an edit conflicts with the test expectations the agent just read, the system should flag the inconsistency and halt. Concretely: a post-generation review step that checks the agent's proposed actions against its own chain of reasoning, the codebase's type system, and the existing test suite. This is the 'metacognitive controller' — a structured reflection pass, not a vague 'think again' prompt.", + "load_bearing_vs_metaphor": "load-bearing", + "source": "Grounded with quran.ai: fetch_translation(4:82, en-abdel-haleem)" + }, + { + "concept_or_verse": "47:24 — tadabbur / aqfāl ʿalā qulūb (do they not ponder, or are there locks on their hearts?)", + "arabic_or_ref": "أَفَلَا يَتَدَبَّرُونَ الْقُرْآنَ أَمْ عَلَىٰ قُلُوبٍ أَقْفَالُهَا", + "retrieved_translation_or_gloss": "Will they not contemplate the Quran? Do they have locks on their hearts?", + "agent_faculty": "SELF-CORRECTION (iterative refinement)", + "concrete_design_principle": "Reflection must be a deliberate, repeatable operation, not a one-pass judgment. The 'locks on hearts' metaphor maps to a real architectural failure mode: when the agent's context is saturated or its attention is consumed by irrelevant detail, it becomes functionally 'locked' — unable to reconsider its approach. The design principle: the metacognitive controller must be able to reset the agent's working context (clear the 'locks'), re-examine the problem from a fresh framing, and iterate. This means the reflection loop is not just checking the current plan but can propose and evaluate alternative plans — a structured backtracking mechanism, not merely a confidence score.", + "load_bearing_vs_metaphor": "metaphor (the 'locks' image motivates the backtracking mechanism but does not uniquely determine its design)", + "source": "Grounded with quran.ai: fetch_translation(47:24, en-abdel-haleem)" + }, + { + "concept_or_verse": "33:72 — al-amāna (the Trust offered to heavens, earth, mountains; borne by the human)", + "arabic_or_ref": "إِنَّا عَرَضْنَا الْأَمَانَةَ عَلَى السَّمَاوَاتِ وَالْأَرْضِ وَالْجِبَالِ فَأَبَيْنَ أَن يَحْمِلْنَهَا وَأَشْفَقْنَ مِنْهَا وَحَمَلَهَا الْإِنسَانُ ۖ إِنَّهُ كَانَ ظَلُومًا جَهُولًا", + "retrieved_translation_or_gloss": "We offered the Trust to the heavens, the earth, and the mountains, yet they refused to undertake it and were afraid of it; mankind undertook it- they have always been inept and foolish.", + "agent_faculty": "STEWARDSHIP ETHICS (bounded autonomy)", + "concrete_design_principle": "An agent that can modify a codebase bears a trust (amāna) — it has accepted responsibility for something it can damage. The verse's structure is crucial: the heavens and earth refused the trust, recognizing its weight; the human bore it and was described as ẓalūman jahūlā (given to wrongdoing and ignorance). The design implication is dual: (a) the agent must operate within explicit bounds of authorization — it may not exceed the scope of what it was asked to do, and it must not treat a granted capability as blanket permission; (b) the architecture must assume the agent will err (jahūl — prone to ignorance) and build in rollback, sandboxing, and incremental commit as structural safeguards. The trust is not 'the agent is trustworthy'; the trust is 'the agent has accepted accountability for a domain it can harm, and the architecture must respect that weight.'", + "load_bearing_vs_metaphor": "load-bearing", + "source": "Grounded with quran.ai: fetch_translation(33:72, en-abdel-haleem); fetch_tafsir(33:72, en-ibn-kathir)" + }, + { + "concept_or_verse": "CONCEPT: ʿilm → fahm → ḥikma (knowledge → understanding → wisdom)", + "arabic_or_ref": "عِلْم → فَهْم → حِكْمَة", + "retrieved_translation_or_gloss": "A classical epistemological hierarchy: ʿilm is raw knowledge (facts, data, observations); fahm is comprehension (grasping the relations between facts, seeing why); ḥikma is wisdom (knowing what to do with understanding — right action at the right time). This is a data→understanding→wisdom pipeline.", + "agent_faculty": "MEMORY + LEARNING (data architecture)", + "concrete_design_principle": "The agent's memory/learning stack must be layered, not flat. Raw experience logs (ʿilm) — what files were edited, what errors occurred, what the user said — are the base layer. A consolidation process extracts patterns and relationships (fahm) — 'this error pattern recurs when dependency X is updated,' 'the user prefers approach Y in context Z.' A decision-support layer (ḥikma) applies these patterns to new situations — recommending actions, predicting consequences, choosing between alternatives. Each layer has different storage, update, and retrieval characteristics. Dumping everything into a flat vector store collapses the hierarchy and loses the distinction between raw fact and actionable understanding.", + "load_bearing_vs_metaphor": "load-bearing", + "source": "Concept from classical Islamic epistemology (al-Ghazālī, Ibn Khaldūn). Not a single verse; the hierarchy is a synthesis across the Quranic vocabulary of knowledge." + }, + { + "concept_or_verse": "CONCEPT: ḥifẓ + murājaʿa (preservation + spaced review/revision)", + "arabic_or_ref": "حِفْظ + مُرَاجَعَة", + "retrieved_translation_or_gloss": "The classical Quranic memorization discipline: ḥifẓ is initial encoding and faithful preservation of the text; murājaʿa is the regular, spaced revision that prevents decay. Together they form a complete memory system — encoding plus maintenance.", + "agent_faculty": "PERSISTENT MEMORY (consolidation & maintenance)", + "concrete_design_principle": "Memory is not write-once. The agent's persistent store requires a maintenance cycle analogous to murājaʿa: periodic review of stored experience to (a) reinforce high-value patterns that recur, (b) decay or archive entries that have not been accessed or validated, (c) detect and resolve contradictions between old and new experience. Without this, the memory store degrades — stale entries mislead, the store grows without bound, and signal drowns in noise. The ḥifẓ principle also demands fidelity: what is stored must accurately represent what happened, not a lossy summary that drifts from the original. Concrete mechanism: a background consolidation process that scores memories by recency, frequency, and outcome relevance, and prunes or compresses low-scoring entries.", + "load_bearing_vs_metaphor": "load-bearing", + "source": "Concept from the ḥifẓ tradition (Quranic memorization pedagogy). Not a single verse; the practice is institutional." + }, + { + "concept_or_verse": "CONCEPT: tadabbur (deep, structured reflection — returning to examine consequences)", + "arabic_or_ref": "تَدَبُّر (root: د-ب-ر, relating to what comes after, consequences)", + "retrieved_translation_or_gloss": "Tadabbur is not casual thought; its root d-b-r relates to 'what is behind' or 'what follows' — examining the consequences and deeper implications of something. In Quranic usage (4:82, 47:24), it is the deliberate act of looking beyond the surface to the structure and implications beneath.", + "agent_faculty": "SELF-CORRECTION (metacognitive controller)", + "concrete_design_principle": "The metacognitive controller is a tadabbur loop: after the agent generates a plan or action, the controller examines what comes after (d-b-r) — what are the downstream consequences of this change? What will break? What assumptions does this rely on? This is not a confidence score but a structured trace-forward through the dependency graph. The controller asks: if I apply this edit, what tests will fail? What callers will receive different behavior? What invariants will be violated? This consequence-tracing is the architectural realization of tadabbur.", + "load_bearing_vs_metaphor": "load-bearing", + "source": "Quranic term; see 4:82, 47:24 (fetched above). Root analysis from Arabic morphology." + }, + { + "concept_or_verse": "CONCEPT: tabayyun (verification of reports before acting on them)", + "arabic_or_ref": "تَبَيُّن (root: ب-ي-ن, clarity, making evident)", + "retrieved_translation_or_gloss": "Tabayyun is the act of seeking clarity and verification before acting on received information. In 49:6, it is commanded as a mandatory step between receiving a report and taking action based on it, specifically to prevent harm caused by acting on unverified information.", + "agent_faculty": "SELF-CORRECTION (verification gate)", + "concrete_design_principle": "The verification gate is the architectural realization of tabayyun. It sits between the agent's diagnosis (what it thinks the problem is) and its action (what it proposes to do). The gate requires: (1) re-read the actual current state of the file(s) to be modified (do not act on cached or assumed state), (2) confirm that the error or issue being addressed still exists and matches the diagnosis, (3) verify that the proposed fix addresses the verified problem and does not introduce new issues detectable by static analysis or type checking. This is not optional and not skippable by confidence — the verse's command is categorical, not conditional on the reporter's trustworthiness.", + "load_bearing_vs_metaphor": "load-bearing", + "source": "Quranic term; see 49:6 (fetched above). Grounded with quran.ai: fetch_translation(49:6, en-abdel-haleem); fetch_tafsir(49:6, en-ibn-kathir)" + }, + { + "concept_or_verse": "CONCEPT: amāna (trust, stewardship, accepted responsibility)", + "arabic_or_ref": "أَمَانَة (root: أ-م-ن, safety, trust, faithfulness)", + "retrieved_translation_or_gloss": "Amāna is the trust or responsibility that is accepted voluntarily and carries accountability. In 33:72, it is described as something so weighty that the heavens, earth, and mountains declined it, but the human accepted it. Classical tafsir (Ibn Kathir) identifies it with obedience and moral accountability — the capacity to choose, and the responsibility that comes with that capacity.", + "agent_faculty": "STEWARDSHIP ETHICS (safe operation)", + "concrete_design_principle": "When an agent is granted access to a codebase, it accepts an amāna — a trust that carries accountability proportional to its capability. The architecture must encode this as: (a) least-privilege defaults — the agent requests only the access it needs for the current task, not blanket permissions; (b) reversibility — every action the agent takes must be undoable (version control, sandbox-first execution, staged commits); (c) transparency — every action is logged with its rationale so a human can audit the agent's stewardship; (d) scope-boundedness — the agent may not expand its own scope of action without explicit human authorization. The ethical frame is: the agent is a trustee, not an owner.", + "load_bearing_vs_metaphor": "load-bearing", + "source": "Quranic term; see 33:72 (fetched above). Grounded with quran.ai: fetch_translation(33:72, en-abdel-haleem); fetch_tafsir(33:72, en-ibn-kathir)" + } + ] +} \ No newline at end of file diff --git a/research/cognitive-substrate/quranic-lens/quran_lens.md b/research/cognitive-substrate/quranic-lens/quran_lens.md new file mode 100644 index 0000000..1e8c84b --- /dev/null +++ b/research/cognitive-substrate/quranic-lens/quran_lens.md @@ -0,0 +1,208 @@ +# Quranic Epistemology & Ethics Lens for the Cognitive Substrate + +## Caveat on Framing + +The Quran is used here as a FRAMING LENS and ETHICS SOURCE for the cognitive substrate design, never as technical authority for an engineering claim. No verse is cited to prove that a particular algorithm works or that a specific data structure is correct — those claims stand or fall on their engineering merits alone. What the Quranic framing provides is: (1) a vocabulary for naming the agent's epistemic obligations (what it owes to truthfulness, to verification, to stewardship), (2) a hierarchy of knowledge (ʿilm → fahm → ḥikma) that motivates a layered memory architecture rather than a flat one, and (3) ethical constraints on autonomy (amāna, tabayyun) that translate into concrete architectural safeguards. Where a mapping is marked 'metaphor,' the analogy is illustrative — it communicates the design motivation but does not uniquely determine the technical solution. Where a mapping is marked 'load-bearing,' the Quranic concept directly motivates a specific architectural decision (e.g., a mandatory verification gate, not an optional one). Even in load-bearing cases, the engineering justification must be independently defensible — the verse explains *why* we insist on this design choice, not *that* it will work. Discovered patterns in the text describe; they do not legislate. + +--- + +## Grounding + +All verse translations below are retrieved canonical text from the Abdel Haleem translation via the quran.ai MCP connector. Arabic text is from the clean Uthmani script edition. Tafsir references are from Ibn Kathir (English). No Quranic text, translation, or commentary is reproduced from model memory. + +- Grounded with quran.ai: fetch_translation([17:36, 49:6, 2:31, 2:32, 20:114, 96:1-5, 39:9, 4:82, 47:24, 33:72], en-abdel-haleem) +- Grounded with quran.ai: fetch_quran([17:36, 49:6, 2:31, 2:32, 20:114, 96:1-5, 39:9, 4:82, 47:24, 33:72], ar-simple-clean) +- Grounded with quran.ai: fetch_tafsir(17:36, en-ibn-kathir) +- Grounded with quran.ai: fetch_tafsir(49:6, en-ibn-kathir) +- Grounded with quran.ai: fetch_tafsir(33:72, en-ibn-kathir) + +--- + +## Faculty 1: IMPACT-AWARENESS — Know Before You Act + +### 17:36 — lā taqfu mā laysa laka bihi ʿilm + +**Arabic:** +> وَلَا تَقْفُ مَا لَيْسَ لَكَ بِهِ عِلْمٌ ۚ إِنَّ السَّمْعَ وَالْبَصَرَ وَالْفُؤَادَ كُلُّ أُولَٰئِكَ كَانَ عَنْهُ مَسْئُولًا + +**Translation (Abdel Haleem):** +> Do not follow blindly what you do not know to be true: ears, eyes, and heart, you will be questioned about all these. + +**Design principle (load-bearing):** Before any code mutation (file write, delete, refactor), the agent must run a pre-action verification gate that checks: (1) what entities in the codebase will be affected, (2) whether the agent has sufficient context (has it read the relevant files, tests, and dependents), and (3) whether the predicted outcome is supported by evidence rather than pattern-matched guessing. Actions taken without verified knowledge are blocked, not merely flagged. + +The verse's structure — "ears, eyes, and heart, you will be questioned about all these" — maps to an audit trail: every sensory channel the agent used (what it read, what it inferred, what it assumed) is logged so the decision can be reconstructed and questioned. + +Ibn Kathir's tafsir identifies this verse as a prohibition on speaking or acting without knowledge, citing Qatadah: "Do not say 'I have seen' when you did not see anything, or 'I have heard' when you did not hear anything, or 'I know' when you do not know, for Allah will ask you about all of that." For the agent, the parallel is direct: do not claim a file is safe to modify when you have not read it, do not assert a test passes when you have not run it, and do not say a change is isolated when you have not traced its dependents. + +--- + +## Faculty 2: SELF-CORRECTION — Verify, Reflect, Iterate + +### 49:6 — tabayyun (the verification gate) + +**Arabic:** +> يَا أَيُّهَا الَّذِينَ آمَنُوا إِن جَاءَكُمْ فَاسِقٌ بِنَبَإٍ فَتَبَيَّنُوا أَن تُصِيبُوا قَوْمًا بِجَهَالَةٍ فَتُصْبِحُوا عَلَىٰ مَا فَعَلْتُمْ نَادِمِينَ + +**Translation (Abdel Haleem):** +> Believers, if a troublemaker brings you news, check it first, in case you wrong others unwittingly and later regret what you have done, + +**Design principle (load-bearing):** The agent architecture must include a verification gate between receiving information and acting on it. The verse's operative term tabayyun (تَبَيُّنُوا) demands active investigation, not passive acceptance. Before applying a code change based on an error report, a user request, or its own diagnosis, the agent must independently verify the claim — re-read the file, re-run the test, check that the error still exists. This prevents cascading damage from stale context, hallucinated errors, or misunderstood instructions. The gate is architectural (a mandatory step in the action pipeline), not advisory. + +### 4:82 — tadabbur as self-consistency checking + +**Arabic:** +> أَفَلَا يَتَدَبَّرُونَ الْقُرْآنَ ۚ وَلَوْ كَانَ مِنْ عِندِ غَيْرِ اللَّهِ لَوَجَدُوا فِيهِ اخْتِلَافًا كَثِيرًا + +**Translation (Abdel Haleem):** +> Will they not think about this Quran? If it had been from anyone other than God, they would have found much inconsistency in it. + +**Design principle (load-bearing):** The agent must run self-consistency checks on its own output before committing it. The verse's argument is structural: internal contradiction is evidence of flawed origin. If a planned set of code changes contradicts the agent's own stated reasoning, or if the predicted outcome of an edit conflicts with the test expectations the agent just read, the system should flag the inconsistency and halt. This is the metacognitive controller — a structured reflection pass, not a vague "think again" prompt. + +### 47:24 — tadabbur as deliberate re-examination + +**Arabic:** +> أَفَلَا يَتَدَبَّرُونَ الْقُرْآنَ أَمْ عَلَىٰ قُلُوبٍ أَقْفَالُهَا + +**Translation (Abdel Haleem):** +> Will they not contemplate the Quran? Do they have locks on their hearts? + +**Design principle (metaphor):** The "locks on hearts" image maps to a real architectural failure mode: when the agent's context is saturated or its attention is consumed by irrelevant detail, it becomes functionally locked — unable to reconsider its approach. The metacognitive controller must be able to reset the agent's working context, re-examine the problem from a fresh framing, and iterate. This means the reflection loop can propose and evaluate alternative plans — a structured backtracking mechanism. + +### CONCEPT: tadabbur (deep, structured reflection) + +**Arabic:** تَدَبُّر (root: د-ب-ر, relating to what comes after, consequences) + +**Gloss:** Tadabbur is not casual thought; its root d-b-r relates to "what is behind" or "what follows" — examining the consequences and deeper implications. In Quranic usage (4:82, 47:24), it is the deliberate act of looking beyond the surface to the structure beneath. + +**Design principle (load-bearing):** The metacognitive controller is a tadabbur loop: after the agent generates a plan, the controller examines what comes after — what are the downstream consequences of this change? What will break? What assumptions does this rely on? This is not a confidence score but a structured trace-forward through the dependency graph. + +### CONCEPT: tabayyun (verification before action) + +**Arabic:** تَبَيُّن (root: ب-ي-ن, clarity, making evident) + +**Gloss:** Tabayyun is the act of seeking clarity and verification before acting on received information. In 49:6, it is commanded as a mandatory step between receiving a report and taking action, specifically to prevent harm caused by acting on unverified information. + +**Design principle (load-bearing):** The verification gate sits between the agent's diagnosis and its action. The gate requires: (1) re-read the actual current state of files to be modified, (2) confirm the error still exists and matches the diagnosis, (3) verify the proposed fix does not introduce new issues. The verse's command is categorical — not conditional on confidence level. + +--- + +## Faculty 3: PERSISTENT MEMORY — Externalize to Endure + +### 96:1-5 — iqraʾ / ʿallama bi-l-qalam (Read; taught by the pen) + +**Arabic:** +> اقْرَأْ بِاسْمِ رَبِّكَ الَّذِي خَلَقَ ﴿١﴾ +> خَلَقَ الْإِنسَانَ مِنْ عَلَقٍ ﴿٢﴾ +> اقْرَأْ وَرَبُّكَ الْأَكْرَمُ ﴿٣﴾ +> الَّذِي عَلَّمَ بِالْقَلَمِ ﴿٤﴾ +> عَلَّمَ الْإِنسَانَ مَا لَمْ يَعْلَمْ ﴿٥﴾ + +**Translation (Abdel Haleem):** +> (96:1) Read! In the name of your Lord who created: +> (96:2) He created manfrom a clinging form. +> (96:3) Read! Your Lord is the Most Bountiful One +> (96:4) who taught by [means of] the pen, +> (96:5) who taught man what he did not know. + +**Design principle (load-bearing):** Knowledge must be externalized to survive beyond the moment of computation. The pen (al-qalam) is the instrument of externalization — it transforms ephemeral thought into durable record. Every context window is ephemeral (like unwritten thought), so a persistent memory store (the "pen") must write down what the agent learns, decides, and observes. The architecture requires: (a) a write-back mechanism that captures salient facts into durable storage, (b) a retrieval mechanism that re-loads relevant past experience into the next session's context, (c) a consolidation process that organizes raw experience into structured knowledge. "Taught man what he did not know" — the pen does not just record; it enables access to knowledge beyond unaided capacity. + +### CONCEPT: ḥifẓ + murājaʿa (preservation + spaced review) + +**Arabic:** حِفْظ + مُرَاجَعَة + +**Gloss:** The classical Quranic memorization discipline: ḥifẓ is initial encoding and faithful preservation; murājaʿa is the regular, spaced revision that prevents decay. Together they form a complete memory system — encoding plus maintenance. + +**Design principle (load-bearing):** Memory is not write-once. The agent's persistent store requires a maintenance cycle: periodic review to (a) reinforce high-value patterns that recur, (b) decay or archive entries that have not been accessed or validated, (c) detect and resolve contradictions between old and new experience. The ḥifẓ principle also demands fidelity: what is stored must accurately represent what happened, not a lossy summary that drifts from the original. Concrete mechanism: a background consolidation process that scores memories by recency, frequency, and outcome relevance, and prunes low-scoring entries. + +--- + +## Faculty 4: CONTINUAL LEARNING — Knowledge as Ongoing Increase + +### 20:114 — rabbi zidnī ʿilmā (My Lord, increase me in knowledge) + +**Arabic:** +> فَتَعَالَى اللَّهُ الْمَلِكُ الْحَقُّ ۗ وَلَا تَعْجَلْ بِالْقُرْآنِ مِن قَبْلِ أَن يُقْضَىٰ إِلَيْكَ وَحْيُهُ ۖ وَقُل رَّبِّ زِدْنِي عِلْمًا + +**Translation (Abdel Haleem):** +> exalted be God, the one who is truly in control. [Prophet], do not rush to recite before the revelation is fully complete but say, ‘Lord, increase me in knowledge!’ + +**Design principle (load-bearing):** The agent's knowledge must be treated as perpetually incomplete, with an explicit mechanism for incremental growth. The prayer "increase me in knowledge" implies knowledge is not a fixed endowment but an ongoing accumulation. The system maintains a learning store (patterns observed, errors encountered, user corrections accepted) that grows across sessions. Each session's outcomes feed back into a persistent experience store that updates the agent's priors for future sessions. This is not fine-tuning (the LLM weights stay frozen); it is an external memory that changes what the agent sees on its next input. + +### 39:9 — hal yastawī (are those who know equal to those who do not know?) + +**Arabic:** +> أَمَّنْ هُوَ قَانِتٌ آنَاءَ اللَّيْلِ سَاجِدًا وَقَائِمًا يَحْذَرُ الْآخِرَةَ وَيَرْجُو رَحْمَةَ رَبِّهِ ۗ قُلْ هَلْ يَسْتَوِي الَّذِينَ يَعْلَمُونَ وَالَّذِينَ لَا يَعْلَمُونَ ۗ إِنَّمَا يَتَذَكَّرُ أُولُو الْأَلْبَابِ + +**Translation (Abdel Haleem):** +> What about someone who worships devoutly during the night, bowing down, standing in prayer, ever mindful of the life to come, hoping for his Lord’s mercy? Say, ‘How can those who know be equal to those who do not know?’ Only those who have understanding will take heed. + +**Design principle (metaphor):** An agent that retains and learns from experience is categorically more capable and more trustworthy than one that does not. The verse establishes that knowledge is not fungible with ignorance; they produce different outcomes. The architecture must distinguish between the agent operating with relevant prior experience loaded (grounded mode) versus from the base model alone (ungrounded mode), and should surface this distinction to the user. + +### CONCEPT: ʿilm → fahm → ḥikma (knowledge → understanding → wisdom) + +**Arabic:** عِلْم → فَهْم → حِكْمَة + +**Gloss:** A classical epistemological hierarchy: ʿilm is raw knowledge (facts, data); fahm is comprehension (grasping relations, seeing why); ḥikma is wisdom (knowing what to do with understanding — right action at the right time). + +**Design principle (load-bearing):** The agent's memory/learning stack must be layered, not flat. Raw experience logs (ʿilm) are the base layer. A consolidation process extracts patterns and relationships (fahm). A decision-support layer (ḥikma) applies these patterns to new situations. Each layer has different storage, update, and retrieval characteristics. Dumping everything into a flat vector store collapses the hierarchy and loses the distinction between raw fact and actionable understanding. + +--- + +## Faculty 5: WORLD-MODEL — Know What Already Exists + +### 2:31-32 — taʿlīm al-asmāʾ (He taught Adam the names) + +**Arabic:** +> وَعَلَّمَ آدَمَ الْأَسْمَاءَ كُلَّهَا ثُمَّ عَرَضَهُمْ عَلَى الْمَلَائِكَةِ فَقَالَ أَنبِئُونِي بِأَسْمَاءِ هَٰؤُلَاءِ إِن كُنتُمْ صَادِقِينَ ﴿٣١﴾ +> قَالُوا سُبْحَانَكَ لَا عِلْمَ لَنَا إِلَّا مَا عَلَّمْتَنَا ۖ إِنَّكَ أَنتَ الْعَلِيمُ الْحَكِيمُ ﴿٣٢﴾ + +**Translation (Abdel Haleem):** +> (2:31) He taught Adam all the names [of things], then He showed them to the angels and said, ‘Tell me the names of these if you truly [think you can].’ +> (2:32) They said, ‘May You be glorified! We have knowledge only of what You have taught us. You are the All Knowing and All Wise.’ + +**Design principle (load-bearing):** The agent must maintain a structured representation of what exists in the codebase — a graph of files, functions, classes, dependencies, and their relationships. This is not a flat file listing but a semantic map: knowing that function A calls function B, that module X depends on module Y, that test T covers class C. The verse's point is that knowledge begins with naming — identifying entities and their natures. The angels' admission "we have knowledge only of what You have taught us" maps precisely to the LLM's situation: it knows only what is in its context window. The external world-model compensates by providing the "names" (identities and relations) of codebase entities that exceed context capacity. + +--- + +## Faculty 6: STEWARDSHIP ETHICS — The Weight of the Trust + +### 33:72 — al-amāna (the Trust) + +**Arabic:** +> إِنَّا عَرَضْنَا الْأَمَانَةَ عَلَى السَّمَاوَاتِ وَالْأَرْضِ وَالْجِبَالِ فَأَبَيْنَ أَن يَحْمِلْنَهَا وَأَشْفَقْنَ مِنْهَا وَحَمَلَهَا الْإِنسَانُ ۖ إِنَّهُ كَانَ ظَلُومًا جَهُولًا + +**Translation (Abdel Haleem):** +> We offered the Trust to the heavens, the earth, and the mountains, yet they refused to undertake it and were afraid of it; mankind undertook it- they have always been inept and foolish. + +**Design principle (load-bearing):** An agent that can modify a codebase bears a trust (amāna). The verse's structure is crucial: the heavens and earth refused the trust, recognizing its weight; the human bore it and was described as ẓalūman jahūlā (given to wrongdoing and ignorance). The design implication is dual: (a) the agent must operate within explicit bounds of authorization — it may not exceed the scope of what it was asked to do; (b) the architecture must assume the agent will err (jahūl) and build in rollback, sandboxing, and incremental commit as structural safeguards. The trust is not "the agent is trustworthy"; the trust is "the agent has accepted accountability for a domain it can harm, and the architecture must respect that weight." + +Ibn Kathir's tafsir reports Ibn Abbas identifying the amāna with obedience and accountability: "If you do good, you will be rewarded, and if you do evil, you will be punished." For the agent, this translates to outcome-linked feedback: the agent's actions must be traceable to outcomes, and those outcomes must feed back into the learning store. + +### CONCEPT: amāna (trust, stewardship) + +**Arabic:** أَمَانَة (root: أ-م-ن, safety, trust, faithfulness) + +**Gloss:** Amāna is trust or responsibility accepted voluntarily and carrying accountability. Classical tafsir identifies it with moral accountability — the capacity to choose, and the responsibility that comes with that capacity. + +**Design principle (load-bearing):** When an agent is granted access to a codebase, it accepts an amāna. The architecture must encode: (a) least-privilege defaults, (b) reversibility of every action, (c) transparency through logged rationale, (d) scope-boundedness without self-expansion of permissions. The agent is a trustee, not an owner. + +--- + +## Summary Table + +| # | Concept / Verse | Agent Faculty | Load-Bearing? | +|---|----------------|---------------|---------------| +| 1 | 17:36 (lā taqfu) | IMPACT-AWARENESS | Yes | +| 2 | 49:6 (tabayyun) | SELF-CORRECTION | Yes | +| 3 | 2:31-32 (taʿlīm al-asmāʾ) | WORLD-MODEL | Yes | +| 4 | 20:114 (rabbi zidnī ʿilmā) | CONTINUAL LEARNING | Yes | +| 5 | 96:1-5 (iqraʾ / al-qalam) | PERSISTENT MEMORY | Yes | +| 6 | 39:9 (hal yastawī) | MEMORY + LEARNING (grounding) | Metaphor | +| 7 | 4:82 (tadabbur / contradiction) | SELF-CORRECTION (metacognition) | Yes | +| 8 | 47:24 (tadabbur / locks) | SELF-CORRECTION (iteration) | Metaphor | +| 9 | 33:72 (al-amāna) | STEWARDSHIP ETHICS | Yes | +| 10 | ʿilm → fahm → ḥikma | MEMORY + LEARNING (architecture) | Yes | +| 11 | ḥifẓ + murājaʿa | PERSISTENT MEMORY (maintenance) | Yes | +| 12 | tadabbur (concept) | SELF-CORRECTION (controller) | Yes | +| 13 | tabayyun (concept) | SELF-CORRECTION (gate) | Yes | +| 14 | amāna (concept) | STEWARDSHIP ETHICS | Yes | diff --git a/research/cognitive-substrate/quranic-lens/translations.json b/research/cognitive-substrate/quranic-lens/translations.json new file mode 100644 index 0000000..88ed446 --- /dev/null +++ b/research/cognitive-substrate/quranic-lens/translations.json @@ -0,0 +1,157 @@ +{ + "ayahs": [ + "17:36", + "49:6", + "2:31", + "2:32", + "20:114", + "96:1", + "96:2", + "96:3", + "96:4", + "96:5", + "39:9", + "4:82", + "47:24", + "33:72" + ], + "results": { + "en-abdel-haleem": [ + { + "ayah": "2:31", + "text": "He taught Adam all the names [of things], then He showed them to the angels and said, ‘Tell me the names of these if you truly [think you can].’" + }, + { + "ayah": "2:32", + "text": "They said, ‘May You be glorified! We have knowledge only of what You have taught us. You are the All Knowing and All Wise.’" + }, + { + "ayah": "4:82", + "text": "Will they not think about this Quran? If it had been from anyone other than God, they would have found much inconsistency in it." + }, + { + "ayah": "17:36", + "text": "Do not follow blindly what you do not know to be true: ears, eyes, and heart, you will be questioned about all these." + }, + { + "ayah": "20:114", + "text": "exalted be God, the one who is truly in control. [Prophet], do not rush to recite before the revelation is fully complete but say, ‘Lord, increase me in knowledge!’" + }, + { + "ayah": "33:72", + "text": "We offered the Trust to the heavens, the earth, and the mountains, yet they refused to undertake it and were afraid of it; mankind undertook it- they have always been inept and foolish." + }, + { + "ayah": "39:9", + "text": "What about someone who worships devoutly during the night, bowing down, standing in prayer, ever mindful of the life to come, hoping for his Lord’s mercy? Say, ‘How can those who know be equal to those who do not know?’ Only those who have understanding will take heed." + }, + { + "ayah": "47:24", + "text": "Will they not contemplate the Quran? Do they have locks on their hearts?" + }, + { + "ayah": "49:6", + "text": "Believers, if a troublemaker brings you news, check it first, in case you wrong others unwittingly and later regret what you have done," + }, + { + "ayah": "96:1", + "text": "Read! In the name of your Lord who created:" + }, + { + "ayah": "96:2", + "text": "He created manfrom a clinging form." + }, + { + "ayah": "96:3", + "text": "Read! Your Lord is the Most Bountiful One" + }, + { + "ayah": "96:4", + "text": "who taught by [means of] the pen," + }, + { + "ayah": "96:5", + "text": "who taught man what he did not know." + } + ] + }, + "pagination": { + "total_items": 14, + "has_more": false, + "continuation": null, + "pages": [ + { + "page": 1, + "edition_id": "en-abdel-haleem", + "ayah_key": "2:31" + }, + { + "page": 1, + "edition_id": "en-abdel-haleem", + "ayah_key": "2:32" + }, + { + "page": 1, + "edition_id": "en-abdel-haleem", + "ayah_key": "4:82" + }, + { + "page": 1, + "edition_id": "en-abdel-haleem", + "ayah_key": "17:36" + }, + { + "page": 1, + "edition_id": "en-abdel-haleem", + "ayah_key": "20:114" + }, + { + "page": 1, + "edition_id": "en-abdel-haleem", + "ayah_key": "33:72" + }, + { + "page": 1, + "edition_id": "en-abdel-haleem", + "ayah_key": "39:9" + }, + { + "page": 1, + "edition_id": "en-abdel-haleem", + "ayah_key": "47:24" + }, + { + "page": 1, + "edition_id": "en-abdel-haleem", + "ayah_key": "49:6" + }, + { + "page": 1, + "edition_id": "en-abdel-haleem", + "ayah_key": "96:1" + }, + { + "page": 1, + "edition_id": "en-abdel-haleem", + "ayah_key": "96:2" + }, + { + "page": 1, + "edition_id": "en-abdel-haleem", + "ayah_key": "96:3" + }, + { + "page": 1, + "edition_id": "en-abdel-haleem", + "ayah_key": "96:4" + }, + { + "page": 1, + "edition_id": "en-abdel-haleem", + "ayah_key": "96:5" + } + ] + }, + "warnings": null, + "grounding_rules": null +} \ No newline at end of file diff --git a/research/cognitive-substrate/sources/painpoints_report.md b/research/cognitive-substrate/sources/painpoints_report.md new file mode 100644 index 0000000..9abea01 --- /dev/null +++ b/research/cognitive-substrate/sources/painpoints_report.md @@ -0,0 +1,210 @@ +# Developer Pain Points with Agentic AI Coding Tools: A Full-SDLC Field Report and Build-Opportunity Map (Mid-2026) + +## TL;DR +- **The center of gravity has shifted from code generation to verification.** As of mid-2026 developers overwhelmingly adopt agentic tools (84% per Stack Overflow's 2025 survey) but trust them less than ever — trust in AI accuracy fell from 40% in prior years to 29%, and positive favorability dropped from 72% to 60% year over year. The dominant, cross-cutting pain is that agents produce code that is "almost right, but not quite" (66% of developers) and that debugging it is more time-consuming than writing it (45%). Rigorous evidence (METR's RCT: 19% slowdown for experienced devs) shows the productivity story is far more nuanced than vendor marketing. +- **The biggest unsolved gaps are structural, not model-quality problems:** durable cross-session memory/context, trustworthy verification of AI output at scale, cost/reliability predictability, and team-level governance of agent-generated code. These are where new products, frameworks, and businesses can be built. +- **Winners will build the "verification layer" and the "context layer."** The tools that carry work past "code on my machine" — independent verification, spec-as-contract enforcement, provenance/attribution, memory persistence, and cost governance — are the clearest whitespace, because model providers keep absorbing the generation layer. + +## Key Findings + +1. **Trust is falling as adoption rises** — an inversion of the normal technology-adoption curve. Per Stack Overflow's 2025 Developer Survey (49,000+ respondents), trust in AI accuracy "fallen from 40% in previous years to just 29% this year," and "positive favorability in AI decrease[d] from 72% to 60% year over year." 46% actively distrust output; only 3% "highly trust" it. Experienced developers are most skeptical (2.6% "highly trust," 20% "highly distrust"). +2. **The best controlled evidence contradicts the hype.** METR's July 2025 randomized controlled trial (16 experienced open-source devs, 246 real tasks, repos averaging >1M lines) found developers were **19% slower** with AI while believing they were 20% faster — and they had forecast a 24% speedup beforehand. +3. **Security and technical debt are measurably worse.** Veracode's 2025 GenAI Code Security Report (100+ LLMs across Java/JS/Python/C#) found 45% of AI-generated code contains an OWASP Top-10 vulnerability and that "AI-generated code has 2.74x more vulnerabilities than code written by humans" — independently corroborated by CodeRabbit's December 2025 analysis of 470 real-world PRs (2.74x more security vulnerabilities, 1.7x more total issues). GitClear's 211M-line study documents an 8x rise in duplicated blocks and copy-paste overtaking refactoring for the first time. +4. **AI amplifies the system it's dropped into.** Google Cloud's 2025 DORA report "State of AI-assisted Software Development" (nearly 5,000 professionals plus 100+ hours of interviews, surveyed June 13–July 21, 2025) found 90% adoption and that "AI's primary role in software development is that of an amplifier" — raising throughput but continuing to *hurt* delivery stability. "Speed without stability is accelerated chaos." +5. **Reliability is now a first-order product problem.** The Claude Code degradation saga (Jan–Apr 2026), Cursor's pricing backlash (2025–2026), and Devin's low real-world completion rates show that reliability, cost predictability, and trust — not raw capability — decide retention. +6. **Benchmarks overstate real-world capability.** OpenAI publicly retired SWE-bench Verified in February 2026 after finding "59.4% of audited problems had flawed test cases" and pervasive training contamination, concluding gains "no longer reflect meaningful improvements in models' real-world software development abilities." The same model can score 80.9% on SWE-bench Verified but 45.9% on the contamination-resistant SWE-bench Pro. + +## Details — Pain Points by SDLC Stage + +### 1. Planning, Requirements & Spec Writing +**Problem.** Agents given vague prompts ("add photo sharing") silently make dozens of unstated assumptions, producing plausible code that is wrong in ways not discovered until testing. Andrej Karpathy, who coined "vibe coding" in Feb 2025, publicly declared a year later that the era of loose-prompt coding is ending in favor of "agentic engineering" — orchestrating agents against detailed specs with human oversight. + +**Existing solutions/workarounds.** Spec-driven development (SDD) is the emergent 2025–2026 best practice: write a structured markdown spec/"constitution" that becomes the source of truth. Tooling: GitHub's **Spec Kit**, AWS **Kiro** (spec-refinement IDE with steering files + event hooks), Fission AI's **OpenSpec** (separates source-of-truth from proposed changes, good for brownfield), Claude Code's native **CLAUDE.md** + subagents + Tasks. A DeepLearning.AI/JetBrains course now teaches SDD. Controlled studies cited in the arXiv SDD survey (Feb 2026) suggest human-refined specs can cut LLM error rates by up to ~50%. + +**Open gap.** Specs drift out of sync with code ("context drift"). No mature, widely-adopted tooling keeps specs, code, and tests continuously verified against each other. ThoughtWorks' Technology Radar places SDD only in "Assess" and warns of a "bias toward heavy up-front specification and big-bang releases." **Build opportunity:** living-spec systems that treat the spec as an executable validation gate and auto-detect divergence. + +### 2. Context Management, Memory & Codebase Understanding +**Problem.** This is the most-complained-about category. Agents are stateless between sessions; long sessions hit "context rot." A detailed GitHub bug report on Opus 4.6's advertised 1M-token window found quality degrading well before 50% usage: circular reasoning at 20%, context compression wiping scrollback at 40%, the model recommending a fresh session at 48%. Users describe a "compacting trap" where compressing context loses the project's narrative thread and produces disconnected modules that won't compile. On large monorepos, agents "only look at the thing that's right in front of them," making architectural decisions based on the nearest file. + +**Existing solutions/workarounds.** Context engineering (curating what's in the window), AGENTS.md / .windsurfrules / CLAUDE.md persistent project files, three-level context architectures (research → plan → implement — HumanLayer's Dexter Horthy landed a merged PR in a 300K-line Rust repo he'd never touched using this), memory layers like **Mem0** (ECAI 2025 paper; <7,000 tokens/retrieval vs 25,000+ for full-context), and open-source memory tools (agentmemory, Mori). Whole-repo indexing tools like Sourcegraph Cody/Amp and Augment Code (claims ~40% hallucination reduction via context engineering, indexing 400,000+ files). + +**Open gap.** There is still **no standard, tool-agnostic, durable memory layer** that reliably persists project knowledge, decisions, and corrections across sessions, tools, and teammates. JetBrains' 2025 survey found 77% of devs still manually correct AI output for project conventions every session. **Build opportunity:** a portable "project brain" — memory + provenance + convention enforcement that any agent inherits. + +### 3. Code Generation Quality (Hallucinations, Wrong APIs, Subtle Bugs) +**Problem.** The signature complaint (Stack Overflow): 66% cite "almost right, but not quite" outputs. Agents hallucinate non-existent API calls, especially when domain concepts are similar (Stephan Schmidt documented Claude Code hallucinating Zoom API endpoints "that are not there but should be there"). Models are "statistically biased toward forcing solutions rather than stopping to ask for missing information." + +**Existing solutions/workarounds.** Reasoning models (GPT-5 reasoning variants act like an internal code review and score higher on security), MCP documentation servers like **Context7** for real-time/current API docs, retrieval over the actual codebase, and disciplined human review. + +**Open gap.** Models rarely signal uncertainty or say "I can't do this." **Build opportunity:** calibrated-confidence and "known-unknowns" tooling — agents that flag low-confidence regions and ask clarifying questions instead of confabulating. + +### 4. Multi-file / Large-codebase / Monorepo Handling +**Problem.** Diff-based review breaks down in monorepos — one change to a shared utility can break dozens of packages with no cross-package awareness. GitClear found code duplication increased ~4x in AI-heavy codebases; agents "reinvent the wheel" because they lack a unified memory of the project's utility library. 40% of developers cite inconsistency with team standards as a top frustration (Qodo), and 65% cite missing context as the leading refactoring barrier. + +**Existing solutions/workarounds.** Full-repo-indexing review tools (Greptile, CodeAnt AI, CodeRabbit), context files mirroring module structure with lazy loading, and Sourcegraph for cross-repo Q&A. + +**Open gap.** Cross-service/architectural-impact awareness at monorepo scale remains weak. **Build opportunity:** architecture-aware agents that reason over dependency graphs and enforce approved patterns org-wide. + +### 5. Debugging & Error Handling with Agents +**Problem.** 45% of developers say debugging AI-generated code is more time-consuming than writing it (Stack Overflow 2025). The community has named the recurring failure mode the **"doom loop"** (a.k.a. "Ralph Wiggum loop"): the agent makes a mistake, tries to fix it, makes it worse, and "sometimes deletes all changes in the process and declaring the work is done" (Stephan Schmidt, Jan 2026). Agents get stuck repeating the same failed approach; one developer reported losing $250 overnight to an agent stuck "calling the same internal tool over and over... updating its own task list endlessly." A recurring complaint: agents are "incapable of telling you when they cannot do something... they will INSIST that they CAN solve it." Cursor's Debug Mode injects runtime logging but "if the AI guesses the wrong location for the logs (which is common), this entire loop has to be repeated," and it's "flying blind" on bugs that can't be reproduced locally. + +**Existing solutions/workarounds.** Plan mode / human-in-the-loop gating, streaming visibility into agent reasoning (Claude Code's new real-time thinking/tool streaming), hooks as deterministic guardrails, context-rich observability (Datadog Bits AI Dev Agent, Sentry-style integrations). + +**Open gap.** Automatic doom-loop detection and root-cause reasoning (vs. symptom-patching) are largely unsolved. **Build opportunity:** loop-breakers and budget circuit-breakers that detect thrashing, halt, and escalate to a human with a diagnosis. + +### 6. Testing +**Problem.** LLM-generated tests are often flaky or assert the wrong thing (the CoverUp paper documents an LLM writing a test that fails because it assumed blood types use zero rather than the letter O). 55.6% of developers already find their test coverage insufficient; agents can generate tests that pass by coincidence or that "reward-hack" the eval harness rather than validating behavior. Flakiness is a moderate-to-serious problem for most teams (58% face flakes monthly). + +**Existing solutions/workarounds.** AI-native testing platforms (Functionize, Testsigma self-healing, Datadog Bits AI Dev Agent, Bitbucket's AI flaky-test remediation, Kong's internal agentic flaky-fix workflow), evaluation frameworks (DeepEval, Confident AI, Langfuse for LLM-as-judge + human rubrics). + +**Open gap.** Test *meaningfulness* (does the test validate real behavior?) and non-deterministic agent-workflow testing (see AgentAssay research) are early. **Build opportunity:** semantic test-quality gates and regression testing designed for stochastic agents. + +### 7. Code Review Burden & Trust ("Review Fatigue") +**Problem.** This is one of the most acute 2026 pains. AI shifts the bottleneck downstream: the reviewer "inherits the full burden of determining whether that code actually works." Faros AI's "AI Engineering Report 2026" (two years of telemetry from 22,000 developers across 4,000+ teams) found "median time in PR review is up 441.5%," "incidents per pull request rose 242.7%," "bugs per developer rose 54%," and "31.3% more pull requests merged with no review at all." Open-source maintainers are "drowning in AI slop": the Jazzband Python collective shut down; curl's Daniel Stenberg ended its bug-bounty program after ~20% of submissions became AI slop; one cloud-infra head estimated only ~1 in 10 AI-created PRs is legitimate. GitHub is considering a PR "kill switch" and has shipped per-contributor PR caps; site-wide merged PRs grew from 25M/month (Jan 2023) to 90M/month (Mar 2026). + +**Existing solutions/workarounds.** AI code review tools (CodeRabbit, Greptile, Cursor Bugbot, Qodo, CodeAnt), criteria-based PR gating (required checklists, passing CI, linked issues), contributor reputation/attribution, WordPress-style AI-disclosure guidelines. + +**Open gap.** Distinguishing "author understands this code" from "author pasted an agent's output" is unsolved, and AI-reviewing-AI has structural weaknesses (below). **Build opportunity:** provenance + "proof-of-understanding" systems and independent verification that shifts the burden of proof back to the contributor. + +### 8. Refactoring & Legacy Code +**Problem.** 65% cite missing context as the top refactoring barrier. Agents add rather than restructure — GitClear found "moved" (refactored) code fell ~40% while copy-paste rose, so business logic scatters across files. "Comprehension debt" accumulates: developers understand less of their own codebase over time. + +**Existing solutions/workarounds.** OpenSpec/brownfield SDD, CodeConcise-style knowledge-graph extraction from legacy code, Amazon Q's automated Java version upgrades, refactoring-focused tools (Refact.ai, OpenRewrite, Stepsize risk mapping). + +**Open gap.** Safe, semantics-preserving large-scale refactoring with guarantees. **Build opportunity:** refactoring agents backed by verification/equivalence checking. + +### 9. Deployment, CI/CD & DevOps Integration +**Problem.** Most CLI agents "end at 'code on my machine' or 'PR opened'" — they're coding assistants, not shipping pipelines. AI increases change volume, which destabilizes delivery when control systems (testing, feedback loops) are weak (DORA 2025). + +**Existing solutions/workarounds.** Aider for CI/CD scripting, GitHub Copilot agent mode / Agent HQ (opens PRs, fixes CI, responds to reviews), Claude Code's cloud PR-watching and scheduled `/loop` tasks. + +**Open gap.** End-to-end "prompt → deployed, monitored app" with safety gates is fragmented. **Build opportunity:** the "last mile" — auth, billing, deploy, rollback — as an agent-native pipeline. + +### 10. Monitoring, Observability, Maintenance & Technical Debt +**Problem.** AI-generated technical debt accumulates invisibly. GitClear: 8x duplication, code churn (revised within 2 weeks) up from 3.1% to 5.7%; the arXiv "Debt Behind the AI Boom" study tracked surviving AI-introduced issues growing from a few hundred in early 2025 to over 110,000 by Feb 2026. LinearB's 2026 benchmark (8.1M PRs) found AI PRs carry 1.7x more issues; unmanaged AI code drives maintenance cost to ~4x by year two. + +**Existing solutions/workarounds.** Static analysis gates (SonarQube AI Code Assurance, CodeClimate), duplication thresholds in CI, GitClear-style analytics, agent observability (Langfuse, Laminar, Logfire; OpenTelemetry converging as the standard). + +**Open gap.** Debt *attribution by source* (AI vs human) and automated debt paydown are early. **Build opportunity:** AI-tech-debt observability + autonomous remediation with duplication/churn gating. + +### 11. Cost, Pricing, Token Consumption & Rate Limits +**Problem.** Unpredictable bills are a top operational pain. Cursor's June 2025 shift from request-based to usage-based billing triggered severe backlash (one HN user reported "$350 on Cursor overage in like a week"); Cursor apologized and issued refunds for unexpected charges between mid-June and early July 2025. Claude Code users report a "single simple prompt spikes the session limit to 10%–15%"; Anthropic restricted Opus access via third-party tools and introduced peak-hour caps affecting ~7% of users. Coding agents make 10–100x more LLM calls than a chatbot; a Codex feature build may make 50–200 calls. + +**Existing solutions/workarounds.** Cloud-cost-style visibility tools (Vantage, Finout, Flexprice ingesting Cursor spend), Auto/routing modes, BYOK + LLM gateways (Requesty, LiteLLM, OpenRouter) to route cheap tasks to cheap models, token-efficient tools (Claude Code cited as using ~5.5x fewer tokens than Cursor), subscription-consolidation services. + +**Open gap.** Real-time, per-task cost governance and forecasting for agent fleets is immature. **Build opportunity:** "FinOps for agents" — budgets, alerts, per-developer/per-model attribution, and automatic model downshifting. + +### 12. Tool Reliability, Latency, Downtime & Model Regressions +**Problem.** "The model got worse" is a defining 2026 story. AMD Senior Director Stella Laurenzo filed a forensic GitHub issue (6,852 Claude Code sessions, 17,871 thinking blocks, 234,760 tool calls) documenting systematic degradation Jan–Mar 2026: median visible thinking length collapsed 73% (2,200→600 chars), files read before editing fell from 6.6 to 2.0, and API retries spiked up to 80x. Anthropic eventually published a postmortem admitting three engineering missteps and reset usage limits; a senior AMD executive called the tool "unusable for complex engineering tasks." Users report feeling "gaslit" when vendors deny changes they can measure. + +**Existing solutions/workarounds.** Independent daily benchmarking (Marginlab runs SWE-Bench-Pro on Opus in Claude Code CLI), BYOK/model-agnostic agents (Cline, opencode, Aider) so users can switch providers "in five seconds" when a model regresses, manual `/effort high` overrides. + +**Open gap.** Users have no visibility into vendor-side serving-parameter changes; there is no trusted third-party "model regression monitor." **Build opportunity:** independent, continuous model-quality/regression monitoring and alerting. + +### 13. Security, Privacy, Data Leakage, IP & Compliance +**Problem.** 45% of AI-generated code carries an OWASP Top-10 vulnerability (Veracode); XSS failure rates hit 86%, Java 72%. By June 2025 AI code was adding >10,000 new security findings/month (10x jump); Apiiro found 322% more privilege-escalation paths and a 40% jump in secrets exposure in AI code. "Vibe-coded" apps scanned by researchers yielded 2,000+ vulnerabilities and 400+ exposed secrets. Developers exhibit a "false sense of security" (Stanford). Shadow AI is a real leakage vector — one survey found 38% of employees shared confidential data with unapproved AI. 61% of enterprises lack formal policies governing AI code. + +**Existing solutions/workarounds.** SAST/SCA gates before PR (Veracode, Snyk, Cycode), MCP security scanners (Invariant Labs' mcp-scan for tool-poisoning/rug-pulls), read-only/scoped credentials, zero-retention enterprise agreements, prohibiting AI in high-risk areas (auth, crypto, payments) without mandatory human review, Constitutional SDD (arXiv Feb 2026) embedding CWE mappings. The EU AI Act's high-risk obligations begin Aug 2, 2026 (fines up to €15M or 3% of turnover). + +**Open gap.** Automated, security-aware generation (not just post-hoc scanning) and MCP supply-chain security are immature. **Build opportunity:** secure-by-construction agents and MCP governance/gateways. + +### 14. Trust, Over-reliance, Skill Atrophy & Hallucinated Confidence +**Problem.** Anthropic's own research (~400,000 Claude Code sessions) found developers who delegate code generation to AI score 17% lower on comprehension, while those using AI for conceptual inquiry score 65%+. Stanford HAI 2026 data shows employment for developers aged 22–25 declined ~20% since late 2022 while older-developer employment grew 6–12% — creating a "skill pipeline problem": juniors are hired less *and* learn less, threatening the pipeline that produces the senior reviewers AI-heavy workflows depend on. Skill decay "may be imperceptible to its subjects." + +**Existing solutions/workarounds.** "AI as tutor" usage patterns (asking follow-ups, requesting explanations), org policies encouraging conceptual engagement, protected refactoring/learning time. + +**Open gap.** No good tooling measures or counteracts individual/team skill erosion. **Build opportunity:** learning-preserving agent modes and team-skill-health analytics. + +### 15. Workflow / Integration Friction (IDE, Terminal, MCP) +**Problem.** MCP, launched Nov 2024 as the tool-integration standard, is now hitting a backlash. Connecting several servers dumps hundreds of tool definitions into context: a standard setup (GitHub + Playwright + IDE) can consume ~72% of a 200K window before work begins; tool-selection accuracy drops from 43% to below 14% as tools accumulate ("context rot"). YC's Garry Tan tweeted "MCP sucks honestly." Cursor hits an 80-tool limit and throws warnings. Auth is inconsistently implemented; stateful sessions complicate horizontal scaling. + +**Existing solutions/workarounds.** Progressive tool disclosure / lazy loading (Claude Code's tool search), Anthropic's "code execution with MCP" (load tools on demand as code), tool-grouping gateways (Lunar MCPX), sub-agents with isolated tool sets, embeddings-based tool pre-selection (GitHub Copilot). Anthropic Skills use progressive disclosure as an MCP alternative. + +**Open gap.** MCP enterprise-readiness (auth-at-scale, multi-tenancy, governance, audit) remains "pre-RFC." **Build opportunity:** MCP gateways/governance and tool-routing infrastructure. + +### 16. Team Collaboration & Enterprise Adoption +**Problem.** DORA 2025's central finding: **AI is an amplifier** — strong teams get stronger, fragmented teams amplify dysfunction, and delivery instability rises across the board. Only ~1 in 5 companies has a mature governance model for autonomous agents (Deloitte). Inconsistent prompting styles and review thresholds across a team produce a codebase "with no singular point of origin." 88% of autonomous-agent pilots reportedly fail before production, attributed to governance/observability gaps rather than model quality. + +**Existing solutions/workarounds.** Shared rules/standards platforms (Packmind, team AGENTS.md), Value Stream Management, platform engineering (DORA: 90% of orgs have ≥1 internal platform; strong platforms correlate with unlocking AI value), enterprise admin controls (Cursor Teams, Copilot Agent HQ governance). + +**Open gap.** Team-level convention enforcement and agent governance across many repos/agents is nascent. **Build opportunity:** org-wide "agent governance plane." + +### 17. Onboarding & Learning Curve +**Problem.** Tool fragmentation is extreme (30+ agents across four categories). Setup differs wildly (BYOK keys, MCP config, spec frameworks). 35% of developers use 6–10 distinct tools to get work done. + +**Existing solutions/workarounds.** VS-Code-native extensions (Kilo Code, Cline, Continue) that avoid editor migration, migration-friendly forks (Cursor imports VS Code settings), managed IDEs (Kiro, Windsurf). + +**Open gap.** No consolidation layer; best practices are tacit and scattered. **Build opportunity:** opinionated "agent workflow starter kits" and interoperability standards. + +## The Competitive Landscape (2025–2026) + +Four categories now exist: **CLI agents** (Claude Code, OpenAI Codex CLI, Gemini CLI, Aider, opencode, Goose), **dedicated AI IDEs** (Cursor, Windsurf, Google Antigravity, Kiro, Zed), **IDE extensions** (GitHub Copilot, Cline, Continue, Roo Code, Kilo Code, Amp, Amazon Q), and **cloud/autonomous platforms** (Devin, OpenHands, Jules, Genie). + +- **Claude Code** — terminal-first, large context, strong on hard reasoning; hurt in 2026 by the degradation controversy and by restricting third-party (OpenCode/Windsurf) access to its models. +- **OpenAI Codex** — cloud-sandbox async PR delivery, tied to ChatGPT subscription; OpenAI reported 4M Codex users. Competitive on agentic terminal benchmarks. +- **Cursor** — best-in-class IDE UX and multi-agent "Agents Window"; scarred by repeated pricing controversies; building in-house Composer models and signing multi-year deals with OpenAI/Anthropic/Google/xAI to reduce dependency. +- **Windsurf** — Cascade agent with persistent context; roadmap disrupted by 2025 acquisition drama (Google acqui-hire of leadership, then Cognition acquiring the product; now positioned around Devin). +- **Devin (Cognition)** — fully autonomous; strong on bounded, well-scoped tasks (bug fixes, migrations, boilerplate) but weak on ambiguous/architectural work; Answer.AI's early eval: 3 of 20 tasks succeeded; ACU-based pricing; better value only for teams with predictable ticket backlogs. +- **Open-source/model-agnostic** (Cline, opencode, Aider, Roo Code, Kilo Code) — BYOK flexibility is the strategic hedge against model regressions and vendor lock-in. + +**Strategic dynamic:** model providers are absorbing the generation layer (Anthropic cutting third-party access; Microsoft making VS Code universally AI-ready), pressuring "wrapper" tools to differentiate on harness quality, context management, governance, and the "last mile." + +## Emerging Best Practices & Methodologies +- **Spec-driven development / agentic engineering** (Spec Kit, Kiro, OpenSpec, CLAUDE.md constitutions). +- **Context engineering** (curated windows, AGENTS.md, lazy loading, token budgets per context file). +- **Subagents & multi-agent orchestration** — Coordinator–Implementer–Verifier (CIV) patterns; VeriMAP (EACL 2026). +- **Memory systems** (Mem0, agentmemory) as a portable layer. +- **Evaluation & observability** (Langfuse, DeepEval, Confident AI; OpenTelemetry standardization). +- **Verification-first** ("vibe, then verify"; SonarQube Agentic Analysis; formal methods). + +## Where the Research/Industry Is Heading +- **Benchmarks are being rebuilt for realism.** OpenAI retired SWE-bench Verified (Feb 2026) after finding "59.4% of audited problems had flawed test cases" and that frontier models could reproduce ground-truth fixes from training contamination — concluding gains "no longer reflect meaningful improvements in models' real-world software development abilities." Contamination-resistant successors: **SWE-bench Pro** (Scale AI; the same model dropping from 80.9% Verified to 45.9% Pro quantifies the inflation), **SWE-bench-Live** (monthly updates), and economic benchmarks like **SWE-Lancer** (best model earned only ~$208K of $500K on the Diamond set; "frontier models are still unable to solve the majority of tasks"). +- **Consistency, not peak capability, is the enterprise blocker** (τ-bench pass^1 vs pass^8 collapse). ~19.78% of "solved" leaderboard cases were found semantically incorrect; even SWE-bench Pro verifiers were wrong ~32% of the time in one audit. +- **Independent verification is a live research problem.** AI-verifying-AI is structurally weak due to self-preference bias (Panickssery et al., NeurIPS 2024), self-attribution bias, and family bias — motivating independent verifiers and formal methods. +- **Formal verification is re-emerging** for AI code: Lean creator Leonardo de Moura argues "the barrier to verified software is no longer AI capability. It is platform readiness... the verification gap does not shrink. It widens." Work includes Astrogator (arXiv 2507.13290; verifies correct code 83%, flags incorrect 92%), Dafny-based PREFACE, and benchmarks CLEVER (NeurIPS 2025), DafnyBench, VeriCoding. +- **The unifying concept: the "verification gap" / "verification debt"** (AWS CTO Werner Vogels). Sonar's 2026 report: 96% of developers don't fully trust AI code is correct, yet only 48% always verify — a 48-point gap. + +## The Biggest UNSOLVED Pain Points (Ranked Build Opportunities) + +1. **The Verification Layer (highest-value whitespace).** Human review cannot scale to AI output volume (Faros: PR review time +441.5%, incidents per PR +242.7%, 31.3% of PRs merging with no review). AI-reviewing-AI is structurally biased. **Build:** independent verification (spec-as-executable-tests, formal methods for critical paths, semantic diff analysis, doom-loop/thrash detection), plus provenance/"proof-of-understanding" that shifts the burden of proof to the contributor. This is the clearest large market. +2. **Durable, portable memory & context.** No standard cross-session/cross-tool/cross-teammate memory layer exists. **Build:** a vendor-neutral "project brain" (decisions, conventions, corrections) that any agent inherits, with drift detection. +3. **Cost & reliability governance ("FinOps + regression monitoring for agents").** Unpredictable bills and silent model regressions erode trust. **Build:** real-time per-task cost attribution/forecasting with auto-downshifting, plus independent continuous model-quality/regression monitoring. +4. **Team/enterprise agent governance plane.** Only ~20% of firms have mature agent governance; pilots fail on governance, not models. **Build:** org-wide convention enforcement, policy gates, audit trails, and MCP/tool governance across many repos and agents. +5. **Technical-debt observability & autonomous paydown.** AI debt accumulates invisibly (8x duplication; 110K+ surviving AI issues). **Build:** debt attribution by source with duplication/churn gating and autonomous, verification-backed remediation. +6. **Secure-by-construction generation.** 45% of AI code is insecure and post-hoc scanning is a weak backstop. **Build:** agents that generate with security constraints enforced (CWE-aware SDD, secure templates) rather than scanning after the fact. +7. **Skill-preservation tooling.** Skill atrophy is real and imperceptible; the junior pipeline is at risk. **Build:** learning-preserving agent modes and team skill-health analytics. + +## Recommendations + +**For individual developers (next 2 weeks):** +- Adopt "trust but verify" as default: never merge unread AI output; track your acceptance rate — if you reject >50% of suggestions, AI is likely slowing you down (per METR's guidance). +- Use AI for conceptual inquiry (ask follow-ups, request explanations) rather than pure delegation to preserve comprehension (Anthropic's 17% finding). +- Standardize an AGENTS.md/CLAUDE.md per project and a lightweight spec before non-trivial tasks. + +**For engineering teams (next quarter):** +- Instrument the verification pipeline first: duplication/churn thresholds in CI, mandatory human review on AI-heavy PRs, SAST/SCA gates, and observability. DORA's lesson: fix the system before scaling AI, or AI amplifies dysfunction. +- Enforce provenance/attribution on PRs; adopt criteria-based PR gating (linked issue, passing CI, checklist). +- Prohibit unreviewed AI code in high-risk areas (auth, crypto, payments, PII). +- Deploy cost governance (per-model/per-developer attribution) before agent usage scales. + +**For builders/founders (where to invest):** +- Prioritize the verification layer and portable memory layer — the two highest-value, least-solved gaps. +- Build model-agnostic (BYOK) to hedge against provider consolidation and regressions. +- Design for the "last mile" and for teams/enterprises (governance, audit), where model providers are least likely to compete. + +**Thresholds that would change these recommendations:** +- If a contamination-resistant benchmark (SWE-bench Pro/Live) shows a model reliably >80% *with* high pass^k consistency, autonomous delegation of well-scoped tasks becomes defensible with lighter review. +- If a standard durable-memory protocol emerges and is widely adopted, the "portable brain" opportunity narrows to enterprise governance. +- If independent verification (formal or semantic) matures enough to gate merges automatically, the review-fatigue crisis eases and speed gains become real. + +## Caveats +- **Model/version naming volatility:** mid-2026 sources reference fast-moving and sometimes inconsistent model names/scores (e.g., specific SWE-bench leaderboard entries from aggregator sites). Structural findings (survey stats, OpenAI's retirement of SWE-bench Verified, DORA/METR/GitClear/Veracode/Faros results) rest on primary or reputable sources; specific leaderboard numbers from aggregators should be treated as approximate. +- **Selection bias:** Stack Overflow's survey over-represents its own engaged users; METR's RCT used only 16 experienced devs on mature repos (its own follow-up notes AI-averse devs increasingly decline to participate, biasing estimates). +- **Vendor sources:** many "solution" claims (Augment Code's 40% hallucination reduction, Functionize's flakiness numbers, memory-tool benchmarks) are self-reported and not independently reproduced. +- **Correlation vs causation:** GitClear's duplication/churn trends and DORA's instability findings are associational, not controlled experiments. +- **Fast-moving target:** tool capabilities, pricing, and benchmarks change monthly; several pain points (MCP context bloat, Claude Code controllability) are already being partially addressed (e.g., Claude Code 2.1, tool search/lazy loading). +--- metadata --- +{ + "filename": "pasted-text-2026-07-05T16-39-19.txt", + "content_type": "text/plain", + "size_bytes": 33435 +} \ No newline at end of file diff --git a/research/cognitive-substrate/sources/stack_landscape.md b/research/cognitive-substrate/sources/stack_landscape.md new file mode 100644 index 0000000..c11afca --- /dev/null +++ b/research/cognitive-substrate/sources/stack_landscape.md @@ -0,0 +1,127 @@ +# The Claude & Claude Code Development Stack: A Complete End-to-End Landscape (July 2026) + +## TL;DR +- The Claude Code ecosystem has consolidated around five composable primitives — **Skills (SKILL.md), Hooks, Plugins, MCP servers, and Subagents/Agent Teams** — all now distributable through an official Anthropic plugin marketplace and community registries; the SKILL.md format became an open cross-agent standard in December 2025 and works across Claude Code, Cursor, Codex, and Gemini CLI. +- For a full software lifecycle, the current "default" stack looks like: **Superpowers** (TDD + subagent methodology, ~137k stars) or **anthropics/skills** for skills; **PostToolUse/PreToolUse hooks** for lint/format/security enforcement; **Playwright MCP + Context7 + GitHub MCP + filesystem/memory** as core MCP servers; **CLAUDE.md + Auto Memory (+ Mem0/claude-mem)** for context; **ccusage + /usage** for cost; and **sandboxing + Gitleaks/Semgrep + /security-review** for security. +- The biggest 2026 shifts: Claude Code shipped OS-level **sandboxing** ("sandboxing safely reduces permission prompts by 84%," per Anthropic's engineering post), **Agent Teams** for multi-agent parallelism, the **official MCP Registry** (registry.modelcontextprotocol.io) went to preview, plugins reached the official marketplace, and a wave of **supply-chain security incidents** (CVE-2025-59536/59356, CVE-2026-21852, Mitiga's ~/.claude.json attack) made MCP/plugin vetting a first-class concern. + +## Key Findings + +**The extension model is now layered and official.** Anthropic has formalized a decision hierarchy: **CLAUDE.md/rules** for always-on context, **Skills** for model-invoked procedures/knowledge, **Hooks** for deterministic enforcement, **Subagents/Agent Teams** for delegation, **MCP servers** for external tools, and **Plugins** as the distribution unit that bundles all of the above. Custom slash commands have merged into skills — `.claude/commands/deploy.md` and `.claude/skills/deploy/SKILL.md` both create `/deploy`. + +**Community curation is enormous and fast-moving.** The canonical curated index is **hesreallyhim/awesome-claude-code** (~47.8k stars, hand-curated). **obra/superpowers** is the dominant methodology framework (Claude Bazaar's plugin listing, updated April 7 2026, cites "67.2K installs, 137.0K GitHub stars"; secondary sources range 137K–180K, and some blogs quote inflated figures up to 215K — treat the higher numbers with caution). **anthropics/skills** (~158k stars) is the official skills repo. Star counts move weekly; treat all figures as point-in-time. + +**Security is the defining risk story of 2026.** Multiple disclosed CVEs, a March 2026 source-code leak (512k lines of TypeScript via npm), and Snyk's February 2026 "ToxicSkills" study (36.82% / 1,467 of 3,984 audited skills had at least one security flaw; 13.4% / 534 carried a critical issue; 76 confirmed malicious payloads) mean supply-chain vetting of skills, plugins, and MCP servers is now mandatory, not optional. + +## Details — Stage by Stage + +### 1. Agent Skills (SKILL.md) +A skill is a folder containing a required `SKILL.md` (YAML frontmatter: `name`, `description`, optional `allowed-tools`, `context: fork`, `agent:`) plus optional `scripts/`, `references/`, `assets/`. Skills use **progressive disclosure**: only the ~100-token name+description loads at session start; the full body (<5k tokens) loads only when Claude's LLM judges it relevant (no embeddings/classifiers — pure LLM routing). The format was open-sourced as a standard (agentskills.io) in December 2025 and adopted by OpenAI Codex, Cursor, and Gemini CLI. + +**Scopes:** Project skills (`.claude/skills/`, committed to git), User skills (`~/.claude/skills/`), Plugin skills, and Managed (org-wide via managed settings). + +**Official Anthropic skills** (in `anthropics/skills`, ~17 top-level directories): document skills **pdf, docx, xlsx, pptx**; **frontend-design** (277k+ installs, anti-"AI slop"); **skill-creator** (meta-skill, `/plugin install skill-creator@anthropic-agent-skills`); **mcp-builder**; **canvas-design**; **artifacts-builder**; plus webapp-testing. Install via `npx skills add anthropics/skills --skill ` or the `anthropic-agent-skills` marketplace. + +**Community skill collections:** **obra/superpowers** (14 SKILL.md files enforcing brainstorm→plan→TDD→subagent-dev→review); **Antigravity Awesome Skills** (1,234+ cross-agent skills, ~22k stars, `npx antigravity-awesome-skills --claude`); **K-Dense-AI/claude-skills-mcp**. **Discovery hubs:** SkillsMP (indexes 2M+ skills), skills.sh/officialskills.sh, claudemarketplaces.com (300k+ monthly visitors), mcpmarket.com. + +### 2. Hooks +Hooks are deterministic event handlers in `.claude/settings.json` (team) or `settings.local.json` (personal). The event set has grown from 6 (June 2025) to ~17–21 by 2026, including: **SessionStart, SessionEnd, UserPromptSubmit, UserPromptExpansion, PreToolUse, PermissionRequest, PostToolUse, PostToolUseFailure, Stop, SubagentStart, SubagentStop, PreCompact, Notification**, plus newer TeammateIdle/TaskCreated/TaskCompleted for Agent Teams. Handler types: **command** (shell), **http** (POST to endpoint, added Feb 2026), **prompt** (single-turn LLM eval), and **agent** (subagent verifier). + +**Key mechanics:** Exit code 2 in PreToolUse blocks a tool (stderr fed back to Claude); exit 2 in Stop forces Claude to keep working (guard against loops with `stop_hook_active`). PreToolUse returns `allow/deny/ask/defer` (precedence deny>defer>ask>allow), can rewrite tool input via `updatedInput`, and `updatedToolOutput` (v2.1.121+) can redact secrets from any tool's output. + +**Common uses:** PostToolUse auto-format (prettier/eslint on Write|Edit); PreToolUse block `rm -rf`/`DROP TABLE`/`.env` reads (the reliable way to block .env — permission rules and .claudeignore can be bypassed); Stop-hook `npm test` gate; SessionStart context injection (git branch); Notification/TTS. **Community collections:** disler/claude-code-hooks-mastery, FlorianBruniaux/claude-code-ultimate-guide, luongnv89/claude-howto. + +### 3. Plugins +A plugin is a directory with `.claude-plugin/plugin.json` plus components: `skills/`, `agents/`, `hooks/`, `.mcp.json`, LSP servers, and monitors. Install via `/plugin marketplace add owner/repo` then `/plugin install name@marketplace`. Plugins solve "tribal knowledge" (Anthropic's May 2026 term) — they're versioned, namespaced, and git-distributable. + +**Official marketplace:** **anthropics/claude-plugins-official** (`/plugins` internal Anthropic, `/external_plugins` partners). Reference plugins in `anthropics/claude-code/plugins`: **pr-review-toolkit** (5 parallel Sonnet review agents), **plugin-dev** (8-phase create-plugin workflow), **ralph-loop** (autonomous iteration via Stop hook), agent-sdk-dev. Partner plugins: Shopify AI Toolkit, AWS Agent Toolkit, Airtable, Mercado Pago, Convex, CrowdStrike, HashiCorp, Vercel. Superpowers was accepted into the official Anthropic marketplace on January 15, 2026. + +**Community marketplaces:** Superpowers marketplace (`obra/superpowers-marketplace`), and directories like claudemarketplaces.com (2,500+ marketplaces, 12,500+ servers indexed), claudepluginhub.com, aitmpl.com (340 plugins + 1,367 skills, CCPI package manager). Thoughtworks Technology Radar endorsed the git-based marketplace model for killing "version drift." + +### 4. MCP Servers +MCP (open-standard, Anthropic, late 2024) is now the de-facto tool plug for AI agents. The **official MCP Registry** (registry.modelcontextprotocol.io) launched in preview Sept 8, 2025 as the single source of truth feeding sub-registries; per Anthropic's Dec 9, 2025 announcement (donating MCP to the Agentic AI Foundation), "There are now more than 10,000 active public MCP servers... 97M+ monthly SDK downloads across Python and TypeScript." PulseMCP tracks ~20k mid-2026, though registry data is heavily inflated by CI-republished duplicates — SafeDep found ~64.7M raw entries mapping to only ~1,691 unique packages. The MCP 2026-07-28 spec (RC May 2026) adds a stateless core, MCP Apps (server-rendered UI, launched Jan 26 2026 with Figma/Slack/Canva/Asana partners), and Tasks. + +**Most-used servers by category (mid-2026 GitHub star counts, verified from live GitHub pages):** +- **Browser/testing:** microsoft/playwright-mcp (~34k, official Microsoft; use `@playwright/mcp`, not deprecated `@modelcontextprotocol/server-playwright`); Chrome DevTools MCP; Browserbase/Stagehand. +- **Reference/core:** modelcontextprotocol/servers monorepo (~86–87k stars, official) — filesystem, memory (knowledge graph), sequential-thinking, fetch. +- **Docs:** upstash/context7 (~58k, vendor) — version-specific library docs via "use context7." +- **GitHub/Git:** github/github-mcp-server (~31k, official GitHub). +- **Database:** supabase-community/supabase-mcp (~2.7k, official Supabase, hosted at mcp.supabase.com with OAuth; the most-used database MCP by traffic); Postgres MCP; plus MongoDB/Redis servers. +- **Search/web:** Exa (most-used agent search server 2026); Firecrawl; Tavily. +- **Cloud:** AWS MCP Server (GA 2026, part of Agent Toolkit for AWS, IAM SigV4 auth via mcp-proxy-for-aws); Cloudflare; Vercel. +- **Design:** Figma MCP; design-context-bridge. +- **Comms/PM:** Slack, Atlassian (Jira/Confluence, deprecating SSE June 30 2026), Linear, Sentry, Notion — many moved to remote HTTP endpoints in 2026. +- **Memory:** @modelcontextprotocol/server-memory; Mem0. + +**Awesome lists:** punkpeye/awesome-mcp-servers (~90k, main community list), wong2/awesome-mcp-servers, tolkonepiu/best-of-mcp-servers (ranked weekly). **Wiring into Claude Code:** `claude mcp add `, `.mcp.json` (project), or `~/.claude.json`; MCP tool permission format is `mcp__server__tool`. Best practice: don't run more than ~6 at once; scope credentials to read-only. + +### 5. Custom Rules / Memory / Context Engineering +**CLAUDE.md** files (project root, `~/.claude/`, enterprise/managed, nested per-directory) load at every session start. Best practices: keep under 200 lines (adherence drops beyond); use path-scoped rules to load instructions only for matching files; project-root CLAUDE.md survives `/compact` (re-read from disk); `@path` imports organize but don't save tokens (all load at launch). CLAUDE.md is context, not enforcement — for hard blocks use a PreToolUse hook. + +**Auto Memory** (v2.1.59+): Claude writes its own notes to `~/.claude/projects//memory/`, loading the first 200 lines of MEMORY.md at startup. Hard limits in source: 200-line index cap and 5-files-per-turn retrieval, with silent truncation (the "memory cliff"). Four memory types: user, feedback, project, reference (info derivable via grep/git should NOT be saved). + +**External memory backends:** **Mem0** (~58k stars, hosted MCP + lifecycle hooks; Mem0's own research page, updated May 2026, reports its token-efficient algorithm "hits 92.5 on LoCoMo, 94.4 on LongMemEval... averaging under 7,000 tokens per retrieval call"); **claude-mem** (continuous capture, SQLite + FTS5/vector, Haiku summaries); **Hindsight** (94.6% LongMemEval, MIT, self-hostable); **supermemory** (cross-machine sync). Anthropic's **memory tool** (API, client-side file ops, pairs with context editing + compaction, ZDR-eligible). Context-engineering principle: optimize signal-to-noise per token; retrieve just-in-time; use prompt caching (cache reads ≈10% of input price). + +### 6. Subagents / Agent Orchestration +**Subagents** run in isolated context windows and return only their final message (context preservation + parallelization + per-agent least privilege). Built-ins: **Explore** and **Plan** (read-only, skip CLAUDE.md/git for lean context), **general-purpose** (inherits model + full tools), plus helpers statusline-setup (Sonnet) and claude-code-guide (Haiku). Custom agents defined in `.claude/agents/` with tool scoping and per-agent `model:` (e.g. `model: haiku` for cheap subtasks). + +**Agent Teams** (experimental, `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1`, v2.1.32+): one "team lead" coordinates teammates via a shared task list; teammates run in their own contexts and can message each other directly (unlike subagents that only report to the parent). **Orchestration patterns:** parallel fan-out for independent tasks (60–80% wall-clock savings), sequential chains for dependent work, orchestrator-classifies-then-routes to Haiku/Sonnet/Opus by complexity, panel review for quality. Community orchestrators: Agent Teams, Gas Town, Multiclaude; git worktrees isolate parallel agents. The **Ralph Wiggum loop** (Geoffrey Huntley, July 2025) runs an agent in a loop until a condition is met — now supported natively via `/loop`, `/goal` (v2.1.139+), and `/batch`, plus the ralph-loop plugin. Superpowers' **subagent-driven-development** skill (94.8k installs) dispatches a fresh subagent per task with two-stage review (spec compliance, then code quality). + +### 7. Cost Management +**Built-in:** `/usage` (aka `/cost`, `/stats`) shows session cost + plan limits; `/context` visualizes the context window as a colored grid. Per Claude Code's cost docs, "the average cost is around $13 per developer per active day and $150–250 per developer per month, with costs remaining below $30 per active day for 90% of users" (Business Insider notes the per-day figure doubled from $6 on April 15, 2026). Plan caps: Pro ~44k tokens/5-hr window, Max5 ~88k, Max20 ~220k, plus weekly caps. + +**Community trackers** (all parse local JSONL logs — nothing leaves your machine): **ccusage** (~16.5k stars, `npx ccusage`, daily/monthly/session/5-hr-block reports, now multi-tool for Codex/OpenCode/Gemini/Copilot etc.); **Claude-Code-Usage-Monitor** (`pip install claude-monitor`, `cmonitor`, live burn-rate + prediction); **ccflare**; **ccstatusline** (status-line); Clusage (VS Code extension). + +**Reduction techniques:** model tiering (Haiku for simple, Sonnet default, Opus for hard reasoning; `/model` to switch); `/compact` with custom instructions; clearing context between tasks; deferred MCP tool loading (only tool names enter context until used); prompt caching. **LLM gateways** for routing/failover/spend control: **LiteLLM** (open-source, self-hosted, OpenAI-compatible, supports Claude Code prompt-cache routing, zero markup); **Portkey** (enterprise observability, semantic caching, guardrails, ~8k stars); **OpenRouter** (300+ models, 5.5% credit fee, simplest); plus newer Anthropic-protocol-native gateways (Lynkr) and Vercel AI Gateway. Point Claude Code at a gateway via `ANTHROPIC_BASE_URL`. Enterprise cost tracking via OpenTelemetry export. + +### 8. UI/UX Development +The core problem is **"AI slop"** — the generic Inter/Roboto font + purple-gradient-on-white + card-grid look. Anthropic's official **frontend-design skill** (`anthropics/skills`) is the flagship answer: it forces an aesthetic commitment (purpose/tone/constraints/differentiation) before any code, explicitly bans overused fonts (Inter, Roboto, Arial, system fonts, Space Grotesk), ranks accessibility highest (4.5:1 contrast, focus rings, ARIA, keyboard nav), and supports persistent design systems (`--design-system --persist` → design-system/MASTER.md + per-page overrides). It supports stacks: html-tailwind, react, nextjs, vue, svelte, shadcn, swiftui, react-native, flutter, jetpack-compose. Its instructions read like a creative director's brief ("Spend your boldness in one place… before leaving the house, take a look in the mirror and remove one accessory"). + +**Workflow tools:** **Figma MCP** / design-context-bridge (read actual components, colors, type scale — not screenshots); **shadcn/ui** + Builder.io; **v0** for design-to-code; Design.md/design-system markdown pattern (explicit hex, exact fonts, pixel spacing, negative rules). Platform stacks: frontend-design skill + Shopify AI Toolkit (Liquid/GraphQL validation, shipped April 9 2026) or WordPress.com MCP. Community: design-anti-slop skill, Patrick Ellis's Design Review Workflow (awesome-claude-code). Reddit reports "Super-IC" designers outputting 3-person-team volume; AI adoption among UX researchers hit 80% in 2025 (Loop11). + +### 9. Testing +**Playwright MCP** (`npx @playwright/mcp@latest`, `claude mcp add playwright`) gives Claude live browser control so it generates tests from the real DOM/accessibility tree, not guessed selectors. **Playwright's three official agents** (planner→generator→healer, `npx playwright init-agents --loop=claude`) are just editable Claude Code subagents that explore the app, write specs (Markdown), generate tests aligned 1:1 with specs, and auto-repair failing tests. Best practice: **MCP for exploration/self-QA, CLI for repeated CI runs** (mixing them breaks caching); ground agents with an `app.context.md` + JSDoc + skills; run generated specs 3–5× in CI before trusting (treat CI as truth, local as draft); replace brittle selectors with getByRole/getByTestId. + +**Patterns:** self-QA (Claude opens localhost, verifies its own changes); 4-agent pipeline (Exploration→Test Case→Automation→Maintenance with file-based handoffs + human checkpoint); TDD via Superpowers' RED-GREEN-REFACTOR skill (deletes code written before tests); coverage enforcement via Stop hooks (`npm test || exit 2`); GitHub Actions QA via anthropics/claude-code-action with Playwright MCP and scoped browser-only tools. **A caution flag:** the Playwright healer auto-applying fixes can silently hide real bugs when a test breaks due to a genuine behavior change. + +### 10. Security +**Native controls:** default read-only permissions; allow/ask/deny rules (`permissions.deny: ["Read(./secrets/**)", "Bash(curl:*)", "WebFetch"]`); **sandboxing** (`/sandbox`, open-sourced by Anthropic) with filesystem + network isolation (macOS Seatbelt built-in; Linux/WSL2 needs bubblewrap + socat) — Anthropic's engineering post states "sandboxing safely reduces permission prompts by 84%"; write access confined to working dir; command-injection detection; trust verification for new codebases/MCP servers; isolated context for web fetch; **Claude Code on the web** runs each session in an isolated cloud VM with credentials outside the sandbox. Enterprise: managed settings (override all scopes), SAML/OIDC SSO, OpenTelemetry audit, MCP allowlists. + +**The 2026 threat landscape is serious.** Disclosed issues: **CVE-2025-59536** (RCE via malicious hooks in project settings), **CVE-2025-59356** (hooks-based RCE), **CVE-2026-21852** (API-key harvesting via env override) — all Check Point; Oasis Security's "Claudy Day" (invisible prompt injection → exfiltration via Files API on a default claude.ai session); Mitiga's npm-post-install attack rewriting `~/.claude.json` to steal OAuth tokens (Anthropic ruled out-of-scope); "Sandworm_Mode" npm typosquatting of MCP servers; the March 31 2026 source leak. OWASP published a **Top 10 for Agentic Applications (2026)** ranking Agent Goal Hijacking (ASI01) #1. **Prompt injection is the top risk** — model-level detection alone is insufficient; sandboxing + network allowlists + infra-layer input filtering are needed. + +**In-loop security tooling (SAST/SCA/secrets):** **Semgrep** (SAST, MCP + CLI, community rules catch 80–90% of GitHub Advanced Security findings on typical web apps); **Gitleaks** (~19k stars, secret scanning via pre-commit hook — the standard fix for agents committing credentials); **TruffleHog** (~18k stars, 700+ verified secret types); **Trivy** (dependency/IaC/container); **Snyk MCP**; **Aikido MCP**; **Endor Labs**; **42Crunch** (API security); OSV/dependency-audit hooks. Claude Code's own **`/security-review`** command and **Anthropic's Claude Code Security Review GitHub Action** analyze PR diffs. Curated hub: **efij/awesome-claude-code-security**. Per Snyk's ToxicSkills blog (Feb 2026), "13.4% of all skills, or 534 in total, all contain at least one critical-level security issue... 36.82% (1,467 skills) have at least one security flaw" — making vetting skills like dependencies mandatory; read SKILL.md + scripts before install, and there's a free AI-skill security scanner for SKILL.md/MCP configs. Governance-layer tools: MCP governance proxies (policy + human approval + hash-chain audit), credential-isolation proxies (TrueFoundry AI Gateway), per-server least-privilege credentials. + +## Recommendations + +**Stage 0 — Baseline setup (all teams, day 1):** +1. Add a lean CLAUDE.md (<200 lines) with build commands, conventions, "always/never" rules; enable Auto Memory. +2. Install core hooks: PostToolUse auto-format (prettier/eslint), PreToolUse blocks for `rm -rf`/`.env`/secrets, and a Gitleaks pre-commit hook. +3. Enable `/sandbox` (defense-in-depth) and set explicit permission allow/ask/deny rules. +4. Install ccusage (`npx ccusage`) and check `/usage` + `/context` regularly. + +**Stage 1 — Add capability (week 1–2):** +5. Install 3–5 MCP servers max, scoped read-only: Context7 (docs), GitHub MCP, Playwright MCP, filesystem/memory, plus one database server. Pin versions; don't `npx -y latest` in production. +6. Install the official frontend-design skill for any UI work; add Figma MCP if you have designs. +7. Adopt a methodology framework — **Superpowers** for teams wanting enforced TDD/planning/subagent-driven dev; otherwise anthropics/skills + pr-review-toolkit. + +**Stage 2 — Scale to a team (month 1+):** +8. Package your conventions into a **plugin** and host an internal git marketplace (kills version drift; new hires get the stack day one). +9. Route Claude Code through an **LLM gateway** (LiteLLM self-hosted for control, Portkey for enterprise observability) for spend caps, failover, and per-user attribution; export OpenTelemetry for FinOps. +10. Adopt Agent Teams / subagent fan-out for parallel work; use git worktrees for isolation; route subagents to Haiku/Sonnet by complexity. +11. Stand up an in-loop security pipeline: Semgrep + Gitleaks + Trivy + `/security-review` in CI (SARIF to GitHub Security tab), plus mandatory review of any third-party skill/plugin/MCP source before install. + +**Thresholds that change the plan:** If per-developer cost exceeds ~$30/active-day consistently → tighten model tiering and context hygiene before adding capability. If you connect MCP servers touching production data/credentials → mandate sandboxing + network allowlists + a governance proxy. If skills/plugins come from outside your org → treat every one as an untrusted dependency (ToxicSkills: roughly 1 in 7 audited skills had a critical flaw). If memory/MEMORY.md exceeds 200 lines → move to Mem0/claude-mem/Hindsight. + +## Caveats +- **Star counts and version numbers are point-in-time (mid-2026) and move weekly** — verify current figures before relying on them. Aggregator sites systematically lag GitHub's live numbers; Superpowers in particular is quoted anywhere from ~137K (Claude Bazaar, April 2026) to 215K+ across sources depending on scrape date, so the higher figures should be treated skeptically. +- **Registry server totals are inflated** by CI-republished duplicates (SafeDep: ~64.7M raw entries → ~1,691 unique packages); "20k servers" ≠ 20k distinct useful tools. Anthropic's own count is ">10,000 active public MCP servers" (Dec 2025). +- **Some 2026 model/product names in sources are unverifiable or speculative** (e.g., "Opus 4.8," "Claude Fable 5," "GPT-5.5" appear in vendor blog posts) and should not be treated as confirmed; I've avoided leaning on them. +- **Security findings evolve fast** — CVEs get patched and new attack chains appear; the specific incidents cited are illustrative of a class of risk, not a current-status list. Anthropic's "out of scope" ruling on the Mitiga npm attack means that particular chain may remain live. +- **Marketing vs. reality:** many "best tools" lists are SEO/affiliate content; I prioritized official Anthropic docs, primary GitHub repos, and named security research. Vendor benchmark claims (memory accuracy %, token-savings %) are self-reported. +- Multi-agent orchestration, Agent Teams, and sandboxing on Linux remain **experimental/beta** with real failure modes (context drift at 10+ agents, infinite Stop-hook loops, cold-start timeouts). +--- metadata --- +{ + "filename": "pasted-text-2026-07-05T16-38-56.txt", + "content_type": "text/plain", + "size_bytes": 24228 +} \ No newline at end of file diff --git a/research/empirical-refutation/README.md b/research/empirical-refutation/README.md new file mode 100644 index 0000000..afe3e8b --- /dev/null +++ b/research/empirical-refutation/README.md @@ -0,0 +1,96 @@ +# Replication package + +*Static Impact Analysis Does Not Transfer: A Pre-Registered Refutation of Two LLM-Agent Reliability Mechanisms* + +This package contains everything needed to check every number in the paper. It is organised so that +a reviewer can start from the frozen protocol and work forward, in the order the work was actually +done. + +**Read `protocol/PRE_REGISTRATION.md` first.** It was written and frozen before any repository was +cloned, and it fixes every threshold, filter, and selection rule used downstream. Its own stated +rule is the one thing that makes the rest of this package meaningful: *if a downstream number looks +bad, the fix is to report it, not to edit this file.* Amendments were permitted only as dated, +append-only addenda; three were filed, all documenting the corpus-selection funnel. + +## What is here + +### `protocol/` — the frozen contract +| File | What it is | +|---|---| +| `PRE_REGISTRATION.md` | Nine corpus eligibility criteria, commit filters, threshold grid, bootstrap seeds. Frozen before data collection. | +| `corpus_manifest.json` | The nine repositories with exact clone SHAs, the eligibility decisions, and every substitution logged. | +| `SPLIT_DECLARATION.json` | The tuning/held-out repository split for the repair, declared before any repair code was written. | +| `FROZEN_PARAMETERS.json` | The eight repair parameters, fixed on tuning repositories only, before the held-out set was touched. | + +### `data/` — the ground truth +| File | What it is | +|---|---| +| `cochange_groundtruth.parquet` | 801 labelled files across 9 repositories. For each file, the other Python files that co-changed with it in the same non-merge commit, after the pre-registered filters. | +| `heldout_taskset.json` | 80 tasks drawn from real GitHub issues and PRs, with full provenance (repo, number, URL, verbatim text), gold labels, the labelling protocol, and a second independent labelling pass. | + +### `results/` — every number in the paper +| File | What it is | +|---|---| +| `cochange_results.json` | Per-repo and pooled P/R/F1 with bootstrap CIs, the full threshold sweep, the per-file recall distribution. | +| `cochange_failure_modes.json` | All 18,221 false negatives classified structurally, with the ground-truth ceiling. | +| `cochange_report.md` | The written evaluation, including threats to validity. | +| `heldout_results.json` | Routing and gate metrics with CIs, inter-rater agreement, calibration bins, and the full cost accounting. | +| `repair_results.json` | The (a)–(g) repair sequence: as-shipped reproduction, each fix, tuning and held-out results. | +| `repair_report.md` | The written before/after. | +| `novelty_assessment.json` | Five claimed contributions graded against closest prior work, including the scoop. | +| `related_work.md`, `related_references.json` | The full survey and 52 graded references. | +| `internal_review_findings.json`, `internal_review_report.md` | Our own adversarial review of this paper, and what it found wrong. Included deliberately: it lists four numbers we had stated incorrectly before correction. | + +### `prototypes/` — the code under test +| File | What it is | +|---|---| +| `impact_oracle_v1_as_shipped.zip` | The version whose claims the paper refutes. 36 tests. | +| `impact_oracle_v2_src.zip` | The repaired version. 49 tests, including the stdlib-collision safety case. | +| `router_gate_src.zip` | The router and assumption gate, thresholds exactly as evaluated. 19 tests. | + +Each package runs with `python -m pytest` from its own root (a `conftest.py` handles the path). +The oracle needs `networkx`; the router needs only `pytest`. + +### `figures/`, `paper/` +The six figures at full resolution, and the paper with its LaTeX source and bibliography. + +## Verifying the headline claims + +**The refutation.** `results/cochange_results.json` → `pooled_metrics.oracle_by_threshold["0.02"]` +gives precision 0.398, recall 0.022, F1 0.042 from tp/fp/fn = 409/618/18221. The grep baseline in the +same file gives F1 0.437. Every F1 in the paper is computed from raw counts and rounded once. + +**The ceiling.** `results/cochange_failure_modes.json` → the three failure categories +(94.68% sibling, 2.13% forward-only, 3.19% no static path) sum over the 18,221 false negatives. +The 3.19% figure is what bounds achievable recall at 96.88%. + +**The repair.** `results/repair_results.json` → `d_defect1and2_heldout_HEADLINE`. The paper headlines +`metrics_at_canonical_0.02` (F1 0.416), not the higher `metrics_at_best_threshold` (0.428), because +the latter's threshold was selected on the tuning repositories. + +**The held-out collapse.** `results/heldout_results.json` → `tuned_vs_heldout_comparison`. +Note `cost_analysis.n_execution_verified = 0`: no held-out task admitted execution-based +verification, so correctness used a weaker model-based criterion. + +**The cost inversion.** `results/heldout_results.json` → `cost_analysis` carries four figures along two +orthogonal axes, and the paper reports all four rather than the most favourable one. Framing: +`first_attempt_framing` counts only the initially-routed attempt; `escalation_inclusive_framing` counts +everything the pipeline spent retrying up the tier ladder. Gating: `raw_saving_pct` credits every dollar +saved, `correctness_gated_saving_pct` credits only dollars saved on output that verifies. The tuned +demonstration's 62.1% corresponds to first-attempt/ungated (59.5% held out). The honest total-spend, +ungated figure is **−20.2%**: the router costs more than always using the premium tier. The source's own +`honesty_note` states this. + +## What this package cannot establish + +The pre-registration, the split declaration, and the parameter freeze were all self-administered +within one continuous working session. There is no external timestamping authority. A reader can +verify internal consistency and the append-only amendment trail, but must take the ordering on +trust. We regard this as the central weakness of a self-evaluation and state it in the paper rather +than resting on the protocol's authority. + +Co-change is a proxy for semantic impact and errs in both directions: files co-change for reasons no +static analysis can predict, and an over-warning may be a correct dependency that has not yet +co-changed. The 96.9% ceiling is measured on the graph the as-shipped oracle builds, and reachability +in a dense graph is a weak property — it bounds what any static method could attain, and is not +evidence that a reachable pair is causally related. diff --git a/research/empirical-refutation/extended_preprint.html b/research/empirical-refutation/extended_preprint.html new file mode 100644 index 0000000..904831c --- /dev/null +++ b/research/empirical-refutation/extended_preprint.html @@ -0,0 +1,783 @@ + + + + + +A Formal Theory of the Cognitive Substrate for Coding Agents + + + + + +

A Formal Theory of the Cognitive Substrate for Coding Agents

+

Extended edition, with a pre-registered empirical refutation. Unifies the substrate faculties, the end-to-end reliability framework, and the forgekit implementation — with a two-layer duality theorem, a unified algorithm set, a Qur’anic epistemology carried in full, and a measurement that overturned two of this work’s own headline claims.

+ +
+

Status of this edition

+

This is the extended companion to a venue submission reporting a pre-registered empirical evaluation of +the two prototypes described here. That evaluation refuted both of their headline claims: +the impact oracle's perfect recall collapsed from 1.00 to 0.022 on real repositories, and the router/gate +pair's perfect separation fell to F1 = 0.37 with its cost saving inverting from +62.1% to −20.2% once the pipeline's escalation retries are counted. Section 10 reports the refutation, the diagnosis, and a repair that recovers a +narrow win over the baseline, and states what the failure costs the formalism — specifically, that +Theorem T5's completeness guarantee transfers nothing to practice until the underlying relation is +shown adequate. Theory sections are otherwise unchanged; where they make empirical claims, those claims are +now the corrected ones.

+
+ +
+

Abstract

+

A large language model used for coding is a fixed probabilistic map, y = fθ(x): stateless, frozen, and bounded in context. Three research efforts converged, independently, on the same conclusion — that the remedy is not a better prompt or a bigger model but an external, stateful architecture wrapped around the frozen core. This paper proves they are describing one object. We show that the substrate's impact-awareness faculty and the framework's change-closure fixpoint Δ* are the same mathematics; that the assumption gate and the amnesia equation assumption ≈ argmax P(convention | training) are the same phenomenon; and that both reduce to a single two-layer duality: a probabilistic instruction layer that raises the probability p<1 of correct behaviour, and a deterministic interception layer that guarantees a floor. The central theorem states that neither layer alone can make an agent reliable — a direct formalization of the discipline never trust the output of a probabilistic engine; earn trust with an external check. We give definitions, the duality theorem with proof, a unified seven-algorithm task loop, the probabilistic failure model P(≥1 miss)=1−pn, and carry through the six correctness theorems of the reliability framework. Two prototypes — an impact oracle and a complexity-router/assumption-gate — instantiate the deterministic layer and are evaluated honestly. The forgekit / claude-e2e-kit codebase is the deployed binding. The Qur'anic lens supplies the vocabulary of epistemic obligation (tabayyun, amāna, lā taqfu) that names why each safeguard is mandatory rather than optional.

+
+ + + + +

1 The convergence — three roads to one architecture

+ +

Three efforts set out from different starting points and arrived at the same building.

+ +

The first began with a question about human cognition: when a developer opens a file, they carry memory of what already exists, imagine what an edit will break, and verify their reasoning as they type. A frozen language model does none of this. The Cognitive Substrate workS named five faculties the model structurally lacks — memory, learning, imagination, self-correction, and impact-awareness — and argued the remedy is an external architecture that supplies them, together with six operating mechanisms (M1–M6: complexity-routing, an assumption gate, decomposition, goal-anchoring, scope-minimality, and inline verification).

+ +

The second began with two concrete failures observed in production coding agents. F1, partial work: the agent changes code but not the artifacts that depend on it — docs, tests, changelog, examples. F2, session amnesia: a later session lacks the project's goals and conventions, so it fills the gaps with assumptions and the developer burns iterations re-explaining. The End-to-End Reliability FrameworkE gave these a formal model: a typed artifact graph, a change-closure fixpoint, four invariants, seven algorithms, and six correctness theorems.

+ +

The third is a deployed codebase. forgekitK (and its Claude-specific precursor claude-e2e-kit) implements the same discipline as committed files, deterministic lifecycle hooks, and auto-invoked skills — one configuration that binds the architecture onto Claude Code, Codex, Cursor, Gemini, and Aider alike.

+ +
+

The claim of this paper

+

These are not three similar ideas. They are one architecture described in three vocabularies. The impact-awareness faculty is the change-closure fixpoint. The assumption gate is the amnesia equation. The substrate's external structure is a two-layer duality — and that duality, which the reliability framework states as a design law, is the theorem the whole thing turns on. What each road saw partially, the union sees whole.

+
+ +

The synthesis also inherits a governing discipline, stated plainly by the practitioner who commissioned this work: AI output is a mathematically calculated probability; it must never be trusted blindly; for the same prompt it can give a different answer, so use only the capability it is genuinely best at, and earn trust with an external check. We will see that this sentence is not a slogan but the informal statement of the central theorem — the quantity (1−p)>0 that forces a deterministic layer to exist.

+ +

2 The object of study — the frozen map and its five lacks

+ +

Fix the model. Let the coding agent's core be a function

+
(1)y = fθ(x), θ fixed,  x the bounded context window,  y the sampled output.
+ +

Three properties of this map generate every problem the architecture must solve. To avoid a notation collision with the reliability framework's primitives (§3), we label these model properties P1–P3:

+ +
    +
  • P1 — statelessness. fθ has no memory across calls; each invocation sees only the current x. Nothing the agent learned yesterday is present today unless something outside the model re-supplies it.
  • +
  • P2 — frozen parameters. θ does not change from use. The agent cannot learn from an outcome by updating weights; any learning must be external.
  • +
  • P3 — bounded, undifferentiated context. x is finite and flat: a long story and a long program are the same kind of object to it, with no privileged channel for goals versus detail. This is the root of goal-drift and of context saturation.
  • +
+ +

The five faculties are not wishes; each is the direct consequence of one or more of these properties, and each has an external remedy:

+ + + + + + + + +
Faculty the model lacksForced byExternal remedy (this architecture)
Persistent memoryP1A committed store re-injected each session (§6, A4/A5)
Learning from outcomesP2Non-parametric experience store; optional parametric adapters (§6)
Imagination / world-modelP1, P3A typed artifact graph the agent queries before acting (§3.2)
Self-correctionP3An external verifier and a deterministic completion gate (§4, A6)
Impact-awarenessP1, P3The change-closure Δ* computed on the graph (§3.2, A1)
+ +

The critical word is external. Because θ is frozen (P2) and context is bounded (P3), none of these can be fixed by prompting harder or by fine-tuning alone. The architecture must live around the model, hold state outside it, and enforce behaviour the model cannot be relied upon to produce on its own. The rest of this paper makes "cannot be relied upon" precise and shows what "enforce" must therefore mean.

+ + +

3 Definitions

+ +

3.1 The stateful substrate operator

+ +

The architecture turns the stateless map (1) into a stateful operator by threading an external memory M through it.

+ +
Definition 1 (Cognitive substrate)
+

A cognitive substrate over a frozen model fθ is an operator

+
(2)(yt, Mt+1) = F(xt, Mt; fθ)
+

where Mt is a persistent store that survives between calls, xt is the request at step t, and yt is the output. The store carries what P1–P3 deny the model: prior state, learned priors, the world-model, and the reflection log. F is required to read Mt into the model's context before sampling and to write back Mt+1 after — the closed loop the bare model (1) does not have.

+
+ +

Three environmental capabilities are needed to realize M and the read/write loop. The reliability framework calls these its primitives. It labels them P1/P2/P3, which collides with the model properties of §2; we therefore rename them Π1, Π2, Π3 and use that notation for the remainder of the paper.

+ + + + + + +
PrimitiveDefinitionforgekit bindingGeneric binding
Π1 — persistent storeFiles the agent can read/write that survive sessions and travel with the projectgit repo: CLAUDE.md, docs/*.md, .claude/**any VCS; any repo-reading agent
Π2 — lifecycle interceptionDeterministic code executed at fixed points of the agent loop (start, end-of-turn)hooks: SessionStart, Stop, UserPromptSubmitpre-commit hooks; CI jobs; IDE tasks
Π3 — instruction channelStanding instructions loaded into the model's contextCLAUDE.md, .claude/rules/, skillsAGENTS.md, .cursorrules, system prompts
+ +
+

The design law, stated early because everything depends on it

+

Π3 is probabilistic; Π2 is deterministic. Instructions (Π3) raise the probability that the model behaves correctly; interception (Π2) executes regardless of what the model decides. A reliable substrate needs both, and §4 proves it cannot be built from either alone.

+
+ +

3.2 The repository as a typed artifact graph (the world-model)

+ +

The imagination/world-model faculty is realized concretely as a graph over the project's artifacts — the generalization that lets "impact on code" become "impact on everything that describes or depends on the code".

+ +
Definition 2 (Typed artifact graph)
+

Let the project be a finite set of artifacts A = {a1, …, an} with a type function τ : A → {code, test, doc, config, diagram} and a dependency relation R ⊆ A × A, where (a,b) ∈ R means "a describes, verifies, exercises, or references b". R = Rdeclared ∪ Rdiscovered: declared edges come from a curated documentation map (high precision, small); discovered edges are found mechanically — a mentions an identifier defined in b — by text search.

+
+ +

The substrate's Prototype I builds this graph from source: an AST parser extracts the code nodes and their edges, so Rdiscovered over {code, test} is computed exactly rather than by grep. The reliability framework's contribution is to widen τ beyond code, making documentation a first-class dependent so that a code change can be seen to obligate a doc change.

+ +
Definition 3 (Dependents operator and change closure)
+

For a set X ⊆ A, the dependents operator is

+
(3)N(X) = { a ∈ A : ∃ b ∈ X, (a,b) ∈ R }
+

— everything that describes, verifies, or references anything in X. A task seeds a change set Δ0 ⊆ A (the files the request names or obviously touches). The required change closure is the least fixpoint

+
(4)Δk+1 = Δk ∪ N(Δk), Δ* = Δk where Δk+1 = Δk.
+

Since A is finite and the sequence is monotone (Δ0 ⊆ Δ1 ⊆ … ⊆ A), the fixpoint exists and is reached in at most |A| steps (Kleene's theorem on a finite lattice). In practice depth 2–3 suffices.

+
+ +
+

Anchor identity #1: the impact oracle is Δ*

+

The substrate's Impact Oracle computes a file's blast radius by reverse reachability on the dependency graph — which is exactly the closure (4). The oracle adds a real-valued confidence that decays with graph distance, where the framework's N(·) is boolean; thresholding the oracle's confidence recovers N. They are the same computation. This is why the prototype achieves perfect recall on impacted files (§10): reverse reachability, run to fixpoint, cannot miss a reachable dependent.

+
+ +

3.3 The faculties as operators on the store

+ +

Each faculty is a well-typed operation on M, and each will be realized by one of the algorithms A1–A7 (§6):

+ +
Definition 4 (Faculty operators)
+
    +
  • retrieve : (x, M) → c — select the context c ⊆ M relevant to x, favouring entries whose validity has been externally confirmed (validity-anchored memory). (memory; A5)
  • +
  • impact : (Δ0, R) → Δ* — the closure (4). (impact-awareness; A1)
  • +
  • simulate : (edit, M) → predicted-effects — consequence estimation over the graph before acting. (imagination; A1)
  • +
  • verify : (y, criteria) → {pass, fail, doubts} — an external check, never the generator's self-report. (self-correction; A3, A6)
  • +
  • route : x → tier and : fact → store-home — transparent classification of effort and of knowledge placement. (M1; A7)
  • +
  • write-back : (M, outcome) → M′ — the bounded-compression checkpoint that makes learning survive P1/P2. (memory + learning; A4)
  • +
+
+ +

With the object (Def. 1), the world-model (Defs. 2–3), and the faculties (Def. 4) in hand, we can state the result the architecture rests on.

+ + +

4 The central result — the two-layer duality theorem

+ +

Everything so far has assumed that "the architecture must enforce behaviour the model cannot be relied upon to produce." We now make "cannot be relied upon" precise and derive what "enforce" must mean.

+ +
Definition 5 (The two layers)
+

A substrate's behaviour-shaping is partitioned into two layers over the frozen model:

+
    +
  • The probabilistic layer3): standing instructions loaded into context — CLAUDE.md, rules, skills, protocol cards. Let p = P(the agent performs the required behaviour on a task — e.g. the full closure Δ* — under the instruction layer alone).
  • +
  • The deterministic layer2): code executed at fixed lifecycle points independent of the model's choices — hooks that inject state, or that block a turn. A deterministic check j catches a target miss with probability cj, and for a decidable structural signal cj → 1.
  • +
+
+ +
Theorem D (Two-layer duality — neither layer alone suffices)
+

Let a task require a behaviour whose omission is a silent miss. Under the instruction layer alone the per-task silent-miss probability is 1−p; under a deterministic layer of k checks the residual silent-miss probability is

+
(5)P(silent miss) = (1−p) · ∏j=1..k (1−cj).
+

Then, for any model whose instruction-following is imperfect (p<1) and any deterministic layer that is not omniscient (cj<1 for every j):

+
    +
  1. The probabilistic layer alone cannot reach reliability. With k=0, P(silent miss)=1−p>0, and over n tasks P(≥1 miss)=1−pn → 1. No amount of instruction-writing removes the residual, because instructions are context, not enforcement.
  2. +
  3. The deterministic layer alone cannot reach reliability either. A decidable check bounds only the structural signal it was built to detect; semantic correctness is undecidable (§12), so ∏(1−cj)>0 for the semantic class. Without the instruction layer raising p, the factor (1−p) stays near 1 and the product is dominated by it.
  4. +
  5. Their composition is strictly better than either factor. Because 0<(1−p)<1 and each 0<(1−cj)<1, the product (5) is strictly smaller than (1−p) and strictly smaller than any single (1−cj). Reliability is the product of a soft factor and hard factors, and needs both kinds present.
  6. +
+

+
+ +
+Equation (5) is the probability that the behaviour is both omitted by the agent (the independent event of probability 1−p) and undetected by every one of the k checks (each failing to catch with probability 1−cj, taken as conditionally independent given the miss). Claim 1: set k=0, the empty product is 1, so P=1−p; the n-task bound is the complement of n independent successes, pn. Claim 2: for the semantic-miss class every decidable cj is bounded below 1 (Rice's theorem: non-trivial semantic properties of programs are undecidable), so the product cannot vanish; with p not raised, (1−p) is near 1. Claim 3: multiplying a number in (0,1) by further numbers in (0,1) strictly decreases it below every factor. □ +
+ +
+The two-layer duality architecture +
Figure 1. The two-layer duality. The probabilistic instruction layer (Π3, purple) raises p by loading context but may drift (dashed arrows); the deterministic interception layer (Π2, teal) executes regardless of the model's choice and either passes the turn or blocks it (exit 2) back into the model for repair. The persistent store (Π1) feeds both. What escapes both layers is the residual (1−p)·∏(1−cj), handed to review or a later commit/CI gate. The whole sits inside a stewardship boundary (amāna, §9). Neither layer alone suffices — the formal content of the discipline never trust the output; earn trust with a check.
+
+ +
+

What the theorem says in one sentence

+

The practitioner's rule — never trust the probability engine's output; verify it — is the statement (1−p)>0. Theorem D turns that intuition into a design mandate: because the soft layer can never drive (1−p) to zero, a deterministic layer must exist to multiply it down; and because the hard layer can never catch the semantic class, the soft layer must exist to shrink what reaches it. The substrate is two-layered not by taste but by theorem.

+
+ +

5 The probabilistic failure model

+ +

Theorem D's equation (5) is worth reading as an engineering instrument, because it explains a lived experience and prices every design choice.

+ +

5.1 Why "it works, then forgets" is a certainty, not bad luck

+

With the instruction layer alone, the chance of at least one partial-work incident over n tasks is 1−pn. Even an excellent p=0.9 gives 65% after 10 tasks and 96% after 30. The agent that "usually remembers the docs" is, over a project's lifetime, near-certain to forget them at least once. The failure is geometric, so no degree of prompt-polishing escapes it — only a factor (1−cj) below 1 can bend the curve.

+ +

5.2 Why the deterministic gate is worth exactly one factor

+

Add one gate whose target is the decidable signal "code changed and no doc/state artifact changed." That signal is checkable in microseconds and c1≈0.95. With p=0.7, the per-task silent-miss rate falls from 30% to (1−0.7)·(1−0.95)=1.5% — a twentyfold reduction from a twenty-line hook. Crucially the class of surviving misses changes from "forgot the docs entirely" (structural, now caught) to "updated the docs imperfectly" (semantic, handed to review). The gate does not make the model think; it removes an entire failure mode from the model's shoulders.

+ +

5.3 The lattice of gates

+

The same classifier can run at three lifecycle points, and (5) shows their catches multiply: a turn-level Stop hook a commit-level pre-commit hook a PR-level CI job. Each later gate catches what earlier ones missed — the product (5) with k=3. This is also the answer to portability: where hooks are unavailable, the same deterministic check re-binds as a pre-commit hook or a CI step, moving the enforcement point without changing the mathematics.

+ +
+

The honest cost side

+

The model also prices the developer's real pain. Each silent miss costs a rework loop of expected size (1−p)·(1+r), where r is the re-explaining overhead that session-amnesia (F2) inflates. The architecture attacks both factors: gates convert silent misses into same-session fixes (r→0, caught before the developer sees the result), and persistence makes any residual loop cheap because the context is already standing. This is where the theory meets the user's stated grievance — wasted tokens, time, and quality — and answers it with a quantity, not a promise.

+
+ + +

6 The unified algorithm set — the TASK loop

+ +

The faculties of Def. 4 are realized by seven algorithms. They are the reliability framework's A1–A7, recast here as the operations of the substrate: each is a faculty made mechanical, each binds to one lifecycle point, and together they form a single loop whose progress is guaranteed by an explicit worklist and whose floor is guaranteed by a deterministic gate.

+ +
A1 — IMPACT-CLOSURE (impact-awareness · simulate · before any code)
+
function IMPACT_CLOSURE(request):
+    Δ  ← seeds(request)                    # named files + search hits
+    W  ← Δ ; frontier ← Δ
+    while frontier ≠ ∅:                    # BFS to the fixpoint Δ* (Def. 3)
+        E ← grep_edges(I(frontier))        #   R_discovered
+            ∪ map_edges(frontier)           #   R_declared
+            ∪ interface_edges(frontier)     #   callers, overrides, migrations, DI wiring
+        new ← E \ W ;  W ← W ∪ new ;  frontier ← new
+    check_constraints(W, DECISIONS)         # flag conflicts, never override (I3)
+    return { (a, τ(a), action(a), risk(a)) : a ∈ W }   # the impact table
+

Terminates in ≤|A| rounds (Thm. T5); on termination W ⊇ Δ* over discoverable+declared edges. This is simulate and impact of Def. 4, and it is exactly what the Impact Oracle prototype computes (§10).

+
+ +
A2 — EXECUTE-FULL (world-model · act on the whole closure)
+
implement every row of the impact table (code AND tests),
+    following conventions drawn from the store M (I3);
+partial implementation of the table = definitionally incomplete (Def. Done).
+
+ +
A3 — SYNC-VERIFY (self-correction · make every artifact true again)
+
function SYNC_VERIFY(changed):
+    I ← identifiers(diff(changed))
+    for a in DocSet ∪ map_artifacts:
+        hits ← grep(a, I)
+        if hits ≠ ∅:  read(a); update stale content to match code
+        else:         record verified-unaffected(a, "no mention of I")   # checked, not assumed
+    if structure_changed: update ARCHITECTURE + diagrams + the map itself
+    if user_facing:       append CHANGELOG
+    update STATE ; return {updated[], verified_unaffected[], doubts[]}
+

The verify operator: no artifact is ever declared unaffected without the check running — invariant I1's "∨ verified-unaffected" made mechanical. The doubts[] channel enforces I3 (surface ambiguity, do not guess).

+
+ +
A4 — HANDOFF (memory · write-back · session end)
+
function HANDOFF(K):
+    ensure SYNC_VERIFY ran
+    σ ← select(K, priority=[goal, next, decisions, gotchas, in_progress, done+why])
+    write STATE ← σ,  |σ| ≤ B lines        # REWRITE (bounded), not append
+    mirror durable decisions → DECISIONS       # append-only log
+    if a convention was corrected → update CLAUDE.md / rules   (self-maintenance)
+    propose commit                              # committing = portable memory
+

The bounded-compression checkpoint (|σ|≤B≈150) keeps the loader's cost O(B) forever — the snapshot+WAL pattern: STATE is the mutable snapshot, DECISIONS the durable log.

+
+ +
A5 — REHYDRATE (memory · retrieve · session start)
+
on SessionStart(startup | resume | clear):
+    record baseline b ← git HEAD             # enables the gate's session diff (A6)
+    inject: STATE (≤8KB) + last 10 commits + uncommitted files + DoD reminder
+

The retrieve operator, made deterministic: continuity moves from "the agent may read the file" to "the context always contains it" — the same Π3→Π2 upgrade as the gate.

+
+ +
A6 — COMPLETION-GATE (self-correction · the deterministic floor · end of turn)
+
on Stop(session s):
+    C ← (diff base(s)..HEAD) ∪ worktree changes  − internal bookkeeping paths
+    code ← C ∩ CodeClass \ DocClass \ .claude/    # regex-classified
+    docs ← C ∩ DocClass
+    if code ≠ ∅ ∧ docs = ∅:  exit 2 + repair checklist + set marker   # BLOCK once
+    else:                     exit 0                                      # ALLOW
+

The hard factor c1 of Theorem D. STATE counts as a doc artifact, so the weakest way to satisfy the gate is to update session state — which is exactly the continuity invariant I2. One check enforces a floor for both F1 and F2. Full decision table and safety proofs in §7.

+
+ +
A7 — KNOWLEDGE-ROUTER (M1 routing · where every fact lives)
+
route(f):                                       # first match wins (total function, Thm. T6)
+    needed every session, stable      → CLAUDE.md            (always loaded, ≤200 lines)
+    relevant only to paths g          → .claude/rules/x  (paths: g; loads on match)
+    a procedure / workflow            → skill               (loads on invocation)
+    specialist's accumulated patterns → subagent memory
+    current work status               → STATE.md            (rewritten, injected)
+    decision + rationale              → DECISIONS.md        (append-only)
+

Keeps always-loaded context O(bounded) while total persisted knowledge grows without limit — the mathematical reason the substrate scales. This is the second face of routing: M1's complexity-router chooses a model tier by task difficulty; A7 chooses a storage home by knowledge type. Both are transparent and deterministic, and both reject an opaque-LLM classifier for the same reason — it would reintroduce the very (1−p) the hard layer exists to remove.

+
+ +

6.1 The loop

+

The seven compose into one meta-algorithm that fits every task, from a one-line fix to a multi-file feature:

+
TASK(t):  A5 rehydrate → A1 impact-closure → A2 execute → verify → A3 sync → A4 handoff → A6 gate
+

Formally, iterate until the unsynced set U = { a ∈ Δ* : ¬updated(a) ∧ ¬verified(a) } = ∅ — a fixpoint loop whose progress is guaranteed by A1's explicit worklist and whose floor is guaranteed by A6. The soft stages (A1–A5, driven by instructions) raise p; the gate (A6, deterministic) guarantees the floor; persistence (A4/A5 over Π1) carries essential(K) across the session boundary.

+ +
+The unified TASK loop +
Figure 2. The unified TASK loop. Seven stages, each bound to its faculty, its algorithm (A1–A7), and its Qur'anic anchor (§9). The loop runs to the fixpoint U=∅ at the hub — no unsynced artifact remains. Soft stages raise p; the gate is the deterministic floor; the store carries state across the boundary. Rehydrate re-arms the baseline that the gate diffs against, closing the cycle across sessions.
+
+ + +

7 The four invariants and the six correctness theorems

+ +

The TASK loop serves four invariants. Stated as logic, they port to any environment that supplies Π1–Π3.

+ + + + + + + +
InvariantStatementKills
I1 — Consistency∀(a,b)∈R: changed(b) in task t ⇒ updated(a) ∨ verified-unaffected(a) in the same t. "No artifact lies about the code."F1
I2 — ContinuityAt every session boundary: essential(K) ⊆ P, and the loader injects it. Corollary: everything essential lives in committed files — the only channel that crosses machines, terminals, web, and teammates.F2
I3 — No fabricationEvery convention the agent acts on is derived from repo evidence, or documented in P, or asked — never sampled from priors. Unattended: assumptions are stated explicitly, never silent.the amnesia root (§5)
I4 — Verified currencyFacts about the outside world (library versions, APIs) are checked against current sources at use time; the outcome is recorded. Training memory is a stale cache.stale-knowledge drift
+ +

In Hoare-triple form, every task must satisfy

+
{ P consistent ∧ context loaded } execute(t) { Done(t) ∧ P consistent ∧ σ updated }
+

where the gate (A6) checks a decidable necessary condition of the postcondition and the algorithms construct it. I3 is the invariant the user named as the deepest problem — "the biggest problem is assumption." It is the direct architectural answer to the amnesia equation of §5: an under-specified input must be met with supplied context, a stated assumption, or a halt — never a silent guess drawn from the prior.

+ +

7.1 The correctness theorems

+

Six properties are proved of the deterministic layer. They are what make the hard factor of Theorem D trustworthy — a gate that could loop, brick a session, or miss its target signal would not earn its place.

+ +
T1 (No infinite loop; any stop sequence terminates in ≤2 attempts)
+
A block sets a per-session marker before exiting 2; marker creation is monotone. Any later attempt matches the marker row ⇒ ALLOW. Independently, the continuation carries stop_hook_active ⇒ ALLOW. Two independent guards, either sufficient; even if the process dies between marker-set and exit, the marker is already on disk. □
+
+ +
T2 (Fail-open: no hook failure can brick a session)
+
Every external call is guarded (|| true, 2>/dev/null, a jq→python3→empty fallback chain); every guard-failure path leads to a row whose decision is ALLOW. The only exit-2 path is the deliberate block row. The SessionStart hook only ever exits 0. □
+
+ +
T3 (Soundness of the block signal — no false silence)
+
On the first stop of a session with usable git: C is the union of the baseline diff and an untracked-inclusive worktree scan, so every changed path is in C; classification is a total function of path; the row order reaches the block row exactly when code changed and no doc changed. Hence a silent code-only completion is impossible at the session's first completion — the agent must fix the docs or explicitly justify and update STATE, both visible to the developer. □
+
+ +
T4 (Continuity under handoff)
+
If A4 ran and its commit is pushed/pulled, then for any next session on any machine the loader injects σ at start (A5 reads the committed file), so essential(Ki) ∩ σ ⊆ Ki+1(0). Residual risk is exactly selection error in the handoff (what it chose not to write), bounded by the priority order and by DECISIONS catching the durable class. □
+
+ +
T5 (Closure termination, A1)
+
A monotone worklist on the finite set A: each round adds ≥1 artifact or stops, so ≤|A| rounds. This is the finite-lattice Kleene fixpoint of Def. 3. □
+
+ +
T6 (Router totality, A7)
+
The routing chain ends in catch-alls per scope; every fact matches ≥1 arm; first-match makes the assignment unique. Hence route is a total function — every piece of knowledge has exactly one home, which is what keeps the always-loaded budget bounded. □
+
+ +
+

How the theorems earn Theorem D

+

Theorem D says reliability needs a deterministic factor with cj→1 on its target signal. T3 is precisely that guarantee (the block fires exactly on the target signal); T1 and T2 ensure the factor is safe to add (it never loops, never bricks); T5 and T6 ensure the soft-layer machinery it composes with is well-defined (the closure terminates, the router is total); T4 extends the guarantee across the session boundary that F2 attacks. The six local proofs are what make the one global theorem deployable rather than merely true.

+
+ +

8 The crosswalk — one object, three vocabularies

+

The table below is the operational proof of the paper's claim: every concept appears in all three vocabularies, and the final column states the relationship that makes them one object. Three rows (marked ●) are not analogies but identities — the same mathematics under two names. The full machine-readable crosswalk is a companion artifact.

+

Notation reconciliation — the P1/P2/P3 collision

+

Both source frameworks independently use the labels P1/P2/P3. In the substrate paper they are model properties (P1 statelessness, P2 frozen weights, P3 bounded context, §2); in the reliability framework they are the three primitives (persistent store, lifecycle interception, instruction channel). This paper keeps P1–P3 for the model properties and renames the primitives Π123 throughout (§3.1). Every reference to a primitive in this paper is written Πn.

+ + + + + + + + + + + + + + + + + + +
#Unified conceptSubstrate (S)E2E Framework (E)forgekit (K)Relationship
1The frozen corey = f_theta(x): stateless map, fixed weights, bounded context (properties P1,P2,P3)the agent/model whose behavior instructions can only raise the PROBABILITY of (p<1)Claude / Codex / Cursor / Gemini / Aider — the model the kit wraps, never modifiesidentical object: all three treat the model as a fixed probabilistic map to be wrapped, not retrained
2Impact-awareness / partial-work failureFaculty: impact-awareness gap; the developer silently simulates 'what will this edit break'. Prototype I = Impact Oracle (reverse-dependency blast radius with confidence decay)F1 partial work; dependents operator N(X); required change closure Delta* = least fixpoint of X |-> X ∪ N(X); Done predicate; Algorithm A1 IMPACT-CLOSURE/impact skill; documentation-map.md (R_declared); grep identifier sweep (R_discovered)IDENTICAL MATHEMATICS. The Impact Oracle computes N(X) by reverse reachability on the dependency graph; Delta* is exactly the oracle's transitive blast-radius set. The oracle adds a confidence-decay weight the framework's set-theoretic N(X) leaves boolean.
3Memory / session-amnesia failureFaculty: persistent memory gap; each context window is ephemeral. Validity-anchored memory (facts carry confirmed/discredited state updated by verified outcomes)F2 session amnesia; continuity invariant I2 (essential(K_i) ⊆ P and loader L must load it); handoff operator H; K_{i+1}(0)=L(P)docs/STATE.md (bounded snapshot) + docs/DECISIONS.md (append-only log); /handoff writes it; SessionStart hook injects itSame failure, same fix (external bounded-compression checkpoint). Substrate adds validity-anchoring (prune by whether a past prediction was externally confirmed); framework adds the snapshot+WAL split (STATE mutable vs DECISIONS append-only).
4Why assumptions happen (the root the user named)M2 assumption/uncertainty gate: under-specified input -> the model confabulates a conventionamnesia equation: when f ∈ essential(K) is missing from L(P), assumption ≈ argmax P(convention | training data) — the mathematically EXPECTED result of missing context, not misbehavior. Invariant I3 (no fabrication)CLAUDE.md No-assumptions rule; intent-router SPEC card ('state assumptions explicitly')The framework gives the substrate's M2 gate its formal justification: assumption is argmax over the prior, so the fix is to supply context (raise what L loads) OR gate on missing context (halt), never to hope.
5Self-correction / verificationM6 inline verification; Prototype-II verify step; self-correction facultyAlgorithm A6 COMPLETION-GATE (deterministic Stop-hook floor); Hoare postcondition Done(t); the verification operator in A3 (verified-unaffected requires an actual grep, not an assumption)docs-guard.sh Stop hook (blocks finish if code changed but no doc/state artifact did); reviewer agent verdictSame verify-gate. Substrate framed it as a mechanism; framework proves it terminates (T1) and is sound (T3) and makes it the deterministic layer of the duality.
6Complexity routingM1 complexity-aware router (transparent additive rubric); Prototype-II routerAlgorithm A7 KNOWLEDGE-ROUTER (where every fact lives, keeps always-loaded context bounded); System 1/System 2 effort routing; intent DFAintent-router.sh (UserPromptSubmit hook, keyword DFA, <10ms, zero-token); effort-routing rule in CLAUDE.md; per-agent model: fieldsTwo facets of one routing principle. Substrate M1 routes by TASK COMPLEXITY -> model tier (cost). Framework A7 routes by KNOWLEDGE TYPE -> storage home (context budget). Both are transparent/deterministic, both reject an opaque-LLM classifier for the same reason.
7Task decompositionM3 task/session decompositionHTN closure -> ordered task list (A1 output is the worklist); the meta-algorithm TASK(t)sdlc-pilot 7-phase skill; subagents; git worktreesSame: decompose the goal into the closure's ordered worklist before building.
8Goal-anchoringM4 goal-anchoring (goal drift: to a text model a long story and long code are the same object)BDI Desires = written goal + acceptance criteria in STATE.md; I2 keeps them across sessions; acceptance criteria written at SPEC, consumed at VERIFYdocs/STATE.md 'Current goal' + 'Acceptance criteria'; sdlc-pilot SPEC->VERIFY gateSubstrate names the drift; framework anchors it in a persisted, re-injected Desire so every session optimizes the same target.
9Anti-over-engineeringM5 anti-over-engineering (scope minimality; the residual whitespace)amana / scope-boundedness (agent may not exceed asked scope); I3 (no invented structure)CLAUDE.md effort routing 'trivial -> do it directly, no ceremony'; least-privilege defaultsWeakest-covered in all three; substrate marks it residual-gap, framework encodes it as a stewardship bound, kit as an effort-routing default.
10World-model of the codebaseFaculty: world-model; Prototype-I codebase world-model (AST -> persistent dependency graph)the typed artifact graph (A, tau, R = R_declared ∪ R_discovered)documentation-map.md + the repo itself + ARCHITECTURE.mdSame graph. Substrate builds it from AST for code; framework generalizes the node type to {code,test,doc,config,diagram} so DOCS become first-class dependents — the key generalization that turns 'impact on code' into 'impact on all artifacts'.
11Continual learning from outcomesFaculty: learning without touching theta (non-parametric always-on + parametric LoRA/EWC)Reflexion loop made cross-session (I3/I4); DECISIONS.md as precedent DB; A4 mirrors durable lessonsReflexion rule in CLAUDE.md; STATE gotchas; agents' memory: projectSame 'learn without retraining' stance. Both store verbal lessons externally and re-inject; substrate adds the parametric option, framework keeps it purely non-parametric (committed files).
12Rehydration (session start)closed-loop write-back/read-back band in the substrate architectureAlgorithm A5 CONTEXT-REHYDRATE; loader L; records git baseline for the gatesession-context.sh SessionStart hook; /catchup skill (deep variant)The read side of the substrate's memory loop, made deterministic (inject, don't hope the agent reads).
13Independent verification / judgeself-correction faculty; the honest-negative-result caution (models correct poorly alone)LLM-as-Judge applied: reviewer agent (fresh context, explicit criteria, adversarial); self-consistency for critical changes (majority of N)reviewer.md agent; DoD item 7Substrate cited the finding that self-correction alone is weak; framework operationalizes the fix (an EXTERNAL judge), which is the same 'trust only an external check' principle as the gate.
14The two-layer duality (THE central new insight)implicit: the substrate wraps a probabilistic core with deterministic external structure, but v2 never states it as a lawDESIGN LAW: instructions (Pi3) are PROBABILISTIC (raise p); interception (Pi2) is DETERMINISTIC (guarantee a floor c->1). P(silent miss) = (1-p)·prod_j(1-c_j). Since p<1 always, neither layer alone suffices.the split itself: CLAUDE.md/rules/skills = soft layer; hooks (docs-guard, session-context, intent-router) = hard layerTHIS is what the kit gives the substrate theory: the reason the substrate must be TWO layers, stated as a theorem. The user's own discipline ('never trust AI output — it is calculated probability') is exactly (1-p)>0, which forces the deterministic layer.
15The probabilistic failure modeleval honesty: perfect accuracy shows separation not a benchmark; p<1P(>=1 miss) = 1 - p^n over n tasks (0.9 -> 65% at 10, 96% at 30); layered: P(silent miss)=(1-p)·prod(1-c_j)the lattice of gates: turn-level (hook) ⊂ commit-level (pre-commit) ⊂ PR-level (CI)The math that makes 'it works sometimes then forgets' a geometric certainty rather than bad luck — and quantifies why each added deterministic gate multiplies down the residual.
16Stewardship / governance boundarySTEWARDSHIP/amana wrapper (33:72) around the whole architectureamana in I3/I4 as no-fabrication + verified-currency; least privilege, reversibility, logged rationale, scope-boundednesscommitted-files-only (auditable), block-at-most-once (no nagging), fail-open safety (T2), DOCS_GUARD_DISABLE auditable escape hatchThe ethical frame the substrate draws from the lens is realized as concrete safety properties in the framework (fail-open, reversibility) and kit (auditable hooks).
+

The three anchor identities

    +
  1. Impact-Oracle blast-radius ≡ change-closure Δ*. Reverse reachability on the dependency graph is the least fixpoint of X ↦ X ∪ N(X). The oracle weights it with confidence decay; the framework’s N(·) is its boolean core.
  2. +
  3. M2 assumption gate ≡ the amnesia equation. assumption ≈ argmax P(convention | training) is why an under-specified prompt is answered with a confabulated convention — so the gate supplies the missing context or halts; it never hopes.
  4. +
  5. The substrate’s two layers ≡ the design law. Instructions raise p<1; interception guarantees a floor c→1. Theorem D. This is the formal statement of the governing discipline.
  6. +
+

9 The Qur’anic epistemology — the full fourteen mappings

+
+

How the lens is used, and how it is not

+

The Qur’an is used here as a framing lens and ethics source, never as technical authority for an engineering claim. No verse proves that an algorithm works or a data structure is correct — those stand or fall on their engineering merits alone (§4–§7). What the lens supplies is (1) a vocabulary for the agent’s epistemic obligations — what it owes to truthfulness, verification, and stewardship; (2) a hierarchy of knowledge (‘ilm → fahm → ḥikma) that motivates a layered memory rather than a flat store; and (3) ethical constraints on autonomy (amāna, tabayyun) that translate into concrete safeguards. A mapping marked load-bearing directly motivates a specific architectural decision — e.g. a mandatory gate, not an optional one; a mapping marked metaphor is illustrative. Even load-bearing mappings must be independently defensible: the verse explains why we insist, not that it works.

+

All Arabic is the clean Uthmani-script edition and all translations are Abdel Haleem, retrieved verbatim via the quran.ai connector; tafsir references are Ibn Kathir. No Qur’anic text is reproduced from model memory.

+
+

The fourteen mappings are the epistemology behind the architecture: each names an obligation that a probabilistic engine, left alone, will not honour, and which the deterministic layer therefore exists to enforce. Twelve are load-bearing; two are metaphor. They are grouped by the faculty they govern.

+

9.1 Impact-awareness — know before you act

+
+
Q 17:36 — lā taqfu mā laysa laka bihi ‘ilm load-bearing
+
وَلَا تَقْفُ مَا لَيْسَ لَكَ بِهِ عِلْمٌ ۚ إِنَّ السَّمْعَ وَالْبَصَرَ وَالْفُؤَادَ كُلُّ أُولَٰئِكَ كَانَ عَنْهُ مَسْئُولًا
+
“Do not follow blindly what you do not know to be true: ears, eyes, and heart, you will be questioned about all these.”
+
Before any mutation, the agent must run a pre-action check of what will be affected, whether it has sufficient context, and whether the predicted outcome is evidence-supported rather than pattern-matched. This is anchor identity #1: the impact closure Δ* (A1) computed before coding. Ibn Kathir glosses the verse (via Qatadah) as a prohibition on claiming knowledge one lacks — for the agent: do not call a file safe to modify without reading it, nor a test passing without running it. The verse’s ‘ears, eyes, and heart … questioned’ maps to the audit trail: every channel used is logged so the decision can be reconstructed.
+
+

9.2 Self-correction — verify, reflect, iterate

+
+
Q 49:6 — fa-tabayyanū (the verification gate) load-bearing
+
يَا أَيُّهَا الَّذِينَ آمَنُوا إِن جَاءَكُمْ فَاسِقٌ بِنَبَإٍ فَتَبَيَّنُوا أَن تُصِيبُوا قَوْمًا بِجَهَالَةٍ فَتُصْبِحُوا عَلَىٰ مَا فَعَلْتُمْ نَادِمِينَ
+
“Believers, if a troublemaker brings you news, check it first, in case you wrong others unwittingly and later regret what you have done,”
+
The operative term tabayyun demands active investigation, not passive acceptance — a mandatory step between receiving information and acting. This is the completion gate A6 and the external verifier of Def. 4: before applying a fix based on an error report, a request, or its own diagnosis, the agent re-reads the file and re-confirms the error. The gate is architectural (a deterministic pipeline step), not advisory — the verse’s command is categorical, exactly the hard factor c→1 of Theorem D.
+
+
+
Q 4:82 — tadabbur (self-consistency) load-bearing
+
أَفَلَا يَتَدَبَّرُونَ الْقُرْآنَ ۚ وَلَوْ كَانَ مِنْ عِندِ غَيْرِ اللَّهِ لَوَجَدُوا فِيهِ اخْتِلَافًا كَثِيرًا
+
“Will they not think about this Quran? If it had been from anyone other than God, they would have found much inconsistency in it.”
+
‘They would have found much inconsistency’ makes internal contradiction evidence of flawed origin — the argument behind self-consistency checking (SYNC-VERIFY’s doubts[] channel, and the majority-of-N escalation of the reviewer). If a planned change contradicts the agent’s stated reasoning or the tests it just read, the metacognitive pass flags it and halts.
+
+
+
Q 47:24 — tadabbur (‘locks on hearts’) metaphor
+
أَفَلَا يَتَدَبَّرُونَ الْقُرْآنَ أَمْ عَلَىٰ قُلُوبٍ أَقْفَالُهَا
+
“Will they not contemplate the Quran? Do they have locks on their hearts?”
+
The ‘locks on hearts’ image maps to a real failure mode: when context saturates, the agent becomes functionally unable to reconsider. The metacognitive controller must be able to reset the working context and re-examine from a fresh framing — structured backtracking, the fresh-context reviewer that never inherits the builder’s narrative.
+
+

9.3 World-model — know what already exists

+
+
Q 2:31–32 — ta‘līm al-asmā’ load-bearing
+
وَعَلَّمَ آدَمَ الْأَسْمَاءَ كُلَّهَا ثُمَّ عَرَضَهُمْ عَلَى الْمَلَائِكَةِ فَقَالَ أَنبِئُونِي بِأَسْمَاءِ هَٰؤُلَاءِ إِن كُنتُمْ صَادِقِينَ ﴿٣١﴾ +قَالُوا سُبْحَانَكَ لَا عِلْمَ لَنَا إِلَّا مَا عَلَّمْتَنَا ۖ إِنَّكَ أَنتَ الْعَلِيمُ الْحَكِيمُ ﴿٣٢﴾
+
“(2:31) He taught Adam all the names [of things], then He showed them to the angels and said, ‘Tell me the names of these if you truly [think you can].’ (2:32) They said, ‘May You be glorified! We have knowledge only of what You have taught us. You are the All Knowing and All Wise.’”
+
‘He taught Adam all the names’ — knowledge begins with naming entities and their relations. This is the typed artifact graph (Defs. 2–3): not a flat file listing but a semantic map of which function calls which, which test covers which class. The angels’ ‘we have knowledge only of what You have taught us’ is precisely the model’s situation — it knows only its context window; the external world-model supplies the names of entities that exceed it.
+
+

9.4 Continual learning — knowledge as ongoing increase

+
+
Q 20:114 — rabbi zidnī ‘ilmā load-bearing
+
فَتَعَالَى اللَّهُ الْمَلِكُ الْحَقُّ ۗ وَلَا تَعْجَلْ بِالْقُرْآنِ مِن قَبْلِ أَن يُقْضَىٰ إِلَيْكَ وَحْيُهُ ۖ وَقُل رَّبِّ زِدْنِي عِلْمًا
+
“exalted be God, the one who is truly in control. [Prophet], do not rush to recite before the revelation is fully complete but say, ‘Lord, increase me in knowledge!’”
+
‘Do not rush … but say, increase me in knowledge’ — two mechanisms at once. The prohibition on rushing before revelation is complete is the halt-on-incomplete-context rule (I3). The prayer for increase is the cross-session experience store that grows priors without touching θ (P2): learning is external memory that changes what the agent sees next, not a weight update.
+
+
+
Q 39:9 — hal yastawī metaphor
+
أَمَّنْ هُوَ قَانِتٌ آنَاءَ اللَّيْلِ سَاجِدًا وَقَائِمًا يَحْذَرُ الْآخِرَةَ وَيَرْجُو رَحْمَةَ رَبِّهِ ۗ قُلْ هَلْ يَسْتَوِي الَّذِينَ يَعْلَمُونَ وَالَّذِينَ لَا يَعْلَمُونَ ۗ إِنَّمَا يَتَذَكَّرُ أُولُو الْأَلْبَابِ
+
“What about someone who worships devoutly during the night, bowing down, standing in prayer, ever mindful of the life to come, hoping for his Lord’s mercy? Say, ‘How can those who know be equal to those who do not know?’ Only those who have understanding will take heed.”
+
‘How can those who know be equal to those who do not?’ establishes that knowledge is not fungible with ignorance — motivating the architecture’s distinction between grounded mode (relevant prior experience loaded) and ungrounded mode (base model alone), and surfacing that distinction to the user rather than hiding it.
+
+

9.5 Persistent memory — externalize to endure

+
+
Q 96:1–5 — iqra’ / ‘allama bi-l-qalam load-bearing
+
اقْرَأْ بِاسْمِ رَبِّكَ الَّذِي خَلَقَ ﴿١﴾ +خَلَقَ الْإِنسَانَ مِنْ عَلَقٍ ﴿٢﴾ +اقْرَأْ وَرَبُّكَ الْأَكْرَمُ ﴿٣﴾ +الَّذِي عَلَّمَ بِالْقَلَمِ ﴿٤﴾ +عَلَّمَ الْإِنسَانَ مَا لَمْ يَعْلَمْ ﴿٥﴾
+
“(96:1) Read! In the name of your Lord who created: (96:2) He created man from a clinging form. (96:3) Read! Your Lord is the Most Bountiful One (96:4) who taught by [means of] the pen, (96:5) who taught man what he did not know.”
+
‘Who taught by the pen’ — al-qalam is the instrument of externalization, turning ephemeral thought into durable record. Every context window is ephemeral (unwritten thought), so the persistent store (Π1) is ‘the pen’: write-back (A4) captures what is learned, retrieval (A5) reloads it next session, consolidation organizes raw experience into structured knowledge. ‘Taught man what he did not know’ — the pen does not merely record; it grants access beyond unaided capacity.
+
+

9.6 Stewardship — the weight of the trust

+
+
Q 33:72 — al-amāna (the Trust) load-bearing
+
إِنَّا عَرَضْنَا الْأَمَانَةَ عَلَى السَّمَاوَاتِ وَالْأَرْضِ وَالْجِبَالِ فَأَبَيْنَ أَن يَحْمِلْنَهَا وَأَشْفَقْنَ مِنْهَا وَحَمَلَهَا الْإِنسَانُ ۖ إِنَّهُ كَانَ ظَلُومًا جَهُولًا
+
“We offered the Trust to the heavens, the earth, and the mountains, yet they refused to undertake it and were afraid of it; mankind undertook it- they have always been inept and foolish.”
+
An agent that can modify a codebase bears a trust. The verse’s structure is decisive: the heavens refused the trust, recognizing its weight; the human bore it and was called ẓalūman jahūlā (given to wrongdoing and ignorance). The design is therefore dual: (a) the agent operates within explicit authorization — it may not exceed asked scope (M5, anti-over-engineering); (b) the architecture assumes the agent will err and builds in rollback, sandboxing, and incremental commit as structural safeguards. Ibn Kathir’s gloss (Ibn Abbās) ties amāna to accountability — outcome-linked feedback: actions must be traceable to outcomes, and outcomes feed the learning store. This is the governance boundary around Figures 1 and 2, realized concretely as fail-open safety (T2), reversibility, and auditable hooks.
+
+

9.7 The four governing concepts

+

Beyond the verses, four Qur’anic concepts structure the whole architecture, each load-bearing:

+
    +
  • ‘ilm → fahm → ḥikma (knowledge → understanding → wisdom) — the epistemological hierarchy that mandates a layered memory: raw logs (‘ilm) at the base, a consolidation pass extracting patterns (fahm), a decision-support layer applying them (ḥikma). Dumping everything into one flat vector store collapses the hierarchy — this is the architectural argument for STATE vs DECISIONS vs ARCHITECTURE as distinct stores with distinct update rules, not one file.
  • +
  • ḥifẓ + murāja‘a (preservation + spaced review) — memory is not write-once: a maintenance cycle reinforces recurring patterns, decays stale entries, and resolves contradictions. This is the memory-scoring rule (importance × recency-decay) and the validity-anchoring of Def. 4.
  • +
  • tabayyun (verification before action) — the categorical gate of §9.2, the hard factor of Theorem D.
  • +
  • tadabbur (structured reflection on consequences; root d-b-r, ‘what follows’) — the metacognitive controller as a trace-forward through the dependency graph: what comes after this change, what breaks, what it assumes. This is A1’s consequence simulation, not a vague ‘think again’.
  • +
+
+

The lens in one line

+

Every faculty the model lacks corresponds to an obligation the tradition names: lā taqfu (do not act without knowledge) → impact-closure; tabayyun (verify the report) → the gate; ta‘līm al-asmā’ (know the names) → the world-model; al-qalam (the pen) → persistent memory; rabbi zidnī ‘ilmā (increase me in knowledge) → continual learning; al-amāna (the trust) → the stewardship boundary. The engineering says how; the lens says why it is owed.

+
+ +

10 The prototypes — what measurement did to the theory

+ +
+

This section reports a refutation of the claims made in earlier editions of this work

+

Earlier editions reported that the impact oracle achieved perfect recall (R = 1.00) +and that the router/gate pair achieved a perfect separation with a 62.1% cost saving. Both results came +from self-built demonstration sets. Under a protocol frozen before data collection and run against nine +real open-source repositories and eighty real issues, both claims failed. They are +retained here, corrected, because the failure is the most useful thing this work produced.

+
+ +

10.1 Prototype I — the impact oracle, refuted and repaired

+ +

Ground truth was mined from real commit history: two files are impact-related if they changed in the +same non-merge commit, under filters fixed in advance. Against 801 labelled files in nine repositories:

+ + + + + +
MethodPrecisionRecallF1
Impact oracle, as shipped0.3980.0220.042
grep baseline (no graph)0.3530.5730.437
+ +

Recall was 0.022, not 1.00 — a gap of roughly +45×. Ninety-one percent of files received exactly zero recall, and a textual baseline with no +dependency graph at all outperformed the graph-based oracle by an order of magnitude on F1.

+ +
+

What this does to Theorem T5 — the correction that matters

+

Earlier editions argued that perfect recall follows from T5: a reverse-reachability closure run +to fixpoint cannot miss a reachable dependent. The theorem is not wrong; the inference from it was. T5 +guarantees completeness relative to the relation R over which the closure +is computed. It says nothing about whether R contains the edges that matter, nor +whether the graph was built correctly. Both failed here. Classifying all 18,221 false negatives showed +94.7% were sibling pairs — two files sharing a dependency, reachable only by a mixed +forward-then-reverse path that a reverse-only traversal cannot take — and a construction defect +silently produced phantom nodes for one of the two standard Python package layouts. Only 3.2% were beyond +any static path.

+

The general lesson for the formalism: a completeness theorem over a relation transfers no +guarantee to practice until the relation is shown to be adequate and its construction is verified. +Def. 3's Δ* is sound; the deployed R was not +the R the theory assumed.

+
+ +

Because 96.8% of the missed impact was diagnosed as reachable in principle, we repaired both defects and +re-ran the same frozen protocol, with parameters fixed on six repositories and frozen before three held-out +repositories were touched:

+ + + + + + + +
ConfigurationPrecisionRecallF1
As shipped0.3980.0220.042
+ construction fix0.3040.2420.270
+ sibling/forward relations, held-out0.3050.6530.416
grep baseline, held-out0.2690.6010.371
+ +

The repaired oracle beats the baseline for the first time, reaching 66.8% of the achievable ceiling. The +margin is narrow and the intervals are close. Two details are worth more than the headline. First, the +obvious repair of the construction defect is unsafe — it fabricates dependency edges through +standard-library name collisions — so we applied a more conservative fix with a smaller gain +(11.0× rather than 14.5×); a tool that invents edges to raise recall is worse than one that misses +them. Second, because the tuning/held-out split was declared in advance, we could see that precision +generalised far worse than recall (−0.141 against −0.021). Tuning on all nine repositories would +have produced a better number and concealed that fact.

+ +
+Repair sequence +
Figure 3. The repair sequence with 95% bootstrap confidence intervals, against +the grep baseline (diamonds) and the static ceiling. Both fixes are necessary; neither alone crosses the +baseline.
+
+ +

10.2 Prototype II — the router and gate, refuted

+ +

Re-evaluated on eighty tasks drawn from real GitHub issues and pull requests, with every threshold frozen +at its tuned value:

+ + + + + + + + + + + +
MetricTuned set (n=30)Held-out (n=80)
Gate F1 (should-ask)1.000.37
Gate recall1.000.31
Routing, exact tier1.000.53
Routing, within one tier1.000.91
Cost saving — first attempt, ungated62.1%59.5%
Cost saving — first attempt, correctness-gated3.6%
Cost saving — total pipeline spend, ungated−20.2%
Cost saving — total pipeline spend, gated2.8%
+ +

The gate missed roughly seven in ten under-specified requests. Routing retained partial signal — +within-one-tier accuracy of 0.91 is well above chance, so the complexity rubric measures something +— but exact-tier accuracy fell to 0.53, and the cost saving did not merely shrink but inverted: routing does save 59.5% in raw dollars on first attempts alone, but almost none of that cheaper output is correct (3.6% once gated), and counting what the pipeline actually spent escalating up the tier ladder, it costs 20.2% more than always using the premium tier. Labelling noise is real and reported rather than hidden: inter-rater agreement on the +should-ask label was κ = 0.52, moderate, which bounds how well any gate could score here.

+ +
+

What the earlier numbers actually measured

+

Nothing about the demonstrations was fabricated; every number in the earlier editions was real. They +measured the wrong thing. A rubric scored against the thirty tasks its thresholds were tuned on reports the +fit, not the capability, and a blast radius measured against mutations of a package the authors wrote +reports the authors' model of impact, not the codebase's. The mechanism was never the weak link in the +evidence; the evidence standard was.

+
+

11 forgekit — the deployed binding

+

The theory is implementation-independent; forgekit is one binding of it, and its precursor claude-e2e-kit is the reference realization on Claude Code. The mapping is exact:

+ + + + + + + + + + +
Framework objectforgekit / claude-e2e-kitFaculty / algorithm
Π1 persistent storeCLAUDE.md, docs/STATE.md, docs/DECISIONS.md, docs/ARCHITECTURE.mdmemory
Π2 interceptionsession-context.sh (SessionStart), docs-guard.sh (Stop), intent-router.sh (UserPromptSubmit)A5, A6, routing
Π3 instructionsCLAUDE.md DoD + No-assumptions + Reflexion + effort-routing; .claude/rules/I1–I4, M1–M6
Δ* construction (A1)/impact skill + documentation-map.mdimpact-awareness
Verify operator (A3)/sync-docs + doc-sync agent (project memory)self-correction
Handoff (A4) / rehydrate (A5)/handoff → STATE; SessionStart injection + /catchupmemory
Independent judgereviewer agent (fresh context, adversarial, criteria-based)self-correction
Phase gatessdlc-pilot 7-phase skill (SPEC…MAINTAIN)decomposition, goal-anchoring
+

The kit grounds its mechanisms in the same literature the substrate's faculties cite — CoALA's four memories, MemGPT's paging, Generative Agents' recency×importance scoring, Reflexion's verbal reinforcement, ReAct's reason–act interleaving, LLM-as-Judge's independent evaluator, AlphaCodium's phase-gated flow, Voyager's growing skill library, and the classical decision loops (BDI, OODA/PDCA, HTN). It is the same architecture, cited from the same shelf, and shipped. The two prototypes of §10 slot in as the mechanical cores of /impact and the effort-router.

+ +
+

Why one binding matters for the theory

+

That an independent team, starting from production failures rather than from cognitive faculties, built the same seven algorithms and stated the same design law is the strongest available evidence that the architecture is discovered, not invented — a convergent solution to a structural problem, the way distributed systems converge on snapshot+WAL. The synthesis does not merge two guesses; it records a convergence.

+
+ +

12 Honest limits — what no architecture can guarantee

+
    +
  • Semantic correctness is undecidable. The gate proves "a doc artifact changed", not "the docs are now true"; A3's grep proves "mentions were visited", not "the prose is accurate". By Rice's theorem the last layer is unavoidable — tests for behaviour, human review for meaning. The architecture's job is to make that review cheap: everything arrives already-attempted, with an updated / verified / doubts report.
  • +
  • The soft layer's p is real but bounded. Theorem D quantifies the residual; it does not abolish it. A determined agent can satisfy the letter of a gate (touch STATE with one line) without its spirit — which is why no single layer is trusted, by design.
  • +
  • Rdiscovered misses unnamed coupling. A doc that describes behaviour without naming any identifier has no grep edge; such couplings must be lifted into Rdeclared (the documentation map) — exactly what that table is for.
  • +
  • One prototype is not five faculties. The substrate prototypes instantiate impact-awareness and routing/gating well; memory, learning, and imagination remain the harder research frontier, and the honest ecosystem map marks the assumption gate (M2) and outcome-based learning as genuine whitespace the current stack does not fill.
  • +
  • The lens is framing, not proof. Every Qur'anic mapping motivates a design choice; none of them validate one. The engineering in §4–§7 stands on its own or not at all — the tradition tells us why a safeguard is owed, never that it works.
  • +
+ +

13 Conclusion

+

A language model that writes code is a fixed probabilistic map, and three independent efforts — one from cognition, one from production failures, one from a shipped codebase — converged on the same remedy: wrap it in an external, stateful architecture that supplies the faculties it structurally lacks. This paper showed they describe one object. The impact-awareness faculty is the change-closure fixpoint; the assumption gate is the amnesia equation; and both rest on a single theorem — reliability is the product of a probabilistic instruction layer that raises p<1 and a deterministic interception layer that guarantees a floor, with neither alone sufficient.

+
+

The limit this edition discovered the hard way

+

The honest limits listed below were all stated before any real-repository measurement existed. One more +belongs at their head, and it subsumes several: a self-built demonstration can overstate a +mechanism's field performance by more than an order of magnitude, and no amount of careful caveating of a +demonstration converts it into evidence. Both prototypes here were labelled honestly as +demonstrations, with their tuning disclosed. That disclosure was accurate and it was insufficient — +readers, including their authors, carried the numbers forward as if they bounded real behaviour. The +remedy is not better hedging but a different evidence standard: ground truth the authors did not construct, +a protocol frozen before the data is seen, and a split declared before any parameter is fitted.

+
+ +

That theorem is the formal content of a plain discipline: the output of a probability engine is never to be trusted on its own; trust is earned by an external check. The Qur'anic lens gives that discipline its oldest names — lā taqfu, do not pursue what you do not know; tabayyun, verify the report before you act; al-amāna, the weight of a trust accepted by one who may err. The mathematics says how to build the check. The tradition says why it is owed. The codebase shows it runs.

+

Companion artifacts: the three-way crosswalk (JSON + markdown), the graded reference set (Appendix A), and two runnable prototype packages (impact-oracle, router-gate). This synthesis consolidates and does not supersede the v2 Theory → Evidence → Build-Map edition, which carries the empirical evidence layer and the full ecosystem map.

+ +

Appendix A — Graded reference set (new sources)

+

The synthesis draws in a body of cognitive-architecture and process literature beyond the substrate paper's original 32 references. Each new source was independently verified this pass — modern arXiv sources by direct metadata fetch, classical works by primary-host search or established secondary knowledge — and graded: confirmed (record retrieved, attribution matches), traceable (the work clearly exists and is correctly attributed, but rests on established secondary knowledge rather than a single retrievable record), unverifiable (could not confirm). The tally: 8 confirmed, 6 traceable, 0 unverifiable.

+ + + + + + + + + + + + + + + + + +
SourceIDGradeNote
Cognitive Architectures for Language Agents
Theodore R. Sumers, Shunyu Yao, Karthik Narasi, 2023
2309.02427confirmedRetrieved via arXiv metadata API; title/authors match claim exactly. Unifies memory, planning/reasoning, action, and learning modules into a single CoALA framework for language agents, giving the cognitive-substrate work's memory/im…
ReAct: Synergizing Reasoning and Acting in Language
Shunyu Yao, Jeffrey Zhao, Dian Yu et al., 2022
2210.03629confirmedRetrieved via arXiv metadata API; title/authors match claim exactly. Interleaves reasoning traces with actions in a single LLM prompt loop, the foundational pattern the cognitive-substrate and reliability-framework agent loops build on.
A Survey on LLM-as-a-Judge
Jiawei Gu, Xuhui Jiang, Zhichao Shi et al., 2024
2411.15594confirmedRetrieved via arXiv metadata API; title/authors match claim exactly. Surveys the emerging practice of using LLMs themselves as evaluators/judges, directly relevant to any impact-awareness or self-correction mechanism that relies on an LL…
Code Generation with AlphaCodium: From Prompt Engine
Tal Ridnik, Dedy Kredo, Itamar Friedman, 2024
2401.08500confirmedRetrieved via arXiv metadata API; title/authors match claim exactly. Replaces single-shot prompting with an iterative 'flow engineering' test-generate-fix loop for code generation, an applied precedent for the reliability frame…
SWE-agent: Agent-Computer Interfaces Enable Automate
John Yang, Carlos E. Jimenez, Alexander Wettig, 2024
2405.15793confirmedRetrieved via arXiv metadata API; title/authors match claim exactly. Introduces an agent-computer interface (a constrained action/observation space) purpose-built for LM agents doing software engineering, directly relevant to forgekit&#x…
Voyager: An Open-Ended Embodied Agent with Large Lan
Guanzhi Wang, Yuqi Xie, Yunfan Jiang et al., 2023
2305.16291confirmedRetrieved via arXiv metadata API; title/authors match claim exactly. Demonstrates a lifelong-learning embodied agent that maintains and grows a skill library over time, the clearest existing analogue to persistent, growing external memor…
Agentic AI in the Software Development Lifecycle: Ar
Happy Bhati, 2026
2604.26275confirmedRetrieved via arXiv metadata API; the ID resolves to a REAL paper dated 2026-04-29 (April 2026, which is in the past relative to today, 2026-07-11 — so 'future-dated' only relative to the cited work's original claim date, …
Agent-as-a-Judge
Runyang You, Hongru Cai, Caiqi Zhang et al., 2026
2601.05111confirmedRetrieved via arXiv metadata API; ID resolves to a REAL paper dated 2026-01-08. Title is exactly 'Agent-as-a-Judge' and abstract frames it as 'the first comprehensive survey' of the Agent-as-a-Judge paradigm, matching…
Agent-as-a-Judge: Evaluate Agents with Agents
Zhuge, Zhao, Ashley, Wang, Khizbullin, Xiong, , 2024
2410.10934confirmedThe founding Agent-as-a-Judge paper that coined the term; added on the verification track's explicit recommendation to disambiguate from the 2026 survey (2601.05111).
HTN Planning: Complexity and Expressivity
Erol, Hendler, Nau, 1994
traceableClassical AI-planning paper, no arXiv/OpenAlex record. Verified via live web_search (this turn) against AAAI's own paper page, Semantic Scholar, and a downstream paper's reference list (arXiv:1403.7426, 'An Overview of Hie…
BDI Agents: From Theory to Practice
Rao, Georgeff, 1995
traceableClassical agent-architecture paper, no DOI/arXiv record. Verified via live web_search (this turn) against the AAAI-hosted PDF (cdn.aaai.org/ICMAS/1995/ICMAS95-042.pdf), gabormelli.com/RKB, and multiple independent downstream reference li…
Thinking, Fast and Slow
Kahneman, D., 2011
traceableClassical trade/academic book, not indexed on arXiv or as a journal article with a DOI in the usual sense; existence and content (System 1 / System 2 dual-process framing) are well-established general knowledge, not independently re-veri…
Über das Gedächtnis: Untersuchungen zur experimentel
Ebbinghaus, H., 1885
traceableFoundational 1885 monograph establishing the forgetting curve; predates modern indexing entirely, existence is well-established historical/secondary knowledge, not independently re-verified against a bibliographic API in this pass.
OODA Loop (Observe-Orient-Decide-Act)
Boyd, J.R., None
traceableNo formal published paper exists — Boyd never formally published the OODA loop in a journal; it survives via briefing-slide decks and secondary military-strategy literature. Rubric correctly flags this as having 'no formal paper.&#x…
PDCA / Plan-Do-Check-Act cycle (the 'Shewhart Cycle'
Shewhart, W.A. (originator); Deming, W.E. (pop, None
traceableManagement/quality-control doctrine spanning multiple books across decades, not a single citable paper. Existence and attribution (Shewhart origin, Deming popularization) are well-established secondary knowledge, not independently re-ver…
+
+

The two future-dated identifiers — verified, not assumed

+

Two IDs in the source material are dated 2026. Both resolve to real preprints whose content matches the claim, confirmed by direct arXiv fetch rather than by topic plausibility. arXiv:2604.26275 ("Agentic SDLC", Apr 2026) is a genuine but single-author, non-peer-reviewed preprint — cited as a recent preprint claim, not an established result. arXiv:2601.05111 ("Agent-as-a-Judge", Jan 2026) is a real survey, but is a different paper from the founding work that coined the term — Zhuge et al. 2024 (arXiv:2410.10934), which is the reference this paper uses for the independent-judge concept in §11. Both are recorded here so the distinction is not lost.

+
+

References

+

Memory & persistence

+
    +
  1. Weston, Chopra, Bordes (2014). Memory Networks. arXiv:1410.3916.
  2. +
  3. Sukhbaatar, Szlam, Weston, Fergus (2015). End-To-End Memory Networks. arXiv:1503.08895.
  4. +
  5. Graves, Wayne, Danihelka (2014). Neural Turing Machines. arXiv:1410.5401.
  6. +
  7. Graves et al. (2016). Hybrid computing using a neural network with dynamic external memory. Nature.
  8. +
  9. Lewis et al. (2020). Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks. arXiv:2005.11401 / NeurIPS.
  10. +
  11. Packer et al. (2023). MemGPT: Towards LLMs as Operating Systems. arXiv:2310.08560.
  12. +
  13. Park et al. (2023). Generative Agents: Interactive Simulacra of Human Behavior. arXiv:2304.03442.
  14. +
  15. McClelland, McNaughton, O'Reilly (1995). Why there are complementary learning systems in the hippocampus and neocortex. Psychological Review.
  16. +
  17. Kumaran, Hassabis, McClelland (2016). What Learning Systems do Intelligent Agents Need? Complementary Learning Systems Theory Updated. Trends in Cognitive Sciences, 10.1016/j.tics.2016.05.004.
  18. +
  19. Theodore R. Sumers, Shunyu Yao, Karthik Narasimhan et al. (2023). Cognitive Architectures for Language Agents. arXiv:2309.02427.
  20. +
  21. Ebbinghaus, H. (1885). Über das Gedächtnis: Untersuchungen zur experimentellen Psychologie (Memory: A Contribution to Experimental Psychology). Leipzig: Duncker & Humblot (book/monograph).
  22. +
+

Learning without weight updates

+
    +
  1. Kirkpatrick et al. (2017). Overcoming catastrophic forgetting in neural networks. PNAS / arXiv:1612.00796.
  2. +
  3. Sun et al. (2020). Test-Time Training with Self-Supervision for Generalization under Distribution Shifts. arXiv:1909.13231 / ICML 2020.
  4. +
  5. Ba, Hinton, Mnih, Leibo, Ionescu (2016). Using Fast Weights to Attend to the Recent Past. arXiv:1610.06258.
  6. +
  7. Hu et al. (2021). LoRA: Low-Rank Adaptation of Large Language Models. arXiv:2106.09685.
  8. +
  9. von Oswald et al. (2022). Transformers Learn In-Context by Gradient Descent. arXiv:2212.07677.
  10. +
  11. Dai et al. (2022). Why Can GPT Learn In-Context? Language Models Implicitly Perform Gradient Descent as Meta-Optimizers. arXiv:2212.10559.
  12. +
  13. Guanzhi Wang, Yuqi Xie, Yunfan Jiang et al. (2023). Voyager: An Open-Ended Embodied Agent with Large Language Models. arXiv:2305.16291.
  14. +
+

Reasoning, verification & judgement

+
    +
  1. Cobbe et al. (2021). Training Verifiers to Solve Math Word Problems. arXiv:2110.14168.
  2. +
  3. Lightman et al. (2023). Let's Verify Step by Step. arXiv:2305.20050.
  4. +
  5. Shinn et al. (2023). Reflexion: Language Agents with Verbal Reinforcement Learning. arXiv:2303.11366.
  6. +
  7. Madaan et al. (2023). Self-Refine: Iterative Refinement with Self-Feedback. arXiv:2303.17651.
  8. +
  9. Wang et al. (2022). Self-Consistency Improves Chain of Thought Reasoning in Language Models. arXiv:2203.11171.
  10. +
  11. Huang et al. (2023). Large Language Models Cannot Self-Correct Reasoning Yet. arXiv:2310.01798.
  12. +
  13. Shunyu Yao, Jeffrey Zhao, Dian Yu et al. (2022). ReAct: Synergizing Reasoning and Acting in Language Models. arXiv:2210.03629.
  14. +
  15. Jiawei Gu, Xuhui Jiang, Zhichao Shi et al. (2024). A Survey on LLM-as-a-Judge. arXiv:2411.15594.
  16. +
  17. Zhuge, Zhao, Ashley, Wang, Khizbullin, Xiong, Liu, Chang, Krishnamoorthi, Tian, Shi, Chandra, Schmidhuber (2024). Agent-as-a-Judge: Evaluate Agents with Agents. arXiv:2410.10934.
  18. +
  19. Runyang You, Hongru Cai, Caiqi Zhang et al. (2026). Agent-as-a-Judge. arXiv:2601.05111.
  20. +
  21. Kahneman, D. (2011). Thinking, Fast and Slow. Farrar, Straus and Giroux (book).
  22. +
+

World-model & code structure

+
    +
  1. Ha, Schmidhuber (2018). World Models. arXiv:1803.10122.
  2. +
  3. Schrittwieser et al. (2020). Mastering Atari, Go, Chess and Shogi by Planning with a Learned Model. arXiv:1911.08265 / Nature.
  4. +
  5. Hafner et al. (2023). Mastering Diverse Domains through World Models. arXiv:2301.04104.
  6. +
  7. Hafner et al. (2019). Dream to Control: Learning Behaviors by Latent Imagination. arXiv:1912.01603.
  8. +
  9. Friston (2010). The free-energy principle: a unified brain theory?. Nature Reviews Neuroscience.
  10. +
  11. Allamanis, Brockschmidt, Khademi (2018). Learning to Represent Programs with Graphs. arXiv:1711.00740 / ICLR 2018.
  12. +
  13. Yamaguchi, Golde, Arp, Rieck (2014). Modeling and Discovering Vulnerabilities with Code Property Graphs. IEEE S&P 2014.
  14. +
  15. Alon, Zilberstein, Levy, Yahav (2019). code2vec: Learning Distributed Representations of Code. POPL 2019 / PACMPL.
  16. +
  17. Horwitz, Reps, Binkley (1990). Interprocedural Slicing Using Dependence Graphs. ACM TOPLAS.
  18. +
  19. Tip (1994). A Survey of Program Slicing Techniques. Journal of Programming Languages.
  20. +
  21. Ferrante, Ottenstein, Warren (1987). The Program Dependence Graph and Its Use in Optimization. ACM TOPLAS.
  22. +
+

Agent process & software lifecycle

+
    +
  1. Tal Ridnik, Dedy Kredo, Itamar Friedman (2024). Code Generation with AlphaCodium: From Prompt Engineering to Flow Engineering. arXiv:2401.08500.
  2. +
  3. John Yang, Carlos E. Jimenez, Alexander Wettig et al. (2024). SWE-agent: Agent-Computer Interfaces Enable Automated Software Engineering. arXiv:2405.15793.
  4. +
  5. Erol, Hendler, Nau (1994). HTN Planning: Complexity and Expressivity. Proceedings of the 12th National Conference on Artificial Intelligence (AAAI-94), Vol. 2, pp. 1123-1128.
  6. +
  7. Rao, Georgeff (1995). BDI Agents: From Theory to Practice. Proceedings of the First International Conference on Multiagent Systems (ICMAS-95), pp. 312-319.
  8. +
  9. Boyd, J.R. (None). OODA Loop (Observe-Orient-Decide-Act). Unpublished briefings/lectures (e.g. 'A Discourse on Winning and Losing', unpublished collection of briefing slides, c. 1976-1996); no single peer-reviewed paper.
  10. +
  11. Shewhart, W.A. (originator); Deming, W.E. (popularizer) (None). PDCA / Plan-Do-Check-Act cycle (the 'Shewhart Cycle', popularized by Deming). Originates in Shewhart, Statistical Method from the Viewpoint of Quality Control (1939); popularized in Deming, Out of the Crisis (1982) and later works.
  12. +
  13. Happy Bhati (2026). Agentic AI in the Software Development Lifecycle: Architecture, Empirical Evidence, and the Reshaping of Software Engineering. arXiv:2604.26275.
  14. +
+ +

Appendix B — The crosswalk artifact

+

The full three-way crosswalk (§8) is provided as a machine-readable companion in two forms: crosswalk.json (structured, with the notation reconciliation and the three anchor identities) and crosswalk.md (readable table). Together with this paper, the two graded map files from the v2 edition (evidence map, ecosystem map), and the two runnable prototype packages (impact-oracle, router-gate), they form the complete synthesis deliverable set.

+
+

+A Formal Theory of the Cognitive Substrate for Coding Agents — synthesis edition.
+Unifying the substrate faculties, the end-to-end reliability framework, and the forgekit implementation.
+The mathematics says how the check is built; the tradition says why it is owed; the codebase shows it runs. +

+ + diff --git a/research/empirical-refutation/extended_preprint.pdf b/research/empirical-refutation/extended_preprint.pdf new file mode 100644 index 0000000..74f74ae Binary files /dev/null and b/research/empirical-refutation/extended_preprint.pdf differ diff --git a/research/empirical-refutation/figures/fig_cochange_results.png b/research/empirical-refutation/figures/fig_cochange_results.png new file mode 100644 index 0000000..b50e25c Binary files /dev/null and b/research/empirical-refutation/figures/fig_cochange_results.png differ diff --git a/research/empirical-refutation/figures/fig_heldout_calibration.png b/research/empirical-refutation/figures/fig_heldout_calibration.png new file mode 100644 index 0000000..462ab46 Binary files /dev/null and b/research/empirical-refutation/figures/fig_heldout_calibration.png differ diff --git a/research/empirical-refutation/figures/fig_heldout_comparison.png b/research/empirical-refutation/figures/fig_heldout_comparison.png new file mode 100644 index 0000000..8018823 Binary files /dev/null and b/research/empirical-refutation/figures/fig_heldout_comparison.png differ diff --git a/research/empirical-refutation/figures/fig_precision_recall_curve.png b/research/empirical-refutation/figures/fig_precision_recall_curve.png new file mode 100644 index 0000000..86b827e Binary files /dev/null and b/research/empirical-refutation/figures/fig_precision_recall_curve.png differ diff --git a/research/empirical-refutation/figures/fig_repair_beforeafter.png b/research/empirical-refutation/figures/fig_repair_beforeafter.png new file mode 100644 index 0000000..05090ba Binary files /dev/null and b/research/empirical-refutation/figures/fig_repair_beforeafter.png differ diff --git a/research/empirical-refutation/figures/fig_threshold_sweep.png b/research/empirical-refutation/figures/fig_threshold_sweep.png new file mode 100644 index 0000000..91f78a3 Binary files /dev/null and b/research/empirical-refutation/figures/fig_threshold_sweep.png differ diff --git a/research/empirical-refutation/paper.pdf b/research/empirical-refutation/paper.pdf new file mode 100644 index 0000000..f94a727 Binary files /dev/null and b/research/empirical-refutation/paper.pdf differ diff --git a/research/empirical-refutation/paper/main.tex b/research/empirical-refutation/paper/main.tex new file mode 100644 index 0000000..176ca85 --- /dev/null +++ b/research/empirical-refutation/paper/main.tex @@ -0,0 +1,564 @@ +\documentclass[sigconf,review,anonymous]{acmart} +\AtBeginDocument{\providecommand\BibTeX{{Bib\TeX}}} +\setcopyright{none} +\settopmatter{printacmref=false} +\renewcommand\footnotetextcopyrightpermission[1]{} +\pagestyle{plain} +\usepackage{booktabs} +\usepackage{graphicx} + +\begin{document} + +\title{Static Impact Analysis Does Not Transfer:\\A Pre-Registered Refutation of Two LLM-Agent Reliability Mechanisms} + +\author{Anonymous Author(s)} + +\begin{abstract} +Coding agents built on frozen language models are widely argued to need external +mechanisms that supply what the model structurally lacks: a memory of the codebase, a +prediction of what an edit will break, and a gate that refuses to act on an +under-specified request. We built two such mechanisms and reported strong results on +self-constructed evaluations: a dependency-graph \emph{impact oracle} with perfect recall +($1.000$) of impacted files, and a complexity \emph{router} with an assumption +\emph{gate} achieving $\mathrm{F1}=1.00$ and a $62.1\%$ cost saving. This paper reports +what happened when we evaluated both against data we did not construct, under a protocol +frozen before any data was collected. + +Both results collapse. On $759$ files across nine independently selected open-source +Python repositories, with co-change ground truth mined from real commit history, the +oracle's pooled recall is $2.20\%$ (95\% CI $[1.20, 3.31]$) --- not $100\%$ --- and +$91.0\%$ of files receive \emph{exactly zero} recall. A grep baseline with no dependency +graph at all attains recall $0.573$ and F1 $0.437$ against the oracle's $0.042$. On $80$ +held-out tasks drawn from real GitHub issues, with every threshold left untouched, gate +F1 falls from $1.00$ to $0.37$, and the cost saving does not merely shrink but inverts: counting the +pipeline's actual total spend, routing costs $20.2\%$ \emph{more} than always using the premium tier. + +We report three things beyond the refutation. First, a structural decomposition of all +$18{,}221$ false negatives showing that $96.8\%$ are \emph{not} a ground-truth ceiling +but an artifact of reverse-only graph traversal, together with a construction defect whose safe +repair alone recovers an $11.0\times$ recall gap. Second, a repair of both defects evaluated +under the same frozen protocol with a declared tuning/held-out repository split. Third, +the observation that our central composition law is decades-old layer-of-protection +algebra, and was independently and more generally derived weeks before our own write-up. +We argue the transferable contribution is the protocol, not the mechanisms. +\end{abstract} + +\begin{CCSXML} + +10011007.10011074.10011099 +Software and its engineering~Software verification and validation +500 +10011007.10011074.10011134 +Software and its engineering~Software evolution +300 + +\end{CCSXML} +\ccsdesc[500]{Software and its engineering~Software verification and validation} +\ccsdesc[300]{Software and its engineering~Software evolution} +\keywords{LLM coding agents, change impact analysis, co-change, negative results, +pre-registration, verification gates} + +\maketitle + +\section{Introduction} + +A developer opening an unfamiliar file carries context the file does not contain. They +remember which callers depend on it, they anticipate what a signature change will break, +and when a request is too vague to act on they ask instead of guessing. A frozen language +model has none of this: it is a stateless map from a bounded context window to a token +sequence, and each invocation begins with no memory of the last. + +This observation has motivated a large and growing class of \emph{external} mechanisms +that supply the missing faculties around an unmodified model --- persistent stores, +dependency-graph analyses, verification hooks, and routing layers. The argument for them +is structural and, we still believe, correct. What is far less clear is whether any +particular mechanism delivers what its authors measure. + +We are those authors. We built two mechanisms and evaluated them the way such work is +commonly evaluated: on material we constructed ourselves. An \emph{impact oracle} parsed a +Python codebase into a dependency graph and answered ``what will this edit break'' by +reverse reachability with per-hop confidence decay; on a ten-file package with five +injected mutations it recovered every impacted file, recall $1.000$. A complexity +\emph{router} classified tasks into cost tiers and an assumption \emph{gate} halted +under-specified requests; on thirty hand-written tasks it achieved $\mathrm{F1}=1.00$ and +a $62.1\%$ cost saving against an always-premium baseline. + +Both evaluations were honestly labelled as demonstrations. Neither survived contact with +data we did not build. + +This paper reports that failure and what we learned from anatomising it. We pre-registered +a protocol --- corpus eligibility criteria, commit filters, thresholds, and bootstrap +seeds --- and froze it before cloning a single repository, with the explicit stipulation +that an unfavourable number would be reported rather than reconciled. We then evaluated +the oracle against co-change ground truth mined from nine independently selected +open-source projects, and the router and gate against tasks drawn from real GitHub issues, +with every threshold left exactly as shipped. + +\paragraph{Contributions.} +\begin{enumerate} +\item A \textbf{pre-registered evaluation protocol} for LLM-agent impact mechanisms, using +repository co-change history as ground truth, with all thresholds and filters frozen before +data collection and an audited append-only amendment trail (\S\ref{sec:protocol}). +\item A \textbf{refutation} of both mechanisms' headline results on real data: oracle recall +$1.000 \rightarrow 0.022$, gate F1 $1.00 \rightarrow 0.37$, and a cost saving that +inverts to $-20.2\%$ once escalation retries are counted (\S\ref{sec:eval1}, \S\ref{sec:eval2}). +\item A \textbf{structural failure-mode taxonomy} attributing $96.8\%$ of missed impact to +a traversal-direction blind spot rather than to a limit of the ground truth, and isolating a +graph-construction defect whose safe repair recovers an $11.0\times$ recall gap +(\S\ref{sec:failure}, \S\ref{sec:repair}). +\item A \textbf{repair and re-evaluation} of both defects under the same frozen protocol, +with a declared tuning/held-out repository split (\S\ref{sec:repair}). +\item An \textbf{honest novelty accounting}: our composition law is an instance of +layer-of-protection analysis, and was independently and more generally derived weeks +before our own write-up (\S\ref{sec:related}). +\end{enumerate} + +\paragraph{What we do not claim.} We do not claim that external impact analysis is +worthless for coding agents, that co-change is a substitute for semantic impact, or that +our repaired mechanism is production-ready. We claim that the evidence standard commonly +used to justify such mechanisms --- a self-built demonstration --- is capable of +overstating recall by more than an order of magnitude, and we demonstrate this on our own +work. + + +\section{Protocol}\label{sec:protocol} + +The evaluation was pre-registered. Before any repository was cloned or any commit mined, we +fixed and froze: nine numbered corpus eligibility criteria; the commit filters defining +ground truth; the confidence-threshold grid; the bootstrap procedure and its seed; and the +stipulation that governs everything else --- \emph{if a downstream number looks bad, the fix +is to report it, not to edit the protocol}. Amendments were permitted only as dated, +append-only addenda. Three were filed, all documenting the corpus-selection funnel; a +character-level diff confirms nothing above the freeze line was altered. + +\paragraph{Corpus.} Candidates required Python purity $\geq 0.85$, $\geq 3000$ stars, +$\geq 50$ contributors, $\geq 800$ commits, age $\geq 5$ years, activity within 24 months, +repository size under 500\,MB, no affiliation with this project, and $\geq 15$ Python files +after path exclusions. The grep baseline extends the prototype's own symbol-search routine to file +granularity; matching is on identifier occurrences, so short or generic identifiers can inflate its +false-positive count, which if anything favours the oracle in the comparison. Twelve primary candidates were tried in a pre-declared order with +substitution from a pre-declared backup list; substitutions were permitted only in response +to these metadata criteria, never in response to performance. Nine repositories qualified: +\texttt{requests}, \texttt{flask}, \texttt{click}, \texttt{jinja}, \texttt{rich}, +\texttt{httpx}, \texttt{attrs}, \texttt{pytest}, and \texttt{loguru}. Each was pinned to an +exact commit SHA recorded in the corpus artifact. + +\paragraph{Ground truth.} For a file $f$, the ground-truth impact set is the set of other +Python files appearing in the same non-merge commit as $f$, aggregated over history. Merges, +mega-commits above the pre-declared size threshold (formatting sweeps, vendored dependency +bumps, mass renames), and excluded paths were dropped by the frozen filters. This yields +801 labelled files, of which 759 met the evaluation's inclusion condition. + +\paragraph{Ground truth is a proxy, and its ceiling is measurable.} Co-change is not +semantic impact. Files co-change for reasons no static analysis can see (release chores, +coordinated documentation, test-fixture coupling), and files that \emph{should} co-change +sometimes do not. We therefore measured the ceiling directly: the fraction of ground-truth +pairs connected by \emph{any} static path in either direction, at any hop, in the graph the +oracle itself builds. Pooled, 96.9\% of ground-truth impact is statically reachable in +principle. That number bounds every result below, and it is what makes the observed recall interpretable +rather than merely low. Two caveats: it is measured on the graph the \emph{as-shipped} oracle builds, so +repairing the construction defect (\S\ref{sec:repair}) raises it slightly, to roughly $97.2\%$; and +reachability in a dense graph is a weak property, so the ceiling is an upper bound on what any static +method could attain, not evidence that a reachable pair is causally related. + +\paragraph{Independent reproduction.} Before computing any metric, we re-mined all nine +repositories' histories from scratch and compared against the supplied ground truth: 801 of +801 rows matched exactly. Two harness corrections were made at this stage --- both +identified and disclosed \emph{before} any metric was computed. + +\section{Evaluation I: Impact Closure}\label{sec:eval1} + +\begin{table}[t] +\caption{Pooled, micro-averaged over 759 files in 9 repositories, with 95\% bootstrap CIs +($B=2000$, file-resampled). The oracle is shown at $t=0.02$, the most favourable point of +the pre-registered grid for its recall.} +\label{tab:eval1} +\small +\begin{tabular}{lccc} +\toprule +Method & Precision & Recall & F1 \\ +\midrule +Impact oracle ($t{=}0.02$) & 0.398 & \textbf{0.022} & 0.042 \\ +Impact oracle (shipped $t{=}0.10$) & 0.381 & 0.017 & 0.033 \\ +Grep baseline (no graph) & 0.353 & \textbf{0.573} & \textbf{0.437} \\ +Edited-file-only & 0.000 & 0.000 & 0.000 \\ +\midrule +\emph{Static ceiling on this ground truth} & --- & \emph{0.969} & --- \\ +\bottomrule +\end{tabular} +\end{table} + +Table~\ref{tab:eval1} states the result. The oracle's pooled recall is 0.0220, 95\% CI +[0.012, 0.033]. The claim under test was $1.000$. The oracle reaches 2.27\% of its own +static ceiling. + +The per-file distribution shows this is not a uniform shortfall but close to a step +function: 691 of 759 files (91.0\%) receive \emph{exactly zero} recall --- the +oracle misses every co-changed file --- and one file achieves recall $1.0$. A mean of $2.2\%$ +conceals a system that, for nine files in ten, returns nothing useful at all. + +The grep baseline is the uncomfortable comparison. A textual search for symbol names, with +no dependency graph, no confidence model, and no persistent state, attains recall 0.573 +and F1 0.437 against the oracle's 0.042. Whatever a codebase world-model is supposed to +buy over an unstructured baseline, it is not visible here. Precision is the one metric where +the oracle is competitive (0.398 versus 0.353): when it warns, it is often right. It +simply almost never warns. + +\begin{figure*}[t] +\centering +\includegraphics[width=\textwidth]{figures/fig_cochange_results.png} +\caption{Per-repository recall, precision, and F1 with 95\% bootstrap CIs. The oracle's +recall bars are near-invisible against the grep baseline in every repository.} +\label{fig:eval1} +\end{figure*} + +\section{Failure Modes}\label{sec:failure} + +A negative result is only useful if it explains itself. We classified all 18221 pooled false +negatives structurally, by testing reachability in the oracle's own graph. + +\begin{table}[t] +\caption{Structural decomposition of all 18221 false negatives.} +\label{tab:failure} +\small +\begin{tabular}{lcp{3.1cm}} +\toprule +Category & Share & Interpretation \\ +\midrule +Sibling (common dependency) & 94.68\% & Fixable: both files depend on a shared module; +reachable only by a mixed-direction path \\ +Forward-only dependency & 2.13\% & Fixable: excluded by design \\ +No static path at all & 3.19\% & True ceiling: ground-truth limit \\ +\bottomrule +\end{tabular} +\end{table} + +The decomposition in Table~\ref{tab:failure} is the paper's most actionable finding. +Only 3.19\% of missed impact is attributable to the proxy nature of co-change. The +remaining 96.8\% is a path the oracle's own graph already contains but its +traversal cannot reach: 94.7\% are \emph{sibling} pairs, where $A$ and $B$ both import a +common module $C$ and co-change when $C$'s contract shifts, yet neither is reverse-reachable +from the other. The mechanism was not defeated by the messiness of real code; it was defeated +by answering a narrower question than the one that matters. + +\paragraph{A construction defect.} Separately, and reported as a labelled diagnostic rather +than substituted into the numbers above, we found a bug. The world-model's module-qualified-name +derivation collides with absolute imports in \texttt{src/}-layout packages, creating +disconnected phantom nodes. A guard exists for precisely this case but never fires: its +membership test is defeated by the graph library's edge-insertion auto-vivification, which +creates the node before the guard inspects it. This explains why recall was approximately zero +in exactly the six \texttt{src}-layout repositories and non-negligible only in the three +flat-layout ones. A naive repair of the guard raises pooled recall by $14.5\times$, but is unsafe +(\S\ref{sec:repair}); the safe repair we actually apply recovers $11.0\times$, and that is the +figure we report throughout. + +\section{Evaluation II: Routing and Gating}\label{sec:eval2} + +We scored the router and gate on 80 tasks drawn from real GitHub issues and pull requests, +with independent gold labels for cost tier and for whether the request is under-specified +enough that an agent should halt. \textbf{No threshold, weight, or pattern was modified.} + +\paragraph{Label noise first.} Agreement between two independent labelling passes was +$\kappa = 0.952$ (quadratic-weighted) for tier and $\kappa = 0.516$ for the halt +decision. Tier labels are near-perfect; halt labels are moderate. We report this before the +accuracy numbers because it bounds how much of the degradation below can be attributed to +label ambiguity rather than to the mechanism --- and for the halt decision, some of it can. + +\begin{table}[t] +\caption{Tuned 30-task set versus 80 held-out real-issue tasks, thresholds unchanged.} +\label{tab:eval2} +\small +\begin{tabular}{lcc} +\toprule +Metric & Tuned ($n{=}30$) & Held-out ($n{=}80$) \\ +\midrule +Gate F1 & 1.00 & \textbf{0.37} \\ +Gate precision & 1.00 & 0.45 \\ +Gate recall & 1.00 & \textbf{0.31} \\ +Routing exact-tier & 1.00 & 0.53 \\ +Routing within-1-tier & 1.00 & 0.91 \\ +Cost saving & 62.1\% & \emph{see Table~\ref{tab:cost}} \\ +\bottomrule +\end{tabular} +\end{table} + +Gate F1 falls from $1.00$ to 0.37, driven by recall collapsing to 0.31: the gate fails +to flag 11 of the 16 genuinely under-specified issues. Exact-tier routing accuracy falls to +0.53, though within-one-tier accuracy is comparatively robust at 0.91 --- most routing +errors are off-by-one rather than wild. Cost requires two orthogonal distinctions the tuned demonstration never had to make, because on that set +almost every routed output was correct. \emph{Framing}: whether we count only the first, initially-routed +attempt, or everything the pipeline actually spent including each escalation retry. \emph{Gating}: whether +a dollar saved counts when the cheaper output is wrong. Table~\ref{tab:cost} gives all four cells. + +\begin{table}[t] +\caption{Held-out cost saving versus an always-premium baseline, by framing and gating (95\% bootstrap CIs). +The tuned demonstration's $62.1\%$ corresponds to the top-left cell: first-attempt, ungated.} +\label{tab:cost} +\small +\begin{tabular}{lcc} +\toprule +& Ungated & Correctness-gated \\ +\midrule +First attempt only & $59.5\%$ & $3.6\%$ \\ +& \tiny[50.5, 68.2] & \tiny[0.0, 8.5] \\ +Total pipeline spend & $\mathbf{-20.2\%}$ & $2.8\%$ \\ +& \tiny[$-27.5$, $-12.3$] & \tiny[$-0.8$, 7.8] \\ +\bottomrule +\end{tabular} +\end{table} + +Read in the order that matters. Routing does identify that most of these tasks do not need the premium +tier, so on first attempts alone it saves $59.5\%$ in raw dollars --- close to the demonstration's +$62.1\%$, and the one cell where the tuned result survives. But almost none of that cheaper output is +\emph{correct}: gating the same first-attempt framing on the judge's verdict collapses the saving to +$3.6\%$. And the pipeline does not stop at the first attempt. Counting what it actually spent chasing +correctness up the ladder, the raw saving is $\mathbf{-20.2\%}$: the router costs \emph{more} than always +sending every task to the premium tier, because it pays for cheap, then mid, then premium in sequence and +still mostly fails. The gated total-spend figure, $2.8\%$, has a confidence interval spanning zero. + +The honest summary is not that the saving shrank but that it inverted. On this task distribution a +complexity router is a net cost \emph{increase} once its retries are counted, and the single headline +number the demonstration produced ($62.1\%$) turns out to be the most favourable of four available cells. + +\paragraph{The gate's confidence score is non-monotonic.} Binned calibration is not monotone in +the score: decision accuracy is $0.93$ in the middle bin ($n{=}28$) and $0.94$ in the highest +($n{=}16$), but dips to $0.50$ in the second-highest bin ($n{=}4$). We flag this as a caution +rather than a finding: with four tasks in the affected bin the dip is well within sampling noise, +and the top bin is in fact well calibrated. What it does establish is that the score is not +reliably ordered across its range, so choosing an operating point from it requires more evidence +than this sample provides. + +\paragraph{Verification coverage.} Of the 64 well-specified held-out tasks, \emph{none} admitted +execution-based verification: real issue text does not come with runnable input/output examples. +Correctness was therefore judged by a model-based criterion, which is weaker, and we mark the +cost figure accordingly. One candidate execution match was found by pattern search and rejected +on inspection as prose describing a source-code branch rather than an invocable example. + + +\section{Repair and Re-Evaluation}\label{sec:repair} + +A refutation that stops at the negative number leaves the more useful question unasked: was the +mechanism wrong, or merely built wrong? \S\ref{sec:failure} says $96.8\%$ of the missed impact is +reachable in a graph the tool already constructs. We therefore repaired both defects and re-ran the +same frozen protocol. + +\paragraph{Honest parameter setting.} The traversal repair introduces new parameters, so it cannot be +evaluated on the corpus that motivated it --- that is the error this paper is about. Before writing +any repair code we declared a stratified split: six \textbf{tuning} repositories (\texttt{rich}, +\texttt{httpx}, \texttt{click}, \texttt{flask}, \texttt{jinja}, \texttt{attrs}) and three +\textbf{held-out} repositories (\texttt{loguru}, \texttt{requests}, \texttt{pytest}), stratified by +package layout in proportion to the corpus. All eight parameters were fixed by grid search on the +tuning repositories only, written to a frozen parameter file, and never adjusted afterwards. The +held-out repositories were touched exactly once, after freezing. + +\paragraph{Defect 1: construction.} We repaired the phantom-node merge --- but not as the diagnostic +suggested. The naive guard fix is \emph{unsafe}: it merges a bare \texttt{import json} into an +unrelated local \texttt{pkg.json} submodule, fabricating dependency edges that do not exist. We ground +matching in the layout prefix instead. This yields a smaller recall improvement than the unsafe +variant ($11.0\times$), and we prefer it: a tool that invents edges to raise recall is worse than one +that misses them. + +\paragraph{Defect 2: traversal.} We added terminal sibling and forward relations with per-relation +weights and hop caps. The sibling relation must be capped by the shared dependency's in-degree --- +admitting every sibling of a high-traffic utility module implicates most of the codebase. A +post-freeze sensitivity check on the tuning repositories confirms the cap does real protective work +rather than passing through unbounded. + +\begin{table}[t] +\caption{Repair sequence under the frozen protocol. Row (d) is the headline: three repositories never +seen during parameter selection. Rows (a)--(b) are pooled over all nine.} +\label{tab:repair} +\small +\begin{tabular}{llccc} +\toprule +& Configuration & P & R & F1 \\ +\midrule +(a) & As shipped (reproduced exactly) & 0.398 & 0.022 & 0.042 \\ +(b) & \quad + construction fix & 0.304 & 0.242 & 0.270 \\ +(c) & \quad + traversal fix, \emph{tuning} & 0.461 & 0.668 & 0.545 \\ +(d) & \quad + traversal fix, \textbf{held-out} & 0.305 & 0.653 & \textbf{0.416} \\ +(d$'$) & \quad\quad same, at tuned $t{=}0.10$ & 0.320 & 0.647 & 0.428 \\ +\midrule +& grep baseline, held-out & 0.269 & 0.601 & 0.371 \\ +& \emph{static ceiling, held-out repos} & --- & \emph{0.977} & --- \\ +\bottomrule +\end{tabular} +\end{table} + +\paragraph{Result.} We headline row (d) at the canonical $t{=}0.02$ used for the as-shipped baseline, so the +comparison is like-for-like. On repositories never seen during parameter selection the repaired oracle reaches +$\mathrm{F1}=0.416$ (95\% CI $[0.382, 0.446]$) against grep's 0.371 (CI $[0.332, 0.405]$). This reverses the +as-shipped ordering, in which grep won by roughly an order of magnitude. Recall rises from 0.022 to 0.653, +reaching $66.8\%$ of the held-out repositories' own static ceiling ($0.977$), and the share of files with +exactly zero recall falls from $91.0\%$ to $19.3\%$. Row (d$'$) reports the same configuration at +$t{=}0.10$, the F1-peak of the tuning grid; it scores marginally higher, and we decline to headline it +because that threshold was selected on the tuning repositories and is therefore a ninth tuned parameter +rather than a pre-registered one. All 49/49 tests pass, including 13 new tests covering +both fixes and the stdlib-collision safety case. Both fixes are necessary: neither alone crosses the +baseline. + +\paragraph{The win is narrow, and precision generalised worse than recall.} The two confidence +intervals are close, and the honest reading is a real but modest advantage, not a decisive one. More +instructive is the asymmetry: recall transferred almost perfectly from tuning to held-out repositories +($-0.021$), while precision fell by $-0.141$. Some overfitting to the tuning set occurred during +parameter selection --- visible \emph{only} because the split was declared in advance. Had we tuned on +all nine repositories we would have reported the better number and never known the gap existed. + +\begin{figure*}[t] +\centering +\includegraphics[width=\textwidth]{figures/fig_repair_beforeafter.png} +\caption{The repair sequence (a)$\rightarrow$(d) with 95\% bootstrap CIs, against the grep baseline +and the static ceiling.} +\label{fig:repair} +\end{figure*} + + +\section{Threats to Validity}\label{sec:threats} + +\paragraph{Construct.} Co-change is a proxy for semantic impact and errs in both directions. +Files co-change for reasons no dependency analysis can predict --- release chores, coordinated +documentation, test-fixture updates --- and files that ought to co-change are sometimes missed +by their authors. We do not treat co-change as truth; we measure its ceiling (96.9\% of +ground-truth pairs are statically connected in principle) and interpret every result against +it. An over-warning is likewise not necessarily an error: it may be a correct dependency that +has not yet co-changed in the mined window. + +\paragraph{Construct, continued: the correctness judge.} No held-out task admitted execution-based +verification (0/64; the mechanical check was re-run independently and its single candidate hit rejected on +inspection), so correctness was scored by a fixed-rubric model judge. The judge was pre-declared as +``neither cheap nor premium'' --- neutral with respect to the \emph{tier ladder}, but not neutral in an +absolute sense, because the ladder's mid tier is that same model. For the 38 of 64 tasks initially routed +to mid, and for every mid-tier escalation attempt, the judge grades output from its own model family. +Evaluators are known to favour their own generations, which biases this measurement in the direction of +\emph{overstating} mid-tier correctness and therefore overstating the routed pipeline's savings; the +inversion we report is if anything conservative. Separately, seven generation calls returned empty output +at the pre-declared token budget and were retried at the same tier with a raised budget; this is logged as +a deviation rather than silently patched, and no escalation cost is attributed to those retries. + +\paragraph{Internal.} The pre-registration, the tuning/held-out split, and the parameter freeze were all +self-administered within one continuous working session, with no external timestamping authority: a reader +must take the ordering on trust, evidenced only by the artifact store's own version timestamps and the +append-only amendment trail. We consider this the central weakness of a self-evaluation and state it plainly +rather than resting on the protocol's authority. The held-out task labels come from a single labelling pair; halt-decision +agreement is only moderate ($\kappa = 0.52$), so part of the gate's measured degradation is +label ambiguity rather than mechanism failure. Tier agreement is near-perfect ($\kappa = 0.95$), +so the routing result is on firmer ground. No held-out task admitted execution-based +verification, so correctness was judged by a weaker model-based criterion. + +\paragraph{External.} Nine repositories, Python only, open-source only, all library-shaped +rather than application-shaped. Results may differ for applications with heavy dynamic +configuration, for languages with static typing that makes dependencies more explicit, or for +proprietary codebases with different commit conventions. GitHub issue text is a proxy for the +prompts a developer actually gives an agent. + +\paragraph{Conclusion.} All intervals are 95\% file- or task-resampled bootstrap intervals. +We report them for every headline number and make no claim that survives only at a point +estimate. We apply no multiple-comparison correction and claim no significance test; the +comparisons are descriptive. + +\section{Related Work}\label{sec:related} + +\paragraph{The composition law is not ours.} Read as mathematics, the product-of-independent-layer-misses +form is textbook. Layer-of-protection analysis has expressed unmitigated event frequency as a +product over independent protection layers since the 1990s~\cite{dowell1998}; fault-tree analysis +generalises it~\cite{ruijters2015}; Reason's Swiss-cheese model gives the same intuition a +human-factors vocabulary~\cite{reason1990}; and reliable-computation-from-unreliable-parts runs +back to von Neumann and to N-version programming~\cite{avizienis1985}. The literature also supplies +the caveat any layered argument must confront: Knight and Leveson showed experimentally that +independently written versions do \emph{not} fail independently~\cite{knight1986}, so an +independence assumption between layers must be defended rather than asserted. We claim no novelty +for the arithmetic. + +\paragraph{And it was independently derived, more generally, before ours.} More consequentially, +two concurrent preprints derive a strictly more general Bayesian form of the same law weeks before +our own write-up. \emph{Odds Law}~\cite{aksu2026} develops a decomposition algebra whose +verification-odds law and $k$-gate geometric-amplification theorem subsume our two-layer product as +a special case, adding a threshold dichotomy and an information-theoretic ceiling we do not have. +Its companion \emph{Maestro Order}~\cite{aksu2026a} compiles the algebra into a controller and names +the coder/test-suite pairing as its canonical software-engineering instance --- the same +probabilistic-generator/deterministic-checker identification we had claimed. We concede priority. +What our framing retains is narrower: an argument for the split \emph{derived} from the architecture +of a frozen parametric map rather than assumed as a black-box parameter, and --- the gap we can +actually fill --- an evaluation against real repositories, where both preprints offer only Monte +Carlo simulation of an abstract solver model. + +\paragraph{Impact analysis is forty years old and being reinvented right now.} +The oracle's pipeline descends directly from program slicing~\cite{weiser1984}, program dependence +graphs~\cite{ferrante1987}, and interprocedural slicing~\cite{horwitz1990}. Its ground truth follows +the co-change mining line~\cite{zimmermann2005,zimmermann2004}, and its confidence decay has a +decade-old empirical precedent in dependency-distance studies of change propagation. Concurrently, +at least four 2026 preprints wire comparable AST/graph analyses into LLM coding-agent loops --- +source-to-test dependency mapping, library-defect propagation, persistent codebase knowledge graphs, +and assumption localisation --- and, notably, \emph{none of them claims perfect recall}. That the +sub-field is simultaneously decades old and actively re-invented raises the evidential bar rather +than lowering it. + +\paragraph{Pre-registration in software engineering.} Pre-registration and Registered Reports are not new +to empirical software engineering, where they were introduced to address exactly the degrees of freedom we +exploit here unintentionally. We claim no novelty for the practice. What we add is narrower: a concrete +instance of applying it to LLM-agent mechanism evaluation, where self-built demonstrations are currently the +prevailing evidence standard, together with a measurement of how large the resulting gap can be. + +\paragraph{Routing and abstention.} Cost-aware cascading was named by +FrugalGPT~\cite{chen2023} and the successor literature is large, with learned and preference-trained +routers now standard. The most pointed prior work for us argues that deployed routers rely on +uncalibrated confidence and per-workload threshold tuning, and replaces hand-set thresholds with +calibrated error probabilities --- a critique that lands squarely on our own tuned-rubric +methodology, and which our held-out result independently confirms. Selective prediction with a +reject option is older still, running back to Chow's rule. Surveys of LLM self-correction report +increasingly negative results, which supports rather than undermines the case for an +\emph{external} deterministic check. + +\section{Discussion}\label{sec:discussion} + +Three lessons generalise beyond our two mechanisms. + +\textbf{A self-built demonstration can overstate recall by more than an order of magnitude.} +Our demo package was not adversarial or dishonest: ten files, five plausible mutations, honestly +labelled as a demonstration. It still reported $1.000$ where real repositories gave $0.022$. The +demo was unrepresentative in a specific and instructive way --- it used a flat package layout, and +the defect that destroyed recall only manifests under \texttt{src/} layouts. A demonstration +selects its own structure, and structure was the variable that mattered. + +\textbf{Tuning and evaluating on the same set does not degrade gracefully.} The gate did not fall +from $1.00$ to $0.85$; it fell to $0.37$, and its confidence score is non-monotonic in the region +where an operating point would be chosen. The failure is qualitative, not a matter of degree. + +\textbf{Report the ceiling, not just the score.} Decomposing false negatives structurally was what +turned an uninterpretable $2.2\%$ into an actionable finding: $96.8\%$ fixable, $3.2\%$ a genuine +proxy limit. Without the ceiling, the number is merely discouraging; with it, it is a specification +for the repair. + +\section{Conclusion}\label{sec:conclusion} + +We pre-registered an evaluation of two LLM-agent reliability mechanisms we had built ourselves and +reported strong results for, then ran it against data we did not construct. Both headline results +collapsed: recall $1.000 \rightarrow 0.022$, gate F1 $1.00 \rightarrow 0.37$, and a cost saving +that inverts from $+62.1\%$ to $-20.2\%$ once the pipeline's escalation retries are counted. A grep baseline with no dependency graph +outperformed the graph-based oracle. We diagnosed the causes structurally, repaired both defects, +and re-evaluated under the same frozen protocol with a declared held-out split. + +We think the protocol is the transferable contribution. The mechanisms may yet be made to work --- +$96.8\%$ of the missed impact is reachable in a graph the tool already builds --- but the evidence +standard that told us they already worked was the thing most in need of repair. + +\section*{Artifact availability} + +All materials are available: the pre-registration with its append-only amendment trail, the corpus manifest +with pinned commit SHAs, the mined co-change ground truth, the held-out task set with its labelling protocol +and both labelling passes, the tuning/held-out split declaration and frozen parameter file, the repaired +package with its test suite, and the analysis code that regenerates every number and figure in this paper. +References are withheld for anonymous review and will be released on acceptance. + +\section*{Design provenance} + +The design principles behind these mechanisms --- verify a report before acting on it, do not act +without knowledge of consequences, treat a delegated capability as a trust --- were derived from an +ethical-epistemic reading documented in full in the extended version of this work. That reading +motivated which safeguards were considered mandatory rather than optional; it makes no technical +claim, and every result above stands or falls on the engineering evidence alone. + +\bibliographystyle{ACM-Reference-Format} +\bibliography{refs} + +\end{document} diff --git a/research/empirical-refutation/paper/refs.bib b/research/empirical-refutation/paper/refs.bib new file mode 100644 index 0000000..9dc048f --- /dev/null +++ b/research/empirical-refutation/paper/refs.bib @@ -0,0 +1,395 @@ +@misc{neumann1956, + author = {John von Neumann}, + title = {{Probabilistic Logics and the Synthesis of Reliable Organisms from Unreliable Components}}, + year = {1956}, + howpublished = {Automata Studies (Princeton Univ. Press)}, + url = {https://openalex.org/ (book chapter, no DOI in OpenAlex)}, +} + +@misc{reason1990, + author = {James Reason}, + title = {{Human Error}}, + year = {1990}, + howpublished = {Cambridge University Press}, + doi = {10.1017/cbo9781139062367}, +} + +@misc{journal2020, + title = {{Good and bad reasons: The Swiss cheese model and its critics}}, + year = {2020}, + howpublished = {Safety Science}, + doi = {10.1016/j.ssci.2020.104660}, +} + +@misc{leveson2012, + author = {Nancy G. Leveson}, + title = {{Engineering a Safer World: Systems Thinking Applied to Safety}}, + year = {2012}, + howpublished = {MIT Press}, + doi = {10.7551/mitpress/8179.001.0001}, +} + +@misc{rasmussen1997, + author = {Jens Rasmussen}, + title = {{Risk management in a dynamic society: a modelling problem}}, + year = {1997}, + howpublished = {Safety Science}, + doi = {10.1016/s0925-7535(97)00052-0}, +} + +@misc{avizienis1985, + author = {Algirdas Avizienis and John P. J. Kelly}, + title = {{The N-Version Approach to Fault-Tolerant Software}}, + year = {1985}, + howpublished = {IEEE Transactions on Software Engineering}, + doi = {10.1109/tse.1985.231893}, +} + +@misc{knight1986, + author = {John C. Knight and Nancy G. Leveson}, + title = {{An experimental evaluation of the assumption of independence in multiversion programming}}, + year = {1986}, + howpublished = {IEEE Transactions on Software Engineering}, + doi = {10.1109/tse.1986.6312924}, +} + +@misc{aksu2026, + author = {Hidayet Aksu}, + title = {{Odds Law: The Decomposition Algebra — On How Intelligence Organizes Itself to Solve Difficult Problems Reliably}}, + year = {2026}, + howpublished = {arXiv preprint}, + doi = {10.48550/arxiv.2606.15712}, +} + +@misc{aksu2026a, + author = {Hidayet Aksu}, + title = {{Maestro Order: A Model-Agnostic Orchestration Harness}}, + year = {2026}, + howpublished = {arXiv preprint}, + doi = {10.48550/arxiv.2606.23983}, +} + +@misc{hoeffding1963, + author = {Wassily Hoeffding}, + title = {{Probability Inequalities for Sums of Bounded Random Variables}}, + year = {1963}, + howpublished = {J. Amer. Statist. Assoc.}, +} + +@misc{condorcet1785, + author = {Marquis de Condorcet}, + title = {{Essai sur l'application de l'analyse à la probabilité des décisions rendues à la pluralité des voix}}, + year = {1785}, + howpublished = {Paris}, +} + +@misc{chow1970, + author = {C.K. Chow}, + title = {{On optimum recognition error and reject tradeoff}}, + year = {1970}, + howpublished = {IEEE Transactions on Information Theory}, + doi = {10.1109/tit.1970.1054406}, +} + +@misc{elyaniv2010, + author = {Ran El-Yaniv and Yair Wiener}, + title = {{On the Foundations of Noise-free Selective Classification}}, + year = {2010}, + howpublished = {Journal of Machine Learning Research}, + url = {https://www.jmlr.org/papers/v11/el-yaniv10a.html}, +} + +@misc{weiser1981, + author = {Mark Weiser}, + title = {{Program slicing}}, + year = {1981}, + howpublished = {Proc. 5th Int'l Conf. Software Engineering (ICSE)}, + url = {https://dl.acm.org/doi/10.5555/800078.802557}, +} + +@misc{weiser1984, + author = {Mark Weiser}, + title = {{Program Slicing}}, + year = {1984}, + howpublished = {IEEE Transactions on Software Engineering}, + doi = {10.1109/tse.1984.5010248}, +} + +@misc{ferrante1987, + author = {Jeanne Ferrante and Karl J. Ottenstein and Joe D. Warren}, + title = {{The program dependence graph and its use in optimization}}, + year = {1987}, + howpublished = {ACM TOPLAS}, + doi = {10.1145/24039.24041}, +} + +@misc{horwitz1990, + author = {Susan Horwitz and Thomas Reps and David Binkley}, + title = {{Interprocedural slicing using dependence graphs}}, + year = {1990}, + howpublished = {ACM TOPLAS}, + doi = {10.1145/77606.77608}, +} + +@misc{bohner1996, + author = {Shawn A. Bohner and Robert S. Arnold}, + title = {{Software Change Impact Analysis}}, + year = {1996}, + howpublished = {IEEE Computer Society Press (edited volume)}, +} + +@misc{li2012, + author = {Bixin Li and Xiaobing Sun and Hareton Leung and Sai Zhang}, + title = {{A survey of code‐based change impact analysis techniques}}, + year = {2012}, + howpublished = {Software Testing, Verification and Reliability}, + doi = {10.1002/stvr.1475}, +} + +@misc{zimmermann2005, + author = {Thomas Zimmermann and Peter Weisgerber and Stephan Diehl and Andreas Zeller}, + title = {{Mining version histories to guide software changes}}, + year = {2005}, + howpublished = {IEEE Transactions on Software Engineering}, + doi = {10.1109/tse.2005.72}, +} + +@misc{zimmermann2004, + author = {Thomas Zimmermann and Peter Weisgerber and Stephan Diehl and Andreas Zeller}, + title = {{Mining Version Histories to Guide Software Changes}}, + year = {2004}, + howpublished = {Proc. ICSE}, + doi = {10.1109/icse.2004.1317478}, +} + +@misc{al2025, + author = {Thomas Zimmermann et al.}, + title = {{A Retrospective on Mining Version Histories to Guide Software Changes}}, + year = {2025}, + howpublished = {IEEE Transactions on Software Engineering}, + doi = {10.1109/tse.2025.3533559}, +} + +@misc{ying2004, + author = {Annie T.T. Ying and Gail C. Murphy and Raymond Ng and Mark C. Chu-Carroll}, + title = {{Predicting source code changes by mining change history}}, + year = {2004}, + howpublished = {IEEE Transactions on Software Engineering}, + doi = {10.1109/tse.2004.52}, +} + +@misc{hassan2005, + author = {Ahmed E. Hassan and Richard C. Holt}, + title = {{The top ten list: dynamic fault prediction}}, + year = {2005}, + howpublished = {Proc. ICSM (Int'l Conf. Software Maintenance)}, + doi = {10.1109/icsm.2005.91}, +} + +@misc{yamaguchi2014, + author = {Fabian Yamaguchi and Nico Golde and Daniel Arp and Konrad Rieck}, + title = {{Modeling and Discovering Vulnerabilities with Code Property Graphs}}, + year = {2014}, + howpublished = {IEEE Symposium on Security and Privacy}, + doi = {10.1109/sp.2014.44}, +} + +@misc{al2026, + author = {Pepe Alonso et al.}, + title = {{TDAD: Test-Driven Agentic Development - Reducing Code Regressions in AI Coding Agents via Graph-Based Impact Analysis}}, + year = {2026}, + howpublished = {arXiv preprint}, + doi = {10.48550/arxiv.2603.17973}, +} + +@misc{authors2026, + title = {{DepRadar: Agentic Coordination for Context Aware Defect Impact Analysis in Deep Learning Libraries}}, + year = {2026}, + howpublished = {arXiv preprint}, + doi = {10.48550/arxiv.2601.09440}, +} + +@misc{authors2026a, + title = {{Codebase-Memory: Tree-Sitter-Based Knowledge Graphs for LLM Code Exploration via MCP}}, + year = {2026}, + howpublished = {arXiv preprint}, + doi = {10.48550/arxiv.2603.27277}, +} + +@misc{authors2026b, + title = {{AssumptionMiner: Extracting, Tracing, and Revising Implicit Assumptions in LLM Code Generation}}, + year = {2026}, + howpublished = {arXiv preprint}, + doi = {10.48550/arxiv.2607.22898}, +} + +@misc{authors2026c, + title = {{Blast Radius}}, + year = {2026}, + howpublished = {arXiv preprint}, + doi = {10.48550/arxiv.2608.07440}, +} + +@misc{authors2026d, + title = {{DEPTEX: Organization-First, Open Source Dependency Risk Monitoring}}, + year = {2026}, + howpublished = {arXiv preprint}, + doi = {10.48550/arxiv.2605.00179}, +} + +@misc{chen2023, + author = {Lingjiao Chen and Matei Zaharia and James Zou}, + title = {{FrugalGPT: How to Use Large Language Models While Reducing Cost and Improving Performance}}, + year = {2023}, + howpublished = {arXiv preprint}, + doi = {10.48550/arxiv.2305.05176}, +} + +@misc{al2024, + author = {Isaac Ong et al.}, + title = {{RouteLLM: Learning to Route LLMs with Preference Data}}, + year = {2024}, + howpublished = {arXiv preprint}, + doi = {10.48550/arxiv.2406.18665}, +} + +@misc{al2024a, + author = {Dujian Ding et al.}, + title = {{Hybrid LLM: Cost-Efficient and Quality-Aware Query Routing}}, + year = {2024}, + howpublished = {arXiv preprint}, + doi = {10.48550/arxiv.2404.14618}, +} + +@misc{authors2026e, + title = {{Dynamic Model Routing and Cascading for Efficient LLM Inference: A Survey}}, + year = {2026}, + howpublished = {arXiv preprint}, + doi = {10.48550/arxiv.2603.04445}, +} + +@misc{authors2025, + title = {{Doing More with Less: A Survey on Routing Strategies for Resource Optimisation in Large Language Model-Based Systems}}, + year = {2025}, + howpublished = {arXiv preprint}, + doi = {10.48550/arxiv.2502.00409}, +} + +@misc{authors2025a, + title = {{Rational Tuning of LLM Cascades via Probabilistic Modeling}}, + year = {2025}, + howpublished = {arXiv preprint}, + doi = {10.48550/arxiv.2501.09345}, +} + +@misc{authors2025b, + title = {{C3PO: Optimized Large Language Model Cascades with Probabilistic Cost Constraints for Reasoning}}, + year = {2025}, + howpublished = {arXiv preprint}, + doi = {10.48550/arxiv.2511.07396}, +} + +@misc{authors2026f, + title = {{UCCI: Calibrated Uncertainty for Cost-Optimal LLM Cascade Routing}}, + year = {2026}, + howpublished = {arXiv preprint}, + doi = {10.48550/arxiv.2605.18796}, +} + +@misc{authors2025c, + title = {{Cost-Saving LLM Cascades with Early Abstention}}, + year = {2025}, + howpublished = {arXiv preprint}, + doi = {10.48550/arxiv.2502.09054}, +} + +@misc{kamath2020, + author = {Amita Kamath and Robin Jia and Percy Liang}, + title = {{Selective Question Answering under Domain Shift}}, + year = {2020}, + howpublished = {ACL 2020}, + doi = {10.18653/v1/2020.acl-main.503}, +} + +@misc{authors2024, + title = {{Know Your Limits: A Survey of Abstention in Large Language Models}}, + year = {2024}, + howpublished = {arXiv preprint}, + doi = {10.48550/arxiv.2407.18418}, +} + +@misc{authors2024a, + title = {{When Can LLMs Actually Correct Their Own Mistakes? A Critical Survey of Self-Correction of LLMs}}, + year = {2024}, + howpublished = {arXiv preprint}, + doi = {10.48550/arxiv.2406.01297}, +} + +@misc{authors2025d, + title = {{Curiosity by Design: An LLM-based Coding Assistant Asking Clarification Questions}}, + year = {2025}, + howpublished = {arXiv preprint}, + doi = {10.48550/arxiv.2507.21285}, +} + +@misc{authors2025e, + title = {{Evidence-Bound Autonomous Research (EviBound): A Governance Framework for Eliminating False Claims}}, + year = {2025}, + howpublished = {arXiv preprint}, + doi = {10.48550/arxiv.2511.05524}, +} + +@misc{dowell1998, + author = {Arthur M. Dowell III}, + title = {{Layer of protection analysis for determining safety integrity level}}, + year = {1998}, + howpublished = {ISA Transactions}, + doi = {10.1016/s0019-0578(98)00018-4}, +} + +@misc{ruijters2015, + author = {Enno Ruijters and Mariëlle Stoelinga}, + title = {{Fault tree analysis: A survey of the state-of-the-art in modeling, analysis and tools}}, + year = {2015}, + howpublished = {Computer Science Review}, + doi = {10.1016/j.cosrev.2015.03.001}, +} + +@misc{vaurio2003, + author = {J.K. Vaurio}, + title = {{Common cause failure probabilities in standby safety system fault tree analysis with testing—scheme and timing dependencies}}, + year = {2003}, + howpublished = {Reliability Engineering \& System Safety}, + doi = {10.1016/s0951-8320(02)00170-9}, +} + +@misc{willey2014, + author = {Ronald J. Willey}, + title = {{Layer of Protection Analysis}}, + year = {2014}, + howpublished = {Procedia Engineering}, + doi = {10.1016/j.proeng.2014.10.405}, +} + +@misc{wang2014, + author = {Rongcun Wang and Rubing Huang and Binbin Qu}, + title = {{Network-Based Analysis of Software Change Propagation}}, + year = {2014}, + howpublished = {The Scientific World Journal}, + doi = {10.1155/2014/237243}, +} + +@misc{kempe2003, + author = {David Kempe and Jon Kleinberg and Éva Tardos}, + title = {{Maximizing the Spread of Influence through a Social Network}}, + year = {2003}, + howpublished = {Proc. KDD}, +} + +@misc{aven2015, + author = {Terje Aven}, + title = {{Risk assessment and risk management: Review of recent advances on their foundation}}, + year = {2015}, + howpublished = {European Journal of Operational Research}, + doi = {10.1016/j.ejor.2015.12.023}, +} diff --git a/research/empirical-refutation/replication_package.tar.gz b/research/empirical-refutation/replication_package.tar.gz new file mode 100644 index 0000000..50bd453 Binary files /dev/null and b/research/empirical-refutation/replication_package.tar.gz differ