@muggleai/works 5.26.0 → 5.27.0-staging.227

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.
@@ -1,4 +1,4 @@
1
- import { readFileSync, existsSync, readdirSync, mkdirSync, openSync, fstatSync, readSync, closeSync, statSync, writeFileSync, renameSync, writeSync, unlinkSync } from 'fs';
1
+ import { readFileSync, existsSync, readdirSync, mkdirSync, openSync, fstatSync, readSync, closeSync, statSync, writeFileSync, renameSync, writeSync, unlinkSync, rmSync } from 'fs';
2
2
  import { join, basename, isAbsolute, resolve, dirname } from 'path';
3
3
  import { homedir, hostname } from 'os';
4
4
  import { execFileSync, spawn } from 'child_process';
@@ -67,6 +67,8 @@ var THREADED_REPLY_TARGET = /pulls\/\d+\/comments\/(\d+)\/replies|discussions\/(
67
67
  var MAX_REPLY_BLOCKS = 3;
68
68
  var CAPABILITY_CLAIM_TRANSCRIPT_TAIL_BYTES = 64e3;
69
69
  var SESSION_STATE_LOCK_WAIT_MS = 250;
70
+ var DEFERRED_STATE_LOCK_WAIT_MS = 3e4;
71
+ var DEFERRED_STATE_MUTATION_INFIX = ".deferred-";
70
72
  var LOCK_POLL_INTERVAL_MS = 10;
71
73
  var CALL_FAILURE_SIGNALS = [
72
74
  /\bgh:\s/,
@@ -152,7 +154,8 @@ function withFileLock(lockPath, waitMs, run) {
152
154
 
153
155
  // src/guardrails/sessionState.ts
154
156
  var baseDir = (override) => override ?? join(homedir(), ".muggle-ai", "guardrails");
155
- var fileFor = (sessionId2, override, suffix = ".json") => join(baseDir(override), `${sessionId2.replace(/[^A-Za-z0-9_-]/g, "_")}${suffix}`);
157
+ var sessionFileStem = (sessionId2) => sessionId2.replace(/[^A-Za-z0-9_-]/g, "_");
158
+ var fileFor = (sessionId2, override, suffix = ".json") => join(baseDir(override), `${sessionFileStem(sessionId2)}${suffix}`);
156
159
  var WALKTHROUGH_SCAN_SUFFIX = ".walkthrough-scan.json";
157
160
  var PR_STATE_SCAN_SUFFIX = ".pr-state-scan.json";
158
161
  function writeAtomically(target, contents, dirOverride) {
@@ -195,20 +198,59 @@ function readPrStateScan(sessionId2, dirOverride) {
195
198
  function writePrStateScan(sessionId2, scan, dirOverride) {
196
199
  writeAtomically(fileFor(sessionId2, dirOverride, PR_STATE_SCAN_SUFFIX), scan, dirOverride);
197
200
  }
201
+ var lockFor = (sessionId2, dirOverride) => `${fileFor(sessionId2, dirOverride)}.lock`;
202
+ function commitUnderHeldLock(sessionId2, mutate, dirOverride) {
203
+ const current = readState(sessionId2, dirOverride);
204
+ const next = mutate(current);
205
+ if (next === current) return current;
206
+ const committed = { ...next, generation: (current.generation ?? 0) + 1 };
207
+ writeState(committed, dirOverride);
208
+ return committed;
209
+ }
198
210
  function commitState(sessionId2, mutate, dirOverride) {
199
211
  mkdirSync(baseDir(dirOverride), { recursive: true });
200
- return withFileLock(`${fileFor(sessionId2, dirOverride)}.lock`, SESSION_STATE_LOCK_WAIT_MS, () => {
201
- const current = readState(sessionId2, dirOverride);
202
- const next = mutate(current);
203
- if (next === current) return current;
204
- const committed = { ...next, generation: (current.generation ?? 0) + 1 };
205
- writeState(committed, dirOverride);
212
+ return withFileLock(
213
+ lockFor(sessionId2, dirOverride),
214
+ SESSION_STATE_LOCK_WAIT_MS,
215
+ () => commitUnderHeldLock(sessionId2, mutate, dirOverride)
216
+ );
217
+ }
218
+ var deferredMutationSequence = 0;
219
+ var deferredMutationPrefix = (sessionId2) => `${sessionFileStem(sessionId2)}${DEFERRED_STATE_MUTATION_INFIX}`;
220
+ function deferredMutationFiles(sessionId2, dirOverride) {
221
+ const prefix = deferredMutationPrefix(sessionId2);
222
+ const creationKey = (name) => name.slice(prefix.length, -".json".length).split("-").map(Number);
223
+ try {
224
+ return readdirSync(baseDir(dirOverride)).filter((name) => name.startsWith(prefix) && name.endsWith(".json")).map((name) => ({ name, key: creationKey(name) })).sort((left, right) => left.key[0] - right.key[0] || left.key[2] - right.key[2]).map((entry) => join(baseDir(dirOverride), entry.name));
225
+ } catch {
226
+ return [];
227
+ }
228
+ }
229
+ function deferStateMutation(sessionId2, mutation, dirOverride) {
230
+ deferredMutationSequence += 1;
231
+ const entryName = `${Date.now()}-${process.pid}-${deferredMutationSequence}.json`;
232
+ writeAtomically(
233
+ join(baseDir(dirOverride), `${deferredMutationPrefix(sessionId2)}${entryName}`),
234
+ mutation,
235
+ dirOverride
236
+ );
237
+ }
238
+ function commitDeferredStateMutations(sessionId2, applyMutation, dirOverride) {
239
+ mkdirSync(baseDir(dirOverride), { recursive: true });
240
+ return withFileLock(lockFor(sessionId2, dirOverride), DEFERRED_STATE_LOCK_WAIT_MS, () => {
241
+ const entryFiles = deferredMutationFiles(sessionId2, dirOverride);
242
+ const mutations = entryFiles.flatMap((entryFile) => {
243
+ try {
244
+ return [JSON.parse(readFileSync(entryFile, "utf-8"))];
245
+ } catch {
246
+ return [];
247
+ }
248
+ });
249
+ const committed = commitUnderHeldLock(sessionId2, (state) => mutations.reduce(applyMutation, state), dirOverride);
250
+ for (const entryFile of entryFiles) rmSync(entryFile, { force: true });
206
251
  return committed;
207
252
  });
208
253
  }
209
- function updateState(sessionId2, mutate, dirOverride) {
210
- return commitState(sessionId2, mutate, dirOverride) !== void 0;
211
- }
212
254
  function markPrHandled(sessionId2, prUrl, dirOverride) {
213
255
  const state = readState(sessionId2, dirOverride);
214
256
  if (!state.prsHandled.includes(prUrl)) state.prsHandled.push(prUrl);
@@ -224,6 +266,7 @@ var GuardrailBackgroundJob = /* @__PURE__ */ ((GuardrailBackgroundJob2) => {
224
266
  GuardrailBackgroundJob2["SettleWalkthroughUnreasoned"] = "settle-walkthrough-unreasoned";
225
267
  GuardrailBackgroundJob2["SettleWalkthroughNoAppLogicChange"] = "settle-walkthrough-no-app-logic-change";
226
268
  GuardrailBackgroundJob2["ScanWatchPrStates"] = "scan-watch-pr-states";
269
+ GuardrailBackgroundJob2["CommitDeferredState"] = "commit-deferred-state";
227
270
  return GuardrailBackgroundJob2;
228
271
  })(GuardrailBackgroundJob || {});
229
272
  var ProviderPrState = /* @__PURE__ */ ((ProviderPrState2) => {
@@ -253,638 +296,314 @@ function startBackgroundJob(job, jobArgs2, cwd) {
253
296
  }
254
297
  }
255
298
 
256
- // src/guardrails/shellTool.ts
257
- function isShellToolCall(input2) {
258
- return SHELL_TOOL_NAMES.includes(input2.tool_name ?? "");
299
+ // src/e2e-skip/types.ts
300
+ var E2eSkipCode = /* @__PURE__ */ ((E2eSkipCode3) => {
301
+ E2eSkipCode3["NoWebSurface"] = "NO_WEB_SURFACE";
302
+ E2eSkipCode3["DevServerUnreachable"] = "DEV_SERVER_UNREACHABLE";
303
+ E2eSkipCode3["EmptyDiff"] = "EMPTY_DIFF";
304
+ E2eSkipCode3["MuggleAuthDown"] = "MUGGLE_AUTH_DOWN";
305
+ E2eSkipCode3["NoPr"] = "NO_PR";
306
+ E2eSkipCode3["UserWaived"] = "USER_WAIVED";
307
+ E2eSkipCode3["NoAppLogicChange"] = "NO_APP_LOGIC_CHANGE";
308
+ E2eSkipCode3["NotApplicable"] = "NOT_APPLICABLE";
309
+ return E2eSkipCode3;
310
+ })(E2eSkipCode || {});
311
+
312
+ // src/e2e-skip/constants.ts
313
+ var E2E_SKIP_DECLARATION = /^\s*echo\s+["']?MUGGLE_E2E_SKIP:(.*)$/;
314
+ var SKIP_CODE_TOKEN = /^[\s:]*([A-Za-z_]+)/;
315
+ var E2E_SKIP_CODES = Object.values(E2eSkipCode);
316
+ var NON_APP_PATH_SUMMARY = "docs, tests, lint/format config, or CI config";
317
+ var E2E_SKIP_CODE_CLAIMS = {
318
+ ["NO_WEB_SURFACE" /* NoWebSurface */]: "the repo ships no web surface to drive",
319
+ ["DEV_SERVER_UNREACHABLE" /* DevServerUnreachable */]: "the named dev server does not answer",
320
+ ["EMPTY_DIFF" /* EmptyDiff */]: "the branch carries no diff against its base",
321
+ ["MUGGLE_AUTH_DOWN" /* MuggleAuthDown */]: "the stored Muggle session is missing or expired",
322
+ ["NO_PR" /* NoPr */]: "no pull request was handled this session",
323
+ ["USER_WAIVED" /* UserWaived */]: "the user waived E2E in their own words",
324
+ ["NO_APP_LOGIC_CHANGE" /* NoAppLogicChange */]: `every path changed since the named commit is ${NON_APP_PATH_SUMMARY}`,
325
+ ["NOT_APPLICABLE" /* NotApplicable */]: "a browser run cannot exercise this change, for the reason stated"
326
+ };
327
+ var CYCLE_SCOPED_SKIP_CODES = ["NO_APP_LOGIC_CHANGE" /* NoAppLogicChange */];
328
+ var PRE_CYCLE_SHA_TOKEN = /^([0-9a-f]{7,40})(?![0-9a-z_])/i;
329
+ var NON_APP_PATH_PATTERNS = [
330
+ /\.(md|markdown|rst)$/i,
331
+ /(^|\/)[^/]+\.(test|spec)\.[^/]+$/,
332
+ /(^|\/)(__tests__|__snapshots__|__mocks__)\//,
333
+ /(^|\/)test_[^/]+\.py$/,
334
+ /(^|\/)[^/]+_test\.(py|go)$/,
335
+ /^tests?\//,
336
+ /(^|\/)\.(eslintrc|prettierrc|stylelintrc)(\.[a-z]+)?$/,
337
+ /(^|\/)(eslint|prettier|stylelint)\.config\.[cm]?[jt]s$/,
338
+ /(^|\/)\.(eslint|prettier|stylelint)ignore$/,
339
+ /(^|\/)\.markdownlint[^/]*$/,
340
+ /(^|\/)(biome\.jsonc?|\.editorconfig)$/,
341
+ /^\.github\/workflows\//,
342
+ /^\.gitlab-ci\.yml$/
343
+ ];
344
+ var MAX_NAMED_APP_LOGIC_PATHS = 5;
345
+ var USER_WAIVE_PHRASE = "SKIP E2E";
346
+ var MIN_NOT_APPLICABLE_REASON_WORDS = 4;
347
+ var DEV_SERVER_PROBE_TIMEOUT_MS = 2e3;
348
+ var GIT_PROBE_TIMEOUT_MS = 5e3;
349
+ var WEB_SERVER_COMMAND = /\b(vite|next\s+(dev|start)|react-scripts|ng\s+serve|nuxt|astro\s+dev|remix\s+dev|webpack(-dev)?-server|http-server|serve\s+-s|gatsby\s+develop|vue-cli-service\s+serve)\b/;
350
+ var BROWSER_FRAMEWORK_PACKAGES = [
351
+ "react-dom",
352
+ "next",
353
+ "vue",
354
+ "svelte",
355
+ "@angular/core",
356
+ "nuxt",
357
+ "astro",
358
+ "@remix-run/react",
359
+ "preact",
360
+ "solid-js"
361
+ ];
362
+ var WEB_SURFACE_CONFIG_FILES = [
363
+ "next.config.js",
364
+ "next.config.mjs",
365
+ "next.config.ts",
366
+ "vite.config.js",
367
+ "vite.config.ts",
368
+ "index.html",
369
+ "public/index.html"
370
+ ];
371
+ var OAUTH_SESSION_FILE = /^oauth-session[\w.-]*\.json$/;
372
+ var MUGGLE_HOME_DIR_NAME = ".muggle-ai";
373
+
374
+ // src/guardrails/callOutcome.ts
375
+ function renderedResponse(toolResponse) {
376
+ const rendered = [];
377
+ const collect = (value) => {
378
+ if (typeof value === "string") rendered.push(value);
379
+ else if (Array.isArray(value)) value.forEach(collect);
380
+ else if (value && typeof value === "object") Object.values(value).forEach(collect);
381
+ };
382
+ collect(toolResponse);
383
+ return rendered.join("\n");
384
+ }
385
+ function callFailed(input2) {
386
+ const rendered = renderedResponse(input2.tool_response);
387
+ return CALL_FAILURE_SIGNALS.some((signal) => signal.test(rendered));
259
388
  }
260
389
 
261
- // src/guardrails/prOpened.ts
262
- var CREATE_CMD = /\bgh\s+pr\s+(create|ready)\b/;
263
- var MR_CREATE_CMD = /\bglab\s+mr\s+create\b|\bglab\s+mr\s+update\b.*--ready\b/;
264
- function detectPrOpened(input2) {
265
- if (!isShellToolCall(input2)) return null;
266
- const cmd = input2.tool_input?.command ?? "";
267
- if (!CREATE_CMD.test(cmd) && !MR_CREATE_CMD.test(cmd)) return null;
268
- const out = `${input2.tool_response?.stdout ?? ""}
269
- ${input2.tool_response?.output ?? ""}`;
270
- const m = out.match(GITHUB_PR_URL) ?? out.match(GITLAB_MR_URL);
271
- return m ? m[0] : null;
390
+ // src/guardrails/prUrls.ts
391
+ function extractPrUrls(text) {
392
+ const githubPrUrls = [...text.matchAll(new RegExp(GITHUB_PR_URL.source, "g"))];
393
+ const gitlabMrUrls = [...text.matchAll(new RegExp(GITLAB_MR_URL.source, "g"))];
394
+ return [...new Set([...githubPrUrls, ...gitlabMrUrls].map((match) => match[0]))];
272
395
  }
273
396
 
274
- // src/guardrails/prTerminal.ts
275
- function terminalProvenance(input2) {
276
- const command = input2.tool_input?.command;
277
- if (command === void 0) return { acceptsForgeLine: true, acceptsMonitorLine: true };
278
- return {
279
- acceptsForgeLine: FORGE_TERMINAL_CMD.test(command),
280
- acceptsMonitorLine: WATCH_TERMINAL_CMD.test(command)
281
- };
397
+ // src/guardrails/delegatedE2e.ts
398
+ function carriesAcceptanceReport(input2) {
399
+ const response = JSON.stringify(input2.tool_response ?? "");
400
+ return ACCEPTANCE_REPORT_MARKERS.some((marker) => response.includes(marker));
282
401
  }
283
- function detectPrTerminal(input2) {
284
- if (!isShellToolCall(input2) && input2.tool_name !== "Monitor") return null;
285
- const response = input2.tool_response;
286
- const provenance = terminalProvenance(input2);
287
- const haystack = [response?.stdout, response?.stderr, response?.output, response?.content].filter((part) => typeof part === "string").join("\n");
288
- const mergedMatch = provenance.acceptsForgeLine ? haystack.match(GH_PR_MERGED_LINE) : null;
289
- if (mergedMatch) {
290
- return { prNumber: Number(mergedMatch[1]), verdict: "merged" /* Merged */ };
291
- }
292
- const closedMatch = provenance.acceptsForgeLine ? haystack.match(GH_PR_CLOSED_LINE) : null;
293
- if (closedMatch) {
294
- return { prNumber: Number(closedMatch[1]), verdict: "closed" /* Closed */ };
295
- }
296
- const monitorMatch = provenance.acceptsMonitorLine ? haystack.match(PR_MONITOR_TERMINAL_LINE) : null;
297
- if (monitorMatch) {
298
- return {
299
- prNumber: Number(monitorMatch[1]),
300
- verdict: monitorMatch[2] === "MERGED" ? "merged" /* Merged */ : "closed" /* Closed */
301
- };
302
- }
303
- return null;
402
+ function detectBackgroundAcceptanceDispatch(input2) {
403
+ if (!SUBAGENT_DISPATCH_TOOL_NAMES.includes(input2.tool_name ?? "")) return null;
404
+ if (!ACCEPTANCE_TESTER_SUBAGENT_TYPE.test(input2.tool_input?.subagent_type ?? "")) return null;
405
+ if (callFailed(input2) || carriesAcceptanceReport(input2)) return null;
406
+ return extractPrUrls(input2.tool_input?.prompt ?? "");
304
407
  }
305
- function detectPrReopened(input2) {
306
- if (!isShellToolCall(input2)) return null;
307
- if (!terminalProvenance(input2).acceptsForgeLine) return null;
308
- const response = input2.tool_response;
309
- const haystack = [response?.stdout, response?.stderr, response?.output, response?.content].filter((part) => typeof part === "string").join("\n");
310
- const reopenedMatch = haystack.match(GH_PR_REOPENED_LINE);
311
- return reopenedMatch ? Number(reopenedMatch[1]) : null;
408
+ function liveDelegations(state, now) {
409
+ return (state.e2eDelegations ?? []).filter((delegation) => now - delegation.dispatchedAt < DELEGATED_E2E_WINDOW_MS);
312
410
  }
313
- function applyPrReopened(state, prNumber) {
314
- const pending = state.terminalPending ?? [];
315
- const handled = state.terminalHandled ?? [];
316
- if (!pending.includes(prNumber) && !handled.includes(prNumber)) return state;
317
- return {
318
- ...state,
319
- terminalPending: pending.filter((number) => number !== prNumber),
320
- terminalHandled: handled.filter((number) => number !== prNumber)
321
- };
411
+ function applyE2eDelegation(state, delegation) {
412
+ return { ...state, e2eDelegations: [...liveDelegations(state, delegation.dispatchedAt), delegation] };
322
413
  }
323
- function applyPrTerminalDetected(state, prNumber) {
324
- const pending = state.terminalPending ?? [];
325
- const handled = state.terminalHandled ?? [];
326
- if (pending.includes(prNumber) || handled.includes(prNumber)) return state;
327
- return { ...state, terminalPending: [...pending, prNumber] };
414
+ function isE2eDelegationInFlight(state, now) {
415
+ return liveDelegations(state, now).length > 0;
328
416
  }
329
- function applyNextOptionsOffered(state) {
330
- const pending = state.terminalPending ?? [];
331
- if (pending.length === 0) return state;
332
- return {
333
- ...state,
334
- terminalPending: [],
335
- terminalHandled: [...state.terminalHandled ?? [], ...pending],
336
- terminalBlockCount: 0
337
- };
417
+ function withoutDelegatedPrs(prUrls, state, now) {
418
+ const delegatedPrUrls = new Set(liveDelegations(state, now).flatMap((delegation) => delegation.prUrls));
419
+ return prUrls.filter((prUrl) => !delegatedPrUrls.has(prUrl));
338
420
  }
339
- function closingMessageAsksUser(closingMessage) {
340
- return typeof closingMessage === "string" && closingMessage.includes("?");
421
+
422
+ // src/guardrails/shouldRunE2E.ts
423
+ var MAX_E2E_BLOCKS = 3;
424
+ function applyE2eSkipDeclaration(state, skip) {
425
+ if (!skip || CYCLE_SCOPED_SKIP_CODES.includes(skip.code)) return state;
426
+ return { ...state, e2eSkipDeclaration: { code: skip.code, detail: skip.detail } };
341
427
  }
342
- function prTerminalGateDecision(state, maxBlocks = MAX_PR_TERMINAL_BLOCKS) {
343
- const blockCount = state.terminalBlockCount ?? 0;
344
- if ((state.terminalPending ?? []).length === 0) {
345
- return { action: "none" /* None */, blockCount };
428
+ function shouldRunE2E(state) {
429
+ const owed = state.unitTestsGreen === true || state.prsHandled.length > 0;
430
+ return owed && state.e2eRun !== true && state.e2eSkipped !== true;
431
+ }
432
+ function applyRecordedRun(state, run) {
433
+ let next = state;
434
+ if (run.unitTestPassed) {
435
+ next = { ...next, unitTestsGreen: true, e2eRun: false };
436
+ if (next.e2eSkipCycleScoped === true) next = { ...next, e2eSkipped: false, e2eSkipCycleScoped: false };
346
437
  }
347
- if (blockCount >= maxBlocks) {
348
- return { action: "release" /* Release */, blockCount };
438
+ if (run.e2eRan) {
439
+ next = { ...next, e2eRun: true, e2eBlockCount: 0 };
440
+ }
441
+ if (run.e2eSkipped) {
442
+ const isEnvironmentSkipHeld = next.e2eSkipped === true && next.e2eSkipCycleScoped !== true;
443
+ next = { ...next, e2eSkipped: true, e2eSkipCycleScoped: !isEnvironmentSkipHeld && run.e2eSkipCycleScoped === true };
444
+ }
445
+ return next;
446
+ }
447
+ function e2eGateDecision(state, maxBlocks = MAX_E2E_BLOCKS, now = Date.now()) {
448
+ const blockCount = state.e2eBlockCount ?? 0;
449
+ if (!shouldRunE2E(state) || isE2eDelegationInFlight(state, now)) {
450
+ return { action: "none" /* None */, blockCount };
349
451
  }
452
+ if (blockCount >= maxBlocks) return { action: "release" /* Release */, blockCount };
350
453
  return { action: "block" /* Block */, blockCount: blockCount + 1 };
351
454
  }
352
455
 
353
- // src/guardrails/capabilityClaim.ts
354
- var SENTENCE = /[^.!?\n]+/g;
355
- var IMPOSSIBILITY = /\b(?:can(?:'|’)?t|cannot|can not|could ?n(?:'|’)?t|unable to|no way to|not able to|impossible|infeasible|untestable|unverifiable|not testable|blocked from|no (?:local )?(?:mail|email|smtp) path)\b/i;
356
- var MUGGLE_CLEARS = /\b(?:magic[- ]?link|sign[- ]?in link|login link|email link|one[- ]time (?:code|password)|otp|verification (?:code|link|email|mail)|email verification|confirmation (?:code|link|email|mail)|2fa|two[- ]factor|password reset|reset link|inbox|mailbox|mailhog|mailpit|mailtrap|mailcatcher|smtp|transactional email|captcha|recaptcha|hcaptcha|log ?in|logged[- ]?in|sign ?in|signed[- ]in|authenticate|credential|sms|text message|texted code|authenticator app|google authenticator|authy|totp)/i;
357
- var TESTING_CONTEXT = /\b(?:e2e|end[- ]to[- ]end|test(?:s|ed|ing|able)?|verif(?:y|ied|ication)|validat(?:e|ed|ion)|automat(?:e|ed|ion)|coverage|covered|exercis(?:e|ed)|reproduc(?:e|ed)|replay|scripts?|scripted|muggle|playwright|cypress|selenium)\b/i;
358
- var GENUINELY_UNSUPPORTED = /\b(?:phone call|voice call|oauth|social (?:login|sign[- ]?in)|sign in with (?:google|github|apple|facebook)|no (?:phone )?number (?:is )?provisioned|no provisioned (?:phone )?number)\b/i;
359
- function detectFalseCapabilityClaim(text) {
360
- const sentences = (text ?? "").match(SENTENCE) ?? [];
361
- return sentences.some(
362
- (sentence) => IMPOSSIBILITY.test(sentence) && MUGGLE_CLEARS.test(sentence) && TESTING_CONTEXT.test(sentence) && !GENUINELY_UNSUPPORTED.test(sentence)
363
- );
456
+ // src/hook-budget/constants.ts
457
+ var HOOK_CHILD_PROCESS_DEADLINE_MS = 600;
458
+
459
+ // src/hook-budget/childProcessBudget.ts
460
+ var childProcessDeadlineEpochMs = null;
461
+ function enforceHookChildProcessDeadline(gatesStartEpochMs = Date.now()) {
462
+ childProcessDeadlineEpochMs = gatesStartEpochMs + HOOK_CHILD_PROCESS_DEADLINE_MS;
364
463
  }
365
- function lastAssistantText(transcriptJsonl) {
366
- const lines = (transcriptJsonl ?? "").split("\n");
367
- for (let index = lines.length - 1; index >= 0; index -= 1) {
368
- const line = lines[index]?.trim();
369
- if (!line) continue;
370
- let entry;
371
- try {
372
- entry = JSON.parse(line);
373
- } catch {
374
- continue;
375
- }
376
- if (entry.type !== "assistant") continue;
377
- const content = entry.message?.content;
378
- if (typeof content === "string") return content;
379
- if (!Array.isArray(content)) continue;
380
- const prose = content.filter((part) => part.type === "text" && typeof part.text === "string").map((part) => part.text).join("\n");
381
- if (prose) return prose;
382
- }
383
- return "";
384
- }
385
- function resolvePluginRoot(env = process.env) {
386
- return env.CLAUDE_PLUGIN_ROOT || env.CURSOR_PLUGIN_ROOT || dirname(dirname(fileURLToPath(import.meta.url)));
464
+ function boundedChildTimeoutMs(ceilingMs) {
465
+ if (childProcessDeadlineEpochMs === null) return ceilingMs;
466
+ const remainingMs = Math.floor(childProcessDeadlineEpochMs - Date.now());
467
+ return remainingMs > 0 ? Math.min(ceilingMs, remainingMs) : null;
387
468
  }
388
469
 
389
- // src/guardrails/mandatoryStages.ts
390
- var FRONTMATTER = /^---\r?\n([\s\S]*?)\r?\n---/;
391
- var SEQUENCE_ENTRY = /^\s*-\s*(.+?)\s*$/;
392
- var FLOW_LIST = /^\s*\[(.*)\]\s*$/;
393
- var STAGE_SKIP_MARKER = /^\s*echo\s+["']?MUGGLE_STAGE_SKIP\b/;
394
- var SKILLS_DIR_NAME = "skills";
395
- var SKILLS_PATH_SEGMENT = `/${SKILLS_DIR_NAME}/`;
396
- var SINGLE_PATH_SEGMENT = /^[A-Za-z0-9._-]+$/;
397
- var SHELL_COMMAND_SEPARATOR = /[;&|\n]/;
398
- var SHELL_ASSIGNMENT = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/s;
399
- var SHELL_VARIABLE_REFERENCE = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g;
400
- var WINDOWS_ABSOLUTE_PATH = /^[A-Za-z]:[\\/]/;
401
- var MARKDOWN_FILE = /\.md$/i;
402
- var unquote = (raw) => raw.trim().replace(/^["']|["']$/g, "").trim();
403
- function parseDeclaredStages(skillMarkdown) {
404
- const frontmatter = FRONTMATTER.exec(skillMarkdown)?.[1];
405
- if (!frontmatter) return [];
406
- const lines = frontmatter.split(/\r?\n/);
407
- const keyIndex = lines.findIndex(
408
- (line) => line.startsWith(`${MANDATORY_STAGES_FRONTMATTER_KEY}:`)
409
- );
410
- if (keyIndex < 0) return [];
411
- const inlineValue = lines[keyIndex].slice(MANDATORY_STAGES_FRONTMATTER_KEY.length + 1).trim();
412
- const flowEntries = FLOW_LIST.exec(inlineValue)?.[1];
413
- if (flowEntries !== void 0) {
414
- return flowEntries.split(",").map(unquote).filter((entry) => entry.length > 0);
470
+ // src/e2e-skip/probes.ts
471
+ var readTextFile = (path) => {
472
+ try {
473
+ return readFileSync(path, "utf8");
474
+ } catch {
475
+ return null;
415
476
  }
416
- const declared = [];
417
- for (const line of lines.slice(keyIndex + 1)) {
418
- const entry = SEQUENCE_ENTRY.exec(line);
419
- if (!entry) break;
420
- declared.push(unquote(entry[1]));
477
+ };
478
+ var listFiles = (dir) => {
479
+ try {
480
+ return readdirSync(dir);
481
+ } catch {
482
+ return [];
421
483
  }
422
- return declared;
423
- }
424
- function normalizeStagePath(filePath) {
425
- return filePath.replaceAll("\\", "/").toLowerCase();
426
- }
427
- function stageLabel(normalizedStagePath) {
428
- const insideSkills = normalizedStagePath.lastIndexOf(SKILLS_PATH_SEGMENT);
429
- if (insideSkills < 0) return normalizedStagePath;
430
- return normalizedStagePath.slice(insideSkills + SKILLS_PATH_SEGMENT.length);
431
- }
432
- function resolvePluginSkillsRoot() {
433
- return join(resolvePluginRoot(), SKILLS_DIR_NAME);
434
- }
435
- function resolveSkillNameFromToolInput(toolInput) {
436
- if (!toolInput) return void 0;
437
- const indexed = toolInput;
438
- for (const inputKey of SKILL_NAME_INPUT_KEYS) {
439
- const value = indexed[inputKey];
440
- if (typeof value !== "string" || value.trim().length === 0) continue;
441
- const skillName = value.trim().split(":").pop()?.replace(/^\//, "") ?? "";
442
- return SINGLE_PATH_SEGMENT.test(skillName) ? skillName : void 0;
484
+ };
485
+ var runGit = (args, cwd) => {
486
+ const timeoutMs = boundedChildTimeoutMs(GIT_PROBE_TIMEOUT_MS);
487
+ if (timeoutMs === null) return null;
488
+ try {
489
+ return execFileSync("git", args, {
490
+ cwd,
491
+ encoding: "utf8",
492
+ timeout: timeoutMs,
493
+ stdio: ["ignore", "pipe", "ignore"],
494
+ windowsHide: true
495
+ });
496
+ } catch {
497
+ return null;
443
498
  }
444
- return void 0;
445
- }
446
- function resolveSkillStagePaths(skillName, skillsRootDir) {
447
- const skillDir = join(skillsRootDir, skillName);
448
- const skillFile = join(skillDir, "SKILL.md");
449
- if (!existsSync(skillFile)) return [];
450
- const normalizedRoot = normalizeStagePath(skillsRootDir);
451
- const staysInsideSkillsTree = (candidate) => normalizeStagePath(candidate).startsWith(`${normalizedRoot}/`);
452
- const resolved = [];
453
- for (const declared of parseDeclaredStages(readFileSync(skillFile, "utf-8"))) {
454
- if (isAbsolute(declared)) continue;
455
- const stagePath = [resolve(skillDir, declared), resolve(skillsRootDir, declared)].find(
456
- (candidate) => staysInsideSkillsTree(candidate) && existsSync(candidate)
457
- );
458
- if (!stagePath) continue;
459
- const normalized = normalizeStagePath(stagePath);
460
- if (!resolved.includes(normalized)) resolved.push(normalized);
499
+ };
500
+ var hostAndPort = (url) => {
501
+ const withScheme = /^https?:\/\//i.test(url) ? url : `http://${url}`;
502
+ try {
503
+ const parsed = new URL(withScheme);
504
+ const port = parsed.port ? Number(parsed.port) : parsed.protocol === "https:" ? 443 : 80;
505
+ return { host: parsed.hostname, port };
506
+ } catch {
507
+ return null;
461
508
  }
462
- return resolved;
463
- }
464
- function applySkillInvocation(state, skillName, stagePaths) {
465
- const merged = [...state.mandatoryStages ?? []];
466
- for (const stagePath of stagePaths) if (!merged.includes(stagePath)) merged.push(stagePath);
467
- if (state.lastInvokedSkillName === skillName && merged.length === (state.mandatoryStages?.length ?? 0)) {
468
- return state;
509
+ };
510
+ var isReachable = (url) => {
511
+ const target = hostAndPort(url);
512
+ if (!target) return false;
513
+ const spawnTimeoutMs = boundedChildTimeoutMs(DEV_SERVER_PROBE_TIMEOUT_MS * 2);
514
+ if (spawnTimeoutMs === null) return false;
515
+ const socketTimeoutMs = Math.min(DEV_SERVER_PROBE_TIMEOUT_MS, Math.floor(spawnTimeoutMs / 2));
516
+ const script = `const net=require('net');const s=net.connect(${target.port},${JSON.stringify(target.host)});s.setTimeout(${socketTimeoutMs});s.on('connect',()=>{s.destroy();process.exit(0)});s.on('timeout',()=>{s.destroy();process.exit(1)});s.on('error',()=>process.exit(1));`;
517
+ try {
518
+ execFileSync(process.execPath, ["-e", script], {
519
+ timeout: spawnTimeoutMs,
520
+ stdio: "ignore",
521
+ windowsHide: true
522
+ });
523
+ return true;
524
+ } catch {
525
+ return false;
469
526
  }
470
- return { ...state, lastInvokedSkillName: skillName, mandatoryStages: merged };
471
- }
472
- function isSkillTreeMarkdown(filePath) {
473
- const normalized = normalizeStagePath(filePath);
474
- return normalized.includes(SKILLS_PATH_SEGMENT) && MARKDOWN_FILE.test(normalized);
475
- }
476
- function applyStageRead(state, filePath) {
477
- const stagePath = normalizeStagePath(filePath);
478
- if ((state.stagesRead ?? []).includes(stagePath)) return state;
479
- return { ...state, stagesRead: [...state.stagesRead ?? [], stagePath] };
527
+ };
528
+ var defaultSkipProbes = {
529
+ readTextFile,
530
+ listFiles,
531
+ runGit,
532
+ isReachable
533
+ };
534
+
535
+ // src/guardrails/changeIdentity.ts
536
+ function toRepoKey(host2, path) {
537
+ const repoPath = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
538
+ return host2 && repoPath ? `${host2}/${repoPath}`.toLowerCase() : void 0;
480
539
  }
481
- var SHELL_ESCAPABLE_UNQUOTED = /* @__PURE__ */ new Set([" ", " ", "'", '"', "\\", "$", ";", "&", "|", "\n"]);
482
- var SHELL_ESCAPABLE_DOUBLE_QUOTED = /* @__PURE__ */ new Set(['"', "\\", "$", "`"]);
483
- function splitShellCommands(command) {
484
- const commands = [];
485
- let words = [];
486
- let word = "";
487
- let wordStarted = false;
488
- let quote = null;
489
- const endWord = () => {
490
- if (wordStarted) words.push(word);
491
- word = "";
492
- wordStarted = false;
493
- };
494
- const endCommand = () => {
495
- endWord();
496
- if (words.length > 0) commands.push(words);
497
- words = [];
498
- };
499
- for (let index = 0; index < command.length; index += 1) {
500
- const character = command[index];
501
- const nextCharacter = command[index + 1];
502
- if (quote !== null) {
503
- if (character === quote) {
504
- quote = null;
505
- } else if (character === "\\" && quote === '"' && SHELL_ESCAPABLE_DOUBLE_QUOTED.has(nextCharacter)) {
506
- word += nextCharacter;
507
- index += 1;
508
- } else {
509
- word += character;
510
- }
511
- continue;
512
- }
513
- if (character === "'" || character === '"') {
514
- quote = character;
515
- wordStarted = true;
516
- } else if (character === "\\" && SHELL_ESCAPABLE_UNQUOTED.has(nextCharacter)) {
517
- word += nextCharacter;
518
- wordStarted = true;
519
- index += 1;
520
- } else if (SHELL_COMMAND_SEPARATOR.test(character)) {
521
- endCommand();
522
- } else if (/\s/.test(character)) {
523
- endWord();
524
- } else {
525
- word += character;
526
- wordStarted = true;
527
- }
540
+ function repoKeyOfPrUrl(prUrl) {
541
+ const pullsAt = prUrl.match(GITHUB_PR_URL) ? prUrl.indexOf("/pull/") : prUrl.match(GITLAB_MR_URL) ? prUrl.indexOf("/-/merge_requests/") : -1;
542
+ if (pullsAt < 0) return void 0;
543
+ try {
544
+ const repoUrl = new URL(prUrl.slice(0, pullsAt));
545
+ return toRepoKey(repoUrl.hostname, repoUrl.pathname);
546
+ } catch {
547
+ return void 0;
528
548
  }
529
- endCommand();
530
- return commands;
531
- }
532
- function expandShellWord(word, variables) {
533
- const withHome = word === "~" || word.startsWith("~/") ? `${homedir()}${word.slice(1)}` : word;
534
- return withHome.replace(
535
- SHELL_VARIABLE_REFERENCE,
536
- (_reference, bracedName, bareName) => variables[bracedName ?? bareName ?? ""] ?? ""
537
- );
538
- }
539
- function resolveShellPath(path, workingDirectory) {
540
- return isAbsolute(path) || WINDOWS_ABSOLUTE_PATH.test(path) ? path : resolve(workingDirectory, path);
541
- }
542
- function detectShellStageReads(command, cwd, env = process.env) {
543
- const variables = { ...env };
544
- let workingDirectory = cwd ?? process.cwd();
545
- const readPaths = [];
546
- for (const words of splitShellCommands(command)) {
547
- let programIndex = 0;
548
- const assignments = [];
549
- for (; programIndex < words.length; programIndex += 1) {
550
- const assignment = SHELL_ASSIGNMENT.exec(words[programIndex]);
551
- if (!assignment) break;
552
- assignments.push([assignment[1], expandShellWord(assignment[2], variables)]);
553
- }
554
- const programWord = words[programIndex];
555
- if (programWord === void 0 || programWord === "export") {
556
- for (const word of words.slice(programIndex + 1)) {
557
- const exported = SHELL_ASSIGNMENT.exec(word);
558
- if (exported) assignments.push([exported[1], expandShellWord(exported[2], variables)]);
559
- }
560
- for (const [name, value] of assignments) variables[name] = value;
561
- continue;
562
- }
563
- const program = basename(programWord.replaceAll("\\", "/")).toLowerCase().replace(/\.exe$/, "");
564
- const argumentWords = words.slice(programIndex + 1).map((word) => expandShellWord(word, variables));
565
- if (program === "cd") {
566
- const target = argumentWords.find((word) => !word.startsWith("-"));
567
- if (target) workingDirectory = resolveShellPath(target, workingDirectory);
568
- continue;
569
- }
570
- if (!FILE_PRINTING_PROGRAMS.includes(program)) continue;
571
- for (const argument of argumentWords) {
572
- if (argument.startsWith("-") || !MARKDOWN_FILE.test(argument)) continue;
573
- const readPath = normalizeStagePath(resolveShellPath(argument, workingDirectory));
574
- if (isSkillTreeMarkdown(readPath) && !readPaths.includes(readPath)) readPaths.push(readPath);
575
- }
576
- }
577
- return readPaths;
578
- }
579
- function unreadMandatoryStages(state) {
580
- const read = new Set(state.stagesRead ?? []);
581
- return (state.mandatoryStages ?? []).filter((stagePath) => !read.has(stagePath));
582
- }
583
- function isStageSkipMarker(command) {
584
- return STAGE_SKIP_MARKER.test(command);
585
- }
586
- function applyStageSkip(state, skipped) {
587
- if (!skipped || state.stageSkipped === true) return state;
588
- return { ...state, stageSkipped: true };
589
- }
590
- function stageGateDecision(state, unreadStagePaths, maxBlocks = MAX_STAGE_BLOCKS) {
591
- const blockCount = state.stageBlockCount ?? 0;
592
- if (state.stageSkipped === true || unreadStagePaths.length === 0) {
593
- return { action: "none" /* None */, blockCount, unread: unreadStagePaths };
594
- }
595
- if (blockCount >= maxBlocks) {
596
- return { action: "release" /* Release */, blockCount, unread: unreadStagePaths };
597
- }
598
- return { action: "block" /* Block */, blockCount: blockCount + 1, unread: unreadStagePaths };
599
- }
600
-
601
- // src/guardrails/callOutcome.ts
602
- function renderedResponse(toolResponse) {
603
- const rendered = [];
604
- const collect = (value) => {
605
- if (typeof value === "string") rendered.push(value);
606
- else if (Array.isArray(value)) value.forEach(collect);
607
- else if (value && typeof value === "object") Object.values(value).forEach(collect);
608
- };
609
- collect(toolResponse);
610
- return rendered.join("\n");
611
- }
612
- function callFailed(input2) {
613
- const rendered = renderedResponse(input2.tool_response);
614
- return CALL_FAILURE_SIGNALS.some((signal) => signal.test(rendered));
615
- }
616
-
617
- // src/guardrails/preExecutionClassification.ts
618
- var CLASSIFICATION_SKIP_MARKER = /^\s*echo\s+["']?MUGGLE_CLASSIFY_SKIP\b/;
619
- function detectClassifiedTestCaseId(input2) {
620
- if (!MUGGLE_EVENT_EMIT_TOOL.test(input2.tool_name ?? "")) return void 0;
621
- if (input2.tool_input?.eventType !== PRE_EXECUTION_CLASSIFICATION_EVENT) return void 0;
622
- if (callFailed(input2)) return void 0;
623
- return input2.tool_input?.testCaseId ?? ANY_TEST_CASE;
624
- }
625
- function applyClassifiedTestCase(state, testCaseId) {
626
- if ((state.classifiedTestCaseIds ?? []).includes(testCaseId)) return state;
627
- return { ...state, classifiedTestCaseIds: [...state.classifiedTestCaseIds ?? [], testCaseId] };
628
- }
629
- function resolveExecutionTargetTestCaseId(input2) {
630
- if (!MUGGLE_EXECUTION_TOOL.test(input2.tool_name ?? "")) return void 0;
631
- return input2.tool_input?.testCase?.id ?? input2.tool_input?.testScript?.testCaseId;
632
- }
633
- function isClassificationSkipMarker(command) {
634
- return CLASSIFICATION_SKIP_MARKER.test(command);
635
- }
636
- function applyClassificationSkip(state, skipped) {
637
- if (!skipped || state.classificationSkipped === true) return state;
638
- return { ...state, classificationSkipped: true };
639
- }
640
- function classificationGateDecision(state, input2) {
641
- if (state.lastInvokedSkillName !== MUGGLE_TEST_SKILL_NAME) return { deny: false };
642
- if (state.classificationSkipped === true) return { deny: false };
643
- const testCaseId = resolveExecutionTargetTestCaseId(input2);
644
- if (!testCaseId) return { deny: false };
645
- const classified = state.classifiedTestCaseIds ?? [];
646
- if (classified.includes(ANY_TEST_CASE) || classified.includes(testCaseId)) return { deny: false };
647
- return { deny: true, testCaseId };
648
- }
649
-
650
- // src/guardrails/prUrls.ts
651
- function extractPrUrls(text) {
652
- const githubPrUrls = [...text.matchAll(new RegExp(GITHUB_PR_URL.source, "g"))];
653
- const gitlabMrUrls = [...text.matchAll(new RegExp(GITLAB_MR_URL.source, "g"))];
654
- return [...new Set([...githubPrUrls, ...gitlabMrUrls].map((match) => match[0]))];
655
- }
656
-
657
- // src/guardrails/delegatedE2e.ts
658
- function carriesAcceptanceReport(input2) {
659
- const response = JSON.stringify(input2.tool_response ?? "");
660
- return ACCEPTANCE_REPORT_MARKERS.some((marker) => response.includes(marker));
661
- }
662
- function detectBackgroundAcceptanceDispatch(input2) {
663
- if (!SUBAGENT_DISPATCH_TOOL_NAMES.includes(input2.tool_name ?? "")) return null;
664
- if (!ACCEPTANCE_TESTER_SUBAGENT_TYPE.test(input2.tool_input?.subagent_type ?? "")) return null;
665
- if (callFailed(input2) || carriesAcceptanceReport(input2)) return null;
666
- return extractPrUrls(input2.tool_input?.prompt ?? "");
667
- }
668
- function liveDelegations(state, now) {
669
- return (state.e2eDelegations ?? []).filter((delegation) => now - delegation.dispatchedAt < DELEGATED_E2E_WINDOW_MS);
670
- }
671
- function applyE2eDelegation(state, delegation) {
672
- return { ...state, e2eDelegations: [...liveDelegations(state, delegation.dispatchedAt), delegation] };
673
- }
674
- function isE2eDelegationInFlight(state, now) {
675
- return liveDelegations(state, now).length > 0;
676
- }
677
- function withoutDelegatedPrs(prUrls, state, now) {
678
- const delegatedPrUrls = new Set(liveDelegations(state, now).flatMap((delegation) => delegation.prUrls));
679
- return prUrls.filter((prUrl) => !delegatedPrUrls.has(prUrl));
680
- }
681
-
682
- // src/guardrails/debugPath.ts
683
- var DEBUG_SKIP_MARKER = /^\s*echo\s+["']?MUGGLE_DEBUG_SKIP\b/;
684
- var serialize = (input2) => `${JSON.stringify(input2.tool_input ?? {})}
685
- ${JSON.stringify(input2.tool_response ?? {})}`;
686
- function renderedResult(toolResponse) {
687
- const rendered = [];
688
- const collect = (value) => {
689
- if (typeof value === "string") rendered.push(value);
690
- else if (Array.isArray(value)) value.forEach(collect);
691
- else if (value && typeof value === "object") Object.values(value).forEach(collect);
692
- };
693
- collect(toolResponse);
694
- return rendered.join("\n");
695
- }
696
- function detectFailedRunId(input2) {
697
- if (!MUGGLE_EXECUTION_TOOL.test(input2.tool_name ?? "")) return void 0;
698
- const rendered = renderedResult(input2.tool_response);
699
- const status = MUGGLE_RUN_STATUS_LINE.exec(rendered)?.[1];
700
- if (!status || status.toLowerCase() === MUGGLE_RUN_PASSED_STATUS) return void 0;
701
- return MUGGLE_RUN_ID_LINE.exec(rendered)?.[1];
702
- }
703
- function applyFailedRun(state, runId) {
704
- if ((state.failedRuns ?? []).includes(runId)) return state;
705
- return { ...state, failedRuns: [...state.failedRuns ?? [], runId] };
706
- }
707
- function detectDebugEvidenceRunIds(input2, owedRunIds) {
708
- const toolName = input2.tool_name ?? "";
709
- const isDiagnosisEmit = MUGGLE_EVENT_EMIT_TOOL.test(toolName) && FAILURE_DIAGNOSIS_EVENT.test(input2.tool_input?.eventType ?? "");
710
- if (!isDiagnosisEmit && !MUGGLE_FEEDBACK_CREATE_TOOL.test(toolName)) return [];
711
- if (callFailed(input2)) return [];
712
- const payload = serialize(input2);
713
- return owedRunIds.filter((runId) => payload.includes(runId));
714
- }
715
- function applyDebugEvidence(state, runIds) {
716
- const debugged = [...state.debuggedRuns ?? []];
717
- for (const runId of runIds) if (!debugged.includes(runId)) debugged.push(runId);
718
- if (debugged.length === (state.debuggedRuns ?? []).length) return state;
719
- return { ...state, debuggedRuns: debugged };
720
- }
721
- function isDebugSkipMarker(command) {
722
- return DEBUG_SKIP_MARKER.test(command);
723
- }
724
- function applyDebugSkip(state, command) {
725
- if (!isDebugSkipMarker(command)) return state;
726
- const namedRuns = (state.failedRuns ?? []).filter((runId) => command.includes(runId));
727
- if (namedRuns.length > 0) return applyDebugEvidence(state, namedRuns);
728
- if (state.debugSkipped === true) return state;
729
- return { ...state, debugSkipped: true };
730
- }
731
- function undebuggedFailedRuns(state) {
732
- const debugged = new Set(state.debuggedRuns ?? []);
733
- return (state.failedRuns ?? []).filter((runId) => !debugged.has(runId));
734
- }
735
- function debugGateDecision(state, maxBlocks = MAX_DEBUG_BLOCKS, now = Date.now()) {
736
- const blockCount = state.debugBlockCount ?? 0;
737
- const undebugged = undebuggedFailedRuns(state);
738
- if (state.debugSkipped === true || undebugged.length === 0 || isE2eDelegationInFlight(state, now)) {
739
- return { action: "none" /* None */, blockCount, undebugged };
740
- }
741
- if (blockCount >= maxBlocks) {
742
- return { action: "release" /* Release */, blockCount, undebugged };
743
- }
744
- return { action: "block" /* Block */, blockCount: blockCount + 1, undebugged };
745
- }
746
-
747
- // src/guardrails/testsGreen.ts
748
- var TEST_CMD = /\b(pnpm|npm|yarn)\s+(run\s+)?test\b|\b(jest|vitest|pytest)\b|\bgo\s+test\b|\bcargo\s+test\b/;
749
- var FAIL = /\b\d+\s+failed\b|\bFAIL\b|✗/;
750
- var E2E_TOOL = /muggle.*(execute|test-generation|replay)/i;
751
- function isTestCommand(cmd) {
752
- return TEST_CMD.test(cmd);
753
- }
754
- function testsPassed(input2) {
755
- const response = input2.tool_response;
756
- const out = `${response?.stdout ?? ""}
757
- ${response?.stderr ?? ""}
758
- ${response?.output ?? ""}`;
759
- if (!out.trim()) return false;
760
- return !FAIL.test(out);
761
- }
762
- function isE2ERun(input2) {
763
- if (E2E_TOOL.test(input2.tool_name ?? "")) return true;
764
- return MUGGLE_SKILL_EMIT_TOOL.test(input2.tool_name ?? "") && input2.tool_input?.skillName === MUGGLE_TEST_SKILL_NAME;
765
- }
766
-
767
- // src/e2e-skip/types.ts
768
- var E2eSkipCode = /* @__PURE__ */ ((E2eSkipCode3) => {
769
- E2eSkipCode3["NoWebSurface"] = "NO_WEB_SURFACE";
770
- E2eSkipCode3["DevServerUnreachable"] = "DEV_SERVER_UNREACHABLE";
771
- E2eSkipCode3["EmptyDiff"] = "EMPTY_DIFF";
772
- E2eSkipCode3["MuggleAuthDown"] = "MUGGLE_AUTH_DOWN";
773
- E2eSkipCode3["NoPr"] = "NO_PR";
774
- E2eSkipCode3["UserWaived"] = "USER_WAIVED";
775
- E2eSkipCode3["NoAppLogicChange"] = "NO_APP_LOGIC_CHANGE";
776
- E2eSkipCode3["NotApplicable"] = "NOT_APPLICABLE";
777
- return E2eSkipCode3;
778
- })(E2eSkipCode || {});
779
-
780
- // src/e2e-skip/constants.ts
781
- var E2E_SKIP_DECLARATION = /^\s*echo\s+["']?MUGGLE_E2E_SKIP:(.*)$/;
782
- var SKIP_CODE_TOKEN = /^[\s:]*([A-Za-z_]+)/;
783
- var E2E_SKIP_CODES = Object.values(E2eSkipCode);
784
- var NON_APP_PATH_SUMMARY = "docs, tests, lint/format config, or CI config";
785
- var E2E_SKIP_CODE_CLAIMS = {
786
- ["NO_WEB_SURFACE" /* NoWebSurface */]: "the repo ships no web surface to drive",
787
- ["DEV_SERVER_UNREACHABLE" /* DevServerUnreachable */]: "the named dev server does not answer",
788
- ["EMPTY_DIFF" /* EmptyDiff */]: "the branch carries no diff against its base",
789
- ["MUGGLE_AUTH_DOWN" /* MuggleAuthDown */]: "the stored Muggle session is missing or expired",
790
- ["NO_PR" /* NoPr */]: "no pull request was handled this session",
791
- ["USER_WAIVED" /* UserWaived */]: "the user waived E2E in their own words",
792
- ["NO_APP_LOGIC_CHANGE" /* NoAppLogicChange */]: `every path changed since the named commit is ${NON_APP_PATH_SUMMARY}`,
793
- ["NOT_APPLICABLE" /* NotApplicable */]: "a browser run cannot exercise this change, for the reason stated"
794
- };
795
- var CYCLE_SCOPED_SKIP_CODES = ["NO_APP_LOGIC_CHANGE" /* NoAppLogicChange */];
796
- var PRE_CYCLE_SHA_TOKEN = /^([0-9a-f]{7,40})(?![0-9a-z_])/i;
797
- var NON_APP_PATH_PATTERNS = [
798
- /\.(md|markdown|rst)$/i,
799
- /(^|\/)[^/]+\.(test|spec)\.[^/]+$/,
800
- /(^|\/)(__tests__|__snapshots__|__mocks__)\//,
801
- /(^|\/)test_[^/]+\.py$/,
802
- /(^|\/)[^/]+_test\.(py|go)$/,
803
- /^tests?\//,
804
- /(^|\/)\.(eslintrc|prettierrc|stylelintrc)(\.[a-z]+)?$/,
805
- /(^|\/)(eslint|prettier|stylelint)\.config\.[cm]?[jt]s$/,
806
- /(^|\/)\.(eslint|prettier|stylelint)ignore$/,
807
- /(^|\/)\.markdownlint[^/]*$/,
808
- /(^|\/)(biome\.jsonc?|\.editorconfig)$/,
809
- /^\.github\/workflows\//,
810
- /^\.gitlab-ci\.yml$/
811
- ];
812
- var MAX_NAMED_APP_LOGIC_PATHS = 5;
813
- var USER_WAIVE_PHRASE = "SKIP E2E";
814
- var MIN_NOT_APPLICABLE_REASON_WORDS = 4;
815
- var DEV_SERVER_PROBE_TIMEOUT_MS = 2e3;
816
- var GIT_PROBE_TIMEOUT_MS = 5e3;
817
- var WEB_SERVER_COMMAND = /\b(vite|next\s+(dev|start)|react-scripts|ng\s+serve|nuxt|astro\s+dev|remix\s+dev|webpack(-dev)?-server|http-server|serve\s+-s|gatsby\s+develop|vue-cli-service\s+serve)\b/;
818
- var BROWSER_FRAMEWORK_PACKAGES = [
819
- "react-dom",
820
- "next",
821
- "vue",
822
- "svelte",
823
- "@angular/core",
824
- "nuxt",
825
- "astro",
826
- "@remix-run/react",
827
- "preact",
828
- "solid-js"
829
- ];
830
- var WEB_SURFACE_CONFIG_FILES = [
831
- "next.config.js",
832
- "next.config.mjs",
833
- "next.config.ts",
834
- "vite.config.js",
835
- "vite.config.ts",
836
- "index.html",
837
- "public/index.html"
838
- ];
839
- var OAUTH_SESSION_FILE = /^oauth-session[\w.-]*\.json$/;
840
- var MUGGLE_HOME_DIR_NAME = ".muggle-ai";
841
-
842
- // src/guardrails/shouldRunE2E.ts
843
- var MAX_E2E_BLOCKS = 3;
844
- function applyE2eSkipDeclaration(state, skip) {
845
- if (!skip || CYCLE_SCOPED_SKIP_CODES.includes(skip.code)) return state;
846
- return { ...state, e2eSkipDeclaration: { code: skip.code, detail: skip.detail } };
847
- }
848
- function shouldRunE2E(state) {
849
- const owed = state.unitTestsGreen === true || state.prsHandled.length > 0;
850
- return owed && state.e2eRun !== true && state.e2eSkipped !== true;
851
- }
852
- function applyRecordedRun(state, run) {
853
- let next = state;
854
- if (run.unitTestPassed) {
855
- next = { ...next, unitTestsGreen: true, e2eRun: false };
856
- if (next.e2eSkipCycleScoped === true) next = { ...next, e2eSkipped: false, e2eSkipCycleScoped: false };
857
- }
858
- if (run.e2eRan) {
859
- next = { ...next, e2eRun: true, e2eBlockCount: 0 };
860
- }
861
- if (run.e2eSkipped) {
862
- const isEnvironmentSkipHeld = next.e2eSkipped === true && next.e2eSkipCycleScoped !== true;
863
- next = { ...next, e2eSkipped: true, e2eSkipCycleScoped: !isEnvironmentSkipHeld && run.e2eSkipCycleScoped === true };
864
- }
865
- return next;
866
549
  }
867
- function e2eGateDecision(state, maxBlocks = MAX_E2E_BLOCKS, now = Date.now()) {
868
- const blockCount = state.e2eBlockCount ?? 0;
869
- if (!shouldRunE2E(state) || isE2eDelegationInFlight(state, now)) {
870
- return { action: "none" /* None */, blockCount };
550
+ function repoKeyOfRemoteUrl(remoteUrl) {
551
+ const trimmedUrl = remoteUrl.trim();
552
+ const scpStyle = trimmedUrl.match(/^[^@\s/]+@([^:\s/]+):(?!\/)(.+)$/);
553
+ if (scpStyle) return toRepoKey(scpStyle[1], scpStyle[2]);
554
+ try {
555
+ const parsedUrl = new URL(trimmedUrl);
556
+ return toRepoKey(parsedUrl.hostname, parsedUrl.pathname);
557
+ } catch {
558
+ return void 0;
871
559
  }
872
- if (blockCount >= maxBlocks) return { action: "release" /* Release */, blockCount };
873
- return { action: "block" /* Block */, blockCount: blockCount + 1 };
560
+ }
561
+ function resolveTreeChange(cwd, runGit2 = defaultSkipProbes.runGit) {
562
+ if (!cwd) return void 0;
563
+ const remoteUrl = runGit2(["remote", "get-url", CHANGE_REPO_REMOTE], cwd);
564
+ const repo = remoteUrl ? repoKeyOfRemoteUrl(remoteUrl) : void 0;
565
+ const branch = runGit2(["branch", "--show-current"], cwd)?.trim();
566
+ return repo && branch ? { repo, branch } : void 0;
567
+ }
568
+ function resolveOpenedPrChange(command, prUrl, cwd, runGit2 = defaultSkipProbes.runGit) {
569
+ const repo = repoKeyOfPrUrl(prUrl);
570
+ if (!repo) return void 0;
571
+ const openAt = command.search(PR_OPEN_COMMAND);
572
+ const headFlag = openAt < 0 ? null : command.slice(openAt).match(PR_HEAD_BRANCH_FLAG);
573
+ if (headFlag) return { repo, branch: headFlag[1].slice(headFlag[1].lastIndexOf(":") + 1) };
574
+ if (DIRECTORY_CHANGE_COMMAND.test(command)) return void 0;
575
+ const treeChange = resolveTreeChange(cwd, runGit2);
576
+ return treeChange?.repo === repo ? treeChange : void 0;
577
+ }
578
+ function isSameChange(left, right) {
579
+ return left !== void 0 && right !== void 0 && left.repo === right.repo && left.branch === right.branch;
874
580
  }
875
581
 
876
- // src/hook-budget/constants.ts
877
- var HOOK_CHILD_PROCESS_DEADLINE_MS = 600;
878
-
879
- // src/hook-budget/childProcessBudget.ts
880
- var childProcessDeadlineEpochMs = null;
881
- function enforceHookChildProcessDeadline(gatesStartEpochMs = Date.now()) {
882
- childProcessDeadlineEpochMs = gatesStartEpochMs + HOOK_CHILD_PROCESS_DEADLINE_MS;
582
+ // src/guardrails/skipScope.ts
583
+ function isPrOfSkipChange(state, prUrl) {
584
+ return isSameChange(state.prChanges?.[prUrl], state.e2eSkipVerifiedChange);
883
585
  }
884
- function boundedChildTimeoutMs(ceilingMs) {
885
- if (childProcessDeadlineEpochMs === null) return ceilingMs;
886
- const remainingMs = Math.floor(childProcessDeadlineEpochMs - Date.now());
887
- return remainingMs > 0 ? Math.min(ceilingMs, remainingMs) : null;
586
+ function withCoveredPrs(state, prUrls) {
587
+ const covered = new Set(state.e2eSkipCoveredPrs ?? []);
588
+ const uncovered = prUrls.filter((prUrl) => !covered.has(prUrl));
589
+ if (uncovered.length === 0) return state;
590
+ return { ...state, e2eSkipCoveredPrs: [...covered, ...uncovered] };
591
+ }
592
+ function isPrCoveredBySkip(state, prUrl) {
593
+ return (state.e2eSkipCoveredPrs ?? []).includes(prUrl);
594
+ }
595
+ function applyPrOpenedToSkipScope(state, prUrl, prChange) {
596
+ if (!prChange) return state;
597
+ const recorded = { ...state, prChanges: { ...state.prChanges, [prUrl]: prChange } };
598
+ return isPrOfSkipChange(recorded, prUrl) && recorded.e2eSkipDeclaration ? withCoveredPrs(recorded, [prUrl]) : recorded;
599
+ }
600
+ function applyE2eSkipScope(state, verifiedChange) {
601
+ if (!verifiedChange || !state.e2eSkipDeclaration) return state;
602
+ const scoped = { ...state, e2eSkipVerifiedChange: verifiedChange };
603
+ return withCoveredPrs(
604
+ scoped,
605
+ scoped.prsHandled.filter((prUrl) => isPrOfSkipChange(scoped, prUrl))
606
+ );
888
607
  }
889
608
 
890
609
  // src/pr-walkthrough/constants.ts
@@ -1045,13 +764,35 @@ function applyWatchSkip(state, skipped) {
1045
764
  }
1046
765
  function resolveWatchSlotStatus(evidence, nowMs, staleAfterMs = WATCH_HEARTBEAT_STALE_MS) {
1047
766
  if (evidence.isStopped) return "stopped" /* Stopped */;
1048
- const recordedState = evidence.recordedPrState?.toLowerCase() ?? "";
1049
- if (evidence.isFinalized || TERMINAL_SLOT_PR_STATES.includes(recordedState)) {
1050
- return "terminal" /* Terminal */;
1051
- }
767
+ if (isTerminalSlot(evidence)) return "terminal" /* Terminal */;
1052
768
  const heartbeatAgeMs = evidence.heartbeatMtimeMs === void 0 ? Infinity : nowMs - evidence.heartbeatMtimeMs;
1053
769
  return heartbeatAgeMs <= staleAfterMs ? "live" /* Live */ : "stale" /* Stale */;
1054
770
  }
771
+ function isTerminalSlot(evidence) {
772
+ const recordedState = evidence.recordedPrState?.toLowerCase() ?? "";
773
+ return evidence.isFinalized || TERMINAL_SLOT_PR_STATES.includes(recordedState);
774
+ }
775
+ function ownsOpenWatchSlot(sessionId2, sessionsDirOverride) {
776
+ if (sessionId2 === "") return false;
777
+ const sessionsDir = join(homedir(), ...MUGGLE_DO_SESSIONS_PATH_SEGMENTS);
778
+ let slugs;
779
+ try {
780
+ slugs = readdirSync(sessionsDir);
781
+ } catch {
782
+ return false;
783
+ }
784
+ return slugs.some((slug) => {
785
+ const slotPath = join(sessionsDir, slug);
786
+ if (readJsonRecord(join(slotPath, OWNER_FILE_NAME)).session_id !== sessionId2) return false;
787
+ const slotPr = readSlotPr(slotPath);
788
+ if (typeof slotPr?.url !== "string") return false;
789
+ return !isTerminalSlot({
790
+ isStopped: slug.endsWith(STOPPED_SLOT_SUFFIX),
791
+ isFinalized: existsSync(join(slotPath, RESULT_FILE_NAME)),
792
+ recordedPrState: typeof slotPr.state === "string" ? slotPr.state : void 0
793
+ });
794
+ });
795
+ }
1055
796
  function readHeartbeatMtimeMs(slotPath) {
1056
797
  try {
1057
798
  return statSync(join(slotPath, "watch-heartbeat")).mtimeMs;
@@ -1100,39 +841,202 @@ function resolveOwedWatchPrs(unwatchedUrls, state, scan) {
1100
841
  return providerState === void 0 || providerState === "OPEN" /* Open */;
1101
842
  });
1102
843
  }
1103
- function prsAwaitingStateScan(unwatchedUrls, state, scan) {
1104
- return unwatchedUrls.filter(
1105
- (prUrl) => !isTerminalThisSession(prUrl, state) && !isEndState(scan?.states[prUrl])
1106
- );
844
+ function prsAwaitingStateScan(unwatchedUrls, state, scan) {
845
+ return unwatchedUrls.filter(
846
+ (prUrl) => !isTerminalThisSession(prUrl, state) && !isEndState(scan?.states[prUrl])
847
+ );
848
+ }
849
+ function lookupProviderPrState(prUrl, run = defaultGhRunner) {
850
+ if (!parsePrUrl(prUrl)) return null;
851
+ const reportedState = run(["pr", "view", prUrl, "--json", "state", "-q", ".state"])?.trim();
852
+ return Object.values(ProviderPrState).find(
853
+ (providerState) => providerState === reportedState && providerState !== "UNREACHABLE" /* Unreachable */
854
+ ) ?? "UNREACHABLE" /* Unreachable */;
855
+ }
856
+ function scanProviderPrStates(prUrls, lookup = lookupProviderPrState) {
857
+ const states = {};
858
+ for (const prUrl of prUrls) {
859
+ const providerState = lookup(prUrl);
860
+ if (providerState !== null) states[prUrl] = providerState;
861
+ }
862
+ return { states };
863
+ }
864
+ function watchGateDecision(state, unwatchedPrUrls, maxBlocks = MAX_WATCH_BLOCKS) {
865
+ const blockCount = state.watchBlockCount ?? 0;
866
+ if (state.watchSkipped === true || unwatchedPrUrls.length === 0) {
867
+ return { action: "none" /* None */, blockCount, unwatched: unwatchedPrUrls };
868
+ }
869
+ if (blockCount >= maxBlocks) {
870
+ return { action: "release" /* Release */, blockCount, unwatched: unwatchedPrUrls };
871
+ }
872
+ return {
873
+ action: "block" /* Block */,
874
+ blockCount: blockCount + 1,
875
+ unwatched: unwatchedPrUrls
876
+ };
877
+ }
878
+
879
+ // src/guardrails/buildFollowthrough.ts
880
+ var BUILD_SKIP_MARKER = /^\s*echo\s+["']?MUGGLE_BUILD_SKIP\b/;
881
+ function isBuildSkipMarker(cmd) {
882
+ return BUILD_SKIP_MARKER.test(cmd);
883
+ }
884
+ function applyBuildSkip(state, skipped) {
885
+ if (!skipped || state.buildSkipped === true) return state;
886
+ return { ...state, buildSkipped: true };
887
+ }
888
+ function buildFollowthroughDecision(state, maxBlocks = MAX_BUILD_BLOCKS) {
889
+ const blockCount = state.buildBlockCount ?? 0;
890
+ const owed = state.buildIntentRouted === true && state.buildSkipped !== true && state.prsHandled.length === 0;
891
+ if (!owed) return { action: "none" /* None */, blockCount };
892
+ if (blockCount >= maxBlocks) {
893
+ return { action: "release" /* Release */, blockCount };
894
+ }
895
+ return { action: "block" /* Block */, blockCount: blockCount + 1 };
896
+ }
897
+
898
+ // src/guardrails/shellTool.ts
899
+ function isShellToolCall(input2) {
900
+ return SHELL_TOOL_NAMES.includes(input2.tool_name ?? "");
901
+ }
902
+ var PR_PROSE_CMD = /\bgh\s+pr\s+(comment|create|edit)\b/;
903
+ var GH_API_CMD = /\bgh\s+api\b/;
904
+ var ISSUE_COMMENT_PATH = /\bissues\/comments\/\d+/;
905
+ var PATCH_METHOD = /(?:--method|-X)[=\s]+PATCH\b/;
906
+ var defaultFileReader = (path, cwd) => {
907
+ try {
908
+ const abs = isAbsolute(path) ? path : resolve(cwd ?? process.cwd(), path);
909
+ if (!existsSync(abs)) return null;
910
+ return readFileSync(abs, "utf-8");
911
+ } catch {
912
+ return null;
913
+ }
914
+ };
915
+ function unquote(s) {
916
+ const t = s.trim();
917
+ if (t.startsWith('"') && t.endsWith('"') || t.startsWith("'") && t.endsWith("'")) {
918
+ return t.slice(1, -1);
919
+ }
920
+ return t;
921
+ }
922
+ function isCommentEditCommand(cmd) {
923
+ return GH_API_CMD.test(cmd) && ISSUE_COMMENT_PATH.test(cmd) && PATCH_METHOD.test(cmd);
924
+ }
925
+ function isPrReportPostCommand(cmd) {
926
+ return PR_PROSE_CMD.test(cmd) || isCommentEditCommand(cmd);
927
+ }
928
+ function collectPrPostText(cmd, cwd, read) {
929
+ let text = cmd;
930
+ for (const match of cmd.matchAll(/(?:--body-file|--input)[=\s]+("[^"]+"|'[^']+'|\S+)/g)) {
931
+ const path = unquote(match[1]);
932
+ if (path && path !== "-") {
933
+ const contents = read(path, cwd);
934
+ if (contents) text += "\n" + contents;
935
+ }
936
+ }
937
+ for (const match of cmd.matchAll(/jq\b[^|]*?("[^"]+\.json"|'[^']+\.json'|\S+\.json)/g)) {
938
+ const contents = read(unquote(match[1]), cwd);
939
+ if (contents) text += "\n" + contents;
940
+ }
941
+ return text;
942
+ }
943
+
944
+ // src/guardrails/walkthroughPosted.ts
945
+ var WALKTHROUGH_SKIP_MARKER = /^\s*echo\s+["']?MUGGLE_WALKTHROUGH_SKIP\b/;
946
+ function isWalkthroughSkipMarker(cmd) {
947
+ return WALKTHROUGH_SKIP_MARKER.test(cmd);
948
+ }
949
+ function detectWalkthroughPost(input2, read = defaultFileReader) {
950
+ if (!isShellToolCall(input2)) return false;
951
+ const cmd = input2.tool_input?.command ?? "";
952
+ if (!isPrReportPostCommand(cmd)) return false;
953
+ if (callFailed(input2)) return false;
954
+ return collectPrPostText(cmd, input2.cwd, read).includes(REPORT_SENTINEL);
955
+ }
956
+ function detectWalkthroughPostTargets(input2) {
957
+ return extractPrUrls(`${input2.tool_response?.stdout ?? ""}
958
+ ${input2.tool_response?.output ?? ""}`);
959
+ }
960
+ function applyWalkthroughPosted(state, posted, postedAt, targetPrUrls) {
961
+ if (!posted) return state;
962
+ if (targetPrUrls.length === 0) return { ...state, walkthroughPostedAt: postedAt };
963
+ const postedPrUrls = /* @__PURE__ */ new Set([...state.walkthroughPostedPrUrls ?? [], ...targetPrUrls]);
964
+ return { ...state, walkthroughPostedPrUrls: [...postedPrUrls] };
965
+ }
966
+ function applyWalkthroughSkip(state, skipped) {
967
+ if (!skipped || state.walkthroughSkipped === true) return state;
968
+ return { ...state, walkthroughSkipped: true };
969
+ }
970
+ function runGh(args) {
971
+ const timeoutMs = boundedChildTimeoutMs(GH_LOOKUP_TIMEOUT_MS);
972
+ if (timeoutMs === null) return null;
973
+ try {
974
+ return execFileSync("gh", args, {
975
+ encoding: "utf-8",
976
+ timeout: timeoutMs,
977
+ stdio: ["ignore", "pipe", "ignore"],
978
+ windowsHide: true
979
+ });
980
+ } catch {
981
+ return null;
982
+ }
983
+ }
984
+ var defaultPrWalkthroughLookup = {
985
+ branchPrUrl: () => {
986
+ const url = runGh(["pr", "view", "--json", "url", "-q", ".url"])?.trim();
987
+ return url && url.startsWith("http") ? url : null;
988
+ },
989
+ // Scans the description as well as the comments: muggle-do embeds the
990
+ // walkthrough in the body at PR-creation time, and a comments-only check
991
+ // would report that PR as owing one it already carries.
992
+ prCarriesWalkthrough: (prUrl, acceptsSkip) => {
993
+ const rendered = runGh(["pr", "view", prUrl, "--json", "body,comments"]);
994
+ if (rendered === null) return true;
995
+ return rendered.includes(REPORT_SENTINEL) || acceptsSkip && rendered.includes(WALKTHROUGH_SKIPPED_MARKER);
996
+ }
997
+ };
998
+ function scanForOwedWalkthroughs(state, lookup = defaultPrWalkthroughLookup) {
999
+ const candidates = new Set(state.prsHandled);
1000
+ const branchPrUrl = lookup.branchPrUrl();
1001
+ if (branchPrUrl) candidates.add(branchPrUrl);
1002
+ const owed = [];
1003
+ const verified2 = [];
1004
+ for (const prUrl of candidates) {
1005
+ const acceptsSkip = state.e2eRun !== true || isPrCoveredBySkip(state, prUrl);
1006
+ if (lookup.prCarriesWalkthrough(prUrl, acceptsSkip)) verified2.push(prUrl);
1007
+ else owed.push(prUrl);
1008
+ }
1009
+ return { owed, verified: verified2 };
1010
+ }
1011
+ function isWalkthroughGateArmed(state) {
1012
+ const isSkipUnsettled = state.e2eSkipDeclaration !== void 0 && state.e2eSkipSettledOnPrs !== true;
1013
+ const isOwed = state.e2eRun === true || isSkipUnsettled;
1014
+ return isOwed && state.walkthroughsVerified !== true && state.walkthroughSkipped !== true;
1015
+ }
1016
+ function isWalkthroughScanCurrent(scan, state) {
1017
+ const scanned = new Set(scan.prsHandled);
1018
+ const coversHandledPrs = scanned.size === new Set(state.prsHandled).size && state.prsHandled.every((prUrl) => scanned.has(prUrl));
1019
+ const postedAt = state.walkthroughPostedAt;
1020
+ const followsLastPost = postedAt === void 0 || (scan.startedAt ?? 0) >= postedAt;
1021
+ return coversHandledPrs && followsLastPost;
1107
1022
  }
1108
- function lookupProviderPrState(prUrl, run = defaultGhRunner) {
1109
- if (!parsePrUrl(prUrl)) return null;
1110
- const reportedState = run(["pr", "view", prUrl, "--json", "state", "-q", ".state"])?.trim();
1111
- return Object.values(ProviderPrState).find(
1112
- (providerState) => providerState === reportedState && providerState !== "UNREACHABLE" /* Unreachable */
1113
- ) ?? "UNREACHABLE" /* Unreachable */;
1023
+ function withoutPostedPrs(prUrls, state) {
1024
+ const postedPrUrls = new Set(state.walkthroughPostedPrUrls ?? []);
1025
+ return prUrls.filter((prUrl) => !postedPrUrls.has(prUrl));
1114
1026
  }
1115
- function scanProviderPrStates(prUrls, lookup = lookupProviderPrState) {
1116
- const states = {};
1117
- for (const prUrl of prUrls) {
1118
- const providerState = lookup(prUrl);
1119
- if (providerState !== null) states[prUrl] = providerState;
1120
- }
1121
- return { states };
1027
+ function applyPrOpenedToWalkthroughs(state) {
1028
+ if (state.walkthroughsVerified !== true && state.e2eSkipSettledOnPrs !== true) return state;
1029
+ return { ...state, walkthroughsVerified: false, e2eSkipSettledOnPrs: false };
1122
1030
  }
1123
- function watchGateDecision(state, unwatchedPrUrls, maxBlocks = MAX_WATCH_BLOCKS) {
1124
- const blockCount = state.watchBlockCount ?? 0;
1125
- if (state.watchSkipped === true || unwatchedPrUrls.length === 0) {
1126
- return { action: "none" /* None */, blockCount, unwatched: unwatchedPrUrls };
1031
+ function walkthroughGateDecision(state, owedPrUrls, maxBlocks = MAX_WALKTHROUGH_BLOCKS) {
1032
+ const blockCount = state.walkthroughBlockCount ?? 0;
1033
+ if (!isWalkthroughGateArmed(state) || owedPrUrls.length === 0) {
1034
+ return { action: "none" /* None */, blockCount, owed: owedPrUrls };
1127
1035
  }
1128
1036
  if (blockCount >= maxBlocks) {
1129
- return { action: "release" /* Release */, blockCount, unwatched: unwatchedPrUrls };
1037
+ return { action: "release" /* Release */, blockCount, owed: owedPrUrls };
1130
1038
  }
1131
- return {
1132
- action: "block" /* Block */,
1133
- blockCount: blockCount + 1,
1134
- unwatched: unwatchedPrUrls
1135
- };
1039
+ return { action: "block" /* Block */, blockCount: blockCount + 1, owed: owedPrUrls };
1136
1040
  }
1137
1041
 
1138
1042
  // src/pr-watch/attempts.ts
@@ -1278,318 +1182,527 @@ function watchFollowThroughDecision(state, owedWork) {
1278
1182
  if (owed.length === 0) return { action: "none" /* None */, blockCount, owed };
1279
1183
  return { action: "block" /* Block */, blockCount: blockCount + 1, owed };
1280
1184
  }
1281
- function parseMaxCatchUpRebases(configuredValue) {
1282
- if (configuredValue === UNBOUNDED_PREFERENCE_VALUE) return null;
1283
- const spelled = typeof configuredValue === "number" ? String(configuredValue) : configuredValue;
1284
- return typeof spelled === "string" && POSITIVE_INTEGER.test(spelled) ? Number(spelled) : void 0;
1185
+
1186
+ // src/guardrails/debugPath.ts
1187
+ var DEBUG_SKIP_MARKER = /^\s*echo\s+["']?MUGGLE_DEBUG_SKIP\b/;
1188
+ var serialize = (input2) => `${JSON.stringify(input2.tool_input ?? {})}
1189
+ ${JSON.stringify(input2.tool_response ?? {})}`;
1190
+ function renderedResult(toolResponse) {
1191
+ const rendered = [];
1192
+ const collect = (value) => {
1193
+ if (typeof value === "string") rendered.push(value);
1194
+ else if (Array.isArray(value)) value.forEach(collect);
1195
+ else if (value && typeof value === "object") Object.values(value).forEach(collect);
1196
+ };
1197
+ collect(toolResponse);
1198
+ return rendered.join("\n");
1285
1199
  }
1286
- function resolveWatchPreferences(homeDir = homedir(), pluginRoot = resolvePluginRoot()) {
1287
- const shippedDefaults = readJsonRecord(join(pluginRoot, ...PREFERENCE_DEFAULTS_PATH_SEGMENTS));
1288
- const userPreferences = asRecord(readJsonRecord(join(homeDir, ...USER_PREFERENCES_PATH_SEGMENTS)).preferences);
1289
- const autoRebase = userPreferences[AUTO_REBASE_PREFERENCE_KEY] ?? shippedDefaults[AUTO_REBASE_PREFERENCE_KEY];
1290
- const userCap = parseMaxCatchUpRebases(userPreferences[MAX_CATCH_UP_REBASES_PREFERENCE_KEY]);
1291
- const shippedCap = parseMaxCatchUpRebases(shippedDefaults[MAX_CATCH_UP_REBASES_PREFERENCE_KEY]);
1292
- return {
1293
- autoRebase: typeof autoRebase === "string" ? autoRebase : void 0,
1294
- maxCatchUpRebases: userCap !== void 0 ? userCap : shippedCap ?? null
1200
+ function detectFailedRunId(input2) {
1201
+ if (!MUGGLE_EXECUTION_TOOL.test(input2.tool_name ?? "")) return void 0;
1202
+ const rendered = renderedResult(input2.tool_response);
1203
+ const status = MUGGLE_RUN_STATUS_LINE.exec(rendered)?.[1];
1204
+ if (!status || status.toLowerCase() === MUGGLE_RUN_PASSED_STATUS) return void 0;
1205
+ return MUGGLE_RUN_ID_LINE.exec(rendered)?.[1];
1206
+ }
1207
+ function applyFailedRun(state, runId) {
1208
+ if ((state.failedRuns ?? []).includes(runId)) return state;
1209
+ return { ...state, failedRuns: [...state.failedRuns ?? [], runId] };
1210
+ }
1211
+ function detectDebugEvidenceRunIds(input2, owedRunIds) {
1212
+ const toolName = input2.tool_name ?? "";
1213
+ const isDiagnosisEmit = MUGGLE_EVENT_EMIT_TOOL.test(toolName) && FAILURE_DIAGNOSIS_EVENT.test(input2.tool_input?.eventType ?? "");
1214
+ if (!isDiagnosisEmit && !MUGGLE_FEEDBACK_CREATE_TOOL.test(toolName)) return [];
1215
+ if (callFailed(input2)) return [];
1216
+ const payload = serialize(input2);
1217
+ return owedRunIds.filter((runId) => payload.includes(runId));
1218
+ }
1219
+ function applyDebugEvidence(state, runIds) {
1220
+ const debugged = [...state.debuggedRuns ?? []];
1221
+ for (const runId of runIds) if (!debugged.includes(runId)) debugged.push(runId);
1222
+ if (debugged.length === (state.debuggedRuns ?? []).length) return state;
1223
+ return { ...state, debuggedRuns: debugged };
1224
+ }
1225
+ function isDebugSkipMarker(command) {
1226
+ return DEBUG_SKIP_MARKER.test(command);
1227
+ }
1228
+ function applyDebugSkip(state, command) {
1229
+ if (!isDebugSkipMarker(command)) return state;
1230
+ const namedRuns = (state.failedRuns ?? []).filter((runId) => command.includes(runId));
1231
+ if (namedRuns.length > 0) return applyDebugEvidence(state, namedRuns);
1232
+ if (state.debugSkipped === true) return state;
1233
+ return { ...state, debugSkipped: true };
1234
+ }
1235
+ function undebuggedFailedRuns(state) {
1236
+ const debugged = new Set(state.debuggedRuns ?? []);
1237
+ return (state.failedRuns ?? []).filter((runId) => !debugged.has(runId));
1238
+ }
1239
+ function debugGateDecision(state, maxBlocks = MAX_DEBUG_BLOCKS, now = Date.now()) {
1240
+ const blockCount = state.debugBlockCount ?? 0;
1241
+ const undebugged = undebuggedFailedRuns(state);
1242
+ if (state.debugSkipped === true || undebugged.length === 0 || isE2eDelegationInFlight(state, now)) {
1243
+ return { action: "none" /* None */, blockCount, undebugged };
1244
+ }
1245
+ if (blockCount >= maxBlocks) {
1246
+ return { action: "release" /* Release */, blockCount, undebugged };
1247
+ }
1248
+ return { action: "block" /* Block */, blockCount: blockCount + 1, undebugged };
1249
+ }
1250
+ function resolvePluginRoot(env = process.env) {
1251
+ return env.CLAUDE_PLUGIN_ROOT || env.CURSOR_PLUGIN_ROOT || dirname(dirname(fileURLToPath(import.meta.url)));
1252
+ }
1253
+
1254
+ // src/guardrails/mandatoryStages.ts
1255
+ var FRONTMATTER = /^---\r?\n([\s\S]*?)\r?\n---/;
1256
+ var SEQUENCE_ENTRY = /^\s*-\s*(.+?)\s*$/;
1257
+ var FLOW_LIST = /^\s*\[(.*)\]\s*$/;
1258
+ var STAGE_SKIP_MARKER = /^\s*echo\s+["']?MUGGLE_STAGE_SKIP\b/;
1259
+ var SKILLS_DIR_NAME = "skills";
1260
+ var SKILLS_PATH_SEGMENT = `/${SKILLS_DIR_NAME}/`;
1261
+ var SINGLE_PATH_SEGMENT = /^[A-Za-z0-9._-]+$/;
1262
+ var SHELL_COMMAND_SEPARATOR = /[;&|\n]/;
1263
+ var SHELL_ASSIGNMENT = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/s;
1264
+ var SHELL_VARIABLE_REFERENCE = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g;
1265
+ var WINDOWS_ABSOLUTE_PATH = /^[A-Za-z]:[\\/]/;
1266
+ var MARKDOWN_FILE = /\.md$/i;
1267
+ var unquote2 = (raw) => raw.trim().replace(/^["']|["']$/g, "").trim();
1268
+ function parseDeclaredStages(skillMarkdown) {
1269
+ const frontmatter = FRONTMATTER.exec(skillMarkdown)?.[1];
1270
+ if (!frontmatter) return [];
1271
+ const lines = frontmatter.split(/\r?\n/);
1272
+ const keyIndex = lines.findIndex(
1273
+ (line) => line.startsWith(`${MANDATORY_STAGES_FRONTMATTER_KEY}:`)
1274
+ );
1275
+ if (keyIndex < 0) return [];
1276
+ const inlineValue = lines[keyIndex].slice(MANDATORY_STAGES_FRONTMATTER_KEY.length + 1).trim();
1277
+ const flowEntries = FLOW_LIST.exec(inlineValue)?.[1];
1278
+ if (flowEntries !== void 0) {
1279
+ return flowEntries.split(",").map(unquote2).filter((entry) => entry.length > 0);
1280
+ }
1281
+ const declared = [];
1282
+ for (const line of lines.slice(keyIndex + 1)) {
1283
+ const entry = SEQUENCE_ENTRY.exec(line);
1284
+ if (!entry) break;
1285
+ declared.push(unquote2(entry[1]));
1286
+ }
1287
+ return declared;
1288
+ }
1289
+ function normalizeStagePath(filePath) {
1290
+ return filePath.replaceAll("\\", "/").toLowerCase();
1291
+ }
1292
+ function stageLabel(normalizedStagePath) {
1293
+ const insideSkills = normalizedStagePath.lastIndexOf(SKILLS_PATH_SEGMENT);
1294
+ if (insideSkills < 0) return normalizedStagePath;
1295
+ return normalizedStagePath.slice(insideSkills + SKILLS_PATH_SEGMENT.length);
1296
+ }
1297
+ function resolvePluginSkillsRoot() {
1298
+ return join(resolvePluginRoot(), SKILLS_DIR_NAME);
1299
+ }
1300
+ function resolveSkillNameFromToolInput(toolInput) {
1301
+ if (!toolInput) return void 0;
1302
+ const indexed = toolInput;
1303
+ for (const inputKey of SKILL_NAME_INPUT_KEYS) {
1304
+ const value = indexed[inputKey];
1305
+ if (typeof value !== "string" || value.trim().length === 0) continue;
1306
+ const skillName = value.trim().split(":").pop()?.replace(/^\//, "") ?? "";
1307
+ return SINGLE_PATH_SEGMENT.test(skillName) ? skillName : void 0;
1308
+ }
1309
+ return void 0;
1310
+ }
1311
+ function resolveSkillStagePaths(skillName, skillsRootDir) {
1312
+ const skillDir = join(skillsRootDir, skillName);
1313
+ const skillFile = join(skillDir, "SKILL.md");
1314
+ if (!existsSync(skillFile)) return [];
1315
+ const normalizedRoot = normalizeStagePath(skillsRootDir);
1316
+ const staysInsideSkillsTree = (candidate) => normalizeStagePath(candidate).startsWith(`${normalizedRoot}/`);
1317
+ const resolved = [];
1318
+ for (const declared of parseDeclaredStages(readFileSync(skillFile, "utf-8"))) {
1319
+ if (isAbsolute(declared)) continue;
1320
+ const stagePath = [resolve(skillDir, declared), resolve(skillsRootDir, declared)].find(
1321
+ (candidate) => staysInsideSkillsTree(candidate) && existsSync(candidate)
1322
+ );
1323
+ if (!stagePath) continue;
1324
+ const normalized = normalizeStagePath(stagePath);
1325
+ if (!resolved.includes(normalized)) resolved.push(normalized);
1326
+ }
1327
+ return resolved;
1328
+ }
1329
+ function applySkillInvocation(state, skillName, stagePaths) {
1330
+ const merged = [...state.mandatoryStages ?? []];
1331
+ for (const stagePath of stagePaths) if (!merged.includes(stagePath)) merged.push(stagePath);
1332
+ if (state.lastInvokedSkillName === skillName && merged.length === (state.mandatoryStages?.length ?? 0)) {
1333
+ return state;
1334
+ }
1335
+ return { ...state, lastInvokedSkillName: skillName, mandatoryStages: merged };
1336
+ }
1337
+ function isSkillTreeMarkdown(filePath) {
1338
+ const normalized = normalizeStagePath(filePath);
1339
+ return normalized.includes(SKILLS_PATH_SEGMENT) && MARKDOWN_FILE.test(normalized);
1340
+ }
1341
+ function applyStageRead(state, filePath) {
1342
+ const stagePath = normalizeStagePath(filePath);
1343
+ if ((state.stagesRead ?? []).includes(stagePath)) return state;
1344
+ return { ...state, stagesRead: [...state.stagesRead ?? [], stagePath] };
1345
+ }
1346
+ var SHELL_ESCAPABLE_UNQUOTED = /* @__PURE__ */ new Set([" ", " ", "'", '"', "\\", "$", ";", "&", "|", "\n"]);
1347
+ var SHELL_ESCAPABLE_DOUBLE_QUOTED = /* @__PURE__ */ new Set(['"', "\\", "$", "`"]);
1348
+ function splitShellCommands(command) {
1349
+ const commands = [];
1350
+ let words = [];
1351
+ let word = "";
1352
+ let wordStarted = false;
1353
+ let quote = null;
1354
+ const endWord = () => {
1355
+ if (wordStarted) words.push(word);
1356
+ word = "";
1357
+ wordStarted = false;
1358
+ };
1359
+ const endCommand = () => {
1360
+ endWord();
1361
+ if (words.length > 0) commands.push(words);
1362
+ words = [];
1295
1363
  };
1364
+ for (let index = 0; index < command.length; index += 1) {
1365
+ const character = command[index];
1366
+ const nextCharacter = command[index + 1];
1367
+ if (quote !== null) {
1368
+ if (character === quote) {
1369
+ quote = null;
1370
+ } else if (character === "\\" && quote === '"' && SHELL_ESCAPABLE_DOUBLE_QUOTED.has(nextCharacter)) {
1371
+ word += nextCharacter;
1372
+ index += 1;
1373
+ } else {
1374
+ word += character;
1375
+ }
1376
+ continue;
1377
+ }
1378
+ if (character === "'" || character === '"') {
1379
+ quote = character;
1380
+ wordStarted = true;
1381
+ } else if (character === "\\" && SHELL_ESCAPABLE_UNQUOTED.has(nextCharacter)) {
1382
+ word += nextCharacter;
1383
+ wordStarted = true;
1384
+ index += 1;
1385
+ } else if (SHELL_COMMAND_SEPARATOR.test(character)) {
1386
+ endCommand();
1387
+ } else if (/\s/.test(character)) {
1388
+ endWord();
1389
+ } else {
1390
+ word += character;
1391
+ wordStarted = true;
1392
+ }
1393
+ }
1394
+ endCommand();
1395
+ return commands;
1296
1396
  }
1297
-
1298
- // src/guardrails/buildFollowthrough.ts
1299
- var BUILD_SKIP_MARKER = /^\s*echo\s+["']?MUGGLE_BUILD_SKIP\b/;
1300
- function isBuildSkipMarker(cmd) {
1301
- return BUILD_SKIP_MARKER.test(cmd);
1397
+ function expandShellWord(word, variables) {
1398
+ const withHome = word === "~" || word.startsWith("~/") ? `${homedir()}${word.slice(1)}` : word;
1399
+ return withHome.replace(
1400
+ SHELL_VARIABLE_REFERENCE,
1401
+ (_reference, bracedName, bareName) => variables[bracedName ?? bareName ?? ""] ?? ""
1402
+ );
1302
1403
  }
1303
- function applyBuildSkip(state, skipped) {
1304
- if (!skipped || state.buildSkipped === true) return state;
1305
- return { ...state, buildSkipped: true };
1404
+ function resolveShellPath(path, workingDirectory) {
1405
+ return isAbsolute(path) || WINDOWS_ABSOLUTE_PATH.test(path) ? path : resolve(workingDirectory, path);
1306
1406
  }
1307
- function buildFollowthroughDecision(state, maxBlocks = MAX_BUILD_BLOCKS) {
1308
- const blockCount = state.buildBlockCount ?? 0;
1309
- const owed = state.buildIntentRouted === true && state.buildSkipped !== true && state.prsHandled.length === 0;
1310
- if (!owed) return { action: "none" /* None */, blockCount };
1311
- if (blockCount >= maxBlocks) {
1312
- return { action: "release" /* Release */, blockCount };
1407
+ function detectShellStageReads(command, cwd, env = process.env) {
1408
+ const variables = { ...env };
1409
+ let workingDirectory = cwd ?? process.cwd();
1410
+ const readPaths = [];
1411
+ for (const words of splitShellCommands(command)) {
1412
+ let programIndex = 0;
1413
+ const assignments = [];
1414
+ for (; programIndex < words.length; programIndex += 1) {
1415
+ const assignment = SHELL_ASSIGNMENT.exec(words[programIndex]);
1416
+ if (!assignment) break;
1417
+ assignments.push([assignment[1], expandShellWord(assignment[2], variables)]);
1418
+ }
1419
+ const programWord = words[programIndex];
1420
+ if (programWord === void 0 || programWord === "export") {
1421
+ for (const word of words.slice(programIndex + 1)) {
1422
+ const exported = SHELL_ASSIGNMENT.exec(word);
1423
+ if (exported) assignments.push([exported[1], expandShellWord(exported[2], variables)]);
1424
+ }
1425
+ for (const [name, value] of assignments) variables[name] = value;
1426
+ continue;
1427
+ }
1428
+ const program = basename(programWord.replaceAll("\\", "/")).toLowerCase().replace(/\.exe$/, "");
1429
+ const argumentWords = words.slice(programIndex + 1).map((word) => expandShellWord(word, variables));
1430
+ if (program === "cd") {
1431
+ const target = argumentWords.find((word) => !word.startsWith("-"));
1432
+ if (target) workingDirectory = resolveShellPath(target, workingDirectory);
1433
+ continue;
1434
+ }
1435
+ if (!FILE_PRINTING_PROGRAMS.includes(program)) continue;
1436
+ for (const argument of argumentWords) {
1437
+ if (argument.startsWith("-") || !MARKDOWN_FILE.test(argument)) continue;
1438
+ const readPath = normalizeStagePath(resolveShellPath(argument, workingDirectory));
1439
+ if (isSkillTreeMarkdown(readPath) && !readPaths.includes(readPath)) readPaths.push(readPath);
1440
+ }
1313
1441
  }
1314
- return { action: "block" /* Block */, blockCount: blockCount + 1 };
1442
+ return readPaths;
1315
1443
  }
1316
- var PR_PROSE_CMD = /\bgh\s+pr\s+(comment|create|edit)\b/;
1317
- var GH_API_CMD = /\bgh\s+api\b/;
1318
- var ISSUE_COMMENT_PATH = /\bissues\/comments\/\d+/;
1319
- var PATCH_METHOD = /(?:--method|-X)[=\s]+PATCH\b/;
1320
- var defaultFileReader = (path, cwd) => {
1321
- try {
1322
- const abs = isAbsolute(path) ? path : resolve(cwd ?? process.cwd(), path);
1323
- if (!existsSync(abs)) return null;
1324
- return readFileSync(abs, "utf-8");
1325
- } catch {
1326
- return null;
1327
- }
1328
- };
1329
- function unquote2(s) {
1330
- const t = s.trim();
1331
- if (t.startsWith('"') && t.endsWith('"') || t.startsWith("'") && t.endsWith("'")) {
1332
- return t.slice(1, -1);
1333
- }
1334
- return t;
1444
+ function unreadMandatoryStages(state) {
1445
+ const read = new Set(state.stagesRead ?? []);
1446
+ return (state.mandatoryStages ?? []).filter((stagePath) => !read.has(stagePath));
1335
1447
  }
1336
- function isCommentEditCommand(cmd) {
1337
- return GH_API_CMD.test(cmd) && ISSUE_COMMENT_PATH.test(cmd) && PATCH_METHOD.test(cmd);
1448
+ function isStageSkipMarker(command) {
1449
+ return STAGE_SKIP_MARKER.test(command);
1338
1450
  }
1339
- function isPrReportPostCommand(cmd) {
1340
- return PR_PROSE_CMD.test(cmd) || isCommentEditCommand(cmd);
1451
+ function applyStageSkip(state, skipped) {
1452
+ if (!skipped || state.stageSkipped === true) return state;
1453
+ return { ...state, stageSkipped: true };
1341
1454
  }
1342
- function collectPrPostText(cmd, cwd, read) {
1343
- let text = cmd;
1344
- for (const match of cmd.matchAll(/(?:--body-file|--input)[=\s]+("[^"]+"|'[^']+'|\S+)/g)) {
1345
- const path = unquote2(match[1]);
1346
- if (path && path !== "-") {
1347
- const contents = read(path, cwd);
1348
- if (contents) text += "\n" + contents;
1349
- }
1455
+ function stageGateDecision(state, unreadStagePaths, maxBlocks = MAX_STAGE_BLOCKS) {
1456
+ const blockCount = state.stageBlockCount ?? 0;
1457
+ if (state.stageSkipped === true || unreadStagePaths.length === 0) {
1458
+ return { action: "none" /* None */, blockCount, unread: unreadStagePaths };
1350
1459
  }
1351
- for (const match of cmd.matchAll(/jq\b[^|]*?("[^"]+\.json"|'[^']+\.json'|\S+\.json)/g)) {
1352
- const contents = read(unquote2(match[1]), cwd);
1353
- if (contents) text += "\n" + contents;
1460
+ if (blockCount >= maxBlocks) {
1461
+ return { action: "release" /* Release */, blockCount, unread: unreadStagePaths };
1354
1462
  }
1355
- return text;
1463
+ return { action: "block" /* Block */, blockCount: blockCount + 1, unread: unreadStagePaths };
1356
1464
  }
1357
1465
 
1358
- // src/guardrails/walkthroughPosted.ts
1359
- var WALKTHROUGH_SKIP_MARKER = /^\s*echo\s+["']?MUGGLE_WALKTHROUGH_SKIP\b/;
1360
- function isWalkthroughSkipMarker(cmd) {
1361
- return WALKTHROUGH_SKIP_MARKER.test(cmd);
1362
- }
1363
- function detectWalkthroughPost(input2, read = defaultFileReader) {
1364
- if (!isShellToolCall(input2)) return false;
1365
- const cmd = input2.tool_input?.command ?? "";
1366
- if (!isPrReportPostCommand(cmd)) return false;
1367
- if (callFailed(input2)) return false;
1368
- return collectPrPostText(cmd, input2.cwd, read).includes(REPORT_SENTINEL);
1369
- }
1370
- function detectWalkthroughPostTargets(input2) {
1371
- return extractPrUrls(`${input2.tool_response?.stdout ?? ""}
1372
- ${input2.tool_response?.output ?? ""}`);
1466
+ // src/guardrails/stateCommit.ts
1467
+ function applyToolOutcome(state, outcome) {
1468
+ const declared = applyE2eSkipDeclaration(applyRecordedRun(state, outcome.run), outcome.acceptedSkip);
1469
+ const recorded = applyE2eSkipScope(declared, outcome.skipVerifiedChange);
1470
+ const withWatchSkip = applyWatchSkip(recorded, outcome.isWatchSkip);
1471
+ const withBuildSkip = applyBuildSkip(withWatchSkip, outcome.isBuildSkip);
1472
+ const withWalkthroughPost = applyWalkthroughPosted(
1473
+ withBuildSkip,
1474
+ outcome.isWalkthroughPosted,
1475
+ outcome.walkthroughPostedAt,
1476
+ outcome.walkthroughPostTargets
1477
+ );
1478
+ const withWalkthroughSkip = applyWalkthroughSkip(withWalkthroughPost, outcome.isWalkthroughSkip);
1479
+ return outcome.failedRunId ? applyFailedRun(withWalkthroughSkip, outcome.failedRunId) : withWalkthroughSkip;
1373
1480
  }
1374
- function applyWalkthroughPosted(state, posted, postedAt, targetPrUrls) {
1375
- if (!posted) return state;
1376
- if (targetPrUrls.length === 0) return { ...state, walkthroughPostedAt: postedAt };
1377
- const postedPrUrls = /* @__PURE__ */ new Set([...state.walkthroughPostedPrUrls ?? [], ...targetPrUrls]);
1378
- return { ...state, walkthroughPostedPrUrls: [...postedPrUrls] };
1481
+ function applyFields(state, fields) {
1482
+ const isUnchanged = Object.entries(fields).every(
1483
+ ([field, value]) => state[field] === value
1484
+ );
1485
+ return isUnchanged ? state : { ...state, ...fields };
1486
+ }
1487
+ function applyStateMutation(state, mutation) {
1488
+ switch (mutation.kind) {
1489
+ case "tool-outcome" /* ToolOutcome */:
1490
+ return applyToolOutcome(state, mutation);
1491
+ case "skill-invocation" /* SkillInvocation */:
1492
+ return applyRecordedRun(applySkillInvocation(state, mutation.skillName, mutation.stagePaths), mutation.emittedRun);
1493
+ case "pr-opened" /* PrOpened */:
1494
+ return applyPrOpenedToSkipScope(applyPrOpenedToWalkthroughs(state), mutation.prUrl, mutation.prChange);
1495
+ case "e2e-delegation" /* E2eDelegation */:
1496
+ return applyE2eDelegation(state, mutation.delegation);
1497
+ case "watch-follow-through" /* WatchFollowThrough */:
1498
+ return { ...applyWatchHolds(state, mutation.heldPrNumbers), watchFollowThroughBlockCount: mutation.blockCount };
1499
+ case "fields" /* Fields */:
1500
+ return applyFields(state, mutation.fields);
1501
+ }
1502
+ }
1503
+ function commitStateMutation(sessionId2, mutation) {
1504
+ const committed = commitState(sessionId2, (state) => applyStateMutation(state, mutation));
1505
+ if (committed) return committed;
1506
+ deferStateMutation(sessionId2, mutation);
1507
+ startBackgroundJob("commit-deferred-state" /* CommitDeferredState */, [sessionId2]);
1508
+ return applyStateMutation(readState(sessionId2), mutation);
1509
+ }
1510
+ function commitDeferredSessionState(sessionId2) {
1511
+ commitDeferredStateMutations(sessionId2, applyStateMutation);
1379
1512
  }
1380
- function applyWalkthroughSkip(state, skipped) {
1381
- if (!skipped || state.walkthroughSkipped === true) return state;
1382
- return { ...state, walkthroughSkipped: true };
1513
+
1514
+ // src/guardrails/prOpened.ts
1515
+ var CREATE_CMD = /\bgh\s+pr\s+(create|ready)\b/;
1516
+ var MR_CREATE_CMD = /\bglab\s+mr\s+create\b|\bglab\s+mr\s+update\b.*--ready\b/;
1517
+ function detectPrOpened(input2) {
1518
+ if (!isShellToolCall(input2)) return null;
1519
+ const cmd = input2.tool_input?.command ?? "";
1520
+ if (!CREATE_CMD.test(cmd) && !MR_CREATE_CMD.test(cmd)) return null;
1521
+ const out = `${input2.tool_response?.stdout ?? ""}
1522
+ ${input2.tool_response?.output ?? ""}`;
1523
+ const m = out.match(GITHUB_PR_URL) ?? out.match(GITLAB_MR_URL);
1524
+ return m ? m[0] : null;
1383
1525
  }
1384
- var readTextFile = (path) => {
1385
- try {
1386
- return readFileSync(path, "utf8");
1387
- } catch {
1388
- return null;
1389
- }
1390
- };
1391
- var listFiles = (dir) => {
1392
- try {
1393
- return readdirSync(dir);
1394
- } catch {
1395
- return [];
1396
- }
1397
- };
1398
- var runGit = (args, cwd) => {
1399
- const timeoutMs = boundedChildTimeoutMs(GIT_PROBE_TIMEOUT_MS);
1400
- if (timeoutMs === null) return null;
1401
- try {
1402
- return execFileSync("git", args, {
1403
- cwd,
1404
- encoding: "utf8",
1405
- timeout: timeoutMs,
1406
- stdio: ["ignore", "pipe", "ignore"],
1407
- windowsHide: true
1408
- });
1409
- } catch {
1410
- return null;
1411
- }
1412
- };
1413
- var hostAndPort = (url) => {
1414
- const withScheme = /^https?:\/\//i.test(url) ? url : `http://${url}`;
1415
- try {
1416
- const parsed = new URL(withScheme);
1417
- const port = parsed.port ? Number(parsed.port) : parsed.protocol === "https:" ? 443 : 80;
1418
- return { host: parsed.hostname, port };
1419
- } catch {
1420
- return null;
1421
- }
1422
- };
1423
- var isReachable = (url) => {
1424
- const target = hostAndPort(url);
1425
- if (!target) return false;
1426
- const spawnTimeoutMs = boundedChildTimeoutMs(DEV_SERVER_PROBE_TIMEOUT_MS * 2);
1427
- if (spawnTimeoutMs === null) return false;
1428
- const socketTimeoutMs = Math.min(DEV_SERVER_PROBE_TIMEOUT_MS, Math.floor(spawnTimeoutMs / 2));
1429
- const script = `const net=require('net');const s=net.connect(${target.port},${JSON.stringify(target.host)});s.setTimeout(${socketTimeoutMs});s.on('connect',()=>{s.destroy();process.exit(0)});s.on('timeout',()=>{s.destroy();process.exit(1)});s.on('error',()=>process.exit(1));`;
1430
- try {
1431
- execFileSync(process.execPath, ["-e", script], {
1432
- timeout: spawnTimeoutMs,
1433
- stdio: "ignore",
1434
- windowsHide: true
1435
- });
1436
- return true;
1437
- } catch {
1438
- return false;
1439
- }
1440
- };
1441
- var defaultSkipProbes = {
1442
- readTextFile,
1443
- listFiles,
1444
- runGit,
1445
- isReachable
1446
- };
1447
1526
 
1448
- // src/guardrails/changeIdentity.ts
1449
- function toRepoKey(host2, path) {
1450
- const repoPath = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
1451
- return host2 && repoPath ? `${host2}/${repoPath}`.toLowerCase() : void 0;
1527
+ // src/guardrails/prTerminal.ts
1528
+ function terminalProvenance(input2) {
1529
+ const command = input2.tool_input?.command;
1530
+ if (command === void 0) return { acceptsForgeLine: true, acceptsMonitorLine: true };
1531
+ return {
1532
+ acceptsForgeLine: FORGE_TERMINAL_CMD.test(command),
1533
+ acceptsMonitorLine: WATCH_TERMINAL_CMD.test(command)
1534
+ };
1452
1535
  }
1453
- function repoKeyOfPrUrl(prUrl) {
1454
- const pullsAt = prUrl.match(GITHUB_PR_URL) ? prUrl.indexOf("/pull/") : prUrl.match(GITLAB_MR_URL) ? prUrl.indexOf("/-/merge_requests/") : -1;
1455
- if (pullsAt < 0) return void 0;
1456
- try {
1457
- const repoUrl = new URL(prUrl.slice(0, pullsAt));
1458
- return toRepoKey(repoUrl.hostname, repoUrl.pathname);
1459
- } catch {
1460
- return void 0;
1536
+ function detectPrTerminal(input2) {
1537
+ if (!isShellToolCall(input2) && input2.tool_name !== "Monitor") return null;
1538
+ const response = input2.tool_response;
1539
+ const provenance = terminalProvenance(input2);
1540
+ const haystack = [response?.stdout, response?.stderr, response?.output, response?.content].filter((part) => typeof part === "string").join("\n");
1541
+ const mergedMatch = provenance.acceptsForgeLine ? haystack.match(GH_PR_MERGED_LINE) : null;
1542
+ if (mergedMatch) {
1543
+ return { prNumber: Number(mergedMatch[1]), verdict: "merged" /* Merged */ };
1461
1544
  }
1462
- }
1463
- function repoKeyOfRemoteUrl(remoteUrl) {
1464
- const trimmedUrl = remoteUrl.trim();
1465
- const scpStyle = trimmedUrl.match(/^[^@\s/]+@([^:\s/]+):(?!\/)(.+)$/);
1466
- if (scpStyle) return toRepoKey(scpStyle[1], scpStyle[2]);
1467
- try {
1468
- const parsedUrl = new URL(trimmedUrl);
1469
- return toRepoKey(parsedUrl.hostname, parsedUrl.pathname);
1470
- } catch {
1471
- return void 0;
1545
+ const closedMatch = provenance.acceptsForgeLine ? haystack.match(GH_PR_CLOSED_LINE) : null;
1546
+ if (closedMatch) {
1547
+ return { prNumber: Number(closedMatch[1]), verdict: "closed" /* Closed */ };
1548
+ }
1549
+ const monitorMatch = provenance.acceptsMonitorLine ? haystack.match(PR_MONITOR_TERMINAL_LINE) : null;
1550
+ if (monitorMatch) {
1551
+ return {
1552
+ prNumber: Number(monitorMatch[1]),
1553
+ verdict: monitorMatch[2] === "MERGED" ? "merged" /* Merged */ : "closed" /* Closed */
1554
+ };
1472
1555
  }
1556
+ return null;
1473
1557
  }
1474
- function resolveTreeChange(cwd, runGit2 = defaultSkipProbes.runGit) {
1475
- if (!cwd) return void 0;
1476
- const remoteUrl = runGit2(["remote", "get-url", CHANGE_REPO_REMOTE], cwd);
1477
- const repo = remoteUrl ? repoKeyOfRemoteUrl(remoteUrl) : void 0;
1478
- const branch = runGit2(["branch", "--show-current"], cwd)?.trim();
1479
- return repo && branch ? { repo, branch } : void 0;
1480
- }
1481
- function resolveOpenedPrChange(command, prUrl, cwd, runGit2 = defaultSkipProbes.runGit) {
1482
- const repo = repoKeyOfPrUrl(prUrl);
1483
- if (!repo) return void 0;
1484
- const openAt = command.search(PR_OPEN_COMMAND);
1485
- const headFlag = openAt < 0 ? null : command.slice(openAt).match(PR_HEAD_BRANCH_FLAG);
1486
- if (headFlag) return { repo, branch: headFlag[1].slice(headFlag[1].lastIndexOf(":") + 1) };
1487
- if (DIRECTORY_CHANGE_COMMAND.test(command)) return void 0;
1488
- const treeChange = resolveTreeChange(cwd, runGit2);
1489
- return treeChange?.repo === repo ? treeChange : void 0;
1558
+ function detectPrReopened(input2) {
1559
+ if (!isShellToolCall(input2)) return null;
1560
+ if (!terminalProvenance(input2).acceptsForgeLine) return null;
1561
+ const response = input2.tool_response;
1562
+ const haystack = [response?.stdout, response?.stderr, response?.output, response?.content].filter((part) => typeof part === "string").join("\n");
1563
+ const reopenedMatch = haystack.match(GH_PR_REOPENED_LINE);
1564
+ return reopenedMatch ? Number(reopenedMatch[1]) : null;
1490
1565
  }
1491
- function isSameChange(left, right) {
1492
- return left !== void 0 && right !== void 0 && left.repo === right.repo && left.branch === right.branch;
1566
+ function applyPrReopened(state, prNumber) {
1567
+ const pending = state.terminalPending ?? [];
1568
+ const handled = state.terminalHandled ?? [];
1569
+ if (!pending.includes(prNumber) && !handled.includes(prNumber)) return state;
1570
+ return {
1571
+ ...state,
1572
+ terminalPending: pending.filter((number) => number !== prNumber),
1573
+ terminalHandled: handled.filter((number) => number !== prNumber)
1574
+ };
1493
1575
  }
1494
-
1495
- // src/guardrails/skipScope.ts
1496
- function isPrOfSkipChange(state, prUrl) {
1497
- return isSameChange(state.prChanges?.[prUrl], state.e2eSkipVerifiedChange);
1576
+ function applyPrTerminalDetected(state, prNumber) {
1577
+ const pending = state.terminalPending ?? [];
1578
+ const handled = state.terminalHandled ?? [];
1579
+ if (pending.includes(prNumber) || handled.includes(prNumber)) return state;
1580
+ return { ...state, terminalPending: [...pending, prNumber] };
1498
1581
  }
1499
- function withCoveredPrs(state, prUrls) {
1500
- const covered = new Set(state.e2eSkipCoveredPrs ?? []);
1501
- const uncovered = prUrls.filter((prUrl) => !covered.has(prUrl));
1502
- if (uncovered.length === 0) return state;
1503
- return { ...state, e2eSkipCoveredPrs: [...covered, ...uncovered] };
1582
+ function applyNextOptionsOffered(state) {
1583
+ const pending = state.terminalPending ?? [];
1584
+ if (pending.length === 0) return state;
1585
+ return {
1586
+ ...state,
1587
+ terminalPending: [],
1588
+ terminalHandled: [...state.terminalHandled ?? [], ...pending],
1589
+ terminalBlockCount: 0
1590
+ };
1504
1591
  }
1505
- function isPrCoveredBySkip(state, prUrl) {
1506
- return (state.e2eSkipCoveredPrs ?? []).includes(prUrl);
1592
+ function closingMessageAsksUser(closingMessage) {
1593
+ return typeof closingMessage === "string" && closingMessage.includes("?");
1507
1594
  }
1508
- function applyPrOpenedToSkipScope(state, prUrl, prChange) {
1509
- if (!prChange) return state;
1510
- const recorded = { ...state, prChanges: { ...state.prChanges, [prUrl]: prChange } };
1511
- return isPrOfSkipChange(recorded, prUrl) && recorded.e2eSkipDeclaration ? withCoveredPrs(recorded, [prUrl]) : recorded;
1595
+ function prTerminalGateDecision(state, maxBlocks = MAX_PR_TERMINAL_BLOCKS) {
1596
+ const blockCount = state.terminalBlockCount ?? 0;
1597
+ if ((state.terminalPending ?? []).length === 0) {
1598
+ return { action: "none" /* None */, blockCount };
1599
+ }
1600
+ if (blockCount >= maxBlocks) {
1601
+ return { action: "release" /* Release */, blockCount };
1602
+ }
1603
+ return { action: "block" /* Block */, blockCount: blockCount + 1 };
1512
1604
  }
1513
- function applyE2eSkipScope(state, verifiedChange) {
1514
- if (!verifiedChange || !state.e2eSkipDeclaration) return state;
1515
- const scoped = { ...state, e2eSkipVerifiedChange: verifiedChange };
1516
- return withCoveredPrs(
1517
- scoped,
1518
- scoped.prsHandled.filter((prUrl) => isPrOfSkipChange(scoped, prUrl))
1605
+
1606
+ // src/guardrails/capabilityClaim.ts
1607
+ var SENTENCE = /[^.!?\n]+/g;
1608
+ var IMPOSSIBILITY = /\b(?:can(?:'|’)?t|cannot|can not|could ?n(?:'|’)?t|unable to|no way to|not able to|impossible|infeasible|untestable|unverifiable|not testable|blocked from|no (?:local )?(?:mail|email|smtp) path)\b/i;
1609
+ var MUGGLE_CLEARS = /\b(?:magic[- ]?link|sign[- ]?in link|login link|email link|one[- ]time (?:code|password)|otp|verification (?:code|link|email|mail)|email verification|confirmation (?:code|link|email|mail)|2fa|two[- ]factor|password reset|reset link|inbox|mailbox|mailhog|mailpit|mailtrap|mailcatcher|smtp|transactional email|captcha|recaptcha|hcaptcha|log ?in|logged[- ]?in|sign ?in|signed[- ]in|authenticate|credential|sms|text message|texted code|authenticator app|google authenticator|authy|totp)/i;
1610
+ var TESTING_CONTEXT = /\b(?:e2e|end[- ]to[- ]end|test(?:s|ed|ing|able)?|verif(?:y|ied|ication)|validat(?:e|ed|ion)|automat(?:e|ed|ion)|coverage|covered|exercis(?:e|ed)|reproduc(?:e|ed)|replay|scripts?|scripted|muggle|playwright|cypress|selenium)\b/i;
1611
+ var GENUINELY_UNSUPPORTED = /\b(?:phone call|voice call|oauth|social (?:login|sign[- ]?in)|sign in with (?:google|github|apple|facebook)|no (?:phone )?number (?:is )?provisioned|no provisioned (?:phone )?number)\b/i;
1612
+ function detectFalseCapabilityClaim(text) {
1613
+ const sentences = (text ?? "").match(SENTENCE) ?? [];
1614
+ return sentences.some(
1615
+ (sentence) => IMPOSSIBILITY.test(sentence) && MUGGLE_CLEARS.test(sentence) && TESTING_CONTEXT.test(sentence) && !GENUINELY_UNSUPPORTED.test(sentence)
1519
1616
  );
1520
1617
  }
1521
-
1522
- // src/guardrails/walkthroughOwed.ts
1523
- function runGh(args) {
1524
- const timeoutMs = boundedChildTimeoutMs(GH_LOOKUP_TIMEOUT_MS);
1525
- if (timeoutMs === null) return null;
1526
- try {
1527
- return execFileSync("gh", args, {
1528
- encoding: "utf-8",
1529
- timeout: timeoutMs,
1530
- stdio: ["ignore", "pipe", "ignore"],
1531
- windowsHide: true
1532
- });
1533
- } catch {
1534
- return null;
1618
+ function lastAssistantText(transcriptJsonl) {
1619
+ const lines = (transcriptJsonl ?? "").split("\n");
1620
+ for (let index = lines.length - 1; index >= 0; index -= 1) {
1621
+ const line = lines[index]?.trim();
1622
+ if (!line) continue;
1623
+ let entry;
1624
+ try {
1625
+ entry = JSON.parse(line);
1626
+ } catch {
1627
+ continue;
1628
+ }
1629
+ if (entry.type !== "assistant") continue;
1630
+ const content = entry.message?.content;
1631
+ if (typeof content === "string") return content;
1632
+ if (!Array.isArray(content)) continue;
1633
+ const prose = content.filter((part) => part.type === "text" && typeof part.text === "string").map((part) => part.text).join("\n");
1634
+ if (prose) return prose;
1535
1635
  }
1636
+ return "";
1536
1637
  }
1537
- var defaultPrWalkthroughLookup = {
1538
- branchPrUrl: () => {
1539
- const url = runGh(["pr", "view", "--json", "url", "-q", ".url"])?.trim();
1540
- return url && url.startsWith("http") ? url : null;
1541
- },
1542
- // Scans the description as well as the comments: muggle-do embeds the
1543
- // walkthrough in the body at PR-creation time, and a comments-only check
1544
- // would report that PR as owing one it already carries.
1545
- prCarriesWalkthrough: (prUrl, acceptsSkip) => {
1546
- const rendered = runGh(["pr", "view", prUrl, "--json", "body,comments"]);
1547
- if (rendered === null) return true;
1548
- return rendered.includes(REPORT_SENTINEL) || acceptsSkip && rendered.includes(WALKTHROUGH_SKIPPED_MARKER);
1549
- }
1550
- };
1551
- function scanForOwedWalkthroughs(state, lookup = defaultPrWalkthroughLookup) {
1552
- const candidates = new Set(state.prsHandled);
1553
- const branchPrUrl = lookup.branchPrUrl();
1554
- if (branchPrUrl) candidates.add(branchPrUrl);
1555
- const owed = [];
1556
- const verified2 = [];
1557
- for (const prUrl of candidates) {
1558
- const acceptsSkip = state.e2eRun !== true || isPrCoveredBySkip(state, prUrl);
1559
- if (lookup.prCarriesWalkthrough(prUrl, acceptsSkip)) verified2.push(prUrl);
1560
- else owed.push(prUrl);
1561
- }
1562
- return { owed, verified: verified2 };
1638
+
1639
+ // src/guardrails/preExecutionClassification.ts
1640
+ var CLASSIFICATION_SKIP_MARKER = /^\s*echo\s+["']?MUGGLE_CLASSIFY_SKIP\b/;
1641
+ function detectClassifiedTestCaseId(input2) {
1642
+ if (!MUGGLE_EVENT_EMIT_TOOL.test(input2.tool_name ?? "")) return void 0;
1643
+ if (input2.tool_input?.eventType !== PRE_EXECUTION_CLASSIFICATION_EVENT) return void 0;
1644
+ if (callFailed(input2)) return void 0;
1645
+ return input2.tool_input?.testCaseId ?? ANY_TEST_CASE;
1563
1646
  }
1564
- function isWalkthroughGateArmed(state) {
1565
- const isSkipUnsettled = state.e2eSkipDeclaration !== void 0 && state.e2eSkipSettledOnPrs !== true;
1566
- const isOwed = state.e2eRun === true || isSkipUnsettled;
1567
- return isOwed && state.walkthroughsVerified !== true && state.walkthroughSkipped !== true;
1647
+ function applyClassifiedTestCase(state, testCaseId) {
1648
+ if ((state.classifiedTestCaseIds ?? []).includes(testCaseId)) return state;
1649
+ return { ...state, classifiedTestCaseIds: [...state.classifiedTestCaseIds ?? [], testCaseId] };
1568
1650
  }
1569
- function isWalkthroughScanCurrent(scan, state) {
1570
- const scanned = new Set(scan.prsHandled);
1571
- const coversHandledPrs = scanned.size === new Set(state.prsHandled).size && state.prsHandled.every((prUrl) => scanned.has(prUrl));
1572
- const postedAt = state.walkthroughPostedAt;
1573
- const followsLastPost = postedAt === void 0 || (scan.startedAt ?? 0) >= postedAt;
1574
- return coversHandledPrs && followsLastPost;
1651
+ function resolveExecutionTargetTestCaseId(input2) {
1652
+ if (!MUGGLE_EXECUTION_TOOL.test(input2.tool_name ?? "")) return void 0;
1653
+ return input2.tool_input?.testCase?.id ?? input2.tool_input?.testScript?.testCaseId;
1575
1654
  }
1576
- function withoutPostedPrs(prUrls, state) {
1577
- const postedPrUrls = new Set(state.walkthroughPostedPrUrls ?? []);
1578
- return prUrls.filter((prUrl) => !postedPrUrls.has(prUrl));
1655
+ function isClassificationSkipMarker(command) {
1656
+ return CLASSIFICATION_SKIP_MARKER.test(command);
1579
1657
  }
1580
- function applyPrOpenedToWalkthroughs(state) {
1581
- if (state.walkthroughsVerified !== true && state.e2eSkipSettledOnPrs !== true) return state;
1582
- return { ...state, walkthroughsVerified: false, e2eSkipSettledOnPrs: false };
1658
+ function applyClassificationSkip(state, skipped) {
1659
+ if (!skipped || state.classificationSkipped === true) return state;
1660
+ return { ...state, classificationSkipped: true };
1583
1661
  }
1584
- function walkthroughGateDecision(state, owedPrUrls, maxBlocks = MAX_WALKTHROUGH_BLOCKS) {
1585
- const blockCount = state.walkthroughBlockCount ?? 0;
1586
- if (!isWalkthroughGateArmed(state) || owedPrUrls.length === 0) {
1587
- return { action: "none" /* None */, blockCount, owed: owedPrUrls };
1588
- }
1589
- if (blockCount >= maxBlocks) {
1590
- return { action: "release" /* Release */, blockCount, owed: owedPrUrls };
1591
- }
1592
- return { action: "block" /* Block */, blockCount: blockCount + 1, owed: owedPrUrls };
1662
+ function classificationGateDecision(state, input2) {
1663
+ if (state.lastInvokedSkillName !== MUGGLE_TEST_SKILL_NAME) return { deny: false };
1664
+ if (state.classificationSkipped === true) return { deny: false };
1665
+ const testCaseId = resolveExecutionTargetTestCaseId(input2);
1666
+ if (!testCaseId) return { deny: false };
1667
+ const classified = state.classifiedTestCaseIds ?? [];
1668
+ if (classified.includes(ANY_TEST_CASE) || classified.includes(testCaseId)) return { deny: false };
1669
+ return { deny: true, testCaseId };
1670
+ }
1671
+
1672
+ // src/guardrails/testsGreen.ts
1673
+ var TEST_CMD = /\b(pnpm|npm|yarn)\s+(run\s+)?test\b|\b(jest|vitest|pytest)\b|\bgo\s+test\b|\bcargo\s+test\b/;
1674
+ var FAIL = /\b\d+\s+failed\b|\bFAIL\b|✗/;
1675
+ var E2E_TOOL = /muggle.*(execute|test-generation|replay)/i;
1676
+ function isTestCommand(cmd) {
1677
+ return TEST_CMD.test(cmd);
1678
+ }
1679
+ function testsPassed(input2) {
1680
+ const response = input2.tool_response;
1681
+ const out = `${response?.stdout ?? ""}
1682
+ ${response?.stderr ?? ""}
1683
+ ${response?.output ?? ""}`;
1684
+ if (!out.trim()) return false;
1685
+ return !FAIL.test(out);
1686
+ }
1687
+ function isE2ERun(input2) {
1688
+ if (E2E_TOOL.test(input2.tool_name ?? "")) return true;
1689
+ return MUGGLE_SKILL_EMIT_TOOL.test(input2.tool_name ?? "") && input2.tool_input?.skillName === MUGGLE_TEST_SKILL_NAME;
1690
+ }
1691
+ function parseMaxCatchUpRebases(configuredValue) {
1692
+ if (configuredValue === UNBOUNDED_PREFERENCE_VALUE) return null;
1693
+ const spelled = typeof configuredValue === "number" ? String(configuredValue) : configuredValue;
1694
+ return typeof spelled === "string" && POSITIVE_INTEGER.test(spelled) ? Number(spelled) : void 0;
1695
+ }
1696
+ function resolveWatchPreferences(homeDir = homedir(), pluginRoot = resolvePluginRoot()) {
1697
+ const shippedDefaults = readJsonRecord(join(pluginRoot, ...PREFERENCE_DEFAULTS_PATH_SEGMENTS));
1698
+ const userPreferences = asRecord(readJsonRecord(join(homeDir, ...USER_PREFERENCES_PATH_SEGMENTS)).preferences);
1699
+ const autoRebase = userPreferences[AUTO_REBASE_PREFERENCE_KEY] ?? shippedDefaults[AUTO_REBASE_PREFERENCE_KEY];
1700
+ const userCap = parseMaxCatchUpRebases(userPreferences[MAX_CATCH_UP_REBASES_PREFERENCE_KEY]);
1701
+ const shippedCap = parseMaxCatchUpRebases(shippedDefaults[MAX_CATCH_UP_REBASES_PREFERENCE_KEY]);
1702
+ return {
1703
+ autoRebase: typeof autoRebase === "string" ? autoRebase : void 0,
1704
+ maxCatchUpRebases: userCap !== void 0 ? userCap : shippedCap ?? null
1705
+ };
1593
1706
  }
1594
1707
 
1595
1708
  // src/e2e-skip/noAppLogicChange.ts
@@ -2281,17 +2394,18 @@ if (!isBackgroundJob(sub)) enforceHookChildProcessDeadline();
2281
2394
  var input = readStdin();
2282
2395
  var sessionId = input.session_id ?? "unknown";
2283
2396
  function releaseGate(field) {
2284
- updateState(
2285
- sessionId,
2286
- (current) => current[field] === true ? current : { ...current, [field]: true }
2287
- );
2397
+ commitStateMutation(sessionId, { kind: "fields" /* Fields */, fields: { [field]: true } });
2288
2398
  return "{}";
2289
2399
  }
2290
2400
  function muggleSkill(slashCommand) {
2291
2401
  return skillInvocation(slashCommand, host);
2292
2402
  }
2293
- function nextOptionsOfferMethod() {
2294
- return host === "codex" ? "by asking them in your closing message (request_user_input where it is available)" : "via AskUserQuestion";
2403
+ function isOfferAskedInClosingMessage() {
2404
+ return host === "codex" || ownsOpenWatchSlot(sessionId);
2405
+ }
2406
+ function nextOptionsOfferMethod(isAskedInClosingMessage) {
2407
+ if (host === "codex") return "by asking them in your closing message (request_user_input where it is available)";
2408
+ return isAskedInClosingMessage ? "as text in your closing message, numbered and ending on the question \u2014 this session still watches an open PR, and an AskUserQuestion would hold the turn while its watcher goes unanswered" : "via AskUserQuestion";
2295
2409
  }
2296
2410
  function prOpened() {
2297
2411
  const url = detectPrOpened(input);
@@ -2299,10 +2413,11 @@ function prOpened() {
2299
2413
  if (readState(sessionId).prsHandled.includes(url)) return "{}";
2300
2414
  markPrHandled(sessionId, url);
2301
2415
  const prChange = resolveOpenedPrChange(input.tool_input?.command ?? "", url, input.cwd);
2302
- const stateAfterOpen = commitState(
2303
- sessionId,
2304
- (state) => applyPrOpenedToSkipScope(applyPrOpenedToWalkthroughs(state), url, prChange)
2305
- ) ?? readState(sessionId);
2416
+ const stateAfterOpen = commitStateMutation(sessionId, {
2417
+ kind: "pr-opened" /* PrOpened */,
2418
+ prUrl: url,
2419
+ prChange
2420
+ });
2306
2421
  const declaredSkip = isPrCoveredBySkip(stateAfterOpen, url) ? stateAfterOpen.e2eSkipDeclaration : void 0;
2307
2422
  if (declaredSkip) {
2308
2423
  startBackgroundJob("settle-walkthrough-skipped" /* SettleWalkthroughSkipped */, [url, declaredSkip.code, declaredSkip.detail]);
@@ -2333,7 +2448,7 @@ function prTerminal() {
2333
2448
  const next = applyPrTerminalDetected(state, terminalEvent.prNumber);
2334
2449
  if (next === state) return "{}";
2335
2450
  writeState(next);
2336
- const ctx = `PR #${terminalEvent.prNumber} went terminal (${terminalEvent.verdict}). Run the post-merge handoff now: finalize the watcher slot, tear down per autoCleanup, then OFFER NEXT OPTIONS to the user ${nextOptionsOfferMethod()} \u2014 release, queued work, deferred items. The stop gate holds until the offer runs.`;
2451
+ const ctx = `PR #${terminalEvent.prNumber} went terminal (${terminalEvent.verdict}). Run the post-merge handoff now: finalize the watcher slot, tear down per autoCleanup, then OFFER NEXT OPTIONS to the user ${nextOptionsOfferMethod(isOfferAskedInClosingMessage())} \u2014 release, queued work, deferred items. The stop gate holds until the offer runs.`;
2337
2452
  return envelope("PostToolUse", ctx, host);
2338
2453
  }
2339
2454
  function offerRan() {
@@ -2345,7 +2460,8 @@ function offerRan() {
2345
2460
  }
2346
2461
  function terminalGate() {
2347
2462
  const pendingState = readState(sessionId);
2348
- const state = host === "codex" && closingMessageAsksUser(input.last_assistant_message) ? applyNextOptionsOffered(pendingState) : pendingState;
2463
+ const isAskedInClosingMessage = isOfferAskedInClosingMessage();
2464
+ const state = isAskedInClosingMessage && closingMessageAsksUser(closingAssistantText()) ? applyNextOptionsOffered(pendingState) : pendingState;
2349
2465
  if (state !== pendingState) writeState(state);
2350
2466
  const decision = prTerminalGateDecision(state);
2351
2467
  if (decision.action === "release" /* Release */) return releaseGate("terminalReleased");
@@ -2353,7 +2469,7 @@ function terminalGate() {
2353
2469
  state.terminalBlockCount = decision.blockCount;
2354
2470
  writeState(state);
2355
2471
  const pendingPrList = (state.terminalPending ?? []).map((prNumber) => `#${prNumber}`).join(", ");
2356
- const reason = decision.blockCount === 1 ? `Do not end the turn yet. PR ${pendingPrList} went terminal (merged/closed) but the post-merge handoff has not run. Finalize the watcher slot, tear down per autoCleanup, then offer next options to the user ${nextOptionsOfferMethod()} \u2014 release, queued work, deferred items. Only that offer clears this gate.` : `Post-merge handoff still owed for PR ${pendingPrList} (reminder ${decision.blockCount}/${MAX_PR_TERMINAL_BLOCKS}): finalize + tear down, then offer the next options ${nextOptionsOfferMethod()}.`;
2472
+ const reason = decision.blockCount === 1 ? `Do not end the turn yet. PR ${pendingPrList} went terminal (merged/closed) but the post-merge handoff has not run. Finalize the watcher slot, tear down per autoCleanup, then offer next options to the user ${nextOptionsOfferMethod(isAskedInClosingMessage)} \u2014 release, queued work, deferred items. Only that offer clears this gate.` : `Post-merge handoff still owed for PR ${pendingPrList} (reminder ${decision.blockCount}/${MAX_PR_TERMINAL_BLOCKS}): finalize + tear down, then offer the next options ${nextOptionsOfferMethod(isAskedInClosingMessage)}.`;
2357
2473
  return blockStop(reason, host);
2358
2474
  }
2359
2475
  function startWalkthroughScanOnGateArming(stateBefore, committed, hasPosted = false) {
@@ -2366,32 +2482,27 @@ function recordTests() {
2366
2482
  const stateBefore = readState(sessionId);
2367
2483
  const judgedSkip = judgeE2eSkip(input, stateBefore);
2368
2484
  const acceptedSkip = judgedSkip?.accepted ? judgedSkip.skip : null;
2369
- const run = {
2370
- unitTestPassed: isTestCommand(cmd) && testsPassed(input),
2371
- e2eRan: isE2ERun(input),
2372
- e2eSkipped: acceptedSkip !== null,
2373
- e2eSkipCycleScoped: acceptedSkip !== null && CYCLE_SCOPED_SKIP_CODES.includes(acceptedSkip.code)
2374
- };
2375
2485
  const walkthroughPosted = detectWalkthroughPost(input);
2376
- const walkthroughPostTargets = walkthroughPosted ? detectWalkthroughPostTargets(input) : [];
2377
- const failedRunId = detectFailedRunId(input);
2378
2486
  const isDeclaredHere = acceptedSkip !== null && !CYCLE_SCOPED_SKIP_CODES.includes(acceptedSkip.code);
2379
- const verifiedChange = isDeclaredHere ? resolveTreeChange(input.cwd) : void 0;
2380
- const record = (state) => {
2381
- const declared = applyE2eSkipDeclaration(applyRecordedRun(state, run), acceptedSkip);
2382
- const recorded = isDeclaredHere ? applyE2eSkipScope(declared, verifiedChange) : declared;
2383
- const withWatchSkip = applyWatchSkip(recorded, isWatchSkipMarker(cmd));
2384
- const withBuildSkip = applyBuildSkip(withWatchSkip, isBuildSkipMarker(cmd));
2385
- const withWalkthroughPost = applyWalkthroughPosted(
2386
- withBuildSkip,
2387
- walkthroughPosted,
2388
- Date.now(),
2389
- walkthroughPostTargets
2390
- );
2391
- const withWalkthroughSkip = applyWalkthroughSkip(withWalkthroughPost, isWalkthroughSkipMarker(cmd));
2392
- return failedRunId ? applyFailedRun(withWalkthroughSkip, failedRunId) : withWalkthroughSkip;
2487
+ const outcome = {
2488
+ kind: "tool-outcome" /* ToolOutcome */,
2489
+ run: {
2490
+ unitTestPassed: isTestCommand(cmd) && testsPassed(input),
2491
+ e2eRan: isE2ERun(input),
2492
+ e2eSkipped: acceptedSkip !== null,
2493
+ e2eSkipCycleScoped: acceptedSkip !== null && CYCLE_SCOPED_SKIP_CODES.includes(acceptedSkip.code)
2494
+ },
2495
+ acceptedSkip,
2496
+ skipVerifiedChange: isDeclaredHere ? resolveTreeChange(input.cwd) : void 0,
2497
+ isWatchSkip: isWatchSkipMarker(cmd),
2498
+ isBuildSkip: isBuildSkipMarker(cmd),
2499
+ isWalkthroughPosted: walkthroughPosted,
2500
+ walkthroughPostedAt: Date.now(),
2501
+ walkthroughPostTargets: walkthroughPosted ? detectWalkthroughPostTargets(input) : [],
2502
+ isWalkthroughSkip: isWalkthroughSkipMarker(cmd),
2503
+ failedRunId: detectFailedRunId(input)
2393
2504
  };
2394
- const next = commitState(sessionId, record) ?? record(readState(sessionId));
2505
+ const next = commitStateMutation(sessionId, outcome);
2395
2506
  startWalkthroughScanOnGateArming(stateBefore, next, walkthroughPosted);
2396
2507
  if (acceptedSkip) recordSkipReasonOnPrs(next, acceptedSkip);
2397
2508
  if (judgedSkip && !judgedSkip.accepted) {
@@ -2412,23 +2523,23 @@ function recordSkipReasonOnPrs(state, skip) {
2412
2523
  function recordDelegation() {
2413
2524
  const prUrls = detectBackgroundAcceptanceDispatch(input);
2414
2525
  if (prUrls === null) return "{}";
2415
- const delegate = (state) => applyE2eDelegation(state, { dispatchedAt: Date.now(), prUrls });
2416
- updateState(sessionId, delegate);
2526
+ commitStateMutation(sessionId, {
2527
+ kind: "e2e-delegation" /* E2eDelegation */,
2528
+ delegation: { dispatchedAt: Date.now(), prUrls }
2529
+ });
2417
2530
  return "{}";
2418
2531
  }
2419
2532
  function skillStages() {
2420
2533
  const skillName = resolveSkillNameFromToolInput(input.tool_input);
2421
2534
  if (!skillName) return "{}";
2422
2535
  const stagePaths = resolveSkillStagePaths(skillName, resolvePluginSkillsRoot());
2423
- const emittedRun = {
2424
- unitTestPassed: false,
2425
- e2eRan: isE2ERun(input),
2426
- e2eSkipped: false,
2427
- e2eSkipCycleScoped: false
2428
- };
2429
2536
  const stateBefore = readState(sessionId);
2430
- const invoke = (state) => applyRecordedRun(applySkillInvocation(state, skillName, stagePaths), emittedRun);
2431
- const next = commitState(sessionId, invoke) ?? invoke(readState(sessionId));
2537
+ const next = commitStateMutation(sessionId, {
2538
+ kind: "skill-invocation" /* SkillInvocation */,
2539
+ skillName,
2540
+ stagePaths,
2541
+ emittedRun: { unitTestPassed: false, e2eRan: isE2ERun(input), e2eSkipped: false, e2eSkipCycleScoped: false }
2542
+ });
2432
2543
  startWalkthroughScanOnGateArming(stateBefore, next);
2433
2544
  const unread = unreadMandatoryStages(next);
2434
2545
  if (unread.length === 0) return "{}";
@@ -2540,17 +2651,19 @@ function watchFollowThroughGate() {
2540
2651
  const decision = watchFollowThroughDecision(state, owedWork);
2541
2652
  if (decision.action === "none" /* None */) {
2542
2653
  if (state !== stateBefore || (state.watchFollowThroughBlockCount ?? 0) > 0) {
2543
- updateState(sessionId, (current) => ({
2544
- ...applyWatchHolds(current, heldPrNumbers),
2545
- watchFollowThroughBlockCount: 0
2546
- }));
2654
+ commitStateMutation(sessionId, {
2655
+ kind: "watch-follow-through" /* WatchFollowThrough */,
2656
+ heldPrNumbers,
2657
+ blockCount: 0
2658
+ });
2547
2659
  }
2548
2660
  return "{}";
2549
2661
  }
2550
- updateState(sessionId, (current) => ({
2551
- ...applyWatchHolds(current, heldPrNumbers),
2552
- watchFollowThroughBlockCount: decision.blockCount
2553
- }));
2662
+ commitStateMutation(sessionId, {
2663
+ kind: "watch-follow-through" /* WatchFollowThrough */,
2664
+ heldPrNumbers,
2665
+ blockCount: decision.blockCount
2666
+ });
2554
2667
  const owedList = decision.owed.map(owedWatchWorkLine).join("\n");
2555
2668
  const holdInstruction = `Only the user can hold it: their own message containing \`${WATCH_HOLD_PHRASE_PREFIX}<pr-number>\` for that PR. Ask if you must; never decide it for them.`;
2556
2669
  const reason = decision.blockCount === 1 ? `Do not end the turn yet. A muggle-pr-followup watch this session owns found work due that nothing acted on:
@@ -2620,7 +2733,7 @@ function recordCommentReplies() {
2620
2733
  if (isReplySkipMarker(cmd)) {
2621
2734
  const deferred = deferredCommentIds(readLedger(slotPath), cmd);
2622
2735
  if (deferred.length === 0) {
2623
- updateState(sessionId, (current) => ({ ...current, commentReplySkipped: true }));
2736
+ commitStateMutation(sessionId, { kind: "fields" /* Fields */, fields: { commentReplySkipped: true } });
2624
2737
  return "{}";
2625
2738
  }
2626
2739
  for (const { threadId, commentIds } of deferred) {
@@ -2657,7 +2770,10 @@ function commentReplyGate() {
2657
2770
  const decision = commentReplyGateDecision(state, overdueThreads(slotPath, sessionId));
2658
2771
  if (decision.action === "release" /* Release */) return releaseGate("commentReplyReleased");
2659
2772
  if (decision.action !== "block" /* Block */) return "{}";
2660
- updateState(sessionId, (current) => ({ ...current, commentReplyBlockCount: decision.blockCount }));
2773
+ commitStateMutation(sessionId, {
2774
+ kind: "fields" /* Fields */,
2775
+ fields: { commentReplyBlockCount: decision.blockCount }
2776
+ });
2661
2777
  const commentList = decision.unanswered.join(", ");
2662
2778
  const reason = decision.blockCount === 1 ? `Do not end the turn yet. This session took these review comments as work and never answered them: ${commentList}. Post one reply per comment in its own thread per muggle-do do/per-comment-replies.md \u2014 "Addressed in <short-sha>: <what changed for THIS comment>", signed via sign-body.sh --mode loop. A silent round leaves the reviewer with no answer in the thread, and the loop marker that reply carries is the only thing that stops the watcher re-dispatching the same thread next tick. If a comment was escalated to the user instead of answered, record it as deferred rather than replying.` : `Review comments still owe a threaded reply (reminder ${decision.blockCount}/${MAX_REPLY_BLOCKS}): ${commentList}. Reply per do/per-comment-replies.md, or record the deferral.`;
2663
2779
  return blockStop(reason, host);
@@ -2800,6 +2916,10 @@ function scanWatchPrStatesJob() {
2800
2916
  writePrStateScan(scannedSessionId, { states: { ...previousScan?.states, ...freshScan.states } });
2801
2917
  return "{}";
2802
2918
  }
2919
+ function commitDeferredStateJob() {
2920
+ commitDeferredSessionState(jobArgs[0] ?? "unknown");
2921
+ return "{}";
2922
+ }
2803
2923
  var backgroundJobs = {
2804
2924
  ["scan-walkthroughs" /* ScanWalkthroughs */]: scanWalkthroughsJob,
2805
2925
  ["reserve-walkthrough-comment" /* ReserveWalkthroughComment */]: reserveWalkthroughCommentJob,
@@ -2807,7 +2927,8 @@ var backgroundJobs = {
2807
2927
  ["settle-branch-walkthrough-skipped" /* SettleBranchWalkthroughSkipped */]: settleBranchWalkthroughSkippedJob,
2808
2928
  ["settle-walkthrough-unreasoned" /* SettleWalkthroughUnreasoned */]: settleWalkthroughUnreasonedJob,
2809
2929
  ["settle-walkthrough-no-app-logic-change" /* SettleWalkthroughNoAppLogicChange */]: settleWalkthroughNoAppLogicChangeJob,
2810
- ["scan-watch-pr-states" /* ScanWatchPrStates */]: scanWatchPrStatesJob
2930
+ ["scan-watch-pr-states" /* ScanWatchPrStates */]: scanWatchPrStatesJob,
2931
+ ["commit-deferred-state" /* CommitDeferredState */]: commitDeferredStateJob
2811
2932
  };
2812
2933
  var runSubcommand = isBackgroundJob(sub) ? backgroundJobs[sub] : handlers[sub] ?? (() => "{}");
2813
2934
  process.stdout.write(runSubcommand());