claude-code-session-manager 0.141.0 → 0.142.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (200) hide show
  1. package/README.md +80 -70
  2. package/bin/cli.cjs +11 -0
  3. package/dist/assets/AppSettings-BcZgIvvY.js +2 -0
  4. package/dist/assets/{History-DJMiuXyK.js → History-DpZuJXi1.js} +1 -1
  5. package/dist/assets/HomeClaudeConfig-D32ZJtU-.js +3 -0
  6. package/dist/assets/{Panel-Bf1Cf8UL.js → Panel-BjdJjhqt.js} +1 -1
  7. package/dist/assets/{ProjectClaudeConfig-BWPpypf9.js → ProjectClaudeConfig-BTClYV6i.js} +7 -7
  8. package/dist/assets/Scheduler-DPobKx1Z.js +16 -0
  9. package/dist/assets/{SkillReferenceGraph-Ba4TkX2C.js → SkillReferenceGraph-Cqyu4mef.js} +1 -1
  10. package/dist/assets/{Skills-C1v91GEO.js → Skills-vv0noNVI.js} +5 -5
  11. package/dist/assets/{TiptapBody-BrcWVpiW.js → TiptapBody-CXi8Pvut.js} +1 -1
  12. package/dist/assets/Toggle-CiYCWLjh.js +1 -0
  13. package/dist/assets/{VoiceButton-qivnDV6K.js → VoiceButton-4NKKd1sC.js} +1 -1
  14. package/dist/assets/{historyTotals-CMCPTKqC.js → historyTotals-DDunb8Ch.js} +1 -1
  15. package/dist/assets/index-Cn5E9958.js +3133 -0
  16. package/dist/assets/{index-DKXdXfka.css → index-DVHIHoJf.css} +1 -1
  17. package/dist/index.html +2 -2
  18. package/dist-web/app.css +1 -1
  19. package/dist-web/app.js +496 -484
  20. package/package.json +4 -2
  21. package/plugins/AGENTS.md +4 -3
  22. package/plugins/session-manager-dev/hooks/hooks.json +15 -0
  23. package/plugins/session-manager-dev/hooks/residue-check.cjs +241 -0
  24. package/plugins/session-manager-dev/skills/develop/SKILL.md +52 -18
  25. package/plugins/session-manager-dev/skills/develop/standards.md +3 -2
  26. package/scripts/README.md +1 -0
  27. package/scripts/hooks/guard-tool-risk.cjs +5 -1
  28. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +158 -1
  29. package/scripts/scheduler-mcp-server.cjs +732 -110
  30. package/src/main/adminRouteRegistry.cjs +59 -0
  31. package/src/main/agentLibrary.cjs +72 -4
  32. package/src/main/agentsIpc.cjs +3 -2
  33. package/src/main/build-info.json +4 -4
  34. package/src/main/chatRunner.cjs +231 -16
  35. package/src/main/config.cjs +30 -0
  36. package/src/main/docEdit.cjs +4 -2
  37. package/src/main/health.cjs +91 -0
  38. package/src/main/index.cjs +98 -48
  39. package/src/main/ipcSchemas.cjs +161 -8
  40. package/src/main/lib/AGENTS.md +1 -1
  41. package/src/main/lib/chatBootRecovery.cjs +2 -0
  42. package/src/main/lib/claude/agentModelResolve.cjs +51 -25
  43. package/src/main/lib/claude/agentSnapshot.cjs +186 -0
  44. package/src/main/lib/claude/environmentProfiles.cjs +242 -0
  45. package/src/main/lib/claude/jobSandboxPolicy.cjs +241 -33
  46. package/src/main/lib/claude/personaToolScope.cjs +82 -31
  47. package/src/main/lib/claude/runClaudeP.cjs +4 -2
  48. package/src/main/lib/claude/toolRiskMarks.cjs +41 -1
  49. package/src/main/lib/claude/usageCircuit.cjs +49 -21
  50. package/src/main/lib/claude/vaultRefs.cjs +277 -0
  51. package/src/main/lib/demo-video-kit/capture.cjs +282 -12
  52. package/src/main/lib/demo-video-kit/cast.md +43 -0
  53. package/src/main/lib/demo-video-kit/character.cjs +722 -30
  54. package/src/main/lib/demo-video-kit/checks.cjs +120 -1
  55. package/src/main/lib/demo-video-kit/export.cjs +218 -0
  56. package/src/main/lib/demo-video-kit/frames.cjs +104 -9
  57. package/src/main/lib/demo-video-kit/kind-marketing.md +121 -0
  58. package/src/main/lib/demo-video-kit/kind-tiktok.md +99 -0
  59. package/src/main/lib/demo-video-kit/kokoroSay.cjs +205 -0
  60. package/src/main/lib/demo-video-kit/project-home-html.md +43 -0
  61. package/src/main/lib/demo-video-kit/resumableRun.cjs +298 -0
  62. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  63. package/src/main/lib/demo-video-kit/voiceLane.cjs +233 -0
  64. package/src/main/lib/demo-video-kit/voiceLibrary.cjs +312 -0
  65. package/src/main/lib/epic/artifactAdminRoutes.cjs +211 -0
  66. package/src/main/lib/epic/artifactIpc.cjs +153 -0
  67. package/src/main/lib/epic/artifactNotice.cjs +72 -0
  68. package/src/main/lib/epic/artifactRetention.cjs +310 -0
  69. package/src/main/lib/epic/artifactStore.cjs +392 -0
  70. package/src/main/lib/epic/delegationReadiness.cjs +76 -2
  71. package/src/main/lib/epic/epicAgentRefresh.cjs +97 -0
  72. package/src/main/lib/epic/epicEventLog.cjs +214 -0
  73. package/src/main/lib/epic/epicMint.cjs +43 -1
  74. package/src/main/lib/epic/epicOutsideRead.cjs +1 -0
  75. package/src/main/lib/epic/epicOutsideState.cjs +18 -4
  76. package/src/main/lib/epic/epicPurge.cjs +347 -0
  77. package/src/main/lib/epic/epicReopen.cjs +5 -2
  78. package/src/main/lib/epic/epicSettle.cjs +4 -13
  79. package/src/main/lib/epic/epicSpawnPlan.cjs +57 -4
  80. package/src/main/lib/epic/epicStatusMirror.cjs +34 -1
  81. package/src/main/lib/epic/epicTransitions.cjs +139 -0
  82. package/src/main/lib/epic/epicValidationHook.cjs +81 -2
  83. package/src/main/lib/epic/guardSpawnSettings.cjs +3 -2
  84. package/src/main/lib/externalContract.cjs +37 -4
  85. package/src/main/lib/feedback-remote/crossProjectReply.cjs +389 -126
  86. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -3
  87. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +11 -6
  88. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +26 -1
  89. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +5 -2
  90. package/src/main/lib/feedback-remote/feedbackBoxDrain.cjs +409 -0
  91. package/src/main/lib/feedback-remote/feedbackBoxKeys.cjs +218 -0
  92. package/src/main/lib/feedback-remote/feedbackEnvelope.cjs +163 -0
  93. package/src/main/lib/feedback-remote/feedbackRelayClient.cjs +164 -0
  94. package/src/main/lib/feedback-remote/feedbackReport.cjs +234 -0
  95. package/src/main/lib/feedback-remote/feedbackSeal.cjs +217 -0
  96. package/src/main/lib/feedback-remote/localAdminHttp.cjs +108 -2
  97. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +2 -1
  98. package/src/main/lib/feedback-remote/needsYouIpc.cjs +17 -0
  99. package/src/main/lib/feedback-remote/needsYouStore.cjs +177 -6
  100. package/src/main/lib/feedback-remote/pendingReplies.cjs +189 -0
  101. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +188 -10
  102. package/src/main/lib/feedback-remote/serviceClient.cjs +429 -0
  103. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +252 -0
  104. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +284 -0
  105. package/src/main/lib/feedback-remote/servicePairings.cjs +313 -0
  106. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +290 -0
  107. package/src/main/lib/feedback-remote/siteFeedbackAdminRoutes.cjs +295 -0
  108. package/src/main/lib/feedback-remote/siteFeedbackInbox.cjs +598 -0
  109. package/src/main/lib/feedback-remote/siteFeedbackIpc.cjs +86 -0
  110. package/src/main/lib/feedback-remote/siteFeedbackService.cjs +477 -0
  111. package/src/main/lib/git/worktreeDeps.cjs +77 -2
  112. package/src/main/lib/mcpToolCatalog.cjs +304 -28
  113. package/src/main/lib/opsOwnership.cjs +29 -1
  114. package/src/main/lib/opsRetentionSettings.cjs +27 -5
  115. package/src/main/lib/persona-macro/builtinMacros.cjs +7 -2
  116. package/src/main/lib/persona-macro/macroJobDispatch.cjs +52 -8
  117. package/src/main/lib/persona-macro/macroJobIpc.cjs +16 -6
  118. package/src/main/lib/persona-macro/macroLibrary.cjs +49 -7
  119. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +83 -0
  120. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +3 -0
  121. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +263 -0
  122. package/src/main/lib/phaseProjection.cjs +103 -0
  123. package/src/main/lib/prd/depSlugResolve.cjs +4 -13
  124. package/src/main/lib/prd/prdBodyPatch.cjs +12 -17
  125. package/src/main/lib/prd/prdCreate.cjs +41 -5
  126. package/src/main/lib/prd/prdCriteria.cjs +225 -0
  127. package/src/main/lib/prd/prdFrontmatter.cjs +43 -3
  128. package/src/main/lib/prd/prdGateFiles.cjs +125 -49
  129. package/src/main/lib/prd/prdSizing.cjs +3 -1
  130. package/src/main/lib/process/cleanEnv.cjs +52 -1
  131. package/src/main/lib/process/leftoverRenice.cjs +178 -0
  132. package/src/main/lib/process/memoryScope.cjs +31 -3
  133. package/src/main/lib/project-pages/pagesLibrary.cjs +72 -6
  134. package/src/main/lib/project-pages/videoReviewIpc.cjs +3 -2
  135. package/src/main/lib/project-pages/voiceAdminRoutes.cjs +175 -0
  136. package/src/main/lib/project-pages/voicePreview.cjs +196 -0
  137. package/src/main/lib/project-pages/voicesIpc.cjs +186 -0
  138. package/src/main/lib/promptSessionSchema.cjs +6 -0
  139. package/src/main/lib/scheduler/cancelledRow.cjs +57 -0
  140. package/src/main/lib/scheduler/cpuSample.cjs +133 -42
  141. package/src/main/lib/scheduler/criteriaChecks.cjs +169 -0
  142. package/src/main/lib/scheduler/definitionOfDone.cjs +44 -5
  143. package/src/main/lib/scheduler/jobMemoryStats.cjs +313 -0
  144. package/src/main/lib/scheduler/loadGate.cjs +82 -4
  145. package/src/main/lib/scheduler/planRecordHarvest.cjs +32 -2
  146. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +133 -0
  147. package/src/main/lib/scheduler/runLogRetention.cjs +42 -1
  148. package/src/main/lib/scheduler/scheduleJobSchema.cjs +5 -0
  149. package/src/main/lib/scheduler/scheduleJobTransitions.cjs +47 -0
  150. package/src/main/lib/scheduler/schedulerConfig.cjs +47 -0
  151. package/src/main/lib/scheduler/schedulerPaths.cjs +0 -3
  152. package/src/main/lib/scheduler/schedulerRuntimeState.cjs +50 -1
  153. package/src/main/lib/scheduler/sessionSlots.cjs +5 -1
  154. package/src/main/lib/scheduler/slotsRoute.cjs +237 -0
  155. package/src/main/lib/scheduler/toolClearance.cjs +258 -0
  156. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +140 -10
  157. package/src/main/lib/tasks/memoryConsolidation.cjs +300 -0
  158. package/src/main/lib/tasks/mitigationReview.cjs +294 -0
  159. package/src/main/lib/tasks/taskAdminRoutes.cjs +312 -22
  160. package/src/main/lib/tasks/taskIpc.cjs +22 -18
  161. package/src/main/lib/tasks/taskLedger.cjs +147 -25
  162. package/src/main/lib/tasks/taskRun.cjs +186 -17
  163. package/src/main/lib/tasks/taskSwitch.cjs +85 -12
  164. package/src/main/lib/tasks/taskSwitchRoute.cjs +172 -0
  165. package/src/main/lib/telemetry/auditEvents.cjs +207 -6
  166. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +198 -6
  167. package/src/main/lib/telemetry/webhookDelivery.cjs +205 -0
  168. package/src/main/lib/telemetry/webhookRegistry.cjs +281 -0
  169. package/src/main/lib/toolUseClassify.cjs +181 -0
  170. package/src/main/lib/util/smfileRange.cjs +77 -0
  171. package/src/main/projectPages.cjs +3 -1
  172. package/src/main/promptSessionEvents.cjs +5 -0
  173. package/src/main/pty.cjs +68 -0
  174. package/src/main/queueOps.cjs +32 -13
  175. package/src/main/runVerify.cjs +74 -9
  176. package/src/main/scheduler/AGENTS.md +1 -0
  177. package/src/main/scheduler/budget.cjs +6 -5
  178. package/src/main/scheduler/prdParser.cjs +46 -13
  179. package/src/main/scheduler/reviewLadder.cjs +9 -25
  180. package/src/main/scheduler/utilizationHold.cjs +101 -0
  181. package/src/main/scheduler.cjs +1414 -189
  182. package/src/main/templates/PRD_AUTHORING.md +5 -2
  183. package/src/main/webRemote.cjs +463 -6
  184. package/src/preload/api.d.ts +529 -38
  185. package/src/preload/apiSurface.json +209 -7
  186. package/src/preload/index.cjs +46 -1
  187. package/src/seed/agents/architect.md +6 -1
  188. package/src/seed/agents/blender-artist.md +2 -1
  189. package/src/seed/agents/competitive-analyst.md +3 -1
  190. package/src/seed/agents/competitive-researcher.md +2 -1
  191. package/src/seed/agents/demo-video-builder.md +87 -83
  192. package/src/seed/agents/dev-lead.md +3 -3
  193. package/src/seed/agents/project-home-builder.md +9 -31
  194. package/src/seed/agents/validator.md +9 -10
  195. package/dist/assets/AppSettings-DExeJhqQ.js +0 -2
  196. package/dist/assets/HomeClaudeConfig-CTp2tkZ4.js +0 -3
  197. package/dist/assets/Scheduler-cyr61UAC.js +0 -16
  198. package/dist/assets/ViewTabs-DXhOWFG0.js +0 -1
  199. package/dist/assets/index-B2TQz3nd.js +0 -3121
  200. package/src/main/lib/epic/epicStateWatcher.cjs +0 -157
@@ -0,0 +1,211 @@
1
+ // @ts-check
2
+ /**
3
+ * artifactAdminRoutes.cjs — loopback admin HTTP routes in front of the per-project
4
+ * Artifacts store (artifactStore.cjs, the ONE writer of `artifacts/`). The artifact
5
+ * MCP tool and other local callers reach the store only through here:
6
+ * POST /admin/artifacts/publish { path, title?, kind?, cwd?, originClaudeSessionId?, sourcePromptId? }
7
+ * -> { ok, storedPath, revealPath, entry }
8
+ * GET /admin/artifacts?cwd= -> { ok, projectRoot, artifacts }
9
+ *
10
+ * The bearer-token check is the transport's (localAdminHttp.cjs handleRequest), shared
11
+ * by every admin route. The calling project + Epic come from resolveProjectContext
12
+ * (projectRootResolve.cjs), so a caller inside an Epic worktree, or one that only knows
13
+ * its claude session id, still lands on the main project and its Epic. A relative
14
+ * `path` resolves against that Epic's worktree when known, else the project root.
15
+ * Allowed source roots: project root, the Epic worktree, the artifact staging base,
16
+ * os.tmpdir().
17
+ *
18
+ * Refusals are 4xx `{ ok:false, error, message }` where `error` names the reason:
19
+ * bad_request, no_project, no_epic, not_found, outside_root, not_a_file, too_large,
20
+ * refused. Deliberately NO route that mints an Epic (SINGLE-CREATOR LAW, epicMint.cjs).
21
+ */
22
+ 'use strict';
23
+
24
+ const os = require('node:os');
25
+ const path = require('node:path');
26
+ const { readBody, sendJson } = require('../feedback-remote/localAdminHttp.cjs');
27
+
28
+ const MAX_PATH = 4096;
29
+ const MAX_TITLE = 500;
30
+ const MAX_ID = 200;
31
+
32
+ class RouteError extends Error {
33
+ /** @param {number} status @param {string} code @param {string} message */
34
+ constructor(status, code, message) {
35
+ super(message);
36
+ this.status = status;
37
+ this.code = code;
38
+ }
39
+ }
40
+
41
+ /** @param {string} message */
42
+ const bad = (message) => new RouteError(400, 'bad_request', message);
43
+
44
+ /** @param {any} req @returns {Promise<Record<string, unknown>>} */
45
+ async function readJsonBody(req) {
46
+ let raw;
47
+ try {
48
+ raw = await readBody(req);
49
+ } catch (/** @type {any} */ e) {
50
+ throw bad(`request body rejected: ${e?.message ?? 'unreadable'}`);
51
+ }
52
+ /** @type {any} */
53
+ let body;
54
+ try {
55
+ body = raw ? JSON.parse(raw) : {};
56
+ } catch {
57
+ throw bad('invalid JSON body');
58
+ }
59
+ if (!body || typeof body !== 'object' || Array.isArray(body)) throw bad('body must be a JSON object');
60
+ return body;
61
+ }
62
+
63
+ /** @param {unknown} v @param {string} name @param {number} max @returns {string | undefined} */
64
+ function optString(v, name, max) {
65
+ if (v === undefined || v === null || v === '') return undefined;
66
+ if (typeof v !== 'string' || v.length > max) throw bad(`${name} must be a string of at most ${max} characters`);
67
+ return v;
68
+ }
69
+
70
+ /** @param {unknown} v @returns {string | undefined} */
71
+ function optAbsCwd(v) {
72
+ const s = optString(v, 'cwd', MAX_PATH);
73
+ if (s !== undefined && !path.isAbsolute(s)) throw bad('cwd must be an absolute path');
74
+ return s;
75
+ }
76
+
77
+ /**
78
+ * Map an artifactStore refusal string to a status + reason code.
79
+ * @param {string} error
80
+ * @returns {RouteError}
81
+ */
82
+ function storeRefusal(error) {
83
+ const msg = String(error || 'publish refused');
84
+ if (/outside every allowed root|already inside the artifacts store/.test(msg)) return new RouteError(400, 'outside_root', msg);
85
+ if (/not a regular file|is a symlink/.test(msg)) return new RouteError(400, 'not_a_file', msg);
86
+ if (/oversize/.test(msg)) return new RouteError(413, 'too_large', msg);
87
+ if (/source unreadable|source unresolvable/.test(msg)) {
88
+ return /ENOENT/.test(msg) ? new RouteError(404, 'not_found', msg) : new RouteError(400, 'not_a_file', msg);
89
+ }
90
+ if (/kind must be|absolute path|unsafe epicId|exactly one of/.test(msg)) return new RouteError(400, 'bad_request', msg);
91
+ if (/copy failed|ledger write failed|publish failed/.test(msg)) return new RouteError(500, 'internal', msg);
92
+ return new RouteError(400, 'refused', msg);
93
+ }
94
+
95
+ /** The artifact staging base (<worktreeBase>/artifact-staging), or null when unresolvable. */
96
+ function defaultStagingBase() {
97
+ try {
98
+ const { worktreeBase } = require('../scheduler/schedulerPaths.cjs');
99
+ return path.join(worktreeBase(), 'artifact-staging');
100
+ } catch {
101
+ return null;
102
+ }
103
+ }
104
+
105
+ /**
106
+ * The Epic's own worktree dir from its PromptSession (`worktree.dir`), or null.
107
+ * @param {(cwd: string) => { sessions: Record<string, any> }} readActiveIndexFn
108
+ * @param {string} projectCwd
109
+ * @param {string} epicId
110
+ * @returns {string | null}
111
+ */
112
+ function epicWorktreeDir(readActiveIndexFn, projectCwd, epicId) {
113
+ try {
114
+ const { sessions } = readActiveIndexFn(projectCwd);
115
+ const dir = sessions && sessions[epicId] && sessions[epicId].worktree && sessions[epicId].worktree.dir;
116
+ return typeof dir === 'string' && path.isAbsolute(dir) ? dir : null;
117
+ } catch {
118
+ return null;
119
+ }
120
+ }
121
+
122
+ /**
123
+ * @param {(req: any, query: URLSearchParams) => Promise<Record<string, unknown>>} fn
124
+ */
125
+ function route(fn) {
126
+ return async (/** @type {any} */ req, /** @type {any} */ res, /** @type {URLSearchParams} */ query) => {
127
+ try {
128
+ sendJson(res, 200, await fn(req, query || new URLSearchParams()));
129
+ } catch (e) {
130
+ if (e instanceof RouteError) {
131
+ sendJson(res, e.status, { ok: false, error: e.code, message: e.message });
132
+ return;
133
+ }
134
+ sendJson(res, 500, { ok: false, error: 'internal', message: e instanceof Error ? e.message : 'request failed' });
135
+ }
136
+ };
137
+ }
138
+
139
+ /**
140
+ * @typedef {{
141
+ * store?: { publishArtifact: Function, listArtifacts: Function },
142
+ * resolveProjectContext?: Function,
143
+ * readActiveIndex?: (cwd: string) => { sessions: Record<string, any> },
144
+ * stagingBase?: () => string | null,
145
+ * tmpdir?: () => string,
146
+ * postArtifactReadyNotice?: Function,
147
+ * }} ArtifactRouteDeps
148
+ */
149
+
150
+ /**
151
+ * @param {any} adminHttp
152
+ * @param {ArtifactRouteDeps} [deps] test seams
153
+ */
154
+ function registerAdminRoute(adminHttp, deps = {}) {
155
+ const store = () => deps.store || require('./artifactStore.cjs');
156
+ const resolveCtx = (/** @type {any} */ args) => (
157
+ deps.resolveProjectContext || require('../projectRootResolve.cjs').resolveProjectContext
158
+ )(args);
159
+ const readIndex = (/** @type {string} */ cwd) => (deps.readActiveIndex || require('./epicMint.cjs').readActiveIndex)(cwd);
160
+ const stagingBase = deps.stagingBase || defaultStagingBase;
161
+ const tmpdir = deps.tmpdir || os.tmpdir;
162
+ const postNotice = deps.postArtifactReadyNotice || require('./artifactNotice.cjs').postArtifactReadyNotice;
163
+
164
+ adminHttp.registerRoute('POST', '/admin/artifacts/publish', route(async (req) => {
165
+ const b = await readJsonBody(req);
166
+ const rawPath = optString(b.path, 'path', MAX_PATH);
167
+ if (!rawPath) throw bad('path is required');
168
+ const title = optString(b.title, 'title', MAX_TITLE);
169
+ const kind = optString(b.kind, 'kind', 20);
170
+ const cwd = optAbsCwd(b.cwd);
171
+ const originClaudeSessionId = optString(b.originClaudeSessionId, 'originClaudeSessionId', MAX_ID);
172
+ const sourcePromptId = optString(b.sourcePromptId, 'sourcePromptId', MAX_ID);
173
+
174
+ const ctx = resolveCtx({ cwd, originClaudeSessionId, epicId: sourcePromptId }) || {};
175
+ const projectRoot = typeof ctx.cwd === 'string' && ctx.cwd ? ctx.cwd : null;
176
+ if (!projectRoot) throw new RouteError(400, 'no_project', 'could not resolve the calling project: give cwd, originClaudeSessionId or sourcePromptId');
177
+ const epicId = typeof ctx.epicId === 'string' && ctx.epicId ? ctx.epicId : null;
178
+ if (!epicId) throw new RouteError(400, 'no_epic', 'no Epic resolved for this caller: give originClaudeSessionId or sourcePromptId of an Epic in this project');
179
+
180
+ const worktreeDir = epicWorktreeDir(readIndex, ctx.epicCwd || projectRoot, epicId);
181
+ const srcPath = path.isAbsolute(rawPath) ? path.resolve(rawPath) : path.resolve(worktreeDir || projectRoot, rawPath);
182
+ const allowedRoots = [projectRoot, worktreeDir, stagingBase(), tmpdir()]
183
+ .filter((r) => typeof r === 'string' && path.isAbsolute(r));
184
+
185
+ const result = await store().publishArtifact({
186
+ projectRoot,
187
+ epicId,
188
+ srcPath,
189
+ title,
190
+ kind,
191
+ producer: { epicId, sessionId: originClaudeSessionId || null },
192
+ allowedRoots,
193
+ });
194
+ if (!result || !result.ok) throw storeRefusal(result && result.error);
195
+ // One 'artifact-ready' notice per publish call, in the owning Epic's chat (never throws).
196
+ await postNotice({ cwd: projectRoot, epicId, entries: [{ storedPath: result.storedPath, entry: result.entry }] });
197
+ const revealPath = path.relative(projectRoot, result.storedPath).split(path.sep).join('/');
198
+ return { ok: true, storedPath: result.storedPath, revealPath, entry: result.entry };
199
+ }));
200
+
201
+ adminHttp.registerRoute('GET', '/admin/artifacts', route(async (_req, q) => {
202
+ const cwd = optAbsCwd(q.get('cwd'));
203
+ if (!cwd) throw bad('cwd is required (absolute path)');
204
+ const ctx = resolveCtx({ cwd }) || {};
205
+ const projectRoot = typeof ctx.cwd === 'string' && ctx.cwd ? ctx.cwd : null;
206
+ if (!projectRoot) throw new RouteError(400, 'no_project', `could not resolve a project for ${cwd}`);
207
+ return { ok: true, projectRoot, artifacts: store().listArtifacts(projectRoot) };
208
+ }));
209
+ }
210
+
211
+ module.exports = { registerAdminRoute };
@@ -0,0 +1,153 @@
1
+ // @ts-check
2
+ 'use strict';
3
+
4
+ /**
5
+ * artifactIpc.cjs — read-only renderer IPC for a project's Artifacts store and its
6
+ * unmerged Epic worktrees, so the File Explorer can show work that has not landed yet.
7
+ *
8
+ * artifacts:list { cwd } → { ok, artifacts: [...listArtifacts entry, epicTitle] }
9
+ * artifacts:worktrees { cwd } → { ok, worktrees: [{ epicId, title, path, branch, aheadOfBase, uncommitted }] }
10
+ *
11
+ * Both payloads are strict zod schemas (ipcSchemas.cjs); `cwd` additionally passes
12
+ * config.cjs's validatePath, like every other renderer-supplied cwd. Epic records come
13
+ * from the project's prompt-sessions active index (epicMint.readActiveIndex) — titles of
14
+ * Epics no longer in the index fall back to their prompt-sessions/<id>.json mirror.
15
+ * Nothing here scans ~/.claude/projects, and nothing writes.
16
+ */
17
+
18
+ const fs = require('node:fs');
19
+ const path = require('node:path');
20
+
21
+ /** Per-git-call bound — one slow repo must not hang the Explorer. */
22
+ const GIT_TIMEOUT_MS = 10_000;
23
+
24
+ /** Upper bound on a worktree's reported uncommitted-path count. */
25
+ const UNCOMMITTED_CAP = 999;
26
+
27
+ /** goalText's first paragraph (an Epic's title), or null. */
28
+ /** @param {{ goalText?: unknown } | null | undefined} record */
29
+ function titleOf(record) {
30
+ const goalText = record && typeof record.goalText === 'string' ? record.goalText : '';
31
+ const m = /\r?\n[ \t]*\r?\n/.exec(goalText);
32
+ const head = (m ? goalText.slice(0, m.index) : goalText).trim();
33
+ return head || null;
34
+ }
35
+
36
+ /** @param {string} p */
37
+ function realOrResolved(p) {
38
+ try { return fs.realpathSync(p); } catch { return path.resolve(p); }
39
+ }
40
+
41
+ /** @param {string} p */
42
+ function isDir(p) {
43
+ try { return fs.statSync(p).isDirectory(); } catch { return false; }
44
+ }
45
+
46
+ /**
47
+ * @param {{
48
+ * readActiveIndex?: (cwd: string) => { sessions: Record<string, any> },
49
+ * readMirror?: (cwd: string, epicId: string) => any,
50
+ * listArtifacts?: (cwd: string) => any[],
51
+ * execGit?: (cwd: string, args: string[], opts?: { timeout?: number }) => Promise<string>,
52
+ * }} [deps]
53
+ */
54
+ function makeArtifactReaders(deps = {}) {
55
+ const readActiveIndex = deps.readActiveIndex || ((cwd) => require('./epicMint.cjs').readActiveIndex(cwd));
56
+ const listArtifacts = deps.listArtifacts || ((cwd) => require('./artifactStore.cjs').listArtifacts(cwd));
57
+ const execGit = deps.execGit || require('../git/gitExec.cjs').execGit;
58
+ const readMirror = deps.readMirror || ((cwd, epicId) => {
59
+ const { epicMirrorPath } = require('./epicStatusMirror.cjs');
60
+ const { readJsonOrSync } = require('../util/atomicFs.cjs');
61
+ const doc = readJsonOrSync(epicMirrorPath(cwd, epicId), null);
62
+ return doc && doc.session && typeof doc.session === 'object' ? doc.session : doc;
63
+ });
64
+
65
+ /** artifacts:list — listArtifacts entries joined with each owning Epic's title. */
66
+ /** @param {string} cwd */
67
+ function listWithTitles(cwd) {
68
+ const { sessions } = readActiveIndex(cwd);
69
+ /** @type {Map<string, string|null>} */
70
+ const titles = new Map();
71
+ const titleFor = (/** @type {unknown} */ ownerId) => {
72
+ if (typeof ownerId !== 'string' || ownerId.startsWith('_tasks/')) return null;
73
+ if (titles.has(ownerId)) return titles.get(ownerId) ?? null;
74
+ let t = Object.prototype.hasOwnProperty.call(sessions, ownerId) ? titleOf(sessions[ownerId]) : null;
75
+ if (t === null) { try { t = titleOf(readMirror(cwd, ownerId)); } catch { t = null; } }
76
+ titles.set(ownerId, t);
77
+ return t;
78
+ };
79
+ const artifacts = listArtifacts(cwd).map((e) => ({ ...e, epicTitle: titleFor(e.ownerId) }));
80
+ return { ok: true, artifacts };
81
+ }
82
+
83
+ /**
84
+ * artifacts:worktrees — active Epics of `cwd` whose recorded worktree is on disk and
85
+ * registered with git, with commits on the Epic branch not yet on the base.
86
+ */
87
+ /** @param {string} cwd */
88
+ async function listWorktrees(cwd) {
89
+ const { sessions } = readActiveIndex(cwd);
90
+ let registered;
91
+ try {
92
+ const { parseWorktreePorcelain } = require('../git/gitExec.cjs');
93
+ const out = await execGit(cwd, ['worktree', 'list', '--porcelain'], { timeout: GIT_TIMEOUT_MS });
94
+ registered = new Map(parseWorktreePorcelain(out).map((w) => [realOrResolved(w.worktree), w.branch]));
95
+ } catch {
96
+ return { ok: true, worktrees: [] }; // not a git repo (or git unavailable): nothing unmerged to show
97
+ }
98
+ const rows = [];
99
+ for (const [epicId, rec] of Object.entries(sessions)) {
100
+ if (!rec || rec.status !== 'active') continue;
101
+ const wt = rec.worktree;
102
+ if (!wt || typeof wt.dir !== 'string' || !wt.dir || (wt.status && wt.status !== 'active')) continue;
103
+ if (!isDir(wt.dir)) continue;
104
+ const real = realOrResolved(wt.dir);
105
+ if (!registered.has(real)) continue;
106
+ const branch = registered.get(real) || (typeof wt.branch === 'string' ? wt.branch : null);
107
+ if (!branch) continue;
108
+ rows.push({ epicId, title: titleOf(rec), path: wt.dir, branch, base: typeof wt.baseBranch === 'string' && wt.baseBranch ? wt.baseBranch : 'HEAD' });
109
+ }
110
+ const worktrees = await Promise.all(rows.map(async ({ base, ...row }) => {
111
+ const ahead = (async () => {
112
+ try {
113
+ const out = await execGit(cwd, ['rev-list', '--count', `${base}..${row.branch}`, '--'], { timeout: GIT_TIMEOUT_MS });
114
+ const n = Number.parseInt(out.trim(), 10);
115
+ return Number.isFinite(n) ? n : null;
116
+ } catch { return null; }
117
+ })();
118
+ // Uncommitted = `git status --porcelain` lines (modified + staged + untracked) in the worktree itself.
119
+ const dirty = (async () => {
120
+ try {
121
+ const out = await execGit(row.path, ['status', '--porcelain'], { timeout: GIT_TIMEOUT_MS });
122
+ const n = String(out).split('\n').filter((l) => l.trim() !== '').length;
123
+ return Math.min(n, UNCOMMITTED_CAP);
124
+ } catch { return null; }
125
+ })();
126
+ const [aheadOfBase, uncommitted] = await Promise.all([ahead, dirty]);
127
+ return { ...row, aheadOfBase, uncommitted };
128
+ }));
129
+ return { ok: true, worktrees };
130
+ }
131
+
132
+ return { listWithTitles, listWorktrees };
133
+ }
134
+
135
+ /**
136
+ * @param {{ ipcMain?: any, validatePath?: (p: string) => string } & Parameters<typeof makeArtifactReaders>[0]} [deps]
137
+ */
138
+ function registerArtifactHandlers(deps = {}) {
139
+ const ipcMain = deps.ipcMain || require('electron').ipcMain;
140
+ const validatePath = deps.validatePath || require('../../config.cjs').validatePath;
141
+ const { schemas: s, validated: v } = require('../../ipcSchemas.cjs');
142
+ const readers = makeArtifactReaders(deps);
143
+ ipcMain.handle('artifacts:list', v(s.artifactsList, async ({ cwd }) => {
144
+ validatePath(cwd);
145
+ return readers.listWithTitles(cwd);
146
+ }));
147
+ ipcMain.handle('artifacts:worktrees', v(s.artifactsWorktrees, async ({ cwd }) => {
148
+ validatePath(cwd);
149
+ return readers.listWorktrees(cwd);
150
+ }));
151
+ }
152
+
153
+ module.exports = { registerArtifactHandlers, makeArtifactReaders, GIT_TIMEOUT_MS };
@@ -0,0 +1,72 @@
1
+ // @ts-check
2
+ /**
3
+ * artifactNotice.cjs — when files land in an Epic's Artifacts store, append ONE
4
+ * PromptSession 'response' event (notice 'artifact-ready') listing what landed, so the
5
+ * owner sees it in the Epic chat. One notice per publish call / ingest batch, never one
6
+ * per file. Writes only through promptSessionEvents.appendResponseEventWithReason (the
7
+ * same append path, and writer id, as the scheduler's 'build-done' notice).
8
+ *
9
+ * postArtifactReadyNotice({ cwd, epicId, entries, append? }) → Promise<{ ok, reason? }>
10
+ * cwd — the project root (artifact paths are made relative to it)
11
+ * entries — artifactStore results: `{ storedPath, entry }` (publishArtifact / ingestDir
12
+ * `published[]`), or flat `{ title, kind, size, path|storedPath }` rows
13
+ * Logs failures, never throws; empty entries or a missing epicId post nothing.
14
+ */
15
+ 'use strict';
16
+
17
+ const path = require('node:path');
18
+
19
+ const MAX_ROWS = 20;
20
+
21
+ /**
22
+ * @param {string} cwd
23
+ * @param {any} item
24
+ * @returns {{ title: string, kind: string, path: string, size: number } | null}
25
+ */
26
+ function toRow(cwd, item) {
27
+ if (!item || typeof item !== 'object') return null;
28
+ const e = item.entry && typeof item.entry === 'object' ? item.entry : item;
29
+ const abs = typeof item.storedPath === 'string' ? item.storedPath : (typeof e.path === 'string' ? e.path : null);
30
+ let rel = '';
31
+ if (abs) {
32
+ rel = path.isAbsolute(abs) && cwd ? path.relative(cwd, abs) : abs;
33
+ rel = rel.split(path.sep).join('/');
34
+ }
35
+ const title = typeof e.title === 'string' && e.title ? e.title : (typeof e.name === 'string' ? e.name : path.basename(rel || 'artifact'));
36
+ return {
37
+ title,
38
+ kind: typeof e.kind === 'string' ? e.kind : 'other',
39
+ path: rel,
40
+ size: typeof e.size === 'number' && Number.isFinite(e.size) ? e.size : 0,
41
+ };
42
+ }
43
+
44
+ /**
45
+ * @param {{ cwd?: string, epicId?: string | null, entries?: any[], append?: Function }} [args]
46
+ * @returns {Promise<{ ok: boolean, reason?: string }>}
47
+ */
48
+ async function postArtifactReadyNotice({ cwd, epicId, entries, append } = {}) {
49
+ try {
50
+ if (!cwd || typeof epicId !== 'string' || !epicId) return { ok: false, reason: 'missing-args' };
51
+ const rows = (Array.isArray(entries) ? entries : [])
52
+ .map((it) => toRow(cwd, it))
53
+ .filter((r) => r !== null);
54
+ if (rows.length === 0) return { ok: false, reason: 'empty' };
55
+ const text = rows.length === 1 ? `Artifact ready: ${rows[0].title}` : `${rows.length} artifacts ready`;
56
+ /** @type {{ notice: string, artifacts: object[], moreCount?: number }} */
57
+ const meta = { notice: 'artifact-ready', artifacts: rows.slice(0, MAX_ROWS) };
58
+ if (rows.length > MAX_ROWS) meta.moreCount = rows.length - MAX_ROWS;
59
+ const fn = append || require('../../promptSessionEvents.cjs').appendResponseEventWithReason;
60
+ const res = await fn(cwd, epicId, text, meta);
61
+ if (res && res.ok === false) {
62
+ console.warn(`[artifactNotice] artifact-ready notice not posted for ${epicId}: ${res.reason || 'refused'}`);
63
+ return { ok: false, reason: res.reason || 'refused' };
64
+ }
65
+ return { ok: true };
66
+ } catch (e) {
67
+ console.error('[artifactNotice] artifact-ready notice failed', epicId, e instanceof Error ? e.message : e);
68
+ return { ok: false, reason: 'error' };
69
+ }
70
+ }
71
+
72
+ module.exports = { postArtifactReadyNotice, MAX_ROWS };