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 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).
+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.
+ +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:
+ +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:
+ +| Faculty | Why it is structurally absent | Follows 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‑correction | Any “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.21 | P2 |
| Impact‑awareness | By 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 |
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.
+ +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.
+ +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.
+ +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.
+ +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.
+ +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.
+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.
+ +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.
+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.
+ +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.
+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.
+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.
+ +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.
+ +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–5 — iqra' 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:24 — tadabbur, 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.
+ +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.
+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:
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.
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:
+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.
+ +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.
+ +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.
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.
+ +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.
+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:
+ +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.
+ +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:
+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:
+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.
+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:
+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.
+ +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.
+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.
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.
+ +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.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:
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.
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.
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.
+ +
+
+
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.
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.
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.
+
+
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.
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.
+ +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.
+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.
Ranking by (evidence strength for the pain) × (how unsolved it is) × (buildability), +the genuine opportunities are:
+ +| Rank | What to build | Why (grounded) | Status |
| 1 | Assumption / 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 |
| 2 | Validity‑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 |
| 3 | Mandatory 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 |
| 4 | Outcome‑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 |
| 5 | Root‑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 |
| 6 | Scope‑minimality check (M5) | +Over‑engineering is untracked outside UI; measuring footprint against the task's minimal +sufficient footprint is genuine whitespace. | +residual gap |
| 7 | Inline 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.
+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.
+| Element | Status | Assessment |
|---|---|---|
| External memory for a frozen model | Reinvented | RAG, 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 split | Reinvented framing | The 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 analysis | Reinvented (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 emphasis | Scoring 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 gate | Novel composition | The 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 framing | Deriving 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.
+ +ast‑based world‑model is sound for static Python structure but conservative‑to‑wrong on dynamic dispatch, monkey‑patching, reflection, eval, and dependency injection. It is single‑language. Precision (0.63) reflects partly that it over‑approximates; recall is its strength precisely because it errs toward inclusion.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.
+ +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.
| ID | Claim | Primary source | Supports | Status |
| C1 | +Experienced 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 Productivity | +M2 (assumption/uncertainty - miscalibration), P3/self-correc | +confirmed | +
| C2 | +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 | +2025 Stack Overflow Developer Survey (49,000+ respondents, 177 countries) | +M2 uncertainty/calibration; M6 inline verification; overall | +confirmed | +
| C3 | +45% 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 Report | +M5 anti-over-engineering / code-quality thesis; security-ver | +vendor‑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 Qua | +M5 anti-over-engineering; long-term codebase impact-awarenes | +vendor‑reported | +
| C5 | +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 beco | +State of AI-assisted Software Development 2025 (DORA Report) | +Systemic framing for all six mechanisms (org context matters | +confirmed | +
| C6 | +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 ga | +Why SWE-bench Verified no longer measures frontier coding capabilities | +M6 inline verification / benchmark-trust thesis; supports 'A | +confirmed | +
| C7 | +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. | +The AI Engineering Report 2026: The Acceleration Whiplash | +M6 inline verification; review-bottleneck / verification-lay | +vendor‑reported | +
| C8 | +Developers 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 Ha | +M6 inline verification / skill-atrophy thesis (comprehension | +unverifiable | +
| C9 | +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'). | +State of Code Developer Survey report 2026 | +M6 inline verification - the central named gap the mechanism | +vendor‑reported | +
| C10 | +JetBrains' 2025 survey found 77% of developers still manually correct AI output for project conventions every session. | +The State of Developer Ecosystem 2025 | +M4 goal-anchoring / M5 anti-over-engineering (convention dri | +unverifiable | +
| C11 | +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 (' | +(a) 72%-context-window claim: no formal paper found, only recurring blog anecdotes (Scott | +M1 complexity-aware routing / M3 task decomposition (context | +vendor‑reported | +
| C12 | +LLM 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 Generations | +M6 inline verification (why an LLM cannot be its own sole ve | +confirmed | +
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.
| Capability | Existing tooling (sample) | Status | Residual gap | What we'd add |
| Memory (across sessions) faculty |
+CLAUDE.md; Auto Memory; Mem0; claude-mem; Hindsight | +partial | +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% | +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 trackers | +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; froz | +Outcome-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 -> review | +partial | +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- | +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-toolkit | +partial | +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 | +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' | +partial | +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 repor | +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 | +
| 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' | +solved | +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 mechanism |
+Reasoning models acting as an internal review pass; Context7; Spec-driven development | +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 r | +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 w | +
| M3 Task / session decomposition mechanism |
+Subagents; Agent Teams; git worktrees for parallel-agent isolation; Parallel fan-out orchestration pattern; Superpowers subagent-driven-development | +solved | +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 t | +Automatic 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 Teams | +partial | +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 dri | +A 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 agents | +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 du | +A 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 gating | +partial | +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 | +A mandatory inline checkpoint that surfaces a human-checkable claim or diff at each meaningful generation step, shifting verification earlier instead of batchin | +
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 / verse | Retrieved gloss | Faculty | Design 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-AWARENESS | 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 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-CORRECTION | The agent architecture must include a verification gate between receiving information (from context, tool output, or its own prior reasoning) and acting on it | load-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 LEARNING | The agent's knowledge must be treated as perpetually incomplete, with an explicit mechanism for incremental growth | load-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 MEMORY | Knowledge must be externalized to survive beyond the moment of computation | load-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 it | load-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 judgment | metaphor |
| 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 damage | load-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 flat | load-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-once | load-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 tabayyun | load-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 capability | load-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.
+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.)
لِّيُعَذِّبَ اللَّهُ الْمُنَـفِقِينَ وَالْمُنَـفِقَـتِ وَالْمُشْرِكِينَ وَالْمُشْرِكَـتِ
(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": "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.
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.
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": "`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 --skillExtended 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.
+ +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.
+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.
+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.
+ +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.
+ +Fix the model. Let the coding agent's core be a function
+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:
+ +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 lacks | Forced by | External remedy (this architecture) |
|---|---|---|
| Persistent memory | P1 | A committed store re-injected each session (§6, A4/A5) |
| Learning from outcomes | P2 | Non-parametric experience store; optional parametric adapters (§6) |
| Imagination / world-model | P1, P3 | A typed artifact graph the agent queries before acting (§3.2) |
| Self-correction | P3 | An external verifier and a deterministic completion gate (§4, A6) |
| Impact-awareness | P1, P3 | The 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.
+ + +The architecture turns the stateless map (1) into a stateful operator by threading an external memory M through it.
+ +A cognitive substrate over a frozen model fθ is an operator
+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.
+ +| Primitive | Definition | forgekit binding | Generic binding |
|---|---|---|---|
| Π1 — persistent store | Files the agent can read/write that survive sessions and travel with the project | git repo: CLAUDE.md, docs/*.md, .claude/** | any VCS; any repo-reading agent |
| Π2 — lifecycle interception | Deterministic code executed at fixed points of the agent loop (start, end-of-turn) | hooks: SessionStart, Stop, UserPromptSubmit | pre-commit hooks; CI jobs; IDE tasks |
| Π3 — instruction channel | Standing instructions loaded into the model's context | CLAUDE.md, .claude/rules/, skills | AGENTS.md, .cursorrules, system prompts |
Π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.
+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".
+ +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.
+ +For a set X ⊆ A, the dependents operator is
+— 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
+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.
+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.
+Each faculty is a well-typed operation on M, and each will be realized by one of the algorithms A1–A7 (§6):
+ +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.
+ + +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.
+ +A substrate's behaviour-shaping is partitioned into two layers over the frozen model:
+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
+Then, for any model whose instruction-following is imperfect (p<1) and any deterministic layer that is not omniscient (cj<1 for every j):
+□
+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.
+Theorem D's equation (5) is worth reading as an engineering instrument, because it explains a lived experience and prices every design choice.
+ +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.
+ +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.
+ +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 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.
+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.
+ +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).
+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).+
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).
+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.
+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.
+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.
+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.
+The seven compose into one meta-algorithm that fits every task, from a one-line fix to a multi-file feature:
+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 TASK loop serves four invariants. Stated as logic, they port to any environment that supplies Π1–Π3.
+ +| Invariant | Statement | Kills |
|---|---|---|
| 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 — Continuity | At 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 fabrication | Every 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 currency | Facts 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
+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.
+ +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.
+ +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.
+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.
+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 Π1/Π2/Π3 throughout (§3.1). Every reference to a primitive in this paper is written Πn.
| # | Unified concept | Substrate (S) | E2E Framework (E) | forgekit (K) | Relationship |
|---|---|---|---|---|---|
| 1 | The frozen core | y = 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 modifies | identical object: all three treat the model as a fixed probabilistic map to be wrapped, not retrained |
| 2 | Impact-awareness / partial-work failure ● | Faculty: 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. |
| 3 | Memory / session-amnesia failure | Faculty: 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 it | Same 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). |
| 4 | Why assumptions happen (the root the user named) ● | M2 assumption/uncertainty gate: under-specified input -> the model confabulates a convention | amnesia 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. |
| 5 | Self-correction / verification | M6 inline verification; Prototype-II verify step; self-correction faculty | Algorithm 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 verdict | Same 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. |
| 6 | Complexity routing | M1 complexity-aware router (transparent additive rubric); Prototype-II router | Algorithm A7 KNOWLEDGE-ROUTER (where every fact lives, keeps always-loaded context bounded); System 1/System 2 effort routing; intent DFA | intent-router.sh (UserPromptSubmit hook, keyword DFA, <10ms, zero-token); effort-routing rule in CLAUDE.md; per-agent model: fields | Two 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. |
| 7 | Task decomposition | M3 task/session decomposition | HTN closure -> ordered task list (A1 output is the worklist); the meta-algorithm TASK(t) | sdlc-pilot 7-phase skill; subagents; git worktrees | Same: decompose the goal into the closure's ordered worklist before building. |
| 8 | Goal-anchoring | M4 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 VERIFY | docs/STATE.md 'Current goal' + 'Acceptance criteria'; sdlc-pilot SPEC->VERIFY gate | Substrate names the drift; framework anchors it in a persisted, re-injected Desire so every session optimizes the same target. |
| 9 | Anti-over-engineering | M5 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 defaults | Weakest-covered in all three; substrate marks it residual-gap, framework encodes it as a stewardship bound, kit as an effort-routing default. |
| 10 | World-model of the codebase | Faculty: 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.md | Same 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'. |
| 11 | Continual learning from outcomes | Faculty: 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 lessons | Reflexion rule in CLAUDE.md; STATE gotchas; agents' memory: project | Same '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). |
| 12 | Rehydration (session start) | closed-loop write-back/read-back band in the substrate architecture | Algorithm A5 CONTEXT-REHYDRATE; loader L; records git baseline for the gate | session-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). |
| 13 | Independent verification / judge | self-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 7 | Substrate 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. |
| 14 | The 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 law | DESIGN 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 layer | THIS 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. |
| 15 | The probabilistic failure model | eval honesty: perfect accuracy shows separation not a benchmark; p<1 | P(>=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. |
| 16 | Stewardship / governance boundary | STEWARDSHIP/amana wrapper (33:72) around the whole architecture | amana in I3/I4 as no-fabrication + verified-currency; least privilege, reversibility, logged rationale, scope-boundedness | committed-files-only (auditable), block-at-most-once (no nagging), fail-open safety (T2), DOCS_GUARD_DISABLE auditable escape hatch | The 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 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.
+Beyond the verses, four Qur’anic concepts structure the whole architecture, each load-bearing:
+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.
+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.
+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:
+ +| Method | Precision | Recall | F1 |
|---|---|---|---|
| Impact oracle, as shipped | 0.398 | 0.022 | 0.042 |
| grep baseline (no graph) | 0.353 | 0.573 | 0.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.
+ +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:
+ +| Configuration | Precision | Recall | F1 |
|---|---|---|---|
| As shipped | 0.398 | 0.022 | 0.042 |
| + construction fix | 0.304 | 0.242 | 0.270 |
| + sibling/forward relations, held-out | 0.305 | 0.653 | 0.416 |
| grep baseline, held-out | 0.269 | 0.601 | 0.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.
+ +Re-evaluated on eighty tasks drawn from real GitHub issues and pull requests, with every threshold frozen +at its tuned value:
+ +| Metric | Tuned set (n=30) | Held-out (n=80) |
|---|---|---|
| Gate F1 (should-ask) | 1.00 | 0.37 |
| Gate recall | 1.00 | 0.31 |
| Routing, exact tier | 1.00 | 0.53 |
| Routing, within one tier | 1.00 | 0.91 |
| Cost saving — first attempt, ungated | 62.1% | 59.5% |
| Cost saving — first attempt, correctness-gated | — | 3.6% |
| Cost saving — total pipeline spend, ungated | — | −20.2% |
| Cost saving — total pipeline spend, gated | — | 2.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.
+ +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.
+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 object | forgekit / claude-e2e-kit | Faculty / algorithm |
|---|---|---|
| Π1 persistent store | CLAUDE.md, docs/STATE.md, docs/DECISIONS.md, docs/ARCHITECTURE.md | memory |
| Π2 interception | session-context.sh (SessionStart), docs-guard.sh (Stop), intent-router.sh (UserPromptSubmit) | A5, A6, routing |
| Π3 instructions | CLAUDE.md DoD + No-assumptions + Reflexion + effort-routing; .claude/rules/ | I1–I4, M1–M6 |
| Δ* construction (A1) | /impact skill + documentation-map.md | impact-awareness |
| Verify operator (A3) | /sync-docs + doc-sync agent (project memory) | self-correction |
| Handoff (A4) / rehydrate (A5) | /handoff → STATE; SessionStart injection + /catchup | memory |
| Independent judge | reviewer agent (fresh context, adversarial, criteria-based) | self-correction |
| Phase gates | sdlc-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.
+ +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.
+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 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.
+ +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.
+| Source | ID | Grade | Note |
|---|---|---|---|
| Cognitive Architectures for Language Agents Theodore R. Sumers, Shunyu Yao, Karthik Narasi, 2023 | 2309.02427 | confirmed | Retrieved 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.03629 | confirmed | Retrieved 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.15594 | confirmed | Retrieved 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.08500 | confirmed | Retrieved 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.15793 | confirmed | Retrieved 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… |
| Voyager: An Open-Ended Embodied Agent with Large Lan Guanzhi Wang, Yuqi Xie, Yunfan Jiang et al., 2023 | 2305.16291 | confirmed | Retrieved 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.26275 | confirmed | Retrieved 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.05111 | confirmed | Retrieved 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.10934 | confirmed | The 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 | — | traceable | Classical 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 | — | traceable | Classical 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 | — | traceable | Classical 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 | — | traceable | Foundational 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 | — | traceable | No 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.… |
| PDCA / Plan-Do-Check-Act cycle (the 'Shewhart Cycle' Shewhart, W.A. (originator); Deming, W.E. (pop, None | — | traceable | Management/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… |
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.
+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.
+