@ngockhoale/ukit 3.5.1 → 3.5.3

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 (39) hide show
  1. package/CHANGELOG.md +35 -297
  2. package/README.md +1 -0
  3. package/manifests/platform.full.yaml +23 -0
  4. package/package.json +8 -1
  5. package/src/cli/commands/doctor.js +14 -2
  6. package/src/cli/commands/memory.js +30 -2
  7. package/src/core/memory/memoryHit.js +2 -0
  8. package/src/core/memory/mutateMemory.js +9 -0
  9. package/src/core/memory/projectIdentity.js +9 -2
  10. package/src/core/memory/recallEngine.js +86 -4
  11. package/src/core/memory/registryPrune.js +230 -0
  12. package/src/core/memory/retrieval.js +12 -3
  13. package/src/core/runtimeConfig.js +1 -0
  14. package/src/index/buildIndex.js +22 -0
  15. package/src/index/impactContext.js +11 -1
  16. package/src/index/queryIndex.js +151 -20
  17. package/template_project/.claude/hooks/edit-hint.mjs +119 -0
  18. package/template_project/.claude/settings.json +2 -2
  19. package/template_project/.claude/ukit/index/edit-graph.mjs +404 -0
  20. package/template_project/.claude/ukit/index/lib/index-core.mjs +185 -20
  21. package/template_project/.claude/ukit/index/post-edit-verify.mjs +8 -5
  22. package/template_project/.claude/ukit/index/resolve-context.mjs +17 -0
  23. package/template_project/.claude/ukit/index/route-task.mjs +4 -1
  24. package/template_project/.claude/ukit/runtime/hook-chain-runner.mjs +62 -5
  25. package/template_project/.claude/ukit/runtime/memory-lanes.mjs +259 -0
  26. package/template_project/.claude/ukit/runtime/memory-recall.mjs +86 -4
  27. package/template_project/.claude/ukit/runtime/memory-validity.mjs +232 -0
  28. package/template_project/.claude/ukit/runtime/reinject-context.mjs +4 -2
  29. package/template_project/.omp/hooks/pre/ukit-bridge.js +2 -1
  30. package/template_project/AGENTS.md +1 -1
  31. package/template_project/CLAUDE.md +1 -1
  32. package/template_project/instructions/core.md +1 -1
  33. package/src/core/observability/evaluation/experimentPlan.js +0 -95
  34. package/src/core/observability/evaluation/perturbation.js +0 -273
  35. package/src/diagnostics/classifyHang.js +0 -246
  36. package/src/diagnostics/ompStallSnapshot.js +0 -199
  37. package/src/render/instructionRenderer.js +0 -290
  38. package/src/skill/auditSkill.js +0 -140
  39. package/template_project/instructions/overlays/repo.md +0 -9
@@ -0,0 +1,404 @@
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
+ import { execFile } from 'node:child_process';
8
+
9
+ export const EDIT_GRAPH_FILE = 'edit-graph.json';
10
+ const SCHEMA = 1;
11
+ const CAP = 5;
12
+ const TOGETHER = 3;
13
+ const MIN_TWIN = 200;
14
+ const MAX_HASH = 512 * 1024;
15
+ const MAX_LOAD = 2 * 1024 * 1024;
16
+ const CODE_EXT = new Set('js mjs cjs ts tsx jsx vue sh py go java cs php rb rs json yaml yml'.split(' '));
17
+ const GENERIC = new Set('index main utils types config constants helpers'.split(' '));
18
+
19
+ const norm = (p) => String(p ?? '').trim().replace(/\\/g, '/').replace(/^(\.\/)+/, '');
20
+ const cmp = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
21
+ const extOf = (p) => path.posix.extname(p).slice(1).toLowerCase();
22
+ const uniq = (list) => [...new Set(list)];
23
+ const cap = (list) => uniq(list).sort(cmp).slice(0, CAP);
24
+ const pairKey = (a, b) => (a < b ? `${a}\0${b}` : `${b}\0${a}`);
25
+
26
+ // Real test file: test-looking path, never under fixtures/mocks.
27
+ export function isTestPath(p) {
28
+ const l = norm(p).toLowerCase();
29
+ if (/(^|\/)(fixtures|__fixtures__|__mocks__)\//.test(l)) return false;
30
+ return /(^|\/)(__tests__|tests?|specs?)\//.test(l) || /\.(test|spec)\.[cm]?[jt]sx?$|\.(test|spec)\.vue$/.test(l);
31
+ }
32
+
33
+ const SRC_RE = /\.([cm]?[jt]sx?|vue)$/;
34
+ export const isTestSource = (p) => isTestPath(p) && SRC_RE.test(norm(p));
35
+
36
+ export function stemOf(p) {
37
+ const base = path.posix.basename(p, path.posix.extname(p)).toLowerCase();
38
+ if (base === 'index') return path.posix.basename(path.posix.dirname(p)).toLowerCase();
39
+ return base.replace(/(?:\.test|\.spec)+$/, '').replace(/[-_.](test|spec)$/, '');
40
+ }
41
+
42
+ // One "mention" = a whole identifier/path-segment token equal to a source stem.
43
+ export function tokenCounts(content) {
44
+ const m = new Map();
45
+ for (const t of String(content).toLowerCase().match(/[a-z0-9_$][a-z0-9_$-]*/g) ?? []) m.set(t, (m.get(t) ?? 0) + 1);
46
+ return m;
47
+ }
48
+
49
+ // {testPath: count} for a non-generic source stem; tokens: Map<testPath, Map<token,count>>.
50
+ export function mentionCountsFor(source, tokens) {
51
+ const stem = stemOf(norm(source));
52
+ const out = {};
53
+ if (GENERIC.has(stem) || stem.length < 5) return out;
54
+ for (const [t, m] of tokens) if (m.has(stem)) out[t] = m.get(stem);
55
+ return out;
56
+ }
57
+
58
+ export function findTwinGroups(entries) {
59
+ const groups = new Map();
60
+ for (const e of entries ?? []) {
61
+ const p = norm(e?.path);
62
+ if (!p || !e.hash || !(e.size >= MIN_TWIN)) continue;
63
+ if (/(^|\/)(fixtures|__fixtures__)\//.test(p) || /(^|\/)docs\/archive\//.test(p)) continue;
64
+ const key = `${e.size}:${e.hash}`;
65
+ if (!groups.has(key)) groups.set(key, new Set());
66
+ groups.get(key).add(p);
67
+ }
68
+ const top = (p) => (p.includes('/') ? p.split('/')[0] : '.');
69
+ return [...groups.values()]
70
+ .map((set) => [...set].sort(cmp))
71
+ .filter((g) => g.length >= 2 && g.length <= 4
72
+ && (g.some((p) => CODE_EXT.has(extOf(p))) || new Set(g.map(top)).size >= 2))
73
+ .sort((a, b) => cmp(a[0], b[0]));
74
+ }
75
+
76
+ // Tiers (lower = earlier). coTests: [{path, count}] test files committed together
77
+ // with the source. A name/import edge that history confirms is the strongest signal,
78
+ // a repeated co-change alone comes next, then the name edges the history never saw.
79
+ export const STRONG_CO = 3;
80
+ // Grid-picked on the replay: a name edge alone outranks a weak (count 2) co-change.
81
+ export const TIER_ORDER = ['both', 'strong', 'name', 'weak'];
82
+ export function rankTestsForSource({ source, stemMatches = [], importingTests = [], mentionCounts = {}, coTests = [] } = {}, tuning = {}) {
83
+ const strongCo = tuning.strongCo ?? STRONG_CO;
84
+ const order = tuning.order ?? TIER_ORDER;
85
+ const base = path.posix.basename(norm(source), path.posix.extname(norm(source))).toLowerCase();
86
+ const generic = GENERIC.has(base) || base.length < 5;
87
+ const count = (t) => Number((mentionCounts instanceof Map ? mentionCounts.get(t) : mentionCounts?.[t]) ?? 0);
88
+ const co = new Map((coTests ?? []).map((c) => [c.path, Number(c.count) || 0]));
89
+ const name = new Map(); // test -> best name tier: 0 stem, 1 import, 2 mention
90
+ const add = (t, tier) => { if (!name.has(t) || name.get(t) > tier) name.set(t, tier); };
91
+ for (const t of stemMatches) add(t, 0);
92
+ for (const t of importingTests) add(t, 1);
93
+ if (!generic) {
94
+ const names = mentionCounts instanceof Map ? [...mentionCounts.keys()] : Object.keys(mentionCounts ?? {});
95
+ for (const t of names) if (count(t) > 0) add(t, 2);
96
+ }
97
+ const klass = (t) => {
98
+ const n = name.get(t);
99
+ const c = co.get(t) ?? 0;
100
+ if (n === undefined) return c >= strongCo ? 'strong' : 'weak'; // co-change only
101
+ return c > 0 ? 'both' : 'name'; // name edge confirmed by history / name edge alone
102
+ };
103
+ const tierOf = (t) => order.indexOf(klass(t)) * 4 + (name.get(t) ?? 0);
104
+ return [...new Set([...name.keys(), ...co.keys()])]
105
+ .sort((a, b) => tierOf(a) - tierOf(b) || (co.get(b) ?? 0) - (co.get(a) ?? 0) || count(b) - count(a) || cmp(a, b));
106
+ }
107
+
108
+ // Co-change model: how often two files were committed together. Commits touching
109
+ // more than MAX_COMMIT_FILES files (merge/squash/format noise) add no pairs but
110
+ // still count toward a file's own commit total. add/remove keep a sliding window
111
+ // cheap, which is how the history bench mines "strictly before this commit".
112
+ export const CO_MAX_COMMITS = 500;
113
+ export const CO_MAX_COMMIT_FILES = 50;
114
+ export const CO_MIN_COUNT = 2;
115
+
116
+ export function createCoChange({ maxCommitFiles = CO_MAX_COMMIT_FILES } = {}) {
117
+ const peers = new Map(); // file -> Map(other -> count)
118
+ const commits = new Map(); // file -> number of commits touching it
119
+ const bump = (map, key, d) => {
120
+ const n = (map.get(key) ?? 0) + d;
121
+ if (n > 0) map.set(key, n); else map.delete(key);
122
+ };
123
+ const apply = (files, d_) => {
124
+ const set = [...new Set((files ?? []).map(norm).filter(Boolean))];
125
+ for (const f of set) bump(commits, f, d_);
126
+ if (set.length < 2 || set.length > maxCommitFiles) return;
127
+ for (const a of set) {
128
+ if (!peers.has(a)) peers.set(a, new Map());
129
+ for (const b of set) if (a !== b) bump(peers.get(a), b, d_);
130
+ if (!peers.get(a).size) peers.delete(a);
131
+ }
132
+ };
133
+ return {
134
+ add: (files) => apply(files, 1),
135
+ remove: (files) => apply(files, -1),
136
+ commitsOf: (file) => commits.get(norm(file)) ?? 0,
137
+ // [{path, count, confidence}] strongest first (count desc, confidence desc, path asc).
138
+ peersOf(file, { minCount = CO_MIN_COUNT } = {}) {
139
+ const f = norm(file);
140
+ const total = commits.get(f) ?? 0;
141
+ const out = [];
142
+ for (const [p, count] of peers.get(f) ?? []) if (count >= minCount) out.push({ path: p, count, confidence: count / total });
143
+ return out.sort((x, y) => y.count - x.count || y.confidence - x.confidence || cmp(x.path, y.path));
144
+ },
145
+ };
146
+ }
147
+
148
+ // Co-changed peers of `source` that still exist, split into test files and the rest.
149
+ // Shared by the graph build and the history bench so both score the same evidence.
150
+ export function coChangeFor(model, source, { exists = () => true, minCount = CO_MIN_COUNT } = {}) {
151
+ const tests = [];
152
+ const files = [];
153
+ const src = norm(source);
154
+ for (const peer of model?.peersOf(src, { minCount }) ?? []) {
155
+ if (peer.path === src || !exists(peer.path)) continue;
156
+ (isTestSource(peer.path) ? tests : isTestPath(peer.path) ? [] : files).push(peer);
157
+ }
158
+ return { tests, files };
159
+ }
160
+
161
+ // "@@<sha>" header lines followed by the commit's file names (git log --name-only).
162
+ export function parseCoChangeLog(out) {
163
+ const list = [];
164
+ let cur = null;
165
+ for (const line of String(out ?? '').split('\n')) {
166
+ if (line.startsWith('@@')) {
167
+ const sha = line.slice(2).trim();
168
+ cur = /^[0-9a-f]{40}$/i.test(sha) ? { sha: sha.toLowerCase(), files: [] } : null;
169
+ if (cur) list.push(cur);
170
+ } else if (cur && line.trim()) {
171
+ cur.files.push(norm(line));
172
+ }
173
+ }
174
+ return list;
175
+ }
176
+
177
+ function git(rootDir, args, { signal, timeoutMs = 20_000 } = {}) {
178
+ return new Promise((resolve) => {
179
+ if (signal?.aborted) return resolve(null);
180
+ try {
181
+ execFile('git', args, { cwd: rootDir, maxBuffer: 64 * 1024 * 1024, timeout: timeoutMs, killSignal: 'SIGKILL', ...(signal ? { signal } : {}), windowsHide: true },
182
+ (error, stdout) => resolve(error ? null : String(stdout)));
183
+ } catch {
184
+ resolve(null);
185
+ }
186
+ });
187
+ }
188
+
189
+ export async function gitHead(rootDir, opts = {}) {
190
+ const sha = String(await git(rootDir, ['rev-parse', 'HEAD'], { timeoutMs: 5000, ...opts }) ?? '').trim();
191
+ return /^[0-9a-f]{40}$/i.test(sha) ? sha.toLowerCase() : null;
192
+ }
193
+
194
+ // Bounded history for the graph build. Graph build/refresh only, never the hook path.
195
+ // Non-git directory or any git failure -> null (graph still builds without co-change).
196
+ export async function mineCoChange(rootDir, { maxCommits = CO_MAX_COMMITS, signal, timeoutMs } = {}) {
197
+ const root = path.resolve(rootDir ?? '.');
198
+ const head = await gitHead(root, { signal });
199
+ if (!head) return null;
200
+ const log = await git(root, ['-c', 'core.quotePath=false', 'log', '--no-renames', '--name-only', '--format=@@%H', '-n', String(maxCommits)], { signal, timeoutMs });
201
+ if (log === null) return null;
202
+ return { head, commits: parseCoChangeLog(log).map((c) => c.files) };
203
+ }
204
+
205
+ function cleanPair(raw) {
206
+ const clean = (v) => {
207
+ if (typeof v !== 'string') return null;
208
+ const p = norm(v);
209
+ if (!p || p.startsWith('/') || /^[a-zA-Z]:/.test(p) || p.split('/').includes('..')) return null;
210
+ return p;
211
+ };
212
+ const a = clean(raw?.source);
213
+ const b = clean(raw?.mirror);
214
+ return a && b && a !== b ? [a, b] : null;
215
+ }
216
+
217
+ async function readHints(root, readFile) {
218
+ try {
219
+ const cfg = JSON.parse(String(await readFile(path.join(root, '.ukit', 'storage', 'config.json'))));
220
+ const h = cfg?.memory?.editHints ?? {};
221
+ return {
222
+ mirrors: Array.isArray(h.mirrors) ? h.mirrors : [],
223
+ ignore: Array.isArray(h.ignoreMirrors) ? h.ignoreMirrors.filter((v) => typeof v === 'string').map(norm) : [],
224
+ coChange: h.coChange === true, // the "changed together" line only; test co-change is always mined
225
+ };
226
+ } catch {
227
+ return { mirrors: [], ignore: [], coChange: false };
228
+ }
229
+ }
230
+
231
+ async function pool(items, limit, worker, signal) {
232
+ let next = 0;
233
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
234
+ while (next < items.length && !signal?.aborted) await worker(items[next++]);
235
+ }));
236
+ }
237
+
238
+ export async function buildEditGraph({
239
+ rootDir, files = [], imports = [], declaredMirrors = [], previousGraph = null,
240
+ indexDigest = null, readFile = (p) => fs.readFile(p), signal = null,
241
+ } = {}) {
242
+ const root = path.resolve(rootDir ?? '.');
243
+ const hints = await readHints(root, readFile);
244
+ const ignored = new Set(hints.ignore);
245
+ const sizes = new Map();
246
+ for (const f of files) {
247
+ const p = norm(typeof f === 'string' ? f : f?.path ?? f?.filePath);
248
+ if (p) sizes.set(p, Number(f?.size ?? 0));
249
+ }
250
+
251
+ const bySize = new Map();
252
+ for (const [p, s] of sizes) {
253
+ if (s < MIN_TWIN || s > MAX_HASH) continue;
254
+ if (!bySize.has(s)) bySize.set(s, []);
255
+ bySize.get(s).push(p);
256
+ }
257
+ const candidates = [...bySize.values()].filter((l) => l.length > 1).flat().sort(cmp);
258
+ const entries = [];
259
+ await pool(candidates, 16, async (p) => {
260
+ try {
261
+ entries.push({ path: p, size: sizes.get(p), hash: crypto.createHash('sha256').update(await readFile(path.join(root, p))).digest('hex') });
262
+ } catch { /* unreadable: no twin evidence */ }
263
+ }, signal);
264
+ if (signal?.aborted) throw new Error('edit-graph build aborted');
265
+
266
+ const pairs = new Map();
267
+ const put = (a, b, k) => {
268
+ if (a === b || !sizes.has(a) || !sizes.has(b) || ignored.has(a) || ignored.has(b)) return;
269
+ const key = pairKey(a, b);
270
+ if (!pairs.has(key) || k === 'declared') pairs.set(key, k);
271
+ };
272
+ for (const g of findTwinGroups(entries)) {
273
+ for (let i = 0; i < g.length; i++) for (let j = i + 1; j < g.length; j++) put(g[i], g[j], 'twin');
274
+ }
275
+ for (const raw of [...declaredMirrors, ...hints.mirrors]) {
276
+ const pair = cleanPair(raw);
277
+ if (pair) put(pair[0], pair[1], 'declared');
278
+ }
279
+ for (const [p, v] of Object.entries(previousGraph?.files ?? {})) {
280
+ for (const m of Array.isArray(v?.m) ? v.m : []) {
281
+ if ((m?.k === 'twin' || m?.k === 'drifted') && typeof m.p === 'string' && !pairs.has(pairKey(p, m.p))) put(p, m.p, 'drifted');
282
+ }
283
+ }
284
+
285
+ const acc = new Map();
286
+ const slot = (p) => {
287
+ if (!acc.has(p)) acc.set(p, { m: [], t: [], c: [], i: new Set(), d: new Set() });
288
+ return acc.get(p);
289
+ };
290
+ for (const [key, k] of pairs) {
291
+ const [a, b] = key.split('\0');
292
+ slot(a).m.push({ p: b, k });
293
+ slot(b).m.push({ p: a, k });
294
+ }
295
+ const edges = imports instanceof Map
296
+ ? [...imports].flatMap(([from, tos]) => [...tos].map((to) => ({ from, to })))
297
+ : imports;
298
+ for (const e of edges) {
299
+ const from = norm(e?.from);
300
+ const to = norm(e?.to);
301
+ if (from && to && from !== to && sizes.has(from) && sizes.has(to)) {
302
+ slot(from).d.add(to);
303
+ slot(to).i.add(from);
304
+ }
305
+ }
306
+ // Tests per source: stem match, importing tests, then whole-token mentions
307
+ // (same evidence the history bench replays).
308
+ const testPaths = [...sizes.keys()].filter((p) => isTestSource(p) && sizes.get(p) <= MAX_HASH).sort(cmp);
309
+ const tokens = new Map();
310
+ await pool(testPaths, 16, async (p) => {
311
+ try { tokens.set(p, tokenCounts(await readFile(path.join(root, p)))); } catch { /* unreadable */ }
312
+ }, signal);
313
+ if (signal?.aborted) throw new Error('edit-graph build aborted');
314
+ const byStem = new Map();
315
+ for (const t of testPaths) byStem.set(stemOf(t), [...(byStem.get(stemOf(t)) ?? []), t]);
316
+ // Co-change from bounded git history (async, abortable; null outside git or on any
317
+ // git failure, in which case the graph is the name/import graph only).
318
+ const mined = await mineCoChange(root, { signal });
319
+ if (signal?.aborted) throw new Error('edit-graph build aborted');
320
+ const model = createCoChange();
321
+ for (const files of mined?.commits ?? []) model.add(files);
322
+ for (const src of [...sizes.keys()].sort(cmp)) {
323
+ if (isTestPath(src) || !SRC_RE.test(src)) continue;
324
+ const co = coChangeFor(model, src, { exists: (p) => sizes.has(p) });
325
+ const ranked = rankTestsForSource({
326
+ source: src,
327
+ stemMatches: byStem.get(stemOf(src)) ?? [],
328
+ importingTests: [...(acc.get(src)?.i ?? [])].filter(isTestPath),
329
+ mentionCounts: mentionCountsFor(src, tokens),
330
+ coTests: co.tests,
331
+ }).slice(0, CAP);
332
+ if (ranked.length) slot(src).t = ranked;
333
+ const twins = new Set((acc.get(src)?.m ?? []).map((x) => x.p));
334
+ const together = co.files.filter((x) => !twins.has(x.path) && !ignored.has(x.path)).slice(0, TOGETHER).map((x) => ({ p: x.path, n: x.count }));
335
+ if (hints.coChange && together.length) slot(src).c = together;
336
+ }
337
+
338
+ const out = {};
339
+ for (const p of [...acc.keys()].sort(cmp)) {
340
+ const s = acc.get(p);
341
+ const m = s.m.sort((x, y) => cmp(x.p, y.p) || cmp(x.k, y.k)).slice(0, CAP);
342
+ const entry = { m, t: s.t, i: cap([...s.i]), d: cap([...s.d]) };
343
+ if (s.c.length) entry.c = s.c;
344
+ if (m.length || entry.t.length || entry.i.length || entry.d.length || s.c.length) out[p] = entry;
345
+ }
346
+ // head: the commit the co-change evidence was mined at; a moved HEAD triggers a rebuild.
347
+ return { schemaVersion: SCHEMA, generatedAt: new Date().toISOString(), indexDigest, head: mined?.head ?? null, files: out };
348
+ }
349
+
350
+ const graphPath = (rootDir) => path.join(path.resolve(rootDir), '.cache', 'index', EDIT_GRAPH_FILE);
351
+
352
+ export async function writeEditGraph(rootDir, graph) {
353
+ const target = graphPath(rootDir);
354
+ const tmp = `${target}.tmp-${process.pid}-${Math.random().toString(16).slice(2)}`;
355
+ await fs.mkdir(path.dirname(target), { recursive: true });
356
+ try {
357
+ await fs.writeFile(tmp, JSON.stringify(graph));
358
+ await fs.rename(tmp, target);
359
+ } catch (error) {
360
+ await fs.rm(tmp, { force: true }).catch(() => {});
361
+ throw error;
362
+ }
363
+ }
364
+
365
+ export async function loadEditGraph(rootDir, { signal } = {}) {
366
+ try {
367
+ if (signal?.aborted) return null;
368
+ const file = graphPath(rootDir);
369
+ if ((await fs.stat(file)).size > MAX_LOAD) return null;
370
+ const graph = JSON.parse(await fs.readFile(file, { encoding: 'utf8', signal }));
371
+ const ok = graph && graph.schemaVersion === SCHEMA && graph.files && typeof graph.files === 'object' && !Array.isArray(graph.files);
372
+ return ok ? graph : null;
373
+ } catch {
374
+ return null;
375
+ }
376
+ }
377
+
378
+ export function neighboursOf(graph, filePath) {
379
+ const e = graph?.files && Object.hasOwn(graph.files, norm(filePath)) ? graph.files[norm(filePath)] : null;
380
+ const strs = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === 'string') : []);
381
+ return {
382
+ mirrors: (Array.isArray(e?.m) ? e.m : []).filter((x) => typeof x?.p === 'string').map((x) => ({ path: x.p, kind: x.k })),
383
+ tests: strs(e?.t),
384
+ importers: strs(e?.i),
385
+ imports: strs(e?.d),
386
+ together: (Array.isArray(e?.c) ? e.c : []).filter((x) => typeof x?.p === 'string').map((x) => ({ path: x.p, count: Number(x.n) || 0 })),
387
+ };
388
+ }
389
+
390
+ // Index-build entry: rebuild only when the artifact is missing or its digest is
391
+ // stale. Never throws, so a graph failure cannot fail the index build.
392
+ // `inputs` may be a function so the (costly) import resolution runs only on rebuild.
393
+ export async function ensureEditGraph({ rootDir, indexDigest, inputs, signal } = {}) {
394
+ try {
395
+ const previousGraph = await loadEditGraph(rootDir);
396
+ const head = await gitHead(path.resolve(rootDir), { signal });
397
+ if (previousGraph && indexDigest && previousGraph.indexDigest === indexDigest && (previousGraph.head ?? null) === head) return previousGraph;
398
+ const graph = await buildEditGraph({ rootDir, indexDigest, previousGraph, signal, ...(typeof inputs === 'function' ? await inputs() : inputs) });
399
+ await writeEditGraph(rootDir, graph);
400
+ return graph;
401
+ } catch {
402
+ return null;
403
+ }
404
+ }