ReadPrintedHistoryCompareGraphs

v3.1 → v4.0

What changed from v3.1 to v4.0

From v3.1 (7 Apr) to v4.0 (30 May): 5,410 words to 7,254 words, 6,710 words in new or rewritten paragraphs and 4,866 taken out, 369 paragraphs changed.

Rewritten: recipes as the agent's executive function

A second full rewrite. The folder's notes say the owner chose on 2026-05-30 to rewrite this paper rather than start a new one, and to write up parts that were already running in the fork but had never been described. The paper now takes the brain's prefrontal cortex as its model: a layer that holds the plan, picks the routine and watches whether it works.

  • New title: "The Recipe Execution Substrate — How a Composable, Self-Authoring, Looping Workflow Engine Becomes an Agent's Executive Function".
  • Six capabilities, one section each: fuzzy matching of a request to a recipe, recipes built from other recipes, writing a new recipe when none fits, bounded loops, effort routing that sets model and thinking budget, and a panel that shows all of it.
  • Drops the idea of a separate orchestrator call and the Claude Code leak as the main evidence; the worker runs the recipe itself.
  • Adds pseudocode for each capability and a recipe document schema in the appendices.
v3.1 · 7 April 2026v4.0 · 30 May 2026
v3.1 · PREFRONTAL v3.1: From Guard Rails to Recipe Engine --- How Structured Orchestration Compounds Agent Intelligence# PREFRONTAL v3.1: From Guard Rails to Recipe Engine --- How Structured Orchestration Compounds Agent Intelligence
removed in v4.0
v3.1 · PREFRONTAL v3.1: From Guard Rails to Recipe Engine --- How Structured Orchestration Compounds Agent Intelligence**Oscar Serra^1^, Jarvis^1^** ^1^Independent Research *7 April 2026 --- v3.1*
removed in v4.0
not in v3.1
v4.0 · PREFRONTAL v4.0: The Recipe Execution Substrate — How a Composable, Self-Authoring, Looping Workflow Engine Becomes an Agent's Executive Function# PREFRONTAL v4.0: The Recipe Execution Substrate — How a Composable, Self-Authoring, Looping Workflow Engine Becomes an Agent's Executive Function
not in v3.1
v4.0 · PREFRONTAL v4.0: The Recipe Execution Substrate — How a Composable, Self-Authoring, Looping Workflow Engine Becomes an Agent's Executive Function**Oscar Serra¹, Jarvis¹** ¹Independent Research *30 May 2026 — v4.0*

··· 2 unchanged paragraphs folded ···

v3.1 · AbstractThe gap between preventing bad behaviour and enabling great behaviour is the central challenge of agent architecture. Version 2.4 of this paper proposed compounded intelligence through fractal reflection --- a post-action review cycle that converts events into reusable rules. Deployment validated the compounding hypothesis (+96% CII) but exposed a structural asymmetry: guards prevent mistakes but do not guide excellence.
removed in v4.0
v3.1 · AbstractThis paper introduces Prefrontal v3.1, a major architectural revision that transforms the orchestration layer from a passive guard system into an active **recipe execution engine**. The key insight comes from convergent evolution across three independent systems: Anthropic's Claude Code achieves its effectiveness through *skills* --- structured workflow prompts injected on demand that decompose complex tasks into ordered steps; Journey Kits (Berman, 2026) demonstrates that the commercial value of AI agents lies not in the model but in the structured *recipe* wrapped around it; and our own `prefrontal-prompt.md`, a rich orchestration prompt that has sat unused in the codebase for months, already encodes the recipe format we now propose to execute.
removed in v4.0
v3.1 · AbstractThe architectural pivot is economical. Prefrontal becomes a **first call** rather than a post-action reflection --- receiving the user's request, selecting or composing a recipe, dispatching parallel subagents, monitoring their progress, and conducting fractal reflection only after the recipe completes. Because this orchestration call shares nearly the same context as the main agent (same SOUL.md, same memory hierarchy, same session history), Anthropic's prompt cache makes the additional LLM call approximately 5% overhead in tokens. The fractal reflection that drove v2.4's compounding becomes the orchestrator's post-completion review --- still present, now properly situated within a complete cognitive cycle that includes pre-action planning, during-action monitoring, and post-action learning.
removed in v4.0
v3.1 · Abstract**Keywords:** recipe execution, agent orchestration, compounded intelligence, cognitive cycle, prompt cache, subagent parallelism, structured workflows
removed in v4.0
not in v3.1
v4.0 · AbstractThe 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*.
not in v3.1
v4.0 · AbstractA 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.
not in v3.1
v4.0 · AbstractThe 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.
not in v3.1
v4.0 · Abstract**Keywords:** recipe execution, executive function, agent orchestration, workflow composition, self-authoring workflows, bounded loops, effort routing, observability, cognitive cycle

··· 1 unchanged paragraph folded ···

v3.1 · 1. Introduction --- The Recipe Gap## 1. Introduction --- The Recipe Gap
removed in v4.0
v3.1 · 1.1 Why Claude Code Works### 1.1 Why Claude Code Works
removed in v4.0
v3.1 · 1.1 Why Claude Code WorksIn March 2026, an accidental source code exposure revealed the internal architecture of Anthropic's Claude Code, the commercially leading AI coding agent. Its effectiveness derives not from a superior model, but from a `while(true)` loop wrapped in three mechanisms:
removed in v4.0
v3.1 · 1.1 Why Claude Code Works1. **Skills**: structured prompts injected on demand that encode specific workflows. A "commit" skill prescribes: check status, diff changes, review history, draft message, stage files, commit. A "review-pr" skill prescribes: fetch PR, read changes, check tests, assess impact, write review. These are not suggestions --- they are recipes that the agent executes step by step.
removed in v4.0
v3.1 · 1.1 Why Claude Code Works2. **Fork subagents**: child agents that inherit the parent's full context (exploiting prompt cache for near-zero marginal cost), run in background with isolated tool sets, and return results to the orchestrator.
removed in v4.0
v3.1 · 1.1 Why Claude Code Works3. **Five-layer context compression**: aggressive management of the context window through conversation compaction, tool result summarisation, and a `SYSTEM_PROMPT_DYNAMIC_BOUNDARY` that separates cacheable from per-turn content.
removed in v4.0
v3.1 · 1.1 Why Claude Code WorksThese are operational recipes distilled from failures.
removed in v4.0
v3.1 · 1.1 Why Claude Code WorksThe meta-pattern is clear: Claude Code's effectiveness comes from skills that are recipes, executed in sequence, by an agent that knows which recipe to apply.
removed in v4.0
v3.1 · 1.2 The Journey Kits Thesis### 1.2 The Journey Kits Thesis
removed in v4.0
v3.1 · 1.2 The Journey Kits ThesisMatthew Berman's Journey Kits (journeykits.ai, 2026) makes clear an insight that was implicit in the Claude Code analysis: **the value is not the model --- it is the structured workflow wrapped around it**. Journey Kits proposes an "npm for AI agent workflows" --- a registry of reusable recipes that bundle skills, source code, documentation, and metadata into distributable packages.
removed in v4.0
v3.1 · 1.2 The Journey Kits ThesisThe thesis is direct: if you give the same model to two teams, the one with better recipes wins. The model is the commodity; the recipe is the differentiator. This inverts the conventional wisdom that model capability is the primary driver of agent quality.
removed in v4.0
v3.1 · 1.2 The Journey Kits ThesisJourney Kits identifies the recipe as the atomic unit of agent value. A recipe is not a prompt --- it is a structured workflow with preconditions, ordered steps, success criteria, and failure handlers. The distinction matters: a prompt says "fix this bug"; a recipe says "reproduce the bug, locate the root cause, write a failing test, implement the fix, verify the test passes, check for regressions, commit with a descriptive message."
removed in v4.0
v3.1 · 1.3 The v2.4 Gap### 1.3 The v2.4 Gap
removed in v4.0
v3.1 · 1.3 The v2.4 GapVersion 2.4 of this paper promised compounded intelligence through fractal reflection --- "the compounding engine" that converts events into reusable rules at multiple abstraction levels. The implementation delivered guards, observability, and monitoring, but lacked a navigation system for agents.
removed in v4.0
v3.1 · 1.3 The v2.4 Gapv2.4 omitted the compounding engine itself. Fractal reflection, described in Section 3.1 of v2.4 as the primary mechanism of intelligence compounding, exists only as a prompt template (`prefrontal-prompt.md`) that was never wired into the execution pipeline. The four-question reflection protocol (MEMORY, PATTERN, RIPPLE, IMPROVE) runs only when the agent voluntarily follows the system prompt's instructions, which it does inconsistently.
removed in v4.0
v3.1 · 1.4 The Cache-Shared First Call### 1.4 The Cache-Shared First Call
removed in v4.0
v3.1 · 1.4 The Cache-Shared First CallThe architectural insight that enables v3.1 is economic. Anthropic's prompt cache means that a second LLM call with *nearly the same context* as the first is dramatically cheaper than two independent calls. If the system prompt, SOUL.md, memory hierarchy, and session history are identical between calls, only the differing portion (the orchestration instruction vs. the task instruction) incurs full token cost.
removed in v4.0
v3.1 · 1.4 The Cache-Shared First CallPrefrontal becomes a **first call**, planning execution at ~5% overhead. Orchestration is nearly free.
removed in v4.0
v3.1 · 1.4 The Cache-Shared First CallThe same cache property enables the fractal reflection to remain a *second call* after task completion, also at minimal marginal cost. The complete cognitive cycle --- plan, execute, reflect --- costs approximately 10% more than unorchestrated execution but produces structured, repeatable, self-improving behaviour.
removed in v4.0
not in v3.1
v4.0 · 1. Introduction — From Library to Substrate## 1. Introduction — From Library to Substrate
not in v3.1
v4.0 · 1.1 The prefrontal analogy, taken seriously### 1.1 The prefrontal analogy, taken seriously
not in v3.1
v4.0 · 1.1 The prefrontal analogy, taken seriouslyWhen 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.
not in v3.1
v4.0 · 1.1 The prefrontal analogy, taken seriouslyA 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*.
not in v3.1
v4.0 · 1.1 The prefrontal analogy, taken seriouslyThis 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.
not in v3.1
v4.0 · 1.2 What a recipe is, and why it is the right unit### 1.2 What a recipe is, and why it is the right unit
not in v3.1
v4.0 · 1.2 What a recipe is, and why it is the right unitA **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. Crucially, a recipe is *not* a prompt and *not* a script.
not in v3.1
v4.0 · 1.2 What a recipe is, and why it is the right unit- 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.
not in v3.1
v4.0 · 1.2 What a recipe is, and why it is the right unitThe 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.
not in v3.1
v4.0 · 1.3 The gap this paper closes### 1.3 The gap this paper closes
not in v3.1
v4.0 · 1.3 The gap this paper closesA 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:
not in v3.1
v4.0 · 1.3 The gap this paper closes1. **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.)
not in v3.1
v4.0 · 1.3 The gap this paper closesThe 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 lists suggested diagrams; Section 12 concludes.

··· 1 unchanged paragraph folded ···

v3.1 · 2. Architecture --- The Orchestrator Model## 2. Architecture --- The Orchestrator Model
removed in v4.0
v3.1 · 2.1 System Overview### 2.1 System Overview
removed in v4.0
v3.1 · 2.1 System OverviewPrefrontal v3.1 introduces a three-phase cognitive cycle that wraps every agent interaction:
removed in v4.0
v3.1 · 2.1 System Overview``` User message | v [Phase 1: PLAN] -- Prefrontal LLM call (cache-shared) | - Classify intent | - Select or compose recipe | - Present plan to user (if complex) | - Allocate subagents v [Phase 2: EXECUTE] -- Subagent dispatch | - Fan-out workers with isolated contexts | - Prefrontal monitors progress via events | - Stall detection and intervention | - Periodic status updates to UI v [Phase 3: REFLECT] -- Fractal reflection (cache-shared) | - MEMORY: persist new knowledge | - PATTERN: multi-level abstraction | - RIPPLE: scan for staleness | - IMPROVE: opportunistic fixes v Response to user ```
removed in v4.0
v3.1 · 2.1 System Overview**Figure 1.** The three-phase cognitive cycle. Phases 1 and 3 are cache-shared LLM calls with approximately 5% token overhead each. Phase 2 is standard agent execution with Prefrontal monitoring via WebSocket events.
removed in v4.0
v3.1 · 2.1 System OverviewFor simple requests, Phase 1 bypasses recipe selection to avoid overhead.
removed in v4.0
v3.1 · 2.2 Prefrontal as First Call### 2.2 Prefrontal as First Call
removed in v4.0
v3.1 · 2.2 Prefrontal as First CallThe traditional agent architecture processes user messages directly: the message enters the model alongside the system prompt, and the model decides what to do. Prefrontal v3.1 interposes an orchestration layer:
removed in v4.0
v3.1 · 2.2 Prefrontal as First Call1. The user's message arrives at the gateway. 2. **Before** the main agent processes it, Prefrontal receives the message with the same context (SOUL.md, memory hierarchy, session history) plus an orchestration-specific instruction set. 3. Prefrontal classifies the intent, selects a recipe, and emits a structured plan. 4. The plan is injected into the main agent's context as a structured preamble. 5. The main agent executes with the recipe's steps as explicit guidance.
removed in v4.0
v3.1 · 2.2 Prefrontal as First CallThe critical design decision is that Prefrontal does *not* replace the main agent, nor does it introduce a separate "manager agent". Prefrontal is a cache-shared first call using the *exact same agent*, simply prepending the recipe. The main agent retains full autonomy; the recipe provides structure, not bureaucratic constraint. This preserves the flexibility that makes LLM agents valuable while adding the predictability that makes them reliable.
removed in v4.0
v3.1 · 2.2 Prefrontal as First Call**Why first, not second?** Version 2.4's fractal reflection operated as a post-action review --- useful for learning, but unable to prevent the mistakes it learned from. By moving to a pre-action position, Prefrontal can shape the agent's approach *before* tokens are spent on a flawed strategy. The post-action reflection remains, but now reviews execution against the plan rather than against an implicit standard.
removed in v4.0
v3.1 · 2.3 The Cache Trick### 2.3 The Cache Trick
removed in v4.0
v3.1 · 2.3 The Cache TrickThe economics of this architecture depend entirely on prompt caching. Consider a typical agent turn:
removed in v4.0
v3.1 · 2.3 The Cache Trick| Component | Tokens | Cached? | |-----------|--------|---------| | System prompt (SOUL.md, agents, rules) | ~8,000 | Yes (static) | | Memory hierarchy (retrieved files) | ~4,000 | Yes (session) | | Session history | ~6,000 | Yes (session) | | Orchestration instruction | ~800 | No | | User message | ~200 | No | | **Total** | **~19,000** | **~95% cached** |
removed in v4.0
v3.1 · 2.3 The Cache TrickThe Prefrontal call uses the same first 18,000 tokens as the main agent call. Only the orchestration instruction (replacing the main agent's task instruction) differs. At Anthropic's cache pricing (90% discount on cached tokens), the Prefrontal call costs approximately 5% of a full call.
removed in v4.0
v3.1 · 2.3 The Cache TrickThis is not an optimisation --- it is an architectural enabler. Without prompt caching, a pre-action orchestration call would double the cost of every turn. With it, orchestration is nearly free, and the question shifts from "can we afford orchestration?" to "can we afford *not* to orchestrate?"
removed in v4.0
v3.1 · 2.4 Subagent Parallelism### 2.4 Subagent Parallelism
removed in v4.0
v3.1 · 2.4 Subagent ParallelismFor decomposable tasks, Prefrontal fans out parallel subagents:
removed in v4.0
v3.1 · 2.4 Subagent Parallelism- **Fork subagents** inherit the parent's rendered prompt (cache-shared) and receive a scoped task: "investigate the stack trace," "write a failing test," "check for similar patterns in the codebase."
removed in v4.0
v3.1 · 2.4 Subagent Parallelism- **Prefrontal monitors** subagent progress via WebSocket events. Each subagent emits structured status updates: task accepted, tool calls in progress, intermediate findings, completion with results.
removed in v4.0
v3.1 · 2.4 Subagent Parallelism- **Stall detection**: if a subagent exceeds its expected duration (configurable per recipe step, default 120 seconds) or enters a tool-denial loop (3 consecutive denials), Prefrontal intervenes --- either reassigning the task, providing additional context, or escalating to the user.
removed in v4.0
v3.1 · 2.4 Subagent Parallelism- **Result aggregation**: as subagents complete, Prefrontal assembles their outputs into a coherent response. For investigation tasks, this means synthesising findings. For implementation tasks, this means verifying consistency across parallel changes.
removed in v4.0
v3.1 · 2.4 Subagent ParallelismThe parallelism model mirrors Claude Code's fork pattern but adds active monitoring. Claude Code's forked subagents run independently and return results; Prefrontal's subagents are *supervised* --- the orchestrator watches their progress and can intervene. This supervision is the difference between delegation and orchestration.
removed in v4.0
v3.1 · 2.5 Periodic Progress Reports### 2.5 Periodic Progress Reports
removed in v4.0
v3.1 · 2.5 Periodic Progress ReportsFor long-running tasks (multi-file refactors, complex investigations, deployment sequences), Prefrontal emits periodic status updates to the Tinker UI via WebSocket events:
removed in v4.0
v3.1 · 2.5 Periodic Progress Reports```json { "type": "prefrontal:progress", "recipe": "feature-implementation", "step": 3, "totalSteps": 7, "stepName": "Write failing tests", "subagents": [ {"id": "sa-001", "status": "complete", "task": "Investigate root cause"}, {"id": "sa-002", "status": "running", "task": "Write test cases", "elapsed": "45s"}, {"id": "sa-003", "status": "pending", "task": "Implement fix"} ], "elapsed": "2m15s" } ```
removed in v4.0
v3.1 · 2.5 Periodic Progress ReportsThe Tinker UI renders these as a real-time progress panel in the right sidebar, extending the existing call tree with recipe step indicators, subagent status badges, and elapsed time per step. Users see not just *that* the agent is working, but *what* it is doing, *where* it is in the recipe, and *how long* each step is taking.
removed in v4.0
v3.1 · 2.6 Visualisation: The Call Tree### 2.6 Visualisation: The Call Tree
removed in v4.0
v3.1 · 2.6 Visualisation: The Call TreeThe existing Prefrontal call tree panel (`prefrontal-tree.ts`) displays agent topology with real-time phase indicators. Version 3.0 extends this with:
removed in v4.0
v3.1 · 2.6 Visualisation: The Call Tree- **Recipe overlay**: the current recipe's steps are displayed as a vertical timeline alongside the call tree, with the active step highlighted and completed steps checked. - **Subagent mapping**: each subagent node in the tree is linked to its recipe step, showing which part of the plan each worker is executing. - **Cost tracking**: cumulative token usage per subagent and per recipe step, enabling real-time cost visibility. - **Stall indicators**: subagents that exceed their expected duration are highlighted with a warning indicator, and Prefrontal's intervention actions are displayed inline.
removed in v4.0
not in v3.1
v4.0 · 2. Architecture — The Executive-Function Cycle## 2. Architecture — The Executive-Function Cycle
not in v3.1
v4.0 · 2.1 The cycle### 2.1 The cycle
not in v3.1
v4.0 · 2.1 The cyclePREFRONTAL wraps every interaction in a five-phase cycle that mirrors executive function:
not in v3.1
v4.0 · 2.1 The cycle``` user message | v PLAN classify intent; gauge effort tier <- effort routing decides the gear | v MATCH / score recipes (fuzzy + confidence); <- task-set selection COMPOSE / merge or compose; on no-match, AUTHOR author a new recipe | v EXECUTE run the plan; fan out parallel groups; <- sequencing + sub-routine calls (w/loops) recurse sub-recipes; loop steps | v OBSERVE render provenance, step progress, <- metacognitive monitoring subagent vitals to RECIPES panel | v ADAPT reflect; tune effort & recipes for <- learning + regulation next turn | v response to user ```
not in v3.1
v4.0 · 2.1 The cycle**Figure 1 (described in §11).** The five-phase executive cycle, annotated with the executive function each phase implements.
not in v3.1
v4.0 · 2.1 The cycleA 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.
not in v3.1
v4.0 · 2.2 Where the structure comes from, and when it is cheap### 2.2 Where the structure comes from, and when it is cheap
not in v3.1
v4.0 · 2.2 Where the structure comes from, and when it is cheapThe 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.
not in v3.1
v4.0 · 2.2 Where the structure comes from, and when it is cheapFirst, **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.
not in v3.1
v4.0 · 2.2 Where the structure comes from, and when it is cheapSecond, **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.
not in v3.1
v4.0 · 2.2 Where the structure comes from, and when it is cheapThird, **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?"
not in v3.1
v4.0 · 2.3 Plans as the runtime trace of recipes### 2.3 Plans as the runtime trace of recipes
not in v3.1
v4.0 · 2.3 Plans as the runtime trace of recipesA 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.
not in v3.1
v4.0 · 2.3 Plans as the runtime trace of recipesBecause 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.

··· 1 unchanged paragraph folded ···

v3.1 · 3. The Recipe System## 3. The Recipe System
removed in v4.0
v3.1 · 3.1 Recipe Format### 3.1 Recipe Format
removed in v4.0
v3.1 · 3.1 Recipe FormatA recipe is a structured markdown document with the following schema:
removed in v4.0
v3.1 · 3.1 Recipe Format```markdown # Recipe: debug
removed in v4.0
v3.1 · Metadata - intent: bug-fix, error-investigation, crash-analysis - complexity: medium - estimated-duration: 5-15 minutes - models: [sonnet, opus]## Metadata - intent: bug-fix, error-investigation, crash-analysis - complexity: medium - estimated-duration: 5-15 minutes - models: [sonnet, opus]
removed in v4.0
v3.1 · Preconditions - [ ] Error report or symptom description available - [ ] Repository context loaded## Preconditions - [ ] Error report or symptom description available - [ ] Repository context loaded
removed in v4.0
v3.1 · Steps## Steps
removed in v4.0
v3.1 · Step 1: Reproduce Confirm the bug exists. Run the failing command, check logs, verify the symptom. - tools: [Bash, Read] - gate: Must have confirmed reproduction before proceeding.### Step 1: Reproduce Confirm the bug exists. Run the failing command, check logs, verify the symptom. - tools: [Bash, Read] - gate: Must have confirmed reproduction before proceeding.
removed in v4.0
v3.1 · Step 2: Locate Find the root cause. Search the codebase, read stack traces, trace the execution path. - tools: [Grep, Glob, Read] - gate: Must have identified a specific file and line range.### Step 2: Locate Find the root cause. Search the codebase, read stack traces, trace the execution path. - tools: [Grep, Glob, Read] - gate: Must have identified a specific file and line range.
removed in v4.0
v3.1 · Step 3: Understand Read the surrounding code. Understand the intent, the constraints, the history. - tools: [Read, Bash(git log)] - gate: Must articulate why the current code is wrong.### Step 3: Understand Read the surrounding code. Understand the intent, the constraints, the history. - tools: [Read, Bash(git log)] - gate: Must articulate why the current code is wrong.
removed in v4.0
v3.1 · Step 4: Fix Implement the minimal fix. Change only what is necessary. - tools: [Edit, Write] - gate: Fix must be consistent with the root cause from Step 2.### Step 4: Fix Implement the minimal fix. Change only what is necessary. - tools: [Edit, Write] - gate: Fix must be consistent with the root cause from Step 2.
removed in v4.0
v3.1 · Step 5: Verify Run tests. Check that the fix works and nothing else broke. - tools: [Bash] - gate: All relevant tests must pass.### Step 5: Verify Run tests. Check that the fix works and nothing else broke. - tools: [Bash] - gate: All relevant tests must pass.
removed in v4.0
v3.1 · Step 6: Document Update any affected documentation, comments, or memory files. - tools: [Edit, Write] - gate: No stale documentation remains.### Step 6: Document Update any affected documentation, comments, or memory files. - tools: [Edit, Write] - gate: No stale documentation remains.
removed in v4.0
v3.1 · Success Criteria - Bug is fixed and verified by test - Root cause is documented - No regressions introduced## Success Criteria - Bug is fixed and verified by test - Root cause is documented - No regressions introduced
removed in v4.0
v3.1 · Failure Handlers - Step 1 fails (cannot reproduce): Gather more information from user - Step 4 fails (fix too complex): Escalate to user with analysis - Step 5 fails (tests break): Revert and re-analyse ```## Failure Handlers - Step 1 fails (cannot reproduce): Gather more information from user - Step 4 fails (fix too complex): Escalate to user with analysis - Step 5 fails (tests break): Revert and re-analyse ```
removed in v4.0
v3.1 · Failure Handlers - Step 1 fails (cannot reproduce): Gather more information from user - Step 4 fails (fix too complex): Escalate to user with analysis - Step 5 fails (tests break): Revert and re-analyse ```Recipes are human-readable markdown files, editable, storable in memory, and versionable via git, favouring transparency and composability.
removed in v4.0
v3.1 · 3.2 Built-in Recipes### 3.2 Built-in Recipes
removed in v4.0
v3.1 · 3.2 Built-in RecipesPrefrontal v3.1 ships with six built-in recipes covering the most common agent tasks:
removed in v4.0
v3.1 · 3.2 Built-in Recipes| Recipe | Steps | Typical Duration | Key Insight | |--------|-------|-----------------|-------------| | **debug** | 6 (reproduce, locate, understand, fix, verify, document) | 5--15 min | Must reproduce before fixing | | **feature** | 7 (clarify, design, plan, implement, test, verify, document) | 10--30 min | Must design before implementing | | **investigate** | 5 (scope, search, analyse, synthesise, report) | 5--20 min | Must scope before searching | | **refactor** | 6 (identify, measure, plan, execute, verify, document) | 10--25 min | Must measure before changing | | **review** | 5 (overview, deep-read, test, assess, report) | 5--15 min | Must read completely before opining | | **deploy** | 7 (pre-check, build, test, stage, verify, promote, post-check) | 10--40 min | Must verify at every stage |
removed in v4.0
v3.1 · 3.2 Built-in RecipesEach recipe encodes hard-won operational lessons. The debug recipe's "reproduce before fixing" step prevents the most common agent failure mode: jumping directly to a code change based on the error message without confirming the bug's actual behaviour. The feature recipe's "design before implementing" step prevents premature coding --- the anti-gold-plating principle elevated from a prompt injection to a structural gate.
removed in v4.0
v3.1 · 3.3 Custom Recipes### 3.3 Custom Recipes
removed in v4.0
v3.1 · 3.3 Custom RecipesUsers can author domain-specific recipes and add them to the recipe library. A data-science team might add recipes for "explore-dataset," "train-model," and "evaluate-results." A DevOps team might add "incident-response," "capacity-planning," and "runbook-execution."
removed in v4.0
v3.1 · 3.3 Custom RecipesCustom recipes are stored in the memory hierarchy (under `memory/recipes/`) and are automatically available to Prefrontal's recipe selection. This makes the recipe library a *growing* asset --- each new recipe captures operational knowledge that compounds across future sessions, extending the compounding thesis from individual lessons (v2.4) to entire workflows (v3.1).
removed in v4.0
v3.1 · 3.4 Recipe Selection### 3.4 Recipe Selection
removed in v4.0
v3.1 · 3.4 Recipe SelectionWhen a user message arrives, Prefrontal classifies the intent and selects the appropriate recipe through a three-tier strategy:
removed in v4.0
v3.1 · 3.4 Recipe Selection1. **Keyword matching**: explicit signals in the message ("fix this bug" -> debug, "add a feature" -> feature, "what's going on with" -> investigate). Fast, cheap, handles the common cases.
removed in v4.0
v3.1 · 3.4 Recipe Selection2. **Structure analysis**: message length, presence of error messages or stack traces, code blocks, file paths. A message with a stack trace is likely a debug task even if it does not contain the word "bug."
removed in v4.0
v3.1 · 3.4 Recipe Selection3. **LLM classification**: for ambiguous messages, Prefrontal's LLM call includes recipe metadata (intent keywords, descriptions) and selects the best match. This is the same call that performs the orchestration, so it incurs no additional cost.
removed in v4.0
v3.1 · 3.4 Recipe SelectionUnstructured messages bypass orchestration.
removed in v4.0
v3.1 · 3.5 Step Enforcement### 3.5 Step Enforcement
removed in v4.0
v3.1 · 3.5 Step EnforcementEach recipe step includes a **gate** --- a condition that must be satisfied before the agent proceeds to the next step. Gates are expressed in natural language and evaluated by the orchestrator:
removed in v4.0
v3.1 · 3.5 Step Enforcement- *"Must have confirmed reproduction before proceeding"* --- Prefrontal checks whether the subagent's output includes evidence of reproduction (a failing test, a reproduced error message, a confirmed symptom). - *"Must have identified a specific file and line range"* --- Prefrontal checks for file paths and line numbers in the investigation output.
removed in v4.0
v3.1 · 3.5 Step EnforcementGates are advisory, not absolute. If a subagent presents a compelling case for skipping a step ("the bug is obvious from the error message, reproduction is unnecessary"), Prefrontal can grant an exception. The enforcement is structural --- it creates a default path of thoroughness that requires explicit justification to deviate from, rather than a rigid pipeline that breaks on edge cases.
removed in v4.0
v3.1 · 3.5 Step EnforcementThis is the critical difference between a recipe and a script. A script executes mechanically; a recipe provides structure that an intelligent agent can follow, adapt, or override with justification.
removed in v4.0
not in v3.1
v4.0 · 3. Capability 1 — Recipe Matching (Task-Set Selection)## 3. Capability 1 — Recipe Matching (Task-Set Selection)
not in v3.1
v4.0 · 3.1 The problem with literal matching### 3.1 The problem with literal matching
not in v3.1
v4.0 · 3.1 The problem with literal matchingThe 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.
not in v3.1
v4.0 · 3.2 Fuzzy, stemmed, edit-distance scoring### 3.2 Fuzzy, stemmed, edit-distance scoring
not in v3.1
v4.0 · 3.2 Fuzzy, stemmed, edit-distance scoringThe 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:
not in v3.1
v4.0 · 3.2 Fuzzy, stemmed, edit-distance scoring- **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.
not in v3.1
v4.0 · 3.2 Fuzzy, stemmed, edit-distance scoringThe 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.
not in v3.1
v4.0 · 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 return score
not in v3.1
v4.0 · 3.2 Fuzzy, stemmed, edit-distance scoringfunction 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) ```
not in v3.1
v4.0 · 3.3 Confidence tiers and what they gate### 3.3 Confidence tiers and what they gate
not in v3.1
v4.0 · 3.3 Confidence tiers and what they gateRaw 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:
not in v3.1
v4.0 · 3.3 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 top >= threshold + 3 and top - second >= 2: return "high" # clear leader return "low" # barely over, or a tie ```
not in v3.1
v4.0 · 3.3 Confidence tiers and what they gate- **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).
not in v3.1
v4.0 · 3.4 Auto-seeding at turn start### 3.4 Auto-seeding at turn start
not in v3.1
v4.0 · 3.4 Auto-seeding at turn startThe 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.
not in v3.1
v4.0 · 3.4 Auto-seeding at turn startThe 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.

··· 1 unchanged paragraph folded ···

v3.1 · 4. The Cognitive Cycle (Complete)## 4. The Cognitive Cycle (Complete)
removed in v4.0
v3.1 · 4. The Cognitive Cycle (Complete)Version 2.4 acknowledged that its architecture captured "only the second half" of the cognitive cycle --- post-action reflection without pre-action planning. GStack's forcing questions (Tan, 2026) demonstrated the value of pre-action reflection, and we incorporated a minimal version (five forcing questions for complex tasks). But forcing questions are not planning --- they refine intent without producing a structured execution strategy.
removed in v4.0
v3.1 · 4. The Cognitive Cycle (Complete)Version 3.0 completes the cycle.
removed in v4.0
v3.1 · 4.1 Pre-Action: From Questions to Recipes### 4.1 Pre-Action: From Questions to Recipes
removed in v4.0
v3.1 · 4.1 Pre-Action: From Questions to RecipesThe pre-action phase now encompasses:
removed in v4.0
v3.1 · 4.1 Pre-Action: From Questions to Recipes1. **Forcing questions** (retained from v2.4): What is the user *actually* asking? What would a wrong answer look like? What constraints exist? These questions refine intent.
removed in v4.0
v3.1 · 4.1 Pre-Action: From Questions to Recipes2. **Recipe selection**: based on the refined intent, Prefrontal selects or composes an appropriate recipe. For standard tasks, this means choosing from the built-in library. For novel tasks, Prefrontal composes an ad hoc recipe by combining steps from multiple templates.
removed in v4.0
v3.1 · 4.1 Pre-Action: From Questions to Recipes3. **Plan presentation**: for complex tasks (estimated duration >5 minutes or >3 steps), Prefrontal presents the plan to the user before execution. This allows user redirection and creates an execution contract.
removed in v4.0
v3.1 · 4.1 Pre-Action: From Questions to Recipes4. **Subagent allocation**: Prefrontal assigns recipe steps to subagents, selecting appropriate models for each (Haiku for simple searches, Sonnet for implementation, Opus for complex reasoning). This operationalises the adaptive effort routing from v2.4 at the recipe level.
removed in v4.0
v3.1 · 4.2 During-Action: Supervised Execution### 4.2 During-Action: Supervised Execution
removed in v4.0
v3.1 · 4.2 During-Action: Supervised ExecutionThe during-action phase is entirely new. Version 2.4 had no mechanism for monitoring agent execution in progress --- the agent ran, and the reflection reviewed the outcome. Version 3.0 introduces:
removed in v4.0
v3.1 · 4.2 During-Action: Supervised Execution- **Progress & Updates**: Subagents emit structured events. Prefrontal updates the UI, showing active steps and progress. - **Stall detection**: Prefrontal detects stalls (timeouts, retry loops) and intervenes by reassigning or providing context. - **Cross-subagent coordination**: Prefrontal relays critical findings between parallel subagents to prevent wasted effort.
removed in v4.0
v3.1 · 4.3 Post-Action: Fractal Reflection, Orchestrated### 4.3 Post-Action: Fractal Reflection, Orchestrated
removed in v4.0
v3.1 · 4.3 Post-Action: Fractal Reflection, OrchestratedThe post-action phase retains v2.4's fractal reflection protocol (MEMORY, PATTERN, RIPPLE, IMPROVE) but elevates it from a voluntary prompt instruction to an *orchestrated execution*:
removed in v4.0
v3.1 · 4.3 Post-Action: Fractal Reflection, Orchestrated1. **Mandatory execution**: Reflection is a distinct, unavoidable LLM call post-completion. 2. **Recipe-aware reflection**: Reflection assesses the turn context, recipe, plan, and execution trace to identify bottlenecks. 3. **Recipe improvement**: Prefrontal updates recipes automatically when systematic issues are identified. 4. **Structured Knowledge**: Extracted lessons are written to memory, deeply tied to their specific recipe context for higher actionability.
removed in v4.0
v3.1 · 4.4 The FRACTAL Pattern: Cache-Shared Follow-Up Calls### 4.4 The FRACTAL Pattern: Cache-Shared Follow-Up Calls
removed in v4.0
v3.1 · 4.4 The FRACTAL Pattern: Cache-Shared Follow-Up CallsThe architectural pattern underlying both the pre-action orchestration and the post-action reflection is what we call the **FRACTAL pattern**: a cache-shared follow-up call with a different role.
removed in v4.0
v3.1 · 4.4 The FRACTAL Pattern: Cache-Shared Follow-Up CallsThe fork's `fractal-reflection` extension already implements this pattern for post-action reflection: it makes a second LLM call after each turn, with nearly the same context (exploiting the prompt cache), but with a different instruction ("reflect on what just happened" instead of "execute the user's request"). Version 3.0 applies the same pattern to pre-action orchestration: a first LLM call with the same context but a different instruction ("plan how to handle this request" instead of "handle this request").
removed in v4.0
v3.1 · 4.4 The FRACTAL Pattern: Cache-Shared Follow-Up CallsThe FRACTAL pattern applies generally: any cognitive function (planning, reflection, review) can be implemented via cache-shared calls at ~5% marginal cost, enabling multiple perspectives per turn.
removed in v4.0
not in v3.1
v4.0 · 4. Capability 2 — Composition (Recipes Built from Recipes)## 4. Capability 2 — Composition (Recipes Built from Recipes)
not in v3.1
v4.0 · 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.
not in v3.1
v4.0 · 4.1 Static composition — step-merge (`composes:`)### 4.1 Static composition — step-merge (`composes:`)
not in v3.1
v4.0 · 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.
not in v3.1
v4.0 · 4.1 Static composition — step-merge (`composes:`)``` 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) ```
not in v3.1
v4.0 · 4.1 Static composition — step-merge (`composes:`)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.
not in v3.1
v4.0 · 4.2 Dynamic composition — runtime sub-recipe calls (`uses:`)### 4.2 Dynamic composition — runtime sub-recipe calls (`uses:`)
not in v3.1
v4.0 · 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.
not in v3.1
v4.0 · 4.2 Dynamic composition — runtime sub-recipe calls (`uses:`)Two safeguards keep recursion safe, exactly as a runtime keeps a call stack from overflowing:
not in v3.1
v4.0 · 4.2 Dynamic composition — runtime sub-recipe calls (`uses:`)- **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.
not in v3.1
v4.0 · 4.2 Dynamic composition — runtime sub-recipe calls (`uses:`)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.
not in v3.1
v4.0 · 4.2 Dynamic composition — runtime sub-recipe calls (`uses:`)``` 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) ```
not in v3.1
v4.0 · 4.2 Dynamic composition — runtime sub-recipe calls (`uses:`)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.

··· 1 unchanged paragraph folded ···

v3.1 · 5. Integration with Existing Extensions## 5. Integration with Existing Extensions
removed in v4.0
v3.1 · 5. Integration with Existing ExtensionsPrefrontal v3.1 does not replace the existing extension ecosystem --- it orchestrates it. Each extension retains its autonomous function while gaining a coordination layer.
removed in v4.0
v3.1 · 5.1 Total Recall (Memory Retrieval)### 5.1 Total Recall (Memory Retrieval)
removed in v4.0
v3.1 · 5.1 Total Recall (Memory Retrieval)Total Recall provides the hybrid retrieval system (semantic search via local embeddings + structured search via filename patterns) that supplies context to every agent turn. In v3.1, Prefrontal uses Total Recall in two new ways:
removed in v4.0
v3.1 · 5.1 Total Recall (Memory Retrieval)- **Recipe-contextual retrieval**: when selecting a recipe, Prefrontal queries Total Recall for prior executions of the same recipe type, injecting relevant lessons into the plan. "Last time you ran the debug recipe on this module, the root cause was in the dependency injection layer."
removed in v4.0
v3.1 · 5.1 Total Recall (Memory Retrieval)- **Reflection-driven writes**: knowledge extracted during fractal reflection is written back through Total Recall's indexing pipeline, ensuring new lessons are immediately retrievable in future sessions.
removed in v4.0
v3.1 · 5.2 Identity Persistence (SOUL.md)### 5.2 Identity Persistence (SOUL.md)
removed in v4.0
v3.1 · 5.2 Identity Persistence (SOUL.md)The agent's identity --- personality, values, communication style --- is encoded in SOUL.md and loaded into every LLM call. In v3.1, this identity persists across all three phases of the cognitive cycle. The Prefrontal orchestration call, the subagent execution calls, and the fractal reflection call all share the same SOUL.md, ensuring that the agent's personality is consistent whether it is planning, executing, or reflecting.
removed in v4.0
v3.1 · 5.2 Identity Persistence (SOUL.md)By sharing SOUL.md across all calls, Prefrontal maintains a unified voice, avoiding the personality discontinuities of separate "planner" agents.
removed in v4.0
v3.1 · 5.3 Learned Intuition (AMYGDALA)### 5.3 Learned Intuition (AMYGDALA)
removed in v4.0
v3.1 · 5.3 Learned Intuition (AMYGDALA)The AMYGDALA extension (Serra, 2026) --- a neural action gating system that learns to recognise dangerous operations through situation embeddings --- integrates with v3.1 at the subagent level. Each subagent's tool calls pass through AMYGDALA's prudence network before execution, providing learned safety gating that complements the recipe's structural gates.
removed in v4.0
v3.1 · 5.3 Learned Intuition (AMYGDALA)The integration is bidirectional: AMYGDALA's training data now includes recipe context (which step, which recipe, what preconditions were met), enabling the prudence network to learn that "a file write during debug.fix after successful debug.locate is safe" while "a file write without prior investigation is dangerous." Recipe context makes safety gating more precise.
removed in v4.0
v3.1 · 5.4 Fractal Reflection (Orchestrated)### 5.4 Fractal Reflection (Orchestrated)
removed in v4.0
v3.1 · 5.4 Fractal Reflection (Orchestrated)In v2.4, the `fractal-reflection` extension operated independently --- a post-turn LLM call that ran on its own schedule. In v3.1, Prefrontal orchestrates when reflection runs and what context it receives:
removed in v4.0
v3.1 · 5.4 Fractal Reflection (Orchestrated)- **After recipe completion**: full reflection with recipe context, execution trace, and plan comparison. - **After simple tasks**: lightweight reflection (MEMORY only, skip PATTERN/RIPPLE/IMPROVE). - **After failures**: extended reflection with root cause analysis and recipe update recommendations.
removed in v4.0
v3.1 · 5.4 Fractal Reflection (Orchestrated)This orchestration eliminates the "reflection fatigue" identified in v2.4 Section 5.6 --- the problem of mandatory reflection on every turn creating visible latency during rapid exchanges. By matching reflection depth to task complexity, v3.1 preserves compounding while reducing overhead.
removed in v4.0
not in v3.1
v4.0 · 5. Capability 3 — On-the-Fly Authoring (Skill Acquisition)## 5. Capability 3 — On-the-Fly Authoring (Skill Acquisition)
not in v3.1
v4.0 · 5.1 Closing the no-match loop### 5.1 Closing the no-match loop
not in v3.1
v4.0 · 5.1 Closing the no-match loopThe executive analogue here is skill acquisition: when a person meets a task for which they have no rehearsed program, they construct one — and, crucially, 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.
not in v3.1
v4.0 · 5.1 Closing the no-match loopWhen 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.
not in v3.1
v4.0 · 5.2 Validation — the gate against a corrupt library### 5.2 Validation — the gate against a corrupt library
not in v3.1
v4.0 · 5.2 Validation — the gate against a corrupt libraryA 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:
not in v3.1
v4.0 · 5.2 Validation — the gate against a corrupt library``` 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 ```
not in v3.1
v4.0 · 5.2 Validation — the gate against a corrupt libraryThree 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.
not in v3.1
v4.0 · 5.3 Provenance and the never-overwrite rule### 5.3 Provenance and the never-overwrite rule
not in v3.1
v4.0 · 5.3 Provenance and the never-overwrite ruleAuthored 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.)
not in v3.1
v4.0 · 5.3 Provenance and the never-overwrite ruleThis 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.

··· 1 unchanged paragraph folded ···

v3.1 · 6. Evaluation Design## 6. Evaluation Design
removed in v4.0
v3.1 · 6.1 FAAR Improvement Targets### 6.1 FAAR Improvement Targets
removed in v4.0
v3.1 · 6.1 FAAR Improvement TargetsThe recipe system should produce measurable improvements in first-attempt accuracy by preventing the most common failure modes:
removed in v4.0
v3.1 · 6.1 FAAR Improvement Targets| Failure Mode | v2.4 FAAR Impact | v3.1 Mechanism | Target FAAR Delta | |-------------|-------------------|----------------|-------------------| | Fixing without reproducing | -0.08 | debug recipe step gate | +0.06 | | Coding without designing | -0.06 | feature recipe step gate | +0.04 | | Searching without scoping | -0.05 | investigate recipe step gate | +0.03 | | Skipping verification | -0.04 | all recipes include verify step | +0.03 | | **Cumulative** | **-0.23** | | **+0.16** |
removed in v4.0
v3.1 · 6.1 FAAR Improvement TargetsThese targets would move the weighted FAAR from 0.90 to ~0.95.
removed in v4.0
v3.1 · 6.2 Cost Analysis### 6.2 Cost Analysis
removed in v4.0
v3.1 · 6.2 Cost AnalysisThe recipe engine adds two LLM calls per complex task (orchestration + reflection). The cost depends on cache hit rates:
removed in v4.0
v3.1 · 6.2 Cost Analysis| Scenario | Cache Hit Rate | Overhead per Turn | Monthly Impact (est.) | |----------|---------------|-------------------|----------------------| | Optimal (stable context) | 95% | ~5% per call, ~10% total | +$2--4 | | Typical (moderate context churn) | 85% | ~8% per call, ~16% total | +$4--8 | | Worst case (high context churn) | 70% | ~15% per call, ~30% total | +$8--15 |
removed in v4.0
v3.1 · 6.2 Cost AnalysisEven worst-case overhead is modest compared to savings from improved first-attempt accuracy.
removed in v4.0
v3.1 · 6.3 Latency Analysis### 6.3 Latency Analysis
removed in v4.0
v3.1 · 6.3 Latency AnalysisThe orchestration call adds latency before the agent begins visible work:
removed in v4.0
v3.1 · 6.3 Latency Analysis| Task Complexity | Orchestration Latency | User-Perceived Impact | |----------------|----------------------|----------------------| | Simple (passthrough) | <100ms (classification only) | None | | Medium (recipe selection) | 1--3s | Minor (plan displayed immediately) | | Complex (recipe + subagent allocation) | 3--8s | Offset by progress visibility |
removed in v4.0
v3.1 · 6.3 Latency AnalysisFor complex tasks, the orchestration latency is offset by faster overall completion (fewer retries, fewer wrong turns) and improved user experience (progress visibility instead of opaque waiting).
removed in v4.0
v3.1 · 6.4 Comparison with Claude Code's Skill System### 6.4 Comparison with Claude Code's Skill System
removed in v4.0
v3.1 · 6.4 Comparison with Claude Code's Skill System| Dimension | Claude Code Skills | Prefrontal Recipes | |-----------|-------------------|-------------------| | Selection | Hard-coded triggers in system prompt | LLM-classified intent matching | | Execution | Injected as prompt text, agent follows voluntarily | Orchestrated with step gates and monitoring | | Parallelism | Fork subagents, unsupervised | Fork subagents, supervised by Prefrontal | | Learning | Skills are static (updated by developers) | Recipes evolve through fractal reflection | | Cost model | Single call (skill text in prompt) | Cache-shared calls (~10% overhead) | | Failure handling | Agent's own judgment | Structured failure handlers per step |
removed in v4.0
v3.1 · 6.4 Comparison with Claude Code's Skill SystemThe key differentiator is **learning**. Claude Code's skills are effective but static --- they encode developer knowledge at deployment time and do not improve through use. Prefrontal's recipes evolve: each execution generates reflection data that can update the recipe itself, creating a compounding loop where recipes get better the more they are used.
removed in v4.0
not in v3.1
v4.0 · 6. Capability 4 — Recipe Loops (The Structural Gap, Closed)## 6. Capability 4 — Recipe Loops (The Structural Gap, Closed)
not in v3.1
v4.0 · 6.1 Why loops are the dividing line### 6.1 Why loops are the dividing line
not in v3.1
v4.0 · 6.1 Why loops are the dividing lineA 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.
not in v3.1
v4.0 · 6.2 Three bounded loop modes### 6.2 Three bounded loop modes
not in v3.1
v4.0 · 6.2 Three bounded loop modesA 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:
not in v3.1
v4.0 · 6.2 Three bounded loop modes- `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*.
not in v3.1
v4.0 · 6.2 Three bounded loop modesThe "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.
not in v3.1
v4.0 · 6.2 Three bounded loop modes``` 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
not in v3.1
v4.0 · 6.2 Three bounded loop modesfunction IS_DRY(note): if note is empty: return true return note matches /no new | nothing left | complete | exhausted | finished | all (covered|done)/ ```
not in v3.1
v4.0 · 6.3 Bounded by construction — the anti-runaway guarantee### 6.3 Bounded by construction — the anti-runaway guarantee
not in v3.1
v4.0 · 6.3 Bounded by construction — the anti-runaway guaranteeA 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.
not in v3.1
v4.0 · 6.3 Bounded by construction — the anti-runaway guarantee`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.

··· 1 unchanged paragraph folded ···

v3.1 · 6.5 Failure Modes and Limitations### 6.5 Failure Modes and Limitations
removed in v4.0
v3.1 · 6.5 Failure Modes and LimitationsWhile cache-shared orchestration minimizes overhead, it is vulnerable to **cache evictions**. If the session goes dormant and Anthropic evicts the prompt cache, Phase 1 incurs a full context token cost. Furthermore, complex recipes with many parallel subagents can exhaust API rate limits, requiring the orchestrator to pace execution or queue sub-tasks. ## 7. Implementation Status
removed in v4.0
v3.1 · 7.1 What Is Built (v2.4 Baseline)### 7.1 What Is Built (v2.4 Baseline)
removed in v4.0
v3.1 · 7.1 What Is Built (v2.4 Baseline)The following components are deployed and operational:
removed in v4.0
v3.1 · 7.1 What Is Built (v2.4 Baseline)- **Exploration gate**: blocks mutating tools until read-only operations are performed. Live, hooked into every turn. - **Anti-gold-plating rules**: 11 engineering discipline injections. Live. - **Forcing questions**: 5 pre-action questions for complex tasks. Live. - **Denial tracking**: escalation after 3 consecutive tool denials. Live. - **Permission hooks**: user-defined shell script gates. Live. - **FAAR tracker**: task outcome recording with category, model, tokens. Live. - **Effort router**: expensive model warnings on subagent spawns. Live. - **CORF trigger**: high-stakes decision flagging. Live. - **Feature flags**: per-hook enable/disable via gateway RPC. Live. - **Call tree panel**: real-time agent topology in Tinker UI. Live. - **Guardian process**: 3-minute health checks with auto-recovery. Live. - **Tool concurrency partitioner**: read-only vs. mutating classification. Tested, wiring pending. - **Prompt cache boundary**: static/dynamic prompt split. Tested, wiring pending. - **Fork subagents**: cache-shared child agents. Tested, wiring pending. - **Deferred tool loading**: on-demand schema loading. Tested, wiring pending.
removed in v4.0
v3.1 · 7.1 What Is Built (v2.4 Baseline)Total: ~3,300 lines of TypeScript, 151 tests, 11 test files, 6 RPC endpoints.
removed in v4.0
v3.1 · 7.2 What Is New in v3.1### 7.2 What Is New in v3.1
removed in v4.0
v3.1 · 7.2 What Is New in v3.1The following components are proposed and specified but not yet implemented:
removed in v4.0
v3.1 · 7.2 What Is New in v3.1- **Recipe engine**: recipe parsing, step tracking, gate evaluation, failure handler dispatch. - **Recipe library**: 6 built-in recipes (debug, feature, investigate, refactor, review, deploy) plus custom recipe loading from memory hierarchy. - **Intent classifier**: three-tier strategy (keyword, structure, LLM) for recipe selection. - **Orchestrator loop**: Prefrontal as first call with plan injection into main agent context. - **Subagent supervisor**: progress monitoring, stall detection, cross-subagent coordination, intervention. - **Progress reporter**: WebSocket event emission for recipe step progress, subagent status, elapsed time. - **Reflection orchestrator**: mandatory post-recipe reflection with recipe context injection. - **Recipe evolution**: automatic recipe updates based on reflection findings. - **UI extensions**: recipe overlay on call tree, cost tracking per step, stall indicators.
removed in v4.0
v3.1 · 7.3 Roadmap### 7.3 Roadmap
removed in v4.0
v3.1 · 7.3 Roadmap**Phase 1 (Foundation)**: Recipe format specification, parser, and built-in library. Intent classifier with keyword and structure matching. Estimated: 1--2 sessions.
removed in v4.0
v3.1 · 7.3 Roadmap**Phase 2 (Orchestration)**: Prefrontal as first call. Orchestrator loop with plan injection. Single-agent execution (no parallelism yet). Estimated: 2--3 sessions.
removed in v4.0
v3.1 · 7.3 Roadmap**Phase 3 (Parallelism)**: Subagent supervisor. Progress reporter. Stall detection. Wire the existing fork-subagent module into the recipe engine. Estimated: 2--3 sessions.
removed in v4.0
v3.1 · 7.3 Roadmap**Phase 4 (Reflection)**: Reflection orchestrator. Recipe-aware reflection context. Recipe evolution from reflection findings. Estimated: 1--2 sessions.
removed in v4.0
v3.1 · 7.3 Roadmap**Phase 5 (UI)**: Recipe overlay on call tree. Cost tracking. Progress panel. Estimated: 1--2 sessions.
removed in v4.0
v3.1 · 7.3 Roadmap**Phase 6 (Learning)**: Recipe selection improves from usage data. Gate thresholds adapt. Recipes fork into variants for different contexts. This phase has no fixed endpoint --- it is the compounding loop itself.
removed in v4.0
not in v3.1
v4.0 · 7. Capability 5 — Dynamic Effort Routing (Effort Regulation)## 7. Capability 5 — Dynamic Effort Routing (Effort Regulation)
not in v3.1
v4.0 · 7.1 From classify-and-log to classify-and-drive### 7.1 From classify-and-log to classify-and-drive
not in v3.1
v4.0 · 7.1 From classify-and-log to classify-and-driveThe 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.
not in v3.1
v4.0 · 7.2 The four tiers and the signals behind them### 7.2 The four tiers and the signals behind them
not in v3.1
v4.0 · 7.2 The four tiers and the signals behind themEach 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.
not in v3.1
v4.0 · 7.2 The four tiers and the signals behind them``` 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
not in v3.1
v4.0 · 7.2 The four tiers and the signals behind themif 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 ```
not in v3.1
v4.0 · 7.2 The four tiers and the signals behind themA trivial turn must have **no** hard or breadth verbs — the design refuses to down-classify a short prompt that nonetheless asks for hard work.
not in v3.1
v4.0 · 7.3 What the tier controls### 7.3 What the tier controls
not in v3.1
v4.0 · 7.3 What the tier controlsThe tier is not advisory; it sets four levers for the turn, injected as guidance the worker adapts to:
not in v3.1
v4.0 · 7.3 What the tier controls| 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 |
not in v3.1
v4.0 · 7.3 What the tier controlsFor 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.

··· 1 unchanged paragraph folded ···

v3.1 · 8. Conclusion## 8. Conclusion
removed in v4.0
v3.1 · 8. ConclusionThe history of software engineering is a history of structured workflows replacing ad hoc improvisation. Waterfall, agile, TDD, CI/CD --- each methodology succeeded not by making developers smarter but by making their process more structured. The same transition is now happening in AI agent architecture.
removed in v4.0
v3.1 · 8. ConclusionVersion 2.4 of this paper demonstrated that intelligence compounds through architecture. Four mechanisms --- fractal reflection, tiered memory, CORF parallelism, and adaptive routing --- produced a 96% improvement in composite intelligence over six months. But v2.4's architecture was defensive: it prevented bad behaviour more effectively than it produced good behaviour. The guards worked; the highway was missing.
removed in v4.0
v3.1 · 8. ConclusionVersion 3.0 proposes the highway. By transforming Prefrontal from a guard system into a recipe execution engine, we complete the cognitive cycle that v2.4 acknowledged was only half-built. Pre-action planning selects the right recipe. During-action monitoring supervises execution. Post-action reflection extracts lessons and improves the recipes themselves. The compounding loop closes: each recipe execution makes the next execution of that recipe better.
removed in v4.0
v3.1 · 8. ConclusionThe convergent evolution evidence is now three-layered. Claude Code's skills are recipes executed by a `while(true)` loop. Journey Kits proposes recipes as the atomic unit of agent value. Meta-Harness demonstrates that harness optimisation --- the automated discovery of better recipes --- produces 6x performance gains. Three independent teams, working from different premises, arrived at the same conclusion: **the recipe is the unit of agent intelligence**.
removed in v4.0
v3.1 · 8. ConclusionThe honest assessment remains that much of v3.1 is specified but not yet implemented. The recipe engine, the orchestrator loop, the subagent supervisor, and the reflection orchestrator exist as designs in this paper, not as code in the repository. The v2.4 baseline --- guards, observability, monitoring --- is live and validated. The v3.1 additions are the next implementation target.
removed in v4.0
v3.1 · 8. ConclusionThe architectural insight is clear: prompt caching makes orchestration nearly free. What remains is wiring existing components into this cognitive cycle.
removed in v4.0
v3.1 · 8. ConclusionThe intern who never makes the same mistake twice writes things down. The intern who gets promoted writes *recipes* --- structured workflows that make the next person as effective as they are. Version 3.0 is about building agents that write recipes.
removed in v4.0
not in v3.1
v4.0 · 8. Capability 6 — The RECIPES Observability Panel (Metacognitive Monitoring)## 8. Capability 6 — The RECIPES Observability Panel (Metacognitive Monitoring)
not in v3.1
v4.0 · 8.1 Why observability is a first-class capability, not a nicety### 8.1 Why observability is a first-class capability, not a nicety
not in v3.1
v4.0 · 8.1 Why observability is a first-class capability, not a nicetyAn 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.
not in v3.1
v4.0 · 8.2 The split-of-concerns invariant### 8.2 The split-of-concerns invariant
not in v3.1
v4.0 · 8.2 The split-of-concerns invariantOne rule governs the panel and is the most load-bearing invariant of the whole system:
not in v3.1
v4.0 · 8.2 The split-of-concerns invariant> **Chat carries substance; the panel carries orchestration mechanics. Never the reverse.**
not in v3.1
v4.0 · 8.2 The split-of-concerns invariantThe 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.
not in v3.1
v4.0 · 8.3 What the panel renders### 8.3 What the panel renders
not in v3.1
v4.0 · 8.3 What the panel rendersThe panel renders the full life-cycle of a recipe run as several stacked sections:
not in v3.1
v4.0 · 8.3 What the panel renders- **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.
not in v3.1
v4.0 · 8.4 The compact-expand decision trail### 8.4 The compact-expand decision trail
not in v3.1
v4.0 · 8.4 The compact-expand decision trailA 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.
not in v3.1
v4.0 · 8.4 The compact-expand decision trail**Figure 2 (described in §11).** The life-cycle state machine the RECIPES panel renders: `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. Every transition emits a provenance-trail verb.

··· 1 unchanged paragraph folded ···

v3.1 · References## References
removed in v4.0
v3.1 · ReferencesAnthropic. (2026). Claude Code source code [Accidentally exposed, March 2026]. Analysis based on publicly available descriptions.
removed in v4.0
v3.1 · ReferencesBerman, M. (2026). Journey Kits: npm for AI agent workflows. https://journeykits.ai
removed in v4.0
v3.1 · ReferencesChen, X. et al. (2026). MemexRL: Learning to manage agent memory through reinforcement. *arXiv preprint*.
removed in v4.0
v3.1 · ReferencesChollet, F. (2019). On the measure of intelligence. *arXiv preprint arXiv:1911.01547*.
removed in v4.0
v3.1 · ReferencesKhattab, O. et al. (2023). DSPy: Compiling declarative language model calls into self-improving pipelines. *arXiv preprint arXiv:2310.03714*.
removed in v4.0
v3.1 · ReferencesLee, J. et al. (2026). Meta-Harness: Automatically optimising agent scaffolding for terminal benchmarks. *arXiv preprint*.
removed in v4.0
v3.1 · ReferencesLi, W. et al. (2026). CraniMem: Neural memory compression with hippocampal indexing for LLM agents. *arXiv preprint*.
removed in v4.0
v3.1 · ReferencesMadaan, A. et al. (2023). Self-Refine: Iterative refinement with self-feedback. *NeurIPS 2023*.
removed in v4.0
v3.1 · ReferencesMaharana, A. et al. (2024). LoCoMo: Long-context memory evaluation for conversational agents. *arXiv preprint*.
removed in v4.0
v3.1 · ReferencesNouse Research. (2026). Hermes Agent: Self-improving skill libraries for autonomous agents.
removed in v4.0
v3.1 · ReferencesPacker, C. et al. (2023). MemGPT: Towards LLMs as operating systems. *arXiv preprint arXiv:2310.08560*.
removed in v4.0
v3.1 · ReferencesPark, J. S. et al. (2023). Generative agents: Interactive simulacra of human behavior. *UIST 2023*.
removed in v4.0
v3.1 · ReferencesPark, S. et al. (2026). Governed Memory: Access control and governance for agent memory systems. *arXiv preprint*.
removed in v4.0
v3.1 · ReferencesSerra, O. (2026). AMYGDALA: Adaptive modulation of agent disposition via affective learned association. *Working paper*.
removed in v4.0
v3.1 · ReferencesSerra, O. & Jarvis. (2026). PREFRONTAL v2.4: Compounded Intelligence --- How Persistent Agents Get Smarter by Remembering What They Learn. *Working paper*.
removed in v4.0
v3.1 · ReferencesShinn, N. et al. (2023). Reflexion: Language agents with verbal reinforcement learning. *NeurIPS 2023*.
removed in v4.0
v3.1 · ReferencesTan, P. (2026). GStack: Multi-perspective code review through role-based prompt specialisation.
removed in v4.0
v3.1 · ReferencesWang, G. et al. (2023). Voyager: An open-ended embodied agent with large language models. *arXiv preprint arXiv:2305.16291*.
removed in v4.0
v3.1 · ReferencesZhang, L. et al. (2026). A survey of memory architectures for LLM-based agents. *arXiv preprint*.
removed in v4.0
not in v3.1
v4.0 · 9. Integration with the Surrounding Cognitive Systems## 9. Integration with the Surrounding Cognitive Systems
not in v3.1
v4.0 · 9. Integration with the Surrounding Cognitive SystemsThe 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.
not in v3.1
v4.0 · 9.1 Identity### 9.1 Identity
not in v3.1
v4.0 · 9.1 IdentityA 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.
not in v3.1
v4.0 · 9.2 Memory### 9.2 Memory
not in v3.1
v4.0 · 9.2 MemoryMemory 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.
not in v3.1
v4.0 · 9.3 Learned action gating### 9.3 Learned action gating
not in v3.1
v4.0 · 9.3 Learned action gatingA 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.
not in v3.1
v4.0 · 9.4 Deliberation and budget### 9.4 Deliberation and budget
not in v3.1
v4.0 · 9.4 Deliberation and budgetWhen 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.
not in v3.1
v4.0 · 9.5 Reflection, orchestrated### 9.5 Reflection, orchestrated
not in v3.1
v4.0 · 9.5 Reflection, orchestratedPost-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.

··· 1 unchanged paragraph folded ···

v3.1 · Appendix A: Recipe Execution Pseudocode## Appendix A: Recipe Execution Pseudocode
removed in v4.0
v3.1 · Appendix A: Recipe Execution Pseudocode``` ALGORITHM: RecipeExecution(user_message, context, recipe_library)
removed in v4.0
v3.1 · Appendix A: Recipe Execution PseudocodeInput: user_message (raw user request) context (SOUL.md, memory hierarchy, session history) recipe_library (set of available recipes) Output: response to user, set of memory writes W
removed in v4.0
v3.1 · Phase 1: PLAN (cache-shared LLM call) intent <- classify_intent(user_message) if intent.complexity < THRESHOLD_SIMPLE: return passthrough(user_message, context) # no orchestration# Phase 1: PLAN (cache-shared LLM call) intent <- classify_intent(user_message) if intent.complexity < THRESHOLD_SIMPLE: return passthrough(user_message, context) # no orchestration
removed in v4.0
v3.1 · Phase 1: PLAN (cache-shared LLM call) intent <- classify_intent(user_message) if intent.complexity < THRESHOLD_SIMPLE: return passthrough(user_message, context) # no orchestrationrecipe <- select_recipe(intent, recipe_library) plan <- compose_plan(recipe, context)
removed in v4.0
v3.1 · Phase 1: PLAN (cache-shared LLM call) intent <- classify_intent(user_message) if intent.complexity < THRESHOLD_SIMPLE: return passthrough(user_message, context) # no orchestrationif plan.estimated_duration > 5 minutes: present_plan_to_user(plan) if user.redirects: plan <- revise_plan(user.feedback)
removed in v4.0
v3.1 · Phase 1: PLAN (cache-shared LLM call) intent <- classify_intent(user_message) if intent.complexity < THRESHOLD_SIMPLE: return passthrough(user_message, context) # no orchestrationsubagents <- allocate_subagents(plan, context)
removed in v4.0
v3.1 · Phase 2: EXECUTE (supervised subagent dispatch) for each step S in plan.steps: workers <- subagents[S] dispatch(workers, S.task, S.tools)# Phase 2: EXECUTE (supervised subagent dispatch) for each step S in plan.steps: workers <- subagents[S] dispatch(workers, S.task, S.tools)
removed in v4.0
v3.1 · Phase 2: EXECUTE (supervised subagent dispatch) for each step S in plan.steps: workers <- subagents[S] dispatch(workers, S.task, S.tools)while not S.complete: events <- collect_events(workers, timeout=S.expected_duration)
removed in v4.0
v3.1 · Phase 2: EXECUTE (supervised subagent dispatch) for each step S in plan.steps: workers <- subagents[S] dispatch(workers, S.task, S.tools)if stall_detected(events, S): intervene(workers, S, context)
removed in v4.0
v3.1 · Phase 2: EXECUTE (supervised subagent dispatch) for each step S in plan.steps: workers <- subagents[S] dispatch(workers, S.task, S.tools)if cross_subagent_update(events): relay_findings(events, subagents)
removed in v4.0
v3.1 · Phase 2: EXECUTE (supervised subagent dispatch) for each step S in plan.steps: workers <- subagents[S] dispatch(workers, S.task, S.tools)emit_progress(S, workers)
removed in v4.0
v3.1 · Phase 2: EXECUTE (supervised subagent dispatch) for each step S in plan.steps: workers <- subagents[S] dispatch(workers, S.task, S.tools)if not gate_satisfied(S.gate, workers.output): if S.failure_handler exists: execute(S.failure_handler) else: escalate_to_user(S, workers.output)
removed in v4.0
v3.1 · Phase 2: EXECUTE (supervised subagent dispatch) for each step S in plan.steps: workers <- subagents[S] dispatch(workers, S.task, S.tools)response <- aggregate_results(plan, subagents)
removed in v4.0
v3.1 · Phase 3: REFLECT (cache-shared LLM call) reflection_context <- { recipe: recipe, plan: plan, execution_trace: subagents.traces, response: response }# Phase 3: REFLECT (cache-shared LLM call) reflection_context <- { recipe: recipe, plan: plan, execution_trace: subagents.traces, response: response }
removed in v4.0
v3.1 · Phase 3: REFLECT (cache-shared LLM call) reflection_context <- { recipe: recipe, plan: plan, execution_trace: subagents.traces, response: response }W <- FractalReflection(reflection_context, memory_files)
removed in v4.0
v3.1 · Phase 3: REFLECT (cache-shared LLM call) reflection_context <- { recipe: recipe, plan: plan, execution_trace: subagents.traces, response: response }if reflection.recipe_update: update_recipe(recipe, reflection.recipe_update)
removed in v4.0
v3.1 · Phase 3: REFLECT (cache-shared LLM call) reflection_context <- { recipe: recipe, plan: plan, execution_trace: subagents.traces, response: response }return response, W ```
removed in v4.0
v3.1 · Appendix B: Built-in Recipe Index## Appendix B: Built-in Recipe Index
removed in v4.0
v3.1 · Appendix B: Built-in Recipe Index| Recipe | Trigger Patterns | Steps | Key Gate | |--------|-----------------|-------|----------| | debug | "fix", "bug", stack traces | 6 | Reproduce before fix | | feature | "add", "implement" | 7 | Design before code | | investigate | "why", "check" | 5 | Scope before search | | refactor | "clean up", "refactor" | 6 | Measure before change | | review | PR URLs, diff blocks | 5 | Read completely before opining | | deploy | "deploy", "release" | 7 | Verify at every stage |
removed in v4.0
not in v3.1
v4.0 · 10. Evaluation Design## 10. Evaluation Design
not in v3.1
v4.0 · 10.1 First-attempt accuracy### 10.1 First-attempt accuracy
not in v3.1
v4.0 · 10.1 First-attempt accuracyThe 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:
not in v3.1
v4.0 · 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* | | 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 |
not in v3.1
v4.0 · 10.1 First-attempt accuracyThe headline metric is the change in weighted first-attempt accuracy across a representative task mix, attributing each delta to the gate responsible.
not in v3.1
v4.0 · 10.2 Matching quality### 10.2 Matching quality
not in v3.1
v4.0 · 10.2 Matching qualityMatching 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.
not in v3.1
v4.0 · 10.3 Authoring quality and library health### 10.3 Authoring quality and library health
not in v3.1
v4.0 · 10.3 Authoring quality and library healthFor 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.
not in v3.1
v4.0 · 10.4 Loop termination### 10.4 Loop termination
not in v3.1
v4.0 · 10.4 Loop terminationEvery 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).
not in v3.1
v4.0 · 10.5 Cost and latency### 10.5 Cost and latency
not in v3.1
v4.0 · 10.5 Cost and latencyBecause 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.
not in v3.1
v4.0 · 10.5 Cost and latency---
not in v3.1
v4.0 · 11. Suggested Diagrams (D2)## 11. Suggested Diagrams (D2)
not in v3.1
v4.0 · 11. 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.
not in v3.1
v4.0 · 11. Suggested Diagrams (D2)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.
not in v3.1
v4.0 · 11. Suggested Diagrams (D2)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.
not in v3.1
v4.0 · 11. Suggested Diagrams (D2)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.
not in v3.1
v4.0 · 11. Suggested Diagrams (D2)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).
not in v3.1
v4.0 · 11. Suggested Diagrams (D2)---
not in v3.1
v4.0 · 12. Conclusion## 12. Conclusion
not in v3.1
v4.0 · 12. ConclusionThe 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.
not in v3.1
v4.0 · 12. ConclusionA 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 robustly 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.
not in v3.1
v4.0 · 12. ConclusionOf 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.
not in v3.1
v4.0 · 12. ConclusionThe 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.
not in v3.1
v4.0 · 12. Conclusion---
not in v3.1
v4.0 · References to Companion Papers## References to Companion Papers
not in v3.1
v4.0 · References to Companion PapersThe 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.
not in v3.1
v4.0 · References to Companion Papers- **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.
not in v3.1
v4.0 · References to Companion Papers---
not in v3.1
v4.0 · Appendix A — The Turn, End to End (Pseudocode)## Appendix A — The Turn, End to End (Pseudocode)
not in v3.1
v4.0 · 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
not in v3.1
v4.0 · 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)# 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)
not in v3.1
v4.0 · 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)# 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)
not in v3.1
v4.0 · 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 ```# 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 ```
not in v3.1
v4.0 · Appendix B — Recipe Document Schema (Illustrative)## Appendix B — Recipe Document Schema (Illustrative)
not in v3.1
v4.0 · 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)
not in v3.1
v4.0 · Appendix B — Recipe Document Schema (Illustrative)--- body --- ### 1. Reproduce done-when: the exact failure is described with evidence Read the error. Run the failing case. Identify the trigger conditions.
not in v3.1
v4.0 · 2. Diagnose done-when: root cause identified with file:line Trace the cause through code; follow evidence, do not guess.### 2. Diagnose done-when: root cause identified with file:line Trace the cause through code; follow evidence, do not guess.
not in v3.1
v4.0 · 3. Fix done-when: minimal change applied Smallest fix that addresses the root cause. One concern per change.### 3. Fix done-when: minimal change applied Smallest fix that addresses the root cause. One concern per change.
not in v3.1
v4.0 · 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. ```### 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. ```
not in v3.1
v4.0 · 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.)*

Changed paragraphs in the same form, for scripts: JSON · Markdown