@denizokcu/haze 1.7.10 → 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.
- package/CHANGELOG.md +25 -0
- package/README.md +125 -99
- package/assets/graph-grammars/NOTICE.md +21 -0
- package/assets/graph-grammars/tree-sitter-javascript.wasm +0 -0
- package/assets/graph-grammars/tree-sitter-tsx.wasm +0 -0
- package/assets/graph-grammars/tree-sitter-typescript.wasm +0 -0
- package/assets/graph-grammars/web-tree-sitter.cjs +4116 -0
- package/assets/graph-grammars/web-tree-sitter.cjs.map +7 -0
- package/assets/graph-grammars/web-tree-sitter.js +4056 -0
- package/assets/graph-grammars/web-tree-sitter.js.map +7 -0
- package/assets/graph-grammars/web-tree-sitter.wasm +0 -0
- package/assets/graph-grammars/web-tree-sitter.wasm.map +55 -0
- package/dist/buildInfo.json +3 -3
- package/dist/cli/chat/BusyBar.d.ts +2 -1
- package/dist/cli/chat/BusyBar.js +2 -2
- package/dist/cli/chat/chatMetrics.d.ts +25 -0
- package/dist/cli/chat/chatMetrics.js +36 -0
- package/dist/cli/chat/inputSuggestions.js +1 -0
- package/dist/cli/chat/sessionLifecycle.d.ts +2 -0
- package/dist/cli/chat/sessionLifecycle.js +29 -19
- package/dist/cli/chat/sessionRecorder.d.ts +2 -1
- package/dist/cli/chat/sessionRecorder.js +29 -9
- package/dist/cli/chat/startupSequence.d.ts +2 -0
- package/dist/cli/chat/startupSequence.js +6 -0
- package/dist/cli/chat/transcriptPartition.js +10 -4
- package/dist/cli/chat/wizard/providerHandlers.js +57 -9
- package/dist/cli/chat/wizard/sessionThemeHandlers.js +5 -1
- package/dist/cli/commands/chat.js +44 -9
- package/dist/cli/commands/commandHelp.js +6 -3
- package/dist/cli/commands/commands.js +2 -0
- package/dist/cli/commands/formatters.js +28 -0
- package/dist/cli/commands/graphCommand.d.ts +2 -0
- package/dist/cli/commands/graphCommand.js +60 -0
- package/dist/cli/commands/initCommand.js +14 -0
- package/dist/cli/commands/providerWizard.js +9 -17
- package/dist/cli/commands/reasoningCommand.d.ts +1 -0
- package/dist/cli/commands/reasoningCommand.js +32 -4
- package/dist/cli/commands/runCommand.js +7 -1
- package/dist/cli/commands/streaming/agentAttempt.js +11 -1
- package/dist/cli/commands/streaming/attemptLifecycle.js +1 -0
- package/dist/cli/commands/streaming/attemptOutcome.js +6 -2
- package/dist/cli/commands/streaming/attemptSetup.d.ts +3 -0
- package/dist/cli/commands/streaming/attemptSetup.js +13 -6
- package/dist/cli/commands/streaming/goalSupervisor.d.ts +1 -1
- package/dist/cli/commands/streaming/goalSupervisor.js +22 -1
- package/dist/cli/commands/streaming/prepareStep.js +1 -0
- package/dist/cli/commands/streaming/streamLoop.d.ts +2 -0
- package/dist/cli/commands/streaming/streamLoop.js +14 -10
- package/dist/cli/commands/streaming/toolPartHandlers.js +7 -1
- package/dist/cli/commands/streaming.d.ts +2 -0
- package/dist/cli/commands/streaming.js +5 -0
- package/dist/cli/commands/wizardFlow.d.ts +1 -0
- package/dist/cli/commands/wizardFlow.js +10 -4
- package/dist/cli/index.js +5 -3
- package/dist/config/hazeBuild.d.ts +2 -2
- package/dist/config/hazeBuild.js +2 -2
- package/dist/config/modelDiscovery.d.ts +1 -1
- package/dist/config/modelDiscovery.js +8 -8
- package/dist/config/{modelCatalog.d.ts → providerModelFacts.d.ts} +13 -2
- package/dist/config/{modelCatalog.js → providerModelFacts.js} +145 -21
- package/dist/config/providerPresets.d.ts +8 -19
- package/dist/config/providerPresets.js +86 -555
- package/dist/config/providerReasoning.d.ts +16 -0
- package/dist/config/providerReasoning.js +56 -0
- package/dist/config/providers.d.ts +4 -0
- package/dist/config/providers.js +19 -2
- package/dist/config/settings.d.ts +14 -0
- package/dist/config/settings.js +5 -0
- package/dist/core/agent/compaction.d.ts +1 -0
- package/dist/core/agent/compaction.js +3 -0
- package/dist/core/agent/events.d.ts +1 -1
- package/dist/core/agent/providerTransition.d.ts +8 -0
- package/dist/core/agent/providerTransition.js +47 -0
- package/dist/core/agent/reasoningPolicy.d.ts +1 -1
- package/dist/core/agent/reasoningPolicy.js +4 -2
- package/dist/core/graph/analyze.d.ts +61 -0
- package/dist/core/graph/analyze.js +274 -0
- package/dist/core/graph/buildGraph.d.ts +44 -0
- package/dist/core/graph/buildGraph.js +290 -0
- package/dist/core/graph/digest.d.ts +2 -0
- package/dist/core/graph/digest.js +40 -0
- package/dist/core/graph/extract.d.ts +58 -0
- package/dist/core/graph/extract.js +394 -0
- package/dist/core/graph/model.d.ts +63 -0
- package/dist/core/graph/model.js +96 -0
- package/dist/core/graph/query.d.ts +69 -0
- package/dist/core/graph/query.js +391 -0
- package/dist/core/graph/store.d.ts +64 -0
- package/dist/core/graph/store.js +171 -0
- package/dist/core/limits.d.ts +0 -2
- package/dist/core/limits.js +0 -2
- package/dist/core/process/runBoundedProcess.js +12 -6
- package/dist/core/providerContracts.d.ts +9 -8
- package/dist/core/providerContracts.js +21 -1
- package/dist/core/safety/redaction.js +12 -2
- package/dist/core/safety/untrustedEnvelopes.d.ts +6 -0
- package/dist/core/safety/untrustedEnvelopes.js +17 -2
- package/dist/core/session/sessionSlimming.js +5 -59
- package/dist/core/session/sessionStore.d.ts +4 -0
- package/dist/core/session/sessionStore.js +149 -9
- package/dist/core/session/snapshotCodec.d.ts +5 -0
- package/dist/core/session/snapshotCodec.js +47 -0
- package/dist/core/shellOutput/registry.js +2 -46
- package/dist/core/subagent/executionProfiles.js +8 -5
- package/dist/core/tasks/taskStorage.js +11 -1
- package/dist/core/toolOutput/reduction.d.ts +55 -2
- package/dist/core/toolOutput/reduction.js +77 -2
- package/dist/core/validation/outputParser.js +16 -8
- package/dist/llm/client.d.ts +4 -2
- package/dist/llm/client.js +104 -55
- package/dist/llm/hazeTools.d.ts +2 -12426
- package/dist/llm/hazeTools.js +2 -0
- package/dist/llm/lspTools.d.ts +3 -12622
- package/dist/llm/mistralReasoning.d.ts +2 -0
- package/dist/llm/mistralReasoning.js +17 -0
- package/dist/llm/mistralVibeAuth.d.ts +5 -0
- package/dist/llm/mistralVibeAuth.js +63 -0
- package/dist/llm/requestContext.d.ts +3 -0
- package/dist/llm/requestContext.js +21 -11
- package/dist/llm/subagentRunner.d.ts +2 -308
- package/dist/llm/subagentRunner.js +15 -7
- package/dist/llm/systemPrompt.js +7 -4
- package/dist/llm/toolResultTypes.d.ts +1 -1
- package/dist/llm/toolResultTypes.js +7 -1
- package/dist/llm/tools/fetchTool.d.ts +2 -1221
- package/dist/llm/tools/fileTools.d.ts +2 -7768
- package/dist/llm/tools/graphAdvisory.d.ts +22 -0
- package/dist/llm/tools/graphAdvisory.js +68 -0
- package/dist/llm/tools/graphTools.d.ts +13 -0
- package/dist/llm/tools/graphTools.js +195 -0
- package/dist/llm/tools/outputCap.d.ts +2 -7
- package/dist/llm/tools/outputCap.js +3 -11
- package/dist/llm/tools/processTool.d.ts +2 -1081
- package/dist/llm/tools/replaceInFiles.js +5 -0
- package/dist/llm/tools/shellTool.d.ts +2 -1513
- package/dist/llm/tools/storedOutputTool.d.ts +2 -355
- package/dist/llm/tools/taskTool.d.ts +2 -489
- package/dist/llm/tools/toolContext.js +24 -9
- package/dist/llm/tools/toolContextState.d.ts +3 -0
- package/dist/llm/tools/toolContextState.js +2 -1
- package/dist/skills/skillTools.js +4 -1
- package/package.json +24 -15
|
@@ -0,0 +1,391 @@
|
|
|
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 { nodeDegree } from './model.js';
|
|
19
|
+
import { isTestPath } from './analyze.js';
|
|
20
|
+
const QUERY_STOPWORDS = new Set([
|
|
21
|
+
'how', 'what', 'why', 'when', 'where', 'which', 'who', 'does', 'did', 'is', 'are', 'was', 'were',
|
|
22
|
+
'can', 'could', 'should', 'would', 'will', 'shall', 'may', 'might', 'must', 'has', 'have', 'had',
|
|
23
|
+
'the', 'and', 'but', 'not', 'for', 'from', 'with', 'into', 'that', 'this', 'these', 'those',
|
|
24
|
+
'work', 'works', 'working', 'get', 'gets', 'call', 'calls', 'called', 'use', 'uses', 'used', 'using',
|
|
25
|
+
'me', 'my', 'it', 'its',
|
|
26
|
+
]);
|
|
27
|
+
const EXACT_TIER = 1000;
|
|
28
|
+
const PREFIX_TIER = 100;
|
|
29
|
+
const SUBSTRING_TIER = 1;
|
|
30
|
+
const PATH_TIER = 0.5;
|
|
31
|
+
export function tokenizeQuery(question) {
|
|
32
|
+
const tokens = question.toLowerCase().split(/[^a-z0-9_$]+/).filter(token => token.length > 1);
|
|
33
|
+
const content = tokens.filter(token => !QUERY_STOPWORDS.has(token));
|
|
34
|
+
return [...new Set(content.length > 0 ? content : tokens)];
|
|
35
|
+
}
|
|
36
|
+
/** Document frequency per token over lowercased labels + file paths, for IDF weighting. */
|
|
37
|
+
function computeIdf(index, tokens) {
|
|
38
|
+
const total = index.nodes.size || 1;
|
|
39
|
+
const idf = new Map();
|
|
40
|
+
for (const token of tokens) {
|
|
41
|
+
let df = 0;
|
|
42
|
+
for (const node of index.nodes.values()) {
|
|
43
|
+
const haystack = `${node.label.toLowerCase()} ${node.file.toLowerCase()}`;
|
|
44
|
+
if (haystack.includes(token))
|
|
45
|
+
df += 1;
|
|
46
|
+
}
|
|
47
|
+
idf.set(token, Math.log(1 + total / (1 + df)));
|
|
48
|
+
}
|
|
49
|
+
return idf;
|
|
50
|
+
}
|
|
51
|
+
function scoreNodes(index, tokens, idf) {
|
|
52
|
+
const ranked = [];
|
|
53
|
+
const bestByTerm = new Map();
|
|
54
|
+
for (const node of index.nodes.values()) {
|
|
55
|
+
const label = node.label.toLowerCase();
|
|
56
|
+
const filePath = node.file.toLowerCase();
|
|
57
|
+
let score = 0;
|
|
58
|
+
let matched = 0;
|
|
59
|
+
let tiered = 0;
|
|
60
|
+
for (const token of tokens) {
|
|
61
|
+
const weight = idf.get(token) ?? 1;
|
|
62
|
+
const substringHit = label.includes(token);
|
|
63
|
+
const pathHit = filePath.includes(token);
|
|
64
|
+
let tier = 0;
|
|
65
|
+
if (token === label) {
|
|
66
|
+
tier = EXACT_TIER * weight;
|
|
67
|
+
matched += 1;
|
|
68
|
+
}
|
|
69
|
+
else if (label.startsWith(token)) {
|
|
70
|
+
tier = PREFIX_TIER * weight;
|
|
71
|
+
matched += 1;
|
|
72
|
+
}
|
|
73
|
+
else if (substringHit) {
|
|
74
|
+
score += SUBSTRING_TIER * weight;
|
|
75
|
+
matched += 1;
|
|
76
|
+
}
|
|
77
|
+
if (pathHit)
|
|
78
|
+
score += PATH_TIER * weight;
|
|
79
|
+
tiered += tier;
|
|
80
|
+
// Track the best node per term for the per-term seed guarantee. Ties
|
|
81
|
+
// prefer the higher-degree node (the more load-bearing definition).
|
|
82
|
+
const singleton = tier > 0 || substringHit || pathHit ? (tier > 0 ? tier : SUBSTRING_TIER * weight) : 0;
|
|
83
|
+
if (singleton > 0) {
|
|
84
|
+
const degree = nodeDegree(index, node.id);
|
|
85
|
+
const current = bestByTerm.get(token);
|
|
86
|
+
if (!current || singleton > current.score || (singleton === current.score && degree > current.degree)) {
|
|
87
|
+
bestByTerm.set(token, { score: singleton, degree, id: node.id });
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
// Coverage scaling: a lone exact hit on one of many terms must not beat
|
|
92
|
+
// nodes matching several terms (squared because exact is 10x prefix).
|
|
93
|
+
if (tiered > 0 && tokens.length > 0) {
|
|
94
|
+
score += tiered * (matched / tokens.length) ** 2;
|
|
95
|
+
}
|
|
96
|
+
// Test helpers repeat the question's words in their own names; demote them
|
|
97
|
+
// unless the question itself asks about tests.
|
|
98
|
+
if (score > 0 && isTestPath(node.file) && !tokens.some(token => token === 'test' || token === 'tests' || token === 'testing' || token === 'spec')) {
|
|
99
|
+
score *= 0.3;
|
|
100
|
+
}
|
|
101
|
+
if (score > 0)
|
|
102
|
+
ranked.push({ id: node.id, score, matched });
|
|
103
|
+
}
|
|
104
|
+
ranked.sort((a, b) => b.score - a.score || a.id.localeCompare(b.id));
|
|
105
|
+
return { ranked, bestByTerm: new Map([...bestByTerm].map(([token, value]) => [token, value.id])) };
|
|
106
|
+
}
|
|
107
|
+
/** Pick BFS seeds: top-scoring with a score-gap cutoff, then guarantee one seed per query term. */
|
|
108
|
+
export function pickSeeds(index, ranked, bestByTerm, maxSeeds = 4, gapRatio = 0.15) {
|
|
109
|
+
if (ranked.length === 0)
|
|
110
|
+
return [];
|
|
111
|
+
const seeds = [];
|
|
112
|
+
const seen = new Set();
|
|
113
|
+
const top = ranked[0].score;
|
|
114
|
+
for (const entry of ranked) {
|
|
115
|
+
if (seeds.length >= maxSeeds)
|
|
116
|
+
break;
|
|
117
|
+
if (seeds.length > 0 && entry.score < top * gapRatio)
|
|
118
|
+
break;
|
|
119
|
+
const labelKey = index.nodes.get(entry.id)?.label.toLowerCase() ?? entry.id;
|
|
120
|
+
if (seen.has(labelKey))
|
|
121
|
+
continue;
|
|
122
|
+
seen.add(labelKey);
|
|
123
|
+
seeds.push(entry.id);
|
|
124
|
+
}
|
|
125
|
+
// Per-term guarantee: an incidental exact match on one term cannot starve matches on the others.
|
|
126
|
+
for (const id of bestByTerm.values()) {
|
|
127
|
+
const node = index.nodes.get(id);
|
|
128
|
+
if (!node || seeds.includes(id))
|
|
129
|
+
continue;
|
|
130
|
+
const labelKey = node.label.toLowerCase();
|
|
131
|
+
if (seen.has(labelKey))
|
|
132
|
+
continue;
|
|
133
|
+
seen.add(labelKey);
|
|
134
|
+
seeds.push(id);
|
|
135
|
+
if (seeds.length >= maxSeeds + 4)
|
|
136
|
+
break;
|
|
137
|
+
}
|
|
138
|
+
return seeds;
|
|
139
|
+
}
|
|
140
|
+
/** p99-degree threshold, floored at 50: nodes at/above it are transit-opaque hubs. */
|
|
141
|
+
export function hubThreshold(index) {
|
|
142
|
+
if (index.nodes.size === 0)
|
|
143
|
+
return 50;
|
|
144
|
+
const degrees = [];
|
|
145
|
+
for (const id of index.nodes.keys())
|
|
146
|
+
degrees.push(nodeDegree(index, id));
|
|
147
|
+
degrees.sort((a, b) => a - b);
|
|
148
|
+
const p99 = degrees[Math.floor(degrees.length * 0.99)] ?? 50;
|
|
149
|
+
return Math.max(50, p99);
|
|
150
|
+
}
|
|
151
|
+
/** Hub-damped BFS/DFS over both edge directions; records induced edges among visited nodes. */
|
|
152
|
+
export function traverse(index, seeds, depth, mode = 'bfs') {
|
|
153
|
+
const seedSet = new Set(seeds);
|
|
154
|
+
const visited = new Set(seeds);
|
|
155
|
+
const edgesSeen = [];
|
|
156
|
+
const edgeKey = new Set();
|
|
157
|
+
const threshold = hubThreshold(index);
|
|
158
|
+
const neighborsOf = (id) => {
|
|
159
|
+
const result = [];
|
|
160
|
+
for (const edge of index.out.get(id) ?? [])
|
|
161
|
+
result.push(edge.target);
|
|
162
|
+
for (const edge of index.in.get(id) ?? [])
|
|
163
|
+
result.push(edge.source);
|
|
164
|
+
return result;
|
|
165
|
+
};
|
|
166
|
+
const record = (from, to) => {
|
|
167
|
+
const key = `${from}\u0000${to}`;
|
|
168
|
+
if (!edgeKey.has(key)) {
|
|
169
|
+
edgeKey.add(key);
|
|
170
|
+
edgesSeen.push({ source: from, target: to });
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
if (mode === 'bfs') {
|
|
174
|
+
let frontier = [...seeds];
|
|
175
|
+
for (let hop = 0; hop < depth && frontier.length > 0; hop++) {
|
|
176
|
+
const next = [];
|
|
177
|
+
for (const current of frontier) {
|
|
178
|
+
if (!seedSet.has(current) && nodeDegree(index, current) >= threshold)
|
|
179
|
+
continue;
|
|
180
|
+
for (const neighbor of neighborsOf(current)) {
|
|
181
|
+
if (visited.has(neighbor))
|
|
182
|
+
continue;
|
|
183
|
+
visited.add(neighbor);
|
|
184
|
+
record(current, neighbor);
|
|
185
|
+
next.push(neighbor);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
frontier = next;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
else {
|
|
192
|
+
const stack = seeds.map(id => ({ id, depth: 0 }));
|
|
193
|
+
while (stack.length > 0) {
|
|
194
|
+
const { id, depth: currentDepth } = stack.pop();
|
|
195
|
+
if (visited.has(id) && !seedSet.has(id))
|
|
196
|
+
continue;
|
|
197
|
+
if (currentDepth > depth)
|
|
198
|
+
continue;
|
|
199
|
+
visited.add(id);
|
|
200
|
+
if (!seedSet.has(id) && nodeDegree(index, id) >= threshold)
|
|
201
|
+
continue;
|
|
202
|
+
for (const neighbor of neighborsOf(id)) {
|
|
203
|
+
if (!visited.has(neighbor)) {
|
|
204
|
+
record(id, neighbor);
|
|
205
|
+
stack.push({ id: neighbor, depth: currentDepth + 1 });
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
// Complete induced edges among visited nodes (traversals only record discovery edges).
|
|
211
|
+
for (const id of [...visited].sort()) {
|
|
212
|
+
for (const edge of index.out.get(id) ?? []) {
|
|
213
|
+
if (edge.target !== id && visited.has(edge.target))
|
|
214
|
+
record(id, edge.target);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
return { visited, edges: edgesSeen };
|
|
218
|
+
}
|
|
219
|
+
const DEFAULT_TOKEN_BUDGET = 1500;
|
|
220
|
+
const MAX_TOKEN_BUDGET = 4000;
|
|
221
|
+
const CHARS_PER_TOKEN = 4;
|
|
222
|
+
function edgeLine(index, source, target) {
|
|
223
|
+
const sourceNode = index.nodes.get(source);
|
|
224
|
+
const targetNode = index.nodes.get(target);
|
|
225
|
+
if (!sourceNode || !targetNode)
|
|
226
|
+
return undefined;
|
|
227
|
+
const first = index.out.get(source)?.find(edge => edge.target === target)
|
|
228
|
+
?? index.in.get(source)?.find(edge => edge.source === target);
|
|
229
|
+
if (!first)
|
|
230
|
+
return undefined;
|
|
231
|
+
const at = first.line ? ` at ${first.file}:${first.line}` : '';
|
|
232
|
+
return `EDGE ${sourceNode.label} --${first.relation} [${first.confidence}]--> ${targetNode.label}${at}`;
|
|
233
|
+
}
|
|
234
|
+
function nodeLine(index, id, seed) {
|
|
235
|
+
const node = index.nodes.get(id);
|
|
236
|
+
const community = node.community != null ? ` community=${node.community}` : '';
|
|
237
|
+
return `NODE ${node.label} [${seed ? 'seed ' : ''}${node.kind} src=${node.file}:${node.line}${community}]`;
|
|
238
|
+
}
|
|
239
|
+
/** Render the traversed subgraph under a token budget; the seed block is never cut. */
|
|
240
|
+
export function renderSubgraph(index, traversal, seeds, budgetTokens = DEFAULT_TOKEN_BUDGET) {
|
|
241
|
+
const charBudget = Math.min(budgetTokens, MAX_TOKEN_BUDGET) * CHARS_PER_TOKEN;
|
|
242
|
+
const seedSet = new Set(seeds);
|
|
243
|
+
const dist = new Map(seeds.map(id => [id, 0]));
|
|
244
|
+
// Hop distance from seeds over both directions, for budget-cut ordering:
|
|
245
|
+
// the nodes that answer the question survive the cut, hubs don't push them out.
|
|
246
|
+
let frontier = [...seeds];
|
|
247
|
+
let hop = 0;
|
|
248
|
+
while (frontier.length > 0) {
|
|
249
|
+
hop += 1;
|
|
250
|
+
const next = [];
|
|
251
|
+
for (const id of frontier) {
|
|
252
|
+
for (const edge of index.out.get(id) ?? []) {
|
|
253
|
+
if (!dist.has(edge.target) && traversal.visited.has(edge.target)) {
|
|
254
|
+
dist.set(edge.target, hop);
|
|
255
|
+
next.push(edge.target);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
for (const edge of index.in.get(id) ?? []) {
|
|
259
|
+
if (!dist.has(edge.source) && traversal.visited.has(edge.source)) {
|
|
260
|
+
dist.set(edge.source, hop);
|
|
261
|
+
next.push(edge.source);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
frontier = next;
|
|
266
|
+
}
|
|
267
|
+
const orderedNodes = [...seeds, ...[...traversal.visited]
|
|
268
|
+
.filter(id => !seedSet.has(id))
|
|
269
|
+
.sort((a, b) => (dist.get(a) ?? 99) - (dist.get(b) ?? 99) || nodeDegree(index, b) - nodeDegree(index, a) || a.localeCompare(b))];
|
|
270
|
+
const lines = [];
|
|
271
|
+
for (const id of orderedNodes) {
|
|
272
|
+
if (index.nodes.has(id))
|
|
273
|
+
lines.push(nodeLine(index, id, seedSet.has(id)));
|
|
274
|
+
}
|
|
275
|
+
for (const edge of traversal.edges) {
|
|
276
|
+
const line = edgeLine(index, edge.source, edge.target);
|
|
277
|
+
if (line)
|
|
278
|
+
lines.push(line);
|
|
279
|
+
}
|
|
280
|
+
let output = lines.join('\n');
|
|
281
|
+
if (output.length <= charBudget)
|
|
282
|
+
return { answer: output, truncated: false };
|
|
283
|
+
const cutCandidate = output.slice(0, charBudget);
|
|
284
|
+
let cutAt = cutCandidate.lastIndexOf('\n');
|
|
285
|
+
if (cutAt <= 0)
|
|
286
|
+
cutAt = charBudget;
|
|
287
|
+
// Never cut the seed block: extend the cut to cover it (seeds are bounded).
|
|
288
|
+
const seedBlockEnd = lines.slice(0, seeds.length).reduce((sum, line) => sum + line.length + 1, 0) - 1;
|
|
289
|
+
cutAt = Math.max(cutAt, Math.min(seedBlockEnd, output.length));
|
|
290
|
+
output = `${output.slice(0, cutAt)}\n[… truncated; raise budget or query more specifically]`;
|
|
291
|
+
return { answer: output, truncated: true };
|
|
292
|
+
}
|
|
293
|
+
/** Full question-to-subgraph pipeline. */
|
|
294
|
+
export function queryGraph(index, question, options = {}) {
|
|
295
|
+
const tokens = tokenizeQuery(question);
|
|
296
|
+
if (tokens.length === 0) {
|
|
297
|
+
return { answer: 'No searchable terms in the question.', truncated: false, seedCount: 0, nodeCount: 0, edgeCount: 0 };
|
|
298
|
+
}
|
|
299
|
+
const idf = computeIdf(index, tokens);
|
|
300
|
+
const { ranked, bestByTerm } = scoreNodes(index, tokens, idf);
|
|
301
|
+
if (ranked.length === 0) {
|
|
302
|
+
return { answer: `No graph nodes matched: ${tokens.join(', ')}.`, truncated: false, seedCount: 0, nodeCount: 0, edgeCount: 0 };
|
|
303
|
+
}
|
|
304
|
+
const seeds = pickSeeds(index, ranked, bestByTerm);
|
|
305
|
+
const traversal = traverse(index, seeds, options.depth ?? 2, options.mode ?? 'bfs');
|
|
306
|
+
const { answer, truncated } = renderSubgraph(index, traversal, seeds, options.budgetTokens);
|
|
307
|
+
return { answer, truncated, seedCount: seeds.length, nodeCount: traversal.visited.size, edgeCount: traversal.edges.length };
|
|
308
|
+
}
|
|
309
|
+
/** Symbol lookup for explain/path/affected: exact label, then label substring, then path substring. */
|
|
310
|
+
export function findNodeCandidates(index, query, limit = 5) {
|
|
311
|
+
const lowered = query.toLowerCase();
|
|
312
|
+
const exact = index.labels.get(lowered) ?? [];
|
|
313
|
+
const scored = [];
|
|
314
|
+
for (const id of exact) {
|
|
315
|
+
const node = index.nodes.get(id);
|
|
316
|
+
if (node)
|
|
317
|
+
scored.push({ node, score: 1000 + nodeDegree(index, id) });
|
|
318
|
+
}
|
|
319
|
+
if (scored.length === 0) {
|
|
320
|
+
for (const node of index.nodes.values()) {
|
|
321
|
+
if (node.kind === 'file')
|
|
322
|
+
continue;
|
|
323
|
+
const label = node.label.toLowerCase();
|
|
324
|
+
if (label === lowered)
|
|
325
|
+
scored.push({ node, score: 1000 + nodeDegree(index, node.id) });
|
|
326
|
+
else if (label.includes(lowered))
|
|
327
|
+
scored.push({ node, score: 100 + nodeDegree(index, node.id) });
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
if (scored.length === 0) {
|
|
331
|
+
for (const node of index.nodes.values()) {
|
|
332
|
+
if (node.file.toLowerCase().includes(lowered))
|
|
333
|
+
scored.push({ node, score: 50 + nodeDegree(index, node.id) });
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
return scored.sort((a, b) => b.score - a.score || a.node.id.localeCompare(b.node.id)).slice(0, limit).map(entry => entry.node);
|
|
337
|
+
}
|
|
338
|
+
/** Shortest path between two nodes over the undirected projection; BFS with parent tracking. */
|
|
339
|
+
export function shortestPath(index, from, to, maxDepth = 8) {
|
|
340
|
+
if (from === to)
|
|
341
|
+
return { path: [from], edges: [] };
|
|
342
|
+
const parent = new Map();
|
|
343
|
+
const visited = new Set([from]);
|
|
344
|
+
let frontier = [from];
|
|
345
|
+
let depth = 0;
|
|
346
|
+
while (frontier.length > 0 && depth < maxDepth) {
|
|
347
|
+
depth += 1;
|
|
348
|
+
const next = [];
|
|
349
|
+
for (const current of frontier) {
|
|
350
|
+
const steps = [];
|
|
351
|
+
for (const edge of index.out.get(current) ?? [])
|
|
352
|
+
steps.push({ neighbor: edge.target, edge });
|
|
353
|
+
for (const edge of index.in.get(current) ?? [])
|
|
354
|
+
steps.push({ neighbor: edge.source, edge });
|
|
355
|
+
for (const step of steps) {
|
|
356
|
+
if (visited.has(step.neighbor))
|
|
357
|
+
continue;
|
|
358
|
+
visited.add(step.neighbor);
|
|
359
|
+
parent.set(step.neighbor, { node: current, edge: step.edge });
|
|
360
|
+
if (step.neighbor === to) {
|
|
361
|
+
const path = [to];
|
|
362
|
+
const edges = [];
|
|
363
|
+
let cursor = to;
|
|
364
|
+
while (cursor !== from) {
|
|
365
|
+
const link = parent.get(cursor);
|
|
366
|
+
edges.unshift(link.edge);
|
|
367
|
+
cursor = link.node;
|
|
368
|
+
path.unshift(cursor);
|
|
369
|
+
}
|
|
370
|
+
return { path, edges };
|
|
371
|
+
}
|
|
372
|
+
next.push(step.neighbor);
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
frontier = next;
|
|
376
|
+
}
|
|
377
|
+
return undefined;
|
|
378
|
+
}
|
|
379
|
+
/** Render a path result: one line per hop with relation and confidence. */
|
|
380
|
+
export function renderPath(index, result) {
|
|
381
|
+
const lines = [];
|
|
382
|
+
for (const [position, edge] of result.edges.entries()) {
|
|
383
|
+
const fromNode = index.nodes.get(result.path[position]);
|
|
384
|
+
const toNode = index.nodes.get(result.path[position + 1]);
|
|
385
|
+
if (!fromNode || !toNode)
|
|
386
|
+
continue;
|
|
387
|
+
const at = edge.line ? ` at ${edge.file}:${edge.line}` : '';
|
|
388
|
+
lines.push(`${fromNode.label} (${fromNode.kind} ${fromNode.file}) --${edge.relation} [${edge.confidence}]--> ${toNode.label}${at}`);
|
|
389
|
+
}
|
|
390
|
+
return lines.length > 0 ? lines.join('\n') : `${index.nodes.get(result.path[0])?.label ?? result.path[0]} (same node)`;
|
|
391
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { type CodeGraph } from './model.js';
|
|
2
|
+
import { type FileExtraction } from './extract.js';
|
|
3
|
+
export interface FileSignature {
|
|
4
|
+
size: number;
|
|
5
|
+
mtimeMs: number;
|
|
6
|
+
hash?: string;
|
|
7
|
+
}
|
|
8
|
+
export interface GraphManifest {
|
|
9
|
+
extractorVersion: number;
|
|
10
|
+
workspaceRoot: string;
|
|
11
|
+
files: Record<string, FileSignature>;
|
|
12
|
+
}
|
|
13
|
+
export interface GraphStore {
|
|
14
|
+
dir: string;
|
|
15
|
+
graphPath: string;
|
|
16
|
+
manifestPath: string;
|
|
17
|
+
cacheDir: string;
|
|
18
|
+
}
|
|
19
|
+
/** Stable directory key for a workspace root (real path, hashed for filename safety). */
|
|
20
|
+
export declare function workspaceGraphKey(root: string): string;
|
|
21
|
+
export declare function graphStoreFor(root: string): GraphStore;
|
|
22
|
+
/** Read the persisted graph; undefined when none exists. Throws on corrupt JSON (caller decides to rebuild). */
|
|
23
|
+
export declare function readGraph(store: GraphStore): Promise<CodeGraph | undefined>;
|
|
24
|
+
export declare function readManifest(store: GraphStore): Promise<GraphManifest | undefined>;
|
|
25
|
+
export interface WriteGraphOptions {
|
|
26
|
+
/** Permit intentional shrink (mass deletion); otherwise a graph that loses most of its nodes is refused. */
|
|
27
|
+
force?: boolean;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Persist graph + manifest atomically. The shrink guard refuses to replace a
|
|
31
|
+
* healthy graph with a near-empty one unless `force` — a half walk or a parser
|
|
32
|
+
* failure must not silently destroy a good map (mirrors graphify's #479 guard).
|
|
33
|
+
*/
|
|
34
|
+
export declare function writeGraph(store: GraphStore, graph: CodeGraph, manifest: GraphManifest, options?: WriteGraphOptions): Promise<void>;
|
|
35
|
+
export declare function readCachedExtraction(store: GraphStore, hash: string): Promise<FileExtraction | undefined>;
|
|
36
|
+
export declare function writeCachedExtraction(store: GraphStore, hash: string, extraction: FileExtraction): Promise<void>;
|
|
37
|
+
/** Drop cache entries beyond a bounded count (oldest mtime first). */
|
|
38
|
+
export declare function pruneExtractionCache(store: GraphStore, maxEntries: number): Promise<void>;
|
|
39
|
+
export interface StaleFileSet {
|
|
40
|
+
changed: string[];
|
|
41
|
+
added: string[];
|
|
42
|
+
removed: string[];
|
|
43
|
+
}
|
|
44
|
+
export interface StalenessReport {
|
|
45
|
+
stale: boolean;
|
|
46
|
+
files: StaleFileSet;
|
|
47
|
+
}
|
|
48
|
+
/** Compare manifest signatures against the current tree; size/mtime mismatches count as changed. */
|
|
49
|
+
export declare function computeStaleness(store: GraphStore, currentSignatures: Record<string, FileSignature>): Promise<StalenessReport>;
|
|
50
|
+
/**
|
|
51
|
+
* Delete the whole persisted graph for a workspace (graph.json, manifest,
|
|
52
|
+
* extraction cache). Returns true when a graph store existed and was removed.
|
|
53
|
+
*/
|
|
54
|
+
export declare function deleteGraph(store: GraphStore): Promise<boolean>;
|
|
55
|
+
/** Cheap existence + freshness check used by tool entry points and /graph. */
|
|
56
|
+
export declare function graphStatus(store: GraphStore): Promise<{
|
|
57
|
+
exists: boolean;
|
|
58
|
+
stale: boolean;
|
|
59
|
+
builtAt?: string;
|
|
60
|
+
nodeCount: number;
|
|
61
|
+
edgeCount: number;
|
|
62
|
+
fileCount: number;
|
|
63
|
+
graph?: CodeGraph;
|
|
64
|
+
}>;
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-workspace graph persistence under `~/.haze/graphs/<workspace-key>/`:
|
|
3
|
+
* `graph.json` (the graph document), `manifest.json` (file signatures), and
|
|
4
|
+
* `cache/` (content-hash extraction cache).
|
|
5
|
+
*
|
|
6
|
+
* Storage lives in the home directory like sessions, so the user's repository
|
|
7
|
+
* is never polluted and gitignore semantics never apply to haze's own
|
|
8
|
+
* artifacts. All writes are atomic (temp file + rename).
|
|
9
|
+
*/
|
|
10
|
+
import fs from 'node:fs/promises';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import { createHash } from 'node:crypto';
|
|
13
|
+
import { parseCodeGraph } from './model.js';
|
|
14
|
+
import { EXTRACTOR_VERSION } from './extract.js';
|
|
15
|
+
import { HAZE_DIR } from '../../config/paths.js';
|
|
16
|
+
/** Stable directory key for a workspace root (real path, hashed for filename safety). */
|
|
17
|
+
export function workspaceGraphKey(root) {
|
|
18
|
+
return createHash('sha256').update(root, 'utf8').digest('hex').slice(0, 16);
|
|
19
|
+
}
|
|
20
|
+
export function graphStoreFor(root) {
|
|
21
|
+
const dir = path.join(HAZE_DIR, 'graphs', workspaceGraphKey(root));
|
|
22
|
+
return { dir, graphPath: path.join(dir, 'graph.json'), manifestPath: path.join(dir, 'manifest.json'), cacheDir: path.join(dir, 'cache') };
|
|
23
|
+
}
|
|
24
|
+
async function writeFileAtomic(target, content) {
|
|
25
|
+
await fs.mkdir(path.dirname(target), { recursive: true });
|
|
26
|
+
const temp = `${target}.tmp-${process.pid}-${Date.now()}`;
|
|
27
|
+
await fs.writeFile(temp, content, 'utf8');
|
|
28
|
+
await fs.rename(temp, target);
|
|
29
|
+
}
|
|
30
|
+
/** Read the persisted graph; undefined when none exists. Throws on corrupt JSON (caller decides to rebuild). */
|
|
31
|
+
export async function readGraph(store) {
|
|
32
|
+
try {
|
|
33
|
+
const raw = await fs.readFile(store.graphPath, 'utf8');
|
|
34
|
+
return parseCodeGraph(JSON.parse(raw));
|
|
35
|
+
}
|
|
36
|
+
catch (error) {
|
|
37
|
+
const code = error.code;
|
|
38
|
+
if (code === 'ENOENT')
|
|
39
|
+
return undefined;
|
|
40
|
+
if (error instanceof SyntaxError)
|
|
41
|
+
throw new Error('graph.json is corrupted; rebuild the graph', { cause: error });
|
|
42
|
+
throw error;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
export async function readManifest(store) {
|
|
46
|
+
try {
|
|
47
|
+
const raw = await fs.readFile(store.manifestPath, 'utf8');
|
|
48
|
+
const data = JSON.parse(raw);
|
|
49
|
+
if (typeof data !== 'object' || data == null || typeof data.files !== 'object')
|
|
50
|
+
throw new Error('manifest.json is corrupted');
|
|
51
|
+
return data;
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
const code = error.code;
|
|
55
|
+
if (code === 'ENOENT')
|
|
56
|
+
return undefined;
|
|
57
|
+
if (error instanceof SyntaxError)
|
|
58
|
+
throw new Error('manifest.json is corrupted; rebuild the graph', { cause: error });
|
|
59
|
+
throw error;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Persist graph + manifest atomically. The shrink guard refuses to replace a
|
|
64
|
+
* healthy graph with a near-empty one unless `force` — a half walk or a parser
|
|
65
|
+
* failure must not silently destroy a good map (mirrors graphify's #479 guard).
|
|
66
|
+
*/
|
|
67
|
+
export async function writeGraph(store, graph, manifest, options = {}) {
|
|
68
|
+
const previous = await readGraph(store);
|
|
69
|
+
if (!options.force && previous && previous.nodes.length > 500 && graph.nodes.length < previous.nodes.length * 0.5) {
|
|
70
|
+
throw new Error(`Refusing to shrink the code graph from ${previous.nodes.length} to ${graph.nodes.length} nodes. If files were really deleted, rebuild with force.`);
|
|
71
|
+
}
|
|
72
|
+
await writeFileAtomic(store.graphPath, JSON.stringify(graph));
|
|
73
|
+
await writeFileAtomic(store.manifestPath, JSON.stringify({ ...manifest, extractorVersion: EXTRACTOR_VERSION }));
|
|
74
|
+
}
|
|
75
|
+
// ---------------------------------------------------------------------------
|
|
76
|
+
// Extraction cache: content-hash keyed JSON per file
|
|
77
|
+
// ---------------------------------------------------------------------------
|
|
78
|
+
function cachePath(store, hash) {
|
|
79
|
+
return path.join(store.cacheDir, `${hash}.json`);
|
|
80
|
+
}
|
|
81
|
+
export async function readCachedExtraction(store, hash) {
|
|
82
|
+
try {
|
|
83
|
+
const raw = await fs.readFile(cachePath(store, hash), 'utf8');
|
|
84
|
+
const data = JSON.parse(raw);
|
|
85
|
+
if (data.version !== EXTRACTOR_VERSION)
|
|
86
|
+
return undefined;
|
|
87
|
+
return data;
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
return undefined;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
export async function writeCachedExtraction(store, hash, extraction) {
|
|
94
|
+
try {
|
|
95
|
+
await writeFileAtomic(cachePath(store, hash), JSON.stringify(extraction));
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
// Cache writes are best-effort; a full cache dir must never fail a build.
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
/** Drop cache entries beyond a bounded count (oldest mtime first). */
|
|
102
|
+
export async function pruneExtractionCache(store, maxEntries) {
|
|
103
|
+
try {
|
|
104
|
+
const entries = await fs.readdir(store.cacheDir).catch(() => []);
|
|
105
|
+
if (entries.length <= maxEntries)
|
|
106
|
+
return;
|
|
107
|
+
const stats = await Promise.all(entries.map(async (name) => {
|
|
108
|
+
const full = path.join(store.cacheDir, name);
|
|
109
|
+
const stat = await fs.stat(full).catch(() => undefined);
|
|
110
|
+
return { full, mtime: stat?.mtimeMs ?? 0 };
|
|
111
|
+
}));
|
|
112
|
+
stats.sort((a, b) => a.mtime - b.mtime);
|
|
113
|
+
for (const entry of stats.slice(0, stats.length - maxEntries)) {
|
|
114
|
+
await fs.rm(entry.full, { force: true });
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
catch {
|
|
118
|
+
// Pruning is best-effort.
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
/** Compare manifest signatures against the current tree; size/mtime mismatches count as changed. */
|
|
122
|
+
export async function computeStaleness(store, currentSignatures) {
|
|
123
|
+
const manifest = await readManifest(store);
|
|
124
|
+
if (!manifest)
|
|
125
|
+
return { stale: true, files: { changed: [], added: [], removed: [] } };
|
|
126
|
+
const changed = [];
|
|
127
|
+
const added = [];
|
|
128
|
+
const removed = [];
|
|
129
|
+
for (const [file, signature] of Object.entries(currentSignatures)) {
|
|
130
|
+
const known = manifest.files[file];
|
|
131
|
+
if (!known)
|
|
132
|
+
added.push(file);
|
|
133
|
+
else if (known.size !== signature.size || known.mtimeMs !== signature.mtimeMs)
|
|
134
|
+
changed.push(file);
|
|
135
|
+
}
|
|
136
|
+
for (const file of Object.keys(manifest.files)) {
|
|
137
|
+
if (!(file in currentSignatures))
|
|
138
|
+
removed.push(file);
|
|
139
|
+
}
|
|
140
|
+
return { stale: changed.length > 0 || added.length > 0 || removed.length > 0 || manifest.extractorVersion !== EXTRACTOR_VERSION, files: { changed, added, removed } };
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Delete the whole persisted graph for a workspace (graph.json, manifest,
|
|
144
|
+
* extraction cache). Returns true when a graph store existed and was removed.
|
|
145
|
+
*/
|
|
146
|
+
export async function deleteGraph(store) {
|
|
147
|
+
const existed = await fs.stat(store.graphPath).then(() => true, () => false);
|
|
148
|
+
await fs.rm(store.dir, { recursive: true, force: true });
|
|
149
|
+
return existed;
|
|
150
|
+
}
|
|
151
|
+
/** Cheap existence + freshness check used by tool entry points and /graph. */
|
|
152
|
+
export async function graphStatus(store) {
|
|
153
|
+
const graph = await readGraph(store);
|
|
154
|
+
if (!graph)
|
|
155
|
+
return { exists: false, stale: false, nodeCount: 0, edgeCount: 0, fileCount: 0 };
|
|
156
|
+
const files = graph.nodes.filter(node => node.kind === 'file');
|
|
157
|
+
const signatures = {};
|
|
158
|
+
const root = process.cwd();
|
|
159
|
+
for (const node of files) {
|
|
160
|
+
try {
|
|
161
|
+
const absolute = path.join(root, node.file);
|
|
162
|
+
const stat = await fs.stat(absolute);
|
|
163
|
+
signatures[node.file] = { size: stat.size, mtimeMs: stat.mtimeMs };
|
|
164
|
+
}
|
|
165
|
+
catch {
|
|
166
|
+
// Missing file: leave it out; computeStaleness reports it as removed.
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
const staleness = await computeStaleness(store, signatures);
|
|
170
|
+
return { exists: true, stale: staleness.stale, builtAt: graph.builtAt, nodeCount: graph.nodes.length, edgeCount: graph.edges.length, fileCount: files.length, graph };
|
|
171
|
+
}
|
package/dist/core/limits.d.ts
CHANGED
|
@@ -49,5 +49,3 @@ export declare const COMPACTION_LLM_TRANSCRIPT_CHARS = 60000;
|
|
|
49
49
|
export declare const SESSION_INLINE_VALUE_BYTES: number;
|
|
50
50
|
/** Preview length for slimmed session values. */
|
|
51
51
|
export declare const SESSION_PREVIEW_CHARS: number;
|
|
52
|
-
/** Strings longer than this are truncated in session snapshots. */
|
|
53
|
-
export declare const SESSION_LARGE_STRING_CHARS: number;
|
package/dist/core/limits.js
CHANGED
|
@@ -49,5 +49,3 @@ export const COMPACTION_LLM_TRANSCRIPT_CHARS = 60_000;
|
|
|
49
49
|
export const SESSION_INLINE_VALUE_BYTES = 32 * 1024;
|
|
50
50
|
/** Preview length for slimmed session values. */
|
|
51
51
|
export const SESSION_PREVIEW_CHARS = 4 * 1024;
|
|
52
|
-
/** Strings longer than this are truncated in session snapshots. */
|
|
53
|
-
export const SESSION_LARGE_STRING_CHARS = 8 * 1024;
|
|
@@ -104,12 +104,13 @@ export async function runBoundedProcess(input) {
|
|
|
104
104
|
resolve({ code, signal, stdout: stdoutResult, stderr: stderrResult, timedOut, aborted, forced, durationMs: Date.now() - startedAt, ...(error ? { error } : {}) });
|
|
105
105
|
};
|
|
106
106
|
const scheduleCloseFallback = () => {
|
|
107
|
-
//
|
|
108
|
-
//
|
|
109
|
-
// SIGTERM
|
|
110
|
-
//
|
|
111
|
-
//
|
|
112
|
-
//
|
|
107
|
+
// Safe after SIGKILL or after the child's own 'exit' (the direct child
|
|
108
|
+
// is dead; nothing else is pending for it). Never run this straight
|
|
109
|
+
// after SIGTERM: that would resolve the promise before the forced-kill
|
|
110
|
+
// escalation, leaking processes that ignore SIGTERM. 50ms is enough for
|
|
111
|
+
// the kernel to deliver a signal / for 'exit' to fire; if 'close' still
|
|
112
|
+
// doesn't fire, a descendant is holding stdio (escaped grandchild, e.g.
|
|
113
|
+
// `cmd & disown`) and we settle with whatever exit info we captured.
|
|
113
114
|
closeTimer ??= setTimeout(() => settle(exitCode, exitSignal), 50);
|
|
114
115
|
closeTimer.unref?.();
|
|
115
116
|
};
|
|
@@ -142,6 +143,11 @@ export async function runBoundedProcess(input) {
|
|
|
142
143
|
child.once('exit', (code, signal) => {
|
|
143
144
|
exitCode = code;
|
|
144
145
|
exitSignal = signal;
|
|
146
|
+
// The direct child exited; if 'close' has not fired shortly after, an
|
|
147
|
+
// escaped descendant holds the stdio pipes (`sleep 300 & disown; echo
|
|
148
|
+
// done`). Settle on the captured exit info instead of waiting out the
|
|
149
|
+
// full timeout for a command that already finished.
|
|
150
|
+
scheduleCloseFallback();
|
|
145
151
|
});
|
|
146
152
|
child.once('close', (code, signal) => settle(code, signal));
|
|
147
153
|
});
|