@denizokcu/haze 1.7.11 → 1.7.12

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 (80) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +113 -97
  3. package/assets/graph-grammars/NOTICE.md +21 -0
  4. package/assets/graph-grammars/tree-sitter-javascript.wasm +0 -0
  5. package/assets/graph-grammars/tree-sitter-tsx.wasm +0 -0
  6. package/assets/graph-grammars/tree-sitter-typescript.wasm +0 -0
  7. package/assets/graph-grammars/web-tree-sitter.cjs +4116 -0
  8. package/assets/graph-grammars/web-tree-sitter.cjs.map +7 -0
  9. package/assets/graph-grammars/web-tree-sitter.js +4056 -0
  10. package/assets/graph-grammars/web-tree-sitter.js.map +7 -0
  11. package/assets/graph-grammars/web-tree-sitter.wasm +0 -0
  12. package/assets/graph-grammars/web-tree-sitter.wasm.map +55 -0
  13. package/dist/buildInfo.json +3 -3
  14. package/dist/cli/chat/inputSuggestions.js +1 -0
  15. package/dist/cli/chat/sessionLifecycle.js +2 -1
  16. package/dist/cli/chat/sessionRecorder.js +4 -1
  17. package/dist/cli/chat/startupSequence.d.ts +2 -0
  18. package/dist/cli/chat/startupSequence.js +6 -0
  19. package/dist/cli/commands/chat.js +5 -2
  20. package/dist/cli/commands/commandHelp.js +4 -1
  21. package/dist/cli/commands/commands.js +2 -0
  22. package/dist/cli/commands/formatters.js +28 -0
  23. package/dist/cli/commands/graphCommand.d.ts +2 -0
  24. package/dist/cli/commands/graphCommand.js +60 -0
  25. package/dist/cli/commands/initCommand.js +14 -0
  26. package/dist/cli/commands/streaming/agentAttempt.js +11 -1
  27. package/dist/cli/commands/streaming/attemptOutcome.js +1 -1
  28. package/dist/cli/commands/streaming/attemptSetup.d.ts +3 -0
  29. package/dist/cli/commands/streaming/attemptSetup.js +8 -3
  30. package/dist/cli/commands/streaming/goalSupervisor.js +5 -3
  31. package/dist/cli/commands/streaming/prepareStep.js +1 -0
  32. package/dist/cli/commands/streaming/streamLoop.d.ts +2 -0
  33. package/dist/cli/commands/streaming/streamLoop.js +3 -0
  34. package/dist/cli/commands/streaming/toolPartHandlers.js +7 -1
  35. package/dist/cli/commands/streaming.js +5 -0
  36. package/dist/core/agent/compaction.d.ts +1 -0
  37. package/dist/core/agent/compaction.js +3 -0
  38. package/dist/core/graph/analyze.d.ts +61 -0
  39. package/dist/core/graph/analyze.js +274 -0
  40. package/dist/core/graph/buildGraph.d.ts +44 -0
  41. package/dist/core/graph/buildGraph.js +290 -0
  42. package/dist/core/graph/digest.d.ts +2 -0
  43. package/dist/core/graph/digest.js +40 -0
  44. package/dist/core/graph/extract.d.ts +58 -0
  45. package/dist/core/graph/extract.js +394 -0
  46. package/dist/core/graph/model.d.ts +63 -0
  47. package/dist/core/graph/model.js +96 -0
  48. package/dist/core/graph/query.d.ts +69 -0
  49. package/dist/core/graph/query.js +391 -0
  50. package/dist/core/graph/store.d.ts +64 -0
  51. package/dist/core/graph/store.js +171 -0
  52. package/dist/core/process/runBoundedProcess.js +12 -6
  53. package/dist/core/safety/untrustedEnvelopes.d.ts +6 -0
  54. package/dist/core/safety/untrustedEnvelopes.js +17 -2
  55. package/dist/core/subagent/executionProfiles.js +4 -4
  56. package/dist/core/tasks/taskStorage.js +11 -1
  57. package/dist/core/validation/outputParser.js +16 -8
  58. package/dist/llm/hazeTools.d.ts +2 -12426
  59. package/dist/llm/hazeTools.js +2 -0
  60. package/dist/llm/lspTools.d.ts +3 -12622
  61. package/dist/llm/requestContext.d.ts +3 -0
  62. package/dist/llm/requestContext.js +13 -4
  63. package/dist/llm/subagentRunner.d.ts +2 -308
  64. package/dist/llm/systemPrompt.js +7 -4
  65. package/dist/llm/toolResultTypes.d.ts +1 -1
  66. package/dist/llm/tools/fetchTool.d.ts +2 -1221
  67. package/dist/llm/tools/fileTools.d.ts +2 -7768
  68. package/dist/llm/tools/graphAdvisory.d.ts +22 -0
  69. package/dist/llm/tools/graphAdvisory.js +68 -0
  70. package/dist/llm/tools/graphTools.d.ts +13 -0
  71. package/dist/llm/tools/graphTools.js +195 -0
  72. package/dist/llm/tools/processTool.d.ts +2 -1081
  73. package/dist/llm/tools/shellTool.d.ts +2 -1513
  74. package/dist/llm/tools/storedOutputTool.d.ts +2 -355
  75. package/dist/llm/tools/taskTool.d.ts +2 -489
  76. package/dist/llm/tools/toolContext.js +24 -9
  77. package/dist/llm/tools/toolContextState.d.ts +3 -0
  78. package/dist/llm/tools/toolContextState.js +2 -1
  79. package/dist/skills/skillTools.js +4 -1
  80. package/package.json +18 -15
@@ -0,0 +1,58 @@
1
+ import { type GraphNodeKind } from './model.js';
2
+ export declare const EXTRACTOR_VERSION = 4;
3
+ /** Largest source file parsed; bigger files are reported as skipped instead. */
4
+ export declare const MAX_SOURCE_BYTES: number;
5
+ export declare function isGraphSupportedExtension(extension: string): boolean;
6
+ export interface ExtractedSymbol {
7
+ id: string;
8
+ name: string;
9
+ kind: GraphNodeKind;
10
+ line: number;
11
+ /** Enclosing class name for methods/fields; absent on top-level symbols. */
12
+ owner?: string;
13
+ }
14
+ export interface ImportedBinding {
15
+ /** Name exported by the source module. */
16
+ importedName: string;
17
+ /** Local name after aliasing (`as`); equals importedName when not aliased. */
18
+ localName: string;
19
+ }
20
+ export interface FileImport {
21
+ /** Raw module specifier as written (./foo.js, ../bar, pkg). */
22
+ specifier: string;
23
+ line: number;
24
+ kind: 'import' | 'export-from' | 'require';
25
+ defaultImport?: string;
26
+ namespaceImport?: string;
27
+ bindings: ImportedBinding[];
28
+ }
29
+ export interface CallSite {
30
+ /** Called identifier, or property name for `this.method()` member calls. */
31
+ name: string;
32
+ line: number;
33
+ /** True for `this.x()` calls; resolvable only against the enclosing class. */
34
+ thisCall?: boolean;
35
+ }
36
+ export interface HeritageEntry {
37
+ /** Superclass identifier as written. */
38
+ name: string;
39
+ line: number;
40
+ }
41
+ export interface FileExtraction {
42
+ version: number;
43
+ file: string;
44
+ symbols: ExtractedSymbol[];
45
+ imports: FileImport[];
46
+ calls: CallSite[];
47
+ heritage: HeritageEntry[];
48
+ /** Names exported for other files (declaration name or explicit export list). */
49
+ exports: string[];
50
+ }
51
+ /**
52
+ * Extract one file's structure. `file` is the workspace-relative path used for
53
+ * node ids; `content` is the UTF-8 source. Throws on parser/grammar problems;
54
+ * syntax errors inside the source degrade gracefully (tree-sitter keeps
55
+ * parsing; partial results are still honest structure).
56
+ */
57
+ export declare function extractFile(file: string, content: string): Promise<FileExtraction>;
58
+ export declare function contentHash(content: string): string;
@@ -0,0 +1,394 @@
1
+ /**
2
+ * Deterministic per-file AST extraction via tree-sitter WASM (core runtime and
3
+ * js/ts/tsx/jsx grammars vendored under `assets/graph-grammars/`).
4
+ *
5
+ * Extraction is pure: one source file in, one {@link FileExtraction} out, no
6
+ * workspace access — so results are content-hash cacheable. Cross-file
7
+ * resolution (import targets, call/heritage endpoints) deliberately lives in
8
+ * `buildGraph.ts`, which sees the whole corpus.
9
+ *
10
+ * Bump {@link EXTRACTOR_VERSION} whenever node/edge derivation logic changes;
11
+ * the cache and the persisted graph both key off it.
12
+ */
13
+ import fs from 'node:fs';
14
+ import path from 'node:path';
15
+ import { fileURLToPath } from 'node:url';
16
+ import { createHash } from 'node:crypto';
17
+ import { Language, Parser } from 'web-tree-sitter';
18
+ import { symbolNodeId } from './model.js';
19
+ export const EXTRACTOR_VERSION = 4;
20
+ /** Largest source file parsed; bigger files are reported as skipped instead. */
21
+ export const MAX_SOURCE_BYTES = 1024 * 1024;
22
+ /** The 0.27.x runtime exposes `Language` as a named export with a static `.load()`.
23
+ * 0.23.x attached it as `Parser.Language` post-init — no longer needed. */
24
+ function languageStatic() {
25
+ return Language;
26
+ }
27
+ let grammarsDir;
28
+ /**
29
+ * Resolve the vendored grammar directory. Compiled output and source agree on
30
+ * depth (`<root>/dist/core/graph` and `<root>/src/core/graph` are both three
31
+ * levels below the package root), so one relative walk covers dev, tests, and
32
+ * the published package.
33
+ */
34
+ function resolveGrammarsDir() {
35
+ if (grammarsDir)
36
+ return grammarsDir;
37
+ const here = path.dirname(fileURLToPath(import.meta.url));
38
+ const vendored = path.resolve(here, '../../../assets/graph-grammars');
39
+ grammarsDir = fs.existsSync(path.join(vendored, 'tree-sitter-typescript.wasm'))
40
+ ? vendored
41
+ : path.dirname(require.resolve('web-tree-sitter/tree-sitter.wasm'));
42
+ return grammarsDir;
43
+ }
44
+ let parserInit;
45
+ const loadedLanguages = new Map();
46
+ const parsers = new Map();
47
+ const GRAMMAR_BY_EXTENSION = {
48
+ '.ts': 'tree-sitter-typescript.wasm',
49
+ '.mts': 'tree-sitter-typescript.wasm',
50
+ '.cts': 'tree-sitter-typescript.wasm',
51
+ '.tsx': 'tree-sitter-tsx.wasm',
52
+ '.js': 'tree-sitter-javascript.wasm',
53
+ '.jsx': 'tree-sitter-tsx.wasm',
54
+ '.mjs': 'tree-sitter-javascript.wasm',
55
+ '.cjs': 'tree-sitter-javascript.wasm',
56
+ };
57
+ export function isGraphSupportedExtension(extension) {
58
+ return extension in GRAMMAR_BY_EXTENSION;
59
+ }
60
+ async function parserFor(extension) {
61
+ if (!(extension in GRAMMAR_BY_EXTENSION))
62
+ throw new Error(`No graph grammar for ${extension}`);
63
+ let parser = parsers.get(extension);
64
+ if (!parser) {
65
+ parser = (async () => {
66
+ parserInit ??= (async () => {
67
+ const dir = resolveGrammarsDir();
68
+ const coreWasm = path.join(dir, 'web-tree-sitter.wasm');
69
+ await Parser.init(fs.existsSync(coreWasm) ? { locateFile: () => coreWasm } : undefined);
70
+ })();
71
+ await parserInit;
72
+ const grammar = GRAMMAR_BY_EXTENSION[extension];
73
+ const wasmPath = path.join(resolveGrammarsDir(), grammar);
74
+ if (!fs.existsSync(wasmPath))
75
+ throw new Error(`Grammar ${grammar} is not available at ${wasmPath}`);
76
+ let language = loadedLanguages.get(grammar);
77
+ if (!language) {
78
+ language = languageStatic().load(wasmPath);
79
+ loadedLanguages.set(grammar, language);
80
+ }
81
+ const parserInstance = new Parser();
82
+ parserInstance.setLanguage(await language);
83
+ return parserInstance;
84
+ })();
85
+ parsers.set(extension, parser);
86
+ }
87
+ return parser;
88
+ }
89
+ // ---------------------------------------------------------------------------
90
+ // Tree walks
91
+ // ---------------------------------------------------------------------------
92
+ const KIND_BY_NODE_TYPE = {
93
+ function_declaration: 'function',
94
+ generator_function_declaration: 'function',
95
+ function_signature: 'function',
96
+ method_definition: 'method',
97
+ method_signature: 'method',
98
+ abstract_method_signature: 'method',
99
+ class_declaration: 'class',
100
+ abstract_class_declaration: 'class',
101
+ interface_declaration: 'type',
102
+ type_alias_declaration: 'type',
103
+ enum_declaration: 'type',
104
+ };
105
+ function identifierText(node) {
106
+ return node && (node.type === 'identifier' || node.type === 'type_identifier') ? node.text : undefined;
107
+ }
108
+ /** Method/property names arrive as `property_identifier`, declarations as identifier/type_identifier. */
109
+ function definitionNameText(node) {
110
+ return node && (node.type === 'identifier' || node.type === 'type_identifier' || node.type === 'property_identifier') ? node.text : undefined;
111
+ }
112
+ function propertyName(nameNode) {
113
+ if (nameNode.type === 'identifier' || nameNode.type === 'property_identifier')
114
+ return nameNode.text;
115
+ if (nameNode.type === 'computed_property_name') {
116
+ const inner = nameNode.namedChildren[0];
117
+ return inner?.text || undefined;
118
+ }
119
+ return undefined;
120
+ }
121
+ /** Best-effort enclosing class name by walking parent links. */
122
+ function enclosingClassName(node) {
123
+ let current = node;
124
+ while (current) {
125
+ if (current.type === 'class_declaration' || current.type === 'abstract_class_declaration' || current.type === 'class_expression') {
126
+ const name = identifierText(current.childForFieldName('name'));
127
+ if (name)
128
+ return name;
129
+ }
130
+ current = current.parent ?? null;
131
+ }
132
+ return undefined;
133
+ }
134
+ /**
135
+ * Declarators whose value is a non-trivial expression become symbols:
136
+ * functions for arrow/function values (callable), fields for object/array/
137
+ * call/new values (`export const hazeTools = {...}` names a real API
138
+ * surface). Primitive literals and plain identifiers stay out.
139
+ *
140
+ * Node wrappers are recreated per access, so the name child is identified by
141
+ * its stable `.id`, never by reference equality.
142
+ */
143
+ const VALUED_DECLARATOR_TYPES = new Set(['arrow_function', 'function_expression', 'object', 'array', 'new_expression', 'call_expression']);
144
+ function declaratorValueKind(declarator) {
145
+ const name = declarator.childForFieldName('name');
146
+ const nameId = name?.id;
147
+ for (const child of declarator.namedChildren) {
148
+ if (child.id === nameId)
149
+ continue;
150
+ // A type annotation (`const x: SomeType = {...}`) sits between the name
151
+ // and the value; skip it so typed declarators still yield their symbol.
152
+ if (child.type === 'type_annotation')
153
+ continue;
154
+ if (child.type === 'arrow_function' || child.type === 'function_expression')
155
+ return 'function';
156
+ if (VALUED_DECLARATOR_TYPES.has(child.type))
157
+ return 'field';
158
+ return undefined;
159
+ }
160
+ return undefined;
161
+ }
162
+ function collectDefinitions(root) {
163
+ const definitions = [];
164
+ const walk = (node, owner) => {
165
+ const type = node.type;
166
+ const mapped = KIND_BY_NODE_TYPE[type];
167
+ if (mapped) {
168
+ const name = definitionNameText(node.childForFieldName('name'));
169
+ if (name) {
170
+ definitions.push({ name, kind: mapped, line: node.startPosition.row + 1, ...(owner ? { owner } : {}) });
171
+ }
172
+ }
173
+ else if (type === 'public_field_definition' || type === 'field_definition') {
174
+ const name = propertyName(node.childForFieldName('name') ?? node.namedChildren[0] ?? node);
175
+ if (name)
176
+ definitions.push({ name, kind: 'field', line: node.startPosition.row + 1, owner: owner ?? enclosingClassName(node) ?? undefined });
177
+ }
178
+ else if (type === 'property_signature') {
179
+ // Interface members are real API surface; anonymous type-literal
180
+ // properties inside expressions are noise and stay out.
181
+ if (node.parent?.type === 'object_type' && node.parent.parent?.type === 'interface_declaration') {
182
+ const name = propertyName(node.childForFieldName('name') ?? node.namedChildren[0] ?? node);
183
+ if (name)
184
+ definitions.push({ name, kind: 'field', line: node.startPosition.row + 1, owner: owner ?? enclosingClassName(node) ?? undefined });
185
+ }
186
+ }
187
+ else if (type === 'variable_declarator') {
188
+ const name = identifierText(node.childForFieldName('name'));
189
+ const valueKind = name ? declaratorValueKind(node) : undefined;
190
+ if (name && valueKind)
191
+ definitions.push({ name, kind: valueKind, line: node.startPosition.row + 1 });
192
+ }
193
+ const childOwner = type === 'class_declaration' || type === 'abstract_class_declaration'
194
+ ? identifierText(node.childForFieldName('name')) ?? owner
195
+ : owner;
196
+ for (const child of node.namedChildren)
197
+ walk(child, childOwner);
198
+ };
199
+ walk(root, undefined);
200
+ return definitions;
201
+ }
202
+ function collectImports(root) {
203
+ const imports = [];
204
+ const specifierOf = (source) => source.text.replace(/^['"]|['"]$/g, '');
205
+ const visit = (node) => {
206
+ if (node.type === 'import_statement') {
207
+ const source = node.childForFieldName('source');
208
+ if (source) {
209
+ const entry = { specifier: specifierOf(source), line: source.startPosition.row + 1, kind: 'import', bindings: [] };
210
+ // The grammar exposes `source` as a field but the clause is a plain named child.
211
+ const clause = node.namedChildren.find(child => child.type === 'import_clause');
212
+ if (clause) {
213
+ for (const part of clause.namedChildren) {
214
+ if (part.type === 'named_imports') {
215
+ for (const spec of part.namedChildren) {
216
+ if (spec.type !== 'import_specifier')
217
+ continue;
218
+ const imported = spec.childForFieldName('name');
219
+ const alias = spec.childForFieldName('alias');
220
+ const importedName = imported ? imported.text : '';
221
+ if (importedName)
222
+ entry.bindings.push({ importedName, localName: alias ? alias.text : importedName });
223
+ }
224
+ }
225
+ else if (part.type === 'identifier') {
226
+ entry.defaultImport = part.text;
227
+ }
228
+ else if (part.type === 'namespace_import') {
229
+ const alias = part.namedChildren.find(child => child.type === 'identifier');
230
+ if (alias)
231
+ entry.namespaceImport = alias.text;
232
+ }
233
+ }
234
+ }
235
+ imports.push(entry);
236
+ }
237
+ }
238
+ else if (node.type === 'export_statement') {
239
+ const source = node.childForFieldName('source');
240
+ if (source) {
241
+ const entry = { specifier: specifierOf(source), line: source.startPosition.row + 1, kind: 'export-from', bindings: [] };
242
+ const clause = node.namedChildren.find(child => child.type === 'export_clause');
243
+ if (clause) {
244
+ for (const spec of clause.namedChildren) {
245
+ if (spec.type !== 'export_specifier')
246
+ continue;
247
+ const name = spec.childForFieldName('name');
248
+ const alias = spec.childForFieldName('alias');
249
+ const importedName = name ? name.text : '';
250
+ if (importedName)
251
+ entry.bindings.push({ importedName, localName: alias ? alias.text : importedName });
252
+ }
253
+ }
254
+ imports.push(entry);
255
+ }
256
+ }
257
+ for (const child of node.namedChildren)
258
+ visit(child);
259
+ };
260
+ visit(root);
261
+ return imports;
262
+ }
263
+ function collectCalls(root) {
264
+ const calls = [];
265
+ const seen = new Set();
266
+ const visit = (node) => {
267
+ if (node.type === 'call_expression') {
268
+ const func = node.childForFieldName('function');
269
+ const record = (name, thisCall = false) => {
270
+ const key = `${name}:${node.startPosition.row + 1}:${thisCall}`;
271
+ if (!seen.has(key)) {
272
+ seen.add(key);
273
+ calls.push({ name, line: node.startPosition.row + 1, ...(thisCall ? { thisCall: true } : {}) });
274
+ }
275
+ };
276
+ if (func?.type === 'identifier') {
277
+ record(func.text);
278
+ }
279
+ else if (func?.type === 'member_expression') {
280
+ const object = func.childForFieldName('object');
281
+ const property = func.childForFieldName('property');
282
+ if (object?.type === 'this' && property?.type === 'property_identifier') {
283
+ record(property.text, true);
284
+ }
285
+ // Other member calls (obj.method()) stay unresolved on purpose:
286
+ // binding receivers to types from AST alone is guesswork, and a wrong
287
+ // calls edge costs more than a missing one.
288
+ }
289
+ }
290
+ for (const child of node.namedChildren)
291
+ visit(child);
292
+ };
293
+ visit(root);
294
+ return calls;
295
+ }
296
+ function collectHeritage(root) {
297
+ const heritage = [];
298
+ const visit = (node) => {
299
+ if (node.type === 'extends_clause') {
300
+ const value = node.childForFieldName('value');
301
+ // `class A extends B` names B as a type_identifier; `extends expr()` stays out.
302
+ const name = value && (value.type === 'identifier' || value.type === 'type_identifier') ? value.text : undefined;
303
+ if (name)
304
+ heritage.push({ name, line: node.startPosition.row + 1 });
305
+ }
306
+ for (const child of node.namedChildren)
307
+ visit(child);
308
+ };
309
+ visit(root);
310
+ return heritage;
311
+ }
312
+ function collectExports(root, localNames) {
313
+ const exportNames = new Set();
314
+ const visit = (node) => {
315
+ if (node.type === 'export_statement') {
316
+ const declaration = node.childForFieldName('declaration');
317
+ const isDefault = node.text.startsWith('export default');
318
+ if (declaration) {
319
+ const nameNode = declaration.childForFieldName('name') ?? declaration.namedChildren[0];
320
+ const name = identifierText(nameNode) ?? (nameNode ? propertyName(nameNode) : undefined);
321
+ if (name)
322
+ exportNames.add(name);
323
+ if (declaration.type === 'lexical_declaration' || declaration.type === 'variable_declaration') {
324
+ for (const declarator of declaration.namedChildren) {
325
+ const declaratorName = identifierText(declarator.childForFieldName('name'));
326
+ if (declaratorName)
327
+ exportNames.add(declaratorName);
328
+ }
329
+ }
330
+ }
331
+ else if (isDefault) {
332
+ const target = node.namedChildren.find(child => child.type === 'identifier');
333
+ if (target)
334
+ exportNames.add(target.text);
335
+ }
336
+ else {
337
+ const clause = node.namedChildren.find(child => child.type === 'export_clause');
338
+ if (clause) {
339
+ for (const spec of clause.namedChildren) {
340
+ if (spec.type !== 'export_specifier')
341
+ continue;
342
+ const original = spec.childForFieldName('name');
343
+ // `export { a as default }` also satisfies a default import of a.
344
+ if (original && localNames.has(original.text))
345
+ exportNames.add(original.text);
346
+ }
347
+ }
348
+ }
349
+ }
350
+ for (const child of node.namedChildren)
351
+ visit(child);
352
+ };
353
+ visit(root);
354
+ return [...exportNames];
355
+ }
356
+ /**
357
+ * Extract one file's structure. `file` is the workspace-relative path used for
358
+ * node ids; `content` is the UTF-8 source. Throws on parser/grammar problems;
359
+ * syntax errors inside the source degrade gracefully (tree-sitter keeps
360
+ * parsing; partial results are still honest structure).
361
+ */
362
+ export async function extractFile(file, content) {
363
+ const extension = path.extname(file).toLowerCase();
364
+ const parser = await parserFor(extension);
365
+ const treeRaw = parser.parse(content);
366
+ const tree = treeRaw ?? parser.parse('');
367
+ try {
368
+ const root = tree.rootNode;
369
+ const definitions = collectDefinitions(root);
370
+ const taken = new Set([file]);
371
+ const symbols = definitions.map(def => ({
372
+ id: symbolNodeId(file, def.name, def.line, taken),
373
+ name: def.name,
374
+ kind: def.kind,
375
+ line: def.line,
376
+ ...(def.owner ? { owner: def.owner } : {}),
377
+ }));
378
+ return {
379
+ version: EXTRACTOR_VERSION,
380
+ file,
381
+ symbols,
382
+ imports: collectImports(root),
383
+ calls: collectCalls(root),
384
+ heritage: collectHeritage(root),
385
+ exports: collectExports(root, new Set(definitions.map(def => def.name))),
386
+ };
387
+ }
388
+ finally {
389
+ tree.delete();
390
+ }
391
+ }
392
+ export function contentHash(content) {
393
+ return createHash('sha256').update(content, 'utf8').digest('hex').slice(0, 32);
394
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Code-graph data model: the persisted graph JSON shape, the in-memory index
3
+ * built from it, and the workspace-keyed store layout contract shared by
4
+ * extraction, build, and query.
5
+ *
6
+ * Nodes are files and the symbols they define; edges carry a relation and an
7
+ * honest confidence label (`EXTRACTED` for relationships explicit in the
8
+ * source, `INFERRED` for relationships resolved across files). The persisted
9
+ * `schemaVersion` lets future extractors detect incompatible graphs, mirroring
10
+ * the signature-validated sparse indexes used for exact readFile paging.
11
+ */
12
+ export declare const GRAPH_SCHEMA_VERSION = 1;
13
+ export type GraphNodeKind = 'file' | 'function' | 'class' | 'method' | 'type' | 'field';
14
+ export type GraphEdgeRelation = 'defines' | 'imports' | 'calls' | 'inherits' | 'references';
15
+ /** How trustworthy an edge is; surfaces in tool output so the model can weigh it. */
16
+ export type GraphConfidence = 'EXTRACTED' | 'INFERRED';
17
+ export interface GraphNode {
18
+ /** Deterministic id: the workspace-relative file path for files, `path#name` (plus `@line` on duplicates) for symbols. */
19
+ id: string;
20
+ label: string;
21
+ kind: GraphNodeKind;
22
+ /** Workspace-relative source file. */
23
+ file: string;
24
+ /** 1-based definition line. */
25
+ line: number;
26
+ /** Community id assigned by label propagation; absent before analysis runs. */
27
+ community?: number;
28
+ }
29
+ export interface GraphEdge {
30
+ source: string;
31
+ target: string;
32
+ relation: GraphEdgeRelation;
33
+ confidence: GraphConfidence;
34
+ /** Workspace-relative file where the relationship site lives (the import/call line, not the definition). */
35
+ file?: string;
36
+ /** 1-based line of the relationship site. */
37
+ line?: number;
38
+ }
39
+ /** The persisted graph document written under `~/.haze/graphs/<workspace>/graph.json`. */
40
+ export interface CodeGraph {
41
+ schemaVersion: number;
42
+ extractorVersion: number;
43
+ builtAt: string;
44
+ fileCount: number;
45
+ nodes: GraphNode[];
46
+ edges: GraphEdge[];
47
+ }
48
+ /** Adjacency index over a {@link CodeGraph}; the query/analysis read surface. */
49
+ export interface GraphIndex {
50
+ graph: CodeGraph;
51
+ nodes: Map<string, GraphNode>;
52
+ out: Map<string, GraphEdge[]>;
53
+ in: Map<string, GraphEdge[]>;
54
+ degree: Map<string, number>;
55
+ /** Lowercased symbol label -> node ids (files excluded; symbol lookup only). */
56
+ labels: Map<string, string[]>;
57
+ }
58
+ export declare function buildGraphIndex(graph: CodeGraph): GraphIndex;
59
+ export declare function nodeDegree(index: GraphIndex, id: string): number;
60
+ /** Stable symbol-id construction; `path#name`, disambiguated by line on duplicates. */
61
+ export declare function symbolNodeId(file: string, name: string, line: number, taken: Set<string>): string;
62
+ /** Parse and validate a graph document read from disk. Throws on unknown schema versions. */
63
+ export declare function parseCodeGraph(value: unknown): CodeGraph;
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Code-graph data model: the persisted graph JSON shape, the in-memory index
3
+ * built from it, and the workspace-keyed store layout contract shared by
4
+ * extraction, build, and query.
5
+ *
6
+ * Nodes are files and the symbols they define; edges carry a relation and an
7
+ * honest confidence label (`EXTRACTED` for relationships explicit in the
8
+ * source, `INFERRED` for relationships resolved across files). The persisted
9
+ * `schemaVersion` lets future extractors detect incompatible graphs, mirroring
10
+ * the signature-validated sparse indexes used for exact readFile paging.
11
+ */
12
+ export const GRAPH_SCHEMA_VERSION = 1;
13
+ export function buildGraphIndex(graph) {
14
+ const nodes = new Map();
15
+ const out = new Map();
16
+ const inn = new Map();
17
+ const degree = new Map();
18
+ const labels = new Map();
19
+ for (const node of graph.nodes) {
20
+ nodes.set(node.id, node);
21
+ if (node.kind !== 'file') {
22
+ const key = node.label.toLowerCase();
23
+ const bucket = labels.get(key);
24
+ if (bucket)
25
+ bucket.push(node.id);
26
+ else
27
+ labels.set(key, [node.id]);
28
+ }
29
+ }
30
+ for (const edge of graph.edges) {
31
+ if (!nodes.has(edge.source) || !nodes.has(edge.target))
32
+ continue;
33
+ let outBucket = out.get(edge.source);
34
+ if (!outBucket) {
35
+ outBucket = [];
36
+ out.set(edge.source, outBucket);
37
+ }
38
+ outBucket.push(edge);
39
+ let inBucket = inn.get(edge.target);
40
+ if (!inBucket) {
41
+ inBucket = [];
42
+ inn.set(edge.target, inBucket);
43
+ }
44
+ inBucket.push(edge);
45
+ degree.set(edge.source, (degree.get(edge.source) ?? 0) + 1);
46
+ degree.set(edge.target, (degree.get(edge.target) ?? 0) + 1);
47
+ }
48
+ return { graph, nodes, out, in: inn, degree, labels };
49
+ }
50
+ export function nodeDegree(index, id) {
51
+ return index.degree.get(id) ?? 0;
52
+ }
53
+ /** Stable symbol-id construction; `path#name`, disambiguated by line on duplicates. */
54
+ export function symbolNodeId(file, name, line, taken) {
55
+ let id = `${file}#${name}`;
56
+ if (!taken.has(id)) {
57
+ taken.add(id);
58
+ return id;
59
+ }
60
+ id = `${file}#${name}@${line}`;
61
+ // Duplicate names at one line are pathological; keep appending until free.
62
+ let suffix = 0;
63
+ while (taken.has(id)) {
64
+ suffix += 1;
65
+ id = `${file}#${name}@${line}-${suffix}`;
66
+ }
67
+ taken.add(id);
68
+ return id;
69
+ }
70
+ /** Parse and validate a graph document read from disk. Throws on unknown schema versions. */
71
+ export function parseCodeGraph(value) {
72
+ if (typeof value !== 'object' || value == null)
73
+ throw new Error('graph.json is not an object');
74
+ const data = value;
75
+ const schemaVersion = data.schemaVersion;
76
+ if (typeof schemaVersion !== 'number' || schemaVersion > GRAPH_SCHEMA_VERSION) {
77
+ throw new Error(`graph.json schema version ${String(schemaVersion)} is newer than supported ${GRAPH_SCHEMA_VERSION}; rebuild the graph`);
78
+ }
79
+ const nodes = Array.isArray(data.nodes) ? data.nodes : [];
80
+ const edges = Array.isArray(data.edges) ? data.edges : [];
81
+ const validNodes = nodes.filter((node) => typeof node === 'object' && node != null
82
+ && typeof node.id === 'string'
83
+ && typeof node.label === 'string'
84
+ && typeof node.file === 'string');
85
+ const validEdges = edges.filter((edge) => typeof edge === 'object' && edge != null
86
+ && typeof edge.source === 'string'
87
+ && typeof edge.target === 'string');
88
+ return {
89
+ schemaVersion: GRAPH_SCHEMA_VERSION,
90
+ extractorVersion: typeof data.extractorVersion === 'number' ? data.extractorVersion : 0,
91
+ builtAt: typeof data.builtAt === 'string' ? data.builtAt : new Date(0).toISOString(),
92
+ fileCount: typeof data.fileCount === 'number' ? data.fileCount : validNodes.filter(node => node.kind === 'file').length,
93
+ nodes: validNodes,
94
+ edges: validEdges,
95
+ };
96
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Graph query engine: natural-language-ish retrieval over the code graph,
3
+ * following the design that made graphify's retrieval outperform grep/read
4
+ * loops on large repos —
5
+ *
6
+ * - IDF-weighted exact/prefix/substring scoring over symbol labels and file
7
+ * paths, with coverage scaling so one incidental exact match cannot drown
8
+ * out multi-term matches;
9
+ * - one guaranteed seed per distinct query term (a collision on one term
10
+ * cannot starve the others);
11
+ * - hub-damped BFS/DFS (nodes above ~p99 degree are never expanded as
12
+ * transit; seeds are exempt) so framework hubs don't flood the answer;
13
+ * - token-budgeted rendering that cuts at line boundaries and never cuts the
14
+ * seed block, file-first so answers read like a map.
15
+ *
16
+ * Haze's 4-chars-per-token heuristic sets the char budget from a token budget.
17
+ */
18
+ import { type GraphEdge, type GraphIndex, type GraphNode } from './model.js';
19
+ export declare function tokenizeQuery(question: string): string[];
20
+ interface ScoredNode {
21
+ id: string;
22
+ score: number;
23
+ /** Query tokens matched by this node's label (coverage numerator). */
24
+ matched: number;
25
+ }
26
+ /** Pick BFS seeds: top-scoring with a score-gap cutoff, then guarantee one seed per query term. */
27
+ export declare function pickSeeds(index: GraphIndex, ranked: ScoredNode[], bestByTerm: Map<string, string>, maxSeeds?: number, gapRatio?: number): string[];
28
+ /** p99-degree threshold, floored at 50: nodes at/above it are transit-opaque hubs. */
29
+ export declare function hubThreshold(index: GraphIndex): number;
30
+ export interface TraversalResult {
31
+ visited: Set<string>;
32
+ edges: Array<{
33
+ source: string;
34
+ target: string;
35
+ }>;
36
+ }
37
+ /** Hub-damped BFS/DFS over both edge directions; records induced edges among visited nodes. */
38
+ export declare function traverse(index: GraphIndex, seeds: string[], depth: number, mode?: 'bfs' | 'dfs'): TraversalResult;
39
+ export interface QueryResult {
40
+ answer: string;
41
+ truncated: boolean;
42
+ seedCount: number;
43
+ nodeCount: number;
44
+ edgeCount: number;
45
+ }
46
+ /** Render the traversed subgraph under a token budget; the seed block is never cut. */
47
+ export declare function renderSubgraph(index: GraphIndex, traversal: TraversalResult, seeds: string[], budgetTokens?: number): {
48
+ answer: string;
49
+ truncated: boolean;
50
+ };
51
+ /** Full question-to-subgraph pipeline. */
52
+ export declare function queryGraph(index: GraphIndex, question: string, options?: {
53
+ mode?: 'bfs' | 'dfs';
54
+ depth?: number;
55
+ budgetTokens?: number;
56
+ }): QueryResult;
57
+ /** Symbol lookup for explain/path/affected: exact label, then label substring, then path substring. */
58
+ export declare function findNodeCandidates(index: GraphIndex, query: string, limit?: number): GraphNode[];
59
+ /** Shortest path between two nodes over the undirected projection; BFS with parent tracking. */
60
+ export declare function shortestPath(index: GraphIndex, from: string, to: string, maxDepth?: number): {
61
+ path: string[];
62
+ edges: GraphEdge[];
63
+ } | undefined;
64
+ /** Render a path result: one line per hop with relation and confidence. */
65
+ export declare function renderPath(index: GraphIndex, result: {
66
+ path: string[];
67
+ edges: GraphEdge[];
68
+ }): string;
69
+ export {};