@cleocode/core 2026.11.13 → 2026.11.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/dist/.source-stamp.json +1 -1
  2. package/dist/build-provenance.json +2 -2
  3. package/dist/intelligence/impact.js +15 -30
  4. package/dist/intelligence/impact.js.map +1 -1
  5. package/dist/memory/brain-reasoning.js +6 -12
  6. package/dist/memory/brain-reasoning.js.map +1 -1
  7. package/dist/orchestrate/lead-records.d.ts +1 -1
  8. package/dist/orchestrate/lead-records.js +1 -1
  9. package/dist/orchestrate/query-ops.d.ts +13 -1
  10. package/dist/orchestrate/query-ops.js +34 -13
  11. package/dist/orchestrate/query-ops.js.map +1 -1
  12. package/dist/orchestration/analyze.d.ts +11 -3
  13. package/dist/orchestration/analyze.js +13 -5
  14. package/dist/orchestration/analyze.js.map +1 -1
  15. package/dist/orchestration/classify-readiness.js +2 -12
  16. package/dist/orchestration/classify-readiness.js.map +1 -1
  17. package/dist/orchestration/critical-path.d.ts +1 -1
  18. package/dist/orchestration/critical-path.js +4 -5
  19. package/dist/orchestration/critical-path.js.map +1 -1
  20. package/dist/orchestration/dashboard.js +5 -7
  21. package/dist/orchestration/dashboard.js.map +1 -1
  22. package/dist/orchestration/spawn-prompt.js +3 -3
  23. package/dist/orchestration/spawn-prompt.js.map +1 -1
  24. package/dist/project-scope.d.ts +2 -0
  25. package/dist/project-scope.js.map +1 -1
  26. package/dist/resources/claim-keepalive.d.ts +56 -0
  27. package/dist/resources/claim-keepalive.js +123 -0
  28. package/dist/resources/claim-keepalive.js.map +1 -1
  29. package/dist/sagas/rollup.d.ts +6 -1
  30. package/dist/sagas/rollup.js +8 -1
  31. package/dist/sagas/rollup.js.map +1 -1
  32. package/dist/sentient/tick.js +5 -3
  33. package/dist/sentient/tick.js.map +1 -1
  34. package/dist/sessions/briefing.js +12 -21
  35. package/dist/sessions/briefing.js.map +1 -1
  36. package/dist/skills/orchestrator/startup.d.ts +13 -0
  37. package/dist/skills/orchestrator/startup.js +18 -6
  38. package/dist/skills/orchestrator/startup.js.map +1 -1
  39. package/dist/store/session-store.d.ts +18 -0
  40. package/dist/store/session-store.js +33 -1
  41. package/dist/store/session-store.js.map +1 -1
  42. package/dist/store/sqlite-data-accessor.js +1 -1
  43. package/dist/store/sqlite-data-accessor.js.map +1 -1
  44. package/dist/store/task-claim.d.ts +7 -2
  45. package/dist/store/task-claim.js +16 -2
  46. package/dist/store/task-claim.js.map +1 -1
  47. package/dist/task-tools/build-task-tree.d.ts +2 -1
  48. package/dist/task-tools/build-task-tree.js +8 -9
  49. package/dist/task-tools/build-task-tree.js.map +1 -1
  50. package/dist/task-work/claims.d.ts +28 -3
  51. package/dist/task-work/claims.js +36 -4
  52. package/dist/task-work/claims.js.map +1 -1
  53. package/dist/task-work/index.d.ts +5 -4
  54. package/dist/task-work/index.js +30 -15
  55. package/dist/task-work/index.js.map +1 -1
  56. package/dist/tasks/agent-lifecycle-lane.d.ts +1 -1
  57. package/dist/tasks/compute-task-view.d.ts +2 -1
  58. package/dist/tasks/compute-task-view.js +18 -8
  59. package/dist/tasks/compute-task-view.js.map +1 -1
  60. package/dist/tasks/dependency-check.d.ts +53 -7
  61. package/dist/tasks/dependency-check.js +63 -51
  62. package/dist/tasks/dependency-check.js.map +1 -1
  63. package/dist/tasks/done-plan.js +20 -9
  64. package/dist/tasks/done-plan.js.map +1 -1
  65. package/dist/tasks/gate-result-cache.d.ts +34 -4
  66. package/dist/tasks/gate-result-cache.js +168 -11
  67. package/dist/tasks/gate-result-cache.js.map +1 -1
  68. package/dist/tasks/gate-runner.d.ts +12 -0
  69. package/dist/tasks/gate-runner.js +186 -30
  70. package/dist/tasks/gate-runner.js.map +1 -1
  71. package/dist/tasks/generic-tree.d.ts +2 -2
  72. package/dist/tasks/generic-tree.js +6 -10
  73. package/dist/tasks/generic-tree.js.map +1 -1
  74. package/dist/tasks/graph-ops.d.ts +3 -1
  75. package/dist/tasks/graph-ops.js +12 -20
  76. package/dist/tasks/graph-ops.js.map +1 -1
  77. package/dist/tasks/merge-close.js +13 -4
  78. package/dist/tasks/merge-close.js.map +1 -1
  79. package/dist/tasks/show.js +3 -2
  80. package/dist/tasks/show.js.map +1 -1
  81. package/dist/tasks/task-blockers.js +6 -16
  82. package/dist/tasks/task-blockers.js.map +1 -1
  83. package/dist/tasks/task-context.js +5 -4
  84. package/dist/tasks/task-context.js.map +1 -1
  85. package/dist/tasks/task-data.d.ts +4 -1
  86. package/dist/tasks/task-data.js +31 -34
  87. package/dist/tasks/task-data.js.map +1 -1
  88. package/dist/tasks/task-tree.d.ts +3 -3
  89. package/dist/tasks/task-tree.js +6 -14
  90. package/dist/tasks/task-tree.js.map +1 -1
  91. package/dist/workgraph/containment.d.ts +3 -1
  92. package/dist/workgraph/containment.js +13 -5
  93. package/dist/workgraph/containment.js.map +1 -1
  94. package/dist/workgraph/scaffold-plan.d.ts +4 -1
  95. package/dist/workgraph/scaffold-plan.js +11 -5
  96. package/dist/workgraph/scaffold-plan.js.map +1 -1
  97. package/package.json +13 -13
@@ -26,7 +26,7 @@
26
26
  */
27
27
  import { execFileSync } from 'node:child_process';
28
28
  import { createHash, randomBytes, randomUUID } from 'node:crypto';
29
- import { constants, mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync, } from 'node:fs';
29
+ import { constants, existsSync, mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync, } from 'node:fs';
30
30
  import { lstat, open, readFile, realpath, stat } from 'node:fs/promises';
31
31
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
32
32
  import { isDeepStrictEqual } from 'node:util';
@@ -46,7 +46,7 @@ import { commandGateCmdProblem } from './command-gate-cmd.js';
46
46
  import { testGateArgv } from './command-line.js';
47
47
  import { resolveCanonicalProjectRoot } from './evidence.js';
48
48
  import { resolveEvidenceRepository, resolveEvidenceTree } from './evidence-tree.js';
49
- import { buildGateCacheEntryBody, captureGateCacheState, describeGateCacheMiss, evidenceCacheKeyPath, gateCacheEntryPath, isCacheableGate, readGateCacheEntry, sealGateCacheEntry, } from './gate-result-cache.js';
49
+ import { buildGateCacheEntryBody, captureGateCacheState, describeGateCacheMiss, evidenceCacheKeyPath, gateCacheEntryPath, gateInputsHash, isCacheableGate, readGateCacheEntry, sealGateCacheEntry, } from './gate-result-cache.js';
50
50
  import { planHeavyToolEnv, vitestWorkerCeiling } from './heavy-tool-env.js';
51
51
  import { readParsedTestReport, readTestReport, TEST_REPORT_FORMATS, testReporterFlag, } from './test-report-counts.js';
52
52
  import { resolveSpawnTimeoutMs } from './tool-cache.js';
@@ -245,7 +245,7 @@ export async function probeTypedGateCache(task, gate, execution, env = process.e
245
245
  reason: error instanceof Error ? error.message : String(error),
246
246
  };
247
247
  }
248
- const state = await captureGateCacheState(gateRoot);
248
+ const state = await captureGateCacheState(gateRoot, mergedGateCommit(gateRoot), task.id);
249
249
  if (state === null)
250
250
  return { status: 'unavailable', reason: 'the gate tree is not a git checkout' };
251
251
  const key = readEvidenceCacheKey();
@@ -268,7 +268,9 @@ export async function probeTypedGateCache(task, gate, execution, env = process.e
268
268
  };
269
269
  }
270
270
  const inputsHash = gateInputsHash(invocation, artifacts);
271
- const lookup = readGateCacheEntry(root, gate, state, inputsHash, key);
271
+ const lookup = readGateCacheEntry(root, gate, state, inputsHash, key, mergedGateCommit(gateRoot) && gate.repo === undefined
272
+ ? { invocation, environmentHash: invocation?.environmentHash ?? null, artifacts }
273
+ : undefined);
272
274
  if (lookup.status === 'hit')
273
275
  return { status: 'hit', cachedAt: lookup.createdAt };
274
276
  if (lookup.status === 'invalid')
@@ -282,13 +284,15 @@ export async function probeTypedGateCache(task, gate, execution, env = process.e
282
284
  };
283
285
  }
284
286
  /**
285
- * Seal and store a pass this runner EXECUTED itself. Module-private for the same
286
- * reason as {@link loadEvidenceCacheKey}: only an observed execution is cached.
287
+ * Seal a runner execution or carry an authenticated pass to a named merge.
288
+ * Only this module holds the key; a carry preserves its original tree and timestamp.
287
289
  */
288
- function writeExecutedGatePass(projectRoot, gate, state, inputsHash, observed, key, inputs) {
290
+ function writeGatePass(projectRoot, gate, state, inputsHash, observed, key, inputs, createdAt) {
289
291
  const body = buildGateCacheEntryBody(gate, state, inputsHash, observed, inputs);
290
292
  if (!body)
291
293
  return;
294
+ if (createdAt)
295
+ body.createdAt = createdAt;
292
296
  try {
293
297
  const path = gateCacheEntryPath(projectRoot, gate, state, inputsHash);
294
298
  mkdirSync(dirname(path), { recursive: true });
@@ -300,16 +304,6 @@ function writeExecutedGatePass(projectRoot, gate, state, inputsHash, observed, k
300
304
  // A cache is an optimisation: failing to persist one never fails the gate.
301
305
  }
302
306
  }
303
- /**
304
- * Digest of a gate's captured invocation and input artifacts: the part of its
305
- * cache key that the git fingerprint cannot see (untracked harness scripts,
306
- * task files, the environment hash).
307
- */
308
- function gateInputsHash(invocation, artifacts) {
309
- return createHash('sha256')
310
- .update(JSON.stringify({ invocation: invocation ?? null, artifacts }))
311
- .digest('hex');
312
- }
313
307
  /**
314
308
  * Compute a gate's cache inputs digest the same way the attesting verifier does.
315
309
  * @param task - Task that owns the gate; its `files` are verifier inputs.
@@ -344,7 +338,7 @@ export async function captureGateInputs(task, gate, execution, env = process.env
344
338
  const artifacts = await snapshotGateInputs(task, gate, invocation, execution, tree);
345
339
  return {
346
340
  hash: gateInputsHash(invocation, artifacts),
347
- inputs: { environmentHash: invocation?.environmentHash ?? null, artifacts },
341
+ inputs: { invocation, environmentHash: invocation?.environmentHash ?? null, artifacts },
348
342
  };
349
343
  }
350
344
  /**
@@ -380,6 +374,9 @@ export async function captureGateInputs(task, gate, execution, env = process.env
380
374
  * from the main checkout. Only this project's checkout or one of its linked
381
375
  * worktrees is accepted; any other candidate is skipped.
382
376
  *
377
+ * The merge sweep uses the store's repository to read immutable merge inputs;
378
+ * it neither enters a worker's old checkout nor executes a historical gate.
379
+ *
383
380
  * @param projectRoot - CLEO store root (the typed gate's authority).
384
381
  * @param cwd - Invocation directory. Defaults to `process.cwd()`.
385
382
  * @param env - Where the evidence declaration is read. Defaults to `process.env`.
@@ -400,6 +397,8 @@ env = process.env, taskId = null) {
400
397
  }
401
398
  };
402
399
  const root = real(projectRoot);
400
+ if (mergedGateCommit(root))
401
+ return projectRoot;
403
402
  const ofThisProject = (top) => real(top) === root || real(resolveCanonicalProjectRoot(top)) === root;
404
403
  const tree = real(resolveEvidenceTree(projectRoot, taskId, cwd, env, ofThisProject).root);
405
404
  return tree === root ? projectRoot : tree;
@@ -470,7 +469,7 @@ export async function runGates(gates, options = {}) {
470
469
  * that runs one gate per call (runTaskGates) passes the reserve it fixed at its
471
470
  * start, so the reserve does not shrink as the shared deadline nears (T14536).
472
471
  */
473
- async function runGateBatch(gates, options, reserveMs) {
472
+ async function runGateBatch(gates, options, reserveMs, binding) {
474
473
  const inherited = worktreeScope.getStore();
475
474
  if (inherited?.execution && options.execution && inherited.execution !== options.execution)
476
475
  throw new Error('Gate execution cannot replace an active captured operation');
@@ -523,7 +522,10 @@ async function runGateBatch(gates, options, reserveMs) {
523
522
  catch {
524
523
  cacheTree = null;
525
524
  }
526
- cacheState = cacheTree === null ? null : await captureGateCacheState(cacheTree);
525
+ cacheState =
526
+ cacheTree === null
527
+ ? null
528
+ : await captureGateCacheState(cacheTree, mergedGateCommit(cacheTree), options.taskId);
527
529
  }
528
530
  const cacheKey = cacheState ? loadEvidenceCacheKey() : null;
529
531
  const results = [];
@@ -544,8 +546,14 @@ async function runGateBatch(gates, options, reserveMs) {
544
546
  throw new Error('Gate includes unsupported or noncanonical fields');
545
547
  const gateRoot = gateTreeFor(parsed, treeRoot, projectRoot);
546
548
  if (cacheState && cacheKey && (cacheMode === 'use' || cacheMode === 'only')) {
547
- const lookup = readGateCacheEntry(projectRoot, parsed, cacheState, cacheInputsHash, cacheKey);
549
+ const lookup = readGateCacheEntry(projectRoot, parsed, cacheState, cacheInputsHash, cacheKey, mergedGateCommit(gateRoot) && parsed.repo === undefined
550
+ ? options.cacheInputs
551
+ : undefined);
548
552
  if (lookup.status === 'hit') {
553
+ const mergeSha = mergedGateCommit(gateRoot);
554
+ const origin = lookup.state;
555
+ if (mergeSha && origin.mergeSha !== mergeSha)
556
+ writeGatePass(projectRoot, parsed, { ...origin, mergeSha }, lookup.inputsHash, { ...lookup.observation, index: i }, cacheKey, undefined, lookup.createdAt);
549
557
  // Re-dated to now (the reuse is this run's check; a bound result
550
558
  // may not precede its input capture) and marked, never disguised.
551
559
  results.push({
@@ -554,6 +562,23 @@ async function runGateBatch(gates, options, reserveMs) {
554
562
  checkedAt: new Date().toISOString(),
555
563
  source: 'cache',
556
564
  cachedAt: lookup.createdAt,
565
+ ...(mergeSha && binding && origin.treeHash
566
+ ? {
567
+ binding: {
568
+ ...binding,
569
+ tree: {
570
+ headSha: origin.head,
571
+ treeHash: origin.treeHash,
572
+ clean: origin.clean === true,
573
+ mergeSha,
574
+ cwd: binding.invocation
575
+ ? relative(gateRoot, binding.invocation.cwd) || '.'
576
+ : '.',
577
+ inputsHash: treeInputsHash(gateRoot, binding.invocation, binding.artifacts),
578
+ },
579
+ },
580
+ }
581
+ : {}),
557
582
  });
558
583
  continue;
559
584
  }
@@ -567,14 +592,25 @@ async function runGateBatch(gates, options, reserveMs) {
567
592
  const why = cacheState && cacheKey
568
593
  ? describeGateCacheMiss(projectRoot, parsed, cacheState, cacheInputsHash, options.cacheInputs)
569
594
  : null;
570
- throw new Error(`${gateNotCachedMessage(parsed, cacheState !== null, cacheKey !== null)}${why ? ` ${why}` : ''}`);
595
+ throw new Error(`${gateNotCachedMessage(parsed, cacheState !== null, cacheKey !== null)}${why ? ` ${why}` : ''}${mergedGateCommit(gateRoot) && options.taskId ? ` Run \`${mergedGateVerifyCommand(options.taskId, projectRoot, mergedGateCommit(gateRoot), parsed.req)}\`.` : ''}`);
571
596
  }
597
+ if (mergedGateCommit(gateRoot) && isCacheableGate(parsed))
598
+ // @sync-invariant none:input-shape the merge sweep cannot execute a historical gate against the live checkout
599
+ throw new Error('Merge-tree verification only reads cached typed-gate passes');
572
600
  const observed = {
573
601
  ...(await runOneGate(parsed, i, gateRoot, options.skipManual ?? true, { ...batch, cwd: gateRoot }, projectRoot)),
574
602
  source: 'executed',
575
603
  };
576
- if (cacheState && cacheKey && cacheMode !== 'only')
577
- writeExecutedGatePass(projectRoot, parsed, cacheState, cacheInputsHash, observed, cacheKey, options.cacheInputs);
604
+ if (cacheState && cacheKey && cacheMode !== 'only') {
605
+ const after = await captureGateCacheState(gateRoot, undefined, options.taskId);
606
+ writeGatePass(projectRoot, parsed, {
607
+ ...cacheState,
608
+ clean: cacheState.clean === true &&
609
+ after?.clean === true &&
610
+ after.head === cacheState.head &&
611
+ after.treeHash === cacheState.treeHash,
612
+ }, cacheInputsHash, observed, cacheKey, options.cacheInputs);
613
+ }
578
614
  results.push(observed);
579
615
  }
580
616
  catch (error) {
@@ -611,6 +647,14 @@ function gitOut(cwd, args) {
611
647
  return null;
612
648
  }
613
649
  }
650
+ /** Immutable commit only while the merge sweep is judging this project's own repository. */
651
+ function mergedGateCommit(tree) {
652
+ const scope = worktreeScope.getStore();
653
+ return scope?.typedGateCommit &&
654
+ resolve(resolveCanonicalProjectRoot(tree)) === resolve(scope.worktreeRoot)
655
+ ? scope.typedGateCommit
656
+ : undefined;
657
+ }
614
658
  /** Digest of a gate's inputs with every path made relative to `tree` (T12625). */
615
659
  function treeInputsHash(tree, invocation, artifacts) {
616
660
  const rel = (path) => relative(tree, path) || '.';
@@ -637,12 +681,14 @@ function captureTreeBinding(tree, invocation, artifacts) {
637
681
  const headSha = gitOut(tree, ['rev-parse', 'HEAD']);
638
682
  if (headSha === null || !/^[0-9a-f]{40}$/.test(headSha))
639
683
  return undefined;
684
+ const treeHash = gitOut(tree, ['rev-parse', `${headSha}^{tree}`]);
640
685
  const dirty = gitOut(tree, ['status', '--porcelain', '--untracked-files=no']);
641
686
  const base = resolveOriginDefault(tree);
642
687
  const baseSha = base ? gitOut(tree, ['merge-base', base, headSha]) : null;
643
688
  return {
644
689
  headSha,
645
690
  clean: dirty === '',
691
+ ...(treeHash && /^[0-9a-f]{40}$/.test(treeHash) ? { treeHash } : {}),
646
692
  cwd: invocation ? relative(tree, invocation.cwd) || '.' : '.',
647
693
  inputsHash: treeInputsHash(tree, invocation, artifacts),
648
694
  ...(baseSha && /^[0-9a-f]{40}$/.test(baseSha) ? { baseSha } : {}),
@@ -663,6 +709,19 @@ export class TypedRevalidationError extends Error {
663
709
  this.fix = fix;
664
710
  }
665
711
  }
712
+ /**
713
+ * Build the exact command that caches a pass in a fresh checkout of the merge.
714
+ * @param taskId - Task whose gate must run.
715
+ * @param root - Existing repository from which to create the checkout.
716
+ * @param mergeSha - Immutable merge commit to verify.
717
+ * @param req - Optional requirement to run alone.
718
+ * @returns Shell command that leaves the existing checkout untouched.
719
+ */
720
+ export function mergedGateVerifyCommand(taskId, root, mergeSha, req) {
721
+ return (`cleo_gate_checkout=$(mktemp -d) && git -C ${shellArg(root)} worktree add --detach "$cleo_gate_checkout" ${shellArg(mergeSha)} && ` +
722
+ `if [ -d ${shellArg(join(root, 'node_modules'))} ] && [ ! -e "$cleo_gate_checkout/node_modules" ]; then ln -s ${shellArg(join(root, 'node_modules'))} "$cleo_gate_checkout/node_modules"; fi && ` +
723
+ `cd "$cleo_gate_checkout" && cleo verify ${taskId} --run${req ? ` --req ${shellArg(req)}` : ''}`);
724
+ }
666
725
  /** Exact command that re-records testsPassed (re-running typed gates) in `tree`. */
667
726
  function reverifyCommand(task, tree) {
668
727
  const atoms = (task.verification?.evidence?.testsPassed?.atoms ?? []).flatMap((atom) => {
@@ -691,6 +750,20 @@ function reverifyCommand(task, tree) {
691
750
  */
692
751
  function assertTreeEquivalent(task, gateLabel, bound, tree, projectRoot, invocation, artifacts) {
693
752
  const fix = reverifyCommand(task, tree);
753
+ const mergeCommit = mergedGateCommit(tree);
754
+ if (mergeCommit) {
755
+ const verifiedTree = gitOut(tree, ['rev-parse', `${bound.headSha}^{tree}`]);
756
+ const mergeTree = gitOut(tree, ['rev-parse', `${mergeCommit}^{tree}`]);
757
+ if (bound.clean &&
758
+ verifiedTree !== null &&
759
+ verifiedTree === mergeTree &&
760
+ bound.treeHash === verifiedTree &&
761
+ (!bound.mergeSha || bound.mergeSha === mergeCommit) &&
762
+ treeInputsHash(tree, invocation, artifacts) === bound.inputsHash)
763
+ return;
764
+ // @sync-invariant none:input-shape a stored typed pass must prove the immutable merge inputs before completion
765
+ throw new TypedRevalidationError(`Typed requirement ${gateLabel} ${bound.treeHash ? `inputs do not match merge commit ${mergeCommit.slice(0, 12)}` : 'has no recorded tree hash; re-run verification to migrate the stored pass'}`, mergedGateVerifyCommand(task.id, projectRoot, mergeCommit, gateLabel));
766
+ }
694
767
  const real = (p) => {
695
768
  try {
696
769
  return realpathSync(p);
@@ -837,18 +910,31 @@ export async function runTaskGates(task, criteria, options) {
837
910
  ? {
838
911
  cacheInputsHash: gateInputsHash(invocation, artifacts),
839
912
  cacheInputs: {
913
+ invocation,
840
914
  environmentHash: invocation?.environmentHash ?? null,
841
915
  artifacts,
842
916
  },
843
917
  }
844
918
  : {}),
845
- }, reserveMs))[0];
846
- let result = { ...observed, index, binding };
919
+ }, reserveMs, binding))[0];
920
+ let result = {
921
+ ...observed,
922
+ index,
923
+ binding: observed.binding ?? binding,
924
+ };
925
+ if (observed.source === 'executed' && binding.tree) {
926
+ const afterTree = captureTreeBinding(gateRoot, invocation, artifacts);
927
+ binding.tree.clean =
928
+ binding.tree.clean &&
929
+ afterTree?.clean === true &&
930
+ afterTree.headSha === binding.tree.headSha &&
931
+ afterTree.treeHash === binding.tree.treeHash;
932
+ }
847
933
  // T13525: a cache-only run must not wipe a stored pass that still proves
848
934
  // this exact gate on these exact inputs (a commit moved HEAD, which keys
849
935
  // the cache, but changed nothing the gate reads).
850
936
  if (result.errorMessage?.startsWith(GATE_NOT_CACHED_PREFIX)) {
851
- const reused = reusableStoredPass(options.priorResults, index, gate, binding);
937
+ const reused = reusableStoredPass(options.priorResults, index, gate, binding, snapshot, gateRoot, root);
852
938
  if (reused)
853
939
  result = reused;
854
940
  }
@@ -878,7 +964,7 @@ export async function runTaskGates(task, criteria, options) {
878
964
  * hash, gate definition hash, invocation and input bytes (T13525). Marked
879
965
  * `source: 'cache'` with the original capture time, like a cache hit.
880
966
  */
881
- function reusableStoredPass(prior, index, gate, binding) {
967
+ function reusableStoredPass(prior, index, gate, binding, task, tree, projectRoot) {
882
968
  const stored = prior?.find((r) => r.index === index);
883
969
  const was = stored?.binding;
884
970
  if (!stored ||
@@ -893,12 +979,26 @@ function reusableStoredPass(prior, index, gate, binding) {
893
979
  !isDeepStrictEqual(was.invocation, binding.invocation) ||
894
980
  !isDeepStrictEqual(was.artifacts, binding.artifacts))
895
981
  return null;
982
+ const mergeSha = mergedGateCommit(tree);
983
+ if (mergeSha) {
984
+ if (!was.tree)
985
+ return null;
986
+ try {
987
+ assertTreeEquivalent(task, gate.req ?? String(index), was.tree, tree, projectRoot, binding.invocation, binding.artifacts);
988
+ }
989
+ catch {
990
+ return null;
991
+ }
992
+ }
896
993
  const { binding: _old, source: _source, cachedAt: _cachedAt, ...observation } = stored;
897
994
  // Re-dated to now, as a cache hit is: a bound result may not precede its capture.
898
995
  return {
899
996
  ...observation,
900
997
  index,
901
- binding,
998
+ binding: {
999
+ ...binding,
1000
+ ...(was.tree ? { tree: { ...was.tree, ...(mergeSha ? { mergeSha } : {}) } } : {}),
1001
+ },
902
1002
  checkedAt: new Date().toISOString(),
903
1003
  source: 'cache',
904
1004
  cachedAt: was.capturedAt,
@@ -1114,6 +1214,13 @@ async function revalidateTypedResult(scope, index, gate) {
1114
1214
  const invocation = resolved && binding.invocation && !binding.invocation.environmentKeys
1115
1215
  ? legacyInvocation(gate, resolved, env)
1116
1216
  : resolved;
1217
+ if (mergedGateCommit(tree) && isCacheableGate(gate)) {
1218
+ if (!binding.tree)
1219
+ // @sync-invariant none:input-shape legacy receipts without a captured tree cannot prove the merge tree
1220
+ throw new TypedRevalidationError(`Typed requirement ${gate.req ?? index} has no clean-tree proof; re-run verification to migrate the stored pass`, mergedGateVerifyCommand(task.id, root, mergedGateCommit(tree), gate.req));
1221
+ assertTreeEquivalent(task, gate.req ?? String(index), binding.tree, tree, root, invocation, artifacts);
1222
+ return;
1223
+ }
1117
1224
  if (isDeepStrictEqual(binding.invocation, invocation) &&
1118
1225
  isDeepStrictEqual(binding.artifacts, artifacts))
1119
1226
  return;
@@ -1126,7 +1233,7 @@ async function revalidateTypedResult(scope, index, gate) {
1126
1233
  return;
1127
1234
  }
1128
1235
  // @sync-invariant none:input-shape a typed result whose inputs moved in its own tree is refused before the completion write; nothing is written
1129
- throw new TypedRevalidationError(`Typed requirement ${label} ${describeTypedDrift(binding, invocation, artifacts, tree)}`, rebindCommand(task, tree));
1236
+ throw new TypedRevalidationError(`Typed requirement ${label} ${binding.artifacts.length < artifacts.length ? 'input inventory predates test-file capture; re-run verification to migrate the stored pass' : describeTypedDrift(binding, invocation, artifacts, tree)}`, rebindCommand(task, tree));
1130
1237
  }
1131
1238
  /**
1132
1239
  * Open a revalidation scope over `task`'s typed results, or throw when its
@@ -1600,6 +1707,33 @@ async function interpreterScript(command, args, cwd) {
1600
1707
  notInputs.add(index);
1601
1708
  return { script: undefined, notInputs, base, flagFiles };
1602
1709
  }
1710
+ /** Read a tracked input from the immutable merge tree; untracked harnesses retain live checks. */
1711
+ function snapshotMergedInput(root, commit, path, execution) {
1712
+ const rel = relative(root, path);
1713
+ const listed = gitOut(root, ['ls-tree', '-z', commit, '--', `:(literal)${rel}`]);
1714
+ if (listed === null)
1715
+ // @sync-invariant none:input-shape an unreadable merge tree cannot establish typed gate inputs
1716
+ throw new Error(`Cannot read typed input ${rel} at merge commit ${commit}`);
1717
+ if (listed === '') {
1718
+ return gitOut(root, ['ls-files', '--error-unmatch', '--', `:(literal)${rel}`]) === null
1719
+ ? undefined
1720
+ : { path, sha256: null, bytes: null };
1721
+ }
1722
+ const blob = /^100(?:644|755) blob ([a-f0-9]{40})\t/.exec(listed)?.[1];
1723
+ if (!blob)
1724
+ // @sync-invariant none:input-shape a merge-tree input must be an unambiguous regular file
1725
+ throw new Error(`Typed input is not a regular file at merge commit ${commit}: ${rel}`);
1726
+ const ceiling = execution.resources.maxBytes ?? 1_048_576;
1727
+ const bytes = execFileSync('git', ['cat-file', 'blob', blob], {
1728
+ cwd: root,
1729
+ env: discoveryEnv(),
1730
+ maxBuffer: ceiling,
1731
+ stdio: ['ignore', 'pipe', 'ignore'],
1732
+ });
1733
+ execution.assertActive();
1734
+ execution.consume({ bytes: bytes.length });
1735
+ return { path, sha256: createHash('sha256').update(bytes).digest('hex'), bytes: bytes.length };
1736
+ }
1603
1737
  /** Capture declared task inputs and an interpreter's explicit harness argument. */
1604
1738
  async function snapshotGateInputs(task, gate, invocation, execution,
1605
1739
  /** T12625: the tree the gate runs in ({@link resolveTypedGateRoot}). */
@@ -1616,6 +1750,20 @@ treeRoot = resolve(execution.identity.projectRoot)) {
1616
1750
  // T13690: a declared task file is a literal path; `app/[id]/page.tsx` is a
1617
1751
  // Next.js route, not a glob. Only paths from other sources are refused.
1618
1752
  const literal = new Set(paths);
1753
+ // A targeted package-manager test command names its input just as an interpreter does.
1754
+ for (const arg of invocation?.args ?? []) {
1755
+ if (arg.startsWith('-') || !/\.(?:test|spec)\.[cm]?[jt]sx?$/.test(arg))
1756
+ continue;
1757
+ const path = resolve(invocation.cwd, arg);
1758
+ if (/[?*[\]{}]/.test(arg) && !existsSync(path)) {
1759
+ const mergeSha = mergedGateCommit(root);
1760
+ if (!mergeSha ||
1761
+ gitOut(root, ['cat-file', '-e', `${mergeSha}:${relative(root, path)}`]) === null)
1762
+ continue;
1763
+ }
1764
+ paths.add(path);
1765
+ literal.add(path);
1766
+ }
1619
1767
  if (gate.kind === 'file' && gate.path)
1620
1768
  paths.add(resolve(root, gate.path));
1621
1769
  if (invocation &&
@@ -1647,6 +1795,14 @@ treeRoot = resolve(execution.identity.projectRoot)) {
1647
1795
  const rel = relative(root, path);
1648
1796
  if (!rel || rel === '..' || rel.startsWith('../') || isAbsolute(rel))
1649
1797
  throw new Error(`Typed input escapes the captured project: ${path}`);
1798
+ const mergeCommit = isCacheableGate(gate) ? mergedGateCommit(root) : undefined;
1799
+ if (mergeCommit) {
1800
+ const merged = snapshotMergedInput(root, mergeCommit, path, execution);
1801
+ if (merged) {
1802
+ artifacts.push(merged);
1803
+ continue;
1804
+ }
1805
+ }
1650
1806
  // Refuse redirected parents even for absent files; absence must belong to this project.
1651
1807
  let parent = dirname(path);
1652
1808
  for (;;) {