@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.
Files changed (55) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/manifests/platform.full.yaml +48 -0
  3. package/package.json +1 -1
  4. package/src/cli/commands/mission.js +102 -0
  5. package/src/cli/commands/rescue.js +83 -0
  6. package/src/cli/index.js +14 -0
  7. package/src/core/compact/contextBudget.js +62 -41
  8. package/src/core/compact/threshold.js +14 -32
  9. package/src/core/observability/schema/registry.js +91 -0
  10. package/src/core/runtimeConfig.js +53 -2
  11. package/src/render/buildVariables.js +2 -5
  12. package/template_project/.claude/commands/ukit/handoff-implement.md +3 -3
  13. package/template_project/.claude/commands/ukit/handoff-review.md +3 -3
  14. package/template_project/.claude/hooks/context-hardcap-gate.sh +47 -20
  15. package/template_project/.claude/hooks/context-window-guard.sh +82 -27
  16. package/template_project/.claude/hooks/handoff-resume.sh +11 -2
  17. package/template_project/.claude/hooks/mission-capture.mjs +37 -0
  18. package/template_project/.claude/hooks/post-compact-observe.mjs +34 -0
  19. package/template_project/.claude/hooks/shell-watch.mjs +34 -0
  20. package/template_project/.claude/hooks/stop-failure-rescue.mjs +109 -0
  21. package/template_project/.claude/settings.json +36 -4
  22. package/template_project/.claude/ukit/runtime/compact-threshold.mjs +15 -29
  23. package/template_project/.claude/ukit/runtime/context-capacity.mjs +64 -1
  24. package/template_project/.claude/ukit/runtime/execution-ledger.mjs +44 -3
  25. package/template_project/.claude/ukit/runtime/hook-chain-runner.mjs +20 -1
  26. package/template_project/.claude/ukit/runtime/mission/checkpoint.mjs +85 -0
  27. package/template_project/.claude/ukit/runtime/mission/classify.mjs +182 -0
  28. package/template_project/.claude/ukit/runtime/mission/drift.mjs +58 -0
  29. package/template_project/.claude/ukit/runtime/mission/graph.mjs +381 -0
  30. package/template_project/.claude/ukit/runtime/mission/hooks.mjs +199 -0
  31. package/template_project/.claude/ukit/runtime/mission/journal.mjs +68 -0
  32. package/template_project/.claude/ukit/runtime/mission/metrics.mjs +64 -0
  33. package/template_project/.claude/ukit/runtime/mission/recall.mjs +132 -0
  34. package/template_project/.claude/ukit/runtime/mission/redact.mjs +25 -0
  35. package/template_project/.claude/ukit/runtime/mission/restore.mjs +107 -0
  36. package/template_project/.claude/ukit/runtime/mission/store.mjs +231 -0
  37. package/template_project/.claude/ukit/runtime/mission/working.mjs +88 -0
  38. package/template_project/.claude/ukit/runtime/prompt-injection-cap.mjs +33 -0
  39. package/template_project/.claude/ukit/runtime/reinject-context.mjs +87 -6
  40. package/template_project/.claude/ukit/runtime/rescue/bundle.mjs +122 -0
  41. package/template_project/.claude/ukit/runtime/rescue/classify-failure.mjs +136 -0
  42. package/template_project/.claude/ukit/runtime/rescue/lease.mjs +65 -0
  43. package/template_project/.claude/ukit/runtime/rescue/reconstruct.mjs +273 -0
  44. package/template_project/.claude/ukit/runtime/rescue/recovery-state.mjs +120 -0
  45. package/template_project/.claude/ukit/runtime/rescue/rollover.mjs +151 -0
  46. package/template_project/.claude/ukit/runtime/sensitive-value-scanner.mjs +1 -1
  47. package/template_project/.claude/ukit/runtime/shell-watch.mjs +278 -0
  48. package/template_project/.claude/ukit/runtime/stop-coordinator.mjs +154 -0
  49. package/template_project/.omp/config.yml +2 -2
  50. package/template_project/.omp/hooks/pre/ukit-bridge.js +69 -2
  51. package/template_project/AGENTS.md +3 -1
  52. package/template_project/CLAUDE.md +3 -1
  53. package/template_project/docs/AI_HANDOFF/RULES.md +4 -4
  54. package/template_project/instructions/core.md +3 -1
  55. package/template_project/ukit/storage/config.json +32 -10
@@ -0,0 +1,109 @@
1
+ // stop-failure-rescue.mjs - StopFailure chain step (detect + record only, always code 0, fail-open).
2
+ // Classifies the failure, appends a redacted event to .ukit/storage/rescue/events.jsonl (rotates at
3
+ // 1 MiB) and advances the recovery state machine. Never writes prompt text or touches transcripts.
4
+ import fsp from 'node:fs/promises';
5
+ import path from 'node:path';
6
+ import crypto from 'node:crypto';
7
+ import { pathToFileURL, fileURLToPath } from 'node:url';
8
+
9
+ export const hookFailClosed = false;
10
+ const NONE = { code: 0, stdout: '', stderr: '' };
11
+ const MODULE_DIR = path.dirname(fileURLToPath(import.meta.url));
12
+ const RESCUE_DIR = path.join(MODULE_DIR, '..', 'ukit', 'runtime', 'rescue');
13
+ export const EVENTS_MAX_BYTES = 1024 * 1024;
14
+
15
+ const load = (name) => import(pathToFileURL(path.join(RESCUE_DIR, name)).href);
16
+
17
+ export async function appendEvent(root, event) {
18
+ const dir = path.join(root, '.ukit', 'storage', 'rescue');
19
+ const file = path.join(dir, 'events.jsonl');
20
+ await fsp.mkdir(dir, { recursive: true });
21
+ try {
22
+ const st = await fsp.stat(file);
23
+ if (st.size >= EVENTS_MAX_BYTES) await fsp.rename(file, `${file}.1`);
24
+ } catch { /* no file yet */ }
25
+ await fsp.appendFile(file, `${JSON.stringify(event)}\n`);
26
+ }
27
+
28
+ async function handle(ctx) {
29
+ const root = ctx.projectRoot || process.cwd();
30
+ const p = ctx.payload || {};
31
+ const cf = await load('classify-failure.mjs');
32
+ const rs = await load('recovery-state.mjs');
33
+ const input = { error: p.error, error_details: p.error_details, message: p.last_assistant_message ?? p.message, usage: p.usage };
34
+ const c = cf.classifyFailure(input);
35
+ const fp = cf.fingerprint(input);
36
+ // eventId: stable for an identical payload within the same session+minute -> duplicate hook events dedupe.
37
+ const sid = String(p.session_id || ctx.sessionId || '').slice(0, 64);
38
+ const eventId = crypto.createHash('sha1').update(`${sid}|${fp}|${p.turn_id ?? ''}|${Math.floor(Date.now() / 60000)}`).digest('hex').slice(0, 24);
39
+ const missionId = p.mission_id || undefined;
40
+
41
+ const cur = await rs.readState({ root, missionId });
42
+ let outcome;
43
+ if (c.action === 'block') {
44
+ outcome = await rs.transition({ root, missionId, from: cur.state, to: 'BLOCKED', eventId, reason: c.name, fingerprint: fp, failure: true });
45
+ } else if (c.action === 'none') {
46
+ outcome = { ok: true, applied: false };
47
+ } else if (cur.state === 'COMPACT_FAILED') {
48
+ outcome = await rs.recordFailure({ root, missionId, fingerprint: fp, eventId });
49
+ if (outcome.ok && outcome.applied && !outcome.open && c.action !== 'wait') {
50
+ outcome = await rs.transition({ root, missionId, from: 'COMPACT_FAILED', to: 'RECOVERING', eventId: `${eventId}:r`, reason: c.name, fingerprint: fp });
51
+ }
52
+ } else if (cur.state === 'HEALTHY' || cur.state === 'PRESSURE' || cur.state === 'CHECKPOINTED' || cur.state === 'COMPACTING' || cur.state === 'RECOVERING' || cur.state === 'ROLLOVER_PENDING') {
53
+ outcome = await rs.transition({ root, missionId, from: cur.state, to: 'COMPACT_FAILED', eventId, reason: c.name, fingerprint: fp, failure: true });
54
+ } else {
55
+ outcome = { ok: true, applied: false };
56
+ }
57
+
58
+ const redacted = cf.redact(`${typeof p.error_details === 'string' ? p.error_details : ''}`).slice(0, 200);
59
+ await appendEvent(root, {
60
+ ts: new Date().toISOString(), type: 'STOP_FAILURE', eventId, error: String(p.error || '').slice(0, 40),
61
+ cls: c.cls, name: c.name, action: c.action, retryable: c.retryable, flags: c.flags, fingerprint: fp,
62
+ byteRatio: Number(c.byteRatio.toFixed(3)), detail: redacted, transition: outcome?.ok ? (outcome.state || null) : outcome?.code || null,
63
+ });
64
+
65
+ try {
66
+ const ev = outcome?.ok && outcome.applied ? { COMPACT_FAILED: 'COMPACT_FAILED', RECOVERING: 'RECOVERY_STARTED' }[outcome.state] : null;
67
+ if (ev) await (await load('rollover.mjs')).emitRescueEvent(root, ev, { eventId, cls: c.cls, name: c.name });
68
+ } catch { /* event is best-effort */ }
69
+
70
+ // WP-R3: rollover/reconstruct-class failures also persist an offline restoration bundle (fail-open).
71
+ let rolloverNotice = '';
72
+ if (c.action === 'rollover' || c.action === 'reconstruct') {
73
+ try {
74
+ const rc = await load('reconstruct.mjs');
75
+ const bd = await load('bundle.mjs');
76
+ const recon = await rc.reconstructMission({ projectRoot: root, transcriptPath: p.transcript_path, sessionId: sid || undefined });
77
+ const bundle = bd.buildBundle(recon, { maxChars: 6000 });
78
+ const w = await bd.writeBundle(root, bundle);
79
+ await appendEvent(root, { ts: new Date().toISOString(), type: 'RESCUE_BUNDLE_WRITTEN', eventId, sha256: bundle.sha256.slice(0, 16), chars: bundle.text.length, reconcile: bundle.reconcile, file: path.basename(w.bundlePath) });
80
+ let ro = null;
81
+ try { ro = await load('rollover.mjs'); await ro.emitRescueEvent(root, 'OFFLINE_CONTEXT_REBUILT', { eventId, sha256: bundle.sha256.slice(0, 16), chars: bundle.text.length, reconcile: bundle.reconcile }); } catch { /* event is best-effort */ }
82
+ if (ro && c.action === 'rollover') {
83
+ let config = {};
84
+ try { config = JSON.parse(await fsp.readFile(path.join(root, '.ukit', 'storage', 'config.json'), 'utf8')); } catch { /* defaults */ }
85
+ const lease = await (await load('lease.mjs')).readLease(root).catch(() => null);
86
+ const state = await rs.readState({ root, missionId });
87
+ const r = await ro.maybeRollover({ projectRoot: root, config, state, lease, autonomy: config?.autonomy?.level, failure: c, fingerprint: fp, ownerStop: recon.ownerStop === true });
88
+ rolloverNotice = typeof r?.notice === 'string' ? r.notice.split('\n')[0] : '';
89
+ }
90
+ } catch { /* bundle is best-effort */ }
91
+ }
92
+
93
+ const rollover = c.action === 'rollover';
94
+ const stderr = rollover
95
+ ? `UKit rescue: context overflow detected (class ${c.cls}: ${c.name}). Your work is preserved; run \`ukit rescue\` or start a fresh session and UKit will reconstruct state on start.\n${rolloverNotice ? `${rolloverNotice}\n` : ''}`
96
+ : '';
97
+ return { code: 0, stdout: '', stderr };
98
+ }
99
+
100
+ export async function runHook(ctx = {}) {
101
+ try {
102
+ const deadlineMs = Number(ctx.deadlineMs || process.env.HOOK_DEADLINE_MS) || 2000;
103
+ let timer;
104
+ const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve(NONE), Math.max(100, deadlineMs - 100)); timer.unref?.(); });
105
+ return await Promise.race([handle(ctx), timeout]).finally(() => clearTimeout(timer));
106
+ } catch {
107
+ return NONE;
108
+ }
109
+ }
@@ -162,6 +162,16 @@
162
162
  }
163
163
  ]
164
164
  },
165
+ {
166
+ "matcher": "TodoWrite|TaskCreate|TaskUpdate",
167
+ "hooks": [
168
+ {
169
+ "type": "command",
170
+ "command": "node \"$CLAUDE_PROJECT_DIR/.claude/ukit/runtime/hook-chain-runner.mjs\" --emit-verdict - \"$CLAUDE_PROJECT_DIR/.claude/hooks/mission-capture.mjs\":8",
171
+ "timeout": 18
172
+ }
173
+ ]
174
+ },
165
175
  {
166
176
  "matcher": "Bash",
167
177
  "hooks": [
@@ -202,8 +212,8 @@
202
212
  "hooks": [
203
213
  {
204
214
  "type": "command",
205
- "command": "node \"$CLAUDE_PROJECT_DIR/.claude/ukit/runtime/hook-chain-runner.mjs\" --emit-verdict - \"$CLAUDE_PROJECT_DIR/.claude/hooks/sensitive-data-guard.mjs\":8 \"$CLAUDE_PROJECT_DIR/.claude/hooks/record-execution.mjs\":8 \"$CLAUDE_PROJECT_DIR/.claude/hooks/skill-router.sh\":20 \"$CLAUDE_PROJECT_DIR/.claude/hooks/vision-router.sh\":12 \"$CLAUDE_PROJECT_DIR/.claude/hooks/context-window-guard.sh\":10",
206
- "timeout": 68
215
+ "command": "node \"$CLAUDE_PROJECT_DIR/.claude/ukit/runtime/hook-chain-runner.mjs\" --emit-verdict - \"$CLAUDE_PROJECT_DIR/.claude/hooks/sensitive-data-guard.mjs\":8 \"$CLAUDE_PROJECT_DIR/.claude/hooks/record-execution.mjs\":8 \"$CLAUDE_PROJECT_DIR/.claude/hooks/skill-router.sh\":20 \"$CLAUDE_PROJECT_DIR/.claude/hooks/vision-router.sh\":12 \"$CLAUDE_PROJECT_DIR/.claude/hooks/context-window-guard.sh\":10 \"$CLAUDE_PROJECT_DIR/.claude/hooks/mission-capture.mjs\":8 \"$CLAUDE_PROJECT_DIR/.claude/hooks/shell-watch.mjs\":8",
216
+ "timeout": 84
207
217
  }
208
218
  ]
209
219
  }
@@ -219,6 +229,28 @@
219
229
  ]
220
230
  }
221
231
  ],
232
+ "StopFailure": [
233
+ {
234
+ "hooks": [
235
+ {
236
+ "type": "command",
237
+ "command": "node \"$CLAUDE_PROJECT_DIR/.claude/ukit/runtime/hook-chain-runner.mjs\" --emit-verdict - \"$CLAUDE_PROJECT_DIR/.claude/hooks/stop-failure-rescue.mjs\":8",
238
+ "timeout": 18
239
+ }
240
+ ]
241
+ }
242
+ ],
243
+ "PostCompact": [
244
+ {
245
+ "hooks": [
246
+ {
247
+ "type": "command",
248
+ "command": "node \"$CLAUDE_PROJECT_DIR/.claude/ukit/runtime/hook-chain-runner.mjs\" --emit-verdict - \"$CLAUDE_PROJECT_DIR/.claude/hooks/post-compact-observe.mjs\":8",
249
+ "timeout": 18
250
+ }
251
+ ]
252
+ }
253
+ ],
222
254
  "PreCompact": [
223
255
  {
224
256
  "hooks": [
@@ -235,8 +267,8 @@
235
267
  "hooks": [
236
268
  {
237
269
  "type": "command",
238
- "command": "node \"$CLAUDE_PROJECT_DIR/.claude/ukit/runtime/hook-chain-runner.mjs\" --emit-verdict - \"$CLAUDE_PROJECT_DIR/.claude/hooks/project-important.sh\":8 \"$CLAUDE_PROJECT_DIR/.claude/hooks/auto-prune-bash.sh\":12 \"$CLAUDE_PROJECT_DIR/.claude/hooks/reset-compact-pressure.sh\":12 \"$CLAUDE_PROJECT_DIR/.claude/hooks/handoff-resume.sh\":8 \"$CLAUDE_PROJECT_DIR/.claude/hooks/observability-emit.mjs\":8 \"$CLAUDE_PROJECT_DIR/.claude/hooks/session-episode-start.mjs\":8",
239
- "timeout": 70
270
+ "command": "node \"$CLAUDE_PROJECT_DIR/.claude/ukit/runtime/hook-chain-runner.mjs\" --emit-verdict - \"$CLAUDE_PROJECT_DIR/.claude/hooks/project-important.sh\":8 \"$CLAUDE_PROJECT_DIR/.claude/hooks/auto-prune-bash.sh\":12 \"$CLAUDE_PROJECT_DIR/.claude/hooks/reset-compact-pressure.sh\":12 \"$CLAUDE_PROJECT_DIR/.claude/hooks/handoff-resume.sh\":8 \"$CLAUDE_PROJECT_DIR/.claude/hooks/reinject-context.sh\":8 \"$CLAUDE_PROJECT_DIR/.claude/hooks/observability-emit.mjs\":8 \"$CLAUDE_PROJECT_DIR/.claude/hooks/session-episode-start.mjs\":8",
271
+ "timeout": 74
240
272
  }
241
273
  ]
242
274
  }
@@ -14,7 +14,7 @@ import {
14
14
  } from './token-utils.mjs';
15
15
  // Sibling runtime module: installs copy the whole runtime dir, so the negotiated-capacity
16
16
  // resolver is always present next to this file.
17
- import { resolveContextCapTokens } from './context-capacity.mjs';
17
+ import { resolveContextCapTokens, resolveContextTiers } from './context-capacity.mjs';
18
18
 
19
19
  const DEFAULT_MAX_PROMPT_ENTRIES = 12;
20
20
  const DEFAULT_MAX_OUTPUT_ENTRIES = 12;
@@ -488,38 +488,28 @@ export async function resolveCompactCapacity(config = {}, { record } = {}) {
488
488
  }
489
489
 
490
490
  export async function buildCompactThresholds(config = {}) {
491
- const explicitSoftThreshold = finiteNumber(config?.compact?.tokenThreshold, 0);
492
- const shippedHardCap = positiveInteger(config?.compact?.hardCapTokens, 235_000);
493
- // Upgrade safety: an install that predates compact.contextWindowTokens still carries the
494
- // old 500k hard cap; the cap must never sit above the declared window it guards.
495
- const declaredWindow = positiveInteger(config?.compact?.contextWindowTokens, 0);
496
- const effectiveShippedHardCap = declaredWindow > 0 ? Math.min(shippedHardCap, declaredWindow) : shippedHardCap;
497
- // Only tighten once a record exists: an install with no evidence yet (and every caller
498
- // that passes no project root) keeps the shipped tuning unchanged.
499
- const record = await readContextCapacityRecord(config?.projectRoot);
500
- const negotiated = record ? await resolveCompactCapacity(config, { record }) : null;
501
- const hardCapTokens = negotiated
502
- ? Math.max(1, Math.min(effectiveShippedHardCap, negotiated.capTokens))
503
- : effectiveShippedHardCap;
504
- // An explicit operator tokenThreshold is honoured but still clamped under the
505
- // negotiated cap: an advisory soft/hard pair sitting at or above hardCapTokens can
506
- // never fire, because context-hardcap-gate.sh already refuses tools at the cap
507
- // (C92-H-01 — on a default install tokenThreshold is the shipped 150k default, not a
508
- // real operator choice, so this is correcting a number, not overriding intent).
509
- const softThreshold = explicitSoftThreshold > 0
510
- ? Math.max(1, Math.min(explicitSoftThreshold, hardCapTokens - 1))
511
- : Math.max(1, Math.round(hardCapTokens * SOFT_TO_CAP_RATIO));
491
+ // UKit-owned tiers (compact.bestTokens/okTokens/mandatoryTokens/stopTokens, legacy
492
+ // hardCapTokens -> stopTokens, tokenThreshold -> bestTokens). They are deliberately NOT
493
+ // clamped to contextWindowTokens or the negotiated model window: the tiers are UKit
494
+ // policy, and the host auto-compaction window (rendered separately) keeps sessions below
495
+ // stopTokens. The capacity record is still read for diagnostics only.
496
+ const tiers = resolveContextTiers(config);
497
+ const hardCapTokens = tiers.stopTokens;
498
+ const softThreshold = Math.max(1, Math.min(tiers.bestTokens, hardCapTokens - 1));
512
499
  const hardThreshold = Math.min(
513
500
  hardCapTokens,
514
501
  Math.max(softThreshold + 1, Math.round(softThreshold * 1.6)),
515
502
  );
516
503
  const baselineTokens = Math.max(120, Math.min(18_000, Math.round(softThreshold * 0.18)));
504
+ const record = await readContextCapacityRecord(config?.projectRoot);
505
+ const negotiated = record ? await resolveCompactCapacity(config, { record }) : null;
517
506
 
518
507
  return {
519
508
  softThreshold,
520
509
  hardThreshold,
521
510
  baselineTokens,
522
511
  hardCapTokens,
512
+ tiers,
523
513
  capacitySource: negotiated?.capacity?.source ?? 'shipped',
524
514
  capacityTokens: negotiated?.capacity?.tokens ?? null,
525
515
  };
@@ -958,13 +948,9 @@ export async function buildCompactPressureState(rawState = null, config = {}) {
958
948
  const thresholds = await buildCompactThresholds(config);
959
949
  const rawSoftThreshold = finiteNumber(rawState?.softThreshold, 0);
960
950
  const rawHardThreshold = finiteNumber(rawState?.hardThreshold, 0);
961
- if (!finiteNumber(config?.compact?.tokenThreshold, 0) && rawSoftThreshold > 0) {
962
- // A persisted pair is only honoured while it still sits inside the negotiated cap.
963
- // The record outlives capacity negotiation: an install that ran before the record
964
- // existed, or before the model was verified, carries thresholds tuned for the
965
- // shipped 500k ceiling — restoring them re-pins the advisory ABOVE the live
966
- // hardCapTokens forever (C92-H-02). Falling through keeps the freshly derived
967
- // pair, which is also what the rewritten record persists, so the file self-heals.
951
+ if (!finiteNumber(config?.compact?.tokenThreshold, 0) && !finiteNumber(config?.compact?.bestTokens, 0) && rawSoftThreshold > 0) {
952
+ // A persisted pair is honoured only while it sits strictly inside stopTokens, so a stale
953
+ // record can never pin the advisory at/above the stop line (C92-H-02).
968
954
  if (rawSoftThreshold < thresholds.hardCapTokens) {
969
955
  thresholds.softThreshold = rawSoftThreshold;
970
956
  thresholds.hardThreshold = Math.min(
@@ -30,7 +30,7 @@ export const CAPACITY_ENV_VAR = 'UKIT_CONTEXT_WINDOW_TOKENS';
30
30
  export const DEFAULT_CAPACITY_TOKENS = 100_000;
31
31
  // The shipped operator ceiling (compact.hardCapTokens) — only ever an UPPER bound; negotiated
32
32
  // capacity can tighten it but never raise it.
33
- export const SHIPPED_HARD_CAP_TOKENS = 235_000;
33
+ export const SHIPPED_HARD_CAP_TOKENS = 185_000;
34
34
  // A verified window is only ever usable as an estimate: the response itself plus the
35
35
  // char/token estimator's own undercount must fit too, so only half the window becomes
36
36
  // the advisory cap (500k cap from a 1M window — the original tuning, made explicit).
@@ -149,3 +149,66 @@ export function resolveContextCapTokens({ env, config, modelMetadata } = {}) {
149
149
  capTokens: Math.max(1, Math.min(ceiling, derived)),
150
150
  };
151
151
  }
152
+
153
+ // ── UKit-owned context tiers ──
154
+ // UKit owns these four numbers (compact.bestTokens / okTokens / mandatoryTokens / stopTokens)
155
+ // and they do NOT depend on any model's context window:
156
+ // < best green silent
157
+ // best..ok yellow one-line advisory (delegate broad reads, short replies)
158
+ // ok..mandatory orange staying under mandatoryTokens is required: land, persist, delegate
159
+ // mandatory..stop red over the mandatory line: persist now; new work is blocked at stop
160
+ // >= stop stop the hard gate blocks new work except persist-to-disk writes; host
161
+ // auto-compaction (always automatic) fires and UKit restores the work.
162
+ // Legacy keys keep working: compact.hardCapTokens maps to stopTokens and
163
+ // compact.tokenThreshold maps to bestTokens WHEN SET (they win over the new keys, so an
164
+ // install that pinned them behaves as before; delete them to adopt the shipped tiers).
165
+ export const DEFAULT_CONTEXT_TIERS = Object.freeze({
166
+ bestTokens: 100_000,
167
+ okTokens: 150_000,
168
+ mandatoryTokens: 200_000,
169
+ stopTokens: 250_000,
170
+ });
171
+
172
+ function positiveInt(value) {
173
+ return typeof value === 'number' && Number.isFinite(value) && Number.isInteger(value) && value > 0
174
+ ? value
175
+ : null;
176
+ }
177
+
178
+ export function resolveContextTiers(config = {}) {
179
+ const compact = config?.compact ?? {};
180
+ const stop = positiveInt(compact.hardCapTokens) ?? positiveInt(compact.stopTokens) ?? DEFAULT_CONTEXT_TIERS.stopTokens;
181
+ const mandatory = Math.min(positiveInt(compact.mandatoryTokens) ?? DEFAULT_CONTEXT_TIERS.mandatoryTokens, stop);
182
+ const ok = Math.min(positiveInt(compact.okTokens) ?? DEFAULT_CONTEXT_TIERS.okTokens, mandatory);
183
+ const best = Math.min(positiveInt(compact.tokenThreshold) ?? positiveInt(compact.bestTokens) ?? DEFAULT_CONTEXT_TIERS.bestTokens, ok);
184
+ return { bestTokens: best, okTokens: ok, mandatoryTokens: mandatory, stopTokens: stop };
185
+ }
186
+
187
+ // -> 'green' | 'yellow' | 'orange' | 'red' | 'stop'
188
+ export function classifyContextTier(tokens, tiers = DEFAULT_CONTEXT_TIERS) {
189
+ const value = Number(tokens);
190
+ if (!Number.isFinite(value)) return 'green';
191
+ if (value >= tiers.stopTokens) return 'stop';
192
+ if (value >= tiers.mandatoryTokens) return 'red';
193
+ if (value >= tiers.okTokens) return 'orange';
194
+ if (value >= tiers.bestTokens) return 'yellow';
195
+ return 'green';
196
+ }
197
+
198
+ // One-line tier text, shared by the prompt guard and the tool gate. Compaction is always
199
+ // automatic: no tier ever asks the user to run /compact.
200
+ export function contextTierMessage(tier, tokens, tiers = DEFAULT_CONTEXT_TIERS) {
201
+ const n = Math.round(Number(tokens) || 0).toLocaleString('en-US');
202
+ switch (tier) {
203
+ case 'yellow':
204
+ return `UKit context ~${n} tokens (OK): prefer delegating broad reads to subagents and keep replies short.`;
205
+ case 'orange':
206
+ return `UKit context ~${n} tokens (MANDATORY zone ${tiers.okTokens.toLocaleString('en-US')}-${tiers.mandatoryTokens.toLocaleString('en-US')}): staying under ${tiers.mandatoryTokens.toLocaleString('en-US')} is required. Land the current item, defer the rest to docs/STATUS.md or handoff tasks, delegate broad work, start nothing new inline.`;
207
+ case 'red':
208
+ return `UKit context ~${n} tokens: over the mandatory ${tiers.mandatoryTokens.toLocaleString('en-US')} line - land and persist state to disk now; new work is blocked at ${tiers.stopTokens.toLocaleString('en-US')}. Host auto-compaction is automatic; do not ask the user to /compact.`;
209
+ case 'stop':
210
+ return `STOP new work: context >=${tiers.stopTokens.toLocaleString('en-US')} (~${n}) - persist state to disk now (STATUS/handoff); the host auto-compaction will fire and UKit restores the work after it - do not ask the user to /compact.`;
211
+ default:
212
+ return '';
213
+ }
214
+ }
@@ -19,7 +19,9 @@ import { operationCompletionPolicy, foldOperationEvidence, compactOperation, con
19
19
 
20
20
  const LEDGER_VERSION = 1;
21
21
  const RESUME_INTENT_VERSION = 1;
22
- const RESUME_INTENT_TTL_MS = 30 * 60 * 1000;
22
+ // Cross-session reuse bound only. A same-session compaction restore (`compact: true` read)
23
+ // ignores age: multi-hour runs compact long after the intent's PreCompact write.
24
+ const RESUME_INTENT_TTL_MS = 24 * 60 * 60 * 1000;
23
25
  const MAX_RECEIPTS = 24;
24
26
  // TASK-005 (FR-005): bounded OutcomeRecord dedupe slot — a resumable-run
25
27
  // pointer (interrupted run) emits `outcome.observed` once per task; replays
@@ -482,13 +484,17 @@ export async function readResumableExecution(projectRoot, payload = {}) {
482
484
  return { state, ledger, sessionId };
483
485
  }
484
486
 
485
- export async function readResumeIntent(projectRoot, payload = {}, { consume = false, now = Date.now() } = {}) {
487
+ export async function readResumeIntent(projectRoot, payload = {}, { consume = false, now = Date.now(), compact = false } = {}) {
486
488
  const sessionId = explicitSessionId(payload);
487
489
  if (!sessionId) return null;
488
490
  const intent = await readJson(resumeIntentPath(projectRoot, sessionId), null);
489
491
  if (!intent || intent.version !== RESUME_INTENT_VERSION) return null;
490
492
  if (intent.sessionKey !== safeSegment(sessionId) || intent.sessionHash !== resumeSessionHash(sessionId)) return null;
491
- if (!intent.promptKey || !intent.requestKey || !Number.isFinite(intent.expiresAt) || intent.expiresAt <= now) return null;
493
+ if (!intent.promptKey || !intent.requestKey) return null;
494
+ // The file is keyed by session id and re-checked against sessionHash above, so a compact
495
+ // read is same-session by construction: age is irrelevant there.
496
+ if (!compact && (!Number.isFinite(intent.expiresAt) || intent.expiresAt <= now)) return null;
497
+ if (intent.cwd && intent.cwd !== projectRoot) return null;
492
498
 
493
499
  const state = await readRouteState(projectRoot, payload);
494
500
  const ledger = await readExecutionLedger(projectRoot, payload);
@@ -515,6 +521,39 @@ export async function readResumeIntent(projectRoot, payload = {}, { consume = fa
515
521
  return intent;
516
522
  }
517
523
 
524
+ // Durable mission snapshot persisted at PreCompact so the post-compaction session can
525
+ // re-orient without the host summary: goal, contract, evidence, next step, git state.
526
+ function resumeIntentSnapshot(state, ledger, cwd) {
527
+ const routing = state?.routingContext || {};
528
+ const goal = String(routing.lastExplicitUserPromptText ?? routing.promptText ?? '').slice(0, 4000);
529
+ const contract = state?.routeSummary?.executionContract?.taskKind
530
+ || state?.routeSummary?.taskKind || state?.routeSummary?.executionMode || null;
531
+ let unmet = [];
532
+ let reason = '';
533
+ try {
534
+ if (state?.routeSummary?.executionContract?.taskKind) {
535
+ const verdict = evaluateCompletion({ state, ledger, cwd });
536
+ unmet = verdict.missingEvidence || [];
537
+ reason = String(verdict.reason || '').slice(0, 400);
538
+ } else {
539
+ unmet = requiredEvidence(state).filter((item) => !evidenceSatisfied(item, ledger, state));
540
+ }
541
+ } catch { /* snapshot is best-effort; the identity fields above stay authoritative */ }
542
+ const observed = [ledger?.sourceSucceeded && 'source-read', ledger?.writeSucceeded && 'write-receipt',
543
+ ledger?.verificationSucceeded && 'verification-receipt'].filter(Boolean);
544
+ const dirty = gitOutputRaw(['status', '--porcelain'], cwd);
545
+ return {
546
+ goal,
547
+ contract,
548
+ observedEvidence: observed,
549
+ unmetEvidence: unmet.slice(0, 12),
550
+ nextStep: unmet.length
551
+ ? `Produce the missing evidence (${unmet.slice(0, 6).join(', ')}) for the goal above${reason ? ` — ${reason}` : ''}`
552
+ : 'Re-check completion evidence against the goal, then finish or continue the next missing milestone',
553
+ git: { head: gitOutputRaw(['rev-parse', 'HEAD'], cwd), dirtyFiles: dirty ? dirty.split('\n').length : 0 },
554
+ };
555
+ }
556
+
518
557
  export async function writeResumeIntent(projectRoot, payload = {}, { now = Date.now() } = {}) {
519
558
  const sessionId = explicitSessionId(payload);
520
559
  if (!sessionId) return null;
@@ -533,6 +572,8 @@ export async function writeResumeIntent(projectRoot, payload = {}, { now = Date.
533
572
  taskInstanceId: state.taskInstanceId || null,
534
573
  requestKey: ledger.requestKey,
535
574
  routeFingerprint: state.fingerprint || null,
575
+ cwd: projectRoot,
576
+ ...resumeIntentSnapshot(state, ledger, projectRoot),
536
577
  createdAt: now,
537
578
  expiresAt: now + RESUME_INTENT_TTL_MS,
538
579
  };
@@ -16,6 +16,7 @@ let recordAllowedSuccess = () => 0;
16
16
  try { ({ adviseOnBlock, recordAllowedSuccess } = await import('./block-breaker.mjs')); } catch { /* advisory only */ }
17
17
  // TASK-019: chain rows and direct-hook rows share one versioned schema and one
18
18
  // append API (hook-telemetry.mjs) — including safeName for session files.
19
+ import { capPromptInjection, DEFAULT_MAX_PROMPT_INJECTION_CHARS } from './prompt-injection-cap.mjs';
19
20
  import { appendTelemetryRow, recordHookTiming, TELEMETRY_VERSION } from './hook-telemetry.mjs';
20
21
  // TASK-018 review fix round 1: the chain budget is resolved by ONE shared module
21
22
  // so the runner's inner deadline and the bridge's outer pi.exec timeout can never
@@ -224,6 +225,24 @@ function coalesceJsonStdout(text) {
224
225
  return `${JSON.stringify(merged)}\n`;
225
226
  }
226
227
 
228
+ function readPromptInjectionCap(projectRoot) {
229
+ try {
230
+ const cfg = JSON.parse(fs.readFileSync(path.join(projectRoot, '.ukit', 'storage', 'config.json'), 'utf8'));
231
+ const n = Number(cfg?.compact?.maxPromptInjectionChars);
232
+ return Number.isFinite(n) && n > 0 ? n : DEFAULT_MAX_PROMPT_INJECTION_CHARS;
233
+ } catch { return DEFAULT_MAX_PROMPT_INJECTION_CHARS; }
234
+ }
235
+
236
+ function capPromptOutput(out, payloadText, firstScriptArg) {
237
+ try {
238
+ const payload = JSON.parse(payloadText || '{}');
239
+ if (payload?.hook_event_name !== 'UserPromptSubmit') return out;
240
+ const first = firstScriptArg ? parseScriptArg(firstScriptArg).scriptPath : '';
241
+ const projectRoot = first ? path.resolve(path.dirname(first), '../..') : (payload.cwd || process.cwd());
242
+ return capPromptInjection(out, readPromptInjectionCap(projectRoot));
243
+ } catch { return out; }
244
+ }
245
+
227
246
  // B1 (TASK-001, SPEC §FR-001): a child that emits a `hookSpecificOutput`
228
247
  // permission decision owns the verdict. `hookSpecificOutput` alone is NOT
229
248
  // enough — a child killed mid-write can carry the marker in a truncated
@@ -980,7 +999,7 @@ try {
980
999
  else process.stderr.write(breakerAdvice(`${last.scriptName} blocked (exit 2) with no reason`));
981
1000
  process.exitCode = 2;
982
1001
  } else {
983
- process.stdout.write(coalesceJsonStdout(`${contextStdout}${last.stdout || ''}`));
1002
+ process.stdout.write(capPromptOutput(coalesceJsonStdout(`${contextStdout}${last.stdout || ''}`), payloadText, scriptPaths[0]));
984
1003
  // A spawn-unavailable `last` carries only the warning already written above.
985
1004
  if (last.stderr && last.failureKind !== 'spawn-unavailable') process.stderr.write(last.stderr);
986
1005
  process.exitCode = last.code === 0 ? 0 : (lastIsFailClosed ? 2 : 0);
@@ -0,0 +1,85 @@
1
+ // Mission semantic checkpoint (WP3). Contract:
2
+ // writeCheckpoint({projectRoot, missionId, trigger, git, graph?, now?}) -> Promise<checkpoint|null>
3
+ // writes <mid>/checkpoints/<seq>.json atomically (tmp+rename), keeps the last 5, never throws.
4
+ // latestCheckpoint(projectRoot, missionId) -> checkpoint|null
5
+ // Checkpoint {v,seq,ts,graphRev,trigger,objective:{promptId,text},facts[{text,src}],activeReqIds,decisions[{id,text,status}],
6
+ // hypotheses[],assumptions[],pending[],failures[],restrictions[],activeTaskId,nextAction,git:{head,branch,dirty},
7
+ // stop:{ownerStop,blockers[]}}
8
+ // Typed buckets never merge. facts come ONLY from verified ACs that hold ac.evidence; a hypothesis linked to an AC
9
+ // (acId) moves to facts only when that AC has evidence. Planned/unverified work is listed under pending, never as done.
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { loadGraph } from './graph.mjs';
13
+ import { listPrompts } from './journal.mjs';
14
+ import { missionDir, readJsonFile, writeJsonAtomicFile } from './store.mjs';
15
+ import { activeTaskOf, buildWorkingMemory, readMemoryItems } from './working.mjs';
16
+
17
+ export const KEEP_CHECKPOINTS = 5;
18
+ const num = (id) => Number(String(id).replace(/\D/g, '')) || 0;
19
+ const dirOf = (projectRoot, mid) => path.join(missionDir(projectRoot, mid), 'checkpoints');
20
+
21
+ function seqs(projectRoot, mid) {
22
+ try { return fs.readdirSync(dirOf(projectRoot, mid)).filter((f) => /^\d+\.json$/.test(f)).map((f) => num(f)).sort((a, b) => a - b); } catch { return []; }
23
+ }
24
+
25
+ export function latestCheckpoint(projectRoot, missionId) {
26
+ const all = seqs(projectRoot, missionId);
27
+ for (let i = all.length - 1; i >= 0; i -= 1) {
28
+ const c = readJsonFile(path.join(dirOf(projectRoot, missionId), `${all[i]}.json`), null);
29
+ if (c) return c;
30
+ }
31
+ return null;
32
+ }
33
+
34
+ export function buildBuckets(g, items, prompts) {
35
+ const first = prompts.find((p) => p.origin === 'user');
36
+ const facts = [];
37
+ for (const ac of Object.values(g.state.acs)) {
38
+ const ev = ac.status === 'verified' ? (ac.evidence || [])[ac.evidence.length - 1] : null;
39
+ if (ev) facts.push({ text: `${ac.id} verified: ${g.acText(ac)}`.slice(0, 200), src: `${ev.kind}:${ev.ref}` });
40
+ }
41
+ const verifiedAc = (id) => id && g.state.acs[id]?.status === 'verified' && (g.state.acs[id].evidence || []).length > 0;
42
+ const hypotheses = [];
43
+ for (const h of items.hypotheses) {
44
+ if (verifiedAc(h.acId)) { const ev = g.state.acs[h.acId].evidence.slice(-1)[0]; facts.push({ text: h.text, src: `${ev.kind}:${ev.ref}` }); } else hypotheses.push({ id: h.id, text: h.text });
45
+ }
46
+ const live = Object.values(g.state.reqs).filter((r) => (r.status === 'active' || r.status === 'conflict') && r.kind !== 'question');
47
+ const pending = Object.values(g.state.tasks).filter((t) => !['verified', 'cancelled'].includes(t.status))
48
+ .sort((a, b) => num(a.id) - num(b.id)).slice(0, 40).map((t) => ({ id: t.id, status: t.status, title: t.title.slice(0, 100) }));
49
+ const lastUser = [...prompts].reverse().find((p) => p.origin === 'user');
50
+ const restrictions = Object.values(g.state.reqs).filter((r) => (r.kind === 'prohibition' || r.kind === 'constraint') && r.status !== 'superseded')
51
+ .slice(0, 20).map((r) => ({ id: r.id, text: r.text.slice(0, 160), promptId: r.promptId }));
52
+ return {
53
+ objective: first ? { promptId: first.promptId, text: first.text.slice(0, 300) } : { promptId: null, text: '' },
54
+ facts: facts.slice(-40), hypotheses: hypotheses.slice(-20), pending, restrictions,
55
+ activeReqIds: live.map((r) => r.id).slice(0, 60),
56
+ decisions: items.decisions.slice(-30).map((d) => ({ id: d.id, text: d.text, status: d.status || 'accepted' })),
57
+ assumptions: items.assumptions.slice(-20).map((a) => ({ id: a.id, text: a.text })),
58
+ failures: items.failures.slice(-20).map((f) => ({ id: f.id, text: f.text })),
59
+ stop: {
60
+ ownerStop: Boolean(lastUser?.ownerStop),
61
+ blockers: Object.entries(g.state.blockers).map(([taskId, b]) => ({ taskId, code: b.code, reason: String(b.reason || '').slice(0, 120) })).slice(0, 20),
62
+ },
63
+ };
64
+ }
65
+
66
+ export async function writeCheckpoint({ projectRoot, missionId, trigger = 'manual', git = {}, graph, now = Date.now() } = {}) {
67
+ try {
68
+ const g = graph || await loadGraph({ projectRoot, missionId });
69
+ const items = readMemoryItems(projectRoot, missionId);
70
+ const b = buildBuckets(g, items, listPrompts(projectRoot, missionId));
71
+ const working = await buildWorkingMemory({ projectRoot, missionId, graph: g, now });
72
+ const all = seqs(projectRoot, missionId);
73
+ const seq = (all[all.length - 1] || 0) + 1;
74
+ const cp = {
75
+ v: 1, seq, ts: now, graphRev: g.state.rev, trigger, ...b,
76
+ activeTaskId: activeTaskOf(g)?.id || null, nextAction: working?.nextAction || '',
77
+ git: { head: git.head || null, branch: git.branch || null, dirty: Boolean(git.dirty) },
78
+ };
79
+ writeJsonAtomicFile(path.join(dirOf(projectRoot, missionId), `${seq}.json`), cp);
80
+ for (const old of seqs(projectRoot, missionId).slice(0, -KEEP_CHECKPOINTS)) {
81
+ try { fs.unlinkSync(path.join(dirOf(projectRoot, missionId), `${old}.json`)); } catch { /* */ }
82
+ }
83
+ return cp;
84
+ } catch { return null; }
85
+ }