graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(#382): warn when a variant fleet's briefs are one concept N times
justrachc76569c3a0c6
diff --git a/src/agent_tools.zig b/src/agent_tools.zigindex 82ca4197..4e057c74 100644--- a/src/agent_tools.zig+++ b/src/agent_tools.zig@@ -43,6 +43,7 @@ const ToolOutput = tools_mod.ToolOutput;const exec = @import("exec.zig");const execTool = exec.execTool;+const brief_diversity = @import("brief_diversity.zig"); // #382: N sibling spawns in one batch are a fleetconst util = @import("util.zig"); // #225: unixMs, for the clock_sleep interrupted-elapsed measurementconst protocol_seq = @import("protocol_seq.zig"); // #330: monotonic `seq` on every --json event@@ -50,10 +51,6 @@ const tool_results_dir = ".graff/tool-results";pub const tool_preview_chars: usize = 2_000;var tool_result_seq: std.atomic.Value(u64) = .init(0);-test {- _ = @import("agent_eval_control_tests.zig");-}-pub fn toolPreviewText(arena: std.mem.Allocator, text: []const u8, path: ?[]const u8) ![]const u8 {if (text.len <= tool_preview_chars) return arena.dupe(u8, text);const marker = if (path) |p|@@ -188,6 +185,7 @@ pub fn runTools(self: *Agent, calls: []const ToolCall) ![]ExecResult {self.eval_repair_pending = false;}}+ brief_diversity.noteSiblingBatch(self.arena, self.tracer, calls, ext_idx.items, results); // #382// #266: a cancelled parallel batch used to just look "running" and then// failed — one terminal line says what completed, failed, and cancelled.if (ext_idx.items.len > 1 and !self.sub) {diff --git a/src/brief_diversity.zig b/src/brief_diversity.zignew file mode 100644index 00000000..c1c5537a--- /dev/null+++ b/src/brief_diversity.zig@@ -0,0 +1,358 @@+//! #382 — the brief-diversity gate for variant fleets.+//!+//! The failure this exists for: a root agent spawned ten "variant" subagents+//! over one session that all reused a single six-slide template and varied+//! only decoration — spark motif, ambient hue, particle field, skin, font+//! pairing, blob saturation. The user was shown the same design seven times.+//! A contrasting run of the SAME model on the SAME harness fanned out five+//! briefs each carrying a distinct compositional thesis (editorial parallax /+//! sticky crossfades / kinetic typography / scroll-scrubbed chapters /+//! horizontal rail) and produced five genuinely different pages. The whole+//! gap was orchestration quality, and the harness already holds every brief+//! in memory before it spawns anything — it just never looked at them.+//!+//! So look. Model-free, allocation-bounded, and WARN-ONLY: a fleet that is+//! deliberately near-identical (N runs of one prompt to sample variance) is a+//! legitimate thing to ask for, and a harness that refused it would be wrong.+//! The note names the number and the similarity and lets the root decide.+//!+//! Metric — mean pairwise Jaccard over deduped word 3-grams (shingles):+//!+//! * 3-grams rather than bare word sets because the signal IS phrasing.+//! Two briefs in one domain share most of their vocabulary whatever they+//! ask for ("page", "section", "scroll", "route", "component", plus every+//! function word), so unigram overlap reads high for fleets that are+//! genuinely different — a false positive, and a warn-only gate that+//! cries wolf gets ignored. A shingle is only shared when a RUN of words+//! is shared, which is exactly what copy-pasting one template does.+//! * Jaccard rather than the overlap coefficient (|A∩B| / min) because+//! overlap saturates to 1.0 whenever one brief is short, and short is not+//! the same as derivative.+//! * MEAN rather than max: one duplicated pair inside an otherwise varied+//! fleet is not the failure — the failure is a whole fleet cut from one+//! pattern, and the mean is what separates those two.+//!+//! Cost is O(N²·W) comparisons over sorted u64 arrays with a hard cap on both+//! N and the words read per brief, so a pathological fleet cannot make this+//! expensive. No model call, no network, no I/O beyond the trace note.+//!+//! Two call sites, both BEFORE anything spawns:+//!+//! workflow.zig a phase fanning out N≥3 tasks; its note rides the run+//! manifest, which is the part of a workflow result the+//! root reliably reads.+//! agent_tools.zig N≥3 sibling `subagent` spawns in ONE tool batch — the+//! same fleet, just never named as one; its note is+//! prepended to the first sibling's result.+//!+//! Both measure the RAW briefs, before workflow `context` is prepended and+//! before {{prev}} is substituted. That matters: those two mechanically+//! inject identical text into every prompt in a phase, so measuring the+//! composed prompts would score every wide phase as a near-duplicate fleet+//! and the gate would be noise by construction.++const std = @import("std");+const Allocator = std.mem.Allocator;+const trace = @import("trace.zig");+const util = @import("util.zig");+const fleet = @import("fleet.zig"); // resolveOverride: the shared system_prompt/agent resolution++/// Shingle width. 3 is the standard near-duplicate-detection default and it+/// is what the fixtures below were tuned against; 2 drifts toward unigram+/// behaviour (too many false positives), 4+ misses reskins that reword a+/// clause while keeping the structure.+pub const gram_n = 3;++/// A fleet needs at least this many briefs before "they all look alike" is+/// even a meaningful statement. Two tasks in a phase are a pair, not a fleet.+pub const min_fleet = 3;++/// Hard bounds. max_briefs is above workflow.max_workflow_tasks (8) on+/// purpose so the sibling-spawn path can share this without a second cap;+/// max_words bounds the per-brief scratch, and truncating to the first ~512+/// words is safe because a brief's thesis is at its head, never its tail.+pub const max_briefs = 16;+pub const max_words = 512;++/// The longest word prefix that participates in a word's hash. Beyond this+/// two words collide, which can only ever RAISE measured similarity for+/// absurd inputs — and absurd inputs are not the case this protects.+const word_cap = 48;++/// Mean pairwise similarity at or above which the fleet gets a note.+///+/// MEASURED, not guessed. Every fixture in brief_diversity_tests.zig is+/// transcribed from the two runs in the post-mortem or from this repo's own+/// shape catalog, and this is where they land on the trigram scale:+///+/// near-copies (one brief, /vN swapped) 0.739 must warn+/// reskin fleet (template + decoration deltas) 0.619 must warn+/// ── warn_threshold 0.55 ─────────────────────────────────────────+/// shape-A verify (one skeptic per finding) 0.512 must stay quiet+/// shape-B sweep (same target, 3 search axes) 0.168 must stay quiet+/// partial redesign (same skeleton, re-planned) 0.167 must stay quiet+/// five-thesis fleet (the successful run) 0.075 must stay quiet+/// three unrelated audits 0.000 must stay quiet+///+/// The tightest constraint is the gap between the reskin fleet and a+/// legitimate verify phase — both share a skeleton on purpose, and only one+/// of them is a failure. 0.55 sits in that 0.512-0.619 band. Trigrams were+/// kept over unigrams partly because that band is WIDER here (0.107) than on+/// unigrams (0.078), where the same two fixtures sit at 0.647 and 0.724.+///+/// Which also explains the number: the issue proposed ~0.7, and ~0.7 is+/// exactly where a reskin lands on the UNIGRAM scale. Shingles run+/// structurally lower — one changed word kills gram_n grams instead of one+/// token — so 0.55 is that same operating point re-expressed in the metric+/// actually in use, with margin measured on both sides rather than assumed.+///+/// Bias is deliberately toward silence: a false warning on a legitimate+/// phase teaches the root to ignore the line, which costs more than the+/// missed reskin it was meant to catch.+pub const warn_threshold: f64 = 0.55;++/// Which text actually carried the fleet's intended variation — see+/// `personaAxis`.+pub const Axis = enum { brief, system_prompt };++pub const Report = struct {+ /// Briefs actually compared (capped at max_briefs).+ n: usize = 0,+ /// Mean pairwise Jaccard, 0..1. Zero for a fleet below min_fleet.+ mean: f64 = 0,+ warn: bool = false,+ axis: Axis = .brief,++ /// Mean as whole percent, for the human-facing line.+ pub fn percent(self: Report) u64 {+ const p = @round(self.mean * 100);+ return if (p <= 0) 0 else @intFromFloat(p);+ }+};++/// Word bytes: ASCII alphanumerics plus every non-ASCII byte, so a UTF-8 word+/// stays ONE token instead of shattering into per-byte tokens (which would+/// make any two non-Latin briefs look similar through their shared+/// continuation bytes).+fn isWordByte(c: u8) bool {+ return std.ascii.isAlphanumeric(c) or c >= 0x80;+}++/// Hash `text`'s words into `out` in order, returning the used prefix.+/// Lowercased so casing never registers as a difference.+fn wordHashes(out: []u64, text: []const u8) []u64 {+ var n: usize = 0;+ var i: usize = 0;+ while (i < text.len and n < out.len) {+ while (i < text.len and !isWordByte(text[i])) : (i += 1) {}+ if (i >= text.len) break;+ const start = i;+ while (i < text.len and isWordByte(text[i])) : (i += 1) {}+ var buf: [word_cap]u8 = undefined;+ const word = text[start..i];+ const m = @min(word.len, buf.len);+ for (buf[0..m], word[0..m]) |*d, s| d.* = std.ascii.toLower(s);+ out[n] = std.hash.Wyhash.hash(0, buf[0..m]);+ n += 1;+ }+ return out[0..n];+}++/// The sorted, deduplicated shingle set for one brief's word hashes, written+/// into `out` (which must hold at least `words.len` entries).+///+/// A brief with fewer than gram_n words has no shingle, so it collapses to a+/// single gram over its whole word list: two such briefs then compare 1.0 iff+/// they are the same words, 0.0 otherwise. That is the honest answer for+/// "build /v1" vs "build /v2" — there is no phrasing to measure.+fn gramSet(out: []u64, words: []const u64) []const u64 {+ var n: usize = 0;+ if (words.len == 0) return out[0..0];+ if (words.len < gram_n) {+ out[0] = std.hash.Wyhash.hash(1, std.mem.sliceAsBytes(words));+ n = 1;+ } else {+ for (0..words.len - gram_n + 1) |i| {+ out[n] = std.hash.Wyhash.hash(1, std.mem.sliceAsBytes(words[i .. i + gram_n]));+ n += 1;+ }+ }+ const filled = out[0..n];+ std.mem.sort(u64, filled, {}, std.sort.asc(u64));+ var w: usize = 0;+ for (filled, 0..) |v, k| {+ if (k == 0 or v != filled[w - 1]) {+ filled[w] = v;+ w += 1;+ }+ }+ return filled[0..w];+}++/// Jaccard over two sorted, deduplicated sets: one linear merge, no+/// allocation. An empty set yields 0 — no evidence, not perfect agreement.+fn jaccard(a: []const u64, b: []const u64) f64 {+ if (a.len == 0 or b.len == 0) return 0;+ var i: usize = 0;+ var j: usize = 0;+ var inter: usize = 0;+ while (i < a.len and j < b.len) {+ if (a[i] == b[j]) {+ inter += 1;+ i += 1;+ j += 1;+ } else if (a[i] < b[j]) {+ i += 1;+ } else {+ j += 1;+ }+ }+ const uni = a.len + b.len - inter;+ return @as(f64, @floatFromInt(inter)) / @as(f64, @floatFromInt(uni));+}++/// Measure a fleet. Below min_fleet (or on any allocation failure) the report+/// is inert: `warn` false, `mean` zero — this is a diagnostic, so it degrades+/// to silence rather than to a guess.+pub fn analyze(arena: Allocator, briefs: []const []const u8) Report {+ // Explicitly usize: @min narrows its result type to the smallest int that+ // can hold max_briefs (u5), and n scales a buffer length below.+ const n: usize = @min(briefs.len, max_briefs);+ if (n < min_fleet) return .{ .n = briefs.len };+ const words = arena.alloc(u64, max_words) catch return .{ .n = n };+ const grams = arena.alloc(u64, n * max_words) catch return .{ .n = n };+ const sets = arena.alloc([]const u64, n) catch return .{ .n = n };+ for (briefs[0..n], sets, 0..) |brief, *set, k| {+ const w = wordHashes(words, brief);+ set.* = gramSet(grams[k * max_words ..][0..max_words], w);+ }+ var total: f64 = 0;+ var pairs: usize = 0;+ for (0..n) |i| {+ for (i + 1..n) |j| {+ total += jaccard(sets[i], sets[j]);+ pairs += 1;+ }+ }+ const mean = total / @as(f64, @floatFromInt(pairs));+ return .{ .n = n, .mean = mean, .warn = mean >= warn_threshold };+}++/// The root-facing line, or null when the fleet is fine. Warn-only by+/// construction: it names the measurement, says what to change, and ends by+/// granting permission to ignore it — a gate that blocked here would break+/// the legitimate "run the same brief N times" fleet.+pub fn warningText(arena: Allocator, r: Report) ?[]const u8 {+ if (!r.warn) return null;+ return std.fmt.allocPrint(+ arena,+ "diversity warning: {d} variant briefs are ~{d}% similar — these read as " +++ "cosmetic variants of one concept. Differentiate composition, narrative, " +++ "or interaction architecture, or proceed if intentional.",+ .{ r.n, r.percent() },+ ) catch null;+}++/// When EVERY task in the fleet carries its own `system_prompt`, that genome+/// is the axis the fleet varies on and the prompts are not — so measure the+/// genomes instead. Returns null (measure the briefs) otherwise.+///+/// This is not a nicety, it is required for the gate to be believable. Shape+/// C in this repo's own catalog reads "N implementers, same task, a DIFFERENT+/// system_prompt each (MVP-first / risk-first / perf-first)": its task+/// prompts are IDENTICAL by design and measure 1.000, while its personas+/// measure 0.006. Judging that fleet on its prompts would fire the warning+/// every single time the harness's own recommended pattern is used, and a+/// warning that fires on correct usage is a warning nobody reads.+///+/// A fleet whose personas ARE near-identical still warns, on the persona+/// text — which is the right answer, since that fleet really is one concept.+pub fn personaAxis(arena: Allocator, briefs: []const []const u8, genomes: []const ?[]const u8) ?[]const []const u8 {+ if (genomes.len != briefs.len) return null;+ for (genomes) |g| if (g == null or g.?.len == 0) return null;+ const out = arena.alloc([]const u8, genomes.len) catch return null;+ for (genomes, out) |g, *o| o.* = g.?;+ return out;+}++/// Cap on the phase label copied into the trace line, matching+/// route_trace.field_cap: a model-authored title must not be able to turn one+/// trace record into a megabyte.+const label_cap = 64;++/// The whole gate as one call, because both call sites are files at (or one+/// line from) the 600-line cap and can afford exactly one statement each.+/// Measures, records, prints, and returns the root-facing line — "" when the+/// fleet is fine or too small to judge. `genomes` is the parallel per-task+/// `system_prompt` slice (pass `&.{}` when the call site has none).+///+/// The measurement is traced for EVERY fleet, not only the ones that warn: a+/// run that stayed quiet is the evidence that the gate was actually looking,+/// and the numbers are what a future threshold re-tune reads.+pub fn check(arena: Allocator, tracer: ?*trace.Tracer, phase: []const u8, briefs: []const []const u8, genomes: []const ?[]const u8) []const u8 {+ const persona = personaAxis(arena, briefs, genomes);+ var r = analyze(arena, persona orelse briefs);+ if (persona != null) r.axis = .system_prompt;+ if (r.n < min_fleet) return "";+ var buf: [160]u8 = undefined;+ const detail = std.fmt.bufPrint(&buf, "n={d} mean={d:.3} threshold={d:.2} axis={s} warn={}", .{ r.n, r.mean, warn_threshold, @tagName(r.axis), r.warn }) catch "";+ if (tracer) |tr| tr.note("diversity", detail);+ // #382 increment 3, done additively: a NEW `kind:"diversity"` row rather+ // than an extra column on the #372 `kind:"score"` rows, so an offline+ // reader can join brief diversity to that run's judge outcomes without a+ // single existing row shape changing underneath it.+ if (trace.g_traj) |tj| tj.node(.{+ .kind = "diversity",+ .phase = util.utf8Prefix(phase, label_cap),+ .n = r.n,+ .mean = r.mean,+ .threshold = warn_threshold,+ .axis = @tagName(r.axis),+ .warn = r.warn,+ .t = tj.elapsedMs(),+ });+ const text = warningText(arena, r) orelse return "";+ // Its own prefix rather than the caller's: this fires from the workflow+ // phase loop AND from a bare sibling-spawn batch, where "[workflow]"+ // would name a workflow that never ran.+ std.debug.print(" [diversity] {s}\n", .{text});+ return text;+}++/// The OTHER fan-out: N sibling `subagent` spawns arriving in ONE tool batch,+/// which is a fleet the harness never named as one. `calls`/`results` are the+/// runTools batch (taken as anytype so this stays off tools.zig's import+/// graph); `ext` indexes the external calls actually dispatched.+///+/// The note is prepended to the FIRST sibling's result rather than emitted on+/// its own, because a tool result is the only channel a batch has back to the+/// root — and prepending puts it above text that toolPreviewText may have+/// truncated. Best-effort throughout: this must never be able to fail a spawn+/// that already succeeded, so every unhappy path is a bare return.+pub fn noteSiblingBatch(arena: Allocator, tracer: ?*trace.Tracer, calls: anytype, ext: []const usize, results: anytype) void {+ var briefs: [max_briefs][]const u8 = undefined;+ var genomes: [max_briefs]?[]const u8 = undefined;+ var first: usize = 0;+ var n: usize = 0;+ for (ext) |i| {+ if (n == max_briefs) break;+ const call = calls[i];+ if (!std.mem.eql(u8, call.name, "subagent") or call.input != .object) continue;+ const p = call.input.object.get("prompt") orelse continue;+ if (p != .string or p.string.len == 0) continue;+ if (n == 0) first = i;+ briefs[n] = p.string;+ // Same resolution the workflow path uses, so an `agent:"reviewer"`+ // fleet is read on its personas there and here alike.+ genomes[n] = fleet.resolveOverride(call.input.object);+ n += 1;+ }+ if (n < min_fleet) return;+ const text = check(arena, tracer, "subagent batch", briefs[0..n], genomes[0..n]);+ if (text.len == 0) return;+ results[first].text = std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ text, results[first].text }) catch return;+}++test {+ _ = @import("brief_diversity_tests.zig");+}diff --git a/src/brief_diversity_tests.zig b/src/brief_diversity_tests.zignew file mode 100644index 00000000..1c808a1c--- /dev/null+++ b/src/brief_diversity_tests.zig@@ -0,0 +1,403 @@+//! #382 fixtures + tests for the brief-diversity gate.+//!+//! Split out of brief_diversity.zig so the fixtures can be full-length real+//! briefs rather than toy strings — the threshold is only defensible if the+//! text it was tuned on is the text the harness actually sees. Every fixture+//! below is either transcribed from the production post-mortem (the reskin+//! fleet that shipped the same design seven times, and the five-thesis fleet+//! that did not) or written straight off this repo's own shape catalog, so a+//! future threshold change has to answer to real orchestration patterns.+//!+//! Reached from brief_diversity.zig's `test {}` block, which workflow.zig+//! imports — so these run without a test_hooks.zig entry.++const std = @import("std");+const bd = @import("brief_diversity.zig");++// ── The failure (post-mortem run A) ─────────────────────────────────────────+// Ten "variant" subagents over one session, all reusing one six-slide+// template and varying only decoration: spark motif, ambient hue, particle+// field, skin, font pairing, blob saturation. Three consecutive briefs.+const reskin_fleet = [_][]const u8{+ "Build variant 4 of the launch deck. Keep the same six-slide scroll structure: hero, problem, product, metrics, testimonial, call to action. Every slide is full-bleed with a centered headline and one supporting line beneath it. For this variant: swap the accent motif to a spark field, warm the blob saturation, and pair Instrument Serif with Inter.",+ "Build variant 5 of the launch deck. Keep the same six-slide scroll structure: hero, problem, product, metrics, testimonial, call to action. Every slide is full-bleed with a centered headline and one supporting line beneath it. For this variant: swap the accent motif to an ambient hue wash, cool the blob saturation, and pair Playfair Display with Satoshi.",+ "Build variant 6 of the launch deck. Keep the same six-slide scroll structure: hero, problem, product, metrics, testimonial, call to action. Every slide is full-bleed with a centered headline and one supporting line beneath it. For this variant: swap the accent motif to a drifting particle layer, deepen the blob saturation, and pair Fraunces with General Sans.",+};++// The degenerate end of the same failure: one brief, route index swapped.+const near_copies = [_][]const u8{+ "Build a six-slide scroll deck for the launch page at route /v1 with hero, problem, product, metrics, testimonial and CTA slides.",+ "Build a six-slide scroll deck for the launch page at route /v2 with hero, problem, product, metrics, testimonial and CTA slides.",+ "Build a six-slide scroll deck for the launch page at route /v3 with hero, problem, product, metrics, testimonial and CTA slides.",+};++// ── The success (post-mortem run B) ─────────────────────────────────────────+// Five parallel briefs, each with a DISTINCT compositional thesis, one+// signature motion system, and its own route. Same model, same harness.+const thesis_fleet = [_][]const u8{+ "Variant 1 - editorial parallax. Thesis: the page reads like a print magazine spread whose plates drift at different depths as the reader scrolls. Signature system: multi-depth parallax on the image plates, nothing else moves. Build it at /v1; the shared components directory is off limits.",+ "Variant 2 - sticky crossfades. Thesis: the whole surface is one pinned frame in which each section dissolves into the next rather than travelling past it. Signature system: scroll-pinned opacity crossfade between sections. Build it at /v2; the shared components directory is off limits.",+ "Variant 3 - kinetic typography. Thesis: the words carry the argument by themselves, set enormous and relaid out on every beat, with imagery demoted to texture. Signature system: per-glyph type animation on entry. Build it at /v3; the shared components directory is off limits.",+ "Variant 4 - scroll-scrubbed chapters. Thesis: the story behaves like a film reel the reader scrubs through, one chapter per segment of the scrollbar. Signature system: a scroll-linked timeline that scrubs a single continuous sequence. Build it at /v4; the shared components directory is off limits.",+ "Variant 5 - horizontal rail. Thesis: content advances sideways along one continuous rail, so progress through the argument is spatial instead of vertical. Signature system: horizontal translation with snap points at each stop. Build it at /v5; the shared components directory is off limits.",+};++// ── Legitimate fleets that MUST stay quiet ──────────────────────────────────+// Shape A's verify slot: one skeptic per finding. Shares a skeleton on+// purpose — this is the hardest true negative, and the constraint that+// actually sets the threshold's ceiling.+const verify_fleet = [_][]const u8{+ "Refute finding 1: unchecked error union at src/http.zig:212. Build the strongest case that this is NOT a real bug - read the callers, the tests that cover it, and the git history of the line. Answer REFUTED or STANDS with evidence.",+ "Refute finding 2: path traversal in the tool-result writer at src/agent_tools.zig:74. Build the strongest case that this is NOT a real bug - read the callers, the tests that cover it, and the git history of the line. Answer REFUTED or STANDS with evidence.",+ "Refute finding 3: the retry loop in src/workflow.zig can double-charge a failed task. Build the strongest case that this is NOT a real bug - read the callers, the tests that cover it, and the git history of the line. Answer REFUTED or STANDS with evidence.",+};++// Shape B's sweep slot: same target, deliberately different search axes.+const sweep_fleet = [_][]const u8{+ "Map how compaction is triggered, searching by SYMBOL: start from every function whose name mentions compact or token, and follow the call graph outward. Do not read the git history - another researcher has that.",+ "Map how compaction is triggered, searching by GIT HISTORY: find the commits that introduced and later changed the threshold, and summarise what each one was fixing. Do not search by symbol - another researcher has that.",+ "Map how compaction is triggered, searching by TESTS: find every test that exercises a compaction path and describe what behaviour each one pins. Do not read the git history - another researcher has that.",+};++// The genuinely ambiguous middle: one six-slide skeleton, but each variant+// RE-PLANS the sections instead of restyling them. Composition differs, so+// this is a real fleet and must stay quiet.+const partial_fleet = [_][]const u8{+ "Build variant A of the launch deck as a six-slide scroll. Open on an oversized product shot, then a single-sentence problem slide, then three proof slides built from customer numbers, then a quiet closing CTA. Typography is the loudest element; motion is limited to slide entry.",+ "Build variant B of the launch deck as a six-slide scroll. Open on a full-screen quote from a customer, then the product shot, then a comparison slide against the status quo, then two objection-handling slides, then the CTA. Colour blocking carries the hierarchy; motion is limited to slide entry.",+ "Build variant C of the launch deck as a six-slide scroll. Open on the problem stated as a statistic, then a narrative build across three slides that each add one product capability, then a pricing slide, then the CTA. Layout density increases as the reader descends; motion is limited to slide entry.",+};++// Three unrelated audits — the easy true negative.+const audit_fleet = [_][]const u8{+ "Audit src/http.zig for correctness bugs: off-by-one indexing, unchecked error unions, and any path that can return a dangling slice into a freed buffer. Report each finding with a file:line and a one-line repro.",+ "Audit the same tree for security problems: command injection through exec.zig argv assembly, path traversal in the tool-result writer, and any secret that reaches a log line or a trace record.",+ "Audit the test suite for coverage holes: which public functions in src/ have no test at all, and which tests assert only that a call returns without checking what it returned.",+};++// Shape C: N implementers, the SAME task, a different system_prompt each.+const shape_c_prompt = "Implement the retry budget for workflow phases described in issue #382.";+const shape_c_prompts = [_][]const u8{ shape_c_prompt, shape_c_prompt, shape_c_prompt };+const shape_c_genomes = [_]?[]const u8{+ "You are an MVP-first implementer. Ship the smallest change that makes the feature real; refuse scope you were not asked for; prefer one function over an abstraction.",+ "You are a risk-first implementer. Before writing code, enumerate the ways this change can break an existing caller, then implement so that each of those ways is impossible or tested.",+ "You are a performance-first implementer. Assume this path runs on every turn; count allocations and syscalls, and justify each one you add in a comment.",+};++fn meanOf(a: std.mem.Allocator, briefs: []const []const u8) f64 {+ return bd.analyze(a, briefs).mean;+}++test "#382: a reskin fleet trips the gate; the five-thesis fleet does not" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();++ // (a) The production failure. Three briefs off one six-slide template,+ // differing only in decoration words, must warn — and must warn LOUDLY,+ // not by a hair, or the threshold is riding on fixture noise.+ const reskin = bd.analyze(a, &reskin_fleet);+ try std.testing.expect(reskin.warn);+ try std.testing.expectEqual(@as(usize, 3), reskin.n);+ try std.testing.expect(reskin.mean > 0.60 and reskin.mean < 0.68);++ // The degenerate case scores higher still.+ const copies = bd.analyze(a, &near_copies);+ try std.testing.expect(copies.warn);+ try std.testing.expect(copies.mean > reskin.mean);++ // (b) The successful run: five briefs, five compositional theses. This is+ // the fleet the gate must never touch, and it is nowhere near the line.+ const thesis = bd.analyze(a, &thesis_fleet);+ try std.testing.expect(!thesis.warn);+ try std.testing.expectEqual(@as(usize, 5), thesis.n);+ try std.testing.expect(thesis.mean < 0.15);++ // The gap between the two production runs is the whole point: it is not a+ // rounding difference, it is most of the scale.+ try std.testing.expect(reskin.mean - thesis.mean > 0.4);+}++test "#382: legitimate skeleton-sharing fleets stay quiet" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();++ // The tightest true negative in the suite: shape A's verify slot repeats+ // its instructions verbatim across tasks BY DESIGN and only the finding+ // changes. It sits below the threshold, and the reskin fleet sits above+ // it — that ordering is what makes the gate usable at all.+ const verify = bd.analyze(a, &verify_fleet);+ try std.testing.expect(!verify.warn);+ try std.testing.expect(verify.mean > 0.45); // genuinely close to the line+ try std.testing.expect(verify.mean < bd.warn_threshold);+ try std.testing.expect(meanOf(a, &reskin_fleet) > verify.mean);++ // Everything else a real workflow fans out is far from the line.+ try std.testing.expect(!bd.analyze(a, &sweep_fleet).warn);+ try std.testing.expect(!bd.analyze(a, &partial_fleet).warn);+ try std.testing.expect(!bd.analyze(a, &audit_fleet).warn);+ try std.testing.expect(meanOf(a, &audit_fleet) < 0.05);+}++test "#382: a fleet whose variation lives in system_prompt is judged on that axis" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();++ // Shape C's prompts are identical by construction — judged on prompts+ // alone this fleet is a perfect 1.0 and would warn every single time the+ // catalog's own design/solve shape is used.+ const on_prompts = bd.analyze(a, &shape_c_prompts);+ try std.testing.expect(on_prompts.warn);+ try std.testing.expectApproxEqAbs(@as(f64, 1.0), on_prompts.mean, 1e-9);++ // With the personas supplied, the axis moves to them and the fleet is+ // correctly read as three different implementers of one task.+ const quiet = bd.check(a, null, "variants", &shape_c_prompts, &shape_c_genomes);+ try std.testing.expectEqualStrings("", quiet);++ // The axis only moves when EVERY task has a genome; a partial fleet is+ // still judged on its briefs (there is no shared axis to move to).+ const partial_genomes = [_]?[]const u8{ shape_c_genomes[0], null, shape_c_genomes[2] };+ try std.testing.expect(bd.personaAxis(a, &shape_c_prompts, &partial_genomes) == null);+ try std.testing.expect(bd.check(a, null, "variants", &shape_c_prompts, &partial_genomes).len > 0);++ // …and near-identical personas still warn, on the persona text.+ const same = [_]?[]const u8{ shape_c_genomes[0], shape_c_genomes[0], shape_c_genomes[0] };+ try std.testing.expect(bd.check(a, null, "variants", &shape_c_prompts, &same).len > 0);+}++test "#382: a fleet smaller than min_fleet is never judged" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();++ // (c) Two byte-identical briefs are a pair, not a fleet: "they all look+ // alike" is not a statement about two things, and a phase of two is the+ // most common shape there is. Nothing is measured and nothing is said.+ const two = [_][]const u8{ reskin_fleet[0], reskin_fleet[0] };+ const r2 = bd.analyze(a, &two);+ try std.testing.expect(!r2.warn);+ try std.testing.expectEqual(@as(f64, 0), r2.mean);+ try std.testing.expectEqualStrings("", bd.check(a, null, "variants", &two, &.{}));++ const one = [_][]const u8{reskin_fleet[0]};+ try std.testing.expect(!bd.analyze(a, &one).warn);+ try std.testing.expectEqualStrings("", bd.check(a, null, "variants", &one, &.{}));+ try std.testing.expect(!bd.analyze(a, &.{}).warn);++ // Three identical briefs is the smallest fleet that CAN warn, and does.+ const three = [_][]const u8{ reskin_fleet[0], reskin_fleet[0], reskin_fleet[0] };+ try std.testing.expect(bd.analyze(a, &three).warn);+}++test "#382: the threshold is a mean over pairs, compared inclusively" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();++ // (d) Boundary, pinned deterministically. Single-word briefs have no+ // trigram, so each pair scores exactly 1.0 or 0.0 and the mean is an+ // exact rational: 3 identical of 4 briefs is 3/6 = 0.500 (quiet), 4+ // identical of 5 is 6/10 = 0.600 (warn). The threshold therefore lives in+ // (0.50, 0.60] no matter what the prose fixtures do.+ const four = [_][]const u8{ "alpha", "alpha", "alpha", "beta" };+ const r4 = bd.analyze(a, &four);+ try std.testing.expectApproxEqAbs(@as(f64, 0.5), r4.mean, 1e-9);+ try std.testing.expect(!r4.warn);++ const five = [_][]const u8{ "alpha", "alpha", "alpha", "alpha", "beta" };+ const r5 = bd.analyze(a, &five);+ try std.testing.expectApproxEqAbs(@as(f64, 0.6), r5.mean, 1e-9);+ try std.testing.expect(r5.warn);++ try std.testing.expect(bd.warn_threshold > 0.5 and bd.warn_threshold <= 0.6);++ // Mean, not max: one duplicated pair inside an otherwise varied fleet is+ // not the failure mode this gate is for.+ const one_dupe = [_][]const u8{ thesis_fleet[0], thesis_fleet[0], thesis_fleet[1], thesis_fleet[2], thesis_fleet[3] };+ try std.testing.expect(!bd.analyze(a, &one_dupe).warn);+}++test "#382: the warning names the count and the measurement, and never blocks" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();++ const text = bd.check(a, null, "variants", &reskin_fleet, &.{});+ try std.testing.expect(std.mem.startsWith(u8, text, "diversity warning: 3 variant briefs are ~6"));+ try std.testing.expect(std.mem.indexOf(u8, text, "% similar") != null);+ try std.testing.expect(std.mem.indexOf(u8, text, "cosmetic variants of one concept") != null);+ // The actionable half: what to change, not just that something is wrong.+ try std.testing.expect(std.mem.indexOf(u8, text, "Differentiate composition, narrative, or interaction architecture") != null);+ // Warn-only. The escape hatch is part of the contract: a deliberately+ // uniform fleet (N samples of one prompt) is a legitimate ask.+ try std.testing.expect(std.mem.indexOf(u8, text, "proceed if intentional") != null);++ // A quiet fleet produces no text at all — no "all good" noise in the+ // root's transcript.+ try std.testing.expectEqualStrings("", bd.check(a, null, "sweep", &thesis_fleet, &.{}));+}++test "#382: degenerate and adversarial inputs cannot crash or mislead the gate" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();++ // Empty briefs have no grams: no evidence is 0, not perfect agreement.+ const empties = [_][]const u8{ "", "", "" };+ try std.testing.expect(!bd.analyze(a, &empties).warn);+ const punct = [_][]const u8{ "!!!", "???", "---" };+ try std.testing.expect(!bd.analyze(a, &punct).warn);++ // Case and punctuation are not differences.+ const cased = [_][]const u8{ "Build the deck.", "BUILD THE DECK!", "build the deck" };+ try std.testing.expectApproxEqAbs(@as(f64, 1.0), bd.analyze(a, &cased).mean, 1e-9);++ // Non-ASCII words stay whole rather than shattering into shared UTF-8+ // continuation bytes, which would make any two non-Latin briefs look+ // alike. Three different Japanese briefs must not warn.+ const jp = [_][]const u8{+ "ヒーロー セクション を 作る 大きな 見出し と 写真",+ "価格 表 を 作る 三 つ の プラン と 比較 表",+ "問い合わせ フォーム を 作る 名前 メール 本文 の 欄",+ };+ try std.testing.expect(!bd.analyze(a, &jp).warn);+ // …while three copies of one of them does warn.+ const jp_same = [_][]const u8{ jp[0], jp[0], jp[0] };+ try std.testing.expect(bd.analyze(a, &jp_same).warn);++ // A fleet wider than the cap is truncated, never unbounded.+ var wide: [bd.max_briefs + 6][]const u8 = undefined;+ for (&wide, 0..) |*w, i| w.* = if (i % 2 == 0) thesis_fleet[0] else thesis_fleet[1];+ const r = bd.analyze(a, &wide);+ try std.testing.expectEqual(@as(usize, bd.max_briefs), r.n);++ // A very long brief is read to max_words and no further.+ const long = try a.alloc(u8, 64 * 1024);+ for (long, 0..) |*c, i| c.* = if (i % 6 == 5) ' ' else @as(u8, 'a') + @as(u8, @intCast(i % 26));+ const longs = [_][]const u8{ long, long, long };+ try std.testing.expect(bd.analyze(a, &longs).warn);+}++// ── the sibling-spawn batch path ────────────────────────────────────────────+const tools = @import("tools.zig");++/// Build a runTools-shaped batch from raw JSON argument objects.+fn batch(a: std.mem.Allocator, names: []const []const u8, args: []const []const u8) ![]tools.ToolCall {+ const calls = try a.alloc(tools.ToolCall, names.len);+ for (calls, names, args) |*c, name, arg| {+ const parsed = try std.json.parseFromSlice(std.json.Value, a, arg, .{});+ c.* = .{ .id = "t", .name = name, .input = parsed.value };+ }+ return calls;+}++/// One JSON-encoded string (a fresh Stringify per value: one instance is+/// good for exactly one top-level value).+fn jsonStr(a: std.mem.Allocator, s: []const u8) ![]const u8 {+ var aw: std.Io.Writer.Allocating = .init(a);+ var st: std.json.Stringify = .{ .writer = &aw.writer };+ try st.write(s);+ return aw.writer.buffered();+}++fn spawnArgs(a: std.mem.Allocator, prompt: []const u8) ![]const u8 {+ return std.fmt.allocPrint(a, "{{\"description\":\"v\",\"prompt\":{s}}}", .{try jsonStr(a, prompt)});+}++fn personaArgs(a: std.mem.Allocator, prompt: []const u8, genome: []const u8) ![]const u8 {+ return std.fmt.allocPrint(a, "{{\"prompt\":{s},\"system_prompt\":{s}}}", .{ try jsonStr(a, prompt), try jsonStr(a, genome) });+}++test "#382: three sibling subagent spawns in one batch are a fleet too" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();++ const args = [_][]const u8{+ try spawnArgs(a, reskin_fleet[0]),+ try spawnArgs(a, reskin_fleet[1]),+ try spawnArgs(a, reskin_fleet[2]),+ };+ const names = [_][]const u8{ "subagent", "subagent", "subagent" };+ const calls = try batch(a, &names, &args);+ var results = [_]tools.ExecResult{+ .{ .text = "first result", .is_error = false },+ .{ .text = "second result", .is_error = false },+ .{ .text = "third result", .is_error = false },+ };+ const ext = [_]usize{ 0, 1, 2 };+ bd.noteSiblingBatch(a, null, calls, &ext, &results);++ // The note rides on the FIRST sibling's result — the only channel a tool+ // batch has back to the root — and never replaces what that spawn said.+ try std.testing.expect(std.mem.startsWith(u8, results[0].text, "diversity warning: 3 variant briefs"));+ try std.testing.expect(std.mem.endsWith(u8, results[0].text, "first result"));+ // Siblings are untouched: one note per batch, not one per spawn.+ try std.testing.expectEqualStrings("second result", results[1].text);+ try std.testing.expectEqualStrings("third result", results[2].text);+ // Warn-only here as well: nothing is marked failed.+ for (results) |r| try std.testing.expect(!r.is_error);+}++test "#382: a sibling batch that is not a variant fleet is left alone" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();++ const ext3 = [_]usize{ 0, 1, 2 };++ // Distinct theses — quiet.+ const varied = [_][]const u8{+ try spawnArgs(a, thesis_fleet[0]),+ try spawnArgs(a, thesis_fleet[1]),+ try spawnArgs(a, thesis_fleet[2]),+ };+ const sub3 = [_][]const u8{ "subagent", "subagent", "subagent" };+ var r1 = [_]tools.ExecResult{ .{ .text = "a", .is_error = false }, .{ .text = "b", .is_error = false }, .{ .text = "c", .is_error = false } };+ bd.noteSiblingBatch(a, null, try batch(a, &sub3, &varied), &ext3, &r1);+ try std.testing.expectEqualStrings("a", r1[0].text);++ // Two near-identical spawns alongside a bash call: only TWO spawns, so+ // there is no fleet — a batch is not made a fleet by its size.+ const mixed_args = [_][]const u8{+ try spawnArgs(a, reskin_fleet[0]),+ try spawnArgs(a, reskin_fleet[1]),+ "{\"command\":\"ls\"}",+ };+ const mixed_names = [_][]const u8{ "subagent", "subagent", "bash" };+ var r2 = [_]tools.ExecResult{ .{ .text = "a", .is_error = false }, .{ .text = "b", .is_error = false }, .{ .text = "c", .is_error = false } };+ bd.noteSiblingBatch(a, null, try batch(a, &mixed_names, &mixed_args), &ext3, &r2);+ try std.testing.expectEqualStrings("a", r2[0].text);++ // A spawn with no prompt is not counted, and the note lands on the first+ // spawn that IS counted rather than on index 0 blindly.+ const gappy_args = [_][]const u8{+ "{\"command\":\"ls\"}",+ try spawnArgs(a, reskin_fleet[0]),+ try spawnArgs(a, reskin_fleet[1]),+ try spawnArgs(a, reskin_fleet[2]),+ };+ const gappy_names = [_][]const u8{ "bash", "subagent", "subagent", "subagent" };+ var r3 = [_]tools.ExecResult{ .{ .text = "ls out", .is_error = false }, .{ .text = "a", .is_error = false }, .{ .text = "b", .is_error = false }, .{ .text = "c", .is_error = false } };+ const ext4 = [_]usize{ 0, 1, 2, 3 };+ bd.noteSiblingBatch(a, null, try batch(a, &gappy_names, &gappy_args), &ext4, &r3);+ try std.testing.expectEqualStrings("ls out", r3[0].text);+ try std.testing.expect(std.mem.startsWith(u8, r3[1].text, "diversity warning:"));++ // Same task, three personas: judged on the personas, so quiet (the+ // sibling path resolves `system_prompt`/`agent` exactly as workflow does).+ var persona_args: [3][]const u8 = undefined;+ for (&persona_args, shape_c_genomes) |*pa, genome| pa.* = try personaArgs(a, shape_c_prompt, genome.?);+ var r4 = [_]tools.ExecResult{ .{ .text = "a", .is_error = false }, .{ .text = "b", .is_error = false }, .{ .text = "c", .is_error = false } };+ bd.noteSiblingBatch(a, null, try batch(a, &sub3, &persona_args), &ext3, &r4);+ try std.testing.expectEqualStrings("a", r4[0].text);+}++test "#382: percent rounds the mean for the human-facing line" {+ try std.testing.expectEqual(@as(u64, 0), (bd.Report{ .mean = 0 }).percent());+ try std.testing.expectEqual(@as(u64, 62), (bd.Report{ .mean = 0.6191 }).percent());+ try std.testing.expectEqual(@as(u64, 100), (bd.Report{ .mean = 1.0 }).percent());+}diff --git a/src/shapes.zig b/src/shapes.zigindex 18a072a3..d75024db 100644--- a/src/shapes.zig+++ b/src/shapes.zig@@ -128,6 +128,17 @@ pub const shape_catalog_note =\\ each item flows independently, so no item waits on any other\\E feature — build something new:\\ scope → implement → review+ \\F concept-fleet — N parallel DESIGN variants of one surface (page, deck, view):+ \\ variants each brief carries (1) a one-sentence design THESIS naming its+ \\ compositional idea (editorial parallax / sticky crossfades /+ \\ kinetic typography / scroll-scrubbed chapters / horizontal rail),+ \\ (2) exactly ONE signature interaction or motion system — never+ \\ stack progress bars + particles + cursor effects + dot rails ++ \\ blobs + line reveals, (3) its OWN route and files (/v1, /v2, …),+ \\ shared implementation off-limits. Theses must differ in+ \\ COMPOSITION, not decoration: one template restyled with a new+ \\ hue/particle/font pairing is ONE concept, not N. Leave every+ \\ variant unmerged until the user picks.\\\\Scale to the ask: "find bugs" is 3 finders + 1 verify; "thoroughly audit" is\\6 finders + 3-vote adversarial verify + synthesize. Use phases only when a@@ -215,12 +226,45 @@ test "#296: no canonical slot is reachable only through a pipeline stage" {try std.testing.expectEqualStrings("", canonicalSlot("transform each file"));}-test "shape catalog covers all five shapes and stays within a sane token budget" {- for ([_][]const u8{ "A review/audit", "B research/understand", "C design/solve", "D migration/mechanical", "E feature" }) |shape| {+test "shape catalog covers all six shapes and stays within a sane token budget" {+ for ([_][]const u8{ "A review/audit", "B research/understand", "C design/solve", "D migration/mechanical", "E feature", "F concept-fleet" }) |shape| {try std.testing.expect(std.mem.indexOf(u8, shape_catalog_note, shape) != null);}- // It rides on every ultracode turn; keep it from silently ballooning.- try std.testing.expect(shape_catalog_note.len < 2048);+ // Keep it from silently ballooning. Raised from 2048 once, for F (#382):+ // shape F is the longest entry in the catalog because it is the only one+ // whose value is in the CONTRACT each brief must carry, not in the phase+ // names — a two-line "N design variants, parallel" F would be exactly the+ // instruction the failing run already followed. #326 also changed what+ // this budget costs: the catalog is composed into sys_ultra once rather+ // than re-pasted per turn, so it is paid on the cached prefix.+ try std.testing.expect(shape_catalog_note.len < 3072);+}++test "#382: shape F carries the contract that separates a concept fleet from a reskin" {+ const f = std.mem.indexOf(u8, shape_catalog_note, "F concept-fleet").?;+ const entry = shape_catalog_note[f..std.mem.indexOf(u8, shape_catalog_note, "Scale to the ask").?];+ // The three things each brief MUST carry. Losing any one of them is how+ // the production failure happened: ten briefs, one template, decoration+ // deltas — every one of them "a design variant" by a looser contract.+ try std.testing.expect(std.mem.indexOf(u8, entry, "one-sentence design THESIS") != null);+ try std.testing.expect(std.mem.indexOf(u8, entry, "exactly ONE signature interaction or motion system") != null);+ try std.testing.expect(std.mem.indexOf(u8, entry, "OWN route and files") != null);+ try std.testing.expect(std.mem.indexOf(u8, entry, "shared implementation off-limits") != null);+ // The anti-stacking list is enumerated rather than implied: "one signature+ // system" alone reads as satisfiable by a page that has all six.+ for ([_][]const u8{ "progress bars", "particles", "cursor effects", "dot rails", "blobs", "line reveals" }) |decoration| {+ try std.testing.expect(std.mem.indexOf(u8, entry, decoration) != null);+ }+ // The distinction the gate in brief_diversity.zig measures, stated where+ // the model reads it BEFORE spawning rather than only in the warning after.+ try std.testing.expect(std.mem.indexOf(u8, entry, "COMPOSITION, not decoration") != null);+ try std.testing.expect(std.mem.indexOf(u8, entry, "ONE concept, not N") != null);+ // Variants are a menu, not a merge queue.+ try std.testing.expect(std.mem.indexOf(u8, entry, "unmerged until the user picks") != null);+ // F is a phases shape naming a canonical slot, so its round is scoreable+ // (#296): a shape whose only slot were off-vocabulary could never accrue+ // fitness, which is the trap `transform` fell into.+ try std.testing.expectEqualStrings("variants", canonicalSlot("variants each brief carries"));}test "shape catalog never tells a dependent chain to isolate into worktrees" {diff --git a/src/test_hooks.zig b/src/test_hooks.zigindex 648a69e2..8d540a95 100644--- a/src/test_hooks.zig+++ b/src/test_hooks.zig@@ -71,6 +71,11 @@ const session_tests = @import("session_tests.zig");// one predicate from it, which analyses the file but does not run its tests.const acp = @import("acp.zig");+// #382: moved off agent_tools.zig when the sibling-spawn diversity check+// needed two lines there and the file was at exactly 600. The tests are+// unchanged and still reachable — this is the file that exists for that.+const agent_eval_control_tests = @import("agent_eval_control_tests.zig");+// #345: the global-vs-project MCP config merge. mcp.zig does reference its// decls, but the hook makes the coverage explicit rather than contingent on// that staying true.@@ -106,4 +111,5 @@ test {_ = session_tests;_ = mcp_config;_ = acp;+ _ = agent_eval_control_tests;}diff --git a/src/workflow.zig b/src/workflow.zigindex 8644b768..6d471b61 100644--- a/src/workflow.zig+++ b/src/workflow.zig@@ -40,6 +40,7 @@ const Isolation = fleet.Isolation; // #276 P0-1const route_policy = @import("route_policy.zig"); // #372 (shape, role) policy cellsconst route_phase = @import("route_phase.zig"); // #376 one learned seat per phaseconst route_trace = @import("route_trace.zig"); // #372 per-worker routing trace+const brief_diversity = @import("brief_diversity.zig"); // #382 fleet-brief similarity gateconst telemetry = @import("telemetry.zig");// #63: stable workflow/phase/task ids + the additive `workflow_progress`// JSONL event, so the REPL can map a run from state instead of scraping the@@ -480,6 +481,7 @@ pub fn execWorkflow(ctx: ToolCtx, input: Value) !ToolOutput {}}+ const diversity = brief_diversity.check(arena, ctx.tracer, title, raws, overrides); // #382: every brief in hand, nothing spawned yet// Join ALL tasks before any fallible work, so an early error return// can never abandon running subagents or free their result slots.const futures = try arena.alloc(Io.Future(ToolOutput), tasks.len);@@ -566,7 +568,7 @@ pub fn execWorkflow(ctx: ToolCtx, input: Value) !ToolOutput {// open (it submits niche=""). Gated on the fleet — no judge cost otherwise.scoreVariants(ctx, arena, seat, prompts, raws, overrides, niches, outputs);- tallies[phase_no - 1] = .{ .phase_no = phase_no, .total_phases = phases.len, .title = title, .ok = tasks.len - phase_failed, .total = tasks.len, .retried = nf };+ tallies[phase_no - 1] = .{ .phase_no = phase_no, .total_phases = phases.len, .title = title, .ok = tasks.len - phase_failed, .total = tasks.len, .retried = nf, .diversity = diversity };// Divide the {{prev}} budget across THIS phase's own task count so a// wide phase's total contribution to the next phase's prompt stays neardiff --git a/src/workflow_progress.zig b/src/workflow_progress.zigindex 0eaf7c04..1e02035a 100644--- a/src/workflow_progress.zig+++ b/src/workflow_progress.zig@@ -149,6 +149,13 @@ pub const PhaseTally = struct {total: usize,retried: usize,skipped_when: ?[]const u8 = null,+ /// #382 — the fleet-diversity note for this phase, or "" when its briefs+ /// were varied enough (or too few to judge). Carried on the tally rather+ /// than printed at the phase, because the manifest is the one part of a+ /// workflow result the ROOT reliably reads: intermediate phases are+ /// summarised into {{prev}} for the NEXT phase, and a note meant for the+ /// orchestrator must not end up in a worker's prompt instead.+ diversity: []const u8 = "",};/// Build the hard-stop text for a phase where every task failed: the@@ -181,6 +188,7 @@ pub fn buildManifest(arena: Allocator, tallies: []const PhaseTally) ![]const u8} else {try aw.writer.print("phase {d}/{d} {s}: {d}/{d} ok, {d} retried\n", .{ t.phase_no, t.total_phases, t.title, t.ok, t.total, t.retried });}+ if (t.diversity.len > 0) try aw.writer.print("{s}\n", .{t.diversity});}return std.mem.trimEnd(u8, aw.writer.buffered(), "\n");}diff --git a/src/workflow_test.zig b/src/workflow_test.zigindex ced7326e..d32fbc97 100644--- a/src/workflow_test.zig+++ b/src/workflow_test.zig@@ -163,6 +163,32 @@ test "buildManifest reports ok/retried per phase and SKIPPED for a gated phase (try std.testing.expect(std.mem.indexOf(u8, block, "phase 2/3 Verify: 0/2") == null);}+test "#382: a phase's diversity note rides the manifest, under its own phase line" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();++ // The manifest is where the ROOT reads a run's shape, so it is where a+ // note addressed to the orchestrator belongs — a phase's own results are+ // summarised into {{prev}} and go to the next phase's WORKERS instead.+ const note = "diversity warning: 3 variant briefs are ~62% similar — proceed if intentional.";+ const tallies = [_]PhaseTally{+ .{ .phase_no = 1, .total_phases = 2, .title = "variants", .ok = 3, .total = 3, .retried = 0, .diversity = note },+ .{ .phase_no = 2, .total_phases = 2, .title = "build", .ok = 1, .total = 1, .retried = 0 },+ };+ const block = try buildManifest(a, &tallies);++ const phase1 = std.mem.indexOf(u8, block, "phase 1/2 variants: 3/3 ok, 0 retried").?;+ const warned = std.mem.indexOf(u8, block, note).?;+ const phase2 = std.mem.indexOf(u8, block, "phase 2/2 build").?;+ try std.testing.expect(phase1 < warned and warned < phase2);++ // A quiet phase adds nothing at all — no "diversity ok" line to train the+ // root to skim past.+ const quiet = [_]PhaseTally{.{ .phase_no = 1, .total_phases = 1, .title = "variants", .ok = 3, .total = 3, .retried = 0 }};+ try std.testing.expectEqualStrings("## workflow\nphase 1/1 variants: 3/3 ok, 0 retried", try buildManifest(a, &quiet));+}+test "pipelinePrompt substitutes {{item}}/{{prev}} and appends when omitted (#3)" {var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);defer arena_state.deinit();