cadre-ai 2.1.0 → 3.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 (81) hide show
  1. package/.claude-plugin/plugin.json +10 -0
  2. package/.codex-plugin/plugin.json +19 -0
  3. package/.mcp.codex.json +9 -0
  4. package/.mcp.json +8 -0
  5. package/LICENSE +21 -202
  6. package/README.md +348 -107
  7. package/agents/cadre-phase-worker.md +17 -0
  8. package/agents/cadre-task-worker.md +16 -0
  9. package/dist/cadre-cli.mjs +2756 -0
  10. package/dist/cadre-mcp.mjs +33680 -0
  11. package/marketplace/claude.json +16 -0
  12. package/marketplace/codex.json +20 -0
  13. package/package.json +36 -34
  14. package/skills/archive/SKILL.md +28 -0
  15. package/skills/archive/agents/openai.yaml +4 -0
  16. package/skills/create/SKILL.md +33 -0
  17. package/skills/create/agents/openai.yaml +4 -0
  18. package/skills/implement/SKILL.md +91 -0
  19. package/skills/implement/agents/openai.yaml +4 -0
  20. package/skills/refresh/SKILL.md +18 -0
  21. package/skills/refresh/agents/openai.yaml +4 -0
  22. package/skills/revert/SKILL.md +20 -0
  23. package/skills/revert/agents/openai.yaml +4 -0
  24. package/skills/review/SKILL.md +32 -0
  25. package/skills/review/agents/openai.yaml +4 -0
  26. package/skills/revise/SKILL.md +32 -0
  27. package/skills/revise/agents/openai.yaml +4 -0
  28. package/skills/status/SKILL.md +21 -0
  29. package/skills/status/agents/openai.yaml +4 -0
  30. package/skills/track/SKILL.md +33 -0
  31. package/skills/track/agents/openai.yaml +4 -0
  32. package/skills/wisp/SKILL.md +16 -0
  33. package/skills/wisp/agents/openai.yaml +4 -0
  34. package/templates/v1/init/archive/.gitkeep +1 -0
  35. package/templates/v1/init/guidelines.md +25 -0
  36. package/templates/v1/init/operations/.gitkeep +1 -0
  37. package/templates/v1/init/patterns/index.md +6 -0
  38. package/templates/v1/init/product.md +30 -0
  39. package/templates/v1/init/project.json +26 -0
  40. package/templates/v1/init/refreshes/.gitkeep +1 -0
  41. package/templates/v1/init/styleguides/general.md +14 -0
  42. package/templates/v1/init/styleguides/language.md +21 -0
  43. package/templates/v1/init/tech-stack.md +21 -0
  44. package/templates/v1/init/tracks/.gitkeep +1 -0
  45. package/templates/v1/init/tracks.md +6 -0
  46. package/templates/v1/init/workflow.md +163 -0
  47. package/templates/v1/project/archive-operation.json +15 -0
  48. package/templates/v1/project/pattern.md +20 -0
  49. package/templates/v1/project/refresh-operation.json +14 -0
  50. package/templates/v1/project/refresh.md +21 -0
  51. package/templates/v1/styleguides/dart.md +27 -0
  52. package/templates/v1/styleguides/flutter.md +27 -0
  53. package/templates/v1/styleguides/go.md +29 -0
  54. package/templates/v1/styleguides/gradle.md +28 -0
  55. package/templates/v1/styleguides/html-css.md +39 -0
  56. package/templates/v1/styleguides/index.md +27 -0
  57. package/templates/v1/styleguides/java.md +27 -0
  58. package/templates/v1/styleguides/javascript.md +27 -0
  59. package/templates/v1/styleguides/kotlin.md +26 -0
  60. package/templates/v1/styleguides/maven.md +28 -0
  61. package/templates/v1/styleguides/python.md +27 -0
  62. package/templates/v1/styleguides/react.md +28 -0
  63. package/templates/v1/styleguides/swift.md +27 -0
  64. package/templates/v1/styleguides/swiftui.md +27 -0
  65. package/templates/v1/styleguides/typescript.md +26 -0
  66. package/templates/v1/track/bug.md +14 -0
  67. package/templates/v1/track/execution.json +18 -0
  68. package/templates/v1/track/learning.md +39 -0
  69. package/templates/v1/track/plan.md +39 -0
  70. package/templates/v1/track/revert-operation.json +13 -0
  71. package/templates/v1/track/revise-operation.json +14 -0
  72. package/templates/v1/track/revision.md +36 -0
  73. package/templates/v1/track/spec.md +38 -0
  74. package/templates/v1/track/state.json +25 -0
  75. package/scripts/cadre-cli.js +0 -869
  76. package/scripts/cadre-core.js +0 -14031
  77. package/scripts/cadre-job-runner.js +0 -3365
  78. package/scripts/cadre-lsp-daemon.js +0 -1212
  79. package/scripts/cadre-lsp-review.js +0 -1067
  80. package/scripts/cadre-lsp-setup.js +0 -470
  81. package/scripts/mcp/cadre-server.js +0 -16837
@@ -1,1212 +0,0 @@
1
- #!/usr/bin/env node
2
- // AUTO-GENERATED by pnpm build from src/*.ts -- do not edit by hand.
3
- // Edit TypeScript sources under src/ instead.
4
- "use strict";
5
- var __create = Object.create;
6
- var __defProp = Object.defineProperty;
7
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
8
- var __getOwnPropNames = Object.getOwnPropertyNames;
9
- var __getProtoOf = Object.getPrototypeOf;
10
- var __hasOwnProp = Object.prototype.hasOwnProperty;
11
- var __export = (target, all) => {
12
- for (var name in all)
13
- __defProp(target, name, { get: all[name], enumerable: true });
14
- };
15
- var __copyProps = (to, from, except, desc) => {
16
- if (from && typeof from === "object" || typeof from === "function") {
17
- for (let key of __getOwnPropNames(from))
18
- if (!__hasOwnProp.call(to, key) && key !== except)
19
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
- }
21
- return to;
22
- };
23
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
- // If the importer is in node compatibility mode or this is not an ESM
25
- // file that has been converted to a CommonJS file using a Babel-
26
- // compatible transform (i.e. "__esModule" has not been set), then set
27
- // "default" to the CommonJS "module.exports" for node compatibility.
28
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
- mod
30
- ));
31
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
-
33
- // src/cadre-lsp-daemon.ts
34
- var cadre_lsp_daemon_exports = {};
35
- __export(cadre_lsp_daemon_exports, {
36
- ClientPool: () => ClientPool,
37
- handleDaemonMessage: () => handleDaemonMessage,
38
- runLspDaemon: () => runLspDaemon
39
- });
40
- module.exports = __toCommonJS(cadre_lsp_daemon_exports);
41
- var import_node_path8 = __toESM(require("node:path"));
42
- var import_node_readline = __toESM(require("node:readline"));
43
-
44
- // src/cadre-lsp-review.ts
45
- var import_node_path7 = __toESM(require("node:path"));
46
-
47
- // src/guards.ts
48
- function isRecord(value) {
49
- return typeof value === "object" && value !== null && !Array.isArray(value);
50
- }
51
- function asJsonObject(value) {
52
- return isRecord(value) ? value : {};
53
- }
54
- function asOptionalString(value) {
55
- return typeof value === "string" ? value : void 0;
56
- }
57
- function asNumber(value, fallback = 0) {
58
- return typeof value === "number" && Number.isFinite(value) ? value : fallback;
59
- }
60
- function asStringArray(value) {
61
- return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
62
- }
63
- function errorMessage(error) {
64
- return error instanceof Error ? error.message : String(error);
65
- }
66
-
67
- // src/lsp/review/client.ts
68
- var import_node_fs = __toESM(require("node:fs"));
69
- var import_node_path2 = __toESM(require("node:path"));
70
- var import_node_child_process = require("node:child_process");
71
- var import_node_url = require("node:url");
72
-
73
- // src/lsp/review/constants.ts
74
- var DEFAULT_STARTUP_TIMEOUT_MS = 1e4;
75
- var DEFAULT_REQUEST_TIMEOUT_MS = 8e3;
76
- var DEFAULT_SHUTDOWN_TIMEOUT_MS = 2e3;
77
- var MAX_TEXT_REFERENCE_RESULTS = 50;
78
- var MAX_SCAN_FILE_BYTES = 1024 * 1024;
79
-
80
- // src/lsp/review/language-ids.ts
81
- var import_node_path = __toESM(require("node:path"));
82
- var DEFAULT_LANGUAGE_IDS = {
83
- ".bash": "shellscript",
84
- ".c": "c",
85
- ".cc": "cpp",
86
- ".clj": "clojure",
87
- ".cljc": "clojure",
88
- ".cljs": "clojure",
89
- ".cpp": "cpp",
90
- ".cs": "csharp",
91
- ".css": "css",
92
- ".cxx": "cpp",
93
- ".dart": "dart",
94
- ".edn": "clojure",
95
- ".elm": "elm",
96
- ".ex": "elixir",
97
- ".exs": "elixir",
98
- ".go": "go",
99
- ".gql": "graphql",
100
- ".graphql": "graphql",
101
- ".h": "c",
102
- ".hcl": "terraform",
103
- ".hpp": "cpp",
104
- ".hs": "haskell",
105
- ".html": "html",
106
- ".htm": "html",
107
- ".java": "java",
108
- ".js": "javascript",
109
- ".json": "json",
110
- ".jsonc": "jsonc",
111
- ".jsx": "javascriptreact",
112
- ".kt": "kotlin",
113
- ".kts": "kotlin",
114
- ".less": "less",
115
- ".lhs": "haskell",
116
- ".lua": "lua",
117
- ".m": "objective-c",
118
- ".md": "markdown",
119
- ".mdx": "markdown",
120
- ".ml": "ocaml",
121
- ".mli": "ocaml",
122
- ".mm": "objective-cpp",
123
- ".nix": "nix",
124
- ".php": "php",
125
- ".prisma": "prisma",
126
- ".proto": "proto",
127
- ".py": "python",
128
- ".pyi": "python",
129
- ".rb": "ruby",
130
- ".rs": "rust",
131
- ".sass": "sass",
132
- ".scala": "scala",
133
- ".sc": "scala",
134
- ".scss": "scss",
135
- ".sh": "shellscript",
136
- ".svelte": "svelte",
137
- ".swift": "swift",
138
- ".tf": "terraform",
139
- ".tfvars": "terraform",
140
- ".toml": "toml",
141
- ".ts": "typescript",
142
- ".tsx": "typescriptreact",
143
- ".vue": "vue",
144
- ".xml": "xml",
145
- ".xsd": "xml",
146
- ".xsl": "xml",
147
- ".xslt": "xml",
148
- ".yaml": "yaml",
149
- ".yml": "yaml",
150
- ".zig": "zig",
151
- ".zsh": "shellscript",
152
- "containerfile": "dockerfile",
153
- "dockerfile": "dockerfile"
154
- };
155
- function languageId(file, server) {
156
- const ext = import_node_path.default.extname(file);
157
- const basename = import_node_path.default.basename(file).toLowerCase();
158
- const overrides = server ? asJsonObject(server.languageIds) : {};
159
- return asOptionalString(overrides[ext]) || asOptionalString(overrides[basename]) || DEFAULT_LANGUAGE_IDS[ext] || DEFAULT_LANGUAGE_IDS[basename] || "plaintext";
160
- }
161
-
162
- // src/lsp/review/utils.ts
163
- function positiveInt(value, fallback) {
164
- const number = Number(value);
165
- return Number.isFinite(number) && number > 0 ? number : fallback;
166
- }
167
- function withTimeout(promise, timeoutMs, message) {
168
- let timer;
169
- return Promise.race([
170
- promise,
171
- new Promise((_, reject) => {
172
- timer = setTimeout(() => reject(new Error(message)), timeoutMs);
173
- })
174
- ]).finally(() => clearTimeout(timer));
175
- }
176
-
177
- // src/lsp/review/client.ts
178
- var LspClient = class {
179
- root;
180
- server;
181
- requestTimeoutMs;
182
- nextId;
183
- pending;
184
- buffer;
185
- opened;
186
- publishedDiagnostics;
187
- proc = null;
188
- constructor(root, server) {
189
- this.root = root;
190
- this.server = server;
191
- this.requestTimeoutMs = positiveInt(server.requestTimeoutMs, DEFAULT_REQUEST_TIMEOUT_MS);
192
- this.nextId = 1;
193
- this.pending = /* @__PURE__ */ new Map();
194
- this.buffer = Buffer.alloc(0);
195
- this.opened = /* @__PURE__ */ new Map();
196
- this.publishedDiagnostics = /* @__PURE__ */ new Map();
197
- }
198
- start() {
199
- return new Promise((resolve, reject) => {
200
- let settled = false;
201
- const finishResolve = () => {
202
- if (settled) return;
203
- settled = true;
204
- resolve();
205
- };
206
- const finishReject = (error) => {
207
- if (settled) return;
208
- settled = true;
209
- reject(error);
210
- };
211
- this.proc = (0, import_node_child_process.spawn)(this.server.command, this.server.args || [], {
212
- cwd: this.root,
213
- stdio: ["pipe", "pipe", "pipe"]
214
- });
215
- this.proc.once("spawn", finishResolve);
216
- this.proc.once("error", (error) => {
217
- finishReject(new Error(`Unable to start ${this.server.command}: ${errorMessage(error)}`));
218
- });
219
- this.proc.stdout.on("data", (chunk) => this.read(chunk));
220
- this.proc.stderr.on("data", () => {
221
- });
222
- this.proc.on("exit", (code, signal) => {
223
- const message = signal ? `LSP server exited with signal ${signal}` : `LSP server exited with code ${code}`;
224
- finishReject(new Error(message));
225
- for (const pending of this.pending.values()) {
226
- clearTimeout(pending.timer);
227
- pending.reject(new Error(message));
228
- }
229
- this.pending.clear();
230
- });
231
- });
232
- }
233
- read(chunk) {
234
- this.buffer = Buffer.concat([this.buffer, chunk]);
235
- while (true) {
236
- const headerEnd = this.buffer.indexOf("\r\n\r\n");
237
- if (headerEnd === -1) return;
238
- const header = this.buffer.slice(0, headerEnd).toString("utf8");
239
- const match = header.match(/Content-Length:\s*(\d+)/i);
240
- if (!match) {
241
- this.buffer = this.buffer.slice(headerEnd + 4);
242
- continue;
243
- }
244
- const length = Number(match[1]);
245
- const bodyStart = headerEnd + 4;
246
- const bodyEnd = bodyStart + length;
247
- if (this.buffer.length < bodyEnd) return;
248
- const body = this.buffer.slice(bodyStart, bodyEnd).toString("utf8");
249
- this.buffer = this.buffer.slice(bodyEnd);
250
- let message;
251
- try {
252
- message = asJsonObject(JSON.parse(body));
253
- } catch {
254
- continue;
255
- }
256
- const messageId = typeof message.id === "number" ? message.id : null;
257
- if (messageId != null && this.pending.has(messageId)) {
258
- const pending = this.pending.get(messageId);
259
- if (!pending) continue;
260
- this.pending.delete(messageId);
261
- clearTimeout(pending.timer);
262
- const error = asJsonObject(message.error);
263
- if (Object.keys(error).length > 0) pending.reject(new Error(asOptionalString(error.message) || "LSP request failed"));
264
- else pending.resolve(message.result);
265
- } else if (message.method === "textDocument/publishDiagnostics") {
266
- const params = asJsonObject(message.params);
267
- const uri = asOptionalString(params.uri);
268
- if (uri) {
269
- const diagnostics = Array.isArray(params.diagnostics) ? params.diagnostics.map((diagnostic) => asJsonObject(diagnostic)) : [];
270
- this.publishedDiagnostics.set(uri, diagnostics);
271
- }
272
- }
273
- }
274
- }
275
- write(message) {
276
- if (!this.proc) throw new Error("LSP process is not running");
277
- const body = JSON.stringify(message);
278
- this.proc.stdin.write(`Content-Length: ${Buffer.byteLength(body, "utf8")}\r
279
- \r
280
- ${body}`);
281
- }
282
- request(method, params) {
283
- const id = this.nextId++;
284
- return new Promise((resolve, reject) => {
285
- const timer = setTimeout(() => {
286
- this.pending.delete(id);
287
- reject(new Error(`${method} timed out after ${this.requestTimeoutMs}ms`));
288
- }, this.requestTimeoutMs);
289
- this.pending.set(id, { resolve, reject, timer });
290
- try {
291
- this.write({ jsonrpc: "2.0", id, method, params });
292
- } catch (error) {
293
- clearTimeout(timer);
294
- this.pending.delete(id);
295
- reject(error);
296
- }
297
- });
298
- }
299
- notify(method, params) {
300
- this.write({ jsonrpc: "2.0", method, params });
301
- }
302
- async initialize() {
303
- await this.request("initialize", {
304
- processId: process.pid,
305
- rootUri: (0, import_node_url.pathToFileURL)(this.root).href,
306
- capabilities: {
307
- textDocument: {
308
- documentSymbol: { hierarchicalDocumentSymbolSupport: true },
309
- references: {}
310
- },
311
- workspace: { workspaceFolders: true }
312
- },
313
- workspaceFolders: [{ uri: (0, import_node_url.pathToFileURL)(this.root).href, name: import_node_path2.default.basename(this.root) }]
314
- });
315
- this.notify("initialized", {});
316
- }
317
- open(file) {
318
- const abs = import_node_path2.default.join(this.root, file);
319
- const uri = (0, import_node_url.pathToFileURL)(abs).href;
320
- const text = import_node_fs.default.readFileSync(abs, "utf8");
321
- const version = (this.opened.get(file) || 0) + 1;
322
- const alreadyOpen = this.opened.has(file);
323
- this.opened.set(file, version);
324
- if (alreadyOpen) {
325
- this.notify("textDocument/didChange", {
326
- textDocument: { uri, version },
327
- contentChanges: [{ text }]
328
- });
329
- } else {
330
- this.notify("textDocument/didOpen", {
331
- textDocument: {
332
- uri,
333
- languageId: languageId(file, this.server),
334
- version,
335
- text
336
- }
337
- });
338
- }
339
- }
340
- async documentSymbols(file) {
341
- return this.request("textDocument/documentSymbol", {
342
- textDocument: { uri: (0, import_node_url.pathToFileURL)(import_node_path2.default.join(this.root, file)).href }
343
- });
344
- }
345
- async references(file, position) {
346
- return this.request("textDocument/references", {
347
- textDocument: { uri: (0, import_node_url.pathToFileURL)(import_node_path2.default.join(this.root, file)).href },
348
- position,
349
- context: { includeDeclaration: false }
350
- });
351
- }
352
- async definition(file, position) {
353
- return this.request("textDocument/definition", {
354
- textDocument: { uri: (0, import_node_url.pathToFileURL)(import_node_path2.default.join(this.root, file)).href },
355
- position
356
- });
357
- }
358
- async typeDefinition(file, position) {
359
- return this.request("textDocument/typeDefinition", {
360
- textDocument: { uri: (0, import_node_url.pathToFileURL)(import_node_path2.default.join(this.root, file)).href },
361
- position
362
- });
363
- }
364
- async implementation(file, position) {
365
- return this.request("textDocument/implementation", {
366
- textDocument: { uri: (0, import_node_url.pathToFileURL)(import_node_path2.default.join(this.root, file)).href },
367
- position
368
- });
369
- }
370
- diagnostics(file) {
371
- return this.publishedDiagnostics.get((0, import_node_url.pathToFileURL)(import_node_path2.default.join(this.root, file)).href) || [];
372
- }
373
- async shutdown() {
374
- try {
375
- await withTimeout(
376
- this.request("shutdown", null),
377
- DEFAULT_SHUTDOWN_TIMEOUT_MS,
378
- `shutdown timed out after ${DEFAULT_SHUTDOWN_TIMEOUT_MS}ms`
379
- );
380
- this.notify("exit", {});
381
- } catch {
382
- }
383
- if (this.proc && !this.proc.killed) this.proc.kill();
384
- }
385
- };
386
-
387
- // src/lsp/review/command-availability.ts
388
- var import_node_child_process2 = require("node:child_process");
389
- function shellQuote(value) {
390
- return `'${String(value).replace(/'/g, "'\\''")}'`;
391
- }
392
- function commandAvailability(command) {
393
- if (!command || typeof command !== "string") {
394
- return {
395
- state: "invalid",
396
- command: typeof command === "string" ? command : null,
397
- message: "Server command is missing or invalid"
398
- };
399
- }
400
- const result = (0, import_node_child_process2.spawnSync)("sh", ["-lc", `command -v ${shellQuote(command)}`], {
401
- encoding: "utf8"
402
- });
403
- if (result.status === 0) {
404
- return {
405
- state: "available",
406
- command,
407
- path: result.stdout.trim().split(/\r?\n/)[0] || command
408
- };
409
- }
410
- return {
411
- state: "missing",
412
- command,
413
- message: (result.stderr || result.stdout || "Command not found on PATH").trim()
414
- };
415
- }
416
-
417
- // src/lsp/review/run-review.ts
418
- var import_node_fs4 = __toESM(require("node:fs"));
419
- var import_node_path6 = __toESM(require("node:path"));
420
-
421
- // src/lsp/ignore-policy.ts
422
- var import_node_path3 = __toESM(require("node:path"));
423
- var DEFAULT_IGNORES = /* @__PURE__ */ new Set([
424
- ".git",
425
- ".hg",
426
- ".svn",
427
- ".worktrees",
428
- ".agents",
429
- ".claude",
430
- ".cache",
431
- ".codex",
432
- ".copilot",
433
- ".dart_tool",
434
- ".gemini",
435
- ".gradle",
436
- ".mypy_cache",
437
- ".pytest_cache",
438
- ".ruff_cache",
439
- ".serverless",
440
- "node_modules",
441
- "vendor",
442
- "dist",
443
- "build",
444
- "coverage",
445
- "out",
446
- "target",
447
- ".next",
448
- ".nuxt",
449
- ".parcel-cache",
450
- ".svelte-kit",
451
- ".turbo",
452
- ".vite",
453
- ".venv",
454
- "venv",
455
- "__pycache__",
456
- "__generated__",
457
- "generated",
458
- "gen",
459
- "tmp",
460
- "temp",
461
- "logs",
462
- "Pods",
463
- "DerivedData",
464
- ".idea",
465
- ".vscode"
466
- ]);
467
- var DEFAULT_IGNORE_PATHS = [
468
- "plugins/cadre",
469
- "plugins/cadre-claude",
470
- "plugins/cadre-copilot",
471
- "plugins/cadre-antigravity"
472
- ];
473
- function normalizeRel(file) {
474
- return file.split(import_node_path3.default.sep).join("/");
475
- }
476
- function shouldIgnore(root, fullPath, name) {
477
- if (DEFAULT_IGNORES.has(name)) return true;
478
- const rel = normalizeRel(import_node_path3.default.relative(root, fullPath));
479
- return DEFAULT_IGNORE_PATHS.some(
480
- (ignored) => rel === ignored || rel.startsWith(`${ignored}/`)
481
- );
482
- }
483
- function isIgnoredFile(root, file) {
484
- const rel = normalizeRel(file);
485
- if (rel.split("/").some((part) => DEFAULT_IGNORES.has(part))) return true;
486
- return DEFAULT_IGNORE_PATHS.some(
487
- (ignored) => rel === ignored || rel.startsWith(`${ignored}/`)
488
- );
489
- }
490
-
491
- // src/lsp/review/git-diff.ts
492
- var import_node_fs2 = __toESM(require("node:fs"));
493
- var import_node_path4 = __toESM(require("node:path"));
494
- var import_node_child_process3 = require("node:child_process");
495
- function runGit(root, args) {
496
- const result = (0, import_node_child_process3.spawnSync)("git", args, { cwd: root, encoding: "utf8" });
497
- if (result.status !== 0) {
498
- throw new Error((result.stderr || result.stdout || `git ${args.join(" ")} failed`).trim());
499
- }
500
- return result.stdout;
501
- }
502
- function changedEntries(root, base, head) {
503
- return runGit(root, ["diff", "--name-status", "--find-renames", `${base}...${head}`]).split(/\r?\n/).map((line) => line.trim()).filter(Boolean).map((line) => {
504
- const parts = line.split(/\t+/);
505
- const status = parts[0] || "M";
506
- const code = status[0] || "M";
507
- const oldPath = (code === "R" || code === "C" ? parts[1] : null) || null;
508
- const file = code === "R" || code === "C" ? parts[2] : parts[1];
509
- const kind = {
510
- A: "added",
511
- C: "copied",
512
- D: "deleted",
513
- M: "modified",
514
- R: "renamed",
515
- T: "type_changed",
516
- U: "unmerged",
517
- X: "unknown"
518
- }[code] || "modified";
519
- return {
520
- status,
521
- kind,
522
- path: file || "",
523
- oldPath,
524
- exists: file ? import_node_fs2.default.existsSync(import_node_path4.default.join(root, file)) : false
525
- };
526
- }).filter((entry) => Boolean(entry.path) && !isIgnoredFile(root, entry.path));
527
- }
528
- function changedSymbolCandidates(root, base, head, entry) {
529
- const paths = Array.from(new Set([entry.oldPath, entry.path].filter((item) => typeof item === "string" && item.length > 0)));
530
- const diff = runGit(root, [
531
- "diff",
532
- "--unified=0",
533
- "--find-renames",
534
- `${base}...${head}`,
535
- "--",
536
- ...paths
537
- ]);
538
- const byName = /* @__PURE__ */ new Map();
539
- const patterns = [
540
- /^[+-]\s*(?:export\s+)?(?:async\s+)?(?:function|def)\s+([A-Za-z_$][\w$]*)\b/,
541
- /^[+-]\s*func\s+(?:\([^)]*\)\s*)?([A-Za-z_$][\w$]*)\b/,
542
- /^[+-]\s*(?:export\s+)?(?:class|interface|type|enum|struct|module|namespace)\s+([A-Za-z_$][\w$]*)\b/,
543
- /^[+-]\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*[:=]/,
544
- /^[+-]\s*(?:public|private|protected|internal|static|final|open|override|async|\s)*(?:fun|func)\s+([A-Za-z_$][\w$]*)\b/,
545
- /^[+-]\s*(?:public|private|protected|static|async|\s)*([A-Za-z_$][\w$]*)\s*\([^)]*\)\s*[:{]/,
546
- /^[+-]\s*(?:local\s+)?function\s+([A-Za-z_][\w.]*)\b/,
547
- /^[+-]\s*(?:defp?|defmacro)\s+([A-Za-z_][\w!?]*)\b/,
548
- /^[+-]\s*(?:function\s+)?([A-Za-z_][\w-]*)\s*\(\)\s*\{?/,
549
- /^[+-]\s*(?:CREATE\s+(?:OR\s+REPLACE\s+)?)?(?:TABLE|VIEW|FUNCTION|PROCEDURE|TYPE)\s+([A-Za-z_][\w."]*)\b/i,
550
- /^[+-]\s*(?:resource|module|variable|output|data)\s+"?([A-Za-z0-9_.-]+)"?/
551
- ];
552
- for (const line of diff.split(/\r?\n/)) {
553
- if (!/^[+-]/.test(line) || /^(\+\+\+|---)/.test(line)) continue;
554
- const direction = line[0] === "-" ? "removed" : "added";
555
- for (const pattern of patterns) {
556
- const match = line.match(pattern);
557
- if (!match) continue;
558
- const name = match[1];
559
- if (!name) continue;
560
- if (!byName.has(name)) {
561
- byName.set(name, {
562
- name,
563
- added: false,
564
- removed: false,
565
- changeType: "changed",
566
- changedFile: entry.path,
567
- oldPath: entry.oldPath,
568
- status: entry.kind,
569
- evidence: []
570
- });
571
- }
572
- const candidate = byName.get(name);
573
- if (!candidate) continue;
574
- if (direction === "removed") candidate.removed = true;
575
- else candidate.added = true;
576
- if (candidate.evidence.length < 4) {
577
- candidate.evidence.push({
578
- direction,
579
- text: line.slice(1).trim().slice(0, 160)
580
- });
581
- }
582
- }
583
- }
584
- return Array.from(byName.values()).map((candidate) => ({
585
- ...candidate,
586
- changeType: candidate.removed ? candidate.added ? "changed" : "removed" : "added"
587
- })).filter((candidate) => candidate.changeType !== "added").sort((a, b) => a.name.localeCompare(b.name));
588
- }
589
-
590
- // src/lsp/review/scanners.ts
591
- var import_node_fs3 = __toESM(require("node:fs"));
592
- var import_node_path5 = __toESM(require("node:path"));
593
- var import_node_url2 = require("node:url");
594
- function flattenSymbols(symbols, out = []) {
595
- if (!Array.isArray(symbols)) return out;
596
- for (const symbol of symbols) {
597
- const candidate = asJsonObject(symbol);
598
- if (candidate.name && candidate.selectionRange) out.push(candidate);
599
- if (candidate.children) flattenSymbols(candidate.children, out);
600
- }
601
- return out;
602
- }
603
- function escapeRegExp(value) {
604
- return String(value).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
605
- }
606
- function serverFileMatch(file, server) {
607
- const extensionSet = new Set(server.extensions || []);
608
- const filenameSet = new Set((server.filenames || []).map((name) => name.toLowerCase()));
609
- const ext = import_node_path5.default.extname(file);
610
- const basename = import_node_path5.default.basename(file).toLowerCase();
611
- return extensionSet.has(ext) || filenameSet.has(basename);
612
- }
613
- function scanTextReferences(root, symbol, changedPathSet, server) {
614
- const results = [];
615
- const pattern = new RegExp(
616
- `(^|[^A-Za-z0-9_$])${escapeRegExp(symbol)}([^A-Za-z0-9_$]|$)`
617
- );
618
- function visit(dir) {
619
- let entries;
620
- try {
621
- entries = import_node_fs3.default.readdirSync(dir, { withFileTypes: true });
622
- } catch {
623
- return;
624
- }
625
- for (const entry of entries) {
626
- const full = import_node_path5.default.join(dir, entry.name);
627
- if (shouldIgnore(root, full, entry.name)) continue;
628
- if (entry.isDirectory()) {
629
- visit(full);
630
- if (results.length >= MAX_TEXT_REFERENCE_RESULTS) return;
631
- continue;
632
- }
633
- if (!entry.isFile()) continue;
634
- if (!serverFileMatch(full, server)) continue;
635
- if (changedPathSet.has(import_node_path5.default.resolve(full))) continue;
636
- let stat;
637
- try {
638
- stat = import_node_fs3.default.statSync(full);
639
- } catch {
640
- continue;
641
- }
642
- if (stat.size > MAX_SCAN_FILE_BYTES) continue;
643
- let text;
644
- try {
645
- text = import_node_fs3.default.readFileSync(full, "utf8");
646
- } catch {
647
- continue;
648
- }
649
- const lines = text.split(/\r?\n/);
650
- for (let i = 0; i < lines.length; i += 1) {
651
- const line = lines[i] || "";
652
- if (!pattern.test(line)) continue;
653
- results.push({
654
- file: full,
655
- relativeFile: normalizeRel(import_node_path5.default.relative(root, full)),
656
- line: i + 1,
657
- snippet: line.trim().slice(0, 160)
658
- });
659
- if (results.length >= MAX_TEXT_REFERENCE_RESULTS) return;
660
- }
661
- }
662
- }
663
- visit(root);
664
- return results;
665
- }
666
- function externalReferenceFinding(server, candidate, refs, engine) {
667
- const removed = candidate.changeType === "removed";
668
- return {
669
- severity: removed ? "blocking" : "warning",
670
- type: "external_reference",
671
- code: removed ? "external_reference_to_removed_symbol" : "external_reference_to_changed_symbol",
672
- server: server.id || server.command,
673
- engine,
674
- symbol: {
675
- name: candidate.name,
676
- changeType: candidate.changeType,
677
- status: candidate.status,
678
- changedFile: candidate.changedFile,
679
- oldPath: candidate.oldPath
680
- },
681
- changedFile: candidate.changedFile,
682
- externalReferences: refs,
683
- message: `${candidate.name} has references outside the track diff after being ${removed ? "removed" : "changed"}.`
684
- };
685
- }
686
- function skipFinding(server, code, message, extra = {}) {
687
- return {
688
- severity: "info",
689
- type: "skip",
690
- code,
691
- server: server.id || server.command || "unknown",
692
- message,
693
- ...extra || {}
694
- };
695
- }
696
- function lspRefToLocation(root, ref) {
697
- const location = asJsonObject(ref);
698
- const uri = location.uri || location.targetUri;
699
- if (!uri) return null;
700
- try {
701
- const file = (0, import_node_url2.fileURLToPath)(uri);
702
- const range = location.range || location.targetSelectionRange || location.targetRange;
703
- return {
704
- file,
705
- relativeFile: normalizeRel(import_node_path5.default.relative(root, file)),
706
- line: (range?.start ? range.start.line : 0) + 1
707
- };
708
- } catch {
709
- return null;
710
- }
711
- }
712
- function locationsFromResult(root, value) {
713
- const items = Array.isArray(value) ? value : value ? [value] : [];
714
- return items.map((item) => {
715
- const object = asJsonObject(item);
716
- const ref = object.targetUri ? { uri: object.targetUri, range: object.targetSelectionRange || object.targetRange } : item;
717
- return lspRefToLocation(root, ref);
718
- }).filter((location) => location !== null).slice(0, 20);
719
- }
720
- async function optionalLocations(client, kind, file, position, root) {
721
- try {
722
- if (kind === "definition") return locationsFromResult(root, await client.definition(file, position));
723
- if (kind === "typeDefinition") return locationsFromResult(root, await client.typeDefinition(file, position));
724
- if (kind === "implementation") return locationsFromResult(root, await client.implementation(file, position));
725
- } catch {
726
- return [];
727
- }
728
- return [];
729
- }
730
- function diagnosticFinding(server, file, diagnostic) {
731
- const severity = diagnostic.severity === 1 ? "blocking" : "warning";
732
- return {
733
- severity,
734
- type: "diagnostic",
735
- code: diagnostic.code || "lsp_diagnostic",
736
- server: server.id || server.command,
737
- file,
738
- line: diagnostic.range && diagnostic.range.start ? diagnostic.range.start.line + 1 : null,
739
- message: diagnostic.message || "LSP diagnostic"
740
- };
741
- }
742
- function nearbyFileHints(root, files) {
743
- const manifests = /* @__PURE__ */ new Set();
744
- const tests = /* @__PURE__ */ new Set();
745
- const manifestNames = /* @__PURE__ */ new Set([
746
- "package.json",
747
- "pyproject.toml",
748
- "go.mod",
749
- "Cargo.toml",
750
- "pom.xml",
751
- "build.gradle",
752
- "build.gradle.kts"
753
- ]);
754
- for (const file of files || []) {
755
- let dir = import_node_path5.default.dirname(import_node_path5.default.join(root, file));
756
- while (dir.startsWith(root)) {
757
- for (const name of manifestNames) {
758
- const candidate = import_node_path5.default.join(dir, name);
759
- if (import_node_fs3.default.existsSync(candidate)) manifests.add(normalizeRel(import_node_path5.default.relative(root, candidate)));
760
- }
761
- if (dir === root) break;
762
- dir = import_node_path5.default.dirname(dir);
763
- }
764
- const parsed = import_node_path5.default.parse(file);
765
- const candidates = [
766
- import_node_path5.default.join(parsed.dir, `${parsed.name}.test${parsed.ext}`),
767
- import_node_path5.default.join(parsed.dir, `${parsed.name}.spec${parsed.ext}`),
768
- import_node_path5.default.join(parsed.dir, `${parsed.name}_test${parsed.ext}`),
769
- import_node_path5.default.join("test", file),
770
- import_node_path5.default.join("tests", file)
771
- ];
772
- for (const candidate of candidates) {
773
- if (import_node_fs3.default.existsSync(import_node_path5.default.join(root, candidate))) tests.add(normalizeRel(candidate));
774
- }
775
- }
776
- return {
777
- package_manifests: Array.from(manifests).slice(0, 20),
778
- likely_tests: Array.from(tests).slice(0, 30)
779
- };
780
- }
781
-
782
- // src/lsp/review/run-review.ts
783
- async function runReview(options = {}) {
784
- const args = {
785
- base: options.base || "main",
786
- head: options.head || "HEAD",
787
- config: options.config || "cadre/lsp.json"
788
- };
789
- const root = options.root || process.cwd();
790
- const clientPool = options.clientPool || null;
791
- const configPath = import_node_path6.default.resolve(root, args.config);
792
- if (!import_node_fs4.default.existsSync(configPath)) {
793
- return {
794
- available: false,
795
- reason: `No LSP config found at ${args.config}`,
796
- changedFiles: [],
797
- changedEntries: [],
798
- servers: [],
799
- findings: []
800
- };
801
- }
802
- const entries = changedEntries(root, args.base, args.head);
803
- const files = entries.map((entry) => entry.path);
804
- const config = asJsonObject(JSON.parse(import_node_fs4.default.readFileSync(configPath, "utf8")));
805
- const servers = Array.isArray(config.servers) ? config.servers.map((server) => asJsonObject(server)).map((server) => ({
806
- ...server,
807
- id: asOptionalString(server.id),
808
- command: asOptionalString(server.command) || "",
809
- args: asStringArray(server.args),
810
- extensions: asStringArray(server.extensions),
811
- filenames: asStringArray(server.filenames),
812
- languageIds: asJsonObject(server.languageIds),
813
- requestTimeoutMs: asNumber(server.requestTimeoutMs, DEFAULT_REQUEST_TIMEOUT_MS),
814
- startupTimeoutMs: asNumber(server.startupTimeoutMs, DEFAULT_STARTUP_TIMEOUT_MS),
815
- diagnosticsDelayMs: asNumber(server.diagnosticsDelayMs, 250)
816
- })) : [];
817
- const findings = [];
818
- const serverReports = [];
819
- const changedSet = /* @__PURE__ */ new Set();
820
- for (const entry of entries) {
821
- if (entry.path) changedSet.add(import_node_path6.default.resolve(root, entry.path));
822
- if (entry.oldPath) changedSet.add(import_node_path6.default.resolve(root, entry.oldPath));
823
- }
824
- for (const server of servers) {
825
- const serverEntries = entries.filter((entry) => {
826
- return serverFileMatch(entry.path, server) || (entry.oldPath ? serverFileMatch(entry.oldPath, server) : false);
827
- });
828
- if (serverEntries.length === 0) continue;
829
- const availability = commandAvailability(server.command);
830
- const serverReport = {
831
- id: server.id || server.command || "unknown",
832
- command: server.command || null,
833
- availability,
834
- files: serverEntries.map((entry) => ({
835
- path: entry.path,
836
- oldPath: entry.oldPath,
837
- status: entry.status,
838
- kind: entry.kind,
839
- exists: entry.exists
840
- })),
841
- candidates: [],
842
- skipped: false
843
- };
844
- serverReports.push(serverReport);
845
- const allCandidates = /* @__PURE__ */ new Map();
846
- for (const entry of serverEntries) {
847
- for (const candidate of changedSymbolCandidates(root, args.base, args.head, entry)) {
848
- const key = `${candidate.name}\0${candidate.changedFile}\0${candidate.oldPath || ""}`;
849
- allCandidates.set(key, candidate);
850
- }
851
- }
852
- serverReport.candidates = Array.from(allCandidates.values()).map((candidate) => ({
853
- name: candidate.name,
854
- changeType: candidate.changeType,
855
- status: candidate.status,
856
- changedFile: candidate.changedFile,
857
- oldPath: candidate.oldPath
858
- }));
859
- if (availability.state !== "available") {
860
- serverReport.skipped = true;
861
- serverReport.degraded = true;
862
- serverReport.fallback = "text_scan";
863
- findings.push(skipFinding(
864
- server,
865
- availability.state === "invalid" ? "server_invalid" : "server_missing",
866
- availability.message || `LSP server command ${server.command} is unavailable`,
867
- { availability }
868
- ));
869
- for (const candidate of allCandidates.values()) {
870
- if (candidate.changeType !== "removed") continue;
871
- const refs = scanTextReferences(root, candidate.name, changedSet, server);
872
- if (refs.length > 0) {
873
- findings.push(externalReferenceFinding(server, candidate, refs, "text"));
874
- }
875
- }
876
- continue;
877
- }
878
- let pooled = null;
879
- let client = null;
880
- try {
881
- pooled = clientPool ? await clientPool.get(root, server) : null;
882
- client = pooled ? pooled.client : new LspClient(root, server);
883
- if (!pooled) {
884
- const startupTimeoutMs = positiveInt(server.startupTimeoutMs, DEFAULT_STARTUP_TIMEOUT_MS);
885
- await withTimeout(
886
- client.start(),
887
- startupTimeoutMs,
888
- `${server.command} did not spawn within ${startupTimeoutMs}ms`
889
- );
890
- await withTimeout(
891
- client.initialize(),
892
- startupTimeoutMs,
893
- `${server.command} did not initialize within ${startupTimeoutMs}ms`
894
- );
895
- }
896
- serverReport.warm = Boolean(pooled);
897
- const openFiles = Array.from(new Set(
898
- serverEntries.filter((entry) => entry.exists).map((entry) => entry.path)
899
- ));
900
- for (const file of openFiles) client.open(file);
901
- await new Promise((resolve) => setTimeout(resolve, positiveInt(server.diagnosticsDelayMs, 250)));
902
- serverReport.diagnostics = [];
903
- serverReport.symbolEvidence = [];
904
- for (const file of openFiles) {
905
- for (const diagnostic of client.diagnostics(file)) {
906
- const item = {
907
- file,
908
- line: diagnostic.range && diagnostic.range.start ? diagnostic.range.start.line + 1 : null,
909
- severity: diagnostic.severity || null,
910
- code: diagnostic.code || null,
911
- message: diagnostic.message || ""
912
- };
913
- serverReport.diagnostics.push(item);
914
- if (diagnostic.severity === 1 || diagnostic.severity === 2) {
915
- findings.push(diagnosticFinding(server, file, diagnostic));
916
- }
917
- }
918
- }
919
- for (const file of openFiles) {
920
- const candidates = Array.from(allCandidates.values()).filter((candidate) => candidate.changedFile === file);
921
- if (candidates.length === 0) continue;
922
- const symbols = flattenSymbols(await client.documentSymbols(file));
923
- for (const candidate of candidates) {
924
- const symbol = symbols.find((item) => item.name === candidate.name);
925
- if (!symbol) {
926
- const refs2 = scanTextReferences(root, candidate.name, changedSet, server);
927
- if (refs2.length > 0) {
928
- findings.push(externalReferenceFinding(server, candidate, refs2, "text"));
929
- }
930
- continue;
931
- }
932
- const rawRefs = await client.references(file, symbol.selectionRange.start);
933
- const refs = Array.isArray(rawRefs) ? rawRefs : [];
934
- const definitions = await optionalLocations(client, "definition", file, symbol.selectionRange.start, root);
935
- const typeDefinitions = await optionalLocations(client, "typeDefinition", file, symbol.selectionRange.start, root);
936
- const implementations = await optionalLocations(client, "implementation", file, symbol.selectionRange.start, root);
937
- serverReport.symbolEvidence.push({
938
- symbol: candidate.name,
939
- file,
940
- definitions,
941
- typeDefinitions,
942
- implementations
943
- });
944
- const externalRefs = refs.map((ref) => lspRefToLocation(root, ref)).filter((ref) => ref !== null).filter((ref) => !changedSet.has(import_node_path6.default.resolve(ref.file))).filter((ref) => !isIgnoredFile(root, ref.relativeFile));
945
- if (externalRefs.length > 0) {
946
- findings.push(externalReferenceFinding(server, candidate, externalRefs, "lsp"));
947
- }
948
- }
949
- }
950
- for (const candidate of allCandidates.values()) {
951
- if (candidate.changeType !== "removed") continue;
952
- if (candidate.changedFile && import_node_fs4.default.existsSync(import_node_path6.default.join(root, candidate.changedFile))) continue;
953
- const refs = scanTextReferences(root, candidate.name, changedSet, server);
954
- if (refs.length > 0) {
955
- findings.push(externalReferenceFinding(server, candidate, refs, "text"));
956
- }
957
- }
958
- } catch (error) {
959
- serverReport.skipped = true;
960
- serverReport.degraded = true;
961
- serverReport.fallback = "text_scan";
962
- findings.push(skipFinding(server, "server_unavailable", `LSP scan skipped: ${errorMessage(error)}`));
963
- if (clientPool && pooled) await clientPool.drop(root, server);
964
- for (const candidate of allCandidates.values()) {
965
- if (candidate.changeType !== "removed") continue;
966
- const refs = scanTextReferences(root, candidate.name, changedSet, server);
967
- if (refs.length > 0) {
968
- findings.push(externalReferenceFinding(server, candidate, refs, "text"));
969
- }
970
- }
971
- } finally {
972
- if (!clientPool && client) await client.shutdown();
973
- }
974
- }
975
- return {
976
- available: true,
977
- base: args.base,
978
- head: args.head,
979
- config: args.config,
980
- degraded: serverReports.some((report) => report.degraded === true),
981
- fallback: serverReports.some((report) => report.fallback === "text_scan") ? "text_scan" : null,
982
- changedFiles: files,
983
- changedEntries: entries,
984
- fileHints: nearbyFileHints(root, files),
985
- servers: serverReports,
986
- findings
987
- };
988
- }
989
-
990
- // src/lsp/review/cli.ts
991
- function usage() {
992
- console.log(`Usage: node <cadre-lsp-review.js> [--base main] [--head HEAD] [--config cadre/lsp.json] [--json]
993
-
994
- Runs a best-effort LSP reference scan for changed/removed symbols. If no
995
- cadre/lsp.json exists, exits successfully with available=false.
996
-
997
- Example cadre/lsp.json:
998
- {
999
- "servers": [
1000
- {
1001
- "id": "typescript",
1002
- "command": "typescript-language-server",
1003
- "args": ["--stdio"],
1004
- "extensions": [".ts", ".tsx", ".js", ".jsx"]
1005
- },
1006
- {
1007
- "id": "python",
1008
- "command": "pyright-langserver",
1009
- "args": ["--stdio"],
1010
- "extensions": [".py", ".pyi"]
1011
- }
1012
- ]
1013
- }`);
1014
- }
1015
- function parseArgs(argv) {
1016
- const args = {
1017
- base: "main",
1018
- head: "HEAD",
1019
- config: "cadre/lsp.json",
1020
- json: false
1021
- };
1022
- for (let i = 2; i < argv.length; i += 1) {
1023
- const arg = argv[i];
1024
- if (arg === "--help" || arg === "-h") {
1025
- usage();
1026
- process.exit(0);
1027
- } else if (arg === "--json") {
1028
- args.json = true;
1029
- } else if (arg === "--base" || arg === "--head" || arg === "--config") {
1030
- const value = argv[++i];
1031
- if (!value) throw new Error(`${arg} requires a value`);
1032
- if (arg === "--base") args.base = value;
1033
- else if (arg === "--head") args.head = value;
1034
- else args.config = value;
1035
- } else {
1036
- throw new Error(`Unknown argument: ${arg}`);
1037
- }
1038
- }
1039
- return args;
1040
- }
1041
- async function runCli() {
1042
- const args = parseArgs(process.argv);
1043
- const result = await runReview({ ...args, root: process.cwd() });
1044
- if (args.json) {
1045
- console.log(JSON.stringify(result, null, 2));
1046
- } else if (!result.available) {
1047
- console.log(`LSP review helper unavailable: ${asOptionalString(result.reason) || "unknown reason"}`);
1048
- } else if (result.findings.length === 0) {
1049
- console.log("LSP review helper found no external reference risks.");
1050
- } else {
1051
- for (const finding of result.findings) {
1052
- console.log(JSON.stringify(finding));
1053
- }
1054
- }
1055
- }
1056
-
1057
- // src/cadre-lsp-review.ts
1058
- if (["cadre-lsp-review.js", "cadre-lsp-review.ts"].includes(import_node_path7.default.basename(process.argv[1] || ""))) {
1059
- runCli().catch((error) => {
1060
- console.error(errorMessage(error));
1061
- process.exit(1);
1062
- });
1063
- }
1064
-
1065
- // src/cadre-lsp-daemon.ts
1066
- var ClientPool = class {
1067
- clients;
1068
- maxClients;
1069
- idleEvictionMs;
1070
- constructor(options = {}) {
1071
- this.clients = /* @__PURE__ */ new Map();
1072
- this.maxClients = Math.max(1, Math.min(32, Number(options.maxClients || process.env.CADRE_LSP_MAX_CLIENTS || 8)));
1073
- this.idleEvictionMs = Math.max(3e4, Number(options.idleEvictionMs || process.env.CADRE_LSP_IDLE_EVICTION_MS || 10 * 60 * 1e3));
1074
- }
1075
- key(root, server) {
1076
- return JSON.stringify({
1077
- root,
1078
- id: server.id || null,
1079
- command: server.command,
1080
- args: server.args || []
1081
- });
1082
- }
1083
- async get(root, server) {
1084
- await this.evictIdle();
1085
- const key = this.key(root, server);
1086
- const existing = this.clients.get(key);
1087
- if (existing) {
1088
- existing.last_used_at = (/* @__PURE__ */ new Date()).toISOString();
1089
- existing.uses += 1;
1090
- return existing;
1091
- }
1092
- await this.evictOverflow(this.maxClients - 1);
1093
- const client = new LspClient(root, server);
1094
- await client.start();
1095
- await client.initialize();
1096
- const entry = {
1097
- key,
1098
- root,
1099
- server_id: server.id || server.command || "unknown",
1100
- command: server.command,
1101
- client,
1102
- started_at: (/* @__PURE__ */ new Date()).toISOString(),
1103
- last_used_at: (/* @__PURE__ */ new Date()).toISOString(),
1104
- uses: 1
1105
- };
1106
- this.clients.set(key, entry);
1107
- return entry;
1108
- }
1109
- async evictIdle(now = Date.now()) {
1110
- const stale = Array.from(this.clients.values()).filter((entry) => {
1111
- const lastUsed = Date.parse(entry.last_used_at);
1112
- return Number.isFinite(lastUsed) && now - lastUsed > this.idleEvictionMs;
1113
- });
1114
- for (const entry of stale) {
1115
- this.clients.delete(entry.key);
1116
- await entry.client.shutdown();
1117
- }
1118
- return stale.length;
1119
- }
1120
- async evictOverflow(maxRemaining) {
1121
- const entries = Array.from(this.clients.values()).sort((left, right) => Date.parse(left.last_used_at) - Date.parse(right.last_used_at));
1122
- let evicted = 0;
1123
- while (this.clients.size > maxRemaining && entries.length > 0) {
1124
- const entry = entries.shift();
1125
- if (!entry) break;
1126
- this.clients.delete(entry.key);
1127
- await entry.client.shutdown();
1128
- evicted += 1;
1129
- }
1130
- return evicted;
1131
- }
1132
- async drop(root, server) {
1133
- const key = this.key(root, server);
1134
- const existing = this.clients.get(key);
1135
- if (!existing) return false;
1136
- this.clients.delete(key);
1137
- await existing.client.shutdown();
1138
- return true;
1139
- }
1140
- status() {
1141
- return {
1142
- client_count: this.clients.size,
1143
- max_clients: this.maxClients,
1144
- idle_eviction_ms: this.idleEvictionMs,
1145
- servers: Array.from(this.clients.values()).map((entry) => ({
1146
- root: entry.root,
1147
- server_id: entry.server_id,
1148
- command: entry.command,
1149
- started_at: entry.started_at,
1150
- last_used_at: entry.last_used_at,
1151
- uses: entry.uses,
1152
- open_documents: entry.client.opened ? entry.client.opened.size : 0
1153
- }))
1154
- };
1155
- }
1156
- async shutdownAll() {
1157
- const entries = Array.from(this.clients.values());
1158
- this.clients.clear();
1159
- await Promise.all(entries.map((entry) => entry.client.shutdown()));
1160
- return entries.length;
1161
- }
1162
- };
1163
- var pool = new ClientPool();
1164
- function send(id, result, error = null) {
1165
- process.stdout.write(`${JSON.stringify({ id, result, error })}
1166
- `);
1167
- }
1168
- async function handleDaemonMessage(message) {
1169
- if (message.method === "status") {
1170
- const evicted_idle = await pool.evictIdle();
1171
- return { ok: true, evicted_idle, ...pool.status() };
1172
- }
1173
- if (message.method === "review") {
1174
- const params = asJsonObject(message.params);
1175
- return runReview({ ...params, clientPool: pool });
1176
- }
1177
- if (message.method === "shutdown") {
1178
- const stopped = await pool.shutdownAll();
1179
- setImmediate(() => process.exit(0));
1180
- return { ok: true, stopped };
1181
- }
1182
- throw new Error(`Unknown LSP daemon method: ${message.method}`);
1183
- }
1184
- function runLspDaemon() {
1185
- const rl = import_node_readline.default.createInterface({ input: process.stdin });
1186
- rl.on("line", async (line) => {
1187
- if (!line.trim()) return;
1188
- let message = null;
1189
- try {
1190
- message = asJsonObject(JSON.parse(line));
1191
- const result = await handleDaemonMessage(message);
1192
- send(message.id || null, result);
1193
- } catch (error) {
1194
- send(message && message.id ? message.id : null, null, {
1195
- message: errorMessage(error),
1196
- stack: error instanceof Error ? error.stack : void 0
1197
- });
1198
- }
1199
- });
1200
- process.on("SIGTERM", () => {
1201
- pool.shutdownAll().finally(() => process.exit(0));
1202
- });
1203
- }
1204
- if (["cadre-lsp-daemon.js", "cadre-lsp-daemon.ts"].includes(import_node_path8.default.basename(process.argv[1] || ""))) {
1205
- runLspDaemon();
1206
- }
1207
- // Annotate the CommonJS export names for ESM import in node:
1208
- 0 && (module.exports = {
1209
- ClientPool,
1210
- handleDaemonMessage,
1211
- runLspDaemon
1212
- });