@muggleai/works 5.26.0-staging.207 → 5.26.0-staging.208

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 (52) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/cli.js +1 -1
  3. package/dist/index.js +1 -1
  4. package/dist/plugin/.claude-plugin/plugin.json +1 -1
  5. package/dist/plugin/.codex-mcp.json +1 -1
  6. package/dist/plugin/.codex-plugin/plugin.json +1 -1
  7. package/dist/plugin/.cursor-plugin/plugin.json +1 -1
  8. package/dist/plugin/.mcp.json +1 -1
  9. package/dist/plugin/hooks/README.md +2 -1
  10. package/dist/plugin/hooks/codex-hooks.json +2 -2
  11. package/dist/plugin/hooks/hooks.json +1 -1
  12. package/dist/plugin/scripts/guardrail-watch-follow-through-gate.sh +48 -0
  13. package/dist/plugin/scripts/guardrails.mjs +282 -32
  14. package/dist/plugin/scripts/pr-watch-arm.sh +64 -37
  15. package/dist/plugin/scripts/pr-watch-due.sh +31 -0
  16. package/dist/plugin/scripts/pr-watch-events.sh +20 -6
  17. package/dist/plugin/scripts/pr-watch-loop.sh +21 -2
  18. package/dist/plugin/scripts/pr-watch-verdict.mjs +197 -0
  19. package/dist/plugin/skills/_shared/ci-check-to-command.md +2 -1
  20. package/dist/plugin/skills/do/fix-ci.md +24 -8
  21. package/dist/plugin/skills/do/resolve-conflicts.md +7 -3
  22. package/dist/plugin/skills/muggle-pr-followup/SKILL.md +1 -1
  23. package/dist/plugin/skills/muggle-pr-followup/arm-watcher.md +5 -3
  24. package/dist/plugin/skills/muggle-pr-followup/blocked-tick.md +2 -0
  25. package/dist/plugin/skills/muggle-pr-followup/contract.md +40 -25
  26. package/dist/plugin/skills/muggle-pr-followup/state-schemas.md +22 -8
  27. package/dist/release-manifest.json +3 -3
  28. package/package.json +1 -1
  29. package/plugin/.claude-plugin/plugin.json +1 -1
  30. package/plugin/.codex-mcp.json +1 -1
  31. package/plugin/.codex-plugin/plugin.json +1 -1
  32. package/plugin/.cursor-plugin/plugin.json +1 -1
  33. package/plugin/.mcp.json +1 -1
  34. package/plugin/hooks/README.md +2 -1
  35. package/plugin/hooks/codex-hooks.json +2 -2
  36. package/plugin/hooks/hooks.json +1 -1
  37. package/plugin/scripts/guardrail-watch-follow-through-gate.sh +48 -0
  38. package/plugin/scripts/guardrails.mjs +282 -32
  39. package/plugin/scripts/pr-watch-arm.sh +64 -37
  40. package/plugin/scripts/pr-watch-due.sh +31 -0
  41. package/plugin/scripts/pr-watch-events.sh +20 -6
  42. package/plugin/scripts/pr-watch-loop.sh +21 -2
  43. package/plugin/scripts/pr-watch-verdict.mjs +197 -0
  44. package/plugin/skills/_shared/ci-check-to-command.md +2 -1
  45. package/plugin/skills/do/fix-ci.md +24 -8
  46. package/plugin/skills/do/resolve-conflicts.md +7 -3
  47. package/plugin/skills/muggle-pr-followup/SKILL.md +1 -1
  48. package/plugin/skills/muggle-pr-followup/arm-watcher.md +5 -3
  49. package/plugin/skills/muggle-pr-followup/blocked-tick.md +2 -0
  50. package/plugin/skills/muggle-pr-followup/contract.md +40 -25
  51. package/plugin/skills/muggle-pr-followup/state-schemas.md +22 -8
  52. /package/dist/{chunk-HGN35NEP.js → chunk-HOKMW4AL.js} +0 -0
@@ -1,4 +1,4 @@
1
- import { readFileSync, existsSync, readdirSync, mkdirSync, statSync, writeFileSync, renameSync, openSync, writeSync, closeSync, unlinkSync } from 'fs';
1
+ import { readFileSync, existsSync, readdirSync, mkdirSync, openSync, fstatSync, readSync, closeSync, statSync, writeFileSync, renameSync, writeSync, unlinkSync } from 'fs';
2
2
  import { join, basename, isAbsolute, resolve, dirname } from 'path';
3
3
  import { homedir, hostname } from 'os';
4
4
  import { execFileSync, spawn } from 'child_process';
@@ -34,6 +34,9 @@ var MAX_WATCH_BLOCKS = 3;
34
34
  var WATCH_HEARTBEAT_STALE_MS = 15 * 6e4;
35
35
  var TERMINAL_SLOT_PR_STATES = ["merged", "closed"];
36
36
  var STOPPED_SLOT_SUFFIX = ".stopped";
37
+ var WATCH_HOLD_PHRASE_PREFIX = "HOLD WATCH #";
38
+ var WATCH_HOLD_INSTRUCTION = /HOLD WATCH #(\d+)\b/g;
39
+ var WATCH_HOLD_TRANSCRIPT_TAIL_BYTES = 4e6;
37
40
  var MAX_BUILD_BLOCKS = 3;
38
41
  var MAX_WALKTHROUGH_BLOCKS = 3;
39
42
  var GH_LOOKUP_TIMEOUT_MS = 1e4;
@@ -370,6 +373,11 @@ function lastAssistantText(transcriptJsonl) {
370
373
  }
371
374
  return "";
372
375
  }
376
+ function resolvePluginRoot(env = process.env) {
377
+ return env.CLAUDE_PLUGIN_ROOT || env.CURSOR_PLUGIN_ROOT || dirname(dirname(fileURLToPath(import.meta.url)));
378
+ }
379
+
380
+ // src/guardrails/mandatoryStages.ts
373
381
  var FRONTMATTER = /^---\r?\n([\s\S]*?)\r?\n---/;
374
382
  var SEQUENCE_ENTRY = /^\s*-\s*(.+?)\s*$/;
375
383
  var FLOW_LIST = /^\s*\[(.*)\]\s*$/;
@@ -413,9 +421,7 @@ function stageLabel(normalizedStagePath) {
413
421
  return normalizedStagePath.slice(insideSkills + SKILLS_PATH_SEGMENT.length);
414
422
  }
415
423
  function resolvePluginSkillsRoot() {
416
- const pluginRoot = process.env.CLAUDE_PLUGIN_ROOT || process.env.CURSOR_PLUGIN_ROOT;
417
- if (pluginRoot) return join(pluginRoot, SKILLS_DIR_NAME);
418
- return join(dirname(dirname(fileURLToPath(import.meta.url))), SKILLS_DIR_NAME);
424
+ return join(resolvePluginRoot(), SKILLS_DIR_NAME);
419
425
  }
420
426
  function resolveSkillNameFromToolInput(toolInput) {
421
427
  if (!toolInput) return void 0;
@@ -916,6 +922,75 @@ function patchPrComment(pr, commentId, body, run) {
916
922
  );
917
923
  }
918
924
 
925
+ // src/pr-watch/constants.ts
926
+ var MUGGLE_DO_SESSIONS_PATH_SEGMENTS = [".muggle-ai", "muggle-do", "sessions"];
927
+ var PRS_FILE_NAME = "prs.json";
928
+ var OWNER_FILE_NAME = "owner.json";
929
+ var LAST_SEEN_FILE_NAME = "last_seen.json";
930
+ var RESULT_FILE_NAME = "result.md";
931
+ var WATCH_DUE_FILE_NAME = "watch-due.env";
932
+ var WATCH_DUE_HEAD_FIELD = "HEAD";
933
+ var WATCH_DUE_REBASE_FIELD = "REBASE_DUE";
934
+ var WATCH_DUE_CI_RED_FIELD = "CI_RED_HEAD";
935
+ var ENV_FILE_LINE = /^([A-Z_]+)="?([^"]*)"?$/;
936
+ var USER_PREFERENCES_PATH_SEGMENTS = [".muggle-ai", "preferences.json"];
937
+ var PREFERENCE_DEFAULTS_PATH_SEGMENTS = ["config", "preference-defaults.json"];
938
+ var AUTO_REBASE_PREFERENCE_KEY = "autoRebase";
939
+ var MAX_CATCH_UP_REBASES_PREFERENCE_KEY = "maxCatchUpRebases";
940
+ var ALWAYS_PREFERENCE_VALUE = "always";
941
+ var UNBOUNDED_PREFERENCE_VALUE = "never";
942
+ var POSITIVE_INTEGER = /^[1-9]\d*$/;
943
+ function readSlotText(filePath) {
944
+ try {
945
+ return readFileSync(filePath, "utf-8");
946
+ } catch {
947
+ return "";
948
+ }
949
+ }
950
+ function readSlotPr(slotPath) {
951
+ try {
952
+ const parsed = JSON.parse(readFileSync(join(slotPath, PRS_FILE_NAME), "utf-8"));
953
+ const slotPr = Array.isArray(parsed) ? parsed[0] : parsed;
954
+ return slotPr !== null && typeof slotPr === "object" ? slotPr : void 0;
955
+ } catch {
956
+ return void 0;
957
+ }
958
+ }
959
+ function readJsonRecord(filePath) {
960
+ try {
961
+ return asRecord(JSON.parse(readFileSync(filePath, "utf-8")));
962
+ } catch {
963
+ return {};
964
+ }
965
+ }
966
+ function asRecord(candidate) {
967
+ return candidate !== null && typeof candidate === "object" && !Array.isArray(candidate) ? candidate : {};
968
+ }
969
+ function lastSeenEntryFor(lastSeenJson, prKey) {
970
+ try {
971
+ return asRecord(asRecord(JSON.parse(lastSeenJson))[prKey]);
972
+ } catch {
973
+ return {};
974
+ }
975
+ }
976
+ function parseEnvFileLines(envFileText) {
977
+ const fields = {};
978
+ for (const rawLine of envFileText.split("\n")) {
979
+ const fieldMatch = ENV_FILE_LINE.exec(rawLine.replace(/\r$/, ""));
980
+ if (fieldMatch) fields[fieldMatch[1]] = fieldMatch[2];
981
+ }
982
+ return fields;
983
+ }
984
+ function parseWatchDueRecord(watchDueText) {
985
+ const fields = parseEnvFileLines(watchDueText);
986
+ const dueRecord = {
987
+ headSha: fields[WATCH_DUE_HEAD_FIELD] ?? "",
988
+ rebaseDueKey: fields[WATCH_DUE_REBASE_FIELD] ?? "",
989
+ ciRedHeadSha: fields[WATCH_DUE_CI_RED_FIELD] ?? ""
990
+ };
991
+ return dueRecord.rebaseDueKey || dueRecord.ciRedHeadSha ? dueRecord : null;
992
+ }
993
+
919
994
  // src/guardrails/watchArmed.ts
920
995
  var WATCH_SKIP_MARKER = /^\s*echo\s+["']?MUGGLE_WATCH_SKIP\b/;
921
996
  function isWatchSkipMarker(cmd) {
@@ -943,7 +1018,7 @@ function readHeartbeatMtimeMs(slotPath) {
943
1018
  }
944
1019
  function findUnwatchedHandledPrs(handledUrls, sessionsDirOverride) {
945
1020
  if (handledUrls.length === 0) return [];
946
- const sessionsDir = join(homedir(), ".muggle-ai", "muggle-do", "sessions");
1021
+ const sessionsDir = join(homedir(), ...MUGGLE_DO_SESSIONS_PATH_SEGMENTS);
947
1022
  let slugs;
948
1023
  try {
949
1024
  slugs = readdirSync(sessionsDir);
@@ -954,18 +1029,12 @@ function findUnwatchedHandledPrs(handledUrls, sessionsDirOverride) {
954
1029
  const watchedUrls = /* @__PURE__ */ new Set();
955
1030
  for (const slug of slugs) {
956
1031
  const slotPath = join(sessionsDir, slug);
957
- let slotPr;
958
- try {
959
- const parsed = JSON.parse(readFileSync(join(slotPath, "prs.json"), "utf-8"));
960
- slotPr = Array.isArray(parsed) ? parsed[0] : parsed;
961
- } catch {
962
- continue;
963
- }
1032
+ const slotPr = readSlotPr(slotPath);
964
1033
  const slotUrl = slotPr?.url;
965
1034
  if (typeof slotUrl !== "string" || !handledUrls.includes(slotUrl)) continue;
966
1035
  const evidence = {
967
1036
  isStopped: slug.endsWith(STOPPED_SLOT_SUFFIX),
968
- isFinalized: existsSync(join(slotPath, "result.md")),
1037
+ isFinalized: existsSync(join(slotPath, RESULT_FILE_NAME)),
969
1038
  recordedPrState: typeof slotPr?.state === "string" ? slotPr.state : void 0,
970
1039
  heartbeatMtimeMs: readHeartbeatMtimeMs(slotPath)
971
1040
  };
@@ -1023,6 +1092,166 @@ function watchGateDecision(state, unwatchedPrUrls, maxBlocks = MAX_WATCH_BLOCKS)
1023
1092
  };
1024
1093
  }
1025
1094
 
1095
+ // src/pr-watch/attempts.ts
1096
+ function recordedCount(counts, key) {
1097
+ const recorded = counts?.[key];
1098
+ return typeof recorded === "number" && Number.isFinite(recorded) ? recorded : 0;
1099
+ }
1100
+ function rebaseAttemptsFor(lastSeenEntry, rebaseKey) {
1101
+ return recordedCount(lastSeenEntry.conflict_resolve_attempts, rebaseKey);
1102
+ }
1103
+ function ciFixAttemptsFor(lastSeenEntry, headSha) {
1104
+ return recordedCount(lastSeenEntry.ci_fix_attempts, headSha);
1105
+ }
1106
+ function isRebaseKeyAttempted(lastSeenEntry, rebaseKey) {
1107
+ return rebaseAttemptsFor(lastSeenEntry, rebaseKey) >= 1;
1108
+ }
1109
+ function isCiHeadAttempted(lastSeenEntry, headSha) {
1110
+ return ciFixAttemptsFor(lastSeenEntry, headSha) >= 1;
1111
+ }
1112
+ function isRebaseBudgetExhausted(lastSeenEntry, maxCatchUpRebases) {
1113
+ const catchUpRebases = lastSeenEntry.catch_up_rebases;
1114
+ return maxCatchUpRebases !== null && typeof catchUpRebases === "number" && catchUpRebases >= maxCatchUpRebases;
1115
+ }
1116
+
1117
+ // src/transcript/constants.ts
1118
+ var USER_ENTRY_TYPE = "user";
1119
+ var HUMAN_ORIGIN_KIND = "human";
1120
+ var TEXT_CONTENT_PART_TYPE = "text";
1121
+ var TOOL_RESULT_CONTENT_PART_TYPE = "tool_result";
1122
+
1123
+ // src/transcript/userTurns.ts
1124
+ function userAuthoredText(entry) {
1125
+ if (entry.type !== USER_ENTRY_TYPE) return null;
1126
+ if (entry.isMeta || entry.isCompactSummary || entry.isSidechain || entry.toolUseResult !== void 0) return null;
1127
+ if (entry.origin != null && entry.origin.kind !== HUMAN_ORIGIN_KIND) return null;
1128
+ const content = entry.message?.content;
1129
+ if (typeof content === "string") return content;
1130
+ if (!Array.isArray(content)) return null;
1131
+ const parts = content;
1132
+ if (parts.some((part) => part?.type === TOOL_RESULT_CONTENT_PART_TYPE)) return null;
1133
+ return parts.filter((part) => part?.type === TEXT_CONTENT_PART_TYPE && typeof part.text === "string").map((part) => part.text).join("\n");
1134
+ }
1135
+ function userAuthoredTextsContaining(transcriptJsonl, literal) {
1136
+ const texts = [];
1137
+ for (const line of transcriptJsonl.split("\n")) {
1138
+ if (!line.includes(literal)) continue;
1139
+ let entry;
1140
+ try {
1141
+ entry = JSON.parse(line);
1142
+ } catch {
1143
+ continue;
1144
+ }
1145
+ const text = userAuthoredText(entry);
1146
+ if (text !== null && text.includes(literal)) texts.push(text);
1147
+ }
1148
+ return texts;
1149
+ }
1150
+ function readFileTail(filePath, maxBytes) {
1151
+ let descriptor;
1152
+ try {
1153
+ descriptor = openSync(filePath, "r");
1154
+ const fileSize = fstatSync(descriptor).size;
1155
+ const length = Math.min(fileSize, maxBytes);
1156
+ const tail = Buffer.alloc(length);
1157
+ readSync(descriptor, tail, 0, length, fileSize - length);
1158
+ return tail.toString("utf-8");
1159
+ } catch {
1160
+ return null;
1161
+ } finally {
1162
+ if (descriptor !== void 0) closeSync(descriptor);
1163
+ }
1164
+ }
1165
+
1166
+ // src/guardrails/watchFollowThrough.ts
1167
+ function mtimeMsOf(filePath) {
1168
+ try {
1169
+ return statSync(filePath).mtimeMs;
1170
+ } catch {
1171
+ return void 0;
1172
+ }
1173
+ }
1174
+ function isDueRecordSuperseded(slotPath, slotPr, dueRecord) {
1175
+ if (!slotPr.head_sha || slotPr.head_sha === dueRecord.headSha) return false;
1176
+ const prsWrittenAtMs = mtimeMsOf(join(slotPath, PRS_FILE_NAME));
1177
+ const dueWrittenAtMs = mtimeMsOf(join(slotPath, WATCH_DUE_FILE_NAME));
1178
+ return prsWrittenAtMs !== void 0 && dueWrittenAtMs !== void 0 && prsWrittenAtMs > dueWrittenAtMs;
1179
+ }
1180
+ function owedWorkInSlot(slotPath, slug, sessionId2, preferences) {
1181
+ if (slug.endsWith(STOPPED_SLOT_SUFFIX)) return [];
1182
+ const dueRecord = parseWatchDueRecord(readSlotText(join(slotPath, WATCH_DUE_FILE_NAME)));
1183
+ if (!dueRecord) return [];
1184
+ if (readJsonRecord(join(slotPath, OWNER_FILE_NAME)).session_id !== sessionId2) return [];
1185
+ if (existsSync(join(slotPath, RESULT_FILE_NAME))) return [];
1186
+ const slotPr = readSlotPr(slotPath);
1187
+ const prUrl = slotPr?.url;
1188
+ const prNumber = slotPr?.number;
1189
+ if (!slotPr?.repo || typeof prUrl !== "string" || typeof prNumber !== "number") return [];
1190
+ if (TERMINAL_SLOT_PR_STATES.includes((slotPr.state ?? "").toLowerCase())) return [];
1191
+ if (isDueRecordSuperseded(slotPath, slotPr, dueRecord)) return [];
1192
+ const lastSeenEntry = lastSeenEntryFor(readSlotText(join(slotPath, LAST_SEEN_FILE_NAME)), `${slotPr.repo}#${prNumber}`);
1193
+ const workOn = (kind, dueOn) => ({
1194
+ kind,
1195
+ slug,
1196
+ prUrl,
1197
+ prNumber,
1198
+ dueOn
1199
+ });
1200
+ const owed = [];
1201
+ const isRebaseOwed = dueRecord.rebaseDueKey !== "" && preferences.autoRebase === ALWAYS_PREFERENCE_VALUE && !isRebaseBudgetExhausted(lastSeenEntry, preferences.maxCatchUpRebases) && !isRebaseKeyAttempted(lastSeenEntry, dueRecord.rebaseDueKey);
1202
+ if (isRebaseOwed) owed.push(workOn("rebase" /* Rebase */, dueRecord.rebaseDueKey));
1203
+ if (dueRecord.ciRedHeadSha !== "" && !isCiHeadAttempted(lastSeenEntry, dueRecord.ciRedHeadSha)) {
1204
+ owed.push(workOn("fix-ci" /* FixCi */, dueRecord.ciRedHeadSha));
1205
+ }
1206
+ return owed;
1207
+ }
1208
+ function findOwedWatchWork(sessionId2, preferences, sessionsDirOverride) {
1209
+ const sessionsDir = join(homedir(), ...MUGGLE_DO_SESSIONS_PATH_SEGMENTS);
1210
+ let slugs;
1211
+ try {
1212
+ slugs = readdirSync(sessionsDir);
1213
+ } catch {
1214
+ return [];
1215
+ }
1216
+ return slugs.flatMap((slug) => owedWorkInSlot(join(sessionsDir, slug), slug, sessionId2, preferences));
1217
+ }
1218
+ function heldPrNumbersIn(transcriptJsonl) {
1219
+ const heldPrNumbers = /* @__PURE__ */ new Set();
1220
+ for (const userText of userAuthoredTextsContaining(transcriptJsonl, WATCH_HOLD_PHRASE_PREFIX)) {
1221
+ for (const hold of userText.matchAll(WATCH_HOLD_INSTRUCTION)) heldPrNumbers.add(Number(hold[1]));
1222
+ }
1223
+ return [...heldPrNumbers];
1224
+ }
1225
+ function applyWatchHolds(state, heldPrNumbers) {
1226
+ const recorded = state.watchHeldPrNumbers ?? [];
1227
+ const newlyHeld = heldPrNumbers.filter((prNumber) => !recorded.includes(prNumber));
1228
+ if (newlyHeld.length === 0) return state;
1229
+ return { ...state, watchHeldPrNumbers: [...recorded, ...newlyHeld] };
1230
+ }
1231
+ function watchFollowThroughDecision(state, owedWork) {
1232
+ const heldPrNumbers = state.watchHeldPrNumbers ?? [];
1233
+ const owed = owedWork.filter((work) => !heldPrNumbers.includes(work.prNumber));
1234
+ const blockCount = state.watchFollowThroughBlockCount ?? 0;
1235
+ if (owed.length === 0) return { action: "none" /* None */, blockCount, owed };
1236
+ return { action: "block" /* Block */, blockCount: blockCount + 1, owed };
1237
+ }
1238
+ function parseMaxCatchUpRebases(configuredValue) {
1239
+ if (configuredValue === UNBOUNDED_PREFERENCE_VALUE) return null;
1240
+ const spelled = typeof configuredValue === "number" ? String(configuredValue) : configuredValue;
1241
+ return typeof spelled === "string" && POSITIVE_INTEGER.test(spelled) ? Number(spelled) : void 0;
1242
+ }
1243
+ function resolveWatchPreferences(homeDir = homedir(), pluginRoot = resolvePluginRoot()) {
1244
+ const shippedDefaults = readJsonRecord(join(pluginRoot, ...PREFERENCE_DEFAULTS_PATH_SEGMENTS));
1245
+ const userPreferences = asRecord(readJsonRecord(join(homeDir, ...USER_PREFERENCES_PATH_SEGMENTS)).preferences);
1246
+ const autoRebase = userPreferences[AUTO_REBASE_PREFERENCE_KEY] ?? shippedDefaults[AUTO_REBASE_PREFERENCE_KEY];
1247
+ const userCap = parseMaxCatchUpRebases(userPreferences[MAX_CATCH_UP_REBASES_PREFERENCE_KEY]);
1248
+ const shippedCap = parseMaxCatchUpRebases(shippedDefaults[MAX_CATCH_UP_REBASES_PREFERENCE_KEY]);
1249
+ return {
1250
+ autoRebase: typeof autoRebase === "string" ? autoRebase : void 0,
1251
+ maxCatchUpRebases: userCap !== void 0 ? userCap : shippedCap ?? null
1252
+ };
1253
+ }
1254
+
1026
1255
  // src/guardrails/buildFollowthrough.ts
1027
1256
  var BUILD_SKIP_MARKER = /^\s*echo\s+["']?MUGGLE_BUILD_SKIP\b/;
1028
1257
  function isBuildSkipMarker(cmd) {
@@ -1397,17 +1626,7 @@ var verifyUserWaived = (context) => {
1397
1626
  const transcript = context.probe.readTextFile(context.transcriptPath);
1398
1627
  if (!transcript) return refuted("the transcript could not be read");
1399
1628
  const tail = transcript.slice(-64e3);
1400
- const waived = tail.split("\n").some((line) => {
1401
- if (!line.includes(USER_WAIVE_PHRASE)) return false;
1402
- try {
1403
- const entry = JSON.parse(line);
1404
- const isUserTurn = entry.type === "user" || entry.message?.role === "user";
1405
- return isUserTurn && JSON.stringify(entry.message?.content ?? "").includes(USER_WAIVE_PHRASE);
1406
- } catch {
1407
- return false;
1408
- }
1409
- });
1410
- if (waived) return verified;
1629
+ if (userAuthoredTextsContaining(tail, USER_WAIVE_PHRASE).length > 0) return verified;
1411
1630
  return refuted(`no user turn in the transcript contains "${USER_WAIVE_PHRASE}"`);
1412
1631
  };
1413
1632
  var namePaths = (paths) => {
@@ -1757,17 +1976,11 @@ function threadForReplyTarget(ledger, targetId) {
1757
1976
  return void 0;
1758
1977
  }
1759
1978
  function resolveSlotForPr(prUrl, sessionsDirOverride) {
1760
- const sessionsDir = join(homedir(), ".muggle-ai", "muggle-do", "sessions");
1979
+ const sessionsDir = join(homedir(), ...MUGGLE_DO_SESSIONS_PATH_SEGMENTS);
1761
1980
  if (!existsSync(sessionsDir)) return void 0;
1762
1981
  for (const slug of readdirSync(sessionsDir)) {
1763
1982
  const slotPath = join(sessionsDir, slug);
1764
- try {
1765
- const parsed = JSON.parse(readFileSync(join(slotPath, "prs.json"), "utf-8"));
1766
- const slotPr = Array.isArray(parsed) ? parsed[0] : parsed;
1767
- if (slotPr?.url === prUrl) return slotPath;
1768
- } catch {
1769
- continue;
1770
- }
1983
+ if (readSlotPr(slotPath)?.url === prUrl) return slotPath;
1771
1984
  }
1772
1985
  return void 0;
1773
1986
  }
@@ -2156,6 +2369,42 @@ function watchGate() {
2156
2369
  const reason = decision.blockCount === 1 ? `Do not end the turn yet. A PR opened this session is open with no live muggle-pr-followup watch: ${prList}. Arm its watch per the muggle-pr-followup arming procedure (arm-watcher.md) \u2014 invoking ${armCommand} bootstraps it and arms it that way (add --resume when its slot already exists). A seeded slot does not count: only a running watch loop does, shown by a watch-heartbeat it touches every poll and that goes stale after ${staleMinutes} minutes (a watch armed moments ago writes it on its first poll). If the PR already merged or closed, end the turn again \u2014 a provider check started now clears it. If it genuinely should not be watched (autoWatchPR=never, handed off elsewhere), tell the user why and run \`echo "MUGGLE_WATCH_SKIP: <reason>"\` \u2014 that records the skip and keeps this gate quiet for the rest of the session.` : `PR watch still owed for ${prList} (reminder ${decision.blockCount}/${MAX_WATCH_BLOCKS}): arm it per arm-watcher.md via ${armCommand} (--resume when its slot exists), or record a legitimate skip via \`echo "MUGGLE_WATCH_SKIP: <reason>"\`.`;
2157
2370
  return blockStop(reason, host);
2158
2371
  }
2372
+ function owedWatchWorkLine(work) {
2373
+ const muggleDo = muggleSkill("/muggle-do");
2374
+ if (work.kind === "rebase" /* Rebase */) {
2375
+ return `- PR #${work.prNumber} (${work.prUrl}) is behind or conflicting with its base (key ${work.dueOn}) and no rebase was attempted: dispatch \`${muggleDo} rebase on ${work.prUrl} slug=${work.slug}\`.`;
2376
+ }
2377
+ return `- PR #${work.prNumber} (${work.prUrl}) has red CI on head ${work.dueOn.slice(0, 8)} and no fix was attempted: dispatch \`${muggleDo} fix ci <red checks> on ${work.prUrl} slug=${work.slug}\` \u2014 the tick \`${muggleSkill("/muggle:muggle-pr-followup")} ${work.slug} ${work.prNumber} --wake=follow-through\` names the checks.`;
2378
+ }
2379
+ function watchFollowThroughGate() {
2380
+ const owedWork = findOwedWatchWork(sessionId, resolveWatchPreferences());
2381
+ const stateBefore = readState(sessionId);
2382
+ const transcriptTail = watchFollowThroughDecision(stateBefore, owedWork).action === "block" /* Block */ && input.transcript_path ? readFileTail(input.transcript_path, WATCH_HOLD_TRANSCRIPT_TAIL_BYTES) : null;
2383
+ const heldPrNumbers = transcriptTail ? heldPrNumbersIn(transcriptTail) : [];
2384
+ const state = applyWatchHolds(stateBefore, heldPrNumbers);
2385
+ const decision = watchFollowThroughDecision(state, owedWork);
2386
+ if (decision.action === "none" /* None */) {
2387
+ if (state !== stateBefore || (state.watchFollowThroughBlockCount ?? 0) > 0) {
2388
+ updateState(sessionId, (current) => ({
2389
+ ...applyWatchHolds(current, heldPrNumbers),
2390
+ watchFollowThroughBlockCount: 0
2391
+ }));
2392
+ }
2393
+ return "{}";
2394
+ }
2395
+ updateState(sessionId, (current) => ({
2396
+ ...applyWatchHolds(current, heldPrNumbers),
2397
+ watchFollowThroughBlockCount: decision.blockCount
2398
+ }));
2399
+ const owedList = decision.owed.map(owedWatchWorkLine).join("\n");
2400
+ const holdInstruction = `Only the user can hold it: their own message containing \`${WATCH_HOLD_PHRASE_PREFIX}<pr-number>\` for that PR. Ask if you must; never decide it for them.`;
2401
+ const reason = decision.blockCount === 1 ? `Do not end the turn yet. A muggle-pr-followup watch this session owns found work due that nothing acted on:
2402
+ ${owedList}
2403
+ autoRebase=always makes a due rebase binding, and how long a CI run or an eval takes is never a reason to wait. Act now \u2014 if the tick finds actionable review feedback it dispatches that first. A recorded attempt (conflict_resolve_attempts / ci_fix_attempts) or a new head clears this; an escalation entry with no attempt behind it does not, and neither does re-arming the watch. ${holdInstruction}` : `Watcher work still owed (reminder ${decision.blockCount}):
2404
+ ${owedList}
2405
+ ${holdInstruction}`;
2406
+ return blockStop(reason, host);
2407
+ }
2159
2408
  function buildFollowthroughGate() {
2160
2409
  const state = readState(sessionId);
2161
2410
  const decision = buildFollowthroughDecision(state);
@@ -2319,6 +2568,7 @@ var handlers = {
2319
2568
  "e2e-gate": e2eGate,
2320
2569
  "terminal-gate": terminalGate,
2321
2570
  "watch-gate": watchGate,
2571
+ "watch-follow-through-gate": watchFollowThroughGate,
2322
2572
  "build-followthrough-gate": buildFollowthroughGate,
2323
2573
  "walkthrough-gate": walkthroughGate,
2324
2574
  "record-comment-replies": recordCommentReplies,
@@ -11,6 +11,11 @@
11
11
  # The floors are taken from the drain's own read rather than from a fresh fetch
12
12
  # afterwards: anything that lands between the two would otherwise be marked seen
13
13
  # without ever being reported.
14
+ #
15
+ # A stale branch or a red head is floored only when the slot proves a cycle ran
16
+ # for it. Flooring whatever was outstanding at arm time let a session that never
17
+ # rebased or fixed anything re-arm at every rollover and silence the loop each
18
+ # time; the drain line said "handled" and nothing checked.
14
19
  set -uo pipefail
15
20
 
16
21
  script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
@@ -33,7 +38,7 @@ if [ -z "$slot" ] || [ -z "$repo" ] || [ -z "$pr_number" ] || [ -z "$base_branch
33
38
  exit 2
34
39
  fi
35
40
 
36
- for lib in pr-watch-guards.sh pr-watch-events.sh pr-watch-fetch.sh; do
41
+ for lib in pr-watch-guards.sh pr-watch-events.sh pr-watch-fetch.sh pr-watch-due.sh; do
37
42
  if [ ! -f "${script_dir}/${lib}" ]; then
38
43
  echo "pr-watch-arm: missing ${lib} beside this script" >&2
39
44
  exit 2
@@ -42,10 +47,12 @@ for lib in pr-watch-guards.sh pr-watch-events.sh pr-watch-fetch.sh; do
42
47
  . "${script_dir}/${lib}"
43
48
  done
44
49
 
45
- if [ ! -f "${script_dir}/pr-watch-state.jq" ]; then
46
- echo "pr-watch-arm: missing pr-watch-state.jq beside this script" >&2
47
- exit 2
48
- fi
50
+ for companion in pr-watch-state.jq pr-watch-verdict.mjs; do
51
+ if [ ! -f "${script_dir}/${companion}" ]; then
52
+ echo "pr-watch-arm: missing ${companion} beside this script" >&2
53
+ exit 2
54
+ fi
55
+ done
49
56
  state_projection="$(cat "${script_dir}/pr-watch-state.jq")"
50
57
 
51
58
  mkdir -p "$slot"
@@ -75,50 +82,68 @@ if [ "$pr_state" = "MERGED" ] || [ "$pr_state" = "CLOSED" ]; then
75
82
  exit 0
76
83
  fi
77
84
 
78
- # A red head at arm time is the drain's to hand over, so it goes into the floor
79
- # and does not re-fire on the loop's first pass. Pending checks are not red yet.
80
- ci_red_floor=""
81
- if [ "${pending_checks:-0}" -eq 0 ] 2>/dev/null && [ "${failed_checks:-0}" -gt 0 ] 2>/dev/null; then
82
- ci_red_floor="$head_sha"
83
- fi
85
+ ci_red_head=""
86
+ watch_checks_settled_red "$pending_checks" "$failed_checks" && ci_red_head="$head_sha"
84
87
 
85
- # Same for staleness: keyed on the head/base-tip pair, so it re-arms when either moves.
86
- rebase_floor=""
88
+ # Keyed on the head/base-tip pair, so it re-arms when either moves.
89
+ rebase_key="${head_sha}..${base_tip_sha}"
90
+ rebase_due_key=""
87
91
  behind_count="$(watch_fetch_behind_count "$repo" "$base_branch" "$head_sha" "$slot")"
88
- if [ "$mergeable" = "CONFLICTING" ] || { [ -n "$behind_count" ] && [ "$behind_count" -gt 0 ] 2>/dev/null; }; then
89
- rebase_floor="${head_sha}..${base_tip_sha}"
90
- fi
92
+ watch_branch_needs_rebase "$mergeable" "$behind_count" && rebase_due_key="$rebase_key"
91
93
 
92
- # A slot re-armed while blocked keeps its resume probe live. Empty is the
93
- # not-blocked state, so seeding it empty here would leave the loop asleep
94
- # through the very CI move the block is waiting on.
94
+ # Whether a cycle already ran for this key and this head, and the blocked
95
+ # fingerprint's digest. A slot re-armed while blocked keeps its resume probe
96
+ # live: empty is the not-blocked state, so seeding it empty would leave the loop
97
+ # asleep through the very CI move the block is waiting on.
95
98
  #
96
- # node rather than sed or jq: the digest sits under a per-PR key, jq is not
97
- # guaranteed present, and a malformed file must read as not blocked rather than
98
- # yield a partial match. The file goes in on stdin because Windows node cannot
99
- # open the POSIX path Git Bash hands it. A digest spanning lines is dropped:
100
- # written into the line-based watermark, it could forge another floor.
99
+ # The verdict script rather than sed or jq: the fields sit under a per-PR key,
100
+ # jq is not guaranteed present, and a malformed file must read as nothing
101
+ # recorded rather than yield a partial match. The file goes in on stdin because
102
+ # Windows node cannot open the POSIX path Git Bash hands it. Any failure leaves
103
+ # every floor empty, which wakes the loop rather than silencing it.
104
+ last_seen_file="${slot}/last_seen.json"
105
+ [ -f "$last_seen_file" ] || last_seen_file=/dev/null
106
+ rebase_attempted=0
107
+ ci_attempted=0
101
108
  blocked_digest_floor=""
102
- if [ -f "${slot}/last_seen.json" ]; then
103
- blocked_digest_floor="$(PR_KEY="${repo}#${pr_number}" node -e '
104
- try {
105
- const digest = JSON.parse(require("fs").readFileSync(0, "utf8"))[process.env.PR_KEY]?.blocked?.fingerprint?.ci_digest;
106
- if (typeof digest === "string" && !/[\r\n]/.test(digest)) process.stdout.write(digest);
107
- } catch {}
108
- ' < "${slot}/last_seen.json" 2>/dev/null)"
109
- fi
109
+ while IFS= read -r evidence_line; do
110
+ evidence_line="${evidence_line%$'\r'}"
111
+ case "$evidence_line" in
112
+ REBASE_ATTEMPTED=*) rebase_attempted="${evidence_line#REBASE_ATTEMPTED=}" ;;
113
+ CI_ATTEMPTED=*) ci_attempted="${evidence_line#CI_ATTEMPTED=}" ;;
114
+ BLOCKED_CIDIGEST=*) blocked_digest_floor="${evidence_line#BLOCKED_CIDIGEST=}" ;;
115
+ esac
116
+ done < <(node "${script_dir}/pr-watch-verdict.mjs" arm-floors --pr-key "${repo}#${pr_number}" \
117
+ --head "$head_sha" --rebase-key "$rebase_key" < "$last_seen_file" 2>/dev/null)
118
+
119
+ ci_red_floor=""
120
+ [ -n "$ci_red_head" ] && [ "$ci_attempted" = "1" ] && ci_red_floor="$ci_red_head"
121
+ rebase_floor=""
122
+ [ -n "$rebase_due_key" ] && [ "$rebase_attempted" = "1" ] && rebase_floor="$rebase_due_key"
110
123
 
111
124
  thread_count=0
112
125
  [ -n "$unresolved_threads" ] && thread_count=$(printf '%s' "$unresolved_threads" | tr ';' '\n' | grep -c .)
113
126
 
114
- # Printed, not swallowed: these are the things the arming session owes a decision
115
- # on before the monitor takes over, and the monitor only ever sees what arrives
116
- # after this point.
127
+ # Printed, not swallowed: these are the things the arming session owes action on
128
+ # before the monitor takes over. Unattempted work is left unfloored, so the
129
+ # loop's first pass reports it again as an event.
117
130
  echo "DRAIN pr=$pr_number state=$pr_state head=${head_sha:0:8}"
118
131
  echo "DRAIN unresolved-threads=$thread_count latest-review=${latest_review:-0} latest-comment=${latest_comment:-0}"
119
132
  echo "DRAIN checks pending=${pending_checks:-0} failed=${failed_checks:-0} behind-base=${behind_count:-unknown} mergeable=${mergeable:-UNKNOWN}"
120
- [ -n "$ci_red_floor" ] && echo "DRAIN ci already red at arm time — handled by the arming session, floored"
121
- [ -n "$rebase_floor" ] && echo "DRAIN branch already stale at arm time — handled by the arming session, floored"
133
+ if [ -n "$ci_red_head" ]; then
134
+ if [ -n "$ci_red_floor" ]; then
135
+ echo "DRAIN ci red at arm time — a fix-ci cycle already ran for head ${head_sha:0:8}, floored"
136
+ else
137
+ echo "DRAIN ci red at arm time — no fix-ci attempt recorded for head ${head_sha:0:8}, not floored: dispatch fix-ci"
138
+ fi
139
+ fi
140
+ if [ -n "$rebase_due_key" ]; then
141
+ if [ -n "$rebase_floor" ]; then
142
+ echo "DRAIN branch stale at arm time — a rebase already ran for key ${rebase_due_key}, floored"
143
+ else
144
+ echo "DRAIN branch stale at arm time — no rebase attempt recorded for key ${rebase_due_key}, not floored: dispatch rebase"
145
+ fi
146
+ fi
122
147
 
123
148
  {
124
149
  printf 'REV=%s\n' "${latest_review:-0}"
@@ -129,6 +154,8 @@ echo "DRAIN checks pending=${pending_checks:-0} failed=${failed_checks:-0} behin
129
154
  printf 'BLOCKED_CIDIGEST="%s"\n' "$blocked_digest_floor"
130
155
  } > "${slot}/watch-watermark.env"
131
156
 
157
+ watch_record_due_work "$slot" "$head_sha" "$rebase_due_key" "$ci_red_head"
158
+
132
159
  # Claim the slot for this session. watcher_lease_is_foreign reads an absent
133
160
  # owner.json as "not foreign", so a slot armed without one leases itself to a
134
161
  # live PID nothing can classify: once the arming session dies its watcher polls
@@ -0,0 +1,31 @@
1
+ #!/usr/bin/env bash
2
+
3
+ # Records the work a watch has seen due on its PR — a rebase or red CI — so the
4
+ # owning session's turn-end gate can tell an event it acted on from one it sat
5
+ # on. Sourced by pr-watch-arm.sh and pr-watch-loop.sh.
6
+ #
7
+ # The gate runs in a Stop hook with about a second to answer and no network, so
8
+ # it cannot ask the provider what is due; it reads this file and the slot's
9
+ # attempt counters instead. A session once held a stale branch and a red head
10
+ # for a day by re-arming its watch, whose drain floored both as "handled", and
11
+ # answering every wake with a question. Nothing on disk said the work was due,
12
+ # so nothing could notice. This file is that record.
13
+ #
14
+ # Rewritten whole each time what is due changes; left empty when nothing is, so
15
+ # the gate's shell pre-filter reads an empty file as nothing owed.
16
+
17
+ MUGGLE_PR_WATCH_DUE_FILE="watch-due.env"
18
+
19
+ # Writes <slot>/watch-due.env: the head the observation was made on, the
20
+ # `<head>..<base-tip>` key of a rebase found due (empty when the branch is
21
+ # current), and the head whose checks settled red (empty otherwise). Builtins
22
+ # only, since the loop writes it every time what is due changes.
23
+ watch_record_due_work() {
24
+ local slot="$1" head_sha="$2" rebase_due_key="$3" ci_red_head="$4"
25
+ if [ -z "$rebase_due_key" ] && [ -z "$ci_red_head" ]; then
26
+ : > "${slot}/${MUGGLE_PR_WATCH_DUE_FILE}"
27
+ return 0
28
+ fi
29
+ printf 'HEAD="%s"\nREBASE_DUE="%s"\nCI_RED_HEAD="%s"\n' "$head_sha" "$rebase_due_key" "$ci_red_head" \
30
+ > "${slot}/${MUGGLE_PR_WATCH_DUE_FILE}"
31
+ }
@@ -71,9 +71,16 @@ watch_wake_thread() {
71
71
  echo "EVENT pr=$pr thread newly unresolved id=$thread_id"
72
72
  }
73
73
 
74
- # The head's checks having **settled** red: nothing still pending and at least
75
- # one failure. Pending-with-a-failure is not a wake — a run in flight may still
76
- # go green, and the tick would idle on it anyway.
74
+ # True when the head's checks have **settled** red: nothing still pending and at
75
+ # least one failure. Pending-with-a-failure is not red yet — a run in flight may
76
+ # still go green, and the tick would idle on it anyway.
77
+ watch_checks_settled_red() {
78
+ local pending_count="$1" failed_count="$2"
79
+ [ "${pending_count:-0}" -eq 0 ] 2>/dev/null || return 1
80
+ [ "${failed_count:-0}" -gt 0 ] 2>/dev/null
81
+ }
82
+
83
+ # The head's checks having settled red (watch_checks_settled_red).
77
84
  #
78
85
  # The floor is the head SHA rather than a monotonic id because a check rollup is
79
86
  # not monotonic: it flips green to red and resets on every push. Keying on the
@@ -82,11 +89,18 @@ watch_wake_ci_red() {
82
89
  local pr="$1" pending_count="$2" failed_count="$3" head_sha="$4" floor="$5"
83
90
  [ -n "$head_sha" ] || return 1
84
91
  [ "$head_sha" != "$floor" ] || return 1
85
- [ "${pending_count:-0}" -eq 0 ] 2>/dev/null || return 1
86
- [ "${failed_count:-0}" -gt 0 ] 2>/dev/null || return 1
92
+ watch_checks_settled_red "$pending_count" "$failed_count" || return 1
87
93
  echo "EVENT pr=$pr checks settled red head=$head_sha"
88
94
  }
89
95
 
96
+ # True when the branch needs a rebase onto its base: conflicting with it, or
97
+ # behind it by a measured, positive count. An unreadable count is not behind.
98
+ watch_branch_needs_rebase() {
99
+ local mergeable="$1" behind_count="$2"
100
+ [ "$mergeable" = "CONFLICTING" ] && return 0
101
+ [ -n "$behind_count" ] && [ "$behind_count" -gt 0 ] 2>/dev/null
102
+ }
103
+
90
104
  # The branch needing a rebase onto its base — conflicting with it, or merely
91
105
  # behind it.
92
106
  #
@@ -106,11 +120,11 @@ watch_wake_rebase() {
106
120
  local pr="$1" mergeable="$2" behind_count="$3" rebase_key="$4" floor="$5"
107
121
  [ -n "$rebase_key" ] || return 1
108
122
  [ "$rebase_key" != "$floor" ] || return 1
123
+ watch_branch_needs_rebase "$mergeable" "$behind_count" || return 1
109
124
  if [ "$mergeable" = "CONFLICTING" ]; then
110
125
  echo "EVENT pr=$pr branch conflicting with base key=$rebase_key"
111
126
  return 0
112
127
  fi
113
- [ -n "$behind_count" ] && [ "$behind_count" -gt 0 ] 2>/dev/null || return 1
114
128
  echo "EVENT pr=$pr branch behind base by $behind_count — rebase due key=$rebase_key"
115
129
  }
116
130