Skip to content

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

Python

Fail fast on shutdown-fixture stalls with renderer/backend/worker forensics

Cursor Agentfe994bdde42b
diff --git a/apps/native/electron/smoke-server-lifecycle.cjs b/apps/native/electron/smoke-server-lifecycle.cjs
index 1cc1be62..67418bce 100644
--- a/apps/native/electron/smoke-server-lifecycle.cjs
+++ b/apps/native/electron/smoke-server-lifecycle.cjs
@@ -1,23 +1,48 @@
const assert = require('node:assert/strict');
const fs = require('node:fs'), path = require('node:path');
const desktop = require('./test-desktop.cjs');
+const timeouts = require('./smoke-timeout.cjs');
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
exports.run = async ({win, backend}) => {
const output = process.env.GRAFF_SHUTDOWN_OUTPUT;
+ const workspace = process.env.GRAFF_CWD;
const js = source => win.webContents.executeJavaScript(source);
- // Phase markers: the next 180s hang shows which phase stalled, in CI output
+ // Phase markers: the next hang shows which phase stalled, in CI output
// and in the uploaded server-desktop dir.
const phase = name => {
console.log(`Shutdown fixture: ${name}`);
try { fs.writeFileSync(path.join(output, 'phase.txt'), `${name}\n`); } catch {}
};
+ // Every wait ends before the external watchdog (see smoke-timeout.cjs), and
+ // the timeout path dumps renderer + backend + model + worker state so the
+ // next stall names where the prompt stopped instead of dying as a generic
+ // "Test deadline exceeded" under SIGKILL.
+ const outer = timeouts.outerMs(), startedAt = Date.now();
+ const dumpTimeout = async (label, waitedMs) => {
+ phase(`timed out: ${label}`);
+ const record = { label, waitedMs, outerMs: outer, at: new Date().toISOString() };
+ try { record.guiText = await js('document.body.innerText'); } catch (error) { record.guiText = `<unreadable: ${error.message}>`; }
+ try {
+ record.backend = await (async () => {
+ const response = await fetch(`${backend.origin}/api/acp`, { signal: AbortSignal.timeout(5000) });
+ const body = await response.json();
+ return `sessions=${body.sessions ?? '?'} ok=${body.ok ?? response.ok}`;
+ })();
+ } catch (error) { record.backend = `<unreachable: ${error.message}>`; }
+ record.workers = timeouts.collectWorkerState(workspace);
+ record.model = timeouts.collectModelState(output);
+ const file = timeouts.slug(label);
+ try { fs.writeFileSync(path.join(output, `timeout-${file}.json`), JSON.stringify(record, null, 2)); } catch {}
+ try { fs.writeFileSync(path.join(output, 'timeout-gui-text.txt'), record.guiText.slice(0, 20000)); } catch {}
+ try { fs.writeFileSync(path.join(output, 'timeout.png'), (await win.webContents.capturePage()).toPNG()); } catch {}
+ console.log(timeouts.formatTimeoutSummary({ label, elapsedMs: waitedMs, outerMs: outer,
+ backend: record.backend, workers: record.workers, model: record.model, guiChars: record.guiText.length }));
+ };
const until = async (condition, label) => {
- // Outer Electron budget is 180s; 30s here lost to CI scheduling on the
- // scripted ACP turn (listener + HTTP check + completion text).
- const budget = Number(process.env.GRAFF_TEST_TIMEOUT_MS);
- const ms = Number.isFinite(budget) && budget >= 10000 ? Math.min(budget, 180000) : 90000;
+ const ms = timeouts.phaseBudget(label, outer, Date.now() - startedAt);
const end = Date.now() + ms;
while (Date.now() < end) { if (await condition()) return; await sleep(50); }
+ await dumpTimeout(label, ms);
throw Error(`Shutdown fixture timed out: ${label}`);
};
await until(() => js(`!!document.querySelector('[data-workspace-ready="true"] textarea[aria-label="Prompt"]')`), 'composer');
@@ -39,7 +64,6 @@ exports.run = async ({win, backend}) => {
await until(() => js(`document.body.innerText.includes('job 1 pinned')`), 'explicit user pin');
phase('explicit user pin');
}
- const workspace = process.env.GRAFF_CWD;
const listener = JSON.parse(fs.readFileSync(path.join(workspace,'listener.json'),'utf8'));
const records = fs.readdirSync(path.join(process.env.HOME,'.codegraff/jobs')).map(name => JSON.parse(fs.readFileSync(path.join(process.env.HOME,'.codegraff/jobs',name),'utf8')));
assert.equal(records.length, 1);
diff --git a/apps/native/electron/smoke-timeout.cjs b/apps/native/electron/smoke-timeout.cjs
new file mode 100644
index 00000000..50b20cf1
--- /dev/null
+++ b/apps/native/electron/smoke-timeout.cjs
@@ -0,0 +1,101 @@
+// Fail-fast budgets + timeout forensics for the server-lifecycle smoke.
+//
+// `until()` used to share the outer Electron budget (180s), so the external
+// watchdog SIGKILLed the process group before `until` could throw: CI showed a
+// generic "Test deadline exceeded" with no GUI/backend/worker state. Every
+// wait below now ends before the watchdog, and the timeout path dumps what
+// the renderer, the backend, the scripted model, and the workers were doing.
+const fs = require('node:fs'), path = require('node:path');
+
+/** The outer `runBounded` budget this Electron run lives under. Lenient here:
+// the spawner already validated the variable; an absent/invalid value means
+// a hand run, which gets the spawner's own default. */
+function outerMs(env = process.env) {
+ const n = Number(env.GRAFF_TEST_TIMEOUT_MS ?? 300000);
+ if (!Number.isFinite(n) || n < 1000 || n > 900000) return 300000;
+ return n;
+}
+
+/** Per-phase wait bound. Long poles end early enough that the timeout dump
+// and a clean `app.exit(1)` land before the watchdog SIGTERM: the scripted
+// turn lands in ~3s, so outer-30s keeps 50x headroom while never racing. */
+function phaseBudget(label, outer = outerMs(), elapsedMs = 0) {
+ switch (label) {
+ case 'composer': return 90000;
+ case 'agent completion': return Math.max(30000, outer - 30000);
+ case 'explicit user pin': return 60000;
+ case 'production backend and worker shutdown':
+ return Math.max(15000, outer - elapsedMs - 10000);
+ default: return 90000;
+ }
+}
+
+function slug(label) {
+ return label.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 48) || 'phase';
+}
+
+function tailText(text, maxChars) {
+ if (typeof text !== 'string' || text.length <= maxChars) return text ?? '';
+ return text.slice(text.length - maxChars);
+}
+
+/** One line per worker trajectory: how far each `graff acp` child got. A run
+// stuck post-`recipe` with no `prompt`/`turn` never received its prompt. */
+function collectWorkerState(workspaceDir) {
+ const trajectories = path.join(workspaceDir, '.graff', 'trajectories');
+ const behavior = path.join(workspaceDir, '.graff', 'behavior');
+ const runs = [];
+ try {
+ const files = fs.readdirSync(trajectories).filter(name => name.endsWith('.jsonl')).slice(0, 12);
+ for (const name of files) {
+ const lines = fs.readFileSync(path.join(trajectories, name), 'utf8').split('\n').filter(Boolean);
+ let first = {}, last = {};
+ try { first = JSON.parse(lines[0] ?? '{}'); } catch {}
+ try { last = JSON.parse(lines[lines.length - 1] ?? '{}'); } catch {}
+ let finished = null;
+ try {
+ const behaviorLines = fs.readFileSync(path.join(behavior, name), 'utf8').split('\n').filter(Boolean);
+ const tail = JSON.parse(behaviorLines[behaviorLines.length - 1] ?? '{}');
+ if (tail.kind === 'run_finished') finished = tail.status ?? true;
+ } catch {}
+ runs.push({ run: name.replace(/\.jsonl$/, ''), pid: first.pid ?? null, lines: lines.length,
+ lastKind: last.kind ?? null, lastEv: last.ev ?? null, finished });
+ }
+ } catch (error) {
+ return { error: error.message };
+ }
+ return { count: runs.length, runs };
+}
+
+/** Scripted-model and backend tails: did any request reach the model, and
+// what was the backend's last word. All reads are best-effort; a missing
+// file is itself evidence (no `requests.json` means no model call). */
+function collectModelState(outputDir) {
+ const state = {};
+ try { state.modelLogTail = tailText(fs.readFileSync(path.join(outputDir, 'model.log'), 'utf8'), 2000); }
+ catch (error) { state.modelLogTail = `<unreadable: ${error.message}>`; }
+ try {
+ const raw = fs.readFileSync(path.join(outputDir, 'requests.json'), 'utf8');
+ state.requests = { bytes: raw.length, count: JSON.parse(raw).length };
+ } catch (error) {
+ state.requests = fs.existsSync(path.join(outputDir, 'requests.json'))
+ ? { error: error.message } : { present: false };
+ }
+ try { state.serverLogTail = tailText(fs.readFileSync(path.join(outputDir, 'logs', 'server.log'), 'utf8'), 4000); }
+ catch (error) { state.serverLogTail = `<unreadable: ${error.message}>`; }
+ return state;
+}
+
+/** One compact block for the CI log; the full record goes to timeout-*.json. */
+function formatTimeoutSummary({ label, elapsedMs, outerMs: outer, backend, workers, model, guiChars }) {
+ const workerLine = workers.error ? `workers=<${workers.error}>`
+ : `workers=${workers.count}${workers.runs.map(run => ` ${run.run.slice(0, 8)}:${run.lastKind ?? run.lastEv ?? '?'}${run.finished ? '(done)' : ''}`).join(',')}`;
+ const requestLine = model.requests.present === false ? 'requests=absent'
+ : model.requests.count !== undefined ? `requests=${model.requests.count}` : `requests=<${model.requests.error ?? '?'}>`;
+ return [
+ `Shutdown fixture timeout: ${label} (waited ${elapsedMs}ms of ${outer}ms outer)`,
+ `Shutdown dump: backend=${backend} ${workerLine} ${requestLine} guiChars=${guiChars}`,
+ ].join('\n');
+}
+
+module.exports = { outerMs, phaseBudget, slug, tailText, collectWorkerState, collectModelState, formatTimeoutSummary };
diff --git a/apps/native/electron/smoke-timeout.test.cjs b/apps/native/electron/smoke-timeout.test.cjs
new file mode 100644
index 00000000..0263f984
--- /dev/null
+++ b/apps/native/electron/smoke-timeout.test.cjs
@@ -0,0 +1,103 @@
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs'), os = require('node:os'), path = require('node:path');
+const { outerMs, phaseBudget, slug, tailText, collectWorkerState, collectModelState, formatTimeoutSummary } = require('./smoke-timeout.cjs');
+
+test('outer budget mirrors the spawner validation, defaulting hand runs', () => {
+ assert.equal(outerMs({ GRAFF_TEST_TIMEOUT_MS: '180000' }), 180000);
+ assert.equal(outerMs({}), 300000);
+ assert.equal(outerMs({ GRAFF_TEST_TIMEOUT_MS: 'soon' }), 300000);
+ assert.equal(outerMs({ GRAFF_TEST_TIMEOUT_MS: '500' }), 300000);
+});
+
+test('waits end before the watchdog instead of racing it', () => {
+ assert.equal(phaseBudget('composer', 180000, 0), 90000);
+ assert.equal(phaseBudget('agent completion', 180000, 0), 150000);
+ assert.equal(phaseBudget('agent completion', 60000, 0), 30000);
+ assert.equal(phaseBudget('explicit user pin', 180000, 0), 60000);
+ assert.equal(phaseBudget('production backend and worker shutdown', 180000, 5000), 165000);
+ assert.equal(phaseBudget('production backend and worker shutdown', 180000, 175000), 15000);
+ assert.equal(phaseBudget('unknown phase', 180000, 0), 90000);
+});
+
+test('timeout artifacts get stable short names', () => {
+ assert.equal(slug('agent completion'), 'agent-completion');
+ assert.equal(slug('production backend and worker shutdown'), 'production-backend-and-worker-shutdown');
+});
+
+test('tails keep the end of long logs', () => {
+ assert.equal(tailText('abcdef', 4), 'cdef');
+ assert.equal(tailText('ab', 4), 'ab');
+});
+
+function fixture() {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'graff-smoke-timeout-'));
+ const trajectories = path.join(root, 'workspace', '.graff', 'trajectories');
+ const behavior = path.join(root, 'workspace', '.graff', 'behavior');
+ fs.mkdirSync(trajectories, { recursive: true });
+ fs.mkdirSync(behavior, { recursive: true });
+ // A worker stalled post-recipe, and one that finished its turn.
+ fs.writeFileSync(path.join(trajectories, 'aa.jsonl'),
+ '{"kind":"session","pid":11,"unix_ms":1000}\n{"kind":"playbook","t":3}\n{"kind":"recipe","t":64}\n');
+ fs.writeFileSync(path.join(behavior, 'aa.jsonl'), '{"kind":"run_started","seq":1}\n');
+ fs.writeFileSync(path.join(trajectories, 'bb.jsonl'),
+ '{"kind":"session","pid":22,"unix_ms":1000}\n{"kind":"prompt","t":300}\n{"kind":"turn","t":350}\n');
+ fs.writeFileSync(path.join(behavior, 'bb.jsonl'), '{"kind":"run_started","seq":1}\n{"kind":"run_finished","seq":2,"status":"closed"}\n');
+ const output = path.join(root, 'output');
+ fs.mkdirSync(path.join(output, 'logs'), { recursive: true });
+ fs.writeFileSync(path.join(output, 'model.log'), 'scripted model on 127.0.0.1:1234\n');
+ fs.writeFileSync(path.join(output, 'requests.json'), JSON.stringify([{ messages: [] }, { messages: [] }]));
+ fs.writeFileSync(path.join(output, 'logs', 'server.log'), 'ready\n');
+ return { root, workspace: path.join(root, 'workspace'), output };
+}
+
+test('worker state names how far each trajectory got', () => {
+ const { root, workspace } = fixture();
+ try {
+ const state = collectWorkerState(workspace);
+ assert.equal(state.count, 2);
+ const stalled = state.runs.find(run => run.run === 'aa');
+ assert.equal(stalled.lastKind, 'recipe');
+ assert.equal(stalled.finished, null);
+ const done = state.runs.find(run => run.run === 'bb');
+ assert.equal(done.lastKind, 'turn');
+ assert.equal(done.finished, 'closed');
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test('worker state survives a missing evidence dir', () => {
+ const state = collectWorkerState(path.join(os.tmpdir(), 'graff-smoke-timeout-missing'));
+ assert.match(state.error, /ENOENT/);
+});
+
+test('model state reports requests and tails', () => {
+ const { root, output } = fixture();
+ try {
+ const state = collectModelState(output);
+ assert.equal(state.requests.count, 2);
+ assert.match(state.modelLogTail, /scripted model on/);
+ assert.equal(state.serverLogTail, 'ready\n');
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test('model state marks an absent requests file', () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'graff-smoke-timeout-'));
+ try {
+ const state = collectModelState(root);
+ assert.equal(state.requests.present, false);
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test('the console summary fits the stall on two lines', () => {
+ const summary = formatTimeoutSummary({ label: 'agent completion', elapsedMs: 150000, outerMs: 180000,
+ backend: 'sessions=1', workers: { count: 1, runs: [{ run: 'aabbccdd', lastKind: 'recipe', finished: null }] },
+ model: { requests: { present: false } }, guiChars: 42 });
+ assert.match(summary, /Shutdown fixture timeout: agent completion \(waited 150000ms of 180000ms outer\)/);
+ assert.match(summary, /backend=sessions=1 workers=1 aabbccdd:recipe requests=absent guiChars=42/);
+});
diff --git a/apps/native/lib/acp-prompt-stream.test.ts b/apps/native/lib/acp-prompt-stream.test.ts
index ab04965d..65930a83 100644
--- a/apps/native/lib/acp-prompt-stream.test.ts
+++ b/apps/native/lib/acp-prompt-stream.test.ts
@@ -3,7 +3,7 @@ import assert from "node:assert/strict";
import { EventEmitter } from "node:events";
import { PassThrough } from "node:stream";
import { AcpTransport } from "./acp-transport";
-import { createPromptStream } from "./acp-prompt-stream";
+import { createPromptStream, promptTimeoutMs } from "./acp-prompt-stream";
import { prompt } from "./acp-client";
import { applyAcpUpdate, emptyTurn, finishAcpTurn } from "./acp";
import { turnActivity } from "./turn-activity";
@@ -90,6 +90,42 @@ for (const outcome of ["end_turn", "cancelled", "error", "exit"] as const) {
}
}
+test("fixture runs cap the prompt stream below the outer watchdog; production keeps the day", () => {
+ const saved = process.env.GRAFF_TEST_TIMEOUT_MS;
+ try {
+ delete process.env.GRAFF_TEST_TIMEOUT_MS;
+ assert.equal(promptTimeoutMs(), 24 * 60 * 60 * 1000);
+ process.env.GRAFF_TEST_TIMEOUT_MS = "180000";
+ assert.equal(promptTimeoutMs(), 120000);
+ process.env.GRAFF_TEST_TIMEOUT_MS = "soon";
+ assert.equal(promptTimeoutMs(), 24 * 60 * 60 * 1000);
+ process.env.GRAFF_TEST_TIMEOUT_MS = "60000";
+ assert.equal(promptTimeoutMs(), 24 * 60 * 60 * 1000);
+ } finally {
+ if (saved === undefined) delete process.env.GRAFF_TEST_TIMEOUT_MS;
+ else process.env.GRAFF_TEST_TIMEOUT_MS = saved;
+ }
+});
+
+test("the capped timeout reaches the transport", async () => {
+ const saved = process.env.GRAFF_TEST_TIMEOUT_MS;
+ process.env.GRAFF_TEST_TIMEOUT_MS = "180000";
+ try {
+ let seen = 0;
+ const transport = { request: (_method: string, _params: unknown, timeout: number) => {
+ seen = timeout;
+ return new Promise(() => {});
+ } };
+ const { stream } = createPromptStream(transport, {}, () => {});
+ await new Promise<void>(resolve => setImmediate(resolve));
+ assert.equal(seen, 120000);
+ await stream.cancel().catch(() => {});
+ } finally {
+ if (saved === undefined) delete process.env.GRAFF_TEST_TIMEOUT_MS;
+ else process.env.GRAFF_TEST_TIMEOUT_MS = saved;
+ }
+});
+
test("closing a live HTTP reader cancels once, and later failure cannot write into it", async () => {
const child = Object.assign(new EventEmitter(), { stdout: new PassThrough(), stdin: new PassThrough() });
const transport = new AcpTransport(child as never);
diff --git a/apps/native/lib/acp-prompt-stream.ts b/apps/native/lib/acp-prompt-stream.ts
index e0b602c6..2e45bece 100644
--- a/apps/native/lib/acp-prompt-stream.ts
+++ b/apps/native/lib/acp-prompt-stream.ts
@@ -1,5 +1,17 @@
import type { AcpTransport } from "./acp-transport";
+/** Production turns run for hours; GUI fixtures script seconds-long turns. When the
+ * fixture's outer budget is visible, a worker silent past (outer - 60s) is hung,
+ * and the HTTP stream must error so the renderer shows failure instead of hanging
+ * until the external watchdog SIGKILLs the group with no diagnostics. The smoke's
+ * own agent-completion bound (outer - 30s) then captures that error in its dump. */
+export function promptTimeoutMs(): number {
+ const day = 24 * 60 * 60 * 1000;
+ const capped = Number(process.env.GRAFF_TEST_TIMEOUT_MS) - 60_000;
+ if (!Number.isFinite(capped) || capped < 30_000) return day;
+ return Math.min(day, capped);
+}
+
/** An ACP error is a terminal RPC reply, not a broken HTTP response. Erroring
* the controller discards queued output and replaces the reason with the
* browser's generic network error. Close on the terminal line itself so reader
@@ -19,7 +31,7 @@ export function createPromptStream(transport: Pick<AcpTransport, "request">, par
controller.close();
}
};
- pending = transport.request("session/prompt", params, 24 * 60 * 60 * 1000, send);
+ pending = transport.request("session/prompt", params, promptTimeoutMs(), send);
// The prompt is now written before any subsequent cancel on this
// transport. Flush readiness immediately: waiting for model output
// makes steering unavailable throughout a slow first response.
diff --git a/src/acp_live_turn.zig b/src/acp_live_turn.zig
index f100f646..389d2a23 100644
--- a/src/acp_live_turn.zig
+++ b/src/acp_live_turn.zig
@@ -32,6 +32,10 @@ pub const LiveTurn = struct {
pub fn run(ctx: *anyopaque, arena: Allocator, text: []const u8) anyerror![]const u8 {
const self: *LiveTurn = @ptrCast(@alignCast(ctx));
+ // Receipt marker before any dedup/turn work: a worker that logged its
+ // recipe but never this line never received its prompt — the stall is
+ // upstream (client dispatch / bootstrap / transport), not in the turn.
+ if (self.root.tracer) |tr| tr.note("acp_prompt", self.session_id);
agent_mod.Agent.prepareRootTurn(); // #753: a prior stream cancel must not steal the continuation
if (self.inbox) |inbox| inbox.begin();
defer if (self.inbox) |inbox| inbox.end();
@@ -124,3 +128,50 @@ pub const LiveTurn = struct {
return final;
}
};
+
+test "session/prompt receipt is traced even when dedup skips the turn" {
+ const dedup = @import("turn_dedup.zig");
+ dedup.resetForTest();
+ defer dedup.resetForTest();
+ @import("side_steer.zig").resetForTest();
+ defer @import("side_steer.zig").resetForTest();
+ const interactive = @import("subagent_interactive.zig");
+ const was_notice = interactive.line_notice;
+ interactive.line_notice = false;
+ defer interactive.line_notice = was_notice;
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var aw: Io.Writer.Allocating = .init(a);
+ defer aw.deinit();
+ var tracer: trace.Tracer = .{
+ .io = std.testing.io,
+ .gpa = std.testing.allocator,
+ .out = &aw.writer,
+ .start = Io.Timestamp.now(std.testing.io, .awake),
+ };
+ var root: agent_mod.Agent = .{
+ .gpa = std.testing.allocator,
+ .arena = a,
+ .io = std.testing.io,
+ .client = undefined,
+ .provider = .{ .id = "xai", .kind = .openai, .auth = .bearer, .url = "", .api_key = "k", .model = "grok-4.6", .context = 100_000 },
+ .messages = std.json.Array.init(a),
+ .sub = false,
+ .label = "test",
+ .out = null,
+ .tracer = &tracer,
+ };
+ try root.messages.append(try messages.textMessage(a, "user", "hi"));
+ var keys: provider_mod.Keys = .{ .values = @splat(null) };
+ var out_buf: [1024]u8 = undefined;
+ var out: Io.Writer = .fixed(&out_buf);
+ var live: LiveTurn = .{ .root = &root, .keys = &keys, .out = &out, .session_id = "s1" };
+ // A back-to-back duplicate skips the model turn entirely — the receipt
+ // marker must already be in the trace, or a skipped prompt is
+ // indistinguishable from one the worker never received.
+ try std.testing.expectEqualStrings("", try LiveTurn.run(&live, a, "hi"));
+ const logged = aw.writer.buffered();
+ try std.testing.expect(std.mem.indexOf(u8, logged, "\"acp_prompt\"") != null);
+ try std.testing.expect(std.mem.indexOf(u8, logged, "s1") != null);
+}
diff --git a/src/turn_dedup.zig b/src/turn_dedup.zig
index 0251e53c..b6eabf12 100644
--- a/src/turn_dedup.zig
+++ b/src/turn_dedup.zig
@@ -47,6 +47,10 @@ pub fn enqueue(root: *Agent, arena: Allocator, out: ?*Io.Writer, text: []const u
if (messages.trailingUserIs(root.messages.items, text)) {
hits +|= 1;
if (hits >= max_replays) {
+ // A skipped turn runs no model call and records no trajectory
+ // nodes; without this note it is invisible next to a prompt the
+ // worker never received at all.
+ if (root.tracer) |tr| tr.note("turn_dedup", "stuck replay");
if (out) |w| {
w.print("{s}{s}{s}\n", .{ style.yellow, stuck_text, style.reset }) catch {};
w.flush() catch {};
@@ -55,6 +59,7 @@ pub fn enqueue(root: *Agent, arena: Allocator, out: ?*Io.Writer, text: []const u
}
return .stuck;
}
+ if (root.tracer) |tr| tr.note("turn_dedup", "skipped duplicate");
return .skipped;
}
hits = 0;
@@ -132,3 +137,46 @@ test "#714: the same words after an assistant reply are a new ask" {
try std.testing.expect(!try enqueueOrSkip(&agent, a, null, "do a little work"));
try std.testing.expectEqual(@as(usize, 3), agent.messages.items.len);
}
+
+test "a skipped duplicate leaves a trace note instead of vanishing" {
+ resetForTest();
+ defer resetForTest();
+ @import("side_steer.zig").resetForTest();
+ defer @import("side_steer.zig").resetForTest();
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var aw: Io.Writer.Allocating = .init(a);
+ defer aw.deinit();
+ var tracer: @import("trace.zig").Tracer = .{
+ .io = std.testing.io,
+ .gpa = std.testing.allocator,
+ .out = &aw.writer,
+ .start = Io.Timestamp.now(std.testing.io, .awake),
+ };
+ var agent: Agent = .{
+ .gpa = std.testing.allocator,
+ .arena = a,
+ .io = std.testing.io,
+ .client = undefined,
+ .provider = .{
+ .id = "xai",
+ .kind = .openai,
+ .auth = .bearer,
+ .url = "",
+ .api_key = "k",
+ .model = "grok-4.6",
+ .context = 100_000,
+ },
+ .messages = .init(a),
+ .sub = false,
+ .label = "test",
+ .out = null,
+ .tracer = &tracer,
+ };
+ try std.testing.expect(!try enqueueOrSkip(&agent, a, null, "Read SPEC.md"));
+ try std.testing.expect(try enqueueOrSkip(&agent, a, null, "Read SPEC.md"));
+ const logged = aw.writer.buffered();
+ try std.testing.expect(std.mem.indexOf(u8, logged, "\"turn_dedup\"") != null);
+ try std.testing.expect(std.mem.indexOf(u8, logged, "skipped duplicate") != null);
+}