@ngockhoale/ukit 3.5.17 → 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.
- package/CHANGELOG.md +10 -0
- package/manifests/platform.full.yaml +48 -0
- package/package.json +1 -1
- package/src/cli/commands/mission.js +102 -0
- package/src/cli/commands/rescue.js +83 -0
- package/src/cli/index.js +14 -0
- package/src/core/compact/contextBudget.js +62 -41
- package/src/core/compact/threshold.js +14 -32
- package/src/core/observability/schema/registry.js +91 -0
- package/src/core/runtimeConfig.js +53 -2
- package/src/render/buildVariables.js +2 -5
- package/template_project/.claude/commands/ukit/handoff-implement.md +3 -3
- package/template_project/.claude/commands/ukit/handoff-review.md +3 -3
- package/template_project/.claude/hooks/context-hardcap-gate.sh +47 -20
- package/template_project/.claude/hooks/context-window-guard.sh +82 -27
- package/template_project/.claude/hooks/handoff-resume.sh +11 -2
- package/template_project/.claude/hooks/mission-capture.mjs +37 -0
- package/template_project/.claude/hooks/post-compact-observe.mjs +34 -0
- package/template_project/.claude/hooks/shell-watch.mjs +34 -0
- package/template_project/.claude/hooks/stop-failure-rescue.mjs +109 -0
- package/template_project/.claude/settings.json +36 -4
- package/template_project/.claude/ukit/runtime/compact-threshold.mjs +15 -29
- package/template_project/.claude/ukit/runtime/context-capacity.mjs +64 -1
- package/template_project/.claude/ukit/runtime/execution-ledger.mjs +44 -3
- package/template_project/.claude/ukit/runtime/hook-chain-runner.mjs +20 -1
- package/template_project/.claude/ukit/runtime/mission/checkpoint.mjs +85 -0
- package/template_project/.claude/ukit/runtime/mission/classify.mjs +182 -0
- package/template_project/.claude/ukit/runtime/mission/drift.mjs +58 -0
- package/template_project/.claude/ukit/runtime/mission/graph.mjs +381 -0
- package/template_project/.claude/ukit/runtime/mission/hooks.mjs +199 -0
- package/template_project/.claude/ukit/runtime/mission/journal.mjs +68 -0
- package/template_project/.claude/ukit/runtime/mission/metrics.mjs +64 -0
- package/template_project/.claude/ukit/runtime/mission/recall.mjs +132 -0
- package/template_project/.claude/ukit/runtime/mission/redact.mjs +25 -0
- package/template_project/.claude/ukit/runtime/mission/restore.mjs +107 -0
- package/template_project/.claude/ukit/runtime/mission/store.mjs +231 -0
- package/template_project/.claude/ukit/runtime/mission/working.mjs +88 -0
- package/template_project/.claude/ukit/runtime/prompt-injection-cap.mjs +33 -0
- package/template_project/.claude/ukit/runtime/reinject-context.mjs +87 -6
- package/template_project/.claude/ukit/runtime/rescue/bundle.mjs +122 -0
- package/template_project/.claude/ukit/runtime/rescue/classify-failure.mjs +136 -0
- package/template_project/.claude/ukit/runtime/rescue/lease.mjs +65 -0
- package/template_project/.claude/ukit/runtime/rescue/reconstruct.mjs +273 -0
- package/template_project/.claude/ukit/runtime/rescue/recovery-state.mjs +120 -0
- package/template_project/.claude/ukit/runtime/rescue/rollover.mjs +151 -0
- package/template_project/.claude/ukit/runtime/sensitive-value-scanner.mjs +1 -1
- package/template_project/.claude/ukit/runtime/shell-watch.mjs +278 -0
- package/template_project/.claude/ukit/runtime/stop-coordinator.mjs +154 -0
- package/template_project/.omp/config.yml +2 -2
- package/template_project/.omp/hooks/pre/ukit-bridge.js +69 -2
- package/template_project/AGENTS.md +3 -1
- package/template_project/CLAUDE.md +3 -1
- package/template_project/docs/AI_HANDOFF/RULES.md +4 -4
- package/template_project/instructions/core.md +3 -1
- package/template_project/ukit/storage/config.json +32 -10
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,16 @@
|
|
|
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
|
+
|
|
5
15
|
## 3.5.17 - 2026-11-21
|
|
6
16
|
|
|
7
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.
|
|
@@ -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
|
@@ -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
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
// .
|
|
8
|
-
//
|
|
9
|
-
//
|
|
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.
|
|
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
|
-
|
|
17
|
-
|
|
18
|
-
|
|
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
|
-
//
|
|
23
|
-
//
|
|
24
|
-
//
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
:
|
|
29
|
-
|
|
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
|
-
|
|
43
|
-
|
|
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
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
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
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
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
|
-
|
|
62
|
-
|
|
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
|
|
84
|
+
autoCompactWindow,
|
|
85
|
+
ompCompactionThresholdTokens,
|
|
65
86
|
};
|
|
66
87
|
}
|
|
67
88
|
|
|
@@ -5,11 +5,10 @@ import {
|
|
|
5
5
|
readContextCapacityRecord,
|
|
6
6
|
SOFT_TO_CAP_RATIO,
|
|
7
7
|
} from '../../../template_project/.claude/ukit/runtime/compact-threshold.mjs';
|
|
8
|
-
import { resolveContextCapTokens } from '../../../template_project/.claude/ukit/runtime/context-capacity.mjs';
|
|
8
|
+
import { resolveContextCapTokens, resolveContextTiers } from '../../../template_project/.claude/ukit/runtime/context-capacity.mjs';
|
|
9
9
|
import { buildRuntimePaths } from '../runtimePaths.js';
|
|
10
10
|
import { buildCompactMachineKey, compressLine, estimateTokenCount } from '../token/index.js';
|
|
11
11
|
import { compactContextBlock } from './index.js';
|
|
12
|
-
import { loadShippedCompactBudget } from './contextBudget.js';
|
|
13
12
|
|
|
14
13
|
const DEFAULT_MAX_PROMPT_ENTRIES = 12;
|
|
15
14
|
const DEFAULT_MAX_OUTPUT_ENTRIES = 12;
|
|
@@ -458,40 +457,27 @@ async function readNegotiatedCapacity(config = {}) {
|
|
|
458
457
|
}
|
|
459
458
|
|
|
460
459
|
export async function buildCompactThresholds(config = {}) {
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
)
|
|
465
|
-
//
|
|
466
|
-
|
|
467
|
-
const
|
|
468
|
-
const
|
|
469
|
-
const explicitSoftThreshold = finiteNumber(config?.compact?.tokenThreshold, 0);
|
|
470
|
-
// Negotiated capacity (H22): the guard publishes what it derived from the live route and
|
|
471
|
-
// this shared path consumes it; without a record the shipped tuning applies unchanged.
|
|
472
|
-
const negotiated = await readNegotiatedCapacity(config);
|
|
473
|
-
const hardCapTokens = negotiated
|
|
474
|
-
? Math.max(1, Math.min(effectiveShippedHardCap, negotiated.capTokens))
|
|
475
|
-
: effectiveShippedHardCap;
|
|
476
|
-
// An explicit operator tokenThreshold is honoured but still clamped under the
|
|
477
|
-
// negotiated cap: an advisory soft/hard pair sitting at or above hardCapTokens can
|
|
478
|
-
// never fire, because context-hardcap-gate.sh already refuses tools at the cap
|
|
479
|
-
// (C92-H-01 — on a default install tokenThreshold is the shipped 150k default, not a
|
|
480
|
-
// real operator choice, so this is correcting a number, not overriding intent).
|
|
481
|
-
const softThreshold = explicitSoftThreshold > 0
|
|
482
|
-
? Math.max(1, Math.min(explicitSoftThreshold, hardCapTokens - 1))
|
|
483
|
-
: Math.max(1, Math.round(hardCapTokens * SOFT_TO_CAP_RATIO));
|
|
460
|
+
// UKit-owned tiers (compact.bestTokens/okTokens/mandatoryTokens/stopTokens, legacy
|
|
461
|
+
// hardCapTokens -> stopTokens, tokenThreshold -> bestTokens). They are deliberately NOT
|
|
462
|
+
// clamped to contextWindowTokens or the negotiated model window: the tiers are UKit
|
|
463
|
+
// policy, and the host auto-compaction window (rendered separately) keeps sessions below
|
|
464
|
+
// stopTokens. The capacity record is still read for diagnostics only.
|
|
465
|
+
const tiers = resolveContextTiers(config);
|
|
466
|
+
const hardCapTokens = tiers.stopTokens;
|
|
467
|
+
const softThreshold = Math.max(1, Math.min(tiers.bestTokens, hardCapTokens - 1));
|
|
484
468
|
const hardThreshold = Math.min(
|
|
485
469
|
hardCapTokens,
|
|
486
470
|
Math.max(softThreshold + 1, Math.round(softThreshold * 1.6)),
|
|
487
471
|
);
|
|
488
472
|
const baselineTokens = Math.max(120, Math.min(18_000, Math.round(softThreshold * 0.18)));
|
|
473
|
+
const negotiated = await readNegotiatedCapacity(config);
|
|
489
474
|
|
|
490
475
|
return {
|
|
491
476
|
softThreshold,
|
|
492
477
|
hardThreshold,
|
|
493
478
|
baselineTokens,
|
|
494
479
|
hardCapTokens,
|
|
480
|
+
tiers,
|
|
495
481
|
capacitySource: negotiated?.capacity?.source ?? 'shipped',
|
|
496
482
|
capacityTokens: negotiated?.capacity?.tokens ?? null,
|
|
497
483
|
};
|
|
@@ -689,13 +675,9 @@ export async function buildCompactPressureState(rawState = null, config = {}) {
|
|
|
689
675
|
const thresholds = await buildCompactThresholds(config);
|
|
690
676
|
const rawSoftThreshold = finiteNumber(rawState?.softThreshold, 0);
|
|
691
677
|
const rawHardThreshold = finiteNumber(rawState?.hardThreshold, 0);
|
|
692
|
-
if (!finiteNumber(config?.compact?.tokenThreshold, 0) && rawSoftThreshold > 0) {
|
|
693
|
-
// A persisted pair is only
|
|
694
|
-
//
|
|
695
|
-
// existed, or before the model was verified, carries thresholds tuned for the
|
|
696
|
-
// shipped 500k ceiling — restoring them re-pins the advisory ABOVE the live
|
|
697
|
-
// hardCapTokens forever (C92-H-02). Falling through keeps the freshly derived
|
|
698
|
-
// pair, which is also what the rewritten record persists, so the file self-heals.
|
|
678
|
+
if (!finiteNumber(config?.compact?.tokenThreshold, 0) && !finiteNumber(config?.compact?.bestTokens, 0) && rawSoftThreshold > 0) {
|
|
679
|
+
// A persisted pair is honoured only while it sits strictly inside stopTokens, so a stale
|
|
680
|
+
// record can never pin the advisory at/above the stop line (C92-H-02).
|
|
699
681
|
if (rawSoftThreshold < thresholds.hardCapTokens) {
|
|
700
682
|
thresholds.softThreshold = rawSoftThreshold;
|
|
701
683
|
thresholds.hardThreshold = Math.min(
|
|
@@ -380,6 +380,97 @@ export const REASON_CODES = Object.freeze({
|
|
|
380
380
|
deprecated: null,
|
|
381
381
|
privacy_class: 'internal',
|
|
382
382
|
},
|
|
383
|
+
CONTEXT_PRESSURE_DETECTED: {
|
|
384
|
+
definition: "Context usage crossed the rescue pressure threshold.",
|
|
385
|
+
unit: null,
|
|
386
|
+
introduced_version: V1_3,
|
|
387
|
+
deprecated: null,
|
|
388
|
+
privacy_class: 'internal',
|
|
389
|
+
},
|
|
390
|
+
CHECKPOINT_SAVED: {
|
|
391
|
+
definition: "A mission checkpoint was persisted before compaction or rollover.",
|
|
392
|
+
unit: null,
|
|
393
|
+
introduced_version: V1_3,
|
|
394
|
+
deprecated: null,
|
|
395
|
+
privacy_class: 'internal',
|
|
396
|
+
},
|
|
397
|
+
COMPACT_STARTED: {
|
|
398
|
+
definition: "A compaction began.",
|
|
399
|
+
unit: null,
|
|
400
|
+
introduced_version: V1_3,
|
|
401
|
+
deprecated: null,
|
|
402
|
+
privacy_class: 'internal',
|
|
403
|
+
},
|
|
404
|
+
COMPACT_SUCCEEDED: {
|
|
405
|
+
definition: "A compaction finished successfully.",
|
|
406
|
+
unit: null,
|
|
407
|
+
introduced_version: V1_3,
|
|
408
|
+
deprecated: null,
|
|
409
|
+
privacy_class: 'internal',
|
|
410
|
+
},
|
|
411
|
+
COMPACT_FAILED: {
|
|
412
|
+
definition: "A compaction failed; payload carries the redacted failure fingerprint.",
|
|
413
|
+
unit: null,
|
|
414
|
+
introduced_version: V1_3,
|
|
415
|
+
deprecated: null,
|
|
416
|
+
privacy_class: 'internal',
|
|
417
|
+
},
|
|
418
|
+
RECOVERY_STARTED: {
|
|
419
|
+
definition: "The rescue supervisor began recovery outside the failed session.",
|
|
420
|
+
unit: null,
|
|
421
|
+
introduced_version: V1_3,
|
|
422
|
+
deprecated: null,
|
|
423
|
+
privacy_class: 'internal',
|
|
424
|
+
},
|
|
425
|
+
OFFLINE_CONTEXT_REBUILT: {
|
|
426
|
+
definition: "The restore bundle was rebuilt offline from durable records.",
|
|
427
|
+
unit: null,
|
|
428
|
+
introduced_version: V1_3,
|
|
429
|
+
deprecated: null,
|
|
430
|
+
privacy_class: 'internal',
|
|
431
|
+
},
|
|
432
|
+
SESSION_ROLLOVER_STARTED: {
|
|
433
|
+
definition: "A clean replacement session was requested for the mission.",
|
|
434
|
+
unit: null,
|
|
435
|
+
introduced_version: V1_3,
|
|
436
|
+
deprecated: null,
|
|
437
|
+
privacy_class: 'internal',
|
|
438
|
+
},
|
|
439
|
+
SESSION_ROLLOVER_SUCCEEDED: {
|
|
440
|
+
definition: "A replacement session process was started (not proof of progress).",
|
|
441
|
+
unit: null,
|
|
442
|
+
introduced_version: V1_3,
|
|
443
|
+
deprecated: null,
|
|
444
|
+
privacy_class: 'internal',
|
|
445
|
+
},
|
|
446
|
+
SESSION_RESTORED: {
|
|
447
|
+
definition: "The replacement session loaded the restore bundle.",
|
|
448
|
+
unit: null,
|
|
449
|
+
introduced_version: V1_3,
|
|
450
|
+
deprecated: null,
|
|
451
|
+
privacy_class: 'internal',
|
|
452
|
+
},
|
|
453
|
+
MISSION_CONTINUED: {
|
|
454
|
+
definition: "Evidence that the mission advanced in the replacement session.",
|
|
455
|
+
unit: null,
|
|
456
|
+
introduced_version: V1_3,
|
|
457
|
+
deprecated: null,
|
|
458
|
+
privacy_class: 'internal',
|
|
459
|
+
},
|
|
460
|
+
RECOVERY_BLOCKED: {
|
|
461
|
+
definition: "Recovery stopped on a terminal blocker (auth, owner STOP, open breaker).",
|
|
462
|
+
unit: null,
|
|
463
|
+
introduced_version: V1_3,
|
|
464
|
+
deprecated: null,
|
|
465
|
+
privacy_class: 'internal',
|
|
466
|
+
},
|
|
467
|
+
MISSION_COMPLETED_VERIFIED: {
|
|
468
|
+
definition: "The mission completed with valid acceptance evidence. Payloads are redacted.",
|
|
469
|
+
unit: null,
|
|
470
|
+
introduced_version: V1_3,
|
|
471
|
+
deprecated: null,
|
|
472
|
+
privacy_class: 'internal',
|
|
473
|
+
},
|
|
383
474
|
});
|
|
384
475
|
|
|
385
476
|
// Guard: registry privacy classes must stay inside the frozen vocabulary.
|