@krisada-m/ksd-intelligence 0.0.0-stage → 1.1.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 (119) hide show
  1. package/.antigravity-plugin/plugin.json +20 -0
  2. package/LICENSE +21 -0
  3. package/README.md +195 -2
  4. package/agy-skills/erosiano-review/SKILL.md +17 -0
  5. package/dist/adapters/agy/skills.js +252 -0
  6. package/dist/adapters/cli/check-changed.js +3 -0
  7. package/dist/adapters/cli/main.js +1013 -0
  8. package/dist/adapters/cli/policy-bin.js +10 -0
  9. package/dist/adapters/cli/review-verdict.js +3 -0
  10. package/dist/adapters/omp/extension.js +884 -0
  11. package/dist/adapters/omp/skills.js +130 -0
  12. package/dist/adapters/ui/hud.js +389 -0
  13. package/dist/adapters/ui/tree.js +471 -0
  14. package/dist/core/audit/index.js +2 -0
  15. package/dist/core/audit/log.js +505 -0
  16. package/dist/core/audit/summary.js +188 -0
  17. package/dist/core/changes/changes.js +591 -0
  18. package/dist/core/changes/git.js +266 -0
  19. package/dist/core/changes/plan.js +109 -0
  20. package/dist/core/changes/render.js +356 -0
  21. package/dist/core/engine/build.js +178 -0
  22. package/dist/core/engine/child.js +389 -0
  23. package/dist/core/engine/host.js +206 -0
  24. package/dist/core/engine/lock.js +133 -0
  25. package/dist/core/engine/protocol.js +43 -0
  26. package/dist/core/engine/runtime.js +44 -0
  27. package/dist/core/engine/status.js +452 -0
  28. package/dist/core/engine/typescript.js +194 -0
  29. package/dist/core/engine/workspace.js +72 -0
  30. package/dist/core/graph/graph.js +127 -0
  31. package/dist/core/graph/limits.js +16 -0
  32. package/dist/core/impact/query.js +1292 -0
  33. package/dist/core/impact/render.js +590 -0
  34. package/dist/core/impact/session.js +694 -0
  35. package/dist/core/indexing/declarations.js +455 -0
  36. package/dist/core/indexing/differential.js +345 -0
  37. package/dist/core/indexing/doctor.js +120 -0
  38. package/dist/core/indexing/indexer.js +811 -0
  39. package/dist/core/indexing/keys.js +451 -0
  40. package/dist/core/indexing/lexical.js +212 -0
  41. package/dist/core/indexing/packages.js +57 -0
  42. package/dist/core/indexing/program.js +171 -0
  43. package/dist/core/indexing/resolve.js +1004 -0
  44. package/dist/core/indexing/stamp.js +52 -0
  45. package/dist/core/indexing/surface.js +335 -0
  46. package/dist/core/indexing/ui-progress.js +37 -0
  47. package/dist/core/indexing/verify.js +76 -0
  48. package/dist/core/kernel/config.js +383 -0
  49. package/dist/core/kernel/glob.js +105 -0
  50. package/dist/core/kernel/guards.js +4 -0
  51. package/dist/core/kernel/types.js +3 -0
  52. package/dist/core/kernel/verdict.js +142 -0
  53. package/dist/core/knowledge/anchors.js +139 -0
  54. package/dist/core/knowledge/knowledge.js +95 -0
  55. package/dist/core/knowledge/learning.js +102 -0
  56. package/dist/core/knowledge/render.js +76 -0
  57. package/dist/core/knowledge/store.js +109 -0
  58. package/dist/core/knowledge/yaml.js +87 -0
  59. package/dist/core/search/lexical.js +382 -0
  60. package/dist/core/search/render.js +98 -0
  61. package/dist/core/search/segments.js +118 -0
  62. package/dist/core/verify/parse.js +127 -0
  63. package/dist/core/verify/render.js +67 -0
  64. package/dist/core/verify/report.js +40 -0
  65. package/dist/core/verify/revision.js +79 -0
  66. package/dist/core/verify/run.js +117 -0
  67. package/dist/core/verify/store.js +66 -0
  68. package/dist/core/verify/verify.js +173 -0
  69. package/dist/core/workspace/init.js +267 -0
  70. package/dist/core/workspace/probe.js +56 -0
  71. package/dist/core/workspace/scan.js +420 -0
  72. package/dist/engineering/baseline.js +337 -0
  73. package/dist/engineering/change-scope.js +500 -0
  74. package/dist/engineering/check-changed.js +40 -0
  75. package/dist/engineering/config.js +129 -0
  76. package/dist/engineering/dist/policy.d.ts +17 -0
  77. package/dist/engineering/dist/policy.js +150 -0
  78. package/dist/engineering/dist/runtime.d.ts +40 -0
  79. package/dist/engineering/dist/runtime.js +77 -0
  80. package/dist/engineering/dist/sdlc.d.ts +7 -0
  81. package/dist/engineering/dist/sdlc.js +27 -0
  82. package/dist/engineering/eslint-rules/index.js +107 -0
  83. package/dist/engineering/index.d.ts +7 -0
  84. package/dist/engineering/index.js +319 -0
  85. package/dist/engineering/intelligence.js +44 -0
  86. package/dist/engineering/package.json +36 -0
  87. package/dist/engineering/policy.js +2 -0
  88. package/dist/engineering/practice-tool.js +72 -0
  89. package/dist/engineering/practices.js +283 -0
  90. package/dist/engineering/practices.json +2453 -0
  91. package/dist/engineering/review-verdict.js +262 -0
  92. package/dist/engineering/sdlc.js +2 -0
  93. package/dist/index.js +20 -0
  94. package/dist/storage/records.js +245 -0
  95. package/dist/storage/sqlite.js +314 -0
  96. package/dist/workflow/catalog.js +69 -0
  97. package/dist/workflow/classify.js +55 -0
  98. package/dist/workflow/loader.js +140 -0
  99. package/dist/workflow/packs.js +469 -0
  100. package/dist/workflow/registry.js +359 -0
  101. package/dist/workflow/render.js +61 -0
  102. package/dist/workflow/router.js +141 -0
  103. package/dist/workflow/sources.js +229 -0
  104. package/dist/workflow/types.js +44 -0
  105. package/dist/workflow/updates.js +532 -0
  106. package/engineering.lock.json +94 -0
  107. package/package.json +81 -4
  108. package/rules/engineering.md +20 -0
  109. package/scripts/agy-mcp.mjs +27 -0
  110. package/scripts/mcp/engineering.mjs +91 -0
  111. package/scripts/mcp/stdio.mjs +304 -0
  112. package/scripts/mcp/tools.mjs +491 -0
  113. package/skills/ksd-intelligence/SKILL.md +54 -0
  114. package/skills/matt-sdlc/SKILL.md +42 -0
  115. package/skills/osmani-quality/SKILL.md +38 -0
  116. package/skills/poteto-mode/SKILL.md +40 -0
  117. package/skills/pstack-analysis/SKILL.md +36 -0
  118. package/skills.lock.json +71 -0
  119. package/skills.registry.json +181 -0
@@ -0,0 +1,52 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readdirSync, readFileSync } from 'node:fs';
3
+ import { fileURLToPath } from 'node:url';
4
+ const INDEXING_DIR = fileURLToPath(new URL('.', import.meta.url));
5
+ // The census classification decides what is indexable, so it is part of the extractor too.
6
+ const SCAN_MODULE = fileURLToPath(new URL('../workspace/scan.js', import.meta.url));
7
+ // Search segmentation and doc/signature extraction determine declarations_fts content.
8
+ const SEARCH_SEGMENTS_MODULE = fileURLToPath(new URL('../search/segments.js', import.meta.url));
9
+ let moduleHash;
10
+ function hashOfExtractorModules() {
11
+ if (moduleHash === undefined) {
12
+ const hash = createHash('sha256');
13
+ const files = readdirSync(INDEXING_DIR)
14
+ .filter((name) => name.endsWith('.js'))
15
+ .sort()
16
+ .map((name) => `${INDEXING_DIR}/${name}`);
17
+ for (const file of [...files, SCAN_MODULE, SEARCH_SEGMENTS_MODULE]) {
18
+ hash.update(readFileSync(file));
19
+ }
20
+ moduleHash = hash.digest('hex');
21
+ }
22
+ return moduleHash;
23
+ }
24
+ /**
25
+ * D23: the extractor stamp, part of every cache key. Built extractor modules + TypeScript version +
26
+ * the index-relevant config, so a change to any of them invalidates every record without anyone
27
+ * remembering to bump a version.
28
+ */
29
+ export function extractorStamp(typescriptVersion, configHash) {
30
+ return createHash('sha256')
31
+ .update(`${hashOfExtractorModules()}\n${typescriptVersion}\n${configHash}`)
32
+ .digest('hex')
33
+ .slice(0, 16);
34
+ }
35
+ /** Recorded at build time; a different hash later means the index no longer matches the config. */
36
+ export function impactConfigHash(impact) {
37
+ const { enabled, include, exclude, routes, maxDepth, freshness, watch, manyCallers, useWorkspaceTypescript, maxMemoryMb, } = impact;
38
+ return createHash('sha256')
39
+ .update(JSON.stringify({
40
+ enabled,
41
+ include,
42
+ exclude,
43
+ routes,
44
+ maxDepth,
45
+ freshness,
46
+ watch,
47
+ manyCallers,
48
+ useWorkspaceTypescript,
49
+ maxMemoryMb,
50
+ }))
51
+ .digest('hex');
52
+ }
@@ -0,0 +1,335 @@
1
+ import { createHash } from 'node:crypto';
2
+ const IDENTIFIER = /[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*/gu;
3
+ const SCRIPT_FILE = /\.(?:[cm]?js|jsx)$/i;
4
+ function shortHash(text, length) {
5
+ return createHash('sha256').update(text).digest('hex').slice(0, length);
6
+ }
7
+ function unwrapExpr(ts, expr) {
8
+ let current = expr;
9
+ while (ts.isParenthesizedExpression(current) ||
10
+ ts.isAsExpression(current) ||
11
+ ts.isSatisfiesExpression(current) ||
12
+ ts.isTypeAssertionExpression(current) ||
13
+ ts.isNonNullExpression(current)) {
14
+ current = current.expression;
15
+ }
16
+ return current;
17
+ }
18
+ function createPiece(ts, sf) {
19
+ const text = sf.text;
20
+ const script = SCRIPT_FILE.test(sf.fileName);
21
+ const begin = (node) => (script ? node.getFullStart() : node.getStart(sf));
22
+ const whole = (node) => text.slice(begin(node), node.end);
23
+ const functionPiece = (node, from) => {
24
+ const hasWrittenResult = ts.isConstructorDeclaration(node) ||
25
+ ts.isSetAccessorDeclaration(node) ||
26
+ node.type !== undefined;
27
+ const written = !script && hasWrittenResult && node.parameters.every((p) => p.type !== undefined);
28
+ if (!written)
29
+ return text.slice(from, node.end);
30
+ const body = 'body' in node ? node.body : undefined;
31
+ return text.slice(from, body === undefined ? node.end : body.getStart(sf));
32
+ };
33
+ const piece = (node) => {
34
+ if (ts.isClassLike(node)) {
35
+ return [text.slice(begin(node), node.members.pos), ...node.members.map(piece)].join('\n');
36
+ }
37
+ if (ts.isFunctionLike(node))
38
+ return functionPiece(node, begin(node));
39
+ if (ts.isVariableDeclaration(node)) {
40
+ // `const` and `let` infer literal types differently.
41
+ const flags = ts.getCombinedNodeFlags(node) & (ts.NodeFlags.Const | ts.NodeFlags.Let);
42
+ const from = begin(node);
43
+ const init = node.initializer;
44
+ if (!script && node.type !== undefined) {
45
+ return `${flags}:${text.slice(from, node.type.end)}`;
46
+ }
47
+ if (!script &&
48
+ init !== undefined &&
49
+ (ts.isArrowFunction(init) || ts.isFunctionExpression(init))) {
50
+ return `${flags}:${functionPiece(init, from)}`;
51
+ }
52
+ return `${flags}:${text.slice(from, node.end)}`;
53
+ }
54
+ if (ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isParameter(node)) {
55
+ if (!script && node.type !== undefined)
56
+ return text.slice(begin(node), node.type.end);
57
+ return whole(node);
58
+ }
59
+ if (ts.isBindingElement(node)) {
60
+ // A destructured name takes its type from the declaration's type or initializer.
61
+ let owner = node.parent;
62
+ while (ts.isObjectBindingPattern(owner) ||
63
+ ts.isArrayBindingPattern(owner) ||
64
+ ts.isBindingElement(owner)) {
65
+ owner = owner.parent;
66
+ }
67
+ return piece(owner);
68
+ }
69
+ return whole(node);
70
+ };
71
+ return { text, script, begin, whole, functionPiece, piece };
72
+ }
73
+ /**
74
+ * The surface hash of one file (DESIGN §6.2.1, ADR 0003). Per observable declaration, the text
75
+ * that states its type: the signature when types are written, the whole declaration (body or
76
+ * initializer) when a type is inferred. A declaration is observable when it is exported, or when
77
+ * the text of an observable declaration names it. Over-reporting a change is allowed; missing
78
+ * one is not, so anything unrecognised is hashed whole, and JavaScript files (types come from
79
+ * inference and JSDoc) are hashed whole.
80
+ */
81
+ export function surfaceOf(ts, sf, declarations) {
82
+ const { text, begin, piece } = createPiece(ts, sf);
83
+ const lines = new Set();
84
+ const meta = new Map(declarations.declarations.map((declaration) => [declaration.key, declaration]));
85
+ // Which declarations exist and whether they are exported; their types are the `src` lines below.
86
+ for (const declaration of declarations.declarations) {
87
+ lines.add(`decl\t${declaration.key}\t${declaration.kind}\t${declaration.exported ? 1 : 0}`);
88
+ }
89
+ // Roots: a member is covered by the declaration that contains it (class, object literal).
90
+ const roots = new Map();
91
+ for (const [node, key] of declarations.keyOf) {
92
+ let covered = false;
93
+ for (let parent = node.parent; parent !== undefined; parent = parent.parent) {
94
+ if (declarations.keyOf.has(parent)) {
95
+ covered = true;
96
+ break;
97
+ }
98
+ }
99
+ if (covered)
100
+ continue;
101
+ roots.set(key, [...(roots.get(key) ?? []), node]);
102
+ }
103
+ const names = new Set();
104
+ const observable = new Set();
105
+ const observe = (key, nodes) => {
106
+ observable.add(key);
107
+ const joined = nodes.map(piece).join('\n');
108
+ lines.add(`src\t${key}\t${shortHash(joined, 16)}`);
109
+ for (const match of joined.matchAll(IDENTIFIER))
110
+ names.add(match[0]);
111
+ };
112
+ for (const [key, nodes] of roots)
113
+ if (meta.get(key)?.exported === true)
114
+ observe(key, nodes);
115
+ for (let grew = true; grew;) {
116
+ grew = false;
117
+ for (const [key, nodes] of roots) {
118
+ const simple = meta.get(key)?.simple;
119
+ if (observable.has(key) || simple === undefined || !names.has(simple))
120
+ continue;
121
+ observe(key, nodes);
122
+ grew = true;
123
+ }
124
+ }
125
+ for (const statement of sf.statements) {
126
+ if (ts.isExportDeclaration(statement) ||
127
+ ts.isExportAssignment(statement) ||
128
+ (ts.isImportEqualsDeclaration(statement) &&
129
+ (ts.getModifiers(statement) ?? []).some((m) => m.kind === ts.SyntaxKind.ExportKeyword)) ||
130
+ (ts.isModuleDeclaration(statement) && !ts.isIdentifier(statement.name))) {
131
+ lines.add(`stmt\t${shortHash(text.slice(begin(statement), statement.end), 16)}`);
132
+ continue;
133
+ }
134
+ // What an import means can change an inferred type that names it.
135
+ const bound = [];
136
+ if (ts.isImportDeclaration(statement)) {
137
+ const clause = statement.importClause;
138
+ if (clause?.name !== undefined)
139
+ bound.push(clause.name.text);
140
+ const bindings = clause?.namedBindings;
141
+ if (bindings !== undefined && ts.isNamespaceImport(bindings))
142
+ bound.push(bindings.name.text);
143
+ if (bindings !== undefined && ts.isNamedImports(bindings)) {
144
+ for (const element of bindings.elements)
145
+ bound.push(element.name.text);
146
+ }
147
+ }
148
+ else if (ts.isImportEqualsDeclaration(statement)) {
149
+ bound.push(statement.name.text);
150
+ }
151
+ if (bound.some((name) => names.has(name))) {
152
+ lines.add(`imp\t${shortHash(text.slice(begin(statement), statement.end), 16)}`);
153
+ }
154
+ }
155
+ return { hash: shortHash([...lines].sort().join('\n'), 32), observableKeys: observable };
156
+ }
157
+ function normalizeTokens(ts, snippet, preserveJsDoc) {
158
+ if (snippet === '')
159
+ return '';
160
+ const scanner = ts.createScanner(ts.ScriptTarget.Latest, false, ts.LanguageVariant.Standard, snippet);
161
+ const parts = [];
162
+ let prevToken;
163
+ const REGEX_PRECEDERS = new Set([
164
+ ts.SyntaxKind.EqualsToken,
165
+ ts.SyntaxKind.OpenParenToken,
166
+ ts.SyntaxKind.OpenBracketToken,
167
+ ts.SyntaxKind.OpenBraceToken,
168
+ ts.SyntaxKind.CommaToken,
169
+ ts.SyntaxKind.ColonToken,
170
+ ts.SyntaxKind.SemicolonToken,
171
+ ts.SyntaxKind.ExclamationToken,
172
+ ts.SyntaxKind.AmpersandToken,
173
+ ts.SyntaxKind.BarToken,
174
+ ts.SyntaxKind.QuestionToken,
175
+ ts.SyntaxKind.EqualsGreaterThanToken,
176
+ ts.SyntaxKind.ReturnKeyword,
177
+ ts.SyntaxKind.ThrowKeyword,
178
+ ts.SyntaxKind.CaseKeyword,
179
+ ts.SyntaxKind.YieldKeyword,
180
+ ts.SyntaxKind.AwaitKeyword,
181
+ ts.SyntaxKind.TypeOfKeyword,
182
+ ts.SyntaxKind.VoidKeyword,
183
+ ts.SyntaxKind.DeleteKeyword,
184
+ ts.SyntaxKind.InKeyword,
185
+ ts.SyntaxKind.InstanceOfKeyword,
186
+ ts.SyntaxKind.NewKeyword,
187
+ ts.SyntaxKind.ElseKeyword,
188
+ ]);
189
+ const ASI_KEYWORDS = new Set([
190
+ ts.SyntaxKind.ReturnKeyword,
191
+ ts.SyntaxKind.BreakKeyword,
192
+ ts.SyntaxKind.ContinueKeyword,
193
+ ts.SyntaxKind.ThrowKeyword,
194
+ ts.SyntaxKind.YieldKeyword,
195
+ ]);
196
+ let token = scanner.scan();
197
+ while (token !== ts.SyntaxKind.EndOfFileToken) {
198
+ if (token === ts.SyntaxKind.WhitespaceTrivia ||
199
+ token === ts.SyntaxKind.NewLineTrivia ||
200
+ token === ts.SyntaxKind.SingleLineCommentTrivia ||
201
+ token === ts.SyntaxKind.ShebangTrivia ||
202
+ token === ts.SyntaxKind.ConflictMarkerTrivia) {
203
+ token = scanner.scan();
204
+ continue;
205
+ }
206
+ if (token === ts.SyntaxKind.MultiLineCommentTrivia) {
207
+ if (preserveJsDoc) {
208
+ const comment = scanner.getTokenText();
209
+ if (comment.startsWith('/**') && comment !== '/**/') {
210
+ parts.push(`jsdoc:${comment.replace(/\s+/g, ' ').trim()}`);
211
+ }
212
+ }
213
+ token = scanner.scan();
214
+ continue;
215
+ }
216
+ if ((token === ts.SyntaxKind.SlashToken || token === ts.SyntaxKind.SlashEqualsToken) &&
217
+ (prevToken === undefined || REGEX_PRECEDERS.has(prevToken))) {
218
+ token = scanner.reScanSlashToken();
219
+ }
220
+ const asiBreak = scanner.hasPrecedingLineBreak() &&
221
+ ((prevToken !== undefined && ASI_KEYWORDS.has(prevToken)) ||
222
+ token === ts.SyntaxKind.PlusPlusToken ||
223
+ token === ts.SyntaxKind.MinusMinusToken);
224
+ if (asiBreak)
225
+ parts.push('\n');
226
+ parts.push(`${token}:${scanner.getTokenText()}`);
227
+ prevToken = token;
228
+ token = scanner.scan();
229
+ }
230
+ return parts.join('\0');
231
+ }
232
+ export function declarationSurfaces(ts, sf, declarations) {
233
+ const { text, script, begin, whole, functionPiece, piece } = createPiece(ts, sf);
234
+ const normalize = (snippet) => normalizeTokens(ts, snippet, script);
235
+ const metaByKey = new Map(declarations.declarations.map((d) => [d.key, d]));
236
+ const nodesByKey = new Map();
237
+ for (const [node, key] of declarations.keyOf) {
238
+ let sameKeyAncestor = false;
239
+ for (let parent = node.parent; parent !== undefined; parent = parent.parent) {
240
+ if (declarations.keyOf.get(parent) === key) {
241
+ sameKeyAncestor = true;
242
+ break;
243
+ }
244
+ }
245
+ if (sameKeyAncestor)
246
+ continue;
247
+ const list = nodesByKey.get(key) ?? [];
248
+ list.push(node);
249
+ nodesByKey.set(key, list);
250
+ }
251
+ const containerHeaderAndUnindexed = (node, forSurface) => {
252
+ const partOf = (child) => (forSurface ? piece(child) : whole(child));
253
+ if (ts.isClassLike(node)) {
254
+ const unindexed = node.members.filter((m) => !declarations.keyOf.has(m)).map(partOf);
255
+ return [text.slice(begin(node), node.members.pos), ...unindexed].join('\n');
256
+ }
257
+ if (ts.isInterfaceDeclaration(node) || ts.isEnumDeclaration(node)) {
258
+ const unindexed = node.members.filter((m) => !declarations.keyOf.has(m)).map(partOf);
259
+ return [text.slice(begin(node), node.members.pos), ...unindexed].join('\n');
260
+ }
261
+ if (ts.isModuleDeclaration(node)) {
262
+ const header = text.slice(begin(node), node.name.getEnd());
263
+ if (node.body !== undefined && ts.isModuleBlock(node.body)) {
264
+ const unindexed = node.body.statements
265
+ .filter((st) => !declarations.keyOf.has(st))
266
+ .map(partOf);
267
+ return [header, ...unindexed].join('\n');
268
+ }
269
+ return header;
270
+ }
271
+ if (ts.isVariableDeclaration(node) ||
272
+ ts.isPropertyAssignment(node) ||
273
+ ts.isBinaryExpression(node)) {
274
+ const prefix = ts.isVariableDeclaration(node)
275
+ ? `${ts.getCombinedNodeFlags(node) & (ts.NodeFlags.Const | ts.NodeFlags.Let)}:`
276
+ : '';
277
+ const rawInit = ts.isBinaryExpression(node) ? node.right : node.initializer;
278
+ const init = rawInit && unwrapExpr(ts, rawInit);
279
+ if (ts.isVariableDeclaration(node) && !script && node.type !== undefined && forSurface) {
280
+ return `${prefix}${text.slice(begin(node), node.type.end)}`;
281
+ }
282
+ if (init !== undefined && (ts.isArrowFunction(init) || ts.isFunctionExpression(init))) {
283
+ return forSurface
284
+ ? `${prefix}${functionPiece(init, begin(node))}`
285
+ : `${prefix}${whole(node)}`;
286
+ }
287
+ if (init !== undefined && ts.isObjectLiteralExpression(init)) {
288
+ const hasIndexedMembers = init.properties.some((p) => declarations.keyOf.has(p));
289
+ if (hasIndexedMembers) {
290
+ const unindexed = init.properties.filter((p) => !declarations.keyOf.has(p)).map(partOf);
291
+ return [`${prefix}${text.slice(begin(node), init.getStart(sf))}`, ...unindexed].join('\n');
292
+ }
293
+ }
294
+ if (init !== undefined && ts.isClassExpression(init)) {
295
+ const unindexed = init.members.filter((m) => !declarations.keyOf.has(m)).map(partOf);
296
+ return [`${prefix}${text.slice(begin(node), init.members.pos)}`, ...unindexed].join('\n');
297
+ }
298
+ }
299
+ return undefined;
300
+ };
301
+ const surfaceSnippet = (node) => containerHeaderAndUnindexed(node, true) ?? piece(node);
302
+ const bodySnippet = (node) => containerHeaderAndUnindexed(node, false) ?? whole(node);
303
+ const result = new Map();
304
+ for (const [key, nodes] of nodesByKey) {
305
+ const meta = metaByKey.get(key);
306
+ if (meta === undefined)
307
+ continue;
308
+ const sorted = [...nodes].sort((a, b) => a.pos - b.pos);
309
+ const surfaceText = sorted.map((n) => normalize(surfaceSnippet(n))).join('\n');
310
+ const bodyText = sorted.map((n) => normalize(bodySnippet(n))).join('\n');
311
+ result.set(key, {
312
+ key,
313
+ kind: meta.kind,
314
+ exported: meta.exported,
315
+ surfaceHash: shortHash(`${meta.kind}\0${meta.exported ? 1 : 0}\0${surfaceText}`, 32),
316
+ bodyHash: shortHash(`${meta.kind}\0${bodyText}`, 32),
317
+ });
318
+ }
319
+ const moduleParts = [];
320
+ for (const statement of sf.statements) {
321
+ if (declarations.keyOf.has(statement))
322
+ continue;
323
+ if (ts.isVariableStatement(statement) &&
324
+ statement.declarationList.declarations.length > 0 &&
325
+ statement.declarationList.declarations.every((decl) => declarations.keyOf.has(decl))) {
326
+ continue;
327
+ }
328
+ moduleParts.push(normalize(whole(statement)));
329
+ }
330
+ return {
331
+ declarations: result,
332
+ moduleHash: shortHash(moduleParts.join('\n'), 32),
333
+ fileTokenHash: shortHash(normalize(text), 32),
334
+ };
335
+ }
@@ -0,0 +1,37 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ export function readBuildHistory(cacheDir) {
5
+ try {
6
+ const value = JSON.parse(readFileSync(join(cacheDir, 'runs.json'), 'utf8'));
7
+ if (!Array.isArray(value))
8
+ return [];
9
+ return value.filter((entry) => {
10
+ if (typeof entry !== 'object' || entry === null || Array.isArray(entry))
11
+ return false;
12
+ return ('durationMs' in entry &&
13
+ typeof entry.durationMs === 'number' &&
14
+ Number.isFinite(entry.durationMs) &&
15
+ entry.durationMs >= 0 &&
16
+ (!('reason' in entry) || typeof entry.reason === 'string'));
17
+ });
18
+ }
19
+ catch {
20
+ return [];
21
+ }
22
+ }
23
+ /** Called only by the lock holder after a successful publish. */
24
+ export function recordBuildHistory(cacheDir, entry) {
25
+ const path = join(cacheDir, 'runs.json');
26
+ const temp = join(cacheDir, `.runs-${randomUUID()}.json`);
27
+ try {
28
+ writeFileSync(temp, `${JSON.stringify([...readBuildHistory(cacheDir), entry].slice(-20))}\n`, {
29
+ mode: 0o600,
30
+ flag: 'wx',
31
+ });
32
+ renameSync(temp, path);
33
+ }
34
+ finally {
35
+ rmSync(temp, { force: true });
36
+ }
37
+ }
@@ -0,0 +1,76 @@
1
+ import { tableCounts } from '../../storage/records.js';
2
+ /** Phase 4 (DESIGN §6.2.1): structural invariants of a staged index. Empty means it may publish. */
3
+ export function verifyIndex(db, expected) {
4
+ const problems = [];
5
+ const check = (label, sql) => {
6
+ const n = Number(db.prepare(sql).get()?.n ?? 0);
7
+ if (n > 0)
8
+ problems.push(`${label}: ${n}`);
9
+ };
10
+ // Unique keys: `symbols.key` is UNIQUE and `declarations.id` its primary key; this checks the link.
11
+ check('declarations without a symbol key', 'SELECT COUNT(*) AS n FROM declarations d LEFT JOIN symbols s ON s.id = d.id WHERE s.id IS NULL');
12
+ check('declarations whose key names another file', `SELECT COUNT(*) AS n FROM declarations d JOIN symbols s ON s.id = d.id
13
+ WHERE substr(s.key, 1, length(d.file) + 1) != d.file || '#'`);
14
+ check('declaration spans outside their file', `SELECT COUNT(*) AS n FROM declarations d LEFT JOIN file_index f ON f.file = d.file
15
+ WHERE f.file IS NULL OR d.start_line < 1 OR d.end_line < d.start_line OR d.end_line > f.lines`);
16
+ check('edges whose source is not a declaration', 'SELECT COUNT(*) AS n FROM edges e LEFT JOIN declarations d ON d.id = e.source WHERE d.id IS NULL');
17
+ check('edges whose target is not a declaration', 'SELECT COUNT(*) AS n FROM edges e LEFT JOIN declarations d ON d.id = e.target WHERE d.id IS NULL');
18
+ check('edge sites outside their file', `SELECT COUNT(*) AS n FROM edges e JOIN declarations d ON d.id = e.source
19
+ JOIN file_index f ON f.file = d.file, json_each(e.lines) j
20
+ WHERE j.value < 1 OR j.value > f.lines`);
21
+ check('exports of a declaration that does not exist', `SELECT COUNT(*) AS n FROM exports x LEFT JOIN symbols s ON s.key = x.target
22
+ LEFT JOIN declarations d ON d.id = s.id WHERE d.id IS NULL`);
23
+ check('indexable files neither indexed nor listed with a reason', `SELECT COUNT(*) AS n FROM files f LEFT JOIN file_index i ON i.file = f.path
24
+ WHERE f.status = 'indexable' AND i.file IS NULL`);
25
+ check('scanned files that are not indexable and have no reason', "SELECT COUNT(*) AS n FROM files WHERE status != 'indexable' AND reason IS NULL");
26
+ check('index records for files that are not indexable', `SELECT COUNT(*) AS n FROM file_index i LEFT JOIN files f ON f.path = i.file
27
+ WHERE f.path IS NULL
28
+ OR (f.status = 'indexable' AND i.extraction = 'lexical')
29
+ OR (f.status != 'indexable' AND (
30
+ i.extraction != 'lexical'
31
+ OR f.hash IS NULL
32
+ OR f.kind IN ('json', 'other')
33
+ OR f.reason NOT IN ('no-tsconfig', 'outside-index-scope', 'excluded')
34
+ ))`);
35
+ check('indexed files without their module declaration', `SELECT COUNT(*) AS n FROM file_index i
36
+ LEFT JOIN symbols s ON s.key = i.file || '#<module>' LEFT JOIN declarations d ON d.id = s.id
37
+ WHERE i.extraction NOT IN ('not-in-program', 'lexical') AND d.id IS NULL`);
38
+ check('lexical records contain compiler-only facts', `SELECT
39
+ (SELECT COUNT(*) FROM declarations d JOIN file_index i ON i.file = d.file WHERE i.extraction = 'lexical')
40
+ + (SELECT COUNT(*) FROM edges e JOIN declarations d ON d.id = e.source JOIN file_index i ON i.file = d.file WHERE i.extraction = 'lexical')
41
+ + (SELECT COUNT(*) FROM gap_sites g JOIN file_index i ON i.file = g.file WHERE i.extraction = 'lexical')
42
+ + (SELECT COUNT(*) FROM external_imports x JOIN file_index i ON i.file = x.file WHERE i.extraction = 'lexical')
43
+ + (SELECT COUNT(*) FROM exports x JOIN file_index i ON i.file = x.file WHERE i.extraction = 'lexical')
44
+ + (SELECT COUNT(*) FROM markers m JOIN file_index i ON i.file = m.file WHERE i.extraction = 'lexical')
45
+ + (SELECT COUNT(*) FROM unresolved u JOIN file_index i ON i.file = u.file WHERE i.extraction = 'lexical' AND u.reason != 'unresolved-name-match')
46
+ + (SELECT COUNT(*) FROM name_tokens t JOIN file_index i ON i.file = t.file WHERE i.extraction = 'lexical' AND t.kind != 'str')
47
+ AS n`);
48
+ check('static import marker without matching import edge', `SELECT COUNT(*) AS n FROM markers m
49
+ WHERE m.kind LIKE 'static-import:%'
50
+ AND NOT EXISTS (
51
+ SELECT 1 FROM edges e
52
+ JOIN symbols s ON s.id = e.source JOIN symbols t ON t.id = e.target,
53
+ json_each(e.lines) site
54
+ WHERE e.kind = 'IMPORTS' AND s.key = m.file || '#<module>'
55
+ AND t.key = substr(m.kind, length('static-import:') + 1) || '#<module>'
56
+ AND site.value = m.line
57
+ )`);
58
+ check('records of files that are not indexed', `SELECT (SELECT COUNT(*) FROM unresolved u LEFT JOIN file_index i ON i.file = u.file WHERE i.file IS NULL)
59
+ + (SELECT COUNT(*) FROM gap_sites g LEFT JOIN file_index i ON i.file = g.file WHERE i.file IS NULL)
60
+ + (SELECT COUNT(*) FROM name_tokens t LEFT JOIN file_index i ON i.file = t.file WHERE i.file IS NULL)
61
+ + (SELECT COUNT(*) FROM markers m LEFT JOIN file_index i ON i.file = m.file WHERE i.file IS NULL)
62
+ AS n`);
63
+ check('search rows without a matching declaration', 'SELECT COUNT(*) AS n FROM declarations_fts f LEFT JOIN declarations d ON d.id = f.rowid WHERE d.id IS NULL');
64
+ check('search rows on non-ok files or module declarations', `SELECT COUNT(*) AS n FROM declarations_fts f
65
+ JOIN declarations d ON d.id = f.rowid JOIN file_index i ON i.file = d.file
66
+ WHERE i.extraction != 'ok' OR d.kind = 'module'`);
67
+ check('ok declarations missing search rows', `SELECT COUNT(*) AS n FROM declarations d JOIN file_index i ON i.file = d.file
68
+ LEFT JOIN declarations_fts f ON f.rowid = d.id
69
+ WHERE i.extraction = 'ok' AND d.kind != 'module' AND f.rowid IS NULL`);
70
+ const actual = tableCounts(db);
71
+ for (const [table, n] of Object.entries(expected)) {
72
+ if (actual[table] !== n)
73
+ problems.push(`${table}: produced ${n}, read back ${actual[table]}`);
74
+ }
75
+ return problems;
76
+ }