@wrongstack/tools 0.284.1 → 0.285.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (311) hide show
  1. package/dist/_concurrency.d.ts +16 -0
  2. package/dist/_concurrency.d.ts.map +1 -0
  3. package/dist/_danger-detect.d.ts +54 -0
  4. package/dist/_danger-detect.d.ts.map +1 -0
  5. package/dist/_edit-match.d.ts +86 -0
  6. package/dist/_edit-match.d.ts.map +1 -0
  7. package/dist/_env.d.ts +6 -0
  8. package/dist/_env.d.ts.map +1 -0
  9. package/dist/_fetch-guard.d.ts +31 -0
  10. package/dist/_fetch-guard.d.ts.map +1 -0
  11. package/dist/_output-spool.d.ts +38 -0
  12. package/dist/_output-spool.d.ts.map +1 -0
  13. package/dist/_redact-command.d.ts +6 -0
  14. package/dist/_redact-command.d.ts.map +1 -0
  15. package/dist/_regex.d.ts +39 -0
  16. package/dist/_regex.d.ts.map +1 -0
  17. package/dist/_session-shell.d.ts +73 -0
  18. package/dist/_session-shell.d.ts.map +1 -0
  19. package/dist/_shell-pick.d.ts +158 -0
  20. package/dist/_shell-pick.d.ts.map +1 -0
  21. package/dist/_spawn-stream.d.ts +32 -0
  22. package/dist/_spawn-stream.d.ts.map +1 -0
  23. package/dist/_syntax-check.d.ts +16 -0
  24. package/dist/_syntax-check.d.ts.map +1 -0
  25. package/dist/_util.d.ts +68 -0
  26. package/dist/_util.d.ts.map +1 -0
  27. package/dist/_win32-resolve.d.ts +42 -0
  28. package/dist/_win32-resolve.d.ts.map +1 -0
  29. package/dist/audit.d.ts +4 -5
  30. package/dist/audit.d.ts.map +1 -0
  31. package/dist/audit.js +2743 -28
  32. package/dist/audit.js.map +7 -1
  33. package/dist/bash-kill-guard.d.ts +62 -0
  34. package/dist/bash-kill-guard.d.ts.map +1 -0
  35. package/dist/bash.d.ts +4 -5
  36. package/dist/bash.d.ts.map +1 -0
  37. package/dist/bash.js +59 -30
  38. package/dist/bash.js.map +7 -1
  39. package/dist/batch-tool-use.d.ts +4 -5
  40. package/dist/batch-tool-use.d.ts.map +1 -0
  41. package/dist/batch-tool-use.js +3 -3
  42. package/dist/batch-tool-use.js.map +7 -1
  43. package/dist/builtin.d.ts +7 -9
  44. package/dist/builtin.d.ts.map +1 -0
  45. package/dist/builtin.js +5282 -1019
  46. package/dist/builtin.js.map +7 -1
  47. package/dist/circuit-breaker.d.ts +4 -5
  48. package/dist/circuit-breaker.d.ts.map +1 -0
  49. package/dist/circuit-breaker.js +3 -3
  50. package/dist/circuit-breaker.js.map +7 -1
  51. package/dist/codebase-index/background-indexer.d.ts +116 -0
  52. package/dist/codebase-index/background-indexer.d.ts.map +1 -0
  53. package/dist/codebase-index/bm25.d.ts +40 -0
  54. package/dist/codebase-index/bm25.d.ts.map +1 -0
  55. package/dist/codebase-index/circuit-breaker.d.ts +94 -0
  56. package/dist/codebase-index/circuit-breaker.d.ts.map +1 -0
  57. package/dist/codebase-index/codebase-index-tool.d.ts +17 -0
  58. package/dist/codebase-index/codebase-index-tool.d.ts.map +1 -0
  59. package/dist/codebase-index/codebase-search-tool.d.ts +43 -0
  60. package/dist/codebase-index/codebase-search-tool.d.ts.map +1 -0
  61. package/dist/codebase-index/codebase-stats-tool.d.ts +23 -0
  62. package/dist/codebase-index/codebase-stats-tool.d.ts.map +1 -0
  63. package/dist/codebase-index/gitignore.d.ts +22 -0
  64. package/dist/codebase-index/gitignore.d.ts.map +1 -0
  65. package/dist/codebase-index/go-parser.d.ts +16 -0
  66. package/dist/codebase-index/go-parser.d.ts.map +1 -0
  67. package/dist/codebase-index/index-service.d.ts +25 -0
  68. package/dist/codebase-index/index-service.d.ts.map +1 -0
  69. package/dist/codebase-index/index.d.ts +23 -271
  70. package/dist/codebase-index/index.d.ts.map +1 -0
  71. package/dist/codebase-index/index.js +136 -68
  72. package/dist/codebase-index/index.js.map +7 -1
  73. package/dist/codebase-index/indexer.d.ts +28 -0
  74. package/dist/codebase-index/indexer.d.ts.map +1 -0
  75. package/dist/codebase-index/json-parser.d.ts +8 -0
  76. package/dist/codebase-index/json-parser.d.ts.map +1 -0
  77. package/dist/codebase-index/lsp-kind.d.ts +53 -0
  78. package/dist/codebase-index/lsp-kind.d.ts.map +1 -0
  79. package/dist/codebase-index/py-parser.d.ts +16 -0
  80. package/dist/codebase-index/py-parser.d.ts.map +1 -0
  81. package/dist/codebase-index/refs-extractor.d.ts +25 -0
  82. package/dist/codebase-index/refs-extractor.d.ts.map +1 -0
  83. package/dist/codebase-index/rs-parser.d.ts +8 -0
  84. package/dist/codebase-index/rs-parser.d.ts.map +1 -0
  85. package/dist/codebase-index/schema.d.ts +82 -0
  86. package/dist/codebase-index/schema.d.ts.map +1 -0
  87. package/dist/codebase-index/ts-parser.d.ts +30 -0
  88. package/dist/codebase-index/ts-parser.d.ts.map +1 -0
  89. package/dist/codebase-index/worker-protocol.d.ts +77 -0
  90. package/dist/codebase-index/worker-protocol.d.ts.map +1 -0
  91. package/dist/codebase-index/worker.d.ts +16 -2
  92. package/dist/codebase-index/worker.d.ts.map +1 -0
  93. package/dist/codebase-index/worker.js +103 -65
  94. package/dist/codebase-index/worker.js.map +7 -1
  95. package/dist/codebase-index/writer.d.ts +189 -0
  96. package/dist/codebase-index/writer.d.ts.map +1 -0
  97. package/dist/codebase-index/yaml-parser.d.ts +8 -0
  98. package/dist/codebase-index/yaml-parser.d.ts.map +1 -0
  99. package/dist/design.d.ts +38 -0
  100. package/dist/design.d.ts.map +1 -0
  101. package/dist/design.js +270 -0
  102. package/dist/design.js.map +7 -0
  103. package/dist/diff.d.ts +4 -5
  104. package/dist/diff.d.ts.map +1 -0
  105. package/dist/diff.js +14 -12
  106. package/dist/diff.js.map +7 -1
  107. package/dist/document.d.ts +4 -5
  108. package/dist/document.d.ts.map +1 -0
  109. package/dist/document.js +8 -7
  110. package/dist/document.js.map +7 -1
  111. package/dist/edit.d.ts +5 -36
  112. package/dist/edit.d.ts.map +1 -0
  113. package/dist/edit.js +28 -16
  114. package/dist/edit.js.map +7 -1
  115. package/dist/exec.d.ts +67 -2
  116. package/dist/exec.d.ts.map +1 -0
  117. package/dist/exec.js +50 -25
  118. package/dist/exec.js.map +7 -1
  119. package/dist/fetch.d.ts +4 -32
  120. package/dist/fetch.d.ts.map +1 -0
  121. package/dist/fetch.js +89 -77
  122. package/dist/fetch.js.map +7 -1
  123. package/dist/format.d.ts +4 -5
  124. package/dist/format.d.ts.map +1 -0
  125. package/dist/format.js +2415 -28
  126. package/dist/format.js.map +7 -1
  127. package/dist/git.d.ts +4 -5
  128. package/dist/git.d.ts.map +1 -0
  129. package/dist/git.js +10 -9
  130. package/dist/git.js.map +7 -1
  131. package/dist/glob.d.ts +4 -5
  132. package/dist/glob.d.ts.map +1 -0
  133. package/dist/glob.js +15 -12
  134. package/dist/glob.js.map +7 -1
  135. package/dist/grep.d.ts +4 -5
  136. package/dist/grep.d.ts.map +1 -0
  137. package/dist/grep.js +13 -10
  138. package/dist/grep.js.map +7 -1
  139. package/dist/index.d.ts +19 -724
  140. package/dist/index.d.ts.map +1 -0
  141. package/dist/index.js +6088 -1690
  142. package/dist/index.js.map +7 -1
  143. package/dist/install.d.ts +4 -5
  144. package/dist/install.d.ts.map +1 -0
  145. package/dist/install.js +2680 -31
  146. package/dist/install.js.map +7 -1
  147. package/dist/json.d.ts +4 -5
  148. package/dist/json.d.ts.map +1 -0
  149. package/dist/json.js +13 -11
  150. package/dist/json.js.map +7 -1
  151. package/dist/kanban.d.ts +107 -0
  152. package/dist/kanban.d.ts.map +1 -0
  153. package/dist/kanban.js +845 -0
  154. package/dist/kanban.js.map +7 -0
  155. package/dist/languages/detect.d.ts +3 -0
  156. package/dist/languages/detect.d.ts.map +1 -0
  157. package/dist/languages/diagnostics.d.ts +15 -0
  158. package/dist/languages/diagnostics.d.ts.map +1 -0
  159. package/dist/languages/execute-tool.d.ts +34 -0
  160. package/dist/languages/execute-tool.d.ts.map +1 -0
  161. package/dist/languages/execute.d.ts +18 -0
  162. package/dist/languages/execute.d.ts.map +1 -0
  163. package/dist/languages/index.d.ts +12 -0
  164. package/dist/languages/index.d.ts.map +1 -0
  165. package/dist/languages/index.js +4457 -0
  166. package/dist/languages/index.js.map +7 -0
  167. package/dist/languages/legacy-bridge.d.ts +29 -0
  168. package/dist/languages/legacy-bridge.d.ts.map +1 -0
  169. package/dist/languages/package-tool.d.ts +29 -0
  170. package/dist/languages/package-tool.d.ts.map +1 -0
  171. package/dist/languages/plan.d.ts +4 -0
  172. package/dist/languages/plan.d.ts.map +1 -0
  173. package/dist/languages/profile-helpers.d.ts +14 -0
  174. package/dist/languages/profile-helpers.d.ts.map +1 -0
  175. package/dist/languages/profiles/additional.d.ts +3 -0
  176. package/dist/languages/profiles/additional.d.ts.map +1 -0
  177. package/dist/languages/profiles/primary.d.ts +3 -0
  178. package/dist/languages/profiles/primary.d.ts.map +1 -0
  179. package/dist/languages/registry.d.ts +11 -0
  180. package/dist/languages/registry.d.ts.map +1 -0
  181. package/dist/languages/tool.d.ts +32 -0
  182. package/dist/languages/tool.d.ts.map +1 -0
  183. package/dist/languages/types.d.ts +207 -0
  184. package/dist/languages/types.d.ts.map +1 -0
  185. package/dist/lint.d.ts +4 -5
  186. package/dist/lint.d.ts.map +1 -0
  187. package/dist/lint.js +2415 -27
  188. package/dist/lint.js.map +7 -1
  189. package/dist/logs.d.ts +4 -5
  190. package/dist/logs.d.ts.map +1 -0
  191. package/dist/logs.js +16 -10
  192. package/dist/logs.js.map +7 -1
  193. package/dist/memory.d.ts +7 -8
  194. package/dist/memory.d.ts.map +1 -0
  195. package/dist/memory.js +7 -5
  196. package/dist/memory.js.map +7 -1
  197. package/dist/mode.d.ts +4 -5
  198. package/dist/mode.d.ts.map +1 -0
  199. package/dist/mode.js +3 -3
  200. package/dist/mode.js.map +7 -1
  201. package/dist/next-steps.d.ts +5 -6
  202. package/dist/next-steps.d.ts.map +1 -0
  203. package/dist/next-steps.js +5 -4
  204. package/dist/next-steps.js.map +7 -1
  205. package/dist/outdated.d.ts +4 -5
  206. package/dist/outdated.d.ts.map +1 -0
  207. package/dist/outdated.js +4777 -68
  208. package/dist/outdated.js.map +7 -1
  209. package/dist/pack.d.ts +3 -6
  210. package/dist/pack.d.ts.map +1 -0
  211. package/dist/pack.js +5275 -1019
  212. package/dist/pack.js.map +7 -1
  213. package/dist/patch.d.ts +4 -5
  214. package/dist/patch.d.ts.map +1 -0
  215. package/dist/patch.js +18 -16
  216. package/dist/patch.js.map +7 -1
  217. package/dist/plan.d.ts +55 -0
  218. package/dist/plan.d.ts.map +1 -0
  219. package/dist/plan.js +280 -0
  220. package/dist/plan.js.map +7 -0
  221. package/dist/process-guardian.d.ts +100 -0
  222. package/dist/process-guardian.d.ts.map +1 -0
  223. package/dist/process-registry-persistent.d.ts +121 -0
  224. package/dist/process-registry-persistent.d.ts.map +1 -0
  225. package/dist/process-registry.d.ts +13 -17
  226. package/dist/process-registry.d.ts.map +1 -0
  227. package/dist/process-registry.js +15 -9
  228. package/dist/process-registry.js.map +7 -1
  229. package/dist/ps-slash.d.ts +106 -0
  230. package/dist/ps-slash.d.ts.map +1 -0
  231. package/dist/ps-slash.js +1291 -0
  232. package/dist/ps-slash.js.map +7 -0
  233. package/dist/read.d.ts +4 -5
  234. package/dist/read.d.ts.map +1 -0
  235. package/dist/read.js +13 -11
  236. package/dist/read.js.map +7 -1
  237. package/dist/replace.d.ts +4 -5
  238. package/dist/replace.d.ts.map +1 -0
  239. package/dist/replace.js +26 -13
  240. package/dist/replace.js.map +7 -1
  241. package/dist/scaffold.d.ts +4 -5
  242. package/dist/scaffold.d.ts.map +1 -0
  243. package/dist/scaffold.js +16 -14
  244. package/dist/scaffold.js.map +7 -1
  245. package/dist/search.d.ts +5 -6
  246. package/dist/search.d.ts.map +1 -0
  247. package/dist/search.js +24 -25
  248. package/dist/search.js.map +7 -1
  249. package/dist/set-working-dir.d.ts +18 -0
  250. package/dist/set-working-dir.d.ts.map +1 -0
  251. package/dist/shim/node-sqlite.d.ts +3 -0
  252. package/dist/shim/node-sqlite.d.ts.map +1 -0
  253. package/dist/skill.d.ts +45 -0
  254. package/dist/skill.d.ts.map +1 -0
  255. package/dist/skill.js +175 -0
  256. package/dist/skill.js.map +7 -0
  257. package/dist/spawn-background.d.ts +80 -0
  258. package/dist/spawn-background.d.ts.map +1 -0
  259. package/dist/task.d.ts +35 -0
  260. package/dist/task.d.ts.map +1 -0
  261. package/dist/task.js +380 -0
  262. package/dist/task.js.map +7 -0
  263. package/dist/test.d.ts +4 -5
  264. package/dist/test.d.ts.map +1 -0
  265. package/dist/test.js +2419 -27
  266. package/dist/test.js.map +7 -1
  267. package/dist/todo.d.ts +4 -5
  268. package/dist/todo.d.ts.map +1 -0
  269. package/dist/todo.js +5 -5
  270. package/dist/todo.js.map +7 -1
  271. package/dist/tool-diff.d.ts +16 -17
  272. package/dist/tool-diff.d.ts.map +1 -0
  273. package/dist/tool-diff.js +11 -3
  274. package/dist/tool-diff.js.map +7 -1
  275. package/dist/tool-help.d.ts +4 -5
  276. package/dist/tool-help.d.ts.map +1 -0
  277. package/dist/tool-help.js +3 -3
  278. package/dist/tool-help.js.map +7 -1
  279. package/dist/tool-icon-map.d.ts +45 -0
  280. package/dist/tool-icon-map.d.ts.map +1 -0
  281. package/dist/tool-icons.d.ts +5 -6
  282. package/dist/tool-icons.d.ts.map +1 -0
  283. package/dist/tool-icons.js +16 -4
  284. package/dist/tool-icons.js.map +7 -1
  285. package/dist/tool-search.d.ts +4 -5
  286. package/dist/tool-search.d.ts.map +1 -0
  287. package/dist/tool-search.js +3 -3
  288. package/dist/tool-search.js.map +7 -1
  289. package/dist/tool-summary.d.ts +4 -5
  290. package/dist/tool-summary.d.ts.map +1 -0
  291. package/dist/tool-summary.js +5 -3
  292. package/dist/tool-summary.js.map +7 -1
  293. package/dist/tool-use.d.ts +4 -5
  294. package/dist/tool-use.d.ts.map +1 -0
  295. package/dist/tool-use.js +3 -3
  296. package/dist/tool-use.js.map +7 -1
  297. package/dist/tree.d.ts +4 -5
  298. package/dist/tree.d.ts.map +1 -0
  299. package/dist/tree.js +11 -9
  300. package/dist/tree.js.map +7 -1
  301. package/dist/typecheck.d.ts +4 -5
  302. package/dist/typecheck.d.ts.map +1 -0
  303. package/dist/typecheck.js +2416 -28
  304. package/dist/typecheck.js.map +7 -1
  305. package/dist/write.d.ts +4 -5
  306. package/dist/write.d.ts.map +1 -0
  307. package/dist/write.js +21 -16
  308. package/dist/write.js.map +7 -1
  309. package/package.json +34 -6
  310. package/dist/background-indexer-BeDBxfSh.d.ts +0 -371
  311. package/dist/exec-2OKoT6tk.d.ts +0 -121
package/dist/audit.js CHANGED
@@ -1,18 +1,17 @@
1
- import { spawn } from 'node:child_process';
2
- import * as Core from '@wrongstack/core';
3
- import { buildChildEnv, expectDefined, wstackGlobalRoot } from '@wrongstack/core';
4
- import * as fs from 'node:fs';
5
- import { mkdirSync, createWriteStream } from 'node:fs';
6
- import * as fsp from 'node:fs/promises';
7
- import * as path3 from 'node:path';
8
- import * as os from 'node:os';
9
-
10
1
  // src/_spawn-stream.ts
2
+ import { spawn as spawn2 } from "node:child_process";
3
+ import { buildChildEnv } from "@wrongstack/core";
4
+
5
+ // src/_output-spool.ts
6
+ import { createWriteStream, mkdirSync } from "node:fs";
7
+ import * as fsp from "node:fs/promises";
8
+ import * as path from "node:path";
9
+ import { wstackGlobalRoot } from "@wrongstack/core";
11
10
  var SPOOL_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3;
12
11
  var SPOOL_WRITE_HWM_BYTES = 4 * 1024 * 1024;
13
12
  var sweepStarted = false;
14
13
  function toolOutputDir() {
15
- return path3.join(wstackGlobalRoot(), "tool-output");
14
+ return path.join(wstackGlobalRoot(), "tool-output");
16
15
  }
17
16
  function sweepOldSpoolFiles(dir) {
18
17
  if (sweepStarted) return;
@@ -22,7 +21,7 @@ function sweepOldSpoolFiles(dir) {
22
21
  const now = Date.now();
23
22
  for (const name of await fsp.readdir(dir)) {
24
23
  if (!name.endsWith(".log")) continue;
25
- const p = path3.join(dir, name);
24
+ const p = path.join(dir, name);
26
25
  try {
27
26
  const st = await fsp.stat(p);
28
27
  if (now - st.mtimeMs > SPOOL_RETENTION_MS) await fsp.unlink(p);
@@ -39,7 +38,7 @@ function spoolNote(info) {
39
38
  [output truncated \u2014 full ${info.bytes} bytes at ${info.path}${dropped}; read/grep that file selectively instead of re-running with more output]`;
40
39
  }
41
40
  function createOutputSpool(opts) {
42
- const threshold = opts.thresholdBytes;
41
+ const threshold = opts.thresholdBytes ?? 32768;
43
42
  const safeTool = opts.tool.replace(/[^a-zA-Z0-9._-]+/g, "_").slice(0, 40) || "tool";
44
43
  let head = "";
45
44
  let headBytes = 0;
@@ -57,7 +56,7 @@ function createOutputSpool(opts) {
57
56
  sweepOldSpoolFiles(dir);
58
57
  const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
59
58
  const rand = Math.random().toString(36).slice(2, 6);
60
- filePath = path3.join(dir, `${stamp}-${safeTool}-${rand}.log`);
59
+ filePath = path.join(dir, `${stamp}-${safeTool}-${rand}.log`);
61
60
  stream = createWriteStream(filePath, { flags: "w", encoding: "utf8" });
62
61
  stream.on("error", () => {
63
62
  failed = true;
@@ -110,6 +109,10 @@ function createOutputSpool(opts) {
110
109
  };
111
110
  }
112
111
 
112
+ // src/process-registry.ts
113
+ import { spawn } from "node:child_process";
114
+ import * as os from "node:os";
115
+
113
116
  // src/circuit-breaker.ts
114
117
  var DEFAULT_MAX_CONSECUTIVE_FAILURES = 5;
115
118
  var DEFAULT_SLOW_CALL_THRESHOLD_MS = 18e4;
@@ -302,7 +305,8 @@ var CircuitBreaker = class {
302
305
  }
303
306
  };
304
307
 
305
- // src/process-registry.ts
308
+ // src/_redact-command.ts
309
+ import { expectDefined } from "@wrongstack/core";
306
310
  var SENSITIVE_FLAG_PATTERNS = [
307
311
  // --flag=value or --flag "value" (value captured up to next space or comma)
308
312
  /--(?: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,
@@ -332,6 +336,8 @@ function redactCommand(cmd) {
332
336
  }
333
337
  return result;
334
338
  }
339
+
340
+ // src/process-registry.ts
335
341
  var DEFAULT_GRACE_MS = 2e3;
336
342
  var WIN32_TASKKILL_TIMEOUT_MS = 5e3;
337
343
  function killWin32Tree(pid, opts = {}) {
@@ -601,7 +607,8 @@ var ProcessRegistryImpl = class {
601
607
  if (liveRealChild && killWin32Tree(pid, {
602
608
  timeoutMs: Math.max(graceMs, WIN32_TASKKILL_TIMEOUT_MS),
603
609
  onSettled: directFallback
604
- })) ; else {
610
+ })) {
611
+ } else {
605
612
  try {
606
613
  p.child.kill(force ? "SIGKILL" : "SIGTERM");
607
614
  } catch {
@@ -688,15 +695,19 @@ function getProcessRegistry() {
688
695
  }
689
696
  return _registry;
690
697
  }
698
+
699
+ // src/_win32-resolve.ts
700
+ import * as fs from "node:fs";
701
+ import * as path2 from "node:path";
691
702
  function resolveWin32Command(cmd) {
692
703
  if (process.platform !== "win32") return cmd;
693
- if (cmd.includes("/") || cmd.includes("\\") || path3.extname(cmd.replace(/\//g, "\\"))) {
704
+ if (cmd.includes("/") || cmd.includes("\\") || path2.extname(cmd.replace(/\//g, "\\"))) {
694
705
  return cmd;
695
706
  }
696
707
  const pathext = (process.env["PATHEXT"] ?? ".COM;.EXE;.BAT;.CMD;.VBS;.JS;.WS;.MSC").toLowerCase().split(";");
697
- const pathDirs = (process.env["PATH"] ?? "").split(path3.delimiter);
708
+ const pathDirs = (process.env["PATH"] ?? "").split(path2.delimiter);
698
709
  for (const dir of pathDirs) {
699
- const base = path3.join(dir, cmd);
710
+ const base = path2.join(dir, cmd);
700
711
  for (const ext of pathext) {
701
712
  const full = `${base}${ext}`;
702
713
  try {
@@ -734,7 +745,7 @@ function quoteWin32CmdArg(arg) {
734
745
  // src/_spawn-stream.ts
735
746
  var isWin = process.platform === "win32";
736
747
  async function* spawnStream(opts) {
737
- const max = opts.maxBytes;
748
+ const max = opts.maxBytes ?? 2e5;
738
749
  const flushAt = opts.flushBytes ?? 4 * 1024;
739
750
  const maxQueue = opts.maxQueueSize ?? 500;
740
751
  let stdout = "";
@@ -747,7 +758,7 @@ async function* spawnStream(opts) {
747
758
  const shim = needsShell ? buildWin32CmdShimInvocation(resolved, opts.args) : null;
748
759
  const cmd = shim?.command ?? resolved;
749
760
  const args = shim?.args ?? opts.args;
750
- const child = spawn(cmd, args, {
761
+ const child = spawn2(cmd, args, {
751
762
  cwd: opts.cwd,
752
763
  env: buildChildEnv(),
753
764
  stdio: ["ignore", "pipe", "pipe"],
@@ -840,8 +851,8 @@ async function* spawnStream(opts) {
840
851
  try {
841
852
  for (; ; ) {
842
853
  while (queue.length === 0) {
843
- await new Promise((resolve2) => {
844
- waiter = resolve2;
854
+ await new Promise((resolve6) => {
855
+ waiter = resolve6;
845
856
  });
846
857
  }
847
858
  const chunk = queue.shift();
@@ -895,15 +906,19 @@ async function* spawnStream(opts) {
895
906
  }
896
907
  }
897
908
  }
909
+
910
+ // src/_util.ts
911
+ import * as path3 from "node:path";
912
+ import * as Core from "@wrongstack/core";
898
913
  async function detectPackageManager(cwd) {
899
- const { stat: stat2 } = await import('node:fs/promises');
914
+ const { stat: stat5 } = await import("node:fs/promises");
900
915
  try {
901
- await stat2(`${cwd}/pnpm-lock.yaml`);
916
+ await stat5(`${cwd}/pnpm-lock.yaml`);
902
917
  return "pnpm";
903
918
  } catch {
904
919
  }
905
920
  try {
906
- await stat2(`${cwd}/yarn.lock`);
921
+ await stat5(`${cwd}/yarn.lock`);
907
922
  return "yarn";
908
923
  } catch {
909
924
  }
@@ -930,6 +945,2678 @@ function ensureInsideRoot(absPath, ctx) {
930
945
  function safeResolve(input, ctx) {
931
946
  return ensureInsideRoot(resolvePath(input, ctx), ctx);
932
947
  }
948
+ var COMMAND_OUTPUT_MAX_BYTES = 32768;
949
+ var REPEAT_RUN_THRESHOLD = 3;
950
+ function collapseCarriageReturns(text) {
951
+ const lf = text.replace(/\r\n/g, "\n");
952
+ if (!lf.includes("\r")) return lf;
953
+ return lf.split("\n").map((line) => line.includes("\r") ? line.slice(line.lastIndexOf("\r") + 1) : line).join("\n");
954
+ }
955
+ function collapseConsecutiveDuplicates(text, minRun = REPEAT_RUN_THRESHOLD) {
956
+ const lines = text.split("\n");
957
+ const out = [];
958
+ let i = 0;
959
+ while (i < lines.length) {
960
+ let j = i + 1;
961
+ while (j < lines.length && lines[j] === lines[i]) j++;
962
+ const run = j - i;
963
+ if (run >= minRun) {
964
+ out.push(lines[i], `\u2026 \u27E8repeated ${run}\xD7\u27E9`);
965
+ } else {
966
+ for (let k = i; k < j; k++) out.push(lines[k]);
967
+ }
968
+ i = j;
969
+ }
970
+ return out.join("\n");
971
+ }
972
+ function takeHeadBytes(s, maxBytes) {
973
+ if (maxBytes <= 0) return "";
974
+ if (Buffer.byteLength(s, "utf8") <= maxBytes) return s;
975
+ let lo = 0;
976
+ let hi = s.length;
977
+ while (lo < hi) {
978
+ const mid = Math.ceil((lo + hi) / 2);
979
+ if (Buffer.byteLength(s.slice(0, mid), "utf8") <= maxBytes) lo = mid;
980
+ else hi = mid - 1;
981
+ }
982
+ return s.slice(0, lo);
983
+ }
984
+ function takeTailBytes(s, maxBytes) {
985
+ if (maxBytes <= 0) return "";
986
+ if (Buffer.byteLength(s, "utf8") <= maxBytes) return s;
987
+ let lo = 0;
988
+ let hi = s.length;
989
+ while (lo < hi) {
990
+ const mid = Math.ceil((lo + hi) / 2);
991
+ if (Buffer.byteLength(s.slice(s.length - mid), "utf8") <= maxBytes) lo = mid;
992
+ else hi = mid - 1;
993
+ }
994
+ return s.slice(s.length - lo);
995
+ }
996
+ function truncateHeadTail(s, maxBytes) {
997
+ const total = Buffer.byteLength(s, "utf8");
998
+ if (total <= maxBytes) return s;
999
+ const MARKER_RESERVE = 64;
1000
+ const avail = Math.max(0, maxBytes - MARKER_RESERVE);
1001
+ const headBudget = Math.floor(avail * 0.45);
1002
+ const head = takeHeadBytes(s, headBudget);
1003
+ const tail = takeTailBytes(s, avail - Buffer.byteLength(head, "utf8"));
1004
+ const kept = Buffer.byteLength(head, "utf8") + Buffer.byteLength(tail, "utf8");
1005
+ return `${head}
1006
+ \u2026[truncated ${total - kept} bytes]\u2026
1007
+ ${tail}`;
1008
+ }
1009
+ function normalizeCommandOutput(raw, opts = {}) {
1010
+ if (!raw) return raw;
1011
+ let text = Core.stripAnsi(raw);
1012
+ text = collapseCarriageReturns(text);
1013
+ text = text.replace(/[ \t]+$/gm, "");
1014
+ text = collapseConsecutiveDuplicates(text);
1015
+ text = text.replace(/\n{3,}/g, "\n\n");
1016
+ return truncateHeadTail(text, opts.maxBytes ?? COMMAND_OUTPUT_MAX_BYTES);
1017
+ }
1018
+
1019
+ // src/languages/legacy-bridge.ts
1020
+ import * as fs5 from "node:fs/promises";
1021
+ import * as path8 from "node:path";
1022
+
1023
+ // src/languages/detect.ts
1024
+ import { createHash } from "node:crypto";
1025
+ import * as fs2 from "node:fs/promises";
1026
+ import * as path4 from "node:path";
1027
+
1028
+ // src/languages/profile-helpers.ts
1029
+ var DEFAULT_TIMEOUT_MS = 12e4;
1030
+ var DEFAULT_OUTPUT_LIMIT_BYTES = 2e5;
1031
+ function processPlan(ctx, operation, command, args, options) {
1032
+ return {
1033
+ profileId: ctx.workspace.language,
1034
+ workspaceId: ctx.workspace.id,
1035
+ operation,
1036
+ kind: "process",
1037
+ command,
1038
+ args: Object.freeze([...args]),
1039
+ cwd: ctx.workspace.root,
1040
+ env: Object.freeze({}),
1041
+ timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
1042
+ outputLimitBytes: DEFAULT_OUTPUT_LIMIT_BYTES,
1043
+ mutating: options.mutating ?? false,
1044
+ network: options.network ?? false,
1045
+ executesProjectCode: options.executesProjectCode ?? false,
1046
+ reason: options.reason,
1047
+ evidence: ctx.workspace.evidence,
1048
+ parser: options.parser
1049
+ };
1050
+ }
1051
+ function internalPlan(ctx, operation, parser, reason) {
1052
+ return {
1053
+ profileId: ctx.workspace.language,
1054
+ workspaceId: ctx.workspace.id,
1055
+ operation,
1056
+ kind: "internal",
1057
+ command: null,
1058
+ args: Object.freeze([]),
1059
+ cwd: ctx.workspace.root,
1060
+ env: Object.freeze({}),
1061
+ timeoutMs: 5e3,
1062
+ outputLimitBytes: 32768,
1063
+ mutating: false,
1064
+ network: false,
1065
+ executesProjectCode: false,
1066
+ reason,
1067
+ evidence: ctx.workspace.evidence,
1068
+ parser
1069
+ };
1070
+ }
1071
+ function unavailable(ctx, operation, reason) {
1072
+ return {
1073
+ status: "unavailable",
1074
+ profileId: ctx.workspace.language,
1075
+ workspaceId: ctx.workspace.id,
1076
+ operation,
1077
+ reason
1078
+ };
1079
+ }
1080
+ function packageNames(ctx) {
1081
+ return ctx.options.packages ?? [];
1082
+ }
1083
+
1084
+ // src/languages/profiles/additional.ts
1085
+ var IGNORES = Object.freeze([
1086
+ ".git",
1087
+ ".wrongstack",
1088
+ "node_modules",
1089
+ "vendor",
1090
+ "dist",
1091
+ "build",
1092
+ "coverage"
1093
+ ]);
1094
+ function pythonProfile() {
1095
+ return {
1096
+ id: "python",
1097
+ displayName: "Python",
1098
+ extensions: Object.freeze([".py", ".pyi"]),
1099
+ lspLanguageIds: Object.freeze(["python"]),
1100
+ detectors: Object.freeze([
1101
+ { kind: "config", filename: "pyproject.toml", weight: 90 },
1102
+ { kind: "config", filename: "setup.py", weight: 70 },
1103
+ { kind: "config", filename: "setup.cfg", weight: 60 },
1104
+ { kind: "manifest", filename: "requirements.txt", weight: 55 },
1105
+ { kind: "manifest", filename: "Pipfile", weight: 50 },
1106
+ { kind: "lockfile", filename: "poetry.lock", weight: 30 },
1107
+ { kind: "lockfile", filename: "Pipfile.lock", weight: 30 },
1108
+ { kind: "lockfile", filename: "uv.lock", weight: 30 }
1109
+ ]),
1110
+ ignoredDirectories: IGNORES,
1111
+ packageManagers: Object.freeze(["pip", "poetry", "pipenv", "uv"]),
1112
+ executables: Object.freeze(["python", "python3", "ruff", "black", "pytest", "mypy", "pyright"]),
1113
+ operations: Object.freeze({
1114
+ syntax: async (ctx) => {
1115
+ const py = ctx.options.target ? "python3" : "python3";
1116
+ return ctx.options.target ? processPlan(ctx, "syntax", py, ["-m", "py_compile", ctx.options.target], {
1117
+ parser: "python",
1118
+ reason: "Compile the target file to check for syntax errors."
1119
+ }) : unavailable(ctx, "syntax", "Python syntax check requires an explicit target file.");
1120
+ },
1121
+ semantic: async (ctx) => processPlan(ctx, "semantic", "mypy", [".", "--no-error-summary"], {
1122
+ parser: "mypy",
1123
+ reason: "Run mypy type checking on the workspace.",
1124
+ executesProjectCode: true
1125
+ }),
1126
+ lint: async (ctx) => processPlan(ctx, "lint", "ruff", ["check", "."], {
1127
+ parser: "ruff",
1128
+ reason: "Run the Ruff linter on the workspace."
1129
+ }),
1130
+ "format-check": async (ctx) => processPlan(ctx, "format-check", "ruff", ["format", "--check", "."], {
1131
+ parser: "ruff",
1132
+ reason: "Check Python formatting without writing files."
1133
+ }),
1134
+ "format-write": async (ctx) => processPlan(ctx, "format-write", "ruff", ["format", "."], {
1135
+ parser: "ruff",
1136
+ reason: "Format Python source files.",
1137
+ mutating: true
1138
+ }),
1139
+ test: async (ctx) => processPlan(
1140
+ ctx,
1141
+ "test",
1142
+ "pytest",
1143
+ [...ctx.options.filter ? ["-k", ctx.options.filter] : [], "."],
1144
+ {
1145
+ parser: "pytest",
1146
+ reason: ctx.options.filter ? "Run filtered Python tests." : "Run all Python tests.",
1147
+ mutating: true,
1148
+ executesProjectCode: true
1149
+ }
1150
+ ),
1151
+ build: async (ctx) => unavailable(ctx, "build", "Python is interpreted; use semantic or test instead."),
1152
+ "debug-compile": async (ctx) => processPlan(ctx, "debug-compile", "mypy", [".", "--no-error-summary"], {
1153
+ parser: "mypy",
1154
+ reason: "Collect mypy type diagnostics.",
1155
+ executesProjectCode: true
1156
+ }),
1157
+ "package-install": async (ctx) => processPlan(ctx, "package-install", "pip", ["install", "--no-cache-dir"], {
1158
+ parser: "package-text",
1159
+ reason: "Install dependencies from requirements.",
1160
+ mutating: true,
1161
+ network: true
1162
+ }),
1163
+ "package-add": async (ctx) => {
1164
+ const names = packageNames(ctx);
1165
+ return names.length === 0 ? unavailable(ctx, "package-add", "At least one package name is required.") : processPlan(ctx, "package-add", "pip", ["install", ...names], {
1166
+ parser: "package-text",
1167
+ reason: "Install specified Python packages.",
1168
+ mutating: true,
1169
+ network: true
1170
+ });
1171
+ },
1172
+ "package-audit": async (ctx) => processPlan(ctx, "package-audit", "pip", ["audit"], {
1173
+ parser: "pip-audit",
1174
+ reason: "Audit Python dependencies for vulnerabilities.",
1175
+ network: true
1176
+ }),
1177
+ run: async (ctx) => {
1178
+ const entries = ["main.py", "app.py", "__main__.py", "manage.py"];
1179
+ const first = (await Promise.all(
1180
+ entries.map((name) => ctx.pathExists(name).then((ok) => ok ? name : void 0))
1181
+ )).find(Boolean);
1182
+ const args = first ? [first] : [];
1183
+ return processPlan(ctx, "run", "python3", args, {
1184
+ parser: "command-text",
1185
+ reason: first ? `Run the Python entry point ${first}.` : "Run the Python project (no common entry point detected \u2014 add the module path manually).",
1186
+ executesProjectCode: true,
1187
+ mutating: true
1188
+ });
1189
+ }
1190
+ })
1191
+ };
1192
+ }
1193
+ function hasGradleEvidence(ctx) {
1194
+ return ctx.workspace.evidence.some(
1195
+ (e) => e.kind === "manifest" && (e.value === "build.gradle" || e.value === "build.gradle.kts" || e.value === "settings.gradle") || e.kind === "lockfile" && e.value === "gradle.lockfile"
1196
+ );
1197
+ }
1198
+ async function gradleRunner(ctx) {
1199
+ if (await ctx.pathExists("gradlew")) return "gradlew";
1200
+ return "gradle";
1201
+ }
1202
+ function javaProfile() {
1203
+ return {
1204
+ id: "java",
1205
+ displayName: "Java / Kotlin",
1206
+ extensions: Object.freeze([".java", ".kt", ".kts", ".scala"]),
1207
+ lspLanguageIds: Object.freeze(["java", "kotlin"]),
1208
+ detectors: Object.freeze([
1209
+ { kind: "manifest", filename: "pom.xml", weight: 90 },
1210
+ { kind: "manifest", filename: "build.gradle", weight: 85 },
1211
+ { kind: "manifest", filename: "build.gradle.kts", weight: 85 },
1212
+ { kind: "manifest", filename: "settings.gradle", weight: 50 },
1213
+ { kind: "lockfile", filename: "gradle.lockfile", weight: 30 }
1214
+ ]),
1215
+ ignoredDirectories: IGNORES,
1216
+ packageManagers: Object.freeze(["maven", "gradle"]),
1217
+ executables: Object.freeze(["mvn", "gradle", "gradlew", "java", "kotlinc"]),
1218
+ operations: Object.freeze({
1219
+ semantic: async (ctx) => {
1220
+ const isGradle = hasGradleEvidence(ctx);
1221
+ const runner = isGradle ? await gradleRunner(ctx) : "mvn";
1222
+ const args = isGradle ? ["compileJava"] : ["compile", "-q"];
1223
+ const reason = isGradle ? "Compile the Gradle project." : "Compile the Maven project.";
1224
+ return processPlan(ctx, "semantic", runner, args, {
1225
+ parser: isGradle ? "gradle" : "maven",
1226
+ reason,
1227
+ mutating: true,
1228
+ executesProjectCode: true
1229
+ });
1230
+ },
1231
+ lint: async (ctx) => unavailable(
1232
+ ctx,
1233
+ "lint",
1234
+ "Java linting requires a configured checkstyle or spotbugs plugin."
1235
+ ),
1236
+ "format-check": async (ctx) => unavailable(
1237
+ ctx,
1238
+ "format-check",
1239
+ "Java formatting check requires a configured spotless or google-java-format plugin."
1240
+ ),
1241
+ test: async (ctx) => {
1242
+ const isGradle = hasGradleEvidence(ctx);
1243
+ const runner = isGradle ? await gradleRunner(ctx) : "mvn";
1244
+ const args = isGradle ? ["test"] : ["test", "-q"];
1245
+ const reason = isGradle ? "Run Gradle tests." : "Run Maven tests.";
1246
+ return processPlan(ctx, "test", runner, args, {
1247
+ parser: isGradle ? "gradle" : "maven",
1248
+ reason,
1249
+ mutating: true,
1250
+ executesProjectCode: true
1251
+ });
1252
+ },
1253
+ build: async (ctx) => {
1254
+ const isGradle = hasGradleEvidence(ctx);
1255
+ const runner = isGradle ? await gradleRunner(ctx) : "mvn";
1256
+ const args = isGradle ? ["build"] : ["package", "-q", "-DskipTests"];
1257
+ const reason = isGradle ? "Build the Gradle project." : "Build the Maven project, skipping tests.";
1258
+ return processPlan(ctx, "build", runner, args, {
1259
+ parser: isGradle ? "gradle" : "maven",
1260
+ reason,
1261
+ mutating: true,
1262
+ executesProjectCode: true
1263
+ });
1264
+ },
1265
+ run: async (ctx) => {
1266
+ if (!hasGradleEvidence(ctx))
1267
+ return unavailable(
1268
+ ctx,
1269
+ "run",
1270
+ "Maven run requires exec-maven-plugin configuration. Use `mvn exec:java -q` manually."
1271
+ );
1272
+ const runner = await gradleRunner(ctx);
1273
+ return processPlan(ctx, "run", runner, ["run"], {
1274
+ parser: "command-text",
1275
+ reason: `Run the Gradle project entry point via ${runner}.`,
1276
+ executesProjectCode: true,
1277
+ mutating: true
1278
+ });
1279
+ },
1280
+ "package-install": async (ctx) => unavailable(
1281
+ ctx,
1282
+ "package-install",
1283
+ "JVM dependency installation happens through build or dependency:get."
1284
+ ),
1285
+ "package-add": async (ctx) => {
1286
+ const names = packageNames(ctx);
1287
+ 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]}`], {
1288
+ parser: "maven",
1289
+ reason: "Resolve and fetch a Maven dependency.",
1290
+ mutating: true,
1291
+ network: true
1292
+ });
1293
+ }
1294
+ })
1295
+ };
1296
+ }
1297
+ function rubyProfile() {
1298
+ return {
1299
+ id: "ruby",
1300
+ displayName: "Ruby",
1301
+ extensions: Object.freeze([".rb"]),
1302
+ lspLanguageIds: Object.freeze(["ruby"]),
1303
+ detectors: Object.freeze([
1304
+ { kind: "manifest", filename: "Gemfile", weight: 90 },
1305
+ { kind: "config", filename: ".ruby-version", weight: 40 },
1306
+ { kind: "lockfile", filename: "Gemfile.lock", weight: 30 }
1307
+ ]),
1308
+ ignoredDirectories: IGNORES,
1309
+ packageManagers: Object.freeze(["gem", "bundler"]),
1310
+ executables: Object.freeze(["ruby", "gem", "bundle", "rubocop", "rspec"]),
1311
+ operations: Object.freeze({
1312
+ syntax: async (ctx) => ctx.options.target ? processPlan(ctx, "syntax", "ruby", ["-c", ctx.options.target], {
1313
+ parser: "ruby",
1314
+ reason: "Check the target Ruby file for syntax errors."
1315
+ }) : unavailable(ctx, "syntax", "Ruby syntax check requires an explicit target file."),
1316
+ lint: async (ctx) => processPlan(ctx, "lint", "rubocop", ["--format=json"], {
1317
+ parser: "rubocop",
1318
+ reason: "Run RuboCop linter.",
1319
+ executesProjectCode: true
1320
+ }),
1321
+ "format-write": async (ctx) => processPlan(ctx, "format-write", "rubocop", ["--auto-correct"], {
1322
+ parser: "rubocop",
1323
+ reason: "Auto-correct RuboCop violations.",
1324
+ mutating: true,
1325
+ executesProjectCode: true
1326
+ }),
1327
+ test: async (ctx) => processPlan(ctx, "test", "rspec", [], {
1328
+ parser: "rspec",
1329
+ reason: "Run the RSpec test suite.",
1330
+ mutating: true,
1331
+ executesProjectCode: true
1332
+ }),
1333
+ "package-install": async (ctx) => processPlan(ctx, "package-install", "bundle", ["install"], {
1334
+ parser: "package-text",
1335
+ reason: "Install Ruby gem dependencies.",
1336
+ mutating: true,
1337
+ network: true,
1338
+ executesProjectCode: true
1339
+ }),
1340
+ "package-add": async (ctx) => {
1341
+ const names = packageNames(ctx);
1342
+ return names.length === 0 ? unavailable(ctx, "package-add", "At least one gem name is required.") : processPlan(ctx, "package-add", "gem", ["install", ...names], {
1343
+ parser: "package-text",
1344
+ reason: "Install specified Ruby gems.",
1345
+ mutating: true,
1346
+ network: true
1347
+ });
1348
+ },
1349
+ "package-audit": async (ctx) => processPlan(ctx, "package-audit", "bundle", ["audit", "--format=json"], {
1350
+ parser: "bundler-audit",
1351
+ reason: "Audit Ruby gems for vulnerabilities.",
1352
+ network: true
1353
+ }),
1354
+ run: async (ctx) => {
1355
+ const entries = ["main.rb", "app.rb", "server.rb", "config.ru"];
1356
+ const first = (await Promise.all(
1357
+ entries.map((name) => ctx.pathExists(name).then((ok) => ok ? name : void 0))
1358
+ )).find(Boolean);
1359
+ const hasGemfile = await ctx.pathExists("Gemfile");
1360
+ const cmd = hasGemfile ? "bundle" : "ruby";
1361
+ const args = hasGemfile ? ["exec", "ruby", first ?? ""] : [first ?? ""];
1362
+ return processPlan(ctx, "run", cmd, args, {
1363
+ parser: "command-text",
1364
+ reason: first ? `Run the Ruby entry point ${first}.` : "Run the Ruby project (no common entry point detected \u2014 add the file path manually).",
1365
+ executesProjectCode: true,
1366
+ mutating: true
1367
+ });
1368
+ }
1369
+ })
1370
+ };
1371
+ }
1372
+ function cProfile() {
1373
+ return {
1374
+ id: "c",
1375
+ displayName: "C / C++",
1376
+ extensions: Object.freeze([".c", ".h"]),
1377
+ lspLanguageIds: Object.freeze(["c"]),
1378
+ detectors: Object.freeze([
1379
+ { kind: "manifest", filename: "CMakeLists.txt", weight: 85 },
1380
+ { kind: "manifest", filename: "Makefile", weight: 60 },
1381
+ { kind: "config", suffix: ".cmake", weight: 50 }
1382
+ ]),
1383
+ ignoredDirectories: IGNORES,
1384
+ packageManagers: Object.freeze([]),
1385
+ executables: Object.freeze(["cc", "gcc", "clang", "cmake", "make"]),
1386
+ operations: Object.freeze({
1387
+ semantic: async (ctx) => processPlan(ctx, "semantic", "cmake", ["--build", ".", "--target", "all"], {
1388
+ parser: "cmake",
1389
+ reason: "Build C project to collect compiler diagnostics.",
1390
+ mutating: true,
1391
+ executesProjectCode: true
1392
+ }),
1393
+ test: async (ctx) => unavailable(
1394
+ ctx,
1395
+ "test",
1396
+ "C test execution requires a configured test runner (ctest, etc.)."
1397
+ ),
1398
+ build: async (ctx) => processPlan(ctx, "build", "cmake", ["--build", "."], {
1399
+ parser: "cmake",
1400
+ reason: "Build the C project.",
1401
+ mutating: true,
1402
+ executesProjectCode: true
1403
+ })
1404
+ })
1405
+ };
1406
+ }
1407
+ function cppProfile() {
1408
+ return {
1409
+ ...cProfile(),
1410
+ id: "cpp",
1411
+ displayName: "C++",
1412
+ extensions: Object.freeze([".cpp", ".cc", ".cxx", ".hpp", ".hxx"]),
1413
+ lspLanguageIds: Object.freeze(["cpp"]),
1414
+ detectors: Object.freeze([
1415
+ { kind: "manifest", filename: "CMakeLists.txt", weight: 85 },
1416
+ { kind: "manifest", filename: "Makefile", weight: 50 }
1417
+ ]),
1418
+ executables: Object.freeze(["c++", "g++", "clang++", "cmake", "make"])
1419
+ };
1420
+ }
1421
+ function swiftProfile() {
1422
+ return {
1423
+ id: "swift",
1424
+ displayName: "Swift",
1425
+ extensions: Object.freeze([".swift"]),
1426
+ lspLanguageIds: Object.freeze(["swift"]),
1427
+ detectors: Object.freeze([{ kind: "manifest", filename: "Package.swift", weight: 90 }]),
1428
+ ignoredDirectories: IGNORES,
1429
+ packageManagers: Object.freeze(["swift"]),
1430
+ executables: Object.freeze(["swift", "swiftc"]),
1431
+ operations: Object.freeze({
1432
+ semantic: async (ctx) => processPlan(ctx, "semantic", "swift", ["build"], {
1433
+ parser: "swift",
1434
+ reason: "Build Swift package to collect compiler diagnostics.",
1435
+ mutating: true,
1436
+ executesProjectCode: true
1437
+ }),
1438
+ test: async (ctx) => processPlan(ctx, "test", "swift", ["test"], {
1439
+ parser: "swift-test",
1440
+ reason: "Run Swift tests.",
1441
+ mutating: true,
1442
+ executesProjectCode: true
1443
+ }),
1444
+ build: async (ctx) => processPlan(ctx, "build", "swift", ["build", "-c", "release"], {
1445
+ parser: "swift",
1446
+ reason: "Build the Swift package in release mode.",
1447
+ mutating: true,
1448
+ executesProjectCode: true
1449
+ }),
1450
+ run: async (ctx) => processPlan(ctx, "run", "swift", ["run"], {
1451
+ parser: "command-text",
1452
+ reason: "Run the Swift package entry point.",
1453
+ executesProjectCode: true
1454
+ })
1455
+ })
1456
+ };
1457
+ }
1458
+ function dartProfile() {
1459
+ return {
1460
+ id: "dart",
1461
+ displayName: "Dart / Flutter",
1462
+ extensions: Object.freeze([".dart"]),
1463
+ lspLanguageIds: Object.freeze(["dart"]),
1464
+ detectors: Object.freeze([
1465
+ { kind: "manifest", filename: "pubspec.yaml", weight: 90 },
1466
+ { kind: "lockfile", filename: "pubspec.lock", weight: 30 }
1467
+ ]),
1468
+ ignoredDirectories: IGNORES,
1469
+ packageManagers: Object.freeze(["pub"]),
1470
+ executables: Object.freeze(["dart", "flutter"]),
1471
+ operations: Object.freeze({
1472
+ semantic: async (ctx) => processPlan(ctx, "semantic", "dart", ["analyze"], {
1473
+ parser: "dart-analyze",
1474
+ reason: "Run Dart static analysis."
1475
+ }),
1476
+ "format-check": async (ctx) => processPlan(
1477
+ ctx,
1478
+ "format-check",
1479
+ "dart",
1480
+ ["format", "--output=none", "--set-exit-if-changed", "."],
1481
+ {
1482
+ parser: "dart-format",
1483
+ reason: "Check Dart formatting without writing files."
1484
+ }
1485
+ ),
1486
+ "format-write": async (ctx) => processPlan(ctx, "format-write", "dart", ["format", "."], {
1487
+ parser: "dart-format",
1488
+ reason: "Format Dart source files.",
1489
+ mutating: true
1490
+ }),
1491
+ test: async (ctx) => processPlan(ctx, "test", "dart", ["test"], {
1492
+ parser: "dart-test",
1493
+ reason: "Run Dart tests.",
1494
+ mutating: true,
1495
+ executesProjectCode: true
1496
+ }),
1497
+ "package-install": async (ctx) => processPlan(ctx, "package-install", "dart", ["pub", "get"], {
1498
+ parser: "package-text",
1499
+ reason: "Fetch Dart package dependencies.",
1500
+ mutating: true,
1501
+ network: true
1502
+ }),
1503
+ "package-outdated": async (ctx) => processPlan(ctx, "package-outdated", "dart", ["pub", "outdated"], {
1504
+ parser: "dart-outdated",
1505
+ reason: "Check for outdated Dart packages.",
1506
+ network: true
1507
+ }),
1508
+ run: async (ctx) => processPlan(ctx, "run", "dart", ["run"], {
1509
+ parser: "command-text",
1510
+ reason: "Run the Dart / Flutter project entry point.",
1511
+ executesProjectCode: true
1512
+ })
1513
+ })
1514
+ };
1515
+ }
1516
+ function denoProfile() {
1517
+ return {
1518
+ id: "deno",
1519
+ displayName: "Deno",
1520
+ extensions: Object.freeze([".ts", ".tsx", ".js", ".jsx"]),
1521
+ lspLanguageIds: Object.freeze(["typescript", "javascript"]),
1522
+ detectors: Object.freeze([
1523
+ { kind: "config", filename: "deno.json", weight: 90 },
1524
+ { kind: "config", filename: "deno.jsonc", weight: 90 },
1525
+ { kind: "config", filename: "import_map.json", weight: 60 }
1526
+ ]),
1527
+ ignoredDirectories: IGNORES,
1528
+ packageManagers: Object.freeze([]),
1529
+ executables: Object.freeze(["deno"]),
1530
+ // .ts/.js extensions are shared with the TypeScript/JavaScript profiles;
1531
+ // only a deno.json(c)/import_map.json detector hit may establish a workspace.
1532
+ sourceFallback: false,
1533
+ operations: Object.freeze({
1534
+ test: async (ctx) => processPlan(ctx, "test", "deno", ["test"], {
1535
+ parser: "deno-test",
1536
+ reason: "Run Deno tests.",
1537
+ mutating: true,
1538
+ executesProjectCode: true
1539
+ }),
1540
+ run: async (ctx) => processPlan(ctx, "run", "deno", ["run", "--allow-all", "main.ts"], {
1541
+ parser: "command-text",
1542
+ reason: "Run the Deno project entry point with full permission.",
1543
+ executesProjectCode: true,
1544
+ mutating: true
1545
+ })
1546
+ })
1547
+ };
1548
+ }
1549
+ function elixirProfile() {
1550
+ return {
1551
+ id: "elixir",
1552
+ displayName: "Elixir",
1553
+ extensions: Object.freeze([".ex", ".exs"]),
1554
+ lspLanguageIds: Object.freeze(["elixir"]),
1555
+ detectors: Object.freeze([
1556
+ { kind: "manifest", filename: "mix.exs", weight: 90 },
1557
+ { kind: "lockfile", filename: "mix.lock", weight: 30 }
1558
+ ]),
1559
+ ignoredDirectories: IGNORES,
1560
+ packageManagers: Object.freeze(["mix"]),
1561
+ executables: Object.freeze(["mix", "elixir"]),
1562
+ operations: Object.freeze({
1563
+ semantic: async (ctx) => unavailable(ctx, "semantic", "Elixir compilation is handled by the build operation."),
1564
+ lint: async (ctx) => unavailable(ctx, "lint", "Elixir linting requires the credo package."),
1565
+ test: async (ctx) => processPlan(ctx, "test", "mix", ["test"], {
1566
+ parser: "mix-test",
1567
+ reason: "Run ExUnit tests.",
1568
+ mutating: true,
1569
+ executesProjectCode: true
1570
+ }),
1571
+ build: async (ctx) => processPlan(ctx, "build", "mix", ["compile"], {
1572
+ parser: "mix",
1573
+ reason: "Compile the Mix project.",
1574
+ mutating: true,
1575
+ executesProjectCode: true
1576
+ }),
1577
+ run: async (ctx) => processPlan(ctx, "run", "mix", ["run"], {
1578
+ parser: "command-text",
1579
+ reason: "Run the Mix project entry point.",
1580
+ executesProjectCode: true
1581
+ }),
1582
+ "package-install": async (ctx) => processPlan(ctx, "package-install", "mix", ["deps.get"], {
1583
+ parser: "package-text",
1584
+ reason: "Fetch Elixir dependencies.",
1585
+ mutating: true,
1586
+ network: true
1587
+ })
1588
+ })
1589
+ };
1590
+ }
1591
+ function shellProfile() {
1592
+ return {
1593
+ id: "shell",
1594
+ displayName: "Shell",
1595
+ extensions: Object.freeze([".sh", ".bash"]),
1596
+ lspLanguageIds: Object.freeze(["shellscript"]),
1597
+ detectors: Object.freeze([{ kind: "config", filename: "ShellCheckrc", weight: 50 }]),
1598
+ ignoredDirectories: IGNORES,
1599
+ packageManagers: Object.freeze([]),
1600
+ executables: Object.freeze(["bash", "sh", "shellcheck", "shfmt"]),
1601
+ operations: Object.freeze({
1602
+ syntax: async (ctx) => ctx.options.target ? processPlan(ctx, "syntax", "bash", ["-n", ctx.options.target], {
1603
+ parser: "shell",
1604
+ reason: "Check the shell script for syntax errors."
1605
+ }) : unavailable(ctx, "syntax", "Shell syntax check requires an explicit target file."),
1606
+ lint: async (ctx) => ctx.options.target ? processPlan(ctx, "lint", "shellcheck", ["--format=json", ctx.options.target], {
1607
+ parser: "shellcheck",
1608
+ reason: "Run ShellCheck on the target script."
1609
+ }) : unavailable(ctx, "lint", "Shell linting requires an explicit target file."),
1610
+ "format-check": async (ctx) => ctx.options.target ? processPlan(ctx, "format-check", "shfmt", ["-d", ctx.options.target], {
1611
+ parser: "shell",
1612
+ reason: "Check shell formatting without writing."
1613
+ }) : unavailable(
1614
+ ctx,
1615
+ "format-check",
1616
+ "Shell formatting check requires an explicit target file."
1617
+ ),
1618
+ "format-write": async (ctx) => ctx.options.target ? processPlan(ctx, "format-write", "shfmt", ["-w", ctx.options.target], {
1619
+ parser: "shell",
1620
+ reason: "Format the shell script.",
1621
+ mutating: true
1622
+ }) : unavailable(ctx, "format-write", "Shell formatting requires an explicit target file.")
1623
+ })
1624
+ };
1625
+ }
1626
+ var ADDITIONAL_LANGUAGE_PROFILES = Object.freeze([
1627
+ pythonProfile(),
1628
+ javaProfile(),
1629
+ rubyProfile(),
1630
+ cProfile(),
1631
+ cppProfile(),
1632
+ swiftProfile(),
1633
+ dartProfile(),
1634
+ denoProfile(),
1635
+ elixirProfile(),
1636
+ shellProfile()
1637
+ ]);
1638
+
1639
+ // src/languages/profiles/primary.ts
1640
+ var COMMON_IGNORES = Object.freeze([
1641
+ ".git",
1642
+ ".wrongstack",
1643
+ "node_modules",
1644
+ "vendor",
1645
+ "target",
1646
+ "bin",
1647
+ "obj",
1648
+ "dist",
1649
+ "build",
1650
+ "coverage"
1651
+ ]);
1652
+ function nodeManager(ctx) {
1653
+ const lockfiles = new Set(
1654
+ ctx.workspace.evidence.filter((evidence) => evidence.kind === "lockfile").map((evidence) => evidence.value.toLowerCase())
1655
+ );
1656
+ if (lockfiles.size > 1 && !ctx.workspace.packageManager) return void 0;
1657
+ return ctx.workspace.packageManager ?? "npm";
1658
+ }
1659
+ function scriptPlan(ctx, operation, script) {
1660
+ const manager = nodeManager(ctx);
1661
+ if (!manager)
1662
+ return unavailable(
1663
+ ctx,
1664
+ operation,
1665
+ "Conflicting Node lockfiles make the package manager ambiguous."
1666
+ );
1667
+ const args = manager === "npm" ? ["run", script] : [script];
1668
+ return processPlan(ctx, operation, manager, args, {
1669
+ parser: "command-text",
1670
+ reason: `Run the detected ${manager} ${script} script for this workspace.`,
1671
+ mutating: true,
1672
+ executesProjectCode: true
1673
+ });
1674
+ }
1675
+ function nodeExec(ctx, executable, args) {
1676
+ const manager = ctx.workspace.packageManager ?? "npm";
1677
+ if (manager === "pnpm") return { command: "pnpm", args: ["exec", executable, ...args] };
1678
+ if (manager === "yarn") return { command: "yarn", args: ["exec", executable, ...args] };
1679
+ if (manager === "bun") return { command: "bun", args: ["x", executable, ...args] };
1680
+ return { command: "npx", args: ["--no-install", executable, ...args] };
1681
+ }
1682
+ function typescriptProfile() {
1683
+ return {
1684
+ id: "typescript",
1685
+ displayName: "TypeScript",
1686
+ extensions: Object.freeze([".ts", ".tsx", ".mts", ".cts"]),
1687
+ lspLanguageIds: Object.freeze(["typescript", "typescriptreact"]),
1688
+ detectors: Object.freeze([
1689
+ { kind: "config", filename: "tsconfig.json", weight: 90 },
1690
+ { kind: "manifest", filename: "package.json", weight: 55 },
1691
+ { kind: "lockfile", filename: "pnpm-lock.yaml", weight: 30 },
1692
+ { kind: "lockfile", filename: "yarn.lock", weight: 30 },
1693
+ { kind: "lockfile", filename: "package-lock.json", weight: 30 },
1694
+ { kind: "lockfile", filename: "bun.lock", weight: 30 },
1695
+ { kind: "lockfile", filename: "bun.lockb", weight: 30 }
1696
+ ]),
1697
+ ignoredDirectories: COMMON_IGNORES,
1698
+ packageManagers: Object.freeze(["pnpm", "yarn", "bun", "npm"]),
1699
+ executables: Object.freeze(["pnpm", "yarn", "bun", "npx", "npm"]),
1700
+ operations: Object.freeze({
1701
+ syntax: async (ctx) => internalPlan(
1702
+ ctx,
1703
+ "syntax",
1704
+ "typescript-parser",
1705
+ "Parse the target with the TypeScript compiler API."
1706
+ ),
1707
+ semantic: async (ctx) => {
1708
+ const run = nodeExec(ctx, "tsc", ["--noEmit", "--pretty", "false"]);
1709
+ return processPlan(ctx, "semantic", run.command, run.args, {
1710
+ parser: "typescript",
1711
+ reason: "Run the workspace TypeScript compiler without emitting files.",
1712
+ executesProjectCode: true
1713
+ });
1714
+ },
1715
+ lint: async (ctx) => {
1716
+ const run = nodeExec(ctx, "biome", ["lint", "."]);
1717
+ return processPlan(ctx, "lint", run.command, run.args, {
1718
+ parser: "biome",
1719
+ reason: "Run the project-local Biome linter.",
1720
+ executesProjectCode: true
1721
+ });
1722
+ },
1723
+ "format-check": async (ctx) => {
1724
+ const run = nodeExec(ctx, "biome", ["format", "--check", "."]);
1725
+ return processPlan(ctx, "format-check", run.command, run.args, {
1726
+ parser: "biome",
1727
+ reason: "Check formatting with the project-local Biome formatter.",
1728
+ executesProjectCode: true
1729
+ });
1730
+ },
1731
+ "format-write": async (ctx) => {
1732
+ const run = nodeExec(ctx, "biome", ["format", "--write", "."]);
1733
+ return processPlan(ctx, "format-write", run.command, run.args, {
1734
+ parser: "biome",
1735
+ reason: "Format the workspace with the project-local Biome formatter.",
1736
+ mutating: true,
1737
+ executesProjectCode: true
1738
+ });
1739
+ },
1740
+ test: async (ctx) => ctx.options.filter || ctx.options.coverage ? unavailable(
1741
+ ctx,
1742
+ "test",
1743
+ "The detected package script does not expose deterministic filter or coverage adapters."
1744
+ ) : scriptPlan(ctx, "test", "test"),
1745
+ build: async (ctx) => scriptPlan(ctx, "build", "build"),
1746
+ run: async (ctx) => scriptPlan(ctx, "run", "dev"),
1747
+ "debug-compile": async (ctx) => {
1748
+ const run = nodeExec(ctx, "tsc", ["--noEmit", "--pretty", "false"]);
1749
+ return processPlan(ctx, "debug-compile", run.command, run.args, {
1750
+ parser: "typescript",
1751
+ reason: "Collect deterministic TypeScript compiler diagnostics.",
1752
+ executesProjectCode: true
1753
+ });
1754
+ },
1755
+ "package-install": async (ctx) => {
1756
+ const manager = ctx.workspace.packageManager ?? "npm";
1757
+ const args = manager === "yarn" ? ["install", "--ignore-scripts"] : ["install", "--ignore-scripts"];
1758
+ return processPlan(ctx, "package-install", manager, args, {
1759
+ parser: "package-text",
1760
+ reason: `Restore declared dependencies with ${manager} and lifecycle scripts disabled.`,
1761
+ mutating: true,
1762
+ network: true,
1763
+ executesProjectCode: false
1764
+ });
1765
+ },
1766
+ "package-add": async (ctx) => {
1767
+ const names = packageNames(ctx);
1768
+ if (names.length === 0)
1769
+ return unavailable(ctx, "package-add", "At least one package name is required.");
1770
+ const manager = ctx.workspace.packageManager ?? "npm";
1771
+ const args = manager === "npm" ? ["install", "--ignore-scripts", ...names] : ["add", "--ignore-scripts", ...names];
1772
+ return processPlan(ctx, "package-add", manager, args, {
1773
+ parser: "package-text",
1774
+ reason: `Add validated packages with ${manager} and lifecycle scripts disabled.`,
1775
+ mutating: true,
1776
+ network: true
1777
+ });
1778
+ },
1779
+ "package-audit": async (ctx) => {
1780
+ const manager = ctx.workspace.packageManager ?? "npm";
1781
+ return processPlan(ctx, "package-audit", manager, ["audit", "--json"], {
1782
+ parser: "npm-audit",
1783
+ reason: `Audit dependencies with the detected ${manager} package manager.`,
1784
+ network: true
1785
+ });
1786
+ },
1787
+ "package-outdated": async (ctx) => {
1788
+ const manager = ctx.workspace.packageManager ?? "npm";
1789
+ return processPlan(ctx, "package-outdated", manager, ["outdated", "--json"], {
1790
+ parser: "npm-outdated",
1791
+ reason: `Check outdated dependencies with ${manager}.`,
1792
+ network: true
1793
+ });
1794
+ }
1795
+ })
1796
+ };
1797
+ }
1798
+ function javascriptProfile() {
1799
+ const ts = typescriptProfile();
1800
+ return {
1801
+ ...ts,
1802
+ id: "javascript",
1803
+ displayName: "JavaScript",
1804
+ extensions: Object.freeze([".js", ".jsx", ".mjs", ".cjs"]),
1805
+ lspLanguageIds: Object.freeze(["javascript", "javascriptreact"]),
1806
+ detectors: Object.freeze([
1807
+ { kind: "config", filename: "jsconfig.json", weight: 90 },
1808
+ { kind: "manifest", filename: "package.json", weight: 70 },
1809
+ { kind: "lockfile", filename: "pnpm-lock.yaml", weight: 30 },
1810
+ { kind: "lockfile", filename: "yarn.lock", weight: 30 },
1811
+ { kind: "lockfile", filename: "package-lock.json", weight: 30 },
1812
+ { kind: "lockfile", filename: "bun.lock", weight: 30 },
1813
+ { kind: "lockfile", filename: "bun.lockb", weight: 30 }
1814
+ ]),
1815
+ operations: Object.freeze({
1816
+ ...ts.operations,
1817
+ syntax: async (ctx) => internalPlan(
1818
+ ctx,
1819
+ "syntax",
1820
+ "typescript-parser",
1821
+ "Parse JavaScript with the TypeScript compiler API."
1822
+ )
1823
+ })
1824
+ };
1825
+ }
1826
+ var goProfile = {
1827
+ id: "go",
1828
+ displayName: "Go",
1829
+ extensions: Object.freeze([".go"]),
1830
+ lspLanguageIds: Object.freeze(["go"]),
1831
+ detectors: Object.freeze([
1832
+ { kind: "manifest", filename: "go.mod", weight: 90 },
1833
+ { kind: "manifest", filename: "go.work", weight: 95 },
1834
+ { kind: "lockfile", filename: "go.sum", weight: 30 }
1835
+ ]),
1836
+ ignoredDirectories: COMMON_IGNORES,
1837
+ packageManagers: Object.freeze(["go"]),
1838
+ executables: Object.freeze(["go", "gofmt"]),
1839
+ operations: Object.freeze({
1840
+ syntax: async (ctx) => {
1841
+ if (!ctx.target)
1842
+ return unavailable(ctx, "syntax", "Go syntax planning requires a target file.");
1843
+ return processPlan(ctx, "syntax", "gofmt", ["-e", "-d", ctx.target], {
1844
+ parser: "gofmt",
1845
+ reason: "Parse the target and report syntax errors without writing it."
1846
+ });
1847
+ },
1848
+ semantic: async (ctx) => processPlan(ctx, "semantic", "go", ["test", "-run", "^$", "./..."], {
1849
+ parser: "go-test",
1850
+ reason: "Compile all Go packages without selecting tests.",
1851
+ mutating: true,
1852
+ executesProjectCode: true
1853
+ }),
1854
+ lint: async (ctx) => processPlan(ctx, "lint", "go", ["vet", "./..."], {
1855
+ parser: "go-compiler",
1856
+ reason: "Run the standard Go vet checks.",
1857
+ mutating: true,
1858
+ executesProjectCode: true
1859
+ }),
1860
+ "format-check": async (ctx) => ctx.target ? processPlan(ctx, "format-check", "gofmt", ["-d", ctx.target], {
1861
+ parser: "gofmt",
1862
+ reason: "Report Go formatting differences for the target without writing it."
1863
+ }) : unavailable(ctx, "format-check", "Go formatting requires an explicit target file."),
1864
+ "format-write": async (ctx) => ctx.target ? processPlan(ctx, "format-write", "gofmt", ["-w", ctx.target], {
1865
+ parser: "gofmt",
1866
+ reason: "Format the target Go source file.",
1867
+ mutating: true
1868
+ }) : unavailable(ctx, "format-write", "Go formatting requires an explicit target file."),
1869
+ test: async (ctx) => processPlan(
1870
+ ctx,
1871
+ "test",
1872
+ "go",
1873
+ ["test", ...ctx.options.filter ? ["-run", ctx.options.filter] : [], "./..."],
1874
+ {
1875
+ parser: "go-test",
1876
+ reason: ctx.options.filter ? "Run filtered Go tests." : "Run all Go tests.",
1877
+ mutating: true,
1878
+ executesProjectCode: true
1879
+ }
1880
+ ),
1881
+ build: async (ctx) => processPlan(ctx, "build", "go", ["build", "./..."], {
1882
+ parser: "go-compiler",
1883
+ reason: "Build all Go packages.",
1884
+ mutating: true,
1885
+ executesProjectCode: true
1886
+ }),
1887
+ run: async (ctx) => processPlan(ctx, "run", "go", ["run", "."], {
1888
+ parser: "command-text",
1889
+ reason: "Run the Go module entry point.",
1890
+ executesProjectCode: true
1891
+ }),
1892
+ "debug-race": async (ctx) => processPlan(ctx, "debug-race", "go", ["test", "-race", "./..."], {
1893
+ parser: "go-test",
1894
+ reason: "Collect Go race-detector evidence.",
1895
+ mutating: true,
1896
+ executesProjectCode: true
1897
+ }),
1898
+ "package-install": async (ctx) => processPlan(ctx, "package-install", "go", ["mod", "download"], {
1899
+ parser: "go-module",
1900
+ reason: "Download the dependencies declared by go.mod.",
1901
+ mutating: true,
1902
+ network: true
1903
+ }),
1904
+ "package-add": async (ctx) => {
1905
+ const names = packageNames(ctx);
1906
+ if (names.length === 0)
1907
+ return unavailable(ctx, "package-add", "At least one Go module is required.");
1908
+ return processPlan(ctx, "package-add", "go", ["get", ...names], {
1909
+ parser: "go-module",
1910
+ reason: "Add validated Go modules.",
1911
+ mutating: true,
1912
+ network: true
1913
+ });
1914
+ },
1915
+ "package-update": async (ctx) => processPlan(ctx, "package-update", "go", ["get", "-u", "./..."], {
1916
+ parser: "go-module",
1917
+ reason: "Update dependencies of all Go packages.",
1918
+ mutating: true,
1919
+ network: true
1920
+ })
1921
+ })
1922
+ };
1923
+ var rustProfile = {
1924
+ id: "rust",
1925
+ displayName: "Rust",
1926
+ extensions: Object.freeze([".rs"]),
1927
+ lspLanguageIds: Object.freeze(["rust"]),
1928
+ detectors: Object.freeze([
1929
+ { kind: "manifest", filename: "Cargo.toml", weight: 90 },
1930
+ { kind: "lockfile", filename: "Cargo.lock", weight: 30 }
1931
+ ]),
1932
+ ignoredDirectories: COMMON_IGNORES,
1933
+ packageManagers: Object.freeze(["cargo"]),
1934
+ executables: Object.freeze(["cargo"]),
1935
+ operations: Object.freeze({
1936
+ syntax: async (ctx) => processPlan(ctx, "syntax", "cargo", ["check", "--message-format=json"], {
1937
+ parser: "cargo-json",
1938
+ reason: "Check Rust syntax and semantics with Cargo.",
1939
+ mutating: true,
1940
+ executesProjectCode: true
1941
+ }),
1942
+ semantic: async (ctx) => processPlan(ctx, "semantic", "cargo", ["check", "--message-format=json"], {
1943
+ parser: "cargo-json",
1944
+ reason: "Collect Rust compiler diagnostics with Cargo check.",
1945
+ mutating: true,
1946
+ executesProjectCode: true
1947
+ }),
1948
+ lint: async (ctx) => processPlan(ctx, "lint", "cargo", ["clippy", "--message-format=json"], {
1949
+ parser: "cargo-json",
1950
+ reason: "Run Clippy for this crate.",
1951
+ mutating: true,
1952
+ executesProjectCode: true
1953
+ }),
1954
+ "format-check": async (ctx) => processPlan(ctx, "format-check", "cargo", ["fmt", "--check"], {
1955
+ parser: "cargo-fmt",
1956
+ reason: "Check Rust formatting without writing files."
1957
+ }),
1958
+ "format-write": async (ctx) => processPlan(ctx, "format-write", "cargo", ["fmt"], {
1959
+ parser: "cargo-fmt",
1960
+ reason: "Format Rust source files in the workspace.",
1961
+ mutating: true
1962
+ }),
1963
+ "test-compile": async (ctx) => processPlan(ctx, "test-compile", "cargo", ["test", "--no-run", "--message-format=json"], {
1964
+ parser: "cargo-json",
1965
+ reason: "Compile Rust tests without running them.",
1966
+ mutating: true,
1967
+ executesProjectCode: true
1968
+ }),
1969
+ test: async (ctx) => processPlan(
1970
+ ctx,
1971
+ "test",
1972
+ "cargo",
1973
+ ["test", ...ctx.options.filter ? [ctx.options.filter] : []],
1974
+ {
1975
+ parser: "cargo-test",
1976
+ reason: ctx.options.filter ? "Run filtered Rust tests." : "Run Rust tests.",
1977
+ mutating: true,
1978
+ executesProjectCode: true
1979
+ }
1980
+ ),
1981
+ build: async (ctx) => processPlan(ctx, "build", "cargo", ["build", "--message-format=json"], {
1982
+ parser: "cargo-json",
1983
+ reason: "Build the Rust workspace.",
1984
+ mutating: true,
1985
+ executesProjectCode: true
1986
+ }),
1987
+ run: async (ctx) => processPlan(ctx, "run", "cargo", ["run"], {
1988
+ parser: "command-text",
1989
+ reason: "Run the Rust workspace entry point.",
1990
+ executesProjectCode: true
1991
+ }),
1992
+ "package-install": async (ctx) => processPlan(ctx, "package-install", "cargo", ["fetch", "--locked"], {
1993
+ parser: "cargo-json",
1994
+ reason: "Fetch locked Rust dependencies.",
1995
+ mutating: true,
1996
+ network: true
1997
+ }),
1998
+ "package-add": async (ctx) => {
1999
+ const names = packageNames(ctx);
2000
+ return names.length === 0 ? unavailable(ctx, "package-add", "At least one crate is required.") : processPlan(ctx, "package-add", "cargo", ["add", ...names], {
2001
+ parser: "cargo-text",
2002
+ reason: "Add validated Rust crates.",
2003
+ mutating: true,
2004
+ network: true
2005
+ });
2006
+ },
2007
+ "package-remove": async (ctx) => {
2008
+ const names = packageNames(ctx);
2009
+ return names.length === 0 ? unavailable(ctx, "package-remove", "At least one crate is required.") : processPlan(ctx, "package-remove", "cargo", ["remove", ...names], {
2010
+ parser: "cargo-text",
2011
+ reason: "Remove validated Rust crates.",
2012
+ mutating: true
2013
+ });
2014
+ },
2015
+ "package-update": async (ctx) => processPlan(ctx, "package-update", "cargo", ["update"], {
2016
+ parser: "cargo-text",
2017
+ reason: "Update the Cargo lockfile.",
2018
+ mutating: true,
2019
+ network: true
2020
+ }),
2021
+ "package-audit": async (ctx) => processPlan(ctx, "package-audit", "cargo", ["audit", "--json"], {
2022
+ parser: "cargo-audit",
2023
+ reason: "Audit Rust dependencies when cargo-audit is installed.",
2024
+ network: true
2025
+ })
2026
+ })
2027
+ };
2028
+ var phpProfile = {
2029
+ id: "php",
2030
+ displayName: "PHP",
2031
+ extensions: Object.freeze([".php"]),
2032
+ lspLanguageIds: Object.freeze(["php"]),
2033
+ detectors: Object.freeze([
2034
+ { kind: "manifest", filename: "composer.json", weight: 90 },
2035
+ { kind: "lockfile", filename: "composer.lock", weight: 30 },
2036
+ { kind: "config", filename: "phpunit.xml", weight: 25 },
2037
+ { kind: "config", filename: "phpunit.xml.dist", weight: 25 }
2038
+ ]),
2039
+ ignoredDirectories: COMMON_IGNORES,
2040
+ packageManagers: Object.freeze(["composer"]),
2041
+ executables: Object.freeze(["php", "composer"]),
2042
+ operations: Object.freeze({
2043
+ syntax: async (ctx) => ctx.target ? processPlan(ctx, "syntax", "php", ["-l", ctx.target], {
2044
+ parser: "php-lint",
2045
+ reason: "Lint the target PHP file without executing it."
2046
+ }) : unavailable(ctx, "syntax", "PHP syntax planning requires a target file."),
2047
+ semantic: async (ctx) => unavailable(
2048
+ ctx,
2049
+ "semantic",
2050
+ "No configured PHPStan or Psalm adapter was detected in Phase 1."
2051
+ ),
2052
+ test: async (ctx) => processPlan(
2053
+ ctx,
2054
+ "test",
2055
+ "php",
2056
+ ["vendor/bin/phpunit", ...ctx.options.filter ? ["--filter", ctx.options.filter] : []],
2057
+ {
2058
+ parser: "phpunit",
2059
+ reason: ctx.options.filter ? "Run filtered tests with the project-local PHPUnit runner." : "Run the project-local PHPUnit test runner.",
2060
+ executesProjectCode: true
2061
+ }
2062
+ ),
2063
+ "package-install": async (ctx) => processPlan(
2064
+ ctx,
2065
+ "package-install",
2066
+ "composer",
2067
+ ["install", "--no-interaction", "--no-scripts"],
2068
+ {
2069
+ parser: "composer",
2070
+ reason: "Restore Composer dependencies without scripts.",
2071
+ mutating: true,
2072
+ network: true
2073
+ }
2074
+ ),
2075
+ "package-add": async (ctx) => {
2076
+ const names = packageNames(ctx);
2077
+ return names.length === 0 ? unavailable(ctx, "package-add", "At least one Composer package is required.") : processPlan(
2078
+ ctx,
2079
+ "package-add",
2080
+ "composer",
2081
+ ["require", "--no-interaction", "--no-scripts", ...names],
2082
+ {
2083
+ parser: "composer",
2084
+ reason: "Add validated Composer packages without scripts.",
2085
+ mutating: true,
2086
+ network: true
2087
+ }
2088
+ );
2089
+ },
2090
+ "package-remove": async (ctx) => {
2091
+ const names = packageNames(ctx);
2092
+ return names.length === 0 ? unavailable(ctx, "package-remove", "At least one Composer package is required.") : processPlan(
2093
+ ctx,
2094
+ "package-remove",
2095
+ "composer",
2096
+ ["remove", "--no-interaction", "--no-scripts", ...names],
2097
+ {
2098
+ parser: "composer",
2099
+ reason: "Remove validated Composer packages without scripts.",
2100
+ mutating: true
2101
+ }
2102
+ );
2103
+ },
2104
+ "package-update": async (ctx) => processPlan(
2105
+ ctx,
2106
+ "package-update",
2107
+ "composer",
2108
+ ["update", "--no-interaction", "--no-scripts"],
2109
+ {
2110
+ parser: "composer",
2111
+ reason: "Update Composer dependencies without scripts.",
2112
+ mutating: true,
2113
+ network: true
2114
+ }
2115
+ ),
2116
+ "package-audit": async (ctx) => processPlan(ctx, "package-audit", "composer", ["audit", "--format=json"], {
2117
+ parser: "composer-audit",
2118
+ reason: "Audit Composer dependencies.",
2119
+ network: true
2120
+ }),
2121
+ "package-outdated": async (ctx) => processPlan(ctx, "package-outdated", "composer", ["outdated", "--format=json"], {
2122
+ parser: "composer-outdated",
2123
+ reason: "Check outdated Composer dependencies.",
2124
+ network: true
2125
+ })
2126
+ })
2127
+ };
2128
+ var csharpProfile = {
2129
+ id: "csharp",
2130
+ displayName: "C# / .NET",
2131
+ extensions: Object.freeze([".cs"]),
2132
+ lspLanguageIds: Object.freeze(["csharp"]),
2133
+ detectors: Object.freeze([
2134
+ { kind: "config", filename: "global.json", weight: 25 },
2135
+ { kind: "manifest", suffix: ".slnx", weight: 95 },
2136
+ { kind: "manifest", suffix: ".sln", weight: 95 },
2137
+ { kind: "manifest", suffix: ".csproj", weight: 90 },
2138
+ { kind: "manifest", suffix: ".fsproj", weight: 90 },
2139
+ { kind: "lockfile", filename: "packages.lock.json", weight: 30 }
2140
+ ]),
2141
+ ignoredDirectories: COMMON_IGNORES,
2142
+ packageManagers: Object.freeze(["dotnet"]),
2143
+ executables: Object.freeze(["dotnet"]),
2144
+ operations: Object.freeze({
2145
+ syntax: async (ctx) => processPlan(ctx, "syntax", "dotnet", ["build", "--no-restore"], {
2146
+ parser: "dotnet-build",
2147
+ reason: "Use the nearest project or solution to collect C# syntax diagnostics.",
2148
+ mutating: true,
2149
+ executesProjectCode: true
2150
+ }),
2151
+ semantic: async (ctx) => processPlan(ctx, "semantic", "dotnet", ["build", "--no-restore"], {
2152
+ parser: "dotnet-build",
2153
+ reason: "Build without restoring to collect .NET compiler diagnostics.",
2154
+ mutating: true,
2155
+ executesProjectCode: true
2156
+ }),
2157
+ lint: async (ctx) => processPlan(ctx, "lint", "dotnet", ["format", "--verify-no-changes", "--no-restore"], {
2158
+ parser: "dotnet-format",
2159
+ reason: "Verify .NET formatting and analyzers without writing source files.",
2160
+ mutating: true,
2161
+ executesProjectCode: true
2162
+ }),
2163
+ "format-check": async (ctx) => processPlan(
2164
+ ctx,
2165
+ "format-check",
2166
+ "dotnet",
2167
+ ["format", "--verify-no-changes", "--no-restore"],
2168
+ {
2169
+ parser: "dotnet-format",
2170
+ reason: "Verify .NET formatting without source writes.",
2171
+ mutating: true,
2172
+ executesProjectCode: true
2173
+ }
2174
+ ),
2175
+ "format-write": async (ctx) => processPlan(ctx, "format-write", "dotnet", ["format", "--no-restore"], {
2176
+ parser: "dotnet-format",
2177
+ reason: "Format .NET source files without restoring packages.",
2178
+ mutating: true,
2179
+ executesProjectCode: true
2180
+ }),
2181
+ test: async (ctx) => processPlan(
2182
+ ctx,
2183
+ "test",
2184
+ "dotnet",
2185
+ ["test", "--no-restore", ...ctx.options.filter ? ["--filter", ctx.options.filter] : []],
2186
+ {
2187
+ parser: "dotnet-test",
2188
+ reason: ctx.options.filter ? "Run filtered .NET tests without restoring packages." : "Run .NET tests without restoring packages.",
2189
+ mutating: true,
2190
+ executesProjectCode: true
2191
+ }
2192
+ ),
2193
+ build: async (ctx) => processPlan(ctx, "build", "dotnet", ["build", "--no-restore"], {
2194
+ parser: "dotnet-build",
2195
+ reason: "Build the nearest .NET project or solution without restoring packages.",
2196
+ mutating: true,
2197
+ executesProjectCode: true
2198
+ }),
2199
+ run: async (ctx) => processPlan(ctx, "run", "dotnet", ["run", "--no-restore"], {
2200
+ parser: "command-text",
2201
+ reason: "Run the .NET project entry point.",
2202
+ mutating: true,
2203
+ executesProjectCode: true
2204
+ }),
2205
+ "package-install": async (ctx) => processPlan(ctx, "package-install", "dotnet", ["restore", "--locked-mode"], {
2206
+ parser: "dotnet-restore",
2207
+ reason: "Restore locked .NET dependencies.",
2208
+ mutating: true,
2209
+ network: true,
2210
+ executesProjectCode: true
2211
+ }),
2212
+ "package-add": async (ctx) => {
2213
+ const names = packageNames(ctx);
2214
+ return names.length === 0 ? unavailable(ctx, "package-add", "At least one NuGet package is required.") : processPlan(ctx, "package-add", "dotnet", ["add", "package", ...names], {
2215
+ parser: "dotnet-package",
2216
+ reason: "Add validated NuGet packages.",
2217
+ mutating: true,
2218
+ network: true,
2219
+ executesProjectCode: true
2220
+ });
2221
+ },
2222
+ "package-remove": async (ctx) => {
2223
+ const names = packageNames(ctx);
2224
+ return names.length === 0 ? unavailable(ctx, "package-remove", "At least one NuGet package is required.") : processPlan(ctx, "package-remove", "dotnet", ["remove", "package", ...names], {
2225
+ parser: "dotnet-package",
2226
+ reason: "Remove validated NuGet packages.",
2227
+ mutating: true
2228
+ });
2229
+ },
2230
+ "package-audit": async (ctx) => processPlan(
2231
+ ctx,
2232
+ "package-audit",
2233
+ "dotnet",
2234
+ ["list", "package", "--vulnerable", "--format", "json"],
2235
+ { parser: "dotnet-package", reason: "List vulnerable NuGet dependencies.", network: true }
2236
+ ),
2237
+ "package-outdated": async (ctx) => processPlan(
2238
+ ctx,
2239
+ "package-outdated",
2240
+ "dotnet",
2241
+ ["list", "package", "--outdated", "--format", "json"],
2242
+ { parser: "dotnet-package", reason: "List outdated NuGet dependencies.", network: true }
2243
+ )
2244
+ })
2245
+ };
2246
+ var PRIMARY_LANGUAGE_PROFILES = Object.freeze([
2247
+ Object.freeze(typescriptProfile()),
2248
+ Object.freeze(javascriptProfile()),
2249
+ Object.freeze(goProfile),
2250
+ Object.freeze(rustProfile),
2251
+ Object.freeze(phpProfile),
2252
+ Object.freeze(csharpProfile)
2253
+ ]);
2254
+
2255
+ // src/languages/registry.ts
2256
+ var PROFILE_ID_RE = /^[a-z][a-z0-9-]{0,63}$/;
2257
+ var EXECUTABLE_RE = /^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/;
2258
+ var KNOWN_OPERATIONS = /* @__PURE__ */ new Set([
2259
+ "syntax",
2260
+ "semantic",
2261
+ "lint",
2262
+ "format-check",
2263
+ "format-write",
2264
+ "test-compile",
2265
+ "test",
2266
+ "build",
2267
+ "run",
2268
+ "debug-compile",
2269
+ "debug-test",
2270
+ "debug-runtime",
2271
+ "debug-race",
2272
+ "package-install",
2273
+ "package-add",
2274
+ "package-remove",
2275
+ "package-update",
2276
+ "package-audit",
2277
+ "package-outdated"
2278
+ ]);
2279
+ var LanguageProfileRegistry = class {
2280
+ #profiles = /* @__PURE__ */ new Map();
2281
+ constructor(profiles = []) {
2282
+ for (const profile of profiles) this.register(profile);
2283
+ }
2284
+ register(profile) {
2285
+ const errors = validateLanguageProfile(profile);
2286
+ if (errors.length > 0) {
2287
+ throw new Error(`Invalid language profile "${profile.id}": ${errors.join("; ")}`);
2288
+ }
2289
+ if (this.#profiles.has(profile.id)) {
2290
+ throw new Error(`Language profile "${profile.id}" is already registered`);
2291
+ }
2292
+ this.#profiles.set(profile.id, freezeProfile(profile));
2293
+ }
2294
+ get(id) {
2295
+ return this.#profiles.get(id);
2296
+ }
2297
+ list() {
2298
+ return Object.freeze([...this.#profiles.values()]);
2299
+ }
2300
+ };
2301
+ function validateLanguageProfile(profile) {
2302
+ const errors = [];
2303
+ if (!PROFILE_ID_RE.test(profile.id)) errors.push("id must be a lowercase stable identifier");
2304
+ if (!profile.displayName.trim()) errors.push("displayName is required");
2305
+ if (profile.extensions.length === 0) errors.push("at least one extension is required");
2306
+ for (const ext of profile.extensions) {
2307
+ if (!/^\.[a-z0-9+.-]+$/i.test(ext)) errors.push(`invalid extension "${ext}"`);
2308
+ }
2309
+ if (profile.detectors.length === 0) errors.push("at least one detector is required");
2310
+ for (const detector of profile.detectors) {
2311
+ if ((detector.filename ? 1 : 0) + (detector.suffix ? 1 : 0) !== 1) {
2312
+ errors.push("each detector must declare exactly one of filename or suffix");
2313
+ }
2314
+ if (!Number.isFinite(detector.weight) || detector.weight <= 0 || detector.weight > 100) {
2315
+ errors.push("detector weights must be in the range 1..100");
2316
+ }
2317
+ const marker = detector.filename ?? detector.suffix ?? "";
2318
+ if (marker.includes("/") || marker.includes("\\") || marker.includes("\0")) {
2319
+ errors.push(`detector marker "${marker}" must be a basename or suffix`);
2320
+ }
2321
+ }
2322
+ if (profile.executables.length === 0) errors.push("at least one executable is required");
2323
+ for (const executable of profile.executables) {
2324
+ if (!EXECUTABLE_RE.test(executable)) errors.push(`invalid executable token "${executable}"`);
2325
+ }
2326
+ for (const operation of Object.keys(profile.operations)) {
2327
+ if (!KNOWN_OPERATIONS.has(operation)) {
2328
+ errors.push(`unknown operation "${operation}"`);
2329
+ }
2330
+ if (typeof profile.operations[operation] !== "function") {
2331
+ errors.push(`operation "${operation}" must be a resolver function`);
2332
+ }
2333
+ }
2334
+ return [...new Set(errors)];
2335
+ }
2336
+ function freezeProfile(profile) {
2337
+ const detectors = Object.freeze(profile.detectors.map((item) => Object.freeze({ ...item })));
2338
+ const operations = Object.freeze({ ...profile.operations });
2339
+ return Object.freeze({
2340
+ ...profile,
2341
+ extensions: Object.freeze([...profile.extensions]),
2342
+ lspLanguageIds: Object.freeze([...profile.lspLanguageIds]),
2343
+ detectors,
2344
+ ignoredDirectories: Object.freeze([...profile.ignoredDirectories]),
2345
+ packageManagers: Object.freeze([...profile.packageManagers]),
2346
+ executables: Object.freeze([...profile.executables]),
2347
+ operations
2348
+ });
2349
+ }
2350
+ var languageProfileRegistry = new LanguageProfileRegistry([
2351
+ ...PRIMARY_LANGUAGE_PROFILES,
2352
+ ...ADDITIONAL_LANGUAGE_PROFILES
2353
+ ]);
2354
+
2355
+ // src/languages/detect.ts
2356
+ var DEFAULT_LIMITS = { maxDepth: 6, maxEntries: 5e3 };
2357
+ var SOURCE_WEIGHT = 5;
2358
+ var SOURCE_WEIGHT_CAP = 25;
2359
+ var TARGET_WEIGHT = 100;
2360
+ var GLOBAL_IGNORES = /* @__PURE__ */ new Set([
2361
+ ".git",
2362
+ ".wrongstack",
2363
+ "node_modules",
2364
+ "vendor",
2365
+ "target",
2366
+ "bin",
2367
+ "obj",
2368
+ "dist",
2369
+ "build",
2370
+ "out",
2371
+ "coverage",
2372
+ ".cache",
2373
+ ".idea",
2374
+ ".vscode",
2375
+ ".next",
2376
+ ".nuxt"
2377
+ ]);
2378
+ async function detectLanguageWorkspaces(options) {
2379
+ const projectRoot = await canonicalDirectory(options.projectRoot);
2380
+ const cwdInput = options.cwd ? path4.isAbsolute(options.cwd) ? options.cwd : path4.resolve(projectRoot, options.cwd) : projectRoot;
2381
+ const cwd = await canonicalInside(cwdInput, projectRoot, "cwd");
2382
+ const target = options.target ? await canonicalInside(resolveFrom(cwd, options.target), projectRoot, "target") : void 0;
2383
+ const profiles = (options.profiles ?? languageProfileRegistry.list()).filter((profile) => !options.language || profile.id === options.language).slice().sort((a, b) => a.id.localeCompare(b.id));
2384
+ const limits = normalizeLimits(options.limits);
2385
+ const state = {
2386
+ entries: 0,
2387
+ truncated: false,
2388
+ sourcePaths: /* @__PURE__ */ new Map(),
2389
+ candidates: /* @__PURE__ */ new Map()
2390
+ };
2391
+ await scanDirectory(projectRoot, 0, profiles, limits, state, options.signal);
2392
+ addSourceFallbacks(projectRoot, profiles, state);
2393
+ if (target) addTargetEvidence(target, projectRoot, profiles, state);
2394
+ const workspaces = await Promise.all(
2395
+ [...state.candidates.values()].map((candidate) => finalizeCandidate(candidate, projectRoot))
2396
+ );
2397
+ workspaces.sort(compareWorkspaces);
2398
+ return {
2399
+ projectRoot,
2400
+ scannedEntries: state.entries,
2401
+ truncated: state.truncated,
2402
+ workspaces
2403
+ };
2404
+ }
2405
+ async function scanDirectory(directory, depth, profiles, limits, state, signal) {
2406
+ signal?.throwIfAborted();
2407
+ if (depth > limits.maxDepth || state.entries >= limits.maxEntries) {
2408
+ state.truncated = true;
2409
+ return;
2410
+ }
2411
+ let entries;
2412
+ try {
2413
+ entries = await fs2.readdir(directory, { withFileTypes: true });
2414
+ } catch {
2415
+ return;
2416
+ }
2417
+ entries.sort((a, b) => a.name.localeCompare(b.name));
2418
+ for (const entry of entries) {
2419
+ signal?.throwIfAborted();
2420
+ if (state.entries >= limits.maxEntries) {
2421
+ state.truncated = true;
2422
+ return;
2423
+ }
2424
+ state.entries++;
2425
+ const fullPath = path4.join(directory, entry.name);
2426
+ if (entry.isSymbolicLink()) continue;
2427
+ if (entry.isDirectory()) {
2428
+ if (shouldIgnoreDirectory(entry.name, profiles)) continue;
2429
+ if (depth >= limits.maxDepth) {
2430
+ state.truncated = true;
2431
+ continue;
2432
+ }
2433
+ await scanDirectory(fullPath, depth + 1, profiles, limits, state, signal);
2434
+ continue;
2435
+ }
2436
+ if (!entry.isFile()) continue;
2437
+ collectFileEvidence(directory, fullPath, entry.name, profiles, state);
2438
+ }
2439
+ }
2440
+ function collectFileEvidence(directory, fullPath, basename4, profiles, state) {
2441
+ const lower = basename4.toLowerCase();
2442
+ const extension = path4.extname(lower);
2443
+ for (const profile of profiles) {
2444
+ const detector = profile.detectors.find(
2445
+ (rule) => rule.filename ? lower === rule.filename.toLowerCase() : lower.endsWith(rule.suffix.toLowerCase())
2446
+ );
2447
+ if (detector) {
2448
+ const candidate = getCandidate(state, profile, directory);
2449
+ candidate.evidence.push({
2450
+ kind: detector.kind,
2451
+ path: fullPath,
2452
+ value: basename4,
2453
+ weight: detector.weight
2454
+ });
2455
+ if (detector.kind === "manifest" || detector.kind === "config") {
2456
+ candidate.manifests.push(fullPath);
2457
+ }
2458
+ }
2459
+ if (profile.extensions.includes(extension)) {
2460
+ const paths = state.sourcePaths.get(profile.id) ?? [];
2461
+ if (paths.length < SOURCE_WEIGHT_CAP / SOURCE_WEIGHT) paths.push(fullPath);
2462
+ state.sourcePaths.set(profile.id, paths);
2463
+ }
2464
+ }
2465
+ }
2466
+ function addSourceFallbacks(projectRoot, profiles, state) {
2467
+ for (const profile of profiles) {
2468
+ const sources = state.sourcePaths.get(profile.id) ?? [];
2469
+ if (sources.length === 0) continue;
2470
+ const profileCandidates = [...state.candidates.values()].filter(
2471
+ (item) => item.profile.id === profile.id
2472
+ );
2473
+ for (const source of sources) {
2474
+ const containing = profileCandidates.filter((candidate2) => isInside(source, candidate2.root)).sort(
2475
+ (a, b) => pathDepth(b.root, projectRoot) - pathDepth(a.root, projectRoot) || a.root.localeCompare(b.root)
2476
+ );
2477
+ const candidate = containing[0] ?? (profile.sourceFallback === false ? void 0 : getCandidate(state, profile, projectRoot));
2478
+ if (!candidate) continue;
2479
+ candidate.evidence.push({
2480
+ kind: "source",
2481
+ path: source,
2482
+ value: path4.extname(source),
2483
+ weight: SOURCE_WEIGHT
2484
+ });
2485
+ }
2486
+ }
2487
+ }
2488
+ function addTargetEvidence(target, projectRoot, profiles, state) {
2489
+ const extension = path4.extname(target).toLowerCase();
2490
+ for (const profile of profiles) {
2491
+ if (!profile.extensions.includes(extension)) continue;
2492
+ const candidates = [...state.candidates.values()].filter(
2493
+ (candidate2) => candidate2.profile.id === profile.id && isInside(target, candidate2.root)
2494
+ );
2495
+ const candidate = candidates.length > 0 ? candidates.sort(
2496
+ (a, b) => pathDepth(b.root, projectRoot) - pathDepth(a.root, projectRoot) || a.root.localeCompare(b.root)
2497
+ )[0] : profile.sourceFallback === false ? void 0 : getCandidate(state, profile, path4.dirname(target));
2498
+ if (!candidate) continue;
2499
+ candidate.evidence.push({
2500
+ kind: "target",
2501
+ path: target,
2502
+ value: extension,
2503
+ weight: TARGET_WEIGHT
2504
+ });
2505
+ }
2506
+ }
2507
+ async function finalizeCandidate(candidate, projectRoot) {
2508
+ const evidence = dedupeEvidence(candidate.evidence).sort(compareEvidence);
2509
+ const manifests = [...new Set(candidate.manifests)].sort();
2510
+ const confidence = Math.min(1, evidence.reduce((sum, item) => sum + item.weight, 0) / 100);
2511
+ const packageManager = await detectPackageManager2(candidate.profile, candidate.root, evidence);
2512
+ const id = createHash("sha256").update(`${candidate.profile.id}\0${path4.relative(projectRoot, candidate.root)}`).digest("hex").slice(0, 16);
2513
+ return Object.freeze({
2514
+ id,
2515
+ language: candidate.profile.id,
2516
+ root: candidate.root,
2517
+ confidence,
2518
+ evidence: Object.freeze(evidence.map((item) => Object.freeze(item))),
2519
+ ...packageManager ? { packageManager } : {},
2520
+ manifests: Object.freeze(manifests),
2521
+ capabilities: Object.freeze(
2522
+ Object.keys(candidate.profile.operations).sort()
2523
+ )
2524
+ });
2525
+ }
2526
+ async function detectPackageManager2(profile, root, evidence) {
2527
+ if (profile.packageManagers.length === 1) return profile.packageManagers[0];
2528
+ if (profile.id !== "typescript" && profile.id !== "javascript") return void 0;
2529
+ let declared;
2530
+ try {
2531
+ const pkg = JSON.parse(await fs2.readFile(path4.join(root, "package.json"), "utf8"));
2532
+ if (typeof pkg.packageManager === "string") {
2533
+ const manager = pkg.packageManager.split("@")[0];
2534
+ if (manager && profile.packageManagers.includes(manager)) declared = manager;
2535
+ }
2536
+ } catch {
2537
+ }
2538
+ const lockManagers = /* @__PURE__ */ new Set();
2539
+ for (const item of evidence) {
2540
+ const name = path4.basename(item.path).toLowerCase();
2541
+ if (name === "pnpm-lock.yaml") lockManagers.add("pnpm");
2542
+ else if (name === "yarn.lock") lockManagers.add("yarn");
2543
+ else if (name === "bun.lock" || name === "bun.lockb") lockManagers.add("bun");
2544
+ else if (name === "package-lock.json") lockManagers.add("npm");
2545
+ }
2546
+ if (declared && (lockManagers.size === 0 || lockManagers.size === 1 && lockManagers.has(declared))) {
2547
+ return declared;
2548
+ }
2549
+ if (lockManagers.size === 1) return [...lockManagers][0];
2550
+ if (lockManagers.size > 1) return void 0;
2551
+ return declared ?? "npm";
2552
+ }
2553
+ function getCandidate(state, profile, root) {
2554
+ const key = `${profile.id}\0${root}`;
2555
+ let candidate = state.candidates.get(key);
2556
+ if (!candidate) {
2557
+ candidate = { profile, root, evidence: [], manifests: [] };
2558
+ state.candidates.set(key, candidate);
2559
+ }
2560
+ return candidate;
2561
+ }
2562
+ function shouldIgnoreDirectory(name, profiles) {
2563
+ if (GLOBAL_IGNORES.has(name) || name.startsWith(".")) return true;
2564
+ return profiles.some((profile) => profile.ignoredDirectories.includes(name));
2565
+ }
2566
+ function normalizeLimits(input) {
2567
+ const maxDepth = Math.max(
2568
+ 0,
2569
+ Math.min(12, Math.trunc(input?.maxDepth ?? DEFAULT_LIMITS.maxDepth))
2570
+ );
2571
+ const maxEntries = Math.max(
2572
+ 1,
2573
+ Math.min(5e4, Math.trunc(input?.maxEntries ?? DEFAULT_LIMITS.maxEntries))
2574
+ );
2575
+ return { maxDepth, maxEntries };
2576
+ }
2577
+ async function canonicalDirectory(input) {
2578
+ const resolved = path4.resolve(input);
2579
+ const real = await fs2.realpath(resolved);
2580
+ const stat5 = await fs2.stat(real);
2581
+ if (!stat5.isDirectory()) throw new Error(`Project root is not a directory: ${input}`);
2582
+ return real;
2583
+ }
2584
+ async function canonicalInside(input, root, label) {
2585
+ const resolved = path4.resolve(input);
2586
+ let real;
2587
+ try {
2588
+ real = await fs2.realpath(resolved);
2589
+ } catch (error) {
2590
+ if (error.code !== "ENOENT") throw error;
2591
+ const parent = await fs2.realpath(path4.dirname(resolved));
2592
+ real = path4.join(parent, path4.basename(resolved));
2593
+ }
2594
+ if (!isInside(real, root)) throw new Error(`${label} is outside project root: ${input}`);
2595
+ return real;
2596
+ }
2597
+ function resolveFrom(cwd, input) {
2598
+ return path4.isAbsolute(input) ? input : path4.resolve(cwd, input);
2599
+ }
2600
+ function isInside(candidate, root) {
2601
+ const relative5 = path4.relative(root, candidate);
2602
+ return relative5 === "" || !relative5.startsWith("..") && !path4.isAbsolute(relative5);
2603
+ }
2604
+ function pathDepth(candidate, root) {
2605
+ const relative5 = path4.relative(root, candidate);
2606
+ return relative5 === "" ? 0 : relative5.split(path4.sep).length;
2607
+ }
2608
+ function dedupeEvidence(items) {
2609
+ const seen = /* @__PURE__ */ new Set();
2610
+ return items.filter((item) => {
2611
+ const key = `${item.kind}\0${item.path}\0${item.value}\0${item.weight}`;
2612
+ if (seen.has(key)) return false;
2613
+ seen.add(key);
2614
+ return true;
2615
+ });
2616
+ }
2617
+ function compareEvidence(a, b) {
2618
+ return a.path.localeCompare(b.path) || a.kind.localeCompare(b.kind) || b.weight - a.weight;
2619
+ }
2620
+ function compareWorkspaces(a, b) {
2621
+ return b.confidence - a.confidence || a.language.localeCompare(b.language) || a.root.localeCompare(b.root) || a.id.localeCompare(b.id);
2622
+ }
2623
+
2624
+ // src/languages/diagnostics.ts
2625
+ import * as path5 from "node:path";
2626
+ var MAX_DIAGNOSTICS = 200;
2627
+ function parseLanguageDiagnostics(parser, stdout, stderr, workspaceRoot) {
2628
+ const text = `${stdout}${stdout && stderr ? "\n" : ""}${stderr}`;
2629
+ let diagnostics;
2630
+ switch (parser) {
2631
+ case "typescript":
2632
+ diagnostics = parseTypeScript(text, workspaceRoot);
2633
+ break;
2634
+ case "cargo-json":
2635
+ diagnostics = parseCargoJson(text, workspaceRoot);
2636
+ break;
2637
+ case "php-lint":
2638
+ diagnostics = parsePhpLint(text, workspaceRoot);
2639
+ break;
2640
+ case "dotnet-build":
2641
+ case "dotnet-format":
2642
+ case "dotnet-test":
2643
+ diagnostics = parseDotnet(text, workspaceRoot);
2644
+ break;
2645
+ case "go-test":
2646
+ case "go-compiler":
2647
+ case "gofmt":
2648
+ diagnostics = parseGo(text, workspaceRoot);
2649
+ break;
2650
+ case "biome":
2651
+ diagnostics = parseBiome(text, workspaceRoot);
2652
+ break;
2653
+ default:
2654
+ diagnostics = parseGeneric(text, parser, workspaceRoot);
2655
+ break;
2656
+ }
2657
+ const sorted = dedupeDiagnostics(diagnostics).sort(compareDiagnostics);
2658
+ const omitted = Math.max(0, sorted.length - MAX_DIAGNOSTICS);
2659
+ const kept = Object.freeze(sorted.slice(0, MAX_DIAGNOSTICS).map((item) => Object.freeze(item)));
2660
+ return {
2661
+ diagnostics: kept,
2662
+ omitted,
2663
+ summary: summarize(kept)
2664
+ };
2665
+ }
2666
+ function parseTypeScript(text, root) {
2667
+ const diagnostics = [];
2668
+ const regex = /^(.+?)\((\d+),(\d+)\):\s+(error|warning)\s+(TS\d+):\s*(.+)$/gm;
2669
+ for (const match of text.matchAll(regex)) {
2670
+ diagnostics.push({
2671
+ severity: match[4] === "warning" ? "warning" : "error",
2672
+ code: match[5],
2673
+ message: match[6].trim(),
2674
+ file: normalizeDiagnosticPath(match[1], root),
2675
+ range: { start: { line: toPositiveInt(match[2]), column: toPositiveInt(match[3]) } },
2676
+ source: "typescript"
2677
+ });
2678
+ }
2679
+ return diagnostics;
2680
+ }
2681
+ function parseCargoJson(text, root) {
2682
+ const diagnostics = [];
2683
+ for (const line of text.split(/\r?\n/)) {
2684
+ if (!line.trim().startsWith("{")) continue;
2685
+ try {
2686
+ const value = JSON.parse(line);
2687
+ if (value.reason !== "compiler-message" || !value.message?.message) continue;
2688
+ const primary = value.message.spans?.find((span) => span.is_primary) ?? value.message.spans?.[0];
2689
+ diagnostics.push({
2690
+ severity: normalizeSeverity(value.message.level),
2691
+ ...value.message.code?.code ? { code: value.message.code.code } : {},
2692
+ message: value.message.message,
2693
+ ...primary?.file_name ? { file: normalizeDiagnosticPath(primary.file_name, root) } : {},
2694
+ ...primary?.line_start ? { range: { start: { line: primary.line_start, column: primary.column_start ?? 1 } } } : {},
2695
+ source: "rustc"
2696
+ });
2697
+ } catch {
2698
+ }
2699
+ }
2700
+ return diagnostics;
2701
+ }
2702
+ function parseGo(text, root) {
2703
+ return parseLinePattern(
2704
+ text,
2705
+ /^(.*?\.go):(\d+):(\d+):\s*(.+)$/gm,
2706
+ root,
2707
+ "go",
2708
+ (_match, message) => ({ message, severity: /warning/i.test(message) ? "warning" : "error" })
2709
+ );
2710
+ }
2711
+ function parsePhpLint(text, root) {
2712
+ const diagnostics = [];
2713
+ const regex = /(?:PHP\s+)?(?:Parse|Fatal) error:\s*(.+?)\s+in\s+(.+?)\s+on line\s+(\d+)/gi;
2714
+ for (const match of text.matchAll(regex)) {
2715
+ diagnostics.push({
2716
+ severity: "error",
2717
+ message: match[1].trim(),
2718
+ file: normalizeDiagnosticPath(match[2], root),
2719
+ range: { start: { line: toPositiveInt(match[3]), column: 1 } },
2720
+ source: "php"
2721
+ });
2722
+ }
2723
+ return diagnostics;
2724
+ }
2725
+ function parseDotnet(text, root) {
2726
+ const diagnostics = [];
2727
+ const regex = /^(.+?)\((\d+),(\d+)\):\s*(error|warning)\s+([A-Z]+\d+):\s*(.+?)(?:\s+\[.+\])?$/gm;
2728
+ for (const match of text.matchAll(regex)) {
2729
+ diagnostics.push({
2730
+ severity: match[4] === "warning" ? "warning" : "error",
2731
+ code: match[5],
2732
+ message: match[6].trim(),
2733
+ file: normalizeDiagnosticPath(match[1], root),
2734
+ range: { start: { line: toPositiveInt(match[2]), column: toPositiveInt(match[3]) } },
2735
+ source: "dotnet"
2736
+ });
2737
+ }
2738
+ return diagnostics;
2739
+ }
2740
+ function parseBiome(text, root) {
2741
+ const diagnostics = [];
2742
+ const regex = /^(.+?):(\d+):(\d+)\s+(lint\/[^\s]+|format)\s+(.+)$/gm;
2743
+ for (const match of text.matchAll(regex)) {
2744
+ diagnostics.push({
2745
+ severity: "warning",
2746
+ code: match[4],
2747
+ message: match[5].trim(),
2748
+ file: normalizeDiagnosticPath(match[1], root),
2749
+ range: { start: { line: toPositiveInt(match[2]), column: toPositiveInt(match[3]) } },
2750
+ source: "biome"
2751
+ });
2752
+ }
2753
+ return diagnostics;
2754
+ }
2755
+ function parseGeneric(text, source, root) {
2756
+ return parseLinePattern(
2757
+ text,
2758
+ /^(.+?):(\d+):(\d+):\s*(?:(error|warning|info):\s*)?(.+)$/gm,
2759
+ root,
2760
+ source,
2761
+ (match, fallback) => ({
2762
+ severity: normalizeSeverity(match[4]),
2763
+ message: match[5]?.trim() || fallback
2764
+ })
2765
+ );
2766
+ }
2767
+ function parsePackageReports(parser, stdout, stderr) {
2768
+ const text = `${stdout}${stdout && stderr ? "\n" : ""}${stderr}`;
2769
+ switch (parser) {
2770
+ case "npm-audit":
2771
+ return parseNpmAudit(text);
2772
+ case "npm-outdated":
2773
+ return parseNpmOutdated(text);
2774
+ case "cargo-audit":
2775
+ return parseCargoAudit(text);
2776
+ case "composer-audit":
2777
+ return parseComposerAudit(text);
2778
+ case "composer-outdated":
2779
+ return parseComposerOutdated(text);
2780
+ case "dotnet-package":
2781
+ return parseDotnetPackage(text);
2782
+ default:
2783
+ return { diagnostics: [], vulnerabilities: [], outdated: [] };
2784
+ }
2785
+ }
2786
+ function parseNpmAudit(text) {
2787
+ const advisories = [];
2788
+ const diagnostics = [];
2789
+ let root;
2790
+ try {
2791
+ root = JSON.parse(text);
2792
+ } catch {
2793
+ return { diagnostics, vulnerabilities: advisories, outdated: [] };
2794
+ }
2795
+ const vulnerabilities = root?.vulnerabilities ?? {};
2796
+ const advisoriesRecord = root?.advisories ?? vulnerabilities;
2797
+ for (const [id, value] of Object.entries(advisoriesRecord)) {
2798
+ const advisory = value;
2799
+ const name = advisory.module_name ?? advisory.package_name ?? advisory.name ?? id;
2800
+ advisories.push({
2801
+ package: name,
2802
+ ...advisory.title ? { advisory: advisory.title } : { advisory: id },
2803
+ severity: mapSeverity(advisory.severity),
2804
+ ...advisory.patched_versions ? { fixedIn: advisory.patched_versions } : {},
2805
+ ...advisory.url ? { url: advisory.url } : {}
2806
+ });
2807
+ diagnostics.push({
2808
+ severity: mapSeverity(advisory.severity) === "critical" || mapSeverity(advisory.severity) === "high" ? "error" : "warning",
2809
+ code: id,
2810
+ message: advisory.title ?? `Vulnerability reported for ${name}.`,
2811
+ source: "npm-audit"
2812
+ });
2813
+ }
2814
+ return { diagnostics, vulnerabilities: advisories, outdated: [] };
2815
+ }
2816
+ function parseNpmOutdated(text) {
2817
+ const diagnostics = [];
2818
+ const outdated = [];
2819
+ let payload = {};
2820
+ try {
2821
+ payload = JSON.parse(text);
2822
+ } catch {
2823
+ return { diagnostics, vulnerabilities: [], outdated };
2824
+ }
2825
+ for (const [name, info] of Object.entries(payload)) {
2826
+ const entry = info;
2827
+ if (!entry.latest || entry.latest === entry.current) continue;
2828
+ outdated.push({
2829
+ name,
2830
+ previous: entry.current,
2831
+ resolved: entry.latest,
2832
+ kind: mapOutdatedKind(entry.type)
2833
+ });
2834
+ diagnostics.push({
2835
+ severity: "info",
2836
+ code: "outdated",
2837
+ message: `${name}: ${entry.current ?? "?"} \u2192 ${entry.latest}`,
2838
+ source: "npm-outdated"
2839
+ });
2840
+ }
2841
+ return { diagnostics, vulnerabilities: [], outdated };
2842
+ }
2843
+ function parseCargoAudit(text) {
2844
+ const diagnostics = [];
2845
+ const vulnerabilities = [];
2846
+ let root;
2847
+ try {
2848
+ root = JSON.parse(text);
2849
+ } catch {
2850
+ return { diagnostics, vulnerabilities, outdated: [] };
2851
+ }
2852
+ const findings = root.vulnerabilities?.found;
2853
+ if (!Array.isArray(findings)) return { diagnostics, vulnerabilities, outdated: [] };
2854
+ for (const finding of findings) {
2855
+ const item = finding;
2856
+ const name = item.package ?? "unknown";
2857
+ const advisory = item.id ?? item.advisory?.id ?? "cargo-audit";
2858
+ vulnerabilities.push({
2859
+ package: name,
2860
+ ...item.title ? { advisory: item.title } : { advisory },
2861
+ severity: mapSeverity(item.severity),
2862
+ ...item.patched_versions && item.patched_versions.length > 0 ? { fixedIn: item.patched_versions[0] } : {},
2863
+ ...item.url?.short ? { url: item.url.short } : {}
2864
+ });
2865
+ diagnostics.push({
2866
+ severity: mapSeverity(item.severity) === "critical" || mapSeverity(item.severity) === "high" ? "error" : "warning",
2867
+ code: advisory,
2868
+ message: item.title ?? `${name} reported by cargo-audit.`,
2869
+ source: "cargo-audit"
2870
+ });
2871
+ }
2872
+ return { diagnostics, vulnerabilities, outdated: [] };
2873
+ }
2874
+ function parseComposerAudit(text) {
2875
+ const diagnostics = [];
2876
+ const vulnerabilities = [];
2877
+ const lines = text.split(/\r?\n/);
2878
+ for (const line of lines) {
2879
+ if (!line.trim().startsWith("{")) continue;
2880
+ try {
2881
+ const entry = JSON.parse(line);
2882
+ if (!entry.package) continue;
2883
+ vulnerabilities.push({
2884
+ package: entry.package,
2885
+ ...entry.advisory ? { advisory: entry.advisory } : {},
2886
+ ...entry.title ? { advisory: entry.title } : { advisory: entry.advisory ?? "composer-audit" },
2887
+ severity: mapSeverity(entry.severity),
2888
+ ...entry.affectedVersions ? { fixedIn: entry.affectedVersions } : {},
2889
+ ...entry.url ? { url: entry.url } : {}
2890
+ });
2891
+ diagnostics.push({
2892
+ severity: "warning",
2893
+ code: entry.advisory ?? "composer-audit",
2894
+ message: entry.title ?? `${entry.package} reported by composer audit.`,
2895
+ source: "composer-audit"
2896
+ });
2897
+ } catch {
2898
+ }
2899
+ }
2900
+ return { diagnostics, vulnerabilities, outdated: [] };
2901
+ }
2902
+ function parseComposerOutdated(text) {
2903
+ const diagnostics = [];
2904
+ const outdated = [];
2905
+ const lines = text.split(/\r?\n/);
2906
+ for (const line of lines) {
2907
+ if (!line.trim().startsWith("{")) continue;
2908
+ try {
2909
+ const entry = JSON.parse(line);
2910
+ if (!entry.name || entry.version === entry.latest) continue;
2911
+ outdated.push({
2912
+ name: entry.name,
2913
+ previous: entry.version,
2914
+ resolved: entry.latest ?? entry.version
2915
+ });
2916
+ diagnostics.push({
2917
+ severity: "info",
2918
+ code: "outdated",
2919
+ message: `${entry.name}: ${entry.version ?? "?"} \u2192 ${entry.latest ?? "?"}`,
2920
+ source: "composer-outdated"
2921
+ });
2922
+ } catch {
2923
+ }
2924
+ }
2925
+ return { diagnostics, vulnerabilities: [], outdated };
2926
+ }
2927
+ function parseDotnetPackage(text) {
2928
+ const diagnostics = [];
2929
+ const vulnerabilities = [];
2930
+ const outdated = [];
2931
+ let root;
2932
+ try {
2933
+ root = JSON.parse(text);
2934
+ } catch {
2935
+ return { diagnostics, vulnerabilities, outdated };
2936
+ }
2937
+ const projects = root.projects;
2938
+ if (!Array.isArray(projects)) return { diagnostics, vulnerabilities, outdated };
2939
+ for (const project of projects) {
2940
+ const packages = Array.isArray(project.packages) ? project.packages : [];
2941
+ for (const pkg of packages) {
2942
+ const name = typeof pkg.name === "string" ? pkg.name : "unknown";
2943
+ const requested = typeof pkg.requestedVersion === "string" ? pkg.requestedVersion : void 0;
2944
+ const resolved = typeof pkg.resolvedVersion === "string" ? pkg.resolvedVersion : void 0;
2945
+ const vulnerabilitiesRaw = Array.isArray(pkg.vulnerabilities) ? pkg.vulnerabilities : [];
2946
+ for (const vuln of vulnerabilitiesRaw) {
2947
+ const advisory = typeof vuln.advisoryUrl === "string" ? vuln.advisoryUrl : "dotnet-vulnerable";
2948
+ vulnerabilities.push({
2949
+ package: name,
2950
+ advisory,
2951
+ severity: mapSeverity(typeof vuln.severity === "string" ? vuln.severity : void 0)
2952
+ });
2953
+ }
2954
+ if (vulnerabilitiesRaw.length > 0) {
2955
+ diagnostics.push({
2956
+ severity: "warning",
2957
+ code: "dotnet-vulnerable",
2958
+ message: `${name} has ${vulnerabilitiesRaw.length} known vulnerability entry/entries.`,
2959
+ source: "dotnet-package"
2960
+ });
2961
+ }
2962
+ if (requested && resolved && requested.startsWith(">") && requested.split(">")[1].split(".").slice(0, 2).join(".") !== resolved.split(".").slice(0, 2).join(".")) {
2963
+ outdated.push({ name, requested, resolved });
2964
+ diagnostics.push({
2965
+ severity: "info",
2966
+ code: "outdated",
2967
+ message: `${name}: ${requested} \u2192 ${resolved}`,
2968
+ source: "dotnet-package"
2969
+ });
2970
+ }
2971
+ }
2972
+ }
2973
+ return { diagnostics, vulnerabilities, outdated };
2974
+ }
2975
+ function mapSeverity(value) {
2976
+ switch (value?.toLowerCase()) {
2977
+ case "critical":
2978
+ case "high":
2979
+ return "high";
2980
+ case "medium":
2981
+ case "moderate":
2982
+ return "moderate";
2983
+ case "low":
2984
+ return "low";
2985
+ case "unknown":
2986
+ return "unknown";
2987
+ default:
2988
+ return "unknown";
2989
+ }
2990
+ }
2991
+ function mapOutdatedKind(value) {
2992
+ switch (value?.toLowerCase()) {
2993
+ case "devdependencies":
2994
+ case "development":
2995
+ return "development";
2996
+ case "optionaldependencies":
2997
+ case "optional":
2998
+ return "optional";
2999
+ default:
3000
+ return "runtime";
3001
+ }
3002
+ }
3003
+ function parseLinePattern(text, regex, root, source, details) {
3004
+ const diagnostics = [];
3005
+ for (const match of text.matchAll(regex)) {
3006
+ const parsed = details(match, match.at(-1)?.trim() ?? "Diagnostic");
3007
+ diagnostics.push({
3008
+ severity: parsed.severity,
3009
+ message: parsed.message,
3010
+ file: normalizeDiagnosticPath(match[1], root),
3011
+ range: { start: { line: toPositiveInt(match[2]), column: toPositiveInt(match[3]) } },
3012
+ source
3013
+ });
3014
+ }
3015
+ return diagnostics;
3016
+ }
3017
+ function normalizeDiagnosticPath(value, root) {
3018
+ const clean = value.trim().replace(/^['"]|['"]$/g, "");
3019
+ return path5.resolve(root, clean);
3020
+ }
3021
+ function normalizeSeverity(value) {
3022
+ if (value === "warning" || value === "warn") return "warning";
3023
+ if (value === "info" || value === "note" || value === "help") return "info";
3024
+ if (value === "hint") return "hint";
3025
+ return "error";
3026
+ }
3027
+ function toPositiveInt(value) {
3028
+ return Math.max(1, Number.parseInt(value ?? "1", 10) || 1);
3029
+ }
3030
+ function summarize(diagnostics) {
3031
+ return {
3032
+ errors: diagnostics.filter((item) => item.severity === "error").length,
3033
+ warnings: diagnostics.filter((item) => item.severity === "warning").length,
3034
+ infos: diagnostics.filter((item) => item.severity === "info" || item.severity === "hint").length
3035
+ };
3036
+ }
3037
+ function dedupeDiagnostics(items) {
3038
+ const seen = /* @__PURE__ */ new Set();
3039
+ return items.filter((item) => {
3040
+ const key = [
3041
+ item.source,
3042
+ item.code ?? "",
3043
+ item.file ?? "",
3044
+ item.range?.start.line ?? 0,
3045
+ item.range?.start.column ?? 0,
3046
+ item.message
3047
+ ].join("\0");
3048
+ if (seen.has(key)) return false;
3049
+ seen.add(key);
3050
+ return true;
3051
+ });
3052
+ }
3053
+ function compareDiagnostics(a, b) {
3054
+ 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);
3055
+ }
3056
+ function severityRank(value) {
3057
+ return value === "error" ? 0 : value === "warning" ? 1 : value === "info" ? 2 : 3;
3058
+ }
3059
+
3060
+ // src/languages/execute.ts
3061
+ import * as fs4 from "node:fs/promises";
3062
+ import * as path7 from "node:path";
3063
+
3064
+ // src/languages/plan.ts
3065
+ import * as fs3 from "node:fs/promises";
3066
+ import * as path6 from "node:path";
3067
+ var MAX_ARGUMENTS = 128;
3068
+ var MAX_ARGUMENT_LENGTH = 4096;
3069
+ var PACKAGE_NAME_RE = /^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+(?:@[a-z0-9*+._~^<>=|-]+)?$/i;
3070
+ var COMPOSER_PACKAGE_RE = /^[a-z0-9_.-]+\/[a-z0-9_.-]+(?::[a-z0-9*+._~^<>=|-]+)?$/i;
3071
+ var GO_MODULE_RE = /^(?:[a-z0-9.-]+\.)+[a-z0-9.-]+\/[a-z0-9._~+/@-]+$/i;
3072
+ async function planLanguageOperation(options) {
3073
+ validateOperationOptions(options.operation, options.operationOptions?.packages);
3074
+ const detection = await detectLanguageWorkspaces(options);
3075
+ const candidates = detection.workspaces.filter(
3076
+ (workspace) => workspace.capabilities.includes(options.operation)
3077
+ );
3078
+ const selected = selectWorkspace(candidates, options);
3079
+ if (selected.status !== "selected") return selected.result;
3080
+ const profile = (options.profiles ?? languageProfileRegistry.list()).find(
3081
+ (item) => item.id === selected.workspace.language
3082
+ );
3083
+ if (!profile) {
3084
+ return {
3085
+ status: "not_found",
3086
+ reason: `Profile ${selected.workspace.language} is unavailable.`,
3087
+ candidates
3088
+ };
3089
+ }
3090
+ if ((profile.id === "typescript" || profile.id === "javascript") && options.operation !== "syntax" && selected.workspace.packageManager === void 0 && new Set(
3091
+ selected.workspace.evidence.filter((evidence) => evidence.kind === "lockfile").map((evidence) => evidence.value.toLowerCase())
3092
+ ).size > 1) {
3093
+ return {
3094
+ status: "unavailable",
3095
+ workspace: selected.workspace,
3096
+ unavailable: {
3097
+ status: "unavailable",
3098
+ profileId: profile.id,
3099
+ workspaceId: selected.workspace.id,
3100
+ operation: options.operation,
3101
+ reason: "Conflicting Node lockfiles make the package manager ambiguous."
3102
+ }
3103
+ };
3104
+ }
3105
+ const resolver = profile.operations[options.operation];
3106
+ if (!resolver) {
3107
+ return {
3108
+ status: "unavailable",
3109
+ workspace: selected.workspace,
3110
+ unavailable: {
3111
+ status: "unavailable",
3112
+ profileId: profile.id,
3113
+ workspaceId: selected.workspace.id,
3114
+ operation: options.operation,
3115
+ reason: `${profile.displayName} does not define ${options.operation}.`
3116
+ }
3117
+ };
3118
+ }
3119
+ const canonicalCwd = options.cwd ? path6.isAbsolute(options.cwd) ? options.cwd : path6.resolve(detection.projectRoot, options.cwd) : detection.projectRoot;
3120
+ const target = options.target ? await canonicalTarget(canonicalCwd, options.target, detection.projectRoot) : void 0;
3121
+ const ctx = {
3122
+ projectRoot: detection.projectRoot,
3123
+ workspace: selected.workspace,
3124
+ ...target ? { target } : {},
3125
+ mode: options.mode ?? "standard",
3126
+ options: options.operationOptions ?? {},
3127
+ platform: process.platform,
3128
+ pathExists: async (candidate) => {
3129
+ try {
3130
+ await fs3.access(path6.resolve(detection.projectRoot, candidate));
3131
+ return true;
3132
+ } catch {
3133
+ return false;
3134
+ }
3135
+ }
3136
+ };
3137
+ const result = await resolver(ctx);
3138
+ if ("status" in result) {
3139
+ return { status: "unavailable", workspace: selected.workspace, unavailable: result };
3140
+ }
3141
+ const errors = validateCommandPlan(result, profile, detection.projectRoot);
3142
+ if (errors.length > 0) {
3143
+ return {
3144
+ status: "unavailable",
3145
+ workspace: selected.workspace,
3146
+ unavailable: {
3147
+ status: "unavailable",
3148
+ profileId: profile.id,
3149
+ workspaceId: selected.workspace.id,
3150
+ operation: options.operation,
3151
+ reason: `Generated plan failed validation: ${errors.join("; ")}`
3152
+ }
3153
+ };
3154
+ }
3155
+ return { status: "planned", workspace: selected.workspace, plan: Object.freeze(result) };
3156
+ }
3157
+ function validateCommandPlan(plan, profile, projectRoot) {
3158
+ const errors = [];
3159
+ if (plan.profileId !== profile.id) errors.push("profile id does not match");
3160
+ if (!isInside2(plan.cwd, projectRoot)) errors.push("cwd is outside project root");
3161
+ if (plan.args.length > MAX_ARGUMENTS) errors.push(`argument count exceeds ${MAX_ARGUMENTS}`);
3162
+ if (plan.args.some((arg) => arg.length > MAX_ARGUMENT_LENGTH || /[\r\n\0]/.test(arg))) {
3163
+ errors.push("arguments contain an invalid or oversized value");
3164
+ }
3165
+ if (!Number.isFinite(plan.timeoutMs) || plan.timeoutMs < 1 || plan.timeoutMs > 6e5) {
3166
+ errors.push("timeout is outside 1..600000ms");
3167
+ }
3168
+ if (!Number.isFinite(plan.outputLimitBytes) || plan.outputLimitBytes < 1 || plan.outputLimitBytes > 1e6) {
3169
+ errors.push("output limit is outside 1..1000000 bytes");
3170
+ }
3171
+ if (plan.kind === "internal") {
3172
+ if (plan.command !== null || plan.args.length !== 0)
3173
+ errors.push("internal plans cannot declare a command");
3174
+ } else {
3175
+ if (!plan.command || !profile.executables.includes(plan.command)) {
3176
+ errors.push(`executable "${plan.command ?? ""}" is not allowlisted by the profile`);
3177
+ }
3178
+ }
3179
+ if (Object.keys(plan.env).length > 0)
3180
+ errors.push("Phase 1 plans cannot override environment variables");
3181
+ return errors;
3182
+ }
3183
+ function selectWorkspace(candidates, options) {
3184
+ if (candidates.length === 0) {
3185
+ return {
3186
+ status: "result",
3187
+ result: {
3188
+ status: "not_found",
3189
+ reason: `No workspace supports ${options.operation}.`,
3190
+ candidates: []
3191
+ }
3192
+ };
3193
+ }
3194
+ if (options.workspace) {
3195
+ const requested = path6.isAbsolute(options.workspace) ? path6.resolve(options.workspace) : path6.resolve(options.projectRoot, options.workspace);
3196
+ const matches = candidates.filter(
3197
+ (item) => item.id === options.workspace || path6.resolve(item.root) === requested
3198
+ );
3199
+ if (matches.length === 1) return { status: "selected", workspace: matches[0] };
3200
+ return {
3201
+ status: "result",
3202
+ result: {
3203
+ status: "not_found",
3204
+ reason: `Requested workspace "${options.workspace}" was not detected.`,
3205
+ candidates: [...candidates]
3206
+ }
3207
+ };
3208
+ }
3209
+ if (options.target) {
3210
+ const base = options.cwd ? path6.isAbsolute(options.cwd) ? path6.resolve(options.cwd) : path6.resolve(options.projectRoot, options.cwd) : path6.resolve(options.projectRoot);
3211
+ const target = path6.isAbsolute(options.target) ? path6.resolve(options.target) : path6.resolve(base, options.target);
3212
+ const targeted = candidates.filter((item) => item.evidence.some((evidence) => evidence.kind === "target")).sort(
3213
+ (a, b) => workspaceDepth(b.root, options.projectRoot) - workspaceDepth(a.root, options.projectRoot) || compareCandidates(a, b)
3214
+ );
3215
+ if (targeted[0]) return { status: "selected", workspace: targeted[0] };
3216
+ const containing = candidates.filter((item) => isInside2(target, item.root)).sort(
3217
+ (a, b) => workspaceDepth(b.root, options.projectRoot) - workspaceDepth(a.root, options.projectRoot) || compareCandidates(a, b)
3218
+ );
3219
+ if (containing[0]) return { status: "selected", workspace: containing[0] };
3220
+ }
3221
+ const sorted = [...candidates].sort(compareCandidates);
3222
+ const first = sorted[0];
3223
+ const firstDepth = workspaceDepth(first.root, options.projectRoot);
3224
+ const tied = sorted.filter(
3225
+ (item) => item.confidence === first.confidence && workspaceDepth(item.root, options.projectRoot) === firstDepth
3226
+ );
3227
+ if (tied.length > 1) {
3228
+ return {
3229
+ status: "result",
3230
+ result: {
3231
+ status: "ambiguous",
3232
+ reason: "Multiple workspaces have equal confidence; provide target, language, or workspace.",
3233
+ candidates: tied
3234
+ }
3235
+ };
3236
+ }
3237
+ return { status: "selected", workspace: first };
3238
+ }
3239
+ function compareCandidates(a, b) {
3240
+ return b.confidence - a.confidence || a.language.localeCompare(b.language) || a.root.localeCompare(b.root);
3241
+ }
3242
+ function workspaceDepth(workspaceRoot, projectRoot) {
3243
+ const relative5 = path6.relative(path6.resolve(projectRoot), path6.resolve(workspaceRoot));
3244
+ return relative5 === "" ? 0 : relative5.split(path6.sep).length;
3245
+ }
3246
+ function validateOperationOptions(operation, packages) {
3247
+ if (!operation.startsWith("package-") || !packages) return;
3248
+ for (const value of packages) {
3249
+ if (!value || value.length > 214 || value.startsWith("-") || /[\r\n\0;&|`$<>\\]/.test(value)) {
3250
+ throw new Error(`Invalid package identifier "${value}"`);
3251
+ }
3252
+ if (value.startsWith(".") || value.startsWith("/") || /^[A-Za-z]:/.test(value) || value.includes("://")) {
3253
+ throw new Error(`Package paths and URLs are not supported: "${value}"`);
3254
+ }
3255
+ if (!PACKAGE_NAME_RE.test(value) && !COMPOSER_PACKAGE_RE.test(value) && !GO_MODULE_RE.test(value)) {
3256
+ throw new Error(`Invalid package identifier "${value}"`);
3257
+ }
3258
+ }
3259
+ }
3260
+ async function canonicalTarget(cwd, target, projectRoot) {
3261
+ const resolved = path6.isAbsolute(target) ? path6.resolve(target) : path6.resolve(cwd, target);
3262
+ let real;
3263
+ try {
3264
+ real = await fs3.realpath(resolved);
3265
+ } catch (error) {
3266
+ if (error.code !== "ENOENT") throw error;
3267
+ const parent = await fs3.realpath(path6.dirname(resolved));
3268
+ real = path6.join(parent, path6.basename(resolved));
3269
+ }
3270
+ if (!isInside2(real, projectRoot)) throw new Error(`target is outside project root: ${target}`);
3271
+ return real;
3272
+ }
3273
+ function isInside2(candidate, root) {
3274
+ const relative5 = path6.relative(path6.resolve(root), path6.resolve(candidate));
3275
+ return relative5 === "" || !relative5.startsWith("..") && !path6.isAbsolute(relative5);
3276
+ }
3277
+
3278
+ // src/languages/execute.ts
3279
+ async function validatePlanRealpaths(plan, projectRoot) {
3280
+ const realRoot = await fs4.realpath(projectRoot);
3281
+ let realCwd;
3282
+ try {
3283
+ realCwd = await fs4.realpath(plan.cwd);
3284
+ } catch (error) {
3285
+ return `Plan cwd is unavailable: ${error instanceof Error ? error.message : String(error)}`;
3286
+ }
3287
+ if (!isRealInside(realCwd, realRoot)) return "Plan cwd resolves outside project root.";
3288
+ for (const argument of plan.args) {
3289
+ if (!path7.isAbsolute(argument)) continue;
3290
+ try {
3291
+ const realArgument = await fs4.realpath(argument);
3292
+ if (!isRealInside(realArgument, realRoot)) {
3293
+ return `Plan argument resolves outside project root: ${argument}`;
3294
+ }
3295
+ } catch (error) {
3296
+ if (error.code !== "ENOENT") {
3297
+ return `Plan argument could not be resolved safely: ${argument}`;
3298
+ }
3299
+ }
3300
+ }
3301
+ return void 0;
3302
+ }
3303
+ function isRealInside(candidate, root) {
3304
+ const relative5 = path7.relative(root, candidate);
3305
+ return relative5 === "" || !relative5.startsWith("..") && !path7.isAbsolute(relative5);
3306
+ }
3307
+ async function* executePackagePlan(options) {
3308
+ const { plan, workspace } = options;
3309
+ const startedAt = Date.now();
3310
+ if (options.signal.aborted) {
3311
+ yield { type: "log", text: "Run cancelled before execution." };
3312
+ return terminalPackageResult(options, "cancelled", startedAt);
3313
+ }
3314
+ const profile = languageProfileRegistry.get(plan.profileId);
3315
+ if (!profile) {
3316
+ yield { type: "warning", text: `Unknown language profile: ${plan.profileId}` };
3317
+ return terminalPackageResult(options, "unavailable", startedAt, "Unknown language profile.");
3318
+ }
3319
+ if (workspace.id !== plan.workspaceId || workspace.language !== plan.profileId) {
3320
+ return terminalPackageResult(
3321
+ options,
3322
+ "unavailable",
3323
+ startedAt,
3324
+ "Plan and workspace identity do not match."
3325
+ );
3326
+ }
3327
+ const validation = validateCommandPlan(plan, profile, options.projectRoot);
3328
+ if (validation.length > 0) {
3329
+ return terminalPackageResult(
3330
+ options,
3331
+ "unavailable",
3332
+ startedAt,
3333
+ `Plan failed execution validation: ${validation.join("; ")}`
3334
+ );
3335
+ }
3336
+ const containmentError = await validatePlanRealpaths(plan, options.projectRoot);
3337
+ if (containmentError) {
3338
+ return terminalPackageResult(options, "unavailable", startedAt, containmentError);
3339
+ }
3340
+ const manifestsBefore = await snapshotPaths(workspace.manifests);
3341
+ const lockfilePaths = collectLockfilePaths(workspace);
3342
+ const lockfilesBefore = await snapshotPaths(lockfilePaths);
3343
+ const manifestSizesBefore = await snapshotSizes(workspace.manifests);
3344
+ const lockfileSizesBefore = await snapshotSizes(lockfilePaths);
3345
+ yield {
3346
+ type: "log",
3347
+ text: plan.kind === "process" ? `${plan.command} ${plan.args.join(" ")}` : `${plan.parser}: ${plan.operation}`,
3348
+ data: {
3349
+ language: plan.profileId,
3350
+ operation: plan.operation,
3351
+ workspace: workspace.root,
3352
+ packages: [...options.packages]
3353
+ }
3354
+ };
3355
+ const timeoutController = new AbortController();
3356
+ const timer = setTimeout(
3357
+ () => timeoutController.abort(new Error("language package plan timed out")),
3358
+ plan.timeoutMs
3359
+ );
3360
+ timer.unref?.();
3361
+ const signal = AbortSignal.any([options.signal, timeoutController.signal]);
3362
+ let spawned;
3363
+ let run;
3364
+ let status = "unavailable";
3365
+ let error;
3366
+ try {
3367
+ if (plan.kind !== "process") {
3368
+ return terminalPackageResult(
3369
+ options,
3370
+ "unavailable",
3371
+ startedAt,
3372
+ "Package operations require an executable plan; internal plans cannot mutate the manifest."
3373
+ );
3374
+ }
3375
+ const stream = spawnStream({
3376
+ cmd: plan.command,
3377
+ args: [...plan.args],
3378
+ cwd: plan.cwd,
3379
+ signal,
3380
+ maxBytes: plan.outputLimitBytes
3381
+ });
3382
+ for (; ; ) {
3383
+ const next = await stream.next();
3384
+ if (next.done) {
3385
+ spawned = next.value;
3386
+ break;
3387
+ }
3388
+ yield next.value;
3389
+ }
3390
+ } catch (error_) {
3391
+ error = error_ instanceof Error ? error_.message : String(error_);
3392
+ } finally {
3393
+ clearTimeout(timer);
3394
+ }
3395
+ if (spawned) {
3396
+ const parsed = parseLanguageDiagnostics(
3397
+ plan.parser,
3398
+ spawned.stdout,
3399
+ spawned.stderr,
3400
+ workspace.root
3401
+ );
3402
+ const timedOut = timeoutController.signal.aborted && !options.signal.aborted;
3403
+ const cancelled = options.signal.aborted;
3404
+ const spawnUnavailable = Boolean(
3405
+ spawned.error && /ENOENT|not found|cannot find/i.test(spawned.error)
3406
+ );
3407
+ status = timedOut ? "timed_out" : cancelled ? "cancelled" : spawnUnavailable ? "unavailable" : spawned.exitCode === 0 ? "passed" : "failed";
3408
+ error ??= spawned.error;
3409
+ const raw = [spawned.stdout, spawned.stderr, spawned.error].filter(Boolean).join("\n");
3410
+ run = {
3411
+ status,
3412
+ language: plan.profileId,
3413
+ workspace,
3414
+ plan,
3415
+ exitCode: spawned.exitCode,
3416
+ durationMs: Date.now() - startedAt,
3417
+ diagnostics: parsed.diagnostics,
3418
+ omittedDiagnostics: parsed.omitted,
3419
+ summary: parsed.summary,
3420
+ output: normalizeCommandOutput(raw, { maxBytes: plan.outputLimitBytes }),
3421
+ truncated: spawned.truncated,
3422
+ ...spawned.spoolPath ? { spoolPath: spawned.spoolPath } : {},
3423
+ ...spawned.error ? { error: spawned.error } : {}
3424
+ };
3425
+ } else {
3426
+ status = options.signal.aborted ? "cancelled" : timeoutController.signal.aborted ? "timed_out" : "failed";
3427
+ }
3428
+ if (status !== "passed") {
3429
+ return terminalPackageResult(
3430
+ options,
3431
+ status,
3432
+ startedAt,
3433
+ error,
3434
+ run,
3435
+ manifestsBefore,
3436
+ lockfilesBefore
3437
+ );
3438
+ }
3439
+ const manifestsAfter = await snapshotPaths(workspace.manifests);
3440
+ const lockfilesAfter = await snapshotPaths(lockfilePaths);
3441
+ const manifestSizesAfter = await snapshotSizes(workspace.manifests);
3442
+ const lockfileSizesAfter = await snapshotSizes(lockfilePaths);
3443
+ const manifestsChanged = await changedPaths(
3444
+ manifestsBefore,
3445
+ manifestsAfter,
3446
+ manifestSizesBefore,
3447
+ manifestSizesAfter
3448
+ );
3449
+ const lockfilesChanged = await changedPaths(
3450
+ lockfilesBefore,
3451
+ lockfilesAfter,
3452
+ lockfileSizesBefore,
3453
+ lockfileSizesAfter
3454
+ );
3455
+ const reports = parsePackageReports(plan.parser, spawned?.stdout ?? "", spawned?.stderr ?? "");
3456
+ const mutations = packageMutationsFromInputs(options.packages, reports.outdated);
3457
+ return {
3458
+ workspace,
3459
+ language: plan.profileId,
3460
+ operation: plan.operation,
3461
+ status,
3462
+ ...run ? { run } : {},
3463
+ durationMs: Date.now() - startedAt,
3464
+ manifestsBefore,
3465
+ lockfilesBefore,
3466
+ manifestsAfter,
3467
+ lockfilesAfter,
3468
+ mutations,
3469
+ vulnerabilities: reports.vulnerabilities,
3470
+ outdated: reports.outdated,
3471
+ manifestsChanged: Object.freeze(manifestsChanged),
3472
+ lockfilesChanged: Object.freeze(lockfilesChanged)
3473
+ };
3474
+ }
3475
+ function packageMutationsFromInputs(inputs, outdated) {
3476
+ const outdatedNames = new Set(outdated.map((entry) => entry.name));
3477
+ return inputs.filter((name) => !outdatedNames.has(name)).map((name) => ({ name, requested: name, kind: "runtime" }));
3478
+ }
3479
+ async function snapshotPaths(paths) {
3480
+ const existing = [];
3481
+ for (const candidate of paths) {
3482
+ try {
3483
+ const stat5 = await fs4.stat(candidate);
3484
+ if (!stat5.isFile()) continue;
3485
+ existing.push(candidate);
3486
+ } catch {
3487
+ }
3488
+ }
3489
+ return Object.freeze(existing);
3490
+ }
3491
+ async function changedPaths(before, after, beforeSizes, afterSizes) {
3492
+ const beforeSet = new Set(before);
3493
+ const afterSet = new Set(after);
3494
+ const changed = /* @__PURE__ */ new Set();
3495
+ for (const path9 of after) {
3496
+ if (!beforeSet.has(path9)) changed.add(path9);
3497
+ }
3498
+ for (const path9 of before) {
3499
+ if (!afterSet.has(path9)) changed.add(path9);
3500
+ }
3501
+ if (beforeSizes && afterSizes) {
3502
+ for (const path9 of after) {
3503
+ if (beforeSizes.get(path9) !== afterSizes.get(path9)) changed.add(path9);
3504
+ }
3505
+ }
3506
+ return [...changed].sort();
3507
+ }
3508
+ async function snapshotSizes(paths) {
3509
+ const sizes = /* @__PURE__ */ new Map();
3510
+ for (const candidate of paths) {
3511
+ try {
3512
+ const stat5 = await fs4.stat(candidate);
3513
+ if (stat5.isFile()) sizes.set(candidate, stat5.size);
3514
+ } catch {
3515
+ }
3516
+ }
3517
+ return sizes;
3518
+ }
3519
+ function collectLockfilePaths(workspace) {
3520
+ const explicit = workspace.evidence.filter((evidence) => evidence.kind === "lockfile").map((evidence) => evidence.path);
3521
+ const detected = LOCKFILE_NAMES_BY_PROFILE.get(workspace.language)?.map(
3522
+ (name) => path7.join(workspace.root, name)
3523
+ ) ?? [];
3524
+ const merged = /* @__PURE__ */ new Set();
3525
+ for (const candidate of [...explicit, ...detected]) merged.add(candidate);
3526
+ return Object.freeze([...merged]);
3527
+ }
3528
+ var LOCKFILE_NAMES_BY_PROFILE = /* @__PURE__ */ new Map([
3529
+ ["typescript", ["package-lock.json", "pnpm-lock.yaml", "yarn.lock", "bun.lock", "bun.lockb"]],
3530
+ ["javascript", ["package-lock.json", "pnpm-lock.yaml", "yarn.lock", "bun.lock", "bun.lockb"]],
3531
+ ["go", ["go.sum"]],
3532
+ ["rust", ["Cargo.lock"]],
3533
+ ["php", ["composer.lock"]],
3534
+ ["csharp", ["packages.lock.json"]]
3535
+ ]);
3536
+ function terminalPackageResult(options, status, startedAt, error, run, manifestsBefore = [], lockfilesBefore = []) {
3537
+ return {
3538
+ workspace: options.workspace,
3539
+ language: options.plan.profileId,
3540
+ operation: options.plan.operation,
3541
+ status,
3542
+ ...run ? { run } : {},
3543
+ durationMs: Date.now() - startedAt,
3544
+ manifestsBefore,
3545
+ lockfilesBefore,
3546
+ manifestsAfter: manifestsBefore,
3547
+ lockfilesAfter: lockfilesBefore,
3548
+ manifestsChanged: Object.freeze([]),
3549
+ lockfilesChanged: Object.freeze([]),
3550
+ mutations: Object.freeze([]),
3551
+ vulnerabilities: Object.freeze([]),
3552
+ outdated: Object.freeze([]),
3553
+ ...error ? { error } : {}
3554
+ };
3555
+ }
3556
+
3557
+ // src/languages/legacy-bridge.ts
3558
+ var NON_JS_MARKERS = [
3559
+ { filename: "go.mod", language: "go" },
3560
+ { filename: "go.work", language: "go" },
3561
+ { filename: "Cargo.toml", language: "rust" },
3562
+ { filename: "composer.json", language: "php" }
3563
+ ];
3564
+ var NON_JS_SUFFIXES = [
3565
+ { suffix: ".csproj", language: "csharp" },
3566
+ { suffix: ".fsproj", language: "csharp" }
3567
+ ];
3568
+ async function detectNonJsEcosystem(cwd, projectRoot) {
3569
+ try {
3570
+ let dir = path8.resolve(cwd);
3571
+ const root = path8.resolve(projectRoot);
3572
+ for (let depth = 0; depth <= 4 && dir.startsWith(root); depth++) {
3573
+ for (const marker of NON_JS_MARKERS) {
3574
+ try {
3575
+ const s = await fs5.stat(path8.join(dir, marker.filename));
3576
+ if (s.isFile()) return marker.language;
3577
+ } catch {
3578
+ }
3579
+ }
3580
+ try {
3581
+ const entries = await fs5.readdir(dir);
3582
+ for (const entry of entries) {
3583
+ for (const suffix of NON_JS_SUFFIXES) {
3584
+ if (entry.toLowerCase().endsWith(suffix.suffix)) return suffix.language;
3585
+ }
3586
+ }
3587
+ } catch {
3588
+ }
3589
+ if (dir === root) break;
3590
+ dir = path8.dirname(dir);
3591
+ }
3592
+ } catch {
3593
+ }
3594
+ return null;
3595
+ }
3596
+ async function tryLegacyPackageOperation(operation, ctx, packages = []) {
3597
+ const language = await detectNonJsEcosystem(ctx.cwd, ctx.projectRoot);
3598
+ if (!language) return null;
3599
+ const planResult = await planLanguageOperation({
3600
+ projectRoot: ctx.projectRoot,
3601
+ cwd: ctx.cwd,
3602
+ operation,
3603
+ language,
3604
+ signal: ctx.signal,
3605
+ ...packages.length > 0 ? { operationOptions: { packages: [...packages] } } : {}
3606
+ });
3607
+ if (planResult.status !== "planned") return null;
3608
+ const runner = executePackagePlan({
3609
+ projectRoot: ctx.projectRoot,
3610
+ workspace: planResult.workspace,
3611
+ plan: planResult.plan,
3612
+ packages,
3613
+ signal: ctx.signal
3614
+ });
3615
+ for (; ; ) {
3616
+ const next = await runner.next();
3617
+ if (next.done) return { language, outcome: next.value };
3618
+ }
3619
+ }
933
3620
 
934
3621
  // src/audit.ts
935
3622
  var auditTool = {
@@ -967,6 +3654,34 @@ var auditTool = {
967
3654
  },
968
3655
  async *executeStream(input, ctx, opts) {
969
3656
  const cwd = input.cwd ? safeResolve(input.cwd, ctx) : ctx.cwd;
3657
+ const bridge = await tryLegacyPackageOperation("package-audit", {
3658
+ cwd,
3659
+ projectRoot: ctx.projectRoot,
3660
+ signal: opts.signal
3661
+ });
3662
+ if (bridge?.outcome) {
3663
+ const outcome = bridge.outcome;
3664
+ const vulns = outcome.vulnerabilities.map((v) => ({
3665
+ severity: v.severity,
3666
+ package: v.package,
3667
+ title: v.advisory ?? "Unknown vulnerability",
3668
+ url: v.url ?? ""
3669
+ }));
3670
+ const total = vulns.length;
3671
+ 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`;
3672
+ yield {
3673
+ type: "final",
3674
+ output: {
3675
+ exit_code: outcome.run?.exitCode ?? 0,
3676
+ vulnerabilities: vulns,
3677
+ total,
3678
+ summary,
3679
+ output: outcome.run?.output ?? "",
3680
+ truncated: outcome.run?.truncated ?? false
3681
+ }
3682
+ };
3683
+ return;
3684
+ }
970
3685
  const manager = await detectPackageManager(cwd);
971
3686
  yield { type: "log", text: `Auditing with ${manager}\u2026`, data: { manager } };
972
3687
  const args = ["audit", "--json"];
@@ -1030,7 +3745,7 @@ function parseAuditOutput(json, exitCode) {
1030
3745
  };
1031
3746
  }
1032
3747
  }
1033
-
1034
- export { auditTool };
3748
+ export {
3749
+ auditTool
3750
+ };
1035
3751
  //# sourceMappingURL=audit.js.map
1036
- //# sourceMappingURL=audit.js.map