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
@@ -465,6 +465,20 @@ function appendChatEpicEvent(cwd, epicId, event) {
465
465
  });
466
466
  }
467
467
 
468
+ /**
469
+ * Poke the Epic outside-state emitter (lib/epic/epicStateEmitter.cjs) at a
470
+ * turn's acceptance and settle — the only moments that time the 'working' and
471
+ * 'needs_input' outside states. Lazy require; never throws, never alters a turn.
472
+ */
473
+ function pokeState(cwd, sessionId) {
474
+ if (typeof cwd !== 'string' || !cwd || typeof sessionId !== 'string' || !sessionId) return;
475
+ try {
476
+ require('./lib/epic/epicStateEmitter.cjs').pokeEpicState(cwd, sessionId);
477
+ } catch (err) {
478
+ console.error('[chatRunner] epic state poke failed', sessionId, err?.message ?? err);
479
+ }
480
+ }
481
+
468
482
  /** Staging folder for a chat session's artifacts, or null (unsafe id / mkdir failure — logged). */
469
483
  function chatArtifactsDir(sessionId) {
470
484
  try {
@@ -658,11 +672,13 @@ function run(opts) {
658
672
  pendingStart.delete(opts.tabId);
659
673
  run({ ...opts, worktreeDirHint: wt && wt.dir ? wt.dir : undefined });
660
674
  });
675
+ if (!opts.silent) pokeState(opts.cwd, opts.sessionId);
661
676
  return { accepted: true, queued: tabBusy };
662
677
  }
663
678
 
664
679
  waiting.push(opts);
665
680
  pump();
681
+ if (!opts.silent) pokeState(opts.cwd, opts.sessionId);
666
682
  return { accepted: true, queued: tabBusy };
667
683
  }
668
684
 
@@ -702,6 +718,7 @@ function pump() {
702
718
  liveSessions.delete(job.sessionId);
703
719
  sessionSlots.release(slotToken);
704
720
  pump();
721
+ if (!job.silent) pokeState(job.cwd, job.sessionId);
705
722
  });
706
723
  }
707
724
  // Anyone still waiting gets a 1-based position update. Silent (automated
@@ -1374,6 +1391,16 @@ function cancel(tabId) {
1374
1391
  // than duplicating it here.
1375
1392
 
1376
1393
  const pendingExternalSends = new Map(); // requestId -> { resolve, timer }
1394
+ // requestId -> expiry timer. A send that timed out may still be acked by the
1395
+ // renderer; a late ack that produced a run confirms the held-turn entries it carried.
1396
+ const timedOutExternalSends = new Map();
1397
+ const TIMED_OUT_SEND_TTL_MS = 10 * 60 * 1000;
1398
+
1399
+ function rememberTimedOutSend(requestId) {
1400
+ const t = setTimeout(() => { timedOutExternalSends.delete(requestId); }, TIMED_OUT_SEND_TTL_MS);
1401
+ t.unref?.();
1402
+ timedOutExternalSends.set(requestId, t);
1403
+ }
1377
1404
 
1378
1405
  function hasLiveWindow() {
1379
1406
  try {
@@ -1383,10 +1410,57 @@ function hasLiveWindow() {
1383
1410
 
1384
1411
  /**
1385
1412
  * Resolves { disposition, reason? } once the renderer reports what it did, or
1386
- * { disposition: 'unconfirmed', reason: 'timeout' | 'no-window' }. Never rejects.
1413
+ * { disposition: 'unconfirmed', reason: 'no-window' } / { disposition: 'unconfirmed',
1414
+ * reason: 'timeout', requestId } (a late ack may still confirm a held batch). Never rejects.
1415
+ */
1416
+ // tabId -> identity key of the usage hold last audited for it (one audit per tab per hold).
1417
+ const heldTurnAuditKeys = new Map();
1418
+
1419
+ function schedulerHoldKey(hold) {
1420
+ try {
1421
+ const { holdIdentityKey } = require('./scheduler/utilizationHold.cjs');
1422
+ if (typeof holdIdentityKey === 'function') return holdIdentityKey(hold);
1423
+ } catch { /* fall through to the local key */ }
1424
+ return `${hold.reason}|${hold.window ?? ''}|${hold.resetsAt ?? ''}`;
1425
+ }
1426
+
1427
+ /**
1428
+ * Usage-hold seam: a scheduler-started turn under an active hold is deferred to the
1429
+ * held store (no broadcast, no claude process). Returns the disposition, or null
1430
+ * when the turn may run now. Required lazily to keep load order safe.
1387
1431
  */
1432
+ function holdSchedulerTurn(tabId, prompt, extra) {
1433
+ const heldSchedulerTurns = require('./lib/scheduler/heldSchedulerTurns.cjs');
1434
+ const hold = heldSchedulerTurns.currentHold();
1435
+ if (!hold) return null;
1436
+ // A drain batch held again keeps its original entries; re-deferring it would
1437
+ // nest coalesced headers on the next delivery.
1438
+ if (extra.heldBatch === true) return { disposition: 'held', reason: hold.reason };
1439
+ const { sessionId, cwd, heldKind } = extra;
1440
+ const entry = heldSchedulerTurns.defer({ tabId, prompt, kind: heldKind || 'scheduler-notice', sessionId, cwd, hold });
1441
+ const key = schedulerHoldKey(hold);
1442
+ if (heldTurnAuditKeys.get(tabId) !== key) {
1443
+ heldTurnAuditKeys.set(tabId, key);
1444
+ // The turn kind is `heldKind`: appendAuditEvent spreads fields over the record,
1445
+ // so a `kind` field would overwrite the event kind itself.
1446
+ require('./lib/telemetry/auditLog.cjs').appendAuditEvent('scheduler_turn_held', {
1447
+ tabId,
1448
+ heldKind: entry.kind,
1449
+ reason: hold.reason ?? null,
1450
+ window: hold.window ?? null,
1451
+ percent: hold.percent ?? null,
1452
+ threshold: hold.threshold ?? null,
1453
+ });
1454
+ }
1455
+ return { disposition: 'held', reason: hold.reason };
1456
+ }
1457
+
1388
1458
  function enqueueExternalPrompt(tabId, prompt, extra = {}) {
1389
1459
  const { sessionId, cwd, origin, relay } = extra ?? {};
1460
+ if (origin === 'scheduler') {
1461
+ const heldResult = holdSchedulerTurn(tabId, prompt, extra ?? {});
1462
+ if (heldResult) return Promise.resolve(heldResult);
1463
+ }
1390
1464
  if (!hasLiveWindow()) return Promise.resolve({ disposition: 'unconfirmed', reason: 'no-window' });
1391
1465
  if (origin === 'scheduler') noteSchedulerPrompt(tabId, prompt);
1392
1466
  const note = origin !== 'scheduler' && relay !== undefined ? noteRelayPrompt(tabId, prompt, relay) : null;
@@ -1401,7 +1475,8 @@ function enqueueExternalPrompt(tabId, prompt, extra = {}) {
1401
1475
  };
1402
1476
  const timer = setTimeout(() => {
1403
1477
  pendingExternalSends.delete(requestId);
1404
- resolve({ disposition: 'unconfirmed', reason: 'timeout' });
1478
+ rememberTimedOutSend(requestId);
1479
+ resolve({ disposition: 'unconfirmed', reason: 'timeout', requestId });
1405
1480
  }, EXTERNAL_SEND_ACK_TIMEOUT_MS);
1406
1481
  timer.unref?.();
1407
1482
  pendingExternalSends.set(requestId, { resolve, timer });
@@ -1417,7 +1492,20 @@ function enqueueExternalPrompt(tabId, prompt, extra = {}) {
1417
1492
 
1418
1493
  function settleExternalSend({ requestId, disposition, reason }) {
1419
1494
  const entry = pendingExternalSends.get(requestId);
1420
- if (!entry) return;
1495
+ if (!entry) {
1496
+ const late = timedOutExternalSends.get(requestId);
1497
+ if (late === undefined) return;
1498
+ clearTimeout(late);
1499
+ timedOutExternalSends.delete(requestId);
1500
+ if (disposition !== 'refused' && disposition !== 'unconfirmed') {
1501
+ try {
1502
+ require('./lib/scheduler/heldSchedulerTurns.cjs').confirmLateDelivery(requestId);
1503
+ } catch (err) {
1504
+ console.error('[chatRunner] confirmLateDelivery failed:', err);
1505
+ }
1506
+ }
1507
+ return;
1508
+ }
1421
1509
  clearTimeout(entry.timer);
1422
1510
  pendingExternalSends.delete(requestId);
1423
1511
  entry.resolve({ disposition, ...(reason !== undefined ? { reason } : {}) });
@@ -1436,7 +1524,8 @@ const EXTERNAL_NEW_SESSION_TIMEOUT_MS = 30000;
1436
1524
  const pendingExternalNewSessions = new Map(); // requestId -> { resolve, timer }
1437
1525
 
1438
1526
  /**
1439
- * @returns {Promise<{ ok: true, epicId: string } | { ok: false, reason: 'no-window'|'timeout'|'launch-failed', error: string }>}
1527
+ * Every payload key (incl. a boolean `reviewStage`) is broadcast unchanged.
1528
+ * @returns {Promise<{ ok: true, epicId: string, entryId?: string, slug?: string, stage?: 'review'|'final'|null } | { ok: false, reason: 'no-window'|'timeout'|'launch-failed', error: string }>}
1440
1529
  */
1441
1530
  function startExternalNewSession(payload) {
1442
1531
  if (!hasLiveWindow()) {
@@ -1454,13 +1543,20 @@ function startExternalNewSession(payload) {
1454
1543
  });
1455
1544
  }
1456
1545
 
1457
- function settleExternalNewSession({ requestId, ok, epicId, error }) {
1546
+ function settleExternalNewSession({ requestId, ok, epicId, error, entryId, slug, stage }) {
1458
1547
  const entry = pendingExternalNewSessions.get(requestId);
1459
1548
  if (!entry) return;
1460
1549
  clearTimeout(entry.timer);
1461
1550
  pendingExternalNewSessions.delete(requestId);
1462
- if (ok && epicId) entry.resolve({ ok: true, epicId });
1463
- else entry.resolve({ ok: false, reason: 'launch-failed', error: error || 'renderer could not start the session' });
1551
+ if (ok && epicId) {
1552
+ entry.resolve({
1553
+ ok: true,
1554
+ epicId,
1555
+ ...(entryId !== undefined ? { entryId } : {}),
1556
+ ...(slug !== undefined ? { slug } : {}),
1557
+ ...(stage !== undefined ? { stage } : {}),
1558
+ });
1559
+ } else entry.resolve({ ok: false, reason: 'launch-failed', error: error || 'renderer could not start the session' });
1464
1560
  }
1465
1561
 
1466
1562
  // Read-only: is a chat turn for this tab running, being dispatched, parked
@@ -1599,4 +1695,6 @@ module.exports = {
1599
1695
  isTabBusy,
1600
1696
  EXTERNAL_NEW_SESSION_TIMEOUT_MS,
1601
1697
  registerAdminRoute,
1698
+ // test-only: the chat turn-end artifact ingest (chatRunnerArtifactNotice.test.cjs)
1699
+ __ingestChatArtifacts: ingestChatArtifacts,
1602
1700
  };
@@ -19,7 +19,7 @@ const fs = require('node:fs');
19
19
  const fsp = require('node:fs/promises');
20
20
  const path = require('node:path');
21
21
  const os = require('node:os');
22
- const { assertOpsWrite, opsPath, OWNERS, OPS_ROOT_DIR } = require('./lib/opsOwnership.cjs');
22
+ const { assertOpsWrite, ensureRuntimeIgnoreForPath, opsPath, OWNERS, OPS_ROOT_DIR } = require('./lib/opsOwnership.cjs');
23
23
  const { walkImports } = require('./lib/persona-macro/personaImportHealth.cjs');
24
24
  const chokidar = require('chokidar');
25
25
  const logs = require('./logs.cjs');
@@ -293,6 +293,7 @@ async function writeRendererText(abs, text, { writer, importedBy } = {}) {
293
293
  throw new Error(`Write outside allowed write boundaries: ${real}`);
294
294
  }
295
295
  assertOpsWrite(real, writer);
296
+ ensureRuntimeIgnoreForPath(real);
296
297
  await atomicFs.writeTextAtomic(real, text, {});
297
298
  const stat = await fsp.stat(real);
298
299
  return { ok: true, mtimeMs: stat.mtimeMs };
@@ -368,6 +369,7 @@ async function writeTextAtomic(abs, text, opts = {}) {
368
369
  const real = validatePath(expandHome(abs));
369
370
  validateWrite(real);
370
371
  assertOpsWrite(real, opts.writer);
372
+ ensureRuntimeIgnoreForPath(real);
371
373
  await atomicFs.writeTextAtomic(real, text, opts);
372
374
  const stat = await fsp.stat(real);
373
375
  return { ok: true, mtimeMs: stat.mtimeMs };
@@ -381,6 +383,7 @@ async function writeBinaryAtomic(abs, buffer, opts = {}) {
381
383
  const real = validatePath(expandHome(abs));
382
384
  validateWrite(real);
383
385
  assertOpsWrite(real, opts.writer);
386
+ ensureRuntimeIgnoreForPath(real);
384
387
  const dir = path.dirname(real);
385
388
  await fsp.mkdir(dir, { recursive: true });
386
389
  const tmp = `${real}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
@@ -409,6 +412,7 @@ function writeJsonSync(abs, data, opts = {}) {
409
412
  const real = validatePath(expandHome(abs));
410
413
  validateWrite(real);
411
414
  assertOpsWrite(real, opts.writer);
415
+ ensureRuntimeIgnoreForPath(real);
412
416
  atomicFs.writeJsonAtomicSync(real, data, opts);
413
417
  const stat = fs.statSync(real);
414
418
  return { ok: true, mtimeMs: stat.mtimeMs };
@@ -22,11 +22,12 @@ const { evaluateDispatchLiveness } = require('./lib/scheduler/watchdogHelpers.cj
22
22
  const { computeStallSummary, computeDepHistorySatisfaction, FAILURE_STREAK_ESCALATION_MS } = require('./scheduler/budget.cjs');
23
23
  const { classifyQueueStarvation, launchBlockedSlugs, STARVE_ESCALATION_MS } = require('./scheduler/starvation.cjs');
24
24
  const { REVERIFY_INTERVAL_MS } = require('./scheduler/reviewLadder.cjs');
25
+ const { proRatedThreshold } = require('./scheduler/utilizationHold.cjs');
25
26
  const { makeDepResolver } = require('./lib/prd/depSlugResolve.cjs');
26
27
  const { findStarvedProjects, findUnresolvableDepRoots, DEFAULT_PROJECT_CWD, DEP_HISTORY_FAIL_OPEN } = require('./lib/scheduler/schedulerBatch.cjs');
27
28
  const { auditLogPath, readTail } = require('./lib/telemetry/auditLog.cjs');
28
29
  const { checkMainDependencyHealth } = require('./lib/git/depHealth.cjs');
29
- const { findTrackedRuntimeState } = require('./lib/git/runtimeStateUntrack.cjs');
30
+ const { findTrackedRuntimeState, findVisibleRuntimeState } = require('./lib/git/runtimeStateUntrack.cjs');
30
31
  const { resolveBuildIdentity } = require('./lib/buildIdentity.cjs');
31
32
  const { computeReport, isRetentionEnabled, liveKeysFromJobs, resolveRetentionConfig } = require('./lib/scheduler/runLogRetention.cjs');
32
33
  const { allProjectCwds } = require('./lib/activeSessions.cjs');
@@ -154,7 +155,16 @@ function evaluateTickLiveness(queueState, heartbeat, now, runningCount) {
154
155
  oldestPendingSlug: pending[0]?.slug,
155
156
  };
156
157
  }
157
- if (typeof heartbeat.utilization === 'number' && heartbeat.utilization >= config.utilizationThreshold) {
158
+ // Same pro-rated 'pause above' the scheduler's own hold reads
159
+ // (scheduler/utilizationHold.cjs) — a flat cap here would call a
160
+ // dispatching queue held, or a held one stalled.
161
+ const effectiveThreshold = proRatedThreshold({
162
+ base: config.utilizationThreshold,
163
+ window: heartbeat.utilizationWindow,
164
+ resetsAt: heartbeat.nextReset,
165
+ now,
166
+ });
167
+ if (typeof heartbeat.utilization === 'number' && heartbeat.utilization >= effectiveThreshold) {
158
168
  // A hold on the binding window is benign only if it self-heals soon
159
169
  // (reset within 5h). A weekly hold, or an unknown reset horizon, can
160
170
  // last days — surface it rather than reading GREEN.
@@ -816,6 +826,25 @@ function evaluateMainDepLinks(results = []) {
816
826
  return { component: { ok: true, checked: list.length, broken }, issues };
817
827
  }
818
828
 
829
+ /**
830
+ * evaluateVisibleRuntimeState(results) → { component, issues }
831
+ *
832
+ * Pure over `Array<{ cwd, count }>` (count = findVisibleRuntimeState(cwd).length).
833
+ * One warn issue per project whose runtime files git can see — a namespace
834
+ * missing its self-ignore. Non-critical: component.ok is always true.
835
+ */
836
+ function evaluateVisibleRuntimeState(results = []) {
837
+ const list = Array.isArray(results) ? results : [];
838
+ const projects = list
839
+ .filter((r) => r && Number.isFinite(r.count) && r.count > 0)
840
+ .map(({ cwd, count }) => ({ cwd, count }));
841
+ if (projects.length === 0) return { component: { ok: true }, issues: [] };
842
+ return {
843
+ component: { ok: true, warn: true, projects },
844
+ issues: projects.map((p) => `warn: ${p.cwd} has ${p.count} Session Manager runtime file(s) git can see (missing self-ignore)`),
845
+ };
846
+ }
847
+
819
848
  /**
820
849
  * evaluateCredentialHealth({ credState, now }) → { component, issues }
821
850
  *
@@ -1489,10 +1518,15 @@ async function check(opts = {}) {
1489
1518
  try {
1490
1519
  const roots = [...new Set(allProjectCwds())].slice(0, 100).filter((cwd) => fs.existsSync(cwd));
1491
1520
  const hits = [];
1521
+ const visible = [];
1492
1522
  for (const cwd of roots) {
1493
1523
  const n = (await findTrackedRuntimeState(cwd)).length;
1494
1524
  if (n > 0) hits.push({ cwd, count: n });
1525
+ visible.push({ cwd, count: (await findVisibleRuntimeState(cwd)).length });
1495
1526
  }
1527
+ const visibleEval = evaluateVisibleRuntimeState(visible);
1528
+ status.components.visible_runtime_state = visibleEval.component;
1529
+ status.issues.push(...visibleEval.issues);
1496
1530
  status.components.tracked_runtime_state = hits.length === 0
1497
1531
  ? { ok: true }
1498
1532
  : { ok: true, warn: true, projects: hits };
@@ -1501,6 +1535,7 @@ async function check(opts = {}) {
1501
1535
  }
1502
1536
  } catch (e) {
1503
1537
  status.components.tracked_runtime_state = { ok: true, error: e.message };
1538
+ status.components.visible_runtime_state = { ok: true, error: e.message };
1504
1539
  }
1505
1540
 
1506
1541
  // 6.8. Credential health (informational-but-loud): is the Claude OAuth token
@@ -1595,6 +1630,7 @@ module.exports = {
1595
1630
  evaluateStarveEscalationHealth,
1596
1631
  evaluateBuildFreshness,
1597
1632
  evaluateMainDepLinks,
1633
+ evaluateVisibleRuntimeState,
1598
1634
  WORKTREE_SAFETY_PATHS,
1599
1635
  latestStarveEscalationReasons,
1600
1636
  DISPATCH_STALL_THRESHOLD_MS,
@@ -68,9 +68,6 @@ const voiceHotkey = require('./voiceHotkey.cjs');
68
68
  const scheduler = require('./scheduler.cjs');
69
69
  const { createAdminHttp } = require('./lib/feedback-remote/localAdminHttp.cjs');
70
70
  const prdCreate = require('./lib/prd/prdCreate.cjs');
71
- const prdAdminRoutes = require('./lib/prd/prdAdminRoutes.cjs');
72
- const projectHomeAdminRoutes = require('./lib/feedback-remote/projectHomeAdminRoutes.cjs');
73
- const macroAdminRoutes = require('./lib/feedback-remote/macroAdminRoutes.cjs');
74
71
  const { smfileResponseHeaders, shouldBlockFrameNavigation, smfileUrlToPath } = require('./lib/smfileHeaders.cjs');
75
72
  const { buildMediaResponse } = require('./lib/util/smfileRange.cjs');
76
73
  const { appendAuditEvent } = require('./lib/telemetry/auditLog.cjs');
@@ -92,12 +89,18 @@ const { resolveProjectContext } = require('./lib/projectRootResolve.cjs');
92
89
  const upgradeDrain = require('./lib/scheduler/upgradeDrain.cjs');
93
90
  const { writeGuardShims } = require('./lib/guardShims.cjs');
94
91
  const { sendIfAlive } = require('./lib/sendToRenderer.cjs');
95
- const crossProjectFeedback = require('./lib/feedback-remote/crossProjectFeedback.cjs');
96
92
  const adminHttp = createAdminHttp();
97
93
  require('./adminRouteRegistry.cjs').registerAppAdminRoutes(adminHttp, {
98
94
  onMacrosChanged: () => broadcastMacrosChanged(),
99
95
  onNeedsYouChanged: broadcastNeedsYouChanged,
100
96
  });
97
+ // Event-driven epic_state_changed (lib/epic/epicStateEmitter.cjs): chat turns poke it,
98
+ // and its job rows wait for any in-flight queue write before a recompute reads them.
99
+ {
100
+ const epicStateEmitter = require('./lib/epic/epicStateEmitter.cjs');
101
+ epicStateEmitter.configureEpicStateEmitter({ isTabBusy: chatRunner.isTabBusy, listJobs: () => scheduler.remote.listJobRowsSettled() });
102
+ epicStateEmitter.startEpicStateEmitter();
103
+ }
101
104
  // Outside apps' "Needs you" items (lib/feedback-remote/needsYouStore.cjs); changes broadcast `needsYou:changed`.
102
105
  function broadcastNeedsYouChanged() {
103
106
  sendIfAlive(mainWindow, 'needsYou:changed', {});
@@ -629,6 +632,11 @@ require('./lib/persona-macro/macroJobIpc.cjs').registerMacroJobIpc(ipcMain, macr
629
632
  // Project Video review step: list + human decide (approve / ask for changes). Same deps
630
633
  // as macroJobIpc — a decision dispatches through runToolJob. Renderer IPC only.
631
634
  require('./lib/project-pages/videoReviewIpc.cjs').registerVideoReviewIpc(ipcMain, macroJobIpcDeps);
635
+ // 'Scripts may run Demo Video' switch: get + the human-click set (by.via 'ui'). Renderer IPC only.
636
+ require('./lib/project-pages/videoScriptSwitchIpc.cjs').registerVideoScriptSwitchIpc(ipcMain, {
637
+ schemas,
638
+ validatePath: require('./config.cjs').validatePath,
639
+ });
632
640
  // Voices screen: list/preview + the ONLY writer of voice approvals and deletions.
633
641
  // Renderer IPC only — no admin route or MCP tool approves, changes or deletes a voice.
634
642
  require('./lib/project-pages/voicesIpc.cjs').registerVoicesIpc(ipcMain, {
@@ -1152,6 +1152,10 @@ const projectVideosReviewDecide = z.object({
1152
1152
  note: z.string().max(2000).optional(),
1153
1153
  }).strict();
1154
1154
  const projectVideosReviewRetry = z.object({ cwd: z.string().min(1).max(4096), entryId }).strict();
1155
+ // 'Scripts may run Demo Video' switch (project-pages/videoScriptSwitchIpc.cjs): renderer IPC only,
1156
+ // the human-click writer (by.via 'ui').
1157
+ const videosScriptSwitchGet = z.object({ cwd: z.string().min(1).max(4096) }).strict();
1158
+ const videosScriptSwitchSet = z.object({ cwd: z.string().min(1).max(4096), enabled: z.boolean() }).strict();
1155
1159
  // Voices screen (project-pages/voicesIpc.cjs): renderer IPC only — the sole writer of
1156
1160
  // voice approvals and deletions. voiceId follows voiceLibrary.VOICE_ID_RE (voiceLibraryId, declared
1157
1161
  // above macrosDispatchJob); text is TEXT_MAX (300).
@@ -1449,6 +1453,11 @@ const chatExternalNewSessionResult = z.object({
1449
1453
  ok: z.boolean(),
1450
1454
  epicId: z.string().min(1).max(128).regex(/^[A-Za-z0-9][A-Za-z0-9_.-]*$/).optional(),
1451
1455
  error: z.string().max(500).optional(),
1456
+ // The background build the renderer queued for a scripted job press
1457
+ // (Demo Video): its Project Home entry id, slug and stage.
1458
+ entryId: entryId.optional(),
1459
+ slug: z.string().min(1).max(200).optional(),
1460
+ stage: z.enum(['review', 'final']).nullable().optional(),
1452
1461
  }).strict();
1453
1462
 
1454
1463
  // Phone drill-down reads. cwd is re-checked against the open tabs in
@@ -2004,6 +2013,8 @@ module.exports = {
2004
2013
  projectVideosReviewList,
2005
2014
  projectVideosReviewDecide,
2006
2015
  projectVideosReviewRetry,
2016
+ videosScriptSwitchGet,
2017
+ videosScriptSwitchSet,
2007
2018
  voicesList,
2008
2019
  voicesPreview,
2009
2020
  voicesApprove,
@@ -24,7 +24,16 @@ persona still holds.
24
24
  ## A member without a voice
25
25
 
26
26
  - A member without `voice` never speaks. Give it no lines.
27
- - It gets sound effects only: sound.cjs cues on its moments, never words.
27
+ - It is heard only through sound effects on its moments, never words: cue one of its `sfx` with
28
+ sound.cjs, or a built-in effect that fits its `note` when it has no `sfx`.
29
+
30
+ ## Sounds
31
+
32
+ - A member's `sfx` names its signature sounds: built-in effects or the persona's own.
33
+ - character.json `sounds` lists the project's own effects (`sfx`) and music beds (`beds`) by
34
+ `name`, each with a `note` on what it is. Use them by name: a sound.cjs cue for an effect, the
35
+ spec's `bed` for a music bed. They are mixed like the built-in ones.
36
+ - An unknown sound name fails the run with sound.cjs's error. Never swap in another sound.
28
37
 
29
38
  ## Captions
30
39
 
@@ -14,6 +14,8 @@ const fs = require('node:fs');
14
14
  const os = require('node:os');
15
15
  const path = require('node:path');
16
16
  const { spawnSync } = require('node:child_process');
17
+ // projectSounds.cjs requires this file only lazily, so this top-level require has no load cycle.
18
+ const { validateSounds, validateMemberSfx } = require('./projectSounds.cjs');
17
19
  // Kit files are seeded to ~/.claude/session-manager/demo-video-kit/ and must
18
20
  // load standalone: node built-ins and this folder only (no ../opsOwnership.cjs).
19
21
  // Allowlisted for this literal in scripts/check-ops-path-literals.cjs ALLOWLIST.
@@ -75,7 +77,11 @@ function validateCharacterJson(c) {
75
77
  if (!v || typeof v !== 'object') return 'voice is required';
76
78
  const vErr = validateVoiceOrRef(v, 'voice');
77
79
  if (vErr) return vErr;
78
- if ('cast' in c) return validateCast(c.cast, c.name);
80
+ if ('sounds' in c) {
81
+ const sErr = validateSounds(c.sounds);
82
+ if (sErr) return sErr;
83
+ }
84
+ if ('cast' in c) return validateCast(c.cast, c.name, c.sounds);
79
85
  return null;
80
86
  }
81
87
 
@@ -135,11 +141,13 @@ function voiceIdRefsOf(c) {
135
141
  return refs;
136
142
  }
137
143
 
138
- const CAST_KEYS = Object.freeze(['name', 'voice', 'note']);
144
+ const CAST_KEYS = Object.freeze(['name', 'voice', 'note', 'sfx']);
139
145
 
140
146
  /** -> null when `cast` is a valid supporting cast for host `hostName`, else a reason.
141
- * A member without `voice` is valid: it never speaks. */
142
- function validateCast(cast, hostName) {
147
+ * A member without `voice` is valid: it never speaks, and is heard only through sound
148
+ * effects. A member's optional `sfx` names its signature sounds (built-in effects or the
149
+ * persona's `sounds.sfx`, passed as `sounds`). */
150
+ function validateCast(cast, hostName, sounds) {
143
151
  if (!Array.isArray(cast) || cast.length > MAX_CAST_MEMBERS) {
144
152
  return `cast must be an array of at most ${MAX_CAST_MEMBERS} members`;
145
153
  }
@@ -165,6 +173,10 @@ function validateCast(cast, hostName) {
165
173
  if ('note' in m && (typeof m.note !== 'string' || m.note.length < 1 || m.note.length > CAST_NOTE_MAX)) {
166
174
  return `${at}.note must be a 1-${CAST_NOTE_MAX} char string`;
167
175
  }
176
+ if ('sfx' in m) {
177
+ const fErr = validateMemberSfx(m.sfx, `${at}.sfx`, sounds);
178
+ if (fErr) return fErr;
179
+ }
168
180
  }
169
181
  return null;
170
182
  }
@@ -313,15 +325,50 @@ function wavSeconds(file) {
313
325
  }
314
326
  }
315
327
 
328
+ /**
329
+ * Time kept back from speaking for mixing and saving the video, given `leftMs` before the
330
+ * job deadline: a quarter of it, at most SPEAK_DEADLINE_MARGIN_MS (45 min). Short jobs still
331
+ * get three quarters of their time to speak; long jobs keep the full 45 minutes.
332
+ */
333
+ function speakReserveMs(leftMs) {
334
+ return Math.min(SPEAK_DEADLINE_MARGIN_MS, Math.floor(leftMs / 4));
335
+ }
336
+
337
+ /** env.SM_SCHEDULER_JOB_DEADLINE_MS as a finite number, else null. */
338
+ function jobDeadline(env) {
339
+ const raw = env && env.SM_SCHEDULER_JOB_DEADLINE_MS;
340
+ const deadline = Number(raw);
341
+ return raw !== undefined && raw !== null && raw !== '' && Number.isFinite(deadline) ? deadline : null;
342
+ }
343
+
344
+ /** Minutes with one decimal, for error messages. */
345
+ function fmtMin(ms) {
346
+ return Math.round(Math.max(0, ms) / 6000) / 10;
347
+ }
348
+
349
+ /**
350
+ * ' (<N> min left before the job deadline, <M> min kept in reserve)' when
351
+ * env.SM_SCHEDULER_JOB_DEADLINE_MS is set, else ''. The one suffix both the batch time-limit
352
+ * error and the voice-lane timeout use, so the two messages say the same thing. reserveMs,
353
+ * when given, is printed as the reserve kept (the lane fixes it when its wait starts) instead
354
+ * of speakReserveMs(time left).
355
+ */
356
+ function deadlineContext({ now = Date.now(), env = process.env, reserveMs } = {}) {
357
+ const deadline = jobDeadline(env);
358
+ if (deadline === null) return '';
359
+ const leftMs = deadline - now;
360
+ const kept = reserveMs === undefined || reserveMs === null ? speakReserveMs(leftMs) : reserveMs;
361
+ return ` (${fmtMin(leftMs)} min left before the job deadline, ${fmtMin(kept)} min kept in reserve)`;
362
+ }
363
+
316
364
  /**
317
365
  * How long one synthesis call may wait for its voice lane: the time left before
318
- * env.SM_SCHEDULER_JOB_DEADLINE_MS minus SPEAK_DEADLINE_MARGIN_MS when that is set
366
+ * env.SM_SCHEDULER_JOB_DEADLINE_MS minus speakReserveMs(time left) when that is set
319
367
  * (may be <= 0: no time left), else LANE_WAIT_DEFAULT_MS (6 h).
320
368
  */
321
369
  function laneWaitMs({ now = Date.now(), env = process.env } = {}) {
322
- const raw = env && env.SM_SCHEDULER_JOB_DEADLINE_MS;
323
- const deadline = Number(raw);
324
- if (raw !== undefined && raw !== null && raw !== '' && Number.isFinite(deadline)) return deadline - now - SPEAK_DEADLINE_MARGIN_MS;
370
+ const deadline = jobDeadline(env);
371
+ if (deadline !== null) return deadline - now - speakReserveMs(deadline - now);
325
372
  return LANE_WAIT_DEFAULT_MS;
326
373
  }
327
374
 
@@ -334,8 +381,10 @@ function lanePositionLine(pos) {
334
381
 
335
382
  /**
336
383
  * Run one synthesis call `fn` (-> {ok, error?}) inside the voice lane of rv's voice.
337
- * ctx: {root, kind, label, onLanePosition?}. Always leaves the lane; the usage line
338
- * carries ok, audioSeconds (sum over `outs`' WAV headers) and wallMs.
384
+ * ctx: {root, kind, label, onLanePosition?, clock?, waitTurn?} (clock / waitTurn are test
385
+ * seams, default Date.now / voiceLane.waitTurn). Always leaves the lane; the usage line
386
+ * carries ok, audioSeconds (sum over `outs`' WAV headers) and wallMs. A lane-wait failure
387
+ * names the minutes left when it failed and the reserve fixed when the wait started.
339
388
  */
340
389
  function inLane(ctx, rv, outs, fn) {
341
390
  const lane = require('./voiceLane.cjs');
@@ -344,8 +393,14 @@ function inLane(ctx, rv, outs, fn) {
344
393
  let granted = false;
345
394
  let ok = false;
346
395
  try {
347
- const left = laneWaitMs();
348
- const w = lane.waitTurn(ticket, {
396
+ const clock = typeof ctx.clock === 'function' ? ctx.clock : Date.now;
397
+ const waitTurn = typeof ctx.waitTurn === 'function' ? ctx.waitTurn : lane.waitTurn;
398
+ const now = clock();
399
+ const env = process.env;
400
+ const left = laneWaitMs({ now, env });
401
+ const deadline = jobDeadline(env);
402
+ const reserveMs = deadline === null ? undefined : speakReserveMs(deadline - now);
403
+ const w = waitTurn(ticket, {
349
404
  timeoutMs: Math.max(1, left),
350
405
  onPosition: (pos) => {
351
406
  if (pos.position > 0) process.stderr.write(`${lanePositionLine(pos)}\n`);
@@ -353,8 +408,7 @@ function inLane(ctx, rv, outs, fn) {
353
408
  },
354
409
  });
355
410
  if (!w.ok) {
356
- const why = left <= 0 ? ` (no time left before the job deadline minus a ${SPEAK_DEADLINE_MARGIN_MS / 60000} min margin)` : '';
357
- return { ok: false, error: `${w.error}${why}` };
411
+ return { ok: false, error: `${w.error}${deadlineContext({ now: clock(), env, reserveMs })}` };
358
412
  }
359
413
  granted = true;
360
414
  const r = fn();
@@ -408,21 +462,20 @@ function speakWithCommand(voice, text, out, { cwd } = {}) {
408
462
  /**
409
463
  * Time limit for one batch voice call over `lineCount` lines -> {ok: true, ms} | {ok: false, error}.
410
464
  * ms = min(lineCount * COMMAND_TIMEOUT_MS, BATCH_TIMEOUT_CEILING_MS), capped at the scheduler's
411
- * job deadline (env.SM_SCHEDULER_JOB_DEADLINE_MS) minus SPEAK_DEADLINE_MARGIN_MS when that is a
465
+ * job deadline (env.SM_SCHEDULER_JOB_DEADLINE_MS) minus speakReserveMs(time left) when that is a
412
466
  * finite number: the voice runs first, so the whole video is still to be built after it.
413
467
  */
414
468
  function batchTimeoutMs(lineCount, { now = Date.now(), env = process.env } = {}) {
415
469
  let ms = Math.min(lineCount * COMMAND_TIMEOUT_MS, BATCH_TIMEOUT_CEILING_MS);
416
- const deadline = Number(env && env.SM_SCHEDULER_JOB_DEADLINE_MS);
417
- const raw = env && env.SM_SCHEDULER_JOB_DEADLINE_MS;
418
- if (raw !== undefined && raw !== null && raw !== '' && Number.isFinite(deadline)) {
419
- ms = Math.min(ms, deadline - now - SPEAK_DEADLINE_MARGIN_MS);
420
- }
470
+ const deadline = jobDeadline(env);
471
+ const leftMs = deadline === null ? null : deadline - now;
472
+ if (leftMs !== null) ms = Math.min(ms, leftMs - speakReserveMs(leftMs));
421
473
  if (ms < MIN_BATCH_TIMEOUT_MS) {
422
474
  const left = Math.max(0, Math.floor(ms / 1000));
475
+ const ctx = deadlineContext({ now, env });
423
476
  return {
424
477
  ok: false,
425
- error: `only ${left}s left before the job deadline (minus a ${SPEAK_DEADLINE_MARGIN_MS / 60000} min margin) for ${lineCount} lines; need at least ${MIN_BATCH_TIMEOUT_MS / 1000}s`,
478
+ error: `only ${left}s left to speak for ${lineCount} lines${ctx}; need at least ${MIN_BATCH_TIMEOUT_MS / 1000}s`,
426
479
  };
427
480
  }
428
481
  return { ok: true, ms };
@@ -649,7 +702,10 @@ module.exports = {
649
702
  isBatchVoice,
650
703
  wavSeconds,
651
704
  laneWaitMs,
705
+ deadlineContext,
706
+ speakReserveMs,
652
707
  lanePositionLine,
708
+ inLane,
653
709
  LANE_WAIT_DEFAULT_MS,
654
710
  validateCharacterJson,
655
711
  validateCharacterJs,
@@ -62,7 +62,9 @@ Run the kit from `~/.claude/session-manager/demo-video-kit/` exactly as the pers
62
62
  post-caption checks must all pass before you save.
63
63
  - sound.cjs: mix the narration over the music bed; the bed is ducked under speech and the mix is
64
64
  normalised to -14 LUFS. When the project has a saved character with a command voice, speak its
65
- lines with `node character.cjs speak spec.json` first.
65
+ lines with `node character.cjs speak spec.json` first. Pass `projectRoot` (`$SM_PROJECT_ROOT`) in
66
+ its spec: a cue or the spec's `bed` may name one of the persona's own `sounds`, and an unknown name
67
+ fails the run; never swap in another sound.
66
68
  - export.cjs: `node export.cjs spec.json` with `{ htmlPath, lengthS, audioPath, outDir }` writes
67
69
  `video.mp4` (1080x1920, H.264/AAC) and `poster.png` in `outDir`. It must exit 0.
68
70
 
@@ -89,6 +91,8 @@ When the `Video target:` line names a series brief file:
89
91
  1. Read the brief, then every season, canon and ledger file it names.
90
92
  2. Make the next episode exactly as they say: its premise, cast, topic and beats. Follow the
91
93
  brief's topic; never invent a premise, never pick an episode the files do not schedule.
94
+ Keep its sound too: every sound cue at its time and its music as the sound.cjs `bed`,
95
+ by the names the files use.
92
96
  3. Use the project persona for the host and voice; never borrow another project's characters.
93
97
  4. When the files have no next episode left, in the review stage or the final stage alike,
94
98
  call `project_video_outcome_write` once with `{ videoId: <the Entry id>, outcome: