@mrclrchtr/supi-code-intelligence 11.3.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 (132) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +15 -9
  3. package/node_modules/@mrclrchtr/supi-code-runtime/package.json +1 -1
  4. package/node_modules/@mrclrchtr/supi-code-runtime/src/api.ts +3 -1
  5. package/node_modules/@mrclrchtr/supi-code-runtime/src/declaration-level.ts +34 -0
  6. package/node_modules/@mrclrchtr/supi-code-runtime/src/types.ts +64 -28
  7. package/node_modules/@mrclrchtr/supi-core/package.json +1 -1
  8. package/node_modules/@mrclrchtr/supi-lsp/README.md +22 -17
  9. package/node_modules/@mrclrchtr/supi-lsp/node_modules/@mrclrchtr/supi-code-runtime/package.json +1 -1
  10. package/node_modules/@mrclrchtr/supi-lsp/node_modules/@mrclrchtr/supi-code-runtime/src/api.ts +3 -1
  11. package/node_modules/@mrclrchtr/supi-lsp/node_modules/@mrclrchtr/supi-code-runtime/src/declaration-level.ts +34 -0
  12. package/node_modules/@mrclrchtr/supi-lsp/node_modules/@mrclrchtr/supi-code-runtime/src/types.ts +64 -28
  13. package/node_modules/@mrclrchtr/supi-lsp/node_modules/@mrclrchtr/supi-core/package.json +1 -1
  14. package/node_modules/@mrclrchtr/supi-lsp/node_modules/semver/classes/range.js +2 -2
  15. package/node_modules/@mrclrchtr/supi-lsp/node_modules/semver/internal/constants.js +30 -0
  16. package/node_modules/@mrclrchtr/supi-lsp/node_modules/semver/internal/trim-comparator-whitespace.js +438 -0
  17. package/node_modules/@mrclrchtr/supi-lsp/node_modules/semver/package.json +1 -1
  18. package/node_modules/@mrclrchtr/supi-lsp/package.json +3 -3
  19. package/node_modules/@mrclrchtr/supi-lsp/src/api.ts +2 -2
  20. package/node_modules/@mrclrchtr/supi-lsp/src/client/client-diagnostic-capabilities.ts +13 -3
  21. package/node_modules/@mrclrchtr/supi-lsp/src/client/client-diagnostics.ts +25 -9
  22. package/node_modules/@mrclrchtr/supi-lsp/src/client/client-document-sync.ts +7 -5
  23. package/node_modules/@mrclrchtr/supi-lsp/src/client/client-edit-capture.ts +258 -0
  24. package/node_modules/@mrclrchtr/supi-lsp/src/client/client.ts +64 -11
  25. package/node_modules/@mrclrchtr/supi-lsp/src/config/capabilities.ts +8 -0
  26. package/node_modules/@mrclrchtr/supi-lsp/src/config/operation-support.ts +48 -79
  27. package/node_modules/@mrclrchtr/supi-lsp/src/config/tsconfig-scope.ts +10 -0
  28. package/node_modules/@mrclrchtr/supi-lsp/src/manager/manager-typescript-coverage.ts +118 -0
  29. package/node_modules/@mrclrchtr/supi-lsp/src/manager/manager.ts +67 -3
  30. package/node_modules/@mrclrchtr/supi-lsp/src/manager/typescript-file-local.ts +87 -0
  31. package/node_modules/@mrclrchtr/supi-lsp/src/provider/lsp-refactor-provider.ts +21 -35
  32. package/node_modules/@mrclrchtr/supi-lsp/src/provider/refactor-command-capture.ts +139 -0
  33. package/node_modules/@mrclrchtr/supi-lsp/src/provider/refactor-planning.ts +202 -47
  34. package/node_modules/@mrclrchtr/supi-lsp/src/provider/semantic-symbol-mapper.ts +22 -17
  35. package/node_modules/@mrclrchtr/supi-lsp/src/session/route-boundary.ts +26 -0
  36. package/node_modules/@mrclrchtr/supi-lsp/src/session/runtime-registry.ts +106 -16
  37. package/node_modules/@mrclrchtr/supi-lsp/src/session/runtime-rename.ts +3 -0
  38. package/node_modules/@mrclrchtr/supi-lsp/src/session/workspace-lsp-runtime.ts +22 -1
  39. package/node_modules/@mrclrchtr/supi-tree-sitter/README.md +1 -1
  40. package/node_modules/@mrclrchtr/supi-tree-sitter/node_modules/@mrclrchtr/supi-code-runtime/package.json +1 -1
  41. package/node_modules/@mrclrchtr/supi-tree-sitter/node_modules/@mrclrchtr/supi-code-runtime/src/api.ts +3 -1
  42. package/node_modules/@mrclrchtr/supi-tree-sitter/node_modules/@mrclrchtr/supi-code-runtime/src/declaration-level.ts +34 -0
  43. package/node_modules/@mrclrchtr/supi-tree-sitter/node_modules/@mrclrchtr/supi-code-runtime/src/types.ts +64 -28
  44. package/node_modules/@mrclrchtr/supi-tree-sitter/node_modules/@mrclrchtr/supi-core/package.json +1 -1
  45. package/node_modules/@mrclrchtr/supi-tree-sitter/package.json +3 -3
  46. package/node_modules/@mrclrchtr/supi-tree-sitter/resources/grammars/tsx/tree-sitter-tsx.wasm +0 -0
  47. package/node_modules/@mrclrchtr/supi-tree-sitter/resources/grammars/tsx/tree-sitter-tsx.wasm.json +5 -1
  48. package/node_modules/@mrclrchtr/supi-tree-sitter/resources/grammars/typescript/tree-sitter-typescript.wasm +0 -0
  49. package/node_modules/@mrclrchtr/supi-tree-sitter/resources/grammars/typescript/tree-sitter-typescript.wasm.json +5 -1
  50. package/node_modules/@mrclrchtr/supi-tree-sitter/src/coordinates.ts +16 -2
  51. package/node_modules/@mrclrchtr/supi-tree-sitter/src/session/structural-worker-client.ts +3 -2
  52. package/node_modules/@mrclrchtr/supi-tree-sitter/src/syntax-errors.ts +2 -0
  53. package/node_modules/@mrclrchtr/supi-tree-sitter/src/tool/call-range.ts +94 -0
  54. package/node_modules/@mrclrchtr/supi-tree-sitter/src/tool/call-sites.ts +26 -6
  55. package/node_modules/@mrclrchtr/supi-tree-sitter/src/tool/callees.ts +6 -3
  56. package/node_modules/@mrclrchtr/supi-tree-sitter/src/tool/exports.ts +13 -4
  57. package/node_modules/@mrclrchtr/supi-tree-sitter/src/worker/runtime.ts +1 -9
  58. package/package.json +5 -5
  59. package/src/analysis/health/server-status.ts +41 -12
  60. package/src/analysis/helpers.ts +0 -7
  61. package/src/analysis/relations/implementations.ts +5 -0
  62. package/src/analysis/relations/references.ts +5 -0
  63. package/src/analysis/target/anchored-structural.ts +4 -1
  64. package/src/analysis/target/file-merge.ts +162 -0
  65. package/src/analysis/target/file-outline-omissions.ts +146 -0
  66. package/src/analysis/target/file-refinement.ts +7 -7
  67. package/src/analysis/target/file.ts +44 -156
  68. package/src/analysis/target/symbol.ts +5 -1
  69. package/src/analysis/target/types.ts +32 -6
  70. package/src/api.ts +1 -1
  71. package/src/app/app.ts +9 -3
  72. package/src/session/find-types.ts +8 -4
  73. package/src/session/find-workflow.ts +11 -16
  74. package/src/session/graph/collect.ts +2 -0
  75. package/src/session/graph-types.ts +3 -1
  76. package/src/session/graph-workflow.ts +5 -4
  77. package/src/session/input/health-refactor.ts +48 -34
  78. package/src/session/input/workflows.ts +45 -46
  79. package/src/session/inspect/file-point.ts +2 -2
  80. package/src/session/inspect-types.ts +1 -1
  81. package/src/session/inspect-workflow.ts +3 -3
  82. package/src/session/orientation/workspace-context.ts +3 -0
  83. package/src/session/orientation-workflow.ts +6 -3
  84. package/src/session/refactor-file-actions.ts +122 -0
  85. package/src/session/refactor-plan-pipeline.ts +152 -0
  86. package/src/session/refactor-plans.ts +18 -15
  87. package/src/session/refactor-types.ts +24 -12
  88. package/src/session/refactor-workflow.ts +70 -244
  89. package/src/session/session.ts +87 -12
  90. package/src/session/target-workflow.ts +23 -21
  91. package/src/tool/code_find/execute.ts +6 -7
  92. package/src/tool/code_find/spec.ts +9 -16
  93. package/src/tool/code_find/tui.ts +12 -6
  94. package/src/tool/code_graph/section.ts +4 -0
  95. package/src/tool/code_graph/spec.ts +6 -0
  96. package/src/tool/code_health/spec.ts +6 -0
  97. package/src/tool/code_health/structured-schema.ts +4 -4
  98. package/src/tool/code_health/structured.ts +15 -17
  99. package/src/tool/code_inspect/execute.ts +1 -1
  100. package/src/tool/code_inspect/markdown.ts +33 -6
  101. package/src/tool/code_inspect/result.ts +1 -1
  102. package/src/tool/code_inspect/spec.ts +14 -6
  103. package/src/tool/code_inspect/structured.ts +2 -2
  104. package/src/tool/code_inspect/tui.ts +2 -2
  105. package/src/tool/code_orientation/directory-navigation.ts +20 -31
  106. package/src/tool/code_orientation/spec.ts +8 -0
  107. package/src/tool/code_orientation/workspace-output.ts +40 -13
  108. package/src/tool/code_orientation/workspace-sections.ts +45 -2
  109. package/src/tool/code_refactor_apply/result.ts +2 -1
  110. package/src/tool/code_refactor_apply/spec.ts +7 -0
  111. package/src/tool/code_refactor_plan/execute.ts +0 -2
  112. package/src/tool/code_refactor_plan/result.ts +23 -13
  113. package/src/tool/code_refactor_plan/spec.ts +8 -2
  114. package/src/tool/code_refactor_plan/structured.ts +59 -12
  115. package/src/tool/code_refactor_plan/tui.ts +14 -17
  116. package/src/tool/code_resolve/guidance.ts +1 -1
  117. package/src/tool/code_resolve/markdown.ts +121 -34
  118. package/src/tool/code_resolve/result.ts +18 -15
  119. package/src/tool/code_resolve/spec.ts +6 -0
  120. package/src/tool/code_resolve/structured.ts +43 -10
  121. package/src/tool/namespace.ts +14 -0
  122. package/src/tool/refactor-markdown.ts +55 -15
  123. package/src/tool/register.ts +3 -0
  124. package/src/tool/result/model-budget.ts +2 -2
  125. package/src/tool/result/refactor-preview.ts +118 -0
  126. package/src/tool/result/refactor-unavailable.ts +16 -0
  127. package/src/tool/result/refactor.ts +8 -2
  128. package/src/tool/result/types.ts +13 -10
  129. package/src/tool/schemas.ts +63 -20
  130. package/src/tool/specs.ts +3 -0
  131. package/src/ui/status-overlay.ts +1 -1
  132. package/src/ui/tui/common.ts +10 -10
@@ -2,6 +2,7 @@
2
2
 
3
3
  import { renderEvidenceListMetadataDisclosure } from "../../analysis/evidence.ts";
4
4
  import { toDisplayPath } from "../../analysis/search/paths.ts";
5
+ import type { TargetProviderProvenance } from "../../session/target-store.ts";
5
6
  import type { TargetWorkflowOutcome } from "../../session/target-workflow.ts";
6
7
  import { formatPartialCandidateDisclosure } from "../result/candidate-row.ts";
7
8
  import type { ResolveDetails } from "../result/types.ts";
@@ -13,8 +14,8 @@ export function renderResolveResult(assembly: ResolveResultAssembly): string {
13
14
  switch (outcome.kind) {
14
15
  case "resolved":
15
16
  return renderResolved(outcome, cwd);
16
- case "target-group":
17
- return renderTargetGroup(assembly.details);
17
+ case "file-outline":
18
+ return renderFileOutline(assembly.details);
18
19
  case "disambiguation":
19
20
  return renderDisambiguation(assembly.details);
20
21
  case "kind-mismatch":
@@ -47,60 +48,146 @@ function renderResolved(
47
48
  return lines.join("\n");
48
49
  }
49
50
 
50
- function renderTargetGroup(details: ResolveDetails): string {
51
- const discovery = details.groupDiscoveryProvenance?.join("+") || "unavailable";
52
- const lines = [
53
- `# Targets in \`${details.groupFile ?? "file"}\``,
54
- "",
55
- `- Group confidence: \`${details.confidence}\``,
56
- `- Discovery provenance: \`${discovery}\``,
57
- ];
58
- appendUnknownHierarchyDisclosure(lines, details.groupUnknownNestingCount ?? 0);
59
- appendGroupRecoveryDisclosure(lines, details);
51
+ function renderFileOutline(details: ResolveDetails): string {
52
+ const lines = [`# File outline of \`${details.outlineFile ?? "file"}\``, ""];
53
+ lines.push(`- Sources: ${outlineSources(details.outlineDiscoveryProvenance ?? [])}`);
54
+ appendUnknownLevelDisclosure(lines, details.outlineUnknownLevelCount ?? 0);
55
+ appendOutlineRecoveryDisclosure(lines, details);
60
56
  lines.push("");
61
- appendTargetGroupItems(lines, details);
57
+ appendFileOutlineItems(lines, details);
62
58
  appendDisclosure(lines, details);
59
+ appendNotListed(lines, details);
63
60
  return lines.join("\n");
64
61
  }
65
62
 
66
- function appendTargetGroupItems(lines: string[], details: ResolveDetails): void {
63
+ const SOURCE_NAMES: Record<TargetProviderProvenance, string> = {
64
+ semantic: "language server",
65
+ structural: "syntax parser",
66
+ };
67
+
68
+ function outlineSources(provenance: readonly TargetProviderProvenance[]): string {
69
+ return provenance.length
70
+ ? provenance.map((source) => SOURCE_NAMES[source]).join(" and ")
71
+ : "none";
72
+ }
73
+
74
+ function appendFileOutlineItems(lines: string[], details: ResolveDetails): void {
67
75
  if (details.targets.length === 0) {
68
76
  lines.push(
69
- details.groupPartialReason
77
+ details.outlinePartialReason
70
78
  ? "No declarations were collected before structural recovery limited discovery."
71
79
  : "No declarations were reported for this file.",
72
80
  );
73
81
  return;
74
82
  }
75
- lines.push(declarationCountHeading(details.targetCount), "");
76
- for (const target of details.targets) {
77
- const displayKind = target.nativeKind ?? target.kind;
78
- const kind = displayKind ? ` (\`${displayKind}\`)` : "";
79
- const container = target.container ? ` in \`${target.container}\`` : "";
80
- lines.push(
81
- `- \`${target.targetId}\` **${target.name ?? "anonymous"}**${kind}${container} — \`${target.displayLine}:${target.displayCharacter}\` (${target.anchorKind} anchor, ${target.confidence}, provenance: ${target.provenance.join("+")})`,
82
- );
83
+ const count = details.targetCount;
84
+ lines.push(
85
+ `${count} declaration${count === 1 ? "" : "s"}: top-level declarations in source order, members indented below their container. Pass a handle as target.handle to code_graph, code_inspect, or code_refactor_plan.`,
86
+ "",
87
+ );
88
+ appendGroupedRows(lines, details.targets);
89
+ }
90
+
91
+ type OutlineRowTarget = ResolveDetails["targets"][number];
92
+
93
+ /**
94
+ * Render each visible member directly below its visible container, so the
95
+ * container name is not repeated per row. Members whose container is not a
96
+ * uniquely named visible row keep an explicit `in` suffix.
97
+ */
98
+ function appendGroupedRows(lines: string[], targets: readonly OutlineRowTarget[]): void {
99
+ const containerCounts = new Map<string, number>();
100
+ for (const target of targets) {
101
+ if (target.name) containerCounts.set(target.name, (containerCounts.get(target.name) ?? 0) + 1);
102
+ }
103
+ const children = new Map<string, OutlineRowTarget[]>();
104
+ const roots: OutlineRowTarget[] = [];
105
+ for (const target of targets) {
106
+ const container = target.container;
107
+ if (container && container !== target.name && containerCounts.get(container) === 1) {
108
+ children.set(container, [...(children.get(container) ?? []), target]);
109
+ } else {
110
+ roots.push(target);
111
+ }
83
112
  }
113
+ const emit = (target: OutlineRowTarget, depth: number): void => {
114
+ lines.push(outlineRow(target, depth));
115
+ const own = target.name ? children.get(target.name) : undefined;
116
+ if (!own) return;
117
+ children.delete(target.name ?? "");
118
+ for (const child of own) emit(child, depth + 1);
119
+ };
120
+ for (const root of roots) emit(root, 0);
121
+ // Containers that are themselves grouped under a hidden row fall back to suffixes.
122
+ for (const orphans of children.values()) for (const orphan of orphans) emit(orphan, 0);
123
+ }
124
+
125
+ /** One compact row; evidence notes appear only when they differ from the usual case. */
126
+ function outlineRow(target: OutlineRowTarget, depth: number): string {
127
+ const displayKind = outlineKind(target.nativeKind ?? target.kind);
128
+ const kind = displayKind ? `${displayKind} ` : "";
129
+ const container = depth === 0 && target.container ? ` in \`${target.container}\`` : "";
130
+ const indent = " ".repeat(depth);
131
+ const suffix = target.provenance.includes("semantic") ? "" : " (syntax parser only)";
132
+ const name = (target.name ?? "anonymous").replace(/\s+/g, " ");
133
+ return `${indent}- \`${target.targetId}\` ${kind}\`${name}\`${container} — L${target.displayLine}:${target.displayCharacter}${suffix}`;
84
134
  }
85
135
 
86
- function appendGroupRecoveryDisclosure(lines: string[], details: ResolveDetails): void {
87
- if (!details.groupPartialReason) return;
88
- const locations = (details.groupErrorRanges ?? []).map(
136
+ /** Lower-case words for both providers' kinds, e.g. `EnumMember` -> `enum member`. */
137
+ function outlineKind(kind: string | null | undefined): string {
138
+ return (kind ?? "").replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase();
139
+ }
140
+
141
+ function appendNotListed(lines: string[], details: ResolveDetails): void {
142
+ const notListed = details.outlineNotListed;
143
+ if (!notListed) return;
144
+ const span = (value: { startLine: number; endLine: number }) =>
145
+ value.startLine === value.endLine
146
+ ? `L${value.startLine}`
147
+ : `L${value.startLine}–L${value.endLine}`;
148
+ const rows = [
149
+ ...(notListed.importedNames
150
+ ? [
151
+ `- ${plural(notListed.importedNames.count, "imported name")} (${span(notListed.importedNames)}). Read those lines, or resolve a name with code_resolve target.symbol.`,
152
+ ]
153
+ : []),
154
+ ...(notListed.reExportStatements
155
+ ? [
156
+ `- ${plural(notListed.reExportStatements.count, "`export … from` statement")} (${span(notListed.reExportStatements)}); they forward names declared in other modules.`,
157
+ ]
158
+ : []),
159
+ ...(notListed.exportListNames
160
+ ? [
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
+ ]
163
+ : []),
164
+ ...(notListed.localDeclarations > 0
165
+ ? [
166
+ `- ${plural(notListed.localDeclarations, "declaration")} inside function, method, or constructor bodies. Resolve one with code_resolve target.symbol and scope set to this file.`,
167
+ ]
168
+ : []),
169
+ ];
170
+ if (rows.length) lines.push("", "Not listed:", ...rows);
171
+ }
172
+
173
+ function plural(count: number, noun: string): string {
174
+ return `${count} ${noun}${count === 1 ? "" : "s"}`;
175
+ }
176
+
177
+ function appendOutlineRecoveryDisclosure(lines: string[], details: ResolveDetails): void {
178
+ if (!details.outlinePartialReason) return;
179
+ const locations = (details.outlineErrorRanges ?? []).map(
89
180
  (range) => `L${range.start.line + 1}:${range.start.character + 1}`,
90
181
  );
91
182
  const errors = locations.length ? ` Error locations: ${locations.join(", ")}.` : "";
92
- lines.push(`- Partial discovery: ${details.groupPartialReason}${errors}`);
93
- }
94
-
95
- function declarationCountHeading(count: number): string {
96
- return `**${count} declaration${count === 1 ? "" : "s"} discovered**`;
183
+ lines.push(`- Partial discovery: ${details.outlinePartialReason}${errors}`);
97
184
  }
98
185
 
99
- function appendUnknownHierarchyDisclosure(lines: string[], count: number): void {
186
+ function appendUnknownLevelDisclosure(lines: string[], count: number): void {
100
187
  if (count <= 0) return;
101
- const declaration = count === 1 ? "declaration has" : "declarations have";
188
+ const declarations = count === 1 ? "declaration has" : "declarations have";
102
189
  lines.push(
103
- `- Hierarchy: ${count} ${declaration} unknown hierarchy; only provider-proven top-level declarations were prioritized.`,
190
+ `- Position unknown: ${count} ${declarations} no enclosing declaration reported by the language server, so ${count === 1 ? "it is" : "they are"} listed after the top-level declarations.`,
104
191
  );
105
192
  }
106
193
 
@@ -85,8 +85,8 @@ function projectResolveOutcome(outcome: TargetWorkflowOutcome, cwd: string): Res
85
85
  switch (outcome.kind) {
86
86
  case "resolved":
87
87
  return projectResolved(outcome, cwd);
88
- case "target-group":
89
- return projectTargetGroup(outcome, cwd);
88
+ case "file-outline":
89
+ return projectFileOutline(outcome, cwd);
90
90
  case "disambiguation":
91
91
  case "kind-mismatch":
92
92
  return projectCandidateOutcome(outcome, cwd);
@@ -121,8 +121,8 @@ function projectResolved(
121
121
  };
122
122
  }
123
123
 
124
- function projectTargetGroup(
125
- outcome: Extract<TargetWorkflowOutcome, { kind: "target-group" }>,
124
+ function projectFileOutline(
125
+ outcome: Extract<TargetWorkflowOutcome, { kind: "file-outline" }>,
126
126
  cwd: string,
127
127
  ): ResolveProjection {
128
128
  const evidence = {
@@ -138,19 +138,20 @@ function projectTargetGroup(
138
138
  },
139
139
  };
140
140
  return {
141
- key: "resolve.target-group",
142
- title: "Target group",
141
+ key: "resolve.file-outline",
142
+ title: "File outline",
143
143
  status: outcome.partial ? "partial" : "complete",
144
144
  items: evidence.items,
145
145
  confidence: outcome.confidence,
146
146
  evidence: evidence.metadata,
147
147
  details: {
148
- resultKind: "target-group",
149
- groupFile: toDisplayPath(cwd, outcome.file),
150
- groupDiscoveryProvenance: [...outcome.discoveryProvenance],
151
- groupUnknownNestingCount: outcome.unknownNestingCount,
152
- groupPartialReason: outcome.partial?.reason ?? null,
153
- groupErrorRanges: outcome.partial?.errorRanges,
148
+ resultKind: "file-outline",
149
+ outlineFile: toDisplayPath(cwd, outcome.file),
150
+ outlineDiscoveryProvenance: [...outcome.discoveryProvenance],
151
+ outlineUnknownLevelCount: outcome.unknownLevelCount,
152
+ outlinePartialReason: outcome.partial?.reason ?? null,
153
+ outlineErrorRanges: outcome.partial?.errorRanges,
154
+ outlineNotListed: outcome.notListed,
154
155
  confidence: outcome.confidence,
155
156
  targetCount: outcome.totalCount,
156
157
  omittedCount: evidence.metadata.omittedCount,
@@ -158,7 +159,9 @@ function projectTargetGroup(
158
159
  targets: evidence.items.map((target) => toTargetDetails(target, cwd)),
159
160
  nextQueries:
160
161
  outcome.totalCount > 0
161
- ? ["Choose one Target group member handle for precise graph or refactor work"]
162
+ ? [
163
+ "Pass one declaration handle from the file outline as target.handle to code_graph, code_inspect, or code_refactor_plan",
164
+ ]
162
165
  : ["Use code_inspect for point facts or code_find for explicit source evidence"],
163
166
  },
164
167
  };
@@ -298,7 +301,7 @@ function resolveProvenance(outcome: TargetWorkflowOutcome): ResultProvenance[] {
298
301
  const sources = new Set<"semantic" | "structural">();
299
302
  if (outcome.kind === "resolved") {
300
303
  for (const source of outcome.entry.provenance) sources.add(source);
301
- } else if (outcome.kind === "target-group") {
304
+ } else if (outcome.kind === "file-outline") {
302
305
  for (const source of outcome.discoveryProvenance) sources.add(source);
303
306
  } else if (outcome.kind === "disambiguation" || outcome.kind === "kind-mismatch") {
304
307
  sources.add("semantic");
@@ -343,7 +346,7 @@ export function finishResolveResult(
343
346
  type: "resolve",
344
347
  data: assembly.details,
345
348
  status:
346
- outcome.kind === "resolved" || outcome.kind === "target-group"
349
+ outcome.kind === "resolved" || outcome.kind === "file-outline"
347
350
  ? "completed"
348
351
  : outcome.kind === "disambiguation" || outcome.kind === "kind-mismatch"
349
352
  ? "disambiguation"
@@ -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
  {
@@ -8,11 +8,16 @@ import {
8
8
  } from "../result/structured.ts";
9
9
  import type { ResolveDetails } from "../result/types.ts";
10
10
 
11
+ const NameSpanSchema = Type.Object(
12
+ { count: Type.Integer(), startLine: Type.Integer(), endLine: Type.Integer() },
13
+ { additionalProperties: false },
14
+ );
15
+
11
16
  /** Codemode contract for resolution, including candidate selection and invalid input. */
12
17
  export const ResolveOutputSchema = Type.Object(
13
18
  {
14
19
  kind: Type.Enum(
15
- ["resolved", "target-group", "disambiguation", "kind-mismatch", "invalid-input"],
20
+ ["resolved", "file-outline", "disambiguation", "kind-mismatch", "invalid-input"],
16
21
  { type: "string" },
17
22
  ),
18
23
  confidence: ConfidenceSchema,
@@ -23,7 +28,18 @@ export const ResolveOutputSchema = Type.Object(
23
28
  message: Type.Optional(Type.String()),
24
29
  file: Type.Optional(Type.String()),
25
30
  requestedKind: Type.Optional(Type.String()),
26
- unknownNestingCount: Type.Optional(Type.Integer()),
31
+ unknownLevelCount: Type.Optional(Type.Integer()),
32
+ notListed: Type.Optional(
33
+ Type.Object(
34
+ {
35
+ importedNames: Type.Union([NameSpanSchema, Type.Null()]),
36
+ exportListNames: Type.Union([NameSpanSchema, Type.Null()]),
37
+ reExportStatements: Type.Union([NameSpanSchema, Type.Null()]),
38
+ localDeclarations: Type.Integer(),
39
+ },
40
+ { additionalProperties: false },
41
+ ),
42
+ ),
27
43
  discoveryProvenance: Type.Optional(
28
44
  Type.Array(Type.Enum(["semantic", "structural"], { type: "string" })),
29
45
  ),
@@ -80,22 +96,39 @@ export function structuredResolveResult(
80
96
  nextQueries: data.nextQueries,
81
97
  notes: outcome.kind === "resolved" ? [...outcome.notes] : [],
82
98
  ...(data.message === undefined ? {} : { message: data.message }),
83
- ...(data.groupFile === undefined ? {} : { file: data.groupFile }),
99
+ ...(data.outlineFile === undefined ? {} : { file: data.outlineFile }),
84
100
  ...(data.requestedKind === undefined ? {} : { requestedKind: data.requestedKind }),
85
- ...(data.groupUnknownNestingCount === undefined
101
+ ...(data.outlineNotListed === undefined
102
+ ? {}
103
+ : { notListed: structuredNotListed(data.outlineNotListed) }),
104
+ ...(data.outlineUnknownLevelCount === undefined
86
105
  ? {}
87
- : { unknownNestingCount: data.groupUnknownNestingCount }),
88
- ...(data.groupDiscoveryProvenance === undefined
106
+ : { unknownLevelCount: data.outlineUnknownLevelCount }),
107
+ ...(data.outlineDiscoveryProvenance === undefined
89
108
  ? {}
90
- : { discoveryProvenance: [...data.groupDiscoveryProvenance] }),
91
- ...(data.groupPartialReason === undefined ? {} : { partialReason: data.groupPartialReason }),
92
- ...(data.groupErrorRanges === undefined
109
+ : { discoveryProvenance: [...data.outlineDiscoveryProvenance] }),
110
+ ...(data.outlinePartialReason === undefined
111
+ ? {}
112
+ : { partialReason: data.outlinePartialReason }),
113
+ ...(data.outlineErrorRanges === undefined
93
114
  ? {}
94
115
  : {
95
- errorRanges: data.groupErrorRanges.map((range) => ({
116
+ errorRanges: data.outlineErrorRanges.map((range) => ({
96
117
  start: { ...range.start },
97
118
  end: { ...range.end },
98
119
  })),
99
120
  }),
100
121
  };
101
122
  }
123
+
124
+ /** Copy outline omission counts into the codemode contract. */
125
+ function structuredNotListed(notListed: NonNullable<ResolveDetails["outlineNotListed"]>) {
126
+ const span = (value: { count: number; startLine: number; endLine: number } | null) =>
127
+ value ? { ...value } : null;
128
+ return {
129
+ importedNames: span(notListed.importedNames),
130
+ exportListNames: span(notListed.exportListNames),
131
+ reExportStatements: span(notListed.reExportStatements),
132
+ localDeclarations: notListed.localDeclarations,
133
+ };
134
+ }
@@ -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,
@@ -113,8 +113,8 @@ function sectionFacts(details: Details): string[] {
113
113
  case "resolve":
114
114
  return [
115
115
  `${details.data.resultKind}: ${details.data.targetCount} targets; ${details.data.omittedCount} cap omissions.`,
116
- ...(details.data.groupPartialReason
117
- ? [`Partial discovery: ${details.data.groupPartialReason}`]
116
+ ...(details.data.outlinePartialReason
117
+ ? [`Partial discovery: ${details.data.outlinePartialReason}`]
118
118
  : []),
119
119
  ...details.data.targets
120
120
  .slice(0, 3)
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Readable preview entries for refactor plans.
3
+ *
4
+ * Some servers (kotlin-lsp) return minimal character-level edits, so renaming
5
+ * `total` to `sumDoubled` arrives as `sumD`, `ub`, `ed`. The preview combines
6
+ * consecutive single-line edits on one line into one before/after entry. The
7
+ * stored plan and its edits stay exactly as the server returned them.
8
+ */
9
+
10
+ import { readFileSync } from "node:fs";
11
+ import type { FileEdit } from "@mrclrchtr/supi-code-runtime/api";
12
+
13
+ /** One preview entry: a server edit as is, or several edits on one line combined. */
14
+ export type RefactorPreviewEntry =
15
+ | { readonly kind: "edit"; readonly edit: FileEdit }
16
+ | {
17
+ readonly kind: "line";
18
+ readonly file: string;
19
+ /** Zero-based line and UTF-16 span covering every combined edit. */
20
+ readonly line: number;
21
+ readonly startCharacter: number;
22
+ readonly endCharacter: number;
23
+ readonly before: string;
24
+ readonly after: string;
25
+ readonly editCount: number;
26
+ };
27
+
28
+ /**
29
+ * Number of leading edits to show so that at least `maxResults` are shown and
30
+ * the last shown edit does not split a group of edits on the same line.
31
+ */
32
+ export function previewEditCount(edits: readonly FileEdit[], maxResults: number): number {
33
+ let count = Math.min(Math.max(0, maxResults), edits.length);
34
+ while (count > 0 && count < edits.length) {
35
+ const last = edits[count - 1] as FileEdit;
36
+ const next = edits[count] as FileEdit;
37
+ if (!isInlineEdit(last) || !isInlineEdit(next) || !sameLine(last, next)) break;
38
+ count++;
39
+ }
40
+ return count;
41
+ }
42
+
43
+ /** Combine consecutive edits on one line when the current file text allows it. */
44
+ export function buildRefactorPreview(edits: readonly FileEdit[]): RefactorPreviewEntry[] {
45
+ const lines = new Map<string, readonly string[] | null>();
46
+ const entries: RefactorPreviewEntry[] = [];
47
+ for (let index = 0; index < edits.length; ) {
48
+ let end = index + 1;
49
+ const first = edits[index] as FileEdit;
50
+ while (
51
+ end < edits.length &&
52
+ isInlineEdit(first) &&
53
+ isInlineEdit(edits[end] as FileEdit) &&
54
+ sameLine(first, edits[end] as FileEdit)
55
+ ) {
56
+ end++;
57
+ }
58
+ const group = edits.slice(index, end);
59
+ const combined = group.length > 1 ? combineLine(group, fileLines(first.file, lines)) : null;
60
+ if (combined) entries.push(combined);
61
+ else entries.push(...group.map((edit) => ({ kind: "edit" as const, edit })));
62
+ index = end;
63
+ }
64
+ return entries;
65
+ }
66
+
67
+ function isInlineEdit(edit: FileEdit): boolean {
68
+ return edit.range.start.line === edit.range.end.line && !/[\r\n]/u.test(edit.newText);
69
+ }
70
+
71
+ function sameLine(a: FileEdit, b: FileEdit): boolean {
72
+ return a.file === b.file && a.range.start.line === b.range.start.line;
73
+ }
74
+
75
+ function fileLines(
76
+ file: string,
77
+ cache: Map<string, readonly string[] | null>,
78
+ ): readonly string[] | null {
79
+ if (!cache.has(file)) {
80
+ try {
81
+ cache.set(file, readFileSync(file, "utf8").split(/\r\n|\r|\n/u));
82
+ } catch {
83
+ cache.set(file, null);
84
+ }
85
+ }
86
+ return cache.get(file) ?? null;
87
+ }
88
+
89
+ /** Apply sorted, non-overlapping edits to their line; null when that is not possible. */
90
+ function combineLine(
91
+ group: readonly FileEdit[],
92
+ lines: readonly string[] | null,
93
+ ): RefactorPreviewEntry | null {
94
+ const first = group[0] as FileEdit;
95
+ const text = lines?.[first.range.start.line];
96
+ if (text === undefined) return null;
97
+ const sorted = [...group].sort((a, b) => a.range.start.character - b.range.start.character);
98
+ let after = "";
99
+ let cursor = (sorted[0] as FileEdit).range.start.character;
100
+ const startCharacter = cursor;
101
+ for (const edit of sorted) {
102
+ const { start, end } = edit.range;
103
+ if (start.character < cursor || end.character < start.character) return null;
104
+ if (end.character > text.length) return null;
105
+ after += text.slice(cursor, start.character) + edit.newText;
106
+ cursor = end.character;
107
+ }
108
+ return {
109
+ kind: "line",
110
+ file: first.file,
111
+ line: first.range.start.line,
112
+ startCharacter,
113
+ endCharacter: cursor,
114
+ before: text.slice(startCharacter, cursor),
115
+ after,
116
+ editCount: group.length,
117
+ };
118
+ }
@@ -0,0 +1,16 @@
1
+ /** Unavailable reasons shared by code_refactor_plan and code_refactor_apply. */
2
+
3
+ /** supi-lsp text for a request superseded by a file change while it ran. */
4
+ const SEMANTIC_INPUT_CHANGED = "Semantic input changed";
5
+ const CONCURRENT_EDIT_HINT = "Retry after concurrent edits finish.";
6
+
7
+ /**
8
+ * Add a recovery hint to a reason caused by a concurrent edit, for example a
9
+ * plan running in parallel with an apply. Other reasons are returned unchanged.
10
+ */
11
+ export function refactorUnavailableReason(reason: string): string {
12
+ if (!reason.includes(SEMANTIC_INPUT_CHANGED) || reason.includes(CONCURRENT_EDIT_HINT)) {
13
+ return reason;
14
+ }
15
+ return `${reason} ${CONCURRENT_EDIT_HINT}`;
16
+ }