@principal-ai/subsystems-core 0.51.4 → 0.51.6

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 (155) hide show
  1. package/README.md +21 -6
  2. package/dist/audit/boundary.d.ts +104 -0
  3. package/dist/audit/boundary.d.ts.map +1 -0
  4. package/dist/audit/boundary.js +363 -0
  5. package/dist/audit/boundary.js.map +1 -0
  6. package/dist/audit/c4.d.ts +41 -0
  7. package/dist/audit/c4.d.ts.map +1 -0
  8. package/dist/audit/c4.js +41 -0
  9. package/dist/audit/c4.js.map +1 -0
  10. package/dist/audit/engine.d.ts +135 -0
  11. package/dist/audit/engine.d.ts.map +1 -0
  12. package/dist/audit/engine.js +828 -0
  13. package/dist/audit/engine.js.map +1 -0
  14. package/dist/audit/fixes.d.ts +80 -0
  15. package/dist/audit/fixes.d.ts.map +1 -0
  16. package/dist/audit/fixes.js +162 -0
  17. package/dist/audit/fixes.js.map +1 -0
  18. package/dist/audit/hash.d.ts +25 -0
  19. package/dist/audit/hash.d.ts.map +1 -0
  20. package/dist/audit/hash.js +53 -0
  21. package/dist/audit/hash.js.map +1 -0
  22. package/dist/audit/index.d.ts +11 -1
  23. package/dist/audit/index.d.ts.map +1 -1
  24. package/dist/audit/index.js +37 -3
  25. package/dist/audit/index.js.map +1 -1
  26. package/dist/audit/local-graphify.d.ts +75 -0
  27. package/dist/audit/local-graphify.d.ts.map +1 -0
  28. package/dist/audit/local-graphify.js +283 -0
  29. package/dist/audit/local-graphify.js.map +1 -0
  30. package/dist/audit/paths.d.ts +16 -0
  31. package/dist/audit/paths.d.ts.map +1 -0
  32. package/dist/audit/paths.js +31 -0
  33. package/dist/audit/paths.js.map +1 -0
  34. package/dist/audit/pure.d.ts +18 -0
  35. package/dist/audit/pure.d.ts.map +1 -0
  36. package/dist/audit/pure.js +50 -0
  37. package/dist/audit/pure.js.map +1 -0
  38. package/dist/audit/report-logic.d.ts +17 -0
  39. package/dist/audit/report-logic.d.ts.map +1 -0
  40. package/dist/audit/report-logic.js +206 -0
  41. package/dist/audit/report-logic.js.map +1 -0
  42. package/dist/audit/report.d.ts +136 -0
  43. package/dist/audit/report.d.ts.map +1 -0
  44. package/dist/audit/report.js +3 -0
  45. package/dist/audit/report.js.map +1 -0
  46. package/dist/audit/trail.d.ts +29 -0
  47. package/dist/audit/trail.d.ts.map +1 -0
  48. package/dist/audit/trail.js +59 -0
  49. package/dist/audit/trail.js.map +1 -0
  50. package/dist/audit/verification.d.ts +98 -0
  51. package/dist/audit/verification.d.ts.map +1 -0
  52. package/dist/audit/verification.js +11 -0
  53. package/dist/audit/verification.js.map +1 -0
  54. package/dist/audit/verify/component.d.ts +68 -0
  55. package/dist/audit/verify/component.d.ts.map +1 -0
  56. package/dist/audit/verify/component.js +500 -0
  57. package/dist/audit/verify/component.js.map +1 -0
  58. package/dist/audit/verify/declarations.d.ts +58 -0
  59. package/dist/audit/verify/declarations.d.ts.map +1 -0
  60. package/dist/audit/verify/declarations.js +227 -0
  61. package/dist/audit/verify/declarations.js.map +1 -0
  62. package/dist/audit/verify/grammar.d.ts +12 -0
  63. package/dist/audit/verify/grammar.d.ts.map +1 -0
  64. package/dist/audit/verify/grammar.js +57 -0
  65. package/dist/audit/verify/grammar.js.map +1 -0
  66. package/dist/audit/verify/index.d.ts +12 -0
  67. package/dist/audit/verify/index.d.ts.map +1 -0
  68. package/dist/audit/verify/index.js +31 -0
  69. package/dist/audit/verify/index.js.map +1 -0
  70. package/dist/audit/verify/parser.d.ts +19 -0
  71. package/dist/audit/verify/parser.d.ts.map +1 -0
  72. package/dist/audit/verify/parser.js +122 -0
  73. package/dist/audit/verify/parser.js.map +1 -0
  74. package/dist/audit/verify/span.d.ts +49 -0
  75. package/dist/audit/verify/span.d.ts.map +1 -0
  76. package/dist/audit/verify/span.js +377 -0
  77. package/dist/audit/verify/span.js.map +1 -0
  78. package/dist/graphify/anchor.d.ts +45 -0
  79. package/dist/graphify/anchor.d.ts.map +1 -0
  80. package/dist/graphify/anchor.js +179 -0
  81. package/dist/graphify/anchor.js.map +1 -0
  82. package/dist/graphify/consolidated.d.ts +259 -0
  83. package/dist/graphify/consolidated.d.ts.map +1 -0
  84. package/dist/graphify/consolidated.js +12 -0
  85. package/dist/graphify/consolidated.js.map +1 -0
  86. package/dist/graphify/construct.d.ts +41 -0
  87. package/dist/graphify/construct.d.ts.map +1 -0
  88. package/dist/graphify/construct.js +106 -0
  89. package/dist/graphify/construct.js.map +1 -0
  90. package/dist/graphify/ids.d.ts +19 -0
  91. package/dist/graphify/ids.d.ts.map +1 -0
  92. package/dist/graphify/ids.js +53 -0
  93. package/dist/graphify/ids.js.map +1 -0
  94. package/dist/graphify/index.d.ts +16 -0
  95. package/dist/graphify/index.d.ts.map +1 -0
  96. package/dist/graphify/index.js +32 -0
  97. package/dist/graphify/index.js.map +1 -0
  98. package/dist/graphify/resolve.d.ts +48 -0
  99. package/dist/graphify/resolve.d.ts.map +1 -0
  100. package/dist/graphify/resolve.js +89 -0
  101. package/dist/graphify/resolve.js.map +1 -0
  102. package/dist/graphify/signature.d.ts +87 -0
  103. package/dist/graphify/signature.d.ts.map +1 -0
  104. package/dist/graphify/signature.js +282 -0
  105. package/dist/graphify/signature.js.map +1 -0
  106. package/dist/graphify/types.d.ts +141 -0
  107. package/dist/graphify/types.d.ts.map +1 -0
  108. package/dist/graphify/types.js +9 -0
  109. package/dist/graphify/types.js.map +1 -0
  110. package/dist/index.d.ts +3 -1
  111. package/dist/index.d.ts.map +1 -1
  112. package/dist/index.js +6 -4
  113. package/dist/index.js.map +1 -1
  114. package/dist/node.d.ts +2 -0
  115. package/dist/node.d.ts.map +1 -1
  116. package/dist/node.js +3 -1
  117. package/dist/node.js.map +1 -1
  118. package/dist/storage/topic-share.d.ts +57 -0
  119. package/dist/storage/topic-share.d.ts.map +1 -0
  120. package/dist/storage/topic-share.js +55 -0
  121. package/dist/storage/topic-share.js.map +1 -0
  122. package/package.json +16 -2
  123. package/src/audit/boundary.ts +447 -0
  124. package/src/audit/c4.ts +70 -0
  125. package/src/audit/engine.ts +1058 -0
  126. package/src/audit/fixes.ts +192 -0
  127. package/src/audit/hash.ts +58 -0
  128. package/src/audit/index.ts +33 -8
  129. package/src/audit/local-graphify.test.ts +163 -0
  130. package/src/audit/local-graphify.ts +354 -0
  131. package/src/audit/paths.ts +25 -0
  132. package/src/audit/pure.ts +91 -0
  133. package/src/audit/report-logic.test.ts +145 -0
  134. package/src/audit/report-logic.ts +245 -0
  135. package/src/audit/report.ts +203 -0
  136. package/src/audit/trail.ts +77 -0
  137. package/src/audit/verification.ts +104 -0
  138. package/src/audit/verify/component.ts +760 -0
  139. package/src/audit/verify/declarations.ts +284 -0
  140. package/src/audit/verify/grammar.ts +57 -0
  141. package/src/audit/verify/index.ts +41 -0
  142. package/src/audit/verify/parser.ts +124 -0
  143. package/src/audit/verify/span.ts +478 -0
  144. package/src/graphify/anchor.ts +206 -0
  145. package/src/graphify/consolidated.ts +298 -0
  146. package/src/graphify/construct.ts +153 -0
  147. package/src/graphify/ids.ts +48 -0
  148. package/src/graphify/index.ts +16 -0
  149. package/src/graphify/resolve.ts +115 -0
  150. package/src/graphify/signature.ts +354 -0
  151. package/src/graphify/types.ts +164 -0
  152. package/src/index.ts +5 -3
  153. package/src/node.ts +2 -0
  154. package/src/storage/topic-share.test.ts +71 -0
  155. package/src/storage/topic-share.ts +91 -0
@@ -0,0 +1,478 @@
1
+ /**
2
+ * Dry-run span derivability classifier — graphify anchor + tree-sitter parse.
3
+ *
4
+ * For every code component: resolve the graphify definition node, read the file
5
+ * at its `source_location` start line, parse with tree-sitter, and derive the
6
+ * declaration's end line. Then classify how *decidable* that derivation is —
7
+ * deterministic (a stored span re-hashes unchanged), trivial (all structural
8
+ * gates pass), ambiguous (candidates/gates disagree), or unknown (no anchor /
9
+ * grammar / parse).
10
+ *
11
+ * Read-only by design: this never writes a span.
12
+ */
13
+
14
+ import type { Tree } from 'web-tree-sitter'
15
+ import type { ComponentAnchorResult } from '../../graphify/anchor'
16
+ import { hashContentRange, parseSourceLocation } from '../hash'
17
+ import { grammarFile } from './grammar'
18
+ import { parseWith, sharedParserFor } from './parser'
19
+
20
+ /** `ts`/`tsx`/`js`/`py` — the dialect key used below. */
21
+ export function languageKey(file: string): string | null {
22
+ const wasm = grammarFile(file)
23
+ if (!wasm) return null
24
+ return wasm.replace('tree-sitter-', '').replace('.wasm', '')
25
+ }
26
+
27
+ // ---------------------------------------------------------------------------
28
+ // declaration kinds + kind→construct mapping
29
+ // ---------------------------------------------------------------------------
30
+
31
+ const TS_DECLARATIONS = new Set([
32
+ 'interface_declaration',
33
+ 'type_alias_declaration',
34
+ 'function_declaration',
35
+ 'generator_function_declaration',
36
+ 'class_declaration',
37
+ 'abstract_class_declaration',
38
+ 'method_definition',
39
+ 'enum_declaration',
40
+ 'lexical_declaration',
41
+ 'variable_declarator',
42
+ ])
43
+
44
+ const PY_DECLARATIONS = new Set([
45
+ 'function_definition',
46
+ 'class_definition',
47
+ 'decorated_definition',
48
+ 'assignment',
49
+ ])
50
+
51
+ const GO_DECLARATIONS = new Set([
52
+ 'function_declaration',
53
+ 'method_declaration',
54
+ 'type_declaration',
55
+ ])
56
+
57
+ function declarationKinds(key: string): Set<string> {
58
+ if (key === 'python') return PY_DECLARATIONS
59
+ if (key === 'go') return GO_DECLARATIONS
60
+ return TS_DECLARATIONS
61
+ }
62
+
63
+ /** Map a tree-sitter node type to the model construct vocabulary. */
64
+ function constructForNode(nodeType: string): string | null {
65
+ switch (nodeType) {
66
+ case 'interface_declaration':
67
+ return 'interface'
68
+ case 'type_alias_declaration':
69
+ return 'type_alias'
70
+ case 'class_declaration':
71
+ case 'abstract_class_declaration':
72
+ return 'class'
73
+ case 'method_definition':
74
+ case 'function_signature':
75
+ case 'abstract_method_signature':
76
+ case 'method_declaration':
77
+ return 'method'
78
+ case 'function_declaration':
79
+ case 'generator_function_declaration':
80
+ return 'function'
81
+ case 'enum_declaration':
82
+ return 'enum'
83
+ default:
84
+ return null // lexical/variable — could be store or function; not classifiable
85
+ }
86
+ }
87
+
88
+ /** True when the derived construct is compatible with the claimed one. */
89
+ function kindCompatible(
90
+ claimed: string | undefined,
91
+ derived: string | null,
92
+ ): boolean {
93
+ if (!derived) return true // variable/unknown node type — not a kind gate
94
+ if (!claimed || claimed === 'external') return true
95
+ if (derived === claimed) return true
96
+ // A store/function variable holding a class/function is not classifiable here.
97
+ if (derived === 'type_alias' && claimed === 'type') return true
98
+ return false
99
+ }
100
+
101
+ // ---------------------------------------------------------------------------
102
+ // derivation
103
+ // ---------------------------------------------------------------------------
104
+
105
+ export type SpanClass =
106
+ | 'deterministic'
107
+ | 'trivial'
108
+ | 'ambiguous'
109
+ | 'unknown'
110
+ | 'skipped'
111
+
112
+ export interface SpanDerivation {
113
+ class: SpanClass
114
+ language: string | null
115
+ graphifyStart: number | null
116
+ derivedEnd: number | null
117
+ declNodeType: string | null
118
+ declName: string | null
119
+ failedGates: string[]
120
+ evidence: string[]
121
+ }
122
+
123
+ interface Candidate {
124
+ type: string
125
+ end: number
126
+ name: string | null
127
+ hasError: boolean
128
+ hasBody: boolean
129
+ }
130
+
131
+ function nameOf(node: {
132
+ type: string
133
+ childForFieldName?: (f: string) => { text: string } | null
134
+ namedChildren: Array<{
135
+ type: string
136
+ text: string
137
+ childForFieldName?: (f: string) => { text: string } | null
138
+ }>
139
+ }): string | null {
140
+ const direct = node.childForFieldName?.('name')
141
+ if (direct?.text) return direct.text
142
+ if (node.type === 'lexical_declaration') {
143
+ const d = node.namedChildren.find((c) => c.type === 'variable_declarator')
144
+ return d?.childForFieldName?.('name')?.text ?? null
145
+ }
146
+ if (node.type === 'type_declaration') {
147
+ // Go: `type Name …` — the name lives on the nested type_spec.
148
+ const spec = node.namedChildren.find((c) => c.type === 'type_spec')
149
+ return spec?.childForFieldName?.('name')?.text ?? null
150
+ }
151
+ if (node.type === 'assignment') {
152
+ // Python: `NAME = …` — no name field; the left identifier is the name.
153
+ const left = node.namedChildren.find((c) => c.type === 'identifier')
154
+ return left?.text ?? null
155
+ }
156
+ if (node.type === 'decorated_definition') {
157
+ const d = node.namedChildren.find(
158
+ (c) => c.type === 'function_definition' || c.type === 'class_definition',
159
+ )
160
+ return d?.childForFieldName?.('name')?.text ?? null
161
+ }
162
+ return null
163
+ }
164
+
165
+ const BODY_TYPES = new Set([
166
+ 'statement_block',
167
+ 'class_body',
168
+ 'interface_body',
169
+ 'enum_body',
170
+ 'block',
171
+ ])
172
+
173
+ function hasBodyChild(node: { namedChildren: Array<{ type: string }> }): boolean {
174
+ return node.namedChildren.some((c) => BODY_TYPES.has(c.type))
175
+ }
176
+
177
+ function collectCandidates(
178
+ root: {
179
+ type: string
180
+ startPosition: { row: number }
181
+ endPosition: { row: number }
182
+ namedChildren: unknown[]
183
+ },
184
+ targetRow: number,
185
+ kinds: Set<string>,
186
+ out: Array<Record<string, unknown>> = [],
187
+ ): Array<Record<string, unknown>> {
188
+ const anyNode = root as unknown as {
189
+ type: string
190
+ startPosition: { row: number }
191
+ endPosition: { row: number }
192
+ namedChildren: Array<Record<string, unknown>>
193
+ childForFieldName?: (f: string) => { text: string } | null
194
+ hasError: boolean
195
+ }
196
+ if (anyNode.startPosition.row === targetRow && kinds.has(anyNode.type)) {
197
+ out.push(anyNode)
198
+ }
199
+ for (const c of anyNode.namedChildren) {
200
+ collectCandidates(c as never, targetRow, kinds, out)
201
+ }
202
+ return out
203
+ }
204
+
205
+ function normalizeCandidates(
206
+ raw: Array<Record<string, unknown>>,
207
+ ): Candidate[] {
208
+ const cands: Candidate[] = raw.map((n) => {
209
+ const node = n as unknown as {
210
+ type: string
211
+ endPosition: { row: number }
212
+ hasError: boolean
213
+ namedChildren: Array<{ type: string }>
214
+ childForFieldName?: (f: string) => { text: string } | null
215
+ }
216
+ return {
217
+ type: node.type,
218
+ end: node.endPosition.row + 1,
219
+ name: nameOf(node as never),
220
+ hasError: node.hasError,
221
+ hasBody: hasBodyChild(node),
222
+ }
223
+ })
224
+ // lexical_declaration duplicates its variable_declarator (same name + end).
225
+ const seen = new Set<string>()
226
+ const deduped: Candidate[] = []
227
+ for (const c of cands) {
228
+ const key = `${c.name ?? '?'}:${c.end}`
229
+ if (seen.has(key)) continue
230
+ seen.add(key)
231
+ deduped.push(c)
232
+ }
233
+ return deduped
234
+ }
235
+
236
+ export const GATE_LABELS: Record<string, string> = {
237
+ 'no-anchor': 'graphify could not anchor file+symbol',
238
+ 'no-grammar': 'no tree-sitter grammar for this extension',
239
+ 'no-candidate': 'no declaration node starts on the graphify line',
240
+ 'multiple-candidates': 'more than one declaration starts on the line',
241
+ 'name-mismatch': 'declaration name does not match the claimed symbol',
242
+ 'kind-mismatch': 'declaration kind does not match the claimed construct',
243
+ 'parse-error': 'tree-sitter reported a syntax error in the declaration',
244
+ 'file-unreadable': 'file could not be read from the checkout',
245
+ }
246
+
247
+ /** Per-audit-pass parse-tree cache, keyed by repo file path. */
248
+ export type SpanTreeCache = Map<string, Tree>
249
+
250
+ export interface DeriveInput {
251
+ content: string
252
+ file: string
253
+ symbol?: string
254
+ construct?: string
255
+ anchor: ComponentAnchorResult
256
+ storedSpan?: { startLine: number; endLine: number; contentHash: string }
257
+ /** Shared across components of the same pass (parse once per file). */
258
+ treeCache?: SpanTreeCache
259
+ }
260
+
261
+ /**
262
+ * Classify one declaration span derivation. Pure given `content` + anchor.
263
+ */
264
+ async function deriveSpanUsingCache(
265
+ input: DeriveInput,
266
+ ): Promise<SpanDerivation> {
267
+ const evidence: string[] = []
268
+ const failed: string[] = []
269
+
270
+ const graphifyStart =
271
+ input.anchor.resolution === 'exact' && input.anchor.node
272
+ ? parseSourceLocation(
273
+ typeof input.anchor.node.source_location === 'string'
274
+ ? input.anchor.node.source_location
275
+ : undefined,
276
+ )
277
+ : null
278
+ evidence.push(`anchor=${input.anchor.resolution}`)
279
+ if (graphifyStart == null) {
280
+ failed.push('no-anchor')
281
+ return {
282
+ class: 'unknown',
283
+ language: languageKey(input.file),
284
+ graphifyStart: null,
285
+ derivedEnd: null,
286
+ declNodeType: null,
287
+ declName: null,
288
+ failedGates: failed,
289
+ evidence,
290
+ }
291
+ }
292
+ evidence.push(`graphify L${graphifyStart}`)
293
+
294
+ if (!grammarFile(input.file)) {
295
+ failed.push('no-grammar')
296
+ return {
297
+ class: 'unknown',
298
+ language: null,
299
+ graphifyStart,
300
+ derivedEnd: null,
301
+ declNodeType: null,
302
+ declName: null,
303
+ failedGates: failed,
304
+ evidence,
305
+ }
306
+ }
307
+
308
+ // Parse once per file per audit pass: reuse a cached tree when the caller
309
+ // shares one (many components live in the same file). Use the shared parser
310
+ // and serialized parse queue: constructing a fresh WASM Parser for every file
311
+ // churns the heap and can abort on larger audits.
312
+ let tree = input.treeCache?.get(input.file) ?? null
313
+ if (!tree) {
314
+ const parser = await sharedParserFor(input.file)
315
+ if (!parser) {
316
+ failed.push('no-grammar')
317
+ return {
318
+ class: 'unknown',
319
+ language: null,
320
+ graphifyStart,
321
+ derivedEnd: null,
322
+ declNodeType: null,
323
+ declName: null,
324
+ failedGates: failed,
325
+ evidence,
326
+ }
327
+ }
328
+ tree = await parseWith(parser, input.content)
329
+ if (tree) input.treeCache?.set(input.file, tree)
330
+ }
331
+ if (!tree) {
332
+ failed.push('parse-error')
333
+ return {
334
+ class: 'unknown',
335
+ language: languageKey(input.file),
336
+ graphifyStart,
337
+ derivedEnd: null,
338
+ declNodeType: null,
339
+ declName: null,
340
+ failedGates: failed,
341
+ evidence,
342
+ }
343
+ }
344
+ const key = languageKey(input.file) ?? 'typescript'
345
+ const kinds = declarationKinds(key)
346
+
347
+ // Candidates at the graphify line; if none, look a few lines forward
348
+ // (graphify may point at a leading decorator or doc comment).
349
+ let row = graphifyStart - 1
350
+ let candidates = normalizeCandidates(
351
+ collectCandidates(tree.rootNode as never, row, kinds),
352
+ )
353
+ let offset = 0
354
+ if (candidates.length === 0) {
355
+ for (let probe = 1; probe <= 5; probe++) {
356
+ candidates = normalizeCandidates(
357
+ collectCandidates(tree.rootNode as never, row + probe, kinds),
358
+ )
359
+ if (candidates.length > 0) {
360
+ offset = probe
361
+ break
362
+ }
363
+ }
364
+ if (offset > 0) evidence.push(`anchor offset +${offset} line(s)`)
365
+ }
366
+
367
+ if (candidates.length === 0) {
368
+ failed.push('no-candidate')
369
+ return {
370
+ class: 'unknown',
371
+ language: key,
372
+ graphifyStart,
373
+ derivedEnd: null,
374
+ declNodeType: null,
375
+ declName: null,
376
+ failedGates: failed,
377
+ evidence,
378
+ }
379
+ }
380
+ if (candidates.length > 1) {
381
+ failed.push('multiple-candidates')
382
+ const ends = new Set(candidates.map((c) => c.end))
383
+ if (ends.size === 1) evidence.push(`${candidates.length} nodes, one end line`)
384
+ return {
385
+ class: 'ambiguous',
386
+ language: key,
387
+ graphifyStart,
388
+ derivedEnd: null,
389
+ declNodeType: candidates[0]!.type,
390
+ declName: candidates[0]!.name,
391
+ failedGates: failed,
392
+ evidence,
393
+ }
394
+ }
395
+
396
+ const cand = candidates[0]!
397
+ evidence.push(`node=${cand.type} end=L${cand.end}`)
398
+
399
+ // name gate
400
+ if (input.symbol && cand.name) {
401
+ const last = input.symbol.includes('.')
402
+ ? (input.symbol.split('.').pop() ?? input.symbol)
403
+ : input.symbol
404
+ const matches = cand.name === input.symbol || cand.name === last
405
+ if (!matches) {
406
+ failed.push('name-mismatch')
407
+ evidence.push(`node name=${cand.name} ≠ symbol=${input.symbol}`)
408
+ } else {
409
+ evidence.push(`name=${cand.name} matches`)
410
+ }
411
+ } else if (input.symbol && !cand.name) {
412
+ evidence.push('declaration has no name field')
413
+ }
414
+
415
+ // kind gate
416
+ const derivedConstruct = constructForNode(cand.type)
417
+ if (!kindCompatible(input.construct, derivedConstruct)) {
418
+ failed.push('kind-mismatch')
419
+ evidence.push(`kind=${derivedConstruct} ≠ claim=${input.construct}`)
420
+ }
421
+
422
+ // parse gate
423
+ if (cand.hasError) {
424
+ failed.push('parse-error')
425
+ }
426
+
427
+ const derivedEnd = cand.end
428
+
429
+ // deterministic: a stored span re-hashes unchanged at the derived range.
430
+ if (
431
+ input.storedSpan &&
432
+ hashContentRange(input.content, graphifyStart, derivedEnd) ===
433
+ input.storedSpan.contentHash
434
+ ) {
435
+ evidence.push('re-hashes to stored contentHash')
436
+ return {
437
+ class: 'deterministic',
438
+ language: key,
439
+ graphifyStart,
440
+ derivedEnd,
441
+ declNodeType: cand.type,
442
+ declName: cand.name,
443
+ failedGates: [],
444
+ evidence,
445
+ }
446
+ }
447
+
448
+ const class_: SpanClass = failed.length === 0 ? 'trivial' : 'ambiguous'
449
+ if (class_ === 'trivial' && !cand.hasBody)
450
+ evidence.push('bodyless (signature only)')
451
+ return {
452
+ class: class_,
453
+ language: key,
454
+ graphifyStart,
455
+ derivedEnd,
456
+ declNodeType: cand.type,
457
+ declName: cand.name,
458
+ failedGates: failed,
459
+ evidence,
460
+ }
461
+ }
462
+
463
+ /** Release parser-owned trees when a caller did not provide a pass cache. */
464
+ export function disposeSpanTreeCache(treeCache: SpanTreeCache): void {
465
+ for (const tree of treeCache.values()) tree.delete()
466
+ treeCache.clear()
467
+ }
468
+
469
+ /** Classify one declaration and dispose its temporary WASM tree when unshared. */
470
+ export async function deriveSpan(input: DeriveInput): Promise<SpanDerivation> {
471
+ if (input.treeCache) return deriveSpanUsingCache(input)
472
+ const treeCache: SpanTreeCache = new Map()
473
+ try {
474
+ return await deriveSpanUsingCache({ ...input, treeCache })
475
+ } finally {
476
+ disposeSpanTreeCache(treeCache)
477
+ }
478
+ }
@@ -0,0 +1,206 @@
1
+ /**
2
+ * Resolve a subsystem component (file + symbol) to a graphify definition node.
3
+ *
4
+ * This is component *anchoring*, not type-ref stub rewiring (`resolve.ts`).
5
+ * Conservative: never bind via corpus-wide same-name alone.
6
+ */
7
+
8
+ import type { GraphifyNode } from './types';
9
+ import type { GraphifyAnchorResolution } from './consolidated';
10
+ import { normalizeGraphifyLabel } from './resolve';
11
+ import {
12
+ graphifyFileStem,
13
+ makeGraphifyId,
14
+ normalizeSourcePath,
15
+ } from './ids';
16
+
17
+ export interface ComponentAnchorInput {
18
+ file?: string;
19
+ symbol?: string;
20
+ kind?: string;
21
+ purl?: string;
22
+ }
23
+
24
+ export interface ComponentAnchorResult {
25
+ resolution: GraphifyAnchorResolution;
26
+ node: GraphifyNode | null;
27
+ candidates: GraphifyNode[];
28
+ /** make_id strings attempted on the fast path. */
29
+ triedIds: string[];
30
+ }
31
+
32
+ const FILE_SUFFIX_RE =
33
+ /\.(py|js|jsx|ts|tsx|mjs|cjs|java|go|rs|rb|php|cs|cpp|cc|c|h|hpp|pas|pp|dpr|swift|kt|scala|dart|lua|pl|pm|ex|exs|zig|vue|svelte)$/i;
34
+
35
+ function isDefinition(node: GraphifyNode): boolean {
36
+ if (node.file_type !== 'code') return false;
37
+ const file = typeof node.source_file === 'string' ? node.source_file : '';
38
+ if (!file) return false;
39
+ const label = typeof node.label === 'string' ? node.label.trim() : '';
40
+ return !!label && !FILE_SUFFIX_RE.test(label);
41
+ }
42
+
43
+ /** Label forms that might match a subsystem symbol on a graphify node. */
44
+ export function symbolLabelVariants(symbol: string): string[] {
45
+ const raw = symbol.trim();
46
+ if (!raw) return [];
47
+ const last = raw.includes('.') ? (raw.split('.').pop() ?? raw) : raw;
48
+ const variants = new Set<string>([
49
+ raw,
50
+ last,
51
+ `${raw}()`,
52
+ `${last}()`,
53
+ `.${last}()`,
54
+ `.${last}`,
55
+ ]);
56
+ return [...variants];
57
+ }
58
+
59
+ function labelMatchesSymbol(label: string, symbol: string): boolean {
60
+ const variants = symbolLabelVariants(symbol);
61
+ const trimmed = label.trim();
62
+ if (variants.includes(trimmed)) return true;
63
+ const foldedLabel = normalizeGraphifyLabel(trimmed);
64
+ return variants.some((v) => normalizeGraphifyLabel(v) === foldedLabel);
65
+ }
66
+
67
+ function candidateIdsFor(file: string, symbol: string): string[] {
68
+ const stem = graphifyFileStem(file);
69
+ if (!stem) return [];
70
+ const parts = symbol.split('.').map((p) => p.trim()).filter(Boolean);
71
+ const ids = new Set<string>();
72
+ ids.add(makeGraphifyId(stem, symbol));
73
+ if (parts.length > 0) ids.add(makeGraphifyId(stem, ...parts));
74
+ if (parts.length === 2) {
75
+ // Class method: make_id(class_id, method) ≈ make_id(stem, Class, method)
76
+ ids.add(makeGraphifyId(stem, parts[0]!, parts[1]!));
77
+ }
78
+ return [...ids];
79
+ }
80
+
81
+ /**
82
+ * Anchor a subsystem component onto a graphify definition node.
83
+ */
84
+ export function resolveComponentAnchor(
85
+ nodes: readonly GraphifyNode[],
86
+ input: ComponentAnchorInput,
87
+ ): ComponentAnchorResult {
88
+ const file = input.file?.trim() ? normalizeSourcePath(input.file) : '';
89
+ const symbol = input.symbol?.trim() ?? '';
90
+ if (!file || !symbol) {
91
+ return { resolution: 'missing', node: null, candidates: [], triedIds: [] };
92
+ }
93
+
94
+ const byId = new Map<string, GraphifyNode>();
95
+ const inFile: GraphifyNode[] = [];
96
+ for (const node of nodes) {
97
+ byId.set(String(node.id), node);
98
+ if (!isDefinition(node)) continue;
99
+ const sf = normalizeSourcePath(String(node.source_file ?? ''));
100
+ if (sf === file) inFile.push(node);
101
+ }
102
+
103
+ const triedIds = candidateIdsFor(file, symbol);
104
+ const idHits: GraphifyNode[] = [];
105
+ for (const id of triedIds) {
106
+ const hit = byId.get(id);
107
+ if (!hit || !isDefinition(hit)) continue;
108
+ const sf = normalizeSourcePath(String(hit.source_file ?? ''));
109
+ if (sf === file) idHits.push(hit);
110
+ }
111
+ const uniqueIdHits = [...new Map(idHits.map((n) => [String(n.id), n])).values()];
112
+ if (uniqueIdHits.length === 1) {
113
+ return {
114
+ resolution: 'exact',
115
+ node: uniqueIdHits[0]!,
116
+ candidates: [],
117
+ triedIds,
118
+ };
119
+ }
120
+ if (uniqueIdHits.length > 1) {
121
+ return {
122
+ resolution: 'ambiguous',
123
+ node: null,
124
+ candidates: uniqueIdHits,
125
+ triedIds,
126
+ };
127
+ }
128
+
129
+ if (inFile.length === 0) {
130
+ return { resolution: 'missing', node: null, candidates: [], triedIds };
131
+ }
132
+
133
+ const labelHits = inFile.filter((n) =>
134
+ labelMatchesSymbol(String(n.label ?? ''), symbol),
135
+ );
136
+ if (labelHits.length === 1) {
137
+ return {
138
+ resolution: 'exact',
139
+ node: labelHits[0]!,
140
+ candidates: [],
141
+ triedIds,
142
+ };
143
+ }
144
+ if (labelHits.length > 1) {
145
+ return {
146
+ resolution: 'ambiguous',
147
+ node: null,
148
+ candidates: labelHits,
149
+ triedIds,
150
+ };
151
+ }
152
+
153
+ // File has code nodes but none matched the symbol.
154
+ return {
155
+ resolution: 'file-only',
156
+ node: null,
157
+ candidates: inFile.slice(0, 8),
158
+ triedIds,
159
+ };
160
+ }
161
+
162
+ export type UniqueDefinitionBySymbolResult =
163
+ | { status: 'unique'; node: GraphifyNode }
164
+ | { status: 'ambiguous'; candidates: GraphifyNode[] }
165
+ | { status: 'none' };
166
+
167
+ /**
168
+ * Corpus-wide definition lookup by symbol label only (no claimed file).
169
+ * Used when the model’s file path is missing and we want a deterministic
170
+ * relocate if exactly one defining file still declares the symbol.
171
+ *
172
+ * Unique means a single `source_file` among matching definition nodes.
173
+ */
174
+ export function findUniqueDefinitionBySymbol(
175
+ nodes: readonly GraphifyNode[],
176
+ symbol: string,
177
+ ): UniqueDefinitionBySymbolResult {
178
+ const trimmed = symbol.trim();
179
+ if (!trimmed) return { status: 'none' };
180
+
181
+ const hits: GraphifyNode[] = [];
182
+ for (const node of nodes) {
183
+ if (!isDefinition(node)) continue;
184
+ if (!labelMatchesSymbol(String(node.label ?? ''), trimmed)) continue;
185
+ hits.push(node);
186
+ }
187
+ if (hits.length === 0) return { status: 'none' };
188
+
189
+ const byFile = new Map<string, GraphifyNode[]>();
190
+ for (const n of hits) {
191
+ const sf = normalizeSourcePath(String(n.source_file ?? ''));
192
+ if (!sf) continue;
193
+ const list = byFile.get(sf) ?? [];
194
+ list.push(n);
195
+ byFile.set(sf, list);
196
+ }
197
+ if (byFile.size === 0) return { status: 'none' };
198
+ if (byFile.size > 1) {
199
+ return {
200
+ status: 'ambiguous',
201
+ candidates: hits.slice(0, 12),
202
+ };
203
+ }
204
+ const only = [...byFile.values()][0]!;
205
+ return { status: 'unique', node: only[0]! };
206
+ }