# BROCA: Giving Agent Recipes a Grammar — A Gradual Type System and Combinator Algebra for Self-Composing Workflows: v1.0 → v1.1

From v1.0 (6 Jun) to v1.1 (14 Jun): 8,185 words to 10,681 words, 2,500 words in new or rewritten paragraphs and 4 taken out, 44 paragraphs changed.

## Change note of v1.1

**Related work added; typed edges set against context compression**

This version places BROCA among open-source projects and admits a gap. It adds a related-work section and compares BROCA with headroom, a tool that compresses prose instead of removing it, and says the two fit together. It also concedes that the claim "typed edges save tokens" has no measurement behind it yet, and describes the benchmark that would settle it. The paper grows by about 2,500 words. The folder's improvement notes of 13 June asked for both the headroom positioning and the interop point.

- New: two ways to fix lossy prose, remove it at typed edges or compress it and fetch it back.
- New: the recipe format is the same `kit/1.0` schema the Journey registry uses; four outside kits were imported.
- New: authoring habits taken from two public skill collections ("when not to use", trigger phrases, test sets).
- The skill search is now described as surface similarity only, citing a negative result from a sibling experiment.
- A runtime gate on tool calls is noted as a second safety layer next to the closed condition language.
- Limitations gain two items: the efficiency claim is unmeasured, and the search does not judge meaning.

## Changed paragraphs

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

### Abstract

This is no longer a design that promises a target; it is a shipped language whose seven pillars are implemented and tested in the running substrate. We are precise throughout about what each pillar actually does, and about the two places where a mechanism is shipped but its strongest mode is held off by default (autonomous recipe self-editing is gated to *propose-only* unless an operator opts in) or scoped narrowly (the combinator algebra is the iteration combinators plus the guard/exit/compose primitives, not yet a closed set of four named higher-order [-recipes).-] {+recipes). We also situate the language against the live open-source ecosystem it now interoperates with — a context-compression layer (chopratejas/headroom) that answers the same lossy-prose problem from the opposite direction, an engineering-discipline plugin (addyosmani/agent-skills) and a marketing-skills corpus (coreyhaines31/marketingskills) whose authoring conventions sharpen ours, and a distribution registry (Journey / journeykits.ai) whose `kit/1.0` schema is the same grammar BROCA emits, making recipes a cross-registry interchange format rather than a private DSL.+}

### Abstract

**Keywords:** typed workflows, gradual typing, named ports, compile-time contracts, combinator algebra, sandboxed guard evaluation, early exit, skill library, catchable recovery, derived budgets, self-sharpening, self-composing agents, [-recipe-as-language-] {+recipe-as-language, context compression, cross-registry interop+}

### Contributions

1. **A gradual type system for prose workflows.** A per-step `out:`/`in:` directive vocabulary that adds named, schema-checked value edges to a recipe *without* converting it to code, where an undeclared step keeps its exact prose behavior — typing is opt-in per step and additive, not a migration. 2. **Compile-time contracts at boundaries.** A seed-time port-wiring check and a seed-time guard-reference check that each verify every consumer reference resolves to a real, strictly-earlier producer that declares the referenced field — turning a class of integration errors from deep-runtime failures into fast, precise authoring-time rejections. 3. **A combinator algebra over recipes.** `map`/`filter` iterate a worker recipe over a typed array edge (with the worker resolvable *dynamically* from a prior step's output), `compose` chains recipes through the depth-/cycle-guarded `uses:` edge, and `if-then-else` is the `when:`-guard / `return:`-exit pair — combinators are ordinary recipes, so they inherit fitness, archive, and versioning for free. 4. **A skill standard library as the composition vocabulary.** A searchable, versioned `SkillLibrary` [-(semantic-embedding-] {+(surface-embedding+} search with a keyword fallback, Laplace-smoothed fitness ranking) that an `invoke skill:` step resolves against; the resolved skill's output schema is adopted *at compile* so downstream `in:` ports type-check against the real contract, and a `recipe.compose` RPC mechanically assembles a recipe from the top-ranked skill hits. 5. **Catchable recovery with a classified-error taxonomy.** Every step failure is classified into one of a closed set of error kinds with a computed `recoverable` flag; an `onError:` policy router does retry (honored only for recoverable errors), fallback to a recovery recipe, or continue-partial, the last settling as a non-aborting `done-partial` that keeps the survivors. 6. **A self-sharpening loop over real usage.** A nightly consolidation lane reads per-step struggle from the live plan archive and proposes `rewrite_step_text` mutations for struggling steps; an apply path guarded by five rails (strict promote gate, authorship guard, snapshot-before-write, validate-or-skip, kill-switch) can enact them — but is *propose-only by default*, enacting nothing unless an operator sets the kill-switch. 7. **All bounds derived, not frozen.** Re-dispatch, combinator fan-out, composition depth, and recovery-retry budgets are each a function of live signals — value-of-work, historical confidence, prior effort spent, and affordability — never a hardcoded constant.

### 1.3 What this paper claims, and what it does not

{+A third honesty boundary is new and methodological. We argue throughout that a typed value edge is cheaper and safer than a re-parsed prose carry-forward, but as of this revision we have **no measured token-savings or accuracy-delta benchmark of our own** for that claim. The adjacent open-source baseline that *does* meet that bar — chopratejas/headroom, with a reproducible GSM8K/TruthfulQA/SQuAD/BFCL eval suite (Section 16.1) — sets a methodological standard this paper has not yet met for the value-model claim. We state the typed-edge efficiency argument as an argued result, not a measured one, and name the eval that would settle it.+}

### 2.2 Two answers to the lossy-prose problem: eliminate the prose, or compress-and-recover it

{+### 2.2 Two answers to the lossy-prose problem: eliminate the prose, or compress-and-recover it+}

### 2.2 Two answers to the lossy-prose problem: eliminate the prose, or compress-and-recover it

{+There are two structurally different ways to defeat the lossy-prose transport, and naming both makes BROCA's choice precise rather than reflexive.+}

### 2.2 Two answers to the lossy-prose problem: eliminate the prose, or compress-and-recover it

{+The first answer — BROCA's — is to make the prose **unnecessary at the load-bearing edges**: replace the paragraph with a typed, named-port value, so the downstream step binds `steps.3.out.failingCount` directly and there is no re-parse, no truncation risk, and no schema-less guessing on those edges at all.+}

### 2.2 Two answers to the lossy-prose problem: eliminate the prose, or compress-and-recover it

{+The second answer is to keep the prose but make it **smaller and recoverable**. This is the design of chopratejas/headroom (Choprateja S. et al., 24.7k★, Apache-2.0), a reversible context-compression layer built on **Compress-Cache-Retrieve (CCR)**: the originals are cached and the model retrieves them on demand, with per-content-type compressors — statistical JSON-array crushing (SmartCrusher), tree-sitter AST-aware code compression, and log/diff/text handlers — reported at 60–95% token savings with near-zero accuracy delta on a reproducible benchmark suite. headroom never needs to know what `failingCount` *is*; it crushes and caches the opaque note and serves it back when asked.+}

### 2.2 Two answers to the lossy-prose problem: eliminate the prose, or compress-and-recover it

{+These are complementary, not competing, and BROCA's gradual typing (Section 3.2) is exactly why: most steps in a living library stay prose by design, and for those untyped steps a CCR layer is the right tool — it directly attacks the same few-hundred-character carry-forward truncation that Section 2.1 names as the third failure mode. BROCA eliminates the prose at the typed edges; headroom compresses-and-recovers it everywhere else. Section 16 develops this positioning and concedes the benchmark BROCA still owes.+}

### 2.3 Why "just write better prose" is not the fix

### [-2.2-] {+2.3+} Why "just write better prose" is not the fix

### 3.2 Gradual: typing is an overlay, never a delete

This gradualness is what makes the type system adoptable inside a *living* library. Recipes authored before the value model existed do not break; an agent can add a typed edge to one step of one recipe without touching the rest; and the nightly evolution loop (Section 8) can rewrite prose steps freely without tripping a type checker that was never asked to apply to [-them.-] {+them. It is also why the typed edge and a context-compression layer (Section 2.2) are complementary: the steps that stay prose under gradual typing are exactly the steps a CCR compressor is for.+}

### 5. Derived, Not Frozen — The Budget Principle

{+A floored constant, where it appears at all, is a **safety ceiling, never the working value** — the working value is always the derived one, and the constant exists only to bound a pathological derivation. That distinction is the precise content of the derive-not-freeze principle, and we are careful to keep every literal in this section on the ceiling side of it.+}

### 6.1 `when:` — a sandboxed boolean grammar, not `eval`

{+The by-construction closure is the grammar's own guarantee, and it is the load-bearing one. It is now also backed by an independent runtime floor: a sibling line of work (the learned-intuition reflex gate) enforces a pre-execution policy on the *tool calls* any step — recipe-authored or freely improvised — is allowed to make, denying disallowed actions before they run rather than observing them after. The two guarantees are layered, not redundant: the closed `when:` grammar means a recipe body cannot *carry* code, and the reflex gate means a step cannot *invoke* a denied action even if its prose tried to. We note the second layer here for completeness; its mechanism, calibration, and its known over-flagging behavior on benign destructive-looking commands are the subject of the companion AMYGDALA work and are out of scope for this paper.+}

### 8.1 The library: search, read, rank, fitness

{+It is worth being precise about what the embedding *is* here, because a sibling line of work (the AMYGDALA danger-head experiments) established a sharp negative result about what frozen sentence embeddings can and cannot carry. A frozen embedding is a competent **surface-similarity** signal — two skill descriptions that talk about the same thing land near each other in the space, which is all `search` asks of it — but it is *not* a carrier of deeper semantic judgment: an offline experiment found that a supervised head trained on top of a frozen MiniLM embedding scored *below chance* at classifying harmfulness, i.e. the geometry does not encode "is this dangerous." We therefore claim only what the geometry supports: the skill search is a relevance ranker over lexical/topical similarity, with the Laplace-smoothed fitness term carrying the *quality* judgment the embedding cannot. The Jaccard fallback is not a degraded approximation of a smarter signal; it is the same family of surface-overlap relevance, which is why graceful degradation to it costs the ranker so little.+}

### 8.4 The library is internal; the grammar is an interchange format

{+### 8.4 The library is internal; the grammar is an interchange format+}

### 8.4 The library is internal; the grammar is an interchange format

{+The `SkillLibrary` is BROCA's *internal* composition vocabulary — it indexes the primitives one runner composes from. It is not a cross-organization distribution surface, and it does not need to be, because the recipe grammar itself turns out to be the distribution unit. The Journey registry (journeykits.ai) publishes workflows as **`kit/1.0` kits — the same schema BROCA recipes are written in** — and we ran a real **license-gated, attribution-stamped import pipeline** that distilled four external Journey kits into the live library. The grammar a second producer emits is the grammar BROCA consumes, which is the strongest available evidence that recipes are a genuine *language* and not a private DSL.+}

### 8.4 The library is internal; the grammar is an interchange format

{+The division of labor is honest and clean. Journey is a **distribution registry**: it ships, indexes, and makes discoverable kits across organizations — a cross-org surface BROCA's internal `SkillLibrary` deliberately does not provide. Journey does *not* provide BROCA's type discipline: an imported kit gains compile-time port-wiring and guard-reference checks (Section 4), derived budgets (Section 5), and catchable recovery (Section 9) only **after** it crosses into our runner. So the two systems are complementary along exactly the axis the paper cares about — Journey answers *where a recipe comes from and how it travels*; BROCA answers *what guarantees it acquires once it is here*. This is the through-line of the recipe-as-language argument made concrete: a typed inter-step edge, then a typed external signature, then a private/public value split, and now a cross-registry interchange format that an independent registry already speaks.+}

### 10. The Empirical-Fitness Loop

The loop closes: run → attribute → consolidate → fitness → budgets and ranking → next run. A recipe's reliability is measured from its actual outcomes and fed back into how hard the language tries on its behalf — confidence is observed, not [-assumed.-] {+assumed. The empirical-fitness term is also where the embedding's limits (Section 8.1) are answered: the geometry ranks by surface relevance, and *this* loop carries the quality judgment the geometry cannot.+}

### 11. Machine-Authorability

This closes the loop the language thesis requires. The same agent that runs typed, contracted, guarded, recoverable workflows can also *emit* them — and emit them already conforming to the contracts, because the author validates against the same rules the runner enforces. The `recipe.compose` RPC of Section 8 is this in its strongest form: the agent does not even hand-author the steps; it composes them mechanically from the skill library. The grammar is not only checkable; it is [-generable.-] {+generable. And, as Section 8.4 establishes, the grammar it generates is the same `kit/1.0` schema an independent registry already speaks — so an agent-emitted recipe is, without translation, a publishable interchange artifact.+}

### 11.1 Authoring conventions imported from the ecosystem

{+### 11.1 Authoring conventions imported from the ecosystem+}

### 11.1 Authoring conventions imported from the ecosystem

{+A second, smaller debt to the open-source ecosystem is methodological. The `validateRecipeSpec` shape above guarantees a recipe is *well-formed*; it does not yet guarantee a recipe declares *when it should and should not be chosen*. Two adjacent corpora supply the missing convention. addyosmani/agent-skills (Addy Osmani, 56.8k★, MIT) — an engineering-discipline plugin packaging skills, subagent personas, commands, and hooks — standardizes a per-skill **"When NOT to use"** section and a **"Loading Constraints"** declaration (where a skill is allowed to load: main session vs. sub-agent). coreyhaines31/marketingskills (Corey Haines, 33k★, MIT) — a 44-skill, 51-CLI marketing corpus — standardizes a per-skill user-phrase trigger description and an `evals/evals.json` acceptance set. Both conventions are directly applicable to BROCA's matcher surface: the substrate's recipe matcher already supports an anti-trigger field (`antiTriggers:` / `whenNotToUse:`) that *subtracts* from a recipe's lexical match score on an exact look-alike phrase, which is the runtime counterpart of Osmani's "When NOT to use." Adopting these as part of the authoring standard — declared triggers and anti-triggers, an evals set, and a load-site constraint — is the concrete next tightening of `validateRecipeSpec`, and it imports a discipline two independent corpora already pay rather than reinventing it.+}

### 12. Implementation Status and Verification

- **The gradual typed value model and named ports** — `recipe-types.ts` (`Port`, `StepIo`, `parseStepIoDirectives`) and `recipe-runner.ts` (`validateTypedNote`): `out:`/`in:` directives, overlay-not-delete parsing, typed-field binding and `{{steps.n.out.path}}` resolution, and persistence of a validated step output as a structured artifact. - **The compile-time contracts** — `checkPortWiring` (and the guard-reference check) reject forward/self references, missing producers, producers with no `out:` schema, and undeclared fields, with the run refused before any dispatch; an invoked skill's `outputSchema` is adopted at compile so downstream ports check against it. The compile test exercises all rejection paths. - **The combinator algebra** — `parseMapIterDirective`/`parseFilterIterDirective`/`parseKeepDirective` plus the `executeOnce` fan-out: array-edge iteration, dynamic worker resolution via `resolveKitRefTemplate`, single-increment composition depth, `keep:` predicates over the `when:` engine, and survivor aggregation under continue-partial. - **The skill standard library** — `skill-library.ts` (`search`/`read`/`rank`/`recordOutcome`, [-embedding-] {+surface-embedding+} search with Jaccard fallback, Laplace ranking), `invoke skill:` resolution at compile and dispatch, fitness loopback, and the `prefrontal.recipe.compose` RPC. - **Catchable recovery** — the `ClassifiedError` taxonomy, the `onError:` router (retry honored only for recoverable errors, fallback via the `uses:` edge, continue-partial), and `done-partial` non-aborting settlement. - **The empirical-fitness loop** — `stampRecipeAttribution` (producer), `attributeRecipe`/`updateRecipeFitness` (consolidation), `makeFitnessLookup`/`fitnessSuccessRate` (consumer into the budgets and the matcher). - **All four derived bounds** — `deriveRedispatchBudget`, `deriveCombinatorFanOut`, `deriveUsesDepthBudget` (floor 3), `deriveRecoveryRetryBudget`, each varying with its live inputs and clamped by affordability, wired into the runner and the orchestration schema. - **The control grammar** — `parseWhenDirective`/`evaluateWhen`/`WhenEvalError` and `parseEarlyExitDirective`, with the guard-skip-as-done and `early-exit`-closes-as-`done` settlements. - **Machine-authorability** — `buildRecipeMd`/`validateRecipeSpec`, emitting directives the runner parses [-back.-] {+back. - **Cross-registry interop** — the `kit/1.0` schema is shared with the Journey registry; a license-gated, attribution-stamped import pipeline distilled four external kits into the live library, which then acquired the contracts, budgets, and recovery of the runner.+}

### 12. Implementation Status and Verification

{+**Not yet measured.** The value-model efficiency claim — that a typed edge costs fewer tokens and loses less information than a re-parsed prose carry-forward — is argued (Sections 2, 16) but not benchmarked. A reproducible eval to the standard headroom sets (Section 16.1) is named future work, not a present result.+}

### 13. Limitations and Negative Results

{+8. **The value-model efficiency claim is unmeasured.** We argue a typed edge is cheaper and lossless versus a prose carry-forward, but we ship no token-savings/accuracy-delta benchmark of our own. The adjacent open-source baseline (headroom, Section 16.1) meets that bar with a reproducible suite; BROCA does not yet, and we mark the claim as argued, not measured.+}

### 13. Limitations and Negative Results

{+9. **Skill search ranks surface similarity, not meaning.** The embedding under `SkillLibrary.search` (Section 8.1) is a relevance ranker over lexical/topical overlap, not a carrier of deeper semantic judgment — a sibling negative result found a supervised head over a frozen embedding scoring below chance on a harmfulness task, so we do not lean the embedding to carry quality. Quality is carried by the empirical-fitness term, not by the geometry.+}

### 15. Conclusion

[-## 15. Conclusion-]

### 15. Related Work

{+## 15. Related Work+}

### 15. Related Work

{+We position BROCA against the live open-source ecosystem it now interoperates with, treating these systems as first-class peers rather than footnotes — they are fresher than any static citation and, in two cases, BROCA shares a schema or a methodological bar with them.+}

### 15. Related Work

{+**Context compression for agents — chopratejas/headroom** (Choprateja S. et al., 24.7k★, Apache-2.0). headroom attacks the same lossy-prose-transport problem from the opposite direction (Sections 2.2, 16): rather than eliminating the prose at typed edges, it keeps the prose and makes it smaller and recoverable via Compress-Cache-Retrieve. The two are complementary — BROCA's typed edge for the load-bearing fields, headroom's CCR for the steps gradual typing deliberately leaves as prose. headroom is also the methodological foil for this revision: its reproducible GSM8K/TruthfulQA/SQuAD/BFCL eval suite is the bar BROCA has not yet met for its own value-model efficiency claim (Section 16.1).+}

### 15. Related Work

{+**Engineering-discipline packaging — addyosmani/agent-skills** (Addy Osmani, 56.8k★, MIT). A single plugin bundling engineering skills, subagent personas, command definitions, and hooks. Its contribution to BROCA is conventional, not architectural: the per-skill **"When NOT to use"** and **"Loading Constraints"** sections (Section 11.1) are precisely the declared-anti-trigger and load-site discipline BROCA's matcher already supports as an anti-trigger field, and adopting them as part of `validateRecipeSpec` imports a convention rather than reinventing it.+}

### 15. Related Work

{+**A marketing-skills corpus — coreyhaines31/marketingskills** (Corey Haines, 33k★, MIT). A 44-skill, 51-CLI corpus whose per-skill user-phrase triggers and `evals/evals.json` acceptance sets are the second source of the authoring-standard tightening in Section 11.1. Its integration into our substrate (a vendored clone behind a single router skill plus a BROCA `marketing` recipe category) is an instance of recipes-as-vocabulary at corpus scale.+}

### 15. Related Work

{+**A distribution registry — Journey / journeykits.ai.** Journey publishes workflows as `kit/1.0` kits, the same schema BROCA recipes are written in (Section 8.4). It is the cross-org distribution surface BROCA's internal `SkillLibrary` is not, and it does not provide BROCA's type discipline — the two compose cleanly along the "where a recipe travels" vs. "what guarantees it acquires" axis. A real license-gated import pipeline (four kits) is the existence proof that the grammar is a portable interchange format.+}

### 15. Related Work

{+The companion lines of work this paper builds on — the recipe-as-substrate argument, the agent-executive-function argument, the derive-not-freeze principle, and the learned-intuition reflex gate — are cited in-text at the sections where they are used (Sections 1.2, 5, 6.1) and are not re-derived here.+}

### 15. Related Work

{+---+}

### 16. Positioning Against Context Compression — and a Benchmark We Owe

{+## 16. Positioning Against Context Compression — and a Benchmark We Owe+}

### 16.1 Eliminate the prose vs. compress-and-recover it

{+### 16.1 Eliminate the prose vs. compress-and-recover it+}

### 16.1 Eliminate the prose vs. compress-and-recover it

{+Sections 2.2 framed the two answers to the lossy-prose problem; here we make the comparison sharp enough to be a real positioning claim and to name what it costs us.+}

### 16.1 Eliminate the prose vs. compress-and-recover it

{+The two systems differ in *what they know about the payload*. headroom's CCR operates on an **opaque** blob — it never knows that the note contains a field called `failingCount`; it crushes the bytes with a content-type-appropriate compressor (statistical for JSON arrays, AST-aware for code), caches the original, and serves it back on demand. BROCA's typed edge operates on a **named, schema-checked** field — it knows `failingCount` is an integer the producer declared and the consumer binds, so at that edge there is no compression, no cache, and no retrieval round-trip, because there is no prose to begin with. Stated plainly: **headroom makes the prose smaller and recoverable; BROCA makes the prose unnecessary at the typed edges.** Neither subsumes the other. A living BROCA library is mostly prose by design (gradual typing, Section 3.2), and a CCR layer is the right tool for exactly those untyped steps and for the few-hundred-character carry-forward truncation Section 2.1 names as a first-class failure mode.+}

### 16.2 The benchmark BROCA owes

{+### 16.2 The benchmark BROCA owes+}

### 16.2 The benchmark BROCA owes

{+The honest cost of this comparison is methodological. headroom backs its compression claim with a reproducible eval suite — GSM8K, TruthfulQA, SQuAD, and BFCL, runnable as a single `python -m headroom.evals` command, reporting token savings against an accuracy delta. BROCA backs its value-model claim — that a typed edge is cheaper and lossless versus a prose carry-forward — with an *argument from structure*, not a measurement. That is a real gap. The next concrete step for the value model is a comparable, reproducible benchmark: a fixed multi-step workflow run two ways (prose carry-forward vs. typed `out:`/`in:` edges), measuring token cost at each edge and downstream task accuracy, on a task set broad enough to be credible. Until that exists, "the typed edge saves tokens" is an argued claim, and we mark it as such (Section 13, item 8). headroom's suite is the standard we are holding ourselves to.+}

### 16.2 The benchmark BROCA owes

{+---+}

### 17. Conclusion

{+## 17. Conclusion+}

### 17. Conclusion

{+This revision also places BROCA in its live ecosystem. The lossy-prose problem has two complementary answers, and an independent, benchmarked context-compression layer (headroom) is the right tool for the prose BROCA deliberately leaves untyped — which also names the reproducible benchmark BROCA still owes for its own typed-edge efficiency claim. Authoring conventions from two large open-source corpora (agent-skills, marketingskills) sharpen the recipe-matcher standard rather than being reinvented. And, most consequentially for the central thesis, the recipe grammar is the same `kit/1.0` schema an independent distribution registry (Journey) already speaks: a second producer emits the language and a real license-gated pipeline imports it, which is the strongest available evidence that this is a genuine *language* and not a private DSL.+}

### 17. Conclusion

We have been precise about the [-two-] lines that remain: autonomous self-editing is shipped but off by [-default, and-] {+default;+} the combinators are shipped as mechanism with their first-class naming deliberately [-unfrozen.-] {+unfrozen; the value-model efficiency claim is argued but not yet measured; and the skill embedding ranks surface similarity, not meaning, with quality carried by the fitness loop rather than the geometry.+} Those lines are not hedges — they are the same discipline the type system itself embodies. A grammar earns trust by checking its claims before it acts on them. So should the paper that describes it.
