@muggleai/works 5.24.0-staging.171 → 5.24.0-staging.172

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.
@@ -9,7 +9,7 @@
9
9
  "name": "muggleai",
10
10
  "source": "./plugin",
11
11
  "description": "Real-browser E2E acceptance for your coding agent: test the flows you changed and open the PR with screenshots. Built for flows other tools can't reach: managed test identities with live inboxes (magic links, email OTP and 2FA, verification mail, password resets), an encrypted secret store for login and test credentials, and a test graph that runs prerequisite flows first. Plain-English tests become replayable scripts on localhost or preview URLs.",
12
- "version": "5.24.0-staging.171"
12
+ "version": "5.24.0-staging.172"
13
13
  }
14
14
  ]
15
15
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "muggle",
3
3
  "description": "Real-browser E2E acceptance for your coding agent: test the flows you changed and open the PR with screenshots. Built for flows other tools can't reach: managed test identities with live inboxes (magic links, email OTP and 2FA, verification mail, password resets), an encrypted secret store for login and test credentials, and a test graph that runs prerequisite flows first. Plain-English tests become replayable scripts on localhost or preview URLs.",
4
- "version": "5.24.0-staging.171",
4
+ "version": "5.24.0-staging.172",
5
5
  "author": {
6
6
  "name": "Muggle AI",
7
7
  "email": "support@muggle-ai.com"
@@ -4,7 +4,7 @@
4
4
  "command": "npx",
5
5
  "args": [
6
6
  "-y",
7
- "@muggleai/works@5.24.0-staging.171",
7
+ "@muggleai/works@5.24.0-staging.172",
8
8
  "serve"
9
9
  ],
10
10
  "env": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "muggle",
3
- "version": "5.24.0-staging.171",
3
+ "version": "5.24.0-staging.172",
4
4
  "description": "Real-browser E2E acceptance for your coding agent: test the flows you changed and open the PR with screenshots. Built for flows other tools can't reach: managed test identities with live inboxes (magic links, email OTP and 2FA, verification mail, password resets), an encrypted secret store for login and test credentials, and a test graph that runs prerequisite flows first. Plain-English tests become replayable scripts on localhost or preview URLs.",
5
5
  "author": {
6
6
  "name": "Muggle AI",
@@ -2,7 +2,7 @@
2
2
  "name": "muggle",
3
3
  "displayName": "Muggle AI",
4
4
  "description": "Real-browser E2E acceptance for your coding agent: test the flows you changed and open the PR with screenshots. Built for flows other tools can't reach: managed test identities with live inboxes (magic links, email OTP and 2FA, verification mail, password resets), an encrypted secret store for login and test credentials, and a test graph that runs prerequisite flows first. Plain-English tests become replayable scripts on localhost or preview URLs.",
5
- "version": "5.24.0-staging.171",
5
+ "version": "5.24.0-staging.172",
6
6
  "author": {
7
7
  "name": "Muggle AI",
8
8
  "email": "support@muggle-ai.com"
@@ -4,7 +4,7 @@
4
4
  "command": "npx",
5
5
  "args": [
6
6
  "-y",
7
- "@muggleai/works@5.24.0-staging.171",
7
+ "@muggleai/works@5.24.0-staging.172",
8
8
  "serve"
9
9
  ]
10
10
  }
@@ -52,6 +52,7 @@ Add-Type -TypeDefinition @'
52
52
  using System;
53
53
  using System.Runtime.InteropServices;
54
54
  using System.Text;
55
+ using System.Threading;
55
56
 
56
57
  namespace MuggleGuardRun
57
58
  {
@@ -91,6 +92,13 @@ namespace MuggleGuardRun
91
92
  public UIntPtr PeakJobMemoryUsed;
92
93
  }
93
94
 
95
+ [StructLayout(LayoutKind.Sequential)]
96
+ public struct JOBOBJECT_ASSOCIATE_COMPLETION_PORT
97
+ {
98
+ public IntPtr CompletionKey;
99
+ public IntPtr CompletionPort;
100
+ }
101
+
94
102
  [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
95
103
  public struct STARTUPINFO
96
104
  {
@@ -128,6 +136,9 @@ namespace MuggleGuardRun
128
136
  const uint JOB_OBJECT_LIMIT_ACTIVE_PROCESS = 0x00000008;
129
137
  const uint JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000;
130
138
  const int JobObjectExtendedLimitInformation = 9;
139
+ const int JobObjectAssociateCompletionPortInformation = 7;
140
+ const uint JOB_OBJECT_MSG_ACTIVE_PROCESS_LIMIT = 3;
141
+ const int LIMIT_WATCHER_DRAIN_TIMEOUT_MS = 2000;
131
142
  const uint CREATE_SUSPENDED = 0x00000004;
132
143
  const uint SYNCHRONIZE = 0x00100000;
133
144
  const uint INFINITE = 0xFFFFFFFF;
@@ -141,6 +152,22 @@ namespace MuggleGuardRun
141
152
  static extern bool SetInformationJobObject(IntPtr hJob, int jobObjectInfoClass,
142
153
  ref JOBOBJECT_EXTENDED_LIMIT_INFORMATION lpJobObjectInfo, uint cbJobObjectInfoLength);
143
154
 
155
+ [DllImport("kernel32.dll", SetLastError = true)]
156
+ static extern bool SetInformationJobObject(IntPtr hJob, int jobObjectInfoClass,
157
+ ref JOBOBJECT_ASSOCIATE_COMPLETION_PORT lpJobObjectInfo, uint cbJobObjectInfoLength);
158
+
159
+ [DllImport("kernel32.dll", SetLastError = true)]
160
+ static extern IntPtr CreateIoCompletionPort(IntPtr fileHandle, IntPtr existingCompletionPort,
161
+ UIntPtr completionKey, uint numberOfConcurrentThreads);
162
+
163
+ [DllImport("kernel32.dll", SetLastError = true)]
164
+ static extern bool GetQueuedCompletionStatus(IntPtr completionPort, out uint numberOfBytes,
165
+ out UIntPtr completionKey, out IntPtr overlapped, uint milliseconds);
166
+
167
+ [DllImport("kernel32.dll", SetLastError = true)]
168
+ static extern bool PostQueuedCompletionStatus(IntPtr completionPort, uint numberOfBytes,
169
+ UIntPtr completionKey, IntPtr overlapped);
170
+
144
171
  [DllImport("kernel32.dll", SetLastError = true)]
145
172
  static extern bool AssignProcessToJobObject(IntPtr hJob, IntPtr hProcess);
146
173
 
@@ -178,6 +205,49 @@ namespace MuggleGuardRun
178
205
  Marshal.GetLastWin32Error() + ")");
179
206
  }
180
207
 
208
+ // A creation the job refuses reaches the caller only as a bare Win32
209
+ // failure (libuv: "spawn UNKNOWN"), which never names the cap. The job's
210
+ // completion port does, so a background thread drains it and says so —
211
+ // draining continuously also keeps a long --service run's per-process
212
+ // messages from piling up in the port.
213
+ static Thread StartLimitWatcher(IntPtr port, int activeProcessLimit)
214
+ {
215
+ Thread watcher = new Thread(() =>
216
+ {
217
+ bool hasReported = false;
218
+ while (true)
219
+ {
220
+ uint message;
221
+ UIntPtr completionKey;
222
+ IntPtr overlapped;
223
+ if (!GetQueuedCompletionStatus(port, out message, out completionKey,
224
+ out overlapped, INFINITE))
225
+ {
226
+ return;
227
+ }
228
+ if (completionKey == UIntPtr.Zero) return;
229
+ if (message == JOB_OBJECT_MSG_ACTIVE_PROCESS_LIMIT && !hasReported)
230
+ {
231
+ hasReported = true;
232
+ Console.Error.WriteLine("guard-run: the process tree reached its active-process " +
233
+ "limit of " + activeProcessLimit + "; the kernel refused process creation past it, " +
234
+ "which the refused caller reports as \"spawn UNKNOWN\". Raise it with --limit.");
235
+ }
236
+ }
237
+ });
238
+ watcher.IsBackground = true;
239
+ watcher.Start();
240
+ return watcher;
241
+ }
242
+
243
+ // The stop marker queues behind every job message already posted, so the
244
+ // watcher reports a refusal that happened just before the tree exited.
245
+ static void StopLimitWatcher(IntPtr port, Thread watcher)
246
+ {
247
+ PostQueuedCompletionStatus(port, 0, UIntPtr.Zero, IntPtr.Zero);
248
+ watcher.Join(LIMIT_WATCHER_DRAIN_TIMEOUT_MS);
249
+ }
250
+
181
251
  public static int Run(string commandLine, int activeProcessLimit, bool killOnClose,
182
252
  int launcherPid)
183
253
  {
@@ -196,6 +266,18 @@ namespace MuggleGuardRun
196
266
  throw LastError("SetInformationJobObject");
197
267
  }
198
268
 
269
+ IntPtr port = CreateIoCompletionPort(new IntPtr(-1), IntPtr.Zero, UIntPtr.Zero, 1);
270
+ if (port == IntPtr.Zero) throw LastError("CreateIoCompletionPort");
271
+ JOBOBJECT_ASSOCIATE_COMPLETION_PORT association = new JOBOBJECT_ASSOCIATE_COMPLETION_PORT();
272
+ association.CompletionKey = job;
273
+ association.CompletionPort = port;
274
+ if (!SetInformationJobObject(job, JobObjectAssociateCompletionPortInformation,
275
+ ref association, (uint)Marshal.SizeOf(typeof(JOBOBJECT_ASSOCIATE_COMPLETION_PORT))))
276
+ {
277
+ throw LastError("SetInformationJobObject (completion port)");
278
+ }
279
+ Thread limitWatcher = StartLimitWatcher(port, activeProcessLimit);
280
+
199
281
  STARTUPINFO startupInfo = new STARTUPINFO();
200
282
  startupInfo.cb = (uint)Marshal.SizeOf(typeof(STARTUPINFO));
201
283
  PROCESS_INFORMATION processInfo;
@@ -233,6 +315,7 @@ namespace MuggleGuardRun
233
315
  {
234
316
  WaitForSingleObject(processInfo.hProcess, INFINITE);
235
317
  }
318
+ StopLimitWatcher(port, limitWatcher);
236
319
 
237
320
  uint exitCode;
238
321
  if (!GetExitCodeProcess(processInfo.hProcess, out exitCode))
@@ -1,5 +1,6 @@
1
1
  import { spawn, spawnSync } from 'child_process';
2
2
  import { existsSync } from 'fs';
3
+ import { availableParallelism } from 'os';
3
4
  import { extname, join, dirname } from 'path';
4
5
  import { fileURLToPath } from 'url';
5
6
 
@@ -119,7 +120,20 @@ function buildBackendLaunchPlan(args) {
119
120
  });
120
121
  }
121
122
 
123
+ // src/guard-run/constants.ts
124
+ var GUARD_RUN_MIN_DEFAULT_ACTIVE_PROCESS_LIMIT = 64;
125
+ var GUARD_RUN_PROCESSES_PER_CPU = 8;
126
+ var WINDOWS_SHELL_SCRIPT_EXTENSIONS = [".cmd", ".bat"];
127
+ var GUARD_RUN_USAGE = `usage: guard-run [--limit N] [--service] -- <command...>
128
+ Runs <command> with its whole process tree kernel-capped at N processes
129
+ (default ${GUARD_RUN_PROCESSES_PER_CPU} per logical CPU, at least ${GUARD_RUN_MIN_DEFAULT_ACTIVE_PROCESS_LIMIT}). Default mode also ties the tree
130
+ to the launcher: killing guard-run reaps every descendant. --service keeps
131
+ the cap but lets the tree outlive the launcher (for dev servers).`;
132
+
122
133
  // src/guard-run/headroom.ts
134
+ function computeDefaultActiveProcessLimit(logicalCpuCount) {
135
+ return Math.max(GUARD_RUN_MIN_DEFAULT_ACTIVE_PROCESS_LIMIT, logicalCpuCount * GUARD_RUN_PROCESSES_PER_CPU);
136
+ }
123
137
  function countProcessListLines(psOutput) {
124
138
  return psOutput.split("\n").filter((line) => line.trim() !== "").length;
125
139
  }
@@ -127,10 +141,6 @@ function computeNprocCeiling(args) {
127
141
  return args.currentUserProcessCount + args.activeProcessLimit;
128
142
  }
129
143
 
130
- // src/guard-run/constants.ts
131
- var GUARD_RUN_DEFAULT_ACTIVE_PROCESS_LIMIT = 64;
132
- var GUARD_RUN_USAGE = "usage: guard-run [--limit N] [--service] -- <command...>\n Runs <command> with its whole process tree kernel-capped at N processes\n (default 64). Default mode also ties the tree to the launcher: killing\n guard-run reaps every descendant. --service keeps the cap but lets the\n tree outlive the launcher (for dev servers).";
133
-
134
144
  // src/guard-run/parseArguments.ts
135
145
  function parseError(errorMessage) {
136
146
  return { options: null, errorMessage: `${errorMessage}
@@ -141,8 +151,8 @@ function parsePositiveInteger(rawValue) {
141
151
  const parsed = Number(rawValue);
142
152
  return parsed >= 1 ? parsed : null;
143
153
  }
144
- function parseGuardRunArguments(argv) {
145
- let activeProcessLimit = GUARD_RUN_DEFAULT_ACTIVE_PROCESS_LIMIT;
154
+ function parseGuardRunArguments(argv, defaultActiveProcessLimit) {
155
+ let activeProcessLimit = defaultActiveProcessLimit;
146
156
  let isServiceMode = false;
147
157
  let index = 0;
148
158
  while (index < argv.length) {
@@ -183,6 +193,14 @@ function parseGuardRunArguments(argv) {
183
193
  function probeRan(probe) {
184
194
  return probe.status !== null && typeof probe.stdout === "string";
185
195
  }
196
+ function isShellScript(path) {
197
+ return WINDOWS_SHELL_SCRIPT_EXTENSIONS.includes(extname(path).toLowerCase());
198
+ }
199
+ function windowsCommandNeedsCmdShell(args) {
200
+ if (extname(args.firstCommandToken) !== "") return isShellScript(args.firstCommandToken);
201
+ const launchableCandidate = (args.whereOutput ?? "").split(/\r?\n/).map((candidate) => candidate.trim()).find((candidate) => extname(candidate) !== "");
202
+ return launchableCandidate !== void 0 && isShellScript(launchableCandidate);
203
+ }
186
204
 
187
205
  // src/guard-run/selectBackend.ts
188
206
  var SYSTEMD_USABLE_MANAGER_STATES = /* @__PURE__ */ new Set(["running", "degraded"]);
@@ -246,18 +264,14 @@ function resolveJobObjectShimPath() {
246
264
  if (existsSync(pluginTreePath)) return pluginTreePath;
247
265
  return fail(`cannot locate ${JOB_OBJECT_SHIM_FILENAME}; refusing to run the command unguarded`);
248
266
  }
249
- function windowsCommandNeedsCmdShell(firstCommandToken) {
250
- const knownExtension = extname(firstCommandToken).toLowerCase();
251
- if (knownExtension === ".cmd" || knownExtension === ".bat") return true;
252
- if (knownExtension !== "") return false;
267
+ function whereExeOutput(firstCommandToken) {
268
+ if (extname(firstCommandToken) !== "") return null;
253
269
  const lookup = spawnSync("where.exe", [firstCommandToken], {
254
270
  encoding: "utf-8",
255
271
  timeout: 1e4,
256
272
  windowsHide: true
257
273
  });
258
- if (lookup.error !== void 0 || lookup.status !== 0) return false;
259
- const resolvedExtension = extname(lookup.stdout.split(/\r?\n/)[0] ?? "").toLowerCase();
260
- return resolvedExtension === ".cmd" || resolvedExtension === ".bat";
274
+ return lookup.error === void 0 && lookup.status === 0 ? lookup.stdout : null;
261
275
  }
262
276
  function currentUserProcessCount() {
263
277
  const uid = typeof process.getuid === "function" ? String(process.getuid()) : "";
@@ -299,7 +313,10 @@ function registerTreeCleanup(plan2, childPid) {
299
313
  });
300
314
  }
301
315
  }
302
- var parseResult = parseGuardRunArguments(process.argv.slice(2));
316
+ var parseResult = parseGuardRunArguments(
317
+ process.argv.slice(2),
318
+ computeDefaultActiveProcessLimit(availableParallelism())
319
+ );
303
320
  if (parseResult.options === null) fail(parseResult.errorMessage ?? "invalid arguments");
304
321
  var options = parseResult.options;
305
322
  var isLinux = process.platform === "linux";
@@ -317,7 +334,10 @@ var plan = buildBackendLaunchPlan({
317
334
  options,
318
335
  jobObjectShimPath: backend === "windows-job-object" /* WindowsJobObject */ ? resolveJobObjectShimPath() : void 0,
319
336
  launcherPid: process.pid,
320
- commandNeedsCmdShell: backend === "windows-job-object" /* WindowsJobObject */ ? windowsCommandNeedsCmdShell(options.command[0]) : false,
337
+ commandNeedsCmdShell: backend === "windows-job-object" /* WindowsJobObject */ ? windowsCommandNeedsCmdShell({
338
+ firstCommandToken: options.command[0],
339
+ whereOutput: whereExeOutput(options.command[0])
340
+ }) : false,
321
341
  scopeUnitName: `muggle-guard-${process.pid}-${Date.now()}.scope`,
322
342
  nprocCeiling: needsNprocCeiling ? computeNprocCeiling({
323
343
  currentUserProcessCount: currentUserProcessCount(),
@@ -47,7 +47,7 @@ Forward pipeline's Stage 7. Invoked by `/muggle-do` after stages 1–6 of a fres
47
47
 
48
48
  6. **Settle the designated walkthrough comment.** Creating the PR reserves one comment for the walkthrough, marked `muggle-pr-walkthrough` and empty until settled — the PR's walkthrough check fails while it stays that way.
49
49
  - E2E report exists → fire [`postPRVisualWalkthrough`](../../muggle-preferences/preference-gates/postPRVisualWalkthrough.md); on skip, leave the comment to the gate's own skip record. Otherwise invoke [`../../muggle-pr-visual-walkthrough/SKILL.md`](../../muggle-pr-visual-walkthrough/SKILL.md) Mode A with the PR number — it fills the reserved comment in place.
50
- - No E2E report (validation was `unit-only` or `skip`) → state the reason on the PR with `echo "MUGGLE_E2E_SKIP: <reason>"`, which settles the comment as a declared skip. A PR whose title says `[UNIT-ONLY]` still owes reviewers the why.
50
+ - No E2E report (validation was `unit-only` or `skip`) → now that the PR exists, re-declare the skip Stage 6 recorded with the same code: `echo "MUGGLE_E2E_SKIP: <CODE>: <detail>"`, codes per [`../e2e-acceptance.md`](../e2e-acceptance.md). An accepted code settles the comment as a declared skip; a free-text reason is rejected and leaves it unsettled. A PR whose title says `[UNIT-ONLY]` still owes reviewers the why.
51
51
 
52
52
  7. **Overflow comment:** if the walkthrough skill returned a non-null `comment`, post it once using the provider resolved in Step 5 — `github` per [`../../_shared/vcs/github/top-level-comment.md`](../../_shared/vcs/github/top-level-comment.md), `gitlab` per [`../../_shared/vcs/gitlab/mr-note.md`](../../_shared/vcs/gitlab/mr-note.md). End the posted body with the signature line (command `/muggle-do`) per [`../../_shared/vcs/post-signature.md`](../../_shared/vcs/post-signature.md). Never post when `comment` is `null`.
53
53
 
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "release": "5.18.0",
3
- "buildId": "run-171-1",
4
- "commitSha": "52b57b3af1c06397647ef53c65dff9ac29f206f9",
5
- "buildTime": "2026-10-22T23:10:26Z",
3
+ "buildId": "run-172-1",
4
+ "commitSha": "c36aaa0dd147d46f8d8bd2ae3cb16b6208e6d0a6",
5
+ "buildTime": "2026-10-22T23:48:10Z",
6
6
  "serviceName": "muggle-ai-works-mcp"
7
7
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@muggleai/works",
3
3
  "mcpName": "io.github.multiplex-ai/muggle",
4
- "version": "5.24.0-staging.171",
4
+ "version": "5.24.0-staging.172",
5
5
  "description": "13 years of Microsoft hyperscale engineering, packaged as a harness for your AI coding agent.",
6
6
  "type": "module",
7
7
  "main": "dist/index.js",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "muggle",
3
3
  "description": "Real-browser E2E acceptance for your coding agent: test the flows you changed and open the PR with screenshots. Built for flows other tools can't reach: managed test identities with live inboxes (magic links, email OTP and 2FA, verification mail, password resets), an encrypted secret store for login and test credentials, and a test graph that runs prerequisite flows first. Plain-English tests become replayable scripts on localhost or preview URLs.",
4
- "version": "5.24.0-staging.171",
4
+ "version": "5.24.0-staging.172",
5
5
  "author": {
6
6
  "name": "Muggle AI",
7
7
  "email": "support@muggle-ai.com"
@@ -4,7 +4,7 @@
4
4
  "command": "npx",
5
5
  "args": [
6
6
  "-y",
7
- "@muggleai/works@5.24.0-staging.171",
7
+ "@muggleai/works@5.24.0-staging.172",
8
8
  "serve"
9
9
  ],
10
10
  "env": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "muggle",
3
- "version": "5.24.0-staging.171",
3
+ "version": "5.24.0-staging.172",
4
4
  "description": "Real-browser E2E acceptance for your coding agent: test the flows you changed and open the PR with screenshots. Built for flows other tools can't reach: managed test identities with live inboxes (magic links, email OTP and 2FA, verification mail, password resets), an encrypted secret store for login and test credentials, and a test graph that runs prerequisite flows first. Plain-English tests become replayable scripts on localhost or preview URLs.",
5
5
  "author": {
6
6
  "name": "Muggle AI",
@@ -2,7 +2,7 @@
2
2
  "name": "muggle",
3
3
  "displayName": "Muggle AI",
4
4
  "description": "Real-browser E2E acceptance for your coding agent: test the flows you changed and open the PR with screenshots. Built for flows other tools can't reach: managed test identities with live inboxes (magic links, email OTP and 2FA, verification mail, password resets), an encrypted secret store for login and test credentials, and a test graph that runs prerequisite flows first. Plain-English tests become replayable scripts on localhost or preview URLs.",
5
- "version": "5.24.0-staging.171",
5
+ "version": "5.24.0-staging.172",
6
6
  "author": {
7
7
  "name": "Muggle AI",
8
8
  "email": "support@muggle-ai.com"
package/plugin/.mcp.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "command": "npx",
5
5
  "args": [
6
6
  "-y",
7
- "@muggleai/works@5.24.0-staging.171",
7
+ "@muggleai/works@5.24.0-staging.172",
8
8
  "serve"
9
9
  ]
10
10
  }
@@ -52,6 +52,7 @@ Add-Type -TypeDefinition @'
52
52
  using System;
53
53
  using System.Runtime.InteropServices;
54
54
  using System.Text;
55
+ using System.Threading;
55
56
 
56
57
  namespace MuggleGuardRun
57
58
  {
@@ -91,6 +92,13 @@ namespace MuggleGuardRun
91
92
  public UIntPtr PeakJobMemoryUsed;
92
93
  }
93
94
 
95
+ [StructLayout(LayoutKind.Sequential)]
96
+ public struct JOBOBJECT_ASSOCIATE_COMPLETION_PORT
97
+ {
98
+ public IntPtr CompletionKey;
99
+ public IntPtr CompletionPort;
100
+ }
101
+
94
102
  [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
95
103
  public struct STARTUPINFO
96
104
  {
@@ -128,6 +136,9 @@ namespace MuggleGuardRun
128
136
  const uint JOB_OBJECT_LIMIT_ACTIVE_PROCESS = 0x00000008;
129
137
  const uint JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000;
130
138
  const int JobObjectExtendedLimitInformation = 9;
139
+ const int JobObjectAssociateCompletionPortInformation = 7;
140
+ const uint JOB_OBJECT_MSG_ACTIVE_PROCESS_LIMIT = 3;
141
+ const int LIMIT_WATCHER_DRAIN_TIMEOUT_MS = 2000;
131
142
  const uint CREATE_SUSPENDED = 0x00000004;
132
143
  const uint SYNCHRONIZE = 0x00100000;
133
144
  const uint INFINITE = 0xFFFFFFFF;
@@ -141,6 +152,22 @@ namespace MuggleGuardRun
141
152
  static extern bool SetInformationJobObject(IntPtr hJob, int jobObjectInfoClass,
142
153
  ref JOBOBJECT_EXTENDED_LIMIT_INFORMATION lpJobObjectInfo, uint cbJobObjectInfoLength);
143
154
 
155
+ [DllImport("kernel32.dll", SetLastError = true)]
156
+ static extern bool SetInformationJobObject(IntPtr hJob, int jobObjectInfoClass,
157
+ ref JOBOBJECT_ASSOCIATE_COMPLETION_PORT lpJobObjectInfo, uint cbJobObjectInfoLength);
158
+
159
+ [DllImport("kernel32.dll", SetLastError = true)]
160
+ static extern IntPtr CreateIoCompletionPort(IntPtr fileHandle, IntPtr existingCompletionPort,
161
+ UIntPtr completionKey, uint numberOfConcurrentThreads);
162
+
163
+ [DllImport("kernel32.dll", SetLastError = true)]
164
+ static extern bool GetQueuedCompletionStatus(IntPtr completionPort, out uint numberOfBytes,
165
+ out UIntPtr completionKey, out IntPtr overlapped, uint milliseconds);
166
+
167
+ [DllImport("kernel32.dll", SetLastError = true)]
168
+ static extern bool PostQueuedCompletionStatus(IntPtr completionPort, uint numberOfBytes,
169
+ UIntPtr completionKey, IntPtr overlapped);
170
+
144
171
  [DllImport("kernel32.dll", SetLastError = true)]
145
172
  static extern bool AssignProcessToJobObject(IntPtr hJob, IntPtr hProcess);
146
173
 
@@ -178,6 +205,49 @@ namespace MuggleGuardRun
178
205
  Marshal.GetLastWin32Error() + ")");
179
206
  }
180
207
 
208
+ // A creation the job refuses reaches the caller only as a bare Win32
209
+ // failure (libuv: "spawn UNKNOWN"), which never names the cap. The job's
210
+ // completion port does, so a background thread drains it and says so —
211
+ // draining continuously also keeps a long --service run's per-process
212
+ // messages from piling up in the port.
213
+ static Thread StartLimitWatcher(IntPtr port, int activeProcessLimit)
214
+ {
215
+ Thread watcher = new Thread(() =>
216
+ {
217
+ bool hasReported = false;
218
+ while (true)
219
+ {
220
+ uint message;
221
+ UIntPtr completionKey;
222
+ IntPtr overlapped;
223
+ if (!GetQueuedCompletionStatus(port, out message, out completionKey,
224
+ out overlapped, INFINITE))
225
+ {
226
+ return;
227
+ }
228
+ if (completionKey == UIntPtr.Zero) return;
229
+ if (message == JOB_OBJECT_MSG_ACTIVE_PROCESS_LIMIT && !hasReported)
230
+ {
231
+ hasReported = true;
232
+ Console.Error.WriteLine("guard-run: the process tree reached its active-process " +
233
+ "limit of " + activeProcessLimit + "; the kernel refused process creation past it, " +
234
+ "which the refused caller reports as \"spawn UNKNOWN\". Raise it with --limit.");
235
+ }
236
+ }
237
+ });
238
+ watcher.IsBackground = true;
239
+ watcher.Start();
240
+ return watcher;
241
+ }
242
+
243
+ // The stop marker queues behind every job message already posted, so the
244
+ // watcher reports a refusal that happened just before the tree exited.
245
+ static void StopLimitWatcher(IntPtr port, Thread watcher)
246
+ {
247
+ PostQueuedCompletionStatus(port, 0, UIntPtr.Zero, IntPtr.Zero);
248
+ watcher.Join(LIMIT_WATCHER_DRAIN_TIMEOUT_MS);
249
+ }
250
+
181
251
  public static int Run(string commandLine, int activeProcessLimit, bool killOnClose,
182
252
  int launcherPid)
183
253
  {
@@ -196,6 +266,18 @@ namespace MuggleGuardRun
196
266
  throw LastError("SetInformationJobObject");
197
267
  }
198
268
 
269
+ IntPtr port = CreateIoCompletionPort(new IntPtr(-1), IntPtr.Zero, UIntPtr.Zero, 1);
270
+ if (port == IntPtr.Zero) throw LastError("CreateIoCompletionPort");
271
+ JOBOBJECT_ASSOCIATE_COMPLETION_PORT association = new JOBOBJECT_ASSOCIATE_COMPLETION_PORT();
272
+ association.CompletionKey = job;
273
+ association.CompletionPort = port;
274
+ if (!SetInformationJobObject(job, JobObjectAssociateCompletionPortInformation,
275
+ ref association, (uint)Marshal.SizeOf(typeof(JOBOBJECT_ASSOCIATE_COMPLETION_PORT))))
276
+ {
277
+ throw LastError("SetInformationJobObject (completion port)");
278
+ }
279
+ Thread limitWatcher = StartLimitWatcher(port, activeProcessLimit);
280
+
199
281
  STARTUPINFO startupInfo = new STARTUPINFO();
200
282
  startupInfo.cb = (uint)Marshal.SizeOf(typeof(STARTUPINFO));
201
283
  PROCESS_INFORMATION processInfo;
@@ -233,6 +315,7 @@ namespace MuggleGuardRun
233
315
  {
234
316
  WaitForSingleObject(processInfo.hProcess, INFINITE);
235
317
  }
318
+ StopLimitWatcher(port, limitWatcher);
236
319
 
237
320
  uint exitCode;
238
321
  if (!GetExitCodeProcess(processInfo.hProcess, out exitCode))
@@ -1,5 +1,6 @@
1
1
  import { spawn, spawnSync } from 'child_process';
2
2
  import { existsSync } from 'fs';
3
+ import { availableParallelism } from 'os';
3
4
  import { extname, join, dirname } from 'path';
4
5
  import { fileURLToPath } from 'url';
5
6
 
@@ -119,7 +120,20 @@ function buildBackendLaunchPlan(args) {
119
120
  });
120
121
  }
121
122
 
123
+ // src/guard-run/constants.ts
124
+ var GUARD_RUN_MIN_DEFAULT_ACTIVE_PROCESS_LIMIT = 64;
125
+ var GUARD_RUN_PROCESSES_PER_CPU = 8;
126
+ var WINDOWS_SHELL_SCRIPT_EXTENSIONS = [".cmd", ".bat"];
127
+ var GUARD_RUN_USAGE = `usage: guard-run [--limit N] [--service] -- <command...>
128
+ Runs <command> with its whole process tree kernel-capped at N processes
129
+ (default ${GUARD_RUN_PROCESSES_PER_CPU} per logical CPU, at least ${GUARD_RUN_MIN_DEFAULT_ACTIVE_PROCESS_LIMIT}). Default mode also ties the tree
130
+ to the launcher: killing guard-run reaps every descendant. --service keeps
131
+ the cap but lets the tree outlive the launcher (for dev servers).`;
132
+
122
133
  // src/guard-run/headroom.ts
134
+ function computeDefaultActiveProcessLimit(logicalCpuCount) {
135
+ return Math.max(GUARD_RUN_MIN_DEFAULT_ACTIVE_PROCESS_LIMIT, logicalCpuCount * GUARD_RUN_PROCESSES_PER_CPU);
136
+ }
123
137
  function countProcessListLines(psOutput) {
124
138
  return psOutput.split("\n").filter((line) => line.trim() !== "").length;
125
139
  }
@@ -127,10 +141,6 @@ function computeNprocCeiling(args) {
127
141
  return args.currentUserProcessCount + args.activeProcessLimit;
128
142
  }
129
143
 
130
- // src/guard-run/constants.ts
131
- var GUARD_RUN_DEFAULT_ACTIVE_PROCESS_LIMIT = 64;
132
- var GUARD_RUN_USAGE = "usage: guard-run [--limit N] [--service] -- <command...>\n Runs <command> with its whole process tree kernel-capped at N processes\n (default 64). Default mode also ties the tree to the launcher: killing\n guard-run reaps every descendant. --service keeps the cap but lets the\n tree outlive the launcher (for dev servers).";
133
-
134
144
  // src/guard-run/parseArguments.ts
135
145
  function parseError(errorMessage) {
136
146
  return { options: null, errorMessage: `${errorMessage}
@@ -141,8 +151,8 @@ function parsePositiveInteger(rawValue) {
141
151
  const parsed = Number(rawValue);
142
152
  return parsed >= 1 ? parsed : null;
143
153
  }
144
- function parseGuardRunArguments(argv) {
145
- let activeProcessLimit = GUARD_RUN_DEFAULT_ACTIVE_PROCESS_LIMIT;
154
+ function parseGuardRunArguments(argv, defaultActiveProcessLimit) {
155
+ let activeProcessLimit = defaultActiveProcessLimit;
146
156
  let isServiceMode = false;
147
157
  let index = 0;
148
158
  while (index < argv.length) {
@@ -183,6 +193,14 @@ function parseGuardRunArguments(argv) {
183
193
  function probeRan(probe) {
184
194
  return probe.status !== null && typeof probe.stdout === "string";
185
195
  }
196
+ function isShellScript(path) {
197
+ return WINDOWS_SHELL_SCRIPT_EXTENSIONS.includes(extname(path).toLowerCase());
198
+ }
199
+ function windowsCommandNeedsCmdShell(args) {
200
+ if (extname(args.firstCommandToken) !== "") return isShellScript(args.firstCommandToken);
201
+ const launchableCandidate = (args.whereOutput ?? "").split(/\r?\n/).map((candidate) => candidate.trim()).find((candidate) => extname(candidate) !== "");
202
+ return launchableCandidate !== void 0 && isShellScript(launchableCandidate);
203
+ }
186
204
 
187
205
  // src/guard-run/selectBackend.ts
188
206
  var SYSTEMD_USABLE_MANAGER_STATES = /* @__PURE__ */ new Set(["running", "degraded"]);
@@ -246,18 +264,14 @@ function resolveJobObjectShimPath() {
246
264
  if (existsSync(pluginTreePath)) return pluginTreePath;
247
265
  return fail(`cannot locate ${JOB_OBJECT_SHIM_FILENAME}; refusing to run the command unguarded`);
248
266
  }
249
- function windowsCommandNeedsCmdShell(firstCommandToken) {
250
- const knownExtension = extname(firstCommandToken).toLowerCase();
251
- if (knownExtension === ".cmd" || knownExtension === ".bat") return true;
252
- if (knownExtension !== "") return false;
267
+ function whereExeOutput(firstCommandToken) {
268
+ if (extname(firstCommandToken) !== "") return null;
253
269
  const lookup = spawnSync("where.exe", [firstCommandToken], {
254
270
  encoding: "utf-8",
255
271
  timeout: 1e4,
256
272
  windowsHide: true
257
273
  });
258
- if (lookup.error !== void 0 || lookup.status !== 0) return false;
259
- const resolvedExtension = extname(lookup.stdout.split(/\r?\n/)[0] ?? "").toLowerCase();
260
- return resolvedExtension === ".cmd" || resolvedExtension === ".bat";
274
+ return lookup.error === void 0 && lookup.status === 0 ? lookup.stdout : null;
261
275
  }
262
276
  function currentUserProcessCount() {
263
277
  const uid = typeof process.getuid === "function" ? String(process.getuid()) : "";
@@ -299,7 +313,10 @@ function registerTreeCleanup(plan2, childPid) {
299
313
  });
300
314
  }
301
315
  }
302
- var parseResult = parseGuardRunArguments(process.argv.slice(2));
316
+ var parseResult = parseGuardRunArguments(
317
+ process.argv.slice(2),
318
+ computeDefaultActiveProcessLimit(availableParallelism())
319
+ );
303
320
  if (parseResult.options === null) fail(parseResult.errorMessage ?? "invalid arguments");
304
321
  var options = parseResult.options;
305
322
  var isLinux = process.platform === "linux";
@@ -317,7 +334,10 @@ var plan = buildBackendLaunchPlan({
317
334
  options,
318
335
  jobObjectShimPath: backend === "windows-job-object" /* WindowsJobObject */ ? resolveJobObjectShimPath() : void 0,
319
336
  launcherPid: process.pid,
320
- commandNeedsCmdShell: backend === "windows-job-object" /* WindowsJobObject */ ? windowsCommandNeedsCmdShell(options.command[0]) : false,
337
+ commandNeedsCmdShell: backend === "windows-job-object" /* WindowsJobObject */ ? windowsCommandNeedsCmdShell({
338
+ firstCommandToken: options.command[0],
339
+ whereOutput: whereExeOutput(options.command[0])
340
+ }) : false,
321
341
  scopeUnitName: `muggle-guard-${process.pid}-${Date.now()}.scope`,
322
342
  nprocCeiling: needsNprocCeiling ? computeNprocCeiling({
323
343
  currentUserProcessCount: currentUserProcessCount(),
@@ -47,7 +47,7 @@ Forward pipeline's Stage 7. Invoked by `/muggle-do` after stages 1–6 of a fres
47
47
 
48
48
  6. **Settle the designated walkthrough comment.** Creating the PR reserves one comment for the walkthrough, marked `muggle-pr-walkthrough` and empty until settled — the PR's walkthrough check fails while it stays that way.
49
49
  - E2E report exists → fire [`postPRVisualWalkthrough`](../../muggle-preferences/preference-gates/postPRVisualWalkthrough.md); on skip, leave the comment to the gate's own skip record. Otherwise invoke [`../../muggle-pr-visual-walkthrough/SKILL.md`](../../muggle-pr-visual-walkthrough/SKILL.md) Mode A with the PR number — it fills the reserved comment in place.
50
- - No E2E report (validation was `unit-only` or `skip`) → state the reason on the PR with `echo "MUGGLE_E2E_SKIP: <reason>"`, which settles the comment as a declared skip. A PR whose title says `[UNIT-ONLY]` still owes reviewers the why.
50
+ - No E2E report (validation was `unit-only` or `skip`) → now that the PR exists, re-declare the skip Stage 6 recorded with the same code: `echo "MUGGLE_E2E_SKIP: <CODE>: <detail>"`, codes per [`../e2e-acceptance.md`](../e2e-acceptance.md). An accepted code settles the comment as a declared skip; a free-text reason is rejected and leaves it unsettled. A PR whose title says `[UNIT-ONLY]` still owes reviewers the why.
51
51
 
52
52
  7. **Overflow comment:** if the walkthrough skill returned a non-null `comment`, post it once using the provider resolved in Step 5 — `github` per [`../../_shared/vcs/github/top-level-comment.md`](../../_shared/vcs/github/top-level-comment.md), `gitlab` per [`../../_shared/vcs/gitlab/mr-note.md`](../../_shared/vcs/gitlab/mr-note.md). End the posted body with the signature line (command `/muggle-do`) per [`../../_shared/vcs/post-signature.md`](../../_shared/vcs/post-signature.md). Never post when `comment` is `null`.
53
53