opencode-model-router 2.8.0 → 2.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/CHANGELOG.md +364 -0
  2. package/README.md +20 -0
  3. package/package.json +5 -1
  4. package/src/commands/output.ts +23 -1
  5. package/src/compat/background.ts +2439 -0
  6. package/src/compat/child-session.ts +6 -0
  7. package/src/compat/turn-state.ts +215 -0
  8. package/src/compat/v2-client.ts +136 -17
  9. package/src/compat/v2-hooks.ts +2656 -114
  10. package/src/compat/v2-observations.ts +328 -0
  11. package/src/executor/capacity.ts +362 -0
  12. package/src/executor/child-guards.ts +40 -0
  13. package/src/executor/command.ts +265 -0
  14. package/src/executor/compile/edges.ts +809 -0
  15. package/src/executor/compile/estimate.ts +158 -0
  16. package/src/executor/compile/footprint.ts +829 -0
  17. package/src/executor/compile/index.ts +1080 -0
  18. package/src/executor/compile/parse.ts +1492 -0
  19. package/src/executor/compile/residue.ts +706 -0
  20. package/src/executor/compile/validate.ts +280 -0
  21. package/src/executor/create.ts +672 -0
  22. package/src/executor/expand.ts +551 -0
  23. package/src/executor/git.ts +1214 -0
  24. package/src/executor/host-preamble.ts +17 -0
  25. package/src/executor/instructions.ts +35 -0
  26. package/src/executor/integrate/bisect.ts +73 -0
  27. package/src/executor/integrate/checks.ts +1086 -0
  28. package/src/executor/integrate/land.ts +177 -0
  29. package/src/executor/integrate/phase-suite.ts +407 -0
  30. package/src/executor/integrate/queue.ts +3083 -0
  31. package/src/executor/integrate/run-resolver.ts +19 -0
  32. package/src/executor/launch.ts +652 -0
  33. package/src/executor/ledger.ts +2208 -0
  34. package/src/executor/observations.ts +212 -0
  35. package/src/executor/paths.ts +159 -0
  36. package/src/executor/platform.ts +39 -0
  37. package/src/executor/process-identity.ts +19 -0
  38. package/src/executor/qa-loop.ts +470 -0
  39. package/src/executor/recovery.ts +403 -0
  40. package/src/executor/runtime.ts +6233 -0
  41. package/src/executor/schedule.ts +246 -0
  42. package/src/executor/slots/env.ts +145 -0
  43. package/src/executor/slots/pool.ts +1564 -0
  44. package/src/executor/slots/provision.ts +853 -0
  45. package/src/executor/tool.ts +534 -0
  46. package/src/executor/types.ts +2064 -0
  47. package/src/executor/unattended.ts +488 -0
  48. package/src/guard/store.ts +3 -1
  49. package/src/index.ts +1498 -288
  50. package/src/router/config.ts +776 -25
  51. package/src/router/git-tools.ts +106 -15
  52. package/src/router/leases.ts +1469 -0
  53. package/src/router/logger.ts +44 -32
  54. package/src/router/protocol.ts +40 -10
  55. package/src/router/role-agents.ts +224 -17
  56. package/src/router/roles-config.ts +10 -1
  57. package/src/router/roles.ts +1 -1
  58. package/src/router/run-tools.ts +56 -4
  59. package/src/router/tool-paths.ts +308 -0
  60. package/src/router/work-roots.ts +86 -0
  61. package/src/routing/advisor/findings.ts +25 -5
  62. package/src/routing/classify/index.ts +7 -1
  63. package/src/routing/classify/rules.ts +11 -0
  64. package/src/routing/commands/stats.ts +2 -2
  65. package/src/routing/outcomes/durations.ts +225 -0
  66. package/src/routing/outcomes/index.ts +59 -2
  67. package/src/routing/outcomes/persist.ts +409 -0
  68. package/src/routing/outcomes/stats.ts +170 -11
  69. package/src/routing/outcomes/timings.ts +836 -0
  70. package/src/routing/outcomes/types.ts +98 -0
  71. package/src/routing/roles/approvals.ts +86 -5
  72. package/src/routing/roles/binding.ts +99 -9
  73. package/src/routing/roles/orphans.ts +68 -0
  74. package/src/routing/roles/policy.ts +21 -3
  75. package/src/routing/roles/work-root.ts +3 -1
  76. package/src/routing/wire/dispatch.ts +86 -12
  77. package/src/routing/wire/hint.ts +56 -8
  78. package/src/v2.ts +94 -49
  79. package/src/verify/branch.ts +8 -2
  80. package/src/verify/canonical-path.ts +35 -0
  81. package/src/verify/deterministic.ts +38 -9
  82. package/src/verify/dispatch.ts +64 -28
  83. package/src/verify/exec.ts +52 -9
  84. package/src/verify/pending.ts +1691 -10
  85. package/src/verify/perimeter.ts +12 -6
  86. package/src/verify/plan-task.ts +729 -0
  87. package/src/verify/reference.ts +216 -3
  88. package/src/verify/tree.ts +30 -13
  89. package/src/verify/types.ts +9 -2
  90. package/src/verify/wiring.ts +290 -31
@@ -0,0 +1,177 @@
1
+ // 3.2.5: landing and phase tags. `createLander` returns a structural `Lander` (queue.ts): this module imports types only
2
+ // from checks.ts and queue.ts and receives the instances by injection. Everything here is bounded to the owner checkout
3
+ // (`repo.toplevel`): every probe runs with `-C <toplevel>`, never against another worktree of the same repository.
4
+ // Never forces and never creates a non-fast-forward.
5
+
6
+ import { hardeningArgs } from "../../router/git-tools";
7
+ import { phaseTagName as gitPhaseTagName } from "../git";
8
+ import type { GitOps } from "../git";
9
+ import type { GitRunner, PhaseId, PlanId } from "../types";
10
+ import type { IntegrateGit, WriteGuard } from "./checks";
11
+ import type { LandInspection, LandOutcome, LandRefusal, LandRequest, TagOutcome } from "./queue";
12
+
13
+ const READ_TIMEOUT_MS = 60_000;
14
+
15
+ /** `omr/<planId>/phase/<encoded phaseId>` (3.2.5.a): the encoded, case-fold-safe name of git.ts. */
16
+ export function phaseTagName(planId: PlanId, phaseId: PhaseId): string {
17
+ return gitPhaseTagName(planId, phaseId);
18
+ }
19
+
20
+ export interface LanderDeps {
21
+ git: GitOps; igit: IntegrateGit; guard: WriteGuard;
22
+ /** Hardened runner for the read-only owner-checkout probes (toplevel, HEAD, status); each call uses `-C <toplevel>`. */
23
+ run: GitRunner;
24
+ realpath: (p: string) => Promise<string>; platform: NodeJS.Platform;
25
+ }
26
+
27
+ export interface LanderApi {
28
+ tagName(planId: PlanId, phaseId: PhaseId): string;
29
+ tag(req: { cwd: string; name: string; commit: string }): Promise<TagOutcome>;
30
+ inspect(req: LandRequest): Promise<LandInspection>;
31
+ fastForward(req: LandRequest): Promise<LandOutcome>;
32
+ commands(req: LandRequest, refusal: LandRefusal): string[];
33
+ }
34
+
35
+ /** Path equality for the toplevel re-validation: separators folded, trailing separators dropped, case-folded on win32. */
36
+ export function samePath(a: string, b: string, platform: NodeJS.Platform): boolean {
37
+ const norm = (p: string): string => {
38
+ const s = p.replace(/\\/g, "/");
39
+ const trimmed = s.length > 1 && !/^[A-Za-z]:\/$/.test(s) ? s.replace(/\/+$/, "") : s;
40
+ return platform === "win32" ? trimmed.toLowerCase() : trimmed;
41
+ };
42
+ return norm(a) === norm(b);
43
+ }
44
+
45
+ function messageOf(error: unknown): string {
46
+ return error instanceof Error ? error.message : String(error);
47
+ }
48
+
49
+ /** Paths of `status --porcelain=v1 -z`; a rename or copy entry carries its origin as the next NUL field. */
50
+ function parseStatusPaths(stdout: string): string[] {
51
+ const fields = stdout.split("\0");
52
+ const paths: string[] = [];
53
+ for (let i = 0; i < fields.length; i++) {
54
+ const field = fields[i] ?? "";
55
+ if (field.length < 4) continue;
56
+ const xy = field.slice(0, 2);
57
+ paths.push(field.slice(3));
58
+ if (/[RC]/.test(xy)) i += 1;
59
+ }
60
+ return paths;
61
+ }
62
+
63
+ export function createLander(d: LanderDeps): LanderApi {
64
+ async function probe(toplevel: string, args: readonly string[]): Promise<{ code: number | null; stdout: string }> {
65
+ // hardeningArgs() neutralises configured hooks/fsmonitor/pagers: `status` must not run a repo-configured program.
66
+ const r = await d.run.run(["-C", toplevel, "--no-optional-locks", ...hardeningArgs(), ...args], { cwd: toplevel, timeoutMs: READ_TIMEOUT_MS });
67
+ return { code: r.code, stdout: r.stdout };
68
+ }
69
+
70
+ async function inspect(req: LandRequest): Promise<LandInspection> {
71
+ const { toplevel, baseBranch, candidate } = req;
72
+
73
+ // 1. The directory is still the owner checkout recorded at compile time.
74
+ const top = await probe(toplevel, ["rev-parse", "--show-toplevel"]);
75
+ const reported = top.code === 0 ? top.stdout.trim() : "";
76
+ let actual = reported;
77
+ if (reported !== "") {
78
+ try { actual = await d.realpath(reported); } catch { actual = reported; }
79
+ }
80
+ let expected = toplevel;
81
+ try { expected = await d.realpath(toplevel); } catch { expected = toplevel; }
82
+ if (reported === "" || !samePath(actual, expected, d.platform)) {
83
+ return { ok: false, refusal: { reason: "toplevel-mismatch", actual }, baseTip: null };
84
+ }
85
+
86
+ const baseTip = await d.igit.readRef(toplevel, `refs/heads/${baseBranch}`);
87
+ if (baseTip === null) return { ok: false, refusal: { reason: "base-missing" }, baseTip: null };
88
+
89
+ // QA-3.2-35: the base already contains the candidate (landed before, or the owner moved on after landing): a no-op that
90
+ // touches nothing, so neither the checked-out branch nor the cleanliness of the owner checkout matters.
91
+ if (baseTip === candidate || await d.igit.isAncestor(toplevel, candidate, baseTip)) return { ok: true, baseTip, noop: true };
92
+
93
+ // 2. The base branch is checked out in the owner checkout.
94
+ const head = await probe(toplevel, ["symbolic-ref", "-q", "HEAD"]);
95
+ const headRef = head.code === 0 ? head.stdout.trim() : null;
96
+ if (headRef !== `refs/heads/${baseBranch}`) {
97
+ return { ok: false, refusal: { reason: "not-checked-out", head: headRef === "" ? null : headRef }, baseTip };
98
+ }
99
+
100
+ // 3. The owner checkout is clean.
101
+ const status = await probe(toplevel, ["status", "--porcelain=v1", "-z", "--untracked-files=all", "--ignore-submodules=none"]);
102
+ if (status.code !== 0) throw new Error(`git status failed in the owner checkout (exit ${status.code ?? "unknown"})`);
103
+ const dirty = parseStatusPaths(status.stdout);
104
+ if (dirty.length > 0) return { ok: false, refusal: { reason: "dirty", paths: dirty }, baseTip };
105
+
106
+ // 4. The base head is an ancestor of the integration head (the base containing the candidate returned above).
107
+ if (!(await d.igit.isAncestor(toplevel, baseTip, candidate))) {
108
+ return { ok: false, refusal: { reason: "diverged", baseTip }, baseTip };
109
+ }
110
+
111
+ // 5. No ignored file sits where the fast-forward adds or changes a path (git overwrites ignored files silently).
112
+ const changed = (await d.igit.diffNameStatus(toplevel, baseTip, candidate)).filter(e => e.status !== "D").map(e => e.path);
113
+ if (changed.length > 0) {
114
+ const ignored = await d.igit.ignoredAt(toplevel, changed);
115
+ if (ignored.length > 0) return { ok: false, refusal: { reason: "ignored-overwrite", paths: ignored }, baseTip };
116
+ }
117
+ return { ok: true, baseTip, noop: false };
118
+ }
119
+
120
+ async function fastForward(req: LandRequest): Promise<LandOutcome> {
121
+ try {
122
+ await d.guard.assertWriteCwd(req.toplevel, "land");
123
+ const i = await inspect(req);
124
+ if (!i.ok) return { kind: "refused", refusal: i.refusal };
125
+ // A no-op lands the empty range candidate..candidate: `to` is the candidate on every landed outcome, and `from` never
126
+ // names a base tip that is a descendant of `to` (the owner moved on after landing).
127
+ if (i.noop) return { kind: "landed", from: req.candidate, to: req.candidate };
128
+ const merged = await d.git.mergeFfOnly(req.toplevel, req.candidate);
129
+ if (!merged.ok) return { kind: "refused", refusal: { reason: "diverged", baseTip: merged.head } };
130
+ if (merged.head !== req.candidate) {
131
+ return { kind: "error", message: `fast-forward left HEAD at ${merged.head}, expected ${req.candidate}` };
132
+ }
133
+ return { kind: "landed", from: i.baseTip, to: merged.head };
134
+ } catch (error) {
135
+ return { kind: "error", message: messageOf(error) };
136
+ }
137
+ }
138
+
139
+ async function tag(req: { cwd: string; name: string; commit: string }): Promise<TagOutcome> {
140
+ try {
141
+ // createRef asserts the "tag" write cwd itself; the create is compare-and-swap against the zero id.
142
+ return await d.igit.createRef(req.cwd, `refs/tags/${req.name}`, req.commit);
143
+ } catch (error) {
144
+ return { kind: "error", message: messageOf(error) };
145
+ }
146
+ }
147
+
148
+ function commands(req: LandRequest, refusal: LandRefusal): string[] {
149
+ const t = `git -C "${req.toplevel}"`;
150
+ const merge = `${t} merge --ff-only ${req.candidate}`;
151
+ switch (refusal.reason) {
152
+ case "dirty":
153
+ return [`${t} status --porcelain=v1 --untracked-files=all`, "# commit or stash the changes above, then:", merge];
154
+ case "not-checked-out":
155
+ return [`${t} switch ${req.baseBranch}`, merge];
156
+ case "diverged":
157
+ return [
158
+ `${t} log --oneline ${req.candidate}..${req.baseBranch}`,
159
+ "# the owner chooses; the executor never runs this:",
160
+ `${t} merge refs/heads/${req.integrationBranch}`,
161
+ ];
162
+ case "ignored-overwrite":
163
+ return [...refusal.paths.map(p => `# ignored file would be overwritten: ${p}`), "# move them, then:", merge];
164
+ case "toplevel-mismatch":
165
+ case "base-missing":
166
+ return [];
167
+ }
168
+ }
169
+
170
+ return {
171
+ tagName: phaseTagName,
172
+ tag,
173
+ inspect,
174
+ fastForward,
175
+ commands,
176
+ };
177
+ }
@@ -0,0 +1,407 @@
1
+ /**
2
+ * Phase suite runner (plan 3.2.4, memo 3.2.1 §4.4, M21-M27).
3
+ */
4
+ import * as nodePath from "node:path";
5
+ import {
6
+ CHECK_TRIES, PREEMPT_BUDGET,
7
+ type BackgroundRuns, type CheckErrorReason, type PreemptBudget, type CheckResult, type CommandRunRequest, type CommandRunResult, type IntegrateGit,
8
+ type IntegrationChecks, type Logger, type ResolvedCommand, type RunResolver,
9
+ } from "./checks";
10
+ import {
11
+ bisectRanges, orderRanges,
12
+ type ProbeVerdict, type RangeBisectResult, type TaskRange,
13
+ } from "./bisect";
14
+ import type {
15
+ PhaseSuiteRunner, RevertRequest, RevertVerdict, StepDetail, StepJournal, SuiteResolution, SuiteRunRequest, SuiteVerdict,
16
+ } from "./queue";
17
+ import { COMMIT_SUBJECT_PATTERN, formatCommitMessage, type GitOps } from "../git";
18
+ import { executorServiceObservation } from "../observations";
19
+ import { ExecutorError, type Clock, type IntegrationStep, type LedgerV1, type PhaseId, type PlanId, type SlotPool, type TaskId } from "../types";
20
+
21
+ export interface PhaseSuiteDeps {
22
+ checks: IntegrationChecks; igit: IntegrateGit; git: GitOps; pool: SlotPool;
23
+ resolver: RunResolver; background: BackgroundRuns; clock: Clock; logger: Logger;
24
+ }
25
+
26
+ /**
27
+ * M22: `reproduced` = original ids failing in at least one rerun; `flaky` = original ids minus `reproduced`.
28
+ * Only the original ids count; ids that fail only in a rerun are ignored. Order follows `original`.
29
+ */
30
+ export function classifyReruns(original: readonly string[], reruns: readonly [readonly string[], readonly string[]]):
31
+ { reproduced: string[]; flaky: string[] } {
32
+ const failed = new Set<string>([...reruns[0], ...reruns[1]]);
33
+ const reproduced: string[] = [];
34
+ const flaky: string[] = [];
35
+ const seen = new Set<string>();
36
+ for (const id of original) {
37
+ if (seen.has(id)) continue;
38
+ seen.add(id);
39
+ (failed.has(id) ? reproduced : flaky).push(id);
40
+ }
41
+ return { reproduced, flaky };
42
+ }
43
+
44
+ // ---------------------------------------------------------------------------------------------------------------
45
+ // Step retries (M13a) and preemption (M12), shared by the suite run and the revert
46
+ // ---------------------------------------------------------------------------------------------------------------
47
+
48
+ type StepFailure = { reason: CheckErrorReason; message: string };
49
+ type Attempt<T> = { error: StepFailure; value?: undefined } | { error: null; value: T };
50
+ type Stepped<T> = { kind: "ok"; value: T } | { kind: "error"; reason: CheckErrorReason; message: string }
51
+ | { kind: "interrupted"; by: "abort" | "dispose" };
52
+
53
+ /**
54
+ * Who stopped the run, read from the journal signal's abort reason: `"dispose"` (or an `E_DISPOSED` ExecutorError)
55
+ * is dispose, anything else (`"abort"`, the default AbortError) is abort. The queue aborts with the matching reason.
56
+ */
57
+ export function interruptedBy(j: Pick<StepJournal, "signal">): "abort" | "dispose" {
58
+ const r: unknown = j.signal.reason;
59
+ return r === "dispose" || (r instanceof ExecutorError && r.code === "E_DISPOSED") ? "dispose" : "abort";
60
+ }
61
+
62
+ /**
63
+ * The `unattributed` reason of a failure the phase base cannot split by ids (QA-3.2-1): the suite's failure names no
64
+ * id, or the base run's output names none. Distinct from `no-base` (the phase has no base at all).
65
+ */
66
+ const BASE_UNPARSED: Extract<SuiteVerdict, { kind: "unattributed" }>["reason"] = "base-unparsed";
67
+
68
+ function clip(s: string, max: number): string {
69
+ return s.length <= max ? s : s.slice(0, max - 1) + "\u2026";
70
+ }
71
+
72
+ /**
73
+ * Runs `op` while `step` is open. A preempted attempt closes the step as refused and reopens it with the same
74
+ * detail (it does not use the try budget, M38). Any other error does the same, at most CHECK_TRIES times; after
75
+ * that no step is left open. An interrupted run leaves the step open and journals nothing more.
76
+ */
77
+ async function stepped<T>(j: StepJournal, step: IntegrationStep, detail: StepDetail, op: () => Promise<Attempt<T>>): Promise<Stepped<T>> {
78
+ let tries = 0;
79
+ let preempts = 0;
80
+ for (;;) {
81
+ if (j.signal.aborted) return { kind: "interrupted", by: interruptedBy(j) };
82
+ const r = await op();
83
+ if (r.error === null) return { kind: "ok", value: r.value };
84
+ const e = r.error;
85
+ if (j.signal.aborted || e.reason === "interrupted") return { kind: "interrupted", by: interruptedBy(j) };
86
+ if (e.reason === "preempted") {
87
+ preempts++;
88
+ await j.end("refused", { v: 1, reason: "preempted", n: preempts });
89
+ await j.start(step, detail);
90
+ continue;
91
+ }
92
+ tries++;
93
+ await j.end("refused", { v: 1, reason: e.reason, message: clip(e.message, 1000) });
94
+ if (tries >= CHECK_TRIES) return { kind: "error", reason: e.reason, message: e.message };
95
+ await j.start(step, detail);
96
+ }
97
+ }
98
+
99
+ /** Raised inside the bisect probe to unwind `bisectRanges` when a probe cannot supply comparable evidence. */
100
+ class ProbeStop extends Error {
101
+ override readonly name = "ProbeStop" as const;
102
+ constructor(readonly outcome: Exclude<Stepped<CommandRunResult>, { kind: "ok" }> | Extract<SuiteVerdict, { kind: "unattributed" }>) {
103
+ super("bisect probe stopped");
104
+ }
105
+ }
106
+
107
+ /**
108
+ * The test file of a suite failing id, as `runCommands` reports it for a full run (`observeFull`: the id's file part,
109
+ * before the first " > " or "::", resolved against the slot).
110
+ */
111
+ export function fileOfSuiteId(slotPath: string, id: string): string {
112
+ const cuts = [id.indexOf(" > "), id.indexOf("::")].filter(n => n >= 0);
113
+ return nodePath.resolve(slotPath, cuts.length === 0 ? id : id.slice(0, Math.min(...cuts)));
114
+ }
115
+
116
+ /** Failure ids of a run for classification: an unparsed failure counts as every id of `original`. */
117
+ function failedIdsOf(r: CommandRunResult, original: readonly string[]): string[] {
118
+ if (r.verdict !== "fail") return [];
119
+ // Fail closed: a failing rerun that names none of the original ids (other ids, another id form) clears none of them.
120
+ return r.idsUnparsed || !r.ids.some(id => original.includes(id)) ? [...original] : r.ids;
121
+ }
122
+
123
+ async function runSuite(d: PhaseSuiteDeps, req: SuiteRunRequest, j: StepJournal): Promise<SuiteVerdict> {
124
+ const observation = executorServiceObservation(d.clock, req.planId, () => ({ planId: req.planId,
125
+ phaseId: req.phaseId, entryId: j.entry.id, taskId: null, attempt: null, taskIds: j.entry.taskIds,
126
+ component: "phase-suite", candidate: req.commit }));
127
+ const startDetail: StepDetail = { v: 1, commit: req.commit, base: req.base, commands: req.commands.map(c => ({ label: c.label, ref: c.ref })) };
128
+ // QA-3.2-8 (M38): one preemption budget for the whole suite entry, shared by every run below. Once spent, the
129
+ // entry's runs register with nothing left, so a foreground check waits instead of preempting again.
130
+ const preempt: PreemptBudget = { left: PREEMPT_BUDGET };
131
+ const exec = async (commit: string, mode: CommandRunRequest["mode"], requireRun = false): Promise<Attempt<CommandRunResult>> => {
132
+ await j.assertWriteCwd(req.slot.path, "slot");
133
+ const r = await d.checks.runCommands({
134
+ slot: req.slot, commit, commands: req.commands, mode, priority: "background", signal: j.signal, prepare: true, preempt, requireRun,
135
+ ...(observation === undefined ? {} : { observation }),
136
+ });
137
+ if (r.verdict === "error") return { error: r.error ?? { reason: "spawn", message: "the run failed without a reason" } };
138
+ return { error: null, value: r };
139
+ };
140
+ const memoStep = async (tasks: readonly TaskId[]): Promise<void> => {
141
+ await j.start("bisect", { v: 1, base: req.base ?? req.commit, candidate: req.commit, tasks: [...tasks], probe: "memo" });
142
+ };
143
+
144
+ // 1. The full run; the phase-suite step is already open (the queue journaled it with the entry).
145
+ const first = await stepped(j, "phase-suite", startDetail, () => exec(req.commit, "full"));
146
+ if (first.kind !== "ok") return first;
147
+ const full = first.value;
148
+ if (full.verdict === "pass") return { kind: "passed" };
149
+ // The full run names its failing ids from the output (QA-3.2-1). ids = [] only when the failure cannot be
150
+ // attributed to ids (collection error, a timeout, an incomplete inventory): then reruns and probes run the full
151
+ // commands (M22), and a base that fails too pauses the phase (unattributed, fail closed).
152
+ const attributable = !full.idsUnparsed && full.ids.length > 0 && full.files.length > 0;
153
+ const ids = attributable ? full.ids : [];
154
+ const files = attributable ? full.files : [];
155
+ const mode: CommandRunRequest["mode"] = attributable ? { rerun: files } : "full";
156
+ await j.end("failed", { v: 1, files: full.files, idsUnparsed: full.idsUnparsed, durationMs: full.durationMs, output: full.output }, ids);
157
+
158
+ // 2. Two reruns at the suite commit. QA-3.2-22: they must run the failing files there; a rerun that ran nothing
159
+ // is a failure (unparsed), never a pass.
160
+ const rerunFailed: string[][] = [];
161
+ let anyRerunFailed = false;
162
+ // NEW-1: the original ids a file-scoped rerun at the suite commit failed WITH (a parsed failure naming them). Only
163
+ // these make the suite commit a known failure for a file-scoped bisect.
164
+ const fileSeen = new Set<string>();
165
+ let reproduced: string[] = [];
166
+ for (const n of [1, 2] as const) {
167
+ const detail: StepDetail = { v: 1, n, files };
168
+ await j.start("suite-rerun", detail);
169
+ const s = await stepped(j, "suite-rerun", detail, () => exec(req.commit, mode, true));
170
+ if (s.kind !== "ok") return s;
171
+ rerunFailed.push(failedIdsOf(s.value, ids));
172
+ if (s.value.verdict === "fail") anyRerunFailed = true;
173
+ // A requested file rerun may execute full commands; even parsed failures then prove no file isolation.
174
+ if (attributable && s.value.scope === "rerun" && s.value.verdict === "fail" && !s.value.idsUnparsed) {
175
+ for (const id of s.value.ids) if (ids.includes(id)) fileSeen.add(id);
176
+ }
177
+ if (n === 1) {
178
+ await j.end(s.value.verdict === "fail" ? "failed" : "ok", { v: 1, durationMs: s.value.durationMs, output: s.value.output }, rerunFailed[0] ?? []);
179
+ continue;
180
+ }
181
+ const classified = classifyReruns(ids, [rerunFailed[0] ?? [], rerunFailed[1] ?? []]);
182
+ let last = s.value;
183
+ reproduced = classified.reproduced;
184
+ let cleared = classified.flaky;
185
+ if (attributable && cleared.length > 0) {
186
+ // QA-3.2-23, NEW-2: reruns of the failing files never clear an id alone. Whenever they cleared any, one run of
187
+ // the full commands (in the same open step) checks them: an id it fails with is reproduced (by the full run
188
+ // only, so it never seeds a file-scoped bisect), all of them when it fails naming none; the rest are flaky.
189
+ const whole = await stepped(j, "suite-rerun", detail, () => exec(req.commit, "full"));
190
+ if (whole.kind !== "ok") return whole;
191
+ last = whole.value;
192
+ const again = new Set(failedIdsOf(last, ids));
193
+ reproduced = ids.filter(id => reproduced.includes(id) || again.has(id));
194
+ cleared = cleared.filter(id => !again.has(id));
195
+ }
196
+ const flaky = attributable ? reproduced.length === 0 : !anyRerunFailed;
197
+ if (flaky) return { kind: "flaky", ids: cleared }; // the second rerun stays open: the queue closes the entry with it
198
+ // NEW-2: ids cleared next to a reproduced failure are reported (counter, and the ids in the step detail).
199
+ if (cleared.length > 0) j.counter("integration.flaky", cleared.length, { where: "suite" });
200
+ await j.end("failed", { v: 1, reproduced, ...(cleared.length > 0 ? { flaky: cleared } : {}), durationMs: last.durationMs, output: last.output }, reproduced);
201
+ }
202
+
203
+ // 3. The phase base (M23): failures that also fail there are pre-existing and not bisected. QA-3.2-23: the base runs
204
+ // the full commands, so pre-existing rests on a complete inventory of the whole base run, not of the failing files.
205
+ if (req.base === null) {
206
+ await memoStep(req.ranges.map(r => r.taskId));
207
+ return { kind: "unattributed", ids: reproduced, reason: "no-base" };
208
+ }
209
+ const base = req.base;
210
+ const baseDetail: StepDetail = { v: 1, at: "base", commit: base, files };
211
+ await j.start("suite-rerun", baseDetail);
212
+ const atBase = await stepped(j, "suite-rerun", baseDetail, () => exec(base, "full"));
213
+ if (atBase.kind !== "ok") return atBase;
214
+ const baseRun = atBase.value;
215
+ // QA-3.2-1 (2): fail closed. When the base failure cannot be split by ids (the suite's failure has none, or the base
216
+ // run's output names none), nothing can be shown pre-existing: the phase pauses (unattributed), it never passes.
217
+ if (baseRun.verdict === "fail" && (!attributable || baseRun.idsUnparsed)) {
218
+ await j.end("failed", { v: 1, durationMs: baseRun.durationMs, output: baseRun.output }, reproduced);
219
+ await memoStep(req.ranges.map(r => r.taskId));
220
+ return { kind: "unattributed", ids: reproduced, reason: BASE_UNPARSED };
221
+ }
222
+ const preexisting = new Set(baseRun.verdict === "fail" ? baseRun.ids : []);
223
+ const regression = reproduced.filter(id => !preexisting.has(id));
224
+ // Without ids (`!attributable`, the base passed) the regression is the whole failure: bisect with the full commands.
225
+ if (attributable && regression.length === 0) return { kind: "pre-existing", ids: reproduced }; // the base step stays open
226
+ await j.end(baseRun.verdict === "fail" ? "failed" : "ok", { v: 1, durationMs: baseRun.durationMs, output: baseRun.output }, baseRun.verdict === "fail" ? baseRun.ids : []);
227
+
228
+ // NEW-1 (M22 "bisect using only regression.files"): the probe files are the files of the REGRESSION ids, minus the
229
+ // files that already fail at the base (with QA-3.2-26 a failing probe fails whatever ids it names, so a pre-existing
230
+ // failure in a probed file would fail every probe). The bisect seeds the suite commit as failing, so a file-scoped
231
+ // bisect is sound only when a file-scoped rerun there failed WITH a regression id in those files. Otherwise the
232
+ // probes run the full commands, which is sound only from a green base: the culprit then carries no files, so its
233
+ // revert check runs the whole command. From a red base nothing can be isolated: unattributed, nobody blamed.
234
+ const baseRed = baseRun.verdict === "fail";
235
+ const baseFiles = new Set(baseRed ? baseRun.files : []);
236
+ const regressionFiles = [...new Set(regression.map(id => fileOfSuiteId(req.slot.path, id)))];
237
+ const mapped = attributable && regressionFiles.every(f => files.includes(f));
238
+ const probeFiles = mapped ? regressionFiles.filter(f => !baseFiles.has(f)) : [];
239
+ const fileScoped = regression.some(id => fileSeen.has(id) && probeFiles.includes(fileOfSuiteId(req.slot.path, id)));
240
+ if (!fileScoped && baseRed) {
241
+ await memoStep(req.ranges.map(r => r.taskId));
242
+ return { kind: "unattributed", ids: regression, reason: "base-overlap" };
243
+ }
244
+ const probeMode: CommandRunRequest["mode"] = fileScoped ? { rerun: probeFiles } : "full";
245
+
246
+ // 4. Bisect over the phase's ranges, running only the regression.
247
+ let ordered: TaskRange[];
248
+ try {
249
+ ordered = orderRanges(req.ranges, await d.igit.revList(req.slot.path, base, req.commit));
250
+ } catch (e) {
251
+ if (e instanceof Error && e.message.includes("is not in the phase chain")) {
252
+ await memoStep(req.ranges.map(r => r.taskId));
253
+ return { kind: "unattributed", ids: regression, reason: "outside" };
254
+ }
255
+ return { kind: "error", reason: "prepare", message: e instanceof Error ? e.message : String(e) };
256
+ }
257
+ const labels = new Map<string, { taskId: TaskId; probe: "to" | "from" }>();
258
+ for (const r of ordered) {
259
+ if (!labels.has(r.from)) labels.set(r.from, { taskId: r.taskId, probe: "from" });
260
+ labels.set(r.to, { taskId: r.taskId, probe: "to" });
261
+ }
262
+ let probes = 0;
263
+ const probe = async (commit: string): Promise<ProbeVerdict> => {
264
+ const label = labels.get(commit) ?? { taskId: ordered[0]?.taskId ?? "", probe: "to" as const };
265
+ const detail: StepDetail = { v: 1, candidate: commit, taskId: label.taskId, probe: label.probe };
266
+ await j.start("bisect", detail);
267
+ const s = await stepped(j, "bisect", detail, () => exec(commit, probeMode));
268
+ if (s.kind !== "ok") throw new ProbeStop(s);
269
+ probes++;
270
+ // Historical runner/config changes can force a full fallback even after the suite commit genuinely scoped.
271
+ // Do not compare that broader verdict with file-scoped seeds (especially a red base seeded as passing).
272
+ if (fileScoped && s.value.scope !== "rerun") {
273
+ await j.end("refused", { v: 1, reason: "full-command-fallback" });
274
+ j.counter("integration.bisect.probes", probes, { kind: "suite" });
275
+ await memoStep(ordered.map(r => r.taskId));
276
+ throw new ProbeStop({ kind: "unattributed", ids: regression, reason: "base-overlap" });
277
+ }
278
+ // QA-3.2-26: fail closed. A failing probe fails, whichever ids it names: a run of the regression files that names
279
+ // none of the regression ids (another id form, or another failure masking them) is no evidence of a pass.
280
+ const failed = s.value.verdict === "fail";
281
+ await j.end(failed ? "failed" : "ok", { v: 1, verdict: failed ? "fail" : "pass", probes }, failed ? regression : []);
282
+ return failed ? "fail" : "pass";
283
+ };
284
+ let found: RangeBisectResult;
285
+ try {
286
+ found = await bisectRanges(ordered, req.commit, probe, new Map<string, ProbeVerdict>([[base, "pass"]]));
287
+ } catch (e) {
288
+ if (e instanceof ProbeStop) return e.outcome;
289
+ throw e;
290
+ }
291
+ j.counter("integration.bisect.probes", probes, { kind: "suite" });
292
+ await memoStep(ordered.map(r => r.taskId));
293
+ if (found.kind === "outside") return { kind: "unattributed", ids: regression, reason: "outside" };
294
+ // The revert's regression check runs the files the bisect ran (the regression's own files), or with full-command
295
+ // probes no file at all, so it runs the whole command (NEW-1).
296
+ return { kind: "culprit", range: found.range, ids: regression, files: fileScoped ? probeFiles : [] };
297
+ }
298
+
299
+ type BuiltRevert = { kind: "built"; head: string; reverted: string[] } | { kind: "conflict"; at: string; paths: string[] };
300
+
301
+ /**
302
+ * M26: the revert of the culprit range is built in the `integration` slot at the current head, newest commit first,
303
+ * then the integration checks run on it with the regression ids as extra (I1: nothing moves before they pass).
304
+ * The runner never fast-forwards; the queue does that on `ok`. The `revert-build` step is open on entry.
305
+ */
306
+ async function runRevert(d: PhaseSuiteDeps, req: RevertRequest, j: StepJournal): Promise<RevertVerdict> {
307
+ const observation = executorServiceObservation(d.clock, req.planId, () => ({ planId: req.planId,
308
+ phaseId: req.phaseId, entryId: j.entry.id, taskId: null, attempt: null, taskIds: j.entry.taskIds,
309
+ component: "checks", candidate: req.head }));
310
+ const cwd = req.slot.path;
311
+ const { culprit } = req;
312
+ const range = { taskId: culprit.taskId, from: culprit.from, to: culprit.to };
313
+ const buildDetail: StepDetail = { v: 1, culprit: range, suiteCommit: req.suiteCommit, head: req.head, files: [...req.regression.files] };
314
+ const built = await stepped<BuiltRevert>(j, "revert-build", buildDetail, async () => {
315
+ await j.assertWriteCwd(cwd, "integration");
316
+ try {
317
+ await d.checks.prepare(req.slot, req.head);
318
+ } catch (e) {
319
+ return { error: { reason: "prepare", message: e instanceof Error ? e.message : String(e) } };
320
+ }
321
+ try {
322
+ const newestFirst = (await d.igit.revList(cwd, culprit.from, culprit.to)).reverse();
323
+ if (newestFirst.length === 0) return { error: { reason: "prepare", message: `range ${culprit.from}..${culprit.to} holds no commit to revert` } };
324
+ for (const sha of newestFirst) {
325
+ const message = revertMessage(await d.igit.subject(cwd, sha), culprit.taskId, culprit.from, culprit.to, req.phaseId, req.planId);
326
+ const r = await d.git.revert(cwd, sha, message);
327
+ if (!r.ok) return { error: null, value: { kind: "conflict", at: sha, paths: [...r.conflicts] } };
328
+ }
329
+ return { error: null, value: { kind: "built", head: await d.git.revParse(cwd, "HEAD"), reverted: newestFirst } };
330
+ } catch (e) {
331
+ return { error: { reason: "spawn", message: e instanceof Error ? e.message : String(e) } };
332
+ }
333
+ });
334
+ if (built.kind !== "ok") return built;
335
+ if (built.value.kind === "conflict") return { kind: "conflict", at: built.value.at, paths: built.value.paths };
336
+ const { head: revertHead, reverted } = built.value;
337
+ await j.end("ok", { v: 1, revertHead, reverted });
338
+
339
+ const checkDetail: StepDetail = { v: 1, base: req.head, candidate: revertHead, extraFiles: [...req.regression.files] };
340
+ await j.start("revert-checks", checkDetail, { candidate: revertHead });
341
+ const checked = await stepped<CheckResult>(j, "revert-checks", checkDetail, async () => {
342
+ const r = await d.checks.run({
343
+ slot: req.slot, base: req.head, candidate: revertHead, priority: "foreground", signal: j.signal,
344
+ extra: { ids: [...req.regression.ids], files: [...req.regression.files], commands: [...req.regression.commands] },
345
+ ...(observation === undefined ? {} : { observation }),
346
+ });
347
+ return r.verdict === "error" ? { error: { reason: r.reason, message: r.message } } : { error: null, value: r };
348
+ });
349
+ if (checked.kind !== "ok") return checked;
350
+ const result = checked.value;
351
+ // The revert-checks step stays open: the queue closes it (ok) or closes the entry with the failure.
352
+ if (result.verdict === "fail") return { kind: "failed", ids: result.failingIds, files: result.failingFiles, output: result.output };
353
+ return { kind: "ok", revertHead, reverted };
354
+ }
355
+
356
+ /** M21: discovery reads `commit` through git; inherited router plans are re-resolved by checks after slot preparation. */
357
+ async function resolveSuite(d: PhaseSuiteDeps, ledger: Readonly<LedgerV1>, phaseId: PhaseId, commit: string): Promise<SuiteResolution> {
358
+ const setting = ledger.config.phaseSuite;
359
+ if (setting === "off") return { kind: "off" };
360
+ const cwd = ledger.integration.worktree;
361
+ if (setting === "auto") {
362
+ try {
363
+ const selection = await d.checks.select(cwd, commit);
364
+ const commands = selection.tests.map(t => t.full);
365
+ return commands.length === 0 ? { kind: "none" } : { kind: "runs", commands };
366
+ } catch (e) {
367
+ return { kind: "refused", reason: `phase ${phaseId} suite selection failed: ${e instanceof Error ? e.message : String(e)}`, ref: null };
368
+ }
369
+ }
370
+ if (setting.length === 0) return { kind: "none" };
371
+ const commands: ResolvedCommand[] = [];
372
+ for (const ref of setting) {
373
+ let r: Awaited<ReturnType<RunResolver["resolve"]>>;
374
+ try {
375
+ r = await d.resolver.resolve(ref, cwd);
376
+ } catch (e) {
377
+ return { kind: "refused", reason: e instanceof Error ? e.message : String(e), ref };
378
+ }
379
+ if (!r.ok) return { kind: "refused", reason: r.reason, ref };
380
+ commands.push(r.command);
381
+ }
382
+ return { kind: "runs", commands };
383
+ }
384
+
385
+ export function createPhaseSuiteRunner(d: PhaseSuiteDeps): PhaseSuiteRunner {
386
+ return {
387
+ resolve: (ledger, phaseId, commit) => resolveSuite(d, ledger, phaseId, commit),
388
+ run: (req, j) => runSuite(d, req, j),
389
+ revert: (req, j) => runRevert(d, req, j),
390
+ preemptBackground: () => d.background.preemptOne(),
391
+ };
392
+ }
393
+
394
+ /**
395
+ * Revert commit message (M26). `GitOps.revert` accepts only a one-line `COMMIT_SUBJECT_PATTERN` subject (no body), so the
396
+ * message is `revert(<phase>): <taskId> <from>..<to> "<subject>" [<planId>:<taskId>]` via `formatCommitMessage` (the
397
+ * title is cut at 72 characters). `planId` defaults to the `[plan:task]` suffix of the reverted subject.
398
+ */
399
+ export function revertMessage(subject: string, taskId: TaskId, from: string, to: string, phaseId: PhaseId, planId?: PlanId): string {
400
+ const plan = planId ?? COMMIT_SUBJECT_PATTERN.exec(subject)?.[4];
401
+ if (plan === undefined) {
402
+ throw new ExecutorError("E_INVALID_INPUT", "revert message needs the plan id", { subject: subject.slice(0, 200) });
403
+ }
404
+ const scope = /^[\w.-]+$/.test(phaseId) ? phaseId : "phase";
405
+ const title = `${taskId} ${from.slice(0, 7)}..${to.slice(0, 7)} "${subject.replace(/ \[[^\]]*\]$/, "")}"`;
406
+ return formatCommitMessage({ type: "revert", scope, title, planId: plan, taskId });
407
+ }