@muggleai/works 5.26.0-staging.210 → 5.26.0-staging.212

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,7 +9,7 @@
9
9
  "name": "muggleai",
10
10
  "source": "./plugin",
11
11
  "description": "Real-browser E2E acceptance for your coding agent: test the flows you changed and open the PR with screenshots. Built for flows other tools can't reach: managed test identities with live inboxes (magic links, email OTP and 2FA, verification mail, password resets), an encrypted secret store for login and test credentials, and a test graph that runs prerequisite flows first. Plain-English tests become replayable scripts on localhost or preview URLs.",
12
- "version": "5.26.0-staging.210"
12
+ "version": "5.26.0-staging.212"
13
13
  }
14
14
  ]
15
15
  }
@@ -1,11 +1,11 @@
1
- import { __export, getLogger, getConfig, createChildLogger, buildElectronAppReleaseAssetUrl, getActiveRuntimeTarget, getAuthService, hasApiKey, getElectronAppVersion, getElectronAppDir, getPlatformKey, reconcileProjectPreferences, getDataDir2, PREFERENCES_FILE_NAME, isFirstRun, writePreferences, DEFAULT_PREFERENCES, isElectronAppInstalled, getElectronAppChecksums, getChecksumForPlatform, getElectronAppSignedFromVersion, getReleaseSignerIdentityUri, verifyFileChecksum, resolveElectronAppExecutablePath, calculateFileChecksum, initTelemetry, Surface, ServiceName, track, EventName, getQaTools, getLocalQaTools, performLogout, assertDeviceCodeClientProvisioned, performLogin, getActiveElectronAppReleaseStream, buildToolInputJsonSchema, toolRequiresAuth, getCallerCredentials, parseElectronAppDirName, getElectronAppReleaseTagPrefix, hasShownDisclosure, markDisclosureShown, getBundledElectronAppVersion, getElectronAppVersionSource, getCredentialsFilePath, ElectronAppReleaseStream, buildElectronAppChecksumsUrl, __require, getDisclosureCopy, buildOnboardingPlan, applyOnboardingAnswers, needsOnboarding, readRunView, RunViewError, renderRunViewText, writeRunViewHtml, openBrowserUrl, evaluateCheckoutFreshness, runGitCommand, BLOCKING_FRESHNESS_VERDICTS, claimServiceStack, BUSY_EXIT_CODE, checkServiceStack, releaseServiceStack, readServiceStackStatus, resolvePreferences, OnboardingBlanketChoice, PreferenceKey, getDataDir } from './chunk-H62MFQKC.js';
1
+ import { __export, getLogger, getConfig, createChildLogger, buildElectronAppReleaseAssetUrl, getActiveRuntimeTarget, getAuthService, hasApiKey, getElectronAppVersion, getElectronAppDir, getPlatformKey, reconcileProjectPreferences, getDataDir2, PREFERENCES_FILE_NAME, isFirstRun, writePreferences, DEFAULT_PREFERENCES, isElectronAppInstalled, getElectronAppChecksums, getChecksumForPlatform, getElectronAppSignedFromVersion, getReleaseSignerIdentityUri, verifyFileChecksum, resolveElectronAppExecutablePath, calculateFileChecksum, initTelemetry, Surface, ServiceName, track, EventName, getQaTools, getLocalQaTools, performLogout, assertDeviceCodeClientProvisioned, performLogin, getActiveElectronAppReleaseStream, buildToolInputJsonSchema, toolRequiresAuth, getCallerCredentials, parseElectronAppDirName, getElectronAppReleaseTagPrefix, hasShownDisclosure, markDisclosureShown, getBundledElectronAppVersion, getElectronAppVersionSource, getCredentialsFilePath, ElectronAppReleaseStream, buildElectronAppChecksumsUrl, __require, getDisclosureCopy, buildOnboardingPlan, applyOnboardingAnswers, needsOnboarding, readRunView, RunViewError, renderRunViewText, writeRunViewHtml, openBrowserUrl, evaluateCheckoutFreshness, runGitCommand, BLOCKING_FRESHNESS_VERDICTS, claimServiceStack, BUSY_EXIT_CODE, checkServiceStack, releaseServiceStack, readServiceStackStatus, resolvePreferences, OnboardingBlanketChoice, PreferenceKey, getDataDir } from './chunk-MJ34HBWC.js';
2
2
  import { Server } from '@modelcontextprotocol/sdk/server/index.js';
3
3
  import { ListToolsRequestSchema, CallToolRequestSchema, ListResourcesRequestSchema, ReadResourceRequestSchema } from '@modelcontextprotocol/sdk/types.js';
4
4
  import { v4 } from 'uuid';
5
5
  import { z, ZodError } from 'zod';
6
6
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
7
7
  import * as fs from 'fs';
8
- import { readFileSync, existsSync, rmSync, mkdirSync, readdirSync, createWriteStream, writeFileSync, statSync, readlinkSync, realpathSync, openSync, writeSync, closeSync, unlinkSync, copyFileSync, renameSync, appendFileSync, readSync } from 'fs';
8
+ import { readFileSync, existsSync, rmSync, mkdirSync, readdirSync, createWriteStream, writeFileSync, statSync, readlinkSync, realpathSync, openSync, writeSync, closeSync, unlinkSync, copyFileSync, renameSync, appendFileSync, readSync, fstatSync } from 'fs';
9
9
  import * as path from 'path';
10
10
  import { dirname, resolve, join, basename } from 'path';
11
11
  import { fileURLToPath, pathToFileURL } from 'url';
@@ -1068,7 +1068,7 @@ async function resolveGsScreenshotUrls(report, opts) {
1068
1068
  if (gsUrls.length === 0) {
1069
1069
  return report;
1070
1070
  }
1071
- const mcps = await import('./src-A45WRSIF.js');
1071
+ const mcps = await import('./src-B7WALKBP.js');
1072
1072
  const credentials = await mcps.getCallerCredentialsAsync();
1073
1073
  if (!credentials.bearerToken && !credentials.apiKey) {
1074
1074
  stderrWrite(
@@ -2296,6 +2296,8 @@ var WATCHER_REARM_GRACE_MS = 5 * 6e4;
2296
2296
  var CODEX_ACTIVE_WINDOW_MS = 10 * 6e4;
2297
2297
  var CODEX_ROLLOUT_DAY_DIRS_SCANNED = 7;
2298
2298
  var MAX_RESPAWNS_PER_TICK = 3;
2299
+ var SESSION_EXIT_WAIT_MS = 2e4;
2300
+ var SESSION_EXIT_POLL_MS = 1e3;
2299
2301
  var MAX_RESUMES_PER_TICK = 2;
2300
2302
  var RECOVERY_COOLDOWN_MS = 30 * 6e4;
2301
2303
  var RECOVERY_MAX_ATTEMPTS = 3;
@@ -2306,6 +2308,8 @@ var TERMINAL_PR_RECHECK_MS = 6 * 60 * 6e4;
2306
2308
  var WATCH_COMMAND_TIMEOUT_MS = 3e4;
2307
2309
  var WATCH_COMMAND_MAX_BUFFER_BYTES = 64 * 1024 * 1024;
2308
2310
  var SESSION_FILE_HEAD_BYTES = 64 * 1024;
2311
+ var SESSION_FILE_TAIL_BYTES = 64 * 1024;
2312
+ var USAGE_LIMIT_NOTICE_PATTERN = /\bhit your (?:session|usage|weekly|daily) limit\b|\busage limit reached\b/i;
2309
2313
  var WATCH_LOCK_FILE = "watch.lock";
2310
2314
  var WATCH_LOCK_WAIT_MS = 6e4;
2311
2315
  var PR_WATCH_SLOTS_RELATIVE_PATH = ["muggle-do", "sessions"];
@@ -2361,6 +2365,9 @@ var WATCH_TICK_INTERVAL_SECONDS = 120;
2361
2365
  var WATCH_LAUNCHD_LABEL = "ai.muggle.watch";
2362
2366
  var WATCH_SYSTEMD_UNIT_NAME = "muggle-watch";
2363
2367
  var WATCH_CRON_MARKER = "# muggle-watch";
2368
+ function blockFor(durationMs) {
2369
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, durationMs);
2370
+ }
2364
2371
  var defaultCommandRunner = (executable, args, options) => {
2365
2372
  const spawned = spawnSync(executable, args, {
2366
2373
  cwd: options?.cwd,
@@ -4203,15 +4210,6 @@ function renderWatchStatus(snapshot, nowMs) {
4203
4210
  return `${lines.join("\n")}
4204
4211
  `;
4205
4212
  }
4206
-
4207
- // src/guardrails/types.ts
4208
- var ProviderPrState = /* @__PURE__ */ ((ProviderPrState2) => {
4209
- ProviderPrState2["Open"] = "OPEN";
4210
- ProviderPrState2["Merged"] = "MERGED";
4211
- ProviderPrState2["Closed"] = "CLOSED";
4212
- ProviderPrState2["Unreachable"] = "UNREACHABLE";
4213
- return ProviderPrState2;
4214
- })(ProviderPrState || {});
4215
4213
  function enumValueOf(values, candidate) {
4216
4214
  return Object.values(values).find((value) => value === candidate);
4217
4215
  }
@@ -4231,6 +4229,21 @@ function readFileHead(filePath) {
4231
4229
  if (fileDescriptor !== void 0) closeSync(fileDescriptor);
4232
4230
  }
4233
4231
  }
4232
+ function readFileTail(filePath) {
4233
+ let fileDescriptor;
4234
+ try {
4235
+ fileDescriptor = openSync(filePath, "r");
4236
+ const fileSize = fstatSync(fileDescriptor).size;
4237
+ const length = Math.min(fileSize, SESSION_FILE_TAIL_BYTES);
4238
+ const buffer = Buffer.alloc(length);
4239
+ const bytesRead = readSync(fileDescriptor, buffer, 0, length, fileSize - length);
4240
+ return buffer.subarray(0, bytesRead).toString("utf-8");
4241
+ } catch {
4242
+ return void 0;
4243
+ } finally {
4244
+ if (fileDescriptor !== void 0) closeSync(fileDescriptor);
4245
+ }
4246
+ }
4234
4247
  function cwdFromSessionHead(head) {
4235
4248
  const parts = head.match(/"cwd"\s*:\s*("(?:[^"\\]|\\.)*")/);
4236
4249
  if (!parts) return void 0;
@@ -4241,6 +4254,15 @@ function cwdFromSessionHead(head) {
4241
4254
  }
4242
4255
  }
4243
4256
 
4257
+ // src/watch/session-liveness.ts
4258
+ function hasLiveProcess(session) {
4259
+ if (session.agent !== "claude" /* Claude */) return true;
4260
+ return session.pid !== void 0 || session.turnStatus !== void 0;
4261
+ }
4262
+ function isIdleBackgroundSession(session) {
4263
+ return session.agent === "claude" /* Claude */ && hasLiveProcess(session) && session.kind === "background" /* Background */ && session.shortId !== void 0 && session.turnStatus === "idle" /* Idle */;
4264
+ }
4265
+
4244
4266
  // src/watch/claude-sessions.ts
4245
4267
  function readPidsBySessionId(registryDir) {
4246
4268
  const pidsBySessionId = /* @__PURE__ */ new Map();
@@ -4262,6 +4284,15 @@ function readPidsBySessionId(registryDir) {
4262
4284
  }
4263
4285
  return pidsBySessionId;
4264
4286
  }
4287
+ function waitForSessionExit(runCommand, registryDir, sessionId, sleep2 = blockFor) {
4288
+ for (let waitedMs = 0; ; waitedMs += SESSION_EXIT_POLL_MS) {
4289
+ const sessions = readClaudeSessions(runCommand, registryDir);
4290
+ const session = sessions?.find((listed) => listed.sessionId === sessionId);
4291
+ if (sessions !== null && (session === void 0 || !hasLiveProcess(session))) return true;
4292
+ if (waitedMs >= SESSION_EXIT_WAIT_MS) return false;
4293
+ sleep2(SESSION_EXIT_POLL_MS);
4294
+ }
4295
+ }
4265
4296
  function readClaudeSessions(runCommand, registryDir) {
4266
4297
  const outcome = runCommand("claude", ["agents", "--json"]);
4267
4298
  if (!outcome || outcome.exitCode !== 0) return null;
@@ -4288,12 +4319,12 @@ function readClaudeSessions(runCommand, registryDir) {
4288
4319
  turnStatus: enumValueOf(ClaudeTurnStatus, listing.status),
4289
4320
  jobState: enumValueOf(ClaudeJobState, listing.state),
4290
4321
  startedAtMs: typeof listing.startedAt === "number" ? listing.startedAt : void 0,
4291
- pid: pidsBySessionId.get(sessionId)
4322
+ pid: typeof listing.pid === "number" ? listing.pid : pidsBySessionId.get(sessionId)
4292
4323
  });
4293
4324
  }
4294
4325
  return sessions;
4295
4326
  }
4296
- function findClaudeSessionCwd(projectsDir, sessionId) {
4327
+ function findTranscriptPath(projectsDir, sessionId) {
4297
4328
  let projectDirNames;
4298
4329
  try {
4299
4330
  projectDirNames = readdirSync(projectsDir);
@@ -4303,12 +4334,40 @@ function findClaudeSessionCwd(projectsDir, sessionId) {
4303
4334
  const transcriptFileName = `${sessionId}.jsonl`;
4304
4335
  for (const projectDirName of projectDirNames) {
4305
4336
  const transcriptPath = join(projectsDir, projectDirName, transcriptFileName);
4306
- if (!existsSync(transcriptPath)) continue;
4307
- const head = readFileHead(transcriptPath);
4308
- return head === void 0 ? void 0 : cwdFromSessionHead(head);
4337
+ if (existsSync(transcriptPath)) return transcriptPath;
4309
4338
  }
4310
4339
  return void 0;
4311
4340
  }
4341
+ function assistantText(entry) {
4342
+ if (entry.type !== "assistant") return void 0;
4343
+ const content = entry.message?.content;
4344
+ if (typeof content === "string") return content;
4345
+ if (!Array.isArray(content)) return "";
4346
+ return content.map((part) => typeof part?.text === "string" ? part.text : "").join(" ");
4347
+ }
4348
+ function findClaudeSessionCwd(projectsDir, sessionId) {
4349
+ const transcriptPath = findTranscriptPath(projectsDir, sessionId);
4350
+ if (transcriptPath === void 0) return void 0;
4351
+ const head = readFileHead(transcriptPath);
4352
+ return head === void 0 ? void 0 : cwdFromSessionHead(head);
4353
+ }
4354
+ function isStoppedAtUsageLimit(projectsDir, sessionId) {
4355
+ const transcriptPath = findTranscriptPath(projectsDir, sessionId);
4356
+ const tail = transcriptPath === void 0 ? void 0 : readFileTail(transcriptPath);
4357
+ if (tail === void 0) return false;
4358
+ const lines = tail.split("\n");
4359
+ for (let index = lines.length - 1; index >= 0; index--) {
4360
+ let entry;
4361
+ try {
4362
+ entry = JSON.parse(lines[index]);
4363
+ } catch {
4364
+ continue;
4365
+ }
4366
+ const text = assistantText(entry);
4367
+ if (text !== void 0) return USAGE_LIMIT_NOTICE_PATTERN.test(text);
4368
+ }
4369
+ return false;
4370
+ }
4312
4371
  var ROLLOUT_SESSION_ID = /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i;
4313
4372
  function sortedChildDirsDescending(dir) {
4314
4373
  try {
@@ -4374,6 +4433,76 @@ mcpToolNamePattern("muggle-local-telemetry-event-emit");
4374
4433
  mcpToolNamePattern("muggle-remote-user-feedback-create");
4375
4434
  var LOCK_POLL_INTERVAL_MS = 10;
4376
4435
 
4436
+ // src/guardrails/types.ts
4437
+ var ProviderPrState = /* @__PURE__ */ ((ProviderPrState2) => {
4438
+ ProviderPrState2["Open"] = "OPEN";
4439
+ ProviderPrState2["Merged"] = "MERGED";
4440
+ ProviderPrState2["Closed"] = "CLOSED";
4441
+ ProviderPrState2["Unreachable"] = "UNREACHABLE";
4442
+ return ProviderPrState2;
4443
+ })(ProviderPrState || {});
4444
+
4445
+ // src/watch/pr-status.ts
4446
+ function isTerminalPrState(state) {
4447
+ return state === "MERGED" /* Merged */ || state === "CLOSED" /* Closed */;
4448
+ }
4449
+ var PR_STATUS_FRAGMENT = `fragment WatchPr on PullRequest {
4450
+ state
4451
+ headRefOid
4452
+ mergeable
4453
+ mergeStateStatus
4454
+ commits(last: 1) { nodes { commit { statusCheckRollup { state } } } }
4455
+ reviewThreads(first: 100) { nodes { isResolved } }
4456
+ }`;
4457
+ function buildPrStatusRequest(prs) {
4458
+ const variableDeclarations = [];
4459
+ const selections = [];
4460
+ const fieldFlags = [];
4461
+ prs.forEach((pr, index) => {
4462
+ const [owner, name] = pr.repo.split("/");
4463
+ variableDeclarations.push(`$o${index}: String!, $r${index}: String!, $n${index}: Int!`);
4464
+ selections.push(` p${index}: repository(owner: $o${index}, name: $r${index}) { pullRequest(number: $n${index}) { ...WatchPr } }`);
4465
+ fieldFlags.push("-f", `o${index}=${owner}`, "-f", `r${index}=${name}`, "-F", `n${index}=${pr.number}`);
4466
+ });
4467
+ const query = `query(${variableDeclarations.join(", ")}) {
4468
+ ${selections.join("\n")}
4469
+ }
4470
+ ${PR_STATUS_FRAGMENT}`;
4471
+ return ["api", "graphql", "-f", `query=${query}`, ...fieldFlags];
4472
+ }
4473
+ function parsePullRequestNode(url, node) {
4474
+ const state = enumValueOf(ProviderPrState, node?.state);
4475
+ if (!node || state === void 0 || state === "UNREACHABLE" /* Unreachable */) return void 0;
4476
+ return {
4477
+ url,
4478
+ state,
4479
+ headSha: optionalString(node.headRefOid),
4480
+ mergeable: enumValueOf(PrMergeable, node.mergeable),
4481
+ mergeStateStatus: enumValueOf(PrMergeStateStatus, node.mergeStateStatus),
4482
+ ciRollup: enumValueOf(CiRollupState, node.commits?.nodes?.[0]?.commit?.statusCheckRollup?.state),
4483
+ unresolvedThreadCount: (node.reviewThreads?.nodes ?? []).filter((thread) => thread.isResolved === false).length
4484
+ };
4485
+ }
4486
+ function fetchPrLiveStatuses(prs, runCommand) {
4487
+ const statusesByUrl = /* @__PURE__ */ new Map();
4488
+ for (let start = 0; start < prs.length; start += PR_STATUS_BATCH_SIZE) {
4489
+ const batch = prs.slice(start, start + PR_STATUS_BATCH_SIZE);
4490
+ const outcome = runCommand("gh", buildPrStatusRequest(batch));
4491
+ if (!outcome?.stdout) continue;
4492
+ let response;
4493
+ try {
4494
+ response = JSON.parse(outcome.stdout);
4495
+ } catch {
4496
+ continue;
4497
+ }
4498
+ batch.forEach((pr, index) => {
4499
+ const liveStatus = parsePullRequestNode(pr.url, response.data?.[`p${index}`]?.pullRequest);
4500
+ if (liveStatus) statusesByUrl.set(pr.url, liveStatus);
4501
+ });
4502
+ }
4503
+ return statusesByUrl;
4504
+ }
4505
+
4377
4506
  // src/watch/findings.ts
4378
4507
  function resolveWatcherLiveness(loop, heartbeatAgeMs, isOwnerSessionActive, isProcessTableKnown) {
4379
4508
  const isHeartbeatWithin = (windowMs) => heartbeatAgeMs !== void 0 && heartbeatAgeMs <= windowMs;
@@ -4429,7 +4558,7 @@ function ownerPhrase(assessment) {
4429
4558
  }
4430
4559
  const owner = shortSessionId(assessment.ownerSessionId);
4431
4560
  if (assessment.isOwnerSessionActive === true) {
4432
- return `owner session ${owner} is running \u2014 run /muggle:muggle-pr-followup reconcile there`;
4561
+ return `owner session ${owner} is running \u2014 run /muggle:muggle-pr-followup reconcile there, or the watch does once it idles in the background`;
4433
4562
  }
4434
4563
  if (assessment.isOwnerSessionActive === false) {
4435
4564
  return assessment.isRegistered ? `owner session ${owner} has ended` : `owner session ${owner} has ended; slot is not registered for recovery`;
@@ -4499,7 +4628,7 @@ function deriveWatchFindings(assessments, processes, isPollingDisabled) {
4499
4628
  for (const assessment of assessments) {
4500
4629
  const subject = `${assessment.pr.repo}#${assessment.pr.number}`;
4501
4630
  const live = assessment.live;
4502
- if (live && (live.state === "MERGED" /* Merged */ || live.state === "CLOSED" /* Closed */)) {
4631
+ if (live && isTerminalPrState(live.state)) {
4503
4632
  findings.push(finding(
4504
4633
  "SLOT_TERMINAL_UNFINALIZED" /* SlotTerminalUnfinalized */,
4505
4634
  [assessment.pr.url],
@@ -4778,64 +4907,6 @@ function readUserPluginsUpdatedAtMs(installedPluginsFile) {
4778
4907
  return updatedAtMs;
4779
4908
  }
4780
4909
 
4781
- // src/watch/pr-status.ts
4782
- var PR_STATUS_FRAGMENT = `fragment WatchPr on PullRequest {
4783
- state
4784
- headRefOid
4785
- mergeable
4786
- mergeStateStatus
4787
- commits(last: 1) { nodes { commit { statusCheckRollup { state } } } }
4788
- reviewThreads(first: 100) { nodes { isResolved } }
4789
- }`;
4790
- function buildPrStatusRequest(prs) {
4791
- const variableDeclarations = [];
4792
- const selections = [];
4793
- const fieldFlags = [];
4794
- prs.forEach((pr, index) => {
4795
- const [owner, name] = pr.repo.split("/");
4796
- variableDeclarations.push(`$o${index}: String!, $r${index}: String!, $n${index}: Int!`);
4797
- selections.push(` p${index}: repository(owner: $o${index}, name: $r${index}) { pullRequest(number: $n${index}) { ...WatchPr } }`);
4798
- fieldFlags.push("-f", `o${index}=${owner}`, "-f", `r${index}=${name}`, "-F", `n${index}=${pr.number}`);
4799
- });
4800
- const query = `query(${variableDeclarations.join(", ")}) {
4801
- ${selections.join("\n")}
4802
- }
4803
- ${PR_STATUS_FRAGMENT}`;
4804
- return ["api", "graphql", "-f", `query=${query}`, ...fieldFlags];
4805
- }
4806
- function parsePullRequestNode(url, node) {
4807
- const state = enumValueOf(ProviderPrState, node?.state);
4808
- if (!node || state === void 0 || state === "UNREACHABLE" /* Unreachable */) return void 0;
4809
- return {
4810
- url,
4811
- state,
4812
- headSha: optionalString(node.headRefOid),
4813
- mergeable: enumValueOf(PrMergeable, node.mergeable),
4814
- mergeStateStatus: enumValueOf(PrMergeStateStatus, node.mergeStateStatus),
4815
- ciRollup: enumValueOf(CiRollupState, node.commits?.nodes?.[0]?.commit?.statusCheckRollup?.state),
4816
- unresolvedThreadCount: (node.reviewThreads?.nodes ?? []).filter((thread) => thread.isResolved === false).length
4817
- };
4818
- }
4819
- function fetchPrLiveStatuses(prs, runCommand) {
4820
- const statusesByUrl = /* @__PURE__ */ new Map();
4821
- for (let start = 0; start < prs.length; start += PR_STATUS_BATCH_SIZE) {
4822
- const batch = prs.slice(start, start + PR_STATUS_BATCH_SIZE);
4823
- const outcome = runCommand("gh", buildPrStatusRequest(batch));
4824
- if (!outcome?.stdout) continue;
4825
- let response;
4826
- try {
4827
- response = JSON.parse(outcome.stdout);
4828
- } catch {
4829
- continue;
4830
- }
4831
- batch.forEach((pr, index) => {
4832
- const liveStatus = parsePullRequestNode(pr.url, response.data?.[`p${index}`]?.pullRequest);
4833
- if (liveStatus) statusesByUrl.set(pr.url, liveStatus);
4834
- });
4835
- }
4836
- return statusesByUrl;
4837
- }
4838
-
4839
4910
  // src/watch/process-table.ts
4840
4911
  function buildWindowsProcessTableScript() {
4841
4912
  const keptExecutables = COMMAND_LINE_EXECUTABLE_PATTERN.source.replace(/'/g, "''");
@@ -4915,18 +4986,31 @@ function readPosixProcessTable(runCommand) {
4915
4986
  function readProcessTable(platform4, runCommand, nowMs) {
4916
4987
  return platform4 === "win32" ? readWindowsProcessTable(runCommand, nowMs) : readPosixProcessTable(runCommand);
4917
4988
  }
4918
- function isRecoverable(assessment) {
4919
- return assessment.isRegistered && assessment.watcher === "dead" /* Dead */ && assessment.live?.state === "OPEN" /* Open */ && assessment.ownerSessionId !== void 0 && assessment.isOwnerSessionActive === false;
4989
+
4990
+ // src/watch/session-restart.ts
4991
+ function resumeOnReconcile(target, runCommand, waitForExit) {
4992
+ if (target.runningShortId !== void 0) {
4993
+ runCommand("claude", ["stop", target.runningShortId]);
4994
+ if (!waitForExit(target.sessionId)) return false;
4995
+ }
4996
+ const resumed = runCommand("claude", ["--resume", target.sessionId, "--bg", RECOVERY_RESUME_PROMPT], { cwd: target.cwd });
4997
+ return resumed?.exitCode === 0;
4998
+ }
4999
+
5000
+ // src/watch/recovery.ts
5001
+ function isRecoverable(assessment, ownerSession) {
5002
+ const isOwnerRestartable = assessment.isOwnerSessionActive === false || assessment.isOwnerSessionActive === true && ownerSession !== void 0 && isIdleBackgroundSession(ownerSession);
5003
+ return assessment.isRegistered && assessment.watcher === "dead" /* Dead */ && assessment.live?.state === "OPEN" /* Open */ && assessment.ownerSessionId !== void 0 && isOwnerRestartable;
4920
5004
  }
4921
5005
  function isSlotCloseOutDue(assessment) {
4922
- const isTerminal = assessment.live?.state === "MERGED" /* Merged */ || assessment.live?.state === "CLOSED" /* Closed */;
4923
- return isTerminal && assessment.watcher === "dead" /* Dead */ && assessment.isOwnerSessionActive !== true;
5006
+ return isTerminalPrState(assessment.live?.state) && assessment.watcher === "dead" /* Dead */ && assessment.isOwnerSessionActive !== true;
4924
5007
  }
4925
- function planWatcherRecoveries(assessments, attemptsByOwner, nowMs, isPollingDisabled) {
5008
+ function planWatcherRecoveries(assessments, attemptsByOwner, nowMs, isPollingDisabled, sessionsById = /* @__PURE__ */ new Map(), isStoppedAtUsageLimit2 = () => false) {
4926
5009
  if (isPollingDisabled) return [];
4927
5010
  const slugsByOwner = /* @__PURE__ */ new Map();
4928
5011
  for (const assessment of assessments) {
4929
- if (!isRecoverable(assessment)) continue;
5012
+ const ownerSession = assessment.ownerSessionId === void 0 ? void 0 : sessionsById.get(assessment.ownerSessionId);
5013
+ if (!isRecoverable(assessment, ownerSession)) continue;
4930
5014
  const ownerSessionId = assessment.ownerSessionId;
4931
5015
  const slugs = slugsByOwner.get(ownerSessionId) ?? /* @__PURE__ */ new Set();
4932
5016
  slugs.add(assessment.slug);
@@ -4937,34 +5021,49 @@ function planWatcherRecoveries(assessments, attemptsByOwner, nowMs, isPollingDis
4937
5021
  for (const ownerSessionId of [...slugsByOwner.keys()].sort()) {
4938
5022
  const recentAttemptsMs = (attemptsByOwner[ownerSessionId] ?? []).map((attemptedAt) => Date.parse(attemptedAt)).filter((attemptedAtMs) => !Number.isNaN(attemptedAtMs) && nowMs - attemptedAtMs < RECOVERY_ATTEMPT_WINDOW_MS);
4939
5023
  const lastAttemptMs = Math.max(-Infinity, ...recentAttemptsMs);
5024
+ const isCapReached = recentAttemptsMs.length >= RECOVERY_MAX_ATTEMPTS && !isStoppedAtUsageLimit2(ownerSessionId);
4940
5025
  let outcome = "resume-due" /* ResumeDue */;
4941
- if (recentAttemptsMs.length >= RECOVERY_MAX_ATTEMPTS) outcome = "attempts-exhausted" /* AttemptsExhausted */;
5026
+ if (isCapReached) outcome = "attempts-exhausted" /* AttemptsExhausted */;
4942
5027
  else if (nowMs - lastAttemptMs < RECOVERY_COOLDOWN_MS) outcome = "cooling-down" /* CoolingDown */;
4943
5028
  else if (resumesPlanned >= MAX_RESUMES_PER_TICK) outcome = "deferred-by-tick-cap" /* DeferredByTickCap */;
4944
5029
  if (outcome === "resume-due" /* ResumeDue */) resumesPlanned++;
5030
+ const runningOwner = sessionsById.get(ownerSessionId);
4945
5031
  recoveries.push({
4946
5032
  ownerSessionId,
4947
5033
  slotSlugs: [...slugsByOwner.get(ownerSessionId) ?? []].sort(),
4948
- outcome
5034
+ outcome,
5035
+ ...runningOwner?.shortId === void 0 ? {} : { ownerShortId: runningOwner.shortId }
4949
5036
  });
4950
5037
  }
4951
5038
  return recoveries;
4952
5039
  }
4953
- function executeWatcherRecoveries(planned, attemptsByOwner, runCommand, claudeProjectsDir, nowMs) {
4954
- const nowIso = new Date(nowMs).toISOString();
5040
+ function executeWatcherRecoveries(planned, attemptsByOwner, deps) {
5041
+ const nowIso = new Date(deps.nowMs).toISOString();
4955
5042
  const nextAttemptsByOwner = {};
4956
5043
  for (const [ownerSessionId, attempts] of Object.entries(attemptsByOwner)) {
4957
- const recent = attempts.filter((attemptedAt) => nowMs - Date.parse(attemptedAt) < RECOVERY_ATTEMPT_WINDOW_MS);
5044
+ const recent = attempts.filter((attemptedAt) => deps.nowMs - Date.parse(attemptedAt) < RECOVERY_ATTEMPT_WINDOW_MS);
4958
5045
  if (recent.length > 0) nextAttemptsByOwner[ownerSessionId] = recent;
4959
5046
  }
4960
5047
  const events = [];
4961
5048
  const recoveries = planned.map((recovery) => {
4962
5049
  if (recovery.outcome !== "resume-due" /* ResumeDue */) return recovery;
4963
- const cwd = findClaudeSessionCwd(claudeProjectsDir, recovery.ownerSessionId);
5050
+ const cwd = findClaudeSessionCwd(deps.claudeProjectsDir, recovery.ownerSessionId);
4964
5051
  if (!cwd || !existsSync(cwd)) return { ...recovery, outcome: "transcript-missing" /* TranscriptMissing */ };
4965
- const outcome = runCommand("claude", ["--resume", recovery.ownerSessionId, "--bg", RECOVERY_RESUME_PROMPT], { cwd });
4966
- const isResumed = outcome?.exitCode === 0;
4967
5052
  nextAttemptsByOwner[recovery.ownerSessionId] = [...nextAttemptsByOwner[recovery.ownerSessionId] ?? [], nowIso];
5053
+ if (recovery.ownerShortId !== void 0 && !deps.canRestartIn(cwd)) {
5054
+ events.push({
5055
+ at: nowIso,
5056
+ kind: "restart-refused" /* RestartRefused */,
5057
+ subject: `session ${shortSessionId(recovery.ownerSessionId)}`,
5058
+ message: `left running: Claude would not resume it in ${cwd}, so ${recovery.slotSlugs.join(", ")} stay unwatched`
5059
+ });
5060
+ return { ...recovery, cwd, outcome: "restart-refused" /* RestartRefused */ };
5061
+ }
5062
+ const isResumed = resumeOnReconcile(
5063
+ { sessionId: recovery.ownerSessionId, cwd, runningShortId: recovery.ownerShortId },
5064
+ deps.runCommand,
5065
+ deps.waitForExit
5066
+ );
4968
5067
  events.push({
4969
5068
  at: nowIso,
4970
5069
  kind: isResumed ? "resumed" /* Resumed */ : "resume-failed" /* ResumeFailed */,
@@ -5000,7 +5099,7 @@ function planReloadFanOut(sessions, pending, watchOwnerSessionIds, maxRestarts =
5000
5099
  const decisions = [];
5001
5100
  for (const session of sessions) {
5002
5101
  if (session.agent !== "claude" /* Claude */) continue;
5003
- if (session.pid === void 0) {
5102
+ if (!hasLiveProcess(session)) {
5004
5103
  decisions.push(decide(session, "skip" /* Skip */, "no live process"));
5005
5104
  } else if (hasCurrentPlugins(session, pending)) {
5006
5105
  decisions.push(decide(session, "skip" /* Skip */, "already on the installed build"));
@@ -5021,7 +5120,7 @@ function planReloadFanOut(sessions, pending, watchOwnerSessionIds, maxRestarts =
5021
5120
  }
5022
5121
  return decisions;
5023
5122
  }
5024
- function executeReloadFanOut(decisions, runCommand, canRestartIn) {
5123
+ function executeReloadFanOut(decisions, runCommand, canRestartIn, waitForExit) {
5025
5124
  const restartableByCwd = /* @__PURE__ */ new Map();
5026
5125
  const isRestartable = (cwd) => {
5027
5126
  if (!restartableByCwd.has(cwd)) restartableByCwd.set(cwd, canRestartIn(cwd));
@@ -5039,9 +5138,11 @@ function executeReloadFanOut(decisions, runCommand, canRestartIn) {
5039
5138
  if (decision.action === "respawn" /* Respawn */) {
5040
5139
  isRestarted = runCommand("claude", ["respawn", decision.shortId])?.exitCode === 0;
5041
5140
  } else {
5042
- runCommand("claude", ["stop", decision.shortId]);
5043
- const resumed = runCommand("claude", ["--resume", decision.sessionId, "--bg", RECOVERY_RESUME_PROMPT], { cwd: decision.cwd });
5044
- isRestarted = resumed?.exitCode === 0;
5141
+ isRestarted = resumeOnReconcile(
5142
+ { sessionId: decision.sessionId, cwd: decision.cwd, runningShortId: decision.shortId },
5143
+ runCommand,
5144
+ waitForExit
5145
+ );
5045
5146
  }
5046
5147
  (isRestarted ? report.respawnedSessionIds : report.failedSessionIds).push(decision.sessionId);
5047
5148
  }
@@ -5123,7 +5224,7 @@ function updateTerminalCache(terminalPrsByUrl, fetchedStatuses, trackedUrls, now
5123
5224
  if (trackedUrls.has(url)) nextCache[url] = record;
5124
5225
  }
5125
5226
  for (const fetched of fetchedStatuses) {
5126
- if (fetched.state === "MERGED" /* Merged */ || fetched.state === "CLOSED" /* Closed */) {
5227
+ if (isTerminalPrState(fetched.state)) {
5127
5228
  nextCache[fetched.url] = { state: fetched.state, checkedAt: nowIso };
5128
5229
  } else {
5129
5230
  delete nextCache[fetched.url];
@@ -5344,8 +5445,11 @@ function observeSessions(deps, installs) {
5344
5445
  const sessions = [...claudeSessions ?? [], ...readCodexSessions(deps.paths.codexSessionsDir, deps.nowMs)];
5345
5446
  return { processes, claudeSessions, sessions };
5346
5447
  }
5448
+ function isRestartAttempted(recovery) {
5449
+ return recovery.outcome === "resumed" /* Resumed */ || recovery.outcome === "resume-failed" /* ResumeFailed */;
5450
+ }
5347
5451
  function watchOwnersOf(slots) {
5348
- return new Set(slots.flatMap((slot) => slot.live?.state === "OPEN" /* Open */ && slot.ownerSessionId ? [slot.ownerSessionId] : []));
5452
+ return new Set(slots.flatMap((slot) => !isTerminalPrState(slot.live?.state) && slot.ownerSessionId ? [slot.ownerSessionId] : []));
5349
5453
  }
5350
5454
  function reloadEvents(report, at) {
5351
5455
  const decisionById = new Map(report.decisions.map((decision) => [decision.sessionId, decision]));
@@ -5369,9 +5473,15 @@ function runReloadPass(record, claudeSessions, watchOwnerSessionIds, deps, at) {
5369
5473
  const decisions = planReloadFanOut(claudeSessions, record, watchOwnerSessionIds).map(
5370
5474
  (decision) => decision.action === "resume-reconcile" /* ResumeReconcile */ ? { ...decision, cwd: findClaudeSessionCwd(deps.paths.claudeProjectsDir, decision.sessionId) ?? decision.cwd } : decision
5371
5475
  );
5372
- const report = executeReloadFanOut(decisions, deps.runCommand, (cwd) => canRestartSessionIn(cwd, deps.runCommand));
5476
+ const report = executeReloadFanOut(decisions, deps.runCommand, canRestartVia(deps), waitForExitVia(deps));
5373
5477
  return { report, pendingReload: advancePendingReload(record, report), events: reloadEvents(report, at) };
5374
5478
  }
5479
+ function canRestartVia(deps) {
5480
+ return (cwd) => canRestartSessionIn(cwd, deps.runCommand);
5481
+ }
5482
+ function waitForExitVia(deps) {
5483
+ return (sessionId) => waitForSessionExit(deps.runCommand, deps.paths.claudeSessionRegistryDir, sessionId, deps.sleep);
5484
+ }
5375
5485
  function reloadTargetAtMs(deps, installs) {
5376
5486
  return resolveReloadTargetAtMs(installs, readUserPluginsUpdatedAtMs(deps.paths.claudeInstalledPluginsFile));
5377
5487
  }
@@ -5396,7 +5506,8 @@ function runTickUnlocked(deps) {
5396
5506
  const at = new Date(deps.nowMs).toISOString();
5397
5507
  const installs = readInstallHistory(deps.paths.muggleInstallLogFile);
5398
5508
  const { processes, claudeSessions, sessions } = observeSessions(deps, installs);
5399
- const activeSessionIds = claudeSessions === null ? null : new Set(sessions.map((session) => session.sessionId));
5509
+ const runningSessions = sessions.filter(hasLiveProcess);
5510
+ const activeSessionIds = claudeSessions === null ? null : new Set(runningSessions.map((session) => session.sessionId));
5400
5511
  const slots = readOpenWatchSlots(deps.paths.slotsDir);
5401
5512
  const isPollingDisabled = isPrPollingDisabled(deps.paths.slotsDir);
5402
5513
  const state = readWatchLedgerState(deps.paths.watchDir);
@@ -5423,8 +5534,21 @@ function runTickUnlocked(deps) {
5423
5534
  let recoveries = [];
5424
5535
  let recoveryAttemptsByOwner = state.recoveryAttemptsByOwner;
5425
5536
  if (deps.isRecoveryEnabled) {
5426
- const planned = planWatcherRecoveries(assessments, recoveryAttemptsByOwner, deps.nowMs, isPollingDisabled);
5427
- const executed = executeWatcherRecoveries(planned, recoveryAttemptsByOwner, deps.runCommand, deps.paths.claudeProjectsDir, deps.nowMs);
5537
+ const planned = planWatcherRecoveries(
5538
+ assessments,
5539
+ recoveryAttemptsByOwner,
5540
+ deps.nowMs,
5541
+ isPollingDisabled,
5542
+ new Map(runningSessions.map((session) => [session.sessionId, session])),
5543
+ (sessionId) => isStoppedAtUsageLimit(deps.paths.claudeProjectsDir, sessionId)
5544
+ );
5545
+ const executed = executeWatcherRecoveries(planned, recoveryAttemptsByOwner, {
5546
+ runCommand: deps.runCommand,
5547
+ claudeProjectsDir: deps.paths.claudeProjectsDir,
5548
+ nowMs: deps.nowMs,
5549
+ canRestartIn: canRestartVia(deps),
5550
+ waitForExit: waitForExitVia(deps)
5551
+ });
5428
5552
  recoveries = executed.recoveries;
5429
5553
  recoveryAttemptsByOwner = executed.attemptsByOwner;
5430
5554
  events.push(...executed.events);
@@ -5433,7 +5557,9 @@ function runTickUnlocked(deps) {
5433
5557
  let reload;
5434
5558
  const targetAtMs = reloadTargetAtMs(deps, installs);
5435
5559
  if (deps.isAutoReloadEnabled && targetAtMs !== void 0 && claudeSessions !== null) {
5436
- const pass = runReloadPass(reloadRecordFor(state, targetAtMs), claudeSessions, watchOwnersOf(assessments), deps, at);
5560
+ const restartedOwnerIds = new Set(recoveries.filter(isRestartAttempted).map((recovery) => recovery.ownerSessionId));
5561
+ const reloadableSessions = claudeSessions.filter((session) => !restartedOwnerIds.has(session.sessionId));
5562
+ const pass = runReloadPass(reloadRecordFor(state, targetAtMs), reloadableSessions, watchOwnersOf(assessments), deps, at);
5437
5563
  pendingReload = pass.pendingReload;
5438
5564
  reload = pass.report;
5439
5565
  events.push(...pass.events);
@@ -5591,6 +5591,23 @@ var FanOutChoice = /* @__PURE__ */ ((FanOutChoice2) => {
5591
5591
  var FanOutChoiceInputSchema = z.enum(["followPolicy" /* FollowPolicy */, "primaryOnly" /* PrimaryOnly */, "allNow" /* AllNow */]).optional().describe(
5592
5592
  "Optional: followPolicy (default) runs each test case's runSettings records per its lane's fan-out policy; primaryOnly runs only the primary record; allNow runs every record at once"
5593
5593
  );
5594
+
5595
+ // packages/mcps/src/mcp/e2e/contracts/secret-group-types.ts
5596
+ var SecretTypeEnum = /* @__PURE__ */ ((SecretTypeEnum2) => {
5597
+ SecretTypeEnum2["LOGIN_CREDENTIAL"] = "login_credential";
5598
+ SecretTypeEnum2["PAYMENT_CARD"] = "payment_card";
5599
+ return SecretTypeEnum2;
5600
+ })(SecretTypeEnum || {});
5601
+ var SecretFieldEnum = /* @__PURE__ */ ((SecretFieldEnum2) => {
5602
+ SecretFieldEnum2["USERNAME"] = "username";
5603
+ SecretFieldEnum2["PASSWORD"] = "password";
5604
+ SecretFieldEnum2["CARDHOLDER_NAME"] = "cardholder_name";
5605
+ SecretFieldEnum2["CARD_NUMBER"] = "card_number";
5606
+ SecretFieldEnum2["EXPIRY"] = "expiry";
5607
+ SecretFieldEnum2["CVC"] = "cvc";
5608
+ SecretFieldEnum2["BILLING_POSTAL_CODE"] = "billing_postal_code";
5609
+ return SecretFieldEnum2;
5610
+ })(SecretFieldEnum || {});
5594
5611
  var DisplayParamsSchema = z.object({
5595
5612
  browserWindowWidth: z.number(),
5596
5613
  browserWindowHeight: z.number()
@@ -5739,6 +5756,29 @@ var SecretUpdateInputSchema = z.object({
5739
5756
  var SecretDeleteInputSchema = z.object({
5740
5757
  secretId: IdSchema.describe("Secret ID (UUID) to delete")
5741
5758
  });
5759
+ var SecretGroupFieldValuesSchema = z.partialRecord(z.enum(SecretFieldEnum), z.string());
5760
+ var SecretGroupListInputSchema = z.object({
5761
+ projectId: IdSchema.describe("Project ID (UUID) to list secret groups for")
5762
+ });
5763
+ var SecretGroupCreateInputSchema = z.object({
5764
+ projectId: IdSchema.describe("Project ID (UUID) to create the secret group for"),
5765
+ secretType: z.enum(SecretTypeEnum).describe("Kind of secret group; decides which fields apply"),
5766
+ groupName: z.string().min(1).describe("Group name, e.g. 'Visa test card'; the member secret names are derived from it"),
5767
+ description: z.string().optional().describe("Human-readable description for selection guidance"),
5768
+ fields: SecretGroupFieldValuesSchema.describe(
5769
+ "Field name \u2192 value for the chosen secretType; include every required field muggle-remote-secret-type-list lists for that type"
5770
+ )
5771
+ });
5772
+ var SecretGroupUpdateInputSchema = z.object({
5773
+ groupId: IdSchema.describe("Secret group ID (UUID) to update"),
5774
+ description: z.string().optional().describe("Updated description"),
5775
+ fields: SecretGroupFieldValuesSchema.optional().describe(
5776
+ "Field name \u2192 new value. A non-empty value sets the field (adding a missing optional one); an empty string clears an optional field; omitted fields stay unchanged"
5777
+ )
5778
+ });
5779
+ var SecretGroupDeleteInputSchema = z.object({
5780
+ groupId: IdSchema.describe("Secret group ID (UUID) to delete")
5781
+ });
5742
5782
  var UseCaseDiscoveryMemoryGetInputSchema = z.object({
5743
5783
  projectId: IdSchema.describe("Project ID (UUID) to get use case discovery memory for")
5744
5784
  });
@@ -6635,16 +6675,69 @@ function mapSecretList(response) {
6635
6675
  return response.data.map(toSecretMetadata);
6636
6676
  }
6637
6677
  function mapSecret(response) {
6638
- const isSingleSecret = typeof response.data === "object" && response.data !== null && !Array.isArray(response.data);
6639
- if (!isSingleSecret) {
6678
+ if (!isSingleObject(response.data)) {
6640
6679
  throw new GatewayError({
6641
6680
  code: "UPSTREAM_ERROR" /* UPSTREAM_ERROR */,
6642
- message: `Secret response was not a single secret (got ${Array.isArray(response.data) ? "array" : typeof response.data}).`,
6681
+ message: `Secret response was not a single secret (got ${describeUpstreamBody(response.data)}).`,
6643
6682
  statusCode: response.statusCode
6644
6683
  });
6645
6684
  }
6646
6685
  return toSecretMetadata(response.data);
6647
6686
  }
6687
+ function mapSecretGroupListing(response) {
6688
+ const isGroupListing = isSingleObject(response.data) && Array.isArray(response.data.groups) && Array.isArray(response.data.adhocSecrets);
6689
+ if (!isGroupListing) {
6690
+ throw new GatewayError({
6691
+ code: "UPSTREAM_ERROR" /* UPSTREAM_ERROR */,
6692
+ message: `Secret group list response was not { groups, adhocSecrets } (got ${describeUpstreamBody(response.data)}).`,
6693
+ statusCode: response.statusCode
6694
+ });
6695
+ }
6696
+ const upstreamListing = response.data;
6697
+ return {
6698
+ groups: upstreamListing.groups.map(toSecretGroupSummary),
6699
+ adhocSecrets: upstreamListing.adhocSecrets.map(toSecretMetadata)
6700
+ };
6701
+ }
6702
+ function mapSecretGroupSummary(response) {
6703
+ const isGroupSummary = isSingleObject(response.data) && isSingleObject(response.data.group) && Array.isArray(response.data.members);
6704
+ if (!isGroupSummary) {
6705
+ throw new GatewayError({
6706
+ code: "UPSTREAM_ERROR" /* UPSTREAM_ERROR */,
6707
+ message: `Secret group response was not { group, members } (got ${describeUpstreamBody(response.data)}).`,
6708
+ statusCode: response.statusCode
6709
+ });
6710
+ }
6711
+ return toSecretGroupSummary(response.data);
6712
+ }
6713
+ function isSingleObject(upstreamBody) {
6714
+ return typeof upstreamBody === "object" && upstreamBody !== null && !Array.isArray(upstreamBody);
6715
+ }
6716
+ function describeUpstreamBody(upstreamBody) {
6717
+ return Array.isArray(upstreamBody) ? "array" : typeof upstreamBody;
6718
+ }
6719
+ function toSecretGroupSummary(upstreamSummary) {
6720
+ return {
6721
+ group: toSecretGroupMetadata(upstreamSummary.group),
6722
+ members: upstreamSummary.members.map((upstreamMember) => ({
6723
+ field: upstreamMember.field,
6724
+ secret: toSecretMetadata(upstreamMember.secret)
6725
+ }))
6726
+ };
6727
+ }
6728
+ function toSecretGroupMetadata(upstreamGroup) {
6729
+ return {
6730
+ id: upstreamGroup.id,
6731
+ projectId: upstreamGroup.projectId,
6732
+ secretType: upstreamGroup.secretType,
6733
+ groupName: upstreamGroup.groupName,
6734
+ description: upstreamGroup.description,
6735
+ createdAt: upstreamGroup.createdAt,
6736
+ createdBy: upstreamGroup.createdBy,
6737
+ lastModifiedAt: upstreamGroup.lastModifiedAt,
6738
+ lastModifiedBy: upstreamGroup.lastModifiedBy
6739
+ };
6740
+ }
6648
6741
  function toSecretMetadata(upstreamSecret) {
6649
6742
  return {
6650
6743
  id: upstreamSecret.id,
@@ -6652,6 +6745,8 @@ function toSecretMetadata(upstreamSecret) {
6652
6745
  secretName: upstreamSecret.secretName,
6653
6746
  description: upstreamSecret.description,
6654
6747
  source: upstreamSecret.source,
6748
+ groupId: upstreamSecret.groupId,
6749
+ field: upstreamSecret.field,
6655
6750
  createdAt: upstreamSecret.createdAt,
6656
6751
  createdBy: upstreamSecret.createdBy,
6657
6752
  lastModifiedAt: upstreamSecret.lastModifiedAt,
@@ -7822,6 +7917,81 @@ var secretTools = [
7822
7917
  };
7823
7918
  },
7824
7919
  mapFromUpstream: mapSecret
7920
+ },
7921
+ {
7922
+ name: "muggle-remote-secret-type-list",
7923
+ description: "List the types a secret group can have, each with its fields in order: field key, label (which carries the expected format, e.g. 'Expiry (MM/YY)'), whether it is required, and whether it is masked. Call before muggle-remote-secret-group-create or muggle-remote-secret-group-update. Response shape: [{ secretType, label, fields: [{ field, label, isRequired, isMasked }] }].",
7924
+ inputSchema: EmptyInputSchema,
7925
+ mapToUpstream: () => {
7926
+ return {
7927
+ method: "GET",
7928
+ path: `${MUGGLE_TEST_PREFIX}/secret-types`
7929
+ };
7930
+ }
7931
+ },
7932
+ {
7933
+ name: "muggle-remote-secret-group-list",
7934
+ description: "List a project's typed secret groups, each with its member secrets in field order, plus the project's ungrouped user-provided secrets. Secret values are never returned. Response shape: { groups: [{ group, members: [{ field, secret }] }], adhocSecrets: [secret] }.",
7935
+ inputSchema: SecretGroupListInputSchema,
7936
+ mapToUpstream: (input) => {
7937
+ const toolInput = input;
7938
+ return {
7939
+ method: "GET",
7940
+ path: `${MUGGLE_TEST_PREFIX}/secret-groups`,
7941
+ queryParams: { projectId: toolInput.projectId }
7942
+ };
7943
+ },
7944
+ mapFromUpstream: mapSecretGroupListing
7945
+ },
7946
+ {
7947
+ name: "muggle-remote-secret-group-create",
7948
+ description: "Create a typed secret group for a project: one named credential, such as a login or a payment card, whose fields are stored as member secrets and offered to test runs together. Pass `fields` as a map of field name to value; call muggle-remote-secret-type-list first for each secretType's fields, which are required, and their formats. Member secret names are the groupName slug plus the field ('Visa test' gives visa_test_card_number); a name that collides with an existing secret or group is rejected. Secret values are never returned.",
7949
+ inputSchema: SecretGroupCreateInputSchema,
7950
+ mapToUpstream: (input) => {
7951
+ const toolInput = input;
7952
+ return {
7953
+ method: "POST",
7954
+ path: `${MUGGLE_TEST_PREFIX}/secret-groups`,
7955
+ body: {
7956
+ projectId: toolInput.projectId,
7957
+ secretType: toolInput.secretType,
7958
+ groupName: toolInput.groupName,
7959
+ description: toolInput.description,
7960
+ fields: toolInput.fields
7961
+ }
7962
+ };
7963
+ },
7964
+ mapFromUpstream: mapSecretGroupSummary
7965
+ },
7966
+ {
7967
+ name: "muggle-remote-secret-group-update",
7968
+ description: "Update a secret group's description or field values; its secretType and groupName are fixed. In `fields`, a non-empty value sets the field (adding a missing optional one), an empty string clears an optional field (a required field cannot be cleared), and an omitted field stays unchanged. Call muggle-remote-secret-type-list for each secretType's fields, which are required, and their formats. Secret values are never returned.",
7969
+ inputSchema: SecretGroupUpdateInputSchema,
7970
+ mapToUpstream: (input) => {
7971
+ const toolInput = input;
7972
+ const body = {};
7973
+ if (toolInput.description !== void 0) body.description = toolInput.description;
7974
+ if (toolInput.fields !== void 0) body.fields = toolInput.fields;
7975
+ return {
7976
+ method: "PUT",
7977
+ path: `${MUGGLE_TEST_PREFIX}/secret-groups/${toolInput.groupId}`,
7978
+ body
7979
+ };
7980
+ },
7981
+ mapFromUpstream: mapSecretGroupSummary
7982
+ },
7983
+ {
7984
+ name: "muggle-remote-secret-group-delete",
7985
+ description: "Delete a secret group together with its member secrets. This is a soft delete. Secret values are never returned.",
7986
+ inputSchema: SecretGroupDeleteInputSchema,
7987
+ mapToUpstream: (input) => {
7988
+ const toolInput = input;
7989
+ return {
7990
+ method: "DELETE",
7991
+ path: `${MUGGLE_TEST_PREFIX}/secret-groups/${toolInput.groupId}`
7992
+ };
7993
+ },
7994
+ mapFromUpstream: mapSecretGroupSummary
7825
7995
  }
7826
7996
  ];
7827
7997
  var prdFileTools = [
@@ -9702,8 +9872,15 @@ __export(e2e_exports2, {
9702
9872
  RunSettingsListInputSchema: () => RunSettingsListInputSchema,
9703
9873
  SecretCreateInputSchema: () => SecretCreateInputSchema,
9704
9874
  SecretDeleteInputSchema: () => SecretDeleteInputSchema,
9875
+ SecretFieldEnum: () => SecretFieldEnum,
9705
9876
  SecretGetInputSchema: () => SecretGetInputSchema,
9877
+ SecretGroupCreateInputSchema: () => SecretGroupCreateInputSchema,
9878
+ SecretGroupDeleteInputSchema: () => SecretGroupDeleteInputSchema,
9879
+ SecretGroupFieldValuesSchema: () => SecretGroupFieldValuesSchema,
9880
+ SecretGroupListInputSchema: () => SecretGroupListInputSchema,
9881
+ SecretGroupUpdateInputSchema: () => SecretGroupUpdateInputSchema,
9706
9882
  SecretListInputSchema: () => SecretListInputSchema,
9883
+ SecretTypeEnum: () => SecretTypeEnum,
9707
9884
  SecretUpdateInputSchema: () => SecretUpdateInputSchema,
9708
9885
  StripePaymentMethodIdSchema: () => StripePaymentMethodIdSchema,
9709
9886
  TestCaseAncestorsGetInputSchema: () => TestCaseAncestorsGetInputSchema,
package/dist/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { runCli } from './chunk-DLNSKLZD.js';
3
- import './chunk-H62MFQKC.js';
2
+ import { runCli } from './chunk-4JVYLRXD.js';
3
+ import './chunk-MJ34HBWC.js';
4
4
 
5
5
  // src/cli/main.ts
6
6
  runCli().catch((error) => {
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- export { src_exports as commands, createUnifiedMcpServer, server_exports as server } from './chunk-DLNSKLZD.js';
2
- export { createChildLogger, e2e_exports as e2e, getConfig, getLocalQaTools, getLogger, getQaTools, local_exports as localQa, mcp_exports as mcp, e2e_exports as qa, src_exports as shared } from './chunk-H62MFQKC.js';
1
+ export { src_exports as commands, createUnifiedMcpServer, server_exports as server } from './chunk-4JVYLRXD.js';
2
+ export { createChildLogger, e2e_exports as e2e, getConfig, getLocalQaTools, getLogger, getQaTools, local_exports as localQa, mcp_exports as mcp, e2e_exports as qa, src_exports as shared } from './chunk-MJ34HBWC.js';
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "muggle",
3
3
  "description": "Real-browser E2E acceptance for your coding agent: test the flows you changed and open the PR with screenshots. Built for flows other tools can't reach: managed test identities with live inboxes (magic links, email OTP and 2FA, verification mail, password resets), an encrypted secret store for login and test credentials, and a test graph that runs prerequisite flows first. Plain-English tests become replayable scripts on localhost or preview URLs.",
4
- "version": "5.26.0-staging.210",
4
+ "version": "5.26.0-staging.212",
5
5
  "author": {
6
6
  "name": "Muggle AI",
7
7
  "email": "support@muggle-ai.com"
@@ -4,7 +4,7 @@
4
4
  "command": "npx",
5
5
  "args": [
6
6
  "-y",
7
- "@muggleai/works@5.26.0-staging.210",
7
+ "@muggleai/works@5.26.0-staging.212",
8
8
  "serve"
9
9
  ],
10
10
  "env": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "muggle",
3
- "version": "5.26.0-staging.210",
3
+ "version": "5.26.0-staging.212",
4
4
  "description": "Real-browser E2E acceptance for your coding agent: test the flows you changed and open the PR with screenshots. Built for flows other tools can't reach: managed test identities with live inboxes (magic links, email OTP and 2FA, verification mail, password resets), an encrypted secret store for login and test credentials, and a test graph that runs prerequisite flows first. Plain-English tests become replayable scripts on localhost or preview URLs.",
5
5
  "author": {
6
6
  "name": "Muggle AI",
@@ -2,7 +2,7 @@
2
2
  "name": "muggle",
3
3
  "displayName": "Muggle AI",
4
4
  "description": "Real-browser E2E acceptance for your coding agent: test the flows you changed and open the PR with screenshots. Built for flows other tools can't reach: managed test identities with live inboxes (magic links, email OTP and 2FA, verification mail, password resets), an encrypted secret store for login and test credentials, and a test graph that runs prerequisite flows first. Plain-English tests become replayable scripts on localhost or preview URLs.",
5
- "version": "5.26.0-staging.210",
5
+ "version": "5.26.0-staging.212",
6
6
  "author": {
7
7
  "name": "Muggle AI",
8
8
  "email": "support@muggle-ai.com"
@@ -4,7 +4,7 @@
4
4
  "command": "npx",
5
5
  "args": [
6
6
  "-y",
7
- "@muggleai/works@5.26.0-staging.210",
7
+ "@muggleai/works@5.26.0-staging.212",
8
8
  "serve"
9
9
  ]
10
10
  }
@@ -18,7 +18,7 @@ Two invariants hold on every trigger, however the sweep was reached: it never se
18
18
 
19
19
  A watcher lives and dies with its session: monitors and `/loop` crons are both session-bound, so a session that ends or hits its usage limit takes every watch down with it. No poller outlives its session to act on a PR. This is deliberate: a review is addressed only inside a session that carries the context to address it, never by a headless process that would reply without that context.
20
20
 
21
- What does run out of session is the muggle watch service (`muggle watch`, a per-user scheduled job). It addresses nothing on any PR. For a slot registered in [`watch-registration.json`](state-schemas.md#watch-registrationjson) whose loop is gone while its owner is down, it resumes the **owning** session in the background. That session's reconcile, this procedure, re-arms the watch with its own context. Restarting an idle owner onto a newly installed build goes the same way — stop, then resume on reconcile — so the watchers come back with it. A slot whose PR went terminal while neither its loop nor its owner is running it finalizes itself, as Step 3 would, leaving the post-merge cleanup unrun. Everything else it finds (a dead watcher under a running owner, red CI, a stale branch) it only reports.
21
+ What does run out of session is the muggle watch service (`muggle watch`, a per-user scheduled job). It addresses nothing on any PR. For a slot registered in [`watch-registration.json`](state-schemas.md#watch-registrationjson) whose loop is gone while its owner is down, or idle in the background between turns, it resumes the **owning** session in the background, stopping an idle one first. That session's reconcile, this procedure, re-arms the watch with its own context. Restarting an idle owner onto a newly installed build goes the same way — stop, then resume on reconcile — so the watchers come back with it. A slot whose PR went terminal while neither its loop nor its owner is running it finalizes itself, as Step 3 would, leaving the post-merge cleanup unrun. Everything else it finds (a dead watcher under an owner mid-turn, waiting on its user, or open in a terminal; red CI; a stale branch) it only reports.
22
22
 
23
23
  **Ownership is session-scoped too, and that is what bounds recovery.** Each slot records the session that armed it in [`owner.json`](state-schemas.md#ownerjson). Step 3.6 re-arms only slots the running session owns — watchers it armed itself, whose poller died under it. A slot owned by another session, or by none, is **never** re-armed here however dead its poller looks. The same argument that forbids a headless daemon forbids a fresh session inheriting a stranger's PR: it would be picking up review work it has no context for, on a branch it never built, and every push it made would be as context-blind as the daemon the design already rejected. Adoption exists precisely so that step is a deliberate act by the owner ([`adopt.md`](adopt.md)) rather than a side effect of starting a session.
24
24
 
@@ -59,7 +59,7 @@ The slot's opt-in to recovery by the muggle watch service (`muggle watch`, a per
59
59
  }
60
60
  ```
61
61
 
62
- Recovery requires all of: the slot is registered, the PR is open on GitHub, no loop process carries the slot's `--slot` path, the heartbeat is older than the rollover hand-off, `polling.disabled` is absent, and the `owner.json` session is not running. The service then resumes that session in the background from the project dir its transcript records, starting it on `/muggle:muggle-pr-followup reconcile`. Reconcile re-arms only the slots the session owns, so recovery never moves a PR to another session. One resume per owner covers every slot it owns. The service caps resumes per pass and per owner, then falls back to a desktop alert.
62
+ Recovery requires all of: the slot is registered, the PR is open on GitHub, no loop process carries the slot's `--slot` path, the heartbeat is older than the rollover hand-off, `polling.disabled` is absent, and the `owner.json` session either has no running process or is a background session idle between turns. The service then resumes that session in the background from the project dir its transcript records, starting it on `/muggle:muggle-pr-followup reconcile`. An idle running owner is stopped first, and only after a throwaway background launch confirms Claude will resume it in that workspace. Reconcile re-arms only the slots the session owns, so recovery never moves a PR to another session. One resume per owner covers every slot it owns. The service caps resumes per pass and per owner, then falls back to a desktop alert. A resume whose turn ended on the usage-limit notice doesn't count toward the per-owner cap.
63
63
 
64
64
  **Absent ⇒ observed only.** The service still reports on the slot's watcher, CI and branch standing, but never resumes its owner. Slots armed before this file existed stay that way until their next arm. The file lives in the slot, so a `.stopped` rename or a `result.md` retires it with the slot.
65
65
 
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "release": "5.18.0",
3
- "buildId": "run-210-1",
4
- "commitSha": "6ff9e102fd856da52beaf3081430c147a3587ceb",
5
- "buildTime": "2026-10-26T17:21:07Z",
3
+ "buildId": "run-212-1",
4
+ "commitSha": "1ce657314cba3cccddc786a3f289ccee7a891e1d",
5
+ "buildTime": "2026-10-26T17:52:13Z",
6
6
  "serviceName": "muggle-ai-works-mcp"
7
7
  }
@@ -1 +1 @@
1
- export { ACTION_SCRIPT_FILE_NAME, BASE_REMOTE_NAME, BLOCKING_FRESHNESS_VERDICTS, BRANCH_CREATION_REFLOG_PREFIX, BUSY_EXIT_CODE, CheckoutFreshnessVerdict, DEFAULT_PREFERENCES, ELECTRON_APP_EXECUTABLE_PATH_SEGMENTS, ElectronAppPlatform, ElectronAppReleaseStream, HTML_VIEW_OFFER_LINE, MAX_LISTED_INHERITED_COMMITS, ONBOARDING_BLANKET_OPTIONS, ONBOARDING_CHOICE_GROUPS, ONBOARDING_MAX_OFFERS, ONBOARDING_PRIMER_BULLETS, ONBOARDING_PRIMER_HEADLINE, ONBOARDING_TOGGLE_GROUPS, ONBOARDING_TOGGLE_PROMPT, ONBOARDING_UNSELECTED_TOGGLE_VALUE, OnboardingBlanketChoice, OnboardingGroupKind, PREFERENCES_FILE_NAME, PREFERENCES_PROJECT_DIR_NAME, PREFERENCES_SCHEMA, PREFERENCES_VERSION, PREFERENCE_ALLOWED_VALUES, PreferenceKey, PreferenceValue, ProjectPreferencesReconcileOutcome, RUN_SESSIONS_DIR_NAME, RUN_VIEW_DASHBOARD_LINK_LABEL, RunViewError, RuntimeTarget, SCREENSHOT_DIR_RELATIVE_PATH, SCREENSHOT_FILE_EXTENSION, StackCheckVerdict, StackClaimVerdict, StackPortAction, WATCHER_LIFETIME_SECONDS, WATCHER_LIFETIME_UNBOUNDED_SECONDS, applyOnboardingAnswers, assertDeviceCodeClientProvisioned, buildElectronAppChecksumsUrl, buildElectronAppDirName, buildElectronAppReleaseAssetUrl, buildElectronAppReleaseTag, buildOnboardingPlan, buildToolInputJsonSchema, calculateFileChecksum, checkServiceStack, claimServiceStack, completeOnboarding, createApiKeyWithToken, createChildLogger, decideStackClaim, decideStackRelease, decideStackRenewal, deleteApiKeyData, deleteCredentials, e2e_exports as e2e, evaluateCheckoutFreshness, formatPreferencesOneLiner, getActiveElectronAppReleaseStream, getActiveRuntimeTarget, getApiKey, getApiKeyFilePath, getAuthService, getBundledElectronAppVersion, getCallerCredentials, getCallerCredentialsAsync, getChecksumForPlatform, getConfig, getCredentialsFilePath, getDashboardBaseUrl, getDataDir2 as getDataDir, getDownloadBaseUrl, getElectronAppChecksums, getElectronAppDir, getElectronAppReleaseTagPrefix, getElectronAppSignedFromVersion, getElectronAppVersion, getElectronAppVersionSource, getLocalQaTools, getLogger, getOnboardingToggleKeys, getPlatformKey, getQaTools, getReleaseSignerIdentityUri, getRunSessionsDir, getValidApiKeyData, getValidCredentials, hasApiKey, isElectronAppInstalled, isElectronAppPlatform, isFirstRun, loadApiKeyData, loadCredentials, local_exports as localQa, markOnboardingCompleted, mcp_exports as mcp, needsConflict, needsOnboarding, openBrowserUrl, parseElectronAppDirName, performLogin, performLogout, pollDeviceCode, portOfUrl, e2e_exports as qa, readPreferencesMetadata, readRunView, readServiceStackStatus, reconcileProjectPreferences, recordOnboardingSkip, releaseServiceStack, renderRunViewHtml, renderRunViewText, resetConfig, resetLogger, resetPreference, resolveActiveProfile, resolveActiveReleaseStream, resolveActiveReleaseTagPrefix, resolveBlanketPreferences, resolveElectronAppExecutablePath, resolveElectronAppPathOrNull, resolveOnboardingAnswers, resolvePreferences, resolveRunSessionPath, resolveRuntimeTarget, resolveTogglePreferences, runGitCommand, saveApiKey, saveApiKeyData, saveCredentials, startDeviceCodeFlow, toDisplayRef, toolRequiresAuth, validatePreference, verifyFileChecksum, writePreferences, writePreferencesWithMetadata, writeRunViewHtml } from './chunk-H62MFQKC.js';
1
+ export { ACTION_SCRIPT_FILE_NAME, BASE_REMOTE_NAME, BLOCKING_FRESHNESS_VERDICTS, BRANCH_CREATION_REFLOG_PREFIX, BUSY_EXIT_CODE, CheckoutFreshnessVerdict, DEFAULT_PREFERENCES, ELECTRON_APP_EXECUTABLE_PATH_SEGMENTS, ElectronAppPlatform, ElectronAppReleaseStream, HTML_VIEW_OFFER_LINE, MAX_LISTED_INHERITED_COMMITS, ONBOARDING_BLANKET_OPTIONS, ONBOARDING_CHOICE_GROUPS, ONBOARDING_MAX_OFFERS, ONBOARDING_PRIMER_BULLETS, ONBOARDING_PRIMER_HEADLINE, ONBOARDING_TOGGLE_GROUPS, ONBOARDING_TOGGLE_PROMPT, ONBOARDING_UNSELECTED_TOGGLE_VALUE, OnboardingBlanketChoice, OnboardingGroupKind, PREFERENCES_FILE_NAME, PREFERENCES_PROJECT_DIR_NAME, PREFERENCES_SCHEMA, PREFERENCES_VERSION, PREFERENCE_ALLOWED_VALUES, PreferenceKey, PreferenceValue, ProjectPreferencesReconcileOutcome, RUN_SESSIONS_DIR_NAME, RUN_VIEW_DASHBOARD_LINK_LABEL, RunViewError, RuntimeTarget, SCREENSHOT_DIR_RELATIVE_PATH, SCREENSHOT_FILE_EXTENSION, StackCheckVerdict, StackClaimVerdict, StackPortAction, WATCHER_LIFETIME_SECONDS, WATCHER_LIFETIME_UNBOUNDED_SECONDS, applyOnboardingAnswers, assertDeviceCodeClientProvisioned, buildElectronAppChecksumsUrl, buildElectronAppDirName, buildElectronAppReleaseAssetUrl, buildElectronAppReleaseTag, buildOnboardingPlan, buildToolInputJsonSchema, calculateFileChecksum, checkServiceStack, claimServiceStack, completeOnboarding, createApiKeyWithToken, createChildLogger, decideStackClaim, decideStackRelease, decideStackRenewal, deleteApiKeyData, deleteCredentials, e2e_exports as e2e, evaluateCheckoutFreshness, formatPreferencesOneLiner, getActiveElectronAppReleaseStream, getActiveRuntimeTarget, getApiKey, getApiKeyFilePath, getAuthService, getBundledElectronAppVersion, getCallerCredentials, getCallerCredentialsAsync, getChecksumForPlatform, getConfig, getCredentialsFilePath, getDashboardBaseUrl, getDataDir2 as getDataDir, getDownloadBaseUrl, getElectronAppChecksums, getElectronAppDir, getElectronAppReleaseTagPrefix, getElectronAppSignedFromVersion, getElectronAppVersion, getElectronAppVersionSource, getLocalQaTools, getLogger, getOnboardingToggleKeys, getPlatformKey, getQaTools, getReleaseSignerIdentityUri, getRunSessionsDir, getValidApiKeyData, getValidCredentials, hasApiKey, isElectronAppInstalled, isElectronAppPlatform, isFirstRun, loadApiKeyData, loadCredentials, local_exports as localQa, markOnboardingCompleted, mcp_exports as mcp, needsConflict, needsOnboarding, openBrowserUrl, parseElectronAppDirName, performLogin, performLogout, pollDeviceCode, portOfUrl, e2e_exports as qa, readPreferencesMetadata, readRunView, readServiceStackStatus, reconcileProjectPreferences, recordOnboardingSkip, releaseServiceStack, renderRunViewHtml, renderRunViewText, resetConfig, resetLogger, resetPreference, resolveActiveProfile, resolveActiveReleaseStream, resolveActiveReleaseTagPrefix, resolveBlanketPreferences, resolveElectronAppExecutablePath, resolveElectronAppPathOrNull, resolveOnboardingAnswers, resolvePreferences, resolveRunSessionPath, resolveRuntimeTarget, resolveTogglePreferences, runGitCommand, saveApiKey, saveApiKeyData, saveCredentials, startDeviceCodeFlow, toDisplayRef, toolRequiresAuth, validatePreference, verifyFileChecksum, writePreferences, writePreferencesWithMetadata, writeRunViewHtml } from './chunk-MJ34HBWC.js';
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@muggleai/works",
3
3
  "mcpName": "io.github.multiplex-ai/muggle",
4
- "version": "5.26.0-staging.210",
4
+ "version": "5.26.0-staging.212",
5
5
  "description": "13 years of Microsoft hyperscale engineering, packaged as a harness for your AI coding agent.",
6
6
  "type": "module",
7
7
  "main": "dist/index.js",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "muggle",
3
3
  "description": "Real-browser E2E acceptance for your coding agent: test the flows you changed and open the PR with screenshots. Built for flows other tools can't reach: managed test identities with live inboxes (magic links, email OTP and 2FA, verification mail, password resets), an encrypted secret store for login and test credentials, and a test graph that runs prerequisite flows first. Plain-English tests become replayable scripts on localhost or preview URLs.",
4
- "version": "5.26.0-staging.210",
4
+ "version": "5.26.0-staging.212",
5
5
  "author": {
6
6
  "name": "Muggle AI",
7
7
  "email": "support@muggle-ai.com"
@@ -4,7 +4,7 @@
4
4
  "command": "npx",
5
5
  "args": [
6
6
  "-y",
7
- "@muggleai/works@5.26.0-staging.210",
7
+ "@muggleai/works@5.26.0-staging.212",
8
8
  "serve"
9
9
  ],
10
10
  "env": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "muggle",
3
- "version": "5.26.0-staging.210",
3
+ "version": "5.26.0-staging.212",
4
4
  "description": "Real-browser E2E acceptance for your coding agent: test the flows you changed and open the PR with screenshots. Built for flows other tools can't reach: managed test identities with live inboxes (magic links, email OTP and 2FA, verification mail, password resets), an encrypted secret store for login and test credentials, and a test graph that runs prerequisite flows first. Plain-English tests become replayable scripts on localhost or preview URLs.",
5
5
  "author": {
6
6
  "name": "Muggle AI",
@@ -2,7 +2,7 @@
2
2
  "name": "muggle",
3
3
  "displayName": "Muggle AI",
4
4
  "description": "Real-browser E2E acceptance for your coding agent: test the flows you changed and open the PR with screenshots. Built for flows other tools can't reach: managed test identities with live inboxes (magic links, email OTP and 2FA, verification mail, password resets), an encrypted secret store for login and test credentials, and a test graph that runs prerequisite flows first. Plain-English tests become replayable scripts on localhost or preview URLs.",
5
- "version": "5.26.0-staging.210",
5
+ "version": "5.26.0-staging.212",
6
6
  "author": {
7
7
  "name": "Muggle AI",
8
8
  "email": "support@muggle-ai.com"
package/plugin/.mcp.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "command": "npx",
5
5
  "args": [
6
6
  "-y",
7
- "@muggleai/works@5.26.0-staging.210",
7
+ "@muggleai/works@5.26.0-staging.212",
8
8
  "serve"
9
9
  ]
10
10
  }
@@ -18,7 +18,7 @@ Two invariants hold on every trigger, however the sweep was reached: it never se
18
18
 
19
19
  A watcher lives and dies with its session: monitors and `/loop` crons are both session-bound, so a session that ends or hits its usage limit takes every watch down with it. No poller outlives its session to act on a PR. This is deliberate: a review is addressed only inside a session that carries the context to address it, never by a headless process that would reply without that context.
20
20
 
21
- What does run out of session is the muggle watch service (`muggle watch`, a per-user scheduled job). It addresses nothing on any PR. For a slot registered in [`watch-registration.json`](state-schemas.md#watch-registrationjson) whose loop is gone while its owner is down, it resumes the **owning** session in the background. That session's reconcile, this procedure, re-arms the watch with its own context. Restarting an idle owner onto a newly installed build goes the same way — stop, then resume on reconcile — so the watchers come back with it. A slot whose PR went terminal while neither its loop nor its owner is running it finalizes itself, as Step 3 would, leaving the post-merge cleanup unrun. Everything else it finds (a dead watcher under a running owner, red CI, a stale branch) it only reports.
21
+ What does run out of session is the muggle watch service (`muggle watch`, a per-user scheduled job). It addresses nothing on any PR. For a slot registered in [`watch-registration.json`](state-schemas.md#watch-registrationjson) whose loop is gone while its owner is down, or idle in the background between turns, it resumes the **owning** session in the background, stopping an idle one first. That session's reconcile, this procedure, re-arms the watch with its own context. Restarting an idle owner onto a newly installed build goes the same way — stop, then resume on reconcile — so the watchers come back with it. A slot whose PR went terminal while neither its loop nor its owner is running it finalizes itself, as Step 3 would, leaving the post-merge cleanup unrun. Everything else it finds (a dead watcher under an owner mid-turn, waiting on its user, or open in a terminal; red CI; a stale branch) it only reports.
22
22
 
23
23
  **Ownership is session-scoped too, and that is what bounds recovery.** Each slot records the session that armed it in [`owner.json`](state-schemas.md#ownerjson). Step 3.6 re-arms only slots the running session owns — watchers it armed itself, whose poller died under it. A slot owned by another session, or by none, is **never** re-armed here however dead its poller looks. The same argument that forbids a headless daemon forbids a fresh session inheriting a stranger's PR: it would be picking up review work it has no context for, on a branch it never built, and every push it made would be as context-blind as the daemon the design already rejected. Adoption exists precisely so that step is a deliberate act by the owner ([`adopt.md`](adopt.md)) rather than a side effect of starting a session.
24
24
 
@@ -59,7 +59,7 @@ The slot's opt-in to recovery by the muggle watch service (`muggle watch`, a per
59
59
  }
60
60
  ```
61
61
 
62
- Recovery requires all of: the slot is registered, the PR is open on GitHub, no loop process carries the slot's `--slot` path, the heartbeat is older than the rollover hand-off, `polling.disabled` is absent, and the `owner.json` session is not running. The service then resumes that session in the background from the project dir its transcript records, starting it on `/muggle:muggle-pr-followup reconcile`. Reconcile re-arms only the slots the session owns, so recovery never moves a PR to another session. One resume per owner covers every slot it owns. The service caps resumes per pass and per owner, then falls back to a desktop alert.
62
+ Recovery requires all of: the slot is registered, the PR is open on GitHub, no loop process carries the slot's `--slot` path, the heartbeat is older than the rollover hand-off, `polling.disabled` is absent, and the `owner.json` session either has no running process or is a background session idle between turns. The service then resumes that session in the background from the project dir its transcript records, starting it on `/muggle:muggle-pr-followup reconcile`. An idle running owner is stopped first, and only after a throwaway background launch confirms Claude will resume it in that workspace. Reconcile re-arms only the slots the session owns, so recovery never moves a PR to another session. One resume per owner covers every slot it owns. The service caps resumes per pass and per owner, then falls back to a desktop alert. A resume whose turn ended on the usage-limit notice doesn't count toward the per-owner cap.
63
63
 
64
64
  **Absent ⇒ observed only.** The service still reports on the slot's watcher, CI and branch standing, but never resumes its owner. Slots armed before this file existed stay that way until their next arm. The file lives in the slot, so a `.stopped` rename or a `result.md` retires it with the slot.
65
65
 
@@ -4,9 +4,9 @@ A standing per-user scheduled job that runs `muggle watch tick` every few minute
4
4
 
5
5
  - **Tracks** active Claude Code sessions (`claude agents --json`) and Codex sessions (recent `~/.codex/sessions` rollouts). It also tracks their processes: claude, codex, muggle MCP servers, and PR watch loops. Each live Claude session is stamped with when it last loaded its plugins (its process start, or its newest muggle MCP server start after a `/reload-plugins`) and the muggle works build installed then, read off `~/.muggle-ai/postinstall.log`.
6
6
  - **Checks every open PR-watch slot** under `~/.muggle-ai/muggle-do/sessions/`. Is its loop running, and heard by a live session? Is CI red? Is the branch behind or conflicting? Are review threads unresolved?
7
- - **Keeps registered watchers running.** A slot carrying `watch-registration.json` (written by `pr-watch-arm.sh` on every arm) has its owner session resumed in the background when its loop is gone and the owner is down. The resumed session's `/muggle:muggle-pr-followup reconcile` re-arms it with that session's own context. The service never addresses a review, pushes, or kills a process.
7
+ - **Keeps registered watchers running.** A slot carrying `watch-registration.json` (written by `pr-watch-arm.sh` on every arm) has its owner session resumed in the background when its loop is gone and the owner is down, or idle in the background (stopped first, once a throwaway launch confirms Claude will resume it there). A resume that only hit the usage limit is retried without counting against the per-owner cap. The resumed session's `/muggle:muggle-pr-followup reconcile` re-arms it with that session's own context. The service never addresses a review, pushes, or kills a process.
8
8
  - **Closes out finished slots.** A slot whose PR GitHub reports merged or closed, with no loop and no running owner, is finalized the way a watcher's terminal tick would: `prs.json` takes the state, `followup.log` the terminal line, and `result.md` is written. Only local files change; post-merge cleanup is left to a session and recorded as not run.
9
- - **Keeps sessions on the installed build.** A session loaded before the newest global install (or a later user-scope plugin update) is behind. Idle background sessions are restarted onto the new build, up to 3 per tick: a session that owns open PR watches is stopped and resumed on `/muggle:muggle-pr-followup reconcile`, so its watchers come back with it; any other is respawned. Before either, a throwaway background launch in the session's workspace confirms Claude will bring it back; a workspace that refuses is left running and named once. Busy or waiting sessions wait for a later tick, and terminal sessions get one notification to run `/reload-plugins`. No interface runs a slash command inside another session.
9
+ - **Keeps sessions on the installed build.** A session loaded before the newest global install (or a later user-scope plugin update) is behind. Idle background sessions are restarted onto the new build, up to 3 per tick: a session that owns open PR watches is stopped and resumed on `/muggle:muggle-pr-followup reconcile`, so its watchers come back with it; any other is respawned. A resume waits for the stopped process to exit and passes no flag beyond `--bg`, so the session continues under its own id and name. Resuming a session that is still running, or adding flags, starts a copy that the agent view lists beside the original. Before either, a throwaway background launch in the session's workspace confirms Claude will bring it back; a workspace that refuses is left running and named once. Busy or waiting sessions wait for a later tick, and terminal sessions get one notification to run `/reload-plugins`. No interface runs a slash command inside another session.
10
10
  - **Records and alerts.** Results go to `status.json` (last snapshot, with open-PR coverage per repo), `state.json` (active findings, recovery attempts, reload progress) and `events.jsonl` (raise/clear/resume/respawn/close-out history) under `~/.muggle-ai/watch/`. New alerts raise one desktop notification per tick.
11
11
 
12
12
  ## Install