opencode-model-router 2.7.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.
- package/CHANGELOG.md +583 -0
- package/README.md +20 -0
- package/package.json +5 -1
- package/src/commands/approvals.ts +354 -0
- package/src/commands/output.ts +34 -1
- package/src/compat/background.ts +2439 -0
- package/src/compat/child-session.ts +6 -0
- package/src/compat/turn-state.ts +215 -0
- package/src/compat/v2-client.ts +136 -17
- package/src/compat/v2-hooks.ts +2853 -109
- package/src/compat/v2-observations.ts +328 -0
- package/src/executor/capacity.ts +362 -0
- package/src/executor/child-guards.ts +40 -0
- package/src/executor/command.ts +265 -0
- package/src/executor/compile/edges.ts +809 -0
- package/src/executor/compile/estimate.ts +158 -0
- package/src/executor/compile/footprint.ts +829 -0
- package/src/executor/compile/index.ts +1080 -0
- package/src/executor/compile/parse.ts +1492 -0
- package/src/executor/compile/residue.ts +706 -0
- package/src/executor/compile/validate.ts +280 -0
- package/src/executor/create.ts +672 -0
- package/src/executor/expand.ts +551 -0
- package/src/executor/git.ts +1214 -0
- package/src/executor/host-preamble.ts +17 -0
- package/src/executor/instructions.ts +35 -0
- package/src/executor/integrate/bisect.ts +73 -0
- package/src/executor/integrate/checks.ts +1086 -0
- package/src/executor/integrate/land.ts +177 -0
- package/src/executor/integrate/phase-suite.ts +407 -0
- package/src/executor/integrate/queue.ts +3083 -0
- package/src/executor/integrate/run-resolver.ts +19 -0
- package/src/executor/launch.ts +652 -0
- package/src/executor/ledger.ts +2208 -0
- package/src/executor/observations.ts +212 -0
- package/src/executor/paths.ts +159 -0
- package/src/executor/platform.ts +39 -0
- package/src/executor/process-identity.ts +19 -0
- package/src/executor/qa-loop.ts +470 -0
- package/src/executor/recovery.ts +403 -0
- package/src/executor/runtime.ts +6233 -0
- package/src/executor/schedule.ts +246 -0
- package/src/executor/slots/env.ts +145 -0
- package/src/executor/slots/pool.ts +1564 -0
- package/src/executor/slots/provision.ts +853 -0
- package/src/executor/tool.ts +534 -0
- package/src/executor/types.ts +2064 -0
- package/src/executor/unattended.ts +488 -0
- package/src/guard/store.ts +3 -1
- package/src/index.ts +1789 -288
- package/src/router/config.ts +823 -26
- package/src/router/dispatch-header.ts +95 -2
- package/src/router/git-tools.ts +266 -19
- package/src/router/leases.ts +1469 -0
- package/src/router/logger.ts +44 -32
- package/src/router/protocol.ts +44 -10
- package/src/router/role-agents.ts +334 -20
- package/src/router/roles-config.ts +93 -1
- package/src/router/roles.ts +1 -1
- package/src/router/run-tools.ts +56 -4
- package/src/router/sessions.ts +11 -0
- package/src/router/tool-paths.ts +308 -0
- package/src/router/work-roots.ts +86 -0
- package/src/routing/advisor/findings.ts +25 -5
- package/src/routing/classify/index.ts +7 -1
- package/src/routing/classify/route-line.ts +96 -5
- package/src/routing/classify/rules.ts +11 -0
- package/src/routing/classify/types.ts +26 -0
- package/src/routing/commands/stats.ts +2 -2
- package/src/routing/outcomes/durations.ts +225 -0
- package/src/routing/outcomes/index.ts +59 -2
- package/src/routing/outcomes/persist.ts +409 -0
- package/src/routing/outcomes/signals.ts +17 -0
- package/src/routing/outcomes/stats.ts +170 -11
- package/src/routing/outcomes/timings.ts +836 -0
- package/src/routing/outcomes/types.ts +98 -0
- package/src/routing/roles/admission.ts +1028 -0
- package/src/routing/roles/approvals.ts +957 -0
- package/src/routing/roles/binding.ts +116 -13
- package/src/routing/roles/check-placement.ts +112 -0
- package/src/routing/roles/git-root.ts +500 -0
- package/src/routing/roles/orphans.ts +68 -0
- package/src/routing/roles/policy.ts +30 -3
- package/src/routing/roles/read-set.ts +325 -0
- package/src/routing/roles/work-root.ts +12 -2
- package/src/routing/wire/dispatch.ts +697 -30
- package/src/routing/wire/hint.ts +56 -8
- package/src/routing/wire/working-set.ts +58 -0
- package/src/util/linear-trim.ts +32 -0
- package/src/v2.ts +94 -49
- package/src/verify/batch.ts +7 -2
- package/src/verify/branch.ts +141 -0
- package/src/verify/canonical-path.ts +35 -0
- package/src/verify/deterministic.ts +268 -17
- package/src/verify/dispatch.ts +348 -37
- package/src/verify/dod.ts +46 -0
- package/src/verify/edges.ts +817 -0
- package/src/verify/exec.ts +52 -9
- package/src/verify/gate.ts +349 -16
- package/src/verify/git-top.ts +43 -0
- package/src/verify/head.ts +107 -0
- package/src/verify/pending.ts +1846 -18
- package/src/verify/perimeter.ts +1186 -0
- package/src/verify/pin.ts +109 -0
- package/src/verify/plan-task.ts +729 -0
- package/src/verify/reference.ts +297 -8
- package/src/verify/risk.ts +16 -3
- package/src/verify/runner.ts +706 -32
- package/src/verify/tree.ts +372 -16
- package/src/verify/types.ts +66 -2
- package/src/verify/wiring.ts +1594 -46
|
@@ -0,0 +1,1086 @@
|
|
|
1
|
+
// src/executor/integrate/checks.ts
|
|
2
|
+
// Phase 3.2.2 (design memo 3.2.1, section 6 and decisions M8-M12, M30). Prepares slots (reset and clean), selects the
|
|
3
|
+
// integration checks, runs them under the machine-wide verification slot and holds the extra git operations of the
|
|
4
|
+
// integration queue. It journals nothing and registers nothing; 5.1 wires the resolver, the spawner and the guard.
|
|
5
|
+
|
|
6
|
+
import { lstat, readdir, readFile, realpath, stat, unlink } from "node:fs/promises";
|
|
7
|
+
import * as nodePath from "node:path";
|
|
8
|
+
import { gitEnvironment, gitExecutable, hardeningArgs, workRootGuards } from "../../router/git-tools";
|
|
9
|
+
import { resolveCommandExecutable, resolveSystemShell, runEnvironment, slotToolExecutable } from "../../router/run-tools";
|
|
10
|
+
import { applySlotEnv, slotEnvFor } from "../slots/env";
|
|
11
|
+
import {
|
|
12
|
+
detectRunner, isNoAffected, isScopedSpec, isUnverifiable, planRerun, planScopedRun, readResult,
|
|
13
|
+
type ChangedPath, type RunnerFs, type TestSearchSeam,
|
|
14
|
+
} from "../../verify/runner";
|
|
15
|
+
import { observeTests } from "../../verify/baseline";
|
|
16
|
+
import { acquireSlot, type SlotHandle } from "../../verify/slot";
|
|
17
|
+
import type { ExecResult } from "../../verify/types";
|
|
18
|
+
import type { GitOps } from "../git";
|
|
19
|
+
import type { ServiceExecution, ServiceObservation } from "../observations";
|
|
20
|
+
import {
|
|
21
|
+
ExecutorError,
|
|
22
|
+
type Clock, type GitRunner, type LedgerV1, type RunCommandRef, type SlotLease, type SlotPool,
|
|
23
|
+
} from "../types";
|
|
24
|
+
|
|
25
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
26
|
+
// Constants and small types
|
|
27
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
28
|
+
|
|
29
|
+
export const CHECK_TRIES = 3, OUTPUT_TAIL_BYTES = 4096, DETAIL_MAX_BYTES = 16384, AX_MAX_CHARS = 4000;
|
|
30
|
+
|
|
31
|
+
const GIT_READ_TIMEOUT_MS = 120_000;
|
|
32
|
+
const SEARCH_TIMEOUT_MS = 30_000;
|
|
33
|
+
const SLOT_WAIT_MS = 2000;
|
|
34
|
+
const DEFAULT_SLOT_MAX = 2;
|
|
35
|
+
const MAX_WORKERS = 2;
|
|
36
|
+
|
|
37
|
+
/** The one logging method the executor modules use (structural, as in slots/pool.ts). */
|
|
38
|
+
export interface Logger { warn(m: string): void }
|
|
39
|
+
|
|
40
|
+
export interface ResolvedCommand {
|
|
41
|
+
label: string; file: string; args: readonly string[];
|
|
42
|
+
source: "package-script" | "run-command" | "pytest"; ref: RunCommandRef | null;
|
|
43
|
+
/** Inherited router plan, not explicit overrides. Re-resolve `ref` after preparing the execution checkout. */
|
|
44
|
+
resolution?: { cwd: string; env: Readonly<Record<string, string>> };
|
|
45
|
+
/** Extra environment for the child (scoped test specs). */
|
|
46
|
+
env?: Readonly<Record<string, string>>;
|
|
47
|
+
/** A resolved, sanitized environment must replace inheritance at the process seam. */
|
|
48
|
+
envMode?: "replace";
|
|
49
|
+
/** Explicit working directory override (for example scoped test specs); default: the check's cwd. */
|
|
50
|
+
cwd?: string;
|
|
51
|
+
}
|
|
52
|
+
export interface CommandOutput { exitCode: number | null; timedOut: boolean; stdout: string; stderr: string; durationMs: number }
|
|
53
|
+
export type CommandRunner = (c: ResolvedCommand, o: { cwd: string; signal: AbortSignal; lowPriority: boolean; service?: ServiceExecution }) => Promise<CommandOutput>;
|
|
54
|
+
export interface RunResolver {
|
|
55
|
+
resolve(ref: RunCommandRef, cwd: string): Promise<{ ok: true; command: ResolvedCommand } | { ok: false; reason: string }>;
|
|
56
|
+
}
|
|
57
|
+
export interface TestComponent { framework: "node" | "pytest"; full: ResolvedCommand }
|
|
58
|
+
export interface CheckSelection { typecheck: ResolvedCommand | null; tests: TestComponent[]; extras: ResolvedCommand[] }
|
|
59
|
+
export type CheckErrorReason = "prepare" | "slot-lost" | "spawn" | "resolve" | "preempted" | "interrupted";
|
|
60
|
+
export interface ComponentResult {
|
|
61
|
+
name: "typecheck" | "tests" | "extra" | "regression"; label: string;
|
|
62
|
+
exitCode: number | null; timedOut: boolean; durationMs: number; scope: "spec" | "no-affected" | "full" | "rerun"; flakyIds: string[];
|
|
63
|
+
}
|
|
64
|
+
export type CheckResult =
|
|
65
|
+
| { verdict: "pass"; components: ComponentResult[]; flakyIds: string[]; note: "no-checks" | null; durationMs: number }
|
|
66
|
+
| { verdict: "fail"; components: ComponentResult[]; failingIds: string[]; failingFiles: string[]; flakyIds: string[]; output: string; durationMs: number }
|
|
67
|
+
| { verdict: "error"; reason: CheckErrorReason; message: string; components: ComponentResult[]; durationMs: number };
|
|
68
|
+
export interface CheckRequest {
|
|
69
|
+
observation?: ServiceObservation;
|
|
70
|
+
slot: SlotLease; base: string; candidate: string; priority: "foreground" | "background";
|
|
71
|
+
/** The queue just rebased this slot to candidate; clean and verify before reusing it. */
|
|
72
|
+
reuseCheckout?: boolean;
|
|
73
|
+
extra?: { ids: string[]; files: string[]; commands: ResolvedCommand[] } | null; signal: AbortSignal;
|
|
74
|
+
}
|
|
75
|
+
export interface CommandRunRequest {
|
|
76
|
+
observation?: ServiceObservation;
|
|
77
|
+
slot: SlotLease; commit: string; commands: readonly ResolvedCommand[];
|
|
78
|
+
mode: "full" | { rerun: readonly string[] }; priority: "foreground" | "background"; signal: AbortSignal; prepare: boolean;
|
|
79
|
+
/** M38: the preemption budget of the suite entry, shared by all of its runs (default: a fresh PREEMPT_BUDGET per run). */
|
|
80
|
+
preempt?: PreemptBudget;
|
|
81
|
+
/**
|
|
82
|
+
* QA-3.2-22: a rerun that runs nothing (its files map to no test) is a failure, unparsed, never a pass. Set for the
|
|
83
|
+
* reruns at the commit where the failure was observed: its failing files must exist there.
|
|
84
|
+
*/
|
|
85
|
+
requireRun?: boolean;
|
|
86
|
+
}
|
|
87
|
+
export interface CommandRunResult {
|
|
88
|
+
verdict: "pass" | "fail" | "error"; ids: string[]; files: string[]; idsUnparsed: boolean;
|
|
89
|
+
/** Effective scope, not the requested mode: any full-command execution (including a mixed run) makes this full. */
|
|
90
|
+
scope: "full" | "rerun";
|
|
91
|
+
output: string; durationMs: number; error: { reason: CheckErrorReason; message: string } | null;
|
|
92
|
+
}
|
|
93
|
+
export interface IntegrationChecks {
|
|
94
|
+
prepare(slot: SlotLease, commit: string): Promise<void>;
|
|
95
|
+
select(cwd: string, commit: string): Promise<CheckSelection>;
|
|
96
|
+
run(req: CheckRequest): Promise<CheckResult>;
|
|
97
|
+
runCommands(req: CommandRunRequest): Promise<CommandRunResult>;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export class CheckPrepareError extends Error {
|
|
101
|
+
override readonly name = "CheckPrepareError" as const;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** A check command the resolver refused (reason "resolve"). */
|
|
105
|
+
class CheckResolveError extends Error {
|
|
106
|
+
override readonly name = "CheckResolveError" as const;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
110
|
+
// Write guard (M30) and IntegrateGit
|
|
111
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
112
|
+
|
|
113
|
+
export type WritePurpose = "slot" | "integration" | "tag" | "land";
|
|
114
|
+
export interface WriteGuard { assertWriteCwd(cwd: string, purpose: WritePurpose): Promise<void> }
|
|
115
|
+
export interface NameStatus { status: "A" | "M" | "D" | "T"; path: string }
|
|
116
|
+
export type CreateRefOutcome = "created" | "exists-same" | { kind: "exists-other"; at: string };
|
|
117
|
+
export interface IntegrateGit {
|
|
118
|
+
diffNameStatus(cwd: string, from: string, to: string): Promise<NameStatus[]>;
|
|
119
|
+
logPaths(cwd: string, from: string, to: string, path: string, max: number): Promise<Array<{ sha: string; subject: string }>>;
|
|
120
|
+
revList(cwd: string, from: string, to: string): Promise<string[]>;
|
|
121
|
+
createRef(cwd: string, ref: string, commit: string): Promise<CreateRefOutcome>;
|
|
122
|
+
mergeBase(cwd: string, a: string, b: string): Promise<string>;
|
|
123
|
+
isAncestor(cwd: string, ancestor: string, descendant: string): Promise<boolean>;
|
|
124
|
+
showFile(cwd: string, commit: string, path: string): Promise<string | null>;
|
|
125
|
+
subject(cwd: string, commit: string): Promise<string>;
|
|
126
|
+
readRef(cwd: string, ref: string): Promise<string | null>;
|
|
127
|
+
ignoredAt(cwd: string, paths: readonly string[]): Promise<string[]>;
|
|
128
|
+
revertAbort(cwd: string): Promise<void>;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function foldPath(p: string, platform: NodeJS.Platform): string {
|
|
132
|
+
const lexical = platform === "win32" ? nodePath.win32.resolve(p).replace(/\//g, "\\").toLowerCase() : nodePath.posix.resolve(p);
|
|
133
|
+
return lexical.length > 1 && /[\\/]$/.test(lexical) && !/^[a-z]:\\$/.test(lexical) ? lexical.slice(0, -1) : lexical;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function createWriteGuard(o: {
|
|
137
|
+
ledger: () => Readonly<LedgerV1>; pool: SlotPool; realpath: (p: string) => Promise<string>; platform: NodeJS.Platform;
|
|
138
|
+
}): WriteGuard {
|
|
139
|
+
return {
|
|
140
|
+
async assertWriteCwd(cwd, purpose) {
|
|
141
|
+
const here = foldPath(await o.realpath(cwd), o.platform);
|
|
142
|
+
const l = o.ledger();
|
|
143
|
+
if (purpose === "land") {
|
|
144
|
+
if (here !== foldPath(await o.realpath(l.repo.toplevel), o.platform)) {
|
|
145
|
+
throw new ExecutorError("E_INVALID_INPUT", "a landing write must run in the repository toplevel", { purpose, cwd: cwd.slice(0, 200) });
|
|
146
|
+
}
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
const allowed: string[] = [l.integration.worktree];
|
|
150
|
+
for (const rec of await o.pool.list(l.planId)) allowed.push(rec.path);
|
|
151
|
+
for (const candidate of allowed) {
|
|
152
|
+
try {
|
|
153
|
+
if (foldPath(await o.realpath(candidate), o.platform) === here) return;
|
|
154
|
+
} catch {
|
|
155
|
+
// A slot path that does not resolve cannot be the cwd.
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
throw new ExecutorError("E_INVALID_INPUT", "git write outside the slots and the integration worktree", { purpose, cwd: cwd.slice(0, 200) });
|
|
159
|
+
},
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function splitNul(text: string): string[] {
|
|
164
|
+
return text.split("\0").filter(part => part !== "");
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** The `lstat` seam of `ignoredAt` (default: node:fs/promises). */
|
|
168
|
+
export type LstatFn = (p: string) => Promise<{ isDirectory(): boolean }>;
|
|
169
|
+
|
|
170
|
+
export function createIntegrateGit(run: GitRunner, guard: WriteGuard, lstatOf: LstatFn = lstat): IntegrateGit {
|
|
171
|
+
const prefix = ["--no-optional-locks", ...hardeningArgs()];
|
|
172
|
+
async function exec(cwd: string, args: readonly string[]) {
|
|
173
|
+
return run.run([...prefix, ...args], { cwd, timeoutMs: GIT_READ_TIMEOUT_MS });
|
|
174
|
+
}
|
|
175
|
+
async function ok(cwd: string, op: string, args: readonly string[]): Promise<string> {
|
|
176
|
+
const r = await exec(cwd, args);
|
|
177
|
+
if (r.code !== 0) {
|
|
178
|
+
throw new ExecutorError("E_GIT", `git ${op} failed (exit ${r.code ?? r.signal ?? "unknown"})`, { op, code: r.code, stderr: r.stderr.slice(-2048) });
|
|
179
|
+
}
|
|
180
|
+
return r.stdout;
|
|
181
|
+
}
|
|
182
|
+
async function readRef(cwd: string, ref: string): Promise<string | null> {
|
|
183
|
+
const r = await exec(cwd, ["rev-parse", "--verify", "-q", "--end-of-options", `${ref}^{commit}`]);
|
|
184
|
+
if (r.code === 0) return r.stdout.trim();
|
|
185
|
+
if (r.code === 1) return null;
|
|
186
|
+
throw new ExecutorError("E_GIT", "git rev-parse failed", { op: "rev-parse", code: r.code, stderr: r.stderr.slice(-2048) });
|
|
187
|
+
}
|
|
188
|
+
return {
|
|
189
|
+
async diffNameStatus(cwd, from, to) {
|
|
190
|
+
const parts = splitNul(await ok(cwd, "diff", ["diff", "--name-status", "-z", "--no-renames", "--no-ext-diff", from, to, "--"]));
|
|
191
|
+
const out: NameStatus[] = [];
|
|
192
|
+
for (let n = 0; n + 1 < parts.length; n += 2) {
|
|
193
|
+
const code = (parts[n] ?? "").charAt(0);
|
|
194
|
+
const status: NameStatus["status"] = code === "A" || code === "D" || code === "T" ? code : "M";
|
|
195
|
+
out.push({ status, path: parts[n + 1] ?? "" });
|
|
196
|
+
}
|
|
197
|
+
return out;
|
|
198
|
+
},
|
|
199
|
+
async logPaths(cwd, from, to, path, max) {
|
|
200
|
+
const parts = (await ok(cwd, "log", ["log", "-z", "--format=%H%x00%s", "-n", String(max), `${from}..${to}`, "--", `:(literal)${path}`])).split("\0");
|
|
201
|
+
const out: Array<{ sha: string; subject: string }> = [];
|
|
202
|
+
for (let n = 0; n + 1 < parts.length; n += 2) {
|
|
203
|
+
const sha = (parts[n] ?? "").trim();
|
|
204
|
+
if (sha !== "") out.push({ sha, subject: parts[n + 1] ?? "" });
|
|
205
|
+
}
|
|
206
|
+
return out;
|
|
207
|
+
},
|
|
208
|
+
async revList(cwd, from, to) {
|
|
209
|
+
return (await ok(cwd, "rev-list", ["rev-list", "--reverse", "--topo-order", `${from}..${to}`])).split("\n").map(s => s.trim()).filter(s => s !== "");
|
|
210
|
+
},
|
|
211
|
+
async createRef(cwd, ref, commit) {
|
|
212
|
+
await guard.assertWriteCwd(cwd, "tag");
|
|
213
|
+
const r = await exec(cwd, ["update-ref", ref, commit, "0".repeat(commit.length)]);
|
|
214
|
+
if (r.code === 0) return "created";
|
|
215
|
+
const at = await readRef(cwd, ref);
|
|
216
|
+
if (at === null) throw new ExecutorError("E_GIT", "git update-ref failed", { op: "update-ref", code: r.code, stderr: r.stderr.slice(-2048) });
|
|
217
|
+
return at === commit ? "exists-same" : { kind: "exists-other", at };
|
|
218
|
+
},
|
|
219
|
+
async mergeBase(cwd, a, b) {
|
|
220
|
+
return (await ok(cwd, "merge-base", ["merge-base", a, b])).trim();
|
|
221
|
+
},
|
|
222
|
+
async isAncestor(cwd, ancestor, descendant) {
|
|
223
|
+
const r = await exec(cwd, ["merge-base", "--is-ancestor", ancestor, descendant]);
|
|
224
|
+
if (r.code === 0) return true;
|
|
225
|
+
if (r.code === 1) return false;
|
|
226
|
+
throw new ExecutorError("E_GIT", "git merge-base failed", { op: "merge-base", code: r.code, stderr: r.stderr.slice(-2048) });
|
|
227
|
+
},
|
|
228
|
+
async showFile(cwd, commit, path) {
|
|
229
|
+
const r = await exec(cwd, ["show", `${commit}:${path}`]);
|
|
230
|
+
if (r.code === 0) return r.stdout;
|
|
231
|
+
const error = r.stderr.trim();
|
|
232
|
+
if (r.code === 128 && (error === `fatal: path '${path}' does not exist in '${commit}'`
|
|
233
|
+
|| error === `fatal: path '${path}' exists on disk, but not in '${commit}'`)) return null;
|
|
234
|
+
throw new ExecutorError("E_GIT", `git show failed (exit ${r.code ?? r.signal ?? "unknown"})`, { op: "show", code: r.code, stderr: r.stderr.slice(-2048) });
|
|
235
|
+
},
|
|
236
|
+
async subject(cwd, commit) {
|
|
237
|
+
return (await ok(cwd, "log", ["log", "-1", "--format=%s", commit, "--"])).replace(/\r?\n$/, "");
|
|
238
|
+
},
|
|
239
|
+
readRef,
|
|
240
|
+
async ignoredAt(cwd, paths) {
|
|
241
|
+
// M29.5 (QA-3.2-12): only the exact changed paths are listed, file by file (no `--directory`, which would report
|
|
242
|
+
// every ignored file under a parent directory). A parent directory counts only when that path exists in the
|
|
243
|
+
// checkout as a non-directory (a file or a symlink git would replace by a directory).
|
|
244
|
+
const specs = new Set<string>();
|
|
245
|
+
const parents = new Set<string>();
|
|
246
|
+
for (const p of paths) {
|
|
247
|
+
specs.add(`:(literal)${p}`);
|
|
248
|
+
for (let dir = nodePath.posix.dirname(p); dir !== "." && dir !== "/" && dir !== ""; dir = nodePath.posix.dirname(dir)) parents.add(dir);
|
|
249
|
+
}
|
|
250
|
+
for (const dir of parents) {
|
|
251
|
+
if (specs.has(`:(literal)${dir}`)) continue;
|
|
252
|
+
try {
|
|
253
|
+
if (!(await lstatOf(nodePath.join(cwd, dir))).isDirectory()) specs.add(`:(literal)${dir}`);
|
|
254
|
+
} catch {
|
|
255
|
+
// Absent: nothing can be overwritten there.
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
if (specs.size === 0) return [];
|
|
259
|
+
return splitNul(await ok(cwd, "ls-files", ["ls-files", "-z", "--others", "--ignored", "--exclude-standard", "--", ...specs]));
|
|
260
|
+
},
|
|
261
|
+
async revertAbort(cwd) {
|
|
262
|
+
await guard.assertWriteCwd(cwd, "slot");
|
|
263
|
+
if ((await exec(cwd, ["rev-parse", "--verify", "-q", "REVERT_HEAD"])).code !== 0) return;
|
|
264
|
+
await ok(cwd, "revert --abort", ["revert", "--abort"]);
|
|
265
|
+
},
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
270
|
+
// Check selection (M9)
|
|
271
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
272
|
+
|
|
273
|
+
/** npm's `npm init` placeholder test script. */
|
|
274
|
+
export function isPlaceholderTestScript(s: string): boolean {
|
|
275
|
+
return /^echo\s+["']?error:\s*no test specified["']?\s*&&\s*exit\s+1$/i.test(s.trim());
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function scriptsOf(packageJson: string | null): Record<string, unknown> {
|
|
279
|
+
if (packageJson === null) return {};
|
|
280
|
+
try {
|
|
281
|
+
const parsed: unknown = JSON.parse(packageJson);
|
|
282
|
+
if (typeof parsed !== "object" || parsed === null) return {};
|
|
283
|
+
const scripts: unknown = Reflect.get(parsed, "scripts");
|
|
284
|
+
return typeof scripts === "object" && scripts !== null ? (scripts as Record<string, unknown>) : {};
|
|
285
|
+
} catch {
|
|
286
|
+
return {};
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
export function selectFromFiles(
|
|
291
|
+
f: { packageJson: string | null; pytestIni: boolean; conftest: boolean; pyproject: string | null; setupCfg: string | null; toxIni: string | null },
|
|
292
|
+
extras: readonly RunCommandRef[] | "auto",
|
|
293
|
+
): { typecheck: boolean; node: boolean; pytest: boolean; extras: RunCommandRef[] } {
|
|
294
|
+
const scripts = scriptsOf(f.packageJson);
|
|
295
|
+
const test = scripts["test"];
|
|
296
|
+
return {
|
|
297
|
+
typecheck: typeof scripts["typecheck"] === "string",
|
|
298
|
+
node: typeof test === "string" && !isPlaceholderTestScript(test),
|
|
299
|
+
pytest: f.pytestIni || f.conftest || (f.pyproject?.includes("[tool.pytest") ?? false)
|
|
300
|
+
|| (f.setupCfg?.includes("[tool:pytest]") ?? false) || (f.toxIni?.includes("[pytest]") ?? false),
|
|
301
|
+
extras: extras === "auto" ? [] : extras.map(e => ({ script: e.script, args: [...e.args] })),
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
306
|
+
// Background runs (M12)
|
|
307
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
308
|
+
|
|
309
|
+
/** Preemptions a suite entry may still take (M38). Shared by every run of the entry, so the cap spans the entry. */
|
|
310
|
+
export interface PreemptBudget { left: number }
|
|
311
|
+
|
|
312
|
+
/** M38: preemptions per suite entry. */
|
|
313
|
+
export const PREEMPT_BUDGET = 3;
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* In-process background (suite) runs that a foreground check may preempt. A number budget is private to the run; a
|
|
317
|
+
* `PreemptBudget` object is shared, so a run registered after the entry's budget is spent is never preempted.
|
|
318
|
+
*/
|
|
319
|
+
export class BackgroundRuns {
|
|
320
|
+
private readonly runs = new Set<{ c: AbortController; budget: PreemptBudget }>();
|
|
321
|
+
register(c: AbortController, budget: number | PreemptBudget): () => void {
|
|
322
|
+
const entry = { c, budget: typeof budget === "number" ? { left: budget } : budget };
|
|
323
|
+
this.runs.add(entry);
|
|
324
|
+
return () => { this.runs.delete(entry); };
|
|
325
|
+
}
|
|
326
|
+
preemptOne(): boolean {
|
|
327
|
+
for (const entry of this.runs) {
|
|
328
|
+
if (entry.budget.left > 0 && !entry.c.signal.aborted) {
|
|
329
|
+
entry.budget.left -= 1;
|
|
330
|
+
entry.c.abort();
|
|
331
|
+
return true;
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
return false;
|
|
335
|
+
}
|
|
336
|
+
get active(): number {
|
|
337
|
+
return this.runs.size;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
342
|
+
// The checks
|
|
343
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
344
|
+
|
|
345
|
+
export interface IntegrationChecksDeps {
|
|
346
|
+
ledger: () => Readonly<LedgerV1>; pool: SlotPool; git: GitOps; igit: IntegrateGit;
|
|
347
|
+
resolver: RunResolver; spawn: CommandRunner; guard: WriteGuard; background: BackgroundRuns; clock: Clock; logger: Logger;
|
|
348
|
+
/** Default: wiring.preemptBackgroundVerification. */
|
|
349
|
+
preemptForeground?: () => Promise<void>;
|
|
350
|
+
/** Default: slot.ts acquireSlot. */
|
|
351
|
+
acquire?: typeof acquireSlot;
|
|
352
|
+
/** Machine-wide verification slots (default 2). */
|
|
353
|
+
slotMax?: number;
|
|
354
|
+
/** `isCommandAllowed` for the pytest command (default: allowed). */
|
|
355
|
+
allowCommand?: (command: string) => boolean;
|
|
356
|
+
/** Whether a test file exists (default: node:fs). A failing id names a rerunnable file only when it does (QA-3.2-22/-24). */
|
|
357
|
+
fileExists?: (p: string) => Promise<boolean>;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
async function fileExistsOnDisk(p: string): Promise<boolean> {
|
|
361
|
+
try { await stat(p); return true; } catch { return false; }
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
const nodeFs: RunnerFs = {
|
|
365
|
+
fileExists: fileExistsOnDisk,
|
|
366
|
+
readFile: p => readFile(p, "utf8"),
|
|
367
|
+
realpath: p => realpath(p),
|
|
368
|
+
async stat(p) {
|
|
369
|
+
const s = await stat(p, { bigint: true });
|
|
370
|
+
return { isFile: s.isFile(), size: s.size, dev: s.dev, ino: s.ino };
|
|
371
|
+
},
|
|
372
|
+
readdir: p => readdir(p),
|
|
373
|
+
async unlink(p) {
|
|
374
|
+
try {
|
|
375
|
+
await unlink(p);
|
|
376
|
+
} catch (e) {
|
|
377
|
+
if (!(e instanceof Error && "code" in e && e.code === "ENOENT")) throw e;
|
|
378
|
+
}
|
|
379
|
+
},
|
|
380
|
+
};
|
|
381
|
+
|
|
382
|
+
function tail(text: string, max: number): string {
|
|
383
|
+
const bytes = Buffer.from(text, "utf8");
|
|
384
|
+
return bytes.length <= max ? text : bytes.subarray(bytes.length - max).toString("utf8");
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
function errText(e: unknown): string {
|
|
388
|
+
return e instanceof Error ? e.message : String(e);
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/** Immutable-object reads must all release their slot cwd before a failed attempt can be retried. */
|
|
392
|
+
async function settledReads<T extends readonly unknown[]>(reads: T) {
|
|
393
|
+
await Promise.allSettled(reads);
|
|
394
|
+
return Promise.all(reads);
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/** The test file part of a stable failing id (`<file> > a > b`, `<file>::Cls::test`, or a bare file). */
|
|
398
|
+
function fileOfId(id: string): string {
|
|
399
|
+
const gt = id.indexOf(" > ");
|
|
400
|
+
const cc = id.indexOf("::");
|
|
401
|
+
const cut = [gt, cc].filter(n => n >= 0);
|
|
402
|
+
return cut.length === 0 ? id : id.slice(0, Math.min(...cut));
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/** A vitest workspace line names its project first (` FAIL |proj| test/a.test.ts > …`): the id is what follows. */
|
|
406
|
+
function stripProject(id: string): string {
|
|
407
|
+
return id.replace(/^\|[^|]*\|\s+/, "");
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
function field(o: unknown, key: string): unknown {
|
|
411
|
+
return typeof o === "object" && o !== null ? Reflect.get(o, key) : undefined;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/**
|
|
415
|
+
* QA-3.2-26: a jest/vitest JSON report on stdout, with its failing ids in `readResult`'s form
|
|
416
|
+
* (`<cwd-relative file> > <ancestor titles> > <title>`). `raw` are the same failures in `observeTests`' form
|
|
417
|
+
* (`<absolute suite name> > <fullName>`), to drop. `errors`: a runtime-error suite or a failed suite without a failed
|
|
418
|
+
* test (an import or collection error, QA-3.2-23).
|
|
419
|
+
*/
|
|
420
|
+
function jsonReport(stdout: string, cwd: string): { ids: string[]; raw: string[]; errors: boolean } | null {
|
|
421
|
+
let json: unknown;
|
|
422
|
+
try {
|
|
423
|
+
json = JSON.parse(stdout);
|
|
424
|
+
} catch {
|
|
425
|
+
return null;
|
|
426
|
+
}
|
|
427
|
+
const results = field(json, "testResults");
|
|
428
|
+
if (!Array.isArray(results)) return null;
|
|
429
|
+
const suites: unknown[] = results;
|
|
430
|
+
const ids: string[] = [];
|
|
431
|
+
const raw: string[] = [];
|
|
432
|
+
let errors = Number(field(json, "numRuntimeErrorTestSuites") ?? 0) > 0;
|
|
433
|
+
for (const suite of suites) {
|
|
434
|
+
const name = String(field(suite, "name") ?? "");
|
|
435
|
+
const rel = (nodePath.isAbsolute(name) ? nodePath.relative(cwd, name) : name).replace(/\\/g, "/");
|
|
436
|
+
const asserts = field(suite, "assertionResults");
|
|
437
|
+
let failed = 0;
|
|
438
|
+
for (const a of Array.isArray(asserts) ? (asserts as unknown[]) : []) {
|
|
439
|
+
if (field(a, "status") !== "failed") continue;
|
|
440
|
+
failed++;
|
|
441
|
+
const fullName = field(a, "fullName");
|
|
442
|
+
if (typeof fullName === "string") raw.push(`${name} > ${fullName}`);
|
|
443
|
+
const ancestors = field(a, "ancestorTitles");
|
|
444
|
+
const title = field(a, "title");
|
|
445
|
+
const parts = [...(Array.isArray(ancestors) ? (ancestors as unknown[]).map(String) : []), String(title ?? fullName ?? "")];
|
|
446
|
+
ids.push(`${rel} > ${parts.join(" > ")}`);
|
|
447
|
+
}
|
|
448
|
+
if (field(suite, "status") === "failed" && failed === 0) errors = true;
|
|
449
|
+
}
|
|
450
|
+
return { ids, raw, errors };
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* QA-3.2-23: output that reports errors outside the test inventory, so its failing ids cannot be the whole failure:
|
|
455
|
+
* a file-level FAIL (vitest's failed suite ` FAIL f.ts [ f.ts ]`, jest's file header), vitest's `Errors N error`,
|
|
456
|
+
* pytest's `ERROR …` lines, an `N error` count in pytest's summary, or an error during collection.
|
|
457
|
+
*/
|
|
458
|
+
function reportsErrors(text: string): boolean {
|
|
459
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
460
|
+
const line = raw.replace(/\x1b\[[0-9;]*m/g, "").trim();
|
|
461
|
+
if (/^FAIL\s/.test(line) && !/\s>\s/.test(line)) return true;
|
|
462
|
+
if (/^Errors?\s+\d+\s+errors?\b/i.test(line) || /^ERROR\b/.test(line)) return true;
|
|
463
|
+
if (/^=+\s.*\b\d+\s+errors?\b/.test(line) || /\berrors? during collection\b/i.test(line)) return true;
|
|
464
|
+
}
|
|
465
|
+
return false;
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/**
|
|
469
|
+
* QA-3.2-1: the failing ids of a full run, read from its output (`observeTests`, verify/baseline.ts), in one form
|
|
470
|
+
* (QA-3.2-26: `readResult`'s; no vitest project prefix, no absolute jest-JSON ids). `files` are the test files of the
|
|
471
|
+
* ids resolved against `cwd`. `complete` is false when the output also reports errors outside the tests (QA-3.2-23).
|
|
472
|
+
* Null when the output names no id.
|
|
473
|
+
*/
|
|
474
|
+
export function observeFull(o: CommandOutput, cwd: string): { ids: string[]; files: string[]; complete: boolean } | null {
|
|
475
|
+
const seen = observeTests({ code: o.exitCode ?? -1, stdout: o.stdout, stderr: o.stderr, timedOut: o.timedOut });
|
|
476
|
+
const json = jsonReport(o.stdout, cwd);
|
|
477
|
+
const raw = new Set(json?.raw ?? []);
|
|
478
|
+
const ids = [...new Set([...seen.failures.filter(id => !raw.has(id)).map(stripProject), ...(json?.ids ?? [])])].sort();
|
|
479
|
+
if (ids.length === 0) return null;
|
|
480
|
+
const files = [...new Set(ids.map(id => nodePath.resolve(cwd, fileOfId(id))))].sort();
|
|
481
|
+
const complete = seen.complete && !(json?.errors ?? false) && !reportsErrors(`${o.stdout}\n${o.stderr}`);
|
|
482
|
+
return { ids, files, complete };
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
type Held<T> = { ok: true; value: T } | { ok: false; reason: CheckErrorReason; message: string };
|
|
486
|
+
|
|
487
|
+
interface Failing { ids: string[]; files: string[]; output: string }
|
|
488
|
+
|
|
489
|
+
interface TestOutcome {
|
|
490
|
+
comp: ComponentResult;
|
|
491
|
+
failing: Failing | null;
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
export function createIntegrationChecks(d: IntegrationChecksDeps): IntegrationChecks {
|
|
495
|
+
// Each underSlot call owns its signal. Never use a mutable instance-wide "current entry": foreground checks
|
|
496
|
+
// and the background suite can overlap. Search/planning spawns intentionally do not go through exec below.
|
|
497
|
+
const executions = new WeakMap<AbortSignal, { observation: ServiceObservation; candidate: string;
|
|
498
|
+
preparation: ReturnType<ServiceObservation["start"]> }>();
|
|
499
|
+
async function prepare(slot: SlotLease, commit: string): Promise<void> {
|
|
500
|
+
try {
|
|
501
|
+
await d.pool.reset(slot.slot, commit);
|
|
502
|
+
await d.pool.cleanForChecks(slot.slot);
|
|
503
|
+
const head = await d.git.revParse(slot.path, "HEAD");
|
|
504
|
+
if (head !== commit) throw new CheckPrepareError(`slot ${slot.slot} is at ${head.slice(0, 12)}, not ${commit.slice(0, 12)}`);
|
|
505
|
+
} catch (e) {
|
|
506
|
+
if (e instanceof CheckPrepareError) throw e;
|
|
507
|
+
throw new CheckPrepareError(`could not prepare slot ${slot.slot}: ${errText(e)}`);
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
async function prepareReused(slot: SlotLease, commit: string): Promise<void> {
|
|
512
|
+
try {
|
|
513
|
+
const { drifted } = await d.pool.cleanForChecks(slot.slot);
|
|
514
|
+
const head = await d.git.revParse(slot.path, "HEAD");
|
|
515
|
+
// A drift install can change tracked files after the clean. Only a full prepare restores and verifies those.
|
|
516
|
+
if (head !== commit || drifted) {
|
|
517
|
+
await prepare(slot, commit);
|
|
518
|
+
} else {
|
|
519
|
+
await d.pool.noteCommit(slot.slot, commit);
|
|
520
|
+
}
|
|
521
|
+
} catch (e) {
|
|
522
|
+
if (e instanceof CheckPrepareError) throw e;
|
|
523
|
+
throw new CheckPrepareError(`could not prepare slot ${slot.slot}: ${errText(e)}`);
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
async function resolveRef(ref: RunCommandRef, cwd: string): Promise<ResolvedCommand> {
|
|
528
|
+
const r = await d.resolver.resolve(ref, cwd);
|
|
529
|
+
if (!r.ok) throw new CheckResolveError(`${ref.script}: ${r.reason}`);
|
|
530
|
+
return r.command;
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
async function resolveForSlot(c: ResolvedCommand, cwd: string): Promise<ResolvedCommand> {
|
|
534
|
+
// A pytest command only comes from a selection: its interpreter is derived from the configuration for this slot.
|
|
535
|
+
if (c.source === "pytest") return resolvePython(c, c.cwd ?? cwd, true);
|
|
536
|
+
if (c.resolution === undefined || c.ref === null) return c;
|
|
537
|
+
// Executable, environment and checkout-dependent authorization all belong to the prepared slot, even when
|
|
538
|
+
// its path is unchanged (base/bisect/revert). Only explicit overrides survive; never reuse the inherited plan.
|
|
539
|
+
return { ...await resolveRef(c.ref, c.cwd ?? cwd),
|
|
540
|
+
...(c.cwd === undefined ? {} : { cwd: c.cwd }), ...(c.env === undefined ? {} : { env: c.env }) };
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
/** The configured pytest interpreter (`python`: a bare name or an absolute path; "auto" is the bare `python`). */
|
|
544
|
+
function configuredPython(): string {
|
|
545
|
+
const python = d.ledger().config.python;
|
|
546
|
+
return python === "auto" ? "python" : python;
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/**
|
|
550
|
+
* QA N-A-1: the full pytest commands resolved from the configured interpreter (a planner's spec is a new object). Their
|
|
551
|
+
* argv[0] is derived from the configuration again at every resolution (a command moved to a prepared slot, each spawn),
|
|
552
|
+
* never taken from an earlier one: that slot's interpreter may have been rewritten, re-provisioned or unregistered since,
|
|
553
|
+
* and another slot's absolute path is outside this slot's guards.
|
|
554
|
+
*/
|
|
555
|
+
const fromConfig = new WeakSet<ResolvedCommand>();
|
|
556
|
+
|
|
557
|
+
/**
|
|
558
|
+
* QA N-A: the pytest interpreter and environment as router_run's planRun builds them. The environment is the hardened
|
|
559
|
+
* run environment (credentials, npm/NODE_OPTIONS and guarded PATH entries dropped, ComSpec the validated system shell
|
|
560
|
+
* on win32) with the slot environment applied (VIRTUAL_ENV, `.venv\Scripts` / `.venv/bin` first on PATH,
|
|
561
|
+
* PYTHONPATH/PYTHONHOME unset). argv[0] is the slot's own provisioned tool for a bare name (slotToolExecutable: it must
|
|
562
|
+
* match the pool's post-provisioning snapshot), else an absolute file outside the work root (resolveCommandExecutable);
|
|
563
|
+
* never a bare name resolved from the cwd. `configured`: argv[0] is the configured interpreter (N-A-1), else the
|
|
564
|
+
* planner's (a scoped or rerun spec planned in this cwd).
|
|
565
|
+
*/
|
|
566
|
+
function resolvePython(c: ResolvedCommand, cwd: string, configured: boolean): ResolvedCommand {
|
|
567
|
+
const platform = process.platform;
|
|
568
|
+
const guards = workRootGuards(cwd);
|
|
569
|
+
let shell: string | undefined;
|
|
570
|
+
if (platform === "win32") {
|
|
571
|
+
// As planRun: ComSpec for anything the child starts is the validated system shell when one exists.
|
|
572
|
+
try { shell = resolveSystemShell({ platform, env: process.env }, guards); } catch { shell = undefined; }
|
|
573
|
+
}
|
|
574
|
+
const base = runEnvironment(process.env, platform, shell, { guards });
|
|
575
|
+
const slotEnv = slotEnvFor(cwd, platform);
|
|
576
|
+
try {
|
|
577
|
+
const host = { platform, env: base };
|
|
578
|
+
const program = configured ? configuredPython() : c.file;
|
|
579
|
+
const file = slotToolExecutable(program, slotEnv, host, () => guards) ?? resolveCommandExecutable(program, host, guards);
|
|
580
|
+
const env = applySlotEnv(base, slotEnv, platform);
|
|
581
|
+
const resolved: ResolvedCommand = { ...c, file, resolution: { cwd, env: Object.fromEntries(Object.entries(env)
|
|
582
|
+
.filter((entry): entry is [string, string] => entry[1] !== undefined)) } };
|
|
583
|
+
if (configured) fromConfig.add(resolved);
|
|
584
|
+
return resolved;
|
|
585
|
+
} catch (e) {
|
|
586
|
+
throw new CheckResolveError(`pytest: ${errText(e)}`);
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
async function readSelection(cwd: string, commit: string) {
|
|
591
|
+
const read = (p: string) => d.igit.showFile(cwd, commit, p);
|
|
592
|
+
const [packageJson, pytestIni, conftest, pyproject, setupCfg, toxIni] = await settledReads([
|
|
593
|
+
read("package.json"), read("pytest.ini"), read("conftest.py"), read("pyproject.toml"), read("setup.cfg"), read("tox.ini"),
|
|
594
|
+
] as const);
|
|
595
|
+
return { packageJson, pytestIni: pytestIni !== null, conftest: conftest !== null, pyproject, setupCfg, toxIni };
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
async function resolveSelection(cwd: string, files: Awaited<ReturnType<typeof readSelection>>): Promise<CheckSelection> {
|
|
599
|
+
const cfg = d.ledger().config;
|
|
600
|
+
const sel = selectFromFiles(files, cfg.integrationChecks);
|
|
601
|
+
const typecheck = sel.typecheck ? await resolveRef({ script: "typecheck", args: [] }, cwd) : null;
|
|
602
|
+
const tests: TestComponent[] = [];
|
|
603
|
+
if (sel.node) tests.push({ framework: "node", full: await resolveRef({ script: "test", args: [] }, cwd) });
|
|
604
|
+
if (sel.pytest) {
|
|
605
|
+
const python = configuredPython();
|
|
606
|
+
const label = `${python} -m pytest`;
|
|
607
|
+
if (d.allowCommand === undefined || d.allowCommand(label)) {
|
|
608
|
+
tests.push({ framework: "pytest", full: resolvePython({ label, file: python, args: ["-m", "pytest"], source: "pytest", ref: null }, cwd, true) });
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
const extras: ResolvedCommand[] = [];
|
|
612
|
+
for (const ref of sel.extras) extras.push(await resolveRef(ref, cwd));
|
|
613
|
+
return { typecheck, tests, extras };
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
async function select(cwd: string, commit: string): Promise<CheckSelection> {
|
|
617
|
+
return resolveSelection(cwd, await readSelection(cwd, commit));
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
/** M12: holds one machine-wide verification slot around `body`, which gets a signal for abort, preemption and a lost slot. */
|
|
621
|
+
async function underSlot<T>(
|
|
622
|
+
o: { signal: AbortSignal; priority: "foreground" | "background"; cwd: string; command: string; budget?: PreemptBudget | undefined;
|
|
623
|
+
observation?: ServiceObservation; candidate: string },
|
|
624
|
+
body: (signal: AbortSignal) => Promise<T>,
|
|
625
|
+
): Promise<Held<T>> {
|
|
626
|
+
const lost = new AbortController();
|
|
627
|
+
const own = new AbortController();
|
|
628
|
+
// QA-3.2-8 (M38): a shared budget carries the preemptions of one suite entry across its runs.
|
|
629
|
+
const unregister = o.priority === "background" ? d.background.register(own, o.budget ?? PREEMPT_BUDGET) : () => undefined;
|
|
630
|
+
const signal = AbortSignal.any([o.signal, lost.signal, own.signal]);
|
|
631
|
+
let handle: SlotHandle | null = null;
|
|
632
|
+
let held: Held<T>;
|
|
633
|
+
const wait = o.observation?.start("service-wait", "verification-slot", o.candidate);
|
|
634
|
+
try {
|
|
635
|
+
if (o.priority === "foreground") {
|
|
636
|
+
const preempt = d.preemptForeground ?? (async () => { await (await import("../../verify/wiring")).preemptBackgroundVerification(); });
|
|
637
|
+
await preempt();
|
|
638
|
+
}
|
|
639
|
+
const acquire = d.acquire ?? acquireSlot;
|
|
640
|
+
while (handle === null) {
|
|
641
|
+
if (signal.aborted) break;
|
|
642
|
+
const r = await acquire({
|
|
643
|
+
max: d.slotMax ?? DEFAULT_SLOT_MAX, waitMs: SLOT_WAIT_MS, signal, meta: { cwd: o.cwd, command: o.command }, onLost: () => lost.abort(),
|
|
644
|
+
});
|
|
645
|
+
if (!("busy" in r)) handle = r;
|
|
646
|
+
else if (o.priority === "foreground") d.background.preemptOne();
|
|
647
|
+
}
|
|
648
|
+
wait?.end(handle === null ? "interrupted" : "acquired");
|
|
649
|
+
if (handle === null) return why(o.signal, lost.signal.aborted, false);
|
|
650
|
+
if (o.observation !== undefined) executions.set(signal, { observation: o.observation, candidate: o.candidate,
|
|
651
|
+
preparation: o.observation.start("service-prep", "command-planning", o.candidate) });
|
|
652
|
+
try {
|
|
653
|
+
const value = await body(signal);
|
|
654
|
+
// QA-3.2-13: whatever the body returned, a run whose signal fired (abort, preemption, lost slot) is no result.
|
|
655
|
+
held = signal.aborted || handle.lost ? why(o.signal, lost.signal.aborted || handle.lost, true) : { ok: true, value };
|
|
656
|
+
} catch (e) {
|
|
657
|
+
// A child killed by the signal rejects: that is the signal's outcome, not a spawn error.
|
|
658
|
+
if (!signal.aborted && !handle.lost) throw e;
|
|
659
|
+
held = why(o.signal, lost.signal.aborted || handle.lost, true);
|
|
660
|
+
}
|
|
661
|
+
} finally {
|
|
662
|
+
wait?.end("error");
|
|
663
|
+
executions.get(signal)?.preparation?.end("completed");
|
|
664
|
+
executions.delete(signal);
|
|
665
|
+
unregister();
|
|
666
|
+
if (handle !== null) await handle.release();
|
|
667
|
+
}
|
|
668
|
+
// QA-3.2-36: an abort that fired while the slot was being released still wins over the result.
|
|
669
|
+
return held.ok && o.signal.aborted ? why(o.signal, false, true) : held;
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
/**
|
|
673
|
+
* The outcome of a run some signal stopped. The outer signal (abort, dispose) wins: the caller asked for the stop, so
|
|
674
|
+
* it is `interrupted`, never a verdict. Then a lost slot; else only the preemption signal is left.
|
|
675
|
+
*/
|
|
676
|
+
function why(outer: AbortSignal, lostSlot: boolean, held: boolean): Held<never> {
|
|
677
|
+
if (outer.aborted) return { ok: false, reason: "interrupted", message: held ? "the run was aborted" : "aborted while waiting for a verification slot" };
|
|
678
|
+
if (lostSlot) return { ok: false, reason: "slot-lost", message: "the verification slot was reclaimed while held" };
|
|
679
|
+
return { ok: false, reason: "preempted", message: "a foreground check preempted this background run" };
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
async function exec(c: ResolvedCommand, cwd: string, signal: AbortSignal, low: boolean): Promise<CommandOutput> {
|
|
683
|
+
// Scoped/rerun planners can replace argv[0]; authorize it too, not just the full-suite interpreter. A full command's
|
|
684
|
+
// interpreter is derived from the configuration again (N-A-1): one rewritten since its selection falls back as there.
|
|
685
|
+
if (c.source === "pytest") c = resolvePython(c, c.cwd ?? cwd, fromConfig.has(c));
|
|
686
|
+
let command = c;
|
|
687
|
+
if (c.resolution !== undefined) {
|
|
688
|
+
const env = { ...c.resolution.env };
|
|
689
|
+
for (const [key, value] of Object.entries(c.env ?? {})) {
|
|
690
|
+
// Node keeps only one spelling on Windows; an explicit Path must replace an inherited PATH too.
|
|
691
|
+
if (process.platform === "win32") for (const inherited of Object.keys(env)) {
|
|
692
|
+
if (inherited.toUpperCase() === key.toUpperCase()) delete env[inherited];
|
|
693
|
+
}
|
|
694
|
+
env[key] = value;
|
|
695
|
+
}
|
|
696
|
+
command = { ...c, env, envMode: "replace" };
|
|
697
|
+
}
|
|
698
|
+
const context = executions.get(signal);
|
|
699
|
+
if (context === undefined) return d.spawn(command, { cwd: c.cwd ?? cwd, signal, lowPriority: low });
|
|
700
|
+
context?.preparation?.end("completed");
|
|
701
|
+
const service = context.observation.execution("command", context.candidate);
|
|
702
|
+
let result = "error";
|
|
703
|
+
try {
|
|
704
|
+
const out = await d.spawn(command, { cwd: c.cwd ?? cwd, signal, lowPriority: low,
|
|
705
|
+
...(service === undefined ? {} : { service }) });
|
|
706
|
+
result = signal.aborted ? "interrupted" : out.timedOut ? "timed-out" : out.exitCode === 0 ? "pass" : "fail";
|
|
707
|
+
return out;
|
|
708
|
+
} finally {
|
|
709
|
+
service?.end(result);
|
|
710
|
+
if (context !== undefined) context.preparation = context.observation.start("service-prep", "command-planning", context.candidate);
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
function asExec(o: CommandOutput): ExecResult {
|
|
715
|
+
return { code: o.exitCode ?? -1, stdout: o.stdout, stderr: o.stderr, timedOut: o.timedOut };
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
function search(cwd: string, signal: AbortSignal): TestSearchSeam {
|
|
719
|
+
const git = async (root: string, args: readonly string[]) => {
|
|
720
|
+
try {
|
|
721
|
+
const guards = workRootGuards(cwd);
|
|
722
|
+
const env = runEnvironment(gitEnvironment(), process.platform, undefined, { guards });
|
|
723
|
+
const r = await d.spawn(
|
|
724
|
+
{ label: "git", file: gitExecutable(guards), args: [...hardeningArgs(), "-C", root, ...args], source: "run-command", ref: null, cwd,
|
|
725
|
+
env: Object.fromEntries(Object.entries(env).filter((entry): entry is [string, string] => entry[1] !== undefined)), envMode: "replace" },
|
|
726
|
+
{ cwd, signal, lowPriority: true },
|
|
727
|
+
);
|
|
728
|
+
return r.timedOut ? undefined : r;
|
|
729
|
+
} catch {
|
|
730
|
+
return undefined;
|
|
731
|
+
}
|
|
732
|
+
};
|
|
733
|
+
const abs = (root: string, text: string) => splitNul(text).map(rel => nodePath.resolve(root, rel));
|
|
734
|
+
const lit = (n: string) => n.replace(/[*?[\]\\]/g, c => (c === "\\" ? "[\\\\]" : `[${c}]`));
|
|
735
|
+
return {
|
|
736
|
+
async findByName(gitRoot, names) {
|
|
737
|
+
const r = await git(gitRoot, ["ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", ...names.map(n => `:(glob)**/${lit(n)}`)]);
|
|
738
|
+
return r !== undefined && r.exitCode === 0 ? abs(gitRoot, r.stdout) : undefined;
|
|
739
|
+
},
|
|
740
|
+
async findByContent(gitRoot, needle, globs, options) {
|
|
741
|
+
const r = await git(gitRoot, ["grep", "-l", "-z", "-F", ...(options?.word === true ? ["-w"] : []), "--untracked", "-e", needle, "--", ...globs]);
|
|
742
|
+
if (r === undefined) return undefined;
|
|
743
|
+
if (r.exitCode === 1) return [];
|
|
744
|
+
return r.exitCode === 0 ? abs(gitRoot, r.stdout) : undefined;
|
|
745
|
+
},
|
|
746
|
+
};
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
function component(name: ComponentResult["name"], c: ResolvedCommand, o: CommandOutput, scope: ComponentResult["scope"], flakyIds: string[] = []): ComponentResult {
|
|
750
|
+
return { name, label: c.label, exitCode: o.exitCode, timedOut: o.timedOut, durationMs: o.durationMs, scope, flakyIds };
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
/** Only scope a known invocation. A ref named `test` can resolve to an unrelated configured command. */
|
|
754
|
+
function scopedCommand(c: ResolvedCommand): string | null {
|
|
755
|
+
// The planner derives its own cwd/environment; it cannot prove equivalence with explicit overrides.
|
|
756
|
+
if (c.cwd !== undefined || c.env !== undefined) return null;
|
|
757
|
+
if (c.source === "package-script" && c.ref?.script === "test" && c.ref.args.length === 0) return "npm test";
|
|
758
|
+
return c.source === "pytest" ? c.label : null;
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
/** M10/M11: one tests component, scoped to the affected tests, with one confirmation rerun of the failing files. */
|
|
762
|
+
async function runTests(
|
|
763
|
+
t: TestComponent, cwd: string, changed: readonly ChangedPath[], signal: AbortSignal, low: boolean,
|
|
764
|
+
): Promise<TestOutcome> {
|
|
765
|
+
const command = scopedCommand(t.full);
|
|
766
|
+
if (command === null) return fullTests(t, command, cwd, signal, low);
|
|
767
|
+
const plan = await planScopedRun({
|
|
768
|
+
command, cwd, changedFiles: changed, budget: { maxWorkers: MAX_WORKERS }, fs: nodeFs, search: search(cwd, signal),
|
|
769
|
+
});
|
|
770
|
+
if (isNoAffected(plan)) {
|
|
771
|
+
const none: CommandOutput = { exitCode: 0, timedOut: false, stdout: "", stderr: "", durationMs: 0 };
|
|
772
|
+
return { comp: component("tests", { ...t.full, label: "no affected tests" }, none, "no-affected"), failing: null };
|
|
773
|
+
}
|
|
774
|
+
// Unscoped or unverifiable: never counted as verified without a run, so the full command decides.
|
|
775
|
+
if (!isScopedSpec(plan)) return fullTests(t, command, cwd, signal, low);
|
|
776
|
+
const spec: ResolvedCommand = { ...t.full, file: plan.file, args: plan.args, env: plan.env, cwd: plan.cwd };
|
|
777
|
+
const out = await exec(spec, cwd, signal, low);
|
|
778
|
+
const result = await readResult(plan, asExec(out), nodeFs);
|
|
779
|
+
const comp = component("tests", spec, out, "spec");
|
|
780
|
+
if (out.exitCode === 0 && !out.timedOut && !result.collectionError && result.complete) return { comp, failing: null };
|
|
781
|
+
const first: Failing = { ids: [...result.failingIds], files: [...result.failingFiles], output: tail(out.stdout + out.stderr, OUTPUT_TAIL_BYTES) };
|
|
782
|
+
// M10/M11: a timeout or a collection error is a final failure.
|
|
783
|
+
if (out.timedOut || result.collectionError) return { comp, failing: first };
|
|
784
|
+
// QA-3.2-7: an incomplete report (exit 0 or not), or a failure that names no id, is no evidence either way: the
|
|
785
|
+
// full command decides, the partial report never blames (and an id-less failure is never confirmed away).
|
|
786
|
+
if (!result.complete || first.ids.length === 0) return fullTests(t, command, cwd, signal, low);
|
|
787
|
+
return confirm(t, command, cwd, signal, low, comp, first);
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
/** QA-3.2-22/-24: the files of `files` that exist; a test id names a rerunnable file only then. */
|
|
791
|
+
async function existing(files: readonly string[]): Promise<string[]> {
|
|
792
|
+
const exists = d.fileExists ?? fileExistsOnDisk;
|
|
793
|
+
const out: string[] = [];
|
|
794
|
+
for (const f of files) if (await exists(f)) out.push(f);
|
|
795
|
+
return out;
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
/** The full test command: exit 0 without a timeout passes; a failure names the ids its output lists (QA-3.2-1). */
|
|
799
|
+
async function runFull(c: ResolvedCommand, cwd: string, signal: AbortSignal, low: boolean) {
|
|
800
|
+
const out = await exec(c, cwd, signal, low);
|
|
801
|
+
const pass = out.exitCode === 0 && !out.timedOut;
|
|
802
|
+
return { out, pass, seen: pass || out.timedOut ? null : observeFull(out, c.cwd ?? cwd), output: tail(out.stdout + out.stderr, OUTPUT_TAIL_BYTES) };
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
async function fullTests(t: TestComponent, command: string | null, cwd: string, signal: AbortSignal, low: boolean): Promise<TestOutcome> {
|
|
806
|
+
const f = await runFull(t.full, cwd, signal, low);
|
|
807
|
+
const comp = component("tests", t.full, f.out, "full");
|
|
808
|
+
if (f.pass) return { comp, failing: null };
|
|
809
|
+
// M11 calls an id flaky only against a complete id inventory whose files all exist (QA-3.2-22: a file the rerun
|
|
810
|
+
// planner drops would leave its ids unrun, and an unrun id must never read as flaky).
|
|
811
|
+
const seen = f.seen;
|
|
812
|
+
const failing: Failing = { ids: seen?.ids ?? [], files: seen?.files ?? [], output: f.output };
|
|
813
|
+
if (command === null || seen === null || !seen.complete || (await existing(seen.files)).length < seen.files.length) return { comp, failing };
|
|
814
|
+
return confirm(t, command, cwd, signal, low, comp, failing);
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
/**
|
|
818
|
+
* M11: one confirmation rerun of the failing files. Only a passing run with a complete report clears an id
|
|
819
|
+
* (QA-3.2-7); an incomplete rerun clears nothing and the full command is the second observation instead.
|
|
820
|
+
*/
|
|
821
|
+
async function confirm(t: TestComponent, command: string, cwd: string, signal: AbortSignal, low: boolean, comp: ComponentResult, first: Failing): Promise<TestOutcome> {
|
|
822
|
+
const runner = await detectRunner(command, cwd, nodeFs);
|
|
823
|
+
if (isUnverifiable(runner)) return { comp, failing: first };
|
|
824
|
+
const again = await planRerun(runner, first.files, cwd, { maxWorkers: MAX_WORKERS }, { fs: nodeFs });
|
|
825
|
+
if (!isScopedSpec(again)) return { comp, failing: first };
|
|
826
|
+
const rerunSpec: ResolvedCommand = { ...t.full, file: again.file, args: again.args, env: again.env, cwd: again.cwd };
|
|
827
|
+
const out = await exec(rerunSpec, cwd, signal, low);
|
|
828
|
+
const result = await readResult(again, asExec(out), nodeFs);
|
|
829
|
+
const sure = !out.timedOut && !result.collectionError;
|
|
830
|
+
if (!sure || result.complete) {
|
|
831
|
+
const seen = sure ? { ids: result.failingIds, complete: true } : null;
|
|
832
|
+
return settle(component("tests", rerunSpec, out, "rerun"), first, confirmedOf(first.ids, sure && out.exitCode === 0, seen), tail(out.stdout + out.stderr, OUTPUT_TAIL_BYTES));
|
|
833
|
+
}
|
|
834
|
+
const f = await runFull(t.full, cwd, signal, low);
|
|
835
|
+
return settle(component("tests", t.full, f.out, "full"), first, confirmedOf(first.ids, f.pass, f.seen), f.output);
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
/** M11: the original ids a second observation confirms. Only a pass clears them; a second failure naming none keeps them all. */
|
|
839
|
+
function confirmedOf(ids: readonly string[], pass: boolean, seen: { ids: readonly string[]; complete: boolean } | null): string[] {
|
|
840
|
+
if (pass) return [];
|
|
841
|
+
const hit = seen !== null && seen.complete ? ids.filter(id => seen.ids.includes(id)) : [];
|
|
842
|
+
return hit.length > 0 ? hit : [...ids];
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
function settle(comp: ComponentResult, first: Failing, failingNow: string[], output: string): TestOutcome {
|
|
846
|
+
const judged: ComponentResult = { ...comp, flakyIds: first.ids.filter(id => !failingNow.includes(id)) };
|
|
847
|
+
return { comp: judged, failing: failingNow.length === 0 ? null : { ids: failingNow, files: first.files, output } };
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
/**
|
|
851
|
+
* QA-3.2-6: regression files come from the slot that observed them (the `ci` slot, absolute). Each is re-rooted under
|
|
852
|
+
* `cwd`: the part below the plan slot (or integration worktree) that holds it, else the path as given if relative.
|
|
853
|
+
* An absolute path under no known root is kept; the rerun then cannot map it and does not pass.
|
|
854
|
+
*/
|
|
855
|
+
async function reroot(files: readonly string[], cwd: string): Promise<string[]> {
|
|
856
|
+
if (files.length === 0) return [];
|
|
857
|
+
const l = d.ledger();
|
|
858
|
+
const roots = [l.integration.worktree, ...(await d.pool.list(l.planId)).map(r => r.path)];
|
|
859
|
+
return files.map(f => {
|
|
860
|
+
if (!nodePath.isAbsolute(f)) return nodePath.join(cwd, f);
|
|
861
|
+
for (const root of roots) {
|
|
862
|
+
const rel = nodePath.relative(root, f);
|
|
863
|
+
if (rel !== "" && !rel.startsWith("..") && !nodePath.isAbsolute(rel)) return nodePath.join(cwd, rel);
|
|
864
|
+
}
|
|
865
|
+
return f;
|
|
866
|
+
});
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
/**
|
|
870
|
+
* QA-3.2-6/-24/-26: the regression of a revert, judged on its own ids. A test command reruns the regression files
|
|
871
|
+
* that exist here. With none (no file given, a file `reroot` could not map, the culprit's own test file reverted
|
|
872
|
+
* away), an unscoped run, a non-test command or an incomplete report, the whole command runs instead: a run that
|
|
873
|
+
* ran nothing never passes the regression. A passing run passes. A failing run fails with the regression ids it
|
|
874
|
+
* names, and with every regression id when it names none of them (fail closed: another id form, or another failure
|
|
875
|
+
* hiding them, cannot clear the regression).
|
|
876
|
+
*/
|
|
877
|
+
async function regressionTests(
|
|
878
|
+
c: ResolvedCommand, ids: readonly string[], files: readonly string[], cwd: string, signal: AbortSignal, low: boolean,
|
|
879
|
+
): Promise<TestOutcome> {
|
|
880
|
+
const fail = (named: readonly string[], output: string): Failing => {
|
|
881
|
+
const still = ids.filter(id => named.includes(id));
|
|
882
|
+
return { ids: still.length > 0 ? still : [...ids], files: [...files], output };
|
|
883
|
+
};
|
|
884
|
+
const present = await existing(files);
|
|
885
|
+
const command = scopedCommand(c);
|
|
886
|
+
if (present.length > 0 && command !== null) {
|
|
887
|
+
const runner = await detectRunner(command, cwd, nodeFs);
|
|
888
|
+
const plan = isUnverifiable(runner) ? runner : await planRerun(runner, present, cwd, { maxWorkers: MAX_WORKERS }, { fs: nodeFs });
|
|
889
|
+
if (isScopedSpec(plan)) {
|
|
890
|
+
const spec: ResolvedCommand = { ...c, file: plan.file, args: plan.args, env: plan.env, cwd: plan.cwd };
|
|
891
|
+
const out = await exec(spec, cwd, signal, low);
|
|
892
|
+
const result = await readResult(plan, asExec(out), nodeFs);
|
|
893
|
+
const comp = component("regression", spec, out, "rerun");
|
|
894
|
+
const output = tail(out.stdout + out.stderr, OUTPUT_TAIL_BYTES);
|
|
895
|
+
if (out.timedOut || result.collectionError) return { comp, failing: fail([], output) };
|
|
896
|
+
if (result.complete) return { comp, failing: out.exitCode === 0 ? null : fail(result.failingIds, output) };
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
const f = await runFull(c, cwd, signal, low);
|
|
900
|
+
return { comp: component("regression", c, f.out, "full"), failing: f.pass ? null : fail(f.seen?.ids ?? [], f.output) };
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
async function run(req: CheckRequest): Promise<CheckResult> {
|
|
904
|
+
const started = d.clock.now();
|
|
905
|
+
const components: ComponentResult[] = [];
|
|
906
|
+
const elapsed = () => d.clock.now() - started;
|
|
907
|
+
const preparation = req.observation?.start("service-prep", "checkout-and-selection", req.candidate);
|
|
908
|
+
const err = (reason: CheckErrorReason, message: string): CheckResult => {
|
|
909
|
+
preparation?.end("error");
|
|
910
|
+
return { verdict: "error", reason, message, components, durationMs: elapsed() };
|
|
911
|
+
};
|
|
912
|
+
const cwd = req.slot.path;
|
|
913
|
+
let selection: CheckSelection;
|
|
914
|
+
let changed: ChangedPath[];
|
|
915
|
+
// These read immutable commit objects, not the checkout. Handle rejection immediately, but let prepare fail first.
|
|
916
|
+
const reads = settledReads([readSelection(cwd, req.candidate), Promise.resolve().then(() => d.igit.diffNameStatus(cwd, req.base, req.candidate))] as const)
|
|
917
|
+
.then(value => ({ ok: true as const, value }), (error: unknown) => ({ ok: false as const, error }));
|
|
918
|
+
try {
|
|
919
|
+
if (req.reuseCheckout) await prepareReused(req.slot, req.candidate);
|
|
920
|
+
else await prepare(req.slot, req.candidate);
|
|
921
|
+
} catch (e) {
|
|
922
|
+
await reads;
|
|
923
|
+
return err("prepare", errText(e));
|
|
924
|
+
}
|
|
925
|
+
let extraFiles: string[];
|
|
926
|
+
try {
|
|
927
|
+
const read = await reads;
|
|
928
|
+
if (!read.ok) throw read.error;
|
|
929
|
+
selection = await resolveSelection(cwd, read.value[0]);
|
|
930
|
+
changed = read.value[1].map(n => ({ path: nodePath.join(cwd, n.path), status: n.status }));
|
|
931
|
+
extraFiles = await reroot(req.extra?.files ?? [], cwd);
|
|
932
|
+
} catch (e) {
|
|
933
|
+
return err(e instanceof CheckResolveError ? "resolve" : "prepare", errText(e));
|
|
934
|
+
}
|
|
935
|
+
const extraIds = req.extra?.ids ?? [];
|
|
936
|
+
// QA-3.2-6: regression ids need test commands to rerun them; without the suite's, this commit's tests serve.
|
|
937
|
+
let regression = extraIds.length > 0 && (req.extra?.commands ?? []).length === 0 ? selection.tests.map(t => t.full) : req.extra?.commands ?? [];
|
|
938
|
+
try {
|
|
939
|
+
regression = await Promise.all(regression.map(c => resolveForSlot(c, cwd)));
|
|
940
|
+
} catch (e) {
|
|
941
|
+
return err("resolve", errText(e));
|
|
942
|
+
}
|
|
943
|
+
if (extraIds.length > 0 && regression.length === 0) return err("resolve", "the regression ids have no test command to rerun them");
|
|
944
|
+
preparation?.end("completed");
|
|
945
|
+
if (selection.typecheck === null && selection.tests.length === 0 && selection.extras.length === 0 && regression.length === 0) {
|
|
946
|
+
return { verdict: "pass", components, flakyIds: [], note: "no-checks", durationMs: elapsed() };
|
|
947
|
+
}
|
|
948
|
+
const low = req.priority === "background";
|
|
949
|
+
const held = await underSlot({ signal: req.signal, priority: req.priority, cwd, command: "integration checks",
|
|
950
|
+
observation: req.observation, candidate: req.candidate }, async (signal): Promise<CheckResult | null> => {
|
|
951
|
+
const simple = async (name: "typecheck" | "extra" | "regression", c: ResolvedCommand): Promise<CheckResult | null> => {
|
|
952
|
+
const out = await exec(c, cwd, signal, low);
|
|
953
|
+
components.push(component(name, c, out, "full"));
|
|
954
|
+
if (out.exitCode === 0 && !out.timedOut) return null;
|
|
955
|
+
return {
|
|
956
|
+
verdict: "fail", components, failingIds: [], failingFiles: [], flakyIds: [], output: tail(out.stdout + out.stderr, OUTPUT_TAIL_BYTES), durationMs: elapsed(),
|
|
957
|
+
};
|
|
958
|
+
};
|
|
959
|
+
if (selection.typecheck !== null) {
|
|
960
|
+
const r = await simple("typecheck", selection.typecheck);
|
|
961
|
+
if (r !== null) return r;
|
|
962
|
+
}
|
|
963
|
+
for (const t of selection.tests) {
|
|
964
|
+
const o = await runTests(t, cwd, changed, signal, low);
|
|
965
|
+
components.push(o.comp);
|
|
966
|
+
if (o.failing !== null) {
|
|
967
|
+
return { verdict: "fail", components, failingIds: o.failing.ids, failingFiles: o.failing.files, flakyIds: o.comp.flakyIds, output: o.failing.output, durationMs: elapsed() };
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
for (const c of selection.extras) {
|
|
971
|
+
const r = await simple("extra", c);
|
|
972
|
+
if (r !== null) return r;
|
|
973
|
+
}
|
|
974
|
+
for (const c of regression) {
|
|
975
|
+
// Without ids the regression is the whole command (an unattributed failure that passed at the phase base).
|
|
976
|
+
if (extraIds.length === 0) {
|
|
977
|
+
const r = await simple("regression", c);
|
|
978
|
+
if (r !== null) return r;
|
|
979
|
+
continue;
|
|
980
|
+
}
|
|
981
|
+
const o = await regressionTests(c, extraIds, extraFiles, cwd, signal, low);
|
|
982
|
+
components.push(o.comp);
|
|
983
|
+
if (o.failing !== null) {
|
|
984
|
+
return { verdict: "fail", components, failingIds: o.failing.ids, failingFiles: o.failing.files, flakyIds: [], output: o.failing.output, durationMs: elapsed() };
|
|
985
|
+
}
|
|
986
|
+
}
|
|
987
|
+
return null;
|
|
988
|
+
}).catch((e: unknown): Held<CheckResult | null> => ({ ok: false, reason: "spawn", message: errText(e) }));
|
|
989
|
+
if (!held.ok) return err(held.reason, held.message);
|
|
990
|
+
if (held.value !== null) return held.value;
|
|
991
|
+
return { verdict: "pass", components, flakyIds: components.flatMap(c => c.flakyIds), note: null, durationMs: elapsed() };
|
|
992
|
+
}
|
|
993
|
+
|
|
994
|
+
async function runCommands(req: CommandRunRequest): Promise<CommandRunResult> {
|
|
995
|
+
const started = d.clock.now();
|
|
996
|
+
const cwd = req.slot.path;
|
|
997
|
+
const base = { ids: [] as string[], files: [] as string[], idsUnparsed: false, scope: "full" as const, output: "", durationMs: 0, error: null };
|
|
998
|
+
const preparation = req.observation?.start("service-prep", "checkout-and-selection", req.commit);
|
|
999
|
+
const done = (r: Partial<CommandRunResult> & { verdict: CommandRunResult["verdict"] }): CommandRunResult => {
|
|
1000
|
+
preparation?.end(r.verdict === "error" ? "error" : "completed");
|
|
1001
|
+
return { ...base, ...r, durationMs: d.clock.now() - started };
|
|
1002
|
+
};
|
|
1003
|
+
if (req.prepare) {
|
|
1004
|
+
try {
|
|
1005
|
+
await prepare(req.slot, req.commit);
|
|
1006
|
+
} catch (e) {
|
|
1007
|
+
return done({ verdict: "error", error: { reason: "prepare", message: errText(e) } });
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
let commands: ResolvedCommand[];
|
|
1011
|
+
try {
|
|
1012
|
+
commands = await Promise.all(req.commands.map(c => resolveForSlot(c, cwd)));
|
|
1013
|
+
} catch (e) {
|
|
1014
|
+
return done({ verdict: "error", error: { reason: "resolve", message: errText(e) } });
|
|
1015
|
+
}
|
|
1016
|
+
preparation?.end("completed");
|
|
1017
|
+
const low = req.priority === "background";
|
|
1018
|
+
const held = await underSlot({ signal: req.signal, priority: req.priority, cwd, command: "integration commands", budget: req.preempt,
|
|
1019
|
+
observation: req.observation, candidate: req.commit }, async (signal): Promise<CommandRunResult> => {
|
|
1020
|
+
const ids = new Set<string>();
|
|
1021
|
+
const files = new Set<string>();
|
|
1022
|
+
let output = "";
|
|
1023
|
+
let unparsed = false;
|
|
1024
|
+
let failed = false;
|
|
1025
|
+
let scope: CommandRunResult["scope"] = req.mode === "full" ? "full" : "rerun";
|
|
1026
|
+
for (const c of commands) {
|
|
1027
|
+
const command = scopedCommand(c);
|
|
1028
|
+
if (typeof req.mode !== "string" && command !== null) {
|
|
1029
|
+
const wanted = [...new Set(req.mode.rerun.map(fileOfId))].map(f => nodePath.resolve(cwd, f));
|
|
1030
|
+
const runner = await detectRunner(command, cwd, nodeFs);
|
|
1031
|
+
const plan = isUnverifiable(runner) ? runner : await planRerun(runner, wanted, cwd, { maxWorkers: MAX_WORKERS }, { fs: nodeFs });
|
|
1032
|
+
if (isNoAffected(plan)) {
|
|
1033
|
+
// QA-3.2-22: where the failure was observed, a rerun that maps to no test ran nothing: a failure, never a pass.
|
|
1034
|
+
if (req.requireRun === true) {
|
|
1035
|
+
failed = true;
|
|
1036
|
+
unparsed = true;
|
|
1037
|
+
output = `the rerun ran no test: ${wanted.length} failing file(s) map to no test file`;
|
|
1038
|
+
}
|
|
1039
|
+
continue;
|
|
1040
|
+
}
|
|
1041
|
+
if (isScopedSpec(plan)) {
|
|
1042
|
+
const spec: ResolvedCommand = { ...c, file: plan.file, args: plan.args, env: plan.env, cwd: plan.cwd };
|
|
1043
|
+
const out = await exec(spec, cwd, signal, low);
|
|
1044
|
+
const result = await readResult(plan, asExec(out), nodeFs);
|
|
1045
|
+
// QA-3.2-1 (3): a rerun passes only on a complete result; exit 0 alone is not evidence.
|
|
1046
|
+
if (out.exitCode === 0 && !out.timedOut && result.complete && !result.collectionError) continue;
|
|
1047
|
+
if (out.timedOut || (out.exitCode !== 0 && result.failingIds.length > 0)) {
|
|
1048
|
+
failed = true;
|
|
1049
|
+
output = tail(out.stdout + out.stderr, OUTPUT_TAIL_BYTES);
|
|
1050
|
+
for (const id of result.failingIds) ids.add(id);
|
|
1051
|
+
for (const f of result.failingFiles) files.add(f);
|
|
1052
|
+
if (!result.complete || result.collectionError || out.timedOut) unparsed = true;
|
|
1053
|
+
continue;
|
|
1054
|
+
}
|
|
1055
|
+
// An incomplete result (or a failure without ids): fall back to the full command below.
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1058
|
+
scope = "full";
|
|
1059
|
+
const out = await exec(c, cwd, signal, low);
|
|
1060
|
+
if (out.exitCode !== 0 || out.timedOut) {
|
|
1061
|
+
failed = true;
|
|
1062
|
+
output = tail(out.stdout + out.stderr, OUTPUT_TAIL_BYTES);
|
|
1063
|
+
// QA-3.2-1 (1): the failing ids of a full test run come from its output (vitest/jest `FAIL <file> > …`,
|
|
1064
|
+
// pytest `FAILED <file>::…`, a jest JSON report). An incomplete inventory, a timeout or output without ids
|
|
1065
|
+
// leaves the failure unattributable.
|
|
1066
|
+
const seen = out.timedOut ? null : observeFull(out, c.cwd ?? cwd);
|
|
1067
|
+
if (seen === null) {
|
|
1068
|
+
unparsed = true;
|
|
1069
|
+
break;
|
|
1070
|
+
}
|
|
1071
|
+
for (const id of seen.ids) ids.add(id);
|
|
1072
|
+
for (const f of seen.files) files.add(f);
|
|
1073
|
+
// QA-3.2-22: ids whose files do not exist here (a vitest root or a delegating script elsewhere) cannot be rerun
|
|
1074
|
+
// by file: the failure is unattributable, so reruns and probes run the full commands.
|
|
1075
|
+
if (!seen.complete || (await existing(seen.files)).length < seen.files.length) unparsed = true;
|
|
1076
|
+
}
|
|
1077
|
+
}
|
|
1078
|
+
// Every failure path without ids sets `unparsed`, so a parsed failure always names at least one id.
|
|
1079
|
+
return done({ verdict: failed ? "fail" : "pass", ids: [...ids].sort(), files: [...files].sort(), idsUnparsed: failed && unparsed, scope, output });
|
|
1080
|
+
}).catch((e: unknown): Held<CommandRunResult> => ({ ok: false, reason: "spawn", message: errText(e) }));
|
|
1081
|
+
if (!held.ok) return done({ verdict: "error", error: { reason: held.reason, message: held.message } });
|
|
1082
|
+
return held.value;
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
return { prepare, select, run, runCommands };
|
|
1086
|
+
}
|