claude-code-session-manager 0.141.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 (223) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +76 -153
  3. package/bin/cli.cjs +11 -0
  4. package/dist/assets/AppSettings-BO4jDVGO.js +2 -0
  5. package/dist/assets/{History-DJMiuXyK.js → History-DTttbvPb.js} +1 -1
  6. package/dist/assets/HomeClaudeConfig-DADP5bfn.js +3 -0
  7. package/dist/assets/{Panel-Bf1Cf8UL.js → Panel-B_D4Bg7L.js} +1 -1
  8. package/dist/assets/{ProjectClaudeConfig-BWPpypf9.js → ProjectClaudeConfig-DPnDJKcr.js} +7 -7
  9. package/dist/assets/Scheduler-CNLjn90m.js +16 -0
  10. package/dist/assets/{SkillReferenceGraph-Ba4TkX2C.js → SkillReferenceGraph-D1b2aiol.js} +1 -1
  11. package/dist/assets/{Skills-C1v91GEO.js → Skills-cfV7sgk6.js} +5 -5
  12. package/dist/assets/{TiptapBody-BrcWVpiW.js → TiptapBody-DVXtEIVy.js} +1 -1
  13. package/dist/assets/Toggle-CYajnSdx.js +1 -0
  14. package/dist/assets/{VoiceButton-qivnDV6K.js → VoiceButton-DJ4gGRuE.js} +1 -1
  15. package/dist/assets/{historyTotals-CMCPTKqC.js → historyTotals-D3MoHY2U.js} +1 -1
  16. package/dist/assets/index-CdTppjKR.js +3133 -0
  17. package/dist/assets/{index-DKXdXfka.css → index-DVHIHoJf.css} +1 -1
  18. package/dist/index.html +2 -2
  19. package/dist-web/app.css +1 -1
  20. package/dist-web/app.js +496 -484
  21. package/package.json +6 -4
  22. package/plugins/AGENTS.md +4 -3
  23. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  24. package/plugins/session-manager-dev/hooks/hooks.json +15 -0
  25. package/plugins/session-manager-dev/hooks/residue-check.cjs +241 -0
  26. package/plugins/session-manager-dev/skills/builder/SKILL.md +5 -0
  27. package/plugins/session-manager-dev/skills/develop/SKILL.md +58 -18
  28. package/plugins/session-manager-dev/skills/develop/standards.md +3 -2
  29. package/scripts/README.md +2 -0
  30. package/scripts/hooks/guard-tool-risk.cjs +5 -1
  31. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +158 -1
  32. package/scripts/scheduler-mcp-server.cjs +1032 -112
  33. package/src/main/adminRouteRegistry.cjs +69 -0
  34. package/src/main/agentLibrary.cjs +72 -4
  35. package/src/main/agentsIpc.cjs +3 -2
  36. package/src/main/build-info.json +4 -4
  37. package/src/main/chatRunner.cjs +336 -23
  38. package/src/main/config.cjs +35 -1
  39. package/src/main/docEdit.cjs +4 -2
  40. package/src/main/health.cjs +129 -2
  41. package/src/main/index.cjs +110 -52
  42. package/src/main/ipcSchemas.cjs +172 -8
  43. package/src/main/lib/AGENTS.md +1 -1
  44. package/src/main/lib/chatBootRecovery.cjs +2 -0
  45. package/src/main/lib/claude/agentModelResolve.cjs +51 -25
  46. package/src/main/lib/claude/agentSnapshot.cjs +186 -0
  47. package/src/main/lib/claude/environmentProfiles.cjs +242 -0
  48. package/src/main/lib/claude/jobSandboxPolicy.cjs +241 -33
  49. package/src/main/lib/claude/personaToolScope.cjs +82 -31
  50. package/src/main/lib/claude/runClaudeP.cjs +4 -2
  51. package/src/main/lib/claude/toolRiskMarks.cjs +41 -1
  52. package/src/main/lib/claude/usageCircuit.cjs +49 -21
  53. package/src/main/lib/claude/vaultRefs.cjs +277 -0
  54. package/src/main/lib/demo-video-kit/capture.cjs +282 -12
  55. package/src/main/lib/demo-video-kit/cast.md +52 -0
  56. package/src/main/lib/demo-video-kit/character.cjs +778 -30
  57. package/src/main/lib/demo-video-kit/checks.cjs +120 -1
  58. package/src/main/lib/demo-video-kit/export.cjs +218 -0
  59. package/src/main/lib/demo-video-kit/frames.cjs +104 -9
  60. package/src/main/lib/demo-video-kit/kind-marketing.md +121 -0
  61. package/src/main/lib/demo-video-kit/kind-tiktok.md +103 -0
  62. package/src/main/lib/demo-video-kit/kokoroSay.cjs +205 -0
  63. package/src/main/lib/demo-video-kit/project-home-html.md +43 -0
  64. package/src/main/lib/demo-video-kit/projectSounds.cjs +191 -0
  65. package/src/main/lib/demo-video-kit/resumableRun.cjs +298 -0
  66. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  67. package/src/main/lib/demo-video-kit/sound.cjs +166 -9
  68. package/src/main/lib/demo-video-kit/standalone.cjs +231 -0
  69. package/src/main/lib/demo-video-kit/voiceLane.cjs +233 -0
  70. package/src/main/lib/demo-video-kit/voiceLibrary.cjs +312 -0
  71. package/src/main/lib/epic/activeIndexMerge.cjs +5 -0
  72. package/src/main/lib/epic/artifactAdminRoutes.cjs +211 -0
  73. package/src/main/lib/epic/artifactIpc.cjs +153 -0
  74. package/src/main/lib/epic/artifactNotice.cjs +72 -0
  75. package/src/main/lib/epic/artifactRetention.cjs +356 -0
  76. package/src/main/lib/epic/artifactStore.cjs +435 -0
  77. package/src/main/lib/epic/delegationReadiness.cjs +83 -2
  78. package/src/main/lib/epic/epicAgentRefresh.cjs +97 -0
  79. package/src/main/lib/epic/epicEventLog.cjs +258 -0
  80. package/src/main/lib/epic/epicMint.cjs +43 -1
  81. package/src/main/lib/epic/epicOutsideRead.cjs +1 -0
  82. package/src/main/lib/epic/epicOutsideState.cjs +18 -4
  83. package/src/main/lib/epic/epicPurge.cjs +347 -0
  84. package/src/main/lib/epic/epicReopen.cjs +5 -2
  85. package/src/main/lib/epic/epicSettle.cjs +4 -13
  86. package/src/main/lib/epic/epicSpawnPlan.cjs +57 -4
  87. package/src/main/lib/epic/epicStateEmitter.cjs +248 -0
  88. package/src/main/lib/epic/epicStatusMirror.cjs +34 -1
  89. package/src/main/lib/epic/epicTransitions.cjs +139 -0
  90. package/src/main/lib/epic/epicValidationHook.cjs +94 -4
  91. package/src/main/lib/epic/guardSpawnSettings.cjs +3 -2
  92. package/src/main/lib/externalContract.cjs +48 -4
  93. package/src/main/lib/feedback-remote/autoStartedSession.cjs +1 -1
  94. package/src/main/lib/feedback-remote/crossProjectReply.cjs +478 -127
  95. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -3
  96. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +11 -6
  97. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +26 -1
  98. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +5 -2
  99. package/src/main/lib/feedback-remote/feedbackBoxDrain.cjs +409 -0
  100. package/src/main/lib/feedback-remote/feedbackBoxKeys.cjs +218 -0
  101. package/src/main/lib/feedback-remote/feedbackEnvelope.cjs +163 -0
  102. package/src/main/lib/feedback-remote/feedbackRelayClient.cjs +164 -0
  103. package/src/main/lib/feedback-remote/feedbackReport.cjs +234 -0
  104. package/src/main/lib/feedback-remote/feedbackSeal.cjs +217 -0
  105. package/src/main/lib/feedback-remote/localAdminHttp.cjs +108 -2
  106. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +32 -1
  107. package/src/main/lib/feedback-remote/needsYouIpc.cjs +17 -0
  108. package/src/main/lib/feedback-remote/needsYouStore.cjs +177 -6
  109. package/src/main/lib/feedback-remote/pendingReplies.cjs +207 -0
  110. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +282 -14
  111. package/src/main/lib/feedback-remote/replyClaims.cjs +159 -0
  112. package/src/main/lib/feedback-remote/serviceClient.cjs +429 -0
  113. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +252 -0
  114. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +284 -0
  115. package/src/main/lib/feedback-remote/servicePairings.cjs +313 -0
  116. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +290 -0
  117. package/src/main/lib/feedback-remote/siteFeedbackAdminRoutes.cjs +295 -0
  118. package/src/main/lib/feedback-remote/siteFeedbackInbox.cjs +598 -0
  119. package/src/main/lib/feedback-remote/siteFeedbackIpc.cjs +86 -0
  120. package/src/main/lib/feedback-remote/siteFeedbackService.cjs +477 -0
  121. package/src/main/lib/git/gitWorktree.cjs +8 -0
  122. package/src/main/lib/git/runtimeStateUntrack.cjs +15 -1
  123. package/src/main/lib/git/worktreeDeps.cjs +182 -4
  124. package/src/main/lib/mcpToolCatalog.cjs +399 -29
  125. package/src/main/lib/opsOwnership.cjs +141 -28
  126. package/src/main/lib/opsRetentionSettings.cjs +27 -5
  127. package/src/main/lib/persona-macro/builtinMacros.cjs +7 -2
  128. package/src/main/lib/persona-macro/macroJobDispatch.cjs +52 -8
  129. package/src/main/lib/persona-macro/macroJobIpc.cjs +16 -6
  130. package/src/main/lib/persona-macro/macroLibrary.cjs +49 -7
  131. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +83 -0
  132. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +3 -0
  133. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +309 -0
  134. package/src/main/lib/phaseProjection.cjs +103 -0
  135. package/src/main/lib/prd/depSlugResolve.cjs +4 -13
  136. package/src/main/lib/prd/prdBodyPatch.cjs +12 -17
  137. package/src/main/lib/prd/prdCreate.cjs +387 -228
  138. package/src/main/lib/prd/prdCriteria.cjs +228 -0
  139. package/src/main/lib/prd/prdFrontmatter.cjs +43 -3
  140. package/src/main/lib/prd/prdGateFiles.cjs +125 -49
  141. package/src/main/lib/prd/prdSizing.cjs +3 -1
  142. package/src/main/lib/process/cleanEnv.cjs +52 -1
  143. package/src/main/lib/process/leftoverRenice.cjs +178 -0
  144. package/src/main/lib/process/memoryScope.cjs +31 -3
  145. package/src/main/lib/project-pages/pagesLibrary.cjs +72 -6
  146. package/src/main/lib/project-pages/videoPressLines.cjs +145 -0
  147. package/src/main/lib/project-pages/videoReviewIpc.cjs +3 -2
  148. package/src/main/lib/project-pages/videoScriptPress.cjs +260 -0
  149. package/src/main/lib/project-pages/videoScriptRunRoute.cjs +351 -0
  150. package/src/main/lib/project-pages/videoScriptSwitchIpc.cjs +49 -0
  151. package/src/main/lib/project-pages/videoScriptSwitchRoute.cjs +173 -0
  152. package/src/main/lib/project-pages/voiceAdminRoutes.cjs +175 -0
  153. package/src/main/lib/project-pages/voicePreview.cjs +196 -0
  154. package/src/main/lib/project-pages/voicesIpc.cjs +186 -0
  155. package/src/main/lib/promptSessionSchema.cjs +6 -0
  156. package/src/main/lib/scheduler/cancelledRow.cjs +57 -0
  157. package/src/main/lib/scheduler/cpuSample.cjs +133 -42
  158. package/src/main/lib/scheduler/criteriaChecks.cjs +313 -0
  159. package/src/main/lib/scheduler/definitionOfDone.cjs +44 -5
  160. package/src/main/lib/scheduler/heldSchedulerTurns.cjs +238 -0
  161. package/src/main/lib/scheduler/jobMemoryStats.cjs +324 -0
  162. package/src/main/lib/scheduler/loadGate.cjs +82 -4
  163. package/src/main/lib/scheduler/planRecordHarvest.cjs +152 -54
  164. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +191 -0
  165. package/src/main/lib/scheduler/queueStore.cjs +16 -0
  166. package/src/main/lib/scheduler/rcaReport.cjs +79 -15
  167. package/src/main/lib/scheduler/runLogRetention.cjs +42 -1
  168. package/src/main/lib/scheduler/scheduleJobSchema.cjs +18 -0
  169. package/src/main/lib/scheduler/scheduleJobTransitions.cjs +47 -0
  170. package/src/main/lib/scheduler/schedulerConfig.cjs +47 -0
  171. package/src/main/lib/scheduler/schedulerPaths.cjs +9 -3
  172. package/src/main/lib/scheduler/schedulerRuntimeState.cjs +50 -1
  173. package/src/main/lib/scheduler/sessionSlots.cjs +5 -1
  174. package/src/main/lib/scheduler/slotsRoute.cjs +251 -0
  175. package/src/main/lib/scheduler/toolClearance.cjs +258 -0
  176. package/src/main/lib/scheduler/usageHoldRoute.cjs +97 -0
  177. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +152 -11
  178. package/src/main/lib/tasks/memoryConsolidation.cjs +312 -0
  179. package/src/main/lib/tasks/mitigationReview.cjs +314 -0
  180. package/src/main/lib/tasks/taskAdminRoutes.cjs +390 -25
  181. package/src/main/lib/tasks/taskIpc.cjs +22 -18
  182. package/src/main/lib/tasks/taskLedger.cjs +147 -25
  183. package/src/main/lib/tasks/taskRun.cjs +186 -17
  184. package/src/main/lib/tasks/taskSwitch.cjs +85 -12
  185. package/src/main/lib/tasks/taskSwitchRoute.cjs +172 -0
  186. package/src/main/lib/telemetry/auditEvents.cjs +204 -6
  187. package/src/main/lib/telemetry/auditLog.cjs +6 -2
  188. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +198 -6
  189. package/src/main/lib/telemetry/webhookDelivery.cjs +205 -0
  190. package/src/main/lib/telemetry/webhookRegistry.cjs +281 -0
  191. package/src/main/lib/toolUseClassify.cjs +181 -0
  192. package/src/main/lib/util/atomicFs.cjs +2 -2
  193. package/src/main/lib/util/smfileRange.cjs +77 -0
  194. package/src/main/projectPages.cjs +3 -1
  195. package/src/main/promptSessionEvents.cjs +21 -1
  196. package/src/main/pty.cjs +77 -0
  197. package/src/main/queueOps.cjs +33 -14
  198. package/src/main/runVerify.cjs +74 -9
  199. package/src/main/scheduler/AGENTS.md +1 -0
  200. package/src/main/scheduler/budget.cjs +6 -5
  201. package/src/main/scheduler/prdParser.cjs +46 -13
  202. package/src/main/scheduler/reviewLadder.cjs +9 -25
  203. package/src/main/scheduler/utilizationHold.cjs +191 -0
  204. package/src/main/scheduler.cjs +1932 -213
  205. package/src/main/templates/PRD_AUTHORING.md +11 -3
  206. package/src/main/webRemote.cjs +463 -6
  207. package/src/preload/api.d.ts +576 -39
  208. package/src/preload/apiSurface.json +223 -7
  209. package/src/preload/index.cjs +48 -1
  210. package/src/seed/agents/architect.md +6 -1
  211. package/src/seed/agents/blender-artist.md +2 -1
  212. package/src/seed/agents/competitive-analyst.md +3 -1
  213. package/src/seed/agents/competitive-researcher.md +2 -1
  214. package/src/seed/agents/demo-video-builder.md +98 -87
  215. package/src/seed/agents/dev-lead.md +3 -3
  216. package/src/seed/agents/project-home-builder.md +9 -31
  217. package/src/seed/agents/validator.md +23 -23
  218. package/dist/assets/AppSettings-DExeJhqQ.js +0 -2
  219. package/dist/assets/HomeClaudeConfig-CTp2tkZ4.js +0 -3
  220. package/dist/assets/Scheduler-cyr61UAC.js +0 -16
  221. package/dist/assets/ViewTabs-DXhOWFG0.js +0 -1
  222. package/dist/assets/index-B2TQz3nd.js +0 -3121
  223. package/src/main/lib/epic/epicStateWatcher.cjs +0 -157
@@ -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
+ };
@@ -26,6 +26,7 @@
26
26
  */
27
27
 
28
28
  const fs = require('node:fs');
29
+ const path = require('node:path');
29
30
  const { assertOpsWrite, opsPath } = require('../opsOwnership.cjs');
30
31
  const atomicFs = require('../util/atomicFs.cjs');
31
32
 
@@ -78,6 +79,38 @@ function mirrorEpicStatus(cwd, epicId, { session = null, status = null, archived
78
79
  atomicFs.writeJsonAtomicSync(file, merged);
79
80
  }
80
81
 
82
+ /**
83
+ * readEpicMirrorStatus(cwd, epicId) → the status recorded in the Epic's
84
+ * mirror/archive file (top-level `status`, else `session.status`), or null
85
+ * when the file is missing, unreadable, or carries none.
86
+ */
87
+ function readEpicMirrorStatus(cwd, epicId) {
88
+ if (!cwd || !epicId) return null;
89
+ let file;
90
+ try { file = epicMirrorPath(cwd, epicId); } catch { return null; }
91
+ const existing = readExistingMirror(file);
92
+ const st = existing.status || (existing.session && existing.session.status) || null;
93
+ return typeof st === 'string' ? st : null;
94
+ }
95
+
96
+ const MIRROR_MARKER = `${path.sep}session-manager-operations${path.sep}prompt-sessions${path.sep}`;
97
+
98
+ /**
99
+ * parseEpicMirrorPath(abs) → { cwd, epicId } when `abs` is exactly an Epic's
100
+ * `prompt-sessions/<epicId>.json` file (no deeper subpath), else null.
101
+ */
102
+ function parseEpicMirrorPath(abs) {
103
+ if (typeof abs !== 'string' || !abs) return null;
104
+ const resolved = path.resolve(abs);
105
+ const idx = resolved.lastIndexOf(MIRROR_MARKER);
106
+ if (idx === -1) return null;
107
+ const rest = resolved.slice(idx + MIRROR_MARKER.length);
108
+ if (!rest.endsWith('.json') || rest.includes(path.sep)) return null;
109
+ const epicId = rest.slice(0, -'.json'.length);
110
+ if (!epicId || epicId === 'active-index') return null;
111
+ return { cwd: resolved.slice(0, idx), epicId };
112
+ }
113
+
81
114
  /**
82
115
  * removeEpicMirror(cwd, epicId) — best-effort delete of the mirror file, used
83
116
  * only by epicMint.cjs's removeEpic() rollback (undoing a mint whose caller
@@ -90,4 +123,4 @@ function removeEpicMirror(cwd, epicId) {
90
123
  } catch { /* never existed, or already gone */ }
91
124
  }
92
125
 
93
- module.exports = { mirrorEpicStatus, removeEpicMirror, epicMirrorPath };
126
+ module.exports = { mirrorEpicStatus, removeEpicMirror, epicMirrorPath, readEpicMirrorStatus, parseEpicMirrorPath };
@@ -0,0 +1,139 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * epicTransitions.cjs — the ONE place an Epic's `status` changes after mint.
5
+ * Mint (birth as `proposed`) stays in epicMint.cjs; every later edge
6
+ * (complete, discard, reopen) goes through `transitionEpic` here.
7
+ *
8
+ * The status law itself lives in
9
+ * session-manager-operations/prompt-sessions/README.md#lifecycle — link it,
10
+ * never restate it. This module only encodes its edges as a table.
11
+ *
12
+ * Semantics copy lib/scheduler/scheduleJobTransitions.cjs's transitionJob:
13
+ * - identity (status unchanged) is a no-op success, nothing recorded;
14
+ * - a legal edge mutates `epic.status`, writes an `epic_transition` audit
15
+ * record and appends `epic.status_changed` to the Epic's event log
16
+ * (fire-and-forget — a log failure never blocks the transition);
17
+ * - an illegal edge is refused: the Epic is left untouched, an
18
+ * `epic_transition_refused` audit record is written, and false is
19
+ * returned. Under test (NODE_ENV=test or VITEST set) it throws instead, so
20
+ * a call site asking for an illegal edge fails its own test loudly.
21
+ *
22
+ * Plain Node module (no Electron deps), like epicMint.cjs.
23
+ */
24
+
25
+ const auditLog = require('../telemetry/auditLog.cjs');
26
+ // Module objects (not destructured) so tests can stub the audit + event emits.
27
+ const epicEventLog = require('./epicEventLog.cjs');
28
+ const opsErrorLog = require('../telemetry/opsErrorLog.cjs');
29
+
30
+ /**
31
+ * Explicit from->to edges (see the README link above for what each means).
32
+ * proposed->completed is Discard on a proposal, which the lifecycle law lists
33
+ * as entering `completed` alongside markCompleted.
34
+ * @type {Readonly<Record<string, readonly string[]>>}
35
+ */
36
+ const EPIC_LEGAL_TRANSITIONS = Object.freeze({
37
+ proposed: Object.freeze(['active', 'completed']),
38
+ active: Object.freeze(['completed']),
39
+ completed: Object.freeze(['active']),
40
+ });
41
+
42
+ let refusedTransitionCount = 0;
43
+
44
+ function isTestEnv() {
45
+ return process.env.NODE_ENV === 'test' || !!process.env.VITEST;
46
+ }
47
+
48
+ /**
49
+ * @param {string|null|undefined} from
50
+ * @param {string|null|undefined} to
51
+ */
52
+ function isLegalEpicTransition(from, to) {
53
+ if (from === to && typeof from === 'string' && from in EPIC_LEGAL_TRANSITIONS) return true;
54
+ if (typeof from !== 'string' || typeof to !== 'string') return false;
55
+ const edges = EPIC_LEGAL_TRANSITIONS[from];
56
+ return Array.isArray(edges) && edges.includes(to);
57
+ }
58
+
59
+ /**
60
+ * @param {string} cwd
61
+ * @param {string} epicId
62
+ * @param {Record<string, unknown>} event
63
+ */
64
+ function emitEpicEvent(cwd, epicId, event) {
65
+ /** @param {unknown} err */
66
+ const onError = (err) => {
67
+ try {
68
+ opsErrorLog.appendError({
69
+ cwd,
70
+ scope: 'epic',
71
+ level: 'error',
72
+ epicId,
73
+ message: `epic event append failed (${String(event.kind)}): ${err instanceof Error ? err.message : String(err)}`,
74
+ meta: { kind: event.kind ?? null },
75
+ });
76
+ } catch { /* logging must never be the thing that fails */ }
77
+ };
78
+ try {
79
+ const p = epicEventLog.appendEpicEvent(cwd, epicId, event);
80
+ if (p && typeof p.catch === 'function') p.catch(onError);
81
+ } catch (err) {
82
+ onError(err);
83
+ }
84
+ }
85
+
86
+ /**
87
+ * transitionEpic(epic, to, { reason, source, allowAnyFrom }) → boolean.
88
+ * Mutates `epic.status` in place on success. `epic.id` and `epic.cwd` name
89
+ * the event log the transition is appended to (skipped when either is
90
+ * missing). `allowAnyFrom` is the same narrow data-repair hatch transitionJob
91
+ * has: a record with no readable prior status still goes through this
92
+ * chokepoint (mutation, audit, event) without consulting the table.
93
+ *
94
+ * @param {{ id?: string, cwd?: string, status?: string|null } & Record<string, unknown>} epic
95
+ * @param {string} to
96
+ * @param {{ reason?: string|null, source?: string|null, allowAnyFrom?: boolean }} [opts]
97
+ */
98
+ function transitionEpic(epic, to, { reason = null, source = null, allowAnyFrom = false } = {}) {
99
+ if (!epic || typeof epic !== 'object') return false;
100
+ const from = epic.status ?? null;
101
+ const epicId = typeof epic.id === 'string' ? epic.id : null;
102
+ const cwd = typeof epic.cwd === 'string' ? epic.cwd : null;
103
+
104
+ const toKnown = typeof to === 'string' && to in EPIC_LEGAL_TRANSITIONS;
105
+ if (!toKnown || (!allowAnyFrom && !isLegalEpicTransition(from, to))) {
106
+ refusedTransitionCount += 1;
107
+ const msg = `[epicTransitions] illegal transition refused: epicId=${epicId ?? '(unknown)'} `
108
+ + `from=${from ?? '(none)'} to=${to ?? '(none)'} reason=${reason ?? '(none)'} source=${source ?? '(none)'}`;
109
+ console.error(msg);
110
+ auditLog.appendAuditEvent('epic_transition_refused', { epicId, cwd, from, to: to ?? null, reason, source });
111
+ if (isTestEnv()) throw new Error(msg);
112
+ return false;
113
+ }
114
+
115
+ if (from === to) return true; // identity — nothing changed, nothing to record
116
+
117
+ epic.status = to;
118
+ auditLog.appendAuditEvent('epic_transition', { epicId, cwd, from, to, reason, source });
119
+ if (epicId && cwd) {
120
+ emitEpicEvent(cwd, epicId, { kind: 'epic.status_changed', from, to, reason, source });
121
+ }
122
+ return true;
123
+ }
124
+
125
+ function getRefusedEpicTransitionCount() {
126
+ return refusedTransitionCount;
127
+ }
128
+
129
+ function _resetRefusedEpicTransitionCountForTests() {
130
+ refusedTransitionCount = 0;
131
+ }
132
+
133
+ module.exports = {
134
+ EPIC_LEGAL_TRANSITIONS,
135
+ isLegalEpicTransition,
136
+ transitionEpic,
137
+ getRefusedEpicTransitionCount,
138
+ _resetRefusedEpicTransitionCountForTests,
139
+ };
@@ -68,7 +68,74 @@ function recordFolderLines(cwd, epicId) {
68
68
  * (plan-records/<epicId>/, never committed), so the digest names that
69
69
  * absolute folder plus the legacy reviews/validation/<epicId>/ one.
70
70
  */
71
- function buildSettledDigest(settle, { epicId, notValidatedReason, cwd } = {}) {
71
+ const SEVERITY_ORDER = ['Critical', 'Important', 'Minor'];
72
+ const MAX_FINDING_LINES = 50;
73
+
74
+ function severityRank(sev) {
75
+ const i = SEVERITY_ORDER.indexOf(String(sev || ''));
76
+ return i === -1 ? SEVERITY_ORDER.length : i;
77
+ }
78
+
79
+ /** Collapse every whitespace run (newlines, tabs) to one space and trim. */
80
+ function oneLine(x) {
81
+ return String(x ?? '').replace(/\s+/g, ' ').trim();
82
+ }
83
+
84
+ /**
85
+ * Findings section lines: every finding gets an outcome in the same turn —
86
+ * Minor ones are the ones that get dropped when only verdict slugs are listed.
87
+ * Critical first, then Important, then Minor (stable within a severity).
88
+ */
89
+ function findingLines(findings) {
90
+ const list = (Array.isArray(findings) ? findings : []).filter((f) => f && typeof f === 'object');
91
+ if (!list.length) return [];
92
+ const sorted = list
93
+ .map((f, i) => ({ f, i }))
94
+ .sort((a, b) => (severityRank(a.f.severity) - severityRank(b.f.severity)) || (a.i - b.i))
95
+ .map((x) => x.f);
96
+ const shown = sorted.slice(0, MAX_FINDING_LINES);
97
+ const out = [
98
+ '', `Findings (${list.length}) — give each one an outcome in this turn: a fix PRD or a one-line close reason:`,
99
+ ...shown.map((f) => {
100
+ const text = oneLine(f.text);
101
+ const file = oneLine(f.file);
102
+ return `- [${oneLine(f.severity)}] ${oneLine(f.prd)}:${text ? ` ${text}` : ''}${file ? ` (${file})` : ''}`;
103
+ }),
104
+ ];
105
+ if (sorted.length > shown.length) out.push(`- …and ${sorted.length - shown.length} more in the records`);
106
+ return out;
107
+ }
108
+
109
+ /**
110
+ * Flatten verdict records ({ prd, at, findings[] }) to digest findings, keeping
111
+ * only verdicts saved after `sinceMs` (null = keep all). A verdict with no
112
+ * parseable `at` is kept only when there is no previous digest.
113
+ */
114
+ function collectFindings(verdicts, sinceMs) {
115
+ const out = [];
116
+ for (const v of Array.isArray(verdicts) ? verdicts : []) {
117
+ if (!v || !Array.isArray(v.findings) || !v.findings.length) continue;
118
+ if (sinceMs != null) {
119
+ const t = typeof v.at === 'string' ? Date.parse(v.at) : NaN;
120
+ if (!Number.isFinite(t) || t <= sinceMs) continue;
121
+ }
122
+ for (const f of v.findings) {
123
+ if (!f || typeof f !== 'object') continue;
124
+ out.push({ prd: v.prd, severity: f.severity, text: f.text, file: f.file });
125
+ }
126
+ }
127
+ return out;
128
+ }
129
+
130
+ function defaultReadVerdictFiles(cwd, epicId) {
131
+ try {
132
+ return require('./epicOutsideRead.cjs').readVerdictFiles(cwd, epicId);
133
+ } catch {
134
+ return [];
135
+ }
136
+ }
137
+
138
+ function buildSettledDigest(settle, { epicId, notValidatedReason, cwd, findings } = {}) {
72
139
  const s = settle || {};
73
140
  const verified = s.verified || [];
74
141
  const refuted = s.refuted || [];
@@ -99,6 +166,7 @@ function buildSettledDigest(settle, { epicId, notValidatedReason, cwd } = {}) {
99
166
  ...cancelled.map((c) => `- ${c}`),
100
167
  );
101
168
  }
169
+ lines.push(...findingLines(findings));
102
170
  if (notValidated.length) {
103
171
  lines.push(
104
172
  '', `Not validated (${notValidated.length}) — ${notValidatedReason || 'no validator checked them'}:`,
@@ -121,7 +189,7 @@ const _rowInEpic = (r, epicId) => r && (r.epicId === epicId || r.sourcePromptId
121
189
 
122
190
  /**
123
191
  * runEpicSettle({ cwd, epicId }, deps) → { action, reason?, slug? }
124
- * Never throws. Actions: 'none' | 'sweep-queued' | 'digest-sent'.
192
+ * Never throws. Actions: 'none' | 'sweep-queued' | 'digest-sent' | 'digest-held'.
125
193
  */
126
194
  async function runEpicSettle({ cwd, epicId } = {}, deps = {}) {
127
195
  const {
@@ -134,6 +202,7 @@ async function runEpicSettle({ cwd, epicId } = {}, deps = {}) {
134
202
  jobBudget,
135
203
  sendPrompt,
136
204
  appendResponseEvent,
205
+ readVerdictFiles = defaultReadVerdictFiles,
137
206
  now = Date.now,
138
207
  log = console,
139
208
  } = deps;
@@ -220,8 +289,29 @@ async function runEpicSettle({ cwd, epicId } = {}, deps = {}) {
220
289
  }
221
290
  }
222
291
 
223
- const prompt = buildSettledDigest(digestSettle, { epicId, notValidatedReason, cwd });
224
- sendPrompt(epicId, prompt, { origin: 'scheduler' });
292
+ let findings = [];
293
+ try {
294
+ const sinceMs = newestDigest ? Date.parse(newestDigest.at) : null;
295
+ findings = collectFindings(
296
+ (await readVerdictFiles(cwd, epicId)) || [],
297
+ sinceMs != null && Number.isFinite(sinceMs) ? sinceMs : null,
298
+ );
299
+ } catch (e) {
300
+ try { (log || console).error('[epicValidationHook] readVerdictFiles failed', epicId, e); } catch { /* noop */ }
301
+ }
302
+ const prompt = buildSettledDigest(digestSettle, { epicId, notValidatedReason, cwd, findings });
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
+ }
225
315
  await appendResponseEvent(
226
316
  cwd, epicId,
227
317
  `Plan digest sent: ${settle.verified.length} verified, ${settle.refuted.length} refuted, ${settle.uncovered.length} not validated`,
@@ -73,8 +73,9 @@ async function writeGuardSpawnSettingsFile({ spawnCwd, homeDir = os.homedir(), d
73
73
  }
74
74
  }
75
75
 
76
- /** Every tool class guard-tool-risk.cjs can mark: Bash rules, file writes, MCP calls. */
77
- const TOOL_RISK_MATCHER = 'Bash|Write|Edit|NotebookEdit|mcp__.*';
76
+ /** Every tool class guard-tool-risk.cjs can mark (Bash rules, file writes, MCP calls), plus
77
+ * WebFetch/WebSearch, which it only observes for environment would-block reports. */
78
+ const TOOL_RISK_MATCHER = 'Bash|Write|Edit|NotebookEdit|WebFetch|WebSearch|mcp__.*';
78
79
 
79
80
  /**
80
81
  * Settings carrying ONLY the guard-tool-risk PreToolUse hook, for headless