@myrialabs/clopen 0.4.38 → 0.4.39

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 (114) hide show
  1. package/backend/auth/permissions.ts +25 -0
  2. package/backend/chat/stream-manager.ts +1 -1
  3. package/backend/database/crypto/secret-columns.ts +5 -1
  4. package/backend/database/migrations/075_create_deploy_bindings.ts +54 -0
  5. package/backend/database/migrations/076_remove_memory_code_graph.ts +229 -0
  6. package/backend/database/migrations/077_create_integration_db_links.ts +150 -0
  7. package/backend/database/migrations/index.ts +21 -0
  8. package/backend/database/queries/db-client-connection-queries.ts +19 -0
  9. package/backend/database/queries/deploy-queries.ts +124 -0
  10. package/backend/database/queries/graph-queries.ts +291 -247
  11. package/backend/database/queries/index.ts +4 -0
  12. package/backend/database/queries/integration-db-link-queries.ts +168 -0
  13. package/backend/database/queries/integration-queries.ts +34 -6
  14. package/backend/db-client/integrations/index.ts +37 -0
  15. package/backend/db-client/integrations/links.ts +533 -0
  16. package/backend/db-client/integrations/projector.test.ts +280 -0
  17. package/backend/db-client/integrations/projector.ts +256 -0
  18. package/backend/db-client/integrations/supabase-service.ts +266 -0
  19. package/backend/db-client/providers/registry.ts +27 -0
  20. package/backend/db-client/providers/supabase/adapter.ts +500 -0
  21. package/backend/db-client/providers/supabase/api-types.ts +92 -0
  22. package/backend/db-client/providers/supabase/apply-migration.ts +104 -0
  23. package/backend/db-client/providers/supabase/client.ts +259 -0
  24. package/backend/db-client/providers/supabase/features.ts +502 -0
  25. package/backend/db-client/providers/supabase/local.test.ts +78 -0
  26. package/backend/db-client/providers/supabase/local.ts +137 -0
  27. package/backend/db-client/providers/types.ts +137 -0
  28. package/backend/deployments/bindings.test.ts +43 -0
  29. package/backend/deployments/bindings.ts +216 -0
  30. package/backend/deployments/index.ts +53 -0
  31. package/backend/deployments/log-streams.ts +214 -0
  32. package/backend/deployments/prompts.ts +70 -0
  33. package/backend/deployments/providers/vercel/adapter.ts +757 -0
  34. package/backend/deployments/providers/vercel/build-logs.test.ts +80 -0
  35. package/backend/deployments/providers/vercel/build-logs.ts +211 -0
  36. package/backend/deployments/providers/vercel/client.ts +203 -0
  37. package/backend/deployments/providers/vercel/list.test.ts +624 -0
  38. package/backend/deployments/providers/vercel/normalise.test.ts +115 -0
  39. package/backend/deployments/providers/vercel/normalise.ts +113 -0
  40. package/backend/deployments/providers/vercel/types.ts +104 -0
  41. package/backend/deployments/registry.ts +27 -0
  42. package/backend/deployments/service.ts +458 -0
  43. package/backend/deployments/types.ts +278 -0
  44. package/backend/index.ts +4 -0
  45. package/backend/integrations/projections/index.ts +0 -0
  46. package/backend/integrations/projections/mcp-projector.ts +7 -3
  47. package/backend/integrations/projections/types.ts +21 -9
  48. package/backend/integrations/registry/index.ts +5 -1
  49. package/backend/integrations/registry/providers/supabase.ts +61 -0
  50. package/backend/integrations/registry/providers/vercel.ts +46 -0
  51. package/backend/mcp/internal/servers/memory-graph/description.ts +3 -3
  52. package/backend/mcp/internal/servers/memory-graph/runner.ts +4 -9
  53. package/backend/mcp/internal/servers/memory-graph/schema.ts +0 -4
  54. package/backend/memory/README.md +57 -34
  55. package/backend/memory/compose.test.ts +3 -3
  56. package/backend/memory/compose.ts +6 -9
  57. package/backend/memory/config.ts +0 -5
  58. package/backend/memory/consolidate.ts +1 -2
  59. package/backend/memory/context.test.ts +8 -54
  60. package/backend/memory/context.ts +19 -25
  61. package/backend/memory/extract/episodic.ts +10 -12
  62. package/backend/memory/extract/index.ts +23 -52
  63. package/backend/memory/extract/scheduler.ts +3 -6
  64. package/backend/memory/index.ts +6 -5
  65. package/backend/memory/invalidate.ts +36 -48
  66. package/backend/memory/layout.ts +319 -130
  67. package/backend/memory/retention.ts +12 -42
  68. package/backend/memory/retrieval.eval.test.ts +2 -2
  69. package/backend/memory/retrieval.test.ts +228 -183
  70. package/backend/memory/retrieval.ts +22 -21
  71. package/backend/memory/revise.test.ts +62 -116
  72. package/backend/memory/revise.ts +0 -1
  73. package/backend/memory/view.ts +8 -5
  74. package/backend/snapshot/helpers.ts +35 -41
  75. package/backend/snapshot/snapshot-service.ts +90 -0
  76. package/backend/snapshot/turn-changes.test.ts +163 -0
  77. package/backend/snapshot/turn-changes.ts +131 -0
  78. package/backend/ws/db-client/accounts.ts +225 -0
  79. package/backend/ws/db-client/connections.ts +34 -3
  80. package/backend/ws/db-client/context.ts +37 -0
  81. package/backend/ws/db-client/index.ts +20 -1
  82. package/backend/ws/db-client/supabase.ts +188 -0
  83. package/backend/ws/deployments/actions.ts +360 -0
  84. package/backend/ws/deployments/context.ts +43 -0
  85. package/backend/ws/deployments/crud.ts +152 -0
  86. package/backend/ws/deployments/index.ts +15 -0
  87. package/backend/ws/deployments/schemas.ts +183 -0
  88. package/backend/ws/index.ts +6 -2
  89. package/backend/ws/memory/crud.ts +4 -16
  90. package/backend/ws/snapshot/changes.ts +279 -0
  91. package/backend/ws/snapshot/index.ts +4 -3
  92. package/dist/assets/{index-CyH7fSbR.js → index-BrF6nqld.js} +1 -1
  93. package/dist/assets/{index-DSHIANSy.js → index-C8Gi-b6U.js} +1 -1
  94. package/dist/assets/main-Bd3gb79F.css +1 -0
  95. package/dist/assets/main-Bo1hD7mt.js +1191 -0
  96. package/dist/index.html +2 -2
  97. package/package.json +1 -1
  98. package/shared/constants/tool-icons.ts +9 -0
  99. package/shared/types/db-client/connection.ts +6 -0
  100. package/shared/types/db-client/index.ts +2 -0
  101. package/shared/types/db-client/integrations.ts +174 -0
  102. package/shared/types/db-client/supabase.ts +131 -0
  103. package/shared/types/deployments.ts +382 -0
  104. package/shared/types/memory.ts +34 -51
  105. package/shared/types/ui/components.ts +1 -1
  106. package/shared/utils/diff-calculator.test.ts +89 -0
  107. package/shared/utils/diff-calculator.ts +30 -65
  108. package/shared/utils/logger.ts +1 -0
  109. package/backend/memory/extract/languages.ts +0 -176
  110. package/backend/memory/extract/structural.test.ts +0 -215
  111. package/backend/memory/extract/structural.ts +0 -364
  112. package/backend/ws/snapshot/content.ts +0 -85
  113. package/dist/assets/main-D2IOjftb.css +0 -1
  114. package/dist/assets/main-DM-tHKbW.js +0 -1152
@@ -2,6 +2,11 @@
2
2
  * Diff Calculator Utility
3
3
  * Calculates git-like line-level differences between file contents
4
4
  * Accepts Buffer for binary-safe handling — converts to string internally for line diffing.
5
+ *
6
+ * "Binary-safe" means binary files are not line-counted at all. Splitting a PNG
7
+ * on newline bytes yields a line count with no meaning, and two screenshots
8
+ * once reported +159 lines into a checkpoint's total — dwarfing the source
9
+ * changes the number was there to describe.
5
10
  */
6
11
 
7
12
  export interface FileChangeStats {
@@ -10,11 +15,16 @@ export interface FileChangeStats {
10
15
  deletions: number;
11
16
  }
12
17
 
13
- export interface FileDiff {
14
- filepath: string;
15
- insertions: number;
16
- deletions: number;
17
- status: 'added' | 'modified' | 'deleted';
18
+ /**
19
+ * Whether these bytes are binary, and so cannot be counted or diffed as lines.
20
+ * A NUL byte in the first few KB is the same heuristic git uses.
21
+ */
22
+ export function isBinaryBuffer(buf: Buffer): boolean {
23
+ const limit = Math.min(buf.length, 8000);
24
+ for (let i = 0; i < limit; i++) {
25
+ if (buf[i] === 0) return true;
26
+ }
27
+ return false;
18
28
  }
19
29
 
20
30
  /**
@@ -29,31 +39,30 @@ export function calculateFileChangeStats(
29
39
  let totalDeletions = 0;
30
40
  const changedFiles = new Set<string>();
31
41
 
32
- // Check added and modified files
42
+ // Check added and modified files. A binary file still counts as changed — it
43
+ // just contributes no lines, because it has none.
33
44
  for (const [filepath, newContent] of Object.entries(currentSnapshot)) {
34
45
  const oldContent = previousSnapshot[filepath];
35
46
 
36
47
  if (!oldContent) {
37
- // File was added - count all lines as insertions
38
- const lines = countLines(newContent.toString('utf-8'));
39
- totalInsertions += lines;
40
48
  changedFiles.add(filepath);
49
+ if (isBinaryBuffer(newContent)) continue;
50
+ totalInsertions += countLines(newContent.toString('utf-8'));
41
51
  } else if (!oldContent.equals(newContent)) {
42
- // File was modified - calculate line diff
52
+ changedFiles.add(filepath);
53
+ if (isBinaryBuffer(newContent) || isBinaryBuffer(oldContent)) continue;
43
54
  const diff = calculateLineDiff(oldContent.toString('utf-8'), newContent.toString('utf-8'));
44
55
  totalInsertions += diff.insertions;
45
56
  totalDeletions += diff.deletions;
46
- changedFiles.add(filepath);
47
57
  }
48
58
  }
49
59
 
50
60
  // Check deleted files
51
61
  for (const [filepath, oldContent] of Object.entries(previousSnapshot)) {
52
62
  if (!currentSnapshot[filepath]) {
53
- // File was deleted - count all lines as deletions
54
- const lines = countLines(oldContent.toString('utf-8'));
55
- totalDeletions += lines;
56
63
  changedFiles.add(filepath);
64
+ if (isBinaryBuffer(oldContent)) continue;
65
+ totalDeletions += countLines(oldContent.toString('utf-8'));
57
66
  }
58
67
  }
59
68
 
@@ -64,56 +73,6 @@ export function calculateFileChangeStats(
64
73
  };
65
74
  }
66
75
 
67
- /**
68
- * Get detailed diff for each file
69
- * Useful for displaying individual file changes
70
- */
71
- export function getDetailedFileDiffs(
72
- previousSnapshot: Record<string, Buffer>,
73
- currentSnapshot: Record<string, Buffer>
74
- ): FileDiff[] {
75
- const diffs: FileDiff[] = [];
76
-
77
- // Check added and modified files
78
- for (const [filepath, newContent] of Object.entries(currentSnapshot)) {
79
- const oldContent = previousSnapshot[filepath];
80
-
81
- if (!oldContent) {
82
- // File was added
83
- diffs.push({
84
- filepath,
85
- insertions: countLines(newContent.toString('utf-8')),
86
- deletions: 0,
87
- status: 'added'
88
- });
89
- } else if (!oldContent.equals(newContent)) {
90
- // File was modified
91
- const diff = calculateLineDiff(oldContent.toString('utf-8'), newContent.toString('utf-8'));
92
- diffs.push({
93
- filepath,
94
- insertions: diff.insertions,
95
- deletions: diff.deletions,
96
- status: 'modified'
97
- });
98
- }
99
- }
100
-
101
- // Check deleted files
102
- for (const [filepath, oldContent] of Object.entries(previousSnapshot)) {
103
- if (!currentSnapshot[filepath]) {
104
- // File was deleted
105
- diffs.push({
106
- filepath,
107
- insertions: 0,
108
- deletions: countLines(oldContent.toString('utf-8')),
109
- status: 'deleted'
110
- });
111
- }
112
- }
113
-
114
- return diffs;
115
- }
116
-
117
76
  /**
118
77
  * Count only the lines that actually changed between two strings, using the
119
78
  * same LCS-based diff as git — identical (context) lines are excluded. Use this
@@ -180,7 +139,13 @@ function longestCommonSubsequence(arr1: string[], arr2: string[]): number {
180
139
  function splitLines(content: string): string[] {
181
140
  if (!content) return [];
182
141
  // Normalize line endings and split
183
- return content.replace(/\r\n/g, '\n').split('\n');
142
+ const lines = content.replace(/\r\n/g, '\n').split('\n');
143
+ // A trailing newline terminates the last line, it does not open a new one.
144
+ // Counting the empty string it leaves behind inflated every added or deleted
145
+ // file by exactly one line — a 2-line new file was reported as +3, which is
146
+ // not what git says and not what the user counts in the editor.
147
+ if (lines.length > 1 && lines[lines.length - 1] === '') lines.pop();
148
+ return lines;
184
149
  }
185
150
 
186
151
  /**
@@ -30,6 +30,7 @@ export type LogLabel =
30
30
  | 'mcp'
31
31
  | 'integrations'
32
32
  | 'work'
33
+ | 'deployments'
33
34
  | 'skills'
34
35
  | 'artifacts'
35
36
  | 'commands'
@@ -1,176 +0,0 @@
1
- /**
2
- * Language detection and source-level pattern extraction.
3
- *
4
- * Imports and definitions are recovered with regular expressions, not a parser.
5
- * That is a deliberate trade: a real AST per language would mean a tree-sitter
6
- * grammar (and a WASM runtime) for every language a user might open, on a hot
7
- * path that runs after every turn. What the graph needs is the *shape* of the
8
- * codebase — which files reference which, and roughly what each defines — and
9
- * regexes recover that well enough to be useful while costing microseconds.
10
- *
11
- * The limits are real and worth stating: a commented-out import still counts, a
12
- * dynamic `import(variable)` is invisible, and a declaration split across lines
13
- * may be missed. Structural nodes are therefore treated as evidence rather than
14
- * ground truth, and every one carries `confidence` below 1.
15
- */
16
-
17
- /** File extension → language label. */
18
- const EXTENSIONS: Record<string, string> = {
19
- ts: 'typescript',
20
- tsx: 'typescript',
21
- mts: 'typescript',
22
- cts: 'typescript',
23
- js: 'javascript',
24
- jsx: 'javascript',
25
- mjs: 'javascript',
26
- cjs: 'javascript',
27
- svelte: 'svelte',
28
- vue: 'vue',
29
- py: 'python',
30
- pyi: 'python',
31
- go: 'go',
32
- rs: 'rust',
33
- java: 'java',
34
- kt: 'kotlin',
35
- kts: 'kotlin',
36
- swift: 'swift',
37
- rb: 'ruby',
38
- php: 'php',
39
- cs: 'csharp',
40
- c: 'c',
41
- h: 'c',
42
- cc: 'cpp',
43
- cpp: 'cpp',
44
- hpp: 'cpp',
45
- css: 'css',
46
- scss: 'scss',
47
- html: 'html',
48
- json: 'json',
49
- yml: 'yaml',
50
- yaml: 'yaml',
51
- toml: 'toml',
52
- sql: 'sql',
53
- sh: 'shell',
54
- bash: 'shell',
55
- md: 'markdown'
56
- };
57
-
58
- /** Extensions tried when resolving an extensionless relative import. */
59
- const RESOLVE_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.svelte', '.vue', '.py', '.go', '.rs'];
60
-
61
- /** Languages worth reading the contents of; others become bare file nodes. */
62
- const PARSEABLE = new Set([
63
- 'typescript',
64
- 'javascript',
65
- 'svelte',
66
- 'vue',
67
- 'python',
68
- 'go',
69
- 'rust',
70
- 'java',
71
- 'kotlin',
72
- 'ruby',
73
- 'php',
74
- 'csharp',
75
- 'c',
76
- 'cpp'
77
- ]);
78
-
79
- export function detectLanguage(path: string): string | null {
80
- const ext = path.split('.').pop()?.toLowerCase();
81
- return ext ? (EXTENSIONS[ext] ?? null) : null;
82
- }
83
-
84
- export function isParseable(language: string | null): boolean {
85
- return language !== null && PARSEABLE.has(language);
86
- }
87
-
88
- export { RESOLVE_EXTENSIONS };
89
-
90
- /** Import/include specifiers per language family. */
91
- const IMPORT_PATTERNS: Record<string, RegExp[]> = {
92
- typescript: [
93
- /\bimport\s+(?:type\s+)?(?:[\w*{}\s,$]+\s+from\s+)?['"]([^'"]+)['"]/g,
94
- /\bexport\s+(?:type\s+)?[\w*{}\s,$]+\s+from\s+['"]([^'"]+)['"]/g,
95
- /\brequire\(\s*['"]([^'"]+)['"]\s*\)/g,
96
- /\bimport\(\s*['"]([^'"]+)['"]\s*\)/g
97
- ],
98
- python: [
99
- /^\s*from\s+([\w.]+)\s+import\b/gm,
100
- /^\s*import\s+([\w.]+)/gm
101
- ],
102
- go: [/^\s*(?:\w+\s+)?"([^"]+)"\s*$/gm],
103
- rust: [/^\s*use\s+([\w:]+)/gm],
104
- java: [/^\s*import\s+(?:static\s+)?([\w.]+);/gm],
105
- ruby: [/\brequire(?:_relative)?\s+['"]([^'"]+)['"]/g],
106
- php: [/\b(?:require|include)(?:_once)?\s*\(?\s*['"]([^'"]+)['"]/g],
107
- csharp: [/^\s*using\s+(?:static\s+)?([\w.]+)\s*;/gm],
108
- c: [/^\s*#include\s*[<"]([^>"]+)[>"]/gm]
109
- };
110
-
111
- IMPORT_PATTERNS.javascript = IMPORT_PATTERNS.typescript;
112
- IMPORT_PATTERNS.svelte = IMPORT_PATTERNS.typescript;
113
- IMPORT_PATTERNS.vue = IMPORT_PATTERNS.typescript;
114
- IMPORT_PATTERNS.kotlin = IMPORT_PATTERNS.java;
115
- IMPORT_PATTERNS.cpp = IMPORT_PATTERNS.c;
116
-
117
- /** Top-level definitions worth naming as their own node. */
118
- const DEFINITION_PATTERNS: Record<string, RegExp[]> = {
119
- typescript: [
120
- /^\s*export\s+(?:default\s+)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)/gm,
121
- /^\s*export\s+(?:abstract\s+)?class\s+([A-Za-z_$][\w$]*)/gm,
122
- /^\s*export\s+(?:interface|type|enum)\s+([A-Za-z_$][\w$]*)/gm,
123
- /^\s*export\s+(?:const|let|var)\s+([A-Za-z_$][\w$]*)/gm
124
- ],
125
- python: [
126
- /^\s*(?:async\s+)?def\s+([A-Za-z_]\w*)/gm,
127
- /^\s*class\s+([A-Za-z_]\w*)/gm
128
- ],
129
- go: [
130
- /^\s*func\s+(?:\([^)]*\)\s*)?([A-Za-z_]\w*)/gm,
131
- /^\s*type\s+([A-Za-z_]\w*)/gm
132
- ],
133
- rust: [
134
- /^\s*(?:pub\s+)?(?:async\s+)?fn\s+([A-Za-z_]\w*)/gm,
135
- /^\s*(?:pub\s+)?(?:struct|enum|trait)\s+([A-Za-z_]\w*)/gm
136
- ],
137
- java: [
138
- /^\s*(?:public|protected|private)?\s*(?:static\s+)?(?:final\s+)?(?:class|interface|enum|record)\s+([A-Za-z_]\w*)/gm
139
- ],
140
- php: [/^\s*(?:abstract\s+|final\s+)?(?:class|interface|trait)\s+([A-Za-z_]\w*)/gm, /^\s*function\s+([A-Za-z_]\w*)/gm],
141
- csharp: [/^\s*(?:public|internal|private|protected)?\s*(?:static\s+)?(?:sealed\s+)?(?:class|interface|record|struct|enum)\s+([A-Za-z_]\w*)/gm],
142
- ruby: [/^\s*(?:class|module)\s+([A-Z]\w*)/gm, /^\s*def\s+([a-z_]\w*[?!]?)/gm]
143
- };
144
-
145
- DEFINITION_PATTERNS.javascript = DEFINITION_PATTERNS.typescript;
146
- DEFINITION_PATTERNS.svelte = DEFINITION_PATTERNS.typescript;
147
- DEFINITION_PATTERNS.vue = DEFINITION_PATTERNS.typescript;
148
- DEFINITION_PATTERNS.kotlin = DEFINITION_PATTERNS.java;
149
- DEFINITION_PATTERNS.cpp = DEFINITION_PATTERNS.c ?? [];
150
-
151
- function collect(source: string, patterns: RegExp[] | undefined, limit: number): string[] {
152
- if (!patterns) return [];
153
- const found = new Set<string>();
154
- for (const pattern of patterns) {
155
- // Patterns are module-level and carry /g, so lastIndex must be reset or a
156
- // previous file's position leaks into this one.
157
- pattern.lastIndex = 0;
158
- let match: RegExpExecArray | null;
159
- while ((match = pattern.exec(source)) !== null) {
160
- const value = match[1]?.trim();
161
- if (value) found.add(value);
162
- if (found.size >= limit) return [...found];
163
- }
164
- }
165
- return [...found];
166
- }
167
-
168
- /** Import specifiers referenced by a source file, verbatim. */
169
- export function extractImports(source: string, language: string, limit = 80): string[] {
170
- return collect(source, IMPORT_PATTERNS[language], limit);
171
- }
172
-
173
- /** Names of top-level definitions in a source file. */
174
- export function extractDefinitions(source: string, language: string, limit = 40): string[] {
175
- return collect(source, DEFINITION_PATTERNS[language], limit);
176
- }
@@ -1,215 +0,0 @@
1
- /**
2
- * Structural extraction tests.
3
- *
4
- * Run against a real temporary project on disk and a real in-memory SQLite
5
- * database, because what is being tested is precisely the interaction with the
6
- * filesystem: which import specifiers resolve to real files, which are packages,
7
- * and which are neither.
8
- *
9
- * Two cases here exist because they were live bugs found during bring-up, and
10
- * both were quiet — they produced a plausible-looking graph that degraded
11
- * retrieval rather than throwing:
12
- *
13
- * - a build-tool path alias (`$shared/types`) was turned into a "dependency"
14
- * node, inventing a shared dependency between every file using the alias;
15
- * - structural nodes were given embedding vectors, and their path-fragment
16
- * text scored above correct answers for natural-language questions.
17
- */
18
-
19
- import { afterEach, beforeEach, describe, expect, it, mock } from 'bun:test';
20
- import { Database } from 'bun:sqlite';
21
- import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises';
22
- import { join } from 'node:path';
23
- import { tmpdir } from 'node:os';
24
- import type { DatabaseConnection } from '$shared/types/database/connection';
25
- import * as migration066 from '$backend/database/migrations/066_create_memory_graph';
26
-
27
- let db: Database;
28
-
29
- // The whole module surface, not just `getDatabase`. `mock.module` replaces the
30
- // module for the entire test PROCESS, so a partial stub leaves any file that runs
31
- // afterwards unable to import the missing names — surfacing as
32
- // "Export named 'closeDatabase' not found" in a test that never touched memory.
33
- mock.module('$backend/database', () => ({
34
- getDatabase: () => db,
35
- initializeDatabase: async () => db,
36
- closeDatabase: () => {},
37
- resetDatabase: async () => {},
38
- getDatabaseInfo: async () => ({}),
39
- vacuumDatabase: async () => {}
40
- }));
41
-
42
- const { graphQueries } = await import('$backend/database/queries/graph-queries');
43
- const { ingestStructuralChanges } = await import('./structural');
44
-
45
- const PROJECT_ID = 'structural-test';
46
- let projectPath: string;
47
-
48
- beforeEach(async () => {
49
- db = new Database(':memory:');
50
- db.exec('PRAGMA foreign_keys = ON');
51
- migration066.up(db as unknown as DatabaseConnection);
52
-
53
- projectPath = await mkdtemp(join(tmpdir(), 'clopen-structural-'));
54
- });
55
-
56
- afterEach(async () => {
57
- await rm(projectPath, { recursive: true, force: true });
58
- });
59
-
60
- async function write(relativePath: string, contents: string): Promise<void> {
61
- const full = join(projectPath, relativePath);
62
- await mkdir(join(full, '..'), { recursive: true });
63
- await writeFile(full, contents, 'utf8');
64
- }
65
-
66
- function ingest(changedPaths: string[]) {
67
- return ingestStructuralChanges({ projectId: PROJECT_ID, projectPath, sessionId: 'session-1', changedPaths });
68
- }
69
-
70
- describe('structural extraction', () => {
71
- it('creates a file node and its containing module', async () => {
72
- await write('src/service.ts', 'export function run(): void {}\n');
73
-
74
- const result = await ingest(['src/service.ts']);
75
- expect(result.files).toBe(1);
76
-
77
- const file = graphQueries.getByPath(PROJECT_ID, 'src/service.ts');
78
- expect(file).not.toBeNull();
79
- expect(file!.language).toBe('typescript');
80
- expect(file!.label).toBe('service.ts');
81
-
82
- // The module edge is what gives the graph a skeleton, which is what makes
83
- // community detection produce meaningful lobes rather than one cloud.
84
- const neighbours = graphQueries.neighbours(file!.id, 1);
85
- expect(neighbours.some(n => n.node.subkind === 'module' && n.node.path === 'src')).toBe(true);
86
- });
87
-
88
- it('resolves a relative import to the file it actually points at', async () => {
89
- await write('src/a.ts', "import { b } from './b';\nexport const a = 1;\n");
90
- await write('src/b.ts', 'export const b = 2;\n');
91
-
92
- await ingest(['src/a.ts']);
93
-
94
- const a = graphQueries.getByPath(PROJECT_ID, 'src/a.ts')!;
95
- const b = graphQueries.getByPath(PROJECT_ID, 'src/b.ts');
96
- expect(b).not.toBeNull();
97
- expect(graphQueries.edgesOf(a.id).some(e => e.srcId === a.id && e.dstId === b!.id && e.rel === 'imports')).toBe(true);
98
- });
99
-
100
- it('records a real package as a global dependency node', async () => {
101
- await write('src/uses-pkg.ts', "import merge from 'lodash/merge';\nimport { z } from 'zod';\n");
102
-
103
- await ingest(['src/uses-pkg.ts']);
104
-
105
- const deps = graphQueries
106
- .list({ projectId: null, kinds: ['structural'] })
107
- .filter(node => node.subkind === 'dependency')
108
- .map(node => node.label)
109
- .sort();
110
-
111
- // Scoped to the package, not the subpath — `lodash/merge` is still lodash.
112
- expect(deps).toEqual(['lodash', 'zod']);
113
- // Dependencies are global so the same package links projects together.
114
- expect(graphQueries.list({ projectId: null }).every(n => n.projectId === null)).toBe(true);
115
- });
116
-
117
- it('never turns a build-tool path alias into a dependency', async () => {
118
- await write(
119
- 'src/aliased.ts',
120
- [
121
- "import type { X } from '$shared/types';",
122
- "import { y } from '~/lib/y';",
123
- "import { z } from '@/utils/z';",
124
- "import { w } from '#internal/w';",
125
- "import { real } from 'nanoid';"
126
- ].join('\n')
127
- );
128
-
129
- await ingest(['src/aliased.ts']);
130
-
131
- const deps = graphQueries
132
- .list({ projectId: null, kinds: ['structural'] })
133
- .filter(node => node.subkind === 'dependency')
134
- .map(node => node.label);
135
-
136
- // Only the genuine package survives. An alias is not a dependency, and
137
- // inventing one would connect every file that uses it.
138
- expect(deps).toEqual(['nanoid']);
139
- });
140
-
141
- it('names exported definitions and links them to their file', async () => {
142
- await write(
143
- 'src/defs.ts',
144
- [
145
- 'export function alpha(): void {}',
146
- 'export class Beta {}',
147
- 'export interface Gamma { x: number }',
148
- 'export const delta = 4;',
149
- 'function notExported(): void {}'
150
- ].join('\n')
151
- );
152
-
153
- await ingest(['src/defs.ts']);
154
-
155
- const file = graphQueries.getByPath(PROJECT_ID, 'src/defs.ts')!;
156
- const symbols = graphQueries
157
- .neighbours(file.id, 1)
158
- .filter(n => n.node.subkind === 'symbol')
159
- .map(n => n.node.symbol)
160
- .sort();
161
-
162
- expect(symbols).toEqual(['Beta', 'Gamma', 'alpha', 'delta']);
163
- // Local helpers are not part of the module's surface, so they are not nodes.
164
- expect(symbols).not.toContain('notExported');
165
- });
166
-
167
- it('skips generated and vendored directories', async () => {
168
- await write('node_modules/pkg/index.js', 'module.exports = 1;\n');
169
- await write('dist/bundle.js', 'console.log(1);\n');
170
- await write('src/real.ts', 'export const real = 1;\n');
171
-
172
- const result = await ingest(['node_modules/pkg/index.js', 'dist/bundle.js', 'src/real.ts']);
173
- expect(result.files).toBe(1);
174
- expect(graphQueries.getByPath(PROJECT_ID, 'src/real.ts')).not.toBeNull();
175
- });
176
-
177
- it('re-ingesting the same file reinforces rather than duplicates', async () => {
178
- await write('src/again.ts', 'export const again = 1;\n');
179
-
180
- await ingest(['src/again.ts']);
181
- const first = graphQueries.getByPath(PROJECT_ID, 'src/again.ts')!;
182
- await ingest(['src/again.ts']);
183
- const second = graphQueries.getByPath(PROJECT_ID, 'src/again.ts')!;
184
-
185
- expect(second.id).toBe(first.id);
186
- expect(second.weight).toBeGreaterThan(first.weight);
187
- });
188
-
189
- it('keeps structural nodes out of the vector index', async () => {
190
- await write('src/vectors.ts', 'export const vectors = 1;\n');
191
- await ingest(['src/vectors.ts']);
192
- graphQueries.upsert({
193
- kind: 'episodic',
194
- subkind: 'decision',
195
- projectId: PROJECT_ID,
196
- label: 'Vectors are only computed for prose memories, never for file paths'
197
- });
198
-
199
- const pending = graphQueries.nodesMissingVectors('test-model', 100);
200
-
201
- // Embedding a path yields a bag of fragments that scores highly against
202
- // arbitrary questions; names are BM25's job. Only the memory is queued.
203
- expect(pending).toHaveLength(1);
204
- expect(pending[0].kind).toBe('episodic');
205
- });
206
-
207
- it('does not fail on a path that no longer exists', async () => {
208
- const result = await ingest(['src/deleted.ts']);
209
-
210
- // A file removed during the turn still deserves its node — memories pointing
211
- // at it remain true history — but nothing may throw on the way there.
212
- expect(result.files).toBe(1);
213
- expect(graphQueries.getByPath(PROJECT_ID, 'src/deleted.ts')).not.toBeNull();
214
- });
215
- });