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,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 };
@@ -0,0 +1,356 @@
1
+ /**
2
+ * artifactRetention — retention sweep for `session-manager-operations/artifacts/`
3
+ * (layout + ledger shape: artifactStore.cjs). Mirrors scheduler/planRecordRetention.cjs.
4
+ *
5
+ * pruneArtifacts({ projectRoot, epicStatus, now, days, tasksDays, dryRun, fsImpl, sizeCapBytes })
6
+ * → { removed: string[] (owner ids whose folder was deleted), trimmed: string[] (owner
7
+ * ids that lost some files but keep pinned/fresh ones), removedFiles, kept,
8
+ * totalBytes (store size left after the sweep), overCap,
9
+ * missingRows: string[] ('<owner-id>/<name>' ledger rows dropped because their file
10
+ * is gone), compacted: string[] (owner ids whose ledger was rewritten only to drop
11
+ * such rows), uncheckedRows: number (ledger rows kept because their file's state is
12
+ * unknown — an lstat error other than ENOENT/ENOTDIR; logged once per sweep) }. Never throws.
13
+ *
14
+ * Missing-file compaction runs for EVERY owner, whatever its lifecycle: a ledger row whose
15
+ * stored file artifacts/<owner>/<name> no longer exists (deleted from the OS file manager)
16
+ * is dropped — pinned rows included, since nothing is left to keep. Only a definite 'gone'
17
+ * (artifactStore.storedFileState: ENOENT/ENOTDIR, or not a regular file) counts as missing;
18
+ * an 'unknown' state (EACCES, EIO, …) keeps the row. The rewrite is asserted as writer 'artifacts'; dryRun reports
19
+ * the rows without writing.
20
+ *
21
+ * Epic folders artifacts/<epic-id>/ are eligible when:
22
+ * - epicStatus(id) → { status: 'completed' | 'archived', completedAt | archivedAt }
23
+ * older than `days` (default opsRetentionSettings artifactsDays, 30), or
24
+ * - epicStatus(id) → null (orphan) and its newest file mtime is older than `days`.
25
+ * proposed/active Epics, a done Epic with no parseable time, and a throwing epicStatus
26
+ * keep the folder. An eligible folder with no pinned ledger entry is deleted whole; one
27
+ * with pinned entries keeps those files and its ledger is rewritten to just them.
28
+ * Task folders artifacts/_tasks/<task-id>/ have no lifecycle, so each unpinned ledger
29
+ * entry whose createdAt (else file mtime) is older than `tasksDays` (default
30
+ * opsRetentionSettings tasksDays) is deleted, and the ledger rewritten; a folder left
31
+ * with nothing is deleted. Untracked files go by mtime.
32
+ * Symlinks, non-directories and unsafe names are never touched. dryRun computes the exact
33
+ * same result and touches nothing. Every delete/rewrite is asserted as writer 'artifacts'
34
+ * (the namespace owner, opsOwnership.cjs). When the store left after the sweep exceeds
35
+ * sizeCapBytes (default SIZE_CAP_BYTES, 5 GiB) ONE warning is logged per call.
36
+ *
37
+ * pruneArtifactStaging({ base, now, days, dryRun, fsImpl })
38
+ * → { removed: string[] (child folder names), removedFiles: string[] ('<child>/<rel>'), kept }.
39
+ * Sweeps the direct child folders of the staging base (default
40
+ * <worktreeBase>/artifact-staging, artifactStore.stagingDirFor). A child is removed when
41
+ * it is empty and its mtime is older than 24 h, or (whatever it holds, recursively) when
42
+ * its newest mtime is older than `days` (default artifactsDays). Each deleted file name
43
+ * is logged. Symlinked children, non-directories and unsafe names are skipped; nothing
44
+ * outside the base is touched. The base is outside every ops root, so no assertOpsWrite.
45
+ * Removing a folder an open terminal/chat still uses is safe: stagingDirFor re-creates it.
46
+ * Never throws.
47
+ */
48
+ 'use strict';
49
+
50
+ const nodeFs = require('node:fs');
51
+ const path = require('node:path');
52
+ const opsOwnership = require('../opsOwnership.cjs');
53
+ const atomicFs = require('../util/atomicFs.cjs');
54
+ const { storedFileState } = require('./artifactStore.cjs');
55
+
56
+ const WRITER = 'artifacts';
57
+ const NS = 'artifacts';
58
+ const TASKS_DIR = '_tasks';
59
+ const LEDGER = 'index.json';
60
+ const DAY_MS = 86400000;
61
+ const SIZE_CAP_BYTES = 5 * 1024 * 1024 * 1024;
62
+ const SAFE_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
63
+ const DONE = new Set(['completed', 'archived']);
64
+
65
+ function toMs(v) {
66
+ if (typeof v === 'number' && Number.isFinite(v)) return v;
67
+ if (typeof v === 'string' && v) {
68
+ const ms = Date.parse(v);
69
+ if (Number.isFinite(ms)) return ms;
70
+ }
71
+ return null;
72
+ }
73
+
74
+ const isSafeId = (n) => typeof n === 'string' && SAFE_ID_RE.test(n) && n !== '.' && n !== '..';
75
+
76
+ function resolveDays(v, key, fallback) {
77
+ if (typeof v === 'number' && Number.isFinite(v) && v > 0) return v;
78
+ try {
79
+ const d = require('../opsRetentionSettings.cjs').read()[key];
80
+ return typeof d === 'number' && d > 0 ? d : fallback;
81
+ } catch {
82
+ return fallback;
83
+ }
84
+ }
85
+
86
+ /** Sum of file sizes + newest file mtime under dir (symlinks not followed). */
87
+ function scan(fsImpl, dir) {
88
+ let bytes = 0;
89
+ let newest = null;
90
+ const walk = (d) => {
91
+ let entries;
92
+ try { entries = fsImpl.readdirSync(d, { withFileTypes: true }); } catch { return; }
93
+ for (const e of entries) {
94
+ const p = path.join(d, e.name);
95
+ if (e.isDirectory()) { walk(p); continue; }
96
+ try {
97
+ const st = fsImpl.lstatSync(p);
98
+ bytes += st.isFile() ? st.size : 0;
99
+ if (newest === null || st.mtimeMs > newest) newest = st.mtimeMs;
100
+ } catch { /* vanished */ }
101
+ }
102
+ };
103
+ walk(dir);
104
+ if (newest === null) {
105
+ try { newest = fsImpl.lstatSync(dir).mtimeMs; } catch { /* vanished */ }
106
+ }
107
+ return { bytes, newest };
108
+ }
109
+
110
+ /** { entries, raw } — entries [] on missing/corrupt; raw keeps the ledger's other keys. */
111
+ function readLedger(fsImpl, file) {
112
+ try {
113
+ const parsed = JSON.parse(fsImpl.readFileSync(file, 'utf8'));
114
+ const list = Array.isArray(parsed) ? parsed : parsed && Array.isArray(parsed.entries) ? parsed.entries : [];
115
+ const raw = parsed && !Array.isArray(parsed) && typeof parsed === 'object' ? parsed : { version: 1 };
116
+ return { entries: list.filter((e) => e && typeof e === 'object' && typeof e.name === 'string'), raw };
117
+ } catch {
118
+ return { entries: [], raw: { version: 1 } };
119
+ }
120
+ }
121
+
122
+ /** Direct child files of dir (no dirs, no symlinks), excluding the ledger. */
123
+ function childFiles(fsImpl, dir) {
124
+ let entries;
125
+ try { entries = fsImpl.readdirSync(dir, { withFileTypes: true }); } catch { return []; }
126
+ return entries.filter((e) => e.name !== LEDGER && !e.isSymbolicLink()).map((e) => e.name);
127
+ }
128
+
129
+ /**
130
+ * Ledger entries not definitely gone (storedFileState !== 'gone'); records the dropped rows on
131
+ * ctx.result.missingRows and counts kept 'unknown' rows on ctx.result.uncheckedRows.
132
+ */
133
+ function presentEntries(ctx, ownerId, dir, entries) {
134
+ const live = [];
135
+ for (const e of entries) {
136
+ const state = storedFileState(path.join(dir, e.name), ctx.fsImpl);
137
+ if (state === 'gone') { ctx.result.missingRows.push(`${ownerId}/${e.name}`); continue; }
138
+ if (state === 'unknown') ctx.result.uncheckedRows += 1;
139
+ live.push(e);
140
+ }
141
+ return live;
142
+ }
143
+
144
+ /** Rewrite a kept owner's ledger without its missing-file rows → 'compacted' | null. */
145
+ function compactOwner(ctx, dir, entries, live, raw) {
146
+ if (live.length === entries.length) return null;
147
+ const ledgerFile = path.join(dir, LEDGER);
148
+ opsOwnership.assertOpsWrite(ledgerFile, WRITER);
149
+ if (!ctx.dryRun) atomicFs.writeJsonAtomicSync(ledgerFile, { ...raw, entries: live });
150
+ return 'compacted';
151
+ }
152
+
153
+ function isEpicEligible(id, dir, epicStatus, cutoffMs, fsImpl) {
154
+ let st;
155
+ try { st = epicStatus(id); } catch { return false; }
156
+ if (st === null || st === undefined) {
157
+ const { newest } = scan(fsImpl, dir);
158
+ return newest !== null && newest < cutoffMs;
159
+ }
160
+ if (!st || typeof st !== 'object' || !DONE.has(st.status)) return false;
161
+ const done = toMs(st.completedAt) ?? toMs(st.archivedAt);
162
+ return done !== null && done < cutoffMs;
163
+ }
164
+
165
+ /**
166
+ * Remove `names` from owner folder `dir`, keeping `keepEntries` in its ledger. Deletes the
167
+ * whole folder when nothing would remain. Returns 'removed' | 'trimmed' | 'compacted'
168
+ * (only missing-file rows left the ledger) | null.
169
+ */
170
+ function applyOwner({ dir, names, keepEntries, entries, raw, dryRun, fsImpl, result }) {
171
+ const remaining = childFiles(fsImpl, dir).filter((n) => !names.includes(n));
172
+ if (remaining.length === 0 && keepEntries.length === 0) {
173
+ opsOwnership.assertOpsWrite(dir, WRITER);
174
+ result.removedFiles += childFiles(fsImpl, dir).length;
175
+ if (!dryRun) fsImpl.rmSync(dir, { recursive: true, force: true });
176
+ return 'removed';
177
+ }
178
+ if (names.length === 0 && keepEntries.length === entries.length) return null;
179
+ for (const n of names) {
180
+ const p = path.join(dir, n);
181
+ opsOwnership.assertOpsWrite(p, WRITER);
182
+ if (!dryRun) fsImpl.rmSync(p, { recursive: true, force: true });
183
+ result.removedFiles += 1;
184
+ }
185
+ const ledgerFile = path.join(dir, LEDGER);
186
+ opsOwnership.assertOpsWrite(ledgerFile, WRITER);
187
+ if (!dryRun) atomicFs.writeJsonAtomicSync(ledgerFile, { ...raw, entries: keepEntries });
188
+ return names.length === 0 ? 'compacted' : 'trimmed';
189
+ }
190
+
191
+ function pruneEpicOwner(ctx, id, dir) {
192
+ const { entries, raw } = readLedger(ctx.fsImpl, path.join(dir, LEDGER));
193
+ const live = presentEntries(ctx, id, dir, entries);
194
+ if (!isEpicEligible(id, dir, ctx.epicStatus, ctx.cutoffMs, ctx.fsImpl)) return compactOwner(ctx, dir, entries, live, raw);
195
+ const keepEntries = live.filter((e) => e.pinned === true);
196
+ const keepNames = new Set(keepEntries.map((e) => e.name));
197
+ const names = childFiles(ctx.fsImpl, dir).filter((n) => !keepNames.has(n));
198
+ return applyOwner({ dir, names, keepEntries, entries, raw, dryRun: ctx.dryRun, fsImpl: ctx.fsImpl, result: ctx.result });
199
+ }
200
+
201
+ function pruneTaskOwner(ctx, ownerId, dir) {
202
+ const { fsImpl, tasksCutoffMs } = ctx;
203
+ const { entries, raw } = readLedger(fsImpl, path.join(dir, LEDGER));
204
+ const live = presentEntries(ctx, ownerId, dir, entries);
205
+ const mtime = (n) => { try { return fsImpl.lstatSync(path.join(dir, n)).mtimeMs; } catch { return null; } };
206
+ const old = (ms) => ms !== null && ms < tasksCutoffMs;
207
+ const keepEntries = live.filter((e) => e.pinned === true || !old(toMs(e.createdAt) ?? mtime(e.name)));
208
+ const tracked = new Set(entries.map((e) => e.name));
209
+ const keepNames = new Set(keepEntries.map((e) => e.name));
210
+ const names = childFiles(fsImpl, dir).filter((n) => (tracked.has(n) ? !keepNames.has(n) : old(mtime(n))));
211
+ return applyOwner({ dir, names, keepEntries, entries, raw, dryRun: ctx.dryRun, fsImpl, result: ctx.result });
212
+ }
213
+
214
+ function safeDirs(fsImpl, dir) {
215
+ try {
216
+ return fsImpl.readdirSync(dir, { withFileTypes: true })
217
+ .filter((e) => e.isDirectory() && !e.isSymbolicLink() && isSafeId(e.name))
218
+ .map((e) => e.name);
219
+ } catch {
220
+ return [];
221
+ }
222
+ }
223
+
224
+ function pruneArtifacts(opts) {
225
+ const result = {
226
+ removed: [], trimmed: [], removedFiles: 0, kept: 0, totalBytes: 0, overCap: false, missingRows: [], compacted: [], uncheckedRows: 0,
227
+ };
228
+ try {
229
+ const o = opts || {};
230
+ const fsImpl = o.fsImpl || nodeFs;
231
+ const now = typeof o.now === 'number' && Number.isFinite(o.now) ? o.now : Date.now();
232
+ const cap = typeof o.sizeCapBytes === 'number' && o.sizeCapBytes >= 0 ? o.sizeCapBytes : SIZE_CAP_BYTES;
233
+ const root = opsOwnership.opsPath(o.projectRoot, NS);
234
+ if (!fsImpl.existsSync(root)) return result;
235
+ const ctx = {
236
+ fsImpl,
237
+ dryRun: !!o.dryRun,
238
+ result,
239
+ epicStatus: typeof o.epicStatus === 'function' ? o.epicStatus : () => { throw new Error('no epicStatus'); },
240
+ cutoffMs: now - resolveDays(o.days, 'artifactsDays', 30) * DAY_MS,
241
+ tasksCutoffMs: now - resolveDays(o.tasksDays, 'tasksDays', 30) * DAY_MS,
242
+ };
243
+ const before = scan(fsImpl, root).bytes;
244
+ let freed = 0;
245
+ const visit = (ownerId, dir, fn) => {
246
+ try {
247
+ const size = scan(fsImpl, dir).bytes;
248
+ const out = fn();
249
+ if (out === 'removed') { result.removed.push(ownerId); freed += size; return; }
250
+ if (out === 'compacted') result.compacted.push(ownerId);
251
+ if (out === 'trimmed') {
252
+ result.trimmed.push(ownerId);
253
+ if (!ctx.dryRun) freed += size - scan(fsImpl, dir).bytes;
254
+ }
255
+ result.kept += 1;
256
+ } catch (err) {
257
+ console.warn(`[artifactRetention] keep ${ownerId}:`, err && err.message);
258
+ result.kept += 1;
259
+ }
260
+ };
261
+ for (const id of safeDirs(fsImpl, root)) {
262
+ if (id === TASKS_DIR) continue;
263
+ const dir = opsOwnership.opsPath(o.projectRoot, NS, id);
264
+ visit(id, dir, () => pruneEpicOwner(ctx, id, dir));
265
+ }
266
+ for (const t of safeDirs(fsImpl, path.join(root, TASKS_DIR))) {
267
+ const dir = opsOwnership.opsPath(o.projectRoot, NS, TASKS_DIR, t);
268
+ const ownerId = `${TASKS_DIR}/${t}`;
269
+ visit(ownerId, dir, () => pruneTaskOwner(ctx, ownerId, dir));
270
+ }
271
+ if (result.uncheckedRows > 0) {
272
+ console.warn(`[artifactRetention] kept ${result.uncheckedRows} unchecked ledger row(s): file state unknown (lstat error other than ENOENT/ENOTDIR) (${root})`);
273
+ }
274
+ result.totalBytes = ctx.dryRun ? Math.max(0, before - freed) : scan(fsImpl, root).bytes;
275
+ if (result.totalBytes > cap) {
276
+ result.overCap = true;
277
+ console.warn(`[artifactRetention] artifacts store over size cap: ${result.totalBytes} bytes > ${cap} (${root})`);
278
+ }
279
+ } catch (err) {
280
+ console.warn('[artifactRetention] sweep skipped:', err && err.message);
281
+ }
282
+ return result;
283
+ }
284
+
285
+ const STAGING_EMPTY_MS = DAY_MS;
286
+
287
+ function defaultStagingBase() {
288
+ const { worktreeBase } = require('../scheduler/schedulerPaths.cjs');
289
+ return path.join(worktreeBase(), 'artifact-staging');
290
+ }
291
+
292
+ /** { files: relative non-dir names, newest: newest mtime of dir + everything under it } — no symlink is followed. */
293
+ function walkStaging(fsImpl, dir) {
294
+ const files = [];
295
+ let newest = fsImpl.lstatSync(dir).mtimeMs;
296
+ const walk = (d, rel) => {
297
+ for (const e of fsImpl.readdirSync(d, { withFileTypes: true })) {
298
+ const p = path.join(d, e.name);
299
+ const r = rel ? `${rel}/${e.name}` : e.name;
300
+ try { const st = fsImpl.lstatSync(p); if (st.mtimeMs > newest) newest = st.mtimeMs; } catch { /* vanished */ }
301
+ if (e.isDirectory() && !e.isSymbolicLink()) walk(p, r);
302
+ else files.push(r);
303
+ }
304
+ };
305
+ walk(dir, '');
306
+ return { files, newest };
307
+ }
308
+
309
+ function pruneArtifactStaging(opts) {
310
+ const result = { removed: [], removedFiles: [], kept: 0 };
311
+ try {
312
+ const o = opts || {};
313
+ const fsImpl = o.fsImpl || nodeFs;
314
+ const now = typeof o.now === 'number' && Number.isFinite(o.now) ? o.now : Date.now();
315
+ const base = typeof o.base === 'string' ? o.base : defaultStagingBase();
316
+ if (!path.isAbsolute(base)) return result;
317
+ let baseSt;
318
+ try { baseSt = fsImpl.lstatSync(base); } catch { return result; }
319
+ if (!baseSt.isDirectory()) return result;
320
+ const oldCutoff = now - resolveDays(o.days, 'artifactsDays', 30) * DAY_MS;
321
+ const emptyCutoff = now - STAGING_EMPTY_MS;
322
+ for (const name of safeDirs(fsImpl, base)) {
323
+ const dir = path.join(base, name);
324
+ try {
325
+ if (path.dirname(dir) !== base) { result.kept += 1; continue; }
326
+ const st = fsImpl.lstatSync(dir);
327
+ if (!st.isDirectory() || st.isSymbolicLink()) { result.kept += 1; continue; }
328
+ const isEmpty = fsImpl.readdirSync(dir).length === 0;
329
+ if (isEmpty) {
330
+ if (st.mtimeMs < emptyCutoff) {
331
+ if (!o.dryRun) fsImpl.rmdirSync(dir);
332
+ result.removed.push(name);
333
+ } else result.kept += 1;
334
+ continue;
335
+ }
336
+ const { files, newest } = walkStaging(fsImpl, dir);
337
+ if (newest >= oldCutoff) { result.kept += 1; continue; }
338
+ const names = files.map((f) => `${name}/${f}`);
339
+ if (names.length) console.warn(`[artifactRetention] staging ${dryTag(o)}deleting ${names.length} file(s) from ${dir}: ${names.join(', ')}`);
340
+ if (!o.dryRun) fsImpl.rmSync(dir, { recursive: true, force: true });
341
+ result.removed.push(name);
342
+ result.removedFiles.push(...names);
343
+ } catch (err) {
344
+ console.warn(`[artifactRetention] staging keep ${name}:`, err && err.message);
345
+ result.kept += 1;
346
+ }
347
+ }
348
+ } catch (err) {
349
+ console.warn('[artifactRetention] staging sweep skipped:', err && err.message);
350
+ }
351
+ return result;
352
+ }
353
+
354
+ const dryTag = (o) => (o.dryRun ? '(dry run) ' : '');
355
+
356
+ module.exports = { pruneArtifacts, pruneArtifactStaging, SIZE_CAP_BYTES };