@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
package/CHANGELOG.md CHANGED
@@ -2,6 +2,38 @@
2
2
 
3
3
  All notable changes to UKit are documented here.
4
4
 
5
+ ## 3.5.19 - 2026-11-21
6
+
7
+ Field-telemetry fix round 5 and faster batched test runs.
8
+
9
+ - **Secret guard false positives (R5-1..R5-4).**
10
+ - `grep -o 'KEY=' .env` (a literal key name, optionally `^`-anchored) is allowed: it can only print that literal. Every grep option is validated, including ones after the pattern (`-e`/`-f`/`-P`).
11
+ - Pipes that try to strip values (`| cut -d= -f1`, `| sed 's/=.*//'`, with or without `-s`/`-n …p`) and regexp classes (`grep -oE '^[A-Z_]*='`) stay blocked. Independent review showed continuation lines of a multi-line value (PEM/base64) carry `=` padding, so these forms can print value text.
12
+ - Inside `$()` nothing new is exempt: digest/metadata verbs (`shasum`, `stat`, `wc`) and `ssh -i KEY` stay blocked on secret files because they echo the filename (`ssh -v … 2>&1`), which an outer `cat $(…)` would read. `wc --files0-from=FILE` is now classified too.
13
+ - Anything that could still print a value stays blocked: an intermediate `tee`, other sed scripts, `cut -f2`, and name producers such as `cat $(echo .env)`.
14
+ - **Loop-breaker (R5-5).** A commit (git HEAD change) now counts as progress. The refused-stop count and its grammar are correct ("1 consecutive time").
15
+ - **Shell watch (R5-8).** Never reports or kills a shell owned by another live Claude Code, Codex or omp session.
16
+ - **Field audit tools (R5-6, R5-7).**
17
+ - `field-telemetry --json` no longer truncates large output on a pipe.
18
+ - `--sample-chars N` controls the sample length for field-telemetry and field-replay.
19
+ - **Release core batches (R5-9).** An empty batch or a missing listed file fails before vitest starts.
20
+ - **Faster full-suite batches.** `test-batches.mjs` gains a `workers` setting (`--workers N` or `.ukit/storage/test-batches.json`). The default of 1 keeps the old serial behaviour, so projects that leave it unset are unaffected.
21
+ - With N>1, each fresh batch process runs up to N files at once (`vitest --maxWorkers`, `jest --maxWorkers`). Batches stay sequential, and every file still runs.
22
+ - Case and file budgets scale per worker, and memory is predicted from the top N peaks.
23
+ - Per-file durations from every report feed longest-first balancing, so one slow file no longer leaves a long tail.
24
+ - Maintainers set `workers` locally (this file is not shipped); the 30.0 → 16.8 min figure used 3 workers.
25
+ - No test was removed or skipped, and the verdict rules are unchanged.
26
+
27
+ ## 3.5.18 - 2026-11-21
28
+
29
+ - **Auto-compaction fix:** context budget sized to the real ~200k route window (hard cap 185k, host auto-compact 148k; was 250k/235k/188k). The context guard measures from the API-reported usage of the newest assistant turn and ignores transcript-only hook attachments (previously ~3x overcount). The over-cap advisory no longer says "keep working"; it says to stop stacking new work, defer to disk, and add one trailing /compact note.
30
+ - **Post-compaction resume:** PreCompact now writes the resume intent (goal, contract, unmet evidence, next step, git). SessionStart(compact) re-injects reinject-context plus a POST-COMPACTION RESUME block (Claude Code; omp via session_compact, once). Same-session restore ignores the old 30-minute TTL (24h for cross-session). Handoff/guard texts no longer end runs by asking for /compact or a fresh session.
31
+ - **Shell watch:** a new UserPromptSubmit step (Claude Code + omp; instruction rule for Codex) flags hung shells and stalled background tasks on every prompt with an ACTION directive to kill them and finish the work. It auto-kills only self-matching `until/while … pgrep -f` loops (logged). Config: `shellWatch`.
32
+ - **Owner context tiers, always auto-compact:** UKit-owned, model-independent tiers `compact.bestTokens/okTokens/mandatoryTokens/stopTokens` (100k/150k/200k/250k; legacy `tokenThreshold`/`hardCapTokens` map to best/stop). Claude Code auto-compact window 180k, omp `compaction.thresholdTokens` 170k, optional `compact.gatewayLimitTokens` caps the window below a gateway's real limit. At ≥250k only persist writes (docs/STATUS/WORKLOG/TASKS, AI_HANDOFF, .ukit) are allowed; below that the guard is advisory. Never asks the user to /compact.
33
+ - **Mission continuity (advisor #1):** durable, redacted prompt journal and mission task graph (`runtime/mission/`): requirements, tasks, ACs, supersede/extend relations, drift detection, working memory, typed checkpoints (last 5), selective recall (index → detail → raw) and a ≤6000-char restore with branch/HEAD reconcile and per-session dedupe. Wired on UserPromptSubmit, PostToolUse(TodoWrite/TaskCreate/TaskUpdate), PreCompact and SessionStart(compact|resume) for Claude Code and omp; Codex uses `ukit mission capture|restore|recall|status|detail|checkpoint`. A mission gate in the Stop coordinator continues only while READY or unverified work remains (only verification evidence closes an AC; owner STOP wins; bounded repeats; fail-open). Pressure bands 30/40/50/60% are advisory only.
34
+ - **Emergency context rescue (advisor #2):** StopFailure and PostCompact listeners classify API failures (incl. gateway-rewritten context-limit 400s), keep a fenced recovery state with breaker, rebuild the mission offline from disk (no model call; only VERIFIED counts as done) into a ≤6000-char bundle re-injected once on the next session, and — only for free-run/vibecode/unattended — start one detached `claude -p` rollover per epoch. omp: `ctx.compact()` once on failed auto-compaction (feature-detected). `ukit rescue status|rebuild|resume|reset-breaker`. Aggregate per-prompt hook injection capped at 4000 chars (ACTION/STOP/BLOCKED/WAITING ON YOU/PROJECT_IMPORTANT never trimmed). 13 observability events.
35
+ - **Shell watch:** an interrupted subagent is no longer reported as a hung task.
36
+
5
37
  ## 3.5.17 - 2026-11-21
6
38
 
7
39
  - **Full test suites run in memory-safe batches.** A new always-on rule (TEST-01) tells the agent to run the whole suite, or any run beyond a few targeted files, with `node .claude/ukit/index/test-batches.mjs run`: sequential fresh-process batches, every file runs, and only a `PASS` verdict counts as green. Targeted 1-3 file runs still use the bare runner. Applies to Claude Code, Codex and omp.
@@ -1679,6 +1679,54 @@ items:
1679
1679
  packs:
1680
1680
  - core
1681
1681
 
1682
+ - id: hook-mission-capture-module
1683
+ type: hook
1684
+ sourceTemplate: .claude/hooks/mission-capture.mjs
1685
+ targetPath: .claude/hooks/mission-capture.mjs
1686
+ requires:
1687
+ - ukit-runtime-scripts
1688
+ mergeStrategy: overwrite_with_backup
1689
+ variables: []
1690
+ enabledByDefault: true
1691
+ packs:
1692
+ - core
1693
+
1694
+ - id: hook-shell-watch-module
1695
+ type: hook
1696
+ sourceTemplate: .claude/hooks/shell-watch.mjs
1697
+ targetPath: .claude/hooks/shell-watch.mjs
1698
+ requires:
1699
+ - ukit-runtime-scripts
1700
+ mergeStrategy: overwrite_with_backup
1701
+ variables: []
1702
+ enabledByDefault: true
1703
+ packs:
1704
+ - core
1705
+
1706
+ - id: hook-stop-failure-rescue-module
1707
+ type: hook
1708
+ sourceTemplate: .claude/hooks/stop-failure-rescue.mjs
1709
+ targetPath: .claude/hooks/stop-failure-rescue.mjs
1710
+ requires:
1711
+ - ukit-runtime-scripts
1712
+ mergeStrategy: overwrite_with_backup
1713
+ variables: []
1714
+ enabledByDefault: true
1715
+ packs:
1716
+ - core
1717
+
1718
+ - id: hook-post-compact-observe-module
1719
+ type: hook
1720
+ sourceTemplate: .claude/hooks/post-compact-observe.mjs
1721
+ targetPath: .claude/hooks/post-compact-observe.mjs
1722
+ requires:
1723
+ - ukit-runtime-scripts
1724
+ mergeStrategy: overwrite_with_backup
1725
+ variables: []
1726
+ enabledByDefault: true
1727
+ packs:
1728
+ - core
1729
+
1682
1730
  - id: hook-session-episode
1683
1731
  type: hook
1684
1732
  sourceTemplate: .claude/hooks/session-episode.sh
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ngockhoale/ukit",
3
- "version": "3.5.17",
3
+ "version": "3.5.19",
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",
@@ -10,7 +10,7 @@
10
10
  * sample commands per class (redacted + truncated; values never printed).
11
11
  *
12
12
  * Usage: node scripts/audit/field-replay.mjs [--projects-dir DIR] [--match SUBSTR]...
13
- * [--since YYYY-MM-DD] [--limit N] [--hook sensitive] [--mode inproc|cli] [--json]
13
+ * [--since YYYY-MM-DD] [--limit N] [--sample-chars N] [--hook sensitive] [--mode inproc|cli] [--json]
14
14
  *
15
15
  * Hooks are registered in HOOKS below; add block-dangerous / execution-ledger
16
16
  * (PostToolUse) by adding an entry with its own payload builder + verdict parser.
@@ -108,7 +108,7 @@ function runCli(hook, payload, projectRoot, tmpDir, idx) {
108
108
  }
109
109
 
110
110
  // --- aggregation -------------------------------------------------------------------
111
- export function classifyResults(results, hook, { samples = 40 } = {}) {
111
+ export function classifyResults(results, hook, { samples = 40, sampleChars = 200 } = {}) {
112
112
  const classes = new Map();
113
113
  let blocked = 0;
114
114
  for (const { command, verdict } of results) {
@@ -120,7 +120,7 @@ export function classifyResults(results, hook, { samples = 40 } = {}) {
120
120
  let c = classes.get(k);
121
121
  if (!c) classes.set(k, (c = { cls: k, count: 0, samples: [] }));
122
122
  c.count += 1;
123
- if (c.samples.length < samples) c.samples.push(truncate(redact(command), 200));
123
+ if (c.samples.length < samples) c.samples.push(truncate(redact(command), sampleChars));
124
124
  }
125
125
  }
126
126
  return { blocked, classes: [...classes.values()].sort((a, b) => b.count - a.count || a.cls.localeCompare(b.cls)) };
@@ -129,7 +129,7 @@ export function classifyResults(results, hook, { samples = 40 } = {}) {
129
129
  export async function main(argv = process.argv.slice(2)) {
130
130
  const opts = parseArgs(argv);
131
131
  if (opts.help) {
132
- process.stdout.write('Usage: field-replay.mjs [--projects-dir DIR] [--match SUBSTR]... [--since YYYY-MM-DD] [--limit N] [--hook sensitive] [--mode inproc|cli] [--json]\n');
132
+ process.stdout.write('Usage: field-replay.mjs [--projects-dir DIR] [--match SUBSTR]... [--since YYYY-MM-DD] [--limit N] [--sample-chars N] [--hook sensitive] [--mode inproc|cli] [--json]\n');
133
133
  return 0;
134
134
  }
135
135
  const hook = HOOKS[opts.hook];
@@ -161,7 +161,7 @@ export async function main(argv = process.argv.slice(2)) {
161
161
  await fsp.rm(projectRoot, { recursive: true, force: true });
162
162
  await fsp.rm(tmpDir, { recursive: true, force: true });
163
163
  }
164
- const rep = classifyResults(results, hook);
164
+ const rep = classifyResults(results, hook, { sampleChars: opts.sampleChars });
165
165
  const meta = { hook: opts.hook, mode: opts.mode, files, since: opts.since, replayed: commands.length, blocked: rep.blocked, errors, ms: Date.now() - t0 };
166
166
  if (opts.json) {
167
167
  process.stdout.write(`${JSON.stringify({ meta, classes: rep.classes }, null, 2)}\n`);
@@ -185,10 +185,10 @@ const isDirect = (() => {
185
185
  })();
186
186
  if (isDirect) {
187
187
  main().then(
188
- (code) => process.exit(code),
188
+ (code) => { process.exitCode = code; },
189
189
  (err) => {
190
190
  process.stderr.write(`field-replay: ${err && err.message ? err.message : err}\n`);
191
- process.exit(1);
191
+ process.exitCode = 1;
192
192
  },
193
193
  );
194
194
  }
@@ -236,7 +236,7 @@ export function aggregate(acc, { top = 15, cmdTop = 20 } = {}) {
236
236
 
237
237
  // --- file discovery ---------------------------------------------------------------
238
238
  export function parseArgs(argv) {
239
- const opts = { projectsDir: path.join(os.homedir(), '.claude', 'projects'), match: [], since: null, json: false, limit: 20000, hook: 'sensitive', mode: 'inproc' };
239
+ const opts = { projectsDir: path.join(os.homedir(), '.claude', 'projects'), match: [], since: null, json: false, limit: 20000, hook: 'sensitive', mode: 'inproc', sampleChars: 200 };
240
240
  for (let i = 0; i < argv.length; i += 1) {
241
241
  const a = argv[i];
242
242
  const next = () => argv[++i];
@@ -245,6 +245,7 @@ export function parseArgs(argv) {
245
245
  else if (a === '--since') opts.since = next();
246
246
  else if (a === '--json') opts.json = true;
247
247
  else if (a === '--limit') opts.limit = Number.parseInt(next(), 10) || opts.limit;
248
+ else if (a === '--sample-chars') opts.sampleChars = Math.max(1, Number.parseInt(next(), 10) || 200);
248
249
  else if (a === '--hook') opts.hook = next();
249
250
  else if (a === '--mode') opts.mode = next();
250
251
  else if (a === '--help' || a === '-h') opts.help = true;
@@ -332,10 +333,10 @@ const isDirect = (() => {
332
333
  })();
333
334
  if (isDirect) {
334
335
  main().then(
335
- (code) => process.exit(code),
336
+ (code) => { process.exitCode = code; },
336
337
  (err) => {
337
338
  process.stderr.write(`field-telemetry: ${err && err.message ? err.message : err}\n`);
338
- process.exit(1);
339
+ process.exitCode = 1;
339
340
  },
340
341
  );
341
342
  }
@@ -30,6 +30,15 @@ export function partition(files, count, cwd = process.cwd()) {
30
30
  return batches;
31
31
  }
32
32
 
33
+ // Guard: an empty batch would make `vitest run` receive no file filter and run the WHOLE suite;
34
+ // a listed path missing on disk would match nothing (vitest filters are substrings) and could
35
+ // silently run 0 tests. Both must fail the batch rather than pass or over-run.
36
+ export function assertBatchRunnable(batch, cwd = process.cwd()) {
37
+ if (!Array.isArray(batch) || batch.length === 0) throw new Error('core batch is empty (no file filter would run the entire suite)');
38
+ const missing = batch.filter((f) => { try { return !statSync(path.join(cwd, f)).isFile(); } catch { return true; } });
39
+ if (missing.length) throw new Error(`core batch lists file(s) not found on disk (would run 0 tests): ${missing.join(', ')}`);
40
+ }
41
+
33
42
  if (import.meta.url === `file://${process.argv[1]}`) {
34
43
  const index = Number(process.argv[2]);
35
44
  const count = Number(process.argv[3]);
@@ -40,6 +49,7 @@ if (import.meta.url === `file://${process.argv[1]}`) {
40
49
  const files = listCoreFiles();
41
50
  if (files.length === 0) { console.error('[core-batch] no test files listed'); process.exit(1); }
42
51
  const batch = partition(files, count)[index - 1];
52
+ try { assertBatchRunnable(batch); } catch (e) { console.error(`[core-batch] ${e.message}`); process.exit(1); }
43
53
  console.log(`[core-batch] ${index}/${count}: ${batch.length} of ${files.length} files`);
44
54
  const child = spawn('yarn', ['vitest', 'run', ...batch, '--bail', '5'], { stdio: 'inherit' });
45
55
  // Backstop watchdog (same budget as the verifier's per-step deadline; the verifier kills the whole tree first).
@@ -0,0 +1,102 @@
1
+ import fsp from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { pathToFileURL, fileURLToPath } from 'node:url';
4
+
5
+ // `ukit mission [status|recall <q>|detail <id>|restore|checkpoint|capture "<prompt>"]` - also the Codex path (no hooks).
6
+ // Read-only except capture/checkpoint. Output goes through the mission redactor; secrets are never printed.
7
+ const PKG_MISSION = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../template_project/.claude/ukit/runtime/mission');
8
+ const SESSION_KEY = 'codex';
9
+
10
+ async function load(projectRoot, name) {
11
+ for (const dir of [path.join(projectRoot, '.claude', 'ukit', 'runtime', 'mission'), PKG_MISSION]) {
12
+ try {
13
+ await fsp.access(path.join(dir, name));
14
+ return await import(pathToFileURL(path.join(dir, name)).href);
15
+ } catch { /* try next */ }
16
+ }
17
+ return null;
18
+ }
19
+
20
+ export function printMissionHelp(log = console.log) {
21
+ log('Usage: ukit mission [status|recall <query>|detail <id>|restore|checkpoint|capture "<prompt>"]');
22
+ log(' status active mission, requirement/task/AC counts, completion');
23
+ log(' recall <q> search mission memory (progressive disclosure index)');
24
+ log(' detail <id> show one requirement/task/AC/prompt/decision');
25
+ log(' restore print the verified restoration text');
26
+ log(' checkpoint write a semantic checkpoint now');
27
+ log(' capture "<prompt>" journal a prompt (Codex has no hooks)');
28
+ }
29
+
30
+ export async function runMission({ projectRoot = process.cwd(), argv = [], log = console.log, sessionKey = SESSION_KEY } = {}) {
31
+ const sub = (argv[0] ?? 'status').toLowerCase();
32
+ if (['help', '--help', '-h'].includes(sub)) { printMissionHelp(log); return; }
33
+ const fail = (msg) => { log(`[UKit] mission: ${msg}`); process.exitCode = 1; };
34
+ try {
35
+ const [store, graphMod, redact] = await Promise.all([load(projectRoot, 'store.mjs'), load(projectRoot, 'graph.mjs'), load(projectRoot, 'redact.mjs')]);
36
+ if (!store || !graphMod || !redact) { fail('runtime not installed (run `ukit install`).'); return; }
37
+ const safe = (t) => redact.redactText(String(t ?? '')).text;
38
+ const active = store.readActive(projectRoot);
39
+ const missionId = active?.sessions?.[sessionKey]?.missionId || active?.activeMissionId || null;
40
+ const git = async () => {
41
+ try {
42
+ const { execFileSync } = await import('node:child_process');
43
+ const run = (a) => { try { return execFileSync('git', a, { cwd: projectRoot, encoding: 'utf8', timeout: 700, stdio: ['ignore', 'pipe', 'ignore'] }).trim(); } catch { return null; } };
44
+ return { head: run(['rev-parse', 'HEAD']), branch: run(['rev-parse', '--abbrev-ref', 'HEAD']), dirty: false, repoRoot: projectRoot };
45
+ } catch { return {}; }
46
+ };
47
+
48
+ if (sub === 'capture') {
49
+ const text = argv.slice(1).join(' ').trim();
50
+ if (!text) { fail('capture needs a prompt: ukit mission capture "<prompt>"'); return; }
51
+ const hooks = await load(projectRoot, 'hooks.mjs');
52
+ if (!hooks) { fail('hooks runtime unavailable.'); return; }
53
+ const drift = await hooks.captureStep({ projectRoot, payload: { prompt: text, session_id: sessionKey, ukit_harness: 'codex' } });
54
+ log('[UKit] mission: prompt captured.');
55
+ if (drift) log(safe(drift));
56
+ return;
57
+ }
58
+
59
+ if (!missionId) { log('[UKit] mission: none active (nothing captured yet).'); return; }
60
+
61
+ if (sub === 'status') {
62
+ const g = await graphMod.loadGraph({ projectRoot, missionId });
63
+ const s = g.state;
64
+ const c = g.isComplete();
65
+ const driftMod = await load(projectRoot, 'drift.mjs');
66
+ const drift = driftMod ? driftMod.detectDrift(g).filter((f) => f.severity === 'warn') : [];
67
+ log(`[UKit] mission ${missionId}: ${Object.keys(s.reqs).length} requirement(s), ${Object.keys(s.tasks).length} task(s), ${Object.keys(s.acs).length} AC(s)`);
68
+ log(`[UKit] mission complete: ${c.complete ? 'yes (all ACs verified)' : `no (unverified: ${c.missing.slice(0, 5).join(', ')})`}`);
69
+ log(`[UKit] mission ready: ${g.readySet().slice(0, 3).map((t) => `${t.id} ${safe(t.title).slice(0, 60)}`).join('; ') || 'none'}`);
70
+ log(`[UKit] mission drift: ${drift.length ? drift.slice(0, 3).map((f) => `${f.code} ${f.ref}`).join(', ') : 'none'}`);
71
+ return;
72
+ }
73
+ if (sub === 'recall' || sub === 'detail') {
74
+ const arg = argv.slice(1).join(' ').trim();
75
+ if (!arg) { fail(`${sub} needs an argument.`); return; }
76
+ const rc = await load(projectRoot, 'recall.mjs');
77
+ if (!rc) { fail('recall runtime unavailable.'); return; }
78
+ const out = sub === 'recall' ? await rc.recall(arg, { projectRoot, missionId }) : await rc.detail(arg, { projectRoot, missionId });
79
+ log(safe(typeof out === 'string' ? out : JSON.stringify(out, null, 2)));
80
+ return;
81
+ }
82
+ if (sub === 'restore') {
83
+ const [rs, hooks] = await Promise.all([load(projectRoot, 'restore.mjs'), load(projectRoot, 'hooks.mjs')]);
84
+ if (!rs) { fail('restore runtime unavailable.'); return; }
85
+ const out = await store.withMissionLock(projectRoot, missionId, async () => rs.renderRestore({ projectRoot, missionId, sessionKey, git: await git(), maxChars: hooks?.COMBINED_RESTORE_CAP ?? 6000 }), { deadlineMs: 800 }).catch(() => null);
86
+ log(out?.ok && out.value?.text ? safe(out.value.text) : '[UKit] mission: nothing to restore.');
87
+ return;
88
+ }
89
+ if (sub === 'checkpoint') {
90
+ const cp = await load(projectRoot, 'checkpoint.mjs');
91
+ if (!cp) { fail('checkpoint runtime unavailable.'); return; }
92
+ const g = await graphMod.loadGraph({ projectRoot, missionId });
93
+ const r = await store.withMissionLock(projectRoot, missionId, async () => cp.writeCheckpoint({ projectRoot, missionId, trigger: 'manual', git: await git(), graph: g }), { deadlineMs: 800 });
94
+ log(r.ok && r.value ? `[UKit] mission checkpoint #${r.value.seq} saved.` : '[UKit] mission checkpoint skipped (lock busy).');
95
+ return;
96
+ }
97
+ printMissionHelp(log);
98
+ process.exitCode = 1;
99
+ } catch (error) {
100
+ fail(`failed open: ${String(error?.message || error).slice(0, 120)}`);
101
+ }
102
+ }
@@ -0,0 +1,83 @@
1
+ import fsp from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { pathToFileURL, fileURLToPath } from 'node:url';
4
+
5
+ // `ukit rescue [status|rebuild|resume|reset-breaker]` - also the Codex path (no hooks there).
6
+ const PKG_RESCUE = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../template_project/.claude/ukit/runtime/rescue');
7
+
8
+ async function load(projectRoot, name) {
9
+ for (const dir of [path.join(projectRoot, '.claude', 'ukit', 'runtime', 'rescue'), PKG_RESCUE]) {
10
+ try {
11
+ await fsp.access(path.join(dir, name));
12
+ return await import(pathToFileURL(path.join(dir, name)).href);
13
+ } catch { /* try next */ }
14
+ }
15
+ return null;
16
+ }
17
+
18
+ async function readJson(file) {
19
+ try { return JSON.parse(await fsp.readFile(file, 'utf8')); } catch { return null; }
20
+ }
21
+
22
+ export function printRescueHelp() {
23
+ console.log('Usage: ukit rescue [status|rebuild|resume|reset-breaker]');
24
+ console.log(' status recovery state, breaker, lease, latest restore bundle');
25
+ console.log(' rebuild rebuild the restore bundle offline (no model call)');
26
+ console.log(' resume print the command to continue in a fresh session');
27
+ console.log(' reset-breaker clear the circuit breaker (owner action)');
28
+ }
29
+
30
+ export async function runRescue({ projectRoot = process.cwd(), argv = [], log = console.log } = {}) {
31
+ const sub = (argv[0] ?? 'status').toLowerCase();
32
+ const rescueDir = path.join(projectRoot, '.ukit', 'storage', 'rescue');
33
+ if (['help', '--help', '-h'].includes(sub)) { printRescueHelp(); return; }
34
+
35
+ const rs = await load(projectRoot, 'recovery-state.mjs');
36
+ const latest = await readJson(path.join(rescueDir, 'latest.json'));
37
+
38
+ if (sub === 'status') {
39
+ const st = rs ? await rs.readState({ root: projectRoot }) : null;
40
+ const lease = await readJson(path.join(rescueDir, 'lease.json'));
41
+ const now = Date.now();
42
+ log(`[UKit] rescue state: ${st?.state ?? 'unknown'}${st?.reason ? ` (${st.reason})` : ''}`);
43
+ const open = rs && st ? Object.keys(st.breaker || {}).filter((fp) => rs.breakerStatus(st, fp, now).open) : [];
44
+ log(`[UKit] rescue breaker: ${open.length ? `OPEN (${open.length} fingerprint(s))` : 'closed'}`);
45
+ log(`[UKit] rescue lease: ${lease ? `epoch ${lease.epoch}, holder ${String(lease.holderSessionId).slice(0, 12)}, ${lease.expiresAt > now ? 'live' : 'expired'}` : 'none'}`);
46
+ log(`[UKit] rescue bundle: ${latest?.bundlePath ?? 'none'}`);
47
+ return;
48
+ }
49
+
50
+ if (sub === 'rebuild') {
51
+ const [rc, bd] = await Promise.all([load(projectRoot, 'reconstruct.mjs'), load(projectRoot, 'bundle.mjs')]);
52
+ if (!rc || !bd) { log('[UKit] rescue rebuild unavailable: reconstruct/bundle runtime not installed (run `ukit install`).'); process.exitCode = 1; return; }
53
+ const reconFn = rc.reconstruct || rc.default;
54
+ if (typeof reconFn !== 'function' || typeof bd.buildBundle !== 'function' || typeof bd.writeBundle !== 'function') {
55
+ log('[UKit] rescue rebuild unavailable: runtime API mismatch.'); process.exitCode = 1; return;
56
+ }
57
+ const recon = await reconFn({ root: projectRoot, projectRoot });
58
+ const bundle = bd.buildBundle(recon, {});
59
+ await bd.writeBundle(projectRoot, bundle);
60
+ const after = await readJson(path.join(rescueDir, 'latest.json'));
61
+ log(`[UKit] rescue bundle rebuilt: ${after?.bundlePath ?? '(see .ukit/storage/rescue)'}`);
62
+ return;
63
+ }
64
+
65
+ if (sub === 'resume') {
66
+ const uuid = latest?.sessionId || null;
67
+ if (uuid) log(`claude --resume ${uuid}`);
68
+ else log(`claude --session-id ${(await import('node:crypto')).randomUUID()}${latest?.bundlePath ? ` (restore bundle: ${latest.bundlePath})` : ''}`);
69
+ return;
70
+ }
71
+
72
+ if (sub === 'reset-breaker') {
73
+ const file = rs ? rs.stateFile(projectRoot) : null;
74
+ const st = file ? await readJson(file) : null;
75
+ if (!st) { log('[UKit] rescue breaker: nothing to reset.'); return; }
76
+ await fsp.writeFile(file, JSON.stringify({ ...st, breaker: {} }));
77
+ log('[UKit] rescue breaker reset.');
78
+ return;
79
+ }
80
+
81
+ printRescueHelp();
82
+ process.exitCode = 1;
83
+ }
package/src/cli/index.js CHANGED
@@ -16,6 +16,8 @@ import { runSelfImproveCommand } from './commands/selfImprove.js';
16
16
  import { runVm } from './commands/vm.js';
17
17
  import { runMarkerStore } from './commands/markerStore.js';
18
18
  import { runAdvisor } from './commands/advisor.js';
19
+ import { runRescue } from './commands/rescue.js';
20
+ import { runMission } from './commands/mission.js';
19
21
  const GLOBAL_FLAGS = new Set(['--help', '-h', '--version', '-v']);
20
22
 
21
23
  export async function runCli({ argv, packageRoot, projectRoot, packageVersion }) {
@@ -118,6 +120,16 @@ export async function runCli({ argv, packageRoot, projectRoot, packageVersion })
118
120
  return;
119
121
  }
120
122
 
123
+ if (command === 'mission') {
124
+ await runMission({ projectRoot, argv: commandArgv });
125
+ return;
126
+ }
127
+
128
+ if (command === 'rescue') {
129
+ await runRescue({ projectRoot, argv: commandArgv });
130
+ return;
131
+ }
132
+
121
133
  if (command === 'vm') {
122
134
  await runVm({ projectRoot, argv: commandArgv });
123
135
  return;
@@ -158,6 +170,8 @@ export async function runCli({ argv, packageRoot, projectRoot, packageVersion })
158
170
  console.log(' self-improve Run the automatic learn/tune/collect pass now (hooks run it)');
159
171
  console.log(' vm Agent VM driver (list/show/status/shadow-run/evidence)');
160
172
  console.log(' marker-store Plan/apply the OMP bridge UNKNOWN marker-store migration (refuses unless writers are verified stopped)');
173
+ console.log(' mission Mission continuity (status/recall/detail/restore/checkpoint/capture)');
174
+ console.log(' rescue Context rescue (status/rebuild/resume/reset-breaker)');
161
175
  console.log(' advisor Codex advisor: $ukit-advisor / ukit:advisor (status/install/uninstall/context)');
162
176
  console.log(' update Upgrade the global UKit CLI to the latest version');
163
177
  console.log(' version Show UKit version');
@@ -1,67 +1,88 @@
1
1
  import { readFileSync } from 'node:fs';
2
2
  import { fileURLToPath } from 'node:url';
3
3
 
4
- // The shipped compact.tokenThreshold / contextWindowTokens / hardCapTokens /
5
- // autoCompactWindowRatio numbers are the ONLY place the context budget is written down. Every other number — the
6
- // code-side defaults, CLAUDE_CODE_MAX_CONTEXT_TOKENS + CLAUDE_CODE_AUTO_COMPACT_WINDOW in
7
- // .claude/settings.json, and
8
- // compaction.thresholdTokens in .omp/config.yml — is read or derived from here, so retuning
9
- // UKit for a different model context window is a config-only edit in
10
- // template_project/ukit/storage/config.json and nothing else.
4
+ // The shipped compact.* numbers are the ONLY place the context budget is written down.
5
+ // UKit-owned tiers (bestTokens/okTokens/mandatoryTokens/stopTokens) are policy and do not
6
+ // depend on any model window; legacy hardCapTokens -> stopTokens and tokenThreshold ->
7
+ // bestTokens when an install still sets them. Everything the HOST needs
8
+ // (CLAUDE_CODE_MAX_CONTEXT_TOKENS + CLAUDE_CODE_AUTO_COMPACT_WINDOW in .claude/settings.json,
9
+ // compaction.thresholdTokens in .omp/config.yml) is rendered from here.
11
10
  const SHIPPED_CONFIG_URL = new URL('../../../template_project/ukit/storage/config.json', import.meta.url);
12
11
 
13
- // Only reachable if the package ships without its own templates. Deliberately conservative:
14
- // a 200k model survives these, a 1M model merely compacts earlier than it had to.
12
+ // Only reachable if the package ships without its own templates.
15
13
  const EMERGENCY_BUDGET = {
16
- tokenThreshold: 50_000,
17
- hardCapTokens: 160_000,
18
- autoCompactWindowRatio: 0.7,
14
+ bestTokens: 100_000,
15
+ okTokens: 150_000,
16
+ mandatoryTokens: 200_000,
17
+ stopTokens: 250_000,
19
18
  contextWindowTokens: 200_000,
19
+ hostAutoCompactTokens: 180_000,
20
+ ompCompactionThresholdTokens: 170_000,
20
21
  };
21
22
 
22
- // Auto-compact must land strictly below hardCapTokens so the client heals itself before
23
- // context-hardcap-gate starts refusing Edit/Write/Bash; a ratio >= 1 would invert that and is
24
- // treated as a typo rather than honoured.
25
- export function deriveAutoCompactWindow(hardCapTokens, ratio) {
26
- const safeRatio = Number.isFinite(ratio) && ratio > 0 && ratio < 1
27
- ? ratio
28
- : EMERGENCY_BUDGET.autoCompactWindowRatio;
29
- return Math.round(hardCapTokens * safeRatio);
23
+ // Host auto-compaction numbers. Compaction must ALWAYS be automatic (the owner never runs
24
+ // /compact), so the host has to fire inside the 150k-200k band, well before stopTokens.
25
+ // - Claude Code: env CLAUDE_CODE_AUTO_COMPACT_WINDOW is the capacity used for auto-compact
26
+ // calculations (values above the model window are clamped; the documented floor is
27
+ // 100000, matching the range test). Claude Code subtracts its own summary/output buffer
28
+ // from the window (a 200k window compacts around ~167k), so 180000 fires at roughly
29
+ // 150k-167k: inside the band, and at least 80k tokens under stopTokens. settings.json
30
+ // `env` is applied at session start and wins over a user-level default; UKit never
31
+ // writes DISABLE_AUTO_COMPACT and keeps autoCompactEnabled:true.
32
+ // - omp: compaction.thresholdTokens is a fixed token limit that overrides thresholdPercent
33
+ // when > 0 (omp v18.8.9); project .omp/config.yml takes precedence over ~/.omp. 170000
34
+ // sits inside the band with headroom for omp's mid-turn compaction.
35
+ // Both are clamped to the declared model window (host-env rendering ONLY - the tiers above
36
+ // are never lowered by contextWindowTokens). Legacy autoCompactWindowRatio still applies
37
+ // when no explicit hostAutoCompactTokens is set and the install pins hardCapTokens.
38
+ export function deriveAutoCompactWindow(base, ratio) {
39
+ const safeRatio = Number.isFinite(ratio) && ratio > 0 && ratio < 1 ? ratio : 0.7;
40
+ return Math.round(base * safeRatio);
30
41
  }
31
42
 
32
- // A malformed hard cap must fall back to a safe ceiling, never collapse to a
33
- // non-positive or fractional cap that would brick every Edit/Write/Bash call or
34
- // invert the autoCompactWindow < hardCapTokens invariant — same operator
35
- // contract as positiveInteger() in compact/threshold.js.
36
43
  function positiveInteger(value, fallback) {
37
44
  return typeof value === 'number' && Number.isFinite(value) && Number.isInteger(value) && value > 0
38
45
  ? value
39
46
  : fallback;
40
47
  }
41
48
 
42
- // Pure normalization of a raw `compact` config object into the budget triple.
43
- // Exported so the fallback rules are testable without touching the shipped file.
49
+ const GATEWAY_HEADROOM_TOKENS = 20_000;
50
+ const GATEWAY_WINDOW_FLOOR = 100_000;
51
+
44
52
  export function deriveCompactBudget(compact = {}) {
45
53
  const source = compact && typeof compact === 'object' ? compact : {};
46
- const tokenThreshold = Number.isFinite(source.tokenThreshold)
47
- ? source.tokenThreshold
48
- : EMERGENCY_BUDGET.tokenThreshold;
49
- // compact.contextWindowTokens is the model window UKit tells the client to assume
50
- // (CLAUDE_CODE_MAX_CONTEXT_TOKENS). It is a deliberate operator CEILING, not a probe of
51
- // what the provider accepts: a gateway alias such as unic-opus is unknown to Claude Code,
52
- // and without this it silently falls back to 200k (or 1M), ignoring UKit's budget.
54
+ const stopTokens = positiveInteger(source.hardCapTokens, positiveInteger(source.stopTokens, EMERGENCY_BUDGET.stopTokens));
55
+ const mandatoryTokens = Math.min(positiveInteger(source.mandatoryTokens, EMERGENCY_BUDGET.mandatoryTokens), stopTokens);
56
+ const okTokens = Math.min(positiveInteger(source.okTokens, EMERGENCY_BUDGET.okTokens), mandatoryTokens);
57
+ const bestTokens = Math.min(
58
+ positiveInteger(source.tokenThreshold, positiveInteger(source.bestTokens, EMERGENCY_BUDGET.bestTokens)),
59
+ okTokens,
60
+ );
53
61
  const contextWindowTokens = positiveInteger(source.contextWindowTokens, EMERGENCY_BUDGET.contextWindowTokens);
54
- // The hard cap must sit inside the window it guards; a cap above the window could never
55
- // fire before the provider rejects the request.
56
- const hardCapTokens = Math.min(
57
- positiveInteger(source.hardCapTokens, EMERGENCY_BUDGET.hardCapTokens),
58
- contextWindowTokens,
62
+ const legacyWindow = positiveInteger(source.hardCapTokens, 0) > 0 && Number.isFinite(source.autoCompactWindowRatio)
63
+ ? deriveAutoCompactWindow(stopTokens, source.autoCompactWindowRatio)
64
+ : 0;
65
+ const hostRaw = positiveInteger(source.hostAutoCompactTokens, legacyWindow || EMERGENCY_BUDGET.hostAutoCompactTokens);
66
+ // Optional gateway limit: the window must sit >= 20k under what the gateway really accepts (floor 100k,
67
+ // the host's documented minimum). UKit does not write CLAUDE_CODE_MAX_OUTPUT_TOKENS, so nothing else to cap.
68
+ const gatewayLimit = positiveInteger(source.gatewayLimitTokens, 0);
69
+ const gatewayCap = gatewayLimit > 0 ? Math.max(GATEWAY_WINDOW_FLOOR, gatewayLimit - GATEWAY_HEADROOM_TOKENS) : Infinity;
70
+ const autoCompactWindow = Math.min(hostRaw, contextWindowTokens, stopTokens - 1, gatewayCap);
71
+ const ompCompactionThresholdTokens = Math.min(
72
+ positiveInteger(source.ompCompactionThresholdTokens, EMERGENCY_BUDGET.ompCompactionThresholdTokens),
73
+ autoCompactWindow,
59
74
  );
60
75
  return {
61
- tokenThreshold,
62
- hardCapTokens,
76
+ bestTokens,
77
+ okTokens,
78
+ mandatoryTokens,
79
+ stopTokens,
80
+ // Back-compat names for existing consumers.
81
+ tokenThreshold: bestTokens,
82
+ hardCapTokens: stopTokens,
63
83
  contextWindowTokens,
64
- autoCompactWindow: deriveAutoCompactWindow(hardCapTokens, source.autoCompactWindowRatio),
84
+ autoCompactWindow,
85
+ ompCompactionThresholdTokens,
65
86
  };
66
87
  }
67
88