claude-code-session-manager 0.141.0 → 0.142.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 (200) hide show
  1. package/README.md +80 -70
  2. package/bin/cli.cjs +11 -0
  3. package/dist/assets/AppSettings-BcZgIvvY.js +2 -0
  4. package/dist/assets/{History-DJMiuXyK.js → History-DpZuJXi1.js} +1 -1
  5. package/dist/assets/HomeClaudeConfig-D32ZJtU-.js +3 -0
  6. package/dist/assets/{Panel-Bf1Cf8UL.js → Panel-BjdJjhqt.js} +1 -1
  7. package/dist/assets/{ProjectClaudeConfig-BWPpypf9.js → ProjectClaudeConfig-BTClYV6i.js} +7 -7
  8. package/dist/assets/Scheduler-DPobKx1Z.js +16 -0
  9. package/dist/assets/{SkillReferenceGraph-Ba4TkX2C.js → SkillReferenceGraph-Cqyu4mef.js} +1 -1
  10. package/dist/assets/{Skills-C1v91GEO.js → Skills-vv0noNVI.js} +5 -5
  11. package/dist/assets/{TiptapBody-BrcWVpiW.js → TiptapBody-CXi8Pvut.js} +1 -1
  12. package/dist/assets/Toggle-CiYCWLjh.js +1 -0
  13. package/dist/assets/{VoiceButton-qivnDV6K.js → VoiceButton-4NKKd1sC.js} +1 -1
  14. package/dist/assets/{historyTotals-CMCPTKqC.js → historyTotals-DDunb8Ch.js} +1 -1
  15. package/dist/assets/index-Cn5E9958.js +3133 -0
  16. package/dist/assets/{index-DKXdXfka.css → index-DVHIHoJf.css} +1 -1
  17. package/dist/index.html +2 -2
  18. package/dist-web/app.css +1 -1
  19. package/dist-web/app.js +496 -484
  20. package/package.json +4 -2
  21. package/plugins/AGENTS.md +4 -3
  22. package/plugins/session-manager-dev/hooks/hooks.json +15 -0
  23. package/plugins/session-manager-dev/hooks/residue-check.cjs +241 -0
  24. package/plugins/session-manager-dev/skills/develop/SKILL.md +52 -18
  25. package/plugins/session-manager-dev/skills/develop/standards.md +3 -2
  26. package/scripts/README.md +1 -0
  27. package/scripts/hooks/guard-tool-risk.cjs +5 -1
  28. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +158 -1
  29. package/scripts/scheduler-mcp-server.cjs +732 -110
  30. package/src/main/adminRouteRegistry.cjs +59 -0
  31. package/src/main/agentLibrary.cjs +72 -4
  32. package/src/main/agentsIpc.cjs +3 -2
  33. package/src/main/build-info.json +4 -4
  34. package/src/main/chatRunner.cjs +231 -16
  35. package/src/main/config.cjs +30 -0
  36. package/src/main/docEdit.cjs +4 -2
  37. package/src/main/health.cjs +91 -0
  38. package/src/main/index.cjs +98 -48
  39. package/src/main/ipcSchemas.cjs +161 -8
  40. package/src/main/lib/AGENTS.md +1 -1
  41. package/src/main/lib/chatBootRecovery.cjs +2 -0
  42. package/src/main/lib/claude/agentModelResolve.cjs +51 -25
  43. package/src/main/lib/claude/agentSnapshot.cjs +186 -0
  44. package/src/main/lib/claude/environmentProfiles.cjs +242 -0
  45. package/src/main/lib/claude/jobSandboxPolicy.cjs +241 -33
  46. package/src/main/lib/claude/personaToolScope.cjs +82 -31
  47. package/src/main/lib/claude/runClaudeP.cjs +4 -2
  48. package/src/main/lib/claude/toolRiskMarks.cjs +41 -1
  49. package/src/main/lib/claude/usageCircuit.cjs +49 -21
  50. package/src/main/lib/claude/vaultRefs.cjs +277 -0
  51. package/src/main/lib/demo-video-kit/capture.cjs +282 -12
  52. package/src/main/lib/demo-video-kit/cast.md +43 -0
  53. package/src/main/lib/demo-video-kit/character.cjs +722 -30
  54. package/src/main/lib/demo-video-kit/checks.cjs +120 -1
  55. package/src/main/lib/demo-video-kit/export.cjs +218 -0
  56. package/src/main/lib/demo-video-kit/frames.cjs +104 -9
  57. package/src/main/lib/demo-video-kit/kind-marketing.md +121 -0
  58. package/src/main/lib/demo-video-kit/kind-tiktok.md +99 -0
  59. package/src/main/lib/demo-video-kit/kokoroSay.cjs +205 -0
  60. package/src/main/lib/demo-video-kit/project-home-html.md +43 -0
  61. package/src/main/lib/demo-video-kit/resumableRun.cjs +298 -0
  62. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  63. package/src/main/lib/demo-video-kit/voiceLane.cjs +233 -0
  64. package/src/main/lib/demo-video-kit/voiceLibrary.cjs +312 -0
  65. package/src/main/lib/epic/artifactAdminRoutes.cjs +211 -0
  66. package/src/main/lib/epic/artifactIpc.cjs +153 -0
  67. package/src/main/lib/epic/artifactNotice.cjs +72 -0
  68. package/src/main/lib/epic/artifactRetention.cjs +310 -0
  69. package/src/main/lib/epic/artifactStore.cjs +392 -0
  70. package/src/main/lib/epic/delegationReadiness.cjs +76 -2
  71. package/src/main/lib/epic/epicAgentRefresh.cjs +97 -0
  72. package/src/main/lib/epic/epicEventLog.cjs +214 -0
  73. package/src/main/lib/epic/epicMint.cjs +43 -1
  74. package/src/main/lib/epic/epicOutsideRead.cjs +1 -0
  75. package/src/main/lib/epic/epicOutsideState.cjs +18 -4
  76. package/src/main/lib/epic/epicPurge.cjs +347 -0
  77. package/src/main/lib/epic/epicReopen.cjs +5 -2
  78. package/src/main/lib/epic/epicSettle.cjs +4 -13
  79. package/src/main/lib/epic/epicSpawnPlan.cjs +57 -4
  80. package/src/main/lib/epic/epicStatusMirror.cjs +34 -1
  81. package/src/main/lib/epic/epicTransitions.cjs +139 -0
  82. package/src/main/lib/epic/epicValidationHook.cjs +81 -2
  83. package/src/main/lib/epic/guardSpawnSettings.cjs +3 -2
  84. package/src/main/lib/externalContract.cjs +37 -4
  85. package/src/main/lib/feedback-remote/crossProjectReply.cjs +389 -126
  86. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -3
  87. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +11 -6
  88. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +26 -1
  89. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +5 -2
  90. package/src/main/lib/feedback-remote/feedbackBoxDrain.cjs +409 -0
  91. package/src/main/lib/feedback-remote/feedbackBoxKeys.cjs +218 -0
  92. package/src/main/lib/feedback-remote/feedbackEnvelope.cjs +163 -0
  93. package/src/main/lib/feedback-remote/feedbackRelayClient.cjs +164 -0
  94. package/src/main/lib/feedback-remote/feedbackReport.cjs +234 -0
  95. package/src/main/lib/feedback-remote/feedbackSeal.cjs +217 -0
  96. package/src/main/lib/feedback-remote/localAdminHttp.cjs +108 -2
  97. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +2 -1
  98. package/src/main/lib/feedback-remote/needsYouIpc.cjs +17 -0
  99. package/src/main/lib/feedback-remote/needsYouStore.cjs +177 -6
  100. package/src/main/lib/feedback-remote/pendingReplies.cjs +189 -0
  101. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +188 -10
  102. package/src/main/lib/feedback-remote/serviceClient.cjs +429 -0
  103. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +252 -0
  104. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +284 -0
  105. package/src/main/lib/feedback-remote/servicePairings.cjs +313 -0
  106. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +290 -0
  107. package/src/main/lib/feedback-remote/siteFeedbackAdminRoutes.cjs +295 -0
  108. package/src/main/lib/feedback-remote/siteFeedbackInbox.cjs +598 -0
  109. package/src/main/lib/feedback-remote/siteFeedbackIpc.cjs +86 -0
  110. package/src/main/lib/feedback-remote/siteFeedbackService.cjs +477 -0
  111. package/src/main/lib/git/worktreeDeps.cjs +77 -2
  112. package/src/main/lib/mcpToolCatalog.cjs +304 -28
  113. package/src/main/lib/opsOwnership.cjs +29 -1
  114. package/src/main/lib/opsRetentionSettings.cjs +27 -5
  115. package/src/main/lib/persona-macro/builtinMacros.cjs +7 -2
  116. package/src/main/lib/persona-macro/macroJobDispatch.cjs +52 -8
  117. package/src/main/lib/persona-macro/macroJobIpc.cjs +16 -6
  118. package/src/main/lib/persona-macro/macroLibrary.cjs +49 -7
  119. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +83 -0
  120. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +3 -0
  121. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +263 -0
  122. package/src/main/lib/phaseProjection.cjs +103 -0
  123. package/src/main/lib/prd/depSlugResolve.cjs +4 -13
  124. package/src/main/lib/prd/prdBodyPatch.cjs +12 -17
  125. package/src/main/lib/prd/prdCreate.cjs +41 -5
  126. package/src/main/lib/prd/prdCriteria.cjs +225 -0
  127. package/src/main/lib/prd/prdFrontmatter.cjs +43 -3
  128. package/src/main/lib/prd/prdGateFiles.cjs +125 -49
  129. package/src/main/lib/prd/prdSizing.cjs +3 -1
  130. package/src/main/lib/process/cleanEnv.cjs +52 -1
  131. package/src/main/lib/process/leftoverRenice.cjs +178 -0
  132. package/src/main/lib/process/memoryScope.cjs +31 -3
  133. package/src/main/lib/project-pages/pagesLibrary.cjs +72 -6
  134. package/src/main/lib/project-pages/videoReviewIpc.cjs +3 -2
  135. package/src/main/lib/project-pages/voiceAdminRoutes.cjs +175 -0
  136. package/src/main/lib/project-pages/voicePreview.cjs +196 -0
  137. package/src/main/lib/project-pages/voicesIpc.cjs +186 -0
  138. package/src/main/lib/promptSessionSchema.cjs +6 -0
  139. package/src/main/lib/scheduler/cancelledRow.cjs +57 -0
  140. package/src/main/lib/scheduler/cpuSample.cjs +133 -42
  141. package/src/main/lib/scheduler/criteriaChecks.cjs +169 -0
  142. package/src/main/lib/scheduler/definitionOfDone.cjs +44 -5
  143. package/src/main/lib/scheduler/jobMemoryStats.cjs +313 -0
  144. package/src/main/lib/scheduler/loadGate.cjs +82 -4
  145. package/src/main/lib/scheduler/planRecordHarvest.cjs +32 -2
  146. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +133 -0
  147. package/src/main/lib/scheduler/runLogRetention.cjs +42 -1
  148. package/src/main/lib/scheduler/scheduleJobSchema.cjs +5 -0
  149. package/src/main/lib/scheduler/scheduleJobTransitions.cjs +47 -0
  150. package/src/main/lib/scheduler/schedulerConfig.cjs +47 -0
  151. package/src/main/lib/scheduler/schedulerPaths.cjs +0 -3
  152. package/src/main/lib/scheduler/schedulerRuntimeState.cjs +50 -1
  153. package/src/main/lib/scheduler/sessionSlots.cjs +5 -1
  154. package/src/main/lib/scheduler/slotsRoute.cjs +237 -0
  155. package/src/main/lib/scheduler/toolClearance.cjs +258 -0
  156. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +140 -10
  157. package/src/main/lib/tasks/memoryConsolidation.cjs +300 -0
  158. package/src/main/lib/tasks/mitigationReview.cjs +294 -0
  159. package/src/main/lib/tasks/taskAdminRoutes.cjs +312 -22
  160. package/src/main/lib/tasks/taskIpc.cjs +22 -18
  161. package/src/main/lib/tasks/taskLedger.cjs +147 -25
  162. package/src/main/lib/tasks/taskRun.cjs +186 -17
  163. package/src/main/lib/tasks/taskSwitch.cjs +85 -12
  164. package/src/main/lib/tasks/taskSwitchRoute.cjs +172 -0
  165. package/src/main/lib/telemetry/auditEvents.cjs +207 -6
  166. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +198 -6
  167. package/src/main/lib/telemetry/webhookDelivery.cjs +205 -0
  168. package/src/main/lib/telemetry/webhookRegistry.cjs +281 -0
  169. package/src/main/lib/toolUseClassify.cjs +181 -0
  170. package/src/main/lib/util/smfileRange.cjs +77 -0
  171. package/src/main/projectPages.cjs +3 -1
  172. package/src/main/promptSessionEvents.cjs +5 -0
  173. package/src/main/pty.cjs +68 -0
  174. package/src/main/queueOps.cjs +32 -13
  175. package/src/main/runVerify.cjs +74 -9
  176. package/src/main/scheduler/AGENTS.md +1 -0
  177. package/src/main/scheduler/budget.cjs +6 -5
  178. package/src/main/scheduler/prdParser.cjs +46 -13
  179. package/src/main/scheduler/reviewLadder.cjs +9 -25
  180. package/src/main/scheduler/utilizationHold.cjs +101 -0
  181. package/src/main/scheduler.cjs +1414 -189
  182. package/src/main/templates/PRD_AUTHORING.md +5 -2
  183. package/src/main/webRemote.cjs +463 -6
  184. package/src/preload/api.d.ts +529 -38
  185. package/src/preload/apiSurface.json +209 -7
  186. package/src/preload/index.cjs +46 -1
  187. package/src/seed/agents/architect.md +6 -1
  188. package/src/seed/agents/blender-artist.md +2 -1
  189. package/src/seed/agents/competitive-analyst.md +3 -1
  190. package/src/seed/agents/competitive-researcher.md +2 -1
  191. package/src/seed/agents/demo-video-builder.md +87 -83
  192. package/src/seed/agents/dev-lead.md +3 -3
  193. package/src/seed/agents/project-home-builder.md +9 -31
  194. package/src/seed/agents/validator.md +9 -10
  195. package/dist/assets/AppSettings-DExeJhqQ.js +0 -2
  196. package/dist/assets/HomeClaudeConfig-CTp2tkZ4.js +0 -3
  197. package/dist/assets/Scheduler-cyr61UAC.js +0 -16
  198. package/dist/assets/ViewTabs-DXhOWFG0.js +0 -1
  199. package/dist/assets/index-B2TQz3nd.js +0 -3121
  200. package/src/main/lib/epic/epicStateWatcher.cjs +0 -157
@@ -20,6 +20,17 @@
20
20
  *
21
21
  * Assumes rows are appended in non-decreasing `at` order (they are: appendAuditEvent
22
22
  * stamps `now` at append time). Rows that fail to parse or lack a string `at` are skipped.
23
+ *
24
+ * epic_state_changed is read from the per-Epic event logs, not from audit rows:
25
+ * every `epic.status_changed` event (written by epicTransitions.transitionEpic at
26
+ * the transition, lib/epic/epicEventLog.cjs) of every registered project becomes
27
+ * one row { at, kind: 'epic_state_changed', cwd, epicId, from, to, externalRef? }
28
+ * (epicStateRowOf), merged into the audit rows by `at` (ties: audit rows first,
29
+ * then cwd, epicId, seq) so one cursor covers both. Status values map to the
30
+ * outside-state words of lib/epic/epicOutsideState.cjs (STATUS_TO_OUTSIDE).
31
+ * Legacy epic_state_changed audit rows already in the log stay readable.
32
+ * Projects come from the `projectRoots` option, else — only when `target` is not
33
+ * given — promptSessionsIpc's registered projects (cached EPIC_ROOTS_TTL_MS).
23
34
  */
24
35
  'use strict';
25
36
 
@@ -28,6 +39,7 @@ const path = require('node:path');
28
39
  const zlib = require('node:zlib');
29
40
 
30
41
  const { auditLogPath, readTail } = require('./auditLog.cjs');
42
+ const { opsPath } = require('../opsOwnership.cjs');
31
43
 
32
44
  const OUTSIDE_EVENT_KINDS = Object.freeze(['epic_state_changed', 'job_transition', 'epic_cross_project_reply', 'needs_you_answered']);
33
45
  const DEFAULT_KINDS = Object.freeze(['epic_state_changed']);
@@ -121,12 +133,194 @@ function withOrdinals(rows) {
121
133
 
122
134
  const cursorOf = (at, n) => `${at}~${n}`;
123
135
 
136
+ // ── epic_state_changed from the per-Epic event logs ──
137
+
138
+ const EPIC_STATE_KIND = 'epic_state_changed';
139
+ const EPIC_STATUS_EVENT = 'epic.status_changed';
140
+ /** Lifecycle status → the outside-state word epicOutsideState.cjs gives an Epic in that status. */
141
+ const STATUS_TO_OUTSIDE = Object.freeze({ proposed: 'awaiting_approval', active: 'open', completed: 'closed' });
142
+ const EPIC_ROOTS_TTL_MS = 10000;
143
+ const EPIC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
144
+
145
+ /** @param {unknown} v */
146
+ const nonEmpty = (v) => (typeof v === 'string' && v !== '' ? v : null);
147
+ /** @param {unknown} v @returns {v is Record<string, any>} */
148
+ const isObj = (v) => v != null && typeof v === 'object' && !Array.isArray(v);
149
+ /** @param {unknown} status */
150
+ const outsideOf = (status) => {
151
+ const s = nonEmpty(status);
152
+ if (s === null) return null;
153
+ return Object.prototype.hasOwnProperty.call(STATUS_TO_OUTSIDE, s) ? STATUS_TO_OUTSIDE[/** @type {'proposed'} */ (s)] : s;
154
+ };
155
+
124
156
  /**
125
- * @param {{ after?: string, kinds?: string[], limit?: number, target?: string, initialWindow?: number, maxArchiveGzBytes?: number }} [opts]
157
+ * One epic.status_changed event → its outside epic_state_changed row, or null.
158
+ * @param {string} cwd project root the event log belongs to
159
+ * @param {Record<string, any>} ev a parsed event-log record
160
+ * @param {string|null} [externalRef]
161
+ */
162
+ function epicStateRowOf(cwd, ev, externalRef = null) {
163
+ if (!isObj(ev) || ev.kind !== EPIC_STATUS_EVENT) return null;
164
+ const at = nonEmpty(ev.time);
165
+ const epicId = nonEmpty(ev.epicId);
166
+ if (!at || !epicId) return null;
167
+ /** @type {Record<string, any>} */
168
+ const row = { at, kind: EPIC_STATE_KIND, cwd, epicId, from: outsideOf(ev.from), to: outsideOf(ev.to) };
169
+ const ref = nonEmpty(ev.externalRef) || nonEmpty(externalRef);
170
+ if (ref) row.externalRef = ref;
171
+ return row;
172
+ }
173
+
174
+ /** events.jsonl path → { size, offset (end of last complete line), events } — read incrementally. */
175
+ const logCache = new Map();
176
+ /** active-index.json path → { mtimeMs, size, refs: Map<epicId, externalRef> }. */
177
+ const indexCache = new Map();
178
+ /** `${cwd}\0${epicId}` → externalRef, kept once seen (a completed Epic leaves the active index). */
179
+ const knownRefs = new Map();
180
+ let rootsCache = { at: 0, roots: /** @type {string[]} */ ([]) };
181
+
182
+ /** Status-change events of one event-log file, re-reading only bytes appended since the last call. */
183
+ function statusEventsOf(file) {
184
+ let size;
185
+ try { size = fs.statSync(file).size; } catch { logCache.delete(file); return []; }
186
+ let c = logCache.get(file);
187
+ if (!c || size < c.offset) c = { size: 0, offset: 0, events: [] };
188
+ if (size > c.offset) {
189
+ let text = '';
190
+ try {
191
+ const fd = fs.openSync(file, 'r');
192
+ try {
193
+ const buf = Buffer.alloc(size - c.offset);
194
+ const n = fs.readSync(fd, buf, 0, buf.length, c.offset);
195
+ text = buf.subarray(0, n).toString('utf8');
196
+ } finally { fs.closeSync(fd); }
197
+ } catch { return c.events; }
198
+ const end = text.lastIndexOf('\n');
199
+ if (end >= 0) {
200
+ const events = c.events.slice();
201
+ for (const line of text.slice(0, end).split('\n')) {
202
+ if (!line.includes(EPIC_STATUS_EVENT)) continue;
203
+ try {
204
+ const r = JSON.parse(line);
205
+ if (isObj(r) && r.kind === EPIC_STATUS_EVENT) events.push(r);
206
+ } catch { /* torn line */ }
207
+ }
208
+ c = { size, offset: c.offset + Buffer.byteLength(text.slice(0, end + 1), 'utf8'), events };
209
+ }
210
+ }
211
+ logCache.set(file, c);
212
+ return c.events;
213
+ }
214
+
215
+ /** externalRef per open Epic of one project, from its active index (cached by mtime + size). */
216
+ function activeRefs(root) {
217
+ let file;
218
+ try { file = opsPath(root, 'prompt-sessions', 'active-index.json'); } catch { return new Map(); }
219
+ let st;
220
+ try { st = fs.statSync(file); } catch { return new Map(); }
221
+ const c = indexCache.get(file);
222
+ if (c && c.mtimeMs === st.mtimeMs && c.size === st.size) return c.refs;
223
+ const refs = new Map();
224
+ try {
225
+ const data = JSON.parse(fs.readFileSync(file, 'utf8'));
226
+ const sessions = isObj(data) && isObj(data.sessions) ? data.sessions : {};
227
+ for (const [id, s] of Object.entries(sessions)) {
228
+ const ref = isObj(s) && isObj(s.source) ? nonEmpty(s.source.externalRef) : null;
229
+ if (ref) refs.set(id, ref);
230
+ }
231
+ } catch { /* unreadable index → no refs */ }
232
+ indexCache.set(file, { mtimeMs: st.mtimeMs, size: st.size, refs });
233
+ return refs;
234
+ }
235
+
236
+ /** Registered project roots, folded to project roots, de-duplicated. */
237
+ function defaultEpicRoots() {
238
+ if (rootsCache.at && Date.now() - rootsCache.at < EPIC_ROOTS_TTL_MS) return rootsCache.roots;
239
+ let raw = [];
240
+ try { raw = require('../../promptSessionsIpc.cjs').defaultProjectRoots() || []; } catch { raw = []; }
241
+ rootsCache = { at: Date.now(), roots: raw };
242
+ return raw;
243
+ }
244
+
245
+ /** @param {string[]} raw */
246
+ function foldRoots(raw) {
247
+ let rootOf = (/** @type {string} */ p) => p;
248
+ try { const { projectRootOf } = require('../activeSessions.cjs'); rootOf = (p) => projectRootOf(p) || p; } catch { /* keep as is */ }
249
+ const out = new Set();
250
+ for (const r of raw) {
251
+ if (typeof r !== 'string' || !r || !path.isAbsolute(r)) continue;
252
+ out.add(path.resolve(rootOf(r)).replace(/[\\/]+$/, ''));
253
+ }
254
+ return [...out].sort();
255
+ }
256
+
257
+ /**
258
+ * Every epic_state_changed row of the given projects, sorted by at, cwd, epicId, seq.
259
+ * Never throws.
260
+ * @param {string[]} roots
261
+ */
262
+ function readEpicStateRows(roots) {
263
+ const rows = [];
264
+ for (const root of foldRoots(roots)) {
265
+ let dir;
266
+ let names;
267
+ try { dir = opsPath(root, 'events'); names = fs.readdirSync(dir).filter((n) => EPIC_ID_RE.test(n)).sort(); } catch { continue; }
268
+ let refs = null;
269
+ for (const epicId of names) {
270
+ const events = statusEventsOf(path.join(dir, epicId, 'events.jsonl'));
271
+ if (!events.length) continue;
272
+ const key = `${root}\0${epicId}`;
273
+ if (!knownRefs.has(key)) {
274
+ refs = refs || activeRefs(root);
275
+ const ref = refs.get(epicId);
276
+ if (ref) knownRefs.set(key, ref);
277
+ }
278
+ for (const ev of events) {
279
+ const row = epicStateRowOf(root, ev, knownRefs.get(key) ?? null);
280
+ if (row) rows.push({ row, seq: Number.isInteger(ev.seq) ? ev.seq : 0 });
281
+ }
282
+ }
283
+ }
284
+ rows.sort((a, b) => (a.row.at < b.row.at ? -1 : a.row.at > b.row.at ? 1 : 0)
285
+ || (a.row.cwd < b.row.cwd ? -1 : a.row.cwd > b.row.cwd ? 1 : 0)
286
+ || (a.row.epicId < b.row.epicId ? -1 : a.row.epicId > b.row.epicId ? 1 : 0)
287
+ || a.seq - b.seq);
288
+ return rows.map((r) => r.row);
289
+ }
290
+
291
+ /** Merge epic rows into audit rows by `at`; audit rows win ties. Both inputs sorted. */
292
+ function mergeByAt(audit, epic) {
293
+ if (!epic.length) return audit;
294
+ const out = [];
295
+ let i = 0;
296
+ let j = 0;
297
+ while (i < audit.length || j < epic.length) {
298
+ if (j >= epic.length || (i < audit.length && audit[i].at <= epic[j].at)) out.push(audit[i++]);
299
+ else out.push(epic[j++]);
300
+ }
301
+ return out;
302
+ }
303
+
304
+ function _resetEpicStateCacheForTests() {
305
+ logCache.clear();
306
+ indexCache.clear();
307
+ knownRefs.clear();
308
+ rootsCache = { at: 0, roots: [] };
309
+ }
310
+
311
+ /**
312
+ * @param {{ after?: string, kinds?: string[], limit?: number, target?: string, initialWindow?: number, maxArchiveGzBytes?: number, projectRoots?: () => string[] }} [opts]
126
313
  * @returns {{ events: object[], next: string, more: boolean, gap: boolean }}
127
314
  */
128
- function readEventsAfter({ after, kinds, limit, target, initialWindow, maxArchiveGzBytes } = {}) {
315
+ function readEventsAfter({ after, kinds, limit, target, initialWindow, maxArchiveGzBytes, projectRoots } = {}) {
129
316
  const file = target ?? auditLogPath();
317
+ /** @type {object[]} */
318
+ let epicRows = [];
319
+ if (typeof projectRoots === 'function' || target === undefined) {
320
+ let roots = [];
321
+ try { roots = typeof projectRoots === 'function' ? (projectRoots() || []) : defaultEpicRoots(); } catch { roots = []; }
322
+ epicRows = readEpicStateRows(roots);
323
+ }
130
324
  const maxGz = Number.isFinite(maxArchiveGzBytes) && maxArchiveGzBytes >= 0 ? maxArchiveGzBytes : MAX_ARCHIVE_GZ_BYTES;
131
325
  const win = Number.isFinite(initialWindow) && initialWindow > 0 ? initialWindow : INITIAL_WINDOW;
132
326
  const kindSet = new Set(Array.isArray(kinds) && kinds.length ? kinds : DEFAULT_KINDS);
@@ -134,9 +328,12 @@ function readEventsAfter({ after, kinds, limit, target, initialWindow, maxArchiv
134
328
 
135
329
  if (after === undefined || after === null) {
136
330
  const probe = parseRows(readTail(Math.min(win, 64 * 1024), file));
137
- if (!probe.length && fileSize(file) === 0) return { events: [], next: START, more: false, gap: false };
138
- const lastAt = probe.length ? probe[probe.length - 1].at : null;
139
- const { rows } = loadLive(file, lastAt, win);
331
+ if (!probe.length && fileSize(file) === 0 && !epicRows.length) return { events: [], next: START, more: false, gap: false };
332
+ const epicLast = epicRows.length ? /** @type {{ at: string }} */ (epicRows[epicRows.length - 1]).at : null;
333
+ let lastAt = probe.length ? probe[probe.length - 1].at : null;
334
+ if (epicLast !== null && (lastAt === null || epicLast > lastAt)) lastAt = epicLast;
335
+ const live = fileSize(file) === 0 ? [] : loadLive(file, lastAt, win).rows;
336
+ const rows = mergeByAt(live, epicRows);
140
337
  if (!rows.length) return { events: [], next: START, more: false, gap: false };
141
338
  const ords = withOrdinals(rows);
142
339
  const last = ords[ords.length - 1];
@@ -157,6 +354,7 @@ function readEventsAfter({ after, kinds, limit, target, initialWindow, maxArchiv
157
354
  gap = archive.skipped || (rows.length > 0 && cur.at < rows[0].at);
158
355
  }
159
356
  }
357
+ rows = mergeByAt(rows, epicRows);
160
358
 
161
359
  const events = [];
162
360
  let more = false;
@@ -173,4 +371,7 @@ function readEventsAfter({ after, kinds, limit, target, initialWindow, maxArchiv
173
371
  return { events, next, more, gap };
174
372
  }
175
373
 
176
- module.exports = { OUTSIDE_EVENT_KINDS, readEventsAfter, CURSOR_FORM, INVALID_AUDIT_CURSOR, MAX_ARCHIVE_GZ_BYTES };
374
+ module.exports = {
375
+ OUTSIDE_EVENT_KINDS, readEventsAfter, CURSOR_FORM, INVALID_AUDIT_CURSOR, MAX_ARCHIVE_GZ_BYTES,
376
+ STATUS_TO_OUTSIDE, epicStateRowOf, _resetEpicStateCacheForTests,
377
+ };
@@ -8,28 +8,141 @@
8
8
  * → 400 { ok: false, error: 'invalid query', details } for an unknown kind,
9
9
  * an out-of-range limit, or a cursor readEventsAfter rejects.
10
10
  *
11
- * Writes no file and no audit row. Auth/loopback binding are the injected
11
+ * GET /admin/events?epicId=<id>[&cwd=<abs>][&after=<seq|start>][&kinds=<k1,k2>][&limit=<n>]
12
+ * → 200 { ok: true, events, cursor, hasMore } — replay of every event kind of
13
+ * that Epic from its per-Epic event log (lib/epic/epicEventLog.cjs
14
+ * readEpicEvents). `after` = the `cursor` (seq integer) of the previous
15
+ * page; absent or 'start' = from the first event. `kinds` filters to a
16
+ * subset of epicEventLog's EVENT_KINDS; `limit` defaults to 100 and is
17
+ * capped at 500. No cwd → the Epic's project is found among the
18
+ * registered projects (findEpicProject); an Epic no project holds → an
19
+ * empty page { events: [], cursor: <after>, hasMore: false }; one held by
20
+ * several → 409 { ok: false, error: 'ambiguous epic id', cwds }.
21
+ * → 400 { ok: false, error: 'invalid query', details } for a malformed
22
+ * epicId, cursor, kind, limit or cwd.
23
+ * Calls without epicId take the audit-log path above; its epic_state_changed
24
+ * rows come from every registered project's epic.status_changed events
25
+ * (auditEvents.cjs), so deps.projectRoots also scopes them.
26
+ *
27
+ * POST /admin/webhooks body { cwd, url, kinds } → 200 { ok: true, id, secret }
28
+ * GET /admin/webhooks?cwd=<abs> → 200 { ok: true, subscriptions } (no secrets)
29
+ * DELETE /admin/webhooks?cwd=<abs>&id=<wh_…> → 200 { ok: true, removed: true }
30
+ * Thin wrappers over webhookRegistry.cjs (the webhooks/ namespace's only
31
+ * writer). A refused URL or invalid kinds → 400 { ok: false, error: <code>,
32
+ * details }; an unknown id → 404; a bad cwd → 400 'invalid query'.
33
+ *
34
+ * The /admin/events routes write no file and no audit row. Auth/loopback binding are the injected
12
35
  * localAdminHttp.cjs transport's job (see index.cjs).
13
36
  */
14
37
  'use strict';
15
38
 
39
+ const path = require('node:path');
16
40
  const { schemas } = require('../../ipcSchemas.cjs');
17
- const { sendJson } = require('../feedback-remote/localAdminHttp.cjs');
41
+ const { sendJson, readBody } = require('../feedback-remote/localAdminHttp.cjs');
18
42
  const { readEventsAfter, INVALID_AUDIT_CURSOR } = require('./auditEvents.cjs');
19
43
 
20
- /** @param {{ registerRoute: Function }} adminHttp */
21
- function registerAdminRoute(adminHttp) {
44
+ const EPIC_MAX_LIMIT = 500;
45
+ const EPIC_DEFAULT_LIMIT = 100;
46
+ const EPIC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
47
+ const SEQ_CURSOR_RE = /^(?:0|[1-9]\d{0,15})$/;
48
+
49
+ /**
50
+ * Parse the epic-mode query by hand (the audit-mode schema strips unknown keys).
51
+ * @param {Record<string, string>} q
52
+ * @returns {{ ok: true, value: { epicId: string, cwd?: string, after: number, kinds?: string[], limit: number } } | { ok: false, details: string }}
53
+ */
54
+ function parseEpicQuery(q) {
55
+ const { EVENT_KINDS } = require('../epic/epicEventLog.cjs');
56
+ const epicId = q.epicId;
57
+ if (typeof epicId !== 'string' || !EPIC_ID_RE.test(epicId)) return { ok: false, details: 'epicId must match [A-Za-z0-9][A-Za-z0-9_-]{0,127}' };
58
+ let cwd;
59
+ if (q.cwd !== undefined) {
60
+ if (typeof q.cwd !== 'string' || q.cwd.length > 4096 || !path.isAbsolute(q.cwd)) return { ok: false, details: 'cwd must be an absolute path' };
61
+ cwd = q.cwd;
62
+ }
63
+ let after = 0;
64
+ if (q.after !== undefined && q.after !== 'start') {
65
+ if (typeof q.after !== 'string' || !SEQ_CURSOR_RE.test(q.after)) {
66
+ return { ok: false, details: `invalid epic event cursor ${JSON.stringify(q.after)}: expected a non-negative integer seq or 'start'` };
67
+ }
68
+ after = Number(q.after);
69
+ }
70
+ let kinds;
71
+ if (q.kinds !== undefined) {
72
+ kinds = String(q.kinds).split(',').map((k) => k.trim());
73
+ const known = new Set(EVENT_KINDS);
74
+ const bad = kinds.filter((k) => !known.has(k));
75
+ if (!kinds.length || bad.length) return { ok: false, details: `unknown event kind(s): ${bad.join(', ') || '(empty)'}` };
76
+ }
77
+ let limit = EPIC_DEFAULT_LIMIT;
78
+ if (q.limit !== undefined) {
79
+ if (!/^\d{1,9}$/.test(String(q.limit)) || Number(q.limit) < 1) return { ok: false, details: 'limit must be a positive integer' };
80
+ limit = Math.min(Number(q.limit), EPIC_MAX_LIMIT);
81
+ }
82
+ return { ok: true, value: { epicId, cwd, after, kinds, limit } };
83
+ }
84
+
85
+ /**
86
+ * @param {any} res @param {Record<string, string>} q
87
+ * @param {{ projectRoots?: () => string[] }} deps
88
+ */
89
+ async function serveEpicEvents(res, q, deps) {
90
+ const parsed = parseEpicQuery(q);
91
+ if (!parsed.ok) {
92
+ sendJson(res, 400, { ok: false, error: 'invalid query', details: parsed.details });
93
+ return;
94
+ }
95
+ const { epicId, after, kinds, limit } = parsed.value;
96
+ let cwd = parsed.value.cwd;
97
+ if (cwd === undefined) {
98
+ const { findEpicProject } = require('../epic/epicOutsideRead.cjs');
99
+ const found = findEpicProject(epicId, typeof deps.projectRoots === 'function' ? { projectRoots: deps.projectRoots } : {});
100
+ if (found && 'ambiguous' in found) {
101
+ sendJson(res, 409, { ok: false, error: 'ambiguous epic id', cwds: found.ambiguous });
102
+ return;
103
+ }
104
+ if (!found) {
105
+ sendJson(res, 200, { ok: true, events: [], cursor: after, hasMore: false });
106
+ return;
107
+ }
108
+ cwd = found.cwd;
109
+ }
110
+ const { readEpicEvents } = require('../epic/epicEventLog.cjs');
111
+ let page;
112
+ try {
113
+ page = await readEpicEvents(cwd, epicId, { after, kinds, limit });
114
+ } catch (e) {
115
+ sendJson(res, 400, { ok: false, error: 'invalid query', details: e instanceof Error ? e.message : String(e) });
116
+ return;
117
+ }
118
+ const { events, cursor, hasMore } = page;
119
+ sendJson(res, 200, { ok: true, events, cursor, hasMore });
120
+ }
121
+
122
+ /**
123
+ * @param {{ registerRoute: Function }} adminHttp
124
+ * @param {{ projectRoots?: () => string[] }} [deps] projectRoots overrides the registered-project list (tests)
125
+ */
126
+ function registerAdminRoute(adminHttp, deps = {}) {
22
127
  adminHttp.registerRoute('GET', '/admin/events', async (req, res, query) => {
128
+ const raw = Object.fromEntries(query ?? []);
129
+ if (raw.epicId !== undefined) {
130
+ await serveEpicEvents(res, raw, deps);
131
+ return;
132
+ }
23
133
  let input;
24
134
  try {
25
- input = schemas.adminListEventsQuery.parse(Object.fromEntries(query ?? []));
135
+ input = schemas.adminListEventsQuery.parse(raw);
26
136
  } catch (e) {
27
137
  sendJson(res, 400, { ok: false, error: 'invalid query', details: e?.issues ?? e?.message });
28
138
  return;
29
139
  }
30
140
  let result;
31
141
  try {
32
- result = readEventsAfter({ after: input.after, kinds: input.kinds, limit: input.limit });
142
+ /** @type {Parameters<typeof readEventsAfter>[0]} */
143
+ const opts = { after: input.after, kinds: input.kinds, limit: input.limit };
144
+ if (typeof deps.projectRoots === 'function') opts.projectRoots = deps.projectRoots;
145
+ result = readEventsAfter(opts);
33
146
  } catch (e) {
34
147
  if (e instanceof Error && /** @type {Error & { code?: unknown }} */ (e).code === INVALID_AUDIT_CURSOR) {
35
148
  sendJson(res, 400, { ok: false, error: 'invalid query', details: e.message });
@@ -40,6 +153,85 @@ function registerAdminRoute(adminHttp) {
40
153
  const { events, next, more, gap } = result;
41
154
  sendJson(res, 200, { ok: true, events, next, more, gap });
42
155
  });
156
+ registerWebhookRoutes(adminHttp);
157
+ }
158
+
159
+ /** @param {unknown} cwd */
160
+ function validCwd(cwd) {
161
+ return typeof cwd === 'string' && cwd.length <= 4096 && path.isAbsolute(cwd);
162
+ }
163
+
164
+ /**
165
+ * Map a webhookRegistry error to an HTTP response; rethrows anything else.
166
+ * @param {any} res @param {unknown} e
167
+ */
168
+ function sendWebhookError(res, e) {
169
+ const code = e instanceof Error ? /** @type {Error & { code?: unknown }} */ (e).code : undefined;
170
+ const details = e instanceof Error ? e.message : String(e);
171
+ if (code === 'webhook_url_refused' || code === 'webhook_kinds_invalid') {
172
+ sendJson(res, 400, { ok: false, error: code, details });
173
+ return;
174
+ }
175
+ if (code === 'webhook_not_found') {
176
+ sendJson(res, 404, { ok: false, error: code, details });
177
+ return;
178
+ }
179
+ if (e instanceof Error && /resolveProjectRoot|refusing to write/.test(e.message)) {
180
+ sendJson(res, 400, { ok: false, error: 'invalid query', details });
181
+ return;
182
+ }
183
+ throw e;
184
+ }
185
+
186
+ /** @param {{ registerRoute: Function }} adminHttp */
187
+ function registerWebhookRoutes(adminHttp) {
188
+ const registry = require('./webhookRegistry.cjs');
189
+ adminHttp.registerRoute('POST', '/admin/webhooks', async (/** @type {any} */ req, /** @type {any} */ res) => {
190
+ let body;
191
+ try {
192
+ const raw = await readBody(req);
193
+ body = raw ? JSON.parse(raw) : {};
194
+ } catch {
195
+ sendJson(res, 400, { ok: false, error: 'invalid JSON body' });
196
+ return;
197
+ }
198
+ if (!body || typeof body !== 'object' || Array.isArray(body) || !validCwd(body.cwd)) {
199
+ sendJson(res, 400, { ok: false, error: 'invalid query', details: 'cwd must be an absolute path' });
200
+ return;
201
+ }
202
+ try {
203
+ const { id, secret } = await registry.addSubscription({ cwd: body.cwd, url: body.url, kinds: body.kinds });
204
+ sendJson(res, 200, { ok: true, id, secret });
205
+ } catch (e) {
206
+ sendWebhookError(res, e);
207
+ }
208
+ });
209
+ adminHttp.registerRoute('GET', '/admin/webhooks', async (/** @type {any} */ _req, /** @type {any} */ res, /** @type {URLSearchParams} */ query) => {
210
+ const cwd = query?.get('cwd');
211
+ if (!validCwd(cwd)) {
212
+ sendJson(res, 400, { ok: false, error: 'invalid query', details: 'cwd must be an absolute path' });
213
+ return;
214
+ }
215
+ try {
216
+ const subscriptions = await registry.listSubscriptions({ cwd: /** @type {string} */ (cwd) });
217
+ sendJson(res, 200, { ok: true, subscriptions });
218
+ } catch (e) {
219
+ sendWebhookError(res, e);
220
+ }
221
+ });
222
+ adminHttp.registerRoute('DELETE', '/admin/webhooks', async (/** @type {any} */ _req, /** @type {any} */ res, /** @type {URLSearchParams} */ query) => {
223
+ const cwd = query?.get('cwd');
224
+ if (!validCwd(cwd)) {
225
+ sendJson(res, 400, { ok: false, error: 'invalid query', details: 'cwd must be an absolute path' });
226
+ return;
227
+ }
228
+ try {
229
+ const out = await registry.removeSubscription({ cwd: /** @type {string} */ (cwd), id: query.get('id') });
230
+ sendJson(res, 200, { ok: true, ...out });
231
+ } catch (e) {
232
+ sendWebhookError(res, e);
233
+ }
234
+ });
43
235
  }
44
236
 
45
237
  module.exports = { registerAdminRoute };