@ngockhoale/ukit 3.4.81 → 3.4.82

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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,21 @@
2
2
 
3
3
  All notable changes to UKit are documented here.
4
4
 
5
+ ## 3.4.82 - 2026-11-10
6
+
7
+ Completion-gate fixes from a field-telemetry audit of the projects running UKit (Stop/gate logs, hook latency, route state, session transcripts).
8
+
9
+ - Fix: **a stale legacy handoff cursor no longer marks every stop BLOCKED.** A `docs/AI_HANDOFF/RUN.md` written before `RunId` existed has no authority record, so nobody can own it until `/ukit:handoff-fullstack --adopt-legacy-run=<RunId>`. A session whose published route holds no handoff binding is now `NOT_OWNED` (an ordinary session beside an old cursor) instead of `UNKNOWN`; telemetry showed ~2,500 "handoff ownership UNKNOWN … report BLOCKED" advisories, 2,000 of them in one project in one month. A route that carries a `handoffRunId`, a duplicated `RunId`, or a missing/foreign/incomplete route still fails closed as `UNKNOWN`; the cursor is never touched and adoption is unchanged.
10
+ - Fix: **questions and acknowledgements are no longer routed as change orders.** Tone-folding turned "cái" into the verb *cài* (install) — likewise chính/chỉnh, Việt/viết, đợi·đối·đội/đổi, cháy·chảy/chạy, sữa/sửa, thèm/thêm — so "Cái này là gì, tại sao có chế độ này" owed write + verification evidence. Also released: "chưa được cấp quyền cập nhật …" / "no permission to update" (a read-only banner, not an order), "còn cần làm gì thêm nữa không" / "có thêm test nữa không" ("anything else", not "add") — only in the closed "còn/có … gì thêm [nữa] [không]" / clause-final "thêm nữa không" shape, so "thêm gì vào README.md" stays an order, a what-is question followed by punctuation, a leading "giải thích …" / "explain …", and bare acknowledgements after a task ("ok", "có", "được", "ừ", "được rồi") which now park the previous contract instead of re-arming it. Every release keeps its order control: "Cái này là gì, sửa giúp tôi", "thêm test nữa đi", "ok sửa đi", "giải thích rồi sửa luôn", "cấp quyền cập nhật cho user admin trong file roles.js" still block an empty stop. A bare "yes / ok / có / được / ừ / đồng ý" that answers a question the agent itself just asked (the last assistant text in the host transcript ends with a question, with no other owner turn in between) is the go-ahead for that same task and keeps its contract armed; "đóng nhé" (close it) is no longer read as "đồng ý". The homograph / banner / question rules are applied to `src/index/taskRouting.js`, `route-task.mjs` and the `skill-router.sh` hook; the acknowledgement rules live in `route-task.mjs` and the hook (the `src/index` copy has no greeting lane).
11
+ - Improved: **an unproven verification now names the command that proves it.** Most verification-evidence blocks were a runner piped into `tail`/`grep`/`tee` or followed by `; echo exit=$?`, and sessions repeated the same masked shape. The PostToolUse notice and the gate instruction now add "Run exactly this once: …" (`set -o pipefail; <same command>` for a pipe, the command up to and including the runner for a status echo, keeping a leading `cd`/env prefix) — only when the same classifier accepts that command and no second runner would be dropped. Guidance only: what counts as proof is unchanged, and loop/background shapes keep the generic wording.
12
+ - Fix: **"semantic contract invariant violation … contradictory contracts" no longer blocks a healthy session.** Telemetry: 172 such Stop blocks. The router re-scores the execution mode on every tool event while the contract stays the task's own, and both the router and the gate re-derived the contract from the *current* mode — so a contract built under `find-cause`/`map-impact` compared unequal to itself once the mode moved to `local-fix`. The comparison now accepts a stored contract that any execution mode reproduces for the same prompt and engine; a contract no mode reproduces (foreign evidence tag, different task kind) still blocks. Two feeders are closed as well: a new task no longer inherits the previous task's evidence tags, operation goals or state targets (a read-only review's `impact-evidence` leaking into the next change order), and a system-injected turn (compact summary, `/loop` wakeup) after an answer-only turn no longer mints a contract bound to the owner's prompt.
13
+ - Fix: **a slow Stop evaluation is no longer reported as a broken install.** One evaluation repeated the same git probes (16 spawns → 10; about 950ms → 550ms measured on this repo); they are now memoized for that single evaluation only. The evaluator's time slice scales with the hook deadline (1500ms → up to 3000ms; `completion-gate.sh` default deadline 3000 → 5000ms, inside the hook's slot, see below), and an evaluator that still runs out of time blocks fail-closed with its own fixed text ("ran out of time … Stop again to re-evaluate") instead of "Run: ukit install".
14
+ - Fix: the Stop message for an unproven verification cut the command at 80 characters — on a real `cd <root> && PYTHONPATH=. venv/bin/python3.12 -m pytest … | grep … | tail -40` that ended exactly at `python3.12 -`, naming a command that never ran and hiding the pipe that made it unproven. The label now keeps the whole command up to 240 characters (both ends beyond that). The hook-deadline block now says to stop again first and reach for `ukit install` only if it repeats; it stays fail-closed.
15
+ - Fix: a Stop on which the completion evaluator could not finish (killed at its time slice, hook deadline, evaluator crash) blocked every time with no cap — one field session took 170+ such blocks in a row on a loaded machine, each costing a turn the agent could do nothing with. These blocks now have their own bounded breaker in `completion-gate.sh`: counted per session (one session never releases another), released only after more than `stopGateMaxCrashStreaks` (default 3) consecutive failures (no more than 10 minutes apart) that also span at least 120 seconds — stopping again a few times in a row never releases — and the release is announced as a blocked, non-complete outcome ("completion was NOT verified … not a pass"). Any real verdict resets the count; evidence blocks, and any decision carrying a handoff-cursor or task-watchdog block, are never counted. The crash breaker for a coordinator that exits non-zero is unchanged and separate. A block verdict the evaluator had already written when its time-slice kill landed is now honoured as that verdict instead of being reported as an evaluator failure (a cut-short release is still never trusted).
16
+ - Fix: the Stop hook's chain slot is 12s (was 8s) and its host timeout 22s (was 18s), keeping the chain-budget rule host ≥ slot + 10s. With the 5000ms coordinator deadline plus the 1500ms killer the wrapper could need 6.5s before bash start-up and staging, and a chain-runner timeout of this wrapper would have been a silent release.
17
+ - Tests: `tests/hooks/semanticContractModeChurn.test.js`, `tests/hooks/stopEvaluatorBudget.test.js`, `tests/hooks/telemetryAuditRouting.test.js` (real hook + gate, fresh and after-task, with order controls), a legacy-cursor bystander case with fail-closed controls in `handoffProvenance.test.js`, and rerun-guidance cases in `stopGateReceiptCapture.test.js`.
18
+ - Not changed (by design, per the audit): pipe/`; echo $?` shapes stay unproven; a carried compact-summary contract still owes its evidence; the teammate-message lane has no fix in this release.
19
+
5
20
  ## 3.4.81 - 2026-11-08
6
21
 
7
22
  - New: **automatic Claude Code session discovery for UKit Advisor.** `ukit:advisor` / `$ukit-advisor` with nothing after the trigger (or only a short remark such as "lỗi rồi") reads the latest main-agent Claude Code session of the current project — no paste needed; `session <id>` and `project <path>` name one explicitly; anything else is still pasted output, as in 3.4.80. A bundled read-only Node reader (`scripts/claude-session-reader.mjs` inside the skill, also `ukit advisor context [--last|--session <id>|--project <path>] [--json]`) matches the project by the session's recorded cwd (realpath, git root, linked worktrees; nested repos and sibling folders excluded), honours `CLAUDE_CONFIG_DIR`, skips subagent/sidechain transcripts and symlinks, refuses to guess between concurrent sessions, streams huge/partial/concurrently-written JSONL with bounded secret redaction, and renders a bounded, redacted, untrusted digest that keeps owner messages, tool results, assistant claims and Stop-hook/gate refusals apart (owner STOP ≠ hook refusal). It never writes, spawns, resumes or messages Claude Code; no session, no permission or a Codex model that cannot run shell commands yields one safe status-request prompt.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ngockhoale/ukit",
3
- "version": "3.4.81",
3
+ "version": "3.4.82",
4
4
  "description": "Install/update an index-first AI workspace for Claude Code, OpenAI Codex and omp (Oh My Pi).",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -1205,8 +1205,16 @@ export function classifyAdvisorRequest({ promptText = '', commandText = '' } = {
1205
1205
  // Used by hasAdvisoryOnlyAssertion (assertion + no order → advisory) and by
1206
1206
  // the question-shape gate below (question + no order → consult, even when the
1207
1207
  // subject vocabulary fires debug/failure/implement signal scores).
1208
+ // Tone-folding turns unrelated Vietnamese words into mutation verbs: "cái" (this/thing) -> cai (cài),
1209
+ // "chính" (main/exactly) -> chinh (chỉnh), "Việt" -> viet (viết), "đợi/đời/đối/đội/đôi/đói" -> doi (đổi),
1210
+ // "cháy/chảy" -> chay (chạy), "sữa" -> sua (sửa), "thèm" -> them (thêm). Mask the toned non-verbs BEFORE
1211
+ // folding, so "Cái này là gì, tại sao…" is not read as an install order (3.4.81 telemetry audit).
1212
+ function maskTonedNonVerbs(text = '') {
1213
+ return String(text ?? '').normalize('NFC')
1214
+ .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, ' _ ');
1215
+ }
1208
1216
  function hasMutationOrder({ promptText = '', commandText = '' } = {}) {
1209
- const folded = `${promptText ?? ''}\n${commandText ?? ''}`
1217
+ const folded = `${maskTonedNonVerbs(promptText)}\n${commandText ?? ''}`
1210
1218
  .toLowerCase()
1211
1219
  .normalize('NFD')
1212
1220
  .replace(/[\u0300-\u036f]/g, '')
@@ -1255,6 +1263,11 @@ function hasMutationOrder({ promptText = '', commandText = '' } = {}) {
1255
1263
  .replace(new RegExp(`\\b(?:neu|if)\\s+${TAIL}`, 'g'), ' ')
1256
1264
  // 'đối chiếu' (cross-check) folds to 'doi chieu' and is not the verb 'đổi' (change).
1257
1265
  .replace(/\bdoi\s+chieu\b/g, ' ')
1266
+ // Field telemetry (3.4.81 audit): words that fold onto a mutation verb but name no order.
1267
+ // "chưa được cấp quyền cập nhật" / "no permission to update" reports a missing permission (read-only
1268
+ // banners); "gì thêm [nữa]" / "thêm nữa không" mean "anything else", never the verb "add".
1269
+ .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, ' ')
1270
+ .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, ' ')
1258
1271
  // R2: a deferred/future clause ("chua sua", "how we would later implement", "R2 onward: ...",
1259
1272
  // "fix strategy ...") describes work for a LATER round, not an order for this turn.
1260
1273
  .replace(new RegExp(`\\bchua\\s+(?:sua|fix|implement|trien\\s+khai|viet|thay\\s+doi)\\b${WAIT_TAIL}`, 'g'), ' ')
@@ -1345,6 +1358,11 @@ function deriveExecutionMode({
1345
1358
  const questionShapedPrompt = /\?\s*$/.test(trimmedPromptText)
1346
1359
  || leadingInterrogative
1347
1360
  || /\b(?:la gi|duoc khong)\s*$/.test(foldedPromptText)
1361
+ // Field telemetry (3.4.81 audit): a what-is question mid-prompt ("… là gì, …") and a leading
1362
+ // explanation request ("giải thích …", "explain …") ask for an answer. Both still pass the
1363
+ // hasMutationOrder/targetFile veto below, so "giải thích rồi sửa luôn" stays an order.
1364
+ || /\bla gi\s*(?:[,.?!;:\n]|$)/.test(foldedPromptText)
1365
+ || /^(?:hay\s+|vui\s+long\s+|lam\s+on\s+|please\s+)?(?:giai\s+thich|explain)\b/.test(foldedPromptText)
1348
1366
  // C85-019: Vietnamese status/consult tails without a '?' — "… chưa",
1349
1367
  // "… chưa nhỉ", "… không nhỉ", "… đúng không". A question about a defect
1350
1368
  // must not mint the bug-fix floor's write/repro debt.
@@ -54,8 +54,7 @@ else
54
54
  __ukit_waiter=$!
55
55
  wait "$__ukit_reader" 2>/dev/null
56
56
  __ukit_stage_rc=$?
57
- kill "$__ukit_waiter" 2>/dev/null
58
- wait "$__ukit_waiter" 2>/dev/null
57
+ { kill "$__ukit_waiter"; wait "$__ukit_waiter"; } 2>/dev/null
59
58
  exec 8<&-
60
59
  __ukit_size="$(wc -c < "$UKIT_INPUT_FILE" 2>/dev/null | tr -d '[:space:]')"
61
60
  if [ "$__ukit_stage_rc" -ne 0 ] || [ "$__ukit_size" -gt 2097152 ]; then
@@ -87,34 +86,86 @@ fi
87
86
  __ukit_coord_out="$(mktemp "${TMPDIR:-/tmp}/ukit-coord-out.XXXXXX")"
88
87
  __ukit_coord_err="$(mktemp "${TMPDIR:-/tmp}/ukit-coord-err.XXXXXX" 2>/dev/null)" || __ukit_coord_err=/dev/null
89
88
  __ukit_coord_t0=$SECONDS
90
- printf '%s' "$INPUT" | UKIT_HARNESS="${UKIT_HARNESS:-claude-code}" UKIT_HOOK_DEADLINE_MS="${UKIT_HOOK_DEADLINE_MS:-3000}" node "$SCRIPT" --evaluate-stop > "$__ukit_coord_out" 2>"$__ukit_coord_err" &
89
+ printf '%s' "$INPUT" | UKIT_HARNESS="${UKIT_HARNESS:-claude-code}" UKIT_HOOK_DEADLINE_MS="${UKIT_HOOK_DEADLINE_MS:-5000}" node "$SCRIPT" --evaluate-stop > "$__ukit_coord_out" 2>"$__ukit_coord_err" &
91
90
  __ukit_coord_pid=$!
92
- __ukit_coord_ms="${UKIT_HOOK_DEADLINE_MS:-3000}"
93
- case "$__ukit_coord_ms" in ''|*[!0-9]*) __ukit_coord_ms=3000 ;; esac
91
+ __ukit_coord_ms="${UKIT_HOOK_DEADLINE_MS:-5000}"
92
+ case "$__ukit_coord_ms" in ''|*[!0-9]*) __ukit_coord_ms=5000 ;; esac
94
93
  __ukit_coord_ms=$((__ukit_coord_ms + 1500))
95
94
  printf -v __ukit_coord_s '%d.%03d' $((__ukit_coord_ms / 1000)) $((__ukit_coord_ms % 1000))
96
95
  ( sleep "$__ukit_coord_s" 2>/dev/null; kill -9 "$__ukit_coord_pid" 2>/dev/null ) <&- >/dev/null 2>&1 &
97
96
  __ukit_killer_pid=$!
98
97
  wait "$__ukit_coord_pid" 2>/dev/null
99
98
  STATUS=$?
100
- kill "$__ukit_killer_pid" 2>/dev/null
101
- wait "$__ukit_killer_pid" 2>/dev/null
99
+ # One redirect around both: bash 3.2 can reap the killed job between the two commands and would print its
100
+ # "Terminated: 15" job notice on the hook's stderr.
101
+ { kill "$__ukit_killer_pid"; wait "$__ukit_killer_pid"; } 2>/dev/null
102
102
  OUTPUT="$(cat "$__ukit_coord_out" 2>/dev/null)"
103
103
  rm -f "$__ukit_coord_out"
104
- # Bounded diagnostic for a crashed coordinator (status>128 = killed by signal N-128, e.g. 137 = the deadline killer's SIGKILL).
104
+ # A coordinator that exits 0 but could not get a verdict out of the completion evaluator (killed at its time
105
+ # slice, hook deadline hit, evaluator crashed) answers with a fixed fail-closed block. Field telemetry: on a
106
+ # loaded machine one session took 170+ such blocks in a row — nothing the agent can do changes the outcome, so
107
+ # every block is a wasted turn. It is the same infrastructure failure as a crashed coordinator and shares its
108
+ # consecutive-failure breaker. The marker is JSON structure (a quote inside a reason string is escaped), so
109
+ # reason text can never forge it.
110
+ INFRA_BLOCK=0
111
+ if [ "$STATUS" -eq 0 ]; then
112
+ case "$OUTPUT" in *'"policyOwner":"fail-closed"'*) INFRA_BLOCK=1 ;; esac
113
+ # A handoff-cursor or task-watchdog block riding on the same decision is a real verdict about unfinished
114
+ # work: never count it toward a release (those lanes own their own stall breakers).
115
+ case "$OUTPUT" in *'also requested a block: '*) INFRA_BLOCK=0 ;; esac
116
+ fi
117
+ # Bounded diagnostic for a failed evaluation (status>128 = killed by signal N-128, e.g. 137 = the deadline killer's SIGKILL).
105
118
  # Written to a private cache file only; never part of the decision text (the reason stays fixed and redacted).
106
- if [ "$STATUS" -ne 0 ]; then
119
+ if [ "$STATUS" -ne 0 ] || [ "$INFRA_BLOCK" -eq 1 ]; then
107
120
  mkdir -p "$PROJECT_ROOT/.ukit/storage/cache" 2>/dev/null
108
121
  { printf 'status=%s elapsed_s=%s deadline_ms=%s\n' "$STATUS" "$((SECONDS - __ukit_coord_t0))" "${__ukit_coord_ms}"; head -c 400 "$__ukit_coord_err" 2>/dev/null; printf '\n'; } > "$PROJECT_ROOT/.ukit/storage/cache/completion-gate-crash.last" 2>/dev/null
109
122
  fi
110
123
  [ "$__ukit_coord_err" = /dev/null ] || rm -f "$__ukit_coord_err"
111
124
 
125
+ CACHE_DIR="$PROJECT_ROOT/.ukit/storage/cache"
126
+ SESSION_KEY="$(printf '%s' "$INPUT" | sed -n 's/.*"session_id"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -1 | tr -c 'A-Za-z0-9_-' '_' | cut -c1-80)"
127
+ [ -n "$SESSION_KEY" ] || SESSION_KEY="unknown"
128
+ INFRA_FILE="$CACHE_DIR/completion-gate-infra.$SESSION_KEY.streak"
129
+ if [ "$INFRA_BLOCK" -eq 1 ]; then
130
+ # Evaluator-failure breaker. Separate from the crash breaker below on purpose:
131
+ # - keyed per session, so one session's failures never count toward releasing another;
132
+ # - one epoch stamp per failure, and a release needs BOTH more than the cap of consecutive failures AND
133
+ # at least INFRA_MIN_SPAN_S of wall clock between the first failure and this one — an agent that
134
+ # simply stops again a few times in a row cannot talk its way out;
135
+ # - the release is announced as a blocked, non-complete outcome, never as a pass.
136
+ INFRA_MIN_SPAN_S=120
137
+ mkdir -p "$CACHE_DIR" 2>/dev/null
138
+ NOW_S="$(date +%s)"
139
+ # Consecutive means close in time as well: a failure left over from an earlier burst (the session then
140
+ # sat idle with no real verdict to clear it) must not lend its age to a new burst of quick stops.
141
+ INFRA_MAX_GAP_S=600
142
+ LAST_S="$(grep '^[0-9][0-9]*$' "$INFRA_FILE" 2>/dev/null | tail -1)"
143
+ case "$LAST_S" in ''|*[!0-9]*) LAST_S="$NOW_S" ;; esac
144
+ [ $((NOW_S - LAST_S)) -le "$INFRA_MAX_GAP_S" ] || : > "$INFRA_FILE" 2>/dev/null
145
+ printf '%s\n' "$NOW_S" >> "$INFRA_FILE" 2>/dev/null
146
+ STREAK="$(grep -c '^[0-9][0-9]*$' "$INFRA_FILE" 2>/dev/null)"
147
+ case "$STREAK" in ''|*[!0-9]*) STREAK=1 ;; esac
148
+ FIRST_S="$(grep -m1 '^[0-9][0-9]*$' "$INFRA_FILE" 2>/dev/null)"
149
+ case "$FIRST_S" in ''|*[!0-9]*) FIRST_S="$NOW_S" ;; esac
150
+ MAX_STREAK="$(sed -n 's/.*"stopGateMaxCrashStreaks"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' "$PROJECT_ROOT/.ukit/storage/config.json" 2>/dev/null | head -1)"
151
+ case "$MAX_STREAK" in ''|*[!0-9]*) MAX_STREAK=3 ;; esac
152
+ SPAN_S=$((NOW_S - FIRST_S))
153
+ if [ "$STREAK" -gt "$MAX_STREAK" ] && [ "$SPAN_S" -ge "$INFRA_MIN_SPAN_S" ]; then
154
+ : > "$INFRA_FILE" 2>/dev/null
155
+ printf '%s\n' '{"systemMessage":"UKit stop coordinator released this stop after '"$STREAK"' consecutive stops over '"$SPAN_S"'s on which the completion evaluator could not finish (out of time or failed — usually a busy machine or slow disk). Completion was NOT verified: this is a blocked, non-complete outcome, not a pass — do not report the task as done on the strength of this release. If this keeps happening on an idle machine, run `ukit install`.","outcome":"blocked","complete":false}'
156
+ exit 0
157
+ fi
158
+ # Under the cap: the coordinator's own fixed, redacted block goes through unchanged.
159
+ printf '%s\n' "$OUTPUT"
160
+ exit 0
161
+ fi
162
+
112
163
  if [ "$STATUS" -ne 0 ]; then
113
- # BUG-C22-05: a PERSISTENT coordinator crash must not block every Stop forever.
114
- # Byte-append one marker per crash; a clean run deletes the file, so the count
115
- # is consecutive crashes, not lifetime crashes. File-based (no node) so the
164
+ # BUG-C22-05: a PERSISTENT infrastructure failure must not block every Stop forever.
165
+ # Byte-append one marker per failure; a clean run deletes the file, so the count
166
+ # is consecutive failures, not lifetime failures. File-based (no node) so the
116
167
  # breaker still works when node itself is what is crashing.
117
- CRASH_FILE="$PROJECT_ROOT/.ukit/storage/cache/completion-gate-crash.streak"
168
+ CRASH_FILE="$CACHE_DIR/completion-gate-crash.streak"
118
169
  mkdir -p "$(dirname "$CRASH_FILE")" 2>/dev/null
119
170
  printf '.' >> "$CRASH_FILE" 2>/dev/null
120
171
  STREAK="$(wc -c < "$CRASH_FILE" 2>/dev/null | tr -d '[:space:]')"
@@ -135,8 +186,10 @@ if [ "$STATUS" -ne 0 ]; then
135
186
  exit 0
136
187
  fi
137
188
 
138
- # A clean coordinator run resets the consecutive-crash streak.
139
- rm -f "$PROJECT_ROOT/.ukit/storage/cache/completion-gate-crash.streak" 2>/dev/null
189
+ # A real verdict resets both consecutive-failure counts: the crash streak, and THIS session's
190
+ # evaluator-failure streak (other sessions keep theirs).
191
+ rm -f "$CACHE_DIR/completion-gate-crash.streak" 2>/dev/null
192
+ [ -s "$INFRA_FILE" ] && : > "$INFRA_FILE" 2>/dev/null
140
193
 
141
194
  if [ -n "$OUTPUT" ]; then
142
195
  printf '%s\n' "$OUTPUT"
@@ -2908,6 +2908,9 @@ function applyTaskSemantics(contract, semantic) {
2908
2908
  'hi', 'hello', 'hey', 'yo', 'chao', 'xin', 'good',
2909
2909
  'morning', 'afternoon', 'evening',
2910
2910
  'thanks', 'thank', 'cam', 'on', 'bye', 'tam', 'biet',
2911
+ // Bare acknowledgements ("ok", "có", "được rồi", "yes") are social turns, not work orders:
2912
+ // they must never mint a fresh implementation contract (3.4.81 audit).
2913
+ 'ok', 'okay', 'oke', 'yes', 'yep', 'yeah', 'co', 'duoc', 'vang', 'da', 'u', 'uh', 'um', 'roi', 'dong', 'y',
2911
2914
  ]);
2912
2915
  const filler = new Set([
2913
2916
  'you', 'u', 'there', 'guys', 'everyone', 'all',
@@ -2915,7 +2918,11 @@ function applyTaskSemantics(contract, semantic) {
2915
2918
  'ok', 'okay', 'again', 'still',
2916
2919
  ]);
2917
2920
  let coreHit = false;
2918
- for (const token of tokens) {
2921
+ for (let i = 0; i < tokens.length; i += 1) {
2922
+ const token = tokens[i];
2923
+ // Tone-folding makes "đóng" (close) and "đồng" (as in "đồng ý", agreed) the same token:
2924
+ // only the pair "dong y" is an acknowledgement; "đóng nhé" is an order to close something.
2925
+ if (token === 'dong' && tokens[i + 1] !== 'y') return false;
2919
2926
  if (core.has(token)) {
2920
2927
  coreHit = true;
2921
2928
  } else if (!filler.has(token)) {
@@ -2992,8 +2999,16 @@ function applyTaskSemantics(contract, semantic) {
2992
2999
  return !mutationOrder;
2993
3000
  }
2994
3001
 
3002
+ // Tone-folding turns unrelated Vietnamese words into mutation verbs: "cái" (this/thing) -> cai (cài),
3003
+ // "chính" (main/exactly) -> chinh (chỉnh), "Việt" -> viet (viết), "đợi/đời/đối/đội/đôi/đói" -> doi (đổi),
3004
+ // "cháy/chảy" -> chay (chạy), "sữa" -> sua (sửa), "thèm" -> them (thêm). Mask the toned non-verbs BEFORE
3005
+ // folding, so "Cái này là gì, tại sao…" is not read as an install order (3.4.81 telemetry audit).
3006
+ function maskTonedNonVerbs(text = '') {
3007
+ return String(text ?? '').normalize('NFC')
3008
+ .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, ' _ ');
3009
+ }
2995
3010
  function hasMutationOrder({ promptText = '', commandText = '' } = {}) {
2996
- const folded = `${publicationScope(promptText).text}\n${commandText ?? ''}`
3011
+ const folded = `${publicationScope(maskTonedNonVerbs(promptText)).text}\n${commandText ?? ''}`
2997
3012
  .toLowerCase()
2998
3013
  .normalize('NFD')
2999
3014
  .replace(/[\u0300-\u036f]/g, '')
@@ -3029,6 +3044,11 @@ function applyTaskSemantics(contract, semantic) {
3029
3044
  .replace(new RegExp(`\\bchua\\s+(?:can|nen|phai)\\s+${WAIT_TAIL}`, 'g'), ' ')
3030
3045
  .replace(new RegExp(`\\b(?:neu|if)\\s+${TAIL}`, 'g'), ' ')
3031
3046
  .replace(/\bdoi\s+chieu\b/g, ' ')
3047
+ // Field telemetry (3.4.81 audit): words that fold onto a mutation verb but name no order.
3048
+ // "chưa được cấp quyền cập nhật" / "no permission to update" reports a missing permission (read-only
3049
+ // banners); "gì thêm [nữa]" / "thêm nữa không" mean "anything else", never the verb "add".
3050
+ .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, ' ')
3051
+ .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, ' ')
3032
3052
  .replace(new RegExp(`\\bchua\\s+(?:sua|fix|implement|trien\\s+khai|viet|thay\\s+doi)\\b${WAIT_TAIL}`, 'g'), ' ')
3033
3053
  .replace(/\bhow\s+(?:we|i|you|they)\s+(?:would|will|could|should|might)\b[^.,;\n?]*/g, ' ')
3034
3054
  .replace(/\b(?:would|will|could|might)\s+later\b[^.,;\n?]*/g, ' ')
@@ -3212,6 +3232,11 @@ function applyTaskSemantics(contract, semantic) {
3212
3232
  const questionShapedPrompt = /\?\s*$/.test(trimmedPromptText)
3213
3233
  || leadingInterrogative
3214
3234
  || /\b(?:la gi|duoc khong)\s*$/.test(foldedPromptText)
3235
+ // Field telemetry (3.4.81 audit): a what-is question mid-prompt ("… là gì, …") and a leading
3236
+ // explanation request ("giải thích …", "explain …") ask for an answer. Both still pass the
3237
+ // hasMutationOrder/targetFile veto below, so "giải thích rồi sửa luôn" stays an order.
3238
+ || /\bla gi\s*(?:[,.?!;:\n]|$)/.test(foldedPromptText)
3239
+ || /^(?:hay\s+|vui\s+long\s+|lam\s+on\s+|please\s+)?(?:giai\s+thich|explain)\b/.test(foldedPromptText)
3215
3240
  || /\b(?:chua|duoc khong|dung khong|khong nhi|khong|nhi)\s*[.!?]*\s*$/.test(foldedPromptText);
3216
3241
  // it with hasMutationOrder keeps "sửa file cho tôi?" mutating while
3217
3242
  // "lỗi này chưa nhỉ" / "should I fix the hook?" consult. A targetFile
@@ -4518,9 +4543,19 @@ function applyTaskSemantics(contract, semantic) {
4518
4543
  if (fresh?.taskKind) {
4519
4544
  const identity = semanticContractIdentity({ promptText: previous.routingContext.lastExplicitUserPromptText,
4520
4545
  targetFile: persisted.routingContext?.targetFile || '', taskInstanceId });
4521
- const comparison = compareSemanticContracts({ stored: storedContract,
4522
- fresh: applyTaskSemantics(buildExecutionContract(persisted.routeSummary?.executionMode || 'local-build'), fresh),
4523
- previousIdentity: previous.semanticIdentity, identity });
4546
+ // The execution mode is re-scored on every tool event while the contract stays the task's own, so
4547
+ // the mode of THIS event is not the mode the contract was derived under. A stored contract is
4548
+ // consistent when it equals the derivation under any mode base (telemetry: 170+ false
4549
+ // "invariant violation" Stop blocks from mode churn alone).
4550
+ const derive = (mode) => compareSemanticContracts({ stored: storedContract,
4551
+ fresh: applyTaskSemantics(buildExecutionContract(mode), fresh), previousIdentity: previous.semanticIdentity, identity });
4552
+ let comparison = derive(persisted.routeSummary?.executionMode || 'local-build');
4553
+ if (comparison.status === 'invariant-violation') {
4554
+ for (const mode of ['tiny-fix', 'local-fix', 'local-build', 'find-cause', 'shared-edit', 'map-impact', 'review-release']) {
4555
+ const other = derive(mode);
4556
+ if (other.status === 'equal') { comparison = other; break; }
4557
+ }
4558
+ }
4524
4559
  if (comparison.status === 'invariant-violation') persisted.semanticDiagnostic = comparison;
4525
4560
  else if (comparison.status !== 'equal') semanticFromPrompt = fresh;
4526
4561
  }
@@ -4541,7 +4576,12 @@ function applyTaskSemantics(contract, semantic) {
4541
4576
  && (semantic.taskKind === 'CODE_IMPLEMENTATION' || answerQuestion)
4542
4577
  && (isInformationalPrompt({ promptText: turnPrompt })
4543
4578
  || isPureGreetingPrompt({ promptText: turnPrompt }));
4544
- const unownedToolTurn = !extractPrompt(payload) && payload.tool_name && !storedContract;
4579
+ // A system-injected turn (wakeup / compaction summary) resumes the previous task; when that task holds
4580
+ // no contract (the owner's last turn was a question), the injected wording must not mint one: it was
4581
+ // classified from the wakeup text but bound to the owner's prompt identity, which the gate then
4582
+ // reported as a contradiction on every stop.
4583
+ const unownedToolTurn = (!extractPrompt(payload) && payload.tool_name && !storedContract)
4584
+ || (systemOriginTurn && !storedContract?.taskKind);
4545
4585
  if (informationalTurn || unownedToolTurn) {
4546
4586
  // An answer-only turn must not enforce carried write debt, but it must not ERASE the
4547
4587
  // contract either: park it (session- and task-bound) so a continuation or the next
@@ -4581,13 +4621,14 @@ function applyTaskSemantics(contract, semantic) {
4581
4621
  const kept = { ...persisted.routeSummary.executionContract };
4582
4622
  // statusReport / verificationOnly are only stripped on re-derivation: for a NEW task they drive the
4583
4623
  // carried-status rebuild below, so they must survive to be recognised there.
4584
- const staleKeys = semanticFromPrompt ? ['publication', 'operationGoal', 'configurationScope', 'releasePolicy', 'conditionalObligations', 'reportArtifact', 'verificationOnly', 'statusReport']
4585
- : ['publication', 'operationGoal', 'configurationScope', 'releasePolicy', 'conditionalObligations', 'reportArtifact'];
4624
+ const staleKeys = semanticFromPrompt ? ['publication', 'operationGoal', 'operationGoals', 'configurationScope', 'releasePolicy', 'conditionalObligations', 'reportArtifact', 'verificationOnly', 'statusReport']
4625
+ : ['publication', 'operationGoal', 'operationGoals', 'configurationScope', 'releasePolicy', 'conditionalObligations', 'reportArtifact', 'stateVerification', 'stateAction', 'stateConditionalStop', 'stateTargets'];
4586
4626
  for (const key of staleKeys) delete kept[key];
4587
- // MIXED/OPERATIONAL evidence tags belong to the previous task's classification: a new task starts from
4588
- // the mode's base evidence so it is not asked for operation proof its own prompt never ordered.
4589
- if ((!continuingTask || semanticFromPrompt) && semantic.taskKind !== 'MIXED' && semantic.taskKind !== 'OPERATIONAL'
4590
- && Array.isArray(kept.completionEvidence) && kept.completionEvidence.includes('operation-verification')) {
4627
+ // Evidence tags belong to the previous task's classification (operation-verification, a READ_ONLY
4628
+ // task's impact-evidence, state-verification, ...): a new task starts from the mode's base evidence so
4629
+ // it is not asked for proof its own prompt never ordered. A leaked tag also made the stored contract
4630
+ // differ from its own re-derivation, which the gate reported as an invariant violation.
4631
+ if ((!continuingTask || semanticFromPrompt) && Array.isArray(kept.completionEvidence) && kept.statusReport !== true) {
4591
4632
  const baseMode = persisted.routeSummary.executionMode === 'informational' ? 'local-build' : persisted.routeSummary.executionMode;
4592
4633
  const base = buildExecutionContract(baseMode);
4593
4634
  if (Array.isArray(base?.completionEvidence)) kept.completionEvidence = base.completionEvidence;
@@ -4603,6 +4644,12 @@ function applyTaskSemantics(contract, semantic) {
4603
4644
  if (!carriedStatus || persisted.routingContext?.mutationOrder === true) {
4604
4645
  persisted.routeSummary.executionContract = applyTaskSemantics(
4605
4646
  persisted.routeSummary.executionContract || buildExecutionContract(persisted.routeSummary.executionMode === 'informational' ? 'local-build' : persisted.routeSummary.executionMode), semantic);
4647
+ // A continuing turn re-applies the task's own contract: its evidence list stays as classified, never
4648
+ // re-unioned with the base of whatever mode this tool event happened to score.
4649
+ if (continuingTask && !semanticFromPrompt && semantic === previous.routeSummary?.executionContract
4650
+ && Array.isArray(semantic.completionEvidence) && semantic.completionEvidence.length > 0) {
4651
+ persisted.routeSummary.executionContract.completionEvidence = [...semantic.completionEvidence];
4652
+ }
4606
4653
  if (persisted.contractOrigin !== 'carried-system') persisted.contractOrigin = 'classified';
4607
4654
  }
4608
4655
  if (semantic.taskKind === 'OPERATIONAL' || semantic.taskKind === 'READ_ONLY'
@@ -4716,8 +4763,62 @@ function applyTaskSemantics(contract, semantic) {
4716
4763
  let previous = sessionId
4717
4764
  ? [storedPrevious, sidecarPrevious].find((state) => String(state?.sessionId || '').trim() === sessionId && publishedPrevious(state)) || {}
4718
4765
  : storedPrevious;
4719
- const continuationPrompt = /^(?:continue|resume|keep going|go on|proceed|tiep tuc|lam tiep)(?:\s+(?:with\s+)?(?:the\s+|this\s+)?(?:previous\s+|last\s+|current\s+|same\s+)?(?:implementation\s+)?(?:task|work))?(?:\s+(?:thoi|di|đi|nhe|nao|nua|a|ha|please|pls|now|then))*\s*[.!]?$/i.test(
4766
+ const explicitContinuationPrompt = /^(?:continue|resume|keep going|go on|proceed|tiep tuc|lam tiep)(?:\s+(?:with\s+)?(?:the\s+|this\s+)?(?:previous\s+|last\s+|current\s+|same\s+)?(?:implementation\s+)?(?:task|work))?(?:\s+(?:thoi|di|đi|nhe|nao|nua|a|ha|please|pls|now|then))*\s*[.!]?$/i.test(
4720
4767
  extractPrompt(payload).normalize('NFD').replace(/[̀-ͯ]/g, '').trim());
4768
+ // A bare "yes / ok / có / được / ừ" is normally a social turn that parks the previous contract. When it
4769
+ // ANSWERS a question the agent itself just asked ("shall I apply the fix?"), it is the owner's go-ahead for
4770
+ // that same task: parking the contract there let the agent stop without the edit it had just offered.
4771
+ // Proof is host-authored only: the last assistant text in this session's transcript must end with a
4772
+ // question. No transcript (or anything else in between) keeps the conservative parking behaviour.
4773
+ const affirmativeAnswerTurn = (() => {
4774
+ if (payload.tool_name || !sessionId) return false;
4775
+ const armed = previous.routeSummary?.executionContract?.completionEvidence?.length
4776
+ || previous.suspendedContract?.routeSummary?.executionContract?.completionEvidence?.length;
4777
+ if (!armed) return false;
4778
+ const raw = extractPrompt(payload).trim();
4779
+ if (!raw || raw.length > 40) return false;
4780
+ const tokens = raw.toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/đ/g, 'd')
4781
+ .replace(/[^a-z0-9\s]/g, ' ').split(/\s+/).filter(Boolean);
4782
+ if (tokens.length === 0 || tokens.length > 4) return false;
4783
+ const yes = new Set(['ok', 'okay', 'oke', 'yes', 'yep', 'yeah', 'co', 'duoc', 'vang', 'da', 'u', 'uh', 'dong', 'y']);
4784
+ const soft = new Set(['nhe', 'nha', 'please', 'pls']);
4785
+ if (!tokens.some((t) => yes.has(t)) || !tokens.every((t) => yes.has(t) || soft.has(t))) return false;
4786
+ if (tokens.some((t, i) => t === 'dong' && tokens[i + 1] !== 'y')) return false;
4787
+ const tp = payload.transcript_path ?? payload.transcriptPath;
4788
+ if (!tp || typeof tp !== 'string') return false;
4789
+ try {
4790
+ const fd = fs.openSync(tp, 'r');
4791
+ try {
4792
+ const size = fs.fstatSync(fd).size;
4793
+ const len = Math.min(size, 256 * 1024);
4794
+ const buf = Buffer.alloc(len);
4795
+ fs.readSync(fd, buf, 0, len, size - len);
4796
+ const lines = buf.toString('utf8').split('\n');
4797
+ const textOf = (entry) => {
4798
+ const content = entry?.message?.content;
4799
+ if (typeof content === 'string') return content;
4800
+ if (!Array.isArray(content)) return '';
4801
+ return content.filter((part) => part?.type === 'text' && typeof part.text === 'string').map((part) => part.text).join('\n');
4802
+ };
4803
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
4804
+ const line = lines[i];
4805
+ if (!line || !(line.includes('"assistant"') || line.includes('"user"'))) continue;
4806
+ let entry; try { entry = JSON.parse(line); } catch { continue; }
4807
+ if (entry?.isSidechain === true || (entry?.sessionId && entry.sessionId !== sessionId)) continue;
4808
+ const text = textOf(entry).trim();
4809
+ if (!text) continue; // tool calls / tool results carry no prose
4810
+ if (entry.type === 'user') {
4811
+ if (entry.isMeta === true || text === raw) continue; // this very prompt, already written by the host
4812
+ return false; // another owner turn sits between the question and this reply
4813
+ }
4814
+ if (entry.type !== 'assistant') continue;
4815
+ return /[??][\s)\]"'*_`]*$/.test(text.slice(-400));
4816
+ }
4817
+ } finally { fs.closeSync(fd); }
4818
+ } catch { /* unreadable transcript: no proof */ }
4819
+ return false;
4820
+ })();
4821
+ const continuationPrompt = explicitContinuationPrompt || affirmativeAnswerTurn;
4721
4822
  // Restore a contract parked by an informational turn: only for the SAME session, and only
4722
4823
  // on an explicit continuation or a mutating tool event (never a fresh prompt, which routes on its own,
4723
4824
  // and never a read during an answer/status turn: that must not resurrect write debt).
@@ -5352,7 +5453,7 @@ function applyTaskSemantics(contract, semantic) {
5352
5453
  || hasAdvisoryOnlyAssertion({ promptText, commandText })) && !filePath;
5353
5454
  // Greeting fast-path: a pure greeting gets the same read-only stamp as an
5354
5455
  // informational question — never a mutating lane, never task debt.
5355
- const greetingFastPath = !filePath && isPureGreetingPrompt({ promptText, commandText });
5456
+ const greetingFastPath = !filePath && !affirmativeAnswerTurn && isPureGreetingPrompt({ promptText, commandText });
5356
5457
  // A delivery-only prompt ("push this to git", "đẩy bộ này lên git") starts a new,
5357
5458
  // mutation-free action and typically matches no skill. It must not inherit the
5358
5459
  // previous request's completion contract — carrying find-cause/map-impact debt
@@ -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
  }
@@ -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 });
@@ -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
  }