@lifeaitools/rdc-skills 0.13.1 → 0.13.3

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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rdc",
3
- "version": "0.13.1",
3
+ "version": "0.13.2",
4
4
  "description": "RDC typed-agent dispatch skill suite for Claude Code — plan, build, review, overnight unattended builds with work-item tracking and TDD enforcement.",
5
5
  "author": {
6
6
  "name": "LIFEAI",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lifeaitools/rdc-skills",
3
- "version": "0.13.1",
3
+ "version": "0.13.3",
4
4
  "description": "RDC typed-agent dispatch skill suite for Claude Code - plan, build, review, overnight builds",
5
5
  "keywords": [
6
6
  "claude-code",
@@ -0,0 +1,400 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * rdc:brochure — zip/folder/html/url/markdown → PDF via Puppeteer.
4
+ * See skills/brochure/SKILL.md for the contract.
5
+ */
6
+ import { execSync, spawnSync } from 'node:child_process';
7
+ import { createHash } from 'node:crypto';
8
+ import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync, copyFileSync } from 'node:fs';
9
+ import { homedir, tmpdir } from 'node:os';
10
+ import { dirname, basename, extname, join, resolve, relative } from 'node:path';
11
+ import { pathToFileURL, fileURLToPath } from 'node:url';
12
+ import { createRequire } from 'node:module';
13
+
14
+ const AUTO_FIT_CSS = `
15
+ /* rdc:brochure --auto-fit corrective stylesheet
16
+ Generic print-overflow safety net. Applied AFTER document stylesheets. */
17
+ @media print, screen {
18
+ html, body { overflow: visible !important; }
19
+ body { max-width: 100% !important; }
20
+ *, *::before, *::after { box-sizing: border-box; }
21
+
22
+ img, svg, video, canvas, iframe, object, embed {
23
+ max-width: 100% !important;
24
+ height: auto !important;
25
+ object-fit: contain;
26
+ }
27
+ figure, .figure, picture { break-inside: avoid; page-break-inside: avoid; max-width: 100%; }
28
+
29
+ table {
30
+ table-layout: fixed !important;
31
+ width: 100% !important;
32
+ max-width: 100% !important;
33
+ word-wrap: break-word;
34
+ overflow-wrap: anywhere;
35
+ border-collapse: collapse;
36
+ }
37
+ th, td { word-wrap: break-word; overflow-wrap: anywhere; max-width: 100%; }
38
+ thead { display: table-header-group; }
39
+ tr, td, th { break-inside: avoid; page-break-inside: avoid; }
40
+
41
+ pre, code, kbd, samp { white-space: pre-wrap !important; word-break: break-word; overflow-wrap: anywhere; max-width: 100%; }
42
+ pre { break-inside: avoid; page-break-inside: avoid; }
43
+
44
+ h1, h2, h3, h4, h5, h6 { break-after: avoid; page-break-after: avoid; }
45
+ h1 + *, h2 + *, h3 + *, h4 + * { break-before: avoid; }
46
+ p, li { orphans: 3; widows: 3; }
47
+
48
+ /* Generic wide-content sentinels */
49
+ .wide, .full-bleed, .panorama { max-width: 100% !important; }
50
+
51
+ /* Avoid blank-page artifacts from oversized flex/grid containers */
52
+ [style*="position: fixed"], [style*="position:fixed"] { position: static !important; }
53
+ }
54
+ `;
55
+
56
+ const HERE = dirname(fileURLToPath(import.meta.url));
57
+ const REPO_ROOT = resolve(HERE, '..');
58
+ const TEMPLATES_DIR = join(REPO_ROOT, 'scaffold', 'templates');
59
+
60
+ // --- args ------------------------------------------------------------------
61
+ const argv = process.argv.slice(2);
62
+ const opts = { template: 'studio-default', format: 'Letter', printEmulate: true, keepWorkdir: false, autoFit: false, scale: 1 };
63
+ let input;
64
+ for (let i = 0; i < argv.length; i++) {
65
+ const a = argv[i];
66
+ if (a === '--out') opts.out = argv[++i];
67
+ else if (a === '--template') opts.template = argv[++i];
68
+ else if (a === '--format') opts.format = argv[++i];
69
+ else if (a === '--margin') opts.margin = argv[++i];
70
+ else if (a === '--no-print-emulate') opts.printEmulate = false;
71
+ else if (a === '--keep-workdir') opts.keepWorkdir = true;
72
+ else if (a === '--auto-fit') opts.autoFit = true;
73
+ else if (a === '--scale') opts.scale = parseFloat(argv[++i]);
74
+ else if (!input) input = a;
75
+ }
76
+ if (!input) {
77
+ console.error('usage: rdc-brochure.mjs <zip|folder|html|md|url> [--out path] [--template name] [--format Letter|A4]');
78
+ process.exit(2);
79
+ }
80
+
81
+ // --- helpers ---------------------------------------------------------------
82
+ const isUrl = /^https?:\/\//i.test(input);
83
+ const hash = createHash('sha1').update(input).digest('hex').slice(0, 10);
84
+ const workRoot = join(tmpdir(), 'rdc-brochure', hash);
85
+ mkdirSync(workRoot, { recursive: true });
86
+
87
+ const log = (...a) => console.log('[brochure]', ...a);
88
+
89
+ function human(n) {
90
+ const u = ['B', 'KB', 'MB', 'GB'];
91
+ let i = 0;
92
+ while (n >= 1024 && i < u.length - 1) { n /= 1024; i++; }
93
+ return `${n.toFixed(1)} ${u[i]}`;
94
+ }
95
+
96
+ function walk(dir) {
97
+ const out = [];
98
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
99
+ const p = join(dir, e.name);
100
+ if (e.isDirectory()) out.push(...walk(p));
101
+ else out.push(p);
102
+ }
103
+ return out;
104
+ }
105
+
106
+ // --- ensure puppeteer ------------------------------------------------------
107
+ async function loadPuppeteer() {
108
+ try { return (await import('puppeteer')).default; } catch {}
109
+ // Try a local cache install.
110
+ const cacheDir = join(homedir(), '.cache', 'rdc-brochure');
111
+ mkdirSync(cacheDir, { recursive: true });
112
+ if (!existsSync(join(cacheDir, 'package.json'))) {
113
+ writeFileSync(join(cacheDir, 'package.json'), JSON.stringify({ name: 'rdc-brochure-cache', private: true }, null, 2));
114
+ }
115
+ if (!existsSync(join(cacheDir, 'node_modules', 'puppeteer'))) {
116
+ log('installing puppeteer into', cacheDir);
117
+ execSync('npm install puppeteer --no-audit --no-fund --loglevel=error', { cwd: cacheDir, stdio: 'inherit' });
118
+ }
119
+ const req = createRequire(join(cacheDir, 'package.json'));
120
+ const mod = req('puppeteer');
121
+ return mod.default || mod;
122
+ }
123
+
124
+ // --- cross-platform unzip --------------------------------------------------
125
+ // Pure-Node first (adm-zip — works on every platform, no external binary).
126
+ // If the lib cannot be resolved or installed, fall back to a platform-native
127
+ // extractor: `unzip` on POSIX, PowerShell `Expand-Archive` on win32.
128
+ function loadAdmZip() {
129
+ try { return createRequire(import.meta.url)('adm-zip'); } catch {}
130
+ // Reuse the puppeteer on-demand cache dir for an isolated local install.
131
+ const cacheDir = join(homedir(), '.cache', 'rdc-brochure');
132
+ mkdirSync(cacheDir, { recursive: true });
133
+ if (!existsSync(join(cacheDir, 'package.json'))) {
134
+ writeFileSync(join(cacheDir, 'package.json'), JSON.stringify({ name: 'rdc-brochure-cache', private: true }, null, 2));
135
+ }
136
+ if (!existsSync(join(cacheDir, 'node_modules', 'adm-zip'))) {
137
+ try {
138
+ log('installing adm-zip into', cacheDir);
139
+ execSync('npm install adm-zip --no-audit --no-fund --loglevel=error', { cwd: cacheDir, stdio: 'inherit' });
140
+ } catch { return null; }
141
+ }
142
+ try { return createRequire(join(cacheDir, 'package.json'))('adm-zip'); } catch { return null; }
143
+ }
144
+
145
+ function extractZip(zipPath, destDir) {
146
+ mkdirSync(destDir, { recursive: true });
147
+ const AdmZip = loadAdmZip();
148
+ if (AdmZip) {
149
+ new AdmZip(zipPath).extractAllTo(destDir, /* overwrite */ true);
150
+ return;
151
+ }
152
+ // Fallback: platform-native extractor.
153
+ log('adm-zip unavailable — falling back to platform unzip');
154
+ let r;
155
+ if (process.platform === 'win32') {
156
+ r = spawnSync('powershell', ['-NoProfile', '-Command',
157
+ `Expand-Archive -Path '${zipPath}' -DestinationPath '${destDir}' -Force`], { stdio: 'inherit' });
158
+ } else {
159
+ r = spawnSync('unzip', ['-o', '-q', zipPath, '-d', destDir], { stdio: 'inherit' });
160
+ }
161
+ if (!r || r.status !== 0) throw new Error('unzip failed (no pure-Node lib and platform extractor failed)');
162
+ }
163
+
164
+ // --- stage input -----------------------------------------------------------
165
+ function stageInput() {
166
+ const stageDir = join(workRoot, 'src');
167
+ mkdirSync(stageDir, { recursive: true });
168
+ if (isUrl) return { kind: 'url', url: input, stageDir };
169
+ const abs = resolve(input);
170
+ if (!existsSync(abs)) throw new Error(`not found: ${abs}`);
171
+ const st = statSync(abs);
172
+ if (st.isDirectory()) return { kind: 'folder', root: abs, stageDir: abs };
173
+ const ext = extname(abs).toLowerCase();
174
+ if (ext === '.zip') {
175
+ log('extracting zip to', stageDir);
176
+ extractZip(abs, stageDir);
177
+ return { kind: 'folder', root: stageDir, stageDir };
178
+ }
179
+ if (ext === '.html' || ext === '.htm') return { kind: 'html', file: abs, stageDir: dirname(abs) };
180
+ if (ext === '.md' || ext === '.markdown') return { kind: 'md', file: abs, stageDir: dirname(abs) };
181
+ throw new Error(`unsupported input: ${ext || '(no extension)'}`);
182
+ }
183
+
184
+ // --- pick HTML in render mode ----------------------------------------------
185
+ function pickHtml(rootDir) {
186
+ const htmls = walk(rootDir).filter((p) => /\.html?$/i.test(p));
187
+ if (!htmls.length) return null;
188
+ const scored = htmls.map((p) => {
189
+ const text = readFileSync(p, 'utf8');
190
+ const size = statSync(p).size;
191
+ let score = 0;
192
+ if (/@page\b/.test(text)) score += 1000;
193
+ if (/@media\s+print/i.test(text)) score += 500;
194
+ if (/-print\.html?$/i.test(p)) score += 300;
195
+ if (/brochure\.html?$/i.test(p)) score += 250;
196
+ if (/(^|[\\/])print\.html?$/i.test(p)) score += 250;
197
+ if (/standalone/i.test(basename(p))) score -= 50; // usually huge embedded duplicate
198
+ score += Math.min(size / 1024, 200); // size as tiebreaker, capped
199
+ return { p, score, size };
200
+ }).sort((a, b) => b.score - a.score);
201
+ return scored[0].p;
202
+ }
203
+
204
+ // --- compose mode ----------------------------------------------------------
205
+ function listTemplates() {
206
+ if (!existsSync(TEMPLATES_DIR)) return [];
207
+ return readdirSync(TEMPLATES_DIR)
208
+ .map((f) => /^brochure-(.+)\.html$/i.exec(f))
209
+ .filter(Boolean)
210
+ .map((m) => m[1])
211
+ .sort();
212
+ }
213
+
214
+ async function composeFromFolder(root, file) {
215
+ const tpl = join(TEMPLATES_DIR, `brochure-${opts.template}.html`);
216
+ if (!existsSync(tpl)) {
217
+ const available = listTemplates();
218
+ const list = available.length ? available.join(', ') : '(none found)';
219
+ throw new Error(`unknown template "${opts.template}". Available template(s): ${list}`);
220
+ }
221
+ let html = readFileSync(tpl, 'utf8');
222
+
223
+ let mdFiles = [];
224
+ if (file) mdFiles = [file];
225
+ else mdFiles = walk(root).filter((p) => /\.(md|markdown)$/i.test(p)).sort();
226
+
227
+ const title = (() => {
228
+ for (const p of mdFiles) {
229
+ const m = readFileSync(p, 'utf8').match(/^#\s+(.+)$/m);
230
+ if (m) return m[1].trim();
231
+ }
232
+ return basename(file || root);
233
+ })();
234
+
235
+ const sections = mdFiles.map((p) => {
236
+ const md = readFileSync(p, 'utf8');
237
+ // Only prepend the filename heading when the markdown has no leading ATX heading
238
+ // of its own. Avoids a redundant <h2>filename</h2> stacked above a "# Title".
239
+ const firstNonEmpty = md.replace(/\r\n/g, '\n').split('\n').find((l) => l.trim() !== '') || '';
240
+ const hasLeadingHeading = /^#{1,6}\s+\S/.test(firstNonEmpty.trim());
241
+ const heading = hasLeadingHeading ? '' : `<h2>${escapeHtml(basename(p, extname(p)))}</h2>`;
242
+ return `<section class="brochure-section">${heading}${mdToHtml(md, dirname(p))}</section>`;
243
+ }).join('\n');
244
+
245
+ html = html.replace(/\{\{TITLE\}\}/g, escapeHtml(title)).replace(/\{\{SECTIONS\}\}/g, sections);
246
+
247
+ const tokensCss = findSibling(root || dirname(file), 'tokens.css');
248
+ if (tokensCss) html = html.replace('/* TOKENS_INJECT */', readFileSync(tokensCss, 'utf8'));
249
+
250
+ const outHtml = join(workRoot, 'composed.html');
251
+ writeFileSync(outHtml, html);
252
+ return outHtml;
253
+ }
254
+
255
+ function findSibling(dir, name) {
256
+ if (!dir) return null;
257
+ const p = join(dir, name);
258
+ return existsSync(p) ? p : null;
259
+ }
260
+
261
+ function escapeHtml(s) {
262
+ return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
263
+ }
264
+
265
+ // Minimal markdown — headings, paragraphs, lists, bold/italic, inline code, fenced code, images.
266
+ function mdToHtml(md, baseDir) {
267
+ let out = md.replace(/\r\n/g, '\n');
268
+ out = out.replace(/```([a-z]*)\n([\s\S]*?)```/g, (_, lang, body) => `<pre><code class="lang-${escapeHtml(lang)}">${escapeHtml(body)}</code></pre>`);
269
+ out = out.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, (_, alt, src) => `<img alt="${escapeHtml(alt)}" src="${resolveImg(src, baseDir)}"/>`);
270
+ out = out.replace(/^######\s+(.+)$/gm, '<h6>$1</h6>')
271
+ .replace(/^#####\s+(.+)$/gm, '<h5>$1</h5>')
272
+ .replace(/^####\s+(.+)$/gm, '<h4>$1</h4>')
273
+ .replace(/^###\s+(.+)$/gm, '<h3>$1</h3>')
274
+ .replace(/^##\s+(.+)$/gm, '<h2>$1</h2>')
275
+ .replace(/^#\s+(.+)$/gm, '<h1>$1</h1>');
276
+ out = out.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>').replace(/\*([^*]+)\*/g, '<em>$1</em>').replace(/`([^`]+)`/g, '<code>$1</code>');
277
+ out = out.replace(/(?:^|\n)((?:[-*]\s+.+\n?)+)/g, (_, block) => `\n<ul>${block.trim().split(/\n/).map((l) => `<li>${l.replace(/^[-*]\s+/, '')}</li>`).join('')}</ul>\n`);
278
+ out = out.split(/\n{2,}/).map((b) => /^<(h\d|ul|ol|pre|img|section|div)/.test(b.trim()) ? b : `<p>${b.trim()}</p>`).join('\n');
279
+ return out;
280
+ }
281
+
282
+ function resolveImg(src, baseDir) {
283
+ if (/^https?:|^data:/.test(src)) return src;
284
+ const p = resolve(baseDir, src);
285
+ if (!existsSync(p)) return src;
286
+ return pathToFileURL(p).href;
287
+ }
288
+
289
+ // --- render ----------------------------------------------------------------
290
+ async function render(htmlSource) {
291
+ const puppeteer = await loadPuppeteer();
292
+ const browser = await puppeteer.launch({ headless: 'new', args: ['--no-sandbox', '--disable-setuid-sandbox', '--font-render-hinting=none'] });
293
+ try {
294
+ const page = await browser.newPage();
295
+ page.on('pageerror', (e) => log('pageerror:', e.message));
296
+ const url = htmlSource.startsWith('http') ? htmlSource : pathToFileURL(htmlSource).href;
297
+ log('loading', url);
298
+ await page.goto(url, { waitUntil: 'networkidle0', timeout: 180_000 });
299
+ await page.evaluateHandle('document.fonts.ready');
300
+ await new Promise((r) => setTimeout(r, 1500));
301
+ if (opts.printEmulate) await page.emulateMediaType('print');
302
+
303
+ if (opts.autoFit) {
304
+ await page.addStyleTag({ content: AUTO_FIT_CSS });
305
+ const report = await page.evaluate(() => {
306
+ const issues = [];
307
+ const all = document.body.querySelectorAll('*');
308
+ const pageWidthPx = document.documentElement.clientWidth;
309
+ for (const el of all) {
310
+ const r = el.getBoundingClientRect();
311
+ if (r.width > pageWidthPx + 4) {
312
+ issues.push({ tag: el.tagName, cls: el.className?.toString().slice(0, 60) || '', width: Math.round(r.width), pageWidth: pageWidthPx });
313
+ if (issues.length >= 25) break;
314
+ }
315
+ }
316
+ return issues;
317
+ });
318
+ if (report.length) {
319
+ log(`auto-fit: ${report.length} overflow element(s) detected — corrective CSS applied`);
320
+ for (const r of report.slice(0, 8)) log(` · ${r.tag}${r.cls ? '.' + r.cls : ''} width=${r.width}px (page=${r.pageWidth}px)`);
321
+ } else {
322
+ log('auto-fit: no overflow detected after corrective CSS');
323
+ }
324
+ await new Promise((r) => setTimeout(r, 400));
325
+ }
326
+
327
+ const outPath = resolve(opts.out || defaultOutPath());
328
+ mkdirSync(dirname(outPath), { recursive: true });
329
+
330
+ const pdfOpts = {
331
+ path: outPath,
332
+ format: opts.format,
333
+ printBackground: true,
334
+ preferCSSPageSize: true,
335
+ displayHeaderFooter: false,
336
+ scale: opts.scale && opts.scale !== 1 ? opts.scale : undefined,
337
+ };
338
+ if (opts.margin) {
339
+ const m = opts.margin;
340
+ pdfOpts.margin = { top: m, bottom: m, left: m, right: m };
341
+ pdfOpts.preferCSSPageSize = false;
342
+ } else if (!htmlSource.startsWith('http')) {
343
+ const text = readFileSync(htmlSource, 'utf8');
344
+ if (!/@page\b/.test(text)) {
345
+ pdfOpts.margin = { top: '0.6in', bottom: '0.6in', left: '0.7in', right: '0.7in' };
346
+ pdfOpts.preferCSSPageSize = false;
347
+ }
348
+ }
349
+
350
+ await page.pdf(pdfOpts);
351
+ return outPath;
352
+ } finally {
353
+ await browser.close();
354
+ }
355
+ }
356
+
357
+ function defaultOutPath() {
358
+ if (isUrl) return resolve('brochure.pdf');
359
+ const abs = resolve(input);
360
+ const base = basename(abs, extname(abs));
361
+ return resolve(dirname(abs), `${base}.pdf`);
362
+ }
363
+
364
+ // --- main ------------------------------------------------------------------
365
+ (async () => {
366
+ const staged = stageInput();
367
+ let htmlSource;
368
+
369
+ if (staged.kind === 'url') {
370
+ htmlSource = staged.url;
371
+ } else if (staged.kind === 'html') {
372
+ htmlSource = staged.file;
373
+ } else if (staged.kind === 'md') {
374
+ htmlSource = await composeFromFolder(null, staged.file);
375
+ } else { // folder
376
+ const picked = pickHtml(staged.stageDir);
377
+ if (picked) {
378
+ log('picked html:', relative(staged.stageDir, picked));
379
+ htmlSource = picked;
380
+ } else {
381
+ log('no html found — composing from markdown');
382
+ htmlSource = await composeFromFolder(staged.stageDir);
383
+ }
384
+ }
385
+
386
+ const outPath = await render(htmlSource);
387
+ const size = statSync(outPath).size;
388
+ let pages = '?';
389
+ try {
390
+ const buf = readFileSync(outPath);
391
+ const m = buf.toString('latin1').match(/\/Type\s*\/Page[^s]/g);
392
+ if (m) pages = String(m.length);
393
+ } catch {}
394
+
395
+ console.log('');
396
+ console.log(`PDF: ${outPath}`);
397
+ console.log(`Pages: ${pages}`);
398
+ console.log(`Size: ${human(size)}`);
399
+ console.log(`Source: ${input} → ${htmlSource.startsWith('http') ? htmlSource : relative(process.cwd(), htmlSource)}`);
400
+ })().catch((err) => { console.error('[brochure] error:', err.message); process.exit(1); });
@@ -0,0 +1,107 @@
1
+ ---
2
+ name: rdc:brochure
3
+ description: "Usage `rdc:brochure <input> [--out <path>] [--template <name>] [--format Letter|A4]` — Turn a zip, folder, HTML file, URL, or markdown folder into a print-quality PDF brochure via Puppeteer. Auto-detects print-variant HTML, honors @page CSS, falls back to a Studio-token-aware template when no HTML exists."
4
+ ---
5
+
6
+ > **⚠️ OUTPUT CONTRACT (READ FIRST):** `guides/output-contract.md`
7
+ > Checklist-only output. No tool-call narration. No raw MCP/JSON/log dumps.
8
+ > One checklist upfront, updated in place, shown again at end with a 1-line verdict.
9
+
10
+ > **Sandbox contract:** Honors `RDC_TEST=1`. Under the flag the skill renders to a fixture path and skips any post-deploy or upload steps.
11
+
12
+ # rdc:brochure — Zip / Folder / HTML → PDF Brochure
13
+
14
+ A focused render pipeline. Two modes:
15
+
16
+ 1. **Render mode** — input already contains print-ready HTML. Skill picks the best HTML file and renders it.
17
+ 2. **Compose mode** — input is a folder of assets + markdown/text with no HTML. Skill composes a Studio-token-aware brochure layout, then renders it.
18
+
19
+ ## When to Use
20
+ - A client zip of deliverables that includes a print-first HTML doc (FuturVille ASP, ranch reports, project plans).
21
+ - A `places/<slug>/` or `apps/<app>/` markdown package that needs a PDF artifact.
22
+ - A single URL or HTML file you want as a clean PDF.
23
+
24
+ ## When NOT to Use
25
+ - Production marketing collateral that lives in `apps/*` and ships via Coolify — that goes through `rdc:design` + `rdc:deploy`.
26
+ - Multi-document publication systems — use `rdc:plan` to scaffold first.
27
+
28
+ ## Arguments
29
+ - `rdc:brochure <input>` — path to `.zip`, folder, `.html`, `.md`, or `http(s)://...` URL.
30
+ - `--out <path>` — output PDF path. Default: `<input-basename>.pdf` next to the input (or `./brochure.pdf` for URLs).
31
+ - `--template <name>` — compose-mode template. Default `studio-default`. Templates live in `scaffold/templates/brochure-*.html`. An unknown name errors out and lists the available template(s) — it does not silently fall back.
32
+ - `--format Letter|A4` — page size. Default `Letter`.
33
+ - `--margin <css>` — override margin. Default honors `@page` from source CSS, else `0.6in 0.7in`.
34
+ - `--no-print-emulate` — render with screen media instead of print.
35
+ - `--keep-workdir` — keep the staged working directory for inspection.
36
+ - `--auto-fit` — inject corrective print-fit CSS (oversized images, wide tables, long code, heading orphans, figure splits) and log overflow diagnostics. Use when source HTML overflows page boundaries.
37
+ - `--scale <n>` — PDF scale factor (e.g. `0.92` to tighten). Default `1`.
38
+
39
+ ## Procedure
40
+
41
+ 1. **Resolve input.**
42
+ - Zip → extract to `tmp/rdc-brochure/<hash>/src`.
43
+ - Folder → stage in place (read-only).
44
+ - URL → fetch into a sandbox dir as `index.html` + linked assets via Puppeteer.
45
+ - `.html` → stage as-is.
46
+ - `.md` or folder-without-html → compose mode.
47
+
48
+ 2. **Pick HTML in render mode.**
49
+ - Prefer the largest standalone HTML containing `@page` or `@media print` rules.
50
+ - Else prefer files matching `*-print.html`, `*-brochure.html`, `print.html`.
51
+ - Else the largest HTML at root.
52
+
53
+ 3. **Compose mode.**
54
+ - Read the chosen template (`scaffold/templates/brochure-studio-default.html`).
55
+ - Inventory the input dir: `*.md`, `*.txt`, images grouped by directory, `cover.*`, `logo.*`.
56
+ - Render markdown to HTML, inject into template slots: cover, foreword, sections, figures, back-matter.
57
+ - Use Studio token CSS (Source Serif 4 + Hanken Grotesk, loam/moss/ochre palette) as the default. If a sibling `tokens.css` is present, prefer that.
58
+
59
+ 4. **Render with Puppeteer.**
60
+ - `headless: 'new'`, `--font-render-hinting=none`.
61
+ - `waitUntil: 'networkidle0'`, await `document.fonts.ready`, then 1500ms settle.
62
+ - `emulateMediaType('print')` unless `--no-print-emulate`.
63
+ - `printBackground: true`, `preferCSSPageSize: true`.
64
+ - Letter @ `0.6in 0.7in` default margins.
65
+
66
+ 5. **Verify.**
67
+ - Output exists and `> 50KB`.
68
+ - PDF metadata: page count > 0.
69
+ - Log: input, picked HTML or template, page count, file size, output path.
70
+
71
+ ## Output
72
+
73
+ ```
74
+ PDF: <absolute path>
75
+ Pages: <n>
76
+ Size: <human bytes>
77
+ Source: <input> → <chosen html or template>
78
+ ```
79
+
80
+ ## Boundaries
81
+ - Does not commit, publish, or upload the resulting PDF. The user moves it.
82
+ - Does not modify the source input.
83
+ - Does not auto-install global dependencies — uses `npx puppeteer` via the skill's own `node_modules` if present, otherwise an on-demand local install under `~/.cache/rdc-brochure/`.
84
+ - Compose-mode templates live in `scaffold/templates/brochure-*.html`. New templates need `rdc:plan` if they cross the architectural-change-approval triggers.
85
+
86
+ ## Implementation
87
+ The executable is `scripts/rdc-brochure.mjs` (in the rdc-skills repo). Invoke directly:
88
+
89
+ ```powershell
90
+ node {RDC_SKILLS_ROOT}/scripts/rdc-brochure.mjs <input> [--out path] [--template name] [--format Letter|A4]
91
+ ```
92
+
93
+ ## Examples
94
+
95
+ ```powershell
96
+ # Zip of deliverables with print HTML inside
97
+ rdc:brochure "C:/Users/me/Downloads/FuturVille Deliverables.zip"
98
+
99
+ # Folder of markdown + images, compose a brochure
100
+ rdc:brochure "places/futurville-vulcan" --template studio-default --out reports/futurville.pdf
101
+
102
+ # Single HTML to PDF, A4
103
+ rdc:brochure docs/source/some-prototype.html --format A4
104
+
105
+ # URL
106
+ rdc:brochure https://example.com/spec.html --out spec.pdf
107
+ ```
@@ -31,17 +31,25 @@ fetch and run the tool in its own session (this is how claude.ai uses it).
31
31
  The command is always `build-corpus <input> [flags]`. Resolve the binary like this:
32
32
 
33
33
  1. **Already on PATH?** Use it directly: `build-corpus --help`.
34
- 2. **Python runtime (recommended on Linux/macOS/claude.ai):**
35
- - one-off, no install: `pipx run build-corpus <input> [flags]`
36
- - or install: `pipx install build-corpus` (PEP 668-safe)
37
- - in a disposable sandbox: `python3 -m pip install build-corpus && build-corpus <input> [flags]`
38
- - S3/R2 image upload needs the extra: `pip install "build-corpus[s3]"`
39
- 3. **Node runtime:** `npx -y -p regen-mde build-corpus <input> [flags]`
34
+ 2. **Install straight from GitHub — REQUIRED for current behavior** (native LaTeX→OMML
35
+ equations, the fidelity report, and the escaped-currency fix; the PyPI/npm packages
36
+ below currently LAG GitHub):
37
+ ```bash
38
+ pip install "git+https://github.com/LIFEAI/build-corpus.git@feat/dual-package-ubuntu"
39
+ # once merged to main, drop the @branch:
40
+ # pip install "git+https://github.com/LIFEAI/build-corpus.git"
41
+ ```
42
+ This installs the `build-corpus` CLI and its deps (latex2mathml, mathml2omml,
43
+ python-docx, Pillow, omml2latex). On Debian/Ubuntu externally-managed Python, add
44
+ `--break-system-packages`, use a venv, or `pipx install "git+https://github.com/LIFEAI/build-corpus.git@feat/dual-package-ubuntu"`.
45
+ 3. **PyPI / npm (only if you do NOT need the latest fixes — these lag GitHub):**
46
+ `pipx install build-corpus` · `npx -y -p regen-mde build-corpus <input> [flags]`
40
47
  4. **Legacy `.ppt` input** additionally needs LibreOffice (`soffice`) on PATH
41
48
  (`sudo apt install libreoffice`). `.docx`/`.pptx` need nothing extra.
49
+ 5. **S3/R2 image upload** needs the extra: append `[s3]` to the package spec.
42
50
 
43
- claude.ai note: pull from PyPI (`build-corpus`) or npm (`regen-mde`) and run in the
44
- analysis/session sandbox. No local repo checkout is required.
51
+ claude.ai note: install from GitHub (step 2) into the analysis/session sandbox and run
52
+ `build-corpus` there. GitHub is the source of truth until PyPI/npm are republished.
45
53
 
46
54
  ## Command Reference
47
55
 
@@ -0,0 +1,127 @@
1
+ ---
2
+ name: rdc-convert
3
+ version: 0.1.0
4
+ description: |
5
+ Convert Office documents to/from Markdown with the build-corpus CLI: .docx/.pptx/.ppt → Markdown (Word OMML equations become KaTeX-readable TeX; tables, images, headings preserved), and Markdown → Word (.docx) where inline $...$ and display $$...$$ LaTeX become NATIVE Office Math (OMML) that Word renders as real equations. Use this skill whenever the user asks to convert a Word/PowerPoint document to Markdown, build a Markdown corpus from Office files, turn Markdown into a .docx (optionally with a .dotx template), or "open the report" to edit. Install build-corpus straight from GitHub and run it in the session.
6
+ triggers:
7
+ - "convert this docx to markdown"
8
+ - "convert to word"
9
+ - "docx to markdown"
10
+ - "pptx to markdown"
11
+ - "markdown to docx"
12
+ - "build a markdown corpus"
13
+ - "render the equations to word"
14
+ - "build-corpus"
15
+ ---
16
+
17
+ # rdc-convert — Office ↔ Markdown conversion (build-corpus)
18
+
19
+ `build-corpus` is a Python CLI that converts between Office documents and Markdown.
20
+ This is a self-contained skill: install the tool from GitHub into the current
21
+ session and run `build-corpus`. No local checkout or other rdc skill is required.
22
+
23
+ ## When to Use
24
+ - `.docx` / `.pptx` / `.ppt` → Markdown — preserves Word OMML equations (as
25
+ KaTeX-readable TeX), tables, images, headings, and lists.
26
+ - Markdown → Word (`.docx`) — inline `$...$` and display `$$...$$` LaTeX are
27
+ converted to **native OMML** Word renders as real equations; optional `.dotx`
28
+ template via `--word-template`.
29
+ - Build a Markdown corpus from a folder of Office files (recursive, one pass).
30
+ - Inline a Markdown file's images as data URIs, or rehost them to R2/S3.
31
+
32
+ ## When NOT to Use
33
+ - Rendering a folder/HTML/zip into a print-ready **PDF** brochure (that is a
34
+ separate brochure pipeline).
35
+ - Rasterizing HTML/JSX/SVG to images — build-corpus is a format converter, not a
36
+ render engine; it flags those and a separate render step handles them.
37
+
38
+ ## Install & Run (install from GitHub — it is the source of truth)
39
+
40
+ The published PyPI/npm packages lag GitHub. Install from the repository to get the
41
+ current behavior (native LaTeX→OMML, the fidelity report, the escaped-currency fix):
42
+
43
+ ```bash
44
+ pip install "git+https://github.com/LIFEAI/build-corpus.git@feat/dual-package-ubuntu"
45
+ # once merged to main, drop the @branch:
46
+ # pip install "git+https://github.com/LIFEAI/build-corpus.git"
47
+ build-corpus --help
48
+ ```
49
+
50
+ This installs the `build-corpus` command and its dependencies (latex2mathml,
51
+ mathml2omml, python-docx, Pillow, omml2latex). Notes:
52
+ - Debian/Ubuntu externally-managed Python (PEP 668): add `--break-system-packages`,
53
+ use a venv, or `pipx install "git+https://github.com/LIFEAI/build-corpus.git@feat/dual-package-ubuntu"`.
54
+ - S3/R2 image upload: append `[s3]` to the package spec.
55
+ - Legacy `.ppt` input also needs LibreOffice (`soffice`) on PATH (`apt install libreoffice`).
56
+ `.docx`/`.pptx` need nothing extra.
57
+
58
+ ## Command Reference
59
+
60
+ ```
61
+ build-corpus <input> [input ...] [options]
62
+ ```
63
+
64
+ `<input>` — one or more `.md`, `.docx`, `.pptx`, or `.ppt` files or directories.
65
+
66
+ | Flag | Values / default | Effect |
67
+ |------|------------------|--------|
68
+ | `--out <dir>` | path | Output directory for the converted tree. |
69
+ | `--out-same-dir` | — | Write `.md`, `.assets`, and reports beside each source file. |
70
+ | `--to` | `auto` \| `markdown` \| `word` (default `auto`) | Output target. `auto` infers from a single-file input. |
71
+ | `--images` | `assets` \| `base64` \| `s3` (default `assets`) | Image handling. |
72
+ | `--equations` | `tex` \| `image` (default `tex`) | docx→md: OMML → KaTeX TeX, or rendered images (debug). |
73
+ | `--inline-images` | — | Emit `<name>.inline.md` with images embedded as data URIs. |
74
+ | `--word-template <file>` | `.docx`/`.dotx` | Template for Markdown → Word exports. |
75
+ | `--move-sources` | — | After a successful convert, move sources into a `sources/` folder. |
76
+ | `--config <file>` | JSON | Conversion/output/S3 defaults (CLI flags override). |
77
+
78
+ S3/R2 (only with `--images s3`): `--s3-bucket`, `--s3-public-base-url`,
79
+ `--s3-prefix`, `--s3-endpoint-url` (required for R2), `--s3-region` (`auto` for R2),
80
+ `--s3-access-key-id`, `--s3-secret-access-key`, `--s3-cache-control`, `--s3-acl`.
81
+
82
+ ## Equations (real in both directions)
83
+ - **docx → markdown** (`--equations`): `tex` converts Word OMML equations to
84
+ KaTeX-readable TeX (default); `image` renders them as images (debug only).
85
+ - **markdown → word** (`--to word`): inline `$...$` and display `$$...$$` LaTeX are
86
+ converted to **native OMML** (`\sum`, `\int`, `\frac`, `\Delta`, `\rightarrow`,
87
+ `\leq`, …). Escaped currency like `\$252.3B` is kept as literal text, never mistaken
88
+ for math. Unparseable fragments fall back to Cambria-Math text and are flagged in the
89
+ report. Fence display math with `$$` on their own lines, no blank lines inside.
90
+
91
+ ## Fidelity report (md → word)
92
+ Each md→word export writes `export-report.json` (and a batch report) so you can
93
+ confirm nothing was silently dropped or changed:
94
+ - **`fidelity_ok`** — top-level ship gate (`true` only when every row matches and no
95
+ equation fell back).
96
+ - **`reconciliation`** — input vs output per type (`tables`, `equations`
97
+ {in/out_omml/fell_back}, `images` {in/out/failed}, `code_blocks`, `headings`, `links`).
98
+ - **`issues`** — `{ type, line, source|target, reason }` per problem.
99
+ - **`text_fixups`** — markdown escapes the engine resolved (e.g. `currency_unescaped`).
100
+ - A one-line **stdout digest** for a quick glance.
101
+
102
+ Image-failure `reason` values: `missing-file`, `unsupported-on-platform` (EMF/WMF —
103
+ install LibreOffice), `unsupported-format` (.html/.jsx — route to a render pipeline),
104
+ `svg-needs-rasterization` / `mislabeled-svg` (rasterize the SVG to PNG and repoint),
105
+ `skipped-remote`.
106
+
107
+ ## Examples
108
+
109
+ ```bash
110
+ build-corpus input.docx --out out # docx → markdown
111
+ build-corpus deck.pptx --out out # pptx → markdown
112
+ build-corpus ./word-files --out ./markdown # whole folder, recursive
113
+ build-corpus ./word-files --out-same-dir # write beside each source
114
+ build-corpus input.md --to word --out out # markdown → Word (LaTeX → OMML)
115
+ build-corpus input.md --to word --word-template custom.dotx --out out
116
+ build-corpus report.md --inline-images # → report.inline.md
117
+ build-corpus input.docx --images s3 --config build-corpus.config.json
118
+ ```
119
+
120
+ ## Boundaries
121
+ - Does not commit, deploy, or upload outputs (except images when `--images s3`).
122
+ - Does not modify source documents unless `--move-sources` is passed.
123
+ - Does not rasterize HTML/JSX/SVG — flags them for an external render step.
124
+
125
+ ## Reference
126
+ - Source (install from here): `github.com/LIFEAI/build-corpus`
127
+ - Packages (currently lag GitHub): PyPI `build-corpus`, npm `regen-mde`.