@mrclrchtr/supi-code-intelligence 11.2.0 → 11.3.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 (112) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +16 -6
  3. package/node_modules/@mrclrchtr/supi-code-runtime/package.json +1 -1
  4. package/node_modules/@mrclrchtr/supi-code-runtime/src/capability/types.ts +3 -1
  5. package/node_modules/@mrclrchtr/supi-code-runtime/src/query-result.ts +9 -0
  6. package/node_modules/@mrclrchtr/supi-core/package.json +1 -1
  7. package/node_modules/@mrclrchtr/supi-core/src/child-web-tools.ts +110 -0
  8. package/node_modules/@mrclrchtr/supi-core/src/session.ts +11 -0
  9. package/node_modules/@mrclrchtr/supi-lsp/README.md +39 -2
  10. package/node_modules/@mrclrchtr/supi-lsp/node_modules/@mrclrchtr/supi-code-runtime/package.json +1 -1
  11. package/node_modules/@mrclrchtr/supi-lsp/node_modules/@mrclrchtr/supi-code-runtime/src/capability/types.ts +3 -1
  12. package/node_modules/@mrclrchtr/supi-lsp/node_modules/@mrclrchtr/supi-code-runtime/src/query-result.ts +9 -0
  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/@mrclrchtr/supi-core/src/child-web-tools.ts +110 -0
  15. package/node_modules/@mrclrchtr/supi-lsp/node_modules/@mrclrchtr/supi-core/src/session.ts +11 -0
  16. package/node_modules/@mrclrchtr/supi-lsp/package.json +3 -3
  17. package/node_modules/@mrclrchtr/supi-lsp/src/client/client-diagnostic-collection.ts +11 -4
  18. package/node_modules/@mrclrchtr/supi-lsp/src/client/client-diagnostics.ts +77 -6
  19. package/node_modules/@mrclrchtr/supi-lsp/src/client/client-input-admission.ts +149 -0
  20. package/node_modules/@mrclrchtr/supi-lsp/src/client/client-typescript-project.ts +40 -0
  21. package/node_modules/@mrclrchtr/supi-lsp/src/client/client.ts +151 -44
  22. package/node_modules/@mrclrchtr/supi-lsp/src/diagnostics/evidence.ts +2 -2
  23. package/node_modules/@mrclrchtr/supi-lsp/src/manager/manager-workspace-symbol.ts +157 -23
  24. package/node_modules/@mrclrchtr/supi-lsp/src/manager/manager.ts +254 -56
  25. package/node_modules/@mrclrchtr/supi-lsp/src/session/runtime-registry.ts +19 -2
  26. package/node_modules/@mrclrchtr/supi-lsp/src/session/runtime-rename.ts +1 -0
  27. package/node_modules/@mrclrchtr/supi-lsp/src/session/workspace-lsp-runtime.ts +5 -1
  28. package/node_modules/@mrclrchtr/supi-tree-sitter/README.md +2 -2
  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/capability/types.ts +3 -1
  31. package/node_modules/@mrclrchtr/supi-tree-sitter/node_modules/@mrclrchtr/supi-code-runtime/src/query-result.ts +9 -0
  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/node_modules/@mrclrchtr/supi-core/src/child-web-tools.ts +110 -0
  34. package/node_modules/@mrclrchtr/supi-tree-sitter/node_modules/@mrclrchtr/supi-core/src/session.ts +11 -0
  35. package/node_modules/@mrclrchtr/supi-tree-sitter/package.json +3 -3
  36. package/node_modules/@mrclrchtr/supi-tree-sitter/resources/grammars/tsx/tree-sitter-tsx.wasm +0 -0
  37. package/node_modules/@mrclrchtr/supi-tree-sitter/resources/grammars/tsx/tree-sitter-tsx.wasm.json +5 -1
  38. package/node_modules/@mrclrchtr/supi-tree-sitter/resources/grammars/typescript/tree-sitter-typescript.wasm +0 -0
  39. package/node_modules/@mrclrchtr/supi-tree-sitter/resources/grammars/typescript/tree-sitter-typescript.wasm.json +5 -1
  40. package/node_modules/@mrclrchtr/supi-tree-sitter/src/tool/call-sites.ts +40 -25
  41. package/node_modules/@mrclrchtr/supi-tree-sitter/src/tool/callees.ts +2 -0
  42. package/node_modules/@mrclrchtr/supi-tree-sitter/src/worker/call-context.ts +44 -0
  43. package/package.json +6 -5
  44. package/src/analysis/health/server-status.ts +6 -2
  45. package/src/analysis/search/exclusions.ts +47 -0
  46. package/src/analysis/search/paths.ts +32 -9
  47. package/src/analysis/target/anchored-structural.ts +3 -8
  48. package/src/analysis/target/anchored.ts +4 -20
  49. package/src/analysis/target/identity.ts +1 -1
  50. package/src/analysis/target/latex-label-container.ts +6 -6
  51. package/src/analysis/target/latex-section-anchor.ts +6 -6
  52. package/src/analysis/target/resolution.ts +18 -0
  53. package/src/analysis/target/symbol.ts +39 -11
  54. package/src/analysis/target/types.ts +6 -1
  55. package/src/extension.ts +17 -11
  56. package/src/session/graph/collect.ts +1 -10
  57. package/src/session/graph-types.ts +2 -0
  58. package/src/session/graph-workflow.ts +1 -0
  59. package/src/session/inspect/collect.ts +8 -2
  60. package/src/session/inspect/file-point.ts +2 -3
  61. package/src/session/inspect-workflow.ts +1 -1
  62. package/src/session/orientation/collect.ts +54 -16
  63. package/src/session/orientation/context-sections.ts +2 -3
  64. package/src/session/orientation/facts.ts +9 -1
  65. package/src/session/orientation-types.ts +3 -0
  66. package/src/session/orientation-workflow.ts +18 -5
  67. package/src/session/refactor-identity.ts +76 -0
  68. package/src/session/refactor-workflow.ts +11 -14
  69. package/src/session/target-store.ts +3 -18
  70. package/src/session/target-workflow.ts +33 -16
  71. package/src/substrate/lsp/recovery.ts +5 -5
  72. package/src/tool/code_find/render.ts +8 -4
  73. package/src/tool/code_find/result.ts +78 -6
  74. package/src/tool/code_find/spec.ts +4 -3
  75. package/src/tool/code_find/structured.ts +25 -9
  76. package/src/tool/code_graph/details.ts +1 -0
  77. package/src/tool/code_graph/display.ts +1 -1
  78. package/src/tool/code_graph/guidance.ts +1 -1
  79. package/src/tool/code_graph/markdown.ts +11 -6
  80. package/src/tool/code_graph/read-next.ts +38 -9
  81. package/src/tool/code_graph/reference-selection.ts +30 -0
  82. package/src/tool/code_graph/result.ts +25 -118
  83. package/src/tool/code_graph/section.ts +133 -0
  84. package/src/tool/code_graph/spec.ts +3 -3
  85. package/src/tool/code_graph/structured.ts +17 -6
  86. package/src/tool/code_health/display-paths.ts +92 -0
  87. package/src/tool/code_health/file-scope-markdown.ts +3 -2
  88. package/src/tool/code_health/result.ts +4 -2
  89. package/src/tool/code_health/spec.ts +3 -3
  90. package/src/tool/code_health/structured-schema.ts +44 -44
  91. package/src/tool/code_inspect/spec.ts +5 -1
  92. package/src/tool/code_inspect/structured.ts +1 -2
  93. package/src/tool/code_orientation/execute.ts +1 -1
  94. package/src/tool/code_orientation/result.ts +22 -5
  95. package/src/tool/code_orientation/structured-schema.ts +46 -36
  96. package/src/tool/code_orientation/structured-workspace.ts +2 -1
  97. package/src/tool/code_orientation/structured.ts +6 -12
  98. package/src/tool/code_orientation/workspace-format.ts +2 -5
  99. package/src/tool/code_orientation/workspace-sections.ts +3 -2
  100. package/src/tool/code_refactor_apply/result.ts +1 -1
  101. package/src/tool/code_refactor_plan/result.ts +2 -1
  102. package/src/tool/code_refactor_plan/structured.ts +2 -3
  103. package/src/tool/code_resolve/markdown.ts +6 -30
  104. package/src/tool/code_resolve/result.ts +24 -11
  105. package/src/tool/code_resolve/structured.ts +7 -9
  106. package/src/tool/result/refactor.ts +8 -5
  107. package/src/tool/result/structured.ts +8 -5
  108. package/src/tool/result/types.ts +18 -14
  109. package/src/tool/schemas.ts +5 -5
  110. package/src/ui/status-command.ts +37 -1
  111. package/src/ui/status-overlay.ts +70 -51
  112. package/src/ui/status-presentation.ts +108 -0
@@ -47,6 +47,7 @@ import {
47
47
  } from "./client-document-state.ts";
48
48
  import { clearTrackedDocumentState, synchronizeTrackedDocument } from "./client-document-sync.ts";
49
49
  import { getDiagnosticFileState } from "./client-file-state.ts";
50
+ import { SemanticInputAdmission } from "./client-input-admission.ts";
50
51
  import { SemanticInputRequestRetryGuard } from "./client-request-enrollment.ts";
51
52
  import {
52
53
  SemanticInputBarrier,
@@ -103,6 +104,7 @@ export class ClientDiagnostics {
103
104
  /** URIs closed by a lifecycle operation: versioned pushes stay fail-closed. */
104
105
  readonly #closedVersionedBarrier = new Set<string>();
105
106
  readonly #inputBarrier: SemanticInputBarrier;
107
+ #inputAdmission = new SemanticInputAdmission();
106
108
  #evidenceRevision = 0;
107
109
  #nextSynchronizationId = 0;
108
110
  /** One active server refresh plus one coalesced newer demand generation. */
@@ -125,6 +127,60 @@ export class ClientDiagnostics {
125
127
  });
126
128
  }
127
129
 
130
+ /** Keep first enrollment outside a semantic query or refactor-planning attempt. */
131
+ withSemanticRequest<T>(
132
+ run: () => Promise<T>,
133
+ control?: CodeRequestControl,
134
+ uri?: string,
135
+ ): Promise<T> {
136
+ return this.#inputAdmission.request(run, control, uri);
137
+ }
138
+
139
+ /** Read content only after admission; tracked-document changes never wait. */
140
+ async openDocument(
141
+ filePath: string,
142
+ readContent: () => string,
143
+ control?: CodeRequestControl,
144
+ protectInputs = false,
145
+ ): Promise<void> {
146
+ throwIfCodeRequestInterrupted(control);
147
+ const open = () => {
148
+ throwIfCodeRequestInterrupted(control);
149
+ if (!this.host.isOperational()) throw new Error("LSP client is not running.");
150
+ this.didOpen(filePath, readContent());
151
+ };
152
+ if (this.#openDocs.has(fileToUri(filePath))) {
153
+ open();
154
+ return;
155
+ }
156
+ await this.#inputAdmission.enroll(fileToUri(filePath), open, control, protectInputs);
157
+ }
158
+
159
+ /** Restore only still-retained documents; a close or replacement wins over recovery. */
160
+ async restoreDocument(
161
+ filePath: string,
162
+ readContent: () => string,
163
+ isCurrent: () => boolean,
164
+ ): Promise<void> {
165
+ const uri = fileToUri(filePath);
166
+ const admission = this.#inputAdmission;
167
+ const canRestore = () =>
168
+ isCurrent() &&
169
+ this.host.isOperational() &&
170
+ admission === this.#inputAdmission &&
171
+ !this.#closedVersionedBarrier.has(uri) &&
172
+ !this.#openDocs.has(uri);
173
+ if (!canRestore()) return;
174
+ try {
175
+ await this.openDocument(filePath, () => {
176
+ if (!canRestore()) throw new Error("Document restoration was superseded.");
177
+ return readContent();
178
+ });
179
+ } catch {
180
+ if (canRestore()) this.markFailedFile(filePath);
181
+ }
182
+ }
183
+
128
184
  /** Synchronize all open document inputs, rejoining once after a new enrollment. */
129
185
  async synchronizeSemanticInputs(
130
186
  control?: CodeRequestControl,
@@ -222,17 +278,22 @@ export class ClientDiagnostics {
222
278
  this.#inputBarrier.forgetDocumentContent(uri);
223
279
  }
224
280
 
225
- #ensureExplicitDocumentContent(
281
+ async #ensureExplicitDocumentContent(
226
282
  filePath: string,
227
283
  content: string,
228
284
  contentIsAuthoritative: boolean,
229
- ): void {
285
+ control?: CodeRequestControl,
286
+ ): Promise<void> {
230
287
  const uri = fileToUri(filePath);
231
288
  const document = this.#openDocs.get(uri);
232
289
  if (!document) {
233
- // An untracked file needs an initial protocol document before its barrier
234
- // read can verify the manager's content.
235
- this.didOpen(filePath, content);
290
+ // A manager read can predate admission. Re-read disk after the wait;
291
+ // explicit authoritative content retains its existing override semantics.
292
+ await this.openDocument(
293
+ filePath,
294
+ () => (contentIsAuthoritative ? content : readFileSync(filePath, "utf-8")),
295
+ control,
296
+ );
236
297
  return;
237
298
  }
238
299
  // Manager reads are not authoritative: an already tracked document can
@@ -260,6 +321,8 @@ export class ClientDiagnostics {
260
321
  }
261
322
 
262
323
  clear(options: { preserveFailedDocuments?: boolean } = {}): void {
324
+ this.#inputAdmission.dispose();
325
+ this.#inputAdmission = new SemanticInputAdmission();
263
326
  if (options.preserveFailedDocuments) {
264
327
  for (const uri of [...this.#openDocs.keys(), ...this.#diagnosticStore.keys()]) {
265
328
  this.#failedUris.add(uri);
@@ -336,6 +399,7 @@ export class ClientDiagnostics {
336
399
 
337
400
  /** Send a save after a disk change that the input barrier observed. */
338
401
  #noteExternalDiskChange(filePath: string, content: string): void {
402
+ this.#inputAdmission.invalidateRequests();
339
403
  if (!this.host.isOperational()) return;
340
404
  const documentSync = this.host.documentSync();
341
405
  if (!documentSync.save) return;
@@ -368,6 +432,7 @@ export class ClientDiagnostics {
368
432
 
369
433
  didClose(filePath: string): void {
370
434
  const uri = fileToUri(filePath);
435
+ this.#inputAdmission.close(uri);
371
436
  const wasOpen = this.#openDocs.has(uri);
372
437
  const hadState =
373
438
  wasOpen ||
@@ -627,7 +692,12 @@ export class ClientDiagnostics {
627
692
  throwIfCodeRequestInterrupted(control);
628
693
  const uri = fileToUri(filePath);
629
694
  const contentIsAuthoritative = options.contentIsAuthoritative !== false;
630
- this.#ensureExplicitDocumentContent(filePath, content, contentIsAuthoritative);
695
+ try {
696
+ await this.#ensureExplicitDocumentContent(filePath, content, contentIsAuthoritative, control);
697
+ } catch (error) {
698
+ throwIfCodeRequestInterrupted(control);
699
+ return unavailableAfterEnrollmentRetry(error);
700
+ }
631
701
  const contentOverrides = this.#getDiagnosticContentOverrides(
632
702
  uri,
633
703
  content,
@@ -1044,6 +1114,7 @@ export class ClientDiagnostics {
1044
1114
  changeKind: SemanticInputChangeKind = "content",
1045
1115
  ): void {
1046
1116
  this.#inputBarrier.noteInputChange(changeKind);
1117
+ if (changeKind !== "enrollment") this.#inputAdmission.invalidateRequests();
1047
1118
  if (invalidateEvidence) this.#advanceEvidenceRevision(false);
1048
1119
  if (cancelRequests) this.#cancelAllDiagnosticRequests();
1049
1120
  }
@@ -0,0 +1,149 @@
1
+ import {
2
+ type CodeRequestControl,
3
+ CodeRequestDeadlineError,
4
+ throwIfCodeRequestInterrupted,
5
+ } from "@mrclrchtr/supi-code-runtime/api";
6
+
7
+ const MAX_PENDING_INPUT_OPERATIONS = 32;
8
+
9
+ type InputOperationKind = "request" | "enrollment" | "request-enrollment";
10
+
11
+ interface PendingInputOperation {
12
+ readonly uri: string | undefined;
13
+ readonly kind: InputOperationKind;
14
+ start(): void;
15
+ cancel(reason: unknown): void;
16
+ }
17
+
18
+ /**
19
+ * Admit first opens between semantic query and refactor-planning attempts on one client.
20
+ * Consecutive readers run concurrently; FIFO admission prevents either new
21
+ * readers or enrollments from overtaking a waiting operation. This is not
22
+ * diagnostic transport ownership: an interrupted semantic attempt can release
23
+ * its admission even when the server has not yet acknowledged cancellation.
24
+ */
25
+ export class SemanticInputAdmission {
26
+ readonly #pending: PendingInputOperation[] = [];
27
+ #readers = 0;
28
+ #enrolling = false;
29
+ #disposed = false;
30
+
31
+ /** Cover one attempt's synchronization, RPCs and acceptance, never its retry. */
32
+ request<T>(run: () => Promise<T>, control?: CodeRequestControl, uri?: string): Promise<T> {
33
+ return this.#run("request", uri, run, control);
34
+ }
35
+
36
+ /**
37
+ * Commit a first open after earlier attempts leave. Demand with original
38
+ * semantic/refactor parameters opts into input invalidation while waiting.
39
+ */
40
+ enroll(
41
+ uri: string,
42
+ run: () => void,
43
+ control?: CodeRequestControl,
44
+ protectInputs = false,
45
+ ): Promise<void> {
46
+ return this.#run(protectInputs ? "request-enrollment" : "enrollment", uri, run, control);
47
+ }
48
+
49
+ /** A close cancels queued opens and queries for that document, before dispatch. */
50
+ close(uri: string): void {
51
+ const cancelled = this.#pending.filter((pending) => pending.uri === uri);
52
+ for (const pending of cancelled) this.#pending.splice(this.#pending.indexOf(pending), 1);
53
+ for (const pending of cancelled)
54
+ pending.cancel(new Error("Document closed before input admission."));
55
+ }
56
+
57
+ /** Discard queued request parameters after a known non-enrollment input change. */
58
+ invalidateRequests(): void {
59
+ const cancelled = this.#pending.filter((pending) => pending.kind !== "enrollment");
60
+ for (const pending of cancelled) this.#pending.splice(this.#pending.indexOf(pending), 1);
61
+ for (const pending of cancelled)
62
+ pending.cancel(new Error("Semantic inputs changed before request admission."));
63
+ }
64
+
65
+ /** Reject queued work without confusing caller completion with transport settlement. */
66
+ dispose(): void {
67
+ this.#disposed = true;
68
+ for (const pending of [...this.#pending]) {
69
+ pending.cancel(new Error("LSP client stopped before input admission."));
70
+ }
71
+ }
72
+
73
+ #run<T>(
74
+ kind: InputOperationKind,
75
+ uri: string | undefined,
76
+ run: () => T | Promise<T>,
77
+ control: CodeRequestControl | undefined,
78
+ ): Promise<T> {
79
+ throwIfCodeRequestInterrupted(control);
80
+ if (this.#disposed) return Promise.reject(new Error("LSP input admission is disposed."));
81
+ if (this.#pending.length >= MAX_PENDING_INPUT_OPERATIONS) {
82
+ return Promise.reject(new Error("LSP input admission queue is full."));
83
+ }
84
+ return new Promise<T>((resolve, reject) => {
85
+ let timer: ReturnType<typeof setTimeout> | undefined;
86
+ let waiting = true;
87
+ const cleanup = () => {
88
+ if (timer !== undefined) clearTimeout(timer);
89
+ control?.signal?.removeEventListener("abort", abort);
90
+ };
91
+ const operation: PendingInputOperation = {
92
+ uri,
93
+ kind,
94
+ cancel: (reason) => {
95
+ if (!waiting) return;
96
+ waiting = false;
97
+ cleanup();
98
+ const index = this.#pending.indexOf(operation);
99
+ if (index !== -1) this.#pending.splice(index, 1);
100
+ reject(reason);
101
+ this.#drain();
102
+ },
103
+ start: () => {
104
+ waiting = false;
105
+ cleanup();
106
+ if (kind !== "request") this.#enrolling = true;
107
+ else this.#readers++;
108
+ const finish = () => {
109
+ if (kind !== "request") this.#enrolling = false;
110
+ else this.#readers--;
111
+ this.#drain();
112
+ };
113
+ try {
114
+ throwIfCodeRequestInterrupted(control);
115
+ Promise.resolve(run()).then(resolve, reject).finally(finish);
116
+ } catch (error) {
117
+ reject(error);
118
+ finish();
119
+ }
120
+ },
121
+ };
122
+ const abort = () => {
123
+ try {
124
+ throwIfCodeRequestInterrupted(control);
125
+ } catch (error) {
126
+ operation.cancel(error);
127
+ }
128
+ };
129
+ this.#pending.push(operation);
130
+ control?.signal?.addEventListener("abort", abort, { once: true });
131
+ if (control?.deadline !== undefined) {
132
+ timer = setTimeout(
133
+ () => operation.cancel(new CodeRequestDeadlineError()),
134
+ Math.max(0, control.deadline - Date.now()),
135
+ );
136
+ }
137
+ this.#drain();
138
+ });
139
+ }
140
+
141
+ #drain(): void {
142
+ while (!this.#disposed && !this.#enrolling && this.#pending.length > 0) {
143
+ const next = this.#pending[0];
144
+ if (next.kind !== "request" && this.#readers > 0) return;
145
+ this.#pending.shift();
146
+ next.start();
147
+ }
148
+ }
149
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Whether tsserver placed an open file in a configured project.
3
+ *
4
+ * - `configured`: a `tsconfig.json` / `jsconfig.json` program owns the file.
5
+ * - `inferred`: tsserver created an inferred project for the file alone, so
6
+ * project-wide requests such as `workspace/symbol` do not cover the
7
+ * configured program.
8
+ * - `unknown`: the route is not TypeScript or tsserver could not answer.
9
+ */
10
+ export type ProjectMembership = "configured" | "inferred" | "unknown";
11
+
12
+ /** Build `workspace/executeCommand` params for tsserver `projectInfo`. */
13
+ export function typeScriptProjectInfoParams(uri: string): unknown {
14
+ return {
15
+ command: "typescript.tsserverRequest",
16
+ arguments: [
17
+ "projectInfo",
18
+ { file: uri, needFileNameList: false },
19
+ // Semantic execution target; the project must be loaded to answer.
20
+ { executionTarget: 0, expectsResult: true, isAsync: false },
21
+ ],
22
+ };
23
+ }
24
+
25
+ /**
26
+ * Read project membership from a tsserver `projectInfo` response.
27
+ * tsserver names projects without a config file `/dev/null/<kind>Project<N>*`.
28
+ */
29
+ export function readTypeScriptProjectMembership(response: unknown): ProjectMembership {
30
+ if (!isRecord(response) || response.type !== "response" || response.success !== true) {
31
+ return "unknown";
32
+ }
33
+ const body = response.body;
34
+ if (!isRecord(body) || typeof body.configFileName !== "string") return "unknown";
35
+ return body.configFileName.startsWith("/dev/null/") ? "inferred" : "configured";
36
+ }
37
+
38
+ function isRecord(value: unknown): value is Record<string, unknown> {
39
+ return typeof value === "object" && value !== null;
40
+ }
@@ -80,6 +80,11 @@ import type {
80
80
  SemanticInputSnapshot,
81
81
  } from "./client-semantic-input-barrier.ts";
82
82
  import { SemanticInputSynchronizationError } from "./client-semantic-input-errors.ts";
83
+ import {
84
+ type ProjectMembership,
85
+ readTypeScriptProjectMembership,
86
+ typeScriptProjectInfoParams,
87
+ } from "./client-typescript-project.ts";
83
88
  import { JsonRpcClient, JsonRpcRequestError } from "./transport.ts";
84
89
 
85
90
  const SHUTDOWN_TIMEOUT_MS = 5_000;
@@ -89,6 +94,12 @@ const CONTENT_MODIFIED_RETRY_DELAY_MS = 100;
89
94
 
90
95
  /** Bounded stderr tail kept for startup-failure error messages. */
91
96
  const STDERR_TAIL_MAX_CHARS = 4_000;
97
+ /**
98
+ * Bound for draining a failed startup's stdio. An initialize write can fail
99
+ * (`EPIPE`) before the exiting server's stderr is read; waiting for `close`
100
+ * lets the failure report the server's own reason instead of the transport error.
101
+ */
102
+ const STARTUP_FAILURE_DRAIN_MS = 500;
92
103
 
93
104
  interface SemanticRequestAttemptState {
94
105
  inputRevision: number | undefined;
@@ -492,6 +503,20 @@ function killFailedStartupProcess(child: ChildProcess): void {
492
503
  child.kill();
493
504
  }
494
505
 
506
+ /** Resolve once `closed()` holds or the child emits `close`, bounded by `ms`. */
507
+ function waitForStdioClose(child: ChildProcess, closed: () => boolean, ms: number): Promise<void> {
508
+ if (closed()) return Promise.resolve();
509
+ return new Promise((resolve) => {
510
+ const done = () => {
511
+ clearTimeout(timer);
512
+ child.off("close", done);
513
+ resolve();
514
+ };
515
+ const timer = setTimeout(done, ms);
516
+ child.once("close", done);
517
+ });
518
+ }
519
+
495
520
  // ── Types ─────────────────────────────────────────────────────────────
496
521
  export type ClientStatus = "initializing" | "running" | "error" | "shutdown";
497
522
 
@@ -726,19 +751,24 @@ export class LspClient {
726
751
  });
727
752
  this.rpc.onRequest((method, params) => this.handleServerRequest(method, params));
728
753
 
729
- // Handle crashes
754
+ // Handle crashes. A failing initialize reports its own detailed failure.
755
+ let reportingStartupFailure = false;
730
756
  this.process.on("exit", (_code) => {
731
- this.handleProcessFailure(new Error("Client crashed"));
757
+ if (!reportingStartupFailure) this.handleProcessFailure(new Error("Client crashed"));
732
758
  });
733
759
 
734
760
  this.process.on("error", (_err) => {
735
- this.handleProcessFailure(new Error("Client process error"));
761
+ if (!reportingStartupFailure) this.handleProcessFailure(new Error("Client process error"));
736
762
  });
737
763
 
738
764
  // Capture a bounded stderr tail (discarded otherwise) so startup
739
765
  // failures can surface the server's own exit reason — expired builds,
740
766
  // missing runtimes, or invalid flags. Stderr never reaches the agent.
741
767
  let stderrTail = "";
768
+ let stdioClosed = false;
769
+ this.process.once("close", () => {
770
+ stdioClosed = true;
771
+ });
742
772
  this.process.stderr?.on("data", (chunk: Buffer | string) => {
743
773
  stderrTail = `${stderrTail}${chunk}`.slice(-STDERR_TAIL_MAX_CHARS);
744
774
  });
@@ -777,12 +807,16 @@ export class LspClient {
777
807
 
778
808
  this.armNoProgressTimer();
779
809
  } catch (err) {
810
+ const child = this.process;
811
+ reportingStartupFailure = true;
812
+ killFailedStartupProcess(child);
813
+ // Let already-written stderr drain before reporting the failure.
814
+ await waitForStdioClose(child, () => stdioClosed, STARTUP_FAILURE_DRAIN_MS);
780
815
  const stderrDetail = stderrTail.trim() ? `\n${this.name} stderr:\n${stderrTail.trim()}` : "";
781
816
  const failure = new Error(`${this.name}: initialize failed: ${err}${stderrDetail}`, {
782
817
  cause: err,
783
818
  });
784
819
  this.handleProcessFailure(failure);
785
- killFailedStartupProcess(this.process);
786
820
  throw failure;
787
821
  }
788
822
  }
@@ -879,6 +913,33 @@ export class LspClient {
879
913
  }
880
914
 
881
915
  // ── Document Synchronization and Diagnostics ────────────────────────
916
+ /**
917
+ * Admit a first open between semantic attempts, reading content after the wait.
918
+ * Semantic/refactor callers protect their original inputs; ordinary tracking
919
+ * can adopt fresh content after a known change instead.
920
+ */
921
+ async openDocument(
922
+ filePath: string,
923
+ readContent: () => string,
924
+ control?: CodeRequestControl,
925
+ protectInputs = false,
926
+ ): Promise<void> {
927
+ const trackedCount = this.openFiles.length;
928
+ await this.diagnostics.openDocument(filePath, readContent, control, protectInputs);
929
+ this.publishTrackedFileChange(trackedCount);
930
+ }
931
+
932
+ /** Restore retained state without resurrecting a closed or replaced document. */
933
+ async restoreDocument(
934
+ filePath: string,
935
+ readContent: () => string,
936
+ isCurrent: () => boolean,
937
+ ): Promise<void> {
938
+ const trackedCount = this.openFiles.length;
939
+ await this.diagnostics.restoreDocument(filePath, readContent, isCurrent);
940
+ this.publishTrackedFileChange(trackedCount);
941
+ }
942
+
882
943
  /** Open a document, or update it when it is already open. */
883
944
  didOpen(filePath: string, content: string): void {
884
945
  const trackedCount = this.openFiles.length;
@@ -1161,6 +1222,23 @@ export class LspClient {
1161
1222
  );
1162
1223
  }
1163
1224
 
1225
+ /**
1226
+ * Report whether the server placed an open file in a configured project.
1227
+ * Only the TypeScript route can answer; other routes return `unknown`.
1228
+ */
1229
+ async projectMembership(
1230
+ filePath: string,
1231
+ control?: CodeRequestControl,
1232
+ ): Promise<ProjectMembership> {
1233
+ if (!this.hasTypeScriptRequestCommand()) return "unknown";
1234
+ const result = await this.query<unknown>(
1235
+ "workspace/executeCommand",
1236
+ typeScriptProjectInfoParams(fileToUri(filePath)),
1237
+ control,
1238
+ );
1239
+ return result.kind === "completed" ? readTypeScriptProjectMembership(result.data) : "unknown";
1240
+ }
1241
+
1164
1242
  async workspaceSymbol(
1165
1243
  query: string,
1166
1244
  control?: CodeRequestControl,
@@ -1258,6 +1336,7 @@ export class LspClient {
1258
1336
  | undefined;
1259
1337
  },
1260
1338
  {
1339
+ documentUri: params.textDocument.uri,
1261
1340
  inputRevision: options.inputRevision,
1262
1341
  onVerifiedSnapshot: (snapshot) => {
1263
1342
  inputRevision = snapshot.revision;
@@ -1309,17 +1388,22 @@ export class LspClient {
1309
1388
  triggerKind: context.triggerKind ?? CodeActionTriggerKind.Invoked,
1310
1389
  ...(context.only ? { only: [...context.only] } : {}),
1311
1390
  };
1312
- return this.runRefactorTransaction("textDocument/codeAction", control, async (transaction) => {
1313
- const raw = await transaction.rpc.sendRequest(
1314
- "textDocument/codeAction",
1315
- { textDocument: { uri: fileToUri(filePath) }, range, context: requestContext },
1316
- control,
1317
- );
1318
- if (raw === null || raw === undefined) return null;
1319
- if (!Array.isArray(raw)) throw new Error("LSP server returned malformed code actions.");
1391
+ return this.runRefactorTransaction(
1392
+ "textDocument/codeAction",
1393
+ control,
1394
+ async (transaction) => {
1395
+ const raw = await transaction.rpc.sendRequest(
1396
+ "textDocument/codeAction",
1397
+ { textDocument: { uri: fileToUri(filePath) }, range, context: requestContext },
1398
+ control,
1399
+ );
1400
+ if (raw === null || raw === undefined) return null;
1401
+ if (!Array.isArray(raw)) throw new Error("LSP server returned malformed code actions.");
1320
1402
 
1321
- return this.resolveCodeActions(raw, transaction, control, requestContext.only);
1322
- });
1403
+ return this.resolveCodeActions(raw, transaction, control, requestContext.only);
1404
+ },
1405
+ { documentUri: fileToUri(filePath) },
1406
+ );
1323
1407
  }
1324
1408
 
1325
1409
  async implementation(
@@ -1384,9 +1468,10 @@ export class LspClient {
1384
1468
  control: CodeRequestControl | undefined,
1385
1469
  operation: (transaction: RefactorTransaction) => Promise<T | null | undefined>,
1386
1470
  options: {
1471
+ readonly documentUri: string;
1387
1472
  readonly onVerifiedSnapshot?: (snapshot: SemanticInputSnapshot) => void;
1388
1473
  readonly inputRevision?: number;
1389
- } = {},
1474
+ },
1390
1475
  ): Promise<CodeQueryResult<T | null>> {
1391
1476
  throwIfCodeRequestInterrupted(control);
1392
1477
  if (!this.rpc || this._status !== "running") {
@@ -1405,6 +1490,7 @@ export class LspClient {
1405
1490
  retryGuard.assertCurrent();
1406
1491
  const data = await this.runRefactorTransactionAttempt({
1407
1492
  method,
1493
+ documentUri: options.documentUri,
1408
1494
  control,
1409
1495
  operation,
1410
1496
  retryGuard,
@@ -1446,9 +1532,10 @@ export class LspClient {
1446
1532
  }
1447
1533
  }
1448
1534
 
1449
- /** Run the complete prepare/request/resolve transaction for one input snapshot. */
1535
+ /** Admit one prepare/request/resolve attempt, not retries or rename's own enrollment. */
1450
1536
  private async runRefactorTransactionAttempt<T>(options: {
1451
1537
  method: string;
1538
+ documentUri: string;
1452
1539
  control?: CodeRequestControl;
1453
1540
  operation: (transaction: RefactorTransaction) => Promise<T | null | undefined>;
1454
1541
  retryGuard: SemanticInputRequestRetryGuard;
@@ -1459,27 +1546,36 @@ export class LspClient {
1459
1546
  throwIfCodeRequestInterrupted(control);
1460
1547
  retryGuard.assertCurrent();
1461
1548
  await this.getReady(control);
1462
- const inputSnapshot = await this.diagnostics.synchronizeSemanticInputs(control);
1463
- attempt.inputRevision = inputSnapshot.revision;
1464
- throwIfCodeRequestInterrupted(control);
1465
- retryGuard.assertCurrent();
1466
- const rpc = this.rpc;
1467
- if (!rpc || this._status !== "running") {
1468
- throw new Error(`LSP request ${method} is unavailable because the client is not running.`);
1469
- }
1470
- const data = await operation({
1471
- rpc,
1472
- assertCurrent: async () => {
1549
+ return this.diagnostics.withSemanticRequest(
1550
+ async () => {
1473
1551
  retryGuard.assertCurrent();
1474
- return this.diagnostics.assertSemanticInputsCurrent(inputSnapshot, control);
1552
+ const inputSnapshot = await this.diagnostics.synchronizeSemanticInputs(control);
1553
+ attempt.inputRevision = inputSnapshot.revision;
1554
+ throwIfCodeRequestInterrupted(control);
1555
+ retryGuard.assertCurrent();
1556
+ const rpc = this.rpc;
1557
+ if (!rpc || this._status !== "running") {
1558
+ throw new Error(
1559
+ `LSP request ${method} is unavailable because the client is not running.`,
1560
+ );
1561
+ }
1562
+ const data = await operation({
1563
+ rpc,
1564
+ assertCurrent: async () => {
1565
+ retryGuard.assertCurrent();
1566
+ return this.diagnostics.assertSemanticInputsCurrent(inputSnapshot, control);
1567
+ },
1568
+ });
1569
+ const verifiedSnapshot = await this.diagnostics.assertSemanticInputsCurrent(
1570
+ inputSnapshot,
1571
+ control,
1572
+ );
1573
+ onVerifiedSnapshot?.(verifiedSnapshot);
1574
+ return data ?? null;
1475
1575
  },
1476
- });
1477
- const verifiedSnapshot = await this.diagnostics.assertSemanticInputsCurrent(
1478
- inputSnapshot,
1479
1576
  control,
1577
+ options.documentUri,
1480
1578
  );
1481
- onVerifiedSnapshot?.(verifiedSnapshot);
1482
- return data ?? null;
1483
1579
  }
1484
1580
 
1485
1581
  private async query<T>(
@@ -1651,17 +1747,28 @@ export class LspClient {
1651
1747
  throwIfCodeRequestInterrupted(control);
1652
1748
  retryGuard.assertCurrent();
1653
1749
  await this.getReady(control);
1654
- const inputSnapshot = await this.diagnostics.synchronizeSemanticInputs(control);
1655
- attempt.inputRevision = inputSnapshot.revision;
1656
- throwIfCodeRequestInterrupted(control);
1657
- retryGuard.assertCurrent();
1658
- const rpc = this.rpc;
1659
- if (!rpc || this._status !== "running") {
1660
- throw new Error(`LSP request ${method} is unavailable because the client is not running.`);
1661
- }
1662
- const data = (await rpc.sendRequest(method, params, control)) as T | null | undefined;
1663
- await this.diagnostics.assertSemanticInputsCurrent(inputSnapshot, control);
1664
- return data ?? null;
1750
+ // Local query methods construct the standard TextDocumentIdentifier envelope.
1751
+ const documentUri = (params as { textDocument?: { uri: string } } | null)?.textDocument?.uri;
1752
+ return this.diagnostics.withSemanticRequest(
1753
+ async () => {
1754
+ retryGuard.assertCurrent();
1755
+ const inputSnapshot = await this.diagnostics.synchronizeSemanticInputs(control);
1756
+ attempt.inputRevision = inputSnapshot.revision;
1757
+ throwIfCodeRequestInterrupted(control);
1758
+ retryGuard.assertCurrent();
1759
+ const rpc = this.rpc;
1760
+ if (!rpc || this._status !== "running") {
1761
+ throw new Error(
1762
+ `LSP request ${method} is unavailable because the client is not running.`,
1763
+ );
1764
+ }
1765
+ const data = (await rpc.sendRequest(method, params, control)) as T | null | undefined;
1766
+ await this.diagnostics.assertSemanticInputsCurrent(inputSnapshot, control);
1767
+ return data ?? null;
1768
+ },
1769
+ control,
1770
+ documentUri,
1771
+ );
1665
1772
  }
1666
1773
 
1667
1774
  private handleServerRequest(method: string, params: unknown): unknown {
@@ -1,6 +1,6 @@
1
- /** Reason for a partial or unavailable single-file result when the push stays tentative. */
1
+ /** Explain the lack of request-based confirmation when only ambient push evidence is available. */
2
2
  export const TENTATIVE_PUSH_UNAVAILABLE_REASON =
3
- "A diagnostic publication is ambient evidence only; it may show issues, but an empty publication cannot confirm that the document is clean.";
3
+ "Only ambient push diagnostics are available for this file; completion of the diagnostic check cannot be confirmed. An empty publication cannot confirm that the document is clean.";
4
4
 
5
5
  /** A final evidence state for one tracked document. */
6
6
  export type DiagnosticEvidenceStatus = "confirmed" | "unconfirmed" | "failed" | "removed";