@ngockhoale/ukit 3.5.15 → 3.5.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +25 -0
- package/manifests/platform.full.yaml +48 -0
- package/package.json +2 -1
- package/scripts/release/heavy-first.mjs +12 -0
- package/scripts/release/release-steps.mjs +7 -4
- package/scripts/release/run-core-batch.mjs +50 -0
- 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/diagnostics/routeOutcomes.js +5 -1
- package/src/diagnostics/skillAccuracy.js +5 -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/delegation-gate.mjs +1 -1
- 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/skill-router.sh +13 -0
- package/template_project/.claude/hooks/stop-failure-rescue.mjs +109 -0
- package/template_project/.claude/settings.json +36 -4
- package/template_project/.claude/skills/backend-api/SKILL.md +1 -1
- package/template_project/.claude/skills/delivery/SKILL.md +1 -1
- package/template_project/.claude/skills/docs-manager/SKILL.md +1 -1
- package/template_project/.claude/skills/duraone/SKILL.md +2 -1
- package/template_project/.claude/skills/file-organizer/SKILL.md +1 -1
- package/template_project/.claude/skills/frontend/SKILL.md +1 -1
- package/template_project/.claude/skills/frontend-vue/SKILL.md +1 -1
- package/template_project/.claude/skills/pdf-processing/SKILL.md +1 -1
- package/template_project/.claude/skills/postgres/SKILL.md +1 -1
- package/template_project/.claude/skills/testing-quality/SKILL.md +2 -0
- package/template_project/.claude/skills/webapp-testing/SKILL.md +1 -1
- package/template_project/.claude/ukit/index/route-task.mjs +3 -1
- package/template_project/.claude/ukit/index/tier-lane.mjs +1 -1
- 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 +107 -4
- 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/RULES.md +1 -1
- package/template_project/.omp/config.yml +2 -2
- package/template_project/.omp/hooks/pre/ukit-bridge.js +69 -2
- package/template_project/AGENTS.md +5 -1
- package/template_project/CLAUDE.md +5 -1
- package/template_project/docs/AI_HANDOFF/RULES.md +4 -4
- package/template_project/instructions/core.md +5 -1
- package/template_project/instructions/overlays/omp-rules.md +1 -1
- package/template_project/ukit/storage/config.json +32 -10
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
// Mission store (WP1). Contract, for other workers:
|
|
2
|
+
// Root: <projectRoot>/.ukit/storage/mission/ ; per mission: <mid>/{journal*.jsonl,events*.jsonl,
|
|
3
|
+
// graph.json,meta.json,pending.jsonl,claims/}. Journal/event segments are append-only and NEVER deleted.
|
|
4
|
+
// Every function fails safe (returns null/false/[]/{ok:false}) and never throws.
|
|
5
|
+
//
|
|
6
|
+
// missionRoot(projectRoot) / missionDir(projectRoot, mid)
|
|
7
|
+
// ensureMission({projectRoot, sessionKey}) -> {missionId, created} | null (active.json selection)
|
|
8
|
+
// readActive(projectRoot) -> object
|
|
9
|
+
// appendJsonlSync(base, obj, {maxBytes}) -> bool append+fsync, rotates base.jsonl -> base.NNNN.jsonl at 4 MiB
|
|
10
|
+
// readJsonl(base) -> object[] all segments in order; torn/corrupt lines skipped
|
|
11
|
+
// repairTornTail(base) -> bool truncates a partial last line of the live segment
|
|
12
|
+
// claimPromptId(projectRoot, mid) -> "P-n" lock-free, unique (O_EXCL claim files)
|
|
13
|
+
// withMissionLock(projectRoot, mid, fn, {deadlineMs=600}) -> {ok, value} | {ok:false, reason}
|
|
14
|
+
// appendEvent(projectRoot, mid, {kind, dedupeKey, ref, data, sessionKey, engine, hostTs}, {locked}) -> {ok, event, duplicate}
|
|
15
|
+
// seq assigned under the lock; id=sha1(kind|dedupeKey); dedupe ring of 512 ids; on lock timeout the event
|
|
16
|
+
// goes to pending.jsonl (cap 500, oldest dropped) and {ok:false, spooled:true} is returned.
|
|
17
|
+
// drainSpool(projectRoot, mid) -> number of events applied (call under no lock; takes it itself)
|
|
18
|
+
// readEvents(projectRoot, mid, sinceSeq=0) -> events with seq > sinceSeq, sorted by seq, de-duplicated by id
|
|
19
|
+
// readSnapshot(projectRoot, mid) / writeSnapshot(projectRoot, mid, obj) -> graph.json (atomic tmp+rename)
|
|
20
|
+
import crypto from 'node:crypto';
|
|
21
|
+
import fs from 'node:fs';
|
|
22
|
+
import path from 'node:path';
|
|
23
|
+
import { withAsyncLock } from '../async-lock.mjs';
|
|
24
|
+
|
|
25
|
+
export const SEGMENT_MAX_BYTES = 4 * 1024 * 1024;
|
|
26
|
+
export const DEDUPE_RING = 512;
|
|
27
|
+
export const SPOOL_CAP = 500;
|
|
28
|
+
|
|
29
|
+
export function missionRoot(projectRoot) {
|
|
30
|
+
return path.join(String(projectRoot || process.cwd()), '.ukit', 'storage', 'mission');
|
|
31
|
+
}
|
|
32
|
+
export function missionDir(projectRoot, mid) {
|
|
33
|
+
return path.join(missionRoot(projectRoot), String(mid).replace(/[^A-Za-z0-9_.-]/g, '_'));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function readJson(file, fallback) {
|
|
37
|
+
try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return fallback; }
|
|
38
|
+
}
|
|
39
|
+
function writeJsonAtomic(file, obj) {
|
|
40
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
41
|
+
const tmp = `${file}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`;
|
|
42
|
+
const fd = fs.openSync(tmp, 'w');
|
|
43
|
+
try { fs.writeSync(fd, JSON.stringify(obj)); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
|
|
44
|
+
fs.renameSync(tmp, file);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function readActive(projectRoot) {
|
|
48
|
+
return readJson(path.join(missionRoot(projectRoot), 'active.json'), { v: 1, activeMissionId: null, sessions: {} });
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function ensureMission({ projectRoot, sessionKey } = {}) {
|
|
52
|
+
try {
|
|
53
|
+
const file = path.join(missionRoot(projectRoot), 'active.json');
|
|
54
|
+
const active = readActive(projectRoot);
|
|
55
|
+
active.v = 1;
|
|
56
|
+
active.sessions = active.sessions || {};
|
|
57
|
+
let created = false;
|
|
58
|
+
if (!active.activeMissionId) {
|
|
59
|
+
active.activeMissionId = `M-${Date.now().toString(36)}${crypto.randomBytes(2).toString('hex')}`;
|
|
60
|
+
created = true;
|
|
61
|
+
}
|
|
62
|
+
const mid = active.activeMissionId;
|
|
63
|
+
const key = sessionKey || 'default';
|
|
64
|
+
if (!active.sessions[key] || active.sessions[key].missionId !== mid) {
|
|
65
|
+
active.sessions[key] = { ...(active.sessions[key] || {}), missionId: mid, lastSeq: active.sessions[key]?.lastSeq || 0 };
|
|
66
|
+
created = created || false;
|
|
67
|
+
}
|
|
68
|
+
fs.mkdirSync(missionDir(projectRoot, mid), { recursive: true });
|
|
69
|
+
if (created || !fs.existsSync(file) || !active.sessions[key]._saved) {
|
|
70
|
+
active.sessions[key]._saved = true;
|
|
71
|
+
writeJsonAtomic(file, active);
|
|
72
|
+
}
|
|
73
|
+
return { missionId: mid, created };
|
|
74
|
+
} catch { return null; }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function segmentFiles(base) {
|
|
78
|
+
const dir = path.dirname(base);
|
|
79
|
+
const stem = path.basename(base);
|
|
80
|
+
let names = [];
|
|
81
|
+
try { names = fs.readdirSync(dir); } catch { return []; }
|
|
82
|
+
const rotated = names.filter((n) => n.startsWith(`${stem}.`) && /\.\d{4}\.jsonl$/.test(n)).sort();
|
|
83
|
+
const out = rotated.map((n) => path.join(dir, n));
|
|
84
|
+
if (names.includes(`${stem}.jsonl`)) out.push(`${base}.jsonl`);
|
|
85
|
+
return out;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function rotate(base) {
|
|
89
|
+
const live = `${base}.jsonl`;
|
|
90
|
+
for (let i = segmentFiles(base).length; i < 100000; i += 1) {
|
|
91
|
+
const target = `${base}.${String(i).padStart(4, '0')}.jsonl`;
|
|
92
|
+
try { fs.linkSync(live, target); fs.unlinkSync(live); return; } catch (e) { if (e.code !== 'EEXIST') return; }
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function appendJsonlSync(base, obj, { maxBytes = SEGMENT_MAX_BYTES } = {}) {
|
|
97
|
+
try {
|
|
98
|
+
fs.mkdirSync(path.dirname(base), { recursive: true });
|
|
99
|
+
const live = `${base}.jsonl`;
|
|
100
|
+
try { if (fs.statSync(live).size >= maxBytes) rotate(base); } catch { /* absent */ }
|
|
101
|
+
const fd = fs.openSync(live, 'a');
|
|
102
|
+
try { fs.writeSync(fd, `${JSON.stringify(obj)}\n`); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
|
|
103
|
+
return true;
|
|
104
|
+
} catch { return false; }
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function readJsonl(base) {
|
|
108
|
+
const out = [];
|
|
109
|
+
for (const f of segmentFiles(base)) {
|
|
110
|
+
let raw = '';
|
|
111
|
+
try { raw = fs.readFileSync(f, 'utf8'); } catch { continue; }
|
|
112
|
+
for (const line of raw.split('\n')) {
|
|
113
|
+
if (!line.trim()) continue;
|
|
114
|
+
try { out.push(JSON.parse(line)); } catch { /* torn or corrupt line: skip */ }
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return out;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function repairTornTail(base) {
|
|
121
|
+
try {
|
|
122
|
+
const live = `${base}.jsonl`;
|
|
123
|
+
const buf = fs.readFileSync(live);
|
|
124
|
+
if (!buf.length || buf[buf.length - 1] === 0x0a) return false;
|
|
125
|
+
const cut = buf.lastIndexOf(0x0a) + 1;
|
|
126
|
+
fs.truncateSync(live, cut);
|
|
127
|
+
return true;
|
|
128
|
+
} catch { return false; }
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export function claimPromptId(projectRoot, mid) {
|
|
132
|
+
const dir = path.join(missionDir(projectRoot, mid), 'claims');
|
|
133
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
134
|
+
let n = 0;
|
|
135
|
+
try { for (const f of fs.readdirSync(dir)) n = Math.max(n, Number(f.replace(/\D/g, '')) || 0); } catch { /* */ }
|
|
136
|
+
for (let i = 0; i < 10000; i += 1) {
|
|
137
|
+
n += 1;
|
|
138
|
+
try { fs.closeSync(fs.openSync(path.join(dir, String(n)), 'wx')); return `P-${n}`; } catch (e) { if (e.code !== 'EEXIST') throw e; }
|
|
139
|
+
}
|
|
140
|
+
throw new Error('claim exhausted');
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export async function withMissionLock(projectRoot, mid, fn, { deadlineMs = 600 } = {}) {
|
|
144
|
+
try {
|
|
145
|
+
const dir = missionDir(projectRoot, mid);
|
|
146
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
147
|
+
const r = await withAsyncLock(path.join(dir, 'mission'), { deadlineMs }, fn);
|
|
148
|
+
return r.ok ? { ok: true, value: r.value } : { ok: false, reason: r.reason };
|
|
149
|
+
} catch (e) { return { ok: false, reason: 'error', error: String(e?.message || e) }; }
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function eventId(kind, dedupeKey) {
|
|
153
|
+
return crypto.createHash('sha1').update(`${kind}|${dedupeKey}`).digest('hex');
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function applyEventLocked(projectRoot, mid, input) {
|
|
157
|
+
const dir = missionDir(projectRoot, mid);
|
|
158
|
+
const metaFile = path.join(dir, 'meta.json');
|
|
159
|
+
const meta = readJson(metaFile, { seq: 0, ring: [] });
|
|
160
|
+
repairTornTail(path.join(dir, 'events'));
|
|
161
|
+
const id = eventId(input.kind, input.dedupeKey ?? JSON.stringify(input.data ?? null));
|
|
162
|
+
if (meta.ring.includes(id)) return { ok: true, duplicate: true, event: null };
|
|
163
|
+
const seq = meta.seq + 1;
|
|
164
|
+
const event = {
|
|
165
|
+
v: 1, seq, id, ts: Date.now(), hostTs: input.hostTs ?? null, missionId: mid,
|
|
166
|
+
sessionKey: input.sessionKey ?? null, engine: input.engine ?? null,
|
|
167
|
+
kind: input.kind, ref: input.ref ?? {}, data: input.data ?? {},
|
|
168
|
+
};
|
|
169
|
+
if (!appendJsonlSync(path.join(dir, 'events'), event)) return { ok: false, reason: 'write' };
|
|
170
|
+
meta.seq = seq;
|
|
171
|
+
meta.ring = [...meta.ring, id].slice(-DEDUPE_RING);
|
|
172
|
+
writeJsonAtomic(metaFile, meta);
|
|
173
|
+
return { ok: true, duplicate: false, event };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function spool(projectRoot, mid, input) {
|
|
177
|
+
const file = path.join(missionDir(projectRoot, mid), 'pending.jsonl');
|
|
178
|
+
try {
|
|
179
|
+
const lines = fs.existsSync(file) ? fs.readFileSync(file, 'utf8').split('\n').filter(Boolean) : [];
|
|
180
|
+
lines.push(JSON.stringify(input));
|
|
181
|
+
const kept = lines.slice(-SPOOL_CAP);
|
|
182
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
183
|
+
fs.writeFileSync(file, `${kept.join('\n')}\n`);
|
|
184
|
+
return true;
|
|
185
|
+
} catch { return false; }
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export async function appendEvent(projectRoot, mid, input, { locked = false, deadlineMs = 600 } = {}) {
|
|
189
|
+
try {
|
|
190
|
+
if (!input || !input.kind) return { ok: false, reason: 'invalid' };
|
|
191
|
+
if (locked) return applyEventLocked(projectRoot, mid, input);
|
|
192
|
+
const r = await withMissionLock(projectRoot, mid, () => applyEventLocked(projectRoot, mid, input), { deadlineMs });
|
|
193
|
+
if (r.ok) return r.value;
|
|
194
|
+
return { ok: false, spooled: spool(projectRoot, mid, input), reason: r.reason };
|
|
195
|
+
} catch { return { ok: false, reason: 'error' }; }
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
export async function drainSpool(projectRoot, mid) {
|
|
199
|
+
try {
|
|
200
|
+
const file = path.join(missionDir(projectRoot, mid), 'pending.jsonl');
|
|
201
|
+
if (!fs.existsSync(file)) return 0;
|
|
202
|
+
const r = await withMissionLock(projectRoot, mid, () => {
|
|
203
|
+
const items = fs.readFileSync(file, 'utf8').split('\n').filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
|
|
204
|
+
let n = 0;
|
|
205
|
+
for (const it of items) if (applyEventLocked(projectRoot, mid, it).ok) n += 1;
|
|
206
|
+
fs.unlinkSync(file);
|
|
207
|
+
return n;
|
|
208
|
+
});
|
|
209
|
+
return r.ok ? r.value : 0;
|
|
210
|
+
} catch { return 0; }
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export function readEvents(projectRoot, mid, sinceSeq = 0) {
|
|
214
|
+
try {
|
|
215
|
+
const seen = new Set();
|
|
216
|
+
return readJsonl(path.join(missionDir(projectRoot, mid), 'events'))
|
|
217
|
+
.filter((e) => e && Number.isFinite(e.seq) && e.seq > sinceSeq && !seen.has(e.id) && seen.add(e.id))
|
|
218
|
+
.sort((a, b) => a.seq - b.seq);
|
|
219
|
+
} catch { return []; }
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
export function readSnapshot(projectRoot, mid) {
|
|
223
|
+
return readJson(path.join(missionDir(projectRoot, mid), 'graph.json'), null);
|
|
224
|
+
}
|
|
225
|
+
export function writeSnapshot(projectRoot, mid, obj) {
|
|
226
|
+
try { writeJsonAtomic(path.join(missionDir(projectRoot, mid), 'graph.json'), obj); return true; } catch { return false; }
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// Additive (WP3): shared JSON helpers for working/checkpoint/recall/restore/metrics.
|
|
230
|
+
export function readJsonFile(file, fallback = null) { return readJson(file, fallback); }
|
|
231
|
+
export function writeJsonAtomicFile(file, obj) { writeJsonAtomic(file, obj); }
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// Mission working memory, Level C (WP3). Contract:
|
|
2
|
+
// recordMemoryItem({projectRoot, missionId, bucket, text, promptId?, acId?, status?}) -> Promise<{ok,id}>
|
|
3
|
+
// bucket: decision | hypothesis | assumption | failure. Stored as events (decision.add, hypothesis.add, ...).
|
|
4
|
+
// readMemoryItems(projectRoot, missionId) -> {decisions[{id,text,status,promptId}], hypotheses[{id,text,acId}], assumptions[], failures[]}
|
|
5
|
+
// a rejected decision keeps status 'rejected' (never dropped). Text is redacted before it is stored.
|
|
6
|
+
// buildWorkingMemory({projectRoot, missionId, graph?, now?}) -> Promise<working> (persisted to <mid>/working.json)
|
|
7
|
+
// working = {v, builtAt, graphRev, focus, activeTask:{id,title,status,paths}|null, ac:[{id,status,text}],
|
|
8
|
+
// recentDecisions(<=5), files[], pendingOps[], nextAction, assumptions[]}
|
|
9
|
+
import crypto from 'node:crypto';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import { redactText } from './redact.mjs';
|
|
12
|
+
import { loadGraph } from './graph.mjs';
|
|
13
|
+
import {
|
|
14
|
+
appendEvent, missionDir, readEvents, writeJsonAtomicFile,
|
|
15
|
+
} from './store.mjs';
|
|
16
|
+
|
|
17
|
+
const BUCKETS = { decision: 'decision.add', hypothesis: 'hypothesis.add', assumption: 'assumption.add', failure: 'failure.add' };
|
|
18
|
+
const sha = (s) => crypto.createHash('sha1').update(String(s)).digest('hex').slice(0, 6);
|
|
19
|
+
const PREFIX = { decision: 'D', hypothesis: 'H', assumption: 'A', failure: 'F' };
|
|
20
|
+
|
|
21
|
+
export async function recordMemoryItem({ projectRoot, missionId, bucket, text, promptId, acId, status } = {}) {
|
|
22
|
+
try {
|
|
23
|
+
const kind = BUCKETS[bucket];
|
|
24
|
+
if (!kind || !text) return { ok: false, reason: 'invalid' };
|
|
25
|
+
const clean = redactText(String(text)).text.slice(0, 400);
|
|
26
|
+
const id = `${PREFIX[bucket]}-${sha(clean)}`;
|
|
27
|
+
const data = { id, text: clean };
|
|
28
|
+
if (promptId) data.promptId = promptId;
|
|
29
|
+
if (acId) data.acId = acId;
|
|
30
|
+
if (bucket === 'decision') data.status = status === 'rejected' ? 'rejected' : 'accepted';
|
|
31
|
+
const r = await appendEvent(projectRoot, missionId, { kind, dedupeKey: `${id}:${data.status || ''}`, ref: { promptId }, data });
|
|
32
|
+
return { ok: Boolean(r.ok), id };
|
|
33
|
+
} catch { return { ok: false, reason: 'error' }; }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function readMemoryItems(projectRoot, missionId) {
|
|
37
|
+
const out = { decisions: [], hypotheses: [], assumptions: [], failures: [] };
|
|
38
|
+
try {
|
|
39
|
+
const put = (list, d) => { const i = list.findIndex((x) => x.id === d.id); if (i >= 0) list[i] = { ...list[i], ...d }; else list.push(d); };
|
|
40
|
+
for (const e of readEvents(projectRoot, missionId)) {
|
|
41
|
+
const d = e.data;
|
|
42
|
+
if (!d || !d.id) continue;
|
|
43
|
+
if (e.kind === 'decision.add') put(out.decisions, d);
|
|
44
|
+
else if (e.kind === 'hypothesis.add') put(out.hypotheses, d);
|
|
45
|
+
else if (e.kind === 'assumption.add') put(out.assumptions, d);
|
|
46
|
+
else if (e.kind === 'failure.add') put(out.failures, d);
|
|
47
|
+
}
|
|
48
|
+
} catch { /* fail safe */ }
|
|
49
|
+
return out;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const num = (id) => Number(String(id).replace(/\D/g, '')) || 0;
|
|
53
|
+
|
|
54
|
+
export function activeTaskOf(graph) {
|
|
55
|
+
const tasks = Object.values(graph.state.tasks);
|
|
56
|
+
const cur = tasks.filter((t) => t.status === 'in_progress').sort((a, b) => (b.ts || 0) - (a.ts || 0) || num(b.id) - num(a.id))[0];
|
|
57
|
+
return cur || graph.readySet()[0] || null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export async function buildWorkingMemory({ projectRoot, missionId, graph, now = Date.now() } = {}) {
|
|
61
|
+
try {
|
|
62
|
+
const g = graph || await loadGraph({ projectRoot, missionId });
|
|
63
|
+
const items = readMemoryItems(projectRoot, missionId);
|
|
64
|
+
const task = activeTaskOf(g);
|
|
65
|
+
const req = task ? g.state.reqs[task.reqIds?.[0]] : null;
|
|
66
|
+
const acs = task ? (task.acIds || []).map((id) => g.state.acs[id]).filter(Boolean).map((a) => ({ id: a.id, status: a.status, text: g.acText(a) })) : [];
|
|
67
|
+
const blocker = task ? g.state.blockers[task.id] : null;
|
|
68
|
+
const files = [...new Set(Object.values(g.state.tasks).filter((t) => t.status === 'in_progress').flatMap((t) => t.paths || []))].slice(0, 20);
|
|
69
|
+
const pendingOps = Object.values(g.state.tasks)
|
|
70
|
+
.filter((t) => t.status === 'in_progress' || t.status === 'done_unverified' || t.status === 'invalidated')
|
|
71
|
+
.slice(0, 10).map((t) => `${t.id} ${t.status}: ${t.title.slice(0, 80)}`);
|
|
72
|
+
for (const [tid, b] of Object.entries(g.state.blockers)) for (const op of b.deniedOps || []) pendingOps.push(`${tid} denied (never re-propose): ${String(op).slice(0, 80)}`);
|
|
73
|
+
let nextAction;
|
|
74
|
+
if (blocker) nextAction = `Resolve blocker ${blocker.code} on ${task.id}: ${blocker.reason}`.slice(0, 200);
|
|
75
|
+
else if (task?.status === 'in_progress') nextAction = `Continue ${task.id}: ${task.title}`.slice(0, 200);
|
|
76
|
+
else if (task) nextAction = `Start ${task.id}: ${task.title}`.slice(0, 200);
|
|
77
|
+
else nextAction = g.isComplete().complete ? 'Verify mission completeness' : 'Create tasks for uncovered requirements';
|
|
78
|
+
const working = {
|
|
79
|
+
v: 1, builtAt: now, graphRev: g.state.rev,
|
|
80
|
+
focus: (req?.text || task?.title || '').slice(0, 200),
|
|
81
|
+
activeTask: task ? { id: task.id, title: task.title, status: task.status, paths: task.paths || [] } : null,
|
|
82
|
+
ac: acs, recentDecisions: items.decisions.filter((d) => d.status !== 'rejected').slice(-5),
|
|
83
|
+
files, pendingOps: pendingOps.slice(0, 15), nextAction, assumptions: items.assumptions.slice(-5),
|
|
84
|
+
};
|
|
85
|
+
writeJsonAtomicFile(path.join(missionDir(projectRoot, missionId), 'working.json'), working);
|
|
86
|
+
return working;
|
|
87
|
+
} catch { return null; }
|
|
88
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// prompt-injection-cap.mjs - aggregate UserPromptSubmit context cap (WP-R3), used by hook-chain-runner.
|
|
2
|
+
// WP-R3: aggregate cap on the joined UserPromptSubmit context. Trims the LOWEST-value (latest, advisory)
|
|
3
|
+
// lines first; never trims shell-watch ACTION / STOP / BLOCKED / WAITING ON YOU lines, a PROJECT_IMPORTANT
|
|
4
|
+
// block, or JSON documents. Appends a one-line trim notice. Config: compact.maxPromptInjectionChars.
|
|
5
|
+
export const DEFAULT_MAX_PROMPT_INJECTION_CHARS = 4000;
|
|
6
|
+
const PROTECTED_LINE_RE = /\[ukit-shell-watch\] ACTION|\bSTOP\b|\bBLOCKED\b|WAITING ON YOU|PROJECT_IMPORTANT/;
|
|
7
|
+
export function capPromptInjection(text, cap = DEFAULT_MAX_PROMPT_INJECTION_CHARS) {
|
|
8
|
+
if (typeof text !== 'string' || !(cap > 0) || text.length <= cap) return text;
|
|
9
|
+
const lines = text.split('\n');
|
|
10
|
+
const keep = new Array(lines.length).fill(true);
|
|
11
|
+
const prot = lines.map((l) => {
|
|
12
|
+
const t = l.trimStart();
|
|
13
|
+
return PROTECTED_LINE_RE.test(l) || t.startsWith('{') || t.startsWith('}');
|
|
14
|
+
});
|
|
15
|
+
let inBlock = false;
|
|
16
|
+
lines.forEach((l, i) => {
|
|
17
|
+
if (l.includes('--- BEGIN PROJECT_IMPORTANT.md ---')) inBlock = true;
|
|
18
|
+
if (inBlock) prot[i] = true;
|
|
19
|
+
if (l.includes('--- END PROJECT_IMPORTANT.md ---')) inBlock = false;
|
|
20
|
+
});
|
|
21
|
+
let total = text.length;
|
|
22
|
+
let trimmed = 0;
|
|
23
|
+
for (let i = lines.length - 1; i >= 0 && total > cap; i -= 1) {
|
|
24
|
+
if (prot[i]) continue;
|
|
25
|
+
keep[i] = false;
|
|
26
|
+
total -= lines[i].length + 1;
|
|
27
|
+
trimmed += lines[i].length + 1;
|
|
28
|
+
}
|
|
29
|
+
if (!trimmed) return text;
|
|
30
|
+
const body = lines.filter((_, i) => keep[i]).join('\n').replace(/\n+$/, '');
|
|
31
|
+
return `${body}\n[ukit] ${trimmed} chars of advisory context trimmed\n`;
|
|
32
|
+
}
|
|
33
|
+
|
|
@@ -58,7 +58,9 @@ if (Number.isFinite(HOOK_DEADLINE_MS) && HOOK_DEADLINE_MS > 0) {
|
|
|
58
58
|
}, HOOK_DEADLINE_MS).unref();
|
|
59
59
|
}
|
|
60
60
|
|
|
61
|
-
|
|
61
|
+
// Cross-session bound only: route state owned by the CALLING session is restored at any age
|
|
62
|
+
// (multi-hour runs compact long after their last prompt).
|
|
63
|
+
const STATE_TTL_MS = 24 * 60 * 60 * 1000;
|
|
62
64
|
const STOPWORDS = new Set([
|
|
63
65
|
'the', 'a', 'an', 'and', 'or', 'to', 'for', 'of', 'with', 'in', 'on', 'is', 'are',
|
|
64
66
|
'this', 'that', 'it', 'as', 'by', 'be', 'use', 'using', 'implement', 'fix', 'task',
|
|
@@ -132,6 +134,47 @@ async function buildResumableRunLines(projectRoot, state, config) {
|
|
|
132
134
|
return [];
|
|
133
135
|
}
|
|
134
136
|
}
|
|
137
|
+
export const HOST_CONTEXT_CAP = 10000;
|
|
138
|
+
export const PRECOMPACT_OUTPUT_CAP = 4000;
|
|
139
|
+
export const RESCUE_MAX_AGE_MS = 24 * 60 * 60 * 1000;
|
|
140
|
+
|
|
141
|
+
// WP-R3: a fresh rescue bundle is appended to the SessionStart restoration output once per session
|
|
142
|
+
// (hash dedupe marker). Returns '' when absent, stale, already injected or unreadable.
|
|
143
|
+
export async function readRescueInjection(projectRoot, sessionId, now = Date.now()) {
|
|
144
|
+
try {
|
|
145
|
+
const dir = path.join(projectRoot, '.ukit', 'storage', 'rescue');
|
|
146
|
+
const latest = JSON.parse(await fs.readFile(path.join(dir, 'latest.json'), 'utf8'));
|
|
147
|
+
const created = Date.parse(latest.createdAt);
|
|
148
|
+
if (!latest.bundlePath || !latest.sha256 || !Number.isFinite(created) || now - created > RESCUE_MAX_AGE_MS) return '';
|
|
149
|
+
const sid = String(sessionId || 'unknown').replace(/[^A-Za-z0-9_.-]/g, '_').slice(0, 80);
|
|
150
|
+
const markerFile = path.join(dir, 'injected.json');
|
|
151
|
+
let marker = {};
|
|
152
|
+
try { marker = JSON.parse(await fs.readFile(markerFile, 'utf8')) || {}; } catch { /* first injection */ }
|
|
153
|
+
if (marker[sid] === latest.sha256) return '';
|
|
154
|
+
const text = await fs.readFile(latest.bundlePath, 'utf8');
|
|
155
|
+
const keys = Object.keys(marker).slice(-15);
|
|
156
|
+
const next = Object.fromEntries(keys.map((k) => [k, marker[k]]));
|
|
157
|
+
next[sid] = latest.sha256;
|
|
158
|
+
await fs.writeFile(markerFile, JSON.stringify(next));
|
|
159
|
+
return text.slice(0, 6000);
|
|
160
|
+
} catch { return ''; }
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// WP4: mission continuity glue. Fail-open — any error degrades to the pre-WP4 behavior.
|
|
164
|
+
async function missionHooks() {
|
|
165
|
+
return import(new URL('./mission/hooks.mjs', import.meta.url).href);
|
|
166
|
+
}
|
|
167
|
+
export async function missionPreCompact(projectRoot, payload) {
|
|
168
|
+
try { return await (await missionHooks()).preCompactStep({ projectRoot, payload }); } catch { return ''; }
|
|
169
|
+
}
|
|
170
|
+
export async function missionRestore(projectRoot, payload, rescue = '') {
|
|
171
|
+
try { return await (await missionHooks()).sessionRestoreStep({ projectRoot, payload, rescue }); } catch { return String(rescue || '').slice(0, 6000); }
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export function capSummaryInstructions(output, cap = PRECOMPACT_OUTPUT_CAP) {
|
|
175
|
+
return output.length > cap ? `${output.slice(0, cap - 1)}…` : output;
|
|
176
|
+
}
|
|
177
|
+
|
|
135
178
|
async function main() {
|
|
136
179
|
const projectRoot = process.env.CLAUDE_PROJECT_DIR && path.isAbsolute(process.env.CLAUDE_PROJECT_DIR)
|
|
137
180
|
? process.env.CLAUDE_PROJECT_DIR
|
|
@@ -155,12 +198,49 @@ async function main() {
|
|
|
155
198
|
return {};
|
|
156
199
|
}
|
|
157
200
|
})();
|
|
201
|
+
const hookEvent = typeof hookPayload.hook_event_name === 'string' ? hookPayload.hook_event_name : '';
|
|
202
|
+
// Claude Code only injects SessionStart stdout into model context, so the restoration block
|
|
203
|
+
// is emitted there (source=compact). PreCompact is the checkpoint writer.
|
|
204
|
+
if (hookEvent === 'SessionStart' && hookPayload.source !== 'compact') {
|
|
205
|
+
// Fresh/resumed/cleared session after a rescue: only the on-disk restoration bundle applies.
|
|
206
|
+
const rescue = await readRescueInjection(projectRoot, hookPayload.session_id);
|
|
207
|
+
// Resume also restores the mission graph (WP4); startup/clear keep the rescue-only behavior.
|
|
208
|
+
const restored = hookPayload.source === 'resume' ? await missionRestore(projectRoot, hookPayload, rescue) : rescue;
|
|
209
|
+
if (restored) process.stdout.write(restored.slice(0, HOST_CONTEXT_CAP));
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
158
212
|
const sessionConfig = {
|
|
159
213
|
...config,
|
|
160
214
|
sessionId: typeof hookPayload.session_id === 'string' && hookPayload.session_id.trim()
|
|
161
215
|
? hookPayload.session_id.trim()
|
|
162
216
|
: undefined,
|
|
163
217
|
};
|
|
218
|
+
let missionNote = '';
|
|
219
|
+
if (hookEvent === 'PreCompact') missionNote = await missionPreCompact(projectRoot, hookPayload);
|
|
220
|
+
if (hookEvent !== 'SessionStart') {
|
|
221
|
+
// PreCompact checkpoint: persist the durable resume intent for the post-compaction session.
|
|
222
|
+
try {
|
|
223
|
+
const ledgerRuntime = await import('./execution-ledger.mjs');
|
|
224
|
+
await ledgerRuntime.writeResumeIntent(projectRoot, hookPayload);
|
|
225
|
+
} catch { /* checkpoint is best-effort; the block below still builds */ }
|
|
226
|
+
// omp delivers the block from its session_compact chain (SessionStart/compact) — emitting it
|
|
227
|
+
// here too would inject the same context twice.
|
|
228
|
+
if (hookEvent === 'PreCompact' && hookPayload.ukit_harness === 'omp') return;
|
|
229
|
+
}
|
|
230
|
+
const finalizeOutput = async (out) => {
|
|
231
|
+
if (hookEvent === 'SessionStart') {
|
|
232
|
+
const rescue = await readRescueInjection(projectRoot, sessionConfig.sessionId);
|
|
233
|
+
// Mission restore + rescue bundle share one <=6000-char budget (WP4), deduped against each other.
|
|
234
|
+
const restored = await missionRestore(projectRoot, hookPayload, rescue);
|
|
235
|
+
if (!restored) return out.slice(0, HOST_CONTEXT_CAP);
|
|
236
|
+
const room = HOST_CONTEXT_CAP - restored.length - 1;
|
|
237
|
+
return `${room > 0 ? out.slice(0, room) : ''}\n${restored}`.slice(0, HOST_CONTEXT_CAP);
|
|
238
|
+
}
|
|
239
|
+
if (hookEvent !== 'PreCompact') return out;
|
|
240
|
+
if (!missionNote) return capSummaryInstructions(out);
|
|
241
|
+
// The mission note must survive the 4000-char cap: shrink the generic block, never the note.
|
|
242
|
+
return `${capSummaryInstructions(out, PRECOMPACT_OUTPUT_CAP - missionNote.length - 1)}\n${missionNote}`;
|
|
243
|
+
};
|
|
164
244
|
const state = await loadFreshRouteState(projectRoot, sessionConfig.sessionId);
|
|
165
245
|
const compressEnabled = shouldCompress(config);
|
|
166
246
|
const header = '=== PROJECT CONTEXT (post-compaction) ===';
|
|
@@ -239,7 +319,7 @@ async function main() {
|
|
|
239
319
|
if (config.tokenPipeline?.promptCache) {
|
|
240
320
|
const cached = await readPromptCacheEntry(projectRoot, requestKey, { touch: true });
|
|
241
321
|
if (cached?.content) {
|
|
242
|
-
process.stdout.write(String(cached.content));
|
|
322
|
+
process.stdout.write(await finalizeOutput(String(cached.content)));
|
|
243
323
|
return;
|
|
244
324
|
}
|
|
245
325
|
}
|
|
@@ -316,7 +396,7 @@ async function main() {
|
|
|
316
396
|
},
|
|
317
397
|
});
|
|
318
398
|
|
|
319
|
-
process.stdout.write(output);
|
|
399
|
+
process.stdout.write(await finalizeOutput(output));
|
|
320
400
|
}
|
|
321
401
|
|
|
322
402
|
function shouldCompress(config) {
|
|
@@ -393,13 +473,14 @@ async function loadRuntimeConfig(projectRoot) {
|
|
|
393
473
|
async function loadFreshRouteState(projectRoot, sessionId) {
|
|
394
474
|
const statePath = path.join(projectRoot, '.claude', 'ukit', 'skill-router-state.json');
|
|
395
475
|
const state = await readJson(statePath, {});
|
|
396
|
-
if (typeof state?.ts === 'number' && (Date.now() - state.ts) > STATE_TTL_MS) {
|
|
397
|
-
return {};
|
|
398
|
-
}
|
|
399
476
|
if (!state || typeof state !== 'object') return {};
|
|
400
477
|
const ownerId = typeof state.sessionId === 'string' && state.sessionId.trim()
|
|
401
478
|
? state.sessionId.trim()
|
|
402
479
|
: null;
|
|
480
|
+
const sameSession = ownerId !== null && ownerId === (sessionId ?? null);
|
|
481
|
+
if (!sameSession && typeof state?.ts === 'number' && (Date.now() - state.ts) > STATE_TTL_MS) {
|
|
482
|
+
return {};
|
|
483
|
+
}
|
|
403
484
|
if (ownerId !== (sessionId ?? null)) {
|
|
404
485
|
try {
|
|
405
486
|
process.stderr.write(
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
// bundle.mjs - layered restoration bundle (WP-R3). Contract consumed by WP-R4:
|
|
2
|
+
// buildBundle(recon, {maxChars}) -> {text, sha256, layers:{L1,L2,L3}, sessionId, reconcile}
|
|
3
|
+
// writeBundle(projectRoot, bundle) -> {bundlePath, latestPath}; writes .ukit/storage/rescue/bundle-<sha8>.md and
|
|
4
|
+
// latest.json {bundlePath, sha256, createdAt, sessionId}.
|
|
5
|
+
// Budgets: L1 <= 1500, L2 <= 4500, L3 pointers only; total <= min(6000, maxChars). Deterministic.
|
|
6
|
+
import crypto from 'node:crypto';
|
|
7
|
+
import fsp from 'node:fs/promises';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
|
|
10
|
+
export const HEADER = 'MISSION RESTORE (UKit rescue) — authoritative state from disk; the compacted summary is not authoritative; context refresh is not an authorization refresh.';
|
|
11
|
+
export const L1_MAX = 1500;
|
|
12
|
+
export const L2_MAX = 4500;
|
|
13
|
+
export const TOTAL_MAX = 6000;
|
|
14
|
+
export const MAX_REQUIREMENTS = 12;
|
|
15
|
+
|
|
16
|
+
const clip = (s, n) => {
|
|
17
|
+
const t = String(s ?? '').replace(/\s+/g, ' ').trim();
|
|
18
|
+
return t.length <= n ? t : `${t.slice(0, Math.max(0, n - 1))}…`;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
/** Join lines but never exceed `max`; whole lines only, the final line is clipped. Returns {text, dropped}. */
|
|
22
|
+
function fit(lines, max) {
|
|
23
|
+
const out = [];
|
|
24
|
+
let used = 0;
|
|
25
|
+
let dropped = 0;
|
|
26
|
+
for (const l of lines) {
|
|
27
|
+
const cost = l.length + (out.length ? 1 : 0);
|
|
28
|
+
if (used + cost <= max) { out.push(l); used += cost; continue; }
|
|
29
|
+
const room = max - used - (out.length ? 1 : 0);
|
|
30
|
+
if (!dropped && room > 40) { out.push(clip(l, room)); used = max; }
|
|
31
|
+
dropped += 1;
|
|
32
|
+
}
|
|
33
|
+
return { text: out.join('\n'), dropped };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function buildBundle(recon = {}, { maxChars = TOTAL_MAX } = {}) {
|
|
37
|
+
const items = Array.isArray(recon.items) ? recon.items : [];
|
|
38
|
+
const total = Math.max(400, Math.min(TOTAL_MAX, Number(maxChars) || TOTAL_MAX));
|
|
39
|
+
const avail = total - HEADER.length - 3;
|
|
40
|
+
const l3Cap = Math.min(500, Math.floor(avail * 0.1));
|
|
41
|
+
const l1Cap = Math.min(L1_MAX, Math.floor(avail * 0.3));
|
|
42
|
+
const l2Cap = Math.min(L2_MAX, avail - l1Cap - l3Cap);
|
|
43
|
+
const by = (kind) => items.filter((i) => i.kind === kind);
|
|
44
|
+
const prompts = by('prompt');
|
|
45
|
+
const todos = by('todo');
|
|
46
|
+
const g = recon.git || {};
|
|
47
|
+
const mismatch = Array.isArray(recon.identityMismatch) ? recon.identityMismatch : [];
|
|
48
|
+
const pendingTodo = todos.find((t) => t.status !== 'completed');
|
|
49
|
+
const latest = prompts[prompts.length - 1];
|
|
50
|
+
const activeText = pendingTodo ? pendingTodo.text : (latest ? latest.text : '');
|
|
51
|
+
const acLines = String(latest?.text || '').split(/(?<=[.!?\n])\s+/).filter((l) => /\b(accept|criteria|must|should|verify|test)/i.test(l)).slice(0, 3);
|
|
52
|
+
const blockers = items.filter((i) => i.class === 'BLOCKED');
|
|
53
|
+
const unknownCritical = !prompts.length;
|
|
54
|
+
|
|
55
|
+
const l1 = [];
|
|
56
|
+
l1.push(`Repo: ${clip(path.basename(String(recon.projectRoot || '')) || '?', 60)} | branch: ${g.ok ? g.branch : 'UNKNOWN'} | HEAD: ${g.ok ? g.head.slice(0, 12) : 'UNKNOWN'} | dirty: ${g.ok ? g.dirty : 'UNKNOWN'}`);
|
|
57
|
+
l1.push('Verify HEAD/branch (git rev-parse HEAD; git status) before mutating anything.');
|
|
58
|
+
if (mismatch.length) l1.push(`RECONCILE BEFORE MUTATING: identity mismatch (${mismatch.map((m) => clip(m, 100)).join('; ')}). Inspect git state read-only, report to the owner, then continue.`);
|
|
59
|
+
if (recon.ownerStop) l1.push('STOP: owner STOP is in effect — do not start tools, edits or subagents until the owner sends a new request.');
|
|
60
|
+
for (const b of blockers.slice(0, 3)) l1.push(`BLOCKED: ${clip(b.text, 160)}`);
|
|
61
|
+
if (unknownCritical) l1.push('UNKNOWN: no original user prompt could be recovered. Do not invent requirements or decisions; ask the owner to restate the goal.');
|
|
62
|
+
else l1.push(`Active task [${pendingTodo ? 'todo, INFERRED_UNVERIFIED' : `prompt ${latest.id}`}]: ${clip(activeText, 260)}`);
|
|
63
|
+
l1.push(acLines.length ? `Acceptance criteria (verbatim, ${latest.id}): ${clip(acLines.join(' '), 300)}` : 'Acceptance criteria: UNKNOWN (not recoverable; confirm with the owner before declaring done).');
|
|
64
|
+
const unresolved = items.filter((i) => i.kind === 'tool-unresolved' || i.kind === 'subagent-active');
|
|
65
|
+
const pend = prompts.filter((p) => p.pendingExecution);
|
|
66
|
+
l1.push(`Next action: ${pend.length ? `execute journaled-but-unexecuted prompt ${pend.map((p) => p.id).join(', ')}` : mismatch.length ? 'reconcile identity, then resume the active task' : unknownCritical ? 'ask the owner for the goal' : 'resume the active task; re-check state read-only first'}.`);
|
|
67
|
+
const L1 = fit(l1, l1Cap);
|
|
68
|
+
|
|
69
|
+
const l2 = ['Requirements (verbatim prompts, class RECOVERED_FROM_SOURCE; later prompts supersede earlier on conflict):'];
|
|
70
|
+
const reqs = prompts.slice(-MAX_REQUIREMENTS);
|
|
71
|
+
const perReq = Math.max(80, Math.min(400, Math.floor((l2Cap * 0.6) / Math.max(1, reqs.length))));
|
|
72
|
+
for (const p of reqs) l2.push(`- [${p.id}]${p.supersedes ? ' (may supersede earlier)' : ''} ${clip(p.text, perReq)}`);
|
|
73
|
+
if (prompts.length > reqs.length) l2.push(`- ${prompts.length - reqs.length} earlier prompt(s) omitted from this layer; retrieve by id from the journal/transcript (L3).`);
|
|
74
|
+
const decisions = prompts.filter((p) => p.supersedes).slice(-4);
|
|
75
|
+
if (decisions.length) l2.push(`Decisions/supersessions to honor: ${decisions.map((p) => `[${p.id}] ${clip(p.text, 90)}`).join(' | ')}`);
|
|
76
|
+
const receipts = by('receipt');
|
|
77
|
+
l2.push(`Verified evidence (receipts): ${receipts.length ? receipts.slice(-5).map((r) => `${r.receiptKind}: ${clip(r.text, 70)}${r.migration ? ' [migration applied; do not re-run]' : ''}`).join(' | ') : 'none'}`);
|
|
78
|
+
const pendTodos = todos.filter((t) => t.status !== 'completed');
|
|
79
|
+
const doneTodos = todos.filter((t) => t.status === 'completed');
|
|
80
|
+
if (pendTodos.length) l2.push(`Pending todos (INFERRED_UNVERIFIED): ${pendTodos.slice(0, 6).map((t) => clip(t.text, 70)).join(' | ')}`);
|
|
81
|
+
if (doneTodos.length) l2.push(`Todos marked completed but NOT verified: ${doneTodos.slice(0, 6).map((t) => clip(t.text, 60)).join(' | ')} - re-verify before relying on them.`);
|
|
82
|
+
for (const f of by('failure').slice(-3)) l2.push(`Failure: ${clip(f.text, 120)}`);
|
|
83
|
+
for (const d of by('denied').slice(-3)) l2.push(`Denied operation (do not repeat): ${clip(d.text, 120)}`);
|
|
84
|
+
for (const u of unresolved.slice(0, 4)) l2.push(`UNKNOWN: ${clip(u.text, 120)} - reconcile read-only before repeating (${u.kind}).`);
|
|
85
|
+
const dirty = by('git-dirty')[0];
|
|
86
|
+
if (dirty) l2.push(`Uncommitted work: ${clip(dirty.text, 220)} - do not discard.`);
|
|
87
|
+
const claim = by('assistant-claim')[0];
|
|
88
|
+
if (claim) l2.push(`Last assistant claim (INFERRED_UNVERIFIED): ${clip(claim.text, 160)}`);
|
|
89
|
+
const L2 = fit(l2, l2Cap);
|
|
90
|
+
|
|
91
|
+
const l3 = ['Pointers (load on demand, not inlined):'];
|
|
92
|
+
if (recon.transcriptPath) l3.push(`- transcript: ${clip(recon.transcriptPath, 160)}`);
|
|
93
|
+
if (recon.missionId) l3.push(`- mission journal: .ukit/storage/mission/${clip(recon.missionId, 40)}/`);
|
|
94
|
+
if (recon.ledgerFile) l3.push(`- execution ledger: ${clip(recon.ledgerFile, 150)}`);
|
|
95
|
+
l3.push('- rescue events: .ukit/storage/rescue/events.jsonl');
|
|
96
|
+
const L3 = fit(l3, l3Cap);
|
|
97
|
+
|
|
98
|
+
const text = [HEADER, L1.text, L2.text, L3.text].filter(Boolean).join('\n\n').slice(0, total);
|
|
99
|
+
const sha256 = crypto.createHash('sha256').update(text).digest('hex');
|
|
100
|
+
return {
|
|
101
|
+
text, sha256, sessionId: String(recon.sessionId || ''), reconcile: mismatch.length > 0,
|
|
102
|
+
layers: { L1: L1.text, L2: L2.text, L3: L3.text, omitted: { L1: L1.dropped, L2: L2.dropped, L3: L3.dropped } },
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async function writeAtomic(file, data) {
|
|
107
|
+
const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
108
|
+
await fsp.writeFile(tmp, data);
|
|
109
|
+
await fsp.rename(tmp, file);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export async function writeBundle(projectRoot, bundle) {
|
|
113
|
+
const dir = path.join(projectRoot, '.ukit', 'storage', 'rescue');
|
|
114
|
+
await fsp.mkdir(dir, { recursive: true });
|
|
115
|
+
const bundlePath = path.join(dir, `bundle-${bundle.sha256.slice(0, 8)}.md`);
|
|
116
|
+
await writeAtomic(bundlePath, bundle.text);
|
|
117
|
+
const latestPath = path.join(dir, 'latest.json');
|
|
118
|
+
await writeAtomic(latestPath, JSON.stringify({
|
|
119
|
+
bundlePath, sha256: bundle.sha256, createdAt: new Date().toISOString(), sessionId: bundle.sessionId || '',
|
|
120
|
+
}));
|
|
121
|
+
return { bundlePath, latestPath };
|
|
122
|
+
}
|