@dimassetoid/septum-mcp 0.0.0-stage → 0.3.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/LICENSE +21 -0
  2. package/README.md +142 -2
  3. package/bin/septum.ts +4 -0
  4. package/package.json +70 -4
  5. package/scripts/postinstall.ts +25 -0
  6. package/src/cli/commands/check.ts +133 -0
  7. package/src/cli/commands/hook.ts +205 -0
  8. package/src/cli/commands/init.ts +570 -0
  9. package/src/cli/commands/serve.ts +5 -0
  10. package/src/cli/commands/sync.ts +39 -0
  11. package/src/cli/hook-payload.ts +43 -0
  12. package/src/cli/index.ts +124 -0
  13. package/src/cli/scaffold/harness-config.ts +661 -0
  14. package/src/cli/templates/hooks.ts +110 -0
  15. package/src/cli/templates/rules.ts +35 -0
  16. package/src/cli/templates/skill.ts +55 -0
  17. package/src/cli/ui/prompts.ts +122 -0
  18. package/src/core/boundary/evaluator.ts +426 -0
  19. package/src/core/boundary/staged-auditor.ts +120 -0
  20. package/src/core/config/domain-ownership.ts +45 -0
  21. package/src/core/config/loader.ts +174 -0
  22. package/src/core/config/schema.ts +59 -0
  23. package/src/core/database/client.ts +60 -0
  24. package/src/core/database/repositories/dependency.repository.ts +733 -0
  25. package/src/core/database/repositories/domain.repository.ts +373 -0
  26. package/src/core/database/repositories/file.repository.ts +117 -0
  27. package/src/core/database/repositories/meta.repository.ts +33 -0
  28. package/src/core/database/repositories/symbol.repository.ts +647 -0
  29. package/src/core/database/repository.ts +358 -0
  30. package/src/core/database/schema.ts +123 -0
  31. package/src/core/discovery/navigation.ts +105 -0
  32. package/src/core/discovery/topology-detector.ts +863 -0
  33. package/src/core/ingestion/hasher.ts +5 -0
  34. package/src/core/ingestion/pipeline.ts +590 -0
  35. package/src/core/parser/behavioral-analyzer.ts +123 -0
  36. package/src/core/parser/boundary-tracker.ts +458 -0
  37. package/src/core/parser/extractors/base.ts +71 -0
  38. package/src/core/parser/extractors/blade.ts +159 -0
  39. package/src/core/parser/extractors/csharp.ts +248 -0
  40. package/src/core/parser/extractors/django-semantic.ts +655 -0
  41. package/src/core/parser/extractors/elysia-semantic.ts +517 -0
  42. package/src/core/parser/extractors/express-semantic.ts +429 -0
  43. package/src/core/parser/extractors/fastapi-semantic.ts +702 -0
  44. package/src/core/parser/extractors/fastify-semantic.ts +759 -0
  45. package/src/core/parser/extractors/flask-semantic.ts +482 -0
  46. package/src/core/parser/extractors/frontend.ts +149 -0
  47. package/src/core/parser/extractors/go-semantic.ts +670 -0
  48. package/src/core/parser/extractors/go.ts +491 -0
  49. package/src/core/parser/extractors/hono-semantic.ts +546 -0
  50. package/src/core/parser/extractors/java.ts +227 -0
  51. package/src/core/parser/extractors/laravel-semantic.ts +1150 -0
  52. package/src/core/parser/extractors/mcp-cli-semantic.ts +367 -0
  53. package/src/core/parser/extractors/nestjs-semantic.ts +527 -0
  54. package/src/core/parser/extractors/php.ts +585 -0
  55. package/src/core/parser/extractors/python.ts +503 -0
  56. package/src/core/parser/extractors/registry.ts +99 -0
  57. package/src/core/parser/extractors/ruby.ts +237 -0
  58. package/src/core/parser/extractors/rust.ts +304 -0
  59. package/src/core/parser/extractors/semantic-extractor.interface.ts +24 -0
  60. package/src/core/parser/extractors/symfony-semantic.ts +321 -0
  61. package/src/core/parser/extractors/typescript.ts +839 -0
  62. package/src/core/parser/implementation-fingerprint.ts +97 -0
  63. package/src/core/parser/language-capabilities.ts +87 -0
  64. package/src/core/parser/schema/providers/laravel-migration-provider.ts +239 -0
  65. package/src/core/parser/schema/schema-provider-registry.ts +41 -0
  66. package/src/core/parser/schema/schema-provider.interface.ts +34 -0
  67. package/src/core/parser/semantic-revision.ts +3 -0
  68. package/src/core/parser/static-string.ts +51 -0
  69. package/src/core/parser/tree-sitter.ts +63 -0
  70. package/src/core/parser/wasm-assets.ts +25 -0
  71. package/src/core/parser/wasm-loader.ts +274 -0
  72. package/src/core/resolver/call-graph-tracer.ts +1033 -0
  73. package/src/core/resolver/import-resolver.ts +365 -0
  74. package/src/core/resolver/interpretation-inputs.ts +7 -0
  75. package/src/core/resolver/languages/go.ts +103 -0
  76. package/src/core/resolver/languages/managed.ts +200 -0
  77. package/src/core/resolver/languages/python.ts +115 -0
  78. package/src/core/resolver/languages/ruby.ts +40 -0
  79. package/src/core/resolver/languages/rust.ts +127 -0
  80. package/src/core/resolver/languages/shared.ts +71 -0
  81. package/src/core/resolver/module-resolver.ts +486 -0
  82. package/src/core/resolver/path-resolver.ts +200 -0
  83. package/src/core/resolver/slice-catalog.ts +79 -0
  84. package/src/core/resolver/slice-format.ts +9 -0
  85. package/src/core/resolver/symbol-impact.ts +381 -0
  86. package/src/core/resolver/symbol-locator.ts +276 -0
  87. package/src/core/resolver/symbol-reference.ts +53 -0
  88. package/src/core/resolver/vertical-slice-tracer.ts +344 -0
  89. package/src/core/resources/ignore.ts +144 -0
  90. package/src/core/resources/limits.ts +14 -0
  91. package/src/core/resources/source-files.ts +185 -0
  92. package/src/core/resources/source-inventory.ts +55 -0
  93. package/src/core/resources/work-queue.ts +74 -0
  94. package/src/core/retrieval/context-page.ts +109 -0
  95. package/src/core/retrieval/context.ts +320 -0
  96. package/src/core/retrieval/resolution-warnings.ts +21 -0
  97. package/src/core/retrieval/symbol-evidence.ts +97 -0
  98. package/src/core/retrieval/typescript-references.ts +262 -0
  99. package/src/core/telemetry/telemetry.ts +142 -0
  100. package/src/index.ts +18 -0
  101. package/src/mcp/schemas.ts +746 -0
  102. package/src/mcp/server.ts +600 -0
  103. package/src/mcp/tools/boundary.ts +17 -0
  104. package/src/mcp/tools/check-boundary.ts +382 -0
  105. package/src/mcp/tools/get-domain-catalog.ts +39 -0
  106. package/src/mcp/tools/get-symbol-impact.ts +104 -0
  107. package/src/mcp/tools/get-symbol.ts +399 -0
  108. package/src/mcp/tools/locate-symbol.ts +236 -0
  109. package/src/mcp/tools/map.ts +26 -0
  110. package/src/mcp/tools/register-domain.ts +113 -0
  111. package/src/mcp/tools/slice.ts +16 -0
  112. package/src/mcp/tools/symbol.ts +95 -0
  113. package/src/mcp/tools/trace-vertical-slice.ts +106 -0
  114. package/src/mcp/workspace-manager.ts +170 -0
  115. package/src/mcp/workspace-watcher.ts +202 -0
  116. package/src/types/index.ts +438 -0
  117. package/src/types/wasm.d.ts +4 -0
  118. package/src/utils/version-check.ts +209 -0
  119. package/src/version.ts +1 -0
@@ -0,0 +1,373 @@
1
+ import { symbolReference } from "../../resolver/symbol-reference.ts";
2
+ import type { Database } from "bun:sqlite";
3
+ import type {
4
+ DomainCatalogResponse,
5
+ DomainConfig,
6
+ DomainRecord,
7
+ FileRecord,
8
+ SymbolKind,
9
+ SymbolRecord,
10
+ } from "../../../types/index.ts";
11
+ import { DependencyRepository } from "./dependency.repository.ts";
12
+ import { domainNameKey, domainRootIdentity, DomainRootConflictError } from "../../config/domain-ownership.ts";
13
+
14
+ const CONTAINER_KINDS = new Set<SymbolKind>([
15
+ "class",
16
+ "interface",
17
+ "trait",
18
+ "struct",
19
+ "enum",
20
+ ]);
21
+
22
+ export class DomainRepository {
23
+ constructor(private db: Database) {}
24
+
25
+ public upsertDomain(name: string, config: DomainConfig, workspaceRoot?: string): number {
26
+ return this.db.transaction(() => {
27
+ const normalizedName = name.trim();
28
+ const root = workspaceRoot ?? this.db.query<{ value: string }, []>("SELECT value FROM repo_meta WHERE key='workspace_root'").get()?.value ?? process.cwd();
29
+ const claims = Object.fromEntries(this.getAllDomains()
30
+ .filter(domain => domainNameKey(domain.name) !== domainNameKey(normalizedName))
31
+ .map(domain => [domain.name, { root: domain.root_path }]));
32
+ // Validate the proposed root inside the same immediate transaction as the write.
33
+ // Unrelated legacy conflicts can be repaired one domain at a time.
34
+ const proposed = domainRootIdentity(config.root, root);
35
+ for (const [owner, claim] of Object.entries(claims)) {
36
+ if (domainRootIdentity(claim.root, root) === proposed) throw new DomainRootConflictError(owner, normalizedName, proposed);
37
+ }
38
+ let existing = this.getDomainByName(normalizedName);
39
+
40
+ // MCP-13: If duplicates exist with different casing, consolidate into canonical primary row
41
+ if (existing) {
42
+ const allMatching = this.db
43
+ .query<DomainRecord, [string]>("SELECT * FROM domains WHERE LOWER(name) = LOWER(?) ORDER BY id ASC")
44
+ .all(normalizedName);
45
+ if (allMatching.length > 1) {
46
+ const primary = allMatching[0];
47
+ const fields = [
48
+ ["allowed_dependencies", "allowed_deps_json"],
49
+ ["forbidden_dependencies", "forbidden_deps_json"],
50
+ ["archetypes", "archetypes_json"],
51
+ ] as const;
52
+ for (const [field, column] of fields) {
53
+ if (config[field] !== undefined) continue;
54
+ const values = allMatching.map(row => {
55
+ const parsed = JSON.parse(row[column]);
56
+ return JSON.stringify(Array.isArray(parsed) ? [...parsed].sort() : Object.entries(parsed).sort());
57
+ });
58
+ if (new Set(values).size > 1) {
59
+ throw new Error(`Conflicting legacy domain '${normalizedName}': provide '${field}' explicitly before consolidating case variants.`);
60
+ }
61
+ }
62
+ for (let i = 1; i < allMatching.length; i++) {
63
+ const duplicate = allMatching[i];
64
+ this.db.query("UPDATE files SET domain_id = ? WHERE domain_id = ?").run(primary.id, duplicate.id);
65
+ this.db.query("UPDATE vertical_slices SET domain_id = ? WHERE domain_id = ?").run(primary.id, duplicate.id);
66
+ this.db.query("DELETE FROM domains WHERE id = ?").run(duplicate.id);
67
+ }
68
+ existing = primary;
69
+ }
70
+ }
71
+
72
+ const targetName = existing ? existing.name : normalizedName;
73
+
74
+ // MCP-12: Distinguish absent (undefined -> preserve) from explicit empty ([] -> clear)
75
+ let allowed: string[];
76
+ if (config.allowed_dependencies !== undefined) {
77
+ allowed = config.allowed_dependencies;
78
+ } else if (existing?.allowed_deps_json) {
79
+ try {
80
+ allowed = JSON.parse(existing.allowed_deps_json);
81
+ } catch {
82
+ allowed = [];
83
+ }
84
+ } else {
85
+ allowed = [];
86
+ }
87
+
88
+ let forbidden: string[];
89
+ if (config.forbidden_dependencies !== undefined) {
90
+ forbidden = config.forbidden_dependencies;
91
+ } else if (existing?.forbidden_deps_json) {
92
+ try {
93
+ forbidden = JSON.parse(existing.forbidden_deps_json);
94
+ } catch {
95
+ forbidden = [];
96
+ }
97
+ } else {
98
+ forbidden = [];
99
+ }
100
+
101
+ let archetypes: Record<string, string>;
102
+ if (config.archetypes !== undefined) {
103
+ archetypes = config.archetypes;
104
+ } else if (existing?.archetypes_json) {
105
+ try {
106
+ archetypes = JSON.parse(existing.archetypes_json);
107
+ } catch {
108
+ archetypes = {};
109
+ }
110
+ } else {
111
+ archetypes = {};
112
+ }
113
+
114
+ const allowedJson = JSON.stringify(allowed);
115
+ const forbiddenJson = JSON.stringify(forbidden);
116
+ const archetypesJson = JSON.stringify(archetypes);
117
+
118
+ const query = `
119
+ INSERT INTO domains (name, root_path, allowed_deps_json, forbidden_deps_json, archetypes_json)
120
+ VALUES (?, ?, ?, ?, ?)
121
+ ON CONFLICT(name) DO UPDATE SET
122
+ root_path = excluded.root_path,
123
+ allowed_deps_json = excluded.allowed_deps_json,
124
+ forbidden_deps_json = excluded.forbidden_deps_json,
125
+ archetypes_json = excluded.archetypes_json,
126
+ updated_at = CURRENT_TIMESTAMP
127
+ `;
128
+ this.db.query(query).run(targetName, config.root, allowedJson, forbiddenJson, archetypesJson);
129
+
130
+ const record = this.getDomainByName(targetName);
131
+ return record?.id ?? 0;
132
+ }).immediate();
133
+ }
134
+
135
+ public getDomainByName(name: string): DomainRecord | null {
136
+ return this.db
137
+ .query<DomainRecord, [string]>("SELECT * FROM domains WHERE LOWER(name) = LOWER(?)")
138
+ .get(name.trim());
139
+ }
140
+
141
+ public getAllDomains(): DomainRecord[] {
142
+ return this.db.query<DomainRecord, []>("SELECT * FROM domains ORDER BY name ASC").all();
143
+ }
144
+
145
+ /** Delete domains not present in activeNames (case-insensitive) and return removed counts. */
146
+ public pruneDomainsNotIn(activeNames: string[]): { prunedDomains: number; removedFiles: number } {
147
+ const activeSet = new Set(activeNames.map((n) => n.trim().toLowerCase()));
148
+ return this.db.transaction(() => {
149
+ const existing = this.getAllDomains();
150
+ const stale = existing.filter((d) => !activeSet.has(d.name.trim().toLowerCase()));
151
+ if (stale.length === 0) return { prunedDomains: 0, removedFiles: 0 };
152
+
153
+ let removedFiles = 0;
154
+ const countFilesStmt = this.db.query<{ cnt: number }, [number]>(
155
+ "SELECT COUNT(*) AS cnt FROM files WHERE domain_id = ?"
156
+ );
157
+ const deleteDomainStmt = this.db.query("DELETE FROM domains WHERE id = ?");
158
+ for (const domain of stale) {
159
+ removedFiles += countFilesStmt.get(domain.id)?.cnt ?? 0;
160
+ deleteDomainStmt.run(domain.id);
161
+ }
162
+ return { prunedDomains: stale.length, removedFiles };
163
+ }).immediate();
164
+ }
165
+
166
+ public getDomainCatalog(
167
+ domainName: string,
168
+ archetypeFilter?: string,
169
+ options?: { detailLevel?: "compact" | "full"; fileFilter?: string; workspaceRoot?: string }
170
+ ): DomainCatalogResponse | null {
171
+ const domain = this.getDomainByName(domainName);
172
+ if (!domain) return null;
173
+
174
+ const detailLevel = options?.detailLevel ?? "compact";
175
+ const fileFilter = options?.fileFilter?.trim();
176
+
177
+ const allowedDeps: string[] = JSON.parse(domain.allowed_deps_json || "[]");
178
+ const forbiddenDeps: string[] = JSON.parse(domain.forbidden_deps_json || "[]");
179
+
180
+ let filesQuery = "SELECT * FROM files WHERE domain_id = ?";
181
+ const params: [number, string?] = [domain.id];
182
+
183
+ if (archetypeFilter) {
184
+ filesQuery += " AND archetype = ?";
185
+ params.push(archetypeFilter);
186
+ }
187
+ filesQuery += " ORDER BY path ASC";
188
+
189
+ const allDomainFiles = this.db.query<FileRecord, any>(filesQuery).all(...params);
190
+ const totalFiles = allDomainFiles.length;
191
+
192
+ const files = fileFilter
193
+ ? allDomainFiles.filter((f) =>
194
+ f.path.replace(/\\/g, "/").toLowerCase().includes(fileFilter.replace(/\\/g, "/").toLowerCase())
195
+ )
196
+ : allDomainFiles;
197
+
198
+ const catalogFiles: DomainCatalogResponse["files"] = [];
199
+
200
+ // Batch retrieve symbols for all files in one query to eliminate N+1 roundtrips
201
+ const symbolsByFileId = new Map<number, SymbolRecord[]>();
202
+ for (const f of files) {
203
+ symbolsByFileId.set(f.id, []);
204
+ }
205
+
206
+ if (files.length > 0) {
207
+ const allDomainSymbols = this.db
208
+ .query<SymbolRecord, [number]>(
209
+ `SELECT s.* FROM symbols s
210
+ JOIN files f ON s.file_id = f.id
211
+ WHERE f.domain_id = ?
212
+ ORDER BY s.file_id ASC, s.line_start ASC`
213
+ )
214
+ .all(domain.id);
215
+
216
+ for (const sym of allDomainSymbols) {
217
+ const list = symbolsByFileId.get(sym.file_id);
218
+ if (list) {
219
+ list.push(sym);
220
+ }
221
+ }
222
+ }
223
+
224
+ // Batch compute file connections for the domain (zero N+1)
225
+ const depRepo = new DependencyRepository(this.db);
226
+ const connectionsByPath = depRepo.getDomainFileConnections(domain.id,options?.workspaceRoot);
227
+
228
+ for (const file of files) {
229
+ const symbols = symbolsByFileId.get(file.id) ?? [];
230
+
231
+ const symbolMap = new Map<
232
+ string,
233
+ {
234
+ name: string;
235
+ kind: SymbolKind;
236
+ lineSpan: string;
237
+ properties: string[];
238
+ methods: string[];
239
+ signatures: string[];
240
+ }
241
+ >();
242
+
243
+ for (const sym of symbols) {
244
+ const lineSpan = `${sym.line_start}-${sym.line_end}`;
245
+ if (CONTAINER_KINDS.has(sym.kind)) {
246
+ if (!symbolMap.has(sym.name)) {
247
+ symbolMap.set(sym.name, {
248
+ name: sym.name,
249
+ kind: sym.kind,
250
+ lineSpan,
251
+ properties: [],
252
+ methods: [],
253
+ signatures: [sym.signature],
254
+ });
255
+ }
256
+ } else if (sym.kind === "method" || sym.kind === "property") {
257
+ let targetContainer:
258
+ | {
259
+ name: string;
260
+ kind: SymbolKind;
261
+ lineSpan: string;
262
+ properties: string[];
263
+ methods: string[];
264
+ signatures: string[];
265
+ }
266
+ | undefined;
267
+
268
+ if (sym.name.includes("::")) {
269
+ const containerName = sym.name.split("::")[0];
270
+ const candidate = symbolMap.get(containerName);
271
+ if (candidate && CONTAINER_KINDS.has(candidate.kind)) {
272
+ targetContainer = candidate;
273
+ }
274
+ }
275
+
276
+ if (targetContainer) {
277
+ if (sym.kind === "method") {
278
+ targetContainer.methods.push(sym.signature);
279
+ } else {
280
+ targetContainer.properties.push(sym.signature);
281
+ }
282
+ } else {
283
+ symbolMap.set(sym.name, {
284
+ name: sym.name,
285
+ kind: sym.kind,
286
+ lineSpan,
287
+ properties: sym.kind === "property" ? [sym.signature] : [],
288
+ methods: [],
289
+ signatures: [sym.signature],
290
+ });
291
+ }
292
+ } else {
293
+ if (
294
+ detailLevel === "compact" &&
295
+ (sym.kind === "variable" || sym.kind === "constant") &&
296
+ sym.visibility === "private"
297
+ ) {
298
+ continue;
299
+ }
300
+ symbolMap.set(sym.name, {
301
+ name: sym.name,
302
+ kind: sym.kind,
303
+ lineSpan,
304
+ properties: [],
305
+ methods: [],
306
+ signatures: [sym.signature],
307
+ });
308
+ }
309
+ }
310
+
311
+ const rawConn = connectionsByPath.get(file.path);
312
+ const fileConnections = {
313
+ imports_from: rawConn?.imports_from ?? [],
314
+ imported_by_count: rawConn?.imported_by_count ?? 0,
315
+ };
316
+
317
+ const allMappedSymbols = Array.from(symbolMap.values());
318
+ const isCompact = detailLevel === "compact";
319
+ const MAX_COMPACT_SYMBOLS = 25;
320
+ const symbolsToDisplay = isCompact && allMappedSymbols.length > MAX_COMPACT_SYMBOLS
321
+ ? allMappedSymbols.slice(0, MAX_COMPACT_SYMBOLS)
322
+ : allMappedSymbols;
323
+ const symbolsOmitted = isCompact && allMappedSymbols.length > MAX_COMPACT_SYMBOLS
324
+ ? allMappedSymbols.length - MAX_COMPACT_SYMBOLS
325
+ : undefined;
326
+
327
+ catalogFiles.push({
328
+ ...(detailLevel === "full" ? { declarations: symbols.map(sym => symbolReference({ ...sym, file_path: file.path, indexed_content_hash: file.content_hash })) } : {}),
329
+ path: file.path,
330
+ archetype: file.archetype,
331
+ line_count: file.line_count,
332
+ connections: fileConnections,
333
+ ...(symbolsOmitted !== undefined ? { symbols_omitted: symbolsOmitted } : {}),
334
+ symbols: symbolsToDisplay.map((s) => {
335
+ if (detailLevel === "compact") {
336
+ return {
337
+ name: s.name,
338
+ kind: s.kind,
339
+ line_span: s.lineSpan,
340
+ methods_count: s.methods.length > 0 ? s.methods.length : undefined,
341
+ properties_count: s.properties.length > 0 ? s.properties.length : undefined,
342
+ };
343
+ }
344
+ return {
345
+ name: s.name,
346
+ kind: s.kind,
347
+ line_span: s.lineSpan,
348
+ methods_count: s.methods.length > 0 ? s.methods.length : undefined,
349
+ properties_count: s.properties.length > 0 ? s.properties.length : undefined,
350
+ properties: s.properties.length > 0 ? s.properties : undefined,
351
+ methods: s.methods.length > 0 ? s.methods : undefined,
352
+ signatures: s.signatures.length > 0 ? s.signatures : undefined,
353
+ };
354
+ }),
355
+ });
356
+ }
357
+
358
+ return {
359
+ domain: domain.name,
360
+ root: domain.root_path,
361
+ detail_level: detailLevel,
362
+ total_files: totalFiles,
363
+ showing_files: catalogFiles.length,
364
+ allowed_dependencies: allowedDeps,
365
+ forbidden_dependencies: forbiddenDeps,
366
+ files: catalogFiles,
367
+ agent_hint:
368
+ detailLevel === "compact"
369
+ ? "Compact declaration catalog. Use septum_symbol({ action: 'context', query: symbol, file_path: '<path>' }) for declaration details. septum_map provides navigation rather than member inventories."
370
+ : undefined,
371
+ };
372
+ }
373
+ }
@@ -0,0 +1,117 @@
1
+ import type { Database } from "bun:sqlite";
2
+ import type { ArchetypeKind, DomainRecord, FileRecord } from "../../../types/index.ts";
3
+
4
+ export class FileRepository {
5
+ constructor(private db: Database) {}
6
+
7
+ public getFileByPath(path: string): FileRecord | null {
8
+ return this.db
9
+ .query<FileRecord, [string]>("SELECT * FROM files WHERE path = ?")
10
+ .get(path);
11
+ }
12
+
13
+ public getFileById(id: number): FileRecord | null {
14
+ return this.db
15
+ .query<FileRecord, [number]>("SELECT * FROM files WHERE id = ?")
16
+ .get(id);
17
+ }
18
+
19
+ public getFilesByDomain(domainId: number): FileRecord[] {
20
+ return this.db
21
+ .query<FileRecord, [number]>("SELECT * FROM files WHERE domain_id = ? ORDER BY path ASC")
22
+ .all(domainId);
23
+ }
24
+
25
+ public getAllFiles(): FileRecord[] {
26
+ return this.db
27
+ .query<FileRecord, []>("SELECT * FROM files ORDER BY path ASC")
28
+ .all();
29
+ }
30
+
31
+ public countFiles(): number {
32
+ const row = this.db
33
+ .query<{ count: number }, []>("SELECT COUNT(*) as count FROM files")
34
+ .get();
35
+ return row?.count ?? 0;
36
+ }
37
+
38
+ public upsertFile(
39
+ domainId: number,
40
+ path: string,
41
+ archetype: ArchetypeKind,
42
+ contentHash: string,
43
+ lineCount: number,
44
+ mtimeMs: number = 0,
45
+ sizeBytes: number = 0
46
+ ): number {
47
+ const row = this.db
48
+ .query<{ id: number }, [number, string, string, string, number, number, number]>(
49
+ `INSERT INTO files (domain_id, path, archetype, content_hash, line_count, mtime_ms, size_bytes)
50
+ VALUES (?, ?, ?, ?, ?, ?, ?)
51
+ ON CONFLICT(path) DO UPDATE SET
52
+ domain_id = excluded.domain_id,
53
+ archetype = excluded.archetype,
54
+ content_hash = excluded.content_hash,
55
+ line_count = excluded.line_count,
56
+ mtime_ms = excluded.mtime_ms,
57
+ size_bytes = excluded.size_bytes,
58
+ last_scanned_at = CURRENT_TIMESTAMP
59
+ RETURNING id`
60
+ )
61
+ .get(domainId, path, archetype, contentHash, lineCount, mtimeMs, sizeBytes);
62
+ return row ? Number(row.id) : 0;
63
+ }
64
+
65
+ public updateFileMetadataOnly(id: number, mtimeMs: number, sizeBytes: number): void {
66
+ this.db
67
+ .query(
68
+ `UPDATE files
69
+ SET mtime_ms = ?, size_bytes = ?, last_scanned_at = CURRENT_TIMESTAMP
70
+ WHERE id = ?`
71
+ )
72
+ .run(mtimeMs, sizeBytes, id);
73
+ }
74
+
75
+ public deleteFilesNotInPaths(domainId: number, validPaths: string[]): number {
76
+ if (validPaths.length === 0) {
77
+ const res = this.db.query("DELETE FROM files WHERE domain_id = ?").run(domainId);
78
+ return Number(res.changes);
79
+ }
80
+ const existingFiles = this.getFilesByDomain(domainId);
81
+ const validSet = new Set(validPaths);
82
+ const idsToDelete = existingFiles.filter((f) => !validSet.has(f.path)).map((f) => f.id);
83
+ if (idsToDelete.length === 0) return 0;
84
+
85
+ const chunkSize = 200;
86
+ let totalDeleted = 0;
87
+ for (let i = 0; i < idsToDelete.length; i += chunkSize) {
88
+ const chunk = idsToDelete.slice(i, i + chunkSize);
89
+ const placeholders = chunk.map(() => "?").join(",");
90
+ const res = this.db.query(`DELETE FROM files WHERE id IN (${placeholders})`).run(...chunk);
91
+ totalDeleted += Number(res.changes);
92
+ }
93
+ return totalDeleted;
94
+ }
95
+
96
+ public deleteFile(path: string): void {
97
+ this.db.query("DELETE FROM files WHERE path = ?").run(path);
98
+ }
99
+
100
+ public deleteFileByPath(path: string): void {
101
+ this.deleteFile(path);
102
+ }
103
+
104
+ public getFileWithDomain(
105
+ filePath: string
106
+ ): { file: FileRecord; domain: DomainRecord } | null {
107
+ const file = this.getFileByPath(filePath);
108
+ if (!file) return null;
109
+
110
+ const domain = this.db
111
+ .query<DomainRecord, [number]>("SELECT * FROM domains WHERE id = ?")
112
+ .get(file.domain_id);
113
+ if (!domain) return null;
114
+
115
+ return { file, domain };
116
+ }
117
+ }
@@ -0,0 +1,33 @@
1
+ import type { Database } from "bun:sqlite";
2
+
3
+ export class MetaRepository {
4
+ constructor(private db: Database) {}
5
+
6
+ public getMeta(key: string): string | null {
7
+ const row = this.db
8
+ .query<{ value: string }, [string]>("SELECT value FROM repo_meta WHERE key = ?")
9
+ .get(key);
10
+ return row ? row.value : null;
11
+ }
12
+
13
+ public setMeta(key: string, value: string): void {
14
+ this.db
15
+ .query(
16
+ `INSERT INTO repo_meta (key, value, updated_at)
17
+ VALUES (?, ?, CURRENT_TIMESTAMP)
18
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP`
19
+ )
20
+ .run(key, value);
21
+ }
22
+
23
+ public getAllMeta(): Record<string, string> {
24
+ const rows = this.db
25
+ .query<{ key: string; value: string }, []>("SELECT key, value FROM repo_meta")
26
+ .all();
27
+ const result: Record<string, string> = {};
28
+ for (const r of rows) {
29
+ result[r.key] = r.value;
30
+ }
31
+ return result;
32
+ }
33
+ }