@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
@@ -13,7 +13,7 @@ import { boundedDiff, fileDiff, findEditRange, splitDiffLines, lineNumberAtOffse
13
13
  import { runDedupedTool, discoverScopedContext, withScopedContext, hazeToolContextSchema } from './toolContext.js';
14
14
  import { prepareWorkspaceMutation, prepareWorkspaceRead, prepareWorkspaceWritePath } from './workspaceFile.js';
15
15
  import { DEFAULT_READ_LINES, INLINE_DIFF_LINE_LIMIT, MAX_OUTPUT_CHARS, sourceOutlineEntries } from './fileToolShared.js';
16
- import { createIgnoreClassifier } from './gitIgnore.js';
16
+ import { createIgnoreClassifier } from '../../core/ignore/gitIgnore.js';
17
17
  import { runRipgrepBounded, resolveRipgrepExecutable } from './grepRunner.js';
18
18
  import { secretSearchExcludeGlobs } from '../../core/safety/secretPaths.js';
19
19
  import { EXACT_MUTATION_BYTES } from '../../core/limits.js';
@@ -0,0 +1,12 @@
1
+ import { type ToolSet } from 'ai';
2
+ /**
3
+ * Dedicated git tools: compact, structured, bounded answers about the
4
+ * workspace repository (and explicit mutating actions) instead of raw
5
+ * `git` shell output. All tools run `git` in the workspace repo root through
6
+ * the shared bounded subprocess primitive.
7
+ */
8
+ export declare const GIT_LOG_DEFAULT_LIMIT = 20;
9
+ export declare const GIT_DIFF_DEFAULT_LINES = 200;
10
+ /** Classify combined `git pull` stdout + stderr into a user-facing reason, or `undefined` when unrecognized. */
11
+ export declare function classifyPullFailure(output: string): string | undefined;
12
+ export declare const gitTools: ToolSet;
@@ -0,0 +1,527 @@
1
+ import { tool } from 'ai';
2
+ import { z } from 'zod';
3
+ import path from 'node:path';
4
+ import fs from 'node:fs/promises';
5
+ import { prepareWorkspaceWritePath } from './workspaceFile.js';
6
+ import { runBoundedProcess } from '../../core/process/runBoundedProcess.js';
7
+ import { SHELL_STREAM_BYTES } from '../../core/limits.js';
8
+ import { workspaceRoot } from '../../utils/path.js';
9
+ import { hazeToolContextSchema, runDedupedTool } from './toolContext.js';
10
+ import { HazeToolError, structuredToolFailure } from './failures.js';
11
+ /**
12
+ * Dedicated git tools: compact, structured, bounded answers about the
13
+ * workspace repository (and explicit mutating actions) instead of raw
14
+ * `git` shell output. All tools run `git` in the workspace repo root through
15
+ * the shared bounded subprocess primitive.
16
+ */
17
+ export const GIT_LOG_DEFAULT_LIMIT = 20;
18
+ const GIT_LOG_MAX_LIMIT = 200;
19
+ export const GIT_DIFF_DEFAULT_LINES = 200;
20
+ const GIT_DIFF_MAX_LINES = 2000;
21
+ const GIT_TIMEOUT_MS = 30_000;
22
+ function gitFailure(toolName, error, fallbackNextStep) {
23
+ return structuredToolFailure(toolName, error, fallbackNextStep);
24
+ }
25
+ /** Resolve the workspace repo root; throws a terminal not_a_repository error. */
26
+ async function resolveRepoRoot() {
27
+ const cwd = workspaceRoot();
28
+ const result = await runBoundedProcess({
29
+ command: 'git', args: ['rev-parse', '--show-toplevel'], cwd,
30
+ timeoutMs: 10_000, maxStdoutBytes: 64 * 1024, maxStderrBytes: 64 * 1024, env: gitEnv(),
31
+ });
32
+ const root = result.stdout.text.trim();
33
+ if (result.code !== 0 || !root) {
34
+ throw new HazeToolError('The current working directory is not inside a git repository.', 'not_a_repository', {
35
+ recoverable: false,
36
+ suggestedNextStep: 'Run git tools from inside a git repository, or use shell for non-git work.',
37
+ });
38
+ }
39
+ return path.resolve(root);
40
+ }
41
+ /** Confine a user-supplied path to the workspace repo. */
42
+ function confinePath(repoRoot, inputPath) {
43
+ const resolved = path.resolve(repoRoot, inputPath);
44
+ const confined = resolved === repoRoot || resolved.startsWith(repoRoot + path.sep);
45
+ if (!confined) {
46
+ throw new HazeToolError(`Path ${inputPath} is outside the workspace repository.`, 'outside_workspace', {
47
+ recoverable: false,
48
+ suggestedNextStep: 'Use a workspace-relative path.',
49
+ });
50
+ }
51
+ if (resolved.split(path.sep).includes('.git')) {
52
+ throw new HazeToolError(`Path ${inputPath} points into .git internals.`, 'git_internals_protected', {
53
+ recoverable: false,
54
+ suggestedNextStep: 'Query repository content, not .git internals; use shell only for explicitly requested raw git plumbing.',
55
+ });
56
+ }
57
+ return path.relative(repoRoot, resolved) || '.';
58
+ }
59
+ /** Longest revision, branch, or range accepted in ref-shaped tool inputs. */
60
+ const MAX_REF_LENGTH = 256;
61
+ /**
62
+ * Ref-shaped inputs must name a revision. A leading dash would make git parse
63
+ * the value as an option (`--exec=…`, `-c key=value`, `-D`), so such inputs
64
+ * are refused before anything is spawned (SEC-06).
65
+ */
66
+ function assertRefName(toolName, field, value) {
67
+ if (value === undefined)
68
+ return;
69
+ if (value.length > MAX_REF_LENGTH || value.startsWith('-') || /[\s\p{Cc}]/u.test(value)) {
70
+ throw new HazeToolError(`${field} must be a plain commit, branch, or range, not a git option: ${JSON.stringify(value.slice(0, 80))}.`, 'invalid_argument', {
71
+ recoverable: true,
72
+ suggestedNextStep: `Retry ${toolName} with a revision that has no leading dash, whitespace, or control characters.`,
73
+ });
74
+ }
75
+ }
76
+ /**
77
+ * Git's environment: the caller's, minus the variables that would redirect git
78
+ * to another repository (haze may itself run from a git hook), and never
79
+ * interactive. Hooks that open an editor or prompt find no terminal either way
80
+ * (stdin is ignored); these settings make git itself give up at once.
81
+ */
82
+ function gitEnv() {
83
+ const env = { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_EDITOR: 'true', LC_ALL: 'C' };
84
+ for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_COMMON_DIR'])
85
+ delete env[key];
86
+ return env;
87
+ }
88
+ async function runGit(repoRoot, args, abortSignal) {
89
+ const result = await runBoundedProcess({
90
+ command: 'git', args, cwd: repoRoot, timeoutMs: GIT_TIMEOUT_MS, signal: abortSignal,
91
+ maxStdoutBytes: SHELL_STREAM_BYTES, maxStderrBytes: SHELL_STREAM_BYTES, env: gitEnv(),
92
+ });
93
+ return { code: result.code, stdout: result.stdout.text, stderr: result.stderr.text, timedOut: result.timedOut, aborted: result.aborted };
94
+ }
95
+ function gitError(toolName, run, nextStep) {
96
+ // A stopped process has no exit code and empty diagnostics; name the timeout,
97
+ // and that the operation may have stopped halfway (rebase, reset, clone).
98
+ const timedOut = run.timedOut;
99
+ const detail = timedOut
100
+ ? `git did not finish within ${GIT_TIMEOUT_MS / 1000} s and was stopped; the repository may be left mid-operation.`
101
+ : run.stderr.trim().split('\n')[0] ?? `git exited with code ${run.code ?? 'null'}`;
102
+ return {
103
+ ok: false,
104
+ toolName,
105
+ path: undefined,
106
+ error: detail,
107
+ reasonCode: 'git_error',
108
+ recoverable: true,
109
+ suggestedNextStep: timedOut ? 'Check the repository state with gitStatus before retrying; a stopped rebase or reset may need to be completed or aborted via shell.' : nextStep,
110
+ recoveryTool: undefined,
111
+ recoveryInput: undefined,
112
+ };
113
+ }
114
+ function abortedResult(toolName) {
115
+ return { ok: false, toolName, reasonCode: 'aborted', recoverable: true, error: 'Aborted.', suggestedNextStep: 'Retry when the turn is active.' };
116
+ }
117
+ const statusInput = z.object({
118
+ path: z.string().optional().describe('Optional workspace-relative path to limit the status to.'),
119
+ });
120
+ const logInput = z.object({
121
+ limit: z.number().int().min(1).max(GIT_LOG_MAX_LIMIT).default(GIT_LOG_DEFAULT_LIMIT).describe(`Max commits to return (default ${GIT_LOG_DEFAULT_LIMIT}).`),
122
+ range: z.string().optional().describe('Optional commit range, e.g. HEAD~5..HEAD.'),
123
+ path: z.string().optional().describe('Optional workspace-relative path to limit history to.'),
124
+ });
125
+ const diffInput = z.object({
126
+ path: z.string().optional().describe('Optional workspace-relative file or directory to diff.'),
127
+ range: z.string().optional().describe('Optional commit range to diff (e.g. HEAD~3..HEAD).'),
128
+ staged: z.boolean().default(false).describe('Diff staged changes instead of unstaged.'),
129
+ limit: z.number().int().min(1).max(GIT_DIFF_MAX_LINES).default(GIT_DIFF_DEFAULT_LINES).describe(`Max diff lines to return (default ${GIT_DIFF_DEFAULT_LINES}).`),
130
+ });
131
+ const branchInput = z.object({
132
+ remotes: z.boolean().default(false).describe('Include remote branches.'),
133
+ });
134
+ const remoteInput = z.object({
135
+ remote: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).optional().describe('Configured remote name; omit to use Git defaults.'),
136
+ });
137
+ const pullInput = remoteInput.extend({
138
+ mode: z.enum(['ff-only', 'rebase', 'merge']).default('ff-only').describe('Integration policy; defaults to fast-forward only.'),
139
+ });
140
+ const cloneInput = z.object({
141
+ url: z.string().min(1).describe('Remote repository URL (HTTPS, SSH, or git://); do not include credentials.'),
142
+ path: z.string().min(1).describe('New workspace-relative destination directory.'),
143
+ });
144
+ async function runNetworkGit(cwd, args, signal) {
145
+ const result = await runBoundedProcess({
146
+ command: 'git', args: ['-c', 'credential.interactive=never', '-c', 'protocol.ext.allow=never', ...args], cwd,
147
+ timeoutMs: 120_000, signal, maxStdoutBytes: 8192, maxStderrBytes: 8192,
148
+ env: { ...gitEnv(), GCM_INTERACTIVE: 'Never', GIT_MERGE_AUTOEDIT: 'no', GIT_SSH_COMMAND: process.env.GIT_SSH_COMMAND ?? 'ssh -oBatchMode=yes' },
149
+ });
150
+ return result;
151
+ }
152
+ function networkFailure(toolName, timedOut) {
153
+ return { ok: false, toolName, reasonCode: 'git_error', recoverable: true,
154
+ error: timedOut ? 'Git network operation timed out.' : 'Git network operation failed.',
155
+ suggestedNextStep: 'Check the remote, network, credentials, and repository state; authentication must be non-interactive.' };
156
+ }
157
+ /** Reasons for a failed `git pull`, in precedence order, matched against C-locale git diagnostics (see `runNetworkGit`). */
158
+ const PULL_FAILURE_REASONS = [
159
+ [/not possible to fast-forward|ca(?:not|n't) (?:be )?fast-forward(?:ed)?|divergent branches|fetch first/i, 'The branch cannot be fast-forwarded.'],
160
+ [/CONFLICT|merge conflict/i, 'Pull stopped with conflicts.'],
161
+ ];
162
+ /** Classify combined `git pull` stdout + stderr into a user-facing reason, or `undefined` when unrecognized. */
163
+ export function classifyPullFailure(output) {
164
+ return PULL_FAILURE_REASONS.find(([pattern]) => pattern.test(output))?.[1];
165
+ }
166
+ function validCloneUrl(value) {
167
+ if (/^[A-Za-z0-9._-]+@[A-Za-z0-9.-]+:[^\s]+$/.test(value))
168
+ return true;
169
+ try {
170
+ const url = new URL(value);
171
+ return ['https:', 'ssh:', 'git:'].includes(url.protocol) && !!url.hostname && !url.password && (url.protocol === 'ssh:' || !url.username);
172
+ }
173
+ catch {
174
+ return false;
175
+ }
176
+ }
177
+ const stageInput = z.object({
178
+ paths: z.array(z.string().min(1)).min(1).describe('Workspace-relative paths to stage.'),
179
+ all: z.boolean().default(false).describe('Stage all changes (git add -A).'),
180
+ });
181
+ const commitInput = z.object({
182
+ message: z.string().min(1).describe('Commit message.'),
183
+ all: z.boolean().default(false).describe('Stage all tracked modifications before committing.'),
184
+ });
185
+ const branchManageInput = z.object({
186
+ action: z.enum(['create', 'delete', 'rename', 'checkout']).describe('Branch action to perform.'),
187
+ name: z.string().min(1).describe('Branch name (the branch to delete/checkout, or the new name for create/rename).'),
188
+ newName: z.string().optional().describe('New branch name for rename.'),
189
+ startPoint: z.string().optional().describe('Start point (commit/branch) for create.'),
190
+ });
191
+ const rebaseInput = z.object({
192
+ onto: z.string().min(1).describe('Explicit target to rebase onto (required; history-rewriting, runs only on explicit request).'),
193
+ });
194
+ const resetInput = z.object({
195
+ target: z.string().min(1).describe('Explicit commit/branch to reset to.'),
196
+ mode: z.enum(['soft', 'mixed', 'hard']).describe('Reset mode; hard discards working-tree changes.'),
197
+ });
198
+ export const gitTools = {
199
+ gitStatus: tool({
200
+ description: 'Compact git status of the workspace repository: current branch, upstream ahead/behind, staged/unstaged/untracked files. Prefer this over running git status via shell.',
201
+ contextSchema: hazeToolContextSchema,
202
+ inputSchema: statusInput,
203
+ execute: async (input, context) => runDedupedTool('gitStatus', input, context, async () => {
204
+ try {
205
+ const root = await resolveRepoRoot();
206
+ const confined = input.path ? confinePath(root, input.path) : undefined;
207
+ const run = await runGit(root, ['status', '--porcelain=v1', '-b', ...(confined ? ['--', confined] : [])], context.abortSignal);
208
+ if (run.aborted)
209
+ return abortedResult('gitStatus');
210
+ if (run.code !== 0)
211
+ return gitError('gitStatus', run, 'Check that the repository is healthy, then retry.');
212
+ const lines = run.stdout.split('\n').filter(line => line.length > 0);
213
+ const header = lines.find(line => line.startsWith('## ')) ?? '';
214
+ const branch = header.replace(/^## /, '').split('...')[0] || '(detached)';
215
+ const aheadBehind = /\[ahead (\d+)(?:, behind (\d+))?\]|\[behind (\d+)\]/.exec(header);
216
+ const staged = [];
217
+ const unstaged = [];
218
+ const untracked = [];
219
+ for (const line of lines) {
220
+ if (line.startsWith('## '))
221
+ continue;
222
+ const x = line[0] ?? ' ';
223
+ const y = line[1] ?? ' ';
224
+ const file = line.slice(3);
225
+ if (x === '?' && y === '?')
226
+ untracked.push(file);
227
+ else {
228
+ if (x !== ' ' && x !== '?')
229
+ staged.push(file);
230
+ if (y !== ' ' && y !== '?')
231
+ unstaged.push(file);
232
+ }
233
+ }
234
+ return {
235
+ ok: true, toolName: 'gitStatus', branch, cwd: root,
236
+ ...(aheadBehind ? { ahead: Number(aheadBehind[1] ?? 0), behind: Number(aheadBehind[2] ?? aheadBehind[3] ?? 0) } : {}),
237
+ staged, unstaged, untracked,
238
+ };
239
+ }
240
+ catch (error) {
241
+ return gitFailure('gitStatus', error, 'Retry gitStatus, or inspect the repository with shell git if the tools do not cover the case.');
242
+ }
243
+ }),
244
+ }),
245
+ gitLog: tool({
246
+ description: `Recent commit history of the workspace repository as compact entries (hash, subject, author, relative time), bounded to ${GIT_LOG_DEFAULT_LIMIT} commits by default. Prefer this over running git log via shell.`,
247
+ contextSchema: hazeToolContextSchema,
248
+ inputSchema: logInput,
249
+ execute: async (input, context) => runDedupedTool('gitLog', input, context, async () => {
250
+ try {
251
+ assertRefName('gitLog', 'range', input.range);
252
+ const root = await resolveRepoRoot();
253
+ const confined = input.path ? confinePath(root, input.path) : undefined;
254
+ const limit = input.limit ?? GIT_LOG_DEFAULT_LIMIT;
255
+ const args = ['log', `--max-count=${limit}`, '--format=%h%x00%s%x00%an%x00%ar', ...(input.range ? [input.range] : []), ...(confined ? ['--', confined] : [])];
256
+ const run = await runGit(root, args, context.abortSignal);
257
+ if (run.aborted)
258
+ return abortedResult('gitLog');
259
+ if (run.code !== 0)
260
+ return gitError('gitLog', run, 'Check the range/path, then retry.');
261
+ const commits = run.stdout.split('\n').filter(line => line.includes('\x00')).map(line => {
262
+ const [hash, subject, author, relativeTime] = line.split('\x00');
263
+ return { hash, subject, author, relativeTime };
264
+ });
265
+ return { ok: true, toolName: 'gitLog', count: commits.length, truncated: commits.length >= limit, commits };
266
+ }
267
+ catch (error) {
268
+ return gitFailure('gitLog', error, 'Retry gitLog with a narrower range or path.');
269
+ }
270
+ }),
271
+ }),
272
+ gitDiff: tool({
273
+ description: `Bounded diff of workspace changes (per-file stats plus patch, default ${GIT_DIFF_DEFAULT_LINES} lines) with a truncation indicator. Prefer this over running git diff via shell.`,
274
+ contextSchema: hazeToolContextSchema,
275
+ inputSchema: diffInput,
276
+ execute: async (input, context) => runDedupedTool('gitDiff', input, context, async () => {
277
+ try {
278
+ assertRefName('gitDiff', 'range', input.range);
279
+ const root = await resolveRepoRoot();
280
+ const confined = input.path ? confinePath(root, input.path) : undefined;
281
+ const staged = input.staged ?? false;
282
+ const statRun = await runGit(root, ['diff', '--stat', ...(staged ? ['--staged'] : []), ...(input.range ? [input.range] : []), ...(confined ? ['--', confined] : [])], context.abortSignal);
283
+ if (statRun.aborted)
284
+ return abortedResult('gitDiff');
285
+ if (statRun.code !== 0)
286
+ return gitError('gitDiff', statRun, 'Check the range/path, then retry.');
287
+ const patchRun = await runGit(root, ['diff', ...(staged ? ['--staged'] : []), ...(input.range ? [input.range] : []), ...(confined ? ['--', confined] : [])], context.abortSignal);
288
+ if (patchRun.aborted)
289
+ return abortedResult('gitDiff');
290
+ if (patchRun.code !== 0)
291
+ return gitError('gitDiff', patchRun, 'Check the range/path, then retry.');
292
+ const limit = input.limit ?? GIT_DIFF_DEFAULT_LINES;
293
+ const patchLines = patchRun.stdout.split('\n');
294
+ const truncated = patchLines.length > limit;
295
+ const patch = truncated ? patchLines.slice(0, limit).join('\n') : patchRun.stdout;
296
+ const files = statRun.stdout.split('\n').filter(line => line.includes('|')).map(line => {
297
+ const [file, stats] = line.split('|');
298
+ return { path: file.trim(), stats: (stats ?? '').trim() };
299
+ });
300
+ return {
301
+ ok: true, toolName: 'gitDiff', files, patch, truncated,
302
+ ...(truncated ? { hint: `Diff truncated at ${limit} lines; narrow with path/range or raise limit (max ${GIT_DIFF_MAX_LINES}).` } : {}),
303
+ };
304
+ }
305
+ catch (error) {
306
+ return gitFailure('gitDiff', error, 'Retry gitDiff with a narrower path or range.');
307
+ }
308
+ }),
309
+ }),
310
+ gitBranch: tool({
311
+ description: 'List branches of the workspace repository (current, local, optionally remotes). Prefer this over running git branch via shell.',
312
+ contextSchema: hazeToolContextSchema,
313
+ inputSchema: branchInput,
314
+ execute: async (input, context) => runDedupedTool('gitBranch', input, context, async () => {
315
+ try {
316
+ const root = await resolveRepoRoot();
317
+ const wantRemotes = input.remotes ?? false;
318
+ const run = await runGit(root, ['branch', ...(wantRemotes ? ['-a'] : [])], context.abortSignal);
319
+ if (run.aborted)
320
+ return abortedResult('gitBranch');
321
+ if (run.code !== 0)
322
+ return gitError('gitBranch', run, 'Retry gitBranch.');
323
+ const current = [];
324
+ const local = [];
325
+ const remotes = [];
326
+ for (const raw of run.stdout.split('\n')) {
327
+ const line = raw.trimEnd();
328
+ if (!line)
329
+ continue;
330
+ if (line.startsWith('* '))
331
+ current.push(line.slice(2).trim());
332
+ else if (line.startsWith('remotes/'))
333
+ remotes.push(line.replace(/^remotes\//, ''));
334
+ else
335
+ local.push(line.trim());
336
+ }
337
+ return { ok: true, toolName: 'gitBranch', current, local, ...(wantRemotes ? { remotes } : {}) };
338
+ }
339
+ catch (error) {
340
+ return gitFailure('gitBranch', error, 'Retry gitBranch.');
341
+ }
342
+ }),
343
+ }),
344
+ gitFetch: tool({
345
+ description: 'Fetch updates from a configured Git remote without interactive authentication. Updates remote-tracking refs; does not integrate changes.',
346
+ contextSchema: hazeToolContextSchema,
347
+ inputSchema: remoteInput,
348
+ execute: async (input, context) => runDedupedTool('gitFetch', input, context, async () => {
349
+ try {
350
+ const root = await resolveRepoRoot();
351
+ const run = await runNetworkGit(root, ['fetch', '--no-recurse-submodules', ...(input.remote ? ['--', input.remote] : [])], context.abortSignal);
352
+ if (run.aborted)
353
+ return abortedResult('gitFetch');
354
+ if (run.code !== 0)
355
+ return networkFailure('gitFetch', run.timedOut);
356
+ return { ok: true, toolName: 'gitFetch', summary: 'Fetched remote updates.' };
357
+ }
358
+ catch (error) {
359
+ return gitFailure('gitFetch', error, 'Check the repository and remote, then retry.');
360
+ }
361
+ }),
362
+ }),
363
+ gitPull: tool({
364
+ description: 'Fetch and integrate remote changes into the current branch. Defaults to fast-forward only; use rebase or merge only when requested.',
365
+ contextSchema: hazeToolContextSchema,
366
+ inputSchema: pullInput,
367
+ execute: async (input, context) => runDedupedTool('gitPull', input, context, async () => {
368
+ try {
369
+ const root = await resolveRepoRoot();
370
+ const mode = input.mode ?? 'ff-only';
371
+ const flag = mode === 'merge' ? '--no-rebase' : mode === 'rebase' ? '--rebase' : '--ff-only';
372
+ const run = await runNetworkGit(root, ['pull', flag, '--no-recurse-submodules', ...(input.remote ? ['--', input.remote] : [])], context.abortSignal);
373
+ if (run.aborted)
374
+ return abortedResult('gitPull');
375
+ if (run.code !== 0) {
376
+ const reason = classifyPullFailure(`${run.stdout.text}\n${run.stderr.text}`);
377
+ return { ...networkFailure('gitPull', run.timedOut), ...(reason && !run.timedOut ? { error: reason } : {}), suggestedNextStep: 'Inspect repository status and upstream; resolve any conflicts or choose an appropriate integration policy before retrying.' };
378
+ }
379
+ return { ok: true, toolName: 'gitPull', summary: `Pulled using ${mode}.` };
380
+ }
381
+ catch (error) {
382
+ return gitFailure('gitPull', error, 'Check the repository and upstream, then retry.');
383
+ }
384
+ }),
385
+ }),
386
+ gitClone: tool({
387
+ description: 'Clone a remote repository into a new workspace-relative directory so its code can be inspected. Authentication is non-interactive.',
388
+ contextSchema: hazeToolContextSchema,
389
+ inputSchema: cloneInput,
390
+ execute: async (input, context) => runDedupedTool('gitClone', input, context, async () => {
391
+ try {
392
+ if (!validCloneUrl(input.url))
393
+ throw new HazeToolError('Use an HTTPS, SSH, or git:// repository URL without embedded credentials.', 'git_error', { recoverable: false });
394
+ const target = await prepareWorkspaceWritePath('gitClone', input.path, false, context);
395
+ if (target.scopedStop)
396
+ return target.scopedStop;
397
+ await target.assertWritableInsideWorkspace();
398
+ try {
399
+ await fs.lstat(target.absolutePath);
400
+ return { ok: false, toolName: 'gitClone', error: 'Destination already exists.', reasonCode: 'git_error', recoverable: true, suggestedNextStep: 'Choose a new destination.' };
401
+ }
402
+ catch (error) {
403
+ if (error.code !== 'ENOENT')
404
+ throw error;
405
+ }
406
+ const run = await runNetworkGit(workspaceRoot(), ['clone', '--no-recurse-submodules', '--', input.url, target.absolutePath], context.abortSignal);
407
+ if (run.aborted)
408
+ return abortedResult('gitClone');
409
+ if (run.code !== 0)
410
+ return networkFailure('gitClone', run.timedOut);
411
+ return { ok: true, toolName: 'gitClone', path: input.path, summary: `Cloned into ${input.path}.` };
412
+ }
413
+ catch (error) {
414
+ return gitFailure('gitClone', error, 'Check the destination and repository URL, then retry.');
415
+ }
416
+ }),
417
+ }),
418
+ gitStage: tool({
419
+ description: 'Stage workspace files (git add). Mutating git operation on the workspace repository.',
420
+ contextSchema: hazeToolContextSchema,
421
+ inputSchema: stageInput,
422
+ execute: async (input, context) => runDedupedTool('gitStage', input, context, async () => {
423
+ try {
424
+ const root = await resolveRepoRoot();
425
+ const confined = input.paths.map(p => confinePath(root, p));
426
+ const run = await runGit(root, (input.all ?? false) ? ['add', '-A'] : ['add', '--', ...confined], context.abortSignal);
427
+ if (run.aborted)
428
+ return abortedResult('gitStage');
429
+ if (run.code !== 0)
430
+ return gitError('gitStage', run, 'Check the paths, then retry.');
431
+ return { ok: true, toolName: 'gitStage', summary: (input.all ?? false) ? 'Staged all changes.' : `Staged: ${confined.join(', ')}` };
432
+ }
433
+ catch (error) {
434
+ return gitFailure('gitStage', error, 'Retry gitStage with valid workspace-relative paths.');
435
+ }
436
+ }),
437
+ }),
438
+ gitCommit: tool({
439
+ description: 'Create a commit in the workspace repository (git commit). Mutating git operation.',
440
+ contextSchema: hazeToolContextSchema,
441
+ inputSchema: commitInput,
442
+ execute: async (input, context) => runDedupedTool('gitCommit', input, context, async () => {
443
+ try {
444
+ const root = await resolveRepoRoot();
445
+ const run = await runGit(root, ['commit', ...((input.all ?? false) ? ['-a'] : []), '-m', input.message], context.abortSignal);
446
+ if (run.aborted)
447
+ return abortedResult('gitCommit');
448
+ if (run.code !== 0)
449
+ return gitError('gitCommit', run, 'Stage changes first (gitStage), resolve conflicts, then retry.');
450
+ return { ok: true, toolName: 'gitCommit', summary: run.stdout.split('\n')[0] ?? 'committed' };
451
+ }
452
+ catch (error) {
453
+ return gitFailure('gitCommit', error, 'Stage changes with gitStage, then retry gitCommit.');
454
+ }
455
+ }),
456
+ }),
457
+ gitBranchManage: tool({
458
+ description: 'Create, rename, checkout, or delete a branch in the workspace repository. Mutating git operation.',
459
+ contextSchema: hazeToolContextSchema,
460
+ inputSchema: branchManageInput,
461
+ execute: async (input, context) => runDedupedTool('gitBranchManage', input, context, async () => {
462
+ try {
463
+ assertRefName('gitBranchManage', 'name', input.name);
464
+ assertRefName('gitBranchManage', 'newName', input.newName);
465
+ assertRefName('gitBranchManage', 'startPoint', input.startPoint);
466
+ const root = await resolveRepoRoot();
467
+ const args = (() => {
468
+ switch (input.action) {
469
+ case 'create': return ['branch', input.name, ...(input.startPoint ? [input.startPoint] : [])];
470
+ case 'delete': return ['branch', '-d', input.name];
471
+ case 'rename': return ['branch', '-m', input.name, ...(input.newName ? [input.newName] : [])];
472
+ case 'checkout': return ['checkout', input.name];
473
+ }
474
+ })();
475
+ const run = await runGit(root, args, context.abortSignal);
476
+ if (run.aborted)
477
+ return abortedResult('gitBranchManage');
478
+ if (run.code !== 0)
479
+ return gitError('gitBranchManage', run, 'Check the branch name/action, then retry.');
480
+ return { ok: true, toolName: 'gitBranchManage', summary: `${input.action} ${input.name}${input.newName ? ` -> ${input.newName}` : ''}` };
481
+ }
482
+ catch (error) {
483
+ return gitFailure('gitBranchManage', error, 'Retry gitBranchManage with a valid action and branch name.');
484
+ }
485
+ }),
486
+ }),
487
+ gitRebase: tool({
488
+ description: 'Rebase the current branch onto an explicit target (git rebase). History-rewriting: runs only when explicitly requested.',
489
+ contextSchema: hazeToolContextSchema,
490
+ inputSchema: rebaseInput,
491
+ execute: async (input, context) => runDedupedTool('gitRebase', input, context, async () => {
492
+ try {
493
+ assertRefName('gitRebase', 'onto', input.onto);
494
+ const root = await resolveRepoRoot();
495
+ const run = await runGit(root, ['rebase', input.onto], context.abortSignal);
496
+ if (run.aborted)
497
+ return abortedResult('gitRebase');
498
+ if (run.code !== 0)
499
+ return gitError('gitRebase', run, 'Resolve conflicts or abort the rebase via shell, then retry.');
500
+ return { ok: true, toolName: 'gitRebase', summary: `Rebased onto ${input.onto}.` };
501
+ }
502
+ catch (error) {
503
+ return gitFailure('gitRebase', error, 'Retry gitRebase with a valid target.');
504
+ }
505
+ }),
506
+ }),
507
+ gitReset: tool({
508
+ description: 'Reset the current branch to an explicit target with an explicit mode (git reset). History/working-tree rewriting (hard): runs only when explicitly requested.',
509
+ contextSchema: hazeToolContextSchema,
510
+ inputSchema: resetInput,
511
+ execute: async (input, context) => runDedupedTool('gitReset', input, context, async () => {
512
+ try {
513
+ assertRefName('gitReset', 'target', input.target);
514
+ const root = await resolveRepoRoot();
515
+ const run = await runGit(root, ['reset', `--${input.mode}`, input.target], context.abortSignal);
516
+ if (run.aborted)
517
+ return abortedResult('gitReset');
518
+ if (run.code !== 0)
519
+ return gitError('gitReset', run, 'Check the target, then retry.');
520
+ return { ok: true, toolName: 'gitReset', summary: `Reset --${input.mode} to ${input.target}.` };
521
+ }
522
+ catch (error) {
523
+ return gitFailure('gitReset', error, 'Retry gitReset with a valid target and mode.');
524
+ }
525
+ }),
526
+ }),
527
+ };
@@ -0,0 +1,22 @@
1
+ export interface GraphAffectedNeighbor {
2
+ symbol: string;
3
+ kind: string;
4
+ /** e.g. `calls [INFERRED] at src/foo.ts:42` */
5
+ via: string;
6
+ }
7
+ export interface PostMutationGraphResult {
8
+ ok: boolean;
9
+ stale: boolean;
10
+ files: Array<{
11
+ path: string;
12
+ affectedNeighbors: GraphAffectedNeighbor[];
13
+ }>;
14
+ truncated: boolean;
15
+ }
16
+ export type PostMutationGraphAdvisory = (paths: readonly string[]) => Promise<PostMutationGraphResult | undefined>;
17
+ /**
18
+ * Build the advisory hook. Self-disables (returns undefined) when no graph
19
+ * exists yet — building one is an explicit model/user action, never a
20
+ * side effect of a mutation.
21
+ */
22
+ export declare function createPostMutationGraphAdvisory(): PostMutationGraphAdvisory;
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Bounded graph advisory attached to successful file-mutation results, the
3
+ * graph-side twin of the automatic LSP diagnostics hook: after editing a file,
4
+ * the model immediately sees which symbols elsewhere depend on it (reverse
5
+ * call/import edges with sites) without another tool call, plus a staleness
6
+ * note for the touched file.
7
+ *
8
+ * Advisory only — it orients validation scope and follow-up edits; it never
9
+ * counts as validation evidence and never blocks a mutation.
10
+ */
11
+ import { workspaceRoot } from '../../utils/path.js';
12
+ import { buildGraphIndex } from '../../core/graph/model.js';
13
+ import { graphStoreFor, readGraph } from '../../core/graph/store.js';
14
+ const ADVISORY_FILE_LIMIT = 8;
15
+ const ADVISORY_PER_FILE = 5;
16
+ const ADVISORY_TOTAL = 12;
17
+ /**
18
+ * Build the advisory hook. Self-disables (returns undefined) when no graph
19
+ * exists yet — building one is an explicit model/user action, never a
20
+ * side effect of a mutation.
21
+ */
22
+ export function createPostMutationGraphAdvisory() {
23
+ return async (paths) => {
24
+ const uniquePaths = [...new Set(paths)].slice(0, ADVISORY_FILE_LIMIT);
25
+ if (uniquePaths.length === 0)
26
+ return undefined;
27
+ const store = graphStoreFor(workspaceRoot());
28
+ let graph;
29
+ try {
30
+ graph = await readGraph(store);
31
+ }
32
+ catch {
33
+ return undefined; // Unreadable graph: silent, the tools surface it on demand.
34
+ }
35
+ if (!graph)
36
+ return undefined;
37
+ const index = buildGraphIndex(graph);
38
+ const files = [];
39
+ let remaining = ADVISORY_TOTAL;
40
+ for (const filePath of uniquePaths) {
41
+ if (remaining <= 0)
42
+ break;
43
+ const normalized = filePath.replace(/\\/g, '/');
44
+ // Symbol nodes defined in the mutated file.
45
+ const owned = graph.nodes.filter(node => node.kind !== 'file' && node.file === normalized);
46
+ const neighbors = [];
47
+ const seen = new Set();
48
+ for (const symbol of owned) {
49
+ for (const edge of index.in.get(symbol.id) ?? []) {
50
+ if (edge.relation === 'defines')
51
+ continue; // the file->symbol edge, not a dependency
52
+ const source = index.nodes.get(edge.source);
53
+ if (!source || source.file === normalized || seen.has(source.id))
54
+ continue;
55
+ seen.add(source.id);
56
+ neighbors.push({ symbol: source.label, kind: source.kind, via: `${edge.relation} [${edge.confidence}] at ${edge.file ?? source.file}:${edge.line ?? '?'}` });
57
+ remaining -= 1;
58
+ if (neighbors.length >= ADVISORY_PER_FILE || remaining <= 0)
59
+ break;
60
+ }
61
+ if (neighbors.length >= ADVISORY_PER_FILE || remaining <= 0)
62
+ break;
63
+ }
64
+ files.push({ path: normalized, affectedNeighbors: neighbors });
65
+ }
66
+ return { ok: true, stale: true, files, truncated: remaining <= 0 || uniquePaths.length < new Set(paths).size };
67
+ };
68
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * The code-graph tool set (`graphQuery`, `graphExplain`, `graphPath`,
3
+ * `graphAffected`, `graphRebuild`) over the persistent workspace symbol graph
4
+ * built by `core/graph`.
5
+ *
6
+ * The graph is a deterministic AST-derived map of the codebase: querying it
7
+ * is cheap and bounded, edges carry EXTRACTED/INFERRED confidence, and every
8
+ * result annotates staleness so the model knows when the map lags the working
9
+ * tree. Graph output is orientation and retrieval — never validation
10
+ * evidence.
11
+ */
12
+ import { type ToolSet } from 'ai';
13
+ export declare const graphTools: ToolSet;