@denizokcu/haze 1.7.11 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (234) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/README.md +142 -102
  3. package/SECURITY.md +1 -1
  4. package/assets/graph-grammars/NOTICE.md +21 -0
  5. package/assets/graph-grammars/tree-sitter-javascript.wasm +0 -0
  6. package/assets/graph-grammars/tree-sitter-tsx.wasm +0 -0
  7. package/assets/graph-grammars/tree-sitter-typescript.wasm +0 -0
  8. package/assets/graph-grammars/web-tree-sitter.cjs +4116 -0
  9. package/assets/graph-grammars/web-tree-sitter.cjs.map +7 -0
  10. package/assets/graph-grammars/web-tree-sitter.js +4056 -0
  11. package/assets/graph-grammars/web-tree-sitter.js.map +7 -0
  12. package/assets/graph-grammars/web-tree-sitter.wasm +0 -0
  13. package/assets/graph-grammars/web-tree-sitter.wasm.map +55 -0
  14. package/bin/haze.js +47 -19
  15. package/dist/buildInfo.json +3 -3
  16. package/dist/cli/chat/BusyBar.d.ts +1 -2
  17. package/dist/cli/chat/ChatHeader.d.ts +6 -0
  18. package/dist/cli/chat/ChatHeader.js +11 -0
  19. package/dist/cli/chat/ChatScreen.d.ts +16 -0
  20. package/dist/cli/chat/ChatScreen.js +399 -0
  21. package/dist/cli/chat/ChatScreenView.d.ts +68 -0
  22. package/dist/cli/chat/ChatScreenView.js +47 -0
  23. package/dist/cli/chat/LiveTail.d.ts +11 -0
  24. package/dist/cli/chat/LiveTail.js +26 -0
  25. package/dist/cli/chat/TaskBar.d.ts +3 -2
  26. package/dist/cli/chat/TaskBar.js +4 -0
  27. package/dist/cli/chat/agentTurnRunner.d.ts +12 -0
  28. package/dist/cli/chat/agentTurnRunner.js +177 -0
  29. package/dist/cli/chat/busyIndicator.js +9 -5
  30. package/dist/cli/chat/chatMetrics.d.ts +7 -0
  31. package/dist/cli/chat/chatMetrics.js +15 -1
  32. package/dist/cli/chat/chatViewModel.d.ts +85 -0
  33. package/dist/cli/chat/chatViewModel.js +66 -0
  34. package/dist/cli/chat/fileMentionSuggestions.d.ts +0 -14
  35. package/dist/cli/chat/fileMentionSuggestions.js +4 -21
  36. package/dist/cli/chat/inputSuggestions.js +1 -0
  37. package/dist/cli/chat/liveTheme.d.ts +11 -0
  38. package/dist/cli/chat/liveTheme.js +26 -0
  39. package/dist/cli/chat/messageFinalize.d.ts +4 -0
  40. package/dist/cli/chat/messageFinalize.js +8 -0
  41. package/dist/cli/chat/messages.js +1 -1
  42. package/dist/cli/chat/pickerOpeners.d.ts +23 -0
  43. package/dist/cli/chat/pickerOpeners.js +36 -0
  44. package/dist/cli/chat/promptSessionState.d.ts +11 -0
  45. package/dist/cli/chat/promptSessionState.js +39 -0
  46. package/dist/cli/chat/renderMetrics.d.ts +8 -0
  47. package/dist/cli/chat/renderMetrics.js +14 -0
  48. package/dist/cli/chat/resizeGuard.d.ts +11 -0
  49. package/dist/cli/chat/resizeGuard.js +25 -0
  50. package/dist/cli/chat/screenDeps.d.ts +116 -0
  51. package/dist/cli/chat/screenDeps.js +1 -0
  52. package/dist/cli/chat/sessionLifecycle.d.ts +2 -0
  53. package/dist/cli/chat/sessionLifecycle.js +6 -2
  54. package/dist/cli/chat/sessionRecorder.js +4 -1
  55. package/dist/cli/chat/settingsSelection.d.ts +33 -0
  56. package/dist/cli/chat/settingsSelection.js +46 -0
  57. package/dist/cli/chat/skillNotices.d.ts +18 -0
  58. package/dist/cli/chat/skillNotices.js +26 -0
  59. package/dist/cli/chat/startupInfo.js +1 -1
  60. package/dist/cli/chat/startupSequence.d.ts +2 -0
  61. package/dist/cli/chat/startupSequence.js +6 -0
  62. package/dist/cli/chat/submitPipeline.d.ts +8 -0
  63. package/dist/cli/chat/submitPipeline.js +141 -0
  64. package/dist/cli/chat/terminalControl.js +1 -1
  65. package/dist/cli/chat/toolSummaries.d.ts +29 -0
  66. package/dist/cli/chat/toolSummaries.js +268 -0
  67. package/dist/cli/chat/turnState.d.ts +8 -0
  68. package/dist/cli/chat/turnState.js +1 -0
  69. package/dist/cli/chat/userCommandFlow.d.ts +21 -0
  70. package/dist/cli/chat/userCommandFlow.js +66 -0
  71. package/dist/cli/chat/userCommandRunner.d.ts +14 -0
  72. package/dist/cli/chat/userCommandRunner.js +56 -0
  73. package/dist/cli/chat/wizard/providerHandlers.js +19 -2
  74. package/dist/cli/chat/wizardTrail.d.ts +22 -0
  75. package/dist/cli/chat/wizardTrail.js +55 -0
  76. package/dist/cli/commands/chat.d.ts +1 -13
  77. package/dist/cli/commands/chat.js +10 -795
  78. package/dist/cli/commands/commandHelp.js +11 -6
  79. package/dist/cli/commands/commandSuggest.d.ts +2 -0
  80. package/dist/cli/commands/commandSuggest.js +35 -0
  81. package/dist/cli/commands/commands.js +12 -3
  82. package/dist/cli/commands/formatters.d.ts +1 -23
  83. package/dist/cli/commands/formatters.js +3 -224
  84. package/dist/cli/commands/graphCommand.d.ts +2 -0
  85. package/dist/cli/commands/graphCommand.js +60 -0
  86. package/dist/cli/commands/initCommand.js +14 -0
  87. package/dist/cli/commands/modelCommand.js +11 -7
  88. package/dist/cli/commands/reasoningCommand.js +3 -3
  89. package/dist/cli/commands/runCommand.js +6 -2
  90. package/dist/cli/commands/streaming/agentAttempt.js +11 -1
  91. package/dist/cli/commands/streaming/attemptLifecycle.js +1 -0
  92. package/dist/cli/commands/streaming/attemptOutcome.js +8 -3
  93. package/dist/cli/commands/streaming/attemptSetup.d.ts +4 -0
  94. package/dist/cli/commands/streaming/attemptSetup.js +34 -5
  95. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +1 -1
  96. package/dist/cli/commands/streaming/goalSupervisor.js +5 -3
  97. package/dist/cli/commands/streaming/prepareStep.js +1 -0
  98. package/dist/cli/commands/streaming/stepProjection.d.ts +59 -0
  99. package/dist/cli/commands/streaming/stepProjection.js +54 -0
  100. package/dist/cli/commands/streaming/streamLoop.d.ts +2 -0
  101. package/dist/cli/commands/streaming/streamLoop.js +34 -23
  102. package/dist/cli/commands/streaming/toolGroupRenderer.js +1 -1
  103. package/dist/cli/commands/streaming/toolPartHandlers.js +8 -2
  104. package/dist/cli/commands/streaming.d.ts +3 -1
  105. package/dist/cli/commands/streaming.js +5 -0
  106. package/dist/cli/commands/wizardFlow.d.ts +2 -0
  107. package/dist/cli/commands/wizardFlow.js +3 -0
  108. package/dist/cli/index.js +8 -4
  109. package/dist/cli/terminalTitle.js +9 -3
  110. package/dist/config/contextFiles.d.ts +2 -5
  111. package/dist/config/contextFiles.js +1 -1
  112. package/dist/config/inputHistory.js +2 -2
  113. package/dist/config/providerAuth.js +2 -2
  114. package/dist/config/providerModelFacts.js +5 -0
  115. package/dist/config/providerPresets.js +1 -1
  116. package/dist/config/settings.d.ts +7 -0
  117. package/dist/config/settings.js +9 -2
  118. package/dist/config/updateCheck.js +2 -2
  119. package/dist/core/agent/compaction.d.ts +1 -0
  120. package/dist/core/agent/compaction.js +3 -0
  121. package/dist/core/agent/completionController.d.ts +1 -1
  122. package/dist/core/agent/contextBudget.d.ts +1 -1
  123. package/dist/core/agent/goalPolicy.js +8 -2
  124. package/dist/core/agent/overflow.js +5 -0
  125. package/dist/core/agent/toolCapabilities.js +14 -0
  126. package/dist/core/agent/userCommands.d.ts +53 -0
  127. package/dist/core/agent/userCommands.js +116 -0
  128. package/dist/core/agent/workState.d.ts +3 -1
  129. package/dist/core/agent/workState.js +57 -26
  130. package/dist/core/contextFileTypes.d.ts +12 -0
  131. package/dist/core/contextFileTypes.js +1 -0
  132. package/dist/core/graph/analyze.d.ts +61 -0
  133. package/dist/core/graph/analyze.js +274 -0
  134. package/dist/core/graph/buildGraph.d.ts +44 -0
  135. package/dist/core/graph/buildGraph.js +290 -0
  136. package/dist/core/graph/digest.d.ts +2 -0
  137. package/dist/core/graph/digest.js +40 -0
  138. package/dist/core/graph/extract.d.ts +58 -0
  139. package/dist/core/graph/extract.js +394 -0
  140. package/dist/core/graph/model.d.ts +63 -0
  141. package/dist/core/graph/model.js +96 -0
  142. package/dist/core/graph/query.d.ts +69 -0
  143. package/dist/core/graph/query.js +391 -0
  144. package/dist/core/graph/store.d.ts +64 -0
  145. package/dist/core/graph/store.js +171 -0
  146. package/dist/core/limits.d.ts +2 -0
  147. package/dist/core/limits.js +2 -0
  148. package/dist/core/log/llmLog.js +2 -2
  149. package/dist/{config → core/persistence}/privateStorage.js +1 -1
  150. package/dist/core/process/runBoundedProcess.d.ts +7 -4
  151. package/dist/core/process/runBoundedProcess.js +22 -11
  152. package/dist/core/safety/redaction.d.ts +2 -0
  153. package/dist/core/safety/redaction.js +26 -5
  154. package/dist/core/safety/secretPaths.js +12 -3
  155. package/dist/core/safety/untrustedEnvelopes.d.ts +6 -0
  156. package/dist/core/safety/untrustedEnvelopes.js +17 -2
  157. package/dist/core/safety/urlGuard.js +2 -0
  158. package/dist/core/session/sessionStore.d.ts +8 -1
  159. package/dist/core/session/sessionStore.js +15 -4
  160. package/dist/core/shellOutput/reducers/validation.d.ts +1 -1
  161. package/dist/core/shellOutput/types.d.ts +1 -1
  162. package/dist/core/subagent/executionProfiles.js +4 -4
  163. package/dist/core/tasks/taskStorage.js +11 -1
  164. package/dist/{llm → core}/toolResultTypes.d.ts +1 -1
  165. package/dist/core/validation/outputParser.d.ts +1 -1
  166. package/dist/core/validation/outputParser.js +16 -8
  167. package/dist/llm/hazeTools.d.ts +2 -12426
  168. package/dist/llm/hazeTools.js +4 -0
  169. package/dist/llm/lsp/pool.js +1 -1
  170. package/dist/llm/lsp/workspaceEdit.d.ts +1 -1
  171. package/dist/llm/lspTools.d.ts +3 -12622
  172. package/dist/llm/requestContext.d.ts +6 -0
  173. package/dist/llm/requestContext.js +28 -7
  174. package/dist/llm/subagentRunner.d.ts +2 -308
  175. package/dist/llm/systemPrompt.js +17 -7
  176. package/dist/llm/toolGroups.d.ts +534 -0
  177. package/dist/llm/toolGroups.js +57 -0
  178. package/dist/llm/tools/editMatch.d.ts +1 -1
  179. package/dist/llm/tools/failures.d.ts +1 -1
  180. package/dist/llm/tools/fetchTool.d.ts +2 -1221
  181. package/dist/llm/tools/fileToolShared.d.ts +1 -1
  182. package/dist/llm/tools/fileToolShared.js +1 -1
  183. package/dist/llm/tools/fileTools.d.ts +2 -7768
  184. package/dist/llm/tools/fileTools.js +1 -1
  185. package/dist/llm/tools/gitTools.d.ts +12 -0
  186. package/dist/llm/tools/gitTools.js +527 -0
  187. package/dist/llm/tools/graphAdvisory.d.ts +22 -0
  188. package/dist/llm/tools/graphAdvisory.js +68 -0
  189. package/dist/llm/tools/graphTools.d.ts +13 -0
  190. package/dist/llm/tools/graphTools.js +195 -0
  191. package/dist/llm/tools/processTool.d.ts +2 -1081
  192. package/dist/llm/tools/readRecovery.d.ts +1 -1
  193. package/dist/llm/tools/replaceInFiles.d.ts +1 -1
  194. package/dist/llm/tools/replaceInFiles.js +1 -1
  195. package/dist/llm/tools/shellTool.d.ts +2 -1513
  196. package/dist/llm/tools/storedOutputTool.d.ts +2 -355
  197. package/dist/llm/tools/taskTool.d.ts +2 -489
  198. package/dist/llm/tools/taskTool.js +4 -1
  199. package/dist/llm/tools/toolContext.js +29 -11
  200. package/dist/llm/tools/toolContextState.d.ts +4 -1
  201. package/dist/llm/tools/toolContextState.js +2 -1
  202. package/dist/llm/tools/workspaceFile.d.ts +2 -2
  203. package/dist/llm/tools/workspaceFile.js +10 -5
  204. package/dist/skills/SkillRegistry.js +1 -1
  205. package/dist/skills/builder/SkillBuilder.js +1 -1
  206. package/dist/skills/plugins/installer.js +1 -1
  207. package/dist/skills/plugins/runtime.js +1 -1
  208. package/dist/skills/skillTools.js +4 -1
  209. package/dist/ui/components/MarkdownText.d.ts +14 -0
  210. package/dist/ui/components/MarkdownText.js +77 -12
  211. package/dist/ui/components/NativeIndicators.js +5 -1
  212. package/dist/ui/components/StreamingMarkdownText.d.ts +3 -1
  213. package/dist/ui/components/StreamingMarkdownText.js +39 -11
  214. package/dist/ui/components/TextInput.d.ts +1 -2
  215. package/dist/ui/components/TextInput.js +79 -9
  216. package/dist/ui/components/WizardChoices.d.ts +1 -2
  217. package/dist/ui/components/useInputSuggestions.d.ts +1 -1
  218. package/dist/ui/components/useInputSuggestions.js +1 -1
  219. package/dist/ui/mentionDetection.d.ts +20 -0
  220. package/dist/ui/mentionDetection.js +24 -0
  221. package/dist/ui/terminalColors.d.ts +4 -4
  222. package/dist/ui/terminalColors.js +23 -6
  223. package/dist/ui/terminalSanitize.js +8 -3
  224. package/dist/ui/textGeometry.d.ts +2 -0
  225. package/dist/ui/textGeometry.js +6 -0
  226. package/dist/ui/themes/registry.js +33 -33
  227. package/dist/utils/openPath.js +7 -0
  228. package/package.json +22 -19
  229. /package/dist/{llm/tools → core/ignore}/gitIgnore.d.ts +0 -0
  230. /package/dist/{llm/tools → core/ignore}/gitIgnore.js +0 -0
  231. /package/dist/{config → core}/paths.d.ts +0 -0
  232. /package/dist/{config → core}/paths.js +0 -0
  233. /package/dist/{config → core/persistence}/privateStorage.d.ts +0 -0
  234. /package/dist/{llm → core}/toolResultTypes.js +0 -0
@@ -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 '../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
+ }
@@ -35,6 +35,8 @@ export declare const MAX_OUTPUT_CHARS = 50000;
35
35
  export declare const COMPACT_COMMAND_CHARS = 12000;
36
36
  /** Compact cap for passing-validation summaries. */
37
37
  export declare const SHORT_VALIDATION_CHARS = 2000;
38
+ /** Max characters of a user-run (`!`) command echoed back in its transcript row and record. */
39
+ export declare const USER_COMMAND_ECHO_CHARS = 2000;
38
40
  /** Total rendered size cap for grep match output. */
39
41
  export declare const GREP_MAX_OUTPUT_CHARS = 30000;
40
42
  /** Model-visible cap for one MCP tool result; larger results move behind a readToolOutput handle. */
@@ -35,6 +35,8 @@ export const MAX_OUTPUT_CHARS = 50_000;
35
35
  export const COMPACT_COMMAND_CHARS = 12_000;
36
36
  /** Compact cap for passing-validation summaries. */
37
37
  export const SHORT_VALIDATION_CHARS = 2_000;
38
+ /** Max characters of a user-run (`!`) command echoed back in its transcript row and record. */
39
+ export const USER_COMMAND_ECHO_CHARS = 2_000;
38
40
  /** Total rendered size cap for grep match output. */
39
41
  export const GREP_MAX_OUTPUT_CHARS = 30_000;
40
42
  /** Model-visible cap for one MCP tool result; larger results move behind a readToolOutput handle. */
@@ -1,7 +1,7 @@
1
1
  import path from 'node:path';
2
2
  import fs from 'node:fs/promises';
3
- import { HAZE_DIR } from '../../config/paths.js';
4
- import { appendPrivateFile, ensurePrivateFile, ensurePrivateDir, tightenPrivateFile } from '../../config/privateStorage.js';
3
+ import { HAZE_DIR } from '../paths.js';
4
+ import { appendPrivateFile, ensurePrivateFile, ensurePrivateDir, tightenPrivateFile } from '../persistence/privateStorage.js';
5
5
  import { OrderedFileWriter } from '../persistence/orderedFileWriter.js';
6
6
  import { JSONL_LINE_BYTES } from '../limits.js';
7
7
  import { iterateBoundedUtf8Lines } from '../io/boundedRead.js';
@@ -1,7 +1,7 @@
1
1
  import crypto from 'node:crypto';
2
2
  import fs from 'node:fs/promises';
3
3
  import path from 'node:path';
4
- import { HAZE_DIR } from './paths.js';
4
+ import { HAZE_DIR } from '../paths.js';
5
5
  const DIRECTORY_MODE = 0o700;
6
6
  const FILE_MODE = 0o600;
7
7
  export async function ensurePrivateDir(dir) {
@@ -32,11 +32,13 @@ export interface SanitizeEnvOptions {
32
32
  extra?: readonly string[];
33
33
  }
34
34
  /**
35
- * Build a child environment that omits secret-shaped keys: anything matching
35
+ * Build a child environment that omits secret-shaped entries: keys matching
36
36
  * TOKEN/KEY/SECRET/PASSWORD/CREDENTIAL (case-insensitive) plus the caller's
37
- * extra substrings. Everything else — PATH, HOME, LANG, TERM, TZ, etc. — is
38
- * passed through untouched. Opt-in only; callers that do not ask for this keep
39
- * the child inheriting the full environment exactly as before.
37
+ * extra substrings, and values that are URLs with embedded credentials or
38
+ * have a known token shape (`DATABASE_URL=postgres://u:p@host`). Everything
39
+ * else — PATH, HOME, LANG, TERM, TZ, etc. — is passed through untouched.
40
+ * Opt-in only; callers that do not ask for this keep the child inheriting the
41
+ * full environment exactly as before.
40
42
  */
41
43
  export declare function sanitizeChildEnv(env: NodeJS.ProcessEnv, options?: SanitizeEnvOptions): NodeJS.ProcessEnv;
42
44
  export declare function signalProcessTree(child: Pick<ChildProcess, 'pid' | 'kill'>, signal: NodeJS.Signals, options?: ProcessTreeSignalOptions): void;
@@ -51,4 +53,5 @@ export declare function runBoundedProcess(input: {
51
53
  killGraceMs?: number;
52
54
  onStdoutChunk?: (chunk: Buffer) => boolean | void;
53
55
  sanitizeEnv?: SanitizeEnvOptions;
56
+ env?: NodeJS.ProcessEnv;
54
57
  }): Promise<BoundedProcessResult>;
@@ -1,13 +1,16 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { StringDecoder } from 'node:string_decoder';
3
+ import { looksLikeSecret } from '../safety/redaction.js';
3
4
  /** Environment keys carrying these case-insensitive markers are treated as secret-shaped (HZ-10). */
4
5
  const SECRET_ENV_KEY_PATTERN = /TOKEN|KEY|SECRET|PASSWORD|CREDENTIAL/i;
5
6
  /**
6
- * Build a child environment that omits secret-shaped keys: anything matching
7
+ * Build a child environment that omits secret-shaped entries: keys matching
7
8
  * TOKEN/KEY/SECRET/PASSWORD/CREDENTIAL (case-insensitive) plus the caller's
8
- * extra substrings. Everything else — PATH, HOME, LANG, TERM, TZ, etc. — is
9
- * passed through untouched. Opt-in only; callers that do not ask for this keep
10
- * the child inheriting the full environment exactly as before.
9
+ * extra substrings, and values that are URLs with embedded credentials or
10
+ * have a known token shape (`DATABASE_URL=postgres://u:p@host`). Everything
11
+ * else — PATH, HOME, LANG, TERM, TZ, etc. — is passed through untouched.
12
+ * Opt-in only; callers that do not ask for this keep the child inheriting the
13
+ * full environment exactly as before.
11
14
  */
12
15
  export function sanitizeChildEnv(env, options = {}) {
13
16
  const extra = (options.extra ?? []).map(marker => marker.trim().toLowerCase()).filter(marker => marker.length > 0);
@@ -17,6 +20,8 @@ export function sanitizeChildEnv(env, options = {}) {
17
20
  continue;
18
21
  if (extra.some(marker => key.toLowerCase().includes(marker)))
19
22
  continue;
23
+ if (value !== undefined && looksLikeSecret(value))
24
+ continue;
20
25
  child[key] = value;
21
26
  }
22
27
  return child;
@@ -74,7 +79,7 @@ export async function runBoundedProcess(input) {
74
79
  const detached = process.platform !== 'win32';
75
80
  // Absent `sanitizeEnv` means the child inherits process.env exactly (no
76
81
  // `env` option at all) — the pre-sanitizer behavior.
77
- const child = spawn(input.command, input.args, { cwd: input.cwd, detached, stdio: ['ignore', 'pipe', 'pipe'], ...(input.sanitizeEnv ? { env: sanitizeChildEnv(process.env, input.sanitizeEnv) } : {}) });
82
+ const child = spawn(input.command, input.args, { cwd: input.cwd, detached, stdio: ['ignore', 'pipe', 'pipe'], ...(input.env ? { env: input.env } : input.sanitizeEnv ? { env: sanitizeChildEnv(process.env, input.sanitizeEnv) } : {}) });
78
83
  let timedOut = false;
79
84
  let aborted = false;
80
85
  let forced = false;
@@ -104,12 +109,13 @@ export async function runBoundedProcess(input) {
104
109
  resolve({ code, signal, stdout: stdoutResult, stderr: stderrResult, timedOut, aborted, forced, durationMs: Date.now() - startedAt, ...(error ? { error } : {}) });
105
110
  };
106
111
  const scheduleCloseFallback = () => {
107
- // Only call after SIGKILL — running this after SIGTERM would resolve the
108
- // promise before the forced-kill escalation, leaking processes that ignore
109
- // SIGTERM. 50ms is enough for the kernel to deliver the signal and for an
110
- // 'exit' event to fire; if 'close' still doesn't fire, the descendant is
111
- // holding stdio (escaped grandchild) and we settle with whatever exit
112
- // info we already captured.
112
+ // Safe after SIGKILL or after the child's own 'exit' (the direct child
113
+ // is dead; nothing else is pending for it). Never run this straight
114
+ // after SIGTERM: that would resolve the promise before the forced-kill
115
+ // escalation, leaking processes that ignore SIGTERM. 50ms is enough for
116
+ // the kernel to deliver a signal / for 'exit' to fire; if 'close' still
117
+ // doesn't fire, a descendant is holding stdio (escaped grandchild, e.g.
118
+ // `cmd & disown`) and we settle with whatever exit info we captured.
113
119
  closeTimer ??= setTimeout(() => settle(exitCode, exitSignal), 50);
114
120
  closeTimer.unref?.();
115
121
  };
@@ -142,6 +148,11 @@ export async function runBoundedProcess(input) {
142
148
  child.once('exit', (code, signal) => {
143
149
  exitCode = code;
144
150
  exitSignal = signal;
151
+ // The direct child exited; if 'close' has not fired shortly after, an
152
+ // escaped descendant holds the stdio pipes (`sleep 300 & disown; echo
153
+ // done`). Settle on the captured exit info instead of waiting out the
154
+ // full timeout for a command that already finished.
155
+ scheduleCloseFallback();
145
156
  });
146
157
  child.once('close', (code, signal) => settle(code, signal));
147
158
  });
@@ -10,6 +10,8 @@
10
10
  */
11
11
  /** Replace common secret token shapes in a string with `[redacted:<kind>]`. */
12
12
  export declare function redactSecrets(text: string): string;
13
+ /** True when `value` has a known token shape (the same list as `redactSecrets`) or is a URL with embedded credentials (SEC-02). */
14
+ export declare function looksLikeSecret(value: string): boolean;
13
15
  /**
14
16
  * Deep redaction for JSON-serializable values: every nested string is passed
15
17
  * through `redactSecrets`. Cycles collapse to a marker (same convention as
@@ -8,11 +8,23 @@
8
8
  * always redact; session files redact only when the `redactSessionSecrets`
9
9
  * setting opts in (default off, to keep sessions debuggable).
10
10
  */
11
+ // AWS secret access keys are 40 base64-ish characters, a shape shared with
12
+ // SHA-1 digests, so they are only masked next to their access key id: either
13
+ // directly (`key = secret`) or behind a short assignment label (`\nLABEL=secret`).
14
+ const AWS_PAIR_SEPARATOR = String.raw `(["']?\s*[=:,]?\s*["']?|\s*[A-Za-z0-9_ -]{0,40}[=:] ?)`;
15
+ const AWS_SECRET = String.raw `[A-Za-z0-9/+=]{40}`;
11
16
  const SECRET_PATTERNS = [
12
17
  // OpenAI-style API keys (and the many gateways that copy the sk- shape).
13
18
  { kind: 'api-key', pattern: /sk-[A-Za-z0-9_-]{16,}/g },
14
- // GitHub personal access / OAuth tokens.
15
- { kind: 'github-token', pattern: /gh[po]_[A-Za-z0-9]{20,}/g },
19
+ // GitLab personal access tokens and npm tokens.
20
+ { kind: 'gitlab-token', pattern: /glpat-[A-Za-z0-9_-]{20,}/g },
21
+ { kind: 'npm-token', pattern: /npm_[A-Za-z0-9]{36}/g },
22
+ // AWS access key id + secret access key pairs, in either order. These run
23
+ // before the bare key-id row, which would otherwise break the adjacency.
24
+ { kind: 'aws-secret', pattern: new RegExp(`AKIA[0-9A-Z]{16}${AWS_PAIR_SEPARATOR}(${AWS_SECRET})(?![A-Za-z0-9/+=])`, 'g'), replacement: '[redacted:aws-key]$1[redacted:aws-secret]' },
25
+ { kind: 'aws-secret', pattern: new RegExp(`(?<![A-Za-z0-9/+=])(${AWS_SECRET})${AWS_PAIR_SEPARATOR}AKIA[0-9A-Z]{16}`, 'g'), replacement: '[redacted:aws-secret]$2[redacted:aws-key]' },
26
+ // GitHub personal, OAuth, user-to-server, server-to-server, and refresh tokens.
27
+ { kind: 'github-token', pattern: /gh[pousr]_[A-Za-z0-9]{20,}/g },
16
28
  // AWS access key IDs.
17
29
  { kind: 'aws-key', pattern: /AKIA[0-9A-Z]{16}/g },
18
30
  // Slack tokens (bot, app, refresh, user tokens).
@@ -21,23 +33,32 @@ const SECRET_PATTERNS = [
21
33
  // minimums cut false positives on short token-shaped strings while still
22
34
  // matching real JWTs, whose segments are far longer than this.
23
35
  { kind: 'jwt', pattern: /eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g },
36
+ // Opaque bearer credentials; JWT bearers were already masked by the row above.
37
+ { kind: 'bearer-token', pattern: /Bearer [A-Za-z0-9._~+/=-]{20,}/gi },
24
38
  // GitHub fine-grained / long-lived personal access tokens (github_pat_ prefix).
25
39
  { kind: 'github-token', pattern: /github_pat_[A-Za-z0-9_]{20,}/g },
26
40
  // GCP API keys (AIza prefix).
27
41
  { kind: 'gcp-api-key', pattern: /AIza[0-9A-Za-z_-]{30,}/g },
28
42
  // Google OAuth client secrets (GOCSPX prefix).
29
43
  { kind: 'oauth-client-secret', pattern: /GOCSPX-[A-Za-z0-9_-]{20,}/g },
30
- // Stripe restricted keys (rk_live_ / rk_test_ prefix).
44
+ // Stripe secret keys (sk_live_ / sk_test_) and restricted keys (rk_live_ / rk_test_).
45
+ { kind: 'stripe-key', pattern: /sk_(?:live|test)_[A-Za-z0-9]{16,}/g },
31
46
  { kind: 'stripe-key', pattern: /rk_(live|test)_[A-Za-z0-9]{20,}/g },
32
47
  ];
33
48
  /** Replace common secret token shapes in a string with `[redacted:<kind>]`. */
34
49
  export function redactSecrets(text) {
35
50
  let result = text;
36
- for (const { kind, pattern } of SECRET_PATTERNS) {
37
- result = result.replace(pattern, `[redacted:${kind}]`);
51
+ for (const { kind, pattern, replacement } of SECRET_PATTERNS) {
52
+ result = result.replace(pattern, replacement ?? `[redacted:${kind}]`);
38
53
  }
39
54
  return result;
40
55
  }
56
+ /** URLs with embedded credentials (`scheme://user:password@host`, user may be empty) are secrets whatever the variable is called (SEC-02). */
57
+ const CREDENTIAL_URL_PATTERN = /\/\/[^\s/?#]*:[^\s@/?#]+@/;
58
+ /** True when `value` has a known token shape (the same list as `redactSecrets`) or is a URL with embedded credentials (SEC-02). */
59
+ export function looksLikeSecret(value) {
60
+ return CREDENTIAL_URL_PATTERN.test(value) || redactSecrets(value) !== value;
61
+ }
41
62
  /**
42
63
  * Deep redaction for JSON-serializable values: every nested string is passed
43
64
  * through `redactSecrets`. Cycles collapse to a marker (same convention as
@@ -76,7 +76,14 @@ const PROTECTED_BASENAME_PATTERNS = [
76
76
  'firebase-adminsdk-*.json',
77
77
  ];
78
78
  const PROTECTED_BASENAME_MATCHERS = PROTECTED_BASENAME_PATTERNS.map(pattern => new RegExp(`^${pattern.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '[^/]*')}$`, 'i'));
79
- /** OpenSSH private-key stems; `<stem>.pub` public keys stay readable. */
79
+ /**
80
+ * OpenSSH private-key names, protected in any directory (workspace included):
81
+ * extension-less `id_<name>` files (`id_rsa`, `id_deploy_ed25519`) and the
82
+ * classic stems with any non-`.pub` suffix (`id_rsa.bak`). A different
83
+ * extension keeps its meaning (`id_token.ts` is source); `<name>.pub` public
84
+ * keys stay readable (SEC-04).
85
+ */
86
+ const SSH_KEY_NAME_PATTERN = /^id_[^./]+$/;
80
87
  const SSH_KEY_STEMS = ['id_rsa', 'id_dsa', 'id_ecdsa', 'id_ed25519'];
81
88
  /** Extensions that conventionally carry private-key material. */
82
89
  const PROTECTED_EXTENSIONS = ['.pem', '.key', '.ppk', '.p12', '.pfx'];
@@ -94,7 +101,9 @@ function isProtectedEnvName(basename) {
94
101
  return false;
95
102
  }
96
103
  function isProtectedSshKeyName(basename) {
97
- return SSH_KEY_STEMS.some(stem => basename === stem || (basename.startsWith(`${stem}.`) && basename !== `${stem}.pub`));
104
+ if (SSH_KEY_NAME_PATTERN.test(basename))
105
+ return true;
106
+ return SSH_KEY_STEMS.some(stem => basename.startsWith(`${stem}.`) && basename !== `${stem}.pub`);
98
107
  }
99
108
  /** Whether a lowercased home-relative directory path matches a `*`-wildcard pattern (one wildcard per segment). */
100
109
  function matchesHomeDirPattern(pattern, joined) {
@@ -156,7 +165,7 @@ export function secretSearchExcludeGlobs() {
156
165
  // Negated-only globs cannot express an exception without widening traversal.
157
166
  return [...new Set([
158
167
  ...ENV_STEMS.flatMap(stem => [`!${stem}`, `!${stem}.*`]),
159
- ...SSH_KEY_STEMS.map(stem => `!${stem}*`),
168
+ '!id_*',
160
169
  ...PROTECTED_EXTENSIONS.map(extension => `!*${extension}`),
161
170
  ...[...PROTECTED_BASENAMES].map(name => `!${name}`),
162
171
  ...PROTECTED_BASENAME_PATTERNS.map(pattern => `!${pattern}`),
@@ -20,3 +20,9 @@
20
20
  * the exact form keep working because the producer's own closer is intact.
21
21
  */
22
22
  export declare function escapeEnvelopeClosers(content: string): string;
23
+ /**
24
+ * Escape every closing-tag variant of one additional labeled container (e.g.
25
+ * `project_skill`) with the same variant tolerance as the five built-in
26
+ * kinds, so ad-hoc per-site `replaceAll` escapes cannot reappear.
27
+ */
28
+ export declare function escapeTagCloserVariants(content: string, tag: string): string;
@@ -13,7 +13,12 @@
13
13
  *
14
14
  * One helper for all envelope producers: no ad-hoc per-site escapes.
15
15
  */
16
- const ENVELOPE_CLOSER = /<\/\s*(web_content|mcp_result|project_instructions|project_context|haze_compaction)\s*>/gi;
16
+ const ENVELOPE_TAGS = ['web_content', 'mcp_result', 'project_instructions', 'project_context', 'haze_compaction'];
17
+ const ENVELOPE_CLOSER = new RegExp(`<\\/\\s*(?:${ENVELOPE_TAGS.join('|')})\\s*>`, 'gi');
18
+ /** Neutralize one matched closer by breaking the tag open (`<\/`). */
19
+ function escapeCloserMatch(closer) {
20
+ return closer.replace('</', '<\\/');
21
+ }
17
22
  /**
18
23
  * Escape every envelope-closing-tag variant in `content` so the payload
19
24
  * cannot forge an envelope boundary. The escape breaks the tag open (`<\/`)
@@ -21,5 +26,15 @@ const ENVELOPE_CLOSER = /<\/\s*(web_content|mcp_result|project_instructions|proj
21
26
  * the exact form keep working because the producer's own closer is intact.
22
27
  */
23
28
  export function escapeEnvelopeClosers(content) {
24
- return content.replace(ENVELOPE_CLOSER, closer => closer.replace('</', '<\\/'));
29
+ return content.replace(ENVELOPE_CLOSER, escapeCloserMatch);
30
+ }
31
+ /**
32
+ * Escape every closing-tag variant of one additional labeled container (e.g.
33
+ * `project_skill`) with the same variant tolerance as the five built-in
34
+ * kinds, so ad-hoc per-site `replaceAll` escapes cannot reappear.
35
+ */
36
+ export function escapeTagCloserVariants(content, tag) {
37
+ if (!/^[a-z0-9_]+$/i.test(tag))
38
+ throw new Error(`Invalid envelope tag: ${tag}`);
39
+ return content.replace(new RegExp(`<\\/\\s*${tag}\\s*>`, 'gi'), escapeCloserMatch);
25
40
  }
@@ -25,6 +25,8 @@ const BLOCKED_IPV6_CIDRS = [
25
25
  parseIpv6Cidr('::1/128'), // loopback
26
26
  parseIpv6Cidr('::ffff:0:0/96'), // IPv4-mapped (checked via v4 ranges too, but be explicit)
27
27
  parseIpv6Cidr('64:ff9b::/96'), // NAT64
28
+ parseIpv6Cidr('2001::/32'), // Teredo (embeds IPv4 client/server addresses; can reach internal space)
29
+ parseIpv6Cidr('2002::/16'), // 6to4 (embeds an IPv4 address)
28
30
  parseIpv6Cidr('100::/64'), // discard prefix
29
31
  parseIpv6Cidr('fc00::/7'), // unique local
30
32
  parseIpv6Cidr('fe80::/10'), // link-local
@@ -1,6 +1,6 @@
1
1
  import type { ModelMessage } from 'ai';
2
2
  import type { WorkState } from '../agent/workState.js';
3
- import type { ValidationKind } from '../../llm/toolResultTypes.js';
3
+ import type { ValidationKind } from '../../core/toolResultTypes.js';
4
4
  export interface SessionModelSelection {
5
5
  provider: string;
6
6
  model: string;
@@ -123,6 +123,13 @@ export interface HazeSession {
123
123
  redactSecrets?: boolean;
124
124
  /** Internal: the existing JSONL tail has been checked before appending. */
125
125
  tailChecked?: boolean;
126
+ /**
127
+ * Internal: file size at the last auto-vacuum attempt that declined to
128
+ * rewrite (BE-01). Appending entries a rewrite cannot drop grows the kept
129
+ * bytes and the file alike, so that outcome cannot change; such appends skip
130
+ * the full re-parse until droppable content (a snapshot or goal row) arrives.
131
+ */
132
+ vacuumDeclinedBytes?: number;
126
133
  }
127
134
  export declare function createSession(options?: {
128
135
  cwd?: string;
@@ -2,10 +2,10 @@ import crypto from 'node:crypto';
2
2
  import path from 'node:path';
3
3
  import fs from 'node:fs/promises';
4
4
  import { pathExists } from '../../utils/fs.js';
5
- import { HAZE_DIR } from '../../config/paths.js';
5
+ import { HAZE_DIR } from '../paths.js';
6
6
  import { prepareSessionEntryForWrite, repairRestoredConversation } from './sessionSlimming.js';
7
7
  import { decodeSnapshotMessages, encodeSnapshotMessages } from './snapshotCodec.js';
8
- import { appendPrivateFile, ensurePrivateDir, tightenPrivateFile, writePrivateFileAtomic } from '../../config/privateStorage.js';
8
+ import { appendPrivateFile, ensurePrivateDir, tightenPrivateFile, writePrivateFileAtomic } from '../persistence/privateStorage.js';
9
9
  import { JSONL_LINE_BYTES } from '../limits.js';
10
10
  import { iterateBoundedUtf8Lines } from '../io/boundedRead.js';
11
11
  function parseLedgerRedEvidence(value) {
@@ -159,6 +159,9 @@ export async function appendSessionEntry(session, entry) {
159
159
  session.tailChecked = true;
160
160
  // Snapshot deduplication runs inside the same serialized writer as the
161
161
  // append, so ordering with subsequent entries is preserved (F-03).
162
+ const droppable = prepared.type === 'conversation_snapshot' || prepared.type === 'work_state_snapshot' || prepared.type === 'goal';
163
+ if (session.vacuumDeclinedBytes !== undefined && !droppable)
164
+ return;
162
165
  await vacuumSessionFileIfLarge(session).catch(() => undefined);
163
166
  }
164
167
  /**
@@ -185,8 +188,11 @@ export async function vacuumSessionFileIfLarge(session, thresholdBytes = effecti
185
188
  if (session.deferredWrite)
186
189
  return false;
187
190
  const stat = await fs.stat(file).catch(() => undefined);
188
- if (!stat || stat.size < thresholdBytes)
191
+ if (!stat || stat.size < thresholdBytes) {
192
+ // Not a declined rewrite: the next append must still get its attempt once the file crosses the threshold.
193
+ session.vacuumDeclinedBytes = undefined;
189
194
  return false;
195
+ }
190
196
  const { entries } = await readSessionEntries(session);
191
197
  let lastConversation = -1;
192
198
  let lastWorkState = -1;
@@ -228,8 +234,13 @@ export async function vacuumSessionFileIfLarge(session, thresholdBytes = effecti
228
234
  // Only rewrite when it meaningfully shrinks the file (otherwise a single
229
235
  // dominant snapshot would trigger a full rewrite on every append), or when
230
236
  // the goal-ledger trim alone has accumulated enough to amortize the rewrite.
231
- if (serialized.length > stat.size / 2 && droppedGoalBytes < GOAL_LEDGER_TRIM_BYTES)
237
+ // Both sides are bytes: the file size is, and UTF-16 length undercounts
238
+ // multi-byte content (BE-01).
239
+ if (Buffer.byteLength(serialized, 'utf8') > stat.size / 2 && droppedGoalBytes < GOAL_LEDGER_TRIM_BYTES) {
240
+ session.vacuumDeclinedBytes = stat.size;
232
241
  return false;
242
+ }
243
+ session.vacuumDeclinedBytes = undefined;
233
244
  await writePrivateFileAtomic(file, serialized);
234
245
  return true;
235
246
  }
@@ -1,2 +1,2 @@
1
- import type { ValidationSummary } from '../../../llm/toolResultTypes.js';
1
+ import type { ValidationSummary } from '../../../core/toolResultTypes.js';
2
2
  export declare function renderValidationReduction(summary: ValidationSummary, rawHandle?: string, raw?: string): string;
@@ -1,5 +1,5 @@
1
1
  import type { ShellClassification } from '../safety/shellClassifier.js';
2
- import type { ValidationSummary } from '../../llm/toolResultTypes.js';
2
+ import type { ValidationSummary } from '../../core/toolResultTypes.js';
3
3
  import type { ReductionContentKind, ReductionParseTier } from '../toolOutput/reduction.js';
4
4
  type ParseTier = ReductionParseTier;
5
5
  export interface ShellOutputFilterInput {
@@ -27,10 +27,10 @@ export const BUILT_IN_SUBAGENT_PROFILES = {
27
27
  'cloud-fast': { ...COMPATIBILITY_PROFILE, name: 'cloud-fast', maxConcurrency: 5, deadlineMs: 240_000, maxRetries: 1 },
28
28
  };
29
29
  export const MODE_TOOL_NAMES = {
30
- inspect: ['listFiles', 'readFile', 'grep', 'readToolOutput'],
31
- research: ['listFiles', 'readFile', 'grep', 'readToolOutput', 'fetch'],
32
- implement: ['listFiles', 'readFile', 'grep', 'readToolOutput', 'editFile', 'replaceLines', 'writeFile', 'shell'],
33
- validate: ['listFiles', 'readFile', 'grep', 'readToolOutput', 'shell'],
30
+ inspect: ['listFiles', 'readFile', 'grep', 'readToolOutput', 'graphQuery', 'graphExplain', 'graphPath'],
31
+ research: ['listFiles', 'readFile', 'grep', 'readToolOutput', 'fetch', 'graphQuery', 'graphExplain', 'graphPath'],
32
+ implement: ['listFiles', 'readFile', 'grep', 'readToolOutput', 'editFile', 'replaceLines', 'writeFile', 'shell', 'graphQuery', 'graphAffected'],
33
+ validate: ['listFiles', 'readFile', 'grep', 'readToolOutput', 'shell', 'graphAffected'],
34
34
  };
35
35
  export function isMutationMode(mode) {
36
36
  return mode === 'implement' || mode === 'validate';
@@ -40,7 +40,17 @@ export async function saveTasks(tasks) {
40
40
  // Mutation guards fail closed: an escaped real path throws instead of writing.
41
41
  await assertWritablePathInsideWorkspace(filePath, filePath);
42
42
  await fs.mkdir(path.dirname(filePath), { recursive: true });
43
- await fs.writeFile(filePath, JSON.stringify(tasks, null, 2), 'utf-8');
43
+ // Atomic temp-file-plus-rename (same directory) so a crash mid-write cannot
44
+ // leave truncated JSON that loadTasks would silently reset to an empty list.
45
+ const tempPath = `${filePath}.tmp-${randomUUID()}`;
46
+ await fs.writeFile(tempPath, JSON.stringify(tasks, null, 2), 'utf-8');
47
+ try {
48
+ await fs.rename(tempPath, filePath);
49
+ }
50
+ catch (error) {
51
+ await fs.rm(tempPath, { force: true }).catch(() => undefined);
52
+ throw error;
53
+ }
44
54
  }
45
55
  export async function clearTasks() {
46
56
  await saveTasks([]);
@@ -1,4 +1,4 @@
1
- export type ToolFailureReasonCode = 'old_text_missing' | 'old_text_not_unique' | 'overlapping_edits' | 'ignored_path' | 'ignore_check_unavailable' | 'secret_file_protected' | 'git_internals_protected' | 'multi_link_file_protected' | 'path_not_found' | 'not_a_file' | 'permission_denied' | 'outside_workspace' | 'binary_file' | 'existing_file_requires_overwrite' | 'write_chunk_too_large' | 'conflicting_write_modes' | 'append_target_missing' | 'invalid_line_range' | 'io_error' | 'file_too_large' | 'blocked_url' | 'background_limit' | 'background_not_allowed' | 'process_id_required' | 'process_not_found' | 'process_already_exited' | 'process_kill_failed' | 'output_expired' | 'aborted' | 'missing_executable' | 'scoped_instructions_discovered';
1
+ export type ToolFailureReasonCode = 'old_text_missing' | 'old_text_not_unique' | 'overlapping_edits' | 'ignored_path' | 'ignore_check_unavailable' | 'secret_file_protected' | 'git_internals_protected' | 'multi_link_file_protected' | 'path_not_found' | 'not_a_file' | 'permission_denied' | 'outside_workspace' | 'binary_file' | 'existing_file_requires_overwrite' | 'write_chunk_too_large' | 'conflicting_write_modes' | 'append_target_missing' | 'invalid_line_range' | 'invalid_argument' | 'io_error' | 'file_too_large' | 'blocked_url' | 'background_limit' | 'background_not_allowed' | 'process_id_required' | 'process_not_found' | 'process_already_exited' | 'process_kill_failed' | 'output_expired' | 'aborted' | 'missing_executable' | 'graph_not_built' | 'graph_unavailable' | 'not_a_repository' | 'git_error' | 'scoped_instructions_discovered';
2
2
  export type ToolDiffLine = {
3
3
  type: 'add' | 'remove' | 'context';
4
4
  oldLine?: number;
@@ -1,5 +1,5 @@
1
1
  import { type ShellClassification } from '../safety/shellClassifier.js';
2
- import type { ValidationKind, ValidationSummary } from '../../llm/toolResultTypes.js';
2
+ import type { ValidationKind, ValidationSummary } from '../../core/toolResultTypes.js';
3
3
  /**
4
4
  * Shape-only kind inference on the unquoted command, exported for per-stage
5
5
  * classification of `&&` compounds in work-state validation recording.