claude-code-session-manager 0.142.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 (95) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +20 -107
  3. package/dist/assets/{AppSettings-BcZgIvvY.js → AppSettings-BO4jDVGO.js} +1 -1
  4. package/dist/assets/{History-DpZuJXi1.js → History-DTttbvPb.js} +1 -1
  5. package/dist/assets/{HomeClaudeConfig-D32ZJtU-.js → HomeClaudeConfig-DADP5bfn.js} +2 -2
  6. package/dist/assets/{Panel-BjdJjhqt.js → Panel-B_D4Bg7L.js} +1 -1
  7. package/dist/assets/{ProjectClaudeConfig-BTClYV6i.js → ProjectClaudeConfig-DPnDJKcr.js} +1 -1
  8. package/dist/assets/{Scheduler-DPobKx1Z.js → Scheduler-CNLjn90m.js} +8 -8
  9. package/dist/assets/{SkillReferenceGraph-Cqyu4mef.js → SkillReferenceGraph-D1b2aiol.js} +1 -1
  10. package/dist/assets/{Skills-vv0noNVI.js → Skills-cfV7sgk6.js} +1 -1
  11. package/dist/assets/{TiptapBody-CXi8Pvut.js → TiptapBody-DVXtEIVy.js} +1 -1
  12. package/dist/assets/{Toggle-CiYCWLjh.js → Toggle-CYajnSdx.js} +1 -1
  13. package/dist/assets/{VoiceButton-4NKKd1sC.js → VoiceButton-DJ4gGRuE.js} +1 -1
  14. package/dist/assets/{historyTotals-DDunb8Ch.js → historyTotals-D3MoHY2U.js} +1 -1
  15. package/dist/assets/{index-Cn5E9958.js → index-CdTppjKR.js} +436 -436
  16. package/dist/index.html +1 -1
  17. package/dist-web/app.js +356 -356
  18. package/package.json +3 -3
  19. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  20. package/plugins/session-manager-dev/skills/builder/SKILL.md +5 -0
  21. package/plugins/session-manager-dev/skills/develop/SKILL.md +9 -3
  22. package/scripts/README.md +1 -0
  23. package/scripts/scheduler-mcp-server.cjs +304 -6
  24. package/src/main/adminRouteRegistry.cjs +10 -0
  25. package/src/main/build-info.json +4 -4
  26. package/src/main/chatRunner.cjs +105 -7
  27. package/src/main/config.cjs +5 -1
  28. package/src/main/health.cjs +38 -2
  29. package/src/main/index.cjs +12 -4
  30. package/src/main/ipcSchemas.cjs +11 -0
  31. package/src/main/lib/demo-video-kit/cast.md +10 -1
  32. package/src/main/lib/demo-video-kit/character.cjs +77 -21
  33. package/src/main/lib/demo-video-kit/kind-tiktok.md +5 -1
  34. package/src/main/lib/demo-video-kit/projectSounds.cjs +191 -0
  35. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  36. package/src/main/lib/demo-video-kit/sound.cjs +166 -9
  37. package/src/main/lib/demo-video-kit/standalone.cjs +231 -0
  38. package/src/main/lib/epic/activeIndexMerge.cjs +5 -0
  39. package/src/main/lib/epic/artifactRetention.cjs +55 -9
  40. package/src/main/lib/epic/artifactStore.cjs +78 -35
  41. package/src/main/lib/epic/delegationReadiness.cjs +10 -3
  42. package/src/main/lib/epic/epicEventLog.cjs +45 -1
  43. package/src/main/lib/epic/epicStateEmitter.cjs +248 -0
  44. package/src/main/lib/epic/epicValidationHook.cjs +13 -2
  45. package/src/main/lib/externalContract.cjs +12 -1
  46. package/src/main/lib/feedback-remote/autoStartedSession.cjs +1 -1
  47. package/src/main/lib/feedback-remote/crossProjectReply.cjs +96 -8
  48. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +30 -0
  49. package/src/main/lib/feedback-remote/pendingReplies.cjs +18 -0
  50. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +94 -4
  51. package/src/main/lib/feedback-remote/replyClaims.cjs +159 -0
  52. package/src/main/lib/git/gitWorktree.cjs +8 -0
  53. package/src/main/lib/git/runtimeStateUntrack.cjs +15 -1
  54. package/src/main/lib/git/worktreeDeps.cjs +113 -10
  55. package/src/main/lib/mcpToolCatalog.cjs +102 -8
  56. package/src/main/lib/opsOwnership.cjs +113 -28
  57. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +46 -0
  58. package/src/main/lib/prd/prdCreate.cjs +350 -227
  59. package/src/main/lib/prd/prdCriteria.cjs +7 -4
  60. package/src/main/lib/project-pages/videoPressLines.cjs +145 -0
  61. package/src/main/lib/project-pages/videoScriptPress.cjs +260 -0
  62. package/src/main/lib/project-pages/videoScriptRunRoute.cjs +351 -0
  63. package/src/main/lib/project-pages/videoScriptSwitchIpc.cjs +49 -0
  64. package/src/main/lib/project-pages/videoScriptSwitchRoute.cjs +173 -0
  65. package/src/main/lib/scheduler/criteriaChecks.cjs +164 -20
  66. package/src/main/lib/scheduler/heldSchedulerTurns.cjs +238 -0
  67. package/src/main/lib/scheduler/jobMemoryStats.cjs +13 -2
  68. package/src/main/lib/scheduler/planRecordHarvest.cjs +120 -52
  69. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +60 -2
  70. package/src/main/lib/scheduler/queueStore.cjs +16 -0
  71. package/src/main/lib/scheduler/rcaReport.cjs +79 -15
  72. package/src/main/lib/scheduler/scheduleJobSchema.cjs +13 -0
  73. package/src/main/lib/scheduler/schedulerPaths.cjs +9 -0
  74. package/src/main/lib/scheduler/slotsRoute.cjs +101 -87
  75. package/src/main/lib/scheduler/usageHoldRoute.cjs +97 -0
  76. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +16 -5
  77. package/src/main/lib/tasks/memoryConsolidation.cjs +14 -2
  78. package/src/main/lib/tasks/mitigationReview.cjs +21 -1
  79. package/src/main/lib/tasks/taskAdminRoutes.cjs +78 -3
  80. package/src/main/lib/tasks/taskLedger.cjs +2 -2
  81. package/src/main/lib/telemetry/auditEvents.cjs +21 -24
  82. package/src/main/lib/telemetry/auditLog.cjs +6 -2
  83. package/src/main/lib/util/atomicFs.cjs +2 -2
  84. package/src/main/promptSessionEvents.cjs +16 -1
  85. package/src/main/pty.cjs +11 -2
  86. package/src/main/queueOps.cjs +1 -1
  87. package/src/main/runVerify.cjs +1 -1
  88. package/src/main/scheduler/utilizationHold.cjs +96 -6
  89. package/src/main/scheduler.cjs +533 -39
  90. package/src/main/templates/PRD_AUTHORING.md +7 -2
  91. package/src/preload/api.d.ts +47 -1
  92. package/src/preload/apiSurface.json +14 -0
  93. package/src/preload/index.cjs +2 -0
  94. package/src/seed/agents/demo-video-builder.md +15 -8
  95. package/src/seed/agents/validator.md +20 -19
@@ -0,0 +1,351 @@
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
+ * 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"}'
7
+ *
8
+ * Starts ONE builtin-demo-video job for the cwd through the same renderer
9
+ * press path as POST /admin/macros/run (deps.startExternalNewSession ->
10
+ * launchSession run 'job'), so persona, checks, review stage and the single
11
+ * mint authority are the human press's own. Checks, in order, each refusal
12
+ * launching nothing:
13
+ * 1. 400 — body/cwd (resolveCwd from projectHomeAdminRoutes.cjs);
14
+ * 2. 403 scripts_not_allowed — the project's 'Scripts may run Demo Video'
15
+ * switch is off (videoScriptPress.isVideoScriptSwitchOn);
16
+ * 3. 400 — the press choices (videoPressLines.parseScriptPress), a voiceId
17
+ * not in voiceLibrary.listVoices(cwd), or a bad externalRef;
18
+ * 4. with externalRef: a ledger run with the same cwd + ref answers
19
+ * 200 { ok, existing:true, entryId, epicId } (concurrent identical calls
20
+ * share one launch under withExternalRefLock);
21
+ * 5. 409 already_building — a pending/held/running builtin-demo-video job
22
+ * row for the cwd (deps.listJobRows), or a launch in flight here.
23
+ * Success: 200 { ok, entryId, epicId, slug, stage }, the run recorded with
24
+ * videoScriptPress.recordScriptRun and one 'admin_video_script_run' audit
25
+ * event. A launch failure, or a result without entryId, is 503.
26
+ *
27
+ * GET /admin/project-home/videos/status?cwd=&id=
28
+ *
29
+ * One Demo Video run's outcome by entry id, read-only. id must match
30
+ * STATUS_ID_RE before any fs call; paths are built only under the resolved
31
+ * project's session-manager-operations/project-pages/videos/<id>/. State, in
32
+ * order: outcome.json -> 'season-complete' (reason = its text); index.html +
33
+ * meta.json -> 'saved' (files {index, meta, mp4?, poster?}, absolute, only
34
+ * those that exist); review/material.json -> 'awaiting_review'; else the job
35
+ * row (macroJobStatus.jobStatusesBySlug, slug from the videoScriptPress
36
+ * ledger) -> 'queued' | 'running' | 'failed' (reason = its one-line reason;
37
+ * a completed row with nothing saved is 'failed'). An id with neither a
38
+ * ledger run nor an entry folder is 404 { ok:false, error:'not found' }.
39
+ * Registered by adminRouteRegistry.cjs.
40
+ */
41
+ 'use strict';
42
+
43
+ const { readBody, sendJson } = require('../feedback-remote/localAdminHttp.cjs');
44
+ const { normalizeExternalRef } = require('../epic/externalRef.cjs');
45
+ const { parseScriptPress, pressLines } = require('./videoPressLines.cjs');
46
+
47
+ const fs = require('node:fs');
48
+ const path = require('node:path');
49
+ const ROUTE_PATH = '/admin/project-home/videos/run';
50
+ const STATUS_ROUTE_PATH = '/admin/project-home/videos/status';
51
+ const STATUS_ID_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
52
+ const MAX_RUN_BODY_BYTES = 64 * 1024;
53
+ const MACRO_ID = 'builtin-demo-video';
54
+ const ACTIVE = new Set(['pending', 'held', 'running']);
55
+ const PRESS_KEYS = ['kind', 'target', 'length', 'style', 'character', 'voiceId', 'focus', 'reviewFirst'];
56
+ const ALLOWED_KEYS = new Set(['cwd', 'externalRef', ...PRESS_KEYS]);
57
+ const SWITCH_REASON = "the 'Scripts may run Demo Video' switch is off for this project; a human turns it on in Project Home > Video";
58
+
59
+ /** cwd -> launch promise; one scripted launch per project at a time. */
60
+ const inFlight = new Map();
61
+
62
+ function oneLine(s) {
63
+ return String(s).replace(/[\r\n]+/g, ' ').slice(0, 300);
64
+ }
65
+
66
+ function launchError(result) {
67
+ if (result && result.ok && !result.entryId) return 'the session started but did not report a Demo Video entry id';
68
+ return oneLine(result?.reason === 'timeout'
69
+ ? 'timed out waiting for the window; the job may still start, check Project Home > Video before retrying'
70
+ : result?.error || 'launch failed');
71
+ }
72
+
73
+ /**
74
+ * @param {{ registerRoute: Function }} adminHttp
75
+ * @param {{ startExternalNewSession?: (p: object) => Promise<any>, isTabBusy?: (id: string) => boolean,
76
+ * listJobRows?: () => Promise<any[]>, resolveCwd?: (c: unknown) => any, videoScriptPress?: any,
77
+ * listVoices?: (cwd: string) => { voices: Array<{ id: string }> }, builtinMacros?: any[],
78
+ * appendAuditEvent?: Function, withExternalRefLock?: Function, now?: () => number,
79
+ * readHistoryTail?: (cwd: string) => Promise<string> }} [deps]
80
+ */
81
+ function registerAdminRoute(adminHttp, deps = {}) {
82
+ const resolveCwd = deps.resolveCwd
83
+ || ((/** @type {any} */ c) => require('../feedback-remote/projectHomeAdminRoutes.cjs').resolveCwd(c));
84
+ const store = () => deps.videoScriptPress || require('./videoScriptPress.cjs');
85
+ const listVoices = deps.listVoices
86
+ || ((/** @type {string} */ c) => require('../demo-video-kit/voiceLibrary.cjs').listVoices(c));
87
+ const builtins = () => deps.builtinMacros || require('../persona-macro/builtinMacros.cjs').BUILTIN_MACROS;
88
+ const audit = deps.appendAuditEvent
89
+ || ((/** @type {string} */ k, /** @type {any} */ f) => require('../telemetry/auditLog.cjs').appendAuditEvent(k, f));
90
+ const withLock = deps.withExternalRefLock
91
+ || ((/** @type {any} */ k, /** @type {any} */ fn) => require('../epic/externalRefIndex.cjs').withExternalRefLock(k, fn));
92
+ const isTabBusy = deps.isTabBusy || (() => false);
93
+ const listJobRows = deps.listJobRows || (async () => []);
94
+ const now = deps.now || Date.now;
95
+
96
+ adminHttp.registerRoute('POST', ROUTE_PATH, async (/** @type {any} */ req, /** @type {any} */ res) => {
97
+ const bad = (/** @type {string} */ error) => sendJson(res, 400, { ok: false, error: oneLine(error) });
98
+
99
+ let raw;
100
+ try {
101
+ raw = await readBody(req, MAX_RUN_BODY_BYTES);
102
+ } catch (e) {
103
+ bad(`request body rejected: ${e instanceof Error ? e.message : String(e)}`);
104
+ return;
105
+ }
106
+ let body;
107
+ try { body = JSON.parse(raw || '{}'); } catch {
108
+ bad('body is not valid JSON');
109
+ return;
110
+ }
111
+ if (!body || typeof body !== 'object' || Array.isArray(body)) return bad('body must be a JSON object');
112
+ const unknown = Object.keys(body).find((k) => !ALLOWED_KEYS.has(k));
113
+ if (unknown) return bad(`unknown field: ${unknown}`);
114
+
115
+ const resolved = resolveCwd(body.cwd);
116
+ if (!resolved || !resolved.ok) {
117
+ sendJson(res, resolved?.status || 400, { ok: false, error: oneLine(resolved?.error || 'cwd rejected') });
118
+ return;
119
+ }
120
+ const cwd = resolved.cwd;
121
+
122
+ if (!store().isVideoScriptSwitchOn(cwd)) {
123
+ sendJson(res, 403, { ok: false, error: 'scripts_not_allowed', reason: SWITCH_REASON });
124
+ return;
125
+ }
126
+
127
+ /** @type {Record<string, unknown>} */
128
+ const pressBody = {};
129
+ for (const k of PRESS_KEYS) if (body[k] !== undefined) pressBody[k] = body[k];
130
+ const parsed = parseScriptPress(pressBody);
131
+ if (!parsed.ok) return bad(parsed.error);
132
+ const cfg = parsed.cfg;
133
+
134
+ if (cfg.voice) {
135
+ let ids;
136
+ try {
137
+ const lib = listVoices(cwd);
138
+ ids = new Set(((lib && lib.voices) || []).map((v) => v && v.id));
139
+ } catch (e) {
140
+ return bad(`could not read the voice library: ${e instanceof Error ? e.message : String(e)}`);
141
+ }
142
+ if (!ids.has(cfg.voice)) return bad(`unknown voice '${cfg.voice}': not in this project's voice library (GET /admin/voices)`);
143
+ }
144
+
145
+ const ref = normalizeExternalRef(body.externalRef);
146
+ if (!ref.ok) return bad(ref.error);
147
+ const externalRef = ref.value;
148
+
149
+ const macro = builtins().find((/** @type {any} */ m) => m && m.id === MACRO_ID);
150
+ if (!macro) {
151
+ sendJson(res, 503, { ok: false, error: `${MACRO_ID} is not a built-in macro in this build` });
152
+ return;
153
+ }
154
+
155
+ const press = async () => {
156
+ if (externalRef !== undefined) {
157
+ const found = store().findScriptRun(cwd, { externalRef });
158
+ if (found) {
159
+ sendJson(res, 200, {
160
+ ok: true, existing: true, entryId: found.entryId, epicId: found.epicId,
161
+ slug: found.slug, alreadyRunning: !!isTabBusy(found.epicId), externalRef,
162
+ });
163
+ return;
164
+ }
165
+ }
166
+ if (inFlight.has(cwd)) {
167
+ sendJson(res, 409, { ok: false, error: 'already_building', activeSlug: null });
168
+ return;
169
+ }
170
+ let rows;
171
+ try {
172
+ rows = (await listJobRows()) || [];
173
+ } catch (e) {
174
+ sendJson(res, 503, { ok: false, error: oneLine(`could not read the job queue: ${e instanceof Error ? e.message : String(e)}`) });
175
+ return;
176
+ }
177
+ const active = rows.find((/** @type {any} */ r) => r && r.macroId === MACRO_ID && (!r.cwd || r.cwd === cwd) && ACTIVE.has(r.status));
178
+ if (active) {
179
+ sendJson(res, 409, { ok: false, error: 'already_building', activeSlug: active.slug ?? null });
180
+ return;
181
+ }
182
+
183
+ const payload = {
184
+ cwd,
185
+ agentName: macro.agentName,
186
+ tag: macro.tag,
187
+ title: macro.label,
188
+ prompt: `${macro.prompt}\n\nAdditional instructions: ${pressLines(cfg).join('\n')}`,
189
+ macroId: MACRO_ID,
190
+ via: 'script',
191
+ ...(cfg.review ? { reviewStage: true } : {}),
192
+ ...(externalRef !== undefined ? { externalRef } : {}),
193
+ };
194
+ const launch = (async () => {
195
+ try {
196
+ return await deps.startExternalNewSession?.(payload);
197
+ } catch (e) {
198
+ return { ok: false, reason: 'launch-failed', error: e instanceof Error ? e.message : 'launch failed' };
199
+ }
200
+ })();
201
+ inFlight.set(cwd, launch);
202
+ let result;
203
+ try {
204
+ result = await launch;
205
+ } finally {
206
+ inFlight.delete(cwd);
207
+ }
208
+ if (!result || !result.ok || typeof result.entryId !== 'string' || !result.entryId || !result.epicId) {
209
+ sendJson(res, 503, { ok: false, error: launchError(result) });
210
+ return;
211
+ }
212
+ const slug = typeof result.slug === 'string' && result.slug ? result.slug : null;
213
+ const stage = result.stage ?? null;
214
+ let recorded = true;
215
+ try {
216
+ store().recordScriptRun(cwd, {
217
+ entryId: result.entryId,
218
+ epicId: result.epicId,
219
+ slug: slug || result.entryId,
220
+ kind: cfg.kind,
221
+ at: new Date(now()).toISOString(),
222
+ ...(externalRef !== undefined ? { externalRef } : {}),
223
+ });
224
+ } catch (e) {
225
+ recorded = false;
226
+ console.warn('[videoScriptRunRoute] could not record the scripted run:', e instanceof Error ? e.message : e);
227
+ }
228
+ try {
229
+ audit('admin_video_script_run', {
230
+ route: ROUTE_PATH, cwd, macroId: MACRO_ID, kind: cfg.kind,
231
+ entryId: result.entryId, epicId: result.epicId, slug, stage,
232
+ ...(externalRef !== undefined ? { externalRef } : {}),
233
+ });
234
+ } catch { /* audit is best-effort */ }
235
+ sendJson(res, 200, {
236
+ ok: true, entryId: result.entryId, epicId: result.epicId, slug, stage,
237
+ ...(recorded ? {} : { runRecorded: false }),
238
+ });
239
+ };
240
+
241
+ if (externalRef !== undefined) await withLock({ cwd, externalRef }, press);
242
+ else await press();
243
+ });
244
+
245
+ adminHttp.registerRoute('GET', STATUS_ROUTE_PATH, async (/** @type {any} */ _req, /** @type {any} */ res, /** @type {any} */ query) => {
246
+ const q = query instanceof URLSearchParams ? query : new URLSearchParams();
247
+ const id = q.get('id') || '';
248
+ if (!STATUS_ID_RE.test(id)) {
249
+ sendJson(res, 400, { ok: false, error: 'id must match /^[a-z0-9][a-z0-9-]{0,63}$/' });
250
+ return;
251
+ }
252
+ const resolved = resolveCwd(q.get('cwd'));
253
+ if (!resolved || !resolved.ok) {
254
+ sendJson(res, resolved?.status || 400, { ok: false, error: oneLine(resolved?.error || 'cwd rejected') });
255
+ return;
256
+ }
257
+ const cwd = resolved.cwd;
258
+ let status;
259
+ try {
260
+ status = await readRunStatus(cwd, id, {
261
+ findScriptRun: (/** @type {string} */ c, /** @type {any} */ qq) => store().findScriptRun(c, qq),
262
+ listJobRows,
263
+ readHistoryTail: deps.readHistoryTail,
264
+ });
265
+ } catch (e) {
266
+ sendJson(res, 503, { ok: false, error: oneLine(`could not read the run: ${e instanceof Error ? e.message : String(e)}`) });
267
+ return;
268
+ }
269
+ if (!status) {
270
+ sendJson(res, 404, { ok: false, error: 'not found' });
271
+ return;
272
+ }
273
+ sendJson(res, 200, { ok: true, ...status });
274
+ });
275
+ }
276
+
277
+ /** @param {string} p */
278
+ function isFile(p) {
279
+ try { return fs.statSync(p).isFile(); } catch { return false; }
280
+ }
281
+
282
+ /** @param {string} p */
283
+ function isDir(p) {
284
+ try { return fs.statSync(p).isDirectory(); } catch { return false; }
285
+ }
286
+
287
+ /** outcome.json's text, or null when absent/invalid. @param {string} file @param {string} id */
288
+ function outcomeText(file, id) {
289
+ let rec;
290
+ try { rec = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return null; }
291
+ if (!rec || typeof rec !== 'object' || Array.isArray(rec)) return null;
292
+ if (rec.id !== undefined && rec.id !== id) return null;
293
+ if (rec.outcome !== 'season-complete' || typeof rec.text !== 'string' || !rec.text.trim()) return null;
294
+ return oneLine(rec.text.trim());
295
+ }
296
+
297
+ /**
298
+ * One run's status, or null when the id has no ledger run and no entry folder.
299
+ * Read-only. `id` must already match STATUS_ID_RE.
300
+ * @param {string} cwd
301
+ * @param {string} id
302
+ * @param {{ findScriptRun: (cwd: string, q: object) => any, listJobRows: () => Promise<any[]>,
303
+ * readHistoryTail?: (cwd: string) => Promise<string> }} io
304
+ */
305
+ async function readRunStatus(cwd, id, io) {
306
+ if (!STATUS_ID_RE.test(id)) throw new Error('bad entry id');
307
+ const { opsPath } = require('../opsOwnership.cjs');
308
+ const dir = opsPath(cwd, 'project-pages', 'videos', id);
309
+ const run = io.findScriptRun(cwd, { entryId: id });
310
+ const hasDir = isDir(dir);
311
+ if (!run && !hasDir) return null;
312
+ const slug = run && typeof run.slug === 'string' && run.slug ? run.slug : null;
313
+ const base = { entryId: id, epicId: (run && run.epicId) || null, slug };
314
+
315
+ const outcome = path.join(dir, 'outcome.json');
316
+ if (isFile(outcome)) {
317
+ const text = outcomeText(outcome, id);
318
+ if (text) return { ...base, state: 'season-complete', reason: text, files: null };
319
+ }
320
+
321
+ const index = path.join(dir, 'index.html');
322
+ const meta = path.join(dir, 'meta.json');
323
+ if (isFile(index) && isFile(meta)) {
324
+ /** @type {Record<string, string>} */
325
+ const files = { index, meta };
326
+ const mp4 = path.join(dir, 'video.mp4');
327
+ const poster = path.join(dir, 'poster.png');
328
+ if (isFile(mp4)) files.mp4 = mp4;
329
+ if (isFile(poster)) files.poster = poster;
330
+ return { ...base, state: 'saved', reason: null, files };
331
+ }
332
+
333
+ if (isFile(path.join(dir, 'review', 'material.json'))) {
334
+ return { ...base, state: 'awaiting_review', reason: null, files: null };
335
+ }
336
+
337
+ if (!slug) return { ...base, state: 'queued', reason: 'no job row for this entry (not a scripted run)', files: null };
338
+ const { jobStatusesBySlug } = require('../persona-macro/macroJobStatus.cjs');
339
+ const byslug = await jobStatusesBySlug({ cwd, slugs: [slug] }, {
340
+ loadJobs: io.listJobRows,
341
+ ...(io.readHistoryTail ? { readHistoryTail: io.readHistoryTail } : {}),
342
+ });
343
+ const row = byslug[slug];
344
+ if (!row) return { ...base, state: 'queued', reason: null, files: null };
345
+ if (row.state === 'running') return { ...base, state: 'running', reason: null, files: null };
346
+ if (row.state === 'failed') return { ...base, state: 'failed', reason: row.reason || `Ended as ${row.status}`, files: null };
347
+ if (row.state === 'done') return { ...base, state: 'failed', reason: 'The job completed without saving the video', files: null };
348
+ return { ...base, state: 'queued', reason: null, files: null };
349
+ }
350
+
351
+ 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 };
@@ -0,0 +1,173 @@
1
+ /**
2
+ * videoScriptSwitchRoute.cjs — the agent path for 'Scripts may run Demo Video'.
3
+ *
4
+ * POST /admin/project-home/videos/script-switch (body ≤ 64 KiB)
5
+ * { enabled, humanRequestQuote, originClaudeSessionId, cwd?, originProjectRoot? }
6
+ * Sets ONE project's switch on or off, and only on a verbatim quote of what
7
+ * the human typed in the calling chat session (humanPromptLedger). Checks,
8
+ * in order, each refusal writing and auditing nothing:
9
+ * 1. 403 human_request_unverified — the quote is not in a prompt the
10
+ * human typed in originClaudeSessionId (the ledger is the only proof);
11
+ * 2. 403 quote_does_not_name_switch — the quote does not say
12
+ * 'Scripts may run Demo Video' (quoteNamesVideoScriptSwitch);
13
+ * 3. 403 quote_does_not_name_project — the target is not the calling
14
+ * session's own project and the quote does not name it
15
+ * (crossProjectFeedback.quoteNamesTarget);
16
+ * 4. 409 request_older_than_switch — the matched prompt is not later
17
+ * than the switch's last change: one human instruction authorizes one
18
+ * write, and never undoes a later click.
19
+ * Success: videoScriptPress.setVideoScriptSwitch(target, enabled, { via:'agent',
20
+ * claudeSessionId, quote, promptAt }), one video_script_switch_changed audit
21
+ * event, 200 { ok, cwd, enabled, changedAt, by, previous }.
22
+ * Setting the value the switch already has re-stamps the attribution.
23
+ *
24
+ * Same shape as lib/tasks/taskSwitchRoute.cjs, minus the held-slot resync
25
+ * (that is Task-only). Scripts, scheduled jobs and Tasks cannot reach this:
26
+ * their prompts are never recorded in humanPromptLedger (only the Chat view
27
+ * records them). Registered by adminRouteRegistry.cjs.
28
+ */
29
+ 'use strict';
30
+
31
+ const path = require('node:path');
32
+ const { z } = require('zod');
33
+ const { readBody, sendJson } = require('../feedback-remote/localAdminHttp.cjs');
34
+
35
+ const ROUTE_PATH = '/admin/project-home/videos/script-switch';
36
+ const MAX_SWITCH_BODY_BYTES = 64 * 1024;
37
+
38
+ const switchBodySchema = z.object({
39
+ enabled: z.boolean(),
40
+ humanRequestQuote: z.string().min(1).max(2000),
41
+ originClaudeSessionId: z.string().min(1).max(128),
42
+ cwd: z.string().min(1).optional(),
43
+ originProjectRoot: z.string().min(1).optional(),
44
+ }).strict();
45
+
46
+ const SWITCH_RE = /(^|[^a-z0-9])scripts?\s+(may|can)\s+run\s+demo\s+videos?($|[^a-z0-9])/;
47
+
48
+ /** True when the quote names the 'Scripts may run Demo Video' switch (case, quote-mark, hyphen variants; 'can' for 'may'). */
49
+ function quoteNamesVideoScriptSwitch(quote) {
50
+ if (typeof quote !== 'string') return false;
51
+ const q = quote
52
+ .toLowerCase()
53
+ .replace(/[-_'"‘’‚‛“”„‟′″`]/g, ' ')
54
+ .replace(/\s+/g, ' ');
55
+ return SWITCH_RE.test(q);
56
+ }
57
+
58
+ /**
59
+ * @param {{ registerRoute: Function }} adminHttp
60
+ * @param {{ findHumanPromptContaining?: Function, resolveProjectContext?: Function,
61
+ * resolveProjectRoot?: Function, videoScriptPress?: any, appendAuditEvent?: Function,
62
+ * quoteNamesTarget?: Function, now?: () => number }} [deps]
63
+ */
64
+ function registerVideoScriptSwitchRoute(adminHttp, deps = {}) {
65
+ const findPrompt = deps.findHumanPromptContaining
66
+ || ((/** @type {string} */ s, /** @type {string} */ q, /** @type {number} */ n) => require('../feedback-remote/humanPromptLedger.cjs').findHumanPromptContaining(s, q, n));
67
+ const resolveContext = deps.resolveProjectContext
68
+ || ((/** @type {any} */ o) => require('../projectRootResolve.cjs').resolveProjectContext(o));
69
+ const projectRoot = deps.resolveProjectRoot
70
+ || ((/** @type {string} */ c, /** @type {any} */ o) => require('../opsOwnership.cjs').resolveProjectRoot(c, o));
71
+ const store = () => deps.videoScriptPress || require('./videoScriptPress.cjs');
72
+ const audit = deps.appendAuditEvent
73
+ || ((/** @type {string} */ k, /** @type {any} */ f) => require('../telemetry/auditLog.cjs').appendAuditEvent(k, f));
74
+ const namesTarget = deps.quoteNamesTarget
75
+ || ((/** @type {string} */ q, /** @type {string} */ c) => require('../feedback-remote/crossProjectFeedback.cjs').quoteNamesTarget(q, c));
76
+ const now = deps.now || Date.now;
77
+
78
+ adminHttp.registerRoute('POST', ROUTE_PATH, async (/** @type {any} */ req, /** @type {any} */ res) => {
79
+ const bad = (/** @type {any} */ details) => sendJson(res, 400, { ok: false, error: 'invalid_request', details });
80
+ const refuse = (/** @type {number} */ status, /** @type {string} */ error, /** @type {string} */ reason) =>
81
+ sendJson(res, status, { ok: false, error, reason });
82
+
83
+ let raw;
84
+ try {
85
+ raw = await readBody(req, MAX_SWITCH_BODY_BYTES);
86
+ } catch (e) {
87
+ bad(e instanceof Error ? e.message : String(e));
88
+ return;
89
+ }
90
+ let json;
91
+ try { json = JSON.parse(raw || '{}'); } catch {
92
+ bad('body is not valid JSON');
93
+ return;
94
+ }
95
+ const parsed = switchBodySchema.safeParse(json);
96
+ if (!parsed.success) {
97
+ bad(parsed.error.issues);
98
+ return;
99
+ }
100
+ const { enabled, humanRequestQuote: quote, originClaudeSessionId, cwd: rawCwd, originProjectRoot } = parsed.data;
101
+
102
+ // The calling session's own project.
103
+ let origin = null;
104
+ try {
105
+ const ctx = resolveContext({ originClaudeSessionId, originProjectRoot });
106
+ const o = ctx && (ctx.epicCwd || ctx.cwd);
107
+ if (typeof o === 'string' && o) origin = path.resolve(o);
108
+ } catch { origin = null; }
109
+
110
+ let target = origin;
111
+ if (rawCwd !== undefined) {
112
+ try {
113
+ const root = projectRoot(rawCwd, { opsInternal: 'refuse' });
114
+ if (path.resolve(root) !== path.resolve(rawCwd)) throw new Error(`cwd is not a project root (its root is "${root}")`);
115
+ target = path.resolve(root);
116
+ } catch (e) {
117
+ bad(e instanceof Error ? e.message : String(e));
118
+ return;
119
+ }
120
+ }
121
+ if (!target) {
122
+ bad('no target project: pass cwd, or call from a Session Manager chat session whose project can be resolved');
123
+ return;
124
+ }
125
+
126
+ const found = findPrompt(originClaudeSessionId, quote, now());
127
+ if (!found) {
128
+ refuse(403, 'human_request_unverified', 'humanRequestQuote was not found in a prompt the human typed in this chat session');
129
+ return;
130
+ }
131
+ if (!quoteNamesVideoScriptSwitch(quote)) {
132
+ refuse(403, 'quote_does_not_name_switch', "the human's quote does not name the 'Scripts may run Demo Video' switch");
133
+ return;
134
+ }
135
+ if (target !== origin && !namesTarget(quote, target)) {
136
+ refuse(403, 'quote_does_not_name_project', `the target is not this session's project and the human's quote does not name it (${path.basename(target)})`);
137
+ return;
138
+ }
139
+ const current = store().getVideoScriptSwitch(target);
140
+ const promptMs = Number(found.at);
141
+ const changedMs = current && current.changedAt ? Date.parse(current.changedAt) : NaN;
142
+ if (!Number.isFinite(promptMs) || (Number.isFinite(changedMs) && !(promptMs > changedMs))) {
143
+ refuse(409, 'request_older_than_switch', "the human's request is not newer than the switch's last change; ask the human again");
144
+ return;
145
+ }
146
+
147
+ const promptAt = new Date(promptMs).toISOString();
148
+ let saved;
149
+ try {
150
+ saved = store().setVideoScriptSwitch(target, enabled, { via: 'agent', claudeSessionId: originClaudeSessionId, quote, promptAt });
151
+ } catch (e) {
152
+ sendJson(res, 500, { ok: false, error: 'switch_write_failed', details: e instanceof Error ? e.message : String(e) });
153
+ return;
154
+ }
155
+ try {
156
+ audit('video_script_switch_changed', { cwd: saved.cwd, enabled: saved.enabled, via: 'agent', claudeSessionId: originClaudeSessionId, quote });
157
+ } catch { /* audit is best-effort, like the Task switch route */ }
158
+
159
+ sendJson(res, 200, {
160
+ ok: true,
161
+ cwd: saved.cwd,
162
+ enabled: saved.enabled,
163
+ changedAt: saved.changedAt,
164
+ by: saved.by,
165
+ previous: {
166
+ enabled: !!(current && current.enabled),
167
+ by: current ? current.by : null,
168
+ },
169
+ });
170
+ });
171
+ }
172
+
173
+ module.exports = { registerVideoScriptSwitchRoute, quoteNamesVideoScriptSwitch, MAX_SWITCH_BODY_BYTES, ROUTE_PATH };