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/dist/verify.js ADDED
@@ -0,0 +1,952 @@
1
+ import { spawn, spawnSync } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { canonicalSha256, sha256Hex } from './canonical-json.js';
5
+ import { evaluatePathBoundary, normalizeRepoRelativePath } from './boundaries.js';
6
+ import {
7
+ collectRepoChanges,
8
+ commitExists,
9
+ isAncestor,
10
+ resolveCurrentBranch,
11
+ resolveHeadSha,
12
+ resolveRepoRoot
13
+ } from './git.js';
14
+ import { validateContract } from './schema.js';
15
+ import {
16
+ EXIT_INCOMPLETE,
17
+ EXIT_PASS,
18
+ EXIT_STALE,
19
+ EXIT_VIOLATION,
20
+
21
+
22
+
23
+
24
+
25
+
26
+ } from './types.js';
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
+
35
+ /**
36
+ * Classifies child process outcomes accurately so sandbox/spawn errors (EPERM, EACCES, ENOENT)
37
+ * are NEVER masked as exit code 124 (timeout).
38
+ */
39
+ export function classifyCheckProcessOutcome(input
40
+
41
+
42
+
43
+
44
+ ) {
45
+ const err = input.error ?? null;
46
+ const errCode = (err )?.code;
47
+ const isTimeout =
48
+ input.timedOut === true ||
49
+ errCode === 'ETIMEDOUT' ||
50
+ (input.signal === 'SIGTERM' && Boolean(err && /ETIMEDOUT|timed?\s*out/i.test(err.message)));
51
+
52
+ if (isTimeout) {
53
+ return { exitCode: 124, timedOut: true };
54
+ }
55
+ if (err) {
56
+ const code = typeof errCode === 'string' && errCode.length > 0 ? errCode : 'SPAWN_ERROR';
57
+ return {
58
+ exitCode: code === 'ENOENT' ? 127 : 126,
59
+ timedOut: false,
60
+ spawnErrorCode: code,
61
+ spawnErrorMessage: err.message
62
+ };
63
+ }
64
+ return { exitCode: input.status ?? 1, timedOut: false };
65
+ }
66
+
67
+ /**
68
+ * Parses skipped test counts from common runners (Vitest, Node --test / TAP, Jest, Pytest)
69
+ * so skipped suites cannot silently masquerade as complete verification ("No Silent Zero").
70
+ */
71
+ export function parseSkippedTestCount(combinedOutput ) {
72
+ const cleanOutput = combinedOutput.replace(/\x1B\[[0-9;]*[a-zA-Z]/g, '');
73
+ let maxSkipped = 0;
74
+ const patterns = [
75
+ /\b(\d+)\s+skipped\b/gi,
76
+ /[#ℹ]\s*skipped\s+(\d+)\b/gi,
77
+ /\bskipped:\s*(\d+)\b/gi,
78
+ /\b(\d+)\s+pending\b/gi
79
+ ];
80
+ for (const pat of patterns) {
81
+ let m ;
82
+ while ((m = pat.exec(cleanOutput)) !== null) {
83
+ const n = Number(m[1]);
84
+ if (Number.isFinite(n) && n > maxSkipped) {
85
+ maxSkipped = n;
86
+ }
87
+ }
88
+ }
89
+ const tapDirectiveMatches = cleanOutput.match(/^(?:ok|not ok)\s+\d+\b[^#\r\n]*#\s*SKIP\b/gim);
90
+ if (tapDirectiveMatches && tapDirectiveMatches.length > maxSkipped) {
91
+ maxSkipped = tapDirectiveMatches.length;
92
+ }
93
+ return maxSkipped;
94
+ }
95
+
96
+ function resolveJsonPointer(obj , pointer ) {
97
+ if (pointer === '' || pointer === '/') return obj;
98
+ const segments = pointer
99
+ .replace(/^\//, '')
100
+ .split('/')
101
+ .map((s) => s.replace(/~1/g, '/').replace(/~0/g, '~'));
102
+ let cur = obj;
103
+ for (const seg of segments) {
104
+ if (cur === null || typeof cur !== 'object' || !(seg in (cur ))) {
105
+ return undefined;
106
+ }
107
+ cur = (cur )[seg];
108
+ }
109
+ return cur;
110
+ }
111
+
112
+ function evaluateVersionAssertions(repoRoot , contract ) {
113
+ const violations = [];
114
+ for (const assertion of contract.version_assertions ?? []) {
115
+ const safeRel = normalizeRepoRelativePath(assertion.path, repoRoot);
116
+ if (!safeRel.ok) {
117
+ violations.push({
118
+ code: 'PATH_ESCAPE',
119
+ path: assertion.path,
120
+ message: safeRel.reason
121
+ });
122
+ continue;
123
+ }
124
+ const targetPath = path.join(repoRoot, safeRel.relPath);
125
+ if (!fs.existsSync(targetPath)) {
126
+ violations.push({
127
+ code: 'PINNED_VERSION_FILE_MISSING',
128
+ path: assertion.path,
129
+ message: `File "${assertion.path}" required by version_assertions is missing`
130
+ });
131
+ continue;
132
+ }
133
+ const buf = fs.readFileSync(targetPath);
134
+ if (assertion.kind === 'sha256') {
135
+ const actual = sha256Hex(buf);
136
+ if (actual !== assertion.expected) {
137
+ violations.push({
138
+ code: 'PINNED_VERSION_MISMATCH',
139
+ path: assertion.path,
140
+ message: `SHA-256 mismatch on "${assertion.path}": expected ${assertion.expected}, got ${actual}`
141
+ });
142
+ }
143
+ } else if (assertion.kind === 'json_pointer') {
144
+ try {
145
+ const parsed = JSON.parse(buf.toString('utf8'));
146
+ const val = resolveJsonPointer(parsed, assertion.key);
147
+ if (String(val) !== assertion.expected) {
148
+ violations.push({
149
+ code: 'PINNED_VERSION_MISMATCH',
150
+ path: assertion.path,
151
+ message: `JSON pointer "${assertion.key}" in "${assertion.path}": expected "${assertion.expected}", got "${String(val)}"`
152
+ });
153
+ }
154
+ } catch (err) {
155
+ violations.push({
156
+ code: 'PINNED_VERSION_INVALID_JSON',
157
+ path: assertion.path,
158
+ message: `Invalid JSON in "${assertion.path}": ${(err ).message}`
159
+ });
160
+ }
161
+ } else if (assertion.kind === 'regex_exact') {
162
+ const text = buf.toString('utf8');
163
+ const escapedKey = assertion.key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
164
+ const re = new RegExp(`${escapedKey}\\s*[:=]\\s*['"\`]?([^'"\`\\s;,]+)['"\`]?`);
165
+ const m = text.match(re);
166
+ if (!m || m[1] !== assertion.expected) {
167
+ violations.push({
168
+ code: 'PINNED_VERSION_MISMATCH',
169
+ path: assertion.path,
170
+ message: `Constant "${assertion.key}" in "${assertion.path}": expected "${assertion.expected}", got "${m?.[1] ?? '<missing>'}"`
171
+ });
172
+ }
173
+ }
174
+ }
175
+ return violations;
176
+ }
177
+
178
+ function evaluateSubcontracts(
179
+ contractDir ,
180
+ parentContract ,
181
+ parentSha256 ,
182
+ repoRoot
183
+ ) {
184
+ const subDir = path.join(contractDir, 'subcontracts');
185
+ if (!fs.existsSync(subDir)) return { count: 0, violations: [] };
186
+
187
+ const files = fs
188
+ .readdirSync(subDir)
189
+ .filter((f) => f.endsWith('.json'))
190
+ .sort();
191
+ const violations = [];
192
+ let totalReserved = 0;
193
+ const maxDepth = parentContract.budget?.max_delegation_depth ?? 1;
194
+
195
+ for (const file of files) {
196
+ const full = path.join(subDir, file);
197
+ let sub ;
198
+ try {
199
+ sub = validateContract(JSON.parse(fs.readFileSync(full, 'utf8')));
200
+ } catch (err) {
201
+ violations.push({
202
+ code: 'INVALID_SUBCONTRACT',
203
+ path: full,
204
+ message: `Subcontract "${file}" invalid: ${(err ).message}`
205
+ });
206
+ continue;
207
+ }
208
+
209
+ if (sub.budget?.parent_contract_sha256 && sub.budget.parent_contract_sha256 !== parentSha256) {
210
+ violations.push({
211
+ code: 'STALE_SUBCONTRACT_PARENT_HASH',
212
+ path: full,
213
+ message: `Subcontract "${file}" parent_contract_sha256 does not match active parent contract`
214
+ });
215
+ }
216
+
217
+ const depth = sub.budget?.delegation_depth ?? 1;
218
+ if (depth > maxDepth) {
219
+ violations.push({
220
+ code: 'DELEGATION_DEPTH_EXCEEDED',
221
+ path: full,
222
+ message: `Subcontract "${file}" depth ${depth} exceeds max_delegation_depth ${maxDepth}`
223
+ });
224
+ }
225
+
226
+ // Check literal sample probe of child allowed_paths against parent forbidden/read_only/allowed
227
+ for (const childGlob of sub.allowed_paths) {
228
+ const samplePath = childGlob.replace(/\*\*/g, 'sample_dir').replace(/\*/g, 'sample_item').replace(/\?/g, 'x');
229
+ const v = evaluatePathBoundary(samplePath, repoRoot, parentContract);
230
+ if (v) {
231
+ violations.push({
232
+ code: 'CHILD_SCOPE_ENLARGEMENT',
233
+ path: childGlob,
234
+ message: `Subcontract "${file}" glob "${childGlob}" escapes parent boundaries (${v.code})`
235
+ });
236
+ }
237
+ }
238
+
239
+ totalReserved += sub.budget?.reserved_budget_usd ?? sub.budget?.max_budget_usd ?? 0;
240
+ }
241
+
242
+ if (
243
+ typeof parentContract.budget?.max_budget_usd === 'number' &&
244
+ totalReserved > parentContract.budget.max_budget_usd + 1e-9
245
+ ) {
246
+ violations.push({
247
+ code: 'SHARED_BUDGET_MULTIPLICATION',
248
+ message: `Subcontracts reserve $${totalReserved.toFixed(2)} exceeding parent max_budget_usd $${parentContract.budget.max_budget_usd.toFixed(2)}`
249
+ });
250
+ }
251
+
252
+ return { count: files.length, violations };
253
+ }
254
+
255
+
256
+
257
+
258
+
259
+
260
+
261
+
262
+
263
+
264
+
265
+
266
+
267
+ function buildCheckViolation(
268
+ chk ,
269
+ res ,
270
+ outcome
271
+ ) {
272
+ if (outcome.timedOut) {
273
+ return {
274
+ code: 'REQUIRED_CHECK_TIMEOUT',
275
+ message: `Required check "${chk.id}" timed out after ${chk.timeout_sec ?? 300}s (exit 124)`
276
+ };
277
+ }
278
+ if (outcome.spawnErrorCode) {
279
+ return {
280
+ code: 'CHECK_SPAWN_ERROR',
281
+ message: `Required check "${chk.id}" failed to spawn (${outcome.spawnErrorCode}): ${outcome.spawnErrorMessage ?? 'unknown spawn error'} (not a timeout; check sandbox or shell permissions)`
282
+ };
283
+ }
284
+ if (res.exit_code !== 0) {
285
+ return {
286
+ code: 'REQUIRED_CHECK_FAILED',
287
+ message: `Required check "${chk.id}" exited with code ${res.exit_code}`
288
+ };
289
+ }
290
+ return null;
291
+ }
292
+
293
+ function resolveCheckCwd(chk , repoRoot ) {
294
+ if (!chk.cwd || chk.cwd === '.') return { ok: true, cwd: repoRoot };
295
+ const safeCwd = normalizeRepoRelativePath(chk.cwd, repoRoot);
296
+ if (!safeCwd.ok) {
297
+ return {
298
+ ok: false,
299
+ violation: {
300
+ code: 'PATH_ESCAPE',
301
+ path: chk.cwd,
302
+ message: safeCwd.reason
303
+ }
304
+ };
305
+ }
306
+ return { ok: true, cwd: path.join(repoRoot, safeCwd.relPath) };
307
+ }
308
+
309
+ function executeCheckSync(
310
+ chk ,
311
+ checkCwd ,
312
+ shellPath
313
+ ) {
314
+ const startMs = Date.now();
315
+ const childEnv = { ...process.env };
316
+ delete childEnv.NODE_TEST_CONTEXT;
317
+ const timeoutMs = (chk.timeout_sec ?? 300) * 1000;
318
+ const proc = spawnSync(shellPath, ['-c', chk.command], {
319
+ cwd: checkCwd,
320
+ env: childEnv,
321
+ timeout: timeoutMs,
322
+ maxBuffer: 32 * 1024 * 1024,
323
+ encoding: 'buffer'
324
+ });
325
+ const durationMs = Date.now() - startMs;
326
+ const stdoutBuf = proc.stdout ?? Buffer.alloc(0);
327
+ const stderrBuf = proc.stderr ?? Buffer.alloc(0);
328
+ const combinedText = stdoutBuf.toString('utf8') + '\n' + stderrBuf.toString('utf8');
329
+ const skippedCount = parseSkippedTestCount(combinedText);
330
+ const outcome = classifyCheckProcessOutcome({
331
+ error: proc.error ?? null,
332
+ status: proc.status,
333
+ signal: proc.signal
334
+ });
335
+
336
+ const result = {
337
+ id: chk.id,
338
+ command: chk.command,
339
+ exit_code: outcome.exitCode,
340
+ skipped_count: skippedCount,
341
+ duration_ms: durationMs,
342
+ stdout_sha256: sha256Hex(stdoutBuf),
343
+ stderr_sha256: sha256Hex(stderrBuf),
344
+ ...(outcome.timedOut ? { timed_out: true } : {}),
345
+ ...(outcome.spawnErrorCode ? { spawn_error_code: outcome.spawnErrorCode } : {}),
346
+ ...(outcome.spawnErrorMessage ? { spawn_error_message: outcome.spawnErrorMessage } : {})
347
+ };
348
+ return { result, outcome };
349
+ }
350
+
351
+ function executeCheckAsync(
352
+ chk ,
353
+ checkCwd ,
354
+ shellPath ,
355
+ heartbeatSec ,
356
+ onHeartbeat
357
+ ) {
358
+ return new Promise((resolve) => {
359
+ const startMs = Date.now();
360
+ const timeoutSec = chk.timeout_sec ?? 300;
361
+ const timeoutMs = timeoutSec * 1000;
362
+ const childEnv = { ...process.env };
363
+ delete childEnv.NODE_TEST_CONTEXT;
364
+
365
+ const stdoutChunks = [];
366
+ const stderrChunks = [];
367
+ let spawnErr = null;
368
+ let timedOut = false;
369
+ let settled = false;
370
+
371
+ const child = spawn(shellPath, ['-c', chk.command], {
372
+ cwd: checkCwd,
373
+ env: childEnv,
374
+ stdio: ['ignore', 'pipe', 'pipe']
375
+ });
376
+
377
+ child.stdout?.on('data', (chunk ) => stdoutChunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)));
378
+ child.stderr?.on('data', (chunk ) => stderrChunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)));
379
+
380
+ const timeoutTimer = setTimeout(() => {
381
+ timedOut = true;
382
+ try {
383
+ child.kill('SIGTERM');
384
+ } catch {
385
+ // ignore kill error
386
+ }
387
+ }, timeoutMs);
388
+ timeoutTimer.unref?.();
389
+
390
+ const hbTimer =
391
+ heartbeatSec > 0
392
+ ? setInterval(() => {
393
+ const elapsedSec = Math.max(1, Math.round((Date.now() - startMs) / 1000));
394
+ const msg = `[diffpact] running check "${chk.id}" (pid=${child.pid ?? 'unknown'}, elapsed ${elapsedSec}s / timeout ${timeoutSec}s)...`;
395
+ if (onHeartbeat) onHeartbeat(msg);
396
+ else process.stderr.write(msg + '\n');
397
+ }, heartbeatSec * 1000)
398
+ : null;
399
+ hbTimer?.unref?.();
400
+
401
+ const finish = (status , signal ) => {
402
+ if (settled) return;
403
+ settled = true;
404
+ clearTimeout(timeoutTimer);
405
+ if (hbTimer) clearInterval(hbTimer);
406
+
407
+ const durationMs = Date.now() - startMs;
408
+ const stdoutBuf = Buffer.concat(stdoutChunks);
409
+ const stderrBuf = Buffer.concat(stderrChunks);
410
+ const combinedText = stdoutBuf.toString('utf8') + '\n' + stderrBuf.toString('utf8');
411
+ const skippedCount = parseSkippedTestCount(combinedText);
412
+ const outcome = classifyCheckProcessOutcome({
413
+ error: spawnErr,
414
+ status,
415
+ signal,
416
+ timedOut
417
+ });
418
+
419
+ const result = {
420
+ id: chk.id,
421
+ command: chk.command,
422
+ exit_code: outcome.exitCode,
423
+ skipped_count: skippedCount,
424
+ duration_ms: durationMs,
425
+ stdout_sha256: sha256Hex(stdoutBuf),
426
+ stderr_sha256: sha256Hex(stderrBuf),
427
+ ...(outcome.timedOut ? { timed_out: true } : {}),
428
+ ...(outcome.spawnErrorCode ? { spawn_error_code: outcome.spawnErrorCode } : {}),
429
+ ...(outcome.spawnErrorMessage ? { spawn_error_message: outcome.spawnErrorMessage } : {})
430
+ };
431
+ resolve({ result, outcome });
432
+ };
433
+
434
+ child.on('error', (err) => {
435
+ spawnErr = err;
436
+ finish(null, null);
437
+ });
438
+ child.on('close', (code, signal) => {
439
+ finish(code, signal);
440
+ });
441
+ });
442
+ }
443
+
444
+ export function runVerify(options )
445
+
446
+
447
+
448
+ {
449
+ const contractAbs = path.resolve(options.cwd ?? process.cwd(), options.contractPath);
450
+ if (!fs.existsSync(contractAbs)) {
451
+ return {
452
+ exitCode: EXIT_INCOMPLETE,
453
+ error: `Missing contract file at "${contractAbs}" (No Silent Zero)`
454
+ };
455
+ }
456
+
457
+ let contract ;
458
+ try {
459
+ contract = validateContract(JSON.parse(fs.readFileSync(contractAbs, 'utf8')));
460
+ } catch (err) {
461
+ return {
462
+ exitCode: EXIT_INCOMPLETE,
463
+ error: `Invalid contract schema: ${(err ).message}`
464
+ };
465
+ }
466
+
467
+ const contractSha256 = canonicalSha256('diffpact/contract/v0.1', contract);
468
+ const workDir = options.cwd ?? path.dirname(path.dirname(contractAbs));
469
+
470
+ let repoRoot ;
471
+ let headSha ;
472
+ let branch ;
473
+ try {
474
+ repoRoot = resolveRepoRoot(workDir);
475
+ headSha = resolveHeadSha(repoRoot);
476
+ branch = resolveCurrentBranch(repoRoot);
477
+ } catch (err) {
478
+ return {
479
+ exitCode: EXIT_INCOMPLETE,
480
+ error: `Git repository unavailable at "${workDir}": ${(err ).message}`
481
+ };
482
+ }
483
+
484
+ const violations = [];
485
+ let staleDetected = false;
486
+ let incompleteDetected = false;
487
+
488
+ // 1. Starting SHA & Ancestry checks
489
+ if (!commitExists(repoRoot, contract.starting_sha)) {
490
+ staleDetected = true;
491
+ violations.push({
492
+ code: 'STARTING_SHA_MISSING',
493
+ message: `starting_sha ${contract.starting_sha} does not exist in Git object store`
494
+ });
495
+ } else if (!isAncestor(repoRoot, contract.starting_sha, headSha)) {
496
+ staleDetected = true;
497
+ violations.push({
498
+ code: 'STARTING_SHA_NOT_ANCESTOR',
499
+ message: `starting_sha ${contract.starting_sha} is not an ancestor of HEAD ${headSha}`
500
+ });
501
+ }
502
+
503
+ if (contract.candidate_sha && contract.candidate_sha !== headSha) {
504
+ staleDetected = true;
505
+ violations.push({
506
+ code: 'CANDIDATE_SHA_MISMATCH',
507
+ message: `Pinned candidate_sha ${contract.candidate_sha} does not match HEAD ${headSha}`
508
+ });
509
+ }
510
+
511
+ // 2. Worktree & Branch checks
512
+ if (contract.worktree.branch && contract.worktree.branch !== branch) {
513
+ violations.push({
514
+ code: 'BRANCH_MISMATCH',
515
+ message: `Expected branch "${contract.worktree.branch}", found "${branch}"`
516
+ });
517
+ }
518
+ if (contract.worktree.path) {
519
+ let expectedReal ;
520
+ try {
521
+ expectedReal = fs.realpathSync(contract.worktree.path);
522
+ } catch {
523
+ expectedReal = path.resolve(contract.worktree.path);
524
+ }
525
+ if (expectedReal !== repoRoot) {
526
+ violations.push({
527
+ code: 'WORKTREE_PATH_MISMATCH',
528
+ message: `Expected worktree "${expectedReal}", found "${repoRoot}"`
529
+ });
530
+ }
531
+ }
532
+
533
+ // 3. Collect repo changes & evaluate path/symlink boundaries
534
+ const snap = commitExists(repoRoot, contract.starting_sha)
535
+ ? collectRepoChanges(repoRoot, contract.starting_sha, headSha)
536
+ : { changedFiles: [], untrackedFiles: [], workingTreeClean: false, rawDiffSha256: sha256Hex('') };
537
+
538
+ if (contract.worktree.require_clean_end !== false && !snap.workingTreeClean) {
539
+ violations.push({
540
+ code: 'DIRTY_WORKING_TREE',
541
+ message: 'Working tree has uncommitted or untracked changes outside .diffpact/'
542
+ });
543
+ }
544
+
545
+ if (
546
+ contract.task_type === 'coding' &&
547
+ !contract.allow_no_commit &&
548
+ headSha === contract.starting_sha
549
+ ) {
550
+ incompleteDetected = true;
551
+ violations.push({
552
+ code: 'NO_CANDIDATE_COMMIT',
553
+ message: 'HEAD equals starting_sha; coding contract requires at least one candidate commit unless allow_no_commit is true'
554
+ });
555
+ }
556
+
557
+ const outOfBoundsSet = new Set ();
558
+ for (const ch of snap.changedFiles) {
559
+ if (ch.is_symlink) {
560
+ outOfBoundsSet.add(ch.path);
561
+ violations.push({
562
+ code: 'SYMLINK_FORBIDDEN',
563
+ path: ch.path,
564
+ message: `Symlink "${ch.path}" is forbidden inside bounded task worktrees`
565
+ });
566
+ }
567
+ if (ch.is_submodule) {
568
+ outOfBoundsSet.add(ch.path);
569
+ violations.push({
570
+ code: 'SUBMODULE_FORBIDDEN',
571
+ path: ch.path,
572
+ message: `Git submodule (mode 160000) "${ch.path}" is forbidden inside bounded task worktrees`
573
+ });
574
+ }
575
+ const vNew = evaluatePathBoundary(ch.path, repoRoot, contract);
576
+ if (vNew) {
577
+ outOfBoundsSet.add(ch.path);
578
+ violations.push(vNew);
579
+ }
580
+ if (ch.old_path) {
581
+ const vOld = evaluatePathBoundary(ch.old_path, repoRoot, contract);
582
+ if (vOld) {
583
+ outOfBoundsSet.add(ch.old_path);
584
+ violations.push(vOld);
585
+ }
586
+ }
587
+ }
588
+ for (const ut of snap.untrackedFiles) {
589
+ const fullUt = path.join(repoRoot, ut);
590
+ try {
591
+ if (fs.lstatSync(fullUt).isSymbolicLink()) {
592
+ outOfBoundsSet.add(ut);
593
+ violations.push({
594
+ code: 'SYMLINK_FORBIDDEN',
595
+ path: ut,
596
+ message: `Untracked symlink "${ut}" is forbidden`
597
+ });
598
+ }
599
+ } catch {
600
+ // ignore
601
+ }
602
+ const vUt = evaluatePathBoundary(ut, repoRoot, contract);
603
+ if (vUt) {
604
+ outOfBoundsSet.add(ut);
605
+ violations.push(vUt);
606
+ }
607
+ }
608
+
609
+ // 4. Version assertions & optional InterfaceDelta lockfile pin
610
+ const versionViolations = evaluateVersionAssertions(repoRoot, contract);
611
+ violations.push(...versionViolations);
612
+ const versionAssertionsOk = versionViolations.length === 0;
613
+
614
+ let lockfileOk = null;
615
+ if (contract.interfacedelta_lockfile) {
616
+ const safeLockRel = normalizeRepoRelativePath(contract.interfacedelta_lockfile.path, repoRoot);
617
+ const lfPath = safeLockRel.ok ? path.join(repoRoot, safeLockRel.relPath) : '';
618
+ if (!safeLockRel.ok) {
619
+ lockfileOk = false;
620
+ violations.push({
621
+ code: 'PATH_ESCAPE',
622
+ path: contract.interfacedelta_lockfile.path,
623
+ message: safeLockRel.reason
624
+ });
625
+ } else if (!fs.existsSync(lfPath)) {
626
+ lockfileOk = false;
627
+ violations.push({
628
+ code: 'LOCKFILE_MISSING',
629
+ path: contract.interfacedelta_lockfile.path,
630
+ message: `Pinned InterfaceDelta lockfile "${contract.interfacedelta_lockfile.path}" is missing`
631
+ });
632
+ } else {
633
+ const actualSha = sha256Hex(fs.readFileSync(lfPath));
634
+ lockfileOk = actualSha === contract.interfacedelta_lockfile.sha256;
635
+ if (!lockfileOk) {
636
+ violations.push({
637
+ code: 'LOCKFILE_DRIFT',
638
+ path: contract.interfacedelta_lockfile.path,
639
+ message: `InterfaceDelta lockfile SHA-256 drifted: expected ${contract.interfacedelta_lockfile.sha256}, got ${actualSha}`
640
+ });
641
+ }
642
+ }
643
+ }
644
+
645
+ // 5. Monotonic Subcontracts check
646
+ const subCheck = evaluateSubcontracts(path.dirname(contractAbs), contract, contractSha256, repoRoot);
647
+ violations.push(...subCheck.violations);
648
+
649
+ // 6. Required checks execution + No Silent Zero enforcement
650
+ const shellPath = options.shellPath ?? '/bin/sh';
651
+ const checkResults = [];
652
+ if (contract.required_checks.length === 0 && !contract.allow_no_checks) {
653
+ incompleteDetected = true;
654
+ violations.push({
655
+ code: 'NO_SILENT_ZERO_EMPTY_CHECKS',
656
+ message: 'required_checks is empty without allow_no_checks: true'
657
+ });
658
+ } else {
659
+ for (const chk of contract.required_checks) {
660
+ const cwdRes = resolveCheckCwd(chk, repoRoot);
661
+ if (!cwdRes.ok) {
662
+ violations.push(cwdRes.violation);
663
+ continue;
664
+ }
665
+ const { result, outcome } = executeCheckSync(chk, cwdRes.cwd, shellPath);
666
+ checkResults.push(result);
667
+
668
+ const failViol = buildCheckViolation(chk, result, outcome);
669
+ if (failViol) {
670
+ violations.push(failViol);
671
+ } else if (chk.forbid_skipped !== false && result.skipped_count > 0) {
672
+ incompleteDetected = true;
673
+ violations.push({
674
+ code: 'NO_SILENT_ZERO_SKIPPED_TESTS',
675
+ message: `Required check "${chk.id}" exited 0 but skipped ${result.skipped_count} test(s)`
676
+ });
677
+ }
678
+ }
679
+ }
680
+
681
+ // 7. Optional advisory checks (recorded in receipt for reviewer visibility; never block exit 0)
682
+ const advisoryResults = [];
683
+ for (const adv of contract.advisory_checks ?? []) {
684
+ const cwdRes = resolveCheckCwd(adv, repoRoot);
685
+ if (!cwdRes.ok) {
686
+ advisoryResults.push({
687
+ id: adv.id,
688
+ command: adv.command,
689
+ exit_code: 126,
690
+ skipped_count: 0,
691
+ duration_ms: 0,
692
+ stdout_sha256: sha256Hex(''),
693
+ stderr_sha256: sha256Hex(cwdRes.violation.message),
694
+ spawn_error_code: 'PATH_ESCAPE',
695
+ spawn_error_message: cwdRes.violation.message
696
+ });
697
+ continue;
698
+ }
699
+ const { result } = executeCheckSync(adv, cwdRes.cwd, shellPath);
700
+ advisoryResults.push(result);
701
+ }
702
+
703
+ // Determine canonical status & exit code:
704
+ // Violation (1) outranks Incomplete (2), Stale (3) outranks Pass (0); if stale git ancestry, return 3 unless explicit boundary violation (1).
705
+ const hardViolations = violations.filter(
706
+ (v) =>
707
+ ![
708
+ 'STARTING_SHA_MISSING',
709
+ 'STARTING_SHA_NOT_ANCESTOR',
710
+ 'CANDIDATE_SHA_MISMATCH',
711
+ 'NO_CANDIDATE_COMMIT',
712
+ 'NO_SILENT_ZERO_EMPTY_CHECKS',
713
+ 'NO_SILENT_ZERO_SKIPPED_TESTS'
714
+ ].includes(v.code)
715
+ );
716
+
717
+ let finalExit = EXIT_PASS;
718
+ let status = 'pass';
719
+ if (hardViolations.length > 0) {
720
+ finalExit = EXIT_VIOLATION;
721
+ status = 'violation';
722
+ } else if (staleDetected) {
723
+ finalExit = EXIT_STALE;
724
+ status = 'stale';
725
+ } else if (incompleteDetected) {
726
+ finalExit = EXIT_INCOMPLETE;
727
+ status = 'incomplete';
728
+ }
729
+
730
+ const receiptBody = {
731
+ schema_version: 'diffpact-receipt-v0.1' ,
732
+ contract_sha256: contractSha256,
733
+ task_id: contract.task_id,
734
+ verified_at: new Date().toISOString(),
735
+ starting_sha: contract.starting_sha,
736
+ candidate_sha: headSha,
737
+ raw_diff_sha256: snap.rawDiffSha256,
738
+ branch,
739
+ worktree_path: repoRoot,
740
+ working_tree_clean: snap.workingTreeClean,
741
+ status,
742
+ exit_code: finalExit,
743
+ diff_summary: {
744
+ changed_files: snap.changedFiles,
745
+ untracked_files: snap.untrackedFiles,
746
+ out_of_bounds_files: [...outOfBoundsSet].sort()
747
+ },
748
+ version_assertions_ok: versionAssertionsOk,
749
+ interfacedelta_lockfile_ok: lockfileOk,
750
+ subcontracts_checked: subCheck.count,
751
+ checks: checkResults,
752
+ ...(advisoryResults.length > 0 ? { advisory_checks: advisoryResults } : {}),
753
+ violations
754
+ };
755
+
756
+ const receiptSha256 = canonicalSha256('diffpact/receipt/v0.1', receiptBody);
757
+ const receipt = {
758
+ receipt_sha256: receiptSha256,
759
+ ...receiptBody
760
+ };
761
+
762
+ if (options.writeReceipt !== false) {
763
+ const outDir = path.dirname(contractAbs);
764
+ fs.mkdirSync(outDir, { recursive: true });
765
+ fs.writeFileSync(path.join(outDir, 'receipt.json'), JSON.stringify(receipt, null, 2) + '\n');
766
+ }
767
+
768
+ return { exitCode: finalExit, receipt };
769
+ }
770
+
771
+ /**
772
+ * Async variant of `runVerify` that emits periodic stderr heartbeats during long-running checks.
773
+ */
774
+ export async function runVerifyAsync(options )
775
+
776
+
777
+
778
+ {
779
+ const heartbeatSec = options.heartbeatSec ?? 0;
780
+ if (heartbeatSec <= 0 && !options.onHeartbeat) {
781
+ return runVerify(options);
782
+ }
783
+
784
+ const contractAbs = path.resolve(options.cwd ?? process.cwd(), options.contractPath);
785
+ if (!fs.existsSync(contractAbs)) {
786
+ return {
787
+ exitCode: EXIT_INCOMPLETE,
788
+ error: `Missing contract file at "${contractAbs}" (No Silent Zero)`
789
+ };
790
+ }
791
+
792
+ let contract ;
793
+ try {
794
+ contract = validateContract(JSON.parse(fs.readFileSync(contractAbs, 'utf8')));
795
+ } catch (err) {
796
+ return {
797
+ exitCode: EXIT_INCOMPLETE,
798
+ error: `Invalid contract schema: ${(err ).message}`
799
+ };
800
+ }
801
+
802
+ // Run synchronous boundary/lockfile/subcontract analysis first without executing checks,
803
+ // then run required + advisory checks asynchronously with heartbeats.
804
+ const baseContractNoChecks = {
805
+ ...contract,
806
+ required_checks: [],
807
+ advisory_checks: [],
808
+ allow_no_checks: true
809
+ };
810
+ const tmpNoChecksPath = path.join(path.dirname(contractAbs), `.tmp-verify-${process.pid}-${Date.now()}.json`);
811
+ let baseRes ;
812
+ try {
813
+ fs.writeFileSync(tmpNoChecksPath, JSON.stringify(baseContractNoChecks));
814
+ baseRes = runVerify({
815
+ contractPath: tmpNoChecksPath,
816
+ cwd: options.cwd,
817
+ writeReceipt: false
818
+ });
819
+ } finally {
820
+ try {
821
+ if (fs.existsSync(tmpNoChecksPath)) fs.unlinkSync(tmpNoChecksPath);
822
+ } catch {
823
+ // ignore
824
+ }
825
+ }
826
+
827
+ if (!baseRes.receipt) return baseRes;
828
+
829
+ const contractSha256 = canonicalSha256('diffpact/contract/v0.1', contract);
830
+ const repoRoot = baseRes.receipt.worktree_path;
831
+ const shellPath = options.shellPath ?? '/bin/sh';
832
+ const violations = [...baseRes.receipt.violations];
833
+ let incompleteDetected = baseRes.receipt.status === 'incomplete';
834
+ const staleDetected = baseRes.receipt.status === 'stale';
835
+
836
+ const checkResults = [];
837
+ if (contract.required_checks.length === 0 && !contract.allow_no_checks) {
838
+ incompleteDetected = true;
839
+ violations.push({
840
+ code: 'NO_SILENT_ZERO_EMPTY_CHECKS',
841
+ message: 'required_checks is empty without allow_no_checks: true'
842
+ });
843
+ } else {
844
+ for (const chk of contract.required_checks) {
845
+ const cwdRes = resolveCheckCwd(chk, repoRoot);
846
+ if (!cwdRes.ok) {
847
+ violations.push(cwdRes.violation);
848
+ continue;
849
+ }
850
+ const { result, outcome } = await executeCheckAsync(
851
+ chk,
852
+ cwdRes.cwd,
853
+ shellPath,
854
+ heartbeatSec,
855
+ options.onHeartbeat
856
+ );
857
+ checkResults.push(result);
858
+ const failViol = buildCheckViolation(chk, result, outcome);
859
+ if (failViol) {
860
+ violations.push(failViol);
861
+ } else if (chk.forbid_skipped !== false && result.skipped_count > 0) {
862
+ incompleteDetected = true;
863
+ violations.push({
864
+ code: 'NO_SILENT_ZERO_SKIPPED_TESTS',
865
+ message: `Required check "${chk.id}" exited 0 but skipped ${result.skipped_count} test(s)`
866
+ });
867
+ }
868
+ }
869
+ }
870
+
871
+ const advisoryResults = [];
872
+ for (const adv of contract.advisory_checks ?? []) {
873
+ const cwdRes = resolveCheckCwd(adv, repoRoot);
874
+ if (!cwdRes.ok) {
875
+ advisoryResults.push({
876
+ id: adv.id,
877
+ command: adv.command,
878
+ exit_code: 126,
879
+ skipped_count: 0,
880
+ duration_ms: 0,
881
+ stdout_sha256: sha256Hex(''),
882
+ stderr_sha256: sha256Hex(cwdRes.violation.message),
883
+ spawn_error_code: 'PATH_ESCAPE',
884
+ spawn_error_message: cwdRes.violation.message
885
+ });
886
+ continue;
887
+ }
888
+ const { result } = await executeCheckAsync(adv, cwdRes.cwd, shellPath, heartbeatSec, options.onHeartbeat);
889
+ advisoryResults.push(result);
890
+ }
891
+
892
+ const hardViolations = violations.filter(
893
+ (v) =>
894
+ ![
895
+ 'STARTING_SHA_MISSING',
896
+ 'STARTING_SHA_NOT_ANCESTOR',
897
+ 'CANDIDATE_SHA_MISMATCH',
898
+ 'NO_CANDIDATE_COMMIT',
899
+ 'NO_SILENT_ZERO_EMPTY_CHECKS',
900
+ 'NO_SILENT_ZERO_SKIPPED_TESTS'
901
+ ].includes(v.code)
902
+ );
903
+
904
+ let finalExit = EXIT_PASS;
905
+ let status = 'pass';
906
+ if (hardViolations.length > 0) {
907
+ finalExit = EXIT_VIOLATION;
908
+ status = 'violation';
909
+ } else if (staleDetected) {
910
+ finalExit = EXIT_STALE;
911
+ status = 'stale';
912
+ } else if (incompleteDetected) {
913
+ finalExit = EXIT_INCOMPLETE;
914
+ status = 'incomplete';
915
+ }
916
+
917
+ const receiptBody = {
918
+ schema_version: 'diffpact-receipt-v0.1' ,
919
+ contract_sha256: contractSha256,
920
+ task_id: contract.task_id,
921
+ verified_at: new Date().toISOString(),
922
+ starting_sha: contract.starting_sha,
923
+ candidate_sha: baseRes.receipt.candidate_sha,
924
+ raw_diff_sha256: baseRes.receipt.raw_diff_sha256,
925
+ branch: baseRes.receipt.branch,
926
+ worktree_path: repoRoot,
927
+ working_tree_clean: baseRes.receipt.working_tree_clean,
928
+ status,
929
+ exit_code: finalExit,
930
+ diff_summary: baseRes.receipt.diff_summary,
931
+ version_assertions_ok: baseRes.receipt.version_assertions_ok,
932
+ interfacedelta_lockfile_ok: baseRes.receipt.interfacedelta_lockfile_ok,
933
+ subcontracts_checked: baseRes.receipt.subcontracts_checked,
934
+ checks: checkResults,
935
+ ...(advisoryResults.length > 0 ? { advisory_checks: advisoryResults } : {}),
936
+ violations
937
+ };
938
+
939
+ const receiptSha256 = canonicalSha256('diffpact/receipt/v0.1', receiptBody);
940
+ const receipt = {
941
+ receipt_sha256: receiptSha256,
942
+ ...receiptBody
943
+ };
944
+
945
+ if (options.writeReceipt !== false) {
946
+ const outDir = path.dirname(contractAbs);
947
+ fs.mkdirSync(outDir, { recursive: true });
948
+ fs.writeFileSync(path.join(outDir, 'receipt.json'), JSON.stringify(receipt, null, 2) + '\n');
949
+ }
950
+
951
+ return { exitCode: finalExit, receipt };
952
+ }