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,178 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * leftoverRenice.cjs — lower leftover chat/aux tool processes to idle priority.
5
+ *
6
+ * 2026-11-23: a Chatterbox voice render started by a one-shot Burrow chat turn
7
+ * kept running after the turn ended (its `claude` process gone, parent bash
8
+ * reparented to pid 1) and used 8 cores for 40+ minutes at the app's nice 12,
9
+ * so the CPU load gate held every scheduler job. Evidence: pid 2893850
10
+ * `/tmp/cbtest/bin/python /tmp/cb-script/takes.py`, SM_PROC_ROLE=chat,
11
+ * CLAUDE_PID=2858266 (gone).
12
+ *
13
+ * A leftover = a process of THIS user whose environment carries
14
+ * SM_PROC_ROLE=chat|aux AND a CLAUDE_PID whose process no longer exists. Such a
15
+ * process is set to nice 19 (never killed — its output may be wanted); the CPU
16
+ * sampler (cpuSample.cjs, PRD 4021) then stops counting it as load.
17
+ *
18
+ * - A process with no CLAUDE_PID (e.g. the chat's own `claude`) is never a
19
+ * leftover: there is no turn to judge it by.
20
+ * - Raising one's own process niceness needs no privileges; lowering it would.
21
+ * - A process whose CLAUDE_PID equals the one the app itself inherited at
22
+ * startup (app launched from inside a claude session) is never a leftover:
23
+ * every chat process carries that value, so it says nothing about the turn.
24
+ * - Only /proc/<pid>/status (Uid) and /proc/<pid>/environ are read; from
25
+ * environ only SM_PROC_ROLE and CLAUDE_PID are kept.
26
+ * - A scan reads at most MAX_SCAN pids, skips unreadable entries, never throws,
27
+ * and never sends a signal.
28
+ */
29
+
30
+ const fs = require('node:fs');
31
+ const os = require('node:os');
32
+ const path = require('node:path');
33
+ const { pidAlive } = require('./pidAlive.cjs');
34
+
35
+ const MAX_SCAN = 4000;
36
+ const IDLE_NICE = 19;
37
+ const LEFTOVER_ROLES = new Set(['chat', 'aux']);
38
+
39
+ /** CLAUDE_PID the app main process inherited, read once at module load. */
40
+ const APP_CLAUDE_PID = parseEnviron(`CLAUDE_PID=${process.env.CLAUDE_PID ?? ''}`).claudePid;
41
+
42
+ /**
43
+ * Pick SM_PROC_ROLE and CLAUDE_PID out of NUL-separated environ text.
44
+ * @param {string} text
45
+ * @returns {{ role: string | null, claudePid: number | null }}
46
+ */
47
+ function parseEnviron(text) {
48
+ let role = null;
49
+ let claudePid = null;
50
+ if (typeof text !== 'string') return { role, claudePid };
51
+ for (const entry of text.split('\0')) {
52
+ if (entry.startsWith('SM_PROC_ROLE=')) role = entry.slice('SM_PROC_ROLE='.length);
53
+ else if (entry.startsWith('CLAUDE_PID=')) {
54
+ const raw = entry.slice('CLAUDE_PID='.length);
55
+ const n = /^\d+$/.test(raw) ? Number(raw) : NaN;
56
+ claudePid = Number.isInteger(n) ? n : null;
57
+ }
58
+ }
59
+ return { role, claudePid };
60
+ }
61
+
62
+ /**
63
+ * Real uid from /proc/<pid>/status text, or null.
64
+ * @param {string} text
65
+ */
66
+ function parseStatusUid(text) {
67
+ if (typeof text !== 'string') return null;
68
+ const m = /^Uid:\s+(\d+)/m.exec(text);
69
+ return m ? Number(m[1]) : null;
70
+ }
71
+
72
+ function currentUid() {
73
+ return typeof process.getuid === 'function' ? process.getuid() : null;
74
+ }
75
+
76
+ /**
77
+ * Leftover processes (see header). Never throws; [] off Linux-like hosts.
78
+ * @param {{ procRoot?: string, uid?: number | null, maxPids?: number,
79
+ * readdir?: (p: string) => string[], readFile?: (p: string) => string,
80
+ * isAlive?: (pid: number) => boolean, selfPid?: number,
81
+ * appClaudePid?: number | null }} [opts]
82
+ * @returns {{ pid: number, role: string, claudePid: number }[]}
83
+ */
84
+ function findLeftovers({
85
+ procRoot = '/proc',
86
+ uid = currentUid(),
87
+ maxPids = MAX_SCAN,
88
+ readdir = (p) => fs.readdirSync(p),
89
+ readFile = (p) => fs.readFileSync(p, 'latin1'),
90
+ isAlive,
91
+ selfPid = process.pid,
92
+ appClaudePid = APP_CLAUDE_PID,
93
+ } = {}) {
94
+ if (uid === null || uid === undefined) return [];
95
+ // Under an injected tree a pid is alive when its directory exists there.
96
+ const alive = isAlive || (procRoot === '/proc'
97
+ ? pidAlive
98
+ : (/** @type {number} */ pid) => {
99
+ try { return fs.existsSync(path.join(procRoot, String(pid))); } catch { return false; }
100
+ });
101
+ /** @type {{ pid: number, role: string, claudePid: number }[]} */
102
+ const out = [];
103
+ let names;
104
+ try { names = readdir(procRoot); } catch { return out; }
105
+ if (!Array.isArray(names)) return out;
106
+ let scanned = 0;
107
+ for (const name of names) {
108
+ if (!/^\d+$/.test(name)) continue;
109
+ if (scanned >= maxPids) break;
110
+ scanned += 1;
111
+ const pid = Number(name);
112
+ if (pid === selfPid || pid <= 1) continue;
113
+ try {
114
+ if (parseStatusUid(readFile(path.join(procRoot, name, 'status'))) !== uid) continue;
115
+ const { role, claudePid } = parseEnviron(readFile(path.join(procRoot, name, 'environ')));
116
+ if (!role || !LEFTOVER_ROLES.has(role)) continue;
117
+ if (claudePid === null || claudePid <= 1) continue;
118
+ if (appClaudePid !== null && appClaudePid !== undefined && claudePid === appClaudePid) continue;
119
+ if (alive(claudePid)) continue;
120
+ out.push({ pid, role, claudePid });
121
+ } catch {
122
+ // Unreadable or vanished entry: skip it.
123
+ }
124
+ }
125
+ return out;
126
+ }
127
+
128
+ /** Pids already logged, so each leftover is reported once. */
129
+ const logged = new Set();
130
+
131
+ /**
132
+ * Set every leftover to nice 19 and log each pid once. Never throws, never
133
+ * sends a signal. Returns the pids reniced this call.
134
+ * @param {Parameters<typeof findLeftovers>[0] & {
135
+ * setPriority?: (pid: number, prio: number) => void,
136
+ * getPriority?: (pid: number) => number,
137
+ * log?: (msg: string) => void, seen?: Set<number> }} [opts]
138
+ * @returns {number[]}
139
+ */
140
+ function reniceLeftovers(opts = {}) {
141
+ const {
142
+ setPriority = (pid, prio) => os.setPriority(pid, prio),
143
+ getPriority = (pid) => os.getPriority(pid),
144
+ log = (msg) => console.log(msg),
145
+ seen = logged,
146
+ ...findOpts
147
+ } = opts;
148
+ /** @type {number[]} */
149
+ const done = [];
150
+ try {
151
+ const leftovers = findLeftovers(findOpts);
152
+ const current = new Set();
153
+ for (const l of leftovers) {
154
+ current.add(l.pid);
155
+ try {
156
+ let prio = null;
157
+ try { prio = getPriority(l.pid); } catch { prio = null; }
158
+ if (prio !== IDLE_NICE) {
159
+ setPriority(l.pid, IDLE_NICE);
160
+ done.push(l.pid);
161
+ }
162
+ if (!seen.has(l.pid)) {
163
+ seen.add(l.pid);
164
+ log(`[leftoverRenice] pid ${l.pid} (SM_PROC_ROLE=${l.role}, CLAUDE_PID ${l.claudePid} gone) set to nice ${IDLE_NICE}`);
165
+ }
166
+ } catch {
167
+ // Vanished, or not ours after all: leave it.
168
+ }
169
+ }
170
+ // Forget pids that are no longer leftovers so a reused pid logs again.
171
+ for (const pid of seen) if (!current.has(pid)) seen.delete(pid);
172
+ } catch {
173
+ // Never throws.
174
+ }
175
+ return done;
176
+ }
177
+
178
+ module.exports = { findLeftovers, APP_CLAUDE_PID, reniceLeftovers, parseEnviron, parseStatusUid, MAX_SCAN, IDLE_NICE };
@@ -19,6 +19,13 @@ const DEFAULT_MAX_FRACTION = 0.45;
19
19
  const HIGH_FRACTION = 0.85;
20
20
  const DEFAULT_SWAP_MAX_MB = 4096;
21
21
 
22
+ // Fixed caps for every scheduler job's scope. MemoryHigh throttles (reclaim
23
+ // pressure) above 6 GB; MemoryMax OOM-kills inside the scope at 10 GB. The
24
+ // largest recorded job peak is 9,142 MB, so 10 GB kills only true runaways —
25
+ // what makes the lower per-job reservations in the memory gate safe.
26
+ const JOB_MEMORY_HIGH_MB = 6144;
27
+ const JOB_MEMORY_MAX_MB = 10240;
28
+
22
29
  /**
23
30
  * @param {{ totalRamMb?: number, env?: Record<string, string | undefined> }} [opts]
24
31
  * @returns {{ memoryMaxMb: number, memoryHighMb: number, swapMaxMb: number } | null} null = disabled
@@ -42,6 +49,24 @@ function memoryLimitsFor(opts = {}) {
42
49
  };
43
50
  }
44
51
 
52
+ /**
53
+ * Limits for a scheduler job's scope: JOB_MEMORY_HIGH_MB / JOB_MEMORY_MAX_MB.
54
+ * SM_JOB_MEMORY_MAX_MB still overrides (0 disables), via memoryLimitsFor.
55
+ * @param {{ env?: Record<string, string | undefined> }} [opts]
56
+ * @returns {{ memoryMaxMb: number, memoryHighMb: number, swapMaxMb: number } | null}
57
+ */
58
+ function schedulerJobMemoryLimits(opts = {}) {
59
+ const env = opts.env || process.env;
60
+ const raw = env.SM_JOB_MEMORY_MAX_MB;
61
+ if (raw !== undefined && raw !== '') return memoryLimitsFor({ env });
62
+ return { memoryMaxMb: JOB_MEMORY_MAX_MB, memoryHighMb: JOB_MEMORY_HIGH_MB, swapMaxMb: DEFAULT_SWAP_MAX_MB };
63
+ }
64
+
65
+ /** systemd size: whole GiB as `<n>G`, otherwise `<n>M`. @param {number} mb */
66
+ function sizeArg(mb) {
67
+ return mb > 0 && mb % 1024 === 0 ? `${mb / 1024}G` : `${mb}M`;
68
+ }
69
+
45
70
  /** @type {boolean | null} */
46
71
  let cachedSupport = null;
47
72
 
@@ -100,9 +125,9 @@ function wrapInMemoryScope(o) {
100
125
  '--quiet',
101
126
  '--collect',
102
127
  `--unit=${sanitizeUnit(unit)}.scope`,
103
- '-p', `MemoryHigh=${limits.memoryHighMb}M`,
104
- '-p', `MemoryMax=${limits.memoryMaxMb}M`,
105
- '-p', `MemorySwapMax=${limits.swapMaxMb}M`,
128
+ '-p', `MemoryHigh=${sizeArg(limits.memoryHighMb)}`,
129
+ '-p', `MemoryMax=${sizeArg(limits.memoryMaxMb)}`,
130
+ '-p', `MemorySwapMax=${sizeArg(limits.swapMaxMb)}`,
106
131
  '-p', 'OOMPolicy=continue',
107
132
  '--',
108
133
  command,
@@ -131,7 +156,10 @@ function stopScope(unit, deps = {}) {
131
156
  }
132
157
 
133
158
  module.exports = {
159
+ JOB_MEMORY_HIGH_MB,
160
+ JOB_MEMORY_MAX_MB,
134
161
  memoryLimitsFor,
162
+ schedulerJobMemoryLimits,
135
163
  scopeSupported,
136
164
  wrapInMemoryScope,
137
165
  stopScope,
@@ -17,6 +17,7 @@ const crypto = require('node:crypto');
17
17
  const config = require('../../config.cjs');
18
18
  const { opsPath, assertOpsWrite } = require('../opsOwnership.cjs');
19
19
  const { injectPlayerBridge } = require('./playerBridge.cjs');
20
+ const { readCharacter } = require('../demo-video-kit/character.cjs');
20
21
 
21
22
  const WRITER = 'project-home';
22
23
  const MAX_ENTRIES = 500;
@@ -57,10 +58,62 @@ async function readEntry(kind, dir, id) {
57
58
  } catch (e) {
58
59
  error = oneLine(e && e.code === 'ENOENT' ? 'meta.json missing' : `meta.json unreadable: ${e && e.message}`);
59
60
  }
60
- return { id, path: file, mtimeMs: st.mtimeMs, meta, error };
61
+ const entry = { id, path: file, mtimeMs: st.mtimeMs, meta, error };
62
+ if (kind === 'videos') entry.exports = await readExports(dir);
63
+ return entry;
61
64
  }
62
65
 
63
- async function listKind(realCwd, kind) {
66
+ /** Absolute path of `file` when it exists as a regular file, else null. */
67
+ async function fileOrNull(file) {
68
+ try {
69
+ return (await fsp.stat(file)).isFile() ? file : null;
70
+ } catch {
71
+ return null;
72
+ }
73
+ }
74
+
75
+ /** Fixed names the save route writes: video.mp4 + poster.png. */
76
+ async function readExports(dir) {
77
+ const [mp4, poster] = await Promise.all([
78
+ fileOrNull(path.join(dir, 'video.mp4')),
79
+ fileOrNull(path.join(dir, 'poster.png')),
80
+ ]);
81
+ return { mp4, poster };
82
+ }
83
+
84
+ /** -> { name } when videos/_character holds a valid character, else null. Never throws. */
85
+ function readPersona(realCwd) {
86
+ try {
87
+ const c = readCharacter(realCwd);
88
+ return c ? { name: c.json.name } : null;
89
+ } catch {
90
+ return null;
91
+ }
92
+ }
93
+
94
+ /** The only outcome a run may record instead of a video (projectHomeAdminRoutes.cjs VIDEO_OUTCOMES). */
95
+ const VIDEO_OUTCOMES = new Set(['season-complete']);
96
+
97
+ /**
98
+ * -> { id, outcome, text, at } from videos/<id>/outcome.json (written by
99
+ * project_video_outcome_write), or null when absent, unreadable or invalid. Never throws.
100
+ */
101
+ async function readOutcome(dir, id) {
102
+ let rec;
103
+ try {
104
+ rec = JSON.parse(await fsp.readFile(path.join(dir, 'outcome.json'), 'utf8'));
105
+ } catch {
106
+ return null;
107
+ }
108
+ if (!rec || typeof rec !== 'object' || Array.isArray(rec)) return null;
109
+ const { outcome, text, at } = rec;
110
+ if (rec.id !== id || !VIDEO_OUTCOMES.has(outcome)) return null;
111
+ if (typeof text !== 'string' || !text.trim() || typeof at !== 'string' || !Number.isFinite(Date.parse(at))) return null;
112
+ return { id, outcome, text, at };
113
+ }
114
+
115
+ /** Lists one kind's entries; for videos, folders with no index.html but a valid outcome.json go to `outcomes`. */
116
+ async function listKind(realCwd, kind, outcomes = []) {
64
117
  const root = pagesPath(realCwd, kind);
65
118
  if (!root) return [];
66
119
  let dirents;
@@ -71,7 +124,15 @@ async function listKind(realCwd, kind) {
71
124
  throw e;
72
125
  }
73
126
  const dirs = dirents.filter((d) => d.isDirectory() && !SKIP_DIRS.has(d.name)).slice(0, MAX_ENTRIES);
74
- const entries = (await Promise.all(dirs.map((d) => readEntry(kind, path.join(root, d.name), d.name)))).filter(Boolean);
127
+ const read = await Promise.all(dirs.map((d) => readEntry(kind, path.join(root, d.name), d.name)));
128
+ if (kind === 'videos') {
129
+ const found = await Promise.all(
130
+ dirs.map((d, i) => (read[i] ? null : readOutcome(path.join(root, d.name), d.name))),
131
+ );
132
+ for (const o of found) if (o) outcomes.push(o);
133
+ outcomes.sort((a, b) => Date.parse(b.at) - Date.parse(a.at));
134
+ }
135
+ const entries = read.filter(Boolean);
75
136
  const stamp = (e) => {
76
137
  const t = e.meta ? Date.parse(e.meta.createdAt) : NaN;
77
138
  return Number.isFinite(t) ? t : e.mtimeMs;
@@ -79,10 +140,15 @@ async function listKind(realCwd, kind) {
79
140
  return entries.sort((a, b) => stamp(b) - stamp(a));
80
141
  }
81
142
 
82
- /** -> { knowledge: Entry[], videos: Entry[] }, newest first. */
143
+ /**
144
+ * -> { knowledge: Entry[], videos: Entry[] (with exports), persona: {name}|null,
145
+ * outcomes: {id, outcome, text, at}[] (video folders with an outcome and no index.html) }, newest first.
146
+ */
83
147
  async function listLibrary(realCwd) {
84
- const [knowledge, videos] = await Promise.all(KINDS.map((k) => listKind(realCwd, k)));
85
- return { knowledge, videos };
148
+ const outcomes = [];
149
+ const [knowledge, videos] = await Promise.all(KINDS.map((k) => listKind(realCwd, k, outcomes)));
150
+ const persona = pagesPath(realCwd) ? readPersona(realCwd) : null;
151
+ return { knowledge, videos, persona, outcomes };
86
152
  }
87
153
 
88
154
  /** Write `outBuf` into `destDir/index.html` + meta; true only after a byte-equal verified write. */
@@ -3,8 +3,9 @@
3
3
  /**
4
4
  * videoReviewIpc.cjs — IPC handlers `project-videos:review-list`,
5
5
  * `project-videos:review-decide` and `project-videos:review-retry`: the human
6
- * review step of a project Video
7
- * tool entry. Renderer IPC only — no admin route or MCP tool reaches a
6
+ * review step of a project Video tool entry or a built-in Demo Video entry
7
+ * (dispatch.macroId 'builtin-demo-video') — decide/retry re-dispatch whatever
8
+ * macroId dispatch.json recorded, with no tool lookup of their own. Renderer IPC only — no admin route or MCP tool reaches a
8
9
  * decision, and nothing here mints an Epic.
9
10
  *
10
11
  * approve — starts the tool's final run in the Epic that built the entry
@@ -0,0 +1,175 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * voiceAdminRoutes.cjs — the voice library's READ routes for agents (MCP
5
+ * voice_list / voice_preview). Neither route can change a voice: approving,
6
+ * unapproving and deleting stay renderer-IPC only (voicesIpc.cjs).
7
+ *
8
+ * GET /admin/voices?cwd=<abs> -> {ok, voices, errors} (voiceLibrary.listVoices)
9
+ * POST /admin/voices/preview {cwd, voiceId, text}
10
+ * -> {ok:true, status:'ready', cached, wavPath, wallMs, audioSeconds}
11
+ * when previewVoice finishes within WAIT_MS (60 s), else
12
+ * -> {ok:true, status:'queued', lane, position}
13
+ * while the run keeps going in-process. A repeat call with the same
14
+ * (project, voiceId, text) joins that run, or — once it finished —
15
+ * previewVoice answers from its clip cache.
16
+ *
17
+ * cwd goes through projectHomeAdminRoutes.resolveCwd (the shared project-root
18
+ * resolver + allowed-roots check); voiceId must match VOICE_ID_RE and text be
19
+ * 1-TEXT_MAX chars after trimming; bad input answers 400.
20
+ *
21
+ * deps (tests): { resolveCwd, voiceLibrary, voiceLane, previewVoice, waitMs, now }.
22
+ */
23
+
24
+ const { readBody, sendJson } = require('../feedback-remote/localAdminHttp.cjs');
25
+ const { wavSeconds } = require('../demo-video-kit/character.cjs');
26
+
27
+ const { VOICE_ID_RE } = require('../demo-video-kit/voiceLibrary.cjs');
28
+ const TEXT_MAX = 300;
29
+ const WAIT_MS = 60 * 1000;
30
+ const BODY_MAX = 64 * 1024;
31
+
32
+ /** key -> {promise, startedAt} for previews still running in-process. */
33
+ const pending = new Map();
34
+
35
+ function depsOf(deps) {
36
+ return {
37
+ resolveCwd: deps.resolveCwd || require('../feedback-remote/projectHomeAdminRoutes.cjs').resolveCwd,
38
+ voiceLibrary: deps.voiceLibrary || require('../demo-video-kit/voiceLibrary.cjs'),
39
+ voiceLane: deps.voiceLane || require('../demo-video-kit/voiceLane.cjs'),
40
+ previewVoice: deps.previewVoice || require('./voicePreview.cjs').previewVoice,
41
+ waitMs: Number.isFinite(deps.waitMs) && deps.waitMs >= 0 ? deps.waitMs : WAIT_MS,
42
+ now: deps.now || Date.now,
43
+ };
44
+ }
45
+
46
+ /** Seconds of audio in the clip at wavPath (character.cjs wavSeconds, 3 dp), else null. */
47
+ function clipSeconds(wavPath) {
48
+ if (!wavPath) return null;
49
+ const s = wavSeconds(wavPath);
50
+ return s > 0 ? Math.round(s * 1000) / 1000 : null;
51
+ }
52
+
53
+ /** -> null when the preview body is acceptable, else the 400 reason. */
54
+ function validatePreviewBody(body) {
55
+ if (!body || typeof body !== 'object' || Array.isArray(body)) return 'invalid payload';
56
+ if (typeof body.voiceId !== 'string' || !VOICE_ID_RE.test(body.voiceId)) {
57
+ return `voiceId must match /${VOICE_ID_RE.source}/`;
58
+ }
59
+ const t = typeof body.text === 'string' ? body.text.trim() : '';
60
+ if (t.length < 1 || t.length > TEXT_MAX) return `text must be 1-${TEXT_MAX} chars`;
61
+ return null;
62
+ }
63
+
64
+ /** This preview's place in the voice lane: {lane, position} or {lane:null, position:null}. */
65
+ function lanePositionOf(d, root, voiceId) {
66
+ let snapshot = {};
67
+ try { snapshot = d.voiceLane.laneSnapshot() || {}; } catch { snapshot = {}; }
68
+ for (const [lane, tickets] of Object.entries(snapshot)) {
69
+ for (const t of Array.isArray(tickets) ? tickets : []) {
70
+ if (!t || t.voiceId !== voiceId) continue;
71
+ if (t.projectRoot && t.projectRoot !== root) continue;
72
+ return { lane, position: Number.isFinite(t.position) ? t.position : null };
73
+ }
74
+ }
75
+ return { lane: null, position: null };
76
+ }
77
+
78
+ function listHandler(deps) {
79
+ return async (_req, res, query) => {
80
+ const d = depsOf(deps);
81
+ const resolved = d.resolveCwd(query?.get('cwd') ?? '');
82
+ if (!resolved.ok) {
83
+ sendJson(res, resolved.status || 400, { ok: false, error: resolved.error });
84
+ return;
85
+ }
86
+ const { voices, errors } = d.voiceLibrary.listVoices(resolved.cwd);
87
+ sendJson(res, 200, { ok: true, voices, errors });
88
+ };
89
+ }
90
+
91
+ function previewHandler(deps) {
92
+ return async (req, res) => {
93
+ const d = depsOf(deps);
94
+ let raw;
95
+ try {
96
+ raw = await readBody(req, BODY_MAX);
97
+ } catch (e) {
98
+ sendJson(res, 400, { ok: false, error: `request body rejected: ${e?.message ?? 'unreadable'}` });
99
+ return;
100
+ }
101
+ let body;
102
+ try {
103
+ body = raw ? JSON.parse(raw) : {};
104
+ } catch {
105
+ sendJson(res, 400, { ok: false, error: 'invalid JSON body' });
106
+ return;
107
+ }
108
+ const invalid = validatePreviewBody(body);
109
+ if (invalid) {
110
+ sendJson(res, 400, { ok: false, error: invalid });
111
+ return;
112
+ }
113
+ const resolved = d.resolveCwd(body.cwd);
114
+ if (!resolved.ok) {
115
+ sendJson(res, resolved.status || 400, { ok: false, error: resolved.error });
116
+ return;
117
+ }
118
+ const root = resolved.cwd;
119
+ const voiceId = body.voiceId;
120
+ const text = body.text.trim();
121
+ const rv = d.voiceLibrary.resolveVoiceId(root, voiceId);
122
+ if (!rv || !rv.ok) {
123
+ sendJson(res, 400, { ok: false, error: (rv && rv.error) || `unknown voice '${voiceId}'` });
124
+ return;
125
+ }
126
+
127
+ const key = JSON.stringify([root, voiceId, text]);
128
+ let run = pending.get(key);
129
+ if (!run) {
130
+ const startedAt = d.now();
131
+ const promise = Promise.resolve()
132
+ .then(() => d.previewVoice({ projectRoot: root, voiceId, text }))
133
+ .catch((e) => ({ ok: false, error: `voice preview failed: ${e?.message ?? String(e)}` }))
134
+ .then((r) => ({ r, endedAt: d.now() }))
135
+ .finally(() => { if (pending.get(key) === run) pending.delete(key); });
136
+ run = { promise, startedAt };
137
+ pending.set(key, run);
138
+ }
139
+
140
+ let timer = null;
141
+ const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve(null), d.waitMs); });
142
+ const outcome = await Promise.race([run.promise, timeout]);
143
+ clearTimeout(timer);
144
+
145
+ if (!outcome) {
146
+ sendJson(res, 200, { ok: true, status: 'queued', ...lanePositionOf(d, root, voiceId) });
147
+ return;
148
+ }
149
+ const { r, endedAt } = outcome;
150
+ if (!r || r.ok !== true) {
151
+ sendJson(res, 500, { ok: false, error: (r && r.error) || 'voice preview failed' });
152
+ return;
153
+ }
154
+ sendJson(res, 200, {
155
+ ok: true,
156
+ status: 'ready',
157
+ cached: !!r.cached,
158
+ wavPath: r.wavPath,
159
+ wallMs: Math.max(0, endedAt - run.startedAt),
160
+ audioSeconds: clipSeconds(r.wavPath),
161
+ });
162
+ };
163
+ }
164
+
165
+ function registerAdminRoute(adminHttp, deps = {}) {
166
+ adminHttp.registerRoute('GET', '/admin/voices', listHandler(deps));
167
+ adminHttp.registerRoute('POST', '/admin/voices/preview', previewHandler(deps));
168
+ }
169
+
170
+ /** Tests only: forget previews still tracked in-process. */
171
+ function _resetPending() {
172
+ pending.clear();
173
+ }
174
+
175
+ module.exports = { registerAdminRoute, validatePreviewBody, VOICE_ID_RE, TEXT_MAX, WAIT_MS, _resetPending };