@mwillbanks/ast-mcp 0.3.0 → 0.4.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 (36) hide show
  1. package/README.md +5 -5
  2. package/dist/ast-mcp.js +172 -156
  3. package/dist/ast-mcp.js.map +35 -31
  4. package/package.json +11 -11
  5. package/src/ast-bro/client.ts +12 -6
  6. package/src/ast-bro/result.ts +79 -0
  7. package/src/ast-bro/tools.json +7 -2
  8. package/src/config-edit.ts +236 -0
  9. package/src/config-migrate.ts +3 -20
  10. package/src/config-registry.ts +8 -0
  11. package/src/config-schema-common.ts +8 -1
  12. package/src/config-v2-schema.ts +12 -0
  13. package/src/config.ts +194 -39
  14. package/src/helpers/config.ts +9 -3
  15. package/src/installer.ts +61 -14
  16. package/src/patch/engine.ts +36 -17
  17. package/src/runtime/config-write.ts +327 -0
  18. package/src/runtime/dependencies.ts +14 -78
  19. package/src/runtime/file-read.ts +4 -13
  20. package/src/runtime/format.ts +27 -5
  21. package/src/runtime/git-worktrees.ts +179 -0
  22. package/src/runtime/path-policy.ts +131 -45
  23. package/src/runtime/path-utils.ts +40 -0
  24. package/src/runtime/paths.ts +29 -3
  25. package/src/tools/ast-bro.ts +106 -8
  26. package/src/tools/configuration.ts +218 -0
  27. package/src/tools/files.ts +1 -1
  28. package/templates/AGENTS.md +5 -1
  29. package/templates/skills/ast-mcp/SKILL.md +30 -1
  30. package/templates/skills/ast-mcp/evals/evals.json +98 -0
  31. package/templates/skills/ast-mcp/references/installation.md +2 -2
  32. package/templates/skills/ast-mcp/references/patch-state-machine.md +2 -2
  33. package/templates/skills/ast-mcp/references/tool-catalog.md +8 -4
  34. package/templates/skills/ast-mcp/scripts/binary-resolution.ts +112 -0
  35. package/templates/skills/ast-mcp/scripts/check-install.ts +162 -39
  36. package/templates/skills/ast-mcp/scripts/managed-hook.ts +34 -2
@@ -0,0 +1,179 @@
1
+ import { lstat, readdir, readFile, realpath, stat } from "node:fs/promises";
2
+ import path from "node:path";
3
+
4
+ const cache = new Map<string, { fingerprint: string; paths: string[] }>();
5
+
6
+ export function clearGitWorktreeCache(): void {
7
+ cache.clear();
8
+ }
9
+
10
+ async function gitEntry(
11
+ start: string,
12
+ ): Promise<{ gitPath: string; workTree: string } | undefined> {
13
+ let current = path.resolve(start);
14
+ while (true) {
15
+ const gitPath = path.join(current, ".git");
16
+ const metadata = await lstat(gitPath).catch(() => undefined);
17
+ if (metadata?.isDirectory() || metadata?.isFile())
18
+ return { gitPath, workTree: current };
19
+ const parent = path.dirname(current);
20
+ if (parent === current) return undefined;
21
+ current = parent;
22
+ }
23
+ }
24
+
25
+ function resolvePointer(baseDir: string, pointer: string): string {
26
+ return path.isAbsolute(pointer)
27
+ ? path.resolve(pointer)
28
+ : path.resolve(baseDir, pointer);
29
+ }
30
+
31
+ function gitDirPointer(source: string, gitPath: string): string | undefined {
32
+ const match = /^\s*gitdir:\s*(.+?)\s*$/m.exec(source);
33
+ const value = match?.[1]?.trim();
34
+ return value ? resolvePointer(path.dirname(gitPath), value) : undefined;
35
+ }
36
+
37
+ async function resolveGitDir(gitPath: string): Promise<string | undefined> {
38
+ const metadata = await lstat(gitPath).catch(() => undefined);
39
+ if (!metadata) return undefined;
40
+ if (metadata.isDirectory()) return gitPath;
41
+ if (!metadata.isFile()) return undefined;
42
+ const source = await readFile(gitPath, "utf8").catch(() => undefined);
43
+ return source ? gitDirPointer(source, gitPath) : undefined;
44
+ }
45
+
46
+ async function commonGitDir(gitDir: string): Promise<string> {
47
+ const source = await readFile(path.join(gitDir, "commondir"), "utf8").catch(
48
+ () => undefined,
49
+ );
50
+ const value = source?.trim();
51
+ if (!value) return gitDir;
52
+ return path.isAbsolute(value)
53
+ ? path.resolve(value)
54
+ : path.resolve(gitDir, value);
55
+ }
56
+
57
+ function mainWorkTree(commonDir: string, discoveredWorkTree: string): string {
58
+ return path.basename(commonDir) === ".git"
59
+ ? path.dirname(commonDir)
60
+ : discoveredWorkTree;
61
+ }
62
+
63
+ async function gitDirBelongsTo(
64
+ gitDir: string,
65
+ gitPath: string,
66
+ ): Promise<boolean> {
67
+ const metadata = await lstat(gitPath).catch(() => undefined);
68
+ if (metadata?.isDirectory()) return sameResolvedPath(gitDir, gitPath);
69
+ if (!metadata?.isFile()) return false;
70
+ const pointer = await readFile(path.join(gitDir, "gitdir"), "utf8").catch(
71
+ () => undefined,
72
+ );
73
+ if (!pointer?.trim()) return false;
74
+ return sameResolvedPath(resolvePointer(gitDir, pointer.trim()), gitPath);
75
+ }
76
+
77
+ async function sameResolvedPath(left: string, right: string): Promise<boolean> {
78
+ const [canonicalLeft, canonicalRight] = await Promise.all([
79
+ realpath(left).catch(() => path.resolve(left)),
80
+ realpath(right).catch(() => path.resolve(right)),
81
+ ]);
82
+ return canonicalLeft === canonicalRight;
83
+ }
84
+
85
+ async function worktreeGitFile(
86
+ gitdirFile: string,
87
+ ): Promise<string | undefined> {
88
+ const source = await readFile(gitdirFile, "utf8").catch(() => undefined);
89
+ const pointer = source?.trim();
90
+ if (!pointer) return undefined;
91
+ const gitFile = resolvePointer(path.dirname(gitdirFile), pointer);
92
+ if (path.basename(gitFile) !== ".git") return undefined;
93
+ const gitMetadata = await lstat(gitFile).catch(() => undefined);
94
+ return gitMetadata?.isFile() ? gitFile : undefined;
95
+ }
96
+
97
+ async function worktreeFromGitdirFile(
98
+ gitdirFile: string,
99
+ commonDir: string,
100
+ ): Promise<string | undefined> {
101
+ const gitFile = await worktreeGitFile(gitdirFile);
102
+ if (!gitFile) return undefined;
103
+ const expectedGitDir = path.dirname(gitdirFile);
104
+ const back = gitDirPointer(
105
+ (await readFile(gitFile, "utf8").catch(() => undefined)) ?? "",
106
+ gitFile,
107
+ );
108
+ if (!back || !(await sameResolvedPath(back, expectedGitDir)))
109
+ return undefined;
110
+ if (!(await sameResolvedPath(await commonGitDir(expectedGitDir), commonDir)))
111
+ return undefined;
112
+ const metadata = await stat(path.dirname(gitFile)).catch(() => undefined);
113
+ return metadata?.isDirectory() ? path.dirname(gitFile) : undefined;
114
+ }
115
+
116
+ async function linkedFromGitdirFiles(commonDir: string): Promise<string[]> {
117
+ const worktreesDir = path.join(commonDir, "worktrees");
118
+ const entries = await readdir(worktreesDir, { withFileTypes: true }).catch(
119
+ () => [],
120
+ );
121
+ const paths: string[] = [];
122
+ for (const entry of entries) {
123
+ if (!entry.isDirectory()) continue;
124
+ const workTree = await worktreeFromGitdirFile(
125
+ path.join(worktreesDir, entry.name, "gitdir"),
126
+ commonDir,
127
+ );
128
+ if (workTree) paths.push(workTree);
129
+ }
130
+ return paths;
131
+ }
132
+
133
+ async function cacheFingerprint(commonDir: string): Promise<string> {
134
+ const gitStat = await stat(commonDir).catch(() => undefined);
135
+ const worktreesDir = path.join(commonDir, "worktrees");
136
+ const worktreesStat = await stat(worktreesDir).catch(() => undefined);
137
+ const names = await readdir(worktreesDir).catch(() => []);
138
+ const gitdirStats = await Promise.all(
139
+ names.map(async (name) => {
140
+ const metadata = await stat(
141
+ path.join(worktreesDir, name, "gitdir"),
142
+ ).catch(() => undefined);
143
+ return `${name}:${metadata?.mtimeMs ?? 0}`;
144
+ }),
145
+ );
146
+ gitdirStats.sort();
147
+ return `${gitStat?.mtimeMs ?? 0}:${worktreesStat?.mtimeMs ?? 0}:${gitdirStats.join(",")}`;
148
+ }
149
+
150
+ async function uniqueCanonical(paths: string[]): Promise<string[]> {
151
+ const unique: string[] = [];
152
+ const seen = new Set<string>();
153
+ for (const item of paths) {
154
+ const canonical = await realpath(item).catch(() => path.resolve(item));
155
+ if (seen.has(canonical)) continue;
156
+ seen.add(canonical);
157
+ unique.push(canonical);
158
+ }
159
+ return unique;
160
+ }
161
+
162
+ export async function linkedWorktrees(root: string): Promise<string[]> {
163
+ const entry = await gitEntry(root);
164
+ if (!entry) return [];
165
+ const gitDir = await resolveGitDir(entry.gitPath);
166
+ if (!gitDir || !(await gitDirBelongsTo(gitDir, entry.gitPath))) return [];
167
+ const commonDir = await commonGitDir(gitDir);
168
+ const common = await stat(commonDir).catch(() => undefined);
169
+ if (!common?.isDirectory()) return uniqueCanonical([entry.workTree]);
170
+ const fingerprint = await cacheFingerprint(commonDir);
171
+ const cached = cache.get(commonDir);
172
+ if (cached?.fingerprint === fingerprint) return cached.paths;
173
+ const paths = await uniqueCanonical([
174
+ mainWorkTree(commonDir, entry.workTree),
175
+ ...(await linkedFromGitdirFiles(commonDir)),
176
+ ]);
177
+ cache.set(commonDir, { fingerprint, paths });
178
+ return paths;
179
+ }
@@ -7,8 +7,10 @@ import type { PathPolicy } from "../config-v2-schema";
7
7
  import { authorizeRequestedDecision } from "./approval";
8
8
  import {
9
9
  canonicalizePath,
10
+ canonicalizePathSync,
10
11
  effectiveWorkspaceRoot,
11
12
  pathWithin,
13
+ relativeRootFromPwd,
12
14
  } from "./path-utils";
13
15
 
14
16
  export type PathOperation = "read" | "write" | "delete";
@@ -46,7 +48,10 @@ async function canonicalPolicyPath(targetPath: string): Promise<string> {
46
48
  }
47
49
 
48
50
  function within(root: string, target: string): boolean {
49
- return pathWithin(root, target);
51
+ return (
52
+ pathWithin(root, target) ||
53
+ pathWithin(canonicalizePathSync(root), canonicalizePathSync(target))
54
+ );
50
55
  }
51
56
 
52
57
  function literalPrefix(glob: string): number {
@@ -95,6 +100,82 @@ function protectedConfiguration(
95
100
  });
96
101
  }
97
102
 
103
+ function projectRelativeAnchors(
104
+ config: ResolvedConfig,
105
+ anchor: string,
106
+ ): string[] {
107
+ if (config.workspace.worktrees === "ignore") return [anchor];
108
+ const projectRoot = path.resolve(config.projectRoot);
109
+ if (!within(projectRoot, anchor)) return [anchor];
110
+ const relative = path.relative(projectRoot, anchor);
111
+ const extras = (config.workspace.linkedWorktrees ?? [])
112
+ .map((item) => path.resolve(item))
113
+ .filter((item) => item !== projectRoot)
114
+ .map((item) => (relative ? path.join(item, relative) : item));
115
+ return [anchor, ...extras];
116
+ }
117
+
118
+ function linkedWorktreeContaining(
119
+ config: ResolvedConfig,
120
+ canonicalPath: string,
121
+ ): string | undefined {
122
+ const projectRoot = path.resolve(config.projectRoot);
123
+ if (within(projectRoot, canonicalPath)) return undefined;
124
+ return (config.workspace.linkedWorktrees ?? [])
125
+ .map((item) => path.resolve(item))
126
+ .filter((item) => item !== projectRoot && within(item, canonicalPath))
127
+ .sort((left, right) => right.length - left.length)[0];
128
+ }
129
+
130
+ function withWorktreeRequest(
131
+ config: ResolvedConfig,
132
+ decision: PolicyDecision,
133
+ ): PolicyDecision {
134
+ if (config.workspace.worktrees !== "request" || decision.policy === "deny")
135
+ return decision;
136
+ if (!linkedWorktreeContaining(config, decision.canonicalPath))
137
+ return decision;
138
+ return {
139
+ ...decision,
140
+ policy: "request",
141
+ reason: `${decision.reason}; linked git worktree requires approval`,
142
+ };
143
+ }
144
+
145
+ function matchRule(
146
+ rule: ResolvedConfig["paths"][number],
147
+ anchor: string,
148
+ canonicalPath: string,
149
+ operation: PathOperation,
150
+ ): PolicyDecision | undefined {
151
+ const lexical = pathWithin(anchor, canonicalPath);
152
+ const canonicalAnchor = canonicalizePathSync(anchor);
153
+ const canonicalTarget = canonicalizePathSync(canonicalPath);
154
+ const canonical = pathWithin(canonicalAnchor, canonicalTarget);
155
+ if (!lexical && !canonical) return undefined;
156
+ const matchedAnchor = lexical ? anchor : canonicalAnchor;
157
+ const matchedTarget = lexical ? canonicalPath : canonicalTarget;
158
+ const relative = path.relative(matchedAnchor, matchedTarget);
159
+ if (relative !== "" && !matches(relative, rule.includes, rule.excludes))
160
+ return undefined;
161
+ const exact = matchedTarget === matchedAnchor ? 1_000_000 : 0;
162
+ const depth = matchedAnchor.split(path.sep).length * 10_000;
163
+ const includeSpecificity = Math.max(
164
+ ...matchingIncludes(relative, rule.includes).map(literalPrefix),
165
+ 0,
166
+ );
167
+ return {
168
+ canonicalPath,
169
+ operation,
170
+ policy: rule.policies[operation],
171
+ reason: `Matched paths rule ${rule.id}`,
172
+ ruleId: rule.id,
173
+ source: rule.source,
174
+ specificity: exact + depth + includeSpecificity,
175
+ symlinks: rule.followSymlinks,
176
+ };
177
+ }
178
+
98
179
  export function evaluatePolicy(
99
180
  config: ResolvedConfig,
100
181
  targetPath: string,
@@ -116,31 +197,14 @@ export function evaluatePolicy(
116
197
  symlinks: false,
117
198
  };
118
199
 
119
- const candidates = (config.paths ?? []).flatMap((rule) => {
120
- const anchor = path.resolve(rule.path);
121
- if (!within(anchor, canonicalPath)) return [];
122
- const relative = path.relative(anchor, canonicalPath);
123
- if (relative !== "" && !matches(relative, rule.includes, rule.excludes))
124
- return [];
125
- const exact = canonicalPath === anchor ? 1_000_000 : 0;
126
- const depth = anchor.split(path.sep).length * 10_000;
127
- const includeSpecificity = Math.max(
128
- ...matchingIncludes(relative, rule.includes).map(literalPrefix),
129
- 0,
130
- );
131
- return [
132
- {
133
- canonicalPath,
134
- operation,
135
- policy: rule.policies[operation],
136
- reason: `Matched paths rule ${rule.id}`,
137
- ruleId: rule.id,
138
- source: rule.source,
139
- specificity: exact + depth + includeSpecificity,
140
- symlinks: rule.followSymlinks,
141
- } satisfies PolicyDecision,
142
- ];
143
- });
200
+ const candidates = (config.paths ?? []).flatMap((rule) =>
201
+ projectRelativeAnchors(config, path.resolve(rule.path)).flatMap(
202
+ (anchor) => {
203
+ const decision = matchRule(rule, anchor, canonicalPath, operation);
204
+ return decision ? [decision] : [];
205
+ },
206
+ ),
207
+ );
144
208
 
145
209
  candidates.sort(
146
210
  (left, right) =>
@@ -157,12 +221,12 @@ export function evaluatePolicy(
157
221
  !withinBaseline &&
158
222
  winner.source === "project"
159
223
  )
160
- return {
224
+ return withWorktreeRequest(config, {
161
225
  ...winner,
162
226
  policy: "request",
163
227
  reason: `${winner.reason}; project access beyond the host baseline requires approval`,
164
- };
165
- return winner;
228
+ });
229
+ return withWorktreeRequest(config, winner);
166
230
  }
167
231
 
168
232
  if (
@@ -170,7 +234,7 @@ export function evaluatePolicy(
170
234
  config.safety.allowTempDirectory &&
171
235
  within(temporaryRoot, canonicalPath)
172
236
  )
173
- return {
237
+ return withWorktreeRequest(config, {
174
238
  canonicalPath,
175
239
  operation,
176
240
  policy: "allow",
@@ -178,9 +242,9 @@ export function evaluatePolicy(
178
242
  source: "baseline",
179
243
  specificity: 0,
180
244
  symlinks: config.safety.followSymlinks,
181
- };
245
+ });
182
246
  if (config.version === 1 && config.safety.allowAnyPath)
183
- return {
247
+ return withWorktreeRequest(config, {
184
248
  canonicalPath,
185
249
  operation,
186
250
  policy: "allow",
@@ -188,11 +252,11 @@ export function evaluatePolicy(
188
252
  source: "baseline",
189
253
  specificity: 0,
190
254
  symlinks: config.safety.followSymlinks,
191
- };
255
+ });
192
256
  const inBaseline = config.trustedRoots.some((root) =>
193
257
  within(root, canonicalPath),
194
258
  );
195
- return {
259
+ return withWorktreeRequest(config, {
196
260
  canonicalPath,
197
261
  operation,
198
262
  policy: inBaseline ? "allow" : "deny",
@@ -202,7 +266,7 @@ export function evaluatePolicy(
202
266
  source: "baseline",
203
267
  specificity: 0,
204
268
  symlinks: config.version === 1 && config.safety.followSymlinks,
205
- };
269
+ });
206
270
  }
207
271
 
208
272
  function symlinkDenied(
@@ -225,10 +289,12 @@ export async function evaluatePolicyForCheck(
225
289
  const workspaceRoots = await Promise.all(
226
290
  config.workspace.roots.map(canonicalizePath),
227
291
  );
228
- const base = effectiveWorkspaceRoot(
229
- await canonicalizePath(config.projectRoot),
230
- workspaceRoots,
231
- );
292
+ const base =
293
+ relativeRootFromPwd(workspaceRoots) ??
294
+ effectiveWorkspaceRoot(
295
+ await canonicalizePath(config.projectRoot),
296
+ workspaceRoots,
297
+ );
232
298
  const inputPath = path.isAbsolute(targetPath)
233
299
  ? targetPath
234
300
  : path.resolve(base, targetPath);
@@ -246,11 +312,11 @@ export async function evaluatePolicyForCheck(
246
312
  : symlinkDenied(targetDecision, target);
247
313
  }
248
314
 
249
- function allowRuleCoversTree(
315
+ function allowRuleCoversAnchor(
250
316
  rule: ResolvedConfig["paths"][number],
317
+ anchor: string,
251
318
  root: string,
252
319
  ): boolean {
253
- const anchor = path.resolve(rule.path);
254
320
  if (!within(anchor, root)) return false;
255
321
  const relative = path.relative(anchor, root).split(path.sep).join("/");
256
322
  const included = rule.includes.some((value) => {
@@ -470,11 +536,21 @@ function selectorIntersectsRuleTree(
470
536
  );
471
537
  }
472
538
 
473
- function ruleIntersectsTree(
539
+ function allowRuleCoversTree(
540
+ config: ResolvedConfig,
541
+ rule: ResolvedConfig["paths"][number],
542
+ root: string,
543
+ ): boolean {
544
+ return projectRelativeAnchors(config, path.resolve(rule.path)).some(
545
+ (anchor) => allowRuleCoversAnchor(rule, anchor, root),
546
+ );
547
+ }
548
+
549
+ function ruleIntersectsAnchor(
474
550
  rule: ResolvedConfig["paths"][number],
551
+ anchor: string,
475
552
  root: string,
476
553
  ): boolean {
477
- const anchor = path.resolve(rule.path);
478
554
  if (within(root, anchor)) return true;
479
555
  if (!within(anchor, root)) return false;
480
556
  const relativeRoot = path.relative(anchor, root).split(path.sep).join("/");
@@ -483,6 +559,16 @@ function ruleIntersectsTree(
483
559
  );
484
560
  }
485
561
 
562
+ function ruleIntersectsTree(
563
+ config: ResolvedConfig,
564
+ rule: ResolvedConfig["paths"][number],
565
+ root: string,
566
+ ): boolean {
567
+ return projectRelativeAnchors(config, path.resolve(rule.path)).some(
568
+ (anchor) => ruleIntersectsAnchor(rule, anchor, root),
569
+ );
570
+ }
571
+
486
572
  export function assertReadableTree(
487
573
  config: ResolvedConfig,
488
574
  targetPath: string,
@@ -495,9 +581,9 @@ export function assertReadableTree(
495
581
  (config.safety.allowAnyPath ||
496
582
  (config.safety.allowTempDirectory && within(temporaryRoot, root))));
497
583
  for (const rule of config.paths ?? []) {
498
- if (!ruleIntersectsTree(rule, root)) continue;
584
+ if (!ruleIntersectsTree(config, rule, root)) continue;
499
585
  if (rule.policies.read === "allow") {
500
- fullTreeAllowed ||= allowRuleCoversTree(rule, root);
586
+ fullTreeAllowed ||= allowRuleCoversTree(config, rule, root);
501
587
  continue;
502
588
  }
503
589
  assertPolicy(
@@ -1,3 +1,4 @@
1
+ import { realpathSync } from "node:fs";
1
2
  import { realpath } from "node:fs/promises";
2
3
  import path from "node:path";
3
4
 
@@ -9,6 +10,45 @@ export function pathWithin(root: string, target: string): boolean {
9
10
  );
10
11
  }
11
12
 
13
+ export function canonicalizePathSync(targetPath: string): string {
14
+ let existing = path.resolve(targetPath);
15
+ const missing: string[] = [];
16
+ while (true) {
17
+ try {
18
+ return path.join(realpathSync(existing), ...missing);
19
+ } catch (error) {
20
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
21
+ return path.join(existing, ...missing);
22
+ }
23
+ const parent = path.dirname(existing);
24
+ if (parent === existing) return path.join(existing, ...missing);
25
+ missing.unshift(path.basename(existing));
26
+ existing = parent;
27
+ }
28
+ }
29
+ }
30
+
31
+ export function containingRoot(
32
+ roots: string[],
33
+ target: string,
34
+ ): string | undefined {
35
+ const canonicalTarget = canonicalizePathSync(target);
36
+ return roots
37
+ .map((root) => ({
38
+ canonical: canonicalizePathSync(root),
39
+ root,
40
+ }))
41
+ .filter(({ canonical }) => pathWithin(canonical, canonicalTarget))
42
+ .sort((left, right) => right.canonical.length - left.canonical.length)[0]
43
+ ?.canonical;
44
+ }
45
+
46
+ export function relativeRootFromPwd(roots: string[]): string | undefined {
47
+ const pwd = process.env.PWD;
48
+ if (!pwd) return undefined;
49
+ return containingRoot(roots, path.resolve(pwd));
50
+ }
51
+
12
52
  export function effectiveWorkspaceRoot(
13
53
  projectRoot: string,
14
54
  roots: string[],
@@ -9,8 +9,11 @@ import {
9
9
  } from "./path-policy";
10
10
  import {
11
11
  canonicalizePath,
12
+ canonicalizePathSync,
13
+ containingRoot,
12
14
  effectiveWorkspaceRoot,
13
15
  pathWithin,
16
+ relativeRootFromPwd,
14
17
  } from "./path-utils";
15
18
 
16
19
  async function realpathOrSelf(filePath: string): Promise<string> {
@@ -72,11 +75,30 @@ export async function primaryRoot(): Promise<string> {
72
75
  async function configuredRootForPath(
73
76
  filePath: string,
74
77
  ): Promise<string | undefined> {
75
- return (await fileOperationRoots()).find((candidate) =>
76
- within(candidate, filePath),
78
+ const canonicalTarget = canonicalizePathSync(filePath);
79
+ return (await fileOperationRoots()).find(
80
+ (candidate) =>
81
+ pathWithin(candidate, filePath) ||
82
+ pathWithin(canonicalizePathSync(candidate), canonicalTarget),
77
83
  );
78
84
  }
79
85
 
86
+ export async function intelligenceRoot(
87
+ requestPaths: string[] = [],
88
+ ): Promise<string> {
89
+ const roots = await workspaceRoots();
90
+ const matched = [
91
+ ...new Set(
92
+ requestPaths
93
+ .filter((item) => path.isAbsolute(item))
94
+ .map((item) => containingRoot(roots, path.resolve(item)))
95
+ .filter((item): item is string => Boolean(item)),
96
+ ),
97
+ ];
98
+ if (matched.length === 1) return matched[0] as string;
99
+ return relativeRootFromPwd(roots) ?? (roots[0] as string);
100
+ }
101
+
80
102
  export async function referenceRootForPath(
81
103
  filePath: string,
82
104
  ): Promise<string | undefined> {
@@ -197,7 +219,11 @@ async function resolvePath(
197
219
  operation: PathOperation,
198
220
  ): Promise<string> {
199
221
  const config = await currentConfig();
200
- const resolved = await canonicalCandidate(filePath, roots[0] as string);
222
+ const base =
223
+ path.isAbsolute(filePath) || !relativeRootFromPwd(roots)
224
+ ? (roots[0] as string)
225
+ : (relativeRootFromPwd(roots) as string);
226
+ const resolved = await canonicalCandidate(filePath, base);
201
227
  assertWithinBoundary(
202
228
  resolved,
203
229
  roots,