@ngockhoale/ukit 3.5.17 → 3.5.19

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 (62) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/manifests/platform.full.yaml +48 -0
  3. package/package.json +1 -1
  4. package/scripts/audit/field-replay.mjs +7 -7
  5. package/scripts/audit/field-telemetry.mjs +4 -3
  6. package/scripts/release/run-core-batch.mjs +10 -0
  7. package/src/cli/commands/mission.js +102 -0
  8. package/src/cli/commands/rescue.js +83 -0
  9. package/src/cli/index.js +14 -0
  10. package/src/core/compact/contextBudget.js +62 -41
  11. package/src/core/compact/threshold.js +14 -32
  12. package/src/core/observability/schema/registry.js +91 -0
  13. package/src/core/runtimeConfig.js +53 -2
  14. package/src/render/buildVariables.js +2 -5
  15. package/template_project/.claude/commands/ukit/handoff-implement.md +3 -3
  16. package/template_project/.claude/commands/ukit/handoff-review.md +3 -3
  17. package/template_project/.claude/hooks/context-hardcap-gate.sh +47 -20
  18. package/template_project/.claude/hooks/context-window-guard.sh +82 -27
  19. package/template_project/.claude/hooks/handoff-resume.sh +11 -2
  20. package/template_project/.claude/hooks/mission-capture.mjs +37 -0
  21. package/template_project/.claude/hooks/post-compact-observe.mjs +34 -0
  22. package/template_project/.claude/hooks/sensitive-data-guard.mjs +35 -3
  23. package/template_project/.claude/hooks/shell-watch.mjs +34 -0
  24. package/template_project/.claude/hooks/stop-failure-rescue.mjs +109 -0
  25. package/template_project/.claude/settings.json +36 -4
  26. package/template_project/.claude/ukit/index/test-batches-adapters.mjs +8 -3
  27. package/template_project/.claude/ukit/index/test-batches.mjs +80 -28
  28. package/template_project/.claude/ukit/runtime/compact-threshold.mjs +15 -29
  29. package/template_project/.claude/ukit/runtime/context-capacity.mjs +64 -1
  30. package/template_project/.claude/ukit/runtime/execution-ledger.mjs +44 -3
  31. package/template_project/.claude/ukit/runtime/hook-chain-runner.mjs +20 -1
  32. package/template_project/.claude/ukit/runtime/loop-state.mjs +17 -2
  33. package/template_project/.claude/ukit/runtime/mission/checkpoint.mjs +85 -0
  34. package/template_project/.claude/ukit/runtime/mission/classify.mjs +182 -0
  35. package/template_project/.claude/ukit/runtime/mission/drift.mjs +58 -0
  36. package/template_project/.claude/ukit/runtime/mission/graph.mjs +381 -0
  37. package/template_project/.claude/ukit/runtime/mission/hooks.mjs +199 -0
  38. package/template_project/.claude/ukit/runtime/mission/journal.mjs +68 -0
  39. package/template_project/.claude/ukit/runtime/mission/metrics.mjs +64 -0
  40. package/template_project/.claude/ukit/runtime/mission/recall.mjs +132 -0
  41. package/template_project/.claude/ukit/runtime/mission/redact.mjs +25 -0
  42. package/template_project/.claude/ukit/runtime/mission/restore.mjs +107 -0
  43. package/template_project/.claude/ukit/runtime/mission/store.mjs +231 -0
  44. package/template_project/.claude/ukit/runtime/mission/working.mjs +88 -0
  45. package/template_project/.claude/ukit/runtime/prompt-injection-cap.mjs +33 -0
  46. package/template_project/.claude/ukit/runtime/reinject-context.mjs +87 -6
  47. package/template_project/.claude/ukit/runtime/rescue/bundle.mjs +122 -0
  48. package/template_project/.claude/ukit/runtime/rescue/classify-failure.mjs +136 -0
  49. package/template_project/.claude/ukit/runtime/rescue/lease.mjs +65 -0
  50. package/template_project/.claude/ukit/runtime/rescue/reconstruct.mjs +273 -0
  51. package/template_project/.claude/ukit/runtime/rescue/recovery-state.mjs +120 -0
  52. package/template_project/.claude/ukit/runtime/rescue/rollover.mjs +151 -0
  53. package/template_project/.claude/ukit/runtime/sensitive-value-scanner.mjs +1 -1
  54. package/template_project/.claude/ukit/runtime/shell-watch.mjs +294 -0
  55. package/template_project/.claude/ukit/runtime/stop-coordinator.mjs +154 -0
  56. package/template_project/.omp/config.yml +2 -2
  57. package/template_project/.omp/hooks/pre/ukit-bridge.js +69 -2
  58. package/template_project/AGENTS.md +4 -2
  59. package/template_project/CLAUDE.md +4 -2
  60. package/template_project/docs/AI_HANDOFF/RULES.md +4 -4
  61. package/template_project/instructions/core.md +4 -2
  62. package/template_project/ukit/storage/config.json +32 -10
@@ -135,7 +135,7 @@ async function emitOrdinaryResume(payload, source) {
135
135
  if (!runtimeExists) return false;
136
136
  try {
137
137
  const runtime = await import(pathToFileURL(runtimePath).href);
138
- const intent = await runtime.readResumeIntent(projectRoot, payload, { consume: true });
138
+ const intent = await runtime.readResumeIntent(projectRoot, payload, { consume: true, compact: source === 'compact' });
139
139
  if (!intent) return false;
140
140
  const out = [
141
141
  'UKIT ROUTED TASK RESUME — an unfinished ordinary routed task was preserved before context compaction.',
@@ -146,7 +146,16 @@ async function emitOrdinaryResume(payload, source) {
146
146
  ];
147
147
  if (source === 'compact') {
148
148
  out.push('');
149
- out.push('The session was just compacted, so the window is clean — resume immediately rather than reporting status and waiting.');
149
+ out.push('=== POST-COMPACTION RESUME ===');
150
+ // Snapshot fields come from the PreCompact checkpoint; absent on legacy intents.
151
+ if (intent.goal) out.push(`Goal: ${intent.goal.replace(/\s+/g, ' ').slice(0, 1200)}`);
152
+ if (intent.contract) out.push(`Contract: ${intent.contract}`);
153
+ if (intent.observedEvidence?.length) out.push(`Evidence observed: ${intent.observedEvidence.join(', ')}`);
154
+ if (intent.unmetEvidence?.length) out.push(`Unmet evidence: ${intent.unmetEvidence.join(', ')}`);
155
+ if (intent.nextStep) out.push(`Next step: ${intent.nextStep}`);
156
+ if (intent.git?.head) out.push(`Git at compaction: HEAD ${String(intent.git.head).slice(0, 12)}, ${intent.git.dirtyFiles || 0} dirty file(s) — re-check git status before mutating.`);
157
+ out.push('Compaction is not completion — continue the work now; the window is clean. Do not report status and wait, and do not ask the user to /compact or start a new session.');
158
+ out.push('=== END ===');
150
159
  }
151
160
  process.stdout.write(`${out.join('\n')}\n`);
152
161
  return true;
@@ -0,0 +1,37 @@
1
+ // mission-capture.mjs - UserPromptSubmit + PostToolUse(TodoWrite|TaskCreate|TaskUpdate) chain step (WP4).
2
+ // Records the (redacted) prompt into the mission journal, classifies it into the requirement graph, and mirrors
3
+ // todo/task tool calls into graph task status. Emits nothing to the model except one short drift line when the
4
+ // drift signature changes. Advisory: always code 0, fail-open, deadline-bounded. Logic: ukit/runtime/mission/hooks.mjs.
5
+ import path from 'node:path';
6
+ import { pathToFileURL, fileURLToPath } from 'node:url';
7
+
8
+ export const hookFailClosed = false;
9
+ const NONE = { code: 0, stdout: '', stderr: '' };
10
+ const MODULE_DIR = path.dirname(fileURLToPath(import.meta.url));
11
+
12
+ export async function runHook(ctx = {}) {
13
+ let timer;
14
+ try {
15
+ const projectRoot = ctx.projectRoot || process.cwd();
16
+ const payload = ctx.payload && typeof ctx.payload === 'object' ? ctx.payload : {};
17
+ const deadlineMs = Number(ctx.deadlineMs || process.env.HOOK_DEADLINE_MS) || 2000;
18
+ const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve(''), Math.max(100, deadlineMs - 150)); timer.unref?.(); });
19
+ const work = (async () => {
20
+ const mod = await import(pathToFileURL(path.join(MODULE_DIR, '..', 'ukit', 'runtime', 'mission', 'hooks.mjs')).href);
21
+ if (payload.hook_event_name === 'PostToolUse') { await mod.todoMirrorStep({ projectRoot, payload }); return ''; }
22
+ if (payload.tool_name) return '';
23
+ return mod.captureStep({ projectRoot, payload });
24
+ })();
25
+ const text = await Promise.race([work, timeout]);
26
+ if (!text) return NONE;
27
+ const env = ctx.env || process.env;
28
+ const omp = payload.ukit_harness === 'omp' || env.UKIT_HARNESS === 'omp';
29
+ const stdout = omp ? `${text}\n`
30
+ : `${JSON.stringify({ hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext: text } })}\n`;
31
+ return { code: 0, stdout, stderr: '' };
32
+ } catch {
33
+ return NONE;
34
+ } finally {
35
+ clearTimeout(timer);
36
+ }
37
+ }
@@ -0,0 +1,34 @@
1
+ // post-compact-observe.mjs - PostCompact chain step (observe-only, always code 0, fail-open).
2
+ // Records COMPACT_SUCCEEDED; an empty/unusable summary (<200 chars) is flagged as failure class 11.
3
+ // Only the summary LENGTH is stored, never its text.
4
+ import path from 'node:path';
5
+ import { pathToFileURL, fileURLToPath } from 'node:url';
6
+
7
+ export const hookFailClosed = false;
8
+ const NONE = { code: 0, stdout: '', stderr: '' };
9
+ const HOOKS_DIR = path.dirname(fileURLToPath(import.meta.url));
10
+ export const MIN_SUMMARY_CHARS = 200;
11
+
12
+ async function handle(ctx) {
13
+ const root = ctx.projectRoot || process.cwd();
14
+ const p = ctx.payload || {};
15
+ const sw = await import(pathToFileURL(path.join(HOOKS_DIR, 'stop-failure-rescue.mjs')).href);
16
+ const len = typeof p.compact_summary === 'string' ? p.compact_summary.trim().length : 0;
17
+ const empty = len < MIN_SUMMARY_CHARS;
18
+ await sw.appendEvent(root, {
19
+ ts: new Date().toISOString(), type: 'COMPACT_SUCCEEDED', trigger: String(p.trigger || '').slice(0, 20),
20
+ summaryChars: len, ...(empty ? { cls: 11, name: 'empty-compaction-summary', flag: 'empty-summary' } : {}),
21
+ });
22
+ return NONE;
23
+ }
24
+
25
+ export async function runHook(ctx = {}) {
26
+ try {
27
+ const deadlineMs = Number(ctx.deadlineMs || process.env.HOOK_DEADLINE_MS) || 2000;
28
+ let timer;
29
+ const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve(NONE), Math.max(100, deadlineMs - 100)); timer.unref?.(); });
30
+ return await Promise.race([handle(ctx), timeout]).finally(() => clearTimeout(timer));
31
+ } catch {
32
+ return NONE;
33
+ }
34
+ }
@@ -702,12 +702,36 @@ async function evaluate({ rawInput, projectRoot, env }) {
702
702
  };
703
703
  // `env | grep -c X` / `printenv | grep -q X`: decided per segment — only an
704
704
  // env/printenv segment whose OWN pipe feeds a count-only grep is exempt.
705
+ const segmentWords = (segments, i) => (i < segments.length
706
+ ? splitShellWords(String(segments[i]).trim()).filter((t) => stripQuotes(t) !== '')
707
+ : []);
708
+ // `grep -o 'KEY=' .env`: with -o the output is only the matched text, and a
709
+ // LITERAL pattern can only ever print itself. No regexp/class form and no
710
+ // downstream "stripper" (`cut -s -d= -f1`, `sed -n 's/=.*//p'`) is exempt:
711
+ // continuation lines of a multi-line value (PEM/base64 body) contain `=` as
712
+ // padding, so any `…=` match or pre-`=` prefix can print value text
713
+ // (independent review of the 3.5.19 candidate, three rounds).
714
+ const isKeyNameOnlyGrep = (tokens, verbIdx) => {
715
+ const words = tokens.slice(verbIdx + 1).map((w) => stripQuotes(w));
716
+ let sawO = false;
717
+ let pattern = null;
718
+ // GNU grep permutes options after operands (`grep -o 'K=' .env -e '.*'`),
719
+ // so EVERY dash word is validated, not only those before the pattern.
720
+ for (const w of words) {
721
+ if (w.startsWith('-')) {
722
+ if (!/^-[oEFirnHhsIw]+$/.test(w)) return false;
723
+ if (w.includes('o')) sawO = true;
724
+ } else if (pattern === null) pattern = w;
725
+ }
726
+ return sawO && pattern !== null && /^\^?[A-Za-z0-9_]+=$/.test(pattern);
727
+ };
705
728
  const envPipedToCountGrep = (segments, seps, si) => {
706
729
  if (seps[si] !== '|' || si + 1 >= segments.length) return false;
707
- const next = splitShellWords(String(segments[si + 1]).trim()).filter((t) => stripQuotes(t) !== '');
730
+ const next = segmentWords(segments, si + 1);
708
731
  if (!next.length) return false;
709
732
  const nextHead = cleanPathToken(next[0]).replace(/^.*\//, '');
710
- return PATTERN_VERBS.has(nextHead) && isCountOnlyGrep(next, 0);
733
+ if (!PATTERN_VERBS.has(nextHead)) return false;
734
+ return isCountOnlyGrep(next, 0);
711
735
  };
712
736
 
713
737
  const scanBashShapes = (command, depth = 0) => {
@@ -737,9 +761,13 @@ async function evaluate({ rawInput, projectRoot, env }) {
737
761
  if (pi !== -1) skip.add(pi);
738
762
  for (const ri of regexpOperandIndexes(segTokens, 0)) skip.add(ri);
739
763
  }
764
+ // No head is exempt here: digest/metadata verbs (shasum/stat/wc) and
765
+ // `ssh -v -i KEY … 2>&1` all echo the filename, which an outer
766
+ // `cat $(…)` or a later `cat $L` then reads (3.5.19 review rounds 4-5).
740
767
  segTokens.forEach((rawTok, ti) => {
741
768
  if (skip.has(ti)) return;
742
- const cleaned = cleanPathToken(rawTok);
769
+ const files0 = /^--files0-from=(.+)$/.exec(stripQuotes(rawTok));
770
+ const cleaned = cleanPathToken(files0 ? files0[1] : rawTok);
743
771
  const kind = classifySecretFile(cleaned);
744
772
  if (!kind || pathAllowed(cleaned)) return;
745
773
  if (segHead === 'jq' && /^\.env\./.test(cleaned)) {
@@ -916,8 +944,12 @@ async function evaluate({ rawInput, projectRoot, env }) {
916
944
  const patternIdx = isPatternVerb ? patternOperandIndex(tokens, headIdx) : -1;
917
945
  const regexpIdx = isPatternVerb ? regexpOperandIndexes(tokens, headIdx) : new Set();
918
946
  const countOnly = isPatternVerb && isCountOnlyGrep(tokens, headIdx);
947
+ // Literal key-name output is exempt for dotenv files only:
948
+ // key/credential files stay blocked regardless.
949
+ const keyNamesOnly = !countOnly && isPatternVerb && isKeyNameOnlyGrep(tokens, headIdx);
919
950
  for (let k = headIdx + 1; k < tokens.length; k += 1) {
920
951
  if (k === patternIdx || regexpIdx.has(k) || countOnly) continue;
952
+ if (keyNamesOnly && classifySecretFile(cleanPathToken(tokens[k])) === 'dotenv/secret env file') continue;
921
953
  const token = tokens[k];
922
954
  // Attached pattern-file operand (`--file=.env`, `-f.env`) reads that
923
955
  // file: classify the value, not the whole flag word.
@@ -0,0 +1,34 @@
1
+ // shell-watch.mjs - UserPromptSubmit chain step (advisory, always code 0, fail-open).
2
+ // Emits an ACTION directive when hung shells / stalled background tasks exist.
3
+ // Claude Code: JSON hookSpecificOutput.additionalContext; omp: plain text (bridge appends it).
4
+ // Logic lives in ukit/runtime/shell-watch.mjs.
5
+ import fsp from 'node:fs/promises';
6
+ import path from 'node:path';
7
+ import { pathToFileURL, fileURLToPath } from 'node:url';
8
+
9
+ export const hookFailClosed = false;
10
+ const NONE = { code: 0, stdout: '', stderr: '' };
11
+ const MODULE_DIR = path.dirname(fileURLToPath(import.meta.url));
12
+
13
+ export async function runHook(ctx = {}) {
14
+ try {
15
+ const projectRoot = ctx.projectRoot || process.cwd();
16
+ let config = null;
17
+ try { config = JSON.parse(await fsp.readFile(path.join(projectRoot, '.ukit', 'storage', 'config.json'), 'utf8')); } catch { /* defaults */ }
18
+ const mod = await import(pathToFileURL(path.join(MODULE_DIR, '..', 'ukit', 'runtime', 'shell-watch.mjs')).href);
19
+ // Deadline contract: never outlive the chain slot (ctx.deadlineMs or HOOK_DEADLINE_MS).
20
+ const deadlineMs = Number(ctx.deadlineMs || process.env.HOOK_DEADLINE_MS) || 2000;
21
+ let timer;
22
+ const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve(''), Math.max(100, deadlineMs - 100)); timer.unref?.(); });
23
+ const text = await Promise.race([mod.runShellWatch({ projectRoot, config }), timeout]).finally(() => clearTimeout(timer));
24
+ if (!text) return NONE;
25
+ const env = ctx.env || process.env;
26
+ const omp = ctx.payload?.ukit_harness === 'omp' || env.UKIT_HARNESS === 'omp';
27
+ const stdout = omp
28
+ ? `${text}\n`
29
+ : `${JSON.stringify({ hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext: text } })}\n`;
30
+ return { code: 0, stdout, stderr: '' };
31
+ } catch {
32
+ return NONE;
33
+ }
34
+ }
@@ -0,0 +1,109 @@
1
+ // stop-failure-rescue.mjs - StopFailure chain step (detect + record only, always code 0, fail-open).
2
+ // Classifies the failure, appends a redacted event to .ukit/storage/rescue/events.jsonl (rotates at
3
+ // 1 MiB) and advances the recovery state machine. Never writes prompt text or touches transcripts.
4
+ import fsp from 'node:fs/promises';
5
+ import path from 'node:path';
6
+ import crypto from 'node:crypto';
7
+ import { pathToFileURL, fileURLToPath } from 'node:url';
8
+
9
+ export const hookFailClosed = false;
10
+ const NONE = { code: 0, stdout: '', stderr: '' };
11
+ const MODULE_DIR = path.dirname(fileURLToPath(import.meta.url));
12
+ const RESCUE_DIR = path.join(MODULE_DIR, '..', 'ukit', 'runtime', 'rescue');
13
+ export const EVENTS_MAX_BYTES = 1024 * 1024;
14
+
15
+ const load = (name) => import(pathToFileURL(path.join(RESCUE_DIR, name)).href);
16
+
17
+ export async function appendEvent(root, event) {
18
+ const dir = path.join(root, '.ukit', 'storage', 'rescue');
19
+ const file = path.join(dir, 'events.jsonl');
20
+ await fsp.mkdir(dir, { recursive: true });
21
+ try {
22
+ const st = await fsp.stat(file);
23
+ if (st.size >= EVENTS_MAX_BYTES) await fsp.rename(file, `${file}.1`);
24
+ } catch { /* no file yet */ }
25
+ await fsp.appendFile(file, `${JSON.stringify(event)}\n`);
26
+ }
27
+
28
+ async function handle(ctx) {
29
+ const root = ctx.projectRoot || process.cwd();
30
+ const p = ctx.payload || {};
31
+ const cf = await load('classify-failure.mjs');
32
+ const rs = await load('recovery-state.mjs');
33
+ const input = { error: p.error, error_details: p.error_details, message: p.last_assistant_message ?? p.message, usage: p.usage };
34
+ const c = cf.classifyFailure(input);
35
+ const fp = cf.fingerprint(input);
36
+ // eventId: stable for an identical payload within the same session+minute -> duplicate hook events dedupe.
37
+ const sid = String(p.session_id || ctx.sessionId || '').slice(0, 64);
38
+ const eventId = crypto.createHash('sha1').update(`${sid}|${fp}|${p.turn_id ?? ''}|${Math.floor(Date.now() / 60000)}`).digest('hex').slice(0, 24);
39
+ const missionId = p.mission_id || undefined;
40
+
41
+ const cur = await rs.readState({ root, missionId });
42
+ let outcome;
43
+ if (c.action === 'block') {
44
+ outcome = await rs.transition({ root, missionId, from: cur.state, to: 'BLOCKED', eventId, reason: c.name, fingerprint: fp, failure: true });
45
+ } else if (c.action === 'none') {
46
+ outcome = { ok: true, applied: false };
47
+ } else if (cur.state === 'COMPACT_FAILED') {
48
+ outcome = await rs.recordFailure({ root, missionId, fingerprint: fp, eventId });
49
+ if (outcome.ok && outcome.applied && !outcome.open && c.action !== 'wait') {
50
+ outcome = await rs.transition({ root, missionId, from: 'COMPACT_FAILED', to: 'RECOVERING', eventId: `${eventId}:r`, reason: c.name, fingerprint: fp });
51
+ }
52
+ } else if (cur.state === 'HEALTHY' || cur.state === 'PRESSURE' || cur.state === 'CHECKPOINTED' || cur.state === 'COMPACTING' || cur.state === 'RECOVERING' || cur.state === 'ROLLOVER_PENDING') {
53
+ outcome = await rs.transition({ root, missionId, from: cur.state, to: 'COMPACT_FAILED', eventId, reason: c.name, fingerprint: fp, failure: true });
54
+ } else {
55
+ outcome = { ok: true, applied: false };
56
+ }
57
+
58
+ const redacted = cf.redact(`${typeof p.error_details === 'string' ? p.error_details : ''}`).slice(0, 200);
59
+ await appendEvent(root, {
60
+ ts: new Date().toISOString(), type: 'STOP_FAILURE', eventId, error: String(p.error || '').slice(0, 40),
61
+ cls: c.cls, name: c.name, action: c.action, retryable: c.retryable, flags: c.flags, fingerprint: fp,
62
+ byteRatio: Number(c.byteRatio.toFixed(3)), detail: redacted, transition: outcome?.ok ? (outcome.state || null) : outcome?.code || null,
63
+ });
64
+
65
+ try {
66
+ const ev = outcome?.ok && outcome.applied ? { COMPACT_FAILED: 'COMPACT_FAILED', RECOVERING: 'RECOVERY_STARTED' }[outcome.state] : null;
67
+ if (ev) await (await load('rollover.mjs')).emitRescueEvent(root, ev, { eventId, cls: c.cls, name: c.name });
68
+ } catch { /* event is best-effort */ }
69
+
70
+ // WP-R3: rollover/reconstruct-class failures also persist an offline restoration bundle (fail-open).
71
+ let rolloverNotice = '';
72
+ if (c.action === 'rollover' || c.action === 'reconstruct') {
73
+ try {
74
+ const rc = await load('reconstruct.mjs');
75
+ const bd = await load('bundle.mjs');
76
+ const recon = await rc.reconstructMission({ projectRoot: root, transcriptPath: p.transcript_path, sessionId: sid || undefined });
77
+ const bundle = bd.buildBundle(recon, { maxChars: 6000 });
78
+ const w = await bd.writeBundle(root, bundle);
79
+ await appendEvent(root, { ts: new Date().toISOString(), type: 'RESCUE_BUNDLE_WRITTEN', eventId, sha256: bundle.sha256.slice(0, 16), chars: bundle.text.length, reconcile: bundle.reconcile, file: path.basename(w.bundlePath) });
80
+ let ro = null;
81
+ try { ro = await load('rollover.mjs'); await ro.emitRescueEvent(root, 'OFFLINE_CONTEXT_REBUILT', { eventId, sha256: bundle.sha256.slice(0, 16), chars: bundle.text.length, reconcile: bundle.reconcile }); } catch { /* event is best-effort */ }
82
+ if (ro && c.action === 'rollover') {
83
+ let config = {};
84
+ try { config = JSON.parse(await fsp.readFile(path.join(root, '.ukit', 'storage', 'config.json'), 'utf8')); } catch { /* defaults */ }
85
+ const lease = await (await load('lease.mjs')).readLease(root).catch(() => null);
86
+ const state = await rs.readState({ root, missionId });
87
+ const r = await ro.maybeRollover({ projectRoot: root, config, state, lease, autonomy: config?.autonomy?.level, failure: c, fingerprint: fp, ownerStop: recon.ownerStop === true });
88
+ rolloverNotice = typeof r?.notice === 'string' ? r.notice.split('\n')[0] : '';
89
+ }
90
+ } catch { /* bundle is best-effort */ }
91
+ }
92
+
93
+ const rollover = c.action === 'rollover';
94
+ const stderr = rollover
95
+ ? `UKit rescue: context overflow detected (class ${c.cls}: ${c.name}). Your work is preserved; run \`ukit rescue\` or start a fresh session and UKit will reconstruct state on start.\n${rolloverNotice ? `${rolloverNotice}\n` : ''}`
96
+ : '';
97
+ return { code: 0, stdout: '', stderr };
98
+ }
99
+
100
+ export async function runHook(ctx = {}) {
101
+ try {
102
+ const deadlineMs = Number(ctx.deadlineMs || process.env.HOOK_DEADLINE_MS) || 2000;
103
+ let timer;
104
+ const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve(NONE), Math.max(100, deadlineMs - 100)); timer.unref?.(); });
105
+ return await Promise.race([handle(ctx), timeout]).finally(() => clearTimeout(timer));
106
+ } catch {
107
+ return NONE;
108
+ }
109
+ }
@@ -162,6 +162,16 @@
162
162
  }
163
163
  ]
164
164
  },
165
+ {
166
+ "matcher": "TodoWrite|TaskCreate|TaskUpdate",
167
+ "hooks": [
168
+ {
169
+ "type": "command",
170
+ "command": "node \"$CLAUDE_PROJECT_DIR/.claude/ukit/runtime/hook-chain-runner.mjs\" --emit-verdict - \"$CLAUDE_PROJECT_DIR/.claude/hooks/mission-capture.mjs\":8",
171
+ "timeout": 18
172
+ }
173
+ ]
174
+ },
165
175
  {
166
176
  "matcher": "Bash",
167
177
  "hooks": [
@@ -202,8 +212,8 @@
202
212
  "hooks": [
203
213
  {
204
214
  "type": "command",
205
- "command": "node \"$CLAUDE_PROJECT_DIR/.claude/ukit/runtime/hook-chain-runner.mjs\" --emit-verdict - \"$CLAUDE_PROJECT_DIR/.claude/hooks/sensitive-data-guard.mjs\":8 \"$CLAUDE_PROJECT_DIR/.claude/hooks/record-execution.mjs\":8 \"$CLAUDE_PROJECT_DIR/.claude/hooks/skill-router.sh\":20 \"$CLAUDE_PROJECT_DIR/.claude/hooks/vision-router.sh\":12 \"$CLAUDE_PROJECT_DIR/.claude/hooks/context-window-guard.sh\":10",
206
- "timeout": 68
215
+ "command": "node \"$CLAUDE_PROJECT_DIR/.claude/ukit/runtime/hook-chain-runner.mjs\" --emit-verdict - \"$CLAUDE_PROJECT_DIR/.claude/hooks/sensitive-data-guard.mjs\":8 \"$CLAUDE_PROJECT_DIR/.claude/hooks/record-execution.mjs\":8 \"$CLAUDE_PROJECT_DIR/.claude/hooks/skill-router.sh\":20 \"$CLAUDE_PROJECT_DIR/.claude/hooks/vision-router.sh\":12 \"$CLAUDE_PROJECT_DIR/.claude/hooks/context-window-guard.sh\":10 \"$CLAUDE_PROJECT_DIR/.claude/hooks/mission-capture.mjs\":8 \"$CLAUDE_PROJECT_DIR/.claude/hooks/shell-watch.mjs\":8",
216
+ "timeout": 84
207
217
  }
208
218
  ]
209
219
  }
@@ -219,6 +229,28 @@
219
229
  ]
220
230
  }
221
231
  ],
232
+ "StopFailure": [
233
+ {
234
+ "hooks": [
235
+ {
236
+ "type": "command",
237
+ "command": "node \"$CLAUDE_PROJECT_DIR/.claude/ukit/runtime/hook-chain-runner.mjs\" --emit-verdict - \"$CLAUDE_PROJECT_DIR/.claude/hooks/stop-failure-rescue.mjs\":8",
238
+ "timeout": 18
239
+ }
240
+ ]
241
+ }
242
+ ],
243
+ "PostCompact": [
244
+ {
245
+ "hooks": [
246
+ {
247
+ "type": "command",
248
+ "command": "node \"$CLAUDE_PROJECT_DIR/.claude/ukit/runtime/hook-chain-runner.mjs\" --emit-verdict - \"$CLAUDE_PROJECT_DIR/.claude/hooks/post-compact-observe.mjs\":8",
249
+ "timeout": 18
250
+ }
251
+ ]
252
+ }
253
+ ],
222
254
  "PreCompact": [
223
255
  {
224
256
  "hooks": [
@@ -235,8 +267,8 @@
235
267
  "hooks": [
236
268
  {
237
269
  "type": "command",
238
- "command": "node \"$CLAUDE_PROJECT_DIR/.claude/ukit/runtime/hook-chain-runner.mjs\" --emit-verdict - \"$CLAUDE_PROJECT_DIR/.claude/hooks/project-important.sh\":8 \"$CLAUDE_PROJECT_DIR/.claude/hooks/auto-prune-bash.sh\":12 \"$CLAUDE_PROJECT_DIR/.claude/hooks/reset-compact-pressure.sh\":12 \"$CLAUDE_PROJECT_DIR/.claude/hooks/handoff-resume.sh\":8 \"$CLAUDE_PROJECT_DIR/.claude/hooks/observability-emit.mjs\":8 \"$CLAUDE_PROJECT_DIR/.claude/hooks/session-episode-start.mjs\":8",
239
- "timeout": 70
270
+ "command": "node \"$CLAUDE_PROJECT_DIR/.claude/ukit/runtime/hook-chain-runner.mjs\" --emit-verdict - \"$CLAUDE_PROJECT_DIR/.claude/hooks/project-important.sh\":8 \"$CLAUDE_PROJECT_DIR/.claude/hooks/auto-prune-bash.sh\":12 \"$CLAUDE_PROJECT_DIR/.claude/hooks/reset-compact-pressure.sh\":12 \"$CLAUDE_PROJECT_DIR/.claude/hooks/handoff-resume.sh\":8 \"$CLAUDE_PROJECT_DIR/.claude/hooks/reinject-context.sh\":8 \"$CLAUDE_PROJECT_DIR/.claude/hooks/observability-emit.mjs\":8 \"$CLAUDE_PROJECT_DIR/.claude/hooks/session-episode-start.mjs\":8",
271
+ "timeout": 74
240
272
  }
241
273
  ]
242
274
  }
@@ -16,6 +16,7 @@ import { spawnSync } from 'node:child_process';
16
16
  const toPosix = (p) => String(p).split(path.sep).join('/').replace(/\\/g, '/');
17
17
  const rel = (root, p) => toPosix(path.isAbsolute(p) ? path.relative(root, p) : p);
18
18
  const readText = (f) => { try { return fs.readFileSync(f, 'utf8'); } catch { return null; } };
19
+ const workersOf = (ctx) => (Number.isInteger(ctx.workers) && ctx.workers > 1 ? ctx.workers : 1);
19
20
  const tail = (s, n = 1500) => String(s ?? '').slice(-n);
20
21
 
21
22
  function run(cmd, args, { cwd, env, timeoutMs = 10 * 60 * 1000 } = {}) {
@@ -170,9 +171,13 @@ export function parseJestLikeReport(root, files, json) {
170
171
  const fileErrors = [];
171
172
  const map = { passed: 'passed', failed: 'failed', pending: 'skipped', skipped: 'skipped', todo: 'skipped', disabled: 'skipped' };
172
173
  const seenFiles = new Set();
174
+ // Per-file wall time from the report (planning hint only: it balances batches, never decides a verdict).
175
+ const fileMs = {};
173
176
  for (const suite of json?.testResults ?? []) {
174
177
  const file = rel(root, suite.name);
175
178
  seenFiles.add(file);
179
+ const ms = Number(suite.endTime) - Number(suite.startTime);
180
+ if (Number.isFinite(ms) && ms >= 0) fileMs[file] = Math.round(ms);
176
181
  const asserts = suite.assertionResults ?? [];
177
182
  for (const a of asserts) {
178
183
  const id = `${file} > ${[...(a.ancestorTitles ?? []), a.title].join(' > ')}`;
@@ -183,7 +188,7 @@ export function parseJestLikeReport(root, files, json) {
183
188
  }
184
189
  }
185
190
  for (const f of files) if (!seenFiles.has(f)) fileErrors.push({ file: f, message: 'file missing from the framework report' });
186
- return { results, fileErrors };
191
+ return { results, fileErrors, fileMs };
187
192
  }
188
193
 
189
194
  const vitest = {
@@ -208,7 +213,7 @@ const vitest = {
208
213
  },
209
214
  batchCommand(ctx, files, report) {
210
215
  const bin = nodeBin(ctx, 'vitest', 'vitest.mjs');
211
- return { cmd: bin.cmd, args: [...bin.pre, 'run', ...files, '--reporter=json', `--outputFile=${report}`, '--no-file-parallelism', '--passWithNoTests', ...ctx.extra], env: {} };
216
+ return { cmd: bin.cmd, args: [...bin.pre, 'run', ...files, '--reporter=json', `--outputFile=${report}`, ...(workersOf(ctx) > 1 ? [`--maxWorkers=${workersOf(ctx)}`, '--minWorkers=1'] : ['--no-file-parallelism']), '--passWithNoTests', ...ctx.extra], env: {} };
212
217
  },
213
218
  parseReport(ctx, files, report) {
214
219
  const text = readText(report);
@@ -237,7 +242,7 @@ const jest = {
237
242
  },
238
243
  batchCommand(ctx, files, report) {
239
244
  const bin = nodeBin(ctx, 'jest', path.join('bin', 'jest.js'));
240
- return { cmd: bin.cmd, args: [...bin.pre, '--runInBand', '--json', `--outputFile=${report}`, '--passWithNoTests', ...ctx.extra, '--runTestsByPath', ...files], env: {} };
245
+ return { cmd: bin.cmd, args: [...bin.pre, ...(workersOf(ctx) > 1 ? [`--maxWorkers=${workersOf(ctx)}`] : ['--runInBand']), '--json', `--outputFile=${report}`, '--passWithNoTests', ...ctx.extra, '--runTestsByPath', ...files], env: {} };
241
246
  },
242
247
  parseReport: vitest.parseReport,
243
248
  leakCommand(ctx, file, samples) {