@ngockhoale/ukit 3.5.15 → 3.5.18

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 (77) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/manifests/platform.full.yaml +48 -0
  3. package/package.json +2 -1
  4. package/scripts/release/heavy-first.mjs +12 -0
  5. package/scripts/release/release-steps.mjs +7 -4
  6. package/scripts/release/run-core-batch.mjs +50 -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/diagnostics/routeOutcomes.js +5 -1
  15. package/src/diagnostics/skillAccuracy.js +5 -2
  16. package/src/render/buildVariables.js +2 -5
  17. package/template_project/.claude/commands/ukit/handoff-implement.md +3 -3
  18. package/template_project/.claude/commands/ukit/handoff-review.md +3 -3
  19. package/template_project/.claude/hooks/context-hardcap-gate.sh +47 -20
  20. package/template_project/.claude/hooks/context-window-guard.sh +82 -27
  21. package/template_project/.claude/hooks/delegation-gate.mjs +1 -1
  22. package/template_project/.claude/hooks/handoff-resume.sh +11 -2
  23. package/template_project/.claude/hooks/mission-capture.mjs +37 -0
  24. package/template_project/.claude/hooks/post-compact-observe.mjs +34 -0
  25. package/template_project/.claude/hooks/shell-watch.mjs +34 -0
  26. package/template_project/.claude/hooks/skill-router.sh +13 -0
  27. package/template_project/.claude/hooks/stop-failure-rescue.mjs +109 -0
  28. package/template_project/.claude/settings.json +36 -4
  29. package/template_project/.claude/skills/backend-api/SKILL.md +1 -1
  30. package/template_project/.claude/skills/delivery/SKILL.md +1 -1
  31. package/template_project/.claude/skills/docs-manager/SKILL.md +1 -1
  32. package/template_project/.claude/skills/duraone/SKILL.md +2 -1
  33. package/template_project/.claude/skills/file-organizer/SKILL.md +1 -1
  34. package/template_project/.claude/skills/frontend/SKILL.md +1 -1
  35. package/template_project/.claude/skills/frontend-vue/SKILL.md +1 -1
  36. package/template_project/.claude/skills/pdf-processing/SKILL.md +1 -1
  37. package/template_project/.claude/skills/postgres/SKILL.md +1 -1
  38. package/template_project/.claude/skills/testing-quality/SKILL.md +2 -0
  39. package/template_project/.claude/skills/webapp-testing/SKILL.md +1 -1
  40. package/template_project/.claude/ukit/index/route-task.mjs +3 -1
  41. package/template_project/.claude/ukit/index/tier-lane.mjs +1 -1
  42. package/template_project/.claude/ukit/runtime/compact-threshold.mjs +15 -29
  43. package/template_project/.claude/ukit/runtime/context-capacity.mjs +64 -1
  44. package/template_project/.claude/ukit/runtime/execution-ledger.mjs +107 -4
  45. package/template_project/.claude/ukit/runtime/hook-chain-runner.mjs +20 -1
  46. package/template_project/.claude/ukit/runtime/mission/checkpoint.mjs +85 -0
  47. package/template_project/.claude/ukit/runtime/mission/classify.mjs +182 -0
  48. package/template_project/.claude/ukit/runtime/mission/drift.mjs +58 -0
  49. package/template_project/.claude/ukit/runtime/mission/graph.mjs +381 -0
  50. package/template_project/.claude/ukit/runtime/mission/hooks.mjs +199 -0
  51. package/template_project/.claude/ukit/runtime/mission/journal.mjs +68 -0
  52. package/template_project/.claude/ukit/runtime/mission/metrics.mjs +64 -0
  53. package/template_project/.claude/ukit/runtime/mission/recall.mjs +132 -0
  54. package/template_project/.claude/ukit/runtime/mission/redact.mjs +25 -0
  55. package/template_project/.claude/ukit/runtime/mission/restore.mjs +107 -0
  56. package/template_project/.claude/ukit/runtime/mission/store.mjs +231 -0
  57. package/template_project/.claude/ukit/runtime/mission/working.mjs +88 -0
  58. package/template_project/.claude/ukit/runtime/prompt-injection-cap.mjs +33 -0
  59. package/template_project/.claude/ukit/runtime/reinject-context.mjs +87 -6
  60. package/template_project/.claude/ukit/runtime/rescue/bundle.mjs +122 -0
  61. package/template_project/.claude/ukit/runtime/rescue/classify-failure.mjs +136 -0
  62. package/template_project/.claude/ukit/runtime/rescue/lease.mjs +65 -0
  63. package/template_project/.claude/ukit/runtime/rescue/reconstruct.mjs +273 -0
  64. package/template_project/.claude/ukit/runtime/rescue/recovery-state.mjs +120 -0
  65. package/template_project/.claude/ukit/runtime/rescue/rollover.mjs +151 -0
  66. package/template_project/.claude/ukit/runtime/sensitive-value-scanner.mjs +1 -1
  67. package/template_project/.claude/ukit/runtime/shell-watch.mjs +278 -0
  68. package/template_project/.claude/ukit/runtime/stop-coordinator.mjs +154 -0
  69. package/template_project/.omp/RULES.md +1 -1
  70. package/template_project/.omp/config.yml +2 -2
  71. package/template_project/.omp/hooks/pre/ukit-bridge.js +69 -2
  72. package/template_project/AGENTS.md +5 -1
  73. package/template_project/CLAUDE.md +5 -1
  74. package/template_project/docs/AI_HANDOFF/RULES.md +4 -4
  75. package/template_project/instructions/core.md +5 -1
  76. package/template_project/instructions/overlays/omp-rules.md +1 -1
  77. package/template_project/ukit/storage/config.json +32 -10
package/CHANGELOG.md CHANGED
@@ -2,6 +2,31 @@
2
2
 
3
3
  All notable changes to UKit are documented here.
4
4
 
5
+ ## 3.5.18 - 2026-11-21
6
+
7
+ - **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.
8
+ - **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.
9
+ - **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`.
10
+ - **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.
11
+ - **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.
12
+ - **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.
13
+ - **Shell watch:** an interrupted subagent is no longer reported as a hung task.
14
+
15
+ ## 3.5.17 - 2026-11-21
16
+
17
+ - **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.
18
+ - **Batch runs count as verification evidence.** `test-batches.mjs run` (default mode included) is recognised as a test run by the Stop gate; `plan`, `audit` and `detect-leaks` are not.
19
+ - **The release verifier runs its core suite in four bounded batches.** The single core phase had outgrown its fixed 600 s budget. It is now split into "Core test suite (batch 1/4)" through "(batch 4/4)". The file list comes from `vitest list` at run time and is dealt deterministically, with heavy files spread across batches. A batch fails if the batches together do not cover every file. No timeout was relaxed, and 3.5.16, which was never published, ships inside this release.
20
+ - **Delegation guidance mentions the batch runner.** The orchestrator brief and the delegation-gate message now point to `test-batches.mjs run` for full-suite verification.
21
+
22
+ ## 3.5.16 - 2026-11-21
23
+
24
+ Field-telemetry fix round 4.
25
+
26
+ - **Projects without a test command can finish (#7, #13).** The Stop gate only accepted a test-runner verdict, so a project with no declared tests (9Router: no package.json; checks were `node --check`) could never satisfy "verification-evidence" and got "check-only does not satisfy this lane" in a loop. When the project declares no test surface — no non-default `test`/`test:*` script, no pytest/go/cargo/gradle/maven/phpunit/mix/Gemfile marker, no `test:` Makefile target, no `tests/`, `test/`, `__tests__/` or `spec/` directory — a current passing check-only verdict now counts. Any declared test surface keeps the strict requirement.
27
+ - **Telemetry logs stop growing without bound (#8).** `decisions.tsv` (13 MB in one project) and `cache/route-audit.segments.jsonl` (12.5 MB) now rotate at 4 MiB to a single `.1` generation, and the diagnostics read both. Per-session `cache/route-state/*.json` files (1,513 in one project) are swept by the existing bounded ledger sweep: older than 30 days, or past 400 files when idle for more than 24 h. A live session's state is never evicted.
28
+ - **Skill descriptions say when to use them (#15).** Ten skills (backend-api, delivery, docs-manager, duraone, file-organizer, frontend, frontend-vue, pdf-processing, postgres, webapp-testing) had descriptions that named a topic but not a trigger; each now carries a "Use when…" clause.
29
+
5
30
  ## 3.5.15 - 2026-11-21
6
31
 
7
32
  Field-telemetry fix round 3.
@@ -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.15",
3
+ "version": "3.5.18",
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",
@@ -114,6 +114,7 @@
114
114
  "test:python:setup": "node tests/python/setup-test-venv.mjs",
115
115
  "test:artifact": "vitest run tests/integration/packageArtifact.test.js tests/integration/artifactReferenceIntegrity.test.js",
116
116
  "test:release-core": "vitest run --exclude tests/integration/packageArtifact.test.js",
117
+ "test:release-core-batch": "node ./scripts/release/run-core-batch.mjs",
117
118
  "release:verify": "node ./scripts/release/verify-release.mjs",
118
119
  "prepublishOnly": "node ./scripts/release/publish-guard.mjs",
119
120
  "test": "vitest run",
@@ -0,0 +1,12 @@
1
+ // Measured slowest suites. Shared by vitest.config.js (run order) and run-core-batch.mjs (spread
2
+ // across release batches so no single batch inherits all the heavy files).
3
+ export const HEAVY_FIRST = [
4
+ 'tests/integration/installPipeline.test.js',
5
+ 'tests/hooks/guidanceSupplementBinding.test.js',
6
+ 'tests/hooks/historicalSemanticMetamorphic.test.js',
7
+ 'tests/hooks/nativePublicationRouting.test.js',
8
+ 'tests/hooks/handoffProvenance.test.js',
9
+ 'tests/hooks/skillRouterHook.test.js',
10
+ 'tests/hooks/releaseCompletionEvidence.test.js',
11
+ 'tests/hooks/completionClosure.test.js',
12
+ ];
@@ -7,6 +7,8 @@ import os from 'node:os';
7
7
  // Ships with verify-release.mjs so installed --post-publish checks can load.
8
8
  export const npmCacheDir = path.join(os.tmpdir(), 'ukit-npm-cache');
9
9
 
10
+ export const CORE_BATCHES = 4;
11
+
10
12
  export const releaseSteps = [
11
13
  {
12
14
  label: 'Rendered instructions up to date (fix: yarn docs:render)',
@@ -45,12 +47,13 @@ export const releaseSteps = [
45
47
  args: ['test:handoff'],
46
48
  env: process.env,
47
49
  },
48
- {
49
- label: 'Core test suite',
50
+ ...Array.from({ length: CORE_BATCHES }, (_, i) => ({
51
+ // Same file set as `yarn test:release-core`, split so no single step nears the per-step deadline.
52
+ label: `Core test suite (batch ${i + 1}/${CORE_BATCHES})`,
50
53
  command: 'yarn',
51
- args: ['test:release-core', '--bail', '5'], // stop after 5 failures instead of finishing a doomed 4 min run
54
+ args: ['test:release-core-batch', String(i + 1), String(CORE_BATCHES)],
52
55
  env: process.env,
53
- },
56
+ })),
54
57
  {
55
58
  label: 'Local package dry-run',
56
59
  command: 'npm',
@@ -0,0 +1,50 @@
1
+ import { spawn, execFileSync } from 'node:child_process';
2
+ import { statSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { HEAVY_FIRST } from './heavy-first.mjs';
5
+
6
+ // Runs batch <index> of <count> of the release core suite (everything `yarn test:release-core`
7
+ // would run). The file list is computed at run time from vitest itself, so new tests are never
8
+ // skipped; partitioning is deterministic and every invocation proves the batches cover the list.
9
+ export const CORE_EXCLUDE = 'tests/integration/packageArtifact.test.js'; // run by the Artifact smoke step
10
+
11
+ export function listCoreFiles(cwd = process.cwd()) {
12
+ const env = { ...process.env };
13
+ delete env.UKIT_VERIFY_PROGRESS_FILE; // listing must not emit phase progress
14
+ const out = execFileSync('yarn', ['--silent', 'vitest', 'list', '--filesOnly', '--exclude', CORE_EXCLUDE], {
15
+ cwd, env, encoding: 'utf8', maxBuffer: 16 * 1024 * 1024, timeout: 120_000, stdio: ['ignore', 'pipe', 'ignore'],
16
+ });
17
+ return out.split('\n').map((l) => l.trim().replace(/\\/g, '/')).filter((l) => /\.test\.[cm]?js$/.test(l));
18
+ }
19
+
20
+ export function partition(files, count, cwd = process.cwd()) {
21
+ const size = (f) => { try { return statSync(path.join(cwd, f)).size; } catch { return 0; } };
22
+ const heavy = (f) => { const i = HEAVY_FIRST.indexOf(f); return i === -1 ? HEAVY_FIRST.length : i; };
23
+ const ordered = [...new Set(files)].sort((a, b) => heavy(a) - heavy(b) || size(b) - size(a) || (a < b ? -1 : 1));
24
+ const batches = Array.from({ length: count }, () => []);
25
+ ordered.forEach((f, i) => batches[i % count].push(f)); // round-robin spreads heavy files
26
+ const union = batches.flat();
27
+ if (union.length !== new Set(files).size || !files.every((f) => union.includes(f))) {
28
+ throw new Error('core batch partition does not cover the full test file list');
29
+ }
30
+ return batches;
31
+ }
32
+
33
+ if (import.meta.url === `file://${process.argv[1]}`) {
34
+ const index = Number(process.argv[2]);
35
+ const count = Number(process.argv[3]);
36
+ if (!Number.isInteger(index) || !Number.isInteger(count) || count < 1 || index < 1 || index > count) {
37
+ console.error('usage: run-core-batch.mjs <batch 1..N> <N>');
38
+ process.exit(2);
39
+ }
40
+ const files = listCoreFiles();
41
+ if (files.length === 0) { console.error('[core-batch] no test files listed'); process.exit(1); }
42
+ const batch = partition(files, count)[index - 1];
43
+ console.log(`[core-batch] ${index}/${count}: ${batch.length} of ${files.length} files`);
44
+ const child = spawn('yarn', ['vitest', 'run', ...batch, '--bail', '5'], { stdio: 'inherit' });
45
+ // Backstop watchdog (same budget as the verifier's per-step deadline; the verifier kills the whole tree first).
46
+ const watchdog = setTimeout(() => { try { child.kill('SIGKILL'); } catch { /* gone */ } }, Number(process.env.UKIT_VERIFY_STEP_TIMEOUT_MS) || 10 * 60 * 1000);
47
+ watchdog.unref();
48
+ child.on('exit', (code, signal) => process.exit(code ?? (signal ? 1 : 0)));
49
+ child.on('error', () => process.exit(1));
50
+ }
@@ -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