claude-code-session-manager 0.142.0 → 0.143.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 (95) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +20 -107
  3. package/dist/assets/{AppSettings-BcZgIvvY.js → AppSettings-BO4jDVGO.js} +1 -1
  4. package/dist/assets/{History-DpZuJXi1.js → History-DTttbvPb.js} +1 -1
  5. package/dist/assets/{HomeClaudeConfig-D32ZJtU-.js → HomeClaudeConfig-DADP5bfn.js} +2 -2
  6. package/dist/assets/{Panel-BjdJjhqt.js → Panel-B_D4Bg7L.js} +1 -1
  7. package/dist/assets/{ProjectClaudeConfig-BTClYV6i.js → ProjectClaudeConfig-DPnDJKcr.js} +1 -1
  8. package/dist/assets/{Scheduler-DPobKx1Z.js → Scheduler-CNLjn90m.js} +8 -8
  9. package/dist/assets/{SkillReferenceGraph-Cqyu4mef.js → SkillReferenceGraph-D1b2aiol.js} +1 -1
  10. package/dist/assets/{Skills-vv0noNVI.js → Skills-cfV7sgk6.js} +1 -1
  11. package/dist/assets/{TiptapBody-CXi8Pvut.js → TiptapBody-DVXtEIVy.js} +1 -1
  12. package/dist/assets/{Toggle-CiYCWLjh.js → Toggle-CYajnSdx.js} +1 -1
  13. package/dist/assets/{VoiceButton-4NKKd1sC.js → VoiceButton-DJ4gGRuE.js} +1 -1
  14. package/dist/assets/{historyTotals-DDunb8Ch.js → historyTotals-D3MoHY2U.js} +1 -1
  15. package/dist/assets/{index-Cn5E9958.js → index-CdTppjKR.js} +436 -436
  16. package/dist/index.html +1 -1
  17. package/dist-web/app.js +356 -356
  18. package/package.json +3 -3
  19. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  20. package/plugins/session-manager-dev/skills/builder/SKILL.md +5 -0
  21. package/plugins/session-manager-dev/skills/develop/SKILL.md +9 -3
  22. package/scripts/README.md +1 -0
  23. package/scripts/scheduler-mcp-server.cjs +304 -6
  24. package/src/main/adminRouteRegistry.cjs +10 -0
  25. package/src/main/build-info.json +4 -4
  26. package/src/main/chatRunner.cjs +105 -7
  27. package/src/main/config.cjs +5 -1
  28. package/src/main/health.cjs +38 -2
  29. package/src/main/index.cjs +12 -4
  30. package/src/main/ipcSchemas.cjs +11 -0
  31. package/src/main/lib/demo-video-kit/cast.md +10 -1
  32. package/src/main/lib/demo-video-kit/character.cjs +77 -21
  33. package/src/main/lib/demo-video-kit/kind-tiktok.md +5 -1
  34. package/src/main/lib/demo-video-kit/projectSounds.cjs +191 -0
  35. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  36. package/src/main/lib/demo-video-kit/sound.cjs +166 -9
  37. package/src/main/lib/demo-video-kit/standalone.cjs +231 -0
  38. package/src/main/lib/epic/activeIndexMerge.cjs +5 -0
  39. package/src/main/lib/epic/artifactRetention.cjs +55 -9
  40. package/src/main/lib/epic/artifactStore.cjs +78 -35
  41. package/src/main/lib/epic/delegationReadiness.cjs +10 -3
  42. package/src/main/lib/epic/epicEventLog.cjs +45 -1
  43. package/src/main/lib/epic/epicStateEmitter.cjs +248 -0
  44. package/src/main/lib/epic/epicValidationHook.cjs +13 -2
  45. package/src/main/lib/externalContract.cjs +12 -1
  46. package/src/main/lib/feedback-remote/autoStartedSession.cjs +1 -1
  47. package/src/main/lib/feedback-remote/crossProjectReply.cjs +96 -8
  48. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +30 -0
  49. package/src/main/lib/feedback-remote/pendingReplies.cjs +18 -0
  50. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +94 -4
  51. package/src/main/lib/feedback-remote/replyClaims.cjs +159 -0
  52. package/src/main/lib/git/gitWorktree.cjs +8 -0
  53. package/src/main/lib/git/runtimeStateUntrack.cjs +15 -1
  54. package/src/main/lib/git/worktreeDeps.cjs +113 -10
  55. package/src/main/lib/mcpToolCatalog.cjs +102 -8
  56. package/src/main/lib/opsOwnership.cjs +113 -28
  57. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +46 -0
  58. package/src/main/lib/prd/prdCreate.cjs +350 -227
  59. package/src/main/lib/prd/prdCriteria.cjs +7 -4
  60. package/src/main/lib/project-pages/videoPressLines.cjs +145 -0
  61. package/src/main/lib/project-pages/videoScriptPress.cjs +260 -0
  62. package/src/main/lib/project-pages/videoScriptRunRoute.cjs +351 -0
  63. package/src/main/lib/project-pages/videoScriptSwitchIpc.cjs +49 -0
  64. package/src/main/lib/project-pages/videoScriptSwitchRoute.cjs +173 -0
  65. package/src/main/lib/scheduler/criteriaChecks.cjs +164 -20
  66. package/src/main/lib/scheduler/heldSchedulerTurns.cjs +238 -0
  67. package/src/main/lib/scheduler/jobMemoryStats.cjs +13 -2
  68. package/src/main/lib/scheduler/planRecordHarvest.cjs +120 -52
  69. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +60 -2
  70. package/src/main/lib/scheduler/queueStore.cjs +16 -0
  71. package/src/main/lib/scheduler/rcaReport.cjs +79 -15
  72. package/src/main/lib/scheduler/scheduleJobSchema.cjs +13 -0
  73. package/src/main/lib/scheduler/schedulerPaths.cjs +9 -0
  74. package/src/main/lib/scheduler/slotsRoute.cjs +101 -87
  75. package/src/main/lib/scheduler/usageHoldRoute.cjs +97 -0
  76. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +16 -5
  77. package/src/main/lib/tasks/memoryConsolidation.cjs +14 -2
  78. package/src/main/lib/tasks/mitigationReview.cjs +21 -1
  79. package/src/main/lib/tasks/taskAdminRoutes.cjs +78 -3
  80. package/src/main/lib/tasks/taskLedger.cjs +2 -2
  81. package/src/main/lib/telemetry/auditEvents.cjs +21 -24
  82. package/src/main/lib/telemetry/auditLog.cjs +6 -2
  83. package/src/main/lib/util/atomicFs.cjs +2 -2
  84. package/src/main/promptSessionEvents.cjs +16 -1
  85. package/src/main/pty.cjs +11 -2
  86. package/src/main/queueOps.cjs +1 -1
  87. package/src/main/runVerify.cjs +1 -1
  88. package/src/main/scheduler/utilizationHold.cjs +96 -6
  89. package/src/main/scheduler.cjs +533 -39
  90. package/src/main/templates/PRD_AUTHORING.md +7 -2
  91. package/src/preload/api.d.ts +47 -1
  92. package/src/preload/apiSurface.json +14 -0
  93. package/src/preload/index.cjs +2 -0
  94. package/src/seed/agents/demo-video-builder.md +15 -8
  95. package/src/seed/agents/validator.md +20 -19
@@ -0,0 +1,248 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * epicStateEmitter.cjs — event-driven Epic outside-state changes.
5
+ *
6
+ * Replaces the deleted tick watcher (epicStateWatcher.cjs, removed in
7
+ * 909f6e47). pokeEpicState(cwd, epicId) debounces per Epic, then recomputes
8
+ * the Epic's outside state through the same epicOutsideRead.getEpicRecord that
9
+ * GET /admin/epic uses, and appends one `epic.state_changed` event
10
+ * { kind, from, to, blockedKind?, externalRef? }
11
+ * to the Epic's own event log whenever (to, blockedKind) differs from the last
12
+ * recorded one. The last state is recovered from that log on first use, so a
13
+ * restart never repeats a row.
14
+ *
15
+ * Lifecycle shortcuts: lifecycleTo 'completed' → 'closed', 'proposed' →
16
+ * 'awaiting_approval' (no recompute). lifecycleTo 'active' retries while the
17
+ * record still reads another status (at most MAX_ACTIVE_RETRIES). A null
18
+ * record → 'gone', only when a last state is set and is not closed/gone.
19
+ *
20
+ * At most one recompute per Epic runs at a time; a poke during one schedules
21
+ * exactly one more. Nothing here throws or rejects.
22
+ *
23
+ * startEpicStateEmitter() subscribes to epicEventLog appends and pokes for
24
+ * POKE_KINDS (never for epic.state_changed itself).
25
+ */
26
+
27
+ const epicEventLog = require('./epicEventLog.cjs');
28
+ const { EPIC_OUTSIDE_STATES } = require('./epicOutsideState.cjs');
29
+
30
+ const KIND = 'epic.state_changed';
31
+ const EPIC_STATE_CHANGED_TO = Object.freeze([...EPIC_OUTSIDE_STATES, 'gone']);
32
+ const TO_SET = new Set(EPIC_STATE_CHANGED_TO);
33
+ const MAX_ACTIVE_RETRIES = 5;
34
+ const RECOVER_PAGE = 1000;
35
+ const RECOVER_MAX_PAGES = 50;
36
+ const POKE_KINDS = new Set([
37
+ 'epic.minted',
38
+ 'epic.status_changed',
39
+ 'job.queued',
40
+ 'job.status_changed',
41
+ 'job.needs_input',
42
+ 'human.answer',
43
+ 'human.message',
44
+ 'external.message',
45
+ 'validator.verdict',
46
+ 'outcome.recorded',
47
+ ]);
48
+
49
+ const DEFAULT_OPTS = () => ({
50
+ isTabBusy: () => false,
51
+ listJobs: () => [],
52
+ projectRoots: undefined,
53
+ debounceMs: 1000,
54
+ });
55
+
56
+ /** @type {{ isTabBusy: (epicId: string) => boolean | Promise<boolean>, listJobs: () => any, projectRoots: undefined | (() => string[]), debounceMs: number }} */
57
+ let opts = DEFAULT_OPTS();
58
+ /** key → debounce timeout */
59
+ const timers = new Map();
60
+ /** key → in-flight recompute promise */
61
+ const running = new Map();
62
+ /** keys poked while their recompute ran */
63
+ const again = new Set();
64
+ /** key → { cwd, epicId, lifecycleTo, attempt } waiting for its timer */
65
+ const pending = new Map();
66
+ /** key → { state, blockedKind, externalRef } | null */
67
+ const last = new Map();
68
+ let unsubscribe = null;
69
+
70
+ const keyOf = (cwd, epicId) => `${cwd}\0${epicId}`;
71
+ const str = (v) => (typeof v === 'string' && v !== '' ? v : null);
72
+ const msg = (e) => (e && e.message ? e.message : String(e));
73
+
74
+ /** @param {{ isTabBusy?: Function, listJobs?: Function, projectRoots?: Function, debounceMs?: number }} [o] */
75
+ function configureEpicStateEmitter(o = {}) {
76
+ if (!o || typeof o !== 'object') return;
77
+ if (typeof o.isTabBusy === 'function') opts.isTabBusy = /** @type {any} */ (o.isTabBusy);
78
+ if (typeof o.listJobs === 'function') opts.listJobs = /** @type {any} */ (o.listJobs);
79
+ if ('projectRoots' in o) opts.projectRoots = typeof o.projectRoots === 'function' ? /** @type {any} */ (o.projectRoots) : undefined;
80
+ if (Number.isFinite(o.debounceMs) && /** @type {number} */ (o.debounceMs) >= 0) opts.debounceMs = /** @type {number} */ (o.debounceMs);
81
+ }
82
+
83
+ /** The newest epic.state_changed in the Epic's log, or null. */
84
+ async function recoverLast(cwd, epicId) {
85
+ let after = 0;
86
+ let newest = null;
87
+ for (let page = 0; page < RECOVER_MAX_PAGES; page++) {
88
+ const res = await epicEventLog.readEpicEvents(cwd, epicId, { kinds: [KIND], after, limit: RECOVER_PAGE });
89
+ if (res.events.length) newest = res.events[res.events.length - 1];
90
+ if (!res.hasMore) break;
91
+ after = res.cursor;
92
+ }
93
+ if (!newest) return null;
94
+ return { state: str(newest.to), blockedKind: str(newest.blockedKind), externalRef: str(newest.externalRef) };
95
+ }
96
+
97
+ function arm(key, delay = opts.debounceMs) {
98
+ const t = timers.get(key);
99
+ if (t) clearTimeout(t);
100
+ const h = setTimeout(() => {
101
+ timers.delete(key);
102
+ fire(key);
103
+ }, delay);
104
+ if (h && typeof h.unref === 'function') h.unref();
105
+ timers.set(key, h);
106
+ }
107
+
108
+ function fire(key) {
109
+ if (running.has(key)) {
110
+ again.add(key);
111
+ return;
112
+ }
113
+ const p = pending.get(key);
114
+ if (!p) return;
115
+ pending.delete(key);
116
+ const prom = recompute(p).catch((e) => {
117
+ console.error('[epicStateEmitter] recompute failed', p.epicId, msg(e));
118
+ }).finally(() => {
119
+ running.delete(key);
120
+ if (again.delete(key)) fire(key);
121
+ });
122
+ running.set(key, prom);
123
+ }
124
+
125
+ /**
126
+ * pokeEpicState(cwd, epicId, { lifecycleTo? }) — schedule a debounced
127
+ * recompute of this Epic's outside state. Never throws.
128
+ */
129
+ function pokeEpicState(cwd, epicId, o = {}) {
130
+ try {
131
+ if (typeof cwd !== 'string' || !cwd || typeof epicId !== 'string' || !epicId) return;
132
+ const key = keyOf(cwd, epicId);
133
+ const p = pending.get(key) || { cwd, epicId, lifecycleTo: undefined, attempt: 0 };
134
+ const lt = o && typeof o === 'object' ? str(o.lifecycleTo) : null;
135
+ if (lt) p.lifecycleTo = lt;
136
+ p.attempt = 0;
137
+ pending.set(key, p);
138
+ arm(key);
139
+ } catch (e) {
140
+ console.error('[epicStateEmitter] poke failed', epicId, msg(e));
141
+ }
142
+ }
143
+
144
+ function scheduleRetry(key, cwd, epicId, attempt) {
145
+ const p = pending.get(key);
146
+ if (p) {
147
+ if (!p.lifecycleTo) p.lifecycleTo = 'active';
148
+ } else {
149
+ pending.set(key, { cwd, epicId, lifecycleTo: 'active', attempt });
150
+ }
151
+ arm(key);
152
+ }
153
+
154
+ async function recompute({ cwd, epicId, lifecycleTo, attempt }) {
155
+ const key = keyOf(cwd, epicId);
156
+ try {
157
+ if (!last.has(key)) last.set(key, await recoverLast(cwd, epicId));
158
+ const prev = last.get(key) || null;
159
+
160
+ /** @type {{ state: string|null, blockedKind: string|null, externalRef: string|null } | null} */
161
+ let next = null;
162
+ if (lifecycleTo === 'completed') {
163
+ next = { state: 'closed', blockedKind: null, externalRef: prev ? prev.externalRef : null };
164
+ } else if (lifecycleTo === 'proposed') {
165
+ next = { state: 'awaiting_approval', blockedKind: null, externalRef: prev ? prev.externalRef : null };
166
+ } else {
167
+ const outsideRead = require('./epicOutsideRead.cjs'); // lazy: pulls in promptSessionsIpc
168
+ const readOpts = { id: epicId, isTabBusy: opts.isTabBusy, listJobs: opts.listJobs };
169
+ if (opts.projectRoots) readOpts.projectRoots = opts.projectRoots;
170
+ const rec = await outsideRead.getEpicRecord(cwd, readOpts);
171
+ if (!rec) {
172
+ if (!prev || !prev.state || prev.state === 'closed' || prev.state === 'gone') return;
173
+ next = { state: 'gone', blockedKind: null, externalRef: prev.externalRef };
174
+ } else {
175
+ if (lifecycleTo === 'active' && rec.status !== 'active' && attempt < MAX_ACTIVE_RETRIES) {
176
+ scheduleRetry(key, cwd, epicId, attempt + 1);
177
+ return;
178
+ }
179
+ const state = str(rec.state);
180
+ next = {
181
+ state,
182
+ blockedKind: state === 'blocked' ? str(rec.blocked && rec.blocked.kind) : null,
183
+ externalRef: str(rec.externalRef),
184
+ };
185
+ }
186
+ }
187
+
188
+ if (!next.state || !TO_SET.has(next.state)) {
189
+ console.error('[epicStateEmitter] dropped unknown state', cwd, epicId, next.state);
190
+ return;
191
+ }
192
+ if (prev && prev.state === next.state && (prev.blockedKind || null) === (next.blockedKind || null)) return;
193
+
194
+ /** @type {Record<string, unknown>} */
195
+ const event = { kind: KIND, from: prev ? prev.state : null, to: next.state };
196
+ if (next.blockedKind) event.blockedKind = next.blockedKind;
197
+ if (next.externalRef) event.externalRef = next.externalRef;
198
+ await epicEventLog.appendEpicEvent(cwd, epicId, event);
199
+ last.set(key, next);
200
+ } catch (e) {
201
+ console.error('[epicStateEmitter] recompute failed', epicId, msg(e));
202
+ }
203
+ }
204
+
205
+ function onAppended(cwd, record) {
206
+ if (!record || !POKE_KINDS.has(record.kind)) return;
207
+ const epicId = str(record.epicId);
208
+ if (!epicId) return;
209
+ pokeEpicState(cwd, epicId, record.kind === 'epic.status_changed' ? { lifecycleTo: record.to } : {});
210
+ }
211
+
212
+ /** Subscribe to event-log appends (idempotent). Returns an unsubscribe function. */
213
+ function startEpicStateEmitter() {
214
+ if (!unsubscribe) unsubscribe = epicEventLog.onEpicEventAppended(onAppended);
215
+ return () => {
216
+ if (unsubscribe) unsubscribe();
217
+ unsubscribe = null;
218
+ };
219
+ }
220
+
221
+ /** Test helper: resolve once no timer or recompute is left. */
222
+ async function _settleForTests() {
223
+ for (let i = 0; i < 1000 && (timers.size || running.size || pending.size); i++) {
224
+ if (running.size) await Promise.all([...running.values()]);
225
+ else await new Promise((r) => setTimeout(r, Math.min(opts.debounceMs, 50) + 1));
226
+ }
227
+ }
228
+
229
+ function _resetForTests() {
230
+ for (const t of timers.values()) clearTimeout(t);
231
+ timers.clear();
232
+ running.clear();
233
+ again.clear();
234
+ pending.clear();
235
+ last.clear();
236
+ if (unsubscribe) unsubscribe();
237
+ unsubscribe = null;
238
+ opts = DEFAULT_OPTS();
239
+ }
240
+
241
+ module.exports = {
242
+ EPIC_STATE_CHANGED_TO,
243
+ configureEpicStateEmitter,
244
+ pokeEpicState,
245
+ startEpicStateEmitter,
246
+ _settleForTests,
247
+ _resetForTests,
248
+ };
@@ -189,7 +189,7 @@ const _rowInEpic = (r, epicId) => r && (r.epicId === epicId || r.sourcePromptId
189
189
 
190
190
  /**
191
191
  * runEpicSettle({ cwd, epicId }, deps) → { action, reason?, slug? }
192
- * Never throws. Actions: 'none' | 'sweep-queued' | 'digest-sent'.
192
+ * Never throws. Actions: 'none' | 'sweep-queued' | 'digest-sent' | 'digest-held'.
193
193
  */
194
194
  async function runEpicSettle({ cwd, epicId } = {}, deps = {}) {
195
195
  const {
@@ -300,7 +300,18 @@ async function runEpicSettle({ cwd, epicId } = {}, deps = {}) {
300
300
  try { (log || console).error('[epicValidationHook] readVerdictFiles failed', epicId, e); } catch { /* noop */ }
301
301
  }
302
302
  const prompt = buildSettledDigest(digestSettle, { epicId, notValidatedReason, cwd, findings });
303
- sendPrompt(epicId, prompt, { origin: 'scheduler' });
303
+ // A non-promise return or a rejected send counts as sent; only an explicit
304
+ // 'held' disposition (usage hold kept the turn) is recorded as held. The
305
+ // digestKey is kept either way so a later settle does not send a second one.
306
+ const sent = await Promise.resolve(sendPrompt(epicId, prompt, { origin: 'scheduler', heldKind: 'settle-digest' })).catch(() => null);
307
+ if (sent && sent.disposition === 'held') {
308
+ await appendResponseEvent(
309
+ cwd, epicId,
310
+ 'Plan digest held by the usage hold — it is delivered when the hold clears',
311
+ { outcome: 'digest', digestKey: settle.digestKey, held: true },
312
+ );
313
+ return { action: 'digest-held' };
314
+ }
304
315
  await appendResponseEvent(
305
316
  cwd, epicId,
306
317
  `Plan digest sent: ${settle.verified.length} verified, ${settle.refuted.length} refuted, ${settle.uncovered.length} not validated`,
@@ -75,6 +75,7 @@ const CONTRACT = deepFreeze({
75
75
  { method: 'POST', path: '/admin/tasks/import' },
76
76
  { method: 'POST', path: '/admin/tasks/switch' },
77
77
  { method: 'GET', path: '/admin/validation-quality' },
78
+ { method: 'GET', path: '/admin/usage-hold' },
78
79
  ],
79
80
  tools: {
80
81
  feedback_open_session: { required: ['toCwd', 'fromCwd', 'title', 'motivation', 'acceptanceCriteria', 'body'] },
@@ -84,6 +85,7 @@ const CONTRACT = deepFreeze({
84
85
  agent_list: { required: [] },
85
86
  task_list: { required: ['cwd'] },
86
87
  task_get: { required: ['cwd', 'id'] },
88
+ usage_hold_get: { required: [] },
87
89
  },
88
90
  epicStates: ['closed', 'awaiting_approval', 'needs_input', 'blocked', 'working', 'in_review', 'verified', 'open'],
89
91
  epicRecordFields: [
@@ -92,6 +94,8 @@ const CONTRACT = deepFreeze({
92
94
  ],
93
95
  receiptFields: ['jobs', 'chat'],
94
96
  epicStateChangedFields: ['at', 'kind', 'cwd', 'epicId', 'from', 'to', 'blockedKind', 'externalRef'],
97
+ // Every `to` an epic_state_changed row can carry: the outside states plus 'gone' (epicStateEmitter.cjs EPIC_STATE_CHANGED_TO).
98
+ epicStateChangedTo: ['closed', 'awaiting_approval', 'needs_input', 'blocked', 'working', 'in_review', 'verified', 'open', 'gone'],
95
99
  // Keys of an event-mode epic_cross_project_reply row (crossProjectReply.cjs replyAsEvent) as readEventsAfter returns it.
96
100
  replyEventFields: [
97
101
  'at', 'kind', 'cwd', 'epicId', 'fromCwd', 'fromEpicId', 'outcome', 'delivery', 'mode', 'externalRef',
@@ -156,7 +160,11 @@ const CONTRACT_FINGERPRINTS = Object.freeze({
156
160
  // then GET /admin/validation-quality (validationQualityHandlers.cjs),
157
161
  // then 'phase' on epicRecordFields + taskFields (phaseProjection.cjs),
158
162
  // then POST /admin/tasks/switch (tasks/taskSwitchRoute.cjs),
159
- // then taskBodyKeys + taskRuntimeKeys + taskGetKeys (advertised on GET /__admin/health via healthInfo()).
163
+ // then taskBodyKeys + taskRuntimeKeys + taskGetKeys (advertised on GET /__admin/health via healthInfo()),
164
+ // then epicStateChangedTo: the pinned `to` set of epic_state_changed rows (the 8 outside states + 'gone',
165
+ // back to the v1 shape 0.141.0 served; 0.142.0 served lifecycle words only, after C6 909f6e47 narrowed it).
166
+ // then GET /admin/usage-hold (scheduler/usageHoldRoute.cjs): the 'pause above' hold POST /admin/tasks refuses on.
167
+ // then usage_hold_get: the MCP tool over GET /admin/usage-hold (scheduler-mcp-server.cjs).
160
168
  1: Object.freeze([
161
169
  '5a56abbb70184ff4a34346a5c6da4c5e6edbd756b54573c199b812d3f5a04101',
162
170
  '7383ff32c80561b1b2c505a78a1e8313ae2851bdc6e8fce6c6a88e1ab119bf5a',
@@ -164,6 +172,9 @@ const CONTRACT_FINGERPRINTS = Object.freeze({
164
172
  '2ddfa9e96382e6d2d8db6849361aeb89a62d86c237ad99d149ccb01c6b57db6a',
165
173
  'a5be9b9b073639b4622574c842ed9a41ebb39c24c0919d699b18d2e197a8eb67',
166
174
  'ffb97327f0bd2da7d3f29693171ee7ee53982d8347d20d009e5aa5baf2bc15d1',
175
+ '4f4ee647977bb670c71db57c6fdfa8dc5db89ce789a1f05dbf23f9468dcff30b',
176
+ '2c87717d95b8b7dceb8a2138affcd3fc990f762072691de7a433b2874fe89d4d',
177
+ '9490d3b89b9468f20666553747b3d4be3558e78ffcb5b79d63397cfa4ddd5235',
167
178
  ]),
168
179
  });
169
180
 
@@ -75,7 +75,7 @@ function autoStartFollowUp({ cwd, tabId, sessionId, send }) {
75
75
  try {
76
76
  if (typeof send !== 'function') return false;
77
77
  if (!autoStartNeedsPlan(cwd, sessionId)) return false;
78
- const r = send(tabId, AUTO_START_FOLLOW_UP_PROMPT, { origin: 'scheduler', sessionId, cwd });
78
+ const r = send(tabId, AUTO_START_FOLLOW_UP_PROMPT, { origin: 'scheduler', heldKind: 'auto-start-follow-up', sessionId, cwd });
79
79
  if (r && typeof r.catch === 'function') r.catch(() => {});
80
80
  return true;
81
81
  } catch {
@@ -43,6 +43,7 @@ const { readActiveIndex } = require('../epic/epicMint.cjs');
43
43
  const { appendAuditEvent } = require('../telemetry/auditLog.cjs');
44
44
  const { resolveProjectContext } = require('../projectRootResolve.cjs');
45
45
  const pendingReplies = require('./pendingReplies.cjs');
46
+ const replyClaims = require('./replyClaims.cjs');
46
47
 
47
48
  const { addPendingReply, countPendingForThread } = pendingReplies;
48
49
 
@@ -147,9 +148,24 @@ function validateReplyInput(input) {
147
148
  }
148
149
  deliverWhen = { appVersionAbove: dw.appVersionAbove };
149
150
  }
151
+ let release = null;
152
+ if (input.release !== undefined && input.release !== null) {
153
+ const claim = replyClaims.normalizeReleaseClaim(input.release);
154
+ if (!claim.ok) return bad(400, claim.error);
155
+ release = claim.value;
156
+ }
157
+ const unfilled = replyClaims.findUnfilledPlaceholders(message, { allowVersionToken: !!(deliverWhen || release) });
158
+ if (unfilled.length) {
159
+ return bad(400, `message still holds an unfilled placeholder: ${unfilled.join(', ')} — `
160
+ + '{version} is filled only for a reply held with deliverWhen or a live reply carrying release.commits');
161
+ }
150
162
  return {
151
163
  ok: true,
152
- value: { message, outcome: input.outcome, referencePaths, ...(deliverWhen ? { deliverWhen } : {}) },
164
+ value: {
165
+ message, outcome: input.outcome, referencePaths,
166
+ ...(deliverWhen ? { deliverWhen } : {}),
167
+ ...(release ? { release } : {}),
168
+ },
153
169
  };
154
170
  }
155
171
 
@@ -238,7 +254,11 @@ function earlierDelivery(receipt, { targetCwd, rt, threadField, sent }) {
238
254
  * deliverWhen { appVersionAbove: 'x.y.z' } holds the reply in the
239
255
  * pending-reply ledger (pendingReplies.cjs) instead of sending it; its
240
256
  * ledger entry holds a slot under MAX_REPLIES_PER_THREAD like a receipt.
241
- * deps: { sendPrompt, appendEvent, resolveEpicId, appendAudit, openFallback }
257
+ * release { commits: [...] } (Session Manager repo only) claims the
258
+ * running release contains those commits; a live one is checked with
259
+ * git (409 when false) and its '{version}' is filled with that version.
260
+ * deps: { sendPrompt, appendEvent, resolveEpicId, appendAudit, openFallback,
261
+ * appVersion (string | () => string), runGit }
242
262
  * openFallback defaults to crossProjectFeedback.openReplyFallbackSession;
243
263
  * pass null to get a 409 fallbackNeeded instead.
244
264
  */
@@ -249,7 +269,8 @@ async function sendFeedbackReply(input, deps = {}) {
249
269
  // 1. Validation.
250
270
  const valid = validateReplyInput(input);
251
271
  if (!valid.ok) return valid;
252
- const { message, outcome, referencePaths, deliverWhen } = valid.value;
272
+ const { outcome, referencePaths, deliverWhen, release } = valid.value;
273
+ let { message } = valid.value;
253
274
 
254
275
  // 2. Identity — Y comes ONLY from the caller's chat session id.
255
276
  const originClaudeSessionId = typeof input.originClaudeSessionId === 'string' ? input.originClaudeSessionId : '';
@@ -269,6 +290,19 @@ async function sendFeedbackReply(input, deps = {}) {
269
290
  const y = yIndex.sessions[yId];
270
291
  if (!y) return bad(403, 'no Epic in the calling project owns this chat session — cannot reply');
271
292
 
293
+ // 2b. Release claims — only Session Manager's own repo can claim one of its releases.
294
+ const smRepo = replyClaims.isSessionManagerRepo(replierCwd);
295
+ if (release && !smRepo) {
296
+ return bad(400, 'release may only be sent from the Session Manager repository — it claims a Session Manager release');
297
+ }
298
+ if (smRepo && outcome === 'done' && !release) {
299
+ const named = replyClaims.findSessionManagerVersions(message);
300
+ if (named.length || message.includes('{version}')) {
301
+ return bad(400, `a done reply that names a Session Manager release (${named.length ? named.join(', ') : '{version}'}) `
302
+ + 'must carry release.commits so the release can be checked to contain them');
303
+ }
304
+ }
305
+
272
306
  // 3. Thread.
273
307
  const resolved = resolveThread(y.source || {});
274
308
  if (!resolved.ok) return bad(400, resolved.error);
@@ -292,6 +326,25 @@ async function sendFeedbackReply(input, deps = {}) {
292
326
  return bad(400, 'replyTo points at the replying project itself — use /develop inside this Epic');
293
327
  }
294
328
 
329
+ // 3b. A live release claim must be true of the running release.
330
+ let releaseMeta = null;
331
+ if (release && !deliverWhen) {
332
+ const version = typeof deps.appVersion === 'function'
333
+ ? deps.appVersion()
334
+ : (deps.appVersion || require('../../../../package.json').version);
335
+ const others = replyClaims.findSessionManagerVersions(message).filter((v) => v !== version);
336
+ if (others.length) {
337
+ return bad(409, `message names Session Manager ${others.join(', ')} but the running release is ${version}`);
338
+ }
339
+ const checked = await replyClaims.checkReleaseContains(
340
+ { repoCwd: replierCwd, version, commits: release.commits },
341
+ deps.runGit ? { runGit: deps.runGit } : {},
342
+ );
343
+ if (!checked.ok) return bad(409, checked.error);
344
+ message = message.split('{version}').join(version);
345
+ releaseMeta = { version, commits: release.commits.slice() };
346
+ }
347
+
295
348
  return withThreadLock(`${realOr(replierCwd)}\u0000${yId}`, async () => {
296
349
  // 4. Identical retry, then cap (receipts + replies still held in the ledger).
297
350
  const receipts = readReceipts(replierCwd, yId);
@@ -337,6 +390,7 @@ async function sendFeedbackReply(input, deps = {}) {
337
390
  message,
338
391
  referencePaths,
339
392
  appVersionAbove: deliverWhen.appVersionAbove,
393
+ commits: release ? release.commits : undefined,
340
394
  hash,
341
395
  ySource: y.source || {},
342
396
  sentAtScheduling: used + 1,
@@ -362,6 +416,7 @@ async function sendFeedbackReply(input, deps = {}) {
362
416
  return deliverAuthorizedReply({
363
417
  replierCwd, yId, y, rt, legacy, eventMode, threadField, targetCwd,
364
418
  message, outcome, referencePaths, hash, sent: used, originClaudeSessionId,
419
+ ...(releaseMeta ? { release: releaseMeta } : {}),
365
420
  }, deps);
366
421
  });
367
422
  }
@@ -380,8 +435,9 @@ async function sendFeedbackReply(input, deps = {}) {
380
435
  async function deliverAuthorizedReply(ctx, deps = {}) {
381
436
  const {
382
437
  replierCwd, yId, y, rt, legacy, eventMode, threadField = {}, targetCwd,
383
- message, outcome, referencePaths = [], hash, sent, originClaudeSessionId,
438
+ message, outcome, referencePaths = [], hash, sent, originClaudeSessionId, release,
384
439
  } = ctx;
440
+ const releaseField = release ? { release } : {};
385
441
  const sendPrompt = deps.sendPrompt || defaultSendPrompt;
386
442
  const appendEvent = deps.appendEvent || defaultAppendEvent;
387
443
  const audit = deps.appendAudit || appendAuditEvent;
@@ -389,7 +445,7 @@ async function deliverAuthorizedReply(ctx, deps = {}) {
389
445
  if (eventMode) {
390
446
  return replyAsEvent({
391
447
  appendEvent, audit, sent, rt, targetCwd, replierCwd, yId, y,
392
- message, outcome, referencePaths, hash,
448
+ message, outcome, referencePaths, hash, releaseField,
393
449
  });
394
450
  }
395
451
 
@@ -439,6 +495,7 @@ async function deliverAuthorizedReply(ctx, deps = {}) {
439
495
  fromCwd: replierCwd, fromEpicId: yId, outcome, referencePaths, hash,
440
496
  delivery: 'fallback', toEpicId: rt.epicId, fallbackEpicId: opened.epicId, reason,
441
497
  ...(reused ? { reused: true } : {}),
498
+ ...releaseField,
442
499
  },
443
500
  });
444
501
  // Best-effort receipt on X, only while X is still in A's active index.
@@ -511,6 +568,7 @@ async function deliverAuthorizedReply(ctx, deps = {}) {
511
568
  fromCwd: replierCwd, fromEpicId: yId, outcome, referencePaths, hash,
512
569
  delivery, toEpicId: x.id,
513
570
  ...(delivery === 'event-only' && sendResult && sendResult.reason ? { reason: sendResult.reason } : {}),
571
+ ...releaseField,
514
572
  },
515
573
  });
516
574
 
@@ -547,6 +605,7 @@ async function deliverAuthorizedReply(ctx, deps = {}) {
547
605
  */
548
606
  async function replyAsEvent({
549
607
  appendEvent, audit, sent, rt, targetCwd, replierCwd, yId, y, message, outcome, referencePaths, hash,
608
+ releaseField = {},
550
609
  }) {
551
610
  const replyMeta = { fromCwd: replierCwd, fromEpicId: yId, outcome, referencePaths };
552
611
  let eventOnAskingEpic = false;
@@ -570,6 +629,7 @@ async function replyAsEvent({
570
629
  reply: {
571
630
  ...replyMeta, hash, delivery: 'event-only', reason: EVENT_MODE_REASON,
572
631
  ...(rt.epicId ? { toEpicId: rt.epicId } : {}),
632
+ ...releaseField,
573
633
  },
574
634
  });
575
635
 
@@ -689,7 +749,11 @@ function resolveThread(src) {
689
749
  }
690
750
 
691
751
  /**
692
- * deliverDueReplies({ appVersion }, deps) → Promise<{ due, delivered, failed, results }>.
752
+ * deliverDueReplies({ appVersion }, deps) → Promise<{ due, delivered, failed, waiting, results }>.
753
+ * An entry carrying release commits is sent only once tag v<appVersion>
754
+ * contains every one (replyClaims.checkReleaseContains); until then it
755
+ * counts as waiting and spends no attempt. A message that still holds a
756
+ * placeholder after {version} is filled is never sent (a failed attempt).
693
757
  * Sends every pending-reply ledger entry whose appVersionAbove is now below
694
758
  * appVersion: `{version}` in its message becomes appVersion, then it goes
695
759
  * through deliverAuthorizedReply (same path + fallback as a live reply) under
@@ -708,7 +772,7 @@ function resolveThread(src) {
708
772
  let dueRepliesPassRunning = false;
709
773
 
710
774
  async function deliverDueReplies(opts = {}, deps = {}) {
711
- if (dueRepliesPassRunning) return { due: 0, delivered: 0, failed: 0, results: [], skipped: true };
775
+ if (dueRepliesPassRunning) return { due: 0, delivered: 0, failed: 0, waiting: 0, results: [], skipped: true };
712
776
  dueRepliesPassRunning = true;
713
777
  try {
714
778
  return await runDueRepliesPass(opts, deps);
@@ -728,13 +792,14 @@ function replyPassLogMeta(r, appVersion) {
728
792
  due: r.due,
729
793
  delivered: r.delivered,
730
794
  failed: r.failed,
795
+ waiting: Number.isInteger(r.waiting) ? r.waiting : 0,
731
796
  skipped: r.skipped === true,
732
797
  ...(r.error ? { error: r.error } : {}),
733
798
  };
734
799
  }
735
800
 
736
801
  async function runDueRepliesPass({ appVersion } = {}, deps = {}) {
737
- const summary = { due: 0, delivered: 0, failed: 0, results: [] };
802
+ const summary = { due: 0, delivered: 0, failed: 0, waiting: 0, results: [] };
738
803
  const listDue = deps.listDueReplies || pendingReplies.listDueReplies;
739
804
  const markDelivered = deps.markReplyDelivered || pendingReplies.markReplyDelivered;
740
805
  const audit = deps.appendAudit || appendAuditEvent;
@@ -750,6 +815,23 @@ async function runDueRepliesPass({ appVersion } = {}, deps = {}) {
750
815
  const version = String(appVersion);
751
816
 
752
817
  for (const entry of due) {
818
+ // A release claim waits — no attempt spent — until tag v<version> holds every commit.
819
+ if (entry && Array.isArray(entry.commits) && entry.commits.length) {
820
+ let checked;
821
+ try {
822
+ checked = await replyClaims.checkReleaseContains(
823
+ { repoCwd: entry.replierCwd, version, commits: entry.commits },
824
+ { runGit: deps.runGit },
825
+ );
826
+ } catch (e) {
827
+ checked = { ok: false, error: e && e.message ? e.message : String(e) };
828
+ }
829
+ if (!checked || !checked.ok) {
830
+ summary.waiting += 1;
831
+ summary.results.push({ id: entry.id, ok: false, waiting: (checked && checked.error) || 'release check failed' });
832
+ continue;
833
+ }
834
+ }
753
835
  let result;
754
836
  try {
755
837
  result = await deliverOneDueReply(entry, version, deps);
@@ -815,6 +897,11 @@ async function deliverOneDueReply(entry, version, deps) {
815
897
  const eventMode = thread.mode === 'event';
816
898
  if (!eventMode && !nonEmpty(thread.epicId)) return { ok: false, error: 'ledger entry has no asking Epic' };
817
899
  const message = String(entry.message ?? '').split('{version}').join(version);
900
+ const unfilled = replyClaims.findUnfilledPlaceholders(message);
901
+ if (unfilled.length) {
902
+ return { ok: false, error: `message still holds unfilled placeholder ${unfilled.join(', ')} — not sent` };
903
+ }
904
+ const commits = Array.isArray(entry.commits) && entry.commits.length ? entry.commits.slice() : null;
818
905
  const outcome = entry.outcome;
819
906
  const referencePaths = Array.isArray(entry.referencePaths) ? entry.referencePaths : [];
820
907
  const legacy = thread.legacy === true;
@@ -843,6 +930,7 @@ async function deliverOneDueReply(entry, version, deps) {
843
930
  threadField: legacy ? { thread: 'legacy' } : {},
844
931
  targetCwd, message, outcome, referencePaths,
845
932
  hash: replyHash(outcome, message), sent,
933
+ ...(commits ? { release: { version, commits } } : {}),
846
934
  }, { ...deps, appendEvent });
847
935
  });
848
936
  }
@@ -63,6 +63,7 @@
63
63
  'use strict';
64
64
 
65
65
  const { readBody, sendJson } = require('./localAdminHttp.cjs');
66
+ const { usageHeldBody } = require('../scheduler/usageHoldRoute.cjs');
66
67
  const { resolveCwd } = require('./projectHomeAdminRoutes.cjs');
67
68
  const macroLibrary = require('../persona-macro/macroLibrary.cjs');
68
69
  const { appendAuditEvent } = require('../telemetry/auditLog.cjs');
@@ -408,6 +409,8 @@ function runHandler(deps, libOpts) {
408
409
  return;
409
410
  }
410
411
 
412
+ if (refusedByUsageHold(deps, res)) return;
413
+
411
414
  const payload = {
412
415
  cwd,
413
416
  agentName: macro.agentName,
@@ -451,6 +454,30 @@ function runHandler(deps, libOpts) {
451
454
  };
452
455
  }
453
456
 
457
+ const USAGE_HOLD_HINT =
458
+ "Usage is above 'pause above': script presses wait until the window resets or usage drops below it. "
459
+ + 'Retry after hold.resetsAt. GET /admin/usage-hold reads the hold.';
460
+
461
+ /**
462
+ * The usage hold ('pause above') gate in front of every script-press
463
+ * startExternalNewSession call. Replies 429 usage_held / 503 usage_hold_error
464
+ * and returns true when the press must not start; false when it may.
465
+ * Read lazily so scheduler.cjs never loads at module load.
466
+ */
467
+ function refusedByUsageHold(deps, res) {
468
+ const usageHold = deps.usageHold || (() => require('../../scheduler.cjs').currentUsageHold());
469
+ let hold;
470
+ try {
471
+ hold = usageHold();
472
+ } catch (e) {
473
+ sendJson(res, 503, { ok: false, error: 'usage_hold_error', details: e instanceof Error ? e.message : String(e) });
474
+ return true;
475
+ }
476
+ if (!hold) return false;
477
+ sendJson(res, 429, usageHeldBody(hold, USAGE_HOLD_HINT));
478
+ return true;
479
+ }
480
+
454
481
  /** 503 error text for a failed startExternalNewSession result. */
455
482
  function launchFailureError(result) {
456
483
  return result?.reason === 'timeout'
@@ -500,6 +527,8 @@ async function runWithExternalRef({ deps, res, cwd, macro, prompt, effort, exter
500
527
  recentRuns.delete(key);
501
528
  }
502
529
 
530
+ if (refusedByUsageHold(deps, res)) return;
531
+
503
532
  const payload = {
504
533
  cwd,
505
534
  agentName: macro.agentName,
@@ -559,6 +588,7 @@ async function runWithExternalRef({ deps, res, cwd, macro, prompt, effort, exter
559
588
  /**
560
589
  * @param {{ onChanged?: () => void, startExternalNewSession?: (p: object) => Promise<any>,
561
590
  * isTabBusy?: (tabId: string) => boolean, listPersonas?: () => Promise<Array<{name: string}>>,
591
+ * usageHold?: () => any,
562
592
  * checkProjectVideoToolRunnable?: (i: { cwd: string, agentName: string, job: object }) => Promise<{ ok: boolean, error?: string }> }} deps
563
593
  */
564
594
  function registerAdminRoute(adminHttp, deps = {}, opts = {}) {