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