@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,792 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { readFileSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { basename, dirname, join } from 'node:path';
4
+ import { isRecord } from '../kernel/guards.js';
5
+ import { isCodeKind, scan, } from '../workspace/scan.js';
6
+ import { FAILURE_FILE, SCHEMA_VERSION, beginBuild, beginUpdate, discardBuild, openPublished, publishBuild, readFiles, readMeta, readSchemaVersion, transaction, writeFiles, writeMeta, } from '../../storage/sqlite.js';
7
+ import { RECORD_TABLES, declarationNamesOf, deleteFileRecords, deleteOrphanSymbols, emptyCounts, filesImportingPrefix, filesReferencingNames, filesWithEdgesInto, filesWithUnresolvedImports, readFileIndex, recordWriter, simpleNameCounts, tableCounts, } from '../../storage/records.js';
8
+ import { fileDeclarations, signatureText } from './declarations.js';
9
+ import { readPackages } from './packages.js';
10
+ import { createAnalysisHost, groupPrograms, splitBy } from './program.js';
11
+ import { Resolver, isGlobalFile } from './resolve.js';
12
+ import { scanLexically } from './lexical.js';
13
+ import { extractSearchRows } from '../search/segments.js';
14
+ import { extractorStamp, impactConfigHash } from './stamp.js';
15
+ import { verifyIndex } from './verify.js';
16
+ import { recordBuildHistory } from './ui-progress.js';
17
+ const LOCKFILES = new Set([
18
+ 'package-lock.json',
19
+ 'npm-shrinkwrap.json',
20
+ 'bun.lock',
21
+ 'bun.lockb',
22
+ 'pnpm-lock.yaml',
23
+ 'yarn.lock',
24
+ ]);
25
+ const CONFIG_NAME = /^(?:tsconfig(?:\..+)?|jsconfig)\.json$/;
26
+ const CODE_OR_JSON = /\.(?:[cm]?[jt]sx?|json)$/;
27
+ /**
28
+ * D55 / D57: every visible code file outside the compiler index scope (orphan, outside `include`,
29
+ * or in an owner `exclude`) whose content was hashed (not secret, symlink, or default-excluded)
30
+ * is scanned lexically for the name cross-check.
31
+ */
32
+ function isLexicalRecord(record) {
33
+ return (record.status !== 'indexable' && isCodeKind(record.kind) && record.hash !== null);
34
+ }
35
+ /** A change to one of these can change how any file resolves: always a cold build. */
36
+ function isConfigLevel(path) {
37
+ const name = basename(path);
38
+ return (CONFIG_NAME.test(name) ||
39
+ name === 'package.json' ||
40
+ name === 'ei.config.json' ||
41
+ LOCKFILES.has(name));
42
+ }
43
+ function diffCensus(before, now) {
44
+ const old = new Map(before.map((file) => [file.path, file]));
45
+ const drift = {
46
+ added: new Set(),
47
+ changed: new Set(),
48
+ deleted: new Set(),
49
+ touched: 0,
50
+ reclassified: null,
51
+ };
52
+ for (const record of now) {
53
+ const previous = old.get(record.path);
54
+ old.delete(record.path);
55
+ if (previous === undefined) {
56
+ drift.added.add(record.path);
57
+ continue;
58
+ }
59
+ const sameStat = previous.size === record.size && previous.mtimeMs === record.mtimeMs;
60
+ // Never-read files (secret, excluded) change by size and mtime alone.
61
+ const sameContent = record.hash === null ? sameStat : previous.hash === record.hash;
62
+ if (!sameContent)
63
+ drift.changed.add(record.path);
64
+ else if (!sameStat)
65
+ drift.touched++;
66
+ const sameClass = previous.kind === record.kind &&
67
+ previous.status === record.status &&
68
+ previous.package === record.package &&
69
+ previous.tsconfig === record.tsconfig &&
70
+ previous.reason === record.reason;
71
+ if (!sameClass)
72
+ drift.reclassified ??= record.path;
73
+ }
74
+ for (const path of old.keys())
75
+ drift.deleted.add(path);
76
+ return drift;
77
+ }
78
+ function rowsOf(ts, file, sf, declarations, resolution) {
79
+ if (sf === undefined || declarations === undefined || resolution === undefined) {
80
+ // Owned by a tsconfig that could not be read: listed with a reason, never dropped.
81
+ return {
82
+ index: {
83
+ file,
84
+ extraction: 'not-in-program',
85
+ lines: 0,
86
+ surface: '',
87
+ global: false,
88
+ counts: {
89
+ indexed: 0,
90
+ local: 0,
91
+ external: 0,
92
+ externalUnresolved: 0,
93
+ unresolvedOther: 0,
94
+ outsideScope: 0,
95
+ },
96
+ },
97
+ declarations: [],
98
+ edges: [],
99
+ unresolved: [],
100
+ gaps: [],
101
+ tokens: [],
102
+ externalImports: [],
103
+ exports: [],
104
+ markers: [],
105
+ search: [],
106
+ };
107
+ }
108
+ const parseError = resolution.gaps.some((gap) => gap.code === 'parse-error');
109
+ return {
110
+ index: {
111
+ file,
112
+ extraction: parseError ? 'parse-error' : 'ok',
113
+ lines: sf.getLineAndCharacterOfPosition(sf.end).line + 1,
114
+ surface: resolution.surface,
115
+ global: resolution.global,
116
+ counts: resolution.counts,
117
+ },
118
+ declarations: declarations.declarations,
119
+ edges: resolution.edges,
120
+ unresolved: resolution.unresolved,
121
+ gaps: resolution.gaps,
122
+ tokens: resolution.tokens,
123
+ externalImports: resolution.externalImports,
124
+ exports: resolution.exports,
125
+ markers: resolution.markers,
126
+ search: parseError
127
+ ? []
128
+ : extractSearchRows(ts, file, declarations.declarations, declarations.nodesOf, (node) => signatureText(ts, sf, node)),
129
+ };
130
+ }
131
+ function roundPhases(phases) {
132
+ const rounded = { ...phases };
133
+ for (const key of Object.keys(rounded)) {
134
+ rounded[key] = Math.round(rounded[key]);
135
+ }
136
+ return rounded;
137
+ }
138
+ /**
139
+ * Decodes escaped string/template literals and identifiers only when `\\` is present so new
140
+ * declaration names match `\u0070`, `\u{70}`, `\x70`, and template escapes incrementally (F14).
141
+ */
142
+ function mentionsAnyName(ts, sf, names, nameList) {
143
+ const text = sf.text;
144
+ if (nameList.some((name) => text.includes(name)))
145
+ return true;
146
+ if (!text.includes('\\'))
147
+ return false;
148
+ let found = false;
149
+ const visit = (node) => {
150
+ if (found)
151
+ return;
152
+ if (ts.isStringLiteralLike(node)) {
153
+ if (names.has(node.text)) {
154
+ found = true;
155
+ return;
156
+ }
157
+ }
158
+ else if (ts.isIdentifier(node)) {
159
+ if (names.has(ts.idText(node))) {
160
+ found = true;
161
+ return;
162
+ }
163
+ }
164
+ else if (ts.isPrivateIdentifier(node)) {
165
+ if (names.has(ts.idText(node).slice(1))) {
166
+ found = true;
167
+ return;
168
+ }
169
+ }
170
+ ts.forEachChild(node, visit);
171
+ };
172
+ visit(sf);
173
+ return found;
174
+ }
175
+ /**
176
+ * The index pipeline of one repository (DESIGN §6.2.1): scan → extract-local → resolve → verify →
177
+ * publish. It keeps nothing between runs: every update creates its programs from the census.
178
+ */
179
+ export class Indexer {
180
+ ts;
181
+ root;
182
+ cacheDir;
183
+ options;
184
+ constructor(ts, root, cacheDir, options = {}) {
185
+ this.ts = ts;
186
+ this.root = root;
187
+ this.cacheDir = cacheDir;
188
+ this.options = options;
189
+ }
190
+ get memoryBudgetMb() {
191
+ return this.options.memoryBudgetMb;
192
+ }
193
+ async index(request) {
194
+ const progress = request.onProgress ?? (() => undefined);
195
+ let lastHudPhase = '';
196
+ let lastHudTotal;
197
+ let lastHudAt = 0;
198
+ const hud = (event) => {
199
+ if (request.onHudProgress === undefined)
200
+ return;
201
+ const now = performance.now();
202
+ if (event.phase === lastHudPhase &&
203
+ event.total === lastHudTotal &&
204
+ (event.done === undefined || event.total === undefined || event.done !== event.total) &&
205
+ now - lastHudAt < 100)
206
+ return;
207
+ lastHudAt = now;
208
+ lastHudPhase = event.phase;
209
+ lastHudTotal = event.total;
210
+ try {
211
+ request.onHudProgress(event);
212
+ }
213
+ catch {
214
+ // Presentation cannot change the build outcome.
215
+ }
216
+ };
217
+ const phases = {
218
+ scan: 0,
219
+ program: 0,
220
+ extract: 0,
221
+ resolve: 0,
222
+ verify: 0,
223
+ publish: 0,
224
+ };
225
+ const stamp = extractorStamp(this.ts.version, impactConfigHash(request.impact));
226
+ const started = performance.now();
227
+ const published = this.readPublished();
228
+ const fingerprint = request.freshness === 'stat' && published !== null
229
+ ? new Map(published.files.map((file) => [file.path, file]))
230
+ : undefined;
231
+ progress('scan');
232
+ hud({ phase: 'scan' });
233
+ const census = await scan(this.root, request.impact, this.ts, fingerprint);
234
+ phases.scan = performance.now() - started;
235
+ hud({ phase: 'scan', done: census.records.length, total: census.records.length });
236
+ const drift = published === null ? null : diffCensus(published.files, census.records);
237
+ const coldReason = this.coldReason(request, stamp, published, drift);
238
+ if (coldReason !== null || published === null || drift === null) {
239
+ return this.cold(census, coldReason ?? 'no published index', stamp, request, phases, progress, hud, started);
240
+ }
241
+ const contentDrift = drift.added.size + drift.changed.size + drift.deleted.size;
242
+ if (contentDrift === 0 && drift.touched === 0) {
243
+ hud({ phase: 'unchanged', kind: 'update' });
244
+ return this.unchanged(census, phases);
245
+ }
246
+ if (contentDrift === 0) {
247
+ return this.update(census, drift, published, stamp, request, phases, progress, hud, started, null);
248
+ }
249
+ const programStarted = performance.now();
250
+ progress('program');
251
+ hud({ phase: 'program', kind: 'update' });
252
+ const programs = this.createPrograms(census.records);
253
+ const late = this.programLevelChange(programs.groups, drift, published);
254
+ phases.program = performance.now() - programStarted;
255
+ if (late !== null) {
256
+ return this.cold(census, late, stamp, request, phases, progress, hud, started);
257
+ }
258
+ return this.update(census, drift, published, stamp, request, phases, progress, hud, started, programs);
259
+ }
260
+ readPublished() {
261
+ const db = openPublished(this.cacheDir);
262
+ if (db === null)
263
+ return null;
264
+ try {
265
+ const schema = readSchemaVersion(db);
266
+ if (schema !== SCHEMA_VERSION)
267
+ return { schema, meta: {}, files: [] };
268
+ return { schema, meta: readMeta(db), files: readFiles(db) };
269
+ }
270
+ finally {
271
+ db.close();
272
+ }
273
+ }
274
+ coldReason(request, stamp, published, drift) {
275
+ if (request.full === true)
276
+ return 'full rebuild requested';
277
+ if (published === null || drift === null)
278
+ return 'no published index';
279
+ if (published.schema !== SCHEMA_VERSION)
280
+ return `index schema ${published.schema}`;
281
+ if (published.meta.extractor_stamp !== stamp)
282
+ return 'extractor stamp changed';
283
+ for (const path of [...drift.changed, ...drift.added, ...drift.deleted]) {
284
+ if (isConfigLevel(path))
285
+ return `config changed: ${path}`;
286
+ }
287
+ if (drift.reclassified !== null)
288
+ return `classification changed: ${drift.reclassified}`;
289
+ return null;
290
+ }
291
+ /**
292
+ * Checks that need the new programs. A changed global file, or a changed file that a program
293
+ * compiles without indexing it (its types reach indexed files untracked), forces a cold build.
294
+ */
295
+ programLevelChange(groups, drift, published) {
296
+ const wasIndexable = new Set(published.files.filter((file) => file.status === 'indexable').map((file) => file.path));
297
+ const globalBefore = this.globalFiles();
298
+ for (const path of [...drift.changed, ...drift.added, ...drift.deleted]) {
299
+ if (globalBefore.has(path))
300
+ return `global file changed: ${path}`;
301
+ const abs = join(this.root, path);
302
+ const group = groups.find((g) => g.program.getSourceFile(abs) !== undefined);
303
+ const sf = group?.program.getSourceFile(abs);
304
+ if (group !== undefined && sf !== undefined) {
305
+ if (isGlobalFile(this.ts, group.program.getTypeChecker(), sf)) {
306
+ return `global file changed: ${path}`;
307
+ }
308
+ }
309
+ if (wasIndexable.has(path) || drift.added.has(path) || !CODE_OR_JSON.test(path))
310
+ continue;
311
+ // No previous programs: a deleted file's membership is unknown, so assume it was compiled.
312
+ const wasCompiled = drift.deleted.has(path);
313
+ if (sf !== undefined || wasCompiled)
314
+ return `non-indexed program file changed: ${path}`;
315
+ }
316
+ return null;
317
+ }
318
+ globalFiles() {
319
+ const db = openPublished(this.cacheDir);
320
+ if (db === null)
321
+ return new Set();
322
+ try {
323
+ const found = new Set();
324
+ for (const [file, info] of readFileIndex(db))
325
+ if (info.global)
326
+ found.add(file);
327
+ return found;
328
+ }
329
+ finally {
330
+ db.close();
331
+ }
332
+ }
333
+ /** Programs for the census, one per set of compatible tsconfigs. */
334
+ createPrograms(census) {
335
+ const owners = new Map();
336
+ for (const record of census) {
337
+ if (record.status !== 'indexable' || record.tsconfig === null)
338
+ continue;
339
+ const list = owners.get(record.tsconfig) ?? [];
340
+ list.push(record.path);
341
+ owners.set(record.tsconfig, list);
342
+ }
343
+ const { groups, errors } = groupPrograms(this.ts, this.root, owners);
344
+ return {
345
+ groups: groups.map((group) => ({
346
+ ...group,
347
+ program: this.ts.createProgram({
348
+ rootNames: group.rootNames,
349
+ options: group.options,
350
+ host: createAnalysisHost(this.ts, group.options, undefined),
351
+ }),
352
+ })),
353
+ errors,
354
+ };
355
+ }
356
+ workspacePackages(census) {
357
+ const names = new Set();
358
+ for (const record of census) {
359
+ if (basename(record.path) !== 'package.json' || record.hash === null)
360
+ continue;
361
+ try {
362
+ const pkg = JSON.parse(readFileSync(join(this.root, record.path), 'utf8'));
363
+ if (isRecord(pkg) && typeof pkg.name === 'string')
364
+ names.add(pkg.name);
365
+ }
366
+ catch {
367
+ // an unreadable package.json names no package
368
+ }
369
+ }
370
+ return names;
371
+ }
372
+ /** The program group of each indexable file's owning tsconfig. */
373
+ ownerGroups(groups, census) {
374
+ const byConfig = new Map();
375
+ for (const group of groups)
376
+ for (const config of group.configs)
377
+ byConfig.set(config, group);
378
+ const result = new Map();
379
+ for (const record of census) {
380
+ if (record.status !== 'indexable' || record.tsconfig === null)
381
+ continue;
382
+ const group = byConfig.get(record.tsconfig);
383
+ if (group !== undefined)
384
+ result.set(record.path, group);
385
+ }
386
+ return result;
387
+ }
388
+ /**
389
+ * Each indexable file's group, source file and a resolver of the group's current program
390
+ * (made on demand; a lightened group gets a new one).
391
+ */
392
+ sources(groups, census, scope) {
393
+ const ownerGroup = this.ownerGroups(groups, census);
394
+ const resolvers = new WeakMap();
395
+ return (path) => {
396
+ const group = ownerGroup.get(path);
397
+ const sf = group?.program.getSourceFile(join(this.root, path));
398
+ if (group === undefined || sf === undefined)
399
+ return undefined;
400
+ let resolver = resolvers.get(group.program);
401
+ if (resolver === undefined) {
402
+ resolver = new Resolver(this.ts, group.program, scope);
403
+ resolvers.set(group.program, resolver);
404
+ }
405
+ return { group, sf, resolver };
406
+ };
407
+ }
408
+ /** Over this share of the memory budget, programs give up their checkers between batches. */
409
+ memoryTight(fraction) {
410
+ const budget = this.options.memoryBudgetMb;
411
+ return budget !== undefined && process.memoryUsage().rss / 2 ** 20 > budget * fraction;
412
+ }
413
+ /** Swaps a group's program for one sharing every parsed file but no checker, to free memory. */
414
+ lighten(group) {
415
+ const host = createAnalysisHost(this.ts, group.options, group.program);
416
+ group.program = this.ts.createProgram({
417
+ rootNames: group.rootNames,
418
+ options: group.options,
419
+ host,
420
+ oldProgram: group.program,
421
+ });
422
+ }
423
+ cold(census, reason, stamp, request, phases, progress, hud, runStarted) {
424
+ let started = performance.now();
425
+ progress('program');
426
+ hud({ phase: 'program', kind: 'cold', reason });
427
+ const programs = this.createPrograms(census.records);
428
+ phases.program += performance.now() - started;
429
+ const indexable = census.records.filter((r) => r.status === 'indexable').map((r) => r.path);
430
+ const declarationNames = new Set();
431
+ const scope = {
432
+ root: this.root,
433
+ indexable: new Set(indexable),
434
+ declarationNames,
435
+ workspacePackages: this.workspacePackages(census.records),
436
+ };
437
+ const ownerGroup = this.ownerGroups(programs.groups, census.records);
438
+ const sourceFile = (path) => ownerGroup.get(path)?.program.getSourceFile(join(this.root, path));
439
+ // EXTRACT-LOCAL: declarations from each file's syntax tree; their names scope the resolve.
440
+ progress('extract', { files: indexable.length });
441
+ hud({ phase: 'extract', done: 0, total: indexable.length, kind: 'cold', reason });
442
+ started = performance.now();
443
+ const declarations = new Map();
444
+ let extracted = 0;
445
+ for (const path of indexable) {
446
+ const sf = sourceFile(path);
447
+ if (sf !== undefined) {
448
+ const found = fileDeclarations(this.ts, sf, path);
449
+ declarations.set(path, found);
450
+ for (const declaration of found.declarations) {
451
+ if (declaration.kind !== 'module')
452
+ declarationNames.add(declaration.simple);
453
+ }
454
+ }
455
+ hud({ phase: 'extract', done: ++extracted, total: indexable.length, file: path });
456
+ }
457
+ phases.extract = performance.now() - started;
458
+ // RESOLVE one program at a time; a resolved program gives up its checker before the next.
459
+ progress('resolve', { files: indexable.length });
460
+ hud({ phase: 'resolve', done: 0, total: indexable.length });
461
+ started = performance.now();
462
+ const db = beginBuild(this.cacheDir);
463
+ try {
464
+ writeFiles(db, census.records);
465
+ const writer = recordWriter(db);
466
+ let resolved = 0;
467
+ transaction(db, () => {
468
+ for (const path of indexable) {
469
+ if (sourceFile(path) !== undefined)
470
+ continue;
471
+ writer.write(rowsOf(this.ts, path, undefined, undefined, undefined));
472
+ hud({ phase: 'resolve', done: ++resolved, total: indexable.length, file: path });
473
+ }
474
+ for (const group of programs.groups) {
475
+ const resolver = new Resolver(this.ts, group.program, scope);
476
+ for (const path of indexable) {
477
+ if (ownerGroup.get(path) !== group)
478
+ continue;
479
+ const sf = sourceFile(path);
480
+ if (sf === undefined)
481
+ continue;
482
+ writer.write(rowsOf(this.ts, path, sf, declarations.get(path), resolver.resolveFile(sf)));
483
+ hud({ phase: 'resolve', done: ++resolved, total: indexable.length, file: path });
484
+ }
485
+ this.lighten(group);
486
+ }
487
+ this.writeOrphans(writer, census, declarationNames);
488
+ });
489
+ phases.resolve = performance.now() - started;
490
+ return this.finish(db, census, writer.inserted, stamp, request, phases, progress, hud, runStarted, programs, {
491
+ action: 'cold',
492
+ reason,
493
+ drift: { added: 0, changed: 0, deleted: 0 },
494
+ resolvedFiles: indexable.length,
495
+ programs: programs.groups.length,
496
+ });
497
+ }
498
+ catch (error) {
499
+ discardBuild(db, this.cacheDir);
500
+ throw error;
501
+ }
502
+ }
503
+ /** Lexical rows for every visible out-of-scope code file (D55, D57): names still cross-check. */
504
+ writeOrphans(writer, census, names, only) {
505
+ for (const record of census.records) {
506
+ if (!isLexicalRecord(record) || (only !== undefined && !only.has(record.path)))
507
+ continue;
508
+ writer.write(scanLexically(this.ts, record.path, readFileSync(join(this.root, record.path), 'utf8'), names));
509
+ }
510
+ }
511
+ update(census, drift, published, stamp, request, phases, progress, hud, runStarted, programs) {
512
+ const indexableNow = new Set(census.records.filter((r) => r.status === 'indexable').map((r) => r.path));
513
+ const changed = [...drift.changed, ...drift.added].filter((path) => indexableNow.has(path));
514
+ const removed = published.files
515
+ .filter((file) => file.status === 'indexable' && !indexableNow.has(file.path))
516
+ .map((file) => file.path);
517
+ const db = beginUpdate(this.cacheDir);
518
+ if (db === null) {
519
+ return this.cold(census, 'published index unreadable', stamp, request, phases, progress, hud, runStarted);
520
+ }
521
+ try {
522
+ let started = performance.now();
523
+ progress('extract', { files: changed.length });
524
+ hud({ phase: 'extract', kind: 'update', done: 0, total: changed.length });
525
+ const before = tableCounts(db);
526
+ const oldIndex = readFileIndex(db);
527
+ const oldKeys = declarationNamesOf(db, [...changed, ...removed]);
528
+ const nameCounts = simpleNameCounts(db);
529
+ const oldNames = new Set([...nameCounts].filter(([, n]) => n > 0).map(([name]) => name));
530
+ for (const simple of oldKeys.values()) {
531
+ nameCounts.set(simple, (nameCounts.get(simple) ?? 0) - 1);
532
+ }
533
+ const declarationNames = new Set();
534
+ const scope = {
535
+ root: this.root,
536
+ indexable: indexableNow,
537
+ declarationNames,
538
+ workspacePackages: this.workspacePackages(census.records),
539
+ };
540
+ const sourceOf = programs === null ? () => undefined : this.sources(programs.groups, census.records, scope);
541
+ const newKeys = new Map();
542
+ let extracted = 0;
543
+ for (const path of changed) {
544
+ const source = sourceOf(path);
545
+ if (source !== undefined) {
546
+ for (const declaration of source.resolver.declarationsOf(source.sf).declarations) {
547
+ newKeys.set(declaration.key, declaration.simple);
548
+ nameCounts.set(declaration.simple, (nameCounts.get(declaration.simple) ?? 0) + 1);
549
+ }
550
+ }
551
+ hud({ phase: 'extract', done: ++extracted, total: changed.length, file: path });
552
+ }
553
+ for (const [name, n] of nameCounts) {
554
+ if (n > 0 && name !== '<module>')
555
+ declarationNames.add(name);
556
+ }
557
+ // Names whose declarations appeared or disappeared change other files' resolution.
558
+ const names = new Set();
559
+ for (const [key, simple] of oldKeys)
560
+ if (!newKeys.has(key))
561
+ names.add(simple);
562
+ for (const [key, simple] of newKeys)
563
+ if (!oldKeys.has(key))
564
+ names.add(simple);
565
+ names.delete('<module>');
566
+ const entering = [...declarationNames].filter((name) => !oldNames.has(name));
567
+ const orphanNamesChanged = entering.length > 0 ||
568
+ [...oldNames].some((name) => name !== '<module>' && !declarationNames.has(name));
569
+ phases.extract = performance.now() - started;
570
+ // Affected set: changed files and this repository's cross-checks (no builder state, D47).
571
+ started = performance.now();
572
+ const pending = new Set(changed);
573
+ if (drift.added.size + drift.deleted.size > 0) {
574
+ // A new or removed file can change how imports resolve.
575
+ for (const path of filesWithUnresolvedImports(db))
576
+ pending.add(path);
577
+ const prefixes = [...drift.added, ...drift.deleted].map((path) => dirname(path) === '.' ? '' : `${dirname(path)}/`);
578
+ for (const path of filesImportingPrefix(db, prefixes))
579
+ pending.add(path);
580
+ }
581
+ for (const path of filesWithEdgesInto(db, removed))
582
+ pending.add(path);
583
+ for (const path of filesReferencingNames(db, names))
584
+ pending.add(path);
585
+ if (entering.length > 0) {
586
+ // A name new to the index: files mentioning it were never recorded under it.
587
+ const enteringSet = new Set(entering);
588
+ for (const path of indexableNow) {
589
+ const sf = sourceOf(path)?.sf;
590
+ if (sf !== undefined && mentionsAnyName(this.ts, sf, enteringSet, entering)) {
591
+ pending.add(path);
592
+ }
593
+ }
594
+ }
595
+ progress('resolve', { files: pending.size });
596
+ hud({ phase: 'resolve' });
597
+ const resolved = new Map();
598
+ // A file's surface counts as changed when its text-derived surface differs, or when one of
599
+ // its observable declarations (types written or inferred) has an edge into a file whose
600
+ // surface changed: an overload, a conditional or an inferred type can then resolve to
601
+ // something else with no edit to the file itself, and its dependents see a different type.
602
+ const changedSurface = new Set();
603
+ const observableKeysOf = new Map();
604
+ const isObservableSource = (keys, source) => {
605
+ if (keys.has(source))
606
+ return true;
607
+ for (let dot = source.indexOf('.', source.indexOf('#')); dot !== -1;) {
608
+ if (keys.has(source.slice(0, dot)))
609
+ return true;
610
+ dot = source.indexOf('.', dot + 1);
611
+ }
612
+ return false;
613
+ };
614
+ const leaks = (path) => {
615
+ const keys = observableKeysOf.get(path);
616
+ const rows = resolved.get(path);
617
+ if (keys === undefined || rows === undefined)
618
+ return false;
619
+ return rows.edges.some((edge) => changedSurface.has(edge.target.slice(0, edge.target.indexOf('#'))) &&
620
+ isObservableSource(keys, edge.source));
621
+ };
622
+ let next = [];
623
+ const markChanged = (start) => {
624
+ const stack = [start];
625
+ for (let path = stack.pop(); path !== undefined; path = stack.pop()) {
626
+ if (changedSurface.has(path))
627
+ continue;
628
+ changedSurface.add(path);
629
+ for (const dependent of filesWithEdgesInto(db, [path])) {
630
+ if (resolved.has(dependent)) {
631
+ if (leaks(dependent))
632
+ stack.push(dependent);
633
+ }
634
+ else if (!pending.has(dependent)) {
635
+ next.push(dependent);
636
+ }
637
+ }
638
+ }
639
+ };
640
+ // Rounds: each resolves its files one program at a time, like the cold build, and queues
641
+ // the dependents of changed surfaces for the next round.
642
+ let round = [...pending];
643
+ while (round.length > 0) {
644
+ next = [];
645
+ const byGroup = new Map();
646
+ for (const path of new Set(round)) {
647
+ if (resolved.has(path) || !indexableNow.has(path))
648
+ continue;
649
+ const group = sourceOf(path)?.group;
650
+ byGroup.set(group, [...(byGroup.get(group) ?? []), path]);
651
+ }
652
+ for (const [group, paths] of byGroup) {
653
+ for (const path of paths) {
654
+ const source = sourceOf(path);
655
+ const resolution = source?.resolver.resolveFile(source.sf);
656
+ resolved.set(path, rowsOf(this.ts, path, source?.sf, source?.resolver.declarationsOf(source.sf), resolution));
657
+ hud({ phase: 'resolve', done: resolved.size, file: path });
658
+ if (resolution === undefined)
659
+ continue;
660
+ observableKeysOf.set(path, resolution.observableKeys);
661
+ if (oldIndex.get(path)?.surface !== resolution.surface || leaks(path)) {
662
+ markChanged(path);
663
+ }
664
+ }
665
+ if (group !== undefined && this.memoryTight(0.5))
666
+ this.lighten(group);
667
+ }
668
+ round = next;
669
+ }
670
+ const expected = emptyCounts();
671
+ transaction(db, () => {
672
+ db.exec('DELETE FROM files');
673
+ writeFiles(db, census.records);
674
+ const orphanNow = new Set(census.records.filter(isLexicalRecord).map((record) => record.path));
675
+ const orphanBefore = new Set(published.files.filter(isLexicalRecord).map((record) => record.path));
676
+ const orphans = new Set(orphanNamesChanged
677
+ ? [...orphanNow, ...orphanBefore]
678
+ : [...drift.changed, ...drift.added, ...drift.deleted].filter((path) => orphanNow.has(path) || orphanBefore.has(path)));
679
+ const deleted = deleteFileRecords(db, [...resolved.keys(), ...removed, ...orphans]);
680
+ const writer = recordWriter(db);
681
+ for (const rows of resolved.values())
682
+ writer.write(rows);
683
+ this.writeOrphans(writer, census, declarationNames, orphans);
684
+ for (const table of RECORD_TABLES) {
685
+ expected[table] = before[table] - deleted[table] + writer.inserted[table];
686
+ }
687
+ deleteOrphanSymbols(db);
688
+ });
689
+ phases.resolve = performance.now() - started;
690
+ return this.finish(db, census, expected, stamp, request, phases, progress, hud, runStarted, programs, {
691
+ action: 'update',
692
+ reason: `${changed.length} changed · ${removed.length} removed · ${resolved.size} resolved`,
693
+ drift: {
694
+ added: drift.added.size,
695
+ changed: drift.changed.size,
696
+ deleted: drift.deleted.size,
697
+ },
698
+ resolvedFiles: resolved.size,
699
+ programs: programs?.groups.length ?? Number(published.meta.programs ?? 0),
700
+ });
701
+ }
702
+ catch (error) {
703
+ discardBuild(db, this.cacheDir);
704
+ throw error;
705
+ }
706
+ }
707
+ /**
708
+ * VERIFY, then PUBLISH; on failure the previous index stays and the report lists why.
709
+ * `programs` null: the census alone changed (sizes or times), not any file's content.
710
+ */
711
+ finish(db, census, produced, stamp, request, phases, progress, hud, runStarted, programs, outcome) {
712
+ progress('verify');
713
+ hud({ phase: 'verify' });
714
+ let started = performance.now();
715
+ const verify = this.options.verify ?? verifyIndex;
716
+ const problems = verify(db, { ...produced, files: census.records.length });
717
+ phases.verify = performance.now() - started;
718
+ const counts = tableCounts(db);
719
+ if (problems.length > 0) {
720
+ discardBuild(db, this.cacheDir);
721
+ const failure = { at: new Date().toISOString(), reason: `${outcome.action} build`, problems };
722
+ writeFileSync(join(this.cacheDir, FAILURE_FILE), JSON.stringify(failure), { mode: 0o600 });
723
+ return {
724
+ ...outcome,
725
+ action: 'failed',
726
+ census: census.summary,
727
+ counts,
728
+ problems,
729
+ phases: roundPhases(phases),
730
+ };
731
+ }
732
+ progress('publish');
733
+ hud({ phase: 'publish' });
734
+ started = performance.now();
735
+ const buildId = randomUUID();
736
+ writeMeta(db, {
737
+ build_id: buildId,
738
+ built_at: (programs === null ? readMeta(db).built_at : undefined) ?? new Date().toISOString(),
739
+ last_action: outcome.action,
740
+ last_reason: outcome.reason,
741
+ extractor_stamp: stamp,
742
+ typescript_version: this.ts.version,
743
+ config_hash: impactConfigHash(request.impact),
744
+ packages: JSON.stringify(readPackages(this.root, census.records)),
745
+ runtime: `${process.versions.bun === undefined ? 'node' : 'bun'} ${process.versions.bun ?? process.versions.node}`,
746
+ scan_ms: String(Math.round(phases.scan)),
747
+ listing: census.summary.listing,
748
+ tsconfigs: JSON.stringify(census.summary.tsconfigs),
749
+ tsconfig_bases: JSON.stringify(census.summary.tsconfigBases),
750
+ tsconfig_errors: JSON.stringify([
751
+ ...census.summary.tsconfigErrors,
752
+ ...(programs?.errors ?? []),
753
+ ]),
754
+ programs: String(outcome.programs),
755
+ ...(programs === null ? {} : { program_split: JSON.stringify(splitBy(programs.groups)) }),
756
+ resolved_last: String(outcome.resolvedFiles),
757
+ phases: JSON.stringify(roundPhases(phases)),
758
+ // Peak of the engine process so far. maxRSS is in kilobytes (libuv converts macOS's bytes);
759
+ // shortcut: Bun's unit on macOS is not verified, check it in the macOS run.
760
+ peak_rss_mb: String(Math.round(process.resourceUsage().maxRSS / 1024)),
761
+ });
762
+ publishBuild(db, this.cacheDir);
763
+ if (programs !== null)
764
+ rmSync(join(this.cacheDir, FAILURE_FILE), { force: true });
765
+ phases.publish = performance.now() - started;
766
+ if (request.recordHistory !== false) {
767
+ try {
768
+ recordBuildHistory(this.cacheDir, {
769
+ durationMs: Math.round(performance.now() - runStarted),
770
+ ...(outcome.action === 'cold' ? { reason: outcome.reason } : {}),
771
+ });
772
+ }
773
+ catch {
774
+ // Optional history must not turn a published build into a failed build.
775
+ }
776
+ }
777
+ return { ...outcome, census: census.summary, counts, problems, phases: roundPhases(phases) };
778
+ }
779
+ unchanged(census, phases) {
780
+ return {
781
+ action: 'unchanged',
782
+ reason: 'no drift',
783
+ census: census.summary,
784
+ drift: { added: 0, changed: 0, deleted: 0 },
785
+ resolvedFiles: 0,
786
+ programs: 0,
787
+ counts: emptyCounts(),
788
+ problems: [],
789
+ phases: roundPhases(phases),
790
+ };
791
+ }
792
+ }