@esankhan3/anvil-knowledge-core 0.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 (126) hide show
  1. package/README.md +194 -0
  2. package/dist/__tests__/chunker.test.d.ts +10 -0
  3. package/dist/__tests__/chunker.test.d.ts.map +1 -0
  4. package/dist/__tests__/chunker.test.js +161 -0
  5. package/dist/__tests__/chunker.test.js.map +1 -0
  6. package/dist/__tests__/query-classifier.test.d.ts +5 -0
  7. package/dist/__tests__/query-classifier.test.d.ts.map +1 -0
  8. package/dist/__tests__/query-classifier.test.js +158 -0
  9. package/dist/__tests__/query-classifier.test.js.map +1 -0
  10. package/dist/__tests__/retriever-defaults.test.d.ts +12 -0
  11. package/dist/__tests__/retriever-defaults.test.d.ts.map +1 -0
  12. package/dist/__tests__/retriever-defaults.test.js +37 -0
  13. package/dist/__tests__/retriever-defaults.test.js.map +1 -0
  14. package/dist/__tests__/structural-hasher.test.d.ts +5 -0
  15. package/dist/__tests__/structural-hasher.test.d.ts.map +1 -0
  16. package/dist/__tests__/structural-hasher.test.js +185 -0
  17. package/dist/__tests__/structural-hasher.test.js.map +1 -0
  18. package/dist/ast-graph-builder.d.ts +38 -0
  19. package/dist/ast-graph-builder.d.ts.map +1 -0
  20. package/dist/ast-graph-builder.js +1041 -0
  21. package/dist/ast-graph-builder.js.map +1 -0
  22. package/dist/chunker.d.ts +47 -0
  23. package/dist/chunker.d.ts.map +1 -0
  24. package/dist/chunker.js +428 -0
  25. package/dist/chunker.js.map +1 -0
  26. package/dist/claude-runner.d.ts +10 -0
  27. package/dist/claude-runner.d.ts.map +1 -0
  28. package/dist/claude-runner.js +10 -0
  29. package/dist/claude-runner.js.map +1 -0
  30. package/dist/config.d.ts +36 -0
  31. package/dist/config.d.ts.map +1 -0
  32. package/dist/config.js +83 -0
  33. package/dist/config.js.map +1 -0
  34. package/dist/cross-repo-detector.d.ts +7 -0
  35. package/dist/cross-repo-detector.d.ts.map +1 -0
  36. package/dist/cross-repo-detector.js +990 -0
  37. package/dist/cross-repo-detector.js.map +1 -0
  38. package/dist/embedder.d.ts +84 -0
  39. package/dist/embedder.d.ts.map +1 -0
  40. package/dist/embedder.js +378 -0
  41. package/dist/embedder.js.map +1 -0
  42. package/dist/file-walker.d.ts +18 -0
  43. package/dist/file-walker.d.ts.map +1 -0
  44. package/dist/file-walker.js +221 -0
  45. package/dist/file-walker.js.map +1 -0
  46. package/dist/git-diff.d.ts +32 -0
  47. package/dist/git-diff.d.ts.map +1 -0
  48. package/dist/git-diff.js +145 -0
  49. package/dist/git-diff.js.map +1 -0
  50. package/dist/graph-metrics.d.ts +31 -0
  51. package/dist/graph-metrics.d.ts.map +1 -0
  52. package/dist/graph-metrics.js +277 -0
  53. package/dist/graph-metrics.js.map +1 -0
  54. package/dist/graph-query.d.ts +8 -0
  55. package/dist/graph-query.d.ts.map +1 -0
  56. package/dist/graph-query.js +79 -0
  57. package/dist/graph-query.js.map +1 -0
  58. package/dist/index.d.ts +27 -0
  59. package/dist/index.d.ts.map +1 -0
  60. package/dist/index.js +43 -0
  61. package/dist/index.js.map +1 -0
  62. package/dist/indexer.d.ts +98 -0
  63. package/dist/indexer.d.ts.map +1 -0
  64. package/dist/indexer.js +635 -0
  65. package/dist/indexer.js.map +1 -0
  66. package/dist/project-graph-builder-core.d.ts +48 -0
  67. package/dist/project-graph-builder-core.d.ts.map +1 -0
  68. package/dist/project-graph-builder-core.js +213 -0
  69. package/dist/project-graph-builder-core.js.map +1 -0
  70. package/dist/project-graph-builder.d.ts +39 -0
  71. package/dist/project-graph-builder.d.ts.map +1 -0
  72. package/dist/project-graph-builder.js +640 -0
  73. package/dist/project-graph-builder.js.map +1 -0
  74. package/dist/query-classifier.d.ts +38 -0
  75. package/dist/query-classifier.d.ts.map +1 -0
  76. package/dist/query-classifier.js +199 -0
  77. package/dist/query-classifier.js.map +1 -0
  78. package/dist/query-router.d.ts +82 -0
  79. package/dist/query-router.d.ts.map +1 -0
  80. package/dist/query-router.js +278 -0
  81. package/dist/query-router.js.map +1 -0
  82. package/dist/rag-evaluator.d.ts +53 -0
  83. package/dist/rag-evaluator.d.ts.map +1 -0
  84. package/dist/rag-evaluator.js +217 -0
  85. package/dist/rag-evaluator.js.map +1 -0
  86. package/dist/repo-profiler.d.ts +62 -0
  87. package/dist/repo-profiler.d.ts.map +1 -0
  88. package/dist/repo-profiler.js +488 -0
  89. package/dist/repo-profiler.js.map +1 -0
  90. package/dist/reranker.d.ts +8 -0
  91. package/dist/reranker.d.ts.map +1 -0
  92. package/dist/reranker.js +250 -0
  93. package/dist/reranker.js.map +1 -0
  94. package/dist/retriever.d.ts +42 -0
  95. package/dist/retriever.d.ts.map +1 -0
  96. package/dist/retriever.js +320 -0
  97. package/dist/retriever.js.map +1 -0
  98. package/dist/semantic-edge-detector.d.ts +28 -0
  99. package/dist/semantic-edge-detector.d.ts.map +1 -0
  100. package/dist/semantic-edge-detector.js +191 -0
  101. package/dist/semantic-edge-detector.js.map +1 -0
  102. package/dist/service-mesh-inferrer.d.ts +57 -0
  103. package/dist/service-mesh-inferrer.d.ts.map +1 -0
  104. package/dist/service-mesh-inferrer.js +322 -0
  105. package/dist/service-mesh-inferrer.js.map +1 -0
  106. package/dist/structural-hasher.d.ts +57 -0
  107. package/dist/structural-hasher.d.ts.map +1 -0
  108. package/dist/structural-hasher.js +350 -0
  109. package/dist/structural-hasher.js.map +1 -0
  110. package/dist/tree-sitter-parser.d.ts +71 -0
  111. package/dist/tree-sitter-parser.d.ts.map +1 -0
  112. package/dist/tree-sitter-parser.js +633 -0
  113. package/dist/tree-sitter-parser.js.map +1 -0
  114. package/dist/types.d.ts +179 -0
  115. package/dist/types.d.ts.map +1 -0
  116. package/dist/types.js +2 -0
  117. package/dist/types.js.map +1 -0
  118. package/dist/vector-store.d.ts +56 -0
  119. package/dist/vector-store.d.ts.map +1 -0
  120. package/dist/vector-store.js +299 -0
  121. package/dist/vector-store.js.map +1 -0
  122. package/dist/workspace-detector.d.ts +11 -0
  123. package/dist/workspace-detector.d.ts.map +1 -0
  124. package/dist/workspace-detector.js +587 -0
  125. package/dist/workspace-detector.js.map +1 -0
  126. package/package.json +41 -0
@@ -0,0 +1,57 @@
1
+ /**
2
+ * WS-6: Structural Hashing for Deduplication
3
+ *
4
+ * Computes logic-based hashes of code entities so that functionally identical
5
+ * code produces the same hash regardless of formatting, comments, or local
6
+ * variable naming.
7
+ *
8
+ * Uses regex-based canonicalization (upgradable to Tree-sitter when WS-4 lands).
9
+ */
10
+ export interface StructuralHashResult {
11
+ hash: string;
12
+ canonicalSize: number;
13
+ }
14
+ /**
15
+ * Compute a structural hash for a code entity.
16
+ *
17
+ * Pipeline:
18
+ * 1. Strip comments (line comments, block comments, docstrings)
19
+ * 2. Strip whitespace/formatting (normalize to single spaces, remove blank lines)
20
+ * 3. Normalize local variable names to positional tokens
21
+ * 4. Sort order-independent constructs (object keys, interface fields, enum variants)
22
+ * 5. SHA256 hash the canonical string
23
+ */
24
+ export declare function computeStructuralHash(content: string, language: string): StructuralHashResult;
25
+ /**
26
+ * Compute structural hashes for all chunks, returning a map of chunkId -> hash.
27
+ * Also returns dedup groups (chunks that share the same structural hash).
28
+ */
29
+ export declare function computeStructuralHashes(chunks: Array<{
30
+ id: string;
31
+ content: string;
32
+ language: string;
33
+ }>): {
34
+ hashes: Map<string, string>;
35
+ dedupGroups: Map<string, string[]>;
36
+ duplicateCount: number;
37
+ uniqueCount: number;
38
+ };
39
+ /**
40
+ * Given chunks with structural hashes, return only unique chunks.
41
+ * For each dedup group, keep the first occurrence (by chunk ID sort order).
42
+ * Returns the chunks that should be embedded + the chunks that are duplicates.
43
+ */
44
+ export declare function deduplicateByStructure<T extends {
45
+ id: string;
46
+ content: string;
47
+ language: string;
48
+ structuralHash?: string;
49
+ }>(chunks: T[]): {
50
+ unique: T[];
51
+ duplicates: T[];
52
+ savings: {
53
+ chunks: number;
54
+ estimatedTokens: number;
55
+ };
56
+ };
57
+ //# sourceMappingURL=structural-hasher.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"structural-hasher.d.ts","sourceRoot":"","sources":["../src/structural-hasher.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAQH,MAAM,WAAW,oBAAoB;IACnC,IAAI,EAAE,MAAM,CAAC;IACb,aAAa,EAAE,MAAM,CAAC;CACvB;AA6RD;;;;;;;;;GASG;AACH,wBAAgB,qBAAqB,CACnC,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,MAAM,GACf,oBAAoB,CAItB;AAED;;;GAGG;AACH,wBAAgB,uBAAuB,CACrC,MAAM,EAAE,KAAK,CAAC;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,CAAC,GAC/D;IACD,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC5B,WAAW,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;IACnC,cAAc,EAAE,MAAM,CAAC;IACvB,WAAW,EAAE,MAAM,CAAC;CACrB,CA8BA;AAKD;;;;GAIG;AACH,wBAAgB,sBAAsB,CACpC,CAAC,SAAS;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,cAAc,CAAC,EAAE,MAAM,CAAA;CAAE,EAEpF,MAAM,EAAE,CAAC,EAAE,GACV;IACD,MAAM,EAAE,CAAC,EAAE,CAAC;IACZ,UAAU,EAAE,CAAC,EAAE,CAAC;IAChB,OAAO,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,eAAe,EAAE,MAAM,CAAA;KAAE,CAAC;CACtD,CA0CA"}
@@ -0,0 +1,350 @@
1
+ /**
2
+ * WS-6: Structural Hashing for Deduplication
3
+ *
4
+ * Computes logic-based hashes of code entities so that functionally identical
5
+ * code produces the same hash regardless of formatting, comments, or local
6
+ * variable naming.
7
+ *
8
+ * Uses regex-based canonicalization (upgradable to Tree-sitter when WS-4 lands).
9
+ */
10
+ import { createHash } from 'node:crypto';
11
+ // ---------------------------------------------------------------------------
12
+ // Comment / string-literal patterns
13
+ // ---------------------------------------------------------------------------
14
+ // Matches string literals (single, double, template) so we can protect them
15
+ // from the comment-stripping pass. Handles escaped quotes.
16
+ const STRING_LITERAL_RE = /(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`)/g;
17
+ const LINE_COMMENT_RE = /\/\/.*$/gm;
18
+ const HASH_COMMENT_RE = /#.*$/gm;
19
+ const BLOCK_COMMENT_RE = /\/\*[\s\S]*?\*\//g;
20
+ const PYTHON_DOCSTRING_RE = /"""[\s\S]*?"""|'''[\s\S]*?'''/g;
21
+ // Languages where `#` starts a line comment
22
+ const HASH_COMMENT_LANGS = new Set(['python', 'ruby', 'bash', 'shell', 'yaml']);
23
+ // Languages where `//` starts a line comment
24
+ const SLASH_COMMENT_LANGS = new Set([
25
+ 'typescript', 'javascript', 'tsx', 'jsx', 'go', 'rust', 'java',
26
+ 'c', 'cpp', 'csharp', 'swift', 'kotlin', 'scala', 'dart', 'php',
27
+ ]);
28
+ // ---------------------------------------------------------------------------
29
+ // Step 1: Strip comments (preserve string literals)
30
+ // ---------------------------------------------------------------------------
31
+ /**
32
+ * Replace string literals with placeholders, strip comments, then restore.
33
+ * This prevents stripping `//` or `#` that appear inside string values.
34
+ */
35
+ function stripComments(content, language) {
36
+ // Protect string literals
37
+ const strings = [];
38
+ let protected_ = content.replace(STRING_LITERAL_RE, (match) => {
39
+ strings.push(match);
40
+ return `__STR_${strings.length - 1}__`;
41
+ });
42
+ // Python docstrings (before block comments since they use triple-quotes)
43
+ if (language === 'python') {
44
+ protected_ = protected_.replace(PYTHON_DOCSTRING_RE, '');
45
+ }
46
+ // Block comments (/* ... */)
47
+ if (SLASH_COMMENT_LANGS.has(language) || language === 'css') {
48
+ protected_ = protected_.replace(BLOCK_COMMENT_RE, '');
49
+ }
50
+ // Line comments
51
+ if (SLASH_COMMENT_LANGS.has(language)) {
52
+ protected_ = protected_.replace(LINE_COMMENT_RE, '');
53
+ }
54
+ if (HASH_COMMENT_LANGS.has(language)) {
55
+ protected_ = protected_.replace(HASH_COMMENT_RE, '');
56
+ }
57
+ // Restore string literals
58
+ protected_ = protected_.replace(/__STR_(\d+)__/g, (_, idx) => strings[Number(idx)]);
59
+ return protected_;
60
+ }
61
+ // ---------------------------------------------------------------------------
62
+ // Step 2: Normalize whitespace
63
+ // ---------------------------------------------------------------------------
64
+ function normalizeWhitespace(content) {
65
+ return content
66
+ .split('\n')
67
+ .map((line) => line.trim())
68
+ .filter((line) => line.length > 0) // remove blank lines
69
+ .map((line) => line.replace(/,\s*$/, '')) // strip trailing commas
70
+ .map((line) => line.replace(/\s+/g, ' ')) // collapse whitespace
71
+ .join('\n');
72
+ }
73
+ // ---------------------------------------------------------------------------
74
+ // Step 3: Normalize local variable names
75
+ // ---------------------------------------------------------------------------
76
+ // Declaration patterns per language family.
77
+ // Captures: (keyword)(name)(rest of line)
78
+ const VAR_DECL_PATTERNS = {
79
+ typescript: [
80
+ /\b(const|let|var)\s+([a-zA-Z_$][\w$]*)\s*=/g,
81
+ ],
82
+ javascript: [
83
+ /\b(const|let|var)\s+([a-zA-Z_$][\w$]*)\s*=/g,
84
+ ],
85
+ tsx: [
86
+ /\b(const|let|var)\s+([a-zA-Z_$][\w$]*)\s*=/g,
87
+ ],
88
+ jsx: [
89
+ /\b(const|let|var)\s+([a-zA-Z_$][\w$]*)\s*=/g,
90
+ ],
91
+ go: [
92
+ /\b([a-zA-Z_][\w]*)\s*:=/g,
93
+ /\bvar\s+([a-zA-Z_][\w]*)\b/g,
94
+ ],
95
+ python: [
96
+ // Simple assignment (not augmented, not type-annotated attribute)
97
+ /^(\s*)([a-zA-Z_][\w]*)\s*=/gm,
98
+ ],
99
+ rust: [
100
+ /\blet\s+(?:mut\s+)?([a-zA-Z_][\w]*)\s*(?::|=)/g,
101
+ ],
102
+ };
103
+ /**
104
+ * Replace locally-declared variable names with positional tokens (v0, v1, ...).
105
+ * Does NOT rename function parameters, exported names, type names, or imports.
106
+ */
107
+ function normalizeLocalVariables(content, language) {
108
+ const langKey = language.toLowerCase();
109
+ const patterns = VAR_DECL_PATTERNS[langKey];
110
+ if (!patterns)
111
+ return content;
112
+ // Collect declared local names in order of appearance
113
+ const localNames = [];
114
+ for (const pattern of patterns) {
115
+ // Reset lastIndex since we may re-use the regex
116
+ const re = new RegExp(pattern.source, pattern.flags);
117
+ let match;
118
+ while ((match = re.exec(content)) !== null) {
119
+ // For Go `:=`, group 1 is the name; for others, group 2 is the name
120
+ const name = match[2] ?? match[1];
121
+ if (name && !localNames.includes(name) && !isReservedIdentifier(name)) {
122
+ localNames.push(name);
123
+ }
124
+ }
125
+ }
126
+ // Build replacement map: original name -> v0, v1, ...
127
+ let result = content;
128
+ for (let i = 0; i < localNames.length; i++) {
129
+ const name = localNames[i];
130
+ // Replace whole-word occurrences only (not inside other identifiers)
131
+ const nameRe = new RegExp(`\\b${escapeRegex(name)}\\b`, 'g');
132
+ result = result.replace(nameRe, `v${i}`);
133
+ }
134
+ return result;
135
+ }
136
+ /** Reserved keywords that should never be treated as local variables */
137
+ function isReservedIdentifier(name) {
138
+ const reserved = new Set([
139
+ // JS/TS
140
+ 'true', 'false', 'null', 'undefined', 'this', 'super', 'return',
141
+ 'if', 'else', 'for', 'while', 'do', 'switch', 'case', 'break',
142
+ 'continue', 'throw', 'try', 'catch', 'finally', 'new', 'delete',
143
+ 'typeof', 'instanceof', 'void', 'in', 'of', 'async', 'await',
144
+ 'yield', 'import', 'export', 'default', 'from', 'as', 'class',
145
+ 'extends', 'implements', 'interface', 'type', 'enum', 'function',
146
+ // Go
147
+ 'func', 'package', 'defer', 'go', 'select', 'chan', 'map', 'range',
148
+ 'struct', 'nil', 'err',
149
+ // Python
150
+ 'def', 'lambda', 'self', 'cls', 'None', 'True', 'False', 'with',
151
+ 'pass', 'raise', 'except', 'global', 'nonlocal',
152
+ // Rust
153
+ 'fn', 'pub', 'crate', 'mod', 'use', 'impl', 'trait', 'where',
154
+ 'Some', 'None', 'Ok', 'Err', 'Self',
155
+ ]);
156
+ return reserved.has(name);
157
+ }
158
+ function escapeRegex(str) {
159
+ return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
160
+ }
161
+ // ---------------------------------------------------------------------------
162
+ // Step 4: Sort order-independent constructs
163
+ // ---------------------------------------------------------------------------
164
+ /**
165
+ * Sort fields inside interface/type bodies, object literal keys,
166
+ * enum variants, and import specifiers.
167
+ *
168
+ * Uses brace-matching to locate blocks, then sorts lines within them.
169
+ */
170
+ function sortOrderIndependentBlocks(content, language) {
171
+ let result = content;
172
+ // Sort import specifiers: import { z, a, m } from '...' → import { a, m, z } from '...'
173
+ result = result.replace(/import\s*\{([^}]+)\}\s*from/g, (_match, specifiers) => {
174
+ const sorted = specifiers
175
+ .split(',')
176
+ .map((s) => s.trim())
177
+ .filter((s) => s.length > 0)
178
+ .sort()
179
+ .join(', ');
180
+ return `import { ${sorted} } from`;
181
+ });
182
+ // Sort interface/type/enum/object bodies if the language supports them.
183
+ // We look for patterns like `interface X {`, `type X = {`, `enum X {`
184
+ // and sort the lines between the braces.
185
+ if (['typescript', 'javascript', 'tsx', 'jsx', 'go', 'rust'].includes(language)) {
186
+ result = sortBracedBlocks(result, /\b(?:interface|type\s+\w+\s*=|enum)\s+\w+[^{]*\{/g);
187
+ }
188
+ return result;
189
+ }
190
+ /**
191
+ * For each match of `blockStartRe`, find the matching `}` and sort the
192
+ * interior lines alphabetically. Only sorts single-depth blocks (no nesting).
193
+ */
194
+ function sortBracedBlocks(content, blockStartRe) {
195
+ const re = new RegExp(blockStartRe.source, blockStartRe.flags);
196
+ let result = content;
197
+ let match;
198
+ // Process from back to front so indices stay valid after replacements
199
+ const replacements = [];
200
+ while ((match = re.exec(result)) !== null) {
201
+ const openBrace = result.indexOf('{', match.index + match[0].length - 1);
202
+ if (openBrace === -1)
203
+ continue;
204
+ // Find matching close brace (depth-aware)
205
+ let depth = 1;
206
+ let pos = openBrace + 1;
207
+ while (pos < result.length && depth > 0) {
208
+ if (result[pos] === '{')
209
+ depth++;
210
+ else if (result[pos] === '}')
211
+ depth--;
212
+ pos++;
213
+ }
214
+ if (depth !== 0)
215
+ continue;
216
+ const closeBrace = pos - 1;
217
+ const interior = result.slice(openBrace + 1, closeBrace);
218
+ // Only sort simple single-line field blocks (no nested braces)
219
+ if (interior.includes('{'))
220
+ continue;
221
+ const lines = interior
222
+ .split('\n')
223
+ .map((l) => l.trim())
224
+ .filter((l) => l.length > 0);
225
+ if (lines.length <= 1)
226
+ continue;
227
+ const sorted = lines.sort().join('\n');
228
+ replacements.push({
229
+ start: openBrace + 1,
230
+ end: closeBrace,
231
+ replacement: '\n' + sorted + '\n',
232
+ });
233
+ }
234
+ // Apply replacements back-to-front
235
+ for (const r of replacements.sort((a, b) => b.start - a.start)) {
236
+ result = result.slice(0, r.start) + r.replacement + result.slice(r.end);
237
+ }
238
+ return result;
239
+ }
240
+ // ---------------------------------------------------------------------------
241
+ // Main canonicalization pipeline
242
+ // ---------------------------------------------------------------------------
243
+ function canonicalize(content, language) {
244
+ let result = content;
245
+ result = stripComments(result, language);
246
+ result = normalizeWhitespace(result);
247
+ result = normalizeLocalVariables(result, language);
248
+ result = sortOrderIndependentBlocks(result, language);
249
+ // Final whitespace pass after sorting
250
+ result = normalizeWhitespace(result);
251
+ return result;
252
+ }
253
+ // ---------------------------------------------------------------------------
254
+ // Public API
255
+ // ---------------------------------------------------------------------------
256
+ /**
257
+ * Compute a structural hash for a code entity.
258
+ *
259
+ * Pipeline:
260
+ * 1. Strip comments (line comments, block comments, docstrings)
261
+ * 2. Strip whitespace/formatting (normalize to single spaces, remove blank lines)
262
+ * 3. Normalize local variable names to positional tokens
263
+ * 4. Sort order-independent constructs (object keys, interface fields, enum variants)
264
+ * 5. SHA256 hash the canonical string
265
+ */
266
+ export function computeStructuralHash(content, language) {
267
+ const canonical = canonicalize(content, language);
268
+ const hash = createHash('sha256').update(canonical).digest('hex');
269
+ return { hash, canonicalSize: canonical.length };
270
+ }
271
+ /**
272
+ * Compute structural hashes for all chunks, returning a map of chunkId -> hash.
273
+ * Also returns dedup groups (chunks that share the same structural hash).
274
+ */
275
+ export function computeStructuralHashes(chunks) {
276
+ const hashes = new Map();
277
+ const dedupGroups = new Map();
278
+ for (const chunk of chunks) {
279
+ const { hash } = computeStructuralHash(chunk.content, chunk.language);
280
+ hashes.set(chunk.id, hash);
281
+ const group = dedupGroups.get(hash);
282
+ if (group) {
283
+ group.push(chunk.id);
284
+ }
285
+ else {
286
+ dedupGroups.set(hash, [chunk.id]);
287
+ }
288
+ }
289
+ let duplicateCount = 0;
290
+ for (const group of Array.from(dedupGroups.values())) {
291
+ if (group.length > 1) {
292
+ // All but the first are duplicates
293
+ duplicateCount += group.length - 1;
294
+ }
295
+ }
296
+ return {
297
+ hashes,
298
+ dedupGroups,
299
+ duplicateCount,
300
+ uniqueCount: chunks.length - duplicateCount,
301
+ };
302
+ }
303
+ /** Rough token estimate: ~4 chars per token */
304
+ const CHARS_PER_TOKEN = 4;
305
+ /**
306
+ * Given chunks with structural hashes, return only unique chunks.
307
+ * For each dedup group, keep the first occurrence (by chunk ID sort order).
308
+ * Returns the chunks that should be embedded + the chunks that are duplicates.
309
+ */
310
+ export function deduplicateByStructure(chunks) {
311
+ // Compute hashes for any chunks that don't already have one
312
+ const hashMap = new Map();
313
+ for (const chunk of chunks) {
314
+ const hash = chunk.structuralHash ?? computeStructuralHash(chunk.content, chunk.language).hash;
315
+ hashMap.set(chunk.id, hash);
316
+ }
317
+ // Group by structural hash, keeping insertion order per group
318
+ const groups = new Map();
319
+ for (const chunk of chunks) {
320
+ const hash = hashMap.get(chunk.id);
321
+ const group = groups.get(hash);
322
+ if (group) {
323
+ group.push(chunk);
324
+ }
325
+ else {
326
+ groups.set(hash, [chunk]);
327
+ }
328
+ }
329
+ const unique = [];
330
+ const duplicates = [];
331
+ let savedChars = 0;
332
+ for (const group of Array.from(groups.values())) {
333
+ // Sort by ID for deterministic selection of the "canonical" chunk
334
+ const sorted = [...group].sort((a, b) => a.id.localeCompare(b.id));
335
+ unique.push(sorted[0]);
336
+ for (let i = 1; i < sorted.length; i++) {
337
+ duplicates.push(sorted[i]);
338
+ savedChars += sorted[i].content.length;
339
+ }
340
+ }
341
+ return {
342
+ unique,
343
+ duplicates,
344
+ savings: {
345
+ chunks: duplicates.length,
346
+ estimatedTokens: Math.round(savedChars / CHARS_PER_TOKEN),
347
+ },
348
+ };
349
+ }
350
+ //# sourceMappingURL=structural-hasher.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"structural-hasher.js","sourceRoot":"","sources":["../src/structural-hasher.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAWzC,8EAA8E;AAC9E,oCAAoC;AACpC,8EAA8E;AAE9E,4EAA4E;AAC5E,4DAA4D;AAC5D,MAAM,iBAAiB,GACrB,4DAA4D,CAAC;AAE/D,MAAM,eAAe,GAAG,WAAW,CAAC;AACpC,MAAM,eAAe,GAAG,QAAQ,CAAC;AACjC,MAAM,gBAAgB,GAAG,mBAAmB,CAAC;AAC7C,MAAM,mBAAmB,GAAG,gCAAgC,CAAC;AAE7D,4CAA4C;AAC5C,MAAM,kBAAkB,GAAG,IAAI,GAAG,CAAC,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC,CAAC;AAEhF,6CAA6C;AAC7C,MAAM,mBAAmB,GAAG,IAAI,GAAG,CAAC;IAClC,YAAY,EAAE,YAAY,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM;IAC9D,GAAG,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,QAAQ,EA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AI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;QACvB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YACvC,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;YAC3B,UAAU,IAAI,MAAM,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC;QACzC,CAAC;IACH,CAAC;IAED,OAAO;QACL,MAAM;QACN,UAAU;QACV,OAAO,EAAE;YACP,MAAM,EAAE,UAAU,CAAC,MAAM;YACzB,eAAe,EAAE,IAAI,CAAC,KAAK,CAAC,UAAU,GAAG,eAAe,CAAC;SAC1D;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Tree-sitter AST parser — compiler-accurate entity extraction.
3
+ *
4
+ * Real AST parsing via web-tree-sitter (WASM). Supports TypeScript,
5
+ * JavaScript, TSX, Go, Python, Rust, Java, and PHP.
6
+ */
7
+ export interface TreeSitterEntity {
8
+ name: string;
9
+ type: 'function' | 'class' | 'method' | 'interface' | 'type' | 'struct' | 'enum' | 'trait' | 'module';
10
+ startLine: number;
11
+ endLine: number;
12
+ startByte: number;
13
+ endByte: number;
14
+ parent?: string;
15
+ signature?: string;
16
+ isExported: boolean;
17
+ body: string;
18
+ }
19
+ export interface TreeSitterImport {
20
+ source: string;
21
+ names: string[];
22
+ startLine: number;
23
+ isRelative: boolean;
24
+ }
25
+ export interface TreeSitterCallSite {
26
+ callee: string;
27
+ startLine: number;
28
+ containingEntity?: string;
29
+ }
30
+ export interface FileParseResult {
31
+ filePath: string;
32
+ language: string;
33
+ entities: TreeSitterEntity[];
34
+ imports: TreeSitterImport[];
35
+ callSites: TreeSitterCallSite[];
36
+ typeReferences: string[];
37
+ }
38
+ /** Initialize the Tree-sitter WASM runtime. Must be called before parsing. */
39
+ export declare function initTreeSitter(): Promise<void>;
40
+ /**
41
+ * Parse a single source file using Tree-sitter AST parsing.
42
+ *
43
+ * Returns null for unsupported languages or parse failures.
44
+ */
45
+ export declare function parseFile(filePath: string, content: string, language: string): Promise<FileParseResult | null>;
46
+ /**
47
+ * Parse multiple files, initializing Tree-sitter once.
48
+ * Returns results for all files that parsed successfully (failures are skipped).
49
+ */
50
+ export declare function parseFiles(files: Array<{
51
+ path: string;
52
+ content: string;
53
+ language: string;
54
+ }>): Promise<FileParseResult[]>;
55
+ /**
56
+ * Compute a structural hash of an entity's AST subtree.
57
+ *
58
+ * Two functions with identical logic but different variable names produce the
59
+ * same hash. This is used by WS-6 for deduplication.
60
+ *
61
+ * The algorithm:
62
+ * 1. Parse the entity body into an AST
63
+ * 2. Walk the tree, collecting node types (skip comments and whitespace)
64
+ * 3. Normalize identifier names to positional tokens (v0, v1, v2...)
65
+ * 4. Build a canonical string representation
66
+ * 5. SHA256 hash it
67
+ */
68
+ export declare function computeStructuralHash(_content: string, entity: TreeSitterEntity, language: string): Promise<string | null>;
69
+ /** Returns the list of languages supported by the Tree-sitter parser. */
70
+ export declare function supportedLanguages(): string[];
71
+ //# sourceMappingURL=tree-sitter-parser.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tree-sitter-parser.d.ts","sourceRoot":"","sources":["../src/tree-sitter-parser.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAaH,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,UAAU,GAAG,OAAO,GAAG,QAAQ,GAAG,WAAW,GAAG,MAAM,GAAG,QAAQ,GAAG,MAAM,GAAG,OAAO,GAAG,QAAQ,CAAC;IACtG,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,SAAS,CAAC,EAAE,MAAM,CAAC;I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