blast-studio 0.0.0-stage → 0.1.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 (255) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +138 -2
  3. package/bin/bstudio.mjs +13 -0
  4. package/dist/agent-env.js +152 -0
  5. package/dist/brief.js +53 -0
  6. package/dist/budget/ledger.js +153 -0
  7. package/dist/campaign-zip.js +93 -0
  8. package/dist/cli.js +118 -0
  9. package/dist/commands/accept.js +64 -0
  10. package/dist/commands/auth.js +77 -0
  11. package/dist/commands/brief.js +117 -0
  12. package/dist/commands/budget.js +22 -0
  13. package/dist/commands/dashboard.js +9 -0
  14. package/dist/commands/doctor.js +57 -0
  15. package/dist/commands/export.js +42 -0
  16. package/dist/commands/init.js +24 -0
  17. package/dist/commands/install-skills.js +52 -0
  18. package/dist/commands/library.js +12 -0
  19. package/dist/commands/make.js +71 -0
  20. package/dist/commands/mark.js +44 -0
  21. package/dist/commands/new.js +25 -0
  22. package/dist/commands/plan.js +57 -0
  23. package/dist/commands/render-preview.js +43 -0
  24. package/dist/commands/render.js +243 -0
  25. package/dist/commands/review.js +119 -0
  26. package/dist/commands/revise.js +73 -0
  27. package/dist/commands/sources.js +33 -0
  28. package/dist/commands/status.js +34 -0
  29. package/dist/config.js +141 -0
  30. package/dist/dashboard/server.js +171 -0
  31. package/dist/dashboard/static/app.css +1 -0
  32. package/dist/dashboard/static/app.js +52 -0
  33. package/dist/dashboard/static/index.html +8 -0
  34. package/dist/env.js +47 -0
  35. package/dist/export.js +110 -0
  36. package/dist/fetch-text.js +64 -0
  37. package/dist/io.js +1 -0
  38. package/dist/keychain.js +41 -0
  39. package/dist/library.js +49 -0
  40. package/dist/packs.js +91 -0
  41. package/dist/plan.js +75 -0
  42. package/dist/posts.js +40 -0
  43. package/dist/providers/images.js +116 -0
  44. package/dist/providers/voice.js +55 -0
  45. package/dist/render/ffmpeg.js +96 -0
  46. package/dist/render/metrics.js +109 -0
  47. package/dist/render/stills.js +172 -0
  48. package/dist/render/template.js +20 -0
  49. package/dist/render/video.js +173 -0
  50. package/dist/review/gates.js +201 -0
  51. package/dist/review/reviewer.js +79 -0
  52. package/dist/review/score.js +21 -0
  53. package/dist/review/slop.js +17 -0
  54. package/dist/review-hash.js +21 -0
  55. package/dist/types.js +29 -0
  56. package/dist/updater/check.js +140 -0
  57. package/dist/updater/propose.js +144 -0
  58. package/dist/workspace.js +142 -0
  59. package/package.json +45 -4
  60. package/platforms/bluesky/guide.md +94 -0
  61. package/platforms/bluesky/pack.yml +150 -0
  62. package/platforms/dailydev/guide.md +82 -0
  63. package/platforms/dailydev/pack.yml +152 -0
  64. package/platforms/devto/guide.md +93 -0
  65. package/platforms/devto/pack.yml +119 -0
  66. package/platforms/gist/guide.md +92 -0
  67. package/platforms/gist/pack.yml +119 -0
  68. package/platforms/github-discussion/guide.md +92 -0
  69. package/platforms/github-discussion/pack.yml +122 -0
  70. package/platforms/hashnode/guide.md +93 -0
  71. package/platforms/hashnode/pack.yml +124 -0
  72. package/platforms/hn/guide.md +48 -0
  73. package/platforms/hn/pack.yml +59 -0
  74. package/platforms/instagram/guide.md +95 -0
  75. package/platforms/instagram/pack.yml +136 -0
  76. package/platforms/lemmy/guide.md +88 -0
  77. package/platforms/lemmy/pack.yml +141 -0
  78. package/platforms/linkedin/guide.md +93 -0
  79. package/platforms/linkedin/pack.yml +145 -0
  80. package/platforms/mastodon/guide.md +92 -0
  81. package/platforms/mastodon/pack.yml +138 -0
  82. package/platforms/medium/guide.md +92 -0
  83. package/platforms/medium/pack.yml +119 -0
  84. package/platforms/newsletter/guide.md +94 -0
  85. package/platforms/newsletter/pack.yml +144 -0
  86. package/platforms/producthunt/guide.md +92 -0
  87. package/platforms/producthunt/pack.yml +166 -0
  88. package/platforms/reddit/guide.md +92 -0
  89. package/platforms/reddit/pack.yml +151 -0
  90. package/platforms/snapshots/.gitkeep +0 -0
  91. package/platforms/snapshots/bluesky-10.sha256 +1 -0
  92. package/platforms/snapshots/bluesky-10.txt +1 -0
  93. package/platforms/snapshots/bluesky-11.sha256 +1 -0
  94. package/platforms/snapshots/bluesky-11.txt +1 -0
  95. package/platforms/snapshots/bluesky-12.sha256 +1 -0
  96. package/platforms/snapshots/bluesky-12.txt +1 -0
  97. package/platforms/snapshots/bluesky-13.sha256 +1 -0
  98. package/platforms/snapshots/bluesky-13.txt +1 -0
  99. package/platforms/snapshots/bluesky-14.sha256 +1 -0
  100. package/platforms/snapshots/bluesky-14.txt +1 -0
  101. package/platforms/snapshots/cross-platform-63.sha256 +1 -0
  102. package/platforms/snapshots/cross-platform-63.txt +1 -0
  103. package/platforms/snapshots/cross-platform-64.sha256 +1 -0
  104. package/platforms/snapshots/cross-platform-64.txt +1 -0
  105. package/platforms/snapshots/dailydev-55.sha256 +1 -0
  106. package/platforms/snapshots/dailydev-55.txt +1 -0
  107. package/platforms/snapshots/dailydev-56.sha256 +1 -0
  108. package/platforms/snapshots/dailydev-56.txt +1 -0
  109. package/platforms/snapshots/dailydev-57.sha256 +1 -0
  110. package/platforms/snapshots/dailydev-57.txt +1 -0
  111. package/platforms/snapshots/devto-26.sha256 +1 -0
  112. package/platforms/snapshots/devto-26.txt +1 -0
  113. package/platforms/snapshots/devto-27.sha256 +1 -0
  114. package/platforms/snapshots/devto-27.txt +1 -0
  115. package/platforms/snapshots/devto-28.sha256 +1 -0
  116. package/platforms/snapshots/devto-28.txt +1 -0
  117. package/platforms/snapshots/devto-29.sha256 +1 -0
  118. package/platforms/snapshots/devto-29.txt +1 -0
  119. package/platforms/snapshots/gist-52.sha256 +1 -0
  120. package/platforms/snapshots/gist-52.txt +1 -0
  121. package/platforms/snapshots/gist-53.sha256 +1 -0
  122. package/platforms/snapshots/gist-53.txt +1 -0
  123. package/platforms/snapshots/gist-54.sha256 +1 -0
  124. package/platforms/snapshots/gist-54.txt +1 -0
  125. package/platforms/snapshots/github-discussion-policy.sha256 +1 -0
  126. package/platforms/snapshots/github-discussion-policy.txt +1 -0
  127. package/platforms/snapshots/hashnode-30.sha256 +1 -0
  128. package/platforms/snapshots/hashnode-30.txt +1 -0
  129. package/platforms/snapshots/hashnode-31.sha256 +1 -0
  130. package/platforms/snapshots/hashnode-31.txt +1 -0
  131. package/platforms/snapshots/hashnode-32.sha256 +1 -0
  132. package/platforms/snapshots/hashnode-32.txt +1 -0
  133. package/platforms/snapshots/hn-23.sha256 +1 -0
  134. package/platforms/snapshots/hn-23.txt +1 -0
  135. package/platforms/snapshots/hn-24.sha256 +1 -0
  136. package/platforms/snapshots/hn-24.txt +1 -0
  137. package/platforms/snapshots/hn-25.sha256 +1 -0
  138. package/platforms/snapshots/hn-25.txt +1 -0
  139. package/platforms/snapshots/hyperframes-releases.sha256 +1 -0
  140. package/platforms/snapshots/hyperframes-releases.txt +1 -0
  141. package/platforms/snapshots/instagram-43.sha256 +1 -0
  142. package/platforms/snapshots/instagram-43.txt +1 -0
  143. package/platforms/snapshots/instagram-47.sha256 +1 -0
  144. package/platforms/snapshots/instagram-47.txt +1 -0
  145. package/platforms/snapshots/lemmy-policy.sha256 +1 -0
  146. package/platforms/snapshots/lemmy-policy.txt +1 -0
  147. package/platforms/snapshots/linkedin-1.sha256 +1 -0
  148. package/platforms/snapshots/linkedin-1.txt +1 -0
  149. package/platforms/snapshots/linkedin-2.sha256 +1 -0
  150. package/platforms/snapshots/linkedin-2.txt +1 -0
  151. package/platforms/snapshots/linkedin-3.sha256 +1 -0
  152. package/platforms/snapshots/linkedin-3.txt +1 -0
  153. package/platforms/snapshots/linkedin-4.sha256 +1 -0
  154. package/platforms/snapshots/linkedin-4.txt +1 -0
  155. package/platforms/snapshots/mastodon-15.sha256 +1 -0
  156. package/platforms/snapshots/mastodon-15.txt +1 -0
  157. package/platforms/snapshots/mastodon-16.sha256 +1 -0
  158. package/platforms/snapshots/mastodon-16.txt +1 -0
  159. package/platforms/snapshots/mastodon-17.sha256 +1 -0
  160. package/platforms/snapshots/mastodon-17.txt +1 -0
  161. package/platforms/snapshots/medium-34.sha256 +1 -0
  162. package/platforms/snapshots/medium-34.txt +1 -0
  163. package/platforms/snapshots/medium-35.sha256 +1 -0
  164. package/platforms/snapshots/medium-35.txt +1 -0
  165. package/platforms/snapshots/medium-36.sha256 +1 -0
  166. package/platforms/snapshots/medium-36.txt +1 -0
  167. package/platforms/snapshots/newsletter-58.sha256 +1 -0
  168. package/platforms/snapshots/newsletter-58.txt +1 -0
  169. package/platforms/snapshots/newsletter-59.sha256 +1 -0
  170. package/platforms/snapshots/newsletter-59.txt +1 -0
  171. package/platforms/snapshots/newsletter-60.sha256 +1 -0
  172. package/platforms/snapshots/newsletter-60.txt +1 -0
  173. package/platforms/snapshots/newsletter-61.sha256 +1 -0
  174. package/platforms/snapshots/newsletter-61.txt +1 -0
  175. package/platforms/snapshots/newsletter-62.sha256 +1 -0
  176. package/platforms/snapshots/newsletter-62.txt +1 -0
  177. package/platforms/snapshots/openai-image-pricing.sha256 +1 -0
  178. package/platforms/snapshots/openai-image-pricing.txt +1 -0
  179. package/platforms/snapshots/playwright-releases.sha256 +1 -0
  180. package/platforms/snapshots/playwright-releases.txt +1 -0
  181. package/platforms/snapshots/producthunt-37.sha256 +1 -0
  182. package/platforms/snapshots/producthunt-37.txt +1 -0
  183. package/platforms/snapshots/producthunt-38.sha256 +1 -0
  184. package/platforms/snapshots/producthunt-38.txt +1 -0
  185. package/platforms/snapshots/producthunt-39.sha256 +1 -0
  186. package/platforms/snapshots/producthunt-39.txt +1 -0
  187. package/platforms/snapshots/reddit-20.sha256 +1 -0
  188. package/platforms/snapshots/reddit-20.txt +1 -0
  189. package/platforms/snapshots/reddit-21.sha256 +1 -0
  190. package/platforms/snapshots/reddit-21.txt +1 -0
  191. package/platforms/snapshots/reddit-22.sha256 +1 -0
  192. package/platforms/snapshots/reddit-22.txt +1 -0
  193. package/platforms/snapshots/substack-policy.sha256 +1 -0
  194. package/platforms/snapshots/substack-policy.txt +1 -0
  195. package/platforms/snapshots/threads-18.sha256 +1 -0
  196. package/platforms/snapshots/threads-18.txt +1 -0
  197. package/platforms/snapshots/threads-19.sha256 +1 -0
  198. package/platforms/snapshots/threads-19.txt +1 -0
  199. package/platforms/snapshots/tiktok-50.sha256 +1 -0
  200. package/platforms/snapshots/tiktok-50.txt +1 -0
  201. package/platforms/snapshots/tiktok-51.sha256 +1 -0
  202. package/platforms/snapshots/tiktok-51.txt +1 -0
  203. package/platforms/snapshots/x-5.sha256 +1 -0
  204. package/platforms/snapshots/x-5.txt +1 -0
  205. package/platforms/snapshots/x-6.sha256 +1 -0
  206. package/platforms/snapshots/x-6.txt +1 -0
  207. package/platforms/snapshots/x-7.sha256 +1 -0
  208. package/platforms/snapshots/x-7.txt +1 -0
  209. package/platforms/snapshots/x-8.sha256 +1 -0
  210. package/platforms/snapshots/x-8.txt +1 -0
  211. package/platforms/snapshots/x-9.sha256 +1 -0
  212. package/platforms/snapshots/x-9.txt +1 -0
  213. package/platforms/snapshots/youtube-shorts-40.sha256 +1 -0
  214. package/platforms/snapshots/youtube-shorts-40.txt +1 -0
  215. package/platforms/snapshots/youtube-shorts-41.sha256 +1 -0
  216. package/platforms/snapshots/youtube-shorts-41.txt +1 -0
  217. package/platforms/snapshots/youtube-shorts-42.sha256 +1 -0
  218. package/platforms/snapshots/youtube-shorts-42.txt +1 -0
  219. package/platforms/sources.yml +947 -0
  220. package/platforms/substack/guide.md +94 -0
  221. package/platforms/substack/pack.yml +116 -0
  222. package/platforms/threads/guide.md +93 -0
  223. package/platforms/threads/pack.yml +148 -0
  224. package/platforms/tiktok/guide.md +92 -0
  225. package/platforms/tiktok/pack.yml +129 -0
  226. package/platforms/x/guide.md +94 -0
  227. package/platforms/x/pack.yml +130 -0
  228. package/platforms/youtube-shorts/guide.md +92 -0
  229. package/platforms/youtube-shorts/pack.yml +138 -0
  230. package/providers/prices.yml +31 -0
  231. package/schemas/campaign.v2.json +26 -0
  232. package/schemas/manifest.v1.json +37 -0
  233. package/schemas/pack.schema.json +601 -0
  234. package/schemas/review.schema.json +31 -0
  235. package/skills/studio-reviewer/SKILL.md +13 -0
  236. package/skills/studio-updater/SKILL.md +8 -0
  237. package/skills/studio-video/SKILL.md +20 -0
  238. package/skills/studio-visual/SKILL.md +12 -0
  239. package/skills/studio-writer/SKILL.md +14 -0
  240. package/templates/README.md +7 -0
  241. package/templates/card.html +1 -0
  242. package/templates/carousel-closing.html +1 -0
  243. package/templates/carousel-content.html +1 -0
  244. package/templates/carousel-title.html +1 -0
  245. package/templates/code.html +1 -0
  246. package/templates/fonts/IBM-Plex-OFL.txt +93 -0
  247. package/templates/fonts/IBMPlexMono.woff2 +0 -0
  248. package/templates/fonts/IBMPlexSans.woff2 +0 -0
  249. package/templates/fonts/Space-Grotesk-OFL.txt +93 -0
  250. package/templates/fonts/SpaceGrotesk.woff2 +0 -0
  251. package/templates/poster.html +1 -0
  252. package/templates/quote.html +1 -0
  253. package/templates/thumbnail.html +1 -0
  254. package/test/fixtures/reviews/calibration.json +22 -0
  255. package/test/fixtures/reviews/grounding/cases.json +17 -0
@@ -0,0 +1,172 @@
1
+ import { execFile } from "node:child_process";
2
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
5
+ import { fileURLToPath, pathToFileURL } from "node:url";
6
+ import { promisify } from "node:util";
7
+ import { Resvg } from "@resvg/resvg-js";
8
+ import { chromium } from "playwright";
9
+ import { agentEnv, sandboxCommand } from "../agent-env.js";
10
+ import { configFile, loadConfig } from "../config.js";
11
+ import { measureText } from "./metrics.js";
12
+ const exec = promisify(execFile);
13
+ let browser;
14
+ function getBrowser() {
15
+ if (!browser)
16
+ browser = chromium.launch({ headless: true }).catch(error => { browser = undefined; throw error; });
17
+ return browser;
18
+ }
19
+ export async function closeBrowser() {
20
+ const current = browser;
21
+ browser = undefined;
22
+ if (current)
23
+ await (await current).close();
24
+ }
25
+ export async function renderHtml({ html, width, height, out, pdf = false, assetDir, projectDir, safeZone, sampleTimeline = false }) {
26
+ if (!Number.isInteger(width) || !Number.isInteger(height) || width <= 0 || height <= 0)
27
+ throw new Error("Render size must be positive integer pixels");
28
+ const dir = mkdtempSync(join(tmpdir(), "bstudio-render-"));
29
+ const page = await (await getBrowser()).newPage({ viewport: { width, height }, deviceScaleFactor: 1 });
30
+ try {
31
+ const input = join(dir, "input.html");
32
+ writeFileSync(input, html);
33
+ const roots = [assetDir, fileURLToPath(new URL('../../templates/', import.meta.url))].filter((path) => !!path).map(path => realpathSync(path));
34
+ const assets = projectDir ? join(projectDir, 'assets') : assetDir ? resolve(assetDir, '../..', 'assets') : undefined;
35
+ const loadedFiles = new Set();
36
+ await page.routeWebSocket('**/*', socket => socket.close());
37
+ await page.route('**/*', route => {
38
+ const url = route.request().url();
39
+ if (url.startsWith('data:'))
40
+ return route.continue();
41
+ if (url.startsWith('file:')) {
42
+ try {
43
+ const path = realpathSync(fileURLToPath(url));
44
+ if (path === realpathSync(input) || roots.some(root => {
45
+ const rel = relative(root, path);
46
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
47
+ }) || (assets && (() => {
48
+ try {
49
+ const rel = relative(realpathSync(assets), path);
50
+ const parts = rel.split(sep);
51
+ return !isAbsolute(rel) && parts[0] !== '..' && parts.length >= 3 && parts[1] === 'out';
52
+ }
53
+ catch {
54
+ return false;
55
+ }
56
+ })())) {
57
+ if (path !== realpathSync(input))
58
+ loadedFiles.add(path);
59
+ return route.continue();
60
+ }
61
+ }
62
+ catch { /* missing, malformed, or inaccessible file */ }
63
+ }
64
+ return route.abort();
65
+ });
66
+ await page.goto(pathToFileURL(input).href, { waitUntil: "load" });
67
+ await page.evaluate(() => document.fonts.ready);
68
+ let metrics = await measureText(page, safeZone);
69
+ if (sampleTimeline) {
70
+ const duration = await page.evaluate(() => {
71
+ const timelines = Object.values(window.__timelines ?? {});
72
+ const seekable = timelines.filter(timeline => typeof timeline.seek === "function" && typeof timeline.duration === "function");
73
+ for (const timeline of seekable)
74
+ timeline.pause?.();
75
+ return Math.max(0, ...seekable.map(timeline => timeline.duration()).filter(Number.isFinite));
76
+ });
77
+ if (duration > 0) {
78
+ for (const fraction of [.25, .5, .75]) {
79
+ await page.evaluate(time => {
80
+ const timelines = Object.values(window.__timelines ?? {});
81
+ for (const timeline of timelines)
82
+ timeline.seek?.(time);
83
+ }, duration * fraction);
84
+ const next = await measureText(page, safeZone);
85
+ const nodes = [...metrics.nodes, ...next.nodes];
86
+ metrics = { minFontPx: nodes.length ? Math.min(...nodes.map(n => n.fontPx)) : null, minContrast: nodes.some(n => n.contrast === null) ? null : nodes.length ? Math.min(...nodes.map(n => n.contrast)) : null, overflow: metrics.overflow || next.overflow, edge: metrics.edge || next.edge, nodes, unmeasurable: [...new Set([...metrics.unmeasurable, ...next.unmeasurable])] };
87
+ }
88
+ }
89
+ else
90
+ metrics.unmeasurable.push("video timeline (only static composition state measured)");
91
+ }
92
+ mkdirSync(dirname(resolve(out)), { recursive: true });
93
+ if (pdf) {
94
+ await page.addStyleTag({ content: `@page { size: ${width}px ${height}px; margin: 0 } html, body { margin: 0; padding: 0 } .slide { break-after: page; page-break-after: always } .slide:last-child { break-after: auto; page-break-after: auto }` });
95
+ await page.pdf({ path: out, width: `${width}px`, height: `${height}px`, printBackground: true, preferCSSPageSize: true });
96
+ }
97
+ else
98
+ await page.screenshot({ path: out, type: "png", animations: "disabled" });
99
+ return { file: out, width, height, bytes: statSync(out).size, metrics, loadedFiles: [...loadedFiles] };
100
+ }
101
+ finally {
102
+ await page.close();
103
+ rmSync(dir, { recursive: true, force: true });
104
+ }
105
+ }
106
+ export function renderSvg(svgPath, outPngs) {
107
+ const svg = readFileSync(svgPath);
108
+ return outPngs.map(({ file, size }) => {
109
+ if (!Number.isInteger(size) || size <= 0)
110
+ throw new Error("SVG size must be a positive integer");
111
+ mkdirSync(dirname(resolve(file)), { recursive: true });
112
+ const png = new Resvg(svg, { fitTo: { mode: "width", value: size } }).render().asPng();
113
+ writeFileSync(file, png);
114
+ return file;
115
+ });
116
+ }
117
+ /** Render both SVG and PNG; `out` selects either artifact's basename. */
118
+ export async function renderDiagram(sourcePath, out, config, io) {
119
+ const ext = extname(sourcePath).toLowerCase();
120
+ if (!['.mmd', '.d2', '.json'].includes(ext))
121
+ throw new Error('Diagram source must be .mmd, .d2 or .json');
122
+ const base = /\.(svg|png)$/i.test(out) ? out.slice(0, -4) : out;
123
+ const svg = `${base}.svg`, png = `${base}.png`;
124
+ mkdirSync(dirname(resolve(svg)), { recursive: true });
125
+ const toolIO = io ?? { cwd: process.cwd(), env: process.env, err: (message) => console.error(message) };
126
+ if (!config) {
127
+ config = existsSync(configFile(toolIO)) ? loadConfig(toolIO) : { root: resolve(toolIO.env.HOME ?? tmpdir(), 'BlastStudio'), file: resolve(toolIO.env.HOME ?? tmpdir(), '.config/blast-studio/studio.yml'), agent: { sandbox: 'off' } };
128
+ }
129
+ const temp = mkdtempSync(join(tmpdir(), 'bstudio-diagram-'));
130
+ const run = async (command, args, extraReads = []) => {
131
+ const wrapped = sandboxCommand(toolIO, config, dirname(resolve(svg)), temp, command, args, { render: true, readPaths: [resolve(sourcePath), ...extraReads] });
132
+ return exec(wrapped.command, wrapped.args, { timeout: 30000, env: agentEnv(toolIO, { temp, home: temp, minimal: true }) });
133
+ };
134
+ try {
135
+ if (ext === '.mmd') {
136
+ const mmdc = fileURLToPath(new URL('../../node_modules/.bin/mmdc', import.meta.url));
137
+ const configPath = join(temp, 'puppeteer.json');
138
+ writeFileSync(configPath, JSON.stringify({ executablePath: chromium.executablePath(), pipe: true, args: ['--no-sandbox'] }));
139
+ const mermaidConfig = join(temp, 'mermaid.json');
140
+ writeFileSync(mermaidConfig, JSON.stringify({ htmlLabels: false, flowchart: { htmlLabels: false } }));
141
+ try {
142
+ await run(mmdc, ['-i', resolve(sourcePath), '-o', resolve(svg), '-p', configPath, '-c', mermaidConfig, '-b', 'white']);
143
+ }
144
+ catch (error) {
145
+ throw new Error(`Mermaid rendering failed; install dependencies with npm install and Chromium with npx playwright install chromium: ${String(error)}`);
146
+ }
147
+ }
148
+ else if (ext === '.json') {
149
+ const script = fileURLToPath(new URL('../../../slipway/skills/arch-diagram/scripts/diagram.py', import.meta.url));
150
+ try {
151
+ await run('python3', [script, resolve(sourcePath), '-o', resolve(base), '--format', 'svg'], [script]);
152
+ }
153
+ catch (error) {
154
+ throw new Error(`Architecture diagram rendering requires ../slipway/skills/arch-diagram/scripts/diagram.py: ${String(error)}`);
155
+ }
156
+ }
157
+ else {
158
+ try {
159
+ await run('d2', [resolve(sourcePath), resolve(svg)]);
160
+ }
161
+ catch (error) {
162
+ throw new Error(`D2 rendering failed; install D2 from https://d2lang.com/tour/install: ${String(error)}`);
163
+ }
164
+ }
165
+ const rendered = new Resvg(readFileSync(svg)).render();
166
+ writeFileSync(png, rendered.asPng());
167
+ return { svg, png };
168
+ }
169
+ finally {
170
+ rmSync(temp, { recursive: true, force: true });
171
+ }
172
+ }
@@ -0,0 +1,20 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { fileURLToPath, pathToFileURL } from 'node:url';
3
+ const templateDir = new URL('../../templates/', import.meta.url);
4
+ const names = { card: true, quote: true, code: true, poster: true, thumbnail: true, 'carousel-title': true, 'carousel-content': true, 'carousel-closing': true };
5
+ const escape = (value) => String(value ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
6
+ const color = (value, fallback) => value && /^(#[\da-f]{3,8}|[a-z]+)$/i.test(value) ? value : fallback;
7
+ const family = (value, fallback) => value && /^[\w -]+$/.test(value) ? value : fallback;
8
+ /** Slots are plain text, never HTML. Code snippets are escaped like every other field. */
9
+ export function fillTemplate(name, data, brand) {
10
+ if (!names[name])
11
+ throw new Error(`Unknown template: ${name}`);
12
+ const source = readFileSync(fileURLToPath(new URL(`${name}.html`, templateDir)), 'utf8');
13
+ const font = (file) => pathToFileURL(fileURLToPath(new URL(`fonts/${file}`, templateDir))).href;
14
+ const styles = `<style>
15
+ @font-face{font-family:'IBM Plex Sans';src:url('${font('IBMPlexSans.woff2')}')}@font-face{font-family:'IBM Plex Mono';src:url('${font('IBMPlexMono.woff2')}')}@font-face{font-family:'Space Grotesk';src:url('${font('SpaceGrotesk.woff2')}')}
16
+ :root{--ink:${color(brand.colors?.ink, '#172a35')};--paper:${color(brand.colors?.paper, '#eef3f3')};--accent:${color(brand.colors?.accent, '#245f73')};--accent2:${color(brand.colors?.accent2, '#d1e2df')};--display:'${family(brand.fonts?.display, 'Space Grotesk')}';--text:'${family(brand.fonts?.text, 'IBM Plex Sans')}';--mono:'${family(brand.fonts?.mono, 'IBM Plex Mono')}'}
17
+ *{box-sizing:border-box}html,body{margin:0;width:100%;height:100%}body{background:var(--paper);color:var(--ink);font-family:var(--text),sans-serif}.slide{width:100vw;height:100vh;padding:8%;display:flex;flex-direction:column;justify-content:space-between;overflow:hidden;background:var(--paper)}h1,h2,p,blockquote,pre{margin:0}h1,h2,blockquote{font-family:var(--display),sans-serif;line-height:1.08;overflow-wrap:anywhere}h1{font-size:clamp(36px,8vw,120px);letter-spacing:-.035em}h2,blockquote{font-size:clamp(30px,6vw,90px);letter-spacing:-.025em}p{font-size:clamp(18px,2.8vw,36px);line-height:1.35;max-width:40ch}.brand{font-size:clamp(15px,1.8vw,24px);font-weight:700}.accent{color:var(--accent)}.content{display:grid;gap:1.4em}pre{font-family:var(--mono),monospace;white-space:pre-wrap;overflow-wrap:anywhere;font-size:clamp(14px,2.3vw,30px);line-height:1.45;background:var(--accent2);padding:1em}.quote-mark{font-size:clamp(60px,12vw,150px);line-height:.7;color:var(--accent)}
18
+ </style>`;
19
+ return source.replace(/{{\s*([\w-]+)\s*}}/g, (_, key) => key === 'styles' ? styles : escape(key === 'brand' ? (data.brand ?? brand.name) : data[key]));
20
+ }
@@ -0,0 +1,173 @@
1
+ import { copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { basename, dirname, extname, isAbsolute, join, relative, resolve } from "node:path";
4
+ import { fileURLToPath, pathToFileURL } from "node:url";
5
+ import { parse } from "yaml";
6
+ import { UserError } from "../types.js";
7
+ import { encodeVideo, extractFrames, probeMedia, runTool } from "./ffmpeg.js";
8
+ import { renderHtml } from "./stills.js";
9
+ const sizes = { "9:16": [1080, 1920], "1:1": [1080, 1080], "16:9": [1920, 1080] };
10
+ const hyperframes = fileURLToPath(new URL("../../node_modules/.bin/hyperframes", import.meta.url));
11
+ function captionScript(vtt, aspect, config) {
12
+ const cues = [];
13
+ const timestamp = (value) => value.split(":").reduce((sum, part) => sum * 60 + Number(part), 0);
14
+ for (const block of vtt.replace(/\r\n?/g, "\n").split(/\n{2,}/).slice(1)) {
15
+ const lines = block.split("\n"), line = lines.findIndex(l => l.includes("-->"));
16
+ if (line < 0)
17
+ continue;
18
+ const match = lines[line].match(/^\s*((?:\d{2,}:)?\d{2}:\d{2}\.\d{3})\s+-->\s+((?:\d{2,}:)?\d{2}:\d{2}\.\d{3})(?:\s|$)/);
19
+ if (!match)
20
+ throw new UserError("Invalid WebVTT cue timing");
21
+ const start = timestamp(match[1]), end = timestamp(match[2]);
22
+ if (end <= start)
23
+ throw new UserError("Invalid WebVTT cue duration");
24
+ cues.push({ start, end, text: lines.slice(line + 1).join("\n").replace(/<[^>]*>/g, "") });
25
+ }
26
+ if (!cues.length)
27
+ throw new UserError("Caption burn-in requires at least one WebVTT cue");
28
+ const font = config.brand?.fonts?.text ? `${JSON.stringify(config.brand.fonts.text)}, BstudioCaption` : "BstudioCaption";
29
+ const data = JSON.stringify({ cues, font, bottom: aspect === "9:16" ? "17%" : "8%" }).replace(/</g, "\\u003c");
30
+ return `<style>@font-face { font-family: BstudioCaption; src: url("./bstudio-caption-font.woff2") format("woff2"); }</style><script>(() => {
31
+ const {cues, font, bottom} = ${data};
32
+ const root = document.querySelector('[data-composition-id]');
33
+ for (const cue of cues) {
34
+ const el = document.createElement('div');
35
+ el.className = 'clip';
36
+ el.dataset.start = String(cue.start);
37
+ el.dataset.duration = String(cue.end - cue.start);
38
+ el.dataset.trackIndex = '999';
39
+ const decoder = document.createElement('textarea');
40
+ decoder.innerHTML = cue.text;
41
+ el.textContent = decoder.value;
42
+ Object.assign(el.style, {position:'absolute', left:'10%', width:'80%', bottom,
43
+ textAlign:'center', whiteSpace:'pre-line', color:'#fff', backgroundColor:'rgba(0,0,0,.85)',
44
+ borderRadius:'12px', padding:'16px', boxSizing:'border-box', fontFamily:font,
45
+ fontSize:'48px', lineHeight:'1.2', zIndex:'2147483647'});
46
+ root.appendChild(el);
47
+ }
48
+ })();</script>`;
49
+ }
50
+ async function hasSubtitleFilter(io) {
51
+ const filters = await runTool(io, "ffmpeg", "ffmpeg", ["-hide_banner", "-filters"]);
52
+ return /^\s*[.A-Z|]+\s+subtitles\s/m.test(filters);
53
+ }
54
+ /** Render editable per-aspect HyperFrames projects or a VHS tape into asset-relative outputs. */
55
+ export async function renderVideo(assetDir, config, io, generatedVoice, zoneForAspect, metrics, projectDir) {
56
+ assetDir = resolve(assetDir);
57
+ const meta = parse(readFileSync(join(assetDir, "asset.yml"), "utf8"));
58
+ if (!meta || typeof meta !== "object")
59
+ throw new UserError("Invalid video asset.yml");
60
+ const source = join(assetDir, "source"), out = join(assetDir, "out"), frameDir = join(out, "frames");
61
+ const caption = join(source, "captions.vtt"), voice = generatedVoice ?? join(source, "voiceover.wav");
62
+ if (meta.captions?.burn && !existsSync(caption))
63
+ throw new UserError("Caption burn-in requested but source/captions.vtt is missing");
64
+ mkdirSync(out, { recursive: true });
65
+ const outputs = [];
66
+ if (existsSync(caption)) {
67
+ const contents = readFileSync(caption, "utf8");
68
+ if (!/^\uFEFF?WEBVTT(?:\s|$)/.test(contents))
69
+ throw new UserError("source/captions.vtt must be a WebVTT file");
70
+ const dest = join(out, "captions.vtt");
71
+ copyFileSync(caption, dest);
72
+ outputs.push({ file: "out/captions.vtt", bytes: statSync(dest).size });
73
+ }
74
+ const tape = existsSync(join(source, "demo.tape")) ? join(source, "demo.tape") : join(assetDir, "demo.tape");
75
+ if (meta.kind === "terminal-demo" || existsSync(tape)) {
76
+ if (!existsSync(tape))
77
+ throw new UserError("Terminal demo requires source/demo.tape");
78
+ if (meta.captions?.burn)
79
+ throw new UserError("Caption burn-in is not supported for VHS output");
80
+ const tapeText = readFileSync(tape, "utf8");
81
+ const names = [...tapeText.matchAll(/^\s*Output\s+(?:"([^"]+)"|'([^']+)'|(\S+))\s*(?:#.*)?$/gmi)].map(m => m[1] ?? m[2] ?? m[3]);
82
+ if (!names.length)
83
+ throw new UserError("VHS tape must declare an MP4 or GIF Output");
84
+ const tapeDir = dirname(tape);
85
+ for (const name of names) {
86
+ if (isAbsolute(name) || relative(tapeDir, resolve(tapeDir, name)).startsWith("..") || ![".mp4", ".gif"].includes(extname(name).toLowerCase()))
87
+ throw new UserError(`Unsafe or unsupported VHS Output: ${name}`);
88
+ }
89
+ if (new Set(names.map(name => basename(name))).size !== names.length)
90
+ throw new UserError("VHS Output filenames must be unique");
91
+ await runTool(io, "vhs", "vhs", [basename(tape)], tapeDir, { config, workspace: assetDir });
92
+ for (const name of names) {
93
+ const from = resolve(tapeDir, name), target = join(out, basename(name));
94
+ if (!existsSync(from))
95
+ throw new UserError(`VHS did not produce ${name}`);
96
+ if (extname(name).toLowerCase() === ".mp4") {
97
+ await encodeVideo(from, target, io, { voiceover: existsSync(voice) ? voice : undefined });
98
+ }
99
+ else {
100
+ if (existsSync(voice))
101
+ throw new UserError("VHS GIF output cannot carry voiceover; use MP4");
102
+ copyFileSync(from, target);
103
+ }
104
+ const info = await probeMedia(target, io);
105
+ metrics?.push({ file: `out/${basename(name)}`, minFontPx: null, minContrast: null, overflow: false, unmeasurable: ["VHS terminal demo (text not measured)"] });
106
+ outputs.push({ file: `out/${basename(name)}`, ...info });
107
+ mkdirSync(frameDir, { recursive: true });
108
+ const prefix = basename(name, extname(name));
109
+ const frames = [1, 2, 3].map(i => join(frameDir, `${prefix}-${i}.png`));
110
+ await extractFrames(target, frames, info.seconds, io);
111
+ for (const frame of frames)
112
+ outputs.push({ file: `out/frames/${basename(frame)}`, bytes: statSync(frame).size });
113
+ }
114
+ return outputs;
115
+ }
116
+ if (!Array.isArray(meta.aspects) || !meta.aspects.length || meta.aspects.some(a => typeof a !== "string" || !(a in sizes)) || new Set(meta.aspects).size !== meta.aspects.length) {
117
+ throw new UserError("Video asset.yml aspects must list distinct values from 9:16, 1:1 and 16:9");
118
+ }
119
+ if (!existsSync(hyperframes))
120
+ throw new UserError("HyperFrames is missing; run bstudio doctor; install: npm install (HyperFrames is an optional dependency)");
121
+ const useFilter = meta.captions?.burn ? await hasSubtitleFilter(io) : false;
122
+ for (const aspect of meta.aspects) {
123
+ const original = join(source, aspect), label = aspect.replace(":", "x");
124
+ if (!existsSync(join(original, "index.html")))
125
+ throw new UserError(`Missing HyperFrames composition: source/${aspect}/index.html`);
126
+ const raw = join(out, `.${label}-hyperframes.mp4`), target = join(out, `${label}.mp4`);
127
+ let temp;
128
+ try {
129
+ let project = original;
130
+ if (meta.captions?.burn && !useFilter) {
131
+ temp = mkdtempSync(join(tmpdir(), "bstudio-caption-"));
132
+ project = join(temp, "project");
133
+ cpSync(original, project, { recursive: true });
134
+ copyFileSync(fileURLToPath(new URL("../../templates/fonts/IBMPlexSans.woff2", import.meta.url)), join(project, "bstudio-caption-font.woff2"));
135
+ const index = join(project, "index.html"), html = readFileSync(index, "utf8");
136
+ if (!/<\/body\s*>/i.test(html))
137
+ throw new UserError(`Composition source/${aspect}/index.html needs a closing body tag for captions`);
138
+ writeFileSync(index, html.replace(/<\/body\s*>/i, `${captionScript(readFileSync(caption, "utf8"), aspect, config)}</body>`));
139
+ }
140
+ if (metrics && zoneForAspect) {
141
+ const [width, height] = sizes[aspect], safe = zoneForAspect(aspect);
142
+ const index = join(project, "index.html"), composition = readFileSync(index, "utf8");
143
+ const base = `<base href="${pathToFileURL(`${project}/`).href}">`;
144
+ const html = /<head(?:\s[^>]*)?>/i.test(composition) ? composition.replace(/<head(?:\s[^>]*)?>/i, `$&${base}`) : base + composition;
145
+ const image = join(out, `.${label}-metrics.png`);
146
+ try {
147
+ const result = await renderHtml({ html, width, height, out: image, assetDir: temp ? project : assetDir, projectDir, safeZone: safe.zone, sampleTimeline: true });
148
+ metrics.push({ file: `out/${label}.mp4`, ...result.metrics, zoneDescription: safe.description, texts: result.metrics.nodes.map(node => node.text) });
149
+ }
150
+ finally {
151
+ rmSync(image, { force: true });
152
+ }
153
+ }
154
+ await runTool(io, "hyperframes", hyperframes, ["render", project, "--output", raw, "--format", "mp4", "--workers", "1", "--refuse-outside-files"], undefined, { config, workspace: assetDir });
155
+ await encodeVideo(raw, target, io, { captions: useFilter ? caption : undefined, voiceover: existsSync(voice) ? voice : undefined });
156
+ }
157
+ finally {
158
+ rmSync(raw, { force: true });
159
+ if (temp)
160
+ rmSync(temp, { recursive: true, force: true });
161
+ }
162
+ const info = await probeMedia(target, io), [width, height] = sizes[aspect];
163
+ if (info.width !== width || info.height !== height)
164
+ throw new UserError(`${aspect} composition rendered ${info.width}x${info.height}, expected ${width}x${height}`);
165
+ outputs.push({ file: `out/${label}.mp4`, aspect, ...info });
166
+ mkdirSync(frameDir, { recursive: true });
167
+ const frames = [1, 2, 3].map(i => join(frameDir, `${label}-${i}.png`));
168
+ await extractFrames(target, frames, info.seconds, io);
169
+ for (const frame of frames)
170
+ outputs.push({ file: `out/frames/${basename(frame)}`, aspect, bytes: statSync(frame).size });
171
+ }
172
+ return outputs;
173
+ }
@@ -0,0 +1,201 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ const numberWords = Object.fromEntries(['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty'].map((word, n) => [word, n]));
4
+ const metricPattern = /(?<![\w.])(\$\s*)?(\d[\d,]*(?:\.\d+)?(?!\d|\.\d)|(?:zero|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty|half|double|twice)\b)\s*(thousand\b|million\b|billion\b|[kmb](?![a-z]))?\s*\+?\s*(%|percent\b|times\b|[x×](?!\w)|users?\b|customers?\b|stars?\b|downloads?\b|dollars?\b|ms\b|seconds?\b|minutes?\b|hours?\b|days?\b|weeks?\b|months?\b|years?\b|bytes?\b|[gmk]b\b)?/gi;
5
+ function metrics(text) {
6
+ const result = [];
7
+ for (const match of text.matchAll(metricPattern)) {
8
+ const token = match[0].trim(), unit = match[4]?.toLowerCase();
9
+ const word = match[2].toLowerCase();
10
+ const multiplier = match[3]?.toLowerCase();
11
+ const number = (word === 'half' ? .5 : word === 'double' || word === 'twice' ? 2 : numberWords[word] ?? Number(word.replace(/,/g, ''))) * (multiplier === 'k' || multiplier === 'thousand' ? 1000 : multiplier === 'm' || multiplier === 'million' ? 1000000 : multiplier === 'b' || multiplier === 'billion' ? 1000000000 : 1);
12
+ const normalizedUnit = match[1] || unit?.startsWith('dollar') ? '$' : unit === 'percent' ? '%' : unit === '×' || unit === 'times' || ['half', 'double', 'twice'].includes(word) ? 'x' : unit?.replace(/s$/, '') ?? '';
13
+ result.push({ token, key: `${number}:${normalizedUnit}`, metric: !!normalizedUnit });
14
+ }
15
+ return result;
16
+ }
17
+ export function runGates(post, pack, assets, brief, config, projectDir) {
18
+ const failures = { policy: [], disclosure: [], specs: [], accessibility: [], 'fabricated-metrics': [], rights: [] };
19
+ const warnings = [...(pack.notes ?? [])];
20
+ const policySources = [{ source: pack.aiSource, lastVerified: pack.aiLastVerified }, ...Object.values(pack.disclosure).filter((rule) => typeof rule === 'object'), ...(typeof pack.sponsorship === 'object' ? [pack.sponsorship] : [])];
21
+ for (const source of policySources)
22
+ if (!source.lastVerified || !Number.isFinite(Date.parse(source.lastVerified)) || Date.now() - Date.parse(source.lastVerified) > 90 * 86400000)
23
+ warnings.push(`Policy verification is missing or stale: ${source.source || pack.sources.join(', ') || pack.id}`);
24
+ const byId = new Map(assets.map(a => [a.id, a]));
25
+ const used = new Set();
26
+ const visit = (id) => { if (used.has(id))
27
+ return; used.add(id); for (const child of byId.get(id)?.embeds ?? [])
28
+ visit(child); };
29
+ post.media.forEach(m => visit(m.asset));
30
+ const selected = assets.filter(a => used.has(a.id));
31
+ const add = (id, message) => failures[id].push(message);
32
+ for (const id of used)
33
+ if (!byId.has(id))
34
+ add('rights', `Missing asset metadata for ${id}`);
35
+ if (pack.ai === 'none' && post.body.trim())
36
+ add('policy', 'Generated text is not permitted');
37
+ if (pack.ai === 'outline' && post.body.split('\n').some(line => {
38
+ const text = line.trim();
39
+ if (!text || /^#{1,6}\s+\S/.test(text))
40
+ return false;
41
+ const bullet = text.match(/^(?:[-*+]\s+|\d+[.)]\s+)(.*)$/);
42
+ return !bullet || bullet[1].trim().split(/\s+/).length > 20;
43
+ }))
44
+ add('policy', 'Only headings and brief outline bullets (at most 20 words) are permitted');
45
+ for (const kind of ['text', 'media', 'voice']) {
46
+ const applies = kind === 'text' ? !!post.body.trim() : kind === 'voice' ? selected.some(a => a.voiceGenerated || a.kind === 'voiceover' && a.aiGenerated) : selected.some(a => a.kind !== 'voiceover' && a.aiGenerated);
47
+ if (!applies)
48
+ continue;
49
+ const rule = pack.disclosure[kind];
50
+ const value = post.disclosure?.[kind]?.trim();
51
+ const accepts = typeof rule === 'object' && kind === 'text' && pack.ai === 'draft' ? rule.acceptsWhenGenerated ?? rule.accepts : typeof rule === 'object' ? rule.accepts : undefined;
52
+ if (typeof rule === 'object' && (!value || accepts?.length && !accepts.some(option => option.toLowerCase() === value.toLowerCase())))
53
+ add('disclosure', `${kind} disclosure required: ${rule.rule} (${rule.source})`);
54
+ if (rule === 'unknown')
55
+ warnings.push(`${kind} disclosure unknown; verify ${pack.sources.join(', ') || pack.id}`);
56
+ }
57
+ if (post.sponsored && typeof pack.sponsorship === 'object') {
58
+ const rule = pack.sponsorship, value = post.disclosure?.sponsorship?.trim();
59
+ if (!value || rule.accepts?.length && !rule.accepts.some(option => option.toLowerCase() === value.toLowerCase()))
60
+ add('disclosure', `sponsorship disclosure required: ${rule.rule} (${rule.source})`);
61
+ }
62
+ const check = (label, value, spec, compare = (a, b) => a > b) => {
63
+ if (value === undefined || spec === undefined)
64
+ return;
65
+ if (spec === 'unknown')
66
+ warnings.push(`${label} unknown; verify ${pack.sources.join(', ') || pack.id}`);
67
+ else {
68
+ if (compare(value, spec.value))
69
+ add('specs', `${label} exceeds ${spec.value} (${spec.source})`);
70
+ if (!spec.lastVerified || !Number.isFinite(Date.parse(spec.lastVerified)) || Date.now() - Date.parse(spec.lastVerified) > 90 * 86400000)
71
+ warnings.push(`${label} verification is missing or stale: ${spec.source}`);
72
+ }
73
+ };
74
+ const segmenter = new Intl.Segmenter('en', { granularity: 'grapheme' });
75
+ const length = (text) => {
76
+ if (post.platform === 'bluesky')
77
+ return [...segmenter.segment(text)].length;
78
+ const linked = text.replace(/https?:\/\/[^\s<>]*[^\s<>.,;:!?\])}'"]/g, 'x'.repeat(23));
79
+ if (post.platform === 'mastodon')
80
+ return [...linked].length;
81
+ if (post.platform !== 'x')
82
+ return [...text].length;
83
+ let count = 0;
84
+ for (const { segment } of segmenter.segment(linked)) {
85
+ if (/\p{Extended_Pictographic}/u.test(segment)) {
86
+ count += 2;
87
+ continue;
88
+ }
89
+ for (const char of segment) {
90
+ const cp = char.codePointAt(0);
91
+ count += cp <= 4351 || cp >= 8192 && cp <= 8205 || cp >= 8208 && cp <= 8223 || cp >= 8242 && cp <= 8247 ? 1 : 2;
92
+ }
93
+ }
94
+ return count;
95
+ };
96
+ for (const item of [post.body, ...(post.thread ?? [])])
97
+ check('text limit', length(item), pack.textLimit);
98
+ if (post.title)
99
+ check('title limit', [...post.title].length, pack.titleLimit);
100
+ if (['devto', 'hashnode', 'gist', 'github-discussion', 'reddit', 'substack', 'lemmy'].includes(post.platform) && !post.title?.trim())
101
+ add('specs', 'Missing required title');
102
+ const anchors = new Set(brief.map(section => section.anchor));
103
+ if (!post.evidence.length || post.evidence.some(anchor => !anchors.has(anchor)))
104
+ add('specs', 'Missing or unknown evidence anchor');
105
+ const mb = pack.marketBlasterMedia;
106
+ if (mb) {
107
+ const kinds = new Set(post.media.map(m => m.kind));
108
+ for (const kind of kinds)
109
+ if (!mb.allowedKinds.includes(kind) || kind === 'image' && post.media.some(m => m.kind === kind && /\.gif$/i.test(m.file)))
110
+ add('specs', `Market Blaster does not support ${kind} media (${mb.source})`);
111
+ for (const group of mb.exclusiveKinds ?? [])
112
+ if (group.filter(kind => kinds.has(kind)).length > 1)
113
+ add('specs', `Market Blaster does not support combining ${group.join(' and ')} (${mb.source})`);
114
+ if (mb.maxCount !== undefined && post.media.length > mb.maxCount)
115
+ add('specs', `Market Blaster attachment count exceeds ${mb.maxCount} (${mb.source})`);
116
+ }
117
+ for (const media of post.media) {
118
+ const spec = pack.media.find(s => s.kind === media.kind);
119
+ const output = byId.get(media.asset)?.outputs.find(o => media.file === `assets/${media.asset}/${o.file}`);
120
+ if (!output)
121
+ add('specs', `Media is not a declared output of ${media.asset}: ${media.file}`);
122
+ // A pack format without a media limits entry means the limits are unverified, not that the media is unsupported.
123
+ const formatFor = { image: ['image', 'carousel'], gif: ['image'], video: ['video'], document: ['carousel', 'article'] };
124
+ if (!spec) {
125
+ if (formatFor[media.kind]?.some(format => pack.formats.includes(format)))
126
+ warnings.push(`${media.kind} limits unknown; verify ${pack.sources.join(', ') || pack.id}`);
127
+ else
128
+ add('specs', `Unsupported ${media.kind} media`);
129
+ }
130
+ else {
131
+ check(`${media.kind} count`, post.media.filter(m => m.kind === media.kind).length, spec.maxCount);
132
+ check(`${media.kind} bytes`, output?.bytes, spec.maxBytes);
133
+ check(`${media.kind} duration`, output?.seconds, spec.maxSeconds);
134
+ check(`${media.kind} minimum duration`, output?.seconds, spec.minSeconds, (a, b) => a < b);
135
+ check(`${media.kind} width`, output?.width, spec.width);
136
+ check(`${media.kind} height`, output?.height, spec.height);
137
+ if (spec.aspectRatios === 'unknown')
138
+ warnings.push(`aspect ratios unknown; verify ${pack.sources.join(', ') || pack.id}`);
139
+ else if (spec.aspectRatios && output?.aspect && !spec.aspectRatios.value.includes(output.aspect))
140
+ add('specs', `Unsupported aspect ${output.aspect} (${spec.aspectRatios.source})`);
141
+ }
142
+ if (['image', 'gif', 'document'].includes(media.kind) && !media.alt?.trim())
143
+ add('accessibility', `Missing alt text for ${media.asset}`);
144
+ if (media.kind === 'video' && !byId.get(media.asset)?.outputs.some(o => /\.vtt$/i.test(o.file)))
145
+ add('accessibility', `Missing captions for ${media.asset}`);
146
+ }
147
+ for (const asset of selected) {
148
+ if (['gemini', 'openai', 'omp'].includes(asset.provider) && !asset.license?.trim())
149
+ add('rights', `Missing license for ${asset.id}`);
150
+ if (asset.kind === 'logo' && !asset.trademarkChecked)
151
+ add('rights', `Trademark search not checked for ${asset.id}`);
152
+ for (const metric of asset.metrics ?? []) {
153
+ for (const kind of metric.unmeasurable ?? [])
154
+ warnings.push(`Text cannot be checked in ${kind} in ${metric.file}`);
155
+ const width = asset.outputs.find(o => o.file === metric.file)?.width ?? 1080;
156
+ const minimum = (pack.accessibility?.minFontPx ?? 24) * width / 1080;
157
+ if (metric.minFontPx !== null && metric.minFontPx < minimum)
158
+ add('accessibility', `Text too small in ${metric.file}`);
159
+ if (metric.nodes?.length) {
160
+ for (const node of metric.nodes) {
161
+ const threshold = node.fontPx >= (pack.accessibility?.largeTextPx ?? (node.bold ? 18.66 : 24)) ? pack.accessibility?.minContrastLarge ?? 3 : pack.accessibility?.minContrast ?? 4.5;
162
+ if (node.contrast === null)
163
+ warnings.push(`Contrast cannot be measured in ${metric.file}`);
164
+ else if (node.contrast < threshold)
165
+ add('accessibility', `Insufficient contrast in ${metric.file}`);
166
+ }
167
+ }
168
+ else if (metric.minFontPx !== null) {
169
+ if (metric.minContrast === null)
170
+ warnings.push(`Contrast cannot be measured in ${metric.file}`);
171
+ else if (metric.minContrast < (metric.minFontPx >= (pack.accessibility?.largeTextPx ?? 24) ? pack.accessibility?.minContrastLarge ?? 3 : pack.accessibility?.minContrast ?? 4.5))
172
+ add('accessibility', `Insufficient contrast in ${metric.file}`);
173
+ }
174
+ if (metric.overflow)
175
+ add('accessibility', `Text is cut off in ${metric.file}`);
176
+ if (metric.edge)
177
+ warnings.push(`Text enters the ${metric.zoneDescription ?? 'default 5% margin'} in ${metric.file}; overlays or cropping may cover it`);
178
+ }
179
+ }
180
+ const measured = new Set(selected.filter(a => a.kind === 'video' || a.kind === 'terminal-demo').flatMap(a => a.outputs.flatMap(o => o.seconds ? [Math.floor(o.seconds), Math.ceil(o.seconds), Number(o.seconds.toFixed(1))].map(s => `${s}:second`) : [])));
181
+ const evidence = new Set(metrics(brief.map(s => `${s.title}\n${s.body}`).join('\n')).map(m => m.key));
182
+ const waived = new Set(config.grounding.waive.flatMap(w => metrics(w).map(m => m.key)));
183
+ const captions = projectDir ? selected.flatMap(asset => asset.outputs.filter(o => /\.vtt$/i.test(o.file)).flatMap(o => {
184
+ const path = join(projectDir, 'assets', asset.id, o.file);
185
+ return existsSync(path) ? [readFileSync(path, 'utf8').replace(/^WEBVTT[^\n]*\n?/i, '').replace(/^(?:[^\n]*\n)?[^\n]*-->[^\n]*$/gm, '')] : [];
186
+ })) : [];
187
+ const text = [post.title ?? '', post.body, ...(post.thread ?? []), ...post.media.map(m => m.alt), ...selected.flatMap(a => (a.metrics ?? []).flatMap(m => m.texts ?? [])), ...captions].join('\n').replace(/https?:\/\/\S+/g, '').replace(/\b[a-z][\w]*-\d[\w.-]*/gi, '').replace(/^\s*\d+[.)]\s+/gm, '');
188
+ const seen = new Set();
189
+ for (const sentence of text.split(/(?<=[.!?])\s+|\n/))
190
+ for (const token of metrics(sentence)) {
191
+ if (seen.has(token.key) || evidence.has(token.key) || waived.has(token.key) || config.grounding.waive.some(w => w.toLowerCase() === token.token.toLowerCase()) || /\b(?:video|demo|clip|recording|shorts?)\b/i.test(sentence) && measured.has(token.key))
192
+ continue;
193
+ seen.add(token.key);
194
+ if (token.metric)
195
+ add('fabricated-metrics', `Ungrounded metric: ${token.token}`);
196
+ else if (/\d/.test(token.token))
197
+ warnings.push(`Ungrounded version or identifier: ${token.token}`);
198
+ }
199
+ const result = Object.keys(failures).map(id => ({ id, pass: failures[id].length === 0, message: failures[id].join('; ') || 'Passed', ...(id === 'rights' && failures.rights.some(s => s.startsWith('Missing license')) ? { unfixable: true } : {}) }));
200
+ return Object.assign(result, { warnings });
201
+ }