@akira-tl/forgerelay 0.4.4 → 0.4.6

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.
@@ -1,5 +1,5 @@
1
1
  import { realpath } from "node:fs/promises";
2
- import { resolve } from "node:path";
2
+ import { resolve, sep } from "node:path";
3
3
  import { CodeIntelligenceError, LanguageService, languageServiceKey, } from "../code-intelligence.js";
4
4
  import { LanguageServerConfigurationError, resolveLanguageProject, } from "../language-server-config.js";
5
5
  const LANGUAGE_SERVICE_IDLE_MS = 10 * 60 * 1_000;
@@ -8,17 +8,25 @@ const MAX_LANGUAGE_SERVICES = 16;
8
8
  const LANGUAGE_SERVICE_START_TIMEOUT_MS = 15_000;
9
9
  const LANGUAGE_REQUEST_TIMEOUT_MS = 10_000;
10
10
  const LANGUAGE_SERVICE_SHUTDOWN_TIMEOUT_MS = 2_000;
11
+ const MAX_CONCURRENT_SEMANTIC_REQUESTS = 4;
12
+ const MAX_QUEUED_SEMANTIC_REQUESTS = 16;
11
13
  const MAX_DIAGNOSTIC_DOCUMENTS = 128;
12
14
  const MAX_DIAGNOSTICS_PER_DOCUMENT = 1000;
15
+ const LANGUAGE_SERVICE_CRASH_COOLDOWN_MS = 5_000;
13
16
  export class CodeIntelligenceManager {
14
17
  config;
15
18
  services = new Map();
16
19
  serviceCreations = new Map();
20
+ invalidatedServiceKeys = new Set();
21
+ crashStates = new Map();
22
+ retiredWorkspaceRoots = new Set();
17
23
  serviceCreationQueue = Promise.resolve();
18
24
  cleanupTimer;
19
25
  policy;
26
+ crashCooldownMs;
20
27
  constructor(config, options = {}) {
21
28
  this.config = config;
29
+ this.crashCooldownMs = positiveInteger(options.crashCooldownMs, LANGUAGE_SERVICE_CRASH_COOLDOWN_MS, "crashCooldownMs");
22
30
  this.policy = {
23
31
  idleMs: positiveInteger(options.idleMs, LANGUAGE_SERVICE_IDLE_MS, "idleMs"),
24
32
  cleanupIntervalMs: positiveInteger(options.cleanupIntervalMs, LANGUAGE_SERVICE_CLEANUP_INTERVAL_MS, "cleanupIntervalMs"),
@@ -26,6 +34,8 @@ export class CodeIntelligenceManager {
26
34
  startTimeoutMs: positiveInteger(options.startTimeoutMs, LANGUAGE_SERVICE_START_TIMEOUT_MS, "startTimeoutMs"),
27
35
  requestTimeoutMs: positiveInteger(options.requestTimeoutMs, LANGUAGE_REQUEST_TIMEOUT_MS, "requestTimeoutMs"),
28
36
  shutdownTimeoutMs: positiveInteger(options.shutdownTimeoutMs, LANGUAGE_SERVICE_SHUTDOWN_TIMEOUT_MS, "shutdownTimeoutMs"),
37
+ maxConcurrentSemanticRequests: positiveInteger(options.maxConcurrentSemanticRequests, MAX_CONCURRENT_SEMANTIC_REQUESTS, "maxConcurrentSemanticRequests"),
38
+ maxQueuedSemanticRequests: positiveInteger(options.maxQueuedSemanticRequests, MAX_QUEUED_SEMANTIC_REQUESTS, "maxQueuedSemanticRequests"),
29
39
  maxDiagnosticDocuments: positiveInteger(options.maxDiagnosticDocuments, MAX_DIAGNOSTIC_DOCUMENTS, "maxDiagnosticDocuments"),
30
40
  maxDiagnosticsPerDocument: positiveInteger(options.maxDiagnosticsPerDocument, MAX_DIAGNOSTICS_PER_DOCUMENT, "maxDiagnosticsPerDocument"),
31
41
  };
@@ -34,11 +44,12 @@ export class CodeIntelligenceManager {
34
44
  }, this.policy.cleanupIntervalMs);
35
45
  this.cleanupTimer.unref();
36
46
  }
37
- async run(workspaceRoot, input) {
47
+ async run(workspaceRoot, input, options = {}) {
38
48
  let project;
39
49
  let canonicalWorkspaceRoot;
40
50
  try {
41
51
  canonicalWorkspaceRoot = await realpath(resolve(workspaceRoot));
52
+ this.assertWorkspaceRootAvailable(canonicalWorkspaceRoot);
42
53
  project = await resolveLanguageProject({
43
54
  workspaceRoot: canonicalWorkspaceRoot,
44
55
  sourcePath: input.path,
@@ -51,26 +62,42 @@ export class CodeIntelligenceManager {
51
62
  }
52
63
  throw error;
53
64
  }
54
- const service = await this.acquireService(canonicalWorkspaceRoot, project);
55
- try {
56
- switch (input.operation) {
57
- case "definition":
58
- return await service.definition(input);
59
- case "hover":
60
- return await service.hover(input);
61
- case "references":
62
- return await service.references(input);
63
- case "documentSymbols":
64
- return await service.documentSymbols(input);
65
- case "workspaceSymbols":
66
- return await service.workspaceSymbols(input);
67
- case "diagnostics":
68
- return await service.diagnostics(input);
65
+ await this.invalidateChangedServices(project);
66
+ const identity = languageServiceKey(project);
67
+ this.assertNotCoolingDown(identity, project);
68
+ let lastCrash;
69
+ for (let attempt = 0; attempt < 2; attempt += 1) {
70
+ this.assertWorkspaceRootAvailable(canonicalWorkspaceRoot);
71
+ const service = await this.acquireService(canonicalWorkspaceRoot, project);
72
+ let crashed = false;
73
+ try {
74
+ const result = await this.executeOperation(service, input, options.signal);
75
+ this.crashStates.delete(identity);
76
+ return result;
77
+ }
78
+ catch (error) {
79
+ if (!(error instanceof CodeIntelligenceError) || error.code !== "code.server_crashed") {
80
+ throw error;
81
+ }
82
+ crashed = true;
83
+ lastCrash = error;
84
+ }
85
+ finally {
86
+ await this.releaseService(service);
87
+ }
88
+ if (crashed) {
89
+ await this.discardService(service);
90
+ const failures = (this.crashStates.get(identity)?.failures ?? 0) + 1;
91
+ if (attempt === 0) {
92
+ this.crashStates.set(identity, { failures, cooldownUntil: 0 });
93
+ continue;
94
+ }
95
+ const cooldownUntil = Date.now() + this.crashCooldownMs;
96
+ this.crashStates.set(identity, { failures, cooldownUntil });
97
+ throw new CodeIntelligenceError("code.language_service_cooldown", `Language server ${project.definition.id} crashed repeatedly; retry after ${this.crashCooldownMs}ms. Last error: ${lastCrash.message}`);
69
98
  }
70
99
  }
71
- finally {
72
- service.release();
73
- }
100
+ throw lastCrash ?? new CodeIntelligenceError("code.server_crashed", `Language server ${project.definition.id} failed without a recoverable result.`);
74
101
  }
75
102
  async shutdown() {
76
103
  clearInterval(this.cleanupTimer);
@@ -78,11 +105,150 @@ export class CodeIntelligenceManager {
78
105
  this.serviceCreations.clear();
79
106
  const services = [...this.services.values()];
80
107
  this.services.clear();
108
+ this.invalidatedServiceKeys.clear();
109
+ this.crashStates.clear();
110
+ this.retiredWorkspaceRoots.clear();
81
111
  await Promise.allSettled(services.map((service) => service.shutdown()));
82
112
  }
83
113
  get size() {
84
114
  return this.services.size;
85
115
  }
116
+ stats() {
117
+ const services = [...this.services.values()];
118
+ const now = Date.now();
119
+ return services.reduce((stats, service) => {
120
+ const serviceStats = service.runtimeStats;
121
+ stats.servicesActive += service.isIdle ? 0 : 1;
122
+ stats.servicesIdle += service.isIdle ? 1 : 0;
123
+ stats.processesRunning += serviceStats.processRunning ? 1 : 0;
124
+ stats.operationsInFlight += serviceStats.operationInFlight;
125
+ stats.semanticRequestsActive += serviceStats.semanticRequestsActive;
126
+ stats.semanticRequestsQueued += serviceStats.semanticRequestsQueued;
127
+ stats.openDocuments += serviceStats.openDocuments;
128
+ stats.diagnosticSnapshots += serviceStats.diagnosticSnapshots;
129
+ stats.diagnosticsRetained += serviceStats.diagnosticsRetained;
130
+ stats.stderrBytes += serviceStats.stderrBytes;
131
+ return stats;
132
+ }, {
133
+ servicesTotal: services.length,
134
+ servicesActive: 0,
135
+ servicesIdle: 0,
136
+ processesRunning: 0,
137
+ operationsInFlight: 0,
138
+ semanticRequestsActive: 0,
139
+ semanticRequestsQueued: 0,
140
+ openDocuments: 0,
141
+ diagnosticSnapshots: 0,
142
+ diagnosticsRetained: 0,
143
+ stderrBytes: 0,
144
+ pendingCreations: this.serviceCreations.size,
145
+ crashCooldowns: [...this.crashStates.values()].filter((state) => state.cooldownUntil > now).length,
146
+ invalidatedServices: this.invalidatedServiceKeys.size,
147
+ retiredWorkspaceRoots: this.retiredWorkspaceRoots.size,
148
+ });
149
+ }
150
+ async retireWorkspaceRoot(workspaceRoot) {
151
+ const canonicalRoot = await realpath(resolve(workspaceRoot));
152
+ this.retiredWorkspaceRoots.add(canonicalRoot);
153
+ await Promise.allSettled(this.serviceCreations.values());
154
+ const matching = [...this.services.entries()].filter(([, service]) => resolve(service.workspaceRoot) === canonicalRoot);
155
+ const active = matching.filter(([, service]) => !service.isIdle);
156
+ if (active.length > 0) {
157
+ this.retiredWorkspaceRoots.delete(canonicalRoot);
158
+ throw new CodeIntelligenceError("code.language_service_busy", `Cannot finalize Workspace ${canonicalRoot} while ${active.length} Language service request(s) are still active.`);
159
+ }
160
+ let releasedServices = 0;
161
+ for (const [key, service] of matching) {
162
+ if (this.services.get(key) === service)
163
+ this.services.delete(key);
164
+ this.invalidatedServiceKeys.delete(key);
165
+ this.crashStates.delete(key);
166
+ await service.shutdown();
167
+ releasedServices += 1;
168
+ }
169
+ this.clearIdentityStateForWorkspaceRoot(canonicalRoot);
170
+ return { root: canonicalRoot, releasedServices };
171
+ }
172
+ restoreWorkspaceRoot(root) {
173
+ this.retiredWorkspaceRoots.delete(resolve(root));
174
+ }
175
+ assertWorkspaceRootAvailable(workspaceRoot) {
176
+ if (!this.retiredWorkspaceRoots.has(resolve(workspaceRoot)))
177
+ return;
178
+ throw new CodeIntelligenceError("code.language_service_unavailable", "Code intelligence is unavailable because this managed-worktree Workspace is being finalized.");
179
+ }
180
+ clearIdentityStateForWorkspaceRoot(workspaceRoot) {
181
+ for (const key of [...this.crashStates.keys()]) {
182
+ if (identityBelongsToWorkspaceRoot(key, workspaceRoot))
183
+ this.crashStates.delete(key);
184
+ }
185
+ for (const key of [...this.invalidatedServiceKeys]) {
186
+ if (identityBelongsToWorkspaceRoot(key, workspaceRoot))
187
+ this.invalidatedServiceKeys.delete(key);
188
+ }
189
+ }
190
+ async executeOperation(service, input, signal) {
191
+ switch (input.operation) {
192
+ case "definition":
193
+ return service.definition(input, signal);
194
+ case "hover":
195
+ return service.hover(input, signal);
196
+ case "references":
197
+ return service.references(input, signal);
198
+ case "documentSymbols":
199
+ return service.documentSymbols(input, signal);
200
+ case "workspaceSymbols":
201
+ return service.workspaceSymbols(input, signal);
202
+ case "diagnostics":
203
+ return service.diagnostics(input, signal);
204
+ }
205
+ }
206
+ assertNotCoolingDown(identity, project) {
207
+ const state = this.crashStates.get(identity);
208
+ if (!state?.cooldownUntil)
209
+ return;
210
+ const remaining = state.cooldownUntil - Date.now();
211
+ if (remaining <= 0) {
212
+ this.crashStates.delete(identity);
213
+ return;
214
+ }
215
+ throw new CodeIntelligenceError("code.language_service_cooldown", `Language server ${project.definition.id} is cooling down after repeated crashes; retry in ${remaining}ms.`);
216
+ }
217
+ async invalidateChangedServices(project) {
218
+ const root = resolve(project.projectRoot);
219
+ const invalidated = [];
220
+ for (const [key, service] of this.services) {
221
+ if (resolve(service.project.projectRoot) === root &&
222
+ service.project.definition.id === project.definition.id &&
223
+ service.project.definition.fingerprint !== project.definition.fingerprint) {
224
+ this.invalidatedServiceKeys.add(key);
225
+ this.crashStates.delete(key);
226
+ if (service.isIdle)
227
+ invalidated.push([key, service]);
228
+ }
229
+ }
230
+ for (const [key, service] of invalidated) {
231
+ if (this.services.get(key) === service)
232
+ this.services.delete(key);
233
+ this.invalidatedServiceKeys.delete(key);
234
+ await service.shutdown();
235
+ }
236
+ }
237
+ async releaseService(service) {
238
+ service.release();
239
+ if (!this.invalidatedServiceKeys.has(service.key) || !service.isIdle)
240
+ return;
241
+ if (this.services.get(service.key) === service)
242
+ this.services.delete(service.key);
243
+ this.invalidatedServiceKeys.delete(service.key);
244
+ await service.shutdown();
245
+ }
246
+ async discardService(service) {
247
+ if (this.services.get(service.key) === service)
248
+ this.services.delete(service.key);
249
+ this.invalidatedServiceKeys.delete(service.key);
250
+ await service.shutdown();
251
+ }
86
252
  async acquireService(workspaceRoot, project) {
87
253
  const key = languageServiceKey(project);
88
254
  const existing = this.services.get(key);
@@ -133,7 +299,7 @@ export class CodeIntelligenceManager {
133
299
  }
134
300
  }
135
301
  async closeIdle(now = Date.now()) {
136
- const stale = [...this.services.entries()].filter(([, service]) => service.inFlight === 0 && now - service.lastUsedAt >= this.policy.idleMs);
302
+ const stale = [...this.services.entries()].filter(([, service]) => service.isIdle && now - service.lastUsedAt >= this.policy.idleMs);
137
303
  for (const [key, service] of stale) {
138
304
  this.services.delete(key);
139
305
  await service.shutdown();
@@ -143,7 +309,7 @@ export class CodeIntelligenceManager {
143
309
  if (this.services.size < this.policy.maxServices)
144
310
  return;
145
311
  const idle = [...this.services.entries()]
146
- .filter(([, service]) => service.inFlight === 0)
312
+ .filter(([, service]) => service.isIdle)
147
313
  .sort((left, right) => left[1].lastUsedAt - right[1].lastUsedAt);
148
314
  const candidate = idle[0];
149
315
  if (!candidate) {
@@ -153,6 +319,21 @@ export class CodeIntelligenceManager {
153
319
  await candidate[1].shutdown();
154
320
  }
155
321
  }
322
+ function identityBelongsToWorkspaceRoot(identity, workspaceRoot) {
323
+ try {
324
+ const parsed = JSON.parse(identity);
325
+ const projectRoot = Array.isArray(parsed) && typeof parsed[0] === "string"
326
+ ? resolve(parsed[0])
327
+ : undefined;
328
+ if (!projectRoot)
329
+ return false;
330
+ const root = resolve(workspaceRoot);
331
+ return projectRoot === root || projectRoot.startsWith(`${root}${sep}`);
332
+ }
333
+ catch {
334
+ return false;
335
+ }
336
+ }
156
337
  function positiveInteger(value, fallback, label) {
157
338
  const resolvedValue = value ?? fallback;
158
339
  if (!Number.isInteger(resolvedValue) || resolvedValue < 1) {
@@ -0,0 +1,116 @@
1
+ import { CancellationTokenSource } from "vscode-jsonrpc";
2
+ import { CodeIntelligenceError } from "../code-intelligence-error.js";
3
+ export class SemanticRequestCoordinator {
4
+ options;
5
+ active = 0;
6
+ queue = [];
7
+ constructor(options) {
8
+ this.options = options;
9
+ }
10
+ async run(label, signal, operation) {
11
+ const startedAt = Date.now();
12
+ await this.acquire(label, signal, startedAt);
13
+ const source = new CancellationTokenSource();
14
+ let settledForCaller = false;
15
+ let timeout;
16
+ let onAbort;
17
+ const cancellation = new Promise((_resolve, reject) => {
18
+ const rejectOnce = (error) => {
19
+ if (settledForCaller)
20
+ return;
21
+ settledForCaller = true;
22
+ try {
23
+ source.cancel();
24
+ }
25
+ catch {
26
+ // The Language-server connection may already have closed or crashed.
27
+ }
28
+ reject(error);
29
+ };
30
+ const remaining = Math.max(1, this.options.deadlineMs - (Date.now() - startedAt));
31
+ timeout = setTimeout(() => rejectOnce(new CodeIntelligenceError("code.request_timeout", `${label} exceeded the ${this.options.deadlineMs}ms semantic request deadline.`)), remaining);
32
+ timeout.unref();
33
+ if (signal) {
34
+ onAbort = () => rejectOnce(new CodeIntelligenceError("code.request_cancelled", `${label} was cancelled by the Host.`));
35
+ if (signal.aborted)
36
+ onAbort();
37
+ else
38
+ signal.addEventListener("abort", onAbort, { once: true });
39
+ }
40
+ });
41
+ const underlying = operation(source.token);
42
+ underlying.finally(() => {
43
+ source.dispose();
44
+ this.release();
45
+ }).catch(() => undefined);
46
+ try {
47
+ const value = await Promise.race([underlying, cancellation]);
48
+ settledForCaller = true;
49
+ return value;
50
+ }
51
+ finally {
52
+ if (timeout)
53
+ clearTimeout(timeout);
54
+ if (signal && onAbort)
55
+ signal.removeEventListener("abort", onAbort);
56
+ }
57
+ }
58
+ get activeCount() {
59
+ return this.active;
60
+ }
61
+ get queuedCount() {
62
+ return this.queue.length;
63
+ }
64
+ async acquire(label, signal, startedAt) {
65
+ if (signal?.aborted) {
66
+ throw new CodeIntelligenceError("code.request_cancelled", `${label} was cancelled by the Host.`);
67
+ }
68
+ if (this.active < this.options.maxConcurrent) {
69
+ this.active += 1;
70
+ return;
71
+ }
72
+ if (this.queue.length >= this.options.maxQueued) {
73
+ throw new CodeIntelligenceError("code.request_capacity", `Semantic request queue capacity reached (${this.options.maxQueued}) for this Language service.`);
74
+ }
75
+ await new Promise((resolve, reject) => {
76
+ const waiter = { resolve, reject, signal };
77
+ const remaining = Math.max(1, this.options.deadlineMs - (Date.now() - startedAt));
78
+ const remove = () => {
79
+ const index = this.queue.indexOf(waiter);
80
+ if (index >= 0)
81
+ this.queue.splice(index, 1);
82
+ };
83
+ waiter.timer = setTimeout(() => {
84
+ remove();
85
+ reject(new CodeIntelligenceError("code.request_timeout", `${label} exceeded the ${this.options.deadlineMs}ms semantic request deadline while queued.`));
86
+ }, remaining);
87
+ waiter.timer.unref();
88
+ if (signal) {
89
+ waiter.onAbort = () => {
90
+ remove();
91
+ if (waiter.timer)
92
+ clearTimeout(waiter.timer);
93
+ reject(new CodeIntelligenceError("code.request_cancelled", `${label} was cancelled by the Host.`));
94
+ };
95
+ signal.addEventListener("abort", waiter.onAbort, { once: true });
96
+ }
97
+ this.queue.push(waiter);
98
+ });
99
+ }
100
+ release() {
101
+ this.active = Math.max(0, this.active - 1);
102
+ while (this.queue.length > 0 && this.active < this.options.maxConcurrent) {
103
+ const waiter = this.queue.shift();
104
+ if (waiter.timer)
105
+ clearTimeout(waiter.timer);
106
+ if (waiter.signal && waiter.onAbort)
107
+ waiter.signal.removeEventListener("abort", waiter.onAbort);
108
+ if (waiter.signal?.aborted) {
109
+ waiter.reject(new CodeIntelligenceError("code.request_cancelled", "Semantic request was cancelled by the Host."));
110
+ continue;
111
+ }
112
+ this.active += 1;
113
+ waiter.resolve();
114
+ }
115
+ }
116
+ }
@@ -51,9 +51,14 @@ export async function createCodeIntelligenceServerFixture(t, options = {}) {
51
51
  };
52
52
  t.after(async () => {
53
53
  await close();
54
- await rm(root, { recursive: true, force: true });
54
+ await rm(root, {
55
+ recursive: true,
56
+ force: true,
57
+ maxRetries: 8,
58
+ retryDelay: 100,
59
+ });
55
60
  });
56
- return { client, project, close };
61
+ return { client, project, codeIntelligence, close };
57
62
  }
58
63
  export async function callOpen(client, path, conversationScopeId) {
59
64
  return client.callTool({
package/dist/server.js CHANGED
@@ -755,10 +755,10 @@ export function createMcpServer(config, workspaces, reviewCheckpoints, processSe
755
755
  inspectHooks: (workspaceRoot) => checkHookConfiguration(workspaceRoot, config.hooks),
756
756
  codeIntelligence: {
757
757
  available: true,
758
- run: async (input, context) => {
758
+ run: async (input, context, options) => {
759
759
  try {
760
760
  return {
761
- value: await codeIntelligence.run(context.workspaceRoot, input),
761
+ value: await codeIntelligence.run(context.workspaceRoot, input, { signal: options.signal }),
762
762
  };
763
763
  }
764
764
  catch (error) {
@@ -1254,7 +1254,7 @@ export function createMcpServer(config, workspaces, reviewCheckpoints, processSe
1254
1254
  idempotentHint: false,
1255
1255
  openWorldHint: true,
1256
1256
  },
1257
- }, async ({ workspaceId, name, action, arguments: capabilityArguments, file }) => {
1257
+ }, async ({ workspaceId, name, action, arguments: capabilityArguments, file }, extra) => {
1258
1258
  const workspace = workspaces.getWorkspace(workspaceId);
1259
1259
  let changedPaths = [];
1260
1260
  return runToolWithHooks(hooks, {
@@ -1289,7 +1289,7 @@ export function createMcpServer(config, workspaces, reviewCheckpoints, processSe
1289
1289
  });
1290
1290
  return result;
1291
1291
  }
1292
- const execution = await capabilityRegistry.run(name, capabilityArguments ?? {}, capabilityContextFor(workspace), { nativeFile: file });
1292
+ const execution = await capabilityRegistry.run(name, capabilityArguments ?? {}, capabilityContextFor(workspace), { nativeFile: file, signal: extra.signal });
1293
1293
  changedPaths = execution.changedPaths ?? [];
1294
1294
  const result = {
1295
1295
  content: [textBlock(`Capability ${name} completed.\n${JSON.stringify(execution.value, null, 2)}`)],
@@ -1389,7 +1389,14 @@ export function createMcpServer(config, workspaces, reviewCheckpoints, processSe
1389
1389
  throw new Error(`Cannot close this worktree-backed workspace while logical workspace processes are still running or awaiting completion delivery: ${busyWorkspaceIds.join(", ")}.`);
1390
1390
  }
1391
1391
  const startedAt = performance.now();
1392
- const closed = await workspaces.closeWorktree(workspaceId, commitMessage);
1392
+ const retirement = await codeIntelligence.retireWorkspaceRoot(workspace.root);
1393
+ let closed;
1394
+ try {
1395
+ closed = await workspaces.closeWorktree(workspaceId, commitMessage);
1396
+ }
1397
+ finally {
1398
+ codeIntelligence.restoreWorkspaceRoot(retirement.root);
1399
+ }
1393
1400
  await Promise.all(physicalWorkspaceIds.map((id) => reviewCheckpoints.releaseWorkspace(id)));
1394
1401
  const result = [
1395
1402
  `Closed managed-worktree-backed workspace ${workspaceId}.`,
@@ -2161,6 +2168,7 @@ export function createServer(config = loadConfig(), options = {}) {
2161
2168
  const logRuntimeResources = () => {
2162
2169
  const memory = process.memoryUsage();
2163
2170
  const processStats = processSessions.stats();
2171
+ const codeStats = codeIntelligence.stats();
2164
2172
  logEvent(config.logging, "debug", "runtime_resources", {
2165
2173
  rssBytes: memory.rss,
2166
2174
  heapUsedBytes: memory.heapUsed,
@@ -2173,7 +2181,20 @@ export function createServer(config = loadConfig(), options = {}) {
2173
2181
  processesCompleted: processStats.completed,
2174
2182
  cachedWorkspaces: workspaces.cachedWorkspaceCount,
2175
2183
  reviewStates: reviewCheckpoints.stateCount,
2176
- languageServices: codeIntelligence.size,
2184
+ languageServices: codeStats.servicesTotal,
2185
+ languageServicesActive: codeStats.servicesActive,
2186
+ languageProcessesRunning: codeStats.processesRunning,
2187
+ languageOperationsInFlight: codeStats.operationsInFlight,
2188
+ languageRequestsActive: codeStats.semanticRequestsActive,
2189
+ languageRequestsQueued: codeStats.semanticRequestsQueued,
2190
+ languageOpenDocuments: codeStats.openDocuments,
2191
+ languageDiagnosticSnapshots: codeStats.diagnosticSnapshots,
2192
+ languageDiagnosticsRetained: codeStats.diagnosticsRetained,
2193
+ languageStderrBytes: codeStats.stderrBytes,
2194
+ languagePendingCreations: codeStats.pendingCreations,
2195
+ languageCrashCooldowns: codeStats.crashCooldowns,
2196
+ languageInvalidatedServices: codeStats.invalidatedServices,
2197
+ languageRetiredWorkspaceRoots: codeStats.retiredWorkspaceRoots,
2177
2198
  });
2178
2199
  };
2179
2200
  const transportCleanupTimer = setInterval(() => {
@@ -154,7 +154,7 @@ force a Host to invalidate its cached schema.
154
154
  ### LSP code intelligence
155
155
 
156
156
  ForgeRelay advertises `code.intelligence` through the Capability Gateway; it does
157
- not add language-specific top-level MCP tools. ForgeRelay 0.4.4 supports
157
+ not add language-specific top-level MCP tools. ForgeRelay 0.4 LSP v1 supports
158
158
  `definition`, `hover`, `references`, `documentSymbols`, `workspaceSymbols`, and
159
159
  `diagnostics`.
160
160
  Position-based operations accept the same workspace-relative source position. Hover
@@ -173,7 +173,28 @@ snapshot. Push and pull use one normalized result shape with `provider`,
173
173
  filesystem document version. Bounded collection results report `returned`, `truncated`,
174
174
  and the real `total` when the complete Language-server response makes it known. Language Servers are external
175
175
  dependencies: ForgeRelay may discover an executable already installed on the
176
- machine, but it never downloads or installs one automatically.
176
+ machine, but it never downloads or installs one automatically. Built-in discovery
177
+ knows `typescript-language-server`, `pyright-langserver`, `rust-analyzer`, `gopls`,
178
+ and `clangd`. See `examples/language-servers.json` for copyable explicit TypeScript
179
+ and Pyright definitions.
180
+
181
+ ForgeRelay 0.4.5 hardens this shared Language-service runtime. Semantic requests
182
+ have one internal bounded deadline, Host cancellation propagates to LSP cancellation,
183
+ and each service has finite concurrent and queued request budgets rather than
184
+ Agent-configurable timeouts. An unexpected server crash is retried at most once;
185
+ repeated crashes enter a short cooldown. Effective server-definition fingerprints
186
+ invalidate only the affected project/service on the next resolution without adding
187
+ a recursive filesystem watcher.
188
+
189
+ Language services are keyed by physical Language project identity, so logical
190
+ workspaces over the same checkout reuse one process. Truly idle services are
191
+ reclaimed after a bounded TTL and the global service cap evicts the least-recently-
192
+ used safe idle service. A server request that ignores cancellation still counts as
193
+ active until the underlying JSON-RPC request settles. Managed-worktree finalization
194
+ releases services rooted in that worktree before removal and refuses finalization
195
+ while semantic work is active. Debug `runtime_resources` telemetry includes only
196
+ aggregate Language-service/process/request/document/diagnostic/stderr counts; it
197
+ does not log source contents or source paths.
177
198
 
178
199
  Effective Language-server definitions resolve in this order:
179
200
 
@@ -225,6 +246,11 @@ not recursively scan the Workspace.
225
246
 
226
247
  Code-intelligence input positions are 1-based line and 1-based Unicode code-point
227
248
  column values. The Workspace filesystem is the only v1 document source of truth.
249
+
250
+ For contributor/release interoperability checks, run `npm run lsp:interop`. The
251
+ command tests each supported real Language server that is already on `PATH` through
252
+ ForgeRelay built-in discovery and stdio LSP, reports a clear skip when an executable
253
+ is absent, and never installs external dependencies.
228
254
  Definition results may point outside the Workspace and are then marked
229
255
  `external: true`; this is informational only and does not expand allowed roots or
230
256
  file-tool authority.
package/docs/roadmap.md CHANGED
@@ -240,6 +240,13 @@ and verify publication before work begins on the next boundary:
240
240
  - **0.4.6** — optional real-server interoperability, cross-platform checks, fresh Host
241
241
  acceptance, documentation, and final LSP v1 closure.
242
242
 
243
+ The shipping 0.4 LSP v1 contract keeps the canonical nine Core MCP tools unchanged
244
+ and exposes semantic operations only through `code.intelligence`. Deterministic
245
+ fake-LSP coverage remains the primary cross-platform protocol/lifecycle gate, while
246
+ `npm run lsp:interop` exercises `typescript-language-server`, Pyright,
247
+ `rust-analyzer`, `gopls`, and `clangd` only when those external executables are
248
+ already present and otherwise reports explicit skips without installing them.
249
+
243
250
  ## 0.5 — First-class subagent MCP
244
251
 
245
252
  ForgeRelay already owns provider adapters and resumable local agent sessions.
@@ -85,6 +85,18 @@ Run the full local release gate with:
85
85
  npm run release:verify
86
86
  ```
87
87
 
88
+ `release:verify` checks the current development runtime and then runs a focused
89
+ `release:parity` gate in an isolated Node 22.19.0 sandbox. The parity sandbox
90
+ performs its own `npm ci` so native addons use the same Node ABI as cloud CI,
91
+ then reruns the LSP/release tests most sensitive to event-loop timing, process
92
+ lifecycle, path canonicalization, executable discovery, and cleanup behavior.
93
+ It also tests that a command which exists on `PATH` but fails its `--version`
94
+ preflight is treated as unavailable rather than as an installed Language server.
95
+
96
+ Cloud verification and the publication job are both pinned to Node 22.19.0, the
97
+ minimum supported Node release, so local parity and the release runners use the
98
+ same runtime instead of drifting across separate Node 22/24 variants.
99
+
88
100
  Validate a specific tag with:
89
101
 
90
102
  ```bash
@@ -158,8 +170,9 @@ npm publishing token.
158
170
  3. Run the appropriate `release:patch`, `release:minor`, or `release:major`
159
171
  command.
160
172
  4. Review the generated version and changelog diff.
161
- 5. Run `npm run release:verify` locally. This full local gate is a release-time
162
- operation; ordinary development pushes do not need to run the full release gate.
173
+ 5. Run `npm run release:verify` locally. This full local gate includes the isolated
174
+ Node 22.19.0 parity sandbox and is a release-time operation; ordinary development
175
+ pushes do not need to run the full release gate.
163
176
  6. Commit the release-ready code and metadata and push `main`.
164
177
  7. Create the exact version tag, for example:
165
178
 
@@ -0,0 +1,30 @@
1
+ {
2
+ "typescript": {
3
+ "command": "typescript-language-server",
4
+ "args": ["--stdio"],
5
+ "env": {},
6
+ "languages": ["typescript", "typescriptreact", "javascript", "javascriptreact"],
7
+ "extensions": [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"],
8
+ "languageIdByExtension": {
9
+ ".ts": "typescript",
10
+ ".tsx": "typescriptreact",
11
+ ".js": "javascript",
12
+ ".jsx": "javascriptreact",
13
+ ".mjs": "javascript",
14
+ ".cjs": "javascript"
15
+ },
16
+ "projectMarkers": ["tsconfig.json", "jsconfig.json", "package.json"]
17
+ },
18
+ "pyright": {
19
+ "command": "pyright-langserver",
20
+ "args": ["--stdio"],
21
+ "env": {},
22
+ "languages": ["python"],
23
+ "extensions": [".py", ".pyi"],
24
+ "languageIdByExtension": {
25
+ ".py": "python",
26
+ ".pyi": "python"
27
+ },
28
+ "projectMarkers": ["pyrightconfig.json", "pyproject.toml", "setup.cfg", "setup.py"]
29
+ }
30
+ }