@wrongstack/tools 0.310.1 → 0.313.1

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 (135) hide show
  1. package/dist/_shell-pick.d.ts +5 -10
  2. package/dist/audit.js +10 -4055
  3. package/dist/bash.js +9 -2332
  4. package/dist/batch-tool-use.js +2 -187
  5. package/dist/browser/index.js +25 -1339
  6. package/dist/builtin.js +69 -33985
  7. package/dist/chunk-2CTB3UK5.js +197 -0
  8. package/dist/chunk-2ME7ZWDD.js +1272 -0
  9. package/dist/chunk-2TFQDEPU.js +113 -0
  10. package/dist/chunk-2ZCJNKFE.js +315 -0
  11. package/dist/chunk-3PVYQFRQ.js +472 -0
  12. package/dist/chunk-3QMQBO5Z.js +89 -0
  13. package/dist/chunk-42AKKX7O.js +385 -0
  14. package/dist/chunk-42SKEETB.js +113 -0
  15. package/dist/chunk-4BHUSMNL.js +104 -0
  16. package/dist/chunk-4I4LWFOO.js +431 -0
  17. package/dist/chunk-553IQUMO.js +478 -0
  18. package/dist/chunk-55KF77OK.js +1944 -0
  19. package/dist/chunk-6HLZK37X.js +359 -0
  20. package/dist/chunk-6RNIFLG4.js +305 -0
  21. package/dist/chunk-A6BRWIXN.js +317 -0
  22. package/dist/chunk-AHHDWNXC.js +200 -0
  23. package/dist/chunk-B2CIOKWP.js +899 -0
  24. package/dist/chunk-BTSFTGIL.js +7 -0
  25. package/dist/chunk-D33S4RQG.js +222 -0
  26. package/dist/chunk-DIJKHSUO.js +134 -0
  27. package/dist/chunk-DPL47QGS.js +3515 -0
  28. package/dist/chunk-EMRGN4KM.js +170 -0
  29. package/dist/chunk-FGOABE4Z.js +955 -0
  30. package/dist/chunk-FW65TP4G.js +520 -0
  31. package/dist/chunk-GOIZNNOA.js +221 -0
  32. package/dist/chunk-H5MJUAA6.js +295 -0
  33. package/dist/chunk-H5OHH6F4.js +223 -0
  34. package/dist/chunk-HC5RM4WY.js +199 -0
  35. package/dist/chunk-HEQFMLZ7.js +190 -0
  36. package/dist/chunk-HFXSNKCV.js +196 -0
  37. package/dist/chunk-HXSBQ2SE.js +1723 -0
  38. package/dist/chunk-ILESNGNM.js +163 -0
  39. package/dist/chunk-INF5CGAO.js +137 -0
  40. package/dist/chunk-IWDFZ6XR.js +337 -0
  41. package/dist/chunk-IXMNTNW5.js +238 -0
  42. package/dist/chunk-J4SRJKBW.js +428 -0
  43. package/dist/chunk-J5SKD6LN.js +235 -0
  44. package/dist/chunk-JRJJX3L5.js +424 -0
  45. package/dist/chunk-KXNDHMUB.js +366 -0
  46. package/dist/chunk-LIJQMYYX.js +59 -0
  47. package/dist/chunk-MAN26PZ5.js +260 -0
  48. package/dist/chunk-MKRQMLZA.js +474 -0
  49. package/dist/chunk-NBDZMMG2.js +169 -0
  50. package/dist/chunk-NHA6BEIH.js +101 -0
  51. package/dist/chunk-OA6YJIWL.js +4412 -0
  52. package/dist/chunk-OZC255IC.js +2830 -0
  53. package/dist/chunk-PUR6WU2B.js +154 -0
  54. package/dist/chunk-Q5JPPCZC.js +12 -0
  55. package/dist/chunk-QBV725YG.js +128 -0
  56. package/dist/chunk-QHVW4AAM.js +892 -0
  57. package/dist/chunk-QNJ7AQ4B.js +1000 -0
  58. package/dist/chunk-RGISBZBD.js +231 -0
  59. package/dist/chunk-RJZQWEMS.js +84 -0
  60. package/dist/chunk-RP2ZA47V.js +15 -0
  61. package/dist/chunk-RXISBFR5.js +315 -0
  62. package/dist/chunk-S5CCLZL3.js +99 -0
  63. package/dist/chunk-TVTCSBJF.js +122 -0
  64. package/dist/chunk-U4D5S3VQ.js +21 -0
  65. package/dist/chunk-U4VAATKP.js +193 -0
  66. package/dist/chunk-UKU2ZX4C.js +203 -0
  67. package/dist/chunk-UNSKG6DC.js +159 -0
  68. package/dist/chunk-URFKEIHM.js +1091 -0
  69. package/dist/chunk-UTV7YAW7.js +178 -0
  70. package/dist/chunk-V43EQ6VR.js +68 -0
  71. package/dist/chunk-VB3MJGCV.js +610 -0
  72. package/dist/chunk-WHIIIREL.js +223 -0
  73. package/dist/chunk-XMIFYKUT.js +1371 -0
  74. package/dist/chunk-YF2RSV34.js +54 -0
  75. package/dist/chunk-Z6DAKQ3U.js +1 -0
  76. package/dist/chunk-ZIGAZFWE.js +522 -0
  77. package/dist/circuit-breaker.js +3 -191
  78. package/dist/codebase-index/index.js +84 -13688
  79. package/dist/codebase-index/parser-worker-script.js +8 -3995
  80. package/dist/codebase-index/project-server.js +60 -8548
  81. package/dist/codebase-index/worker.js +20 -8416
  82. package/dist/design.js +2 -299
  83. package/dist/diff.js +4 -256
  84. package/dist/document.js +4 -222
  85. package/dist/e2e.js +5 -476
  86. package/dist/edit.js +14 -10200
  87. package/dist/exec.js +16 -3131
  88. package/dist/fetch.js +8 -398
  89. package/dist/format.js +10 -3750
  90. package/dist/generic-parser-VUXDIAOZ.js +13 -0
  91. package/dist/git.js +4 -380
  92. package/dist/glob.js +6 -280
  93. package/dist/go-parser-6CA77WZ4.js +469 -0
  94. package/dist/grep.js +7 -604
  95. package/dist/index.js +318 -35423
  96. package/dist/install.js +10 -4091
  97. package/dist/json-parser-7YMDJSBJ.js +213 -0
  98. package/dist/json.js +4 -665
  99. package/dist/kanban.js +3 -2096
  100. package/dist/languages/index.js +23 -4664
  101. package/dist/legacy-bridge-7UKZT46G.js +18 -0
  102. package/dist/lint.js +10 -3706
  103. package/dist/logs.js +4 -287
  104. package/dist/memory.js +6 -215
  105. package/dist/mode.js +3 -99
  106. package/dist/outdated.js +4 -5170
  107. package/dist/pack.js +65 -33933
  108. package/dist/parser-dispatch-VPOFDO2U.js +14 -0
  109. package/dist/patch.js +13 -9935
  110. package/dist/plan.js +5 -3286
  111. package/dist/process-registry.js +8 -651
  112. package/dist/ps-slash.js +12 -1439
  113. package/dist/py-parser-GPM5VYRG.js +16 -0
  114. package/dist/read.js +13 -9816
  115. package/dist/replace.js +15 -10014
  116. package/dist/rs-parser-WVQ4KYCX.js +81 -0
  117. package/dist/scaffold.js +4 -253
  118. package/dist/search.js +5 -585
  119. package/dist/session-kanban.js +30 -972
  120. package/dist/skill.js +2 -215
  121. package/dist/task.js +5 -3410
  122. package/dist/test.js +10 -3773
  123. package/dist/todo.js +4 -2891
  124. package/dist/tool-help.js +3 -123
  125. package/dist/tool-search.js +3 -79
  126. package/dist/tool-tier.js +68 -34020
  127. package/dist/tool-use.js +2 -93
  128. package/dist/tree-sitter-parser-YCILHGZD.js +17 -0
  129. package/dist/tree.js +4 -288
  130. package/dist/ts-parser-YH4ZMWMH.js +232 -0
  131. package/dist/typecheck.js +10 -3753
  132. package/dist/win32.js +6 -60
  133. package/dist/write.js +14 -9882
  134. package/dist/yaml-parser-GFAOKV53.js +157 -0
  135. package/package.json +5 -5
package/dist/lint.js CHANGED
@@ -1,3710 +1,14 @@
1
- // src/_spawn-stream.ts
2
- import { spawn as spawn2 } from "node:child_process";
3
1
  import {
4
- emitProcessCompleted,
5
- emitProcessOutput,
6
- emitProcessStarted
7
- } from "@wrongstack/core/observability";
8
- import { buildChildEnv } from "@wrongstack/core/utils";
9
-
10
- // src/_output-spool.ts
11
- import { createWriteStream, mkdirSync } from "node:fs";
12
- import * as fsp from "node:fs/promises";
13
- import * as path from "node:path";
14
- import { wstackGlobalRoot } from "@wrongstack/core/utils";
15
- var SPOOL_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3;
16
- var SPOOL_WRITE_HWM_BYTES = 4 * 1024 * 1024;
17
- var sweepStarted = false;
18
- function toolOutputDir() {
19
- return path.join(wstackGlobalRoot(), "tool-output");
20
- }
21
- function sweepOldSpoolFiles(dir) {
22
- if (sweepStarted) return;
23
- sweepStarted = true;
24
- void (async () => {
25
- try {
26
- const now = Date.now();
27
- for (const name of await fsp.readdir(dir)) {
28
- if (!name.endsWith(".log")) continue;
29
- const p = path.join(dir, name);
30
- try {
31
- const st = await fsp.stat(p);
32
- if (now - st.mtimeMs > SPOOL_RETENTION_MS) await fsp.unlink(p);
33
- } catch {
34
- }
35
- }
36
- } catch {
37
- }
38
- })();
39
- }
40
- function spoolNote(info) {
41
- const dropped = info.droppedBytes > 0 ? `, ~${info.droppedBytes} bytes dropped under backpressure` : "";
42
- return `
43
- [output truncated \u2014 full ${info.bytes} bytes at ${info.path}${dropped}; read/grep that file selectively instead of re-running with more output]`;
44
- }
45
- function createOutputSpool(opts) {
46
- const threshold = opts.thresholdBytes ?? 32768;
47
- const safeTool = opts.tool.replace(/[^a-zA-Z0-9._-]+/g, "_").slice(0, 40) || "tool";
48
- let head = "";
49
- let headBytes = 0;
50
- let totalBytes = 0;
51
- let droppedBytes = 0;
52
- let stream = null;
53
- let filePath = null;
54
- let failed = false;
55
- let finalized = false;
56
- const open = () => {
57
- if (stream || failed) return;
58
- try {
59
- const dir = toolOutputDir();
60
- mkdirSync(dir, { recursive: true });
61
- sweepOldSpoolFiles(dir);
62
- const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
63
- const rand = Math.random().toString(36).slice(2, 6);
64
- filePath = path.join(dir, `${stamp}-${safeTool}-${rand}.log`);
65
- stream = createWriteStream(filePath, { flags: "w", encoding: "utf8" });
66
- stream.on("error", () => {
67
- failed = true;
68
- stream = null;
69
- filePath = null;
70
- });
71
- stream.write(head);
72
- } catch {
73
- failed = true;
74
- stream = null;
75
- filePath = null;
76
- }
77
- };
78
- return {
79
- write(text) {
80
- if (finalized || !text) return;
81
- const textBytes = Buffer.byteLength(text, "utf8");
82
- totalBytes += textBytes;
83
- if (!stream && !failed) {
84
- if (headBytes + textBytes <= threshold) {
85
- head += text;
86
- headBytes += textBytes;
87
- return;
88
- }
89
- head += text;
90
- open();
91
- head = "";
92
- return;
93
- }
94
- if (stream) {
95
- if (stream.writableLength > SPOOL_WRITE_HWM_BYTES) {
96
- droppedBytes += textBytes;
97
- return;
98
- }
99
- stream.write(text);
100
- }
101
- },
102
- finalize() {
103
- if (finalized) {
104
- return filePath ? { path: filePath, bytes: totalBytes, droppedBytes } : null;
105
- }
106
- finalized = true;
107
- head = "";
108
- if (!stream || !filePath) return null;
109
- try {
110
- stream.end();
111
- } catch {
112
- }
113
- return { path: filePath, bytes: totalBytes, droppedBytes };
114
- }
115
- };
116
- }
117
-
118
- // src/_win32-resolve.ts
119
- import * as fs from "node:fs";
120
- import * as path2 from "node:path";
121
- function resolveWin32Command(cmd) {
122
- if (process.platform !== "win32") return cmd;
123
- if (cmd.includes("/") || cmd.includes("\\") || path2.extname(cmd.replace(/\//g, "\\"))) {
124
- return cmd;
125
- }
126
- const pathext = (process.env["PATHEXT"] ?? ".COM;.EXE;.BAT;.CMD;.VBS;.JS;.WS;.MSC").toLowerCase().split(";");
127
- const pathDirs = (process.env["PATH"] ?? "").split(path2.delimiter);
128
- for (const dir of pathDirs) {
129
- const base = path2.join(dir, cmd);
130
- for (const ext of pathext) {
131
- const full = `${base}${ext}`;
132
- try {
133
- fs.accessSync(full, fs.constants.X_OK);
134
- return full;
135
- } catch {
136
- }
137
- }
138
- }
139
- return cmd;
140
- }
141
- var WIN32_SHELL_META = /[&|<>"%\r\n\0]/;
142
- function assertSafeWin32ShellArgs(args) {
143
- for (const arg of args) {
144
- if (typeof arg === "string" && WIN32_SHELL_META.test(arg)) {
145
- throw new Error(
146
- 'win32 cmd shim spawn: argument contains a shell metacharacter (one of & | < > " %, or a newline) that could enable command injection through the .cmd/.bat wrapper - refusing to run. Offending argument: ' + JSON.stringify(arg)
147
- );
148
- }
149
- }
150
- }
151
- function buildWin32CmdShimInvocation(command, args = []) {
152
- assertSafeWin32ShellArgs([command, ...args]);
153
- const line = ["call", quoteWin32CmdArg(command), ...args.map(quoteWin32CmdArg)].join(" ");
154
- return {
155
- command: process.env["COMSPEC"] ?? "cmd.exe",
156
- args: ["/d", "/c", line],
157
- windowsVerbatimArguments: true
158
- };
159
- }
160
- function quoteWin32CmdArg(arg) {
161
- return `"${arg}"`;
162
- }
163
-
164
- // src/process-registry.ts
165
- import { spawn } from "node:child_process";
166
- import * as os from "node:os";
167
-
168
- // src/circuit-breaker.ts
169
- var DEFAULT_MAX_CONSECUTIVE_FAILURES = 5;
170
- var DEFAULT_SLOW_CALL_THRESHOLD_MS = 18e4;
171
- var DEFAULT_MAX_SLOW_CALLS = 3;
172
- var DEFAULT_WINDOW_MS = 6e4;
173
- var DEFAULT_MAX_CALLS_PER_WINDOW = 30;
174
- var DEFAULT_COOLDOWN_MS = 3e4;
175
- var CircuitBreaker = class {
176
- maxConsecutiveFailures;
177
- slowCallThresholdMs;
178
- maxSlowCalls;
179
- windowMs;
180
- maxCallsPerWindow;
181
- cooldownMs;
182
- state = "closed";
183
- consecutiveFailures = 0;
184
- window = [];
185
- lastFailureAt = null;
186
- lastSlowAt = null;
187
- /** Timestamp when the breaker was opened (for cooldown calculation). */
188
- openedAt = null;
189
- /**
190
- * Master enable flag. When false the breaker is bypassed: `beforeCall`
191
- * always returns true and `afterCall` records nothing. The class itself
192
- * defaults to enabled (so the standalone unit tests exercise tripping); the
193
- * ProcessRegistry flips this off until the user opts in via `/settings`.
194
- */
195
- enabled = true;
196
- /**
197
- * Fired (best-effort) when the breaker transitions into the `open` state.
198
- * The registry uses this to arm its auto kill/reset countdown.
199
- */
200
- onTrip;
201
- /**
202
- * Fired (best-effort) when the breaker returns to `closed` after having been
203
- * open/half-open. The registry uses this to cancel a pending kill/reset.
204
- */
205
- onReset;
206
- constructor(config = {}) {
207
- this.maxConsecutiveFailures = config.maxConsecutiveFailures ?? DEFAULT_MAX_CONSECUTIVE_FAILURES;
208
- this.slowCallThresholdMs = config.slowCallThresholdMs ?? DEFAULT_SLOW_CALL_THRESHOLD_MS;
209
- this.maxSlowCalls = config.maxSlowCalls ?? DEFAULT_MAX_SLOW_CALLS;
210
- this.windowMs = config.windowMs ?? DEFAULT_WINDOW_MS;
211
- this.maxCallsPerWindow = config.maxCallsPerWindow ?? DEFAULT_MAX_CALLS_PER_WINDOW;
212
- this.cooldownMs = config.cooldownMs ?? DEFAULT_COOLDOWN_MS;
213
- }
214
- /** Toggle the master enable. Disabling resets to a clean `closed` state. */
215
- setEnabled(enabled) {
216
- if (this.enabled === enabled) return;
217
- this.enabled = enabled;
218
- if (!enabled) this._reset();
219
- }
220
- get isEnabled() {
221
- return this.enabled;
222
- }
223
- /**
224
- * Returns true if the circuit allows a new call to proceed.
225
- * When false, callers should abort the tool call and return a
226
- * circuit-breaker error instead of spawning a process.
227
- */
228
- get canProceed() {
229
- if (!this.enabled) return true;
230
- this._checkStateTransition();
231
- return this.state !== "open";
232
- }
233
- /**
234
- * Snapshot of the current breaker state for observability (`/kill`).
235
- */
236
- snapshot() {
237
- this._checkStateTransition();
238
- const now = Date.now();
239
- let cooldownRemaining = null;
240
- if (this.openedAt !== null && this.state === "open") {
241
- const elapsed = now - this.openedAt;
242
- cooldownRemaining = Math.max(0, this.cooldownMs - elapsed);
243
- }
244
- return {
245
- state: this.state,
246
- consecutiveFailures: this.consecutiveFailures,
247
- slowCallsInWindow: this.window.filter((c) => c.slow).length,
248
- callsInWindow: this.window.length,
249
- windowMs: this.windowMs,
250
- cooldownRemainingMs: cooldownRemaining,
251
- lastFailureAt: this.lastFailureAt,
252
- lastSlowAt: this.lastSlowAt
253
- };
254
- }
255
- /**
256
- * Call this BEFORE spawning a bash/exec process.
257
- * Returns true if the call is allowed; false if the breaker is open.
258
- * When false, callers MUST NOT spawn a process.
259
- *
260
- * @param bypass - If true, skip the circuit breaker check entirely.
261
- * Use for background/fire-and-forget processes that should
262
- * not affect breaker state.
263
- */
264
- beforeCall(bypass = false) {
265
- if (bypass || !this.enabled) return true;
266
- this._checkStateTransition();
267
- if (this.state === "open") return false;
268
- return true;
269
- }
270
- /**
271
- * Call this AFTER a bash/exec process finishes (success or failure).
272
- * `durationMs` is the wall-clock time the process ran.
273
- * `failed` is true when the process returned a non-zero exit code or
274
- * threw an exception before spawning.
275
- *
276
- * @param bypass - If true, do not update breaker state.
277
- * Use for background/fire-and-forget processes.
278
- */
279
- afterCall(durationMs, failed, bypass = false) {
280
- if (bypass || !this.enabled) return;
281
- const now = Date.now();
282
- if (this.state === "half-open") {
283
- if (failed) {
284
- this._trip();
285
- return;
286
- }
287
- this._reset();
288
- return;
289
- }
290
- this._pruneWindow(now);
291
- const slow = durationMs >= this.slowCallThresholdMs;
292
- this.window.push({ at: now, failed, slow });
293
- if (failed) {
294
- this.consecutiveFailures++;
295
- this.lastFailureAt = now;
296
- if (this.consecutiveFailures >= this.maxConsecutiveFailures) {
297
- this._trip();
298
- }
299
- return;
300
- }
301
- this.consecutiveFailures = 0;
302
- if (slow) {
303
- this.lastSlowAt = now;
304
- const slowCount = this.window.filter((c) => c.slow).length;
305
- if (slowCount >= this.maxSlowCalls) {
306
- this._trip();
307
- }
308
- }
309
- const callCount = this.window.length;
310
- if (callCount >= this.maxCallsPerWindow) {
311
- this._trip();
312
- }
313
- }
314
- /** Force the breaker open. Used by /kill force and Ctrl+C. */
315
- forceOpen() {
316
- this._trip();
317
- }
318
- /** Force a reset to closed. Used by tests and /kill reset. */
319
- forceReset() {
320
- this._reset();
321
- }
322
- _trip() {
323
- if (this.state === "open") return;
324
- this.state = "open";
325
- this.openedAt = Date.now();
326
- this.window = [];
327
- try {
328
- this.onTrip?.();
329
- } catch {
330
- }
331
- }
332
- _reset() {
333
- const wasRecovering = this.state !== "closed";
334
- this.state = "closed";
335
- this.consecutiveFailures = 0;
336
- this.window = [];
337
- this.openedAt = null;
338
- if (wasRecovering) {
339
- try {
340
- this.onReset?.();
341
- } catch {
342
- }
343
- }
344
- }
345
- /** Transition from open → half-open when cooldown elapses. */
346
- _checkStateTransition() {
347
- if (this.state !== "open" || this.openedAt === null) return;
348
- const elapsed = Date.now() - this.openedAt;
349
- if (elapsed >= this.cooldownMs) {
350
- this.state = "half-open";
351
- this.openedAt = null;
352
- }
353
- }
354
- _pruneWindow(now) {
355
- const cutoff = now - this.windowMs;
356
- this.window = this.window.filter((c) => c.at >= cutoff);
357
- }
358
- };
359
-
360
- // src/_redact-command.ts
361
- import { expectDefined } from "@wrongstack/core/utils";
362
- var SENSITIVE_FLAG_PATTERNS = [
363
- // --flag=value or --flag "value" (value captured up to next space or comma)
364
- /--(?:token|password|passwd|pwd|secret|api[-_]?key|api[-_]?secret|auth|credential|private[-_]?key|access[-_]?key|github[-_]?token|gh[-_]?token|bearer|jwt|oauth|pin|pincode|passphrase|access[-_]?token)(?:[=\s,][^\s]*)?/gi,
365
- // -t short flag (token): attached (-tVALUE), separated (-t VALUE), or -t=VALUE.
366
- // (?<![-\w]) anchors to a token start so we don't match the `-t` inside `--token`.
367
- // The value must be token-like (>= 8 chars) so ordinary combined flags such
368
- // as `tar -tf` / `ssh -tt` are not eaten. Global flag: EVERY occurrence is
369
- // redacted, not just the first.
370
- // NOTE: synced with @wrongstack/core observability/redact-command.ts.
371
- /(?<![-\w])-t(?:[=\s]+)?[^\s,-]{8,}/g,
372
- // -p|-password|-a (redis auth) short flags: attached + separated + =value.
373
- // Same token-start anchor; over-redaction is an accepted tradeoff for a
374
- // redaction function. Synced with core copy.
375
- /(?<![-\w])-(?:password|p|a)(?:[=\s]+)?[^\s,-]+/gi,
376
- // env var–style secrets: TOKEN=x, API_KEY=y, etc.
377
- /(?:TOKEN|API_KEY|API_SECRET|AUTH_TOKEN|GITHUB_TOKEN|GH_TOKEN|BEARER|JWT|OAUTH|CREDENTIAL|SECRET|PRIVATE_KEY|PASSWORD|PASSWD|PASSPHRASE)\s*[=:]\s*[^\s,]+/gi,
378
- // Generic high-entropy look: base64 strings >32 chars or hex strings >32 digits — but only
379
- // when preceded by a flag name (e.g. --github-token=EyJ...). Global flag so
380
- // every such flag in the command line is redacted, not just the first.
381
- /--\w*(?:token|key|secret|password|passwd|auth|credential)\w*[=\s,][A-Za-z0-9+/=]{32,}/g
382
- ];
383
- function redactCommand(cmd) {
384
- let result = cmd;
385
- for (const pattern of SENSITIVE_FLAG_PATTERNS) {
386
- result = result.replace(pattern, (match) => {
387
- const eq = match.indexOf("=");
388
- const sp = match.search(/\s/);
389
- const delim = eq !== -1 ? "=" : sp !== -1 ? match[sp] : null;
390
- if (delim !== null) {
391
- const flag = match.slice(0, match.indexOf(expectDefined(delim)) + 1);
392
- return `${flag}[REDACTED]`;
393
- }
394
- if (match.startsWith("--")) {
395
- return match;
396
- }
397
- return `${match.slice(0, 2)}[REDACTED]`;
398
- });
399
- }
400
- return result;
401
- }
402
-
403
- // src/process-registry.ts
404
- var DEFAULT_GRACE_MS = 2e3;
405
- var WIN32_TASKKILL_TIMEOUT_MS = 5e3;
406
- function killWin32Tree(pid, opts = {}) {
407
- try {
408
- const child = spawn("taskkill", ["/pid", String(pid), "/T", "/F"], {
409
- stdio: "ignore",
410
- windowsHide: true
411
- });
412
- let settled = false;
413
- let timeout;
414
- const settle = () => {
415
- if (settled) return;
416
- settled = true;
417
- if (timeout) clearTimeout(timeout);
418
- try {
419
- opts.onSettled?.();
420
- } catch {
421
- }
422
- };
423
- child.on("error", settle);
424
- child.on("close", settle);
425
- timeout = setTimeout(
426
- () => {
427
- try {
428
- child.kill();
429
- } catch {
430
- }
431
- settle();
432
- },
433
- Math.max(1, opts.timeoutMs ?? WIN32_TASKKILL_TIMEOUT_MS)
434
- );
435
- timeout.unref?.();
436
- child.unref();
437
- return true;
438
- } catch {
439
- return false;
440
- }
441
- }
442
- var ProcessRegistryImpl = class {
443
- processes = /* @__PURE__ */ new Map();
444
- breaker;
445
- /**
446
- * Auto kill/reset config. When the breaker trips and `autoKillResetMs > 0`,
447
- * a countdown is armed; on expiry all tracked processes are killed and the
448
- * breaker is reset to closed (forced recovery). Zero means manual recovery
449
- * only (`/kill reset`).
450
- */
451
- autoKillResetMs = 0;
452
- autoKillTimer = null;
453
- autoKillArmedAt = null;
454
- breakerCountdownListeners = [];
455
- constructor(breakerConfig) {
456
- this.breaker = new CircuitBreaker(breakerConfig);
457
- this.breaker.onTrip = () => this._armAutoKillReset();
458
- this.breaker.onReset = () => this._cancelAutoKillReset();
459
- this.breaker.setEnabled(false);
460
- }
461
- register(info) {
462
- this.processes.set(info.pid, {
463
- ...info,
464
- killed: false,
465
- protected: info.protected ?? false,
466
- background: info.background ?? false
467
- });
468
- }
469
- _isSafeSignalPid(pid) {
470
- return Number.isInteger(pid) && pid > 1 && pid !== process.pid && pid !== process.ppid;
471
- }
472
- _canSignalProcessGroup(p) {
473
- return os.platform() !== "win32" && p.processGroupLeader === true && this._isSafeSignalPid(p.pid) && p.child !== null && typeof p.child.pid === "number" && p.child.pid === p.pid;
474
- }
475
- _killChildDirect(p, signal) {
476
- try {
477
- if (p.child) {
478
- p.child.kill(signal);
479
- return;
480
- }
481
- if (this._isSafeSignalPid(p.pid)) process.kill(p.pid, signal);
482
- } catch {
483
- }
484
- }
485
- _killPosix(p, signal) {
486
- if (this._canSignalProcessGroup(p)) {
487
- try {
488
- process.kill(-p.pid, signal);
489
- return;
490
- } catch {
491
- }
492
- }
493
- this._killChildDirect(p, signal);
494
- }
495
- /** Unregister a process by PID. Called on 'close' / 'exit' events. */
496
- unregister(pid) {
497
- this.processes.delete(pid);
498
- }
499
- /** Get a single process by PID. */
500
- get(pid) {
501
- this._pruneStale(pid);
502
- return this.processes.get(pid);
503
- }
504
- /** Get all tracked processes. */
505
- list() {
506
- this._pruneAllStale();
507
- return Array.from(this.processes.values());
508
- }
509
- /** Get processes filtered by name (e.g. 'bash', 'exec'). */
510
- byName(name) {
511
- return this.list().filter((p) => p.name === name);
512
- }
513
- /** Get processes filtered by session. */
514
- bySession(sessionId) {
515
- return this.list().filter((p) => p.sessionId === sessionId);
516
- }
517
- /** Count of active (non-killed) processes. */
518
- get activeCount() {
519
- let n = 0;
520
- for (const p of this.processes.values()) {
521
- if (!p.killed) n++;
522
- }
523
- return n;
524
- }
525
- /** Count of active jobs explicitly launched in background mode. */
526
- get activeBackgroundCount() {
527
- let n = 0;
528
- for (const p of this.processes.values()) {
529
- if (p.background && !p.killed) n++;
530
- }
531
- return n;
532
- }
533
- /**
534
- * Combined stats for observability — used by /ps and the TUI status bar.
535
- */
536
- stats() {
537
- this._pruneAllStale();
538
- return {
539
- activeCount: this.activeCount,
540
- backgroundCount: this.activeBackgroundCount,
541
- totalCount: this.processes.size,
542
- breaker: this.breaker.snapshot()
543
- };
544
- }
545
- /**
546
- * Returns true if the circuit allows a new bash/exec call to proceed.
547
- * When false, callers MUST NOT spawn a process.
548
- */
549
- get canProceed() {
550
- return this.breaker.canProceed;
551
- }
552
- /**
553
- * Called before spawning a process. Returns true if allowed; false if
554
- * the circuit breaker is open.
555
- *
556
- * @param bypass - If true, skip circuit breaker check (for background processes).
557
- */
558
- beforeCall(bypass = false) {
559
- return this.breaker.beforeCall(bypass);
560
- }
561
- /**
562
- * Called after a process finishes. `durationMs` is wall-clock time;
563
- * `failed` is true for non-zero exit codes.
564
- *
565
- * @param bypass - If true, do not update circuit breaker state (for background processes).
566
- */
567
- afterCall(durationMs, failed, bypass = false) {
568
- this.breaker.afterCall(durationMs, failed, bypass);
569
- }
570
- /** Force-open the circuit breaker (Ctrl+C, /kill force). */
571
- forceBreakerOpen() {
572
- this.breaker.forceOpen();
573
- }
574
- /** Force-reset the circuit breaker to closed (/kill reset). */
575
- forceBreakerReset() {
576
- this.breaker.forceReset();
577
- }
578
- /**
579
- * Configure circuit-breaker protection at runtime. Called from `/settings`
580
- * (instant, all modes) and on TUI mount (applies persisted config).
581
- *
582
- * - `enabled` toggles whether the breaker gates `bash`/`exec`.
583
- * - `autoKillResetMs` arms the auto kill/reset countdown when the breaker
584
- * trips (0 = manual recovery only).
585
- *
586
- * Re-applies cleanly on every call: cancels a pending countdown when the
587
- * timeout is cleared or protection disabled, and re-arms if the breaker is
588
- * currently open under the new settings.
589
- */
590
- setBreakerConfig(cfg) {
591
- if (cfg.enabled !== void 0) this.breaker.setEnabled(cfg.enabled);
592
- if (cfg.autoKillResetMs !== void 0) this.autoKillResetMs = Math.max(0, cfg.autoKillResetMs);
593
- if (this.autoKillResetMs <= 0) {
594
- this._cancelAutoKillReset();
595
- return;
596
- }
597
- if (this.breaker.isEnabled && this.breaker.snapshot().state === "open") {
598
- this._armAutoKillReset();
599
- }
600
- }
601
- /**
602
- * Live countdown to the next auto kill/reset, or null when nothing is armed.
603
- * The TUI polls this on a 1s tick while armed so the statusline decrements.
604
- */
605
- getBreakerCountdown() {
606
- if (this.autoKillArmedAt === null || this.autoKillResetMs <= 0) return null;
607
- const elapsed = Date.now() - this.autoKillArmedAt;
608
- return {
609
- remainingMs: Math.max(0, this.autoKillResetMs - elapsed),
610
- totalMs: this.autoKillResetMs
611
- };
612
- }
613
- /**
614
- * Subscribe to countdown arm/cancel events. Returns an unsubscribe function.
615
- * Use {@link getBreakerCountdown} for the live ticking value between events.
616
- */
617
- onBreakerCountdownChange(listener) {
618
- this.breakerCountdownListeners.push(listener);
619
- return () => {
620
- this.breakerCountdownListeners = this.breakerCountdownListeners.filter((l) => l !== listener);
621
- };
622
- }
623
- _emitBreakerCountdown() {
624
- const snap = this.getBreakerCountdown();
625
- for (const l of this.breakerCountdownListeners) {
626
- try {
627
- l(snap);
628
- } catch {
629
- }
630
- }
631
- }
632
- /**
633
- * Arm the auto kill/reset countdown. Idempotent: re-arming resets the window
634
- * (a fresh trip after a failed half-open probe restarts the clock). No-op
635
- * when protection is off or no timeout is configured.
636
- */
637
- _armAutoKillReset() {
638
- if (this.autoKillResetMs <= 0 || !this.breaker.isEnabled) return;
639
- this._clearAutoKillTimer();
640
- this.autoKillArmedAt = Date.now();
641
- this.autoKillTimer = setTimeout(() => {
642
- this.autoKillTimer = null;
643
- this.autoKillArmedAt = null;
644
- this.killAll({ force: false, preserveBackground: true });
645
- this.breaker.forceReset();
646
- this._emitBreakerCountdown();
647
- }, this.autoKillResetMs);
648
- this.autoKillTimer.unref?.();
649
- this._emitBreakerCountdown();
650
- }
651
- _cancelAutoKillReset() {
652
- const wasArmed = this.autoKillArmedAt !== null;
653
- this._clearAutoKillTimer();
654
- if (wasArmed) {
655
- this.autoKillArmedAt = null;
656
- this._emitBreakerCountdown();
657
- }
658
- }
659
- _clearAutoKillTimer() {
660
- if (this.autoKillTimer !== null) {
661
- clearTimeout(this.autoKillTimer);
662
- this.autoKillTimer = null;
663
- }
664
- }
665
- /** Kill a single process by PID.
666
- *
667
- * On POSIX: sends SIGTERM to the *process group* (-pid) so that
668
- * runaway grandchild processes (`sleep 9999 & disown`) are also killed.
669
- * After `graceMs` a SIGKILL is sent if the process hasn't exited.
670
- *
671
- * On Windows: `child.kill()` maps to TerminateProcess — process groups
672
- * are not meaningfully supported. A second `force=true` call sends
673
- * SIGKILL (which maps to TerminateProcess again — the distinction is
674
- * in the exit code, not the signal).
675
- *
676
- * Returns true if the process was found and kill was attempted.
677
- */
678
- kill(pid, opts = {}) {
679
- this._pruneStale(pid);
680
- const p = this.processes.get(pid);
681
- if (!p) return false;
682
- if (p.killed && opts.force !== true) return true;
683
- if (p.protected && opts.includeProtected !== true) return false;
684
- if (opts.preserveBackground && p.background) return false;
685
- const { force = false, graceMs = DEFAULT_GRACE_MS } = opts;
686
- const isWin2 = os.platform() === "win32";
687
- if (isWin2) {
688
- const liveRealChild = p.child === null || p.child.exitCode === null && typeof p.child.pid === "number";
689
- const directFallback = () => {
690
- if (p.child && p.child.exitCode === null) {
691
- try {
692
- p.child.kill("SIGKILL");
693
- } catch {
694
- }
695
- }
696
- };
697
- if (liveRealChild && killWin32Tree(pid, {
698
- timeoutMs: Math.max(graceMs, WIN32_TASKKILL_TIMEOUT_MS),
699
- onSettled: directFallback
700
- })) {
701
- } else {
702
- this._killChildDirect(p, force ? "SIGKILL" : "SIGTERM");
703
- }
704
- p.killed = true;
705
- return true;
706
- }
707
- try {
708
- if (force) {
709
- this._killPosix(p, "SIGKILL");
710
- } else {
711
- this._killPosix(p, "SIGTERM");
712
- const timer = setTimeout(() => {
713
- if (this.processes.has(pid) && !p.child?.killed) {
714
- this._killPosix(p, "SIGKILL");
715
- }
716
- }, graceMs);
717
- timer.unref?.();
718
- }
719
- } catch {
720
- }
721
- p.killed = true;
722
- return true;
723
- }
724
- /**
725
- * Kill all tracked processes.
726
- * Returns the PIDs that were kill()ed.
727
- */
728
- killAll(opts = {}) {
729
- const pids = Array.from(this.processes.keys());
730
- const killed = [];
731
- const includeProtected = opts.includeProtected === true;
732
- for (const pid of pids) {
733
- const p = this.processes.get(pid);
734
- if (!p) continue;
735
- if (p.protected && !includeProtected) continue;
736
- if (opts.preserveBackground && p.background) continue;
737
- if (this.kill(pid, opts)) killed.push(pid);
738
- }
739
- return killed;
740
- }
741
- /**
742
- * Kill all processes for a specific session.
743
- * Returns the PIDs that were kill()ed.
744
- */
745
- killSession(sessionId, opts = {}) {
746
- const pids = this.bySession(sessionId).map((p) => p.pid);
747
- const killed = [];
748
- for (const pid of pids) {
749
- if (this.kill(pid, opts)) killed.push(pid);
750
- }
751
- return killed;
752
- }
753
- /**
754
- * Check whether a tracked process entry is stale — the child has exited
755
- * (exitCode !== null) AND it's been in the registry long enough that the
756
- * OS may have reused the PID for a new, unrelated process.
757
- *
758
- * P3 #24 (before-release.md): on POSIX, PIDs are reused after process
759
- * exit. If a tracked process exits but its 'close' event hasn't fired yet
760
- * (or was missed), the registry still holds the entry. A new process
761
- * gets the same PID, and PID-based lookups (get, kill, shouldBlockKill)
762
- * may incorrectly protect or target the wrong process.
763
- *
764
- * The 60s threshold is conservative — the OS typically waits much longer
765
- * before reusing a PID, but we want to clean up before that becomes a risk.
766
- */
767
- _isStaleEntry(entry) {
768
- if (entry.child === null) {
769
- if (Date.now() - entry.startedAt <= 6e4) return false;
770
- if (os.platform() === "win32") return false;
771
- try {
772
- process.kill(entry.pid, 0);
773
- return false;
774
- } catch (err) {
775
- return err.code !== "EPERM";
776
- }
777
- }
778
- return entry.child.exitCode !== null && Date.now() - entry.startedAt > 6e4;
779
- }
780
- /**
781
- * Remove a stale entry for a specific PID before any PID-based lookup.
782
- * This prevents PID reuse from causing the registry to act on a dead
783
- * process that has been replaced by a new one with the same PID.
784
- */
785
- _pruneStale(pid) {
786
- const entry = this.processes.get(pid);
787
- if (entry && this._isStaleEntry(entry)) {
788
- this.processes.delete(pid);
789
- }
790
- }
791
- /**
792
- * Remove every stale entry, not just one PID. `list()`/`stats()` — the
793
- * surfaces the TUI status bar and `/ps` poll — must prune too: a child
794
- * whose 'close' event never fires (e.g. Windows grandchildren holding stdio
795
- * open) would otherwise linger in the registry until someone looks up its
796
- * exact PID, and PID reuse meanwhile makes `get()`/`kill()` target the
797
- * wrong process. RAM-leak audit 2026-07-31, MEDIUM.
798
- */
799
- _pruneAllStale() {
800
- for (const [pid, entry] of this.processes) {
801
- if (this._isStaleEntry(entry)) this.processes.delete(pid);
802
- }
803
- }
804
- };
805
- var _registry;
806
- function getProcessRegistry() {
807
- if (!_registry) {
808
- _registry = new ProcessRegistryImpl();
809
- }
810
- return _registry;
811
- }
812
-
813
- // src/_spawn-stream.ts
814
- var isWin = process.platform === "win32";
815
- async function* spawnStream(opts) {
816
- const max = opts.maxBytes ?? 999999999;
817
- const flushAt = opts.flushBytes ?? 4 * 1024;
818
- const maxQueue = opts.maxQueueSize ?? 500;
819
- const maxQueueBytes = opts.maxQueueBytes ?? 1024 * 1024;
820
- let stdout = "";
821
- let stderr = "";
822
- let stdoutRetainedBytes = 0;
823
- let stderrRetainedBytes = 0;
824
- let pending = "";
825
- let error;
826
- const spool = createOutputSpool({ tool: opts.cmd, thresholdBytes: max });
827
- const resolved = resolveWin32Command(opts.cmd);
828
- const needsShell = isWin && (resolved.endsWith(".cmd") || resolved.endsWith(".bat"));
829
- const shim = needsShell ? buildWin32CmdShimInvocation(resolved, opts.args) : null;
830
- const cmd = shim?.command ?? resolved;
831
- const args = shim?.args ?? opts.args;
832
- const child = spawn2(cmd, args, {
833
- cwd: opts.cwd,
834
- env: buildChildEnv(),
835
- stdio: ["ignore", "pipe", "pipe"],
836
- windowsHide: true,
837
- ...isWin ? {} : { signal: opts.signal },
838
- ...shim ? { windowsVerbatimArguments: shim.windowsVerbatimArguments } : {}
839
- });
840
- const registry = getProcessRegistry();
841
- const pid = child.pid;
842
- const processStartedAt = Date.now();
843
- let stdoutBytes = 0;
844
- let stderrBytes = 0;
845
- let telemetryCompleted = false;
846
- emitProcessStarted({
847
- ...pid !== void 0 ? { pid } : {},
848
- parentPid: process.pid,
849
- command: redactCommand(`${opts.cmd} ${opts.args.join(" ")}`),
850
- args: redactCommand(opts.args.join(" ")).split(" ").filter(Boolean),
851
- cwd: opts.cwd,
852
- background: false,
853
- startedAt: new Date(processStartedAt).toISOString()
854
- });
855
- if (typeof pid === "number") {
856
- registry.register({
857
- pid,
858
- name: opts.cmd,
859
- command: redactCommand(`${opts.cmd} ${opts.args.join(" ")}`),
860
- startedAt: Date.now(),
861
- child
862
- });
863
- }
864
- const queue = [];
865
- let queuedBytes = 0;
866
- let waiter;
867
- let paused = false;
868
- const wake = () => {
869
- if (waiter) {
870
- const w = waiter;
871
- waiter = void 0;
872
- w();
873
- }
874
- };
875
- const resume = () => {
876
- if (paused && queue.length <= Math.floor(maxQueue / 2) && queuedBytes <= Math.floor(maxQueueBytes / 2)) {
877
- paused = false;
878
- child.stdout?.resume();
879
- child.stderr?.resume();
880
- }
881
- };
882
- const onOut = (c) => {
883
- const s = c.toString();
884
- stdoutBytes += c.byteLength;
885
- emitProcessOutput({ pid, stream: "stdout", chunk: c });
886
- if (stdoutRetainedBytes < max) {
887
- const retained = utf8Prefix(s, max - stdoutRetainedBytes);
888
- stdout += retained;
889
- stdoutRetainedBytes += Buffer.byteLength(retained, "utf8");
890
- }
891
- spool.write(s);
892
- queue.push({ kind: "out", data: s, bytes: c.byteLength });
893
- queuedBytes += c.byteLength;
894
- wake();
895
- if (!paused && (queue.length >= maxQueue || queuedBytes >= maxQueueBytes)) {
896
- paused = true;
897
- child.stdout?.pause();
898
- child.stderr?.pause();
899
- }
900
- };
901
- const onErr = (c) => {
902
- const s = c.toString();
903
- stderrBytes += c.byteLength;
904
- emitProcessOutput({ pid, stream: "stderr", chunk: c });
905
- if (stderrRetainedBytes < max) {
906
- const retained = utf8Prefix(s, max - stderrRetainedBytes);
907
- stderr += retained;
908
- stderrRetainedBytes += Buffer.byteLength(retained, "utf8");
909
- }
910
- spool.write(s);
911
- queue.push({ kind: "err", data: s, bytes: c.byteLength });
912
- queuedBytes += c.byteLength;
913
- wake();
914
- if (!paused && (queue.length >= maxQueue || queuedBytes >= maxQueueBytes)) {
915
- paused = true;
916
- child.stdout?.pause();
917
- child.stderr?.pause();
918
- }
919
- };
920
- child.stdout?.on("data", onOut);
921
- child.stderr?.on("data", onErr);
922
- child.on("error", (e) => {
923
- error = e.message;
924
- const bytes = Buffer.byteLength(e.message, "utf8");
925
- queue.push({ kind: "error", data: e.message, bytes });
926
- queuedBytes += bytes;
927
- wake();
928
- });
929
- const completeTelemetry = (code, signal, timedOut = false) => {
930
- if (telemetryCompleted) return;
931
- telemetryCompleted = true;
932
- emitProcessCompleted({
933
- ...pid !== void 0 ? { pid } : {},
934
- exitCode: code,
935
- ...signal ? { signal } : {},
936
- durationMs: Date.now() - processStartedAt,
937
- stdoutBytes,
938
- stderrBytes,
939
- timedOut,
940
- endedAt: (/* @__PURE__ */ new Date()).toISOString()
941
- });
942
- };
943
- child.on("close", (code, signal) => {
944
- if (typeof pid === "number") registry.unregister(pid);
945
- const exitCode2 = code ?? (signal ? 1 : 0);
946
- completeTelemetry(exitCode2, signal ?? void 0);
947
- queue.push({
948
- kind: "close",
949
- data: "",
950
- bytes: 0,
951
- code: exitCode2,
952
- ...signal ? { signal } : {}
953
- });
954
- wake();
955
- });
956
- const onAbort = () => {
957
- if (typeof pid === "number") {
958
- registry.kill(pid, { force: true });
959
- } else {
960
- try {
961
- child.kill("SIGKILL");
962
- } catch {
963
- }
964
- }
965
- queue.push({ kind: "close", data: "", bytes: 0, code: 124 });
966
- completeTelemetry(124, "SIGKILL", true);
967
- wake();
968
- };
969
- if (isWin) {
970
- if (opts.signal.aborted) onAbort();
971
- else opts.signal.addEventListener("abort", onAbort, { once: true });
972
- }
973
- let exitCode = 0;
974
- let spawnFailed = false;
975
- try {
976
- for (; ; ) {
977
- while (queue.length === 0) {
978
- await new Promise((resolve6) => {
979
- waiter = resolve6;
980
- });
981
- }
982
- const chunk = queue.shift();
983
- queuedBytes -= chunk.bytes;
984
- resume();
985
- if (chunk.kind === "close") {
986
- if (!spawnFailed) exitCode = chunk.code ?? 0;
987
- break;
988
- }
989
- if (chunk.kind === "error") {
990
- spawnFailed = true;
991
- exitCode = 1;
992
- continue;
993
- }
994
- pending += chunk.data;
995
- if (pending.length >= flushAt) {
996
- yield { type: "partial_output", text: pending };
997
- pending = "";
998
- }
999
- }
1000
- if (pending.length > 0) {
1001
- yield { type: "partial_output", text: pending };
1002
- }
1003
- const spooled = spool.finalize();
1004
- return {
1005
- // The marker rides on stdout's tail so every consumer's head+tail
1006
- // normalization keeps it without per-tool changes.
1007
- stdout: spooled ? stdout + spoolNote(spooled) : stdout,
1008
- stderr,
1009
- exitCode,
1010
- truncated: stdoutBytes > stdoutRetainedBytes || stderrBytes > stderrRetainedBytes,
1011
- error,
1012
- spoolPath: spooled?.path,
1013
- spoolBytes: spooled?.bytes
1014
- };
1015
- } finally {
1016
- spool.finalize();
1017
- if (isWin) opts.signal.removeEventListener("abort", onAbort);
1018
- child.stdout?.off("data", onOut);
1019
- child.stderr?.off("data", onErr);
1020
- child.stdout?.destroy();
1021
- child.stderr?.destroy();
1022
- if (child.exitCode === null && !child.killed) {
1023
- if (typeof pid === "number") {
1024
- registry.kill(pid, { force: true });
1025
- } else {
1026
- try {
1027
- child.kill("SIGKILL");
1028
- } catch {
1029
- }
1030
- }
1031
- }
1032
- }
1033
- }
1034
- function utf8Prefix(text, maxBytes) {
1035
- if (maxBytes <= 0) return "";
1036
- if (Buffer.byteLength(text, "utf8") <= maxBytes) return text;
1037
- let low = 0;
1038
- let high = text.length;
1039
- while (low < high) {
1040
- const mid = Math.ceil((low + high) / 2);
1041
- if (Buffer.byteLength(text.slice(0, mid), "utf8") <= maxBytes) low = mid;
1042
- else high = mid - 1;
1043
- }
1044
- let end = low;
1045
- if (end > 0 && /[\uD800-\uDBFF]/.test(text[end - 1])) end--;
1046
- return text.slice(0, end);
1047
- }
1048
-
1049
- // src/_util.ts
1050
- import * as fsp2 from "node:fs/promises";
1051
- import * as path3 from "node:path";
1052
- import * as Core from "@wrongstack/core/utils";
1053
- function resolvePath(input, ctx) {
1054
- return path3.isAbsolute(input) ? path3.normalize(input) : path3.resolve(ctx.workingDir ?? ctx.cwd, input);
1055
- }
1056
- function allowedRoots(ctx) {
1057
- return [path3.resolve(ctx.projectRoot), path3.resolve(Core.wstackGlobalRoot())];
1058
- }
1059
- function isInsideAny(target, roots) {
1060
- return roots.some((root) => {
1061
- const rel = path3.relative(root, target);
1062
- return rel === "" || !rel.startsWith("..") && !path3.isAbsolute(rel);
1063
- });
1064
- }
1065
- function ensureInsideRoot(absPath, ctx) {
1066
- const target = path3.resolve(absPath);
1067
- if (ctx.allowOutsideProjectRoot) return target;
1068
- if (isInsideAny(target, allowedRoots(ctx))) return target;
1069
- throw new Error(`Path "${absPath}" is outside project root "${path3.resolve(ctx.projectRoot)}"`);
1070
- }
1071
- function safeResolve(input, ctx) {
1072
- return ensureInsideRoot(resolvePath(input, ctx), ctx);
1073
- }
1074
- async function resolveRealInsideRoot(absPath, ctx) {
1075
- if (ctx.allowOutsideProjectRoot) return absPath;
1076
- const realRoots = await Promise.all(
1077
- allowedRoots(ctx).map((r) => fsp2.realpath(r).catch(() => path3.resolve(r)))
1078
- );
1079
- let probe = absPath;
1080
- const pendingTail = [];
1081
- for (; ; ) {
1082
- let real;
1083
- try {
1084
- real = await fsp2.realpath(probe);
1085
- } catch (err) {
1086
- if (err.code === "ENOENT") {
1087
- const parent = path3.dirname(probe);
1088
- if (parent === probe) return absPath;
1089
- pendingTail.unshift(path3.basename(probe));
1090
- probe = parent;
1091
- continue;
1092
- }
1093
- throw err;
1094
- }
1095
- const candidate = pendingTail.length > 0 ? path3.join(real, ...pendingTail) : real;
1096
- if (isInsideAny(candidate, realRoots)) {
1097
- return candidate;
1098
- }
1099
- throw new Error(
1100
- `Path "${absPath}" resolves through a symlink outside project root "${realRoots[0]}"`
1101
- );
1102
- }
1103
- }
1104
- async function safeResolveReal(input, ctx) {
1105
- const abs = safeResolve(input, ctx);
1106
- return await resolveRealInsideRoot(abs, ctx);
1107
- }
1108
- var COMMAND_OUTPUT_MAX_BYTES = 32768;
1109
- var REPEAT_RUN_THRESHOLD = 3;
1110
- function collapseCarriageReturns(text) {
1111
- const lf = text.replace(/\r\n/g, "\n");
1112
- if (!lf.includes("\r")) return lf;
1113
- return lf.split("\n").map((line) => line.includes("\r") ? line.slice(line.lastIndexOf("\r") + 1) : line).join("\n");
1114
- }
1115
- function collapseConsecutiveDuplicates(text, minRun = REPEAT_RUN_THRESHOLD) {
1116
- const lines = text.split("\n");
1117
- const out = [];
1118
- let i = 0;
1119
- while (i < lines.length) {
1120
- let j = i + 1;
1121
- while (j < lines.length && lines[j] === lines[i]) j++;
1122
- const run = j - i;
1123
- if (run >= minRun) {
1124
- out.push(lines[i], `\u2026 \u27E8repeated ${run}\xD7\u27E9`);
1125
- } else {
1126
- for (let k = i; k < j; k++) out.push(lines[k]);
1127
- }
1128
- i = j;
1129
- }
1130
- return out.join("\n");
1131
- }
1132
- function takeHeadBytes(s, maxBytes) {
1133
- if (maxBytes <= 0) return "";
1134
- if (Buffer.byteLength(s, "utf8") <= maxBytes) return s;
1135
- let lo = 0;
1136
- let hi = s.length;
1137
- while (lo < hi) {
1138
- const mid = Math.ceil((lo + hi) / 2);
1139
- if (Buffer.byteLength(s.slice(0, mid), "utf8") <= maxBytes) lo = mid;
1140
- else hi = mid - 1;
1141
- }
1142
- return s.slice(0, lo);
1143
- }
1144
- function takeTailBytes(s, maxBytes) {
1145
- if (maxBytes <= 0) return "";
1146
- if (Buffer.byteLength(s, "utf8") <= maxBytes) return s;
1147
- let lo = 0;
1148
- let hi = s.length;
1149
- while (lo < hi) {
1150
- const mid = Math.ceil((lo + hi) / 2);
1151
- if (Buffer.byteLength(s.slice(s.length - mid), "utf8") <= maxBytes) lo = mid;
1152
- else hi = mid - 1;
1153
- }
1154
- return s.slice(s.length - lo);
1155
- }
1156
- function truncateHeadTail(s, maxBytes) {
1157
- const total = Buffer.byteLength(s, "utf8");
1158
- if (total <= maxBytes) return s;
1159
- const MARKER_RESERVE = 64;
1160
- const avail = Math.max(0, maxBytes - MARKER_RESERVE);
1161
- const headBudget = Math.floor(avail * 0.45);
1162
- const head = takeHeadBytes(s, headBudget);
1163
- const tail = takeTailBytes(s, avail - Buffer.byteLength(head, "utf8"));
1164
- const kept = Buffer.byteLength(head, "utf8") + Buffer.byteLength(tail, "utf8");
1165
- return `${head}
1166
- \u2026[truncated ${total - kept} bytes]\u2026
1167
- ${tail}`;
1168
- }
1169
- function normalizeCommandOutput(raw, opts = {}) {
1170
- if (!raw) return raw;
1171
- let text = Core.stripAnsi(raw);
1172
- text = collapseCarriageReturns(text);
1173
- text = text.replace(/[ \t]+$/gm, "");
1174
- text = collapseConsecutiveDuplicates(text);
1175
- text = text.replace(/\n{3,}/g, "\n\n");
1176
- return truncateHeadTail(text, opts.maxBytes ?? COMMAND_OUTPUT_MAX_BYTES);
1177
- }
1178
-
1179
- // src/languages/legacy-bridge.ts
1180
- import * as fs5 from "node:fs/promises";
1181
- import * as path8 from "node:path";
1182
-
1183
- // src/languages/detect.ts
1184
- import { createHash } from "node:crypto";
1185
- import * as fs2 from "node:fs/promises";
1186
- import * as path4 from "node:path";
1187
-
1188
- // src/languages/profile-helpers.ts
1189
- var DEFAULT_TIMEOUT_MS = 12e4;
1190
- var DEFAULT_OUTPUT_LIMIT_BYTES = 2e5;
1191
- function processPlan(ctx, operation, command, args, options) {
1192
- return {
1193
- profileId: ctx.workspace.language,
1194
- workspaceId: ctx.workspace.id,
1195
- operation,
1196
- kind: "process",
1197
- command,
1198
- args: Object.freeze([...args]),
1199
- cwd: ctx.workspace.root,
1200
- env: Object.freeze({}),
1201
- timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
1202
- outputLimitBytes: DEFAULT_OUTPUT_LIMIT_BYTES,
1203
- mutating: options.mutating ?? false,
1204
- network: options.network ?? false,
1205
- executesProjectCode: options.executesProjectCode ?? false,
1206
- reason: options.reason,
1207
- evidence: ctx.workspace.evidence,
1208
- parser: options.parser
1209
- };
1210
- }
1211
- function internalPlan(ctx, operation, parser, reason) {
1212
- return {
1213
- profileId: ctx.workspace.language,
1214
- workspaceId: ctx.workspace.id,
1215
- operation,
1216
- kind: "internal",
1217
- command: null,
1218
- args: Object.freeze([]),
1219
- cwd: ctx.workspace.root,
1220
- env: Object.freeze({}),
1221
- timeoutMs: 5e3,
1222
- outputLimitBytes: 32768,
1223
- mutating: false,
1224
- network: false,
1225
- executesProjectCode: false,
1226
- reason,
1227
- evidence: ctx.workspace.evidence,
1228
- parser
1229
- };
1230
- }
1231
- function unavailable(ctx, operation, reason) {
1232
- return {
1233
- status: "unavailable",
1234
- profileId: ctx.workspace.language,
1235
- workspaceId: ctx.workspace.id,
1236
- operation,
1237
- reason
1238
- };
1239
- }
1240
- function packageNames(ctx) {
1241
- return ctx.options.packages ?? [];
1242
- }
1243
-
1244
- // src/languages/profiles/additional.ts
1245
- var IGNORES = Object.freeze([
1246
- ".git",
1247
- ".wrongstack",
1248
- "node_modules",
1249
- "vendor",
1250
- "dist",
1251
- "build",
1252
- "coverage"
1253
- ]);
1254
- function pythonProfile() {
1255
- return {
1256
- id: "python",
1257
- displayName: "Python",
1258
- extensions: Object.freeze([".py", ".pyi"]),
1259
- lspLanguageIds: Object.freeze(["python"]),
1260
- detectors: Object.freeze([
1261
- { kind: "config", filename: "pyproject.toml", weight: 90 },
1262
- { kind: "config", filename: "setup.py", weight: 70 },
1263
- { kind: "config", filename: "setup.cfg", weight: 60 },
1264
- { kind: "manifest", filename: "requirements.txt", weight: 55 },
1265
- { kind: "manifest", filename: "Pipfile", weight: 50 },
1266
- { kind: "lockfile", filename: "poetry.lock", weight: 30 },
1267
- { kind: "lockfile", filename: "Pipfile.lock", weight: 30 },
1268
- { kind: "lockfile", filename: "uv.lock", weight: 30 }
1269
- ]),
1270
- ignoredDirectories: IGNORES,
1271
- packageManagers: Object.freeze(["pip", "poetry", "pipenv", "uv"]),
1272
- executables: Object.freeze([
1273
- "python",
1274
- "python3",
1275
- "pip",
1276
- "pip3",
1277
- "poetry",
1278
- "pipenv",
1279
- "uv",
1280
- "ruff",
1281
- "black",
1282
- "pytest",
1283
- "mypy",
1284
- "pyright"
1285
- ]),
1286
- operations: Object.freeze({
1287
- syntax: async (ctx) => {
1288
- const py = ctx.options.target ? "python3" : "python3";
1289
- return ctx.options.target ? processPlan(ctx, "syntax", py, ["-m", "py_compile", ctx.options.target], {
1290
- parser: "python",
1291
- reason: "Compile the target file to check for syntax errors."
1292
- }) : unavailable(ctx, "syntax", "Python syntax check requires an explicit target file.");
1293
- },
1294
- semantic: async (ctx) => processPlan(ctx, "semantic", "mypy", [".", "--no-error-summary"], {
1295
- parser: "mypy",
1296
- reason: "Run mypy type checking on the workspace.",
1297
- executesProjectCode: true
1298
- }),
1299
- lint: async (ctx) => processPlan(ctx, "lint", "ruff", ["check", "."], {
1300
- parser: "ruff",
1301
- reason: "Run the Ruff linter on the workspace."
1302
- }),
1303
- "format-check": async (ctx) => processPlan(ctx, "format-check", "ruff", ["format", "--check", "."], {
1304
- parser: "ruff",
1305
- reason: "Check Python formatting without writing files."
1306
- }),
1307
- "format-write": async (ctx) => processPlan(ctx, "format-write", "ruff", ["format", "."], {
1308
- parser: "ruff",
1309
- reason: "Format Python source files.",
1310
- mutating: true
1311
- }),
1312
- test: async (ctx) => processPlan(
1313
- ctx,
1314
- "test",
1315
- "pytest",
1316
- [...ctx.options.filter ? ["-k", ctx.options.filter] : [], "."],
1317
- {
1318
- parser: "pytest",
1319
- reason: ctx.options.filter ? "Run filtered Python tests." : "Run all Python tests.",
1320
- mutating: true,
1321
- executesProjectCode: true
1322
- }
1323
- ),
1324
- build: async (ctx) => unavailable(ctx, "build", "Python is interpreted; use semantic or test instead."),
1325
- "debug-compile": async (ctx) => processPlan(ctx, "debug-compile", "mypy", [".", "--no-error-summary"], {
1326
- parser: "mypy",
1327
- reason: "Collect mypy type diagnostics.",
1328
- executesProjectCode: true
1329
- }),
1330
- "package-install": async (ctx) => processPlan(ctx, "package-install", "pip", ["install", "--no-cache-dir"], {
1331
- parser: "package-text",
1332
- reason: "Install dependencies from requirements.",
1333
- mutating: true,
1334
- network: true
1335
- }),
1336
- "package-add": async (ctx) => {
1337
- const names = packageNames(ctx);
1338
- return names.length === 0 ? unavailable(ctx, "package-add", "At least one package name is required.") : processPlan(ctx, "package-add", "pip", ["install", ...names], {
1339
- parser: "package-text",
1340
- reason: "Install specified Python packages.",
1341
- mutating: true,
1342
- network: true
1343
- });
1344
- },
1345
- "package-remove": async (ctx) => {
1346
- const names = packageNames(ctx);
1347
- return names.length === 0 ? unavailable(ctx, "package-remove", "At least one package name is required.") : processPlan(ctx, "package-remove", "pip", ["uninstall", "--yes", ...names], {
1348
- parser: "package-text",
1349
- reason: "Remove validated Python packages.",
1350
- mutating: true
1351
- });
1352
- },
1353
- "package-audit": async (ctx) => processPlan(ctx, "package-audit", "pip", ["audit"], {
1354
- parser: "pip-audit",
1355
- reason: "Audit Python dependencies for vulnerabilities.",
1356
- network: true
1357
- }),
1358
- run: async (ctx) => {
1359
- const entries = ["main.py", "app.py", "__main__.py", "manage.py"];
1360
- const first = (await Promise.all(
1361
- entries.map((name) => ctx.pathExists(name).then((ok) => ok ? name : void 0))
1362
- )).find(Boolean);
1363
- const args = first ? [first] : [];
1364
- return processPlan(ctx, "run", "python3", args, {
1365
- parser: "command-text",
1366
- reason: first ? `Run the Python entry point ${first}.` : "Run the Python project (no common entry point detected \u2014 add the module path manually).",
1367
- executesProjectCode: true,
1368
- mutating: true
1369
- });
1370
- }
1371
- })
1372
- };
1373
- }
1374
- function hasGradleEvidence(ctx) {
1375
- return ctx.workspace.evidence.some(
1376
- (e) => e.kind === "manifest" && (e.value === "build.gradle" || e.value === "build.gradle.kts" || e.value === "settings.gradle") || e.kind === "lockfile" && e.value === "gradle.lockfile"
1377
- );
1378
- }
1379
- async function gradleRunner(ctx) {
1380
- if (await ctx.pathExists("gradlew")) return "gradlew";
1381
- return "gradle";
1382
- }
1383
- function javaProfile() {
1384
- return {
1385
- id: "java",
1386
- displayName: "Java / Kotlin",
1387
- extensions: Object.freeze([".java", ".kt", ".kts", ".scala"]),
1388
- lspLanguageIds: Object.freeze(["java", "kotlin"]),
1389
- detectors: Object.freeze([
1390
- { kind: "manifest", filename: "pom.xml", weight: 90 },
1391
- { kind: "manifest", filename: "build.gradle", weight: 85 },
1392
- { kind: "manifest", filename: "build.gradle.kts", weight: 85 },
1393
- { kind: "manifest", filename: "settings.gradle", weight: 50 },
1394
- { kind: "lockfile", filename: "gradle.lockfile", weight: 30 }
1395
- ]),
1396
- ignoredDirectories: IGNORES,
1397
- packageManagers: Object.freeze(["maven", "gradle"]),
1398
- executables: Object.freeze(["mvn", "gradle", "gradlew", "java", "kotlinc"]),
1399
- operations: Object.freeze({
1400
- semantic: async (ctx) => {
1401
- const isGradle = hasGradleEvidence(ctx);
1402
- const runner = isGradle ? await gradleRunner(ctx) : "mvn";
1403
- const args = isGradle ? ["compileJava"] : ["compile", "-q"];
1404
- const reason = isGradle ? "Compile the Gradle project." : "Compile the Maven project.";
1405
- return processPlan(ctx, "semantic", runner, args, {
1406
- parser: isGradle ? "gradle" : "maven",
1407
- reason,
1408
- mutating: true,
1409
- executesProjectCode: true
1410
- });
1411
- },
1412
- lint: async (ctx) => unavailable(
1413
- ctx,
1414
- "lint",
1415
- "Java linting requires a configured checkstyle or spotbugs plugin."
1416
- ),
1417
- "format-check": async (ctx) => unavailable(
1418
- ctx,
1419
- "format-check",
1420
- "Java formatting check requires a configured spotless or google-java-format plugin."
1421
- ),
1422
- test: async (ctx) => {
1423
- const isGradle = hasGradleEvidence(ctx);
1424
- const runner = isGradle ? await gradleRunner(ctx) : "mvn";
1425
- const args = isGradle ? ["test"] : ["test", "-q"];
1426
- const reason = isGradle ? "Run Gradle tests." : "Run Maven tests.";
1427
- return processPlan(ctx, "test", runner, args, {
1428
- parser: isGradle ? "gradle" : "maven",
1429
- reason,
1430
- mutating: true,
1431
- executesProjectCode: true
1432
- });
1433
- },
1434
- build: async (ctx) => {
1435
- const isGradle = hasGradleEvidence(ctx);
1436
- const runner = isGradle ? await gradleRunner(ctx) : "mvn";
1437
- const args = isGradle ? ["build"] : ["package", "-q", "-DskipTests"];
1438
- const reason = isGradle ? "Build the Gradle project." : "Build the Maven project, skipping tests.";
1439
- return processPlan(ctx, "build", runner, args, {
1440
- parser: isGradle ? "gradle" : "maven",
1441
- reason,
1442
- mutating: true,
1443
- executesProjectCode: true
1444
- });
1445
- },
1446
- run: async (ctx) => {
1447
- if (!hasGradleEvidence(ctx))
1448
- return unavailable(
1449
- ctx,
1450
- "run",
1451
- "Maven run requires exec-maven-plugin configuration. Use `mvn exec:java -q` manually."
1452
- );
1453
- const runner = await gradleRunner(ctx);
1454
- return processPlan(ctx, "run", runner, ["run"], {
1455
- parser: "command-text",
1456
- reason: `Run the Gradle project entry point via ${runner}.`,
1457
- executesProjectCode: true,
1458
- mutating: true
1459
- });
1460
- },
1461
- "package-install": async (ctx) => unavailable(
1462
- ctx,
1463
- "package-install",
1464
- "JVM dependency installation happens through build or dependency:get."
1465
- ),
1466
- "package-add": async (ctx) => {
1467
- const names = packageNames(ctx);
1468
- return names.length === 0 ? unavailable(ctx, "package-add", "At least one dependency coordinate is required.") : processPlan(ctx, "package-add", "mvn", ["dependency:get", `-Dartifact=${names[0]}`], {
1469
- parser: "maven",
1470
- reason: "Resolve and fetch a Maven dependency.",
1471
- mutating: true,
1472
- network: true
1473
- });
1474
- }
1475
- })
1476
- };
1477
- }
1478
- function rubyProfile() {
1479
- return {
1480
- id: "ruby",
1481
- displayName: "Ruby",
1482
- extensions: Object.freeze([".rb"]),
1483
- lspLanguageIds: Object.freeze(["ruby"]),
1484
- detectors: Object.freeze([
1485
- { kind: "manifest", filename: "Gemfile", weight: 90 },
1486
- { kind: "config", filename: ".ruby-version", weight: 40 },
1487
- { kind: "lockfile", filename: "Gemfile.lock", weight: 30 }
1488
- ]),
1489
- ignoredDirectories: IGNORES,
1490
- packageManagers: Object.freeze(["gem", "bundler"]),
1491
- executables: Object.freeze(["ruby", "gem", "bundle", "rubocop", "rspec"]),
1492
- operations: Object.freeze({
1493
- syntax: async (ctx) => ctx.options.target ? processPlan(ctx, "syntax", "ruby", ["-c", ctx.options.target], {
1494
- parser: "ruby",
1495
- reason: "Check the target Ruby file for syntax errors."
1496
- }) : unavailable(ctx, "syntax", "Ruby syntax check requires an explicit target file."),
1497
- lint: async (ctx) => processPlan(ctx, "lint", "rubocop", ["--format=json"], {
1498
- parser: "rubocop",
1499
- reason: "Run RuboCop linter.",
1500
- executesProjectCode: true
1501
- }),
1502
- "format-write": async (ctx) => processPlan(ctx, "format-write", "rubocop", ["--auto-correct"], {
1503
- parser: "rubocop",
1504
- reason: "Auto-correct RuboCop violations.",
1505
- mutating: true,
1506
- executesProjectCode: true
1507
- }),
1508
- test: async (ctx) => processPlan(ctx, "test", "rspec", [], {
1509
- parser: "rspec",
1510
- reason: "Run the RSpec test suite.",
1511
- mutating: true,
1512
- executesProjectCode: true
1513
- }),
1514
- "package-install": async (ctx) => processPlan(ctx, "package-install", "bundle", ["install"], {
1515
- parser: "package-text",
1516
- reason: "Install Ruby gem dependencies.",
1517
- mutating: true,
1518
- network: true,
1519
- executesProjectCode: true
1520
- }),
1521
- "package-add": async (ctx) => {
1522
- const names = packageNames(ctx);
1523
- return names.length === 0 ? unavailable(ctx, "package-add", "At least one gem name is required.") : processPlan(ctx, "package-add", "gem", ["install", ...names], {
1524
- parser: "package-text",
1525
- reason: "Install specified Ruby gems.",
1526
- mutating: true,
1527
- network: true
1528
- });
1529
- },
1530
- "package-audit": async (ctx) => processPlan(ctx, "package-audit", "bundle", ["audit", "--format=json"], {
1531
- parser: "bundler-audit",
1532
- reason: "Audit Ruby gems for vulnerabilities.",
1533
- network: true
1534
- }),
1535
- run: async (ctx) => {
1536
- const entries = ["main.rb", "app.rb", "server.rb", "config.ru"];
1537
- const first = (await Promise.all(
1538
- entries.map((name) => ctx.pathExists(name).then((ok) => ok ? name : void 0))
1539
- )).find(Boolean);
1540
- const hasGemfile = await ctx.pathExists("Gemfile");
1541
- const cmd = hasGemfile ? "bundle" : "ruby";
1542
- const args = hasGemfile ? ["exec", "ruby", first ?? ""] : [first ?? ""];
1543
- return processPlan(ctx, "run", cmd, args, {
1544
- parser: "command-text",
1545
- reason: first ? `Run the Ruby entry point ${first}.` : "Run the Ruby project (no common entry point detected \u2014 add the file path manually).",
1546
- executesProjectCode: true,
1547
- mutating: true
1548
- });
1549
- }
1550
- })
1551
- };
1552
- }
1553
- function cProfile() {
1554
- return {
1555
- id: "c",
1556
- displayName: "C / C++",
1557
- extensions: Object.freeze([".c", ".h"]),
1558
- lspLanguageIds: Object.freeze(["c"]),
1559
- detectors: Object.freeze([
1560
- { kind: "manifest", filename: "CMakeLists.txt", weight: 85 },
1561
- { kind: "manifest", filename: "Makefile", weight: 60 },
1562
- { kind: "config", suffix: ".cmake", weight: 50 }
1563
- ]),
1564
- ignoredDirectories: IGNORES,
1565
- packageManagers: Object.freeze([]),
1566
- executables: Object.freeze(["cc", "gcc", "clang", "cmake", "make"]),
1567
- operations: Object.freeze({
1568
- semantic: async (ctx) => processPlan(ctx, "semantic", "cmake", ["--build", ".", "--target", "all"], {
1569
- parser: "cmake",
1570
- reason: "Build C project to collect compiler diagnostics.",
1571
- mutating: true,
1572
- executesProjectCode: true
1573
- }),
1574
- test: async (ctx) => unavailable(
1575
- ctx,
1576
- "test",
1577
- "C test execution requires a configured test runner (ctest, etc.)."
1578
- ),
1579
- build: async (ctx) => processPlan(ctx, "build", "cmake", ["--build", "."], {
1580
- parser: "cmake",
1581
- reason: "Build the C project.",
1582
- mutating: true,
1583
- executesProjectCode: true
1584
- })
1585
- })
1586
- };
1587
- }
1588
- function cppProfile() {
1589
- return {
1590
- ...cProfile(),
1591
- id: "cpp",
1592
- displayName: "C++",
1593
- extensions: Object.freeze([".cpp", ".cc", ".cxx", ".hpp", ".hxx"]),
1594
- lspLanguageIds: Object.freeze(["cpp"]),
1595
- detectors: Object.freeze([
1596
- { kind: "manifest", filename: "CMakeLists.txt", weight: 85 },
1597
- { kind: "manifest", filename: "Makefile", weight: 50 }
1598
- ]),
1599
- executables: Object.freeze(["c++", "g++", "clang++", "cmake", "make"])
1600
- };
1601
- }
1602
- function swiftProfile() {
1603
- return {
1604
- id: "swift",
1605
- displayName: "Swift",
1606
- extensions: Object.freeze([".swift"]),
1607
- lspLanguageIds: Object.freeze(["swift"]),
1608
- detectors: Object.freeze([{ kind: "manifest", filename: "Package.swift", weight: 90 }]),
1609
- ignoredDirectories: IGNORES,
1610
- packageManagers: Object.freeze(["swift"]),
1611
- executables: Object.freeze(["swift", "swiftc"]),
1612
- operations: Object.freeze({
1613
- semantic: async (ctx) => processPlan(ctx, "semantic", "swift", ["build"], {
1614
- parser: "swift",
1615
- reason: "Build Swift package to collect compiler diagnostics.",
1616
- mutating: true,
1617
- executesProjectCode: true
1618
- }),
1619
- test: async (ctx) => processPlan(ctx, "test", "swift", ["test"], {
1620
- parser: "swift-test",
1621
- reason: "Run Swift tests.",
1622
- mutating: true,
1623
- executesProjectCode: true
1624
- }),
1625
- build: async (ctx) => processPlan(ctx, "build", "swift", ["build", "-c", "release"], {
1626
- parser: "swift",
1627
- reason: "Build the Swift package in release mode.",
1628
- mutating: true,
1629
- executesProjectCode: true
1630
- }),
1631
- run: async (ctx) => processPlan(ctx, "run", "swift", ["run"], {
1632
- parser: "command-text",
1633
- reason: "Run the Swift package entry point.",
1634
- executesProjectCode: true
1635
- })
1636
- })
1637
- };
1638
- }
1639
- function dartProfile() {
1640
- return {
1641
- id: "dart",
1642
- displayName: "Dart / Flutter",
1643
- extensions: Object.freeze([".dart"]),
1644
- lspLanguageIds: Object.freeze(["dart"]),
1645
- detectors: Object.freeze([
1646
- { kind: "manifest", filename: "pubspec.yaml", weight: 90 },
1647
- { kind: "lockfile", filename: "pubspec.lock", weight: 30 }
1648
- ]),
1649
- ignoredDirectories: IGNORES,
1650
- packageManagers: Object.freeze(["pub"]),
1651
- executables: Object.freeze(["dart", "flutter"]),
1652
- operations: Object.freeze({
1653
- semantic: async (ctx) => processPlan(ctx, "semantic", "dart", ["analyze"], {
1654
- parser: "dart-analyze",
1655
- reason: "Run Dart static analysis."
1656
- }),
1657
- "format-check": async (ctx) => processPlan(
1658
- ctx,
1659
- "format-check",
1660
- "dart",
1661
- ["format", "--output=none", "--set-exit-if-changed", "."],
1662
- {
1663
- parser: "dart-format",
1664
- reason: "Check Dart formatting without writing files."
1665
- }
1666
- ),
1667
- "format-write": async (ctx) => processPlan(ctx, "format-write", "dart", ["format", "."], {
1668
- parser: "dart-format",
1669
- reason: "Format Dart source files.",
1670
- mutating: true
1671
- }),
1672
- test: async (ctx) => processPlan(ctx, "test", "dart", ["test"], {
1673
- parser: "dart-test",
1674
- reason: "Run Dart tests.",
1675
- mutating: true,
1676
- executesProjectCode: true
1677
- }),
1678
- "package-install": async (ctx) => processPlan(ctx, "package-install", "dart", ["pub", "get"], {
1679
- parser: "package-text",
1680
- reason: "Fetch Dart package dependencies.",
1681
- mutating: true,
1682
- network: true
1683
- }),
1684
- "package-outdated": async (ctx) => processPlan(ctx, "package-outdated", "dart", ["pub", "outdated"], {
1685
- parser: "dart-outdated",
1686
- reason: "Check for outdated Dart packages.",
1687
- network: true
1688
- }),
1689
- run: async (ctx) => processPlan(ctx, "run", "dart", ["run"], {
1690
- parser: "command-text",
1691
- reason: "Run the Dart / Flutter project entry point.",
1692
- executesProjectCode: true
1693
- })
1694
- })
1695
- };
1696
- }
1697
- function denoProfile() {
1698
- return {
1699
- id: "deno",
1700
- displayName: "Deno",
1701
- extensions: Object.freeze([".ts", ".tsx", ".js", ".jsx"]),
1702
- lspLanguageIds: Object.freeze(["typescript", "javascript"]),
1703
- detectors: Object.freeze([
1704
- { kind: "config", filename: "deno.json", weight: 90 },
1705
- { kind: "config", filename: "deno.jsonc", weight: 90 },
1706
- { kind: "config", filename: "import_map.json", weight: 60 }
1707
- ]),
1708
- ignoredDirectories: IGNORES,
1709
- packageManagers: Object.freeze([]),
1710
- executables: Object.freeze(["deno"]),
1711
- // .ts/.js extensions are shared with the TypeScript/JavaScript profiles;
1712
- // only a deno.json(c)/import_map.json detector hit may establish a workspace.
1713
- sourceFallback: false,
1714
- operations: Object.freeze({
1715
- test: async (ctx) => processPlan(ctx, "test", "deno", ["test"], {
1716
- parser: "deno-test",
1717
- reason: "Run Deno tests.",
1718
- mutating: true,
1719
- executesProjectCode: true
1720
- }),
1721
- run: async (ctx) => processPlan(ctx, "run", "deno", ["run", "--allow-all", "main.ts"], {
1722
- parser: "command-text",
1723
- reason: "Run the Deno project entry point with full permission.",
1724
- executesProjectCode: true,
1725
- mutating: true
1726
- })
1727
- })
1728
- };
1729
- }
1730
- function elixirProfile() {
1731
- return {
1732
- id: "elixir",
1733
- displayName: "Elixir",
1734
- extensions: Object.freeze([".ex", ".exs"]),
1735
- lspLanguageIds: Object.freeze(["elixir"]),
1736
- detectors: Object.freeze([
1737
- { kind: "manifest", filename: "mix.exs", weight: 90 },
1738
- { kind: "lockfile", filename: "mix.lock", weight: 30 }
1739
- ]),
1740
- ignoredDirectories: IGNORES,
1741
- packageManagers: Object.freeze(["mix"]),
1742
- executables: Object.freeze(["mix", "elixir"]),
1743
- operations: Object.freeze({
1744
- semantic: async (ctx) => unavailable(ctx, "semantic", "Elixir compilation is handled by the build operation."),
1745
- lint: async (ctx) => unavailable(ctx, "lint", "Elixir linting requires the credo package."),
1746
- test: async (ctx) => processPlan(ctx, "test", "mix", ["test"], {
1747
- parser: "mix-test",
1748
- reason: "Run ExUnit tests.",
1749
- mutating: true,
1750
- executesProjectCode: true
1751
- }),
1752
- build: async (ctx) => processPlan(ctx, "build", "mix", ["compile"], {
1753
- parser: "mix",
1754
- reason: "Compile the Mix project.",
1755
- mutating: true,
1756
- executesProjectCode: true
1757
- }),
1758
- run: async (ctx) => processPlan(ctx, "run", "mix", ["run"], {
1759
- parser: "command-text",
1760
- reason: "Run the Mix project entry point.",
1761
- executesProjectCode: true
1762
- }),
1763
- "package-install": async (ctx) => processPlan(ctx, "package-install", "mix", ["deps.get"], {
1764
- parser: "package-text",
1765
- reason: "Fetch Elixir dependencies.",
1766
- mutating: true,
1767
- network: true
1768
- })
1769
- })
1770
- };
1771
- }
1772
- function shellProfile() {
1773
- return {
1774
- id: "shell",
1775
- displayName: "Shell",
1776
- extensions: Object.freeze([".sh", ".bash"]),
1777
- lspLanguageIds: Object.freeze(["shellscript"]),
1778
- detectors: Object.freeze([{ kind: "config", filename: "ShellCheckrc", weight: 50 }]),
1779
- ignoredDirectories: IGNORES,
1780
- packageManagers: Object.freeze([]),
1781
- executables: Object.freeze(["bash", "sh", "shellcheck", "shfmt"]),
1782
- operations: Object.freeze({
1783
- syntax: async (ctx) => ctx.options.target ? processPlan(ctx, "syntax", "bash", ["-n", ctx.options.target], {
1784
- parser: "shell",
1785
- reason: "Check the shell script for syntax errors."
1786
- }) : unavailable(ctx, "syntax", "Shell syntax check requires an explicit target file."),
1787
- lint: async (ctx) => ctx.options.target ? processPlan(ctx, "lint", "shellcheck", ["--format=json", ctx.options.target], {
1788
- parser: "shellcheck",
1789
- reason: "Run ShellCheck on the target script."
1790
- }) : unavailable(ctx, "lint", "Shell linting requires an explicit target file."),
1791
- "format-check": async (ctx) => ctx.options.target ? processPlan(ctx, "format-check", "shfmt", ["-d", ctx.options.target], {
1792
- parser: "shell",
1793
- reason: "Check shell formatting without writing."
1794
- }) : unavailable(
1795
- ctx,
1796
- "format-check",
1797
- "Shell formatting check requires an explicit target file."
1798
- ),
1799
- "format-write": async (ctx) => ctx.options.target ? processPlan(ctx, "format-write", "shfmt", ["-w", ctx.options.target], {
1800
- parser: "shell",
1801
- reason: "Format the shell script.",
1802
- mutating: true
1803
- }) : unavailable(ctx, "format-write", "Shell formatting requires an explicit target file.")
1804
- })
1805
- };
1806
- }
1807
- var ADDITIONAL_LANGUAGE_PROFILES = Object.freeze([
1808
- pythonProfile(),
1809
- javaProfile(),
1810
- rubyProfile(),
1811
- cProfile(),
1812
- cppProfile(),
1813
- swiftProfile(),
1814
- dartProfile(),
1815
- denoProfile(),
1816
- elixirProfile(),
1817
- shellProfile()
1818
- ]);
1819
-
1820
- // src/languages/profiles/primary.ts
1821
- var COMMON_IGNORES = Object.freeze([
1822
- ".git",
1823
- ".wrongstack",
1824
- "node_modules",
1825
- "vendor",
1826
- "target",
1827
- "bin",
1828
- "obj",
1829
- "dist",
1830
- "build",
1831
- "coverage"
1832
- ]);
1833
- function nodeManager(ctx) {
1834
- const lockfiles = new Set(
1835
- ctx.workspace.evidence.filter((evidence) => evidence.kind === "lockfile").map((evidence) => evidence.value.toLowerCase())
1836
- );
1837
- if (lockfiles.size > 1 && !ctx.workspace.packageManager) return void 0;
1838
- return ctx.workspace.packageManager ?? "npm";
1839
- }
1840
- function scriptPlan(ctx, operation, script) {
1841
- const manager = nodeManager(ctx);
1842
- if (!manager)
1843
- return unavailable(
1844
- ctx,
1845
- operation,
1846
- "Conflicting Node lockfiles make the package manager ambiguous."
1847
- );
1848
- const args = manager === "npm" ? ["run", script] : [script];
1849
- return processPlan(ctx, operation, manager, args, {
1850
- parser: "command-text",
1851
- reason: `Run the detected ${manager} ${script} script for this workspace.`,
1852
- mutating: true,
1853
- executesProjectCode: true
1854
- });
1855
- }
1856
- function nodeExec(ctx, executable, args) {
1857
- const manager = ctx.workspace.packageManager ?? "npm";
1858
- if (manager === "pnpm") return { command: "pnpm", args: ["exec", executable, ...args] };
1859
- if (manager === "yarn") return { command: "yarn", args: ["exec", executable, ...args] };
1860
- if (manager === "bun") return { command: "bun", args: ["x", executable, ...args] };
1861
- return { command: "npx", args: ["--no-install", executable, ...args] };
1862
- }
1863
- function typescriptProfile() {
1864
- return {
1865
- id: "typescript",
1866
- displayName: "TypeScript",
1867
- extensions: Object.freeze([".ts", ".tsx", ".mts", ".cts"]),
1868
- lspLanguageIds: Object.freeze(["typescript", "typescriptreact"]),
1869
- detectors: Object.freeze([
1870
- { kind: "config", filename: "tsconfig.json", weight: 90 },
1871
- { kind: "manifest", filename: "package.json", weight: 55 },
1872
- { kind: "lockfile", filename: "pnpm-lock.yaml", weight: 30 },
1873
- { kind: "lockfile", filename: "yarn.lock", weight: 30 },
1874
- { kind: "lockfile", filename: "package-lock.json", weight: 30 },
1875
- { kind: "lockfile", filename: "bun.lock", weight: 30 },
1876
- { kind: "lockfile", filename: "bun.lockb", weight: 30 }
1877
- ]),
1878
- ignoredDirectories: COMMON_IGNORES,
1879
- packageManagers: Object.freeze(["pnpm", "yarn", "bun", "npm"]),
1880
- executables: Object.freeze(["pnpm", "yarn", "bun", "npx", "npm"]),
1881
- operations: Object.freeze({
1882
- syntax: async (ctx) => internalPlan(
1883
- ctx,
1884
- "syntax",
1885
- "typescript-parser",
1886
- "Parse the target with the TypeScript compiler API."
1887
- ),
1888
- semantic: async (ctx) => {
1889
- const run = nodeExec(ctx, "tsc", ["--noEmit", "--pretty", "false"]);
1890
- return processPlan(ctx, "semantic", run.command, run.args, {
1891
- parser: "typescript",
1892
- reason: "Run the workspace TypeScript compiler without emitting files.",
1893
- executesProjectCode: true
1894
- });
1895
- },
1896
- lint: async (ctx) => {
1897
- const run = nodeExec(ctx, "biome", ["lint", "."]);
1898
- return processPlan(ctx, "lint", run.command, run.args, {
1899
- parser: "biome",
1900
- reason: "Run the project-local Biome linter.",
1901
- executesProjectCode: true
1902
- });
1903
- },
1904
- "format-check": async (ctx) => {
1905
- const run = nodeExec(ctx, "biome", ["format", "--check", "."]);
1906
- return processPlan(ctx, "format-check", run.command, run.args, {
1907
- parser: "biome",
1908
- reason: "Check formatting with the project-local Biome formatter.",
1909
- executesProjectCode: true
1910
- });
1911
- },
1912
- "format-write": async (ctx) => {
1913
- const run = nodeExec(ctx, "biome", ["format", "--write", "."]);
1914
- return processPlan(ctx, "format-write", run.command, run.args, {
1915
- parser: "biome",
1916
- reason: "Format the workspace with the project-local Biome formatter.",
1917
- mutating: true,
1918
- executesProjectCode: true
1919
- });
1920
- },
1921
- test: async (ctx) => ctx.options.filter || ctx.options.coverage ? unavailable(
1922
- ctx,
1923
- "test",
1924
- "The detected package script does not expose deterministic filter or coverage adapters."
1925
- ) : scriptPlan(ctx, "test", "test"),
1926
- build: async (ctx) => scriptPlan(ctx, "build", "build"),
1927
- run: async (ctx) => scriptPlan(ctx, "run", "dev"),
1928
- "debug-compile": async (ctx) => {
1929
- const run = nodeExec(ctx, "tsc", ["--noEmit", "--pretty", "false"]);
1930
- return processPlan(ctx, "debug-compile", run.command, run.args, {
1931
- parser: "typescript",
1932
- reason: "Collect deterministic TypeScript compiler diagnostics.",
1933
- executesProjectCode: true
1934
- });
1935
- },
1936
- "package-install": async (ctx) => {
1937
- const manager = ctx.workspace.packageManager ?? "npm";
1938
- const args = manager === "yarn" ? ["install", "--ignore-scripts"] : ["install", "--ignore-scripts"];
1939
- return processPlan(ctx, "package-install", manager, args, {
1940
- parser: "package-text",
1941
- reason: `Restore declared dependencies with ${manager} and lifecycle scripts disabled.`,
1942
- mutating: true,
1943
- network: true,
1944
- executesProjectCode: false
1945
- });
1946
- },
1947
- "package-add": async (ctx) => {
1948
- const names = packageNames(ctx);
1949
- if (names.length === 0)
1950
- return unavailable(ctx, "package-add", "At least one package name is required.");
1951
- const manager = ctx.workspace.packageManager ?? "npm";
1952
- const args = manager === "npm" ? ["install", "--ignore-scripts", ...names] : ["add", "--ignore-scripts", ...names];
1953
- return processPlan(ctx, "package-add", manager, args, {
1954
- parser: "package-text",
1955
- reason: `Add validated packages with ${manager} and lifecycle scripts disabled.`,
1956
- mutating: true,
1957
- network: true
1958
- });
1959
- },
1960
- "package-remove": async (ctx) => {
1961
- const names = packageNames(ctx);
1962
- if (names.length === 0)
1963
- return unavailable(ctx, "package-remove", "At least one package name is required.");
1964
- const manager = ctx.workspace.packageManager ?? "npm";
1965
- const args = manager === "npm" ? ["uninstall", "--ignore-scripts", ...names] : ["remove", "--ignore-scripts", ...names];
1966
- return processPlan(ctx, "package-remove", manager, args, {
1967
- parser: "package-text",
1968
- reason: `Remove validated packages with ${manager} and lifecycle scripts disabled.`,
1969
- mutating: true,
1970
- network: true
1971
- });
1972
- },
1973
- "package-audit": async (ctx) => {
1974
- const manager = ctx.workspace.packageManager ?? "npm";
1975
- return processPlan(ctx, "package-audit", manager, ["audit", "--json"], {
1976
- parser: "npm-audit",
1977
- reason: `Audit dependencies with the detected ${manager} package manager.`,
1978
- network: true
1979
- });
1980
- },
1981
- "package-outdated": async (ctx) => {
1982
- const manager = ctx.workspace.packageManager ?? "npm";
1983
- return processPlan(ctx, "package-outdated", manager, ["outdated", "--json"], {
1984
- parser: "npm-outdated",
1985
- reason: `Check outdated dependencies with ${manager}.`,
1986
- network: true
1987
- });
1988
- }
1989
- })
1990
- };
1991
- }
1992
- function javascriptProfile() {
1993
- const ts = typescriptProfile();
1994
- return {
1995
- ...ts,
1996
- id: "javascript",
1997
- displayName: "JavaScript",
1998
- extensions: Object.freeze([".js", ".jsx", ".mjs", ".cjs"]),
1999
- lspLanguageIds: Object.freeze(["javascript", "javascriptreact"]),
2000
- detectors: Object.freeze([
2001
- { kind: "config", filename: "jsconfig.json", weight: 90 },
2002
- { kind: "manifest", filename: "package.json", weight: 70 },
2003
- { kind: "lockfile", filename: "pnpm-lock.yaml", weight: 30 },
2004
- { kind: "lockfile", filename: "yarn.lock", weight: 30 },
2005
- { kind: "lockfile", filename: "package-lock.json", weight: 30 },
2006
- { kind: "lockfile", filename: "bun.lock", weight: 30 },
2007
- { kind: "lockfile", filename: "bun.lockb", weight: 30 }
2008
- ]),
2009
- operations: Object.freeze({
2010
- ...ts.operations,
2011
- syntax: async (ctx) => internalPlan(
2012
- ctx,
2013
- "syntax",
2014
- "typescript-parser",
2015
- "Parse JavaScript with the TypeScript compiler API."
2016
- )
2017
- })
2018
- };
2019
- }
2020
- var goProfile = {
2021
- id: "go",
2022
- displayName: "Go",
2023
- extensions: Object.freeze([".go"]),
2024
- lspLanguageIds: Object.freeze(["go"]),
2025
- detectors: Object.freeze([
2026
- { kind: "manifest", filename: "go.mod", weight: 90 },
2027
- { kind: "manifest", filename: "go.work", weight: 95 },
2028
- { kind: "lockfile", filename: "go.sum", weight: 30 }
2029
- ]),
2030
- ignoredDirectories: COMMON_IGNORES,
2031
- packageManagers: Object.freeze(["go"]),
2032
- executables: Object.freeze(["go", "gofmt"]),
2033
- operations: Object.freeze({
2034
- syntax: async (ctx) => {
2035
- if (!ctx.target)
2036
- return unavailable(ctx, "syntax", "Go syntax planning requires a target file.");
2037
- return processPlan(ctx, "syntax", "gofmt", ["-e", "-d", ctx.target], {
2038
- parser: "gofmt",
2039
- reason: "Parse the target and report syntax errors without writing it."
2040
- });
2041
- },
2042
- semantic: async (ctx) => processPlan(ctx, "semantic", "go", ["test", "-run", "^$", "./..."], {
2043
- parser: "go-test",
2044
- reason: "Compile all Go packages without selecting tests.",
2045
- mutating: true,
2046
- executesProjectCode: true
2047
- }),
2048
- lint: async (ctx) => processPlan(ctx, "lint", "go", ["vet", "./..."], {
2049
- parser: "go-compiler",
2050
- reason: "Run the standard Go vet checks.",
2051
- mutating: true,
2052
- executesProjectCode: true
2053
- }),
2054
- "format-check": async (ctx) => ctx.target ? processPlan(ctx, "format-check", "gofmt", ["-d", ctx.target], {
2055
- parser: "gofmt",
2056
- reason: "Report Go formatting differences for the target without writing it."
2057
- }) : unavailable(ctx, "format-check", "Go formatting requires an explicit target file."),
2058
- "format-write": async (ctx) => ctx.target ? processPlan(ctx, "format-write", "gofmt", ["-w", ctx.target], {
2059
- parser: "gofmt",
2060
- reason: "Format the target Go source file.",
2061
- mutating: true
2062
- }) : unavailable(ctx, "format-write", "Go formatting requires an explicit target file."),
2063
- test: async (ctx) => processPlan(
2064
- ctx,
2065
- "test",
2066
- "go",
2067
- ["test", ...ctx.options.filter ? ["-run", ctx.options.filter] : [], "./..."],
2068
- {
2069
- parser: "go-test",
2070
- reason: ctx.options.filter ? "Run filtered Go tests." : "Run all Go tests.",
2071
- mutating: true,
2072
- executesProjectCode: true
2073
- }
2074
- ),
2075
- build: async (ctx) => processPlan(ctx, "build", "go", ["build", "./..."], {
2076
- parser: "go-compiler",
2077
- reason: "Build all Go packages.",
2078
- mutating: true,
2079
- executesProjectCode: true
2080
- }),
2081
- run: async (ctx) => processPlan(ctx, "run", "go", ["run", "."], {
2082
- parser: "command-text",
2083
- reason: "Run the Go module entry point.",
2084
- executesProjectCode: true
2085
- }),
2086
- "debug-race": async (ctx) => processPlan(ctx, "debug-race", "go", ["test", "-race", "./..."], {
2087
- parser: "go-test",
2088
- reason: "Collect Go race-detector evidence.",
2089
- mutating: true,
2090
- executesProjectCode: true
2091
- }),
2092
- "package-install": async (ctx) => processPlan(ctx, "package-install", "go", ["mod", "download"], {
2093
- parser: "go-module",
2094
- reason: "Download the dependencies declared by go.mod.",
2095
- mutating: true,
2096
- network: true
2097
- }),
2098
- "package-add": async (ctx) => {
2099
- const names = packageNames(ctx);
2100
- if (names.length === 0)
2101
- return unavailable(ctx, "package-add", "At least one Go module is required.");
2102
- return processPlan(ctx, "package-add", "go", ["get", ...names], {
2103
- parser: "go-module",
2104
- reason: "Add validated Go modules.",
2105
- mutating: true,
2106
- network: true
2107
- });
2108
- },
2109
- "package-update": async (ctx) => processPlan(ctx, "package-update", "go", ["get", "-u", "./..."], {
2110
- parser: "go-module",
2111
- reason: "Update dependencies of all Go packages.",
2112
- mutating: true,
2113
- network: true
2114
- })
2115
- })
2116
- };
2117
- var rustProfile = {
2118
- id: "rust",
2119
- displayName: "Rust",
2120
- extensions: Object.freeze([".rs"]),
2121
- lspLanguageIds: Object.freeze(["rust"]),
2122
- detectors: Object.freeze([
2123
- { kind: "manifest", filename: "Cargo.toml", weight: 90 },
2124
- { kind: "lockfile", filename: "Cargo.lock", weight: 30 }
2125
- ]),
2126
- ignoredDirectories: COMMON_IGNORES,
2127
- packageManagers: Object.freeze(["cargo"]),
2128
- executables: Object.freeze(["cargo"]),
2129
- operations: Object.freeze({
2130
- syntax: async (ctx) => processPlan(ctx, "syntax", "cargo", ["check", "--message-format=json"], {
2131
- parser: "cargo-json",
2132
- reason: "Check Rust syntax and semantics with Cargo.",
2133
- mutating: true,
2134
- executesProjectCode: true
2135
- }),
2136
- semantic: async (ctx) => processPlan(ctx, "semantic", "cargo", ["check", "--message-format=json"], {
2137
- parser: "cargo-json",
2138
- reason: "Collect Rust compiler diagnostics with Cargo check.",
2139
- mutating: true,
2140
- executesProjectCode: true
2141
- }),
2142
- lint: async (ctx) => processPlan(ctx, "lint", "cargo", ["clippy", "--message-format=json"], {
2143
- parser: "cargo-json",
2144
- reason: "Run Clippy for this crate.",
2145
- mutating: true,
2146
- executesProjectCode: true
2147
- }),
2148
- "format-check": async (ctx) => processPlan(ctx, "format-check", "cargo", ["fmt", "--check"], {
2149
- parser: "cargo-fmt",
2150
- reason: "Check Rust formatting without writing files."
2151
- }),
2152
- "format-write": async (ctx) => processPlan(ctx, "format-write", "cargo", ["fmt"], {
2153
- parser: "cargo-fmt",
2154
- reason: "Format Rust source files in the workspace.",
2155
- mutating: true
2156
- }),
2157
- "test-compile": async (ctx) => processPlan(ctx, "test-compile", "cargo", ["test", "--no-run", "--message-format=json"], {
2158
- parser: "cargo-json",
2159
- reason: "Compile Rust tests without running them.",
2160
- mutating: true,
2161
- executesProjectCode: true
2162
- }),
2163
- test: async (ctx) => processPlan(
2164
- ctx,
2165
- "test",
2166
- "cargo",
2167
- ["test", ...ctx.options.filter ? [ctx.options.filter] : []],
2168
- {
2169
- parser: "cargo-test",
2170
- reason: ctx.options.filter ? "Run filtered Rust tests." : "Run Rust tests.",
2171
- mutating: true,
2172
- executesProjectCode: true
2173
- }
2174
- ),
2175
- build: async (ctx) => processPlan(ctx, "build", "cargo", ["build", "--message-format=json"], {
2176
- parser: "cargo-json",
2177
- reason: "Build the Rust workspace.",
2178
- mutating: true,
2179
- executesProjectCode: true
2180
- }),
2181
- run: async (ctx) => processPlan(ctx, "run", "cargo", ["run"], {
2182
- parser: "command-text",
2183
- reason: "Run the Rust workspace entry point.",
2184
- executesProjectCode: true
2185
- }),
2186
- "package-install": async (ctx) => processPlan(ctx, "package-install", "cargo", ["fetch", "--locked"], {
2187
- parser: "cargo-json",
2188
- reason: "Fetch locked Rust dependencies.",
2189
- mutating: true,
2190
- network: true
2191
- }),
2192
- "package-add": async (ctx) => {
2193
- const names = packageNames(ctx);
2194
- return names.length === 0 ? unavailable(ctx, "package-add", "At least one crate is required.") : processPlan(ctx, "package-add", "cargo", ["add", ...names], {
2195
- parser: "cargo-text",
2196
- reason: "Add validated Rust crates.",
2197
- mutating: true,
2198
- network: true
2199
- });
2200
- },
2201
- "package-remove": async (ctx) => {
2202
- const names = packageNames(ctx);
2203
- return names.length === 0 ? unavailable(ctx, "package-remove", "At least one crate is required.") : processPlan(ctx, "package-remove", "cargo", ["remove", ...names], {
2204
- parser: "cargo-text",
2205
- reason: "Remove validated Rust crates.",
2206
- mutating: true
2207
- });
2208
- },
2209
- "package-update": async (ctx) => processPlan(ctx, "package-update", "cargo", ["update"], {
2210
- parser: "cargo-text",
2211
- reason: "Update the Cargo lockfile.",
2212
- mutating: true,
2213
- network: true
2214
- }),
2215
- "package-audit": async (ctx) => processPlan(ctx, "package-audit", "cargo", ["audit", "--json"], {
2216
- parser: "cargo-audit",
2217
- reason: "Audit Rust dependencies when cargo-audit is installed.",
2218
- network: true
2219
- })
2220
- })
2221
- };
2222
- var phpProfile = {
2223
- id: "php",
2224
- displayName: "PHP",
2225
- extensions: Object.freeze([".php"]),
2226
- lspLanguageIds: Object.freeze(["php"]),
2227
- detectors: Object.freeze([
2228
- { kind: "manifest", filename: "composer.json", weight: 90 },
2229
- { kind: "lockfile", filename: "composer.lock", weight: 30 },
2230
- { kind: "config", filename: "phpunit.xml", weight: 25 },
2231
- { kind: "config", filename: "phpunit.xml.dist", weight: 25 }
2232
- ]),
2233
- ignoredDirectories: COMMON_IGNORES,
2234
- packageManagers: Object.freeze(["composer"]),
2235
- executables: Object.freeze(["php", "composer"]),
2236
- operations: Object.freeze({
2237
- syntax: async (ctx) => ctx.target ? processPlan(ctx, "syntax", "php", ["-l", ctx.target], {
2238
- parser: "php-lint",
2239
- reason: "Lint the target PHP file without executing it."
2240
- }) : unavailable(ctx, "syntax", "PHP syntax planning requires a target file."),
2241
- semantic: async (ctx) => unavailable(
2242
- ctx,
2243
- "semantic",
2244
- "No configured PHPStan or Psalm adapter was detected in Phase 1."
2245
- ),
2246
- test: async (ctx) => processPlan(
2247
- ctx,
2248
- "test",
2249
- "php",
2250
- ["vendor/bin/phpunit", ...ctx.options.filter ? ["--filter", ctx.options.filter] : []],
2251
- {
2252
- parser: "phpunit",
2253
- reason: ctx.options.filter ? "Run filtered tests with the project-local PHPUnit runner." : "Run the project-local PHPUnit test runner.",
2254
- executesProjectCode: true
2255
- }
2256
- ),
2257
- "package-install": async (ctx) => processPlan(
2258
- ctx,
2259
- "package-install",
2260
- "composer",
2261
- ["install", "--no-interaction", "--no-scripts"],
2262
- {
2263
- parser: "composer",
2264
- reason: "Restore Composer dependencies without scripts.",
2265
- mutating: true,
2266
- network: true
2267
- }
2268
- ),
2269
- "package-add": async (ctx) => {
2270
- const names = packageNames(ctx);
2271
- return names.length === 0 ? unavailable(ctx, "package-add", "At least one Composer package is required.") : processPlan(
2272
- ctx,
2273
- "package-add",
2274
- "composer",
2275
- ["require", "--no-interaction", "--no-scripts", ...names],
2276
- {
2277
- parser: "composer",
2278
- reason: "Add validated Composer packages without scripts.",
2279
- mutating: true,
2280
- network: true
2281
- }
2282
- );
2283
- },
2284
- "package-remove": async (ctx) => {
2285
- const names = packageNames(ctx);
2286
- return names.length === 0 ? unavailable(ctx, "package-remove", "At least one Composer package is required.") : processPlan(
2287
- ctx,
2288
- "package-remove",
2289
- "composer",
2290
- ["remove", "--no-interaction", "--no-scripts", ...names],
2291
- {
2292
- parser: "composer",
2293
- reason: "Remove validated Composer packages without scripts.",
2294
- mutating: true
2295
- }
2296
- );
2297
- },
2298
- "package-update": async (ctx) => processPlan(
2299
- ctx,
2300
- "package-update",
2301
- "composer",
2302
- ["update", "--no-interaction", "--no-scripts"],
2303
- {
2304
- parser: "composer",
2305
- reason: "Update Composer dependencies without scripts.",
2306
- mutating: true,
2307
- network: true
2308
- }
2309
- ),
2310
- "package-audit": async (ctx) => processPlan(ctx, "package-audit", "composer", ["audit", "--format=json"], {
2311
- parser: "composer-audit",
2312
- reason: "Audit Composer dependencies.",
2313
- network: true
2314
- }),
2315
- "package-outdated": async (ctx) => processPlan(ctx, "package-outdated", "composer", ["outdated", "--format=json"], {
2316
- parser: "composer-outdated",
2317
- reason: "Check outdated Composer dependencies.",
2318
- network: true
2319
- })
2320
- })
2321
- };
2322
- var csharpProfile = {
2323
- id: "csharp",
2324
- displayName: "C# / .NET",
2325
- extensions: Object.freeze([".cs"]),
2326
- lspLanguageIds: Object.freeze(["csharp"]),
2327
- detectors: Object.freeze([
2328
- { kind: "config", filename: "global.json", weight: 25 },
2329
- { kind: "manifest", suffix: ".slnx", weight: 95 },
2330
- { kind: "manifest", suffix: ".sln", weight: 95 },
2331
- { kind: "manifest", suffix: ".csproj", weight: 90 },
2332
- { kind: "manifest", suffix: ".fsproj", weight: 90 },
2333
- { kind: "lockfile", filename: "packages.lock.json", weight: 30 }
2334
- ]),
2335
- ignoredDirectories: COMMON_IGNORES,
2336
- packageManagers: Object.freeze(["dotnet"]),
2337
- executables: Object.freeze(["dotnet"]),
2338
- operations: Object.freeze({
2339
- syntax: async (ctx) => processPlan(ctx, "syntax", "dotnet", ["build", "--no-restore"], {
2340
- parser: "dotnet-build",
2341
- reason: "Use the nearest project or solution to collect C# syntax diagnostics.",
2342
- mutating: true,
2343
- executesProjectCode: true
2344
- }),
2345
- semantic: async (ctx) => processPlan(ctx, "semantic", "dotnet", ["build", "--no-restore"], {
2346
- parser: "dotnet-build",
2347
- reason: "Build without restoring to collect .NET compiler diagnostics.",
2348
- mutating: true,
2349
- executesProjectCode: true
2350
- }),
2351
- lint: async (ctx) => processPlan(ctx, "lint", "dotnet", ["format", "--verify-no-changes", "--no-restore"], {
2352
- parser: "dotnet-format",
2353
- reason: "Verify .NET formatting and analyzers without writing source files.",
2354
- mutating: true,
2355
- executesProjectCode: true
2356
- }),
2357
- "format-check": async (ctx) => processPlan(
2358
- ctx,
2359
- "format-check",
2360
- "dotnet",
2361
- ["format", "--verify-no-changes", "--no-restore"],
2362
- {
2363
- parser: "dotnet-format",
2364
- reason: "Verify .NET formatting without source writes.",
2365
- mutating: true,
2366
- executesProjectCode: true
2367
- }
2368
- ),
2369
- "format-write": async (ctx) => processPlan(ctx, "format-write", "dotnet", ["format", "--no-restore"], {
2370
- parser: "dotnet-format",
2371
- reason: "Format .NET source files without restoring packages.",
2372
- mutating: true,
2373
- executesProjectCode: true
2374
- }),
2375
- test: async (ctx) => processPlan(
2376
- ctx,
2377
- "test",
2378
- "dotnet",
2379
- ["test", "--no-restore", ...ctx.options.filter ? ["--filter", ctx.options.filter] : []],
2380
- {
2381
- parser: "dotnet-test",
2382
- reason: ctx.options.filter ? "Run filtered .NET tests without restoring packages." : "Run .NET tests without restoring packages.",
2383
- mutating: true,
2384
- executesProjectCode: true
2385
- }
2386
- ),
2387
- build: async (ctx) => processPlan(ctx, "build", "dotnet", ["build", "--no-restore"], {
2388
- parser: "dotnet-build",
2389
- reason: "Build the nearest .NET project or solution without restoring packages.",
2390
- mutating: true,
2391
- executesProjectCode: true
2392
- }),
2393
- run: async (ctx) => processPlan(ctx, "run", "dotnet", ["run", "--no-restore"], {
2394
- parser: "command-text",
2395
- reason: "Run the .NET project entry point.",
2396
- mutating: true,
2397
- executesProjectCode: true
2398
- }),
2399
- "package-install": async (ctx) => processPlan(ctx, "package-install", "dotnet", ["restore", "--locked-mode"], {
2400
- parser: "dotnet-restore",
2401
- reason: "Restore locked .NET dependencies.",
2402
- mutating: true,
2403
- network: true,
2404
- executesProjectCode: true
2405
- }),
2406
- "package-add": async (ctx) => {
2407
- const names = packageNames(ctx);
2408
- const [spec] = names;
2409
- const versionAt = spec?.lastIndexOf("@") ?? -1;
2410
- const packageName = versionAt > 0 ? spec?.slice(0, versionAt) : spec;
2411
- const packageVersion = versionAt > 0 ? spec?.slice(versionAt + 1) : void 0;
2412
- return names.length === 0 ? unavailable(ctx, "package-add", "At least one NuGet package is required.") : names.length > 1 ? unavailable(ctx, "package-add", "NuGet package changes run one package at a time.") : processPlan(
2413
- ctx,
2414
- "package-add",
2415
- "dotnet",
2416
- [
2417
- "add",
2418
- "package",
2419
- packageName ?? "",
2420
- ...packageVersion ? ["--version", packageVersion] : []
2421
- ],
2422
- {
2423
- parser: "dotnet-package",
2424
- reason: "Add validated NuGet packages.",
2425
- mutating: true,
2426
- network: true,
2427
- executesProjectCode: true
2428
- }
2429
- );
2430
- },
2431
- "package-remove": async (ctx) => {
2432
- const names = packageNames(ctx);
2433
- return names.length === 0 ? unavailable(ctx, "package-remove", "At least one NuGet package is required.") : processPlan(ctx, "package-remove", "dotnet", ["remove", "package", ...names], {
2434
- parser: "dotnet-package",
2435
- reason: "Remove validated NuGet packages.",
2436
- mutating: true
2437
- });
2438
- },
2439
- "package-audit": async (ctx) => processPlan(
2440
- ctx,
2441
- "package-audit",
2442
- "dotnet",
2443
- ["list", "package", "--vulnerable", "--format", "json"],
2444
- { parser: "dotnet-package", reason: "List vulnerable NuGet dependencies.", network: true }
2445
- ),
2446
- "package-outdated": async (ctx) => processPlan(
2447
- ctx,
2448
- "package-outdated",
2449
- "dotnet",
2450
- ["list", "package", "--outdated", "--format", "json"],
2451
- { parser: "dotnet-package", reason: "List outdated NuGet dependencies.", network: true }
2452
- )
2453
- })
2454
- };
2455
- var PRIMARY_LANGUAGE_PROFILES = Object.freeze([
2456
- Object.freeze(typescriptProfile()),
2457
- Object.freeze(javascriptProfile()),
2458
- Object.freeze(goProfile),
2459
- Object.freeze(rustProfile),
2460
- Object.freeze(phpProfile),
2461
- Object.freeze(csharpProfile)
2462
- ]);
2463
-
2464
- // src/languages/registry.ts
2465
- var PROFILE_ID_RE = /^[a-z][a-z0-9-]{0,63}$/;
2466
- var EXECUTABLE_RE = /^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/;
2467
- var KNOWN_OPERATIONS = /* @__PURE__ */ new Set([
2468
- "syntax",
2469
- "semantic",
2470
- "lint",
2471
- "format-check",
2472
- "format-write",
2473
- "test-compile",
2474
- "test",
2475
- "build",
2476
- "run",
2477
- "debug-compile",
2478
- "debug-test",
2479
- "debug-runtime",
2480
- "debug-race",
2481
- "package-install",
2482
- "package-add",
2483
- "package-remove",
2484
- "package-update",
2485
- "package-audit",
2486
- "package-outdated"
2487
- ]);
2488
- var LanguageProfileRegistry = class {
2489
- #profiles = /* @__PURE__ */ new Map();
2490
- constructor(profiles = []) {
2491
- for (const profile of profiles) this.register(profile);
2492
- }
2493
- register(profile) {
2494
- const errors = validateLanguageProfile(profile);
2495
- if (errors.length > 0) {
2496
- throw new Error(`Invalid language profile "${profile.id}": ${errors.join("; ")}`);
2497
- }
2498
- if (this.#profiles.has(profile.id)) {
2499
- throw new Error(`Language profile "${profile.id}" is already registered`);
2500
- }
2501
- this.#profiles.set(profile.id, freezeProfile(profile));
2502
- }
2503
- get(id) {
2504
- return this.#profiles.get(id);
2505
- }
2506
- list() {
2507
- return Object.freeze([...this.#profiles.values()]);
2508
- }
2509
- };
2510
- function validateLanguageProfile(profile) {
2511
- const errors = [];
2512
- if (!PROFILE_ID_RE.test(profile.id)) errors.push("id must be a lowercase stable identifier");
2513
- if (!profile.displayName.trim()) errors.push("displayName is required");
2514
- if (profile.extensions.length === 0) errors.push("at least one extension is required");
2515
- for (const ext of profile.extensions) {
2516
- if (!/^\.[a-z0-9+.-]+$/i.test(ext)) errors.push(`invalid extension "${ext}"`);
2517
- }
2518
- if (profile.detectors.length === 0) errors.push("at least one detector is required");
2519
- for (const detector of profile.detectors) {
2520
- if ((detector.filename ? 1 : 0) + (detector.suffix ? 1 : 0) !== 1) {
2521
- errors.push("each detector must declare exactly one of filename or suffix");
2522
- }
2523
- if (!Number.isFinite(detector.weight) || detector.weight <= 0 || detector.weight > 100) {
2524
- errors.push("detector weights must be in the range 1..100");
2525
- }
2526
- const marker = detector.filename ?? detector.suffix ?? "";
2527
- if (marker.includes("/") || marker.includes("\\") || marker.includes("\0")) {
2528
- errors.push(`detector marker "${marker}" must be a basename or suffix`);
2529
- }
2530
- }
2531
- if (profile.executables.length === 0) errors.push("at least one executable is required");
2532
- for (const executable of profile.executables) {
2533
- if (!EXECUTABLE_RE.test(executable)) errors.push(`invalid executable token "${executable}"`);
2534
- }
2535
- for (const operation of Object.keys(profile.operations)) {
2536
- if (!KNOWN_OPERATIONS.has(operation)) {
2537
- errors.push(`unknown operation "${operation}"`);
2538
- }
2539
- if (typeof profile.operations[operation] !== "function") {
2540
- errors.push(`operation "${operation}" must be a resolver function`);
2541
- }
2542
- }
2543
- return [...new Set(errors)];
2544
- }
2545
- function freezeProfile(profile) {
2546
- const detectors = Object.freeze(profile.detectors.map((item) => Object.freeze({ ...item })));
2547
- const operations = Object.freeze({ ...profile.operations });
2548
- return Object.freeze({
2549
- ...profile,
2550
- extensions: Object.freeze([...profile.extensions]),
2551
- lspLanguageIds: Object.freeze([...profile.lspLanguageIds]),
2552
- detectors,
2553
- ignoredDirectories: Object.freeze([...profile.ignoredDirectories]),
2554
- packageManagers: Object.freeze([...profile.packageManagers]),
2555
- executables: Object.freeze([...profile.executables]),
2556
- operations
2557
- });
2558
- }
2559
- var languageProfileRegistry = new LanguageProfileRegistry([
2560
- ...PRIMARY_LANGUAGE_PROFILES,
2561
- ...ADDITIONAL_LANGUAGE_PROFILES
2562
- ]);
2563
-
2564
- // src/languages/detect.ts
2565
- var DEFAULT_LIMITS = { maxDepth: 6, maxEntries: 5e3 };
2566
- var SOURCE_WEIGHT = 5;
2567
- var SOURCE_WEIGHT_CAP = 25;
2568
- var TARGET_WEIGHT = 100;
2569
- var GLOBAL_IGNORES = /* @__PURE__ */ new Set([
2570
- ".git",
2571
- ".wrongstack",
2572
- "node_modules",
2573
- "vendor",
2574
- "target",
2575
- "bin",
2576
- "obj",
2577
- "dist",
2578
- "build",
2579
- "out",
2580
- "coverage",
2581
- ".cache",
2582
- ".idea",
2583
- ".vscode",
2584
- ".next",
2585
- ".nuxt"
2586
- ]);
2587
- async function detectLanguageWorkspaces(options) {
2588
- const projectRoot = await canonicalDirectory(options.projectRoot);
2589
- const cwdInput = options.cwd ? path4.isAbsolute(options.cwd) ? options.cwd : path4.resolve(projectRoot, options.cwd) : projectRoot;
2590
- const cwd = await canonicalInside(cwdInput, projectRoot, "cwd");
2591
- const target = options.target ? await canonicalInside(resolveFrom(cwd, options.target), projectRoot, "target") : void 0;
2592
- const profiles = (options.profiles ?? languageProfileRegistry.list()).filter((profile) => !options.language || profile.id === options.language).slice().sort((a, b) => a.id.localeCompare(b.id));
2593
- const limits = normalizeLimits(options.limits);
2594
- const extraIgnores = new Set(options.ignoredDirectories ?? []);
2595
- const state = {
2596
- entries: 0,
2597
- truncated: false,
2598
- sourcePaths: /* @__PURE__ */ new Map(),
2599
- candidates: /* @__PURE__ */ new Map()
2600
- };
2601
- await scanDirectory(projectRoot, 0, profiles, limits, state, extraIgnores, options.signal);
2602
- addSourceFallbacks(projectRoot, profiles, state);
2603
- if (target) addTargetEvidence(target, projectRoot, profiles, state);
2604
- const workspaces = await Promise.all(
2605
- [...state.candidates.values()].map((candidate) => finalizeCandidate(candidate, projectRoot))
2606
- );
2607
- workspaces.sort(compareWorkspaces);
2608
- return {
2609
- projectRoot,
2610
- scannedEntries: state.entries,
2611
- truncated: state.truncated,
2612
- workspaces
2613
- };
2614
- }
2615
- async function scanDirectory(directory, depth, profiles, limits, state, extraIgnores, signal) {
2616
- signal?.throwIfAborted();
2617
- if (depth > limits.maxDepth || state.entries >= limits.maxEntries) {
2618
- state.truncated = true;
2619
- return;
2620
- }
2621
- let entries;
2622
- try {
2623
- entries = await fs2.readdir(directory, { withFileTypes: true });
2624
- } catch {
2625
- return;
2626
- }
2627
- entries.sort((a, b) => a.name.localeCompare(b.name));
2628
- for (const entry of entries) {
2629
- signal?.throwIfAborted();
2630
- if (state.entries >= limits.maxEntries) {
2631
- state.truncated = true;
2632
- return;
2633
- }
2634
- state.entries++;
2635
- const fullPath = path4.join(directory, entry.name);
2636
- if (entry.isSymbolicLink()) continue;
2637
- if (entry.isDirectory()) {
2638
- if (shouldIgnoreDirectory(entry.name, profiles, extraIgnores)) continue;
2639
- if (depth >= limits.maxDepth) {
2640
- state.truncated = true;
2641
- continue;
2642
- }
2643
- await scanDirectory(fullPath, depth + 1, profiles, limits, state, extraIgnores, signal);
2644
- continue;
2645
- }
2646
- if (!entry.isFile()) continue;
2647
- collectFileEvidence(directory, fullPath, entry.name, profiles, state);
2648
- }
2649
- }
2650
- function collectFileEvidence(directory, fullPath, basename5, profiles, state) {
2651
- const lower = basename5.toLowerCase();
2652
- const extension = path4.extname(lower);
2653
- for (const profile of profiles) {
2654
- const detector = profile.detectors.find(
2655
- (rule) => rule.filename ? lower === rule.filename.toLowerCase() : lower.endsWith(rule.suffix.toLowerCase())
2656
- );
2657
- if (detector) {
2658
- const candidate = getCandidate(state, profile, directory);
2659
- candidate.evidence.push({
2660
- kind: detector.kind,
2661
- path: fullPath,
2662
- value: basename5,
2663
- weight: detector.weight
2664
- });
2665
- if (detector.kind === "manifest" || detector.kind === "config") {
2666
- candidate.manifests.push(fullPath);
2667
- }
2668
- }
2669
- if (profile.extensions.includes(extension)) {
2670
- const paths = state.sourcePaths.get(profile.id) ?? [];
2671
- if (paths.length < SOURCE_WEIGHT_CAP / SOURCE_WEIGHT) paths.push(fullPath);
2672
- state.sourcePaths.set(profile.id, paths);
2673
- }
2674
- }
2675
- }
2676
- function addSourceFallbacks(projectRoot, profiles, state) {
2677
- for (const profile of profiles) {
2678
- const sources = state.sourcePaths.get(profile.id) ?? [];
2679
- if (sources.length === 0) continue;
2680
- const profileCandidates = [...state.candidates.values()].filter(
2681
- (item) => item.profile.id === profile.id
2682
- );
2683
- for (const source of sources) {
2684
- const containing = profileCandidates.filter((candidate2) => isInside(source, candidate2.root)).sort(
2685
- (a, b) => pathDepth(b.root, projectRoot) - pathDepth(a.root, projectRoot) || a.root.localeCompare(b.root)
2686
- );
2687
- const candidate = containing[0] ?? (profile.sourceFallback === false ? void 0 : getCandidate(state, profile, projectRoot));
2688
- if (!candidate) continue;
2689
- candidate.evidence.push({
2690
- kind: "source",
2691
- path: source,
2692
- value: path4.extname(source),
2693
- weight: SOURCE_WEIGHT
2694
- });
2695
- }
2696
- }
2697
- }
2698
- function addTargetEvidence(target, projectRoot, profiles, state) {
2699
- const extension = path4.extname(target).toLowerCase();
2700
- for (const profile of profiles) {
2701
- if (!profile.extensions.includes(extension)) continue;
2702
- const candidates = [...state.candidates.values()].filter(
2703
- (candidate2) => candidate2.profile.id === profile.id && isInside(target, candidate2.root)
2704
- );
2705
- const candidate = candidates.length > 0 ? candidates.sort(
2706
- (a, b) => pathDepth(b.root, projectRoot) - pathDepth(a.root, projectRoot) || a.root.localeCompare(b.root)
2707
- )[0] : profile.sourceFallback === false ? void 0 : getCandidate(state, profile, path4.dirname(target));
2708
- if (!candidate) continue;
2709
- candidate.evidence.push({
2710
- kind: "target",
2711
- path: target,
2712
- value: extension,
2713
- weight: TARGET_WEIGHT
2714
- });
2715
- }
2716
- }
2717
- async function finalizeCandidate(candidate, projectRoot) {
2718
- const evidence = dedupeEvidence(candidate.evidence).sort(compareEvidence);
2719
- const manifests = [...new Set(candidate.manifests)].sort();
2720
- const confidence = Math.min(1, evidence.reduce((sum, item) => sum + item.weight, 0) / 100);
2721
- const packageManager = await detectPackageManager(candidate.profile, candidate.root, evidence);
2722
- const id = createHash("sha256").update(`${candidate.profile.id}\0${path4.relative(projectRoot, candidate.root)}`).digest("hex").slice(0, 16);
2723
- return Object.freeze({
2724
- id,
2725
- language: candidate.profile.id,
2726
- root: candidate.root,
2727
- confidence,
2728
- evidence: Object.freeze(evidence.map((item) => Object.freeze(item))),
2729
- ...packageManager ? { packageManager } : {},
2730
- manifests: Object.freeze(manifests),
2731
- capabilities: Object.freeze(
2732
- Object.keys(candidate.profile.operations).sort()
2733
- )
2734
- });
2735
- }
2736
- async function detectPackageManager(profile, root, evidence) {
2737
- if (profile.packageManagers.length === 1) return profile.packageManagers[0];
2738
- if (profile.id !== "typescript" && profile.id !== "javascript") return void 0;
2739
- let declared;
2740
- try {
2741
- const pkg = JSON.parse(await fs2.readFile(path4.join(root, "package.json"), "utf8"));
2742
- if (typeof pkg.packageManager === "string") {
2743
- const manager = pkg.packageManager.split("@")[0];
2744
- if (manager && profile.packageManagers.includes(manager)) declared = manager;
2745
- }
2746
- } catch {
2747
- }
2748
- const lockManagers = /* @__PURE__ */ new Set();
2749
- for (const item of evidence) {
2750
- const name = path4.basename(item.path).toLowerCase();
2751
- if (name === "pnpm-lock.yaml") lockManagers.add("pnpm");
2752
- else if (name === "yarn.lock") lockManagers.add("yarn");
2753
- else if (name === "bun.lock" || name === "bun.lockb") lockManagers.add("bun");
2754
- else if (name === "package-lock.json") lockManagers.add("npm");
2755
- }
2756
- if (declared && (lockManagers.size === 0 || lockManagers.size === 1 && lockManagers.has(declared))) {
2757
- return declared;
2758
- }
2759
- if (lockManagers.size === 1) return [...lockManagers][0];
2760
- if (lockManagers.size > 1) return void 0;
2761
- return declared ?? "npm";
2762
- }
2763
- function getCandidate(state, profile, root) {
2764
- const key = `${profile.id}\0${root}`;
2765
- let candidate = state.candidates.get(key);
2766
- if (!candidate) {
2767
- candidate = { profile, root, evidence: [], manifests: [] };
2768
- state.candidates.set(key, candidate);
2769
- }
2770
- return candidate;
2771
- }
2772
- function shouldIgnoreDirectory(name, profiles, extraIgnores) {
2773
- if (GLOBAL_IGNORES.has(name) || extraIgnores.has(name) || name.startsWith(".")) return true;
2774
- return profiles.some((profile) => profile.ignoredDirectories.includes(name));
2775
- }
2776
- function normalizeLimits(input) {
2777
- const maxDepth = Math.max(
2778
- 0,
2779
- Math.min(12, Math.trunc(input?.maxDepth ?? DEFAULT_LIMITS.maxDepth))
2780
- );
2781
- const maxEntries = Math.max(
2782
- 1,
2783
- Math.min(5e4, Math.trunc(input?.maxEntries ?? DEFAULT_LIMITS.maxEntries))
2784
- );
2785
- return { maxDepth, maxEntries };
2786
- }
2787
- async function canonicalDirectory(input) {
2788
- const resolved = path4.resolve(input);
2789
- const real = await fs2.realpath(resolved);
2790
- const stat5 = await fs2.stat(real);
2791
- if (!stat5.isDirectory()) throw new Error(`Project root is not a directory: ${input}`);
2792
- return real;
2793
- }
2794
- async function canonicalInside(input, root, label) {
2795
- const resolved = path4.resolve(input);
2796
- let real;
2797
- try {
2798
- real = await fs2.realpath(resolved);
2799
- } catch (error) {
2800
- if (error.code !== "ENOENT") throw error;
2801
- const parent = await fs2.realpath(path4.dirname(resolved));
2802
- real = path4.join(parent, path4.basename(resolved));
2803
- }
2804
- if (!isInside(real, root)) throw new Error(`${label} is outside project root: ${input}`);
2805
- return real;
2806
- }
2807
- function resolveFrom(cwd, input) {
2808
- return path4.isAbsolute(input) ? input : path4.resolve(cwd, input);
2809
- }
2810
- function isInside(candidate, root) {
2811
- const relative5 = path4.relative(root, candidate);
2812
- return relative5 === "" || !relative5.startsWith("..") && !path4.isAbsolute(relative5);
2813
- }
2814
- function pathDepth(candidate, root) {
2815
- const relative5 = path4.relative(root, candidate);
2816
- return relative5 === "" ? 0 : relative5.split(path4.sep).length;
2817
- }
2818
- function dedupeEvidence(items) {
2819
- const seen = /* @__PURE__ */ new Set();
2820
- return items.filter((item) => {
2821
- const key = `${item.kind}\0${item.path}\0${item.value}\0${item.weight}`;
2822
- if (seen.has(key)) return false;
2823
- seen.add(key);
2824
- return true;
2825
- });
2826
- }
2827
- function compareEvidence(a, b) {
2828
- return a.path.localeCompare(b.path) || a.kind.localeCompare(b.kind) || b.weight - a.weight;
2829
- }
2830
- function compareWorkspaces(a, b) {
2831
- return b.confidence - a.confidence || a.language.localeCompare(b.language) || a.root.localeCompare(b.root) || a.id.localeCompare(b.id);
2832
- }
2833
-
2834
- // src/languages/diagnostics.ts
2835
- import * as path5 from "node:path";
2836
- var MAX_DIAGNOSTICS = 200;
2837
- function parseLanguageDiagnostics(parser, stdout, stderr, workspaceRoot) {
2838
- const text = `${stdout}${stdout && stderr ? "\n" : ""}${stderr}`;
2839
- let diagnostics;
2840
- switch (parser) {
2841
- case "typescript":
2842
- diagnostics = parseTypeScript(text, workspaceRoot);
2843
- break;
2844
- case "cargo-json":
2845
- diagnostics = parseCargoJson(text, workspaceRoot);
2846
- break;
2847
- case "php-lint":
2848
- diagnostics = parsePhpLint(text, workspaceRoot);
2849
- break;
2850
- case "dotnet-build":
2851
- case "dotnet-format":
2852
- case "dotnet-test":
2853
- diagnostics = parseDotnet(text, workspaceRoot);
2854
- break;
2855
- case "go-test":
2856
- case "go-compiler":
2857
- case "gofmt":
2858
- diagnostics = parseGo(text, workspaceRoot);
2859
- break;
2860
- case "biome":
2861
- diagnostics = parseBiome(text, workspaceRoot);
2862
- break;
2863
- default:
2864
- diagnostics = parseGeneric(text, parser, workspaceRoot);
2865
- break;
2866
- }
2867
- const sorted = dedupeDiagnostics(diagnostics).sort(compareDiagnostics);
2868
- const omitted = Math.max(0, sorted.length - MAX_DIAGNOSTICS);
2869
- const kept = Object.freeze(sorted.slice(0, MAX_DIAGNOSTICS).map((item) => Object.freeze(item)));
2870
- return {
2871
- diagnostics: kept,
2872
- omitted,
2873
- summary: summarize(kept)
2874
- };
2875
- }
2876
- function diagnosticsForInternalSyntax(language, target, sourceText) {
2877
- if (language !== "typescript" && language !== "javascript") {
2878
- return Promise.resolve({ diagnostics: [], omitted: 0, summary: emptySummary() });
2879
- }
2880
- return import("@typescript/typescript6").then((tsModule) => {
2881
- const ts = tsModule.default ?? tsModule;
2882
- const extension = path5.extname(target).toLowerCase();
2883
- const scriptKind = extension === ".tsx" ? ts.ScriptKind.TSX : extension === ".ts" || extension === ".mts" || extension === ".cts" ? ts.ScriptKind.TS : ts.ScriptKind.JSX;
2884
- const sourceFile = ts.createSourceFile(
2885
- path5.basename(target),
2886
- sourceText,
2887
- ts.ScriptTarget.Latest,
2888
- false,
2889
- scriptKind
2890
- );
2891
- const native = sourceFile.parseDiagnostics ?? [];
2892
- const diagnostics = native.map((diagnostic) => {
2893
- const start = diagnostic.start ?? 0;
2894
- const location = sourceFile.getLineAndCharacterOfPosition(start);
2895
- return {
2896
- severity: diagnostic.category === ts.DiagnosticCategory.Warning ? "warning" : "error",
2897
- ...diagnostic.code ? { code: `TS${diagnostic.code}` } : {},
2898
- message: ts.flattenDiagnosticMessageText(diagnostic.messageText, " "),
2899
- file: target,
2900
- range: { start: { line: location.line + 1, column: location.character + 1 } },
2901
- source: "typescript-parser"
2902
- };
2903
- });
2904
- const sorted = dedupeDiagnostics(diagnostics).sort(compareDiagnostics);
2905
- const omitted = Math.max(0, sorted.length - MAX_DIAGNOSTICS);
2906
- const kept = Object.freeze(sorted.slice(0, MAX_DIAGNOSTICS).map((item) => Object.freeze(item)));
2907
- return { diagnostics: kept, omitted, summary: summarize(kept) };
2908
- });
2909
- }
2910
- function parseTypeScript(text, root) {
2911
- const diagnostics = [];
2912
- const regex = /^(.+?)\((\d+),(\d+)\):\s+(error|warning)\s+(TS\d+):\s*(.+)$/gm;
2913
- for (const match of text.matchAll(regex)) {
2914
- diagnostics.push({
2915
- severity: match[4] === "warning" ? "warning" : "error",
2916
- code: match[5],
2917
- message: match[6].trim(),
2918
- file: normalizeDiagnosticPath(match[1], root),
2919
- range: { start: { line: toPositiveInt(match[2]), column: toPositiveInt(match[3]) } },
2920
- source: "typescript"
2921
- });
2922
- }
2923
- return diagnostics;
2924
- }
2925
- function parseCargoJson(text, root) {
2926
- const diagnostics = [];
2927
- for (const line of text.split(/\r?\n/)) {
2928
- if (!line.trim().startsWith("{")) continue;
2929
- try {
2930
- const value = JSON.parse(line);
2931
- if (value.reason !== "compiler-message" || !value.message?.message) continue;
2932
- const primary = value.message.spans?.find((span) => span.is_primary) ?? value.message.spans?.[0];
2933
- diagnostics.push({
2934
- severity: normalizeSeverity(value.message.level),
2935
- ...value.message.code?.code ? { code: value.message.code.code } : {},
2936
- message: value.message.message,
2937
- ...primary?.file_name ? { file: normalizeDiagnosticPath(primary.file_name, root) } : {},
2938
- ...primary?.line_start ? { range: { start: { line: primary.line_start, column: primary.column_start ?? 1 } } } : {},
2939
- source: "rustc"
2940
- });
2941
- } catch {
2942
- }
2943
- }
2944
- return diagnostics;
2945
- }
2946
- function parseGo(text, root) {
2947
- return parseLinePattern(
2948
- text,
2949
- /^(.*?\.go):(\d+):(\d+):\s*(.+)$/gm,
2950
- root,
2951
- "go",
2952
- (_match, message) => ({ message, severity: /warning/i.test(message) ? "warning" : "error" })
2953
- );
2954
- }
2955
- function parsePhpLint(text, root) {
2956
- const diagnostics = [];
2957
- const regex = /(?:PHP\s+)?(?:Parse|Fatal) error:\s*(.+?)\s+in\s+(.+?)\s+on line\s+(\d+)/gi;
2958
- for (const match of text.matchAll(regex)) {
2959
- diagnostics.push({
2960
- severity: "error",
2961
- message: match[1].trim(),
2962
- file: normalizeDiagnosticPath(match[2], root),
2963
- range: { start: { line: toPositiveInt(match[3]), column: 1 } },
2964
- source: "php"
2965
- });
2966
- }
2967
- return diagnostics;
2968
- }
2969
- function parseDotnet(text, root) {
2970
- const diagnostics = [];
2971
- const regex = /^(.+?)\((\d+),(\d+)\):\s*(error|warning)\s+([A-Z]+\d+):\s*(.+?)(?:\s+\[.+\])?$/gm;
2972
- for (const match of text.matchAll(regex)) {
2973
- diagnostics.push({
2974
- severity: match[4] === "warning" ? "warning" : "error",
2975
- code: match[5],
2976
- message: match[6].trim(),
2977
- file: normalizeDiagnosticPath(match[1], root),
2978
- range: { start: { line: toPositiveInt(match[2]), column: toPositiveInt(match[3]) } },
2979
- source: "dotnet"
2980
- });
2981
- }
2982
- return diagnostics;
2983
- }
2984
- function parseBiome(text, root) {
2985
- const diagnostics = [];
2986
- const regex = /^(.+?):(\d+):(\d+)\s+(lint\/[^\s]+|format)\s+(.+)$/gm;
2987
- for (const match of text.matchAll(regex)) {
2988
- diagnostics.push({
2989
- severity: "warning",
2990
- code: match[4],
2991
- message: match[5].trim(),
2992
- file: normalizeDiagnosticPath(match[1], root),
2993
- range: { start: { line: toPositiveInt(match[2]), column: toPositiveInt(match[3]) } },
2994
- source: "biome"
2995
- });
2996
- }
2997
- return diagnostics;
2998
- }
2999
- function parseGeneric(text, source, root) {
3000
- return parseLinePattern(
3001
- text,
3002
- /^(.+?):(\d+):(\d+):\s*(?:(error|warning|info):\s*)?(.+)$/gm,
3003
- root,
3004
- source,
3005
- (match, fallback) => ({
3006
- severity: normalizeSeverity(match[4]),
3007
- message: match[5]?.trim() || fallback
3008
- })
3009
- );
3010
- }
3011
- function parseLinePattern(text, regex, root, source, details) {
3012
- const diagnostics = [];
3013
- for (const match of text.matchAll(regex)) {
3014
- const parsed = details(match, match.at(-1)?.trim() ?? "Diagnostic");
3015
- diagnostics.push({
3016
- severity: parsed.severity,
3017
- message: parsed.message,
3018
- file: normalizeDiagnosticPath(match[1], root),
3019
- range: { start: { line: toPositiveInt(match[2]), column: toPositiveInt(match[3]) } },
3020
- source
3021
- });
3022
- }
3023
- return diagnostics;
3024
- }
3025
- function normalizeDiagnosticPath(value, root) {
3026
- const clean = value.trim().replace(/^['"]|['"]$/g, "");
3027
- return path5.resolve(root, clean);
3028
- }
3029
- function normalizeSeverity(value) {
3030
- if (value === "warning" || value === "warn") return "warning";
3031
- if (value === "info" || value === "note" || value === "help") return "info";
3032
- if (value === "hint") return "hint";
3033
- return "error";
3034
- }
3035
- function toPositiveInt(value) {
3036
- return Math.max(1, Number.parseInt(value ?? "1", 10) || 1);
3037
- }
3038
- function summarize(diagnostics) {
3039
- return {
3040
- errors: diagnostics.filter((item) => item.severity === "error").length,
3041
- warnings: diagnostics.filter((item) => item.severity === "warning").length,
3042
- infos: diagnostics.filter((item) => item.severity === "info" || item.severity === "hint").length
3043
- };
3044
- }
3045
- function emptySummary() {
3046
- return { errors: 0, warnings: 0, infos: 0 };
3047
- }
3048
- function dedupeDiagnostics(items) {
3049
- const seen = /* @__PURE__ */ new Set();
3050
- return items.filter((item) => {
3051
- const key = [
3052
- item.source,
3053
- item.code ?? "",
3054
- item.file ?? "",
3055
- item.range?.start.line ?? 0,
3056
- item.range?.start.column ?? 0,
3057
- item.message
3058
- ].join("\0");
3059
- if (seen.has(key)) return false;
3060
- seen.add(key);
3061
- return true;
3062
- });
3063
- }
3064
- function compareDiagnostics(a, b) {
3065
- return (a.file ?? "").localeCompare(b.file ?? "") || (a.range?.start.line ?? 0) - (b.range?.start.line ?? 0) || (a.range?.start.column ?? 0) - (b.range?.start.column ?? 0) || severityRank(a.severity) - severityRank(b.severity) || (a.code ?? "").localeCompare(b.code ?? "") || a.message.localeCompare(b.message);
3066
- }
3067
- function severityRank(value) {
3068
- return value === "error" ? 0 : value === "warning" ? 1 : value === "info" ? 2 : 3;
3069
- }
3070
-
3071
- // src/languages/execute.ts
3072
- import * as fs4 from "node:fs/promises";
3073
- import * as path7 from "node:path";
3074
-
3075
- // src/languages/plan.ts
3076
- import * as fs3 from "node:fs/promises";
3077
- import * as path6 from "node:path";
3078
- var MAX_ARGUMENTS = 128;
3079
- var MAX_ARGUMENT_LENGTH = 4096;
3080
- var PACKAGE_NAME_RE = /^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+(?:@[a-z0-9*+._~^<>=|-]+)?$/i;
3081
- var COMPOSER_PACKAGE_RE = /^[a-z0-9_.-]+\/[a-z0-9_.-]+(?::[a-z0-9*+._~^<>=|-]+)?$/i;
3082
- var GO_MODULE_RE = /^(?:[a-z0-9-]+\.)+[a-z0-9-]+\/[a-z0-9._~+/@-]+$/i;
3083
- var PYTHON_PACKAGE_RE = /^[a-z0-9._-]+(?:\[[a-z0-9._,-]+\])?==[a-z0-9*+._!~-]+$/i;
3084
- async function planLanguageOperation(options) {
3085
- validateOperationOptions(options.operation, options.operationOptions?.packages);
3086
- validateFilterOption(options.operationOptions?.filter);
3087
- const detection = await detectLanguageWorkspaces(options);
3088
- const candidates = detection.workspaces.filter(
3089
- (workspace) => workspace.capabilities.includes(options.operation)
3090
- );
3091
- const selected = selectWorkspace(candidates, options);
3092
- if (selected.status !== "selected") return selected.result;
3093
- const profile = (options.profiles ?? languageProfileRegistry.list()).find(
3094
- (item) => item.id === selected.workspace.language
3095
- );
3096
- if (!profile) {
3097
- return {
3098
- status: "not_found",
3099
- reason: `Profile ${selected.workspace.language} is unavailable.`,
3100
- candidates
3101
- };
3102
- }
3103
- if ((profile.id === "typescript" || profile.id === "javascript") && options.operation !== "syntax" && selected.workspace.packageManager === void 0 && new Set(
3104
- selected.workspace.evidence.filter((evidence) => evidence.kind === "lockfile").map((evidence) => evidence.value.toLowerCase())
3105
- ).size > 1) {
3106
- return {
3107
- status: "unavailable",
3108
- workspace: selected.workspace,
3109
- unavailable: {
3110
- status: "unavailable",
3111
- profileId: profile.id,
3112
- workspaceId: selected.workspace.id,
3113
- operation: options.operation,
3114
- reason: "Conflicting Node lockfiles make the package manager ambiguous."
3115
- }
3116
- };
3117
- }
3118
- const resolver = profile.operations[options.operation];
3119
- if (!resolver) {
3120
- return {
3121
- status: "unavailable",
3122
- workspace: selected.workspace,
3123
- unavailable: {
3124
- status: "unavailable",
3125
- profileId: profile.id,
3126
- workspaceId: selected.workspace.id,
3127
- operation: options.operation,
3128
- reason: `${profile.displayName} does not define ${options.operation}.`
3129
- }
3130
- };
3131
- }
3132
- const canonicalCwd = options.cwd ? path6.isAbsolute(options.cwd) ? options.cwd : path6.resolve(detection.projectRoot, options.cwd) : detection.projectRoot;
3133
- const target = options.target ? await canonicalTarget(canonicalCwd, options.target, detection.projectRoot) : void 0;
3134
- const ctx = {
3135
- projectRoot: detection.projectRoot,
3136
- workspace: selected.workspace,
3137
- ...target ? { target } : {},
3138
- mode: options.mode ?? "standard",
3139
- options: options.operationOptions ?? {},
3140
- platform: process.platform,
3141
- pathExists: async (candidate) => {
3142
- try {
3143
- await fs3.access(path6.resolve(detection.projectRoot, candidate));
3144
- return true;
3145
- } catch {
3146
- return false;
3147
- }
3148
- }
3149
- };
3150
- const result = await resolver(ctx);
3151
- if ("status" in result) {
3152
- return { status: "unavailable", workspace: selected.workspace, unavailable: result };
3153
- }
3154
- const errors = validateCommandPlan(result, profile, detection.projectRoot);
3155
- if (errors.length > 0) {
3156
- return {
3157
- status: "unavailable",
3158
- workspace: selected.workspace,
3159
- unavailable: {
3160
- status: "unavailable",
3161
- profileId: profile.id,
3162
- workspaceId: selected.workspace.id,
3163
- operation: options.operation,
3164
- reason: `Generated plan failed validation: ${errors.join("; ")}`
3165
- }
3166
- };
3167
- }
3168
- return { status: "planned", workspace: selected.workspace, plan: Object.freeze(result) };
3169
- }
3170
- function validateCommandPlan(plan, profile, projectRoot) {
3171
- const errors = [];
3172
- if (plan.profileId !== profile.id) errors.push("profile id does not match");
3173
- if (!isInside2(plan.cwd, projectRoot)) errors.push("cwd is outside project root");
3174
- if (plan.args.length > MAX_ARGUMENTS) errors.push(`argument count exceeds ${MAX_ARGUMENTS}`);
3175
- if (plan.args.some((arg) => arg.length > MAX_ARGUMENT_LENGTH || /[\r\n\0]/.test(arg))) {
3176
- errors.push("arguments contain an invalid or oversized value");
3177
- }
3178
- if (!Number.isFinite(plan.timeoutMs) || plan.timeoutMs < 1 || plan.timeoutMs > 6e5) {
3179
- errors.push("timeout is outside 1..600000ms");
3180
- }
3181
- if (!Number.isFinite(plan.outputLimitBytes) || plan.outputLimitBytes < 1 || plan.outputLimitBytes > 1e6) {
3182
- errors.push("output limit is outside 1..1000000 bytes");
3183
- }
3184
- if (plan.kind === "internal") {
3185
- if (plan.command !== null || plan.args.length !== 0)
3186
- errors.push("internal plans cannot declare a command");
3187
- } else {
3188
- if (!plan.command || !profile.executables.includes(plan.command)) {
3189
- errors.push(`executable "${plan.command ?? ""}" is not allowlisted by the profile`);
3190
- }
3191
- }
3192
- if (Object.keys(plan.env).length > 0)
3193
- errors.push("Phase 1 plans cannot override environment variables");
3194
- return errors;
3195
- }
3196
- function selectWorkspace(candidates, options) {
3197
- if (candidates.length === 0) {
3198
- return {
3199
- status: "result",
3200
- result: {
3201
- status: "not_found",
3202
- reason: `No workspace supports ${options.operation}.`,
3203
- candidates: []
3204
- }
3205
- };
3206
- }
3207
- if (options.workspace) {
3208
- const requested = path6.isAbsolute(options.workspace) ? path6.resolve(options.workspace) : path6.resolve(options.projectRoot, options.workspace);
3209
- const matches = candidates.filter(
3210
- (item) => item.id === options.workspace || path6.resolve(item.root) === requested
3211
- );
3212
- if (matches.length === 1) return { status: "selected", workspace: matches[0] };
3213
- return {
3214
- status: "result",
3215
- result: {
3216
- status: "not_found",
3217
- reason: `Requested workspace "${options.workspace}" was not detected.`,
3218
- candidates: [...candidates]
3219
- }
3220
- };
3221
- }
3222
- if (options.target) {
3223
- const base = options.cwd ? path6.isAbsolute(options.cwd) ? path6.resolve(options.cwd) : path6.resolve(options.projectRoot, options.cwd) : path6.resolve(options.projectRoot);
3224
- const target = path6.isAbsolute(options.target) ? path6.resolve(options.target) : path6.resolve(base, options.target);
3225
- const targeted = candidates.filter((item) => item.evidence.some((evidence) => evidence.kind === "target")).sort(
3226
- (a, b) => workspaceDepth(b.root, options.projectRoot) - workspaceDepth(a.root, options.projectRoot) || compareCandidates(a, b)
3227
- );
3228
- if (targeted[0]) return { status: "selected", workspace: targeted[0] };
3229
- const containing = candidates.filter((item) => isInside2(target, item.root)).sort(
3230
- (a, b) => workspaceDepth(b.root, options.projectRoot) - workspaceDepth(a.root, options.projectRoot) || compareCandidates(a, b)
3231
- );
3232
- if (containing[0]) return { status: "selected", workspace: containing[0] };
3233
- }
3234
- const sorted = [...candidates].sort(compareCandidates);
3235
- const first = sorted[0];
3236
- const firstDepth = workspaceDepth(first.root, options.projectRoot);
3237
- const tied = sorted.filter(
3238
- (item) => item.confidence === first.confidence && workspaceDepth(item.root, options.projectRoot) === firstDepth
3239
- );
3240
- if (tied.length > 1) {
3241
- return {
3242
- status: "result",
3243
- result: {
3244
- status: "ambiguous",
3245
- reason: "Multiple workspaces have equal confidence; provide target, language, or workspace.",
3246
- candidates: tied
3247
- }
3248
- };
3249
- }
3250
- return { status: "selected", workspace: first };
3251
- }
3252
- function compareCandidates(a, b) {
3253
- return b.confidence - a.confidence || a.language.localeCompare(b.language) || a.root.localeCompare(b.root);
3254
- }
3255
- function workspaceDepth(workspaceRoot, projectRoot) {
3256
- const relative5 = path6.relative(path6.resolve(projectRoot), path6.resolve(workspaceRoot));
3257
- return relative5 === "" ? 0 : relative5.split(path6.sep).length;
3258
- }
3259
- function validateFilterOption(filter) {
3260
- if (filter === void 0) return;
3261
- if (filter.startsWith("-") || filter.includes(" --")) {
3262
- throw new Error(`Invalid test filter (parsed as a runner option): "${filter}"`);
3263
- }
3264
- if (filter.length > MAX_ARGUMENT_LENGTH || /[\r\n\0]/.test(filter)) {
3265
- throw new Error("Invalid test filter (oversized or contains a control character)");
3266
- }
3267
- }
3268
- function validateOperationOptions(operation, packages) {
3269
- if (!operation.startsWith("package-") || !packages) return;
3270
- for (const value of packages) {
3271
- if (!value || value.length > 214 || value.startsWith("-") || /[\r\n\0;&|`$<>\\]/.test(value)) {
3272
- throw new Error(`Invalid package identifier "${value}"`);
3273
- }
3274
- if (value.startsWith(".") || value.startsWith("/") || /^[A-Za-z]:/.test(value) || value.includes("://")) {
3275
- throw new Error(`Package paths and URLs are not supported: "${value}"`);
3276
- }
3277
- if (!PACKAGE_NAME_RE.test(value) && !COMPOSER_PACKAGE_RE.test(value) && !GO_MODULE_RE.test(value) && !PYTHON_PACKAGE_RE.test(value)) {
3278
- throw new Error(`Invalid package identifier "${value}"`);
3279
- }
3280
- }
3281
- }
3282
- async function canonicalTarget(cwd, target, projectRoot) {
3283
- const resolved = path6.isAbsolute(target) ? path6.resolve(target) : path6.resolve(cwd, target);
3284
- let real;
3285
- try {
3286
- real = await fs3.realpath(resolved);
3287
- } catch (error) {
3288
- if (error.code !== "ENOENT") throw error;
3289
- const parent = await fs3.realpath(path6.dirname(resolved));
3290
- real = path6.join(parent, path6.basename(resolved));
3291
- }
3292
- if (!isInside2(real, projectRoot)) throw new Error(`target is outside project root: ${target}`);
3293
- return real;
3294
- }
3295
- function isInside2(candidate, root) {
3296
- const relative5 = path6.relative(path6.resolve(root), path6.resolve(candidate));
3297
- return relative5 === "" || !relative5.startsWith("..") && !path6.isAbsolute(relative5);
3298
- }
3299
-
3300
- // src/languages/execute.ts
3301
- var MAX_INTERNAL_SOURCE_BYTES = 15e5;
3302
- async function* executeLanguagePlan(options) {
3303
- const { plan, workspace } = options;
3304
- if (options.signal.aborted) {
3305
- return terminalResult(options, "cancelled", options.signal.reason);
3306
- }
3307
- const profile = languageProfileRegistry.get(plan.profileId);
3308
- if (!profile) return unavailableResult(options, `Unknown language profile: ${plan.profileId}`);
3309
- if (workspace.id !== plan.workspaceId || workspace.language !== plan.profileId) {
3310
- return unavailableResult(options, "Plan and workspace identity do not match.");
3311
- }
3312
- const validation = validateCommandPlan(plan, profile, options.projectRoot);
3313
- if (validation.length > 0) {
3314
- return unavailableResult(options, `Plan failed execution validation: ${validation.join("; ")}`);
3315
- }
3316
- const containmentError = await validatePlanRealpaths(plan, options.projectRoot);
3317
- if (containmentError) return unavailableResult(options, containmentError);
3318
- if (plan.operation.startsWith("package-") || plan.network) {
3319
- return terminalNonPackageResult(
3320
- options,
3321
- "Package and network plans require the separate language_package tool (Phase 3)."
3322
- );
3323
- }
3324
- const startedAt = Date.now();
3325
- yield {
3326
- type: "log",
3327
- text: plan.kind === "internal" ? `Running ${plan.parser}\u2026` : `${plan.command} ${plan.args.join(" ")}`,
3328
- data: { language: plan.profileId, operation: plan.operation, workspace: workspace.root }
3329
- };
3330
- if (plan.kind === "internal") {
3331
- try {
3332
- return await executeInternal(options, startedAt);
3333
- } catch (error) {
3334
- return unavailableResult(options, error instanceof Error ? error.message : String(error));
3335
- }
3336
- }
3337
- const timeoutController = new AbortController();
3338
- const timer = setTimeout(
3339
- () => timeoutController.abort(new Error("language plan timed out")),
3340
- plan.timeoutMs
3341
- );
3342
- timer.unref?.();
3343
- const signal = AbortSignal.any([options.signal, timeoutController.signal]);
3344
- let spawned;
3345
- try {
3346
- const stream = spawnStream({
3347
- cmd: plan.command,
3348
- args: [...plan.args],
3349
- cwd: plan.cwd,
3350
- signal,
3351
- maxBytes: plan.outputLimitBytes
3352
- });
3353
- for (; ; ) {
3354
- const next = await stream.next();
3355
- if (next.done) {
3356
- spawned = next.value;
3357
- break;
3358
- }
3359
- yield next.value;
3360
- }
3361
- } catch (error) {
3362
- const timedOut2 = timeoutController.signal.aborted && !options.signal.aborted;
3363
- const cancelled2 = options.signal.aborted;
3364
- return {
3365
- status: timedOut2 ? "timed_out" : cancelled2 ? "cancelled" : "failed",
3366
- language: plan.profileId,
3367
- workspace,
3368
- plan,
3369
- exitCode: null,
3370
- durationMs: Date.now() - startedAt,
3371
- diagnostics: Object.freeze([]),
3372
- omittedDiagnostics: 0,
3373
- summary: emptySummary2(),
3374
- output: "",
3375
- truncated: false,
3376
- error: error instanceof Error ? error.message : String(error)
3377
- };
3378
- } finally {
3379
- clearTimeout(timer);
3380
- }
3381
- const parsed = parseLanguageDiagnostics(
3382
- plan.parser,
3383
- spawned.stdout,
3384
- spawned.stderr,
3385
- workspace.root
3386
- );
3387
- const timedOut = timeoutController.signal.aborted && !options.signal.aborted;
3388
- const cancelled = options.signal.aborted;
3389
- const spawnUnavailable = Boolean(
3390
- spawned.error && /ENOENT|not found|cannot find/i.test(spawned.error)
3391
- );
3392
- const status = timedOut ? "timed_out" : cancelled ? "cancelled" : spawnUnavailable ? "unavailable" : spawned.exitCode === 0 ? "passed" : "failed";
3393
- const raw = [spawned.stdout, spawned.stderr, spawned.error].filter(Boolean).join("\n");
3394
- return {
3395
- status,
3396
- language: plan.profileId,
3397
- workspace,
3398
- plan,
3399
- exitCode: spawned.exitCode,
3400
- durationMs: Date.now() - startedAt,
3401
- diagnostics: parsed.diagnostics,
3402
- omittedDiagnostics: parsed.omitted,
3403
- summary: parsed.summary,
3404
- output: normalizeCommandOutput(raw, { maxBytes: plan.outputLimitBytes }),
3405
- truncated: spawned.truncated,
3406
- ...spawned.spoolPath ? { spoolPath: spawned.spoolPath } : {},
3407
- ...spawned.error ? { error: spawned.error } : {}
3408
- };
3409
- }
3410
- async function executeInternal(options, startedAt) {
3411
- const target = options.plan.evidence.find((item) => item.kind === "target")?.path;
3412
- if (!target) return unavailableResult(options, "Internal syntax plan has no target evidence.");
3413
- const safeTarget = await assertContainedFile(target, options.projectRoot);
3414
- const stat5 = await fs4.stat(safeTarget);
3415
- if (stat5.size > MAX_INTERNAL_SOURCE_BYTES) {
3416
- return unavailableResult(
3417
- options,
3418
- `Internal syntax target exceeds ${MAX_INTERNAL_SOURCE_BYTES} bytes.`
3419
- );
3420
- }
3421
- const source = await fs4.readFile(safeTarget, "utf8");
3422
- const parsed = await diagnosticsForInternalSyntax(options.plan.profileId, safeTarget, source);
3423
- return {
3424
- status: parsed.summary.errors > 0 ? "failed" : "passed",
3425
- language: options.plan.profileId,
3426
- workspace: options.workspace,
3427
- plan: options.plan,
3428
- exitCode: parsed.summary.errors > 0 ? 1 : 0,
3429
- durationMs: Date.now() - startedAt,
3430
- diagnostics: parsed.diagnostics,
3431
- omittedDiagnostics: parsed.omitted,
3432
- summary: parsed.summary,
3433
- output: parsed.summary.errors > 0 ? `${parsed.summary.errors} syntax error(s) found.` : "Syntax check passed.",
3434
- truncated: false
3435
- };
3436
- }
3437
- async function validatePlanRealpaths(plan, projectRoot) {
3438
- const realRoot = await fs4.realpath(projectRoot);
3439
- let realCwd;
3440
- try {
3441
- realCwd = await fs4.realpath(plan.cwd);
3442
- } catch (error) {
3443
- return `Plan cwd is unavailable: ${error instanceof Error ? error.message : String(error)}`;
3444
- }
3445
- if (!isRealInside(realCwd, realRoot)) return "Plan cwd resolves outside project root.";
3446
- for (const argument of plan.args) {
3447
- if (!path7.isAbsolute(argument)) continue;
3448
- try {
3449
- const realArgument = await fs4.realpath(argument);
3450
- if (!isRealInside(realArgument, realRoot)) {
3451
- return `Plan argument resolves outside project root: ${argument}`;
3452
- }
3453
- } catch (error) {
3454
- if (error.code !== "ENOENT") {
3455
- return `Plan argument could not be resolved safely: ${argument}`;
3456
- }
3457
- }
3458
- }
3459
- return void 0;
3460
- }
3461
- function isRealInside(candidate, root) {
3462
- const relative5 = path7.relative(root, candidate);
3463
- return relative5 === "" || !relative5.startsWith("..") && !path7.isAbsolute(relative5);
3464
- }
3465
- async function assertContainedFile(candidate, projectRoot) {
3466
- const realRoot = await fs4.realpath(projectRoot);
3467
- const realTarget = await fs4.realpath(candidate);
3468
- const relative5 = path7.relative(realRoot, realTarget);
3469
- if (relative5.startsWith("..") || path7.isAbsolute(relative5)) {
3470
- throw new Error(`Internal syntax target resolves outside project root: ${candidate}`);
3471
- }
3472
- return realTarget;
3473
- }
3474
- function terminalResult(options, status, reason) {
3475
- const message = reason instanceof Error ? reason.message : reason ? String(reason) : status;
3476
- return {
3477
- status,
3478
- language: options.plan.profileId,
3479
- workspace: options.workspace,
3480
- plan: options.plan,
3481
- exitCode: null,
3482
- durationMs: 0,
3483
- diagnostics: Object.freeze([]),
3484
- omittedDiagnostics: 0,
3485
- summary: emptySummary2(),
3486
- output: "",
3487
- truncated: false,
3488
- error: message
3489
- };
3490
- }
3491
- function unavailableResult(options, reason) {
3492
- return {
3493
- status: "unavailable",
3494
- language: options.plan.profileId,
3495
- workspace: options.workspace,
3496
- plan: options.plan,
3497
- exitCode: null,
3498
- durationMs: 0,
3499
- diagnostics: Object.freeze([]),
3500
- omittedDiagnostics: 0,
3501
- summary: emptySummary2(),
3502
- output: reason,
3503
- truncated: false,
3504
- error: reason
3505
- };
3506
- }
3507
- function emptySummary2() {
3508
- return { errors: 0, warnings: 0, infos: 0 };
3509
- }
3510
- function terminalNonPackageResult(options, reason) {
3511
- return {
3512
- status: "unavailable",
3513
- language: options.plan.profileId,
3514
- workspace: options.workspace,
3515
- plan: options.plan,
3516
- exitCode: null,
3517
- durationMs: 0,
3518
- diagnostics: Object.freeze([]),
3519
- omittedDiagnostics: 0,
3520
- summary: emptySummary2(),
3521
- output: reason,
3522
- truncated: false,
3523
- error: reason
3524
- };
3525
- }
3526
-
3527
- // src/languages/legacy-bridge.ts
3528
- var NON_JS_MARKERS = [
3529
- { filename: "go.mod", language: "go" },
3530
- { filename: "go.work", language: "go" },
3531
- { filename: "Cargo.toml", language: "rust" },
3532
- { filename: "composer.json", language: "php" }
3533
- ];
3534
- var NON_JS_SUFFIXES = [
3535
- { suffix: ".csproj", language: "csharp" },
3536
- { suffix: ".fsproj", language: "csharp" }
3537
- ];
3538
- async function detectNonJsEcosystem(cwd, projectRoot) {
3539
- try {
3540
- let dir = path8.resolve(cwd);
3541
- const root = path8.resolve(projectRoot);
3542
- for (let depth = 0; depth <= 4 && dir.startsWith(root); depth++) {
3543
- for (const marker of NON_JS_MARKERS) {
3544
- try {
3545
- const s = await fs5.stat(path8.join(dir, marker.filename));
3546
- if (s.isFile()) return marker.language;
3547
- } catch {
3548
- }
3549
- }
3550
- try {
3551
- const entries = await fs5.readdir(dir);
3552
- for (const entry of entries) {
3553
- for (const suffix of NON_JS_SUFFIXES) {
3554
- if (entry.toLowerCase().endsWith(suffix.suffix)) return suffix.language;
3555
- }
3556
- }
3557
- } catch {
3558
- }
3559
- if (dir === root) break;
3560
- dir = path8.dirname(dir);
3561
- }
3562
- } catch {
3563
- }
3564
- return null;
3565
- }
3566
- async function tryLegacyCodeOperation(operation, ctx) {
3567
- const language = await detectNonJsEcosystem(ctx.cwd, ctx.projectRoot);
3568
- if (!language) return null;
3569
- const planResult = await planLanguageOperation({
3570
- projectRoot: ctx.projectRoot,
3571
- cwd: ctx.cwd,
3572
- operation,
3573
- language,
3574
- ...ctx.target ? { target: ctx.target } : {},
3575
- signal: ctx.signal
3576
- });
3577
- if (planResult.status !== "planned") return null;
3578
- const runner = executeLanguagePlan({
3579
- projectRoot: ctx.projectRoot,
3580
- workspace: planResult.workspace,
3581
- plan: planResult.plan,
3582
- signal: ctx.signal
3583
- });
3584
- for (; ; ) {
3585
- const next = await runner.next();
3586
- if (next.done) return { language, run: next.value };
3587
- }
3588
- }
3589
-
3590
- // src/lint.ts
3591
- var lintTool = {
3592
- name: "lint",
3593
- category: "Code Quality",
3594
- description: "Run the project linter (primarily Biome in this repo). Detects style violations, potential bugs, and formatting issues.",
3595
- usageHint: "RUN OFTEN DURING DEVELOPMENT:\n\n- `fix: true` will automatically correct what it can.\n- Target specific files or globs when you only want to check part of the project.\nThis is a fast and important quality gate. Use it before typecheck in most workflows.",
3596
- permission: "confirm",
3597
- mutating: false,
3598
- timeoutMs: 6e4,
3599
- capabilities: ["shell.restricted"],
3600
- icon: "code",
3601
- inputSchema: {
3602
- type: "object",
3603
- properties: {
3604
- files: {
3605
- type: "string",
3606
- description: 'Files/patterns: single path, comma-separated list, or glob (e.g. "src/**/*.ts")'
3607
- },
3608
- fix: { type: "boolean", description: "Auto-fix fixable issues (default: false)" },
3609
- linter: {
3610
- type: "string",
3611
- enum: ["biome", "eslint", "tslint", "auto"],
3612
- description: "Linter to use (default: auto-detect)"
3613
- },
3614
- cwd: { type: "string", description: "Working directory (default: cwd)" }
3615
- }
3616
- },
3617
- async execute(input, ctx, opts) {
3618
- let final;
3619
- const executeStream = lintTool.executeStream;
3620
- if (!executeStream) throw new Error("lintTool: stream execution unavailable");
3621
- for await (const ev of executeStream(input, ctx, opts)) {
3622
- if (ev.type === "final") final = ev.output;
3623
- }
3624
- if (!final) throw new Error("lint: stream ended without final event");
3625
- return final;
3626
- },
3627
- async *executeStream(input, ctx, opts) {
3628
- const cwd = input.cwd ? await safeResolveReal(input.cwd, ctx) : ctx.cwd;
3629
- const linter = input.linter ?? "auto";
3630
- if (linter === "auto" && !input.files) {
3631
- const bridge = await tryLegacyCodeOperation("lint", {
3632
- cwd,
3633
- projectRoot: ctx.projectRoot,
3634
- signal: opts.signal
3635
- });
3636
- if (bridge?.run) {
3637
- const run = bridge.run;
3638
- yield {
3639
- type: "final",
3640
- output: {
3641
- linter: bridge.language,
3642
- files_checked: 0,
3643
- errors: run.summary.errors,
3644
- warnings: run.summary.warnings,
3645
- output: normalizeCommandOutput(run.output || run.error || ""),
3646
- fix_applied: false,
3647
- truncated: run.truncated
3648
- }
3649
- };
3650
- return;
3651
- }
3652
- }
3653
- const detected = linter === "auto" ? await detectLinter(cwd) : linter;
3654
- if (!detected) {
3655
- yield {
3656
- type: "final",
3657
- output: {
3658
- linter: "none",
3659
- files_checked: 0,
3660
- errors: 0,
3661
- warnings: 0,
3662
- output: "No linter found (biome.json, .eslintrc, tslint.json)",
3663
- fix_applied: false,
3664
- truncated: false
3665
- }
3666
- };
3667
- return;
3668
- }
3669
- yield { type: "log", text: `Running ${detected}\u2026`, data: { linter: detected } };
3670
- const args = ["lint"];
3671
- if (input.fix) args.push("--write");
3672
- if (input.files) {
3673
- const files = Array.isArray(input.files) ? input.files : input.files.split(",");
3674
- args.push("--", ...files.map((f) => f.trim()));
3675
- }
3676
- const cmd = detected === "biome" ? "biome" : detected;
3677
- const result = yield* spawnStream({ cmd, args, cwd, signal: opts.signal, maxBytes: 1e5 });
3678
- const errors = [...result.stdout.matchAll(/\berror\b/gi)].length;
3679
- const warnings = [...result.stdout.matchAll(/\bwarning\b/gi)].length;
3680
- yield {
3681
- type: "final",
3682
- output: {
3683
- linter: detected,
3684
- files_checked: input.files ? Array.isArray(input.files) ? input.files.length : input.files.split(",").length : 0,
3685
- errors,
3686
- warnings,
3687
- output: normalizeCommandOutput(result.stdout),
3688
- fix_applied: input.fix ?? false,
3689
- truncated: result.truncated
3690
- }
3691
- };
3692
- }
3693
- };
3694
- async function detectLinter(cwd) {
3695
- const { stat: stat5 } = await import("node:fs/promises");
3696
- const checks = ["biome.json", ".eslintrc.json", "tslint.json", ".eslintrc.js", "tsconfig.json"];
3697
- for (const f of checks) {
3698
- try {
3699
- await stat5(`${cwd}/${f}`);
3700
- if (f.includes("biome")) return "biome";
3701
- if (f.includes("eslint")) return "eslint";
3702
- if (f.includes("tslint")) return "tslint";
3703
- } catch {
3704
- }
3705
- }
3706
- return "biome";
3707
- }
2
+ lintTool
3
+ } from "./chunk-DIJKHSUO.js";
4
+ import "./chunk-NHA6BEIH.js";
5
+ import "./chunk-DPL47QGS.js";
6
+ import "./chunk-MAN26PZ5.js";
7
+ import "./chunk-2TFQDEPU.js";
8
+ import "./chunk-3PVYQFRQ.js";
9
+ import "./chunk-HFXSNKCV.js";
10
+ import "./chunk-V43EQ6VR.js";
11
+ import "./chunk-D33S4RQG.js";
3708
12
  export {
3709
13
  lintTool
3710
14
  };