@flyingrobots/graft 0.3.5 → 0.5.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 (111) hide show
  1. package/ARCHITECTURE.md +386 -0
  2. package/CHANGELOG.md +69 -0
  3. package/CODE_OF_CONDUCT.md +65 -0
  4. package/README.md +153 -17
  5. package/bin/graft.js +4 -11
  6. package/docs/ADVANCED_GUIDE.md +49 -0
  7. package/docs/CLI.md +43 -0
  8. package/docs/GUIDE.md +321 -32
  9. package/docs/MCP.md +44 -0
  10. package/package.json +17 -4
  11. package/src/adapters/node-fs.ts +4 -0
  12. package/src/adapters/node-git.ts +47 -0
  13. package/src/adapters/node-process-runner.ts +27 -0
  14. package/src/cli/index-cmd.ts +86 -0
  15. package/src/cli/init.ts +808 -57
  16. package/src/cli/main.ts +437 -0
  17. package/src/contracts/capabilities.ts +341 -0
  18. package/src/contracts/causal-ontology.ts +622 -0
  19. package/src/contracts/causal-surface-next-action.ts +18 -0
  20. package/src/contracts/output-schemas.ts +1169 -0
  21. package/src/git/diff.ts +25 -21
  22. package/src/git/target-git-hook-bootstrap.ts +56 -0
  23. package/src/hooks/posttooluse-read.ts +21 -74
  24. package/src/hooks/pretooluse-read.ts +20 -56
  25. package/src/hooks/read-governor.ts +95 -0
  26. package/src/hooks/read-messages.ts +53 -0
  27. package/src/mcp/burden.ts +123 -0
  28. package/src/mcp/cache.ts +51 -0
  29. package/src/mcp/cached-file.ts +10 -8
  30. package/src/mcp/context.ts +67 -2
  31. package/src/mcp/daemon-control-plane.ts +554 -0
  32. package/src/mcp/daemon-job-scheduler.ts +279 -0
  33. package/src/mcp/daemon-repos.ts +216 -0
  34. package/src/mcp/daemon-server.ts +396 -0
  35. package/src/mcp/daemon-worker-pool.ts +310 -0
  36. package/src/mcp/daemon-worker-process.ts +52 -0
  37. package/src/mcp/metrics.ts +108 -1
  38. package/src/mcp/monitor-tick-job.ts +99 -0
  39. package/src/mcp/persisted-local-history.ts +1246 -0
  40. package/src/mcp/persistent-monitor-runtime.ts +549 -0
  41. package/src/mcp/policy.ts +84 -0
  42. package/src/mcp/receipt.ts +82 -12
  43. package/src/mcp/repo-concurrency.ts +318 -0
  44. package/src/mcp/repo-state.ts +777 -0
  45. package/src/mcp/repo-tool-job.ts +302 -0
  46. package/src/mcp/run-capture-config.ts +33 -0
  47. package/src/mcp/runtime-causal-context.ts +72 -0
  48. package/src/mcp/runtime-observability.ts +219 -0
  49. package/src/mcp/runtime-staged-target.ts +161 -0
  50. package/src/mcp/runtime-workspace-overlay.ts +255 -0
  51. package/src/mcp/semantic-transition-guidance.ts +60 -0
  52. package/src/mcp/semantic-transition-summary.ts +130 -0
  53. package/src/mcp/server.ts +704 -45
  54. package/src/mcp/stdio-server.ts +12 -0
  55. package/src/mcp/stdio.ts +2 -5
  56. package/src/mcp/tools/activity-view.ts +325 -0
  57. package/src/mcp/tools/causal-attach.ts +67 -0
  58. package/src/mcp/tools/causal-status.ts +58 -0
  59. package/src/mcp/tools/changed-since.ts +13 -11
  60. package/src/mcp/tools/code-find.ts +164 -0
  61. package/src/mcp/tools/code-refs.ts +466 -0
  62. package/src/mcp/tools/code-show.ts +252 -0
  63. package/src/mcp/tools/daemon-monitors.ts +14 -0
  64. package/src/mcp/tools/daemon-repos.ts +22 -0
  65. package/src/mcp/tools/daemon-sessions.ts +14 -0
  66. package/src/mcp/tools/daemon-status.ts +12 -0
  67. package/src/mcp/tools/doctor.ts +45 -2
  68. package/src/mcp/tools/explain.ts +4 -0
  69. package/src/mcp/tools/file-outline.ts +7 -3
  70. package/src/mcp/tools/git-files.ts +73 -0
  71. package/src/mcp/tools/graft-diff.ts +12 -4
  72. package/src/mcp/tools/map.ts +136 -0
  73. package/src/mcp/tools/monitor-pause.ts +18 -0
  74. package/src/mcp/tools/monitor-resume.ts +18 -0
  75. package/src/mcp/tools/monitor-start.ts +20 -0
  76. package/src/mcp/tools/monitor-stop.ts +18 -0
  77. package/src/mcp/tools/precision-match.ts +51 -0
  78. package/src/mcp/tools/precision-query.ts +127 -0
  79. package/src/mcp/tools/precision.ts +312 -0
  80. package/src/mcp/tools/run-capture.ts +126 -44
  81. package/src/mcp/tools/safe-read.ts +14 -12
  82. package/src/mcp/tools/since.ts +49 -0
  83. package/src/mcp/tools/state.ts +11 -3
  84. package/src/mcp/tools/stats.ts +5 -1
  85. package/src/mcp/tools/workspace-authorizations.ts +14 -0
  86. package/src/mcp/tools/workspace-authorize.ts +20 -0
  87. package/src/mcp/tools/workspace-bind.ts +25 -0
  88. package/src/mcp/tools/workspace-rebind.ts +25 -0
  89. package/src/mcp/tools/workspace-revoke.ts +18 -0
  90. package/src/mcp/tools/workspace-status.ts +12 -0
  91. package/src/mcp/warp-pool.ts +36 -0
  92. package/src/mcp/workspace-router.ts +984 -0
  93. package/src/operations/file-outline.ts +12 -2
  94. package/src/operations/graft-diff.ts +56 -10
  95. package/src/operations/safe-read.ts +27 -4
  96. package/src/operations/state.ts +6 -9
  97. package/src/parser/lang.ts +19 -3
  98. package/src/parser/outline.ts +191 -2
  99. package/src/parser/types.ts +9 -1
  100. package/src/policy/types.ts +4 -3
  101. package/src/ports/filesystem.ts +1 -0
  102. package/src/ports/git.ts +16 -0
  103. package/src/ports/process-runner.ts +22 -0
  104. package/src/release/security-gate.ts +102 -0
  105. package/src/session/tracker.ts +31 -0
  106. package/src/version.ts +3 -0
  107. package/src/warp/indexer.ts +513 -0
  108. package/src/warp/observers.ts +105 -0
  109. package/src/warp/open.ts +31 -0
  110. package/src/warp/plumbing.d.ts +15 -0
  111. package/src/warp/writer-id.ts +30 -0
@@ -0,0 +1,164 @@
1
+ import { z } from "zod";
2
+ import type { ToolDefinition, ToolContext, ToolHandler } from "../context.js";
3
+ import { GitFileQuery, listGitFiles } from "./git-files.js";
4
+ import {
5
+ evaluatePrecisionPolicy,
6
+ getIndexedCommitCeilings,
7
+ loadFileContent,
8
+ normalizeRepoPath,
9
+ PrecisionSearchRequest,
10
+ type PrecisionSymbolMatch,
11
+ resolveGitRef,
12
+ searchLiveSymbols,
13
+ searchWarpSymbols,
14
+ } from "./precision.js";
15
+
16
+ class CodeFindRequest {
17
+ readonly query: string;
18
+ readonly kind?: string;
19
+ readonly dirPath: string;
20
+
21
+ constructor(args: Record<string, unknown>, projectRoot: string) {
22
+ const query = args["query"];
23
+ const kind = args["kind"];
24
+ const rawPath = args["path"];
25
+ if (typeof query !== "string" || query.trim().length === 0) {
26
+ throw new Error("CodeFindRequest: query must be a non-empty string");
27
+ }
28
+ if (kind !== undefined && typeof kind !== "string") {
29
+ throw new Error("CodeFindRequest: kind must be a string when provided");
30
+ }
31
+ if (rawPath !== undefined && typeof rawPath !== "string") {
32
+ throw new Error("CodeFindRequest: path must be a string when provided");
33
+ }
34
+
35
+ this.query = query.trim();
36
+ if (kind !== undefined && kind.trim().length > 0) this.kind = kind.trim();
37
+ this.dirPath = rawPath !== undefined && rawPath.trim().length > 0
38
+ ? normalizeRepoPath(projectRoot, rawPath)
39
+ : "";
40
+ Object.freeze(this);
41
+ }
42
+
43
+ toPrecisionSearchRequest(): PrecisionSearchRequest {
44
+ return new PrecisionSearchRequest({
45
+ query: this.query,
46
+ ...(this.kind !== undefined ? { kind: this.kind } : {}),
47
+ ...(this.dirPath.length > 0 ? { pathPrefix: this.dirPath } : {}),
48
+ });
49
+ }
50
+
51
+ toProjectFileQuery(projectRoot: string): GitFileQuery {
52
+ return GitFileQuery.project(projectRoot, this.dirPath);
53
+ }
54
+ }
55
+
56
+ interface CodeFindOptions {
57
+ readonly allowWarp: boolean;
58
+ }
59
+
60
+ export async function runCodeFind(
61
+ ctx: ToolContext,
62
+ args: Record<string, unknown>,
63
+ options: CodeFindOptions,
64
+ ) {
65
+ const request = new CodeFindRequest(args, ctx.projectRoot);
66
+ const precisionRequest = request.toPrecisionSearchRequest();
67
+ const repoState = ctx.getRepoState();
68
+ const layer = repoState.dirty ? "workspace_overlay" : "ref_view";
69
+
70
+ let allMatches: PrecisionSymbolMatch[] = [];
71
+ let source: "warp" | "live" = "live";
72
+
73
+ if (options.allowWarp && !repoState.dirty) {
74
+ try {
75
+ const warp = await ctx.getWarp();
76
+ const ceilings = await getIndexedCommitCeilings(warp);
77
+ const headSha = await resolveGitRef("HEAD", ctx.git, ctx.projectRoot);
78
+ if (ceilings.has(headSha)) {
79
+ allMatches = await searchWarpSymbols(warp, precisionRequest);
80
+ source = "warp";
81
+ }
82
+ } catch {
83
+ source = "live";
84
+ }
85
+ }
86
+
87
+ if (source === "live") {
88
+ allMatches = await searchLiveSymbols(
89
+ ctx,
90
+ (await listGitFiles(request.toProjectFileQuery(ctx.projectRoot), ctx.git)).paths,
91
+ precisionRequest,
92
+ );
93
+ }
94
+
95
+ const visibleMatches: PrecisionSymbolMatch[] = [];
96
+ const fileCache = new Map<string, string>();
97
+ let firstRefusal:
98
+ | {
99
+ path: string;
100
+ reason: string;
101
+ reasonDetail: string;
102
+ next: readonly string[];
103
+ actual: { lines: number; bytes: number };
104
+ }
105
+ | undefined;
106
+
107
+ for (const match of allMatches) {
108
+ let content = fileCache.get(match.path);
109
+ if (content === undefined) {
110
+ const loaded = await loadFileContent(ctx, match.path);
111
+ if (loaded === null) continue;
112
+ fileCache.set(match.path, loaded);
113
+ content = loaded;
114
+ }
115
+
116
+ const refusal = evaluatePrecisionPolicy(ctx, match.path, content);
117
+ if (refusal !== null) {
118
+ firstRefusal ??= refusal;
119
+ continue;
120
+ }
121
+ visibleMatches.push(match);
122
+ }
123
+
124
+ if (visibleMatches.length === 0 && firstRefusal !== undefined) {
125
+ return ctx.respond("code_find", {
126
+ query: request.query,
127
+ kind: request.kind ?? null,
128
+ path: firstRefusal.path,
129
+ projection: "refused",
130
+ reason: firstRefusal.reason,
131
+ reasonDetail: firstRefusal.reasonDetail,
132
+ next: [...firstRefusal.next],
133
+ actual: firstRefusal.actual,
134
+ source,
135
+ layer,
136
+ });
137
+ }
138
+
139
+ return ctx.respond("code_find", {
140
+ query: request.query,
141
+ kind: request.kind ?? null,
142
+ matches: visibleMatches,
143
+ total: visibleMatches.length,
144
+ source,
145
+ layer,
146
+ });
147
+ }
148
+
149
+ export const codeFindTool: ToolDefinition = {
150
+ name: "code_find",
151
+ description:
152
+ "Search for symbols across the project by approximate name or glob " +
153
+ "pattern. Returns matches with file path, kind, signature, and " +
154
+ "line range. Use code_show to read the source of a specific match.",
155
+ schema: {
156
+ query: z.string(),
157
+ kind: z.string().optional(),
158
+ path: z.string().optional(),
159
+ },
160
+ policyCheck: true,
161
+ createHandler(ctx: ToolContext): ToolHandler {
162
+ return (args) => runCodeFind(ctx, args, { allowWarp: true });
163
+ },
164
+ };
@@ -0,0 +1,466 @@
1
+ import * as path from "node:path";
2
+ import { z } from "zod";
3
+ import type { ToolDefinition, ToolContext, ToolHandler } from "../context.js";
4
+ import type { ProcessRunner } from "../../ports/process-runner.js";
5
+ import { GitFileQuery, listGitFiles } from "./git-files.js";
6
+ import {
7
+ evaluatePrecisionPolicy,
8
+ loadFileContent,
9
+ normalizeRepoPath,
10
+ } from "./precision.js";
11
+
12
+ const CODE_REFS_MODES = ["text", "import", "call", "property"] as const;
13
+
14
+ type CodeRefsMode = typeof CODE_REFS_MODES[number];
15
+ type SearchEngine = "ripgrep" | "grep";
16
+
17
+ class CodeRefsRequest {
18
+ readonly query: string;
19
+ readonly mode: CodeRefsMode;
20
+ readonly dirPath: string;
21
+
22
+ constructor(args: Record<string, unknown>, projectRoot: string) {
23
+ const rawQuery = args["query"];
24
+ const rawMode = args["mode"];
25
+ const rawPath = args["path"];
26
+
27
+ if (typeof rawQuery !== "string" || rawQuery.trim().length === 0) {
28
+ throw new Error("CodeRefsRequest: query must be a non-empty string");
29
+ }
30
+ if (rawMode !== undefined && (typeof rawMode !== "string" || !CODE_REFS_MODES.includes(rawMode as CodeRefsMode))) {
31
+ throw new Error("CodeRefsRequest: mode must be one of text, import, call, property");
32
+ }
33
+ if (rawPath !== undefined && typeof rawPath !== "string") {
34
+ throw new Error("CodeRefsRequest: path must be a string when provided");
35
+ }
36
+
37
+ this.query = rawQuery.trim();
38
+ this.mode = inferCodeRefsMode(this.query, rawMode as CodeRefsMode | undefined);
39
+ this.dirPath = normalizeScopePath(projectRoot, rawPath);
40
+ Object.freeze(this);
41
+ }
42
+
43
+ toProjectFileQuery(projectRoot: string): GitFileQuery {
44
+ return GitFileQuery.project(projectRoot, this.dirPath);
45
+ }
46
+
47
+ scope(): string {
48
+ return this.dirPath.length > 0 ? this.dirPath : ".";
49
+ }
50
+ }
51
+
52
+ class CodeRefsMatch {
53
+ readonly path: string;
54
+ readonly line: number;
55
+ readonly column?: number;
56
+ readonly preview: string;
57
+
58
+ constructor(opts: {
59
+ path: string;
60
+ line: number;
61
+ column?: number;
62
+ preview: string;
63
+ }) {
64
+ if (opts.path.trim().length === 0) {
65
+ throw new Error("CodeRefsMatch: path must be non-empty");
66
+ }
67
+ if (!Number.isInteger(opts.line) || opts.line < 1) {
68
+ throw new Error("CodeRefsMatch: line must be an integer >= 1");
69
+ }
70
+ if (opts.column !== undefined && (!Number.isInteger(opts.column) || opts.column < 1)) {
71
+ throw new Error("CodeRefsMatch: column must be an integer >= 1");
72
+ }
73
+ if (opts.preview.length === 0) {
74
+ throw new Error("CodeRefsMatch: preview must be non-empty");
75
+ }
76
+
77
+ this.path = opts.path.trim();
78
+ this.line = opts.line;
79
+ if (opts.column !== undefined) this.column = opts.column;
80
+ this.preview = opts.preview;
81
+ Object.freeze(this);
82
+ }
83
+ }
84
+
85
+ class CodeRefsPattern {
86
+ readonly mode: CodeRefsMode;
87
+ readonly query: string;
88
+ readonly pattern: string;
89
+ readonly fixedStrings: boolean;
90
+ readonly highlight: string;
91
+
92
+ constructor(opts: {
93
+ mode: CodeRefsMode;
94
+ query: string;
95
+ pattern: string;
96
+ fixedStrings: boolean;
97
+ highlight: string;
98
+ }) {
99
+ this.mode = opts.mode;
100
+ this.query = opts.query;
101
+ this.pattern = opts.pattern;
102
+ this.fixedStrings = opts.fixedStrings;
103
+ this.highlight = opts.highlight;
104
+ Object.freeze(this);
105
+ }
106
+ }
107
+
108
+ function inferCodeRefsMode(query: string, explicitMode?: CodeRefsMode): CodeRefsMode {
109
+ if (explicitMode !== undefined) return explicitMode;
110
+ if (query.startsWith(".")) return "property";
111
+ if (query.endsWith("(")) return "call";
112
+ return "text";
113
+ }
114
+
115
+ function normalizeScopePath(projectRoot: string, rawPath: unknown): string {
116
+ if (typeof rawPath !== "string" || rawPath.trim().length === 0) {
117
+ return "";
118
+ }
119
+
120
+ const normalized = normalizeRepoPath(projectRoot, rawPath);
121
+ if (path.isAbsolute(normalized)) {
122
+ throw new Error(`Path must stay inside the repository: ${rawPath}`);
123
+ }
124
+
125
+ const resolved = path.resolve(projectRoot, normalized);
126
+ const rel = path.relative(projectRoot, resolved);
127
+ if (rel.startsWith("..")) {
128
+ throw new Error(`Path must stay inside the repository: ${rawPath}`);
129
+ }
130
+
131
+ return rel === "" || rel === "." ? "" : rel;
132
+ }
133
+
134
+ function escapeRegex(literal: string): string {
135
+ return literal.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
136
+ }
137
+
138
+ function buildCodeRefsPattern(request: CodeRefsRequest): CodeRefsPattern {
139
+ if (request.mode === "text") {
140
+ return new CodeRefsPattern({
141
+ mode: request.mode,
142
+ query: request.query,
143
+ pattern: request.query,
144
+ fixedStrings: true,
145
+ highlight: request.query,
146
+ });
147
+ }
148
+
149
+ if (request.mode === "import") {
150
+ const escaped = escapeRegex(request.query);
151
+ return new CodeRefsPattern({
152
+ mode: request.mode,
153
+ query: request.query,
154
+ pattern: `(\\bimport\\b.*\\b${escaped}\\b|\\bexport\\b.*\\b${escaped}\\b.*\\bfrom\\b)`,
155
+ fixedStrings: false,
156
+ highlight: request.query,
157
+ });
158
+ }
159
+
160
+ if (request.mode === "call") {
161
+ const normalizedQuery = request.query.endsWith("(")
162
+ ? request.query.slice(0, -1).trim()
163
+ : request.query;
164
+ const escaped = escapeRegex(normalizedQuery);
165
+ return new CodeRefsPattern({
166
+ mode: request.mode,
167
+ query: normalizedQuery,
168
+ pattern: `\\b${escaped}\\s*\\(`,
169
+ fixedStrings: false,
170
+ highlight: normalizedQuery,
171
+ });
172
+ }
173
+
174
+ const propertyName = request.query.startsWith(".")
175
+ ? request.query.slice(1)
176
+ : request.query.includes(".")
177
+ ? request.query.split(".").at(-1) ?? request.query
178
+ : request.query;
179
+ const escaped = escapeRegex(propertyName);
180
+ return new CodeRefsPattern({
181
+ mode: request.mode,
182
+ query: propertyName,
183
+ pattern: `[?]?\\.${escaped}\\b`,
184
+ fixedStrings: false,
185
+ highlight: `.${propertyName}`,
186
+ });
187
+ }
188
+
189
+ function buildRipgrepArgs(pattern: CodeRefsPattern, filePaths: readonly string[]): string[] {
190
+ return [
191
+ "--no-heading",
192
+ "--line-number",
193
+ "--column",
194
+ "--color",
195
+ "never",
196
+ "--with-filename",
197
+ ...(pattern.fixedStrings ? ["-F"] : []),
198
+ "-e",
199
+ pattern.pattern,
200
+ "--",
201
+ ...filePaths,
202
+ ];
203
+ }
204
+
205
+ function buildGrepArgs(pattern: CodeRefsPattern, filePaths: readonly string[]): string[] {
206
+ return [
207
+ "-nH",
208
+ "-F",
209
+ pattern.highlight,
210
+ "--",
211
+ ...filePaths,
212
+ ];
213
+ }
214
+
215
+ function computeColumn(preview: string, highlight: string): number | undefined {
216
+ const index = preview.indexOf(highlight);
217
+ return index >= 0 ? index + 1 : undefined;
218
+ }
219
+
220
+ function parseRipgrepLine(line: string): CodeRefsMatch | null {
221
+ const match = /^(.*?):(\d+):(\d+):(.*)$/.exec(line);
222
+ if (match === null) return null;
223
+ const filePath = match[1];
224
+ const rawLine = match[2];
225
+ const rawColumn = match[3];
226
+ const preview = match[4];
227
+ if (filePath === undefined || rawLine === undefined || rawColumn === undefined || preview === undefined) {
228
+ return null;
229
+ }
230
+ return new CodeRefsMatch({
231
+ path: filePath,
232
+ line: Number(rawLine),
233
+ column: Number(rawColumn),
234
+ preview,
235
+ });
236
+ }
237
+
238
+ function parseGrepLine(line: string, highlight: string): CodeRefsMatch | null {
239
+ const match = /^(.*?):(\d+):(.*)$/.exec(line);
240
+ if (match === null) return null;
241
+ const filePath = match[1];
242
+ const rawLine = match[2];
243
+ const preview = match[3];
244
+ if (filePath === undefined || rawLine === undefined || preview === undefined) {
245
+ return null;
246
+ }
247
+ const column = computeColumn(preview, highlight);
248
+ return new CodeRefsMatch({
249
+ path: filePath,
250
+ line: Number(rawLine),
251
+ ...(column !== undefined ? { column } : {}),
252
+ preview,
253
+ });
254
+ }
255
+
256
+ function parseSearchOutput(
257
+ stdout: string,
258
+ parser: (line: string, highlight: string) => CodeRefsMatch | null,
259
+ highlight: string,
260
+ ): CodeRefsMatch[] {
261
+ if (stdout.trim().length === 0) return [];
262
+ return stdout
263
+ .trim()
264
+ .split("\n")
265
+ .map((line) => parser(line, highlight))
266
+ .filter((match): match is CodeRefsMatch => match !== null);
267
+ }
268
+
269
+ function parseRipgrepOutput(stdout: string): CodeRefsMatch[] {
270
+ return parseSearchOutput(stdout, (line) => parseRipgrepLine(line), "");
271
+ }
272
+
273
+ function isRelevantReferencePreview(pattern: CodeRefsPattern, preview: string): boolean {
274
+ const trimmed = preview.trim();
275
+
276
+ if (pattern.mode === "text") {
277
+ return true;
278
+ }
279
+
280
+ if (pattern.mode === "import") {
281
+ return /\bimport\b/.test(trimmed) || (/\bexport\b/.test(trimmed) && /\bfrom\b/.test(trimmed));
282
+ }
283
+
284
+ if (pattern.mode === "call") {
285
+ if (/^\s*import\b/.test(trimmed)) {
286
+ return false;
287
+ }
288
+ if (/^\s*export\b/.test(trimmed) && /\bfrom\b/.test(trimmed)) {
289
+ return false;
290
+ }
291
+
292
+ const escaped = escapeRegex(pattern.query);
293
+ const functionDeclaration = new RegExp(`\\bfunction\\s+${escaped}\\s*\\(`);
294
+ if (functionDeclaration.test(trimmed)) {
295
+ return false;
296
+ }
297
+
298
+ const methodDeclaration = new RegExp(
299
+ `^(?:export\\s+)?(?:async\\s+)?${escaped}\\s*\\([^)]*\\)\\s*(?::[^=]+)?\\{`,
300
+ );
301
+ return !methodDeclaration.test(trimmed);
302
+ }
303
+
304
+ return trimmed.includes(`.${pattern.query}`) || trimmed.includes(`?.${pattern.query}`);
305
+ }
306
+
307
+ function filterReferenceMatches(
308
+ matches: readonly CodeRefsMatch[],
309
+ pattern: CodeRefsPattern,
310
+ ): CodeRefsMatch[] {
311
+ return matches.filter((match) => isRelevantReferencePreview(pattern, match.preview));
312
+ }
313
+
314
+ function runSearchCommand(
315
+ command: string,
316
+ args: readonly string[],
317
+ cwd: string,
318
+ process: ProcessRunner,
319
+ ): {
320
+ status: number | null;
321
+ stdout: string;
322
+ stderr: string;
323
+ error?: Error;
324
+ } {
325
+ return process.run({ command, args, cwd });
326
+ }
327
+
328
+ function runTextFallbackSearch(
329
+ projectRoot: string,
330
+ pattern: CodeRefsPattern,
331
+ filePaths: readonly string[],
332
+ process: ProcessRunner,
333
+ ): {
334
+ engine: SearchEngine;
335
+ matches: readonly CodeRefsMatch[];
336
+ } {
337
+ if (filePaths.length === 0) {
338
+ return { engine: "ripgrep", matches: [] };
339
+ }
340
+
341
+ const rg = runSearchCommand("rg", buildRipgrepArgs(pattern, filePaths), projectRoot, process);
342
+ if (rg.error === undefined) {
343
+ if (rg.status === 0) {
344
+ return {
345
+ engine: "ripgrep",
346
+ matches: filterReferenceMatches(parseRipgrepOutput(rg.stdout), pattern),
347
+ };
348
+ }
349
+ if (rg.status === 1) {
350
+ return { engine: "ripgrep", matches: [] };
351
+ }
352
+ throw new Error(`ripgrep search failed: ${rg.stderr.trim()}`);
353
+ }
354
+
355
+ const grep = runSearchCommand("grep", buildGrepArgs(pattern, filePaths), projectRoot, process);
356
+ if (grep.error === undefined) {
357
+ if (grep.status === 0) {
358
+ return {
359
+ engine: "grep",
360
+ matches: filterReferenceMatches(
361
+ parseSearchOutput(grep.stdout, parseGrepLine, pattern.highlight),
362
+ pattern,
363
+ ),
364
+ };
365
+ }
366
+ if (grep.status === 1) {
367
+ return { engine: "grep", matches: [] };
368
+ }
369
+ throw new Error(`grep search failed: ${grep.stderr.trim()}`);
370
+ }
371
+
372
+ const rgMessage = rg.error instanceof Error ? rg.error.message : String(rg.error);
373
+ const grepMessage = grep.error instanceof Error ? grep.error.message : String(grep.error);
374
+ throw new Error(`reference search failed: ripgrep unavailable (${rgMessage}); grep unavailable (${grepMessage})`);
375
+ }
376
+
377
+ export const codeRefsTool: ToolDefinition = {
378
+ name: "code_refs",
379
+ description:
380
+ "Search for import sites, callsites, property access, or literal text " +
381
+ "references across the working tree. Returns explicit text-fallback " +
382
+ "matches with the engine, pattern, and scope used.",
383
+ schema: {
384
+ query: z.string(),
385
+ mode: z.enum(CODE_REFS_MODES).optional(),
386
+ path: z.string().optional(),
387
+ },
388
+ createHandler(ctx: ToolContext): ToolHandler {
389
+ return async (args) => {
390
+ const request = new CodeRefsRequest(args, ctx.projectRoot);
391
+ const pattern = buildCodeRefsPattern(request);
392
+ const repoState = ctx.getRepoState();
393
+ const layer = repoState.dirty ? "workspace_overlay" : "ref_view";
394
+ const filePaths = (await listGitFiles(request.toProjectFileQuery(ctx.projectRoot), ctx.git)).paths;
395
+ const fallback = runTextFallbackSearch(ctx.projectRoot, pattern, filePaths, ctx.process);
396
+
397
+ const visibleMatches: CodeRefsMatch[] = [];
398
+ const fileCache = new Map<string, string>();
399
+ let firstRefusal:
400
+ | {
401
+ path: string;
402
+ reason: string;
403
+ reasonDetail: string;
404
+ next: readonly string[];
405
+ actual: { lines: number; bytes: number };
406
+ }
407
+ | undefined;
408
+
409
+ for (const match of fallback.matches) {
410
+ let content = fileCache.get(match.path);
411
+ if (content === undefined) {
412
+ const loaded = await loadFileContent(ctx, match.path);
413
+ if (loaded === null) continue;
414
+ fileCache.set(match.path, loaded);
415
+ content = loaded;
416
+ }
417
+
418
+ const refusal = evaluatePrecisionPolicy(ctx, match.path, content);
419
+ if (refusal !== null) {
420
+ firstRefusal ??= refusal;
421
+ continue;
422
+ }
423
+
424
+ visibleMatches.push(match);
425
+ }
426
+
427
+ if (visibleMatches.length === 0 && firstRefusal !== undefined) {
428
+ return ctx.respond("code_refs", {
429
+ query: request.query,
430
+ mode: request.mode,
431
+ scope: request.scope(),
432
+ path: firstRefusal.path,
433
+ projection: "refused",
434
+ reason: firstRefusal.reason,
435
+ reasonDetail: firstRefusal.reasonDetail,
436
+ next: [...firstRefusal.next],
437
+ actual: firstRefusal.actual,
438
+ source: "text_fallback",
439
+ provenance: {
440
+ engine: fallback.engine,
441
+ pattern: pattern.pattern,
442
+ approximate: true,
443
+ filesSearched: filePaths.length,
444
+ },
445
+ layer,
446
+ });
447
+ }
448
+
449
+ return ctx.respond("code_refs", {
450
+ query: request.query,
451
+ mode: request.mode,
452
+ scope: request.scope(),
453
+ matches: visibleMatches,
454
+ total: visibleMatches.length,
455
+ source: "text_fallback",
456
+ provenance: {
457
+ engine: fallback.engine,
458
+ pattern: pattern.pattern,
459
+ approximate: true,
460
+ filesSearched: filePaths.length,
461
+ },
462
+ layer,
463
+ });
464
+ };
465
+ },
466
+ };