@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,262 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync, realpathSync } from "node:fs";
3
+ import { resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ const STATES = new Set(["VERIFIED", "PARTIAL", "NOT_RUN", "BLOCKED", "FAILED", "FIX_REQUIRED", "UNVERIFIED"]);
7
+ const RESERVED_EXECUTION_IDS = new Set(["typecheck", "lint", "tests", "runtime", "security"]);
8
+ const COUNT_KEYS = ["passed", "failed", "skipped"];
9
+
10
+ /**
11
+ * Strict "executable evidence present" shape. Legacy command reports without exit code or cwd
12
+ * are accepted as input but cannot verify an executed command via this predicate.
13
+ */
14
+ export function hasEvidence(gate) {
15
+ const e = gate?.evidence;
16
+ if (!e || typeof e !== "object") return false;
17
+ if (e.type === "command") {
18
+ return typeof e.command === "string" && !!e.command.trim() &&
19
+ typeof e.cwd === "string" && !!e.cwd.trim() &&
20
+ typeof e.result === "string" && !!e.result.trim() &&
21
+ e.exitCode === 0 &&
22
+ e.timedOut !== true && e.signal == null;
23
+ }
24
+ if (e.type === "source") return typeof e.path === "string" && !!e.path.trim() && typeof e.observation === "string" && !!e.observation.trim();
25
+ if (e.type === "ci-run") return typeof e.url === "string" && /^https:\/\//.test(e.url) && e.conclusion === "success";
26
+
27
+ return false;
28
+ }
29
+
30
+ const GIT_OID = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
31
+
32
+ function ciRunEvidenceValid(evidence, reviewedCommit) {
33
+ if (evidence.type !== "ci-run" || evidence.conclusion !== "success") return false;
34
+ if (typeof evidence.url !== "string" || typeof evidence.headSha !== "string" || !GIT_OID.test(evidence.headSha)) return false;
35
+ let parsed;
36
+ try {
37
+ parsed = new URL(evidence.url);
38
+ } catch {
39
+ return false;
40
+ }
41
+ if (parsed.protocol !== "https:" || !parsed.hostname) return false;
42
+
43
+ if (parsed.username || parsed.password) return false;
44
+
45
+ return typeof reviewedCommit === "string" && GIT_OID.test(reviewedCommit) && reviewedCommit === evidence.headSha;
46
+ }
47
+
48
+ function validateTestCounts(evidence) {
49
+ const counts = evidence.testCounts;
50
+ if (counts === undefined) return null;
51
+ if (counts === null || typeof counts !== "object" || Array.isArray(counts)) {
52
+ throw new Error("testCounts must be an object when supplied");
53
+ }
54
+ const read = {};
55
+ for (const key of COUNT_KEYS) {
56
+ const value = counts[key];
57
+ if (value === undefined) { read[key] = 0; continue; }
58
+ if (!Number.isSafeInteger(value) || value < 0) {
59
+ throw new Error(`testCounts.${key} must be a nonnegative integer`);
60
+ }
61
+ read[key] = value;
62
+
63
+ }
64
+
65
+ return read;
66
+ }
67
+
68
+ /**
69
+ * A deterministic evidence summary, not a substitute for human release approval.
70
+ * In particular, CI coverage is only VERIFIED with a successful cited CI run matching the
71
+ * reviewed commit; supplied evidence is never authenticated.
72
+ */
73
+ export function assessReview({ scope = "code-review", gates, requiredGates = [], reviewedCommit } = {}) {
74
+ if (!["code-review", "release"].includes(scope)) throw new Error("Invalid scope");
75
+ if (gates !== undefined && !Array.isArray(gates)) throw new Error("gates must be an array");
76
+ if (!Array.isArray(requiredGates)) throw new Error("requiredGates must be an array");
77
+ if (reviewedCommit !== undefined && !GIT_OID.test(reviewedCommit)) {
78
+ throw new Error("reviewedCommit must be a 40- or 64-hex Git object id");
79
+ }
80
+
81
+ const declared = new Map();
82
+ for (const required of requiredGates) {
83
+ if (!required || typeof required !== "object" || Array.isArray(required)) {
84
+ throw new Error("Each requiredGate must be an object with an id");
85
+ }
86
+ validateId(required, "requiredGate");
87
+ validateFlag(required, "required", "requiredGate");
88
+ validateFlag(required, "critical", "requiredGate");
89
+ if (required.required === false) {
90
+ throw new Error("A requiredGate entry cannot declare itself not required");
91
+ }
92
+ const id = required.id.trim();
93
+ if (declared.has(id)) throw new Error(`Duplicate required gate id: ${id}`);
94
+ declared.set(id, required.critical === true);
95
+ }
96
+
97
+ const normalized = (gates ?? []).map(gate => {
98
+ if (!gate || typeof gate !== "object" || Array.isArray(gate)) {
99
+ throw new Error("Each gate must be an object with an id and a status");
100
+ }
101
+ validateId(gate, "gate");
102
+ validateFlag(gate, "required", "gate");
103
+ validateFlag(gate, "critical", "gate");
104
+ if (gate.status === undefined || !STATES.has(gate.status)) {
105
+ throw new Error("Each gate needs an id and a supported status");
106
+
107
+ }
108
+
109
+ return { ...gate, id: gate.id.trim() };
110
+ });
111
+
112
+ const seen = new Set();
113
+ for (const gate of normalized) {
114
+ if (seen.has(gate.id)) throw new Error(`Duplicate gate id: ${gate.id}`);
115
+ seen.add(gate.id);
116
+ }
117
+
118
+ // Missing declared gates are synthesized as required NOT_RUN; declared critical beats supplied false.
119
+ for (const [id, critical] of declared) {
120
+ if (seen.has(id)) {
121
+ const supplied = normalized.find(g => g.id === id);
122
+ supplied.required = true;
123
+ if (critical) supplied.critical = true;
124
+ continue;
125
+ }
126
+ normalized.push({ id, status: "NOT_RUN", required: true, critical });
127
+ seen.add(id);
128
+ }
129
+
130
+ if (normalized.length === 0) {
131
+ return { verdict: "NOT_ASSESSED", gates: [], reasons: ["No gates were supplied"] };
132
+ }
133
+
134
+ const results = normalized.map(gate => {
135
+ const counts = validateTestCounts(gate.evidence ?? {});
136
+ const normalizedGate = { ...gate };
137
+
138
+ if (gate.evidence?.type === "command" &&
139
+ ((Number.isInteger(gate.evidence.exitCode) && gate.evidence.exitCode !== 0) || (counts !== null && counts.failed > 0))) {
140
+ normalizedGate.status = "FAILED";
141
+ } else if (gate.status === "VERIFIED") {
142
+ normalizedGate.status = normalLife(gate, counts, reviewedCommit);
143
+ }
144
+
145
+ normalizedGate.required = normalizedGate.required !== false || normalizedGate.critical === true;
146
+ normalizedGate.critical = normalizedGate.critical === true;
147
+
148
+ normalizedGate.evidenceValid = normalizedGate.status === "VERIFIED";
149
+
150
+ return normalizedGate;
151
+ });
152
+
153
+ const required = results.filter(g => g.required);
154
+ if (!required.length) {
155
+ return { verdict: "NOT_ASSESSED", gates: results, reasons: ["No required gates were supplied"] };
156
+ }
157
+
158
+ const failing = required.filter(g => ["FAILED", "FIX_REQUIRED"].includes(g.status));
159
+ const missing = required.filter(g => g.status !== "VERIFIED");
160
+ const criticalUnknown = missing.filter(g => g.critical);
161
+
162
+ let verdict;
163
+ if (failing.length || criticalUnknown.length) verdict = "NO_GO";
164
+ else if (missing.length) verdict = scope === "release" ? "NO_GO" : "CONDITIONAL_GO";
165
+ else verdict = scope === "release" ? "RELEASE_CANDIDATE" : "READY_FOR_REVIEW";
166
+
167
+ return {
168
+ verdict,
169
+ gates: results,
170
+ reasons: missing.map(g => g.id + ": " + g.status),
171
+ disclaimer: "Reported evidence is supplied by the caller and not independently authenticated. No merge or deployment approval is granted.",
172
+ };
173
+ }
174
+
175
+ function validateId(gate, kind) {
176
+ if (typeof gate.id !== "string" || !gate.id.trim()) {
177
+ throw new Error(`Each ${kind} needs a nonempty id`);
178
+ }
179
+ }
180
+
181
+ function validateFlag(gate, key, kind) {
182
+ if (gate[key] !== undefined && typeof gate[key] !== "boolean") {
183
+ throw new Error(`${kind} ${key} flag must be boolean`);
184
+ }
185
+ }
186
+
187
+ function normalLife(gate, counts, reviewedCommit) {
188
+ const evidence = gate.evidence;
189
+ if (!evidence || typeof evidence !== "object") return "UNVERIFIED";
190
+ const id = gate.id;
191
+
192
+ if (id === "ci-parity") {
193
+ return ciRunEvidenceValid(evidence, reviewedCommit) ? "VERIFIED" : "UNVERIFIED";
194
+ }
195
+ if (RESERVED_EXECUTION_IDS.has(id)) {
196
+
197
+ if (evidence.type !== "command") return "UNVERIFIED";
198
+
199
+ return commandVerified(gate, counts);
200
+ }
201
+ if (evidence.type === "source") return hasEvidence(gate) ? "VERIFIED" : "UNVERIFIED";
202
+
203
+ if (evidence.type === "command") return commandVerified(gate, counts);
204
+
205
+ return "UNVERIFIED";
206
+ }
207
+
208
+ /**
209
+ * A command claim verifies only under the strict shape: integer exit code 0, nonempty
210
+ * command/cwd/result, no timeout or signal. Legacy shapes stay readable but UNVERIFIED;
211
+ * contradictory outcomes (failing exit or failed tests) demote to FAILED even when the
212
+ * caller said VERIFIED.
213
+ */
214
+ function commandVerified(gate, counts) {
215
+ const evidence = gate.evidence;
216
+ if (Number.isInteger(evidence.exitCode) && evidence.exitCode !== 0) return "FAILED";
217
+ if (counts !== null && counts.failed > 0) return "FAILED";
218
+ if (!hasEvidence(gate)) return "UNVERIFIED";
219
+ if (counts !== null && counts.skipped > 0) return "PARTIAL";
220
+ if (counts !== null && (counts.passed === 0 || COUNT_KEYS.some(key => evidence.testCounts[key] === undefined))) return "UNVERIFIED";
221
+ if (gate.id === "tests" && counts === null) return "UNVERIFIED";
222
+
223
+ return "VERIFIED";
224
+ }
225
+
226
+ function main(args) {
227
+ if (args.length !== 2 || args[0] !== "--report") {
228
+ throw new Error("Usage: node review-verdict.js --report assessment.json");
229
+ }
230
+ const payload = JSON.parse(readFileSync(resolve(args[1]), "utf8"));
231
+ const result = assessReview({
232
+ scope: payload.scope,
233
+ reviewedCommit: payload.reviewedCommit,
234
+ gates: payload.gates,
235
+ requiredGates: payload.requiredGates,
236
+ });
237
+ process.stdout.write(JSON.stringify(result, null, 2) + "\n");
238
+
239
+ if (result.verdict === "NO_GO" || result.verdict === "CONDITIONAL_GO") process.exitCode = 1;
240
+ else if (result.verdict === "NOT_ASSESSED") process.exitCode = 2;
241
+ }
242
+
243
+ // Compare REAL paths so npm .bin symlinks still execute the CLI; unresolvable argv means NOT main.
244
+ function isMainModule() {
245
+ try {
246
+
247
+ if (!process.argv[1]) return false;
248
+
249
+ return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
250
+ } catch {
251
+ return false;
252
+ }
253
+ }
254
+
255
+ if (isMainModule()) {
256
+ try {
257
+ main(process.argv.slice(2));
258
+ } catch (error) {
259
+ process.stderr.write("KSD review NOT ASSESSED: " + error.message + "\n");
260
+ process.exitCode = 2;
261
+ }
262
+ }
@@ -0,0 +1,2 @@
1
+ // Compatibility entrypoint; implementation is strict TypeScript compiled to ESM.
2
+ export { SDLC_PHASES, KSD_MODES, buildSdlcPolicy } from "./dist/sdlc.js";
package/dist/index.js ADDED
@@ -0,0 +1,20 @@
1
+ export { PROVIDERS, catalog, lookupSkill, rootsFromEnv, skillIdsOf } from './workflow/catalog.js';
2
+ export { classifyTask } from './workflow/classify.js';
3
+ export { MAX_SKILL_BYTES, loadPackSkill, loadSkill, prepareWorkflow, readSkill, sha256Hex, } from './workflow/loader.js';
4
+ export { SKILL_PACKS, auditSkillContent, defaultSkillsDir, discoverSkillsForPlatform, listSkillPacks, orchestratorSkillPath, packForSkillId, packSkillPath, parseSkillFrontmatter, } from './workflow/packs.js';
5
+ export { buildAgySkillsConfig, detectAgyPaths, discoverAgySkills } from './adapters/agy/skills.js';
6
+ export { detectOmpEnvironment, discoverOmpSkills } from './adapters/omp/skills.js';
7
+ export { defaultRegistryPath, parseRegistry, readRegistry, validateRegistryConsistency, writeRegistry, } from './workflow/registry.js';
8
+ export { checkUpstreamUpdates, defaultUpdateStateDir, publishStagedUpdate, rollbackSkillUpdate, stageSkillUpdate, } from './workflow/updates.js';
9
+ export { PRECEDENCE_HEADER, renderWorkflow, stageProtocolLine } from './workflow/render.js';
10
+ export { hasRequirementComplianceSignal, routeTask } from './workflow/router.js';
11
+ export { checkSources, defaultLockPath, formatReports, parseLock, readLock, reportStatus, writeLock, } from './workflow/sources.js';
12
+ export { CATALOG_SKILL_NAMES, COMPLIANCE_DIMENSIONS, ORCHESTRATOR_SKILL_ID, PROVIDER_IDS, RISKS, SKILL_IDS, SKILL_PACK_IDS, STAGES, TASK_TYPES, WorkflowError, } from './workflow/types.js';
13
+ export { DEFAULT_RISK_ZONES, defaultConfig, parseProjectConfig, resolveRiskZones, } from './core/kernel/config.js';
14
+ export { computeRepoId, detectProjectLayout, discoverTsconfigs, findGitRoot, initProject, resolveCacheDir, } from './core/workspace/init.js';
15
+ export { loadWorkspace, resolveWorkspaceCache } from './core/engine/workspace.js';
16
+ export { AUDIT_FILE, MAX_AUDIT_BYTES, MAX_QUERY_CHARS, MAX_ROTATIONS, MAX_TASK_CHARS, auditFieldsForSearch, clearAuditState, consumeAuditWarning, parseSince, recordAudit, renderAuditSummary, sanitizeAuditText, summarizeAudit, } from './core/audit/index.js';
17
+ export { runChanges } from './core/changes/changes.js';
18
+ export { CHANGES_BUDGET, renderChanges, renderChangesOutcome } from './core/changes/render.js';
19
+ export { DEFAULT_SEARCH_LIMIT, MAX_SEARCH_LIMIT, MAX_SEARCH_QUERY_CHARS, MIN_SEARCH_LIMIT, buildFtsQuery, querySearch, quoteFtsLiteral, runSearch, validateSearchInput, } from './core/search/lexical.js';
20
+ export { SEARCH_BUDGET, renderSearch, renderSearchOutcome } from './core/search/render.js';
@@ -0,0 +1,245 @@
1
+ export const RECORD_TABLES = [
2
+ 'file_index',
3
+ 'declarations',
4
+ 'edges',
5
+ 'unresolved',
6
+ 'gap_sites',
7
+ 'name_tokens',
8
+ 'external_imports',
9
+ 'exports',
10
+ 'markers',
11
+ 'declarations_fts',
12
+ ];
13
+ export function emptyCounts() {
14
+ return {
15
+ files: 0,
16
+ file_index: 0,
17
+ declarations: 0,
18
+ edges: 0,
19
+ unresolved: 0,
20
+ gap_sites: 0,
21
+ name_tokens: 0,
22
+ external_imports: 0,
23
+ exports: 0,
24
+ markers: 0,
25
+ declarations_fts: 0,
26
+ };
27
+ }
28
+ /** Deletes every record these files contributed; returns rows deleted per table. */
29
+ export function deleteFileRecords(db, files) {
30
+ const deleted = emptyCounts();
31
+ // Edges and FTS search rows first: they are keyed via `declarations.id` for `file`.
32
+ const edges = db.prepare('DELETE FROM edges WHERE source IN (SELECT id FROM declarations WHERE file = ?)');
33
+ const searchFts = db.prepare('DELETE FROM declarations_fts WHERE rowid IN (SELECT id FROM declarations WHERE file = ?)');
34
+ const byFile = [
35
+ 'file_index',
36
+ 'declarations',
37
+ 'unresolved',
38
+ 'gap_sites',
39
+ 'name_tokens',
40
+ 'external_imports',
41
+ 'exports',
42
+ 'markers',
43
+ ].map((table) => [table, db.prepare(`DELETE FROM ${table} WHERE file = ?`)]);
44
+ for (const file of files) {
45
+ deleted.edges += Number(edges.run(file).changes);
46
+ deleted.declarations_fts += Number(searchFts.run(file).changes);
47
+ for (const [table, statement] of byFile)
48
+ deleted[table] += Number(statement.run(file).changes);
49
+ }
50
+ return deleted;
51
+ }
52
+ /** Symbols no declaration carries any more (their keys were deleted or renamed). */
53
+ export function deleteOrphanSymbols(db) {
54
+ db.exec('DELETE FROM symbols WHERE id NOT IN (SELECT id FROM declarations)');
55
+ }
56
+ export function recordWriter(db) {
57
+ const symbol = db.prepare('INSERT INTO symbols (key) VALUES (?) ON CONFLICT (key) DO UPDATE SET key = excluded.key RETURNING id');
58
+ const ids = new Map();
59
+ const idOf = (key) => {
60
+ let id = ids.get(key);
61
+ if (id === undefined) {
62
+ id = Number(symbol.get(key)?.id);
63
+ ids.set(key, id);
64
+ }
65
+ return id;
66
+ };
67
+ const fileIndex = db.prepare(`INSERT INTO file_index (file, extraction, lines, surface, global, indexed_uses, local_uses,
68
+ external, external_unresolved, unresolved_other, outside_scope)
69
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
70
+ const declaration = db.prepare(`INSERT INTO declarations (id, file, name, simple, kind, exported, start_line, end_line,
71
+ other_spans, sig_hash) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
72
+ const edge = db.prepare('INSERT INTO edges (source, target, kind, strength, lines) VALUES (?, ?, ?, ?, ?)');
73
+ const unresolved = db.prepare('INSERT INTO unresolved (file, line, name, reason, source) VALUES (?, ?, ?, ?, ?)');
74
+ const gap = db.prepare('INSERT INTO gap_sites (file, line, code, detail, source) VALUES (?, ?, ?, ?, ?)');
75
+ const token = db.prepare('INSERT INTO name_tokens (file, name, kind, lines) VALUES (?, ?, ?, ?)');
76
+ const external = db.prepare('INSERT INTO external_imports (file, specifier, line) VALUES (?, ?, ?)');
77
+ const exported = db.prepare('INSERT INTO exports (file, name, target) VALUES (?, ?, ?)');
78
+ const marker = db.prepare('INSERT INTO markers (file, line, kind) VALUES (?, ?, ?)');
79
+ const search = db.prepare(`INSERT INTO declarations_fts (rowid, stable_key, name_tokens, owner_tokens, kind, signature,
80
+ doc, path_tokens) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`);
81
+ const inserted = emptyCounts();
82
+ return {
83
+ inserted,
84
+ write(rows) {
85
+ const i = rows.index;
86
+ fileIndex.run(i.file, i.extraction, i.lines, i.surface, i.global ? 1 : 0, i.counts.indexed, i.counts.local, i.counts.external, i.counts.externalUnresolved, i.counts.unresolvedOther, i.counts.outsideScope);
87
+ inserted.file_index++;
88
+ for (const d of rows.declarations) {
89
+ declaration.run(idOf(d.key), d.file, d.name, d.simple, d.kind, d.exported ? 1 : 0, d.startLine, d.endLine, JSON.stringify(d.otherSpans), d.sigHash);
90
+ }
91
+ inserted.declarations += rows.declarations.length;
92
+ for (const e of rows.edges) {
93
+ edge.run(idOf(e.source), idOf(e.target), e.kind, e.strength, JSON.stringify(e.lines));
94
+ }
95
+ inserted.edges += rows.edges.length;
96
+ for (const u of rows.unresolved)
97
+ unresolved.run(u.file, u.line, u.name, u.reason, u.source);
98
+ inserted.unresolved += rows.unresolved.length;
99
+ for (const g of rows.gaps)
100
+ gap.run(g.file, g.line, g.code, g.detail, g.source);
101
+ inserted.gap_sites += rows.gaps.length;
102
+ for (const t of rows.tokens)
103
+ token.run(t.file, t.name, t.kind, JSON.stringify(t.lines));
104
+ inserted.name_tokens += rows.tokens.length;
105
+ for (const x of rows.externalImports)
106
+ external.run(x.file, x.specifier, x.line);
107
+ inserted.external_imports += rows.externalImports.length;
108
+ for (const x of rows.exports)
109
+ exported.run(x.file, x.name, x.target);
110
+ inserted.exports += rows.exports.length;
111
+ for (const m of rows.markers)
112
+ marker.run(m.file, m.line, m.kind);
113
+ inserted.markers += rows.markers.length;
114
+ for (const s of rows.search) {
115
+ search.run(idOf(s.key), s.key, s.nameTokens, s.ownerTokens, s.kind, s.signature, s.doc, s.pathTokens);
116
+ }
117
+ inserted.declarations_fts += rows.search.length;
118
+ },
119
+ };
120
+ }
121
+ export function tableCounts(db) {
122
+ const counts = emptyCounts();
123
+ for (const table of ['files', ...RECORD_TABLES]) {
124
+ counts[table] = Number(db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get()?.n ?? 0);
125
+ }
126
+ return counts;
127
+ }
128
+ function filesFrom(db, sql, params, repeat = 1) {
129
+ const found = new Set();
130
+ const statement = db.prepare(sql);
131
+ for (const param of params) {
132
+ for (const row of statement.all(...Array(repeat).fill(param)))
133
+ found.add(String(row.file));
134
+ }
135
+ return found;
136
+ }
137
+ /** Files with any edge into a declaration of one of `files` (importers, callers, users). */
138
+ export function filesWithEdgesInto(db, files) {
139
+ return filesFrom(db, `SELECT DISTINCT s.file AS file FROM declarations t JOIN edges e ON e.target = t.id
140
+ JOIN declarations s ON s.id = e.source WHERE t.file = ?`, files);
141
+ }
142
+ /** Files importing a module whose path starts with one of `prefixes` (resolution may change). */
143
+ export function filesImportingPrefix(db, prefixes) {
144
+ return filesFrom(db, `SELECT DISTINCT s.file AS file FROM edges e JOIN declarations t ON t.id = e.target
145
+ JOIN declarations s ON s.id = e.source
146
+ WHERE e.kind = 'IMPORTS' AND substr(t.file, 1, length(?)) = ?`, prefixes, 2);
147
+ }
148
+ /**
149
+ * Files whose records depend on which declarations carry these simple names: an unresolved name
150
+ * match, a string token, or an edge to a declaration with that name.
151
+ */
152
+ export function filesReferencingNames(db, names) {
153
+ const list = [...names];
154
+ const found = filesFrom(db, "SELECT DISTINCT file FROM unresolved WHERE reason = 'unresolved-name-match' AND name = ?", list);
155
+ for (const file of filesFrom(db, 'SELECT DISTINCT file FROM name_tokens WHERE name = ?', list)) {
156
+ found.add(file);
157
+ }
158
+ const viaEdges = filesFrom(db, `SELECT DISTINCT s.file AS file FROM declarations d JOIN edges e ON e.target = d.id
159
+ JOIN declarations s ON s.id = e.source WHERE d.simple = ?`, list);
160
+ for (const file of viaEdges)
161
+ found.add(file);
162
+ return found;
163
+ }
164
+ export function filesWithUnresolvedImports(db) {
165
+ const rows = db
166
+ .prepare("SELECT DISTINCT file FROM unresolved WHERE reason = 'unresolved-import'")
167
+ .all();
168
+ return new Set(rows.map((row) => String(row.file)));
169
+ }
170
+ export function readFileIndex(db) {
171
+ const result = new Map();
172
+ for (const row of db.prepare('SELECT file, surface, global FROM file_index').all()) {
173
+ result.set(String(row.file), {
174
+ surface: String(row.surface),
175
+ global: Number(row.global) === 1,
176
+ });
177
+ }
178
+ return result;
179
+ }
180
+ /** Declaration keys of these files, each with its simple name. */
181
+ export function declarationNamesOf(db, files) {
182
+ const result = new Map();
183
+ const statement = db.prepare('SELECT s.key AS key, d.simple AS simple FROM declarations d JOIN symbols s ON s.id = d.id WHERE d.file = ?');
184
+ for (const file of files) {
185
+ for (const row of statement.all(file))
186
+ result.set(String(row.key), String(row.simple));
187
+ }
188
+ return result;
189
+ }
190
+ /** How many declarations carry each simple name. */
191
+ export function simpleNameCounts(db) {
192
+ const result = new Map();
193
+ for (const row of db
194
+ .prepare('SELECT simple, COUNT(*) AS n FROM declarations GROUP BY simple')
195
+ .all()) {
196
+ result.set(String(row.simple), Number(row.n));
197
+ }
198
+ return result;
199
+ }
200
+ const CANONICAL = {
201
+ // mtime is left out: the same tree indexed at another time is the same index.
202
+ files: 'SELECT path, size, hash, kind, package, tsconfig, status, reason FROM files ORDER BY path',
203
+ // The per-file use counters are statistics, not graph content: see `counterLines`.
204
+ file_index: 'SELECT file, extraction, lines, surface, global FROM file_index ORDER BY file',
205
+ // Symbol ids are storage details; keys are what the index states.
206
+ declarations: `SELECT s.key, d.file, d.name, d.simple, d.kind, d.exported, d.start_line, d.end_line,
207
+ d.other_spans, d.sig_hash FROM declarations d JOIN symbols s ON s.id = d.id ORDER BY s.key`,
208
+ // Aliased: a row object keeps one value per column name, so two `key` columns would be one.
209
+ edges: `SELECT s.key AS source, t.key AS target, e.kind, e.strength, e.lines FROM edges e
210
+ JOIN symbols s ON s.id = e.source JOIN symbols t ON t.id = e.target ORDER BY 1, 2, 3`,
211
+ unresolved: 'SELECT * FROM unresolved ORDER BY file, line, name, reason, source',
212
+ gap_sites: 'SELECT * FROM gap_sites ORDER BY file, line, code, detail, source',
213
+ name_tokens: 'SELECT * FROM name_tokens ORDER BY file, name, kind',
214
+ external_imports: 'SELECT * FROM external_imports ORDER BY file, line, specifier',
215
+ exports: 'SELECT * FROM exports ORDER BY file, name, target',
216
+ markers: 'SELECT * FROM markers ORDER BY file, line, kind',
217
+ declarations_fts: `SELECT stable_key, name_tokens, owner_tokens, kind, signature, doc, path_tokens
218
+ FROM declarations_fts ORDER BY stable_key`,
219
+ };
220
+ /** The use counters of every file, as sorted text lines (statistics only; never graph content). */
221
+ export function counterLines(db) {
222
+ return db
223
+ .prepare(`SELECT file, indexed_uses, local_uses, external, external_unresolved, unresolved_other,
224
+ outside_scope FROM file_index ORDER BY file`)
225
+ .all()
226
+ .map((row) => `counters\t${Object.values(row).map(String).join('\t')}`);
227
+ }
228
+ /**
229
+ * Every graph record as sorted text lines, `table\tcolumns…`; equal indexes give equal lines.
230
+ * The use counters are left out unless asked for: TypeScript infers lazily, so they depend on
231
+ * checking order, and nothing in a query or verdict may depend on them.
232
+ */
233
+ export function canonicalLines(db, options = {}) {
234
+ const lines = [];
235
+ for (const [table, sql] of Object.entries(CANONICAL)) {
236
+ for (const row of db.prepare(sql).all()) {
237
+ lines.push(`${table}\t${Object.values(row)
238
+ .map((value) => String(value))
239
+ .join('\t')}`);
240
+ }
241
+ }
242
+ if (options.counters === true)
243
+ lines.push(...counterLines(db));
244
+ return lines;
245
+ }