@ngockhoale/ukit 3.4.76 → 3.4.77

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.
@@ -10,7 +10,7 @@ import { fileURLToPath } from 'node:url';
10
10
  import { withAsyncLock, LOCK_MAX_SLICE_MS } from './async-lock.mjs';
11
11
  import { cronOperationReceipt, bashOperationReceipt, releaseOperationReceipt, preservesNativeOperationExit } from './cron-operation-adapter.mjs';
12
12
  import * as playbookExecution from './playbook-execution.mjs';
13
- import { operationCompletionPolicy, foldOperationEvidence, compactOperation, conditionalAbsenceGoal } from './operation-evidence.mjs';
13
+ import { operationCompletionPolicy, foldOperationEvidence, compactOperation, conditionalAbsenceGoal, contractOperationGoals, operationAttempted } from './operation-evidence.mjs';
14
14
 
15
15
  // Hook-context self-deadline (2.4.1 orphan-leak class): armed ONLY on direct
16
16
  // CLI invocation (see isDirectRun below) — never at import time. An import-time
@@ -365,6 +365,34 @@ export async function readSessionRouteState(projectRoot, sessionId) {
365
365
  return state;
366
366
  }
367
367
 
368
+ // Returns the bounded single-hop predecessor link (null otherwise) when an owner prompt explicitly resumes the previous checkpoint: it carries resume wording AND names
369
+ // something only that checkpoint owns (a background job id recorded in the previous task's ledger, or a
370
+ // commit sha that is the current HEAD / appears in the previous owner prompt). Never true for a new task.
371
+ export async function checkpointPredecessorLink(projectRoot, payload = {}, promptText = '', previous = {}) {
372
+ try {
373
+ const text = String(promptText || '');
374
+ const folded = text.normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/\u0111/gi, 'd').toLowerCase();
375
+ if (!/\b(?:continue|resume|tiep tuc|lam tiep|checkpoint)\b/.test(folded)) return null;
376
+ if (!previous?.taskInstanceId) return null;
377
+ const ledger = await readExecutionLedger(projectRoot, payload);
378
+ if (!ledger || ledger.taskInstanceId !== previous.taskInstanceId) return null;
379
+ const link = { predecessorTaskInstanceId: previous.taskInstanceId, predecessorSessionKey: ledger.sessionKey, workspace: projectRoot };
380
+ const ids = new Set((ledger.receipts || []).map((r) => r?.backgroundTaskId).filter(Boolean));
381
+ if ([...ids].some((id) => text.includes(id))) return link;
382
+ const head = gitOutput(['rev-parse', 'HEAD'], projectRoot);
383
+ const prior = String(previous.routingContext?.lastExplicitUserPromptText || '');
384
+ for (const sha of text.match(/\b[0-9a-f]{7,40}\b/g) || []) {
385
+ // A commit reference has hex letters AND digits (never a date/number), exists as a commit here, and is
386
+ // either HEAD or a word-bounded token of the previous owner prompt. Fail closed on any git error.
387
+ if (!/[a-f]/.test(sha) || !/\d/.test(sha)) continue;
388
+ if (!gitOutput(['rev-parse', '--verify', '--quiet', `${sha}^{commit}`], projectRoot)) continue;
389
+ const inPrior = new RegExp(`(?:^|[^0-9a-f])${sha}(?![0-9a-f])`, 'i').test(prior);
390
+ if ((head && head.startsWith(sha)) || inPrior) return link;
391
+ }
392
+ return null;
393
+ } catch { return null; }
394
+ }
395
+
368
396
  export async function readExecutionLedger(projectRoot, payload = {}) {
369
397
  const target = ledgerPath(projectRoot, payload);
370
398
  return mergeContinuationSidecar(await readJson(target, null), target);
@@ -389,7 +417,7 @@ function explicitPromptKey(routeState = {}) {
389
417
  }
390
418
 
391
419
  export function hasUnfinishedCompletion(state = {}, ledger = {}, { cwd } = {}) {
392
- ledger = effectiveRequestLedger(state, ledger);
420
+ ledger = effectiveRequestLedger(state, ledger, cwd);
393
421
  if (state?.routeSummary?.executionContract?.taskKind) {
394
422
  const result = evaluateCompletion({ state, ledger, cwd });
395
423
  return result.complete !== true && (result.missingEvidence || []).length > 0 && !ledger.blocker;
@@ -850,19 +878,28 @@ function maskedVerificationStage(command, depth = 0, options = {}) {
850
878
  : -1;
851
879
  let pipefail = false;
852
880
  let sawRunner = false;
881
+ let lastRunner = null;
882
+ // Attribution only: name the runner whose status is unproven and, separately, the consumer that masks it.
883
+ const hit = (consumer) => {
884
+ if (options?.detail && !options.detail.consumer) {
885
+ options.detail.runner = lastRunner && lastRunner !== consumer ? lastRunner : null;
886
+ options.detail.consumer = consumer;
887
+ }
888
+ return consumer;
889
+ };
853
890
  for (let i = 0; i < units.length; i += 1) {
854
891
  const unit = units[i];
855
892
  const plain = maskQuotedLiterals(unit.text);
856
893
  // Unsupported flow may skip a runner or discard an earlier iteration's failure.
857
894
  // Parens, braces and `if` are not interpreted here. A sequential consumer must not
858
895
  // turn the status of an earlier runner into PASS, even when it prints that status.
859
- if (sawRunner && units[i - 1]?.separator === ';' && !/^[)}]+$/.test(plain)) return unit.text;
896
+ if (sawRunner && units[i - 1]?.separator === ';' && !/^[)}]+$/.test(plain)) return hit(unit.text);
860
897
  // Command position only: `vitest -t case` is an argument, not a loop.
861
- if (/^(?:\[|(?:for|while|until|case|function|done|test|coproc|setsid)\b)/.test(plain)) return unit.text;
898
+ if (/^(?:\[|(?:for|while|until|case|function|done|test|coproc|setsid)\b)/.test(plain)) return hit(unit.text);
862
899
  // A later `exit 0`/`true`/`:` replaces the runner's status; a leading `!` inverts it.
863
- if (sawRunner && /^(?:exit\s+0|true|:)$/.test(plain)) return unit.text;
864
- if (/^!\s/.test(plain) && (i === attestedIdx || isVerificationCommand(unit.text))) return unit.text;
865
- if (unit.separator === '||' || unit.separator === '&') return unit.text;
900
+ if (sawRunner && /^(?:exit\s+0|true|:)$/.test(plain)) return hit(unit.text);
901
+ if (/^!\s/.test(plain) && (i === attestedIdx || isVerificationCommand(unit.text))) return hit(unit.text);
902
+ if (unit.separator === '||' || unit.separator === '&') return hit(unit.text);
866
903
  const enable = /^set\s+-(?:[a-z]*o)\s+pipefail$/.test(plain);
867
904
  const disable = /^set\s+\+(?:[a-z]*o)\s+pipefail$/.test(plain);
868
905
  if (enable || disable) pipefail = enable;
@@ -871,9 +908,9 @@ function maskedVerificationStage(command, depth = 0, options = {}) {
871
908
  // Only an entire simple shell wrapper can inherit the inner script's proof.
872
909
  const wrapper = unit.text.match(/^(?:bash|sh|zsh|dash|ksh)\s+(?:-o\s+\w+\s+|-[a-z]+\s+)*(-[a-z]*c)\s+(?:'([^']*)'|"((?:[^"\\]|\\.)*)")$/);
873
910
  if (knownRunner && wrapper) {
874
- if (maskedVerificationStage(wrapper[2] ?? wrapper[3] ?? '', depth + 1)) return unit.text;
875
- } else if (knownRunner && /(?:^|\s)(?:bash|sh|zsh|dash|ksh)\s/.test(plain)) return unit.text;
876
- if (runner) sawRunner = true;
911
+ if (maskedVerificationStage(wrapper[2] ?? wrapper[3] ?? '', depth + 1)) return hit(unit.text);
912
+ } else if (knownRunner && /(?:^|\s)(?:bash|sh|zsh|dash|ksh)\s/.test(plain)) return hit(unit.text);
913
+ if (runner) { sawRunner = true; lastRunner = unit.text; }
877
914
  if (unit.separator === '|' || unit.separator === '|&') {
878
915
  if (runner && !pipefail) {
879
916
  // A single runner's immediate Bash PIPESTATUS read can propagate its status.
@@ -882,7 +919,10 @@ function maskedVerificationStage(command, depth = 0, options = {}) {
882
919
  const proof = units[end + 1];
883
920
  const expected = `exit ${'${'}PIPESTATUS[${i - (units.slice(0, i).findLastIndex((u) => u.separator !== '|' && u.separator !== '|&') + 1)}]}`;
884
921
  if (units[end]?.separator !== ';' || proof?.text !== expected || proof.separator
885
- || units.slice(i + 1, end + 1).some((u) => isVerificationCommand(u.text))) return unit.text;
922
+ || units.slice(i + 1, end + 1).some((u) => isVerificationCommand(u.text))) {
923
+ if (options?.detail && !options.detail.consumer) { options.detail.runner = unit.text; options.detail.consumer = units[i + 1]?.text || null; }
924
+ return unit.text;
925
+ }
886
926
  return null;
887
927
  }
888
928
  continue;
@@ -979,13 +1019,45 @@ function hostCompletionExit(transcriptPath, id) {
979
1019
  return found;
980
1020
  }
981
1021
 
1022
+ // One transcript pass for every host task-notification (same acceptance rules as hostCompletionExit;
1023
+ // ANY notification, with or without an exit code, ends the pending state), memoized per (path, mtimeMs, size) so repeated Stop checks do not re-read the file.
1024
+ const HOST_SCAN_CACHE = [];
1025
+ function scanHostNotifications(transcriptPath) {
1026
+ const empty = { notified: new Set(), exits: new Map() };
1027
+ if (!transcriptPath) return empty;
1028
+ let st;
1029
+ try { st = fsSync.statSync(transcriptPath); } catch { return empty; }
1030
+ const hit = HOST_SCAN_CACHE.find((e) => e.path === transcriptPath && e.mtimeMs === st.mtimeMs && e.size === st.size);
1031
+ if (hit) return hit.scan;
1032
+ let raw;
1033
+ try { raw = fsSync.readFileSync(transcriptPath, 'utf8'); } catch { return empty; }
1034
+ const scan = { notified: new Set(), exits: new Map() };
1035
+ for (const line of raw.split('\n')) {
1036
+ if (!line.includes('<task-id>')) continue;
1037
+ let o;
1038
+ try { o = JSON.parse(line); } catch { continue; }
1039
+ let text = null;
1040
+ if (o?.type === 'queue-operation' && o.operation === 'enqueue' && typeof o.content === 'string') text = o.content;
1041
+ else if (o?.type === 'user' && typeof o.message?.content === 'string') text = o.message.content;
1042
+ if (!text || !text.trimStart().startsWith('<task-notification>')) continue;
1043
+ const exit = /\(exit code (-?\d+)\)/.exec(text);
1044
+ for (const m of text.matchAll(/<task-id>([^<]*)<\/task-id>/g)) {
1045
+ scan.notified.add(m[1]);
1046
+ if (exit) scan.exits.set(m[1], Number(exit[1]));
1047
+ }
1048
+ }
1049
+ HOST_SCAN_CACHE.unshift({ path: transcriptPath, mtimeMs: st.mtimeMs, size: st.size, scan });
1050
+ HOST_SCAN_CACHE.length = Math.min(HOST_SCAN_CACHE.length, 2);
1051
+ return scan;
1052
+ }
1053
+
982
1054
  // A host-backgrounded run completes OUTSIDE any tool event the hooks see (a task-notification system
983
1055
  // event). The supported capture is the host-written task output file: when the agent Reads
984
1056
  // `.../tasks/<id>.output` and its LAST line is the host footer `[exited with code N]`, that status is the
985
1057
  // runner's exit status. It is bound to the launch receipt by `backgroundTaskId` (same task ledger, so a
986
1058
  // completion for another task/session finds no launch), counted once, and judged against the tree that
987
1059
  // was tested at LAUNCH. A bare "passed" line, a partial read, or a path whose id has no launch is no proof.
988
- async function backgroundCompletionFor({ projectRoot, payload, toolInput, toolResponse }) {
1060
+ async function backgroundCompletionFor({ projectRoot, payload, toolInput, toolResponse, routeState = null }) {
989
1061
  const file = String(toolInput?.file_path || toolInput?.path || '');
990
1062
  const id = /[\\/]tasks[\\/]([A-Za-z0-9_-]+)\.output$/.exec(file)?.[1];
991
1063
  if (!id) return null;
@@ -997,7 +1069,11 @@ async function backgroundCompletionFor({ projectRoot, payload, toolInput, toolRe
997
1069
  const hostExit = hostCompletionExit(payload?.transcript_path || payload?.transcriptPath, id);
998
1070
  if (hostExit === null) return { rejected: 'no-host-notification' };
999
1071
  if (hostExit !== Number(footer[1])) return { rejected: 'host-footer-mismatch' };
1000
- const ledger = await readExecutionLedger(projectRoot, payload);
1072
+ const raw = await readExecutionLedger(projectRoot, payload);
1073
+ // A launch minted by the linked single-hop predecessor (same session + workspace) belongs to the successor.
1074
+ const ledger = raw && routeState?.taskInstanceId && raw.taskInstanceId !== routeState.taskInstanceId
1075
+ ? (predecessorLinkMatches({ ...routeState, sessionId: routeState.sessionId || explicitSessionId(payload) }, raw, projectRoot) ? raw : null)
1076
+ : raw;
1001
1077
  const receipts = ledger?.receipts || [];
1002
1078
  const launch = receipts.find((r) => r.kind === 'verification' && r.backgroundTaskId === id && !r.backgroundCompletion);
1003
1079
  if (!launch) return { rejected: 'no-matching-launch' };
@@ -1019,10 +1095,12 @@ async function backgroundCompletionFor({ projectRoot, payload, toolInput, toolRe
1019
1095
  };
1020
1096
  }
1021
1097
 
1022
- function noteUnprovenExitStatus(stage) {
1098
+ function noteUnprovenExitStatus(stage, detail = null) {
1023
1099
  if (!ledgerMessageEmitter) return;
1100
+ const named = detail?.runner
1101
+ ? `runner \`${detail.runner}\`${detail.consumer ? ` (masked by \`${detail.consumer}\`, which is not the runner)` : ''}` : `\`${stage}\``;
1024
1102
  const message =
1025
- `UKit execution-ledger: runner exit status is unproven for \`${stage}\` — `
1103
+ `UKit execution-ledger: runner exit status is unproven for ${named} — `
1026
1104
  + 'the shell wrapper may mask or skip the runner; it is NOT counted as passing verification. '
1027
1105
  + 'Re-run the bare verification command in the same workspace, in the foreground (a host background launch acknowledgement carries no exit status), without loops or status-swallowing consumers.';
1028
1106
  try {
@@ -1695,6 +1773,9 @@ function carriedEvidenceLedger(fresh, current) {
1695
1773
  },
1696
1774
  continuationRequestKey: current.continuationRequestKey || fresh.continuationRequestKey || null,
1697
1775
  notified: fresh.notified === true || current.notified === true,
1776
+ // Finite-handback markers are task-keyed (marker.task) and survive same-task re-keys.
1777
+ lastBlockState: current.lastBlockState || fresh.lastBlockState || null,
1778
+ handback: current.handback || fresh.handback || null,
1698
1779
  // Verification-loop tracking and any minted blocker belong to the same logical request
1699
1780
  // too — dropping a blocker on re-key would resume the exact loop it recorded.
1700
1781
  failedVerificationStreak: current.failedVerificationStreak || null,
@@ -1809,7 +1890,24 @@ const JOURNAL_VERSION = 1;
1809
1890
  const MAX_JOURNAL_SEEN = 64;
1810
1891
  const MAX_JOURNAL_RECORDS = 128;
1811
1892
  const MAX_JOURNAL_QUARANTINE_LINES = 32;
1812
- const LEDGER_EVENT_TYPES = new Set(['receipt', 'continuation', 'notified', 'stop-progress', 'resumable-run']);
1893
+ const LEDGER_EVENT_TYPES = new Set(['receipt', 'continuation', 'notified', 'stop-progress', 'resumable-run', 'wait-released', 'handback']);
1894
+ // Per-task state markers for the finite handback: `lastBlockState` = state fingerprint at the last BLOCK,
1895
+ // `handback` = state fingerprint whose single handback was delivered. Both are keyed to the task.
1896
+ function stateMarker(event) {
1897
+ const ok = (v) => typeof v === 'string' && v.length > 0 && v.length <= 200;
1898
+ return ok(event?.stateFp) && ok(event?.taskKey) ? { task: event.taskKey, fp: event.stateFp, ...(event.opOnly === true ? { op: true } : {}) } : null;
1899
+ }
1900
+ function applyHandbackToLedger(ledger, event) {
1901
+ const marker = stateMarker(event);
1902
+ return marker ? { ...ledger, handback: marker, updatedAt: Date.now() } : ledger;
1903
+ }
1904
+ const MAX_WAIT_RELEASES = 8;
1905
+ function applyWaitReleased(ledger, event) {
1906
+ const id = typeof event?.jobId === 'string' && /^[A-Za-z0-9_-]{1,64}$/.test(event.jobId) ? event.jobId : null;
1907
+ if (!id) return ledger;
1908
+ const prior = Array.isArray(ledger.waitReleasedFor) ? ledger.waitReleasedFor : [];
1909
+ return prior.includes(id) ? ledger : { ...ledger, waitReleasedFor: [...prior, id].slice(-MAX_WAIT_RELEASES), updatedAt: Date.now() };
1910
+ }
1813
1911
  const RECEIPT_KINDS = new Set(['source', 'state', 'write', 'verification', 'playbook-finding', 'workspace', 'operation', 'handback', 'review', 'delegation-violation']);
1814
1912
 
1815
1913
  function journalPathFor(target) {
@@ -1862,6 +1960,7 @@ async function mergeContinuationSidecar(ledger, target) {
1862
1960
  noProgressCount: Number(sidecar.noProgressCount) || 0,
1863
1961
  lastProgressDigest: sidecar.lastProgressDigest ?? null,
1864
1962
  notified: sidecar.notified === true,
1963
+ lastBlockState: sidecar.lastBlockState ?? null,
1865
1964
  lastContinuationAt: sidecarAt,
1866
1965
  updatedAt: Number(sidecar.updatedAt) || sidecarAt,
1867
1966
  };
@@ -1875,6 +1974,7 @@ async function mergeContinuationSidecar(ledger, target) {
1875
1974
  continuationRequestKey: sidecar.requestKey ?? ledger.continuationRequestKey ?? null,
1876
1975
  lastProgressDigest: sidecar.lastProgressDigest ?? ledger.lastProgressDigest ?? null,
1877
1976
  notified: ledger.notified === true || sidecar.notified === true,
1977
+ lastBlockState: sidecar.lastBlockState ?? ledger.lastBlockState ?? null,
1878
1978
  lastContinuationAt: sidecarAt,
1879
1979
  updatedAt: Math.max(Number(ledger.updatedAt) || 0, sidecarAt),
1880
1980
  };
@@ -1902,7 +2002,7 @@ async function bumpContinuationSidecar(target, event, { signal, deadlineMs } = {
1902
2002
  const base = event.taskInstanceId && stored.taskInstanceId !== event.taskInstanceId
1903
2003
  ? { taskInstanceId: event.taskInstanceId } : stored;
1904
2004
  const applied = event.type === 'notified'
1905
- ? { ...base, notified: true, updatedAt: Date.now() }
2005
+ ? { ...base, notified: true, ...(stateMarker(event) ? { lastBlockState: stateMarker(event) } : {}), updatedAt: Date.now() }
1906
2006
  : applyContinuationToLedger(base, event);
1907
2007
  // The merge gate requires sidecarAt > ledgerAt. A notified tick inherits the
1908
2008
  // base stamp unchanged, so it must be bumped past the base it was computed
@@ -1919,6 +2019,7 @@ async function bumpContinuationSidecar(target, event, { signal, deadlineMs } = {
1919
2019
  noProgressCount: Number(applied.noProgressCount) || 0,
1920
2020
  lastProgressDigest: applied.lastProgressDigest ?? null,
1921
2021
  notified: applied.notified === true,
2022
+ lastBlockState: applied.lastBlockState ?? null,
1922
2023
  lastContinuationAt: stampedAt,
1923
2024
  updatedAt: Date.now(),
1924
2025
  });
@@ -2139,7 +2240,13 @@ function applyJournalRecord(ledger, record, projectRoot) {
2139
2240
  return { ledger: applyContinuationToLedger(ledger, record.event), value: null };
2140
2241
  }
2141
2242
  if (record.type === 'notified') {
2142
- return { ledger: { ...ledger, notified: true, updatedAt: Date.now() }, value: null };
2243
+ return { ledger: { ...ledger, notified: true, ...(stateMarker(record.event) ? { lastBlockState: stateMarker(record.event) } : {}), updatedAt: Date.now() }, value: null };
2244
+ }
2245
+ if (record.type === 'handback') {
2246
+ return { ledger: applyHandbackToLedger(ledger, record.event), value: null };
2247
+ }
2248
+ if (record.type === 'wait-released') {
2249
+ return { ledger: applyWaitReleased(ledger, record.event), value: null };
2143
2250
  }
2144
2251
  if (record.type === 'resumable-run') {
2145
2252
  return { ledger: applyResumableRunToLedger(ledger, record.event?.run), value: null };
@@ -2906,6 +3013,7 @@ function applyContinuationToLedger(ledger, event) {
2906
3013
  continuationCount: (stale ? 0 : Number(ledger?.continuationCount || 0)) + 1,
2907
3014
  noProgressCount: progressed ? 0 : Number(ledger?.noProgressCount || 0) + 1,
2908
3015
  lastProgressDigest: digest,
3016
+ ...(stateMarker(event) ? { lastBlockState: stateMarker(event) } : {}),
2909
3017
  ...(event?.requestKey ? { continuationRequestKey: event.requestKey } : {}),
2910
3018
  lastContinuationAt: Date.now(),
2911
3019
  updatedAt: Date.now(),
@@ -2946,7 +3054,102 @@ function applyResumableRunToLedger(ledger, run) {
2946
3054
  };
2947
3055
  }
2948
3056
 
2949
- function liveBaseLedger(event, current, payload, routeState, harness, fallbackLedger) {
3057
+ // --- Single-hop predecessor reconciliation --------------------------------------------------------
3058
+ // The router mints a fresh task id for an owner prompt that explicitly resumes the previous checkpoint and
3059
+ // records `{predecessorTaskInstanceId, predecessorSessionKey, workspace}` on the new route. Only that exact
3060
+ // link lets the successor see the predecessor's evidence, and only when the session and workspace match.
3061
+ // Verification evidence additionally has to be content-current (`verdictCurrent`): a commit-only change
3062
+ // keeps it, a real source/test change invalidates it. Operation receipts are never adopted (they are bound
3063
+ // to the minting task); a background launch is, so its native completion can still be ingested.
3064
+ function predecessorLinkMatches(state, ledger, cwd) {
3065
+ const link = state?.predecessor;
3066
+ if (!link || !ledger || !state?.taskInstanceId || !ledger.taskInstanceId || !cwd) return false;
3067
+ if (ledger.taskInstanceId === state.taskInstanceId) return false;
3068
+ const stateSession = state.sessionId ? safeSegment(state.sessionId) : null;
3069
+ return link.predecessorTaskInstanceId === ledger.taskInstanceId
3070
+ && Boolean(link.predecessorSessionKey) && link.predecessorSessionKey === ledger.sessionKey
3071
+ && Boolean(stateSession) && stateSession === ledger.sessionKey
3072
+ && typeof link.workspace === 'string' && path.resolve(link.workspace) === path.resolve(cwd);
3073
+ }
3074
+
3075
+ function reconcilePredecessorLedger(state, ledger, cwd) {
3076
+ if (!predecessorLinkMatches(state, ledger, cwd)) return null;
3077
+ // Only a satisfying verdict is a content anchor; a later unproven launch verdict anchors nothing.
3078
+ const all = [ledger.verdict, ...(ledger.verdictHistory || [])].filter((v) => v && VERDICT_SATISFYING_KINDS.has(v.kind));
3079
+ const verdicts = all.filter((v) => verdictCurrent(v, { cwd }).current === true);
3080
+ const verified = verdicts.length > 0;
3081
+ // A recorded verdict is the content anchor: if every one is stale the tree really changed since the
3082
+ // predecessor's evidence, so nothing is adopted (source, write or verification). With no verdict at all
3083
+ // there is no anchor: reads/writes carry, verification does not (fail-closed).
3084
+ if (all.length > 0 && !verified) return {
3085
+ ...freshLedger({ session_id: ledger.sessionId, transcript_path: ledger.transcriptPath }, state, ledger.harness),
3086
+ sessionKey: ledger.sessionKey, receiptSequence: ledger.receiptSequence || 0,
3087
+ receipts: (ledger.receipts || []).filter((r) => r?.kind === 'verification' && r.backgroundTaskId && !r.backgroundCompletion).slice(-MAX_RECEIPTS),
3088
+ adoptedFrom: ledger.taskInstanceId,
3089
+ };
3090
+ const adopted = {
3091
+ ...ledger,
3092
+ taskInstanceId: state.taskInstanceId,
3093
+ requestKey: state.requestKey || ledger.requestKey || null,
3094
+ promptKey: evidencePromptKey(state),
3095
+ routeFingerprint: state.fingerprint || ledger.routeFingerprint || null,
3096
+ adoptedFrom: ledger.taskInstanceId,
3097
+ operationBank: {},
3098
+ // Operation observations are task-owned: a predecessor's state observation/receipts never satisfy the
3099
+ // successor's state-verification or operation-verification.
3100
+ stateObserved: false,
3101
+ stateProof: null,
3102
+ receipts: (ledger.receipts || []).filter((r) => r?.kind !== 'operation'),
3103
+ // A fresh successor task does not inherit predecessor gate blockers: owner STOP and denials live in the route
3104
+ // state and are evaluated separately (ownerStopActive / hooks), and a verification-loop blocker is scoped to
3105
+ // the task that looped.
3106
+ blocker: null,
3107
+ failedVerificationStreak: null,
3108
+ verificationFailureCounts: {},
3109
+ // The continuation budget belongs to the successor's own request: a capped predecessor must not leave the
3110
+ // new owner authorization with no budget (the sidecar is task-bound and is ignored for the new id).
3111
+ continuationCount: 0,
3112
+ continuationRequestKey: null,
3113
+ noProgressCount: 0,
3114
+ lastProgressDigest: null,
3115
+ lastContinuationAt: 0,
3116
+ notified: false,
3117
+ waitReleasedFor: [],
3118
+ verdict: verified ? verdicts[0] : null,
3119
+ verdictHistory: verdicts.slice(1, MAX_VERDICT_HISTORY),
3120
+ };
3121
+ if (!verified) {
3122
+ adopted.verificationSucceeded = false;
3123
+ adopted.targetedVerificationSucceeded = false;
3124
+ adopted.bankedVerifications = {};
3125
+ }
3126
+ return adopted;
3127
+ }
3128
+
3129
+ // Pending Claude Code background job owned by this (possibly adopted) ledger: launch receipt, no
3130
+ // completion, no host completion notification yet. omp ids carry no completion protocol and are excluded.
3131
+ function pendingBackgroundJob(ledger, { unreleasedOnly = false } = {}) {
3132
+ const receipts = ledger?.receipts || [];
3133
+ const done = new Set(receipts.filter((r) => r?.backgroundCompletion).map((r) => r.backgroundCompletion));
3134
+ let scan = null;
3135
+ for (const r of [...receipts].reverse()) {
3136
+ if (r?.kind !== 'verification' || !r.backgroundTaskId || r.backgroundCompletion) continue;
3137
+ if (done.has(r.backgroundTaskId) || isOmpBackgroundId(r.backgroundTaskId)) continue;
3138
+ scan ||= scanHostNotifications(ledger.transcriptPath);
3139
+ if (scan.exits.has(r.backgroundTaskId) || scan.notified.has(r.backgroundTaskId)) continue;
3140
+ if (unreleasedOnly && (ledger.waitReleasedFor || []).includes(r.backgroundTaskId)) continue;
3141
+ return r.backgroundTaskId;
3142
+ }
3143
+ return null;
3144
+ }
3145
+
3146
+ function liveBaseLedger(event, current, payload, routeState, harness, fallbackLedger, projectRoot = null) {
3147
+ if (current && routeState?.taskInstanceId && current.taskInstanceId !== routeState.taskInstanceId
3148
+ && routeState.predecessor && current.taskInstanceId === routeState.predecessor.predecessorTaskInstanceId) {
3149
+ const adopted = reconcilePredecessorLedger({ ...routeState, sessionId: routeState.sessionId || payload.session_id || payload.sessionId },
3150
+ current, projectRoot);
3151
+ if (adopted && (adopted.sessionKey === sessionIdentity(payload))) return { ...adopted, harness: adopted.harness || harness };
3152
+ }
2950
3153
  if (event.type === 'receipt') {
2951
3154
  // A missing/foreign route state must never blank the evidence this session already
2952
3155
  // banked. The shared state slot is single-owner (a parallel subagent re-stamps it),
@@ -3074,7 +3277,7 @@ export async function recordLedgerEvent(event, {
3074
3277
  const state = liveState || lockedRouteState;
3075
3278
  lockedRouteState = state || null;
3076
3279
  const current = await readExecutionLedger(projectRoot, payload);
3077
- let ledger = liveBaseLedger(event, current, payload, state, harness, fallbackLedger);
3280
+ let ledger = liveBaseLedger(event, current, payload, state, harness, fallbackLedger, projectRoot);
3078
3281
  // Reconcile pending journaled events first — inside this caller's acquired lock and
3079
3282
  // before its own evidence, so a timed-out writer's receipt is never stranded.
3080
3283
  const drained = await drainJournal(target, { ledger, payload, signal, deadlineMs, projectRoot });
@@ -3135,7 +3338,11 @@ export async function recordLedgerEvent(event, {
3135
3338
  } else if (event.type === 'continuation') {
3136
3339
  ledger = applyContinuationToLedger(ledger, event);
3137
3340
  } else if (event.type === 'notified') {
3138
- ledger = { ...ledger, notified: true, updatedAt: Date.now() };
3341
+ ledger = { ...ledger, notified: true, ...(stateMarker(event) ? { lastBlockState: stateMarker(event) } : {}), updatedAt: Date.now() };
3342
+ } else if (event.type === 'handback') {
3343
+ ledger = applyHandbackToLedger(ledger, event);
3344
+ } else if (event.type === 'wait-released') {
3345
+ ledger = applyWaitReleased(ledger, event);
3139
3346
  } else if (event.type === 'resumable-run') {
3140
3347
  // TASK-005 (FR-005): a resumable-run pointer is the interrupted-run
3141
3348
  // terminal event — emit `outcome.observed` verdict INTERRUPTED exactly
@@ -3360,25 +3567,28 @@ export async function recordExecutionReceipt({
3360
3567
  // verification or operation evidence (completion arrives later, outside this tool event).
3361
3568
  const backgroundLaunchAck = toolName === 'Bash' && isBackgroundLaunchAck(toolResponse);
3362
3569
  const bgCompletion = toolName === 'Read'
3363
- ? await backgroundCompletionFor({ projectRoot, payload, toolInput, toolResponse }) : null;
3364
- const nativeGoal = routeState?.routeSummary?.executionContract?.operationGoal;
3570
+ ? await backgroundCompletionFor({ projectRoot, payload, toolInput, toolResponse, routeState }) : null;
3571
+ // Every native goal of the contract is tried in order; each adapter only recognizes its own domain's commands
3572
+ // (git verbs/ls-remote vs service mutation/deploy script/curl), so a multi-operation task banks both proofs.
3573
+ const nativeGoals = contractOperationGoals(routeState?.routeSummary?.executionContract);
3574
+ // One receipt per matching goal: `git push && ./deploy.sh` banks git-integrity AND service-runtime proofs.
3575
+ const nativeReceipts = backgroundLaunchAck || toolName !== 'Bash' || bashScope.foreign ? []
3576
+ : nativeGoals.map((goal) => bashOperationReceipt(toolInput.command, toolResponse, success, goal, { sessionId: explicitSessionId(payload), harness })).filter(Boolean);
3365
3577
  const operationReceipt = backgroundLaunchAck ? null : cronOperationReceipt(toolName, toolInput, toolResponse, success, { sessionId: explicitSessionId(payload), harness })
3578
+ || nativeReceipts[0]
3366
3579
  || (toolName === 'Bash' && !bashScope.foreign
3367
- ? (bashOperationReceipt(toolInput.command, toolResponse, success, nativeGoal, { sessionId: explicitSessionId(payload), harness })
3368
- || releaseOperationReceipt(toolInput.command, toolResponse, success, { sessionId: explicitSessionId(payload), harness, candidate: cleanTreeCandidate(projectRoot) }))
3580
+ ? releaseOperationReceipt(toolInput.command, toolResponse, success, { sessionId: explicitSessionId(payload), harness, candidate: cleanTreeCandidate(projectRoot) })
3369
3581
  : null);
3582
+ // An absent native exit is not successful execution, even when no error flag was supplied —
3583
+ // except where the host's own contract carries the proof (see hostProvesCleanBashExit).
3584
+ const exitUnproven = toolName === 'Bash' && (!preservesNativeOperationExit(toolInput.command)
3585
+ || malformedNativeExitPayload(payload) || (exitCode === null && !hostProvesCleanBashExit(harness, payload, toolResponse)));
3586
+ const extraOperations = operationReceipt === nativeReceipts[0] ? nativeReceipts.slice(1) : [];
3370
3587
  if (bgCompletion && !bgCompletion.rejected) {
3371
3588
  Object.assign(receipt, bgCompletion);
3372
3589
  } else if (operationReceipt) {
3373
3590
  Object.assign(receipt, operationReceipt);
3374
- // An absent native exit is not successful execution, even when no error flag was supplied —
3375
- // except where the host's own contract carries the proof (see hostProvesCleanBashExit).
3376
- if (toolName === 'Bash' && (!preservesNativeOperationExit(toolInput.command)
3377
- || malformedNativeExitPayload(payload)
3378
- || (exitCode === null && !hostProvesCleanBashExit(harness, payload, toolResponse)))) {
3379
- receipt.exitStatusUnproven = true;
3380
- receipt.success = false;
3381
- }
3591
+ if (exitUnproven) { receipt.exitStatusUnproven = true; receipt.success = false; }
3382
3592
  } else if (routeState?.routeSummary?.executionContract?.stateVerification === true
3383
3593
  && (STATE_OBSERVATION_TOOLS.has(toolName) || (toolName === 'Bash' && !bashScope.foreign && !isVerificationCommand(toolInput.command)))) {
3384
3594
  receipt.kind = 'state';
@@ -3411,8 +3621,9 @@ export async function recordExecutionReceipt({
3411
3621
  // A pipe-masked runner status (exit 0 from `| tail`) is not evidence of a pass.
3412
3622
  const recognizedRunner = isVerificationCommand(toolInput.command);
3413
3623
  const attestedProgram = Boolean(evidence) && !recognizedRunner;
3624
+ const maskDetail = {};
3414
3625
  const maskedStage = recognizedRunner || attestedProgram
3415
- ? maskedVerificationStage(toolInput.command, 0, { attested: attestedProgram }) : null;
3626
+ ? maskedVerificationStage(toolInput.command, 0, { attested: attestedProgram, detail: maskDetail }) : null;
3416
3627
  if (backgroundLaunchAck) receipt.backgroundTaskId = backgroundTaskIdOf(toolResponse);
3417
3628
  if (!backgroundLaunchAck && receipt.success) {
3418
3629
  if (exitCode === 0) receipt.exitProof = 'native-exit';
@@ -3427,7 +3638,7 @@ export async function recordExecutionReceipt({
3427
3638
  } else if (maskedStage && receipt.success) {
3428
3639
  receipt.success = false;
3429
3640
  receipt.exitStatusUnproven = true;
3430
- noteUnprovenExitStatus(maskedStage);
3641
+ noteUnprovenExitStatus(maskedStage, maskDetail);
3431
3642
  } else if (receipt.success && isVerificationCommand(toolInput.command) && malformedNativeExitPayload(payload)) {
3432
3643
  // F-4: a malformed native payload (exit field present but non-numeric/null, or a result
3433
3644
  // container of the wrong type) is unproven input — fail closed, never mint a passing
@@ -3514,14 +3725,16 @@ export async function recordExecutionReceipt({
3514
3725
  receipt.reviewer = pairIdentity(payload.reviewer ?? toolInput.reviewer);
3515
3726
  receipt.reviewVerdict = pairIdentity(payload.reviewVerdict ?? toolInput.reviewVerdict);
3516
3727
 
3517
- return recordLedgerEvent(
3518
- {
3519
- type: 'receipt',
3520
- receipt,
3521
- vibecode: routeState?.routeSummary?.autonomyLevel === 'vibecode',
3522
- },
3523
- { projectRoot, payload, harness, signal, deadlineMs, routeState },
3524
- );
3728
+ const vibecode = routeState?.routeSummary?.autonomyLevel === 'vibecode';
3729
+ const recorded = await recordLedgerEvent({ type: 'receipt', receipt, vibecode },
3730
+ { projectRoot, payload, harness, signal, deadlineMs, routeState });
3731
+ // One receipt event per extra matching goal (same toolUseId). This also bumps receipts.length/receiptSequence,
3732
+ // so the handback stateFingerprint counts the call more than once — it can only change the fingerprint, never seal.
3733
+ for (const extra of extraOperations) {
3734
+ await recordLedgerEvent({ type: 'receipt', vibecode, receipt: { ts: receipt.ts, toolName, toolUseId: receipt.toolUseId, exitCode, ...extra,
3735
+ ...(exitUnproven ? { exitStatusUnproven: true, success: false } : {}) } }, { projectRoot, payload, harness, signal, deadlineMs, routeState });
3736
+ }
3737
+ return recorded;
3525
3738
  }
3526
3739
 
3527
3740
  // F-15: mirror of isExplicitBroadVerificationRequest in
@@ -3937,7 +4150,15 @@ function recoveryInstruction(missingEvidence, ledger = {}, routeSummary = {}, {
3937
4150
  if (!instruction && missingEvidence.includes('integration-verification') && !missingEvidence.includes('write-evidence')) {
3938
4151
  instruction = 'Worker changes are not yet verified together: in this session (not inside a worker), run the routed targeted verification once on the integrated state, after the last worker handback, and inspect its result. A worker\'s own pass does not count.';
3939
4152
  }
3940
- if (!instruction && missingEvidence.includes('write-evidence')) {
4153
+ const pendingJob = pendingBackgroundJob(ledger); // includes a job whose single WAIT was already released
4154
+ const contractKind = String(routeSummary?.executionContract?.taskKind || '').toUpperCase();
4155
+ const noSourceOrder = contractKind === 'OPERATIONAL'
4156
+ || (Boolean(routeSummary?.executionContract?.operationGoal) && hardExpectedSourceFiles(routeSummary).length === 0);
4157
+ if (!instruction && missingEvidence.includes('write-evidence') && (pendingJob || noSourceOrder)) {
4158
+ instruction = pendingJob
4159
+ ? `Background job ${pendingJob} is still pending: wait for its host task-notification, then Read its tasks/${pendingJob}.output through the exit footer. Do not edit source, do not relaunch the job; reconcile the checkpoint evidence instead.`
4160
+ : 'No source change is ordered by this request: do not make an Edit/Write. Reconcile the existing checkpoint evidence or report the handback precisely.';
4161
+ } else if (!instruction && missingEvidence.includes('write-evidence')) {
3941
4162
  if (!ledger.sourceSucceeded) {
3942
4163
  instruction = 'Pull one bounded indexed source slice, then make the requested Edit/Write in this continuation.';
3943
4164
  } else if (ledger.writeAttempted && !ledger.writeSucceeded) {
@@ -4099,8 +4320,9 @@ function scopedContract(state, ledger) {
4099
4320
  goal = { ...goal, completionSemantics: 'ensure-state' };
4100
4321
  }
4101
4322
  }
4102
- return { ...contract, operationGoal: { ...goal,
4103
- scope: goal.scope || (session ? `session:${session}` : null) } };
4323
+ const scoped = (g) => ({ ...g, scope: g.scope || (session ? `session:${session}` : null) });
4324
+ return { ...contract, operationGoal: scoped(goal),
4325
+ ...(Array.isArray(contract.operationGoals) ? { operationGoals: contract.operationGoals.map((g) => (g && typeof g === 'object' ? scoped(g) : g)) } : {}) };
4104
4326
  }
4105
4327
 
4106
4328
  // Gate-time local git truth for the remote-parity proof (cwd-bound, so it lives here, not in the pure evidence module).
@@ -4129,9 +4351,13 @@ function withGitAuthority(ledger, cwd) {
4129
4351
  return gitAuth ? { ...ledger, gitAuthority: gitAuth } : ledger;
4130
4352
  }
4131
4353
 
4132
- function effectiveRequestLedger(state = {}, ledger = {}) {
4354
+ function effectiveRequestLedger(state = {}, ledger = {}, cwd = null) {
4133
4355
  if (state?.sessionId && ledger?.sessionId && state.sessionId !== ledger.sessionId) return {};
4134
4356
  if (state?.taskInstanceId || ledger?.taskInstanceId) {
4357
+ if (state?.predecessor && state?.taskInstanceId && ledger?.taskInstanceId
4358
+ && state.taskInstanceId !== ledger.taskInstanceId) {
4359
+ return reconcilePredecessorLedger(state, ledger, cwd) || {};
4360
+ }
4135
4361
  return state?.taskInstanceId && state.taskInstanceId === ledger?.taskInstanceId ? ledger : {};
4136
4362
  }
4137
4363
  const sameRequest = !ledger?.requestKey || !state?.requestKey
@@ -4213,11 +4439,24 @@ function cleanTreeCandidate(cwd) {
4213
4439
  } catch { return null; }
4214
4440
  }
4215
4441
 
4442
+ function hasNpmTarget(cwd) {
4443
+ try { return fsSync.statSync(path.join(cwd || process.cwd(), 'package.json')).isFile(); } catch { return false; }
4444
+ }
4445
+
4446
+ // A routed native deploy (service-runtime goal on an operational/mixed contract) is proven by the operation
4447
+ // layer (deploy receipt + post-deploy observation), never by the npm registry.
4448
+ function nativeDeployContract(state) {
4449
+ const contract = state?.routeSummary?.executionContract;
4450
+ return contractOperationGoals(contract).some((goal) => goal.domain === 'service-runtime')
4451
+ && ['OPERATIONAL', 'MIXED'].includes(String(contract.taskKind || '').toUpperCase());
4452
+ }
4453
+
4216
4454
  function releasePublicationMissing(state, ledger, cwd) {
4217
4455
  const routedPublication = state?.routeSummary?.executionContract?.publication === true
4218
4456
  && ordersPublication(state?.routingContext?.lastExplicitUserPromptText);
4219
4457
  if (!routedPublication && !promptOrdersNpmPublish(state)
4220
4458
  && !conditionalRepairOrdersPublish(state, ledger, cwd)) return null;
4459
+ if (nativeDeployContract(state) && (!hasNpmTarget(cwd) || !promptOrdersNpmPublish(state))) return null; // operation-verification owns the native deploy proof
4221
4460
  let pkg = null;
4222
4461
  try { pkg = JSON.parse(fsSync.readFileSync(path.join(cwd || process.cwd(), 'package.json'), 'utf8')); } catch { return 'release-publication'; }
4223
4462
  if (!pkg?.name || !pkg?.version) return 'release-publication';
@@ -4310,6 +4549,23 @@ function workingTreeShippedChange(pkg, tagCommit, cwd) {
4310
4549
 
4311
4550
  // Resolve only explicit package-test predicates from native receipts. Unknown
4312
4551
  // predicates, missing currency and evicted receipts remain pending, never false.
4552
+ // The owner deferred this operation behind a condition ("after the restore passes", "sau khi ... dat", "if ...").
4553
+ // Bounded clause check over the folded prompt: a clause that names the goal's operation AND a condition word.
4554
+ const OPERATION_WORDS = { 'service-runtime': /\b(?:deploy|redeploy|restart|trien khai|khoi dong lai|[\w-]+\.sh)\b/, 'git-integrity': /\b(?:commit|push|tag|merge)\b/ };
4555
+ // Real condition heads only: sequencing ("after they pass", trailing "once/when it is up") and concessive
4556
+ // "even if" never defer; "(sau) khi ... dat|pass|xong|ok" is conditional on a result.
4557
+ const DEFERRAL_WORDS = /(?:^|[\s,(:-])(?:only\s+(?:if|when)|if|unless|neu|chi khi|khi nao|(?:sau khi|khi)\s+(?:[^,]{0,60}\s)?(?:dat|pass(?:es)?|xong|ok))\b/;
4558
+ // "check/see/verify if ..." is a probe question (= whether), not a condition on the operation.
4559
+ const PROBE_IF = /\b(?:check|see|verify|confirm|find\s+out|ask|xem|kiem\s+tra)\s+(?:whether|if)\b/g;
4560
+ function operationDeferred(promptText, goal) {
4561
+ const words = OPERATION_WORDS[goal?.domain];
4562
+ if (!words || typeof promptText !== 'string' || !promptText) return false;
4563
+ const folded = promptText.slice(0, 20000).normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/đ/g, 'd').replace(/Đ/g, 'D').toLowerCase();
4564
+ const named = goal.deployCommand ? goal.deployCommand.toLowerCase() : null;
4565
+ return folded.split(/[\n;]+|\.(?=\s|$)/).some((clause) => (named ? clause.includes(named) || words.test(clause) : words.test(clause))
4566
+ && DEFERRAL_WORDS.test(clause.replace(/\beven\s+(?:if|when)\b/g, ' ').replace(PROBE_IF, ' ')));
4567
+ }
4568
+
4313
4569
  function resolveConditionalContract(state, ledger, cwd) {
4314
4570
  const promptText = state?.routingContext?.lastExplicitUserPromptText || '';
4315
4571
  const intent = analyzeTaskIntent({ promptText });
@@ -4344,7 +4600,7 @@ function resolveConditionalContract(state, ledger, cwd) {
4344
4600
  }
4345
4601
  const semantic = analyzeTaskIntent({ promptText: activePrompt }).semantic;
4346
4602
  const { conditionalObligations: _pending, verificationOnly: _verificationOnly,
4347
- statusReport: _statusReport, publication: _publication, operationGoal: _operationGoal, ...base } = state.routeSummary.executionContract;
4603
+ statusReport: _statusReport, publication: _publication, operationGoal: _operationGoal, operationGoals: _operationGoals, ...base } = state.routeSummary.executionContract;
4348
4604
  const contract = applyTaskSemantics(base, semantic);
4349
4605
  return { ...state, routingContext: { ...state.routingContext, lastExplicitUserPromptText: activePrompt,
4350
4606
  ephemeralProjection: { authoritativePromptText: promptText } },
@@ -4364,7 +4620,7 @@ function evaluateCompletionContract({ state = {}, ledger = {}, cwd, phase = null
4364
4620
  // new task's gate (its verification debt stays enforced below) — while the current task's
4365
4621
  // own blocker still ends the run truthfully: complete:false + outcome:'blocked', never a
4366
4622
  // fabricated complete and never another continuation loop.
4367
- const requestLedger = effectiveRequestLedger(state, ledger);
4623
+ const requestLedger = effectiveRequestLedger(state, ledger, cwd);
4368
4624
  if (requestLedger?.blocker) {
4369
4625
  // A blocker minted by the gate itself (verification loop) is the run's exit path — it
4370
4626
  // must be user-visible or the release is indistinguishable from a stall. A blocker
@@ -4460,7 +4716,7 @@ function evaluateCompletionContract({ state = {}, ledger = {}, cwd, phase = null
4460
4716
  // Request identity is the prompt (see evidencePromptKey): the router re-keys requestKey on
4461
4717
  // every Edit/Write, so a requestKey mismatch alone must not discard the evidence — and the
4462
4718
  // continuation budget — the request already accumulated. A different prompt keeps a clean slate.
4463
- const effectiveLedger = effectiveRequestLedger(state, ledger);
4719
+ const effectiveLedger = effectiveRequestLedger(state, ledger, cwd);
4464
4720
  const operationStatus = operationCompletionPolicy(scopedContract(state, effectiveLedger),
4465
4721
  null, withGitAuthority(effectiveLedger, cwd));
4466
4722
  const operationalTask = operationStatus !== null;
@@ -4658,6 +4914,47 @@ function evaluateCompletionContract({ state = {}, ledger = {}, cwd, phase = null
4658
4914
  };
4659
4915
  }
4660
4916
 
4917
+ // WAIT: a host background job owned by this task (or its adopted predecessor) has not completed. Nothing
4918
+ // can be produced by blocking Stop, so release with the job named. It spends no continuation budget, never
4919
+ // demands an Edit/Write, and is not a loop (every Stop with the job pending is a release). Native completion
4920
+ // (host task-notification + Read of the output footer) resumes the next milestone. Owner STOP and blockers
4921
+ // were handled earlier; omp background ids carry no completion protocol and keep UNSUPPORTED_EVIDENCE.
4922
+ {
4923
+ // At most ONE WAIT release per (task, job id): the CLI records it (`wait-released`), after which a job that
4924
+ // is still pending falls back to the normal gate (finite cap, pending-job wording, never an edit demand).
4925
+ const waitingOn = pendingBackgroundJob(effectiveLedger, { unreleasedOnly: true });
4926
+ if (waitingOn) {
4927
+ return { continue: false, notify: true, complete: false, wait: true, outcome: 'waiting', waitingOn, missingEvidence,
4928
+ reason: `UKit WAIT: background job ${waitingOn} is pending. Wait for the same job; do not launch a duplicate. This Stop is released without spending continuation budget and without demanding an edit. Missing ${missingEvidence.join(', ')} until the host task-notification arrives; then Read tasks/${waitingOn}.output through the exit footer and continue with the next milestone (artifact verification, authorized deploy, live verification). Do not relaunch the job.` };
4929
+ }
4930
+ }
4931
+ // Finite handback (one per task state). The state fingerprint covers every owned signal a continuation can
4932
+ // move: receipts, banked write/verification progress, native operation proofs, the working tree and the
4933
+ // unmet obligations. A Stop whose state is unchanged since the previous BLOCK cannot progress by blocking
4934
+ // again, so it releases ONCE with the unmet obligations named (complete:false — missing evidence is never
4935
+ // a pass); a later Stop at the same state is a silent release, never another final or block. Any new
4936
+ // receipt/file change resets this naturally. Vibecode keeps its own explicit liveness breaker.
4937
+ const handbackKey = state?.taskInstanceId || evidencePromptKey(state) || null;
4938
+ const stateFingerprint = handbackKey ? crypto.createHash('sha256').update(JSON.stringify({
4939
+ r: (effectiveLedger?.receipts || []).length, t: (effectiveLedger?.receipts || []).at(-1)?.ts || 0,
4940
+ s: effectiveLedger?.receiptSequence || 0, p: progressDigest(effectiveLedger || {}), o: operationSeq(effectiveLedger),
4941
+ c: contentFingerprint(cwd) || '', m: [...missingEvidence].sort(),
4942
+ })).digest('hex').slice(0, 32) : null;
4943
+ const sameState = (marker) => Boolean(stateFingerprint) && marker?.task === handbackKey && marker.fp === stateFingerprint;
4944
+ const handback = (gateRelease, why, job = null) => ({ continue: false, notify: true, complete: false, outcome: 'handback', gateRelease,
4945
+ missingEvidence, stateFingerprint, handbackKey,
4946
+ reason: `UKit handback: ${why} Unmet task obligation(s): ${missingEvidence.join(', ')}. The task is NOT complete; ${job
4947
+ ? `background job ${job} is still pending — wait for its host task-notification, then Read tasks/${job}.output through the exit footer and continue. Do not relaunch it or edit source meanwhile.`
4948
+ : 'report exactly what is unmet and what the owner must do next, then stop.'} Do not repeat the final report.` });
4949
+ if (!vibecode && sameState(effectiveLedger?.handback)) {
4950
+ // The single handback for this state was already delivered: release silently (nothing new to say).
4951
+ return { continue: false, notify: false, complete: false, outcome: 'handback', gateRelease: 'handback-delivered',
4952
+ missingEvidence: [], unmetEvidence: missingEvidence, stateFingerprint, handbackKey };
4953
+ }
4954
+ // Publication recovery keeps its own owned-receipt progress breaker (runEvaluateStop), with its own wording.
4955
+ if (!vibecode && sameState(effectiveLedger?.lastBlockState) && !missingEvidence.includes('release-publication')) {
4956
+ return handback('no-progress-handback', 'continuation cannot progress — no new receipt, evidence, operation proof or file change since the previous block.', pendingBackgroundJob(effectiveLedger));
4957
+ }
4661
4958
  // Continuation attempts only make sense within the request that minted them: a new
4662
4959
  // routed request in the same session must start with a fresh budget, otherwise a cap
4663
4960
  // exhausted on task A suppresses recovery for task B. A requestKey mismatch within the
@@ -4669,6 +4966,24 @@ function evaluateCompletionContract({ state = {}, ledger = {}, cwd, phase = null
4669
4966
  const continuationCount = staleContinuations
4670
4967
  ? 0
4671
4968
  : Number(effectiveLedger?.continuationCount || 0);
4969
+ // Milestone vs task obligation: when the only unmet debt is a native operation that this task has not
4970
+ // attempted at all, blocking cannot produce its proof. A deferred/conditional operation (the owner made it
4971
+ // wait for a condition) hands back at once; an unconditional one first gets one continuation to attempt it.
4972
+ // Either way the release is complete:false and names the obligation. An ATTEMPTED operation keeps the normal
4973
+ // verification demand (prove the mutation you ran).
4974
+ if (operationalTask && !operationStatus.complete && missingEvidence.length > 0
4975
+ && missingEvidence.every((item) => item === 'operation-verification')
4976
+ && !pendingBackgroundJob(effectiveLedger)) {
4977
+ const unmetGoals = Array.isArray(operationStatus.unmetGoals) ? operationStatus.unmetGoals : contractOperationGoals(scopedContract(state, effectiveLedger));
4978
+ const promptText = state?.routingContext?.lastExplicitUserPromptText || '';
4979
+ if (unmetGoals.length > 0 && !unmetGoals.some((goal) => operationAttempted(goal, effectiveLedger))
4980
+ // Unconditional: only after a continuation issued while operation-verification was the SOLE unmet item.
4981
+ && ((effectiveLedger?.lastBlockState?.op === true && effectiveLedger.lastBlockState.task === handbackKey)
4982
+ || unmetGoals.every((goal) => operationDeferred(promptText, goal)))) {
4983
+ const names = unmetGoals.map((goal) => `${goal.domain}${goal.deployCommand ? ` (${goal.deployCommand})` : ''}${goal.requiredTargets?.length ? ` [${goal.requiredTargets.join(', ')}]` : ''}`).join('; ');
4984
+ return handback('operation-not-attempted', `no native mutation for ${names} was attempted by this task, so its proof cannot exist yet (deferred, conditional, or awaiting its prerequisite).`);
4985
+ }
4986
+ }
4672
4987
  if (!vibecode && continuationCount >= MAX_CONTINUATIONS) {
4673
4988
  if (effectiveLedger?.notified === true) {
4674
4989
  return {
@@ -4676,6 +4991,7 @@ function evaluateCompletionContract({ state = {}, ledger = {}, cwd, phase = null
4676
4991
  capped: true,
4677
4992
  notify: true,
4678
4993
  missingEvidence,
4994
+ stateFingerprint, handbackKey,
4679
4995
  ...(playbookId === BUGFIX_PLAYBOOK_ID ? { outcome: 'inconclusive' } : {}),
4680
4996
  reason: `UKit continuation cap reached with missing evidence: ${missingEvidence.join(', ')}.`,
4681
4997
  };
@@ -4686,6 +5002,7 @@ function evaluateCompletionContract({ state = {}, ledger = {}, cwd, phase = null
4686
5002
  notify: true,
4687
5003
  capped: true,
4688
5004
  missingEvidence,
5005
+ stateFingerprint, handbackKey,
4689
5006
  ...(playbookId === BUGFIX_PLAYBOOK_ID ? { outcome: 'blocked' } : {}),
4690
5007
  reason: `UKit stopping with unfinished work: ${missingEvidence.join(', ')}. Tell the user what is unfinished and stop; do not continue further.`,
4691
5008
  };
@@ -4730,10 +5047,13 @@ function evaluateCompletionContract({ state = {}, ledger = {}, cwd, phase = null
4730
5047
  return { continue: false, notify: true, complete: false, outcome: 'blocked', missingEvidence,
4731
5048
  reason: 'UKit publication BLOCKED: the current owner prompt prohibits publication. No authorized publication action remains; do not retry or infer permission from missing evidence.' };
4732
5049
  }
5050
+ const pendingJobId = operationalTask ? pendingBackgroundJob(effectiveLedger) : null;
4733
5051
  const instruction = publicationPending
4734
5052
  ? prerequisites.length > 0
4735
5053
  ? `Complete the permitted prerequisites first (${prerequisites.join(', ')}). ${recoveryInstruction(prerequisites, effectiveLedger, routeSummary, { cwd })} Do not publish before mandatory verification and separate execution authorization are established.`
4736
5054
  : '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.'
5055
+ : operationalTask && pendingJobId
5056
+ ? `Background job ${pendingJobId} is still pending: wait for its host task-notification, then Read its tasks/${pendingJobId}.output through the exit footer. Do not edit source and do not relaunch the job.`
4737
5057
  : operationalTask
4738
5058
  ? 'Inspect native mutation receipts and verify the requested operational state; do not fabricate source edits or source-test evidence.'
4739
5059
  : recoveryInstruction(missingEvidence, effectiveLedger, routeSummary, { cwd });
@@ -4741,6 +5061,7 @@ function evaluateCompletionContract({ state = {}, ledger = {}, cwd, phase = null
4741
5061
  continue: true,
4742
5062
  missingEvidence,
4743
5063
  noProgressCount,
5064
+ stateFingerprint, handbackKey,
4744
5065
  ...(playbookId === BUGFIX_PLAYBOOK_ID ? { outcome: 'blocked' } : {}),
4745
5066
  reason: [
4746
5067
  `UKit completion gate: missing ${missingEvidence.join(', ')}.`,
@@ -4759,7 +5080,7 @@ function featureRunContext({ state = {}, ledger = {}, cwd } = {}) {
4759
5080
  const routeSummary = state?.routeSummary || {};
4760
5081
  const playbookId = routeSummary.playbookId || null;
4761
5082
  if (playbookId !== playbookExecution.FEATURE_PLAYBOOK_ID) return null;
4762
- const owned = effectiveRequestLedger(state, ledger) || {};
5083
+ const owned = effectiveRequestLedger(state, ledger, cwd) || {};
4763
5084
  const trace = buildPlaybookTrace(owned, playbookId);
4764
5085
  const run = owned.playbookRun || null;
4765
5086
  return { routeSummary, playbookId, owned, trace, run, cwd, host: owned.harness || ledger?.harness || null };
@@ -4849,7 +5170,7 @@ function playbookStopAdvisory({ state = {}, ledger = {}, cwd } = {}, result = {}
4849
5170
  const routeSummary = state?.routeSummary || {};
4850
5171
  const playbookId = routeSummary.playbookId || null;
4851
5172
  if (!playbookId || playbookId === BUGFIX_PLAYBOOK_ID) return null;
4852
- const effectiveLedger = effectiveRequestLedger(state, ledger);
5173
+ const effectiveLedger = effectiveRequestLedger(state, ledger, cwd);
4853
5174
  if (effectiveLedger.writeAttempted !== true) return null;
4854
5175
  const trace = buildPlaybookTrace(effectiveLedger, playbookId);
4855
5176
  const stepNote = playbookTraceMissingSteps(trace).length === 0 ? null
@@ -4867,7 +5188,7 @@ export function evaluateCompletion(args = {}) {
4867
5188
  const result = evaluateCompletionContract(args);
4868
5189
  // Explain the verdict from the SAME task-scoped snapshot used by the verifier. These are proof summaries,
4869
5190
  // not an alternative evidence source; a diagnostic must never satisfy or relax an obligation.
4870
- const owned = effectiveRequestLedger(args.state, args.ledger) || {};
5191
+ const owned = effectiveRequestLedger(args.state, args.ledger, args.cwd) || {};
4871
5192
  const diagnostics = {
4872
5193
  taskInstanceId: args.state?.taskInstanceId || null,
4873
5194
  contract: args.state?.routeSummary?.executionContract?.taskKind || args.state?.routeSummary?.taskKind || args.state?.routeSummary?.executionMode || null,
@@ -4903,24 +5224,38 @@ export function evaluateCompletion(args = {}) {
4903
5224
  return result;
4904
5225
  }
4905
5226
 
4906
- export async function incrementContinuation(projectRoot, payload = {}, ledger = null, requestKey = null, promptKey = null, { signal, deadlineMs } = {}) {
5227
+ export async function incrementContinuation(projectRoot, payload = {}, ledger = null, requestKey = null, promptKey = null, { signal, deadlineMs, stateFp, taskKey, opOnly } = {}) {
4907
5228
  // Locked (and fail-closed) via recordLedgerEvent: parallel subagents firing Stop hooks
4908
5229
  // share one ledger file, and a stale-snapshot rewrite would reset each other's
4909
5230
  // continuationCount. An expired lock wait journals the increment instead of running
4910
5231
  // the read-modify-write unlocked.
4911
5232
  return recordLedgerEvent(
4912
- { type: 'continuation', requestKey, promptKey },
5233
+ { type: 'continuation', requestKey, promptKey, ...(stateFp && taskKey ? { stateFp, taskKey, opOnly: opOnly === true } : {}) },
4913
5234
  { projectRoot, payload, fallbackLedger: ledger, signal, deadlineMs },
4914
5235
  );
4915
5236
  }
4916
5237
 
4917
- export async function markNotified(projectRoot, payload = {}, ledger = null, { signal, deadlineMs } = {}) {
5238
+ export async function markNotified(projectRoot, payload = {}, ledger = null, { signal, deadlineMs, stateFp, taskKey } = {}) {
4918
5239
  return recordLedgerEvent(
4919
- { type: 'notified' },
5240
+ { type: 'notified', ...(stateFp && taskKey ? { stateFp, taskKey } : {}) },
4920
5241
  { projectRoot, payload, fallbackLedger: ledger, signal, deadlineMs },
4921
5242
  );
4922
5243
  }
4923
5244
 
5245
+ // Persist the single finite handback for a task state (idempotent: same task + fingerprint = same marker).
5246
+ export async function markHandback(projectRoot, payload = {}, result = {}, { signal, deadlineMs } = {}) {
5247
+ if (!result?.stateFingerprint || !result.handbackKey) return null;
5248
+ return recordLedgerEvent(
5249
+ { type: 'handback', stateFp: result.stateFingerprint, taskKey: result.handbackKey },
5250
+ { projectRoot, payload, signal, deadlineMs },
5251
+ );
5252
+ }
5253
+
5254
+ // Records the single WAIT release for a pending background job (bounds WAIT to one Stop per job).
5255
+ export async function noteWaitReleased(projectRoot, payload = {}, jobId, { signal, deadlineMs } = {}) {
5256
+ return recordLedgerEvent({ type: 'wait-released', jobId }, { projectRoot, payload, signal, deadlineMs });
5257
+ }
5258
+
4924
5259
  // omp's session_stop carries no stop_hook_active marker, so reentrancy must be detected from
4925
5260
  // the ledger itself: a stop whose recovery turn produced no new receipts is the reentrant
4926
5261
  // shape Claude Code flags natively. The fingerprint deliberately excludes continuation
@@ -5057,7 +5392,7 @@ async function writeSeal(projectRoot, payload, state, result, ledger) {
5057
5392
  await writeJsonAtomic(file, Object.fromEntries(keep));
5058
5393
  }
5059
5394
 
5060
- const CLASSIFIER_OWNED_FIELDS = ['publication', 'operationGoal', 'configurationScope', 'releasePolicy', 'conditionalObligations', 'reportArtifact', 'verificationOnly', 'statusReport'];
5395
+ const CLASSIFIER_OWNED_FIELDS = ['publication', 'operationGoal', 'operationGoals', 'configurationScope', 'releasePolicy', 'conditionalObligations', 'reportArtifact', 'verificationOnly', 'statusReport'];
5061
5396
 
5062
5397
  // Re-derive a router-classified contract from the task's own explicit prompt. Only a contract
5063
5398
  // this router classified itself (contractOrigin 'classified') is eligible: system-carried,
@@ -5140,9 +5475,12 @@ async function runEvaluateStop() {
5140
5475
  const progress = await noteStopProgress(projectRoot, payload);
5141
5476
  if (progress?.value?.reentrant === true) {
5142
5477
  result = { ...result, continue: false, notify: true, complete: false, outcome: 'blocked',
5143
- reason: `UKit publication recovery BLOCKED: no new owned receipts since the previous Stop. Missing ${result.missingEvidence.join(', ')}. Do not repeat evidence requests or retry publication; report the unavailable authorization/prerequisite with task provenance. [task=${state?.taskInstanceId || 'unknown'}]` };
5478
+ reason: `UKit publication recovery BLOCKED: no new owned receipts since the previous Stop. Missing ${result.missingEvidence.join(', ')}${hasNpmTarget(projectRoot) ? '' : ' (this project has no npm package target: the missing layer is a native deploy receipt plus a post-deploy verification, not an npm registry proof)'}. Do not repeat evidence requests or retry publication; report the unavailable authorization/prerequisite with task provenance. [task=${state?.taskInstanceId || 'unknown'}]` };
5144
5479
  }
5145
5480
  }
5481
+ if (result.wait === true && result.waitingOn) {
5482
+ try { await noteWaitReleased(projectRoot, payload, result.waitingOn); } catch { /* an unrecorded release only repeats one WAIT */ }
5483
+ }
5146
5484
  if (result.continue === true && !result.finalNotice) {
5147
5485
  try {
5148
5486
  const seal = await readSeal(projectRoot, payload, state?.taskInstanceId);
@@ -5225,9 +5563,19 @@ async function runEvaluateStop() {
5225
5563
  // is guaranteed elsewhere — non-vibecode routes end at the continuation cap (final-notice
5226
5564
  // block -> capped visible release), and vibecode ends on the visible verification-loop
5227
5565
  // blocker.
5566
+ if (result.gateRelease === 'handback-delivered') {
5567
+ // The one handback for this state was already shown: no message, but never a silent success either.
5568
+ process.stdout.write(`${JSON.stringify({ outcome: 'blocked', complete: false, gateRelease: 'handback-delivered' })}\n`);
5569
+ return;
5570
+ }
5571
+ if (!result.continue && (result.outcome === 'handback' || result.capped === true)) {
5572
+ try { await markHandback(projectRoot, payload, result); } catch { /* an unrecorded marker only repeats one handback */ }
5573
+ }
5228
5574
  if (result.continue) {
5229
- if (result.finalNotice) await markNotified(projectRoot, payload, ledger);
5230
- else await incrementContinuation(projectRoot, payload, ledger, state?.requestKey || null, evidencePromptKey(state));
5575
+ const marker = { stateFp: result.stateFingerprint, taskKey: result.handbackKey,
5576
+ opOnly: result.missingEvidence?.length > 0 && result.missingEvidence.every((item) => item === 'operation-verification') };
5577
+ if (result.finalNotice) await markNotified(projectRoot, payload, ledger, marker);
5578
+ else await incrementContinuation(projectRoot, payload, ledger, state?.requestKey || null, evidencePromptKey(state), marker);
5231
5579
  if (result.missingEvidence?.includes('release-publication')) await noteStopProgress(projectRoot, payload);
5232
5580
  // Provenance: the harness will re-inject this reason as a prompt. Bind it to this
5233
5581
  // session+task+exact-reason (hash) so the router can recognise our own continuation
@@ -5251,7 +5599,7 @@ async function runEvaluateStop() {
5251
5599
  const message = result.playbookAdvisory ? `${result.reason} ${result.playbookAdvisory}` : result.reason;
5252
5600
  process.stderr.write(`[ukit-completion] ${result.reason}\n`);
5253
5601
  process.stdout.write(`${JSON.stringify({ systemMessage: message,
5254
- ...(result.outcome === 'blocked' ? { outcome: 'blocked', complete: false } : {}),
5602
+ ...(result.outcome === 'blocked' || result.outcome === 'handback' ? { outcome: 'blocked', complete: false } : {}),
5255
5603
  })}\n`);
5256
5604
  return;
5257
5605
  }