@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
@@ -0,0 +1,152 @@
1
+ /** Shared refactor-plan pipeline: provider calls, readiness, validation, and plan storage. */
2
+
3
+ import type {
4
+ RefactorOperation,
5
+ RefactorRequest,
6
+ RefactorResult,
7
+ SemanticProvider,
8
+ } from "@mrclrchtr/supi-code-runtime/api";
9
+ import { SEMANTIC_READINESS_TIMEOUT_REASON } from "../analysis/readiness.ts";
10
+ import { establishMutationAuthority } from "../analysis/refactor/mutation-authority.ts";
11
+ import { validateEdit } from "../analysis/refactor/safety.ts";
12
+ import type { CapabilityAdapter } from "./capability-adapter.ts";
13
+ import { collectFileFingerprints, dropIdentityEdits } from "./refactor-identity.ts";
14
+ import {
15
+ generatePlanId,
16
+ type RefactorPlan,
17
+ validateSynchronizedContentFingerprints,
18
+ } from "./refactor-plans.ts";
19
+ import type { RefactorPlanWorkflowOutcome } from "./refactor-types.ts";
20
+ import type { TargetWorkflowDeps } from "./target-workflow.ts";
21
+ import { throwIfAborted, type WorkflowControl } from "./workflow-control.ts";
22
+
23
+ /** Session collaborators for refactor planning and apply workflows. */
24
+ export interface RefactorWorkflowDeps extends TargetWorkflowDeps {
25
+ readonly capability: CapabilityAdapter;
26
+ readonly storePlan: (plan: RefactorPlan) => string;
27
+ readonly getPlan: (id: string) => RefactorPlan | undefined;
28
+ readonly removePlan: (id: string) => void;
29
+ }
30
+
31
+ /** Wait for semantic readiness for one file; returns an outcome only when planning must stop. */
32
+ export async function ensureFileReadiness(
33
+ file: string,
34
+ deps: RefactorWorkflowDeps,
35
+ control?: WorkflowControl,
36
+ ): Promise<RefactorPlanWorkflowOutcome | null> {
37
+ const readiness = await deps.capability.ensureSemanticReadiness(
38
+ deps.cwd,
39
+ { kind: "file", file },
40
+ control,
41
+ );
42
+ throwIfAborted(control);
43
+ if (readiness.kind === "timeout") {
44
+ return { kind: "unavailable", reason: SEMANTIC_READINESS_TIMEOUT_REASON };
45
+ }
46
+ if (readiness.kind === "unavailable") return readiness;
47
+ return null;
48
+ }
49
+
50
+ /** Validate a provider result and store it as a fingerprinted plan. */
51
+ export async function finishProviderPlan(
52
+ result: RefactorResult,
53
+ deps: RefactorWorkflowDeps,
54
+ plan: {
55
+ readonly operation: RefactorOperation;
56
+ readonly file: string;
57
+ readonly discriminator: string;
58
+ readonly fields: Pick<RefactorPlan, "newName" | "target" | "range">;
59
+ readonly evidenceSource: "semantic" | "structural";
60
+ readonly sourceFingerprint?: string;
61
+ },
62
+ ): Promise<RefactorPlanWorkflowOutcome> {
63
+ if (result.kind === "unavailable") return { kind: "unavailable", reason: result.reason };
64
+ if (result.kind === "ambiguous") {
65
+ return { kind: "ambiguous", candidates: result.candidates };
66
+ }
67
+
68
+ const validation = validateEdit(result.edits);
69
+ if (!validation.safe) {
70
+ return { kind: "invalid-input", message: `Refactor safety check failed: ${validation.reason}` };
71
+ }
72
+ const authority = establishMutationAuthority(
73
+ result.edits.edits.map((edit) => edit.file),
74
+ result.authorizedMutationRoots,
75
+ );
76
+ if (authority.kind === "unavailable") return authority;
77
+ const fileFingerprints = collectFileFingerprints(
78
+ result.edits.edits,
79
+ plan.sourceFingerprint ? { file: plan.file, fingerprint: plan.sourceFingerprint } : undefined,
80
+ );
81
+ const snapshotError = validateSynchronizedContentFingerprints(
82
+ result.edits.documentPreconditions,
83
+ fileFingerprints,
84
+ deps.cwd,
85
+ );
86
+ if (snapshotError) return { kind: "unavailable", reason: snapshotError };
87
+ const changed = dropIdentityEdits(result.edits, fileFingerprints);
88
+ if (changed.kind === "unavailable") return changed;
89
+ if (changed.edits.edits.length === 0) {
90
+ return {
91
+ kind: "invalid-input",
92
+ message: `The ${plan.operation} refactor produces no changes; every planned edit matches the current text.`,
93
+ };
94
+ }
95
+
96
+ const stored: RefactorPlan = {
97
+ id: generatePlanId(plan.operation, plan.file, plan.discriminator),
98
+ operation: plan.operation,
99
+ file: plan.file,
100
+ ...plan.fields,
101
+ ...(result.action ? { action: { ...result.action } } : {}),
102
+ edits: changed.edits,
103
+ evidenceSource: plan.evidenceSource,
104
+ authorizedMutationRoots: authority.canonicalRoots,
105
+ fileFingerprints: changed.fileFingerprints,
106
+ createdAt: Date.now(),
107
+ };
108
+ deps.storePlan(stored);
109
+ return { kind: "completed", plan: immutablePlan(stored) };
110
+ }
111
+
112
+ /** Ask the active semantic provider for one refactor result. */
113
+ export async function planWithProvider(
114
+ provider: SemanticProvider | null,
115
+ request: RefactorRequest,
116
+ control?: WorkflowControl,
117
+ ): Promise<RefactorResult> {
118
+ if (!provider) return { kind: "unavailable", reason: "No semantic provider is active." };
119
+ if (provider.refactor) return provider.refactor(request, control);
120
+ if (request.operation === "rename_symbol" && provider.rename) {
121
+ return provider.rename(request.file, request.position, request.newName, control);
122
+ }
123
+ return {
124
+ kind: "unavailable",
125
+ reason: `The semantic provider cannot plan ${request.operation}.`,
126
+ };
127
+ }
128
+
129
+ /** Freeze a stored plan before it leaves the session. */
130
+ export function immutablePlan(plan: RefactorPlan): Readonly<RefactorPlan> {
131
+ return Object.freeze({
132
+ ...plan,
133
+ ...(plan.target ? { target: Object.freeze({ ...plan.target }) } : {}),
134
+ ...(plan.range ? { range: Object.freeze({ ...plan.range }) } : {}),
135
+ ...(plan.action ? { action: Object.freeze({ ...plan.action }) } : {}),
136
+ edits: Object.freeze({
137
+ ...plan.edits,
138
+ edits: Object.freeze(plan.edits.edits.map((edit) => Object.freeze({ ...edit }))),
139
+ documentPreconditions: plan.edits.documentPreconditions
140
+ ? Object.freeze(
141
+ plan.edits.documentPreconditions.map((precondition) =>
142
+ Object.freeze({ ...precondition }),
143
+ ),
144
+ )
145
+ : undefined,
146
+ }),
147
+ authorizedMutationRoots: Object.freeze([...plan.authorizedMutationRoots]),
148
+ fileFingerprints: Object.freeze(
149
+ plan.fileFingerprints.map((fingerprint) => Object.freeze({ ...fingerprint })),
150
+ ),
151
+ }) as Readonly<RefactorPlan>;
152
+ }
@@ -8,17 +8,27 @@
8
8
 
9
9
  import { createHash } from "node:crypto";
10
10
  import { readFileSync } from "node:fs";
11
- import type { RefactorOperation, WorkspaceEdit } from "@mrclrchtr/supi-code-runtime/api";
11
+ import type {
12
+ RefactorActionIdentity,
13
+ RefactorOperation,
14
+ WorkspaceEdit,
15
+ } from "@mrclrchtr/supi-code-runtime/api";
12
16
  import { toDisplayPath } from "../analysis/search/paths.ts";
17
+ import type { PublicSourceRange } from "./refactor-types.ts";
13
18
 
14
19
  export interface RefactorPlan {
15
20
  id: string;
16
21
  operation: RefactorOperation;
22
+ /** Absolute file the operation was requested for. */
23
+ file: string;
24
+ /** `rename_symbol`: the requested name. */
17
25
  newName?: string;
18
- destination?: string;
19
- targetFile: string;
20
- targetLine: number;
21
- targetCharacter: number;
26
+ /** `rename_symbol`: one-based target position in `file`. */
27
+ target?: { line: number; character: number };
28
+ /** `code_action`: the one-based requested range in `file`. */
29
+ range?: PublicSourceRange;
30
+ /** `code_action` / `source_action`: the selected server action. */
31
+ action?: RefactorActionIdentity;
22
32
  edits: WorkspaceEdit;
23
33
  /** Evidence source used to compose this plan. */
24
34
  evidenceSource?: "semantic" | "structural";
@@ -56,17 +66,10 @@ export function validateSynchronizedContentFingerprints(
56
66
  return null;
57
67
  }
58
68
 
59
- /** Generate a stable plan id from operation details. */
60
- // biome-ignore lint/complexity/useMaxParams: plan id construction needs all positional args
61
- export function generatePlanId(
62
- operation: string,
63
- file: string,
64
- line: number,
65
- character: number,
66
- discriminator: string = "",
67
- ): string {
69
+ /** Generate a plan id from operation details and a time discriminator. */
70
+ export function generatePlanId(operation: string, file: string, discriminator: string): string {
68
71
  const hash = createHash("sha256")
69
- .update(`${operation}:${file}:${line}:${character}:${discriminator}:${Date.now()}`)
72
+ .update(`${operation}:${file}:${discriminator}:${Date.now()}`)
70
73
  .digest("hex")
71
74
  .slice(0, 12);
72
75
  return `plan-${hash}`;
@@ -6,38 +6,50 @@ import type { RefactorTargetInput, SourcePointInput } from "./target-input.ts";
6
6
  /** Public refactor operations exposed by code_refactor_plan. */
7
7
  export const PUBLIC_REFACTOR_OPERATION_NAMES = [
8
8
  "rename_symbol",
9
- "extract_function",
10
- "extract_variable",
11
- "update_imports",
12
- "delete_dead_code",
9
+ "code_action",
10
+ "source_action",
13
11
  ] as const;
14
12
 
15
13
  export type PublicRefactorOperationName = (typeof PUBLIC_REFACTOR_OPERATION_NAMES)[number];
16
14
 
15
+ /** One-based public source range; the end is exclusive. */
17
16
  export interface PublicSourceRange {
18
17
  readonly start: Omit<SourcePointInput, "file">;
19
18
  readonly end: Omit<SourcePointInput, "file">;
20
19
  }
21
20
 
21
+ /**
22
+ * One refactor operation with its own scope. Only `rename_symbol` needs a
23
+ * symbol target; code and source actions name a file directly.
24
+ */
22
25
  export type RefactorOperationInput =
23
- | { readonly rename_symbol: { readonly newName: string } }
24
26
  | {
25
- readonly extract_function: {
27
+ readonly rename_symbol: {
28
+ readonly target: RefactorTargetInput;
26
29
  readonly newName: string;
27
- readonly range: PublicSourceRange;
28
30
  };
29
31
  }
30
32
  | {
31
- readonly extract_variable: {
32
- readonly newName: string;
33
+ readonly code_action: {
34
+ readonly file: string;
33
35
  readonly range: PublicSourceRange;
36
+ /** CodeActionKind prefix under `refactor`. */
37
+ readonly kind: string;
38
+ /** Exact action title that selects one matching action. */
39
+ readonly title?: string;
34
40
  };
35
41
  }
36
- | { readonly update_imports: Record<string, never> }
37
- | { readonly delete_dead_code: Record<string, never> };
42
+ | {
43
+ readonly source_action: {
44
+ readonly file: string;
45
+ /** CodeActionKind prefix under `source`. */
46
+ readonly kind: string;
47
+ /** Exact action title that selects one matching action. */
48
+ readonly title?: string;
49
+ };
50
+ };
38
51
 
39
52
  export interface RefactorPlanWorkflowInput {
40
- readonly target: RefactorTargetInput;
41
53
  readonly operation: RefactorOperationInput;
42
54
  }
43
55
 
@@ -1,57 +1,38 @@
1
1
  /** Session-owned refactor planning and apply workflows. */
2
2
 
3
- import type {
4
- RefactorOperation,
5
- RefactorResult,
6
- SemanticProvider,
7
- SourceRange,
8
- } from "@mrclrchtr/supi-code-runtime/api";
9
3
  import { toLspPosition } from "@mrclrchtr/supi-lsp/api";
10
- import { SEMANTIC_READINESS_TIMEOUT_REASON } from "../analysis/readiness.ts";
11
4
  import { applyWorkspaceEdit } from "../analysis/refactor/apply.ts";
12
5
  import {
13
6
  isLatexSectionTarget,
14
7
  refineLatexSectionRenameResult,
15
8
  } from "../analysis/refactor/latex-section-rename.ts";
16
- import {
17
- establishMutationAuthority,
18
- revalidateMutationAuthority,
19
- } from "../analysis/refactor/mutation-authority.ts";
9
+ import { revalidateMutationAuthority } from "../analysis/refactor/mutation-authority.ts";
20
10
  import { validateEdit } from "../analysis/refactor/safety.ts";
21
11
  import { normalizePath } from "../analysis/search/paths.ts";
22
- import type { CapabilityAdapter } from "./capability-adapter.ts";
23
12
  import {
24
13
  parseRefactorApplyWorkflowInput,
25
14
  parseRefactorPlanWorkflowInput,
26
15
  } from "./input/health-refactor.ts";
27
- import { collectFileFingerprints, dropIdentityEdits } from "./refactor-identity.ts";
28
- import {
29
- computeFileFingerprint,
30
- generatePlanId,
31
- isPlanFresh,
32
- type RefactorPlan,
33
- validateSynchronizedContentFingerprints,
34
- } from "./refactor-plans.ts";
16
+ import { planFileAction } from "./refactor-file-actions.ts";
35
17
  import {
36
- PUBLIC_REFACTOR_OPERATION_NAMES,
37
- type PublicSourceRange,
38
- type RefactorApplyWorkflowInput,
39
- type RefactorApplyWorkflowOutcome,
40
- type RefactorOperationInput,
41
- type RefactorPlanWorkflowInput,
42
- type RefactorPlanWorkflowOutcome,
18
+ ensureFileReadiness,
19
+ finishProviderPlan,
20
+ immutablePlan,
21
+ planWithProvider,
22
+ type RefactorWorkflowDeps,
23
+ } from "./refactor-plan-pipeline.ts";
24
+ import { computeFileFingerprint, isPlanFresh } from "./refactor-plans.ts";
25
+ import type {
26
+ RefactorApplyWorkflowInput,
27
+ RefactorApplyWorkflowOutcome,
28
+ RefactorOperationInput,
29
+ RefactorPlanWorkflowInput,
30
+ RefactorPlanWorkflowOutcome,
43
31
  } from "./refactor-types.ts";
44
32
  import type { TargetStoreEntry } from "./target-store.ts";
45
- import { resolveTargetWorkflow, type TargetWorkflowDeps } from "./target-workflow.ts";
33
+ import { resolveTargetWorkflow } from "./target-workflow.ts";
46
34
  import { reportProgress, throwIfAborted, type WorkflowControl } from "./workflow-control.ts";
47
35
 
48
- export interface RefactorWorkflowDeps extends TargetWorkflowDeps {
49
- readonly capability: CapabilityAdapter;
50
- readonly storePlan: (plan: RefactorPlan) => string;
51
- readonly getPlan: (id: string) => RefactorPlan | undefined;
52
- readonly removePlan: (id: string) => void;
53
- }
54
-
55
36
  /** Plan one precise refactor without mutating files. */
56
37
  export async function runRefactorPlanWorkflow(
57
38
  input: RefactorPlanWorkflowInput,
@@ -60,53 +41,77 @@ export async function runRefactorPlanWorkflow(
60
41
  ): Promise<RefactorPlanWorkflowOutcome> {
61
42
  const validatedInput = parseRefactorPlanWorkflowInput(input);
62
43
  if (validatedInput.kind === "invalid-input") return validatedInput;
63
- const request = validatedInput.value;
64
- const parsed = parseOperation(request.operation);
65
- if (parsed.kind === "invalid-input") return parsed;
66
- const rangeError = parsed.range ? validateRange(parsed.range) : null;
67
- if (rangeError) return { kind: "invalid-input", message: rangeError };
68
-
44
+ const { operation } = validatedInput.value;
69
45
  throwIfAborted(control);
46
+ if ("rename_symbol" in operation) {
47
+ return planRename(operation.rename_symbol, deps, control);
48
+ }
49
+ return planFileAction(operation, deps, control);
50
+ }
51
+
52
+ async function planRename(
53
+ input: Extract<RefactorOperationInput, { rename_symbol: unknown }>["rename_symbol"],
54
+ deps: RefactorWorkflowDeps,
55
+ control?: WorkflowControl,
56
+ ): Promise<RefactorPlanWorkflowOutcome> {
70
57
  reportProgress(control, {
71
58
  intent: "refactor-plan",
72
59
  phase: "target",
73
60
  message: "Resolving refactor target",
74
61
  });
75
62
  const target = await resolveTargetWorkflow(
76
- request.target,
77
- {
78
- fileLevelAllowed: false,
79
- nameAnchorRequired: parsed.operation === "rename_symbol",
80
- },
63
+ input.target,
64
+ { fileLevelAllowed: false, nameAnchorRequired: true },
81
65
  deps,
82
66
  control,
83
67
  );
84
68
  throwIfAborted(control);
85
- if (target.kind === "target-group") {
69
+ if (target.kind === "file-outline") {
86
70
  return {
87
71
  kind: "invalid-input",
88
- message: "Refactor planning requires one member handle from a Target group.",
72
+ message:
73
+ "Rename requires one declaration, not a whole file. Pass one handle from the file outline as target.handle.",
89
74
  };
90
75
  }
91
76
  if (target.kind === "disambiguation" || target.kind === "kind-mismatch") {
92
77
  return {
93
78
  kind: "invalid-input",
94
- message: "Refactor planning requires one precise target handle or anchor.",
79
+ message: "Rename requires one precise target handle or anchor.",
95
80
  };
96
81
  }
97
82
  if (target.kind !== "resolved") return target;
98
83
 
99
- const readiness = await deps.capability.ensureSemanticReadiness(
100
- deps.cwd,
101
- { kind: "file", file: target.entry.file },
84
+ const file = normalizePath(target.entry.file, deps.cwd);
85
+ const readiness = await ensureFileReadiness(file, deps, control);
86
+ if (readiness) return readiness;
87
+ const sectionRename = await planWithLatexSafety({
88
+ newName: input.newName,
89
+ target: target.entry,
90
+ file,
91
+ deps,
102
92
  control,
103
- );
104
- if (readiness.kind === "timeout") {
105
- return { kind: "unavailable", reason: SEMANTIC_READINESS_TIMEOUT_REASON };
93
+ });
94
+ if (
95
+ sectionRename.result.kind === "precise" &&
96
+ sectionRename.sourceFingerprint &&
97
+ computeFileFingerprint(file) !== sectionRename.sourceFingerprint
98
+ ) {
99
+ return {
100
+ kind: "unavailable",
101
+ reason: "The LaTeX source changed before the title rename plan was stored.",
102
+ };
106
103
  }
107
- if (readiness.kind === "unavailable") return readiness;
108
- throwIfAborted(control);
109
- return planResolvedRefactor(parsed, target.entry, deps, control);
104
+ return finishProviderPlan(sectionRename.result, deps, {
105
+ operation: "rename_symbol",
106
+ file,
107
+ discriminator: `${target.entry.displayLine}:${target.entry.displayCharacter}:${input.newName}`,
108
+ fields: {
109
+ newName: input.newName,
110
+ target: { line: target.entry.displayLine, character: target.entry.displayCharacter },
111
+ },
112
+ evidenceSource: sectionRename.evidenceSource,
113
+ sourceFingerprint: sectionRename.sourceFingerprint,
114
+ });
110
115
  }
111
116
 
112
117
  /** Revalidate and apply one stored plan through the per-file mutation queue. */
@@ -156,94 +161,17 @@ export async function runRefactorApplyWorkflow(
156
161
  return { kind: "completed", plan: immutablePlan(plan), result };
157
162
  }
158
163
 
159
- type ParsedRefactorOperation = Extract<ReturnType<typeof parseOperation>, { kind: "ok" }>;
160
164
  type RefinedRefactorResult = Awaited<ReturnType<typeof refineLatexSectionRenameResult>>;
161
165
 
162
- async function planResolvedRefactor(
163
- parsed: ParsedRefactorOperation,
164
- target: Readonly<TargetStoreEntry>,
165
- deps: RefactorWorkflowDeps,
166
- control?: WorkflowControl,
167
- ): Promise<RefactorPlanWorkflowOutcome> {
168
- const file = normalizePath(target.file, deps.cwd);
169
- const sectionRename = await planWithLatexSafety({ parsed, target, file, deps, control });
170
- const result = sectionRename.result;
171
- if (result.kind === "unavailable") return result;
172
- if (result.kind === "ambiguous") {
173
- return { kind: "ambiguous", candidates: result.candidates };
174
- }
175
- if (
176
- sectionRename.sourceFingerprint &&
177
- computeFileFingerprint(file) !== sectionRename.sourceFingerprint
178
- ) {
179
- return {
180
- kind: "unavailable",
181
- reason: "The LaTeX source changed before the title rename plan was stored.",
182
- };
183
- }
184
-
185
- const validation = validateEdit(result.edits);
186
- if (!validation.safe) {
187
- return { kind: "invalid-input", message: `Refactor safety check failed: ${validation.reason}` };
188
- }
189
- const authority = establishMutationAuthority(
190
- result.edits.edits.map((edit) => edit.file),
191
- result.authorizedMutationRoots,
192
- );
193
- if (authority.kind === "unavailable") return authority;
194
- const fileFingerprints = collectFileFingerprints(
195
- result.edits.edits,
196
- sectionRename.sourceFingerprint
197
- ? { file, fingerprint: sectionRename.sourceFingerprint }
198
- : undefined,
199
- );
200
- const snapshotError = validateSynchronizedContentFingerprints(
201
- result.edits.documentPreconditions,
202
- fileFingerprints,
203
- deps.cwd,
204
- );
205
- if (snapshotError) return { kind: "unavailable", reason: snapshotError };
206
- const changed = dropIdentityEdits(result.edits, fileFingerprints);
207
- if (changed.kind === "unavailable") return changed;
208
- if (changed.edits.edits.length === 0) {
209
- return {
210
- kind: "invalid-input",
211
- message: `The ${parsed.operation} refactor produces no changes; every planned edit matches the current text.`,
212
- };
213
- }
214
-
215
- const plan: RefactorPlan = {
216
- id: generatePlanId(
217
- parsed.operation,
218
- file,
219
- target.displayLine,
220
- target.displayCharacter,
221
- parsed.newName,
222
- ),
223
- operation: parsed.operation,
224
- newName: parsed.newName,
225
- targetFile: file,
226
- targetLine: target.displayLine,
227
- targetCharacter: target.displayCharacter,
228
- edits: changed.edits,
229
- evidenceSource: sectionRename.evidenceSource,
230
- authorizedMutationRoots: authority.canonicalRoots,
231
- fileFingerprints: changed.fileFingerprints,
232
- createdAt: Date.now(),
233
- };
234
- deps.storePlan(plan);
235
- return { kind: "completed", plan: immutablePlan(plan) };
236
- }
237
-
238
166
  async function planWithLatexSafety(input: {
239
- readonly parsed: ParsedRefactorOperation;
167
+ readonly newName: string;
240
168
  readonly target: Readonly<TargetStoreEntry>;
241
169
  readonly file: string;
242
170
  readonly deps: RefactorWorkflowDeps;
243
171
  readonly control?: WorkflowControl;
244
172
  }): Promise<RefinedRefactorResult> {
245
- const { parsed, target, file, deps, control } = input;
246
- const isLatexRename = parsed.operation === "rename_symbol" && isLatexSectionTarget(target);
173
+ const { newName, target, file, deps, control } = input;
174
+ const isLatexRename = isLatexSectionTarget(target);
247
175
  if (isLatexRename && computeFileFingerprint(file) !== target.fileFingerprint) {
248
176
  return {
249
177
  result: {
@@ -257,11 +185,10 @@ async function planWithLatexSafety(input: {
257
185
  const result = await planWithProvider(
258
186
  deps.capability.getSemanticProvider(deps.cwd),
259
187
  {
260
- operation: parsed.operation,
188
+ operation: "rename_symbol",
261
189
  file,
262
190
  position: toLspPosition(target.displayLine, target.displayCharacter),
263
- range: parsed.range ? toLspRange(parsed.range) : undefined,
264
- newName: parsed.newName,
191
+ newName,
265
192
  },
266
193
  control,
267
194
  );
@@ -275,11 +202,11 @@ async function planWithLatexSafety(input: {
275
202
  };
276
203
  }
277
204
  return refineLatexSectionRenameResult({
278
- operation: parsed.operation,
205
+ operation: "rename_symbol",
279
206
  result,
280
207
  target,
281
208
  file,
282
- newName: parsed.newName,
209
+ newName,
283
210
  structural: deps.capability.getStructuralProvider(deps.cwd),
284
211
  documentVersionReader: getDocumentVersionReader(deps),
285
212
  control,
@@ -294,104 +221,3 @@ function getDocumentVersionReader(
294
221
  if (typeof state.runtime.getOpenDocumentVersion !== "function") return undefined;
295
222
  return (file) => state.runtime.getOpenDocumentVersion(file);
296
223
  }
297
-
298
- function parseOperation(input: RefactorOperationInput):
299
- | {
300
- kind: "ok";
301
- operation: RefactorOperation;
302
- newName?: string;
303
- range?: PublicSourceRange;
304
- }
305
- | { kind: "invalid-input"; message: string } {
306
- const keys = PUBLIC_REFACTOR_OPERATION_NAMES.filter((key) => key in input);
307
- if (keys.length !== 1) {
308
- return { kind: "invalid-input", message: "Select exactly one refactor operation." };
309
- }
310
- if ("rename_symbol" in input) {
311
- return {
312
- kind: "ok",
313
- operation: "rename_symbol",
314
- newName: input.rename_symbol.newName,
315
- };
316
- }
317
- if ("extract_function" in input) {
318
- return {
319
- kind: "ok",
320
- operation: "extract_function",
321
- newName: input.extract_function.newName,
322
- range: input.extract_function.range,
323
- };
324
- }
325
- if ("extract_variable" in input) {
326
- return {
327
- kind: "ok",
328
- operation: "extract_variable",
329
- newName: input.extract_variable.newName,
330
- range: input.extract_variable.range,
331
- };
332
- }
333
- return {
334
- kind: "ok",
335
- operation: "update_imports" in input ? "update_imports" : "delete_dead_code",
336
- };
337
- }
338
-
339
- function validateRange(range: PublicSourceRange): string | null {
340
- if (
341
- range.end.line < range.start.line ||
342
- (range.end.line === range.start.line && range.end.character <= range.start.character)
343
- ) {
344
- return "range.end must be after range.start.";
345
- }
346
- return null;
347
- }
348
-
349
- function toLspRange(range: PublicSourceRange): SourceRange {
350
- return {
351
- start: toLspPosition(range.start.line, range.start.character),
352
- end: toLspPosition(range.end.line, range.end.character),
353
- };
354
- }
355
-
356
- async function planWithProvider(
357
- provider: SemanticProvider | null,
358
- request: {
359
- operation: RefactorOperation;
360
- file: string;
361
- position: { line: number; character: number };
362
- range?: SourceRange;
363
- newName?: string;
364
- },
365
- control?: WorkflowControl,
366
- ): Promise<RefactorResult> {
367
- if (!provider) return { kind: "unavailable", reason: "No semantic provider is active." };
368
- if (provider.refactor) return provider.refactor(request, control);
369
- if (request.operation === "rename_symbol" && request.newName !== undefined && provider.rename) {
370
- return provider.rename(request.file, request.position, request.newName, control);
371
- }
372
- return {
373
- kind: "unavailable",
374
- reason: `The semantic provider cannot plan ${request.operation}.`,
375
- };
376
- }
377
-
378
- function immutablePlan(plan: RefactorPlan): Readonly<RefactorPlan> {
379
- return Object.freeze({
380
- ...plan,
381
- edits: Object.freeze({
382
- ...plan.edits,
383
- edits: Object.freeze(plan.edits.edits.map((edit) => Object.freeze({ ...edit }))),
384
- documentPreconditions: plan.edits.documentPreconditions
385
- ? Object.freeze(
386
- plan.edits.documentPreconditions.map((precondition) =>
387
- Object.freeze({ ...precondition }),
388
- ),
389
- )
390
- : undefined,
391
- }),
392
- authorizedMutationRoots: Object.freeze([...plan.authorizedMutationRoots]),
393
- fileFingerprints: Object.freeze(
394
- plan.fileFingerprints.map((fingerprint) => Object.freeze({ ...fingerprint })),
395
- ),
396
- }) as Readonly<RefactorPlan>;
397
- }