@ngockhoale/ukit 3.5.17 → 3.5.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/manifests/platform.full.yaml +48 -0
  3. package/package.json +1 -1
  4. package/scripts/audit/field-replay.mjs +7 -7
  5. package/scripts/audit/field-telemetry.mjs +4 -3
  6. package/scripts/release/run-core-batch.mjs +10 -0
  7. package/src/cli/commands/mission.js +102 -0
  8. package/src/cli/commands/rescue.js +83 -0
  9. package/src/cli/index.js +14 -0
  10. package/src/core/compact/contextBudget.js +62 -41
  11. package/src/core/compact/threshold.js +14 -32
  12. package/src/core/observability/schema/registry.js +91 -0
  13. package/src/core/runtimeConfig.js +53 -2
  14. package/src/render/buildVariables.js +2 -5
  15. package/template_project/.claude/commands/ukit/handoff-implement.md +3 -3
  16. package/template_project/.claude/commands/ukit/handoff-review.md +3 -3
  17. package/template_project/.claude/hooks/context-hardcap-gate.sh +47 -20
  18. package/template_project/.claude/hooks/context-window-guard.sh +82 -27
  19. package/template_project/.claude/hooks/handoff-resume.sh +11 -2
  20. package/template_project/.claude/hooks/mission-capture.mjs +37 -0
  21. package/template_project/.claude/hooks/post-compact-observe.mjs +34 -0
  22. package/template_project/.claude/hooks/sensitive-data-guard.mjs +35 -3
  23. package/template_project/.claude/hooks/shell-watch.mjs +34 -0
  24. package/template_project/.claude/hooks/stop-failure-rescue.mjs +109 -0
  25. package/template_project/.claude/settings.json +36 -4
  26. package/template_project/.claude/ukit/index/test-batches-adapters.mjs +8 -3
  27. package/template_project/.claude/ukit/index/test-batches.mjs +80 -28
  28. package/template_project/.claude/ukit/runtime/compact-threshold.mjs +15 -29
  29. package/template_project/.claude/ukit/runtime/context-capacity.mjs +64 -1
  30. package/template_project/.claude/ukit/runtime/execution-ledger.mjs +44 -3
  31. package/template_project/.claude/ukit/runtime/hook-chain-runner.mjs +20 -1
  32. package/template_project/.claude/ukit/runtime/loop-state.mjs +17 -2
  33. package/template_project/.claude/ukit/runtime/mission/checkpoint.mjs +85 -0
  34. package/template_project/.claude/ukit/runtime/mission/classify.mjs +182 -0
  35. package/template_project/.claude/ukit/runtime/mission/drift.mjs +58 -0
  36. package/template_project/.claude/ukit/runtime/mission/graph.mjs +381 -0
  37. package/template_project/.claude/ukit/runtime/mission/hooks.mjs +199 -0
  38. package/template_project/.claude/ukit/runtime/mission/journal.mjs +68 -0
  39. package/template_project/.claude/ukit/runtime/mission/metrics.mjs +64 -0
  40. package/template_project/.claude/ukit/runtime/mission/recall.mjs +132 -0
  41. package/template_project/.claude/ukit/runtime/mission/redact.mjs +25 -0
  42. package/template_project/.claude/ukit/runtime/mission/restore.mjs +107 -0
  43. package/template_project/.claude/ukit/runtime/mission/store.mjs +231 -0
  44. package/template_project/.claude/ukit/runtime/mission/working.mjs +88 -0
  45. package/template_project/.claude/ukit/runtime/prompt-injection-cap.mjs +33 -0
  46. package/template_project/.claude/ukit/runtime/reinject-context.mjs +87 -6
  47. package/template_project/.claude/ukit/runtime/rescue/bundle.mjs +122 -0
  48. package/template_project/.claude/ukit/runtime/rescue/classify-failure.mjs +136 -0
  49. package/template_project/.claude/ukit/runtime/rescue/lease.mjs +65 -0
  50. package/template_project/.claude/ukit/runtime/rescue/reconstruct.mjs +273 -0
  51. package/template_project/.claude/ukit/runtime/rescue/recovery-state.mjs +120 -0
  52. package/template_project/.claude/ukit/runtime/rescue/rollover.mjs +151 -0
  53. package/template_project/.claude/ukit/runtime/sensitive-value-scanner.mjs +1 -1
  54. package/template_project/.claude/ukit/runtime/shell-watch.mjs +294 -0
  55. package/template_project/.claude/ukit/runtime/stop-coordinator.mjs +154 -0
  56. package/template_project/.omp/config.yml +2 -2
  57. package/template_project/.omp/hooks/pre/ukit-bridge.js +69 -2
  58. package/template_project/AGENTS.md +4 -2
  59. package/template_project/CLAUDE.md +4 -2
  60. package/template_project/docs/AI_HANDOFF/RULES.md +4 -4
  61. package/template_project/instructions/core.md +4 -2
  62. package/template_project/ukit/storage/config.json +32 -10
@@ -0,0 +1,151 @@
1
+ // rollover.mjs - hard session rollover planner/executor (WP-R4). Consumes ONLY latest.json/bundlePath
2
+ // written by bundle.mjs. planRollover decides; executeRollover performs (spawn is injected so tests never
3
+ // start claude). Once per epoch via an exclusive-create marker; never during owner STOP / open breaker.
4
+ import fs from 'node:fs';
5
+ import fsp from 'node:fs/promises';
6
+ import path from 'node:path';
7
+ import crypto from 'node:crypto';
8
+ import { spawn as nodeSpawn } from 'node:child_process';
9
+ import { breakerStatus, readState, transition } from './recovery-state.mjs';
10
+ import { redact } from './classify-failure.mjs';
11
+
12
+ export const BOOTSTRAP_PROMPT = 'Resume the UKit mission from the restore bundle above. Do not repeat denied operations; do not push/publish; verify git state first.';
13
+ export const DEFAULT_MAX_TURNS = 40;
14
+ export const EVENT_TYPES = Object.freeze([
15
+ 'CONTEXT_PRESSURE_DETECTED', 'CHECKPOINT_SAVED', 'COMPACT_STARTED', 'COMPACT_SUCCEEDED', 'COMPACT_FAILED',
16
+ 'RECOVERY_STARTED', 'OFFLINE_CONTEXT_REBUILT', 'SESSION_ROLLOVER_STARTED', 'SESSION_ROLLOVER_SUCCEEDED',
17
+ 'SESSION_RESTORED', 'MISSION_CONTINUED', 'RECOVERY_BLOCKED', 'MISSION_COMPLETED_VERIFIED',
18
+ ]);
19
+
20
+ const rescueDir = (root) => path.join(root, '.ukit', 'storage', 'rescue');
21
+ const epochMarker = (root, epoch) => path.join(rescueDir(root), `rollover-epoch-${epoch}.json`);
22
+
23
+ /** Append a redacted rescue event (same events.jsonl the StopFailure hook uses). Fail-open. */
24
+ export async function emitRescueEvent(root, type, payload = {}) {
25
+ try {
26
+ const dir = rescueDir(root);
27
+ await fsp.mkdir(dir, { recursive: true });
28
+ const safe = {};
29
+ for (const [k, v] of Object.entries(payload)) safe[k] = typeof v === 'string' ? redact(v).slice(0, 200) : v;
30
+ await fsp.appendFile(path.join(dir, 'events.jsonl'), `${JSON.stringify({ ts: new Date().toISOString(), type, ...safe })}\n`);
31
+ return true;
32
+ } catch { return false; }
33
+ }
34
+
35
+ export async function readLatestBundle(root) {
36
+ try {
37
+ const latest = JSON.parse(await fsp.readFile(path.join(rescueDir(root), 'latest.json'), 'utf8'));
38
+ if (!latest?.bundlePath) return null;
39
+ const p = path.isAbsolute(latest.bundlePath) ? latest.bundlePath : path.join(root, latest.bundlePath);
40
+ return { ...latest, bundlePath: p };
41
+ } catch { return null; }
42
+ }
43
+
44
+ /** 'auto' => on only for free-run / vibecode / unattended. */
45
+ export function rolloverEnabled({ config = {}, autonomy } = {}) {
46
+ const mode = config?.rescue?.autoRollover ?? 'auto';
47
+ if (mode === 'on' || mode === true) return true;
48
+ if (mode === 'off' || mode === false) return false;
49
+ const level = typeof autonomy === 'string' ? autonomy : autonomy?.level ?? config?.autonomy?.level;
50
+ return level === 'free-run' || level === 'vibecode' || config?.orchestration?.permissionMode === 'unattended';
51
+ }
52
+
53
+ const noticeFor = (uuid, bundlePath, spawned) => (spawned
54
+ ? `UKit rescue: continue in a fresh session with: claude --resume ${uuid}`
55
+ : `UKit rescue: start a fresh session with: claude --session-id ${uuid}${bundlePath ? ` (restore bundle: ${bundlePath})` : ''}`);
56
+
57
+ /**
58
+ * planRollover({projectRoot, config, state, lease, autonomy, failure?, fingerprint?, ownerStop?, now?, uuid?})
59
+ * -> {action:'spawn'|'notice'|'none', argv, sessionId, reason, notice?, bundlePath?, epoch?, command?}
60
+ * `failure` = classifyFailure() result (falls back to state.failure).
61
+ */
62
+ export async function planRollover({ projectRoot, config = {}, state = {}, lease = null, autonomy, failure, fingerprint, ownerStop = false, now = Date.now(), uuid } = {}) {
63
+ const none = (reason, extra = {}) => ({ action: 'none', argv: null, sessionId: null, reason, ...extra });
64
+ const st = state || {};
65
+ if (ownerStop || st.state === 'PAUSED_OWNER_STOP') return none('owner-stop');
66
+ if (st.state === 'BLOCKED') return none('blocked');
67
+ const f = failure || st.failure || null;
68
+ if (f?.action === 'block') return none('blocked', { blocked: true });
69
+ if (!f || f.action !== 'rollover') return none('class-not-rollover-eligible');
70
+
71
+ const fps = fingerprint ? [fingerprint] : Object.keys(st.breaker || {});
72
+ if (fps.some((fp) => breakerStatus(st, fp, now).open)) return none('breaker-open');
73
+
74
+ const sessionId = uuid || crypto.randomUUID();
75
+ const bundle = projectRoot ? await readLatestBundle(projectRoot) : null;
76
+ const notice = (spawned) => noticeFor(sessionId, bundle?.bundlePath, spawned);
77
+ if (!rolloverEnabled({ config, autonomy })) return { action: 'notice', argv: null, sessionId, reason: 'auto-rollover-off', notice: notice(false), bundlePath: bundle?.bundlePath || null };
78
+ if (!lease || !(lease.expiresAt > now)) return { action: 'notice', argv: null, sessionId, reason: 'lease-not-held', notice: notice(false), bundlePath: bundle?.bundlePath || null };
79
+ if (!bundle) return { action: 'notice', argv: null, sessionId, reason: 'no-bundle', notice: notice(false), bundlePath: null };
80
+ try { await fsp.access(epochMarker(projectRoot, lease.epoch)); return none('already-rolled-over-this-epoch', { epoch: lease.epoch }); } catch { /* not yet */ }
81
+
82
+ let text;
83
+ try { text = await fsp.readFile(bundle.bundlePath, 'utf8'); } catch { return { action: 'notice', argv: null, sessionId, reason: 'bundle-unreadable', notice: notice(false), bundlePath: bundle.bundlePath }; }
84
+ const maxTurns = Number.isInteger(config?.rescue?.maxTurns) && config.rescue.maxTurns > 0 ? config.rescue.maxTurns : DEFAULT_MAX_TURNS;
85
+ const argv = ['claude', '-p', '--session-id', sessionId, '--append-system-prompt', text, '--max-turns', String(maxTurns), '--output-format', 'stream-json', '--verbose', BOOTSTRAP_PROMPT];
86
+ return { action: 'spawn', argv, sessionId, reason: 'rollover-eligible', notice: notice(true), bundlePath: bundle.bundlePath, epoch: lease.epoch, fingerprint };
87
+ }
88
+
89
+ async function advance(root, missionId, from, path_, eventBase, fingerprint) {
90
+ let cur = from;
91
+ for (const to of path_) {
92
+ const r = await transition({ root, missionId, from: cur, to, eventId: `${eventBase}:${to}`, reason: 'rollover', fingerprint });
93
+ if (!r.ok) return { ok: false, at: cur, code: r.code };
94
+ cur = to;
95
+ }
96
+ return { ok: true, state: cur };
97
+ }
98
+
99
+ /**
100
+ * executeRollover(plan, {spawn, projectRoot, missionId?}) -> {spawned, pid?, notice, reason}
101
+ * Spawns detached + unref'd with output redirected to rollover-<uuid>.jsonl; claims the epoch first (wx).
102
+ */
103
+ export async function executeRollover(plan, { spawn = nodeSpawn, projectRoot, missionId } = {}) {
104
+ const root = projectRoot || plan?.projectRoot;
105
+ if (!plan || !root) return { spawned: false, reason: 'invalid-plan' };
106
+ if (plan.action === 'none') {
107
+ if (plan.blocked || plan.reason === 'blocked') await emitRescueEvent(root, 'RECOVERY_BLOCKED', { reason: plan.reason });
108
+ return { spawned: false, reason: plan.reason, notice: plan.notice || null };
109
+ }
110
+ if (plan.action === 'notice') return { spawned: false, reason: plan.reason, notice: plan.notice };
111
+
112
+ // Exclusive epoch claim: a second caller for the same epoch cannot spawn.
113
+ try {
114
+ await fsp.mkdir(rescueDir(root), { recursive: true });
115
+ await fsp.writeFile(epochMarker(root, plan.epoch), JSON.stringify({ sessionId: plan.sessionId, at: Date.now() }), { flag: 'wx' });
116
+ } catch (error) {
117
+ if (error?.code === 'EEXIST') return { spawned: false, reason: 'already-rolled-over-this-epoch', notice: plan.notice };
118
+ return { spawned: false, reason: 'epoch-claim-failed', notice: plan.notice };
119
+ }
120
+
121
+ const [cmd, ...args] = plan.argv;
122
+ let fd = null;
123
+ try {
124
+ fd = fs.openSync(path.join(rescueDir(root), `rollover-${plan.sessionId}.jsonl`), 'a');
125
+ const cur = await readState({ root, missionId });
126
+ const steps = { RECOVERING: ['RECONSTRUCTED', 'ROLLOVER_PENDING'], RECONSTRUCTED: ['ROLLOVER_PENDING'] }[cur.state] || [];
127
+ await advance(root, missionId, cur.state, steps, `rollover:${plan.sessionId}`, plan.fingerprint);
128
+ await emitRescueEvent(root, 'SESSION_ROLLOVER_STARTED', { sessionId: plan.sessionId, epoch: plan.epoch });
129
+ const child = spawn(cmd, args, { cwd: root, detached: true, stdio: ['ignore', fd, fd] });
130
+ child?.on?.('error', () => {});
131
+ child?.unref?.();
132
+ const after = await readState({ root, missionId });
133
+ if (after.state === 'ROLLOVER_PENDING') await advance(root, missionId, 'ROLLOVER_PENDING', ['ROLLED_OVER'], `rollover:${plan.sessionId}`, plan.fingerprint);
134
+ await emitRescueEvent(root, 'SESSION_ROLLOVER_SUCCEEDED', { sessionId: plan.sessionId, epoch: plan.epoch, pid: child?.pid ?? null });
135
+ return { spawned: true, pid: child?.pid ?? null, sessionId: plan.sessionId, reason: plan.reason, notice: plan.notice };
136
+ } catch (error) {
137
+ await emitRescueEvent(root, 'RECOVERY_BLOCKED', { reason: `spawn-failed:${error?.code || 'error'}` });
138
+ return { spawned: false, reason: 'spawn-failed', notice: noticeFor(plan.sessionId, plan.bundlePath, false) };
139
+ } finally {
140
+ if (fd !== null) { try { fs.closeSync(fd); } catch { /* already closed */ } }
141
+ }
142
+ }
143
+
144
+ /** One-call helper for hooks (R3 stop-failure-rescue): plan + execute; never throws. */
145
+ export async function maybeRollover(input, opts = {}) {
146
+ try {
147
+ const plan = await planRollover(input);
148
+ const result = await executeRollover(plan, { projectRoot: input.projectRoot, ...opts });
149
+ return { plan, ...result };
150
+ } catch { return { plan: null, spawned: false, reason: 'error' }; }
151
+ }
@@ -33,7 +33,7 @@ function sha256(value) {
33
33
  // AKIA/ASIA/AIza prefixes are pure base64-compatible text, so an encoded blob
34
34
  // can contain a coincidental key-shaped substring — those rules must stand
35
35
  // alone with no base64/base64url character on either side.
36
- const TOKEN_PATTERNS = [
36
+ export const TOKEN_PATTERNS = [
37
37
  { label: 'OpenAI/Anthropic-style API key', re: /\bsk-(?:proj-|ant-|svc-|acct-|admin-)?[A-Za-z0-9_-]{20,}/g },
38
38
  { label: 'AWS access key id', re: /(?<![A-Za-z0-9+/_-])(?:AKIA|ASIA)[0-9A-Z]{16}(?![A-Za-z0-9+/_-])/g },
39
39
  { label: 'GitHub token', re: /\bgh[pousr]_[A-Za-z0-9]{30,}\b/g },
@@ -0,0 +1,294 @@
1
+ // shell-watch.mjs - on every user prompt, find hung/orphaned shells and stalled host
2
+ // background tasks, auto-kill only deterministic hangs, and emit an ACTION directive.
3
+ //
4
+ // Suspects (one `ps`, bounded 300 ms):
5
+ // (a) self-matching wait loops: shell `-c` with until/while + `pgrep -f` (never ends,
6
+ // the pattern matches the loop's own command line). Auto-killed when owned by the
7
+ // current user and older than staleMinutes (config shellWatch.autoKillSelfMatchingLoops).
8
+ // (b) agent-launched shells older than staleMinutes running a loop/wait
9
+ // (while/until/tail -f/sleep): Claude Code marker `.claude/shell-snapshots/snapshot-`,
10
+ // or a generic `sh|bash|zsh -c` loop whose parent is PID 1 (orphaned). Codex and omp
11
+ // expose no known command-line marker: only the generic orphan rule covers them.
12
+ // (c) orphaned (ppid 1) vitest/jest/mocha older than staleMinutes.
13
+ // (d) stalled Claude Code background tasks: `<tmp>/claude-<uid>/<slug>/<session>/tasks/*.output`
14
+ // whose (symlink-resolved) mtime is older than staleMinutes while the transcript
15
+ // is unfinished (last message is not a final assistant turn).
16
+ // Report-only except (a). Fail-open: any error -> no output. Result cached ~60 s.
17
+ // Engines: Claude Code + omp share the UserPromptSubmit chain step (hooks/shell-watch.mjs);
18
+ // Codex has no hook surface (not covered); omp does not use the Claude tasks dir (no task scan).
19
+ import fs from 'node:fs';
20
+ import fsp from 'node:fs/promises';
21
+ import os from 'node:os';
22
+ import path from 'node:path';
23
+ import { execFile } from 'node:child_process';
24
+
25
+ export const DEFAULTS = Object.freeze({
26
+ enabled: true,
27
+ staleMinutes: 20,
28
+ autoKillSelfMatchingLoops: true,
29
+ });
30
+ const CACHE_TTL_MS = 60_000;
31
+ const PS_TIMEOUT_MS = 300;
32
+ const MAX_CMD = 100;
33
+ const SNAPSHOT_MARKER = '.claude/shell-snapshots/snapshot-';
34
+
35
+ export function resolveConfig(config) {
36
+ const c = config && typeof config.shellWatch === 'object' && config.shellWatch ? config.shellWatch : {};
37
+ const stale = Number(c.staleMinutes);
38
+ return {
39
+ enabled: c.enabled !== false,
40
+ staleMinutes: Number.isFinite(stale) && stale > 0 ? stale : DEFAULTS.staleMinutes,
41
+ autoKillSelfMatchingLoops: c.autoKillSelfMatchingLoops !== false,
42
+ };
43
+ }
44
+
45
+ export function redact(text) {
46
+ return String(text)
47
+ .replace(/\b(sk|pk|rk)-[A-Za-z0-9_-]{8,}/g, '[redacted]')
48
+ .replace(/\bgh[pousr]_[A-Za-z0-9]{10,}/g, '[redacted]')
49
+ .replace(/Bearer\s+\S+/gi, 'Bearer [redacted]')
50
+ .replace(/\b([A-Za-z0-9_.-]*(?:key|token|secret|password|passwd|pwd|auth)[A-Za-z0-9_.-]*)(\s*[=:]\s*)("[^"]*"|'[^']*'|\S+)/gi, '$1$2[redacted]')
51
+ .replace(/\b[0-9a-fA-F]{32,}\b/g, '[redacted]')
52
+ .replace(/[A-Za-z0-9+/_-]{40,}={0,2}/g, '[redacted]');
53
+ }
54
+
55
+ function brief(command) {
56
+ const one = redact(command.replace(/\s+/g, ' ').trim());
57
+ return one.length > MAX_CMD ? `${one.slice(0, MAX_CMD)}...` : one;
58
+ }
59
+
60
+ export function parseEtimeMinutes(etime) {
61
+ const m = /^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)$/.exec(String(etime || '').trim());
62
+ if (!m) return null;
63
+ const [, d = 0, h = 0, mi, s] = m;
64
+ return Number(d) * 1440 + Number(h) * 60 + Number(mi) + Number(s) / 60;
65
+ }
66
+
67
+ const fmtAge = (min) => (min >= 60 ? `${Math.floor(min / 60)}h${String(Math.floor(min % 60)).padStart(2, '0')}m` : `${Math.floor(min)}m`);
68
+
69
+ export function parsePs(text) {
70
+ const rows = [];
71
+ for (const line of String(text || '').split('\n')) {
72
+ const m = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.*)$/.exec(line);
73
+ if (!m) continue;
74
+ const ageMin = parseEtimeMinutes(m[4]);
75
+ if (ageMin === null) continue;
76
+ rows.push({ pid: Number(m[1]), ppid: Number(m[2]), uid: Number(m[3]), ageMin, command: m[5] });
77
+ }
78
+ return rows;
79
+ }
80
+
81
+ const SHELL_C_RE = /(?:^|[\s/])(?:sh|bash|zsh|dash)\s+(?:-\w+\s+)*-\w*c\b/;
82
+ const LOOP_RE = /\b(?:while|until)\b|\btail\s+-[A-Za-z]*f|\bsleep\s+\d/;
83
+ const SELF_MATCH_RE = /\bpgrep\s+(?:-\w*f\w*|--full)\b/;
84
+ const RUNNER_RE = /\b(?:vitest|jest|mocha)\b/;
85
+
86
+ function excluded(row, selfSet, uid) {
87
+ if (selfSet.has(row.pid)) return true;
88
+ if (uid !== null && row.uid !== uid) return true;
89
+ const c = row.command.trimStart();
90
+ return c.startsWith('-') || /^(?:\S*\/)?login\s+-f/.test(c) || /\bps\s+-[A-Za-z]*o\b/.test(c.slice(0, 40));
91
+ }
92
+
93
+ function selfTree(rows, selfPid) {
94
+ const set = new Set([selfPid]);
95
+ const byPid = new Map(rows.map((r) => [r.pid, r]));
96
+ for (let p = byPid.get(selfPid)?.ppid, n = 0; p > 1 && !set.has(p) && n < 64; n += 1) {
97
+ set.add(p);
98
+ p = byPid.get(p)?.ppid;
99
+ }
100
+ let grew = true;
101
+ while (grew) {
102
+ grew = false;
103
+ for (const r of rows) if (!set.has(r.pid) && set.has(r.ppid) && r.ppid > 1) { set.add(r.pid); grew = true; }
104
+ }
105
+ return set;
106
+ }
107
+
108
+ // Agent host processes (Claude Code / codex / omp). A shell whose ancestor chain reaches a live
109
+ // host outside our own tree belongs to ANOTHER live session: never kill or report it.
110
+ const HOST_RE = /^(?:\S*\/)?(?:claude|codex|omp)(?:\s|$)|^(?:\S*\/)?node\s+(?:\S+\s+)*\S*\/(?:claude|codex|omp)(?:\.m?js)?(?:\s|$)/;
111
+ function ownedByOtherLiveHost(row, byPid, selfSet) {
112
+ for (let p = row.ppid, n = 0; p > 1 && n < 64; n += 1) {
113
+ if (selfSet.has(p)) return false;
114
+ const a = byPid.get(p);
115
+ if (!a) return false;
116
+ if (HOST_RE.test(a.command.trimStart())) return true;
117
+ p = a.ppid;
118
+ }
119
+ return false;
120
+ }
121
+
122
+ /** Pure classification of ps rows -> [{ kind, pid, ageMin, text, deterministic }]. */
123
+ export function classifyShells(rows, { staleMinutes, uid = null, selfPid = process.pid }) {
124
+ const selfSet = selfTree(rows, selfPid);
125
+ const byPid = new Map(rows.map((r) => [r.pid, r]));
126
+ const out = [];
127
+ for (const row of rows) {
128
+ if (excluded(row, selfSet, uid)) continue;
129
+ if (ownedByOtherLiveHost(row, byPid, selfSet)) continue; // another live session's shell: skip, never kill
130
+ const cmd = row.command;
131
+ const isShell = SHELL_C_RE.test(cmd) || cmd.includes(SNAPSHOT_MARKER);
132
+ const old = row.ageMin >= staleMinutes;
133
+ if (isShell && /\b(?:until|while)\b/.test(cmd) && SELF_MATCH_RE.test(cmd)) {
134
+ out.push({ kind: 'shell', pid: row.pid, ageMin: row.ageMin, text: brief(cmd), deterministic: old });
135
+ } else if (isShell && old && LOOP_RE.test(cmd) && (cmd.includes(SNAPSHOT_MARKER) || row.ppid === 1)) {
136
+ out.push({ kind: 'shell', pid: row.pid, ageMin: row.ageMin, text: brief(cmd), deterministic: false });
137
+ } else if (old && row.ppid === 1 && RUNNER_RE.test(cmd) && !isShell) {
138
+ out.push({ kind: 'runner', pid: row.pid, ageMin: row.ageMin, text: brief(cmd), deterministic: false });
139
+ }
140
+ }
141
+ return out;
142
+ }
143
+
144
+ async function lastTurnFinished(file) {
145
+ let fh;
146
+ try {
147
+ fh = await fsp.open(file, 'r');
148
+ const { size } = await fh.stat();
149
+ const len = Math.min(size, 65536);
150
+ const buf = Buffer.alloc(len);
151
+ await fh.read(buf, 0, len, size - len);
152
+ const lines = buf.toString('utf8').split('\n').filter(Boolean).reverse();
153
+ for (const l of lines) {
154
+ let j;
155
+ try { j = JSON.parse(l); } catch { continue; }
156
+ if (j?.type !== 'assistant' && j?.type !== 'user') continue;
157
+ if (j.type === 'user') {
158
+ // An interrupted subagent is terminal (dead), not hung — nothing left to kill or finish.
159
+ const c = j.message?.content;
160
+ const text = typeof c === 'string' ? c : Array.isArray(c) ? c.map((p) => p?.text || '').join(' ') : '';
161
+ return /^\s*\[Request interrupted by user/.test(text);
162
+ }
163
+ const stop = j.message?.stop_reason;
164
+ return stop !== 'tool_use' && stop != null;
165
+ }
166
+ return true; // undeterminable: conservative, never flag
167
+ } catch {
168
+ return true;
169
+ } finally {
170
+ await fh?.close().catch(() => {});
171
+ }
172
+ }
173
+
174
+ export function claudeTaskDirs(projectRoot, uid, tmpRoots = ['/tmp', os.tmpdir()]) {
175
+ const slug = path.resolve(projectRoot).replace(/[^A-Za-z0-9]/g, '-');
176
+ const dirs = [];
177
+ for (const root of new Set(tmpRoots)) {
178
+ const base = path.join(root, `claude-${uid}`, slug);
179
+ let sessions = [];
180
+ try { sessions = fs.readdirSync(base); } catch { continue; }
181
+ for (const s of sessions.slice(0, 40)) dirs.push(path.join(base, s, 'tasks'));
182
+ }
183
+ return dirs;
184
+ }
185
+
186
+ /** Stalled Claude Code background tasks: stale mtime + unfinished transcript. */
187
+ export async function findStalledTasks({ taskDirs, now, staleMinutes, deadline }) {
188
+ const out = [];
189
+ const maxAgeMs = 7 * 864e5;
190
+ let budget = 120;
191
+ for (const dir of taskDirs) {
192
+ let names;
193
+ try { names = await fsp.readdir(dir); } catch { continue; }
194
+ for (const n of names) {
195
+ if (!n.endsWith('.output') || budget <= 0 || Date.now() > deadline) continue;
196
+ budget -= 1;
197
+ try {
198
+ const f = path.join(dir, n);
199
+ const st = await fsp.stat(f); // follows the symlink to the live transcript
200
+ const idleMs = now - st.mtimeMs;
201
+ if (idleMs < staleMinutes * 60_000 || idleMs > maxAgeMs) continue;
202
+ if (!(await fsp.lstat(f)).isSymbolicLink()) continue; // plain bash output has no completion marker
203
+ if (await lastTurnFinished(f)) continue;
204
+ out.push({ kind: 'task', id: n.replace(/\.output$/, ''), ageMin: idleMs / 60_000, text: 'host background task (subagent)' });
205
+ } catch { /* skip entry */ }
206
+ }
207
+ }
208
+ return out;
209
+ }
210
+
211
+ const defaultReadPs = () => new Promise((resolve) => {
212
+ execFile('ps', ['-Ao', 'pid=,ppid=,uid=,etime=,command='], { timeout: PS_TIMEOUT_MS, maxBuffer: 4 * 1024 * 1024 }, (err, stdout) => {
213
+ resolve(err ? null : String(stdout));
214
+ });
215
+ });
216
+
217
+ export function formatDirective(pending, killed) {
218
+ const items = pending.map((s) => (s.kind === 'task'
219
+ ? `- task ${s.id} (${fmtAge(s.ageMin)} idle): ${s.text}`
220
+ : `- ${s.kind} pid ${s.pid} (${fmtAge(s.ageMin)}): ${s.text}`));
221
+ const lines = [];
222
+ const tail = 'Do not leave pending work across days.';
223
+ if (pending.length === 0) {
224
+ lines.push(`[ukit-shell-watch] ACTION before the new prompt: auto-killed ${killed.length} self-matching pgrep -f wait loop(s): pid ${killed.map((k) => k.pid).join(', ')} (log .ukit/storage/logs/shell-watch.log).`);
225
+ lines.push(`Re-run or finish the work they were doing (relaunch with a correct wait: pidfile/\`kill -0 <pid>\`, never \`pgrep -f\`), and report what was cleaned up. ${tail}`);
226
+ return lines.join('\n');
227
+ }
228
+ lines.push(`[ukit-shell-watch] ACTION before the new prompt: ${pending.length} hung shell(s)/stalled task(s):`);
229
+ if (killed.length) lines.push(`Auto-killed ${killed.length} self-matching pgrep -f loop(s): pid ${killed.map((k) => k.pid).join(', ')}.`);
230
+ const room = killed.length ? 1 : 2;
231
+ if (items.length <= room) lines.push(...items);
232
+ else lines.push(...items.slice(0, room - 1), `- +${items.length - room + 1} more`);
233
+ lines.push(`Kill the hung ones (\`kill <pid>\`; TaskStop for host tasks), then re-run or finish the work they were doing (relaunch with a correct wait: pidfile/\`kill -0 <pid>\`, never \`pgrep -f\`), and report what was cleaned up. ${tail}`);
234
+ return lines.join('\n');
235
+ }
236
+
237
+ async function logKill(projectRoot, entry) {
238
+ try {
239
+ const dir = path.join(projectRoot, '.ukit', 'storage', 'logs');
240
+ await fsp.mkdir(dir, { recursive: true });
241
+ await fsp.appendFile(path.join(dir, 'shell-watch.log'), `${JSON.stringify(entry)}\n`);
242
+ } catch { /* logging is best-effort */ }
243
+ }
244
+
245
+ /**
246
+ * @returns {Promise<string>} directive text, or '' when nothing is found / disabled / any error.
247
+ * Injectables for tests: readPs, killer, now, uid, selfPid, taskDirs, platform.
248
+ */
249
+ export async function runShellWatch({
250
+ projectRoot, config, readPs = defaultReadPs, killer = (pid) => process.kill(pid, 'SIGTERM'),
251
+ now = Date.now(), uid = typeof process.getuid === 'function' ? process.getuid() : null,
252
+ selfPid = process.pid, taskDirs, platform = process.platform, useCache = true,
253
+ }) {
254
+ try {
255
+ const cfg = resolveConfig(config);
256
+ if (!cfg.enabled || platform === 'win32') return '';
257
+ const cacheFile = path.join(projectRoot, '.ukit', 'storage', 'cache', 'shell-watch.json');
258
+ if (useCache) {
259
+ try {
260
+ const c = JSON.parse(await fsp.readFile(cacheFile, 'utf8'));
261
+ if (typeof c?.at === 'number' && now - c.at >= 0 && now - c.at < CACHE_TTL_MS && typeof c.text === 'string') return c.text;
262
+ } catch { /* no cache */ }
263
+ }
264
+ const deadline = Date.now() + 250;
265
+ const psText = await readPs();
266
+ if (typeof psText !== 'string') return '';
267
+ const suspects = classifyShells(parsePs(psText), { staleMinutes: cfg.staleMinutes, uid, selfPid });
268
+ const killed = [];
269
+ const pending = [];
270
+ for (const s of suspects) {
271
+ if (s.deterministic && cfg.autoKillSelfMatchingLoops && s.pid > 1 && s.pid !== selfPid) {
272
+ try {
273
+ await killer(s.pid);
274
+ killed.push(s);
275
+ await logKill(projectRoot, { at: new Date(now).toISOString(), pid: s.pid, ageMin: Math.round(s.ageMin), reason: 'self-matching pgrep -f loop', command: s.text });
276
+ continue;
277
+ } catch { /* fall through to directive-only */ }
278
+ }
279
+ pending.push(s);
280
+ }
281
+ const dirs = taskDirs ?? claudeTaskDirs(projectRoot, uid);
282
+ pending.push(...await findStalledTasks({ taskDirs: dirs, now, staleMinutes: cfg.staleMinutes, deadline: deadline + 150 }));
283
+ const text = pending.length || killed.length ? formatDirective(pending, killed) : '';
284
+ if (useCache) {
285
+ try {
286
+ await fsp.mkdir(path.dirname(cacheFile), { recursive: true });
287
+ await fsp.writeFile(cacheFile, JSON.stringify({ at: now, text }));
288
+ } catch { /* cache is best-effort */ }
289
+ }
290
+ return text;
291
+ } catch {
292
+ return '';
293
+ }
294
+ }
@@ -3122,12 +3122,149 @@ export async function stopCoordinationInput({ projectRoot, payload = {}, authori
3122
3122
  return stopInputKey();
3123
3123
  }
3124
3124
 
3125
+ // ─── Mission continuity gate (WP5) ────────────────────────────────────────
3126
+ // Advisory-first and fail-open: it can only turn an already-released stop into a bounded continuation,
3127
+ // never relaxes an existing block, and never traps the user (owner STOP is handled before this runs).
3128
+ export const MISSION_GATE_MAX_BLOCKS = 20;
3129
+ export const MISSION_GATE_MAX_SAME = 2;
3130
+ const MISSION_DRIFT_ACTIONABLE = new Set(['req-without-task', 'stale-ac', 'stale-done-unverified', 'write-to-verified-paths']);
3131
+
3132
+ async function newestPassingVerification(projectRoot) {
3133
+ try {
3134
+ const dir = path.join(projectRoot, '.ukit', 'storage', 'cache', 'exec-ledger');
3135
+ const names = (await fs.readdir(dir)).filter((f) => f.endsWith('.json') && f !== 'gate-crash-counter.json').slice(0, 64);
3136
+ let newest = null; let ms = -1;
3137
+ for (const n of names) {
3138
+ try { const st = await fs.stat(path.join(dir, n)); if (st.mtimeMs > ms) { ms = st.mtimeMs; newest = n; } } catch { /* vanished */ }
3139
+ }
3140
+ if (!newest) return null;
3141
+ const receipts = JSON.parse(await fs.readFile(path.join(dir, newest), 'utf8'))?.receipts;
3142
+ if (!Array.isArray(receipts)) return null;
3143
+ for (let i = receipts.length - 1; i >= 0; i -= 1) {
3144
+ const r = receipts[i];
3145
+ if (!r || r.kind !== 'verification') continue;
3146
+ if (r.success === true && r.verdict?.kind !== 'failed' && r.verdict?.kind !== 'unproven') {
3147
+ const ts = Date.parse(r.verdict?.ts || r.ts || '') || 0;
3148
+ return { ts, ref: `receipt:${crypto.createHash('sha1').update(`${r.command || ''}|${ts}`).digest('hex').slice(0, 12)}` };
3149
+ }
3150
+ return null; // newest verification failed/unproven: no evidence
3151
+ }
3152
+ } catch { /* no ledger */ }
3153
+ return null;
3154
+ }
3155
+
3156
+ async function missionGateEmit(projectRoot, type, payload) {
3157
+ try { await (await import('./rescue/rollover.mjs')).emitRescueEvent(projectRoot, type, payload); } catch { /* observability is best-effort */ }
3158
+ }
3159
+
3160
+ /**
3161
+ * @param {object} merged coordinated decision (after pretool reconciliation)
3162
+ * @returns {Promise<object>} merged, possibly converted to a bounded mission-continuation block; never throws
3163
+ */
3164
+ export async function evaluateMissionGate({ merged, projectRoot, payload = {}, ownerStop = false, now = Date.now() } = {}) {
3165
+ try {
3166
+ if (ownerStop || !merged) return merged;
3167
+ // Never double-block or relax: any existing block / terminal release stands as is.
3168
+ if (merged.decision === 'block' || merged.loopBreak === true || merged.pretoolBlocked === true || merged.blockedOutcome === true) return merged;
3169
+ let config = null;
3170
+ try { config = JSON.parse(await fs.readFile(path.join(projectRoot, '.ukit', 'storage', 'config.json'), 'utf8')); } catch { /* defaults */ }
3171
+ if (config?.mission?.enabled === false) return merged;
3172
+ const store = await import('./mission/store.mjs');
3173
+ const sid = String(payload?.session_id || payload?.sessionId || 'default').replace(/[^A-Za-z0-9_.-]/g, '_').slice(0, 80) || 'default';
3174
+ const active = store.readActive(projectRoot);
3175
+ const mid = active?.sessions?.[sid]?.missionId || active?.activeMissionId;
3176
+ if (!mid) return merged;
3177
+ const gm = await import('./mission/graph.mjs');
3178
+ const g = await gm.loadGraph({ projectRoot, missionId: mid });
3179
+ const live = (r) => (r.status === 'active' || r.status === 'conflict') && r.kind !== 'question';
3180
+ if (!Object.values(g.state.reqs).some(live)) return merged;
3181
+
3182
+ // Ledger evidence: a passing verification receipt newer than the task's done claim verifies its ACs.
3183
+ const receipt = await newestPassingVerification(projectRoot);
3184
+ if (receipt) {
3185
+ let head = null;
3186
+ try { head = spawnSync('git', ['rev-parse', 'HEAD'], { cwd: projectRoot, encoding: 'utf8', timeout: 700 }).stdout?.trim() || null; } catch { /* no git */ }
3187
+ let changed = false;
3188
+ for (const t of Object.values(g.state.tasks)) {
3189
+ if (t.status !== 'done_unverified' || (t.ts || 0) > receipt.ts) continue;
3190
+ for (const acId of t.acIds || []) {
3191
+ const ac = g.state.acs[acId];
3192
+ if (!ac || ac.status === 'verified' || (ac.evidence || []).some((e) => e.ref === receipt.ref)) continue;
3193
+ if (g.recordEvidence(acId, { kind: 'receipt', ref: receipt.ref, gitRev: head, ts: receipt.ts })) changed = true;
3194
+ }
3195
+ }
3196
+ if (changed) await gm.persistGraph(g, { projectRoot, missionId: mid });
3197
+ }
3198
+
3199
+ const done = g.isComplete();
3200
+ if (done.complete) {
3201
+ await missionGateEmit(projectRoot, 'MISSION_COMPLETED_VERIFIED', { missionId: mid });
3202
+ return merged;
3203
+ }
3204
+ const drift = (await import('./mission/drift.mjs')).detectDrift(g, { now })
3205
+ .filter((f) => f.severity === 'warn' && MISSION_DRIFT_ACTIONABLE.has(f.code));
3206
+ const ready = g.readySet();
3207
+ // Work claimed done but never verified still needs a verification step (evidence, not claims, closes an AC).
3208
+ const unverified = Object.values(g.state.tasks).filter((t) => t.status === 'done_unverified' && !g.state.blockers?.[t.id]);
3209
+ const items = [
3210
+ ...ready.map((t) => `${t.id} ${String(t.title).slice(0, 80)}`),
3211
+ ...unverified.map((t) => `verify ${t.id} ${String(t.title).slice(0, 60)}`),
3212
+ ...drift.map((f) => `${f.code} ${f.ref}`),
3213
+ ];
3214
+ const advise = (text) => ({ ...merged, systemMessage: [merged.systemMessage, text].filter(Boolean).join('\n') });
3215
+ if (!items.length) {
3216
+ const blocked = Object.keys(g.state.blockers || {});
3217
+ if (!blocked.length) return merged;
3218
+ await missionGateEmit(projectRoot, 'RECOVERY_BLOCKED', { missionId: mid, blockedTasks: blocked.length });
3219
+ return advise(`[ukit-mission] BLOCKED: ${done.missing.length} requirement(s) unverified; remaining work is blocked (${blocked.slice(0, 3).join(', ')}) with no READY independent task. Stop released; report the blockers verbatim.`);
3220
+ }
3221
+
3222
+ // Bounded: same unresolved state at most MISSION_GATE_MAX_SAME times, MISSION_GATE_MAX_BLOCKS per mission,
3223
+ // and the loop-breaker (policyOwner 'mission-gate') counts these blocks too.
3224
+ const gateFile = path.join(store.missionDir(projectRoot, mid), 'gate.json');
3225
+ const st = store.readJsonFile(gateFile, null) || { blocks: 0, sig: '', same: 0 };
3226
+ const sig = crypto.createHash('sha1').update(`${g.state.rev}|${items.join(',')}`).digest('hex').slice(0, 12);
3227
+ const same = sig === st.sig ? (st.same || 0) + 1 : 0;
3228
+ if (same >= MISSION_GATE_MAX_SAME || (st.blocks || 0) >= MISSION_GATE_MAX_BLOCKS) {
3229
+ await missionGateEmit(projectRoot, 'RECOVERY_BLOCKED', { missionId: mid, reason: 'no-progress' });
3230
+ return advise(`[ukit-mission] stop released: no mission progress since the last continuation (${items.length} item(s) still open). Not approval; ${done.missing.length} requirement(s) remain unverified.`);
3231
+ }
3232
+ try { store.writeJsonAtomicFile(gateFile, { blocks: (st.blocks || 0) + 1, sig, same, ts: now }); } catch { /* counter is best-effort */ }
3233
+ await missionGateEmit(projectRoot, 'MISSION_CONTINUED', { missionId: mid, ready: ready.length, unverified: unverified.length, drift: drift.length });
3234
+ const named = items.slice(0, 3).join('; ');
3235
+ return {
3236
+ ...merged,
3237
+ decision: 'block',
3238
+ reason: `UKit mission continuity: ${done.missing.length} requirement(s) (${done.missing.slice(0, 3).join(', ')}) lack verified acceptance evidence. Next: ${named}${items.length > 3 ? ` (+${items.length - 3} more)` : ''}. Continue the mission, or state BLOCKED with the reason; todo-completed or planned work is not verification.`,
3239
+ policyOwner: 'mission-gate',
3240
+ policies: [...(merged.policies || []), 'mission-gate'],
3241
+ };
3242
+ } catch {
3243
+ return merged;
3244
+ }
3245
+ }
3246
+
3125
3247
  // ─── Orchestration ────────────────────────────────────────────────────────
3126
3248
  /**
3127
3249
  * One coordinator invocation: event guard → once-per-stop dedupe → completion
3128
3250
  * evaluator (once) → watchdog evaluator (once) → ordered merge. Returns
3129
3251
  * `{ skip, merged }`; `skip` is a reason string when nothing may be emitted.
3130
3252
  */
3253
+ /** Rescue integration: returns the active rescue state (RECOVERING/ROLLOVER_PENDING) or null. Never throws. */
3254
+ export async function rescueStopGate({ projectRoot, ownerStop = false } = {}) {
3255
+ try {
3256
+ const rs = await import('./rescue/recovery-state.mjs');
3257
+ const st = await rs.readState({ root: projectRoot });
3258
+ if (ownerStop) {
3259
+ if (st.state !== 'PAUSED_OWNER_STOP' && st.state !== 'BLOCKED') {
3260
+ await rs.transition({ root: projectRoot, from: st.state, to: 'PAUSED_OWNER_STOP', eventId: `owner-stop:${st.version}:${st.state}`, reason: 'owner-stop' });
3261
+ }
3262
+ return null;
3263
+ }
3264
+ return st.state === 'RECOVERING' || st.state === 'ROLLOVER_PENDING' ? st.state : null;
3265
+ } catch { return null; }
3266
+ }
3267
+
3131
3268
  export async function runStopCoordinator({
3132
3269
  projectRoot,
3133
3270
  payload = {},
@@ -3210,6 +3347,20 @@ export async function runStopCoordinator({
3210
3347
  } catch { /* advisory lane: detection failure never changes the stop */ }
3211
3348
 
3212
3349
  const ownerStop = await releaseForOwnerStop({ projectRoot, payload });
3350
+ // Context rescue (fail-open): owner STOP wins over recovery; while recovering/rolling over, release with an advisory.
3351
+ const rescueGate = await rescueStopGate({ projectRoot, ownerStop: !!ownerStop });
3352
+ if (rescueGate && !ownerStop) {
3353
+ return {
3354
+ skip: null,
3355
+ merged: {
3356
+ decision: null,
3357
+ terminalOutcome: 'WAIT_FOR_APPROVAL',
3358
+ systemMessage: `[ukit-stop-coordinator] stop released: context rescue is ${rescueGate} outside this session; no continuation is forced. Run \`ukit rescue status\` to follow it.`,
3359
+ policyOwner: 'context-rescue',
3360
+ policies: ['context-rescue'],
3361
+ },
3362
+ };
3363
+ }
3213
3364
  if (ownerStop) {
3214
3365
  return {
3215
3366
  skip: null,
@@ -3350,6 +3501,9 @@ export async function runStopCoordinator({
3350
3501
  } catch { /* advisory: reconciliation failure keeps the original decision */ }
3351
3502
  }
3352
3503
 
3504
+ // Mission continuity gate (WP5): fail-open, advisory-first; owner STOP already released above.
3505
+ merged = await evaluateMissionGate({ merged, projectRoot, payload, ownerStop: false, now });
3506
+
3353
3507
  // Bounded loop detection (fail-closed infra block keeps its own cap).
3354
3508
  try {
3355
3509
  const loop = await import('./loop-state.mjs');
@@ -129,8 +129,8 @@ memory:
129
129
  # Keys VERIFIED against omp v18.8.9 (`omp config get compaction.<key>`):
130
130
  # thresholdTokens is a fixed token limit that overrides thresholdPercent when > 0
131
131
  # (omp default -1).
132
- # thresholdTokens = min(90000, Claude Code auto-compact window), so a small-context
133
- # budget is never exceeded by the omp threshold. Starting default, not a hard limit:
132
+ # thresholdTokens = compact.ompCompactionThresholdTokens (170000, inside the 150k-200k band
133
+ # and clamped to the host auto-compact window); compaction is always automatic. Starting default, not a hard limit:
134
134
  # edit any value here and `ukit update` keeps it. The legacy shipped 350000 is migrated
135
135
  # only when UKit's install ledger proves UKit wrote it; `ukit uninstall` reverts just
136
136
  # UKit's own additions and keeps your edits. Auto-compact must still trigger BEFORE