@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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,35 @@
2
2
 
3
3
  All notable changes to UKit are documented here.
4
4
 
5
+ ## 3.4.83 - 2026-11-13
6
+
7
+ Hook fixes from a one-week audit of this repository's own Claude Code transcripts, hook-latency rows, decision log and permission audit log (6,685 hook runs, no hook timeouts; Stop p95 about 1.6s).
8
+
9
+ - Fix: **`auto-allow-bash` no longer mints junk permission rules.** The binary was picked by whitespace splitting, so a leading assignment with a quoted or substituted value was cut in half and the next fragment became the "binary": `UKIT_EVIDENCE='… HEAD …' yarn test` minted `Bash(HEAD:*)`, `d=$(ls -td …)` minted `Bash(-td:*)`. The hook now scans real shell words (single/double quotes, `$(…)` with nesting, backticks, backslash escapes), skips whole `NAME=value` / `NAME+=value` words, and mints nothing when the first command word cannot be determined (unbalanced quote or substitution, leading operator, redirection or subshell) or starts with `-`. Behaviour change: `command -v node` and `env -i FOO=1 ls` now mint nothing (they minted `-v` / `-i`). The denylist block, charset check, interpreter list and locked atomic write are unchanged. omp runs this same script through its bridge; Codex has no auto-allow lane.
10
+ - Fix: `reset-auto-permissions.mjs --sanitize` also removes rules whose token starts with `-` (option fragments left by the old tokenizer), behind the same proven-provenance gate. Other junk words (`HEAD`, `status`, `view` …) cannot be told apart from real binaries and are left in place; the full reset removes every UKit-managed rule.
11
+ - Fix: **`task-watchdog` no longer announces "payload was truncated or stalled" on large Edit/Write calls.** Its PostToolUse path reads only the event name from the payload (tasks, state and config come from disk), yet any payload over the 64 KiB staging cap was reported as incomplete input. A payload cut only by the size cap, whose event name is provably complete and exactly `PostToolUse`, now runs normally. Stalled staging, an unrecoverable event name, Stop (which forwards the raw payload to the coordinator) and the pre-install fallback branch keep the announced degrade.
12
+ - Fix: **self-improve no longer mints handoff tasks for failures that never happened.** The `timeout-hang` class matched `timeout|hang|hung` anywhere in a command's text, so "c*hang*elog", "unc*hang*ed", a test file named `verifyReleaseTimeout.test.js` or an env var `UKIT_VERIFY_STEP_TIMEOUT_MS` each produced an `AUTO-<n>.md` task telling the executor to raise a timeout. Mined patterns now carry the failed receipts' exit codes (`exitCodes`); `timeout-hang` needs exit 124 or a whole-word marker ("timed out", "timeout exceeded/expired", "hangs", "hanging", "hung") on the command's invocation lines — heredoc bodies and comment lines are not read. The other three classes use whole-word matches on the same stripped text. Known limit: a timeout the host kills with exit 1 or 137 is not classified (a missed task, not a wrong one).
13
+ - Fix (tests only): hook latency telemetry from test runs no longer lands in the repository's own `.ukit/storage/cache/hook-latency/` (seven test files spawned hooks against the real root; about 4,200 rows over five days). `appendTelemetryRow` drops rows for the root named by `UKIT_TELEMETRY_DENY_ROOT`, which only this repository's `vitest.config.js` sets; unset, it is inert.
14
+ - Fix (pre-release review): the new scanner gives up — mints nothing — on constructs whose end it cannot prove. Two review rounds each found a command resolving to the wrong binary (`X=$'\' curl ' ls` and `A=${x:- curl } ls` both minted `Bash(curl:*)` while bash runs `ls`). Every `$` now goes through one helper that accepts only `$(…)`, `$NAME` and a simple `${NAME}`; ANSI-C/locale quoting (`$'…'`, `$"…"`), any other `${…}`, `$[…]`, and a `#`, heredoc or `case` inside `$(…)` mint nothing. The scan is bounded to the first 4,096 characters of the command (a 100 KB assignment value stalled the hook for more than 45 seconds; a first command word not resolved inside the window mints nothing), and variable names are matched against explicit ASCII classes (`É=a ls` no longer counts as an assignment).
15
+ - Tests: `tests/hooks/autoAllowBinaryResolution.test.js` (41), four size-truncation cases in `tests/hooks/taskWatchdog.test.js`, classifier and `exitCodes` cases in `tests/core/codeProposals.test.js` / `tests/core/failurePatterns.test.js`.
16
+ - Packaging: the 2.5.1–2.6.11 changelog entries moved verbatim to `docs/archive/CHANGELOG-2.5.1-2.6.11.md` (repository only); size limits unchanged.
17
+ - Not changed: decision-plane shadow calls to the local `unic-decision` endpoint timed out 184 times in the audited week and five decision keys never returned a valid answer — shadow-only, not root-caused in this release.
18
+
19
+ ## 3.4.82 - 2026-11-10
20
+
21
+ Completion-gate fixes from a field-telemetry audit of the projects running UKit (Stop/gate logs, hook latency, route state, session transcripts).
22
+
23
+ - 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.
24
+ - 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).
25
+ - 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.
26
+ - 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.
27
+ - 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".
28
+ - 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.
29
+ - 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).
30
+ - 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.
31
+ - 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`.
32
+ - 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.
33
+
5
34
  ## 3.4.81 - 2026-11-08
6
35
 
7
36
  - 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.
@@ -1166,405 +1195,6 @@ OMP fully autonomous / unattended mode — cycle C35 (TASK-008..014).
1166
1195
  note); opencode `bash."*": "ask"` flip deferred pending deny-set
1167
1196
  expansion.
1168
1197
 
1169
- ## 2.6.11 - 2026-09-20
1170
-
1171
- Self-improvement roadmap phases 2–4 — cycle C32 (TASK-227..232).
1172
-
1173
- - Feedback capture: `src/diagnostics/feedbackEvents.js` + shared
1174
- `ledgerFiles.js` ledger helper record labeled wrong-route /
1175
- manual-correction events; new `ukit feedback` CLI.
1176
- - Telemetry emitters: `skillIds` in route-audit entries
1177
- (`route-task.mjs`); retriever lane stats appended to
1178
- `.ukit/storage/cache/retriever-lanes.jsonl` (`retriever.js`).
1179
- - Metrics surfaces: `skillAccuracy.js` + `laneStats.js` collectors;
1180
- `ukit metrics` gains `feedback`, `skills`, `retriever-lanes`, and
1181
- `learning` sections (lazy-import, degrade to `n/a`).
1182
- - Memory promotion lanes: `ukit memory learn` mines failure-patterns into
1183
- pending `ukit memory propose` candidates (`src/learning/patternProposals.js`);
1184
- `ukit memory promote` writes approved project_rule/procedure records to
1185
- MEMORY.md `## ukit-learned`; `ukit memory episode` writes a session-episode
1186
- record (`--session`/`UKIT_SESSION_ID`/latest-ledger resolution) plus
1187
- SessionEnd hook `session-episode.sh`.
1188
- - Tuning loop: `learning.*` config namespace (validated in runtimeConfig,
1189
- template parity) + `src/learning/tuning.js` advisory lane-weight/threshold
1190
- suggestions.
1191
- - Verification: per-task suites green on rerun; `.claude`↔`templates/.claude`
1192
- parity diff-clean. 6/6 tasks approved, 0 fix rounds.
1193
-
1194
- ## 2.6.10 - 2026-09-20
1195
-
1196
- Self-improvement roadmap phase 1 — cycle C31 (HK-401, SI-101..103).
1197
-
1198
- - Hook contract fix: centralized `ukit_emit_permission_decision` in
1199
- hook-input.sh (keyed on `UKIT_HOOK_CHAIN_RUNNER`); bypassPermissions probe
1200
- replaced with locked fallback deny + exit 0 — dead `ask` path closed.
1201
- - Router v2-memory lane: `listMemoryItems` reads memory records.json;
1202
- `record` branch added to buildMemorySegments.
1203
- - Outcome join: `routeOutcomes.js` joins route-audit × exec-ledger on
1204
- requestKey; new `ukit metrics` command surfaces route accuracy.
1205
- - Failure mining: `failurePatterns.js` mines exec-ledger into
1206
- failure-patterns.json (advisory, never-throws).
1207
- - Self-improvement surface audit + roadmap spec:
1208
- `docs/research/2026-09-20_self-improvement-surface-audit.md`.
1209
-
1210
- ## 2.6.9 - 2026-09-19
1211
-
1212
- Code Intelligence scale release — cycle C30 (CI-301..305, TASK-218..222).
1213
-
1214
- - Vector lane: dep-free `vectorProvider.js` (FNV-1a feature-hashed embeddings,
1215
- L2-normalized, cosine-ranked; injectable loader seam for real embeddings,
1216
- degrade to hashed/null); wired as RRF lane w=0.6 between bm25 and semantic.
1217
- - Analogy lane: `analogy.js` fingerprints memory `procedure` records + index
1218
- symbols/files; `analogy` compile mode ranks by Jaccard, hits land in
1219
- packet.memory + L2 evidence.
1220
- - Co-change mining: `cochange.js` mines `git log --name-only` (spawnSync,
1221
- bounded, core.quotePath=false) into `cochange.json`; impact sets gain a
1222
- provenance-preserving co-change lane (kind:'cochange', confidence=count/10).
1223
- - L3 summaries: `summaries.js` extractive docblock/symbol summaries for
1224
- deep_flow+analogy packets; `packetToText` renders `summary:` lines.
1225
- - Graph store: `graph.js` `codegraph.json` JsonGraphStore (imports+calls+
1226
- cochange → nodes/edges, content-gated atomic write), contract-only
1227
- scip/pdg/lsp stubs via `createGraphProvider`.
1228
- - Derived artifacts wired into `ukit index build|refresh`, stale-refresh,
1229
- install, and index scripts via `buildDerivedIndexArtifacts` (config-gated,
1230
- never fatal, outside the core build's atomic-rename contract).
1231
- - Config: `codeIntel.{embedding,analogy,cochange,summaries,graph}` +
1232
- `retriever.weights.vector` validated in runtimeConfig with template parity;
1233
- `enabled:false` honored for analogy/graph lanes.
1234
- - Verification: full suite 2720/2720 green; unpacked ceiling 6.9MB.
1235
-
1236
- ## 2.6.8 - 2026-09-19
1237
-
1238
- Code Intelligence Plane + memory v2 release — cycles C26–C29
1239
- (TASK-001..011, CI-201..206, DOC-201..206, DOC-301..305).
1240
-
1241
- - Memory v2: 4-type record model (`project_rule|derived_fact|episode|procedure`),
1242
- atomic `records.json` store, backup-first idempotent migration from v1,
1243
- `ukit memory v2` ops; legacy `.ukit/storage/memory/` layout and all
1244
- `ukit memory *` subcommands stay compatible.
1245
- - Code Intelligence Plane: `compileContext` → Context Packet v1 with
1246
- peek→expand→read levels and token budgets; Task Router v1; freshness
1247
- identity (`HEAD + overlay + config`) with incremental dirty-gated reuse
1248
- and per-branch snapshots; hybrid retriever (exact + symbol + BM25 + RRF
1249
- rerank); `impact.js` multi-hop impact sets; post-edit `invalidation.js`
1250
- dirty-set and `diagnostics.js` feeding packet `next_actions`;
1251
- `TypeScriptSemanticProvider` (optional `typescript` import — no new deps,
1252
- degrade-safe).
1253
- - CLI: `ukit code peek|search|context|impact` (`--depth`, `--diagnostics`),
1254
- `ukit index status|doctor`, `ukit doctor --docs` (doc-contract checks).
1255
- - Docs governance: `docContracts.js` validator (links/stale-version/
1256
- render-vars/commands/budgets/registry/templates/dead-docs/archive-suggestions),
1257
- `context_layers` + `docs=` route segment, host capability matrix, BUG docs
1258
- consolidated into `docs/BUG_INDEX.md`, PROMPT_CACHING canonical/vendor split,
1259
- `templates/instructions/core.md` 210→157 lines.
1260
- - Benchmarks: `scripts/bench/runGold.mjs` scorecard + `--json` export.
1261
-
1262
- ## 2.6.7 - 2026-09-19
1263
-
1264
- Canonical-instructions release — second roadmap slice (cycle C25,
1265
- DOC-101..107). Root instruction files are now generated from a single
1266
- canonical source; shipped contracts shrink ~25%; no runtime behavior
1267
- changes to install/update/uninstall flows.
1268
-
1269
- - **DOC-102 — deterministic core/overlay renderer**: new
1270
- `templates/instructions/` sources (`core.md` + host overlays +
1271
- `layout.yaml`) rendered by `src/render/instructionRenderer.js` into
1272
- `templates/CLAUDE.md`, `templates/AGENTS.md`, `templates/.omp/RULES.md`
1273
- (plus repo roots). `yarn docs:render` regenerates; `yarn docs:render:check`
1274
- fails CI on drift. Byte-stable, duplicate-heading and unreferenced-section
1275
- errors enforced.
1276
- - **DOC-101 — rule IDs + markers**: `manifests/instructionRules.yaml`
1277
- declares 48 rule IDs (kind/anchor/marker_in); `<!-- RULE: ID -->` markers
1278
- embedded in the 4 marker-bearing artifacts; `instructionRules.test.js`
1279
- validates schema, marker coverage, and anchor presence.
1280
- - **DOC-103 — parity → semantic tests**: `contextDocsParity.test.js`
1281
- rewritten to generated-artifact checks (drift, rule coverage, overlay
1282
- heading allowlists, Release Policy boundary) + mutation tests that fail
1283
- on dropped/duplicate critical rules; shared helpers in
1284
- `tests/consistency/helpers/semanticParity.js`.
1285
- - **DOC-104 — root contract shrink ≥25%**: `templates/CLAUDE.md` 288→214
1286
- lines, `templates/AGENTS.md` 305→229 (all critical rule markers + anchors
1287
- preserved). Internal-orchestration detail moved to new shipped doc
1288
- `templates/docs/UKIT_INTERNALS.md` (manifest item `docs-ukit-internals`);
1289
- baselines recorded in `docs/_baseline/root-instruction-lines.txt`.
1290
- - **DOC-105 — WORKLOG rotation + MEMORY cleanup**: live worklog ≤500 lines,
1291
- rotated entries preserved in `docs/WORKLOG_ARCHIVE.md` (regression-tested);
1292
- MEMORY.md trimmed to durable protocol/decisions/constraints (≤200).
1293
- - **DOC-106 — PROJECT_IMPORTANT_SPEC archived**: shrunk to a decision
1294
- record; full body at `docs/archive/specs/PROJECT_IMPORTANT_SPEC.md`;
1295
- `docArchiveLinks.test.js` guards link integrity.
1296
- - **DOC-107 — user-first README**: rewritten around `ukit install` +
1297
- natural-language flow (115 lines); maintainer detail moved to linked docs.
1298
-
1299
- ## 2.6.6 - 2026-09-19
1300
-
1301
- Documentation-hardening release — first slice of the
1302
- DOCUMENTATION_IMPROVEMENT_ROADMAP (cycle C24, DOC-001..006). No runtime
1303
- behavior changes: new manifest, new test lanes, doc cleanup, and a shipped
1304
- registry the remaining roadmap items build on.
1305
-
1306
- - **DOC-001 — documentation ownership/source registry**: new
1307
- `manifests/documentation.yaml` classifies every active/template/adapter
1308
- documentation surface (owner, source_of_truth, merge_strategy, budget);
1309
- `tests/consistency/docRegistry.test.js` enforces schema, coverage,
1310
- manifest-skip consistency, and `error`-level budgets.
1311
- - **DOC-002 — cross-agent benchmark corpus**: spec + fixtures at
1312
- `tests/fixtures/doc-benchmark/` (corpus index, 4 host files, 9+ task files);
1313
- `tests/benchmarks/docBenchmarkCorpus.test.js` validates structure and
1314
- registry cross-references. Host execution deferred — every host recorded
1315
- `untested` (roadmap-permitted).
1316
- - **DOC-003 — artifact reference-integrity checks**:
1317
- `tests/integration/artifactReferenceIntegrity.test.js` fails when a shipped
1318
- instruction/skill doc references an internal command/file that does not
1319
- resolve into the `npm pack` artifact (or the declared runtime-generated
1320
- allowlist); wired into `yarn test:artifact`.
1321
- - **DOC-004 — owner-file preservation lifecycle tests**:
1322
- `tests/integration/ownerPreservation.test.js` proves install/update/uninstall
1323
- preserve exact bytes and symlink posture of every registry
1324
- `merge_strategy: skip` file, including BOM/CRLF and absent-seed cases.
1325
- - **DOC-005 — STATUS.md live snapshot**: `docs/STATUS.md` shrunk to a ≤150-line
1326
- live snapshot; historical body preserved verbatim at
1327
- `docs/archive/status/STATUS-2026-09-19.md` with two-way links; registry
1328
- budget for STATUS.md flipped to `error`.
1329
- - **DOC-006 — adapter stale-version cleanup**: zero stale `vX.Y.Z` literals on
1330
- adapter doc surfaces (`templates/.codex/README.md`, `.codex/README.md`,
1331
- `templates/ukit/README.md`, `.ukit/README.md`); Codex-specific mechanics
1332
- retained; `tests/consistency/staleVersionProse.test.js` enforces.
1333
-
1334
- ## 2.6.5 - 2026-09-19
1335
-
1336
- Stability release — third full audit pass on the 2.6.4 base (cycle C23). 15
1337
- confirmed hang / freeze / silent-idle / silent-hook defects fixed with root
1338
- causes (full register: `docs/AI_HANDOFF/BUGS-2.6.5.md`). Headline: the
1339
- cycle-lockout mechanism observed live — stall-breaker streak erased on every
1340
- Stop (BUG-C23-08) — is fixed, plus every blocking/degrading hook exit now
1341
- announces on stdout per the §8 contract.
1342
-
1343
- - **Handoff stall-breaker streak erased every Stop (BUG-C23-08)**: the
1344
- stop-coordinator dedupe write dropped the `handoff` streak slot, so a wedged
1345
- RUN.md blocked forever; the merge now preserves the slot.
1346
- - **Silent non-zero hook failures (BUG-C23-01, -03, -07)**: stderr-only crash
1347
- reasons in `output-compression`/`reinject-context`/`post-edit-verify`/
1348
- `stale-spec-check` + safe-patch exit-2 blocks + skill-router/vision-router/
1349
- task-watchdog crash paths now emit a stdout `systemMessage` before exit —
1350
- stderr reaches the model, not reliably the user.
1351
- - **Lost/silent deadline emissions (BUG-C23-02, -04)**: compact-threshold's
1352
- same-tick `stdout.write` + `process.exit(0)` discarded the announce on pipes
1353
- (now `writeSync(1)`); deadline-expiry `exit 0` in four called `.mjs` modules
1354
- and `handoff-resume.sh` now announces the abandoned work.
1355
- - **Fail-open/crash-posture defects (BUG-C23-05, -06)**: context-hardcap-gate's
1356
- internal-error catch now announces its fail-open degrade on stdout;
1357
- completion-gate's stop-coordinator spawn is deadline-bounded with forced
1358
- kill routed to the crash-streak path.
1359
- - **Silent data loss + hot-path waste (BUG-C23-09, -10, -13, -15)**:
1360
- compact-threshold double capacity read collapsed to one; sweep failures
1361
- announce (bounded) instead of `.catch(() => {})` swallow; unguarded `main()`
1362
- no longer runs on `import()`; route-audit merges stage to an append-only
1363
- sidecar with a locked + exit fold instead of silently dropping entries.
1364
- - **Unbounded growth + unbounded stalls (BUG-C23-11, -12, -14)**: memory
1365
- project archives capped; `permission-audit.log` rotates inside the prune
1366
- pass; `bin/ukit` runCli got an overall deadline watchdog.
1367
-
1368
- Regression gate: 138 files / 2360 tests green, liveness 120/120, §8 sweep
1369
- clean, template↔installed parity byte-identical, async-caller census clean,
1370
- all 25 C22 verdicts re-confirmed.
1371
-
1372
- ## 2.6.4 - 2026-09-19
1373
-
1374
- Stability release — second full audit pass on the 2.6.3 base (cycle C22). 25
1375
- confirmed hang / freeze / silent-idle / silent-hook defects fixed with root causes
1376
- (full register: `docs/AI_HANDOFF/BUGS-2.6.4.md`), including the two carried C21
1377
- residual lineages: **R1** (sync fs inside the hardcap-gate deadline → BUG-C22-01)
1378
- and **R2** (sync fs inside handoff-resume deadline → BUG-C22-02).
1379
-
1380
- - **Stalled-mount freeze in the compact/hardcap chain (R1, BUG-C22-01)**: the entire
1381
- compact-threshold fs path (`readNegotiatedCapacity`, `buildCompactThresholds`,
1382
- `resolveCompactPhase`, `buildCompactPressureState`, pressure registration, compact
1383
- plan) converted to async `fsp`; every caller in hooks, `src/core/compact`, and
1384
- `src/core/status.js` now awaits; `isDirectRun` in `execution-ledger.mjs` /
1385
- `stop-coordinator.mjs` guards `realpathSync` behind a basename check so module
1386
- import no longer does sync fs on the deadline path.
1387
- - **handoff-resume sync fs inside its deadline (R2, BUG-C22-02)** plus the same
1388
- sync-fs-under-deadline class in `reset-compact-pressure` (BUG-C22-03),
1389
- `auto-prune-bash` (BUG-C22-04) and `auto-allow-bash` (BUG-C22-06) — sync calls
1390
- inside armed unref'd hook deadlines parked the event loop so the deadline itself
1391
- could never fire.
1392
- - **Stop-gate crash → block-forever (BUG-C22-05)**: a `completion-gate` coordinator
1393
- crash used to produce an unconditional `decision:block` on every subsequent stop.
1394
- New crash-streak breaker (`.ukit/storage/cache/completion-gate-crash.streak`,
1395
- byte-append counter, cap `handoff.fullstack.stopGateMaxCrashStreaks` default 3)
1396
- fails closed up to the cap then releases *loud*; omp bridge got the identical
1397
- try/catch + streak parity.
1398
- - **Silent `exit 0` / `exit(0)` clusters now announce (§8 contract)**: missing-script
1399
- silent exits in 4 hooks (BUG-C22-07), deadline-expiry silent exits on 3 gated
1400
- hooks plus the hardcap-gate sites (BUG-C22-08), and `verification-guard`
1401
- stderr-only catch-all (BUG-C22-09) all emit the fail-open §8 JSON + stderr
1402
- announcement instead of going quiet.
1403
- - **Unbounded spawned children get self-deadlines**: `compact-threshold.mjs`
1404
- `runCli` (BUG-C22-15, `UKIT_COMPACT_CLI_DEADLINE_MS` default 4s — bounds the
1405
- skill-router spawn too), `verify-release.mjs` spawn watchdog + tree-kill
1406
- (BUG-C22-20), `parallel-agents.mjs` per-level `UKIT_BENCH_LEVEL_TIMEOUT_MS`
1407
- 30 min deadline with detached process-group SIGKILL (BUG-C22-21).
1408
- - **`withFileLock` busy-spin on persistent stat errors (BUG-C22-16 runtime twin /
1409
- BUG-C22-17 core twin)**: a stat error inside the retry loop skipped both the
1410
- `maxWaitMs` check and the backoff sleep → tight spin for the process lifetime.
1411
- The budget check now lives inside the catch path in both copies.
1412
- - **Sweep caps that could never fire (BUG-C22-10/11/12/13)**: tee sweep,
1413
- hook-telemetry sweep, exec-ledger sweep and omp hook-errors sweep computed the
1414
- overflow from the scanned *sample* instead of the eligible count, so configured
1415
- max-file caps (e.g. `TEE_MAX_FILES=500`) were unreachable.
1416
- - **Vision receipts eaten / orphaned (BUG-C22-14/18)**: the vision marker-dir sweep
1417
- deleted `analyzed-*` receipts early → vision gate re-fired on every image; legacy
1418
- top-level `vision/analyzed-*.json` orphans had no pruner at all. Both prunes are
1419
- now TTL-coordinated with `isAlreadyAnalyzed`.
1420
- - **Unbounded `.bak` backup writer (BUG-C22-19)**: `.claude/ukit/.ukit/backups/`
1421
- had no pruner; `pruneOldBackups` is now bounded.
1422
- - **Registered timeout < internal worst case (BUG-C22-22/23/24/25)**:
1423
- `auto-allow-bash` 12→15s (internal worst 13s), `skill-router` 8→20s (worst
1424
- ~18s), `stale-spec-guard` 8→11s, and omp chain child budget 4000→12000ms with
1425
- ceiling 16000→52000ms — a hook can no longer be killed mid-work by a budget
1426
- smaller than its own declared worst case.
1427
-
1428
- Full fixed-bug enumeration (register `docs/AI_HANDOFF/BUGS-2.6.4.md`, all rows
1429
- `verified`):
1430
-
1431
- - BUG-C22-01 (R1) — sync fs inside hardcap-gate deadline (compact-threshold + execution-ledger)
1432
- - BUG-C22-02 (R2) — sync fs inside handoff-resume deadline
1433
- - BUG-C22-03 — reset-compact-pressure: swallow-all + sync fs inside deadline
1434
- - BUG-C22-04 — auto-prune-bash: invisible prune failure + sync fs inside deadline
1435
- - BUG-C22-05 — completion-gate: persistent coordinator crash → block-forever (crash-streak breaker)
1436
- - BUG-C22-06 — auto-allow-bash: sync fs inside deadline
1437
- - BUG-C22-07 — missing-script silent `exit 0` cluster (4 hooks)
1438
- - BUG-C22-08 — deadline-expiry silent `exit(0)` on gated hooks (+ hardcap sites)
1439
- - BUG-C22-09 — verification-guard catch-all degrade on stderr only
1440
- - BUG-C22-10 — tee sweep count cap unreachable (`TEE_MAX_FILES=500` never enforced)
1441
- - BUG-C22-11 — hook-telemetry sweep count cap unreachable
1442
- - BUG-C22-12 — exec-ledger sweep count cap unreachable
1443
- - BUG-C22-13 — omp hook-errors sweep count cap unreachable
1444
- - BUG-C22-14 — vision marker-dir sweep deletes `analyzed-*` receipts → vision gate re-fires
1445
- - BUG-C22-15 — skill-router spawns `node compact-threshold.mjs prompt` unbounded (CLI self-deadline)
1446
- - BUG-C22-16 — `withFileLock` busy-spin, runtime twin (token-utils.mjs)
1447
- - BUG-C22-17 — `withFileLock` busy-spin, core twin (fileOps.js)
1448
- - BUG-C22-18 — legacy top-level `vision/analyzed-*.json` orphans never pruned
1449
- - BUG-C22-19 — `.claude/ukit/.ukit/backups/` `.bak` writer had no pruner
1450
- - BUG-C22-20 — `verify-release.mjs` spawns with no timeout (watchdog + tree-kill)
1451
- - BUG-C22-21 — `parallel-agents.mjs` N children, no timeout, partial-settle hang
1452
- - BUG-C22-22 — auto-allow-bash registered timeout < internal worst case (12→15s)
1453
- - BUG-C22-23 — skill-router registered timeout < internal worst case (8→20s)
1454
- - BUG-C22-24 — stale-spec-guard registered timeout zero margin (8→11s)
1455
- - BUG-C22-25 — omp chain child budget < every staged hook's worst case (4000→12000ms, ceiling 16000→52000ms)
1456
-
1457
- ## 2.6.3 - 2026-09-18
1458
-
1459
- - **Informational side-questions no longer self-block at the Stop gate.** A no-route
1460
- question ("còn task nào dang dở không", "is anything left?") carries the previous
1461
- prompt's `routeSummary` + completion contract forward by design — but the prompt
1462
- re-key also empties the effective ledger, so the gate unconditionally demanded
1463
- write+verification evidence that a text answer can never produce. `evaluateCompletion`
1464
- now releases silently when the turn is informational (routed `executionMode` or the
1465
- no-route branch's `routingContext.executionMode` marker). The carried contract stays
1466
- on disk, so real work after the question is still gated. One fix covers Claude Code
1467
- and omp (shared `execution-ledger.mjs`). 3 regression tests.
1468
-
1469
- ## 2.6.2 - 2026-09-18
1470
-
1471
- Stability release — 17 confirmed hang / silent-idle / silent-hook defects fixed with
1472
- root causes (full register: `docs/AI_HANDOFF/BUGS-2.6.2.md`), focused on the "system
1473
- goes quiet and does nothing" failure class.
1474
-
1475
- - **No more silent degraded input (§8 contract, BUG-C21-01/02/03)**: every hook that
1476
- stages stdin now *announces* when staging fails, stalls, or refuses — fail-closed
1477
- hooks (`block-dangerous`, `protect-files`, `context-hardcap-gate`,
1478
- `sensitive-data-guard`) emit an `ask`/`systemMessage` JSON + stderr `BLOCKED` +
1479
- `exit 2`; advisory hooks emit a `systemMessage` + `exit 0`. The old bounded-cut
1480
- silently truncated and proceeded. `sensitive-data-guard` now also fails closed
1481
- (exit 2) on any non-refusal staging failure and mirrors its deadline block to
1482
- stderr so the reason survives `process.exit` truncation.
1483
- - **Sync-fs defeats inside self-deadlines removed (BUG-C21-04)**: the
1484
- deadline-guarded node blocks in `context-window-guard.sh` and
1485
- `context-hardcap-gate.sh` no longer call synchronous `fs.*Sync` inside the kill
1486
- window — a stalled `.ukit` mount can no longer freeze the gate so the unref'd
1487
- deadline can never fire. (Residual call-frame past the grant boundary recorded
1488
- as BUG-C21-R1/R2 for the next cycle.)
1489
- - **Host timeouts now cover internal budgets (BUG-C21-05)**: every hook registered
1490
- in `settings.json` gets `timeout ≥ stage bound + node deadline + margin`; the
1491
- regression test iterates *all* registered hooks instead of a hand-picked list,
1492
- and four under-budgeted hooks (`auto-allow-bash`, `vision-router`,
1493
- `auto-prune-bash`, `reset-compact-pressure`) were raised to 12s.
1494
- - **Missing `await` in skill-router (review major)**: an un-awaited async context
1495
- snapshot could leave the router writing a stale/partial decision silently.
1496
- - **CLI hangs eliminated (BUG-C21-12/13)**: `ukit update`/`install` `spawnSync`
1497
- calls now carry timeouts with `killSignal: 'SIGKILL'` (SIGTERM alone keeps
1498
- waiting on signal-resistant children); a wedged `npm root -g` now reports
1499
- `global-root-query-timeout` instead of hanging forever. `promptYesNo` resolves
1500
- on stdin EOF / `ERR_USE_AFTER_CLOSE` instead of hanging or crashing.
1501
- - **Unbounded growth bounded (BUG-C21-07/09/10/11)**: `tee/` cache, hook-errors
1502
- jsonl, hook-latency and exec-ledger session files now have count caps; the
1503
- ledger protects receipt files (`.journal`, `.quarantine`, gate crash counter)
1504
- from count-cap eviction, and the overflow basis uses `entries.length`
1505
- (post-filter) everywhere.
1506
- - **Handoff machinery (BUG-C21-15)**: all four `RUN.md` `Phase:` consumers treat
1507
- `done`/`blocked` as terminal — dead runs no longer nag forever.
1508
- - **Wiring/parity (BUG-C21-06/08/14/16/17)**: stale-spec-guard deadline exits
1509
- distinguish "stall" from "match"; `provision-worktree` spawnSync calls carry
1510
- timeouts; `task-budget-validator.mjs` is manifest-covered so the documented
1511
- command works on fresh installs; `verification-guard.sh` is actually registered
1512
- on PreToolUse Bash; shipped `config.json` regained `codex-context-budget` and a
1513
- parity test now guards every array field under `subagents`.
1514
-
1515
-
1516
- ## 2.6.0 - 2026-09-18
1517
-
1518
- handoff-fullstack v2 — autonomous create→implement→review loop that runs to 100%
1519
- completion of all unfinished work, with a mandatory detailed SPEC gate.
1520
-
1521
- - **Never-stall Stop gate**: `stop-coordinator.mjs` gained a `handoff-cursor` lane that
1522
- reads `docs/AI_HANDOFF/RUN.md` and blocks stop while `Phase:` is not `done`/`blocked`,
1523
- carrying the cursor's `Next:` step. Liveness breaker releases after
1524
- `handoff.fullstack.stopGateMaxStalledBlocks` (default 12) un-advancing blocks; the lane
1525
- is advisory-on-failure and `stopGateEnabled` disables it. This fixes the observed
1526
- stall where runs went idle after a recap.
1527
- - **Mandatory SPEC.md**: `handoff-create` now writes `docs/AI_HANDOFF/SPEC.md` — a
1528
- 15-section template (FRs with Given/When/Then, fullstack scope, data model, API
1529
- contract, test matrix, acceptance criteria, migration, chosen defaults) — before task
1530
- files. Tasks carry `Spec references`; `handoff-model-guard.sh` hard-blocks fresh task
1531
- creation without a filled SPEC (`handoff.fullstack.specRequired=false` bypasses).
1532
- - **Autonomous loop contract**: only `HANDOFF FULLSTACK COMPLETE` / `HANDOFF FULLSTACK
1533
- BLOCKED` may end a run; `CHECKPOINT — WORK CONTINUING` replaces bare recaps. Phase 0
1534
- sweeps INDEX, task files, HISTORY/archive, `docs/TASKS.md` Ready-for-AI, and
1535
- uncommitted WIP. Stuck tasks recover via `cancelled_superseded` + `TASK-xxx-R<n>`
1536
- replacement tasks. `idleWatchdogMin` (default 5) scheduled wakeups keep the loop
1537
- alive off-Claude-Code; `quietScansRequired` (default 2) guards completion; Phase F
1538
- runs docs sync → `archive/cycle-NN/` → `Phase: done` → marker report.
1539
- - **Agent + command wiring**: `handoff-planner` gained legacy-sweep and SPEC-authoring
1540
- phases; `code-reviewer` reviews SPEC+PLAN against a 7-point spec quality gate;
1541
- `feature-implementer` treats `Spec references` as outranking task-file wording;
1542
- `handoff-implement`/`handoff-review` codify spec-is-the-contract and `-R<n>`
1543
- recovery. `handoff-clear` archives SPEC and must close RUN.md; `handoff-status`
1544
- reports run phase + spec presence.
1545
- - **Config**: `handoff.fullstack.*` keys (`stopGateEnabled`, `stopGateMaxStalledBlocks`,
1546
- `quietScansRequired`, `idleWatchdogMin`, `autoArchive`, `specRequired`) with `_help`
1547
- notes, in both config trees.
1548
-
1549
- ## 2.5.1 - 2026-09-18
1550
-
1551
- Post-release fixes from C20 reviewer advisories.
1552
-
1553
- - **`projectImportant` symlink fallback**: the odd-open-error fallback imported
1554
- `stat` as `lstat`, which follows symlinks — a broken symlink degraded to `missing`
1555
- and a symlink-to-file to `unreadable` instead of the correct `unsafe-type`
1556
- (spec §6.1). Now uses real `lstat`; fixed in `src/core/projectImportant.js` and both
1557
- installed-runtime mirrors (parity-locked).
1558
- - **`inspectProjectImportant` guard**: a non-string `projectRoot` threw `TypeError`
1559
- before the try block instead of degrading to `unreadable`, violating the
1560
- "no documented entry point throws" contract. Guard added (src + mirrors).
1561
- - **Uninstall backup exhaustion surfaced**: when all 101 backup-name candidates are
1562
- occupied, `PROJECT_IMPORTANT.md` was silently preserved without a backup. Now emits
1563
- a `backupWarnings` line telling the user to free a slot and rerun.
1564
- - **Test tightening**: the packed-install smoke now asserts `project-important.sh`
1565
- occupies SessionStart index 0 (spec: must run first); corrected a stale "~5%
1566
- headroom" comment on the unpacked-size ceiling.
1567
-
1568
1198
  ## 2.5.0 - 2026-09-18
1569
1199
 
1570
1200
  C20 feature release (14 handoff tasks + 3-lane review): project-owner instructions via a
@@ -1627,4 +1257,4 @@ UKit gains a fourth runtime and loses one. omp (Oh My Pi) reaches full parity wi
1627
1257
 
1628
1258
  **Known gap:** omp was not installed on the machine this release was built on. Every omp assertion in the test suite is against the generated `.omp/` tree and the bridge module's shape — the packed-tarball test confirms `templates/.omp/**` actually publishes, but nothing here observes omp's runtime behaviour. The three open verification items (does omp emit `session_start` on a post-compact continuation; omp's real base-URL key; omp's real auto-compact-window key) are recorded in `docs/AI_HANDOFF/tasks/TASK-008.md`.
1629
1259
 
1630
- Entries for 3.0.0 through 3.3.3 are archived in the repository at `docs/archive/CHANGELOG-3.0.0-3.3.3.md`. Entries for 2.1.0 through 2.2.16 (except 2.2.1) are archived in the repository at `docs/archive/CHANGELOG-2.1.0-2.2.16.md`; entries for 1.0.0 through 2.0.7 at `docs/archive/CHANGELOG-1.0.0-2.0.7.md` (neither is shipped in the npm package).
1260
+ Entries for 2.5.1 through 2.6.11 are archived in the repository at `docs/archive/CHANGELOG-2.5.1-2.6.11.md`. Entries for 3.0.0 through 3.3.3 are archived in the repository at `docs/archive/CHANGELOG-3.0.0-3.3.3.md`. Entries for 2.1.0 through 2.2.16 (except 2.2.1) are archived in the repository at `docs/archive/CHANGELOG-2.1.0-2.2.16.md`; entries for 1.0.0 through 2.0.7 at `docs/archive/CHANGELOG-1.0.0-2.0.7.md` (neither is shipped in the npm package).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ngockhoale/ukit",
3
- "version": "3.4.81",
3
+ "version": "3.4.83",
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",
@@ -60,7 +60,7 @@ function failureCommands(ledger) {
60
60
  const verifyFail = receipt.success === false && VERIFY_KINDS.has(receipt.kind);
61
61
  const ledgerFlagged = ledger.verificationFailed === true && receipt.success === false;
62
62
  if (verifyFail || ledgerFlagged) {
63
- out.push({ command: receipt.command, file: receipt.file });
63
+ out.push({ command: receipt.command, file: receipt.file, exitCode: receipt.exitCode });
64
64
  }
65
65
  }
66
66
  return out;
@@ -87,7 +87,7 @@ async function writeArtifact(filePath, result) {
87
87
  * @returns {Promise<{generatedAt: string, ledgersScanned: number,
88
88
  * ledgersWithFailures: number,
89
89
  * patterns: Array<{signature: string, count: number, sessions: number,
90
- * commands: string[], files: string[]}>}>} never throws.
90
+ * commands: string[], files: string[], exitCodes: number[]}>}>} never throws.
91
91
  */
92
92
  export async function mineFailurePatterns(projectRoot, { limitLedgers = 500, minCount = 2 } = {}) {
93
93
  const result = {
@@ -116,15 +116,17 @@ export async function mineFailurePatterns(projectRoot, { limitLedgers = 500, min
116
116
  result.ledgersWithFailures += 1;
117
117
  const sessionId = typeof ledger.sessionId === 'string' ? ledger.sessionId : null;
118
118
 
119
- for (const { command, file } of failures) {
119
+ for (const { command, file, exitCode } of failures) {
120
120
  const signature = normalizeSignature(command);
121
121
  if (!signature) continue;
122
122
  let group = groups.get(signature);
123
123
  if (!group) {
124
- group = { signature, count: 0, sessions: new Set(), commands: [], files: [] };
124
+ group = { signature, count: 0, sessions: new Set(), commands: [], files: [], exitCodes: new Set() };
125
125
  groups.set(signature, group);
126
126
  }
127
127
  group.count += 1;
128
+ // Real failure evidence: non-zero exit status the host reported (e.g. 124 = timeout(1)).
129
+ if (Number.isInteger(exitCode) && exitCode !== 0) group.exitCodes.add(exitCode);
128
130
  if (sessionId) group.sessions.add(sessionId);
129
131
  if (group.commands.length < MAX_EXAMPLES && !group.commands.includes(command)) {
130
132
  group.commands.push(command);
@@ -145,6 +147,7 @@ export async function mineFailurePatterns(projectRoot, { limitLedgers = 500, min
145
147
  sessions: g.sessions.size,
146
148
  commands: g.commands,
147
149
  files: g.files,
150
+ exitCodes: [...g.exitCodes].sort((a, b) => a - b),
148
151
  }));
149
152
  } catch {
150
153
  // Any unexpected failure → return whatever was computed so far.
@@ -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.