# PREFRONTAL: The Recipe Execution Substrate — How a Composable, Self-Authoring, Looping Workflow Engine Becomes an Agent's Executive Function: v4.6 → v4.7

From v4.6 (2 Jun) to v4.7 (14 Jun): 9,006 words to 12,193 words, 3,259 words in new or rewritten paragraphs and 72 taken out, 73 paragraphs changed.

## Change note of v4.7

**Five new parts: anti-triggers, skill calls, budgets, load rules, a doubt critic**

The longest step since v4.0: about 3,200 words added. It writes up work recorded in the folder's notes between 4 and 13 June.

- Recipes can say when they must not match (anti-triggers), and the scorer subtracts for them.
- A recipe step can call a skill from a shared library (a third step type besides merge and sub-recipe call).
- Effort routing moves from advice to an enforced budget, and a recipe can declare where it may run.
- A completion critic that checks the work without inheriting the worker's framing.
- Saved plans can be rolled back, and a new part on compressing artifacts without losing them.
- Failures inside a parallel fan-out are reported per branch.

## Changed paragraphs

Marks: [-removed-] {+added+}.

### Abstract

A recipe is a structured workflow: ordered steps, tool hints, success gates, and failure handlers, written as a portable document rather than as code. The substrate does six things with recipes that together make them an execution engine rather than a static library. (1) It **matches** the user's intent to recipes with a fuzzy, stemmed, edit-distance-tolerant scorer that reports a confidence [-tier,-] {+tier — and that admits negative as well as positive evidence, so a recipe can declare the prompts for which it must *not* be chosen —+} and seeds a plan automatically at the start of every turn. (2) It **composes** recipes from recipes — a recipe may merge another recipe's steps into its own at plan-build time, or call a sub-recipe at runtime, both cycle- and depth-guarded, exactly as functions call functions. (3) When nothing matches, it **authors** a new recipe on the fly, validates it, persists it, and makes it matchable on the very next turn — closing the loop on its own coverage gaps. (4) It supports bounded **loops** over steps (run *N* times / until-dry / until a marker appears), the element that lifts recipes from straight-line checklists to a structured execution substrate and closes the long-standing structural gap against hand-coded agent workflows. (5) It **routes effort dynamically**, classifying each turn as trivial / standard / deep / ultra and using that classification to *drive* the turn — model tier, thinking budget, orchestration mode, and token generosity all scale to the work. (6) It makes all of this **observable** through a dedicated RECIPES panel that renders the provenance trail (searched → matched → merged → composed → authored), per-subagent vitals, and the compact-versus-expanded decision trail, while keeping orchestration mechanics out of the substantive chat.

### Abstract

The thesis is that intelligence in a deployed agent is not primarily a property of the model. It is a property of the *structure the model executes inside* — and that structure is most powerful when it is composable, self-authoring, looping, effort-adaptive, and observable. This paper specifies that substrate, grounds the brain metaphor in concrete mechanism, gives language-agnostic pseudocode for each of the six capabilities, and reports which of the substrate's harder extensions — durable resume, a self-improving library, external acquisition, and a versioned marketplace — are implemented and running, and which one — searched execution — remains specified but [-unbuilt.-] {+unbuilt. Throughout, we position the substrate against the fresh open-source ecosystem it shares a problem space with — chopratejas/headroom's reversible context-compression and addyosmani/agent-skills' anti-trigger and load-constraint discipline — and fold their stronger ideas into the substrate's own seams where they sharpen a claim.+}

### 1.3 The gap this paper closes

1. **Matching** turns "the agent should pick the right playbook" into "the right plan is already seeded before the agent's first token," via a fuzzy scorer with confidence [-tiers.-] {+tiers that admits both positive evidence (tag/title/summary hits) and negative evidence (a recipe's own anti-triggers).+} (Task-set selection.) 2. **Composition** lets recipes be built from recipes, both statically (step-merge) and dynamically (runtime sub-recipe calls), so workflows reuse workflows instead of duplicating them. (Hierarchical program structure.) 3. **On-the-fly authoring** lets the substrate write a new recipe when none fits, validate it, and add it to the library mid-conversation — so coverage gaps heal themselves. (Skill acquisition.) 4. **Loops** let a step repeat under a bounded condition, the single feature that elevates recipes from straight-line sequences to a substrate expressive enough to encode iterative work. (Sustained, monitored repetition.) 5. **Effort routing** classifies the turn and *drives* it — choosing model tier, thinking budget, orchestration mode, and token generosity to fit. (Effort regulation.) 6. **Observability** surfaces the whole life-cycle in a dedicated panel, so a human can see what program is running, where it is, and how each worker is doing, without that machinery polluting the substantive answer. (Metacognitive monitoring.)

### 2.1 The cycle

{+When the EXECUTE phase fans a step out across multiple subagents, the substrate treats each branch as a settled result rather than a value-or-silence: a branch that throws surfaces a typed, index-attributable failure rather than vanishing as a null, the result order and the await-all barrier are preserved, and the step can settle its survivors and report a partial outcome instead of failing wholesale. Parallel execution under the substrate is therefore partial-failure-tolerant and attributable, not all-or-nothing-and-silent — a reliability property a real execution engine must have, and the precondition for the per-subagent vitals the panel renders (§8.3).+}

### 2.2 Where the structure comes from, and when it is cheap

Third, **follow-up cognition reuses context.** When a phase does require a model call (a reflection pass, or a tiebreak judge when two recipes score within a hair of each other), that call shares almost the entire context of the main turn — the same identity, the same retrieved memory, the same conversation. [-Under context-caching pricing, a-] {+A+} follow-up call that differs only in its instruction [-costs a small fraction of-] {+is therefore far cheaper than+} a fresh one. The executive layer is [-therefore-] cheap precisely where it is invoked most.

### 2.3 Plans as the runtime trace of recipes

Because the plan is persisted and seeded automatically at turn start, the substrate gains crash-resilience: if the process restarts mid-task, there is an `in_progress` plan on disk describing exactly where the work was, and the executive resumes from it rather than re-deriving intent from scratch. The plan schema reserves a per-step `artifact` field and a plan-level `currentStep` cursor for exactly this purpose; Section 11.1 reports the resume path that reads them [-back.-] {+back, and how each carried-forward artifact is made a *reversible* pointer rather than a lossy truncation.+} The plan *is* the agent's working memory, [-externalised.-] {+externalised — and §11.1 is what makes that claim lossless rather than approximate.+}

### 3.2 Fuzzy, stemmed, edit-distance scoring

``` function SCORE_RECIPE(prompt_tokens, recipe): score <- 0 for tag in recipe.tags: if tag is multi-word: if prompt contains tag as a phrase: score += 5 else if any prompt token equals tag: score += 3 else if any prompt token FUZZY-MATCHES tag: score += 2 for word in tokens(recipe.title): if any prompt token equals word: score += 2 else if any prompt token FUZZY-MATCHES word: score += 1 for word in tokens(recipe.summary): if any prompt token FUZZY-MATCHES word: score += 1 {+for anti in recipe.not_when: # negative evidence if anti is multi-word and prompt contains anti as a phrase: score -= 5 else if any prompt token FUZZY-MATCHES anti: score -= 3+} return score

### 3.3 Negative evidence — anti-triggers

{+### 3.3 Negative evidence — anti-triggers+}

### 3.3 Negative evidence — anti-triggers

{+A purely *additive* matcher has a real expressive gap: it can score a recipe upward on tag, title, and summary overlap, but it has no way for a recipe to declare *the prompts for which it must not be chosen*. The consequence is concrete: a recipe that fuzzily shares tokens with an out-of-scope prompt can win on lexical score alone, and the only correction available is the low-confidence advisory (§3.3 confidence tiers, below) — a soft signal, after the fact. The discipline that closes this gap is borrowed from addyosmani/agent-skills (Addy Osmani's agent-skills plugin), where every skill carries an explicit "When NOT to use" anti-trigger section that is as load-bearing as its triggers.+}

### 3.3 Negative evidence — anti-triggers

{+The substrate adopts the same idea as a first-class matcher input: a recipe may declare a `not-when:` set — anti-triggers expressed exactly like tags — and a fuzzy hit against an anti-trigger *subtracts* from the score (above), with a strong-enough negative hit able to veto a tier promotion outright (§3.4). This makes task-set selection bidirectional: a recipe is now defined as much by the prompts it disclaims as by the prompts it claims. The anti-trigger is the executive analogue of *task-set inapplicability* — the recognition that a familiar-looking situation is, on a salient cue, the wrong situation for this program. The negative path reuses the same fuzzy/stemmed machinery as the positive path, so it inherits the same typo- and inflection-tolerance and adds no new scoring primitive.+}

### 3.4 Confidence tiers and what they gate

### [-3.3-] {+3.4+} Confidence tiers and what they gate

### 3.4 Confidence tiers and what they gate

Raw scores are reduced to a **confidence tier** — `none`, `low`, or `high` — because the executive must behave differently depending on how sure it is, just as a person hesitates before committing to an ambiguous task framing. A tier is `high` only when the leader clears the threshold with margin *and* leads the runner-up clearly; everything else that clears the bar is [-`low`:-] {+`low`; and a strong anti-trigger hit on the would-be leader caps it at `low` even when it clears on positive evidence alone:+}

### 3.4 Confidence tiers and what they gate

``` function CLASSIFY_CONFIDENCE(matches, threshold): if matches is empty: return "none" top <- matches[0].score second <- matches[1].score or 0 {+if matches[0].anti_vetoed: return "low" # anti-trigger caps promotion+} if top >= threshold + 3 and top - second >= 2: return "high" # clear leader return "low" # barely over, or a tie ```

### 3.4 Confidence tiers and what they gate

- **High** confidence: a clear leader well above the [-bar.-] {+bar, with no anti-trigger veto.+} Seed the plan silently and proceed. - **Low** confidence: barely over the bar, [-or-] a near-tie among [-candidates.-] {+candidates, or a leader that an anti-trigger flagged.+} Seed the best, but surface the alternatives; optionally break the tie with a short, context-shared judge call. - **None**: nothing clears the bar. This is not a dead end — it is the *authoring opportunity* (Section 5).

### 3.5 Auto-seeding at turn start

### [-3.4-] {+3.5+} Auto-seeding at turn start

### 4.3 Calling the library — `invoke skill:`

{+### 4.3 Calling the library — `invoke skill:`+}

### 4.3 Calling the library — `invoke skill:`

{+There is a third leading directive, and it completes the reuse vocabulary. Where `uses:` calls a *recipe* (another structured workflow) and `composes:` inlines one, `invoke skill:<id>` calls a typed **stdlib skill primitive** — a single vetted, reusable routine with a declared output schema, drawn from a deposited skill library rather than synthesised on the spot. The directive parses exactly like its siblings (leading-directive-lines only, so a prose or fenced mention does not fire) and is recognised by the runner's scanners regardless of directive order, so `loop:`, `uses:`, and `invoke skill:` can be combined on the same step.+}

### 4.3 Calling the library — `invoke skill:`

{+The execution path injects the skill's documented procedure into the worker's task, adopts the skill's output schema (a step's own `out:` port may *narrow* it but not widen it), validates the produced artifact against that schema, and — on a validation miss — redispatches within a bounded budget before persisting the typed artifact. On a missing or deprecated skill the step **fails closed** rather than silently degrading to a free-form dispatch. The typed-output machinery this rides on (the schema, the validate→redispatch→persist path) is specified by the companion work on typed, composable recipes; here it matters only that the substrate can now invoke a vetted routine, not merely inline a sub-recipe.+}

### 4.3 Calling the library — `invoke skill:`

{+The distinction is worth stating because it changes what "sequence + branch + bounded iteration" (§6.1) can express: the minimal vocabulary now includes a **library call** to a typed primitive. The executive can reach for a known-good routine the way a programmer reaches for a standard-library function, instead of re-deriving it inline every time — and because the skill is typed, its output is checkable, which a free-form sub-recipe's is not.+}

### 4.3 Calling the library — `invoke skill:`

```{=latex} \begin{figure}[H] \centering \includegraphics[width=\linewidth,height=0.85\textheight,keepaspectratio]{images/fig-composition.pdf} \caption{Composition algebra: static step-merge flattens sub-recipe steps into one plan at build time (de-duplicated, depth- and cycle-guarded); a runtime call transfers control into a nested plan on a child session and folds its terminal note back as the step's [-outcome. Both-] {+outcome; an \texttt{invoke skill:} directive calls a typed stdlib primitive whose output is schema-validated. All+} are bounded by a depth cap and a cycle guard.} \end{figure} ```

### 5.1 Closing the no-match loop

The executive analogue here is skill acquisition: when a person meets a task for which they have no rehearsed program, they construct one — and they *keep* it, so the next encounter is no longer novel. A recipe substrate that merely shrugs on no-match has no way to grow; its coverage is frozen at whatever a human last hand-authored. The substrate closes this [-loop.-] {+loop two ways, and the distinction between them is real.+}

### 5.1 Closing the no-match loop

{+**Authoring from intent.**+} When matching returns `none` for a non-trivial turn, the turn-start hook injects a `recipe-gap` directive into the agent's context, instructing it to compose a new recipe specification — a slug, title, summary, tags, and three-to-seven ordered steps with tool hints and done-when criteria — and to author it. Authoring is a single call that **validates, assembles, and persists** a real recipe document. {+The LLM *synthesises* the steps from the prompt.+} From the next turn onward, that document is in the index and matchable like any hand-written [-recipe. The coverage gap heals itself, in the conversation that exposed it.-] {+recipe.+}

### 5.1 Closing the no-match loop

{+**Authoring from the library.** There is also a deterministic sibling: rather than synthesising steps, the substrate can *mechanically wire existing typed primitives into a runnable plan*. A compose call takes the query, searches the deposited skill library semantically, and emits one `invoke skill:` step per hit in rank order, then runs the result through the same validator and persistence path. This is authoring *from the library* — no LLM synthesis, fully determined by what the skill search returns — and the no-match flow prefers it: on a gap the substrate tries compose-from-library first (when the skill search returns relevant primitives) before falling through to from-scratch synthesis. Both stamp the result with an authored-by marker, so the §5.3 never-overwrite-curated guard holds for either path. The coverage gap heals itself, in the conversation that exposed it — sometimes by writing new steps, sometimes by wiring known-good ones.+}

### 5.2 Validation — the gate against a corrupt library

Three checks are load-bearing. The **slug** is also the directory name, so it must be traversal-safe — a self-authoring system that accepted `../../etc` as a slug would be a security hole, not a feature. The **phantom-heading** check forbids a numbered markdown heading inside a step body, because the runner splits steps on exactly that pattern; an un-checked heading would silently desynchronise the step count from the parallelism map. The **parallelism coverage** check guarantees the fan-out groups reference every step once and only [-once.-] {+once. The same validator gates *both* authoring paths and every imported recipe (§11.3), so there is a single chokepoint through which no malformed or unsafe recipe can reach the library.+}

### 5.3 Provenance and the never-overwrite rule

{+Two persistence properties keep this discipline durable. First, provenance lives in the recipe's own frontmatter — authored-by, and, for a composed recipe, the lineage of which skills and which source query produced it — so a recipe's history is a property of the artifact, not a sidecar that can drift from it. Second, a continuously-edited library cannot live only inside the packaged tree, because an upstream update would clobber operator edits; the substrate therefore keeps a writable **out-of-repo overlay** that the runner, the read RPC, and the save endpoint all honour with **read-precedence** over the bundled copy (first-readable-wins, and an in-place edit is write-redirected to the overlay). Separating the user-customised overlay (writable, precedence) from the packaged baseline (read-only, replaceable) is what lets the library evolve continuously without losing local adaptation on every sync — the substrate's "captured behaviour" survives the fork's own updates.+}

### 6.2 Three bounded loop modes

A step whose leading directive is `loop:` repeats — whether the step is a plain worker [-dispatch-] {+dispatch, an `invoke skill:` call,+} or a `uses:` sub-recipe call — under one of three termination conditions:

### 6.3 Bounded by construction — the anti-runaway guarantee

A self-driving loop in an autonomous agent is a liability unless it is *provably* bounded. Every loop is therefore clamped twice: a per-loop {+working maximum (a+} default [-maximum-] of five iterations, {+or a ceiling derived from the live situation — prior iterations, the recipe's empirical success rate, and a convergence heuristic — rather than a frozen quantity),+} and an absolute hard ceiling of twenty-five that no recipe — authored or hand-written — can exceed. {+The derived bound is the principled stopping point; the frozen twenty-five is only a structural safety net (the policy of deriving bounds from the situation rather than freezing a threshold is the subject of separate work, and we adopt it here without re-deriving it).+} The count is clamped into `[1, HARD_CAP]` at parse time, so even a maliciously or accidentally enormous `count` collapses to the ceiling rather than running away. The substrate is expressive enough to iterate and *constitutionally incapable* of spinning forever — the executive analogue of perseveration control, the prefrontal function that stops a behaviour that has stopped being productive.

### 6.3 Bounded by construction — the anti-runaway guarantee

[-`loop:`-] {+`loop:`, `uses:`,+} and [-`uses:`-] {+`invoke skill:`+} compose on the same leading directive lines, so the most powerful single construct the substrate offers is "loop a whole sub-recipe until it reports dry" — iterate an entire nested workflow to fixpoint, bounded.

### 7.4 From guidance to a binding budget

{+### 7.4 From guidance to a binding budget+}

### 7.4 From guidance to a binding budget

{+The table above describes *guidance*, and guidance has no teeth: a runaway worker can ignore the token-generosity lever and keep spending. The substrate closes that gap with a per-spawn **enforced** budget. The budget itself is derived from the live situation — fan-out width set by the required-field surface, by whether the step invokes a skill, by the recipe's empirical fitness (wider when the recipe is shaky), and by token affordability — not frozen, with a structural ceiling only as a backstop. A runner watchdog recomputes the budget on each tool result and at each assistant-message start, and on exhaustion it does not guillotine the work: it **settles a partial** result, records terminal lifecycle metadata, and stops the spawn gracefully (with a `budget-exhausted` stop reason) rather than killing a near-done task. The token-generosity lever in §7.3 is therefore an enforced lever, not advice — the executive actually withdrawing metabolic budget rather than merely recommending it, with adaptive pressure before a graceful cliff. The honest seam: the tool-whitelist and budget validation land at the spawn boundary, the enforcement at the run watchdog; §11 reports this with its LIVE status.+}

### 7.5 Where a recipe may run — load constraints

{+### 7.5 Where a recipe may run — load constraints+}

### 7.5 Where a recipe may run — load constraints

{+A second discipline borrowed from addyosmani/agent-skills belongs here: each of Addy Osmani's skills declares *where* it may load — the main orchestrator versus a subagent — with a documented degraded fallback for the unmet case. The substrate dispatches the same recipe steps to the main worker and to fan-out subagents (the parallel and full-workflow modes above) with no notion that a given recipe or step might be invalid in a subagent context — a step that needs the orchestrator's privileges or its conversation-level view will simply misbehave when fanned out. A per-recipe (or per-step) **load-constraint** declaration, with a degraded fallback when the constraint is unmet, is the executive analogue of task-set *applicability*: the recognition that a program is valid in one execution context and not another. It belongs in the recipe schema (Appendix B) and is consulted on the dispatch path, so that fanning a step out is gated on that step actually being safe to run there — and falls back gracefully, rather than silently, when it is not.+}

### 8.3 What the panel renders

- **Discovery.** Catalog size, the scored candidate recipes with their [-scores,-] {+scores (including any anti-trigger penalty applied),+} the matching threshold, and what was selected (or a visible NO-MATCH). This makes task-set selection auditable: a wrong recipe choice {+— or a recipe that *should* have been vetoed by its anti-trigger —+} is now a thing you can *see*, not infer. - **Composition.** When more than one recipe contributed (via match-merge or `composes:`), a summary of which recipes contributed how many steps, and how many steps survived de-duplication. Each step row in the plan carries a badge naming its source recipe, so provenance is not lost in the merge. - **Plan with per-step status.** The ordered steps, the single active step, and each step's `pending / in_progress / done / error` status — the externalised working-memory cursor. {+A read-only resolver can return the *actual parsed program* (each step's title, prose, the skill it invokes, the sub-recipe it uses, its ports), so the panel renders the program the substrate is executing, not merely a trail of what it did; each step is attributed to the turn and to the skill executing it.+} - **Per-step fan-out — subagent vitals.** Under the active step, one row per dispatched subagent: a stable colour derived from its run identity, its model, its status, elapsed time, and the tool it is currently using. {+Because fan-out is settled-not-silent (§2.1), a failed branch renders *which* unit failed and *why* (a typed error kind) rather than vanishing.+} This is where "the agent is working" becomes "this subagent, on this model, is reading this file, and has been for forty [-seconds."-] {+seconds" — and "that subagent failed, here, for this reason."+} - **The provenance / decision trail.** A running log of the executive's decisions, each tagged with a small fixed vocabulary of verbs — **searched**, **matched**, **merged**, **composed**, **authored**, plus the in-flight verbs **dispatch / complete / note / transition / warn**. Reading the trail top to bottom reconstructs exactly how the substrate reasoned its way from prompt to plan to execution.

### 8.3 What the panel renders

```{=latex} \begin{figure}[H] \centering \includegraphics[width=\linewidth,height=0.85\textheight,keepaspectratio]{images/fig-panel.pdf} \caption{The RECIPES panel sits beside the chat, divided by the split-of-concerns boundary: the chat carries the substantive answer, the panel carries orchestration mechanics. The panel stacks Discovery (catalog size, scored [-candidates,-] {+candidates with anti-trigger penalties,+} threshold, NO-MATCH), Composition (source badges, de-dup count), the Plan with per-step [-status,-] {+status and the parsed program,+} per-step Fan-out (one subagent-vitals row per [-dispatch),-] {+dispatch, typed failures attributed),+} and the compact, expandable decision trail.} \end{figure} ```

### 9.3 Learned action gating

{+This integration is no longer design-only at the enforcement layer. The affective gate now *bites*: native enforcement runs as a pre-tool-use hook that can deny a tool call before it executes, even under a permissive run posture, rather than merely scoring it and logging. The consequence for the substrate's reliability story is that a recipe's structural gates and the learned affective gate are now both binding — the *done-when* discipline shapes what the worker attempts, and the affective gate can refuse the attempt at the tool boundary — so "sits beneath the worker's tool calls" describes an enforced floor, not an advisory observer.+}

### 9.4 Deliberation and budget

When a step is genuinely high-stakes, it can fan out to multiple models for a structured deliberation and synthesise the result — the recipe step is the natural activation point for cross-model debate that otherwise has no obvious trigger. And the effort router's model-tier choices are exactly where budget-aware prompting belongs: under budget pressure, the same classifier that picks "maximum" can be told to step down a tier, so the executive regulates spend as well as [-effort.-] {+effort (the binding form of which is §7.4).+}

### 9.5 Reflection, orchestrated

[-### 9.5 Reflection, orchestrated-]

### 9.5 Reflection and self-supervised completion

{+### 9.5 Reflection and self-supervised completion+}

### 9.5 Reflection and self-supervised completion

{+The reflection phase's forward-looking sibling is *completion supervision*: judging not whether a step finished but whether the **whole task** is actually done, and re-engaging effort until it is. The substrate runs this as a critic at the end of an ultra-tier turn (§7.3), and the discipline it should follow is the subject of §9.6 — because how a completion critic is structured determines whether it can be fooled.+}

### 9.6 Doubt-driven verification — a completion critic that cannot inherit the worker's framing

{+### 9.6 Doubt-driven verification — a completion critic that cannot inherit the worker's framing+}

### 9.6 Doubt-driven verification — a completion critic that cannot inherit the worker's framing

{+A completion critic that judges the task *inside the same run and chat window* inherits the worker's framing: it sees the producing reasoning, and reasoning that talked itself into "mostly done" tends to talk the critic into it too. A loop-until-a-completion-marker critic — the natural shape, built directly from the substrate's own `loop: until MARKER` vocabulary (§6.2) — is a real improvement over no critic, but it shares this blind spot: it presses "is the whole task done?" against a context that already believes the answer is yes.+}

### 9.6 Doubt-driven verification — a completion critic that cannot inherit the worker's framing

{+The sharper discipline, drawn from the doubt-driven-development recipe in addyosmani/agent-skills, is to put a **fresh-context** boundary between the work and its review. Its loop is CLAIM → **EXTRACT** (reduce the work to its artifact and its contract, with the producing reasoning stripped out) → **DOUBT** (a fresh-context adversarial reviewer that never saw the reasoning re-examines the artifact cold) → **RECONCILE** (each finding is classified against the artifact text, trivial versus non-trivial) → **STOP** (explicit termination when only trivial findings remain, at a three-cycle cap, or on user override, with stated criteria for what counts as a non-trivial decision). The key mechanism a same-context critic lacks is exactly that EXTRACT/DOUBT boundary: stripping the reasoning and reviewing the artifact cold is structurally harder to fool than asking the producing context to grade itself. Its bounded STOP rule (trivial-only / three-cycle / override) is the same derived-ceiling discipline the substrate already uses for loops (§6.3), so it imports cleanly.+}

### 9.6 Doubt-driven verification — a completion critic that cannot inherit the worker's framing

{+This fits the substrate without new machinery: doubt-driven verification is naturally a `uses:`-callable sub-recipe that composes after a worker step, so an ultra-tier plan can end with `uses: doubt-driven-verify` exactly where it would otherwise end with a same-context completion check. And it pairs with the now-enforced affective gate of §9.3: where the structural critic re-reviews the *artifact* cold, the affective gate refuses dangerous *actions* at the tool boundary — a structural completion gate and an enforced safety gate biting from two different directions on the same execution.+}

### 10.1 First-attempt accuracy

| Failure mode (executive deficit) | Mechanism that prevents it | |----------------------------------|----------------------------| | Fixing before reproducing (impulse) | debug recipe's *reproduce* gate before *fix* | | Coding before designing (impulse) | feature recipe's *design* gate before *implement* | | Searching before scoping (impulse) | investigate recipe's *scope* gate before *search* | | {+Selecting a look-alike but wrong program (mis-recognition) | a recipe's `not-when:` anti-trigger vetoing a lexical false-positive | |+} Declaring done before verifying (premature closure) | every recipe's terminal *verify* [-step-] {+step, hardened by a fresh-context doubt-driven critic+} | | Stopping an iterative task early (under-persistence) | `until-dry` loops that run to exhaustion | | Over- or under-investing effort (mis-regulation) | effort router driving model/thinking/tokens per [-tier-] {+tier, enforced by the spawn budget+} |

### 10.2 Matching quality

Matching is evaluated on a labelled set of prompts with a known correct recipe (including paraphrases, inflections, and typos), reporting top-1 and top-3 accuracy and, separately, the **NO-MATCH precision** — how often a true coverage gap is correctly flagged versus a real match being missed. The {+anti-trigger mechanism is evaluated on its own axis: a held-out set of *near-miss* prompts that lexically resemble a recipe but lie outside its scope, measuring how often the `not-when:` penalty correctly demotes or vetoes the look-alike without suppressing genuine matches (anti-trigger precision/recall). The+} confidence tiers are evaluated by calibration: high-confidence selections should be right far more often than low-confidence ones.

### 10.3 Authoring quality and library health

For on-the-fly authoring: the rate at which an authored recipe is re-matched and successfully reused on subsequent turns (the loop-closure rate), the validation rejection rate (how often a draft is malformed), and a periodic audit of library health — duplicate slugs, dead recipes that never match, and recipes whose steps never satisfy their [-gates.-] {+gates. Authoring-from-library (compose) is evaluated against authoring-from-intent on the same gaps: how often the deterministic, skill-wired plan succeeds where the synthesised one would, and vice versa.+}

### 10.4 Loop termination

Every loop mode is checked for the two failure directions: premature termination (an `until-dry` loop that stops while work remains) and non-termination (caught structurally by the hard cap, but worth measuring as *how often the cap is the thing that stops a loop*, which signals a mis-specified [-condition).-] {+condition or a too-tight derived ceiling rather than a real fixpoint).+}

### 10.5 Cost, latency, and the artifact-compression frontier

### 10.5 [-Cost-] {+Cost, latency,+} and [-latency-] {+the artifact-compression frontier+}

### 10.5 Cost, latency, and the artifact-compression frontier

Because matching is local and effort-gated, the per-turn overhead should be near-zero for trivial turns and small for the rest. The evaluation reports overhead as a function of effort tier [-and of context-cache hit rate,-] and the latency the executive adds *before* visible work — which, for complex turns, is expected to be repaid many times over by fewer wrong turns and the user's ability to watch progress rather than wait blindly.

### 10.5 Cost, latency, and the artifact-compression frontier

{+A second axis becomes measurable once the carry-forward artifact (§11.1) is compressed rather than truncated: the **compression-versus-accuracy frontier**. The relevant external reference point is chopratejas/headroom (Tejas Chopra et al.), whose reproducible eval suite reports 60–95% token savings at roughly zero accuracy delta on standard benchmarks (GSM8K, TruthfulQA, SQuAD, BFCL) for its reversible Compress-Cache-Retrieve scheme. The substrate's artifact spine is the natural place to import that measurement: for each artifact content-type (a code done-note, a JSON tool result, a diff), report the tokens saved by the carry-forward compressor against the rate at which a later step had to *retrieve* the verbatim original — a concrete compression-vs-recovery curve, rather than the bare assertion that overhead is "small."+}

### 11.1 Durable checkpointing — implemented, and now reversible

### 11.1 Durable checkpointing — [-implemented-] {+implemented, and now reversible+}

### 11.1 Durable checkpointing — implemented, and now reversible

The paper's claim is that "the plan *is* the agent's working memory, externalised" (§2.3). For that to be true, the durable spine must be read back, not merely written, and it is. The runner reads an `in_progress` plan whose recipe reference matches the current run and resumes from its `currentStep` cursor, skipping any step already marked `done`; on each step's success it persists a [-bounded-] digest of the done-note [-— capped at a few hundred characters, truncated on a word boundary —-] into the reserved per-step `artifact` field, and it carries the prior steps' artifacts forward as upstream context for the step that follows. A sub-recipe call bubbles its nested plan's terminal result up as the parent step's artifact. No schema change was needed — both the `artifact` field and the `currentStep` cursor already existed.

### 11.1 Durable checkpointing — implemented, and now reversible

Two policy choices keep resume safe. Resume is **opt-in, not automatic**: a bare run always force-restarts at step 0, and the runner re-attaches to an existing plan only when an explicit `resume` flag is passed *and* the recipe reference matches — so a stale plan from an unrelated prior session is never silently picked up. And a long-polling step emits a checkpoint heartbeat after a fixed interval, so a guardian can distinguish a step that is genuinely working from one that has stalled, against the per-step ten-minute [-wall. The one residual risk is lossiness — the bounded artifact digest can drop context a later step needs — which is mitigated by keeping the full done-note in the plan body and only the digest in the bounded field. This is what makes "the plan is the program counter" a guarantee rather than a description.-] {+wall.+}

### 11.1 Durable checkpointing — implemented, and now reversible

{+The honest residual risk in earlier versions of this design was **lossiness**: a blind char-bounded truncation of the done-note can drop context a later step needs, and the only mitigation was keeping the full note in the plan body while the bounded field carried a one-way truncation. The principled fix is to make the carry-forward *reversible* and *content-type-aware*, and the external system that solves exactly this problem is chopratejas/headroom's **Compress-Cache-Retrieve** (CCR): the original artifact is cached verbatim, a compressed surrogate is what flows forward, and a later step that needs the dropped detail *retrieves the original on demand* rather than living with a lossy truncation. CCR also ships per-content-type compressors — AST-aware code compression (via tree-sitter), statistical JSON-array crushing, and log/diff/text handlers — which map directly onto the substrate's artifact payloads, where a blind char-truncation is worst *exactly* when the artifact is structured (a truncated code block or JSON array loses its tail wholesale). The §11.1 digest accordingly becomes content-type-aware (compress a code artifact by its AST, a JSON artifact by array-crushing, prose by summary) with the verbatim original cached behind a retrieve seam.+}

### 11.1 Durable checkpointing — implemented, and now reversible

{+The division of labour is the honest part. The substrate owns the *structural* unit — the plan/step/artifact spine, and the decision of *when and what* to checkpoint, bounded and attributed per-step against a typed plan. CCR (or any reversible compressor) owns the *content-layer* transform — compressing any artifact generically and serving its original back on demand, with a measured accuracy-delta to back the trade. What the substrate does that headroom does not: bound, attribute, and resume the artifact per-step against a typed plan. What headroom does that the substrate did not: make the carry-forward reversible and content-type-aware with a measured accuracy-delta eval. Folding CCR into the artifact seam is what turns "the plan is the program counter" from a lossy description into a lossless guarantee — and it is also what makes §10.5's compression-vs-recovery curve measurable.+}

### 11.2 The self-improving library — implemented, live end-to-end

### 11.2 The self-improving library — [-implemented-] {+implemented, live end-to-end+}

### 11.2 The self-improving library — implemented, live end-to-end

Section 5 makes the library self-*expanding* (it authors when nothing matches) and Section 9.5 makes it self-*updating* (a reflection pass can recommend a change). The third axis is self-*improvement*: feeding real execution outcomes back into the matcher so its scoring weights are not purely hand-tuned. That loop is [-closed,-] {+now closed and live producer-to-matcher,+} with a deliberate division of labour between subsystems. A background consolidation layer — the offline process that runs between turns to compact and learn from accumulated experience — owns the *offline* measurement: it distils a per-recipe **fitness** from accumulated execution episodes — success rate, latency, token cost. Each episode attributes to a recipe only via an explicit `recipe:<owner/slug>` {+attribution+} tag the runner [-sets-] {+stamps onto the run's event store+} at [-dispatch,-] {+run start,+} so an untagged episode is never counted against any recipe (no false [-attribution).-] {+attribution); the producer seam that earlier only reached the observability trail now reaches the episode store, so the consolidation pass actually credits the outcome and the matcher reads a non-empty fitness, keyed by the full `owner/slug` so two owners sharing a slug do not cross-pollute.+}

### 11.2 The self-improving library — implemented, live end-to-end

The matcher reads that fitness through a single injected lookup seam and folds it in *after* the lexical base score, with the lexical base preserved as a **floor** — empirical evidence can lift a proven recipe but cannot bury a lexically-relevant one whose fitness is merely unknown or low. The precedence is strict: lexical base [-first,-] {+first (including any anti-trigger penalty, §3.3),+} then the empirical-fitness adjustment, then a small clamped marketplace-popularity tie-breaker last (§11.4). A recipe with no fitness record yet contributes a neutral zero, so a cold library behaves exactly as the pure lexical matcher did. {+Beyond matcher weights, the library can now *grow and promote reusable primitives*, not only recipes: a deposited skill library accepts new typed primitives, and a candidate is promoted only when its measured success rate clears a bar set against the library's *current* success-rate distribution (a fitness bar measured against the live distribution rather than a hardcoded threshold; the no-frozen-bound policy is owned by separate work), with a never-delete archive making the deposit reversible.+} The honest caveat survives: a closed plan's outcome reflects the *worker's* execution, not whether the *recipe* was the right structure — so the design treats inferred outcome as weaker evidence than an explicit verdict would be. NO-MATCH mining — bucketing the accumulated no-match log by normalised intent and proposing a recipe to author {+(preferring compose-from-library, §5.1)+} once a bucket crosses a threshold — is the remaining active-authoring step that this machinery is built to support.

### 11.3 External acquisition — implemented

[-Three-] {+The same external ecosystem that supplies importable content also supplies *discipline* the substrate has adopted natively rather than imported as data: addyosmani/agent-skills' anti-trigger and load-constraint conventions (now §3.3 and §7.5) are a case of treating a fresh open-source corpus as a source of mechanism, not merely of bridgeable artifacts. When such a corpus *is* bridged, three+} guards make importing untrusted content safe. Bridged recipes are stamped [-`authored-by: cc-bridge`, marking them distinguishable and-] low-trust against the curated [-set.-] {+set, marking them distinguishable.+} Transpilation is heuristic — a skill documents *capability*, not always an ordered procedure — so a bad transpile is caught by the same validator that gates hand-authored recipes, and a malformed skill is rejected before any file is written. And because the sandbox-path resolver blocks `../` but not symlinks, the importer refuses to follow a symlinked `SKILL.md` (or any symlinked component of its path) rather than read through it. Namespacing by owner keeps an imported `code-review` from shadowing a curated one. The one genuinely open question is policy, not engineering: whether bridged recipes are matchable on import or quarantined until a human promotes them.

### 11.4 The versioned marketplace — implemented (client side)

The design's contract under failure is the load-bearing part: when the marketplace fetch fails, resolution degrades to the last cached copy — within or even past the TTL — and **never throws**, so an outage degrades a match to local cache rather than hard-failing a turn. Discovery folds a small **clamped** popularity bonus into the matcher score through the *same* post-base adjustment seam as the fitness feedback (§11.2), so there is exactly one place that perturbs base scores. The bonus is additive and hard-clamped to a tiny band — on the order of a fifth of a point against a scale where a single exact tag hit is worth several — with rating (0–5) supplying most of it and download count adding only a gentle log-scaled nudge. A merely-popular recipe can therefore never override a genuine text [-mismatch-] {+mismatch, an anti-trigger veto,+} or out-rank a recipe with stronger empirical fitness. Authored recipes are still never auto-published — publishing stays an explicit human action (§5.3) — and only the frontmatter owner may publish a new version of a slug. The marketplace *backend* itself is a separate deliverable outside the substrate; this is the client-side half.

### 11.5 Bounded search (ToT/LATS) — the one open gap

Some of the raw material is already present: the matcher returns a ranked top-N with confidence, so "alternate recipes" is just consuming the list rather than only its first [-element, and-] {+element;+} the per-step artifacts from §11.1 are the snapshots a backtrack would [-restore.-] {+restore (and, now that they are reversible CCR pointers, restoring a branch's full pre-state is lossless rather than approximate); and the top-N typed skill primitives from the compose path (§5.1) are a richer branch frontier than recipes alone.+} The expensive parts are what remain unwritten — a search controller that maintains a scored frontier, a runner that can restore plan state to re-enter a prior step, and a value estimate good enough that search converges faster than brute force. The risks are why this is last. Combinatorial blow-up across recipes × parameters × orderings makes a hard budget — max nodes, max tokens, max wall-time — mandatory, not optional. It also interacts badly with loops: a long loop *inside* a searched branch can stall for the better part of an hour. Every backtrack is a real subagent dispatch, so a weak value estimate makes search net-negative. And searched execution is non-deterministic, which collides with the marketplace's need for a recipe's behaviour to be a function of its text — so a deterministic mode that disables search would be the contract for published recipes. A failure-only mode (search only when a step fails) is a reasonable, cheaper first cut, but it is not the full vision.

### 12. Conclusion

A deployed language agent has the capability of a frontier model and, without an executive, the coherence of a reflex. This paper has argued that the missing executive is best built as a **recipe execution substrate**, and that the substrate becomes genuinely executive only when it can do six things: match intent to a program reliably and with calibrated [-confidence;-] {+confidence — claiming the prompts it serves and disclaiming the ones it must not;+} compose programs from programs, [-statically-] {+statically, dynamically,+} and [-dynamically,-] {+by calling typed library primitives,+} with the safety rails a call stack requires; author a new program when none fits {+— by synthesis or by mechanically wiring the library —+} and keep it; loop a program under a bounded condition; regulate the effort each turn deserves and drive the turn [-accordingly;-] {+accordingly, with a binding budget rather than mere advice;+} and make the whole thing observable without drowning the answer.

### 12. Conclusion

Of these, the loop is the quiet pivot. Sequence and selection make a checklist; sequence, selection, *and bounded iteration* make a substrate expressive enough to encode the iterative, exhaust-the-search, retry-until-clean work that real tasks demand — exactly the structural gap that separated a static playbook from a hand-coded workflow, now closed. And on-the-fly authoring is the quiet flywheel: a substrate that writes its own missing programs grows its competence inside the very conversations that expose its gaps. With [-durable-] {+durable, now-reversible+} resume, an empirically self-improving [-library,-] {+library running live end-to-end,+} external [-acquisition,-] {+acquisition that mines fresh open-source corpora for both artifacts and discipline,+} and a versioned marketplace running on top of those six capabilities, the substrate realises most of the full thesis, leaving only searched execution as a specified, deliberately bounded gap.

### 12. Conclusion

The intern who never repeats a mistake writes things down. The intern who gets promoted writes *recipes* — programs that make the next person as effective as they are. The agent described here writes its own recipes, composes them, loops them, runs them at the right intensity, {+doubts its own "done,"+} and shows its work. That is not a better worker. It is an executive.

### 13. The Surrounding Cognitive Stack

- **Episodic memory and consolidation.** A retrieval layer supplies the context the matcher and worker share, and an offline consolidation process — the background pass that runs between turns to compact experience and learn from it — owns the recipe-fitness measurement the matcher reads [-(§11.2).-] {+(§11.2) and the skill-library deposit/promote substrate.+} The ADAPT phase writes its lessons back through this layer's indexing path. - **A fast, cache-friendly index over memory.** The auto-seed hot path [-(§3.4)-] {+(§3.5)+} must add negligible latency, so it depends on retrieval that is structured and cache-friendly rather than a fresh similarity search each turn. Bi-temporal validity on stored facts — superseding rather than overwriting — keeps a recipe's contextual hints reflecting what is true now (§9.2). - **A {+reversible context-compression layer.** The artifact carry-forward (§11.1) depends on a compressor that caches the original verbatim and serves it back on demand — a Compress-Cache-Retrieve facility, content-type-aware — so the externalised working memory is lossless rather than truncated. - **A+} learned action-gating [-system.**-] {+system with native enforcement.**+} An affective intuition for which operations are dangerous sits beneath the worker's tool calls and complements the recipe's structural gates; {+it denies at the tool boundary, not merely scores, and+} the recipe context it receives (which step, which preconditions met) gives that intuition a vocabulary (§9.3). - **Multi-model deliberation.** A facility to fan a decision out to several models and synthesise the result; a high-stakes recipe step is its natural trigger (§9.4). - **Budget-aware prompting.** The effort router's model-tier choice (§7.3) is where a budget governor applies: under pressure, the same classifier that picks the maximum tier can be told to step down [-one.-] {+one; the enforced per-spawn budget (§7.4) is the binding form. - **A typed-composable recipe language.** The typed `invoke skill:` output schema, the validate→redispatch→persist path, and the classified-error taxonomy behind settled fan-out are specified by the companion typed-recipe-language work; the substrate consumes them at named seams (§4.3, §2.1) without re-deriving them.+}

### 13. The Surrounding Cognitive Stack

Between tasks, an idle agent with any intrinsic-motivation drive has an obvious use for the accumulating NO-MATCH log [-(§3.4):-] {+(§3.5):+} mining it to *propose* recipes worth authoring {+— by compose-from-library where the skills exist, by synthesis otherwise —+} before they are next demanded.

### Appendix A — The Turn, End to End (Pseudocode)

``` function HANDLE_TURN(prompt, context, library): # PLAN: effort regulation tier <- CLASSIFY_EFFORT(prompt) if tier != "trivial": [-inject_effort_guidance(tier)-] {+inject_effort_guidance(tier); arm_spawn_budget(tier)+} if tier == "trivial": return answer_inline(prompt, context) # executive dormant

### MATCH / COMPOSE / AUTHOR: task-set selection if context.has_in_progress_plan(): plan <- context.resume_plan() # never clobber an explicit/prior plan else: result <- MATCH_RECIPES(prompt, library) # fuzzy + anti-trigger + confidence + fitness + rating emit_trail("searched", catalog_size) if result.confidence == "none": emit_trail("no-match") spec <- COMPOSE_FROM_LIBRARY(prompt) or AUTHOR_RECIPE(prompt) # library-wire, else synthesise if VALIDATE(spec).ok: library.add(spec); emit_trail("authored", spec.slug) plan <- seed_plan_from(spec) else: plan <- implicit_two_step_plan() else: emit_trail("matched", result.matches) plan <- BUILD_MERGED_PLAN(result.matches, library) # composes: inlined if plan.from_multiple(): emit_trail("merged", plan.sources) persist(plan)

# MATCH / COMPOSE / AUTHOR: task-set selection if context.has_in_progress_plan(): plan <- context.resume_plan() # never clobber an explicit/prior plan else: result <- MATCH_RECIPES(prompt, library) # fuzzy + {+anti-trigger ++} confidence + fitness + rating emit_trail("searched", catalog_size) if result.confidence == "none": emit_trail("no-match") spec <- {+COMPOSE_FROM_LIBRARY(prompt) or+} AUTHOR_RECIPE(prompt) # {+library-wire, else+} synthesise [-+ validate + persist-] if VALIDATE(spec).ok: library.add(spec); emit_trail("authored", spec.slug) plan <- seed_plan_from(spec) else: plan <- implicit_two_step_plan() else: emit_trail("matched", result.matches) plan <- BUILD_MERGED_PLAN(result.matches, library) # composes: inlined if plan.from_multiple(): emit_trail("merged", plan.sources) persist(plan)

### EXECUTE (loops + sub-recipe calls + skill invocations): sequencing for group in plan.parallelism_groups: # groups run sequentially dispatch_all(group) in parallel: # steps within a group fan out for step in group: if not load_constraint_ok(step, here): step <- degraded_fallback(step) loop <- parse_loop(step); sub <- parse_uses(step); skill <- parse_invoke_skill(step) if loop: RUN_LOOPED_STEP(step, loop, context) elif sub: emit_trail("composed", sub); RUN_RECIPE(sub, child(context)) elif skill: INVOKE_SKILL(skill, step.out, context) # typed, schema-validated else: dispatch_worker(step) # OBSERVE: panel updates with step status + subagent vitals (settled, attributed) # persist a reversible (CCR) artifact pointer of each done step (resume spine) barrier() # survivors settle; typed failures attributed, not dropped response <- aggregate(plan)

# EXECUTE (loops + sub-recipe [-calls):-] {+calls + skill invocations):+} sequencing for group in plan.parallelism_groups: # groups run sequentially dispatch_all(group) in parallel: # steps within a group fan out for step in group: {+if not load_constraint_ok(step, here): step <- degraded_fallback(step)+} loop <- parse_loop(step); sub <- [-parse_uses(step)-] {+parse_uses(step); skill <- parse_invoke_skill(step)+} if loop: RUN_LOOPED_STEP(step, loop, context) elif sub: emit_trail("composed", sub); RUN_RECIPE(sub, child(context)) {+elif skill: INVOKE_SKILL(skill, step.out, context) # typed, schema-validated+} else: dispatch_worker(step) # OBSERVE: panel updates with step status + subagent vitals {+(settled, attributed)+} # persist a [-bounded-] {+reversible (CCR)+} artifact [-digest-] {+pointer+} of each done step (resume spine) barrier() {+# survivors settle; typed failures attributed, not dropped+} response <- aggregate(plan)

### ADAPT: learning, completion supervision, regulation if tier == "ultra": RUN_RECIPE("doubt-driven-verify", child(context)) # fresh-context critic reflection <- REFLECT(scaled_to = tier, trace = plan.trace) persist_lessons(reflection.memory_writes) if reflection.recipe_update: library.update(reflection.recipe_update) close_plan(plan) return response ```

# ADAPT: [-learning +-] {+learning, completion supervision,+} regulation {+if tier == "ultra": RUN_RECIPE("doubt-driven-verify", child(context)) # fresh-context critic+} reflection <- REFLECT(scaled_to = tier, trace = plan.trace) persist_lessons(reflection.memory_writes) if reflection.recipe_update: library.update(reflection.recipe_update) close_plan(plan) return response ```

### Appendix B — Recipe Document Schema (Illustrative)

``` --- frontmatter --- schema: recipe/1.0 slug: debug # also the on-disk directory name; traversal-safe title: Debug & Fix summary: Systematic debugging — reproduce, diagnose, fix, verify tags: [bug, error, crash, broken, not working, fails, exception, fix] {+not-when: [design from scratch, greenfield, new feature, brainstorm] # anti-triggers (negative match)+} composes: [] # static step-merge (recipes built from recipes) {+loads-in: [main, subagent] # load constraint; degraded fallback if unmet authoredBy: curated # curated | jarvis-on-the-fly | cc-bridge+} parallelism: groups: [[0],[1],[2],[3]] # 0-based; serial chain (data-dependent)

### 4. Verify done-when: the original error is gone and tests pass loop: until-dry max 3 # re-run verification until nothing new fails uses: doubt-driven-verify # fresh-context adversarial review of the artifact Run the failing test, then the broader suite, then trigger the original scenario. ```

### 4. Verify done-when: the original error is gone and tests pass loop: until-dry max 3 # re-run verification until nothing new fails {+uses: doubt-driven-verify # fresh-context adversarial review of the artifact+} Run the failing test, then the broader suite, then trigger the original scenario. ```

### 4. Verify done-when: the original error is gone and tests pass loop: until-dry max 3 # re-run verification until nothing new fails uses: doubt-driven-verify # fresh-context adversarial review of the artifact Run the failing test, then the broader suite, then trigger the original scenario. ```

*(In a composite recipe, a step body might instead open with `uses: adversarial-verify` to call that recipe as a sub-routine, {+with `invoke skill: extract-json-field` to call a typed library primitive,+} or with both `loop: until-dry` and `uses: <recipe>` to iterate a whole nested workflow to exhaustion.)*
