@ngockhoale/ukit 3.4.82 → 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,20 @@
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
+
5
19
  ## 3.4.82 - 2026-11-10
6
20
 
7
21
  Completion-gate fixes from a field-telemetry audit of the projects running UKit (Stop/gate logs, hook latency, route state, session transcripts).
@@ -1181,405 +1195,6 @@ OMP fully autonomous / unattended mode — cycle C35 (TASK-008..014).
1181
1195
  note); opencode `bash."*": "ask"` flip deferred pending deny-set
1182
1196
  expansion.
1183
1197
 
1184
- ## 2.6.11 - 2026-09-20
1185
-
1186
- Self-improvement roadmap phases 2–4 — cycle C32 (TASK-227..232).
1187
-
1188
- - Feedback capture: `src/diagnostics/feedbackEvents.js` + shared
1189
- `ledgerFiles.js` ledger helper record labeled wrong-route /
1190
- manual-correction events; new `ukit feedback` CLI.
1191
- - Telemetry emitters: `skillIds` in route-audit entries
1192
- (`route-task.mjs`); retriever lane stats appended to
1193
- `.ukit/storage/cache/retriever-lanes.jsonl` (`retriever.js`).
1194
- - Metrics surfaces: `skillAccuracy.js` + `laneStats.js` collectors;
1195
- `ukit metrics` gains `feedback`, `skills`, `retriever-lanes`, and
1196
- `learning` sections (lazy-import, degrade to `n/a`).
1197
- - Memory promotion lanes: `ukit memory learn` mines failure-patterns into
1198
- pending `ukit memory propose` candidates (`src/learning/patternProposals.js`);
1199
- `ukit memory promote` writes approved project_rule/procedure records to
1200
- MEMORY.md `## ukit-learned`; `ukit memory episode` writes a session-episode
1201
- record (`--session`/`UKIT_SESSION_ID`/latest-ledger resolution) plus
1202
- SessionEnd hook `session-episode.sh`.
1203
- - Tuning loop: `learning.*` config namespace (validated in runtimeConfig,
1204
- template parity) + `src/learning/tuning.js` advisory lane-weight/threshold
1205
- suggestions.
1206
- - Verification: per-task suites green on rerun; `.claude`↔`templates/.claude`
1207
- parity diff-clean. 6/6 tasks approved, 0 fix rounds.
1208
-
1209
- ## 2.6.10 - 2026-09-20
1210
-
1211
- Self-improvement roadmap phase 1 — cycle C31 (HK-401, SI-101..103).
1212
-
1213
- - Hook contract fix: centralized `ukit_emit_permission_decision` in
1214
- hook-input.sh (keyed on `UKIT_HOOK_CHAIN_RUNNER`); bypassPermissions probe
1215
- replaced with locked fallback deny + exit 0 — dead `ask` path closed.
1216
- - Router v2-memory lane: `listMemoryItems` reads memory records.json;
1217
- `record` branch added to buildMemorySegments.
1218
- - Outcome join: `routeOutcomes.js` joins route-audit × exec-ledger on
1219
- requestKey; new `ukit metrics` command surfaces route accuracy.
1220
- - Failure mining: `failurePatterns.js` mines exec-ledger into
1221
- failure-patterns.json (advisory, never-throws).
1222
- - Self-improvement surface audit + roadmap spec:
1223
- `docs/research/2026-09-20_self-improvement-surface-audit.md`.
1224
-
1225
- ## 2.6.9 - 2026-09-19
1226
-
1227
- Code Intelligence scale release — cycle C30 (CI-301..305, TASK-218..222).
1228
-
1229
- - Vector lane: dep-free `vectorProvider.js` (FNV-1a feature-hashed embeddings,
1230
- L2-normalized, cosine-ranked; injectable loader seam for real embeddings,
1231
- degrade to hashed/null); wired as RRF lane w=0.6 between bm25 and semantic.
1232
- - Analogy lane: `analogy.js` fingerprints memory `procedure` records + index
1233
- symbols/files; `analogy` compile mode ranks by Jaccard, hits land in
1234
- packet.memory + L2 evidence.
1235
- - Co-change mining: `cochange.js` mines `git log --name-only` (spawnSync,
1236
- bounded, core.quotePath=false) into `cochange.json`; impact sets gain a
1237
- provenance-preserving co-change lane (kind:'cochange', confidence=count/10).
1238
- - L3 summaries: `summaries.js` extractive docblock/symbol summaries for
1239
- deep_flow+analogy packets; `packetToText` renders `summary:` lines.
1240
- - Graph store: `graph.js` `codegraph.json` JsonGraphStore (imports+calls+
1241
- cochange → nodes/edges, content-gated atomic write), contract-only
1242
- scip/pdg/lsp stubs via `createGraphProvider`.
1243
- - Derived artifacts wired into `ukit index build|refresh`, stale-refresh,
1244
- install, and index scripts via `buildDerivedIndexArtifacts` (config-gated,
1245
- never fatal, outside the core build's atomic-rename contract).
1246
- - Config: `codeIntel.{embedding,analogy,cochange,summaries,graph}` +
1247
- `retriever.weights.vector` validated in runtimeConfig with template parity;
1248
- `enabled:false` honored for analogy/graph lanes.
1249
- - Verification: full suite 2720/2720 green; unpacked ceiling 6.9MB.
1250
-
1251
- ## 2.6.8 - 2026-09-19
1252
-
1253
- Code Intelligence Plane + memory v2 release — cycles C26–C29
1254
- (TASK-001..011, CI-201..206, DOC-201..206, DOC-301..305).
1255
-
1256
- - Memory v2: 4-type record model (`project_rule|derived_fact|episode|procedure`),
1257
- atomic `records.json` store, backup-first idempotent migration from v1,
1258
- `ukit memory v2` ops; legacy `.ukit/storage/memory/` layout and all
1259
- `ukit memory *` subcommands stay compatible.
1260
- - Code Intelligence Plane: `compileContext` → Context Packet v1 with
1261
- peek→expand→read levels and token budgets; Task Router v1; freshness
1262
- identity (`HEAD + overlay + config`) with incremental dirty-gated reuse
1263
- and per-branch snapshots; hybrid retriever (exact + symbol + BM25 + RRF
1264
- rerank); `impact.js` multi-hop impact sets; post-edit `invalidation.js`
1265
- dirty-set and `diagnostics.js` feeding packet `next_actions`;
1266
- `TypeScriptSemanticProvider` (optional `typescript` import — no new deps,
1267
- degrade-safe).
1268
- - CLI: `ukit code peek|search|context|impact` (`--depth`, `--diagnostics`),
1269
- `ukit index status|doctor`, `ukit doctor --docs` (doc-contract checks).
1270
- - Docs governance: `docContracts.js` validator (links/stale-version/
1271
- render-vars/commands/budgets/registry/templates/dead-docs/archive-suggestions),
1272
- `context_layers` + `docs=` route segment, host capability matrix, BUG docs
1273
- consolidated into `docs/BUG_INDEX.md`, PROMPT_CACHING canonical/vendor split,
1274
- `templates/instructions/core.md` 210→157 lines.
1275
- - Benchmarks: `scripts/bench/runGold.mjs` scorecard + `--json` export.
1276
-
1277
- ## 2.6.7 - 2026-09-19
1278
-
1279
- Canonical-instructions release — second roadmap slice (cycle C25,
1280
- DOC-101..107). Root instruction files are now generated from a single
1281
- canonical source; shipped contracts shrink ~25%; no runtime behavior
1282
- changes to install/update/uninstall flows.
1283
-
1284
- - **DOC-102 — deterministic core/overlay renderer**: new
1285
- `templates/instructions/` sources (`core.md` + host overlays +
1286
- `layout.yaml`) rendered by `src/render/instructionRenderer.js` into
1287
- `templates/CLAUDE.md`, `templates/AGENTS.md`, `templates/.omp/RULES.md`
1288
- (plus repo roots). `yarn docs:render` regenerates; `yarn docs:render:check`
1289
- fails CI on drift. Byte-stable, duplicate-heading and unreferenced-section
1290
- errors enforced.
1291
- - **DOC-101 — rule IDs + markers**: `manifests/instructionRules.yaml`
1292
- declares 48 rule IDs (kind/anchor/marker_in); `<!-- RULE: ID -->` markers
1293
- embedded in the 4 marker-bearing artifacts; `instructionRules.test.js`
1294
- validates schema, marker coverage, and anchor presence.
1295
- - **DOC-103 — parity → semantic tests**: `contextDocsParity.test.js`
1296
- rewritten to generated-artifact checks (drift, rule coverage, overlay
1297
- heading allowlists, Release Policy boundary) + mutation tests that fail
1298
- on dropped/duplicate critical rules; shared helpers in
1299
- `tests/consistency/helpers/semanticParity.js`.
1300
- - **DOC-104 — root contract shrink ≥25%**: `templates/CLAUDE.md` 288→214
1301
- lines, `templates/AGENTS.md` 305→229 (all critical rule markers + anchors
1302
- preserved). Internal-orchestration detail moved to new shipped doc
1303
- `templates/docs/UKIT_INTERNALS.md` (manifest item `docs-ukit-internals`);
1304
- baselines recorded in `docs/_baseline/root-instruction-lines.txt`.
1305
- - **DOC-105 — WORKLOG rotation + MEMORY cleanup**: live worklog ≤500 lines,
1306
- rotated entries preserved in `docs/WORKLOG_ARCHIVE.md` (regression-tested);
1307
- MEMORY.md trimmed to durable protocol/decisions/constraints (≤200).
1308
- - **DOC-106 — PROJECT_IMPORTANT_SPEC archived**: shrunk to a decision
1309
- record; full body at `docs/archive/specs/PROJECT_IMPORTANT_SPEC.md`;
1310
- `docArchiveLinks.test.js` guards link integrity.
1311
- - **DOC-107 — user-first README**: rewritten around `ukit install` +
1312
- natural-language flow (115 lines); maintainer detail moved to linked docs.
1313
-
1314
- ## 2.6.6 - 2026-09-19
1315
-
1316
- Documentation-hardening release — first slice of the
1317
- DOCUMENTATION_IMPROVEMENT_ROADMAP (cycle C24, DOC-001..006). No runtime
1318
- behavior changes: new manifest, new test lanes, doc cleanup, and a shipped
1319
- registry the remaining roadmap items build on.
1320
-
1321
- - **DOC-001 — documentation ownership/source registry**: new
1322
- `manifests/documentation.yaml` classifies every active/template/adapter
1323
- documentation surface (owner, source_of_truth, merge_strategy, budget);
1324
- `tests/consistency/docRegistry.test.js` enforces schema, coverage,
1325
- manifest-skip consistency, and `error`-level budgets.
1326
- - **DOC-002 — cross-agent benchmark corpus**: spec + fixtures at
1327
- `tests/fixtures/doc-benchmark/` (corpus index, 4 host files, 9+ task files);
1328
- `tests/benchmarks/docBenchmarkCorpus.test.js` validates structure and
1329
- registry cross-references. Host execution deferred — every host recorded
1330
- `untested` (roadmap-permitted).
1331
- - **DOC-003 — artifact reference-integrity checks**:
1332
- `tests/integration/artifactReferenceIntegrity.test.js` fails when a shipped
1333
- instruction/skill doc references an internal command/file that does not
1334
- resolve into the `npm pack` artifact (or the declared runtime-generated
1335
- allowlist); wired into `yarn test:artifact`.
1336
- - **DOC-004 — owner-file preservation lifecycle tests**:
1337
- `tests/integration/ownerPreservation.test.js` proves install/update/uninstall
1338
- preserve exact bytes and symlink posture of every registry
1339
- `merge_strategy: skip` file, including BOM/CRLF and absent-seed cases.
1340
- - **DOC-005 — STATUS.md live snapshot**: `docs/STATUS.md` shrunk to a ≤150-line
1341
- live snapshot; historical body preserved verbatim at
1342
- `docs/archive/status/STATUS-2026-09-19.md` with two-way links; registry
1343
- budget for STATUS.md flipped to `error`.
1344
- - **DOC-006 — adapter stale-version cleanup**: zero stale `vX.Y.Z` literals on
1345
- adapter doc surfaces (`templates/.codex/README.md`, `.codex/README.md`,
1346
- `templates/ukit/README.md`, `.ukit/README.md`); Codex-specific mechanics
1347
- retained; `tests/consistency/staleVersionProse.test.js` enforces.
1348
-
1349
- ## 2.6.5 - 2026-09-19
1350
-
1351
- Stability release — third full audit pass on the 2.6.4 base (cycle C23). 15
1352
- confirmed hang / freeze / silent-idle / silent-hook defects fixed with root
1353
- causes (full register: `docs/AI_HANDOFF/BUGS-2.6.5.md`). Headline: the
1354
- cycle-lockout mechanism observed live — stall-breaker streak erased on every
1355
- Stop (BUG-C23-08) — is fixed, plus every blocking/degrading hook exit now
1356
- announces on stdout per the §8 contract.
1357
-
1358
- - **Handoff stall-breaker streak erased every Stop (BUG-C23-08)**: the
1359
- stop-coordinator dedupe write dropped the `handoff` streak slot, so a wedged
1360
- RUN.md blocked forever; the merge now preserves the slot.
1361
- - **Silent non-zero hook failures (BUG-C23-01, -03, -07)**: stderr-only crash
1362
- reasons in `output-compression`/`reinject-context`/`post-edit-verify`/
1363
- `stale-spec-check` + safe-patch exit-2 blocks + skill-router/vision-router/
1364
- task-watchdog crash paths now emit a stdout `systemMessage` before exit —
1365
- stderr reaches the model, not reliably the user.
1366
- - **Lost/silent deadline emissions (BUG-C23-02, -04)**: compact-threshold's
1367
- same-tick `stdout.write` + `process.exit(0)` discarded the announce on pipes
1368
- (now `writeSync(1)`); deadline-expiry `exit 0` in four called `.mjs` modules
1369
- and `handoff-resume.sh` now announces the abandoned work.
1370
- - **Fail-open/crash-posture defects (BUG-C23-05, -06)**: context-hardcap-gate's
1371
- internal-error catch now announces its fail-open degrade on stdout;
1372
- completion-gate's stop-coordinator spawn is deadline-bounded with forced
1373
- kill routed to the crash-streak path.
1374
- - **Silent data loss + hot-path waste (BUG-C23-09, -10, -13, -15)**:
1375
- compact-threshold double capacity read collapsed to one; sweep failures
1376
- announce (bounded) instead of `.catch(() => {})` swallow; unguarded `main()`
1377
- no longer runs on `import()`; route-audit merges stage to an append-only
1378
- sidecar with a locked + exit fold instead of silently dropping entries.
1379
- - **Unbounded growth + unbounded stalls (BUG-C23-11, -12, -14)**: memory
1380
- project archives capped; `permission-audit.log` rotates inside the prune
1381
- pass; `bin/ukit` runCli got an overall deadline watchdog.
1382
-
1383
- Regression gate: 138 files / 2360 tests green, liveness 120/120, §8 sweep
1384
- clean, template↔installed parity byte-identical, async-caller census clean,
1385
- all 25 C22 verdicts re-confirmed.
1386
-
1387
- ## 2.6.4 - 2026-09-19
1388
-
1389
- Stability release — second full audit pass on the 2.6.3 base (cycle C22). 25
1390
- confirmed hang / freeze / silent-idle / silent-hook defects fixed with root causes
1391
- (full register: `docs/AI_HANDOFF/BUGS-2.6.4.md`), including the two carried C21
1392
- residual lineages: **R1** (sync fs inside the hardcap-gate deadline → BUG-C22-01)
1393
- and **R2** (sync fs inside handoff-resume deadline → BUG-C22-02).
1394
-
1395
- - **Stalled-mount freeze in the compact/hardcap chain (R1, BUG-C22-01)**: the entire
1396
- compact-threshold fs path (`readNegotiatedCapacity`, `buildCompactThresholds`,
1397
- `resolveCompactPhase`, `buildCompactPressureState`, pressure registration, compact
1398
- plan) converted to async `fsp`; every caller in hooks, `src/core/compact`, and
1399
- `src/core/status.js` now awaits; `isDirectRun` in `execution-ledger.mjs` /
1400
- `stop-coordinator.mjs` guards `realpathSync` behind a basename check so module
1401
- import no longer does sync fs on the deadline path.
1402
- - **handoff-resume sync fs inside its deadline (R2, BUG-C22-02)** plus the same
1403
- sync-fs-under-deadline class in `reset-compact-pressure` (BUG-C22-03),
1404
- `auto-prune-bash` (BUG-C22-04) and `auto-allow-bash` (BUG-C22-06) — sync calls
1405
- inside armed unref'd hook deadlines parked the event loop so the deadline itself
1406
- could never fire.
1407
- - **Stop-gate crash → block-forever (BUG-C22-05)**: a `completion-gate` coordinator
1408
- crash used to produce an unconditional `decision:block` on every subsequent stop.
1409
- New crash-streak breaker (`.ukit/storage/cache/completion-gate-crash.streak`,
1410
- byte-append counter, cap `handoff.fullstack.stopGateMaxCrashStreaks` default 3)
1411
- fails closed up to the cap then releases *loud*; omp bridge got the identical
1412
- try/catch + streak parity.
1413
- - **Silent `exit 0` / `exit(0)` clusters now announce (§8 contract)**: missing-script
1414
- silent exits in 4 hooks (BUG-C22-07), deadline-expiry silent exits on 3 gated
1415
- hooks plus the hardcap-gate sites (BUG-C22-08), and `verification-guard`
1416
- stderr-only catch-all (BUG-C22-09) all emit the fail-open §8 JSON + stderr
1417
- announcement instead of going quiet.
1418
- - **Unbounded spawned children get self-deadlines**: `compact-threshold.mjs`
1419
- `runCli` (BUG-C22-15, `UKIT_COMPACT_CLI_DEADLINE_MS` default 4s — bounds the
1420
- skill-router spawn too), `verify-release.mjs` spawn watchdog + tree-kill
1421
- (BUG-C22-20), `parallel-agents.mjs` per-level `UKIT_BENCH_LEVEL_TIMEOUT_MS`
1422
- 30 min deadline with detached process-group SIGKILL (BUG-C22-21).
1423
- - **`withFileLock` busy-spin on persistent stat errors (BUG-C22-16 runtime twin /
1424
- BUG-C22-17 core twin)**: a stat error inside the retry loop skipped both the
1425
- `maxWaitMs` check and the backoff sleep → tight spin for the process lifetime.
1426
- The budget check now lives inside the catch path in both copies.
1427
- - **Sweep caps that could never fire (BUG-C22-10/11/12/13)**: tee sweep,
1428
- hook-telemetry sweep, exec-ledger sweep and omp hook-errors sweep computed the
1429
- overflow from the scanned *sample* instead of the eligible count, so configured
1430
- max-file caps (e.g. `TEE_MAX_FILES=500`) were unreachable.
1431
- - **Vision receipts eaten / orphaned (BUG-C22-14/18)**: the vision marker-dir sweep
1432
- deleted `analyzed-*` receipts early → vision gate re-fired on every image; legacy
1433
- top-level `vision/analyzed-*.json` orphans had no pruner at all. Both prunes are
1434
- now TTL-coordinated with `isAlreadyAnalyzed`.
1435
- - **Unbounded `.bak` backup writer (BUG-C22-19)**: `.claude/ukit/.ukit/backups/`
1436
- had no pruner; `pruneOldBackups` is now bounded.
1437
- - **Registered timeout < internal worst case (BUG-C22-22/23/24/25)**:
1438
- `auto-allow-bash` 12→15s (internal worst 13s), `skill-router` 8→20s (worst
1439
- ~18s), `stale-spec-guard` 8→11s, and omp chain child budget 4000→12000ms with
1440
- ceiling 16000→52000ms — a hook can no longer be killed mid-work by a budget
1441
- smaller than its own declared worst case.
1442
-
1443
- Full fixed-bug enumeration (register `docs/AI_HANDOFF/BUGS-2.6.4.md`, all rows
1444
- `verified`):
1445
-
1446
- - BUG-C22-01 (R1) — sync fs inside hardcap-gate deadline (compact-threshold + execution-ledger)
1447
- - BUG-C22-02 (R2) — sync fs inside handoff-resume deadline
1448
- - BUG-C22-03 — reset-compact-pressure: swallow-all + sync fs inside deadline
1449
- - BUG-C22-04 — auto-prune-bash: invisible prune failure + sync fs inside deadline
1450
- - BUG-C22-05 — completion-gate: persistent coordinator crash → block-forever (crash-streak breaker)
1451
- - BUG-C22-06 — auto-allow-bash: sync fs inside deadline
1452
- - BUG-C22-07 — missing-script silent `exit 0` cluster (4 hooks)
1453
- - BUG-C22-08 — deadline-expiry silent `exit(0)` on gated hooks (+ hardcap sites)
1454
- - BUG-C22-09 — verification-guard catch-all degrade on stderr only
1455
- - BUG-C22-10 — tee sweep count cap unreachable (`TEE_MAX_FILES=500` never enforced)
1456
- - BUG-C22-11 — hook-telemetry sweep count cap unreachable
1457
- - BUG-C22-12 — exec-ledger sweep count cap unreachable
1458
- - BUG-C22-13 — omp hook-errors sweep count cap unreachable
1459
- - BUG-C22-14 — vision marker-dir sweep deletes `analyzed-*` receipts → vision gate re-fires
1460
- - BUG-C22-15 — skill-router spawns `node compact-threshold.mjs prompt` unbounded (CLI self-deadline)
1461
- - BUG-C22-16 — `withFileLock` busy-spin, runtime twin (token-utils.mjs)
1462
- - BUG-C22-17 — `withFileLock` busy-spin, core twin (fileOps.js)
1463
- - BUG-C22-18 — legacy top-level `vision/analyzed-*.json` orphans never pruned
1464
- - BUG-C22-19 — `.claude/ukit/.ukit/backups/` `.bak` writer had no pruner
1465
- - BUG-C22-20 — `verify-release.mjs` spawns with no timeout (watchdog + tree-kill)
1466
- - BUG-C22-21 — `parallel-agents.mjs` N children, no timeout, partial-settle hang
1467
- - BUG-C22-22 — auto-allow-bash registered timeout < internal worst case (12→15s)
1468
- - BUG-C22-23 — skill-router registered timeout < internal worst case (8→20s)
1469
- - BUG-C22-24 — stale-spec-guard registered timeout zero margin (8→11s)
1470
- - BUG-C22-25 — omp chain child budget < every staged hook's worst case (4000→12000ms, ceiling 16000→52000ms)
1471
-
1472
- ## 2.6.3 - 2026-09-18
1473
-
1474
- - **Informational side-questions no longer self-block at the Stop gate.** A no-route
1475
- question ("còn task nào dang dở không", "is anything left?") carries the previous
1476
- prompt's `routeSummary` + completion contract forward by design — but the prompt
1477
- re-key also empties the effective ledger, so the gate unconditionally demanded
1478
- write+verification evidence that a text answer can never produce. `evaluateCompletion`
1479
- now releases silently when the turn is informational (routed `executionMode` or the
1480
- no-route branch's `routingContext.executionMode` marker). The carried contract stays
1481
- on disk, so real work after the question is still gated. One fix covers Claude Code
1482
- and omp (shared `execution-ledger.mjs`). 3 regression tests.
1483
-
1484
- ## 2.6.2 - 2026-09-18
1485
-
1486
- Stability release — 17 confirmed hang / silent-idle / silent-hook defects fixed with
1487
- root causes (full register: `docs/AI_HANDOFF/BUGS-2.6.2.md`), focused on the "system
1488
- goes quiet and does nothing" failure class.
1489
-
1490
- - **No more silent degraded input (§8 contract, BUG-C21-01/02/03)**: every hook that
1491
- stages stdin now *announces* when staging fails, stalls, or refuses — fail-closed
1492
- hooks (`block-dangerous`, `protect-files`, `context-hardcap-gate`,
1493
- `sensitive-data-guard`) emit an `ask`/`systemMessage` JSON + stderr `BLOCKED` +
1494
- `exit 2`; advisory hooks emit a `systemMessage` + `exit 0`. The old bounded-cut
1495
- silently truncated and proceeded. `sensitive-data-guard` now also fails closed
1496
- (exit 2) on any non-refusal staging failure and mirrors its deadline block to
1497
- stderr so the reason survives `process.exit` truncation.
1498
- - **Sync-fs defeats inside self-deadlines removed (BUG-C21-04)**: the
1499
- deadline-guarded node blocks in `context-window-guard.sh` and
1500
- `context-hardcap-gate.sh` no longer call synchronous `fs.*Sync` inside the kill
1501
- window — a stalled `.ukit` mount can no longer freeze the gate so the unref'd
1502
- deadline can never fire. (Residual call-frame past the grant boundary recorded
1503
- as BUG-C21-R1/R2 for the next cycle.)
1504
- - **Host timeouts now cover internal budgets (BUG-C21-05)**: every hook registered
1505
- in `settings.json` gets `timeout ≥ stage bound + node deadline + margin`; the
1506
- regression test iterates *all* registered hooks instead of a hand-picked list,
1507
- and four under-budgeted hooks (`auto-allow-bash`, `vision-router`,
1508
- `auto-prune-bash`, `reset-compact-pressure`) were raised to 12s.
1509
- - **Missing `await` in skill-router (review major)**: an un-awaited async context
1510
- snapshot could leave the router writing a stale/partial decision silently.
1511
- - **CLI hangs eliminated (BUG-C21-12/13)**: `ukit update`/`install` `spawnSync`
1512
- calls now carry timeouts with `killSignal: 'SIGKILL'` (SIGTERM alone keeps
1513
- waiting on signal-resistant children); a wedged `npm root -g` now reports
1514
- `global-root-query-timeout` instead of hanging forever. `promptYesNo` resolves
1515
- on stdin EOF / `ERR_USE_AFTER_CLOSE` instead of hanging or crashing.
1516
- - **Unbounded growth bounded (BUG-C21-07/09/10/11)**: `tee/` cache, hook-errors
1517
- jsonl, hook-latency and exec-ledger session files now have count caps; the
1518
- ledger protects receipt files (`.journal`, `.quarantine`, gate crash counter)
1519
- from count-cap eviction, and the overflow basis uses `entries.length`
1520
- (post-filter) everywhere.
1521
- - **Handoff machinery (BUG-C21-15)**: all four `RUN.md` `Phase:` consumers treat
1522
- `done`/`blocked` as terminal — dead runs no longer nag forever.
1523
- - **Wiring/parity (BUG-C21-06/08/14/16/17)**: stale-spec-guard deadline exits
1524
- distinguish "stall" from "match"; `provision-worktree` spawnSync calls carry
1525
- timeouts; `task-budget-validator.mjs` is manifest-covered so the documented
1526
- command works on fresh installs; `verification-guard.sh` is actually registered
1527
- on PreToolUse Bash; shipped `config.json` regained `codex-context-budget` and a
1528
- parity test now guards every array field under `subagents`.
1529
-
1530
-
1531
- ## 2.6.0 - 2026-09-18
1532
-
1533
- handoff-fullstack v2 — autonomous create→implement→review loop that runs to 100%
1534
- completion of all unfinished work, with a mandatory detailed SPEC gate.
1535
-
1536
- - **Never-stall Stop gate**: `stop-coordinator.mjs` gained a `handoff-cursor` lane that
1537
- reads `docs/AI_HANDOFF/RUN.md` and blocks stop while `Phase:` is not `done`/`blocked`,
1538
- carrying the cursor's `Next:` step. Liveness breaker releases after
1539
- `handoff.fullstack.stopGateMaxStalledBlocks` (default 12) un-advancing blocks; the lane
1540
- is advisory-on-failure and `stopGateEnabled` disables it. This fixes the observed
1541
- stall where runs went idle after a recap.
1542
- - **Mandatory SPEC.md**: `handoff-create` now writes `docs/AI_HANDOFF/SPEC.md` — a
1543
- 15-section template (FRs with Given/When/Then, fullstack scope, data model, API
1544
- contract, test matrix, acceptance criteria, migration, chosen defaults) — before task
1545
- files. Tasks carry `Spec references`; `handoff-model-guard.sh` hard-blocks fresh task
1546
- creation without a filled SPEC (`handoff.fullstack.specRequired=false` bypasses).
1547
- - **Autonomous loop contract**: only `HANDOFF FULLSTACK COMPLETE` / `HANDOFF FULLSTACK
1548
- BLOCKED` may end a run; `CHECKPOINT — WORK CONTINUING` replaces bare recaps. Phase 0
1549
- sweeps INDEX, task files, HISTORY/archive, `docs/TASKS.md` Ready-for-AI, and
1550
- uncommitted WIP. Stuck tasks recover via `cancelled_superseded` + `TASK-xxx-R<n>`
1551
- replacement tasks. `idleWatchdogMin` (default 5) scheduled wakeups keep the loop
1552
- alive off-Claude-Code; `quietScansRequired` (default 2) guards completion; Phase F
1553
- runs docs sync → `archive/cycle-NN/` → `Phase: done` → marker report.
1554
- - **Agent + command wiring**: `handoff-planner` gained legacy-sweep and SPEC-authoring
1555
- phases; `code-reviewer` reviews SPEC+PLAN against a 7-point spec quality gate;
1556
- `feature-implementer` treats `Spec references` as outranking task-file wording;
1557
- `handoff-implement`/`handoff-review` codify spec-is-the-contract and `-R<n>`
1558
- recovery. `handoff-clear` archives SPEC and must close RUN.md; `handoff-status`
1559
- reports run phase + spec presence.
1560
- - **Config**: `handoff.fullstack.*` keys (`stopGateEnabled`, `stopGateMaxStalledBlocks`,
1561
- `quietScansRequired`, `idleWatchdogMin`, `autoArchive`, `specRequired`) with `_help`
1562
- notes, in both config trees.
1563
-
1564
- ## 2.5.1 - 2026-09-18
1565
-
1566
- Post-release fixes from C20 reviewer advisories.
1567
-
1568
- - **`projectImportant` symlink fallback**: the odd-open-error fallback imported
1569
- `stat` as `lstat`, which follows symlinks — a broken symlink degraded to `missing`
1570
- and a symlink-to-file to `unreadable` instead of the correct `unsafe-type`
1571
- (spec §6.1). Now uses real `lstat`; fixed in `src/core/projectImportant.js` and both
1572
- installed-runtime mirrors (parity-locked).
1573
- - **`inspectProjectImportant` guard**: a non-string `projectRoot` threw `TypeError`
1574
- before the try block instead of degrading to `unreadable`, violating the
1575
- "no documented entry point throws" contract. Guard added (src + mirrors).
1576
- - **Uninstall backup exhaustion surfaced**: when all 101 backup-name candidates are
1577
- occupied, `PROJECT_IMPORTANT.md` was silently preserved without a backup. Now emits
1578
- a `backupWarnings` line telling the user to free a slot and rerun.
1579
- - **Test tightening**: the packed-install smoke now asserts `project-important.sh`
1580
- occupies SessionStart index 0 (spec: must run first); corrected a stale "~5%
1581
- headroom" comment on the unpacked-size ceiling.
1582
-
1583
1198
  ## 2.5.0 - 2026-09-18
1584
1199
 
1585
1200
  C20 feature release (14 handoff tasks + 3-lane review): project-owner instructions via a
@@ -1642,4 +1257,4 @@ UKit gains a fourth runtime and loses one. omp (Oh My Pi) reaches full parity wi
1642
1257
 
1643
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`.
1644
1259
 
1645
- 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.82",
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.
@@ -33,27 +33,36 @@ const DENIED_TARGET_RES = [
33
33
  /secret|credential|token/i,
34
34
  ];
35
35
 
36
- // Whitelist — bounded deterministic mapping only.
36
+ // Whitelist — bounded deterministic mapping only. Classification needs evidence,
37
+ // not a word that happens to occur in a command's text: the ledger records no
38
+ // timed-out/killed/signal marker, only `exitCode` (mined onto pattern.exitCodes),
39
+ // so timeout-hang keys on exit 124 (GNU timeout(1)). Text markers are a fallback:
40
+ // whole words only, matched against the command's invocation lines — never
41
+ // heredoc bodies, comments, env-var names or file names.
42
+ const TIMEOUT_EXIT_CODES = new Set([124]);
43
+
37
44
  const FIX_CLASSES = [
38
45
  {
39
46
  id: 'timeout-hang',
40
- matches: (hay) => /timeout|timed?\s*out|hang|hung/.test(hay),
47
+ matches: (text, pattern) => (Array.isArray(pattern.exitCodes)
48
+ && pattern.exitCodes.some((code) => TIMEOUT_EXIT_CODES.has(code)))
49
+ || /\b(?:timed out|timeout (?:exceeded|expired)|hangs|hanging|hung)\b/.test(text.commands),
41
50
  change: 'Increase the timeout, add an explicit deadline, and retry once before giving up.',
42
51
  },
43
52
  {
44
53
  id: 'missing-fallback',
45
- matches: (hay) => /missing-fallback/.test(hay)
46
- || (/fallback/.test(hay) && /decision|decisionruntime/.test(hay)),
54
+ matches: (text) => /\bmissing-fallback\b/.test(text.all)
55
+ || (/\bfallback\b/.test(text.all) && /\b(?:decision|decisionruntime)\b/.test(text.all)),
47
56
  change: 'Add a `fallbackCode` path plus a deterministic default so the caller never blocks on the decision call.',
48
57
  },
49
58
  {
50
59
  id: 'empty-output',
51
- matches: (hay) => /empty[-_ ]?output|no output|empty stdout/.test(hay),
60
+ matches: (text) => /\bempty[-_ ]?output\b|\bno output\b|\bempty stdout\b/.test(text.all),
52
61
  change: 'Keep the chain alive on empty output (`|| true` or equivalent) and log stderr for diagnosis.',
53
62
  },
54
63
  {
55
64
  id: 'stale-doc',
56
- matches: (hay) => /stale[-_ ]?doc|doc drift|docs?\s+drift|out[- ]?of[- ]?date\s+doc/.test(hay),
65
+ matches: (text) => /\bstale[-_ ]?doc\b|\bdoc drift\b|\bdocs?\s+drift\b|\bout[- ]?of[- ]?date\s+doc\b/.test(text.all),
57
66
  change: 'Re-render or refresh the flagged documentation file to match current source.',
58
67
  },
59
68
  ];
@@ -62,21 +71,33 @@ function isObject(value) {
62
71
  return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
63
72
  }
64
73
 
65
- // Evidence haystack: signature + commands + files, lowercased.
66
- function haystack(pattern) {
67
- return [
68
- pattern.signature,
69
- ...(Array.isArray(pattern.commands) ? pattern.commands : []),
70
- ...(Array.isArray(pattern.files) ? pattern.files : []),
71
- ].join(' ').toLowerCase();
74
+ // Invocation text of a shell command: drop comment lines and everything from the
75
+ // line that opens a heredoc (body = prose/data, not the command).
76
+ function invocationText(command) {
77
+ const kept = [];
78
+ for (const line of String(command).split('\n')) {
79
+ if (/^\s*#/.test(line)) continue;
80
+ kept.push(line);
81
+ if (/<<-?\s*['"]?\w+/.test(line)) break;
82
+ }
83
+ return kept.join(' ');
84
+ }
85
+
86
+ // Evidence text, lowercased: `commands` = invocation text only; `all` adds signature + files.
87
+ function evidenceText(pattern) {
88
+ const commands = (Array.isArray(pattern.commands) ? pattern.commands : [])
89
+ .filter((c) => typeof c === 'string').map(invocationText).join(' ').toLowerCase();
90
+ const all = [pattern.signature, commands, ...(Array.isArray(pattern.files) ? pattern.files : [])]
91
+ .join(' ').toLowerCase();
92
+ return { commands, all };
72
93
  }
73
94
 
74
95
  /** Map a mined pattern to a whitelisted fix class; null = none. */
75
96
  export function mapPatternToFixTarget(pattern) {
76
97
  if (!isObject(pattern)) return null;
77
- const hay = haystack(pattern);
98
+ const text = evidenceText(pattern);
78
99
  for (const fixClass of FIX_CLASSES) {
79
- if (fixClass.matches(hay)) return { id: fixClass.id, change: fixClass.change };
100
+ if (fixClass.matches(text, pattern)) return { id: fixClass.id, change: fixClass.change };
80
101
  }
81
102
  return null;
82
103
  }
@@ -81,26 +81,171 @@ if [ -z "$COMMAND" ]; then
81
81
  exit 0
82
82
  fi
83
83
 
84
- # set -f: unquoted $COMMAND word-splits AND glob-expands — a bare `*` or `*.sh`
85
- # command would otherwise resolve to cwd filenames and persist an allow rule
86
- # for a file that was never the invoked binary.
87
- set -f
84
+ # Binary resolution: a small shell-word scanner (NOT `for token in $COMMAND`).
85
+ # Leading env assignments (`NAME=value`) are skipped as WHOLE shell words — the
86
+ # value may be '...'/"..." quoted or a $(...)/`...` substitution containing
87
+ # spaces, which plain whitespace splitting cut in half and minted junk such as
88
+ # Bash(HEAD:*) or Bash(-td:*). If the first command word cannot be determined
89
+ # confidently (unbalanced quote/substitution, leading operator, redirection,
90
+ # subshell) BIN stays empty: nothing is minted and the normal permission prompt
91
+ # applies, which is always safe. Pure bash, 3.2 compatible (no globbing involved,
92
+ # so no `set -f` is needed either).
93
+ __ukit_scan_sq() { # I is after the opening '
94
+ local rest="${COMMAND:I}"
95
+ case "$rest" in
96
+ *"'"*) rest="${rest%%\'*}"; I=$((I + ${#rest} + 1)); return 0 ;;
97
+ esac
98
+ return 1
99
+ }
100
+ __ukit_scan_bt() { # I is after the opening backtick
101
+ local c
102
+ while [ "$I" -lt "$N" ]; do
103
+ c="${COMMAND:I:1}"
104
+ case "$c" in
105
+ '\') I=$((I + 2)) ;;
106
+ '`') I=$((I + 1)); return 0 ;;
107
+ *) I=$((I + 1)) ;;
108
+ esac
109
+ done
110
+ return 1
111
+ }
112
+ # I is AT a `$`. Only three forms are understood: `$(...)`, a plain `$NAME`-style
113
+ # expansion, and a simple `${NAME}`. Everything else whose end this scanner
114
+ # cannot prove — `${x:- a b }` (spaces/quotes/braces inside), `$[ ... ]`, and
115
+ # outside double quotes ANSI-C/locale quoting ($'..\'..' / $"..") — returns 1,
116
+ # so nothing is minted. $1 = "dq" when scanning inside double quotes, where
117
+ # `$'` and `$"` are a literal dollar.
118
+ # Name classes are spelled out: a locale-collated `[A-Za-z]` range also matches
119
+ # letters such as `É`, which bash itself never accepts in a variable name.
120
+ __ukit_n1='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_'
121
+ __ukit_simple_brace_re="^[\$][{][${__ukit_n1}][${__ukit_n1}0123456789]*[}]"
122
+ __ukit_assign_re="^[${__ukit_n1}][${__ukit_n1}0123456789]*[+]?="
123
+ __ukit_scan_dollar() {
124
+ case "${COMMAND:I+1:1}" in
125
+ '(') I=$((I + 2)); __ukit_scan_paren || return 1 ;;
126
+ '{')
127
+ if [[ "${COMMAND:I}" =~ $__ukit_simple_brace_re ]]; then
128
+ I=$((I + ${#BASH_REMATCH[0]}))
129
+ else
130
+ return 1
131
+ fi
132
+ ;;
133
+ '[') return 1 ;;
134
+ "'"|'"')
135
+ [ "${1:-}" = "dq" ] || return 1
136
+ I=$((I + 1))
137
+ ;;
138
+ *) I=$((I + 1)) ;;
139
+ esac
140
+ return 0
141
+ }
142
+ __ukit_scan_dq() { # I is after the opening "
143
+ local c
144
+ while [ "$I" -lt "$N" ]; do
145
+ c="${COMMAND:I:1}"
146
+ case "$c" in
147
+ '\') I=$((I + 2)) ;;
148
+ '"') I=$((I + 1)); return 0 ;;
149
+ '`') I=$((I + 1)); __ukit_scan_bt || return 1 ;;
150
+ '$') __ukit_scan_dollar dq || return 1 ;;
151
+ *) I=$((I + 1)) ;;
152
+ esac
153
+ done
154
+ return 1
155
+ }
156
+ __ukit_scan_paren() { # I is after an opening ( — consume through its matching )
157
+ # Not a full parser: constructs whose `)`/quote does not delimit what this
158
+ # scanner assumes — anything __ukit_scan_dollar rejects, a `#` (comment), a
159
+ # heredoc (`<<`), and `case` patterns (`a)`) — make it give up (return 1 →
160
+ # nothing is minted) rather than guess where the substitution ends.
161
+ local c start=$I
162
+ while [ "$I" -lt "$N" ]; do
163
+ c="${COMMAND:I:1}"
164
+ case "$c" in
165
+ ')')
166
+ I=$((I + 1))
167
+ case "${COMMAND:start:I-start}" in
168
+ *case*) return 1 ;;
169
+ esac
170
+ return 0
171
+ ;;
172
+ '#') return 1 ;;
173
+ '<') [ "${COMMAND:I+1:1}" = "<" ] && return 1; I=$((I + 1)) ;;
174
+ '$') __ukit_scan_dollar || return 1 ;;
175
+ '(') I=$((I + 1)); __ukit_scan_paren || return 1 ;;
176
+ "'") I=$((I + 1)); __ukit_scan_sq || return 1 ;;
177
+ '"') I=$((I + 1)); __ukit_scan_dq || return 1 ;;
178
+ '`') I=$((I + 1)); __ukit_scan_bt || return 1 ;;
179
+ '\') I=$((I + 2)) ;;
180
+ *) I=$((I + 1)) ;;
181
+ esac
182
+ done
183
+ return 1
184
+ }
185
+
186
+ # Bounded scan: the per-character substring scan is quadratic in the command
187
+ # length (a 100 KB assignment value stalled the hook for 45s+). Only the first
188
+ # 4096 characters are scanned; if the first command word is not fully resolved
189
+ # inside that window, nothing is minted.
88
190
  BIN=""
89
- for token in $COMMAND; do
90
- case "$token" in
91
- *=*) continue ;;
191
+ __ukit_cut=0
192
+ if [ "${#COMMAND}" -gt 4096 ]; then
193
+ COMMAND="${COMMAND:0:4096}"
194
+ __ukit_cut=1
195
+ fi
196
+ N=${#COMMAND}
197
+ I=0
198
+ while :; do
199
+ while [ "$I" -lt "$N" ]; do
200
+ case "${COMMAND:I:1}" in
201
+ ' '|' ') I=$((I + 1)) ;;
202
+ *) break ;;
203
+ esac
204
+ done
205
+ [ "$I" -ge "$N" ] && break
206
+ case "${COMMAND:I:1}" in
207
+ ';'|'|'|'&'|'('|')'|'<'|'>'|'
208
+ ') break ;;
209
+ esac
210
+ __ukit_ws=$I
211
+ __ukit_ok=1
212
+ while [ "$I" -lt "$N" ]; do
213
+ __ukit_c="${COMMAND:I:1}"
214
+ case "$__ukit_c" in
215
+ ' '|' '|';'|'|'|'&'|'('|')'|'<'|'>'|'
216
+ ') break ;;
217
+ '\') I=$((I + 2)) ;;
218
+ "'") I=$((I + 1)); __ukit_scan_sq || { __ukit_ok=0; break; } ;;
219
+ '"') I=$((I + 1)); __ukit_scan_dq || { __ukit_ok=0; break; } ;;
220
+ '`') I=$((I + 1)); __ukit_scan_bt || { __ukit_ok=0; break; } ;;
221
+ '$') __ukit_scan_dollar || { __ukit_ok=0; break; } ;;
222
+ *) I=$((I + 1)) ;;
223
+ esac
224
+ done
225
+ [ "$__ukit_ok" -eq 1 ] || break
226
+ # The word ran into the scan window's edge: it may continue past it.
227
+ if [ "$__ukit_cut" -eq 1 ] && [ "$I" -ge "$N" ]; then break; fi
228
+ __ukit_word="${COMMAND:__ukit_ws:I-__ukit_ws}"
229
+ if [[ "$__ukit_word" =~ $__ukit_assign_re ]]; then
230
+ continue
231
+ fi
232
+ case "$__ukit_word" in
92
233
  time|command|env) continue ;;
93
- '|'|'||'|'&&'|';') break ;;
94
234
  esac
95
- BIN="$token"
235
+ BIN="$__ukit_word"
96
236
  break
97
237
  done
98
- set +f
99
238
 
100
239
  if [ -z "$BIN" ]; then
101
240
  exit 0
102
241
  fi
103
242
 
243
+ # A leading dash is an option of a skipped wrapper (`command -v`, `env -i`,
244
+ # `time -p`) or leftover junk, never a binary — never mint it.
245
+ case "$BIN" in
246
+ -*) exit 0 ;;
247
+ esac
248
+
104
249
  if [[ ! "$BIN" =~ ^[a-zA-Z0-9._/-]+$ ]]; then
105
250
  exit 0
106
251
  fi
@@ -48,7 +48,19 @@ source "$SCRIPT_DIR/../ukit/runtime/hook-telemetry.sh" 2>/dev/null || true
48
48
  ukit_emit_input_degraded advisory "task-watchdog"
49
49
  fi
50
50
  # BUG-C21-01: a truncated/stalled staged payload must be announced (SPEC §8), never silently passed.
51
- ukit_input_degraded && ukit_emit_input_degraded advisory "task-watchdog"
51
+ # Exception: a payload cut ONLY by the 64 KiB size cap (not a stall) for PostToolUse. That path reads
52
+ # nothing but hook_event_name from the payload (tasks/state/config all come from disk), so a size-truncated
53
+ # payload is not incomplete for this hook. The event name is recovered only when provably complete
54
+ # (ukit_salvage_tool_field); anything else - stall, unrecoverable name, non-PostToolUse (Stop forwards the
55
+ # raw payload to the coordinator) - keeps the announced degrade.
56
+ UKIT_WD_SALVAGED_EVENT=""
57
+ if ukit_input_degraded; then
58
+ if [ "${UKIT_HOOK_INPUT_STALLED:-0}" != "1" ] && [ -n "${UKIT_INPUT_FILE:-}" ]; then
59
+ __ukit_wd_event="$(ukit_salvage_tool_field "$UKIT_INPUT_FILE" hook_event_name 2>/dev/null)" || __ukit_wd_event=""
60
+ [ "$__ukit_wd_event" = "PostToolUse" ] && UKIT_WD_SALVAGED_EVENT="PostToolUse"
61
+ fi
62
+ [ -n "$UKIT_WD_SALVAGED_EVENT" ] || ukit_emit_input_degraded advisory "task-watchdog"
63
+ fi
52
64
  else
53
65
  # 64 KiB cap and the advisory degrade path alive.
54
66
  # Runtime helper missing (pre-install tree): the SAME bounded staging,
@@ -89,7 +101,7 @@ else
89
101
  fi
90
102
  PROJECT_ROOT="${CLAUDE_PROJECT_DIR:-$PWD}"
91
103
 
92
- INPUT_FILE="$UKIT_INPUT_FILE" PROJECT_ROOT="$PROJECT_ROOT" node <<'NODE' || true
104
+ INPUT_FILE="$UKIT_INPUT_FILE" PROJECT_ROOT="$PROJECT_ROOT" SALVAGED_EVENT="${UKIT_WD_SALVAGED_EVENT:-}" node <<'NODE' || true
93
105
  'use strict';
94
106
 
95
107
  const fsp = require('fs/promises');
@@ -124,7 +136,11 @@ setTimeout(() => process.exit(0), HOOK_DEADLINE_MS).unref();
124
136
  }
125
137
  })();
126
138
 
127
- const hookEvent = typeof payload.hook_event_name === 'string' ? payload.hook_event_name : '';
139
+ // A size-truncated payload fails JSON.parse; the wrapper then passes the provably-complete
140
+ // PostToolUse event name it salvaged (the only payload field this path uses).
141
+ const hookEvent = typeof payload.hook_event_name === 'string'
142
+ ? payload.hook_event_name
143
+ : (process.env.SALVAGED_EVENT === 'PostToolUse' ? 'PostToolUse' : '');
128
144
  const projectRoot = process.env.PROJECT_ROOT || process.cwd();
129
145
 
130
146
  // Silent degrade for non-relevant events — same posture as every other
@@ -98,7 +98,9 @@ function classifyAllowRules({ allow, managedRules, auditRules, denyTokens }) {
98
98
  }
99
99
  const token = parsed[1];
100
100
  const base = token.includes('/') ? token.slice(token.lastIndexOf('/') + 1) : token;
101
- if (!denyTokens.has(base)) {
101
+ // A token starting with `-` is an option fragment, never a binary (leftover of the
102
+ // old whitespace tokenizer); it is junk by shape. Provenance gates below still apply.
103
+ if (!token.startsWith('-') && !denyTokens.has(base)) {
102
104
  skips.push({ rule, reason: 'not a UKit auto-allow denylist token — left in place' });
103
105
  continue;
104
106
  }
@@ -309,9 +309,23 @@ export function noteSweepFailure(error) {
309
309
  return message;
310
310
  }
311
311
 
312
+ // Opt-in guard (inert when UKIT_TELEMETRY_DENY_ROOT is unset): rows whose project
313
+ // root resolves to the denied directory are dropped. The UKit dev repo's vitest
314
+ // config sets it to the repo root so test runs never write into the live runtime
315
+ // storage, while tests using their own temp project roots still write normally.
316
+ function isDeniedRoot(projectRoot) {
317
+ const deny = process.env.UKIT_TELEMETRY_DENY_ROOT;
318
+ if (!deny) return false;
319
+ const canon = (p) => {
320
+ try { return fs.realpathSync(path.resolve(String(p))); } catch { return path.resolve(String(p)); }
321
+ };
322
+ return canon(projectRoot) === canon(deny);
323
+ }
324
+
312
325
  export function appendTelemetryRow(projectRoot, sessionId, row, options = {}) {
313
326
  try {
314
327
  if (!row || typeof row !== 'object') return false;
328
+ if (isDeniedRoot(projectRoot)) return false;
315
329
  const dir = telemetryDirFor(projectRoot);
316
330
  fs.mkdirSync(dir, { recursive: true });
317
331
  const filePath = path.join(dir, `${safeName(sessionId)}.jsonl`);