Skip to content

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

Python
30.3 KB
Raw Blame
//! One isolated subagent run: provider selection, failure classification,
//! worktree lifecycle, usage emission, and trajectory recording.

const std = @import("std");
const Io = std.Io;
const Allocator = std.mem.Allocator;

const main_mod = @import("main.zig");
const Agent = @import("agent.zig").Agent;
pub const Provider = @import("provider.zig").Provider;
const route_policy = @import("route_policy.zig"); // #376 rung stratification
const util = @import("util.zig");
const goal_pacing = @import("goal_pacing.zig");
const playbook = @import("playbook.zig"); // #381/#383: the constraint + learned block every brief carries
const tools = @import("tools.zig");
const ToolCtx = tools.ToolCtx;
const ToolOutput = tools.ToolOutput;
const telemetry = @import("telemetry.zig");
const scoring = @import("scoring.zig");
const promptFingerprint = scoring.promptFingerprint;
const providerClass = scoring.providerClass;
const fleet = @import("fleet.zig");
const Isolation = fleet.Isolation;
const learning_privacy = @import("learning_privacy.zig");
const jobs = @import("jobs.zig");
const cards = @import("cards.zig");
const trace = @import("trace.zig");
const textMessage = @import("messages.zig").textMessage;
const protocol_seq = @import("protocol_seq.zig"); // #330: monotonic `seq` on every --json event
const subagent_retry = @import("subagent_retry.zig"); // bounded in-worker re-ask: the failover the root has and a worker did not

fn guiEmit(io: Io, ev: anytype) void {
    if (!main_mod.json_mode) return;
    const w = main_mod.g_out orelse return;
    main_mod.g_gui_mu.lockUncancelable(io);
    defer main_mod.g_gui_mu.unlock(io);
    // #330: one shared --json stream, one shared sequence — a pool-thread
    // subagent emit takes its id under the same lock as the root agent's.
    protocol_seq.writeEvent(w, ev) catch return;
    w.writeByte('\n') catch return;
    w.flush() catch return;
}

pub const FailKind = enum {
    quota,
    transport,
    model,
    invalid,
    auth,
    /// The shared model-call pool is dry (run_budget.RunBudgetExhausted).
    /// Distinct from `quota`, which is the PROVIDER refusing: this one is the
    /// harness's own ceiling, it is GLOBAL to the run, and no amount of
    /// waiting or retrying changes it — the next attempt is refused before it
    /// reaches the network, and is still charged for trying.
    budget_exhausted,
    cancelled,
    synthesis_limit,
    unknown,

    pub fn label(self: FailKind) []const u8 {
        return switch (self) {
            .quota => "quota/rate-limit",
            .transport => "transport",
            .model => "model-availability",
            .invalid => "invalid-arguments",
            .auth => "auth",
            .budget_exhausted => "model-call-budget",
            .cancelled => "cancelled",
            .synthesis_limit => "synthesis-limit",
            .unknown => "unknown",
        };
    }

    pub fn retrySafe(self: FailKind) bool {
        return switch (self) {
            .quota, .transport, .unknown => true,
            .model, .invalid, .auth, .budget_exhausted, .cancelled, .synthesis_limit => false,
        };
    }
};

/// The marker a budget-exhausted failure carries, so a workflow retry pass can
/// tell it apart from any other unretryable failure and abort the WHOLE pass
/// rather than skipping one task. Matches agent_request.zig's message text.
pub const budget_exhausted_marker = "model-call budget exhausted";

/// Did this failure come from the shared pool running dry? Read by the
/// workflow retry sites: the first one of these ends the pass, because every
/// sibling retry would be refused identically and each refusal still costs.
pub fn isBudgetExhausted(text: []const u8) bool {
    return util.indexOfIgnoreCase(text, budget_exhausted_marker) != null;
}

fn containsAnyCI(hay: []const u8, needles: []const []const u8) bool {
    for (needles) |n| if (util.indexOfIgnoreCase(hay, n) != null) return true;
    return false;
}

pub fn classifyFailure(err: anyerror, detail: ?[]const u8) FailKind {
    switch (err) {
        error.Interrupted, error.Canceled => return .cancelled,
        error.WorkflowSynthesisLimit => return .synthesis_limit,
        error.StreamStalled, error.StreamDropped => return .transport,
        else => {},
    }
    if (err == error.RunBudgetExhausted) return .budget_exhausted;
    const msg = detail orelse return .unknown;
    // Before every other arm, including the 5xx one: the harness's OWN pool
    // running dry says "budget" and "exhausted", and the words in that message
    // ("quota"-adjacent, and it names a limit) would otherwise classify it as
    // a provider rate limit and earn it a retry that cannot possibly succeed.
    if (isBudgetExhausted(msg)) return .budget_exhausted;
    // 5xx before everything: a server-side outage is the most common transient
    // failure there is, and "503 Service Unavailable" used to fall through to
    // the .model arm on the bare word "unavailable". That was harmless while
    // this classifier was advisory prose; once failureAllowsRetry made it
    // control flow it meant a whole fan-out stopped retrying an outage.
    if (containsAnyCI(msg, &.{ "500", "502", "503", "504", "service unavailable", "temporarily unavailable", "bad gateway", "gateway timeout", "internal server error", "overloaded_error" })) return .transport;
    if (containsAnyCI(msg, &.{ "network error", "stream stalled", "stream dropped", "timed out", "connection reset", "connection closed" })) return .transport;
    if (containsAnyCI(msg, &.{ "rate limit", "rate_limit", "quota", "429", "overloaded", "out of credits", "credits", "billing", "too many requests" })) return .quota;
    if (containsAnyCI(msg, &.{ "api key", "unauthorized", "expired", "authentication", "invalid_api_key", "401", "sign-in was rejected" })) return .auth;
    // "unavailable" must stay qualified: bare, it swallows every 5xx above.
    if (containsAnyCI(msg, &.{ "does not exist", "not found", "no such model", "decommission", "no longer", "model_not_found", "model unavailable", "model is unavailable", "404" })) return .model;
    if (containsAnyCI(msg, &.{ "context length", "context window", "invalid", "unsupported", "not supported", "must be", "too long", "400", "parameter", "max_tokens", "bad request" })) return .invalid;
    return .unknown;
}

/// Advisory text appended to a subagentFailure message when the classified
/// cause is transient (quota/transport/unknown) — the model sees this exact
/// string, and failureAllowsRetry below keys off it, so keep them in sync.
pub const retry_ok_note = "retry is likely safe — re-run the same task (after a short backoff for quota/transport)";
/// Advisory text appended when the cause is NOT transient (model/invalid/
/// auth) — retrying would just double the cost of a broken run for zero
/// chance of success. failureAllowsRetry keys off this exact string.
pub const retry_unsafe_note = "retry is NOT safe as-is — fix the cause first (switch model, correct arguments, or re-auth)";

/// The one text the parent reads when a worker dies. `attempts` is how many
/// asks this worker actually made (subagent_retry's bounded ladder), and it is
/// in the string on purpose: "failed before producing a report" left the
/// parent unable to tell a worker that was never really tried from one that
/// was tried three times and refused every time. Naming the count is the
/// honesty half of adding a retry at all.
///
/// It rides in the CLASS bracket, after the cause, not in the prefix. The
/// prefix is scarce: workflow.zig head-slices this text at fail_excerpt_cap
/// (200 chars) precisely because the cause sits immediately behind
/// "…failed before producing a report: ", so every character spent before the
/// colon is a character of real provider error deleted from the next phase's
/// {{prev}}. "failed after 3 attempts before producing a report:" cost ~17 of
/// them; this ordering keeps the count and the prefix.
pub fn subagentFailure(gpa: Allocator, sub_id: []const u8, err: anyerror, detail: ?[]const u8, attempts: u8) ToolOutput {
    const kind = classifyFailure(err, detail);
    const cause = if (kind == .cancelled or kind == .synthesis_limit) @errorName(err) else detail orelse @errorName(err);
    const retry = switch (kind) {
        .cancelled, .synthesis_limit => "retry is NOT safe as-is — the worker stopped; use the completed evidence without restarting it",
        else => if (kind.retrySafe()) retry_ok_note else retry_unsafe_note,
    };
    const text = std.fmt.allocPrint(
        gpa,
        "subagent {s} failed before producing a report: {s} [{s} failure, {d} {s}]. {s}",
        .{ sub_id, cause, kind.label(), attempts, subagent_retry.attemptsWord(attempts), retry },
    ) catch return .{ .is_error = true };
    return .{ .text = text, .is_error = true, .cancelled = kind == .cancelled };
}

/// Whether a workflow retry site should re-run a failed task. Failures that
/// went through subagentFailure carry retry_unsafe_note when the harness's
/// own classification (FailKind.retrySafe) already ruled retrying out — auth
/// or an invalid/unavailable model — so retrying the whole phase would only
/// double the cost of a broken run for zero chance of success. Any failure
/// text that did NOT come from subagentFailure (an empty report, an
/// isolation-setup failure) carries no marker and keeps retrying, since those
/// are exactly the transient cases retry exists for.
pub fn failureAllowsRetry(text: []const u8) bool {
    return std.mem.indexOf(u8, text, "retry is NOT safe as-is") == null;
}

pub fn childProvider(root: Provider, pinned: ?Provider, allow_cross_provider: bool) Provider {
    const child = pinned orelse return root;
    return if (std.mem.eql(u8, child.id, root.id) or allow_cross_provider) child else root;
}

/// Capability tier ("frontier" | "mid" | "small") of the model that ran variant
/// `i` of a workflow phase — the provider-class axis of the MAP-Elites cell.
///
/// `seat` is the PHASE's resolved provider (#376). It used to be derived from
/// `ctx` here, on the standing assumption that a phase always ran the session
/// default; route_phase.forPhase may now re-seat a whole phase, so the model
/// a variant actually ran on has to be passed in or every row this feeds would
/// name a model that never ran.
///
/// It is still the same value for every `i`, and that is the #290 property,
/// not an accident: a phase takes ONE seat for all of its workers, so
/// scoreVariants keeps ranking prompt variants that shared a configuration.
/// #292's per-spawn pins likewise still reach `subagent` only, never a phase
/// task or a pipeline stage. The lookup stays per-variant so that whenever a
/// finer grain does reach a phase, this pair of functions is the seam that has
/// to learn about it instead of a phase-level constant going stale.
pub fn variantProviderClass(seat: Provider, i: usize) []const u8 {
    _ = i; // phase-uniform by construction — route_phase.forPhase
    return scoring.providerClass(seat.model);
}

/// #376 — the routing STRATUM variant `i` was observed in: the resolved model
/// itself, not its capability bucket.
///
/// providerClass once bucketed gpt-5.6-sol/-terra/-luna identically as
/// "frontier" (the #291 gap, closed since), and a class stays coarser than a
/// model regardless — "frontier" pools sol with bare gpt-5.6 — so a
/// matched-tournament guard keyed on it was blind to a rung-only difference,
/// which made phase routing unsafe. Keyed on this it is not: a phase whose
/// variants somehow spanned two models is refused as unscoreable, and every
/// fitness row records the same value so a cross-run comparison can stratify
/// by it (fitness_strata.zig) rather than averaging over rungs.
pub fn variantStratum(seat: Provider, i: usize) []const u8 {
    _ = i;
    return route_policy.stratumOf(seat.model);
}

pub const AgentUsage = struct {
    duration_ms: u64 = 0,
    tool_calls: u32 = 0,
    context_tokens: u64 = 0,
    cache_read_tokens: u64 = 0,
};

const AgentUsageEvent = struct {
    type: []const u8 = "agent_usage",
    id: []const u8,
    ok: bool,
    duration_ms: u64,
    tool_calls: u32,
    context_tokens: u64,
    cache_read_tokens: u64,
};

pub fn agentUsageEvent(sub_id: []const u8, ok: bool, usage: AgentUsage) AgentUsageEvent {
    return .{
        .id = sub_id,
        .ok = ok,
        .duration_ms = usage.duration_ms,
        .tool_calls = usage.tool_calls,
        .context_tokens = usage.context_tokens,
        .cache_read_tokens = usage.cache_read_tokens,
    };
}

pub const SubRun = struct { output: ToolOutput, usage: AgentUsage };

/// `pin` (#292) is an already-resolved, provider-local per-spawn model
/// override — subagent_pin.forSpawn's answer for this one call. It replaces
/// the session-level worker choice for this child only; null keeps it. It is
/// deliberately a resolved Provider rather than a name: resolution (catalog
/// lookup, graceful fallback, provider locality) happens once at the call
/// site, so nothing here can fail a spawn on an unavailable pin.
///
/// `effort` is the same story on the reasoning axis (#292 follow-up):
/// forSpawn's resolved per-spawn/per-persona depth; null keeps the worker
/// default (medium — a child never inherits the root's /effort implicitly).
pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const u8, sys_override: ?[]const u8, niche: []const u8, isolation: Isolation, isolation_fallback: bool, pin: ?Provider, effort: ?main_mod.ReasoningEffort) !SubRun {
    const gpa = ctx.gpa;
    defer if (ctx.retained_worker) |state| state.release(ctx.io);
    if (ctx.run_budget) |budget| if (ctx.depth >= budget.max_depth) return .{
        .output = .{
            .text = try gpa.dupe(u8, "agent depth limit reached (max depth 1) — do this work in the current agent"),
            .is_error = true,
        },
        .usage = .{},
    };
    var arena_state = std.heap.ArenaAllocator.init(gpa);
    defer arena_state.deinit();
    const arena = arena_state.allocator();
    // #292: a resolved per-spawn/per-persona pin replaces the session-level
    // worker choice for this child. Already provider-local (see
    // subagent_pin), so the cross-provider consent check childProvider
    // enforces has nothing left to decide.
    const child_provider = pin orelse childProvider(ctx.provider, ctx.subagent_provider, ctx.subagent_cross_provider);

    var agent: Agent = .{
        .gpa = gpa,
        .arena = arena,
        .io = ctx.io,
        .client = ctx.client,
        .provider = child_provider,
        .messages = std.json.Array.init(arena),
        .sub = true,
        .worker_family = @import("subagent_retained.zig").family(ctx),
        .worker_id = if (ctx.retained_worker) |state| state.record.id else null,
        .feedback = ctx.subagent_feedback,
        .label = label,
        .out = null,
        .approvals = ctx.approvals,
        .registry = ctx.registry,
        .tracer = ctx.tracer,
        .run_budget = ctx.run_budget,
        .loop_deadline_ms = ctx.loop_deadline_ms, // a timed run's deadline reaches grandchildren too, not just depth 1
        .depth = ctx.depth + 1,
        .call_kind = if (std.mem.eql(u8, kind, "judge_task"))
            .judge
        else if (std.mem.eql(u8, kind, "workflow_retry"))
            .workflow_retry
        else
            .child,
        .sys_override = sys_override,
        // §2c: the judge is text-only. It ranks handed excerpts, so a toolset
        // only buys it the chance to go re-read the repo — which is where its
        // ~3 calls per score went. One judge, one call.
        .text_only = std.mem.eql(u8, kind, "judge_task"),
        .synthesis = .{ .enabled = ctx.synthesis and !std.mem.eql(u8, kind, "judge_task") },
        // #1360: an informational child still needs its read tools; it is
        // read-only, not tool-less.
        .read_only = @import("task_intent.zig").classify(prompt) == .informational,
        .reasoning = effort orelse .medium, // #292 follow-up: effort pin; unpinned workers keep the default depth, not the root's /effort
    };
    const sub_start = Io.Timestamp.now(ctx.io, .awake);
    if (sys_override) |so| if (telemetry.g_telem) |t| {
        if (fleet.promptIsPublic(so)) _ = learning_privacy.approveTemplate(ctx.io, so);
        t.countVariant();
        const child_fp = promptFingerprint(so);
        var parent_buf: [16]u8 = undefined;
        var parent_sha: []const u8 = "";
        if (niche.len > 0) if (fleet.agentTypePrompt(niche)) |ep| {
            parent_buf = promptFingerprint(ep);
            parent_sha = &parent_buf;
        };
        if (so.len <= telemetry.Telemetry.max_propose_text)
            t.fleetEvent("propose", niche, &child_fp, parent_sha, providerClass(agent.provider.model), "", 0, so)
        else if (ctx.tracer) |tr| tr.note("fleet", "propose skipped: genome > 64KB");
    };

    const ordinal = cards.g_subagent_seq.fetchAdd(1, .monotonic);
    var id_buf: [40]u8 = undefined;
    const sub_id = cards.subagentId(&id_buf, ordinal, label, prompt);
    const sprite = cards.subagentSprite(ordinal);
    cards.subagentLaunchCard(arena, sub_id, sprite, label, kind, prompt);
    var activity = @import("subagent_activity.zig").start(gpa, ctx.io, sub_id, label, prompt);
    defer if (activity) |*recorder| recorder.deinit();
    if (activity) |*recorder| {
        recorder.setModel(agent.provider.id, agent.provider.model);
        if (@import("subagent_activity.zig").interruptRequested(ctx.io, recorder.dir, sub_id)) {
            recorder.finish(false, "Interrupted.");
            return .{ .output = subagentFailure(gpa, sub_id, error.Interrupted, null, 0), .usage = .{} };
        }
        agent.sink = recorder.engineSink();
    }

    var wt: ?jobs.AgentWorktree = null;
    var isolation_note: []const u8 = "";
    var pool_seat = false;
    if (ctx.retained_worker != null and ctx.retained_worker.?.record.messages.len > 0) {
        agent.agent_cwd = ctx.retained_worker.?.record.cwd;
    } else if (isolation == .shared_cwd and ctx.agent_cwd != null) {
        agent.agent_cwd = ctx.agent_cwd;
    } else if (@import("experiment_pool.zig").claimSeat()) |seat| {
        agent.agent_cwd = seat.path;
        wt = .{ .path = seat.path, .branch = seat.branch, .base = seat.base };
        pool_seat = true;
    } else if (isolation == .worktree) {
        if (@import("agent_worktree.zig").agentWorktreeCreateAt(gpa, ctx.io, arena, sub_id, ctx.agent_cwd orelse ".")) |created| {
            wt = created;
        } else |err| {
            if (!isolation_fallback) return .{
                .output = .{ .text = try gpa.dupe(u8, jobs.isolationFailureText(err)), .is_error = true },
                .usage = .{},
            };
            isolation_note = "\n\n[note: isolation:\"worktree\" failed and fell back to the shared working tree — isolation_fallback:true allowed it]";
        }
        agent.agent_cwd = if (wt) |w| w.path else null;
    } else {
        agent.agent_cwd = ctx.agent_cwd;
    }

    // ACP v1's draft child-session scope is one foreground prompt. Detached
    // workers use a separate opted-in Graff notification and retain the
    // graff/agents inspection path after session/prompt returns.
    const acp_children = @import("acp_subagent_live.zig");
    const detached = ctx.subagent_feedback != null;
    const announce_child = acp_children.eligible(kind, ctx.depth, detached);
    const announced = announce_child and acp_children.announce(ctx.io, sub_id, label, prompt, ctx.parent_tool_call_id, agent.provider.id, agent.provider.model);
    const background_handle: ?acp_children.BackgroundHandle = if (detached and std.mem.eql(u8, kind, "subagent") and ctx.depth == 0 and ctx.parent_tool_call_id.len > 0)
        acp_children.announceBackground(arena, ctx.io, sub_id, label, prompt, ctx.parent_tool_call_id, agent.provider.id, agent.provider.model)
    else
        null;
    const background_announced = background_handle != null;
    const progress_on = !announced and !background_announced and acp_children.progressFor(ctx.io, kind, ctx.depth, ctx.parent_tool_call_id);
    var child_stream: acp_children.ChildSink = .{
        .id = sub_id,
        .io = ctx.io,
        .recorder = agent.sink,
        .background_handle = background_handle,
        .progress = if (progress_on) .{ .parent_call_id = ctx.parent_tool_call_id, .child_id = sub_id, .name = label, .provider = agent.provider.id, .model = agent.provider.model } else null,
    };
    if (announced or background_announced or progress_on) agent.sink = child_stream.engineSink();
    if (progress_on) child_stream.startProgress();
    var child_state: []const u8 = "failed";
    defer if (announced) acp_children.finish(ctx.io, sub_id, child_state, ctx.parent_tool_call_id);
    defer if (background_handle) |handle| acp_children.finishBackground(ctx.io, handle, sub_id, child_stream.seq, child_state);
    defer if (progress_on) child_stream.finishProgress(child_state);

    const wf_task = std.mem.eql(u8, kind, "workflow_task");
    if (wf_task) guiEmit(ctx.io, .{ .type = "tool_call", .name = "subagent", .input = .{ .description = label }, .id = sub_id });
    const tasked = try @import("subagent_brief.zig").prepare(arena, ctx.io, kind, prompt, ctx.agent_cwd, main_mod.g_hooks.pre_tool);
    const task_prompt = playbook.rideBrief(ctx.io, arena, try goal_pacing.childTaskPrompt(arena, tasked, ctx.loop_deadline_ms, util.unixMs(ctx.io)));
    try @import("subagent_retained.zig").restore(&agent, ctx);
    if (!std.mem.eql(u8, kind, "judge_task") and agent.messages.items.len == 0) {
        if (ctx.fork_source) |snapshot| try snapshot.seed(&agent);
    }
    @import("worker_mcp.zig").inherit(&agent); // ADR 0227
    @import("worker_jev.zig").offer(&agent); // ADR 0232: a child asks Jev for its own effort mid-run
    // ADR 0232: a fresh child starts from the user's request; a resumed one already has it.
    const first = if (ctx.fork_source != null and !std.mem.eql(u8, kind, "judge_task"))
        try std.fmt.allocPrint(arena, "The preceding conversation is forked context, not a request to repeat earlier work. Do only this new task:\n\n{s}", .{task_prompt})
    else if (agent.messages.items.len == 0)
        try @import("subagent_fork.zig").firstMessage(arena, ctx.parent_task, task_prompt)
    else
        task_prompt;
    @import("named_work.zig").rememberOn(&agent, prompt);
    try agent.messages.append(try textMessage(arena, "user", first));
    defer agent.tools_used.deinit(gpa);
    // Retry transient failures against the same child history.
    var attempts: u8 = 0;
    const report: anyerror![]const u8 = ask: {
        while (true) {
            attempts += 1;
            agent.last_api_error = null; // a stale cause must never classify the next ask
            const r = agent.runTurn();
            const err = if (r) |_| break :ask r else |e| e;
            const fail_kind = classifyFailure(err, agent.last_api_error);
            if (!subagent_retry.shouldRetry(err, fail_kind, agent.last_api_error, attempts)) break :ask r;
            // A run deadline already past makes waiting pointless.
            if (subagent_retry.pastDeadline(util.unixMs(ctx.io), ctx.loop_deadline_ms)) break :ask r;
            subagent_retry.traceAttempt(ctx.tracer, sub_id, attempts, fail_kind, agent.last_api_error);
            agent.sleepInterruptible(@import("retry_jitter.zig").ms(agent.io, subagent_retry.backoffMs(fail_kind, attempts))) catch break :ask r; // #1274
            agent.tool_repeat.carryOver(); // #1706: the re-ask resumes this history, so a looping worker keeps its count
        }
    };
    agent.synthesis.finish(&agent);
    // A worker that ran keeps its report and usage when its state can't be
    // saved for follow-ups; the save error used to replace both (#1671).
    const retained_failure: ?anyerror = if (@import("subagent_retained.zig").checkpoint(&agent, ctx)) |_| null else |e| e;
    const run_ms: i64 = @intCast(@max(0, sub_start.untilNow(ctx.io, .awake).toMilliseconds()));
    const run_ok = if (report) |r| r.len > 0 else |_| false;
    const interrupted = if (activity) |*recorder| @import("subagent_activity.zig").interruptRequested(ctx.io, recorder.dir, sub_id) else false;
    child_state = if (interrupted) "cancelled" else if (report) |_| (if (run_ok) "completed" else "failed") else |err| (if (err == error.Interrupted or err == error.Canceled) "cancelled" else "failed");
    if (activity) |*recorder| recorder.finish(run_ok, if (report) |r| r else |_| (agent.last_api_error orelse "Sub-agent failed"));
    if (wf_task) {
        // The sa- id (shared with agent_usage) pairs parallel workflow rows;
        // without it a consumer can only match tool_call/tool_result by order.
        const sub_report: []const u8 = if (report) |r|
            (if (r.len > 0) r else "subagent returned no report")
        else |_|
            (agent.last_api_error orelse "subagent failed");
        guiEmit(ctx.io, .{ .type = "tool_result", .name = "subagent", .is_error = !run_ok, .text = util.utf8Prefix(sub_report, 600), .id = sub_id });
    }
    const used_tools = agent.tools_used.render(arena);
    const usage: AgentUsage = .{
        .duration_ms = @intCast(run_ms),
        .tool_calls = @intCast(agent.tools_used.count()),
        .context_tokens = agent.effectiveContextTokens(),
        .cache_read_tokens = agent.last_cache_read,
    };
    guiEmit(ctx.io, agentUsageEvent(sub_id, run_ok, usage));
    // ADR 0232: one line per child, so a trace splits a run into the parent's time and each child's.
    if (ctx.tracer) |tr| tr.note("subagent", std.fmt.allocPrint(arena, "{s} {s} label={s} ms={d} tools={d} context={d} cached={d} effort={t}", .{ sub_id, if (run_ok) "ok" else "failed", label, run_ms, usage.tool_calls, usage.context_tokens, usage.cache_read_tokens, agent.reasoning }) catch "");
    const fp = promptFingerprint(agent.systemPrompt());
    if (trace.g_traj) |tj| {
        tj.capturePrompt(fp, agent.systemPrompt());
        tj.node(.{
            .id = tj.nextId(),
            .parent = tj.currentTurn(),
            .kind = kind,
            .label = label,
            .provider = agent.provider.id,
            .model = agent.provider.model,
            .t = tj.elapsedMs(),
            .ms = run_ms,
            .prompt_sha = &fp,
            .prompt_mutated = sys_override != null,
            .niche = niche,
            .task = util.utf8Prefix(prompt, 160),
            .tools = used_tools,
            .ok = run_ok,
            .context_tokens = agent.effectiveContextTokens(),
        });
    }
    if (telemetry.g_telem) |t| t.runEvent(&fp, sys_override != null, run_ok, run_ms, used_tools);
    const text = report catch |err| {
        var out = subagentFailure(gpa, sub_id, err, agent.last_api_error, attempts);
        const recovered = @import("subagent_recovery.zig").append(gpa, out.text, agent.messages.items, agent.partial_text.items) catch null;
        if (recovered) |body| {
            gpa.free(out.text);
            out.text = body;
        }
        if (wt) |w| {
            const tail = if (pool_seat)
                @import("experiment_pool.zig").deliverNote(gpa, ctx.io, .{ .path = w.path, .branch = w.branch, .base = w.base })
            else
                (std.fmt.allocPrint(gpa, "\n\n[worktree left in place after failure — path: {s}, branch: {s}]", .{ w.path, w.branch }) catch "");
            if (tail.len > 0) {
                const combined = std.fmt.allocPrint(gpa, "{s}{s}", .{ out.text, tail }) catch return .{ .output = out, .usage = usage };
                gpa.free(out.text);
                gpa.free(tail);
                out.text = combined;
            }
        }
        return .{ .output = out, .usage = usage };
    };
    const empty = text.len == 0;
    const report_body = if (empty) "subagent finished without a report" else text;
    // task_prompt, not the raw `prompt`: the detail file is the record of what
    // this worker was ACTUALLY sent, so it has to show the deadline note and
    // the #381 constraint block too. Reading a report against the raw prompt
    // is how "the subagent ignored my instruction" becomes unfalsifiable.
    const detail = cards.writeSubagentDetail(ctx.io, arena, sub_id, label, kind, task_prompt, report_body, !empty, run_ms, used_tools);
    cards.subagentDoneCard(arena, sub_id, sprite, label, !empty, run_ms, used_tools, detail, usage.cache_read_tokens, usage.context_tokens);

    var extra: []const u8 = isolation_note;
    var extra_owned = false;
    if (wt) |w| {
        if (ctx.retained_worker != null) {
            extra = try std.fmt.allocPrint(gpa, "\n\n[worker workspace retained: {s}]", .{w.path});
            extra_owned = true;
        } else if (pool_seat) {
            extra = @import("experiment_pool.zig").deliverNote(gpa, ctx.io, .{ .path = w.path, .branch = w.branch, .base = w.base });
            extra_owned = extra.len > 0;
        } else {
            const outcome = jobs.agentWorktreeFinish(gpa, ctx.io, w);
            @import("worktree_reap.zig").reapAfterTask(gpa, ctx.io);
            if (outcome.kept) {
                extra = std.fmt.allocPrint(gpa, "\n\n[worktree kept ({s}) — path: {s}, branch: {s}; finish is not archive — do not spawn a cleanup child]", .{ jobs.keepReasonText(outcome.reason), w.path, w.branch }) catch "";
                extra_owned = extra.len > 0;
            }
        }
    }
    defer if (extra_owned) gpa.free(extra);
    const unsaved = if (retained_failure) |e| try retainedFailureNote(arena, e) else "";

    if (empty) return .{
        .output = .{ .text = try std.fmt.allocPrint(gpa, "{s}{s}{s}", .{ report_body, extra, unsaved }), .is_error = true },
        .usage = usage,
    };
    if (detail) |p| return .{
        .output = .{ .text = try std.fmt.allocPrint(gpa, "{s}\n\n[subagent {s} · inspect: {s}]{s}{s}", .{ text, sub_id, p, extra, unsaved }) },
        .usage = usage,
    };
    return .{ .output = .{ .text = try std.fmt.allocPrint(gpa, "{s}{s}{s}", .{ text, extra, unsaved }) }, .usage = usage };
}

/// The report still stands; only continuing this worker is lost.
pub fn retainedFailureNote(a: Allocator, err: anyerror) ![]const u8 {
    return std.fmt.allocPrint(a, "\n\n[worker state was not saved for follow-ups ({t}); this report is complete, but agent_message and resume cannot continue this worker]", .{err});
}

/// A worker whose run never started: setup failed before its first step,
/// so nothing it would do has happened yet (#1671).
pub fn startFailure(gpa: Allocator, err: anyerror) ToolOutput {
    const text = std.fmt.allocPrint(gpa, "subagent did not start: {t}. It failed during setup, before its first step, so no tools ran.", .{err}) catch return .{ .is_error = true };
    return .{ .text = text, .is_error = true };
}