claude-code-session-manager 0.140.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 (204) 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--JwsFnbn.js → History-DpZuJXi1.js} +1 -1
  5. package/dist/assets/HomeClaudeConfig-D32ZJtU-.js +3 -0
  6. package/dist/assets/{Panel-CALyU0pe.js → Panel-BjdJjhqt.js} +1 -1
  7. package/dist/assets/{ProjectClaudeConfig-sdlA-fUb.js → ProjectClaudeConfig-BTClYV6i.js} +7 -7
  8. package/dist/assets/Scheduler-DPobKx1Z.js +16 -0
  9. package/dist/assets/{SkillReferenceGraph-CxAuwhNN.js → SkillReferenceGraph-Cqyu4mef.js} +1 -1
  10. package/dist/assets/{Skills-DtRzghn5.js → Skills-vv0noNVI.js} +5 -5
  11. package/dist/assets/{TiptapBody-DApeu7x8.js → TiptapBody-CXi8Pvut.js} +1 -1
  12. package/dist/assets/Toggle-CiYCWLjh.js +1 -0
  13. package/dist/assets/{VoiceButton-DtStfv1H.js → VoiceButton-4NKKd1sC.js} +1 -1
  14. package/dist/assets/{historyTotals-ydfnwepc.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/builder/SKILL.md +4 -2
  25. package/plugins/session-manager-dev/skills/develop/SKILL.md +55 -18
  26. package/plugins/session-manager-dev/skills/develop/standards.md +3 -2
  27. package/scripts/README.md +1 -0
  28. package/scripts/hooks/guard-tool-risk.cjs +5 -1
  29. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +158 -1
  30. package/scripts/scheduler-mcp-server.cjs +737 -110
  31. package/src/main/adminRouteRegistry.cjs +59 -0
  32. package/src/main/agentLibrary.cjs +72 -4
  33. package/src/main/agentsIpc.cjs +3 -2
  34. package/src/main/build-info.json +4 -4
  35. package/src/main/chatRunner.cjs +231 -16
  36. package/src/main/config.cjs +30 -0
  37. package/src/main/docEdit.cjs +4 -2
  38. package/src/main/health.cjs +91 -0
  39. package/src/main/index.cjs +98 -48
  40. package/src/main/ipcSchemas.cjs +171 -8
  41. package/src/main/lib/AGENTS.md +1 -1
  42. package/src/main/lib/chatBootRecovery.cjs +2 -0
  43. package/src/main/lib/claude/agentModelResolve.cjs +51 -25
  44. package/src/main/lib/claude/agentSnapshot.cjs +186 -0
  45. package/src/main/lib/claude/environmentProfiles.cjs +242 -0
  46. package/src/main/lib/claude/jobSandboxPolicy.cjs +241 -33
  47. package/src/main/lib/claude/personaToolScope.cjs +82 -31
  48. package/src/main/lib/claude/runClaudeP.cjs +4 -2
  49. package/src/main/lib/claude/toolRiskMarks.cjs +41 -1
  50. package/src/main/lib/claude/usageCircuit.cjs +49 -21
  51. package/src/main/lib/claude/vaultRefs.cjs +277 -0
  52. package/src/main/lib/demo-video-kit/capture.cjs +282 -12
  53. package/src/main/lib/demo-video-kit/cast.md +43 -0
  54. package/src/main/lib/demo-video-kit/character.cjs +722 -30
  55. package/src/main/lib/demo-video-kit/checks.cjs +120 -1
  56. package/src/main/lib/demo-video-kit/export.cjs +218 -0
  57. package/src/main/lib/demo-video-kit/frames.cjs +104 -9
  58. package/src/main/lib/demo-video-kit/kind-marketing.md +121 -0
  59. package/src/main/lib/demo-video-kit/kind-tiktok.md +99 -0
  60. package/src/main/lib/demo-video-kit/kokoroSay.cjs +205 -0
  61. package/src/main/lib/demo-video-kit/project-home-html.md +43 -0
  62. package/src/main/lib/demo-video-kit/resumableRun.cjs +298 -0
  63. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  64. package/src/main/lib/demo-video-kit/voiceLane.cjs +233 -0
  65. package/src/main/lib/demo-video-kit/voiceLibrary.cjs +312 -0
  66. package/src/main/lib/epic/artifactAdminRoutes.cjs +211 -0
  67. package/src/main/lib/epic/artifactIpc.cjs +153 -0
  68. package/src/main/lib/epic/artifactNotice.cjs +72 -0
  69. package/src/main/lib/epic/artifactRetention.cjs +310 -0
  70. package/src/main/lib/epic/artifactStore.cjs +392 -0
  71. package/src/main/lib/epic/delegationReadiness.cjs +76 -2
  72. package/src/main/lib/epic/epicAgentRefresh.cjs +97 -0
  73. package/src/main/lib/epic/epicEventLog.cjs +214 -0
  74. package/src/main/lib/epic/epicMint.cjs +43 -1
  75. package/src/main/lib/epic/epicOutsideRead.cjs +1 -0
  76. package/src/main/lib/epic/epicOutsideState.cjs +18 -4
  77. package/src/main/lib/epic/epicPurge.cjs +347 -0
  78. package/src/main/lib/epic/epicReopen.cjs +5 -2
  79. package/src/main/lib/epic/epicSettle.cjs +4 -13
  80. package/src/main/lib/epic/epicSpawnPlan.cjs +57 -4
  81. package/src/main/lib/epic/epicStatusMirror.cjs +34 -1
  82. package/src/main/lib/epic/epicTransitions.cjs +139 -0
  83. package/src/main/lib/epic/epicValidationHook.cjs +81 -2
  84. package/src/main/lib/epic/guardSpawnSettings.cjs +3 -2
  85. package/src/main/lib/externalContract.cjs +37 -4
  86. package/src/main/lib/feedback-remote/crossProjectReply.cjs +389 -126
  87. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -3
  88. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +11 -6
  89. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +26 -1
  90. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +5 -2
  91. package/src/main/lib/feedback-remote/feedbackBoxDrain.cjs +409 -0
  92. package/src/main/lib/feedback-remote/feedbackBoxKeys.cjs +218 -0
  93. package/src/main/lib/feedback-remote/feedbackEnvelope.cjs +163 -0
  94. package/src/main/lib/feedback-remote/feedbackRelayClient.cjs +164 -0
  95. package/src/main/lib/feedback-remote/feedbackReport.cjs +234 -0
  96. package/src/main/lib/feedback-remote/feedbackSeal.cjs +217 -0
  97. package/src/main/lib/feedback-remote/localAdminHttp.cjs +108 -2
  98. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +2 -1
  99. package/src/main/lib/feedback-remote/needsYouIpc.cjs +17 -0
  100. package/src/main/lib/feedback-remote/needsYouStore.cjs +177 -6
  101. package/src/main/lib/feedback-remote/pendingReplies.cjs +189 -0
  102. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +188 -10
  103. package/src/main/lib/feedback-remote/serviceClient.cjs +429 -0
  104. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +252 -0
  105. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +284 -0
  106. package/src/main/lib/feedback-remote/servicePairings.cjs +313 -0
  107. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +290 -0
  108. package/src/main/lib/feedback-remote/siteFeedbackAdminRoutes.cjs +295 -0
  109. package/src/main/lib/feedback-remote/siteFeedbackInbox.cjs +598 -0
  110. package/src/main/lib/feedback-remote/siteFeedbackIpc.cjs +86 -0
  111. package/src/main/lib/feedback-remote/siteFeedbackService.cjs +477 -0
  112. package/src/main/lib/git/worktreeDeps.cjs +77 -2
  113. package/src/main/lib/mcpToolCatalog.cjs +315 -30
  114. package/src/main/lib/opsOwnership.cjs +29 -1
  115. package/src/main/lib/opsRetentionSettings.cjs +27 -5
  116. package/src/main/lib/persona-macro/builtinMacros.cjs +7 -2
  117. package/src/main/lib/persona-macro/macroJobDispatch.cjs +52 -8
  118. package/src/main/lib/persona-macro/macroJobIpc.cjs +16 -6
  119. package/src/main/lib/persona-macro/macroLibrary.cjs +49 -7
  120. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +83 -0
  121. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +3 -0
  122. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +263 -0
  123. package/src/main/lib/phaseProjection.cjs +103 -0
  124. package/src/main/lib/prd/depSlugResolve.cjs +4 -13
  125. package/src/main/lib/prd/prdBodyPatch.cjs +12 -17
  126. package/src/main/lib/prd/prdCreate.cjs +67 -5
  127. package/src/main/lib/prd/prdCriteria.cjs +225 -0
  128. package/src/main/lib/prd/prdFrontmatter.cjs +68 -3
  129. package/src/main/lib/prd/prdGateFiles.cjs +125 -49
  130. package/src/main/lib/prd/prdSizing.cjs +3 -1
  131. package/src/main/lib/process/cleanEnv.cjs +52 -1
  132. package/src/main/lib/process/leftoverRenice.cjs +178 -0
  133. package/src/main/lib/process/memoryScope.cjs +31 -3
  134. package/src/main/lib/project-pages/pagesLibrary.cjs +72 -6
  135. package/src/main/lib/project-pages/videoReviewIpc.cjs +3 -2
  136. package/src/main/lib/project-pages/voiceAdminRoutes.cjs +175 -0
  137. package/src/main/lib/project-pages/voicePreview.cjs +196 -0
  138. package/src/main/lib/project-pages/voicesIpc.cjs +186 -0
  139. package/src/main/lib/promptSessionSchema.cjs +6 -0
  140. package/src/main/lib/scheduler/cancelledRow.cjs +57 -0
  141. package/src/main/lib/scheduler/cpuSample.cjs +133 -42
  142. package/src/main/lib/scheduler/criteriaChecks.cjs +169 -0
  143. package/src/main/lib/scheduler/definitionOfDone.cjs +44 -5
  144. package/src/main/lib/scheduler/jobMemoryStats.cjs +313 -0
  145. package/src/main/lib/scheduler/loadGate.cjs +82 -4
  146. package/src/main/lib/scheduler/planRecordHarvest.cjs +32 -2
  147. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +133 -0
  148. package/src/main/lib/scheduler/preflightCheck.cjs +97 -0
  149. package/src/main/lib/scheduler/reviewNotice.cjs +39 -0
  150. package/src/main/lib/scheduler/runLogRetention.cjs +42 -1
  151. package/src/main/lib/scheduler/scheduleJobSchema.cjs +5 -0
  152. package/src/main/lib/scheduler/scheduleJobTransitions.cjs +47 -0
  153. package/src/main/lib/scheduler/schedulerConfig.cjs +47 -0
  154. package/src/main/lib/scheduler/schedulerPaths.cjs +0 -3
  155. package/src/main/lib/scheduler/schedulerRuntimeState.cjs +50 -1
  156. package/src/main/lib/scheduler/sessionSlots.cjs +5 -1
  157. package/src/main/lib/scheduler/slotsRoute.cjs +237 -0
  158. package/src/main/lib/scheduler/toolClearance.cjs +258 -0
  159. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +140 -10
  160. package/src/main/lib/tasks/memoryConsolidation.cjs +300 -0
  161. package/src/main/lib/tasks/mitigationReview.cjs +294 -0
  162. package/src/main/lib/tasks/taskAdminRoutes.cjs +312 -22
  163. package/src/main/lib/tasks/taskIpc.cjs +22 -18
  164. package/src/main/lib/tasks/taskLedger.cjs +147 -25
  165. package/src/main/lib/tasks/taskRun.cjs +186 -17
  166. package/src/main/lib/tasks/taskSwitch.cjs +85 -12
  167. package/src/main/lib/tasks/taskSwitchRoute.cjs +172 -0
  168. package/src/main/lib/telemetry/auditEvents.cjs +207 -6
  169. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +198 -6
  170. package/src/main/lib/telemetry/webhookDelivery.cjs +205 -0
  171. package/src/main/lib/telemetry/webhookRegistry.cjs +281 -0
  172. package/src/main/lib/toolUseClassify.cjs +181 -0
  173. package/src/main/lib/util/smfileRange.cjs +77 -0
  174. package/src/main/projectPages.cjs +3 -1
  175. package/src/main/promptSessionEvents.cjs +5 -0
  176. package/src/main/pty.cjs +68 -0
  177. package/src/main/queueOps.cjs +32 -13
  178. package/src/main/runVerify.cjs +74 -9
  179. package/src/main/scheduler/AGENTS.md +1 -0
  180. package/src/main/scheduler/budget.cjs +6 -5
  181. package/src/main/scheduler/prdParser.cjs +62 -14
  182. package/src/main/scheduler/reviewLadder.cjs +45 -28
  183. package/src/main/scheduler/starvation.cjs +69 -0
  184. package/src/main/scheduler/utilizationHold.cjs +101 -0
  185. package/src/main/scheduler.cjs +1745 -210
  186. package/src/main/templates/PRD_AUTHORING.md +13 -2
  187. package/src/main/webRemote.cjs +463 -6
  188. package/src/preload/api.d.ts +529 -38
  189. package/src/preload/apiSurface.json +209 -7
  190. package/src/preload/index.cjs +46 -1
  191. package/src/seed/agents/architect.md +6 -1
  192. package/src/seed/agents/blender-artist.md +2 -1
  193. package/src/seed/agents/competitive-analyst.md +3 -1
  194. package/src/seed/agents/competitive-researcher.md +2 -1
  195. package/src/seed/agents/demo-video-builder.md +87 -83
  196. package/src/seed/agents/dev-lead.md +3 -3
  197. package/src/seed/agents/project-home-builder.md +9 -31
  198. package/src/seed/agents/validator.md +9 -10
  199. package/dist/assets/AppSettings-CMFEM68R.js +0 -2
  200. package/dist/assets/HomeClaudeConfig-ijEXs--3.js +0 -3
  201. package/dist/assets/Scheduler-YT3j8SUa.js +0 -16
  202. package/dist/assets/ViewTabs-B7qLXRAH.js +0 -1
  203. package/dist/assets/index-CtxruO1L.js +0 -3121
  204. package/src/main/lib/epic/epicStateWatcher.cjs +0 -157
@@ -0,0 +1,214 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * epicEventLog.cjs — the per-Epic durable event log (the Managed Agents
5
+ * session event stream). THE ONLY WRITER of a project's
6
+ * `session-manager-operations/events/` namespace (writer id 'event-log' in
7
+ * lib/opsOwnership.cjs).
8
+ *
9
+ * Layout: events/<epicId>/events.jsonl — one JSON line per event:
10
+ * { seq, time, epicId, kind, ...summary fields }
11
+ * `seq` is a per-Epic monotonic integer (1, 2, 3, ...) and the replay cursor;
12
+ * `time` is an ISO-8601 UTC timestamp. Both are assigned here and cannot be
13
+ * supplied by the caller.
14
+ *
15
+ * Kinds are a CLOSED {domain}.{action} set (EVENT_KINDS); an unknown kind
16
+ * throws. Events carry summaries, never full transcript content: every string
17
+ * field, at any depth, is capped at MAX_FIELD_CHARS.
18
+ *
19
+ * Concurrency: appends to one file are serialized by an in-process promise
20
+ * chain keyed by file path; the last seq is cached per file and recovered from
21
+ * the file on first use. Reads skip an unparsable (torn) line; an append
22
+ * after a torn tail starts on a fresh line.
23
+ *
24
+ * Retention: keep forever (runtime, self-ignored).
25
+ */
26
+
27
+ const fsp = require('node:fs/promises');
28
+ const path = require('node:path');
29
+ const { opsPath, assertOpsWrite } = require('../opsOwnership.cjs');
30
+
31
+ const WRITER = 'event-log';
32
+ const NS = 'events';
33
+ const FILE_NAME = 'events.jsonl';
34
+ const MAX_FIELD_CHARS = 2000;
35
+ const DEFAULT_LIMIT = 100;
36
+ const MAX_LIMIT = 1000;
37
+ const EPIC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
38
+ const RESERVED = new Set(['seq', 'time', 'epicId', 'kind']);
39
+
40
+ const EVENT_KINDS = Object.freeze([
41
+ 'epic.minted',
42
+ 'epic.status_changed',
43
+ 'job.queued',
44
+ 'job.status_changed',
45
+ 'job.tool_use',
46
+ 'job.needs_input',
47
+ 'job.confirmation_requested',
48
+ 'human.message',
49
+ 'human.answer',
50
+ 'human.interrupt',
51
+ 'human.tool_confirmation',
52
+ 'external.message',
53
+ 'validator.verdict',
54
+ 'outcome.recorded',
55
+ 'artifact.published',
56
+ ]);
57
+ const KIND_SET = new Set(EVENT_KINDS);
58
+
59
+ /** file path → tail of its append chain. */
60
+ const chains = new Map();
61
+ /** file path → last seq written. */
62
+ const lastSeq = new Map();
63
+
64
+ function assertEpicId(epicId) {
65
+ if (typeof epicId !== 'string' || !EPIC_ID_RE.test(epicId)) {
66
+ throw new Error(`epicEventLog: invalid epicId "${epicId}"`);
67
+ }
68
+ }
69
+
70
+ function assertKind(kind) {
71
+ if (typeof kind !== 'string' || !KIND_SET.has(kind)) {
72
+ throw new Error(`epicEventLog: unknown event kind "${kind}"`);
73
+ }
74
+ }
75
+
76
+ function logFile(cwd, epicId) {
77
+ return opsPath(cwd, NS, epicId, FILE_NAME);
78
+ }
79
+
80
+ /** Deep copy with every string capped at MAX_FIELD_CHARS. Drops functions/undefined via JSON later. */
81
+ function capFields(value, depth = 0) {
82
+ if (typeof value === 'string') {
83
+ return value.length > MAX_FIELD_CHARS ? value.slice(0, MAX_FIELD_CHARS) : value;
84
+ }
85
+ if (value === null || typeof value !== 'object') return value;
86
+ if (depth > 8) return '[depth-capped]';
87
+ if (Array.isArray(value)) return value.map((v) => capFields(v, depth + 1));
88
+ /** @type {Record<string, unknown>} */
89
+ const out = {};
90
+ for (const [k, v] of Object.entries(value)) out[capFields(k, depth + 1)] = capFields(v, depth + 1);
91
+ return out;
92
+ }
93
+
94
+ /** Parse JSONL text; unparsable lines (a torn tail) are skipped. */
95
+ function parseLines(text) {
96
+ const out = [];
97
+ for (const line of text.split('\n')) {
98
+ if (!line) continue;
99
+ try {
100
+ const obj = JSON.parse(line);
101
+ if (obj && typeof obj === 'object' && Number.isInteger(obj.seq)) out.push(obj);
102
+ } catch { /* torn or corrupt line */ }
103
+ }
104
+ return out;
105
+ }
106
+
107
+ async function readText(file) {
108
+ try {
109
+ return await fsp.readFile(file, 'utf8');
110
+ } catch (err) {
111
+ if (err && err.code === 'ENOENT') return '';
112
+ throw err;
113
+ }
114
+ }
115
+
116
+ /**
117
+ * appendEpicEvent(cwd, epicId, event) → Promise<the written record>.
118
+ * Throws (rejects) on an unknown kind or bad epicId before touching disk.
119
+ */
120
+ function appendEpicEvent(cwd, epicId, event) {
121
+ try {
122
+ assertEpicId(epicId);
123
+ if (!event || typeof event !== 'object') throw new Error('epicEventLog: event must be an object');
124
+ assertKind(event.kind);
125
+ } catch (err) {
126
+ return Promise.reject(err);
127
+ }
128
+ let file;
129
+ try {
130
+ file = logFile(cwd, epicId);
131
+ assertOpsWrite(file, WRITER);
132
+ } catch (err) {
133
+ return Promise.reject(err);
134
+ }
135
+ /** @type {Record<string, unknown>} */
136
+ const payload = {};
137
+ for (const [k, v] of Object.entries(event)) if (!RESERVED.has(k)) payload[k] = v;
138
+ const capped = capFields(payload);
139
+
140
+ const prev = chains.get(file) || Promise.resolve();
141
+ const next = prev.catch(() => {}).then(async () => {
142
+ await fsp.mkdir(path.dirname(file), { recursive: true });
143
+ let prefix = '';
144
+ if (!lastSeq.has(file)) {
145
+ const text = await readText(file);
146
+ const rows = parseLines(text);
147
+ lastSeq.set(file, rows.reduce((m, r) => Math.max(m, r.seq), 0));
148
+ if (text && !text.endsWith('\n')) prefix = '\n';
149
+ } else {
150
+ // Cheap tail check: a torn tail written by a crashed process.
151
+ const fh = await fsp.open(file, 'a+').catch(() => null);
152
+ if (fh) {
153
+ try {
154
+ const { size } = await fh.stat();
155
+ if (size > 0) {
156
+ const buf = Buffer.alloc(1);
157
+ await fh.read(buf, 0, 1, size - 1);
158
+ if (buf[0] !== 0x0a) prefix = '\n';
159
+ }
160
+ } finally { await fh.close(); }
161
+ }
162
+ }
163
+ const seq = /** @type {number} */ (lastSeq.get(file)) + 1;
164
+ const record = { seq, time: new Date().toISOString(), epicId, kind: event.kind, ...capped };
165
+ await fsp.appendFile(file, `${prefix}${JSON.stringify(record)}\n`, 'utf8');
166
+ lastSeq.set(file, seq);
167
+ return record;
168
+ });
169
+ chains.set(file, next);
170
+ const cleanup = () => { if (chains.get(file) === next) chains.delete(file); };
171
+ next.then(cleanup, cleanup);
172
+ return next;
173
+ }
174
+
175
+ /**
176
+ * readEpicEvents(cwd, epicId, { after, limit, kinds }) →
177
+ * Promise<{ events, cursor, hasMore }>
178
+ * `after` — return only events with seq > after (default 0).
179
+ * `cursor` — seq of the last returned event (or `after` when none) — pass it
180
+ * back as `after` to resume. `hasMore` — more matching events remain.
181
+ */
182
+ async function readEpicEvents(cwd, epicId, opts = {}) {
183
+ assertEpicId(epicId);
184
+ const after = Number.isInteger(opts.after) && opts.after > 0 ? opts.after : 0;
185
+ const limit = Number.isInteger(opts.limit) && opts.limit > 0 ? Math.min(opts.limit, MAX_LIMIT) : DEFAULT_LIMIT;
186
+ let kindFilter = null;
187
+ if (Array.isArray(opts.kinds) && opts.kinds.length) {
188
+ opts.kinds.forEach(assertKind);
189
+ kindFilter = new Set(opts.kinds);
190
+ }
191
+ const rows = parseLines(await readText(logFile(cwd, epicId)))
192
+ .filter((r) => r.seq > after && (!kindFilter || kindFilter.has(r.kind)))
193
+ .sort((a, b) => a.seq - b.seq);
194
+ const events = rows.slice(0, limit);
195
+ return {
196
+ events,
197
+ cursor: events.length ? events[events.length - 1].seq : after,
198
+ hasMore: rows.length > limit,
199
+ };
200
+ }
201
+
202
+ function _resetForTests() {
203
+ chains.clear();
204
+ lastSeq.clear();
205
+ }
206
+
207
+ module.exports = {
208
+ EVENT_KINDS,
209
+ MAX_FIELD_CHARS,
210
+ WRITER,
211
+ appendEpicEvent,
212
+ readEpicEvents,
213
+ _resetForTests,
214
+ };
@@ -319,7 +319,7 @@ function ensureEpic(cwd, { goalText, tag, epicId: explicitEpicId, status = 'prop
319
319
  // against the tab's absolute path, so a relative value silently produces an
320
320
  // Epic that exists on disk but never renders in any project's queue.
321
321
  cwd = path.resolve(cwd);
322
- return withPathLock(activeIndexPath(cwd), () => {
322
+ return withPathLock(activeIndexPath(cwd), async () => {
323
323
  // Agent-CLI rules run first — a bad id or combination throws before
324
324
  // anything (index, mirror, audit, PRD dir) is written.
325
325
  const cliFields = agentCliMintFields(agentCli, agentCliModel, restoreSessionId, packs);
@@ -404,6 +404,26 @@ function ensureEpic(cwd, { goalText, tag, epicId: explicitEpicId, status = 'prop
404
404
  }
405
405
  }
406
406
 
407
+ // AGENT SNAPSHOT PIN (Managed Agents' versioned agent): freeze the persona this Epic runs
408
+ // as — body, model, effort, tools, packs — so every later chat turn builds from it
409
+ // (epicSpawnPlan.cjs) and a persona edit reaches only NEW Epics. Claude Code Epics with an
410
+ // agentType only: an agentType-less Epic has no persona to pin, and a non-Claude agent CLI
411
+ // never loads a persona. A refusal (persona_missing / persona_invalid) fails the mint.
412
+ let pinned = null;
413
+ if (agentType && !cliFields.agentCli) {
414
+ const build = deps.buildAgentSnapshot || require('../claude/agentSnapshot.cjs').buildAgentSnapshot;
415
+ const built = await build({ cwd, agentType, packs: cliFields.packs || [], deps: deps.snapshotDeps || {} });
416
+ if (built.refusal) {
417
+ const reason = `agentType '${agentType}' cannot be pinned as an AgentSnapshot `
418
+ + `(${built.refusal.code}): ${built.refusal.detail}`;
419
+ appendAuditEvent('epic_mint_refused', { cwd, epicId: explicitEpicId ?? null, status, reason, code: built.refusal.code });
420
+ const err = new Error(`ensureEpic: ${reason}`);
421
+ /** @type {any} */ (err).code = built.refusal.code;
422
+ throw err;
423
+ }
424
+ pinned = built;
425
+ }
426
+
407
427
  const epicId = `${slugify(goalText)}-${crypto.randomUUID().slice(0, 8)}`;
408
428
  const now = new Date().toISOString();
409
429
  const session = {
@@ -445,6 +465,8 @@ function ensureEpic(cwd, { goalText, tag, epicId: explicitEpicId, status = 'prop
445
465
  ...(developLoop === false ? { developLoop: false } : {}),
446
466
  // Agent-CLI fields: agentCli/agentCliModel (non-Claude only) or packs (Claude only); absent = legacy shape.
447
467
  ...cliFields,
468
+ // The pinned AgentSnapshot's content id (see AGENT SNAPSHOT PIN above); absent = live read.
469
+ ...(pinned ? { agentSnapshotId: pinned.id } : {}),
448
470
  };
449
471
 
450
472
  // Validate the constructed record against the canonical PromptSession
@@ -464,6 +486,13 @@ function ensureEpic(cwd, { goalText, tag, epicId: explicitEpicId, status = 'prop
464
486
  throw err;
465
487
  }
466
488
 
489
+ // Write the snapshot only once the record validated — a refused mint leaves no file.
490
+ // Write-once and content-addressed, so an identical persona shares one file.
491
+ if (pinned) {
492
+ const write = deps.writeAgentSnapshot || require('../claude/agentSnapshot.cjs').writeAgentSnapshot;
493
+ await write(cwd, pinned.snapshot);
494
+ }
495
+
467
496
  const firstEvent = {
468
497
  id: crypto.randomUUID(),
469
498
  promptSessionId: epicId,
@@ -498,6 +527,19 @@ function ensureEpic(cwd, { goalText, tag, epicId: explicitEpicId, status = 'prop
498
527
  const prdDir = resolveEpicPrdWriteDir(cwd, epicId);
499
528
  fs.mkdirSync(prdDir, { recursive: true });
500
529
  telemetryCounters.trackEpicCreate({ tag, agentType });
530
+ // Durable Epic event log: one epic.minted per successful mint. Awaited so
531
+ // the event is on disk when ensureEpic resolves; a failure is logged, never thrown.
532
+ try {
533
+ const append = deps.appendEpicEvent || require('./epicEventLog.cjs').appendEpicEvent;
534
+ await append(cwd, epicId, {
535
+ kind: 'epic.minted',
536
+ agentType: agentType ?? null,
537
+ tag: tag ?? null,
538
+ agentSnapshotId: pinned ? pinned.id : null,
539
+ });
540
+ } catch (err) {
541
+ console.error('[epicMint] epic.minted event append failed', epicId, err && err.message ? err.message : err);
542
+ }
501
543
  return { epicId, prdDir, created: true };
502
544
  });
503
545
  }
@@ -220,6 +220,7 @@ function buildRecord(cwd, epicId, session, events, jobs, needsInput, chatBusy) {
220
220
  agentType: str(session.agentType),
221
221
  status: str(session.status),
222
222
  state: computed.state,
223
+ phase: computed.phase,
223
224
  blocked: computed.blocked,
224
225
  prds: computed.prds,
225
226
  verified: computed.verified,
@@ -15,7 +15,8 @@
15
15
  */
16
16
 
17
17
  const { bareSlug } = require('../prd/depSlugResolve.cjs');
18
- const { isCancelledRow } = require('./epicSettle.cjs');
18
+ const { isCancelledRow } = require('../scheduler/cancelledRow.cjs');
19
+ const { phaseOfJob, phaseOfEpic } = require('../phaseProjection.cjs');
19
20
 
20
21
  // Mirrors epicSettle's (unexported) isValidatorCheckin.
21
22
  const isValidatorCheckin = (e, bare) =>
@@ -134,8 +135,9 @@ function reviewReason(row) {
134
135
  * @param {{ session?: any, events?: any[], jobs?: any[], needsInput?: boolean, chatBusy?: boolean }} [args]
135
136
  * @returns {{
136
137
  * state: string,
138
+ * phase: string,
137
139
  * blocked: null | { kind: 'refuted'|'failed'|'needs_review'|'quarantined', prds: { slug: string, reason: string }[] },
138
- * prds: { total: number, pending: number, running: number, completed: number, failed: number, needsReview: number, quarantined: number, skipped: number },
140
+ * prds: { total: number, pending: number, running: number, completed: number, failed: number, needsReview: number, quarantined: number, skipped: number, cancelled: number },
139
141
  * verified: string[],
140
142
  * refuted: { slug: string, reason: string }[],
141
143
  * unvalidated: string[],
@@ -151,9 +153,11 @@ function computeEpicOutsideState(args) {
151
153
 
152
154
  const known = [...buildKnownPrds(session, events, allRows).values()];
153
155
 
154
- const prds = { total: 0, pending: 0, running: 0, completed: 0, failed: 0, needsReview: 0, quarantined: 0, skipped: 0 };
156
+ const prds = { total: 0, pending: 0, running: 0, completed: 0, failed: 0, needsReview: 0, quarantined: 0, skipped: 0, cancelled: 0 };
155
157
  for (const k of known) {
156
158
  prds.total++;
159
+ // A cancelled row (failed/needs_review by a cancel) is its own count, never failed or needsReview.
160
+ if (k.row && isCancelledRow(k.row)) { prds.cancelled++; continue; }
157
161
  switch (k.status) {
158
162
  case 'pending': prds.pending++; break;
159
163
  case 'running':
@@ -208,7 +212,17 @@ function computeEpicOutsideState(args) {
208
212
  .map((k) => ({ slug: k.bare, reason: cut(reasonOf(k)) }))
209
213
  .sort(bySlug);
210
214
 
211
- const result = (state, blocked = null) => ({ state, blocked, prds, verified, refuted, unvalidated });
215
+ // phaseProjection.cjs: one outside phase across Epics, jobs and Tasks. A
216
+ // row-less PRD (known only from its check-in) is projected from its outcome.
217
+ const phase = phaseOfEpic({
218
+ status: session.status,
219
+ needsInput,
220
+ chatBusy,
221
+ refuted: refuted.length,
222
+ jobPhases: known.map((k) => phaseOfJob(k.row || { status: k.status })),
223
+ });
224
+
225
+ const result = (state, blocked = null) => ({ state, phase, blocked, prds, verified, refuted, unvalidated });
212
226
 
213
227
  if (session.status === 'completed') return result('closed');
214
228
  if (session.status === 'proposed') return result('awaiting_approval');