@muggleai/works 5.26.0-staging.198 → 5.26.0-staging.199
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.
- package/.claude-plugin/marketplace.json +1 -1
- package/dist/{chunk-SLU7LHVJ.js → chunk-IL5E5YGY.js} +1 -1
- package/dist/{chunk-U5ZA3VTZ.js → chunk-MKQYUSIW.js} +1430 -23
- package/dist/cli.js +2 -2
- package/dist/index.js +2 -2
- package/dist/plugin/.claude-plugin/plugin.json +1 -1
- package/dist/plugin/.codex-mcp.json +1 -1
- package/dist/plugin/.codex-plugin/plugin.json +1 -1
- package/dist/plugin/.cursor-plugin/plugin.json +1 -1
- package/dist/plugin/.mcp.json +1 -1
- package/dist/plugin/hooks/README.md +1 -1
- package/dist/plugin/scripts/guardrail-walkthrough-gate.sh +15 -12
- package/dist/plugin/scripts/guardrails.mjs +134 -91
- package/dist/plugin/scripts/pr-watch-arm.sh +8 -1
- package/dist/plugin/skills/do/open-prs/forward.md +1 -1
- package/dist/plugin/skills/muggle-pr-followup/arm-watcher.md +2 -0
- package/dist/plugin/skills/muggle-pr-followup/reconcile.md +4 -2
- package/dist/plugin/skills/muggle-pr-followup/state-schemas.md +15 -0
- package/dist/plugin/skills/muggle-pr-followup/stop.md +1 -1
- package/dist/release-manifest.json +3 -3
- package/dist/{src-3HZTU2TJ.js → src-UVZTYRQY.js} +1 -1
- package/package.json +2 -1
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/.codex-mcp.json +1 -1
- package/plugin/.codex-plugin/plugin.json +1 -1
- package/plugin/.cursor-plugin/plugin.json +1 -1
- package/plugin/.mcp.json +1 -1
- package/plugin/hooks/README.md +1 -1
- package/plugin/scripts/guardrail-walkthrough-gate.sh +15 -12
- package/plugin/scripts/guardrails.mjs +134 -91
- package/plugin/scripts/pr-watch-arm.sh +8 -1
- package/plugin/skills/do/open-prs/forward.md +1 -1
- package/plugin/skills/muggle-pr-followup/arm-watcher.md +2 -0
- package/plugin/skills/muggle-pr-followup/reconcile.md +4 -2
- package/plugin/skills/muggle-pr-followup/state-schemas.md +15 -0
- package/plugin/skills/muggle-pr-followup/stop.md +1 -1
- package/scripts/muggle-watch/README.md +45 -0
- package/scripts/muggle-watch/install-muggle-watch.ps1 +92 -0
- package/scripts/muggle-watch/muggle-watch-hidden.vbs +39 -0
|
@@ -1,20 +1,20 @@
|
|
|
1
|
-
import { __export, getLogger, getConfig, createChildLogger, buildElectronAppReleaseAssetUrl, getActiveRuntimeTarget, getAuthService, hasApiKey, getElectronAppVersion, getElectronAppDir, getPlatformKey, reconcileProjectPreferences,
|
|
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, OnboardingBlanketChoice, PreferenceKey, resolvePreferences, getDataDir } from './chunk-IL5E5YGY.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 } from 'fs';
|
|
8
|
+
import { readFileSync, existsSync, rmSync, mkdirSync, readdirSync, createWriteStream, writeFileSync, statSync, readlinkSync, realpathSync, openSync, writeSync, closeSync, unlinkSync, renameSync, appendFileSync, readSync } from 'fs';
|
|
9
9
|
import * as path from 'path';
|
|
10
|
-
import { dirname, resolve, join } from 'path';
|
|
10
|
+
import { dirname, resolve, join, basename } from 'path';
|
|
11
11
|
import { fileURLToPath, pathToFileURL } from 'url';
|
|
12
12
|
import { Command } from 'commander';
|
|
13
13
|
import axios from 'axios';
|
|
14
14
|
import { createHash } from 'crypto';
|
|
15
|
-
import { platform, homedir, arch } from 'os';
|
|
15
|
+
import { platform, homedir, arch, hostname } from 'os';
|
|
16
16
|
import { createInterface } from 'readline/promises';
|
|
17
|
-
import { execFile, execFileSync } from 'child_process';
|
|
17
|
+
import { execFile, execFileSync, spawnSync } from 'child_process';
|
|
18
18
|
import { pipeline } from 'stream/promises';
|
|
19
19
|
import { readFile } from 'fs/promises';
|
|
20
20
|
import { verify } from 'sigstore';
|
|
@@ -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-
|
|
1071
|
+
const mcps = await import('./src-UVZTYRQY.js');
|
|
1072
1072
|
const credentials = await mcps.getCallerCredentialsAsync();
|
|
1073
1073
|
if (!credentials.bearerToken && !credentials.apiKey) {
|
|
1074
1074
|
stderrWrite(
|
|
@@ -1363,7 +1363,7 @@ function getCursorSkillsDir() {
|
|
|
1363
1363
|
return path.join(homedir(), CURSOR_SKILLS_DIR, CURSOR_SKILLS_SUBDIR);
|
|
1364
1364
|
}
|
|
1365
1365
|
function getInstallManifestPath() {
|
|
1366
|
-
return path.join(
|
|
1366
|
+
return path.join(getDataDir2(), INSTALL_MANIFEST_FILE);
|
|
1367
1367
|
}
|
|
1368
1368
|
function readInstallManifest() {
|
|
1369
1369
|
const manifestPath = getInstallManifestPath();
|
|
@@ -1932,7 +1932,7 @@ function validateCursorMcpConfig() {
|
|
|
1932
1932
|
function runDiagnostics() {
|
|
1933
1933
|
const results = [];
|
|
1934
1934
|
const config = getConfig();
|
|
1935
|
-
const dataDir =
|
|
1935
|
+
const dataDir = getDataDir2();
|
|
1936
1936
|
results.push({
|
|
1937
1937
|
name: "Data Directory",
|
|
1938
1938
|
passed: existsSync(dataDir),
|
|
@@ -2163,6 +2163,12 @@ function getHelpGuidance() {
|
|
|
2163
2163
|
` ${cmd("muggle logout")} Clear stored credentials`,
|
|
2164
2164
|
` ${cmd("muggle status")} Show authentication status`,
|
|
2165
2165
|
"",
|
|
2166
|
+
` ${colorize("Watch Service:", COLORS.bold)}`,
|
|
2167
|
+
` ${cmd("muggle watch status")} Sessions, processes, PR watchers, findings`,
|
|
2168
|
+
` ${cmd("muggle watch tick")} Run one watch pass now`,
|
|
2169
|
+
` ${cmd("muggle watch reload-plugins")} Reload plugins across active sessions`,
|
|
2170
|
+
` ${cmd("muggle watch register")} Opt a PR-watch slot into recovery`,
|
|
2171
|
+
"",
|
|
2166
2172
|
` ${colorize("Maintenance:", COLORS.bold)}`,
|
|
2167
2173
|
` ${cmd("muggle versions")} List installed Electron app versions`,
|
|
2168
2174
|
` ${cmd("muggle cleanup")} Remove old Electron app versions`,
|
|
@@ -2572,6 +2578,7 @@ function boundedChildTimeoutMs(ceilingMs) {
|
|
|
2572
2578
|
}
|
|
2573
2579
|
|
|
2574
2580
|
// src/pr-walkthrough/gh.ts
|
|
2581
|
+
var GITHUB_PR_URL = /^https:\/\/github\.com\/([^/\s]+)\/([^/\s]+)\/pull\/(\d+)/;
|
|
2575
2582
|
var GH_CALLS_ENV = "MUGGLE_GUARDRAIL_GH_CALLS";
|
|
2576
2583
|
var defaultGhRunner = (args, input) => {
|
|
2577
2584
|
if (process.env[GH_CALLS_ENV] === "off") return null;
|
|
@@ -2589,6 +2596,11 @@ var defaultGhRunner = (args, input) => {
|
|
|
2589
2596
|
return null;
|
|
2590
2597
|
}
|
|
2591
2598
|
};
|
|
2599
|
+
function parsePrUrl(prUrl) {
|
|
2600
|
+
const parts = prUrl.match(GITHUB_PR_URL);
|
|
2601
|
+
if (!parts) return null;
|
|
2602
|
+
return { repo: `${parts[1]}/${parts[2]}`, prNumber: Number(parts[3]) };
|
|
2603
|
+
}
|
|
2592
2604
|
function listPrComments(pr, run) {
|
|
2593
2605
|
let raw;
|
|
2594
2606
|
try {
|
|
@@ -2984,7 +2996,7 @@ function getBinaryName() {
|
|
|
2984
2996
|
}
|
|
2985
2997
|
}
|
|
2986
2998
|
async function extractZip(zipPath, destDir) {
|
|
2987
|
-
return new Promise((
|
|
2999
|
+
return new Promise((resolve3, reject) => {
|
|
2988
3000
|
if (platform() === "win32") {
|
|
2989
3001
|
execFile(
|
|
2990
3002
|
"powershell",
|
|
@@ -2993,7 +3005,7 @@ async function extractZip(zipPath, destDir) {
|
|
|
2993
3005
|
if (error) {
|
|
2994
3006
|
reject(error);
|
|
2995
3007
|
} else {
|
|
2996
|
-
|
|
3008
|
+
resolve3();
|
|
2997
3009
|
}
|
|
2998
3010
|
}
|
|
2999
3011
|
);
|
|
@@ -3002,25 +3014,25 @@ async function extractZip(zipPath, destDir) {
|
|
|
3002
3014
|
if (error) {
|
|
3003
3015
|
reject(error);
|
|
3004
3016
|
} else {
|
|
3005
|
-
|
|
3017
|
+
resolve3();
|
|
3006
3018
|
}
|
|
3007
3019
|
});
|
|
3008
3020
|
}
|
|
3009
3021
|
});
|
|
3010
3022
|
}
|
|
3011
3023
|
async function extractTarGz(tarPath, destDir) {
|
|
3012
|
-
return new Promise((
|
|
3024
|
+
return new Promise((resolve3, reject) => {
|
|
3013
3025
|
execFile("tar", ["-xzf", tarPath, "-C", destDir], (error) => {
|
|
3014
3026
|
if (error) {
|
|
3015
3027
|
reject(error);
|
|
3016
3028
|
} else {
|
|
3017
|
-
|
|
3029
|
+
resolve3();
|
|
3018
3030
|
}
|
|
3019
3031
|
});
|
|
3020
3032
|
});
|
|
3021
3033
|
}
|
|
3022
3034
|
function sleep(ms) {
|
|
3023
|
-
return new Promise((
|
|
3035
|
+
return new Promise((resolve3) => setTimeout(resolve3, ms));
|
|
3024
3036
|
}
|
|
3025
3037
|
async function downloadWithRetry(downloadUrl, destPath) {
|
|
3026
3038
|
let lastError = null;
|
|
@@ -3114,12 +3126,12 @@ async function setupCommand(options) {
|
|
|
3114
3126
|
const projectPreferencesReconcile = reconcileProjectPreferences(process.cwd());
|
|
3115
3127
|
if (projectPreferencesReconcile.outcome === "copiedToGlobal" /* CopiedToGlobal */) {
|
|
3116
3128
|
console.log(
|
|
3117
|
-
`Preferences are now user-level. Copied ${projectPreferencesReconcile.projectFilePath} to ${path.join(
|
|
3129
|
+
`Preferences are now user-level. Copied ${projectPreferencesReconcile.projectFilePath} to ${path.join(getDataDir2(), PREFERENCES_FILE_NAME)}.`
|
|
3118
3130
|
);
|
|
3119
3131
|
}
|
|
3120
3132
|
if (isFirstRun()) {
|
|
3121
3133
|
writePreferences(DEFAULT_PREFERENCES);
|
|
3122
|
-
console.log(`Default preferences written to ${path.join(
|
|
3134
|
+
console.log(`Default preferences written to ${path.join(getDataDir2(), PREFERENCES_FILE_NAME)}`);
|
|
3123
3135
|
console.log("You can customize them anytime by editing the file or telling the agent to change a preference.");
|
|
3124
3136
|
}
|
|
3125
3137
|
if (!options.force && isElectronAppInstalled()) {
|
|
@@ -3248,7 +3260,7 @@ function extractVersionFromTag(tag, releaseTagPrefix) {
|
|
|
3248
3260
|
return match ? match[1] : null;
|
|
3249
3261
|
}
|
|
3250
3262
|
function getVersionOverridePath() {
|
|
3251
|
-
return path.join(
|
|
3263
|
+
return path.join(getDataDir2(), VERSION_OVERRIDE_FILE);
|
|
3252
3264
|
}
|
|
3253
3265
|
function getEffectiveElectronAppVersion() {
|
|
3254
3266
|
const overridePath = getVersionOverridePath();
|
|
@@ -3265,7 +3277,7 @@ function getEffectiveElectronAppVersion() {
|
|
|
3265
3277
|
}
|
|
3266
3278
|
function saveVersionOverride(version) {
|
|
3267
3279
|
const overridePath = getVersionOverridePath();
|
|
3268
|
-
const dataDir =
|
|
3280
|
+
const dataDir = getDataDir2();
|
|
3269
3281
|
if (!existsSync(dataDir)) {
|
|
3270
3282
|
mkdirSync(dataDir, { recursive: true });
|
|
3271
3283
|
}
|
|
@@ -3331,7 +3343,7 @@ function writeInstallMetadata2(params) {
|
|
|
3331
3343
|
`, "utf-8");
|
|
3332
3344
|
}
|
|
3333
3345
|
async function extractZip2(zipPath, destDir) {
|
|
3334
|
-
return new Promise((
|
|
3346
|
+
return new Promise((resolve3, reject) => {
|
|
3335
3347
|
if (platform() === "win32") {
|
|
3336
3348
|
execFile(
|
|
3337
3349
|
"powershell",
|
|
@@ -3340,7 +3352,7 @@ async function extractZip2(zipPath, destDir) {
|
|
|
3340
3352
|
if (error) {
|
|
3341
3353
|
reject(error);
|
|
3342
3354
|
} else {
|
|
3343
|
-
|
|
3355
|
+
resolve3();
|
|
3344
3356
|
}
|
|
3345
3357
|
}
|
|
3346
3358
|
);
|
|
@@ -3349,19 +3361,19 @@ async function extractZip2(zipPath, destDir) {
|
|
|
3349
3361
|
if (error) {
|
|
3350
3362
|
reject(error);
|
|
3351
3363
|
} else {
|
|
3352
|
-
|
|
3364
|
+
resolve3();
|
|
3353
3365
|
}
|
|
3354
3366
|
});
|
|
3355
3367
|
}
|
|
3356
3368
|
});
|
|
3357
3369
|
}
|
|
3358
3370
|
async function extractTarGz2(tarPath, destDir) {
|
|
3359
|
-
return new Promise((
|
|
3371
|
+
return new Promise((resolve3, reject) => {
|
|
3360
3372
|
execFile("tar", ["-xzf", tarPath, "-C", destDir], (error) => {
|
|
3361
3373
|
if (error) {
|
|
3362
3374
|
reject(error);
|
|
3363
3375
|
} else {
|
|
3364
|
-
|
|
3376
|
+
resolve3();
|
|
3365
3377
|
}
|
|
3366
3378
|
});
|
|
3367
3379
|
});
|
|
@@ -3554,6 +3566,1395 @@ Cleaned up ${cleanupResult.removed.length} old version(s), freed ${formatBytes(c
|
|
|
3554
3566
|
}
|
|
3555
3567
|
}
|
|
3556
3568
|
|
|
3569
|
+
// src/watch/format.ts
|
|
3570
|
+
function formatDuration(durationMs) {
|
|
3571
|
+
const totalMinutes = Math.max(0, Math.floor(durationMs / 6e4));
|
|
3572
|
+
if (totalMinutes < 60) return `${totalMinutes}m`;
|
|
3573
|
+
const totalHours = Math.floor(totalMinutes / 60);
|
|
3574
|
+
if (totalHours < 24) return `${totalHours}h${String(totalMinutes % 60).padStart(2, "0")}m`;
|
|
3575
|
+
return `${Math.floor(totalHours / 24)}d${String(totalHours % 24).padStart(2, "0")}h`;
|
|
3576
|
+
}
|
|
3577
|
+
function shortSessionId(sessionId) {
|
|
3578
|
+
return sessionId.slice(0, 8);
|
|
3579
|
+
}
|
|
3580
|
+
function shortSha(sha) {
|
|
3581
|
+
return sha ? sha.slice(0, 8) : "?";
|
|
3582
|
+
}
|
|
3583
|
+
|
|
3584
|
+
// src/watch/types.ts
|
|
3585
|
+
var ClaudeSessionKind = /* @__PURE__ */ ((ClaudeSessionKind2) => {
|
|
3586
|
+
ClaudeSessionKind2["Background"] = "background";
|
|
3587
|
+
ClaudeSessionKind2["Interactive"] = "interactive";
|
|
3588
|
+
return ClaudeSessionKind2;
|
|
3589
|
+
})(ClaudeSessionKind || {});
|
|
3590
|
+
var ClaudeTurnStatus = /* @__PURE__ */ ((ClaudeTurnStatus2) => {
|
|
3591
|
+
ClaudeTurnStatus2["Busy"] = "busy";
|
|
3592
|
+
ClaudeTurnStatus2["Idle"] = "idle";
|
|
3593
|
+
ClaudeTurnStatus2["Waiting"] = "waiting";
|
|
3594
|
+
return ClaudeTurnStatus2;
|
|
3595
|
+
})(ClaudeTurnStatus || {});
|
|
3596
|
+
var ClaudeJobState = /* @__PURE__ */ ((ClaudeJobState2) => {
|
|
3597
|
+
ClaudeJobState2["Working"] = "working";
|
|
3598
|
+
ClaudeJobState2["Blocked"] = "blocked";
|
|
3599
|
+
ClaudeJobState2["Done"] = "done";
|
|
3600
|
+
return ClaudeJobState2;
|
|
3601
|
+
})(ClaudeJobState || {});
|
|
3602
|
+
var PrMergeable = /* @__PURE__ */ ((PrMergeable2) => {
|
|
3603
|
+
PrMergeable2["Mergeable"] = "MERGEABLE";
|
|
3604
|
+
PrMergeable2["Conflicting"] = "CONFLICTING";
|
|
3605
|
+
PrMergeable2["Unknown"] = "UNKNOWN";
|
|
3606
|
+
return PrMergeable2;
|
|
3607
|
+
})(PrMergeable || {});
|
|
3608
|
+
var PrMergeStateStatus = /* @__PURE__ */ ((PrMergeStateStatus2) => {
|
|
3609
|
+
PrMergeStateStatus2["Behind"] = "BEHIND";
|
|
3610
|
+
PrMergeStateStatus2["Blocked"] = "BLOCKED";
|
|
3611
|
+
PrMergeStateStatus2["Clean"] = "CLEAN";
|
|
3612
|
+
PrMergeStateStatus2["Dirty"] = "DIRTY";
|
|
3613
|
+
PrMergeStateStatus2["Draft"] = "DRAFT";
|
|
3614
|
+
PrMergeStateStatus2["HasHooks"] = "HAS_HOOKS";
|
|
3615
|
+
PrMergeStateStatus2["Unknown"] = "UNKNOWN";
|
|
3616
|
+
PrMergeStateStatus2["Unstable"] = "UNSTABLE";
|
|
3617
|
+
return PrMergeStateStatus2;
|
|
3618
|
+
})(PrMergeStateStatus || {});
|
|
3619
|
+
var CiRollupState = /* @__PURE__ */ ((CiRollupState2) => {
|
|
3620
|
+
CiRollupState2["Success"] = "SUCCESS";
|
|
3621
|
+
CiRollupState2["Failure"] = "FAILURE";
|
|
3622
|
+
CiRollupState2["Error"] = "ERROR";
|
|
3623
|
+
CiRollupState2["Pending"] = "PENDING";
|
|
3624
|
+
CiRollupState2["Expected"] = "EXPECTED";
|
|
3625
|
+
return CiRollupState2;
|
|
3626
|
+
})(CiRollupState || {});
|
|
3627
|
+
|
|
3628
|
+
// src/watch/render.ts
|
|
3629
|
+
var SEVERITY_ORDER = ["alert" /* Alert */, "warning" /* Warning */, "notice" /* Notice */];
|
|
3630
|
+
function sessionLine(session) {
|
|
3631
|
+
const host = session.agent === "codex" /* Codex */ ? "codex" : session.kind ?? "claude";
|
|
3632
|
+
const activity = [session.turnStatus, session.jobState].filter(Boolean).join("/") || "active";
|
|
3633
|
+
const label = session.name ? ` ${session.name}` : "";
|
|
3634
|
+
return ` ${host.padEnd(11)} ${activity.padEnd(15)} ${shortSessionId(session.sessionId)}${label} ${session.cwd ?? ""}`.trimEnd();
|
|
3635
|
+
}
|
|
3636
|
+
function ownerLabel(slot) {
|
|
3637
|
+
if (!slot.ownerSessionId) return "no owner";
|
|
3638
|
+
const ownerState = slot.isOwnerSessionActive === void 0 ? "unknown" : slot.isOwnerSessionActive ? "active" : "ended";
|
|
3639
|
+
return `owner ${shortSessionId(slot.ownerSessionId)} (${ownerState})`;
|
|
3640
|
+
}
|
|
3641
|
+
function slotLine(slot) {
|
|
3642
|
+
const live = slot.live;
|
|
3643
|
+
const githubState = live ? [live.state.toLowerCase(), live.ciRollup ? `ci ${live.ciRollup.toLowerCase()}` : "", live.mergeStateStatus?.toLowerCase() ?? ""].filter(Boolean).join(", ") : "status unavailable";
|
|
3644
|
+
const registration = slot.isRegistered ? "registered" : "unregistered";
|
|
3645
|
+
return ` ${`${slot.pr.repo}#${slot.pr.number}`.padEnd(44)} ${slot.watcher.padEnd(9)} ${registration.padEnd(12)} ${ownerLabel(slot)} ${githubState}`;
|
|
3646
|
+
}
|
|
3647
|
+
function processSummary(snapshot) {
|
|
3648
|
+
const countOf = (kind) => snapshot.processes.filter((tracked) => tracked.kind === kind).length;
|
|
3649
|
+
const orphanedServers = snapshot.processes.filter(
|
|
3650
|
+
(tracked) => tracked.kind === "muggle-mcp-server" /* MuggleMcpServer */ && tracked.isOrphaned === true
|
|
3651
|
+
).length;
|
|
3652
|
+
return [
|
|
3653
|
+
`${countOf("claude-cli" /* ClaudeCli */)} claude`,
|
|
3654
|
+
`${countOf("codex-cli" /* CodexCli */)} codex`,
|
|
3655
|
+
`${countOf("muggle-mcp-server" /* MuggleMcpServer */)} muggle MCP servers (${orphanedServers} orphaned)`,
|
|
3656
|
+
`${countOf("pr-watch-loop" /* PrWatchLoop */)} PR watch loop processes`
|
|
3657
|
+
].join(", ");
|
|
3658
|
+
}
|
|
3659
|
+
function renderWatchStatus(snapshot, nowMs) {
|
|
3660
|
+
const lines = [];
|
|
3661
|
+
const snapshotAgeMs = nowMs - Date.parse(snapshot.takenAt);
|
|
3662
|
+
lines.push(`Muggle Watch \u2014 last tick ${formatDuration(snapshotAgeMs)} ago (${snapshot.takenAt})`, "");
|
|
3663
|
+
const claudeCount = snapshot.sessions.filter((session) => session.agent === "claude" /* Claude */).length;
|
|
3664
|
+
lines.push(`Sessions: ${claudeCount} Claude, ${snapshot.sessions.length - claudeCount} Codex`);
|
|
3665
|
+
lines.push(...snapshot.sessions.map(sessionLine), "");
|
|
3666
|
+
lines.push(`Processes: ${processSummary(snapshot)}`, "");
|
|
3667
|
+
lines.push(`PR watches: ${snapshot.slots.length} open`);
|
|
3668
|
+
lines.push(...snapshot.slots.map(slotLine), "");
|
|
3669
|
+
lines.push(`Findings: ${snapshot.findings.length}`);
|
|
3670
|
+
for (const severity of SEVERITY_ORDER) {
|
|
3671
|
+
for (const current of snapshot.findings.filter((candidate) => candidate.severity === severity)) {
|
|
3672
|
+
lines.push(` ${severity.toUpperCase().padEnd(8)} ${current.subject.padEnd(44)} ${current.code} ${current.message}`);
|
|
3673
|
+
}
|
|
3674
|
+
}
|
|
3675
|
+
if (snapshot.recoveries.length > 0) {
|
|
3676
|
+
lines.push("", "Recoveries:");
|
|
3677
|
+
for (const recovery of snapshot.recoveries) {
|
|
3678
|
+
lines.push(` session ${shortSessionId(recovery.ownerSessionId)} ${recovery.outcome} ${recovery.slotSlugs.join(", ")}`);
|
|
3679
|
+
}
|
|
3680
|
+
}
|
|
3681
|
+
if (snapshot.reload) {
|
|
3682
|
+
const countOf = (action) => snapshot.reload?.decisions.filter((decision) => decision.action === action).length ?? 0;
|
|
3683
|
+
lines.push(
|
|
3684
|
+
"",
|
|
3685
|
+
`Plugin reload: ${snapshot.reload.respawnedSessionIds.length} respawned, ${snapshot.reload.failedSessionIds.length} failed, ${countOf("defer" /* Defer */)} deferred, ${countOf("notify-manual" /* NotifyManual */)} need /reload-plugins by hand`
|
|
3686
|
+
);
|
|
3687
|
+
}
|
|
3688
|
+
return `${lines.join("\n")}
|
|
3689
|
+
`;
|
|
3690
|
+
}
|
|
3691
|
+
|
|
3692
|
+
// src/watch/constants.ts
|
|
3693
|
+
var WATCH_DIR_NAME = "watch";
|
|
3694
|
+
var WATCH_STATUS_FILE = "status.json";
|
|
3695
|
+
var WATCH_STATE_FILE = "state.json";
|
|
3696
|
+
var WATCH_EVENTS_FILE = "events.jsonl";
|
|
3697
|
+
var WATCH_EVENTS_ROTATE_BYTES = 5 * 1024 * 1024;
|
|
3698
|
+
var MONITOR_STDOUT_CAP_MS = 30 * 6e4;
|
|
3699
|
+
var WATCHER_REARM_GRACE_MS = 5 * 6e4;
|
|
3700
|
+
var CODEX_ACTIVE_WINDOW_MS = 10 * 6e4;
|
|
3701
|
+
var CODEX_ROLLOUT_DAY_DIRS_SCANNED = 7;
|
|
3702
|
+
var MAX_RESPAWNS_PER_TICK = 3;
|
|
3703
|
+
var MAX_RESUMES_PER_TICK = 2;
|
|
3704
|
+
var RECOVERY_COOLDOWN_MS = 30 * 6e4;
|
|
3705
|
+
var RECOVERY_MAX_ATTEMPTS = 3;
|
|
3706
|
+
var RECOVERY_ATTEMPT_WINDOW_MS = 24 * 60 * 6e4;
|
|
3707
|
+
var RECOVERY_RESUME_PROMPT = "/muggle:muggle-pr-followup reconcile";
|
|
3708
|
+
var PR_STATUS_BATCH_SIZE = 25;
|
|
3709
|
+
var TERMINAL_PR_RECHECK_MS = 6 * 60 * 6e4;
|
|
3710
|
+
var WATCH_COMMAND_TIMEOUT_MS = 3e4;
|
|
3711
|
+
var WATCH_COMMAND_MAX_BUFFER_BYTES = 64 * 1024 * 1024;
|
|
3712
|
+
var SESSION_FILE_HEAD_BYTES = 64 * 1024;
|
|
3713
|
+
var WATCH_LOCK_FILE = "watch.lock";
|
|
3714
|
+
var WATCH_LOCK_WAIT_MS = 6e4;
|
|
3715
|
+
var PR_WATCH_SLOTS_RELATIVE_PATH = ["muggle-do", "sessions"];
|
|
3716
|
+
var PR_POLLING_DISABLED_FILE = "polling.disabled";
|
|
3717
|
+
var WATCH_REGISTRATION_FILE = "watch-registration.json";
|
|
3718
|
+
var WATCH_REGISTRATION_SOURCE_CLI = "muggle-watch-cli";
|
|
3719
|
+
var MAX_ANCESTOR_HOPS = 8;
|
|
3720
|
+
var WATCH_NOTIFICATION_TITLE = "Muggle Watch";
|
|
3721
|
+
var WATCH_NOTIFICATION_MAX_LINES = 3;
|
|
3722
|
+
var WATCH_FINDING_SEVERITY = {
|
|
3723
|
+
["WATCHER_DEAD" /* WatcherDead */]: "alert" /* Alert */,
|
|
3724
|
+
["WATCHER_DEAF" /* WatcherDeaf */]: "alert" /* Alert */,
|
|
3725
|
+
["CI_FAILING" /* CiFailing */]: "alert" /* Alert */,
|
|
3726
|
+
["BASE_CONFLICT" /* BaseConflict */]: "alert" /* Alert */,
|
|
3727
|
+
["BEHIND_BASE" /* BehindBase */]: "warning" /* Warning */,
|
|
3728
|
+
["REVIEW_THREADS_UNRESOLVED" /* ReviewThreadsUnresolved */]: "warning" /* Warning */,
|
|
3729
|
+
["PR_STATUS_UNAVAILABLE" /* PrStatusUnavailable */]: "warning" /* Warning */,
|
|
3730
|
+
["ORPHANED_MCP_SERVER" /* OrphanedMcpServer */]: "warning" /* Warning */,
|
|
3731
|
+
["SLOT_TERMINAL_UNFINALIZED" /* SlotTerminalUnfinalized */]: "notice" /* Notice */
|
|
3732
|
+
};
|
|
3733
|
+
var CLAUDE_EXECUTABLE_PATTERN = /^claude$/;
|
|
3734
|
+
var CODEX_EXECUTABLE_PATTERN = /^codex(?:-[\w-]+)?$/;
|
|
3735
|
+
var COMMAND_LINE_EXECUTABLE_PATTERN = /^(?:claude|codex(?:-[\w-]+)?|node|bash)$/;
|
|
3736
|
+
var MUGGLE_MCP_SERVER_PATTERN = /@muggleai[\\/]works\b.*\bserve\b/;
|
|
3737
|
+
var PR_WATCH_LOOP_PATTERN = /pr-watch-loop\.sh\b.*?--slot\s+(?:"([^"]+)"|(\S+))/;
|
|
3738
|
+
var CLAUDE_SESSION_REGISTRY_DIR_NAME = "sessions";
|
|
3739
|
+
var CLAUDE_PROJECTS_DIR_NAME = "projects";
|
|
3740
|
+
var CLAUDE_INSTALLED_PLUGINS_RELATIVE_PATH = ["plugins", "installed_plugins.json"];
|
|
3741
|
+
var RELOAD_PLUGIN_SCOPE = "user";
|
|
3742
|
+
var CODEX_ROLLOUT_PREFIX = "rollout-";
|
|
3743
|
+
|
|
3744
|
+
// src/watch/field-parsers.ts
|
|
3745
|
+
function enumValueOf(values, candidate) {
|
|
3746
|
+
return Object.values(values).find((value) => value === candidate);
|
|
3747
|
+
}
|
|
3748
|
+
function optionalString(candidate) {
|
|
3749
|
+
return typeof candidate === "string" && candidate.length > 0 ? candidate : void 0;
|
|
3750
|
+
}
|
|
3751
|
+
function readFileHead(filePath) {
|
|
3752
|
+
let fileDescriptor;
|
|
3753
|
+
try {
|
|
3754
|
+
fileDescriptor = openSync(filePath, "r");
|
|
3755
|
+
const buffer = Buffer.alloc(SESSION_FILE_HEAD_BYTES);
|
|
3756
|
+
const bytesRead = readSync(fileDescriptor, buffer, 0, SESSION_FILE_HEAD_BYTES, 0);
|
|
3757
|
+
return buffer.subarray(0, bytesRead).toString("utf-8");
|
|
3758
|
+
} catch {
|
|
3759
|
+
return void 0;
|
|
3760
|
+
} finally {
|
|
3761
|
+
if (fileDescriptor !== void 0) closeSync(fileDescriptor);
|
|
3762
|
+
}
|
|
3763
|
+
}
|
|
3764
|
+
function cwdFromSessionHead(head) {
|
|
3765
|
+
const parts = head.match(/"cwd"\s*:\s*("(?:[^"\\]|\\.)*")/);
|
|
3766
|
+
if (!parts) return void 0;
|
|
3767
|
+
try {
|
|
3768
|
+
return optionalString(JSON.parse(parts[1]));
|
|
3769
|
+
} catch {
|
|
3770
|
+
return void 0;
|
|
3771
|
+
}
|
|
3772
|
+
}
|
|
3773
|
+
|
|
3774
|
+
// src/watch/claude-sessions.ts
|
|
3775
|
+
function readPidsBySessionId(registryDir) {
|
|
3776
|
+
const pidsBySessionId = /* @__PURE__ */ new Map();
|
|
3777
|
+
let fileNames;
|
|
3778
|
+
try {
|
|
3779
|
+
fileNames = readdirSync(registryDir).filter((fileName) => fileName.endsWith(".json"));
|
|
3780
|
+
} catch {
|
|
3781
|
+
return pidsBySessionId;
|
|
3782
|
+
}
|
|
3783
|
+
for (const fileName of fileNames) {
|
|
3784
|
+
try {
|
|
3785
|
+
const entry = JSON.parse(readFileSync(join(registryDir, fileName), "utf-8"));
|
|
3786
|
+
if (typeof entry.pid === "number" && typeof entry.sessionId === "string") {
|
|
3787
|
+
pidsBySessionId.set(entry.sessionId, entry.pid);
|
|
3788
|
+
}
|
|
3789
|
+
} catch {
|
|
3790
|
+
continue;
|
|
3791
|
+
}
|
|
3792
|
+
}
|
|
3793
|
+
return pidsBySessionId;
|
|
3794
|
+
}
|
|
3795
|
+
function readClaudeSessions(runCommand, registryDir) {
|
|
3796
|
+
const outcome = runCommand("claude", ["agents", "--json"]);
|
|
3797
|
+
if (!outcome || outcome.exitCode !== 0) return null;
|
|
3798
|
+
let listings;
|
|
3799
|
+
try {
|
|
3800
|
+
const parsed = JSON.parse(outcome.stdout);
|
|
3801
|
+
if (!Array.isArray(parsed)) return null;
|
|
3802
|
+
listings = parsed;
|
|
3803
|
+
} catch {
|
|
3804
|
+
return null;
|
|
3805
|
+
}
|
|
3806
|
+
const pidsBySessionId = readPidsBySessionId(registryDir);
|
|
3807
|
+
const sessions = [];
|
|
3808
|
+
for (const listing of listings) {
|
|
3809
|
+
const sessionId = optionalString(listing.sessionId);
|
|
3810
|
+
if (!sessionId) continue;
|
|
3811
|
+
sessions.push({
|
|
3812
|
+
agent: "claude" /* Claude */,
|
|
3813
|
+
sessionId,
|
|
3814
|
+
shortId: optionalString(listing.id),
|
|
3815
|
+
name: optionalString(listing.name),
|
|
3816
|
+
cwd: optionalString(listing.cwd),
|
|
3817
|
+
kind: enumValueOf(ClaudeSessionKind, listing.kind),
|
|
3818
|
+
turnStatus: enumValueOf(ClaudeTurnStatus, listing.status),
|
|
3819
|
+
jobState: enumValueOf(ClaudeJobState, listing.state),
|
|
3820
|
+
startedAtMs: typeof listing.startedAt === "number" ? listing.startedAt : void 0,
|
|
3821
|
+
pid: pidsBySessionId.get(sessionId)
|
|
3822
|
+
});
|
|
3823
|
+
}
|
|
3824
|
+
return sessions;
|
|
3825
|
+
}
|
|
3826
|
+
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;
|
|
3827
|
+
function sortedChildDirsDescending(dir) {
|
|
3828
|
+
try {
|
|
3829
|
+
return readdirSync(dir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort().reverse();
|
|
3830
|
+
} catch {
|
|
3831
|
+
return [];
|
|
3832
|
+
}
|
|
3833
|
+
}
|
|
3834
|
+
function newestDayDirs(sessionsDir, limit) {
|
|
3835
|
+
const dayDirs = [];
|
|
3836
|
+
for (const year of sortedChildDirsDescending(sessionsDir)) {
|
|
3837
|
+
for (const month of sortedChildDirsDescending(join(sessionsDir, year))) {
|
|
3838
|
+
for (const day of sortedChildDirsDescending(join(sessionsDir, year, month))) {
|
|
3839
|
+
dayDirs.push(join(sessionsDir, year, month, day));
|
|
3840
|
+
if (dayDirs.length >= limit) return dayDirs;
|
|
3841
|
+
}
|
|
3842
|
+
}
|
|
3843
|
+
}
|
|
3844
|
+
return dayDirs;
|
|
3845
|
+
}
|
|
3846
|
+
function readCodexSessions(sessionsDir, nowMs) {
|
|
3847
|
+
const sessions = [];
|
|
3848
|
+
for (const dayDir of newestDayDirs(sessionsDir, CODEX_ROLLOUT_DAY_DIRS_SCANNED)) {
|
|
3849
|
+
let fileNames;
|
|
3850
|
+
try {
|
|
3851
|
+
fileNames = readdirSync(dayDir).filter((fileName) => fileName.startsWith(CODEX_ROLLOUT_PREFIX));
|
|
3852
|
+
} catch {
|
|
3853
|
+
continue;
|
|
3854
|
+
}
|
|
3855
|
+
for (const fileName of fileNames) {
|
|
3856
|
+
const sessionId = fileName.match(ROLLOUT_SESSION_ID)?.[1];
|
|
3857
|
+
if (!sessionId) continue;
|
|
3858
|
+
const rolloutPath = join(dayDir, fileName);
|
|
3859
|
+
let lastActivityAtMs;
|
|
3860
|
+
try {
|
|
3861
|
+
lastActivityAtMs = statSync(rolloutPath).mtimeMs;
|
|
3862
|
+
} catch {
|
|
3863
|
+
continue;
|
|
3864
|
+
}
|
|
3865
|
+
if (nowMs - lastActivityAtMs > CODEX_ACTIVE_WINDOW_MS) continue;
|
|
3866
|
+
const head = readFileHead(rolloutPath);
|
|
3867
|
+
sessions.push({
|
|
3868
|
+
agent: "codex" /* Codex */,
|
|
3869
|
+
sessionId,
|
|
3870
|
+
cwd: head === void 0 ? void 0 : cwdFromSessionHead(head),
|
|
3871
|
+
lastActivityAtMs
|
|
3872
|
+
});
|
|
3873
|
+
}
|
|
3874
|
+
}
|
|
3875
|
+
return sessions;
|
|
3876
|
+
}
|
|
3877
|
+
var defaultCommandRunner = (executable, args, options) => {
|
|
3878
|
+
const spawned = spawnSync(executable, args, {
|
|
3879
|
+
cwd: options?.cwd,
|
|
3880
|
+
encoding: "utf-8",
|
|
3881
|
+
maxBuffer: WATCH_COMMAND_MAX_BUFFER_BYTES,
|
|
3882
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
3883
|
+
timeout: WATCH_COMMAND_TIMEOUT_MS,
|
|
3884
|
+
windowsHide: true
|
|
3885
|
+
});
|
|
3886
|
+
if (spawned.error || spawned.status === null) return null;
|
|
3887
|
+
return { exitCode: spawned.status, stdout: spawned.stdout };
|
|
3888
|
+
};
|
|
3889
|
+
|
|
3890
|
+
// src/guardrails/constants.ts
|
|
3891
|
+
var WATCH_HEARTBEAT_STALE_MS = 15 * 6e4;
|
|
3892
|
+
var TERMINAL_SLOT_PR_STATES = ["merged", "closed"];
|
|
3893
|
+
var STOPPED_SLOT_SUFFIX = ".stopped";
|
|
3894
|
+
function mcpToolNamePattern(hyphenatedSource) {
|
|
3895
|
+
return new RegExp(hyphenatedSource.replaceAll("-", "[-_]"), "i");
|
|
3896
|
+
}
|
|
3897
|
+
mcpToolNamePattern("muggle-local-telemetry-skill-emit");
|
|
3898
|
+
mcpToolNamePattern("muggle-local-(execute-test-generation|execute-replay)");
|
|
3899
|
+
mcpToolNamePattern("muggle-local-telemetry-event-emit");
|
|
3900
|
+
mcpToolNamePattern("muggle-remote-user-feedback-create");
|
|
3901
|
+
var LOCK_POLL_INTERVAL_MS = 10;
|
|
3902
|
+
|
|
3903
|
+
// src/guardrails/types.ts
|
|
3904
|
+
var ProviderPrState = /* @__PURE__ */ ((ProviderPrState2) => {
|
|
3905
|
+
ProviderPrState2["Open"] = "OPEN";
|
|
3906
|
+
ProviderPrState2["Merged"] = "MERGED";
|
|
3907
|
+
ProviderPrState2["Closed"] = "CLOSED";
|
|
3908
|
+
ProviderPrState2["Unreachable"] = "UNREACHABLE";
|
|
3909
|
+
return ProviderPrState2;
|
|
3910
|
+
})(ProviderPrState || {});
|
|
3911
|
+
|
|
3912
|
+
// src/watch/findings.ts
|
|
3913
|
+
function resolveWatcherLiveness(loop, heartbeatAgeMs, isOwnerSessionActive, isProcessTableKnown) {
|
|
3914
|
+
const isHeartbeatWithin = (windowMs) => heartbeatAgeMs !== void 0 && heartbeatAgeMs <= windowMs;
|
|
3915
|
+
if (!isProcessTableKnown) {
|
|
3916
|
+
return isHeartbeatWithin(WATCH_HEARTBEAT_STALE_MS) ? "polling" /* Polling */ : "dead" /* Dead */;
|
|
3917
|
+
}
|
|
3918
|
+
if (loop) {
|
|
3919
|
+
const hasOutlivedMonitor = (loop.ageMs ?? 0) > MONITOR_STDOUT_CAP_MS;
|
|
3920
|
+
return hasOutlivedMonitor || isOwnerSessionActive === false ? "deaf" /* Deaf */ : "polling" /* Polling */;
|
|
3921
|
+
}
|
|
3922
|
+
return isHeartbeatWithin(WATCHER_REARM_GRACE_MS) ? "rearming" /* Rearming */ : "dead" /* Dead */;
|
|
3923
|
+
}
|
|
3924
|
+
function oldestLoopFor(slug, processes) {
|
|
3925
|
+
return processes.filter((tracked) => tracked.kind === "pr-watch-loop" /* PrWatchLoop */ && tracked.watchSlotSlug === slug).sort((left, right) => (right.ageMs ?? 0) - (left.ageMs ?? 0))[0];
|
|
3926
|
+
}
|
|
3927
|
+
function assessWatchSlots(slots, processes, activeSessionIds, liveStatusesByUrl, nowMs) {
|
|
3928
|
+
const assessments = [];
|
|
3929
|
+
for (const slot of slots) {
|
|
3930
|
+
const loop = processes ? oldestLoopFor(slot.slug, processes) : void 0;
|
|
3931
|
+
const heartbeatAgeMs = slot.heartbeatMtimeMs === void 0 ? void 0 : Math.max(0, nowMs - slot.heartbeatMtimeMs);
|
|
3932
|
+
const isOwnerSessionActive = slot.ownerSessionId === void 0 || activeSessionIds === null ? void 0 : activeSessionIds.has(slot.ownerSessionId);
|
|
3933
|
+
const watcher = resolveWatcherLiveness(loop, heartbeatAgeMs, isOwnerSessionActive, processes !== null);
|
|
3934
|
+
for (const pr of slot.openPrs) {
|
|
3935
|
+
assessments.push({
|
|
3936
|
+
slug: slot.slug,
|
|
3937
|
+
slotDir: slot.slotDir,
|
|
3938
|
+
pr,
|
|
3939
|
+
isRegistered: slot.isRegistered,
|
|
3940
|
+
watcher,
|
|
3941
|
+
loopPid: loop?.pid,
|
|
3942
|
+
loopAgeMs: loop?.ageMs,
|
|
3943
|
+
heartbeatAgeMs,
|
|
3944
|
+
ownerSessionId: slot.ownerSessionId,
|
|
3945
|
+
isOwnerSessionActive,
|
|
3946
|
+
live: liveStatusesByUrl.get(pr.url)
|
|
3947
|
+
});
|
|
3948
|
+
}
|
|
3949
|
+
}
|
|
3950
|
+
return assessments;
|
|
3951
|
+
}
|
|
3952
|
+
function finding(code, keyParts, subject, message) {
|
|
3953
|
+
return {
|
|
3954
|
+
key: [code, ...keyParts.map((part) => String(part ?? ""))].join(":"),
|
|
3955
|
+
code,
|
|
3956
|
+
severity: WATCH_FINDING_SEVERITY[code],
|
|
3957
|
+
subject,
|
|
3958
|
+
message
|
|
3959
|
+
};
|
|
3960
|
+
}
|
|
3961
|
+
function ownerPhrase(assessment) {
|
|
3962
|
+
if (assessment.ownerSessionId === void 0) {
|
|
3963
|
+
return `slot has no owner \u2014 adopt it with /muggle:muggle-pr-followup adopt ${assessment.slug}`;
|
|
3964
|
+
}
|
|
3965
|
+
const owner = shortSessionId(assessment.ownerSessionId);
|
|
3966
|
+
if (assessment.isOwnerSessionActive === true) {
|
|
3967
|
+
return `owner session ${owner} is running \u2014 run /muggle:muggle-pr-followup reconcile there`;
|
|
3968
|
+
}
|
|
3969
|
+
if (assessment.isOwnerSessionActive === false) {
|
|
3970
|
+
return assessment.isRegistered ? `owner session ${owner} has ended` : `owner session ${owner} has ended; slot is not registered for recovery`;
|
|
3971
|
+
}
|
|
3972
|
+
return `owner session ${owner} could not be checked`;
|
|
3973
|
+
}
|
|
3974
|
+
function watcherFinding(assessment, subject) {
|
|
3975
|
+
if (assessment.watcher === "dead" /* Dead */) {
|
|
3976
|
+
const heartbeat = assessment.heartbeatAgeMs === void 0 ? "no heartbeat" : `heartbeat ${formatDuration(assessment.heartbeatAgeMs)} old`;
|
|
3977
|
+
return finding(
|
|
3978
|
+
"WATCHER_DEAD" /* WatcherDead */,
|
|
3979
|
+
[assessment.pr.url],
|
|
3980
|
+
subject,
|
|
3981
|
+
`no watch loop is running (${heartbeat}); ${ownerPhrase(assessment)}`
|
|
3982
|
+
);
|
|
3983
|
+
}
|
|
3984
|
+
if (assessment.watcher === "deaf" /* Deaf */) {
|
|
3985
|
+
const reason = assessment.isOwnerSessionActive === false ? `its owner session ${shortSessionId(assessment.ownerSessionId ?? "")} has ended` : `it has run ${formatDuration(assessment.loopAgeMs ?? 0)}, past the 30-minute Monitor cap`;
|
|
3986
|
+
return finding(
|
|
3987
|
+
"WATCHER_DEAF" /* WatcherDeaf */,
|
|
3988
|
+
[assessment.pr.url, assessment.loopPid],
|
|
3989
|
+
subject,
|
|
3990
|
+
`watch loop pid ${assessment.loopPid} reports to no session: ${reason}`
|
|
3991
|
+
);
|
|
3992
|
+
}
|
|
3993
|
+
return void 0;
|
|
3994
|
+
}
|
|
3995
|
+
function prStateFindings(assessment, live, subject) {
|
|
3996
|
+
const prFindings = [];
|
|
3997
|
+
const head = shortSha(live.headSha);
|
|
3998
|
+
if (live.ciRollup === "FAILURE" /* Failure */ || live.ciRollup === "ERROR" /* Error */) {
|
|
3999
|
+
prFindings.push(finding(
|
|
4000
|
+
"CI_FAILING" /* CiFailing */,
|
|
4001
|
+
[assessment.pr.url, live.headSha],
|
|
4002
|
+
subject,
|
|
4003
|
+
`checks on ${head} are ${live.ciRollup.toLowerCase()}`
|
|
4004
|
+
));
|
|
4005
|
+
}
|
|
4006
|
+
if (live.mergeable === "CONFLICTING" /* Conflicting */ || live.mergeStateStatus === "DIRTY" /* Dirty */) {
|
|
4007
|
+
prFindings.push(finding(
|
|
4008
|
+
"BASE_CONFLICT" /* BaseConflict */,
|
|
4009
|
+
[assessment.pr.url, live.headSha],
|
|
4010
|
+
subject,
|
|
4011
|
+
`head ${head} conflicts with its base \u2014 rebase due`
|
|
4012
|
+
));
|
|
4013
|
+
} else if (live.mergeStateStatus === "BEHIND" /* Behind */) {
|
|
4014
|
+
prFindings.push(finding(
|
|
4015
|
+
"BEHIND_BASE" /* BehindBase */,
|
|
4016
|
+
[assessment.pr.url, live.headSha],
|
|
4017
|
+
subject,
|
|
4018
|
+
`head ${head} is behind its base`
|
|
4019
|
+
));
|
|
4020
|
+
}
|
|
4021
|
+
if (live.unresolvedThreadCount > 0) {
|
|
4022
|
+
const threads = live.unresolvedThreadCount === 1 ? "thread" : "threads";
|
|
4023
|
+
prFindings.push(finding(
|
|
4024
|
+
"REVIEW_THREADS_UNRESOLVED" /* ReviewThreadsUnresolved */,
|
|
4025
|
+
[assessment.pr.url],
|
|
4026
|
+
subject,
|
|
4027
|
+
`${live.unresolvedThreadCount} unresolved review ${threads}`
|
|
4028
|
+
));
|
|
4029
|
+
}
|
|
4030
|
+
return prFindings;
|
|
4031
|
+
}
|
|
4032
|
+
function deriveWatchFindings(assessments, processes, isPollingDisabled) {
|
|
4033
|
+
const findings = [];
|
|
4034
|
+
for (const assessment of assessments) {
|
|
4035
|
+
const subject = `${assessment.pr.repo}#${assessment.pr.number}`;
|
|
4036
|
+
const live = assessment.live;
|
|
4037
|
+
if (live && (live.state === "MERGED" /* Merged */ || live.state === "CLOSED" /* Closed */)) {
|
|
4038
|
+
findings.push(finding(
|
|
4039
|
+
"SLOT_TERMINAL_UNFINALIZED" /* SlotTerminalUnfinalized */,
|
|
4040
|
+
[assessment.pr.url],
|
|
4041
|
+
subject,
|
|
4042
|
+
`PR is ${live.state.toLowerCase()} but slot ${assessment.slug} is still open \u2014 reconcile finalizes it`
|
|
4043
|
+
));
|
|
4044
|
+
continue;
|
|
4045
|
+
}
|
|
4046
|
+
if (!live) {
|
|
4047
|
+
findings.push(finding(
|
|
4048
|
+
"PR_STATUS_UNAVAILABLE" /* PrStatusUnavailable */,
|
|
4049
|
+
[assessment.pr.url],
|
|
4050
|
+
subject,
|
|
4051
|
+
`GitHub did not return this PR's status (watcher ${assessment.watcher})`
|
|
4052
|
+
));
|
|
4053
|
+
continue;
|
|
4054
|
+
}
|
|
4055
|
+
const watcherIssue = isPollingDisabled ? void 0 : watcherFinding(assessment, subject);
|
|
4056
|
+
if (watcherIssue) findings.push(watcherIssue);
|
|
4057
|
+
findings.push(...prStateFindings(assessment, live, subject));
|
|
4058
|
+
}
|
|
4059
|
+
for (const tracked of processes) {
|
|
4060
|
+
if (tracked.kind !== "muggle-mcp-server" /* MuggleMcpServer */ || tracked.isOrphaned !== true) continue;
|
|
4061
|
+
findings.push(finding(
|
|
4062
|
+
"ORPHANED_MCP_SERVER" /* OrphanedMcpServer */,
|
|
4063
|
+
[tracked.pid],
|
|
4064
|
+
`pid ${tracked.pid}`,
|
|
4065
|
+
"muggle MCP server outlived the agent that launched it"
|
|
4066
|
+
));
|
|
4067
|
+
}
|
|
4068
|
+
return findings;
|
|
4069
|
+
}
|
|
4070
|
+
function reconcileActiveFindings(previous, current, nowIso) {
|
|
4071
|
+
const activeFindings = {};
|
|
4072
|
+
const raised = [];
|
|
4073
|
+
for (const currentFinding of current) {
|
|
4074
|
+
const earlier = previous[currentFinding.key];
|
|
4075
|
+
if (!earlier) raised.push(currentFinding);
|
|
4076
|
+
activeFindings[currentFinding.key] = {
|
|
4077
|
+
code: currentFinding.code,
|
|
4078
|
+
severity: currentFinding.severity,
|
|
4079
|
+
subject: currentFinding.subject,
|
|
4080
|
+
message: currentFinding.message,
|
|
4081
|
+
firstSeenAt: earlier?.firstSeenAt ?? nowIso
|
|
4082
|
+
};
|
|
4083
|
+
}
|
|
4084
|
+
const cleared = Object.entries(previous).filter(([key]) => !(key in activeFindings)).map(([key, record]) => ({ key, record }));
|
|
4085
|
+
return { activeFindings, raised, cleared };
|
|
4086
|
+
}
|
|
4087
|
+
function isProcessAlive(pid) {
|
|
4088
|
+
try {
|
|
4089
|
+
process.kill(pid, 0);
|
|
4090
|
+
return true;
|
|
4091
|
+
} catch (error) {
|
|
4092
|
+
return error.code === "EPERM";
|
|
4093
|
+
}
|
|
4094
|
+
}
|
|
4095
|
+
function recordedHolder(lockPath) {
|
|
4096
|
+
try {
|
|
4097
|
+
return JSON.parse(readFileSync(lockPath, "utf-8"));
|
|
4098
|
+
} catch {
|
|
4099
|
+
return void 0;
|
|
4100
|
+
}
|
|
4101
|
+
}
|
|
4102
|
+
function breakLockIfHolderIsDead(lockPath) {
|
|
4103
|
+
const holder = recordedHolder(lockPath);
|
|
4104
|
+
if (!holder) return;
|
|
4105
|
+
if (holder.host !== hostname() || isProcessAlive(holder.pid)) return;
|
|
4106
|
+
try {
|
|
4107
|
+
unlinkSync(lockPath);
|
|
4108
|
+
} catch {
|
|
4109
|
+
return;
|
|
4110
|
+
}
|
|
4111
|
+
}
|
|
4112
|
+
function pauseBetweenAttempts() {
|
|
4113
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, LOCK_POLL_INTERVAL_MS);
|
|
4114
|
+
}
|
|
4115
|
+
function withFileLock(lockPath, waitMs, run) {
|
|
4116
|
+
const deadline = Date.now() + waitMs;
|
|
4117
|
+
for (; ; ) {
|
|
4118
|
+
let lockFileDescriptor;
|
|
4119
|
+
try {
|
|
4120
|
+
lockFileDescriptor = openSync(lockPath, "wx");
|
|
4121
|
+
writeSync(
|
|
4122
|
+
lockFileDescriptor,
|
|
4123
|
+
JSON.stringify({
|
|
4124
|
+
pid: process.pid,
|
|
4125
|
+
host: hostname(),
|
|
4126
|
+
acquiredAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
4127
|
+
})
|
|
4128
|
+
);
|
|
4129
|
+
} catch {
|
|
4130
|
+
breakLockIfHolderIsDead(lockPath);
|
|
4131
|
+
if (Date.now() >= deadline) return void 0;
|
|
4132
|
+
pauseBetweenAttempts();
|
|
4133
|
+
continue;
|
|
4134
|
+
}
|
|
4135
|
+
try {
|
|
4136
|
+
return run();
|
|
4137
|
+
} finally {
|
|
4138
|
+
closeSync(lockFileDescriptor);
|
|
4139
|
+
try {
|
|
4140
|
+
unlinkSync(lockPath);
|
|
4141
|
+
} catch {
|
|
4142
|
+
}
|
|
4143
|
+
}
|
|
4144
|
+
}
|
|
4145
|
+
}
|
|
4146
|
+
|
|
4147
|
+
// src/watch/ledger.ts
|
|
4148
|
+
function emptyLedgerState() {
|
|
4149
|
+
return { activeFindings: {}, recoveryAttemptsByOwner: {}, terminalPrsByUrl: {} };
|
|
4150
|
+
}
|
|
4151
|
+
function writeJsonAtomically(filePath, contents) {
|
|
4152
|
+
const stagingPath = `${filePath}.${process.pid}.tmp`;
|
|
4153
|
+
writeFileSync(stagingPath, `${JSON.stringify(contents, null, 2)}
|
|
4154
|
+
`);
|
|
4155
|
+
renameSync(stagingPath, filePath);
|
|
4156
|
+
}
|
|
4157
|
+
function readWatchLedgerState(watchDir) {
|
|
4158
|
+
try {
|
|
4159
|
+
const parsed = JSON.parse(readFileSync(join(watchDir, WATCH_STATE_FILE), "utf-8"));
|
|
4160
|
+
return {
|
|
4161
|
+
...parsed,
|
|
4162
|
+
activeFindings: parsed.activeFindings ?? {},
|
|
4163
|
+
recoveryAttemptsByOwner: parsed.recoveryAttemptsByOwner ?? {},
|
|
4164
|
+
terminalPrsByUrl: parsed.terminalPrsByUrl ?? {}
|
|
4165
|
+
};
|
|
4166
|
+
} catch {
|
|
4167
|
+
return emptyLedgerState();
|
|
4168
|
+
}
|
|
4169
|
+
}
|
|
4170
|
+
function writeWatchLedgerState(watchDir, state) {
|
|
4171
|
+
mkdirSync(watchDir, { recursive: true });
|
|
4172
|
+
writeJsonAtomically(join(watchDir, WATCH_STATE_FILE), state);
|
|
4173
|
+
}
|
|
4174
|
+
function readWatchSnapshot(watchDir) {
|
|
4175
|
+
try {
|
|
4176
|
+
return JSON.parse(readFileSync(join(watchDir, WATCH_STATUS_FILE), "utf-8"));
|
|
4177
|
+
} catch {
|
|
4178
|
+
return null;
|
|
4179
|
+
}
|
|
4180
|
+
}
|
|
4181
|
+
function writeWatchSnapshot(watchDir, snapshot) {
|
|
4182
|
+
mkdirSync(watchDir, { recursive: true });
|
|
4183
|
+
writeJsonAtomically(join(watchDir, WATCH_STATUS_FILE), snapshot);
|
|
4184
|
+
}
|
|
4185
|
+
function appendWatchEvents(watchDir, events) {
|
|
4186
|
+
if (events.length === 0) return;
|
|
4187
|
+
mkdirSync(watchDir, { recursive: true });
|
|
4188
|
+
const eventsPath = join(watchDir, WATCH_EVENTS_FILE);
|
|
4189
|
+
try {
|
|
4190
|
+
if (statSync(eventsPath).size > WATCH_EVENTS_ROTATE_BYTES) {
|
|
4191
|
+
renameSync(eventsPath, join(watchDir, WATCH_EVENTS_FILE.replace(/\.jsonl$/, ".1.jsonl")));
|
|
4192
|
+
}
|
|
4193
|
+
} catch {
|
|
4194
|
+
}
|
|
4195
|
+
appendFileSync(eventsPath, events.map((event) => `${JSON.stringify(event)}
|
|
4196
|
+
`).join(""));
|
|
4197
|
+
}
|
|
4198
|
+
function withWatchLock(watchDir, run, waitMs = WATCH_LOCK_WAIT_MS) {
|
|
4199
|
+
mkdirSync(watchDir, { recursive: true });
|
|
4200
|
+
return withFileLock(join(watchDir, WATCH_LOCK_FILE), waitMs, run);
|
|
4201
|
+
}
|
|
4202
|
+
|
|
4203
|
+
// src/watch/notify.ts
|
|
4204
|
+
function composeTickNotification(raised, recoveries, reload) {
|
|
4205
|
+
const lines = [];
|
|
4206
|
+
for (const raisedFinding of raised) {
|
|
4207
|
+
if (raisedFinding.severity === "alert" /* Alert */) {
|
|
4208
|
+
lines.push(`${raisedFinding.subject}: ${raisedFinding.message}`);
|
|
4209
|
+
}
|
|
4210
|
+
}
|
|
4211
|
+
for (const recovery of recoveries) {
|
|
4212
|
+
const owner = shortSessionId(recovery.ownerSessionId);
|
|
4213
|
+
if (recovery.outcome === "resumed" /* Resumed */) {
|
|
4214
|
+
lines.push(`Resumed session ${owner} to re-arm ${recovery.slotSlugs.join(", ")}`);
|
|
4215
|
+
} else if (recovery.outcome === "resume-failed" /* ResumeFailed */) {
|
|
4216
|
+
lines.push(`Could not resume session ${owner} for ${recovery.slotSlugs.join(", ")}`);
|
|
4217
|
+
}
|
|
4218
|
+
}
|
|
4219
|
+
const manualReloads = (reload?.decisions ?? []).filter((decision) => decision.action === "notify-manual" /* NotifyManual */);
|
|
4220
|
+
if (manualReloads.length > 0) {
|
|
4221
|
+
const sessionNames = manualReloads.map((decision) => decision.name ?? shortSessionId(decision.sessionId));
|
|
4222
|
+
lines.push(`Plugins changed \u2014 run /reload-plugins in: ${sessionNames.join(", ")}`);
|
|
4223
|
+
}
|
|
4224
|
+
if (lines.length <= WATCH_NOTIFICATION_MAX_LINES) return lines;
|
|
4225
|
+
return [...lines.slice(0, WATCH_NOTIFICATION_MAX_LINES), `+${lines.length - WATCH_NOTIFICATION_MAX_LINES} more \u2014 muggle watch status`];
|
|
4226
|
+
}
|
|
4227
|
+
function powershellLiteral(text) {
|
|
4228
|
+
return `'${text.replace(/'/g, "''")}'`;
|
|
4229
|
+
}
|
|
4230
|
+
function buildWindowsToastScript(title, body) {
|
|
4231
|
+
return [
|
|
4232
|
+
"$ErrorActionPreference = 'Stop'",
|
|
4233
|
+
"[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null",
|
|
4234
|
+
"$toastXml = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastText02)",
|
|
4235
|
+
"$textNodes = $toastXml.GetElementsByTagName('text')",
|
|
4236
|
+
`$textNodes.Item(0).AppendChild($toastXml.CreateTextNode(${powershellLiteral(title)})) | Out-Null`,
|
|
4237
|
+
`$textNodes.Item(1).AppendChild($toastXml.CreateTextNode(${powershellLiteral(body)})) | Out-Null`,
|
|
4238
|
+
"[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('MuggleWatch').Show([Windows.UI.Notifications.ToastNotification]::new($toastXml))"
|
|
4239
|
+
].join("\n");
|
|
4240
|
+
}
|
|
4241
|
+
function appleScriptLiteral(text) {
|
|
4242
|
+
return `"${text.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
|
|
4243
|
+
}
|
|
4244
|
+
function createDesktopNotifier(platform4, runCommand) {
|
|
4245
|
+
return (title, lines) => {
|
|
4246
|
+
if (lines.length === 0) return;
|
|
4247
|
+
const body = lines.join("\n");
|
|
4248
|
+
if (platform4 === "win32") {
|
|
4249
|
+
const encodedScript = Buffer.from(buildWindowsToastScript(title, body), "utf16le").toString("base64");
|
|
4250
|
+
runCommand("powershell.exe", ["-NoProfile", "-NonInteractive", "-EncodedCommand", encodedScript]);
|
|
4251
|
+
} else if (platform4 === "darwin") {
|
|
4252
|
+
runCommand("osascript", ["-e", `display notification ${appleScriptLiteral(body)} with title ${appleScriptLiteral(title)}`]);
|
|
4253
|
+
} else {
|
|
4254
|
+
runCommand("notify-send", [title, body]);
|
|
4255
|
+
}
|
|
4256
|
+
};
|
|
4257
|
+
}
|
|
4258
|
+
function resolveWatchPaths(env = process.env) {
|
|
4259
|
+
const muggleDataDir = getDataDir();
|
|
4260
|
+
const claudeConfigDir = env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude");
|
|
4261
|
+
const codexHome = env.CODEX_HOME || join(homedir(), ".codex");
|
|
4262
|
+
return {
|
|
4263
|
+
watchDir: join(muggleDataDir, WATCH_DIR_NAME),
|
|
4264
|
+
slotsDir: join(muggleDataDir, ...PR_WATCH_SLOTS_RELATIVE_PATH),
|
|
4265
|
+
claudeSessionRegistryDir: join(claudeConfigDir, CLAUDE_SESSION_REGISTRY_DIR_NAME),
|
|
4266
|
+
claudeProjectsDir: join(claudeConfigDir, CLAUDE_PROJECTS_DIR_NAME),
|
|
4267
|
+
claudeInstalledPluginsFile: join(claudeConfigDir, ...CLAUDE_INSTALLED_PLUGINS_RELATIVE_PATH),
|
|
4268
|
+
codexSessionsDir: join(codexHome, "sessions")
|
|
4269
|
+
};
|
|
4270
|
+
}
|
|
4271
|
+
function readPluginFingerprint(installedPluginsFile) {
|
|
4272
|
+
let plugins;
|
|
4273
|
+
try {
|
|
4274
|
+
const parsed = JSON.parse(readFileSync(installedPluginsFile, "utf-8"));
|
|
4275
|
+
if (!parsed.plugins || typeof parsed.plugins !== "object") return null;
|
|
4276
|
+
plugins = parsed.plugins;
|
|
4277
|
+
} catch {
|
|
4278
|
+
return null;
|
|
4279
|
+
}
|
|
4280
|
+
const identities = [];
|
|
4281
|
+
let changedAtMs;
|
|
4282
|
+
for (const pluginName of Object.keys(plugins).sort()) {
|
|
4283
|
+
const installs = Array.isArray(plugins[pluginName]) ? plugins[pluginName] : [];
|
|
4284
|
+
for (const install of installs) {
|
|
4285
|
+
if (install.scope !== RELOAD_PLUGIN_SCOPE) continue;
|
|
4286
|
+
identities.push(`${pluginName}@${String(install.version)}#${String(install.gitCommitSha)}@${String(install.lastUpdated)}`);
|
|
4287
|
+
const updatedAtMs = typeof install.lastUpdated === "string" ? Date.parse(install.lastUpdated) : NaN;
|
|
4288
|
+
if (!Number.isNaN(updatedAtMs)) changedAtMs = Math.max(changedAtMs ?? 0, updatedAtMs);
|
|
4289
|
+
}
|
|
4290
|
+
}
|
|
4291
|
+
return {
|
|
4292
|
+
fingerprint: createHash("sha256").update(identities.join("\n")).digest("hex"),
|
|
4293
|
+
changedAtMs
|
|
4294
|
+
};
|
|
4295
|
+
}
|
|
4296
|
+
|
|
4297
|
+
// src/watch/pr-status.ts
|
|
4298
|
+
var PR_STATUS_FRAGMENT = `fragment WatchPr on PullRequest {
|
|
4299
|
+
state
|
|
4300
|
+
headRefOid
|
|
4301
|
+
mergeable
|
|
4302
|
+
mergeStateStatus
|
|
4303
|
+
commits(last: 1) { nodes { commit { statusCheckRollup { state } } } }
|
|
4304
|
+
reviewThreads(first: 100) { nodes { isResolved } }
|
|
4305
|
+
}`;
|
|
4306
|
+
function buildPrStatusRequest(prs) {
|
|
4307
|
+
const variableDeclarations = [];
|
|
4308
|
+
const selections = [];
|
|
4309
|
+
const fieldFlags = [];
|
|
4310
|
+
prs.forEach((pr, index) => {
|
|
4311
|
+
const [owner, name] = pr.repo.split("/");
|
|
4312
|
+
variableDeclarations.push(`$o${index}: String!, $r${index}: String!, $n${index}: Int!`);
|
|
4313
|
+
selections.push(` p${index}: repository(owner: $o${index}, name: $r${index}) { pullRequest(number: $n${index}) { ...WatchPr } }`);
|
|
4314
|
+
fieldFlags.push("-f", `o${index}=${owner}`, "-f", `r${index}=${name}`, "-F", `n${index}=${pr.number}`);
|
|
4315
|
+
});
|
|
4316
|
+
const query = `query(${variableDeclarations.join(", ")}) {
|
|
4317
|
+
${selections.join("\n")}
|
|
4318
|
+
}
|
|
4319
|
+
${PR_STATUS_FRAGMENT}`;
|
|
4320
|
+
return ["api", "graphql", "-f", `query=${query}`, ...fieldFlags];
|
|
4321
|
+
}
|
|
4322
|
+
function parsePullRequestNode(url, node) {
|
|
4323
|
+
const state = enumValueOf(ProviderPrState, node?.state);
|
|
4324
|
+
if (!node || state === void 0 || state === "UNREACHABLE" /* Unreachable */) return void 0;
|
|
4325
|
+
return {
|
|
4326
|
+
url,
|
|
4327
|
+
state,
|
|
4328
|
+
headSha: optionalString(node.headRefOid),
|
|
4329
|
+
mergeable: enumValueOf(PrMergeable, node.mergeable),
|
|
4330
|
+
mergeStateStatus: enumValueOf(PrMergeStateStatus, node.mergeStateStatus),
|
|
4331
|
+
ciRollup: enumValueOf(CiRollupState, node.commits?.nodes?.[0]?.commit?.statusCheckRollup?.state),
|
|
4332
|
+
unresolvedThreadCount: (node.reviewThreads?.nodes ?? []).filter((thread) => thread.isResolved === false).length
|
|
4333
|
+
};
|
|
4334
|
+
}
|
|
4335
|
+
function fetchPrLiveStatuses(prs, runCommand) {
|
|
4336
|
+
const statusesByUrl = /* @__PURE__ */ new Map();
|
|
4337
|
+
for (let start = 0; start < prs.length; start += PR_STATUS_BATCH_SIZE) {
|
|
4338
|
+
const batch = prs.slice(start, start + PR_STATUS_BATCH_SIZE);
|
|
4339
|
+
const outcome = runCommand("gh", buildPrStatusRequest(batch));
|
|
4340
|
+
if (!outcome?.stdout) continue;
|
|
4341
|
+
let response;
|
|
4342
|
+
try {
|
|
4343
|
+
response = JSON.parse(outcome.stdout);
|
|
4344
|
+
} catch {
|
|
4345
|
+
continue;
|
|
4346
|
+
}
|
|
4347
|
+
batch.forEach((pr, index) => {
|
|
4348
|
+
const liveStatus = parsePullRequestNode(pr.url, response.data?.[`p${index}`]?.pullRequest);
|
|
4349
|
+
if (liveStatus) statusesByUrl.set(pr.url, liveStatus);
|
|
4350
|
+
});
|
|
4351
|
+
}
|
|
4352
|
+
return statusesByUrl;
|
|
4353
|
+
}
|
|
4354
|
+
|
|
4355
|
+
// src/watch/process-table.ts
|
|
4356
|
+
function buildWindowsProcessTableScript() {
|
|
4357
|
+
const keptExecutables = COMMAND_LINE_EXECUTABLE_PATTERN.source.replace(/'/g, "''");
|
|
4358
|
+
return [
|
|
4359
|
+
"$ErrorActionPreference = 'Stop'",
|
|
4360
|
+
"[Console]::OutputEncoding = [Text.Encoding]::UTF8",
|
|
4361
|
+
`$kept = '${keptExecutables}'`,
|
|
4362
|
+
"$rows = @(Get-CimInstance Win32_Process | ForEach-Object {",
|
|
4363
|
+
" $base = ($_.Name -replace '\\.exe$', '').ToLowerInvariant()",
|
|
4364
|
+
" $isKept = $base -match $kept",
|
|
4365
|
+
" [pscustomobject]@{",
|
|
4366
|
+
" p = [int]$_.ProcessId",
|
|
4367
|
+
" pp = [int]$_.ParentProcessId",
|
|
4368
|
+
" n = $base",
|
|
4369
|
+
" c = $(if ($isKept) { [string]$_.CommandLine } else { '' })",
|
|
4370
|
+
" s = $(if ($isKept -and $_.CreationDate) { ([DateTimeOffset]$_.CreationDate).ToUnixTimeMilliseconds() } else { $null })",
|
|
4371
|
+
" }",
|
|
4372
|
+
"})",
|
|
4373
|
+
"ConvertTo-Json -InputObject $rows -Compress"
|
|
4374
|
+
].join("\n");
|
|
4375
|
+
}
|
|
4376
|
+
function readWindowsProcessTable(runCommand, nowMs) {
|
|
4377
|
+
const encodedScript = Buffer.from(buildWindowsProcessTableScript(), "utf16le").toString("base64");
|
|
4378
|
+
const outcome = runCommand("powershell.exe", ["-NoProfile", "-NonInteractive", "-EncodedCommand", encodedScript]);
|
|
4379
|
+
if (!outcome || outcome.exitCode !== 0) return null;
|
|
4380
|
+
let rows;
|
|
4381
|
+
try {
|
|
4382
|
+
const parsed = JSON.parse(outcome.stdout);
|
|
4383
|
+
rows = Array.isArray(parsed) ? parsed : [parsed];
|
|
4384
|
+
} catch {
|
|
4385
|
+
return null;
|
|
4386
|
+
}
|
|
4387
|
+
const entries = [];
|
|
4388
|
+
for (const row of rows) {
|
|
4389
|
+
if (typeof row.p !== "number" || typeof row.pp !== "number") continue;
|
|
4390
|
+
entries.push({
|
|
4391
|
+
pid: row.p,
|
|
4392
|
+
parentPid: row.pp,
|
|
4393
|
+
executableName: typeof row.n === "string" ? row.n : "",
|
|
4394
|
+
commandLine: typeof row.c === "string" ? row.c : "",
|
|
4395
|
+
ageMs: typeof row.s === "number" ? Math.max(0, nowMs - row.s) : void 0
|
|
4396
|
+
});
|
|
4397
|
+
}
|
|
4398
|
+
return entries;
|
|
4399
|
+
}
|
|
4400
|
+
function parsePsElapsedSeconds(elapsed) {
|
|
4401
|
+
const parts = elapsed.match(/^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)$/);
|
|
4402
|
+
if (!parts) return void 0;
|
|
4403
|
+
const [, days, hours, minutes, seconds] = parts;
|
|
4404
|
+
return Number(days ?? 0) * 86400 + Number(hours ?? 0) * 3600 + Number(minutes) * 60 + Number(seconds);
|
|
4405
|
+
}
|
|
4406
|
+
function executableNameOf(commandLine) {
|
|
4407
|
+
const firstToken = commandLine.trim().split(/\s+/)[0] ?? "";
|
|
4408
|
+
const baseName = firstToken.split(/[\\/]/).pop() ?? "";
|
|
4409
|
+
return baseName.replace(/\.exe$/i, "").toLowerCase();
|
|
4410
|
+
}
|
|
4411
|
+
function readPosixProcessTable(runCommand) {
|
|
4412
|
+
const outcome = runCommand("ps", ["-axo", "pid=,ppid=,etime=,command="]);
|
|
4413
|
+
if (!outcome || outcome.exitCode !== 0) return null;
|
|
4414
|
+
const entries = [];
|
|
4415
|
+
for (const line of outcome.stdout.split("\n")) {
|
|
4416
|
+
const columns = line.match(/^\s*(\d+)\s+(\d+)\s+(\S+)\s+(.*)$/);
|
|
4417
|
+
if (!columns) continue;
|
|
4418
|
+
const commandLine = columns[4].trim();
|
|
4419
|
+
const executableName = executableNameOf(commandLine);
|
|
4420
|
+
const elapsedSeconds = parsePsElapsedSeconds(columns[3]);
|
|
4421
|
+
entries.push({
|
|
4422
|
+
pid: Number(columns[1]),
|
|
4423
|
+
parentPid: Number(columns[2]),
|
|
4424
|
+
executableName,
|
|
4425
|
+
commandLine: COMMAND_LINE_EXECUTABLE_PATTERN.test(executableName) ? commandLine : "",
|
|
4426
|
+
ageMs: elapsedSeconds === void 0 ? void 0 : elapsedSeconds * 1e3
|
|
4427
|
+
});
|
|
4428
|
+
}
|
|
4429
|
+
return entries;
|
|
4430
|
+
}
|
|
4431
|
+
function readProcessTable(platform4, runCommand, nowMs) {
|
|
4432
|
+
return platform4 === "win32" ? readWindowsProcessTable(runCommand, nowMs) : readPosixProcessTable(runCommand);
|
|
4433
|
+
}
|
|
4434
|
+
function findClaudeSessionCwd(projectsDir, sessionId) {
|
|
4435
|
+
let projectDirNames;
|
|
4436
|
+
try {
|
|
4437
|
+
projectDirNames = readdirSync(projectsDir);
|
|
4438
|
+
} catch {
|
|
4439
|
+
return void 0;
|
|
4440
|
+
}
|
|
4441
|
+
const transcriptFileName = `${sessionId}.jsonl`;
|
|
4442
|
+
for (const projectDirName of projectDirNames) {
|
|
4443
|
+
const transcriptPath = join(projectsDir, projectDirName, transcriptFileName);
|
|
4444
|
+
if (!existsSync(transcriptPath)) continue;
|
|
4445
|
+
const head = readFileHead(transcriptPath);
|
|
4446
|
+
return head === void 0 ? void 0 : cwdFromSessionHead(head);
|
|
4447
|
+
}
|
|
4448
|
+
return void 0;
|
|
4449
|
+
}
|
|
4450
|
+
|
|
4451
|
+
// src/watch/recovery.ts
|
|
4452
|
+
function isRecoverable(assessment) {
|
|
4453
|
+
return assessment.isRegistered && assessment.watcher === "dead" /* Dead */ && assessment.live?.state === "OPEN" /* Open */ && assessment.ownerSessionId !== void 0 && assessment.isOwnerSessionActive === false;
|
|
4454
|
+
}
|
|
4455
|
+
function planWatcherRecoveries(assessments, attemptsByOwner, nowMs, isPollingDisabled) {
|
|
4456
|
+
if (isPollingDisabled) return [];
|
|
4457
|
+
const slugsByOwner = /* @__PURE__ */ new Map();
|
|
4458
|
+
for (const assessment of assessments) {
|
|
4459
|
+
if (!isRecoverable(assessment)) continue;
|
|
4460
|
+
const ownerSessionId = assessment.ownerSessionId;
|
|
4461
|
+
const slugs = slugsByOwner.get(ownerSessionId) ?? /* @__PURE__ */ new Set();
|
|
4462
|
+
slugs.add(assessment.slug);
|
|
4463
|
+
slugsByOwner.set(ownerSessionId, slugs);
|
|
4464
|
+
}
|
|
4465
|
+
let resumesPlanned = 0;
|
|
4466
|
+
const recoveries = [];
|
|
4467
|
+
for (const ownerSessionId of [...slugsByOwner.keys()].sort()) {
|
|
4468
|
+
const recentAttemptsMs = (attemptsByOwner[ownerSessionId] ?? []).map((attemptedAt) => Date.parse(attemptedAt)).filter((attemptedAtMs) => !Number.isNaN(attemptedAtMs) && nowMs - attemptedAtMs < RECOVERY_ATTEMPT_WINDOW_MS);
|
|
4469
|
+
const lastAttemptMs = Math.max(-Infinity, ...recentAttemptsMs);
|
|
4470
|
+
let outcome = "resume-due" /* ResumeDue */;
|
|
4471
|
+
if (recentAttemptsMs.length >= RECOVERY_MAX_ATTEMPTS) outcome = "attempts-exhausted" /* AttemptsExhausted */;
|
|
4472
|
+
else if (nowMs - lastAttemptMs < RECOVERY_COOLDOWN_MS) outcome = "cooling-down" /* CoolingDown */;
|
|
4473
|
+
else if (resumesPlanned >= MAX_RESUMES_PER_TICK) outcome = "deferred-by-tick-cap" /* DeferredByTickCap */;
|
|
4474
|
+
if (outcome === "resume-due" /* ResumeDue */) resumesPlanned++;
|
|
4475
|
+
recoveries.push({
|
|
4476
|
+
ownerSessionId,
|
|
4477
|
+
slotSlugs: [...slugsByOwner.get(ownerSessionId) ?? []].sort(),
|
|
4478
|
+
outcome
|
|
4479
|
+
});
|
|
4480
|
+
}
|
|
4481
|
+
return recoveries;
|
|
4482
|
+
}
|
|
4483
|
+
function executeWatcherRecoveries(planned, attemptsByOwner, runCommand, claudeProjectsDir, nowMs) {
|
|
4484
|
+
const nowIso = new Date(nowMs).toISOString();
|
|
4485
|
+
const nextAttemptsByOwner = {};
|
|
4486
|
+
for (const [ownerSessionId, attempts] of Object.entries(attemptsByOwner)) {
|
|
4487
|
+
const recent = attempts.filter((attemptedAt) => nowMs - Date.parse(attemptedAt) < RECOVERY_ATTEMPT_WINDOW_MS);
|
|
4488
|
+
if (recent.length > 0) nextAttemptsByOwner[ownerSessionId] = recent;
|
|
4489
|
+
}
|
|
4490
|
+
const events = [];
|
|
4491
|
+
const recoveries = planned.map((recovery) => {
|
|
4492
|
+
if (recovery.outcome !== "resume-due" /* ResumeDue */) return recovery;
|
|
4493
|
+
const cwd = findClaudeSessionCwd(claudeProjectsDir, recovery.ownerSessionId);
|
|
4494
|
+
if (!cwd || !existsSync(cwd)) return { ...recovery, outcome: "transcript-missing" /* TranscriptMissing */ };
|
|
4495
|
+
const outcome = runCommand("claude", ["--resume", recovery.ownerSessionId, "--bg", RECOVERY_RESUME_PROMPT], { cwd });
|
|
4496
|
+
const isResumed = outcome?.exitCode === 0;
|
|
4497
|
+
nextAttemptsByOwner[recovery.ownerSessionId] = [...nextAttemptsByOwner[recovery.ownerSessionId] ?? [], nowIso];
|
|
4498
|
+
events.push({
|
|
4499
|
+
at: nowIso,
|
|
4500
|
+
kind: isResumed ? "resumed" /* Resumed */ : "resume-failed" /* ResumeFailed */,
|
|
4501
|
+
subject: `session ${shortSessionId(recovery.ownerSessionId)}`,
|
|
4502
|
+
message: `${isResumed ? "resumed" : "could not resume"} to re-arm ${recovery.slotSlugs.join(", ")}`
|
|
4503
|
+
});
|
|
4504
|
+
return {
|
|
4505
|
+
...recovery,
|
|
4506
|
+
cwd,
|
|
4507
|
+
outcome: isResumed ? "resumed" /* Resumed */ : "resume-failed" /* ResumeFailed */
|
|
4508
|
+
};
|
|
4509
|
+
});
|
|
4510
|
+
return { recoveries, attemptsByOwner: nextAttemptsByOwner, events };
|
|
4511
|
+
}
|
|
4512
|
+
|
|
4513
|
+
// src/watch/reload-plugins.ts
|
|
4514
|
+
function decide(session, action, reason) {
|
|
4515
|
+
return { sessionId: session.sessionId, shortId: session.shortId, name: session.name, action, reason };
|
|
4516
|
+
}
|
|
4517
|
+
function planReloadFanOut(sessions, pending, maxRespawns = MAX_RESPAWNS_PER_TICK) {
|
|
4518
|
+
let respawnsPlanned = 0;
|
|
4519
|
+
const decisions = [];
|
|
4520
|
+
for (const session of sessions) {
|
|
4521
|
+
if (session.agent !== "claude" /* Claude */) continue;
|
|
4522
|
+
if (session.startedAtMs !== void 0 && session.startedAtMs >= pending.changedAtMs) {
|
|
4523
|
+
decisions.push(decide(session, "skip" /* Skip */, "started after the plugin change"));
|
|
4524
|
+
} else if (pending.respawnedSessionIds.includes(session.sessionId)) {
|
|
4525
|
+
decisions.push(decide(session, "skip" /* Skip */, "already respawned"));
|
|
4526
|
+
} else if (session.kind === "interactive" /* Interactive */) {
|
|
4527
|
+
decisions.push(pending.notifiedSessionIds.includes(session.sessionId) ? decide(session, "skip" /* Skip */, "already asked to run /reload-plugins") : decide(session, "notify-manual" /* NotifyManual */, "terminal session \u2014 run /reload-plugins in it"));
|
|
4528
|
+
} else if (session.kind !== "background" /* Background */ || !session.shortId) {
|
|
4529
|
+
decisions.push(decide(session, "skip" /* Skip */, "not a background session the watch can respawn"));
|
|
4530
|
+
} else if (session.jobState === "done" /* Done */) {
|
|
4531
|
+
decisions.push(decide(session, "skip" /* Skip */, "job finished"));
|
|
4532
|
+
} else if (session.turnStatus !== "idle" /* Idle */) {
|
|
4533
|
+
decisions.push(decide(session, "defer" /* Defer */, `turn in flight (${session.turnStatus ?? "unknown"})`));
|
|
4534
|
+
} else if (respawnsPlanned >= maxRespawns) {
|
|
4535
|
+
decisions.push(decide(session, "defer" /* Defer */, "respawn cap reached this tick"));
|
|
4536
|
+
} else {
|
|
4537
|
+
respawnsPlanned++;
|
|
4538
|
+
decisions.push(decide(session, "respawn" /* Respawn */, "idle background session"));
|
|
4539
|
+
}
|
|
4540
|
+
}
|
|
4541
|
+
return decisions;
|
|
4542
|
+
}
|
|
4543
|
+
function executeReloadFanOut(decisions, runCommand) {
|
|
4544
|
+
const respawnedSessionIds = [];
|
|
4545
|
+
const failedSessionIds = [];
|
|
4546
|
+
for (const decision of decisions) {
|
|
4547
|
+
if (decision.action !== "respawn" /* Respawn */ || !decision.shortId) continue;
|
|
4548
|
+
const outcome = runCommand("claude", ["respawn", decision.shortId]);
|
|
4549
|
+
(outcome?.exitCode === 0 ? respawnedSessionIds : failedSessionIds).push(decision.sessionId);
|
|
4550
|
+
}
|
|
4551
|
+
return { decisions, respawnedSessionIds, failedSessionIds };
|
|
4552
|
+
}
|
|
4553
|
+
function advancePendingReload(pending, report) {
|
|
4554
|
+
if (!report.decisions.some((decision) => decision.action === "defer" /* Defer */)) return void 0;
|
|
4555
|
+
const notifiedSessionIds = report.decisions.filter((decision) => decision.action === "notify-manual" /* NotifyManual */).map((decision) => decision.sessionId);
|
|
4556
|
+
return {
|
|
4557
|
+
...pending,
|
|
4558
|
+
respawnedSessionIds: [...pending.respawnedSessionIds, ...report.respawnedSessionIds, ...report.failedSessionIds],
|
|
4559
|
+
notifiedSessionIds: [...pending.notifiedSessionIds, ...notifiedSessionIds]
|
|
4560
|
+
};
|
|
4561
|
+
}
|
|
4562
|
+
|
|
4563
|
+
// src/watch/terminal-pr-cache.ts
|
|
4564
|
+
function isRecheckDue(record, nowMs) {
|
|
4565
|
+
if (!record) return true;
|
|
4566
|
+
const checkedAtMs = Date.parse(record.checkedAt);
|
|
4567
|
+
return Number.isNaN(checkedAtMs) || nowMs - checkedAtMs >= TERMINAL_PR_RECHECK_MS;
|
|
4568
|
+
}
|
|
4569
|
+
function partitionByTerminalCache(prs, terminalPrsByUrl, nowMs) {
|
|
4570
|
+
const prsToQuery = [];
|
|
4571
|
+
const cachedStatuses = [];
|
|
4572
|
+
for (const pr of prs) {
|
|
4573
|
+
const record = terminalPrsByUrl[pr.url];
|
|
4574
|
+
if (record && !isRecheckDue(record, nowMs)) {
|
|
4575
|
+
cachedStatuses.push({ url: pr.url, state: record.state, unresolvedThreadCount: 0 });
|
|
4576
|
+
} else {
|
|
4577
|
+
prsToQuery.push(pr);
|
|
4578
|
+
}
|
|
4579
|
+
}
|
|
4580
|
+
return { prsToQuery, cachedStatuses };
|
|
4581
|
+
}
|
|
4582
|
+
function updateTerminalCache(terminalPrsByUrl, fetchedStatuses, trackedUrls, nowIso) {
|
|
4583
|
+
const nextCache = {};
|
|
4584
|
+
for (const [url, record] of Object.entries(terminalPrsByUrl)) {
|
|
4585
|
+
if (trackedUrls.has(url)) nextCache[url] = record;
|
|
4586
|
+
}
|
|
4587
|
+
for (const fetched of fetchedStatuses) {
|
|
4588
|
+
if (fetched.state === "MERGED" /* Merged */ || fetched.state === "CLOSED" /* Closed */) {
|
|
4589
|
+
nextCache[fetched.url] = { state: fetched.state, checkedAt: nowIso };
|
|
4590
|
+
} else {
|
|
4591
|
+
delete nextCache[fetched.url];
|
|
4592
|
+
}
|
|
4593
|
+
}
|
|
4594
|
+
return nextCache;
|
|
4595
|
+
}
|
|
4596
|
+
function isAgentExecutable(executableName) {
|
|
4597
|
+
return CLAUDE_EXECUTABLE_PATTERN.test(executableName) || CODEX_EXECUTABLE_PATTERN.test(executableName);
|
|
4598
|
+
}
|
|
4599
|
+
function classifyKind(entry) {
|
|
4600
|
+
if (CLAUDE_EXECUTABLE_PATTERN.test(entry.executableName)) return "claude-cli" /* ClaudeCli */;
|
|
4601
|
+
if (CODEX_EXECUTABLE_PATTERN.test(entry.executableName)) return "codex-cli" /* CodexCli */;
|
|
4602
|
+
if (entry.executableName === "node" && MUGGLE_MCP_SERVER_PATTERN.test(entry.commandLine)) {
|
|
4603
|
+
return "muggle-mcp-server" /* MuggleMcpServer */;
|
|
4604
|
+
}
|
|
4605
|
+
if (entry.executableName === "bash" && PR_WATCH_LOOP_PATTERN.test(entry.commandLine)) {
|
|
4606
|
+
return "pr-watch-loop" /* PrWatchLoop */;
|
|
4607
|
+
}
|
|
4608
|
+
return void 0;
|
|
4609
|
+
}
|
|
4610
|
+
function watchSlotSlugOf(commandLine) {
|
|
4611
|
+
const parts = commandLine.match(PR_WATCH_LOOP_PATTERN);
|
|
4612
|
+
const slotPath = parts?.[1] ?? parts?.[2];
|
|
4613
|
+
if (!slotPath) return void 0;
|
|
4614
|
+
return basename(slotPath.replace(/\\/g, "/").replace(/\/+$/, ""));
|
|
4615
|
+
}
|
|
4616
|
+
function isOrphanedFromAgent(entry, entriesByPid, platform4) {
|
|
4617
|
+
if (platform4 !== "win32") return entry.parentPid === 1;
|
|
4618
|
+
let parentPid = entry.parentPid;
|
|
4619
|
+
for (let hop = 0; hop < MAX_ANCESTOR_HOPS; hop++) {
|
|
4620
|
+
if (parentPid === 0) return false;
|
|
4621
|
+
const parent = entriesByPid.get(parentPid);
|
|
4622
|
+
if (!parent) return true;
|
|
4623
|
+
if (isAgentExecutable(parent.executableName)) return false;
|
|
4624
|
+
parentPid = parent.parentPid;
|
|
4625
|
+
}
|
|
4626
|
+
return false;
|
|
4627
|
+
}
|
|
4628
|
+
function classifyTrackedProcesses(table, platform4) {
|
|
4629
|
+
const entriesByPid = new Map(table.map((entry) => [entry.pid, entry]));
|
|
4630
|
+
const tracked = [];
|
|
4631
|
+
for (const entry of table) {
|
|
4632
|
+
const kind = classifyKind(entry);
|
|
4633
|
+
if (kind === void 0) continue;
|
|
4634
|
+
const isWatchLoop = kind === "pr-watch-loop" /* PrWatchLoop */;
|
|
4635
|
+
tracked.push({
|
|
4636
|
+
pid: entry.pid,
|
|
4637
|
+
parentPid: entry.parentPid,
|
|
4638
|
+
kind,
|
|
4639
|
+
ageMs: entry.ageMs,
|
|
4640
|
+
isOrphaned: isWatchLoop ? void 0 : isOrphanedFromAgent(entry, entriesByPid, platform4),
|
|
4641
|
+
watchSlotSlug: isWatchLoop ? watchSlotSlugOf(entry.commandLine) : void 0
|
|
4642
|
+
});
|
|
4643
|
+
}
|
|
4644
|
+
return tracked;
|
|
4645
|
+
}
|
|
4646
|
+
function readJsonFile(filePath) {
|
|
4647
|
+
try {
|
|
4648
|
+
return JSON.parse(readFileSync(filePath, "utf-8"));
|
|
4649
|
+
} catch {
|
|
4650
|
+
return void 0;
|
|
4651
|
+
}
|
|
4652
|
+
}
|
|
4653
|
+
function openGithubPrsOf(prsJson) {
|
|
4654
|
+
const entries = Array.isArray(prsJson) ? prsJson : prsJson ? [prsJson] : [];
|
|
4655
|
+
const openPrs = [];
|
|
4656
|
+
for (const entry of entries) {
|
|
4657
|
+
const recordedState = typeof entry.state === "string" ? entry.state.toLowerCase() : "";
|
|
4658
|
+
if (TERMINAL_SLOT_PR_STATES.includes(recordedState)) continue;
|
|
4659
|
+
if (entry.provider !== void 0 && entry.provider !== "github") continue;
|
|
4660
|
+
const url = optionalString(entry.url);
|
|
4661
|
+
const coordinates = url ? parsePrUrl(url) : null;
|
|
4662
|
+
if (!url || !coordinates) continue;
|
|
4663
|
+
openPrs.push({
|
|
4664
|
+
repo: coordinates.repo,
|
|
4665
|
+
number: coordinates.prNumber,
|
|
4666
|
+
url,
|
|
4667
|
+
headSha: optionalString(entry.head_sha)
|
|
4668
|
+
});
|
|
4669
|
+
}
|
|
4670
|
+
return openPrs;
|
|
4671
|
+
}
|
|
4672
|
+
function heartbeatMtimeMsOf(slotDir) {
|
|
4673
|
+
try {
|
|
4674
|
+
return statSync(join(slotDir, "watch-heartbeat")).mtimeMs;
|
|
4675
|
+
} catch {
|
|
4676
|
+
return void 0;
|
|
4677
|
+
}
|
|
4678
|
+
}
|
|
4679
|
+
function readOpenWatchSlots(slotsDir) {
|
|
4680
|
+
let slugs;
|
|
4681
|
+
try {
|
|
4682
|
+
slugs = readdirSync(slotsDir);
|
|
4683
|
+
} catch {
|
|
4684
|
+
return [];
|
|
4685
|
+
}
|
|
4686
|
+
const slots = [];
|
|
4687
|
+
for (const slug of slugs) {
|
|
4688
|
+
if (slug.endsWith(STOPPED_SLOT_SUFFIX)) continue;
|
|
4689
|
+
const slotDir = join(slotsDir, slug);
|
|
4690
|
+
if (existsSync(join(slotDir, "result.md"))) continue;
|
|
4691
|
+
const openPrs = openGithubPrsOf(readJsonFile(join(slotDir, "prs.json")));
|
|
4692
|
+
if (openPrs.length === 0) continue;
|
|
4693
|
+
const owner = readJsonFile(join(slotDir, "owner.json"));
|
|
4694
|
+
slots.push({
|
|
4695
|
+
slug,
|
|
4696
|
+
slotDir,
|
|
4697
|
+
ownerSessionId: optionalString(owner?.session_id),
|
|
4698
|
+
heartbeatMtimeMs: heartbeatMtimeMsOf(slotDir),
|
|
4699
|
+
isRegistered: existsSync(join(slotDir, WATCH_REGISTRATION_FILE)),
|
|
4700
|
+
openPrs
|
|
4701
|
+
});
|
|
4702
|
+
}
|
|
4703
|
+
return slots;
|
|
4704
|
+
}
|
|
4705
|
+
function isPrPollingDisabled(slotsDir) {
|
|
4706
|
+
return existsSync(join(dirname(slotsDir), PR_POLLING_DISABLED_FILE));
|
|
4707
|
+
}
|
|
4708
|
+
function writeSlotRegistration(slotDir, registeredBy, now) {
|
|
4709
|
+
if (!existsSync(join(slotDir, "prs.json"))) {
|
|
4710
|
+
throw new Error(`${slotDir} has no prs.json \u2014 arm the watch before registering it`);
|
|
4711
|
+
}
|
|
4712
|
+
const registration = {
|
|
4713
|
+
registered_at: now.toISOString(),
|
|
4714
|
+
registered_by: registeredBy
|
|
4715
|
+
};
|
|
4716
|
+
writeFileSync(join(slotDir, WATCH_REGISTRATION_FILE), `${JSON.stringify(registration, null, 2)}
|
|
4717
|
+
`);
|
|
4718
|
+
}
|
|
4719
|
+
function removeSlotRegistration(slotDir) {
|
|
4720
|
+
const registrationPath = join(slotDir, WATCH_REGISTRATION_FILE);
|
|
4721
|
+
if (!existsSync(registrationPath)) return false;
|
|
4722
|
+
rmSync(registrationPath);
|
|
4723
|
+
return true;
|
|
4724
|
+
}
|
|
4725
|
+
|
|
4726
|
+
// src/watch/watch-service.ts
|
|
4727
|
+
function createDefaultWatchTickDeps(options) {
|
|
4728
|
+
return {
|
|
4729
|
+
nowMs: Date.now(),
|
|
4730
|
+
platform: process.platform,
|
|
4731
|
+
paths: resolveWatchPaths(),
|
|
4732
|
+
runCommand: defaultCommandRunner,
|
|
4733
|
+
notify: createDesktopNotifier(process.platform, defaultCommandRunner),
|
|
4734
|
+
isAutoReloadEnabled: options.isAutoReloadEnabled,
|
|
4735
|
+
isRecoveryEnabled: options.isRecoveryEnabled
|
|
4736
|
+
};
|
|
4737
|
+
}
|
|
4738
|
+
function notifyIfAny(deps, lines) {
|
|
4739
|
+
if (lines.length > 0) deps.notify(WATCH_NOTIFICATION_TITLE, lines);
|
|
4740
|
+
}
|
|
4741
|
+
function lockedOrThrow(watchDir, run) {
|
|
4742
|
+
const outcome = withWatchLock(watchDir, run);
|
|
4743
|
+
if (outcome === void 0) throw new Error("another muggle watch run holds the lock \u2014 try again shortly");
|
|
4744
|
+
return outcome;
|
|
4745
|
+
}
|
|
4746
|
+
function reloadEvents(report, at) {
|
|
4747
|
+
const sessionNameById = new Map(report.decisions.map((decision) => [decision.sessionId, decision.name]));
|
|
4748
|
+
const describe = (sessionId) => `session ${sessionNameById.get(sessionId) ?? shortSessionId(sessionId)}`;
|
|
4749
|
+
return [
|
|
4750
|
+
...report.respawnedSessionIds.map((sessionId) => ({ at, kind: "respawned" /* Respawned */, subject: describe(sessionId) })),
|
|
4751
|
+
...report.failedSessionIds.map((sessionId) => ({ at, kind: "respawn-failed" /* RespawnFailed */, subject: describe(sessionId) }))
|
|
4752
|
+
];
|
|
4753
|
+
}
|
|
4754
|
+
function runReloadPass(pending, claudeSessions, deps, at) {
|
|
4755
|
+
const report = executeReloadFanOut(planReloadFanOut(claudeSessions, pending), deps.runCommand);
|
|
4756
|
+
return { report, pendingReload: advancePendingReload(pending, report), events: reloadEvents(report, at) };
|
|
4757
|
+
}
|
|
4758
|
+
function stepPluginReload(state, claudeSessions, deps, at) {
|
|
4759
|
+
const current = readPluginFingerprint(deps.paths.claudeInstalledPluginsFile);
|
|
4760
|
+
const events = [];
|
|
4761
|
+
let pending = state.pendingReload;
|
|
4762
|
+
const hasChanged = current !== null && state.pluginFingerprint !== void 0 && current.fingerprint !== state.pluginFingerprint;
|
|
4763
|
+
if (hasChanged && deps.isAutoReloadEnabled) {
|
|
4764
|
+
pending = {
|
|
4765
|
+
fingerprint: current.fingerprint,
|
|
4766
|
+
changedAtMs: current.changedAtMs ?? deps.nowMs,
|
|
4767
|
+
respawnedSessionIds: [],
|
|
4768
|
+
notifiedSessionIds: []
|
|
4769
|
+
};
|
|
4770
|
+
events.push({ at, kind: "reload-requested" /* ReloadRequested */, message: "installed plugins changed" });
|
|
4771
|
+
}
|
|
4772
|
+
const pluginFingerprint = current?.fingerprint ?? state.pluginFingerprint;
|
|
4773
|
+
if (!pending || claudeSessions === null) return { pluginFingerprint, pendingReload: pending, events };
|
|
4774
|
+
const pass = runReloadPass(pending, claudeSessions, deps, at);
|
|
4775
|
+
return {
|
|
4776
|
+
pluginFingerprint,
|
|
4777
|
+
pendingReload: pass.pendingReload,
|
|
4778
|
+
report: pass.report,
|
|
4779
|
+
events: [...events, ...pass.events]
|
|
4780
|
+
};
|
|
4781
|
+
}
|
|
4782
|
+
function runTickUnlocked(deps) {
|
|
4783
|
+
const at = new Date(deps.nowMs).toISOString();
|
|
4784
|
+
const table = readProcessTable(deps.platform, deps.runCommand, deps.nowMs);
|
|
4785
|
+
const processes = table ? classifyTrackedProcesses(table, deps.platform) : null;
|
|
4786
|
+
const claudeSessions = readClaudeSessions(deps.runCommand, deps.paths.claudeSessionRegistryDir);
|
|
4787
|
+
const sessions = [...claudeSessions ?? [], ...readCodexSessions(deps.paths.codexSessionsDir, deps.nowMs)];
|
|
4788
|
+
const activeSessionIds = claudeSessions === null ? null : new Set(sessions.map((session) => session.sessionId));
|
|
4789
|
+
const slots = readOpenWatchSlots(deps.paths.slotsDir);
|
|
4790
|
+
const isPollingDisabled = isPrPollingDisabled(deps.paths.slotsDir);
|
|
4791
|
+
const state = readWatchLedgerState(deps.paths.watchDir);
|
|
4792
|
+
const slotPrs = slots.flatMap((slot) => slot.openPrs);
|
|
4793
|
+
const { prsToQuery, cachedStatuses } = partitionByTerminalCache(slotPrs, state.terminalPrsByUrl, deps.nowMs);
|
|
4794
|
+
const liveStatusesByUrl = fetchPrLiveStatuses(prsToQuery, deps.runCommand);
|
|
4795
|
+
const terminalPrsByUrl = updateTerminalCache(
|
|
4796
|
+
state.terminalPrsByUrl,
|
|
4797
|
+
[...liveStatusesByUrl.values()],
|
|
4798
|
+
new Set(slotPrs.map((pr) => pr.url)),
|
|
4799
|
+
at
|
|
4800
|
+
);
|
|
4801
|
+
for (const cachedStatus of cachedStatuses) liveStatusesByUrl.set(cachedStatus.url, cachedStatus);
|
|
4802
|
+
const assessments = assessWatchSlots(slots, processes, activeSessionIds, liveStatusesByUrl, deps.nowMs);
|
|
4803
|
+
const findings = deriveWatchFindings(assessments, processes ?? [], isPollingDisabled);
|
|
4804
|
+
const transitions = reconcileActiveFindings(state.activeFindings, findings, at);
|
|
4805
|
+
const events = [
|
|
4806
|
+
...transitions.raised.map((raised) => ({ at, kind: "raised" /* Raised */, key: raised.key, code: raised.code, subject: raised.subject, message: raised.message })),
|
|
4807
|
+
...transitions.cleared.map(({ key, record }) => ({ at, kind: "cleared" /* Cleared */, key, code: record.code, subject: record.subject }))
|
|
4808
|
+
];
|
|
4809
|
+
let recoveries = [];
|
|
4810
|
+
let recoveryAttemptsByOwner = state.recoveryAttemptsByOwner;
|
|
4811
|
+
if (deps.isRecoveryEnabled) {
|
|
4812
|
+
const planned = planWatcherRecoveries(assessments, recoveryAttemptsByOwner, deps.nowMs, isPollingDisabled);
|
|
4813
|
+
const executed = executeWatcherRecoveries(planned, recoveryAttemptsByOwner, deps.runCommand, deps.paths.claudeProjectsDir, deps.nowMs);
|
|
4814
|
+
recoveries = executed.recoveries;
|
|
4815
|
+
recoveryAttemptsByOwner = executed.attemptsByOwner;
|
|
4816
|
+
events.push(...executed.events);
|
|
4817
|
+
}
|
|
4818
|
+
const reloadStep = stepPluginReload(state, claudeSessions, deps, at);
|
|
4819
|
+
events.push(...reloadStep.events);
|
|
4820
|
+
appendWatchEvents(deps.paths.watchDir, events);
|
|
4821
|
+
notifyIfAny(deps, composeTickNotification(transitions.raised, recoveries, reloadStep.report));
|
|
4822
|
+
writeWatchLedgerState(deps.paths.watchDir, {
|
|
4823
|
+
activeFindings: transitions.activeFindings,
|
|
4824
|
+
recoveryAttemptsByOwner,
|
|
4825
|
+
terminalPrsByUrl,
|
|
4826
|
+
pluginFingerprint: reloadStep.pluginFingerprint,
|
|
4827
|
+
pendingReload: reloadStep.pendingReload
|
|
4828
|
+
});
|
|
4829
|
+
const snapshot = {
|
|
4830
|
+
takenAt: at,
|
|
4831
|
+
sessions,
|
|
4832
|
+
processes: processes ?? [],
|
|
4833
|
+
slots: assessments,
|
|
4834
|
+
findings,
|
|
4835
|
+
recoveries,
|
|
4836
|
+
reload: reloadStep.report
|
|
4837
|
+
};
|
|
4838
|
+
writeWatchSnapshot(deps.paths.watchDir, snapshot);
|
|
4839
|
+
return snapshot;
|
|
4840
|
+
}
|
|
4841
|
+
function runWatchTick(deps) {
|
|
4842
|
+
return lockedOrThrow(deps.paths.watchDir, () => runTickUnlocked(deps));
|
|
4843
|
+
}
|
|
4844
|
+
function runReloadPluginsPass(deps, isDryRun) {
|
|
4845
|
+
return lockedOrThrow(deps.paths.watchDir, () => {
|
|
4846
|
+
const claudeSessions = readClaudeSessions(deps.runCommand, deps.paths.claudeSessionRegistryDir);
|
|
4847
|
+
if (claudeSessions === null) return null;
|
|
4848
|
+
const state = readWatchLedgerState(deps.paths.watchDir);
|
|
4849
|
+
const current = readPluginFingerprint(deps.paths.claudeInstalledPluginsFile);
|
|
4850
|
+
const pending = {
|
|
4851
|
+
fingerprint: current?.fingerprint ?? state.pluginFingerprint ?? "",
|
|
4852
|
+
changedAtMs: deps.nowMs,
|
|
4853
|
+
respawnedSessionIds: [],
|
|
4854
|
+
notifiedSessionIds: []
|
|
4855
|
+
};
|
|
4856
|
+
if (isDryRun) {
|
|
4857
|
+
return { decisions: planReloadFanOut(claudeSessions, pending), respawnedSessionIds: [], failedSessionIds: [] };
|
|
4858
|
+
}
|
|
4859
|
+
const at = new Date(deps.nowMs).toISOString();
|
|
4860
|
+
const pass = runReloadPass(pending, claudeSessions, deps, at);
|
|
4861
|
+
appendWatchEvents(deps.paths.watchDir, [
|
|
4862
|
+
{ at, kind: "reload-requested" /* ReloadRequested */, message: "requested with muggle watch reload-plugins" },
|
|
4863
|
+
...pass.events
|
|
4864
|
+
]);
|
|
4865
|
+
notifyIfAny(deps, composeTickNotification([], [], pass.report));
|
|
4866
|
+
writeWatchLedgerState(deps.paths.watchDir, {
|
|
4867
|
+
...state,
|
|
4868
|
+
pluginFingerprint: current?.fingerprint ?? state.pluginFingerprint,
|
|
4869
|
+
pendingReload: pass.pendingReload
|
|
4870
|
+
});
|
|
4871
|
+
return pass.report;
|
|
4872
|
+
});
|
|
4873
|
+
}
|
|
4874
|
+
function loadLastWatchSnapshot(paths = resolveWatchPaths()) {
|
|
4875
|
+
return readWatchSnapshot(paths.watchDir);
|
|
4876
|
+
}
|
|
4877
|
+
function registerWatchSlot(slotDir, now = /* @__PURE__ */ new Date()) {
|
|
4878
|
+
writeSlotRegistration(resolve(slotDir), WATCH_REGISTRATION_SOURCE_CLI, now);
|
|
4879
|
+
}
|
|
4880
|
+
function unregisterWatchSlot(slotDir) {
|
|
4881
|
+
return removeSlotRegistration(resolve(slotDir));
|
|
4882
|
+
}
|
|
4883
|
+
|
|
4884
|
+
// src/cli/watch.ts
|
|
4885
|
+
function failWith(message) {
|
|
4886
|
+
process.stderr.write(`muggle watch: ${message}
|
|
4887
|
+
`);
|
|
4888
|
+
process.exitCode = 1;
|
|
4889
|
+
}
|
|
4890
|
+
function watchTickCommand(flags) {
|
|
4891
|
+
try {
|
|
4892
|
+
const snapshot = runWatchTick(
|
|
4893
|
+
createDefaultWatchTickDeps({ isAutoReloadEnabled: flags.autoReload, isRecoveryEnabled: flags.recovery })
|
|
4894
|
+
);
|
|
4895
|
+
if (flags.json) {
|
|
4896
|
+
process.stdout.write(`${JSON.stringify(snapshot, null, 2)}
|
|
4897
|
+
`);
|
|
4898
|
+
return;
|
|
4899
|
+
}
|
|
4900
|
+
const alertCount = snapshot.findings.filter((current) => current.severity === "alert" /* Alert */).length;
|
|
4901
|
+
const resumedCount = snapshot.recoveries.filter((recovery) => recovery.outcome === "resumed" /* Resumed */).length;
|
|
4902
|
+
process.stdout.write(
|
|
4903
|
+
`muggle watch: ${snapshot.sessions.length} sessions, ${snapshot.slots.length} PR watches, ${snapshot.findings.length} findings (${alertCount} alerts), ${resumedCount} owner sessions resumed
|
|
4904
|
+
`
|
|
4905
|
+
);
|
|
4906
|
+
} catch (error) {
|
|
4907
|
+
failWith(error instanceof Error ? error.message : String(error));
|
|
4908
|
+
}
|
|
4909
|
+
}
|
|
4910
|
+
function watchStatusCommand(flags) {
|
|
4911
|
+
const snapshot = loadLastWatchSnapshot();
|
|
4912
|
+
if (!snapshot) {
|
|
4913
|
+
failWith("no snapshot yet \u2014 install the service (scripts/muggle-watch/install-muggle-watch.ps1) or run `muggle watch tick`");
|
|
4914
|
+
return;
|
|
4915
|
+
}
|
|
4916
|
+
process.stdout.write(flags.json ? `${JSON.stringify(snapshot, null, 2)}
|
|
4917
|
+
` : renderWatchStatus(snapshot, Date.now()));
|
|
4918
|
+
}
|
|
4919
|
+
function renderReloadReport(report, isDryRun) {
|
|
4920
|
+
const lines = report.decisions.map((decision) => {
|
|
4921
|
+
const label = decision.name ?? decision.shortId ?? decision.sessionId;
|
|
4922
|
+
const failed = report.failedSessionIds.includes(decision.sessionId) ? " (respawn failed)" : "";
|
|
4923
|
+
return ` ${decision.action.padEnd(13)} ${label} ${decision.reason}${failed}`;
|
|
4924
|
+
});
|
|
4925
|
+
const respawnVerb = isDryRun ? "would respawn" : "respawned";
|
|
4926
|
+
const respawnCount = isDryRun ? report.decisions.filter((decision) => decision.action === "respawn" /* Respawn */).length : report.respawnedSessionIds.length;
|
|
4927
|
+
return [`muggle watch reload-plugins: ${respawnVerb} ${respawnCount}`, ...lines, ""].join("\n");
|
|
4928
|
+
}
|
|
4929
|
+
function watchReloadPluginsCommand(flags) {
|
|
4930
|
+
try {
|
|
4931
|
+
const isDryRun = flags.dryRun === true;
|
|
4932
|
+
const report = runReloadPluginsPass(createDefaultWatchTickDeps({ isAutoReloadEnabled: true, isRecoveryEnabled: false }), isDryRun);
|
|
4933
|
+
if (!report) {
|
|
4934
|
+
failWith("could not list Claude sessions (`claude agents --json` failed)");
|
|
4935
|
+
return;
|
|
4936
|
+
}
|
|
4937
|
+
process.stdout.write(flags.json ? `${JSON.stringify(report, null, 2)}
|
|
4938
|
+
` : renderReloadReport(report, isDryRun));
|
|
4939
|
+
} catch (error) {
|
|
4940
|
+
failWith(error instanceof Error ? error.message : String(error));
|
|
4941
|
+
}
|
|
4942
|
+
}
|
|
4943
|
+
function watchRegisterCommand(flags) {
|
|
4944
|
+
try {
|
|
4945
|
+
registerWatchSlot(flags.slot);
|
|
4946
|
+
process.stdout.write(`muggle watch: registered ${flags.slot}
|
|
4947
|
+
`);
|
|
4948
|
+
} catch (error) {
|
|
4949
|
+
failWith(error instanceof Error ? error.message : String(error));
|
|
4950
|
+
}
|
|
4951
|
+
}
|
|
4952
|
+
function watchUnregisterCommand(flags) {
|
|
4953
|
+
const wasRegistered = unregisterWatchSlot(flags.slot);
|
|
4954
|
+
process.stdout.write(`muggle watch: ${wasRegistered ? "unregistered" : "was not registered:"} ${flags.slot}
|
|
4955
|
+
`);
|
|
4956
|
+
}
|
|
4957
|
+
|
|
3557
4958
|
// packages/commands/src/cli/run-cli.ts
|
|
3558
4959
|
var __dirname$1 = dirname(fileURLToPath(import.meta.url));
|
|
3559
4960
|
function getPackageRoot() {
|
|
@@ -3584,6 +4985,12 @@ function createProgram() {
|
|
|
3584
4985
|
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);
|
|
3585
4986
|
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);
|
|
3586
4987
|
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);
|
|
4988
|
+
const watch = program.command("watch").description("Standing watch over Claude/Codex sessions, their processes, and PR watchers");
|
|
4989
|
+
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);
|
|
4990
|
+
watch.command("status").description("Show the last watch pass: sessions, processes, PR watches, findings").option("--json", "Print the snapshot as JSON").action(watchStatusCommand);
|
|
4991
|
+
watch.command("reload-plugins").description("Reload plugins across active Claude sessions (respawns idle background ones)").option("--dry-run", "Show what each session would get without respawning anything").option("--json", "Print the report as JSON").action(watchReloadPluginsCommand);
|
|
4992
|
+
watch.command("register").description("Opt a PR-watch slot into out-of-session recovery").requiredOption("--slot <dir>", "The slot dir under ~/.muggle-ai/muggle-do/sessions").action(watchRegisterCommand);
|
|
4993
|
+
watch.command("unregister").description("Withdraw a PR-watch slot from recovery (it is still reported on)").requiredOption("--slot <dir>", "The slot dir under ~/.muggle-ai/muggle-do/sessions").action(watchUnregisterCommand);
|
|
3587
4994
|
program.action(() => {
|
|
3588
4995
|
helpCommand();
|
|
3589
4996
|
});
|