claude-code-session-manager 0.127.0 → 0.128.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 (76) hide show
  1. package/dist/assets/{AgentLibrary-DKQznr7o.js → AgentLibrary-cNQU5YWy.js} +1 -1
  2. package/dist/assets/{Button-CZXqmIiM.js → Button-9dIPAOBg.js} +1 -1
  3. package/dist/assets/{DataModel-piyV33To.js → DataModel-DrDJ6ysw.js} +1 -1
  4. package/dist/assets/{History-BxwtrKF2.js → History-4rrDdWNP.js} +1 -1
  5. package/dist/assets/{Hooks-DogeSPII.js → Hooks-Bj_jF5Pa.js} +1 -1
  6. package/dist/assets/{Library-BDt6EeQQ.js → Library-D-Wsxrh7.js} +1 -1
  7. package/dist/assets/{ListDetail-CwS-LKar.js → ListDetail-D7Om0H8j.js} +1 -1
  8. package/dist/assets/{McpServers-D2HVljgS.js → McpServers-CbIbSd5o.js} +1 -1
  9. package/dist/assets/{Memory-hNzuOGn8.js → Memory-DgQlvQrO.js} +1 -1
  10. package/dist/assets/{Panel-BLDrsUeq.js → Panel-DZHiD8Ar.js} +1 -1
  11. package/dist/assets/{Permissions-DzZ5vaJW.js → Permissions-CfzduF4B.js} +1 -1
  12. package/dist/assets/{Plugins-Cz9yaxzG.js → Plugins-D-AG5nAo.js} +2 -2
  13. package/dist/assets/{ProvenanceBadge-CCgLO4m9.js → ProvenanceBadge-B9JSEjll.js} +1 -1
  14. package/dist/assets/{SaveBar-Shmn699J.js → SaveBar-mVKig6hL.js} +1 -1
  15. package/dist/assets/{Scheduler-Bqr0WHNd.js → Scheduler-DFTCnh60.js} +1 -1
  16. package/dist/assets/{ScopeSwitcher-CBx1fB5g.js → ScopeSwitcher-s8J-yr7Z.js} +1 -1
  17. package/dist/assets/{Settings-Ci8in-yF.js → Settings-BTmxRMaP.js} +1 -1
  18. package/dist/assets/{SkillReferenceGraph-BWwljba8.js → SkillReferenceGraph-C5lKqf5y.js} +1 -1
  19. package/dist/assets/{Skills-BON6o-c4.js → Skills-CxOacq0k.js} +1 -1
  20. package/dist/assets/{SystemPrompt-D5epIYYs.js → SystemPrompt-BCWg5FAz.js} +1 -1
  21. package/dist/assets/{TagLibrary-C2qDZROJ.js → TagLibrary-BnF0_PkG.js} +1 -1
  22. package/dist/assets/{TiptapBody-SZhI3-bW.js → TiptapBody-C2Iu6rZd.js} +1 -1
  23. package/dist/assets/{Toggle-C_qFDG0g.js → Toggle-C-oD66BG.js} +1 -1
  24. package/dist/assets/{ViewTabs-C9q5WCEd.js → ViewTabs-Cs4v7vLY.js} +1 -1
  25. package/dist/assets/{historyTotals-BCl7IOhY.js → historyTotals-CbRSLD8f.js} +1 -1
  26. package/dist/assets/{index-BnKaYERU.css → index-DtdWBGrI.css} +1 -1
  27. package/dist/assets/index-DzY_GXYY.js +3081 -0
  28. package/dist/assets/{settingsSchema-BBrRBrBr.js → settingsSchema-bSBfHuan.js} +1 -1
  29. package/dist/assets/{skillFrontmatter-B01qJk6N.js → skillFrontmatter-BEseWm8r.js} +1 -1
  30. package/dist/assets/{useAgentsDirWatch-CuR3GSjS.js → useAgentsDirWatch-CdyHxKCI.js} +1 -1
  31. package/dist/index.html +2 -2
  32. package/dist-web/app.css +1 -1
  33. package/dist-web/app.js +343 -341
  34. package/package.json +1 -1
  35. package/scripts/scheduler-mcp-server.cjs +170 -6
  36. package/src/main/build-info.json +4 -4
  37. package/src/main/index.cjs +14 -0
  38. package/src/main/ipcSchemas.cjs +107 -0
  39. package/src/main/lib/claude/agentModelResolve.cjs +26 -7
  40. package/src/main/lib/claude/personaToolScope.cjs +40 -2
  41. package/src/main/lib/demo-video-kit/capture.cjs +113 -0
  42. package/src/main/lib/demo-video-kit/character.cjs +97 -0
  43. package/src/main/lib/demo-video-kit/checks.cjs +150 -0
  44. package/src/main/lib/demo-video-kit/frames.cjs +200 -0
  45. package/src/main/lib/demo-video-kit/seedKit.cjs +52 -0
  46. package/src/main/lib/demo-video-kit/sound.cjs +312 -0
  47. package/src/main/lib/epic/epicValidationHook.cjs +17 -1
  48. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +185 -34
  49. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +15 -0
  50. package/src/main/lib/mcpToolCatalog.cjs +71 -11
  51. package/src/main/lib/opsOwnership.cjs +9 -5
  52. package/src/main/lib/persona-macro/builtinMacros.cjs +19 -5
  53. package/src/main/lib/persona-macro/macroJobDispatch.cjs +116 -0
  54. package/src/main/lib/persona-macro/macroJobIpc.cjs +50 -0
  55. package/src/main/lib/persona-macro/macroJobStatus.cjs +112 -0
  56. package/src/main/lib/persona-macro/macroLibrary.cjs +16 -0
  57. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +89 -0
  58. package/src/main/lib/prd/prdCreate.cjs +12 -1
  59. package/src/main/lib/prd/prdFrontmatter.cjs +7 -2
  60. package/src/main/lib/project-pages/pagesLibrary.cjs +171 -0
  61. package/src/main/lib/project-pages/playerBridge.cjs +129 -0
  62. package/src/main/lib/scheduler/scheduleJobSchema.cjs +2 -0
  63. package/src/main/lib/smfileHeaders.cjs +11 -3
  64. package/src/main/projectPages.cjs +107 -30
  65. package/src/main/promptSessionsIpc.cjs +131 -0
  66. package/src/main/scheduler/prdParser.cjs +2 -0
  67. package/src/main/scheduler.cjs +26 -9
  68. package/src/main/seedSchedulerMcp.cjs +10 -1
  69. package/src/main/transcripts.cjs +8 -0
  70. package/src/main/webRemote.cjs +3 -1
  71. package/src/preload/api.d.ts +101 -5
  72. package/src/preload/apiSurface.json +70 -0
  73. package/src/preload/index.cjs +13 -0
  74. package/src/seed/agents/demo-video-builder.md +86 -36
  75. package/src/seed/agents/project-home-builder.md +26 -13
  76. package/dist/assets/index-CMIYLbPb.js +0 -3079
@@ -0,0 +1,113 @@
1
+ 'use strict';
2
+ // Demo-video kit capture helper: up to 6 size-budgeted screenshots (and optional short clips)
3
+ // of the live product at one URL. Playwright is resolved at runtime (cwd, then global npm
4
+ // root, or an injected loader) and is never installed here. Node builtins only.
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+ const { spawnSync } = require('child_process');
8
+
9
+ const MAX_SHOTS = 6;
10
+ const IMAGE_BUDGET = 120 * 1024;
11
+ const CLIP_BUDGET = 280 * 1024;
12
+ const QUALITY_STEPS = [80, 65, 52, 40, 30, 20]; // at most 6 tries
13
+ const NAV_TIMEOUT_MS = 30000;
14
+ const VIEWPORT = { width: 1280, height: 720 };
15
+
16
+ function tryRequire(name, paths) {
17
+ try {
18
+ return require(require.resolve(name, { paths }));
19
+ } catch {
20
+ return null;
21
+ }
22
+ }
23
+
24
+ function globalNpmRoot() {
25
+ try {
26
+ const r = spawnSync('npm', ['root', '-g'], { encoding: 'utf8', timeout: 15000 });
27
+ return r.status === 0 ? String(r.stdout).trim() : '';
28
+ } catch {
29
+ return '';
30
+ }
31
+ }
32
+
33
+ /** Default loader: process.cwd() first, then the global npm root. Never installs. */
34
+ function defaultLoader() {
35
+ for (const name of ['playwright', 'playwright-core']) {
36
+ const m = tryRequire(name, [process.cwd()]);
37
+ if (m) return m;
38
+ }
39
+ const root = globalNpmRoot();
40
+ if (root) {
41
+ for (const name of ['playwright', 'playwright-core']) {
42
+ const m = tryRequire(name, [root]);
43
+ if (m) return m;
44
+ }
45
+ }
46
+ return null;
47
+ }
48
+
49
+ async function defaultEncode(page, { kind, quality }) {
50
+ if (kind !== 'image') return null; // clips need an injected encoder; dropped otherwise
51
+ return page.screenshot({ type: 'jpeg', quality });
52
+ }
53
+
54
+ /** Step quality down (<= 6 tries) until the buffer fits the budget; null when it never does. */
55
+ async function fitBudget(encode, page, kind, budget) {
56
+ const steps = kind === 'image' ? QUALITY_STEPS : [QUALITY_STEPS[0], QUALITY_STEPS[2], QUALITY_STEPS[4]];
57
+ for (let i = 0; i < steps.length && i < 6; i++) {
58
+ const buf = await encode(page, { kind, quality: steps[i] });
59
+ if (!buf) return null;
60
+ if (buf.length <= budget) return buf;
61
+ }
62
+ return null;
63
+ }
64
+
65
+ async function focusFor(page, shot) {
66
+ const sel = shot.focusSelector || shot.selector;
67
+ if (sel) {
68
+ try {
69
+ const b = await page.locator(sel).first().boundingBox();
70
+ if (b) return { x: Math.round(b.x), y: Math.round(b.y), w: Math.round(b.width), h: Math.round(b.height) };
71
+ } catch { /* fall through to default */ }
72
+ }
73
+ return { x: Math.round(VIEWPORT.width * 0.25), y: Math.round(VIEWPORT.height * 0.25), w: Math.round(VIEWPORT.width * 0.5), h: Math.round(VIEWPORT.height * 0.5) };
74
+ }
75
+
76
+ async function capture({ url, outDir, shots, max = MAX_SHOTS, loadPlaywright, encode, navTimeoutMs } = {}) {
77
+ if (!url || typeof url !== 'string') return { skipped: 'no-url' };
78
+ const pw = (loadPlaywright || defaultLoader)();
79
+ const resolved = pw && typeof pw.then === 'function' ? await pw : pw;
80
+ const chromium = resolved && resolved.chromium;
81
+ if (!chromium) return { skipped: 'no-playwright' };
82
+
83
+ const cap = Math.max(0, Math.min(Number(max) || MAX_SHOTS, MAX_SHOTS));
84
+ const list = (Array.isArray(shots) && shots.length ? shots : [{}]).slice(0, cap);
85
+ const enc = encode || defaultEncode;
86
+ const timeout = Math.min(Number(navTimeoutMs) || NAV_TIMEOUT_MS, NAV_TIMEOUT_MS);
87
+ fs.mkdirSync(outDir, { recursive: true });
88
+
89
+ const items = [];
90
+ const browser = await chromium.launch({ headless: true });
91
+ try {
92
+ const page = await browser.newPage({ viewport: VIEWPORT });
93
+ page.setDefaultTimeout(timeout);
94
+ await page.goto(url, { timeout, waitUntil: 'load' }); // the only navigation, to the given URL
95
+ for (let i = 0; i < list.length; i++) {
96
+ const shot = list[i] || {};
97
+ const kind = shot.kind === 'clip' ? 'clip' : 'image';
98
+ if (shot.selector) {
99
+ try { await page.locator(shot.selector).first().scrollIntoViewIfNeeded({ timeout }); } catch { /* keep going */ }
100
+ }
101
+ const buf = await fitBudget(enc, page, kind, kind === 'image' ? IMAGE_BUDGET : CLIP_BUDGET);
102
+ if (!buf) continue;
103
+ const file = path.join(outDir, `shot-${String(i + 1).padStart(2, '0')}.${kind === 'image' ? 'jpg' : 'webm'}`);
104
+ fs.writeFileSync(file, buf);
105
+ items.push({ file, kind, bytes: buf.length, focus: await focusFor(page, shot) });
106
+ }
107
+ } finally {
108
+ await browser.close().catch(() => {});
109
+ }
110
+ return { items };
111
+ }
112
+
113
+ module.exports = { capture, IMAGE_BUDGET, CLIP_BUDGET, QUALITY_STEPS };
@@ -0,0 +1,97 @@
1
+ 'use strict';
2
+ // Demo-video kit character: a project's mascot lives in
3
+ // <ops>/project-pages/videos/_character/{character.json,character.js}.
4
+ // Reading is plain file reading; writing goes only through the
5
+ // POST /admin/project-home/character/write route (writer 'project-home').
6
+ // speakWithCommand spawns the user's TTS argv directly — never through a shell.
7
+ const fs = require('node:fs');
8
+ const path = require('node:path');
9
+ const { spawnSync } = require('node:child_process');
10
+ const { opsPath } = require('../opsOwnership.cjs');
11
+
12
+ const MAX_JS_BYTES = 300 * 1024;
13
+ const MAX_JSON_BYTES = 16 * 1024;
14
+ const COMMAND_TIMEOUT_MS = 120000;
15
+
16
+ /** -> null when `c` is a valid character.json object, else a reason string. */
17
+ function validateCharacterJson(c) {
18
+ if (!c || typeof c !== 'object' || Array.isArray(c)) return 'character.json must be an object';
19
+ if (typeof c.name !== 'string' || !c.name.trim()) return 'name must be a non-empty string';
20
+ if (!Array.isArray(c.palette) || c.palette.length === 0 || !c.palette.every((p) => typeof p === 'string' && p)) {
21
+ return 'palette must be a non-empty array of strings';
22
+ }
23
+ const v = c.voice;
24
+ if (!v || typeof v !== 'object') return 'voice is required';
25
+ if (v.engine === 'kokoro') {
26
+ if (typeof v.id !== 'string' || !v.id) return 'voice.id must be a non-empty string for engine kokoro';
27
+ return null;
28
+ }
29
+ if (v.engine === 'command') {
30
+ const cmd = v.command;
31
+ if (!Array.isArray(cmd) || cmd.length === 0 || !cmd.every((a) => typeof a === 'string')) {
32
+ return 'voice.command must be a non-empty string[]';
33
+ }
34
+ if (!cmd[0]) return 'voice.command[0] must be a program name';
35
+ if (!cmd.some((a) => a.includes('{text}'))) return 'voice.command must contain a {text} placeholder';
36
+ if (!cmd.some((a) => a.includes('{out}'))) return 'voice.command must contain an {out} placeholder';
37
+ return null;
38
+ }
39
+ return "voice.engine must be 'kokoro' or 'command'";
40
+ }
41
+
42
+ /** -> null when `js` is acceptable character.js source, else a reason. Needs the
43
+ * route's network checks, so they are injected (avoids a require cycle). */
44
+ function validateCharacterJs(js, networkChecks = []) {
45
+ if (typeof js !== 'string' || !js.trim()) return 'js must be a non-empty string';
46
+ if (Buffer.byteLength(js, 'utf8') > MAX_JS_BYTES) return `js exceeds the ${MAX_JS_BYTES}-byte limit`;
47
+ for (const { re, message } of networkChecks) {
48
+ if (re.test(js)) return `js must not be network-capable: ${message}`;
49
+ }
50
+ return null;
51
+ }
52
+
53
+ function characterDir(projectRoot) {
54
+ return opsPath(projectRoot, 'project-pages', 'videos', '_character');
55
+ }
56
+
57
+ /** -> {json, js} | null (absent or invalid). */
58
+ function readCharacter(projectRoot) {
59
+ try {
60
+ const dir = characterDir(projectRoot);
61
+ const jsonRaw = fs.readFileSync(path.join(dir, 'character.json'), 'utf8');
62
+ if (Buffer.byteLength(jsonRaw, 'utf8') > MAX_JSON_BYTES) return null;
63
+ const json = JSON.parse(jsonRaw);
64
+ if (validateCharacterJson(json)) return null;
65
+ const js = fs.readFileSync(path.join(dir, 'character.js'), 'utf8');
66
+ if (!js.trim()) return null;
67
+ return { json, js };
68
+ } catch {
69
+ return null;
70
+ }
71
+ }
72
+
73
+ /** Substitute {text}/{out} into each argv element; the argv is never joined. */
74
+ function buildCommandArgv(voice, text, out) {
75
+ return voice.command.map((a) => a.split('{text}').join(text).split('{out}').join(out));
76
+ }
77
+
78
+ /** Run the voice command (no shell). -> {ok, status, error?} */
79
+ function speakWithCommand(voice, text, out) {
80
+ if (!voice || voice.engine !== 'command' || validateCharacterJson({ name: 'x', palette: ['x'], voice })) {
81
+ return { ok: false, status: null, error: 'not a valid command voice' };
82
+ }
83
+ const [bin, ...args] = buildCommandArgv(voice, String(text), String(out));
84
+ const r = spawnSync(bin, args, { shell: false, stdio: 'ignore', timeout: COMMAND_TIMEOUT_MS });
85
+ if (r.error) return { ok: false, status: r.status, error: r.error.message };
86
+ return { ok: r.status === 0, status: r.status, ...(r.status === 0 ? {} : { error: `exit ${r.status}` }) };
87
+ }
88
+
89
+ module.exports = {
90
+ readCharacter,
91
+ speakWithCommand,
92
+ buildCommandArgv,
93
+ validateCharacterJson,
94
+ validateCharacterJs,
95
+ characterDir,
96
+ MAX_JS_BYTES,
97
+ };
@@ -0,0 +1,150 @@
1
+ 'use strict';
2
+ // Pure, dependency-free analyzers a demo-video builder must pass before saving.
3
+ // Node builtins only: this folder is copied to ~/.claude/session-manager/demo-video-kit/.
4
+ // Each check returns {id, ok, detail}. CLI: node checks.cjs <input.json> -> JSON, exit 1 on failure.
5
+
6
+ const fs = require('fs');
7
+
8
+ const BANNED_WORDS = Object.freeze([
9
+ 'MCP', 'API', 'SDK', 'CLI', 'repo', 'cron', 'pipeline', 'automation', 'npm', 'pnpm', 'deploy',
10
+ 'backend', 'frontend', 'local-first', 'headless', 'leverage', 'utilize', 'seamless', 'robust',
11
+ 'facilitate', 'sign up now', "don't miss", 'game-changer', 'revolutionary', 'unlock', 'level up',
12
+ 'supercharge', 'best-in-class', 'world-class', 'cutting-edge', 'limited time', 'act now',
13
+ 'buy now', 'skyrocket', 'must-have',
14
+ ]);
15
+
16
+ const MAX_CAPTION_WORDS = 12;
17
+ const MAX_SENTENCE_WORDS = 14;
18
+ const MAX_GRADE = 8;
19
+ const VOICE_FIT_RATIO = 1.2;
20
+ const MIN_SPEECH_COVERAGE = 0.4;
21
+ const BLANK_AFTER_S = 0.5;
22
+ const DEFAULT_BLANK_STDDEV = 3;
23
+ const HTML_MB_PER_30S = 2 * 1024 * 1024;
24
+
25
+ const result = (id, ok, detail) => ({ id, ok: !!ok, detail });
26
+ const words = (s) => String(s || '').split(/\s+/).filter(Boolean);
27
+ const escRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
28
+
29
+ // Syllable heuristic: count vowel groups (aeiouy), drop a trailing silent "e"
30
+ // (but not "-le"), minimum 1 per word. Approximate, good enough for grade lint.
31
+ function countSyllables(word) {
32
+ let w = String(word).toLowerCase().replace(/[^a-z]/g, '');
33
+ if (!w) return 0;
34
+ if (w.length > 2 && /e$/.test(w) && !/[aeiouy]le$/.test(w) && !/[^aeiouy]le$/.test(w)) w = w.slice(0, -1);
35
+ const groups = w.match(/[aeiouy]+/g);
36
+ return Math.max(1, groups ? groups.length : 0);
37
+ }
38
+
39
+ function splitSentences(text) {
40
+ return String(text || '').split(/[.!?]+(?:\s+|$)|\n+/).map((s) => s.trim()).filter((s) => words(s).length);
41
+ }
42
+
43
+ function checkCaptions(captions) {
44
+ const list = Array.isArray(captions) ? captions : [];
45
+ const bad = list.map((c, i) => ({ i, n: words(c).length })).filter((x) => x.n > MAX_CAPTION_WORDS);
46
+ return result('captions', bad.length === 0,
47
+ bad.length ? `caption(s) over ${MAX_CAPTION_WORDS} words: ${bad.map((b) => `#${b.i + 1} (${b.n})`).join(', ')}`
48
+ : `${list.length} caption(s) within ${MAX_CAPTION_WORDS} words`);
49
+ }
50
+
51
+ function findBanned(text) {
52
+ const t = String(text || '');
53
+ return BANNED_WORDS.filter((b) => new RegExp(`(?<![A-Za-z0-9])${escRe(b)}(?![A-Za-z0-9])`, 'i').test(t));
54
+ }
55
+
56
+ function lintLanguage(text) {
57
+ const t = Array.isArray(text) ? text.join('. ') : String(text || '');
58
+ const problems = [];
59
+ const sentences = splitSentences(t);
60
+ const ws = words(t);
61
+ const long = sentences.filter((s) => words(s).length > MAX_SENTENCE_WORDS);
62
+ if (long.length) problems.push(`${long.length} sentence(s) over ${MAX_SENTENCE_WORDS} words`);
63
+ let grade = 0;
64
+ if (ws.length && sentences.length) {
65
+ const syl = ws.reduce((n, w) => n + countSyllables(w), 0);
66
+ grade = 0.39 * (ws.length / sentences.length) + 11.8 * (syl / ws.length) - 15.59;
67
+ if (grade > MAX_GRADE) problems.push(`Flesch-Kincaid grade ${grade.toFixed(1)} > ${MAX_GRADE}`);
68
+ }
69
+ const banned = findBanned(t);
70
+ if (banned.length) problems.push(`banned: ${banned.join(', ')}`);
71
+ return result('language', problems.length === 0,
72
+ problems.length ? problems.join('; ') : `grade ${grade.toFixed(1)}, sentences <= ${MAX_SENTENCE_WORDS} words, no banned words`);
73
+ }
74
+
75
+ const SHELL_CMD = /(?<![A-Za-z0-9-])(npm|npx|pnpm|yarn|git|curl|wget|pip|pip3|brew|sudo|apt|docker)\s+[A-Za-z-]/i;
76
+ function checkClosing(closing) {
77
+ const t = String(closing || '');
78
+ const lead = /^\s*\$/.test(t) || /(^|\n)\s*\$\s/.test(t);
79
+ const m = t.match(SHELL_CMD);
80
+ const ok = !lead && !m;
81
+ return result('closing', ok, ok ? 'closing has no shell command' : `closing contains a shell command (${lead ? 'leading $' : m[0].trim()})`);
82
+ }
83
+
84
+ // lines: [{text?, speechS, sceneS}]
85
+ function checkVoiceFit(lines) {
86
+ const list = Array.isArray(lines) ? lines : [];
87
+ const bad = list.map((l, i) => ({ i, r: l.sceneS > 0 ? l.speechS / l.sceneS : Infinity }))
88
+ .filter((x) => x.r > VOICE_FIT_RATIO);
89
+ return result('voiceFit', bad.length === 0,
90
+ bad.length ? `line(s) need more than ${VOICE_FIT_RATIO}x scene time: ${bad.map((b) => `#${b.i + 1} (${b.r.toFixed(2)}x)`).join(', ')}`
91
+ : `${list.length} line(s) fit within ${VOICE_FIT_RATIO}x`);
92
+ }
93
+
94
+ function checkSpeechCoverage(speechS, lengthS) {
95
+ const total = Number(lengthS) || 0;
96
+ const ratio = total > 0 ? (Number(speechS) || 0) / total : 0;
97
+ return result('speechCoverage', ratio >= MIN_SPEECH_COVERAGE,
98
+ `speech covers ${(ratio * 100).toFixed(0)}% of ${total}s (min ${MIN_SPEECH_COVERAGE * 100}%)`);
99
+ }
100
+
101
+ // frames: [{t, lumaStddev}]; frames after 0.5 s whose stddev < threshold are blank.
102
+ function checkBlankFrames(frames, threshold = DEFAULT_BLANK_STDDEV) {
103
+ const list = Array.isArray(frames) ? frames : [];
104
+ const bad = list.filter((f) => f.t > BLANK_AFTER_S && f.lumaStddev < threshold);
105
+ return result('blankFrames', bad.length === 0,
106
+ bad.length ? `blank frame(s) at ${bad.map((f) => `${f.t}s`).join(', ')}` : `${list.length} frame(s) non-blank`);
107
+ }
108
+
109
+ function checkHtmlLimits({ html, bytes, lengthS } = {}) {
110
+ const h = String(html || '');
111
+ const size = Number.isFinite(bytes) ? bytes : Buffer.byteLength(h);
112
+ const cap = Math.ceil((Number(lengthS) || 0) / 30) * HTML_MB_PER_30S;
113
+ const problems = [];
114
+ if (size > cap) problems.push(`${size} bytes exceeds cap ${cap}`);
115
+ const dur = h.match(/<meta[^>]*name=["']sm-demo-duration["'][^>]*content=["']([^"']*)["']/i)
116
+ || h.match(/<meta[^>]*content=["']([^"']*)["'][^>]*name=["']sm-demo-duration["']/i);
117
+ if (!dur) problems.push('sm-demo-duration meta missing');
118
+ else if (Number(dur[1]) !== Number(lengthS)) problems.push(`sm-demo-duration ${dur[1]} != ${lengthS}`);
119
+ if (!/window\.smDemo\s*=/.test(h) || !/scenes\s*:/.test(h)) problems.push('window.smDemo with scenes missing');
120
+ return result('htmlLimits', problems.length === 0, problems.length ? problems.join('; ') : `${size} bytes within cap ${cap}`);
121
+ }
122
+
123
+ // input: {captions, narration (string|string[]), closing, lines, speechS, lengthS, frames, blankThreshold, html, bytes}
124
+ function runChecks(input = {}) {
125
+ const out = [];
126
+ if (input.captions) out.push(checkCaptions(input.captions));
127
+ if (input.narration != null) out.push(lintLanguage(input.narration));
128
+ if (input.closing != null) out.push(checkClosing(input.closing));
129
+ if (input.lines) out.push(checkVoiceFit(input.lines));
130
+ if (input.speechS != null) out.push(checkSpeechCoverage(input.speechS, input.lengthS));
131
+ if (input.frames) out.push(checkBlankFrames(input.frames, input.blankThreshold));
132
+ if (input.html != null) out.push(checkHtmlLimits({ html: input.html, bytes: input.bytes, lengthS: input.lengthS }));
133
+ return out;
134
+ }
135
+
136
+ module.exports = {
137
+ BANNED_WORDS, countSyllables, checkCaptions, lintLanguage, checkClosing, checkVoiceFit,
138
+ checkSpeechCoverage, checkBlankFrames, checkHtmlLimits, runChecks,
139
+ };
140
+
141
+ if (require.main === module) {
142
+ try {
143
+ const report = runChecks(JSON.parse(fs.readFileSync(process.argv[2], 'utf8')));
144
+ process.stdout.write(JSON.stringify(report, null, 2) + '\n');
145
+ process.exit(report.some((c) => !c.ok) ? 1 : 0);
146
+ } catch (e) {
147
+ process.stderr.write(`checks: ${e.message}\n`);
148
+ process.exit(2);
149
+ }
150
+ }
@@ -0,0 +1,200 @@
1
+ 'use strict';
2
+ // Demo-video kit frame sampler: open a finished video document in headless Chromium, seek
3
+ // window.smDemo every stepS seconds, compute per-frame luma stats (input for checkBlankFrames)
4
+ // and write a contact sheet PNG for the persona to review. Playwright is resolved at runtime
5
+ // (same resolution as capture.cjs) and never installed here. Node builtins only.
6
+ const fs = require('fs');
7
+ const path = require('path');
8
+ const zlib = require('zlib');
9
+ const { spawnSync } = require('child_process');
10
+ const { pathToFileURL } = require('url');
11
+
12
+ const MAX_FRAMES = 120;
13
+ const VIEWPORT = { width: 1280, height: 720 };
14
+ const TILE_W = 160;
15
+ const SHEET_COLS = 8;
16
+ const PNG_SIG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
17
+
18
+ function tryRequire(name, paths) {
19
+ try { return require(require.resolve(name, { paths })); } catch { return null; }
20
+ }
21
+ function globalNpmRoot() {
22
+ try {
23
+ const r = spawnSync('npm', ['root', '-g'], { encoding: 'utf8', timeout: 15000 });
24
+ return r.status === 0 ? String(r.stdout).trim() : '';
25
+ } catch { return ''; }
26
+ }
27
+ /** Same resolution as capture.cjs: process.cwd() first, then the global npm root. */
28
+ function defaultLoader() {
29
+ for (const name of ['playwright', 'playwright-core']) {
30
+ const m = tryRequire(name, [process.cwd()]);
31
+ if (m) return m;
32
+ }
33
+ const root = globalNpmRoot();
34
+ if (root) {
35
+ for (const name of ['playwright', 'playwright-core']) {
36
+ const m = tryRequire(name, [root]);
37
+ if (m) return m;
38
+ }
39
+ }
40
+ return null;
41
+ }
42
+
43
+ // ---- minimal PNG codec -------------------------------------------------------------------
44
+ const CHANNELS = { 0: 1, 2: 3, 4: 2, 6: 4 };
45
+
46
+ /** Decode a non-interlaced 8-bit PNG (gray, RGB, gray+alpha, RGBA) -> {width, height, channels, data}. */
47
+ function decodePng(buf) {
48
+ if (!Buffer.isBuffer(buf) || buf.length < 8 || !buf.subarray(0, 8).equals(PNG_SIG)) throw new Error('not a PNG');
49
+ let pos = 8; let ihdr = null; const idat = [];
50
+ while (pos + 8 <= buf.length) {
51
+ const len = buf.readUInt32BE(pos);
52
+ const type = buf.toString('latin1', pos + 4, pos + 8);
53
+ const body = buf.subarray(pos + 8, pos + 8 + len);
54
+ if (type === 'IHDR') ihdr = body;
55
+ else if (type === 'IDAT') idat.push(body);
56
+ else if (type === 'IEND') break;
57
+ pos += 12 + len;
58
+ }
59
+ if (!ihdr) throw new Error('PNG missing IHDR');
60
+ const width = ihdr.readUInt32BE(0); const height = ihdr.readUInt32BE(4);
61
+ const depth = ihdr[8]; const ctype = ihdr[9]; const interlace = ihdr[12];
62
+ if (depth !== 8 || !CHANNELS[ctype] || interlace !== 0) throw new Error(`unsupported PNG (depth ${depth}, type ${ctype}, interlace ${interlace})`);
63
+ const ch = CHANNELS[ctype];
64
+ const raw = zlib.inflateSync(Buffer.concat(idat));
65
+ const stride = width * ch;
66
+ if (raw.length < (stride + 1) * height) throw new Error('PNG data truncated');
67
+ const out = Buffer.alloc(stride * height);
68
+ for (let y = 0; y < height; y++) {
69
+ const f = raw[y * (stride + 1)];
70
+ const src = y * (stride + 1) + 1; const dst = y * stride;
71
+ for (let i = 0; i < stride; i++) {
72
+ const x = raw[src + i];
73
+ const a = i >= ch ? out[dst + i - ch] : 0;
74
+ const b = y > 0 ? out[dst - stride + i] : 0;
75
+ const c = i >= ch && y > 0 ? out[dst - stride + i - ch] : 0;
76
+ let v;
77
+ if (f === 0) v = x;
78
+ else if (f === 1) v = x + a;
79
+ else if (f === 2) v = x + b;
80
+ else if (f === 3) v = x + ((a + b) >> 1);
81
+ else if (f === 4) {
82
+ const p = a + b - c; const pa = Math.abs(p - a); const pb = Math.abs(p - b); const pc = Math.abs(p - c);
83
+ v = x + (pa <= pb && pa <= pc ? a : pb <= pc ? b : c);
84
+ } else throw new Error(`bad PNG filter ${f}`);
85
+ out[dst + i] = v & 255;
86
+ }
87
+ }
88
+ return { width, height, channels: ch, data: out };
89
+ }
90
+
91
+ let crcTable = null;
92
+ function crc32(buf) {
93
+ if (!crcTable) {
94
+ crcTable = new Int32Array(256);
95
+ for (let n = 0; n < 256; n++) { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; crcTable[n] = c; }
96
+ }
97
+ let c = -1;
98
+ for (let i = 0; i < buf.length; i++) c = crcTable[(c ^ buf[i]) & 255] ^ (c >>> 8);
99
+ return (c ^ -1) >>> 0;
100
+ }
101
+ function chunk(type, body) {
102
+ const t = Buffer.from(type, 'latin1');
103
+ const len = Buffer.alloc(4); len.writeUInt32BE(body.length);
104
+ const crc = Buffer.alloc(4); crc.writeUInt32BE(crc32(Buffer.concat([t, body])));
105
+ return Buffer.concat([len, t, body, crc]);
106
+ }
107
+ /** Encode 8-bit RGB pixels (width*height*3) as a PNG. */
108
+ function encodePng(width, height, rgb) {
109
+ const stride = width * 3;
110
+ const raw = Buffer.alloc((stride + 1) * height);
111
+ for (let y = 0; y < height; y++) rgb.copy(raw, y * (stride + 1) + 1, y * stride, (y + 1) * stride);
112
+ const ihdr = Buffer.alloc(13);
113
+ ihdr.writeUInt32BE(width, 0); ihdr.writeUInt32BE(height, 4); ihdr[8] = 8; ihdr[9] = 2;
114
+ return Buffer.concat([PNG_SIG, chunk('IHDR', ihdr), chunk('IDAT', zlib.deflateSync(raw)), chunk('IEND', Buffer.alloc(0))]);
115
+ }
116
+
117
+ /** Rec.601 luma of every pixel (alpha ignored) -> {mean, stdDev}. */
118
+ function lumaStats(img) {
119
+ const { width, height, channels: ch, data } = img;
120
+ const n = width * height;
121
+ if (!n) return { mean: 0, stdDev: 0 };
122
+ let sum = 0; let sumSq = 0;
123
+ for (let p = 0; p < n; p++) {
124
+ const o = p * ch;
125
+ const l = ch >= 3 ? 0.299 * data[o] + 0.587 * data[o + 1] + 0.114 * data[o + 2] : data[o];
126
+ sum += l; sumSq += l * l;
127
+ }
128
+ const mean = sum / n;
129
+ return { mean, stdDev: Math.sqrt(Math.max(0, sumSq / n - mean * mean)) };
130
+ }
131
+
132
+ function toRgb(img, x, y) {
133
+ const o = (y * img.width + x) * img.channels;
134
+ return img.channels >= 3 ? [img.data[o], img.data[o + 1], img.data[o + 2]] : [img.data[o], img.data[o], img.data[o]];
135
+ }
136
+ /** Nearest-neighbour tile grid of decoded images -> PNG buffer. */
137
+ function buildContactSheet(images) {
138
+ const cols = Math.max(1, Math.min(SHEET_COLS, images.length));
139
+ const rows = Math.max(1, Math.ceil(images.length / cols));
140
+ const first = images[0];
141
+ const tileH = first ? Math.max(1, Math.round(TILE_W * first.height / first.width)) : Math.round(TILE_W * 9 / 16);
142
+ const W = cols * TILE_W; const H = rows * tileH;
143
+ const out = Buffer.alloc(W * H * 3);
144
+ images.forEach((img, i) => {
145
+ const ox = (i % cols) * TILE_W; const oy = Math.floor(i / cols) * tileH;
146
+ for (let y = 0; y < tileH; y++) {
147
+ const sy = Math.min(img.height - 1, Math.floor(y * img.height / tileH));
148
+ for (let x = 0; x < TILE_W; x++) {
149
+ const [r, g, b] = toRgb(img, Math.min(img.width - 1, Math.floor(x * img.width / TILE_W)), sy);
150
+ const o = ((oy + y) * W + ox + x) * 3;
151
+ out[o] = r; out[o + 1] = g; out[o + 2] = b;
152
+ }
153
+ }
154
+ });
155
+ return encodePng(W, H, out);
156
+ }
157
+
158
+ /**
159
+ * Seek the video document every stepS seconds and report per-frame luma spread.
160
+ * Returns {frames:[{t, lumaStdDev, lumaStddev}], contactSheet} | {skipped} | {error}.
161
+ * `lumaStddev` mirrors `lumaStdDev` because checkBlankFrames reads that spelling.
162
+ */
163
+ async function sampleFrames({ htmlPath, lengthS, stepS = 0.5, outDir, loadPlaywright } = {}) {
164
+ const length = Number(lengthS); const step = Number(stepS);
165
+ if (!htmlPath || !outDir || !(length > 0) || !(step > 0)) return { error: 'htmlPath, outDir, lengthS > 0 and stepS > 0 are required' };
166
+ const count = Math.floor(length / step + 1e-9) + 1;
167
+ if (count > MAX_FRAMES) return { error: `refused: ${count} frames exceeds the ${MAX_FRAMES} frame cap` };
168
+ const pw = (loadPlaywright || defaultLoader)();
169
+ const resolved = pw && typeof pw.then === 'function' ? await pw : pw;
170
+ const chromium = resolved && resolved.chromium;
171
+ if (!chromium) return { skipped: 'no-playwright' };
172
+
173
+ fs.mkdirSync(outDir, { recursive: true });
174
+ const frames = []; const images = [];
175
+ let browser;
176
+ try { browser = await chromium.launch({ headless: true }); } catch { return { skipped: 'no-playwright' }; } // package without a browser binary
177
+ try {
178
+ const page = await browser.newPage({ viewport: VIEWPORT });
179
+ page.setDefaultTimeout(30000);
180
+ await page.goto(pathToFileURL(path.resolve(htmlPath)).href, { timeout: 30000, waitUntil: 'load' });
181
+ await page.evaluate(() => { const d = window.smDemo; if (d && typeof d.pause === 'function') d.pause(); });
182
+ for (let i = 0; i < count; i++) {
183
+ const t = Math.round(i * step * 1000) / 1000;
184
+ await page.evaluate((s) => { const d = window.smDemo; if (d && typeof d.seek === 'function') d.seek(s); }, t);
185
+ await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))));
186
+ const img = decodePng(await page.screenshot({ type: 'png' }));
187
+ const { stdDev } = lumaStats(img);
188
+ const v = Math.round(stdDev * 100) / 100;
189
+ frames.push({ t, lumaStdDev: v, lumaStddev: v });
190
+ images.push(img);
191
+ }
192
+ } finally {
193
+ await browser.close();
194
+ }
195
+ const contactSheet = path.join(outDir, 'contact-sheet.png');
196
+ fs.writeFileSync(contactSheet, buildContactSheet(images));
197
+ return { frames, contactSheet };
198
+ }
199
+
200
+ module.exports = { MAX_FRAMES, sampleFrames, decodePng, encodePng, lumaStats, buildContactSheet };
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Boot-time seeder for the demo-video kit.
3
+ *
4
+ * Copies the kit's runnable modules to a stable per-machine folder,
5
+ * `~/.claude/session-manager/demo-video-kit/`, so the demo-video persona can
6
+ * `require()` them from any project's cwd (the app's own install path changes
7
+ * with every npx hash dir). A `KIT_VERSION` stamp file records which kit
8
+ * version is installed; files are overwritten only when the stamp differs, so
9
+ * a normal boot is one small read. Bump KIT_VERSION whenever any kit file
10
+ * changes behaviour.
11
+ *
12
+ * Fire-and-forget from index.cjs: errors are logged, never thrown.
13
+ * Kill-switch: SM_SEED_DEMO_VIDEO_KIT_DISABLE=1.
14
+ */
15
+ const fs = require('node:fs');
16
+ const path = require('node:path');
17
+ const { schedulerHome } = require('../scheduler/schedulerPaths.cjs');
18
+ const { writeTextAtomic } = require('../util/atomicFs.cjs');
19
+
20
+ const KIT_VERSION = '1';
21
+ const KIT_FILES = ['checks.cjs', 'sound.cjs', 'capture.cjs', 'frames.cjs', 'character.cjs'];
22
+ const STAMP_FILE = 'KIT_VERSION';
23
+
24
+ function kitDestDir() {
25
+ return path.join(schedulerHome(), 'demo-video-kit');
26
+ }
27
+
28
+ async function seedDemoVideoKit({ logger = console, writeLog = () => {}, destDir = kitDestDir(), srcDir = __dirname, kitVersion = KIT_VERSION } = {}) {
29
+ if (process.env.SM_SEED_DEMO_VIDEO_KIT_DISABLE === '1') return { seeded: false, reason: 'disabled' };
30
+ try {
31
+ const stampPath = path.join(destDir, STAMP_FILE);
32
+ let installed = null;
33
+ try { installed = fs.readFileSync(stampPath, 'utf8').trim(); } catch { /* no stamp yet */ }
34
+ const filesPresent = KIT_FILES.every((f) => fs.existsSync(path.join(destDir, f)));
35
+ if (installed === String(kitVersion) && filesPresent) return { seeded: false, reason: 'current' };
36
+
37
+ fs.mkdirSync(destDir, { recursive: true });
38
+ for (const f of KIT_FILES) {
39
+ await writeTextAtomic(path.join(destDir, f), fs.readFileSync(path.join(srcDir, f), 'utf8'));
40
+ }
41
+ // Stamp last: a crash mid-copy leaves the old/no stamp, so the next boot retries.
42
+ await writeTextAtomic(stampPath, `${kitVersion}\n`);
43
+ logger.log?.(`[seedDemoVideoKit] installed kit v${kitVersion} at ${destDir}`);
44
+ return { seeded: true, reason: installed === null ? 'fresh' : 'updated' };
45
+ } catch (err) {
46
+ logger.warn?.('[seedDemoVideoKit] error:', err?.message ?? err);
47
+ writeLog({ scope: 'seed-demo-video-kit', level: 'error', message: 'seed error', meta: { error: err?.message ?? String(err) } });
48
+ return { seeded: false, reason: 'error' };
49
+ }
50
+ }
51
+
52
+ module.exports = { seedDemoVideoKit, kitDestDir, KIT_VERSION, KIT_FILES };