@wrongstack/tools 0.310.1 → 0.313.1

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