@ngockhoale/ukit 3.5.1 → 3.5.2

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,24 @@
2
2
 
3
3
  All notable changes to UKit are documented here.
4
4
 
5
+ ## 3.5.2 - 2026-11-15
6
+
7
+ Edit hints. After the agent edits a file, UKit now tells it what else usually has to change with that file, instead of leaving the agent to find the mirror copy or the test on its own.
8
+
9
+ - **A hint after each successful Edit or Write, once per file per task.** It lists the file's mirror copies, the tests most likely to cover it, and project notes (from `docs/MEMORY.md` and memory records) that name that file, its mirror, its tests or its directory. Mirrors are byte-identical twins found at index time, the pairs UKit already declares, and any pair you add under `memory.editHints.mirrors` in `.ukit/storage/config.json`. A pair that was a mirror and has since drifted is still listed, labelled as drifted. List a pair under `memory.editHints.ignoreMirrors` to silence it.
10
+ - **Delivery per engine.** Claude Code: PostToolUse `additionalContext`, which reaches the model with the tool result. omp: the bridge appends the hint as text to the tool result. Codex has no hooks, so `node .claude/ukit/index/resolve-context.mjs "<intent>" --target <file>` prints the same block, and the instructions tell the agent to run it before editing.
11
+ - **New index artifact `.cache/index/edit-graph.json`**, rebuilt with the index only when the index changed. On this repository it is 289 KB; the graph step adds about 218 ms to a one-file refresh, and a full index build with no graph took about 1.2 s (both figures are for this repository only). A per-file token cache was tried to cut the 218 ms and gave no measurable gain in total refresh time, so it was not kept.
12
+ - **`resolve-context` impact output now includes the graph's mirrors**, next to the mirror pairs it already declared.
13
+ - **Off switches:** `UKIT_EDIT_HINTS=0` in the environment, or `memory.editHints.enabled: false`.
14
+ - **Hook runner:** a context-only document (PostToolUse `hookSpecificOutput` with no `permissionDecision` and no top-level `decision`, `continue: false` or `stopReason`) no longer ends the chain's output; it is merged with the other steps' output, and plain-text lines printed alongside it are folded into its `additionalContext` so Claude Code still receives one valid JSON document. Everything else behaves as before.
15
+ - **Safe Patch OK line:** `post-edit-verify` now prints its `[ukit-safe-patch] OK: ...` line as a `systemMessage` JSON document on Claude Code (it was plain text, which made the merged hook output invalid JSON and lost the hint on Safe Patch-backed files). omp still gets the plain line.
16
+ - Measured by replaying this repository's last 400 commits against each commit's parent tree (`scripts/bench/edit-hint-history.mjs`; repository only): mirrors recall 34/34 and precision 34/35. Tests, top 3 per commit: recall 0.39, precision 0.18, and at least one right test in 97 of 148 commits; per source file, recall is 0.06. Test hints are a starting point, not a complete list. The replay does not use importing-test evidence, which the shipped ranking also uses.
17
+ - Memory attached to code is thin so far: in this repository 13 of 66 `docs/MEMORY.md` bullets name a file that exists, and 0 of 9 memory records do, so most hints carry mirrors and tests only.
18
+ - Limits: `MultiEdit` and `NotebookEdit` get no hint. A hint dropped by context compaction is not re-sent in the same task. The step has a 400 ms budget (250 ms of it for memory) and stays silent rather than delay the edit; measured 164-199 ms through the real hook runner on the maintainer's machine, with the hint delivered together with memory lines.
19
+ - Engines: observed live on Claude Code for Edit: editing `docs/STATUS.md` and `docs/MEMORY.md` in this repository put the hint into the model's context as PostToolUse additional context, once per file (a second edit of the same file produced none). Codex and omp were not run live; omp is covered through the real bridge function with the real runner, not the omp host. Coverage is otherwise the shared runtime's tests.
20
+ - The step keeps its per-task state small: once there are more than 64 state files it removes those older than 7 days, at most 32 per run.
21
+ - Repository only: `CHANGELOG.md` entries 3.4.51-3.4.75 moved verbatim to `docs/archive/CHANGELOG-3.4.51-3.4.75.md` to keep the package inside its size budget (limits unchanged).
22
+
5
23
  ## 3.5.1 - 2026-11-14
6
24
 
7
25
  First release of the memory line (3.5.x). Recall now returns the project's written decisions instead of content-free session stubs. Design and evidence: `docs/research/2026-11-14_memory-system-research.md` (repository only).
@@ -105,213 +123,6 @@ Completion-gate fixes from a field-telemetry audit of the projects running UKit
105
123
  - Consumers: close related OMP/bridge sessions, `ukit update`, `ukit marker-store migrate`, then `--apply --writers-stopped`, verify, reopen. STOP stays in effect; legacy cursors are adopted only via explicit `--adopt-legacy-run`.
106
124
  - Artifact budget: packed < 3,500,000 and unpacked < 11,300,000 bytes (limits unchanged). To stay under the unpacked limit, about 92 verbose bullets in historical entries (mostly older than 2.7) were shortened in this file, saving about 22 KB; no release was removed, and the full original text is in git history at 46b48d11.
107
125
 
108
- ## 3.4.75 - 2026-11-01
109
-
110
- - Publish receipts bind to artifact integrity.
111
-
112
- ## 3.4.74 - 2026-10-30
113
-
114
- **Route publication protocol, handoff ownership authority and explicit legacy adoption; no live-host certification beyond the isolated native OMP A/B/C acceptance recorded in `docs/STATUS.md`.**
115
-
116
- - Route publication: pending sidecar → shared write with UUID revision → final sidecar commit across all route writers/readers (`docs/ROUTE_PUBLICATION.md`); Stop coherence tests and a fault-injection matrix cover torn/concurrent publication.
117
- - Handoff ownership: immutable run binding plus per-run authority record (generation/history) in `handoff-provenance.mjs`; `resolveCursorApplicability` yields OWNED / NOT_OWNED / UNKNOWN and UNKNOWN is never treated as ownership. Not described as fail-safe beyond what the tests prove.
118
- - OMP case A: a Stop with unavailable route identity is released as NOT_OWNED only when a bounded transcript intent scan proves the session never targeted the handoff; torn or non-JSON-shaped transcript lines stay unknown. Intent only releases a non-claimant and never grants ownership. Claude/OMP Stop differences are documented and tested (`stopHostSemantics.test.js`); advisory or loop-breaker release is not completion evidence.
119
- - Legacy adoption: owner-invoked `--adopt-legacy-run=<sha256>` only (never at session start or Stop), validated under lock against the cursor snapshot hash; preserves content and state and never declares a run done.
120
- - Publication intent: `publicationScope` treats "do not publish until/unless …" as a temporary restriction rather than a task-wide prohibition (it never grants authorization); `evidenceStatement` masks the repo's own release-policy sentence so it is not read as an execution order; `SEMANTIC_ENGINE_VERSION` bumped so cached intent scans are invalidated.
121
- - Release completion: `releasePublicationMissing` accepts only a task-owned, tool-use-attributed, non-masked publish receipt with a parsed `+ pkg@version` line followed by a later same-scope registry view (registry state alone is not proof); `cron-operation-adapter` reports publish receipts without that line as unproven; background completions apply the masked-exit check.
122
- - Artifact budget: packed < 3,500,000 and unpacked < 11,300,000 bytes.
123
-
124
- ## 3.4.73 - 2026-10-28
125
-
126
- - Git history proof tolerates unrelated untracked files; tracked/staged drift and explicit whole-tree clean obligations remain strict. No filename exemptions.
127
- - Native ledger-to-Stop fixtures cover Claude Code/Codex/omp, repeated Stop and untracked shipped-source publication drift; not live-host certification.
128
-
129
- ## 3.4.72 - 2026-10-28
130
-
131
- - Native evidence: reject background, masked and test-expression exits as operation/verification proof; retain supported foreground controls across shared Claude Code/Codex/OMP fixtures. No live-host certification.
132
- - Completion: retained publication-only debt uses task-owned registry proof only without a real operation goal; unrelated Git/service duties remain enforced.
133
- - Self-improve: serialize deferred AUTO queue replay/merge, retain snapshots/provenance and corrupt/legacy entries, drain only written tasks; dry-run remains read-only.
134
- - Release recovery: bind mandatory phase exits and independent final review to unchanged candidate bytes; publish lifecycle refuses missing prerequisites. Local evidence files are integrity checks, not cryptographic identity proof. Final acceptance and isolated registry consumers remain pending; 3.4.71 incident evidence is preserved below.
135
-
136
- ## 3.4.71 - 2026-10-28
137
-
138
- **F-7 intent scope, release-freeze coordination and Claude Code operation-receipt exit proof; no native-host certification.**
139
-
140
- - Classification (F-7): an inspection verb followed by an interrogative object ("review how the publish and deploy flow works", "explain why update failed") no longer lets its coordinated fragments become orders. The collapse ends at `then` or any coordinator followed by an action verb, so real orders after the question (including bare-verb, Vietnamese and adverb-interposed forms) keep their kind. Independent review probed ~490 prompt pairs against 3.4.70 with no remaining executable-to-READ_ONLY regression except intended compound-noun cases.
141
- - Self-improve: added a verifier freeze marker and deferred AUTO queue. Later review found repeated frozen passes could overwrite queued proposals; the original no-loss claim was incorrect.
142
- - Completion evidence: added Claude Code clean-PostToolUse shell-exit inference. Later review found background-child attribution unsafe; shell success alone is not native-operation success. No live-host certification.
143
- - Verification: full `yarn test` 698 files / 11,371 passed / 3 skipped, exit 0; official verifier PASS. Unpacked budget 11,200,000 owner-approved. Published before final independent CHANGES-REQUESTED review; normal-update testing also changed the owner's global installation instead of staying isolated. 3.4.71 was published, not fully accepted. Wrapper/correlation/stale-obligation and P2 work remained open.
144
-
145
- ## 3.4.70 - 2026-10-26
146
-
147
- **Task-owned completion evidence and bounded reminder recovery; no native-host certification.**
148
-
149
- - Classification: configuration comparisons, read-only output specifications and owner-approval reminders do not inherit mutation or verification debt. Explicit verification and publication orders retain their own obligations; private Git scope and later affirmative orders remain distinct. Descriptive acceptance-review prose — subordinator continuation fragments ("…, including source fixes F-3") and non-imperative goal/acceptance lines ("Final product goal: … normal ukit update pass") — no longer routes read-only reviews as implementation orders; any imperative fragment inside such a line still enforces write+verification.
150
- - Completion: preserve truthful blocked outcomes, scoped exhausted-denial reconciliation and native Git/remote evidence. Launch acknowledgements, missing exit proof, masked commands, foreign receipts and stale parity cannot prove success. Docs-only Handoff creation honors the owner's explicit Git publication scope.
151
- - Reminder recovery: reapply classified evidence obligations even when the task-kind signature is unchanged. Repeated read-only reminders need no artificial checkpoint verification; owned external blockers remain blocked rather than successful. No permission reset, receipt bypass or safety relaxation.
152
- - Release verification: bind mandatory phases to candidate bytes and fail on drift; run existing live-documentation checks before expensive gates and retain external per-run result metadata. Mandatory lanes, artifact budgets and timeouts are unchanged.
153
- - Evidence limits: targeted regressions and independent reviews cover shared Claude/OMP sources and fixtures; Codex remains advisory where no native hook exists. Historical failed verifier runs remain failed. The review integration fixture now has a measured, first-case-only 15s allowance after bounded child-latency reproduction; global/runtime timeouts are unchanged. Discovery deadline testing waits for the intended filesystem phase instead of racing startup I/O. No speculative performance fix or exact historical slowdown attribution is claimed.
154
-
155
- ## 3.4.69 - 2026-10-25
156
-
157
- **Narrow shared-lock cancellation repair; no new unattended-Handoff certification.**
158
-
159
- - Fix: cancellation after a successful lock owner stamp now passes through token-checked, best-effort release before returning `aborted`; the callback remains unexecuted. Deterministic regression verifies lock absence and immediate reacquisition.
160
- - Tests: managed Handoff template cases pin owner-byte preservation, exact sidecar bytes/provenance and no-write aligned behavior. Preflight fixtures now use an independent temporary Git repository with ownership-checked cleanup, avoiding default dirty-worktree/sandbox accumulation without touching retained evidence.
161
- - Verification: independent original and cleanup-only reviews approved with minor findings; full release verifier passed (core 10,741 passed / three skipped, isolated handoff 351/351, artifact 39/39). Cleanup review retains a non-blocking concurrency-sensitive source-inventory assertion and fail-loud fixture cleanup caveats.
162
- - Limits unchanged: native isolation dispatch, clean unattended lifecycle/native-host acceptance, historical `ukitcmd25` loss and unidentified `79/1` remain unresolved. This fix is not established as the cause of those incidents. No 3.4.68 live-gate waiver is inherited or live acceptance claimed.
163
-
164
- ## 3.4.68 - 2026-10-25
165
-
166
- **Stable hardening release; outstanding live acceptance explicitly deferred by the owner for the internal six-person team. This is not certification of unattended Handoff.**
167
-
168
- - Planning: durable source snapshots, recorded validator/independent-review ready gates, amendment/plan-count/overwrite controls, and realpath-safe installed helper entrypoints.
169
- - Runtime: authenticated asynchronous delegation completion, bounded recovery and claim fencing; landing coordinated with claims; explicit already-applied adoption and non-completing metadata reconciliation; completed-only archive/resume safeguards and three-engine adapter consistency.
170
- - Owner preservation: managed Handoff templates refresh only with provenance, retain custom content/sidecars safely through update and uninstall; prevent shell-keyword/state-builtin permission minting, with provenance-only sanitizer.
171
- - Classification/continuation: read-only output specifications and scheduled permission reminders no longer manufacture implementation work; real edit orders retain evidence obligations.
172
- - Safety: existing-only delegation guard also honors restrictive runner policy without a RUN marker. Planning instructions omit isolation, but **actual native dispatch is not fixed**: the latest create10 failed at its first isolation-bearing Agent call (0/10 accepted, nine skipped). The guard remains; no payload stripping, trust/permission expansion or provider workaround.
173
- - Known limits retained: clean unattended multi-plan execution, review-return/replan, blocked-independent scheduling, wait/no-duplicate, interruption/cycle resume, late-create frozen scope, pause/compact, current-candidate OMP lifecycle and missing native-host/platform coverage are not certified. Historical unidentified `79/1` and lost `ukitcmd25` (29/30) remain unexplained; later passing checks do not resolve them. Inspection-command friction also remains.
174
- - Evidence: reviewed repair groups; full code-candidate suite 673 files / 10,771 tests passed, three skipped. Recovered roadmap 8/8, integration 61/61, completed-only archive and unchanged reinvocation remain recovery evidence, not a clean unattended PASS. The owner explicitly waived these outstanding live gates as release blockers, not technical/package/registry-consumer checks. No FAIL/BLOCKED evidence is relabeled PASS.
175
-
176
- ## 3.4.67 - 2026-10-23
177
-
178
- - Fix: a wait/monitor/hold-only request ("keep waiting on the verifier job, read output to the footer, do not edit while the candidate is frozen") is now classified verification-only (`READ_ONLY`, `verification-evidence`) instead of the `CODE_IMPLEMENTATION` default that demanded `write-evidence` and forced an Edit/Write. A wait that also carries a real order ("wait, then fix src/app.js") stays an implementation. Vietnamese "rồi" now splits clauses for this check. Both classifier copies (`src/core/executionContracts.js`, installed `route-resolver.mjs`) changed together; regression in `tests/hooks/gateIntentClassification.test.js`.
179
- - Test-only: `hookProcessTree` escapee regression budget no longer races a cold Node start under full-suite load.
180
-
181
- ## 3.4.66 - 2026-10-23
182
-
183
- **Handoff hardening: scope-frozen runs, completed-only ARCHIVE, bounded repair, isolated verification.**
184
- - Stop coordinator: INDEX task rows parse positionally (empty cells keep columns; malformed rows fail closed); an unreadable or vanished archive snapshot no longer falls back to stale task headers; optional `ScopeQueue`/`Cycle` freeze a run to its assigned scope so unrelated queued or archived history cannot prove completion; `Paused: yes` releases continuation without minting completion.
185
- - Archive writer: canonical `docs/AI_HANDOFF/ARCHIVE/cycle-NN/`; refuses (before any write) symlinked docs/AI_HANDOFF/archive/cycle/INDEX/TASK paths, malformed or unreadable prior snapshots and any task-enumeration error instead of snapshotting a partial cycle; legacy lowercase archives stay read-only.
186
- - Commands: create queues independent plans instead of overwriting, preserves sources and amendments; fullstack/implement/review commit with `git commit --only` explicit paths (unrelated staged and unstaged owner work preserved, proven against a real Git fixture); failures route to bounded repair or replan instead of blocked; one persisted Recovery exception after escalation; clear pauses and preserves unfinished work and keeps read-back write verification; blocked is reserved for external blockers or genuine owner requirement conflicts.
187
- - `yarn test:handoff` now runs `tests/handoff/**` in a disposable copy with throwaway HOME, excluded live handoff state (any-case ARCHIVE), vetted symlinks, checked git setup, bounded children and explicit path validation; wired into `release:verify`.
188
-
189
- ## 3.4.65 - 2026-10-22
190
-
191
- **Configuration capture: Vietnamese comparison is not a mutation order.**
192
- - Original pilot prompt reproduced CONFIGURATION/external with no operationGoal: “Đối chiếu cấu hình đang hoạt động” normalized to `doi chieu`, then `doi` was mistaken for “đổi” (change). Exclude only `doi chieu` from config mutation verbs in the three shared classifier copies; do not change repository detection, operation receipts or completion gates.
193
- - Exact prompt fixture, comparison variants and genuine change commands (including comparison followed by change) retain regression coverage. Existing Stop-boundary reconciliation corrects the stale classified contract without resetting task identity/counters; original rotated live contract is not reconstructed or sealed.
194
- - Authorized one-pair CLI-worker experiment: cap2 COMPLETE 4/4; cap4 INCOMPLETE 2/4. No four-worker adoption, extra arm, global/BAGuide/default change or native OMP throughput claim. Experiment harness/report are repository evidence, not installed runtime.
195
-
196
- ## 3.4.64 - 2026-10-22
197
-
198
- **Completion Gate: defect-contingent repair/release is not an unconditional publish order.**
199
- - Exact approved pilot prompt reproduced false `release-publication`: line/comma splitting detached `release npm` from the preceding wrapped “Nếu gặp bug UKit…” condition. Standing policy/carryover is not needed to reproduce it.
200
- - Preserve defect-repair sentence scope across line wraps; activate its release branch only after owned runtime writes. Direct publish commands still require registry verification, and foreign-task proofs remain rejected.
201
- - Do not interpret hashed write-bank keys as paths; bank the runtime-write classification separately across same-task rekeys. Docs/test-only direct writes do not activate repair publication. Legacy pathless Bash deltas remain conservative (may demand release); no new path-attribution architecture added.
202
- - Pilot preflight narrowed to existing host interfaces and exact condition-change options; no paid arms, no relaxed limits adopted, no BAGuide/default changes.
203
-
204
- ## 3.4.63 - 2026-10-22
205
-
206
- **Completion recovery: background pending is not a pipeline.**
207
- - Reproduced task `task-848c14831946f7c359cdf11faf45edd2` / `bk1n4wpks`: bare release verifier exited 0 in host notification; Bash/grep read did not ingest completion. Launch and masked-shell receipts share `exitStatusUnproven`; recovery falsely asserted pipeline and requested reruns.
208
- - Diagnostic-only fix: background launch -> wait SAME job, no duplicate; host completion -> Read task output through footer, not rerun; masked shell -> wrapper status unproven, actual pipe only a possible cause. Receipt acceptance/freshness unchanged; unsupported hosts remain fail-closed.
209
- - Regressions: pending, host completion+Bash vs Read, later launch not masking valid completion, failed runner, masked wrapper, analysis-doc freshness vs living STATUS; existing forged/mismatched/duplicate/foreign/stale controls retained.
210
- - Release-gate fixture repair: TERM-ignoring grandchild now signals readiness after handler installation before the measured runner deadline starts (injected real child); retains ≥700ms grace/escalation and no-survivor assertions. Production hook-process unchanged.
211
- - Independent four-task fixture pilot and whole-workflow budget proposal recorded; no paid pilot. OMP genuine-service live smoke remains unverified (deterministic RPC bash lacks name/ready); no claim of every-service coverage.
212
-
213
- ## 3.4.62 - 2026-10-22
214
-
215
- **Handoff commands: state what `handoff.maxParallelAgents` counts (wording only).**
216
- - The cap is child workers of ONE batch or review set, summed across roles (implementers and reviewers together); the main session is outside it; it is not a session-wide limit; it is prompt-level guidance (no hook counts children) and the host's own concurrency limit is separate. Added to `handoff-implement`, `handoff-fullstack` (implement batch + review set) and `handoff-review`.
217
- - No default, config key, scope or behavior change. Basis: BAGuide field audit (peak 14 concurrent children while the cap text said 2, never refused), see `docs/analysis/CONCURRENCY-CHECKPOINT-2026-10-22.md`.
218
-
219
- ## 3.4.61 - 2026-10-22
220
-
221
- **omp bash: stop sending the call shape the host rejects (`name` + `async`/`timeout`).**
222
- - Field evidence (BAGuide session log, 2026-10-19..22): 1,771 of 6,541 bash calls failed with "Service mode does not accept async or timeout; use ready.timeout for readiness." Every failing call carried `name` with `async`/`timeout`; calls without `name` never failed and 66 immediate retries that dropped `name` succeeded. `name` was used as a label on finite commands.
223
- - Host contract (omp 18.12.5 bash `execute`, read from the installed binary): `name` selects SERVICE mode, which rejects `async === true` and any `timeout`; readiness is `ready.timeout`. Without `name`, `async`/`timeout` are valid and `ready` is only ignored with a warning.
224
- - Change: `omp-bash-call-guard.mjs` (block-only, stateless, never rewrites input or changes a command's meaning) wired into the omp bridge `tool_call` for `bash`; the block reason separates the two intents (finite command: drop `name`/`ready`; service: drop `async`/`timeout`, use `ready.timeout`). Same rule added to the Stall & Wait instructions (STALL-02) for all three engines.
225
- - Live smoke (omp 18.12.5, isolated temp project with the template bridge, model `unic/unic-lite`, BAGuide and the omp binary untouched): `name`+`timeout` was blocked with the UKit preflight text (not the host's "Service mode..." text), so the `tool_call` hook runs before the host validator; a finite command ran; the corrected retry (name dropped) ran and was not blocked. NOT verified live: a genuine service call (the test model kept adding a top-level `timeout`; one attempt hung with no output and was stopped; no process was left running). The service-allowed path is covered only by the bridge-boundary tests. Guidance, not host enforcement.
226
- - Flaky test root cause + fix: `withTransientFsRetry` compared `Date.now()` against a deadline while sleeping with `setTimeout`; node timers can fire up to ~2% early at small delays, so after a clamped sleep the clock still showed time remaining and an extra attempt ran. It now measures with `performance.now()` (injectable `now`/`sleep`) and stops after a sleep that exhausted the deadline. Regression: `tests/hooks/transientFsRetry.test.js` (controlled clock incl. early-timer skew, plus one real-timer smoke); 30/30 repeated runs.
227
- - Review freshness through a real Bash mutation (git fixture, real PostToolUse receipt): review approved -> `sed -i` via Bash -> `changeSeq` advances, review is `review-stale`, verification is `edited-after-verification`; a no-op Bash keeps the approval. No defect reproduced; regression `tests/hooks/playbookReviewBashMutation.test.js`.
228
- - Regression: `tests/hooks/ompBashCallGuard.test.js` (normal finite command with timeout/async allowed; genuine service with `ready.timeout` allowed; `name`+`timeout` / `name`+`async` blocked repeatably; blank `name` is not service mode; input never mutated).
229
-
230
- ## 3.4.60 - 2026-10-22
231
-
232
- **Completion Gate: a background completion footer is no longer trusted on its own.**
233
- - Gap: 3.4.59 accepted `[exited with code N]` at the end of `.../tasks/<id>.output` as the runner's exit status. That file holds the runner's own stdout, so a process (or a test fixture) that prints the footer while still running, or before a non-zero exit, could produce a false PASS.
234
- - Fix: a completion is accepted only when the session transcript holds the HOST's `<task-notification>` for the same task id (queue event or plain user turn; tool-result text, including a Read of the output file, never counts) and its exit code equals the footer. No notification -> `no-host-notification`; disagreement -> `host-footer-mismatch`. A host-reported failure is recorded as failed.
235
- - Regression: `tests/hooks/backgroundCompletionForgery.test.js` (footer printed while running, imitation notification inside a tool result, matching notification, mismatching exit, host failure, other task id); lifecycle tests now mirror the host notification.
236
- - Limit: needs `transcript_path` in the hook payload (Claude Code provides it); without it a background completion stays unproven. omp/Codex shapes not covered; replay, not a live host.
237
-
238
- ## 3.4.59 - 2026-10-22
239
-
240
- **Completion Gate: a host-backgrounded verification can now complete through a supported, provenance-bound result capture.**
241
- - Gap: 3.4.57 made a background launch acknowledgement unproven, but nothing could later turn it into evidence, so the only route was re-running a long suite in the foreground. Claude Code delivers the completion as a task-notification the hooks never see; the host does write the runner's output to `.../tasks/<id>.output` ending in `[exited with code N]`.
242
- - Fix: when the agent reads that file back, the ledger records a verification receipt bound to the launch receipt by `backgroundTaskId` (same task ledger, so another task/session finds no launch), exit status from the host footer, judged against the LAUNCH tree fingerprint. Rejected: no footer (still running / "passed" text only), no matching launch, duplicate completion, output file older than the launch. Exit 1 yields a failed verdict.
243
- - Regression: `tests/hooks/backgroundCompletionLifecycle.test.js` (success, failure, partial, duplicate, other task, other session, late, stale file, unrelated file, Stop-gate outcomes). Also `tests/orchestration/schedulingHarness.test.js`: a deterministic offline scheduling-logic model (not a throughput benchmark).
244
- - Limit: replay of the host file format observed on Claude Code; omp/Codex background shapes are not covered, and no hook receives the notification itself.
245
-
246
- ## 3.4.58 - 2026-10-22
247
-
248
- **Completion Gate: plain publish orders create the registry obligation, new tasks do not inherit the previous task's evidence, and a Vietnamese status line about a config is not a config order.**
249
- - Bug: "Please/Now npm publish the package", "Đưa package lên npm" and "Phát hành bản này lên npm" were not read as publish orders, so code + tests PASS completed the gate with nothing on the registry. `promptOrdersNpmPublish` now accepts polite/sequencing prefixes and the Vietnamese publish verbs; negations, `--dry-run` and prohibitions still create no debt.
250
- - Bug: a new task inherited the previous task's classifier-owned contract fields and MIXED evidence (a stale `git-integrity push` goal and `operation-verification` under "npm publish the package"), so a correct publish run stayed blocked on an unordered push. `skill-router.sh` now resets them when a new task starts.
251
- - Bug: "OMP version/config đã load lúc bắt đầu vẫn unknown" classified CONFIGURATION/external (`bat` in "bắt đầu", `tat` in "tất cả" read as toggle verbs), demanding operation proof for a status report. `bat`/`tat` no longer match those phrases; real "Bật/Tắt config" orders stay CONFIGURATION (3 classifier copies + mirrors).
252
- - Regression: `tests/hooks/releaseCompletionEvidence.test.js` (resolver → contract → gate), `tests/hooks/configPreferenceNotOrder.test.js` + real-prompt fixture.
253
- - Limit: the resolver still emits no release-specific contract field; the obligation is enforced gate-side from the prompt. Verified offline on macOS/Node 22; replay, not a live host.
254
-
255
- ## 3.4.57 - 2026-10-22
256
-
257
- **Completion Gate: background launch acknowledgements are not verification evidence; stale-contract reconciliation covers all obligation fields and the Stop boundary.**
258
- - Bug: a host-backgrounded Bash runner (`run_in_background`) answers with a launch acknowledgement (`backgroundTaskId` / "Command running in background with ID: …") that carries no exit status, yet the ledger minted a `test-verified` verdict from it. The ack now records an `unproven` verification receipt (`exitStatusUnproven`, not success); a foreground exit status is still required. Completion of the background job is a separate host event and is not accepted as evidence by this change.
259
- - Stale contract (3.4.56 follow-up): reconciliation now compares kind plus `operationGoal` / `configurationScope` / `releasePolicy` / `reportArtifact` and replaces classifier-owned fields wholesale (no leaked stale `operationGoal`); the Stop evaluator (`execution-ledger.mjs --evaluate-stop`) also reconciles in memory, so read-only / Bash-only tasks (which never trigger the router) no longer stay stuck. Only `contractOrigin: classified` contracts are eligible; system-carried and status-report contracts, and genuine MIXED/OPERATIONAL contracts, are unchanged.
260
- - Regression: `tests/hooks/backgroundLaunchAckNotEvidence.test.js`, extended `tests/hooks/staleContractRederive.test.js`.
261
- - Verified offline on macOS/Node 22; replay, not a live host.
262
-
263
- ## 3.4.56 - 2026-10-22
264
-
265
- **Completion Gate: a stale self-classified contract is re-derived from the task's own prompt on continuation.**
266
- - Field case: after the 3.4.55 classifier fix, an in-flight task kept its previously stored MIXED contract (continuations reused `routeSummary.executionContract` verbatim), so the gate still demanded `operation-verification` the user's prompt never ordered.
267
- - Fix (`persistRouteState` in `skill-router.sh`): on a non-system continuation whose stored contract was classified by the router (`contractOrigin` != `carried-system`, not a status report), the contract is re-classified from `lastExplicitUserPromptText`; it is replaced only when the taskKind differs. Genuine contracts re-classify identically and are kept; system-carried contracts are never touched. No gate loosening, no receipts added.
268
- - Regression: `tests/hooks/staleContractRederive.test.js` (stale MIXED corrected, genuine MIXED retained, carried-system untouched, new task classified on its own).
269
- - Verified offline on macOS/Node 22; hook replay, not a live host.
270
-
271
- ## 3.4.55 - 2026-10-22
272
-
273
- **Completion Gate: preference, conditional-future and prohibition-list text is not an order (field false-block).**
274
- - Field case: an audit prompt saying "Ưu tiên configuration change" (preference) and "Nếu chỉ cần configuration change:" (future branch) was classified `CONFIGURATION`/external, so the Stop gate demanded `operation-verification` for a config edit nobody ordered (task `task-0c7425cb…`, `accepted-count=0`). A follow-up prompt listing what an authorization does NOT allow as bullets ("không cho phép: - restart …") plus "Negative controls: … chỉnh config/restart/deploy" was classified `MIXED`/service-runtime.
275
- - Fix (`neutralizeNonOrders` in all three classifier copies: `src/core/executionContracts.js`, `route-resolver.mjs` mirror, `skill-router.sh` inline): a config preference, a prohibition-header bullet list (bounded to its own sentence and ended by a blank line) and "negative/positive controls" test-case bullets are neutralized; the audit/inspect/review lead filter now tolerates bullet prefixes. Gate, ledger and loop-breaker logic untouched; genuine config/restart/deploy orders and mixed implementation tasks keep their obligations (negative controls in tests).
276
- - Regression: `tests/hooks/configPreferenceNotOrder.test.js` (src + installed + hook copy; real prompt fixtures `concurrency-audit-config-preference-prompt.txt`, `authorization-boundary-bullets-prompt.txt`). Independent review found one false negative (header regex swallowed the whole line before it); fixed and pinned.
277
- - Housekeeping: `docs/STATUS.md` rotated under its 150-line budget (verbatim archive), concurrency audit report registered in `manifests/documentation.yaml`.
278
- - Verified offline on macOS/Node 22; classifier replay, not a live OMP/Claude Code/Codex session; Windows/Linux not run.
279
-
280
- ## 3.4.54 - 2026-10-22
281
-
282
- **Completion Gate: a stated prohibition is not an operation order (field false-block).**
283
- - Fix: `classifyTaskSemantics` (src + shipped `route-resolver.mjs` mirror) treated "Production deploy/restart vẫn bị cấm", "production deploy vẫn bị chặn", "forbidden deploy/publish" and a bare list item "Production restart." as actionable runtime operations, so an audit/report prompt became MIXED + service-runtime and the Stop gate demanded `operation-verification` for a restart nobody ordered.
284
- - New guard `operationNotOrdered` applies to the git/runtime operation checks only: a prohibition attached to the operation, or a bare production-operation noun item, orders nothing. Lift/past markers ("was prohibited, owner now allows", "even though it is not allowed", "khong bi chan") keep the clause an order. Real orders (restart + verify, deploy to production, fix + restart) are unchanged.
285
- - Regression: `tests/hooks/prohibitionNotOrder.test.js` (78 cases across src + installed copies) with the real field prompt fixture. Ledger, gates and release logic untouched.
286
- - Verified offline on macOS/Node 22; OMP/Claude Code coverage is classifier replay, not live host.
287
-
288
- ## 3.4.53 - 2026-10-22
289
-
290
- **Stop-level closure of the UNPROVEN verdict (follow-up to 3.4.52).**
291
- - `recoveryInstruction`: a non-current `unproven` verdict no longer yields "verdict is stale, re-run at current head"; it names the real gap (masked pipe, exit status unproven) and never "fix the failure".
292
- - `stop-coordinator`: the `verify:pass` predicate and `goalVerificationVerdict` treat `unproven` as unmet but report "unproven (exit status not proven)", not a verified failure; `unproven` never counts as a pass.
293
- - New Stop-level regressions (`tests/hooks/executionLedgerStopLifecycle.test.js`, GC-03e): UNPROVEN neither failure nor PASS; exhausted retry budget ends visibly without a recovery loop or write demand; same-task same-command PASS clears its own blocker, a different command / UNPROVEN rerun / another task does not; a superseded failure stops producing recovery text.
294
- - Note: `tests/handoff/**` is excluded from `vitest`; run `tests/handoff/goalCompletion.test.js` with `node --test` (vitest exits 1 with "No test files found").
295
- - Verified offline on macOS/Node 22; no live host proof.
296
-
297
- ## 3.4.52 - 2026-10-22
298
-
299
- **Verification-loop ledger integrity (post-3.4.51 follow-up).**
300
- - Fix: the fd number of a redirection (`2>&1`, `2>/dev/null`, `12>&1`) leaked into the verification-loop fingerprint as an argument, so `... .test.js 2>&1 | tail` was reported as `... .test.js 2`. Genuine numeric arguments and quoted text are untouched.
301
- - A masked-pipe exit (`exitStatusUnproven`) now carries its own non-satisfying `unproven` verdict kind and is no longer counted as a definite failure toward the verification-loop streak.
302
- - A later valid PASS of the same command on the same task/ledger clears its own sticky `verification-loop` blocker; evidence never crosses tasks or ledgers. Wrapper exit 0 still never becomes PASS.
303
- - Regressions: `tests/hooks/executionLedger*.test.js`, `verificationExitProof`. Verified offline on macOS/Node 22; live host (Claude Code/OMP) in-memory state unverified, reload/`ukit update` + restart needed to load the fix.
304
-
305
- ## 3.4.51 - 2026-10-21
306
-
307
- **Handoff orchestration integrity (CKit/OMP 18.12.5 incident audit).**
308
- - OMP `Task` preflight (block-only): an ordinary agent carrying `sourceSession`/`model` (any value, even empty) or batch-root `sourceSession`/`model` is blocked with exact remove-field guidance; args are never rewritten, seance stays native-owned. Retries are counted per session + task instance + fingerprint (prose/name/status excluded), hashed, bounded and persisted; STOP guidance after two identical blocks.
309
- - Stop-gate continuation provenance: only positively native/system-origin continuations (OMP branch `session-stop-continuation` match) reuse the task contract; a user paste of the gate text mints a fresh task. Pending-continuation marker is session/task/reason-hash scoped and lock-serialized.
310
- - Resumable records now require exact stored task-id equality (lossy filename normalization could collide).
311
- - Classifier: diagnostic "which config changed" reports are READ_ONLY; forward configuration orders and mixed source mutation + report stay CONFIGURATION / CODE_IMPLEMENTATION.
312
- - Review-panel aggregation: FAIL/NOT_RUN dominate, underscore verdict aliases normalized, executable N/A becomes NOT_RUN; explicit product / integration-evidence / status-only review kinds. Handoff commands carry retry-fingerprint and pending-review continuity rules.
313
- - Audit: `docs/analysis/HANDOFF-INTENT-DISPATCH-AUDIT.md`. Historical CKit wrapper/contract origin remains unknown; verified offline on macOS/Node 22 only; no live host proof, no CI dispatch.
314
-
315
126
  ## 3.4.22 - 2026-10-07
316
127
 
317
128
  **Windows: `.sh` hooks no longer deny every Edit/Write/Bash.**
@@ -1322,6 +1322,19 @@ items:
1322
1322
  packs:
1323
1323
  - core
1324
1324
 
1325
+ # 3.5.2 WP-C: advisory PostToolUse Edit|Write module step (edit-graph hint).
1326
+ - id: hook-edit-hint-module
1327
+ type: hook
1328
+ sourceTemplate: .claude/hooks/edit-hint.mjs
1329
+ targetPath: .claude/hooks/edit-hint.mjs
1330
+ requires:
1331
+ - ukit-runtime-scripts
1332
+ mergeStrategy: overwrite_with_backup
1333
+ variables: []
1334
+ enabledByDefault: true
1335
+ packs:
1336
+ - core
1337
+
1325
1338
  - id: hook-completion-gate
1326
1339
  type: hook
1327
1340
  sourceTemplate: .claude/hooks/completion-gate.sh
@@ -1862,6 +1875,16 @@ items:
1862
1875
  packs:
1863
1876
  - core
1864
1877
 
1878
+ - id: ukit-index-edit-graph-script
1879
+ type: config
1880
+ sourceTemplate: .claude/ukit/index/edit-graph.mjs
1881
+ targetPath: .claude/ukit/index/edit-graph.mjs
1882
+ mergeStrategy: overwrite_with_backup
1883
+ variables: []
1884
+ enabledByDefault: true
1885
+ packs:
1886
+ - core
1887
+
1865
1888
  - id: ukit-index-route-catalog-script
1866
1889
  type: config
1867
1890
  sourceTemplate: .claude/ukit/index/route-catalog.mjs
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ngockhoale/ukit",
3
- "version": "3.5.1",
3
+ "version": "3.5.2",
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",
@@ -532,6 +532,7 @@ export function buildDefaultRuntimeConfig(overrides = {}) {
532
532
  maxPatternCandidates: 50,
533
533
  redactSecrets: true,
534
534
  sources: ['docs/MEMORY.md'],
535
+ editHints: { enabled: true, mirrors: [], ignoreMirrors: [] },
535
536
  },
536
537
  validation: {
537
538
  enabled: true,
@@ -11,6 +11,8 @@ import { withAsyncLock } from '../../template_project/.claude/ukit/runtime/async
11
11
 
12
12
  import { getArtifactPath, getIndexDir, INDEX_ARTIFACTS, INDEX_SCHEMA_VERSION, isLikelyTestFilePath, normalizeRelative } from './paths.js';
13
13
  import { importsNeedAliasContext, loadImportAliasContextState, resolveImportSpecifier } from './importResolution.js';
14
+ import { ensureEditGraph } from '../../template_project/.claude/ukit/index/edit-graph.mjs';
15
+ import { MIRROR_PAIRS } from './impactCatalog.js';
14
16
  import { clearIndexArtifactCache } from './queryIndex.js';
15
17
  import { clearRelatedTestArtifactCache } from './relatedTests.js';
16
18
 
@@ -582,6 +584,7 @@ async function buildCodeIndexInner({ rootDir = process.cwd(), changedFiles = nul
582
584
  [INDEX_ARTIFACTS.relations]: relations.length,
583
585
  },
584
586
  });
587
+ await refreshEditGraph(absoluteRoot, sourceFingerprint.digest, fileRecords, codeFiles, imports, importAliasContext, signal);
585
588
  const preservedRuntimeCaches = canReuseFilesArtifact
586
589
  && canReuseAllParsedArtifacts
587
590
  && canReuseTestsMap
@@ -1241,6 +1244,7 @@ async function tryIncrementalIndexUpdate({ absoluteRoot, indexDir, changedPaths,
1241
1244
  clearIndexArtifactCache(absoluteRoot);
1242
1245
  clearRelatedTestArtifactCache(absoluteRoot);
1243
1246
  }
1247
+ await refreshEditGraph(absoluteRoot, refreshedFingerprint.digest, mergedFileRecords, codeFiles, imports, importAliasContext, signal);
1244
1248
 
1245
1249
  return {
1246
1250
  indexDir,
@@ -2573,6 +2577,24 @@ function areSourceFingerprintsEqual(previousFingerprint, nextFingerprint) {
2573
2577
  && previousFingerprint?.digest === nextFingerprint?.digest;
2574
2578
  }
2575
2579
 
2580
+ // Edit graph (mirror/test/import edges): rebuilt only when missing or its digest
2581
+ // differs from the index fingerprint. Never fails the index build.
2582
+ async function refreshEditGraph(rootDir, indexDigest, fileRecords, codeFiles, imports, aliasContext, signal) {
2583
+ await ensureEditGraph({
2584
+ rootDir,
2585
+ indexDigest,
2586
+ signal,
2587
+ inputs: () => {
2588
+ const resolved = buildResolvedImportMap(rootDir, imports, new Set(codeFiles.map((f) => f.filePath)), aliasContext);
2589
+ return {
2590
+ files: fileRecords,
2591
+ imports: resolved,
2592
+ declaredMirrors: MIRROR_PAIRS,
2593
+ };
2594
+ },
2595
+ });
2596
+ }
2597
+
2576
2598
  async function writeArtifact(rootDir, artifactName, payload) {
2577
2599
  const artifactPath = getArtifactPath(rootDir, artifactName);
2578
2600
  const temporaryPath = `${artifactPath}.tmp-${Date.now()}-${Math.random().toString(16).slice(2)}`;
@@ -2,6 +2,7 @@ import fs from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
 
4
4
  import { getArtifactPath, INDEX_ARTIFACTS, isLikelyTestFilePath } from './paths.js';
5
+ import { loadEditGraph, neighboursOf } from '../../template_project/.claude/ukit/index/edit-graph.mjs';
5
6
  import { classifyImpactRisk, findMirrorCounterparts } from './impactCatalog.js';
6
7
  import { inferRelatedTestsFromArtifacts, loadRelatedTestArtifacts } from './relatedTests.js';
7
8
  import { importsNeedAliasContext, loadImportAliasContext, resolveImportSpecifier } from './importResolution.js';
@@ -108,7 +109,16 @@ export async function resolveImpactContext({
108
109
  const callItems = safeItems(callsArtifact);
109
110
  const importItems = safeItems(importsArtifact);
110
111
  const risk = classifyImpactRisk(normalizedChangedFiles);
111
- const mirrorCounterparts = findMirrorCounterparts(normalizedChangedFiles).slice(0, budget.maxMirrors);
112
+ const editGraph = await loadEditGraph(absoluteRoot);
113
+ const mirrorCounterparts = [...findMirrorCounterparts(normalizedChangedFiles)];
114
+ for (const changed of normalizedChangedFiles) {
115
+ for (const mirror of neighboursOf(editGraph, changed).mirrors) {
116
+ if (!mirrorCounterparts.some((m) => m.filePath === mirror.path && m.source === changed)) {
117
+ mirrorCounterparts.push({ filePath: mirror.path, reason: `edit-graph ${mirror.kind} mirror`, source: changed });
118
+ }
119
+ }
120
+ }
121
+ mirrorCounterparts.splice(budget.maxMirrors);
112
122
 
113
123
  const changedFileSet = new Set(normalizedChangedFiles);
114
124
  const changedSymbolSet = new Set(normalizedChangedSymbols);
@@ -0,0 +1,119 @@
1
+ // edit-hint.mjs — PostToolUse Edit|Write chain step (advisory, always code 0).
2
+ // After a successful edit of file X, hands the MODEL the edit-graph hint once per
3
+ // file per task (mirror to fix, tests to run, cited memory). Claude Code: JSON
4
+ // hookSpecificOutput.additionalContext; omp: the bridge appends stdout verbatim,
5
+ // so plain text. Async fs only; self-deadline 400 ms; any failure emits nothing.
6
+ import fsp from 'node:fs/promises';
7
+ import path from 'node:path';
8
+
9
+ const DEADLINE_MS = 400; // once per file per task; the step slot is 8 s
10
+ const MEMORY_MS = 250; // memory sub-budget: a miss still emits mirrors/tests
11
+ const MAX_SEEN = 200;
12
+ const MAX_BYTES = 16 * 1024;
13
+ const NONE = { code: 0, stdout: '', stderr: '' };
14
+ const safe = (v, d) => String(v || d).replace(/[^A-Za-z0-9_-]/g, '_').slice(0, 80) || d;
15
+ const readJson = async (file) => {
16
+ try { return JSON.parse(await fsp.readFile(file, 'utf8')); } catch { return null; }
17
+ };
18
+
19
+ // Retention: over 64 entries, drop this step's own `<safe>.<safe>.json` files older than 7 days (max 32 deletions, 128 stats per run). Fire-and-forget.
20
+ async function prune(dir, keep) {
21
+ try {
22
+ const names = await fsp.readdir(dir);
23
+ if (names.length <= 64) return;
24
+ let left = 32;
25
+ let stats = 128;
26
+ for (const n of names) {
27
+ if (left <= 0 || stats <= 0) break;
28
+ if (n === keep || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.json$/.test(n)) continue;
29
+ stats -= 1;
30
+ try {
31
+ const f = path.join(dir, n);
32
+ if (Date.now() - (await fsp.stat(f)).mtimeMs <= 7 * 864e5) continue;
33
+ await fsp.unlink(f);
34
+ left -= 1;
35
+ } catch { /* ignore */ }
36
+ }
37
+ } catch { /* retention is best-effort */ }
38
+ }
39
+
40
+ async function hint(ctx, signal, commit) {
41
+ const { payload: p = {}, projectRoot, env = {} } = ctx;
42
+ if (env.UKIT_EDIT_HINTS === '0' || process.env.UKIT_EDIT_HINTS === '0') return NONE;
43
+ if (!['Edit', 'Write'].includes(p.tool_name) || !projectRoot) return NONE;
44
+ const res = p.tool_response;
45
+ if (res && (res.is_error === true || res.isError === true || res.success === false)) return NONE;
46
+ const raw = p.tool_input?.file_path;
47
+ if (typeof raw !== 'string' || !raw) return NONE;
48
+ const rel = path.relative(projectRoot, path.resolve(p.cwd || projectRoot, raw)).split(path.sep).join('/');
49
+ if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return NONE;
50
+
51
+ const config = await readJson(path.join(projectRoot, '.ukit/storage/config.json'));
52
+ if (config?.memory?.editHints?.enabled === false) return NONE;
53
+ const route = await readJson(path.join(projectRoot, '.claude/ukit/skill-router-state.json'));
54
+ const session = safe(p.session_id, 'nosession');
55
+ const task = typeof route?.taskInstanceId === 'string' && route.taskInstanceId ? route.taskInstanceId : session;
56
+ const stateFile = path.join(projectRoot, '.ukit/storage/cache/edit-hints', `${session}.${safe(p.agent_id, 'main')}.json`);
57
+ const prev = await readJson(stateFile);
58
+ const st = prev && prev.task === task && Array.isArray(prev.seen)
59
+ ? { task, seen: prev.seen.filter((x) => typeof x === 'string'), shownMem: Array.isArray(prev.shownMem) ? prev.shownMem.filter((x) => typeof x === 'string') : [] }
60
+ : { task, seen: [], shownMem: [] };
61
+ if (st.seen.includes(rel)) return NONE;
62
+
63
+ const lanes = await import('../ukit/runtime/memory-lanes.mjs');
64
+ const out = await lanes.editHintFor({
65
+ projectRoot, target: rel, config: config ?? {}, signal, memoryBudgetMs: MEMORY_MS,
66
+ exclude: { paths: st.seen, memoryIds: st.shownMem },
67
+ });
68
+ if (signal.aborted) return NONE;
69
+ // Memory missed its budget and there is no graph text: not "nothing to say", retry next edit.
70
+ if (out?.memoryMissed && !out.text) return NONE;
71
+
72
+ // Commit point: once state is being marked, finish and emit (a few ms of fs) so a
73
+ // deadline firing mid-write can never mark the file seen without delivering the hint.
74
+ commit.on = true;
75
+ st.seen.push(rel);
76
+ st.shownMem.push(...(out?.memoryIds || []));
77
+ st.seen = st.seen.slice(-MAX_SEEN);
78
+ st.shownMem = st.shownMem.slice(-MAX_SEEN);
79
+ let body = JSON.stringify(st);
80
+ while (body.length > MAX_BYTES && st.seen.length > 1) {
81
+ st.seen.shift();
82
+ st.shownMem.shift();
83
+ body = JSON.stringify(st);
84
+ }
85
+ try {
86
+ await fsp.mkdir(path.dirname(stateFile), { recursive: true });
87
+ const tmp = `${stateFile}.${process.pid}.tmp`;
88
+ await fsp.writeFile(tmp, body);
89
+ await fsp.rename(tmp, stateFile);
90
+ } catch { /* state is best-effort */ }
91
+ void prune(path.dirname(stateFile), path.basename(stateFile));
92
+
93
+ const text = typeof out?.text === 'string' ? out.text.trim() : '';
94
+ if (!text) return NONE;
95
+ const omp = p.ukit_harness === 'omp' || env.UKIT_HARNESS === 'omp';
96
+ const stdout = omp
97
+ ? `${text}\n`
98
+ : `${JSON.stringify({ hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext: text } })}\n`;
99
+ return { code: 0, stdout, stderr: '' };
100
+ }
101
+
102
+ export async function runHook(ctx = {}) {
103
+ const ac = new AbortController();
104
+ const commit = { on: false };
105
+ const ms = Math.min(DEADLINE_MS, Number.isFinite(ctx.deadlineMs) ? ctx.deadlineMs : DEADLINE_MS);
106
+ const timer = setTimeout(() => ac.abort(), Math.max(1, ms));
107
+ const outer = ctx.signal;
108
+ if (outer) outer.aborted ? ac.abort() : outer.addEventListener('abort', () => ac.abort(), { once: true });
109
+ try {
110
+ return await Promise.race([
111
+ hint(ctx, ac.signal, commit),
112
+ new Promise((resolve) => ac.signal.addEventListener('abort', () => { if (!commit.on) resolve(NONE); }, { once: true })),
113
+ ]);
114
+ } catch {
115
+ return NONE;
116
+ } finally {
117
+ clearTimeout(timer);
118
+ }
119
+ }
@@ -146,8 +146,8 @@
146
146
  "hooks": [
147
147
  {
148
148
  "type": "command",
149
- "command": "node \"$CLAUDE_PROJECT_DIR/.claude/ukit/runtime/hook-chain-runner.mjs\" --emit-verdict - \"$CLAUDE_PROJECT_DIR/.claude/hooks/post-edit-verify.sh\":8 \"$CLAUDE_PROJECT_DIR/.claude/hooks/record-execution.mjs\":8 \"$CLAUDE_PROJECT_DIR/.claude/hooks/task-watchdog.sh\":8",
150
- "timeout": 34
149
+ "command": "node \"$CLAUDE_PROJECT_DIR/.claude/ukit/runtime/hook-chain-runner.mjs\" --emit-verdict - \"$CLAUDE_PROJECT_DIR/.claude/hooks/post-edit-verify.sh\":8 \"$CLAUDE_PROJECT_DIR/.claude/hooks/record-execution.mjs\":8 \"$CLAUDE_PROJECT_DIR/.claude/hooks/task-watchdog.sh\":8 \"$CLAUDE_PROJECT_DIR/.claude/hooks/edit-hint.mjs\":8",
150
+ "timeout": 42
151
151
  }
152
152
  ]
153
153
  },