@mrclrchtr/supi-code-intelligence 11.4.0 → 12.0.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 (89) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +13 -7
  3. package/node_modules/@mrclrchtr/supi-code-runtime/package.json +1 -1
  4. package/node_modules/@mrclrchtr/supi-code-runtime/src/api.ts +1 -0
  5. package/node_modules/@mrclrchtr/supi-code-runtime/src/types.ts +51 -23
  6. package/node_modules/@mrclrchtr/supi-core/package.json +1 -1
  7. package/node_modules/@mrclrchtr/supi-lsp/README.md +21 -16
  8. package/node_modules/@mrclrchtr/supi-lsp/node_modules/@mrclrchtr/supi-code-runtime/package.json +1 -1
  9. package/node_modules/@mrclrchtr/supi-lsp/node_modules/@mrclrchtr/supi-code-runtime/src/api.ts +1 -0
  10. package/node_modules/@mrclrchtr/supi-lsp/node_modules/@mrclrchtr/supi-code-runtime/src/types.ts +51 -23
  11. package/node_modules/@mrclrchtr/supi-lsp/node_modules/@mrclrchtr/supi-core/package.json +1 -1
  12. package/node_modules/@mrclrchtr/supi-lsp/package.json +3 -3
  13. package/node_modules/@mrclrchtr/supi-lsp/src/api.ts +2 -2
  14. package/node_modules/@mrclrchtr/supi-lsp/src/client/client-diagnostic-capabilities.ts +13 -3
  15. package/node_modules/@mrclrchtr/supi-lsp/src/client/client-diagnostics.ts +25 -9
  16. package/node_modules/@mrclrchtr/supi-lsp/src/client/client-document-sync.ts +7 -5
  17. package/node_modules/@mrclrchtr/supi-lsp/src/client/client-edit-capture.ts +258 -0
  18. package/node_modules/@mrclrchtr/supi-lsp/src/client/client.ts +64 -11
  19. package/node_modules/@mrclrchtr/supi-lsp/src/config/capabilities.ts +8 -0
  20. package/node_modules/@mrclrchtr/supi-lsp/src/config/operation-support.ts +48 -79
  21. package/node_modules/@mrclrchtr/supi-lsp/src/manager/manager.ts +3 -1
  22. package/node_modules/@mrclrchtr/supi-lsp/src/provider/lsp-refactor-provider.ts +21 -35
  23. package/node_modules/@mrclrchtr/supi-lsp/src/provider/refactor-command-capture.ts +139 -0
  24. package/node_modules/@mrclrchtr/supi-lsp/src/provider/refactor-planning.ts +202 -47
  25. package/node_modules/@mrclrchtr/supi-lsp/src/session/route-boundary.ts +26 -0
  26. package/node_modules/@mrclrchtr/supi-lsp/src/session/runtime-registry.ts +57 -12
  27. package/node_modules/@mrclrchtr/supi-lsp/src/session/runtime-rename.ts +3 -0
  28. package/node_modules/@mrclrchtr/supi-lsp/src/session/workspace-lsp-runtime.ts +22 -1
  29. package/node_modules/@mrclrchtr/supi-tree-sitter/node_modules/@mrclrchtr/supi-code-runtime/package.json +1 -1
  30. package/node_modules/@mrclrchtr/supi-tree-sitter/node_modules/@mrclrchtr/supi-code-runtime/src/api.ts +1 -0
  31. package/node_modules/@mrclrchtr/supi-tree-sitter/node_modules/@mrclrchtr/supi-code-runtime/src/types.ts +51 -23
  32. package/node_modules/@mrclrchtr/supi-tree-sitter/node_modules/@mrclrchtr/supi-core/package.json +1 -1
  33. package/node_modules/@mrclrchtr/supi-tree-sitter/package.json +3 -3
  34. package/node_modules/@mrclrchtr/supi-tree-sitter/src/coordinates.ts +16 -2
  35. package/node_modules/@mrclrchtr/supi-tree-sitter/src/session/structural-worker-client.ts +3 -2
  36. package/node_modules/@mrclrchtr/supi-tree-sitter/src/syntax-errors.ts +2 -0
  37. package/node_modules/@mrclrchtr/supi-tree-sitter/src/tool/call-range.ts +94 -0
  38. package/node_modules/@mrclrchtr/supi-tree-sitter/src/tool/call-sites.ts +26 -6
  39. package/node_modules/@mrclrchtr/supi-tree-sitter/src/tool/callees.ts +6 -3
  40. package/node_modules/@mrclrchtr/supi-tree-sitter/src/tool/exports.ts +13 -4
  41. package/node_modules/@mrclrchtr/supi-tree-sitter/src/worker/runtime.ts +1 -9
  42. package/package.json +5 -5
  43. package/src/analysis/health/server-status.ts +41 -12
  44. package/src/analysis/target/anchored-structural.ts +4 -1
  45. package/src/analysis/target/symbol.ts +1 -1
  46. package/src/session/find-types.ts +8 -4
  47. package/src/session/find-workflow.ts +11 -16
  48. package/src/session/input/health-refactor.ts +48 -34
  49. package/src/session/input/workflows.ts +45 -46
  50. package/src/session/inspect/file-point.ts +2 -2
  51. package/src/session/inspect-types.ts +1 -1
  52. package/src/session/inspect-workflow.ts +3 -3
  53. package/src/session/refactor-file-actions.ts +122 -0
  54. package/src/session/refactor-plan-pipeline.ts +152 -0
  55. package/src/session/refactor-plans.ts +18 -15
  56. package/src/session/refactor-types.ts +24 -12
  57. package/src/session/refactor-workflow.ts +68 -243
  58. package/src/tool/code_find/execute.ts +6 -7
  59. package/src/tool/code_find/spec.ts +9 -16
  60. package/src/tool/code_find/tui.ts +12 -6
  61. package/src/tool/code_graph/spec.ts +6 -0
  62. package/src/tool/code_health/spec.ts +6 -0
  63. package/src/tool/code_health/structured-schema.ts +4 -4
  64. package/src/tool/code_health/structured.ts +15 -17
  65. package/src/tool/code_inspect/execute.ts +1 -1
  66. package/src/tool/code_inspect/markdown.ts +33 -6
  67. package/src/tool/code_inspect/result.ts +1 -1
  68. package/src/tool/code_inspect/spec.ts +14 -6
  69. package/src/tool/code_inspect/structured.ts +2 -2
  70. package/src/tool/code_inspect/tui.ts +2 -2
  71. package/src/tool/code_orientation/spec.ts +8 -0
  72. package/src/tool/code_refactor_apply/result.ts +2 -1
  73. package/src/tool/code_refactor_apply/spec.ts +7 -0
  74. package/src/tool/code_refactor_plan/execute.ts +0 -2
  75. package/src/tool/code_refactor_plan/result.ts +23 -13
  76. package/src/tool/code_refactor_plan/spec.ts +8 -2
  77. package/src/tool/code_refactor_plan/structured.ts +59 -12
  78. package/src/tool/code_refactor_plan/tui.ts +14 -17
  79. package/src/tool/code_resolve/markdown.ts +1 -1
  80. package/src/tool/code_resolve/spec.ts +6 -0
  81. package/src/tool/namespace.ts +14 -0
  82. package/src/tool/refactor-markdown.ts +55 -15
  83. package/src/tool/register.ts +3 -0
  84. package/src/tool/result/refactor-preview.ts +118 -0
  85. package/src/tool/result/refactor-unavailable.ts +16 -0
  86. package/src/tool/result/refactor.ts +8 -2
  87. package/src/tool/schemas.ts +63 -20
  88. package/src/tool/specs.ts +3 -0
  89. package/src/ui/status-overlay.ts +1 -1
@@ -32,13 +32,13 @@ function renderNode(
32
32
  appendSyntaxRecovery(lines, observation.recovery);
33
33
  const node = observation.data;
34
34
  if (!node) {
35
- lines.push("_No syntax node at this point._", "");
35
+ lines.push("_No syntax node at this anchor._", "");
36
36
  return;
37
37
  }
38
38
  lines.push(
39
39
  `- \`${node.type}\` L${node.startLine}:${node.startCharacter}–L${node.endLine}:${node.endCharacter}`,
40
40
  );
41
- if (node.text) lines.push("```text", node.text, "```");
41
+ if (node.text) appendNodeText(lines, node);
42
42
  if (node.ancestry.length > 0) {
43
43
  lines.push(
44
44
  `Ancestry: ${node.ancestry.map((ancestor) => `\`${ancestor.type} L${ancestor.startLine}:${ancestor.startCharacter}–L${ancestor.endLine}:${ancestor.endCharacter}\``).join(" > ")}`,
@@ -47,6 +47,33 @@ function renderNode(
47
47
  lines.push("");
48
48
  }
49
49
 
50
+ /** Preview bounds for syntax-node text; a whitespace anchor selects the whole file's root node. */
51
+ const NODE_TEXT_MAX_LINES = 12;
52
+ const NODE_TEXT_MAX_CHARACTERS = 1200;
53
+
54
+ /** Print a bounded preview of the node text; the range above locates the rest. */
55
+ function appendNodeText(
56
+ lines: string[],
57
+ node: { text: string; startLine: number; endLine: number },
58
+ ): void {
59
+ const textLines = node.text.split("\n");
60
+ let shown = textLines.slice(0, NODE_TEXT_MAX_LINES).join("\n");
61
+ // Array.from keeps surrogate pairs whole when a single long line is cut.
62
+ const characters = Array.from(shown);
63
+ if (characters.length > NODE_TEXT_MAX_CHARACTERS) {
64
+ shown = characters.slice(0, NODE_TEXT_MAX_CHARACTERS).join("");
65
+ }
66
+ lines.push("```text", shown, "```");
67
+ if (shown.length === node.text.length) return;
68
+ const preview =
69
+ textLines.length > NODE_TEXT_MAX_LINES
70
+ ? `first ${NODE_TEXT_MAX_LINES} of ${textLines.length} lines`
71
+ : `first ${NODE_TEXT_MAX_CHARACTERS} characters`;
72
+ lines.push(
73
+ `_Node text shortened to the ${preview}; read L${node.startLine}–L${node.endLine} for the rest._`,
74
+ );
75
+ }
76
+
50
77
  function renderEnclosingSymbol(
51
78
  lines: string[],
52
79
  observation: InspectResultAssembly["data"]["sections"]["enclosingSymbol"],
@@ -60,7 +87,7 @@ function renderEnclosingSymbol(
60
87
  appendSyntaxRecovery(lines, observation.recovery);
61
88
  const symbol = observation.data;
62
89
  if (!symbol) {
63
- lines.push("_No provider-reported declaration encloses this point._", "");
90
+ lines.push("_No provider-reported declaration encloses this anchor._", "");
64
91
  return;
65
92
  }
66
93
  lines.push(
@@ -79,7 +106,7 @@ function renderHover(
79
106
  return;
80
107
  }
81
108
  appendPartial(lines, observation);
82
- lines.push(observation.data ?? "_No hover result at this point._", "");
109
+ lines.push(observation.data ?? "_No hover result at this anchor._", "");
83
110
  }
84
111
 
85
112
  function renderDefinitions(lines: string[], assembly: InspectResultAssembly): void {
@@ -88,7 +115,7 @@ function renderDefinitions(lines: string[], assembly: InspectResultAssembly): vo
88
115
  if (appendUnavailable(lines, observation)) return;
89
116
  appendPartial(lines, observation);
90
117
  if (assembly.displayedDefinitions.length === 0) {
91
- lines.push("_No definition result at this point._");
118
+ lines.push("_No definition result at this anchor._");
92
119
  } else {
93
120
  for (const definition of assembly.displayedDefinitions) {
94
121
  lines.push(`- ${formatDefinition(definition, assembly.data)}`);
@@ -109,7 +136,7 @@ function formatDefinition(
109
136
  return `\`${definition.file}:${definition.line}:${definition.character}\``;
110
137
  }
111
138
  if (definition.line === focus.line && definition.character === focus.character)
112
- return "Same point";
139
+ return "Same anchor";
113
140
  return `L${definition.line}:${definition.character}`;
114
141
  }
115
142
 
@@ -336,7 +336,7 @@ type InspectOutcome = Awaited<ReturnType<CodeIntelToolExecCtx["session"]["inspec
336
336
  export function finishInspectResult(outcome: InspectOutcome): CodeIntelResult {
337
337
  if (outcome.kind === "unavailable") throw new Error(outcome.reason);
338
338
  if (outcome.kind === "invalid-input") {
339
- const nextQueries = ["Provide an existing file and exact 1-based point"];
339
+ const nextQueries = ["Provide an existing file and exact 1-based anchor"];
340
340
  return {
341
341
  ...inspectErrorResult(`**Error:** ${outcome.message}`, {
342
342
  focusTarget: "invalid input",
@@ -12,15 +12,23 @@ export const CODE_INSPECT_TOOL_LABEL = "Code Inspect";
12
12
  export const codeInspectSpec = {
13
13
  name: CODE_INSPECT_TOOL_NAME,
14
14
  label: CODE_INSPECT_TOOL_LABEL,
15
+ annotations: {
16
+ readOnlyHint: true,
17
+ destructiveHint: false,
18
+ idempotentHint: true,
19
+ openWorldHint: false,
20
+ },
15
21
  outputSchema: InspectOutputSchema,
16
22
  parameters: Type.Object(
17
23
  {
18
- point: SourcePointParam,
19
- maxResults: Type.Optional({
20
- ...MaxResultsParam,
21
- description:
22
- "Maximum entries per definition or diagnostic list; does not limit syntax or hover text.",
23
- }),
24
+ anchor: SourcePointParam,
25
+ maxResults: Type.Optional(
26
+ Type.Integer({
27
+ ...MaxResultsParam,
28
+ description:
29
+ "Maximum entries per definition or diagnostic list; does not limit syntax or hover text.",
30
+ }),
31
+ ),
24
32
  },
25
33
  { additionalProperties: false },
26
34
  ),
@@ -78,7 +78,7 @@ export const InspectOutputSchema = Type.Union([
78
78
  Type.Object(
79
79
  {
80
80
  kind: Type.Literal("completed"),
81
- point: Type.Object(
81
+ anchor: Type.Object(
82
82
  { file: Type.String(), line: Type.Integer(), character: Type.Integer() },
83
83
  { additionalProperties: false },
84
84
  ),
@@ -141,7 +141,7 @@ export function structuredInspectResult(
141
141
  const { data, assembled } = assembly;
142
142
  return {
143
143
  kind: "completed",
144
- point: { file: data.relPath, line: data.line, character: data.character },
144
+ anchor: { file: data.relPath, line: data.line, character: data.character },
145
145
  confidence: data.confidence,
146
146
  diagnosticWindow: {
147
147
  startLine: data.diagnosticWindow.startLine,
@@ -16,11 +16,11 @@ export function renderInspectCall(
16
16
  _context: ToolRendererContext | undefined,
17
17
  ): Text {
18
18
  const params = (args ?? {}) as {
19
- point?: { file?: unknown; line?: unknown; character?: unknown };
19
+ anchor?: { file?: unknown; line?: unknown; character?: unknown };
20
20
  };
21
21
 
22
22
  let content = theme.fg("toolTitle", "code_inspect");
23
- const point = params.point;
23
+ const point = params.anchor;
24
24
  if (point && typeof point === "object") {
25
25
  const file = formatCallPath(point.file);
26
26
  if (file) content += ` ${theme.fg("accent", file)}`;
@@ -12,6 +12,14 @@ export const CODE_ORIENTATION_TOOL_LABEL = "Code Orientation";
12
12
  export const codeOrientationSpec = {
13
13
  name: CODE_ORIENTATION_TOOL_NAME,
14
14
  label: CODE_ORIENTATION_TOOL_LABEL,
15
+ // Read-only by default. Gradle observation runs project build logic only after an explicit
16
+ // per-project allow; that consent covers its effects, so the hints describe the default path.
17
+ annotations: {
18
+ readOnlyHint: true,
19
+ destructiveHint: false,
20
+ idempotentHint: true,
21
+ openWorldHint: true,
22
+ },
15
23
  outputSchema: OrientationOutputSchema,
16
24
  parameters: Type.Object(
17
25
  {
@@ -4,6 +4,7 @@ import type { CodeIntelResult, CodeIntelToolExecCtx } from "../../types/index.ts
4
4
  import { renderRefactorApplyResult } from "../refactor-markdown.ts";
5
5
  import { searchErrorResult } from "../result/errors.ts";
6
6
  import { assembleRefactorApplyDetails } from "../result/refactor.ts";
7
+ import { refactorUnavailableReason } from "../result/refactor-unavailable.ts";
7
8
  import { structuredRefactorApply } from "./structured.ts";
8
9
 
9
10
  type RefactorApplyOutcome = Awaited<ReturnType<CodeIntelToolExecCtx["session"]["applyRefactor"]>>;
@@ -13,7 +14,7 @@ export function finishRefactorApplyResult(
13
14
  outcome: RefactorApplyOutcome,
14
15
  cwd: string,
15
16
  ): CodeIntelResult {
16
- if (outcome.kind === "unavailable") throw new Error(outcome.reason);
17
+ if (outcome.kind === "unavailable") throw new Error(refactorUnavailableReason(outcome.reason));
17
18
  if (outcome.kind === "invalid-input") {
18
19
  return {
19
20
  ...searchErrorResult(`**Error:** ${outcome.message}`, {
@@ -11,6 +11,13 @@ export const CODE_REFACTOR_APPLY_TOOL_LABEL = "Code Refactor Apply";
11
11
  export const codeRefactorApplySpec = {
12
12
  name: CODE_REFACTOR_APPLY_TOOL_NAME,
13
13
  label: CODE_REFACTOR_APPLY_TOOL_LABEL,
14
+ // Overwrites workspace files; a repeated planId is rejected because Apply consumes the plan.
15
+ annotations: {
16
+ readOnlyHint: false,
17
+ destructiveHint: true,
18
+ idempotentHint: true,
19
+ openWorldHint: false,
20
+ },
14
21
  parameters: Type.Object(
15
22
  {
16
23
  planId: Type.String({
@@ -4,13 +4,11 @@ import type {
4
4
  RefactorOperationInput,
5
5
  RefactorPlanWorkflowInput,
6
6
  } from "../../session/refactor-types.ts";
7
- import type { RefactorTargetInput } from "../../session/target-input.ts";
8
7
  import type { CodeIntelResult, CodeIntelToolExecCtx } from "../../types/index.ts";
9
8
  import { toWorkflowControl } from "../infra/workflow-control.ts";
10
9
  import { finishRefactorPlanResult } from "./result.ts";
11
10
 
12
11
  export interface CodeRefactorPlanToolParams {
13
- target: RefactorTargetInput;
14
12
  operation: RefactorOperationInput;
15
13
  }
16
14
 
@@ -5,7 +5,8 @@ import type { CodeIntelResult, CodeIntelToolExecCtx } from "../../types/index.ts
5
5
  import { renderRefactorPlanResult } from "../refactor-markdown.ts";
6
6
  import { searchErrorResult } from "../result/errors.ts";
7
7
  import { assembleRefactorPlanDetails } from "../result/refactor.ts";
8
- import { structuredRefactorPlan } from "./structured.ts";
8
+ import { refactorUnavailableReason } from "../result/refactor-unavailable.ts";
9
+ import { AMBIGUOUS_NEXT_ACTION, structuredRefactorPlan } from "./structured.ts";
9
10
 
10
11
  type RefactorPlanOutcome = Awaited<ReturnType<CodeIntelToolExecCtx["session"]["planRefactor"]>>;
11
12
 
@@ -14,28 +15,37 @@ export function finishRefactorPlanResult(
14
15
  outcome: RefactorPlanOutcome,
15
16
  cwd: string,
16
17
  ): CodeIntelResult {
17
- if (outcome.kind === "unavailable") throw new Error(outcome.reason);
18
+ if (outcome.kind === "unavailable") throw new Error(refactorUnavailableReason(outcome.reason));
18
19
  if (outcome.kind === "invalid-input") {
19
20
  return {
20
21
  ...searchErrorResult(`**Error:** ${outcome.message}`, {
21
- nextQueries: ["Fix the target or operation and retry"],
22
+ nextQueries: ["Fix the operation input and retry"],
22
23
  message: outcome.message,
23
24
  }),
24
25
  structuredContent: structuredRefactorPlan(outcome, cwd),
25
26
  };
26
27
  }
27
28
  if (outcome.kind === "ambiguous") {
28
- const candidates = outcome.candidates
29
- .map(
30
- (candidate, index) =>
31
- `${index + 1}. ${candidate.description} (${candidate.file === undefined ? candidate.file : toDisplayPath(cwd, candidate.file)}:${candidate.line})`,
32
- )
33
- .join("\n");
29
+ const candidates = outcome.candidates.map((candidate, index) => {
30
+ const label =
31
+ candidate.title === undefined
32
+ ? candidate.description
33
+ : `${candidate.kind ? `\`${candidate.kind}\` — ` : ""}${JSON.stringify(candidate.title)}`;
34
+ const location =
35
+ candidate.file === undefined
36
+ ? ""
37
+ : ` — first edit ${toDisplayPath(cwd, candidate.file)}:${candidate.line}`;
38
+ return `${index + 1}. ${label}${location}`;
39
+ });
34
40
  return {
35
- ...searchErrorResult(`**Refactor ambiguous:**\n${candidates}`, {
36
- nextQueries: ["Use a precise target handle or anchor"],
37
- message: "The refactor target is ambiguous.",
38
- }),
41
+ ...searchErrorResult(
42
+ `**Refactor ambiguous:**\n${candidates.join("\n")}\n\n${AMBIGUOUS_NEXT_ACTION}.`,
43
+ {
44
+ status: "disambiguation",
45
+ nextQueries: [AMBIGUOUS_NEXT_ACTION],
46
+ message: "Several matching actions produce different edits.",
47
+ },
48
+ ),
39
49
  structuredContent: structuredRefactorPlan(outcome, cwd),
40
50
  };
41
51
  }
@@ -1,6 +1,6 @@
1
1
  import { Type } from "typebox";
2
2
  import type { CodeIntelToolExecCtx } from "../../types/index.ts";
3
- import { RefactorOperationParam, RefactorTargetParam } from "../schemas.ts";
3
+ import { RefactorOperationParam } from "../schemas.ts";
4
4
  import { executeRefactorPlanTool } from "./execute.ts";
5
5
  import { RefactorPlanOutputSchema } from "./structured.ts";
6
6
  import { renderRefactorPlanCall, renderRefactorPlanResult } from "./tui.ts";
@@ -12,9 +12,15 @@ export const CODE_REFACTOR_PLAN_TOOL_LABEL = "Code Refactor Plan";
12
12
  export const codeRefactorPlanSpec = {
13
13
  name: CODE_REFACTOR_PLAN_TOOL_NAME,
14
14
  label: CODE_REFACTOR_PLAN_TOOL_LABEL,
15
+ // Previews only: server-pushed edits are captured and refused; no file changes.
16
+ annotations: {
17
+ readOnlyHint: true,
18
+ destructiveHint: false,
19
+ idempotentHint: true,
20
+ openWorldHint: false,
21
+ },
15
22
  parameters: Type.Object(
16
23
  {
17
- target: RefactorTargetParam,
18
24
  operation: RefactorOperationParam,
19
25
  },
20
26
  { additionalProperties: false },
@@ -23,9 +23,30 @@ const Edit = Type.Object(
23
23
  },
24
24
  { additionalProperties: false },
25
25
  );
26
+ const OnePosition = Type.Object(
27
+ { line: Type.Integer({ minimum: 1 }), character: Type.Integer({ minimum: 1 }) },
28
+ { additionalProperties: false },
29
+ );
30
+ const Action = Type.Object(
31
+ {
32
+ kind: Type.String(),
33
+ title: Type.String(),
34
+ provenance: Type.Optional(
35
+ Type.Union([Type.Literal("edit"), Type.Literal("captured-command")], {
36
+ description:
37
+ "edit: the action's own edit. captured-command: the edit the server pushed while running the action's command; SuPi refused it, so nothing was applied.",
38
+ }),
39
+ ),
40
+ },
41
+ { additionalProperties: false, description: "Server-reported code action kind and title." },
42
+ );
26
43
  const Candidate = Type.Object(
27
44
  {
28
45
  description: Type.String(),
46
+ kind: Type.Optional(Type.String()),
47
+ title: Type.Optional(
48
+ Type.String({ description: "Pass back as the operation `title` to select this action." }),
49
+ ),
29
50
  file: Type.Optional(Type.String()),
30
51
  line: Type.Optional(Type.Integer()),
31
52
  character: Type.Optional(Type.Integer()),
@@ -37,6 +58,10 @@ const Candidate = Type.Object(
37
58
  },
38
59
  );
39
60
 
61
+ /** Guidance for choosing among matching code actions. */
62
+ export const AMBIGUOUS_NEXT_ACTION =
63
+ "Several matching actions produce different edits; repeat the call with one candidate's exact `title`";
64
+
40
65
  /** Native plan data, including all edits rather than the bounded text preview. */
41
66
  export const RefactorPlanOutputSchema = Type.Union([
42
67
  Type.Object(
@@ -44,12 +69,27 @@ export const RefactorPlanOutputSchema = Type.Union([
44
69
  kind: Type.Literal("completed"),
45
70
  planId: Type.String(),
46
71
  operation: Type.Enum([...PUBLIC_REFACTOR_OPERATION_NAMES], { type: "string" }),
47
- target: Type.Object(
48
- { file: Type.String(), line: Type.Integer(), character: Type.Integer() },
49
- { additionalProperties: false, description: "One-based line and UTF-16 character." },
72
+ file: Type.String({ description: "File the operation was requested for." }),
73
+ target: Type.Optional(
74
+ Type.Object(
75
+ { line: Type.Integer(), character: Type.Integer() },
76
+ {
77
+ additionalProperties: false,
78
+ description: "rename_symbol target; one-based line and UTF-16 character.",
79
+ },
80
+ ),
81
+ ),
82
+ range: Type.Optional(
83
+ Type.Object(
84
+ { start: OnePosition, end: OnePosition },
85
+ {
86
+ additionalProperties: false,
87
+ description: "code_action range; one-based positions, end exclusive.",
88
+ },
89
+ ),
50
90
  ),
51
91
  newName: Type.Optional(Type.String()),
52
- destination: Type.Optional(Type.String()),
92
+ action: Type.Optional(Action),
53
93
  edits: Type.Array(Edit),
54
94
  fileCount: Type.Integer({ minimum: 0 }),
55
95
  editCount: Type.Integer({ minimum: 0 }),
@@ -84,18 +124,20 @@ export function structuredRefactorPlan(
84
124
  return {
85
125
  kind: outcome.kind,
86
126
  message: outcome.message,
87
- nextAction: "Fix the target or operation and retry",
127
+ nextAction: "Fix the operation input and retry",
88
128
  };
89
129
  if (outcome.kind === "ambiguous")
90
130
  return {
91
131
  kind: outcome.kind,
92
132
  candidates: outcome.candidates.map((candidate) => ({
93
133
  description: candidate.description,
134
+ ...(candidate.kind === undefined ? {} : { kind: candidate.kind }),
135
+ ...(candidate.title === undefined ? {} : { title: candidate.title }),
94
136
  ...(candidate.file === undefined ? {} : { file: toDisplayPath(cwd, candidate.file) }),
95
137
  ...(candidate.line === undefined ? {} : { line: candidate.line }),
96
138
  ...(candidate.character === undefined ? {} : { character: candidate.character }),
97
139
  })),
98
- nextAction: "Use a precise target handle or anchor",
140
+ nextAction: AMBIGUOUS_NEXT_ACTION,
99
141
  };
100
142
  const plan = outcome.plan;
101
143
  const operation = PUBLIC_REFACTOR_OPERATION_NAMES.find((name) => name === plan.operation);
@@ -104,13 +146,18 @@ export function structuredRefactorPlan(
104
146
  kind: "completed",
105
147
  planId: plan.id,
106
148
  operation,
107
- target: {
108
- file: toDisplayPath(cwd, plan.targetFile),
109
- line: plan.targetLine,
110
- character: plan.targetCharacter,
111
- },
149
+ file: toDisplayPath(cwd, plan.file),
150
+ ...(plan.target === undefined ? {} : { target: { ...plan.target } }),
151
+ ...(plan.range === undefined
152
+ ? {}
153
+ : {
154
+ range: {
155
+ start: { ...plan.range.start },
156
+ end: { ...plan.range.end },
157
+ },
158
+ }),
112
159
  ...(plan.newName === undefined ? {} : { newName: plan.newName }),
113
- ...(plan.destination === undefined ? {} : { destination: plan.destination }),
160
+ ...(plan.action === undefined ? {} : { action: { ...plan.action } }),
114
161
  edits: plan.edits.edits.map((edit) => ({
115
162
  file: toDisplayPath(cwd, edit.file),
116
163
  range: {
@@ -16,28 +16,25 @@ export function renderRefactorPlanCall(
16
16
  theme: Theme,
17
17
  _context: ToolRendererContext | undefined,
18
18
  ): Text {
19
- const params = (args ?? {}) as {
20
- operation?: Record<string, { newName?: unknown } | undefined>;
21
- target?: { anchor?: { file?: unknown }; handle?: unknown };
22
- };
19
+ const params = (args ?? {}) as { operation?: Record<string, unknown> };
23
20
 
24
21
  let content = theme.fg("toolTitle", "code_refactor_plan");
25
22
  const operation = params.operation ? Object.entries(params.operation)[0] : undefined;
26
23
  if (operation) {
27
24
  content += ` ${theme.fg("accent", formatCallValue(operation[0], 40) ?? "operation")}`;
28
- const newName =
29
- operation[1] && typeof operation[1] === "object"
30
- ? formatCallValue(operation[1].newName)
31
- : null;
32
- if (newName) content += ` ${theme.fg("muted", newName)}`;
33
- }
34
-
35
- const anchorFile = formatCallPath(params.target?.anchor?.file);
36
- if (anchorFile) {
37
- content += ` ${theme.fg("muted", anchorFile)}`;
38
- } else {
39
- const handle = formatCallValue(params.target?.handle);
40
- if (handle) content += ` ${theme.fg("muted", handle)}`;
25
+ const payload = (operation[1] ?? {}) as {
26
+ newName?: unknown;
27
+ kind?: unknown;
28
+ file?: unknown;
29
+ target?: { anchor?: { file?: unknown }; handle?: unknown };
30
+ };
31
+ const detail = formatCallValue(payload.newName) ?? formatCallValue(payload.kind);
32
+ if (detail) content += ` ${theme.fg("muted", detail)}`;
33
+ const location =
34
+ formatCallPath(payload.file) ??
35
+ formatCallPath(payload.target?.anchor?.file) ??
36
+ formatCallValue(payload.target?.handle);
37
+ if (location) content += ` ${theme.fg("muted", location)}`;
41
38
  }
42
39
 
43
40
  return new Text(content, 0, 0);
@@ -158,7 +158,7 @@ function appendNotListed(lines: string[], details: ResolveDetails): void {
158
158
  : []),
159
159
  ...(notListed.exportListNames
160
160
  ? [
161
- `- ${plural(notListed.exportListNames.count, "name")} in export lists (${span(notListed.exportListNames)}). Read those lines, or find them with code_find mode "ast", kind "export", a name fragment as query, and scope set to this file.`,
161
+ `- ${plural(notListed.exportListNames.count, "name")} in export lists (${span(notListed.exportListNames)}). Read those lines, or find them with code_find search.ast, kind "export", a name fragment as query, and scopes set to this file.`,
162
162
  ]
163
163
  : []),
164
164
  ...(notListed.localDeclarations > 0
@@ -12,6 +12,12 @@ export const CODE_RESOLVE_TOOL_LABEL = "Code Resolve";
12
12
  export const codeResolveSpec = {
13
13
  name: CODE_RESOLVE_TOOL_NAME,
14
14
  label: CODE_RESOLVE_TOOL_LABEL,
15
+ annotations: {
16
+ readOnlyHint: true,
17
+ destructiveHint: false,
18
+ idempotentHint: true,
19
+ openWorldHint: false,
20
+ },
15
21
  outputSchema: ResolveOutputSchema,
16
22
  parameters: Type.Object(
17
23
  {
@@ -0,0 +1,14 @@
1
+ import type { ToolNamespace } from "@earendil-works/pi-coding-agent";
2
+
3
+ /** Codemode namespace shared by every `code_*` tool. */
4
+ export const CODE_TOOL_NAMESPACE: ToolNamespace = {
5
+ name: "code",
6
+ description:
7
+ "Code-aware navigation, diagnostics, and refactoring through language servers and syntax trees.",
8
+ instructions: [
9
+ "Orient with code_orientation, discover with code_find, and pin exact targets with code_resolve.",
10
+ "Pass returned target handles to code_inspect, code_graph, or code_refactor_plan instead of re-resolving names.",
11
+ "Use code_health for diagnostics and language-server status.",
12
+ "Refactors are two steps: code_refactor_plan previews edits without writing files; code_refactor_apply writes one stored planId.",
13
+ ].join("\n"),
14
+ };
@@ -2,6 +2,7 @@ import { renderEvidenceListDisclosure } from "../analysis/evidence.ts";
2
2
  import { toDisplayPath } from "../analysis/search/paths.ts";
3
3
  import { assembledNextQueries } from "./result/assembly.ts";
4
4
  import type { RefactorApplyResultAssembly, RefactorPlanResultAssembly } from "./result/refactor.ts";
5
+ import { buildRefactorPreview, type RefactorPreviewEntry } from "./result/refactor-preview.ts";
5
6
 
6
7
  /** Render a refactor plan from its canonical assembled evidence. */
7
8
  export function renderRefactorPlanResult(assembly: RefactorPlanResultAssembly): string {
@@ -14,14 +15,14 @@ export function renderRefactorPlanResult(assembly: RefactorPlanResultAssembly):
14
15
  lines.push("");
15
16
  lines.push(`**Plan ID:** \`${plan.id}\``);
16
17
  lines.push(`**Operation:** \`${plan.operation}\``);
17
- lines.push(
18
- `**Target:** \`${toDisplayPath(cwd, plan.targetFile)}\`:${plan.targetLine}:${plan.targetCharacter}`,
19
- );
18
+ lines.push(`**${plan.target ? "Target" : "File"}:** ${formatPlanScope(plan, cwd)}`);
20
19
  if (plan.newName) {
21
20
  lines.push(`**New name:** \`${plan.newName}\``);
22
21
  }
23
- if (plan.destination) {
24
- lines.push(`**Destination:** \`${plan.destination}\``);
22
+ if (plan.action) {
23
+ lines.push(`**Action:** ${plan.action.title} (\`${plan.action.kind}\`)`);
24
+ const source = actionSource(plan.action.provenance);
25
+ if (source) lines.push(`**Source:** ${source}`);
25
26
  }
26
27
  lines.push(`**Confidence:** \`${assembly.assembled.confidence}\``);
27
28
  lines.push(`**Files to change:** ${fileCount} file${fileCount !== 1 ? "s" : ""}`);
@@ -37,14 +38,8 @@ export function renderRefactorPlanResult(assembly: RefactorPlanResultAssembly):
37
38
  lines.push("");
38
39
  lines.push("## Preview");
39
40
  lines.push("");
40
- for (const edit of edits.items) {
41
- const range = edit.range;
42
- lines.push(
43
- `- \`${toDisplayPath(cwd, edit.file)}\` L${range.start.line + 1}:${range.start.character + 1} → L${range.end.line + 1}:${range.end.character + 1}`,
44
- );
45
- lines.push(" ```");
46
- lines.push(` ${edit.newText.split("\n").join("\n ")}`);
47
- lines.push(" ```");
41
+ for (const entry of buildRefactorPreview(edits.items)) {
42
+ lines.push(...renderPreviewEntry(entry, cwd));
48
43
  }
49
44
  const disclosure = renderEvidenceListDisclosure(edits);
50
45
  if (disclosure) {
@@ -73,14 +68,28 @@ export function renderRefactorApplyResult(assembly: RefactorApplyResultAssembly)
73
68
  if (plan.newName) {
74
69
  lines.push(`- New name: \`${plan.newName}\``);
75
70
  }
76
- if (plan.destination) {
77
- lines.push(`- Destination: \`${plan.destination}\``);
71
+ if (plan.action) {
72
+ lines.push(`- Action: ${plan.action.title} (\`${plan.action.kind}\`)`);
78
73
  }
79
74
  const followUps = assembledNextQueries(assembly.assembled);
80
75
  if (followUps.length > 0) lines.push("", ...followUps);
81
76
  return lines.join("\n");
82
77
  }
83
78
 
79
+ /** Render the operation scope: a rename target point, a code-action range, or a whole file. */
80
+ function formatPlanScope(
81
+ plan: RefactorPlanResultAssembly["assembled"]["data"]["plan"],
82
+ cwd: string,
83
+ ): string {
84
+ const file = `\`${toDisplayPath(cwd, plan.file)}\``;
85
+ if (plan.target) return `${file}:${plan.target.line}:${plan.target.character}`;
86
+ if (plan.range) {
87
+ const { start, end } = plan.range;
88
+ return `${file} L${start.line}:${start.character} → L${end.line}:${end.character}`;
89
+ }
90
+ return `${file} (whole file)`;
91
+ }
92
+
84
93
  function collectChangedFiles(
85
94
  plan: RefactorPlanResultAssembly["assembled"]["data"]["plan"],
86
95
  ): Array<[file: string, count: number]> {
@@ -90,3 +99,34 @@ function collectChangedFiles(
90
99
  }
91
100
  return [...counts.entries()];
92
101
  }
102
+
103
+ /** Describe how a code-action plan obtained its edits. */
104
+ function actionSource(provenance: "edit" | "captured-command" | undefined): string | null {
105
+ if (provenance === "edit") return "code action edit";
106
+ if (provenance === "captured-command") {
107
+ return "edit captured from the server command; it was refused, not applied";
108
+ }
109
+ return null;
110
+ }
111
+
112
+ /** Render one server edit as its replacement text, or a combined line as before/after. */
113
+ function renderPreviewEntry(entry: RefactorPreviewEntry, cwd: string): string[] {
114
+ if (entry.kind === "line") {
115
+ const at = `L${entry.line + 1}`;
116
+ return [
117
+ `- \`${toDisplayPath(cwd, entry.file)}\` ${at}:${entry.startCharacter + 1} → ${at}:${entry.endCharacter + 1} (${entry.editCount} edits)`,
118
+ " ```",
119
+ ` - ${entry.before}`,
120
+ ` + ${entry.after}`,
121
+ " ```",
122
+ ];
123
+ }
124
+ const { edit } = entry;
125
+ const range = edit.range;
126
+ return [
127
+ `- \`${toDisplayPath(cwd, edit.file)}\` L${range.start.line + 1}:${range.start.character + 1} → L${range.end.line + 1}:${range.end.character + 1}`,
128
+ " ```",
129
+ ` ${edit.newText.split("\n").join("\n ")}`,
130
+ " ```",
131
+ ];
132
+ }
@@ -12,6 +12,7 @@ import {
12
12
  type CodeIntelligenceToolPromptSurfaceMap,
13
13
  } from "./guidance.ts";
14
14
  import { boundCodeToolResult } from "./infra/truncate.ts";
15
+ import { CODE_TOOL_NAMESPACE } from "./namespace.ts";
15
16
  import { CODE_INTELLIGENCE_TOOL_SPECS, type CodeIntelligenceToolDefinitionSpec } from "./specs.ts";
16
17
 
17
18
  /**
@@ -101,6 +102,8 @@ export function registerCodeIntelligenceTools(
101
102
  pi.registerTool({
102
103
  name: spec.name,
103
104
  label: spec.label,
105
+ namespace: CODE_TOOL_NAMESPACE,
106
+ annotations: spec.annotations,
104
107
  description: surface.description,
105
108
  promptSnippet: surface.promptSnippet,
106
109
  promptGuidelines: surface.promptGuidelines,