huashu-motion 0.1.1 → 0.4.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 (46) hide show
  1. package/README.en.md +164 -5
  2. package/README.md +165 -6
  3. package/THIRD_PARTY.md +1 -0
  4. package/cli/lib/capture.js +1 -1
  5. package/cli/lib/check.js +13 -0
  6. package/cli/lib/composed.js +2 -2
  7. package/cli/lib/composer.js +33 -12
  8. package/cli/lib/grab.js +239 -0
  9. package/cli/lib/qa.js +53 -1
  10. package/cli/lib/render-om.js +3 -1
  11. package/cli/lib/render.js +6 -4
  12. package/cli/lib/share.js +101 -0
  13. package/cli/lib/sound.js +4 -0
  14. package/cli/lib/soundprint.js +72 -0
  15. package/cli/lib/swatch.js +7 -3
  16. package/cli/om.js +22 -3
  17. package/package.json +2 -2
  18. package/runtime/om-engine.js +129 -1
  19. package/runtime/om.js +180 -1
  20. package/runtime/three/LICENSE +21 -0
  21. package/runtime/three/entry.js +19 -0
  22. package/runtime/three/om-three.js +280 -0
  23. package/runtime/three/three.min.js +4586 -0
  24. package/skills/huashu-motion/SKILL.md +43 -6
  25. package/skills/huashu-motion/references/about-author.md +2 -1
  26. package/skills/huashu-motion/references/colour.md +16 -11
  27. package/skills/huashu-motion/references/contract.md +27 -1
  28. package/skills/huashu-motion/references/depth.md +109 -0
  29. package/skills/huashu-motion/references/director.md +27 -9
  30. package/skills/huashu-motion/references/library/README.md +1 -1
  31. package/skills/huashu-motion/references/library/languages/3d-object.md +5 -3
  32. package/skills/huashu-motion/references/library/techniques.md +4 -2
  33. package/skills/huashu-motion/references/music.md +411 -0
  34. package/skills/huashu-motion/references/punch-up.md +108 -0
  35. package/skills/huashu-motion/references/scores/first-light.abc +1 -1
  36. package/skills/huashu-motion/references/scores/four-rooms.abc +1 -1
  37. package/skills/huashu-motion/references/sound.md +5 -3
  38. package/templates/object-3d/assets/comment.svg +1 -0
  39. package/templates/object-3d/assets/cursor.svg +1 -0
  40. package/templates/object-3d/assets/studio.jpg +0 -0
  41. package/templates/object-3d/index.html +163 -0
  42. package/templates/object-3d/materials.md +6 -0
  43. package/templates/object-3d/template.json +23 -0
  44. package/templates/ui-space/index.html +150 -0
  45. package/templates/ui-space/materials.md +6 -0
  46. package/templates/ui-space/template.json +22 -0
@@ -0,0 +1,239 @@
1
+ // om grab — the product's real material into <project>/materials/, before any direction is drawn. A film about a
2
+ // product is made of the product: its logo as a file, its own colours and typefaces, its real interface. Agents that had
3
+ // to collect these by hand drew grey boxes instead; this collects them in one command.
4
+ //
5
+ // om grab <url> [dir] a website or a GitHub repo page: screenshots down the page (2x), the images on it, logo
6
+ // candidates (icons, og:image, inline SVG logos), the colours and typefaces it really uses
7
+ // om grab <folder> [dir] the product's own project on this machine: README images, screenshots, media, icons, and
8
+ // the colours and fonts its stylesheets declare
9
+ //
10
+ // Every file gets a line in materials/manifest.json and materials.md saying where it came from.
11
+ import { spawnSync } from 'node:child_process';
12
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync, appendFileSync } from 'node:fs';
13
+ import { basename, extname, join, relative, resolve } from 'node:path';
14
+ import { findChrome, NO_CHROME } from './browser.js';
15
+ import { launch, newPage } from './cdp.js';
16
+ import { OmError } from './project.js';
17
+
18
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
19
+ const MEDIA = /\.(png|jpe?g|webp|gif|svg|avif|mp4|mov|webm|icns|ico)$/i;
20
+ const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build', 'out', '.om', '_archive', '.next', 'coverage', 'vendor', 'Pods', 'DerivedData', '.cache']);
21
+
22
+ function slug(s) { return String(s).toLowerCase().replace(/^https?:\/\//, '').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 48) || 'source'; }
23
+
24
+ // The materials folder and its two indexes: manifest.json for tools, materials.md for people and the treatment.
25
+ function ledger(root) {
26
+ const dir = join(root, 'materials');
27
+ mkdirSync(dir, { recursive: true });
28
+ const file = join(dir, 'manifest.json');
29
+ let m = { sources: [] };
30
+ try { m = JSON.parse(readFileSync(file, 'utf8')); } catch { /* new */ }
31
+ return { dir, add(source) { m.sources = m.sources.filter((s) => s.from !== source.from).concat(source); writeFileSync(file, JSON.stringify(m, null, 2)); } };
32
+ }
33
+
34
+ function writeMd(root, source) {
35
+ const md = join(root, 'materials.md');
36
+ if (!existsSync(md)) writeFileSync(md, `# Materials\n\nWhat the film is made of, and where each piece came from. Real material first: the logo as a file, the product's own colours and type, its real interface. Anything rebuilt is traced over a capture listed here.\n`);
37
+ const rel = (f) => relative(root, f).split('\\').join('/');
38
+ const lines = [`\n## ${source.kind === 'web' ? 'Web' : 'Local'} · ${source.from} (${source.at.slice(0, 10)})\n`];
39
+ const by = (k) => source.files.filter((f) => f.kind === k);
40
+ for (const [k, label] of [['logo', 'Logo / icon'], ['screen', 'Screenshots of the page'], ['image', 'Images'], ['video', 'Video'], ['media', 'Media files']]) {
41
+ const fs = by(k);
42
+ if (fs.length) lines.push(`- ${label} (${fs.length}): ${fs.slice(0, 12).map((f) => `\`${rel(f.file)}\`${source.kind === 'local' ? ` ← ${f.from}` : ''}${f.note ? ` ${f.note}` : ''}`).join(', ')}${fs.length > 12 ? ', …' : ''}`);
43
+ }
44
+ if (source.colours?.length) lines.push(`- Colours it uses: ${source.colours.slice(0, 10).map((c) => `${c.hex} (${c.role})`).join(' · ')}`);
45
+ if (source.fonts?.length) lines.push(`- Typefaces: ${source.fonts.slice(0, 6).map((f) => f.family).join(' · ')}`);
46
+ if (source.missing?.length) lines.push(`- Not captured: ${source.missing.join('; ')}`);
47
+ appendFileSync(md, lines.join('\n') + '\n');
48
+ return md;
49
+ }
50
+
51
+ function curl(url, file, referer) {
52
+ const r = spawnSync('curl', ['-sSL', '--max-time', '40', '--max-filesize', String(30 << 20), '-A', 'Mozilla/5.0 (huashu-motion om grab)', ...(referer ? ['-e', referer] : []), '-o', file, url], { encoding: 'utf8' });
53
+ return r.status === 0 && existsSync(file) && statSync(file).size > 200;
54
+ }
55
+
56
+ // ---------- web ----------
57
+ const PAGE_FACTS = `(() => {
58
+ const vis = (el) => { const r = el.getBoundingClientRect(), s = getComputedStyle(el); return r.width > 1 && r.height > 1 && s.visibility !== 'hidden' && s.display !== 'none' && Number(s.opacity) > 0.05; };
59
+ const abs = (u) => { try { return new URL(u, location.href).href; } catch (e) { return null; } };
60
+ const images = [];
61
+ for (const im of document.images) if (im.naturalWidth >= 240 && im.naturalHeight >= 120) images.push({ src: abs(im.currentSrc || im.src), w: im.naturalWidth, h: im.naturalHeight, alt: (im.alt || '').slice(0, 80) });
62
+ for (const el of document.querySelectorAll('*')) { const b = getComputedStyle(el).backgroundImage; const m = b && /url\\(["']?([^"')]+)["']?\\)/.exec(b); if (m && el.getBoundingClientRect().width >= 240) images.push({ src: abs(m[1]), w: Math.round(el.getBoundingClientRect().width), h: Math.round(el.getBoundingClientRect().height), alt: 'background' }); }
63
+ const videos = [...document.querySelectorAll('video')].map((v) => ({ src: abs(v.currentSrc || v.src || (v.querySelector('source') || {}).src), poster: abs(v.poster) })).filter((v) => v.src || v.poster);
64
+ const logos = [];
65
+ for (const l of document.querySelectorAll('link[rel~="icon"],link[rel="apple-touch-icon"],link[rel="mask-icon"]')) logos.push({ src: abs(l.href), note: l.rel + (l.sizes && l.sizes.value ? ' ' + l.sizes.value : '') });
66
+ for (const m of document.querySelectorAll('meta[property="og:image"],meta[name="twitter:image"]')) logos.push({ src: abs(m.content), note: m.getAttribute('property') || m.getAttribute('name') });
67
+ const isLogo = (el) => /logo|brand|wordmark|lockup/i.test([el.id, el.getAttribute('class'), el.getAttribute('alt'), el.getAttribute('aria-label'), el.getAttribute('src')].join(' '));
68
+ for (const im of document.querySelectorAll('img')) if (isLogo(im) || isLogo(im.parentElement || im)) logos.push({ src: abs(im.currentSrc || im.src), note: 'img ' + (im.alt || '') });
69
+ const svgs = [];
70
+ for (const s of document.querySelectorAll('svg')) { if (!vis(s) || s.parentElement.closest('svg')) continue; const host = s.closest('a,header,nav,[class*=logo],[id*=logo]'); if (isLogo(s) || (host && (isLogo(host) || host.matches('header a:first-of-type, nav a:first-of-type')))) svgs.push(s.outerHTML.slice(0, 200000)); }
71
+ // colours, weighted: grounds by area, type by characters, accents from buttons and links
72
+ const tally = {}, add = (c, role, w) => { if (!c || /rgba?\\(0, 0, 0, 0\\)|transparent/.test(c)) return; const k = role + '|' + c; tally[k] = (tally[k] || 0) + w; };
73
+ const all = [...document.querySelectorAll('body, body *')].slice(0, 6000);
74
+ for (const el of all) {
75
+ if (!vis(el)) continue;
76
+ const s = getComputedStyle(el), r = el.getBoundingClientRect();
77
+ add(s.backgroundColor, 'ground', Math.min(r.width * r.height, 4e6));
78
+ const own = [...el.childNodes].filter((n) => n.nodeType === 3).map((n) => n.textContent.trim()).join('').length;
79
+ if (own) add(s.color, 'type', own);
80
+ if (el.matches('button, a[class*=btn], a[class*=button], [role=button], .btn, .button')) { add(s.backgroundColor, 'accent', 400); add(s.borderColor, 'accent', 100); }
81
+ if (el.matches('a')) add(s.color, 'accent', 30);
82
+ }
83
+ const fonts = {};
84
+ for (const el of all) { if (!vis(el)) continue; const own = [...el.childNodes].filter((n) => n.nodeType === 3).map((n) => n.textContent.trim()).join('').length; if (!own) continue; const f = getComputedStyle(el).fontFamily.split(',')[0].replace(/["']/g, '').trim(); fonts[f] = (fonts[f] || 0) + own; }
85
+ const vars = {};
86
+ for (const sh of document.styleSheets) { let rules; try { rules = sh.cssRules; } catch (e) { continue; } for (const r of rules) { if (!r.style) continue; for (const p of r.style) if (p.startsWith('--')) { const v = r.style.getPropertyValue(p).trim(); if (/^(#[0-9a-f]{3,8}|rgba?\\(|hsla?\\(|oklch\\()/i.test(v)) vars[p] = v; } } }
87
+ return { title: document.title, description: (document.querySelector('meta[name=description]') || {}).content || '', height: document.documentElement.scrollHeight, images, videos, logos, svgs, tally, fonts, vars };
88
+ })()`;
89
+
90
+ const toHex = (c) => { const m = /rgba?\(([^)]+)\)/.exec(c); if (!m) return c; const [r, g, b] = m[1].split(/[\s,/]+/).map(Number); return '#' + [r, g, b].map((x) => Math.round(x).toString(16).padStart(2, '0')).join(''); };
91
+
92
+ export async function grabWeb(root, url, { maxShots = 8, maxImages = 40, onLog = () => {} } = {}) {
93
+ const chrome = findChrome();
94
+ if (!chrome) throw new OmError(NO_CHROME);
95
+ const L = ledger(root);
96
+ const host = slug(url);
97
+ const dir = join(L.dir, `web-${host}`);
98
+ mkdirSync(dir, { recursive: true });
99
+ const conn = await launch(chrome, { args: ['--window-size=1440,900'] });
100
+ const files = [], missing = [];
101
+ let facts;
102
+ try {
103
+ const page = await newPage(conn);
104
+ await Promise.all([page.send('Page.enable'), page.send('Runtime.enable')]);
105
+ await page.send('Emulation.setDeviceMetricsOverride', { width: 1440, height: 900, deviceScaleFactor: 2, mobile: false });
106
+ const loaded = new Promise((ok) => page.on('Page.loadEventFired', ok));
107
+ const nav = await page.send('Page.navigate', { url });
108
+ if (nav.errorText) throw new OmError(`could not open ${url}: ${nav.errorText}`);
109
+ await Promise.race([loaded, sleep(30_000)]);
110
+ await sleep(1500);
111
+ // walk the page once so lazy images load, then back to the top
112
+ const h0 = await page.evaluate('document.documentElement.scrollHeight');
113
+ for (let y = 0; y < Math.min(h0, 900 * maxShots); y += 700) { await page.evaluate(`window.scrollTo(0, ${y})`); await sleep(150); }
114
+ await page.evaluate('window.scrollTo(0, 0)'); await sleep(800);
115
+ facts = await page.evaluate(PAGE_FACTS);
116
+ const shots = Math.max(1, Math.min(maxShots, Math.ceil(facts.height / 900)));
117
+ for (let i = 0; i < shots; i++) {
118
+ await page.evaluate(`window.scrollTo(0, ${i * 900})`); await sleep(500);
119
+ const { data } = await page.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }, 30_000);
120
+ const file = join(dir, `screen-${String(i + 1).padStart(2, '0')}.png`);
121
+ writeFileSync(file, Buffer.from(data, 'base64'));
122
+ files.push({ kind: 'screen', file, from: url, note: `y=${i * 900}px, 2x` });
123
+ }
124
+ if (facts.height > 900 * maxShots) missing.push(`page continues below ${900 * maxShots}px (raise --shots)`);
125
+ } finally { await conn.close(); }
126
+
127
+ // downloads: logos first, then the largest images, then video posters/sources
128
+ const seen = new Set();
129
+ const take = (src, kind, note, n) => {
130
+ if (!src || seen.has(src) || src.startsWith('data:') && src.length > 2e6) return;
131
+ seen.add(src);
132
+ const ext = (/\.(png|jpe?g|webp|gif|svg|avif|ico|mp4|webm|mov)(\?|#|$)/i.exec(src)?.[1] || (kind === 'video' ? 'mp4' : 'png')).toLowerCase();
133
+ const file = join(dir, `${kind}-${String(n).padStart(2, '0')}.${ext}`);
134
+ let ok;
135
+ if (src.startsWith('data:')) { const m = /^data:[^;,]+(;base64)?,(.*)$/s.exec(src); ok = !!m; if (m) writeFileSync(file, m[1] ? Buffer.from(m[2], 'base64') : decodeURIComponent(m[2])); }
136
+ else ok = curl(src, file, url);
137
+ if (ok) files.push({ kind, file, from: src, note });
138
+ else missing.push(`${kind} ${src.slice(0, 90)}`);
139
+ };
140
+ let n = 0;
141
+ for (const l of facts.logos) take(l.src, 'logo', l.note, ++n);
142
+ facts.svgs.forEach((s, i) => { const file = join(dir, `logo-svg-${i + 1}.svg`); writeFileSync(file, s.includes('xmlns=') ? s : s.replace('<svg', '<svg xmlns="http://www.w3.org/2000/svg"')); files.push({ kind: 'logo', file, from: url, note: 'inline SVG from the page' }); });
143
+ n = 0;
144
+ for (const im of facts.images.sort((a, b) => b.w * b.h - a.w * a.h).slice(0, maxImages)) take(im.src, 'image', `${im.w}×${im.h}${im.alt ? ` "${im.alt}"` : ''}`, ++n);
145
+ n = 0;
146
+ for (const v of facts.videos) { if (v.src) take(v.src, 'video', 'video on the page', ++n); if (v.poster) take(v.poster, 'image', 'video poster', ++n); }
147
+
148
+ const colours = Object.entries(facts.tally).map(([k, w]) => { const [role, c] = k.split('|'); return { role, hex: toHex(c), w }; });
149
+ const merged = {};
150
+ for (const c of colours) { const k = c.role + c.hex; merged[k] = merged[k] ? { ...merged[k], w: merged[k].w + c.w } : c; }
151
+ const top = (role, n) => Object.values(merged).filter((c) => c.role === role).sort((a, b) => b.w - a.w).slice(0, n);
152
+ const palette = [...top('ground', 4), ...top('type', 3), ...top('accent', 4)];
153
+ for (const [k, v] of Object.entries(facts.vars).slice(0, 24)) palette.push({ role: `css ${k}`, hex: v });
154
+ const fonts = Object.entries(facts.fonts).sort((a, b) => b[1] - a[1]).slice(0, 6).map(([family, chars]) => ({ family, chars }));
155
+ const source = { kind: 'web', from: url, at: new Date().toISOString(), title: facts.title, description: facts.description, files: files.map((f) => ({ ...f, file: relative(root, f.file).split('\\').join('/') })), colours: palette, fonts, missing };
156
+ L.add(source);
157
+ const md = writeMd(root, { ...source, files });
158
+ return { dir, files, colours: palette, fonts, missing, md, title: facts.title };
159
+ }
160
+
161
+ // ---------- local project ----------
162
+ export function grabLocal(root, folder, { maxFiles = 60, onLog = () => {} } = {}) {
163
+ const src = resolve(folder);
164
+ if (!existsSync(src) || !statSync(src).isDirectory()) throw new OmError(`${src} is not a folder`);
165
+ const L = ledger(root);
166
+ const dir = join(L.dir, `local-${slug(basename(src))}`);
167
+ mkdirSync(dir, { recursive: true });
168
+ const found = [], css = [];
169
+ const walk = (d, depth) => {
170
+ if (depth > 6) return;
171
+ let entries; try { entries = readdirSync(d, { withFileTypes: true }); } catch { return; }
172
+ for (const e of entries) {
173
+ if (e.name.startsWith('.') && e.name !== '.github') continue;
174
+ const p = join(d, e.name);
175
+ if (e.isDirectory()) { if (!SKIP_DIRS.has(e.name) && resolve(p) !== resolve(root)) walk(p, depth + 1); continue; }
176
+ if (!e.isFile()) continue;
177
+ if ((/\.(css|scss|less)$/i.test(e.name) || (/\.html?$/i.test(e.name) && statSync(p).size < 400_000)) && css.length < 60) css.push(p);
178
+ if (!MEDIA.test(e.name)) continue;
179
+ const size = statSync(p).size;
180
+ const icon = /icon|logo|favicon|appicon|brand|wordmark/i.test(p);
181
+ if (size < (icon ? 200 : 15_000) || size > 80 << 20) continue;
182
+ found.push({ p, size, icon });
183
+ }
184
+ };
185
+ walk(src, 0);
186
+ // what the README shows first: those images are the product as its maker presents it
187
+ const readme = readdirSync(src).find((n) => /^readme(\.[a-z]+)?\.md$/i.test(n));
188
+ const featured = new Set();
189
+ if (readme) {
190
+ const text = readFileSync(join(src, readme), 'utf8');
191
+ for (const m of text.matchAll(/!\[[^\]]*\]\(([^)\s]+)|<img[^>]+src=["']([^"']+)["']/g)) {
192
+ const ref = (m[1] || m[2] || '').split(/[?#]/)[0];
193
+ if (ref && !/^https?:/.test(ref)) { const f = resolve(src, ref); if (existsSync(f)) featured.add(f); }
194
+ }
195
+ }
196
+ const rank = (x) => (featured.has(x.p) ? 0 : x.icon ? 1 : /screen|shot|截屏|截图|demo|media|preview|素材|promo|banner/i.test(x.p) ? 2 : 3);
197
+ const pick = found.sort((a, b) => rank(a) - rank(b) || b.size - a.size).slice(0, maxFiles);
198
+ const files = [];
199
+ const used = new Set();
200
+ for (const x of pick) {
201
+ let name = basename(x.p);
202
+ while (used.has(name)) name = '_' + name;
203
+ used.add(name);
204
+ const file = join(dir, name);
205
+ copyFileSync(x.p, file);
206
+ const kind = x.icon ? 'logo' : /\.(mp4|mov|webm)$/i.test(x.p) ? 'video' : /screen|shot|截屏|截图/i.test(x.p) ? 'screen' : 'media';
207
+ files.push({ kind, file, from: relative(src, x.p).split('\\').join('/'), note: featured.has(x.p) ? '(in the README)' : '' });
208
+ }
209
+ // the colours and fonts the stylesheets declare: custom properties first, then the most used values
210
+ const counts = {}, vars = {}, fonts = {};
211
+ for (const f of css) {
212
+ const t = readFileSync(f, 'utf8');
213
+ for (const m of t.matchAll(/(--[\w-]+)\s*:\s*(#[0-9a-fA-F]{3,8}|rgba?\([^)]+\)|hsla?\([^)]+\)|oklch\([^)]+\))/g)) vars[m[1]] = m[2];
214
+ for (const m of t.matchAll(/#[0-9a-fA-F]{6}\b/g)) counts[m[0].toLowerCase()] = (counts[m[0].toLowerCase()] || 0) + 1;
215
+ for (const m of t.matchAll(/font-family\s*:\s*([^;}{]+)/g)) { const fam = m[1].split(',')[0].replace(/["']/g, '').trim(); if (fam && !fam.startsWith('var(')) fonts[fam] = (fonts[fam] || 0) + 1; }
216
+ }
217
+ const colours = [...Object.entries(vars).slice(0, 24).map(([k, v]) => ({ role: `css ${k}`, hex: v })), ...Object.entries(counts).sort((a, b) => b[1] - a[1]).slice(0, 8).map(([hex, c]) => ({ role: `used ${c}×`, hex }))];
218
+ const fontList = Object.entries(fonts).sort((a, b) => b[1] - a[1]).slice(0, 6).map(([family, n]) => ({ family, n }));
219
+ const missing = [];
220
+ if (!files.some((f) => f.kind === 'logo')) missing.push('no logo or icon file found — look in the app bundle, the site (om grab <url>) or ask the user');
221
+ if (!files.some((f) => f.kind === 'screen' || f.kind === 'video')) missing.push('no screenshots or recordings — run the product and capture it');
222
+ const source = { kind: 'local', from: src, at: new Date().toISOString(), files: files.map((f) => ({ ...f, file: relative(root, f.file).split('\\').join('/') })), colours, fonts: fontList, missing };
223
+ L.add(source);
224
+ const md = writeMd(root, { ...source, files });
225
+ return { dir, files, colours, fonts: fontList, missing, md };
226
+ }
227
+
228
+ export async function grab(root, target, opts = {}) {
229
+ const r = /^https?:\/\//i.test(target) ? await grabWeb(root, target, opts) : grabLocal(root, target, opts);
230
+ const count = (k) => r.files.filter((f) => f.kind === k).length;
231
+ const rel = (f) => relative(root, f).split('\\').join('/');
232
+ const lines = [`grab ${target}${r.title ? ` "${r.title}"` : ''}`,
233
+ ` ${rel(r.dir)}/ logo ${count('logo')} · screens ${count('screen')} · images ${count('image') + count('media')} · video ${count('video')}`,
234
+ r.colours.length ? ` colours ${r.colours.slice(0, 8).map((c) => `${c.hex} ${c.role}`).join(' · ')}` : ' colours none found',
235
+ r.fonts.length ? ` type ${r.fonts.map((f) => f.family).join(' · ')}` : ' type none found',
236
+ ` ${rel(r.md)} updated — look at every file before choosing a direction (om still can't see them for you)`];
237
+ for (const m of r.missing.slice(0, 6)) lines.push(` ! ${m}`);
238
+ return lines.join('\n');
239
+ }
package/cli/lib/qa.js CHANGED
@@ -3,7 +3,8 @@
3
3
  // (stretches where nothing moves), hard cuts, whether the last frame matches the first (loops), and
4
4
  // the motion curve per second so a flat film is visible as a flat line.
5
5
  import { spawnSync } from 'node:child_process';
6
- import { existsSync } from 'node:fs';
6
+ import { existsSync, mkdirSync, readdirSync, unlinkSync } from 'node:fs';
7
+ import { basename, join } from 'node:path';
7
8
  import { OmError } from './project.js';
8
9
 
9
10
  const W = 96, H = 54;
@@ -59,10 +60,37 @@ export function qa(file, { loop = false } = {}) {
59
60
  const mean = perSec.reduce((a, b) => a + b, 0) / (perSec.length || 1);
60
61
  const sd = Math.sqrt(perSec.reduce((a, b) => a + (b - mean) ** 2, 0) / (perSec.length || 1));
61
62
  const loopGap = +diff(f[0], f[f.length - 1]).toFixed(2);
63
+ // The opening and the whole: what separates a film people watch from a slide deck that happens to move. Measured on
64
+ // 15 films the user signed off (2026-10) against a one-line film by a new user: their strongest second in the first
65
+ // 5 s was 2.0–24 (median ~6) with no still stretch over 1.1 s there, and the whole film averaged 0.85–5.8; the
66
+ // one-line film peaked at 0.9 in its first 5 s, stood still from 0.95 to 4.2 s and averaged 0.18 with no cut.
67
+ const head = perSec.slice(0, 5), stillHead = dead.filter((x) => x.from < 5 && x.seconds >= 1.5);
68
+ const opening = { peak: head.length ? Math.max(...head) : 0, still: stillHead, flat: info.duration >= 6 && ((head.length ? Math.max(...head) : 0) < 1.5 || stillHead.length > 0) };
69
+ const flatFilm = info.duration >= 6 && mean < 0.6 && cuts.length / info.duration * 60 < 3;
70
+ // Frame 0 is the poster: feeds and players show it before the film plays, a README GIF shows it while it loads, a
71
+ // share preview often is it. "Content" = pixels away from the frame's median grey and edges between neighbours.
72
+ // Measured 2026-10-22: films that open on their subject had 7–94 % such pixels and 2–18 % edges in frame 0; a blank
73
+ // page, black, or a lone small mark on black had under 2.5 % and 1.2 % (three of the user's approved films opened
74
+ // that way, fading up over ~2 s — fine to watch, an empty poster).
75
+ const content = (px) => {
76
+ const m = median(px);
77
+ let far = 0, edges = 0;
78
+ for (let i = 0; i < px.length; i++) {
79
+ if (Math.abs(px[i] - m) > 16) far++;
80
+ if (i % W < W - 1 && Math.abs(px[i] - px[i + 1]) > 20) edges++;
81
+ }
82
+ return { far: far / px.length, edges: edges / (H * (W - 1)) };
83
+ };
84
+ const filled = (c) => c.far >= 0.05 && c.edges >= 0.015;
85
+ const c0 = f.length ? content(f[0]) : { far: 0, edges: 0 };
86
+ let arrives = null;
87
+ for (let i = 0; i < f.length && i < fps * 10; i++) if (filled(content(f[i]))) { arrives = t(i); break; }
88
+ const firstFrame = { far: +c0.far.toFixed(3), edges: +c0.edges.toFixed(3), empty: c0.far < 0.03 && c0.edges < 0.012, contentAt: arrives };
62
89
  return {
63
90
  file, ...info, frames: f.length,
64
91
  pops, cuts, dead,
65
92
  motion: { perSecond: perSec, mean: +mean.toFixed(2), contrast: +(sd / (mean + 1e-6)).toFixed(2) },
93
+ opening, flatFilm, firstFrame,
66
94
  loop: { firstLastDiff: loopGap, seamless: loopGap < 1.5, checked: loop },
67
95
  };
68
96
  }
@@ -73,6 +101,30 @@ export function report(r) {
73
101
  lines.push(r.dead.length ? `${r.dead.some((x) => x.seconds > 2) ? '✗' : '·'} still for ≥1 s: ${r.dead.map((x) => `${x.from}–${x.to}s`).join(', ')} — fine for a reading hold or an end card, dead time anywhere else` : '✓ no stretch of ≥1 s without motion');
74
102
  lines.push(`· ${r.cuts.length} hard cut(s)${r.cuts.length ? ': ' + r.cuts.slice(0, 20).join(', ') + 's' : ''} (average shot ${(r.duration / (r.cuts.length + 1)).toFixed(1)} s)`);
75
103
  lines.push(`· motion per second: ${r.motion.perSecond.join(' ')} (contrast ${r.motion.contrast}${r.motion.contrast < 0.35 ? ' — very even: the film may feel flat; give it fast and slow moments' : ''})`);
104
+ if (r.firstFrame && r.firstFrame.empty) lines.push(`✗ frame 0 is nearly empty — it is the poster feeds, players and README GIFs show before the film plays${r.firstFrame.contentAt != null ? `; the frame fills at ${r.firstFrame.contentAt}s` : ''}. Open on the subject already in frame (in motion), not on a blank, a black or a lone small mark the film builds from`);
105
+ if (r.opening && r.opening.flat) lines.push(`✗ flat opening: the strongest second of the first 5 s moves ${r.opening.peak}${r.opening.still.length ? `, still ${r.opening.still.map((x) => `${x.from}–${x.to}s`).join(', ')}` : ''} — films people kept peaked at 2–24 (median ~6) there with no still stretch over 1 s. Open on a big move (a push, a whip, a flood, the result slammed in) and land the first burst before 5 s, unless the brief asked for calm`);
106
+ if (r.flatFilm) lines.push(`✗ the whole film barely moves (mean ${r.motion.mean}, ${r.cuts.length} cuts) — it reads as slides. Films people kept averaged 0.85–5.8: cut, change shot scale, bring in a montage burst (rhythm.md)`);
76
107
  if (r.loop.checked) lines.push(r.loop.seamless ? `✓ last frame matches the first (diff ${r.loop.firstLastDiff}) — loops cleanly` : `✗ last frame differs from the first (diff ${r.loop.firstLastDiff}) — it will stutter as a loop`);
77
108
  return lines.join('\n');
78
109
  }
110
+
111
+ // om qa --sheet — the whole film as a few pictures: frames at a steady rate, tiled left to right, top to
112
+ // bottom. Looking at one still per scene finds layout faults; looking at every quarter second finds what a
113
+ // viewer feels: a stretch where neighbouring tiles are the same picture (dead), a run of scenes that are all
114
+ // the same picture with different content (slides), the one frame where something is half-way and ugly.
115
+ export function sheet(file, outDir, { fps = 4, cols = 6, rows = 6, width = 384 } = {}) {
116
+ if (!existsSync(file)) throw new OmError(`no such video: ${file}`);
117
+ const p = probe(file), per = cols * rows, stem = basename(file).replace(/\.[^.]+$/, '');
118
+ mkdirSync(outDir, { recursive: true });
119
+ for (const f of readdirSync(outDir)) if (f.startsWith(`${stem}-sheet`)) unlinkSync(join(outDir, f));
120
+ const r = spawnSync('ffmpeg', ['-v', 'error', '-y', '-i', file, '-vf', `fps=${fps},scale=${width}:-2,tile=${cols}x${rows}`, join(outDir, `${stem}-sheet%d.jpg`)]);
121
+ if (r.status !== 0) throw new OmError(`ffmpeg could not tile ${file}`);
122
+ const files = readdirSync(outDir).filter((f) => f.startsWith(`${stem}-sheet`)).sort((a, b) => parseInt(a.split('sheet').pop(), 10) - parseInt(b.split('sheet').pop(), 10)).map((f) => join(outDir, f));
123
+ return { files, fps, cols, rows, sheets: files.map((f, i) => ({ file: f, from: i * per / fps, to: Math.min(p.duration, (i + 1) * per / fps) })) };
124
+ }
125
+
126
+ export function sheetReport(s) {
127
+ return [`sheets ${s.fps} frames a second, read left to right; one row is ${(s.cols / s.fps).toFixed(2)} s`,
128
+ ...s.sheets.map((x) => ` ${x.from.toFixed(1)}–${x.to.toFixed(1)} s ${x.file}`),
129
+ ' look for: neighbouring tiles that are the same picture (dead), scenes that are the same layout with other content (slides), a tile caught half-way that is ugly'].join('\n');
130
+ }
@@ -57,7 +57,7 @@ const CONTAINERS = {
57
57
  };
58
58
  export const FORMATS = Object.keys(CONTAINERS);
59
59
 
60
- export async function renderOm(project, { fps, out, format = 'mp4', transparent = false, blur = 1, video = 'extract', frameFormat = 'png', workers = defaultWorkers(), shotFormat = null, paintWaits = 0, chunk = 8, preset = 'veryfast', crf = 16, software = false, onFrame = null, variables = null, allowPageErrors = false, prepare = null, verify = null, onLog = () => {}, onWarn = () => {} }) {
60
+ export async function renderOm(project, { fps, out, format = 'mp4', transparent = false, blur = 1, video = 'extract', frameFormat = 'png', workers = defaultWorkers(), shotFormat = null, paintWaits = 0, chunk = 8, preset = 'veryfast', crf = 16, software = false, onFrame = null, variables = null, allowPageErrors = false, prepare = null, verify = null, onLog = () => {}, onNote = onLog, onWarn = () => {} }) {
61
61
  if (!['extract', 'seek'].includes(video)) throw new OmError('--video must be extract or seek');
62
62
  if (!['jpg', 'png'].includes(frameFormat)) throw new OmError('--frames must be jpg or png');
63
63
  const box = CONTAINERS[format];
@@ -87,6 +87,8 @@ export async function renderOm(project, { fps, out, format = 'mp4', transparent
87
87
  }
88
88
  }
89
89
  const film = films[0];
90
+ const sig = await film.evaluate('window.__omEngine.signature()').catch(() => null);
91
+ if (sig) onNote(sig.on ? `signature on: "Made with huashu-motion" in a free corner for the last 1.2s (data-om-signature="off" on the root removes it)` : `signature off (${sig.why})`);
90
92
  const tmp = mkdtempSync(join(tmpdir(), 'om-render-'));
91
93
  const forgetTmp = cleanupOnInterrupt(() => rmSync(tmp, { recursive: true, force: true }));
92
94
  const picture = join(tmp, format === 'gif' ? 'picture.mp4' : `picture.${format}`);
package/cli/lib/render.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // om render: the film as a video file, through the huashu-motion renderer (render-om.js). Output always
2
2
  // lands in <project>/out/ with a new name — a render never overwrites a file the user may already have shared.
3
3
  import { spawnSync } from 'node:child_process';
4
- import { existsSync, mkdirSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
4
+ import { existsSync, mkdirSync, readdirSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
5
5
  import { join, sep } from 'node:path';
6
6
  import { OmError, readSource, readVariables } from './project.js';
7
7
  import { FORMATS, renderOm } from './render-om.js';
@@ -14,7 +14,9 @@ export function nextOutput(project, ext) {
14
14
  const dir = join(project.root, 'out');
15
15
  mkdirSync(dir, { recursive: true });
16
16
  const base = project.root.split(sep).pop();
17
- for (let v = 1; ; v++) {
17
+ // one past the highest version of any format: a deleted v1–v3 beside a kept v4 gives v5, never a new "v1"
18
+ const top = Math.max(0, ...readdirSync(dir).map((f) => (f.startsWith(`${base}-v`) ? parseInt(f.slice(base.length + 2), 10) || 0 : 0)));
19
+ for (let v = top + 1; ; v++) {
18
20
  const file = join(dir, `${base}-v${v}.${ext}`);
19
21
  try { writeFileSync(file, '', { flag: 'wx' }); return file; } catch (e) { if (e.code !== 'EEXIST') throw e; }
20
22
  }
@@ -24,7 +26,7 @@ export function nextOutput(project, ext) {
24
26
  // with alpha (WebM VP9 alpha also works); a composition that declares a boolean variable
25
27
  // `transparent` gets it set to true for this render (hide the footage, clear the background); the
26
28
  // sound is dropped because the edit underneath already has it; and the result is checked for alpha.
27
- export async function render(project, { format, fps, out, transparent = false, blur = 1, engine, video = 'extract', workers, frameFormat, tune = {}, allowPageErrors = false, prepare = null, onLog = () => {}, onWarn = () => {} } = {}) {
29
+ export async function render(project, { format, fps, out, transparent = false, blur = 1, engine, video = 'extract', workers, frameFormat, tune = {}, allowPageErrors = false, prepare = null, onLog = () => {}, onNote = onLog, onWarn = () => {} } = {}) {
28
30
  if (engine && engine !== 'om') throw new OmError(engine === 'hyperframes' ? 'the HyperFrames renderer was removed — om render uses its own engine now (drop --engine)' : '--engine must be om');
29
31
  const { html } = readSource(project);
30
32
  format = format || (transparent ? 'mov' : 'mp4');
@@ -45,7 +47,7 @@ export async function render(project, { format, fps, out, transparent = false, b
45
47
  const target = out || nextOutput(project, format);
46
48
  let r;
47
49
  try {
48
- r = await renderOm(project, { fps, out: target, format, transparent, blur, video, variables: switchVar ? { transparent: true } : null, ...(workers ? { workers } : {}), ...(frameFormat ? { frameFormat } : {}), ...tune, allowPageErrors, prepare, verify: transparent ? (file) => checkOverlay(file, switchVar, onWarn) : null, onLog, onWarn });
50
+ r = await renderOm(project, { fps, out: target, format, transparent, blur, video, variables: switchVar ? { transparent: true } : null, ...(workers ? { workers } : {}), ...(frameFormat ? { frameFormat } : {}), ...tune, allowPageErrors, prepare, verify: transparent ? (file) => checkOverlay(file, switchVar, onWarn) : null, onLog, onNote, onWarn });
49
51
  } catch (e) {
50
52
  // the version we claimed stays free for the next try (only the empty placeholder is removed, never a film)
51
53
  if (claimed && existsSync(target) && statSync(target).size === 0) unlinkSync(target);
@@ -0,0 +1,101 @@
1
+ // om share — after the render, the things a person needs to post the film: a GIF small enough for a README, X or a
2
+ // chat (≤ 10 MB: the opening plus the end frame with its signature), and share.md with where each file goes, a slot for
3
+ // the post the agent writes in the user's language, the line that says where the film came from, and a README snippet.
4
+ // Nothing is uploaded or posted: the user decides where it goes.
5
+ import { spawnSync } from 'node:child_process';
6
+ import { existsSync, mkdirSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
7
+ import { basename, join, relative } from 'node:path';
8
+ import { OmError } from './project.js';
9
+ import { REPO_URL } from './export.js';
10
+
11
+ const LIMIT = 10 * 1024 * 1024; // GitHub's limit for an image in a README; X and most chats take more
12
+ const END = 1.6; // the end frame and its signature (the engine shows it for the last 1.2 s)
13
+ const run = (args) => spawnSync('ffmpeg', ['-v', 'error', '-y', ...args], { encoding: 'utf8', maxBuffer: 64 << 20 });
14
+
15
+ function probe(file) {
16
+ const r = spawnSync('ffprobe', ['-v', 'error', '-select_streams', 'v:0', '-show_entries', 'stream=width,height:format=duration', '-of', 'json', file], { encoding: 'utf8' });
17
+ if (r.status !== 0) throw new OmError(`cannot read ${file}: ${(r.stderr || '').trim()}`);
18
+ const j = JSON.parse(r.stdout);
19
+ return { width: j.streams[0].width, height: j.streams[0].height, duration: Number(j.format.duration) };
20
+ }
21
+
22
+ // The newest video in <project>/out (the share folder itself is skipped).
23
+ export function newestRender(project) {
24
+ const dir = join(project.root, 'out');
25
+ const vids = existsSync(dir) ? readdirSync(dir).filter((n) => /\.(mp4|mov|webm)$/i.test(n) && statSync(join(dir, n)).size > 0).map((n) => join(dir, n)) : [];
26
+ if (!vids.length) throw new OmError('nothing rendered yet — run `om render` first');
27
+ return vids.sort((a, b) => statSync(b).mtimeMs - statSync(a).mtimeMs)[0];
28
+ }
29
+
30
+ // The GIF: [from, to] of the film, then its last END seconds when those are not already in it. Tried at falling sizes
31
+ // (then frame rates) until it fits under LIMIT; each try makes its own palette.
32
+ export function makeShareGif(video, target, { from = 0, to = null, limit = LIMIT } = {}) {
33
+ const info = probe(video);
34
+ const d = info.duration;
35
+ to = Math.min(d, to == null ? Math.max(from + 1, Math.min(d, from + 10)) : Number(to));
36
+ from = Math.max(0, Math.min(Number(from) || 0, to - 0.5));
37
+ const withEnd = to < d - END - 0.3;
38
+ const parts = withEnd ? [[from, to], [d - END, d]] : [[from, d - to < 0.3 ? d : to]];
39
+ const landscape = info.width >= info.height;
40
+ const sizes = [960, 800, 640, 540, 480, 400].filter((s) => s <= (landscape ? info.width : info.height));
41
+ if (!sizes.length) sizes.push(landscape ? info.width : info.height);
42
+ const tries = [...sizes.map((s) => [s, 15]), [sizes[sizes.length - 1], 12], [sizes[sizes.length - 1], 10]];
43
+ const palette = target.replace(/\.gif$/i, '.palette.png');
44
+ let last = null;
45
+ try {
46
+ for (const [s, fps] of tries) {
47
+ const scale = landscape ? `scale=${s}:-2:flags=lanczos` : `scale=-2:${s}:flags=lanczos`;
48
+ const cut = parts.map(([a, b], i) => `[0:v]trim=${a.toFixed(3)}:${b.toFixed(3)},setpts=PTS-STARTPTS,fps=${fps},${scale}[p${i}]`).join(';');
49
+ const joined = parts.length > 1 ? `${cut};${parts.map((_, i) => `[p${i}]`).join('')}concat=n=${parts.length}:v=1:a=0[v]` : `${cut};[p0]null[v]`;
50
+ let r = run(['-i', video, '-filter_complex', `${joined};[v]palettegen=max_colors=256:stats_mode=diff[pal]`, '-map', '[pal]', '-frames:v', '1', '-update', '1', palette]);
51
+ if (r.status !== 0) throw new OmError(`could not make the GIF palette: ${(r.stderr || '').trim().split('\n').pop()}`);
52
+ r = run(['-i', video, '-i', palette, '-filter_complex', `${joined};[v][1:v]paletteuse=dither=bayer:bayer_scale=4:diff_mode=rectangle`, '-loop', '0', target]);
53
+ if (r.status !== 0) throw new OmError(`could not write the GIF: ${(r.stderr || '').trim().split('\n').pop()}`);
54
+ last = { size: statSync(target).size, px: s, fps };
55
+ if (last.size <= limit) break;
56
+ }
57
+ } finally { rmSync(palette, { force: true }); }
58
+ return { ...last, parts, fits: last.size <= limit, landscape, source: info };
59
+ }
60
+
61
+ const mb = (n) => (n / 1024 / 1024).toFixed(1) + ' MB';
62
+ const t = (s) => s.toFixed(1) + 's';
63
+
64
+ export function share(project, { from = 0, to = null, video = null } = {}) {
65
+ const src = video || newestRender(project);
66
+ const index = join(project.root, 'index.html');
67
+ const stale = existsSync(index) && statSync(index).mtimeMs > statSync(src).mtimeMs + 1000;
68
+ const dir = join(project.root, 'out', 'share');
69
+ mkdirSync(dir, { recursive: true });
70
+ const name = basename(src).replace(/\.[^.]+$/, '');
71
+ const gif = join(dir, `${name}.gif`);
72
+ const g = makeShareGif(src, gif, { from, to });
73
+ const rel = (f) => relative(project.root, f).split('\\').join('/');
74
+ const span = g.parts.map(([a, b]) => `${t(a)}–${t(b)}`).join(' + ');
75
+ const md = `# 分享包 · Share kit
76
+
77
+ | 文件 File | 用途 Use |
78
+ |---|---|
79
+ | \`${rel(src)}\` | 完整成片(${t(g.source.duration)},${g.source.width}×${g.source.height}):X、视频号、B站、小红书、抖音 |
80
+ | \`${rel(gif)}\` | 动图(${span},${g.px}px,${g.fps} fps,${mb(g.size)}):GitHub README 头图、X、即刻、群聊 |
81
+
82
+ ## 发帖文案 · Post
83
+
84
+ <!-- agent: write 2–3 sentences in the user's language: what the film is about and one concrete detail of how it was made
85
+ (the one-line request, a note given in the studio, the music it composed). Keep the last line as it is. -->
86
+
87
+ Made with huashu-motion · ${REPO_URL} #huashumotion
88
+
89
+ ## README 头图 · README header
90
+
91
+ \`\`\`html
92
+ <a href="${REPO_URL}"><img src="${rel(gif)}" alt="" width="100%"></a>
93
+ <sub>Made with <a href="${REPO_URL}">huashu-motion</a></sub>
94
+ \`\`\`
95
+ `;
96
+ const mdFile = join(dir, 'share.md');
97
+ writeFileSync(mdFile, md);
98
+ const lines = [`share ${dir}`, ` ${rel(gif).padEnd(34)} ${span}, ${g.px}px ${g.fps} fps, ${mb(g.size)}${g.fits ? '' : ` — still over ${mb(LIMIT)}: pass a shorter --from/--to`}`, ` ${rel(mdFile).padEnd(34)} write the post into it (the user's language), then show the user`];
99
+ if (stale) lines.push(` ! ${rel(src)} is older than index.html — run om render first if the film changed since`);
100
+ return lines.join('\n');
101
+ }
package/cli/lib/sound.js CHANGED
@@ -4,6 +4,7 @@
4
4
  // no samples, no network, no dependencies — and the same source always gives the same file.
5
5
  // The music itself is composed in score.js (styles, products, drop, ending, motif); this file renders
6
6
  // the effects in the style's kit, automates and mixes the buses and writes the master.
7
+ import { soundprintReport } from './soundprint.js';
7
8
  import { createHash } from 'node:crypto';
8
9
  import { copyFileSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
9
10
  import { dirname, join } from 'node:path';
@@ -533,8 +534,11 @@ export async function sound(project, opts = {}, log = () => {}) {
533
534
  : `music ${trackInfo || describe(p)} · ${p.sections.length} section${p.sections.length > 1 ? 's' : ''} (${p.sections.map((s) => `${s.id}${s.drop ? '◆' : ''}:${s.energy.toFixed(1)}`).join(' ')})`,
534
535
  ];
535
536
  if (composed) {
537
+ try { lines.push(...soundprintReport(project.root, readScore(html)).lines); } catch { /* a score the print cannot read still plays */ }
536
538
  lines.push(`fit ${composed.marks.length ? `marks on the picture: ${composed.marks.join(' · ')}` : 'no !mark:name! matched a scene label — the score plays from the start at its written tempo'}${composed.unmatched.length ? ` · unmatched: ${composed.unmatched.join(', ')}` : ''}`);
537
539
  if (composed.stretches.length) lines.push(`tempo ${composed.stretches.map((x) => `${x.from}→${x.to} ${x.qpm.toFixed(1)} bpm (${x.bend >= 0 ? '+' : ''}${(x.bend * 100).toFixed(1)}%)`).join(' · ')}${composed.stretches.some((x) => Math.abs(x.bend) > 0.08) ? ' — a stretch bent more than 8 %: add or remove bars there instead' : ''}`);
540
+ for (const w of (composed.warnings || []).slice(0, 6)) lines.push(`warning score: ${w}`);
541
+ if ((composed.warnings || []).length > 6) lines.push(`warning score: … and ${composed.warnings.length - 6} more bars that do not add up`);
538
542
  if (composed.end > p.duration + 0.3) lines.push(`warning the score runs to ${composed.end.toFixed(2)}s, past the film's end (${p.duration.toFixed(2)}s); it is faded out`);
539
543
  }
540
544
  if (musicOn && !trackInfo && !composed) {
@@ -0,0 +1,72 @@
1
+ // What a score sounds like at a glance — its tempo, key and band — so `om sound` can say when a film's music is
2
+ // the same music as the bundled example scores or as the films made recently on this machine.
3
+ // 2026-10-22: ten test films in a row (two products, four skill versions) all played Signal's band — synpluck,
4
+ // supersaw, violins, piano, synbass, an 808 and a pop kit, same gains — at 120 BPM in E/A/D minor: the agent
5
+ // copied the closest example score's header every time, and every film sounded the same.
6
+ import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
7
+ import { homedir } from 'node:os';
8
+ import { dirname, join, resolve } from 'node:path';
9
+ import { fileURLToPath } from 'node:url';
10
+ import { parseAbc } from './composer.js';
11
+
12
+ const CASES = join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'skills', 'huashu-motion', 'references', 'scores');
13
+ export const historyFile = () => join(process.env.OM_HOME || join(homedir(), '.huashu-motion'), 'soundtracks.jsonl');
14
+
15
+ // tempo (first Q:), key (K:), meter, and the band: each voice's instrument (drum voices by kit)
16
+ export function soundprint(text) {
17
+ const s = parseAbc(text);
18
+ const q = /^Q:\s*(?:\d+\/\d+\s*=\s*)?(\d+(?:\.\d+)?)/m.exec(text), k = /^K:\s*([^\s%]+)/m.exec(text);
19
+ const key = k ? k[1] : 'C';
20
+ const minor = /^[A-Ga-g][#b]?(m|min|aeo|dor|phr|loc)/i.test(key) && !/^[A-Ga-g][#b]?(maj|mix|lyd)/i.test(key);
21
+ const band = [...new Set(Object.values(s.voices).map((v) => (v.inst === 'drums' ? `drums:${v.kit || 'pop'}` : v.inst || 'piano')))].sort();
22
+ return { title: s.title || '', bpm: q ? Number(q[1]) : 120, key, minor, meter: (s.meter || [4, 4]).join('/'), band };
23
+ }
24
+
25
+ const jaccard = (a, b) => { const A = new Set(a), B = new Set(b); let n = 0; for (const x of A) if (B.has(x)) n++; return n / (A.size + B.size - n || 1); };
26
+
27
+ // Two soundtracks are "the same music" when they share most of the band, or half of it at a nearby tempo.
28
+ // (A live film, 2026-10-22, answered the warning by swapping two of Signal's seven instruments at 120 BPM:
29
+ // 56 % shared, 8 BPM apart — still the same film to the ear.)
30
+ export function alike(a, b) {
31
+ const band = jaccard(a.band, b.band), tempo = Math.abs(a.bpm - b.bpm);
32
+ return { band: +band.toFixed(2), tempo, same: band >= 0.7 || (band >= 0.5 && tempo <= 12) };
33
+ }
34
+
35
+ export function cases() {
36
+ if (!existsSync(CASES)) return [];
37
+ return readdirSync(CASES).filter((f) => f.endsWith('.abc')).map((f) => ({ name: f, print: soundprint(readFileSync(join(CASES, f), 'utf8')) }));
38
+ }
39
+
40
+ export function recent(root, limit = 12) {
41
+ let rows = [];
42
+ try { rows = readFileSync(historyFile(), 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l)); } catch { return []; }
43
+ const here = resolve(root);
44
+ const latest = new Map();
45
+ for (const r of rows) if (r && r.root && r.print) latest.set(r.root, r); // the last entry per film
46
+ return [...latest.values()].filter((r) => r.root !== here).slice(-limit);
47
+ }
48
+
49
+ export function remember(root, print) {
50
+ try {
51
+ const f = historyFile();
52
+ mkdirSync(dirname(f), { recursive: true });
53
+ const line = JSON.stringify({ date: new Date().toISOString().slice(0, 10), root: resolve(root), print });
54
+ const prev = existsSync(f) ? readFileSync(f, 'utf8') : '';
55
+ writeFileSync(f, prev + line + '\n');
56
+ } catch { /* a read-only home: the check still ran */ }
57
+ }
58
+
59
+ const fmt = (p) => `${p.bpm} BPM ${p.key} · ${p.band.join(' ')}`;
60
+
61
+ // Lines for the om sound report: this film's soundprint, and what it repeats.
62
+ export function soundprintReport(root, text) {
63
+ const print = soundprint(text), lines = [`print ${fmt(print)}`];
64
+ for (const c of cases()) {
65
+ const m = alike(print, c.print);
66
+ if (m.same) lines.push(`warning this is the band of the example score ${c.name} (${fmt(c.print)}; ${Math.round(m.band * 100)} % of the instruments shared) — the examples teach structure, not a sound. Choose the band, tempo and key from the film's music direction (music.md)`);
67
+ }
68
+ const twins = recent(root).filter((r) => alike(print, r.print).same);
69
+ if (twins.length) lines.push(`warning the same music as ${twins.length} recent film${twins.length > 1 ? 's' : ''} on this machine (${twins.slice(-3).map((r) => `${r.root.split(/[\\/]/).slice(-2).join('/')}: ${fmt(r.print)}`).join(' | ')}) — every film so far has sounded alike; pick another world from music.md`);
70
+ remember(root, print);
71
+ return { print, lines };
72
+ }
package/cli/lib/swatch.js CHANGED
@@ -52,16 +52,20 @@ export function checkPalettes(palettes) {
52
52
  if (!p.from) parts.push('no source ("— from: …"): say where the colours came from');
53
53
  notes.push(`${p.name.padEnd(24)} ${parts.join(' · ')}`);
54
54
  }
55
- if (palettes.length >= 2) {
55
+ // A palette taken from the product (its site, CSS, logo, interface, materials.md) is the brand's, not a house look:
56
+ // an orange brand stays orange. The cross-direction warnings below are only for palettes the agent invented.
57
+ const owned = (p) => /\b(site|css|brand|logo|product|interface|ui|app|screenshot|materials?|icon|官网|品牌|界面|截图|素材)\b/i.test(p.from || '');
58
+ if (palettes.length >= 2 && palettes.every(owned)) notes.push('· every palette comes from the product — kept as the brand; no house-look warnings (colour.md §3)');
59
+ else if (palettes.length >= 2) {
56
60
  const grounds = palettes.map((p) => role(p, 'ground') || p.swatches[0]);
57
61
  const dark = grounds.filter((g) => hsl(g.hex).l < 0.2).length, light = grounds.filter((g) => hsl(g.hex).l > 0.8).length;
58
62
  if (dark === palettes.length) notes.push(`warning every direction has a dark ground — at least one should not (colour.md §3)`);
59
63
  if (light === palettes.length) notes.push(`warning every direction has a light ground — let one differ in value`);
60
64
  // the loudest colour of each palette, whatever its role is called (accent, flood, glow…)
61
65
  const accents = palettes.map((p) => [...p.swatches].sort((a, b) => hsl(b.hex).s * (1 - Math.abs(2 * hsl(b.hex).l - 1)) - hsl(a.hex).s * (1 - Math.abs(2 * hsl(a.hex).l - 1)))[0]);
62
- if (accents.every((a) => warm(a.hex))) notes.push('warning every accent is a warm orange-red — the house look; change the hue family of at least one (colour.md §2)');
66
+ if (accents.every((a) => warm(a.hex))) notes.push('warning every accent is a warm orange-red — the house look, unless it is the colour of the product itself (then say so in "— from:"); otherwise change the hue family of at least one (colour.md §2)');
63
67
  const single = palettes.filter((p) => p.swatches.filter((s) => /accent/i.test(s.role)).length === 1 && p.swatches.length <= 4).length;
64
- if (single === palettes.length) notes.push('warning all directions are "neutral ground + one accent" — vary the strategy too (colour.md §3)');
68
+ if (single === palettes.length) notes.push('warning all directions are "neutral ground + one accent" — fine when that is the brand (say so in "— from:"); otherwise vary the strategy (colour.md §3)');
65
69
  }
66
70
  return notes;
67
71
  }