@ngockhoale/ukit 3.4.85 → 3.5.2

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 (34) hide show
  1. package/CHANGELOG.md +33 -1064
  2. package/bin/ukit +9 -0
  3. package/manifests/documentation.yaml +12 -0
  4. package/manifests/platform.full.yaml +23 -0
  5. package/package.json +1 -1
  6. package/src/cli/commands/install.js +12 -0
  7. package/src/cli/commands/memory.js +30 -3
  8. package/src/core/memory/episodeArchive.js +147 -0
  9. package/src/core/memory/episodes.js +199 -37
  10. package/src/core/memory/memoryHit.js +59 -40
  11. package/src/core/memory/mutateMemory.js +23 -3
  12. package/src/core/memory/recallEngine.js +423 -0
  13. package/src/core/memory/retrieval.js +55 -92
  14. package/src/core/observability/emit/lifecycle.js +30 -0
  15. package/src/core/runtimeConfig.js +7 -0
  16. package/src/index/buildIndex.js +22 -0
  17. package/src/index/impactContext.js +11 -1
  18. package/template_project/.claude/hooks/edit-hint.mjs +119 -0
  19. package/template_project/.claude/hooks/skill-router.sh +82 -51
  20. package/template_project/.claude/settings.json +2 -2
  21. package/template_project/.claude/ukit/index/edit-graph.mjs +274 -0
  22. package/template_project/.claude/ukit/index/lib/index-core.mjs +36 -1
  23. package/template_project/.claude/ukit/index/post-edit-verify.mjs +8 -5
  24. package/template_project/.claude/ukit/index/resolve-context.mjs +17 -0
  25. package/template_project/.claude/ukit/index/route-task.mjs +29 -48
  26. package/template_project/.claude/ukit/runtime/execution-ledger.mjs +45 -0
  27. package/template_project/.claude/ukit/runtime/hook-chain-runner.mjs +62 -5
  28. package/template_project/.claude/ukit/runtime/memory-lanes.mjs +237 -0
  29. package/template_project/.claude/ukit/runtime/memory-recall.mjs +423 -0
  30. package/template_project/.claude/ukit/runtime/reinject-context.mjs +29 -45
  31. package/template_project/.omp/hooks/pre/ukit-bridge.js +2 -1
  32. package/template_project/AGENTS.md +1 -1
  33. package/template_project/CLAUDE.md +1 -1
  34. package/template_project/instructions/core.md +1 -1
@@ -146,8 +146,8 @@
146
146
  "hooks": [
147
147
  {
148
148
  "type": "command",
149
- "command": "node \"$CLAUDE_PROJECT_DIR/.claude/ukit/runtime/hook-chain-runner.mjs\" --emit-verdict - \"$CLAUDE_PROJECT_DIR/.claude/hooks/post-edit-verify.sh\":8 \"$CLAUDE_PROJECT_DIR/.claude/hooks/record-execution.mjs\":8 \"$CLAUDE_PROJECT_DIR/.claude/hooks/task-watchdog.sh\":8",
150
- "timeout": 34
149
+ "command": "node \"$CLAUDE_PROJECT_DIR/.claude/ukit/runtime/hook-chain-runner.mjs\" --emit-verdict - \"$CLAUDE_PROJECT_DIR/.claude/hooks/post-edit-verify.sh\":8 \"$CLAUDE_PROJECT_DIR/.claude/hooks/record-execution.mjs\":8 \"$CLAUDE_PROJECT_DIR/.claude/hooks/task-watchdog.sh\":8 \"$CLAUDE_PROJECT_DIR/.claude/hooks/edit-hint.mjs\":8",
150
+ "timeout": 42
151
151
  }
152
152
  ]
153
153
  },
@@ -0,0 +1,274 @@
1
+ // Edit graph: compact per-file mirror/test/import edges, written next to the other
2
+ // index artifacts so an edit hook can read ONE small file instead of imports.json.
3
+ // Measured 218 ms graph step per one-file refresh on this repo; a per-file token cache was tried and gave no measurable total gain.
4
+ import fs from 'node:fs/promises';
5
+ import path from 'node:path';
6
+ import crypto from 'node:crypto';
7
+
8
+ export const EDIT_GRAPH_FILE = 'edit-graph.json';
9
+ const SCHEMA = 1;
10
+ const CAP = 5;
11
+ const MIN_TWIN = 200;
12
+ const MAX_HASH = 512 * 1024;
13
+ const MAX_LOAD = 2 * 1024 * 1024;
14
+ const CODE_EXT = new Set('js mjs cjs ts tsx jsx vue sh py go java cs php rb rs json yaml yml'.split(' '));
15
+ const GENERIC = new Set('index main utils types config constants helpers'.split(' '));
16
+
17
+ const norm = (p) => String(p ?? '').trim().replace(/\\/g, '/').replace(/^(\.\/)+/, '');
18
+ const cmp = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
19
+ const extOf = (p) => path.posix.extname(p).slice(1).toLowerCase();
20
+ const uniq = (list) => [...new Set(list)];
21
+ const cap = (list) => uniq(list).sort(cmp).slice(0, CAP);
22
+ const pairKey = (a, b) => (a < b ? `${a}\0${b}` : `${b}\0${a}`);
23
+
24
+ // Real test file: test-looking path, never under fixtures/mocks.
25
+ export function isTestPath(p) {
26
+ const l = norm(p).toLowerCase();
27
+ if (/(^|\/)(fixtures|__fixtures__|__mocks__)\//.test(l)) return false;
28
+ return /(^|\/)(__tests__|tests?|specs?)\//.test(l) || /\.(test|spec)\.[cm]?[jt]sx?$|\.(test|spec)\.vue$/.test(l);
29
+ }
30
+
31
+ const SRC_RE = /\.([cm]?[jt]sx?|vue)$/;
32
+ export const isTestSource = (p) => isTestPath(p) && SRC_RE.test(norm(p));
33
+
34
+ export function stemOf(p) {
35
+ const base = path.posix.basename(p, path.posix.extname(p)).toLowerCase();
36
+ if (base === 'index') return path.posix.basename(path.posix.dirname(p)).toLowerCase();
37
+ return base.replace(/(?:\.test|\.spec)+$/, '').replace(/[-_.](test|spec)$/, '');
38
+ }
39
+
40
+ // One "mention" = a whole identifier/path-segment token equal to a source stem.
41
+ export function tokenCounts(content) {
42
+ const m = new Map();
43
+ for (const t of String(content).toLowerCase().match(/[a-z0-9_$][a-z0-9_$-]*/g) ?? []) m.set(t, (m.get(t) ?? 0) + 1);
44
+ return m;
45
+ }
46
+
47
+ // {testPath: count} for a non-generic source stem; tokens: Map<testPath, Map<token,count>>.
48
+ export function mentionCountsFor(source, tokens) {
49
+ const stem = stemOf(norm(source));
50
+ const out = {};
51
+ if (GENERIC.has(stem) || stem.length < 5) return out;
52
+ for (const [t, m] of tokens) if (m.has(stem)) out[t] = m.get(stem);
53
+ return out;
54
+ }
55
+
56
+ export function findTwinGroups(entries) {
57
+ const groups = new Map();
58
+ for (const e of entries ?? []) {
59
+ const p = norm(e?.path);
60
+ if (!p || !e.hash || !(e.size >= MIN_TWIN)) continue;
61
+ if (/(^|\/)(fixtures|__fixtures__)\//.test(p) || /(^|\/)docs\/archive\//.test(p)) continue;
62
+ const key = `${e.size}:${e.hash}`;
63
+ if (!groups.has(key)) groups.set(key, new Set());
64
+ groups.get(key).add(p);
65
+ }
66
+ const top = (p) => (p.includes('/') ? p.split('/')[0] : '.');
67
+ return [...groups.values()]
68
+ .map((set) => [...set].sort(cmp))
69
+ .filter((g) => g.length >= 2 && g.length <= 4
70
+ && (g.some((p) => CODE_EXT.has(extOf(p))) || new Set(g.map(top)).size >= 2))
71
+ .sort((a, b) => cmp(a[0], b[0]));
72
+ }
73
+
74
+ export function rankTestsForSource({ source, stemMatches = [], importingTests = [], mentionCounts = {} } = {}) {
75
+ const base = path.posix.basename(norm(source), path.posix.extname(norm(source))).toLowerCase();
76
+ const generic = GENERIC.has(base) || base.length < 5;
77
+ const count = (t) => Number((mentionCounts instanceof Map ? mentionCounts.get(t) : mentionCounts?.[t]) ?? 0);
78
+ const rows = new Map();
79
+ const add = (t, tier) => { if (!rows.has(t) || rows.get(t).tier > tier) rows.set(t, { t, tier }); };
80
+ for (const t of stemMatches) add(t, 0);
81
+ for (const t of importingTests) add(t, 1);
82
+ if (!generic) {
83
+ const names = mentionCounts instanceof Map ? [...mentionCounts.keys()] : Object.keys(mentionCounts ?? {});
84
+ for (const t of names) if (count(t) > 0) add(t, 2);
85
+ }
86
+ return [...rows.values()]
87
+ .sort((a, b) => a.tier - b.tier || (a.tier === 2 ? count(b.t) - count(a.t) : 0) || cmp(a.t, b.t))
88
+ .map((r) => r.t);
89
+ }
90
+
91
+ function cleanPair(raw) {
92
+ const clean = (v) => {
93
+ if (typeof v !== 'string') return null;
94
+ const p = norm(v);
95
+ if (!p || p.startsWith('/') || /^[a-zA-Z]:/.test(p) || p.split('/').includes('..')) return null;
96
+ return p;
97
+ };
98
+ const a = clean(raw?.source);
99
+ const b = clean(raw?.mirror);
100
+ return a && b && a !== b ? [a, b] : null;
101
+ }
102
+
103
+ async function readHints(root, readFile) {
104
+ try {
105
+ const cfg = JSON.parse(String(await readFile(path.join(root, '.ukit', 'storage', 'config.json'))));
106
+ const h = cfg?.memory?.editHints ?? {};
107
+ return {
108
+ mirrors: Array.isArray(h.mirrors) ? h.mirrors : [],
109
+ ignore: Array.isArray(h.ignoreMirrors) ? h.ignoreMirrors.filter((v) => typeof v === 'string').map(norm) : [],
110
+ };
111
+ } catch {
112
+ return { mirrors: [], ignore: [] };
113
+ }
114
+ }
115
+
116
+ async function pool(items, limit, worker, signal) {
117
+ let next = 0;
118
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
119
+ while (next < items.length && !signal?.aborted) await worker(items[next++]);
120
+ }));
121
+ }
122
+
123
+ export async function buildEditGraph({
124
+ rootDir, files = [], imports = [], declaredMirrors = [], previousGraph = null,
125
+ indexDigest = null, readFile = (p) => fs.readFile(p), signal = null,
126
+ } = {}) {
127
+ const root = path.resolve(rootDir ?? '.');
128
+ const hints = await readHints(root, readFile);
129
+ const ignored = new Set(hints.ignore);
130
+ const sizes = new Map();
131
+ for (const f of files) {
132
+ const p = norm(typeof f === 'string' ? f : f?.path ?? f?.filePath);
133
+ if (p) sizes.set(p, Number(f?.size ?? 0));
134
+ }
135
+
136
+ const bySize = new Map();
137
+ for (const [p, s] of sizes) {
138
+ if (s < MIN_TWIN || s > MAX_HASH) continue;
139
+ if (!bySize.has(s)) bySize.set(s, []);
140
+ bySize.get(s).push(p);
141
+ }
142
+ const candidates = [...bySize.values()].filter((l) => l.length > 1).flat().sort(cmp);
143
+ const entries = [];
144
+ await pool(candidates, 16, async (p) => {
145
+ try {
146
+ entries.push({ path: p, size: sizes.get(p), hash: crypto.createHash('sha256').update(await readFile(path.join(root, p))).digest('hex') });
147
+ } catch { /* unreadable: no twin evidence */ }
148
+ }, signal);
149
+ if (signal?.aborted) throw new Error('edit-graph build aborted');
150
+
151
+ const pairs = new Map();
152
+ const put = (a, b, k) => {
153
+ if (a === b || !sizes.has(a) || !sizes.has(b) || ignored.has(a) || ignored.has(b)) return;
154
+ const key = pairKey(a, b);
155
+ if (!pairs.has(key) || k === 'declared') pairs.set(key, k);
156
+ };
157
+ for (const g of findTwinGroups(entries)) {
158
+ for (let i = 0; i < g.length; i++) for (let j = i + 1; j < g.length; j++) put(g[i], g[j], 'twin');
159
+ }
160
+ for (const raw of [...declaredMirrors, ...hints.mirrors]) {
161
+ const pair = cleanPair(raw);
162
+ if (pair) put(pair[0], pair[1], 'declared');
163
+ }
164
+ for (const [p, v] of Object.entries(previousGraph?.files ?? {})) {
165
+ for (const m of Array.isArray(v?.m) ? v.m : []) {
166
+ if ((m?.k === 'twin' || m?.k === 'drifted') && typeof m.p === 'string' && !pairs.has(pairKey(p, m.p))) put(p, m.p, 'drifted');
167
+ }
168
+ }
169
+
170
+ const acc = new Map();
171
+ const slot = (p) => {
172
+ if (!acc.has(p)) acc.set(p, { m: [], t: [], i: new Set(), d: new Set() });
173
+ return acc.get(p);
174
+ };
175
+ for (const [key, k] of pairs) {
176
+ const [a, b] = key.split('\0');
177
+ slot(a).m.push({ p: b, k });
178
+ slot(b).m.push({ p: a, k });
179
+ }
180
+ const edges = imports instanceof Map
181
+ ? [...imports].flatMap(([from, tos]) => [...tos].map((to) => ({ from, to })))
182
+ : imports;
183
+ for (const e of edges) {
184
+ const from = norm(e?.from);
185
+ const to = norm(e?.to);
186
+ if (from && to && from !== to && sizes.has(from) && sizes.has(to)) {
187
+ slot(from).d.add(to);
188
+ slot(to).i.add(from);
189
+ }
190
+ }
191
+ // Tests per source: stem match, importing tests, then whole-token mentions
192
+ // (same evidence the history bench replays).
193
+ const testPaths = [...sizes.keys()].filter((p) => isTestSource(p) && sizes.get(p) <= MAX_HASH).sort(cmp);
194
+ const tokens = new Map();
195
+ await pool(testPaths, 16, async (p) => {
196
+ try { tokens.set(p, tokenCounts(await readFile(path.join(root, p)))); } catch { /* unreadable */ }
197
+ }, signal);
198
+ if (signal?.aborted) throw new Error('edit-graph build aborted');
199
+ const byStem = new Map();
200
+ for (const t of testPaths) byStem.set(stemOf(t), [...(byStem.get(stemOf(t)) ?? []), t]);
201
+ for (const src of [...sizes.keys()].sort(cmp)) {
202
+ if (isTestPath(src) || !SRC_RE.test(src)) continue;
203
+ const ranked = rankTestsForSource({
204
+ source: src,
205
+ stemMatches: byStem.get(stemOf(src)) ?? [],
206
+ importingTests: [...(acc.get(src)?.i ?? [])].filter(isTestPath),
207
+ mentionCounts: mentionCountsFor(src, tokens),
208
+ }).slice(0, CAP);
209
+ if (ranked.length) slot(src).t = ranked;
210
+ }
211
+
212
+ const out = {};
213
+ for (const p of [...acc.keys()].sort(cmp)) {
214
+ const s = acc.get(p);
215
+ const m = s.m.sort((x, y) => cmp(x.p, y.p) || cmp(x.k, y.k)).slice(0, CAP);
216
+ const entry = { m, t: s.t, i: cap([...s.i]), d: cap([...s.d]) };
217
+ if (m.length || entry.t.length || entry.i.length || entry.d.length) out[p] = entry;
218
+ }
219
+ return { schemaVersion: SCHEMA, generatedAt: new Date().toISOString(), indexDigest, files: out };
220
+ }
221
+
222
+ const graphPath = (rootDir) => path.join(path.resolve(rootDir), '.cache', 'index', EDIT_GRAPH_FILE);
223
+
224
+ export async function writeEditGraph(rootDir, graph) {
225
+ const target = graphPath(rootDir);
226
+ const tmp = `${target}.tmp-${process.pid}-${Math.random().toString(16).slice(2)}`;
227
+ await fs.mkdir(path.dirname(target), { recursive: true });
228
+ try {
229
+ await fs.writeFile(tmp, JSON.stringify(graph));
230
+ await fs.rename(tmp, target);
231
+ } catch (error) {
232
+ await fs.rm(tmp, { force: true }).catch(() => {});
233
+ throw error;
234
+ }
235
+ }
236
+
237
+ export async function loadEditGraph(rootDir, { signal } = {}) {
238
+ try {
239
+ if (signal?.aborted) return null;
240
+ const file = graphPath(rootDir);
241
+ if ((await fs.stat(file)).size > MAX_LOAD) return null;
242
+ const graph = JSON.parse(await fs.readFile(file, { encoding: 'utf8', signal }));
243
+ const ok = graph && graph.schemaVersion === SCHEMA && graph.files && typeof graph.files === 'object' && !Array.isArray(graph.files);
244
+ return ok ? graph : null;
245
+ } catch {
246
+ return null;
247
+ }
248
+ }
249
+
250
+ export function neighboursOf(graph, filePath) {
251
+ const e = graph?.files && Object.hasOwn(graph.files, norm(filePath)) ? graph.files[norm(filePath)] : null;
252
+ const strs = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === 'string') : []);
253
+ return {
254
+ mirrors: (Array.isArray(e?.m) ? e.m : []).filter((x) => typeof x?.p === 'string').map((x) => ({ path: x.p, kind: x.k })),
255
+ tests: strs(e?.t),
256
+ importers: strs(e?.i),
257
+ imports: strs(e?.d),
258
+ };
259
+ }
260
+
261
+ // Index-build entry: rebuild only when the artifact is missing or its digest is
262
+ // stale. Never throws, so a graph failure cannot fail the index build.
263
+ // `inputs` may be a function so the (costly) import resolution runs only on rebuild.
264
+ export async function ensureEditGraph({ rootDir, indexDigest, inputs, signal } = {}) {
265
+ try {
266
+ const previousGraph = await loadEditGraph(rootDir);
267
+ if (previousGraph && indexDigest && previousGraph.indexDigest === indexDigest) return previousGraph;
268
+ const graph = await buildEditGraph({ rootDir, indexDigest, previousGraph, signal, ...(typeof inputs === 'function' ? await inputs() : inputs) });
269
+ await writeEditGraph(rootDir, graph);
270
+ return graph;
271
+ } catch {
272
+ return null;
273
+ }
274
+ }
@@ -4,6 +4,12 @@ import crypto from 'node:crypto';
4
4
  import { execFile, spawnSync } from 'node:child_process';
5
5
  import { withFileLock } from '../../runtime/token-utils.mjs';
6
6
  import { withAsyncLock } from '../../runtime/async-lock.mjs';
7
+ // edit-graph.mjs is optional: a partial install must not lose the whole index core.
8
+ let editGraphModule;
9
+ function loadEditGraphModule() {
10
+ editGraphModule ??= import('../edit-graph.mjs').catch(() => null);
11
+ return editGraphModule;
12
+ }
7
13
 
8
14
  // One wall-clock ceiling for the WHOLE discovery phase: both `git ls-files`
9
15
  // enumerations AND the non-git fallback walk share this single budget. Every
@@ -599,6 +605,7 @@ async function buildCodeIndexInner({ rootDir = process.cwd(), changedFiles = nul
599
605
  [INDEX_ARTIFACTS.relations]: relations.length,
600
606
  },
601
607
  });
608
+ await refreshEditGraph(absoluteRoot, sourceFingerprint.digest, fileRecords, codeFiles, imports, importAliasContext, signal);
602
609
 
603
610
  return {
604
611
  indexDir,
@@ -1192,6 +1199,7 @@ async function tryIncrementalIndexUpdate({ absoluteRoot, indexDir, changedPaths,
1192
1199
  clearIndexArtifactCache(absoluteRoot);
1193
1200
  RELATED_TEST_LOOKUP_CACHE.delete(absoluteRoot);
1194
1201
  }
1202
+ await refreshEditGraph(absoluteRoot, refreshedFingerprint.digest, mergedFileRecords, codeFiles, imports, importAliasContext, signal);
1195
1203
 
1196
1204
  return {
1197
1205
  indexDir,
@@ -3236,6 +3244,23 @@ function areBugIndexSnapshotsEqual(previousSnapshot, nextSnapshot) {
3236
3244
  && previousSnapshot.size === nextSnapshot.size;
3237
3245
  }
3238
3246
 
3247
+ // Edit graph (mirror/test/import edges): rebuilt only when missing or its digest
3248
+ // differs from the index fingerprint. Never fails the index build.
3249
+ async function refreshEditGraph(rootDir, indexDigest, fileRecords, codeFiles, imports, aliasContext, signal) {
3250
+ const graphModule = await loadEditGraphModule();
3251
+ if (!graphModule) return;
3252
+ await graphModule.ensureEditGraph({
3253
+ rootDir,
3254
+ indexDigest,
3255
+ signal,
3256
+ inputs: () => ({
3257
+ files: fileRecords,
3258
+ imports: buildResolvedImportMap(rootDir, imports, new Set(codeFiles.map((f) => f.filePath)), aliasContext),
3259
+ declaredMirrors: IMPACT_MIRROR_PAIRS,
3260
+ }),
3261
+ });
3262
+ }
3263
+
3239
3264
  async function writeArtifact(rootDir, artifactName, payload) {
3240
3265
  const artifactPath = getArtifactPath(rootDir, artifactName);
3241
3266
  const temporaryPath = `${artifactPath}.tmp-${Date.now()}-${Math.random().toString(16).slice(2)}`;
@@ -5217,7 +5242,17 @@ export async function resolveImpactContext({
5217
5242
  const callItems = safeItems(callsArtifact);
5218
5243
  const importItems = safeItems(importsArtifact);
5219
5244
  const risk = classifyImpactRisk(normalizedChangedFiles);
5220
- const mirrorCounterparts = findMirrorCounterparts(normalizedChangedFiles).slice(0, budget.maxMirrors);
5245
+ const graphModule = await loadEditGraphModule();
5246
+ const editGraph = graphModule ? await graphModule.loadEditGraph(absoluteRoot) : null;
5247
+ const mirrorCounterparts = [...findMirrorCounterparts(normalizedChangedFiles)];
5248
+ for (const changed of normalizedChangedFiles) {
5249
+ for (const mirror of graphModule?.neighboursOf(editGraph, changed).mirrors ?? []) {
5250
+ if (!mirrorCounterparts.some((m) => m.filePath === mirror.path && m.source === changed)) {
5251
+ mirrorCounterparts.push({ filePath: mirror.path, reason: `edit-graph ${mirror.kind} mirror`, source: changed });
5252
+ }
5253
+ }
5254
+ }
5255
+ mirrorCounterparts.splice(budget.maxMirrors);
5221
5256
  const changedFileSet = new Set(normalizedChangedFiles);
5222
5257
  const changedSymbolSet = new Set(normalizedChangedSymbols);
5223
5258
  const changedRecords = callItems.filter((item) => {
@@ -239,14 +239,17 @@ async function main() {
239
239
  }
240
240
  const projectRoot = process.env.CLAUDE_PROJECT_DIR || process.cwd();
241
241
  const runtimeConfig = await readRuntimeSafePatchConfig(projectRoot);
242
- const result = await verifyPostEdit({
243
- projectRoot,
244
- payload: parseJsonInput(await readStdin(), {}),
245
- });
242
+ const payload = parseJsonInput(await readStdin(), {});
243
+ const result = await verifyPostEdit({ projectRoot, payload });
246
244
  if (json) {
247
245
  process.stdout.write(`${JSON.stringify(result)}\n`);
248
246
  } else if (result.status === 'ok') {
249
- process.stdout.write(`[ukit-safe-patch] ${result.message}\n`);
247
+ // A plain-text line would make the chain's merged stdout invalid JSON and Claude Code
248
+ // would drop a later step's additionalContext (edit-hint). omp's bridge appends step
249
+ // stdout verbatim to the tool result, so omp keeps the plain line.
250
+ const line = `[ukit-safe-patch] ${result.message}`;
251
+ if (payload?.ukit_harness === 'omp' || process.env.UKIT_HARNESS === 'omp') process.stdout.write(`${line}\n`);
252
+ else emitSystemMessage(line);
250
253
  } else if (result.status === 'advisory') {
251
254
  process.stderr.write(`[ukit-safe-patch] ${result.message}\n`);
252
255
  process.stderr.write('[ukit-safe-patch] handoff authoring advisory — change is already written; continue updating docs/AI_HANDOFF/.\n');
@@ -62,6 +62,7 @@ if (!intent && !targetFile) {
62
62
  }
63
63
 
64
64
  await printContextResult(result, { rootDir, showOutline });
65
+ if (targetFile) await printEditHint({ rootDir, targetFile, intent });
65
66
  }
66
67
 
67
68
  catch (error) {
@@ -69,6 +70,22 @@ catch (error) {
69
70
  process.exit(1);
70
71
  }
71
72
 
73
+ // Computed after (never inside) the result cache so memory edits are never stale.
74
+ async function printEditHint({ rootDir, targetFile, intent }) {
75
+ try {
76
+ const { editHintFor } = await import('../runtime/memory-lanes.mjs');
77
+ let target = targetFile;
78
+ if (path.isAbsolute(target)) {
79
+ target = path.relative(path.resolve(rootDir), target).split(path.sep).join('/');
80
+ if (!target || target.startsWith('..') || path.isAbsolute(target)) return; // outside the project: silent
81
+ }
82
+ const hint = await editHintFor({ projectRoot: rootDir, target, query: intent });
83
+ if (hint.text) console.log(hint.text);
84
+ } catch {
85
+ // Hints are advisory; never fail the helper.
86
+ }
87
+ }
88
+
72
89
  async function ensureFreshIndex({ rootDir, logPrefix }) {
73
90
  if (typeof indexCore.ensureIndexFresh === 'function') {
74
91
  return indexCore.ensureIndexFresh({ rootDir, logPrefix });
@@ -38,6 +38,7 @@ import {
38
38
  } from '../runtime/memory-policy.mjs';
39
39
  import { resolveRecordFreshness } from '../runtime/memory-freshness.mjs';
40
40
  import { resolveMemoryStage } from '../runtime/memory-flags.mjs';
41
+ import { recallForHook, renderMarkdownDoc } from '../runtime/memory-recall.mjs';
41
42
  import {
42
43
  ROUTE_VERSION,
43
44
  ROUTE_CONTRACT_VERSION,
@@ -6967,12 +6968,6 @@ function normalize(text) {
6967
6968
  .trim();
6968
6969
  }
6969
6970
 
6970
- function tokenize(text) {
6971
- return normalize(text)
6972
- .split(/\s+/)
6973
- .filter((token) => token && !STOPWORDS.has(token) && token.length > 1);
6974
- }
6975
-
6976
6971
  function getMemoryTimestamp(item) {
6977
6972
  return item.content?.updatedAt
6978
6973
  ?? item.content?.endedAt
@@ -7016,29 +7011,6 @@ function buildMemorySegments(item) {
7016
7011
  ];
7017
7012
  }
7018
7013
 
7019
- function scoreMemoryItem(item, queryTokens) {
7020
- if (queryTokens.length === 0) {
7021
- return 0;
7022
- }
7023
-
7024
- let score = 0;
7025
- for (const segment of buildMemorySegments(item)) {
7026
- const segmentTokens = new Set(tokenize(segment.text));
7027
- for (const token of queryTokens) {
7028
- if (segmentTokens.has(token)) {
7029
- score += segment.weight;
7030
- }
7031
- }
7032
- }
7033
-
7034
- if (score === 0) {
7035
- return 0;
7036
- }
7037
-
7038
- const recencyBonus = getMemoryTimestamp(item) > 0 ? Math.min(1, getMemoryTimestamp(item) / Date.now()) : 0;
7039
- return score + recencyBonus;
7040
- }
7041
-
7042
7014
  async function readDirectoryJsonItems(dirPath) {
7043
7015
  let entries = [];
7044
7016
  try {
@@ -7140,8 +7112,6 @@ async function listMemoryItems(rootDir, { config, projectId } = {}) {
7140
7112
  ];
7141
7113
  }
7142
7114
 
7143
- const MEMORY_V2_RECORD_POOL_LIMIT = 20;
7144
-
7145
7115
  // v2 lane (SI-101): approved records live in a single records.json document.
7146
7116
  // Missing/malformed store → [] (same never-throw discipline as
7147
7117
  // readDirectoryJsonItems). Candidates: status 'active' AND (valid_until == null
@@ -7166,8 +7136,6 @@ export async function listMemoryV2RecordItems(runtimeRootOrProjectRoot, { config
7166
7136
  .filter((record) => record && typeof record === 'object')
7167
7137
  .filter((record) => record.status === 'active')
7168
7138
  .filter((record) => record.valid_until == null || record.valid_until > now)
7169
- .sort((left, right) => (right.created_at ?? 0) - (left.created_at ?? 0))
7170
- .slice(0, MEMORY_V2_RECORD_POOL_LIMIT)
7171
7139
  .map((record) => ({
7172
7140
  id: `record:${record.id}`,
7173
7141
  type: 'record',
@@ -7263,7 +7231,6 @@ async function buildPreviousContextSnapshot({ rootDir = process.cwd(), routingCo
7263
7231
  },
7264
7232
  };
7265
7233
  const items = await listMemoryItems(rootDir, { config: memoryConfig, projectId: binding.projectId });
7266
- const queryTokens = tokenize(taskQuery);
7267
7234
  // v2/legacy dedup: collect the legacy-lane ids first, then drop any record
7268
7235
  // whose logical twin (meta.legacyId → session:<id>, project_id →
7269
7236
  // project:<id>) is present — the legacy item carries the richer summary.
@@ -7271,7 +7238,7 @@ async function buildPreviousContextSnapshot({ rootDir = process.cwd(), routingCo
7271
7238
  items.filter((item) => item.type !== 'record').map((item) => item.id),
7272
7239
  );
7273
7240
  const eligibleCtx = { projectId: binding.projectId, projectAliases: binding.aliases, includeUser: false };
7274
- const rankedItems = items
7241
+ const eligibleItems = items
7275
7242
  .filter((item) => item.type !== 'user')
7276
7243
  .filter((item) => {
7277
7244
  if (item.type === 'record') {
@@ -7285,18 +7252,30 @@ async function buildPreviousContextSnapshot({ rootDir = process.cwd(), routingCo
7285
7252
  return matchesProjectBinding(item, binding);
7286
7253
  }
7287
7254
  return true;
7288
- })
7289
- .map((item) => ({
7290
- item,
7291
- score: scoreMemoryItem(item, queryTokens),
7292
- }))
7293
- .filter((entry) => entry.score > 0)
7294
- .sort((left, right) => (
7295
- right.score - left.score
7296
- || getMemoryTimestamp(right.item) - getMemoryTimestamp(left.item)
7297
- ))
7298
- .slice(0, 2)
7299
- .map((entry) => entry.item);
7255
+ });
7256
+ // Score-before-cut (3.5.1): every eligible item plus the markdown source
7257
+ // bullets goes through the shared BM25 engine; only then is the top 2 cut.
7258
+ const itemById = new Map();
7259
+ const docs = eligibleItems.map((item) => {
7260
+ itemById.set(item.id, item);
7261
+ return {
7262
+ id: item.id,
7263
+ type: item.type === 'record' ? item.record.type : item.type,
7264
+ provenance: item.type === 'record' ? item.record.provenance : undefined,
7265
+ // Records go in as their raw text, exactly as the CLI lane passes them: a
7266
+ // type prefix would defeat the engine's start-anchored episode shape checks.
7267
+ text: item.type === 'record'
7268
+ ? String(item.record.text ?? '')
7269
+ : buildMemorySegments(item).map((segment) => String(segment.text ?? '')).join(' '),
7270
+ created_at: getMemoryTimestamp(item),
7271
+ };
7272
+ });
7273
+ const recalled = await recallForHook({
7274
+ projectRoot: rootDir, query: taskQuery, docs, config: memoryConfig, limit: 2,
7275
+ });
7276
+ const rankedItems = recalled.ranked.map((entry) => (entry.doc.type === 'markdown'
7277
+ ? { id: entry.doc.id, type: 'markdown', doc: entry.doc }
7278
+ : itemById.get(entry.doc.id))).filter(Boolean);
7300
7279
 
7301
7280
  if (rankedItems.length === 0) {
7302
7281
  return null;
@@ -7313,7 +7292,9 @@ async function buildPreviousContextSnapshot({ rootDir = process.cwd(), routingCo
7313
7292
  }));
7314
7293
 
7315
7294
  return {
7316
- line: rankedItems.map((item) => buildPreviousContextSnippet(item, freshnessById.get(item.id))).join(' | '),
7295
+ line: rankedItems.map((item) => (item.type === 'markdown'
7296
+ ? renderMarkdownDoc(item.doc, 120)
7297
+ : buildPreviousContextSnippet(item, freshnessById.get(item.id)))).join(' | '),
7317
7298
  selectedIds: rankedItems.map((item) => item.id),
7318
7299
  fingerprint: buildCompactMachineKey('route-memory-v2', {
7319
7300
  taskQuery: normalize(taskQuery),
@@ -1890,6 +1890,7 @@ function carriedEvidenceLedger(fresh, current) {
1890
1890
  ...fresh,
1891
1891
  taskStartedAt: Number.isFinite(current.taskStartedAt) ? current.taskStartedAt : (fresh.taskStartedAt ?? null),
1892
1892
  parentSessionId: current.parentSessionId || fresh.parentSessionId || null,
1893
+ taskPrompt: current.taskPrompt || fresh.taskPrompt || null,
1893
1894
  operationBank: current.operationBank || {},
1894
1895
  receiptSequence: current.receiptSequence || 0,
1895
1896
  sourceSucceeded: fresh.sourceSucceeded || current.sourceSucceeded === true,
@@ -1989,9 +1990,51 @@ function evidencePromptKey(routeState) {
1989
1990
  }
1990
1991
  export { evidencePromptKey };
1991
1992
 
1993
+ // Episode spool (3.5.1): when a task's ledger is replaced by a different task, the outgoing
1994
+ // task's compact episode inputs are appended to `<ledger>.episodes` (bounded, async, advisory).
1995
+ // The store write stays in the CLI/SessionEnd/backfill consumer (src/core/memory/episodes.js).
1996
+ const EPISODE_SPOOL_MAX = 32;
1997
+ function boundedPrompt(text) {
1998
+ return String(text || '').replace(/\s+/g, ' ').trim().slice(0, 240) || null;
1999
+ }
2000
+ async function spoolOutgoingEpisode(target, current, next) {
2001
+ try {
2002
+ if (!current?.taskInstanceId || current.taskInstanceId === next?.taskInstanceId
2003
+ || next?.adoptedFrom === current.taskInstanceId) return;
2004
+ const receipts = Array.isArray(current.receipts) ? current.receipts : [];
2005
+ const writes = receipts.filter((r) => r?.kind === 'write' && r.success === true && typeof r.file === 'string');
2006
+ if (writes.length === 0 && current.writeSucceeded !== true) return;
2007
+ const lastVerification = receipts.filter((r) => r?.kind === 'verification').slice(-1);
2008
+ const compact = [...writes.slice(-12), ...lastVerification].map((r) => ({
2009
+ kind: r.kind,
2010
+ success: r.success === true,
2011
+ ...(typeof r.file === 'string' ? { file: r.file.slice(0, 300) } : {}),
2012
+ ...(typeof r.command === 'string' ? { command: r.command.slice(0, 300) } : {}),
2013
+ }));
2014
+ const spoolPath = `${target}.episodes`;
2015
+ const list = await readJson(spoolPath, []);
2016
+ const kept = (Array.isArray(list) ? list : []).filter((e) => e?.taskInstanceId !== current.taskInstanceId);
2017
+ kept.push({
2018
+ sessionKey: current.sessionKey,
2019
+ sessionId: current.sessionId || null,
2020
+ taskInstanceId: current.taskInstanceId,
2021
+ taskPrompt: boundedPrompt(current.taskPrompt),
2022
+ startedAt: current.taskStartedAt ?? null,
2023
+ endedAt: Date.now(),
2024
+ writeSucceeded: true,
2025
+ verificationAttempted: current.verificationAttempted === true || lastVerification.length > 0,
2026
+ verificationSucceeded: current.verificationSucceeded === true,
2027
+ blocker: current.blocker ? String(current.blocker.reason || current.blocker.code || current.blocker).slice(0, 80) : null,
2028
+ receipts: compact,
2029
+ });
2030
+ await writeJsonAtomic(spoolPath, kept.slice(-EPISODE_SPOOL_MAX));
2031
+ } catch { /* advisory: a spool failure never changes the ledger event */ }
2032
+ }
2033
+
1992
2034
  function freshLedger(payload, routeState, harness) {
1993
2035
  return {
1994
2036
  version: LEDGER_VERSION,
2037
+ taskPrompt: boundedPrompt(authoritativePromptText(routeState)),
1995
2038
  sessionKey: sessionIdentity(payload),
1996
2039
  sessionId: payload.session_id || payload.sessionId || null,
1997
2040
  transcriptPath: payload.transcript_path || payload.transcriptPath || null,
@@ -3262,6 +3305,7 @@ function reconcilePredecessorLedger(state, ledger, cwd) {
3262
3305
  taskInstanceId: state.taskInstanceId,
3263
3306
  requestKey: state.requestKey || ledger.requestKey || null,
3264
3307
  promptKey: evidencePromptKey(state),
3308
+ taskPrompt: boundedPrompt(authoritativePromptText(state)),
3265
3309
  routeFingerprint: state.fingerprint || ledger.routeFingerprint || null,
3266
3310
  adoptedFrom: ledger.taskInstanceId,
3267
3311
  operationBank: {},
@@ -3448,6 +3492,7 @@ export async function recordLedgerEvent(event, {
3448
3492
  lockedRouteState = state || null;
3449
3493
  const current = await readExecutionLedger(projectRoot, payload);
3450
3494
  let ledger = liveBaseLedger(event, current, payload, state, harness, fallbackLedger, projectRoot);
3495
+ await spoolOutgoingEpisode(target, current, ledger);
3451
3496
  // Reconcile pending journaled events first — inside this caller's acquired lock and
3452
3497
  // before its own evidence, so a timed-out writer's receipt is never stranded.
3453
3498
  const drained = await drainJournal(target, { ledger, payload, signal, deadlineMs, projectRoot });