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,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. */
@@ -0,0 +1,145 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * videoPressLines.cjs — a scripted Demo Video press: validate its choices and
5
+ * build exactly the prompt lines the Project Home composer sends for the same
6
+ * choices, so a scripted press runs the same job as a human press.
7
+ *
8
+ * Pure: no fs, no IPC. Mirrors renderer composerTemplates.ts (VIDEO_KINDS,
9
+ * videoLengthsFor, voiceLine, videoPromptLines); main may not import renderer
10
+ * code, so __tests__/videoPressLines.test.cjs asserts the two stay identical.
11
+ * Whether a voice exists in the project's library is the route's check, not this one.
12
+ *
13
+ * parseScriptPress(body) -> { ok: true, cfg } | { ok: false, error } (error: one line)
14
+ * body: { kind, target?, length?, style?, character?, voiceId?, focus?, reviewFirst? }
15
+ * cfg (renderer VideoCfg shape): { kind, target, style, length, mascot, review, focus, voice? }
16
+ * pressLines(cfg) -> string[]
17
+ *
18
+ * Review first travels only as cfg.review (the press's reviewStage), never as a
19
+ * line; a 'Review:' or 'Replace entry:' line in target or focus is refused so a
20
+ * script cannot forge an owner approval or overwrite an entry.
21
+ */
22
+
23
+ const { VOICE_ID_RE } = require('../demo-video-kit/voiceLibrary.cjs');
24
+
25
+ const VIDEO_KINDS = Object.freeze(['Project demo', 'Blog post', 'Feature', 'TikTok', 'Marketing']);
26
+ const KIND_SLUGS = Object.freeze({
27
+ 'project-demo': 'Project demo',
28
+ 'blog-post': 'Blog post',
29
+ feature: 'Feature',
30
+ tiktok: 'TikTok',
31
+ marketing: 'Marketing',
32
+ });
33
+ const VIDEO_STYLES = Object.freeze(['Auto', 'Professional', 'Fun', 'Animated whiteboard', 'Kinetic typography']);
34
+ const TARGET_REQUIRED_KINDS = Object.freeze(['Blog post', 'Feature']);
35
+ const MAX_TARGET = 500;
36
+ const MAX_FOCUS = 2000;
37
+ const RESERVED_LINE_RE = /^\s*(review|replace entry)\s*:/im;
38
+ const CONTROL_RE = /[\u0000-\u001f\u007f]/;
39
+ const FOCUS_CONTROL_RE = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/;
40
+
41
+ /** The length chips a kind offers: 15 s only for TikTok (renderer videoLengthsFor). */
42
+ function videoLengthsFor(kind) {
43
+ return kind === 'TikTok' ? [15, 30, 60] : [30, 60];
44
+ }
45
+
46
+ function fail(error) {
47
+ return { ok: false, error };
48
+ }
49
+
50
+ function parseScriptPress(body) {
51
+ if (!body || typeof body !== 'object' || Array.isArray(body)) return fail('press body must be an object');
52
+
53
+ const rawKind = body.kind;
54
+ if (typeof rawKind !== 'string') return fail(`kind is required: one of ${VIDEO_KINDS.join(', ')}`);
55
+ const kind = VIDEO_KINDS.includes(rawKind) ? rawKind : Object.prototype.hasOwnProperty.call(KIND_SLUGS, rawKind) ? KIND_SLUGS[rawKind] : null;
56
+ if (!kind) return fail(`unknown kind '${oneLine(rawKind)}': one of ${VIDEO_KINDS.join(', ')} (or its slug)`);
57
+
58
+ let length = 30;
59
+ if (body.length !== undefined) {
60
+ const allowed = videoLengthsFor(kind);
61
+ if (typeof body.length !== 'number' || !allowed.includes(body.length)) {
62
+ return fail(`length for ${kind} must be one of ${allowed.join(', ')}`);
63
+ }
64
+ length = body.length;
65
+ }
66
+
67
+ let style = 'Auto';
68
+ if (body.style !== undefined) {
69
+ if (typeof body.style !== 'string' || !VIDEO_STYLES.includes(body.style)) {
70
+ return fail(`style must be one of ${VIDEO_STYLES.join(', ')}`);
71
+ }
72
+ style = body.style;
73
+ }
74
+
75
+ let mascot = true;
76
+ if (body.character !== undefined) {
77
+ if (typeof body.character !== 'boolean') return fail('character must be true or false');
78
+ mascot = body.character;
79
+ }
80
+
81
+ let review = false;
82
+ if (body.reviewFirst !== undefined) {
83
+ if (typeof body.reviewFirst !== 'boolean') return fail('reviewFirst must be true or false');
84
+ review = body.reviewFirst;
85
+ }
86
+
87
+ let voice;
88
+ if (body.voiceId !== undefined) {
89
+ if (typeof body.voiceId !== 'string' || !VOICE_ID_RE.test(body.voiceId)) {
90
+ return fail(`voiceId must match ${VOICE_ID_RE}`);
91
+ }
92
+ voice = body.voiceId;
93
+ }
94
+
95
+ let target = '';
96
+ if (body.target !== undefined) {
97
+ if (typeof body.target !== 'string') return fail('target must be a string');
98
+ if (CONTROL_RE.test(body.target)) return fail('target must be one line with no control characters');
99
+ target = body.target.trim();
100
+ if (target.length > MAX_TARGET) return fail(`target must be at most ${MAX_TARGET} characters`);
101
+ if (RESERVED_LINE_RE.test(target)) return fail("target may not carry a 'Review:' or 'Replace entry:' line");
102
+ }
103
+ if (TARGET_REQUIRED_KINDS.includes(kind) && !target) return fail(`target is required for a ${kind} video`);
104
+
105
+ let focus = '';
106
+ if (body.focus !== undefined) {
107
+ if (typeof body.focus !== 'string') return fail('focus must be a string');
108
+ if (FOCUS_CONTROL_RE.test(body.focus)) return fail('focus may not contain control characters');
109
+ focus = body.focus.trim();
110
+ if (focus.length > MAX_FOCUS) return fail(`focus must be at most ${MAX_FOCUS} characters`);
111
+ if (RESERVED_LINE_RE.test(focus)) return fail("focus may not carry a 'Review:' or 'Replace entry:' line");
112
+ }
113
+
114
+ const cfg = { kind, target, style, length, mascot, review, focus };
115
+ if (voice) cfg.voice = voice;
116
+ return { ok: true, cfg };
117
+ }
118
+
119
+ /** Same lines as renderer videoPromptLines(cfg); a target is named only for a non-demo kind. */
120
+ function pressLines(cfg) {
121
+ const lines = [`Video kind: ${cfg.kind}`];
122
+ const target = (cfg.target || '').trim();
123
+ if (cfg.kind !== 'Project demo' && target) lines.push(`Video target: ${target}`);
124
+ lines.push(`Video style: ${cfg.style}`);
125
+ const voice = typeof cfg.voice === 'string' ? cfg.voice.trim() : '';
126
+ if (voice) lines.push(`Voice: ${voice}`);
127
+ lines.push(`Video length: ${cfg.length}`, `Character: ${cfg.mascot ? 'on' : 'off'}`);
128
+ const focus = (cfg.focus || '').trim();
129
+ if (focus) lines.push(focus);
130
+ return lines;
131
+ }
132
+
133
+ function oneLine(s) {
134
+ return String(s).replace(/[\u0000-\u001f\u007f]+/g, ' ').slice(0, 80);
135
+ }
136
+
137
+ module.exports = {
138
+ parseScriptPress,
139
+ pressLines,
140
+ VIDEO_KINDS,
141
+ VIDEO_STYLES,
142
+ KIND_SLUGS,
143
+ MAX_TARGET,
144
+ MAX_FOCUS,
145
+ };
@@ -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