@ngockhoale/ukit 3.4.74 → 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.
@@ -330,6 +330,26 @@ export async function readRouteState(projectRoot, payload = {}) {
330
330
  return readSessionRouteState(projectRoot, sessionId);
331
331
  }
332
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
+
333
353
  // Per-session route-state sidecar (written by skill-router.sh and route-task.mjs next to the
334
354
  // shared single-slot file). Owner is re-verified from the embedded sessionId, so a misfiled or
335
355
  // tampered record can never be adopted by another session.
@@ -394,7 +414,7 @@ export function hasUnfinishedCompletion(state = {}, ledger = {}, { cwd } = {}) {
394
414
  // TASK-009 (BL-011): a bug-fix route is also unfinished while its floor is
395
415
  // missing — the generic evidence alone never releases a bug fix.
396
416
  if (state?.routeSummary?.playbookId === BUGFIX_PLAYBOOK_ID) {
397
- return bugFixFloorMissing(bugFixFloorStatus(ledger, BUGFIX_PLAYBOOK_ID)).length > 0;
417
+ return bugFixFloorMissing(bugFixFloorStatus(ledger, BUGFIX_PLAYBOOK_ID, cwd)).length > 0;
398
418
  }
399
419
  return false;
400
420
  }
@@ -682,6 +702,45 @@ function extractExitCode(payload = {}) {
682
702
  return null;
683
703
  }
684
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
+
685
744
  // Recognize runner presence separately from exit proof. A trailing echo of `$?`
686
745
  // can report a status in text but cannot make the wrapper's exit authoritative.
687
746
  // Blank out quoted literals so `echo '(jest passed)'` / `git commit -m "run yarn test"` do not
@@ -723,7 +782,7 @@ function executableSubstitutions(command) {
723
782
  }
724
783
 
725
784
  function isVerificationCommand(command, depth = 0) {
726
- const raw = String(command || '').trim();
785
+ const raw = withoutInertHeredocBodies(command).trim();
727
786
  if (!raw) return false;
728
787
  if (depth < 2) {
729
788
  for (const sub of executableSubstitutions(raw)) {
@@ -780,11 +839,15 @@ function verificationShellUnits(command) {
780
839
  return units.filter((unit) => unit.text || unit.separator !== ';');
781
840
  }
782
841
 
783
- function maskedVerificationStage(command, depth = 0) {
784
- const text = String(command || '').trim();
842
+ function maskedVerificationStage(command, depth = 0, options = {}) {
843
+ const text = withoutInertHeredocBodies(command).trim();
785
844
  if (executableSubstitutions(text).length) return text;
786
845
  const units = verificationShellUnits(text);
787
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;
788
851
  let pipefail = false;
789
852
  let sawRunner = false;
790
853
  for (let i = 0; i < units.length; i += 1) {
@@ -798,17 +861,18 @@ function maskedVerificationStage(command, depth = 0) {
798
861
  if (/^(?:\[|(?:for|while|until|case|function|done|test|coproc|setsid)\b)/.test(plain)) return unit.text;
799
862
  // A later `exit 0`/`true`/`:` replaces the runner's status; a leading `!` inverts it.
800
863
  if (sawRunner && /^(?:exit\s+0|true|:)$/.test(plain)) return unit.text;
801
- if (/^!\s/.test(plain) && isVerificationCommand(unit.text)) return unit.text;
864
+ if (/^!\s/.test(plain) && (i === attestedIdx || isVerificationCommand(unit.text))) return unit.text;
802
865
  if (unit.separator === '||' || unit.separator === '&') return unit.text;
803
866
  const enable = /^set\s+-(?:[a-z]*o)\s+pipefail$/.test(plain);
804
867
  const disable = /^set\s+\+(?:[a-z]*o)\s+pipefail$/.test(plain);
805
868
  if (enable || disable) pipefail = enable;
806
- let runner = isVerificationCommand(unit.text);
869
+ const knownRunner = isVerificationCommand(unit.text);
870
+ let runner = knownRunner || i === attestedIdx;
807
871
  // Only an entire simple shell wrapper can inherit the inner script's proof.
808
872
  const wrapper = unit.text.match(/^(?:bash|sh|zsh|dash|ksh)\s+(?:-o\s+\w+\s+|-[a-z]+\s+)*(-[a-z]*c)\s+(?:'([^']*)'|"((?:[^"\\]|\\.)*)")$/);
809
- if (runner && wrapper) {
873
+ if (knownRunner && wrapper) {
810
874
  if (maskedVerificationStage(wrapper[2] ?? wrapper[3] ?? '', depth + 1)) return unit.text;
811
- } 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;
812
876
  if (runner) sawRunner = true;
813
877
  if (unit.separator === '|' || unit.separator === '|&') {
814
878
  if (runner && !pipefail) {
@@ -835,14 +899,37 @@ function maskedVerificationStage(command, depth = 0) {
835
899
  // return-code interpretation such as grep's "No matches found") is the host's proof of exit 0. Any other
836
900
  // host, or a response without that exact shape, keeps the fail-closed rule.
837
901
  function hostProvesCleanBashExit(harness, payload, response) {
902
+ if (harness === 'omp') return ompForegroundCleanExit(payload, response);
838
903
  return harness === 'claude-code' && payload?.hook_event_name === 'PostToolUse'
839
904
  && response && typeof response === 'object' && !Array.isArray(response)
840
905
  && response.interrupted === false && !response.backgroundTaskId && !response.returnCodeInterpretation;
841
906
  }
842
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
+
843
929
  function isBackgroundLaunchAck(response) {
844
930
  if (response && typeof response === 'object' && !Array.isArray(response)) {
845
931
  if (typeof response.backgroundTaskId === 'string' && response.backgroundTaskId) return true;
932
+ if (ompAsyncRunning(response)) return true;
846
933
  if (response.exitCode !== undefined && response.exitCode !== null) return false;
847
934
  return isBackgroundLaunchAck(response.stdout ?? response.output ?? response.content);
848
935
  }
@@ -854,6 +941,8 @@ function isBackgroundLaunchAck(response) {
854
941
  function backgroundTaskIdOf(response) {
855
942
  if (response && typeof response === 'object' && !Array.isArray(response)) {
856
943
  if (typeof response.backgroundTaskId === 'string' && response.backgroundTaskId) return response.backgroundTaskId;
944
+ const job = ompAsyncRunning(response);
945
+ if (job) return job;
857
946
  return backgroundTaskIdOf(response.stdout ?? response.output ?? response.content);
858
947
  }
859
948
  const m = typeof response === 'string' ? /^\s*Command running in background with ID: ([A-Za-z0-9_-]+)/.exec(response) : null;
@@ -947,7 +1036,7 @@ function compactReceipt(receipt) {
947
1036
  kind: receipt.kind,
948
1037
  success: receipt.success,
949
1038
  };
950
- 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']) {
951
1040
  if (receipt[key] !== undefined && receipt[key] !== null && receipt[key] !== '') {
952
1041
  compact[key] = key === 'operation' ? compactOperation(receipt[key]) : receipt[key];
953
1042
  }
@@ -1551,9 +1640,13 @@ function carriedEvidenceLedger(fresh, current) {
1551
1640
  }
1552
1641
  return {
1553
1642
  ...fresh,
1643
+ taskStartedAt: Number.isFinite(current.taskStartedAt) ? current.taskStartedAt : (fresh.taskStartedAt ?? null),
1644
+ parentSessionId: current.parentSessionId || fresh.parentSessionId || null,
1554
1645
  operationBank: current.operationBank || {},
1555
1646
  receiptSequence: current.receiptSequence || 0,
1556
1647
  sourceSucceeded: fresh.sourceSucceeded || current.sourceSucceeded === true,
1648
+ stateObserved: fresh.stateObserved === true || current.stateObserved === true,
1649
+ stateProof: mergeStateProof(fresh.stateProof, current.stateProof),
1557
1650
  // targeted-verification evidence (2.3.0) must survive the same re-key carry as the
1558
1651
  // coarse flags, or the stricter gates re-demand evidence mid-request — the exact
1559
1652
  // stall this carry exists to prevent.
@@ -1651,6 +1744,8 @@ function freshLedger(payload, routeState, harness) {
1651
1744
  sessionKey: sessionIdentity(payload),
1652
1745
  sessionId: payload.session_id || payload.sessionId || null,
1653
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,
1654
1749
  harness,
1655
1750
  requestKey: routeState?.requestKey || null,
1656
1751
  promptKey: evidencePromptKey(routeState),
@@ -1673,6 +1768,8 @@ function freshLedger(payload, routeState, harness) {
1673
1768
  taskType: null,
1674
1769
  playbookTrace: null,
1675
1770
  sourceSucceeded: false,
1771
+ stateObserved: false,
1772
+ stateProof: null,
1676
1773
  sourceFiles: [],
1677
1774
  writeAttempted: false,
1678
1775
  writeSucceeded: false,
@@ -1698,6 +1795,7 @@ function freshLedger(payload, routeState, harness) {
1698
1795
  // Emitted-once for INTERRUPTED survives re-keys via carriedEvidenceLedger.
1699
1796
  outcomes: [],
1700
1797
  startedAt: Date.now(),
1798
+ taskStartedAt: Date.now(),
1701
1799
  updatedAt: Date.now(),
1702
1800
  };
1703
1801
  }
@@ -1712,7 +1810,7 @@ const MAX_JOURNAL_SEEN = 64;
1712
1810
  const MAX_JOURNAL_RECORDS = 128;
1713
1811
  const MAX_JOURNAL_QUARANTINE_LINES = 32;
1714
1812
  const LEDGER_EVENT_TYPES = new Set(['receipt', 'continuation', 'notified', 'stop-progress', 'resumable-run']);
1715
- 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']);
1716
1814
 
1717
1815
  function journalPathFor(target) {
1718
1816
  return `${target}.journal`;
@@ -1853,7 +1951,7 @@ function newEventId() {
1853
1951
  return `${Date.now().toString(36)}-${crypto.randomBytes(8).toString('hex')}`;
1854
1952
  }
1855
1953
 
1856
- 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'];
1857
1955
 
1858
1956
  // TASK-009 (BL-011): evidence attestations are whitelisted verbatim — class /
1859
1957
  // surface / result / claim, the ARCH §Evidence Schema fields a receipt may
@@ -2384,6 +2482,8 @@ function bugFixReceiptClass(receipt, floor, failureCounts = {}, playbookId = nul
2384
2482
  if (playbookId !== BUGFIX_PLAYBOOK_ID || receipt?.kind !== 'verification' || receipt?.evidence) {
2385
2483
  return null;
2386
2484
  }
2485
+ if (receipt.exitStatusUnproven === true || receipt.backgroundTaskId) return null;
2486
+
2387
2487
  if (receipt.success === true) {
2388
2488
  const surface = bugFixReceiptSurface(receipt);
2389
2489
  if (
@@ -2449,8 +2549,13 @@ function foldBugFixReceipt(floor, receipt, playbookId = null, failureCounts = {}
2449
2549
  // window are folded through the same rules so a fixture ledger that never ran
2450
2550
  // recordExecutionReceipt (no bank) is judged identically. Per-surface failure
2451
2551
  // counts are rebuilt by walking the window in order.
2452
- function bugFixFloorStatus(ledger = {}, playbookId = null) {
2552
+ function bugFixFloorStatus(ledger = {}, playbookId = null, cwd = null) {
2453
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
+ }
2454
2559
  const counts = {};
2455
2560
  let merged = {
2456
2561
  ...floor,
@@ -2572,12 +2677,17 @@ function applyReceiptCore(ledger, receipt, { vibecode = false, projectRoot } = {
2572
2677
  return { ledger: next, value: null };
2573
2678
  }
2574
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);
2575
2682
  if (receipt.kind === 'operation') {
2576
2683
  next.operationBank = foldOperationEvidence(ledger.operationBank, receipt, ledger);
2577
2684
  }
2578
2685
  if (receipt.releasePreflight) next.releasePreflight = { ...receipt.releasePreflight, sequence: next.receiptSequence };
2579
2686
  if (receipt.kind === 'write' && receipt.success) next.releasePreflight = null;
2580
- 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') {
2581
2691
  next.sourceSucceeded = next.sourceSucceeded || receipt.success;
2582
2692
  if (receipt.success && receipt.file) {
2583
2693
  next.sourceFiles = [...new Set([...(next.sourceFiles || []), receipt.file])].slice(-MAX_SOURCE_FILES);
@@ -3255,7 +3365,7 @@ export async function recordExecutionReceipt({
3255
3365
  const operationReceipt = backgroundLaunchAck ? null : cronOperationReceipt(toolName, toolInput, toolResponse, success, { sessionId: explicitSessionId(payload), harness })
3256
3366
  || (toolName === 'Bash' && !bashScope.foreign
3257
3367
  ? (bashOperationReceipt(toolInput.command, toolResponse, success, nativeGoal, { sessionId: explicitSessionId(payload), harness })
3258
- || releaseOperationReceipt(toolInput.command, toolResponse, success, { sessionId: explicitSessionId(payload), harness }))
3368
+ || releaseOperationReceipt(toolInput.command, toolResponse, success, { sessionId: explicitSessionId(payload), harness, candidate: cleanTreeCandidate(projectRoot) }))
3259
3369
  : null);
3260
3370
  if (bgCompletion && !bgCompletion.rejected) {
3261
3371
  Object.assign(receipt, bgCompletion);
@@ -3269,6 +3379,11 @@ export async function recordExecutionReceipt({
3269
3379
  receipt.exitStatusUnproven = true;
3270
3380
  receipt.success = false;
3271
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));
3272
3387
  } else if (toolName === 'Read' || toolName === 'Grep' || toolName === 'Glob') {
3273
3388
  receipt.kind = 'source';
3274
3389
  receipt.file = toolInput.file_path || toolInput.path || null;
@@ -3294,13 +3409,20 @@ export async function recordExecutionReceipt({
3294
3409
  receipt.sessionKey = sessionIdentity(payload);
3295
3410
  receipt.command = String(toolInput.command || '').trim();
3296
3411
  // A pipe-masked runner status (exit 0 from `| tail`) is not evidence of a pass.
3297
- 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;
3298
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
+ }
3299
3421
  if (backgroundLaunchAck && receipt.success) {
3300
3422
  receipt.success = false;
3301
3423
  receipt.exitStatusUnproven = true;
3302
3424
  if (ledgerMessageEmitter) {
3303
- 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 */ }
3304
3426
  }
3305
3427
  } else if (maskedStage && receipt.success) {
3306
3428
  receipt.success = false;
@@ -3326,7 +3448,7 @@ export async function recordExecutionReceipt({
3326
3448
  // SPEC-typed-verdicts §2.1: every verification receipt mints a typed verdict record
3327
3449
  // (kind/evidence/verifier/headSha/baseSha/patchId/ts). Explicit payload.verdict
3328
3450
  // fields win so a hook or subagent verifier can attest its own kind and identity.
3329
- if (isVerificationCommand(toolInput.command)) {
3451
+ if (recognizedRunner || (attestedProgram && receipt.exitStatusUnproven === true)) {
3330
3452
  receipt.verdict = mintVerificationVerdict(receipt, payload, workspaceRoot, projectRoot);
3331
3453
  }
3332
3454
  } else if (toolName === 'Bash' && workspaceFp) {
@@ -3365,6 +3487,11 @@ export async function recordExecutionReceipt({
3365
3487
  }
3366
3488
  }
3367
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
+ }
3368
3495
  if (workspaceFp) {
3369
3496
  // A background completion is judged against the tree that was tested at LAUNCH, never today's tree.
3370
3497
  receipt.workspaceFp = bgCompletion && !bgCompletion.rejected && bgCompletion.workspaceFp ? bgCompletion.workspaceFp : workspaceFp;
@@ -3467,8 +3594,190 @@ function requiredEvidence(state = {}) {
3467
3594
  return [...new Set(required)];
3468
3595
  }
3469
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
+
3470
3766
  function evidenceSatisfied(evidence, ledger = {}, state = {}, { cwd } = {}) {
3471
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
+ }
3472
3781
  if (evidence === 'release-publication') return releasePublicationMissing(state, ledger, cwd) === null;
3473
3782
  if (evidence === 'report-artifact') {
3474
3783
  const artifact = routeSummary.executionContract?.reportArtifact;
@@ -3489,7 +3798,13 @@ function evidenceSatisfied(evidence, ledger = {}, state = {}, { cwd } = {}) {
3489
3798
  return operationCompletionPolicy(contract, null, withGitAuthority(ledger, cwd))?.complete === true;
3490
3799
  }
3491
3800
  if (evidence === 'write-evidence') {
3492
- 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
+ }
3493
3808
  if (routeSummary.executionContract?.taskKind && expected.length) {
3494
3809
  const bank = evidenceBank(ledger, 'bankedWrites');
3495
3810
  return expected.some((file) => typeof file === 'string' && (
@@ -3532,9 +3847,7 @@ function evidenceSatisfied(evidence, ledger = {}, state = {}, { cwd } = {}) {
3532
3847
  if (evidence === 'impact-evidence') {
3533
3848
  // WS-C: when the route names expected source files, a read must cover one of them —
3534
3849
  // ANY read (e.g. docs) no longer satisfies the impact-evidence gate.
3535
- const expectedFiles = Array.isArray(routeSummary?.expectedSourceFiles)
3536
- ? routeSummary.expectedSourceFiles
3537
- : [];
3850
+ const expectedFiles = hardExpectedSourceFiles(routeSummary);
3538
3851
  if (expectedFiles.length > 0) {
3539
3852
  const readFiles = Array.isArray(ledger.sourceFiles) ? ledger.sourceFiles : [];
3540
3853
  return readFiles.some((file) => expectedFiles.some((expected) => fileMatchesExpected(file, expected)));
@@ -3610,7 +3923,11 @@ function recoveryInstruction(missingEvidence, ledger = {}, routeSummary = {}, {
3610
3923
  // TASK-009 (BL-011): bug-fix floor instructions take precedence — the fix
3611
3924
  // loop needs the verbatim repro pair and the named mechanism, not more
3612
3925
  // generic write/verify pushes.
3613
- 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')) {
3614
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.';
3615
3932
  } else if (missingEvidence.includes('repro-after')) {
3616
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.';
@@ -3653,7 +3970,9 @@ function recoveryInstruction(missingEvidence, ledger = {}, routeSummary = {}, {
3653
3970
  // Unproven never sets `verificationFailed`, so this must not key off that flag.
3654
3971
  const lastVerification = [...(ledger.receipts || [])].reverse().find((r) => r?.kind === 'verification');
3655
3972
  if (!instruction && lastVerification?.exitStatusUnproven === true) {
3656
- 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) {
3657
3976
  const id = lastVerification.backgroundTaskId;
3658
3977
  const hostExit = hostCompletionExit(ledger.transcriptPath, id);
3659
3978
  instruction = hostExit === null
@@ -3692,7 +4011,7 @@ function recoveryInstruction(missingEvidence, ledger = {}, routeSummary = {}, {
3692
4011
  // WS-C: the target hint travels with the reason whenever impact evidence is missing and
3693
4012
  // the route names expected files — it must survive branch precedence above.
3694
4013
  if (missingEvidence.includes('impact-evidence')) {
3695
- const expectedFiles = Array.isArray(routeSummary?.expectedSourceFiles) ? routeSummary.expectedSourceFiles : [];
4014
+ const expectedFiles = hardExpectedSourceFiles(routeSummary);
3696
4015
  if (expectedFiles.length > 0 && !expectedFiles.some(
3697
4016
  (expected) => (ledger.sourceFiles || []).some((file) => fileMatchesExpected(file, expected))
3698
4017
  )) {
@@ -3885,6 +4204,15 @@ function conditionalRepairOrdersPublish(state, ledger, cwd) {
3885
4204
  } }));
3886
4205
  }
3887
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
+
3888
4216
  function releasePublicationMissing(state, ledger, cwd) {
3889
4217
  const routedPublication = state?.routeSummary?.executionContract?.publication === true
3890
4218
  && ordersPublication(state?.routingContext?.lastExplicitUserPromptText);
@@ -3908,6 +4236,11 @@ function releasePublicationMissing(state, ledger, cwd) {
3908
4236
  || view.sequence <= mutation.sequence || view.operation.scope !== mutation.operation.scope) return 'release-publication';
3909
4237
  const tagCommit = gitOutput(['rev-parse', '--verify', '--quiet', `v${pkg.version}^{commit}`], cwd);
3910
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';
3911
4244
  // A repository that tags its releases (any v<semver> tag exists) must have tagged THIS version: without the
3912
4245
  // tag there is no immutable identity to tie the published artifact to. A repository that never tags keeps
3913
4246
  // the registry receipt as its only proof (the pre-P1 behaviour) instead of being blocked forever.
@@ -4064,6 +4397,11 @@ function evaluateCompletionContract({ state = {}, ledger = {}, cwd, phase = null
4064
4397
  if (Array.isArray(conditionalObligations) && conditionalObligations.length > 0) {
4065
4398
  const resolved = resolveConditionalContract(state, requestLedger, cwd);
4066
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
+ }
4067
4405
  return { continue: false, notify: true, complete: false, outcome: 'blocked',
4068
4406
  missingEvidence: ['conditional-predicate'],
4069
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.' };
@@ -4134,7 +4472,7 @@ function evaluateCompletionContract({ state = {}, ledger = {}, cwd, phase = null
4134
4472
  // the same session). Any attempted write keeps the obligation: an unauthorized side effect
4135
4473
  // of a read-only request is never treated as irrelevant.
4136
4474
  if (routeSummary.executionContract?.taskKind === 'READ_ONLY' && effectiveLedger.writeAttempted !== true
4137
- && !(Array.isArray(routeSummary.expectedSourceFiles) && routeSummary.expectedSourceFiles.length > 0)) {
4475
+ && hardExpectedSourceFiles(routeSummary).length === 0) {
4138
4476
  const at = missingEvidence.indexOf('impact-evidence');
4139
4477
  if (at !== -1) missingEvidence.splice(at, 1);
4140
4478
  }
@@ -4165,7 +4503,7 @@ function evaluateCompletionContract({ state = {}, ledger = {}, cwd, phase = null
4165
4503
  // completion behavior (false-block = 0 on the P2 gate).
4166
4504
  const playbookId = routeSummary.playbookId || null;
4167
4505
  if (playbookId === BUGFIX_PLAYBOOK_ID) {
4168
- const floor = bugFixFloorStatus(effectiveLedger, playbookId);
4506
+ const floor = bugFixFloorStatus(effectiveLedger, playbookId, cwd);
4169
4507
  missingEvidence.push(...bugFixFloorMissing(floor));
4170
4508
  // An unreproducible defect ends INCONCLUSIVE, never a fabricated pass and
4171
4509
  // never an unbounded recovery loop: the defect could not be reproduced in
@@ -4522,6 +4860,10 @@ function playbookStopAdvisory({ state = {}, ledger = {}, cwd } = {}, result = {}
4522
4860
  }
4523
4861
 
4524
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
+ }
4525
4867
  const result = evaluateCompletionContract(args);
4526
4868
  // Explain the verdict from the SAME task-scoped snapshot used by the verifier. These are proof summaries,
4527
4869
  // not an alternative evidence source; a diagnostic must never satisfy or relax an obligation.
@@ -4545,9 +4887,7 @@ export function evaluateCompletion(args = {}) {
4545
4887
  // route names files). Ledger-scoped only: "none" means no LEDGER-captured
4546
4888
  // evidence — never a claim about reads a host hook may not have captured, and
4547
4889
  // Bash workspace activity is never counted as source evidence.
4548
- const diagExpectedFiles = Array.isArray(args.state?.routeSummary?.expectedSourceFiles)
4549
- ? args.state.routeSummary.expectedSourceFiles
4550
- : [];
4890
+ const diagExpectedFiles = hardExpectedSourceFiles(args.state?.routeSummary);
4551
4891
  const diagCoveredCount = diagExpectedFiles.length
4552
4892
  ? diagExpectedFiles.filter((expected) => (Array.isArray(owned.sourceFiles) ? owned.sourceFiles : []).some((file) => fileMatchesExpected(file, expected))).length
4553
4893
  : 0;