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,298 @@
1
+ 'use strict';
2
+ // Demo-video kit resumable run: one long kit step (e.g. a slow local voice)
3
+ // runs under a detached supervisor, and callers wait for it in slices.
4
+ //
5
+ // Why: a headless scheduler job's foreground Bash call is capped at 15 minutes
6
+ // and its idle watchdog fires after 20 minutes without output, so a step that
7
+ // can take longer must outlive one call. Each call runs startOrAttach (same
8
+ // key -> attach to the live run) then waitForResult for one slice; 'pending'
9
+ // means "call again".
10
+ //
11
+ // How it ends: on Linux the job's scope and the scheduler's leftover sweep stop
12
+ // the supervisor's process group with the job. On every platform (macOS sweeps
13
+ // only the job's own process group) the caller lease ends it: startOrAttach and
14
+ // every waitForResult check refresh <stateDir>/lease, and the supervisor writes
15
+ // an 'abandoned' result and SIGTERMs its whole group once no caller has checked
16
+ // in for DEFAULT_LEASE_MS.
17
+ //
18
+ // Why own pid check, single-write result file and tolerant JSON read although
19
+ // src/main/lib/AGENTS.md says to reuse process/pidAlive.cjs and
20
+ // util/atomicFs.cjs: kit files are seeded to ~/.claude/session-manager/
21
+ // demo-video-kit/ and must load standalone (node built-ins and this folder
22
+ // only), so they cannot require those modules. A partial result.json reads as
23
+ // "not written yet".
24
+ //
25
+ // Files in stateDir: state.json { key, pid, startedAt }, lease (mtime only),
26
+ // result.json { key, result }, run.log (supervisor + step stdout/stderr of the
27
+ // latest fresh run; truncated on each fresh start), start.lock (held only while
28
+ // startOrAttach starts a run, so two concurrent starts spawn one supervisor).
29
+ //
30
+ // Process tree: on POSIX the supervisor leads its own process group and stops
31
+ // the whole group (SIGTERM) on lease expiry and after its step exits, so a
32
+ // voice wrapper's grandchildren never outlive the run. On win32 the same
33
+ // points run `taskkill /PID <pid> /T /F` (winTreeKillArgv).
34
+ const fs = require('node:fs');
35
+ const path = require('node:path');
36
+ const { spawn, spawnSync } = require('node:child_process');
37
+
38
+ const DEFAULT_LEASE_MS = 20 * 60 * 1000;
39
+ const LEASE_CHECK_MAX_MS = 15 * 1000;
40
+ const DEFAULT_POLL_MS = 1000;
41
+ const LOG_TAIL_BYTES = 500;
42
+ const START_LOCK_STALE_MS = 30 * 1000;
43
+ const START_LOCK_WAIT_MS = 50;
44
+ const START_LOCK_MAX_WAITS = 40;
45
+
46
+ const statePath = (d) => path.join(d, 'state.json');
47
+ const leasePath = (d) => path.join(d, 'lease');
48
+ const resultPath = (d) => path.join(d, 'result.json');
49
+ const logPath = (d) => path.join(d, 'run.log');
50
+ const lockPath = (d) => path.join(d, 'start.lock');
51
+
52
+ function readJson(file) {
53
+ try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return null; }
54
+ }
55
+
56
+ /** process.kill(pid, 0): ESRCH = dead, EPERM = alive (someone else's). */
57
+ function pidAlive(pid) {
58
+ if (!Number.isInteger(pid) || pid <= 0) return false;
59
+ try { process.kill(pid, 0); return true; } catch (err) { return err && err.code === 'EPERM'; }
60
+ }
61
+
62
+ function rmQuiet(file) {
63
+ try { fs.rmSync(file, { force: true }); } catch { /* ignore */ }
64
+ }
65
+
66
+ function refreshLease(stateDir) {
67
+ const p = leasePath(stateDir);
68
+ try {
69
+ fs.closeSync(fs.openSync(p, 'a'));
70
+ const now = new Date();
71
+ fs.utimesSync(p, now, now);
72
+ } catch { /* stateDir gone: the run was stopped */ }
73
+ }
74
+
75
+ function readState(stateDir) {
76
+ const s = readJson(statePath(stateDir));
77
+ return s && typeof s === 'object' && typeof s.key === 'string' && Number.isInteger(s.pid) ? s : null;
78
+ }
79
+
80
+ /** Single write of { key, result }; readers treat a partial file as not written yet. */
81
+ function writeResult(stateDir, key, result) {
82
+ fs.writeFileSync(resultPath(stateDir), JSON.stringify({ key, result }));
83
+ }
84
+
85
+ function readResult(stateDir, key) {
86
+ const r = readJson(resultPath(stateDir));
87
+ if (!r || typeof r !== 'object' || r.key !== key || !('result' in r)) return null;
88
+ return r;
89
+ }
90
+
91
+ /** Last `bytes` of run.log as text ('' when missing). */
92
+ function readLogTail(stateDir, bytes = LOG_TAIL_BYTES) {
93
+ let fd;
94
+ try {
95
+ fd = fs.openSync(logPath(stateDir), 'r');
96
+ const size = fs.fstatSync(fd).size;
97
+ const len = Math.min(size, Math.max(0, bytes));
98
+ const buf = Buffer.alloc(len);
99
+ fs.readSync(fd, buf, 0, len, size - len);
100
+ return buf.toString('utf8');
101
+ } catch {
102
+ return '';
103
+ } finally {
104
+ if (fd !== undefined) try { fs.closeSync(fd); } catch { /* ignore */ }
105
+ }
106
+ }
107
+
108
+ function killQuiet(pid, sig) {
109
+ try { process.kill(pid, sig); } catch { /* ESRCH: already gone */ }
110
+ }
111
+
112
+ /** win32 argv that ends pid and every descendant. */
113
+ function winTreeKillArgv(pid) {
114
+ return ['taskkill', '/PID', String(pid), '/T', '/F'];
115
+ }
116
+
117
+ /** End pid's whole tree: taskkill /T on win32, SIGTERM to its process group on POSIX. */
118
+ function killTree(pid) {
119
+ if (process.platform === 'win32') {
120
+ const argv = winTreeKillArgv(pid);
121
+ try { spawnSync(argv[0], argv.slice(1), { shell: false, windowsHide: true, stdio: 'ignore' }); } catch { /* ignore */ }
122
+ return;
123
+ }
124
+ killQuiet(-pid, 'SIGTERM');
125
+ killQuiet(pid, 'SIGTERM');
126
+ }
127
+
128
+ /** Synchronous pause without a busy loop. */
129
+ function sleepSync(ms) {
130
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
131
+ }
132
+
133
+ /** Stop the recorded run (its whole process tree) and clear its files. */
134
+ function stopRun(stateDir) {
135
+ const s = readState(stateDir);
136
+ if (s) killTree(s.pid);
137
+ rmQuiet(statePath(stateDir));
138
+ rmQuiet(resultPath(stateDir));
139
+ rmQuiet(leasePath(stateDir));
140
+ }
141
+
142
+ /**
143
+ * Start `argv` (node args, run with process.execPath) under a detached
144
+ * supervisor, or attach when the same key's supervisor is still alive.
145
+ * -> { pid, started }
146
+ */
147
+ function startOrAttach({ stateDir, key, argv, cwd, leaseMs = DEFAULT_LEASE_MS }) {
148
+ if (!stateDir || typeof key !== 'string' || !key) throw new Error('resumableRun: stateDir and key are required');
149
+ if (!Array.isArray(argv) || argv.length === 0) throw new Error('resumableRun: argv must be a non-empty array');
150
+ fs.mkdirSync(stateDir, { recursive: true });
151
+ const attached = attachLive(stateDir, key);
152
+ if (attached) return attached;
153
+ const lock = lockPath(stateDir);
154
+ let waits = 0;
155
+ let staleRemoved = false;
156
+ for (;;) {
157
+ try {
158
+ fs.closeSync(fs.openSync(lock, 'wx'));
159
+ break;
160
+ } catch (err) {
161
+ if (!err || err.code !== 'EEXIST') throw err;
162
+ }
163
+ // Another caller is starting a run: attach to it once it is recorded.
164
+ const other = attachLive(stateDir, key);
165
+ if (other) return other;
166
+ let age = 0;
167
+ try { age = Date.now() - fs.statSync(lock).mtimeMs; } catch { /* released meanwhile: retry */ }
168
+ if (age > START_LOCK_STALE_MS && !staleRemoved) {
169
+ staleRemoved = true;
170
+ rmQuiet(lock);
171
+ continue;
172
+ }
173
+ if (waits >= START_LOCK_MAX_WAITS) {
174
+ throw new Error(`resumableRun: start lock ${lock} is still held after ${START_LOCK_MAX_WAITS * START_LOCK_WAIT_MS} ms`);
175
+ }
176
+ waits++;
177
+ sleepSync(START_LOCK_WAIT_MS);
178
+ }
179
+ try {
180
+ return startLocked({ stateDir, key, argv, cwd, leaseMs });
181
+ } finally {
182
+ rmQuiet(lock);
183
+ }
184
+ }
185
+
186
+ /** Same key with a live supervisor -> attach result; otherwise null. */
187
+ function attachLive(stateDir, key) {
188
+ const s = readState(stateDir);
189
+ if (s && s.key === key && pidAlive(s.pid)) {
190
+ refreshLease(stateDir);
191
+ return { pid: s.pid, started: false };
192
+ }
193
+ return null;
194
+ }
195
+
196
+ /** Called with start.lock held: re-check, then start a fresh run. */
197
+ function startLocked({ stateDir, key, argv, cwd, leaseMs }) {
198
+ const s = readState(stateDir);
199
+ if (s && pidAlive(s.pid)) {
200
+ if (s.key === key) {
201
+ refreshLease(stateDir);
202
+ return { pid: s.pid, started: false };
203
+ }
204
+ stopRun(stateDir);
205
+ }
206
+ // A fresh run: its waiter must see only its own result and its own log.
207
+ rmQuiet(resultPath(stateDir));
208
+ refreshLease(stateDir);
209
+ const logFd = fs.openSync(logPath(stateDir), 'w');
210
+ let child;
211
+ try {
212
+ child = spawn(process.execPath, [__filename, '__supervise', stateDir, key, String(leaseMs), '--', ...argv], {
213
+ detached: true,
214
+ stdio: ['ignore', logFd, logFd],
215
+ cwd,
216
+ env: process.env,
217
+ });
218
+ child.unref();
219
+ } finally {
220
+ fs.closeSync(logFd);
221
+ }
222
+ fs.writeFileSync(statePath(stateDir), JSON.stringify({ key, pid: child.pid, startedAt: Date.now() }));
223
+ refreshLease(stateDir);
224
+ return { pid: child.pid, started: true };
225
+ }
226
+
227
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
228
+
229
+ /**
230
+ * Wait up to waitMs (never more than waitMs + pollMs) for the key's result.
231
+ * -> { status: 'done', result } | { status: 'pending', pid, elapsedMs } | { status: 'lost', error }
232
+ */
233
+ async function waitForResult({ stateDir, key, waitMs, pollMs = DEFAULT_POLL_MS }) {
234
+ const t0 = Date.now();
235
+ const wait = Math.max(0, Number(waitMs) || 0);
236
+ const poll = Math.max(1, Number(pollMs) || DEFAULT_POLL_MS);
237
+ for (;;) {
238
+ refreshLease(stateDir);
239
+ let r = readResult(stateDir, key);
240
+ if (r) return { status: 'done', result: r.result };
241
+ const s = readState(stateDir);
242
+ if (!s || s.key !== key || !pidAlive(s.pid)) {
243
+ r = readResult(stateDir, key); // the step may have written it just before exiting
244
+ if (r) return { status: 'done', result: r.result };
245
+ const why = !s || s.key !== key ? `no run recorded for key ${key}` : `run ${s.pid} ended without a result`;
246
+ return { status: 'lost', error: `${why}; log tail:\n${readLogTail(stateDir, LOG_TAIL_BYTES)}` };
247
+ }
248
+ const spent = Date.now() - t0;
249
+ if (spent >= wait) {
250
+ return { status: 'pending', pid: s.pid, elapsedMs: Date.now() - (Number(s.startedAt) || t0) };
251
+ }
252
+ await sleep(Math.min(poll, wait - spent));
253
+ }
254
+ }
255
+
256
+ function supervise(args) {
257
+ const [stateDir, key, leaseArg, sep, ...argv] = args;
258
+ const leaseMs = Number(leaseArg) > 0 ? Number(leaseArg) : DEFAULT_LEASE_MS;
259
+ if (sep !== '--' || argv.length === 0) {
260
+ process.stderr.write('resumableRun supervisor: missing step argv\n');
261
+ process.exit(2);
262
+ }
263
+ // Not detached: the step and anything it spawns stay in this process group.
264
+ const step = spawn(process.execPath, argv, { stdio: ['ignore', 'inherit', 'inherit'], cwd: process.cwd() });
265
+ const every = Math.min(LEASE_CHECK_MAX_MS, Math.max(1, Math.floor(leaseMs / 4)));
266
+ const timer = setInterval(() => {
267
+ let age = Infinity;
268
+ try { age = Date.now() - fs.statSync(leasePath(stateDir)).mtimeMs; } catch { /* missing lease = no caller */ }
269
+ if (age <= leaseMs) return;
270
+ clearInterval(timer);
271
+ try {
272
+ writeResult(stateDir, key, { ok: false, error: `abandoned: no caller for ${Math.round(leaseMs / 60000)} min` });
273
+ } catch { /* stateDir gone */ }
274
+ process.stderr.write(`resumableRun supervisor: lease expired, stopping group ${process.pid}\n`);
275
+ killTree(process.pid);
276
+ process.exit(1);
277
+ }, every);
278
+ step.on('error', (err) => {
279
+ process.stderr.write(`resumableRun supervisor: step failed to start: ${err.message}\n`);
280
+ clearInterval(timer);
281
+ process.exit(1);
282
+ });
283
+ step.on('exit', (code, signal) => {
284
+ clearInterval(timer);
285
+ // The step wrote its result before exiting; stop whatever it left in this
286
+ // group (e.g. a voice wrapper's grandchildren). The waiter is not in it.
287
+ const exitCode = code ?? (signal ? 1 : 0);
288
+ process.on('SIGTERM', () => process.exit(exitCode));
289
+ killTree(process.pid);
290
+ process.exit(exitCode);
291
+ });
292
+ }
293
+
294
+ if (require.main === module && process.argv[2] === '__supervise') {
295
+ supervise(process.argv.slice(3));
296
+ }
297
+
298
+ module.exports = { startOrAttach, waitForResult, writeResult, stopRun, readLogTail, winTreeKillArgv, DEFAULT_LEASE_MS };
@@ -19,10 +19,10 @@ const path = require('node:path');
19
19
  const { schedulerHome } = require('../scheduler/schedulerPaths.cjs');
20
20
  const { writeTextAtomic } = require('../util/atomicFs.cjs');
21
21
 
22
- const KIT_VERSION = '3';
22
+ const KIT_VERSION = '45';
23
23
  // sha256 of kitDigest(__dirname). Update together with a KIT_VERSION bump.
24
- const KIT_DIGEST = 'b3bb70c8984d8b794a20a68d36c22e2f7fe97cdfad8215f5ae7294c47388571c';
25
- const KIT_FILES = Object.freeze(['checks.cjs', 'sound.cjs', 'capture.cjs', 'frames.cjs', 'character.cjs', 'playwrightLoader.cjs']);
24
+ const KIT_DIGEST = 'd1735e9ad8044d68d81ba52fd4d95f5b80f763f2811a8674211d25ef5d49f482';
25
+ const KIT_FILES = Object.freeze(['checks.cjs', 'sound.cjs', 'capture.cjs', 'frames.cjs', 'character.cjs', 'playwrightLoader.cjs', 'export.cjs', 'kind-tiktok.md', 'kind-marketing.md', 'cast.md', 'project-home-html.md', 'resumableRun.cjs', 'voiceLibrary.cjs', 'voiceLane.cjs', 'kokoroSay.cjs', 'projectSounds.cjs', 'standalone.cjs']);
26
26
  const STAMP_FILE = 'KIT_VERSION';
27
27
 
28
28
  /** The single list of kit files (paths relative to the kit dir) the seeder copies. */
@@ -261,21 +261,178 @@ function duckEnvelope(narr) {
261
261
  return { gain, speechS: active * 0.02 };
262
262
  }
263
263
 
264
+ /** Decode any audio file to mono 44.1 kHz float samples (non-finite samples -> 0). */
265
+ function decodeMono(file, dir, tag) {
266
+ const f32 = path.join(dir, `${tag}.f32.wav`);
267
+ runFfmpeg(['-hide_banner', '-nostats', '-y', '-i', file, '-vn', '-ac', '1', '-ar', String(SR), '-c:a', 'pcm_f32le', f32]);
268
+ const x = decodeWavF32(fs.readFileSync(f32));
269
+ // A single NaN in the buffer handed to ffmpeg makes libmp3lame assert (0-byte mp3).
270
+ for (let i = 0; i < x.length; i++) if (!Number.isFinite(x[i])) x[i] = 0;
271
+ return x;
272
+ }
273
+
274
+ const BUILTIN_LIST = SFX_NAMES.join(', ');
275
+
276
+ // Mutable so a test can shorten the limit; production never changes it.
277
+ const BED_COMMAND_LIMITS = { timeoutMs: 300000 };
278
+ const BED_STDERR_TAIL = 500;
279
+
280
+ /** Lazy, memoised persona reader for the cue/bed pre-pass; throws when character.json exists but is unusable. */
281
+ function personaLoader(projectRoot) {
282
+ let persona;
283
+ return () => {
284
+ if (persona === undefined) {
285
+ const { inspectCharacter } = require('./character.cjs');
286
+ persona = inspectCharacter(projectRoot);
287
+ if (!persona.ok && persona.exists) throw new Error(`project persona unusable: ${persona.error}`);
288
+ }
289
+ return persona;
290
+ };
291
+ }
292
+
293
+ const hasRoot = (projectRoot) => projectRoot !== undefined && projectRoot !== null;
294
+
295
+ /**
296
+ * Resolve every cue name before any audio work: built-ins map to null, a persona
297
+ * sounds.sfx name to its WAV path. Throws a named reason for anything else.
298
+ * The persona is read only when some cue is not built-in.
299
+ */
300
+ function resolveCueFiles(cues, projectRoot, getPersona) {
301
+ const files = new Map();
302
+ for (const cue of cues) {
303
+ const name = cue && cue.name;
304
+ if (SFX_NAMES.includes(name) || files.has(name)) continue;
305
+ if (!hasRoot(projectRoot)) {
306
+ throw new Error(`unknown sfx: ${name} (built-in: ${BUILTIN_LIST}; pass projectRoot to use the persona's own sounds)`);
307
+ }
308
+ const { findProjectSound, soundFile, checkSoundWav } = require('./projectSounds.cjs');
309
+ const persona = getPersona();
310
+ const found = persona.ok ? findProjectSound(persona.json, name) : null;
311
+ if (!found || found.kind !== 'sfx') {
312
+ const s = persona.ok && persona.json.sounds && Array.isArray(persona.json.sounds.sfx) ? persona.json.sounds.sfx : [];
313
+ const names = s.map((e) => e && e.name).filter((n) => typeof n === 'string').join(', ');
314
+ throw new Error(`unknown sfx: ${name} (built-in: ${BUILTIN_LIST}; persona sounds.sfx: ${names || 'none'})`);
315
+ }
316
+ const file = soundFile(projectRoot, name);
317
+ if (!fs.existsSync(file)) {
318
+ throw new Error(`project sfx '${name}' has no WAV at ${file} (save the persona again with its sound files)`);
319
+ }
320
+ const reason = checkSoundWav(fs.readFileSync(file), `project sfx '${name}' (${file})`, 'sfx');
321
+ if (reason) throw new Error(reason);
322
+ files.set(name, file);
323
+ }
324
+ return files;
325
+ }
326
+
327
+ /**
328
+ * Resolve spec.bed before any audio work -> {style} for a built-in bed, {name, file}
329
+ * for a file-backed persona bed, {name, command} for a command bed. Throws a named reason.
330
+ */
331
+ function resolveBed(bed, style, projectRoot, getPersona) {
332
+ if (bed === undefined || bed === null) return { style };
333
+ if (Object.prototype.hasOwnProperty.call(STYLES, bed)) return { style: bed };
334
+ const styles = Object.keys(STYLES).join(', ');
335
+ if (!hasRoot(projectRoot)) {
336
+ throw new Error(`unknown bed: ${bed} (built-in styles: ${styles}; pass projectRoot to use the persona's own beds)`);
337
+ }
338
+ const { findProjectSound, soundFile, checkSoundWav } = require('./projectSounds.cjs');
339
+ const persona = getPersona();
340
+ const found = persona.ok ? findProjectSound(persona.json, bed) : null;
341
+ if (!found || found.kind !== 'bed') {
342
+ const b = persona.ok && persona.json.sounds && Array.isArray(persona.json.sounds.beds) ? persona.json.sounds.beds : [];
343
+ const names = b.map((e) => e && e.name).filter((n) => typeof n === 'string').join(', ');
344
+ throw new Error(`unknown bed: ${bed} (built-in styles: ${styles}; persona sounds.beds: ${names || 'none'})`);
345
+ }
346
+ const name = bed;
347
+ if (Array.isArray(found.entry.command)) return { name, command: [...found.entry.command] };
348
+ const file = soundFile(projectRoot, name);
349
+ if (!fs.existsSync(file)) {
350
+ throw new Error(`project bed '${name}' has no WAV at ${file} (save the persona again with its sound files)`);
351
+ }
352
+ const reason = checkSoundWav(fs.readFileSync(file), `project bed '${name}' (${file})`, 'bed');
353
+ if (reason) throw new Error(reason);
354
+ return { name, file };
355
+ }
356
+
357
+ /** A file bed looped end to end to n samples with bedSamples' edge fades. */
358
+ function loopFileBed(file, dir, n) {
359
+ const s = decodeMono(file, dir, 'bed');
360
+ const out = new Float32Array(n);
361
+ if (s.length > 0) for (let i = 0; i < n; i++) out[i] = s[i % s.length];
362
+ const fade = Math.min(Math.round(1.0 * SR), Math.floor(n / 2));
363
+ for (let i = 0; i < fade; i++) { const g = i / fade; out[i] *= g; out[n - 1 - i] *= g; }
364
+ return out;
365
+ }
366
+
367
+ /** Render a command bed of n samples via the project's own command (no shell, cwd = projectRoot). */
368
+ function renderCommandBed({ name, command }, { dir, n, seed, projectRoot }) {
369
+ const { wavFormatError } = require('./projectSounds.cjs');
370
+ const outWav = path.join(dir, `bed-${name}.wav`);
371
+ const lengthS = (n / SR).toFixed(3);
372
+ const subs = { '{name}': name, '{lengthS}': lengthS, '{seed}': String(seed), '{out}': outWav };
373
+ const argv = command.map((a) => {
374
+ let v = a;
375
+ for (const [k, val] of Object.entries(subs)) v = v.split(k).join(val);
376
+ return v;
377
+ });
378
+ const r = spawnSync(argv[0], argv.slice(1), {
379
+ cwd: projectRoot,
380
+ shell: false,
381
+ stdio: ['ignore', 'ignore', 'pipe'],
382
+ timeout: BED_COMMAND_LIMITS.timeoutMs,
383
+ maxBuffer: 16 * 1024 * 1024,
384
+ });
385
+ const stderr = r.stderr ? r.stderr.toString('utf8').trim().slice(-BED_STDERR_TAIL) : '';
386
+ const withStderr = (msg) => (stderr ? `${msg}: ${stderr}` : msg);
387
+ const label = `project bed '${name}' command`;
388
+ if (r.error && r.error.code === 'ETIMEDOUT') throw new Error(withStderr(`${label} killed at its ${BED_COMMAND_LIMITS.timeoutMs / 1000} s limit`));
389
+ if (r.error) throw new Error(withStderr(`${label} failed to run: ${r.error.message}`));
390
+ if (r.status !== 0) {
391
+ const why = r.signal ? `killed by ${r.signal}` : `exit ${r.status}`;
392
+ throw new Error(withStderr(`${label} failed (${why})`));
393
+ }
394
+ if (!fs.existsSync(outWav)) throw new Error(withStderr(`${label} wrote no WAV to ${outWav}`));
395
+ const reason = wavFormatError(fs.readFileSync(outWav), `${label} output (${outWav})`);
396
+ if (reason) throw new Error(reason);
397
+ const s = decodeMono(outWav, dir, 'bed');
398
+ if (s.length < Math.round((n / SR - 0.05) * SR)) {
399
+ throw new Error(`${label} wrote ${(s.length / SR).toFixed(3)} s of audio; the mix needs at least ${(n / SR - 0.05).toFixed(3)} s (${lengthS} s less the 0.05 s tolerance)`);
400
+ }
401
+ if (s.length >= n) return s.subarray(0, n);
402
+ const out = new Float32Array(n);
403
+ out.set(s);
404
+ return out;
405
+ }
406
+
264
407
  /**
265
408
  * Mix narration + ducked music bed + SFX cues, then loudnorm to -14 LUFS / -1.5 dBTP.
266
- * cues: [{name, t}] (t in seconds; `at` also accepted). Output length is the longer of
267
- * lengthS and the narration. Returns the measured {lufs, truePeakDb, speechS}.
409
+ * cues: [{name, t}] (t in seconds; `at` also accepted). A name that is not a built-in
410
+ * effect is read from the persona's sounds.sfx under projectRoot (absolute).
411
+ * bed: absent -> the style's built-in bed; a STYLES key -> that built-in bed; any other
412
+ * name -> the persona's sounds.beds entry (a WAV looped to length, or rendered by its
413
+ * command). Output length is the longer of lengthS and the narration.
414
+ * Returns {lufs, truePeakDb, speechS}.
268
415
  */
269
- function mix({ narrationWav, cues = [], style, lengthS, out, seed = 1 }) {
416
+ function mix({ narrationWav, cues = [], style, bed: bedName, lengthS, out, seed = 1, projectRoot }) {
417
+ if (hasRoot(projectRoot) && (typeof projectRoot !== 'string' || !path.isAbsolute(projectRoot))) {
418
+ throw new Error('spec.projectRoot must be an absolute path');
419
+ }
420
+ const getPersona = personaLoader(projectRoot);
421
+ const cueFiles = resolveCueFiles(cues, projectRoot, getPersona);
422
+ const bedSpec = resolveBed(bedName, style, projectRoot, getPersona);
270
423
  const dir = fs.mkdtempSync(path.join(require('os').tmpdir(), 'dvk-sound-'));
271
424
  try {
272
- const narrF32 = path.join(dir, 'narration.f32.wav');
273
- runFfmpeg(['-hide_banner', '-nostats', '-y', '-i', narrationWav, '-vn', '-ac', '1', '-ar', String(SR), '-c:a', 'pcm_f32le', narrF32]);
274
- const narr = decodeWavF32(fs.readFileSync(narrF32));
425
+ const narr = decodeMono(narrationWav, dir, 'narration');
275
426
  const n = Math.max(narr.length, Math.round(Number(lengthS) * SR));
276
- const bed = bedSamples({ style, lengthS: n / SR, seed });
427
+ let bed;
428
+ if (bedSpec.file) bed = loopFileBed(bedSpec.file, dir, n);
429
+ else if (bedSpec.command) bed = renderCommandBed(bedSpec, { dir, n, seed, projectRoot });
430
+ else bed = bedSamples({ style: bedSpec.style, lengthS: n / SR, seed });
277
431
  // A single NaN in the buffer handed to ffmpeg makes libmp3lame assert (0-byte mp3).
278
432
  for (let i = 0; i < bed.length; i++) if (!Number.isFinite(bed[i])) bed[i] = 0;
433
+ const projectSfx = new Map();
434
+ let k = 0;
435
+ for (const [name, file] of cueFiles) projectSfx.set(name, decodeMono(file, dir, `sfx-${k++}`));
279
436
  const { gain, speechS } = duckEnvelope(narr);
280
437
  const bedGain = dbToGain(BED_BASE_DB);
281
438
  const mixed = new Float32Array(n);
@@ -286,7 +443,7 @@ function mix({ narrationWav, cues = [], style, lengthS, out, seed = 1 }) {
286
443
  const sfxGain = dbToGain(-10);
287
444
  for (const cue of cues) {
288
445
  const at = Math.round(Number(cue.t ?? cue.at ?? 0) * SR);
289
- const s = sfxSamples(cue.name);
446
+ const s = projectSfx.get(cue.name) || sfxSamples(cue.name);
290
447
  for (let i = 0; i < s.length && at + i < n; i++) if (at + i >= 0) mixed[at + i] += s[i] * sfxGain;
291
448
  }
292
449
  const pre = path.join(dir, 'premix.f32.wav');
@@ -299,7 +456,7 @@ function mix({ narrationWav, cues = [], style, lengthS, out, seed = 1 }) {
299
456
  }
300
457
  }
301
458
 
302
- module.exports = { buildMusicBed, buildSfx, mix, measure, parseEbur128, runFfmpeg, decodeWavF32, STYLES, SFX_NAMES, TARGET };
459
+ module.exports = { buildMusicBed, buildSfx, mix, measure, parseEbur128, runFfmpeg, decodeWavF32, STYLES, SFX_NAMES, TARGET, BED_COMMAND_LIMITS };
303
460
 
304
461
  if (require.main === module) {
305
462
  try {