@krisada-m/ksd-intelligence 0.0.0-stage → 1.0.0

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 (110) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +167 -2
  3. package/dist/adapters/agy/skills.js +252 -0
  4. package/dist/adapters/cli/check-changed.js +3 -0
  5. package/dist/adapters/cli/main.js +1002 -0
  6. package/dist/adapters/cli/policy-bin.js +10 -0
  7. package/dist/adapters/cli/review-verdict.js +3 -0
  8. package/dist/adapters/omp/extension.js +893 -0
  9. package/dist/adapters/omp/skills.js +130 -0
  10. package/dist/adapters/ui/hud.js +318 -0
  11. package/dist/adapters/ui/tree.js +460 -0
  12. package/dist/core/audit/index.js +2 -0
  13. package/dist/core/audit/log.js +505 -0
  14. package/dist/core/audit/summary.js +188 -0
  15. package/dist/core/changes/changes.js +591 -0
  16. package/dist/core/changes/git.js +266 -0
  17. package/dist/core/changes/plan.js +109 -0
  18. package/dist/core/changes/render.js +356 -0
  19. package/dist/core/engine/build.js +178 -0
  20. package/dist/core/engine/child.js +389 -0
  21. package/dist/core/engine/host.js +206 -0
  22. package/dist/core/engine/lock.js +133 -0
  23. package/dist/core/engine/protocol.js +43 -0
  24. package/dist/core/engine/runtime.js +44 -0
  25. package/dist/core/engine/status.js +381 -0
  26. package/dist/core/engine/typescript.js +194 -0
  27. package/dist/core/engine/workspace.js +72 -0
  28. package/dist/core/graph/graph.js +127 -0
  29. package/dist/core/graph/limits.js +16 -0
  30. package/dist/core/impact/query.js +1292 -0
  31. package/dist/core/impact/render.js +590 -0
  32. package/dist/core/impact/session.js +694 -0
  33. package/dist/core/indexing/declarations.js +455 -0
  34. package/dist/core/indexing/differential.js +345 -0
  35. package/dist/core/indexing/doctor.js +120 -0
  36. package/dist/core/indexing/indexer.js +792 -0
  37. package/dist/core/indexing/keys.js +451 -0
  38. package/dist/core/indexing/lexical.js +212 -0
  39. package/dist/core/indexing/packages.js +57 -0
  40. package/dist/core/indexing/program.js +171 -0
  41. package/dist/core/indexing/resolve.js +1004 -0
  42. package/dist/core/indexing/stamp.js +52 -0
  43. package/dist/core/indexing/surface.js +335 -0
  44. package/dist/core/indexing/ui-progress.js +37 -0
  45. package/dist/core/indexing/verify.js +76 -0
  46. package/dist/core/kernel/config.js +383 -0
  47. package/dist/core/kernel/glob.js +105 -0
  48. package/dist/core/kernel/guards.js +4 -0
  49. package/dist/core/kernel/types.js +3 -0
  50. package/dist/core/kernel/verdict.js +142 -0
  51. package/dist/core/knowledge/anchors.js +139 -0
  52. package/dist/core/knowledge/knowledge.js +95 -0
  53. package/dist/core/knowledge/learning.js +102 -0
  54. package/dist/core/knowledge/render.js +76 -0
  55. package/dist/core/knowledge/store.js +109 -0
  56. package/dist/core/knowledge/yaml.js +87 -0
  57. package/dist/core/search/lexical.js +382 -0
  58. package/dist/core/search/render.js +98 -0
  59. package/dist/core/search/segments.js +118 -0
  60. package/dist/core/verify/parse.js +127 -0
  61. package/dist/core/verify/render.js +67 -0
  62. package/dist/core/verify/report.js +40 -0
  63. package/dist/core/verify/revision.js +79 -0
  64. package/dist/core/verify/run.js +117 -0
  65. package/dist/core/verify/store.js +66 -0
  66. package/dist/core/verify/verify.js +173 -0
  67. package/dist/core/workspace/init.js +267 -0
  68. package/dist/core/workspace/probe.js +56 -0
  69. package/dist/core/workspace/scan.js +420 -0
  70. package/dist/index.js +20 -0
  71. package/dist/policy/change-scope.js +500 -0
  72. package/dist/policy/check-changed.js +40 -0
  73. package/dist/policy/config.js +106 -0
  74. package/dist/policy/dist/policy.d.ts +17 -0
  75. package/dist/policy/dist/policy.js +147 -0
  76. package/dist/policy/dist/runtime.d.ts +40 -0
  77. package/dist/policy/dist/runtime.js +75 -0
  78. package/dist/policy/dist/sdlc.d.ts +7 -0
  79. package/dist/policy/dist/sdlc.js +27 -0
  80. package/dist/policy/eslint-rules/index.js +107 -0
  81. package/dist/policy/index.d.ts +2 -0
  82. package/dist/policy/index.js +241 -0
  83. package/dist/policy/package.json +33 -0
  84. package/dist/policy/policy.d.ts +2 -0
  85. package/dist/policy/policy.js +2 -0
  86. package/dist/policy/review-verdict.js +262 -0
  87. package/dist/policy/sdlc.js +2 -0
  88. package/dist/storage/records.js +245 -0
  89. package/dist/storage/sqlite.js +314 -0
  90. package/dist/workflow/catalog.js +69 -0
  91. package/dist/workflow/classify.js +55 -0
  92. package/dist/workflow/loader.js +140 -0
  93. package/dist/workflow/packs.js +469 -0
  94. package/dist/workflow/registry.js +359 -0
  95. package/dist/workflow/render.js +61 -0
  96. package/dist/workflow/router.js +141 -0
  97. package/dist/workflow/sources.js +229 -0
  98. package/dist/workflow/types.js +44 -0
  99. package/dist/workflow/updates.js +532 -0
  100. package/package.json +74 -4
  101. package/scripts/agy-mcp.mjs +27 -0
  102. package/scripts/mcp/stdio.mjs +304 -0
  103. package/scripts/mcp/tools.mjs +451 -0
  104. package/skills/ksd-intelligence/SKILL.md +54 -0
  105. package/skills/matt-sdlc/SKILL.md +42 -0
  106. package/skills/osmani-quality/SKILL.md +38 -0
  107. package/skills/poteto-mode/SKILL.md +40 -0
  108. package/skills/pstack-analysis/SKILL.md +36 -0
  109. package/skills.lock.json +71 -0
  110. package/skills.registry.json +181 -0
@@ -0,0 +1,345 @@
1
+ import { join } from 'node:path';
2
+ import { enclosingKey, fileDeclarations } from './declarations.js';
3
+ import { groupPrograms } from './program.js';
4
+ /** Deterministic sample: every declaration when `size` is 0, else `size` of them by a seeded shuffle. */
5
+ function sample(db, size, seed) {
6
+ const rows = db
7
+ .prepare(`SELECT s.key AS key, d.file AS file FROM declarations d JOIN symbols s ON s.id = d.id
8
+ WHERE d.name != '<module>' ORDER BY s.key`)
9
+ .all()
10
+ .map((row) => ({ key: String(row.key), file: String(row.file) }));
11
+ if (size <= 0 || size >= rows.length)
12
+ return rows;
13
+ let state = seed >>> 0;
14
+ const random = () => {
15
+ state = (state + 0x6d2b79f5) >>> 0;
16
+ let t = state;
17
+ t = Math.imul(t ^ (t >>> 15), t | 1);
18
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
19
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
20
+ };
21
+ for (let i = rows.length - 1; i > 0; i--) {
22
+ const j = Math.floor(random() * (i + 1));
23
+ const swap = rows[i];
24
+ const other = rows[j];
25
+ if (swap === undefined || other === undefined)
26
+ continue;
27
+ rows[i] = other;
28
+ rows[j] = swap;
29
+ }
30
+ return rows.slice(0, size).sort((a, b) => (a.key < b.key ? -1 : 1));
31
+ }
32
+ /** Ranges of every JSDoc comment of a file: `[pos, end)`. */
33
+ function jsDocRanges(ts, sf) {
34
+ const ranges = [];
35
+ const visit = (node) => {
36
+ if ('jsDoc' in node && Array.isArray(node.jsDoc)) {
37
+ for (const doc of node.jsDoc)
38
+ if (ts.isJSDoc(doc))
39
+ ranges.push([doc.pos, doc.end]);
40
+ }
41
+ ts.forEachChild(node, visit);
42
+ };
43
+ visit(sf);
44
+ return ranges;
45
+ }
46
+ function nameNode(ts, node) {
47
+ if (ts.isBinaryExpression(node)) {
48
+ const left = node.left;
49
+ return ts.isPropertyAccessExpression(left) ? left.name : undefined;
50
+ }
51
+ if (ts.isSourceFile(node))
52
+ return undefined;
53
+ const name = ts.getNameOfDeclaration(node);
54
+ return name;
55
+ }
56
+ /** The innermost node at a position. */
57
+ function nodeAt(ts, sf, position) {
58
+ let current = sf;
59
+ for (;;) {
60
+ let next;
61
+ ts.forEachChild(current, (child) => {
62
+ if (next === undefined && child.getStart(sf) <= position && position < child.getEnd()) {
63
+ next = child;
64
+ }
65
+ });
66
+ if (next === undefined)
67
+ return current;
68
+ current = next;
69
+ }
70
+ }
71
+ function contextOf(ts, node) {
72
+ const kinds = [];
73
+ let current = node;
74
+ for (let depth = 0; current !== undefined && depth < 4; depth++) {
75
+ kinds.push(ts.SyntaxKind[current.kind] ?? String(current.kind));
76
+ current = current.parent;
77
+ }
78
+ return kinds.join(' < ');
79
+ }
80
+ function insideImportOrReexport(ts, node) {
81
+ for (let current = node; current !== undefined; current = current.parent) {
82
+ if (ts.isImportDeclaration(current) || ts.isImportEqualsDeclaration(current))
83
+ return current;
84
+ if (ts.isExportDeclaration(current)) {
85
+ return current.moduleSpecifier === undefined ? 'local-export' : current;
86
+ }
87
+ if (ts.isStatement(current))
88
+ return null;
89
+ }
90
+ return null;
91
+ }
92
+ /**
93
+ * D36 differential test: for sampled indexed declarations, every reference TypeScript's language
94
+ * service reports inside the index scope must be an edge in the index at that line, or a recorded
95
+ * unresolved use or gap site there. Import and re-export bindings must have their file-level
96
+ * IMPORTS edge (ADR 0003 stores bindings at file level).
97
+ */
98
+ export function differential(ts, root, db, options) {
99
+ const owners = new Map();
100
+ const indexable = new Set();
101
+ for (const row of db
102
+ .prepare("SELECT path, tsconfig FROM files WHERE status = 'indexable'")
103
+ .all()) {
104
+ const path = String(row.path);
105
+ indexable.add(path);
106
+ if (row.tsconfig === null)
107
+ continue;
108
+ const list = owners.get(String(row.tsconfig)) ?? [];
109
+ list.push(path);
110
+ owners.set(String(row.tsconfig), list);
111
+ }
112
+ const ownerOf = new Map();
113
+ for (const [config, files] of owners)
114
+ for (const file of files)
115
+ ownerOf.set(file, config);
116
+ const edgeLines = db.prepare(`SELECT e.lines AS lines FROM edges e JOIN symbols s ON s.id = e.source
117
+ JOIN symbols t ON t.id = e.target WHERE s.key = ? AND t.key = ?`);
118
+ const importLines = db.prepare(`SELECT e.lines AS lines FROM edges e JOIN symbols s ON s.id = e.source
119
+ WHERE s.key = ? AND e.kind = 'IMPORTS'`);
120
+ const recorded = db.prepare(`SELECT 1 FROM gap_sites WHERE file = ? AND line = ?
121
+ UNION ALL SELECT 1 FROM unresolved WHERE file = ? AND line = ? LIMIT 1`);
122
+ const hasLine = (rows, line) => rows.some((row) => {
123
+ const lines = JSON.parse(String(row.lines));
124
+ return Array.isArray(lines) && lines.includes(line);
125
+ });
126
+ const report = {
127
+ declarations: 0,
128
+ references: 0,
129
+ covered: 0,
130
+ coveredBy: { edge: 0, exportStatus: 0, recordOnly: 0 },
131
+ skipped: {},
132
+ docOnly: 0,
133
+ misses: [],
134
+ };
135
+ const skip = (reason) => {
136
+ report.skipped[reason] = (report.skipped[reason] ?? 0) + 1;
137
+ };
138
+ const samples = sample(db, options.size, options.seed ?? 1);
139
+ const { groups } = groupPrograms(ts, root, owners);
140
+ for (const group of groups) {
141
+ const members = samples.filter((s) => group.configs.includes(ownerOf.get(s.file) ?? ''));
142
+ if (members.length === 0)
143
+ continue;
144
+ const host = {
145
+ getCompilationSettings: () => group.options,
146
+ getScriptFileNames: () => group.rootNames,
147
+ getScriptVersion: () => '1',
148
+ getScriptSnapshot: (fileName) => {
149
+ const text = ts.sys.readFile(fileName);
150
+ return text === undefined ? undefined : ts.ScriptSnapshot.fromString(text);
151
+ },
152
+ getCurrentDirectory: () => root,
153
+ getDefaultLibFileName: (o) => ts.getDefaultLibFilePath(o),
154
+ fileExists: ts.sys.fileExists,
155
+ readFile: ts.sys.readFile,
156
+ readDirectory: ts.sys.readDirectory,
157
+ directoryExists: ts.sys.directoryExists,
158
+ getDirectories: ts.sys.getDirectories,
159
+ realpath: ts.sys.realpath,
160
+ };
161
+ const service = ts.createLanguageService(host, ts.createDocumentRegistry());
162
+ const program = service.getProgram();
163
+ if (program === undefined)
164
+ continue;
165
+ const declarationsCache = new Map();
166
+ const declarationsOf = (path, sf) => {
167
+ let found = declarationsCache.get(path);
168
+ if (found === undefined) {
169
+ found = fileDeclarations(ts, sf, path);
170
+ declarationsCache.set(path, found);
171
+ }
172
+ return found;
173
+ };
174
+ const docRanges = new Map();
175
+ const insideJsDoc = (sf, position) => {
176
+ let ranges = docRanges.get(sf.fileName);
177
+ if (ranges === undefined) {
178
+ ranges = jsDocRanges(ts, sf);
179
+ docRanges.set(sf.fileName, ranges);
180
+ }
181
+ return ranges.some(([pos, end]) => pos <= position && position < end);
182
+ };
183
+ const keyAtName = (path, sf, start) => {
184
+ for (const [node, key] of declarationsOf(path, sf).keyOf) {
185
+ const name = nameNode(ts, node);
186
+ if (name === undefined)
187
+ continue;
188
+ // TypeScript's span of a quoted name (`"tab.shell": …`) starts inside the quotes.
189
+ if (name.getStart(sf) + (ts.isStringLiteralLike(name) ? 1 : 0) === start)
190
+ return key;
191
+ }
192
+ return undefined;
193
+ };
194
+ /** The indexed declaration a group of references belongs to. */
195
+ const targetOf = (definition, queried) => {
196
+ // An import or re-export binding is the queried declaration under another name.
197
+ if (definition.kind === ts.ScriptElementKind.alias)
198
+ return queried;
199
+ const path = repoPath(root, definition.fileName);
200
+ const file = path === null ? undefined : program.getSourceFile(definition.fileName);
201
+ if (path === null || file === undefined)
202
+ return undefined;
203
+ return keyAtName(path, file, definition.textSpan.start);
204
+ };
205
+ for (const { key, file } of members) {
206
+ const sf = program.getSourceFile(join(root, file));
207
+ if (sf === undefined)
208
+ continue;
209
+ const entry = [...declarationsOf(file, sf).keyOf].find(([, k]) => k === key);
210
+ const name = entry === undefined ? undefined : nameNode(ts, entry[0]);
211
+ if (name === undefined) {
212
+ skip('declaration without a name node');
213
+ continue;
214
+ }
215
+ report.declarations++;
216
+ for (const symbol of service.findReferences(sf.fileName, name.getStart(sf)) ?? []) {
217
+ const target = targetOf(symbol.definition, key);
218
+ // ADR 0003 explains each kind: parameters, locals, type parameters, members of anonymous
219
+ // types and library declarations are not indexed declarations.
220
+ const outside = repoPath(root, symbol.definition.fileName) === null;
221
+ const unindexed = `target is not an indexed declaration: ${symbol.definition.kind}${outside ? ' (outside the repository)' : ''}`;
222
+ for (const reference of symbol.references) {
223
+ if (reference.isDefinition === true) {
224
+ skip('definition');
225
+ continue;
226
+ }
227
+ const path = repoPath(root, reference.fileName);
228
+ if (path === null || !indexable.has(path)) {
229
+ skip('outside the index scope');
230
+ continue;
231
+ }
232
+ if (target === undefined) {
233
+ skip(unindexed);
234
+ continue;
235
+ }
236
+ const refFile = program.getSourceFile(reference.fileName);
237
+ if (refFile === undefined)
238
+ continue;
239
+ const start = reference.textSpan.start;
240
+ const line = refFile.getLineAndCharacterOfPosition(start).line + 1;
241
+ if (insideJsDoc(refFile, start)) {
242
+ report.docOnly++;
243
+ continue;
244
+ }
245
+ const node = nodeAt(ts, refFile, start);
246
+ // TypeScript lists the names of related declarations (an implementing or overriding
247
+ // member) among the references; a name is a declaration, not a use, unless it is a
248
+ // shorthand `{ x }`, which is both.
249
+ if (keyAtName(path, refFile, start) !== undefined &&
250
+ !ts.isShorthandPropertyAssignment(node.parent)) {
251
+ skip('declaration name of a related symbol');
252
+ continue;
253
+ }
254
+ // `{ x }` is a property and a use of `x`; findReferences on the property also lists the
255
+ // uses of the value `x` itself, which belong to x's declaration, not to the property.
256
+ const sampled = entry?.[0];
257
+ if (sampled !== undefined && ts.isShorthandPropertyAssignment(sampled)) {
258
+ const symbol = program.getTypeChecker().getSymbolAtLocation(node);
259
+ if (symbol !== undefined && !(symbol.declarations ?? []).includes(sampled)) {
260
+ skip('use of the value a shorthand property names');
261
+ continue;
262
+ }
263
+ }
264
+ // A key of an object literal typed by a mapped type over literal keys (`Record<1 | 2, V>`)
265
+ // has no declaration to be a use of: TypeScript relates it to every other literal typed the
266
+ // same way, but none uses another. Keys that have declarations are still checked.
267
+ const member = node.parent;
268
+ if ((ts.isPropertyAssignment(member) ||
269
+ ts.isMethodDeclaration(member) ||
270
+ ts.isGetAccessorDeclaration(member) ||
271
+ ts.isSetAccessorDeclaration(member)) &&
272
+ member.name === node &&
273
+ ts.isObjectLiteralExpression(member.parent) &&
274
+ (ts.isIdentifier(node) || ts.isStringLiteralLike(node) || ts.isNumericLiteral(node))) {
275
+ const properties = contextualProperties(program.getTypeChecker(), member.parent, node.text);
276
+ if (properties.length > 0 &&
277
+ properties.every((p) => (p.declarations ?? []).length === 0)) {
278
+ skip('key of an object literal typed by a mapped type (no declaration)');
279
+ continue;
280
+ }
281
+ }
282
+ // The same holds for an access (`map["k"]` on a `Record<"k" | …, V>`): the property it
283
+ // uses has no declaration, so ADR 0003 stores no edge, yet TypeScript lists the access
284
+ // under each object literal's `"k"`.
285
+ const own = program.getTypeChecker().getSymbolAtLocation(node);
286
+ if (own !== undefined && (own.declarations ?? []).length === 0) {
287
+ skip('use of a property of a mapped type (no declaration)');
288
+ continue;
289
+ }
290
+ report.references++;
291
+ const declarations = declarationsOf(path, refFile);
292
+ const binding = insideImportOrReexport(ts, node);
293
+ let by = null;
294
+ if (binding === 'local-export') {
295
+ by = 'exportStatus';
296
+ }
297
+ else if (binding !== null) {
298
+ const statementLine = refFile.getLineAndCharacterOfPosition(binding.getStart(refFile)).line + 1;
299
+ if (hasLine(importLines.all(declarations.moduleKey), statementLine))
300
+ by = 'edge';
301
+ }
302
+ else if (hasLine(edgeLines.all(enclosingKey(node, declarations), target), line)) {
303
+ by = 'edge';
304
+ }
305
+ else if (recorded.get(path, line, path, line) !== undefined) {
306
+ by = 'recordOnly';
307
+ }
308
+ if (by !== null) {
309
+ report.covered++;
310
+ report.coveredBy[by]++;
311
+ continue;
312
+ }
313
+ report.misses.push({
314
+ declaration: target,
315
+ file: path,
316
+ line,
317
+ text: (refFile.text.split('\n')[line - 1] ?? '').trim().slice(0, 160),
318
+ context: contextOf(ts, node),
319
+ });
320
+ }
321
+ }
322
+ }
323
+ service.dispose();
324
+ }
325
+ return report;
326
+ }
327
+ /** The property `name` of an object literal's contextual type; of each member for a union. */
328
+ function contextualProperties(checker, literal, name) {
329
+ const type = checker.getContextualType(literal);
330
+ if (type === undefined)
331
+ return [];
332
+ const found = new Set();
333
+ for (const part of type.isUnion() ? type.types : [type]) {
334
+ const property = checker.getPropertyOfType(checker.getApparentType(part), name);
335
+ if (property !== undefined)
336
+ found.add(property);
337
+ }
338
+ return [...found];
339
+ }
340
+ function repoPath(root, fileName) {
341
+ if (!fileName.startsWith(`${root}/`))
342
+ return null;
343
+ const rel = fileName.slice(root.length + 1);
344
+ return rel.includes('node_modules/') ? null : rel;
345
+ }
@@ -0,0 +1,120 @@
1
+ import { rmSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { FAILURE_FILE, indexPath, openPublished } from '../../storage/sqlite.js';
4
+ import { canonicalLines, counterLines } from '../../storage/records.js';
5
+ import { differential } from './differential.js';
6
+ import { Indexer } from './indexer.js';
7
+ function lines(cacheDir) {
8
+ const db = openPublished(cacheDir);
9
+ if (db === null)
10
+ return { graph: [], counters: [] };
11
+ try {
12
+ return { graph: canonicalLines(db), counters: counterLines(db) };
13
+ }
14
+ finally {
15
+ db.close();
16
+ }
17
+ }
18
+ /**
19
+ * `ei doctor --deep`: update the active index, rebuild from scratch into a temp database and diff
20
+ * the two (any difference is an incremental bug); optionally run the differential test against
21
+ * TypeScript's find-references. One set of programs is alive at a time.
22
+ */
23
+ export async function doctorDeep(ts, indexer, impact, options) {
24
+ const progress = options.onProgress ?? (() => undefined);
25
+ const hud = (event) => {
26
+ try {
27
+ options.onHudProgress?.(event);
28
+ }
29
+ catch {
30
+ // Optional presentation must not change doctor results.
31
+ }
32
+ };
33
+ progress('doctor: update active index');
34
+ hud({ phase: 'doctor:update' });
35
+ const update = await indexer.index({
36
+ impact,
37
+ freshness: 'hash',
38
+ onProgress: progress,
39
+ onHudProgress: options.onHudProgress === undefined
40
+ ? undefined
41
+ : (event) => hud({ ...event, phase: `doctor:update:${event.phase}` }),
42
+ });
43
+ if (update.action === 'failed') {
44
+ throw new Error(`doctor: active index verification failed: ${update.problems.join('; ')}`);
45
+ }
46
+ const temp = join(indexer.cacheDir, `doctor-${process.pid}`);
47
+ rmSync(temp, { recursive: true, force: true });
48
+ let cold;
49
+ let differences;
50
+ let counterDifferences;
51
+ const rebuild = new Indexer(ts, indexer.root, temp, {
52
+ memoryBudgetMb: indexer.memoryBudgetMb,
53
+ });
54
+ try {
55
+ progress('doctor: cold rebuild');
56
+ hud({ phase: 'doctor:rebuild', kind: 'cold' });
57
+ cold = await rebuild.index({
58
+ impact,
59
+ full: true,
60
+ recordHistory: false,
61
+ onHudProgress: options.onHudProgress === undefined
62
+ ? undefined
63
+ : (event) => hud({ ...event, phase: `doctor:rebuild:${event.phase}` }),
64
+ });
65
+ if (cold.action === 'failed') {
66
+ throw new Error(`doctor: cold rebuild verification failed: ${cold.problems.join('; ')}`);
67
+ }
68
+ const active = lines(indexer.cacheDir);
69
+ const rebuilt = lines(temp);
70
+ const inActive = new Set(active.graph);
71
+ const inRebuilt = new Set(rebuilt.graph);
72
+ const onlyActive = active.graph.filter((line) => !inRebuilt.has(line));
73
+ const onlyCold = rebuilt.graph.filter((line) => !inActive.has(line));
74
+ differences = {
75
+ count: onlyActive.length + onlyCold.length,
76
+ onlyActive: onlyActive.slice(0, 20),
77
+ onlyCold: onlyCold.slice(0, 20),
78
+ };
79
+ const counterSet = new Set(rebuilt.counters);
80
+ const drifted = active.counters.filter((line) => !counterSet.has(line));
81
+ counterDifferences = {
82
+ count: drifted.length,
83
+ files: drifted.slice(0, 20).map((line) => line.split('\t')[1] ?? ''),
84
+ };
85
+ }
86
+ finally {
87
+ rmSync(temp, { recursive: true, force: true });
88
+ }
89
+ let report = null;
90
+ if (options.differential !== 0) {
91
+ progress('doctor: differential');
92
+ hud({ phase: 'doctor:differential' });
93
+ const db = openPublished(indexer.cacheDir);
94
+ if (db === null)
95
+ throw new Error(`doctor: no published index at ${indexPath(indexer.cacheDir)}`);
96
+ try {
97
+ report = differential(ts, indexer.root, db, {
98
+ size: Math.max(0, options.differential),
99
+ seed: options.seed,
100
+ });
101
+ }
102
+ finally {
103
+ db.close();
104
+ }
105
+ }
106
+ const problems = [
107
+ ...(differences.count > 0 ? [`doctor: ${differences.count} canonical differences`] : []),
108
+ ...((report?.misses.length ?? 0) > 0
109
+ ? [`doctor: ${report?.misses.length} differential misses`]
110
+ : []),
111
+ ];
112
+ const failurePath = join(indexer.cacheDir, FAILURE_FILE);
113
+ if (problems.length > 0) {
114
+ writeFileSync(failurePath, JSON.stringify({ at: new Date().toISOString(), reason: 'doctor', problems }), { mode: 0o600 });
115
+ }
116
+ else {
117
+ rmSync(failurePath, { force: true });
118
+ }
119
+ return { update, cold, differences, counterDifferences, differential: report };
120
+ }