Skip to content

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

Python

feat(pipeline): stages accrue judge-free stage-level fitness — transform rejoins canonical_slots (#296)

justrach5dac8081258c
diff --git a/src/pipeline_score.zig b/src/pipeline_score.zig
new file mode 100644
index 00000000..d9952f6c
--- /dev/null
+++ b/src/pipeline_score.zig
@@ -0,0 +1,186 @@
+//! #296 — judge-free stage-level fitness for pipeline runs (shape D).
+//!
+//! Pipelines were the one execution mode with no scoring path at all: stages
+//! call runSub directly and never reach scoreVariants, so a slot the catalog
+//! named only inside shape D advertised a MAP-Elites cell nothing could ever
+//! fill (`transform` was dropped from canonical_slots for exactly that).
+//!
+//! The honest unit is the STAGE, never the item. One stage runs ONE genome
+//! (one system_prompt override, one prompt template) over N items that
+//! differ per worker BY DESIGN — ranking items against each other would
+//! confound item difficulty with genome quality, the per-task variation
+//! #290 forbids attributing fitness across. So each stage files exactly one
+//! row per run: the fraction of items that completed the stage without
+//! error, under the stage's (migration, slot) cell and its one resolved
+//! seat. Judge-free — no model call is ever spent on it.
+//!
+//! Scale note: migration cells hold completion fractions while phase cells
+//! hold judged quality. Both are [0,1] and they never pool — only pipeline
+//! stages write shape=migration (shapeOfPhases cannot produce it), so
+//! learnedRung always compares like with like inside one cell.
+//!
+//! Local capture only (the #372 discipline): rows go through
+//! route_trace.captureVariant into the local DGM archive, which runs with
+//! telemetry OFF too. Nothing here reaches scoreEvent/fleetEvent, so no new
+//! bytes can leave the machine. The edit-landed signal (edit_contract's
+//! porcelain probe) is deliberately NOT folded in: pipeline briefs carry no
+//! contract note, and item chains interleave in one shared cwd, so a
+//! per-stage snapshot pair could not attribute a tree change to one stage.
+
+const std = @import("std");
+
+const main_mod = @import("main.zig");
+const route_policy = @import("route_policy.zig");
+const route_trace = @import("route_trace.zig");
+const scoring = @import("scoring.zig");
+const util = @import("util.zig");
+const Provider = @import("provider.zig").Provider;
+
+/// Per-stage outcome counters, shared by every item's chain. Chains run
+/// concurrently on pool threads; the futures join in workflow_pipeline.run
+/// is the read barrier, so monotonic increments suffice.
+pub const StageStat = struct {
+ /// Items whose chain reached this stage and ran it.
+ attempted: std.atomic.Value(u32) = .init(0),
+ /// Items whose attempt (including the one #2 retry) ended without error.
+ ok: std.atomic.Value(u32) = .init(0),
+
+ pub fn noteAttempt(self: *StageStat) void {
+ _ = self.attempted.fetchAdd(1, .monotonic);
+ }
+
+ pub fn noteOk(self: *StageStat) void {
+ _ = self.ok.fetchAdd(1, .monotonic);
+ }
+};
+
+/// One stage's score, or null when the run carries no signal: a stage no
+/// item reached says nothing about its genome, and a total failure is
+/// skipped rather than filed as 0 (scoreVariants' s<=0 rule — an all-fail
+/// stage is far more often an environment failure than genome evidence,
+/// and a 0 row would poison the cell mean).
+pub fn stageScore(attempted: u32, ok: u32) ?f64 {
+ if (attempted == 0 or ok == 0 or ok > attempted) return null;
+ return @as(f64, @floatFromInt(ok)) / @as(f64, @floatFromInt(attempted));
+}
+
+/// File ONE fitness row for one stage of one pipeline run. `provider` is the
+/// stage's resolved seat — every item ran on it, stage-uniform (#290/#376) —
+/// and `genome_text` the stage's one configuration (its system_prompt
+/// override, else its prompt template; only its fingerprint is recorded).
+/// Returns whether a row was written, so the call site and the tests can
+/// tell a gated round from a scored one.
+pub fn captureStage(provider: Provider, label: []const u8, niche: []const u8, genome_text: []const u8, stat: *const StageStat) bool {
+ if (!main_mod.g_fleet) return false;
+ // An off-vocabulary stage stays uncelled, exactly like an off-vocabulary
+ // phase title: execution is unaffected, only fitness accrual needs a slot.
+ if (route_policy.roleOf(label, niche).len == 0) return false;
+ const s01 = stageScore(stat.attempted.load(.monotonic), stat.ok.load(.monotonic)) orelse return false;
+ const fp = scoring.promptFingerprint(genome_text);
+ var niche_buf: [64]u8 = undefined;
+ const clean = scoring.sanitizeMetaField(&niche_buf, util.utf8Prefix(niche, 64));
+ route_trace.captureVariant(provider, .migration, label, clean, &fp, s01);
+ return true;
+}
+
+// ── tests ──────────────────────────────────────────────────────────────────
+
+const Io = std.Io;
+const trace = @import("trace.zig");
+
+fn codex(model: []const u8) Provider {
+ return .{ .id = "codex", .kind = .responses, .auth = .bearer, .url = "", .api_key = "sk-test", .model = model, .context = 272_000 };
+}
+
+/// A real Trajectory writing real rows into memory, installed as the live
+/// archive sink. Restore via the returned prior value.
+fn installTraj(traj: *trace.Trajectory) ?*trace.Trajectory {
+ const saved = trace.g_traj;
+ trace.g_traj = traj;
+ return saved;
+}
+
+test "#296: a pipeline stage accrues exactly ONE fitness row, celled on its slot — never per item" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+
+ var out: Io.Writer.Allocating = .init(a);
+ var traj: trace.Trajectory = .{ .io = std.testing.io, .gpa = std.testing.allocator, .out = &out.writer, .start = Io.Timestamp.now(std.testing.io, .awake) };
+ defer traj.deinit();
+ const saved = installTraj(&traj);
+ defer trace.g_traj = saved;
+ const saved_fleet = main_mod.g_fleet;
+ main_mod.g_fleet = true;
+ defer main_mod.g_fleet = saved_fleet;
+
+ // Five items reached the stage, four finished clean: five per-item
+ // outcomes, ONE stage-level row at 0.8.
+ var stat: StageStat = .{};
+ for (0..5) |_| stat.noteAttempt();
+ for (0..4) |_| stat.noteOk();
+ try std.testing.expect(captureStage(codex("gpt-5.6-terra"), "transform each file", "transform each file", "Apply the codemod; keep behavior identical.", &stat));
+ const rows = out.writer.buffered();
+ try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, rows, "\"kind\":\"score\""));
+
+ // And the row round-trips into exactly the cell the policy learns from —
+ // `transform` claims a fillable MAP-Elites cell, closing the #296 gap.
+ const cells = route_policy.foldCells(a, rows);
+ try std.testing.expectEqual(@as(usize, 1), cells.len);
+ try std.testing.expectEqualStrings("migration", cells[0].shape);
+ try std.testing.expectEqualStrings("transform", cells[0].role);
+ try std.testing.expectEqualStrings("mid", cells[0].tier);
+ try std.testing.expectEqualStrings("gpt-5.6-terra", cells[0].model);
+ try std.testing.expectEqual(@as(u32, 1), cells[0].n);
+ try std.testing.expectApproxEqAbs(@as(f64, 0.8), cells[0].mean(), 1e-9);
+}
+
+test "#296: rounds with no signal file nothing — unreached, all-fail, off-vocabulary, fleet off" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+
+ var out: Io.Writer.Allocating = .init(arena_state.allocator());
+ var traj: trace.Trajectory = .{ .io = std.testing.io, .gpa = std.testing.allocator, .out = &out.writer, .start = Io.Timestamp.now(std.testing.io, .awake) };
+ defer traj.deinit();
+ const saved = installTraj(&traj);
+ defer trace.g_traj = saved;
+ const saved_fleet = main_mod.g_fleet;
+ main_mod.g_fleet = true;
+ defer main_mod.g_fleet = saved_fleet;
+
+ // A stage no item reached says nothing about its genome.
+ var unreached: StageStat = .{};
+ try std.testing.expect(!captureStage(codex("gpt-5.6-terra"), "transform each file", "", "g", &unreached));
+ // Total failure is skipped, not filed as a cell-poisoning 0.
+ var all_fail: StageStat = .{};
+ all_fail.noteAttempt();
+ try std.testing.expect(!captureStage(codex("gpt-5.6-terra"), "transform each file", "", "g", &all_fail));
+ // An off-vocabulary stage runs fine but stays uncelled, like a phase.
+ var clean: StageStat = .{};
+ clean.noteAttempt();
+ clean.noteOk();
+ try std.testing.expect(!captureStage(codex("gpt-5.6-terra"), "polish the files", "some-persona", "g", &clean));
+ // The fleet master switch gates local capture the same way it gates
+ // scoreVariants.
+ main_mod.g_fleet = false;
+ try std.testing.expect(!captureStage(codex("gpt-5.6-terra"), "transform each file", "", "g", &clean));
+ try std.testing.expectEqual(@as(usize, 0), std.mem.count(u8, out.writer.buffered(), "\"kind\":\"score\""));
+}
+
+test "#296/#290 firewall: capture is per STAGE after the join, and every item runs the stage's one seat" {
+ // The property is about the CALL SITE — no per-item path may write
+ // fitness, and no item may influence its own model — so it is pinned as
+ // source text, the same way #376 pinned the phase-seat invariant.
+ const src = @embedFile("workflow_pipeline.zig");
+ // Exactly one capture call, sitting AFTER the all-chains join: per-item
+ // outcomes are folded into it and can never become per-item rows.
+ try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, src, "pipeline_score.captureStage("));
+ const join_at = std.mem.indexOf(u8, src, "out.* = fut.await(ctx.io)").?;
+ try std.testing.expect(std.mem.indexOf(u8, src, "pipeline_score.captureStage(").? > join_at);
+ // The seat is resolved once per stage, in the parse loop, before any
+ // chain spawns — route_phase.forPhase, the same door phases go through.
+ const seat_at = std.mem.indexOf(u8, src, "sp.seat = route_phase.forPhase(").?;
+ try std.testing.expect(seat_at < std.mem.indexOf(u8, src, "ctx.io.async(pipelineChain").?);
+ // Both spawn attempts — first try and retry — receive that seat verbatim.
+ try std.testing.expectEqual(@as(usize, 2), std.mem.count(u8, src, "st.isolation_fallback, st.seat.pin, null)"));
+}
diff --git a/src/route_policy.zig b/src/route_policy.zig
index 542c5103..d77344ed 100644
--- a/src/route_policy.zig
+++ b/src/route_policy.zig
@@ -75,7 +75,7 @@ pub const Shape = enum {
review, // A — find/verify/synthesize
research, // B — sweep/synthesize
design, // C — variants/build
- migration, // D — pipeline (transform/verify); never scored, see #296
+ migration, // D — pipeline (transform/verify); stage-level scored, see #296
feature, // E — scope/implement/review
adhoc,
diff --git a/src/scoring_slot_test.zig b/src/scoring_slot_test.zig
index 4a710f93..18cd0be3 100644
--- a/src/scoring_slot_test.zig
+++ b/src/scoring_slot_test.zig
@@ -57,11 +57,11 @@ test "canonicalSlot + telemetrySlot compose: a real phase title reaches a cell o
try std.testing.expectEqualStrings("find", compose("find security bugs"));
try std.testing.expectEqualStrings("verify", compose("verify each finding"));
try std.testing.expectEqualStrings("synthesize", compose("Synthesize the results"));
- // #296 — `transform` is a PIPELINE stage label, and pipeline stages never
- // reach scoreVariants, so it was dropped from the vocabulary rather than
- // left advertising a cell nothing could fill. It is now uncelled like any
- // other off-vocabulary title; see the D-shape comment in shapes.zig.
- try std.testing.expectEqualStrings("", compose("transform each file"));
+ // #296 — `transform` is a PIPELINE stage label. It was dropped while no
+ // stage could be scored, and rejoined the vocabulary with the stage-level
+ // capture (pipeline_score.zig): a transform stage now reaches its cell
+ // like any phase slot; see the D-shape comment in shapes.zig.
+ try std.testing.expectEqualStrings("transform", compose("transform each file"));
// A customer name in a phase title reaches no cell and leaves no plaintext.
try std.testing.expectEqualStrings("", compose("Migrate Acme billing schema"));
// And the composed result is always vocabulary-or-empty, never caller text.
diff --git a/src/shapes.zig b/src/shapes.zig
index a0089b42..d2d2f498 100644
--- a/src/shapes.zig
+++ b/src/shapes.zig
@@ -40,17 +40,16 @@ pub const canonical_slots = [_][]const u8{
// C — design/solve
"variants",
"build",
- // D — migration/mechanical has NO slot: shape D is a pipeline, and a
- // pipeline stage cannot be scored (#296). `transform` used to sit here and
- // advertise a cell nothing could ever fill — pipeline stages call runSub
- // directly and never reach scoreVariants, the one path that derives a slot,
- // so the only way to score one was to disobey the catalog and run it as a
- // phase. Dropped rather than scored: a tournament needs an axis a stage
- // does not have. One stage carries ONE system_prompt, so its N "variants"
- // would be N ITEMS — the same genome on different inputs — and ranking
- // those measures item difficulty, not prompt quality. Restore `transform`
- // only together with per-stage prompt variants; migration EXECUTION is
- // unaffected either way, the catalog still names the stage below.
+ // D — migration/mechanical: scored at STAGE level, never per item (#296).
+ // A stage carries ONE genome run over items that differ BY DESIGN, so a
+ // judge tournament across items would rank item difficulty, not prompt
+ // quality — the per-task variation #290 forbids attributing fitness
+ // across. pipeline_score.captureStage instead files one judge-free row
+ // per stage per run (item completion fraction) under the stage's
+ // (migration, slot) cell and its one #376 seat, so `transform` claims a
+ // cell that pipeline runs actually fill. The #296 test below pins that
+ // path: remove it and this slot must leave the vocabulary again.
+ "transform",
// E — feature
"scope",
"implement",
@@ -205,28 +204,34 @@ test "shape catalog names every canonical slot it depends on" {
}
}
-test "#296: no canonical slot is reachable only through a pipeline stage" {
- // Only the PHASES path scores: scoreVariants derives the slot with
- // canonicalSlot(phase title), and pipeline stages call runSub directly.
- // So a slot the catalog names ONLY inside shape D (the pipeline shape)
- // declares a MAP-Elites cell nothing can ever fill. `transform` was exactly
- // that, and this pins it shut — re-adding it to canonical_slots turns this
- // red, because D's stage list is the only place the catalog says the word.
+test "#296: every canonical slot is reachable by a scoring path — phases OR the stage capture" {
+ // Two scoring paths exist. PHASES: scoreVariants derives the slot with
+ // canonicalSlot(phase title). STAGES: pipeline_score.captureStage files
+ // one stage-level row per run under the stage's slot. A slot the catalog
+ // names ONLY inside shape D (the pipeline shape) therefore needs the
+ // stage path alive, or it declares a MAP-Elites cell nothing can ever
+ // fill — the trap `transform` sat in while pipelines went unscored.
+ // Adding a slot no path reaches turns this red, by design.
const d = std.mem.indexOf(u8, shape_catalog_note, "D migration/mechanical").?;
const e = std.mem.indexOf(u8, shape_catalog_note, "E feature").?;
// The trailing prose (scaling advice, the isolation warning) names stages
// by example, so the E window has to stop before it or this proves nothing.
const tail = std.mem.indexOf(u8, shape_catalog_note, "Scale to the ask").?;
+ // The stage path, pinned as source text: workflow_pipeline.run folds each
+ // stage's per-item outcomes into ONE captureStage call. Removing that
+ // call re-opens the gap for every slot only shape D names.
+ const stage_path_alive = std.mem.indexOf(u8, @embedFile("workflow_pipeline.zig"), "pipeline_score.captureStage(") != null;
for (canonical_slots) |slot| {
const in_a_phase_shape = std.mem.indexOf(u8, shape_catalog_note[0..d], slot) != null or
std.mem.indexOf(u8, shape_catalog_note[e..tail], slot) != null;
- try std.testing.expect(in_a_phase_shape);
+ const in_the_pipeline_shape = std.mem.indexOf(u8, shape_catalog_note[d..e], slot) != null;
+ try std.testing.expect(in_a_phase_shape or (in_the_pipeline_shape and stage_path_alive));
}
- // Migration EXECUTION is untouched: the catalog still tells the model to
- // run a `transform` stage, it just no longer claims a fitness cell for it.
- try std.testing.expect(std.mem.indexOf(u8, shape_catalog_note, "transform") != null);
- try std.testing.expectEqualStrings("", canonicalSlot("transform"));
- try std.testing.expectEqualStrings("", canonicalSlot("transform each file"));
+ // `transform` claims its cell through the stage path ALONE: the catalog
+ // names it only in D, and it is celled again — the #296 gap is closed.
+ try std.testing.expect(stage_path_alive);
+ try std.testing.expectEqualStrings("transform", canonicalSlot("transform"));
+ try std.testing.expectEqualStrings("transform", canonicalSlot("transform each file"));
}
test "shape catalog covers all six shapes and stays within a sane token budget" {
@@ -266,7 +271,7 @@ test "#382: shape F carries the contract that separates a concept fleet from a r
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.
+ // fitness — the trap `transform` sat in until the stage capture existed.
try std.testing.expectEqualStrings("variants", canonicalSlot("variants each brief carries"));
}
diff --git a/src/test_hooks.zig b/src/test_hooks.zig
index 81575dc3..0ce37f16 100644
--- a/src/test_hooks.zig
+++ b/src/test_hooks.zig
@@ -105,6 +105,9 @@ const orchestration_policy = @import("orchestration_policy.zig");
const orchestration_policy_tests = @import("orchestration_policy_tests.zig");
const orchestration_rows = @import("orchestration_rows.zig");
const workflow_pipeline = @import("workflow_pipeline.zig");
+// #296: the pipeline stage-level fitness capture. Reached in production only
+// through workflow_pipeline.run's CALL, so its tests need the hook.
+const pipeline_score = @import("pipeline_score.zig");
// #364: shutdown-phase timings. Production reaches it from readline.zig,
// session.zig, mcp.zig, telemetry.zig and startup_timing.zig, so its coverage
@@ -155,4 +158,5 @@ test {
_ = orchestration_policy_tests;
_ = orchestration_rows;
_ = workflow_pipeline;
+ _ = pipeline_score;
}
diff --git a/src/workflow_pipeline.zig b/src/workflow_pipeline.zig
index a6ee012c..c6fe4c6a 100644
--- a/src/workflow_pipeline.zig
+++ b/src/workflow_pipeline.zig
@@ -35,7 +35,9 @@ const failureAllowsRetry = subagent_run.failureAllowsRetry;
const fleet = @import("fleet.zig");
const Isolation = fleet.Isolation;
const route_policy = @import("route_policy.zig");
+const route_phase = @import("route_phase.zig"); // #376 one learned seat per stage
const route_trace = @import("route_trace.zig");
+const pipeline_score = @import("pipeline_score.zig"); // #296 stage-level fitness
const telemetry = @import("telemetry.zig");
const wfp = @import("workflow_progress.zig");
const escalation = @import("escalation.zig");
@@ -59,6 +61,12 @@ const StageSpec = struct {
isolation: Isolation = .shared_cwd, // #276 P0-1
isolation_fallback: bool = false,
role: []const u8 = "", // #372: this stage's canonical slot, for its route trace
+ /// #376 applied to stages: the ONE seat every item's worker for this
+ /// stage runs on, resolved once in run(). Stage-uniform, so #290's
+ /// no-per-task-variation rule holds across items exactly as it does
+ /// across a phase's tasks — which is what makes the stage scoreable as
+ /// a unit (#296).
+ seat: route_phase.Seat = .{ .provider = undefined },
};
/// Replace every `needle` in `hay` with `repl` (arena-allocated); returns `hay`
@@ -94,19 +102,23 @@ pub fn pipelinePrompt(arena: Allocator, raw: []const u8, item: []const u8, prev:
/// concurrently. A failed stage is retried once (#2); a stage that still fails
/// ends the chain with a terse marker plus a capped one-line excerpt of its
/// error (#248), rather than feeding the whole error downstream.
-fn pipelineChain(ctx: ToolCtx, item: []const u8, stages: []const StageSpec) ToolOutput {
+fn pipelineChain(ctx: ToolCtx, item: []const u8, stages: []const StageSpec, stats: []pipeline_score.StageStat) ToolOutput {
const gpa = ctx.gpa;
var arena_state = std.heap.ArenaAllocator.init(gpa);
defer arena_state.deinit();
const arena = arena_state.allocator();
var prev: []const u8 = "";
- for (stages, 1..) |st, stage_no| {
+ for (stages, stats, 1..) |st, *stat, stage_no| {
const prompt = pipelinePrompt(arena, st.prompt, item, prev, stage_no) catch |e| return failure(gpa, e);
// #372: say out loud which route this stage worker actually got, and
- // under which cell — an inherited route was invisible before.
- route_trace.emitSpawnProvider(ctx.io, ctx.tracer, st.label, subagent_run.childProvider(ctx.provider, ctx.subagent_provider, ctx.subagent_cross_provider), .{ .shape = .migration, .role = st.role }, if (st.override != null) .workflow_override else route_trace.sessionSource(ctx.subagent_provider != null), st.override, st.niche);
- // null pin: neither #292's per-spawn pins nor #376's phase seat reach a pipeline stage — a chain is never scored (#296), so it has no cell to learn from.
- var out = if (runSub(ctx, "workflow_task", st.label, prompt, st.override, st.niche, st.isolation, st.isolation_fallback, null, null)) |r| r.output else |e| failure(gpa, e);
+ // under which cell. The seat was resolved ONCE per stage in run()
+ // (#376), so every item's worker reports — and runs — the same model;
+ // #292's per-spawn pins still reach `subagent` only.
+ route_trace.emitSpawnProvider(ctx.io, ctx.tracer, st.label, st.seat.provider, st.seat.cellOf(st.niche), st.seat.sourceFor(st.override != null), st.override, st.niche);
+ // Counters only — the fitness fold happens per STAGE after run()'s
+ // join (#296), never here where it would be a per-item row (#290).
+ stat.noteAttempt();
+ var out = if (runSub(ctx, "workflow_task", st.label, prompt, st.override, st.niche, st.isolation, st.isolation_fallback, st.seat.pin, null)) |r| r.output else |e| failure(gpa, e);
if (out.is_error) {
// Only spend the one retry (#2) when the harness's own
// classification hasn't already ruled it out (auth, invalid
@@ -114,7 +126,9 @@ fn pipelineChain(ctx: ToolCtx, item: []const u8, stages: []const StageSpec) Tool
// stay failed below without wasting a second attempt.
if (failureAllowsRetry(out.text)) {
gpa.free(out.text);
- out = if (runSub(ctx, "workflow_retry", st.label, prompt, st.override, st.niche, st.isolation, st.isolation_fallback, null, null)) |r| r.output else |e| failure(gpa, e);
+ // The SAME seat: a retry that changed model would break the
+ // stage uniformity the fitness row attributes to.
+ out = if (runSub(ctx, "workflow_retry", st.label, prompt, st.override, st.niche, st.isolation, st.isolation_fallback, st.seat.pin, null)) |r| r.output else |e| failure(gpa, e);
}
if (out.is_error) {
// #248 — excerpt the stage's own error BEFORE freeing it, so
@@ -132,6 +146,7 @@ fn pipelineChain(ctx: ToolCtx, item: []const u8, stages: []const StageSpec) Tool
};
}
}
+ stat.noteOk();
const duped = arena.dupe(u8, out.text) catch {
gpa.free(out.text);
return failure(gpa, error.OutOfMemory);
@@ -164,10 +179,11 @@ pub fn pipelineIsolationError(stage_index: usize, iso: Isolation) ?[]const u8 {
};
}
-/// What a pipeline of `items` x `stages` will cost, at the default per-stage
-/// role cost. Pipelines are never scored (#296) so their stages carry no
-/// canonical slot to price individually — the flat median is the honest
-/// estimate, and it is the one the study's refactor run would have failed.
+/// What a pipeline of `items` x `stages` will cost, at each stage's role
+/// cost. `transform` rejoined the vocabulary for stage-level SCORING (#296)
+/// but deliberately has no entry in phase_budget's pricing table, so a
+/// mechanical stage is still charged the default median — the estimate the
+/// study's refactor run would have failed, unchanged by the scoring path.
pub fn pipelineEstimate(items: usize, stage_roles: []const []const u8) u64 {
var per_item: u64 = 0;
for (stage_roles) |r| per_item += phase_budget.roleCost(r);
@@ -206,7 +222,9 @@ pub fn run(ctx: ToolCtx, pv: Value, outer_context: []const u8) !ToolOutput {
defer arena_state.deinit();
const arena = arena_state.allocator();
- // Parse stages once — shared (read-only) by every item chain.
+ // Parse stages once — shared (read-only) by every item chain. `base` is
+ // the model every stage worker would have used before #376's seats.
+ const base = subagent_run.childProvider(ctx.provider, ctx.subagent_provider, ctx.subagent_cross_provider);
const stages = try arena.alloc(StageSpec, stage_vals.len);
for (stage_vals, stages, 0..) |sv, *sp, stage_index| {
if (sv != .object) return .{ .text = try gpa.dupe(u8, "each pipeline stage must be an object"), .is_error = true };
@@ -226,6 +244,11 @@ pub fn run(ctx: ToolCtx, pv: Value, outer_context: []const u8) !ToolOutput {
return .{ .text = try gpa.dupe(u8, msg), .is_error = true };
sp.isolation_fallback = fleet.resolveIsolationFallback(so);
sp.role = route_policy.roleOf(sp.label, sp.niche); // #372
+ // #376 for stages: ONE learned seat per stage, shared by every item's
+ // chain — stage-uniform, so #290 holds across items. Same guardrails
+ // as a phase seat: only a ladder-descended session may move, only to
+ // a rung that dominates on the bench sheet, provider-local always.
+ sp.seat = route_phase.forPhase(base, .migration, sp.label, &.{sp.niche}, ctx.subagent_provider != null);
}
// Admission, pipeline flavour. The phases path runs the full escalation
@@ -260,10 +283,19 @@ pub fn run(ctx: ToolCtx, pv: Value, outer_context: []const u8) !ToolOutput {
// return can never abandon a running chain.
const futures = try arena.alloc(Io.Future(ToolOutput), items.len);
const outputs = try arena.alloc(ToolOutput, items.len);
- for (item_strs, futures) |item, *fut| fut.* = ctx.io.async(pipelineChain, .{ ctx, item, stages });
+ const stats = try arena.alloc(pipeline_score.StageStat, stages.len);
+ for (stats) |*s| s.* = .{};
+ for (item_strs, futures) |item, *fut| fut.* = ctx.io.async(pipelineChain, .{ ctx, item, stages, stats });
for (futures, outputs) |*fut, *out| out.* = fut.await(ctx.io);
defer for (outputs) |out| gpa.free(out.text);
+ // #296 — the stage-level fitness fold: one judge-free row per stage per
+ // run, under the stage's (migration, slot) cell and its one seat. After
+ // the join, so per-item outcomes can never become per-item fitness rows
+ // (#290: items differ by design, and ranking them would confound item
+ // difficulty with genome quality). Observation only — nothing reads it.
+ for (stages, stats) |st, *stat| _ = pipeline_score.captureStage(st.seat.provider, st.label, st.niche, st.override orelse st.prompt, stat);
+
var failed: usize = 0;
for (outputs) |out| if (out.is_error) {
failed += 1;