pi-spine 2.2.0 → 2.3.1
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/bin/spine-cli/verify.mjs +15 -46
- package/package.json +1 -1
- package/src/batch/attached-runner-promote.mjs +370 -0
- package/src/batch/attached-runner-reconcile.mjs +291 -0
- package/src/batch/attached-runner.mjs +24 -645
- package/src/batch/batch-guards.mjs +69 -0
- package/src/batch/contract-exec.mjs +483 -0
- package/src/batch/contract-parse.mjs +243 -0
- package/src/batch/contract-verify.mjs +32 -707
- package/src/batch/detached-diagnostics.mjs +255 -0
- package/src/batch/detached-run.mjs +326 -0
- package/src/batch/detached-start.mjs +18 -894
- package/src/batch/detached-wait.mjs +346 -0
- package/src/batch/diagnosis.mjs +35 -4
- package/src/batch/engine-lanes/orch-sync.mjs +126 -0
- package/src/batch/engine-lanes.mjs +69 -0
- package/src/batch/engine.mjs +8 -67
- package/src/batch/integrate-git.mjs +21 -0
- package/src/batch/integrate.mjs +5 -15
- package/src/batch/journal-rebuild-structural.mjs +352 -0
- package/src/batch/journal-rebuild.mjs +16 -348
- package/src/batch/lane-dirty-check-commit.mjs +361 -0
- package/src/batch/lane-dirty-check-git.mjs +298 -0
- package/src/batch/lane-dirty-check.mjs +31 -297
- package/src/batch/reconcile-batch.mjs +495 -0
- package/src/batch/reconcile-classify.mjs +433 -0
- package/src/batch/reconcile-diagnosis.mjs +459 -0
- package/src/batch/reconcile-light-cache.mjs +61 -0
- package/src/batch/reconcile-orphan.mjs +198 -0
- package/src/batch/reconcile.mjs +19 -1693
- package/src/batch/resume-multi-lanes.mjs +6 -148
- package/src/batch/resume-multi-queue.mjs +159 -0
- package/src/batch/resume-single-validate.mjs +25 -0
- package/src/batch/resume.mjs +3 -20
- package/src/batch/review-artifacts.mjs +419 -0
- package/src/batch/review-step-run.mjs +383 -0
- package/src/batch/review-step.mjs +451 -0
- package/src/batch/review.mjs +32 -1199
- package/src/batch/salvage-batch-list.mjs +291 -0
- package/src/batch/salvage-batch.mjs +10 -284
- package/src/batch/sequence-plan.mjs +234 -0
- package/src/batch/sequence-run.mjs +418 -0
- package/src/batch/sequence-wait.mjs +167 -0
- package/src/batch/sequence.mjs +22 -783
- package/src/batch/state-guards.mjs +284 -0
- package/src/batch/state-io.mjs +135 -0
- package/src/batch/state.mjs +27 -396
- package/src/batch/worker-heartbeat.mjs +382 -0
- package/src/batch/worker-host.mjs +56 -548
- package/src/batch/worker-spawn.mjs +326 -0
- package/src/batch/worktree.mjs +68 -0
- package/src/config/preflight/integrate-plan.mjs +6 -1
- package/src/config/preflight/loc-capstone.mjs +274 -0
- package/src/config/spine-preflight-lib.mjs +14 -0
- package/src/planner/index.mjs +14 -3
- package/src/process/terminate-tree.mjs +154 -0
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
/**
|
|
3
|
+
* Nested batch-spawn guards (SP-482 / SP-588).
|
|
4
|
+
* Blocks workers from starting a batch engine inside a lane worktree.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { appendJournalEvent } from "./journal.mjs";
|
|
8
|
+
|
|
9
|
+
const WORKTREE_SPINE_PATTERN = /[/\\]\.worktrees[/\\]spine-/;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Detect whether the current process is running inside a spine worker context.
|
|
13
|
+
* Returns a human-readable reason string if nested, or null if safe to proceed.
|
|
14
|
+
*
|
|
15
|
+
* Two guards: (1) SPINE_IS_WORKER env set by worker-host, and
|
|
16
|
+
* (2) projectRoot inside a .worktrees/spine-* directory (catches cases where
|
|
17
|
+
* the env was not inherited but the target is clearly a lane worktree).
|
|
18
|
+
*
|
|
19
|
+
* @param {string} projectRoot — the directory where the batch would run
|
|
20
|
+
* @returns {string | null}
|
|
21
|
+
*/
|
|
22
|
+
export function detectNestedWorkerContext(projectRoot) {
|
|
23
|
+
if (process.env.SPINE_IS_WORKER === "1") {
|
|
24
|
+
return "SPINE_IS_WORKER=1 is set (running inside a worker process)";
|
|
25
|
+
}
|
|
26
|
+
const parentBatchId = process.env.SPINE_PARENT_BATCH_ID ?? process.env.SPINE_BATCH_ID;
|
|
27
|
+
if (parentBatchId && WORKTREE_SPINE_PATTERN.test(projectRoot)) {
|
|
28
|
+
return (
|
|
29
|
+
`parent batch ${parentBatchId} is active and projectRoot is inside a ` +
|
|
30
|
+
`.worktrees/spine-* lane directory`
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
if (WORKTREE_SPINE_PATTERN.test(projectRoot)) {
|
|
34
|
+
return "projectRoot is inside a .worktrees/spine-* lane directory";
|
|
35
|
+
}
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* If nested, journal and return the startBatch error result; otherwise null.
|
|
41
|
+
*
|
|
42
|
+
* @param {string} projectRoot
|
|
43
|
+
* @returns {{ ok: false, exitCode: number, error: string, output: string } | null}
|
|
44
|
+
*/
|
|
45
|
+
export function rejectNestedBatchStart(projectRoot) {
|
|
46
|
+
const nestedReason = detectNestedWorkerContext(projectRoot);
|
|
47
|
+
if (!nestedReason) {
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
const parentBatchId = process.env.SPINE_PARENT_BATCH_ID ?? process.env.SPINE_BATCH_ID ?? "unknown";
|
|
51
|
+
try {
|
|
52
|
+
appendJournalEvent(projectRoot, parentBatchId, "engine.nested_spawn_blocked", {
|
|
53
|
+
projectRoot,
|
|
54
|
+
parentBatchId,
|
|
55
|
+
reason: nestedReason,
|
|
56
|
+
});
|
|
57
|
+
} catch {
|
|
58
|
+
// Journal may not be writable from a worker worktree; best-effort.
|
|
59
|
+
}
|
|
60
|
+
return {
|
|
61
|
+
ok: false,
|
|
62
|
+
exitCode: 1,
|
|
63
|
+
error: "nested_batch_spawn_blocked",
|
|
64
|
+
output:
|
|
65
|
+
`Nested batch start blocked: ${nestedReason}. ` +
|
|
66
|
+
`Workers must not spawn batch engines. ` +
|
|
67
|
+
`Parent batch: ${parentBatchId}, projectRoot: ${projectRoot}\n`,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
@@ -0,0 +1,483 @@
|
|
|
1
|
+
// @ts-nocheck
|
|
2
|
+
/**
|
|
3
|
+
* Contract testCommand execution, npm guard, and verifyContract (SP-603 / SP-541).
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import fs from "node:fs";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import { spawnSync } from "node:child_process";
|
|
9
|
+
import micromatch from "micromatch";
|
|
10
|
+
import { parseAggregateLineCoverage } from "../../scripts/coverage-parse.mjs";
|
|
11
|
+
import {
|
|
12
|
+
isBaseFileScopeSatisfied,
|
|
13
|
+
isPrelandedFileScopeSatisfied,
|
|
14
|
+
isResumeBaselineFileScopeSatisfied,
|
|
15
|
+
} from "./contract-prelanded.mjs";
|
|
16
|
+
import {
|
|
17
|
+
listChangedFiles,
|
|
18
|
+
matchesContractPattern,
|
|
19
|
+
} from "./contract-parse.mjs";
|
|
20
|
+
import { appendJournalEvent } from "./journal.mjs";
|
|
21
|
+
import {
|
|
22
|
+
sanitizeFlutterBuildBeforeAnalyze,
|
|
23
|
+
shouldCleanFlutterBuildBeforeAnalyze,
|
|
24
|
+
} from "./lane-dirty-check.mjs";
|
|
25
|
+
import {
|
|
26
|
+
NPM_TEST_DASH_DASH_RE,
|
|
27
|
+
TEST_COMMAND_NPM_TEST_DASH_DASH_FIX_HINT,
|
|
28
|
+
} from "../tasks/validate-contract-warn.mjs";
|
|
29
|
+
|
|
30
|
+
/** Default stdout/stderr capture limit for contract testCommand (issue #86). */
|
|
31
|
+
export const CONTRACT_TEST_COMMAND_MAX_BUFFER = 10 * 1024 * 1024;
|
|
32
|
+
|
|
33
|
+
/** Default number of retries for failed testCommand (SP-485, issue #136). */
|
|
34
|
+
export const CONTRACT_TEST_DEFAULT_RETRIES = 1;
|
|
35
|
+
|
|
36
|
+
/** Default delay in ms between testCommand retry attempts. */
|
|
37
|
+
export const CONTRACT_TEST_RETRY_DELAY_MS = 5000;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Worker-only env keys stripped from contract testCommand subprocesses so full-suite
|
|
41
|
+
* tests match operator re-run outside worker-host (SP-491, issue #155).
|
|
42
|
+
*/
|
|
43
|
+
export const CONTRACT_TEST_WORKER_ENV_KEYS = ["SPINE_IS_WORKER"];
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Build env for contract testCommand subprocess — omits worker-only keys inherited from
|
|
47
|
+
* worker-host.mjs that would false-fail batch-spawn integration tests (SP-482 guard).
|
|
48
|
+
* Preserves parent batch id as SPINE_PARENT_BATCH_ID so nested-spawn guard can block
|
|
49
|
+
* live engines in lane worktrees while still allowing isolated fixture tests (#162).
|
|
50
|
+
*
|
|
51
|
+
* @param {NodeJS.ProcessEnv} [sourceEnv]
|
|
52
|
+
* @returns {NodeJS.ProcessEnv}
|
|
53
|
+
*/
|
|
54
|
+
export function buildContractTestEnv(sourceEnv = process.env) {
|
|
55
|
+
const env = { ...sourceEnv };
|
|
56
|
+
for (const key of CONTRACT_TEST_WORKER_ENV_KEYS) {
|
|
57
|
+
delete env[key];
|
|
58
|
+
}
|
|
59
|
+
if (env.SPINE_BATCH_ID && !env.SPINE_PARENT_BATCH_ID) {
|
|
60
|
+
env.SPINE_PARENT_BATCH_ID = env.SPINE_BATCH_ID;
|
|
61
|
+
}
|
|
62
|
+
delete env.SPINE_BATCH_ID;
|
|
63
|
+
return env;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* @param {number} byteCount
|
|
68
|
+
*/
|
|
69
|
+
function formatMaxBufferLabel(byteCount) {
|
|
70
|
+
const mib = byteCount / (1024 * 1024);
|
|
71
|
+
if (mib >= 1 && Number.isInteger(mib)) {
|
|
72
|
+
return `${mib}MB`;
|
|
73
|
+
}
|
|
74
|
+
if (byteCount >= 1024) {
|
|
75
|
+
return `${Math.round(byteCount / 1024)}KB`;
|
|
76
|
+
}
|
|
77
|
+
return `${byteCount}B`;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Block the current thread for the given duration without busy-waiting.
|
|
82
|
+
* Safe for CLI/batch tools; not suitable for servers.
|
|
83
|
+
*
|
|
84
|
+
* @param {number} ms
|
|
85
|
+
*/
|
|
86
|
+
function sleepSync(ms) {
|
|
87
|
+
if (ms <= 0) return;
|
|
88
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Write a failure log for a contract testCommand attempt to the task's .reviews/ directory.
|
|
93
|
+
* Returns the written path, or null if taskFolder is not provided.
|
|
94
|
+
*
|
|
95
|
+
* @param {string | undefined} taskFolder
|
|
96
|
+
* @param {string} command
|
|
97
|
+
* @param {{ exitCode: number, output: string, bufferOverflow?: boolean }} result
|
|
98
|
+
* @param {number} attempt
|
|
99
|
+
* @param {number} totalAttempts
|
|
100
|
+
* @returns {string | null}
|
|
101
|
+
*/
|
|
102
|
+
export function writeContractFailureLog(taskFolder, command, result, attempt, totalAttempts) {
|
|
103
|
+
if (!taskFolder) return null;
|
|
104
|
+
const reviewsDir = path.join(taskFolder, ".reviews");
|
|
105
|
+
fs.mkdirSync(reviewsDir, { recursive: true });
|
|
106
|
+
const ts = new Date().toISOString().replace(/[:.]/g, "-");
|
|
107
|
+
const logPath = path.join(reviewsDir, `contract-fail-${ts}.log`);
|
|
108
|
+
const header = [
|
|
109
|
+
"Contract testCommand failure log",
|
|
110
|
+
`Command: ${command}`,
|
|
111
|
+
`Exit code: ${result.exitCode}`,
|
|
112
|
+
`Attempt: ${attempt} of ${totalAttempts}`,
|
|
113
|
+
`Timestamp: ${new Date().toISOString()}`,
|
|
114
|
+
`Buffer overflow: ${result.bufferOverflow ? "yes" : "no"}`,
|
|
115
|
+
"---",
|
|
116
|
+
"",
|
|
117
|
+
].join("\n");
|
|
118
|
+
fs.writeFileSync(logPath, header + (result.output ?? ""), "utf-8");
|
|
119
|
+
return logPath;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Defense in depth: block `npm test -- <path>` before subprocess spawn (issue #187, SP-541).
|
|
124
|
+
*
|
|
125
|
+
* @param {string} command
|
|
126
|
+
* @returns {boolean}
|
|
127
|
+
*/
|
|
128
|
+
export function isRefusedNpmTestDashDashCommand(command) {
|
|
129
|
+
const trimmed = String(command ?? "").trim();
|
|
130
|
+
if (!trimmed || trimmed === "true") {
|
|
131
|
+
return false;
|
|
132
|
+
}
|
|
133
|
+
return NPM_TEST_DASH_DASH_RE.test(trimmed);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* @param {string} command
|
|
138
|
+
* @returns {string}
|
|
139
|
+
*/
|
|
140
|
+
function formatRefusedNpmTestDashDashMessage(command) {
|
|
141
|
+
return `Contract testCommand refused before spawn: npm test -- <path> is blocked at runtime (command: ${command}). ${TEST_COMMAND_NPM_TEST_DASH_DASH_FIX_HINT}`;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* @param {string} worktreePath
|
|
146
|
+
* @param {string} command
|
|
147
|
+
* @param {{ maxBuffer?: number }} [options]
|
|
148
|
+
*/
|
|
149
|
+
export function runContractTestCommand(worktreePath, command, options = {}) {
|
|
150
|
+
const trimmed = String(command ?? "").trim();
|
|
151
|
+
if (!trimmed || trimmed === "true") {
|
|
152
|
+
return { ok: true, exitCode: 0, output: "" };
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
if (isRefusedNpmTestDashDashCommand(trimmed)) {
|
|
156
|
+
const summary = formatRefusedNpmTestDashDashMessage(trimmed);
|
|
157
|
+
return {
|
|
158
|
+
ok: false,
|
|
159
|
+
exitCode: 1,
|
|
160
|
+
output: summary,
|
|
161
|
+
summary,
|
|
162
|
+
refusedBeforeSpawn: true,
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const maxBuffer = options.maxBuffer ?? CONTRACT_TEST_COMMAND_MAX_BUFFER;
|
|
167
|
+
const shell = process.env.SHELL || (process.platform === "win32" ? "cmd.exe" : "/bin/sh");
|
|
168
|
+
const shellFlag = process.platform === "win32" ? "/c" : "-c";
|
|
169
|
+
const result = spawnSync(shell, [shellFlag, trimmed], {
|
|
170
|
+
cwd: worktreePath,
|
|
171
|
+
env: buildContractTestEnv(),
|
|
172
|
+
encoding: "utf-8",
|
|
173
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
174
|
+
timeout: 10 * 60 * 1000,
|
|
175
|
+
maxBuffer,
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
const stdout = String(result.stdout ?? "");
|
|
179
|
+
const stderr = String(result.stderr ?? "");
|
|
180
|
+
const output = `${stdout}\n${stderr}`;
|
|
181
|
+
|
|
182
|
+
if (result.error?.code === "ENOBUFS") {
|
|
183
|
+
const limitLabel = formatMaxBufferLabel(maxBuffer);
|
|
184
|
+
return {
|
|
185
|
+
ok: false,
|
|
186
|
+
exitCode: Number(result.status ?? 255),
|
|
187
|
+
output,
|
|
188
|
+
bufferOverflow: true,
|
|
189
|
+
summary: `testCommand output exceeded maxBuffer (${limitLabel}); use a scoped testCommand instead of full-suite commands. Command: ${trimmed}`,
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const exitCode = Number(result.status ?? 1);
|
|
194
|
+
if (exitCode === 0) {
|
|
195
|
+
return { ok: true, exitCode: 0, output };
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const summary = [stdout.trim(), stderr.trim()].filter(Boolean).join("\n").slice(0, 500);
|
|
199
|
+
return { ok: false, exitCode, output, summary };
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* @param {string} worktreePath
|
|
204
|
+
* @param {object} config
|
|
205
|
+
*/
|
|
206
|
+
function resolveCoverageCommand(config) {
|
|
207
|
+
return (
|
|
208
|
+
config?.testing?.testWithCoverage ??
|
|
209
|
+
config?.testing?.test ??
|
|
210
|
+
"npm run coverage:check"
|
|
211
|
+
);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* @param {string} worktreePath
|
|
216
|
+
* @param {ReturnType<import("../tasks/packet/parse-prompt.mjs").parseContract>} parsedContract
|
|
217
|
+
* @param {object} config
|
|
218
|
+
* @param {string} [testCommandOutput]
|
|
219
|
+
*/
|
|
220
|
+
function resolveLineCoverage(worktreePath, parsedContract, config, testCommandOutput = "") {
|
|
221
|
+
let output = testCommandOutput;
|
|
222
|
+
if (parsedContract.minLineCoverage != null) {
|
|
223
|
+
const parsedFromTest = parseAggregateLineCoverage(output);
|
|
224
|
+
if (parsedFromTest != null) {
|
|
225
|
+
return parsedFromTest;
|
|
226
|
+
}
|
|
227
|
+
const coverageCommand = resolveCoverageCommand(config);
|
|
228
|
+
const coverageResult = runContractTestCommand(worktreePath, coverageCommand);
|
|
229
|
+
output = coverageResult.output;
|
|
230
|
+
}
|
|
231
|
+
return parseAggregateLineCoverage(output);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* @param {string} worktreePath
|
|
236
|
+
* @param {string} artifactPattern
|
|
237
|
+
* @returns {{ ok: boolean, matchedPath?: string }}
|
|
238
|
+
*/
|
|
239
|
+
function findArtifactMatch(worktreePath, artifactPattern) {
|
|
240
|
+
const normalized = String(artifactPattern ?? "").replace(/\\/g, "/");
|
|
241
|
+
if (!normalized) {
|
|
242
|
+
return { ok: false };
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
if (!/[*?[\]{}]/.test(normalized)) {
|
|
246
|
+
const fullPath = path.join(worktreePath, normalized);
|
|
247
|
+
return fs.existsSync(fullPath) ? { ok: true, matchedPath: normalized } : { ok: false };
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const baseDir = path.dirname(normalized);
|
|
251
|
+
const searchRoot = path.join(worktreePath, baseDir);
|
|
252
|
+
if (!fs.existsSync(searchRoot)) {
|
|
253
|
+
return { ok: false };
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** @type {Array<{ abs: string, rel: string }>} */
|
|
257
|
+
const stack = [{ abs: searchRoot, rel: baseDir === "." ? "" : baseDir }];
|
|
258
|
+
while (stack.length > 0) {
|
|
259
|
+
const { abs, rel } = stack.pop();
|
|
260
|
+
for (const entry of fs.readdirSync(abs, { withFileTypes: true })) {
|
|
261
|
+
const entryRel = rel ? `${rel}/${entry.name}` : entry.name;
|
|
262
|
+
const entryAbs = path.join(abs, entry.name);
|
|
263
|
+
if (entry.isDirectory()) {
|
|
264
|
+
stack.push({ abs: entryAbs, rel: entryRel });
|
|
265
|
+
continue;
|
|
266
|
+
}
|
|
267
|
+
if (micromatch.isMatch(entryRel, normalized)) {
|
|
268
|
+
return { ok: true, matchedPath: entryRel };
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
return { ok: false };
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* Prepare lane worktree before contract testCommand (Flutter analyzer hygiene #78).
|
|
278
|
+
*
|
|
279
|
+
* @param {string} worktreePath
|
|
280
|
+
* @param {ReturnType<import("../tasks/packet/parse-prompt.mjs").parseContract>} parsedContract
|
|
281
|
+
* @param {object} [config]
|
|
282
|
+
* @returns {{ hygieneApplied: boolean, cleaned?: boolean, buildDir?: string, reason?: string }}
|
|
283
|
+
*/
|
|
284
|
+
export function prepareContractVerifyEnvironment(worktreePath, parsedContract, config = {}) {
|
|
285
|
+
const testCommand = parsedContract?.testCommand;
|
|
286
|
+
if (!testCommand || !shouldCleanFlutterBuildBeforeAnalyze(testCommand, config)) {
|
|
287
|
+
return { hygieneApplied: false };
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
const result = sanitizeFlutterBuildBeforeAnalyze(worktreePath);
|
|
291
|
+
return { hygieneApplied: true, ...result };
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* @param {string} worktreePath
|
|
296
|
+
* @param {ReturnType<import("../tasks/packet/parse-prompt.mjs").parseContract>} parsedContract
|
|
297
|
+
* @param {object} [config]
|
|
298
|
+
* @param {string} [config.baseBranch]
|
|
299
|
+
* @param {string} [config.sinceCommit] When set, scope file-scope checks to `sinceCommit..HEAD` (serialized lanes).
|
|
300
|
+
* @param {string} [config.taskStartCommit] Alias for `sinceCommit` (SP-415 journal resolution; anchor stable across retry/resume per SP-478).
|
|
301
|
+
* @param {string} [config.projectRoot] Repo root for journal events (optional).
|
|
302
|
+
* @param {string} [config.batchId] Batch ID for journal events (optional).
|
|
303
|
+
* @param {string} [config.taskId] Task ID for journal events (optional).
|
|
304
|
+
* @param {string} [config.taskFolder] Task folder path for writing failure logs to .reviews/ (optional).
|
|
305
|
+
* @returns {{ ok: boolean, checks: Array<{ field: string, ok: boolean, message: string }>, retries?: number }}
|
|
306
|
+
*/
|
|
307
|
+
export function verifyContract(worktreePath, parsedContract, config = {}) {
|
|
308
|
+
/** @type {Array<{ field: string, ok: boolean, message: string }>} */
|
|
309
|
+
const checks = [];
|
|
310
|
+
const baseBranch = config?.baseBranch ?? "main";
|
|
311
|
+
const sinceCommit = config?.sinceCommit ?? config?.taskStartCommit ?? undefined;
|
|
312
|
+
const changedFiles = listChangedFiles(worktreePath, baseBranch, sinceCommit);
|
|
313
|
+
|
|
314
|
+
prepareContractVerifyEnvironment(worktreePath, parsedContract, config);
|
|
315
|
+
|
|
316
|
+
let testCommandOutput = "";
|
|
317
|
+
let testCommandOk = true;
|
|
318
|
+
let retriedCount = 0;
|
|
319
|
+
if (parsedContract.testCommand) {
|
|
320
|
+
const maxRetries = config?.contract?.testRetries ?? CONTRACT_TEST_DEFAULT_RETRIES;
|
|
321
|
+
const retryDelayMs = config?.contract?.testRetryDelayMs ?? CONTRACT_TEST_RETRY_DELAY_MS;
|
|
322
|
+
const totalAttempts = maxRetries + 1;
|
|
323
|
+
let lastResult = null;
|
|
324
|
+
let successAttempt = 0;
|
|
325
|
+
|
|
326
|
+
for (let attempt = 1; attempt <= totalAttempts; attempt++) {
|
|
327
|
+
lastResult = runContractTestCommand(worktreePath, parsedContract.testCommand, {
|
|
328
|
+
maxBuffer: config?.contractTestMaxBuffer,
|
|
329
|
+
});
|
|
330
|
+
|
|
331
|
+
if (lastResult.ok) {
|
|
332
|
+
successAttempt = attempt;
|
|
333
|
+
break;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
writeContractFailureLog(
|
|
337
|
+
config?.taskFolder,
|
|
338
|
+
parsedContract.testCommand,
|
|
339
|
+
lastResult,
|
|
340
|
+
attempt,
|
|
341
|
+
totalAttempts,
|
|
342
|
+
);
|
|
343
|
+
|
|
344
|
+
if (attempt < totalAttempts) {
|
|
345
|
+
retriedCount++;
|
|
346
|
+
if (config?.projectRoot && config?.batchId) {
|
|
347
|
+
appendJournalEvent(config.projectRoot, config.batchId, "contract.test_retry", {
|
|
348
|
+
taskId: config?.taskId,
|
|
349
|
+
attempt,
|
|
350
|
+
exitCode: lastResult.exitCode,
|
|
351
|
+
totalAttempts,
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
sleepSync(retryDelayMs);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
testCommandOutput = lastResult.output;
|
|
359
|
+
testCommandOk = lastResult.ok;
|
|
360
|
+
const attemptLabel = successAttempt > 1
|
|
361
|
+
? ` (passed on attempt ${successAttempt} of ${totalAttempts})`
|
|
362
|
+
: "";
|
|
363
|
+
checks.push({
|
|
364
|
+
field: "testCommand",
|
|
365
|
+
ok: lastResult.ok,
|
|
366
|
+
message: lastResult.ok
|
|
367
|
+
? `testCommand passed${attemptLabel}`
|
|
368
|
+
: lastResult.bufferOverflow
|
|
369
|
+
? `Contract ${lastResult.summary}`
|
|
370
|
+
: `Contract testCommand failed after ${totalAttempts} attempt(s) (exit ${lastResult.exitCode}): ${lastResult.summary || "(no output)"}`,
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
for (const pattern of parsedContract.fileScopeMustChange ?? []) {
|
|
375
|
+
const matched = changedFiles.some((file) =>
|
|
376
|
+
pattern.endsWith("/") ? file.startsWith(pattern) : matchesContractPattern(file, pattern),
|
|
377
|
+
);
|
|
378
|
+
const prelanded = !matched &&
|
|
379
|
+
isPrelandedFileScopeSatisfied(
|
|
380
|
+
worktreePath,
|
|
381
|
+
pattern,
|
|
382
|
+
changedFiles,
|
|
383
|
+
parsedContract,
|
|
384
|
+
config,
|
|
385
|
+
baseBranch,
|
|
386
|
+
{ testCommandOk },
|
|
387
|
+
(worktree, artifactPath) => findArtifactMatch(worktree, artifactPath).ok,
|
|
388
|
+
);
|
|
389
|
+
const resumeBaseline = !matched && !prelanded && sinceCommit &&
|
|
390
|
+
isResumeBaselineFileScopeSatisfied(
|
|
391
|
+
worktreePath,
|
|
392
|
+
pattern,
|
|
393
|
+
changedFiles,
|
|
394
|
+
sinceCommit,
|
|
395
|
+
baseBranch,
|
|
396
|
+
parsedContract,
|
|
397
|
+
{ testCommandOk },
|
|
398
|
+
(worktree, artifactPath) => findArtifactMatch(worktree, artifactPath).ok,
|
|
399
|
+
);
|
|
400
|
+
const baseSatisfied = !matched && !prelanded && !resumeBaseline &&
|
|
401
|
+
isBaseFileScopeSatisfied(
|
|
402
|
+
worktreePath,
|
|
403
|
+
pattern,
|
|
404
|
+
changedFiles,
|
|
405
|
+
parsedContract,
|
|
406
|
+
baseBranch,
|
|
407
|
+
{ testCommandOk },
|
|
408
|
+
(worktree, artifactPath) => findArtifactMatch(worktree, artifactPath).ok,
|
|
409
|
+
config,
|
|
410
|
+
);
|
|
411
|
+
const ok = matched || prelanded || resumeBaseline || baseSatisfied;
|
|
412
|
+
checks.push({
|
|
413
|
+
field: "fileScopeMustChange",
|
|
414
|
+
ok,
|
|
415
|
+
message: matched
|
|
416
|
+
? `fileScopeMustChange matched: ${pattern}`
|
|
417
|
+
: prelanded
|
|
418
|
+
? `fileScopeMustChange pre-landed on ${baseBranch}: ${pattern}`
|
|
419
|
+
: resumeBaseline
|
|
420
|
+
? `fileScopeMustChange pre-landed at resume baseline: ${pattern}`
|
|
421
|
+
: baseSatisfied
|
|
422
|
+
? `fileScopeMustChange satisfied on ${baseBranch}: ${pattern}`
|
|
423
|
+
: `Contract fileScopeMustChange: no matching changes for ${pattern}`,
|
|
424
|
+
});
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
for (const pattern of parsedContract.fileScopeMustNotChange ?? []) {
|
|
428
|
+
const forbidden = changedFiles.filter((file) => matchesContractPattern(file, pattern));
|
|
429
|
+
if (forbidden.length === 0) {
|
|
430
|
+
checks.push({
|
|
431
|
+
field: "fileScopeMustNotChange",
|
|
432
|
+
ok: true,
|
|
433
|
+
message: `fileScopeMustNotChange respected: ${pattern}`,
|
|
434
|
+
});
|
|
435
|
+
} else {
|
|
436
|
+
for (const file of forbidden) {
|
|
437
|
+
checks.push({
|
|
438
|
+
field: "fileScopeMustNotChange",
|
|
439
|
+
ok: false,
|
|
440
|
+
message: `Contract fileScopeMustNotChange: forbidden change ${file}`,
|
|
441
|
+
});
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
if (parsedContract.minLineCoverage != null) {
|
|
447
|
+
const actual = resolveLineCoverage(worktreePath, parsedContract, config, testCommandOutput);
|
|
448
|
+
const required = parsedContract.minLineCoverage;
|
|
449
|
+
if (actual == null) {
|
|
450
|
+
checks.push({
|
|
451
|
+
field: "minLineCoverage",
|
|
452
|
+
ok: false,
|
|
453
|
+
message: `Contract minLineCoverage: could not parse coverage output (required ${required}%)`,
|
|
454
|
+
});
|
|
455
|
+
} else {
|
|
456
|
+
const ok = actual >= required;
|
|
457
|
+
checks.push({
|
|
458
|
+
field: "minLineCoverage",
|
|
459
|
+
ok,
|
|
460
|
+
message: ok
|
|
461
|
+
? `minLineCoverage met: ${actual.toFixed(2)}% >= ${required}%`
|
|
462
|
+
: `Contract minLineCoverage: ${actual.toFixed(2)}% < ${required}%`,
|
|
463
|
+
});
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
for (const artifactPath of parsedContract.artifactsMustExist ?? []) {
|
|
468
|
+
const match = findArtifactMatch(worktreePath, artifactPath);
|
|
469
|
+
checks.push({
|
|
470
|
+
field: "artifactsMustExist",
|
|
471
|
+
ok: match.ok,
|
|
472
|
+
message: match.ok
|
|
473
|
+
? `artifact exists: ${match.matchedPath ?? artifactPath}`
|
|
474
|
+
: `Contract artifactsMustExist: missing ${artifactPath}`,
|
|
475
|
+
});
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
return {
|
|
479
|
+
ok: checks.length === 0 || checks.every((check) => check.ok),
|
|
480
|
+
checks,
|
|
481
|
+
...(retriedCount > 0 ? { retries: retriedCount } : {}),
|
|
482
|
+
};
|
|
483
|
+
}
|