claude-code-session-manager 0.142.0 → 0.144.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 (162) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +22 -107
  3. package/dist/assets/AppSettings-Z68gQiVE.js +2 -0
  4. package/dist/assets/{History-DpZuJXi1.js → History-C3E6y_7t.js} +2 -2
  5. package/dist/assets/HomeClaudeConfig-Yd1vXzBn.js +5 -0
  6. package/dist/assets/{Panel-BjdJjhqt.js → Panel-CnfWs46Z.js} +1 -1
  7. package/dist/assets/ProjectClaudeConfig-CP0Wsg-H.js +26 -0
  8. package/dist/assets/Scheduler-D8un7N3B.js +16 -0
  9. package/dist/assets/{SkillReferenceGraph-Cqyu4mef.js → SkillReferenceGraph-DRtZV1Al.js} +1 -1
  10. package/dist/assets/{Skills-vv0noNVI.js → Skills-Bg5O2Hyn.js} +23 -23
  11. package/dist/assets/{TiptapBody-CXi8Pvut.js → TiptapBody-BdzoBmqu.js} +27 -27
  12. package/dist/assets/{Toggle-CiYCWLjh.js → Toggle-Dt5K1OXt.js} +1 -1
  13. package/dist/assets/{VoiceButton-4NKKd1sC.js → VoiceButton-CTLyRgdF.js} +1 -1
  14. package/dist/assets/{historyTotals-DDunb8Ch.js → historyTotals-B2_KWBga.js} +1 -1
  15. package/dist/assets/{index-Cn5E9958.js → index-446b69rr.js} +715 -714
  16. package/dist/assets/{index-DVHIHoJf.css → index-BJ5TJvmz.css} +1 -1
  17. package/dist/index.html +2 -2
  18. package/dist-web/app.css +1 -1
  19. package/dist-web/app.js +438 -435
  20. package/package.json +6 -4
  21. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  22. package/plugins/session-manager-dev/skills/builder/SKILL.md +5 -0
  23. package/plugins/session-manager-dev/skills/develop/SKILL.md +23 -16
  24. package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +16 -2
  25. package/plugins/session-manager-dev/skills/maintaining-md-network/weekly-consolidation.md +87 -0
  26. package/scripts/README.md +1 -0
  27. package/scripts/scheduler-mcp-server.cjs +381 -6
  28. package/src/main/adminRouteRegistry.cjs +16 -0
  29. package/src/main/agentLibrary.cjs +60 -11
  30. package/src/main/agentsIpc.cjs +19 -0
  31. package/src/main/build-info.json +4 -4
  32. package/src/main/chatRunner.cjs +214 -7
  33. package/src/main/config.cjs +5 -1
  34. package/src/main/health.cjs +92 -14
  35. package/src/main/index.cjs +16 -4
  36. package/src/main/ipcSchemas.cjs +61 -1
  37. package/src/main/lib/claude/agentArmory.cjs +128 -0
  38. package/src/main/lib/claude/agentModelResolve.cjs +3 -2
  39. package/src/main/lib/claude/agentSnapshot.cjs +24 -3
  40. package/src/main/lib/claude/builtinTools.cjs +110 -0
  41. package/src/main/lib/claude/environmentProfiles.cjs +1 -1
  42. package/src/main/lib/claude/headlessMcpServers.cjs +138 -0
  43. package/src/main/lib/claude/jobSandboxPolicy.cjs +8 -2
  44. package/src/main/lib/claude/personaToolScope.cjs +77 -6
  45. package/src/main/lib/demo-video-kit/cast.md +10 -1
  46. package/src/main/lib/demo-video-kit/character.cjs +77 -21
  47. package/src/main/lib/demo-video-kit/kind-tiktok.md +5 -1
  48. package/src/main/lib/demo-video-kit/projectSounds.cjs +191 -0
  49. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  50. package/src/main/lib/demo-video-kit/sound.cjs +166 -9
  51. package/src/main/lib/demo-video-kit/standalone.cjs +231 -0
  52. package/src/main/lib/epic/activeIndexMerge.cjs +5 -0
  53. package/src/main/lib/epic/artifactRetention.cjs +55 -9
  54. package/src/main/lib/epic/artifactStore.cjs +78 -35
  55. package/src/main/lib/epic/delegationReadiness.cjs +10 -3
  56. package/src/main/lib/epic/epicDepsSync.cjs +66 -0
  57. package/src/main/lib/epic/epicEventLog.cjs +45 -1
  58. package/src/main/lib/epic/epicOutsideRead.cjs +38 -1
  59. package/src/main/lib/epic/epicSettle.cjs +48 -4
  60. package/src/main/lib/epic/epicSpawnPlan.cjs +3 -1
  61. package/src/main/lib/epic/epicStateEmitter.cjs +248 -0
  62. package/src/main/lib/epic/epicValidationHook.cjs +22 -3
  63. package/src/main/lib/epic/planReviewInput.cjs +123 -0
  64. package/src/main/lib/epic/restorableSessions.cjs +1 -0
  65. package/src/main/lib/epic/scriptStartedBy.cjs +71 -0
  66. package/src/main/lib/externalContract.cjs +24 -1
  67. package/src/main/lib/feedback-remote/autoStartedSession.cjs +1 -1
  68. package/src/main/lib/feedback-remote/createdProjects.cjs +291 -0
  69. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +24 -2
  70. package/src/main/lib/feedback-remote/crossProjectReply.cjs +96 -8
  71. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +54 -3
  72. package/src/main/lib/feedback-remote/pendingReplies.cjs +22 -0
  73. package/src/main/lib/feedback-remote/projectCreate.cjs +415 -0
  74. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +94 -4
  75. package/src/main/lib/feedback-remote/replyClaims.cjs +168 -0
  76. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +29 -1
  77. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +43 -2
  78. package/src/main/lib/feedback-remote/servicePairLocalRoutes.cjs +91 -0
  79. package/src/main/lib/feedback-remote/servicePairings.cjs +47 -7
  80. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +99 -1
  81. package/src/main/lib/git/gitWorktree.cjs +8 -0
  82. package/src/main/lib/git/runtimeStateUntrack.cjs +15 -1
  83. package/src/main/lib/git/worktreeDeps.cjs +119 -10
  84. package/src/main/lib/mcpToolCatalog.cjs +144 -12
  85. package/src/main/lib/mcpToolsProbe.cjs +19 -2
  86. package/src/main/lib/opsOwnership.cjs +113 -28
  87. package/src/main/lib/packs/packCatalog.cjs +98 -5
  88. package/src/main/lib/persona-macro/agentPersonaSchema.cjs +6 -0
  89. package/src/main/lib/persona-macro/builtinMacros.cjs +6 -4
  90. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +9 -0
  91. package/src/main/lib/persona-macro/personaLoadout.cjs +58 -0
  92. package/src/main/lib/persona-macro/personaMerge.cjs +11 -3
  93. package/src/main/lib/persona-macro/personaUpgrade.cjs +96 -0
  94. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +1 -1
  95. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +140 -0
  96. package/src/main/lib/prd/prdCreate.cjs +395 -229
  97. package/src/main/lib/prd/prdCriteria.cjs +7 -4
  98. package/src/main/lib/prd/prdFrontmatter.cjs +5 -2
  99. package/src/main/lib/prd/prdMcpReachWarnings.cjs +44 -0
  100. package/src/main/lib/prd/prdSandboxWarnings.cjs +49 -0
  101. package/src/main/lib/process/peerChatSession.cjs +165 -0
  102. package/src/main/lib/project-pages/videoPressLines.cjs +145 -0
  103. package/src/main/lib/project-pages/videoScriptPress.cjs +266 -0
  104. package/src/main/lib/project-pages/videoScriptRunRoute.cjs +371 -0
  105. package/src/main/lib/project-pages/videoScriptSwitchIpc.cjs +49 -0
  106. package/src/main/lib/project-pages/videoScriptSwitchRoute.cjs +173 -0
  107. package/src/main/lib/promptSessionSchema.cjs +2 -0
  108. package/src/main/lib/scheduler/baselineGate.cjs +31 -2
  109. package/src/main/lib/scheduler/criteriaChecks.cjs +164 -20
  110. package/src/main/lib/scheduler/heldSchedulerTurns.cjs +238 -0
  111. package/src/main/lib/scheduler/jobMemoryStats.cjs +13 -2
  112. package/src/main/lib/scheduler/planRecordHarvest.cjs +215 -55
  113. package/src/main/lib/scheduler/planReleaseRoute.cjs +110 -0
  114. package/src/main/lib/scheduler/planReviewSchema.cjs +182 -0
  115. package/src/main/lib/scheduler/planReviewStats.cjs +63 -0
  116. package/src/main/lib/scheduler/planReviewStore.cjs +128 -0
  117. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +60 -2
  118. package/src/main/lib/scheduler/queueStore.cjs +16 -0
  119. package/src/main/lib/scheduler/rcaReport.cjs +79 -15
  120. package/src/main/lib/scheduler/sandboxEnvironmentLimit.cjs +141 -0
  121. package/src/main/lib/scheduler/scheduleJobSchema.cjs +15 -0
  122. package/src/main/lib/scheduler/schedulerPaths.cjs +9 -0
  123. package/src/main/lib/scheduler/slotsRoute.cjs +101 -87
  124. package/src/main/lib/scheduler/upgradeDrain.cjs +32 -5
  125. package/src/main/lib/scheduler/usageHoldRoute.cjs +97 -0
  126. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +28 -7
  127. package/src/main/lib/tasks/memoryConsolidation.cjs +123 -39
  128. package/src/main/lib/tasks/mitigationReview.cjs +21 -1
  129. package/src/main/lib/tasks/taskAdminRoutes.cjs +104 -17
  130. package/src/main/lib/tasks/taskLedger.cjs +2 -2
  131. package/src/main/lib/tasks/taskRun.cjs +3 -1
  132. package/src/main/lib/tasks/weeklyConsolidationInputs.cjs +178 -0
  133. package/src/main/lib/telemetry/auditEvents.cjs +21 -24
  134. package/src/main/lib/telemetry/auditLog.cjs +6 -2
  135. package/src/main/lib/util/atomicFs.cjs +2 -2
  136. package/src/main/projectPages.cjs +22 -14
  137. package/src/main/promptSessionEvents.cjs +16 -1
  138. package/src/main/pty.cjs +14 -2
  139. package/src/main/queueOps.cjs +1 -1
  140. package/src/main/runVerify.cjs +4 -3
  141. package/src/main/scheduler/planReviewHold.cjs +140 -0
  142. package/src/main/scheduler/prdParser.cjs +1 -0
  143. package/src/main/scheduler/reviewLadder.cjs +2 -0
  144. package/src/main/scheduler/utilizationHold.cjs +101 -6
  145. package/src/main/scheduler.cjs +1055 -107
  146. package/src/main/seedAgentPersonas.cjs +11 -6
  147. package/src/main/seedStatus.cjs +1 -1
  148. package/src/main/templates/PRD_AUTHORING.md +22 -2
  149. package/src/main/webRemote.cjs +47 -7
  150. package/src/preload/api.d.ts +118 -2
  151. package/src/preload/apiSurface.json +42 -0
  152. package/src/preload/index.cjs +11 -0
  153. package/src/seed/agents/architect.md +28 -43
  154. package/src/seed/agents/demo-video-builder.md +15 -8
  155. package/src/seed/agents/dev-lead.md +3 -1
  156. package/src/seed/agents/md-network-curator.md +27 -0
  157. package/src/seed/agents/plan-reviewer.md +47 -0
  158. package/src/seed/agents/validator.md +21 -19
  159. package/dist/assets/AppSettings-BcZgIvvY.js +0 -2
  160. package/dist/assets/HomeClaudeConfig-D32ZJtU-.js +0 -3
  161. package/dist/assets/ProjectClaudeConfig-BTClYV6i.js +0 -26
  162. package/dist/assets/Scheduler-DPobKx1Z.js +0 -16
@@ -0,0 +1,266 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * videoScriptPress.cjs — the per-project human switch 'Scripts may run Demo
5
+ * Video' and the small ledger of scripted Demo Video presses.
6
+ *
7
+ * Two MACHINE-LEVEL files beside task-switches.json (schedulerPaths):
8
+ * videoScriptSwitchesPath() — keyed by absolute project cwd (path.resolve):
9
+ * { "v": 1, "projects": { "/abs/cwd": { "enabled": true, "changedAt": "ISO", "by": {...} } } }
10
+ * `by` records WHO made the last change: { via: 'ui' } or
11
+ * { via: 'agent', claudeSessionId, quote, promptAt }. An entry without a
12
+ * well-formed `by` reads as { via: 'unknown' }; reads never rewrite the file.
13
+ * videoScriptRunsPath() — the scripted-press ledger, newest last, at most
14
+ * MAX_RUNS_PER_PROJECT runs per project (oldest dropped):
15
+ * { "v": 1, "projects": { "/abs/cwd": [ { entryId, epicId, slug, externalRef?, kind, at } ] } }
16
+ * Both live outside every project ops root, so opsOwnership does not govern
17
+ * them (same reason as tasks/taskSwitch.cjs).
18
+ *
19
+ * EXACTLY TWO WRITERS of the switch: it is a human decision, recorded with who made it.
20
+ * - The UI IPC is a human click: by.via 'ui'.
21
+ * - The agent route POST /admin/project-home/videos/script-switch writes
22
+ * by.via 'agent', and only on a verified human quote.
23
+ * (Both land in later PRDs.) Any other write is outside the law and reads as
24
+ * by.via 'unknown'. The switch is a consent gate, not a sandbox.
25
+ * The ledger's ONLY writer is the scripted-press route
26
+ * POST /admin/project-home/videos/run; it refuses presses while the switch is
27
+ * off and reads the ledger to answer a run's status by entry id.
28
+ *
29
+ * Switching off keeps the entry (enabled:false + changedAt). Switch reads are
30
+ * cached by file mtime; a missing or corrupt file reads as all-off / empty
31
+ * and never throws.
32
+ */
33
+
34
+ const fs = require('node:fs');
35
+ const path = require('node:path');
36
+ const { videoScriptSwitchesPath, videoScriptRunsPath } = require('../scheduler/schedulerPaths.cjs');
37
+ const atomicFs = require('../util/atomicFs.cjs');
38
+
39
+ const VERSION = 1;
40
+ const MAX_RUNS_PER_PROJECT = 200;
41
+
42
+ /** @type {{ file: string, mtimeMs: number, data: Record<string, { enabled: boolean, changedAt: string, by: object | null }> } | null} */
43
+ let cache = null;
44
+
45
+ function normalizeCwd(cwd) {
46
+ if (typeof cwd !== 'string' || cwd.trim() === '') return null;
47
+ return path.resolve(cwd);
48
+ }
49
+
50
+ const BY_ERROR = "setVideoScriptSwitch: by must be {via:'ui'} or {via:'agent', claudeSessionId, quote, promptAt}";
51
+ const UNKNOWN_BY = Object.freeze({ via: 'unknown' });
52
+
53
+ function boundedString(v, max) {
54
+ return typeof v === 'string' && v.length >= 1 && v.length <= max;
55
+ }
56
+
57
+ function isIsoish(v) {
58
+ return typeof v === 'string' && v.trim() !== '' && !Number.isNaN(Date.parse(v));
59
+ }
60
+
61
+ /** Normalized copy of a well-formed attribution, or null (same rules as taskSwitch). */
62
+ function validBy(by) {
63
+ if (!by || typeof by !== 'object' || Array.isArray(by)) return null;
64
+ if (by.via === 'ui') {
65
+ return Object.keys(by).length === 1 ? { via: 'ui' } : null;
66
+ }
67
+ if (by.via === 'agent') {
68
+ const { claudeSessionId, quote, promptAt } = by;
69
+ if (!boundedString(claudeSessionId, 128)) return null;
70
+ if (!boundedString(quote, 2000)) return null;
71
+ if (!isIsoish(promptAt)) return null;
72
+ return { via: 'agent', claudeSessionId, quote, promptAt };
73
+ }
74
+ return null;
75
+ }
76
+
77
+ function projectsOf(parsed) {
78
+ const projects = parsed && typeof parsed === 'object' ? parsed.projects : null;
79
+ if (!projects || typeof projects !== 'object' || Array.isArray(projects)) return null;
80
+ return projects;
81
+ }
82
+
83
+ /* ── switch ─────────────────────────────────────────────────────────────── */
84
+
85
+ function sanitizeSwitches(parsed) {
86
+ const out = {};
87
+ const projects = projectsOf(parsed);
88
+ if (!projects) return out;
89
+ for (const [cwd, entry] of Object.entries(projects)) {
90
+ if (!entry || typeof entry !== 'object') continue;
91
+ out[path.resolve(cwd)] = {
92
+ enabled: entry.enabled === true,
93
+ changedAt: typeof entry.changedAt === 'string' ? entry.changedAt : '',
94
+ by: validBy(entry.by),
95
+ };
96
+ }
97
+ return out;
98
+ }
99
+
100
+ function readSwitches() {
101
+ let file;
102
+ try {
103
+ file = videoScriptSwitchesPath();
104
+ } catch {
105
+ return {};
106
+ }
107
+ let mtimeMs;
108
+ try {
109
+ mtimeMs = fs.statSync(file).mtimeMs;
110
+ } catch {
111
+ cache = null;
112
+ return {};
113
+ }
114
+ if (cache && cache.file === file && cache.mtimeMs === mtimeMs) return cache.data;
115
+ const data = sanitizeSwitches(atomicFs.readJsonOrSync(file, null));
116
+ cache = { file, mtimeMs, data };
117
+ return data;
118
+ }
119
+
120
+ /** True only when `cwd`'s switch is explicitly on. Never throws. */
121
+ function isVideoScriptSwitchOn(cwd) {
122
+ try {
123
+ const key = normalizeCwd(cwd);
124
+ if (!key) return false;
125
+ const entry = readSwitches()[key];
126
+ return !!(entry && entry.enabled);
127
+ } catch {
128
+ return false;
129
+ }
130
+ }
131
+
132
+ /**
133
+ * One of the two sanctioned writers only (see header). Records
134
+ * { enabled, changedAt, by }; switching off keeps the entry. An invalid `by`
135
+ * throws before any fs call.
136
+ */
137
+ function setVideoScriptSwitch(cwd, enabled, by) {
138
+ const attribution = validBy(by);
139
+ if (!attribution) throw new Error(BY_ERROR);
140
+ const key = normalizeCwd(cwd);
141
+ if (!key) throw new Error('setVideoScriptSwitch: cwd must be a non-empty string');
142
+ const projects = { ...readSwitches() };
143
+ projects[key] = { enabled: enabled === true, changedAt: new Date().toISOString(), by: attribution };
144
+ const file = videoScriptSwitchesPath();
145
+ fs.mkdirSync(path.dirname(file), { recursive: true });
146
+ atomicFs.writeJsonAtomicSync(file, { v: VERSION, projects });
147
+ cache = null;
148
+ return { cwd: key, enabled: projects[key].enabled, changedAt: projects[key].changedAt, by: { ...attribution } };
149
+ }
150
+
151
+ /**
152
+ * One project's entry with attribution. changedAt/by null when there is no
153
+ * entry; by { via:'unknown' } for an entry without a well-formed by; null for
154
+ * a non-string or empty cwd. Never throws.
155
+ */
156
+ function getVideoScriptSwitch(cwd) {
157
+ try {
158
+ const key = normalizeCwd(cwd);
159
+ if (!key) return null;
160
+ const entry = readSwitches()[key];
161
+ if (!entry) return { cwd: key, enabled: false, changedAt: null, by: null };
162
+ return { cwd: key, enabled: entry.enabled, changedAt: entry.changedAt, by: entry.by ? { ...entry.by } : { ...UNKNOWN_BY } };
163
+ } catch {
164
+ return null;
165
+ }
166
+ }
167
+
168
+ /* ── ledger ─────────────────────────────────────────────────────────────── */
169
+
170
+ /** Normalized run record, or null when malformed. */
171
+ function validRun(run) {
172
+ if (!run || typeof run !== 'object' || Array.isArray(run)) return null;
173
+ const { entryId, epicId, slug, externalRef, kind, at } = run;
174
+ if (!boundedString(entryId, 200)) return null;
175
+ if (!boundedString(epicId, 200)) return null;
176
+ if (!boundedString(slug, 200)) return null;
177
+ if (!boundedString(kind, 100)) return null;
178
+ if (!isIsoish(at)) return null;
179
+ if (externalRef !== undefined && externalRef !== null && !boundedString(externalRef, 500)) return null;
180
+ const out = { entryId, epicId, slug, kind, at };
181
+ if (typeof externalRef === 'string') out.externalRef = externalRef;
182
+ if (run.caller !== undefined) {
183
+ const { CallerSchema } = require('../epic/scriptStartedBy.cjs');
184
+ const c = CallerSchema.safeParse(run.caller);
185
+ if (c.success) out.caller = c.data;
186
+ }
187
+ if (boundedString(run.fromEpicId, 200)) out.fromEpicId = run.fromEpicId;
188
+ return out;
189
+ }
190
+
191
+ function readRuns() {
192
+ let file;
193
+ try {
194
+ file = videoScriptRunsPath();
195
+ } catch {
196
+ return {};
197
+ }
198
+ const projects = projectsOf(atomicFs.readJsonOrSync(file, null));
199
+ const out = {};
200
+ if (!projects) return out;
201
+ for (const [cwd, list] of Object.entries(projects)) {
202
+ if (!Array.isArray(list)) continue;
203
+ const runs = list.map(validRun).filter(Boolean);
204
+ if (runs.length) out[path.resolve(cwd)] = runs;
205
+ }
206
+ return out;
207
+ }
208
+
209
+ /**
210
+ * The scripted-press route's write (see header). Appends the run (an earlier
211
+ * run with the same entryId is replaced), keeps the newest
212
+ * MAX_RUNS_PER_PROJECT for the project, and returns the stored record.
213
+ * Throws on a malformed cwd or run before any write.
214
+ */
215
+ function recordScriptRun(cwd, run) {
216
+ const key = normalizeCwd(cwd);
217
+ if (!key) throw new Error('recordScriptRun: cwd must be a non-empty string');
218
+ const record = validRun(run);
219
+ if (!record) throw new Error('recordScriptRun: run must be {entryId, epicId, slug, externalRef?, kind, at(ISO)}');
220
+ const projects = readRuns();
221
+ const list = (projects[key] || []).filter((r) => r.entryId !== record.entryId);
222
+ list.push(record);
223
+ projects[key] = list.length > MAX_RUNS_PER_PROJECT ? list.slice(list.length - MAX_RUNS_PER_PROJECT) : list;
224
+ const file = videoScriptRunsPath();
225
+ fs.mkdirSync(path.dirname(file), { recursive: true });
226
+ atomicFs.writeJsonAtomicSync(file, { v: VERSION, projects });
227
+ return { ...record };
228
+ }
229
+
230
+ /**
231
+ * A project's run by entryId (preferred) or by externalRef (newest match), or
232
+ * null. Never throws.
233
+ */
234
+ function findScriptRun(cwd, query) {
235
+ try {
236
+ const key = normalizeCwd(cwd);
237
+ if (!key || !query || typeof query !== 'object') return null;
238
+ const list = readRuns()[key];
239
+ if (!list) return null;
240
+ let hit;
241
+ if (typeof query.entryId === 'string' && query.entryId) {
242
+ hit = list.find((r) => r.entryId === query.entryId);
243
+ } else if (typeof query.externalRef === 'string' && query.externalRef) {
244
+ for (let i = list.length - 1; i >= 0; i--) {
245
+ if (list[i].externalRef === query.externalRef) { hit = list[i]; break; }
246
+ }
247
+ }
248
+ return hit ? { ...hit } : null;
249
+ } catch {
250
+ return null;
251
+ }
252
+ }
253
+
254
+ function _resetForTests() {
255
+ cache = null;
256
+ }
257
+
258
+ module.exports = {
259
+ MAX_RUNS_PER_PROJECT,
260
+ getVideoScriptSwitch,
261
+ setVideoScriptSwitch,
262
+ isVideoScriptSwitchOn,
263
+ recordScriptRun,
264
+ findScriptRun,
265
+ _resetForTests,
266
+ };
@@ -0,0 +1,371 @@
1
+ /**
2
+ * videoScriptRunRoute.cjs — a project's own script presses Demo Video.
3
+ *
4
+ * POST /admin/project-home/videos/run (body ≤ 64 KiB)
5
+ * { cwd, kind, target?, length?, style?, character?, voiceId?, focus?, reviewFirst?, externalRef?,
6
+ * caller?: { pipeline?, runId?, step?, attempt? } }
7
+ * curl -s -X POST "http://127.0.0.1:$(jq -r .port ~/.claude/session-manager/admin-api.json)/admin/project-home/videos/run" -H "Authorization: Bearer $(jq -r .token ~/.claude/session-manager/admin-api.json)" -H 'Content-Type: application/json' -d '{"cwd":"/abs/project","kind":"blog-post","target":"posts/hello.md","externalRef":"post:hello"}'
8
+ *
9
+ * Starts ONE builtin-demo-video job for the cwd through the same renderer
10
+ * press path as POST /admin/macros/run (deps.startExternalNewSession ->
11
+ * launchSession run 'job'), so persona, checks, review stage and the single
12
+ * mint authority are the human press's own. Checks, in order, each refusal
13
+ * launching nothing:
14
+ * 1. 400 — body/cwd (resolveCwd from projectHomeAdminRoutes.cjs), or a caller
15
+ * failing CallerSchema (epic/scriptStartedBy.cjs). caller names the script;
16
+ * every press sends startedBy (+ the resolved calling chat) so the minted
17
+ * Epic's source says a script started it; ledger + audit record the caller;
18
+ * 2. 403 scripts_not_allowed — the project's 'Scripts may run Demo Video'
19
+ * switch is off (videoScriptPress.isVideoScriptSwitchOn);
20
+ * 3. 400 — the press choices (videoPressLines.parseScriptPress), a voiceId
21
+ * not in voiceLibrary.listVoices(cwd), or a bad externalRef;
22
+ * 4. with externalRef: a ledger run with the same cwd + ref answers
23
+ * 200 { ok, existing:true, entryId, epicId } (concurrent identical calls
24
+ * share one launch under withExternalRefLock);
25
+ * 5. 409 already_building — a pending/held/running builtin-demo-video job
26
+ * row for the cwd (deps.listJobRows), or a launch in flight here.
27
+ * Success: 200 { ok, entryId, epicId, slug, stage }, the run recorded with
28
+ * videoScriptPress.recordScriptRun and one 'admin_video_script_run' audit
29
+ * event. A launch failure, or a result without entryId, is 503.
30
+ *
31
+ * GET /admin/project-home/videos/status?cwd=&id=
32
+ *
33
+ * One Demo Video run's outcome by entry id, read-only. id must match
34
+ * STATUS_ID_RE before any fs call; paths are built only under the resolved
35
+ * project's session-manager-operations/project-pages/videos/<id>/. State, in
36
+ * order: outcome.json -> 'season-complete' (reason = its text); index.html +
37
+ * meta.json -> 'saved' (files {index, meta, mp4?, poster?}, absolute, only
38
+ * those that exist); review/material.json -> 'awaiting_review'; else the job
39
+ * row (macroJobStatus.jobStatusesBySlug, slug from the videoScriptPress
40
+ * ledger) -> 'queued' | 'running' | 'failed' (reason = its one-line reason;
41
+ * a completed row with nothing saved is 'failed'). An id with neither a
42
+ * ledger run nor an entry folder is 404 { ok:false, error:'not found' }.
43
+ * Registered by adminRouteRegistry.cjs.
44
+ */
45
+ 'use strict';
46
+
47
+ const { readBody, sendJson } = require('../feedback-remote/localAdminHttp.cjs');
48
+ const { normalizeExternalRef } = require('../epic/externalRef.cjs');
49
+ const { parseScriptPress, pressLines } = require('./videoPressLines.cjs');
50
+ const { CallerSchema } = require('../epic/scriptStartedBy.cjs');
51
+
52
+ const fs = require('node:fs');
53
+ const path = require('node:path');
54
+ const ROUTE_PATH = '/admin/project-home/videos/run';
55
+ const STATUS_ROUTE_PATH = '/admin/project-home/videos/status';
56
+ const STATUS_ID_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
57
+ const MAX_RUN_BODY_BYTES = 64 * 1024;
58
+ const MACRO_ID = 'builtin-demo-video';
59
+ const ACTIVE = new Set(['pending', 'held', 'running']);
60
+ const PRESS_KEYS = ['kind', 'target', 'length', 'style', 'character', 'voiceId', 'focus', 'reviewFirst'];
61
+ const ALLOWED_KEYS = new Set(['cwd', 'externalRef', 'caller', ...PRESS_KEYS]);
62
+ const SWITCH_REASON = "the 'Scripts may run Demo Video' switch is off for this project; a human turns it on in Project Home > Video";
63
+
64
+ /** cwd -> launch promise; one scripted launch per project at a time. */
65
+ const inFlight = new Map();
66
+
67
+ function oneLine(s) {
68
+ return String(s).replace(/[\r\n]+/g, ' ').slice(0, 300);
69
+ }
70
+
71
+ function launchError(result) {
72
+ if (result && result.ok && !result.entryId) return 'the session started but did not report a Demo Video entry id';
73
+ return oneLine(result?.reason === 'timeout'
74
+ ? 'timed out waiting for the window; the job may still start, check Project Home > Video before retrying'
75
+ : result?.error || 'launch failed');
76
+ }
77
+
78
+ /**
79
+ * @param {{ registerRoute: Function }} adminHttp
80
+ * @param {{ startExternalNewSession?: (p: object) => Promise<any>, isTabBusy?: (id: string) => boolean,
81
+ * listJobRows?: () => Promise<any[]>, resolveCwd?: (c: unknown) => any, videoScriptPress?: any,
82
+ * listVoices?: (cwd: string) => { voices: Array<{ id: string }> }, builtinMacros?: any[],
83
+ * appendAuditEvent?: Function, withExternalRefLock?: Function, now?: () => number,
84
+ * readHistoryTail?: (cwd: string) => Promise<string>, startedByFromRequest?: Function }} [deps]
85
+ */
86
+ function registerAdminRoute(adminHttp, deps = {}) {
87
+ const resolveCwd = deps.resolveCwd
88
+ || ((/** @type {any} */ c) => require('../feedback-remote/projectHomeAdminRoutes.cjs').resolveCwd(c));
89
+ const store = () => deps.videoScriptPress || require('./videoScriptPress.cjs');
90
+ const listVoices = deps.listVoices
91
+ || ((/** @type {string} */ c) => require('../demo-video-kit/voiceLibrary.cjs').listVoices(c));
92
+ const builtins = () => deps.builtinMacros || require('../persona-macro/builtinMacros.cjs').BUILTIN_MACROS;
93
+ const audit = deps.appendAuditEvent
94
+ || ((/** @type {string} */ k, /** @type {any} */ f) => require('../telemetry/auditLog.cjs').appendAuditEvent(k, f));
95
+ const withLock = deps.withExternalRefLock
96
+ || ((/** @type {any} */ k, /** @type {any} */ fn) => require('../epic/externalRefIndex.cjs').withExternalRefLock(k, fn));
97
+ const isTabBusy = deps.isTabBusy || (() => false);
98
+ const listJobRows = deps.listJobRows || (async () => []);
99
+ const now = deps.now || Date.now;
100
+
101
+ adminHttp.registerRoute('POST', ROUTE_PATH, async (/** @type {any} */ req, /** @type {any} */ res) => {
102
+ const bad = (/** @type {string} */ error) => sendJson(res, 400, { ok: false, error: oneLine(error) });
103
+
104
+ let raw;
105
+ try {
106
+ raw = await readBody(req, MAX_RUN_BODY_BYTES);
107
+ } catch (e) {
108
+ bad(`request body rejected: ${e instanceof Error ? e.message : String(e)}`);
109
+ return;
110
+ }
111
+ let body;
112
+ try { body = JSON.parse(raw || '{}'); } catch {
113
+ bad('body is not valid JSON');
114
+ return;
115
+ }
116
+ if (!body || typeof body !== 'object' || Array.isArray(body)) return bad('body must be a JSON object');
117
+ const unknown = Object.keys(body).find((k) => !ALLOWED_KEYS.has(k));
118
+ if (unknown) return bad(`unknown field: ${unknown}`);
119
+
120
+ let caller;
121
+ if (body.caller !== undefined) {
122
+ const c = CallerSchema.safeParse(body.caller);
123
+ if (!c.success) return bad(`invalid caller: ${c.error.issues.map((i) => `${i.path.join('.') || 'caller'} ${i.message}`).join('; ')}`);
124
+ caller = c.data;
125
+ }
126
+
127
+ const resolved = resolveCwd(body.cwd);
128
+ if (!resolved || !resolved.ok) {
129
+ sendJson(res, resolved?.status || 400, { ok: false, error: oneLine(resolved?.error || 'cwd rejected') });
130
+ return;
131
+ }
132
+ const cwd = resolved.cwd;
133
+
134
+ if (!store().isVideoScriptSwitchOn(cwd)) {
135
+ sendJson(res, 403, { ok: false, error: 'scripts_not_allowed', reason: SWITCH_REASON });
136
+ return;
137
+ }
138
+
139
+ /** @type {Record<string, unknown>} */
140
+ const pressBody = {};
141
+ for (const k of PRESS_KEYS) if (body[k] !== undefined) pressBody[k] = body[k];
142
+ const parsed = parseScriptPress(pressBody);
143
+ if (!parsed.ok) return bad(parsed.error);
144
+ const cfg = parsed.cfg;
145
+
146
+ if (cfg.voice) {
147
+ let ids;
148
+ try {
149
+ const lib = listVoices(cwd);
150
+ ids = new Set(((lib && lib.voices) || []).map((v) => v && v.id));
151
+ } catch (e) {
152
+ return bad(`could not read the voice library: ${e instanceof Error ? e.message : String(e)}`);
153
+ }
154
+ if (!ids.has(cfg.voice)) return bad(`unknown voice '${cfg.voice}': not in this project's voice library (GET /admin/voices)`);
155
+ }
156
+
157
+ const ref = normalizeExternalRef(body.externalRef);
158
+ if (!ref.ok) return bad(ref.error);
159
+ const externalRef = ref.value;
160
+
161
+ const macro = builtins().find((/** @type {any} */ m) => m && m.id === MACRO_ID);
162
+ if (!macro) {
163
+ sendJson(res, 503, { ok: false, error: `${MACRO_ID} is not a built-in macro in this build` });
164
+ return;
165
+ }
166
+
167
+ const press = async () => {
168
+ if (externalRef !== undefined) {
169
+ const found = store().findScriptRun(cwd, { externalRef });
170
+ if (found) {
171
+ sendJson(res, 200, {
172
+ ok: true, existing: true, entryId: found.entryId, epicId: found.epicId,
173
+ slug: found.slug, alreadyRunning: !!isTabBusy(found.epicId), externalRef,
174
+ });
175
+ return;
176
+ }
177
+ }
178
+ if (inFlight.has(cwd)) {
179
+ sendJson(res, 409, { ok: false, error: 'already_building', activeSlug: null });
180
+ return;
181
+ }
182
+ let rows;
183
+ try {
184
+ rows = (await listJobRows()) || [];
185
+ } catch (e) {
186
+ sendJson(res, 503, { ok: false, error: oneLine(`could not read the job queue: ${e instanceof Error ? e.message : String(e)}`) });
187
+ return;
188
+ }
189
+ const active = rows.find((/** @type {any} */ r) => r && r.macroId === MACRO_ID && (!r.cwd || r.cwd === cwd) && ACTIVE.has(r.status));
190
+ if (active) {
191
+ sendJson(res, 409, { ok: false, error: 'already_building', activeSlug: active.slug ?? null });
192
+ return;
193
+ }
194
+
195
+ const startedByFn = deps.startedByFromRequest
196
+ || ((/** @type {any} */ a, /** @type {any} */ d) => require('../epic/scriptStartedBy.cjs').startedByFromRequest(a, d));
197
+ const startedBy = await startedByFn({ route: ROUTE_PATH, caller, socket: req.socket }, deps);
198
+ const payload = {
199
+ cwd,
200
+ agentName: macro.agentName,
201
+ tag: macro.tag,
202
+ title: macro.label,
203
+ prompt: `${macro.prompt}\n\nAdditional instructions: ${pressLines(cfg).join('\n')}`,
204
+ macroId: MACRO_ID,
205
+ via: 'script',
206
+ startedBy,
207
+ ...(cfg.review ? { reviewStage: true } : {}),
208
+ ...(externalRef !== undefined ? { externalRef } : {}),
209
+ };
210
+ const launch = (async () => {
211
+ try {
212
+ return await deps.startExternalNewSession?.(payload);
213
+ } catch (e) {
214
+ return { ok: false, reason: 'launch-failed', error: e instanceof Error ? e.message : 'launch failed' };
215
+ }
216
+ })();
217
+ inFlight.set(cwd, launch);
218
+ let result;
219
+ try {
220
+ result = await launch;
221
+ } finally {
222
+ inFlight.delete(cwd);
223
+ }
224
+ if (!result || !result.ok || typeof result.entryId !== 'string' || !result.entryId || !result.epicId) {
225
+ sendJson(res, 503, { ok: false, error: launchError(result) });
226
+ return;
227
+ }
228
+ const slug = typeof result.slug === 'string' && result.slug ? result.slug : null;
229
+ const stage = result.stage ?? null;
230
+ let recorded = true;
231
+ try {
232
+ store().recordScriptRun(cwd, {
233
+ entryId: result.entryId,
234
+ epicId: result.epicId,
235
+ slug: slug || result.entryId,
236
+ kind: cfg.kind,
237
+ at: new Date(now()).toISOString(),
238
+ ...(externalRef !== undefined ? { externalRef } : {}),
239
+ ...(caller ? { caller } : {}),
240
+ ...(startedBy.fromEpicId ? { fromEpicId: startedBy.fromEpicId } : {}),
241
+ });
242
+ } catch (e) {
243
+ recorded = false;
244
+ console.warn('[videoScriptRunRoute] could not record the scripted run:', e instanceof Error ? e.message : e);
245
+ }
246
+ try {
247
+ audit('admin_video_script_run', {
248
+ route: ROUTE_PATH, cwd, macroId: MACRO_ID, kind: cfg.kind,
249
+ entryId: result.entryId, epicId: result.epicId, slug, stage,
250
+ ...(externalRef !== undefined ? { externalRef } : {}),
251
+ ...(caller ? { caller } : {}),
252
+ ...(startedBy.fromEpicId ? { fromEpicId: startedBy.fromEpicId } : {}),
253
+ });
254
+ } catch { /* audit is best-effort */ }
255
+ sendJson(res, 200, {
256
+ ok: true, entryId: result.entryId, epicId: result.epicId, slug, stage,
257
+ ...(recorded ? {} : { runRecorded: false }),
258
+ });
259
+ };
260
+
261
+ if (externalRef !== undefined) await withLock({ cwd, externalRef }, press);
262
+ else await press();
263
+ });
264
+
265
+ adminHttp.registerRoute('GET', STATUS_ROUTE_PATH, async (/** @type {any} */ _req, /** @type {any} */ res, /** @type {any} */ query) => {
266
+ const q = query instanceof URLSearchParams ? query : new URLSearchParams();
267
+ const id = q.get('id') || '';
268
+ if (!STATUS_ID_RE.test(id)) {
269
+ sendJson(res, 400, { ok: false, error: 'id must match /^[a-z0-9][a-z0-9-]{0,63}$/' });
270
+ return;
271
+ }
272
+ const resolved = resolveCwd(q.get('cwd'));
273
+ if (!resolved || !resolved.ok) {
274
+ sendJson(res, resolved?.status || 400, { ok: false, error: oneLine(resolved?.error || 'cwd rejected') });
275
+ return;
276
+ }
277
+ const cwd = resolved.cwd;
278
+ let status;
279
+ try {
280
+ status = await readRunStatus(cwd, id, {
281
+ findScriptRun: (/** @type {string} */ c, /** @type {any} */ qq) => store().findScriptRun(c, qq),
282
+ listJobRows,
283
+ readHistoryTail: deps.readHistoryTail,
284
+ });
285
+ } catch (e) {
286
+ sendJson(res, 503, { ok: false, error: oneLine(`could not read the run: ${e instanceof Error ? e.message : String(e)}`) });
287
+ return;
288
+ }
289
+ if (!status) {
290
+ sendJson(res, 404, { ok: false, error: 'not found' });
291
+ return;
292
+ }
293
+ sendJson(res, 200, { ok: true, ...status });
294
+ });
295
+ }
296
+
297
+ /** @param {string} p */
298
+ function isFile(p) {
299
+ try { return fs.statSync(p).isFile(); } catch { return false; }
300
+ }
301
+
302
+ /** @param {string} p */
303
+ function isDir(p) {
304
+ try { return fs.statSync(p).isDirectory(); } catch { return false; }
305
+ }
306
+
307
+ /** outcome.json's text, or null when absent/invalid. @param {string} file @param {string} id */
308
+ function outcomeText(file, id) {
309
+ let rec;
310
+ try { rec = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return null; }
311
+ if (!rec || typeof rec !== 'object' || Array.isArray(rec)) return null;
312
+ if (rec.id !== undefined && rec.id !== id) return null;
313
+ if (rec.outcome !== 'season-complete' || typeof rec.text !== 'string' || !rec.text.trim()) return null;
314
+ return oneLine(rec.text.trim());
315
+ }
316
+
317
+ /**
318
+ * One run's status, or null when the id has no ledger run and no entry folder.
319
+ * Read-only. `id` must already match STATUS_ID_RE.
320
+ * @param {string} cwd
321
+ * @param {string} id
322
+ * @param {{ findScriptRun: (cwd: string, q: object) => any, listJobRows: () => Promise<any[]>,
323
+ * readHistoryTail?: (cwd: string) => Promise<string> }} io
324
+ */
325
+ async function readRunStatus(cwd, id, io) {
326
+ if (!STATUS_ID_RE.test(id)) throw new Error('bad entry id');
327
+ const { opsPath } = require('../opsOwnership.cjs');
328
+ const dir = opsPath(cwd, 'project-pages', 'videos', id);
329
+ const run = io.findScriptRun(cwd, { entryId: id });
330
+ const hasDir = isDir(dir);
331
+ if (!run && !hasDir) return null;
332
+ const slug = run && typeof run.slug === 'string' && run.slug ? run.slug : null;
333
+ const base = { entryId: id, epicId: (run && run.epicId) || null, slug };
334
+
335
+ const outcome = path.join(dir, 'outcome.json');
336
+ if (isFile(outcome)) {
337
+ const text = outcomeText(outcome, id);
338
+ if (text) return { ...base, state: 'season-complete', reason: text, files: null };
339
+ }
340
+
341
+ const index = path.join(dir, 'index.html');
342
+ const meta = path.join(dir, 'meta.json');
343
+ if (isFile(index) && isFile(meta)) {
344
+ /** @type {Record<string, string>} */
345
+ const files = { index, meta };
346
+ const mp4 = path.join(dir, 'video.mp4');
347
+ const poster = path.join(dir, 'poster.png');
348
+ if (isFile(mp4)) files.mp4 = mp4;
349
+ if (isFile(poster)) files.poster = poster;
350
+ return { ...base, state: 'saved', reason: null, files };
351
+ }
352
+
353
+ if (isFile(path.join(dir, 'review', 'material.json'))) {
354
+ return { ...base, state: 'awaiting_review', reason: null, files: null };
355
+ }
356
+
357
+ if (!slug) return { ...base, state: 'queued', reason: 'no job row for this entry (not a scripted run)', files: null };
358
+ const { jobStatusesBySlug } = require('../persona-macro/macroJobStatus.cjs');
359
+ const byslug = await jobStatusesBySlug({ cwd, slugs: [slug] }, {
360
+ loadJobs: io.listJobRows,
361
+ ...(io.readHistoryTail ? { readHistoryTail: io.readHistoryTail } : {}),
362
+ });
363
+ const row = byslug[slug];
364
+ if (!row) return { ...base, state: 'queued', reason: null, files: null };
365
+ if (row.state === 'running') return { ...base, state: 'running', reason: null, files: null };
366
+ if (row.state === 'failed') return { ...base, state: 'failed', reason: row.reason || `Ended as ${row.status}`, files: null };
367
+ if (row.state === 'done') return { ...base, state: 'failed', reason: 'The job completed without saving the video', files: null };
368
+ return { ...base, state: 'queued', reason: null, files: null };
369
+ }
370
+
371
+ module.exports = { registerAdminRoute, readRunStatus, ROUTE_PATH, STATUS_ROUTE_PATH, STATUS_ID_RE, MAX_RUN_BODY_BYTES };
@@ -0,0 +1,49 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * videoScriptSwitchIpc.cjs — IPC handlers over the per-project human switch
5
+ * 'Scripts may run Demo Video' (videoScriptPress.cjs), shown and changed in
6
+ * Project Home ▸ Video.
7
+ *
8
+ * videos:script-switch-get { cwd } → { enabled, changedAt, by }
9
+ * videos:script-switch-set { cwd, enabled } → { enabled, changedAt, by }
10
+ *
11
+ * script-switch-set is the human-click writer of setVideoScriptSwitch and
12
+ * records by { via: 'ui' } (the other sanctioned writer is the agent route —
13
+ * see videoScriptPress.cjs), then appends one 'video_script_switch_changed'
14
+ * audit event. Payloads are validated by strict zod schemas (ipcSchemas.cjs)
15
+ * and cwd goes through validatePath; an invalid payload rejects the invoke.
16
+ * Renderer IPC only — mirrors tasks:get-switch / tasks:set-switch (taskIpc.cjs).
17
+ *
18
+ * deps: { schemas, validatePath } plus optional videoScriptPress /
19
+ * appendAuditEvent overrides for tests.
20
+ */
21
+
22
+ const CHANNELS = Object.freeze(['videos:script-switch-get', 'videos:script-switch-set']);
23
+
24
+ function defaultAppendAuditEvent() {
25
+ return require('../telemetry/auditLog.cjs').appendAuditEvent;
26
+ }
27
+
28
+ function registerVideoScriptSwitchIpc(ipcMain, deps = {}) {
29
+ const press = () => deps.videoScriptPress || require('./videoScriptPress.cjs');
30
+
31
+ ipcMain.handle('videos:script-switch-get', async (_event, rawPayload) => {
32
+ const payload = deps.schemas.videosScriptSwitchGet.parse(rawPayload);
33
+ const cwd = deps.validatePath(payload.cwd);
34
+ const entry = press().getVideoScriptSwitch(cwd);
35
+ if (!entry) throw new Error('videos:script-switch-get: invalid cwd');
36
+ return { enabled: entry.enabled, changedAt: entry.changedAt, by: entry.by };
37
+ });
38
+
39
+ ipcMain.handle('videos:script-switch-set', async (_event, rawPayload) => {
40
+ const payload = deps.schemas.videosScriptSwitchSet.parse(rawPayload);
41
+ const cwd = deps.validatePath(payload.cwd);
42
+ const saved = press().setVideoScriptSwitch(cwd, payload.enabled, { via: 'ui' });
43
+ const append = deps.appendAuditEvent || defaultAppendAuditEvent();
44
+ append('video_script_switch_changed', { cwd: saved.cwd, enabled: saved.enabled, via: 'ui' });
45
+ return { enabled: saved.enabled, changedAt: saved.changedAt, by: saved.by };
46
+ });
47
+ }
48
+
49
+ module.exports = { registerVideoScriptSwitchIpc, CHANNELS };