diffpact 0.0.0-stage → 0.4.2
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 +126 -0
- package/LICENSE +21 -0
- package/README.md +214 -2
- package/bin/diffpact.mjs +10 -0
- package/dist/adapters/claude-code.js +191 -0
- package/dist/adapters/codex.js +348 -0
- package/dist/adapters/gemini-agy.js +429 -0
- package/dist/adapters/vercel-board.js +138 -0
- package/dist/amend.js +470 -0
- package/dist/boundaries.js +309 -0
- package/dist/canonical-json.js +63 -0
- package/dist/cli.js +1433 -0
- package/dist/delegate.js +140 -0
- package/dist/doctor.js +293 -0
- package/dist/git.js +219 -0
- package/dist/index.js +19 -0
- package/dist/merge-verify.js +721 -0
- package/dist/report.js +220 -0
- package/dist/review.js +527 -0
- package/dist/runner.js +213 -0
- package/dist/schema.js +424 -0
- package/dist/types.js +220 -0
- package/dist/verify.js +952 -0
- package/dist/worktree.js +717 -0
- package/examples/harnesses/README.md +63 -0
- package/examples/quickstart/README.md +17 -0
- package/examples/quickstart/run.mjs +247 -0
- package/package.json +62 -4
- package/schemas/contract.schema.json +148 -0
- package/schemas/receipt.schema.json +49 -0
- package/schemas/review.schema.json +48 -0
|
@@ -0,0 +1,721 @@
|
|
|
1
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { evaluatePathBoundary, normalizeRepoRelativePath } from './boundaries.js';
|
|
5
|
+
import { canonicalSha256, sha256Hex } from './canonical-json.js';
|
|
6
|
+
import {
|
|
7
|
+
collectRepoChanges,
|
|
8
|
+
commitExists,
|
|
9
|
+
ensureGitInfoExclude,
|
|
10
|
+
isAncestor,
|
|
11
|
+
resolveCurrentBranch,
|
|
12
|
+
resolveHeadSha,
|
|
13
|
+
resolveRepoRoot,
|
|
14
|
+
runGitText
|
|
15
|
+
} from './git.js';
|
|
16
|
+
import { validateContract } from './schema.js';
|
|
17
|
+
import {
|
|
18
|
+
EXIT_INCOMPLETE,
|
|
19
|
+
EXIT_PASS,
|
|
20
|
+
EXIT_STALE,
|
|
21
|
+
EXIT_VIOLATION,
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
} from './types.js';
|
|
31
|
+
import { classifyCheckProcessOutcome, parseSkippedTestCount } from './verify.js';
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
export function resolveSourceContractPath(inputPath , cwd ) {
|
|
61
|
+
const abs = path.resolve(cwd, inputPath);
|
|
62
|
+
if (!fs.existsSync(abs)) {
|
|
63
|
+
throw new Error(`Contract or archive path not found: "${inputPath}"`);
|
|
64
|
+
}
|
|
65
|
+
const st = fs.statSync(abs);
|
|
66
|
+
if (st.isFile()) return abs;
|
|
67
|
+
if (st.isDirectory()) {
|
|
68
|
+
const direct = path.join(abs, 'contract.json');
|
|
69
|
+
if (fs.existsSync(direct) && fs.statSync(direct).isFile()) return direct;
|
|
70
|
+
const nested = path.join(abs, '.diffpact', 'contract.json');
|
|
71
|
+
if (fs.existsSync(nested) && fs.statSync(nested).isFile()) return nested;
|
|
72
|
+
}
|
|
73
|
+
throw new Error(`No contract.json found inside "${inputPath}"`);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function dedupeChecks(
|
|
77
|
+
sources
|
|
78
|
+
) {
|
|
79
|
+
const byCmdKey = new Map ();
|
|
80
|
+
const usedIds = new Set ();
|
|
81
|
+
const out = [];
|
|
82
|
+
|
|
83
|
+
for (const src of sources) {
|
|
84
|
+
for (const chk of src.checks) {
|
|
85
|
+
const cmdKey = `${chk.cwd ?? '.'}\0${chk.command.trim()}`;
|
|
86
|
+
const existing = byCmdKey.get(cmdKey);
|
|
87
|
+
if (existing) {
|
|
88
|
+
if (chk.timeout_sec && (!existing.timeout_sec || chk.timeout_sec > existing.timeout_sec)) {
|
|
89
|
+
existing.timeout_sec = chk.timeout_sec;
|
|
90
|
+
}
|
|
91
|
+
if (chk.forbid_skipped !== false) {
|
|
92
|
+
existing.forbid_skipped = true;
|
|
93
|
+
}
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
let id = chk.id;
|
|
98
|
+
if (usedIds.has(id)) {
|
|
99
|
+
id = `${src.taskId}:${chk.id}`;
|
|
100
|
+
}
|
|
101
|
+
let suffix = 2;
|
|
102
|
+
while (usedIds.has(id)) {
|
|
103
|
+
id = `${src.taskId}:${chk.id}-${suffix++}`;
|
|
104
|
+
}
|
|
105
|
+
usedIds.add(id);
|
|
106
|
+
|
|
107
|
+
const merged = {
|
|
108
|
+
...chk,
|
|
109
|
+
id
|
|
110
|
+
};
|
|
111
|
+
byCmdKey.set(cmdKey, merged);
|
|
112
|
+
out.push(merged);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
return out;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function resolveJsonPointer(obj , pointer ) {
|
|
120
|
+
if (pointer === '' || pointer === '/') return obj;
|
|
121
|
+
const segments = pointer
|
|
122
|
+
.replace(/^\//, '')
|
|
123
|
+
.split('/')
|
|
124
|
+
.map((s) => s.replace(/~1/g, '/').replace(/~0/g, '~'));
|
|
125
|
+
let cur = obj;
|
|
126
|
+
for (const seg of segments) {
|
|
127
|
+
if (cur === null || typeof cur !== 'object' || !(seg in (cur ))) {
|
|
128
|
+
return undefined;
|
|
129
|
+
}
|
|
130
|
+
cur = (cur )[seg];
|
|
131
|
+
}
|
|
132
|
+
return cur;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function evaluateMergedVersionAssertions(repoRoot , assertions ) {
|
|
136
|
+
const violations = [];
|
|
137
|
+
const seen = new Set ();
|
|
138
|
+
for (const assertion of assertions) {
|
|
139
|
+
const key = `${assertion.path}\0${assertion.kind}\0${assertion.key}\0${assertion.expected}`;
|
|
140
|
+
if (seen.has(key)) continue;
|
|
141
|
+
seen.add(key);
|
|
142
|
+
|
|
143
|
+
const safeRel = normalizeRepoRelativePath(assertion.path, repoRoot);
|
|
144
|
+
if (!safeRel.ok) {
|
|
145
|
+
violations.push({ code: 'PATH_ESCAPE', path: assertion.path, message: safeRel.reason });
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
const targetPath = path.join(repoRoot, safeRel.relPath);
|
|
149
|
+
if (!fs.existsSync(targetPath)) {
|
|
150
|
+
violations.push({
|
|
151
|
+
code: 'PINNED_VERSION_FILE_MISSING',
|
|
152
|
+
path: assertion.path,
|
|
153
|
+
message: `File "${assertion.path}" required by merged version_assertions is missing`
|
|
154
|
+
});
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
const buf = fs.readFileSync(targetPath);
|
|
158
|
+
if (assertion.kind === 'sha256') {
|
|
159
|
+
const actual = sha256Hex(buf);
|
|
160
|
+
if (actual !== assertion.expected) {
|
|
161
|
+
violations.push({
|
|
162
|
+
code: 'PINNED_VERSION_MISMATCH',
|
|
163
|
+
path: assertion.path,
|
|
164
|
+
message: `SHA-256 mismatch on "${assertion.path}": expected ${assertion.expected}, got ${actual}`
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
} else if (assertion.kind === 'json_pointer') {
|
|
168
|
+
try {
|
|
169
|
+
const val = resolveJsonPointer(JSON.parse(buf.toString('utf8')), assertion.key);
|
|
170
|
+
if (String(val) !== assertion.expected) {
|
|
171
|
+
violations.push({
|
|
172
|
+
code: 'PINNED_VERSION_MISMATCH',
|
|
173
|
+
path: assertion.path,
|
|
174
|
+
message: `JSON pointer "${assertion.key}" in "${assertion.path}": expected "${assertion.expected}", got "${String(val)}"`
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
} catch (err) {
|
|
178
|
+
violations.push({
|
|
179
|
+
code: 'PINNED_VERSION_INVALID_JSON',
|
|
180
|
+
path: assertion.path,
|
|
181
|
+
message: `Invalid JSON in "${assertion.path}": ${(err ).message}`
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
} else if (assertion.kind === 'regex_exact') {
|
|
185
|
+
const text = buf.toString('utf8');
|
|
186
|
+
const escapedKey = assertion.key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
187
|
+
const re = new RegExp(`${escapedKey}\\s*[:=]\\s*['"\`]?([^'"\`\\s;,]+)['"\`]?`);
|
|
188
|
+
const m = text.match(re);
|
|
189
|
+
if (!m || m[1] !== assertion.expected) {
|
|
190
|
+
violations.push({
|
|
191
|
+
code: 'PINNED_VERSION_MISMATCH',
|
|
192
|
+
path: assertion.path,
|
|
193
|
+
message: `Constant "${assertion.key}" in "${assertion.path}": expected "${assertion.expected}", got "${m?.[1] ?? '<missing>'}"`
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
return violations;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function resolveCommonBaseSha(repoRoot , contracts , explicitBase ) {
|
|
202
|
+
if (explicitBase) {
|
|
203
|
+
return runGitText(repoRoot, ['rev-parse', '--verify', `${explicitBase}^{commit}`]).trim();
|
|
204
|
+
}
|
|
205
|
+
const uniqueStarts = [...new Set(contracts.map((c) => c.starting_sha))];
|
|
206
|
+
if (uniqueStarts.length === 1) return uniqueStarts[0] ;
|
|
207
|
+
try {
|
|
208
|
+
return runGitText(repoRoot, ['merge-base', '--octopus', ...uniqueStarts]).trim();
|
|
209
|
+
} catch {
|
|
210
|
+
return uniqueStarts[0] ;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function evaluatePathAcrossMergedContracts(
|
|
215
|
+
relPath ,
|
|
216
|
+
repoRoot ,
|
|
217
|
+
contracts ,
|
|
218
|
+
integrationPolicy
|
|
219
|
+
) {
|
|
220
|
+
const failures = [];
|
|
221
|
+
for (const contract of contracts) {
|
|
222
|
+
const v = evaluatePathBoundary(relPath, repoRoot, contract);
|
|
223
|
+
if (v === null) {
|
|
224
|
+
// Explicitly authorized by at least one participating contract in the merge
|
|
225
|
+
return null;
|
|
226
|
+
}
|
|
227
|
+
failures.push(v);
|
|
228
|
+
}
|
|
229
|
+
if (integrationPolicy) {
|
|
230
|
+
const vi = evaluatePathBoundary(relPath, repoRoot, integrationPolicy);
|
|
231
|
+
if (vi === null) {
|
|
232
|
+
// Explicitly authorized as orchestrator post-merge integration glue (and not globally forbidden)
|
|
233
|
+
return null;
|
|
234
|
+
}
|
|
235
|
+
failures.push(vi);
|
|
236
|
+
}
|
|
237
|
+
// Unauthorized by EVERY participating contract (and integration scope): prefer strongest violation
|
|
238
|
+
const priority = ['GIT_METADATA_FORBIDDEN', 'PATH_ESCAPE', 'FORBIDDEN_PATH', 'READ_ONLY_PATH'];
|
|
239
|
+
for (const code of priority) {
|
|
240
|
+
const hit = failures.find((f) => f.code === code);
|
|
241
|
+
if (hit) return hit;
|
|
242
|
+
}
|
|
243
|
+
return (
|
|
244
|
+
failures[0] ?? {
|
|
245
|
+
code: 'OUTSIDE_ALLOWED_PATHS',
|
|
246
|
+
path: relPath,
|
|
247
|
+
message: `Path "${relPath}" is not authorized by any merged contract`
|
|
248
|
+
}
|
|
249
|
+
);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function executeCheck(
|
|
253
|
+
chk ,
|
|
254
|
+
checkCwd ,
|
|
255
|
+
shellPath ,
|
|
256
|
+
heartbeatSec ,
|
|
257
|
+
onHeartbeat
|
|
258
|
+
) {
|
|
259
|
+
if (heartbeatSec <= 0 && !onHeartbeat) {
|
|
260
|
+
const startMs = Date.now();
|
|
261
|
+
const childEnv = { ...process.env };
|
|
262
|
+
delete childEnv.NODE_TEST_CONTEXT;
|
|
263
|
+
const proc = spawnSync(shellPath, ['-c', chk.command], {
|
|
264
|
+
cwd: checkCwd,
|
|
265
|
+
env: childEnv,
|
|
266
|
+
timeout: (chk.timeout_sec ?? 300) * 1000,
|
|
267
|
+
maxBuffer: 32 * 1024 * 1024,
|
|
268
|
+
encoding: 'buffer'
|
|
269
|
+
});
|
|
270
|
+
const stdoutBuf = proc.stdout ?? Buffer.alloc(0);
|
|
271
|
+
const stderrBuf = proc.stderr ?? Buffer.alloc(0);
|
|
272
|
+
const outcome = classifyCheckProcessOutcome({
|
|
273
|
+
error: proc.error ?? null,
|
|
274
|
+
status: proc.status,
|
|
275
|
+
signal: proc.signal
|
|
276
|
+
});
|
|
277
|
+
return Promise.resolve({
|
|
278
|
+
outcome,
|
|
279
|
+
result: {
|
|
280
|
+
id: chk.id,
|
|
281
|
+
command: chk.command,
|
|
282
|
+
exit_code: outcome.exitCode,
|
|
283
|
+
skipped_count: parseSkippedTestCount(stdoutBuf.toString('utf8') + '\n' + stderrBuf.toString('utf8')),
|
|
284
|
+
duration_ms: Date.now() - startMs,
|
|
285
|
+
stdout_sha256: sha256Hex(stdoutBuf),
|
|
286
|
+
stderr_sha256: sha256Hex(stderrBuf),
|
|
287
|
+
...(outcome.timedOut ? { timed_out: true } : {}),
|
|
288
|
+
...(outcome.spawnErrorCode ? { spawn_error_code: outcome.spawnErrorCode } : {}),
|
|
289
|
+
...(outcome.spawnErrorMessage ? { spawn_error_message: outcome.spawnErrorMessage } : {})
|
|
290
|
+
}
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
return new Promise((resolve) => {
|
|
295
|
+
const startMs = Date.now();
|
|
296
|
+
const timeoutSec = chk.timeout_sec ?? 300;
|
|
297
|
+
const childEnv = { ...process.env };
|
|
298
|
+
delete childEnv.NODE_TEST_CONTEXT;
|
|
299
|
+
const stdoutChunks = [];
|
|
300
|
+
const stderrChunks = [];
|
|
301
|
+
let spawnErr = null;
|
|
302
|
+
let timedOut = false;
|
|
303
|
+
let settled = false;
|
|
304
|
+
|
|
305
|
+
const child = spawn(shellPath, ['-c', chk.command], {
|
|
306
|
+
cwd: checkCwd,
|
|
307
|
+
env: childEnv,
|
|
308
|
+
stdio: ['ignore', 'pipe', 'pipe']
|
|
309
|
+
});
|
|
310
|
+
child.stdout?.on('data', (c ) => stdoutChunks.push(Buffer.isBuffer(c) ? c : Buffer.from(c)));
|
|
311
|
+
child.stderr?.on('data', (c ) => stderrChunks.push(Buffer.isBuffer(c) ? c : Buffer.from(c)));
|
|
312
|
+
|
|
313
|
+
const timeoutTimer = setTimeout(() => {
|
|
314
|
+
timedOut = true;
|
|
315
|
+
try {
|
|
316
|
+
child.kill('SIGTERM');
|
|
317
|
+
} catch {
|
|
318
|
+
// ignore
|
|
319
|
+
}
|
|
320
|
+
}, timeoutSec * 1000);
|
|
321
|
+
timeoutTimer.unref?.();
|
|
322
|
+
|
|
323
|
+
const hbTimer =
|
|
324
|
+
heartbeatSec > 0
|
|
325
|
+
? setInterval(() => {
|
|
326
|
+
const elapsedSec = Math.max(1, Math.round((Date.now() - startMs) / 1000));
|
|
327
|
+
const msg = `[diffpact merge-verify] running check "${chk.id}" (pid=${child.pid ?? 'unknown'}, elapsed ${elapsedSec}s / timeout ${timeoutSec}s)...`;
|
|
328
|
+
if (onHeartbeat) onHeartbeat(msg);
|
|
329
|
+
else process.stderr.write(msg + '\n');
|
|
330
|
+
}, heartbeatSec * 1000)
|
|
331
|
+
: null;
|
|
332
|
+
hbTimer?.unref?.();
|
|
333
|
+
|
|
334
|
+
const finish = (status , signal ) => {
|
|
335
|
+
if (settled) return;
|
|
336
|
+
settled = true;
|
|
337
|
+
clearTimeout(timeoutTimer);
|
|
338
|
+
if (hbTimer) clearInterval(hbTimer);
|
|
339
|
+
const stdoutBuf = Buffer.concat(stdoutChunks);
|
|
340
|
+
const stderrBuf = Buffer.concat(stderrChunks);
|
|
341
|
+
const outcome = classifyCheckProcessOutcome({ error: spawnErr, status, signal, timedOut });
|
|
342
|
+
resolve({
|
|
343
|
+
outcome,
|
|
344
|
+
result: {
|
|
345
|
+
id: chk.id,
|
|
346
|
+
command: chk.command,
|
|
347
|
+
exit_code: outcome.exitCode,
|
|
348
|
+
skipped_count: parseSkippedTestCount(stdoutBuf.toString('utf8') + '\n' + stderrBuf.toString('utf8')),
|
|
349
|
+
duration_ms: Date.now() - startMs,
|
|
350
|
+
stdout_sha256: sha256Hex(stdoutBuf),
|
|
351
|
+
stderr_sha256: sha256Hex(stderrBuf),
|
|
352
|
+
...(outcome.timedOut ? { timed_out: true } : {}),
|
|
353
|
+
...(outcome.spawnErrorCode ? { spawn_error_code: outcome.spawnErrorCode } : {}),
|
|
354
|
+
...(outcome.spawnErrorMessage ? { spawn_error_message: outcome.spawnErrorMessage } : {})
|
|
355
|
+
}
|
|
356
|
+
});
|
|
357
|
+
};
|
|
358
|
+
|
|
359
|
+
child.on('error', (err) => {
|
|
360
|
+
spawnErr = err;
|
|
361
|
+
finish(null, null);
|
|
362
|
+
});
|
|
363
|
+
child.on('close', (code, signal) => finish(code, signal));
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* Post-merge verification gate across two or more merged task contracts (or archived
|
|
369
|
+
* `.diffpact/archive/...` bundles). Verifies that:
|
|
370
|
+
* 1. The merged working tree is clean and every changed file since `base_sha` is authorized
|
|
371
|
+
* by at least one participating contract (catching unauthorized conflict-resolution edits).
|
|
372
|
+
* 2. The deduplicated UNION of all contracts' `required_checks`, `version_assertions`, and
|
|
373
|
+
* `interfacedelta_lockfile` pins passes on the joined tree (with No Silent Zero enforcement).
|
|
374
|
+
* 3. A canonical SHA-256 signed `merge-receipt.json` is written durably under `.diffpact/merges/`.
|
|
375
|
+
*/
|
|
376
|
+
export async function runMergeVerify(options ) {
|
|
377
|
+
const cwd = options.cwd ?? process.cwd();
|
|
378
|
+
if (!options.fromPaths || options.fromPaths.length === 0) {
|
|
379
|
+
return {
|
|
380
|
+
exitCode: EXIT_INCOMPLETE,
|
|
381
|
+
error: 'diffpact merge-verify requires at least one --from <contract-or-archive-dir> path'
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
const loaded = [];
|
|
386
|
+
for (const rawPath of options.fromPaths) {
|
|
387
|
+
try {
|
|
388
|
+
const resolvedPath = resolveSourceContractPath(rawPath, cwd);
|
|
389
|
+
const contract = validateContract(JSON.parse(fs.readFileSync(resolvedPath, 'utf8')));
|
|
390
|
+
const contractSha256 = canonicalSha256('diffpact/contract/v0.1', contract);
|
|
391
|
+
loaded.push({ resolvedPath, contract, contractSha256 });
|
|
392
|
+
} catch (err) {
|
|
393
|
+
return {
|
|
394
|
+
exitCode: EXIT_INCOMPLETE,
|
|
395
|
+
error: `Failed to load source contract "${rawPath}": ${(err ).message}`
|
|
396
|
+
};
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
let repoRoot ;
|
|
401
|
+
let headSha ;
|
|
402
|
+
let branch ;
|
|
403
|
+
try {
|
|
404
|
+
repoRoot = resolveRepoRoot(cwd);
|
|
405
|
+
headSha = resolveHeadSha(repoRoot);
|
|
406
|
+
branch = resolveCurrentBranch(repoRoot);
|
|
407
|
+
} catch (err) {
|
|
408
|
+
return {
|
|
409
|
+
exitCode: EXIT_INCOMPLETE,
|
|
410
|
+
error: `Git repository unavailable at "${cwd}": ${(err ).message}`
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
const contracts = loaded.map((l) => l.contract);
|
|
415
|
+
let baseSha ;
|
|
416
|
+
try {
|
|
417
|
+
baseSha = resolveCommonBaseSha(repoRoot, contracts, options.baseSha);
|
|
418
|
+
} catch (err) {
|
|
419
|
+
return {
|
|
420
|
+
exitCode: EXIT_STALE,
|
|
421
|
+
error: `Failed to resolve merge base SHA: ${(err ).message}`
|
|
422
|
+
};
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
const violations = [];
|
|
426
|
+
let staleDetected = false;
|
|
427
|
+
let incompleteDetected = false;
|
|
428
|
+
|
|
429
|
+
if (!commitExists(repoRoot, baseSha)) {
|
|
430
|
+
staleDetected = true;
|
|
431
|
+
violations.push({
|
|
432
|
+
code: 'BASE_SHA_MISSING',
|
|
433
|
+
message: `Merge base SHA ${baseSha} does not exist in Git object store`
|
|
434
|
+
});
|
|
435
|
+
} else if (!isAncestor(repoRoot, baseSha, headSha)) {
|
|
436
|
+
staleDetected = true;
|
|
437
|
+
violations.push({
|
|
438
|
+
code: 'BASE_SHA_NOT_ANCESTOR',
|
|
439
|
+
message: `Merge base SHA ${baseSha} is not an ancestor of merged HEAD ${headSha}`
|
|
440
|
+
});
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
const snap = commitExists(repoRoot, baseSha)
|
|
444
|
+
? collectRepoChanges(repoRoot, baseSha, headSha)
|
|
445
|
+
: { changedFiles: [], untrackedFiles: [], workingTreeClean: false, trackedTreeClean: false, rawDiffSha256: sha256Hex('') };
|
|
446
|
+
|
|
447
|
+
const allowUntracked = Boolean(options.allowUntracked);
|
|
448
|
+
const ignoredUntrackedFiles = allowUntracked ? [...snap.untrackedFiles] : [];
|
|
449
|
+
|
|
450
|
+
if (allowUntracked) {
|
|
451
|
+
if (!snap.trackedTreeClean) {
|
|
452
|
+
violations.push({
|
|
453
|
+
code: 'DIRTY_WORKING_TREE',
|
|
454
|
+
message: 'Merged working tree has uncommitted changes to tracked files (not ignored by --allow-untracked)'
|
|
455
|
+
});
|
|
456
|
+
}
|
|
457
|
+
} else if (!snap.workingTreeClean) {
|
|
458
|
+
const onlyUntracked = snap.trackedTreeClean && snap.untrackedFiles.length > 0;
|
|
459
|
+
violations.push({
|
|
460
|
+
code: 'DIRTY_WORKING_TREE',
|
|
461
|
+
message: onlyUntracked
|
|
462
|
+
? `Merged working tree has ${snap.untrackedFiles.length} untracked file(s) outside .diffpact/: ${snap.untrackedFiles.slice(0, 5).join(', ')}${snap.untrackedFiles.length > 5 ? ', …' : ''}`
|
|
463
|
+
: 'Merged working tree has uncommitted or untracked changes outside .diffpact/'
|
|
464
|
+
});
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
const allowedUnion = [...new Set(contracts.flatMap((c) => c.allowed_paths))].sort();
|
|
468
|
+
const forbiddenIntersection =
|
|
469
|
+
contracts.length > 0
|
|
470
|
+
? [...new Set(contracts[0] .forbidden_paths)].filter((p) =>
|
|
471
|
+
contracts.every((c) => c.forbidden_paths.includes(p))
|
|
472
|
+
).sort()
|
|
473
|
+
: [];
|
|
474
|
+
|
|
475
|
+
const safeIntegrationGlobs = [];
|
|
476
|
+
for (const rawGlob of options.allowIntegrationPaths ?? []) {
|
|
477
|
+
const norm = rawGlob.trim().normalize('NFC').replace(/\\/g, '/');
|
|
478
|
+
if (!norm || norm.startsWith('/') || norm.split('/').includes('..') || norm.includes('\0')) {
|
|
479
|
+
return {
|
|
480
|
+
exitCode: EXIT_INCOMPLETE,
|
|
481
|
+
error: `Invalid --allow-integration glob "${rawGlob}": must be a clean repo-relative glob without leading "/" or ".." segments`
|
|
482
|
+
};
|
|
483
|
+
}
|
|
484
|
+
safeIntegrationGlobs.push(norm);
|
|
485
|
+
}
|
|
486
|
+
const integrationPolicy =
|
|
487
|
+
safeIntegrationGlobs.length > 0
|
|
488
|
+
? {
|
|
489
|
+
allowed_paths: safeIntegrationGlobs,
|
|
490
|
+
forbidden_paths: forbiddenIntersection
|
|
491
|
+
}
|
|
492
|
+
: null;
|
|
493
|
+
|
|
494
|
+
const outOfBoundsSet = new Set ();
|
|
495
|
+
for (const ch of snap.changedFiles) {
|
|
496
|
+
if (ch.is_symlink) {
|
|
497
|
+
outOfBoundsSet.add(ch.path);
|
|
498
|
+
violations.push({
|
|
499
|
+
code: 'SYMLINK_FORBIDDEN',
|
|
500
|
+
path: ch.path,
|
|
501
|
+
message: `Symlink "${ch.path}" is forbidden in merged tree`
|
|
502
|
+
});
|
|
503
|
+
}
|
|
504
|
+
if (ch.is_submodule) {
|
|
505
|
+
outOfBoundsSet.add(ch.path);
|
|
506
|
+
violations.push({
|
|
507
|
+
code: 'SUBMODULE_FORBIDDEN',
|
|
508
|
+
path: ch.path,
|
|
509
|
+
message: `Git submodule "${ch.path}" is forbidden in merged tree`
|
|
510
|
+
});
|
|
511
|
+
}
|
|
512
|
+
const vNew = evaluatePathAcrossMergedContracts(ch.path, repoRoot, contracts, integrationPolicy);
|
|
513
|
+
if (vNew) {
|
|
514
|
+
outOfBoundsSet.add(ch.path);
|
|
515
|
+
violations.push(vNew);
|
|
516
|
+
}
|
|
517
|
+
if (ch.old_path) {
|
|
518
|
+
const vOld = evaluatePathAcrossMergedContracts(ch.old_path, repoRoot, contracts, integrationPolicy);
|
|
519
|
+
if (vOld) {
|
|
520
|
+
outOfBoundsSet.add(ch.old_path);
|
|
521
|
+
violations.push(vOld);
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
if (!allowUntracked) {
|
|
526
|
+
for (const ut of snap.untrackedFiles) {
|
|
527
|
+
const vUt = evaluatePathAcrossMergedContracts(ut, repoRoot, contracts, integrationPolicy);
|
|
528
|
+
if (vUt) {
|
|
529
|
+
outOfBoundsSet.add(ut);
|
|
530
|
+
violations.push(vUt);
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
// Union version assertions & lockfile pins
|
|
536
|
+
const allAssertions = contracts.flatMap((c) => c.version_assertions ?? []);
|
|
537
|
+
const versionViolations = evaluateMergedVersionAssertions(repoRoot, allAssertions);
|
|
538
|
+
violations.push(...versionViolations);
|
|
539
|
+
const versionAssertionsOk = versionViolations.length === 0;
|
|
540
|
+
|
|
541
|
+
const lockfiles = contracts
|
|
542
|
+
.map((c) => c.interfacedelta_lockfile)
|
|
543
|
+
.filter((lf) => Boolean(lf));
|
|
544
|
+
let lockfilesOk = null;
|
|
545
|
+
if (lockfiles.length > 0) {
|
|
546
|
+
lockfilesOk = true;
|
|
547
|
+
const seenLock = new Set ();
|
|
548
|
+
for (const lf of lockfiles) {
|
|
549
|
+
const key = `${lf.path}\0${lf.sha256}`;
|
|
550
|
+
if (seenLock.has(key)) continue;
|
|
551
|
+
seenLock.add(key);
|
|
552
|
+
const safeRel = normalizeRepoRelativePath(lf.path, repoRoot);
|
|
553
|
+
if (!safeRel.ok) {
|
|
554
|
+
lockfilesOk = false;
|
|
555
|
+
violations.push({ code: 'PATH_ESCAPE', path: lf.path, message: safeRel.reason });
|
|
556
|
+
continue;
|
|
557
|
+
}
|
|
558
|
+
const lfAbs = path.join(repoRoot, safeRel.relPath);
|
|
559
|
+
if (!fs.existsSync(lfAbs)) {
|
|
560
|
+
lockfilesOk = false;
|
|
561
|
+
violations.push({ code: 'LOCKFILE_MISSING', path: lf.path, message: `Pinned lockfile "${lf.path}" is missing` });
|
|
562
|
+
} else {
|
|
563
|
+
const actual = sha256Hex(fs.readFileSync(lfAbs));
|
|
564
|
+
if (actual !== lf.sha256) {
|
|
565
|
+
lockfilesOk = false;
|
|
566
|
+
violations.push({
|
|
567
|
+
code: 'LOCKFILE_DRIFT',
|
|
568
|
+
path: lf.path,
|
|
569
|
+
message: `Pinned lockfile "${lf.path}" drifted: expected ${lf.sha256}, got ${actual}`
|
|
570
|
+
});
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
// Union checks across all participating contracts
|
|
577
|
+
const unionRequired = dedupeChecks(
|
|
578
|
+
contracts.map((c) => ({ taskId: c.task_id, checks: c.required_checks }))
|
|
579
|
+
);
|
|
580
|
+
const unionAdvisory = dedupeChecks(
|
|
581
|
+
contracts.map((c) => ({ taskId: c.task_id, checks: c.advisory_checks ?? [] }))
|
|
582
|
+
);
|
|
583
|
+
const allAllowNoChecks = contracts.every((c) => c.allow_no_checks === true);
|
|
584
|
+
|
|
585
|
+
const shellPath = options.shellPath ?? '/bin/sh';
|
|
586
|
+
const heartbeatSec = options.heartbeatSec ?? 0;
|
|
587
|
+
const checkResults = [];
|
|
588
|
+
|
|
589
|
+
if (unionRequired.length === 0 && !allAllowNoChecks) {
|
|
590
|
+
incompleteDetected = true;
|
|
591
|
+
violations.push({
|
|
592
|
+
code: 'NO_SILENT_ZERO_EMPTY_CHECKS',
|
|
593
|
+
message: 'Merged contracts define zero required_checks'
|
|
594
|
+
});
|
|
595
|
+
} else {
|
|
596
|
+
for (const chk of unionRequired) {
|
|
597
|
+
const checkCwd = !chk.cwd || chk.cwd === '.' ? repoRoot : path.join(repoRoot, chk.cwd);
|
|
598
|
+
const { result, outcome } = await executeCheck(chk, checkCwd, shellPath, heartbeatSec, options.onHeartbeat);
|
|
599
|
+
checkResults.push(result);
|
|
600
|
+
|
|
601
|
+
if (outcome.timedOut) {
|
|
602
|
+
violations.push({
|
|
603
|
+
code: 'REQUIRED_CHECK_TIMEOUT',
|
|
604
|
+
message: `Merged required check "${chk.id}" timed out after ${chk.timeout_sec ?? 300}s (exit 124)`
|
|
605
|
+
});
|
|
606
|
+
} else if (outcome.spawnErrorCode) {
|
|
607
|
+
violations.push({
|
|
608
|
+
code: 'CHECK_SPAWN_ERROR',
|
|
609
|
+
message: `Merged required check "${chk.id}" failed to spawn (${outcome.spawnErrorCode}): ${outcome.spawnErrorMessage ?? 'unknown'}`
|
|
610
|
+
});
|
|
611
|
+
} else if (result.exit_code !== 0) {
|
|
612
|
+
violations.push({
|
|
613
|
+
code: 'REQUIRED_CHECK_FAILED',
|
|
614
|
+
message: `Merged required check "${chk.id}" exited with code ${result.exit_code}`
|
|
615
|
+
});
|
|
616
|
+
} else if (chk.forbid_skipped !== false && result.skipped_count > 0) {
|
|
617
|
+
incompleteDetected = true;
|
|
618
|
+
violations.push({
|
|
619
|
+
code: 'NO_SILENT_ZERO_SKIPPED_TESTS',
|
|
620
|
+
message: `Merged required check "${chk.id}" exited 0 but skipped ${result.skipped_count} test(s)`
|
|
621
|
+
});
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
const advisoryResults = [];
|
|
627
|
+
for (const adv of unionAdvisory) {
|
|
628
|
+
const checkCwd = !adv.cwd || adv.cwd === '.' ? repoRoot : path.join(repoRoot, adv.cwd);
|
|
629
|
+
const { result } = await executeCheck(adv, checkCwd, shellPath, heartbeatSec, options.onHeartbeat);
|
|
630
|
+
advisoryResults.push(result);
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
const hardViolations = violations.filter(
|
|
634
|
+
(v) =>
|
|
635
|
+
![
|
|
636
|
+
'BASE_SHA_MISSING',
|
|
637
|
+
'BASE_SHA_NOT_ANCESTOR',
|
|
638
|
+
'NO_SILENT_ZERO_EMPTY_CHECKS',
|
|
639
|
+
'NO_SILENT_ZERO_SKIPPED_TESTS'
|
|
640
|
+
].includes(v.code)
|
|
641
|
+
);
|
|
642
|
+
|
|
643
|
+
let finalExit = EXIT_PASS;
|
|
644
|
+
let status = 'pass';
|
|
645
|
+
if (hardViolations.length > 0) {
|
|
646
|
+
finalExit = EXIT_VIOLATION;
|
|
647
|
+
status = 'violation';
|
|
648
|
+
} else if (staleDetected) {
|
|
649
|
+
finalExit = EXIT_STALE;
|
|
650
|
+
status = 'stale';
|
|
651
|
+
} else if (incompleteDetected) {
|
|
652
|
+
finalExit = EXIT_INCOMPLETE;
|
|
653
|
+
status = 'incomplete';
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
const receiptBody = {
|
|
657
|
+
schema_version: 'diffpact-merge-receipt-v0.1' ,
|
|
658
|
+
verified_at: new Date().toISOString(),
|
|
659
|
+
base_sha: baseSha,
|
|
660
|
+
merged_sha: headSha,
|
|
661
|
+
raw_diff_sha256: snap.rawDiffSha256,
|
|
662
|
+
branch,
|
|
663
|
+
repo_root: repoRoot,
|
|
664
|
+
working_tree_clean: snap.workingTreeClean,
|
|
665
|
+
status,
|
|
666
|
+
exit_code: finalExit,
|
|
667
|
+
source_contracts: loaded.map((l) => ({
|
|
668
|
+
path: l.resolvedPath,
|
|
669
|
+
task_id: l.contract.task_id,
|
|
670
|
+
contract_sha256: l.contractSha256,
|
|
671
|
+
starting_sha: l.contract.starting_sha
|
|
672
|
+
})),
|
|
673
|
+
merged_policy: {
|
|
674
|
+
allowed_paths: allowedUnion,
|
|
675
|
+
global_forbidden_paths: forbiddenIntersection,
|
|
676
|
+
...(safeIntegrationGlobs.length > 0 ? { integration_allowed_paths: [...new Set(safeIntegrationGlobs)].sort() } : {}),
|
|
677
|
+
...(options.integrationReason ? { integration_reason: options.integrationReason } : {}),
|
|
678
|
+
...(allowUntracked ? { allow_untracked: true } : {}),
|
|
679
|
+
required_checks_count: unionRequired.length,
|
|
680
|
+
advisory_checks_count: unionAdvisory.length
|
|
681
|
+
},
|
|
682
|
+
diff_summary: {
|
|
683
|
+
changed_files: snap.changedFiles,
|
|
684
|
+
untracked_files: allowUntracked ? [] : snap.untrackedFiles,
|
|
685
|
+
...(ignoredUntrackedFiles.length > 0 ? { ignored_untracked_files: ignoredUntrackedFiles } : {}),
|
|
686
|
+
out_of_bounds_files: [...outOfBoundsSet].sort()
|
|
687
|
+
},
|
|
688
|
+
version_assertions_ok: versionAssertionsOk,
|
|
689
|
+
lockfiles_ok: lockfilesOk,
|
|
690
|
+
checks: checkResults,
|
|
691
|
+
...(advisoryResults.length > 0 ? { advisory_checks: advisoryResults } : {}),
|
|
692
|
+
violations
|
|
693
|
+
};
|
|
694
|
+
|
|
695
|
+
const mergeReceiptSha256 = canonicalSha256('diffpact/merge-receipt/v0.1', receiptBody);
|
|
696
|
+
const receipt = {
|
|
697
|
+
merge_receipt_sha256: mergeReceiptSha256,
|
|
698
|
+
...receiptBody
|
|
699
|
+
};
|
|
700
|
+
|
|
701
|
+
let writtenPath ;
|
|
702
|
+
if (options.writeReceipt !== false) {
|
|
703
|
+
const stamp = receipt.verified_at.replace(/[:.]/g, '-');
|
|
704
|
+
writtenPath = options.receiptPath
|
|
705
|
+
? path.resolve(cwd, options.receiptPath)
|
|
706
|
+
: path.join(repoRoot, '.diffpact', 'merges', `${stamp}-${headSha.slice(0, 8)}.json`);
|
|
707
|
+
fs.mkdirSync(path.dirname(writtenPath), { recursive: true });
|
|
708
|
+
fs.writeFileSync(writtenPath, JSON.stringify(receipt, null, 2) + '\n', 'utf8');
|
|
709
|
+
try {
|
|
710
|
+
ensureGitInfoExclude(repoRoot, '.diffpact/');
|
|
711
|
+
} catch {
|
|
712
|
+
// ignore
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
return {
|
|
717
|
+
exitCode: finalExit,
|
|
718
|
+
receipt,
|
|
719
|
+
...(writtenPath ? { receiptPath: writtenPath } : {})
|
|
720
|
+
};
|
|
721
|
+
}
|