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,347 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * epicPurge.cjs — the ONE way an Epic's data leaves this machine: a human-only
5
+ * purge. Keep-forever stays the default retention for every namespace; this is
6
+ * the single, explicit exception (session-manager-operations/AGENTS.md).
7
+ *
8
+ * purgeEpic({ cwd, epicId, authority }) removes, in order:
9
+ * 1. CLI JSONL (~/.claude/projects/<enc>/<sid>.jsonl + its <sid>/ subagent dir,
10
+ * every candidate epicTranscriptPath.cjs knows) and a non-Claude agent-CLI
11
+ * transcript (agentCliSessionStore.transcriptPathFor).
12
+ * 2. Run logs: every `<slug>.*` file of the Epic's slugs in the scheduler runs dir
13
+ * (runLogRetention.cjs's scanRunEntries).
14
+ * 3. History rows: the Epic's rows in the project history shard and the legacy
15
+ * global history file (queueHistory.cjs). writer 'scheduler'
16
+ * 4. PRD sources + outcome records: scheduler/epics/<epicId>/ (prdOutcomeRecord.cjs
17
+ * layout), and plan-records/<epicId>/. writer 'scheduler'
18
+ * Published artifacts: artifacts/<epicId>/ (artifactStore.cjs), pinned
19
+ * entries included — a purge removes everything. writer 'artifacts'
20
+ * 5. Event log: events/<epicId>/ (epicEventLog.cjs). writer 'event-log'
21
+ * 6. Agent-snapshot refs: the Epic's pinned agents/snapshots/<id>.json when no
22
+ * other Epic or queue row still references it (agentSnapshot.cjs). writer 'agents'
23
+ * 7. Archived transcript prompt-sessions/transcripts-archive/<epicId>.jsonl.gz,
24
+ * the Epic JSON prompt-sessions/<epicId>.json (and any archive JSON whose
25
+ * session.id is this Epic), and the active-index row + events, leaving only a
26
+ * content-free tombstone (an ISO time) so a stale renderer cannot resurrect it.
27
+ * writer 'epics'
28
+ * then appends ONE audit record { kind: 'epic_purged', epicId, at } (auditLog.cjs,
29
+ * which also stamps its usual pid/ppid caller context) — never a title, prompt or
30
+ * any content.
31
+ *
32
+ * Every ops-root delete goes through assertOpsWrite with the namespace's owning
33
+ * writer (single-writer law, opsOwnership.cjs). Refusals return
34
+ * { ok: false, code, error } and touch nothing:
35
+ * - not_human: `authority` is not PURGE_AUTHORITY_IPC (the purge IPC handler,
36
+ * the only caller a human press reaches).
37
+ * - invalid_epic_id: unsafe id.
38
+ * - epic_running: a queue row of this Epic is `running`.
39
+ *
40
+ * purgeEpic({ cwd, epicId, dryRun: true }) walks the same seven steps and
41
+ * returns every artifact it WOULD remove — { ok, dryRun: true, artifacts:
42
+ * [{ kind, path }], counts: { <kind>: n }, total, removed: [] } — deleting and
43
+ * writing nothing (no tombstone, no audit record). A dry run needs no
44
+ * `authority` (scripts/purge-dry-run.cjs calls it read-only); a real purge still
45
+ * refuses anything but PURGE_AUTHORITY_IPC. A real purge returns the same
46
+ * artifacts/counts/total for what it actually removed. Artifact kinds:
47
+ * PURGE_ARTIFACT_KINDS.
48
+ *
49
+ * Not removed: queue.json rows (the live scheduler owns that file in memory —
50
+ * a terminal row ages into history on the next reconcile; a pending row whose
51
+ * PRD source is gone is skipped), and earlier audit-log records (a security trace).
52
+ */
53
+
54
+ const fs = require('node:fs');
55
+ const path = require('node:path');
56
+ const opsOwnership = require('../opsOwnership.cjs');
57
+ const { opsPath, parseOpsPath } = opsOwnership;
58
+ const atomicFs = require('../util/atomicFs.cjs');
59
+
60
+ /** The purge IPC handler's authority token — the only accepted `authority`. */
61
+ const PURGE_AUTHORITY_IPC = 'ipc:promptSessions:purge-epic';
62
+
63
+ /** Every artifact kind a purge can remove, in purge order. */
64
+ const PURGE_ARTIFACT_KINDS = Object.freeze([
65
+ 'cli-transcript', 'run-log', 'history-rows', 'prd-sources', 'plan-records', 'artifacts',
66
+ 'event-log', 'agent-snapshot', 'archived-transcript', 'epic-json', 'index-row',
67
+ ]);
68
+
69
+ const EPIC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
70
+
71
+ function refuse(code, error) {
72
+ return { ok: false, code, error };
73
+ }
74
+
75
+ function readJson(file) {
76
+ try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return null; }
77
+ }
78
+
79
+ function exists(p) {
80
+ try { fs.lstatSync(p); return true; } catch { return false; }
81
+ }
82
+
83
+ /**
84
+ * The purge's running ledger. `dryRun` true = record only, never touch disk.
85
+ * @param {boolean} dryRun
86
+ */
87
+ function makeLedger(dryRun) {
88
+ /** @type {{ kind: string, path: string }[]} */
89
+ const artifacts = [];
90
+ return {
91
+ dryRun,
92
+ artifacts,
93
+ add(kind, p) { artifacts.push({ kind, path: p }); },
94
+ };
95
+ }
96
+
97
+ /**
98
+ * Remove `p` (file or dir, recursive) and record it as `kind`. Inside an ops root
99
+ * the owning writer is asserted first. A dry-run ledger only records. Returns true
100
+ * when something was (or would be) removed.
101
+ */
102
+ function removeOwned(p, writer, kind, ledger) {
103
+ if (!exists(p)) return false;
104
+ if (parseOpsPath(p).inOps) opsOwnership.assertOpsWrite(p, writer);
105
+ if (!ledger.dryRun) fs.rmSync(p, { recursive: true, force: true });
106
+ ledger.add(kind, p);
107
+ return true;
108
+ }
109
+
110
+ /** The project queue shard's jobs (raw rows; [] when absent/unreadable). */
111
+ function readProjectJobs(cwd) {
112
+ try {
113
+ const { projectQueuePath } = require('../scheduler/queueStore.cjs');
114
+ const data = readJson(projectQueuePath(cwd));
115
+ return data && Array.isArray(data.jobs) ? data.jobs.filter((j) => j && typeof j === 'object') : [];
116
+ } catch {
117
+ return [];
118
+ }
119
+ }
120
+
121
+ function rowIsEpic(row, epicId) {
122
+ return !!row && typeof row === 'object' && (row.epicId === epicId || row.sourcePromptId === epicId);
123
+ }
124
+
125
+ /** History files in play for this project: its shard + the legacy global file. */
126
+ function historyFiles(cwd) {
127
+ const out = [];
128
+ try { out.push(require('../scheduler/queueStore.cjs').projectHistoryPath(cwd)); } catch { /* unusable cwd */ }
129
+ try { out.push(require('../scheduler/queueHistory.cjs').historyPath()); } catch { /* no scheduler home */ }
130
+ return [...new Set(out)];
131
+ }
132
+
133
+ function readLines(file) {
134
+ try { return fs.readFileSync(file, 'utf8').split('\n'); } catch { return null; }
135
+ }
136
+
137
+ /** Slugs this Epic ran: queue rows, history rows, and its PRD sources. */
138
+ function collectSlugs(cwd, epicId, jobs) {
139
+ const slugs = new Set();
140
+ for (const j of jobs) if (rowIsEpic(j, epicId) && typeof j.slug === 'string') slugs.add(j.slug);
141
+ for (const file of historyFiles(cwd)) {
142
+ for (const line of readLines(file) || []) {
143
+ if (!line.trim()) continue;
144
+ let row;
145
+ try { row = JSON.parse(line); } catch { continue; }
146
+ if (rowIsEpic(row, epicId) && typeof row.slug === 'string') slugs.add(row.slug);
147
+ }
148
+ }
149
+ try {
150
+ for (const name of fs.readdirSync(opsPath(cwd, 'scheduler', 'epics', epicId, 'prds'))) {
151
+ if (name.endsWith('.md')) slugs.add(name.slice(0, -3));
152
+ }
153
+ } catch { /* no PRD dir */ }
154
+ return slugs;
155
+ }
156
+
157
+ /** Rewrite each history file without the Epic's rows (rows of its slugs count too). */
158
+ function purgeHistoryRows(cwd, epicId, slugs, ledger) {
159
+ for (const file of historyFiles(cwd)) {
160
+ const lines = readLines(file);
161
+ if (!lines) continue;
162
+ const keep = [];
163
+ let dropped = 0;
164
+ for (const line of lines) {
165
+ if (!line.trim()) continue;
166
+ let row = null;
167
+ try { row = JSON.parse(line); } catch { /* keep a torn line untouched */ }
168
+ if (row && (rowIsEpic(row, epicId) || (typeof row.slug === 'string' && slugs.has(row.slug) && !row.epicId))) {
169
+ dropped += 1;
170
+ continue;
171
+ }
172
+ keep.push(line);
173
+ }
174
+ if (!dropped) continue;
175
+ if (parseOpsPath(file).inOps) opsOwnership.assertOpsWrite(file, 'scheduler');
176
+ if (!ledger.dryRun) atomicFs.writeTextAtomicSync(file, keep.length ? `${keep.join('\n')}\n` : '');
177
+ ledger.add('history-rows', file);
178
+ }
179
+ }
180
+
181
+ /** Every run-log file of the Epic's slugs. */
182
+ function purgeRunLogs(slugs, ledger) {
183
+ if (!slugs.size) return;
184
+ let runsDir;
185
+ try { runsDir = require('../scheduler/schedulerPaths.cjs').runsDir(); } catch { return; }
186
+ const { scanRunEntries } = require('../scheduler/runLogRetention.cjs');
187
+ for (const entry of scanRunEntries(runsDir)) {
188
+ if (!slugs.has(entry.slug)) continue;
189
+ for (const f of entry.files) removeOwned(f, 'scheduler', 'run-log', ledger);
190
+ if (ledger.dryRun) continue;
191
+ try { if (fs.readdirSync(entry.dir).length === 0) fs.rmdirSync(entry.dir); } catch { /* not empty / gone */ }
192
+ }
193
+ }
194
+
195
+ /** CLI JSONL (+ <sid>/ subagent dir) at every candidate location, and a non-Claude transcript. */
196
+ function purgeCliTranscripts(cwd, sid, ledger) {
197
+ const { resolveEpicTranscriptPath } = require('./epicTranscriptPath.cjs');
198
+ const { candidates } = resolveEpicTranscriptPath({ cwd, claudeSessionId: sid });
199
+ for (const file of candidates) {
200
+ removeOwned(file, null, 'cli-transcript', ledger);
201
+ const sideDir = file.replace(/\.jsonl$/, '');
202
+ if (sideDir !== file) removeOwned(sideDir, null, 'cli-transcript', ledger);
203
+ }
204
+ try {
205
+ const file = require('../agent-cli/agentCliSessionStore.cjs').transcriptPathFor(sid);
206
+ removeOwned(file, null, 'cli-transcript', ledger);
207
+ } catch { /* no agent-cli store / invalid id */ }
208
+ }
209
+
210
+ /** Snapshot ids still referenced by any OTHER Epic (index rows, archive JSONs) or queue row. */
211
+ function snapshotRefsElsewhere(cwd, epicId, sessions, jobs) {
212
+ const refs = new Set();
213
+ for (const [id, s] of Object.entries(sessions)) {
214
+ if (id !== epicId && s && typeof s.agentSnapshotId === 'string') refs.add(s.agentSnapshotId);
215
+ }
216
+ for (const j of jobs) {
217
+ if (!rowIsEpic(j, epicId) && typeof j.agentSnapshotId === 'string') refs.add(j.agentSnapshotId);
218
+ }
219
+ for (const { session } of archiveJsons(cwd)) {
220
+ if (session && session.id !== epicId && typeof session.agentSnapshotId === 'string') refs.add(session.agentSnapshotId);
221
+ }
222
+ return refs;
223
+ }
224
+
225
+ /** prompt-sessions/*.json (minus active-index.json), parsed; `session` unwrapped. */
226
+ function archiveJsons(cwd) {
227
+ const dir = opsPath(cwd, 'prompt-sessions');
228
+ let names = [];
229
+ try { names = fs.readdirSync(dir); } catch { return []; }
230
+ const out = [];
231
+ for (const name of names) {
232
+ if (!name.endsWith('.json') || name === 'active-index.json') continue;
233
+ const file = path.join(dir, name);
234
+ const parsed = readJson(file);
235
+ const session = parsed && typeof parsed === 'object'
236
+ ? (parsed.session && typeof parsed.session === 'object' ? parsed.session : parsed)
237
+ : null;
238
+ out.push({ file, name, session });
239
+ }
240
+ return out;
241
+ }
242
+
243
+ /** Drop the index row + events, record a content-free tombstone (writer 'epics'). */
244
+ async function purgeIndexRow(cwd, epicId, ledger) {
245
+ const { activeIndexPath, readActiveIndex, withPathLock } = require('./epicMint.cjs');
246
+ const file = activeIndexPath(cwd);
247
+ if (ledger.dryRun) {
248
+ // Read-only: no lock, no tombstone — list the file only when it holds this Epic.
249
+ const index = readActiveIndex(cwd);
250
+ if (exists(file) && (Object.prototype.hasOwnProperty.call(index.sessions, epicId)
251
+ || Object.prototype.hasOwnProperty.call(index.events, epicId))) {
252
+ ledger.add('index-row', file);
253
+ }
254
+ return;
255
+ }
256
+ await withPathLock(file, () => {
257
+ if (!exists(file)) return;
258
+ const index = readActiveIndex(cwd);
259
+ delete index.sessions[epicId];
260
+ delete index.events[epicId];
261
+ index.tombstones[epicId] = new Date().toISOString();
262
+ opsOwnership.assertOpsWrite(file, 'epics');
263
+ atomicFs.writeJsonAtomicSync(file, index, { newline: false });
264
+ ledger.add('index-row', file);
265
+ });
266
+ }
267
+
268
+ /** { artifacts, counts, total } from a ledger; counts has every kind (0 when none). */
269
+ function summarize(ledger) {
270
+ /** @type {Record<string, number>} */
271
+ const counts = {};
272
+ for (const k of PURGE_ARTIFACT_KINDS) counts[k] = 0;
273
+ for (const a of ledger.artifacts) counts[a.kind] = (counts[a.kind] || 0) + 1;
274
+ return { artifacts: ledger.artifacts, counts, total: ledger.artifacts.length };
275
+ }
276
+
277
+ /**
278
+ * purgeEpic({ cwd, epicId, authority, dryRun }) →
279
+ * Promise<{ ok: true, dryRun, artifacts, counts, total, removed: string[] } | { ok: false, code, error }>.
280
+ */
281
+ async function purgeEpic({ cwd, epicId, authority, dryRun = false } = /** @type {any} */ ({})) {
282
+ const isDryRun = dryRun === true;
283
+ if (!isDryRun && authority !== PURGE_AUTHORITY_IPC) {
284
+ return refuse('not_human', 'epicPurge: only the purge IPC handler (a human press) may purge an Epic');
285
+ }
286
+ if (typeof epicId !== 'string' || !EPIC_ID_RE.test(epicId)) {
287
+ return refuse('invalid_epic_id', `epicPurge: invalid epicId "${epicId}"`);
288
+ }
289
+ if (typeof cwd !== 'string' || !path.isAbsolute(cwd)) {
290
+ return refuse('invalid_cwd', 'epicPurge: cwd must be an absolute path');
291
+ }
292
+
293
+ const jobs = readProjectJobs(cwd);
294
+ if (jobs.some((j) => rowIsEpic(j, epicId) && j.status === 'running')) {
295
+ return refuse('epic_running', `epicPurge: Epic ${epicId} has a running job — stop it first`);
296
+ }
297
+
298
+ const { readActiveIndex } = require('./epicMint.cjs');
299
+ const sessions = readActiveIndex(cwd).sessions;
300
+ const ownArchives = archiveJsons(cwd).filter(({ name, session }) => name === `${epicId}.json` || (session && session.id === epicId));
301
+ const row = (Object.prototype.hasOwnProperty.call(sessions, epicId) && sessions[epicId])
302
+ || (ownArchives.find((a) => a.session) || {}).session
303
+ || {};
304
+ const sid = typeof row.claudeSessionId === 'string' && row.claudeSessionId ? row.claudeSessionId : epicId;
305
+ const snapshotId = typeof row.agentSnapshotId === 'string' ? row.agentSnapshotId : null;
306
+
307
+ const ledger = makeLedger(isDryRun);
308
+
309
+ // 1. CLI transcripts — before the index row goes, since the candidate list reads it.
310
+ purgeCliTranscripts(cwd, sid, ledger);
311
+
312
+ // 2-3. Run logs + history rows (scheduler).
313
+ const slugs = collectSlugs(cwd, epicId, jobs);
314
+ purgeRunLogs(slugs, ledger);
315
+ purgeHistoryRows(cwd, epicId, slugs, ledger);
316
+
317
+ // 4. PRD sources + outcome records, plan records (scheduler).
318
+ removeOwned(opsPath(cwd, 'scheduler', 'epics', epicId), 'scheduler', 'prd-sources', ledger);
319
+ removeOwned(opsPath(cwd, 'plan-records', epicId), 'scheduler', 'plan-records', ledger);
320
+ // 4b. Published artifacts (artifacts), pinned entries too.
321
+ removeOwned(opsPath(cwd, 'artifacts', epicId), 'artifacts', 'artifacts', ledger);
322
+
323
+ // 5. Event log (event-log).
324
+ removeOwned(opsPath(cwd, 'events', epicId), 'event-log', 'event-log', ledger);
325
+
326
+ // 6. Agent snapshot, only when nothing else still pins it (agents).
327
+ if (snapshotId && /^[0-9a-f]{64}$/.test(snapshotId)
328
+ && !snapshotRefsElsewhere(cwd, epicId, sessions, jobs).has(snapshotId)) {
329
+ const snapFile = opsPath(cwd, 'agents', 'snapshots', `${snapshotId}.json`);
330
+ removeOwned(snapFile, 'agents', 'agent-snapshot', ledger);
331
+ }
332
+
333
+ // 7. Archived transcript, Epic JSON(s), index row (epics).
334
+ const { sidecarPath } = require('./archivedTranscript.cjs');
335
+ const sidecar = sidecarPath(cwd, epicId);
336
+ removeOwned(sidecar, 'epics', 'archived-transcript', ledger);
337
+ for (const { file } of ownArchives) removeOwned(file, 'epics', 'epic-json', ledger);
338
+ await purgeIndexRow(cwd, epicId, ledger);
339
+
340
+ const summary = summarize(ledger);
341
+ if (isDryRun) return { ok: true, dryRun: true, ...summary, removed: [] };
342
+
343
+ require('../telemetry/auditLog.cjs').appendAuditEvent('epic_purged', { epicId });
344
+ return { ok: true, dryRun: false, ...summary, removed: summary.artifacts.map((a) => a.path) };
345
+ }
346
+
347
+ module.exports = { purgeEpic, PURGE_AUTHORITY_IPC, PURGE_ARTIFACT_KINDS };
@@ -16,6 +16,7 @@ const atomicFs = require('../util/atomicFs.cjs');
16
16
  const { hasTranscriptSource, ensureEpicTranscriptReachable } = require('./epicTranscriptRestore.cjs');
17
17
  const { restoreEpicWorktree } = require('./epicSpawnCwd.cjs');
18
18
  const { isNonClaudeAgentCli } = require('../agent-cli/agentCliEvents.cjs');
19
+ const { transitionEpic } = require('./epicTransitions.cjs');
19
20
 
20
21
  const inFlight = new Map();
21
22
 
@@ -116,7 +117,10 @@ async function doReopen({ cwd, epicId, deps }) {
116
117
  await withPathLock(indexFile, async () => {
117
118
  const index = readActiveIndex(cwd);
118
119
  delete index.tombstones[epicId];
119
- reopened = { ...arch, status: 'active', completedAt: null };
120
+ reopened = { ...arch, id: epicId, cwd, status: 'completed', completedAt: null };
121
+ if (!transitionEpic(reopened, 'active', { reason: 'reopen', source: 'epicReopen' })) {
122
+ throw new Error('illegal status transition completed -> active');
123
+ }
120
124
  if (worktree) reopened.worktree = worktree;
121
125
  events = Array.isArray(archive.events) ? archive.events : [];
122
126
  index.sessions[epicId] = reopened;
@@ -129,7 +133,6 @@ async function doReopen({ cwd, epicId, deps }) {
129
133
  ...reopened,
130
134
  id: epicId,
131
135
  cwd,
132
- status: 'active',
133
136
  archivedAt: null,
134
137
  indexedAt: new Date().toISOString(),
135
138
  });
@@ -5,11 +5,13 @@
5
5
  *
6
6
  * Given the Epic's event chain and the scheduler queue rows, says whether the
7
7
  * Epic has settled (no pending/running PRD) and which finished PRDs no
8
- * validator has checked yet. No fs, no scheduler require.
8
+ * validator has checked yet. No fs; only the pure lib/scheduler/cancelledRow
9
+ * predicate, never the scheduler itself.
9
10
  */
10
11
 
11
12
  const { createHash } = require('node:crypto');
12
13
  const { bareSlug } = require('../prd/depSlugResolve.cjs');
14
+ const { isCancelledRow } = require('../scheduler/cancelledRow.cjs');
13
15
 
14
16
  const DEFAULT_SETTLE_HORIZON_MS = 24 * 60 * 60 * 1000;
15
17
 
@@ -21,17 +23,6 @@ const ts = (at) => {
21
23
  const isValidatorCheckin = (e, bare) =>
22
24
  e.agentType === 'validator' || (e.agentType == null && bare.startsWith('validate-'));
23
25
 
24
- // Mirrors the scheduler's cancel rule locally (lib/epic stays free of scheduler deps).
25
- const isCancelledRow = (r) => {
26
- if (!r || (r.status !== 'failed' && r.status !== 'needs_review')) return false;
27
- if (typeof r.cancelledAt === 'string' && r.cancelledAt) return true;
28
- const hist = Array.isArray(r.statusHistory) ? r.statusHistory : [];
29
- for (let i = hist.length - 1; i >= 0; i--) {
30
- if (hist[i] && hist[i].to === r.status) return hist[i].source === 'remote:cancelJob';
31
- }
32
- return false;
33
- };
34
-
35
26
  /**
36
27
  * @param {{ epicId: string, cwd?: string|null, events?: any[], jobs?: any[], now?: number, horizonMs?: number }} args
37
28
  */
@@ -118,4 +109,4 @@ function evaluateEpicSettle({ epicId, cwd, events, jobs, now, horizonMs } = {})
118
109
  return { settled, uncovered, verified, refuted, failed, parked, cancelled, digestKey, hasContent };
119
110
  }
120
111
 
121
- module.exports = { evaluateEpicSettle, DEFAULT_SETTLE_HORIZON_MS, isCancelledRow };
112
+ module.exports = { evaluateEpicSettle, DEFAULT_SETTLE_HORIZON_MS };
@@ -23,6 +23,14 @@
23
23
  * breaker: once a session is found unreachable, later requests are refused after ONE stat (is the
24
24
  * worktree dir still missing?) without re-running the restore git commands.
25
25
  *
26
+ * Persona pin: an ok plan also carries `persona` — the body + `--model` this turn runs with. An
27
+ * Epic with `agentSnapshotId` (stamped at mint, epicMint.cjs) builds them from that immutable
28
+ * AgentSnapshot (claude/agentSnapshot.cjs), so a persona edit after mint never reaches it; an Epic
29
+ * without one (minted before pinning, agentType-less, or whose snapshot file is gone/tampered)
30
+ * keeps today's live read (agentModelResolve.cjs's resolveEpicModel, no per-turn body). Model
31
+ * precedence with a snapshot: the Epic's own `model` override, then the snapshot's model, then
32
+ * Settings / 'sonnet' — never left unpinned. Non-Claude agent CLIs get `persona: null`.
33
+ *
26
34
  * Ops-root hazard (epicSpawnCwd.cjs): `execCwd` returned here is for the spawn cwd option ONLY;
27
35
  * ops reads/writes keep using the project `cwd` (projectRootOf / resolveProjectRoot).
28
36
  */
@@ -37,6 +45,51 @@ const { resolveEpicSpawnCwd } = require('./epicSpawnCwd.cjs');
37
45
  const { resolveEpicTranscriptPath } = require('./epicTranscriptPath.cjs');
38
46
  const { isNonClaudeAgentCli } = require('../agent-cli/agentCliEvents.cjs');
39
47
 
48
+ /**
49
+ * The persona (body + model) this turn runs with — see the header's "Persona pin".
50
+ * @returns {{ source: 'snapshot'|'live', agentSnapshotId: string|null, body: string|null, model: string, snapshotMissing?: true } | null}
51
+ */
52
+ function resolveTurnPersona(cwd, claudeSessionId, epic, deps) {
53
+ if (epic && isNonClaudeAgentCli(epic.agentCli)) return null;
54
+ const modelResolve = require('../claude/agentModelResolve.cjs');
55
+ const live = () => (deps.resolveEpicModel || modelResolve.resolveEpicModel)({ cwd, claudeSessionId, deps });
56
+ const id = epic && typeof epic.agentSnapshotId === 'string' && epic.agentSnapshotId ? epic.agentSnapshotId : null;
57
+ if (!id) return { source: 'live', agentSnapshotId: null, body: null, model: live() };
58
+ const readSnap = deps.readAgentSnapshotSync || require('../claude/agentSnapshot.cjs').readAgentSnapshotSync;
59
+ let snap = null;
60
+ try { snap = readSnap(cwd, id); } catch { snap = null; }
61
+ if (!snap) return { source: 'live', agentSnapshotId: id, body: null, model: live(), snapshotMissing: true };
62
+ const override = modelResolve.epicOverrideValue(epic, 'model');
63
+ let model = override && override !== 'inherit' ? override : null;
64
+ if (!model && typeof snap.model === 'string' && snap.model && snap.model !== 'inherit') model = snap.model;
65
+ if (!model) {
66
+ try { model = require('../claude/modelCatalog.cjs').readSettingsModel(cwd, deps) || null; } catch { model = null; }
67
+ }
68
+ return {
69
+ source: 'snapshot',
70
+ agentSnapshotId: id,
71
+ body: typeof snap.body === 'string' && snap.body ? snap.body : null,
72
+ model: model || modelResolve.FALLBACK_MODEL,
73
+ };
74
+ }
75
+
76
+ /**
77
+ * The `--model` an Epic turn launches with — the ONE resolver both views call (Chat:
78
+ * chatRunner.cjs; Terminal: agents:resolve-epic-model in agentsIpc.cjs), so a pinned Epic's two
79
+ * views agree. Pinned snapshot when present, else agentModelResolve.cjs's live resolveEpicModel.
80
+ * Never throws; never returns an empty model.
81
+ * @param {{ cwd: string, claudeSessionId: string, deps?: object }} opts
82
+ * @returns {string}
83
+ */
84
+ function resolveEpicTurnModel({ cwd, claudeSessionId, deps = {} } = /** @type {any} */ ({})) {
85
+ const modelResolve = require('../claude/agentModelResolve.cjs');
86
+ try {
87
+ const persona = resolveTurnPersona(cwd, claudeSessionId, findEpic(cwd, claudeSessionId, deps), deps);
88
+ if (persona && persona.model) return persona.model;
89
+ } catch { /* fall through to the live read */ }
90
+ return modelResolve.resolveEpicModel({ cwd, claudeSessionId, deps });
91
+ }
92
+
40
93
  /** Map<sessionId, { dir, message }> — sessions found unreachable; valid while `dir` stays missing. */
41
94
  const unreachable = new Map();
42
95
 
@@ -75,7 +128,7 @@ function findEpic(cwd, claudeSessionId, deps) {
75
128
 
76
129
  /**
77
130
  * @param {{ cwd: string, claudeSessionId: string, fallbackResume?: boolean, deps?: object }} opts
78
- * @returns {{ ok: true, execCwd: string, useResume: boolean, transcriptPath: string|null }
131
+ * @returns {{ ok: true, execCwd: string, useResume: boolean, transcriptPath: string|null, persona: ReturnType<typeof resolveTurnPersona> }
79
132
  * | { ok: false, code: 'epic_closed'|'session_unreachable'|'spawn_cwd_missing', message: string }}
80
133
  */
81
134
  function planEpicSpawn({ cwd, claudeSessionId, fallbackResume = false, worktreeDirHint, deps = {} } = {}) {
@@ -104,7 +157,7 @@ function planEpicSpawn({ cwd, claudeSessionId, fallbackResume = false, worktreeD
104
157
 
105
158
  // Turn-1 hint: no transcript anywhere yet and the freshly minted worktree exists → spawn there.
106
159
  if ((!resolved || !resolved.existsAnywhere) && typeof worktreeDirHint === 'string' && worktreeDirHint && isDir(worktreeDirHint, statSync)) {
107
- return { ok: true, execCwd: worktreeDirHint, useResume: false, transcriptPath: null };
160
+ return { ok: true, execCwd: worktreeDirHint, useResume: false, transcriptPath: null, persona: resolveTurnPersona(cwd, claudeSessionId, epic, deps) };
108
161
  }
109
162
 
110
163
  let execCwd = (deps.resolveSpawnCwd || resolveEpicSpawnCwd)({ cwd, claudeSessionId, deps: { restore: true, readActiveIndex: deps.readActiveIndex, statSync: deps.statSync, restoreWorktree: deps.restoreWorktree } });
@@ -167,7 +220,7 @@ function planEpicSpawn({ cwd, claudeSessionId, fallbackResume = false, worktreeD
167
220
  };
168
221
  }
169
222
 
170
- return { ok: true, execCwd, useResume, transcriptPath: resolved?.path ?? null };
223
+ return { ok: true, execCwd, useResume, transcriptPath: resolved?.path ?? null, persona: resolveTurnPersona(cwd, claudeSessionId, epic, deps) };
171
224
  }
172
225
 
173
- module.exports = { planEpicSpawn, __resetForTests };
226
+ module.exports = { planEpicSpawn, resolveTurnPersona, resolveEpicTurnModel, __resetForTests };
@@ -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 };