@muggleai/works 5.26.0-staging.209 → 5.26.0-staging.211

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/{chunk-PQVRAFNE.js → chunk-3Y6U6TRB.js} +336 -107
  3. package/dist/{chunk-ZR7KLGHQ.js → chunk-H62MFQKC.js} +597 -26
  4. package/dist/cli.js +2 -2
  5. package/dist/index.js +2 -2
  6. package/dist/plugin/.claude-plugin/plugin.json +1 -1
  7. package/dist/plugin/.codex-mcp.json +1 -1
  8. package/dist/plugin/.codex-plugin/plugin.json +1 -1
  9. package/dist/plugin/.cursor-plugin/plugin.json +1 -1
  10. package/dist/plugin/.mcp.json +1 -1
  11. package/dist/plugin/agents/test-prepare-runner.md +1 -1
  12. package/dist/plugin/skills/_shared/dev-loop/run.md +2 -0
  13. package/dist/plugin/skills/muggle-pr-followup/reconcile.md +1 -1
  14. package/dist/plugin/skills/muggle-pr-followup/state-schemas.md +1 -1
  15. package/dist/plugin/skills/muggle-test-prepare/SKILL.md +6 -3
  16. package/dist/plugin/skills/muggle-test-prepare/steps/check-running.md +1 -0
  17. package/dist/plugin/skills/muggle-test-prepare/steps/claim-stack.md +43 -0
  18. package/dist/plugin/skills/muggle-test-prepare/steps/replay-or-learn.md +1 -1
  19. package/dist/release-manifest.json +3 -3
  20. package/dist/src-A45WRSIF.js +1 -0
  21. package/package.json +1 -1
  22. package/plugin/.claude-plugin/plugin.json +1 -1
  23. package/plugin/.codex-mcp.json +1 -1
  24. package/plugin/.codex-plugin/plugin.json +1 -1
  25. package/plugin/.cursor-plugin/plugin.json +1 -1
  26. package/plugin/.mcp.json +1 -1
  27. package/plugin/agents/test-prepare-runner.md +1 -1
  28. package/plugin/skills/_shared/dev-loop/run.md +2 -0
  29. package/plugin/skills/muggle-pr-followup/reconcile.md +1 -1
  30. package/plugin/skills/muggle-pr-followup/state-schemas.md +1 -1
  31. package/plugin/skills/muggle-test-prepare/SKILL.md +6 -3
  32. package/plugin/skills/muggle-test-prepare/steps/check-running.md +1 -0
  33. package/plugin/skills/muggle-test-prepare/steps/claim-stack.md +43 -0
  34. package/plugin/skills/muggle-test-prepare/steps/replay-or-learn.md +1 -1
  35. package/scripts/muggle-watch/README.md +2 -2
  36. package/dist/src-J2TJ76XG.js +0 -1
@@ -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, resolvePreferences, OnboardingBlanketChoice, PreferenceKey, getDataDir } from './chunk-ZR7KLGHQ.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-H62MFQKC.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-J2TJ76XG.js');
1071
+ const mcps = await import('./src-A45WRSIF.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,
@@ -3684,6 +3691,99 @@ The archive may be corrupted or in an unexpected format.`
3684
3691
  process.exit(1);
3685
3692
  }
3686
3693
  }
3694
+
3695
+ // src/cli/service-stack.ts
3696
+ var NEED_PATTERN = /^(\d+)=(.+?)(?:@([0-9a-f]{7,40}))?$/i;
3697
+ function parseStackNeed(value) {
3698
+ const match = NEED_PATTERN.exec(value.trim());
3699
+ if (!match) throw new Error(`--need "${value}" is not <port>=<run-dir>[@<sha>]`);
3700
+ return { port: Number(match[1]), runDir: match[2], headSha: match[3] };
3701
+ }
3702
+ function renderStackClaimSummary(report) {
3703
+ if (report.verdict === "GRANTED" /* Granted */) {
3704
+ const lines2 = [`${report.verdict}: the stack is this checkout's to use (${report.cwd})`];
3705
+ for (const port of report.plan) {
3706
+ const current = port.current ? ` \u2014 now ${port.current.dir} @ ${shortSha(port.current.headSha)} (PID ${port.current.pid})` : "";
3707
+ lines2.push(`${port.action} ${port.port}: ${port.runDir} @ ${shortSha(port.headSha)}${current}`);
3708
+ }
3709
+ for (const peer of report.sharedWith) lines2.push(`shared with: ${peer}`);
3710
+ return lines2.join("\n");
3711
+ }
3712
+ const lines = [`${report.verdict}: place ${report.position} of ${report.queueLength} in line`];
3713
+ for (const blocker of report.blockers) {
3714
+ const who = blocker.blockingLabel ? `${blocker.blockingLabel} (${blocker.blockingCwd})` : blocker.blockingCwd;
3715
+ const how = blocker.isQueuedAhead ? "is ahead in line for" : "holds";
3716
+ const heldFor = blocker.isQueuedAhead ? "" : ` (for ${seconds(blocker.heldForMs ?? 0)})`;
3717
+ lines.push(`port ${blocker.port}: ${who} ${how} ${blocker.needsRunDir} @ ${shortSha(blocker.needsHeadSha)}${heldFor}`);
3718
+ }
3719
+ lines.push(`retry in ~${seconds(report.retryAfterMs ?? 0)}; your place is kept while you keep asking`);
3720
+ return lines.join("\n");
3721
+ }
3722
+ function renderStackCheckSummary(report) {
3723
+ const lines = [`${report.verdict}: ${report.reason}`];
3724
+ for (const mismatch of report.mismatches) {
3725
+ const actual = mismatch.actual ? `${mismatch.actual.dir} @ ${shortSha(mismatch.actual.headSha)}` : "nothing tracked";
3726
+ lines.push(`port ${mismatch.need.port}: claimed ${mismatch.need.runDir} @ ${shortSha(mismatch.need.headSha)}, serving ${actual}`);
3727
+ }
3728
+ return lines.join("\n");
3729
+ }
3730
+ function renderStackStatusSummary(report) {
3731
+ const now = Date.now();
3732
+ const lines = [`generation ${report.generation}`];
3733
+ if (report.leases.length === 0) lines.push("leases: none");
3734
+ for (const lease of report.leases) {
3735
+ const ports = lease.needs.map((need) => `${need.port}=${need.runDir}@${shortSha(need.headSha)}`).join(", ");
3736
+ lines.push(`lease: ${lease.label ?? lease.cwd} \u2014 ${ports} (held ${seconds(now - lease.grantedAt)}, renewed ${seconds(now - lease.lastSeenAt)} ago)`);
3737
+ }
3738
+ report.queue.forEach((ticket, index) => {
3739
+ const ports = ticket.needs.map((need) => need.port).join(", ");
3740
+ lines.push(`waiting ${index + 1}: ${ticket.label ?? ticket.cwd} \u2014 port ${ports} (asked ${seconds(now - ticket.lastSeenAt)} ago)`);
3741
+ });
3742
+ for (const service of report.services) {
3743
+ lines.push(`service: ${service.port} ${service.name} \u2014 ${service.dir} @ ${shortSha(service.headSha)} (PID ${service.pid})`);
3744
+ }
3745
+ return lines.join("\n");
3746
+ }
3747
+ async function stackClaimCommand(flags) {
3748
+ const needs = flags.need.map((value) => parseStackNeed(value));
3749
+ const report = await claimServiceStack({
3750
+ cwd: flags.cwd ?? process.cwd(),
3751
+ label: flags.label,
3752
+ needs,
3753
+ waitMs: flags.wait === void 0 ? void 0 : Number(flags.wait) * 1e3
3754
+ });
3755
+ writeReport({ json: flags.json, report, summary: renderStackClaimSummary(report) });
3756
+ if (report.verdict === "BUSY" /* Busy */) process.exitCode = BUSY_EXIT_CODE;
3757
+ }
3758
+ async function stackCheckCommand(flags) {
3759
+ const report = await checkServiceStack({
3760
+ cwd: flags.cwd ?? process.cwd(),
3761
+ port: flags.port === void 0 ? void 0 : Number(flags.port),
3762
+ shouldRenew: true
3763
+ });
3764
+ writeReport({ json: flags.json, report, summary: renderStackCheckSummary(report) });
3765
+ if (report.verdict === "STALE" /* Stale */ || report.verdict === "PEER_LEASE" /* PeerLease */) process.exitCode = 1;
3766
+ }
3767
+ async function stackReleaseCommand(flags) {
3768
+ const isReleased = await releaseServiceStack({ cwd: flags.cwd ?? process.cwd() });
3769
+ const summary = isReleased ? "released" : "nothing to release";
3770
+ writeReport({ json: flags.json, report: { released: isReleased }, summary });
3771
+ }
3772
+ async function stackStatusCommand(flags) {
3773
+ const report = await readServiceStackStatus();
3774
+ writeReport({ json: flags.json, report, summary: renderStackStatusSummary(report) });
3775
+ }
3776
+ function writeReport(params) {
3777
+ const output = params.json ? JSON.stringify(params.report, null, 2) : params.summary;
3778
+ process.stdout.write(`${output}
3779
+ `);
3780
+ }
3781
+ function shortSha(sha) {
3782
+ return sha ? sha.slice(0, 7) : "unknown";
3783
+ }
3784
+ function seconds(ms) {
3785
+ return `${Math.max(0, Math.round(ms / 1e3))}s`;
3786
+ }
3687
3787
  var logger7 = getLogger();
3688
3788
  var GITHUB_RELEASES_API = "https://api.github.com/repos/multiplex-ai/muggle-ai-works/releases?per_page=100";
3689
3789
  var INSTALL_METADATA_FILE_NAME2 = ".install-metadata.json";
@@ -4027,7 +4127,7 @@ function formatDuration(durationMs) {
4027
4127
  function shortSessionId(sessionId) {
4028
4128
  return sessionId.slice(0, 8);
4029
4129
  }
4030
- function shortSha(sha) {
4130
+ function shortSha2(sha) {
4031
4131
  return sha ? sha.slice(0, 8) : "?";
4032
4132
  }
4033
4133
 
@@ -4110,15 +4210,6 @@ function renderWatchStatus(snapshot, nowMs) {
4110
4210
  return `${lines.join("\n")}
4111
4211
  `;
4112
4212
  }
4113
-
4114
- // src/guardrails/types.ts
4115
- var ProviderPrState = /* @__PURE__ */ ((ProviderPrState2) => {
4116
- ProviderPrState2["Open"] = "OPEN";
4117
- ProviderPrState2["Merged"] = "MERGED";
4118
- ProviderPrState2["Closed"] = "CLOSED";
4119
- ProviderPrState2["Unreachable"] = "UNREACHABLE";
4120
- return ProviderPrState2;
4121
- })(ProviderPrState || {});
4122
4213
  function enumValueOf(values, candidate) {
4123
4214
  return Object.values(values).find((value) => value === candidate);
4124
4215
  }
@@ -4138,6 +4229,21 @@ function readFileHead(filePath) {
4138
4229
  if (fileDescriptor !== void 0) closeSync(fileDescriptor);
4139
4230
  }
4140
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
+ }
4141
4247
  function cwdFromSessionHead(head) {
4142
4248
  const parts = head.match(/"cwd"\s*:\s*("(?:[^"\\]|\\.)*")/);
4143
4249
  if (!parts) return void 0;
@@ -4148,6 +4254,15 @@ function cwdFromSessionHead(head) {
4148
4254
  }
4149
4255
  }
4150
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
+
4151
4266
  // src/watch/claude-sessions.ts
4152
4267
  function readPidsBySessionId(registryDir) {
4153
4268
  const pidsBySessionId = /* @__PURE__ */ new Map();
@@ -4169,6 +4284,15 @@ function readPidsBySessionId(registryDir) {
4169
4284
  }
4170
4285
  return pidsBySessionId;
4171
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
+ }
4172
4296
  function readClaudeSessions(runCommand, registryDir) {
4173
4297
  const outcome = runCommand("claude", ["agents", "--json"]);
4174
4298
  if (!outcome || outcome.exitCode !== 0) return null;
@@ -4195,12 +4319,12 @@ function readClaudeSessions(runCommand, registryDir) {
4195
4319
  turnStatus: enumValueOf(ClaudeTurnStatus, listing.status),
4196
4320
  jobState: enumValueOf(ClaudeJobState, listing.state),
4197
4321
  startedAtMs: typeof listing.startedAt === "number" ? listing.startedAt : void 0,
4198
- pid: pidsBySessionId.get(sessionId)
4322
+ pid: typeof listing.pid === "number" ? listing.pid : pidsBySessionId.get(sessionId)
4199
4323
  });
4200
4324
  }
4201
4325
  return sessions;
4202
4326
  }
4203
- function findClaudeSessionCwd(projectsDir, sessionId) {
4327
+ function findTranscriptPath(projectsDir, sessionId) {
4204
4328
  let projectDirNames;
4205
4329
  try {
4206
4330
  projectDirNames = readdirSync(projectsDir);
@@ -4210,12 +4334,40 @@ function findClaudeSessionCwd(projectsDir, sessionId) {
4210
4334
  const transcriptFileName = `${sessionId}.jsonl`;
4211
4335
  for (const projectDirName of projectDirNames) {
4212
4336
  const transcriptPath = join(projectsDir, projectDirName, transcriptFileName);
4213
- if (!existsSync(transcriptPath)) continue;
4214
- const head = readFileHead(transcriptPath);
4215
- return head === void 0 ? void 0 : cwdFromSessionHead(head);
4337
+ if (existsSync(transcriptPath)) return transcriptPath;
4216
4338
  }
4217
4339
  return void 0;
4218
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
+ }
4219
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;
4220
4372
  function sortedChildDirsDescending(dir) {
4221
4373
  try {
@@ -4281,6 +4433,76 @@ mcpToolNamePattern("muggle-local-telemetry-event-emit");
4281
4433
  mcpToolNamePattern("muggle-remote-user-feedback-create");
4282
4434
  var LOCK_POLL_INTERVAL_MS = 10;
4283
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
+
4284
4506
  // src/watch/findings.ts
4285
4507
  function resolveWatcherLiveness(loop, heartbeatAgeMs, isOwnerSessionActive, isProcessTableKnown) {
4286
4508
  const isHeartbeatWithin = (windowMs) => heartbeatAgeMs !== void 0 && heartbeatAgeMs <= windowMs;
@@ -4336,7 +4558,7 @@ function ownerPhrase(assessment) {
4336
4558
  }
4337
4559
  const owner = shortSessionId(assessment.ownerSessionId);
4338
4560
  if (assessment.isOwnerSessionActive === true) {
4339
- 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`;
4340
4562
  }
4341
4563
  if (assessment.isOwnerSessionActive === false) {
4342
4564
  return assessment.isRegistered ? `owner session ${owner} has ended` : `owner session ${owner} has ended; slot is not registered for recovery`;
@@ -4366,7 +4588,7 @@ function watcherFinding(assessment, subject) {
4366
4588
  }
4367
4589
  function prStateFindings(assessment, live, subject) {
4368
4590
  const prFindings = [];
4369
- const head = shortSha(live.headSha);
4591
+ const head = shortSha2(live.headSha);
4370
4592
  if (live.ciRollup === "FAILURE" /* Failure */ || live.ciRollup === "ERROR" /* Error */) {
4371
4593
  prFindings.push(finding(
4372
4594
  "CI_FAILING" /* CiFailing */,
@@ -4406,7 +4628,7 @@ function deriveWatchFindings(assessments, processes, isPollingDisabled) {
4406
4628
  for (const assessment of assessments) {
4407
4629
  const subject = `${assessment.pr.repo}#${assessment.pr.number}`;
4408
4630
  const live = assessment.live;
4409
- if (live && (live.state === "MERGED" /* Merged */ || live.state === "CLOSED" /* Closed */)) {
4631
+ if (live && isTerminalPrState(live.state)) {
4410
4632
  findings.push(finding(
4411
4633
  "SLOT_TERMINAL_UNFINALIZED" /* SlotTerminalUnfinalized */,
4412
4634
  [assessment.pr.url],
@@ -4685,64 +4907,6 @@ function readUserPluginsUpdatedAtMs(installedPluginsFile) {
4685
4907
  return updatedAtMs;
4686
4908
  }
4687
4909
 
4688
- // src/watch/pr-status.ts
4689
- var PR_STATUS_FRAGMENT = `fragment WatchPr on PullRequest {
4690
- state
4691
- headRefOid
4692
- mergeable
4693
- mergeStateStatus
4694
- commits(last: 1) { nodes { commit { statusCheckRollup { state } } } }
4695
- reviewThreads(first: 100) { nodes { isResolved } }
4696
- }`;
4697
- function buildPrStatusRequest(prs) {
4698
- const variableDeclarations = [];
4699
- const selections = [];
4700
- const fieldFlags = [];
4701
- prs.forEach((pr, index) => {
4702
- const [owner, name] = pr.repo.split("/");
4703
- variableDeclarations.push(`$o${index}: String!, $r${index}: String!, $n${index}: Int!`);
4704
- selections.push(` p${index}: repository(owner: $o${index}, name: $r${index}) { pullRequest(number: $n${index}) { ...WatchPr } }`);
4705
- fieldFlags.push("-f", `o${index}=${owner}`, "-f", `r${index}=${name}`, "-F", `n${index}=${pr.number}`);
4706
- });
4707
- const query = `query(${variableDeclarations.join(", ")}) {
4708
- ${selections.join("\n")}
4709
- }
4710
- ${PR_STATUS_FRAGMENT}`;
4711
- return ["api", "graphql", "-f", `query=${query}`, ...fieldFlags];
4712
- }
4713
- function parsePullRequestNode(url, node) {
4714
- const state = enumValueOf(ProviderPrState, node?.state);
4715
- if (!node || state === void 0 || state === "UNREACHABLE" /* Unreachable */) return void 0;
4716
- return {
4717
- url,
4718
- state,
4719
- headSha: optionalString(node.headRefOid),
4720
- mergeable: enumValueOf(PrMergeable, node.mergeable),
4721
- mergeStateStatus: enumValueOf(PrMergeStateStatus, node.mergeStateStatus),
4722
- ciRollup: enumValueOf(CiRollupState, node.commits?.nodes?.[0]?.commit?.statusCheckRollup?.state),
4723
- unresolvedThreadCount: (node.reviewThreads?.nodes ?? []).filter((thread) => thread.isResolved === false).length
4724
- };
4725
- }
4726
- function fetchPrLiveStatuses(prs, runCommand) {
4727
- const statusesByUrl = /* @__PURE__ */ new Map();
4728
- for (let start = 0; start < prs.length; start += PR_STATUS_BATCH_SIZE) {
4729
- const batch = prs.slice(start, start + PR_STATUS_BATCH_SIZE);
4730
- const outcome = runCommand("gh", buildPrStatusRequest(batch));
4731
- if (!outcome?.stdout) continue;
4732
- let response;
4733
- try {
4734
- response = JSON.parse(outcome.stdout);
4735
- } catch {
4736
- continue;
4737
- }
4738
- batch.forEach((pr, index) => {
4739
- const liveStatus = parsePullRequestNode(pr.url, response.data?.[`p${index}`]?.pullRequest);
4740
- if (liveStatus) statusesByUrl.set(pr.url, liveStatus);
4741
- });
4742
- }
4743
- return statusesByUrl;
4744
- }
4745
-
4746
4910
  // src/watch/process-table.ts
4747
4911
  function buildWindowsProcessTableScript() {
4748
4912
  const keptExecutables = COMMAND_LINE_EXECUTABLE_PATTERN.source.replace(/'/g, "''");
@@ -4791,8 +4955,8 @@ function readWindowsProcessTable(runCommand, nowMs) {
4791
4955
  function parsePsElapsedSeconds(elapsed) {
4792
4956
  const parts = elapsed.match(/^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)$/);
4793
4957
  if (!parts) return void 0;
4794
- const [, days, hours, minutes, seconds] = parts;
4795
- return Number(days ?? 0) * 86400 + Number(hours ?? 0) * 3600 + Number(minutes) * 60 + Number(seconds);
4958
+ const [, days, hours, minutes, seconds2] = parts;
4959
+ return Number(days ?? 0) * 86400 + Number(hours ?? 0) * 3600 + Number(minutes) * 60 + Number(seconds2);
4796
4960
  }
4797
4961
  function executableNameOf(commandLine) {
4798
4962
  const firstToken = commandLine.trim().split(/\s+/)[0] ?? "";
@@ -4822,18 +4986,31 @@ function readPosixProcessTable(runCommand) {
4822
4986
  function readProcessTable(platform4, runCommand, nowMs) {
4823
4987
  return platform4 === "win32" ? readWindowsProcessTable(runCommand, nowMs) : readPosixProcessTable(runCommand);
4824
4988
  }
4825
- function isRecoverable(assessment) {
4826
- 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;
4827
5004
  }
4828
5005
  function isSlotCloseOutDue(assessment) {
4829
- const isTerminal = assessment.live?.state === "MERGED" /* Merged */ || assessment.live?.state === "CLOSED" /* Closed */;
4830
- return isTerminal && assessment.watcher === "dead" /* Dead */ && assessment.isOwnerSessionActive !== true;
5006
+ return isTerminalPrState(assessment.live?.state) && assessment.watcher === "dead" /* Dead */ && assessment.isOwnerSessionActive !== true;
4831
5007
  }
4832
- function planWatcherRecoveries(assessments, attemptsByOwner, nowMs, isPollingDisabled) {
5008
+ function planWatcherRecoveries(assessments, attemptsByOwner, nowMs, isPollingDisabled, sessionsById = /* @__PURE__ */ new Map(), isStoppedAtUsageLimit2 = () => false) {
4833
5009
  if (isPollingDisabled) return [];
4834
5010
  const slugsByOwner = /* @__PURE__ */ new Map();
4835
5011
  for (const assessment of assessments) {
4836
- if (!isRecoverable(assessment)) continue;
5012
+ const ownerSession = assessment.ownerSessionId === void 0 ? void 0 : sessionsById.get(assessment.ownerSessionId);
5013
+ if (!isRecoverable(assessment, ownerSession)) continue;
4837
5014
  const ownerSessionId = assessment.ownerSessionId;
4838
5015
  const slugs = slugsByOwner.get(ownerSessionId) ?? /* @__PURE__ */ new Set();
4839
5016
  slugs.add(assessment.slug);
@@ -4844,34 +5021,49 @@ function planWatcherRecoveries(assessments, attemptsByOwner, nowMs, isPollingDis
4844
5021
  for (const ownerSessionId of [...slugsByOwner.keys()].sort()) {
4845
5022
  const recentAttemptsMs = (attemptsByOwner[ownerSessionId] ?? []).map((attemptedAt) => Date.parse(attemptedAt)).filter((attemptedAtMs) => !Number.isNaN(attemptedAtMs) && nowMs - attemptedAtMs < RECOVERY_ATTEMPT_WINDOW_MS);
4846
5023
  const lastAttemptMs = Math.max(-Infinity, ...recentAttemptsMs);
5024
+ const isCapReached = recentAttemptsMs.length >= RECOVERY_MAX_ATTEMPTS && !isStoppedAtUsageLimit2(ownerSessionId);
4847
5025
  let outcome = "resume-due" /* ResumeDue */;
4848
- if (recentAttemptsMs.length >= RECOVERY_MAX_ATTEMPTS) outcome = "attempts-exhausted" /* AttemptsExhausted */;
5026
+ if (isCapReached) outcome = "attempts-exhausted" /* AttemptsExhausted */;
4849
5027
  else if (nowMs - lastAttemptMs < RECOVERY_COOLDOWN_MS) outcome = "cooling-down" /* CoolingDown */;
4850
5028
  else if (resumesPlanned >= MAX_RESUMES_PER_TICK) outcome = "deferred-by-tick-cap" /* DeferredByTickCap */;
4851
5029
  if (outcome === "resume-due" /* ResumeDue */) resumesPlanned++;
5030
+ const runningOwner = sessionsById.get(ownerSessionId);
4852
5031
  recoveries.push({
4853
5032
  ownerSessionId,
4854
5033
  slotSlugs: [...slugsByOwner.get(ownerSessionId) ?? []].sort(),
4855
- outcome
5034
+ outcome,
5035
+ ...runningOwner?.shortId === void 0 ? {} : { ownerShortId: runningOwner.shortId }
4856
5036
  });
4857
5037
  }
4858
5038
  return recoveries;
4859
5039
  }
4860
- function executeWatcherRecoveries(planned, attemptsByOwner, runCommand, claudeProjectsDir, nowMs) {
4861
- const nowIso = new Date(nowMs).toISOString();
5040
+ function executeWatcherRecoveries(planned, attemptsByOwner, deps) {
5041
+ const nowIso = new Date(deps.nowMs).toISOString();
4862
5042
  const nextAttemptsByOwner = {};
4863
5043
  for (const [ownerSessionId, attempts] of Object.entries(attemptsByOwner)) {
4864
- 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);
4865
5045
  if (recent.length > 0) nextAttemptsByOwner[ownerSessionId] = recent;
4866
5046
  }
4867
5047
  const events = [];
4868
5048
  const recoveries = planned.map((recovery) => {
4869
5049
  if (recovery.outcome !== "resume-due" /* ResumeDue */) return recovery;
4870
- const cwd = findClaudeSessionCwd(claudeProjectsDir, recovery.ownerSessionId);
5050
+ const cwd = findClaudeSessionCwd(deps.claudeProjectsDir, recovery.ownerSessionId);
4871
5051
  if (!cwd || !existsSync(cwd)) return { ...recovery, outcome: "transcript-missing" /* TranscriptMissing */ };
4872
- const outcome = runCommand("claude", ["--resume", recovery.ownerSessionId, "--bg", RECOVERY_RESUME_PROMPT], { cwd });
4873
- const isResumed = outcome?.exitCode === 0;
4874
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
+ );
4875
5067
  events.push({
4876
5068
  at: nowIso,
4877
5069
  kind: isResumed ? "resumed" /* Resumed */ : "resume-failed" /* ResumeFailed */,
@@ -4907,7 +5099,7 @@ function planReloadFanOut(sessions, pending, watchOwnerSessionIds, maxRestarts =
4907
5099
  const decisions = [];
4908
5100
  for (const session of sessions) {
4909
5101
  if (session.agent !== "claude" /* Claude */) continue;
4910
- if (session.pid === void 0) {
5102
+ if (!hasLiveProcess(session)) {
4911
5103
  decisions.push(decide(session, "skip" /* Skip */, "no live process"));
4912
5104
  } else if (hasCurrentPlugins(session, pending)) {
4913
5105
  decisions.push(decide(session, "skip" /* Skip */, "already on the installed build"));
@@ -4928,7 +5120,7 @@ function planReloadFanOut(sessions, pending, watchOwnerSessionIds, maxRestarts =
4928
5120
  }
4929
5121
  return decisions;
4930
5122
  }
4931
- function executeReloadFanOut(decisions, runCommand, canRestartIn) {
5123
+ function executeReloadFanOut(decisions, runCommand, canRestartIn, waitForExit) {
4932
5124
  const restartableByCwd = /* @__PURE__ */ new Map();
4933
5125
  const isRestartable = (cwd) => {
4934
5126
  if (!restartableByCwd.has(cwd)) restartableByCwd.set(cwd, canRestartIn(cwd));
@@ -4946,9 +5138,11 @@ function executeReloadFanOut(decisions, runCommand, canRestartIn) {
4946
5138
  if (decision.action === "respawn" /* Respawn */) {
4947
5139
  isRestarted = runCommand("claude", ["respawn", decision.shortId])?.exitCode === 0;
4948
5140
  } else {
4949
- runCommand("claude", ["stop", decision.shortId]);
4950
- const resumed = runCommand("claude", ["--resume", decision.sessionId, "--bg", RECOVERY_RESUME_PROMPT], { cwd: decision.cwd });
4951
- isRestarted = resumed?.exitCode === 0;
5141
+ isRestarted = resumeOnReconcile(
5142
+ { sessionId: decision.sessionId, cwd: decision.cwd, runningShortId: decision.shortId },
5143
+ runCommand,
5144
+ waitForExit
5145
+ );
4952
5146
  }
4953
5147
  (isRestarted ? report.respawnedSessionIds : report.failedSessionIds).push(decision.sessionId);
4954
5148
  }
@@ -5030,7 +5224,7 @@ function updateTerminalCache(terminalPrsByUrl, fetchedStatuses, trackedUrls, now
5030
5224
  if (trackedUrls.has(url)) nextCache[url] = record;
5031
5225
  }
5032
5226
  for (const fetched of fetchedStatuses) {
5033
- if (fetched.state === "MERGED" /* Merged */ || fetched.state === "CLOSED" /* Closed */) {
5227
+ if (isTerminalPrState(fetched.state)) {
5034
5228
  nextCache[fetched.url] = { state: fetched.state, checkedAt: nowIso };
5035
5229
  } else {
5036
5230
  delete nextCache[fetched.url];
@@ -5251,8 +5445,11 @@ function observeSessions(deps, installs) {
5251
5445
  const sessions = [...claudeSessions ?? [], ...readCodexSessions(deps.paths.codexSessionsDir, deps.nowMs)];
5252
5446
  return { processes, claudeSessions, sessions };
5253
5447
  }
5448
+ function isRestartAttempted(recovery) {
5449
+ return recovery.outcome === "resumed" /* Resumed */ || recovery.outcome === "resume-failed" /* ResumeFailed */;
5450
+ }
5254
5451
  function watchOwnersOf(slots) {
5255
- 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] : []));
5256
5453
  }
5257
5454
  function reloadEvents(report, at) {
5258
5455
  const decisionById = new Map(report.decisions.map((decision) => [decision.sessionId, decision]));
@@ -5276,9 +5473,15 @@ function runReloadPass(record, claudeSessions, watchOwnerSessionIds, deps, at) {
5276
5473
  const decisions = planReloadFanOut(claudeSessions, record, watchOwnerSessionIds).map(
5277
5474
  (decision) => decision.action === "resume-reconcile" /* ResumeReconcile */ ? { ...decision, cwd: findClaudeSessionCwd(deps.paths.claudeProjectsDir, decision.sessionId) ?? decision.cwd } : decision
5278
5475
  );
5279
- const report = executeReloadFanOut(decisions, deps.runCommand, (cwd) => canRestartSessionIn(cwd, deps.runCommand));
5476
+ const report = executeReloadFanOut(decisions, deps.runCommand, canRestartVia(deps), waitForExitVia(deps));
5280
5477
  return { report, pendingReload: advancePendingReload(record, report), events: reloadEvents(report, at) };
5281
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
+ }
5282
5485
  function reloadTargetAtMs(deps, installs) {
5283
5486
  return resolveReloadTargetAtMs(installs, readUserPluginsUpdatedAtMs(deps.paths.claudeInstalledPluginsFile));
5284
5487
  }
@@ -5303,7 +5506,8 @@ function runTickUnlocked(deps) {
5303
5506
  const at = new Date(deps.nowMs).toISOString();
5304
5507
  const installs = readInstallHistory(deps.paths.muggleInstallLogFile);
5305
5508
  const { processes, claudeSessions, sessions } = observeSessions(deps, installs);
5306
- 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));
5307
5511
  const slots = readOpenWatchSlots(deps.paths.slotsDir);
5308
5512
  const isPollingDisabled = isPrPollingDisabled(deps.paths.slotsDir);
5309
5513
  const state = readWatchLedgerState(deps.paths.watchDir);
@@ -5330,8 +5534,21 @@ function runTickUnlocked(deps) {
5330
5534
  let recoveries = [];
5331
5535
  let recoveryAttemptsByOwner = state.recoveryAttemptsByOwner;
5332
5536
  if (deps.isRecoveryEnabled) {
5333
- const planned = planWatcherRecoveries(assessments, recoveryAttemptsByOwner, deps.nowMs, isPollingDisabled);
5334
- 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
+ });
5335
5552
  recoveries = executed.recoveries;
5336
5553
  recoveryAttemptsByOwner = executed.attemptsByOwner;
5337
5554
  events.push(...executed.events);
@@ -5340,7 +5557,9 @@ function runTickUnlocked(deps) {
5340
5557
  let reload;
5341
5558
  const targetAtMs = reloadTargetAtMs(deps, installs);
5342
5559
  if (deps.isAutoReloadEnabled && targetAtMs !== void 0 && claudeSessions !== null) {
5343
- 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);
5344
5563
  pendingReload = pass.pendingReload;
5345
5564
  reload = pass.report;
5346
5565
  events.push(...pass.events);
@@ -5527,6 +5746,16 @@ function createProgram() {
5527
5746
  program.command("run-view").argument("[runId]", "Run id, or a unique prefix of one (default: the newest run)").description("Show a local run's steps beside the frames they produced").option("--html", "Render a self-contained HTML page instead of terminal text").option("--open", "Open the rendered page in the default browser (implies --html)").option("--out-dir <dir>", "Directory to write the page into (default: current directory)").action(runViewCommand);
5528
5747
  program.command("pr-walkthrough-check").description("Check that a PR's Muggle AI walkthrough comment carries a result or a stated skip").option("--repo <owner/repo>", "Repository (default: $GITHUB_REPOSITORY)").option("--pr <number>", "Pull request number (default: the Actions event payload)").option("--head-sha <sha>", "Commit the check run attaches to (default: the PR head)").option("--check-run", "Publish the verdict as a check run instead of failing the process").action(prWalkthroughCheckCommand);
5529
5748
  program.command("checkout-freshness").description("Fetch the base branch and check that a checkout is built on its latest commit").option("--cwd <dir>", "Directory inside the checkout (default: the current directory)").option("--base <branch>", "Branch the change merges into (default: origin's default branch)").option("--no-fetch", "Check against the last fetched base instead of fetching").option("--json", "Print the full report as JSON").action(checkoutFreshnessCommand);
5749
+ const stack = program.command("stack").description("Share one set of local services between agents in different checkouts");
5750
+ stack.command("claim").description("Claim the ports this checkout's E2E run needs; answers granted or busy at once").option("--cwd <dir>", "Directory inside the claiming checkout (default: the current directory)").option(
5751
+ "--need <port=run-dir[@sha]>",
5752
+ "A port and the directory (and commit) it must serve; repeat per port",
5753
+ (value, previous) => [...previous, value],
5754
+ []
5755
+ ).option("--label <name>", "Name shown to peers waiting on this checkout").option("--wait <seconds>", "Keep re-asking this long while busy").option("--json", "Print the full report as JSON").action(stackClaimCommand);
5756
+ stack.command("check").description("Check that the stack still serves what this checkout claimed, renewing the lease").option("--cwd <dir>", "Directory inside the checkout (default: the current directory)").option("--port <port>", "Port the run will target").option("--json", "Print the full report as JSON").action(stackCheckCommand);
5757
+ stack.command("release").description("Give up this checkout's lease and place in line").option("--cwd <dir>", "Directory inside the checkout (default: the current directory)").option("--json", "Print the result as JSON").action(stackReleaseCommand);
5758
+ stack.command("status").description("Show every lease, the line, and the services prepare tracks").option("--json", "Print the full report as JSON").action(stackStatusCommand);
5530
5759
  program.command("ci-install").description("Add the Muggle walkthrough check to this repository's GitHub Actions").option("--force", "Replace an existing workflow file").action(ciInstallCommand);
5531
5760
  const watch = program.command("watch").description("Standing watch over Claude/Codex sessions, their processes, and PR watchers");
5532
5761
  watch.command("tick").description("Run one watch pass (the scheduled task runs this)").option("--no-auto-reload", "Do not start a plugin reload fan-out when installed plugins change").option("--no-recovery", "Report dead watchers without resuming their owner sessions").option("--json", "Print the full snapshot as JSON").action(watchTickCommand);