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