Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

fix(budget): reserve the narration turn, not just landing work (#390)

Rach Pradhan88853c5189f6
diff --git a/docs/tier2-eval-design.md b/docs/tier2-eval-design.md
index 84d47b4a..228030cd 100644
--- a/docs/tier2-eval-design.md
+++ b/docs/tier2-eval-design.md
@@ -35,7 +35,7 @@ Global rank in brackets = position in `append_now`.
**[1] escalation-third-failure-earns-the-fleet** — The only case that exhausts the R0d deep retry and exercises a spawned R3 fleet end to end. Guards the `prior_failure_count == 1` gate and the noteDeclined bump on the R0d decline; loosening either reproduces the exact stuck-task solo-revision loop the 0.0.237 ladder redesign exists to break. Red plan: loosen the count gate to `>= 1` or drop the noteDeclined bump — call #3 stays R0d, zero `agent_route` events; conversely a fleet-on-second-call regression fails the index-4 R0d assert. Live: does a real root model walk the full trajectory — obey R0, retry only on real failure, follow the R0d prescription, land the third call as a working fleet with resolving anchors.
-**[5] escalation-audit-fleet-unaffordable-declines** — The affordability boundary, empirically exact: cap 23 → spendable 16, one short of review fleetFloor 17 (cap-24 probe spawned). The authored plan fits, so only the fleetFloor+reserve gate stands between decline and spawn. Guards the failure class the study's cap-30 exhaustion run exposed. Red plan: drop the landing reserve from `Ledger.spendable` or the `fleet_affordable` term — workers spawn, `no_event agent_route` fails. Live: decline compliance under scarcity — audit solo instead of re-invoking or stalling.
+**[5] escalation-audit-fleet-unaffordable-declines** — The affordability boundary, empirically exact: cap 24 → spendable 16, one short of review fleetFloor 17 (cap-25 probe spawned). The reserve it clears is 7 — six calls to land the work and one to narrate it (#390). The authored plan fits, so only the fleetFloor+reserve gate stands between decline and spawn. Guards the failure class the study's cap-30 exhaustion run exposed. Red plan: drop the landing reserve from `Ledger.spendable`, drop `cost_narration` from `totalReserve`, or drop the `fleet_affordable` term — workers spawn, `no_event agent_route` fails. Live: decline compliance under scarcity — audit solo instead of re-invoking or stalling.
**[7] escalation-audit-language-earns-r3** — First case to cover the paid-for-breadth spawn path: audit language + unlimited pool must admit R3 with zero named files, and the find brief must carry the anchor contract verbatim. Red plan: remove the `(o.audit or o.prior_failure) and fleet_affordable` branch or gut `isAuditClass` — declines to R0, zero spawns; losing the anchor-note wiring fails the request-2 assert alone. Live: does the model author an admissible shape-A plan for explicit breadth language, and does its real finder cite resolving paths.
diff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonl
index 7d337f9f..1f504f10 100644
--- a/evals/harness_behavior.jsonl
+++ b/evals/harness_behavior.jsonl
@@ -16,7 +16,7 @@
{"id": "child-refused-last-call-root-lands", "why": "#390 hard half (green regression lock): with cap 2, call 1 spawns a child; the child's acquire sees one slot left and is refused BEFORE the network (run_budget.zig depth>0 guard), surfacing as an is_error subagent tool_result classified [model-call-budget failure] with retry ruled out - and the ROOT takes call 2 as the landing call. Deleting the guard lets a worker eat the last slot and the run dies narrating. The bracket now also carries the attempt count - 1 attempt locks that a budget refusal is never blind-retried by the worker retry ladder.", "args": ["--max-model-calls", "2"], "prompt": "spawn a subagent to survey the payments module, then summarize what happened", "script": [{"tool": "subagent", "arguments": {"description": "survey payments", "prompt": "read every file under payments/ and list the exported functions"}}, {"text": "landing: the survey child was refused by the run budget; nothing was surveyed and nothing is verified"}], "assert": [{"event": {"type": "tool_call", "name": "subagent"}}, {"event": {"type": "tool_result", "name": "subagent", "is_error": true}}, {"request_contains": {"index": -1, "text": "model-call budget exhausted for this graff run"}}, {"request_contains": {"index": -1, "text": "[model-call-budget failure, 1 attempt]"}}, {"request_contains": {"index": -1, "text": "retry is NOT safe as-is"}}, {"request_contains": {"index": -1, "text": "[budget landing]"}}, {"request_lacks": {"index": -1, "text": "\"todo_write\""}}, {"final_text_contains": "the survey child was refused"}]}
{"id": "uncapped-run-never-sees-landing-note", "why": "#390 containment (green regression lock): with no --max-model-calls the landing machinery must be invisible - no [budget landing] on any request and tools still offered on the last one. Guards the max_model_calls != 0 gate in agent_request.zig: a hand-rolled remaining()-style check saturates to 0 under cap 0 and would strip tools from every normal run.", "args": [], "prompt": "check the todo list and report", "script": [{"tool": "todo_read", "arguments": {}}, {"text": "uncapped: the list is checked and empty"}], "assert": [{"request_lacks": {"index": 0, "text": "[budget landing]"}}, {"request_lacks": {"index": -1, "text": "[budget landing]"}}, {"request_contains": {"index": -1, "text": "\"todo_write\""}}, {"final_text_contains": "uncapped: the list is checked"}]}
{"id": "repair-ask-review-word-does-not-cross-cell", "why": "Intuition trap (green regression lock): 'fix the bug the review found in report.py' must cell as BUGFIX so its R0 decline parks in the bugfix column; the follow-up 'critique report.py' cells as REVIEW with a clean history and must get the plain R0 advisory, never the R0d revision prescription. Fails if the decline ledger collapses to one counter or classOf lets the word 'review' inside a repair ask steal the cell. Live replay measures whether the model treats the two asks as different kinds of work.", "args": [], "prompt": "ultracode fix the bug the review found in report.py", "script": [{"tool": "workflow", "arguments": {"phases": [{"title": "find the defect", "tasks": [{"description": "find", "prompt": "read report.py and locate the defect"}]}, {"title": "implement the fix", "tasks": [{"description": "fix", "prompt": "fix the defect in report.py"}]}]}}, {"text": "declined, so I repaired report.py myself"}, {"tool": "workflow", "arguments": {"phases": [{"title": "find problems", "tasks": [{"description": "find", "prompt": "read report.py and list the problems"}]}, {"title": "verify each finding", "tasks": [{"description": "verify", "prompt": "verify the problems in report.py"}]}]}}, {"text": "declined again with the plain advisory, so I critiqued report.py solo"}], "second_prompt": "now ultracode critique report.py, the earlier pass missed real problems", "assert": [{"events_at_least": {"match": {"type": "tool_result", "name": "workflow", "is_error": false}, "count": 2}}, {"request_contains": {"index": 1, "text": "(escalation R0):"}}, {"request_contains": {"index": -1, "text": "(escalation R0):"}}, {"request_lacks": {"index": -1, "text": "(escalation R0d):"}}, {"request_lacks": {"index": -1, "text": "revision case"}}, {"final_text_contains": "critiqued report.py solo"}]}
-{"id": "escalation-audit-fleet-unaffordable-declines", "why": "GREEN regression lock, the affordability boundary: same audit ask as the R3 case, but --max-model-calls 23 leaves 22 calls at admission — spendable 16 after the landing reserve, one short of the review fleetFloor (17) — so even paid-for breadth must decline to R0, non-error. The authored plan itself (6 calls) FITS, so only the fleetFloor+reserve gate stands between decline and spawn: drop the reserve from Ledger.spendable, or the fleet_affordable term from the R3 branch, and this exact case spawns a fleet.", "args": ["--max-model-calls", "23"], "prompt": "run a thorough audit of the error handling across the codebase and report what you find", "script": [{"tool": "workflow", "arguments": {"phases": [{"title": "find problems", "tasks": [{"description": "auditor", "prompt": "audit the error handling and list every problem with evidence"}]}, {"title": "synthesize the findings", "tasks": [{"description": "synthesis", "prompt": "rank the problems most-severe first"}]}]}}, {"text": "pool too dry for a fleet — auditing solo as advised"}], "assert": [{"request_contains": {"index": 1, "text": "workflow declined (escalation R0):"}}, {"request_contains": {"index": 1, "text": "budget and scope fit solo work"}}, {"request_lacks": {"index": 1, "text": "(escalation R0d):"}}, {"no_event": {"type": "agent_route"}}, {"event": {"type": "tool_result", "name": "workflow", "is_error": false}}, {"final_text_contains": "auditing solo"}]}
+{"id": "escalation-audit-fleet-unaffordable-declines", "why": "GREEN regression lock, the affordability boundary: same audit ask as the R3 case, but --max-model-calls 24 leaves 23 calls at admission — spendable 16 after the landing reserve (7: 6 to land the work, 1 to narrate it) — one short of the review fleetFloor (17) — so even paid-for breadth must decline to R0, non-error. The authored plan itself (6 calls) FITS, so only the fleetFloor+reserve gate stands between decline and spawn: drop the reserve from Ledger.spendable, drop cost_narration from totalReserve (#390), or drop the fleet_affordable term from the R3 branch, and this exact case spawns a fleet.", "args": ["--max-model-calls", "24"], "prompt": "run a thorough audit of the error handling across the codebase and report what you find", "script": [{"tool": "workflow", "arguments": {"phases": [{"title": "find problems", "tasks": [{"description": "auditor", "prompt": "audit the error handling and list every problem with evidence"}]}, {"title": "synthesize the findings", "tasks": [{"description": "synthesis", "prompt": "rank the problems most-severe first"}]}]}}, {"text": "pool too dry for a fleet — auditing solo as advised"}], "assert": [{"request_contains": {"index": 1, "text": "workflow declined (escalation R0):"}}, {"request_contains": {"index": 1, "text": "budget and scope fit solo work"}}, {"request_lacks": {"index": 1, "text": "(escalation R0d):"}}, {"no_event": {"type": "agent_route"}}, {"event": {"type": "tool_result", "name": "workflow", "is_error": false}}, {"final_text_contains": "auditing solo"}]}
{"id": "fabricated-report-anchors-reject-and-retry", "why": "report_anchors: a sweep-slot report citing only paths that do not exist (ghost.py, phantom.zig) must be rejected as fabricated, the rejection must be retry-SAFE, and the phase retry re-runs the worker with the anchor contract still in its brief so only a tree-anchored report reaches the root. Green-expected regression lock on anchorCheck in execWorkflow's await pipeline and anchor_brief_note delivery.", "args": [], "prompt": "investigate how the throttle limit reaches the sensor loop", "script": [{"tool": "workflow", "arguments": {"phases": [{"title": "sweep the throttle wiring", "tasks": [{"description": "scout", "prompt": "trace the throttle limit and report where it is enforced"}]}]}}, {"text": "The throttle limit is enforced in ghost.py and re-checked in phantom.zig."}, {"text": "The throttle limit is enforced inside the sensor loop initializer; RETRY-SENTINEL-c41a verified against the tree."}, {"text": "the throttle map is assembled"}], "timeout_s": 90, "assert": [{"request_contains": {"index": 1, "text": "Anchor every finding to real code"}}, {"request_contains": {"index": 1, "text": "as `proposed: <path>`"}}, {"request_contains": {"index": 2, "text": "Anchor every finding to real code"}}, {"events_at_least": {"match": {"type": "agent_usage"}, "count": 2}}, {"event": {"type": "tool_result", "name": "workflow", "is_error": false}}, {"request_contains": {"index": 3, "text": "RETRY-SENTINEL-c41a"}}, {"request_contains": {"index": 3, "text": "1/1 ok, 1 retried"}}, {"request_lacks": {"index": 3, "text": "ghost.py"}}, {"final_text_contains": "the throttle map is assembled"}]}
{"id": "escalation-audit-language-earns-r3", "why": "GREEN regression lock. Audit-class language in the ask (shapes.isAuditClass) is the paid-for-breadth signal: with an unlimited pool the workflow must ADMIT (R3) even though the ask names zero files — no other rung can admit it — and the find brief must carry the report-anchor contract. Guards the `(o.audit or o.prior_failure) and fleet_affordable` branch of ladderRung; remove it and the fleet never spawns and the decline advisory appears instead.", "args": [], "prompt": "run a thorough audit of the error handling across the codebase and report what you find", "script": [{"tool": "bash", "arguments": {"command": "echo 'def handler(): pass' > app.py && echo seeded-app"}}, {"tool": "workflow", "arguments": {"phases": [{"title": "find problems", "tasks": [{"description": "auditor", "prompt": "audit the error handling and list every problem with evidence"}]}, {"title": "synthesize the findings", "tasks": [{"description": "synthesis", "prompt": "rank the problems most-severe first"}]}]}}, {"text": "AUDIT-FINDING-ALPHA: app.py swallows errors in its handler and reports success"}, {"text": "AUDIT-SYNTHESIS: one severe issue — app.py swallows errors"}, {"text": "audit complete: the handler swallows errors"}], "assert": [{"event": {"type": "tool_result", "name": "bash", "text": "seeded-app\n"}}, {"event": {"type": "tool_result", "name": "workflow", "is_error": false}}, {"events_at_least": {"match": {"type": "agent_route"}, "count": 2}}, {"events_at_most": {"match": {"type": "agent_route"}, "count": 2}}, {"request_contains": {"index": 2, "text": "Anchor every finding to real code"}}, {"request_contains": {"index": -1, "text": "AUDIT-SYNTHESIS"}}, {"request_lacks": {"index": -1, "text": "workflow declined"}}, {"final_text_contains": "audit complete"}], "timeout_s": 120}
{"id": "landing-note-fires-exactly-once", "why": "#390 (green regression lock): the landing note and the tools-withheld trick belong to the FINAL admitted call only. On a cap-3 run, request 3 must carry [budget landing] with no tools, while request 2 still offers the full toolset and no note - an off-by-one that stamps the penultimate call would strand a run tool-less with budget still in the pool.", "args": ["--max-model-calls", "3"], "prompt": "read the todo list twice, then report what you saw", "script": [{"tool": "todo_read", "arguments": {}}, {"tool": "todo_read", "arguments": {}}, {"text": "landing: read the list twice; it was empty both times; nothing else was verified"}], "assert": [{"events_at_least": {"match": {"type": "tool_call", "name": "todo_read"}, "count": 2}}, {"request_lacks": {"index": 0, "text": "[budget landing]"}}, {"request_lacks": {"index": 1, "text": "[budget landing]"}}, {"request_contains": {"index": 1, "text": "\"todo_write\""}}, {"request_contains": {"index": -1, "text": "[budget landing]"}}, {"request_lacks": {"index": -1, "text": "\"todo_write\""}}, {"final_text_contains": "landing: read the list twice"}]}
diff --git a/src/compact_note_tests.zig b/src/compact_note_tests.zig
index 8abaecce..2060812f 100644
--- a/src/compact_note_tests.zig
+++ b/src/compact_note_tests.zig
@@ -151,7 +151,7 @@ test "decideCalls (#391): the budget gate IS #390's landing reserve, not a secon
// Derived, never hard-coded: the first `remaining` that admits a note is
// one call above whatever phase_budget holds back for the root to land and
// narrate the work. A parallel reserve of the note's own would move this.
- const reserve = phase_budget.landingReserve(cap);
+ const reserve = phase_budget.totalReserve(cap);
var in = baseInputs();
in.cap = cap;
diff --git a/src/escalation.zig b/src/escalation.zig
index e475e33e..98623b25 100644
--- a/src/escalation.zig
+++ b/src/escalation.zig
@@ -461,7 +461,7 @@ pub fn decide(o: Observables, phases: []const Value, explicit: bool, arms: []con
const rung: Rung = if (ladder.level() >= Rung.R2.level()) ladder else .R2;
return .{ .rung = rung, .source = .explicit, .verdict = verdictFor(rung, o, phases) };
}
- const reserve = pb.landingReserve(o.cap);
+ const reserve = pb.totalReserve(o.cap); // landing work AND narration (#390)
if (orch.override(arms, key, ladder, o.remaining, reserve)) |learned| {
return .{ .rung = learned, .source = .learned, .verdict = learnedVerdict(learned, o, phases) };
}
@@ -494,7 +494,7 @@ pub fn admit(c: Ctx, phases: []const Value, shape: route_policy.Shape) Decision
var d = decide(o, phases, userChoseShape(raw), armsFor(key), key);
// No learned cell: fall back to the compiled bootstrap prior (study rows, n=2).
if (d.source == .bootstrap and !userChoseShape(raw)) {
- if (orch.learnedRung(key, d.rung, o.remaining, pb.landingReserve(o.cap))) |learned| {
+ if (orch.learnedRung(key, d.rung, o.remaining, pb.totalReserve(o.cap))) |learned| {
d = .{ .rung = learned, .source = .learned, .verdict = learnedVerdict(learned, o, phases) };
}
}
@@ -523,7 +523,7 @@ pub fn admit(c: Ctx, phases: []const Value, shape: route_policy.Shape) Decision
var buf: [192]u8 = undefined;
const line = std.fmt.bufPrint(&buf, "arm={s} source={s} class={s} files={d} tasks={d} band={s} plan={d} reserve={d}", .{
d.rung.label(), d.source.label(), o.task_class.label(), o.files,
- o.tasks, key.budget_band.label(), o.plan_estimate, pb.landingReserve(o.cap),
+ o.tasks, key.budget_band.label(), o.plan_estimate, pb.totalReserve(o.cap),
}) catch "";
tr.note("escalation", line);
}
diff --git a/src/escalation_tests.zig b/src/escalation_tests.zig
index 3ab9e5da..6640f217 100644
--- a/src/escalation_tests.zig
+++ b/src/escalation_tests.zig
@@ -47,7 +47,7 @@ test "ladder: the study's cap-30 bugfix is R0 — one file is not a fleet" {
var o = base();
try std.testing.expectEqual(Rung.R0, escalation.ladderRung(o));
// Note WHY it is R0 and not a budget refusal: a review fleet (17) plus the
- // landing reserve (6) does fit the 27 that remain. The budget said yes.
+ // landing reserve (7) does fit the 27 that remain. The budget said yes.
try std.testing.expect(pb.Ledger.init(30).fits(27, pb.fleetFloor(.review)));
// Two files is still a pair, not a fan-out.
o.files = 2;
@@ -69,7 +69,7 @@ test "ladder: scope alone opens R2, and only at 3+ files with a plan that fans o
test "ladder: budget vetoes R2 even at full scope" {
var o = base();
o.files = 6;
- // 12 left, 6 reserved, a review fleet needs 17: the fleet cannot finish,
+ // 12 left, 7 reserved, a review fleet needs 17: the fleet cannot finish,
// so the answer is the rung that can.
o.remaining = 12;
try std.testing.expectEqual(Rung.R0, escalation.ladderRung(o));
@@ -146,25 +146,26 @@ test "downsizeWidth: trims redundant finders and never the landing phase" {
defer arena_state.deinit();
const a = arena_state.allocator();
// A-fix at width: 4 finders (16) + 1 implementer (6) + 1 verify (3) = 25,
- // against 21 spendable at cap 30 / 27 remaining.
+ // against 20 spendable at cap 30 / 27 remaining.
const phases = phasesFrom(a,
\\[{"title":"find the defect","tasks":[1,2,3,4]},
\\ {"title":"implement the fix","tasks":[1]},
\\ {"title":"verify the diff","tasks":[1]}]
);
const w = escalation.downsizeWidth(phases, 30, 27);
- // 3 finders (12) + 6 + 3 = 21 fits exactly; 4 (16+6+3=25) would not.
- try std.testing.expectEqual(@as(usize, 3), w);
+ // 2 finders (8) + 6 + 3 = 17 fits; 3 (12+6+3=21) is one call past the
+ // reserve, because the reserve also holds the narration turn (#390).
+ try std.testing.expectEqual(@as(usize, 2), w);
// Whatever the width, the implement phase carries one task, so the edit
// contract survives every trim — which is §4-P1's inviolable rule.
try std.testing.expect(w >= 1);
// Squeeze until only the skinniest plan fits: 1 finder + 1 implementer +
- // 1 verify = 13, on top of the 6-call reserve, so 19 left is the floor.
- try std.testing.expectEqual(@as(usize, 1), escalation.downsizeWidth(phases, 30, 19));
+ // 1 verify = 13, on top of the 7-call reserve, so 20 left is the floor.
+ try std.testing.expectEqual(@as(usize, 1), escalation.downsizeWidth(phases, 30, 20));
// And below that, nothing fits — the caller must fall back to solo. Note
// WHAT does not fit: the landing phase's own implementer, which is the
// point at which a fleet stops being able to produce a patch at all.
- try std.testing.expectEqual(@as(usize, 0), escalation.downsizeWidth(phases, 30, 18));
+ try std.testing.expectEqual(@as(usize, 0), escalation.downsizeWidth(phases, 30, 19));
// An unlimited pool never trims.
try std.testing.expectEqual(@as(usize, 4), escalation.downsizeWidth(phases, 0, std.math.maxInt(u64)));
}
diff --git a/src/phase_budget.zig b/src/phase_budget.zig
index 88a5127d..08a323d4 100644
--- a/src/phase_budget.zig
+++ b/src/phase_budget.zig
@@ -25,6 +25,13 @@
//! P3 optional judges and other nice-to-haves run only when they fit
//! ON TOP of the reserve (subagent.scoreVariants).
//!
+//! The reserve is not only landing WORK. Every call that reads a result or
+//! makes an edit ends in a tool round-trip, so a run can spend the reserve
+//! down to zero doing exactly what it was asked to do and then have nothing
+//! left to SAY SO. The final narration turn is a model call like any other:
+//! `cost_narration` names it and `totalReserve` folds it into the reserve, so
+//! no gate here can spend the turn that reports the work (#390).
+//!
//! Everything here is PURE arithmetic over cheap observables — no model call,
//! no I/O — so the whole ladder is unit-testable without a network.
@@ -89,9 +96,34 @@ pub fn landingReserve(cap: u64) u64 {
return @max(min_landing_reserve, cap / 5);
}
+/// #390: what the run's FINAL turn costs — the one model call that tells the
+/// user what happened. One call, no tools, and until it was named here nobody
+/// had reserved it. `landingReserve` sizes the calls that LAND the work (read
+/// a result, edit, verify), and each of those ends in a tool round-trip that
+/// owes a follow-up call; a run could therefore admit its work, land it,
+/// verify it, truncate its last phase correctly — and still die on the turn
+/// that would have reported all of it. That is not hypothetical either: it is
+/// the 06-audit acceptance run at cap 30, `exhaustedFatal` with the work done
+/// and nothing narrated.
+pub const cost_narration: u64 = 1;
+
+/// What the ledger actually holds back: the calls that land the work PLUS the
+/// one that narrates it.
+///
+/// THE TWO HARNESS LIABILITIES ARE ORDERED, AND THE ORDER IS NOT SYMMETRIC.
+/// Narration is MANDATORY and senior — it IS part of the reserve, funded
+/// before any phase spends a call and before #391's optional note, and no
+/// gate below can reach it. The pre-compaction note is optional and junior:
+/// it must clear this whole number to run at all. Narration is counted
+/// exactly ONCE, right here, and nothing adds it again — a liability with a
+/// reserve of its own is the double-count `cost_precompact_note` warns about.
+pub fn totalReserve(cap: u64) u64 {
+ return landingReserve(cap) + cost_narration;
+}
+
/// #391: what ONE pre-compaction note-to-self costs. It is a cost, not a
-/// second reserve, and that distinction is the whole point. The reserve above
-/// already protects the calls the root needs to land and narrate the work
+/// second reserve, and that distinction is the whole point. `totalReserve`
+/// already protects the calls the root needs to land AND narrate the work
/// (#390); a note with a reserve of its own would be a SECOND ledger over the
/// same pool, and two ledgers each holding back "the last call" double-count
/// it. Charged through `affordsHarnessNote` instead, so the note runs only
@@ -170,13 +202,14 @@ pub fn isLandingRole(role: []const u8) bool {
pub const Ledger = struct {
/// The run's `--max-model-calls`; 0 means unlimited.
cap: u64,
- /// Calls held back for the root to land the work.
+ /// Calls held back for the root to land the work AND narrate it — the
+ /// landing reserve plus the one final turn (`totalReserve`).
reserve: u64,
/// Calls this run's phases have already been charged for by `commit`.
committed: u64 = 0,
pub fn init(cap: u64) Ledger {
- return .{ .cap = cap, .reserve = landingReserve(cap) };
+ return .{ .cap = cap, .reserve = totalReserve(cap) };
}
/// An unlimited pool cannot exhaust, so every gate below passes; keeping
@@ -206,11 +239,32 @@ pub const Ledger = struct {
return remaining < later_min + self.reserve;
}
+ /// The part of the reserve that funds landing WORK — everything except
+ /// the final turn. Stated so the split is readable rather than inferred:
+ /// `reserve == landingWork() + cost_narration`, always.
+ pub fn landingWork(self: Ledger) u64 {
+ return self.reserve -| cost_narration;
+ }
+
+ /// The SENIOR harness liability: can the run still say what it did?
+ /// Narration sits INSIDE the reserve rather than on top of it, so unlike
+ /// the note it is never asked to clear anything — one call left is
+ /// enough, and every gate above exists to make sure one call is left.
+ /// Deliberately NOT `fits`: routing narration through the P3 predicate
+ /// would make the mandatory turn junior to the reserve that exists for
+ /// it, which is the inversion #390 is about.
+ pub fn affordsNarration(self: Ledger, remaining: u64) bool {
+ if (self.unlimited()) return true;
+ return remaining >= cost_narration;
+ }
+
/// P3 for the HARNESS's own optional call (#391's pre-compaction note).
/// Same predicate the judges use, and deliberately so: the note is the
- /// junior liability on this ledger. Narration is mandatory and owns the
- /// reserve; the note is a nice-to-have and must clear it. A run that can
- /// only afford one more call spends it landing, not journaling.
+ /// JUNIOR liability on this ledger. Narration is mandatory and is part of
+ /// the reserve; the note is a nice-to-have and must clear the whole of
+ /// it. A run that can only afford one more call spends it landing and
+ /// narrating, not journaling — so of the two harness calls the note is
+ /// always the one refused first.
pub fn affordsHarnessNote(self: Ledger, remaining: u64) bool {
return self.fits(remaining, cost_precompact_note);
}
@@ -264,12 +318,27 @@ test "landingReserve: a floor below cap 30, a fifth above it" {
try std.testing.expectEqual(@as(u64, 20), landingReserve(100));
}
+test "totalReserve (#390): the work reserve PLUS the one turn that reports it" {
+ // Narration is one turn, not a proportion, and it is added exactly once —
+ // at every cap, including the unlimited pool whose reserve is nominal.
+ for ([_]u64{ 0, 12, 30, 40, 100 }) |cap| {
+ const l = Ledger.init(cap);
+ try std.testing.expectEqual(landingReserve(cap) + cost_narration, totalReserve(cap));
+ try std.testing.expectEqual(totalReserve(cap), l.reserve);
+ // The split reads back exactly, so no call is counted on both sides.
+ try std.testing.expectEqual(landingReserve(cap), l.landingWork());
+ try std.testing.expectEqual(l.reserve, l.landingWork() + cost_narration);
+ }
+ // The 06-audit acceptance cap: 6 calls to land, 1 to say what happened.
+ try std.testing.expectEqual(@as(u64, 7), totalReserve(30));
+}
+
test "fleetFloor: every shape costs more than the reserve it must clear" {
for ([_]Shape{ .review, .research, .design, .feature, .migration, .adhoc }) |s| {
try std.testing.expect(fleetFloor(s) >= min_landing_reserve);
}
- // The study's cap-30 bugfix: a review fleet (17) plus the reserve (6) is
- // 23 of the ~27 calls left after the root has read the task — affordable
+ // The study's cap-30 bugfix: a review fleet (17) plus the reserve (7) is
+ // 24 of the ~27 calls left after the root has read the task — affordable
// on paper, which is exactly why SCOPE, not budget alone, has to gate it.
try std.testing.expectEqual(@as(u64, 17), fleetFloor(.review));
try std.testing.expectEqual(@as(u64, 14), fleetFloor(.research));
@@ -278,10 +347,10 @@ test "fleetFloor: every shape costs more than the reserve it must clear" {
test "Ledger: spendable, fits and earlyExit all sit ON TOP of the reserve" {
var l = Ledger.init(30);
- try std.testing.expectEqual(@as(u64, 6), l.reserve);
- try std.testing.expectEqual(@as(u64, 21), l.spendable(27));
- try std.testing.expect(l.fits(27, 21));
- try std.testing.expect(!l.fits(27, 22)); // one call into the reserve is one too many
+ try std.testing.expectEqual(@as(u64, 7), l.reserve); // 6 to land + 1 to narrate
+ try std.testing.expectEqual(@as(u64, 20), l.spendable(27));
+ try std.testing.expect(l.fits(27, 20));
+ try std.testing.expect(!l.fits(27, 21)); // one call into the reserve is one too many
// Saturating, never wrapping: below the reserve there is simply nothing
// to spend, and no gate may read that as "a very large budget".
try std.testing.expectEqual(@as(u64, 0), l.spendable(4));
@@ -295,13 +364,13 @@ test "Ledger: spendable, fits and earlyExit all sit ON TOP of the reserve" {
test "affordsHarnessNote (#391): the note clears #390's reserve, it does not get one of its own" {
const l = Ledger.init(30);
- // The boundary is DERIVED from the landing reserve, not from a constant of
- // the note's own: the first `remaining` that admits a note is one call
- // above the reserve #390 holds back. A second, independent reserve would
- // move this boundary and fail here.
- const boundary = landingReserve(30) + cost_precompact_note;
+ // The boundary is DERIVED from the reserve, not from a constant of the
+ // note's own: the first `remaining` that admits a note is one call above
+ // the whole reserve #390 holds back (landing work AND narration). A
+ // second, independent reserve would move this boundary and fail here.
+ const boundary = l.reserve + cost_precompact_note;
try std.testing.expect(l.affordsHarnessNote(boundary));
- try std.testing.expect(!l.affordsHarnessNote(boundary - 1)); // exactly the reserve: landing only
+ try std.testing.expect(!l.affordsHarnessNote(boundary - 1)); // the reserve: land and narrate only
try std.testing.expect(!l.affordsHarnessNote(0));
// And the note is junior to a phase that fits: whatever spendable() says
// is available for real work is available for the note too, never more.
@@ -310,6 +379,54 @@ test "affordsHarnessNote (#391): the note clears #390's reserve, it does not get
try std.testing.expect(Ledger.init(0).affordsHarnessNote(std.math.maxInt(u64)));
}
+test "#390: a run that spends every call it may is still left one to narrate" {
+ const l = Ledger.init(30);
+ // The shape the issue reports: 27 left after the root has read the task,
+ // a fleet that takes every call the ledger will release, then a P2 stop.
+ var remaining: u64 = 27;
+ const spent = l.spendable(remaining);
+ try std.testing.expect(l.fits(remaining, spent));
+ remaining -= spent;
+ try std.testing.expectEqual(l.reserve, remaining); // the reserve, untouched
+ // The root now lands the work, spending the calls `landingReserve` was
+ // sized for — read a result, make the edit, verify it …
+ remaining -= landingReserve(l.cap);
+ // … and one call is STILL there. That is the entire point of #390, and
+ // the assertion that goes red the moment cost_narration stops being
+ // added: before it, landing consumed the reserve down to nothing.
+ try std.testing.expectEqual(cost_narration, remaining);
+ try std.testing.expect(l.affordsNarration(remaining));
+
+ // At the boundary — nothing spendable left at all, P2 stopping the loop —
+ // the run still narrates. This is what failed before cost_narration.
+ try std.testing.expectEqual(@as(u64, 0), l.spendable(l.reserve));
+ try std.testing.expect(l.earlyExit(l.reserve, 1));
+ try std.testing.expect(l.affordsNarration(l.reserve));
+ try std.testing.expect(l.affordsNarration(cost_narration));
+ // Only a pool that is genuinely empty cannot narrate.
+ try std.testing.expect(!l.affordsNarration(0));
+ try std.testing.expect(Ledger.init(0).affordsNarration(0)); // unlimited never gates
+}
+
+test "#390/#391: narration is senior, the note is junior, and neither is counted twice" {
+ const l = Ledger.init(30);
+ var narrates_but_no_note: u64 = 0;
+ var r: u64 = 0;
+ while (r <= l.reserve + 3) : (r += 1) {
+ // The junior liability never runs where the senior one could not.
+ if (l.affordsHarnessNote(r)) try std.testing.expect(l.affordsNarration(r));
+ if (l.affordsNarration(r) and !l.affordsHarnessNote(r)) narrates_but_no_note += 1;
+ }
+ // And the gap is real, not vacuous: every call from 1 up to the whole
+ // reserve narrates and refuses the note, so of the two harness calls the
+ // note is always the one given up first.
+ try std.testing.expectEqual(l.reserve, narrates_but_no_note);
+ // The note's boundary is the reserve + its own cost: narration is paid
+ // for ONCE, inside the reserve, and never charged again on top of it.
+ try std.testing.expect(!l.affordsHarnessNote(l.reserve));
+ try std.testing.expect(l.affordsHarnessNote(l.reserve + cost_precompact_note));
+}
+
test "Ledger: an unlimited pool never gates" {
const l = Ledger.init(0);
try std.testing.expect(l.unlimited());
diff --git a/src/workflow_pipeline.zig b/src/workflow_pipeline.zig
index 8eb925e9..ccf2db13 100644
--- a/src/workflow_pipeline.zig
+++ b/src/workflow_pipeline.zig
@@ -313,7 +313,7 @@ pub fn run(ctx: ToolCtx, pv: Value, outer_context: []const u8) !ToolOutput {
test "pipelineEstimate prices a chain per item, so a wide pipeline is not free" {
// The study's refactor run: 4 items x 2 off-vocabulary stages. At the
// median role cost that is 24 calls, which does not fit a cap-30 pool
- // once the landing reserve (6) is held back from the ~27 that remain.
+ // once the landing reserve (7) is held back from the ~27 that remain.
const roles = [_][]const u8{ "", "" };
try std.testing.expectEqual(@as(u64, 24), pipelineEstimate(4, &roles));
try std.testing.expect(!phase_budget.Ledger.init(30).fits(27, 24));