claude-code-session-manager 0.140.0 → 0.142.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 (204) hide show
  1. package/README.md +80 -70
  2. package/bin/cli.cjs +11 -0
  3. package/dist/assets/AppSettings-BcZgIvvY.js +2 -0
  4. package/dist/assets/{History--JwsFnbn.js → History-DpZuJXi1.js} +1 -1
  5. package/dist/assets/HomeClaudeConfig-D32ZJtU-.js +3 -0
  6. package/dist/assets/{Panel-CALyU0pe.js → Panel-BjdJjhqt.js} +1 -1
  7. package/dist/assets/{ProjectClaudeConfig-sdlA-fUb.js → ProjectClaudeConfig-BTClYV6i.js} +7 -7
  8. package/dist/assets/Scheduler-DPobKx1Z.js +16 -0
  9. package/dist/assets/{SkillReferenceGraph-CxAuwhNN.js → SkillReferenceGraph-Cqyu4mef.js} +1 -1
  10. package/dist/assets/{Skills-DtRzghn5.js → Skills-vv0noNVI.js} +5 -5
  11. package/dist/assets/{TiptapBody-DApeu7x8.js → TiptapBody-CXi8Pvut.js} +1 -1
  12. package/dist/assets/Toggle-CiYCWLjh.js +1 -0
  13. package/dist/assets/{VoiceButton-DtStfv1H.js → VoiceButton-4NKKd1sC.js} +1 -1
  14. package/dist/assets/{historyTotals-ydfnwepc.js → historyTotals-DDunb8Ch.js} +1 -1
  15. package/dist/assets/index-Cn5E9958.js +3133 -0
  16. package/dist/assets/{index-DKXdXfka.css → index-DVHIHoJf.css} +1 -1
  17. package/dist/index.html +2 -2
  18. package/dist-web/app.css +1 -1
  19. package/dist-web/app.js +496 -484
  20. package/package.json +4 -2
  21. package/plugins/AGENTS.md +4 -3
  22. package/plugins/session-manager-dev/hooks/hooks.json +15 -0
  23. package/plugins/session-manager-dev/hooks/residue-check.cjs +241 -0
  24. package/plugins/session-manager-dev/skills/builder/SKILL.md +4 -2
  25. package/plugins/session-manager-dev/skills/develop/SKILL.md +55 -18
  26. package/plugins/session-manager-dev/skills/develop/standards.md +3 -2
  27. package/scripts/README.md +1 -0
  28. package/scripts/hooks/guard-tool-risk.cjs +5 -1
  29. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +158 -1
  30. package/scripts/scheduler-mcp-server.cjs +737 -110
  31. package/src/main/adminRouteRegistry.cjs +59 -0
  32. package/src/main/agentLibrary.cjs +72 -4
  33. package/src/main/agentsIpc.cjs +3 -2
  34. package/src/main/build-info.json +4 -4
  35. package/src/main/chatRunner.cjs +231 -16
  36. package/src/main/config.cjs +30 -0
  37. package/src/main/docEdit.cjs +4 -2
  38. package/src/main/health.cjs +91 -0
  39. package/src/main/index.cjs +98 -48
  40. package/src/main/ipcSchemas.cjs +171 -8
  41. package/src/main/lib/AGENTS.md +1 -1
  42. package/src/main/lib/chatBootRecovery.cjs +2 -0
  43. package/src/main/lib/claude/agentModelResolve.cjs +51 -25
  44. package/src/main/lib/claude/agentSnapshot.cjs +186 -0
  45. package/src/main/lib/claude/environmentProfiles.cjs +242 -0
  46. package/src/main/lib/claude/jobSandboxPolicy.cjs +241 -33
  47. package/src/main/lib/claude/personaToolScope.cjs +82 -31
  48. package/src/main/lib/claude/runClaudeP.cjs +4 -2
  49. package/src/main/lib/claude/toolRiskMarks.cjs +41 -1
  50. package/src/main/lib/claude/usageCircuit.cjs +49 -21
  51. package/src/main/lib/claude/vaultRefs.cjs +277 -0
  52. package/src/main/lib/demo-video-kit/capture.cjs +282 -12
  53. package/src/main/lib/demo-video-kit/cast.md +43 -0
  54. package/src/main/lib/demo-video-kit/character.cjs +722 -30
  55. package/src/main/lib/demo-video-kit/checks.cjs +120 -1
  56. package/src/main/lib/demo-video-kit/export.cjs +218 -0
  57. package/src/main/lib/demo-video-kit/frames.cjs +104 -9
  58. package/src/main/lib/demo-video-kit/kind-marketing.md +121 -0
  59. package/src/main/lib/demo-video-kit/kind-tiktok.md +99 -0
  60. package/src/main/lib/demo-video-kit/kokoroSay.cjs +205 -0
  61. package/src/main/lib/demo-video-kit/project-home-html.md +43 -0
  62. package/src/main/lib/demo-video-kit/resumableRun.cjs +298 -0
  63. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  64. package/src/main/lib/demo-video-kit/voiceLane.cjs +233 -0
  65. package/src/main/lib/demo-video-kit/voiceLibrary.cjs +312 -0
  66. package/src/main/lib/epic/artifactAdminRoutes.cjs +211 -0
  67. package/src/main/lib/epic/artifactIpc.cjs +153 -0
  68. package/src/main/lib/epic/artifactNotice.cjs +72 -0
  69. package/src/main/lib/epic/artifactRetention.cjs +310 -0
  70. package/src/main/lib/epic/artifactStore.cjs +392 -0
  71. package/src/main/lib/epic/delegationReadiness.cjs +76 -2
  72. package/src/main/lib/epic/epicAgentRefresh.cjs +97 -0
  73. package/src/main/lib/epic/epicEventLog.cjs +214 -0
  74. package/src/main/lib/epic/epicMint.cjs +43 -1
  75. package/src/main/lib/epic/epicOutsideRead.cjs +1 -0
  76. package/src/main/lib/epic/epicOutsideState.cjs +18 -4
  77. package/src/main/lib/epic/epicPurge.cjs +347 -0
  78. package/src/main/lib/epic/epicReopen.cjs +5 -2
  79. package/src/main/lib/epic/epicSettle.cjs +4 -13
  80. package/src/main/lib/epic/epicSpawnPlan.cjs +57 -4
  81. package/src/main/lib/epic/epicStatusMirror.cjs +34 -1
  82. package/src/main/lib/epic/epicTransitions.cjs +139 -0
  83. package/src/main/lib/epic/epicValidationHook.cjs +81 -2
  84. package/src/main/lib/epic/guardSpawnSettings.cjs +3 -2
  85. package/src/main/lib/externalContract.cjs +37 -4
  86. package/src/main/lib/feedback-remote/crossProjectReply.cjs +389 -126
  87. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -3
  88. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +11 -6
  89. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +26 -1
  90. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +5 -2
  91. package/src/main/lib/feedback-remote/feedbackBoxDrain.cjs +409 -0
  92. package/src/main/lib/feedback-remote/feedbackBoxKeys.cjs +218 -0
  93. package/src/main/lib/feedback-remote/feedbackEnvelope.cjs +163 -0
  94. package/src/main/lib/feedback-remote/feedbackRelayClient.cjs +164 -0
  95. package/src/main/lib/feedback-remote/feedbackReport.cjs +234 -0
  96. package/src/main/lib/feedback-remote/feedbackSeal.cjs +217 -0
  97. package/src/main/lib/feedback-remote/localAdminHttp.cjs +108 -2
  98. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +2 -1
  99. package/src/main/lib/feedback-remote/needsYouIpc.cjs +17 -0
  100. package/src/main/lib/feedback-remote/needsYouStore.cjs +177 -6
  101. package/src/main/lib/feedback-remote/pendingReplies.cjs +189 -0
  102. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +188 -10
  103. package/src/main/lib/feedback-remote/serviceClient.cjs +429 -0
  104. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +252 -0
  105. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +284 -0
  106. package/src/main/lib/feedback-remote/servicePairings.cjs +313 -0
  107. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +290 -0
  108. package/src/main/lib/feedback-remote/siteFeedbackAdminRoutes.cjs +295 -0
  109. package/src/main/lib/feedback-remote/siteFeedbackInbox.cjs +598 -0
  110. package/src/main/lib/feedback-remote/siteFeedbackIpc.cjs +86 -0
  111. package/src/main/lib/feedback-remote/siteFeedbackService.cjs +477 -0
  112. package/src/main/lib/git/worktreeDeps.cjs +77 -2
  113. package/src/main/lib/mcpToolCatalog.cjs +315 -30
  114. package/src/main/lib/opsOwnership.cjs +29 -1
  115. package/src/main/lib/opsRetentionSettings.cjs +27 -5
  116. package/src/main/lib/persona-macro/builtinMacros.cjs +7 -2
  117. package/src/main/lib/persona-macro/macroJobDispatch.cjs +52 -8
  118. package/src/main/lib/persona-macro/macroJobIpc.cjs +16 -6
  119. package/src/main/lib/persona-macro/macroLibrary.cjs +49 -7
  120. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +83 -0
  121. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +3 -0
  122. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +263 -0
  123. package/src/main/lib/phaseProjection.cjs +103 -0
  124. package/src/main/lib/prd/depSlugResolve.cjs +4 -13
  125. package/src/main/lib/prd/prdBodyPatch.cjs +12 -17
  126. package/src/main/lib/prd/prdCreate.cjs +67 -5
  127. package/src/main/lib/prd/prdCriteria.cjs +225 -0
  128. package/src/main/lib/prd/prdFrontmatter.cjs +68 -3
  129. package/src/main/lib/prd/prdGateFiles.cjs +125 -49
  130. package/src/main/lib/prd/prdSizing.cjs +3 -1
  131. package/src/main/lib/process/cleanEnv.cjs +52 -1
  132. package/src/main/lib/process/leftoverRenice.cjs +178 -0
  133. package/src/main/lib/process/memoryScope.cjs +31 -3
  134. package/src/main/lib/project-pages/pagesLibrary.cjs +72 -6
  135. package/src/main/lib/project-pages/videoReviewIpc.cjs +3 -2
  136. package/src/main/lib/project-pages/voiceAdminRoutes.cjs +175 -0
  137. package/src/main/lib/project-pages/voicePreview.cjs +196 -0
  138. package/src/main/lib/project-pages/voicesIpc.cjs +186 -0
  139. package/src/main/lib/promptSessionSchema.cjs +6 -0
  140. package/src/main/lib/scheduler/cancelledRow.cjs +57 -0
  141. package/src/main/lib/scheduler/cpuSample.cjs +133 -42
  142. package/src/main/lib/scheduler/criteriaChecks.cjs +169 -0
  143. package/src/main/lib/scheduler/definitionOfDone.cjs +44 -5
  144. package/src/main/lib/scheduler/jobMemoryStats.cjs +313 -0
  145. package/src/main/lib/scheduler/loadGate.cjs +82 -4
  146. package/src/main/lib/scheduler/planRecordHarvest.cjs +32 -2
  147. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +133 -0
  148. package/src/main/lib/scheduler/preflightCheck.cjs +97 -0
  149. package/src/main/lib/scheduler/reviewNotice.cjs +39 -0
  150. package/src/main/lib/scheduler/runLogRetention.cjs +42 -1
  151. package/src/main/lib/scheduler/scheduleJobSchema.cjs +5 -0
  152. package/src/main/lib/scheduler/scheduleJobTransitions.cjs +47 -0
  153. package/src/main/lib/scheduler/schedulerConfig.cjs +47 -0
  154. package/src/main/lib/scheduler/schedulerPaths.cjs +0 -3
  155. package/src/main/lib/scheduler/schedulerRuntimeState.cjs +50 -1
  156. package/src/main/lib/scheduler/sessionSlots.cjs +5 -1
  157. package/src/main/lib/scheduler/slotsRoute.cjs +237 -0
  158. package/src/main/lib/scheduler/toolClearance.cjs +258 -0
  159. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +140 -10
  160. package/src/main/lib/tasks/memoryConsolidation.cjs +300 -0
  161. package/src/main/lib/tasks/mitigationReview.cjs +294 -0
  162. package/src/main/lib/tasks/taskAdminRoutes.cjs +312 -22
  163. package/src/main/lib/tasks/taskIpc.cjs +22 -18
  164. package/src/main/lib/tasks/taskLedger.cjs +147 -25
  165. package/src/main/lib/tasks/taskRun.cjs +186 -17
  166. package/src/main/lib/tasks/taskSwitch.cjs +85 -12
  167. package/src/main/lib/tasks/taskSwitchRoute.cjs +172 -0
  168. package/src/main/lib/telemetry/auditEvents.cjs +207 -6
  169. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +198 -6
  170. package/src/main/lib/telemetry/webhookDelivery.cjs +205 -0
  171. package/src/main/lib/telemetry/webhookRegistry.cjs +281 -0
  172. package/src/main/lib/toolUseClassify.cjs +181 -0
  173. package/src/main/lib/util/smfileRange.cjs +77 -0
  174. package/src/main/projectPages.cjs +3 -1
  175. package/src/main/promptSessionEvents.cjs +5 -0
  176. package/src/main/pty.cjs +68 -0
  177. package/src/main/queueOps.cjs +32 -13
  178. package/src/main/runVerify.cjs +74 -9
  179. package/src/main/scheduler/AGENTS.md +1 -0
  180. package/src/main/scheduler/budget.cjs +6 -5
  181. package/src/main/scheduler/prdParser.cjs +62 -14
  182. package/src/main/scheduler/reviewLadder.cjs +45 -28
  183. package/src/main/scheduler/starvation.cjs +69 -0
  184. package/src/main/scheduler/utilizationHold.cjs +101 -0
  185. package/src/main/scheduler.cjs +1745 -210
  186. package/src/main/templates/PRD_AUTHORING.md +13 -2
  187. package/src/main/webRemote.cjs +463 -6
  188. package/src/preload/api.d.ts +529 -38
  189. package/src/preload/apiSurface.json +209 -7
  190. package/src/preload/index.cjs +46 -1
  191. package/src/seed/agents/architect.md +6 -1
  192. package/src/seed/agents/blender-artist.md +2 -1
  193. package/src/seed/agents/competitive-analyst.md +3 -1
  194. package/src/seed/agents/competitive-researcher.md +2 -1
  195. package/src/seed/agents/demo-video-builder.md +87 -83
  196. package/src/seed/agents/dev-lead.md +3 -3
  197. package/src/seed/agents/project-home-builder.md +9 -31
  198. package/src/seed/agents/validator.md +9 -10
  199. package/dist/assets/AppSettings-CMFEM68R.js +0 -2
  200. package/dist/assets/HomeClaudeConfig-ijEXs--3.js +0 -3
  201. package/dist/assets/Scheduler-YT3j8SUa.js +0 -16
  202. package/dist/assets/ViewTabs-B7qLXRAH.js +0 -1
  203. package/dist/assets/index-CtxruO1L.js +0 -3121
  204. package/src/main/lib/epic/epicStateWatcher.cjs +0 -157
@@ -216,7 +216,124 @@ function checkAudioHasSpeech({ html } = {}) {
216
216
  }
217
217
  }
218
218
 
219
- // input: {captions, narration (string|string[]), closing, lines, speechS, lengthS, frames, blankThreshold, html, bytes}
219
+ // ---- TikTok checks (run by runChecks only when input.tiktok is present) -------------------
220
+ const TIKTOK_CHECK_IDS = Object.freeze(['tiktok-hook', 'tiktok-cadence', 'tiktok-payoff', 'tiktok-loop', 'tiktok-safe-zone', 'tiktok-post-caption']);
221
+ const HOOK_BY_S = 3.0;
222
+ const MAX_CUT_GAP_S = 3.0;
223
+ const PAYOFF_WINDOW_S = 5;
224
+ const LOOP_WINDOW_S = 2;
225
+ // Max allowed |last - first| for both luma mean and luma stddev (0..255 scale) for a seamless loop.
226
+ const LOOP_LUMA_TOLERANCE = 12;
227
+ const SAFE_MAX_BOTTOM = 0.8;
228
+ const SAFE_MAX_RIGHT = 0.85;
229
+ const MAX_POST_CAPTION_CHARS = 150;
230
+ const MAX_POST_HASHTAGS = 2;
231
+ const MAX_POST_EMOJI = 1;
232
+
233
+ const num = (v) => (v == null || v === '' ? NaN : Number(v));
234
+
235
+ function checkHookBy(hook) {
236
+ const h = num(hook);
237
+ const ok = Number.isFinite(h) && h >= 0 && h <= HOOK_BY_S;
238
+ return result('tiktok-hook', ok, Number.isFinite(h) ? `hook beat at ${h}s (max ${HOOK_BY_S}s)` : 'hook beat missing');
239
+ }
240
+
241
+ function checkCutCadence(cuts, lengthS) {
242
+ const total = num(lengthS);
243
+ if (!(total > 0)) return result('tiktok-cadence', false, 'lengthS > 0 is required');
244
+ const list = (Array.isArray(cuts) ? cuts : []).map(Number).filter(Number.isFinite);
245
+ const pts = [0, ...list.filter((c) => c > 0 && c < total), total].sort((a, b) => a - b);
246
+ let worst = { gap: 0, from: 0, to: 0 };
247
+ for (let i = 1; i < pts.length; i++) {
248
+ const gap = pts[i] - pts[i - 1];
249
+ if (gap > worst.gap) worst = { gap, from: pts[i - 1], to: pts[i] };
250
+ }
251
+ const ok = worst.gap <= MAX_CUT_GAP_S + 1e-9;
252
+ return result('tiktok-cadence', ok,
253
+ ok ? `${list.length} cut(s), longest gap ${worst.gap.toFixed(2)}s (max ${MAX_CUT_GAP_S}s)`
254
+ : `gap ${worst.gap.toFixed(2)}s from ${worst.from}s to ${worst.to}s exceeds ${MAX_CUT_GAP_S}s`);
255
+ }
256
+
257
+ function checkPayoff(payoff, lengthS) {
258
+ const p = num(payoff); const total = num(lengthS);
259
+ if (!Number.isFinite(p)) return result('tiktok-payoff', false, 'payoff beat missing');
260
+ if (!(total > 0)) return result('tiktok-payoff', false, 'lengthS > 0 is required');
261
+ const ok = p >= total - PAYOFF_WINDOW_S && p <= total;
262
+ return result('tiktok-payoff', ok, `payoff beat at ${p}s (must be within the last ${PAYOFF_WINDOW_S}s of ${total}s)`);
263
+ }
264
+
265
+ const frameMean = (f) => num(f && (f.lumaMean != null ? f.lumaMean : f.mean));
266
+ const frameStd = (f) => num(f && (f.lumaStdDev != null ? f.lumaStdDev : f.lumaStddev));
267
+
268
+ // frames: [{t, lumaMean, lumaStdDev}] from frames.cjs sampleFrames.
269
+ function checkLoopEnding(loop, lengthS, frames) {
270
+ const id = 'tiktok-loop';
271
+ const l = num(loop); const total = num(lengthS);
272
+ if (!Number.isFinite(l)) return result(id, false, 'loop beat missing');
273
+ if (!(total > 0)) return result(id, false, 'lengthS > 0 is required');
274
+ if (l < total - LOOP_WINDOW_S) return result(id, false, `loop beat at ${l}s is before ${total - LOOP_WINDOW_S}s`);
275
+ const list = (Array.isArray(frames) ? frames : []).filter((f) => f && Number.isFinite(num(f.t)));
276
+ if (list.length < 2) return result(id, false, 'need at least 2 sampled frames to compare first and last');
277
+ const sorted = [...list].sort((a, b) => num(a.t) - num(b.t));
278
+ const first = sorted[0]; const last = sorted[sorted.length - 1];
279
+ const dm = Math.abs(frameMean(last) - frameMean(first));
280
+ const ds = Math.abs(frameStd(last) - frameStd(first));
281
+ if (!Number.isFinite(dm) || !Number.isFinite(ds)) return result(id, false, 'first/last frame luma stats missing (lumaMean, lumaStdDev)');
282
+ const ok = dm <= LOOP_LUMA_TOLERANCE && ds <= LOOP_LUMA_TOLERANCE;
283
+ return result(id, ok,
284
+ `loop beat at ${l}s; last frame (${last.t}s) vs first (${first.t}s): luma mean diff ${dm.toFixed(2)}, stddev diff ${ds.toFixed(2)} (max ${LOOP_LUMA_TOLERANCE})`);
285
+ }
286
+
287
+ // frames: [{t, textBoxes:[{text, x, y, w, h}]}] with box coords as 0..1 fractions of the viewport.
288
+ function checkSafeZone(frames) {
289
+ const list = Array.isArray(frames) ? frames : [];
290
+ let boxes = 0;
291
+ for (const f of list) {
292
+ for (const b of (f && Array.isArray(f.textBoxes) ? f.textBoxes : [])) {
293
+ boxes++;
294
+ const bottom = num(b.y) + num(b.h); const right = num(b.x) + num(b.w);
295
+ if (bottom > SAFE_MAX_BOTTOM + 1e-9 || right > SAFE_MAX_RIGHT + 1e-9) {
296
+ const where = bottom > SAFE_MAX_BOTTOM + 1e-9 ? `reaches ${(bottom * 100).toFixed(1)}% of height (max ${SAFE_MAX_BOTTOM * 100}%)`
297
+ : `reaches ${(right * 100).toFixed(1)}% of width (max ${SAFE_MAX_RIGHT * 100}%)`;
298
+ return result('tiktok-safe-zone', false, `frame ${f.t}s: text "${String(b.text || '')}" ${where}`);
299
+ }
300
+ }
301
+ }
302
+ return result('tiktok-safe-zone', true, `${boxes} text box(es) in ${list.length} frame(s) inside the safe zone`);
303
+ }
304
+
305
+ const EMOJI_RE = /\p{Extended_Pictographic}/gu;
306
+ const URL_RE = /(https?:\/\/|www\.)\S+|\b[a-z0-9-]+\.(com|net|org|io|run|app|dev|co|ly|me|tv|ai)\b/i;
307
+ function checkPostCaption(postCaption) {
308
+ const t = String(postCaption == null ? '' : postCaption).trim();
309
+ const problems = [];
310
+ const len = [...t].length;
311
+ if (len < 1 || len > MAX_POST_CAPTION_CHARS) problems.push(`${len} chars (must be 1-${MAX_POST_CAPTION_CHARS})`);
312
+ const tags = t.match(/#[\p{L}\p{N}_]+/gu) || [];
313
+ if (tags.length > MAX_POST_HASHTAGS) problems.push(`${tags.length} hashtags (max ${MAX_POST_HASHTAGS})`);
314
+ const emoji = (t.replace(/[\u{1F3FB}-\u{1F3FF}]/gu, '').match(EMOJI_RE) || []).length;
315
+ if (emoji > MAX_POST_EMOJI) problems.push(`${emoji} emoji (max ${MAX_POST_EMOJI})`);
316
+ if (URL_RE.test(t)) problems.push('contains a URL');
317
+ const body = t.replace(/(?:\s*#[\p{L}\p{N}_]+)+\s*$/u, '').trim();
318
+ if (len >= 1 && !/\?$/.test(body)) problems.push('text before trailing hashtags must end with "?"');
319
+ return result('tiktok-post-caption', problems.length === 0,
320
+ problems.length ? problems.join('; ') : `${len} chars, ${tags.length} hashtag(s), ${emoji} emoji, ends with a question`);
321
+ }
322
+
323
+ function runTiktokChecks(tiktok, lengthS, frames) {
324
+ const beats = (tiktok && tiktok.beats) || {};
325
+ return [
326
+ checkHookBy(beats.hook),
327
+ checkCutCadence(tiktok.cuts, lengthS),
328
+ checkPayoff(beats.payoff, lengthS),
329
+ checkLoopEnding(beats.loop, lengthS, frames),
330
+ checkSafeZone(frames),
331
+ checkPostCaption(tiktok.postCaption),
332
+ ];
333
+ }
334
+
335
+ // input: {captions, narration (string|string[]), closing, lines, speechS, lengthS, frames, blankThreshold, html, bytes,
336
+ // tiktok?: {beats: {hook, payoff, loop}, cuts: number[], postCaption}}
220
337
  function runChecks(input = {}) {
221
338
  const out = [];
222
339
  if (input.captions) out.push(checkCaptions(input.captions));
@@ -227,12 +344,14 @@ function runChecks(input = {}) {
227
344
  if (input.frames) out.push(checkBlankFrames(input.frames, input.blankThreshold));
228
345
  if (input.html != null) out.push(checkHtmlLimits({ html: input.html, bytes: input.bytes, lengthS: input.lengthS }));
229
346
  if (typeof input.html === 'string') out.push(checkAudioHasSpeech({ html: input.html }));
347
+ if (input.tiktok && typeof input.tiktok === 'object') out.push(...runTiktokChecks(input.tiktok, input.lengthS, input.frames));
230
348
  return out;
231
349
  }
232
350
 
233
351
  module.exports = {
234
352
  BANNED_WORDS, countSyllables, checkCaptions, lintLanguage, checkClosing, checkVoiceFit,
235
353
  checkSpeechCoverage, checkBlankFrames, checkHtmlLimits, speechModulationShare, checkAudioHasSpeech, runChecks,
354
+ TIKTOK_CHECK_IDS, LOOP_LUMA_TOLERANCE, checkHookBy, checkCutCadence, checkPayoff, checkLoopEnding, checkSafeZone, checkPostCaption,
236
355
  };
237
356
 
238
357
  if (require.main === module) {
@@ -0,0 +1,218 @@
1
+ 'use strict';
2
+ // Demo-video kit exporter: render a finished self-contained video document frame by frame in
3
+ // headless Chromium (window.smDemo.seek(i / fps), never real-time playback), pipe the PNG frames
4
+ // into ffmpeg (image2pipe) muxed with the soundtrack, write outDir/video.mp4 (H.264 yuv420p
5
+ // +faststart, AAC) and outDir/poster.png, then verify the MP4 with ffprobe. Playwright is
6
+ // resolved at runtime (shared playwrightLoader.cjs). Node builtins + this folder only; no shell.
7
+ // CLI: node export.cjs spec.json -> prints the JSON result; exit 0 ok, 1 failed export, 2 bad input.
8
+ const fs = require('fs');
9
+ const path = require('path');
10
+ const { spawn, spawnSync } = require('child_process');
11
+ const { pathToFileURL } = require('url');
12
+ const { loadPlaywright: defaultLoader } = require('./playwrightLoader.cjs');
13
+ const { settleFrame } = require('./frames.cjs');
14
+
15
+ const FFMPEG = process.env.SM_FFMPEG || 'ffmpeg';
16
+ const FFPROBE = process.env.SM_FFPROBE || 'ffprobe';
17
+ const TIMEOUT_MS = 600000;
18
+ const DURATION_TOLERANCE_S = 0.2;
19
+ const SIZE_16_9 = { width: 1920, height: 1080 };
20
+ const SIZE_9_16 = { width: 1080, height: 1920 };
21
+
22
+ /** Export size from the document's sm-demo-aspect meta: 9:16 -> 1080x1920, else 1920x1080. */
23
+ function sizeForHtml(html) {
24
+ const h = String(html || '');
25
+ const m = h.match(/<meta[^>]*name=["']sm-demo-aspect["'][^>]*content=["']([^"']*)["']/i)
26
+ || h.match(/<meta[^>]*content=["']([^"']*)["'][^>]*name=["']sm-demo-aspect["']/i);
27
+ return m && m[1].replace(/\s+/g, '') === '9:16' ? { ...SIZE_9_16 } : { ...SIZE_16_9 };
28
+ }
29
+
30
+ /** ffmpeg argv: PNG frames on stdin + audio file -> H.264/AAC MP4 of exactly lengthS seconds. */
31
+ function ffmpegArgs({ fps, audioPath, lengthS, mp4Path }) {
32
+ return [
33
+ '-hide_banner', '-nostats', '-loglevel', 'error', '-y',
34
+ '-f', 'image2pipe', '-framerate', String(fps), '-c:v', 'png', '-i', 'pipe:0',
35
+ '-i', audioPath,
36
+ '-map', '0:v:0', '-map', '1:a:0',
37
+ '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-r', String(fps),
38
+ '-c:a', 'aac', '-b:a', '192k',
39
+ '-t', String(lengthS),
40
+ '-movflags', '+faststart',
41
+ mp4Path,
42
+ ];
43
+ }
44
+
45
+ function ffprobeArgs(file) {
46
+ return ['-v', 'error', '-print_format', 'json', '-show_streams', '-show_format', file];
47
+ }
48
+
49
+ /**
50
+ * Default ffmpeg runner: spawn without a shell, stream every Buffer from the async iterable
51
+ * `input` into stdin (respecting backpressure), resolve with stderr on exit 0. Rejects when
52
+ * ffmpeg cannot start, exits non-zero, exceeds the timeout, or `input` throws.
53
+ */
54
+ function runFfmpegDefault(args, { input, spawnFn = spawn } = {}) {
55
+ return new Promise((resolve, reject) => {
56
+ let settled = false;
57
+ let stderr = '';
58
+ const child = spawnFn(FFMPEG, args, { stdio: ['pipe', 'ignore', 'pipe'], shell: false });
59
+ const finish = (err, val) => {
60
+ if (settled) return;
61
+ settled = true;
62
+ clearTimeout(timer);
63
+ if (err) { try { child.kill('SIGKILL'); } catch { /* gone */ } reject(err); } else resolve(val);
64
+ };
65
+ const timer = setTimeout(() => finish(new Error(`ffmpeg timed out after ${TIMEOUT_MS / 1000} s`)), TIMEOUT_MS);
66
+ child.on('error', (e) => finish(new Error(`ffmpeg failed to run: ${e.message}`)));
67
+ child.stderr.on('data', (d) => { stderr = (stderr + d).slice(-4000); });
68
+ child.stdin.on('error', () => { /* EPIPE: the exit code reports the cause */ });
69
+ child.on('close', (code) => {
70
+ if (code === 0) finish(null, stderr);
71
+ else finish(new Error(`ffmpeg exited ${code}: ${stderr.slice(-600)}`));
72
+ });
73
+ (async () => {
74
+ if (input) {
75
+ for await (const buf of input) {
76
+ if (settled) return;
77
+ if (!child.stdin.write(buf)) {
78
+ // Wait for drain or close, then drop BOTH listeners so none accumulate per frame.
79
+ await new Promise((r) => {
80
+ const done = () => { child.stdin.off('drain', done); child.off('close', done); r(); };
81
+ child.stdin.once('drain', done);
82
+ child.once('close', done);
83
+ });
84
+ }
85
+ }
86
+ }
87
+ child.stdin.end();
88
+ })().catch((e) => finish(e));
89
+ });
90
+ }
91
+
92
+ /** Default ffprobe runner: returns stdout (JSON text). Throws when ffprobe cannot run or fails. */
93
+ function runFfprobeDefault(args) {
94
+ const r = spawnSync(FFPROBE, args, { encoding: 'utf8', timeout: TIMEOUT_MS, maxBuffer: 16 * 1024 * 1024, shell: false });
95
+ if (r.error) throw new Error(`ffprobe failed to run: ${r.error.message}`);
96
+ if (r.status !== 0) throw new Error(`ffprobe exited ${r.status}: ${String(r.stderr).slice(-600)}`);
97
+ return String(r.stdout || '');
98
+ }
99
+
100
+ /** Compare ffprobe JSON against the expected export -> {ok, detail, durationS}. */
101
+ function verifyProbe(probe, { width, height, lengthS }) {
102
+ const streams = Array.isArray(probe && probe.streams) ? probe.streams : [];
103
+ const v = streams.find((s) => s && s.codec_type === 'video');
104
+ const a = streams.find((s) => s && s.codec_type === 'audio');
105
+ const problems = [];
106
+ if (!v) problems.push('no video stream');
107
+ else {
108
+ if (v.codec_name !== 'h264') problems.push(`video codec ${v.codec_name}, expected h264`);
109
+ if (Number(v.width) !== width || Number(v.height) !== height) problems.push(`size ${v.width}x${v.height}, expected ${width}x${height}`);
110
+ }
111
+ if (!a) problems.push('no audio stream');
112
+ else if (a.codec_name !== 'aac') problems.push(`audio codec ${a.codec_name}, expected aac`);
113
+ const durationS = Number((probe && probe.format && probe.format.duration) ?? (v && v.duration));
114
+ if (!Number.isFinite(durationS)) problems.push('duration unknown');
115
+ else if (Math.abs(durationS - lengthS) > DURATION_TOLERANCE_S + 1e-9) problems.push(`duration ${durationS} s, expected ${lengthS} s (±${DURATION_TOLERANCE_S} s)`);
116
+ return problems.length
117
+ ? { ok: false, detail: `ffprobe verification failed: ${problems.join('; ')}`, durationS }
118
+ : { ok: true, detail: `h264+aac ${width}x${height}, ${durationS} s`, durationS };
119
+ }
120
+
121
+ const fail = (error) => ({ ok: false, error, check: { id: 'export', ok: false, detail: error } });
122
+ const errMsg = (e) => (e && e.message) || String(e);
123
+
124
+ /**
125
+ * Export a video document + soundtrack to outDir/video.mp4 and outDir/poster.png.
126
+ * runFfmpeg(args, {input}) receives an async iterable of PNG Buffers for stdin;
127
+ * runFfprobe(args) returns ffprobe's JSON stdout. Both may be sync or async.
128
+ * Returns {ok:true, mp4Path, posterPath, width, height, durationS, check} | {ok:false, error, check}.
129
+ */
130
+ async function exportVideo({ htmlPath, lengthS, audioPath, outDir, fps = 30, posterAtS, loadPlaywright, runFfmpeg = runFfmpegDefault, runFfprobe = runFfprobeDefault } = {}) {
131
+ const length = Number(lengthS); const rate = Number(fps);
132
+ if (!htmlPath || !audioPath || !outDir || !(length > 0) || !(rate > 0)) return fail('htmlPath, audioPath, outDir, lengthS > 0 and fps > 0 are required');
133
+ const posterT = posterAtS == null ? Math.min(3, length / 2) : Number(posterAtS);
134
+ if (!(posterT >= 0 && posterT <= length)) return fail(`posterAtS must be within 0..${length}`);
135
+ let html;
136
+ try { html = fs.readFileSync(path.resolve(htmlPath), 'utf8'); } catch (e) { return fail(`cannot read htmlPath: ${errMsg(e)}`); }
137
+ if (!fs.existsSync(path.resolve(audioPath))) return fail(`audioPath not found: ${audioPath}`);
138
+
139
+ let chromium;
140
+ try {
141
+ const pw = (loadPlaywright || (() => defaultLoader()))();
142
+ const resolved = pw && typeof pw.then === 'function' ? await pw : pw;
143
+ chromium = resolved && resolved.chromium;
144
+ } catch (e) { return fail(`playwright failed to load: ${errMsg(e)}`); }
145
+ if (!chromium) return fail('playwright not found (no-playwright)');
146
+
147
+ const { width, height } = sizeForHtml(html);
148
+ const frameCount = Math.round(length * rate);
149
+ const out = path.resolve(outDir);
150
+ const mp4Path = path.join(out, 'video.mp4');
151
+ const posterPath = path.join(out, 'poster.png');
152
+ const cleanup = () => { for (const f of [mp4Path, posterPath]) { try { fs.rmSync(f, { force: true }); } catch { /* best effort */ } } };
153
+
154
+ let browser;
155
+ try {
156
+ fs.mkdirSync(out, { recursive: true });
157
+ cleanup();
158
+ browser = await chromium.launch({ headless: true });
159
+ const page = await browser.newPage({ viewport: { width, height } });
160
+ page.setDefaultTimeout(30000);
161
+ await page.goto(pathToFileURL(path.resolve(htmlPath)).href, { timeout: 30000, waitUntil: 'load' });
162
+ await page.evaluate(() => { const d = window.smDemo; if (d && typeof d.pause === 'function') d.pause(); });
163
+ const seekTo = async (t) => {
164
+ await page.evaluate((s) => {
165
+ const d = window.smDemo;
166
+ if (!d || typeof d.seek !== 'function') throw new Error('window.smDemo.seek is missing');
167
+ d.seek(s);
168
+ }, t);
169
+ await settleFrame(page, t);
170
+ };
171
+ async function* frames() {
172
+ for (let i = 0; i < frameCount; i++) {
173
+ await seekTo(i / rate);
174
+ yield await page.screenshot({ type: 'png' });
175
+ }
176
+ }
177
+ await runFfmpeg(ffmpegArgs({ fps: rate, audioPath: path.resolve(audioPath), lengthS: length, mp4Path }), { input: frames() });
178
+ await seekTo(posterT);
179
+ await page.screenshot({ type: 'png', path: posterPath });
180
+ } catch (e) {
181
+ cleanup();
182
+ return fail(errMsg(e));
183
+ } finally {
184
+ if (browser) { try { await browser.close(); } catch { /* already gone */ } }
185
+ }
186
+
187
+ let probe;
188
+ try {
189
+ const text = await runFfprobe(ffprobeArgs(mp4Path));
190
+ probe = typeof text === 'string' ? JSON.parse(text) : text;
191
+ } catch (e) {
192
+ cleanup();
193
+ return fail(`ffprobe: ${errMsg(e)}`);
194
+ }
195
+ const v = verifyProbe(probe, { width, height, lengthS: length });
196
+ if (!v.ok) { cleanup(); return fail(v.detail); }
197
+ return { ok: true, mp4Path, posterPath, width, height, durationS: v.durationS, check: { id: 'export', ok: true, detail: v.detail } };
198
+ }
199
+
200
+ module.exports = { exportVideo, runFfmpegDefault, sizeForHtml, ffmpegArgs, ffprobeArgs, verifyProbe, DURATION_TOLERANCE_S, TIMEOUT_MS };
201
+
202
+ if (require.main === module) {
203
+ let spec;
204
+ try {
205
+ spec = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));
206
+ if (!spec || typeof spec !== 'object') throw new Error('spec must be a JSON object');
207
+ } catch (e) {
208
+ process.stderr.write(`export: ${e.message}\n`);
209
+ process.exit(2);
210
+ }
211
+ exportVideo(spec).then((r) => {
212
+ process.stdout.write(JSON.stringify(r, null, 2) + '\n');
213
+ process.exit(r.ok ? 0 : 1);
214
+ }, (e) => {
215
+ process.stdout.write(JSON.stringify(fail(errMsg(e)), null, 2) + '\n');
216
+ process.exit(1);
217
+ });
218
+ }
@@ -11,6 +11,8 @@ const { pathToFileURL } = require('url');
11
11
 
12
12
  const MAX_FRAMES = 120;
13
13
  const VIEWPORT = { width: 1280, height: 720 };
14
+ const VIEWPORT_9_16 = { width: 1080, height: 1920 };
15
+ const MAX_BOX_TEXT = 60;
14
16
  const TILE_W = 160;
15
17
  const SHEET_COLS = 8;
16
18
  const PNG_SIG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
@@ -130,10 +132,91 @@ function buildContactSheet(images) {
130
132
  return encodePng(W, H, out);
131
133
  }
132
134
 
135
+ /** Viewport for a document: sm-demo-aspect 9:16 -> 1080x1920, anything else -> the default 1280x720. */
136
+ function viewportForHtml(html) {
137
+ const h = String(html || '');
138
+ const m = h.match(/<meta[^>]*name=["']sm-demo-aspect["'][^>]*content=["']([^"']*)["']/i)
139
+ || h.match(/<meta[^>]*content=["']([^"']*)["'][^>]*name=["']sm-demo-aspect["']/i);
140
+ return m && m[1].replace(/\s+/g, '') === '9:16' ? { ...VIEWPORT_9_16 } : { ...VIEWPORT };
141
+ }
142
+
143
+ // Runs in the page: rects of visible elements that directly own non-whitespace text,
144
+ // normalized to the viewport (0..1). Skips display:none, visibility:hidden, opacity 0 (self
145
+ // or ancestor) and zero-size boxes.
146
+ function collectTextBoxes(maxText) {
147
+ const vw = window.innerWidth || 1; const vh = window.innerHeight || 1;
148
+ const hidden = (el) => {
149
+ for (let e = el; e && e.nodeType === 1; e = e.parentElement) {
150
+ const cs = getComputedStyle(e);
151
+ if (cs.display === 'none' || Number(cs.opacity) === 0) return true;
152
+ if (e === el && (cs.visibility === 'hidden' || cs.visibility === 'collapse')) return true;
153
+ }
154
+ return false;
155
+ };
156
+ const out = [];
157
+ for (const el of document.body ? document.body.querySelectorAll('*') : []) {
158
+ if (/^(SCRIPT|STYLE|NOSCRIPT|TEMPLATE)$/.test(el.tagName)) continue;
159
+ let text = '';
160
+ for (const n of el.childNodes) if (n.nodeType === 3) text += n.nodeValue;
161
+ text = text.replace(/\s+/g, ' ').trim();
162
+ if (!text) continue;
163
+ const r = el.getBoundingClientRect();
164
+ if (!(r.width > 0) || !(r.height > 0)) continue;
165
+ if (hidden(el)) continue;
166
+ out.push({ text: text.slice(0, maxText), x: r.left / vw, y: r.top / vh, w: r.width / vw, h: r.height / vh });
167
+ }
168
+ return out;
169
+ }
170
+
171
+ // Upper bound for embedded <video> elements to finish seeking after one smDemo.seek(t).
172
+ const VIDEO_SETTLE_MS = 2000;
173
+
174
+ // Runs in the page after smDemo.seek(t): wait until every <video> is not seeking and has
175
+ // readyState >= 2 (HAVE_CURRENT_DATA), rejecting after timeoutMs, then two animation frames so
176
+ // the settled pixels are painted. A document without <video> goes straight to the two frames.
177
+ function awaitFrameSettled(timeoutMs) {
178
+ const vids = Array.from(document.querySelectorAll('video'));
179
+ const pending = () => vids.filter((v) => v.seeking || !(v.readyState >= 2));
180
+ const paint = () => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
181
+ if (!pending().length) return paint();
182
+ return new Promise((resolve, reject) => {
183
+ const start = Date.now();
184
+ const tick = () => {
185
+ const left = pending();
186
+ if (!left.length) { resolve(); return; }
187
+ if (Date.now() - start >= timeoutMs) {
188
+ reject(new Error(`${left.length} of ${vids.length} <video> element(s) still seeking or not ready after ${timeoutMs} ms`));
189
+ return;
190
+ }
191
+ setTimeout(tick, 10);
192
+ };
193
+ tick();
194
+ }).then(paint);
195
+ }
196
+
197
+ /** Node side: settle the frame for time t, or throw an error naming t (never a stale frame). */
198
+ async function settleFrame(page, t) {
199
+ try {
200
+ await page.evaluate(awaitFrameSettled, VIDEO_SETTLE_MS);
201
+ } catch (e) {
202
+ throw new Error(`frame at t=${t} s: embedded video did not finish seeking: ${(e && e.message) || e}`);
203
+ }
204
+ }
205
+
206
+ const round4 = (v) => Math.round(v * 10000) / 10000;
207
+ function normalizeBoxes(list) {
208
+ return (Array.isArray(list) ? list : []).map((b) => ({
209
+ text: String((b && b.text) || '').slice(0, MAX_BOX_TEXT),
210
+ x: round4(Number(b && b.x) || 0), y: round4(Number(b && b.y) || 0),
211
+ w: round4(Number(b && b.w) || 0), h: round4(Number(b && b.h) || 0),
212
+ }));
213
+ }
214
+
133
215
  /**
134
- * Seek the video document every stepS seconds and report per-frame luma spread.
135
- * Returns {frames:[{t, lumaStdDev, lumaStddev}], contactSheet} | {skipped} | {error}.
136
- * `lumaStddev` mirrors `lumaStdDev` because checkBlankFrames reads that spelling.
216
+ * Seek the video document every stepS seconds and report per-frame luma stats and text boxes.
217
+ * Returns {frames:[{t, lumaMean, lumaStdDev, lumaStddev, textBoxes}], beats, cuts, viewport, contactSheet}
218
+ * | {skipped} | {error}. `lumaStddev` mirrors `lumaStdDev` because checkBlankFrames reads that spelling.
219
+ * beats/cuts are window.smDemo.beats / window.smDemo.cuts (null when absent).
137
220
  */
138
221
  async function sampleFrames({ htmlPath, lengthS, stepS = 0.5, outDir, loadPlaywright } = {}) {
139
222
  const length = Number(lengthS); const step = Number(stepS);
@@ -145,23 +228,35 @@ async function sampleFrames({ htmlPath, lengthS, stepS = 0.5, outDir, loadPlaywr
145
228
  const chromium = resolved && resolved.chromium;
146
229
  if (!chromium) return { skipped: 'no-playwright' };
147
230
 
231
+ let html = '';
232
+ try { html = fs.readFileSync(path.resolve(htmlPath), 'utf8'); } catch { /* page load reports it */ }
233
+ const viewport = viewportForHtml(html);
148
234
  fs.mkdirSync(outDir, { recursive: true });
149
235
  const frames = []; const images = [];
236
+ let beats = null; let cuts = null;
150
237
  let browser;
151
238
  try { browser = await chromium.launch({ headless: true }); } catch { return { skipped: 'no-playwright' }; } // package without a browser binary
152
239
  try {
153
- const page = await browser.newPage({ viewport: VIEWPORT });
240
+ const page = await browser.newPage({ viewport });
154
241
  page.setDefaultTimeout(30000);
155
242
  await page.goto(pathToFileURL(path.resolve(htmlPath)).href, { timeout: 30000, waitUntil: 'load' });
156
243
  await page.evaluate(() => { const d = window.smDemo; if (d && typeof d.pause === 'function') d.pause(); });
244
+ const meta = await page.evaluate(() => {
245
+ const d = window.smDemo;
246
+ const plain = (v) => { try { return v == null ? null : JSON.parse(JSON.stringify(v)); } catch { return null; } };
247
+ return { beats: plain(d && d.beats), cuts: plain(d && d.cuts) };
248
+ });
249
+ beats = (meta && meta.beats) ?? null;
250
+ cuts = (meta && meta.cuts) ?? null;
157
251
  for (let i = 0; i < count; i++) {
158
252
  const t = Math.round(i * step * 1000) / 1000;
159
253
  await page.evaluate((s) => { const d = window.smDemo; if (d && typeof d.seek === 'function') d.seek(s); }, t);
160
- await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))));
254
+ try { await settleFrame(page, t); } catch (e) { return { error: e.message }; }
255
+ const textBoxes = normalizeBoxes(await page.evaluate(collectTextBoxes, MAX_BOX_TEXT));
161
256
  const img = decodePng(await page.screenshot({ type: 'png' }));
162
- const { stdDev } = lumaStats(img);
257
+ const { mean, stdDev } = lumaStats(img);
163
258
  const v = Math.round(stdDev * 100) / 100;
164
- frames.push({ t, lumaStdDev: v, lumaStddev: v });
259
+ frames.push({ t, lumaMean: Math.round(mean * 100) / 100, lumaStdDev: v, lumaStddev: v, textBoxes });
165
260
  images.push(img);
166
261
  }
167
262
  } finally {
@@ -169,7 +264,7 @@ async function sampleFrames({ htmlPath, lengthS, stepS = 0.5, outDir, loadPlaywr
169
264
  }
170
265
  const contactSheet = path.join(outDir, 'contact-sheet.png');
171
266
  fs.writeFileSync(contactSheet, buildContactSheet(images));
172
- return { frames, contactSheet };
267
+ return { frames, beats, cuts, viewport, contactSheet };
173
268
  }
174
269
 
175
- module.exports = { MAX_FRAMES, sampleFrames, decodePng, encodePng, lumaStats, buildContactSheet };
270
+ module.exports = { MAX_FRAMES, VIDEO_SETTLE_MS, awaitFrameSettled, settleFrame, VIEWPORT_9_16, sampleFrames, viewportForHtml, collectTextBoxes, decodePng, encodePng, lumaStats, buildContactSheet };
@@ -0,0 +1,121 @@
1
+ # Playbook: Marketing kind
2
+
3
+ Read this when the `Video kind:` line is Marketing. It is for the demo-video-builder persona: short
4
+ imperative rules for one open-web video, the kind that plays on the product's landing page.
5
+
6
+ This playbook overrides four persona rules: the scene order, the drawn-scene fallback for the
7
+ product, the title card, and the close. Everything else in the persona still holds: plain language,
8
+ the claims list, the voice-first rule, the character, the keystone holds after the opening 3 s, the
9
+ kit-tool failure rule, and the single save call.
10
+
11
+ ## Format
12
+
13
+ - Stage: 16:9, 1280x720 logical pixels, scaled to fit with letterboxing. export.cjs writes it as
14
+ 1920x1080. Do not add an `sm-demo-aspect` meta of 9:16.
15
+ - Length: 30 s or 60 s, nothing else. The duration meta and `smDemo.duration` both say it.
16
+ - The first 3 s show what the product does for the visitor: the real product on screen doing the
17
+ one thing, with one line that names the gain. No logo sting, no title card, no fade from black.
18
+ - It works autoplay-muted: captions carry every point the narration makes, at most 12 words each,
19
+ large and high-contrast. A visitor who never turns the sound on still gets the whole story.
20
+ - The project persona hosts it: the project's own saved character, voice and look. Never borrow
21
+ another project's host or mascot.
22
+
23
+ ## Story
24
+
25
+ The story runs value, then proof, then a call to action. Nothing else.
26
+
27
+ - Value: what the visitor gets, in their words.
28
+ - Proof: the product doing it, in real captures, one thing per moment.
29
+ - Call to action: one plain line that sends the visitor to the landing URL.
30
+
31
+ ### The 30 s story spine
32
+
33
+ | Beat | Time | What is on screen |
34
+ | --- | --- | --- |
35
+ | Value hook | 0-3 s | The product doing the one thing; one line naming the gain |
36
+ | Reveal | 3-8 s | The product in full, first clear look |
37
+ | Proof moments | 8-22 s | Two or three moments, 5-7 s each, one thing the visitor can do per moment |
38
+ | Payoff | 22-26 s | What the visitor ends up with, shown |
39
+ | Call to action | 26-30 s | The landing URL as plain text, and the line that sends them there |
40
+
41
+ For 60 s keep the same five beats in the same order: stretch the reveal to 8 s and use up to five
42
+ proof moments. Never pad with invented claims; use longer holds instead.
43
+
44
+ ## Product shots
45
+
46
+ - Show the product only through real captures of the live product, made with capture.cjs. Never
47
+ a drawn fake screen, a mock-up, or a hand-built imitation of the interface.
48
+ - Ask capture.cjs for real clips for the reveal and for each proof moment: shots of
49
+ `{ kind: 'clip', durationS: 4 }`, with `durationS` from 2 to 6. Use image shots for the rest,
50
+ within the 6-shot limit.
51
+ - A clip's `durationS` must be a number: a string (`'3'`) or `null` becomes the 4 s default, as
52
+ does a missing value. capture.cjs clamps every value to 2-6 s; the clip starts on the settled page
53
+ (the load lead-in is trimmed off). A clip that comes out shorter than `durationS` minus one frame
54
+ (a page that redirects can do this) is dropped with the reason `too-short`.
55
+ - A clip comes back as an `items` entry with `kind: 'clip'`, `mime: 'video/mp4'`, `file`, `bytes`,
56
+ `durationS` and `focus`. A clip capture.cjs could not make is listed in `dropped` with its
57
+ `reason`. For every dropped clip, use a screenshot of that moment with camera moves instead: a
58
+ slow push in, a pan across, a pull out to the focus rect it returned.
59
+
60
+ ### Embedding a clip
61
+
62
+ - Read the clip's `file` and embed it inline as base64, never a file path or a URL (the write tool
63
+ rejects any http src):
64
+ `<video muted playsinline preload="auto" src="data:video/mp4;base64,..."></video>`.
65
+ - No `controls`, no `autoplay`, no `loop`. The clip never plays on its own clock; `seek(t)` drives it.
66
+ - Give each clip a start time `clipStart` on the timeline. In `smDemo.seek(t)`, while the clip is
67
+ on screen, set `video.currentTime = t - clipStart` and call `video.pause()`. Clamp to the clip's
68
+ `durationS`, and hold its last frame after that. Do the same when the document plays in real
69
+ time: its play loop calls `seek(t)`, so frames.cjs, checks.cjs and export.cjs see the exact frame
70
+ for every `t`. frames.cjs and export.cjs wait for each `<video>` to finish seeking.
71
+ - Clips count toward the document size cap (2 MiB per started 30 s of length). Base64 adds about a
72
+ third to each clip's `bytes`. Add up every clip and image before you embed them; when the sum
73
+ would pass the cap, swap the lowest-value clip for a screenshot with camera moves.
74
+ - View every capture before you use it. Drop any that shows an error, a blank page, a loading
75
+ state or a sign-in screen.
76
+ - When capture.cjs returns nothing usable, say so in the report and keep the product off screen:
77
+ words and simple props only, never a drawn screen.
78
+
79
+ ## Landing URL
80
+
81
+ - Take the landing URL from the `Video target:` line when it names one. Otherwise use the
82
+ manifest's `homepage`, or a live URL in the README. Never invent one, never guess a domain.
83
+ - Show it on the call-to-action card as plain text, never an `<a>` tag (the write tool rejects
84
+ outbound links). Say its short form aloud.
85
+ - Never close on a shell command, an install line or a code host page when a landing URL exists.
86
+ - With no landing URL at all, close on the project's name and one plain line on what it does.
87
+
88
+ ## Grounding
89
+
90
+ - Every claim comes from what you read: the README, the landing copy, the docs.
91
+ - Save every claim in `meta.sources` as `{claim, source, ref}`, where `source` is a verbatim span
92
+ copied from what was read and `ref` names the file or page. A claim with no verbatim span is cut.
93
+ - No invented numbers, features, customers, quotes or prices.
94
+ - Never claim the host is a human and never give a location.
95
+
96
+ ## Language
97
+
98
+ - Say "you". Say what the visitor can do, never how it was built.
99
+ - Short sentences in plain words. Run checks.cjs `lintLanguage` over the narration and the
100
+ captions (pass them as `narration` in the input JSON); it must pass: no sentence over 14 words,
101
+ reading grade 8 or under, and none of its `BANNED_WORDS`.
102
+ - Also never use these words and phrases, which `BANNED_WORDS` does not catch: "honestly",
103
+ "actually", "genuinely", "kind of", "sort of", "a bit", "underrated", "nuance", "resonate",
104
+ "load-bearing", "hot take", "unpopular opinion", "the real reason", "nobody tells you",
105
+ "most people don't realize". Check for them yourself before you save.
106
+ - At most one exclamation mark in the whole script.
107
+
108
+ ## Kit checks
109
+
110
+ Run the kit from `~/.claude/session-manager/demo-video-kit/` exactly as the persona says, plus:
111
+
112
+ - capture.cjs: `capture({ url, outDir, shots })` against the live product, at most 6 shots.
113
+ - checks.cjs: the language lint above, plus the persona's caption, closing and voice-fit checks.
114
+ All must pass before you save.
115
+ - sound.cjs: `mix({ narrationWav, cues, style, lengthS, out })` lays the narration over the music
116
+ bed. The bed is ducked under speech, stays audible between lines, and the mix is normalised to
117
+ -14 LUFS. When the project has a saved character with a command voice, speak its lines with
118
+ `node character.cjs speak spec.json` first.
119
+ - export.cjs: `node export.cjs spec.json` with `{ htmlPath, lengthS, audioPath, outDir }` writes
120
+ `video.mp4` (1920x1080, H.264/AAC) and `poster.png` in `outDir`. It must exit 0. The poster is
121
+ the frame a visitor sees before play, so pick `posterAtS` on the value hook or the payoff.