claude-code-session-manager 0.141.0 → 0.143.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (223) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +76 -153
  3. package/bin/cli.cjs +11 -0
  4. package/dist/assets/AppSettings-BO4jDVGO.js +2 -0
  5. package/dist/assets/{History-DJMiuXyK.js → History-DTttbvPb.js} +1 -1
  6. package/dist/assets/HomeClaudeConfig-DADP5bfn.js +3 -0
  7. package/dist/assets/{Panel-Bf1Cf8UL.js → Panel-B_D4Bg7L.js} +1 -1
  8. package/dist/assets/{ProjectClaudeConfig-BWPpypf9.js → ProjectClaudeConfig-DPnDJKcr.js} +7 -7
  9. package/dist/assets/Scheduler-CNLjn90m.js +16 -0
  10. package/dist/assets/{SkillReferenceGraph-Ba4TkX2C.js → SkillReferenceGraph-D1b2aiol.js} +1 -1
  11. package/dist/assets/{Skills-C1v91GEO.js → Skills-cfV7sgk6.js} +5 -5
  12. package/dist/assets/{TiptapBody-BrcWVpiW.js → TiptapBody-DVXtEIVy.js} +1 -1
  13. package/dist/assets/Toggle-CYajnSdx.js +1 -0
  14. package/dist/assets/{VoiceButton-qivnDV6K.js → VoiceButton-DJ4gGRuE.js} +1 -1
  15. package/dist/assets/{historyTotals-CMCPTKqC.js → historyTotals-D3MoHY2U.js} +1 -1
  16. package/dist/assets/index-CdTppjKR.js +3133 -0
  17. package/dist/assets/{index-DKXdXfka.css → index-DVHIHoJf.css} +1 -1
  18. package/dist/index.html +2 -2
  19. package/dist-web/app.css +1 -1
  20. package/dist-web/app.js +496 -484
  21. package/package.json +6 -4
  22. package/plugins/AGENTS.md +4 -3
  23. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  24. package/plugins/session-manager-dev/hooks/hooks.json +15 -0
  25. package/plugins/session-manager-dev/hooks/residue-check.cjs +241 -0
  26. package/plugins/session-manager-dev/skills/builder/SKILL.md +5 -0
  27. package/plugins/session-manager-dev/skills/develop/SKILL.md +58 -18
  28. package/plugins/session-manager-dev/skills/develop/standards.md +3 -2
  29. package/scripts/README.md +2 -0
  30. package/scripts/hooks/guard-tool-risk.cjs +5 -1
  31. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +158 -1
  32. package/scripts/scheduler-mcp-server.cjs +1032 -112
  33. package/src/main/adminRouteRegistry.cjs +69 -0
  34. package/src/main/agentLibrary.cjs +72 -4
  35. package/src/main/agentsIpc.cjs +3 -2
  36. package/src/main/build-info.json +4 -4
  37. package/src/main/chatRunner.cjs +336 -23
  38. package/src/main/config.cjs +35 -1
  39. package/src/main/docEdit.cjs +4 -2
  40. package/src/main/health.cjs +129 -2
  41. package/src/main/index.cjs +110 -52
  42. package/src/main/ipcSchemas.cjs +172 -8
  43. package/src/main/lib/AGENTS.md +1 -1
  44. package/src/main/lib/chatBootRecovery.cjs +2 -0
  45. package/src/main/lib/claude/agentModelResolve.cjs +51 -25
  46. package/src/main/lib/claude/agentSnapshot.cjs +186 -0
  47. package/src/main/lib/claude/environmentProfiles.cjs +242 -0
  48. package/src/main/lib/claude/jobSandboxPolicy.cjs +241 -33
  49. package/src/main/lib/claude/personaToolScope.cjs +82 -31
  50. package/src/main/lib/claude/runClaudeP.cjs +4 -2
  51. package/src/main/lib/claude/toolRiskMarks.cjs +41 -1
  52. package/src/main/lib/claude/usageCircuit.cjs +49 -21
  53. package/src/main/lib/claude/vaultRefs.cjs +277 -0
  54. package/src/main/lib/demo-video-kit/capture.cjs +282 -12
  55. package/src/main/lib/demo-video-kit/cast.md +52 -0
  56. package/src/main/lib/demo-video-kit/character.cjs +778 -30
  57. package/src/main/lib/demo-video-kit/checks.cjs +120 -1
  58. package/src/main/lib/demo-video-kit/export.cjs +218 -0
  59. package/src/main/lib/demo-video-kit/frames.cjs +104 -9
  60. package/src/main/lib/demo-video-kit/kind-marketing.md +121 -0
  61. package/src/main/lib/demo-video-kit/kind-tiktok.md +103 -0
  62. package/src/main/lib/demo-video-kit/kokoroSay.cjs +205 -0
  63. package/src/main/lib/demo-video-kit/project-home-html.md +43 -0
  64. package/src/main/lib/demo-video-kit/projectSounds.cjs +191 -0
  65. package/src/main/lib/demo-video-kit/resumableRun.cjs +298 -0
  66. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  67. package/src/main/lib/demo-video-kit/sound.cjs +166 -9
  68. package/src/main/lib/demo-video-kit/standalone.cjs +231 -0
  69. package/src/main/lib/demo-video-kit/voiceLane.cjs +233 -0
  70. package/src/main/lib/demo-video-kit/voiceLibrary.cjs +312 -0
  71. package/src/main/lib/epic/activeIndexMerge.cjs +5 -0
  72. package/src/main/lib/epic/artifactAdminRoutes.cjs +211 -0
  73. package/src/main/lib/epic/artifactIpc.cjs +153 -0
  74. package/src/main/lib/epic/artifactNotice.cjs +72 -0
  75. package/src/main/lib/epic/artifactRetention.cjs +356 -0
  76. package/src/main/lib/epic/artifactStore.cjs +435 -0
  77. package/src/main/lib/epic/delegationReadiness.cjs +83 -2
  78. package/src/main/lib/epic/epicAgentRefresh.cjs +97 -0
  79. package/src/main/lib/epic/epicEventLog.cjs +258 -0
  80. package/src/main/lib/epic/epicMint.cjs +43 -1
  81. package/src/main/lib/epic/epicOutsideRead.cjs +1 -0
  82. package/src/main/lib/epic/epicOutsideState.cjs +18 -4
  83. package/src/main/lib/epic/epicPurge.cjs +347 -0
  84. package/src/main/lib/epic/epicReopen.cjs +5 -2
  85. package/src/main/lib/epic/epicSettle.cjs +4 -13
  86. package/src/main/lib/epic/epicSpawnPlan.cjs +57 -4
  87. package/src/main/lib/epic/epicStateEmitter.cjs +248 -0
  88. package/src/main/lib/epic/epicStatusMirror.cjs +34 -1
  89. package/src/main/lib/epic/epicTransitions.cjs +139 -0
  90. package/src/main/lib/epic/epicValidationHook.cjs +94 -4
  91. package/src/main/lib/epic/guardSpawnSettings.cjs +3 -2
  92. package/src/main/lib/externalContract.cjs +48 -4
  93. package/src/main/lib/feedback-remote/autoStartedSession.cjs +1 -1
  94. package/src/main/lib/feedback-remote/crossProjectReply.cjs +478 -127
  95. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -3
  96. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +11 -6
  97. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +26 -1
  98. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +5 -2
  99. package/src/main/lib/feedback-remote/feedbackBoxDrain.cjs +409 -0
  100. package/src/main/lib/feedback-remote/feedbackBoxKeys.cjs +218 -0
  101. package/src/main/lib/feedback-remote/feedbackEnvelope.cjs +163 -0
  102. package/src/main/lib/feedback-remote/feedbackRelayClient.cjs +164 -0
  103. package/src/main/lib/feedback-remote/feedbackReport.cjs +234 -0
  104. package/src/main/lib/feedback-remote/feedbackSeal.cjs +217 -0
  105. package/src/main/lib/feedback-remote/localAdminHttp.cjs +108 -2
  106. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +32 -1
  107. package/src/main/lib/feedback-remote/needsYouIpc.cjs +17 -0
  108. package/src/main/lib/feedback-remote/needsYouStore.cjs +177 -6
  109. package/src/main/lib/feedback-remote/pendingReplies.cjs +207 -0
  110. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +282 -14
  111. package/src/main/lib/feedback-remote/replyClaims.cjs +159 -0
  112. package/src/main/lib/feedback-remote/serviceClient.cjs +429 -0
  113. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +252 -0
  114. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +284 -0
  115. package/src/main/lib/feedback-remote/servicePairings.cjs +313 -0
  116. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +290 -0
  117. package/src/main/lib/feedback-remote/siteFeedbackAdminRoutes.cjs +295 -0
  118. package/src/main/lib/feedback-remote/siteFeedbackInbox.cjs +598 -0
  119. package/src/main/lib/feedback-remote/siteFeedbackIpc.cjs +86 -0
  120. package/src/main/lib/feedback-remote/siteFeedbackService.cjs +477 -0
  121. package/src/main/lib/git/gitWorktree.cjs +8 -0
  122. package/src/main/lib/git/runtimeStateUntrack.cjs +15 -1
  123. package/src/main/lib/git/worktreeDeps.cjs +182 -4
  124. package/src/main/lib/mcpToolCatalog.cjs +399 -29
  125. package/src/main/lib/opsOwnership.cjs +141 -28
  126. package/src/main/lib/opsRetentionSettings.cjs +27 -5
  127. package/src/main/lib/persona-macro/builtinMacros.cjs +7 -2
  128. package/src/main/lib/persona-macro/macroJobDispatch.cjs +52 -8
  129. package/src/main/lib/persona-macro/macroJobIpc.cjs +16 -6
  130. package/src/main/lib/persona-macro/macroLibrary.cjs +49 -7
  131. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +83 -0
  132. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +3 -0
  133. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +309 -0
  134. package/src/main/lib/phaseProjection.cjs +103 -0
  135. package/src/main/lib/prd/depSlugResolve.cjs +4 -13
  136. package/src/main/lib/prd/prdBodyPatch.cjs +12 -17
  137. package/src/main/lib/prd/prdCreate.cjs +387 -228
  138. package/src/main/lib/prd/prdCriteria.cjs +228 -0
  139. package/src/main/lib/prd/prdFrontmatter.cjs +43 -3
  140. package/src/main/lib/prd/prdGateFiles.cjs +125 -49
  141. package/src/main/lib/prd/prdSizing.cjs +3 -1
  142. package/src/main/lib/process/cleanEnv.cjs +52 -1
  143. package/src/main/lib/process/leftoverRenice.cjs +178 -0
  144. package/src/main/lib/process/memoryScope.cjs +31 -3
  145. package/src/main/lib/project-pages/pagesLibrary.cjs +72 -6
  146. package/src/main/lib/project-pages/videoPressLines.cjs +145 -0
  147. package/src/main/lib/project-pages/videoReviewIpc.cjs +3 -2
  148. package/src/main/lib/project-pages/videoScriptPress.cjs +260 -0
  149. package/src/main/lib/project-pages/videoScriptRunRoute.cjs +351 -0
  150. package/src/main/lib/project-pages/videoScriptSwitchIpc.cjs +49 -0
  151. package/src/main/lib/project-pages/videoScriptSwitchRoute.cjs +173 -0
  152. package/src/main/lib/project-pages/voiceAdminRoutes.cjs +175 -0
  153. package/src/main/lib/project-pages/voicePreview.cjs +196 -0
  154. package/src/main/lib/project-pages/voicesIpc.cjs +186 -0
  155. package/src/main/lib/promptSessionSchema.cjs +6 -0
  156. package/src/main/lib/scheduler/cancelledRow.cjs +57 -0
  157. package/src/main/lib/scheduler/cpuSample.cjs +133 -42
  158. package/src/main/lib/scheduler/criteriaChecks.cjs +313 -0
  159. package/src/main/lib/scheduler/definitionOfDone.cjs +44 -5
  160. package/src/main/lib/scheduler/heldSchedulerTurns.cjs +238 -0
  161. package/src/main/lib/scheduler/jobMemoryStats.cjs +324 -0
  162. package/src/main/lib/scheduler/loadGate.cjs +82 -4
  163. package/src/main/lib/scheduler/planRecordHarvest.cjs +152 -54
  164. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +191 -0
  165. package/src/main/lib/scheduler/queueStore.cjs +16 -0
  166. package/src/main/lib/scheduler/rcaReport.cjs +79 -15
  167. package/src/main/lib/scheduler/runLogRetention.cjs +42 -1
  168. package/src/main/lib/scheduler/scheduleJobSchema.cjs +18 -0
  169. package/src/main/lib/scheduler/scheduleJobTransitions.cjs +47 -0
  170. package/src/main/lib/scheduler/schedulerConfig.cjs +47 -0
  171. package/src/main/lib/scheduler/schedulerPaths.cjs +9 -3
  172. package/src/main/lib/scheduler/schedulerRuntimeState.cjs +50 -1
  173. package/src/main/lib/scheduler/sessionSlots.cjs +5 -1
  174. package/src/main/lib/scheduler/slotsRoute.cjs +251 -0
  175. package/src/main/lib/scheduler/toolClearance.cjs +258 -0
  176. package/src/main/lib/scheduler/usageHoldRoute.cjs +97 -0
  177. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +152 -11
  178. package/src/main/lib/tasks/memoryConsolidation.cjs +312 -0
  179. package/src/main/lib/tasks/mitigationReview.cjs +314 -0
  180. package/src/main/lib/tasks/taskAdminRoutes.cjs +390 -25
  181. package/src/main/lib/tasks/taskIpc.cjs +22 -18
  182. package/src/main/lib/tasks/taskLedger.cjs +147 -25
  183. package/src/main/lib/tasks/taskRun.cjs +186 -17
  184. package/src/main/lib/tasks/taskSwitch.cjs +85 -12
  185. package/src/main/lib/tasks/taskSwitchRoute.cjs +172 -0
  186. package/src/main/lib/telemetry/auditEvents.cjs +204 -6
  187. package/src/main/lib/telemetry/auditLog.cjs +6 -2
  188. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +198 -6
  189. package/src/main/lib/telemetry/webhookDelivery.cjs +205 -0
  190. package/src/main/lib/telemetry/webhookRegistry.cjs +281 -0
  191. package/src/main/lib/toolUseClassify.cjs +181 -0
  192. package/src/main/lib/util/atomicFs.cjs +2 -2
  193. package/src/main/lib/util/smfileRange.cjs +77 -0
  194. package/src/main/projectPages.cjs +3 -1
  195. package/src/main/promptSessionEvents.cjs +21 -1
  196. package/src/main/pty.cjs +77 -0
  197. package/src/main/queueOps.cjs +33 -14
  198. package/src/main/runVerify.cjs +74 -9
  199. package/src/main/scheduler/AGENTS.md +1 -0
  200. package/src/main/scheduler/budget.cjs +6 -5
  201. package/src/main/scheduler/prdParser.cjs +46 -13
  202. package/src/main/scheduler/reviewLadder.cjs +9 -25
  203. package/src/main/scheduler/utilizationHold.cjs +191 -0
  204. package/src/main/scheduler.cjs +1932 -213
  205. package/src/main/templates/PRD_AUTHORING.md +11 -3
  206. package/src/main/webRemote.cjs +463 -6
  207. package/src/preload/api.d.ts +576 -39
  208. package/src/preload/apiSurface.json +223 -7
  209. package/src/preload/index.cjs +48 -1
  210. package/src/seed/agents/architect.md +6 -1
  211. package/src/seed/agents/blender-artist.md +2 -1
  212. package/src/seed/agents/competitive-analyst.md +3 -1
  213. package/src/seed/agents/competitive-researcher.md +2 -1
  214. package/src/seed/agents/demo-video-builder.md +98 -87
  215. package/src/seed/agents/dev-lead.md +3 -3
  216. package/src/seed/agents/project-home-builder.md +9 -31
  217. package/src/seed/agents/validator.md +23 -23
  218. package/dist/assets/AppSettings-DExeJhqQ.js +0 -2
  219. package/dist/assets/HomeClaudeConfig-CTp2tkZ4.js +0 -3
  220. package/dist/assets/Scheduler-cyr61UAC.js +0 -16
  221. package/dist/assets/ViewTabs-DXhOWFG0.js +0 -1
  222. package/dist/assets/index-B2TQz3nd.js +0 -3121
  223. package/src/main/lib/epic/epicStateWatcher.cjs +0 -157
@@ -0,0 +1,435 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * artifactStore.cjs — the per-project Artifacts store. THE ONLY WRITER of a
5
+ * project's `session-manager-operations/artifacts/` namespace (writer id
6
+ * 'artifacts' in lib/opsOwnership.cjs; runtime). The store writes its own
7
+ * artifacts/.gitignore ('*') on every write, inside the owner lock and before
8
+ * any byte is copied (publishArtifact fails closed if it cannot) — it never
9
+ * relies on the scheduler's periodic ensureRuntimeIgnores sweep.
10
+ *
11
+ * Files an agent makes for human review (videos, images, docs, data) are
12
+ * copied out of the job/Epic worktree into the MAIN project's ops root so they
13
+ * survive worktree teardown and show in the File Explorer without a merge.
14
+ *
15
+ * Layout:
16
+ * artifacts/<epic-id>/<name> Epic-owned artifacts
17
+ * artifacts/<epic-id>/index.json that owner's ledger
18
+ * artifacts/_tasks/<task-id>/<name> Task-owned artifacts (+ index.json)
19
+ * Ledger: { version: 1, entries: [{ name, title, kind, size, sha256, createdAt,
20
+ * producer: { epicId, prdSlug, sessionId, taskId } }] }.
21
+ *
22
+ * Never overwrites: a name collision gets a -2, -3, ... suffix. All writes for
23
+ * one owner folder (name pick, copy, ledger read-modify-write) are serialized
24
+ * by an in-process promise lock. publishArtifact/ingestDir never throw — every
25
+ * refusal is a returned { ok:false, error } / skipped reason.
26
+ *
27
+ * fs seam: reads are injectable (listArtifacts/readLedger take fsImpl); writes
28
+ * (publishArtifact/ingestDir) always use the real fs.
29
+ *
30
+ * Retention: artifactsDays after the owning Epic completes (pruning lives in a
31
+ * sibling module).
32
+ */
33
+
34
+ const fs = require('node:fs');
35
+ const path = require('node:path');
36
+ const crypto = require('node:crypto');
37
+ const { opsPath, checkOpsWrite, assertOpsWrite, ensureRuntimeIgnore } = require('../opsOwnership.cjs');
38
+ const { writeJsonAtomic, readJsonOrSync } = require('../util/atomicFs.cjs');
39
+
40
+ const NAMESPACE = 'artifacts';
41
+ const WRITER = 'artifacts';
42
+ const TASKS_DIR = '_tasks';
43
+ const LEDGER = 'index.json';
44
+ const MAX_BYTES = 2 * 1024 * 1024 * 1024; // 2 GiB
45
+ const MAX_INGEST_FILES = 200;
46
+ const MAX_TITLE_CHARS = 500;
47
+ const EPIC_ID_RE = /^[a-z0-9][a-z0-9-]*$/;
48
+ const TASK_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
49
+ const RUN_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
50
+ const KINDS = Object.freeze(['video', 'audio', 'image', 'doc', 'data', 'other']);
51
+
52
+ const EXT_KIND = Object.freeze({
53
+ video: ['mp4', 'webm', 'mov', 'mkv', 'avi', 'm4v'],
54
+ audio: ['mp3', 'wav', 'ogg', 'flac', 'm4a', 'aac', 'opus'],
55
+ image: ['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg', 'bmp', 'avif', 'ico'],
56
+ doc: ['md', 'txt', 'pdf', 'html', 'htm', 'docx', 'doc', 'rtf', 'pptx', 'odt'],
57
+ data: ['json', 'jsonl', 'csv', 'tsv', 'xml', 'yaml', 'yml', 'xlsx', 'sqlite', 'db', 'parquet'],
58
+ });
59
+ /** @type {Map<string, string>} */
60
+ const KIND_BY_EXT = new Map();
61
+ for (const [kind, exts] of Object.entries(EXT_KIND)) for (const e of exts) KIND_BY_EXT.set(e, kind);
62
+
63
+ /** owner folder abs path → tail of its lock chain. */
64
+ const locks = new Map();
65
+
66
+ function errMsg(e) {
67
+ return e && e.message ? e.message : String(e);
68
+ }
69
+
70
+ function inferKind(name) {
71
+ const ext = path.extname(name).slice(1).toLowerCase();
72
+ return KIND_BY_EXT.get(ext) || 'other';
73
+ }
74
+
75
+ /** Safe file name from a source basename: no separators, no leading dot, bounded. */
76
+ function safeName(base) {
77
+ let n = String(base).replace(/[^A-Za-z0-9._ -]/g, '_').replace(/^[.\s]+/, '').trim();
78
+ if (n.length > 200) {
79
+ const ext = path.extname(n).slice(0, 20);
80
+ n = n.slice(0, 200 - ext.length) + ext;
81
+ }
82
+ return n || 'artifact';
83
+ }
84
+
85
+ /** First free name in `dir`: name, name-2.ext, name-3.ext, ... (index.json is reserved). */
86
+ function freeName(dir, name) {
87
+ const ext = path.extname(name);
88
+ const stem = ext ? name.slice(0, -ext.length) : name;
89
+ for (let i = 1; i < 100000; i += 1) {
90
+ const candidate = i === 1 ? name : `${stem}-${i}${ext}`;
91
+ if (candidate === LEDGER) continue;
92
+ if (!fs.existsSync(path.join(dir, candidate))) return candidate;
93
+ }
94
+ throw new Error('no free artifact name');
95
+ }
96
+
97
+ function isUnder(child, root) {
98
+ const rel = path.relative(root, child);
99
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
100
+ }
101
+
102
+ function sha256File(file) {
103
+ return new Promise((resolve, reject) => {
104
+ const hash = crypto.createHash('sha256');
105
+ const stream = fs.createReadStream(file);
106
+ stream.on('error', reject);
107
+ stream.on('data', (chunk) => hash.update(chunk));
108
+ stream.on('end', () => resolve(hash.digest('hex')));
109
+ });
110
+ }
111
+
112
+ /** Run `fn` after every earlier holder of `key`'s lock. */
113
+ function withLock(key, fn) {
114
+ const prev = locks.get(key) || Promise.resolve();
115
+ const next = prev.catch(() => {}).then(fn);
116
+ locks.set(key, next);
117
+ const cleanup = () => { if (locks.get(key) === next) locks.delete(key); };
118
+ next.then(cleanup, cleanup);
119
+ return next;
120
+ }
121
+
122
+ /** Owner id + folder segments, or an error string. */
123
+ function ownerOf(epicId, taskId) {
124
+ const hasEpic = epicId !== undefined && epicId !== null && epicId !== '';
125
+ const hasTask = taskId !== undefined && taskId !== null && taskId !== '';
126
+ if (hasEpic === hasTask) return { error: 'exactly one of epicId or taskId is required' };
127
+ if (hasEpic) {
128
+ if (typeof epicId !== 'string' || !EPIC_ID_RE.test(epicId)) return { error: 'unsafe epicId' };
129
+ return { ownerId: epicId, segs: [epicId] };
130
+ }
131
+ if (typeof taskId !== 'string' || !TASK_ID_RE.test(taskId)) return { error: 'unsafe taskId' };
132
+ return { ownerId: `${TASKS_DIR}/${taskId}`, segs: [TASKS_DIR, taskId] };
133
+ }
134
+
135
+ /**
136
+ * Read a ledger's entries through fsImpl; missing, empty, corrupt or entries-not-an-array → [].
137
+ */
138
+ function readLedger(file, fsImpl) {
139
+ const parsed = readJsonOrSync(file, null, fsImpl);
140
+ const entries = Array.isArray(parsed) ? parsed : parsed && Array.isArray(parsed.entries) ? parsed.entries : null;
141
+ if (!entries) return [];
142
+ return entries.filter((e) => e && typeof e === 'object' && typeof e.name === 'string');
143
+ }
144
+
145
+ function cleanProducer(producer, epicId, taskId) {
146
+ const p = producer && typeof producer === 'object' ? producer : {};
147
+ const str = (v) => (typeof v === 'string' && v ? v.slice(0, 200) : null);
148
+ return {
149
+ epicId: str(p.epicId) || str(epicId),
150
+ prdSlug: str(p.prdSlug),
151
+ sessionId: str(p.sessionId),
152
+ taskId: str(p.taskId) || str(taskId),
153
+ };
154
+ }
155
+
156
+ /**
157
+ * publishArtifact({ projectRoot, epicId, taskId, srcPath, title, kind, producer,
158
+ * allowedRoots, appendEvent })
159
+ * → Promise<{ ok: true, storedPath, entry } | { ok: false, error }>
160
+ * Never rejects. Every write step (lstat, realpath, mkdir, copy, hash,
161
+ * rename, unlink, ledger write) uses the real fs — there is no fsImpl seam.
162
+ */
163
+ async function publishArtifact({
164
+ projectRoot, epicId, taskId, srcPath, title, kind, producer, allowedRoots,
165
+ appendEvent = null,
166
+ } = {}) {
167
+ try {
168
+ const owner = ownerOf(epicId, taskId);
169
+ if (owner.error) return { ok: false, error: owner.error };
170
+ if (typeof projectRoot !== 'string' || !path.isAbsolute(projectRoot)) {
171
+ return { ok: false, error: 'projectRoot must be an absolute path' };
172
+ }
173
+ if (typeof srcPath !== 'string' || !path.isAbsolute(srcPath)) {
174
+ return { ok: false, error: 'srcPath must be an absolute path' };
175
+ }
176
+ if (kind !== undefined && kind !== null && !KINDS.includes(kind)) {
177
+ return { ok: false, error: `kind must be one of ${KINDS.join(', ')}` };
178
+ }
179
+
180
+ let st;
181
+ try { st = fs.lstatSync(srcPath); } catch (e) { return { ok: false, error: `source unreadable: ${errMsg(e)}` }; }
182
+ if (st.isSymbolicLink()) return { ok: false, error: 'source is a symlink' };
183
+ if (!st.isFile()) return { ok: false, error: 'source is not a regular file' };
184
+ if (st.size > MAX_BYTES) return { ok: false, error: `oversize (${st.size} > ${MAX_BYTES} bytes)` };
185
+
186
+ let realSrc;
187
+ try { realSrc = fs.realpathSync(srcPath); } catch (e) { return { ok: false, error: `source unresolvable: ${errMsg(e)}` }; }
188
+ const roots = (Array.isArray(allowedRoots) && allowedRoots.length ? allowedRoots : [projectRoot])
189
+ .filter((r) => typeof r === 'string' && path.isAbsolute(r))
190
+ .map((r) => { try { return fs.realpathSync(r); } catch { return null; } })
191
+ .filter(Boolean);
192
+ if (!roots.some((r) => isUnder(realSrc, /** @type {string} */ (r)))) {
193
+ return { ok: false, error: 'source is outside every allowed root' };
194
+ }
195
+
196
+ let destDir;
197
+ let nsDir;
198
+ try {
199
+ destDir = path.resolve(opsPath(projectRoot, NAMESPACE, ...owner.segs));
200
+ nsDir = path.resolve(opsPath(projectRoot, NAMESPACE));
201
+ } catch (e) {
202
+ return { ok: false, error: `destination refused: ${errMsg(e)}` };
203
+ }
204
+ if (isUnder(realSrc, destDir)) return { ok: false, error: 'source is already inside the artifacts store' };
205
+ const resolvedRoot = path.dirname(path.dirname(nsDir));
206
+ const ledgerFile = path.join(destDir, LEDGER);
207
+
208
+ return await withLock(destDir, async () => {
209
+ fs.mkdirSync(destDir, { recursive: true });
210
+ // Self-ignore BEFORE any byte lands: never rely on a later sweep. Fail closed.
211
+ try {
212
+ ensureRuntimeIgnore(resolvedRoot, NAMESPACE);
213
+ } catch (e) {
214
+ return { ok: false, error: `could not write artifacts/.gitignore: ${errMsg(e)}` };
215
+ }
216
+ const name = freeName(destDir, safeName(path.basename(srcPath)));
217
+ const dest = path.join(destDir, name);
218
+ const verdict = checkOpsWrite(dest, WRITER);
219
+ if (!verdict.ok) return { ok: false, error: `write refused: ${verdict.error}` };
220
+ assertOpsWrite(dest, WRITER);
221
+ assertOpsWrite(ledgerFile, WRITER);
222
+
223
+ const tmp = `${dest}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
224
+ let sha256;
225
+ let size;
226
+ try {
227
+ fs.copyFileSync(realSrc, tmp, fs.constants.COPYFILE_FICLONE);
228
+ size = fs.statSync(tmp).size;
229
+ if (size > MAX_BYTES) throw new Error(`oversize after copy (${size} > ${MAX_BYTES} bytes)`);
230
+ sha256 = await sha256File(tmp);
231
+ if (fs.existsSync(dest)) throw new Error('destination appeared during copy');
232
+ fs.renameSync(tmp, dest);
233
+ } catch (e) {
234
+ try { fs.unlinkSync(tmp); } catch { /* never created or already gone */ }
235
+ return { ok: false, error: `copy failed: ${errMsg(e)}` };
236
+ }
237
+
238
+ const entry = {
239
+ name,
240
+ title: (typeof title === 'string' && title.trim() ? title.trim() : name).slice(0, MAX_TITLE_CHARS),
241
+ kind: kind || inferKind(name),
242
+ size,
243
+ sha256,
244
+ createdAt: new Date().toISOString(),
245
+ producer: cleanProducer(producer, epicId, taskId),
246
+ };
247
+ try {
248
+ const entries = readLedger(ledgerFile, fs);
249
+ entries.push(entry);
250
+ await writeJsonAtomic(ledgerFile, { version: 1, entries });
251
+ } catch (e) {
252
+ try { fs.unlinkSync(dest); } catch { /* best effort: keep store and ledger in step */ }
253
+ return { ok: false, error: `ledger write failed: ${errMsg(e)}` };
254
+ }
255
+
256
+ if (owner.segs[0] !== TASKS_DIR) {
257
+ try {
258
+ const append = appendEvent || require('./epicEventLog.cjs').appendEpicEvent;
259
+ await append(projectRoot, epicId, {
260
+ kind: 'artifact.published',
261
+ name: entry.name,
262
+ title: entry.title,
263
+ artifactKind: entry.kind,
264
+ size: entry.size,
265
+ path: path.relative(resolvedRoot, dest).split(path.sep).join('/'),
266
+ });
267
+ } catch (e) {
268
+ console.error('[artifactStore] artifact.published event append failed', epicId, name, errMsg(e));
269
+ }
270
+ }
271
+ return { ok: true, storedPath: dest, entry };
272
+ });
273
+ } catch (e) {
274
+ return { ok: false, error: `publish failed: ${errMsg(e)}` };
275
+ }
276
+ }
277
+
278
+ /**
279
+ * ingestDir({ projectRoot, epicId, taskId, srcDir, producer, allowedRoots, minAgeMs, appendEvent })
280
+ * → Promise<{ published: { srcPath, storedPath, entry }[], skipped: { path, reason }[] }>
281
+ * Publishes every regular file directly in srcDir (non-recursive, max 200),
282
+ * deleting each source only after its copy succeeded. Never rejects.
283
+ * minAgeMs (default 0) skips any file modified within the last minAgeMs as
284
+ * 'still being written', so a periodic sweep never moves a half-written file.
285
+ * Like publishArtifact, it uses the real fs for every step (no fsImpl seam).
286
+ */
287
+ async function ingestDir({
288
+ projectRoot, epicId, taskId, srcDir, producer, allowedRoots, minAgeMs = 0, appendEvent = null,
289
+ } = {}) {
290
+ /** @type {{ srcPath: string, storedPath: string, entry: object }[]} */
291
+ const published = [];
292
+ /** @type {{ path: string, reason: string }[]} */
293
+ const skipped = [];
294
+ try {
295
+ if (typeof srcDir !== 'string' || !path.isAbsolute(srcDir)) {
296
+ skipped.push({ path: String(srcDir), reason: 'srcDir must be an absolute path' });
297
+ return { published, skipped };
298
+ }
299
+ let names;
300
+ try {
301
+ const st = fs.lstatSync(srcDir);
302
+ if (!st.isDirectory()) {
303
+ skipped.push({ path: srcDir, reason: 'srcDir is not a directory' });
304
+ return { published, skipped };
305
+ }
306
+ names = fs.readdirSync(srcDir).map(String).sort();
307
+ } catch (e) {
308
+ if (e && e.code === 'ENOENT') return { published, skipped };
309
+ skipped.push({ path: srcDir, reason: `cannot list srcDir: ${errMsg(e)}` });
310
+ return { published, skipped };
311
+ }
312
+ const roots = Array.isArray(allowedRoots) && allowedRoots.length ? allowedRoots : [srcDir];
313
+ const minAge = Number.isFinite(minAgeMs) && minAgeMs > 0 ? minAgeMs : 0;
314
+ const cutoff = Date.now() - minAge;
315
+ let count = 0;
316
+ for (const name of names) {
317
+ const src = path.join(srcDir, name);
318
+ try {
319
+ const st = fs.lstatSync(src);
320
+ if (st.isSymbolicLink()) { skipped.push({ path: src, reason: 'symlink' }); continue; }
321
+ if (st.isDirectory()) { skipped.push({ path: src, reason: 'directory' }); continue; }
322
+ if (!st.isFile()) { skipped.push({ path: src, reason: 'not a regular file' }); continue; }
323
+ if (minAge > 0 && st.mtimeMs > cutoff) { skipped.push({ path: src, reason: 'still being written' }); continue; }
324
+ if (count >= MAX_INGEST_FILES) { skipped.push({ path: src, reason: `over the ${MAX_INGEST_FILES}-file limit` }); continue; }
325
+ count += 1;
326
+ const res = await publishArtifact({
327
+ projectRoot, epicId, taskId, srcPath: src, producer, allowedRoots: roots, appendEvent,
328
+ });
329
+ if (!res.ok) { skipped.push({ path: src, reason: res.error }); continue; }
330
+ published.push({ srcPath: src, storedPath: res.storedPath, entry: res.entry });
331
+ try { fs.unlinkSync(src); } catch (e) {
332
+ console.error('[artifactStore] could not delete ingested source', src, errMsg(e));
333
+ }
334
+ } catch (e) {
335
+ skipped.push({ path: src, reason: `ingest failed: ${errMsg(e)}` });
336
+ }
337
+ }
338
+ } catch (e) {
339
+ skipped.push({ path: String(srcDir), reason: `ingest failed: ${errMsg(e)}` });
340
+ }
341
+ return { published, skipped };
342
+ }
343
+
344
+ /**
345
+ * storedFileState(file, fsImpl) → 'file' | 'gone' | 'unknown', from lstat (no
346
+ * symlink following). 'file': a regular file. 'gone': lstat succeeded on
347
+ * something that is not a regular file (publish never stores a symlink, so a
348
+ * symlink — dangling or not — or a folder counts as gone), or lstat threw
349
+ * ENOENT/ENOTDIR. 'unknown': any other error (EACCES, EIO, …) — the file may
350
+ * still exist. The one rule shared by listArtifacts (shows only 'file') and the
351
+ * retention sweep (artifactRetention.cjs compacts only 'gone'). Never throws.
352
+ * @param {string} file
353
+ * @param {{ lstatSync: (p: string) => { isFile: () => boolean } }} [fsImpl]
354
+ * @returns {'file' | 'gone' | 'unknown'}
355
+ */
356
+ function storedFileState(file, fsImpl = fs) {
357
+ try {
358
+ const st = fsImpl.lstatSync(file);
359
+ return st.isFile() === true ? 'file' : 'gone';
360
+ } catch (e) {
361
+ const code = e && /** @type {{ code?: unknown }} */ (e).code;
362
+ return code === 'ENOENT' || code === 'ENOTDIR' ? 'gone' : 'unknown';
363
+ }
364
+ }
365
+
366
+ /**
367
+ * listArtifacts(projectRoot, { fsImpl }) → entries newest first, each with
368
+ * `ownerId` (an Epic id, or `_tasks/<task-id>`). A missing or corrupt ledger
369
+ * contributes [] for that owner. An entry whose stored file
370
+ * (artifacts/<owner>/<name>) no longer exists — e.g. deleted from the OS file
371
+ * manager, or replaced by a symlink — or whose state is unknown (an lstat error other than
372
+ * ENOENT/ENOTDIR) is omitted (one lstat per entry through fsImpl, storedFileState); the daily sweep
373
+ * (artifactRetention.cjs) compacts such rows out of the ledger. Never throws.
374
+ */
375
+ function listArtifacts(projectRoot, { fsImpl = fs } = {}) {
376
+ /** @type {object[]} */
377
+ const out = [];
378
+ let nsDir;
379
+ try { nsDir = opsPath(projectRoot, NAMESPACE); } catch { return out; }
380
+ const dirsIn = (dir) => {
381
+ try {
382
+ return fsImpl.readdirSync(dir, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => String(d.name));
383
+ } catch { return []; }
384
+ };
385
+ /** @type {{ ownerId: string, dir: string }[]} */
386
+ const owners = [];
387
+ for (const name of dirsIn(nsDir)) {
388
+ if (name === TASKS_DIR) {
389
+ for (const t of dirsIn(path.join(nsDir, TASKS_DIR))) {
390
+ if (TASK_ID_RE.test(t)) owners.push({ ownerId: `${TASKS_DIR}/${t}`, dir: path.join(nsDir, TASKS_DIR, t) });
391
+ }
392
+ } else if (EPIC_ID_RE.test(name)) {
393
+ owners.push({ ownerId: name, dir: path.join(nsDir, name) });
394
+ }
395
+ }
396
+ for (const { ownerId, dir } of owners) {
397
+ for (const e of readLedger(path.join(dir, LEDGER), fsImpl)) {
398
+ if (storedFileState(path.join(dir, e.name), fsImpl) !== 'file') continue;
399
+ out.push({ ...e, ownerId });
400
+ }
401
+ }
402
+ const t = (e) => { const v = Date.parse(e.createdAt); return Number.isFinite(v) ? v : 0; };
403
+ out.sort((a, b) => t(b) - t(a));
404
+ return out;
405
+ }
406
+
407
+ /**
408
+ * stagingDirFor({ runId }) → <worktreeBase>/artifact-staging/<runId>, created
409
+ * mode 0700. Throws on an unsafe runId.
410
+ */
411
+ function stagingDirFor({ runId } = {}) {
412
+ if (typeof runId !== 'string' || !RUN_ID_RE.test(runId)) {
413
+ throw new Error(`artifactStore.stagingDirFor: unsafe runId "${runId}"`);
414
+ }
415
+ const { worktreeBase } = require('../scheduler/schedulerPaths.cjs');
416
+ const dir = path.join(worktreeBase(), 'artifact-staging', runId);
417
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
418
+ try { fs.chmodSync(dir, 0o700); } catch { /* best effort */ }
419
+ return dir;
420
+ }
421
+
422
+ module.exports = {
423
+ publishArtifact,
424
+ ingestDir,
425
+ listArtifacts,
426
+ storedFileState,
427
+ stagingDirFor,
428
+ inferKind,
429
+ MAX_BYTES,
430
+ MAX_INGEST_FILES,
431
+ KINDS,
432
+ EPIC_ID_RE,
433
+ TASK_ID_RE,
434
+ RUN_ID_RE,
435
+ };
@@ -26,6 +26,8 @@ const { shimPath: guardShimPath, resolveShimTarget, ensureGuardShimsOrError } =
26
26
  const { resolveProjectRoot } = require('../opsOwnership.cjs');
27
27
  const { nodeShellCommand } = require('../appRuntime.cjs');
28
28
  const { readJsonOrSync } = require('../util/atomicFs.cjs');
29
+ const { sandboxDependencies, sandboxInstallHint } = require('../claude/jobSandboxPolicy.cjs');
30
+ const { environmentEnforcementStatus } = require('../scheduler/schedulerConfig.cjs');
29
31
 
30
32
  const SCHEDULER_MCP_NAME = 'session-manager-scheduler';
31
33
  const DEV_PLUGIN_ENABLED_KEY = 'session-manager-dev@session-manager';
@@ -445,6 +447,83 @@ function checkAgentPersonas({ cwd, homeDir }) {
445
447
  };
446
448
  }
447
449
 
450
+ /** First executable `name` on PATH, or null. */
451
+ function whichOnPath(name) {
452
+ const dirs = String(process.env.PATH || '').split(path.delimiter).filter(Boolean);
453
+ for (const dir of dirs) {
454
+ const candidate = path.join(dir, name);
455
+ try { fs.accessSync(candidate, fs.constants.X_OK); return candidate; } catch { /* next */ }
456
+ }
457
+ return null;
458
+ }
459
+
460
+ /**
461
+ * Said with every missing-sandbox notice: sandboxed Bash cannot reach host
462
+ * loopback, so a live check is an http criterion the scheduler runs outside
463
+ * the sandbox (managed-agents-alignment.md#environments).
464
+ */
465
+ const SANDBOX_LOOPBACK_CLAUSE = "under the sandbox a job cannot reach services on this machine's loopback, so live checks run as http criteria";
466
+
467
+ /** A local-timezone calendar date, e.g. "Nov 30, 2026". */
468
+ function formatLocalDate(ms) {
469
+ return new Date(ms).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
470
+ }
471
+
472
+ /**
473
+ * Can headless jobs get the OS sandbox their environment requires? A machine
474
+ * runs a report-only week first (schedulerConfig.environmentEnforcementStatus,
475
+ * PRD 3942); from `enforceFrom` a job whose environment needs it (dev-lead,
476
+ * validator) parks 'environment_unavailable: <missing>' when bwrap/socat
477
+ * (linux) or sandbox-exec (macOS) is missing — so during the week the banner
478
+ * names the date enforcement starts and the packages to install, and under
479
+ * 'enforce' it is a failure. `sandboxDeps` / `platform` / `mode` /
480
+ * `enforceFrom` are injectable for tests; with no `mode` both come from the
481
+ * scheduler config.
482
+ * @param {{ sandboxDeps?: { available: boolean, missing?: string[] }|null, platform?: string, mode?: string, enforceFrom?: number|null }} [opts]
483
+ */
484
+ function checkJobSandbox({ sandboxDeps = null, platform = process.platform, mode, enforceFrom = null } = {}) {
485
+ const base = { id: 'job-sandbox', label: 'OS sandbox packages installed for headless jobs' };
486
+ let deps = sandboxDeps;
487
+ if (!deps) {
488
+ try { deps = sandboxDependencies({ platform, which: whichOnPath }); } catch (e) {
489
+ deps = { available: false, missing: [`sandbox dependency probe failed: ${(e && e.message) || e}`] };
490
+ }
491
+ }
492
+ let effectiveMode;
493
+ let from = enforceFrom;
494
+ if (mode === 'report' || mode === 'enforce') {
495
+ effectiveMode = mode;
496
+ } else {
497
+ const status = environmentEnforcementStatus();
498
+ effectiveMode = status.mode;
499
+ from = status.enforceFrom;
500
+ }
501
+ const date = effectiveMode === 'report' && typeof from === 'number' && Number.isFinite(from) ? formatLocalDate(from) : null;
502
+ if (deps.available) {
503
+ const detail = date
504
+ ? `OS sandbox dependencies present — report mode until enforcement starts ${date}`
505
+ : 'OS sandbox dependencies present';
506
+ return { ...base, ok: true, detail, fix: null };
507
+ }
508
+ const missing = Array.isArray(deps.missing) && deps.missing.length ? deps.missing : ['unknown'];
509
+ const hint = sandboxInstallHint({ platform, missing });
510
+ const fix = hint.packages.length
511
+ ? `Install ${hint.packages.join(', ')}${hint.command ? ` (${hint.command})` : ''}${date ? ` before ${date}` : ''}, then restart Session Manager`
512
+ : `Run Session Manager on Linux (bubblewrap + socat) or macOS (sandbox-exec)`;
513
+ if (effectiveMode === 'report') {
514
+ const detail = date
515
+ ? `missing: ${missing.join(', ')} — report mode until ${date}: jobs fall back to tool rules now; from ${date} headless dev-lead and validator jobs will park with environment_unavailable until installed; ${SANDBOX_LOOPBACK_CLAUSE}`
516
+ : `missing: ${missing.join(', ')} — report mode: jobs fall back to tool rules; ${SANDBOX_LOOPBACK_CLAUSE}`;
517
+ return { ...base, ok: true, warn: true, detail, fix };
518
+ }
519
+ return {
520
+ ...base,
521
+ ok: false,
522
+ detail: `missing: ${missing.join(', ')} — dev-lead and validator jobs park with environment_unavailable until installed; ${SANDBOX_LOOPBACK_CLAUSE}`,
523
+ fix,
524
+ };
525
+ }
526
+
448
527
  /**
449
528
  * Pull a guard script's path out of a hook `command` string.
450
529
  *
@@ -717,7 +796,7 @@ async function installSelfScheduleGuard({ cwd, homeDir = os.homedir(), skipShimE
717
796
  }
718
797
 
719
798
  /**
720
- * Runs all eight delegation-readiness checks for `cwd`. Every filesystem read
799
+ * Runs all ten delegation-readiness checks for `cwd`. Every filesystem read
721
800
  * is wrapped (readJsonOrSync / try-catch) so a missing or unparseable file
722
801
  * yields ok:false with a detail, never a thrown exception. Async because
723
802
  * scheduler-mcp-live genuinely spawns a process and waits on it (bounded by
@@ -725,7 +804,7 @@ async function installSelfScheduleGuard({ cwd, homeDir = os.homedir(), skipShimE
725
804
  * callers — the New Epic banner, session_manager_help — don't each pay for
726
805
  * a fresh spawn).
727
806
  */
728
- async function checkDelegationReadiness({ cwd, homeDir = os.homedir() }) {
807
+ async function checkDelegationReadiness({ cwd, homeDir = os.homedir(), sandboxDeps = null, sandboxPlatform, environmentMode }) {
729
808
  const schedulerMcpCheck = checkSchedulerMcp({ cwd, homeDir });
730
809
  const schedulerMcpLiveCheck = await checkSchedulerMcpLive({ cwd, homeDir, schedulerMcpCheck });
731
810
 
@@ -742,6 +821,7 @@ async function checkDelegationReadiness({ cwd, homeDir = os.homedir() }) {
742
821
  checkDestructiveGitGuard({ cwd, homeDir }),
743
822
  checkInlineImplementationGuard({ cwd, homeDir }),
744
823
  checkSelfScheduleGuard({ cwd, homeDir }),
824
+ checkJobSandbox({ sandboxDeps, platform: sandboxPlatform, mode: environmentMode }),
745
825
  ].map((c) => ({ fixAction: null, warn: false, ...c }));
746
826
 
747
827
  return {
@@ -895,6 +975,7 @@ module.exports = {
895
975
  checkDevPlugin,
896
976
  DEV_PLUGIN_REINSTALL_FIX,
897
977
  checkDelegationReadiness,
978
+ checkJobSandbox,
898
979
  ensureGuardsInstalled,
899
980
  logAutoInstallEvent,
900
981
  clearGuardsInstalledCache,
@@ -0,0 +1,97 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * epicAgentRefresh.cjs — the ONLY path by which a live persona edit reaches an existing Epic.
5
+ *
6
+ * An Epic minted with an agentType pins its persona as an AgentSnapshot (epicMint.cjs's
7
+ * AGENT SNAPSHOT PIN); every later turn builds from that snapshot, so an edit to the persona
8
+ * file reaches only NEW Epics. refreshEpicAgentSnapshot is the explicit, audited action that
9
+ * re-snapshots the persona (same agentType + packs) and re-stamps the Epic's agentSnapshotId.
10
+ * One audit record { kind: 'epic_agent_snapshot_updated', epicId, from, to } per change; an
11
+ * unchanged persona (same content id) is a no-op that writes nothing.
12
+ *
13
+ * Electron-free at load; electron/config/ipcSchemas are required lazily in the register fn.
14
+ */
15
+
16
+ const { activeIndexPath, readActiveIndex, writeActiveIndex, withPathLock } = require('./epicMint.cjs');
17
+ const { mirrorEpicStatus } = require('./epicStatusMirror.cjs');
18
+ const { appendAuditEvent } = require('../telemetry/auditLog.cjs');
19
+
20
+ const AUDIT_KIND = 'epic_agent_snapshot_updated';
21
+
22
+ const fail = (code, message) => ({ ok: false, code, message });
23
+
24
+ function readRow(cwd, epicId) {
25
+ const index = readActiveIndex(cwd);
26
+ return Object.prototype.hasOwnProperty.call(index.sessions, epicId) ? index.sessions[epicId] : null;
27
+ }
28
+
29
+ /**
30
+ * @param {{ cwd: string, epicId: string, deps?: object }} opts
31
+ * @returns {Promise<
32
+ * | { ok: true, changed: boolean, from: string|null, to: string, session: object }
33
+ * | { ok: false, code: string, message: string }>}
34
+ */
35
+ async function refreshEpicAgentSnapshot({ cwd, epicId, deps = {} } = {}) {
36
+ if (typeof cwd !== 'string' || !cwd || typeof epicId !== 'string' || !epicId) {
37
+ return fail('invalid_args', 'cwd and epicId are required.');
38
+ }
39
+ const row = readRow(cwd, epicId);
40
+ if (!row) return fail('not_found', `No open Epic ${epicId} in ${cwd}.`);
41
+ if (!row.agentType) return fail('no_agent_type', `Epic ${epicId} has no agentType to snapshot.`);
42
+ if (row.agentCli) return fail('not_pinnable', `Epic ${epicId} runs a non-Claude agent CLI; it loads no persona.`);
43
+
44
+ const agentSnapshot = require('../claude/agentSnapshot.cjs');
45
+ const build = deps.buildAgentSnapshot || agentSnapshot.buildAgentSnapshot;
46
+ const built = await build({
47
+ cwd,
48
+ agentType: row.agentType,
49
+ packs: Array.isArray(row.packs) ? row.packs : [],
50
+ deps: deps.snapshotDeps || {},
51
+ });
52
+ if (built.refusal) return fail(built.refusal.code, built.refusal.detail);
53
+
54
+ const from = typeof row.agentSnapshotId === 'string' ? row.agentSnapshotId : null;
55
+ if (built.id === from) return { ok: true, changed: false, from, to: built.id, session: row };
56
+
57
+ // Write-once + content-addressed: an id another Epic already pinned is a no-op write.
58
+ const write = deps.writeAgentSnapshot || agentSnapshot.writeAgentSnapshot;
59
+ await write(cwd, built.snapshot);
60
+
61
+ let result;
62
+ try {
63
+ result = await withPathLock(activeIndexPath(cwd), async () => {
64
+ const index = readActiveIndex(cwd);
65
+ const current = Object.prototype.hasOwnProperty.call(index.sessions, epicId) ? index.sessions[epicId] : null;
66
+ if (!current) return fail('not_found', `Epic ${epicId} disappeared before it could be re-stamped.`);
67
+ const prior = typeof current.agentSnapshotId === 'string' ? current.agentSnapshotId : null;
68
+ if (prior === built.id) return { ok: true, changed: false, from: prior, to: built.id, session: current };
69
+ const session = { ...current, agentSnapshotId: built.id };
70
+ index.sessions[epicId] = session;
71
+ writeActiveIndex(cwd, index);
72
+ mirrorEpicStatus(cwd, epicId, { session });
73
+ return { ok: true, changed: true, from: prior, to: built.id, session };
74
+ });
75
+ } catch (err) {
76
+ return fail('write_failed', `Could not re-stamp Epic ${epicId}: ${err && err.message ? err.message : err}`);
77
+ }
78
+ if (result.ok && result.changed) {
79
+ appendAuditEvent(AUDIT_KIND, { cwd, epicId, from: result.from, to: result.to }, deps.auditOpts || {});
80
+ }
81
+ return result;
82
+ }
83
+
84
+ function registerEpicAgentRefreshHandlers() {
85
+ const { ipcMain } = require('electron');
86
+ const { validatePath } = require('../../config.cjs');
87
+ const { schemas: s, validated: v } = require('../../ipcSchemas.cjs');
88
+ ipcMain.handle(
89
+ 'epic:refresh-agent-snapshot',
90
+ v(s.epicRefreshAgentSnapshot, ({ cwd, epicId }) => {
91
+ validatePath(cwd);
92
+ return refreshEpicAgentSnapshot({ cwd, epicId });
93
+ }),
94
+ );
95
+ }
96
+
97
+ module.exports = { refreshEpicAgentSnapshot, registerEpicAgentRefreshHandlers, AUDIT_KIND };