@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/audit.js CHANGED
@@ -1,4059 +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
- async function detectPackageManager(cwd, stopAt) {
1054
- let dir = path3.resolve(cwd);
1055
- const stop = stopAt ? path3.resolve(stopAt) : dir;
1056
- for (; ; ) {
1057
- const found = await detectPackageManagerInDir(dir);
1058
- if (found) return found;
1059
- if (dir === stop) break;
1060
- const parent = path3.dirname(dir);
1061
- const relParent = path3.relative(stop, parent);
1062
- if (parent === dir || relParent.startsWith("..") || path3.isAbsolute(relParent)) break;
1063
- dir = parent;
1064
- }
1065
- return "npm";
1066
- }
1067
- async function detectPackageManagerInDir(dir) {
1068
- const fs6 = await import("node:fs/promises");
1069
- try {
1070
- const raw = await fs6.readFile(path3.join(dir, "package.json"), "utf8");
1071
- const declared = JSON.parse(raw).packageManager;
1072
- if (typeof declared === "string") {
1073
- const name = declared.split("@")[0] ?? "";
1074
- if (name === "pnpm" || name === "yarn") return name;
1075
- if (name === "npm" || name === "bun") return "npm";
1076
- }
1077
- } catch {
1078
- }
1079
- const lockfiles = [
1080
- ["pnpm-lock.yaml", "pnpm"],
1081
- ["yarn.lock", "yarn"],
1082
- ["bun.lockb", "npm"],
1083
- ["bun.lock", "npm"],
1084
- ["package-lock.json", "npm"],
1085
- ["npm-shrinkwrap.json", "npm"]
1086
- ];
1087
- for (const [file, manager] of lockfiles) {
1088
- try {
1089
- await fs6.stat(`${dir}/${file}`);
1090
- return manager;
1091
- } catch {
1092
- }
1093
- }
1094
- return null;
1095
- }
1096
- function resolvePath(input, ctx) {
1097
- return path3.isAbsolute(input) ? path3.normalize(input) : path3.resolve(ctx.workingDir ?? ctx.cwd, input);
1098
- }
1099
- function allowedRoots(ctx) {
1100
- return [path3.resolve(ctx.projectRoot), path3.resolve(Core.wstackGlobalRoot())];
1101
- }
1102
- function isInsideAny(target, roots) {
1103
- return roots.some((root) => {
1104
- const rel = path3.relative(root, target);
1105
- return rel === "" || !rel.startsWith("..") && !path3.isAbsolute(rel);
1106
- });
1107
- }
1108
- function ensureInsideRoot(absPath, ctx) {
1109
- const target = path3.resolve(absPath);
1110
- if (ctx.allowOutsideProjectRoot) return target;
1111
- if (isInsideAny(target, allowedRoots(ctx))) return target;
1112
- throw new Error(`Path "${absPath}" is outside project root "${path3.resolve(ctx.projectRoot)}"`);
1113
- }
1114
- function safeResolve(input, ctx) {
1115
- return ensureInsideRoot(resolvePath(input, ctx), ctx);
1116
- }
1117
- async function resolveRealInsideRoot(absPath, ctx) {
1118
- if (ctx.allowOutsideProjectRoot) return absPath;
1119
- const realRoots = await Promise.all(
1120
- allowedRoots(ctx).map((r) => fsp2.realpath(r).catch(() => path3.resolve(r)))
1121
- );
1122
- let probe = absPath;
1123
- const pendingTail = [];
1124
- for (; ; ) {
1125
- let real;
1126
- try {
1127
- real = await fsp2.realpath(probe);
1128
- } catch (err) {
1129
- if (err.code === "ENOENT") {
1130
- const parent = path3.dirname(probe);
1131
- if (parent === probe) return absPath;
1132
- pendingTail.unshift(path3.basename(probe));
1133
- probe = parent;
1134
- continue;
1135
- }
1136
- throw err;
1137
- }
1138
- const candidate = pendingTail.length > 0 ? path3.join(real, ...pendingTail) : real;
1139
- if (isInsideAny(candidate, realRoots)) {
1140
- return candidate;
1141
- }
1142
- throw new Error(
1143
- `Path "${absPath}" resolves through a symlink outside project root "${realRoots[0]}"`
1144
- );
1145
- }
1146
- }
1147
- async function safeResolveReal(input, ctx) {
1148
- const abs = safeResolve(input, ctx);
1149
- return await resolveRealInsideRoot(abs, ctx);
1150
- }
1151
- var COMMAND_OUTPUT_MAX_BYTES = 32768;
1152
- var REPEAT_RUN_THRESHOLD = 3;
1153
- function collapseCarriageReturns(text) {
1154
- const lf = text.replace(/\r\n/g, "\n");
1155
- if (!lf.includes("\r")) return lf;
1156
- return lf.split("\n").map((line) => line.includes("\r") ? line.slice(line.lastIndexOf("\r") + 1) : line).join("\n");
1157
- }
1158
- function collapseConsecutiveDuplicates(text, minRun = REPEAT_RUN_THRESHOLD) {
1159
- const lines = text.split("\n");
1160
- const out = [];
1161
- let i = 0;
1162
- while (i < lines.length) {
1163
- let j = i + 1;
1164
- while (j < lines.length && lines[j] === lines[i]) j++;
1165
- const run = j - i;
1166
- if (run >= minRun) {
1167
- out.push(lines[i], `\u2026 \u27E8repeated ${run}\xD7\u27E9`);
1168
- } else {
1169
- for (let k = i; k < j; k++) out.push(lines[k]);
1170
- }
1171
- i = j;
1172
- }
1173
- return out.join("\n");
1174
- }
1175
- function takeHeadBytes(s, maxBytes) {
1176
- if (maxBytes <= 0) return "";
1177
- if (Buffer.byteLength(s, "utf8") <= maxBytes) return s;
1178
- let lo = 0;
1179
- let hi = s.length;
1180
- while (lo < hi) {
1181
- const mid = Math.ceil((lo + hi) / 2);
1182
- if (Buffer.byteLength(s.slice(0, mid), "utf8") <= maxBytes) lo = mid;
1183
- else hi = mid - 1;
1184
- }
1185
- return s.slice(0, lo);
1186
- }
1187
- function takeTailBytes(s, maxBytes) {
1188
- if (maxBytes <= 0) return "";
1189
- if (Buffer.byteLength(s, "utf8") <= maxBytes) return s;
1190
- let lo = 0;
1191
- let hi = s.length;
1192
- while (lo < hi) {
1193
- const mid = Math.ceil((lo + hi) / 2);
1194
- if (Buffer.byteLength(s.slice(s.length - mid), "utf8") <= maxBytes) lo = mid;
1195
- else hi = mid - 1;
1196
- }
1197
- return s.slice(s.length - lo);
1198
- }
1199
- function truncateHeadTail(s, maxBytes) {
1200
- const total = Buffer.byteLength(s, "utf8");
1201
- if (total <= maxBytes) return s;
1202
- const MARKER_RESERVE = 64;
1203
- const avail = Math.max(0, maxBytes - MARKER_RESERVE);
1204
- const headBudget = Math.floor(avail * 0.45);
1205
- const head = takeHeadBytes(s, headBudget);
1206
- const tail = takeTailBytes(s, avail - Buffer.byteLength(head, "utf8"));
1207
- const kept = Buffer.byteLength(head, "utf8") + Buffer.byteLength(tail, "utf8");
1208
- return `${head}
1209
- \u2026[truncated ${total - kept} bytes]\u2026
1210
- ${tail}`;
1211
- }
1212
- function normalizeCommandOutput(raw, opts = {}) {
1213
- if (!raw) return raw;
1214
- let text = Core.stripAnsi(raw);
1215
- text = collapseCarriageReturns(text);
1216
- text = text.replace(/[ \t]+$/gm, "");
1217
- text = collapseConsecutiveDuplicates(text);
1218
- text = text.replace(/\n{3,}/g, "\n\n");
1219
- return truncateHeadTail(text, opts.maxBytes ?? COMMAND_OUTPUT_MAX_BYTES);
1220
- }
1221
-
1222
- // src/languages/legacy-bridge.ts
1223
- import * as fs5 from "node:fs/promises";
1224
- import * as path8 from "node:path";
1225
-
1226
- // src/languages/detect.ts
1227
- import { createHash } from "node:crypto";
1228
- import * as fs2 from "node:fs/promises";
1229
- import * as path4 from "node:path";
1230
-
1231
- // src/languages/profile-helpers.ts
1232
- var DEFAULT_TIMEOUT_MS = 12e4;
1233
- var DEFAULT_OUTPUT_LIMIT_BYTES = 2e5;
1234
- function processPlan(ctx, operation, command, args, options) {
1235
- return {
1236
- profileId: ctx.workspace.language,
1237
- workspaceId: ctx.workspace.id,
1238
- operation,
1239
- kind: "process",
1240
- command,
1241
- args: Object.freeze([...args]),
1242
- cwd: ctx.workspace.root,
1243
- env: Object.freeze({}),
1244
- timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
1245
- outputLimitBytes: DEFAULT_OUTPUT_LIMIT_BYTES,
1246
- mutating: options.mutating ?? false,
1247
- network: options.network ?? false,
1248
- executesProjectCode: options.executesProjectCode ?? false,
1249
- reason: options.reason,
1250
- evidence: ctx.workspace.evidence,
1251
- parser: options.parser
1252
- };
1253
- }
1254
- function internalPlan(ctx, operation, parser, reason) {
1255
- return {
1256
- profileId: ctx.workspace.language,
1257
- workspaceId: ctx.workspace.id,
1258
- operation,
1259
- kind: "internal",
1260
- command: null,
1261
- args: Object.freeze([]),
1262
- cwd: ctx.workspace.root,
1263
- env: Object.freeze({}),
1264
- timeoutMs: 5e3,
1265
- outputLimitBytes: 32768,
1266
- mutating: false,
1267
- network: false,
1268
- executesProjectCode: false,
1269
- reason,
1270
- evidence: ctx.workspace.evidence,
1271
- parser
1272
- };
1273
- }
1274
- function unavailable(ctx, operation, reason) {
1275
- return {
1276
- status: "unavailable",
1277
- profileId: ctx.workspace.language,
1278
- workspaceId: ctx.workspace.id,
1279
- operation,
1280
- reason
1281
- };
1282
- }
1283
- function packageNames(ctx) {
1284
- return ctx.options.packages ?? [];
1285
- }
1286
-
1287
- // src/languages/profiles/additional.ts
1288
- var IGNORES = Object.freeze([
1289
- ".git",
1290
- ".wrongstack",
1291
- "node_modules",
1292
- "vendor",
1293
- "dist",
1294
- "build",
1295
- "coverage"
1296
- ]);
1297
- function pythonProfile() {
1298
- return {
1299
- id: "python",
1300
- displayName: "Python",
1301
- extensions: Object.freeze([".py", ".pyi"]),
1302
- lspLanguageIds: Object.freeze(["python"]),
1303
- detectors: Object.freeze([
1304
- { kind: "config", filename: "pyproject.toml", weight: 90 },
1305
- { kind: "config", filename: "setup.py", weight: 70 },
1306
- { kind: "config", filename: "setup.cfg", weight: 60 },
1307
- { kind: "manifest", filename: "requirements.txt", weight: 55 },
1308
- { kind: "manifest", filename: "Pipfile", weight: 50 },
1309
- { kind: "lockfile", filename: "poetry.lock", weight: 30 },
1310
- { kind: "lockfile", filename: "Pipfile.lock", weight: 30 },
1311
- { kind: "lockfile", filename: "uv.lock", weight: 30 }
1312
- ]),
1313
- ignoredDirectories: IGNORES,
1314
- packageManagers: Object.freeze(["pip", "poetry", "pipenv", "uv"]),
1315
- executables: Object.freeze([
1316
- "python",
1317
- "python3",
1318
- "pip",
1319
- "pip3",
1320
- "poetry",
1321
- "pipenv",
1322
- "uv",
1323
- "ruff",
1324
- "black",
1325
- "pytest",
1326
- "mypy",
1327
- "pyright"
1328
- ]),
1329
- operations: Object.freeze({
1330
- syntax: async (ctx) => {
1331
- const py = ctx.options.target ? "python3" : "python3";
1332
- return ctx.options.target ? processPlan(ctx, "syntax", py, ["-m", "py_compile", ctx.options.target], {
1333
- parser: "python",
1334
- reason: "Compile the target file to check for syntax errors."
1335
- }) : unavailable(ctx, "syntax", "Python syntax check requires an explicit target file.");
1336
- },
1337
- semantic: async (ctx) => processPlan(ctx, "semantic", "mypy", [".", "--no-error-summary"], {
1338
- parser: "mypy",
1339
- reason: "Run mypy type checking on the workspace.",
1340
- executesProjectCode: true
1341
- }),
1342
- lint: async (ctx) => processPlan(ctx, "lint", "ruff", ["check", "."], {
1343
- parser: "ruff",
1344
- reason: "Run the Ruff linter on the workspace."
1345
- }),
1346
- "format-check": async (ctx) => processPlan(ctx, "format-check", "ruff", ["format", "--check", "."], {
1347
- parser: "ruff",
1348
- reason: "Check Python formatting without writing files."
1349
- }),
1350
- "format-write": async (ctx) => processPlan(ctx, "format-write", "ruff", ["format", "."], {
1351
- parser: "ruff",
1352
- reason: "Format Python source files.",
1353
- mutating: true
1354
- }),
1355
- test: async (ctx) => processPlan(
1356
- ctx,
1357
- "test",
1358
- "pytest",
1359
- [...ctx.options.filter ? ["-k", ctx.options.filter] : [], "."],
1360
- {
1361
- parser: "pytest",
1362
- reason: ctx.options.filter ? "Run filtered Python tests." : "Run all Python tests.",
1363
- mutating: true,
1364
- executesProjectCode: true
1365
- }
1366
- ),
1367
- build: async (ctx) => unavailable(ctx, "build", "Python is interpreted; use semantic or test instead."),
1368
- "debug-compile": async (ctx) => processPlan(ctx, "debug-compile", "mypy", [".", "--no-error-summary"], {
1369
- parser: "mypy",
1370
- reason: "Collect mypy type diagnostics.",
1371
- executesProjectCode: true
1372
- }),
1373
- "package-install": async (ctx) => processPlan(ctx, "package-install", "pip", ["install", "--no-cache-dir"], {
1374
- parser: "package-text",
1375
- reason: "Install dependencies from requirements.",
1376
- mutating: true,
1377
- network: true
1378
- }),
1379
- "package-add": async (ctx) => {
1380
- const names = packageNames(ctx);
1381
- return names.length === 0 ? unavailable(ctx, "package-add", "At least one package name is required.") : processPlan(ctx, "package-add", "pip", ["install", ...names], {
1382
- parser: "package-text",
1383
- reason: "Install specified Python packages.",
1384
- mutating: true,
1385
- network: true
1386
- });
1387
- },
1388
- "package-remove": async (ctx) => {
1389
- const names = packageNames(ctx);
1390
- return names.length === 0 ? unavailable(ctx, "package-remove", "At least one package name is required.") : processPlan(ctx, "package-remove", "pip", ["uninstall", "--yes", ...names], {
1391
- parser: "package-text",
1392
- reason: "Remove validated Python packages.",
1393
- mutating: true
1394
- });
1395
- },
1396
- "package-audit": async (ctx) => processPlan(ctx, "package-audit", "pip", ["audit"], {
1397
- parser: "pip-audit",
1398
- reason: "Audit Python dependencies for vulnerabilities.",
1399
- network: true
1400
- }),
1401
- run: async (ctx) => {
1402
- const entries = ["main.py", "app.py", "__main__.py", "manage.py"];
1403
- const first = (await Promise.all(
1404
- entries.map((name) => ctx.pathExists(name).then((ok) => ok ? name : void 0))
1405
- )).find(Boolean);
1406
- const args = first ? [first] : [];
1407
- return processPlan(ctx, "run", "python3", args, {
1408
- parser: "command-text",
1409
- reason: first ? `Run the Python entry point ${first}.` : "Run the Python project (no common entry point detected \u2014 add the module path manually).",
1410
- executesProjectCode: true,
1411
- mutating: true
1412
- });
1413
- }
1414
- })
1415
- };
1416
- }
1417
- function hasGradleEvidence(ctx) {
1418
- return ctx.workspace.evidence.some(
1419
- (e) => e.kind === "manifest" && (e.value === "build.gradle" || e.value === "build.gradle.kts" || e.value === "settings.gradle") || e.kind === "lockfile" && e.value === "gradle.lockfile"
1420
- );
1421
- }
1422
- async function gradleRunner(ctx) {
1423
- if (await ctx.pathExists("gradlew")) return "gradlew";
1424
- return "gradle";
1425
- }
1426
- function javaProfile() {
1427
- return {
1428
- id: "java",
1429
- displayName: "Java / Kotlin",
1430
- extensions: Object.freeze([".java", ".kt", ".kts", ".scala"]),
1431
- lspLanguageIds: Object.freeze(["java", "kotlin"]),
1432
- detectors: Object.freeze([
1433
- { kind: "manifest", filename: "pom.xml", weight: 90 },
1434
- { kind: "manifest", filename: "build.gradle", weight: 85 },
1435
- { kind: "manifest", filename: "build.gradle.kts", weight: 85 },
1436
- { kind: "manifest", filename: "settings.gradle", weight: 50 },
1437
- { kind: "lockfile", filename: "gradle.lockfile", weight: 30 }
1438
- ]),
1439
- ignoredDirectories: IGNORES,
1440
- packageManagers: Object.freeze(["maven", "gradle"]),
1441
- executables: Object.freeze(["mvn", "gradle", "gradlew", "java", "kotlinc"]),
1442
- operations: Object.freeze({
1443
- semantic: async (ctx) => {
1444
- const isGradle = hasGradleEvidence(ctx);
1445
- const runner = isGradle ? await gradleRunner(ctx) : "mvn";
1446
- const args = isGradle ? ["compileJava"] : ["compile", "-q"];
1447
- const reason = isGradle ? "Compile the Gradle project." : "Compile the Maven project.";
1448
- return processPlan(ctx, "semantic", runner, args, {
1449
- parser: isGradle ? "gradle" : "maven",
1450
- reason,
1451
- mutating: true,
1452
- executesProjectCode: true
1453
- });
1454
- },
1455
- lint: async (ctx) => unavailable(
1456
- ctx,
1457
- "lint",
1458
- "Java linting requires a configured checkstyle or spotbugs plugin."
1459
- ),
1460
- "format-check": async (ctx) => unavailable(
1461
- ctx,
1462
- "format-check",
1463
- "Java formatting check requires a configured spotless or google-java-format plugin."
1464
- ),
1465
- test: async (ctx) => {
1466
- const isGradle = hasGradleEvidence(ctx);
1467
- const runner = isGradle ? await gradleRunner(ctx) : "mvn";
1468
- const args = isGradle ? ["test"] : ["test", "-q"];
1469
- const reason = isGradle ? "Run Gradle tests." : "Run Maven tests.";
1470
- return processPlan(ctx, "test", runner, args, {
1471
- parser: isGradle ? "gradle" : "maven",
1472
- reason,
1473
- mutating: true,
1474
- executesProjectCode: true
1475
- });
1476
- },
1477
- build: async (ctx) => {
1478
- const isGradle = hasGradleEvidence(ctx);
1479
- const runner = isGradle ? await gradleRunner(ctx) : "mvn";
1480
- const args = isGradle ? ["build"] : ["package", "-q", "-DskipTests"];
1481
- const reason = isGradle ? "Build the Gradle project." : "Build the Maven project, skipping tests.";
1482
- return processPlan(ctx, "build", runner, args, {
1483
- parser: isGradle ? "gradle" : "maven",
1484
- reason,
1485
- mutating: true,
1486
- executesProjectCode: true
1487
- });
1488
- },
1489
- run: async (ctx) => {
1490
- if (!hasGradleEvidence(ctx))
1491
- return unavailable(
1492
- ctx,
1493
- "run",
1494
- "Maven run requires exec-maven-plugin configuration. Use `mvn exec:java -q` manually."
1495
- );
1496
- const runner = await gradleRunner(ctx);
1497
- return processPlan(ctx, "run", runner, ["run"], {
1498
- parser: "command-text",
1499
- reason: `Run the Gradle project entry point via ${runner}.`,
1500
- executesProjectCode: true,
1501
- mutating: true
1502
- });
1503
- },
1504
- "package-install": async (ctx) => unavailable(
1505
- ctx,
1506
- "package-install",
1507
- "JVM dependency installation happens through build or dependency:get."
1508
- ),
1509
- "package-add": async (ctx) => {
1510
- const names = packageNames(ctx);
1511
- 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]}`], {
1512
- parser: "maven",
1513
- reason: "Resolve and fetch a Maven dependency.",
1514
- mutating: true,
1515
- network: true
1516
- });
1517
- }
1518
- })
1519
- };
1520
- }
1521
- function rubyProfile() {
1522
- return {
1523
- id: "ruby",
1524
- displayName: "Ruby",
1525
- extensions: Object.freeze([".rb"]),
1526
- lspLanguageIds: Object.freeze(["ruby"]),
1527
- detectors: Object.freeze([
1528
- { kind: "manifest", filename: "Gemfile", weight: 90 },
1529
- { kind: "config", filename: ".ruby-version", weight: 40 },
1530
- { kind: "lockfile", filename: "Gemfile.lock", weight: 30 }
1531
- ]),
1532
- ignoredDirectories: IGNORES,
1533
- packageManagers: Object.freeze(["gem", "bundler"]),
1534
- executables: Object.freeze(["ruby", "gem", "bundle", "rubocop", "rspec"]),
1535
- operations: Object.freeze({
1536
- syntax: async (ctx) => ctx.options.target ? processPlan(ctx, "syntax", "ruby", ["-c", ctx.options.target], {
1537
- parser: "ruby",
1538
- reason: "Check the target Ruby file for syntax errors."
1539
- }) : unavailable(ctx, "syntax", "Ruby syntax check requires an explicit target file."),
1540
- lint: async (ctx) => processPlan(ctx, "lint", "rubocop", ["--format=json"], {
1541
- parser: "rubocop",
1542
- reason: "Run RuboCop linter.",
1543
- executesProjectCode: true
1544
- }),
1545
- "format-write": async (ctx) => processPlan(ctx, "format-write", "rubocop", ["--auto-correct"], {
1546
- parser: "rubocop",
1547
- reason: "Auto-correct RuboCop violations.",
1548
- mutating: true,
1549
- executesProjectCode: true
1550
- }),
1551
- test: async (ctx) => processPlan(ctx, "test", "rspec", [], {
1552
- parser: "rspec",
1553
- reason: "Run the RSpec test suite.",
1554
- mutating: true,
1555
- executesProjectCode: true
1556
- }),
1557
- "package-install": async (ctx) => processPlan(ctx, "package-install", "bundle", ["install"], {
1558
- parser: "package-text",
1559
- reason: "Install Ruby gem dependencies.",
1560
- mutating: true,
1561
- network: true,
1562
- executesProjectCode: true
1563
- }),
1564
- "package-add": async (ctx) => {
1565
- const names = packageNames(ctx);
1566
- return names.length === 0 ? unavailable(ctx, "package-add", "At least one gem name is required.") : processPlan(ctx, "package-add", "gem", ["install", ...names], {
1567
- parser: "package-text",
1568
- reason: "Install specified Ruby gems.",
1569
- mutating: true,
1570
- network: true
1571
- });
1572
- },
1573
- "package-audit": async (ctx) => processPlan(ctx, "package-audit", "bundle", ["audit", "--format=json"], {
1574
- parser: "bundler-audit",
1575
- reason: "Audit Ruby gems for vulnerabilities.",
1576
- network: true
1577
- }),
1578
- run: async (ctx) => {
1579
- const entries = ["main.rb", "app.rb", "server.rb", "config.ru"];
1580
- const first = (await Promise.all(
1581
- entries.map((name) => ctx.pathExists(name).then((ok) => ok ? name : void 0))
1582
- )).find(Boolean);
1583
- const hasGemfile = await ctx.pathExists("Gemfile");
1584
- const cmd = hasGemfile ? "bundle" : "ruby";
1585
- const args = hasGemfile ? ["exec", "ruby", first ?? ""] : [first ?? ""];
1586
- return processPlan(ctx, "run", cmd, args, {
1587
- parser: "command-text",
1588
- reason: first ? `Run the Ruby entry point ${first}.` : "Run the Ruby project (no common entry point detected \u2014 add the file path manually).",
1589
- executesProjectCode: true,
1590
- mutating: true
1591
- });
1592
- }
1593
- })
1594
- };
1595
- }
1596
- function cProfile() {
1597
- return {
1598
- id: "c",
1599
- displayName: "C / C++",
1600
- extensions: Object.freeze([".c", ".h"]),
1601
- lspLanguageIds: Object.freeze(["c"]),
1602
- detectors: Object.freeze([
1603
- { kind: "manifest", filename: "CMakeLists.txt", weight: 85 },
1604
- { kind: "manifest", filename: "Makefile", weight: 60 },
1605
- { kind: "config", suffix: ".cmake", weight: 50 }
1606
- ]),
1607
- ignoredDirectories: IGNORES,
1608
- packageManagers: Object.freeze([]),
1609
- executables: Object.freeze(["cc", "gcc", "clang", "cmake", "make"]),
1610
- operations: Object.freeze({
1611
- semantic: async (ctx) => processPlan(ctx, "semantic", "cmake", ["--build", ".", "--target", "all"], {
1612
- parser: "cmake",
1613
- reason: "Build C project to collect compiler diagnostics.",
1614
- mutating: true,
1615
- executesProjectCode: true
1616
- }),
1617
- test: async (ctx) => unavailable(
1618
- ctx,
1619
- "test",
1620
- "C test execution requires a configured test runner (ctest, etc.)."
1621
- ),
1622
- build: async (ctx) => processPlan(ctx, "build", "cmake", ["--build", "."], {
1623
- parser: "cmake",
1624
- reason: "Build the C project.",
1625
- mutating: true,
1626
- executesProjectCode: true
1627
- })
1628
- })
1629
- };
1630
- }
1631
- function cppProfile() {
1632
- return {
1633
- ...cProfile(),
1634
- id: "cpp",
1635
- displayName: "C++",
1636
- extensions: Object.freeze([".cpp", ".cc", ".cxx", ".hpp", ".hxx"]),
1637
- lspLanguageIds: Object.freeze(["cpp"]),
1638
- detectors: Object.freeze([
1639
- { kind: "manifest", filename: "CMakeLists.txt", weight: 85 },
1640
- { kind: "manifest", filename: "Makefile", weight: 50 }
1641
- ]),
1642
- executables: Object.freeze(["c++", "g++", "clang++", "cmake", "make"])
1643
- };
1644
- }
1645
- function swiftProfile() {
1646
- return {
1647
- id: "swift",
1648
- displayName: "Swift",
1649
- extensions: Object.freeze([".swift"]),
1650
- lspLanguageIds: Object.freeze(["swift"]),
1651
- detectors: Object.freeze([{ kind: "manifest", filename: "Package.swift", weight: 90 }]),
1652
- ignoredDirectories: IGNORES,
1653
- packageManagers: Object.freeze(["swift"]),
1654
- executables: Object.freeze(["swift", "swiftc"]),
1655
- operations: Object.freeze({
1656
- semantic: async (ctx) => processPlan(ctx, "semantic", "swift", ["build"], {
1657
- parser: "swift",
1658
- reason: "Build Swift package to collect compiler diagnostics.",
1659
- mutating: true,
1660
- executesProjectCode: true
1661
- }),
1662
- test: async (ctx) => processPlan(ctx, "test", "swift", ["test"], {
1663
- parser: "swift-test",
1664
- reason: "Run Swift tests.",
1665
- mutating: true,
1666
- executesProjectCode: true
1667
- }),
1668
- build: async (ctx) => processPlan(ctx, "build", "swift", ["build", "-c", "release"], {
1669
- parser: "swift",
1670
- reason: "Build the Swift package in release mode.",
1671
- mutating: true,
1672
- executesProjectCode: true
1673
- }),
1674
- run: async (ctx) => processPlan(ctx, "run", "swift", ["run"], {
1675
- parser: "command-text",
1676
- reason: "Run the Swift package entry point.",
1677
- executesProjectCode: true
1678
- })
1679
- })
1680
- };
1681
- }
1682
- function dartProfile() {
1683
- return {
1684
- id: "dart",
1685
- displayName: "Dart / Flutter",
1686
- extensions: Object.freeze([".dart"]),
1687
- lspLanguageIds: Object.freeze(["dart"]),
1688
- detectors: Object.freeze([
1689
- { kind: "manifest", filename: "pubspec.yaml", weight: 90 },
1690
- { kind: "lockfile", filename: "pubspec.lock", weight: 30 }
1691
- ]),
1692
- ignoredDirectories: IGNORES,
1693
- packageManagers: Object.freeze(["pub"]),
1694
- executables: Object.freeze(["dart", "flutter"]),
1695
- operations: Object.freeze({
1696
- semantic: async (ctx) => processPlan(ctx, "semantic", "dart", ["analyze"], {
1697
- parser: "dart-analyze",
1698
- reason: "Run Dart static analysis."
1699
- }),
1700
- "format-check": async (ctx) => processPlan(
1701
- ctx,
1702
- "format-check",
1703
- "dart",
1704
- ["format", "--output=none", "--set-exit-if-changed", "."],
1705
- {
1706
- parser: "dart-format",
1707
- reason: "Check Dart formatting without writing files."
1708
- }
1709
- ),
1710
- "format-write": async (ctx) => processPlan(ctx, "format-write", "dart", ["format", "."], {
1711
- parser: "dart-format",
1712
- reason: "Format Dart source files.",
1713
- mutating: true
1714
- }),
1715
- test: async (ctx) => processPlan(ctx, "test", "dart", ["test"], {
1716
- parser: "dart-test",
1717
- reason: "Run Dart tests.",
1718
- mutating: true,
1719
- executesProjectCode: true
1720
- }),
1721
- "package-install": async (ctx) => processPlan(ctx, "package-install", "dart", ["pub", "get"], {
1722
- parser: "package-text",
1723
- reason: "Fetch Dart package dependencies.",
1724
- mutating: true,
1725
- network: true
1726
- }),
1727
- "package-outdated": async (ctx) => processPlan(ctx, "package-outdated", "dart", ["pub", "outdated"], {
1728
- parser: "dart-outdated",
1729
- reason: "Check for outdated Dart packages.",
1730
- network: true
1731
- }),
1732
- run: async (ctx) => processPlan(ctx, "run", "dart", ["run"], {
1733
- parser: "command-text",
1734
- reason: "Run the Dart / Flutter project entry point.",
1735
- executesProjectCode: true
1736
- })
1737
- })
1738
- };
1739
- }
1740
- function denoProfile() {
1741
- return {
1742
- id: "deno",
1743
- displayName: "Deno",
1744
- extensions: Object.freeze([".ts", ".tsx", ".js", ".jsx"]),
1745
- lspLanguageIds: Object.freeze(["typescript", "javascript"]),
1746
- detectors: Object.freeze([
1747
- { kind: "config", filename: "deno.json", weight: 90 },
1748
- { kind: "config", filename: "deno.jsonc", weight: 90 },
1749
- { kind: "config", filename: "import_map.json", weight: 60 }
1750
- ]),
1751
- ignoredDirectories: IGNORES,
1752
- packageManagers: Object.freeze([]),
1753
- executables: Object.freeze(["deno"]),
1754
- // .ts/.js extensions are shared with the TypeScript/JavaScript profiles;
1755
- // only a deno.json(c)/import_map.json detector hit may establish a workspace.
1756
- sourceFallback: false,
1757
- operations: Object.freeze({
1758
- test: async (ctx) => processPlan(ctx, "test", "deno", ["test"], {
1759
- parser: "deno-test",
1760
- reason: "Run Deno tests.",
1761
- mutating: true,
1762
- executesProjectCode: true
1763
- }),
1764
- run: async (ctx) => processPlan(ctx, "run", "deno", ["run", "--allow-all", "main.ts"], {
1765
- parser: "command-text",
1766
- reason: "Run the Deno project entry point with full permission.",
1767
- executesProjectCode: true,
1768
- mutating: true
1769
- })
1770
- })
1771
- };
1772
- }
1773
- function elixirProfile() {
1774
- return {
1775
- id: "elixir",
1776
- displayName: "Elixir",
1777
- extensions: Object.freeze([".ex", ".exs"]),
1778
- lspLanguageIds: Object.freeze(["elixir"]),
1779
- detectors: Object.freeze([
1780
- { kind: "manifest", filename: "mix.exs", weight: 90 },
1781
- { kind: "lockfile", filename: "mix.lock", weight: 30 }
1782
- ]),
1783
- ignoredDirectories: IGNORES,
1784
- packageManagers: Object.freeze(["mix"]),
1785
- executables: Object.freeze(["mix", "elixir"]),
1786
- operations: Object.freeze({
1787
- semantic: async (ctx) => unavailable(ctx, "semantic", "Elixir compilation is handled by the build operation."),
1788
- lint: async (ctx) => unavailable(ctx, "lint", "Elixir linting requires the credo package."),
1789
- test: async (ctx) => processPlan(ctx, "test", "mix", ["test"], {
1790
- parser: "mix-test",
1791
- reason: "Run ExUnit tests.",
1792
- mutating: true,
1793
- executesProjectCode: true
1794
- }),
1795
- build: async (ctx) => processPlan(ctx, "build", "mix", ["compile"], {
1796
- parser: "mix",
1797
- reason: "Compile the Mix project.",
1798
- mutating: true,
1799
- executesProjectCode: true
1800
- }),
1801
- run: async (ctx) => processPlan(ctx, "run", "mix", ["run"], {
1802
- parser: "command-text",
1803
- reason: "Run the Mix project entry point.",
1804
- executesProjectCode: true
1805
- }),
1806
- "package-install": async (ctx) => processPlan(ctx, "package-install", "mix", ["deps.get"], {
1807
- parser: "package-text",
1808
- reason: "Fetch Elixir dependencies.",
1809
- mutating: true,
1810
- network: true
1811
- })
1812
- })
1813
- };
1814
- }
1815
- function shellProfile() {
1816
- return {
1817
- id: "shell",
1818
- displayName: "Shell",
1819
- extensions: Object.freeze([".sh", ".bash"]),
1820
- lspLanguageIds: Object.freeze(["shellscript"]),
1821
- detectors: Object.freeze([{ kind: "config", filename: "ShellCheckrc", weight: 50 }]),
1822
- ignoredDirectories: IGNORES,
1823
- packageManagers: Object.freeze([]),
1824
- executables: Object.freeze(["bash", "sh", "shellcheck", "shfmt"]),
1825
- operations: Object.freeze({
1826
- syntax: async (ctx) => ctx.options.target ? processPlan(ctx, "syntax", "bash", ["-n", ctx.options.target], {
1827
- parser: "shell",
1828
- reason: "Check the shell script for syntax errors."
1829
- }) : unavailable(ctx, "syntax", "Shell syntax check requires an explicit target file."),
1830
- lint: async (ctx) => ctx.options.target ? processPlan(ctx, "lint", "shellcheck", ["--format=json", ctx.options.target], {
1831
- parser: "shellcheck",
1832
- reason: "Run ShellCheck on the target script."
1833
- }) : unavailable(ctx, "lint", "Shell linting requires an explicit target file."),
1834
- "format-check": async (ctx) => ctx.options.target ? processPlan(ctx, "format-check", "shfmt", ["-d", ctx.options.target], {
1835
- parser: "shell",
1836
- reason: "Check shell formatting without writing."
1837
- }) : unavailable(
1838
- ctx,
1839
- "format-check",
1840
- "Shell formatting check requires an explicit target file."
1841
- ),
1842
- "format-write": async (ctx) => ctx.options.target ? processPlan(ctx, "format-write", "shfmt", ["-w", ctx.options.target], {
1843
- parser: "shell",
1844
- reason: "Format the shell script.",
1845
- mutating: true
1846
- }) : unavailable(ctx, "format-write", "Shell formatting requires an explicit target file.")
1847
- })
1848
- };
1849
- }
1850
- var ADDITIONAL_LANGUAGE_PROFILES = Object.freeze([
1851
- pythonProfile(),
1852
- javaProfile(),
1853
- rubyProfile(),
1854
- cProfile(),
1855
- cppProfile(),
1856
- swiftProfile(),
1857
- dartProfile(),
1858
- denoProfile(),
1859
- elixirProfile(),
1860
- shellProfile()
1861
- ]);
1862
-
1863
- // src/languages/profiles/primary.ts
1864
- var COMMON_IGNORES = Object.freeze([
1865
- ".git",
1866
- ".wrongstack",
1867
- "node_modules",
1868
- "vendor",
1869
- "target",
1870
- "bin",
1871
- "obj",
1872
- "dist",
1873
- "build",
1874
- "coverage"
1875
- ]);
1876
- function nodeManager(ctx) {
1877
- const lockfiles = new Set(
1878
- ctx.workspace.evidence.filter((evidence) => evidence.kind === "lockfile").map((evidence) => evidence.value.toLowerCase())
1879
- );
1880
- if (lockfiles.size > 1 && !ctx.workspace.packageManager) return void 0;
1881
- return ctx.workspace.packageManager ?? "npm";
1882
- }
1883
- function scriptPlan(ctx, operation, script) {
1884
- const manager = nodeManager(ctx);
1885
- if (!manager)
1886
- return unavailable(
1887
- ctx,
1888
- operation,
1889
- "Conflicting Node lockfiles make the package manager ambiguous."
1890
- );
1891
- const args = manager === "npm" ? ["run", script] : [script];
1892
- return processPlan(ctx, operation, manager, args, {
1893
- parser: "command-text",
1894
- reason: `Run the detected ${manager} ${script} script for this workspace.`,
1895
- mutating: true,
1896
- executesProjectCode: true
1897
- });
1898
- }
1899
- function nodeExec(ctx, executable, args) {
1900
- const manager = ctx.workspace.packageManager ?? "npm";
1901
- if (manager === "pnpm") return { command: "pnpm", args: ["exec", executable, ...args] };
1902
- if (manager === "yarn") return { command: "yarn", args: ["exec", executable, ...args] };
1903
- if (manager === "bun") return { command: "bun", args: ["x", executable, ...args] };
1904
- return { command: "npx", args: ["--no-install", executable, ...args] };
1905
- }
1906
- function typescriptProfile() {
1907
- return {
1908
- id: "typescript",
1909
- displayName: "TypeScript",
1910
- extensions: Object.freeze([".ts", ".tsx", ".mts", ".cts"]),
1911
- lspLanguageIds: Object.freeze(["typescript", "typescriptreact"]),
1912
- detectors: Object.freeze([
1913
- { kind: "config", filename: "tsconfig.json", weight: 90 },
1914
- { kind: "manifest", filename: "package.json", weight: 55 },
1915
- { kind: "lockfile", filename: "pnpm-lock.yaml", weight: 30 },
1916
- { kind: "lockfile", filename: "yarn.lock", weight: 30 },
1917
- { kind: "lockfile", filename: "package-lock.json", weight: 30 },
1918
- { kind: "lockfile", filename: "bun.lock", weight: 30 },
1919
- { kind: "lockfile", filename: "bun.lockb", weight: 30 }
1920
- ]),
1921
- ignoredDirectories: COMMON_IGNORES,
1922
- packageManagers: Object.freeze(["pnpm", "yarn", "bun", "npm"]),
1923
- executables: Object.freeze(["pnpm", "yarn", "bun", "npx", "npm"]),
1924
- operations: Object.freeze({
1925
- syntax: async (ctx) => internalPlan(
1926
- ctx,
1927
- "syntax",
1928
- "typescript-parser",
1929
- "Parse the target with the TypeScript compiler API."
1930
- ),
1931
- semantic: async (ctx) => {
1932
- const run = nodeExec(ctx, "tsc", ["--noEmit", "--pretty", "false"]);
1933
- return processPlan(ctx, "semantic", run.command, run.args, {
1934
- parser: "typescript",
1935
- reason: "Run the workspace TypeScript compiler without emitting files.",
1936
- executesProjectCode: true
1937
- });
1938
- },
1939
- lint: async (ctx) => {
1940
- const run = nodeExec(ctx, "biome", ["lint", "."]);
1941
- return processPlan(ctx, "lint", run.command, run.args, {
1942
- parser: "biome",
1943
- reason: "Run the project-local Biome linter.",
1944
- executesProjectCode: true
1945
- });
1946
- },
1947
- "format-check": async (ctx) => {
1948
- const run = nodeExec(ctx, "biome", ["format", "--check", "."]);
1949
- return processPlan(ctx, "format-check", run.command, run.args, {
1950
- parser: "biome",
1951
- reason: "Check formatting with the project-local Biome formatter.",
1952
- executesProjectCode: true
1953
- });
1954
- },
1955
- "format-write": async (ctx) => {
1956
- const run = nodeExec(ctx, "biome", ["format", "--write", "."]);
1957
- return processPlan(ctx, "format-write", run.command, run.args, {
1958
- parser: "biome",
1959
- reason: "Format the workspace with the project-local Biome formatter.",
1960
- mutating: true,
1961
- executesProjectCode: true
1962
- });
1963
- },
1964
- test: async (ctx) => ctx.options.filter || ctx.options.coverage ? unavailable(
1965
- ctx,
1966
- "test",
1967
- "The detected package script does not expose deterministic filter or coverage adapters."
1968
- ) : scriptPlan(ctx, "test", "test"),
1969
- build: async (ctx) => scriptPlan(ctx, "build", "build"),
1970
- run: async (ctx) => scriptPlan(ctx, "run", "dev"),
1971
- "debug-compile": async (ctx) => {
1972
- const run = nodeExec(ctx, "tsc", ["--noEmit", "--pretty", "false"]);
1973
- return processPlan(ctx, "debug-compile", run.command, run.args, {
1974
- parser: "typescript",
1975
- reason: "Collect deterministic TypeScript compiler diagnostics.",
1976
- executesProjectCode: true
1977
- });
1978
- },
1979
- "package-install": async (ctx) => {
1980
- const manager = ctx.workspace.packageManager ?? "npm";
1981
- const args = manager === "yarn" ? ["install", "--ignore-scripts"] : ["install", "--ignore-scripts"];
1982
- return processPlan(ctx, "package-install", manager, args, {
1983
- parser: "package-text",
1984
- reason: `Restore declared dependencies with ${manager} and lifecycle scripts disabled.`,
1985
- mutating: true,
1986
- network: true,
1987
- executesProjectCode: false
1988
- });
1989
- },
1990
- "package-add": async (ctx) => {
1991
- const names = packageNames(ctx);
1992
- if (names.length === 0)
1993
- return unavailable(ctx, "package-add", "At least one package name is required.");
1994
- const manager = ctx.workspace.packageManager ?? "npm";
1995
- const args = manager === "npm" ? ["install", "--ignore-scripts", ...names] : ["add", "--ignore-scripts", ...names];
1996
- return processPlan(ctx, "package-add", manager, args, {
1997
- parser: "package-text",
1998
- reason: `Add validated packages with ${manager} and lifecycle scripts disabled.`,
1999
- mutating: true,
2000
- network: true
2001
- });
2002
- },
2003
- "package-remove": async (ctx) => {
2004
- const names = packageNames(ctx);
2005
- if (names.length === 0)
2006
- return unavailable(ctx, "package-remove", "At least one package name is required.");
2007
- const manager = ctx.workspace.packageManager ?? "npm";
2008
- const args = manager === "npm" ? ["uninstall", "--ignore-scripts", ...names] : ["remove", "--ignore-scripts", ...names];
2009
- return processPlan(ctx, "package-remove", manager, args, {
2010
- parser: "package-text",
2011
- reason: `Remove validated packages with ${manager} and lifecycle scripts disabled.`,
2012
- mutating: true,
2013
- network: true
2014
- });
2015
- },
2016
- "package-audit": async (ctx) => {
2017
- const manager = ctx.workspace.packageManager ?? "npm";
2018
- return processPlan(ctx, "package-audit", manager, ["audit", "--json"], {
2019
- parser: "npm-audit",
2020
- reason: `Audit dependencies with the detected ${manager} package manager.`,
2021
- network: true
2022
- });
2023
- },
2024
- "package-outdated": async (ctx) => {
2025
- const manager = ctx.workspace.packageManager ?? "npm";
2026
- return processPlan(ctx, "package-outdated", manager, ["outdated", "--json"], {
2027
- parser: "npm-outdated",
2028
- reason: `Check outdated dependencies with ${manager}.`,
2029
- network: true
2030
- });
2031
- }
2032
- })
2033
- };
2034
- }
2035
- function javascriptProfile() {
2036
- const ts = typescriptProfile();
2037
- return {
2038
- ...ts,
2039
- id: "javascript",
2040
- displayName: "JavaScript",
2041
- extensions: Object.freeze([".js", ".jsx", ".mjs", ".cjs"]),
2042
- lspLanguageIds: Object.freeze(["javascript", "javascriptreact"]),
2043
- detectors: Object.freeze([
2044
- { kind: "config", filename: "jsconfig.json", weight: 90 },
2045
- { kind: "manifest", filename: "package.json", weight: 70 },
2046
- { kind: "lockfile", filename: "pnpm-lock.yaml", weight: 30 },
2047
- { kind: "lockfile", filename: "yarn.lock", weight: 30 },
2048
- { kind: "lockfile", filename: "package-lock.json", weight: 30 },
2049
- { kind: "lockfile", filename: "bun.lock", weight: 30 },
2050
- { kind: "lockfile", filename: "bun.lockb", weight: 30 }
2051
- ]),
2052
- operations: Object.freeze({
2053
- ...ts.operations,
2054
- syntax: async (ctx) => internalPlan(
2055
- ctx,
2056
- "syntax",
2057
- "typescript-parser",
2058
- "Parse JavaScript with the TypeScript compiler API."
2059
- )
2060
- })
2061
- };
2062
- }
2063
- var goProfile = {
2064
- id: "go",
2065
- displayName: "Go",
2066
- extensions: Object.freeze([".go"]),
2067
- lspLanguageIds: Object.freeze(["go"]),
2068
- detectors: Object.freeze([
2069
- { kind: "manifest", filename: "go.mod", weight: 90 },
2070
- { kind: "manifest", filename: "go.work", weight: 95 },
2071
- { kind: "lockfile", filename: "go.sum", weight: 30 }
2072
- ]),
2073
- ignoredDirectories: COMMON_IGNORES,
2074
- packageManagers: Object.freeze(["go"]),
2075
- executables: Object.freeze(["go", "gofmt"]),
2076
- operations: Object.freeze({
2077
- syntax: async (ctx) => {
2078
- if (!ctx.target)
2079
- return unavailable(ctx, "syntax", "Go syntax planning requires a target file.");
2080
- return processPlan(ctx, "syntax", "gofmt", ["-e", "-d", ctx.target], {
2081
- parser: "gofmt",
2082
- reason: "Parse the target and report syntax errors without writing it."
2083
- });
2084
- },
2085
- semantic: async (ctx) => processPlan(ctx, "semantic", "go", ["test", "-run", "^$", "./..."], {
2086
- parser: "go-test",
2087
- reason: "Compile all Go packages without selecting tests.",
2088
- mutating: true,
2089
- executesProjectCode: true
2090
- }),
2091
- lint: async (ctx) => processPlan(ctx, "lint", "go", ["vet", "./..."], {
2092
- parser: "go-compiler",
2093
- reason: "Run the standard Go vet checks.",
2094
- mutating: true,
2095
- executesProjectCode: true
2096
- }),
2097
- "format-check": async (ctx) => ctx.target ? processPlan(ctx, "format-check", "gofmt", ["-d", ctx.target], {
2098
- parser: "gofmt",
2099
- reason: "Report Go formatting differences for the target without writing it."
2100
- }) : unavailable(ctx, "format-check", "Go formatting requires an explicit target file."),
2101
- "format-write": async (ctx) => ctx.target ? processPlan(ctx, "format-write", "gofmt", ["-w", ctx.target], {
2102
- parser: "gofmt",
2103
- reason: "Format the target Go source file.",
2104
- mutating: true
2105
- }) : unavailable(ctx, "format-write", "Go formatting requires an explicit target file."),
2106
- test: async (ctx) => processPlan(
2107
- ctx,
2108
- "test",
2109
- "go",
2110
- ["test", ...ctx.options.filter ? ["-run", ctx.options.filter] : [], "./..."],
2111
- {
2112
- parser: "go-test",
2113
- reason: ctx.options.filter ? "Run filtered Go tests." : "Run all Go tests.",
2114
- mutating: true,
2115
- executesProjectCode: true
2116
- }
2117
- ),
2118
- build: async (ctx) => processPlan(ctx, "build", "go", ["build", "./..."], {
2119
- parser: "go-compiler",
2120
- reason: "Build all Go packages.",
2121
- mutating: true,
2122
- executesProjectCode: true
2123
- }),
2124
- run: async (ctx) => processPlan(ctx, "run", "go", ["run", "."], {
2125
- parser: "command-text",
2126
- reason: "Run the Go module entry point.",
2127
- executesProjectCode: true
2128
- }),
2129
- "debug-race": async (ctx) => processPlan(ctx, "debug-race", "go", ["test", "-race", "./..."], {
2130
- parser: "go-test",
2131
- reason: "Collect Go race-detector evidence.",
2132
- mutating: true,
2133
- executesProjectCode: true
2134
- }),
2135
- "package-install": async (ctx) => processPlan(ctx, "package-install", "go", ["mod", "download"], {
2136
- parser: "go-module",
2137
- reason: "Download the dependencies declared by go.mod.",
2138
- mutating: true,
2139
- network: true
2140
- }),
2141
- "package-add": async (ctx) => {
2142
- const names = packageNames(ctx);
2143
- if (names.length === 0)
2144
- return unavailable(ctx, "package-add", "At least one Go module is required.");
2145
- return processPlan(ctx, "package-add", "go", ["get", ...names], {
2146
- parser: "go-module",
2147
- reason: "Add validated Go modules.",
2148
- mutating: true,
2149
- network: true
2150
- });
2151
- },
2152
- "package-update": async (ctx) => processPlan(ctx, "package-update", "go", ["get", "-u", "./..."], {
2153
- parser: "go-module",
2154
- reason: "Update dependencies of all Go packages.",
2155
- mutating: true,
2156
- network: true
2157
- })
2158
- })
2159
- };
2160
- var rustProfile = {
2161
- id: "rust",
2162
- displayName: "Rust",
2163
- extensions: Object.freeze([".rs"]),
2164
- lspLanguageIds: Object.freeze(["rust"]),
2165
- detectors: Object.freeze([
2166
- { kind: "manifest", filename: "Cargo.toml", weight: 90 },
2167
- { kind: "lockfile", filename: "Cargo.lock", weight: 30 }
2168
- ]),
2169
- ignoredDirectories: COMMON_IGNORES,
2170
- packageManagers: Object.freeze(["cargo"]),
2171
- executables: Object.freeze(["cargo"]),
2172
- operations: Object.freeze({
2173
- syntax: async (ctx) => processPlan(ctx, "syntax", "cargo", ["check", "--message-format=json"], {
2174
- parser: "cargo-json",
2175
- reason: "Check Rust syntax and semantics with Cargo.",
2176
- mutating: true,
2177
- executesProjectCode: true
2178
- }),
2179
- semantic: async (ctx) => processPlan(ctx, "semantic", "cargo", ["check", "--message-format=json"], {
2180
- parser: "cargo-json",
2181
- reason: "Collect Rust compiler diagnostics with Cargo check.",
2182
- mutating: true,
2183
- executesProjectCode: true
2184
- }),
2185
- lint: async (ctx) => processPlan(ctx, "lint", "cargo", ["clippy", "--message-format=json"], {
2186
- parser: "cargo-json",
2187
- reason: "Run Clippy for this crate.",
2188
- mutating: true,
2189
- executesProjectCode: true
2190
- }),
2191
- "format-check": async (ctx) => processPlan(ctx, "format-check", "cargo", ["fmt", "--check"], {
2192
- parser: "cargo-fmt",
2193
- reason: "Check Rust formatting without writing files."
2194
- }),
2195
- "format-write": async (ctx) => processPlan(ctx, "format-write", "cargo", ["fmt"], {
2196
- parser: "cargo-fmt",
2197
- reason: "Format Rust source files in the workspace.",
2198
- mutating: true
2199
- }),
2200
- "test-compile": async (ctx) => processPlan(ctx, "test-compile", "cargo", ["test", "--no-run", "--message-format=json"], {
2201
- parser: "cargo-json",
2202
- reason: "Compile Rust tests without running them.",
2203
- mutating: true,
2204
- executesProjectCode: true
2205
- }),
2206
- test: async (ctx) => processPlan(
2207
- ctx,
2208
- "test",
2209
- "cargo",
2210
- ["test", ...ctx.options.filter ? [ctx.options.filter] : []],
2211
- {
2212
- parser: "cargo-test",
2213
- reason: ctx.options.filter ? "Run filtered Rust tests." : "Run Rust tests.",
2214
- mutating: true,
2215
- executesProjectCode: true
2216
- }
2217
- ),
2218
- build: async (ctx) => processPlan(ctx, "build", "cargo", ["build", "--message-format=json"], {
2219
- parser: "cargo-json",
2220
- reason: "Build the Rust workspace.",
2221
- mutating: true,
2222
- executesProjectCode: true
2223
- }),
2224
- run: async (ctx) => processPlan(ctx, "run", "cargo", ["run"], {
2225
- parser: "command-text",
2226
- reason: "Run the Rust workspace entry point.",
2227
- executesProjectCode: true
2228
- }),
2229
- "package-install": async (ctx) => processPlan(ctx, "package-install", "cargo", ["fetch", "--locked"], {
2230
- parser: "cargo-json",
2231
- reason: "Fetch locked Rust dependencies.",
2232
- mutating: true,
2233
- network: true
2234
- }),
2235
- "package-add": async (ctx) => {
2236
- const names = packageNames(ctx);
2237
- return names.length === 0 ? unavailable(ctx, "package-add", "At least one crate is required.") : processPlan(ctx, "package-add", "cargo", ["add", ...names], {
2238
- parser: "cargo-text",
2239
- reason: "Add validated Rust crates.",
2240
- mutating: true,
2241
- network: true
2242
- });
2243
- },
2244
- "package-remove": async (ctx) => {
2245
- const names = packageNames(ctx);
2246
- return names.length === 0 ? unavailable(ctx, "package-remove", "At least one crate is required.") : processPlan(ctx, "package-remove", "cargo", ["remove", ...names], {
2247
- parser: "cargo-text",
2248
- reason: "Remove validated Rust crates.",
2249
- mutating: true
2250
- });
2251
- },
2252
- "package-update": async (ctx) => processPlan(ctx, "package-update", "cargo", ["update"], {
2253
- parser: "cargo-text",
2254
- reason: "Update the Cargo lockfile.",
2255
- mutating: true,
2256
- network: true
2257
- }),
2258
- "package-audit": async (ctx) => processPlan(ctx, "package-audit", "cargo", ["audit", "--json"], {
2259
- parser: "cargo-audit",
2260
- reason: "Audit Rust dependencies when cargo-audit is installed.",
2261
- network: true
2262
- })
2263
- })
2264
- };
2265
- var phpProfile = {
2266
- id: "php",
2267
- displayName: "PHP",
2268
- extensions: Object.freeze([".php"]),
2269
- lspLanguageIds: Object.freeze(["php"]),
2270
- detectors: Object.freeze([
2271
- { kind: "manifest", filename: "composer.json", weight: 90 },
2272
- { kind: "lockfile", filename: "composer.lock", weight: 30 },
2273
- { kind: "config", filename: "phpunit.xml", weight: 25 },
2274
- { kind: "config", filename: "phpunit.xml.dist", weight: 25 }
2275
- ]),
2276
- ignoredDirectories: COMMON_IGNORES,
2277
- packageManagers: Object.freeze(["composer"]),
2278
- executables: Object.freeze(["php", "composer"]),
2279
- operations: Object.freeze({
2280
- syntax: async (ctx) => ctx.target ? processPlan(ctx, "syntax", "php", ["-l", ctx.target], {
2281
- parser: "php-lint",
2282
- reason: "Lint the target PHP file without executing it."
2283
- }) : unavailable(ctx, "syntax", "PHP syntax planning requires a target file."),
2284
- semantic: async (ctx) => unavailable(
2285
- ctx,
2286
- "semantic",
2287
- "No configured PHPStan or Psalm adapter was detected in Phase 1."
2288
- ),
2289
- test: async (ctx) => processPlan(
2290
- ctx,
2291
- "test",
2292
- "php",
2293
- ["vendor/bin/phpunit", ...ctx.options.filter ? ["--filter", ctx.options.filter] : []],
2294
- {
2295
- parser: "phpunit",
2296
- reason: ctx.options.filter ? "Run filtered tests with the project-local PHPUnit runner." : "Run the project-local PHPUnit test runner.",
2297
- executesProjectCode: true
2298
- }
2299
- ),
2300
- "package-install": async (ctx) => processPlan(
2301
- ctx,
2302
- "package-install",
2303
- "composer",
2304
- ["install", "--no-interaction", "--no-scripts"],
2305
- {
2306
- parser: "composer",
2307
- reason: "Restore Composer dependencies without scripts.",
2308
- mutating: true,
2309
- network: true
2310
- }
2311
- ),
2312
- "package-add": async (ctx) => {
2313
- const names = packageNames(ctx);
2314
- return names.length === 0 ? unavailable(ctx, "package-add", "At least one Composer package is required.") : processPlan(
2315
- ctx,
2316
- "package-add",
2317
- "composer",
2318
- ["require", "--no-interaction", "--no-scripts", ...names],
2319
- {
2320
- parser: "composer",
2321
- reason: "Add validated Composer packages without scripts.",
2322
- mutating: true,
2323
- network: true
2324
- }
2325
- );
2326
- },
2327
- "package-remove": async (ctx) => {
2328
- const names = packageNames(ctx);
2329
- return names.length === 0 ? unavailable(ctx, "package-remove", "At least one Composer package is required.") : processPlan(
2330
- ctx,
2331
- "package-remove",
2332
- "composer",
2333
- ["remove", "--no-interaction", "--no-scripts", ...names],
2334
- {
2335
- parser: "composer",
2336
- reason: "Remove validated Composer packages without scripts.",
2337
- mutating: true
2338
- }
2339
- );
2340
- },
2341
- "package-update": async (ctx) => processPlan(
2342
- ctx,
2343
- "package-update",
2344
- "composer",
2345
- ["update", "--no-interaction", "--no-scripts"],
2346
- {
2347
- parser: "composer",
2348
- reason: "Update Composer dependencies without scripts.",
2349
- mutating: true,
2350
- network: true
2351
- }
2352
- ),
2353
- "package-audit": async (ctx) => processPlan(ctx, "package-audit", "composer", ["audit", "--format=json"], {
2354
- parser: "composer-audit",
2355
- reason: "Audit Composer dependencies.",
2356
- network: true
2357
- }),
2358
- "package-outdated": async (ctx) => processPlan(ctx, "package-outdated", "composer", ["outdated", "--format=json"], {
2359
- parser: "composer-outdated",
2360
- reason: "Check outdated Composer dependencies.",
2361
- network: true
2362
- })
2363
- })
2364
- };
2365
- var csharpProfile = {
2366
- id: "csharp",
2367
- displayName: "C# / .NET",
2368
- extensions: Object.freeze([".cs"]),
2369
- lspLanguageIds: Object.freeze(["csharp"]),
2370
- detectors: Object.freeze([
2371
- { kind: "config", filename: "global.json", weight: 25 },
2372
- { kind: "manifest", suffix: ".slnx", weight: 95 },
2373
- { kind: "manifest", suffix: ".sln", weight: 95 },
2374
- { kind: "manifest", suffix: ".csproj", weight: 90 },
2375
- { kind: "manifest", suffix: ".fsproj", weight: 90 },
2376
- { kind: "lockfile", filename: "packages.lock.json", weight: 30 }
2377
- ]),
2378
- ignoredDirectories: COMMON_IGNORES,
2379
- packageManagers: Object.freeze(["dotnet"]),
2380
- executables: Object.freeze(["dotnet"]),
2381
- operations: Object.freeze({
2382
- syntax: async (ctx) => processPlan(ctx, "syntax", "dotnet", ["build", "--no-restore"], {
2383
- parser: "dotnet-build",
2384
- reason: "Use the nearest project or solution to collect C# syntax diagnostics.",
2385
- mutating: true,
2386
- executesProjectCode: true
2387
- }),
2388
- semantic: async (ctx) => processPlan(ctx, "semantic", "dotnet", ["build", "--no-restore"], {
2389
- parser: "dotnet-build",
2390
- reason: "Build without restoring to collect .NET compiler diagnostics.",
2391
- mutating: true,
2392
- executesProjectCode: true
2393
- }),
2394
- lint: async (ctx) => processPlan(ctx, "lint", "dotnet", ["format", "--verify-no-changes", "--no-restore"], {
2395
- parser: "dotnet-format",
2396
- reason: "Verify .NET formatting and analyzers without writing source files.",
2397
- mutating: true,
2398
- executesProjectCode: true
2399
- }),
2400
- "format-check": async (ctx) => processPlan(
2401
- ctx,
2402
- "format-check",
2403
- "dotnet",
2404
- ["format", "--verify-no-changes", "--no-restore"],
2405
- {
2406
- parser: "dotnet-format",
2407
- reason: "Verify .NET formatting without source writes.",
2408
- mutating: true,
2409
- executesProjectCode: true
2410
- }
2411
- ),
2412
- "format-write": async (ctx) => processPlan(ctx, "format-write", "dotnet", ["format", "--no-restore"], {
2413
- parser: "dotnet-format",
2414
- reason: "Format .NET source files without restoring packages.",
2415
- mutating: true,
2416
- executesProjectCode: true
2417
- }),
2418
- test: async (ctx) => processPlan(
2419
- ctx,
2420
- "test",
2421
- "dotnet",
2422
- ["test", "--no-restore", ...ctx.options.filter ? ["--filter", ctx.options.filter] : []],
2423
- {
2424
- parser: "dotnet-test",
2425
- reason: ctx.options.filter ? "Run filtered .NET tests without restoring packages." : "Run .NET tests without restoring packages.",
2426
- mutating: true,
2427
- executesProjectCode: true
2428
- }
2429
- ),
2430
- build: async (ctx) => processPlan(ctx, "build", "dotnet", ["build", "--no-restore"], {
2431
- parser: "dotnet-build",
2432
- reason: "Build the nearest .NET project or solution without restoring packages.",
2433
- mutating: true,
2434
- executesProjectCode: true
2435
- }),
2436
- run: async (ctx) => processPlan(ctx, "run", "dotnet", ["run", "--no-restore"], {
2437
- parser: "command-text",
2438
- reason: "Run the .NET project entry point.",
2439
- mutating: true,
2440
- executesProjectCode: true
2441
- }),
2442
- "package-install": async (ctx) => processPlan(ctx, "package-install", "dotnet", ["restore", "--locked-mode"], {
2443
- parser: "dotnet-restore",
2444
- reason: "Restore locked .NET dependencies.",
2445
- mutating: true,
2446
- network: true,
2447
- executesProjectCode: true
2448
- }),
2449
- "package-add": async (ctx) => {
2450
- const names = packageNames(ctx);
2451
- const [spec] = names;
2452
- const versionAt = spec?.lastIndexOf("@") ?? -1;
2453
- const packageName = versionAt > 0 ? spec?.slice(0, versionAt) : spec;
2454
- const packageVersion = versionAt > 0 ? spec?.slice(versionAt + 1) : void 0;
2455
- 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(
2456
- ctx,
2457
- "package-add",
2458
- "dotnet",
2459
- [
2460
- "add",
2461
- "package",
2462
- packageName ?? "",
2463
- ...packageVersion ? ["--version", packageVersion] : []
2464
- ],
2465
- {
2466
- parser: "dotnet-package",
2467
- reason: "Add validated NuGet packages.",
2468
- mutating: true,
2469
- network: true,
2470
- executesProjectCode: true
2471
- }
2472
- );
2473
- },
2474
- "package-remove": async (ctx) => {
2475
- const names = packageNames(ctx);
2476
- return names.length === 0 ? unavailable(ctx, "package-remove", "At least one NuGet package is required.") : processPlan(ctx, "package-remove", "dotnet", ["remove", "package", ...names], {
2477
- parser: "dotnet-package",
2478
- reason: "Remove validated NuGet packages.",
2479
- mutating: true
2480
- });
2481
- },
2482
- "package-audit": async (ctx) => processPlan(
2483
- ctx,
2484
- "package-audit",
2485
- "dotnet",
2486
- ["list", "package", "--vulnerable", "--format", "json"],
2487
- { parser: "dotnet-package", reason: "List vulnerable NuGet dependencies.", network: true }
2488
- ),
2489
- "package-outdated": async (ctx) => processPlan(
2490
- ctx,
2491
- "package-outdated",
2492
- "dotnet",
2493
- ["list", "package", "--outdated", "--format", "json"],
2494
- { parser: "dotnet-package", reason: "List outdated NuGet dependencies.", network: true }
2495
- )
2496
- })
2497
- };
2498
- var PRIMARY_LANGUAGE_PROFILES = Object.freeze([
2499
- Object.freeze(typescriptProfile()),
2500
- Object.freeze(javascriptProfile()),
2501
- Object.freeze(goProfile),
2502
- Object.freeze(rustProfile),
2503
- Object.freeze(phpProfile),
2504
- Object.freeze(csharpProfile)
2505
- ]);
2506
-
2507
- // src/languages/registry.ts
2508
- var PROFILE_ID_RE = /^[a-z][a-z0-9-]{0,63}$/;
2509
- var EXECUTABLE_RE = /^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/;
2510
- var KNOWN_OPERATIONS = /* @__PURE__ */ new Set([
2511
- "syntax",
2512
- "semantic",
2513
- "lint",
2514
- "format-check",
2515
- "format-write",
2516
- "test-compile",
2517
- "test",
2518
- "build",
2519
- "run",
2520
- "debug-compile",
2521
- "debug-test",
2522
- "debug-runtime",
2523
- "debug-race",
2524
- "package-install",
2525
- "package-add",
2526
- "package-remove",
2527
- "package-update",
2528
- "package-audit",
2529
- "package-outdated"
2530
- ]);
2531
- var LanguageProfileRegistry = class {
2532
- #profiles = /* @__PURE__ */ new Map();
2533
- constructor(profiles = []) {
2534
- for (const profile of profiles) this.register(profile);
2535
- }
2536
- register(profile) {
2537
- const errors = validateLanguageProfile(profile);
2538
- if (errors.length > 0) {
2539
- throw new Error(`Invalid language profile "${profile.id}": ${errors.join("; ")}`);
2540
- }
2541
- if (this.#profiles.has(profile.id)) {
2542
- throw new Error(`Language profile "${profile.id}" is already registered`);
2543
- }
2544
- this.#profiles.set(profile.id, freezeProfile(profile));
2545
- }
2546
- get(id) {
2547
- return this.#profiles.get(id);
2548
- }
2549
- list() {
2550
- return Object.freeze([...this.#profiles.values()]);
2551
- }
2552
- };
2553
- function validateLanguageProfile(profile) {
2554
- const errors = [];
2555
- if (!PROFILE_ID_RE.test(profile.id)) errors.push("id must be a lowercase stable identifier");
2556
- if (!profile.displayName.trim()) errors.push("displayName is required");
2557
- if (profile.extensions.length === 0) errors.push("at least one extension is required");
2558
- for (const ext of profile.extensions) {
2559
- if (!/^\.[a-z0-9+.-]+$/i.test(ext)) errors.push(`invalid extension "${ext}"`);
2560
- }
2561
- if (profile.detectors.length === 0) errors.push("at least one detector is required");
2562
- for (const detector of profile.detectors) {
2563
- if ((detector.filename ? 1 : 0) + (detector.suffix ? 1 : 0) !== 1) {
2564
- errors.push("each detector must declare exactly one of filename or suffix");
2565
- }
2566
- if (!Number.isFinite(detector.weight) || detector.weight <= 0 || detector.weight > 100) {
2567
- errors.push("detector weights must be in the range 1..100");
2568
- }
2569
- const marker = detector.filename ?? detector.suffix ?? "";
2570
- if (marker.includes("/") || marker.includes("\\") || marker.includes("\0")) {
2571
- errors.push(`detector marker "${marker}" must be a basename or suffix`);
2572
- }
2573
- }
2574
- if (profile.executables.length === 0) errors.push("at least one executable is required");
2575
- for (const executable of profile.executables) {
2576
- if (!EXECUTABLE_RE.test(executable)) errors.push(`invalid executable token "${executable}"`);
2577
- }
2578
- for (const operation of Object.keys(profile.operations)) {
2579
- if (!KNOWN_OPERATIONS.has(operation)) {
2580
- errors.push(`unknown operation "${operation}"`);
2581
- }
2582
- if (typeof profile.operations[operation] !== "function") {
2583
- errors.push(`operation "${operation}" must be a resolver function`);
2584
- }
2585
- }
2586
- return [...new Set(errors)];
2587
- }
2588
- function freezeProfile(profile) {
2589
- const detectors = Object.freeze(profile.detectors.map((item) => Object.freeze({ ...item })));
2590
- const operations = Object.freeze({ ...profile.operations });
2591
- return Object.freeze({
2592
- ...profile,
2593
- extensions: Object.freeze([...profile.extensions]),
2594
- lspLanguageIds: Object.freeze([...profile.lspLanguageIds]),
2595
- detectors,
2596
- ignoredDirectories: Object.freeze([...profile.ignoredDirectories]),
2597
- packageManagers: Object.freeze([...profile.packageManagers]),
2598
- executables: Object.freeze([...profile.executables]),
2599
- operations
2600
- });
2601
- }
2602
- var languageProfileRegistry = new LanguageProfileRegistry([
2603
- ...PRIMARY_LANGUAGE_PROFILES,
2604
- ...ADDITIONAL_LANGUAGE_PROFILES
2605
- ]);
2606
-
2607
- // src/languages/detect.ts
2608
- var DEFAULT_LIMITS = { maxDepth: 6, maxEntries: 5e3 };
2609
- var SOURCE_WEIGHT = 5;
2610
- var SOURCE_WEIGHT_CAP = 25;
2611
- var TARGET_WEIGHT = 100;
2612
- var GLOBAL_IGNORES = /* @__PURE__ */ new Set([
2613
- ".git",
2614
- ".wrongstack",
2615
- "node_modules",
2616
- "vendor",
2617
- "target",
2618
- "bin",
2619
- "obj",
2620
- "dist",
2621
- "build",
2622
- "out",
2623
- "coverage",
2624
- ".cache",
2625
- ".idea",
2626
- ".vscode",
2627
- ".next",
2628
- ".nuxt"
2629
- ]);
2630
- async function detectLanguageWorkspaces(options) {
2631
- const projectRoot = await canonicalDirectory(options.projectRoot);
2632
- const cwdInput = options.cwd ? path4.isAbsolute(options.cwd) ? options.cwd : path4.resolve(projectRoot, options.cwd) : projectRoot;
2633
- const cwd = await canonicalInside(cwdInput, projectRoot, "cwd");
2634
- const target = options.target ? await canonicalInside(resolveFrom(cwd, options.target), projectRoot, "target") : void 0;
2635
- const profiles = (options.profiles ?? languageProfileRegistry.list()).filter((profile) => !options.language || profile.id === options.language).slice().sort((a, b) => a.id.localeCompare(b.id));
2636
- const limits = normalizeLimits(options.limits);
2637
- const extraIgnores = new Set(options.ignoredDirectories ?? []);
2638
- const state = {
2639
- entries: 0,
2640
- truncated: false,
2641
- sourcePaths: /* @__PURE__ */ new Map(),
2642
- candidates: /* @__PURE__ */ new Map()
2643
- };
2644
- await scanDirectory(projectRoot, 0, profiles, limits, state, extraIgnores, options.signal);
2645
- addSourceFallbacks(projectRoot, profiles, state);
2646
- if (target) addTargetEvidence(target, projectRoot, profiles, state);
2647
- const workspaces = await Promise.all(
2648
- [...state.candidates.values()].map((candidate) => finalizeCandidate(candidate, projectRoot))
2649
- );
2650
- workspaces.sort(compareWorkspaces);
2651
- return {
2652
- projectRoot,
2653
- scannedEntries: state.entries,
2654
- truncated: state.truncated,
2655
- workspaces
2656
- };
2657
- }
2658
- async function scanDirectory(directory, depth, profiles, limits, state, extraIgnores, signal) {
2659
- signal?.throwIfAborted();
2660
- if (depth > limits.maxDepth || state.entries >= limits.maxEntries) {
2661
- state.truncated = true;
2662
- return;
2663
- }
2664
- let entries;
2665
- try {
2666
- entries = await fs2.readdir(directory, { withFileTypes: true });
2667
- } catch {
2668
- return;
2669
- }
2670
- entries.sort((a, b) => a.name.localeCompare(b.name));
2671
- for (const entry of entries) {
2672
- signal?.throwIfAborted();
2673
- if (state.entries >= limits.maxEntries) {
2674
- state.truncated = true;
2675
- return;
2676
- }
2677
- state.entries++;
2678
- const fullPath = path4.join(directory, entry.name);
2679
- if (entry.isSymbolicLink()) continue;
2680
- if (entry.isDirectory()) {
2681
- if (shouldIgnoreDirectory(entry.name, profiles, extraIgnores)) continue;
2682
- if (depth >= limits.maxDepth) {
2683
- state.truncated = true;
2684
- continue;
2685
- }
2686
- await scanDirectory(fullPath, depth + 1, profiles, limits, state, extraIgnores, signal);
2687
- continue;
2688
- }
2689
- if (!entry.isFile()) continue;
2690
- collectFileEvidence(directory, fullPath, entry.name, profiles, state);
2691
- }
2692
- }
2693
- function collectFileEvidence(directory, fullPath, basename5, profiles, state) {
2694
- const lower = basename5.toLowerCase();
2695
- const extension = path4.extname(lower);
2696
- for (const profile of profiles) {
2697
- const detector = profile.detectors.find(
2698
- (rule) => rule.filename ? lower === rule.filename.toLowerCase() : lower.endsWith(rule.suffix.toLowerCase())
2699
- );
2700
- if (detector) {
2701
- const candidate = getCandidate(state, profile, directory);
2702
- candidate.evidence.push({
2703
- kind: detector.kind,
2704
- path: fullPath,
2705
- value: basename5,
2706
- weight: detector.weight
2707
- });
2708
- if (detector.kind === "manifest" || detector.kind === "config") {
2709
- candidate.manifests.push(fullPath);
2710
- }
2711
- }
2712
- if (profile.extensions.includes(extension)) {
2713
- const paths = state.sourcePaths.get(profile.id) ?? [];
2714
- if (paths.length < SOURCE_WEIGHT_CAP / SOURCE_WEIGHT) paths.push(fullPath);
2715
- state.sourcePaths.set(profile.id, paths);
2716
- }
2717
- }
2718
- }
2719
- function addSourceFallbacks(projectRoot, profiles, state) {
2720
- for (const profile of profiles) {
2721
- const sources = state.sourcePaths.get(profile.id) ?? [];
2722
- if (sources.length === 0) continue;
2723
- const profileCandidates = [...state.candidates.values()].filter(
2724
- (item) => item.profile.id === profile.id
2725
- );
2726
- for (const source of sources) {
2727
- const containing = profileCandidates.filter((candidate2) => isInside(source, candidate2.root)).sort(
2728
- (a, b) => pathDepth(b.root, projectRoot) - pathDepth(a.root, projectRoot) || a.root.localeCompare(b.root)
2729
- );
2730
- const candidate = containing[0] ?? (profile.sourceFallback === false ? void 0 : getCandidate(state, profile, projectRoot));
2731
- if (!candidate) continue;
2732
- candidate.evidence.push({
2733
- kind: "source",
2734
- path: source,
2735
- value: path4.extname(source),
2736
- weight: SOURCE_WEIGHT
2737
- });
2738
- }
2739
- }
2740
- }
2741
- function addTargetEvidence(target, projectRoot, profiles, state) {
2742
- const extension = path4.extname(target).toLowerCase();
2743
- for (const profile of profiles) {
2744
- if (!profile.extensions.includes(extension)) continue;
2745
- const candidates = [...state.candidates.values()].filter(
2746
- (candidate2) => candidate2.profile.id === profile.id && isInside(target, candidate2.root)
2747
- );
2748
- const candidate = candidates.length > 0 ? candidates.sort(
2749
- (a, b) => pathDepth(b.root, projectRoot) - pathDepth(a.root, projectRoot) || a.root.localeCompare(b.root)
2750
- )[0] : profile.sourceFallback === false ? void 0 : getCandidate(state, profile, path4.dirname(target));
2751
- if (!candidate) continue;
2752
- candidate.evidence.push({
2753
- kind: "target",
2754
- path: target,
2755
- value: extension,
2756
- weight: TARGET_WEIGHT
2757
- });
2758
- }
2759
- }
2760
- async function finalizeCandidate(candidate, projectRoot) {
2761
- const evidence = dedupeEvidence(candidate.evidence).sort(compareEvidence);
2762
- const manifests = [...new Set(candidate.manifests)].sort();
2763
- const confidence = Math.min(1, evidence.reduce((sum, item) => sum + item.weight, 0) / 100);
2764
- const packageManager = await detectPackageManager2(candidate.profile, candidate.root, evidence);
2765
- const id = createHash("sha256").update(`${candidate.profile.id}\0${path4.relative(projectRoot, candidate.root)}`).digest("hex").slice(0, 16);
2766
- return Object.freeze({
2767
- id,
2768
- language: candidate.profile.id,
2769
- root: candidate.root,
2770
- confidence,
2771
- evidence: Object.freeze(evidence.map((item) => Object.freeze(item))),
2772
- ...packageManager ? { packageManager } : {},
2773
- manifests: Object.freeze(manifests),
2774
- capabilities: Object.freeze(
2775
- Object.keys(candidate.profile.operations).sort()
2776
- )
2777
- });
2778
- }
2779
- async function detectPackageManager2(profile, root, evidence) {
2780
- if (profile.packageManagers.length === 1) return profile.packageManagers[0];
2781
- if (profile.id !== "typescript" && profile.id !== "javascript") return void 0;
2782
- let declared;
2783
- try {
2784
- const pkg = JSON.parse(await fs2.readFile(path4.join(root, "package.json"), "utf8"));
2785
- if (typeof pkg.packageManager === "string") {
2786
- const manager = pkg.packageManager.split("@")[0];
2787
- if (manager && profile.packageManagers.includes(manager)) declared = manager;
2788
- }
2789
- } catch {
2790
- }
2791
- const lockManagers = /* @__PURE__ */ new Set();
2792
- for (const item of evidence) {
2793
- const name = path4.basename(item.path).toLowerCase();
2794
- if (name === "pnpm-lock.yaml") lockManagers.add("pnpm");
2795
- else if (name === "yarn.lock") lockManagers.add("yarn");
2796
- else if (name === "bun.lock" || name === "bun.lockb") lockManagers.add("bun");
2797
- else if (name === "package-lock.json") lockManagers.add("npm");
2798
- }
2799
- if (declared && (lockManagers.size === 0 || lockManagers.size === 1 && lockManagers.has(declared))) {
2800
- return declared;
2801
- }
2802
- if (lockManagers.size === 1) return [...lockManagers][0];
2803
- if (lockManagers.size > 1) return void 0;
2804
- return declared ?? "npm";
2805
- }
2806
- function getCandidate(state, profile, root) {
2807
- const key = `${profile.id}\0${root}`;
2808
- let candidate = state.candidates.get(key);
2809
- if (!candidate) {
2810
- candidate = { profile, root, evidence: [], manifests: [] };
2811
- state.candidates.set(key, candidate);
2812
- }
2813
- return candidate;
2814
- }
2815
- function shouldIgnoreDirectory(name, profiles, extraIgnores) {
2816
- if (GLOBAL_IGNORES.has(name) || extraIgnores.has(name) || name.startsWith(".")) return true;
2817
- return profiles.some((profile) => profile.ignoredDirectories.includes(name));
2818
- }
2819
- function normalizeLimits(input) {
2820
- const maxDepth = Math.max(
2821
- 0,
2822
- Math.min(12, Math.trunc(input?.maxDepth ?? DEFAULT_LIMITS.maxDepth))
2823
- );
2824
- const maxEntries = Math.max(
2825
- 1,
2826
- Math.min(5e4, Math.trunc(input?.maxEntries ?? DEFAULT_LIMITS.maxEntries))
2827
- );
2828
- return { maxDepth, maxEntries };
2829
- }
2830
- async function canonicalDirectory(input) {
2831
- const resolved = path4.resolve(input);
2832
- const real = await fs2.realpath(resolved);
2833
- const stat5 = await fs2.stat(real);
2834
- if (!stat5.isDirectory()) throw new Error(`Project root is not a directory: ${input}`);
2835
- return real;
2836
- }
2837
- async function canonicalInside(input, root, label) {
2838
- const resolved = path4.resolve(input);
2839
- let real;
2840
- try {
2841
- real = await fs2.realpath(resolved);
2842
- } catch (error) {
2843
- if (error.code !== "ENOENT") throw error;
2844
- const parent = await fs2.realpath(path4.dirname(resolved));
2845
- real = path4.join(parent, path4.basename(resolved));
2846
- }
2847
- if (!isInside(real, root)) throw new Error(`${label} is outside project root: ${input}`);
2848
- return real;
2849
- }
2850
- function resolveFrom(cwd, input) {
2851
- return path4.isAbsolute(input) ? input : path4.resolve(cwd, input);
2852
- }
2853
- function isInside(candidate, root) {
2854
- const relative5 = path4.relative(root, candidate);
2855
- return relative5 === "" || !relative5.startsWith("..") && !path4.isAbsolute(relative5);
2856
- }
2857
- function pathDepth(candidate, root) {
2858
- const relative5 = path4.relative(root, candidate);
2859
- return relative5 === "" ? 0 : relative5.split(path4.sep).length;
2860
- }
2861
- function dedupeEvidence(items) {
2862
- const seen = /* @__PURE__ */ new Set();
2863
- return items.filter((item) => {
2864
- const key = `${item.kind}\0${item.path}\0${item.value}\0${item.weight}`;
2865
- if (seen.has(key)) return false;
2866
- seen.add(key);
2867
- return true;
2868
- });
2869
- }
2870
- function compareEvidence(a, b) {
2871
- return a.path.localeCompare(b.path) || a.kind.localeCompare(b.kind) || b.weight - a.weight;
2872
- }
2873
- function compareWorkspaces(a, b) {
2874
- return b.confidence - a.confidence || a.language.localeCompare(b.language) || a.root.localeCompare(b.root) || a.id.localeCompare(b.id);
2875
- }
2876
-
2877
- // src/languages/diagnostics.ts
2878
- import * as path5 from "node:path";
2879
- var MAX_DIAGNOSTICS = 200;
2880
- function parseLanguageDiagnostics(parser, stdout, stderr, workspaceRoot) {
2881
- const text = `${stdout}${stdout && stderr ? "\n" : ""}${stderr}`;
2882
- let diagnostics;
2883
- switch (parser) {
2884
- case "typescript":
2885
- diagnostics = parseTypeScript(text, workspaceRoot);
2886
- break;
2887
- case "cargo-json":
2888
- diagnostics = parseCargoJson(text, workspaceRoot);
2889
- break;
2890
- case "php-lint":
2891
- diagnostics = parsePhpLint(text, workspaceRoot);
2892
- break;
2893
- case "dotnet-build":
2894
- case "dotnet-format":
2895
- case "dotnet-test":
2896
- diagnostics = parseDotnet(text, workspaceRoot);
2897
- break;
2898
- case "go-test":
2899
- case "go-compiler":
2900
- case "gofmt":
2901
- diagnostics = parseGo(text, workspaceRoot);
2902
- break;
2903
- case "biome":
2904
- diagnostics = parseBiome(text, workspaceRoot);
2905
- break;
2906
- default:
2907
- diagnostics = parseGeneric(text, parser, workspaceRoot);
2908
- break;
2909
- }
2910
- const sorted = dedupeDiagnostics(diagnostics).sort(compareDiagnostics);
2911
- const omitted = Math.max(0, sorted.length - MAX_DIAGNOSTICS);
2912
- const kept = Object.freeze(sorted.slice(0, MAX_DIAGNOSTICS).map((item) => Object.freeze(item)));
2913
- return {
2914
- diagnostics: kept,
2915
- omitted,
2916
- summary: summarize(kept)
2917
- };
2918
- }
2919
- function parseTypeScript(text, root) {
2920
- const diagnostics = [];
2921
- const regex = /^(.+?)\((\d+),(\d+)\):\s+(error|warning)\s+(TS\d+):\s*(.+)$/gm;
2922
- for (const match of text.matchAll(regex)) {
2923
- diagnostics.push({
2924
- severity: match[4] === "warning" ? "warning" : "error",
2925
- code: match[5],
2926
- message: match[6].trim(),
2927
- file: normalizeDiagnosticPath(match[1], root),
2928
- range: { start: { line: toPositiveInt(match[2]), column: toPositiveInt(match[3]) } },
2929
- source: "typescript"
2930
- });
2931
- }
2932
- return diagnostics;
2933
- }
2934
- function parseCargoJson(text, root) {
2935
- const diagnostics = [];
2936
- for (const line of text.split(/\r?\n/)) {
2937
- if (!line.trim().startsWith("{")) continue;
2938
- try {
2939
- const value = JSON.parse(line);
2940
- if (value.reason !== "compiler-message" || !value.message?.message) continue;
2941
- const primary = value.message.spans?.find((span) => span.is_primary) ?? value.message.spans?.[0];
2942
- diagnostics.push({
2943
- severity: normalizeSeverity(value.message.level),
2944
- ...value.message.code?.code ? { code: value.message.code.code } : {},
2945
- message: value.message.message,
2946
- ...primary?.file_name ? { file: normalizeDiagnosticPath(primary.file_name, root) } : {},
2947
- ...primary?.line_start ? { range: { start: { line: primary.line_start, column: primary.column_start ?? 1 } } } : {},
2948
- source: "rustc"
2949
- });
2950
- } catch {
2951
- }
2952
- }
2953
- return diagnostics;
2954
- }
2955
- function parseGo(text, root) {
2956
- return parseLinePattern(
2957
- text,
2958
- /^(.*?\.go):(\d+):(\d+):\s*(.+)$/gm,
2959
- root,
2960
- "go",
2961
- (_match, message) => ({ message, severity: /warning/i.test(message) ? "warning" : "error" })
2962
- );
2963
- }
2964
- function parsePhpLint(text, root) {
2965
- const diagnostics = [];
2966
- const regex = /(?:PHP\s+)?(?:Parse|Fatal) error:\s*(.+?)\s+in\s+(.+?)\s+on line\s+(\d+)/gi;
2967
- for (const match of text.matchAll(regex)) {
2968
- diagnostics.push({
2969
- severity: "error",
2970
- message: match[1].trim(),
2971
- file: normalizeDiagnosticPath(match[2], root),
2972
- range: { start: { line: toPositiveInt(match[3]), column: 1 } },
2973
- source: "php"
2974
- });
2975
- }
2976
- return diagnostics;
2977
- }
2978
- function parseDotnet(text, root) {
2979
- const diagnostics = [];
2980
- const regex = /^(.+?)\((\d+),(\d+)\):\s*(error|warning)\s+([A-Z]+\d+):\s*(.+?)(?:\s+\[.+\])?$/gm;
2981
- for (const match of text.matchAll(regex)) {
2982
- diagnostics.push({
2983
- severity: match[4] === "warning" ? "warning" : "error",
2984
- code: match[5],
2985
- message: match[6].trim(),
2986
- file: normalizeDiagnosticPath(match[1], root),
2987
- range: { start: { line: toPositiveInt(match[2]), column: toPositiveInt(match[3]) } },
2988
- source: "dotnet"
2989
- });
2990
- }
2991
- return diagnostics;
2992
- }
2993
- function parseBiome(text, root) {
2994
- const diagnostics = [];
2995
- const regex = /^(.+?):(\d+):(\d+)\s+(lint\/[^\s]+|format)\s+(.+)$/gm;
2996
- for (const match of text.matchAll(regex)) {
2997
- diagnostics.push({
2998
- severity: "warning",
2999
- code: match[4],
3000
- message: match[5].trim(),
3001
- file: normalizeDiagnosticPath(match[1], root),
3002
- range: { start: { line: toPositiveInt(match[2]), column: toPositiveInt(match[3]) } },
3003
- source: "biome"
3004
- });
3005
- }
3006
- return diagnostics;
3007
- }
3008
- function parseGeneric(text, source, root) {
3009
- return parseLinePattern(
3010
- text,
3011
- /^(.+?):(\d+):(\d+):\s*(?:(error|warning|info):\s*)?(.+)$/gm,
3012
- root,
3013
- source,
3014
- (match, fallback) => ({
3015
- severity: normalizeSeverity(match[4]),
3016
- message: match[5]?.trim() || fallback
3017
- })
3018
- );
3019
- }
3020
- function parsePackageReports(parser, stdout, stderr) {
3021
- const text = `${stdout}${stdout && stderr ? "\n" : ""}${stderr}`;
3022
- switch (parser) {
3023
- case "npm-audit":
3024
- return parseNpmAudit(text);
3025
- case "npm-outdated":
3026
- return parseNpmOutdated(text);
3027
- case "cargo-audit":
3028
- return parseCargoAudit(text);
3029
- case "composer-audit":
3030
- return parseComposerAudit(text);
3031
- case "composer-outdated":
3032
- return parseComposerOutdated(text);
3033
- case "dotnet-package":
3034
- return parseDotnetPackage(text);
3035
- default:
3036
- return { diagnostics: [], vulnerabilities: [], outdated: [] };
3037
- }
3038
- }
3039
- function parseNpmAudit(text) {
3040
- const advisories = [];
3041
- const diagnostics = [];
3042
- let root;
3043
- try {
3044
- root = JSON.parse(text);
3045
- } catch {
3046
- return { diagnostics, vulnerabilities: advisories, outdated: [] };
3047
- }
3048
- const vulnerabilities = root?.vulnerabilities ?? {};
3049
- const advisoriesRecord = root?.advisories ?? vulnerabilities;
3050
- for (const [id, value] of Object.entries(advisoriesRecord)) {
3051
- const advisory = value;
3052
- const name = advisory.module_name ?? advisory.package_name ?? advisory.name ?? id;
3053
- advisories.push({
3054
- package: name,
3055
- ...advisory.title ? { advisory: advisory.title } : { advisory: id },
3056
- severity: mapSeverity(advisory.severity),
3057
- ...advisory.patched_versions ? { fixedIn: advisory.patched_versions } : {},
3058
- ...advisory.url ? { url: advisory.url } : {}
3059
- });
3060
- diagnostics.push({
3061
- severity: mapSeverity(advisory.severity) === "critical" || mapSeverity(advisory.severity) === "high" ? "error" : "warning",
3062
- code: id,
3063
- message: advisory.title ?? `Vulnerability reported for ${name}.`,
3064
- source: "npm-audit"
3065
- });
3066
- }
3067
- return { diagnostics, vulnerabilities: advisories, outdated: [] };
3068
- }
3069
- function parseNpmOutdated(text) {
3070
- const diagnostics = [];
3071
- const outdated = [];
3072
- let payload = {};
3073
- try {
3074
- payload = JSON.parse(text);
3075
- } catch {
3076
- return { diagnostics, vulnerabilities: [], outdated };
3077
- }
3078
- for (const [name, info] of Object.entries(payload)) {
3079
- const entry = info;
3080
- if (!entry.latest || entry.latest === entry.current) continue;
3081
- outdated.push({
3082
- name,
3083
- previous: entry.current,
3084
- resolved: entry.latest,
3085
- kind: mapOutdatedKind(entry.type)
3086
- });
3087
- diagnostics.push({
3088
- severity: "info",
3089
- code: "outdated",
3090
- message: `${name}: ${entry.current ?? "?"} \u2192 ${entry.latest}`,
3091
- source: "npm-outdated"
3092
- });
3093
- }
3094
- return { diagnostics, vulnerabilities: [], outdated };
3095
- }
3096
- function parseCargoAudit(text) {
3097
- const diagnostics = [];
3098
- const vulnerabilities = [];
3099
- let root;
3100
- try {
3101
- root = JSON.parse(text);
3102
- } catch {
3103
- return { diagnostics, vulnerabilities, outdated: [] };
3104
- }
3105
- const findings = root.vulnerabilities?.found;
3106
- if (!Array.isArray(findings)) return { diagnostics, vulnerabilities, outdated: [] };
3107
- for (const finding of findings) {
3108
- const item = finding;
3109
- const name = item.package ?? "unknown";
3110
- const advisory = item.id ?? item.advisory?.id ?? "cargo-audit";
3111
- vulnerabilities.push({
3112
- package: name,
3113
- ...item.title ? { advisory: item.title } : { advisory },
3114
- severity: mapSeverity(item.severity),
3115
- ...item.patched_versions && item.patched_versions.length > 0 ? { fixedIn: item.patched_versions[0] } : {},
3116
- ...item.url?.short ? { url: item.url.short } : {}
3117
- });
3118
- diagnostics.push({
3119
- severity: mapSeverity(item.severity) === "critical" || mapSeverity(item.severity) === "high" ? "error" : "warning",
3120
- code: advisory,
3121
- message: item.title ?? `${name} reported by cargo-audit.`,
3122
- source: "cargo-audit"
3123
- });
3124
- }
3125
- return { diagnostics, vulnerabilities, outdated: [] };
3126
- }
3127
- function parseComposerAudit(text) {
3128
- const diagnostics = [];
3129
- const vulnerabilities = [];
3130
- const lines = text.split(/\r?\n/);
3131
- for (const line of lines) {
3132
- if (!line.trim().startsWith("{")) continue;
3133
- try {
3134
- const entry = JSON.parse(line);
3135
- if (!entry.package) continue;
3136
- vulnerabilities.push({
3137
- package: entry.package,
3138
- ...entry.advisory ? { advisory: entry.advisory } : {},
3139
- ...entry.title ? { advisory: entry.title } : { advisory: entry.advisory ?? "composer-audit" },
3140
- severity: mapSeverity(entry.severity),
3141
- ...entry.affectedVersions ? { fixedIn: entry.affectedVersions } : {},
3142
- ...entry.url ? { url: entry.url } : {}
3143
- });
3144
- diagnostics.push({
3145
- severity: "warning",
3146
- code: entry.advisory ?? "composer-audit",
3147
- message: entry.title ?? `${entry.package} reported by composer audit.`,
3148
- source: "composer-audit"
3149
- });
3150
- } catch {
3151
- }
3152
- }
3153
- return { diagnostics, vulnerabilities, outdated: [] };
3154
- }
3155
- function parseComposerOutdated(text) {
3156
- const diagnostics = [];
3157
- const outdated = [];
3158
- const lines = text.split(/\r?\n/);
3159
- for (const line of lines) {
3160
- if (!line.trim().startsWith("{")) continue;
3161
- try {
3162
- const entry = JSON.parse(line);
3163
- if (!entry.name || entry.version === entry.latest) continue;
3164
- outdated.push({
3165
- name: entry.name,
3166
- previous: entry.version,
3167
- resolved: entry.latest ?? entry.version
3168
- });
3169
- diagnostics.push({
3170
- severity: "info",
3171
- code: "outdated",
3172
- message: `${entry.name}: ${entry.version ?? "?"} \u2192 ${entry.latest ?? "?"}`,
3173
- source: "composer-outdated"
3174
- });
3175
- } catch {
3176
- }
3177
- }
3178
- return { diagnostics, vulnerabilities: [], outdated };
3179
- }
3180
- function parseDotnetPackage(text) {
3181
- const diagnostics = [];
3182
- const vulnerabilities = [];
3183
- const outdated = [];
3184
- let root;
3185
- try {
3186
- root = JSON.parse(text);
3187
- } catch {
3188
- return { diagnostics, vulnerabilities, outdated };
3189
- }
3190
- const projects = root.projects;
3191
- if (!Array.isArray(projects)) return { diagnostics, vulnerabilities, outdated };
3192
- for (const project of projects) {
3193
- const packages = Array.isArray(project.packages) ? project.packages : [];
3194
- for (const pkg of packages) {
3195
- const name = typeof pkg.name === "string" ? pkg.name : "unknown";
3196
- const requested = typeof pkg.requestedVersion === "string" ? pkg.requestedVersion : void 0;
3197
- const resolved = typeof pkg.resolvedVersion === "string" ? pkg.resolvedVersion : void 0;
3198
- const vulnerabilitiesRaw = Array.isArray(pkg.vulnerabilities) ? pkg.vulnerabilities : [];
3199
- for (const vuln of vulnerabilitiesRaw) {
3200
- const advisory = typeof vuln.advisoryUrl === "string" ? vuln.advisoryUrl : "dotnet-vulnerable";
3201
- vulnerabilities.push({
3202
- package: name,
3203
- advisory,
3204
- severity: mapSeverity(typeof vuln.severity === "string" ? vuln.severity : void 0)
3205
- });
3206
- }
3207
- if (vulnerabilitiesRaw.length > 0) {
3208
- diagnostics.push({
3209
- severity: "warning",
3210
- code: "dotnet-vulnerable",
3211
- message: `${name} has ${vulnerabilitiesRaw.length} known vulnerability entry/entries.`,
3212
- source: "dotnet-package"
3213
- });
3214
- }
3215
- if (requested && resolved && requested.startsWith(">") && requested.split(">")[1].split(".").slice(0, 2).join(".") !== resolved.split(".").slice(0, 2).join(".")) {
3216
- outdated.push({ name, requested, resolved });
3217
- diagnostics.push({
3218
- severity: "info",
3219
- code: "outdated",
3220
- message: `${name}: ${requested} \u2192 ${resolved}`,
3221
- source: "dotnet-package"
3222
- });
3223
- }
3224
- }
3225
- }
3226
- return { diagnostics, vulnerabilities, outdated };
3227
- }
3228
- function mapSeverity(value) {
3229
- switch (value?.toLowerCase()) {
3230
- case "critical":
3231
- case "high":
3232
- return "high";
3233
- case "medium":
3234
- case "moderate":
3235
- return "moderate";
3236
- case "low":
3237
- return "low";
3238
- case "unknown":
3239
- return "unknown";
3240
- default:
3241
- return "unknown";
3242
- }
3243
- }
3244
- function mapOutdatedKind(value) {
3245
- switch (value?.toLowerCase()) {
3246
- case "devdependencies":
3247
- case "development":
3248
- return "development";
3249
- case "optionaldependencies":
3250
- case "optional":
3251
- return "optional";
3252
- default:
3253
- return "runtime";
3254
- }
3255
- }
3256
- function parseLinePattern(text, regex, root, source, details) {
3257
- const diagnostics = [];
3258
- for (const match of text.matchAll(regex)) {
3259
- const parsed = details(match, match.at(-1)?.trim() ?? "Diagnostic");
3260
- diagnostics.push({
3261
- severity: parsed.severity,
3262
- message: parsed.message,
3263
- file: normalizeDiagnosticPath(match[1], root),
3264
- range: { start: { line: toPositiveInt(match[2]), column: toPositiveInt(match[3]) } },
3265
- source
3266
- });
3267
- }
3268
- return diagnostics;
3269
- }
3270
- function normalizeDiagnosticPath(value, root) {
3271
- const clean = value.trim().replace(/^['"]|['"]$/g, "");
3272
- return path5.resolve(root, clean);
3273
- }
3274
- function normalizeSeverity(value) {
3275
- if (value === "warning" || value === "warn") return "warning";
3276
- if (value === "info" || value === "note" || value === "help") return "info";
3277
- if (value === "hint") return "hint";
3278
- return "error";
3279
- }
3280
- function toPositiveInt(value) {
3281
- return Math.max(1, Number.parseInt(value ?? "1", 10) || 1);
3282
- }
3283
- function summarize(diagnostics) {
3284
- return {
3285
- errors: diagnostics.filter((item) => item.severity === "error").length,
3286
- warnings: diagnostics.filter((item) => item.severity === "warning").length,
3287
- infos: diagnostics.filter((item) => item.severity === "info" || item.severity === "hint").length
3288
- };
3289
- }
3290
- function dedupeDiagnostics(items) {
3291
- const seen = /* @__PURE__ */ new Set();
3292
- return items.filter((item) => {
3293
- const key = [
3294
- item.source,
3295
- item.code ?? "",
3296
- item.file ?? "",
3297
- item.range?.start.line ?? 0,
3298
- item.range?.start.column ?? 0,
3299
- item.message
3300
- ].join("\0");
3301
- if (seen.has(key)) return false;
3302
- seen.add(key);
3303
- return true;
3304
- });
3305
- }
3306
- function compareDiagnostics(a, b) {
3307
- 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);
3308
- }
3309
- function severityRank(value) {
3310
- return value === "error" ? 0 : value === "warning" ? 1 : value === "info" ? 2 : 3;
3311
- }
3312
-
3313
- // src/languages/execute.ts
3314
- import * as fs4 from "node:fs/promises";
3315
- import * as path7 from "node:path";
3316
-
3317
- // src/languages/plan.ts
3318
- import * as fs3 from "node:fs/promises";
3319
- import * as path6 from "node:path";
3320
- var MAX_ARGUMENTS = 128;
3321
- var MAX_ARGUMENT_LENGTH = 4096;
3322
- var PACKAGE_NAME_RE = /^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+(?:@[a-z0-9*+._~^<>=|-]+)?$/i;
3323
- var COMPOSER_PACKAGE_RE = /^[a-z0-9_.-]+\/[a-z0-9_.-]+(?::[a-z0-9*+._~^<>=|-]+)?$/i;
3324
- var GO_MODULE_RE = /^(?:[a-z0-9-]+\.)+[a-z0-9-]+\/[a-z0-9._~+/@-]+$/i;
3325
- var PYTHON_PACKAGE_RE = /^[a-z0-9._-]+(?:\[[a-z0-9._,-]+\])?==[a-z0-9*+._!~-]+$/i;
3326
- async function planLanguageOperation(options) {
3327
- validateOperationOptions(options.operation, options.operationOptions?.packages);
3328
- validateFilterOption(options.operationOptions?.filter);
3329
- const detection = await detectLanguageWorkspaces(options);
3330
- const candidates = detection.workspaces.filter(
3331
- (workspace) => workspace.capabilities.includes(options.operation)
3332
- );
3333
- const selected = selectWorkspace(candidates, options);
3334
- if (selected.status !== "selected") return selected.result;
3335
- const profile = (options.profiles ?? languageProfileRegistry.list()).find(
3336
- (item) => item.id === selected.workspace.language
3337
- );
3338
- if (!profile) {
3339
- return {
3340
- status: "not_found",
3341
- reason: `Profile ${selected.workspace.language} is unavailable.`,
3342
- candidates
3343
- };
3344
- }
3345
- if ((profile.id === "typescript" || profile.id === "javascript") && options.operation !== "syntax" && selected.workspace.packageManager === void 0 && new Set(
3346
- selected.workspace.evidence.filter((evidence) => evidence.kind === "lockfile").map((evidence) => evidence.value.toLowerCase())
3347
- ).size > 1) {
3348
- return {
3349
- status: "unavailable",
3350
- workspace: selected.workspace,
3351
- unavailable: {
3352
- status: "unavailable",
3353
- profileId: profile.id,
3354
- workspaceId: selected.workspace.id,
3355
- operation: options.operation,
3356
- reason: "Conflicting Node lockfiles make the package manager ambiguous."
3357
- }
3358
- };
3359
- }
3360
- const resolver = profile.operations[options.operation];
3361
- if (!resolver) {
3362
- return {
3363
- status: "unavailable",
3364
- workspace: selected.workspace,
3365
- unavailable: {
3366
- status: "unavailable",
3367
- profileId: profile.id,
3368
- workspaceId: selected.workspace.id,
3369
- operation: options.operation,
3370
- reason: `${profile.displayName} does not define ${options.operation}.`
3371
- }
3372
- };
3373
- }
3374
- const canonicalCwd = options.cwd ? path6.isAbsolute(options.cwd) ? options.cwd : path6.resolve(detection.projectRoot, options.cwd) : detection.projectRoot;
3375
- const target = options.target ? await canonicalTarget(canonicalCwd, options.target, detection.projectRoot) : void 0;
3376
- const ctx = {
3377
- projectRoot: detection.projectRoot,
3378
- workspace: selected.workspace,
3379
- ...target ? { target } : {},
3380
- mode: options.mode ?? "standard",
3381
- options: options.operationOptions ?? {},
3382
- platform: process.platform,
3383
- pathExists: async (candidate) => {
3384
- try {
3385
- await fs3.access(path6.resolve(detection.projectRoot, candidate));
3386
- return true;
3387
- } catch {
3388
- return false;
3389
- }
3390
- }
3391
- };
3392
- const result = await resolver(ctx);
3393
- if ("status" in result) {
3394
- return { status: "unavailable", workspace: selected.workspace, unavailable: result };
3395
- }
3396
- const errors = validateCommandPlan(result, profile, detection.projectRoot);
3397
- if (errors.length > 0) {
3398
- return {
3399
- status: "unavailable",
3400
- workspace: selected.workspace,
3401
- unavailable: {
3402
- status: "unavailable",
3403
- profileId: profile.id,
3404
- workspaceId: selected.workspace.id,
3405
- operation: options.operation,
3406
- reason: `Generated plan failed validation: ${errors.join("; ")}`
3407
- }
3408
- };
3409
- }
3410
- return { status: "planned", workspace: selected.workspace, plan: Object.freeze(result) };
3411
- }
3412
- function validateCommandPlan(plan, profile, projectRoot) {
3413
- const errors = [];
3414
- if (plan.profileId !== profile.id) errors.push("profile id does not match");
3415
- if (!isInside2(plan.cwd, projectRoot)) errors.push("cwd is outside project root");
3416
- if (plan.args.length > MAX_ARGUMENTS) errors.push(`argument count exceeds ${MAX_ARGUMENTS}`);
3417
- if (plan.args.some((arg) => arg.length > MAX_ARGUMENT_LENGTH || /[\r\n\0]/.test(arg))) {
3418
- errors.push("arguments contain an invalid or oversized value");
3419
- }
3420
- if (!Number.isFinite(plan.timeoutMs) || plan.timeoutMs < 1 || plan.timeoutMs > 6e5) {
3421
- errors.push("timeout is outside 1..600000ms");
3422
- }
3423
- if (!Number.isFinite(plan.outputLimitBytes) || plan.outputLimitBytes < 1 || plan.outputLimitBytes > 1e6) {
3424
- errors.push("output limit is outside 1..1000000 bytes");
3425
- }
3426
- if (plan.kind === "internal") {
3427
- if (plan.command !== null || plan.args.length !== 0)
3428
- errors.push("internal plans cannot declare a command");
3429
- } else {
3430
- if (!plan.command || !profile.executables.includes(plan.command)) {
3431
- errors.push(`executable "${plan.command ?? ""}" is not allowlisted by the profile`);
3432
- }
3433
- }
3434
- if (Object.keys(plan.env).length > 0)
3435
- errors.push("Phase 1 plans cannot override environment variables");
3436
- return errors;
3437
- }
3438
- function selectWorkspace(candidates, options) {
3439
- if (candidates.length === 0) {
3440
- return {
3441
- status: "result",
3442
- result: {
3443
- status: "not_found",
3444
- reason: `No workspace supports ${options.operation}.`,
3445
- candidates: []
3446
- }
3447
- };
3448
- }
3449
- if (options.workspace) {
3450
- const requested = path6.isAbsolute(options.workspace) ? path6.resolve(options.workspace) : path6.resolve(options.projectRoot, options.workspace);
3451
- const matches = candidates.filter(
3452
- (item) => item.id === options.workspace || path6.resolve(item.root) === requested
3453
- );
3454
- if (matches.length === 1) return { status: "selected", workspace: matches[0] };
3455
- return {
3456
- status: "result",
3457
- result: {
3458
- status: "not_found",
3459
- reason: `Requested workspace "${options.workspace}" was not detected.`,
3460
- candidates: [...candidates]
3461
- }
3462
- };
3463
- }
3464
- if (options.target) {
3465
- const base = options.cwd ? path6.isAbsolute(options.cwd) ? path6.resolve(options.cwd) : path6.resolve(options.projectRoot, options.cwd) : path6.resolve(options.projectRoot);
3466
- const target = path6.isAbsolute(options.target) ? path6.resolve(options.target) : path6.resolve(base, options.target);
3467
- const targeted = candidates.filter((item) => item.evidence.some((evidence) => evidence.kind === "target")).sort(
3468
- (a, b) => workspaceDepth(b.root, options.projectRoot) - workspaceDepth(a.root, options.projectRoot) || compareCandidates(a, b)
3469
- );
3470
- if (targeted[0]) return { status: "selected", workspace: targeted[0] };
3471
- const containing = candidates.filter((item) => isInside2(target, item.root)).sort(
3472
- (a, b) => workspaceDepth(b.root, options.projectRoot) - workspaceDepth(a.root, options.projectRoot) || compareCandidates(a, b)
3473
- );
3474
- if (containing[0]) return { status: "selected", workspace: containing[0] };
3475
- }
3476
- const sorted = [...candidates].sort(compareCandidates);
3477
- const first = sorted[0];
3478
- const firstDepth = workspaceDepth(first.root, options.projectRoot);
3479
- const tied = sorted.filter(
3480
- (item) => item.confidence === first.confidence && workspaceDepth(item.root, options.projectRoot) === firstDepth
3481
- );
3482
- if (tied.length > 1) {
3483
- return {
3484
- status: "result",
3485
- result: {
3486
- status: "ambiguous",
3487
- reason: "Multiple workspaces have equal confidence; provide target, language, or workspace.",
3488
- candidates: tied
3489
- }
3490
- };
3491
- }
3492
- return { status: "selected", workspace: first };
3493
- }
3494
- function compareCandidates(a, b) {
3495
- return b.confidence - a.confidence || a.language.localeCompare(b.language) || a.root.localeCompare(b.root);
3496
- }
3497
- function workspaceDepth(workspaceRoot, projectRoot) {
3498
- const relative5 = path6.relative(path6.resolve(projectRoot), path6.resolve(workspaceRoot));
3499
- return relative5 === "" ? 0 : relative5.split(path6.sep).length;
3500
- }
3501
- function validateFilterOption(filter) {
3502
- if (filter === void 0) return;
3503
- if (filter.startsWith("-") || filter.includes(" --")) {
3504
- throw new Error(`Invalid test filter (parsed as a runner option): "${filter}"`);
3505
- }
3506
- if (filter.length > MAX_ARGUMENT_LENGTH || /[\r\n\0]/.test(filter)) {
3507
- throw new Error("Invalid test filter (oversized or contains a control character)");
3508
- }
3509
- }
3510
- function validateOperationOptions(operation, packages) {
3511
- if (!operation.startsWith("package-") || !packages) return;
3512
- for (const value of packages) {
3513
- if (!value || value.length > 214 || value.startsWith("-") || /[\r\n\0;&|`$<>\\]/.test(value)) {
3514
- throw new Error(`Invalid package identifier "${value}"`);
3515
- }
3516
- if (value.startsWith(".") || value.startsWith("/") || /^[A-Za-z]:/.test(value) || value.includes("://")) {
3517
- throw new Error(`Package paths and URLs are not supported: "${value}"`);
3518
- }
3519
- if (!PACKAGE_NAME_RE.test(value) && !COMPOSER_PACKAGE_RE.test(value) && !GO_MODULE_RE.test(value) && !PYTHON_PACKAGE_RE.test(value)) {
3520
- throw new Error(`Invalid package identifier "${value}"`);
3521
- }
3522
- }
3523
- }
3524
- async function canonicalTarget(cwd, target, projectRoot) {
3525
- const resolved = path6.isAbsolute(target) ? path6.resolve(target) : path6.resolve(cwd, target);
3526
- let real;
3527
- try {
3528
- real = await fs3.realpath(resolved);
3529
- } catch (error) {
3530
- if (error.code !== "ENOENT") throw error;
3531
- const parent = await fs3.realpath(path6.dirname(resolved));
3532
- real = path6.join(parent, path6.basename(resolved));
3533
- }
3534
- if (!isInside2(real, projectRoot)) throw new Error(`target is outside project root: ${target}`);
3535
- return real;
3536
- }
3537
- function isInside2(candidate, root) {
3538
- const relative5 = path6.relative(path6.resolve(root), path6.resolve(candidate));
3539
- return relative5 === "" || !relative5.startsWith("..") && !path6.isAbsolute(relative5);
3540
- }
3541
-
3542
- // src/languages/execute.ts
3543
- async function validatePlanRealpaths(plan, projectRoot) {
3544
- const realRoot = await fs4.realpath(projectRoot);
3545
- let realCwd;
3546
- try {
3547
- realCwd = await fs4.realpath(plan.cwd);
3548
- } catch (error) {
3549
- return `Plan cwd is unavailable: ${error instanceof Error ? error.message : String(error)}`;
3550
- }
3551
- if (!isRealInside(realCwd, realRoot)) return "Plan cwd resolves outside project root.";
3552
- for (const argument of plan.args) {
3553
- if (!path7.isAbsolute(argument)) continue;
3554
- try {
3555
- const realArgument = await fs4.realpath(argument);
3556
- if (!isRealInside(realArgument, realRoot)) {
3557
- return `Plan argument resolves outside project root: ${argument}`;
3558
- }
3559
- } catch (error) {
3560
- if (error.code !== "ENOENT") {
3561
- return `Plan argument could not be resolved safely: ${argument}`;
3562
- }
3563
- }
3564
- }
3565
- return void 0;
3566
- }
3567
- function isRealInside(candidate, root) {
3568
- const relative5 = path7.relative(root, candidate);
3569
- return relative5 === "" || !relative5.startsWith("..") && !path7.isAbsolute(relative5);
3570
- }
3571
- async function* executePackagePlan(options) {
3572
- const { plan, workspace } = options;
3573
- const startedAt = Date.now();
3574
- if (options.signal.aborted) {
3575
- yield { type: "log", text: "Run cancelled before execution." };
3576
- return terminalPackageResult(options, "cancelled", startedAt);
3577
- }
3578
- const profile = languageProfileRegistry.get(plan.profileId);
3579
- if (!profile) {
3580
- yield { type: "warning", text: `Unknown language profile: ${plan.profileId}` };
3581
- return terminalPackageResult(options, "unavailable", startedAt, "Unknown language profile.");
3582
- }
3583
- if (workspace.id !== plan.workspaceId || workspace.language !== plan.profileId) {
3584
- return terminalPackageResult(
3585
- options,
3586
- "unavailable",
3587
- startedAt,
3588
- "Plan and workspace identity do not match."
3589
- );
3590
- }
3591
- const validation = validateCommandPlan(plan, profile, options.projectRoot);
3592
- if (validation.length > 0) {
3593
- return terminalPackageResult(
3594
- options,
3595
- "unavailable",
3596
- startedAt,
3597
- `Plan failed execution validation: ${validation.join("; ")}`
3598
- );
3599
- }
3600
- const containmentError = await validatePlanRealpaths(plan, options.projectRoot);
3601
- if (containmentError) {
3602
- return terminalPackageResult(options, "unavailable", startedAt, containmentError);
3603
- }
3604
- const manifestsBefore = await snapshotPaths(workspace.manifests);
3605
- const lockfilePaths = collectLockfilePaths(workspace);
3606
- const lockfilesBefore = await snapshotPaths(lockfilePaths);
3607
- const manifestSizesBefore = await snapshotSizes(workspace.manifests);
3608
- const lockfileSizesBefore = await snapshotSizes(lockfilePaths);
3609
- yield {
3610
- type: "log",
3611
- text: plan.kind === "process" ? `${plan.command} ${plan.args.join(" ")}` : `${plan.parser}: ${plan.operation}`,
3612
- data: {
3613
- language: plan.profileId,
3614
- operation: plan.operation,
3615
- workspace: workspace.root,
3616
- packages: [...options.packages]
3617
- }
3618
- };
3619
- const timeoutController = new AbortController();
3620
- const timer = setTimeout(
3621
- () => timeoutController.abort(new Error("language package plan timed out")),
3622
- plan.timeoutMs
3623
- );
3624
- timer.unref?.();
3625
- const signal = AbortSignal.any([options.signal, timeoutController.signal]);
3626
- let spawned;
3627
- let run;
3628
- let status = "unavailable";
3629
- let error;
3630
- try {
3631
- if (plan.kind !== "process") {
3632
- return terminalPackageResult(
3633
- options,
3634
- "unavailable",
3635
- startedAt,
3636
- "Package operations require an executable plan; internal plans cannot mutate the manifest."
3637
- );
3638
- }
3639
- const stream = spawnStream({
3640
- cmd: plan.command,
3641
- args: [...plan.args],
3642
- cwd: plan.cwd,
3643
- signal,
3644
- maxBytes: plan.outputLimitBytes
3645
- });
3646
- for (; ; ) {
3647
- const next = await stream.next();
3648
- if (next.done) {
3649
- spawned = next.value;
3650
- break;
3651
- }
3652
- yield next.value;
3653
- }
3654
- } catch (error_) {
3655
- error = error_ instanceof Error ? error_.message : String(error_);
3656
- } finally {
3657
- clearTimeout(timer);
3658
- }
3659
- if (spawned) {
3660
- const parsed = parseLanguageDiagnostics(
3661
- plan.parser,
3662
- spawned.stdout,
3663
- spawned.stderr,
3664
- workspace.root
3665
- );
3666
- const timedOut = timeoutController.signal.aborted && !options.signal.aborted;
3667
- const cancelled = options.signal.aborted;
3668
- const spawnUnavailable = Boolean(
3669
- spawned.error && /ENOENT|not found|cannot find/i.test(spawned.error)
3670
- );
3671
- status = timedOut ? "timed_out" : cancelled ? "cancelled" : spawnUnavailable ? "unavailable" : spawned.exitCode === 0 ? "passed" : "failed";
3672
- error ??= spawned.error;
3673
- const raw = [spawned.stdout, spawned.stderr, spawned.error].filter(Boolean).join("\n");
3674
- run = {
3675
- status,
3676
- language: plan.profileId,
3677
- workspace,
3678
- plan,
3679
- exitCode: spawned.exitCode,
3680
- durationMs: Date.now() - startedAt,
3681
- diagnostics: parsed.diagnostics,
3682
- omittedDiagnostics: parsed.omitted,
3683
- summary: parsed.summary,
3684
- output: normalizeCommandOutput(raw, { maxBytes: plan.outputLimitBytes }),
3685
- truncated: spawned.truncated,
3686
- ...spawned.spoolPath ? { spoolPath: spawned.spoolPath } : {},
3687
- ...spawned.error ? { error: spawned.error } : {}
3688
- };
3689
- } else {
3690
- status = options.signal.aborted ? "cancelled" : timeoutController.signal.aborted ? "timed_out" : "failed";
3691
- }
3692
- if (status !== "passed") {
3693
- return terminalPackageResult(
3694
- options,
3695
- status,
3696
- startedAt,
3697
- error,
3698
- run,
3699
- manifestsBefore,
3700
- lockfilesBefore
3701
- );
3702
- }
3703
- const manifestsAfter = await snapshotPaths(workspace.manifests);
3704
- const lockfilesAfter = await snapshotPaths(lockfilePaths);
3705
- const manifestSizesAfter = await snapshotSizes(workspace.manifests);
3706
- const lockfileSizesAfter = await snapshotSizes(lockfilePaths);
3707
- const manifestsChanged = await changedPaths(
3708
- manifestsBefore,
3709
- manifestsAfter,
3710
- manifestSizesBefore,
3711
- manifestSizesAfter
3712
- );
3713
- const lockfilesChanged = await changedPaths(
3714
- lockfilesBefore,
3715
- lockfilesAfter,
3716
- lockfileSizesBefore,
3717
- lockfileSizesAfter
3718
- );
3719
- const reports = parsePackageReports(plan.parser, spawned?.stdout ?? "", spawned?.stderr ?? "");
3720
- const mutations = packageMutationsFromInputs(options.packages, reports.outdated);
3721
- return {
3722
- workspace,
3723
- language: plan.profileId,
3724
- operation: plan.operation,
3725
- status,
3726
- ...run ? { run } : {},
3727
- durationMs: Date.now() - startedAt,
3728
- manifestsBefore,
3729
- lockfilesBefore,
3730
- manifestsAfter,
3731
- lockfilesAfter,
3732
- mutations,
3733
- vulnerabilities: reports.vulnerabilities,
3734
- outdated: reports.outdated,
3735
- manifestsChanged: Object.freeze(manifestsChanged),
3736
- lockfilesChanged: Object.freeze(lockfilesChanged)
3737
- };
3738
- }
3739
- function packageMutationsFromInputs(inputs, outdated) {
3740
- const outdatedNames = new Set(outdated.map((entry) => entry.name));
3741
- return inputs.filter((name) => !outdatedNames.has(name)).map((name) => ({ name, requested: name, kind: "runtime" }));
3742
- }
3743
- async function snapshotPaths(paths) {
3744
- const existing = [];
3745
- for (const candidate of paths) {
3746
- try {
3747
- const stat5 = await fs4.stat(candidate);
3748
- if (!stat5.isFile()) continue;
3749
- existing.push(candidate);
3750
- } catch {
3751
- }
3752
- }
3753
- return Object.freeze(existing);
3754
- }
3755
- async function changedPaths(before, after, beforeSizes, afterSizes) {
3756
- const beforeSet = new Set(before);
3757
- const afterSet = new Set(after);
3758
- const changed = /* @__PURE__ */ new Set();
3759
- for (const path9 of after) {
3760
- if (!beforeSet.has(path9)) changed.add(path9);
3761
- }
3762
- for (const path9 of before) {
3763
- if (!afterSet.has(path9)) changed.add(path9);
3764
- }
3765
- if (beforeSizes && afterSizes) {
3766
- for (const path9 of after) {
3767
- if (beforeSizes.get(path9) !== afterSizes.get(path9)) changed.add(path9);
3768
- }
3769
- }
3770
- return [...changed].sort();
3771
- }
3772
- async function snapshotSizes(paths) {
3773
- const sizes = /* @__PURE__ */ new Map();
3774
- for (const candidate of paths) {
3775
- try {
3776
- const stat5 = await fs4.stat(candidate);
3777
- if (stat5.isFile()) sizes.set(candidate, stat5.size);
3778
- } catch {
3779
- }
3780
- }
3781
- return sizes;
3782
- }
3783
- function collectLockfilePaths(workspace) {
3784
- const explicit = workspace.evidence.filter((evidence) => evidence.kind === "lockfile").map((evidence) => evidence.path);
3785
- const detected = LOCKFILE_NAMES_BY_PROFILE.get(workspace.language)?.map(
3786
- (name) => path7.join(workspace.root, name)
3787
- ) ?? [];
3788
- const merged = /* @__PURE__ */ new Set();
3789
- for (const candidate of [...explicit, ...detected]) merged.add(candidate);
3790
- return Object.freeze([...merged]);
3791
- }
3792
- var LOCKFILE_NAMES_BY_PROFILE = /* @__PURE__ */ new Map([
3793
- ["typescript", ["package-lock.json", "pnpm-lock.yaml", "yarn.lock", "bun.lock", "bun.lockb"]],
3794
- ["javascript", ["package-lock.json", "pnpm-lock.yaml", "yarn.lock", "bun.lock", "bun.lockb"]],
3795
- ["go", ["go.sum"]],
3796
- ["rust", ["Cargo.lock"]],
3797
- ["php", ["composer.lock"]],
3798
- ["csharp", ["packages.lock.json"]]
3799
- ]);
3800
- function terminalPackageResult(options, status, startedAt, error, run, manifestsBefore = [], lockfilesBefore = []) {
3801
- return {
3802
- workspace: options.workspace,
3803
- language: options.plan.profileId,
3804
- operation: options.plan.operation,
3805
- status,
3806
- ...run ? { run } : {},
3807
- durationMs: Date.now() - startedAt,
3808
- manifestsBefore,
3809
- lockfilesBefore,
3810
- manifestsAfter: manifestsBefore,
3811
- lockfilesAfter: lockfilesBefore,
3812
- manifestsChanged: Object.freeze([]),
3813
- lockfilesChanged: Object.freeze([]),
3814
- mutations: Object.freeze([]),
3815
- vulnerabilities: Object.freeze([]),
3816
- outdated: Object.freeze([]),
3817
- ...error ? { error } : {}
3818
- };
3819
- }
3820
-
3821
- // src/languages/legacy-bridge.ts
3822
- var NON_JS_MARKERS = [
3823
- { filename: "go.mod", language: "go" },
3824
- { filename: "go.work", language: "go" },
3825
- { filename: "Cargo.toml", language: "rust" },
3826
- { filename: "composer.json", language: "php" }
3827
- ];
3828
- var NON_JS_SUFFIXES = [
3829
- { suffix: ".csproj", language: "csharp" },
3830
- { suffix: ".fsproj", language: "csharp" }
3831
- ];
3832
- async function detectNonJsEcosystem(cwd, projectRoot) {
3833
- try {
3834
- let dir = path8.resolve(cwd);
3835
- const root = path8.resolve(projectRoot);
3836
- for (let depth = 0; depth <= 4 && dir.startsWith(root); depth++) {
3837
- for (const marker of NON_JS_MARKERS) {
3838
- try {
3839
- const s = await fs5.stat(path8.join(dir, marker.filename));
3840
- if (s.isFile()) return marker.language;
3841
- } catch {
3842
- }
3843
- }
3844
- try {
3845
- const entries = await fs5.readdir(dir);
3846
- for (const entry of entries) {
3847
- for (const suffix of NON_JS_SUFFIXES) {
3848
- if (entry.toLowerCase().endsWith(suffix.suffix)) return suffix.language;
3849
- }
3850
- }
3851
- } catch {
3852
- }
3853
- if (dir === root) break;
3854
- dir = path8.dirname(dir);
3855
- }
3856
- } catch {
3857
- }
3858
- return null;
3859
- }
3860
- async function tryLegacyPackageOperation(operation, ctx, packages = []) {
3861
- const language = await detectNonJsEcosystem(ctx.cwd, ctx.projectRoot);
3862
- if (!language) return null;
3863
- const planResult = await planLanguageOperation({
3864
- projectRoot: ctx.projectRoot,
3865
- cwd: ctx.cwd,
3866
- operation,
3867
- language,
3868
- signal: ctx.signal,
3869
- ...packages.length > 0 ? { operationOptions: { packages: [...packages] } } : {}
3870
- });
3871
- if (planResult.status !== "planned") return null;
3872
- const runner = executePackagePlan({
3873
- projectRoot: ctx.projectRoot,
3874
- workspace: planResult.workspace,
3875
- plan: planResult.plan,
3876
- packages,
3877
- signal: ctx.signal
3878
- });
3879
- for (; ; ) {
3880
- const next = await runner.next();
3881
- if (next.done) return { language, outcome: next.value };
3882
- }
3883
- }
3884
-
3885
- // src/audit.ts
3886
- var SEVERITY_RANK = {
3887
- info: 0,
3888
- low: 1,
3889
- moderate: 2,
3890
- high: 3,
3891
- critical: 4
3892
- };
3893
- var auditTool = {
3894
- name: "audit",
3895
- category: "Package Management",
3896
- description: "Run a security audit against project dependencies (using pnpm/npm audit). Reports known vulnerabilities with severity.",
3897
- usageHint: "CRITICAL SECURITY TOOL:\n\n- Run regularly and especially before any release.\n- Use `level` to focus on high/critical issues.\n- This tool is read-only: to remediate, use `install` (or `language_package`) to upgrade the affected packages.\nThis is one of the most important tools for supply chain security.",
3898
- permission: "confirm",
3899
- mutating: false,
3900
- capabilities: ["shell.restricted"],
3901
- icon: "package",
3902
- timeoutMs: 6e4,
3903
- inputSchema: {
3904
- type: "object",
3905
- properties: {
3906
- cwd: { type: "string", description: "Working directory (default: cwd)" },
3907
- level: {
3908
- type: "string",
3909
- enum: ["low", "moderate", "high", "critical"],
3910
- description: "Minimum severity level to report"
3911
- },
3912
- fix: {
3913
- type: "boolean",
3914
- description: "Deprecated and rejected \u2014 this tool is read-only and never modifies dependencies. Use `install` (or `language_package`) to remediate vulnerabilities."
3915
- }
3916
- }
3917
- },
3918
- async execute(input, ctx, opts) {
3919
- let final;
3920
- const executeStream = auditTool.executeStream;
3921
- if (!executeStream) throw new Error("auditTool: stream execution unavailable");
3922
- for await (const ev of executeStream(input, ctx, opts)) {
3923
- if (ev.type === "final") final = ev.output;
3924
- }
3925
- if (!final) throw new Error("audit: stream ended without final event");
3926
- return final;
3927
- },
3928
- async *executeStream(input, ctx, opts) {
3929
- if (input.fix === true) {
3930
- throw new Error(
3931
- "audit: `fix: true` is not supported \u2014 this tool is read-only (mutating: false). To remediate vulnerabilities, upgrade the affected packages with the `install` tool (or `language_package` for non-JS ecosystems)."
3932
- );
3933
- }
3934
- const cwd = input.cwd ? await safeResolveReal(input.cwd, ctx) : ctx.cwd;
3935
- const bridge = await tryLegacyPackageOperation("package-audit", {
3936
- cwd,
3937
- projectRoot: ctx.projectRoot,
3938
- signal: opts.signal
3939
- });
3940
- if (bridge?.outcome) {
3941
- const outcome = bridge.outcome;
3942
- const vulns = outcome.vulnerabilities.map((v) => ({
3943
- severity: v.severity,
3944
- package: v.package,
3945
- title: v.advisory ?? "Unknown vulnerability",
3946
- url: v.url ?? ""
3947
- }));
3948
- const total = vulns.length;
3949
- const summary = total === 0 ? "No vulnerabilities found" : `Found ${total} vulnerabilities: ${vulns.filter((a) => a.severity === "critical").length} critical, ${vulns.filter((a) => a.severity === "high").length} high`;
3950
- yield {
3951
- type: "final",
3952
- output: {
3953
- exit_code: outcome.run?.exitCode ?? 0,
3954
- vulnerabilities: vulns,
3955
- total,
3956
- summary,
3957
- output: outcome.run?.output ?? "",
3958
- truncated: outcome.run?.truncated ?? false
3959
- }
3960
- };
3961
- return;
3962
- }
3963
- const manager = await detectPackageManager(cwd, ctx.projectRoot);
3964
- yield { type: "log", text: `Auditing with ${manager}\u2026`, data: { manager } };
3965
- const args = ["audit", "--json"];
3966
- if (input.level && (manager === "npm" || manager === "pnpm")) {
3967
- args.push(`--audit-level=${input.level}`);
3968
- }
3969
- const result = yield* spawnStream({
3970
- cmd: manager,
3971
- args,
3972
- cwd,
3973
- signal: opts.signal,
3974
- maxBytes: 1e5
3975
- });
3976
- yield {
3977
- type: "final",
3978
- output: parseAuditOutput(result.stdout, result.exitCode, {
3979
- level: input.level,
3980
- spawnTruncated: result.truncated
3981
- })
3982
- };
3983
- }
3984
- };
3985
- function parseAuditOutput(json, exitCode, opts = {}) {
3986
- if (!json) {
3987
- return {
3988
- exit_code: exitCode,
3989
- vulnerabilities: [],
3990
- total: 0,
3991
- summary: exitCode === 0 ? "No vulnerabilities found" : "Audit failed",
3992
- output: "",
3993
- truncated: false
3994
- };
3995
- }
3996
- const cappedOutput = normalizeCommandOutput(json);
3997
- const truncated = opts.spawnTruncated === true || Buffer.byteLength(json, "utf8") > COMMAND_OUTPUT_MAX_BYTES;
3998
- try {
3999
- const data = JSON.parse(json);
4000
- let advisories = extractAdvisories(data);
4001
- const minRank = opts.level ? SEVERITY_RANK[opts.level] ?? 0 : 0;
4002
- if (minRank > 0) {
4003
- advisories = advisories.filter((a) => (SEVERITY_RANK[a.severity] ?? 0) >= minRank);
4004
- }
4005
- const total = advisories.length;
4006
- const summary = total === 0 ? "No vulnerabilities found" : `Found ${total} vulnerabilities: ${advisories.filter((a) => a.severity === "critical").length} critical, ${advisories.filter((a) => a.severity === "high").length} high`;
4007
- return {
4008
- exit_code: exitCode,
4009
- vulnerabilities: advisories,
4010
- total,
4011
- summary,
4012
- output: cappedOutput,
4013
- truncated
4014
- };
4015
- } catch {
4016
- return {
4017
- exit_code: exitCode,
4018
- vulnerabilities: [],
4019
- total: 0,
4020
- summary: "Could not parse audit output",
4021
- output: cappedOutput,
4022
- truncated
4023
- };
4024
- }
4025
- }
4026
- function extractAdvisories(data) {
4027
- const advisories = [];
4028
- const ads = data["advisories"];
4029
- if (ads && typeof ads === "object") {
4030
- for (const [id, value] of Object.entries(ads)) {
4031
- const adv = value ?? {};
4032
- advisories.push({
4033
- severity: typeof adv["severity"] === "string" ? adv["severity"] : "unknown",
4034
- package: typeof adv["module_name"] === "string" ? adv["module_name"] : id,
4035
- title: typeof adv["title"] === "string" ? adv["title"] : "Unknown vulnerability",
4036
- url: typeof adv["url"] === "string" ? adv["url"] : ""
4037
- });
4038
- }
4039
- return advisories;
4040
- }
4041
- const vulns = data["vulnerabilities"];
4042
- if (vulns && typeof vulns === "object") {
4043
- for (const [pkg, value] of Object.entries(vulns)) {
4044
- const vuln = value ?? {};
4045
- const via = Array.isArray(vuln["via"]) ? vuln["via"] : [];
4046
- const detail = via.find((v) => !!v && typeof v === "object");
4047
- advisories.push({
4048
- severity: typeof vuln["severity"] === "string" ? vuln["severity"] : "unknown",
4049
- package: pkg,
4050
- title: detail && typeof detail["title"] === "string" ? detail["title"] : "Unknown vulnerability",
4051
- url: detail && typeof detail["url"] === "string" ? detail["url"] : ""
4052
- });
4053
- }
4054
- }
4055
- return advisories;
4056
- }
2
+ auditTool
3
+ } from "./chunk-HEQFMLZ7.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";
4057
12
  export {
4058
13
  auditTool
4059
14
  };