@ngockhoale/ukit 3.4.73 → 3.4.75

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.
Files changed (28) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/manifests/documentation.yaml +10 -0
  3. package/manifests/platform.full.yaml +15 -0
  4. package/package.json +4 -1
  5. package/template_project/.claude/commands/ukit/handoff-fullstack.md +34 -12
  6. package/template_project/.claude/hooks/completion-gate.sh +10 -1
  7. package/template_project/.claude/hooks/handoff-resume.sh +38 -53
  8. package/template_project/.claude/hooks/owner-stop-gate.mjs +41 -0
  9. package/template_project/.claude/hooks/skill-router.sh +473 -36
  10. package/template_project/.claude/hooks/verification-guard.sh +8 -1
  11. package/template_project/.claude/settings.json +33 -1
  12. package/template_project/.claude/ukit/index/publication-intent.mjs +128 -13
  13. package/template_project/.claude/ukit/index/route-task.mjs +124 -26
  14. package/template_project/.claude/ukit/runtime/block-breaker.mjs +1 -0
  15. package/template_project/.claude/ukit/runtime/compact-threshold.mjs +8 -1
  16. package/template_project/.claude/ukit/runtime/cron-operation-adapter.mjs +14 -5
  17. package/template_project/.claude/ukit/runtime/execution-ledger.mjs +399 -35
  18. package/template_project/.claude/ukit/runtime/handoff-intent.mjs +5 -0
  19. package/template_project/.claude/ukit/runtime/handoff-provenance.mjs +277 -0
  20. package/template_project/.claude/ukit/runtime/loop-state.mjs +23 -4
  21. package/template_project/.claude/ukit/runtime/operation-evidence.mjs +9 -0
  22. package/template_project/.claude/ukit/runtime/reinject-context.mjs +10 -0
  23. package/template_project/.claude/ukit/runtime/resumable-run.mjs +33 -11
  24. package/template_project/.claude/ukit/runtime/stop-coordinator.mjs +284 -58
  25. package/template_project/.omp/hooks/pre/ukit-bridge.js +171 -3
  26. package/scripts/dev/worktree-preflight.mjs +0 -166
  27. package/scripts/measure-decision-gateway.mjs +0 -306
  28. package/scripts/probe/codex-capability-probe.mjs +0 -169
package/CHANGELOG.md CHANGED
@@ -2,6 +2,22 @@
2
2
 
3
3
  All notable changes to UKit are documented here.
4
4
 
5
+ ## 3.4.75 - 2026-11-01
6
+
7
+ - Publish receipts bind to artifact integrity.
8
+
9
+ ## 3.4.74 - 2026-10-30
10
+
11
+ **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`.**
12
+
13
+ - 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.
14
+ - 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.
15
+ - 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.
16
+ - 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.
17
+ - 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.
18
+ - 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.
19
+ - Artifact budget: packed < 3,500,000 and unpacked < 11,300,000 bytes.
20
+
5
21
  ## 3.4.73 - 2026-10-28
6
22
 
7
23
  - Git history proof tolerates unrelated untracked files; tracked/staged drift and explicit whole-tree clean obligations remain strict. No filename exemptions.
@@ -277,6 +277,16 @@ entries:
277
277
  load_policy: on-demand
278
278
  validation: [manual]
279
279
  archive_policy: never
280
+ - id: docs-route-publication
281
+ path: docs/ROUTE_PUBLICATION.md
282
+ class: canonical
283
+ audience: [agent, maintainer]
284
+ owner: runtime
285
+ source_of_truth: docs/ROUTE_PUBLICATION.md
286
+ merge_strategy: none
287
+ load_policy: on-demand
288
+ validation: [manual]
289
+ archive_policy: never
280
290
  - id: docs-release-checklist
281
291
  path: docs/RELEASE_CHECKLIST.md
282
292
  class: canonical
@@ -1226,6 +1226,7 @@ items:
1226
1226
  - hook-block-dangerous
1227
1227
  - hook-handoff-model-guard
1228
1228
  - hook-delegation-gate-module
1229
+ - hook-owner-stop-gate-module
1229
1230
  - hook-auto-prune-bash
1230
1231
  - hook-project-important
1231
1232
  # Env block is post-merged by applyGatewayResilienceEnv (TASK-011) to add managed
@@ -1426,6 +1427,20 @@ items:
1426
1427
  packs:
1427
1428
  - core
1428
1429
 
1430
+ # Owner STOP gate: in-proc PreToolUse catch-all (`.*`) step; denies every NEW tool/spawn start for a stopped session
1431
+ # and its delegated children. Reads route state through ukit-runtime-scripts (execution-ledger.mjs).
1432
+ - id: hook-owner-stop-gate-module
1433
+ type: hook
1434
+ sourceTemplate: .claude/hooks/owner-stop-gate.mjs
1435
+ targetPath: .claude/hooks/owner-stop-gate.mjs
1436
+ requires:
1437
+ - ukit-runtime-scripts
1438
+ mergeStrategy: overwrite_with_backup
1439
+ variables: []
1440
+ enabledByDefault: true
1441
+ packs:
1442
+ - core
1443
+
1429
1444
  # P0 delegation enforcement: in-proc PreToolUse chain step (Edit|Write, MultiEdit, Bash). Claude Code
1430
1445
  # only (agent_id main/worker identity); reads route state + ledger from ukit-runtime-scripts.
1431
1446
  - id: hook-delegation-gate-module
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ngockhoale/ukit",
3
- "version": "3.4.73",
3
+ "version": "3.4.75",
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",
@@ -32,6 +32,9 @@
32
32
  "scripts/",
33
33
  "!scripts/dev/benchmark-verification-currency.mjs",
34
34
  "!scripts/dev/capture-omp-stall.mjs",
35
+ "!scripts/dev/worktree-preflight.mjs",
36
+ "!scripts/measure-decision-gateway.mjs",
37
+ "!scripts/probe/codex-capability-probe.mjs",
35
38
  "!scripts/install/generate-semantic-engine.mjs",
36
39
  "!scripts/release/progress-reporter.mjs",
37
40
  "!scripts/release/publish-guard-core.mjs",
@@ -79,10 +79,11 @@ Before dispatching any mutating worker (including blueprint folding), write and
79
79
  P0/P1 cursor with the actual phase, frozen scope, next action and known job references. Do not
80
80
  defer cursor creation until P2; omit ExitPredicate until P2 pins it, never invent a satisfied one.
81
81
  Reconcile partial writes and existing jobs from that cursor on interruption; never restart the fold blindly.
82
-
82
+ The invocation's RunId must come from an authoritative UKit invocation binding, not from transcript text or a guessed value. If no binding is available, do not create or rewrite a cursor or claim ownership; report the missing invocation provenance as BLOCKED. On resume, verify that the existing cursor's RunId matches that binding before changing it.
83
83
 
84
84
  ```
85
85
  Command: handoff-fullstack
86
+ RunId: <exact invocation RunId supplied by the UKit hook; never invent or backfill>
86
87
  Goal: <one sentence from the **Problem / feature** section above>
87
88
  Base: <BASE branch>
88
89
  Phase: <P0|P1|P2|P2.5|P3|I1|I2|I3|I4|R1|R2|R3|R4|R4.5|R5|F|done|blocked>
@@ -194,31 +195,52 @@ Wherever a step below says **verify the write**, it means this rule.
194
195
 
195
196
  ### Resume — when the run is re-invoked mid-flight
196
197
 
197
- If `docs/AI_HANDOFF/RUN.md` exists with `Phase:` not `done` or `blocked`, this is a
198
- **continuation, not a new cycle**. Do NOT re-plan, do NOT overwrite `PLAN.md`, do NOT ask
198
+ An existing cursor is not itself ownership. To resume a bound run from a new task or
199
+ session, the user must explicitly invoke `/ukit:handoff-fullstack --resume-run=<RunId>`
200
+ with its exact RunId; the invocation hook must verify the binding and current route.
201
+ Missing, mismatched or unverified identity means BLOCKED without changing the cursor.
202
+ A bare invocation continues when the current task already owns the cursor. It cannot
203
+ transfer ownership from an earlier task, even if there is only one cursor: the cursor
204
+ is not authorization. This is a compatibility change for older bare cross-task resumes;
205
+ use the exact RunId from the original authoritative invocation with `--resume-run`.
206
+ If that identity or binding is unavailable, stop without rewriting the cursor.
207
+
208
+ If `docs/AI_HANDOFF/RUN.md` exists with `Phase:` not `done` or `blocked` and the
209
+ current route owns its RunId, this is a **continuation, not a new cycle**. Do NOT re-plan, do NOT overwrite `PLAN.md`, do NOT ask
199
210
  the human whether to continue. Read the cursor, then jump straight to `Next:` and carry on.
200
211
  Tasks already `done` are skipped. `pending_review` tasks are NOT re-implemented — they go to
201
212
  the R-phase review (R2–R4). `ready`, `in_progress`, `changes_requested` and `blocked` tasks
202
213
  are routed to implementation/fix (I-phase). Any nonterminal state gets a branch; none is
203
214
  skipped silently.
204
215
 
205
- `Phase: blocked` is terminal for the run — the machinery (Stop gate, hooks, stop-coordinator)
206
- all treats it as closed. It is *paused*, not abandoned: an explicit `/ukit:handoff-fullstack`
207
- re-invocation resumes it as a continuation; `ukit handoff-clear` pauses it (`Paused: yes`, backlog and scope kept, no completion minted). Only when
208
- `RUN.md` is absent or `Phase: done` does a new request start a fresh cycle.
216
+ `Phase: blocked` releases the current run at Stop when no independent work remains,
217
+ but an authorized explicit invocation may continue its frozen scope; it is not a new
218
+ cycle. `Phase: done` is terminal. A nonterminal run may also be paused (`Paused: yes`),
219
+ with backlog and scope retained and no completion minted.
220
+
221
+ ### Legacy run without a RunId — explicit adoption
222
+
223
+ A live cursor written before ownership existed has no `RunId:` line, so no session owns it and
224
+ a bare invocation is refused. The refusal prints the exact command; the owner runs
225
+ `/ukit:handoff-fullstack --adopt-legacy-run=<RunId>` where `<RunId>` is the digest of that exact
226
+ cursor. Adoption is never automatic (not at session start, not at Stop, not from the Skill tool).
227
+ It refuses a stale snapshot, a completed run, a cursor that already has a RunId, and any run that
228
+ already has an owner or invalid identity state. It creates the identity through the same ownership
229
+ authority, then adds only a `RunId:` line; phase, scope, queue and ExitPredicate are untouched, and it
230
+ never marks the run done or repairs a malformed ExitPredicate. After an interrupted adoption only the same
231
+ session may re-invoke the same command to finish it.
209
232
 
210
233
  ### Explicit invocation reacquires ownership
211
234
 
212
- An explicit `/ukit:handoff-fullstack` also lifts a liveness pause: the resume hook rewrites `Paused: yes` to `Paused: no` in `RUN.md`, reads it back, and keeps `Phase:`, scope, and the queue untouched. Ordinary prompts, startup, and clear never lift it.
235
+ An explicit resume may lift a liveness pause only after the current route's ownership is verified. The rewrite must keep `Phase:`, scope, and the queue untouched and be read back. Ordinary prompts, startup, and clear never lift it.
213
236
 
214
237
  `/ukit:handoff-create` is planning-only and makes a session's handoff intent *planning* — so
215
238
  while the human is planning, neither the Stop gate nor the SessionStart compact/resume hook
216
239
  forces a paused run back into implementation. This command is the explicit counter-action:
217
240
 
218
- - Invoking `/ukit:handoff-fullstack` (or running the `handoff-fullstack` skill) makes the
219
- session's handoff intent *implementation* again — ownership is reacquired, the queued
220
- `ready` tasks from the create phase are picked up, and a `Phase:` outside `done`/`blocked`
221
- in `RUN.md` is once more held to completion by the Stop gate.
241
+ - An authorized invocation makes the session's handoff intent *implementation* again.
242
+ Ownership is retained by the current owner or transferred only by a verified explicit
243
+ resume claim; invoking the skill alone does not reacquire a foreign cursor.
222
244
  - Work queued by planning is **not lost**: it waits in `INDEX.md`/`PLAN.md` until this
223
245
  explicit invocation (or `/ukit:handoff-implement`) claims it.
224
246
 
@@ -85,7 +85,9 @@ fi
85
85
  # (coordinator deadline + margin); a forced kill lands on the existing crash-streak
86
86
  # path (non-zero STATUS) so the outcome is announced, never silently released.
87
87
  __ukit_coord_out="$(mktemp "${TMPDIR:-/tmp}/ukit-coord-out.XXXXXX")"
88
- printf '%s' "$INPUT" | UKIT_HARNESS="${UKIT_HARNESS:-claude-code}" UKIT_HOOK_DEADLINE_MS="${UKIT_HOOK_DEADLINE_MS:-3000}" node "$SCRIPT" --evaluate-stop > "$__ukit_coord_out" 2>/dev/null &
88
+ __ukit_coord_err="$(mktemp "${TMPDIR:-/tmp}/ukit-coord-err.XXXXXX" 2>/dev/null)" || __ukit_coord_err=/dev/null
89
+ __ukit_coord_t0=$SECONDS
90
+ printf '%s' "$INPUT" | UKIT_HARNESS="${UKIT_HARNESS:-claude-code}" UKIT_HOOK_DEADLINE_MS="${UKIT_HOOK_DEADLINE_MS:-3000}" node "$SCRIPT" --evaluate-stop > "$__ukit_coord_out" 2>"$__ukit_coord_err" &
89
91
  __ukit_coord_pid=$!
90
92
  __ukit_coord_ms="${UKIT_HOOK_DEADLINE_MS:-3000}"
91
93
  case "$__ukit_coord_ms" in ''|*[!0-9]*) __ukit_coord_ms=3000 ;; esac
@@ -99,6 +101,13 @@ kill "$__ukit_killer_pid" 2>/dev/null
99
101
  wait "$__ukit_killer_pid" 2>/dev/null
100
102
  OUTPUT="$(cat "$__ukit_coord_out" 2>/dev/null)"
101
103
  rm -f "$__ukit_coord_out"
104
+ # Bounded diagnostic for a crashed coordinator (status>128 = killed by signal N-128, e.g. 137 = the deadline killer's SIGKILL).
105
+ # Written to a private cache file only; never part of the decision text (the reason stays fixed and redacted).
106
+ if [ "$STATUS" -ne 0 ]; then
107
+ mkdir -p "$PROJECT_ROOT/.ukit/storage/cache" 2>/dev/null
108
+ { printf 'status=%s elapsed_s=%s deadline_ms=%s\n' "$STATUS" "$((SECONDS - __ukit_coord_t0))" "${__ukit_coord_ms}"; head -c 400 "$__ukit_coord_err" 2>/dev/null; printf '\n'; } > "$PROJECT_ROOT/.ukit/storage/cache/completion-gate-crash.last" 2>/dev/null
109
+ fi
110
+ [ "$__ukit_coord_err" = /dev/null ] || rm -f "$__ukit_coord_err"
102
111
 
103
112
  if [ "$STATUS" -ne 0 ]; then
104
113
  # BUG-C22-05: a PERSISTENT coordinator crash must not block every Stop forever.
@@ -249,46 +249,6 @@ function boundedTaskScopeLines(all, runCycle, currentTask) {
249
249
  })();
250
250
  const source = typeof payload.source === 'string' ? payload.source : 'startup';
251
251
 
252
- // Explicit-pause lift. Only a transcript whose latest handoff intent is `fullstack`
253
- // may clear `Paused: yes`. The shared classifier does not split the user `<command-name>`
254
- // tag from the resume banner, so both count as this lift's evidence; a paused run never
255
- // gets a banner (the pause returns before any banner is written), so a banner in the
256
- // transcript only comes from an earlier resume. The rewrite changes only the `Paused:`
257
- // line (atomic tmp+rename) and is read back before it is trusted; any failure returns
258
- // { ok:false } and the pause stays.
259
- async function liftExplicitPause(mod, payload, runFile, text) {
260
- try {
261
- const transcript = typeof payload.transcript_path === 'string' ? payload.transcript_path : null;
262
- if (!transcript || typeof mod.transcriptHandoffIntent !== 'function') return { ok: false };
263
- const { intent, known } = await mod.transcriptHandoffIntent(transcript);
264
- if (!known || intent !== 'fullstack') return { ok: false };
265
- // The banner also classifies as fullstack, so require the user's explicit command tag to be
266
- // the LAST evidence: a `<command-name>` tag for fullstack/implement must appear after the last
267
- // resume banner. A banner from an earlier resume never lifts a later pause.
268
- const tail = await fs.promises.readFile(transcript, 'utf8');
269
- const lastTag = Math.max(
270
- tail.lastIndexOf('<command-name>/ukit:handoff-fullstack</command-name>'),
271
- tail.lastIndexOf('<command-name>/ukit:handoff-implement</command-name>'),
272
- tail.lastIndexOf('<command-name>ukit:handoff-fullstack</command-name>'),
273
- tail.lastIndexOf('<command-name>ukit:handoff-implement</command-name>'),
274
- tail.lastIndexOf('<command-name>/handoff-fullstack</command-name>'),
275
- tail.lastIndexOf('<command-name>/handoff-implement</command-name>'),
276
- );
277
- const lastBanner = tail.lastIndexOf('UKIT HANDOFF RESUME');
278
- if (lastTag < 0 || lastTag < lastBanner) return { ok: false };
279
- const next = text.replace(/^Paused:.*$/m, 'Paused: no');
280
- if (next === text) return { ok: false };
281
- const tmp = `${runFile}.tmp-unpause-${process.pid}-${Date.now()}`;
282
- await fs.promises.writeFile(tmp, next, 'utf8');
283
- await fs.promises.rename(tmp, runFile);
284
- const readBack = await fs.promises.readFile(runFile, 'utf8');
285
- if (!/^Paused:\s*no\b/m.test(readBack) || /^Paused:\s*yes\b/m.test(readBack)) return { ok: false };
286
- return { ok: true, text: readBack };
287
- } catch {
288
- return { ok: false };
289
- }
290
- }
291
-
292
252
  // Worktree scoping: the host pins CLAUDE_PROJECT_DIR to the primary checkout, so a
293
253
  // session in an independent linked worktree must not be handed the primary's
294
254
  // cursor. Only a git-verified worktree of this repo re-scopes the cursor; any
@@ -314,32 +274,57 @@ async function liftExplicitPause(mod, payload, runFile, text) {
314
274
  const phase = field('Phase');
315
275
  // `done` and `blocked` are both terminal (blocked = closed with instructions, the
316
276
  // same posture stop-coordinator.mjs uses). Anything else means a step was in flight.
317
- if (!phase || /^(done|blocked)\b/i.test(phase)) {
277
+ const terminalPhase = /^(done|blocked)\b/i.exec(phase)?.[1]?.toLowerCase() || '';
278
+ if (!phase || terminalPhase === 'done') {
318
279
  await emitOrdinaryResume(payload, source);
319
280
  process.exit(0);
320
281
  }
321
282
 
322
- // Structured PAUSED (C100 P1): never inject a resume for a paused run, on any source.
323
- // The one lift: an EXPLICIT /ukit:handoff-fullstack in this session's transcript (a
324
- // user `<command-name>` tag, never the banner this hook injects) clears `Paused: yes`
325
- // back to `Paused: no`, verified by read-back, Phase/scope untouched, then the resume
326
- // continues below. Startup/clear and non-explicit prompts never lift a pause.
283
+ try {
284
+ const ledger = await import(pathToFileURL(runtimePath).href);
285
+ const routeState = await ledger.readRouteState(projectRoot, payload);
286
+ if (ledger.ownerStopActive(routeState, payload)) {
287
+ process.stdout.write('UKit note: an owner STOP is standing for this session; handoff run not resumed. Cursor untouched. Only a new owner request resumes work.\n');
288
+ process.exit(0);
289
+ }
290
+ } catch {}
291
+
292
+ // Transcript intent cannot establish ownership of a cursor. Resolve the current
293
+ // session's durable binding before either injecting a resume or lifting a pause.
294
+ let ownership;
295
+ try {
296
+ const provenance = await import(pathToFileURL(path.join(projectRoot, '.claude', 'ukit', 'runtime', 'handoff-provenance.mjs')).href);
297
+ ownership = await provenance.resolveCursorApplicability({
298
+ projectRoot, runRoot: path.dirname(path.dirname(path.dirname(runPath))),
299
+ sessionId: payload.session_id || payload.sessionId,
300
+ });
301
+ } catch {
302
+ ownership = { status: 'UNKNOWN', reason: 'handoff provenance runtime unavailable' };
303
+ }
304
+ if (terminalPhase === 'blocked' && ownership.status === 'OWNED' && !ownership.claim) {
305
+ await emitOrdinaryResume(payload, source);
306
+ process.exit(0);
307
+ }
308
+ if (ownership.status !== 'OWNED') {
309
+ if (ownership.status === 'UNKNOWN') {
310
+ process.stdout.write(`UKit handoff ownership UNKNOWN (${ownership.reason}); cursor untouched and automatic resume skipped.\n`);
311
+ } else {
312
+ process.stdout.write('UKit note: an unfinished handoff-fullstack run may be present, but this task does not own its cursor; planning or other current work may continue. Cursor untouched.\n');
313
+ }
314
+ process.exit(0);
315
+ }
316
+
317
+ // Session-start and compaction are not authoritative user invocations. Never
318
+ // lift a pause here, even if a historical transcript contains a command.
327
319
  try {
328
320
  const mod = await import(pathToFileURL(intentPath).href);
329
321
  if (typeof mod.runCursorPaused === 'function' && mod.runCursorPaused(text) === true) {
330
- const lift = source !== 'startup' && source !== 'clear'
331
- ? await liftExplicitPause(mod, payload, runPath, text)
332
- : null;
333
- if (lift?.ok) {
334
- text = lift.text;
335
- } else {
336
322
  process.stdout.write([
337
323
  'UKit note: docs/AI_HANDOFF/RUN.md has a handoff-fullstack run that is PAUSED '
338
324
  + `(Phase: ${phase}; Cursor: ${field('Cursor') || 'not recorded'}).`,
339
325
  'Not resumed or spawned; only an explicit user instruction lifts the pause. RUN.md untouched.',
340
326
  ].join('\n') + '\n');
341
327
  process.exit(0);
342
- }
343
328
  }
344
329
  } catch {}
345
330
 
@@ -0,0 +1,41 @@
1
+ // owner-stop-gate.mjs — PreToolUse chain step (in-proc `runHook(ctx)`), wired on the catch-all `.*` matcher.
2
+ //
3
+ // While an owner STOP stands on a session (route state `ownerControl.kind === 'stop'`), NO new tool, shell command,
4
+ // edit, MCP call or subagent may start for that session or for a subagent it delegated. Matching is by the shared
5
+ // dispatch point (every tool name), not a tool list, so a new or renamed tool cannot slip past it.
6
+ //
7
+ // Scope, stated honestly:
8
+ // * It prevents NEW starts. It cannot cancel an operation that is already running — that is the host's `session_stop`.
9
+ // * Session-bound: an independent session in the same repo has its own route record and is never affected.
10
+ // * The STOP never expires; only a genuine owner prompt (the router) lifts it. Quoted/hook-shaped text cannot.
11
+ // * Denying is terminal for the call and creates no continuation: the Stop lanes already release on a standing STOP.
12
+ // * Codex exposes no hook surface, so nothing here runs there (advisory-only engine; see manifests/hostCapabilities.yaml).
13
+ // Fail-open on an internal fault (a broken advisory step must not wedge the session); the omp bridge applies the same
14
+ // check in-process at its own `tool_call` / `before_subagent_spawn` handlers.
15
+
16
+ import { ownerStopGovernsStart } from '../ukit/runtime/execution-ledger.mjs';
17
+
18
+ export const hookFailClosed = false;
19
+
20
+ export const OWNER_STOP_REASON = 'Owner STOP is in effect for this session: no new tool, shell command, edit or subagent may start until the owner sends a new request. Do not retry; report the stop and wait.';
21
+
22
+ export async function runHook(ctx) {
23
+ try {
24
+ const payload = ctx?.payload || {};
25
+ const env = ctx?.env || {};
26
+ // Bounded by the chain runner's per-step deadline (ctx.deadlineMs); a slow read fails open rather than wedge the call.
27
+ const deadlineMs = Number(ctx?.deadlineMs) > 0 ? Number(ctx.deadlineMs) : 4000;
28
+ const root = env.CLAUDE_PROJECT_DIR || ctx?.projectRoot || process.cwd();
29
+ const ids = [payload.session_id, payload.sessionId, payload.ukit_parent_session_id];
30
+ const stopped = await Promise.race([ownerStopGovernsStart(root, ids), new Promise((resolve) => setTimeout(() => resolve(false), Math.max(500, deadlineMs - 500)).unref())]);
31
+ if (!stopped) return { code: 0, stdout: '', stderr: '' };
32
+ const inChain = Boolean(env.UKIT_HOOK_CHAIN_RUNNER);
33
+ return {
34
+ code: inChain ? 2 : 0,
35
+ stdout: `${JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: OWNER_STOP_REASON } })}\n`,
36
+ stderr: `BLOCKED: ${OWNER_STOP_REASON}\n`,
37
+ };
38
+ } catch {
39
+ return { code: 0, stdout: '', stderr: '' };
40
+ }
41
+ }