@ngockhoale/ukit 3.4.81 → 3.4.83

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.
@@ -48,7 +48,19 @@ source "$SCRIPT_DIR/../ukit/runtime/hook-telemetry.sh" 2>/dev/null || true
48
48
  ukit_emit_input_degraded advisory "task-watchdog"
49
49
  fi
50
50
  # BUG-C21-01: a truncated/stalled staged payload must be announced (SPEC §8), never silently passed.
51
- ukit_input_degraded && ukit_emit_input_degraded advisory "task-watchdog"
51
+ # Exception: a payload cut ONLY by the 64 KiB size cap (not a stall) for PostToolUse. That path reads
52
+ # nothing but hook_event_name from the payload (tasks/state/config all come from disk), so a size-truncated
53
+ # payload is not incomplete for this hook. The event name is recovered only when provably complete
54
+ # (ukit_salvage_tool_field); anything else - stall, unrecoverable name, non-PostToolUse (Stop forwards the
55
+ # raw payload to the coordinator) - keeps the announced degrade.
56
+ UKIT_WD_SALVAGED_EVENT=""
57
+ if ukit_input_degraded; then
58
+ if [ "${UKIT_HOOK_INPUT_STALLED:-0}" != "1" ] && [ -n "${UKIT_INPUT_FILE:-}" ]; then
59
+ __ukit_wd_event="$(ukit_salvage_tool_field "$UKIT_INPUT_FILE" hook_event_name 2>/dev/null)" || __ukit_wd_event=""
60
+ [ "$__ukit_wd_event" = "PostToolUse" ] && UKIT_WD_SALVAGED_EVENT="PostToolUse"
61
+ fi
62
+ [ -n "$UKIT_WD_SALVAGED_EVENT" ] || ukit_emit_input_degraded advisory "task-watchdog"
63
+ fi
52
64
  else
53
65
  # 64 KiB cap and the advisory degrade path alive.
54
66
  # Runtime helper missing (pre-install tree): the SAME bounded staging,
@@ -89,7 +101,7 @@ else
89
101
  fi
90
102
  PROJECT_ROOT="${CLAUDE_PROJECT_DIR:-$PWD}"
91
103
 
92
- INPUT_FILE="$UKIT_INPUT_FILE" PROJECT_ROOT="$PROJECT_ROOT" node <<'NODE' || true
104
+ INPUT_FILE="$UKIT_INPUT_FILE" PROJECT_ROOT="$PROJECT_ROOT" SALVAGED_EVENT="${UKIT_WD_SALVAGED_EVENT:-}" node <<'NODE' || true
93
105
  'use strict';
94
106
 
95
107
  const fsp = require('fs/promises');
@@ -124,7 +136,11 @@ setTimeout(() => process.exit(0), HOOK_DEADLINE_MS).unref();
124
136
  }
125
137
  })();
126
138
 
127
- const hookEvent = typeof payload.hook_event_name === 'string' ? payload.hook_event_name : '';
139
+ // A size-truncated payload fails JSON.parse; the wrapper then passes the provably-complete
140
+ // PostToolUse event name it salvaged (the only payload field this path uses).
141
+ const hookEvent = typeof payload.hook_event_name === 'string'
142
+ ? payload.hook_event_name
143
+ : (process.env.SALVAGED_EVENT === 'PostToolUse' ? 'PostToolUse' : '');
128
144
  const projectRoot = process.env.PROJECT_ROOT || process.cwd();
129
145
 
130
146
  // Silent degrade for non-relevant events — same posture as every other
@@ -212,8 +212,8 @@
212
212
  "hooks": [
213
213
  {
214
214
  "type": "command",
215
- "command": "node \"$CLAUDE_PROJECT_DIR/.claude/ukit/runtime/hook-chain-runner.mjs\" --emit-verdict - \"$CLAUDE_PROJECT_DIR/.claude/hooks/completion-gate.sh\":8",
216
- "timeout": 18
215
+ "command": "node \"$CLAUDE_PROJECT_DIR/.claude/ukit/runtime/hook-chain-runner.mjs\" --emit-verdict - \"$CLAUDE_PROJECT_DIR/.claude/hooks/completion-gate.sh\":12",
216
+ "timeout": 22
217
217
  }
218
218
  ]
219
219
  }
@@ -98,7 +98,9 @@ function classifyAllowRules({ allow, managedRules, auditRules, denyTokens }) {
98
98
  }
99
99
  const token = parsed[1];
100
100
  const base = token.includes('/') ? token.slice(token.lastIndexOf('/') + 1) : token;
101
- if (!denyTokens.has(base)) {
101
+ // A token starting with `-` is an option fragment, never a binary (leftover of the
102
+ // old whitespace tokenizer); it is junk by shape. Provenance gates below still apply.
103
+ if (!token.startsWith('-') && !denyTokens.has(base)) {
102
104
  skips.push({ rule, reason: 'not a UKit auto-allow denylist token — left in place' });
103
105
  continue;
104
106
  }
@@ -4596,6 +4596,9 @@ const GREETING_CORE_TOKENS = new Set([
4596
4596
  'hi', 'hello', 'hey', 'yo', 'chao', 'xin', 'good',
4597
4597
  'morning', 'afternoon', 'evening',
4598
4598
  'thanks', 'thank', 'cam', 'on', 'bye', 'tam', 'biet',
4599
+ // Bare acknowledgements ("ok", "có", "được rồi", "yes") are social turns, not work orders:
4600
+ // they must never mint a fresh implementation contract (3.4.81 audit).
4601
+ 'ok', 'okay', 'oke', 'yes', 'yep', 'yeah', 'co', 'duoc', 'vang', 'da', 'u', 'uh', 'um', 'roi', 'dong', 'y',
4599
4602
  ]);
4600
4603
  const GREETING_FILLER_TOKENS = new Set([
4601
4604
  'you', 'u', 'there', 'guys', 'everyone', 'all',
@@ -4616,7 +4619,11 @@ function isPureGreetingPrompt({ promptText = '', commandText = '', targetFile =
4616
4619
  const tokens = foldRouteText(raw).replace(/[^a-z0-9\s]/g, ' ').split(/\s+/).filter(Boolean);
4617
4620
  if (tokens.length === 0 || tokens.length > 6) return false;
4618
4621
  let coreHit = false;
4619
- for (const token of tokens) {
4622
+ for (let i = 0; i < tokens.length; i += 1) {
4623
+ const token = tokens[i];
4624
+ // Tone-folding makes "đóng" (close) and "đồng" (as in "đồng ý", agreed) the same token:
4625
+ // only the pair "dong y" is an acknowledgement; "đóng nhé" is an order to close something.
4626
+ if (token === 'dong' && tokens[i + 1] !== 'y') return false;
4620
4627
  if (GREETING_CORE_TOKENS.has(token)) {
4621
4628
  coreHit = true;
4622
4629
  } else if (!GREETING_FILLER_TOKENS.has(token)) {
@@ -4865,8 +4872,16 @@ export function classifyAdvisorRequest({ promptText = '', commandText = '' } = {
4865
4872
  // Used by hasAdvisoryOnlyAssertion (assertion + no order → advisory) and by
4866
4873
  // the question-shape gate below (question + no order → consult, even when the
4867
4874
  // subject vocabulary fires debug/failure/implement signal scores).
4875
+ // Tone-folding turns unrelated Vietnamese words into mutation verbs: "cái" (this/thing) -> cai (cài),
4876
+ // "chính" (main/exactly) -> chinh (chỉnh), "Việt" -> viet (viết), "đợi/đời/đối/đội/đôi/đói" -> doi (đổi),
4877
+ // "cháy/chảy" -> chay (chạy), "sữa" -> sua (sửa), "thèm" -> them (thêm). Mask the toned non-verbs BEFORE
4878
+ // folding, so "Cái này là gì, tại sao…" is not read as an install order (3.4.81 telemetry audit).
4879
+ function maskTonedNonVerbs(text = '') {
4880
+ return String(text ?? '').normalize('NFC')
4881
+ .replace(/(?<![\p{L}\p{N}_])(?:cái|chính|việt|cháy|chảy|đợi|đời|đối|đội|đôi|đói|sữa|thèm)(?![\p{L}\p{N}_])/giu, ' _ ');
4882
+ }
4868
4883
  function hasMutationOrder({ promptText = '', commandText = '' } = {}) {
4869
- const folded = `${promptText ?? ''}\n${commandText ?? ''}`
4884
+ const folded = `${maskTonedNonVerbs(promptText)}\n${commandText ?? ''}`
4870
4885
  .toLowerCase()
4871
4886
  .normalize('NFD')
4872
4887
  .replace(/[\u0300-\u036f]/g, '')
@@ -4919,6 +4934,11 @@ function hasMutationOrder({ promptText = '', commandText = '' } = {}) {
4919
4934
  .replace(new RegExp(`\\b(?:neu|if)\\s+${TAIL}`, 'g'), ' ')
4920
4935
  // 'đối chiếu' (cross-check) folds to 'doi chieu' and is not the verb 'đổi' (change).
4921
4936
  .replace(/\bdoi\s+chieu\b/g, ' ')
4937
+ // Field telemetry (3.4.81 audit): words that fold onto a mutation verb but name no order.
4938
+ // "chưa được cấp quyền cập nhật" / "no permission to update" reports a missing permission (read-only
4939
+ // banners); "gì thêm [nữa]" / "thêm nữa không" mean "anything else", never the verb "add".
4940
+ .replace(/\b(?:(?:chua|khong)\s+(?:duoc\s+)?(?:cap\s+|co\s+)?quyen|(?:no|not\s+have|without|lacks?)\s+permission\s+to)\s+(?:implement|apply|update|modify|add|create|ship|deliver|fix|refactor|remove|delete|rename|change|write|build|make|install|run|deploy|execute|edit|sua|them|tao|xoa|doi|thay\s+the|cap\s+nhat|viet|chay|cai|chinh|trien\s+khai|cau\s+hinh)(?![a-z0-9_])/g, ' ')
4941
+ .replace(/(?<=\b(?:con|co)\b[^.?!,;:\n]{0,40})\b(?:gi|nao)\s+them(?:\s+nua)?(?:\s+(?:khong|ko))?\s*(?=[?.!,;:\n]|$)|\bthem\s+nua\s+(?:khong|ko)\s*(?=[?.!\n]|$)/g, ' ')
4922
4942
  // R2: a deferred/future clause ("chua sua", "how we would later implement", "R2 onward: ...",
4923
4943
  // "fix strategy ...") describes work for a LATER round, not an order for this turn.
4924
4944
  .replace(new RegExp(`\\bchua\\s+(?:sua|fix|implement|trien\\s+khai|viet|thay\\s+doi)\\b${WAIT_TAIL}`, 'g'), ' ')
@@ -5019,6 +5039,11 @@ function deriveExecutionMode({
5019
5039
  const questionShapedPrompt = /\?\s*$/.test(trimmedPromptText)
5020
5040
  || leadingInterrogative
5021
5041
  || /\b(?:la gi|duoc khong)\s*$/.test(foldedPromptText)
5042
+ // Field telemetry (3.4.81 audit): a what-is question mid-prompt ("… là gì, …") and a leading
5043
+ // explanation request ("giải thích …", "explain …") ask for an answer. Both still pass the
5044
+ // hasMutationOrder/targetFile veto below, so "giải thích rồi sửa luôn" stays an order.
5045
+ || /\bla gi\s*(?:[,.?!;:\n]|$)/.test(foldedPromptText)
5046
+ || /^(?:hay\s+|vui\s+long\s+|lam\s+on\s+|please\s+)?(?:giai\s+thich|explain)\b/.test(foldedPromptText)
5022
5047
  // C85-019: Vietnamese status/consult tails without a '?' — "… chưa",
5023
5048
  // "… chưa nhỉ", "… không nhỉ", "… đúng không", "… à". A question about a
5024
5049
  // defect must not mint the bug-fix floor's write/repro debt (user-reported
@@ -1095,13 +1095,61 @@ async function backgroundCompletionFor({ projectRoot, payload, toolInput, toolRe
1095
1095
  };
1096
1096
  }
1097
1097
 
1098
- function noteUnprovenExitStatus(stage, detail = null) {
1098
+ // Field telemetry (3.4.81 audit): ~60% of unproven-verification gate blocks were a runner piped into
1099
+ // tail/grep/tee, another ~15% a "; echo exit=$?" consumer — and sessions then repeated the same masked
1100
+ // shape, because the notice named the gap but not a command that closes it. Derive ONE concrete rerun and
1101
+ // offer it only when this same classifier proves it unmasked; otherwise return null and the caller keeps
1102
+ // the generic wording. Guidance only: nothing here changes what counts as proof.
1103
+ // Label for a verification command inside a gate message. A fixed 80-char prefix cut real commands in front of
1104
+ // the runner (`cd <root> && PYTHONPATH=. venv/bin/python3.12 -` — the `-m pytest … | grep … | tail` was gone),
1105
+ // so the message named a command the agent never ran and hid the pipe that made it unproven. Keep the whole
1106
+ // command when it is short; otherwise keep both ends, because the masking wrapper (`| tail`, `; echo $?`) is
1107
+ // at the end. Single line, backticks neutralised so the label cannot break out of its code span.
1108
+ export function verificationCommandLabel(command, max = 240) {
1109
+ const text = String(command || '').replace(/\s+/g, ' ').trim().replace(/`/g, "'");
1110
+ if (text.length <= max) return text;
1111
+ const tail = Math.floor(max / 3);
1112
+ return `${text.slice(0, max - tail - 3)} … ${text.slice(-tail)}`;
1113
+ }
1114
+
1115
+ function provableRerunCommand(command) {
1116
+ const original = String(command || '').trim();
1117
+ if (!original || original.length > 400 || /\n/.test(original)) return null;
1118
+ try {
1119
+ const detail = {};
1120
+ const stage = maskedVerificationStage(original, 0, { detail });
1121
+ if (!stage) return null;
1122
+ const candidates = [];
1123
+ // Pipe without pipefail: the same command keeps its output filter and gains the runner's status.
1124
+ if (detail.runner && stage === detail.runner) candidates.push(`set -o pipefail; ${original}`);
1125
+ // Sequential consumer / status echo: the command up to and including the runner is the proof.
1126
+ // The leading part (`cd pkg &&`, env assignments) is kept — the bare runner would run elsewhere.
1127
+ const at = detail.runner ? original.indexOf(detail.runner) : -1;
1128
+ if (at >= 0) {
1129
+ const head = original.slice(0, at + detail.runner.length).trim();
1130
+ const count = (re) => (head.match(re) || []).length;
1131
+ const balanced = count(/\(/g) === count(/\)/g) && count(/\{/g) === count(/\}/g)
1132
+ && count(/"/g) % 2 === 0 && count(/'/g) % 2 === 0 && count(/`/g) % 2 === 0;
1133
+ // A second runner after this one would be dropped by the suggestion: offer nothing then.
1134
+ const rest = original.slice(at + detail.runner.length).replace(/^[\s;&|]+/, '');
1135
+ if (balanced && !(rest && isVerificationCommand(rest))) candidates.push(head);
1136
+ }
1137
+ for (const candidate of candidates) {
1138
+ if (candidate.length <= 400 && isVerificationCommand(candidate) && maskedVerificationStage(candidate) === null) return candidate;
1139
+ }
1140
+ } catch { /* guidance is best-effort */ }
1141
+ return null;
1142
+ }
1143
+
1144
+ function noteUnprovenExitStatus(stage, detail = null, command = null) {
1099
1145
  if (!ledgerMessageEmitter) return;
1146
+ const rerun = provableRerunCommand(command);
1100
1147
  const named = detail?.runner
1101
1148
  ? `runner \`${detail.runner}\`${detail.consumer ? ` (masked by \`${detail.consumer}\`, which is not the runner)` : ''}` : `\`${stage}\``;
1102
1149
  const message =
1103
1150
  `UKit execution-ledger: runner exit status is unproven for ${named} — `
1104
1151
  + 'the shell wrapper may mask or skip the runner; it is NOT counted as passing verification. '
1152
+ + (rerun ? `Run exactly this instead, once: \`${rerun}\` — ` : '')
1105
1153
  + '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.';
1106
1154
  try {
1107
1155
  ledgerMessageEmitter(`${JSON.stringify({ systemMessage: message })}\n`);
@@ -1134,7 +1182,22 @@ const VERDICT_KINDS = new Set(['live-verified', 'test-verified', 'check-only', '
1134
1182
  const VERDICT_SATISFYING_KINDS = new Set(['test-verified', 'live-verified']);
1135
1183
  const MAX_VERDICT_HISTORY = 8;
1136
1184
 
1137
- function gitOutput(args, cwd) {
1185
+ // One `--evaluate-stop` run asks git the same read-only questions many times (HEAD up to 8x, the content
1186
+ // fingerprint up to 4x at 4 spawns each: ~31 spawns per stop). Under load that alone exceeded the
1187
+ // coordinator's evaluator budget, and the stop was reported as an evaluator failure (telemetry: 205+ blocks,
1188
+ // rising monthly). The memo exists ONLY inside one evaluate-stop process (enabled by runEvaluateStop), which
1189
+ // never mutates the work tree: same question, same instant, same answer. Receipt capture and every other
1190
+ // entry point stay unmemoized. A null (git failure) is memoized too: it stays fail-closed.
1191
+ let gitMemo = null;
1192
+ function memoGit(key, compute) {
1193
+ if (!gitMemo) return compute();
1194
+ if (gitMemo.has(key)) return gitMemo.get(key);
1195
+ const value = compute();
1196
+ gitMemo.set(key, value);
1197
+ return value;
1198
+ }
1199
+ function gitOutput(args, cwd) { return memoGit(`out\0${cwd}\0${args.join('\0')}`, () => gitOutputRaw(args, cwd)); }
1200
+ function gitOutputRaw(args, cwd) {
1138
1201
  try {
1139
1202
  const out = execFileSync('git', args, {
1140
1203
  cwd,
@@ -1190,7 +1253,8 @@ function bashWorkspaceScope(command, projectRoot, shellCwd) {
1190
1253
  // differs from the one recorded at the previous receipt. Any git failure, timeout or
1191
1254
  // oversize diff yields null, and null never creates evidence (fail-closed). Untracked files
1192
1255
  // are deliberately excluded: runtime state under .ukit/ would otherwise look like a change.
1193
- function workspaceFingerprint(cwd) {
1256
+ function workspaceFingerprint(cwd) { return memoGit(`ws\0${cwd}`, () => workspaceFingerprintRaw(cwd)); }
1257
+ function workspaceFingerprintRaw(cwd) {
1194
1258
  if (!cwd) return null;
1195
1259
  try {
1196
1260
  const run = (args) => execFileSync('git', args, {
@@ -1257,7 +1321,8 @@ function promptNamesBookkeepingFile(state, file) {
1257
1321
  return promptNamesBookkeeping(state);
1258
1322
  }
1259
1323
 
1260
- function contentFingerprint(cwd) {
1324
+ function contentFingerprint(cwd) { return memoGit(`content\0${cwd}`, () => contentFingerprintRaw(cwd)); }
1325
+ function contentFingerprintRaw(cwd) {
1261
1326
  if (!cwd) return null;
1262
1327
  try {
1263
1328
  const opts = { cwd, stdio: ['ignore', 'pipe', 'ignore'], timeout: 4000, maxBuffer: 64 * 1024 * 1024 };
@@ -1288,7 +1353,8 @@ function contentFingerprint(cwd) {
1288
1353
  } catch { return null; }
1289
1354
  }
1290
1355
 
1291
- function verificationDirtyFingerprint(cwd) {
1356
+ function verificationDirtyFingerprint(cwd) { return memoGit(`dirty\0${cwd}`, () => verificationDirtyFingerprintRaw(cwd)); }
1357
+ function verificationDirtyFingerprintRaw(cwd) {
1292
1358
  try {
1293
1359
  const paths = ['.', ...VERIFICATION_FINGERPRINT_EXCLUDES];
1294
1360
  const options = { cwd, stdio: ['ignore', 'pipe', 'ignore'], timeout: 1500, maxBuffer: 16 * 1024 * 1024 };
@@ -3638,7 +3704,7 @@ export async function recordExecutionReceipt({
3638
3704
  } else if (maskedStage && receipt.success) {
3639
3705
  receipt.success = false;
3640
3706
  receipt.exitStatusUnproven = true;
3641
- noteUnprovenExitStatus(maskedStage, maskDetail);
3707
+ noteUnprovenExitStatus(maskedStage, maskDetail, toolInput.command);
3642
3708
  } else if (receipt.success && isVerificationCommand(toolInput.command) && malformedNativeExitPayload(payload)) {
3643
3709
  // F-4: a malformed native payload (exit field present but non-numeric/null, or a result
3644
3710
  // container of the wrong type) is unproven input — fail closed, never mint a passing
@@ -4200,7 +4266,8 @@ function recoveryInstruction(missingEvidence, ledger = {}, routeSummary = {}, {
4200
4266
  ? `Background verification ${id} has no ingested completion (pending or unsupported host evidence). Wait for the same job and its host task-notification; do not launch a duplicate. Then use Read on its tasks/${id}.output through the final exit footer. Bash/grep does not ingest completion; a footer without a matching host notification is not proof.`
4201
4267
  : `Background verification ${id} has host completion exit ${hostExit}, but no ingested completion receipt. Use Read on its tasks/${id}.output through the final exit footer (Bash/grep does not ingest completion). Do not rerun the completed job just to create evidence. If Read is rejected, check the matching launch, host notification, footer and output-file freshness; never fabricate a receipt.`;
4202
4268
  } else {
4203
- instruction = `The last verification (\`${String(lastVerification.command || '').slice(0, 80)}\`) exit status is unproven: its shell wrapper may mask or skip the runner (a pipeline is one possible cause). Run the bare verification command and inspect its exit code; for an actual pipeline, propagate the runner status with \`set -o pipefail\`.`;
4269
+ const rerun = provableRerunCommand(lastVerification.command);
4270
+ instruction = `The last verification (\`${verificationCommandLabel(lastVerification.command)}\`) exit status is unproven: its shell wrapper may mask or skip the runner (a pipeline is one possible cause). ${rerun ? `Run exactly this once, in the foreground: \`${rerun.replace(/`/g, "'")}\` — do not repeat the masked form. ` : ''}Run the bare verification command and inspect its exit code; for an actual pipeline, propagate the runner status with \`set -o pipefail\`.`;
4204
4271
  }
4205
4272
  }
4206
4273
  if (!instruction && ledger.verificationFailed) {
@@ -5392,6 +5459,7 @@ async function writeSeal(projectRoot, payload, state, result, ledger) {
5392
5459
  await writeJsonAtomic(file, Object.fromEntries(keep));
5393
5460
  }
5394
5461
 
5462
+ const RECONCILE_MODES = ['tiny-fix', 'local-fix', 'local-build', 'find-cause', 'shared-edit', 'map-impact', 'review-release'];
5395
5463
  const CLASSIFIER_OWNED_FIELDS = ['publication', 'operationGoal', 'operationGoals', 'configurationScope', 'releasePolicy', 'conditionalObligations', 'reportArtifact', 'verificationOnly', 'statusReport'];
5396
5464
 
5397
5465
  // Re-derive a router-classified contract from the task's own explicit prompt. Only a contract
@@ -5407,19 +5475,30 @@ export async function reconcileStaleContract(projectRoot, state) {
5407
5475
  if (!fresh?.taskKind) return state;
5408
5476
  const engine = await import(new URL('../index/publication-intent.mjs', import.meta.url).href);
5409
5477
  const identity = engine.semanticContractIdentity({ promptText: prompt, targetFile: state.routingContext?.targetFile || '', taskInstanceId: state.taskInstanceId });
5410
- const base = { ...stored };
5411
- for (const key of CLASSIFIER_OWNED_FIELDS) delete base[key];
5412
- // Evidence tags added by the stale classification (operation-verification, report-artifact, ...) do not
5413
- // describe the re-derived kind: restart from the execution mode's base evidence unless the fresh kind
5414
- // sets its own (MIXED/OPERATIONAL/DOCUMENTATION/READ_ONLY are rewritten by applyTaskSemantics).
5415
- if (fresh.taskKind === 'CODE_IMPLEMENTATION' || (fresh.taskKind === 'CONFIGURATION' && fresh.configurationScope !== 'external')) {
5416
- const mode = state.routeSummary?.executionMode === 'informational' ? 'local-build' : state.routeSummary?.executionMode;
5417
- const baseEvidence = resolver.buildExecutionContract(mode)?.completionEvidence;
5418
- if (Array.isArray(baseEvidence)) base.completionEvidence = baseEvidence;
5478
+ const derive = (mode, everyKind) => {
5479
+ const base = { ...stored };
5480
+ for (const key of CLASSIFIER_OWNED_FIELDS) delete base[key];
5481
+ // Evidence tags added by the stale classification (operation-verification, report-artifact, ...) do not
5482
+ // describe the re-derived kind: restart from the execution mode's base evidence unless the fresh kind
5483
+ // sets its own (MIXED/OPERATIONAL/DOCUMENTATION/READ_ONLY are rewritten by applyTaskSemantics).
5484
+ if (everyKind || fresh.taskKind === 'CODE_IMPLEMENTATION' || (fresh.taskKind === 'CONFIGURATION' && fresh.configurationScope !== 'external')) {
5485
+ const baseEvidence = resolver.buildExecutionContract(mode)?.completionEvidence;
5486
+ if (Array.isArray(baseEvidence)) base.completionEvidence = baseEvidence;
5487
+ }
5488
+ const contract = resolver.applyTaskSemantics(base, fresh);
5489
+ return { contract, comparison: engine.compareSemanticContracts({ stored, fresh: contract, previousIdentity: state.semanticIdentity, identity }) };
5490
+ };
5491
+ let { contract: executionContract, comparison } = derive(state.routeSummary?.executionMode === 'informational' ? 'local-build' : state.routeSummary?.executionMode, false);
5492
+ if (comparison.status === 'invariant-violation') {
5493
+ // The router re-scores executionMode on every tool event while the contract stays the task's own, so
5494
+ // the mode stored now is not necessarily the mode the contract was derived under. The same
5495
+ // task/prompt/engine is contradictory only when NO mode base reproduces the stored contract.
5496
+ for (const mode of RECONCILE_MODES) {
5497
+ const other = derive(mode, true);
5498
+ if (other.comparison.status === 'equal') return { ...state, semanticIdentity: identity, semanticDiagnostic: other.comparison };
5499
+ }
5500
+ return { ...state, semanticDiagnostic: comparison };
5419
5501
  }
5420
- const executionContract = resolver.applyTaskSemantics(base, fresh);
5421
- const comparison = engine.compareSemanticContracts({ stored, fresh: executionContract, previousIdentity: state.semanticIdentity, identity });
5422
- if (comparison.status === 'invariant-violation') return { ...state, semanticDiagnostic: comparison };
5423
5502
  return { ...state, semanticIdentity: identity, semanticDiagnostic: comparison,
5424
5503
  routeSummary: { ...state.routeSummary, executionContract } };
5425
5504
  } catch { return state; }
@@ -5427,6 +5506,7 @@ export async function reconcileStaleContract(projectRoot, state) {
5427
5506
 
5428
5507
  async function runEvaluateStop() {
5429
5508
  const projectRoot = process.env.CLAUDE_PROJECT_DIR || process.cwd();
5509
+ gitMemo = new Map();
5430
5510
  let payload;
5431
5511
  try {
5432
5512
  payload = JSON.parse((await readStdin()) || '{}');
@@ -258,6 +258,12 @@ export async function resolveCursorApplicability({ projectRoot, runRoot = projec
258
258
  catch { return { status: 'UNKNOWN', reason: 'route identity unavailable' }; }
259
259
  if (route?.routePublicationIncomplete || route?.sessionId !== sessionId || !route.taskInstanceId || !route.routeGeneration) return { status: 'UNKNOWN', reason: 'route identity unavailable or foreign' };
260
260
  const ids = [...text.matchAll(/^RunId:\s*(\S+)\s*$/gim)];
261
+ // A legacy cursor (no RunId at all) has no authority record, so nobody can own it until an
262
+ // explicit --adopt-legacy-run stamps one. A session whose published route carries no handoff
263
+ // binding provably never claimed a run: it is an ordinary session beside a stale cursor, not an
264
+ // unproven owner. Reporting UNKNOWN there marked EVERY stop of the project BLOCKED (telemetry:
265
+ // ~2500 advisories, one project 800+). A bound route or a duplicated RunId stays UNKNOWN.
266
+ if (ids.length === 0 && !route.handoffRunId) return { status: 'NOT_OWNED', reason: 'legacy cursor without RunId; this session holds no handoff binding' };
261
267
  if (ids.length !== 1) return { status: 'UNKNOWN', reason: 'run cursor identity unavailable' };
262
268
  const runId = ids[0][1];
263
269
  const applicability = await resolveHandoffApplicability({ projectRoot, sessionId, taskInstanceId: route.taskInstanceId, routeGeneration: route.routeGeneration, runId });
@@ -309,9 +309,23 @@ export function noteSweepFailure(error) {
309
309
  return message;
310
310
  }
311
311
 
312
+ // Opt-in guard (inert when UKIT_TELEMETRY_DENY_ROOT is unset): rows whose project
313
+ // root resolves to the denied directory are dropped. The UKit dev repo's vitest
314
+ // config sets it to the repo root so test runs never write into the live runtime
315
+ // storage, while tests using their own temp project roots still write normally.
316
+ function isDeniedRoot(projectRoot) {
317
+ const deny = process.env.UKIT_TELEMETRY_DENY_ROOT;
318
+ if (!deny) return false;
319
+ const canon = (p) => {
320
+ try { return fs.realpathSync(path.resolve(String(p))); } catch { return path.resolve(String(p)); }
321
+ };
322
+ return canon(projectRoot) === canon(deny);
323
+ }
324
+
312
325
  export function appendTelemetryRow(projectRoot, sessionId, row, options = {}) {
313
326
  try {
314
327
  if (!row || typeof row !== 'object') return false;
328
+ if (isDeniedRoot(projectRoot)) return false;
315
329
  const dir = telemetryDirFor(projectRoot);
316
330
  fs.mkdirSync(dir, { recursive: true });
317
331
  const filePath = path.join(dir, `${safeName(sessionId)}.jsonl`);
@@ -9,7 +9,7 @@
9
9
  * Stalled-cursor releases are advisory, never completion evidence.
10
10
  * Completion infrastructure failures block with redacted reasons (details only
11
11
  * on stderr); watchdog failures are advisory and reported verbatim.
12
- * UKIT_HOOK_DEADLINE_MS bounds execution (default 3000ms), including the ledger
12
+ * UKIT_HOOK_DEADLINE_MS bounds execution (wrapper default 5000ms), including the ledger
13
13
  * child. Deadline expiry synchronously emits a fail-closed block and reaps the
14
14
  * child before exit0: empty stdout would incorrectly release the wrapper.
15
15
  * Exported evaluators, merge, normalization and redaction seams are tested directly.
@@ -83,7 +83,7 @@ let decisionEmitted = false;
83
83
  * evaluator crash without weakening redaction.
84
84
  */
85
85
  export function redactDeadlineReason() {
86
- return 'UKit stop coordinator: this stop exceeded the hook deadline before the fail-closed completion evaluator could decide, so the stop is blocked fail-closed (details withheld). Run: ukit install, then re-send the task in a new message.';
86
+ return 'UKit stop coordinator: this stop exceeded the hook deadline before the fail-closed completion evaluator could decide, so the stop is blocked fail-closed (details withheld). This is usually a busy machine or slow disk, not a fault in the task or the install: stop again to re-evaluate; only if this repeats, run: ukit install, then re-send the task in a new message.';
87
87
  }
88
88
 
89
89
  /**
@@ -135,9 +135,18 @@ if (Number.isFinite(HOOK_DEADLINE_MS) && HOOK_DEADLINE_MS > 0) {
135
135
  // same-event double registration, never legitimate consecutive Stops.
136
136
  export const DEDUPE_WINDOW_MS = 2000;
137
137
 
138
- // Fixed budget slices inside the default 3000ms hook deadline: the ledger child
139
- // gets the larger slice, each watchdog lock acquisition gets a short one.
140
- const LEDGER_BUDGET_MS = 1500;
138
+ // Budget slices inside the hook deadline: the ledger child gets the larger slice, each
139
+ // watchdog lock acquisition gets a short one. The ledger slice is 1500ms under a short
140
+ // deadline and grows with a longer one (the shipped wrapper arms 5000ms) up to 3000ms,
141
+ // always leaving 1500ms for the advisory lanes and the decision write. Field telemetry:
142
+ // on a loaded machine / external volume a healthy evaluation overran 1500ms and the
143
+ // stop was blocked as an "infrastructure failure".
144
+ export function resolveLedgerBudgetMs(deadlineMs) {
145
+ const deadline = Number(deadlineMs);
146
+ if (!Number.isFinite(deadline) || deadline <= 3000) return 1500;
147
+ return Math.min(3000, deadline - 1500);
148
+ }
149
+ const LEDGER_BUDGET_MS = resolveLedgerBudgetMs(HOOK_DEADLINE_MS);
141
150
  export const LOCK_BUDGET_MS = 600;
142
151
 
143
152
  const WATCHDOG_PROVENANCE_PREFIX = '[ukit-stop-coordinator] task-watchdog also requested a block: ';
@@ -177,6 +186,16 @@ export function redactInfrastructureReason() {
177
186
  return 'UKit stop coordinator: the fail-closed completion evaluator failed while this stop was being evaluated, so the stop is blocked fail-closed (failure details withheld). Run: ukit install, then re-send the task in a new message.';
178
187
  }
179
188
 
189
+ /**
190
+ * Fixed reason for the one infrastructure failure that is NOT a broken install: the
191
+ * evaluator was killed at its time slice (slow volume, loaded machine, huge worktree).
192
+ * Field telemetry showed the generic text sending users to reinstall a healthy runtime.
193
+ * Still a fail-closed block, still no interpolation.
194
+ */
195
+ export function redactEvaluatorTimeoutReason() {
196
+ return 'UKit stop coordinator: the fail-closed completion evaluator ran out of time on this stop (slow disk or a busy machine — not a fault in the task or the install), so the stop is blocked fail-closed (details withheld). Stop again to re-evaluate; only if this repeats, run: ukit install, then re-send the task in a new message.';
197
+ }
198
+
180
199
  // ─── Normalization ────────────────────────────────────────────────────────
181
200
  /**
182
201
  * Parse one evaluator's stdout into a normalized result.
@@ -248,7 +267,7 @@ export function coordinateStopDecisions({ completion = null, watchdog = null, ha
248
267
  // 1. The fail-closed blocker itself failed → block, redacted, detail on stderr only.
249
268
  if (completionFailed) {
250
269
  policies.push('completion-gate');
251
- let reason = redactInfrastructureReason();
270
+ let reason = failures?.completionTimedOut === true ? redactEvaluatorTimeoutReason() : redactInfrastructureReason();
252
271
  if (handoff?.kind === 'block') {
253
272
  policies.push('handoff-cursor');
254
273
  reason += `\n${HANDOFF_PROVENANCE_PREFIX}${handoff.reason}`;
@@ -454,7 +473,17 @@ function runEvaluatorChild(scriptPath, input, budgetMs, { cwd = null } = {}) {
454
473
  liveEvaluatorChildren.delete(child);
455
474
  clearTimeout(timer);
456
475
  if (timedOut) {
457
- reject(new Error(`completion evaluator exceeded its ${budgetMs}ms budget and was killed`));
476
+ // The kill can land after the evaluator already wrote its verdict (it was still flushing ledger state).
477
+ // A complete BLOCK line is real evidence about the work and must not be downgraded to an
478
+ // infrastructure failure, which the wrapper's consecutive-failure breaker may eventually release.
479
+ // Only a block is honoured: a release cut short by the kill is never trusted.
480
+ const nl = stdout.indexOf('\n');
481
+ if (nl > 0) {
482
+ try {
483
+ if (JSON.parse(stdout.slice(0, nl))?.decision === 'block') { resolve({ stdout: stdout.slice(0, nl + 1), stderr }); return; }
484
+ } catch { /* partial or foreign line: fall through to the timeout */ }
485
+ }
486
+ reject(Object.assign(new Error(`completion evaluator exceeded its ${budgetMs}ms budget and was killed`), { code: 'UKIT_EVALUATOR_TIMEOUT' }));
458
487
  return;
459
488
  }
460
489
  if (code !== 0) {
@@ -3201,6 +3230,7 @@ export async function runStopCoordinator({
3201
3230
  completion = await evaluateCompletionPolicy({ projectRoot, rawInput, budgetMs: ledgerBudgetMs });
3202
3231
  } catch (error) {
3203
3232
  failures.completion = error?.message || String(error);
3233
+ if (error?.code === 'UKIT_EVALUATOR_TIMEOUT') failures.completionTimedOut = true;
3204
3234
  // Raw detail is loud on stderr; the parsed decision stays redacted.
3205
3235
  process.stderr.write(`[ukit-stop-coordinator] completion evaluator failed: ${failures.completion}\n`);
3206
3236
  }
@@ -3499,6 +3529,6 @@ if (isDirectRun()) {
3499
3529
  main().catch((error) => {
3500
3530
  // Last-resort failure INSIDE the coordinator: still fail-closed, still redacted.
3501
3531
  process.stderr.write(`[ukit-stop-coordinator] ${error?.message || error}\n`);
3502
- writeDecisionLine({ decision: 'block', reason: redactInfrastructureReason() });
3532
+ writeDecisionLine({ decision: 'block', reason: redactInfrastructureReason(), policyOwner: 'fail-closed' });
3503
3533
  });
3504
3534
  }