claude-code-session-manager 0.125.1 → 0.127.0

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 (97) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/bin/cli.cjs +71 -9
  3. package/bin/supervise.cjs +84 -0
  4. package/dist/assets/{AgentLibrary-DjEH5SoY.js → AgentLibrary-DKQznr7o.js} +1 -1
  5. package/dist/assets/{Button-B8NLivk-.js → Button-CZXqmIiM.js} +1 -1
  6. package/dist/assets/{DataModel-CHiBk8m_.js → DataModel-piyV33To.js} +1 -1
  7. package/dist/assets/{History-DttgrJO0.js → History-BxwtrKF2.js} +1 -1
  8. package/dist/assets/{Hooks-Bvy0BH1u.js → Hooks-DogeSPII.js} +1 -1
  9. package/dist/assets/{Library-UbBOgkkP.js → Library-BDt6EeQQ.js} +1 -1
  10. package/dist/assets/{ListDetail-xOyOpVZX.js → ListDetail-CwS-LKar.js} +1 -1
  11. package/dist/assets/{McpServers-CoGL0ddv.js → McpServers-D2HVljgS.js} +1 -1
  12. package/dist/assets/{Memory-Cise856d.js → Memory-hNzuOGn8.js} +1 -1
  13. package/dist/assets/{Panel-Cj72VO5s.js → Panel-BLDrsUeq.js} +1 -1
  14. package/dist/assets/{Permissions-BoJ9AB-G.js → Permissions-DzZ5vaJW.js} +1 -1
  15. package/dist/assets/{Plugins-DfT24sAZ.js → Plugins-Cz9yaxzG.js} +2 -2
  16. package/dist/assets/{ProvenanceBadge-ChkIslT4.js → ProvenanceBadge-CCgLO4m9.js} +1 -1
  17. package/dist/assets/{SaveBar-RCXr0jey.js → SaveBar-Shmn699J.js} +1 -1
  18. package/dist/assets/{Scheduler-B70tknnx.js → Scheduler-Bqr0WHNd.js} +1 -1
  19. package/dist/assets/{ScopeSwitcher-p_tgO5Sa.js → ScopeSwitcher-CBx1fB5g.js} +1 -1
  20. package/dist/assets/{Settings-wHiAxTfI.js → Settings-Ci8in-yF.js} +1 -1
  21. package/dist/assets/{SkillReferenceGraph-D_Pt35vb.js → SkillReferenceGraph-BWwljba8.js} +1 -1
  22. package/dist/assets/{Skills-DUvOrgw9.js → Skills-BON6o-c4.js} +1 -1
  23. package/dist/assets/{SystemPrompt-BrNIdy68.js → SystemPrompt-D5epIYYs.js} +1 -1
  24. package/dist/assets/{TagLibrary-CDRatxXG.js → TagLibrary-C2qDZROJ.js} +1 -1
  25. package/dist/assets/{TiptapBody-BF8PxUDj.js → TiptapBody-SZhI3-bW.js} +1 -1
  26. package/dist/assets/{Toggle-CQH8NGXW.js → Toggle-C_qFDG0g.js} +1 -1
  27. package/dist/assets/{ViewTabs-DwnxqCVs.js → ViewTabs-C9q5WCEd.js} +1 -1
  28. package/dist/assets/{historyTotals-KINLTHQ4.js → historyTotals-BCl7IOhY.js} +1 -1
  29. package/dist/assets/{index-CfR3NU2t.js → index-CMIYLbPb.js} +581 -581
  30. package/dist/assets/{settingsSchema-BUcHqLnt.js → settingsSchema-BBrRBrBr.js} +1 -1
  31. package/dist/assets/{skillFrontmatter-BwwkyuMD.js → skillFrontmatter-B01qJk6N.js} +1 -1
  32. package/dist/assets/{useAgentsDirWatch-Coem9Wg-.js → useAgentsDirWatch-CuR3GSjS.js} +1 -1
  33. package/dist/index.html +1 -1
  34. package/dist-web/{assets/app.js → app.js} +351 -351
  35. package/dist-web/index.html +2 -2
  36. package/package.json +2 -2
  37. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  38. package/plugins/session-manager-dev/skills/develop/SKILL.md +3 -2
  39. package/plugins/session-manager-dev/skills/send-feedback/SKILL.md +10 -2
  40. package/scripts/scheduler-mcp-server.cjs +56 -5
  41. package/src/main/build-info.json +4 -4
  42. package/src/main/chatRunner.cjs +73 -6
  43. package/src/main/crashDiagnostics.cjs +83 -8
  44. package/src/main/health.cjs +16 -5
  45. package/src/main/index.cjs +32 -0
  46. package/src/main/lib/chatBootRecovery.cjs +136 -0
  47. package/src/main/lib/chatInflight.cjs +88 -0
  48. package/src/main/lib/epic/epicDelegationStats.cjs +1 -0
  49. package/src/main/lib/epic/epicMint.cjs +6 -0
  50. package/src/main/lib/epic/epicSweepValidator.cjs +60 -6
  51. package/src/main/lib/epic/epicValidationHook.cjs +14 -2
  52. package/src/main/lib/epic/epicWorktreeMerge.cjs +9 -1
  53. package/src/main/lib/feedback-remote/autoStartedSession.cjs +102 -0
  54. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +130 -15
  55. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +71 -15
  56. package/src/main/lib/feedback-remote/remoteAssets.cjs +25 -1
  57. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +13 -2
  58. package/src/main/lib/git/gitExec.cjs +11 -1
  59. package/src/main/lib/git/gitWorktree.cjs +255 -9
  60. package/src/main/lib/git/jobWorktree.cjs +5 -0
  61. package/src/main/lib/mcpToolCatalog.cjs +27 -5
  62. package/src/main/lib/persona-macro/builtinMacros.cjs +12 -1
  63. package/src/main/lib/persona-macro/macroLibrary.cjs +78 -3
  64. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +11 -0
  65. package/src/main/lib/prd/prdCreate.cjs +5 -1
  66. package/src/main/lib/prd/prdDeclaredPaths.cjs +29 -2
  67. package/src/main/lib/process/childWithLog.cjs +38 -95
  68. package/src/main/lib/process/memoryScope.cjs +140 -0
  69. package/src/main/lib/process/ozonePlatform.cjs +15 -0
  70. package/src/main/lib/process/procIdentity.cjs +10 -3
  71. package/src/main/lib/process/scopeOomPolicy.cjs +69 -0
  72. package/src/main/lib/promptSessionSchema.cjs +6 -1
  73. package/src/main/lib/scheduler/cpuSample.cjs +147 -0
  74. package/src/main/lib/scheduler/definitionOfDone.cjs +40 -0
  75. package/src/main/lib/scheduler/jobLeftovers.cjs +204 -0
  76. package/src/main/lib/scheduler/jobSupervisorRecord.cjs +2 -1
  77. package/src/main/lib/scheduler/landedSinceRun.cjs +13 -5
  78. package/src/main/lib/scheduler/loadGate.cjs +116 -45
  79. package/src/main/lib/scheduler/queueStore.cjs +5 -2
  80. package/src/main/lib/scheduler/rcaReport.cjs +1 -0
  81. package/src/main/lib/scheduler/reviewNotice.cjs +1 -0
  82. package/src/main/lib/scheduler/schedulerBatch.cjs +10 -3
  83. package/src/main/lib/scheduler/schedulerConfig.cjs +7 -2
  84. package/src/main/lib/telemetry/crashTelemetry.cjs +8 -4
  85. package/src/main/runVerify.cjs +59 -110
  86. package/src/main/scheduler/budget.cjs +31 -0
  87. package/src/main/scheduler/gitTreeGuard.cjs +51 -1
  88. package/src/main/scheduler/prdPaths.cjs +54 -0
  89. package/src/main/scheduler/reviewLadder.cjs +28 -5
  90. package/src/main/scheduler/starvation.cjs +22 -0
  91. package/src/main/scheduler.cjs +662 -90
  92. package/src/main/templates/PRD_AUTHORING.md +10 -3
  93. package/src/main/usage.cjs +4 -2
  94. package/src/main/webRemote.cjs +3 -0
  95. package/src/preload/api.d.ts +19 -3
  96. package/src/seed/agents/demo-video-builder.md +62 -14
  97. /package/dist-web/{assets/app.css → app.css} +0 -0
@@ -29,6 +29,7 @@ const { createProjectFolder } = require('./lib/projectFolder.cjs');
29
29
  const { cleanChildEnv } = require('./lib/process/cleanEnv.cjs');
30
30
  const { applyLoginShellPath } = require('./lib/process/loginShellPath.cjs');
31
31
  const { terminateLosingInstance } = require('./lib/process/singleInstanceGuard.cjs');
32
+ const { ensureScopeOomPolicy } = require('./lib/process/scopeOomPolicy.cjs');
32
33
  const { acquireSchedulerOwnership, releaseSchedulerOwnership } = require('./lib/process/instanceLock.cjs');
33
34
  const { manager: ptyManager, registerPtyHandlers } = require('./pty.cjs');
34
35
  const configMgr = require('./config.cjs');
@@ -1086,6 +1087,29 @@ try {
1086
1087
  logs.writeLine({ scope: 'main', level: 'error', message: 'ops retention IPC registration failed', meta: { error: e?.message } });
1087
1088
  }
1088
1089
  chatRunner.registerChatHandlers();
1090
+ // Boot recovery of chat turns that were in flight when the app last died (once, after handlers).
1091
+ try {
1092
+ const chatInflight = require('./lib/chatInflight.cjs');
1093
+ const { identity } = require('./lib/process/procIdentity.cjs');
1094
+ require('./lib/chatBootRecovery.cjs').recoverInflightTurns({
1095
+ ledger: chatInflight,
1096
+ run: (o) => chatRunner.run(o),
1097
+ holdOrphan: chatRunner.holdOrphanSession,
1098
+ releaseOrphan: chatRunner.releaseOrphanSession,
1099
+ identityOf: identity,
1100
+ sessionTurnState: async (entry) => {
1101
+ try {
1102
+ const { resolveEpicTranscriptPath } = require('./lib/epic/epicTranscriptPath.cjs');
1103
+ const { readTranscriptTail } = require('./lib/epic/epicDelegationStats.cjs');
1104
+ const filePath = resolveEpicTranscriptPath({ cwd: entry.cwd, claudeSessionId: entry.sessionId }).path;
1105
+ if (!filePath) return 'missing';
1106
+ return require('./lib/chatBootRecovery.cjs').classifyTurnTail(readTranscriptTail(filePath));
1107
+ } catch { return 'missing'; }
1108
+ },
1109
+ }).catch((e) => logs.writeLine({ scope: 'main', level: 'error', message: 'chat boot recovery failed', meta: { error: e?.message } }));
1110
+ } catch (e) {
1111
+ logs.writeLine({ scope: 'main', level: 'error', message: 'chat boot recovery wiring failed', meta: { error: e?.message } });
1112
+ }
1089
1113
 
1090
1114
  // Direct in-process PRD authoring for a queued PromptTicket classified
1091
1115
  // 'develop' (PRD 749 follow-up) — calls the same createPrd() the admin HTTP
@@ -1223,6 +1247,7 @@ app.on('web-contents-created', (_e, wc) => {
1223
1247
  app.whenReady().then(async () => {
1224
1248
  logs.pruneOld();
1225
1249
  logs.writeLine({ scope: 'main', level: 'info', message: 'app start', meta: { version: app.getVersion(), platform: process.platform } });
1250
+ logs.writeLine({ scope: 'main', level: 'info', message: 'ozone platform', meta: { ozonePlatform: app.commandLine.getSwitchValue('ozone-platform') || 'default', override: process.env.SM_OZONE_PLATFORM || null } });
1226
1251
 
1227
1252
  // Crash/OOM diagnostics: logs a postmortem if the PREVIOUS run died
1228
1253
  // uncleanly (the silent OOM-kill we've been chasing), then starts the memory
@@ -1456,6 +1481,13 @@ app.whenReady().then(async () => {
1456
1481
  // owner's running job and overwrote admin-api.json. Losing instances run
1457
1482
  // scheduler-PASSIVE: read IPC still works (handlers registered above),
1458
1483
  // nothing mutates.
1484
+ // Child OOM-kill must not stop the whole app scope (OOMPolicy=continue drop-in).
1485
+ try {
1486
+ const oom = ensureScopeOomPolicy({ log: (m) => logs.writeLine({ scope: 'main', level: 'warn', message: m }) });
1487
+ logs.writeLine({ scope: 'main', level: 'info', message: 'scope OOM policy', meta: oom });
1488
+ } catch (e) {
1489
+ logs.writeLine({ scope: 'main', level: 'warn', message: 'scope OOM policy failed', meta: { error: e?.message } });
1490
+ }
1459
1491
  const ownership = acquireSchedulerOwnership();
1460
1492
  if (ownership.owner) {
1461
1493
  scheduler.init().catch((e) => {
@@ -0,0 +1,136 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Boot recovery for chat turns that were in flight when the app died
5
+ * (ledger: lib/chatInflight.cjs). Per ledger entry:
6
+ * - pid alive AND it is an sm-claude-chat process for that sessionId → orphan: hold the
7
+ * session in chatRunner so run() queues instead of spawning a second writer, poll until
8
+ * it exits, then treat it as dead;
9
+ * - dead (or recycled pid) → Claude's own session JSONL decides (classifyTurnTail): finished or
10
+ * missing, or a silent entry → just clear the entry; unfinished → re-run ONCE through
11
+ * chatRunner.run() with the same sessionId and a fixed continue prompt, at most once per
12
+ * session per 24 h.
13
+ * Touches only the session's own turn: never mints an Epic or edits its title/objective/status.
14
+ */
15
+
16
+ const DAY_MS = 24 * 60 * 60 * 1000;
17
+ const ORPHAN_POLL_MS = 5000;
18
+
19
+ const CONTINUE_PROMPT = 'The Session Manager app restarted while your previous turn was running. '
20
+ + 'Check what already landed (files, git status, commits, tool results) before repeating any step, '
21
+ + 'then continue the interrupted work from where it stopped.';
22
+
23
+ function defaultPidAlive(pid) {
24
+ if (!Number.isInteger(pid) || pid <= 0) return false;
25
+ try { process.kill(pid, 0); return true; } catch (e) { return !!(e && e.code === 'EPERM'); }
26
+ }
27
+
28
+ function isChatProcessFor(identity, sessionId) {
29
+ const cmd = identity && typeof identity.cmdline === 'string' ? identity.cmdline : '';
30
+ return cmd.includes('sm-claude-chat') && cmd.includes(sessionId);
31
+ }
32
+
33
+ /**
34
+ * Classify the tail of a Claude session JSONL.
35
+ * @param {string} text
36
+ * @returns {'finished'|'unfinished'|'missing'}
37
+ */
38
+ function classifyTurnTail(text) {
39
+ if (typeof text !== 'string' || !text) return 'missing';
40
+ const lines = text.split('\n');
41
+ for (let i = lines.length - 1; i >= 0; i--) {
42
+ const t = lines[i].trim();
43
+ if (!t) continue;
44
+ let obj;
45
+ try { obj = JSON.parse(t); } catch { continue; }
46
+ if (!obj || typeof obj !== 'object') continue;
47
+ if (obj.type === 'user') return 'unfinished';
48
+ if (obj.type === 'assistant') {
49
+ const sr = obj.message && obj.message.stop_reason;
50
+ return sr != null && sr !== 'tool_use' ? 'finished' : 'unfinished';
51
+ }
52
+ }
53
+ return 'missing';
54
+ }
55
+
56
+ /**
57
+ * @param {object} deps
58
+ * ledger {list,end,markRecovered,recoveredMap}, run(opts), holdOrphan(sid), releaseOrphan(sid),
59
+ * pidAlive(pid), identityOf(pid), sessionTurnState(entry) → 'finished'|'unfinished'|'missing',
60
+ * now(), pollMs, setTimer/clearTimer (tests)
61
+ * @returns {Promise<{ pending: Promise<void>, results: object[] }>} resolves after the first pass;
62
+ * `pending` settles once every orphan has exited and been handled.
63
+ */
64
+ async function recoverInflightTurns(deps) {
65
+ const {
66
+ ledger, run, holdOrphan = () => {}, releaseOrphan = () => {},
67
+ pidAlive = defaultPidAlive, identityOf = () => null,
68
+ sessionTurnState = async () => 'missing',
69
+ now = Date.now, pollMs = ORPHAN_POLL_MS,
70
+ setTimer = setTimeout,
71
+ } = deps;
72
+ const results = [];
73
+ const waits = [];
74
+ let entries = [];
75
+ try { entries = await ledger.list(); } catch { entries = []; }
76
+
77
+ async function settleDead(entry) {
78
+ const { sessionId, tabId, cwd } = entry;
79
+ let state = 'missing';
80
+ if (!entry.silent) {
81
+ try { state = await sessionTurnState(entry); } catch { state = 'missing'; }
82
+ }
83
+ if (entry.silent || state !== 'unfinished') {
84
+ await ledger.end(sessionId);
85
+ return { sessionId, outcome: 'finished' };
86
+ }
87
+ let recovered = {};
88
+ try { recovered = await ledger.recoveredMap(); } catch { recovered = {}; }
89
+ const prev = Number(recovered[sessionId]);
90
+ if (Number.isFinite(prev) && now() - prev < DAY_MS) {
91
+ await ledger.end(sessionId);
92
+ return { sessionId, outcome: 'guarded' };
93
+ }
94
+ await ledger.markRecovered(sessionId, now());
95
+ await ledger.end(sessionId);
96
+ run({
97
+ tabId, sessionId, cwd, prompt: CONTINUE_PROMPT, resume: true,
98
+ ...(entry.promptId ? { promptId: entry.promptId } : {}),
99
+ ...(entry.origin ? { origin: entry.origin } : {}),
100
+ ...(entry.worktreeDirHint ? { worktreeDirHint: entry.worktreeDirHint } : {}),
101
+ });
102
+ return { sessionId, outcome: 'rerun' };
103
+ }
104
+
105
+ function isOrphan(entry) {
106
+ if (!pidAlive(entry.pid)) return false;
107
+ try { return isChatProcessFor(identityOf(entry.pid), entry.sessionId); } catch { return false; }
108
+ }
109
+
110
+ for (const entry of entries) {
111
+ if (!entry || !entry.sessionId) continue;
112
+ if (isOrphan(entry)) {
113
+ holdOrphan(entry.sessionId);
114
+ waits.push(new Promise((resolve) => {
115
+ const tick = () => {
116
+ if (isOrphan(entry)) {
117
+ const t = setTimer(tick, pollMs);
118
+ if (t && typeof t.unref === 'function') t.unref();
119
+ return;
120
+ }
121
+ settleDead(entry)
122
+ .catch(() => ({ sessionId: entry.sessionId, outcome: 'error' }))
123
+ .then((r) => { results.push(r); releaseOrphan(entry.sessionId); resolve(); });
124
+ };
125
+ const t = setTimer(tick, pollMs);
126
+ if (t && typeof t.unref === 'function') t.unref();
127
+ }));
128
+ results.push({ sessionId: entry.sessionId, outcome: 'orphan' });
129
+ continue;
130
+ }
131
+ try { results.push(await settleDead(entry)); } catch { results.push({ sessionId: entry.sessionId, outcome: 'error' }); }
132
+ }
133
+ return { results, pending: Promise.all(waits).then(() => undefined) };
134
+ }
135
+
136
+ module.exports = { recoverInflightTurns, classifyTurnTail, CONTINUE_PROMPT, DAY_MS };
@@ -0,0 +1,88 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Durable ledger of in-flight chat turns (~/.claude/session-manager/chat-inflight.json).
5
+ * begin() after a successful spawn, end() when the turn settles; list() lets the next
6
+ * boot see what was running. Carries NO prompt text and nothing from childEnv.
7
+ * Never throws into a turn: a missing/corrupt ledger reads as empty.
8
+ */
9
+
10
+ const path = require('node:path');
11
+ const { readJsonOr, writeJsonAtomic } = require('./util/atomicFs.cjs');
12
+ const { schedulerHome } = require('./scheduler/schedulerPaths.cjs');
13
+
14
+ function ledgerPath() {
15
+ return process.env.SM_CHAT_INFLIGHT_PATH || path.join(schedulerHome(), 'chat-inflight.json');
16
+ }
17
+
18
+ // One in-process chain serializes every read-modify-write.
19
+ let chain = Promise.resolve();
20
+
21
+ async function readAll() {
22
+ try {
23
+ const data = await readJsonOr(ledgerPath(), {});
24
+ return data && typeof data === 'object' && !Array.isArray(data) ? data : {};
25
+ } catch { return {}; }
26
+ }
27
+
28
+ function enqueue(mutate) {
29
+ const next = chain.then(async () => {
30
+ try {
31
+ const all = await readAll();
32
+ mutate(all);
33
+ await writeJsonAtomic(ledgerPath(), all);
34
+ } catch { /* ledger is best-effort */ }
35
+ });
36
+ chain = next;
37
+ return next;
38
+ }
39
+
40
+ /** Fields of a run() payload that may be persisted (never prompt / env). */
41
+ function sanitize(sessionId, entry) {
42
+ const e = entry || {};
43
+ const out = { sessionId, startedAt: Date.now() };
44
+ for (const k of ['tabId', 'cwd', 'pid', 'startedAt', 'resume', 'silent', 'promptId', 'origin', 'worktreeDirHint']) {
45
+ if (e[k] !== undefined && typeof e[k] !== 'function') out[k] = e[k];
46
+ }
47
+ out.sessionId = sessionId;
48
+ return out;
49
+ }
50
+
51
+ function begin(sessionId, entry) {
52
+ if (!sessionId) return Promise.resolve();
53
+ return enqueue((all) => { all[sessionId] = sanitize(sessionId, entry); });
54
+ }
55
+
56
+ function end(sessionId) {
57
+ if (!sessionId) return Promise.resolve();
58
+ return enqueue((all) => { delete all[sessionId]; });
59
+ }
60
+
61
+ const RECOVERED_KEY = '__recovered';
62
+
63
+ /** @returns {Promise<object[]>} */
64
+ async function list() {
65
+ await chain;
66
+ const all = await readAll();
67
+ return Object.entries(all).filter(([k]) => k !== RECOVERED_KEY).map(([, v]) => v);
68
+ }
69
+
70
+ /** Stamp a session as boot-recovered now (separate key, survives begin/end). */
71
+ function markRecovered(sessionId, at = Date.now()) {
72
+ if (!sessionId) return Promise.resolve();
73
+ return enqueue((all) => {
74
+ const m = all[RECOVERED_KEY] && typeof all[RECOVERED_KEY] === 'object' ? all[RECOVERED_KEY] : {};
75
+ for (const [k, v] of Object.entries(m)) if (at - Number(v) > 7 * 86400000) delete m[k];
76
+ m[sessionId] = at;
77
+ all[RECOVERED_KEY] = m;
78
+ });
79
+ }
80
+
81
+ /** @returns {Promise<Record<string, number>>} sessionId → last recovery ms */
82
+ async function recoveredMap() {
83
+ await chain;
84
+ const m = (await readAll())[RECOVERED_KEY];
85
+ return m && typeof m === 'object' ? m : {};
86
+ }
87
+
88
+ module.exports = { begin, end, list, ledgerPath, markRecovered, recoveredMap };
@@ -123,4 +123,5 @@ module.exports = {
123
123
  countPrdsQueued,
124
124
  countInlineEdits,
125
125
  isApplicationSourcePath,
126
+ readTranscriptTail,
126
127
  };
@@ -69,6 +69,12 @@ const MINT_AUTHORITY_NEW_EPIC_UI = 'new-epic-ui';
69
69
  // that is all it may do. The removed channel let an agent file work into the
70
70
  // project it was already running in, which is what /develop-inside-your-own-
71
71
  // Epic replaced and which stays refused.
72
+ //
73
+ // Two grounds can stamp source.autoApprove on a cross-project Epic (it is
74
+ // still minted 'proposed'; the receiving renderer approves it): a verified
75
+ // human request quote, or a MACRO ground — the sender Epic was launched by a
76
+ // human pressing a macro whose autoStartTargets names the target project
77
+ // (bug/feature only, capped per sender Epic). Anything else stays a proposal.
72
78
  const MINT_AUTHORITY_CROSS_PROJECT_FEEDBACK = 'cross-project-feedback';
73
79
 
74
80
  const MINT_AUTHORITIES = Object.freeze([
@@ -6,12 +6,38 @@
6
6
  * checks the completed PRDs of a settled Epic that no validator has checked.
7
7
  * Pure: no fs, no child_process. The caller decides when a sweep is needed and
8
8
  * whether to create the PRD.
9
+ *
10
+ * Sizing: the sweep's kill budget must cover every gate running to its own
11
+ * timeout plus reading/writing time, because a kill loses every minute of
12
+ * evidence. Why these numbers: across 916 real validator runs the most
13
+ * non-gate time was 13.7 minutes, hence VALIDATOR_OVERHEAD_MS = 15 minutes;
14
+ * UNKNOWN_GATE_MS matches definitionOfDone's DEFAULT_GATE_TIMEOUT_MS; the plain
15
+ * sum with no dedupe follows the validator's rule to re-run every command in
16
+ * each PRD's gate. Real runs sit far under their timeouts (median 7%), so about
17
+ * 2.3% of sweeps (3 of 130) will split that strictly did not need it. An extra
18
+ * validator costs far less than a lost run, so that is accepted.
9
19
  */
10
20
 
11
21
  const { bareSlug } = require('../prd/depSlugResolve.cjs');
22
+ const { JOB_BUDGET_FACTOR, JOB_BUDGET_CEILING_MS } = require('../scheduler/schedulerConfig.cjs');
12
23
 
13
24
  const SWEEP_SLUG_PREFIX = 'validate-sweep';
14
25
  const MAX_SWEEP_PRDS = 25;
26
+ const VALIDATOR_OVERHEAD_MS = 15 * 60_000;
27
+ const UNKNOWN_GATE_MS = 5 * 60_000;
28
+ const MIN_VALIDATOR_ESTIMATE_MINUTES = 10;
29
+
30
+ /** A value that is not a finite number >= 0 counts UNKNOWN_GATE_MS; 0 stays 0. */
31
+ function gateMsOrUnknown(v) {
32
+ return typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : UNKNOWN_GATE_MS;
33
+ }
34
+
35
+ /** max(10, ceil((sum + overhead) / 60000 / factor)). */
36
+ function validatorEstimateMinutes(gateMsValues, { factor } = {}) {
37
+ const f = typeof factor === 'number' && factor > 0 ? factor : JOB_BUDGET_FACTOR;
38
+ const sum = (Array.isArray(gateMsValues) ? gateMsValues : []).reduce((a, v) => a + gateMsOrUnknown(v), 0);
39
+ return Math.max(MIN_VALIDATOR_ESTIMATE_MINUTES, Math.ceil((sum + VALIDATOR_OVERHEAD_MS) / 60_000 / f));
40
+ }
15
41
 
16
42
  const PERSONA_LINE = 'Work as the validator persona — the procedure is your system prompt.';
17
43
 
@@ -27,14 +53,31 @@ function isSweepValidatorSlug(slug) {
27
53
  * baseSha?: string | null, now: number | Date | string }} args
28
54
  * @returns {{ input: object | null, carried: Array<object> }}
29
55
  */
30
- function buildSweepValidatorInput({ epicId, cwd, uncovered, baseSha, now }) {
56
+ function buildSweepValidatorInput({ epicId, cwd, uncovered, baseSha, now, jobBudget }) {
31
57
  if (!Array.isArray(uncovered) || uncovered.length === 0) return { input: null, carried: [] };
32
58
 
33
- const covered = uncovered.slice(0, MAX_SWEEP_PRDS);
34
- const carried = uncovered.slice(MAX_SWEEP_PRDS);
59
+ const factor = jobBudget && typeof jobBudget.factor === 'number' && jobBudget.factor > 0
60
+ ? jobBudget.factor : JOB_BUDGET_FACTOR;
61
+ const ceilingMs = jobBudget && typeof jobBudget.ceilingMs === 'number' && jobBudget.ceilingMs > 0
62
+ ? jobBudget.ceilingMs : JOB_BUDGET_CEILING_MS;
63
+
64
+ // First-fit in input order; the first entry always joins.
65
+ const covered = [];
66
+ const carried = [];
67
+ let workMs = VALIDATOR_OVERHEAD_MS;
68
+ for (const entry of uncovered) {
69
+ const g = gateMsOrUnknown(entry && entry.gateMs);
70
+ if (covered.length === 0 || (covered.length < MAX_SWEEP_PRDS && workMs + g <= ceilingMs)) {
71
+ covered.push(entry);
72
+ workMs += g;
73
+ } else {
74
+ carried.push(entry);
75
+ }
76
+ }
77
+ const budgetExempt = covered.length === 1 && workMs > ceilingMs;
35
78
  const names = covered.map((entry) => entry.bareSlug || bareSlug(entry.slug));
36
79
 
37
- const stamp = new Date(now).toISOString().replace(/\D/g, '').slice(0, 12);
80
+ const stamp = new Date(now).toISOString().replace(/\D/g, '').slice(0, 14);
38
81
  const slug = `${SWEEP_SLUG_PREFIX}-${stamp}`;
39
82
  const recordPath = `session-manager-operations/reviews/validation/${epicId}/${slug}.md`;
40
83
 
@@ -60,7 +103,7 @@ function buildSweepValidatorInput({ epicId, cwd, uncovered, baseSha, now }) {
60
103
  outOfScope: ['Editing product code', 'Queuing fix PRDs'],
61
104
  gate: ['none'],
62
105
  files: [recordPath],
63
- estimateMinutes: 10,
106
+ estimateMinutes: validatorEstimateMinutes(covered.map((e) => e.gateMs), { factor }),
64
107
  agentType: 'validator',
65
108
  tag: 'build',
66
109
  sourcePromptId: epicId,
@@ -68,7 +111,18 @@ function buildSweepValidatorInput({ epicId, cwd, uncovered, baseSha, now }) {
68
111
  dependsOn: names,
69
112
  };
70
113
 
114
+ if (budgetExempt) input.budgetExempt = true;
115
+
71
116
  return { input, carried };
72
117
  }
73
118
 
74
- module.exports = { SWEEP_SLUG_PREFIX, MAX_SWEEP_PRDS, isSweepValidatorSlug, buildSweepValidatorInput };
119
+ module.exports = {
120
+ SWEEP_SLUG_PREFIX,
121
+ MAX_SWEEP_PRDS,
122
+ VALIDATOR_OVERHEAD_MS,
123
+ UNKNOWN_GATE_MS,
124
+ MIN_VALIDATOR_ESTIMATE_MINUTES,
125
+ isSweepValidatorSlug,
126
+ validatorEstimateMinutes,
127
+ buildSweepValidatorInput,
128
+ };
@@ -11,6 +11,8 @@
11
11
  * Kill-switch: SM_EPIC_VALIDATION_DISABLE=1 turns the whole runner off.
12
12
  * SM_EPIC_SETTLE_SECONDS sets the debounce before a settle run (default 120).
13
13
  *
14
+ * A sweep covers what fits one budget; the rest go to the next settle.
15
+ *
14
16
  * This module spawns NO process itself: the sweep validator is a PRD queued
15
17
  * through the scheduler (which acquires a lib/scheduler/sessionSlots.cjs slot),
16
18
  * and the digest goes through the chat queue's pump, which does the same.
@@ -108,6 +110,8 @@ async function runEpicSettle({ cwd, epicId } = {}, deps = {}) {
108
110
  loadHistory = async () => [],
109
111
  createPrd,
110
112
  resolveBaseSha = async () => null,
113
+ readGateMs = async () => new Map(),
114
+ jobBudget,
111
115
  sendPrompt,
112
116
  appendResponseEvent,
113
117
  now = Date.now,
@@ -158,14 +162,22 @@ async function runEpicSettle({ cwd, epicId } = {}, deps = {}) {
158
162
  }
159
163
  let baseSha = null;
160
164
  try { baseSha = earliest ? await resolveBaseSha(cwd, earliest.landedCommit) : null; } catch { baseSha = null; }
161
- const { input } = buildSweepValidatorInput({ epicId, cwd, uncovered: candidates, baseSha, now: now() });
165
+ let gateMap = new Map();
166
+ try {
167
+ const m = await readGateMs(cwd, epicId, candidates.map((c) => c.slug));
168
+ if (m instanceof Map) gateMap = m;
169
+ } catch (e) {
170
+ try { (log || console).error('[epicValidationHook] readGateMs failed', epicId, e); } catch { /* noop */ }
171
+ }
172
+ const sized = candidates.map((c) => ({ ...c, gateMs: gateMap.get(c.slug) }));
173
+ const { input, carried } = buildSweepValidatorInput({ epicId, cwd, uncovered: sized, baseSha, now: now(), jobBudget });
162
174
  let res;
163
175
  try {
164
176
  res = await createPrd(input);
165
177
  } catch (e) {
166
178
  res = { ok: false, error: e && e.message ? e.message : String(e) };
167
179
  }
168
- if (res && res.ok) return { action: 'sweep-queued', slug: input.slug };
180
+ if (res && res.ok) return { action: 'sweep-queued', slug: input.slug, carried: carried.length };
169
181
  notValidatedReason = `the validator persona could not be queued: ${(res && res.error) || 'unknown error'}`;
170
182
  } else {
171
183
  notValidatedReason = 'a sweep validator already ran and did not check them';
@@ -25,7 +25,7 @@
25
25
  * them from the command line.
26
26
  */
27
27
 
28
- const { integrateEpicBranch, cleanupEpicWorktree } = require('../git/gitWorktree.cjs');
28
+ const { integrateEpicBranch, cleanupEpicWorktree, reconcileWorktreeHead } = require('../git/gitWorktree.cjs');
29
29
  const { validatePath } = require('../../config.cjs');
30
30
 
31
31
  /**
@@ -40,6 +40,14 @@ const { validatePath } = require('../../config.cjs');
40
40
  */
41
41
  async function mergeEpicToMainViaIpc(cwd, epicId, branch, dir, carriedPaths) {
42
42
  validatePath(cwd);
43
+ if (dir) {
44
+ const rec = await reconcileWorktreeHead({ cwd, dir, branch, key: epicId });
45
+ if (rec && rec.action === 'diverged') {
46
+ const reason = `worktree HEAD ${rec.finalHead} is not on ${branch}; commit pinned at ${rec.pinnedRef || 'no ref'} — resolve manually`;
47
+ console.log(`[epicWorktreeMerge] ${epicId}: needs manual resolution (${reason})`);
48
+ return { ok: false, status: 'needs_merge_resolution', reason };
49
+ }
50
+ }
43
51
  const outcome = await integrateEpicBranch({ cwd, branch, epicId, carriedPaths });
44
52
  if (!outcome.ok) {
45
53
  console.log(`[epicWorktreeMerge] ${epicId}: needs manual resolution (${outcome.reason})`);
@@ -0,0 +1,102 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+
6
+ /**
7
+ * autoStartedSession.cjs — recognises an Epic that cross-project feedback
8
+ * auto-started (nobody watching its first turn) and supplies the no-ask turn
9
+ * instruction for it. Takes the stop sentinel as an argument so it never
10
+ * requires chatRunner.cjs. See epicMint.cjs for the autoApprove stamp.
11
+ */
12
+
13
+ /** Finds the Epic by claude session id → { epicId, session } or null. Never throws. */
14
+ function findEpic(cwd, claudeSessionId) {
15
+ try {
16
+ if (!cwd || !claudeSessionId) return null;
17
+ const { readActiveIndex } = require('../epic/epicMint.cjs');
18
+ const { sessions } = readActiveIndex(cwd);
19
+ for (const [key, session] of Object.entries(sessions)) {
20
+ if (session && session.claudeSessionId === claudeSessionId) {
21
+ return { epicId: session.id || key, session };
22
+ }
23
+ }
24
+ return null;
25
+ } catch {
26
+ return null;
27
+ }
28
+ }
29
+
30
+ function stampedAutoStart(session) {
31
+ const source = session && session.source;
32
+ return !!(source && source.producer === 'cross-project-feedback' && source.autoApprove);
33
+ }
34
+
35
+ /** True only for an Epic stamped producer 'cross-project-feedback' + autoApprove. Never throws. */
36
+ function isAutoStartedEpic(cwd, claudeSessionId) {
37
+ const found = findEpic(cwd, claudeSessionId);
38
+ return !!found && stampedAutoStart(found.session);
39
+ }
40
+
41
+ function hasMarkdown(dir) {
42
+ try {
43
+ const entries = fs.readdirSync(dir, { recursive: true });
44
+ return entries.some((e) => String(e).toLowerCase().endsWith('.md'));
45
+ } catch {
46
+ return false; // missing folder = empty
47
+ }
48
+ }
49
+
50
+ /**
51
+ * True when the Epic is auto-started, tagged bug or feature, and has no PRD
52
+ * file under prds/ or prds-archived/ (timestamped subfolders included). Never throws.
53
+ */
54
+ function autoStartNeedsPlan(cwd, claudeSessionId) {
55
+ try {
56
+ const found = findEpic(cwd, claudeSessionId);
57
+ if (!found || !stampedAutoStart(found.session)) return false;
58
+ const tag = found.session.tag;
59
+ if (tag !== 'bug' && tag !== 'feature') return false;
60
+ const { resolveEpicPrdWriteDir } = require('../prd/prdLocations.cjs');
61
+ const prds = resolveEpicPrdWriteDir(cwd, found.epicId);
62
+ const archived = path.join(path.dirname(prds), 'prds-archived');
63
+ return !hasMarkdown(prds) && !hasMarkdown(archived);
64
+ } catch {
65
+ return false;
66
+ }
67
+ }
68
+
69
+ const AUTO_START_FOLLOW_UP_PROMPT =
70
+ 'Your first turn ended with nothing queued. Queue the plan now with the /develop skill. ' +
71
+ 'If nothing needs building, say why and stop.';
72
+
73
+ /** Sends one automatic follow-up turn when the first turn left no plan. Never throws. */
74
+ function autoStartFollowUp({ cwd, tabId, sessionId, send }) {
75
+ try {
76
+ if (typeof send !== 'function') return false;
77
+ if (!autoStartNeedsPlan(cwd, sessionId)) return false;
78
+ const r = send(tabId, AUTO_START_FOLLOW_UP_PROMPT, { origin: 'scheduler', sessionId, cwd });
79
+ if (r && typeof r.catch === 'function') r.catch(() => {});
80
+ return true;
81
+ } catch {
82
+ return false;
83
+ }
84
+ }
85
+
86
+ function autoStartTurnInstruction(stopSentinel) {
87
+ return (
88
+ `IMPORTANT: This session was started automatically and nobody is watching. ` +
89
+ `Never ask questions and never print ${stopSentinel}. First check the report below ` +
90
+ `against this codebase. If it holds and the Mission is to plan or fix, finish the plan ` +
91
+ `in this turn and queue it with the /develop skill. If it does not hold, say why and ` +
92
+ `stop. End with a short report.\n\n`
93
+ );
94
+ }
95
+
96
+ module.exports = {
97
+ isAutoStartedEpic,
98
+ autoStartNeedsPlan,
99
+ autoStartFollowUp,
100
+ autoStartTurnInstruction,
101
+ AUTO_START_FOLLOW_UP_PROMPT,
102
+ };