@ngockhoale/ukit 3.4.73 → 3.4.75

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 (28) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/manifests/documentation.yaml +10 -0
  3. package/manifests/platform.full.yaml +15 -0
  4. package/package.json +4 -1
  5. package/template_project/.claude/commands/ukit/handoff-fullstack.md +34 -12
  6. package/template_project/.claude/hooks/completion-gate.sh +10 -1
  7. package/template_project/.claude/hooks/handoff-resume.sh +38 -53
  8. package/template_project/.claude/hooks/owner-stop-gate.mjs +41 -0
  9. package/template_project/.claude/hooks/skill-router.sh +473 -36
  10. package/template_project/.claude/hooks/verification-guard.sh +8 -1
  11. package/template_project/.claude/settings.json +33 -1
  12. package/template_project/.claude/ukit/index/publication-intent.mjs +128 -13
  13. package/template_project/.claude/ukit/index/route-task.mjs +124 -26
  14. package/template_project/.claude/ukit/runtime/block-breaker.mjs +1 -0
  15. package/template_project/.claude/ukit/runtime/compact-threshold.mjs +8 -1
  16. package/template_project/.claude/ukit/runtime/cron-operation-adapter.mjs +14 -5
  17. package/template_project/.claude/ukit/runtime/execution-ledger.mjs +399 -35
  18. package/template_project/.claude/ukit/runtime/handoff-intent.mjs +5 -0
  19. package/template_project/.claude/ukit/runtime/handoff-provenance.mjs +277 -0
  20. package/template_project/.claude/ukit/runtime/loop-state.mjs +23 -4
  21. package/template_project/.claude/ukit/runtime/operation-evidence.mjs +9 -0
  22. package/template_project/.claude/ukit/runtime/reinject-context.mjs +10 -0
  23. package/template_project/.claude/ukit/runtime/resumable-run.mjs +33 -11
  24. package/template_project/.claude/ukit/runtime/stop-coordinator.mjs +284 -58
  25. package/template_project/.omp/hooks/pre/ukit-bridge.js +171 -3
  26. package/scripts/dev/worktree-preflight.mjs +0 -166
  27. package/scripts/measure-decision-gateway.mjs +0 -306
  28. package/scripts/probe/codex-capability-probe.mjs +0 -169
@@ -315,12 +315,41 @@ export async function readRouteState(projectRoot, payload = {}) {
315
315
  // The shared file is single-slot: with no shared file there is still a per-session record.
316
316
  return sessionId ? readSessionRouteState(projectRoot, sessionId) : state;
317
317
  }
318
- if (stateSessionId === sessionId) return state;
318
+ if (stateSessionId === sessionId) {
319
+ const sidecar = await readSessionRouteState(projectRoot, sessionId);
320
+ // A pending marker means a publication was in flight and never committed, whether or not the shared
321
+ // document carries a revision. A legacy shared document (no revision) otherwise has no metadata to check.
322
+ if (sidecar?.routePublicationIncomplete) return { sessionId, routePublicationIncomplete: true };
323
+ if (state.routePersistenceRevision && (!sidecar || sidecar.routePersistenceRevision !== state.routePersistenceRevision)) {
324
+ return { sessionId, routePublicationIncomplete: true };
325
+ }
326
+ return state;
327
+ }
319
328
  // Shared file missing an owner or owned by another session (a concurrent session routed
320
329
  // after this one): recover this session's own record instead of declaring the route lost.
321
330
  return readSessionRouteState(projectRoot, sessionId);
322
331
  }
323
332
 
333
+ export function ownerStopActive(state, payload = {}) {
334
+ const control = state?.ownerControl;
335
+ if (!control || control.kind !== 'stop') return false;
336
+ const sessionId = explicitSessionId(payload);
337
+ const owner = explicitSessionId(control) || explicitSessionId(state || {});
338
+ return Boolean(sessionId && owner && sessionId === owner);
339
+ }
340
+
341
+ export async function ownerStopGovernsStart(projectRoot, sessionIds = []) {
342
+ const ids = [...new Set((Array.isArray(sessionIds) ? sessionIds : [sessionIds])
343
+ .filter((v) => typeof v === 'string' && v.trim()).map((v) => v.trim()))];
344
+ for (const id of ids) {
345
+ const probe = { session_id: id };
346
+ const raw = await readJson(path.join(projectRoot, '.ukit', 'storage', 'cache', 'route-state', `${safeSegment(id)}.json`), null);
347
+ if (raw && ownerStopActive(raw, probe)) return true;
348
+ if (ownerStopActive(await readRouteState(projectRoot, probe), probe)) return true;
349
+ }
350
+ return false;
351
+ }
352
+
324
353
  // Per-session route-state sidecar (written by skill-router.sh and route-task.mjs next to the
325
354
  // shared single-slot file). Owner is re-verified from the embedded sessionId, so a misfiled or
326
355
  // tampered record can never be adopted by another session.
@@ -331,7 +360,9 @@ export async function readSessionRouteState(projectRoot, sessionId) {
331
360
  path.join(projectRoot, '.ukit', 'storage', 'cache', 'route-state', `${safeSegment(id)}.json`),
332
361
  null,
333
362
  );
334
- return state && explicitSessionId(state) === id ? state : null;
363
+ if (!state || explicitSessionId(state) !== id) return null;
364
+ if (state.routePublicationIncomplete === true) return { sessionId: id, routePublicationIncomplete: true };
365
+ return state;
335
366
  }
336
367
 
337
368
  export async function readExecutionLedger(projectRoot, payload = {}) {
@@ -383,7 +414,7 @@ export function hasUnfinishedCompletion(state = {}, ledger = {}, { cwd } = {}) {
383
414
  // TASK-009 (BL-011): a bug-fix route is also unfinished while its floor is
384
415
  // missing — the generic evidence alone never releases a bug fix.
385
416
  if (state?.routeSummary?.playbookId === BUGFIX_PLAYBOOK_ID) {
386
- return bugFixFloorMissing(bugFixFloorStatus(ledger, BUGFIX_PLAYBOOK_ID)).length > 0;
417
+ return bugFixFloorMissing(bugFixFloorStatus(ledger, BUGFIX_PLAYBOOK_ID, cwd)).length > 0;
387
418
  }
388
419
  return false;
389
420
  }
@@ -671,6 +702,45 @@ function extractExitCode(payload = {}) {
671
702
  return null;
672
703
  }
673
704
 
705
+ const SHELL_BODY_CONSUMERS = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh', 'ash', 'source', '.', 'eval', 'xargs', 'sudo', 'exec', 'nohup', 'time', 'command', ['e', 'nv'].join('')]);
706
+
707
+ function withoutInertHeredocBodies(command) {
708
+ const text = String(command || '');
709
+ if (!text.includes('<<')) return text;
710
+ const lines = text.split('\n');
711
+ const out = [];
712
+ for (let i = 0; i < lines.length; i += 1) {
713
+ const line = lines[i];
714
+ out.push(line);
715
+ const heredocs = [];
716
+ for (const m of line.matchAll(/<<(-?)[ \t]*(?:(['"])([^'"\n]+)\2|([A-Za-z_][A-Za-z0-9_]*))/g)) {
717
+ if (line[m.index - 1] === '<' || line[m.index + 2] === '<' || insideQuote(line, m.index)) continue;
718
+ heredocs.push({ strip: m[1] === '-', delimiter: m[3] ?? m[4], quoted: Boolean(m[2]), index: m.index });
719
+ }
720
+ if (!heredocs.length) continue;
721
+ const words = line.slice(0, heredocs[0].index).split(/\|\||&&|[|;&(]/).pop().trim().split(/\s+/)
722
+ .filter((w) => w && !/^[A-Za-z_][A-Za-z0-9_]*=/.test(w));
723
+ const shellConsumer = SHELL_BODY_CONSUMERS.has((words[0] || '').replace(/^.*\//, ''));
724
+ for (const heredoc of heredocs) {
725
+ const body = [];
726
+ let closed = false;
727
+ while (i + 1 < lines.length) {
728
+ i += 1;
729
+ const candidate = heredoc.strip ? lines[i].replace(/^\t+/, '') : lines[i];
730
+ if (candidate === heredoc.delimiter) { closed = true; break; }
731
+ body.push(lines[i]);
732
+ }
733
+ if (shellConsumer) {
734
+ out.push(...body);
735
+ } else if (!heredoc.quoted) {
736
+ out.push(...(body.join('\n').match(/\$\([^]*?\)|`[^`]*`/g) || []));
737
+ }
738
+ if (closed) out.push(heredoc.delimiter);
739
+ }
740
+ }
741
+ return out.join('\n');
742
+ }
743
+
674
744
  // Recognize runner presence separately from exit proof. A trailing echo of `$?`
675
745
  // can report a status in text but cannot make the wrapper's exit authoritative.
676
746
  // Blank out quoted literals so `echo '(jest passed)'` / `git commit -m "run yarn test"` do not
@@ -712,7 +782,7 @@ function executableSubstitutions(command) {
712
782
  }
713
783
 
714
784
  function isVerificationCommand(command, depth = 0) {
715
- const raw = String(command || '').trim();
785
+ const raw = withoutInertHeredocBodies(command).trim();
716
786
  if (!raw) return false;
717
787
  if (depth < 2) {
718
788
  for (const sub of executableSubstitutions(raw)) {
@@ -769,11 +839,15 @@ function verificationShellUnits(command) {
769
839
  return units.filter((unit) => unit.text || unit.separator !== ';');
770
840
  }
771
841
 
772
- function maskedVerificationStage(command, depth = 0) {
773
- const text = String(command || '').trim();
842
+ function maskedVerificationStage(command, depth = 0, options = {}) {
843
+ const text = withoutInertHeredocBodies(command).trim();
774
844
  if (executableSubstitutions(text).length) return text;
775
845
  const units = verificationShellUnits(text);
776
846
  if (!units?.length || depth > 2) return text;
847
+ const attestedIdx = options?.attested
848
+ ? units.findIndex((u) => u.text && !/^(?:cd|set|export|unset|pushd|popd)(?:\s|$)/.test(u.text)
849
+ && !/^(?:[A-Za-z_][A-Za-z0-9_]*=(?:"[^"]*"|'[^']*'|\S*)\s*)+$/.test(u.text))
850
+ : -1;
777
851
  let pipefail = false;
778
852
  let sawRunner = false;
779
853
  for (let i = 0; i < units.length; i += 1) {
@@ -787,17 +861,18 @@ function maskedVerificationStage(command, depth = 0) {
787
861
  if (/^(?:\[|(?:for|while|until|case|function|done|test|coproc|setsid)\b)/.test(plain)) return unit.text;
788
862
  // A later `exit 0`/`true`/`:` replaces the runner's status; a leading `!` inverts it.
789
863
  if (sawRunner && /^(?:exit\s+0|true|:)$/.test(plain)) return unit.text;
790
- if (/^!\s/.test(plain) && isVerificationCommand(unit.text)) return unit.text;
864
+ if (/^!\s/.test(plain) && (i === attestedIdx || isVerificationCommand(unit.text))) return unit.text;
791
865
  if (unit.separator === '||' || unit.separator === '&') return unit.text;
792
866
  const enable = /^set\s+-(?:[a-z]*o)\s+pipefail$/.test(plain);
793
867
  const disable = /^set\s+\+(?:[a-z]*o)\s+pipefail$/.test(plain);
794
868
  if (enable || disable) pipefail = enable;
795
- let runner = isVerificationCommand(unit.text);
869
+ const knownRunner = isVerificationCommand(unit.text);
870
+ let runner = knownRunner || i === attestedIdx;
796
871
  // Only an entire simple shell wrapper can inherit the inner script's proof.
797
872
  const wrapper = unit.text.match(/^(?:bash|sh|zsh|dash|ksh)\s+(?:-o\s+\w+\s+|-[a-z]+\s+)*(-[a-z]*c)\s+(?:'([^']*)'|"((?:[^"\\]|\\.)*)")$/);
798
- if (runner && wrapper) {
873
+ if (knownRunner && wrapper) {
799
874
  if (maskedVerificationStage(wrapper[2] ?? wrapper[3] ?? '', depth + 1)) return unit.text;
800
- } else if (runner && /(?:^|\s)(?:bash|sh|zsh|dash|ksh)\s/.test(plain)) return unit.text;
875
+ } else if (knownRunner && /(?:^|\s)(?:bash|sh|zsh|dash|ksh)\s/.test(plain)) return unit.text;
801
876
  if (runner) sawRunner = true;
802
877
  if (unit.separator === '|' || unit.separator === '|&') {
803
878
  if (runner && !pipefail) {
@@ -824,14 +899,37 @@ function maskedVerificationStage(command, depth = 0) {
824
899
  // return-code interpretation such as grep's "No matches found") is the host's proof of exit 0. Any other
825
900
  // host, or a response without that exact shape, keeps the fail-closed rule.
826
901
  function hostProvesCleanBashExit(harness, payload, response) {
902
+ if (harness === 'omp') return ompForegroundCleanExit(payload, response);
827
903
  return harness === 'claude-code' && payload?.hook_event_name === 'PostToolUse'
828
904
  && response && typeof response === 'object' && !Array.isArray(response)
829
905
  && response.interrupted === false && !response.backgroundTaskId && !response.returnCodeInterpretation;
830
906
  }
831
907
 
908
+ function ompForegroundCleanExit(payload, response) {
909
+ if (payload?.hook_event_name !== 'PostToolUse') return false;
910
+ const out = payload.tool_output;
911
+ if (!out || typeof out !== 'object' || out.isError !== false) return false;
912
+ const details = out.details;
913
+ if (!details || typeof details !== 'object' || Array.isArray(details)) return false;
914
+ if (details.async || ompAsyncRunning(details) || ompAsyncRunning(response)) return false;
915
+ if (EXIT_FIELDS.some((f) => Object.hasOwn(details, f) || Object.hasOwn(out, f) && out[f] !== undefined)) return false;
916
+ if (response && typeof response === 'object' && (response.backgroundTaskId || isBackgroundLaunchAck(response))) return false;
917
+ return true;
918
+ }
919
+
920
+ function ompAsyncRunning(response) {
921
+ const info = response?.async ?? response?.details?.async;
922
+ return info && typeof info === 'object' && info.state === 'running' ? (String(info.jobId || '') || 'omp-async') : null;
923
+ }
924
+
925
+ function isOmpBackgroundId(id) {
926
+ return typeof id === 'string' && (/^bg_\d+$/.test(id) || id === 'omp-async');
927
+ }
928
+
832
929
  function isBackgroundLaunchAck(response) {
833
930
  if (response && typeof response === 'object' && !Array.isArray(response)) {
834
931
  if (typeof response.backgroundTaskId === 'string' && response.backgroundTaskId) return true;
932
+ if (ompAsyncRunning(response)) return true;
835
933
  if (response.exitCode !== undefined && response.exitCode !== null) return false;
836
934
  return isBackgroundLaunchAck(response.stdout ?? response.output ?? response.content);
837
935
  }
@@ -843,6 +941,8 @@ function isBackgroundLaunchAck(response) {
843
941
  function backgroundTaskIdOf(response) {
844
942
  if (response && typeof response === 'object' && !Array.isArray(response)) {
845
943
  if (typeof response.backgroundTaskId === 'string' && response.backgroundTaskId) return response.backgroundTaskId;
944
+ const job = ompAsyncRunning(response);
945
+ if (job) return job;
846
946
  return backgroundTaskIdOf(response.stdout ?? response.output ?? response.content);
847
947
  }
848
948
  const m = typeof response === 'string' ? /^\s*Command running in background with ID: ([A-Za-z0-9_-]+)/.exec(response) : null;
@@ -906,11 +1006,13 @@ async function backgroundCompletionFor({ projectRoot, payload, toolInput, toolRe
906
1006
  try { mtime = fsSync.statSync(file).mtimeMs; } catch { return { rejected: 'output-file-missing' }; }
907
1007
  if (mtime + 2000 < launch.ts) return { rejected: 'output-predates-launch' };
908
1008
  const exitCode = Number(footer[1]);
909
- const success = exitCode === 0;
1009
+ const masked = Boolean(maskedVerificationStage(launch.command));
1010
+ const success = exitCode === 0 && !masked;
910
1011
  const lv = launch.verdict || {};
911
- const kind = success ? (isTestGateCommand(launch.command) ? 'test-verified' : 'check-only') : 'failed';
1012
+ const kind = masked ? 'unproven' : success ? (isTestGateCommand(launch.command) ? 'test-verified' : 'check-only') : 'failed';
912
1013
  return {
913
1014
  kind: 'verification', command: launch.command, success, exitCode, backgroundCompletion: id,
1015
+ ...(masked ? { exitStatusUnproven: true } : {}),
914
1016
  ...(launch.scope ? { scope: launch.scope } : {}),
915
1017
  ...(launch.workspaceFp ? { workspaceFp: launch.workspaceFp } : {}),
916
1018
  verdict: { ...lv, kind, evidence: launch.command, verifier: lv.verifier || 'self', ts: new Date().toISOString() },
@@ -934,7 +1036,7 @@ function compactReceipt(receipt) {
934
1036
  kind: receipt.kind,
935
1037
  success: receipt.success,
936
1038
  };
937
- for (const key of ['toolName', 'toolUseId', 'file', 'command', 'exitCode', 'scope', 'error', 'verdict', 'evidence', 'evidenceSurface', 'class', 'status', 'detail', 'operation', 'transportSuccess', 'taskInstanceId', 'sessionKey', 'sequence', 'exitStatusUnproven', 'backgroundTaskId', 'backgroundCompletion', 'agentId', 'agentType', 'contentSha']) {
1039
+ for (const key of ['toolName', 'toolUseId', 'file', 'command', 'exitCode', 'exitProof', 'scope', 'error', 'verdict', 'evidence', 'evidenceSurface', 'class', 'status', 'detail', 'operation', 'transportSuccess', 'taskInstanceId', 'sessionKey', 'sequence', 'exitStatusUnproven', 'backgroundTaskId', 'backgroundCompletion', 'agentId', 'agentType', 'contentSha']) {
938
1040
  if (receipt[key] !== undefined && receipt[key] !== null && receipt[key] !== '') {
939
1041
  compact[key] = key === 'operation' ? compactOperation(receipt[key]) : receipt[key];
940
1042
  }
@@ -1538,9 +1640,13 @@ function carriedEvidenceLedger(fresh, current) {
1538
1640
  }
1539
1641
  return {
1540
1642
  ...fresh,
1643
+ taskStartedAt: Number.isFinite(current.taskStartedAt) ? current.taskStartedAt : (fresh.taskStartedAt ?? null),
1644
+ parentSessionId: current.parentSessionId || fresh.parentSessionId || null,
1541
1645
  operationBank: current.operationBank || {},
1542
1646
  receiptSequence: current.receiptSequence || 0,
1543
1647
  sourceSucceeded: fresh.sourceSucceeded || current.sourceSucceeded === true,
1648
+ stateObserved: fresh.stateObserved === true || current.stateObserved === true,
1649
+ stateProof: mergeStateProof(fresh.stateProof, current.stateProof),
1544
1650
  // targeted-verification evidence (2.3.0) must survive the same re-key carry as the
1545
1651
  // coarse flags, or the stricter gates re-demand evidence mid-request — the exact
1546
1652
  // stall this carry exists to prevent.
@@ -1638,6 +1744,8 @@ function freshLedger(payload, routeState, harness) {
1638
1744
  sessionKey: sessionIdentity(payload),
1639
1745
  sessionId: payload.session_id || payload.sessionId || null,
1640
1746
  transcriptPath: payload.transcript_path || payload.transcriptPath || null,
1747
+ parentSessionId: typeof payload.ukit_parent_session_id === 'string' && payload.ukit_parent_session_id
1748
+ ? safeSegment(payload.ukit_parent_session_id) : null,
1641
1749
  harness,
1642
1750
  requestKey: routeState?.requestKey || null,
1643
1751
  promptKey: evidencePromptKey(routeState),
@@ -1660,6 +1768,8 @@ function freshLedger(payload, routeState, harness) {
1660
1768
  taskType: null,
1661
1769
  playbookTrace: null,
1662
1770
  sourceSucceeded: false,
1771
+ stateObserved: false,
1772
+ stateProof: null,
1663
1773
  sourceFiles: [],
1664
1774
  writeAttempted: false,
1665
1775
  writeSucceeded: false,
@@ -1685,6 +1795,7 @@ function freshLedger(payload, routeState, harness) {
1685
1795
  // Emitted-once for INTERRUPTED survives re-keys via carriedEvidenceLedger.
1686
1796
  outcomes: [],
1687
1797
  startedAt: Date.now(),
1798
+ taskStartedAt: Date.now(),
1688
1799
  updatedAt: Date.now(),
1689
1800
  };
1690
1801
  }
@@ -1699,7 +1810,7 @@ const MAX_JOURNAL_SEEN = 64;
1699
1810
  const MAX_JOURNAL_RECORDS = 128;
1700
1811
  const MAX_JOURNAL_QUARANTINE_LINES = 32;
1701
1812
  const LEDGER_EVENT_TYPES = new Set(['receipt', 'continuation', 'notified', 'stop-progress', 'resumable-run']);
1702
- const RECEIPT_KINDS = new Set(['source', 'write', 'verification', 'playbook-finding', 'workspace', 'operation', 'handback', 'review', 'delegation-violation']);
1813
+ const RECEIPT_KINDS = new Set(['source', 'state', 'write', 'verification', 'playbook-finding', 'workspace', 'operation', 'handback', 'review', 'delegation-violation']);
1703
1814
 
1704
1815
  function journalPathFor(target) {
1705
1816
  return `${target}.journal`;
@@ -1840,7 +1951,7 @@ function newEventId() {
1840
1951
  return `${Date.now().toString(36)}-${crypto.randomBytes(8).toString('hex')}`;
1841
1952
  }
1842
1953
 
1843
- const JOURNAL_RECEIPT_FIELDS = ['ts', 'kind', 'toolName', 'toolUseId', 'success', 'exitCode', 'file', 'command', 'scope', 'workspaceFp', 'workspaceRoot', 'workspaceHeadTs', 'bashReadOnly', 'exitStatusUnproven', 'backgroundTaskId', 'backgroundCompletion', 'detail', 'operation', 'transportSuccess', 'taskInstanceId', 'sessionKey', 'sequence', 'agentId', 'agentType', 'contentSha', 'handback', 'review', 'verdict'];
1954
+ const JOURNAL_RECEIPT_FIELDS = ['ts', 'kind', 'toolName', 'toolUseId', 'success', 'exitCode', 'exitProof', 'file', 'command', 'scope', 'workspaceFp', 'workspaceRoot', 'workspaceHeadTs', 'bashReadOnly', 'exitStatusUnproven', 'backgroundTaskId', 'backgroundCompletion', 'detail', 'operation', 'transportSuccess', 'taskInstanceId', 'sessionKey', 'sequence', 'agentId', 'agentType', 'contentSha', 'handback', 'review', 'verdict'];
1844
1955
 
1845
1956
  // TASK-009 (BL-011): evidence attestations are whitelisted verbatim — class /
1846
1957
  // surface / result / claim, the ARCH §Evidence Schema fields a receipt may
@@ -2371,6 +2482,8 @@ function bugFixReceiptClass(receipt, floor, failureCounts = {}, playbookId = nul
2371
2482
  if (playbookId !== BUGFIX_PLAYBOOK_ID || receipt?.kind !== 'verification' || receipt?.evidence) {
2372
2483
  return null;
2373
2484
  }
2485
+ if (receipt.exitStatusUnproven === true || receipt.backgroundTaskId) return null;
2486
+
2374
2487
  if (receipt.success === true) {
2375
2488
  const surface = bugFixReceiptSurface(receipt);
2376
2489
  if (
@@ -2436,8 +2549,13 @@ function foldBugFixReceipt(floor, receipt, playbookId = null, failureCounts = {}
2436
2549
  // window are folded through the same rules so a fixture ledger that never ran
2437
2550
  // recordExecutionReceipt (no bank) is judged identically. Per-surface failure
2438
2551
  // counts are rebuilt by walking the window in order.
2439
- function bugFixFloorStatus(ledger = {}, playbookId = null) {
2552
+ function bugFixFloorStatus(ledger = {}, playbookId = null, cwd = null) {
2440
2553
  const floor = ledger.bugFixFloor || emptyBugFixFloor();
2554
+ const delegated = cwd && playbookId === BUGFIX_PLAYBOOK_ID ? delegatedVerificationReceipts(ledger, cwd) : [];
2555
+ if (delegated.length > 0) {
2556
+ const own = Array.isArray(ledger.receipts) ? ledger.receipts : [];
2557
+ ledger = { ...ledger, receipts: [...own, ...delegated].sort((a, b) => (a.ts || 0) - (b.ts || 0)) };
2558
+ }
2441
2559
  const counts = {};
2442
2560
  let merged = {
2443
2561
  ...floor,
@@ -2559,12 +2677,17 @@ function applyReceiptCore(ledger, receipt, { vibecode = false, projectRoot } = {
2559
2677
  return { ledger: next, value: null };
2560
2678
  }
2561
2679
  if (receipt.kind === 'operation') receipt = { ...receipt, sequence: next.receiptSequence };
2680
+ if (receipt.kind === 'operation' && receipt.success === true && receipt.operation?.scope) next.stateObserved = true;
2681
+ if (receipt.kind === 'operation' && receipt.success === true && receipt.operation?.scope) next.stateProof = foldStateProof(next.stateProof, { role: receipt.toolName === 'CronDelete' ? 'stop' : 'observe', terminal: false, targets: receipt.operation?.target ? [String(receipt.operation.target).toLowerCase()] : [] }, next.receiptSequence);
2562
2682
  if (receipt.kind === 'operation') {
2563
2683
  next.operationBank = foldOperationEvidence(ledger.operationBank, receipt, ledger);
2564
2684
  }
2565
2685
  if (receipt.releasePreflight) next.releasePreflight = { ...receipt.releasePreflight, sequence: next.receiptSequence };
2566
2686
  if (receipt.kind === 'write' && receipt.success) next.releasePreflight = null;
2567
- if (receipt.kind === 'source') {
2687
+ if (receipt.kind === 'state') {
2688
+ next.stateObserved = next.stateObserved === true || receipt.success === true;
2689
+ if (receipt.success === true) next.stateProof = foldStateProof(next.stateProof, receipt, next.receiptSequence);
2690
+ } else if (receipt.kind === 'source') {
2568
2691
  next.sourceSucceeded = next.sourceSucceeded || receipt.success;
2569
2692
  if (receipt.success && receipt.file) {
2570
2693
  next.sourceFiles = [...new Set([...(next.sourceFiles || []), receipt.file])].slice(-MAX_SOURCE_FILES);
@@ -3242,7 +3365,7 @@ export async function recordExecutionReceipt({
3242
3365
  const operationReceipt = backgroundLaunchAck ? null : cronOperationReceipt(toolName, toolInput, toolResponse, success, { sessionId: explicitSessionId(payload), harness })
3243
3366
  || (toolName === 'Bash' && !bashScope.foreign
3244
3367
  ? (bashOperationReceipt(toolInput.command, toolResponse, success, nativeGoal, { sessionId: explicitSessionId(payload), harness })
3245
- || releaseOperationReceipt(toolInput.command, toolResponse, success, { sessionId: explicitSessionId(payload), harness }))
3368
+ || releaseOperationReceipt(toolInput.command, toolResponse, success, { sessionId: explicitSessionId(payload), harness, candidate: cleanTreeCandidate(projectRoot) }))
3246
3369
  : null);
3247
3370
  if (bgCompletion && !bgCompletion.rejected) {
3248
3371
  Object.assign(receipt, bgCompletion);
@@ -3256,6 +3379,11 @@ export async function recordExecutionReceipt({
3256
3379
  receipt.exitStatusUnproven = true;
3257
3380
  receipt.success = false;
3258
3381
  }
3382
+ } else if (routeState?.routeSummary?.executionContract?.stateVerification === true
3383
+ && (STATE_OBSERVATION_TOOLS.has(toolName) || (toolName === 'Bash' && !bashScope.foreign && !isVerificationCommand(toolInput.command)))) {
3384
+ receipt.kind = 'state';
3385
+ receipt.command = String(toolInput.command || toolInput.task_id || toolInput.shell_id || '').slice(0, 200);
3386
+ Object.assign(receipt, stateReceiptShape(toolName, toolInput, toolResponse, routeState.routeSummary.executionContract));
3259
3387
  } else if (toolName === 'Read' || toolName === 'Grep' || toolName === 'Glob') {
3260
3388
  receipt.kind = 'source';
3261
3389
  receipt.file = toolInput.file_path || toolInput.path || null;
@@ -3281,13 +3409,20 @@ export async function recordExecutionReceipt({
3281
3409
  receipt.sessionKey = sessionIdentity(payload);
3282
3410
  receipt.command = String(toolInput.command || '').trim();
3283
3411
  // A pipe-masked runner status (exit 0 from `| tail`) is not evidence of a pass.
3284
- const maskedStage = isVerificationCommand(toolInput.command) ? maskedVerificationStage(toolInput.command) : null;
3412
+ const recognizedRunner = isVerificationCommand(toolInput.command);
3413
+ const attestedProgram = Boolean(evidence) && !recognizedRunner;
3414
+ const maskedStage = recognizedRunner || attestedProgram
3415
+ ? maskedVerificationStage(toolInput.command, 0, { attested: attestedProgram }) : null;
3285
3416
  if (backgroundLaunchAck) receipt.backgroundTaskId = backgroundTaskIdOf(toolResponse);
3417
+ if (!backgroundLaunchAck && receipt.success) {
3418
+ if (exitCode === 0) receipt.exitProof = 'native-exit';
3419
+ else if (exitCode === null && hostProvesCleanBashExit(harness, payload, toolResponse)) receipt.exitProof = 'host-contract';
3420
+ }
3286
3421
  if (backgroundLaunchAck && receipt.success) {
3287
3422
  receipt.success = false;
3288
3423
  receipt.exitStatusUnproven = true;
3289
3424
  if (ledgerMessageEmitter) {
3290
- try { ledgerMessageEmitter(`${JSON.stringify({ systemMessage: `UKit execution-ledger: background verification ${receipt.backgroundTaskId || '(unknown id)'} is pending. Wait for the same job; do not launch a duplicate. After the host task-notification, Read its tasks/<id>.output through the final exit footer to ingest completion; Bash/grep does not ingest it.` })}\n`); } catch { /* advisory */ }
3425
+ try { ledgerMessageEmitter(`${JSON.stringify({ systemMessage: isOmpBackgroundId(receipt.backgroundTaskId) ? `UKit execution-ledger: UNSUPPORTED_EVIDENCE — omp job ${receipt.backgroundTaskId} has no exit status and cannot count as a pass; run the verification once in the foreground (async:false) for a native exit.` : `UKit execution-ledger: background verification ${receipt.backgroundTaskId || '(unknown id)'} is pending. Wait for the same job; do not launch a duplicate. After the host task-notification, Read its tasks/<id>.output through the final exit footer to ingest completion; Bash/grep does not ingest it.` })}\n`); } catch { /* advisory */ }
3291
3426
  }
3292
3427
  } else if (maskedStage && receipt.success) {
3293
3428
  receipt.success = false;
@@ -3313,7 +3448,7 @@ export async function recordExecutionReceipt({
3313
3448
  // SPEC-typed-verdicts §2.1: every verification receipt mints a typed verdict record
3314
3449
  // (kind/evidence/verifier/headSha/baseSha/patchId/ts). Explicit payload.verdict
3315
3450
  // fields win so a hook or subagent verifier can attest its own kind and identity.
3316
- if (isVerificationCommand(toolInput.command)) {
3451
+ if (recognizedRunner || (attestedProgram && receipt.exitStatusUnproven === true)) {
3317
3452
  receipt.verdict = mintVerificationVerdict(receipt, payload, workspaceRoot, projectRoot);
3318
3453
  }
3319
3454
  } else if (toolName === 'Bash' && workspaceFp) {
@@ -3352,6 +3487,11 @@ export async function recordExecutionReceipt({
3352
3487
  }
3353
3488
  }
3354
3489
  }
3490
+ if (receipt.kind === 'write' && receipt.success && typeof receipt.file === 'string' && !receipt.contentSha
3491
+ && typeof payload.ukit_parent_session_id === 'string' && payload.ukit_parent_session_id) {
3492
+ const digest = fileContentSha(path.resolve(projectRoot, receipt.file));
3493
+ if (digest) receipt.contentSha = digest;
3494
+ }
3355
3495
  if (workspaceFp) {
3356
3496
  // A background completion is judged against the tree that was tested at LAUNCH, never today's tree.
3357
3497
  receipt.workspaceFp = bgCompletion && !bgCompletion.rejected && bgCompletion.workspaceFp ? bgCompletion.workspaceFp : workspaceFp;
@@ -3454,8 +3594,190 @@ function requiredEvidence(state = {}) {
3454
3594
  return [...new Set(required)];
3455
3595
  }
3456
3596
 
3597
+ function hardExpectedSourceFiles(routeSummary = {}) {
3598
+ const expected = Array.isArray(routeSummary?.expectedSourceFiles) ? routeSummary.expectedSourceFiles : [];
3599
+ const provenance = routeSummary?.expectedSourceProvenance;
3600
+ if (!Array.isArray(provenance) || expected.length === 0) return expected;
3601
+ const guesses = new Set(provenance.filter((e) => e && e.source === 'index-guess' && typeof e.file === 'string').map((e) => e.file));
3602
+ return guesses.size === 0 ? expected : expected.filter((file) => !guesses.has(file));
3603
+ }
3604
+
3605
+ function delegatedChildLedgers(ledger = {}, cwd) {
3606
+ const parentId = ledger?.sessionId;
3607
+ const since = ledger?.taskStartedAt;
3608
+ if (!cwd || !parentId || !Number.isFinite(since)) return [];
3609
+ const dir = path.join(cwd, '.ukit', 'storage', 'cache', 'exec-ledger');
3610
+ let names;
3611
+ try {
3612
+ names = fsSync.readdirSync(dir).filter((n) => n.endsWith('.json'))
3613
+ .map((n) => { let t = 0; try { t = fsSync.statSync(path.join(dir, n)).mtimeMs; } catch { /* ignore */ } return [n, t]; })
3614
+ .sort((a, b) => b[1] - a[1]).slice(0, 256).map((e) => e[0]);
3615
+ } catch { return []; }
3616
+ const children = [];
3617
+ for (const name of names) {
3618
+ let child;
3619
+ try {
3620
+ const full = path.join(dir, name);
3621
+ if (fsSync.statSync(full).size > 4 * 1024 * 1024) continue;
3622
+ child = JSON.parse(fsSync.readFileSync(full, 'utf8'));
3623
+ } catch { continue; }
3624
+ if (!child || child.sessionId === parentId || child.parentSessionId !== safeSegment(parentId)) continue;
3625
+ children.push(child);
3626
+ }
3627
+ return children;
3628
+ }
3629
+
3630
+ function delegatedVerificationReceipts(ledger = {}, cwd) {
3631
+ const since = ledger?.taskStartedAt;
3632
+ const out = [];
3633
+ for (const child of delegatedChildLedgers(ledger, cwd)) {
3634
+ const writtenAt = delegatedWriteTimes(ledger, cwd, [child]);
3635
+ if (!writtenAt.length) continue;
3636
+ const revisionAt = Math.max(...writtenAt.map((w) => w.ts));
3637
+ for (const r of Array.isArray(child.receipts) ? child.receipts : []) {
3638
+ if (r?.kind !== 'verification' || !(r.ts >= since) || r.workspaceRoot) continue;
3639
+ if (r.success === true && !(r.ts > revisionAt)) continue;
3640
+ out.push(r);
3641
+ }
3642
+ }
3643
+ return out.sort((a, b) => a.ts - b.ts);
3644
+ }
3645
+
3646
+ function delegatedWriteTimes(ledger = {}, cwd, children = null) {
3647
+ const since = ledger?.taskStartedAt;
3648
+ const writes = [];
3649
+ for (const child of children || delegatedChildLedgers(ledger, cwd)) {
3650
+ for (const r of Array.isArray(child.receipts) ? child.receipts : []) {
3651
+ if (r?.kind !== 'write' || r.success !== true || typeof r.file !== 'string' || !r.contentSha) continue;
3652
+ if (!(r.ts >= since) || r.workspaceRoot || isBookkeepingWrite(r.file)) continue;
3653
+ const abs = path.resolve(cwd, r.file);
3654
+ const rel = path.relative(path.resolve(cwd), abs);
3655
+ if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) continue;
3656
+ if (fileContentSha(abs) !== r.contentSha) continue;
3657
+ writes.push({ file: rel.split(path.sep).join('/'), ts: r.ts });
3658
+ }
3659
+ }
3660
+ return writes;
3661
+ }
3662
+
3663
+ function delegatedWriteFiles(ledger = {}, cwd, children = null) {
3664
+ return [...new Set(delegatedWriteTimes(ledger, cwd, children).map((w) => w.file))];
3665
+ }
3666
+
3667
+ const STATE_STOP_TOOLS = new Set(['TaskStop', 'KillShell', 'CronDelete']);
3668
+ const STATE_CMD_PREFIX = String.raw`(?:(?:[A-Za-z_]\w*=\S*|command|builtin|time|nohup|sudo|exec|xargs|nice|stdbuf|setsid|${'e' + 'nv'})(?:\s+-\S+)*\s+)*`;
3669
+ const STATE_KILL_CMD_RE = new RegExp(String.raw`(?:^|[;&|(]\s*|\bthen\s+|\bdo\s+)${STATE_CMD_PREFIX}(?:kill|pkill|killall)\b`);
3670
+ const STATE_KILL0_RE = new RegExp(String.raw`(?:^|[;&|(]\s*)${STATE_CMD_PREFIX}kill\s+-0\b`);
3671
+ const STATE_PROBE_CMD_RE = /(?:^|[;&|(]\s*|\b(?:sudo|xargs)\s+)(?:ps|pgrep|pstree|jobs|lsof|tmux\s+(?:ls|list-\w+)|screen\s+-ls|launchctl\s+(?:list|print)|systemctl\s+(?:status|is-active|list-\w+)|pm2\s+(?:ls|list|status)|docker\s+(?:ps|inspect)|kill\s+-0|crontab\s+-l|atq)\b/;
3672
+ function stateConditionOf(toolResponse) {
3673
+ let obj = toolResponse;
3674
+ if (typeof obj === 'string') { try { obj = JSON.parse(obj); } catch { return null; } }
3675
+ if (!obj || typeof obj !== 'object') return null;
3676
+ const numeric = (scope, re) => {
3677
+ for (const [key, value] of Object.entries(scope)) {
3678
+ if (re.test(key) && typeof value === 'number' && Number.isFinite(value)) return value;
3679
+ }
3680
+ return null;
3681
+ };
3682
+ for (const scope of [obj, obj.details, obj.task, obj.job]) {
3683
+ if (!scope || typeof scope !== 'object') continue;
3684
+ const elapsed = numeric(scope, /^(?:elapsed|runtime|running_for|duration)/i);
3685
+ const limit = numeric(scope, /^(?:deadline|timeout|time_?limit|max_?(?:runtime|duration|seconds))/i);
3686
+ if (elapsed !== null && limit !== null) return elapsed > limit ? 'met' : 'unmet';
3687
+ }
3688
+ return null;
3689
+ }
3690
+ function mergeStateProof(a, b) {
3691
+ if (!a) return b || null;
3692
+ if (!b) return a;
3693
+ return { stopSeq: Math.max(a.stopSeq || 0, b.stopSeq || 0), observedAfterStop: a.observedAfterStop || b.observedAfterStop,
3694
+ terminalObserved: a.terminalObserved || b.terminalObserved, condition: b.condition ?? a.condition ?? null, boundObserved: a.boundObserved || b.boundObserved, targets: [...new Set([...(a.targets || []), ...(b.targets || [])])] };
3695
+ }
3696
+ function foldStateProof(proof, receipt, seq) {
3697
+ const prev = proof || { stopSeq: 0, observedAfterStop: false, terminalObserved: false, boundObserved: false, condition: null, targets: [] };
3698
+ const next = { ...prev, targets: [...new Set([...(prev.targets || []), ...(receipt.targets || [])])] };
3699
+ if (receipt.role === 'stop') { next.stopSeq = seq; next.observedAfterStop = false; next.terminalObserved = false; }
3700
+ else {
3701
+ if (receipt.bound !== false) {
3702
+ next.boundObserved = true;
3703
+ if (receipt.condition) next.condition = receipt.condition;
3704
+ if (prev.stopSeq > 0 && seq > prev.stopSeq && receipt.terminal === true) next.observedAfterStop = true;
3705
+ if (receipt.terminal === true) next.terminalObserved = true;
3706
+ }
3707
+ }
3708
+ return next;
3709
+ }
3710
+ const STATE_TERMINAL_STATUS_RE = /^(?:completed?|finished|exited|done|killed|stopped|cancell?ed|terminated|failed|errored|not[ _-]?found|missing|gone)$/i;
3711
+ const STATE_ID_KEYS = ['id', 'task_id', 'taskId', 'job_id', 'jobId', 'shell_id', 'shellId', 'bash_id', 'bashId', 'agent_id', 'agentId'];
3712
+ function stateJobRecords(toolInput, toolResponse) {
3713
+ let root = toolResponse;
3714
+ if (typeof root === 'string') { try { root = JSON.parse(root); } catch { return []; } }
3715
+ const records = [];
3716
+ const inputId = STATE_ID_KEYS.map((k) => toolInput?.[k]).find((v) => typeof v === 'string' && v);
3717
+ const walk = (node, depth) => {
3718
+ if (!node || typeof node !== 'object' || depth > 4) return;
3719
+ if (Array.isArray(node)) { for (const item of node.slice(0, 200)) walk(item, depth + 1); return; }
3720
+ const status = [node.status, node.state].find((v) => typeof v === 'string');
3721
+ if (status !== undefined) {
3722
+ const id = STATE_ID_KEYS.map((k) => node[k]).find((v) => typeof v === 'string' && v) || (depth === 0 ? inputId : null);
3723
+ records.push({ id: id ? id.toLowerCase() : null, terminal: STATE_TERMINAL_STATUS_RE.test(status.trim()) });
3724
+ return;
3725
+ }
3726
+ for (const key of Object.keys(node)) {
3727
+ if (/^(?:tasks?|jobs?|shells?|agents?|details|result|results|items|data|processes)$/i.test(key)) walk(node[key], depth + 1);
3728
+ }
3729
+ };
3730
+ walk(root, 0);
3731
+ return records;
3732
+ }
3733
+ function stateReceiptShape(toolName, toolInput, toolResponse, contract) {
3734
+ const command = String(toolInput.command || '');
3735
+ const isKill = toolName === 'Bash' && STATE_KILL_CMD_RE.test(command) && !STATE_KILL0_RE.test(command);
3736
+ const role = STATE_STOP_TOOLS.has(toolName) || isKill ? 'stop' : 'observe';
3737
+ let text = '';
3738
+ try { text = (typeof toolResponse === 'string' ? toolResponse : JSON.stringify(toolResponse ?? '')).slice(0, 6000); } catch { text = ''; }
3739
+ const inputText = toolName === 'Bash' ? command.replace(/"[^"]*"|'[^']*'/g, ' ') : JSON.stringify(toolInput).slice(0, 2000);
3740
+ const haystack = `${inputText} ${text}`.toLowerCase();
3741
+ const wanted = contract?.stateTargets || [];
3742
+ const targetsSeen = wanted.filter((id) => haystack.includes(id));
3743
+ const probesState = toolName !== 'Bash' || STATE_PROBE_CMD_RE.test(command);
3744
+ const targets = role === 'observe' && !probesState ? [] : targetsSeen;
3745
+ const condition = role === 'observe' && contract?.stateConditionalStop === true ? stateConditionOf(toolResponse) : null;
3746
+ const records = role === 'observe' && probesState && toolName !== 'Bash' ? stateJobRecords(toolInput, toolResponse) : [];
3747
+ const terminalTargets = [];
3748
+ const liveTargets = [];
3749
+ let bashAbsent = false;
3750
+ for (const id of wanted) {
3751
+ const own = records.filter((r) => r.id === id);
3752
+ if (own.length === 0) continue;
3753
+ (own.every((r) => r.terminal) ? terminalTargets : liveTargets).push(id);
3754
+ }
3755
+ const idlessTerminal = wanted.length === 0 && records.length > 0 && records.every((r) => r.terminal);
3756
+ if (role === 'observe' && probesState && toolName === 'Bash') {
3757
+ const out = text.toLowerCase();
3758
+ for (const id of targetsSeen) (out.includes(id) ? liveTargets : terminalTargets).push(id);
3759
+ bashAbsent = wanted.length === 0 && /\bno such process\b|\bno (?:matching |running )?processes? (?:found|running)\b/.test(out) && !/command not found|permission denied/.test(out);
3760
+ }
3761
+ const terminal = wanted.length > 0 ? terminalTargets.length > 0 && liveTargets.length === 0 : (idlessTerminal || bashAbsent);
3762
+ return { role, condition, terminal, terminalTargets, liveTargets, targets, bound: wanted.length > 0 ? targets.length > 0 : probesState };
3763
+ }
3764
+ const STATE_OBSERVATION_TOOLS = new Set(['TaskStop', 'TaskOutput', 'TaskGet', 'TaskList', 'ListAgents', 'CronList', 'CronDelete', 'BashOutput', 'KillShell']);
3765
+
3457
3766
  function evidenceSatisfied(evidence, ledger = {}, state = {}, { cwd } = {}) {
3458
3767
  const routeSummary = state?.routeSummary || {};
3768
+ if (evidence === 'state-verification') {
3769
+ const contract = routeSummary.executionContract || {};
3770
+ const proof = ledger.stateProof;
3771
+ if (ledger.stateObserved !== true || !proof) return false;
3772
+ if ((contract.stateTargets || []).some((id) => !(proof.targets || []).includes(id))) return false;
3773
+ if (proof.boundObserved !== true) return false;
3774
+ if (contract.stateAction === true) return proof.observedAfterStop === true || proof.terminalObserved === true;
3775
+ if (contract.stateConditionalStop === true) {
3776
+ if (proof.stopSeq > 0) return proof.observedAfterStop === true || proof.terminalObserved === true;
3777
+ return proof.terminalObserved === true || proof.condition === 'unmet';
3778
+ }
3779
+ return true;
3780
+ }
3459
3781
  if (evidence === 'release-publication') return releasePublicationMissing(state, ledger, cwd) === null;
3460
3782
  if (evidence === 'report-artifact') {
3461
3783
  const artifact = routeSummary.executionContract?.reportArtifact;
@@ -3476,7 +3798,13 @@ function evidenceSatisfied(evidence, ledger = {}, state = {}, { cwd } = {}) {
3476
3798
  return operationCompletionPolicy(contract, null, withGitAuthority(ledger, cwd))?.complete === true;
3477
3799
  }
3478
3800
  if (evidence === 'write-evidence') {
3479
- const expected = routeSummary.expectedSourceFiles || [];
3801
+ const expected = hardExpectedSourceFiles(routeSummary);
3802
+ const delegated = delegatedWriteFiles(ledger, cwd);
3803
+ if (delegated.length > 0) {
3804
+ if (expected.length === 0) return true;
3805
+ const wanted = new Set(expected.map((f) => (typeof f === 'string' ? path.relative(path.resolve(cwd), path.resolve(cwd, f)).split(path.sep).join('/') : '')));
3806
+ if (delegated.some((f) => wanted.has(f))) return true;
3807
+ }
3480
3808
  if (routeSummary.executionContract?.taskKind && expected.length) {
3481
3809
  const bank = evidenceBank(ledger, 'bankedWrites');
3482
3810
  return expected.some((file) => typeof file === 'string' && (
@@ -3519,9 +3847,7 @@ function evidenceSatisfied(evidence, ledger = {}, state = {}, { cwd } = {}) {
3519
3847
  if (evidence === 'impact-evidence') {
3520
3848
  // WS-C: when the route names expected source files, a read must cover one of them —
3521
3849
  // ANY read (e.g. docs) no longer satisfies the impact-evidence gate.
3522
- const expectedFiles = Array.isArray(routeSummary?.expectedSourceFiles)
3523
- ? routeSummary.expectedSourceFiles
3524
- : [];
3850
+ const expectedFiles = hardExpectedSourceFiles(routeSummary);
3525
3851
  if (expectedFiles.length > 0) {
3526
3852
  const readFiles = Array.isArray(ledger.sourceFiles) ? ledger.sourceFiles : [];
3527
3853
  return readFiles.some((file) => expectedFiles.some((expected) => fileMatchesExpected(file, expected)));
@@ -3597,7 +3923,11 @@ function recoveryInstruction(missingEvidence, ledger = {}, routeSummary = {}, {
3597
3923
  // TASK-009 (BL-011): bug-fix floor instructions take precedence — the fix
3598
3924
  // loop needs the verbatim repro pair and the named mechanism, not more
3599
3925
  // generic write/verify pushes.
3600
- if (missingEvidence.includes('repro-before')) {
3926
+ const lastRun = [...(ledger.receipts || [])].reverse().find((r) => r?.kind === 'verification');
3927
+ if (lastRun?.exitStatusUnproven === true && isOmpBackgroundId(lastRun.backgroundTaskId) && !lastRun.backgroundCompletion
3928
+ && (missingEvidence.includes('repro-before') || missingEvidence.includes('repro-after') || missingEvidence.includes('root-cause'))) {
3929
+ instruction = `UNSUPPORTED_EVIDENCE: omp job ${lastRun.backgroundTaskId} has no exit status, so it is neither the failing repro nor the passing re-run. Run the original command once in the foreground (async:false, long enough timeout) for a native exit; do not poll, relaunch, or write docs. The bug-fix obligations are unchanged.`;
3930
+ } else if (missingEvidence.includes('repro-before')) {
3601
3931
  instruction = 'Reproduce the original failure verbatim on the defect surface and record it as the repro-before receipt (failing run). No fix evidence counts before the failure is proven.';
3602
3932
  } else if (missingEvidence.includes('repro-after')) {
3603
3933
  instruction = 'Re-run the original repro on the same surface after the fix and record the passing repro-after receipt — a different surface or unrelated green check is not the fix-proof.';
@@ -3640,7 +3970,9 @@ function recoveryInstruction(missingEvidence, ledger = {}, routeSummary = {}, {
3640
3970
  // Unproven never sets `verificationFailed`, so this must not key off that flag.
3641
3971
  const lastVerification = [...(ledger.receipts || [])].reverse().find((r) => r?.kind === 'verification');
3642
3972
  if (!instruction && lastVerification?.exitStatusUnproven === true) {
3643
- if (lastVerification.backgroundTaskId && !lastVerification.backgroundCompletion) {
3973
+ if (isOmpBackgroundId(lastVerification.backgroundTaskId) && !lastVerification.backgroundCompletion) {
3974
+ instruction = `UNSUPPORTED_EVIDENCE: omp job ${lastVerification.backgroundTaskId} has no exit status, so it is not a pass. Run the same command once in the foreground (async:false, long enough timeout) for a native exit; do not poll, relaunch in background, or write docs.`;
3975
+ } else if (lastVerification.backgroundTaskId && !lastVerification.backgroundCompletion) {
3644
3976
  const id = lastVerification.backgroundTaskId;
3645
3977
  const hostExit = hostCompletionExit(ledger.transcriptPath, id);
3646
3978
  instruction = hostExit === null
@@ -3679,7 +4011,7 @@ function recoveryInstruction(missingEvidence, ledger = {}, routeSummary = {}, {
3679
4011
  // WS-C: the target hint travels with the reason whenever impact evidence is missing and
3680
4012
  // the route names expected files — it must survive branch precedence above.
3681
4013
  if (missingEvidence.includes('impact-evidence')) {
3682
- const expectedFiles = Array.isArray(routeSummary?.expectedSourceFiles) ? routeSummary.expectedSourceFiles : [];
4014
+ const expectedFiles = hardExpectedSourceFiles(routeSummary);
3683
4015
  if (expectedFiles.length > 0 && !expectedFiles.some(
3684
4016
  (expected) => (ledger.sourceFiles || []).some((file) => fileMatchesExpected(file, expected))
3685
4017
  )) {
@@ -3872,6 +4204,15 @@ function conditionalRepairOrdersPublish(state, ledger, cwd) {
3872
4204
  } }));
3873
4205
  }
3874
4206
 
4207
+ function cleanTreeCandidate(cwd) {
4208
+ const head = gitOutput(['rev-parse', 'HEAD'], cwd);
4209
+ if (!head) return null;
4210
+ try {
4211
+ const dirty = execFileSync('git', ['status', '--porcelain', '--untracked-files=no'], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 5000 });
4212
+ return String(dirty).trim() === '' ? head : null;
4213
+ } catch { return null; }
4214
+ }
4215
+
3875
4216
  function releasePublicationMissing(state, ledger, cwd) {
3876
4217
  const routedPublication = state?.routeSummary?.executionContract?.publication === true
3877
4218
  && ordersPublication(state?.routingContext?.lastExplicitUserPromptText);
@@ -3885,9 +4226,21 @@ function releasePublicationMissing(state, ledger, cwd) {
3885
4226
  && proof.success === true && proof.operation.complete === true)
3886
4227
  .sort((a, b) => b.sequence - a.sequence)[0];
3887
4228
  const wanted = `published:${pkg.name}@${pkg.version}`;
3888
- if (view?.operation?.state !== wanted) return 'release-publication';
4229
+ const mutation = release.map((entry) => entry.mutation).filter((proof) => proof?.operation?.domain === 'release'
4230
+ && proof.operation.target === 'npm-publish' && proof.taskInstanceId === ledger.taskInstanceId
4231
+ && proof.sessionKey === ledger.sessionKey).sort((a, b) => b.sequence - a.sequence)[0];
4232
+ if (view?.operation?.state !== wanted || view.taskInstanceId !== ledger.taskInstanceId
4233
+ || view.sessionKey !== ledger.sessionKey || !view.toolUseId || view.exitStatusUnproven
4234
+ || !mutation?.success || mutation.exitStatusUnproven || !mutation.toolUseId || mutation.operation.state !== wanted
4235
+ || !Number.isSafeInteger(mutation.sequence) || !Number.isSafeInteger(view.sequence)
4236
+ || view.sequence <= mutation.sequence || view.operation.scope !== mutation.operation.scope) return 'release-publication';
3889
4237
  const tagCommit = gitOutput(['rev-parse', '--verify', '--quiet', `v${pkg.version}^{commit}`], cwd);
3890
4238
  const head = gitOutput(['rev-parse', 'HEAD'], cwd);
4239
+ const publishedCandidate = mutation.operation.candidate;
4240
+ if (!publishedCandidate || !head || !mutation.operation.integrity || view.operation.integrity !== mutation.operation.integrity
4241
+ || view.operation.integrityFor !== `${pkg.name}@${pkg.version}`) return 'release-publication';
4242
+ if (tagCommit ? tagCommit !== publishedCandidate
4243
+ : head && publishedCandidate !== head && publishedReleaseDrifted(pkg, publishedCandidate, head, cwd)) return 'release-publication';
3891
4244
  // A repository that tags its releases (any v<semver> tag exists) must have tagged THIS version: without the
3892
4245
  // tag there is no immutable identity to tie the published artifact to. A repository that never tags keeps
3893
4246
  // the registry receipt as its only proof (the pre-P1 behaviour) instead of being blocked forever.
@@ -4044,6 +4397,11 @@ function evaluateCompletionContract({ state = {}, ledger = {}, cwd, phase = null
4044
4397
  if (Array.isArray(conditionalObligations) && conditionalObligations.length > 0) {
4045
4398
  const resolved = resolveConditionalContract(state, requestLedger, cwd);
4046
4399
  if (resolved) return evaluateCompletionContract({ state: resolved, ledger, cwd, phase });
4400
+ if (routeSummary.executionContract?.taskKind && routeSummary.executionContract.taskKind !== 'READ_ONLY') {
4401
+ const { conditionalObligations: _deferred, publication: _publication, ...permitted } = routeSummary.executionContract;
4402
+ permitted.completionEvidence = (permitted.completionEvidence || []).filter((item) => item !== 'release-publication');
4403
+ return evaluateCompletionContract({ state: { ...state, routeSummary: { ...routeSummary, executionContract: permitted } }, ledger, cwd, phase });
4404
+ }
4047
4405
  return { continue: false, notify: true, complete: false, outcome: 'blocked',
4048
4406
  missingEvidence: ['conditional-predicate'],
4049
4407
  reason: 'UKit conditional obligation unresolved: no native owned predicate resolver is available for this branch. Report the predicate and retained actions; do not infer authorization, request publication evidence, or claim completion from a generic verification receipt.' };
@@ -4114,7 +4472,7 @@ function evaluateCompletionContract({ state = {}, ledger = {}, cwd, phase = null
4114
4472
  // the same session). Any attempted write keeps the obligation: an unauthorized side effect
4115
4473
  // of a read-only request is never treated as irrelevant.
4116
4474
  if (routeSummary.executionContract?.taskKind === 'READ_ONLY' && effectiveLedger.writeAttempted !== true
4117
- && !(Array.isArray(routeSummary.expectedSourceFiles) && routeSummary.expectedSourceFiles.length > 0)) {
4475
+ && hardExpectedSourceFiles(routeSummary).length === 0) {
4118
4476
  const at = missingEvidence.indexOf('impact-evidence');
4119
4477
  if (at !== -1) missingEvidence.splice(at, 1);
4120
4478
  }
@@ -4145,7 +4503,7 @@ function evaluateCompletionContract({ state = {}, ledger = {}, cwd, phase = null
4145
4503
  // completion behavior (false-block = 0 on the P2 gate).
4146
4504
  const playbookId = routeSummary.playbookId || null;
4147
4505
  if (playbookId === BUGFIX_PLAYBOOK_ID) {
4148
- const floor = bugFixFloorStatus(effectiveLedger, playbookId);
4506
+ const floor = bugFixFloorStatus(effectiveLedger, playbookId, cwd);
4149
4507
  missingEvidence.push(...bugFixFloorMissing(floor));
4150
4508
  // An unreproducible defect ends INCONCLUSIVE, never a fabricated pass and
4151
4509
  // never an unbounded recovery loop: the defect could not be reproduced in
@@ -4375,7 +4733,7 @@ function evaluateCompletionContract({ state = {}, ledger = {}, cwd, phase = null
4375
4733
  const instruction = publicationPending
4376
4734
  ? prerequisites.length > 0
4377
4735
  ? `Complete the permitted prerequisites first (${prerequisites.join(', ')}). ${recoveryInstruction(prerequisites, effectiveLedger, routeSummary, { cwd })} Do not publish before mandatory verification and separate execution authorization are established.`
4378
- : 'Publication remains unproven. Accepted evidence: a Bash result of exactly `npm view <package> version` (optionally --prefer-online) with successful native exit and the current package version, owned by this task. Rejected as unproven: the same command behind a pipeline, masked exit, stale or foreign-task receipt. Inspect existing owned registry/tag evidence first; never republish a served version or move its tag. Missing evidence does not authorize execution: publication requires the owner permission and mandatory release prerequisites. If either is unavailable, report BLOCKED with provenance; do not retry the same blocker.'
4736
+ : 'Publication remains unproven. A task-owned successful native publish receipt and a subsequent matching registry observation are required; registry state alone does not prove execution. Masked, stale or foreign-task receipts are not proof. Inspect existing evidence first; never republish a served version or move its tag. Missing evidence does not authorize execution: publication requires owner permission and mandatory release prerequisites. If provenance or authorization is unavailable, report BLOCKED; do not retry the same blocker.'
4379
4737
  : operationalTask
4380
4738
  ? 'Inspect native mutation receipts and verify the requested operational state; do not fabricate source edits or source-test evidence.'
4381
4739
  : recoveryInstruction(missingEvidence, effectiveLedger, routeSummary, { cwd });
@@ -4502,6 +4860,10 @@ function playbookStopAdvisory({ state = {}, ledger = {}, cwd } = {}, result = {}
4502
4860
  }
4503
4861
 
4504
4862
  export function evaluateCompletion(args = {}) {
4863
+ if (ownerStopActive(args.state, args.payload || args.state)) {
4864
+ return { continue: false, complete: false, outcome: 'owner-stopped', gateRelease: 'owner-stop', missingEvidence: [],
4865
+ reason: 'Owner requested STOP; no write or verification evidence is demanded and no continuation is scheduled. Unfinished work stays unfinished until a new owner request.' };
4866
+ }
4505
4867
  const result = evaluateCompletionContract(args);
4506
4868
  // Explain the verdict from the SAME task-scoped snapshot used by the verifier. These are proof summaries,
4507
4869
  // not an alternative evidence source; a diagnostic must never satisfy or relax an obligation.
@@ -4525,9 +4887,7 @@ export function evaluateCompletion(args = {}) {
4525
4887
  // route names files). Ledger-scoped only: "none" means no LEDGER-captured
4526
4888
  // evidence — never a claim about reads a host hook may not have captured, and
4527
4889
  // Bash workspace activity is never counted as source evidence.
4528
- const diagExpectedFiles = Array.isArray(args.state?.routeSummary?.expectedSourceFiles)
4529
- ? args.state.routeSummary.expectedSourceFiles
4530
- : [];
4890
+ const diagExpectedFiles = hardExpectedSourceFiles(args.state?.routeSummary);
4531
4891
  const diagCoveredCount = diagExpectedFiles.length
4532
4892
  ? diagExpectedFiles.filter((expected) => (Array.isArray(owned.sourceFiles) ? owned.sourceFiles : []).some((file) => fileMatchesExpected(file, expected))).length
4533
4893
  : 0;
@@ -4745,6 +5105,10 @@ async function runEvaluateStop() {
4745
5105
 
4746
5106
  const state = await readRouteState(projectRoot, payload);
4747
5107
  const ledger = await readExecutionLedger(projectRoot, payload) || {};
5108
+ if (state?.routePublicationIncomplete) {
5109
+ process.stdout.write(`${JSON.stringify({ decision: 'block', reason: 'UKit route publication incomplete: shared state and session route do not match; completion is unproven.' })}\n`);
5110
+ return;
5111
+ }
4748
5112
 
4749
5113
  // A session ledger with activity proves this session was routed and accumulating evidence.
4750
5114
  // If the route state is now missing or unreadable (router crashed/timed out before