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

**Oscar Serra¹, Jarvis¹**
¹Independent Research
*2 June 2026 — v4.1*

---

## Abstract

The dorsolateral prefrontal cortex does not *do* tasks. It holds the plan, selects the right behavioural program for the moment, sequences sub-routines, suppresses the impulsive response, watches whether the program is working, and re-allocates effort when it is not. It is the brain's executive: not a worker, but the structure that makes work coherent. We argue that a deployed language agent needs the same thing, and that the right shape for it is neither a guard rail nor a manager-agent but a **recipe execution substrate** — a layer that turns each turn into an executive-function cognitive cycle of *plan → match/compose/author → execute-with-loops → observe → adapt-effort*.

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 we describe 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, 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), which is the element that lifts recipes from straight-line checklists to a structured, Turing-complete-ish 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 strictly out of the substantive chat.

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, and gives language-agnostic pseudocode for each of the six capabilities.

**Keywords:** recipe execution, executive function, agent orchestration, workflow composition, self-authoring workflows, bounded loops, effort routing, observability, cognitive cycle

---

## 1. Introduction — From Library to Substrate

### 1.1 The prefrontal analogy, taken seriously

When a person sits down to debug a stubborn problem, very little of the work is the "debugging." Most of it is executive: deciding *that* this is a debugging task and not a redesign task, recalling the program ("reproduce, then isolate, then fix, then verify"), holding that program in working memory while the hands and eyes do the reading and editing, suppressing the urge to patch the first symptom, noticing when the current step has stopped producing new information, and spending more attention when the problem is hard and less when it is trivial. The prefrontal cortex is the organ of that executive layer: working memory, task-set selection, sequencing, response inhibition, and effort regulation.

A language model is an extraordinary worker and a poor executive. Turn to turn it can read, reason, write, and call tools at a level that dwarfs human working memory for a single step — and yet, left to itself, it repeats the same structural mistakes: it edits before it reproduces, it codes before it designs, it searches before it scopes, it declares victory before it verifies. The deficit is not capability. It is the absence of an executive layer that holds and sequences the *program*.

This paper describes that layer. We call it PREFRONTAL, and we argue its correct form is a **recipe execution substrate**: a thin layer wrapped around the agent that, on every turn, recognises the task, selects or assembles the appropriate behavioural program, runs it with the agent as the worker, watches the execution, and regulates how much effort the turn deserves. The brain metaphor is not decoration; each capability below maps onto a specific executive function, and we name the mapping explicitly as we go.

### 1.2 What a recipe is, and why it is the right unit

A **recipe** is a structured workflow expressed as a portable document. It carries metadata (what intents it serves, what it is for), a set of triggers, an ordered list of steps — each with a short instruction, optional tool hints, and a *done-when* success criterion — and, where relevant, constraints, safety notes, and a record of the failure modes it was designed to prevent. A recipe is *not* a prompt and *not* a script.

- A **prompt** says "fix this bug." It is a wish.
- A **script** says, in code, "run command X, parse output, branch on line 12." It executes mechanically and shatters on the first input it did not anticipate.
- A **recipe** says "reproduce the failure with evidence; *then* trace the root cause to a file and line; *then* apply the smallest fix; *then* verify the original error is gone." It is structure that an intelligent worker can follow, adapt, or — with justification — override.

The recipe is the right granularity because it is the unit at which operational knowledge actually accumulates. A team that has debugged a thousand issues does not encode that experience as a better model; it encodes it as the discipline of *reproduce before you fix*. A recipe is where that discipline lives in a form that is human-readable, versionable, composable, and — as we will show — machine-authorable.

### 1.3 The gap this paper closes

A recipe *library* is useful but inert: a shelf of playbooks the agent consults when it remembers to. The contribution of this work is to make the library a **substrate** — an active engine with six properties that, taken together, are what separate a checklist from a programming language for behaviour:

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. (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, which is 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.)

The rest of the paper specifies each in turn (Sections 3–8), after establishing the architecture and the economics that make it affordable (Section 2). Section 9 integrates the substrate with the surrounding cognitive systems; Section 10 gives evaluation design; Section 11 is honest about what the substrate does *not* yet do and lays out the roadmap that closes those gaps; Section 12 lists suggested diagrams; Section 13 concludes.

---

## 2. Architecture — The Executive-Function Cycle

### 2.1 The cycle

PREFRONTAL wraps every interaction in a five-phase cycle that mirrors executive function:

```{=latex}
\begin{figure}[H]
\centering
\includegraphics[width=\linewidth,height=0.85\textheight,keepaspectratio]{images/fig-cycle.pdf}
\caption{The five-phase executive cycle, annotated with the executive function each phase implements. The dashed back-edge shows recipe improvement (the ADAPT phase) feeding the next turn.}
\end{figure}
```

A defining design choice: the EXECUTE phase uses *the same agent* as the worker. PREFRONTAL does not introduce a separate "manager agent" with its own personality and its own context. It seeds structure — a plan — and lets the worker run inside it. This preserves the property that makes language agents valuable (open-ended competence) while adding the property that makes them reliable (a default path of thoroughness). The recipe is a track, not a cage: the worker can deviate from a step when it can justify the deviation, because the gates are evaluated by judgement, not by a state machine.

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

The substrate is engineered so that the executive overhead is near-free for the common case and is *only* spent where it pays. Three mechanisms make this true.

First, **matching is local and lazy.** Task-set selection runs at the very start of every turn against an in-memory index of recipe metadata, cached and invalidated by the recipe directory's modification time. There is no network call and no model call on this hot path; the scorer is a few hundred microseconds of token arithmetic. A plan is therefore seeded *before* the worker's first token, at negligible cost.

Second, **effort routing gates depth.** A trivial turn ("thanks," "what time is it") is classified as trivial and the substrate stays out of the way entirely — no plan injection, no extra reasoning, minimal tokens. The machinery of the cycle is only fully engaged when the turn warrants it. This is the analogue of the cortex spending metabolic budget proportional to task difficulty rather than firing at full intensity for every stimulus.

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 follow-up call that differs only in its instruction costs a small fraction of a fresh call. The question therefore shifts from "can we afford an executive layer?" to "can we afford to run without one?"

### 2.3 Plans as the runtime trace of recipes

A recipe is a template; a **plan** is the instance of one recipe (or several, merged) executing inside a specific session. The plan is a persisted, structured document: it records which recipe(s) seeded it, the ordered steps, and the live status of each step (`pending → in_progress → done | error`). A single invariant governs it: *at most one step is `in_progress` at a time per plan*, enforced by the store rather than by the caller, so the executive's working-memory "cursor" is always unambiguous.

Because the plan is persisted and seeded automatically at turn start, the substrate gains crash-resilience almost for free: if the process restarts mid-task, there is an `in_progress` plan on disk describing exactly where the work was, and the executive can resume from it rather than re-deriving intent from scratch. The plan *is* the agent's working memory, externalised.

---

## 3. Capability 1 — Recipe Matching (Task-Set Selection)

### 3.1 The problem with literal matching

The naïve approach to recipe selection is keyword matching: if the message contains "bug," select the debug recipe. It is brittle in exactly the way human task recognition is not. A person reading "the build keeps dying after I touched the config" instantly recognises a debugging situation; a literal matcher sees no shared token with a recipe tagged `bug, error, crash` and silently selects nothing. Worse, a silent non-selection is invisible: the agent proceeds with no program, and no one knows the executive failed to engage.

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

The matcher tokenises the prompt (lower-casing, dropping stop-words and very short tokens) and scores each recipe's metadata against those tokens with a graduated notion of "match" that tolerates the ways natural language varies:

- **Exact equality** ("debug" == "debug").
- **Shared stem** after stripping common English inflections, so *debugging*, *debugged*, *debugger* all reduce to the same root as *debug*.
- **Prefix overlap** for tokens of reasonable length, so *configuration* matches *config*.
- **Edit-distance-1** on the stemmed forms for longer tokens, absorbing typos and minor morphological drift.

The graduation matters: tiny tokens are matched only by equality (to avoid spurious hits), while longer tokens earn the looser rules. Scoring is weighted by *where* the match lands: a hit against a recipe's hand-curated trigger tags counts most, a hit in the title less, a hit in the summary least. Multi-word tags match as phrases; single-word tags and title/summary words match fuzzily.

```
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
    return score

function FUZZY-MATCH(a, b):
    return a == b
        or (stem(a) == stem(b) and len >= 3)
        or (len(a),len(b) >= 4 and one is a prefix of the other)
        or (len(a),len(b) >= 5 and edit_distance(stem(a), stem(b)) <= 1)
```

### 3.3 Confidence tiers and what they gate

Raw scores are reduced to a **confidence tier** — `none`, `low`, or `high` — because the executive needs to behave differently depending on how sure it is, just as a person hesitates before committing to an ambiguous task framing:

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

- **High** confidence: a clear leader well above the bar. Seed the plan silently and proceed.
- **Low** confidence: barely over the bar, or a near-tie among candidates. 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.4 Auto-seeding at turn start

The matcher runs automatically as a turn-start hook, not on the agent's initiative. This is deliberate: an executive function that must be *remembered* is an executive function that fails under load. The hook scores the prompt, builds a plan from the matched recipe(s), and persists it — with one inviolable rule: **it never clobbers an existing `in_progress` plan.** An explicit plan, or one carried over from a prior turn, always wins over a fresh auto-seed. Trivial and conversational turns (and re-injected completion signals) are filtered out before scoring, so the executive engages exactly when there is a program worth running.

The accumulating record of *which prompts produce no match* is itself a signal: a class of prompts that repeatedly fails to match means the library is too thin, the work has drifted into new territory, or it is time to author. Mining that signal is how the library grows — and Section 5 makes the growth automatic.

---

## 4. Capability 2 — Composition (Recipes Built from Recipes)

Hierarchical structure is the hallmark of executive control: complex behaviours are not flat sequences but programs that call sub-programs. The substrate gives recipes two complementary forms of composition, mirroring the two ways code reuses code.

### 4.1 Static composition — step-merge (`composes:`)

A recipe may declare, in its metadata, that it *composes* other recipes. At plan-build time, the composed recipes' steps are expanded **into** the merged plan ahead of the composing recipe's own steps — so a composite reads as "do sub-recipe A, then sub-recipe B, then my own steps." This is inlining: the sub-recipes' steps become first-class rows in the single resulting plan. Expansion is **cycle-guarded** (a recipe already on the expansion stack is not expanded again) and **depth-bounded**, so a composition graph can never loop forever. Step de-duplication by normalised title keeps a step that appears in two composed recipes from running twice.

```
function BUILD_MERGED_PLAN(matches, library):
    steps <- [];  seen <- {};  expanded <- {}
    function ADD_FROM(recipe, depth):
        if recipe in expanded or depth > MAX_COMPOSE_DEPTH: return
        mark recipe expanded
        for sub_slug in recipe.composes:           # composed steps lead
            ADD_FROM(library[sub_slug], depth + 1)
        for step in parse_steps(recipe):
            key <- normalise(step.title)
            if key not in seen:
                add step to steps;  mark key seen
    for m in matches: ADD_FROM(m.recipe, 0)
    return plan(steps)
```

This is how a heavyweight workflow ("ship a paper end-to-end") is assembled from lighter, independently useful recipes ("draft," "adversarially verify," "compile") without copying their steps.

### 4.2 Dynamic composition — runtime sub-recipe calls (`uses:`)

Static merge fixes the program before execution; sometimes a step should *call* another recipe at runtime, the way a function call defers control to a callee. A step whose body opens with a `uses: <recipe>` directive runs that sub-recipe instead of a plain worker dispatch, on a derived child session, and folds its result back as the step's outcome. This is a true call: the sub-recipe has its own plan, its own steps, its own fan-out.

Two safeguards keep recursion safe, exactly as a runtime keeps a call stack from overflowing:

- **Depth cap.** Sub-recipe calls may nest only to a fixed maximum; exceeding it errors the step rather than recursing further.
- **Cycle guard.** The chain of recipe references on the current call stack is tracked; a recipe that would re-enter itself (directly or transitively) is refused.

A subtle but important parsing rule guards correctness: only the **consecutive leading directive lines** of a step body are interpreted as directives. A `uses:` mentioned in prose, or shown inside a code fence as an example, does *not* fire. This prevents a documentation example from accidentally triggering a recursive call — the difference between citing a function and calling it.

```
function EXECUTE_STEP(step, ctx):
    directives <- leading_directive_lines(step.body)   # stop at first prose/blank line
    sub_ref    <- parse_uses(directives)
    if sub_ref is set:
        if depth(ctx) >= MAX_USES_DEPTH or sub_ref in ctx.call_chain:
            return error("recursion guard")
        result <- RUN_RECIPE(sub_ref, child_session(ctx), chain = ctx.call_chain + [sub_ref])
        return done(result.note)
    else:
        return dispatch_worker(step)
```

Together, `composes:` (inline at build time) and `uses:` (call at run time) give recipes the full reuse vocabulary of a programming language — composition and invocation — with the loop-safety guarantees a substrate must provide.

---

## 5. Capability 3 — On-the-Fly Authoring (Skill Acquisition)

### 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.

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. 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.

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

A self-authoring system that writes unvalidated files would slowly poison its own library. Authoring therefore refuses any specification that would produce a malformed or unsafe recipe:

```
function VALIDATE(spec):
    errors <- []
    if spec.slug does not match SAFE_SLUG_PATTERN:        # lowercase, no slashes, no ".."
        errors += "slug unsafe (also the on-disk dir name)"
    if spec.title or spec.summary missing:               errors += "title/summary required"
    if spec.tags is empty:                                errors += "tags required (else unmatchable)"
    if spec.category set and not in CANONICAL_CATEGORIES: errors += "bad category"
    if spec.steps is empty:                               errors += ">=1 step required"
    for i, step in spec.steps:
        if step.title or step.body missing:               errors += "step {i} incomplete"
        if step.body contains a numbered markdown heading: # "### N. ..."
            errors += "step {i} body would re-parse as a PHANTOM step"
    if spec.parallelism_groups set:
        require every step index covered exactly once, in range, non-overlapping
    return errors
```

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.

### 5.3 Provenance and the never-overwrite rule

Authored recipes are stamped with an *authored-by* marker that distinguishes them from the curated, hand-written library. The persistence layer will overwrite an authored recipe only with an explicit overwrite flag, and **will never overwrite a curated recipe** — the substrate cannot cannibalise its own carefully written playbooks. Trigger phrases supplied by the author are folded into the recipe's tag set, because the matcher scores against tags; an authored recipe whose triggers never reached the tags would be invisible to the very matcher that is meant to surface it next turn. (Authored recipes are never auto-published to any shared registry; publishing is an explicit, separate human action.)

This is the compounding thesis applied to workflows: each authored recipe is a captured behaviour that makes the next encounter of that task class cheaper, and the library is a *growing* asset rather than a fixed one.

---

## 6. Capability 4 — Recipe Loops (The Structural Gap, Closed)

### 6.1 Why loops are the dividing line

A straight-line recipe is a checklist. A checklist cannot express "keep collecting findings until there are no new ones," or "retry this verification up to five times," or "iterate the draft until it crosses a quality marker." Those are the shape of real iterative work, and their absence is precisely the structural gap that separates a static playbook from a hand-coded agent workflow. A loop construct — even a bounded one — is the feature that closes the gap, because sequence + branch + bounded iteration is the minimal vocabulary of a general execution substrate. With loops, recipes stop being checklists and become *programs* for behaviour.

### 6.2 Three bounded loop modes

A step whose leading directive is `loop:` repeats — whether the step is a plain worker dispatch or a `uses:` sub-recipe call — under one of three termination conditions:

- `loop: count N` — run exactly *N* times (or until an iteration fails).
- `loop: until-dry [max M]` — re-run until the worker's done-note signals it found nothing new this pass, capped at *M*.
- `loop: until MARKER [max M]` — re-run until a step note contains a named marker, capped at *M*.

The "dry" test is a small natural-language classifier over the worker's done-note: an empty note, or one containing phrases like *no new*, *nothing left*, *complete*, *exhausted*, *all covered*, counts as dry and terminates the loop. This lets a worker signal exhaustion in prose rather than via a rigid protocol.

```
function RUN_LOOPED_STEP(step, loop, ctx):
    for i in 1 .. loop.max:
        result <- EXECUTE_ONCE(step, ctx, iteration = i)
        if not result.ok:                                       break   # failure stops the loop
        if loop.mode == "until-dry"   and IS_DRY(result.note):  break
        if loop.mode == "until-marker" and result.note contains loop.marker: break
        # count mode: continue to loop.max
    mark step done with last result.note

function IS_DRY(note):
    if note is empty: return true
    return note matches /no new | nothing left | complete | exhausted | finished | all (covered|done)/
```

### 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 default maximum, and an absolute hard cap that no recipe (authored or hand-written) can exceed. A loop count is clamped into `[1, HARD_CAP]` at parse time, so even a maliciously or accidentally enormous `count` collapses to the hard ceiling. 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.

`loop:` and `uses:` 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. Capability 5 — Dynamic Effort Routing (Effort Regulation)

### 7.1 From classify-and-log to classify-and-drive

The prefrontal cortex meters effort: it does not spend the same metabolic budget on "pass the salt" as on "prove this theorem." An agent that reasons at full intensity on a greeting and at minimum intensity on an architecture decision is mis-regulated in both directions — wasteful on the trivial, negligent on the hard. Earlier effort routing only *classified* the turn and logged the result, which changed nothing. The substrate makes the classification **drive** the turn.

### 7.2 The four tiers and the signals behind them

Each turn is scored into one of four tiers — **trivial → standard → deep → ultra** — from cheap, language-level signals: prompt length, the number of clauses/sub-tasks (conjunctions, list markers, line breaks as a proxy for "how many things am I being asked to do"), the presence of code or file paths, the count of distinct "hard work" verbs (*architect, design, investigate, refactor, migrate, audit, debug, optimise, …*), the count of "maximum effort / breadth" cues (*comprehensive, exhaustive, end-to-end, entire codebase, deep dive, be generous, …*, weighted double), and a word-boundary-checked set of conversational/acknowledgement tokens that mark a turn as trivial.

```
function CLASSIFY_EFFORT(prompt):
    score <- 0
    if words > 40:  score += 1; if words > 120: score += 1; if words > 300: score += 1
    if clauses >= 4: score += 1; if clauses >= 10: score += 1
    if has_code:    score += 1
    if has_paths:   score += 1
    score += min(4, count_distinct(deep_verbs))
    score += min(4, 2 * count(ultra_cues))          # breadth cues weigh double
    if questions >= 3: score += 1

    if trivial_token_hit or (words <= 4 and score == 0): tier <- "trivial"
    elif score >= 7 or ultra_cues >= 2:                  tier <- "ultra"
    elif score >= 4:                                     tier <- "deep"
    else:                                                tier <- "standard"
    if tier == "standard" and count(deep_verbs) >= 3:    tier <- "deep"   # floor
    return tier
```

A trivial turn must have **no** hard or breadth verbs — the design refuses to down-classify a short prompt that nonetheless asks for hard work.

### 7.3 What the tier controls

The tier is not advisory; it sets four levers for the turn, injected as guidance the worker adapts to:

| Tier | Model tier | Thinking budget | Orchestration mode | Token generosity |
|------|-----------|-----------------|--------------------|------------------|
| **trivial** | minimal | none — answer directly | solo, inline | terse (a sentence or two) |
| **standard** | standard | brief; verify before claiming done | solo, inline | normal — cover the ask, no padding |
| **deep** | maximum | extended; lay out KNOW / ASSUME / DON'T-KNOW before acting | parallel — fan independent read-only work to subagents | generous |
| **ultra** | maximum | maximum; design before implementing | full workflow — understand → design → implement → review, with adversarial verification and a completeness critic at the end | very generous — correctness over cost |

For trivial turns the substrate injects *nothing* and keeps the turn cheap and fast; the executive stays dormant when there is nothing to regulate. For deep and ultra turns it shifts the whole posture of the agent — bigger model, more thinking, parallel or full-workflow orchestration, and explicit permission to spend tokens on correctness. This is the lever that lets a single agent be both a quick conversationalist and a rigorous engineer, choosing per turn rather than per deployment.

---

## 8. Capability 6 — The RECIPES Observability Panel (Metacognitive Monitoring)

### 8.1 Why observability is a first-class capability, not a nicety

An executive that runs invisibly is impossible to trust or to debug. If a human collaborator cannot see *which* program is running, *where* it is, and *how* each worker is doing, then every long-running turn is an opaque wait, and every failure is a mystery. The substrate therefore treats observability as a designed capability with its own surface: the **RECIPES** panel.

### 8.2 The split-of-concerns invariant

One rule governs the panel and is the most load-bearing invariant of the whole system:

> **Chat carries substance; the panel carries orchestration mechanics. Never the reverse.**

The substantive answer — what was found, what changed, what is stuck — goes in the chat. The orchestration mechanics — which recipes were searched, which step is active, which subagent is doing what — go in the panel. Pushing dispatch chatter into the chat drowns the substance; pushing substance into the panel hides the answer. If a person has to flip between surfaces to understand where the agent is, the split was drawn wrong.

### 8.3 What the panel renders

The panel renders the full life-cycle of a recipe run as several stacked sections:

- **Discovery.** Catalog size, the scored candidate recipes with their scores, the matching threshold, and what was selected (or a visible NO-MATCH). This makes task-set selection auditable: a wrong recipe choice 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.
- **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. This is where "the agent is working" becomes "this subagent, on this model, is reading this file, and has been for forty seconds."
- **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.4 The compact-expand decision trail

A trail that grows without bound becomes noise, and a panel that stays verbose for hours after work ends is worse than no panel. The decision trail is therefore **compact by default and expandable on demand**, and it self-folds: when the last subagent completes and the call tree returns to idle, the recipe header and the accumulated trail fold away while the persistent plan (a task tracker, not an in-flight indicator) remains. The state is kept in memory for the next job's resumption; the panel simply stops painting it. The executive's monitor is loud while there is something to monitor and quiet when there is not — the metacognitive analogue of attention that disengages when the task is done.

```{=latex}
\begin{figure}[H]
\centering
\includegraphics[width=\linewidth,height=0.85\textheight,keepaspectratio]{images/fig-statemachine.pdf}
\caption{The life-cycle state machine the RECIPES panel renders: \texttt{searched} $\rightarrow$ \texttt{matched} $\rightarrow$ \texttt{merged/composed} $\rightarrow$ \texttt{seeded} $\rightarrow$ \texttt{running} $\rightarrow$ \texttt{looping/composing} $\rightarrow$ \texttt{done}, with the no-match $\rightarrow$ authoring $\rightarrow$ matchable-next-turn branch and the no-match $\rightarrow$ trivial $\rightarrow$ idle branch. Every transition emits a provenance-trail verb, so the figure doubles as a legend for the RECIPES trail.}
\end{figure}
```

---

## 9. Integration with the Surrounding Cognitive Systems

The substrate does not stand alone; it sits among the other organs of the agent's cognition and coordinates them. Each retains its autonomous function and gains a coordination point.

### 9.1 Identity

A single persistent identity — personality, values, voice — is loaded into every call the substrate makes: the worker's execution calls, any tiebreak or reflection call, and every subagent dispatch. There is no separate "planner persona" to introduce voice discontinuities. The executive and the worker are the same self, wearing different instructions. This is what keeps a parallel fan-out of five subagents reading as one coherent agent rather than five strangers.

### 9.2 Memory

Memory retrieval supplies the context the matcher and the worker share, and the substrate uses it two ways. Recipe-contextual retrieval injects prior executions of the same recipe class into the plan ("last time this recipe ran on this module, the root cause was in the injection layer"). Reflection-driven writes push freshly learned lessons back through the indexing pipeline so they are retrievable next session. Bi-temporal validity on memory edges — facts that become *superseded* rather than overwritten — is the natural upgrade path here, so a recipe's contextual hints reflect what is true *now* rather than what was once true.

### 9.3 Learned action gating

A learned action-gating system (the agent's affective intuition for which operations are dangerous) sits beneath the worker's tool calls and complements the recipe's structural gates. The integration is bidirectional: gating now receives recipe context — which step, which recipe, which preconditions were met — so it can learn that "a file write during the *fix* step, after a successful *diagnose* step, is safe" while "a file write with no prior investigation is suspect." Structural gates (the recipe's *done-when* criteria) and learned gates (the affective network) reinforce each other; the recipe gives the intuition a vocabulary.

### 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.

### 9.5 Reflection, orchestrated

Post-action reflection is no longer a turn-by-turn ritual that fires regardless of whether anything happened. The substrate scales it to the work: a full reflection (with recipe context, execution trace, and plan-versus-outcome comparison) after a substantive recipe completes; a lightweight pass after a simple task; an extended root-cause reflection after a failure — with the authority to *recommend a recipe update*. Matching reflection depth to task complexity preserves the compounding benefit of learning while eliminating the latency tax of reflecting on a greeting. Reflection is the ADAPT phase of the cycle, and its most important output is sometimes not a memory note but an improved recipe.

---

## 10. Evaluation Design

### 10.1 First-attempt accuracy

The substrate should raise first-attempt accuracy by structurally preventing the most common failure modes — the same way the prefrontal cortex prevents impulsive errors by holding the plan. Each gate targets a known failure:

| 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* |
| Declaring done before verifying (premature closure) | every recipe's terminal *verify* step |
| 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 |

The headline metric is the change in weighted first-attempt accuracy across a representative task mix, attributing each delta to the gate responsible.

### 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 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.

### 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).

### 10.5 Cost and latency

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.

---

## 11. Limitations and Roadmap

The substrate as specified above is the part that ships and runs. This section is deliberate about its boundary: what the six capabilities do *not* yet do, and the concrete next steps that close each gap. The roadmap is ordered by dependency, because the items are not independent — durable state is a prerequisite for the feedback loop, which is a prerequisite for search. Each item names the seam it attaches to, so the roadmap reads as engineering work, not a wish list.

### 11.1 The plan is written, not yet read back — durable checkpointing

The plan-store is the durable spine of the cycle (§2.3), and the paper's claim is that "the plan *is* the agent's working memory, externalised." Today that spine is **write-mostly**. The runner records each step's status and advances the cursor, and the plan schema already reserves a per-step `artifact` field and a plan-level `currentStep`, but the runner always starts at step 0 and never reads back what a finished step produced. So the resume story in §2.3 is currently an aspiration: a plan interrupted at step 3 of 6 by a gateway crash, the 10-minute per-step wall, or a guardian kill restarts from the top rather than resuming at step 4.

Closing this turns "the plan is the program counter" from a description into a guarantee. The work is contained: on entry, read back an `in_progress` plan with a matching recipe reference and set the start index to its cursor, skipping any step already marked done; on each step's success, persist a bounded digest of the done-note into the reserved `artifact` field and carry prior artifacts forward as upstream context for the next step; for a sub-recipe call, bubble the nested plan's terminal result up as the parent step's artifact. No schema change is needed — both fields already exist. The two load-bearing risks are lossiness (a bounded digest can drop context a later step needs — mitigated by keeping the full note in the plan body and the digest in the bounded field) and read-path atomicity (a partially written plan read during resume must quarantine and fall back to a clean restart rather than crash). This is item one because the next two roadmap items both consume per-step outcomes.

### 11.2 The library expands but does not yet self-improve — the feedback loop

Section 5 makes the library self-*expanding*: it authors a recipe when none matches. Section 9.5 makes it self-*updating*: a reflection pass can recommend a recipe change. What is missing is making it self-*improving* — feeding real execution outcomes back into the matcher so the scoring weights (§3.2) stop being hand-tuned constants and become evidence-updated. Right now a high-confidence recipe that fails on every run keeps its high confidence; a class of intent that misses on every turn re-authors from scratch instead of being surfaced once for a durable fix.

The outcome-capture seam already exists: every plan that closes is a natural training row, so no new call is needed on the hot path. A per-recipe weight delta — derived from closed-plan outcomes plus an explicit "this recipe was wrong" verdict — is read in the scorer and applied after the base score, *before* the confidence tiering. Two guards keep the loop stable: the delta is clamped to a small bounded range so a single mis-attributed failure cannot bury a curated recipe, and the curated base weights remain the floor. The honest caveat is attribution: a closed plan's status reflects the *worker's* execution, not whether the *recipe* was the right structure — so an explicit verdict is higher-signal than an inferred one and should weigh more. The same machinery subsumes the NO-MATCH mining sketched in §3.4: a between-tasks pass buckets the accumulated no-match log by normalised intent and, when a bucket crosses a threshold, proposes a recipe to author — turning authoring from purely reactive into partly active.

### 11.3 The format is portable but the ecosystem is not yet a supply — external acquisition

Section 5.3 establishes `recipe/1.0` as a portable document and the substrate as a general runtime rather than a closed hand-authored set. The portability is real but under-exploited: the matchable library is still almost entirely local. Two outside sources could feed it. Journey kits are a near-native format and the search/install path is already wired to a remote registry; the gaps are a local-only fallback when the registry is unreachable (today it fails silently) and merging remote results with local matches so discovery spans both. Claude Code skills are a *different* shape — a `SKILL.md` plus scripts — and need an adapter that transpiles the skill into a recipe spec and runs it through the **existing** authoring validator (§5.2), so the slug-traversal and phantom-heading guards apply to imported content for free.

The honest limitations here are about trust and fidelity. Skill-to-step transpilation is heuristic — a skill documents *capability*, not always an ordered procedure — so a bad transpile yields a non-executable recipe; gating every import behind the validator and marking bridged recipes low-trust is the guard. Imported content is untrusted, so the sandbox-path resolver that blocks `../` must also refuse to follow symlinks. And an imported `code-review` must not shadow a curated one, so imports are namespaced by owner. Whether bridged recipes are matchable by default or quarantined until a human promotes them is a policy decision, not an engineering one.

### 11.4 Recipes are authored but not yet shared as artifacts — the marketplace

The capstone of treating a recipe as an artifact is making a tested one a versioned, discoverable object rather than a file that lives in one workshop. The frontmatter already carries owner, version, tested-harness, and authored-by fields, and the publish path is already wired to a remote endpoint, so the remaining work is *semantics* layered on existing plumbing: a semver bump on publish with immutable published versions (a republish that would overwrite an existing version is refused), version-constrained resolution on install (latest / exact / range) with a cache TTL so updates propagate without hammering the API, and a small rating-or-download bonus folded into the same post-score adjustment seam as the feedback loop (§11.2), so there is exactly one place that perturbs base scores. Authored recipes are never auto-published — publishing stays an explicit human action (§5.3) — and only the frontmatter owner may publish a new version of a slug.

Two tensions are worth naming rather than hiding. Version immutability collides with the need to retract a bad recipe: the answer is a yank/deprecate flag, not deletion, so pinned consumers do not break. And rating-weighted discovery risks a rich-get-richer bias that buries good new recipes, so the bonus stays small and clamped. The marketplace backend itself is out of scope of the substrate — it is a separate deliverable — and whether it reuses the Journey service or a distinct endpoint is undecided.

### 11.5 The substrate runs a recipe but does not yet *find* one — bounded search (ToT/LATS)

This is the most ambitious gap and the furthest out. Today the substrate executes a *single* pre-seeded plan top to bottom; loops retry the *same* step to a fixpoint and `uses:` recurses a *fixed* sub-recipe. None of this *searches*. The unrealised degree of freedom is: when a step fails, explore alternate recipes, alternate parameters, or alternate orderings, score the branches, backtrack, and prune — turning the plan from a fixed program into a searched one, and advancing the thesis from "the substrate runs a recipe" to "the substrate finds the recipe that works."

Some of the raw material is already present: the matcher already returns a ranked top-N with confidence, so "alternate recipes" is just consuming the list rather than only its first element. The expensive parts are a search controller that maintains a scored frontier, a runner that can snapshot and restore plan state to backtrack into a prior step (which depends entirely on §11.1's per-step artifacts being lossless enough to re-enter a 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, and it 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.

### 11.6 What this section does not claim

These five items are specified, not shipped. The paper's six capabilities (Sections 3–8) are the implemented substrate; this section is the gap between that substrate and the stronger claims the thesis invites — durable resume, a self-improving library, an ecosystem supply, shared artifacts, and searched execution. Stating the boundary explicitly is the point: a substrate that overstates what it does is no more trustworthy than an agent that declares victory before it verifies.

---

## 12. Suggested Diagrams (D2)

These are descriptions for a designer; the diagrams themselves are not drawn here. D2 is suggested for its clean layered layout and first-class containers.

1. **The executive-function cycle (Figure 1).** A vertical D2 flow of the five phases — PLAN, MATCH/COMPOSE/AUTHOR, EXECUTE (with loops), OBSERVE, ADAPT — each phase as a container, annotated on the right with the prefrontal function it implements. A back-edge from ADAPT to the recipe library shows recipe improvement feeding the next turn.

2. **The recipe-run life-cycle state machine (Figure 2).** A D2 state diagram of `searched → matched → merged/composed → seeded → running → looping/composing → done`, with the `no-match → authoring → matchable-next-turn` branch and the `no-match → trivial → idle` branch. Annotate each transition with the provenance verb it emits, since the figure doubles as a legend for the RECIPES trail.

3. **Composition algebra — inline vs. call.** A side-by-side D2 figure contrasting `composes:` (static step-merge: sub-recipe steps flattened into one plan, with de-dup) against `uses:` (dynamic call: a step transferring control to a nested plan on a child session and returning), with the depth cap and cycle guard drawn explicitly as the recursion's safety rails.

4. **The RECIPES panel anatomy.** A D2 container diagram of the panel's stacked sections — Discovery, Composition, Plan-with-badges, per-step Fan-out (subagent vitals), and the compact/expandable Trail — placed beside the chat surface, with a bold boundary marking the split-of-concerns invariant (substance left, mechanics right).

---

## 13. Conclusion

The history of engineering is the history of structure replacing improvisation: not by making practitioners smarter, but by giving their work a shape that makes good outcomes the default. The prefrontal cortex did the same thing for cognition long before engineering existed — it is the structure that lets a capable brain act coherently rather than impulsively, by holding the plan, selecting the program, sequencing the sub-routines, suppressing the wrong move, watching the result, and metering the effort.

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; compose programs from programs, statically and dynamically, with the safety rails a call stack requires; author a new program when none fits and keep it; loop a program under a bounded condition; regulate the effort each turn deserves and drive the turn accordingly; and make the whole thing observable without drowning the answer.

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 — which is 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.

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, and shows its work. That is not a better worker. It is an executive.

---

## References to Companion Papers

The following companion working papers describe the surrounding organs of the agent's cognition. Each is summarised inline; this paper is self-contained and does not depend on having read them.

- **ENGRAM / Total Recall (memory consolidation).** The episodic-memory and consolidation layer. Supplies the retrieval the matcher and worker share, and the write path the ADAPT phase uses.
- **HIPPOCAMPUS (instant recall).** The fast structured-index layer over memory; the auto-seed hot path depends on fast, cache-friendly retrieval. Bi-temporal validity on edges keeps recipe hints current.
- **MNEMOSYNE (memory enhancements).** Contradiction handling, compaction capture, task-conditioned scoring — the natural place to make retrieval recipe-aware.
- **CEREBELLUM (sleep consolidation).** Background consolidation and failure-driven self-improvement — the principled engine for recipe *evolution* (mutate + benchmark against real traces, keep an archive).
- **SYNAPSE / Round Table (multi-model deliberation).** Cross-provider debate; a high-stakes recipe step is the natural trigger.
- **AMYGDALA (learned intuition).** A neural action-gating system; learned gates sit beneath tool calls and complement the recipe's structural gates.
- **MYELIN (budget prompting).** The effort router's model-tier choice is where budget awareness applies.
- **The Wondering Machine (curiosity / intrinsic motivation).** Between tasks, an intrinsically motivated agent could mine the accumulated NO-MATCH signal to *propose* recipes to author.

---

## 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)
    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 + confidence
        emit_trail("searched", catalog_size)
        if result.confidence == "none":
            emit_trail("no-match")
            spec <- AUTHOR_RECIPE(prompt)           # 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): 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:
                loop <- parse_loop(step); sub <- parse_uses(step)
                if loop:  RUN_LOOPED_STEP(step, loop, context)
                elif sub: emit_trail("composed", sub); RUN_RECIPE(sub, child(context))
                else:     dispatch_worker(step)
                # OBSERVE: panel updates with step status + subagent vitals
        barrier()
    response <- aggregate(plan)

    # ADAPT: learning + regulation
    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]
composes: []                            # static step-merge (recipes built from recipes)
parallelism:
  groups: [[0],[1],[2],[3]]             # 0-based; serial chain (data-dependent)

--- body ---
### 1. Reproduce
   done-when: the exact failure is described with evidence
   Read the error. Run the failing case. Identify the trigger conditions.

### 2. Diagnose
   done-when: root cause identified with file:line
   Trace the cause through code; follow evidence, do not guess.

### 3. Fix
   done-when: minimal change applied
   Smallest fix that addresses the root cause. One concern per change.

### 4. Verify
   done-when: the original error is gone and tests pass
   loop: until-dry max 3                # re-run verification until nothing new fails
   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, or with both `loop: until-dry` and `uses: <recipe>` to iterate a whole nested workflow to exhaustion.)*
