@cruxy/cli 0.22.1 → 0.23.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 (60) hide show
  1. package/dist/approval/classify.js +18 -0
  2. package/dist/approval/prompt.js +11 -0
  3. package/dist/checkpoint/gate.d.ts +65 -0
  4. package/dist/checkpoint/gate.js +86 -0
  5. package/dist/checkpoint/index.d.ts +2 -0
  6. package/dist/checkpoint/index.js +2 -0
  7. package/dist/checkpoint/set-rollback.d.ts +51 -0
  8. package/dist/checkpoint/set-rollback.js +74 -0
  9. package/dist/cli/commands/rollback.d.ts +11 -6
  10. package/dist/cli/commands/rollback.js +93 -33
  11. package/dist/cli/commands/run.js +59 -10
  12. package/dist/cli/onboard.js +4 -1
  13. package/dist/cli/repl.d.ts +2 -2
  14. package/dist/cli/session-factory.d.ts +4 -3
  15. package/dist/cli/session-factory.js +98 -12
  16. package/dist/errors/constructors.d.ts +28 -0
  17. package/dist/errors/constructors.js +59 -0
  18. package/dist/errors/types.d.ts +20 -0
  19. package/dist/errors/types.js +26 -0
  20. package/dist/indexing/retriever.d.ts +29 -0
  21. package/dist/indexing/retriever.js +26 -0
  22. package/dist/indexing/service.js +3 -1
  23. package/dist/indexing/types.d.ts +7 -0
  24. package/dist/lsp/tools/common.d.ts +34 -7
  25. package/dist/lsp/tools/common.js +33 -11
  26. package/dist/lsp/tools/find-definition.js +2 -2
  27. package/dist/lsp/tools/find-references.js +10 -4
  28. package/dist/lsp/tools/get-diagnostics.js +6 -4
  29. package/dist/render/diff.js +42 -5
  30. package/dist/subagent/orchestrator.d.ts +15 -0
  31. package/dist/subagent/orchestrator.js +2 -0
  32. package/dist/testing/run-tests-tool.js +3 -0
  33. package/dist/tools/create-pull-request.d.ts +3 -0
  34. package/dist/tools/create-pull-request.js +50 -4
  35. package/dist/tools/file/apply-patch.js +2 -2
  36. package/dist/tools/file/edit-file.js +2 -2
  37. package/dist/tools/file/glob.d.ts +9 -2
  38. package/dist/tools/file/glob.js +73 -19
  39. package/dist/tools/file/grep-files.d.ts +12 -2
  40. package/dist/tools/file/grep-files.js +113 -38
  41. package/dist/tools/file/paths.d.ts +122 -9
  42. package/dist/tools/file/paths.js +165 -10
  43. package/dist/tools/file/read-file.js +2 -2
  44. package/dist/tools/file/write-file.js +2 -2
  45. package/dist/tools/git-status.d.ts +8 -1
  46. package/dist/tools/git-status.js +43 -11
  47. package/dist/tools/list-files.d.ts +9 -3
  48. package/dist/tools/list-files.js +48 -13
  49. package/dist/tools/search-codebase.d.ts +10 -0
  50. package/dist/tools/search-codebase.js +117 -14
  51. package/dist/tools/shell/exec.js +8 -1
  52. package/dist/tools/types.d.ts +63 -1
  53. package/dist/vcs/git.d.ts +8 -0
  54. package/dist/vcs/git.js +14 -0
  55. package/dist/vcs/github.d.ts +7 -1
  56. package/dist/vcs/github.js +10 -1
  57. package/dist/vcs/service.d.ts +8 -0
  58. package/dist/vcs/service.js +33 -1
  59. package/dist/vcs/types.d.ts +18 -2
  60. package/package.json +1 -1
@@ -1,13 +1,20 @@
1
1
  import { promises as fsp } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { CruxyError } from "../../errors/index.js";
4
- import { resolveInRoot } from "../../tools/file/paths.js";
4
+ import { contextWorkspace, labelPath, resolveToolPath, } from "../../tools/file/paths.js";
5
5
  import { getLspService } from "../service.js";
6
6
  /**
7
- * The shared spine of every LSP tool (C.12): enforce the master switch, validate
8
- * the target path stays in the project root, prove it exists, get the per-cwd
9
- * service, and run `query`. Read-only throughout — no `ctx.requestApproval`, so
10
- * these bypass the U.3 gate exactly like `search_codebase` and `grep_files`.
7
+ * The shared spine of every LSP tool (C.12): enforce the master switch, resolve
8
+ * the target file to the ONE declared root that contains it, prove it exists, get
9
+ * THAT root's language-server pool, and run `query`. Read-only throughout — no
10
+ * `ctx.requestApproval`, so these bypass the U.3 gate exactly like `search_codebase`
11
+ * and `grep_files`.
12
+ *
13
+ * Multi-repo (C.26, Funnel A→pool): the file is resolved through the shared
14
+ * `resolveToolPath`, so it commits to exactly one root, and the pool is keyed by
15
+ * THAT root's `absPath` (`getLspService` caches per resolved cwd → a per-root map
16
+ * for free). A file in root B is answered by B's server, never A's — the
17
+ * `(file → root)` selection and the `(root → pool)` key are the same value.
11
18
  *
12
19
  * Errors are surfaced as `{ ok:false }` text the agent can act on: a coded LSP
13
20
  * failure (no server / timeout / crash) is rendered WITH its next step, so the
@@ -21,9 +28,11 @@ export async function runLspTool(ctx, file, query) {
21
28
  error: "LSP tools are disabled (set lsp.enabled = true to use language-server features)",
22
29
  };
23
30
  }
31
+ const ws = contextWorkspace(ctx);
32
+ let root;
24
33
  let absFile;
25
34
  try {
26
- absFile = await resolveInRoot(ctx, file);
35
+ ({ root, abs: absFile } = await resolveToolPath(ctx, { path: file }));
27
36
  }
28
37
  catch (err) {
29
38
  return { ok: false, error: err.message };
@@ -38,8 +47,8 @@ export async function runLspTool(ctx, file, query) {
38
47
  return { ok: false, error: `file not found: ${file}` };
39
48
  }
40
49
  try {
41
- const service = getLspService(ctx.cwd, ctx.config, ctx.logger);
42
- return await query(service, absFile);
50
+ const service = getLspService(root.absPath, ctx.config, ctx.logger);
51
+ return await query(service, absFile, { root, isMultiRoot: ws.isMultiRoot });
43
52
  }
44
53
  catch (err) {
45
54
  return { ok: false, error: describeError(err) };
@@ -54,14 +63,27 @@ function describeError(err) {
54
63
  }
55
64
  return err.message;
56
65
  }
66
+ /**
67
+ * A note stating that a per-root language server only sees its own root, so
68
+ * references/definitions in sibling roots are NOT searched (⚖︎JC-7) — returned only
69
+ * in a multi-root session, so a references list is never read as complete when it
70
+ * silently could not span roots. Empty string in single-root (byte-identical).
71
+ */
72
+ export function crossRootNote(rc) {
73
+ return rc.isMultiRoot
74
+ ? `\n(note: only root ‹${rc.root.name}› was searched — a per-root language server does not resolve symbols across roots)`
75
+ : "";
76
+ }
57
77
  /**
58
78
  * Render up to `max` locations as `path:line:col-endLine:endCol`, one per line,
59
79
  * with a trailing "N more" note when capped — the same bounded-honest pattern as
60
- * grep_files and search_codebase (never silently drop the overflow).
80
+ * grep_files and search_codebase (never silently drop the overflow). In a
81
+ * multi-root session each path is labelled `‹root› ▸ path` (the query ran against
82
+ * one root, so every location carries that root's label).
61
83
  */
62
- export function formatLocations(locations, max) {
84
+ export function formatLocations(locations, max, rc) {
63
85
  const shown = locations.slice(0, max);
64
- const lines = shown.map((l) => `${l.path}:${l.startLine}:${l.startCol}-${l.endLine}:${l.endCol}`);
86
+ const lines = shown.map((l) => `${labelPath(rc.root, l.path, rc.isMultiRoot)}:${l.startLine}:${l.startCol}-${l.endLine}:${l.endCol}`);
65
87
  const omitted = locations.length - shown.length;
66
88
  if (omitted > 0) {
67
89
  lines.push(`… [${omitted} more location(s) omitted]`);
@@ -27,14 +27,14 @@ export const findDefinitionTool = {
27
27
  description: "Resolve where a symbol is defined using the project's language server (go-to-definition). Give the file and the 1-based line/column of the identifier. Returns definition locations as 'path:line:col-endLine:endCol'. Read-only, no approval. Precise where grep is textual — prefer this to jump to a symbol's definition.",
28
28
  parameters,
29
29
  execute(input, ctx) {
30
- return runLspTool(ctx, input.file, async (service, absFile) => {
30
+ return runLspTool(ctx, input.file, async (service, absFile, rc) => {
31
31
  const locations = await service.definition(absFile, input.line, input.column);
32
32
  if (locations.length === 0) {
33
33
  return { ok: true, output: "(no definition found)" };
34
34
  }
35
35
  return {
36
36
  ok: true,
37
- output: formatLocations(locations, ctx.config.lsp.maxResults),
37
+ output: formatLocations(locations, ctx.config.lsp.maxResults, rc),
38
38
  };
39
39
  });
40
40
  },
@@ -1,5 +1,5 @@
1
1
  import { z } from "zod";
2
- import { formatLocations, runLspTool } from "./common.js";
2
+ import { crossRootNote, formatLocations, runLspTool } from "./common.js";
3
3
  const parameters = z.object({
4
4
  file: z
5
5
  .string()
@@ -27,14 +27,20 @@ export const findReferencesTool = {
27
27
  description: "Find all references to a symbol using the project's language server. Give the file and the 1-based line/column of the identifier. Returns use sites as 'path:line:col-endLine:endCol' (capped, with an 'N more' note). Read-only, no approval. Precise where grep is textual — prefer this to see every caller/user of a symbol.",
28
28
  parameters,
29
29
  execute(input, ctx) {
30
- return runLspTool(ctx, input.file, async (service, absFile) => {
30
+ return runLspTool(ctx, input.file, async (service, absFile, rc) => {
31
31
  const locations = await service.references(absFile, input.line, input.column);
32
+ // The cross-root note is appended even to an empty result: "(no references)"
33
+ // from a per-root server must not read as "no references anywhere" (⚖︎JC-7).
32
34
  if (locations.length === 0) {
33
- return { ok: true, output: "(no references found)" };
35
+ return {
36
+ ok: true,
37
+ output: `(no references found)${crossRootNote(rc)}`,
38
+ };
34
39
  }
35
40
  return {
36
41
  ok: true,
37
- output: formatLocations(locations, ctx.config.lsp.maxResults),
42
+ output: formatLocations(locations, ctx.config.lsp.maxResults, rc) +
43
+ crossRootNote(rc),
38
44
  };
39
45
  });
40
46
  },
@@ -1,4 +1,5 @@
1
1
  import { z } from "zod";
2
+ import { labelPath } from "../../tools/file/paths.js";
2
3
  import { runLspTool } from "./common.js";
3
4
  const parameters = z.object({
4
5
  file: z
@@ -17,23 +18,24 @@ export const getDiagnosticsTool = {
17
18
  description: "Get the language server's diagnostics (errors, warnings) for a file. Give the project-relative path. Returns diagnostics as 'severity path:line:col message'. Read-only, no approval. Use this after an edit to see type errors the compiler/linter reports, without running a build.",
18
19
  parameters,
19
20
  execute(input, ctx) {
20
- return runLspTool(ctx, input.file, async (service, absFile) => {
21
+ return runLspTool(ctx, input.file, async (service, absFile, rc) => {
21
22
  const diagnostics = await service.diagnostics(absFile);
22
23
  if (diagnostics.length === 0) {
23
24
  return { ok: true, output: "(no diagnostics)" };
24
25
  }
25
26
  return {
26
27
  ok: true,
27
- output: formatDiagnostics(diagnostics, ctx.config.lsp.maxResults),
28
+ output: formatDiagnostics(diagnostics, ctx.config.lsp.maxResults, rc),
28
29
  };
29
30
  });
30
31
  },
31
32
  };
32
- function formatDiagnostics(diagnostics, max) {
33
+ function formatDiagnostics(diagnostics, max, rc) {
33
34
  const shown = diagnostics.slice(0, max);
34
35
  const lines = shown.map((d) => {
35
36
  const src = d.source ? ` [${d.source}]` : "";
36
- return `${d.severity} ${d.path}:${d.range.startLine}:${d.range.startCol} ${d.message}${src}`;
37
+ const loc = labelPath(rc.root, d.path, rc.isMultiRoot);
38
+ return `${d.severity} ${loc}:${d.range.startLine}:${d.range.startCol} ${d.message}${src}`;
37
39
  });
38
40
  const omitted = diagnostics.length - shown.length;
39
41
  if (omitted > 0) {
@@ -36,6 +36,10 @@ function renderPatchFiles(files, c) {
36
36
  /** Render a `vcs` pull-request publish plan: branch, commit, and PR body. */
37
37
  function renderPrPreview(preview, c) {
38
38
  const out = [];
39
+ // The resolved forge destination (⚖︎JC-4): the human sees the real owner/repo the
40
+ // PR will open against — not just a branch — and it is exactly the target the
41
+ // wrong-repo guard re-checks before the API call.
42
+ out.push(`${c.strong("target")} ${c.accent(`${preview.target.host}/${preview.target.owner}/${preview.target.repo}`)}`);
39
43
  out.push(`${c.strong("branch")} ${c.success(preview.branch)} ${c.glyph.arrow} ${preview.base}`);
40
44
  out.push("");
41
45
  out.push(c.strong("commit"));
@@ -60,16 +64,46 @@ function renderRollbackPreview(preview, c) {
60
64
  if (preview.runSummary)
61
65
  out.push(c.muted(`run: ${preview.runSummary}`));
62
66
  out.push(c.muted("working-tree files only — commits, pushes, and PRs made during the run are not undone"));
63
- if (preview.externalPaths.length > 0) {
67
+ out.push(...rollbackWarnings(preview.externalPaths, preview.attributionUnknown, c));
68
+ out.push("");
69
+ out.push(...renderPatchFiles(preview.files, c));
70
+ return out;
71
+ }
72
+ /**
73
+ * The blast-radius warnings for one checkpoint: paths changed outside the tracked
74
+ * run (which rollback will overwrite), and the shell-attribution caveat. Emitted
75
+ * BEFORE the file diffs so the global collapse cap can never hide them.
76
+ */
77
+ function rollbackWarnings(externalPaths, attributionUnknown, c) {
78
+ const out = [];
79
+ if (externalPaths.length > 0) {
64
80
  out.push(c.danger(c.strong("changed outside this run — rollback will overwrite these too:")));
65
- for (const p of preview.externalPaths)
81
+ for (const p of externalPaths)
66
82
  out.push(c.danger(`! ${p}`));
67
83
  }
68
- if (preview.attributionUnknown) {
84
+ if (attributionUnknown) {
69
85
  out.push(c.warning("this run executed shell commands; some changes below may not have been made by the run"));
70
86
  }
71
- out.push("");
72
- out.push(...renderPatchFiles(preview.files, c));
87
+ return out;
88
+ }
89
+ /**
90
+ * Render a multi-root set rollback (C.26): one run header, then each touched root
91
+ * as its own labeled block with its own warnings + diffs. Grouping is the point —
92
+ * a reviewer sees which repo each change lands in before the single approval.
93
+ */
94
+ function renderRollbackSetPreview(preview, c) {
95
+ const out = [];
96
+ out.push(`${c.strong("restore run")} ${c.accent(preview.runId)} ${c.muted(`(${preview.createdAt})`)}`);
97
+ if (preview.runSummary)
98
+ out.push(c.muted(`run: ${preview.runSummary}`));
99
+ out.push(c.muted(`${preview.roots.length} root${preview.roots.length === 1 ? "" : "s"} — ` +
100
+ "working-tree files only; commits, pushes, and PRs made during the run are not undone"));
101
+ for (const r of preview.roots) {
102
+ out.push("");
103
+ out.push(`${c.strong(`root ${r.rootName}`)} ${c.muted(`checkpoint ${r.checkpointId}`)}`);
104
+ out.push(...rollbackWarnings(r.externalPaths, r.attributionUnknown, c));
105
+ out.push(...renderPatchFiles(r.files, c));
106
+ }
73
107
  return out;
74
108
  }
75
109
  /** Split a multi-line body into trimmed-of-trailing lines, dropping a trailing blank. */
@@ -98,6 +132,9 @@ export function renderActionPreview(preview, c) {
98
132
  else if (preview.type === "rollback") {
99
133
  lines = renderRollbackPreview(preview, c);
100
134
  }
135
+ else if (preview.type === "rollback-set") {
136
+ lines = renderRollbackSetPreview(preview, c);
137
+ }
101
138
  else {
102
139
  const header = preview.exists
103
140
  ? c.warning("OVERWRITE existing")
@@ -5,6 +5,7 @@ import type { StreamRenderer } from "../render/index.js";
5
5
  import type { Router } from "../routing/index.js";
6
6
  import type { ApproveAction, ToolContext, ToolRegistry } from "../tools/index.js";
7
7
  import type { SandboxService } from "../sandbox/index.js";
8
+ import type { Workspace } from "../workspace/index.js";
8
9
  import type { SubagentResult, SubagentSpec } from "./types.js";
9
10
  /**
10
11
  * Everything a spawn needs from the surrounding session, injected by the
@@ -24,6 +25,13 @@ export interface SubagentOrchestratorDeps {
24
25
  /** The parent's registry — the ceiling every child scope derives from. */
25
26
  parentRegistry: ToolRegistry;
26
27
  cwd: string;
28
+ /**
29
+ * The session's declared workspace (C.26). Threaded onto the child ctx so a
30
+ * subagent sees the SAME roots as the main loop — without it the child would
31
+ * fall back to a single-root workspace over `cwd` and its fan tools would go
32
+ * silently primary-only (a split-brain WITHIN one session).
33
+ */
34
+ workspace: Workspace;
27
35
  logger: ToolContext["logger"];
28
36
  git?: {
29
37
  branch: string;
@@ -45,6 +53,13 @@ export interface SubagentOrchestratorDeps {
45
53
  * one checkpoint, C.32).
46
54
  */
47
55
  makeChildApproval(): (action: ApproveAction) => Promise<ApprovalDecision>;
56
+ /**
57
+ * Whether per-root checkpointing is active for the run (C.26 step 3). Threaded
58
+ * onto the child ctx so a subagent's non-primary writes lift the JC-1 refusal on
59
+ * the SAME condition as the parent — and, because `makeChildApproval` wraps the
60
+ * same shared checkpoint gate, those writes join the run's one set (⚖︎JC-δ).
61
+ */
62
+ checkpointsActive?: boolean;
48
63
  }
49
64
  /**
50
65
  * Spawns subagents (C.14): the existing agent loop re-driven over isolated
@@ -57,6 +57,7 @@ export class SubagentOrchestrator {
57
57
  const artifacts = new Set();
58
58
  const ctx = {
59
59
  cwd: deps.cwd,
60
+ workspace: deps.workspace,
60
61
  config: deps.config,
61
62
  logger: deps.logger,
62
63
  requestApproval: async (action) => {
@@ -65,6 +66,7 @@ export class SubagentOrchestrator {
65
66
  recordArtifacts(action, artifacts, deps.cwd);
66
67
  return decision;
67
68
  },
69
+ checkpointsActive: deps.checkpointsActive,
68
70
  sandbox: deps.sandbox,
69
71
  };
70
72
  const label = taskLabel(spec.task);
@@ -97,6 +97,9 @@ export function makeRunTestsTool(deps = {}) {
97
97
  const decision = await ctx.requestApproval({
98
98
  kind: "test",
99
99
  command: resolved.command,
100
+ // C.26 attribution seam (JC-β): primary root name for Steps 4/5. Tests are
101
+ // primary-only this release; the gate hard-attributes to the primary.
102
+ root: ctx.workspace?.primary().name,
100
103
  });
101
104
  if (!decision.allow) {
102
105
  return {
@@ -8,14 +8,17 @@ import type { Tool } from "./types.js";
8
8
  * never prompted for or stored.
9
9
  */
10
10
  declare const parameters: z.ZodObject<{
11
+ root: z.ZodOptional<z.ZodString>;
11
12
  title: z.ZodOptional<z.ZodString>;
12
13
  body: z.ZodOptional<z.ZodString>;
13
14
  base: z.ZodOptional<z.ZodString>;
14
15
  }, "strip", z.ZodTypeAny, {
16
+ root?: string | undefined;
15
17
  body?: string | undefined;
16
18
  base?: string | undefined;
17
19
  title?: string | undefined;
18
20
  }, {
21
+ root?: string | undefined;
19
22
  body?: string | undefined;
20
23
  base?: string | undefined;
21
24
  title?: string | undefined;
@@ -1,6 +1,8 @@
1
+ import path from "node:path";
1
2
  import { z } from "zod";
2
- import { CruxyError, ErrorCode } from "../errors/index.js";
3
- import { createForgeProvider, createPrService, fillContent, loadCommitGuidance, resolveForgeToken, } from "../vcs/index.js";
3
+ import { CruxyError, ErrorCode, vcsCrossRoot } from "../errors/index.js";
4
+ import { createForgeProvider, createPrService, fillContent, gitToplevel, loadCommitGuidance, resolveForgeToken, } from "../vcs/index.js";
5
+ import { contextWorkspace, resolveMutationRoot } from "./file/paths.js";
4
6
  /**
5
7
  * Open a pull request from the agent's work (C.15): branch → conventional commit
6
8
  * → push → open PR, all behind the one U.3 approval. The model authors `title`
@@ -9,6 +11,12 @@ import { createForgeProvider, createPrService, fillContent, loadCommitGuidance,
9
11
  * never prompted for or stored.
10
12
  */
11
13
  const parameters = z.object({
14
+ root: z
15
+ .string()
16
+ .optional()
17
+ .describe("Workspace root to open the pull request for, by its declared name. Required " +
18
+ "when the session declares more than one root (a PR targets exactly one " +
19
+ "repository, so it must not be guessed); optional in a single-root session."),
12
20
  title: z
13
21
  .string()
14
22
  .optional()
@@ -31,11 +39,18 @@ export const createPullRequestTool = {
31
39
  parameters,
32
40
  async execute(input, ctx) {
33
41
  try {
42
+ // ⚖︎#11 / JC-1: commit to exactly one root first. Multi-root with no `root`
43
+ // refuses (ROOT_AMBIGUOUS) BEFORE any git runs; single-root defaults to the
44
+ // primary (byte-identical to pre-C.26). A cross-root PR (a sibling root in the
45
+ // same repo) is refused too — a PR is a single-repo artifact (JC-3).
46
+ const selected = resolveMutationRoot(ctx, { root: input.root }, "a pull request");
47
+ assertSingleRepoRoot(contextWorkspace(ctx), selected);
34
48
  const token = resolveForgeToken();
35
49
  const forge = createForgeProvider(token);
36
- const guidance = await loadCommitGuidance(ctx.cwd);
50
+ const guidance = await loadCommitGuidance(selected.absPath);
37
51
  const service = createPrService({
38
- cwd: ctx.cwd,
52
+ cwd: selected.absPath,
53
+ rootName: selected.name,
39
54
  config: ctx.config,
40
55
  forge,
41
56
  requestApproval: ctx.requestApproval,
@@ -75,6 +90,37 @@ export const createPullRequestTool = {
75
90
  }
76
91
  },
77
92
  };
93
+ /**
94
+ * Refuse a PR whose selected root shares one git working tree with a SIBLING
95
+ * declared root (JC-3). Filesystem-overlap refusal (ROOT_OVERLAP) only catches
96
+ * nesting; two non-overlapping roots — `packages/a` and `packages/b` under one
97
+ * `.git` — pass that check yet still share a repo. Committing in one would
98
+ * `git add -A` the other's changes, so the PR would span both. We detect it by
99
+ * comparing git top-levels: same top-level ⇒ same repo ⇒ refuse (naming both).
100
+ *
101
+ * If the selected root is not in a git repo, there is nothing to compare — the PR
102
+ * flow fails loudly later at `getRepoInfo`/`currentBranch`. Read-only `rev-parse`
103
+ * only; this runs after selection, so a no-root multi-root call still spawns zero
104
+ * git before its ROOT_AMBIGUOUS refusal.
105
+ */
106
+ function assertSingleRepoRoot(ws, selected) {
107
+ if (!ws.isMultiRoot)
108
+ return;
109
+ const topSelected = gitToplevel(selected.absPath);
110
+ if (topSelected === null)
111
+ return;
112
+ const canonical = path.resolve(topSelected);
113
+ for (const sibling of ws.roots()) {
114
+ if (sibling.name === selected.name)
115
+ continue;
116
+ const topSibling = gitToplevel(sibling.absPath);
117
+ if (topSibling === null)
118
+ continue;
119
+ if (path.resolve(topSibling) === canonical) {
120
+ throw vcsCrossRoot(selected.name, sibling.name, canonical);
121
+ }
122
+ }
123
+ }
78
124
  /** One-line, model-readable rendering of a coded error + its next steps. */
79
125
  function formatCoded(err) {
80
126
  const head = err.cause ? `${err.title} — ${err.cause}` : err.title;
@@ -1,7 +1,7 @@
1
1
  import { promises as fs } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { z } from "zod";
4
- import { resolveInRoot } from "./paths.js";
4
+ import { resolveToolPath } from "./paths.js";
5
5
  import { countOccurrences } from "./edit-file.js";
6
6
  /** How many leading lines of a created file the approval preview shows. */
7
7
  const PREVIEW_LINES = 20;
@@ -62,7 +62,7 @@ export const applyPatchTool = {
62
62
  const op = input.operations[i];
63
63
  let abs;
64
64
  try {
65
- abs = await resolveInRoot(ctx, op.path);
65
+ ({ abs } = await resolveToolPath(ctx, { path: op.path }, { deferNonPrimaryWrite: true }));
66
66
  }
67
67
  catch (err) {
68
68
  return { ok: false, error: opError(i, op, err.message) };
@@ -1,6 +1,6 @@
1
1
  import { promises as fs } from "node:fs";
2
2
  import { z } from "zod";
3
- import { resolveInRoot } from "./paths.js";
3
+ import { resolveToolPath } from "./paths.js";
4
4
  /** Count non-overlapping exact occurrences of `needle` in `haystack`. */
5
5
  export function countOccurrences(haystack, needle) {
6
6
  let count = 0;
@@ -32,7 +32,7 @@ export const editFileTool = {
32
32
  async execute(input, ctx) {
33
33
  let abs;
34
34
  try {
35
- abs = await resolveInRoot(ctx, input.path);
35
+ ({ abs } = await resolveToolPath(ctx, { path: input.path }, { deferNonPrimaryWrite: true }));
36
36
  }
37
37
  catch (err) {
38
38
  return { ok: false, error: err.message };
@@ -1,10 +1,17 @@
1
1
  import { z } from "zod";
2
2
  import type { Tool } from "../types.js";
3
3
  /**
4
- * Find files by glob pattern within the project root. Read-only — no approval.
5
- * The pattern is constrained to the root (no absolute or `..` patterns) so glob
4
+ * Find files by glob pattern within the workspace. Read-only — no approval.
5
+ * The pattern is constrained to a root (no absolute or `..` patterns) so glob
6
6
  * can't reach outside, consistent with the other file tools.
7
+ *
8
+ * Multi-repo (C.26, Funnel B): with more than one declared root, glob fans every
9
+ * root — an independent walk rooted at each root's own `absPath` — and labels each
10
+ * match `‹root› ▸ path`. There is no path to confine here; the boundary is which
11
+ * root's `absPath` each walk starts from, so a match can only ever come from the
12
+ * root its label names. A `root` argument scopes the walk to that one root.
7
13
  */
8
14
  export declare const globTool: Tool<z.ZodObject<{
9
15
  pattern: z.ZodString;
16
+ root: z.ZodOptional<z.ZodString>;
10
17
  }>>;
@@ -1,13 +1,19 @@
1
- import path from "node:path";
2
1
  import { glob } from "tinyglobby";
3
2
  import { z } from "zod";
3
+ import { contextWorkspace, isEscapingPattern, labelPath, resolveReadRoots, } from "./paths.js";
4
4
  /** Cap on returned paths — beyond this we truncate with a notice. */
5
5
  const MAX_RESULTS = 200;
6
6
  const DEFAULT_IGNORE = ["**/node_modules/**", "**/.git/**"];
7
7
  /**
8
- * Find files by glob pattern within the project root. Read-only — no approval.
9
- * The pattern is constrained to the root (no absolute or `..` patterns) so glob
8
+ * Find files by glob pattern within the workspace. Read-only — no approval.
9
+ * The pattern is constrained to a root (no absolute or `..` patterns) so glob
10
10
  * can't reach outside, consistent with the other file tools.
11
+ *
12
+ * Multi-repo (C.26, Funnel B): with more than one declared root, glob fans every
13
+ * root — an independent walk rooted at each root's own `absPath` — and labels each
14
+ * match `‹root› ▸ path`. There is no path to confine here; the boundary is which
15
+ * root's `absPath` each walk starts from, so a match can only ever come from the
16
+ * root its label names. A `root` argument scopes the walk to that one root.
11
17
  */
12
18
  export const globTool = {
13
19
  name: "glob",
@@ -16,37 +22,85 @@ export const globTool = {
16
22
  pattern: z
17
23
  .string()
18
24
  .describe("Glob pattern, relative to the project root (e.g. 'src/**/*.ts')."),
25
+ root: z
26
+ .string()
27
+ .optional()
28
+ .describe("In a multi-repo session, restrict the search to a single declared root by name. Omit to search every root and label each match with its root."),
19
29
  }),
20
30
  async execute(input, ctx) {
21
31
  const pattern = input.pattern;
22
- if (path.isAbsolute(pattern) || pattern.split(/[/\\]/).includes("..")) {
32
+ // Walk-rooted tool: the pattern is not a resolvable path, so confinement is
33
+ // (a) rejecting a pattern that could escape (shared with grep_files) and
34
+ // (b) rooting each walk at a declared root's absPath, never a bare ctx.cwd.
35
+ if (isEscapingPattern(pattern)) {
23
36
  return {
24
37
  ok: false,
25
38
  error: "pattern must be relative to the project root (no '..' or absolute paths)",
26
39
  };
27
40
  }
41
+ const ws = contextWorkspace(ctx);
42
+ let roots;
43
+ try {
44
+ roots = resolveReadRoots(ctx, { root: input.root });
45
+ }
46
+ catch (err) {
47
+ return { ok: false, error: err.message };
48
+ }
28
49
  try {
29
- const matches = await glob(pattern, {
30
- cwd: path.resolve(ctx.cwd),
31
- ignore: DEFAULT_IGNORE,
32
- onlyFiles: true,
33
- dot: false,
34
- });
35
- matches.sort();
36
- if (matches.length === 0) {
50
+ // Fan: one independent walk per root; each match is attributed to (and, in
51
+ // multi-root, labelled with) the root whose absPath produced it.
52
+ const rows = [];
53
+ const totalByRoot = new Map();
54
+ for (const root of roots) {
55
+ const matches = await glob(pattern, {
56
+ cwd: root.absPath,
57
+ ignore: DEFAULT_IGNORE,
58
+ onlyFiles: true,
59
+ dot: false,
60
+ });
61
+ matches.sort();
62
+ totalByRoot.set(root.name, matches.length);
63
+ for (const m of matches) {
64
+ rows.push({
65
+ root: root.name,
66
+ line: labelPath(root, m, ws.isMultiRoot),
67
+ });
68
+ }
69
+ }
70
+ if (rows.length === 0) {
37
71
  return { ok: true, output: "(no matches)" };
38
72
  }
39
- if (matches.length > MAX_RESULTS) {
40
- const shown = matches.slice(0, MAX_RESULTS).join("\n");
41
- return {
42
- ok: true,
43
- output: `${shown}\n\n[truncated: showing ${MAX_RESULTS} of ${matches.length} matches]`,
44
- };
73
+ if (rows.length > MAX_RESULTS) {
74
+ const shownRows = rows.slice(0, MAX_RESULTS);
75
+ const shown = shownRows.map((r) => r.line).join("\n");
76
+ const footer = ws.isMultiRoot
77
+ ? truncationFooter(rows.length, shownRows, totalByRoot)
78
+ : `[truncated: showing ${MAX_RESULTS} of ${rows.length} matches]`;
79
+ return { ok: true, output: `${shown}\n\n${footer}` };
45
80
  }
46
- return { ok: true, output: matches.join("\n") };
81
+ return { ok: true, output: rows.map((r) => r.line).join("\n") };
47
82
  }
48
83
  catch (err) {
49
84
  return { ok: false, error: err.message };
50
85
  }
51
86
  },
52
87
  };
88
+ /**
89
+ * Truncation footer for a fanned walk: the overall count plus a per-root note for
90
+ * every root whose matches the cap dropped — so a root cut off by the cap is
91
+ * named, never silently read as having no files.
92
+ */
93
+ function truncationFooter(total, shownRows, totalByRoot) {
94
+ const shownByRoot = new Map();
95
+ for (const r of shownRows) {
96
+ shownByRoot.set(r.root, (shownByRoot.get(r.root) ?? 0) + 1);
97
+ }
98
+ const lines = [`[truncated: showing ${MAX_RESULTS} of ${total} matches]`];
99
+ for (const [name, count] of totalByRoot) {
100
+ const dropped = count - (shownByRoot.get(name) ?? 0);
101
+ if (dropped > 0) {
102
+ lines.push(`— ${name}: ${dropped} more not shown`);
103
+ }
104
+ }
105
+ return lines.join("\n");
106
+ }
@@ -6,27 +6,37 @@ declare const parameters: z.ZodObject<{
6
6
  glob: z.ZodOptional<z.ZodString>;
7
7
  ignoreCase: z.ZodOptional<z.ZodBoolean>;
8
8
  maxResults: z.ZodOptional<z.ZodNumber>;
9
+ root: z.ZodOptional<z.ZodString>;
9
10
  }, "strip", z.ZodTypeAny, {
10
11
  pattern: string;
11
12
  path?: string | undefined;
13
+ root?: string | undefined;
12
14
  maxResults?: number | undefined;
13
15
  glob?: string | undefined;
14
16
  ignoreCase?: boolean | undefined;
15
17
  }, {
16
18
  pattern: string;
17
19
  path?: string | undefined;
20
+ root?: string | undefined;
18
21
  maxResults?: number | undefined;
19
22
  glob?: string | undefined;
20
23
  ignoreCase?: boolean | undefined;
21
24
  }>;
22
25
  /**
23
- * Search file *contents* for a regex within the project root. Read-only — no
26
+ * Search file *contents* for a regex within the workspace. Read-only — no
24
27
  * approval — so the model should prefer this over shelling out to grep/rg via
25
28
  * run_command (which is platform-dependent and routes through the approval gate).
26
29
  *
27
30
  * Files are enumerated with the same glob mechanism as the `glob` tool (so
28
31
  * node_modules and .git are always ignored), binary files are skipped, and the
29
- * search is bounded by the project-root path boundary shared by every file tool.
32
+ * search is bounded by the same root boundary as every file tool.
33
+ *
34
+ * Multi-repo (C.26, Funnel B): with more than one declared root and no root-
35
+ * selecting argument, the search FANS every root — a bare relative `path` is
36
+ * applied under each root (⚖︎JC-6) — and labels each match `‹root› ▸ path`. A
37
+ * `root` argument, or an absolute / `‹root›/…`-prefixed `path`, scopes it to that
38
+ * one root. Each walk starts at exactly one confined root directory, so a match
39
+ * can only come from the root its label names.
30
40
  */
31
41
  export declare const grepFilesTool: Tool<typeof parameters>;
32
42
  export {};