graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix: keep background-agent handles across an interrupted API turn (#753)
Cursor Agent856a89da3c74
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e2465311..5c182522 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,14 @@ The release workflow uses a tag's section here as its release notes (ahand-written `docs/releases/<tag>.md` wins if present), so keeping this filecurrent is part of cutting a release.+## Unreleased++- `#753`: a background-agent handle survives a recoverable API interruption.+ `agent_output` replays a finished report, or says the launch ended with the+ parent turn, instead of "it may never have started". The ids ride in the+ session file. An ACP API error is a failed turn (saved), not a dead process.+ ADR 0068.+## v0.0.288 (2026-09-06)- Recorded user constraints ride the root prefix as live ledger JSON, includingdiff --git a/apps/native/app/api/acp/route.ts b/apps/native/app/api/acp/route.tsindex 2c51a24e..35a4248e 100644--- a/apps/native/app/api/acp/route.ts+++ b/apps/native/app/api/acp/route.ts@@ -308,6 +308,7 @@ export async function POST(req: NextRequest) {if (method === "session/prompt") {const id = slot.nextId++;const encoder = new TextEncoder();+ let finished = false;const stream = new ReadableStream({start(controller) {const onData = (chunk: Buffer) => {@@ -325,6 +326,7 @@ export async function POST(req: NextRequest) {}controller.enqueue(encoder.encode(`${line}\n`));if (msg.id === id && !msg.method) {+ finished = true;slot.child.stdout.off("data", onData);controller.close();return;@@ -340,6 +342,9 @@ export async function POST(req: NextRequest) {});},cancel() {+ // #753: reader.cancel() after a completed error/result must not+ // raise session/cancel — that stole the next continuation's handles.+ if (finished) return;writeLine(slot, { jsonrpc: "2.0", method: "session/cancel", params: { sessionId: slot.sessionId } });},});diff --git a/docs/adr/0068-background-agent-handles-survive-interrupt.md b/docs/adr/0068-background-agent-handles-survive-interrupt.mdnew file mode 100644index 00000000..64a502f8--- /dev/null+++ b/docs/adr/0068-background-agent-handles-survive-interrupt.md@@ -0,0 +1,33 @@+# 0068. Background-agent handles survive an interrupted parent turn++Status: accepted 2026-09-06++## Context++`subagent {run_in_background:true}` returns a numeric handle from a+process-global pump table (`g_agent_jobs`). That table is gone after a+recoverable API interruption that kills or respawns the process (ACP+`-32603`, native `reader.cancel()` raising `session/cancel`, a panic on a+bad envelope). `#753` then saw `agent_output` answer every issued id with+"no background agent — it may never have started", which is false: the+launches succeeded.++The live table cannot be reattached across a process boundary. The+*record* of what we issued can.++## Decision++* Every issued handle is written to a session ledger (`subagent_ledger.zig`)+ and saved with the conversation (`background_agents` in the session file).+* `agent_output` that misses the live table consults the ledger: a finished+ row replays the report; a still-running row from a dead process is named+ as interrupted, never as "never started".+* An ACP API error is a failed turn: save the session (including the+ ledger) and return the error text. Do not exit the ACP loop. A completed+ prompt stream must not send `session/cancel` on reader cleanup.++## Consequences++* Continuation after an interrupt can poll the same ids. Running children+ that died with the process cannot resume; the model is told to re-launch.+* Session files grow a small optional array. Older builds ignore the field.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 10d2d5f2..669f4efe 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -78,6 +78,7 @@ record only when you need the evidence or the edge cases.| [0065](0065-stop-bounded-prose-repetition.md) | Stop bounded lexical prose loops before delivery without user cancellation, transport retries, or completion nudges. || [0066](0066-publication-policy-and-ledger-authority.md) | Publication safeguards survive custom prompts; recaps cannot change ledger authority, and constraint writes refresh active prompts atomically. || [0067](0067-recorded-constraints-are-ledger-state.md) | Recorded constraints are live ledger JSON in the root prefix; recap prose is not authority, and a write refreshes instructions in the same turn. |+| [0068](0068-background-agent-handles-survive-interrupt.md) | Background-agent ids are a session ledger; an interrupted parent turn must not report them as never started (#753). |## When to write onediff --git a/src/acp.zig b/src/acp.zigindex 49ead453..3d754cc9 100644--- a/src/acp.zig+++ b/src/acp.zig@@ -164,6 +164,7 @@ const LiveTurn = struct {fn run(ctx: *anyopaque, arena: Allocator, text: []const u8) anyerror![]const u8 {const self: *LiveTurn = @ptrCast(@alignCast(ctx));+ agent_mod.Agent.prepareRootTurn(); // #753: a prior stream cancel must not steal the continuationswitch (try @import("turn_dedup.zig").enqueue(self.root, arena, self.out, text)) {.started => {},.skipped => return "",@@ -181,7 +182,17 @@ const LiveTurn = struct {self.root.out = null;main_mod.g_out = null;}- const final = try providers.runTurnWithFallback(self.root, self.keys, arena, null);+ const final = providers.runTurnWithFallback(self.root, self.keys, arena, null) catch |err| {+ // #753: an API interruption is a failed turn, not a dead ACP+ // process. Save so the next prompt (and a respawn --resume) still+ // sees the tool results and the background-agent ledger.+ session.saveSession(self.root, self.root.arena, self.root.session_name) catch {};+ if (err == error.ApiError) {+ const msg = self.root.last_api_error orelse "provider API error";+ return std.fmt.allocPrint(arena, "{s}", .{msg});+ }+ return err;+ };// The REPL checkpoints after every turn (mainloop); an ACP host's// conversation deserves the same durability. Without this a text-only// turn reached .graff/sessions only at stdin EOF, and a tab the hostdiff --git a/src/cli.zig b/src/cli.zigindex 6bc48b5a..b44bea84 100644--- a/src/cli.zig+++ b/src/cli.zig@@ -21,6 +21,9 @@ const harness_version = root.harness_version;pub const changelog_text =\\What's new\\──────────+ \\0.0.289+ \\ • background-agent handles survive an interrupted API turn (#753)+ \\\\0.0.288\\ • Gemini is a first-class provider on Google's Interactions API\\ • recorded constraints ride the prefix as ledger JSON; recaps cannot invent them (#738)diff --git a/src/commands_session.zig b/src/commands_session.zigindex 664fdf62..dd56afe9 100644--- a/src/commands_session.zig+++ b/src/commands_session.zig@@ -81,6 +81,7 @@ pub fn resetConversationSteering(root: *Agent) void {if (root.goal_flag) |g| root.goal = goal_flow.standingGoalFromFlag(g, null, root.todos.items, 0);@import("rlm_spec.zig").resetBindsSession(root.io);@import("native_fold.zig").resetSession();+ @import("subagent_ledger.zig").reset(root.gpa); // #753: handles belong to the conversation}/// Try to handle a session/environment slash command. Returns false (linediff --git a/src/session.zig b/src/session.zigindex 47e39d36..90bcbb76 100644--- a/src/session.zig+++ b/src/session.zig@@ -24,6 +24,7 @@ const provider_mod = @import("provider.zig");const util = @import("util.zig");const goal_state = @import("goal_state.zig");const session_writer = @import("session_writer.zig"); // #273: the fingerprint + the background write+const subagent_ledger = @import("subagent_ledger.zig"); // #753: persist background-agent handlesconst shutdown_trace = @import("shutdown_trace.zig"); // #364: teardown phase stampsconst protocol_seq = @import("protocol_seq.zig"); // #330: the --json event sequence survives a resumeconst http_headers = @import("http_headers.zig"); // the k3/codex prompt-cache key survives one too@@ -177,6 +178,7 @@ fn fingerprint(root: *Agent, name: []const u8) u64 {f.num(protocol_seq.current());f.json(Value{ .array = root.messages });session_peer.mixFingerprint(&f);+ subagent_ledger.mixFingerprint(&f);return f.final();}@@ -339,6 +341,7 @@ fn queueSave(root: *Agent, arena: Allocator, dir: Io.Dir, name: []const u8) !u64try s.objectField("cache_key");try s.write(http_headers.sessionId(root.io));try session_peer.writeFields(&s);+ try subagent_ledger.writeFields(&s, root.io);try s.endObject();// #289: two graffs in one workspace share this file — the writer makes the@@ -536,4 +539,8 @@ pub fn loadSession(root: *Agent, keys: *Keys, arena: Allocator, name: []const u8root.fallback_active = false;root.fallback_blocked = false;session_peer.restore(root, obj);+ subagent_ledger.restore(root.gpa, root.io, obj.get("background_agents"));+ const subagent = @import("subagent.zig");+ if (subagent_ledger.nextId() > subagent.g_agent_jobs.next_id)+ subagent.g_agent_jobs.next_id = subagent_ledger.nextId();}diff --git a/src/subagent.zig b/src/subagent.zigindex deb12f19..bfb6e168 100644--- a/src/subagent.zig+++ b/src/subagent.zig@@ -35,6 +35,7 @@ const learning_privacy = @import("learning_privacy.zig");const agentTypePrompt = fleet.agentTypePrompt;const Isolation = fleet.Isolation;const jobs = @import("jobs.zig"); // #276 P0-1: agentWorktreeCreate/agentWorktreeFinish/isolationFailureText+const ledger = @import("subagent_ledger.zig"); // #753: handles survive an interrupted parent turnconst run_budget = @import("run_budget.zig"); // #276 P0-3: default_max_concurrency, reused as the background-agent cap's default valueconst cards = @import("cards.zig");const trace = @import("trace.zig");@@ -117,14 +118,14 @@ const classifyFailure = subagent_run.classifyFailure;/// each job needs to ever finish and release it — a deadlock. Same admission/// SHAPE as RunBudget.acquireConcurrency (spin-wait, no failure on saturation)/// and the same default value, but an independent resource.-const max_concurrent_background_agents: u32 = run_budget.default_max_concurrency;+pub const max_concurrent_background_agents: u32 = run_budget.default_max_concurrency;/// One background subagent spawn: the runSub arguments (gpa-owned copies —/// the caller's ToolCtx.arena-backed strings do not outlive this tool call's/// return, the whole point of fire-and-forget) plus its outcome once done./// `admitted` is false while queued behind max_concurrent_background_agents;/// jobs.zig's Job mirrors this shape (id/cmd there ~ id/label+prompt here).-const AgentJob = struct {+pub const AgentJob = struct {id: u32,label: []u8,prompt: []u8,@@ -151,7 +152,7 @@ const AgentJob = struct {future: Io.Future(void) = undefined, // pump; awaited only by agentJobsReap};-const AgentJobs = struct {+pub const AgentJobs = struct {mutex: Io.Mutex = .init,list: std.ArrayList(*AgentJob) = .empty,active: u32 = 0, // admitted and not yet done@@ -170,7 +171,7 @@ pub var g_agent_jobs: AgentJobs = .{};/// nothing is queued. No Io — callers hold AgentJobs.mutex around it; kept/// separate so the queue-not-fail contract (design point 6) is unit-testable/// without a real Io/thread pool.-fn admitOneLocked(registry: *AgentJobs) ?*AgentJob {+pub fn admitOneLocked(registry: *AgentJobs) ?*AgentJob {if (registry.active >= max_concurrent_background_agents) return null;for (registry.list.items) |j| {if (!j.admitted) {@@ -223,6 +224,7 @@ fn agentJobPump(job: *AgentJob, gpa: Allocator, io: Io) void {job.done = true;g_agent_jobs.active -= 1;g_agent_jobs.mutex.unlock(io);+ ledger.finish(gpa, io, job.id, job.is_error, job.result, job.usage);admitNext(gpa, io);}@@ -273,6 +275,7 @@ fn spawnSubBackground(ctx: ToolCtx, label: []const u8, prompt: []const u8, sys_oreturn error.OutOfMemory;}admitNext(gpa, ctx.io);+ ledger.remember(gpa, ctx.io, job.id, job.label);return .{ .text = try std.fmt.allocPrint(gpa,"[agent {d} started: {s}]\nIt runs in the background across turns. Do not poll. agent_output(id {d}, wait_ms>0) blocks until it finishes; omit wait_ms for a snapshot. After completion, agent_output keeps returning the same result.",@@ -317,7 +320,7 @@ pub fn agentOutput(gpa: Allocator, io: Io, id: u32, wait_ms: u64) !ToolOutput {g_agent_jobs.mutex.lockUncancelable(io);const job = g_agent_jobs.find(id) orelse {g_agent_jobs.mutex.unlock(io);- return .{ .text = try std.fmt.allocPrint(gpa, "no background agent {d} — it may never have started; subagent with run_in_background:true returns the id when it launches", .{id}), .is_error = true };+ return ledger.missing(gpa, io, id);};if (job.done or waited >= deadline) {const text = try agentStatusText(gpa, id, job.done, job.is_error, job.usage, job.result);@@ -348,6 +351,7 @@ pub fn agentOutput(gpa: Allocator, io: Io, id: u32, wait_ms: u64) !ToolOutput {/// at shutdown never started, so it's simply dropped: nothing ran, nothing/// to lose.pub fn agentJobsReap(gpa: Allocator, io: Io) void {+ ledger.markRunningInterrupted(io);g_agent_jobs.mutex.lockUncancelable(io);const list = g_agent_jobs.list.toOwnedSlice(gpa) catch {g_agent_jobs.mutex.unlock(io);@@ -366,43 +370,6 @@ pub fn agentJobsReap(gpa: Allocator, io: Io) void {gpa.free(list);}-test "admitOneLocked: admits up to the cap, queues the rest, FIFO order (#276 P0-3 design point 6)" {- const gpa = std.testing.allocator;- var registry: AgentJobs = .{};- defer registry.list.deinit(gpa);-- var stub_jobs: [max_concurrent_background_agents + 3]AgentJob = undefined;- for (&stub_jobs, 0..) |*j, i| j.* = .{- .id = @intCast(i + 1),- .label = @constCast(""),- .prompt = @constCast(""),- .niche = @constCast(""),- .isolation = .shared_cwd,- .isolation_fallback = false,- .ctx = undefined,- };- for (&stub_jobs) |*j| try registry.list.append(gpa, j);-- var admitted_order: [stub_jobs.len]u32 = undefined;- var n: usize = 0;- while (admitOneLocked(®istry)) |j| : (n += 1) admitted_order[n] = j.id;-- try std.testing.expectEqual(@as(usize, max_concurrent_background_agents), n); // only the cap gets admitted immediately- try std.testing.expectEqual(max_concurrent_background_agents, registry.active);- for (admitted_order[0..n], 1..) |id, expect| try std.testing.expectEqual(@as(u32, @intCast(expect)), id); // FIFO-- var still_queued: usize = 0;- for (stub_jobs) |j| if (!j.admitted) {- still_queued += 1;- };- try std.testing.expectEqual(stub_jobs.len - n, still_queued); // the remainder stay queued, not failed-- // A finished job frees its slot; the next queued one is then admittable.- registry.active -= 1;- const next = admitOneLocked(®istry).?;- try std.testing.expectEqual(@as(u32, max_concurrent_background_agents + 1), next.id);-}-/// One task inside a workflow phase; never throws, suitable for io.async./// `niche` is the task's MAP-Elites cell, threaded through so runSub's/// fleet:propose — and scoreVariants' submit — tag the variant's genome.diff --git a/src/subagent_ledger.zig b/src/subagent_ledger.zignew file mode 100644index 00000000..3f9de1a2--- /dev/null+++ b/src/subagent_ledger.zig@@ -0,0 +1,291 @@+//! Session ledger for background subagent handles (#753).+//!+//! `g_agent_jobs` is the live pump table: it dies with the process (ACP child+//! respawn, a panic on a bad API envelope, `agentJobsReap` at session end).+//! The model still holds the numeric ids from the interrupted turn. This+//! ledger is the durable record of every id we issued, so `agent_output`+//! can replay a finished report or say the launch ended with the parent+//! turn instead of "it may never have started".++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;+const Value = std.json.Value;++const tools = @import("tools.zig");+const ToolOutput = tools.ToolOutput;+const AgentUsage = @import("subagent_run.zig").AgentUsage;+const agentStatusText = @import("subagent.zig").agentStatusText;++const Entry = struct {+ id: u32,+ label: []u8,+ done: bool = false,+ is_error: bool = false,+ interrupted: bool = false,+ result: []u8 = &.{},+ usage: AgentUsage = .{},+};++const Ledger = struct {+ mutex: Io.Mutex = .init,+ list: std.ArrayList(*Entry) = .empty,+ next_id: u32 = 1,++ fn find(self: *Ledger, id: u32) ?*Entry {+ for (self.list.items) |e| if (e.id == id) return e;+ return null;+ }+};++var g_ledger: Ledger = .{};++fn dup(gpa: Allocator, s: []const u8) []u8 {+ return gpa.dupe(u8, s) catch &.{};+}++/// Record a freshly issued handle. Best-effort: a failed append still leaves+/// the live job in `g_agent_jobs`.+pub fn remember(gpa: Allocator, io: Io, id: u32, label: []const u8) void {+ g_ledger.mutex.lockUncancelable(io);+ defer g_ledger.mutex.unlock(io);+ if (g_ledger.find(id) != null) {+ if (id >= g_ledger.next_id) g_ledger.next_id = id + 1;+ return;+ }+ const e = gpa.create(Entry) catch return;+ e.* = .{ .id = id, .label = dup(gpa, label) };+ g_ledger.list.append(gpa, e) catch {+ gpa.free(e.label);+ gpa.destroy(e);+ return;+ };+ if (id >= g_ledger.next_id) g_ledger.next_id = id + 1;+}++/// Pump finished: keep the report so a later `agent_output` can replay it+/// after the live table is gone.+pub fn finish(gpa: Allocator, io: Io, id: u32, is_error: bool, result: []const u8, usage: AgentUsage) void {+ g_ledger.mutex.lockUncancelable(io);+ defer g_ledger.mutex.unlock(io);+ const e = g_ledger.find(id) orelse return;+ if (e.result.len > 0) gpa.free(e.result);+ e.result = dup(gpa, result);+ e.is_error = is_error;+ e.usage = usage;+ e.done = true;+ e.interrupted = false;+}++/// Still-running handles cannot be reattached after a process death or a+/// reap. Mark them so `agent_output` names the interruption.+pub fn markRunningInterrupted(io: Io) void {+ g_ledger.mutex.lockUncancelable(io);+ defer g_ledger.mutex.unlock(io);+ for (g_ledger.list.items) |e| {+ if (!e.done) e.interrupted = true;+ }+}++pub fn missingText(gpa: Allocator, id: u32, interrupted: bool, label: []const u8) ![]u8 {+ if (interrupted) {+ if (label.len > 0)+ return std.fmt.allocPrint(gpa, "background agent {d} ({s}) started, then the parent turn was interrupted — it is no longer running in this process. Re-launch with subagent run_in_background:true if the work is still needed.", .{ id, label });+ return std.fmt.allocPrint(gpa, "background agent {d} started, then the parent turn was interrupted — it is no longer running in this process. Re-launch with subagent run_in_background:true if the work is still needed.", .{id});+ }+ return std.fmt.allocPrint(gpa, "no background agent {d} — it may never have started; subagent with run_in_background:true returns the id when it launches", .{id});+}++/// `agent_output` when the live pump table has no row. Replays a finished+/// report from the ledger, or names an interrupted launch, or the original+/// "never started" text when we never issued that id.+pub fn missing(gpa: Allocator, io: Io, id: u32) !ToolOutput {+ g_ledger.mutex.lockUncancelable(io);+ defer g_ledger.mutex.unlock(io);+ const e = g_ledger.find(id) orelse {+ return .{ .text = try missingText(gpa, id, false, ""), .is_error = true };+ };+ if (e.done) {+ const text = try agentStatusText(gpa, id, true, e.is_error, e.usage, e.result);+ return .{ .text = text, .is_error = e.is_error };+ }+ return .{ .text = try missingText(gpa, id, true, e.label), .is_error = true };+}++pub fn writeFields(s: *std.json.Stringify, io: Io) !void {+ g_ledger.mutex.lockUncancelable(io);+ defer g_ledger.mutex.unlock(io);+ try s.objectField("background_agents");+ try s.beginArray();+ for (g_ledger.list.items) |e| {+ try s.beginObject();+ try s.objectField("id");+ try s.write(e.id);+ try s.objectField("label");+ try s.write(e.label);+ try s.objectField("done");+ try s.write(e.done);+ try s.objectField("is_error");+ try s.write(e.is_error);+ try s.objectField("interrupted");+ try s.write(e.interrupted or !e.done);+ try s.objectField("result");+ try s.write(e.result);+ try s.objectField("duration_ms");+ try s.write(e.usage.duration_ms);+ try s.objectField("tool_calls");+ try s.write(e.usage.tool_calls);+ try s.endObject();+ }+ try s.endArray();+}++pub fn mixFingerprint(f: anytype) void {+ f.num(g_ledger.list.items.len);+ f.num(g_ledger.next_id);+ for (g_ledger.list.items) |e| {+ f.num(e.id);+ f.flag(e.done);+ f.flag(e.interrupted);+ f.num(e.result.len);+ }+}++/// Resume: restore reports we can replay, and treat leftover running rows as+/// interrupted (pumps do not survive a new process). Advances `next_id` so+/// a later spawn does not reuse a handle from the saved turn.+pub fn restore(gpa: Allocator, io: Io, v: ?Value) void {+ const arr = if (v) |val| (if (val == .array) val.array else return) else return;+ g_ledger.mutex.lockUncancelable(io);+ defer g_ledger.mutex.unlock(io);+ for (arr.items) |item| {+ if (item != .object) continue;+ const obj = item.object;+ const id_v = obj.get("id") orelse continue;+ if (id_v != .integer or id_v.integer < 1 or id_v.integer > std.math.maxInt(u32)) continue;+ const id: u32 = @intCast(id_v.integer);+ if (g_ledger.find(id) != null) {+ if (id >= g_ledger.next_id) g_ledger.next_id = id + 1;+ continue;+ }+ const label = if (obj.get("label")) |x| (if (x == .string) x.string else "") else "";+ const result = if (obj.get("result")) |x| (if (x == .string) x.string else "") else "";+ const done = if (obj.get("done")) |x| (x == .bool and x.bool) else false;+ const is_err = if (obj.get("is_error")) |x| (x == .bool and x.bool) else false;+ const interrupted = !done or (if (obj.get("interrupted")) |x| (x == .bool and x.bool) else false);+ const e = gpa.create(Entry) catch continue;+ e.* = .{+ .id = id,+ .label = dup(gpa, label),+ .done = done,+ .is_error = is_err,+ .interrupted = interrupted,+ .result = dup(gpa, result),+ .usage = .{+ .duration_ms = intUsage64(obj, "duration_ms"),+ .tool_calls = intUsage(obj, "tool_calls"),+ },+ };+ g_ledger.list.append(gpa, e) catch {+ gpa.free(e.label);+ gpa.free(e.result);+ gpa.destroy(e);+ continue;+ };+ if (id >= g_ledger.next_id) g_ledger.next_id = id + 1;+ }+}++pub fn nextId() u32 {+ return g_ledger.next_id;+}++fn intUsage(obj: std.json.ObjectMap, field: []const u8) u32 {+ const v = obj.get(field) orelse return 0;+ if (v != .integer or v.integer < 0) return 0;+ return @intCast(@min(v.integer, std.math.maxInt(u32)));+}++fn intUsage64(obj: std.json.ObjectMap, field: []const u8) u64 {+ const v = obj.get(field) orelse return 0;+ if (v != .integer or v.integer < 0) return 0;+ return @intCast(v.integer);+}++pub fn reset(gpa: Allocator) void {+ for (g_ledger.list.items) |e| {+ gpa.free(e.label);+ gpa.free(e.result);+ gpa.destroy(e);+ }+ g_ledger.list.deinit(gpa);+ g_ledger = .{};+}++test "#753: missing names an interrupted launch, not 'never started'" {+ const gpa = std.testing.allocator;+ const io = std.testing.io;+ reset(gpa);+ defer reset(gpa);++ remember(gpa, io, 3, "review auth");+ const out = try missing(gpa, io, 3);+ defer gpa.free(out.text);+ try std.testing.expect(out.is_error);+ try std.testing.expect(std.mem.indexOf(u8, out.text, "interrupted") != null);+ try std.testing.expect(std.mem.indexOf(u8, out.text, "review auth") != null);+ try std.testing.expect(std.mem.indexOf(u8, out.text, "may never have started") == null);++ const unknown = try missing(gpa, io, 99);+ defer gpa.free(unknown.text);+ try std.testing.expect(std.mem.indexOf(u8, unknown.text, "may never have started") != null);+}++test "#753: a finished ledger row replays the report after the live table is gone" {+ const gpa = std.testing.allocator;+ const io = std.testing.io;+ reset(gpa);+ defer reset(gpa);++ remember(gpa, io, 1, "scan");+ finish(gpa, io, 1, false, "found three files", .{ .duration_ms = 40, .tool_calls = 2 });+ const out = try missing(gpa, io, 1);+ defer gpa.free(out.text);+ try std.testing.expect(!out.is_error);+ try std.testing.expect(std.mem.indexOf(u8, out.text, "completed") != null);+ try std.testing.expect(std.mem.indexOf(u8, out.text, "found three files") != null);+}++test "#753: restore marks leftover running rows interrupted and advances next_id" {+ const gpa = std.testing.allocator;+ const io = std.testing.io;+ reset(gpa);+ defer reset(gpa);++ const parsed = try std.json.parseFromSlice(Value, gpa,+ \\[{"id":2,"label":"left","done":false,"result":""},{"id":5,"label":"done","done":true,"result":"ok"}]+ , .{});+ defer parsed.deinit();+ restore(gpa, io, parsed.value);++ const running = try missing(gpa, io, 2);+ defer gpa.free(running.text);+ try std.testing.expect(std.mem.indexOf(u8, running.text, "interrupted") != null);++ const done = try missing(gpa, io, 5);+ defer gpa.free(done.text);+ try std.testing.expect(std.mem.indexOf(u8, done.text, "ok") != null);++ try std.testing.expectEqual(@as(u32, 6), g_ledger.next_id);+}++test "missingText: interrupted vs never-started wording" {+ const gpa = std.testing.allocator;+ const gone = try missingText(gpa, 4, true, "audit");+ defer gpa.free(gone);+ try std.testing.expect(std.mem.indexOf(u8, gone, "agent 4") != null);+ try std.testing.expect(std.mem.indexOf(u8, gone, "audit") != null);+ const never = try missingText(gpa, 4, false, "");+ defer gpa.free(never);+ try std.testing.expect(std.mem.indexOf(u8, never, "may never have started") != null);+}diff --git a/src/subagent_tests.zig b/src/subagent_tests.zigindex 36b68f9d..91249f41 100644--- a/src/subagent_tests.zig+++ b/src/subagent_tests.zig@@ -97,3 +97,39 @@ test "agentStatusText: composes with isolation:\"worktree\" — a kept-worktreetry std.testing.expect(std.mem.indexOf(u8, out, "[worktree kept (has changes) — path:") != null);try std.testing.expect(std.mem.indexOf(u8, out, "branch: graff/agents/sa-001-aa11") != null);}++test "admitOneLocked: admits up to the cap, queues the rest, FIFO order (#276 P0-3 design point 6)" {+ const gpa = std.testing.allocator;+ var registry: subagent.AgentJobs = .{};+ defer registry.list.deinit(gpa);++ var stub_jobs: [subagent.max_concurrent_background_agents + 3]subagent.AgentJob = undefined;+ for (&stub_jobs, 0..) |*j, i| j.* = .{+ .id = @intCast(i + 1),+ .label = @constCast(""),+ .prompt = @constCast(""),+ .niche = @constCast(""),+ .isolation = .shared_cwd,+ .isolation_fallback = false,+ .ctx = undefined,+ };+ for (&stub_jobs) |*j| try registry.list.append(gpa, j);++ var admitted_order: [stub_jobs.len]u32 = undefined;+ var n: usize = 0;+ while (subagent.admitOneLocked(®istry)) |j| : (n += 1) admitted_order[n] = j.id;++ try std.testing.expectEqual(@as(usize, subagent.max_concurrent_background_agents), n);+ try std.testing.expectEqual(subagent.max_concurrent_background_agents, registry.active);+ for (admitted_order[0..n], 1..) |id, expect| try std.testing.expectEqual(@as(u32, @intCast(expect)), id);++ var still_queued: usize = 0;+ for (stub_jobs) |j| if (!j.admitted) {+ still_queued += 1;+ };+ try std.testing.expectEqual(stub_jobs.len - n, still_queued);++ registry.active -= 1;+ const next = subagent.admitOneLocked(®istry).?;+ try std.testing.expectEqual(@as(u32, subagent.max_concurrent_background_agents + 1), next.id);+}diff --git a/src/test_hooks.zig b/src/test_hooks.zigindex 29a1ed19..949212cc 100644--- a/src/test_hooks.zig+++ b/src/test_hooks.zig@@ -48,6 +48,7 @@ const native_fold = @import("native_fold.zig");const edit_batch = @import("edit_batch.zig");// Moved off subagent.zig, which is at the 600-line cap.const subagent_tests = @import("subagent_tests.zig");+const subagent_ledger = @import("subagent_ledger.zig"); // #753: handle ledger tests// Bench score/cost priors → derived tier ladders (.harness/bench.json).const bench_priors = @import("bench_priors.zig");const bench_priors_tests = @import("bench_priors_tests.zig");@@ -249,6 +250,7 @@ test {_ = native_fold;_ = edit_batch;_ = subagent_tests;+ _ = subagent_ledger;_ = bench_priors;_ = bench_priors_tests;_ = route_policy;