Skip to content

Commit e3d6cfc

Browse files
MrPickeringclaude
andcommitted
Walkthrough generator: inventory, explain, slides, audio and render
Builds an author-facing walkthrough of a Weaver book (install, run, edit manuscripts, what every file does and how to maintain it) as slides, a pptx and an mp4. Written 2026-09-28 and left uncommitted in this worktree; committed now so it is not lost. 10/10 tests pass. Fixtures are synthetic. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Session-Id: 61e7c924-7a69-4dda-83e6-6e95ffcb326b Agent: claude-code
1 parent 81ee875 commit e3d6cfc

25 files changed

Lines changed: 880 additions & 0 deletions

File tree

‎walkthrough/.gitignore‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
node_modules/
2+
out/
3+
.env

‎walkthrough/README.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Weaver author walkthrough generator
2+
3+
Generate a PowerPoint deck, slide PNGs, and a silent video from an installed Weaver book project. The book is read only; all generated files go to `--out`.
4+
5+
## Setup
6+
7+
Requires Node.js 22, the Claude Code CLI signed in to a subscription, headless Microsoft Edge at the standard Windows path, and `ffmpeg` plus `ffprobe` on `PATH`.
8+
9+
```powershell
10+
cd walkthrough
11+
npm install
12+
cd ..
13+
node walkthrough/bin/walkthrough.mjs --book C:\path\to\book --out C:\path\to\walkthrough-output --title "Book title" --author "Author name"
14+
```
15+
16+
Audio uses the `none` provider by default; `--no-audio` selects the same provider explicitly. It makes no TTS request and reads no API key. A local TTS provider can be added to `lib/audio.mjs`. Silent slides stay on screen for at least six seconds and longer when needed to read the narration at about 150 words per minute. Add `--no-video` to omit MP4 creation or `--refresh` to regenerate cached explanations.
17+
18+
`inventory.json` records grouped files and hashes. `explanations.json` contains the five plain English descriptions for each entry. `slides.json` is the content source for the PowerPoint, HTML, frames, audio, and video. Failed Claude responses are marked `[needs review]` in the output README and slides.
19+
20+
Run `npm test` inside `walkthrough/` for its unit tests.
21+
22+
The package uses `pptxgenjs` as its only direct dependency. Its transitive `image-size` dependency is overridden to 2.0.4 because the version allowed by `pptxgenjs` has published denial-of-service advisories; the deck writer does not use its image parsing API.

‎walkthrough/bin/walkthrough.mjs‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
#!/usr/bin/env node
2+
import path from 'node:path';
3+
import { mkdir, readFile, writeFile } from 'node:fs/promises';
4+
import { fileURLToPath } from 'node:url';
5+
import { inventory } from '../lib/inventory.mjs';
6+
import { getDocs, explainAll } from '../lib/explain.mjs';
7+
import { makeSlides, validateSlides } from '../lib/slides.mjs';
8+
import { renderDeck, renderFrames, renderVideo } from '../lib/render.mjs';
9+
import { renderAudio } from '../lib/audio.mjs';
10+
11+
const here = path.dirname(fileURLToPath(import.meta.url));
12+
const walkRoot = path.dirname(here);
13+
const repo = path.dirname(walkRoot);
14+
function argsOf(argv) {
15+
const options = { audioProvider: 'none', video: true, refresh: false };
16+
for (let i = 0; i < argv.length; i++) {
17+
const a = argv[i];
18+
if (['--book', '--out', '--title', '--author'].includes(a)) options[a.slice(2)] = argv[++i];
19+
else if (a === '--no-audio') options.audioProvider = 'none';
20+
else if (a === '--no-video') options.video = false;
21+
else if (a === '--refresh') options.refresh = true;
22+
else throw Error(`Unknown argument: ${a}`);
23+
}
24+
if (!options.book || !options.out) throw Error('Usage: node walkthrough/bin/walkthrough.mjs --book <book-dir> --out <out-dir> [--title "..."] [--author "..."] [--no-audio] [--no-video] [--refresh]');
25+
options.book = path.resolve(options.book); options.out = path.resolve(options.out);
26+
if (options.out === options.book || options.out.startsWith(options.book + path.sep)) throw Error('--out must be outside the read-only book folder');
27+
return options;
28+
}
29+
async function main() {
30+
const opt = argsOf(process.argv.slice(2));
31+
await mkdir(opt.out, { recursive: true });
32+
const entries = await inventory(opt.book);
33+
await writeFile(path.join(opt.out, 'inventory.json'), JSON.stringify(entries, null, 2) + '\n');
34+
process.stdout.write(`Inventory: ${entries.length} entries\n`);
35+
const docs = await getDocs(opt.book, repo);
36+
const explanations = await explainAll(entries, docs, opt.out, { refresh: opt.refresh });
37+
await writeFile(path.join(opt.out, 'explanations.json'), JSON.stringify(explanations, null, 2) + '\n');
38+
let title = opt.title;
39+
if (!title) { try { title = JSON.parse(await readFile(path.join(opt.book, 'project.json'), 'utf8')).title; } catch { /* fallback */ } }
40+
title ||= path.basename(opt.book);
41+
const slides = await makeSlides({ book: opt.book, repo, entries, explanations, docs, title, author: opt.author || 'the author', out: opt.out, refresh: opt.refresh });
42+
validateSlides(slides);
43+
await writeFile(path.join(opt.out, 'slides.json'), JSON.stringify(slides, null, 2) + '\n');
44+
await renderDeck(slides, opt.out);
45+
await renderFrames(slides, opt.out);
46+
const audio = await renderAudio(slides, opt.out, opt.audioProvider);
47+
const duration = opt.video ? await renderVideo(slides, opt.out, audio) : null;
48+
const sections = Object.groupBy(slides, x => x.section);
49+
const needsReview = explanations.filter(x => x.needsReview).length + slides.filter(x => x.section === 'Code review' && x.bullets.some(b => b.includes('[needs review]'))).length;
50+
const lines = [
51+
`# ${title}: Weaver walkthrough`, '',
52+
`Generated ${new Date().toISOString()}.`, '',
53+
`- Inventory: ${entries.length} entries in \`inventory.json\`.`,
54+
`- Explanations: \`explanations.json\`; ${needsReview} [needs review] placeholders.`,
55+
`- Slides: ${slides.length} in \`slides.json\` and \`walkthrough.pptx\`.`,
56+
`- Frames: ${slides.length} PNG files in \`frames/\`, with matching HTML in \`html/\`.`,
57+
`- Audio: ${audio.length ? `${audio.length} audio files in \`audio/\`.` : 'skipped (provider none).'}`,
58+
`- Video: ${duration == null ? 'skipped.' : `\`walkthrough.mp4\`, expected duration ${duration.toFixed(1)} seconds.`}`,
59+
'', '## Slides by section', '',
60+
...Object.entries(sections).map(([name, list]) => `- ${name}: ${list.length}`),
61+
'', '## Review', '',
62+
...entries.filter((_, i) => explanations[i].needsReview).map(x => `- [needs review] ${x.path}`),
63+
...slides.filter(x => x.section === 'Code review' && x.bullets.some(b => b.includes('[needs review]'))).map(x => `- [needs review] ${x.title}`)
64+
];
65+
await writeFile(path.join(opt.out, 'README.md'), lines.join('\n') + '\n');
66+
process.stdout.write(`Done: ${slides.length} slides, ${needsReview} [needs review] placeholders${duration == null ? '' : `, ${duration.toFixed(1)}s video`}\n`);
67+
}
68+
main().catch(e => { process.stderr.write(`${e.stack || e.message}\n`); process.exitCode = 1; });

‎walkthrough/lib/audio.mjs‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// Add a local TTS provider here when one is available. Providers implement
2+
// render(slides, out) and return one audio path per slide, or an empty array.
3+
const providers = {
4+
none: {
5+
async render() {
6+
process.stdout.write('Audio skipped: provider none.\n');
7+
return [];
8+
}
9+
}
10+
};
11+
12+
export async function renderAudio(slides, out, provider = 'none') {
13+
const implementation = providers[provider];
14+
if (!implementation) throw Error(`Unknown audio provider: ${provider}`);
15+
return implementation.render(slides, out);
16+
}

‎walkthrough/lib/common.mjs‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import { createHash } from 'node:crypto';
2+
import { readFile, mkdir, writeFile } from 'node:fs/promises';
3+
import path from 'node:path';
4+
5+
export const sha = value => createHash('sha256').update(value).digest('hex');
6+
export const words = value => String(value).trim().split(/\s+/).filter(Boolean).length;
7+
export async function json(path, value) {
8+
await mkdir((await import('node:path')).default.dirname(path), { recursive: true });
9+
await writeFile(path, JSON.stringify(value, null, 2) + '\n');
10+
}
11+
export async function readJson(path, fallback = null) {
12+
try { return JSON.parse(await readFile(path, 'utf8')); } catch { return fallback; }
13+
}
14+
export function short(value, max) {
15+
const s = String(value).replace(/\s+/g, ' ').trim();
16+
const a = s.split(' ');
17+
return a.length <= max ? s : a.slice(0, max).join(' ').replace(/[,:;.]?$/, '…');
18+
}

‎walkthrough/lib/explain.mjs‎

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
import { spawn } from 'node:child_process';
2+
import { mkdir, readFile, writeFile } from 'node:fs/promises';
3+
import path from 'node:path';
4+
import { readJson, sha, words } from './common.mjs';
5+
6+
export const FIELDS = ['what_it_is', 'what_it_does', 'how_the_pipeline_uses_it', 'when_you_touch_it', 'how_to_maintain'];
7+
export const EXPLAIN_PROMPT_VERSION = 'complete-short-v2';
8+
export function completePhrase(value) {
9+
const s = String(value).trim();
10+
return !!s && !/(?:\.{3,}|…|[,;:\-–—])\s*$/.test(s) &&
11+
!/\b(?:a|an|the|and|or|but|for|from|into|of|to|with|your|its)\s*[.!?]?$/i.test(s);
12+
}
13+
export function validateExplanation(value) {
14+
if (!value || typeof value !== 'object' || Array.isArray(value)) throw Error('Response must be an object');
15+
for (const key of FIELDS) {
16+
if (typeof value[key] !== 'string' || !value[key].trim()) throw Error(`${key} must be a nonempty string`);
17+
if (words(value[key]) > 12) throw Error(`${key} exceeds 12 words`);
18+
if (!completePhrase(value[key])) throw Error(`${key} is incomplete`);
19+
}
20+
if (!FIELDS.some(key => /\b(you|your)\b/i.test(value[key]))) throw Error('Response must address the author as you');
21+
return Object.fromEntries(FIELDS.map(key => [key, value[key].trim()]));
22+
}
23+
export function validateCommit(value) {
24+
if (!value || typeof value !== 'object') throw Error('Response must be an object');
25+
for (const key of ['what_changed', 'why']) {
26+
if (typeof value[key] !== 'string' || !value[key].trim() || words(value[key]) > 25) throw Error(`${key} needs 1 to 25 words`);
27+
if (!/\b(you|your)\b/i.test(value[key])) throw Error(`${key} must address the author as you`);
28+
}
29+
return { what_changed: value.what_changed.trim(), why: value.why.trim() };
30+
}
31+
export function parseResponse(raw) {
32+
const clean = String(raw).trim().replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/, '');
33+
return JSON.parse(clean);
34+
}
35+
export async function withRepair(prompt, validator, call) {
36+
let error;
37+
for (let attempt = 0; attempt < 2; attempt++) {
38+
try {
39+
const raw = await call(attempt ? `${prompt}\n\nYour previous response failed validation: ${error.message}. Repair it. Return only valid JSON.` : prompt);
40+
return { value: validator(parseResponse(raw)), needsReview: false };
41+
} catch (e) { error = e; }
42+
}
43+
return { value: null, needsReview: true, error: error?.message || 'Unknown error' };
44+
}
45+
export async function claude(prompt) {
46+
const env = { ...process.env };
47+
delete env.ANTHROPIC_API_KEY;
48+
delete env.OPENAI_API_KEY;
49+
return await new Promise((resolve, reject) => {
50+
const child = spawn('cmd.exe', ['/d', '/s', '/c', 'claude.cmd -p --output-format text'], { env, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
51+
let stdout = '', stderr = '';
52+
const timer = setTimeout(() => child.kill(), 180000);
53+
child.stdout.on('data', d => stdout += d);
54+
child.stderr.on('data', d => stderr += d);
55+
child.on('error', reject);
56+
child.on('close', code => { clearTimeout(timer); code === 0 ? resolve(stdout) : reject(Error(`claude exit ${code}: ${stderr.slice(0, 300)}`)); });
57+
child.stdin.end(prompt);
58+
});
59+
}
60+
export async function getDocs(book, repo) {
61+
const roots = [path.join(book, 'node_modules', '@pickbitsai', 'weaver'), repo];
62+
for (const root of roots) {
63+
try {
64+
const { readdir } = await import('node:fs/promises');
65+
const docs = [path.join(root, 'README.md'), ...(await readdir(path.join(root, 'docs'))).filter(x => x.endsWith('.md')).map(x => path.join(root, 'docs', x))];
66+
return (await Promise.all(docs.map(p => readFile(p, 'utf8')))).join('\n').slice(0, 70000);
67+
} catch { /* try repository */ }
68+
}
69+
return '';
70+
}
71+
function docContext(entry, docs) {
72+
const pathParts = entry.path.toLowerCase().replace(/\.[a-z0-9]+$/i, '').split(/[\/._ -]+/).filter(x => x.length >= 4 && !['weaver', 'chapter', 'scene', 'file'].includes(x));
73+
const terms = [...new Set(pathParts)].slice(-4);
74+
const pieces = [docs.slice(0, 3500)];
75+
const lower = docs.toLowerCase();
76+
for (const term of terms) {
77+
let at = 0, hits = 0;
78+
while ((at = lower.indexOf(term, at)) >= 0 && hits++ < 3) {
79+
pieces.push(docs.slice(Math.max(0, at - 260), Math.min(docs.length, at + 750)));
80+
at += term.length;
81+
}
82+
}
83+
return pieces.join('\n...\n').slice(0, 8500);
84+
}
85+
export async function explainAll(entries, docs, out, { refresh = false, call = claude } = {}) {
86+
const cache = path.join(out, 'cache');
87+
await mkdir(cache, { recursive: true });
88+
const results = new Array(entries.length);
89+
let next = 0;
90+
async function worker() {
91+
while (next < entries.length) {
92+
const i = next++;
93+
const entry = entries[i];
94+
const file = path.join(cache, `explain-${EXPLAIN_PROMPT_VERSION}-${entry.sha256}-${sha(entry.path).slice(0, 12)}.json`);
95+
const cached = refresh ? null : await readJson(file);
96+
if (cached && !cached.needsReview) {
97+
try { results[i] = { ...validateExplanation(cached), needsReview: false }; continue; } catch { /* regenerate invalid cache */ }
98+
}
99+
const prompt = `Explain this Weaver book item to a nontechnical author. Use only the file excerpt and documentation below. Return ONLY JSON with keys ${FIELDS.join(', ')}. Each value must be a complete, natural, short sentence or phrase of 1 to 12 words. Never truncate or end with ellipses. Use plain English and address the author as "you" or "your" in at least one value. For installed tool files, say "You do not edit this; Weaver updates it" in how_to_maintain.\nPath: ${entry.path}\nGroup: ${entry.group}\nFiles: ${entry.files.length}\nExcerpt:\n${entry.excerpt}\nDocumentation:\n${docContext(entry, docs)}`;
100+
const answer = await withRepair(prompt, validateExplanation, call);
101+
const value = answer.value || {
102+
what_it_is: '[needs review] You need an explanation of this item.',
103+
what_it_does: '[needs review] You need its purpose explained.',
104+
how_the_pipeline_uses_it: '[needs review] You need its place in the workflow explained.',
105+
when_you_touch_it: '[needs review] You need guidance on when to open it.',
106+
how_to_maintain: entry.group === 'The tool' ? '[needs review] You should not edit this installed Weaver file.' : '[needs review] You need guidance on keeping this file current.'
107+
};
108+
results[i] = { ...value, needsReview: answer.needsReview };
109+
await writeFile(file, JSON.stringify(results[i], null, 2));
110+
process.stdout.write(`Explained ${i + 1}/${entries.length}: ${entry.path}${answer.needsReview ? ` [needs review: ${answer.error}]` : ''}\n`);
111+
}
112+
}
113+
await worker();
114+
return results;
115+
}
116+
export async function explainCommit(commit, out, { refresh = false, call = claude } = {}) {
117+
const key = sha(JSON.stringify(commit));
118+
const file = path.join(out, 'cache', `commit-${key}.json`);
119+
const cached = refresh ? null : await readJson(file);
120+
if (cached && !cached.needsReview) return cached;
121+
const prompt = `Explain this Git commit to a nontechnical book author. Return ONLY JSON with what_changed and why, each 1 to 25 plain-English words that address the author as "you" or "your". Base why only on the commit message; if it gives no reason say so.\n${JSON.stringify(commit)}`;
122+
const answer = await withRepair(prompt, validateCommit, call);
123+
const value = answer.value || { what_changed: '[needs review] You need a summary of this change.', why: '[needs review] You need the reason checked against the commit.' };
124+
const result = { ...value, needsReview: answer.needsReview };
125+
await mkdir(path.dirname(file), { recursive: true });
126+
await writeFile(file, JSON.stringify(result, null, 2));
127+
return result;
128+
}

‎walkthrough/lib/inventory.mjs‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import { readdir, readFile } from 'node:fs/promises';
2+
import path from 'node:path';
3+
import { sha } from './common.mjs';
4+
5+
const slash = s => s.replaceAll('\\', '/');
6+
async function walk(root, sub = '') {
7+
let names;
8+
try { names = await readdir(path.join(root, sub), { withFileTypes: true }); } catch { return []; }
9+
const found = [];
10+
for (const d of names) {
11+
if (['.git', 'node_modules', 'out'].includes(d.name)) continue;
12+
const rel = slash(path.join(sub, d.name));
13+
if (d.isDirectory()) found.push(...await walk(root, rel));
14+
else if (d.isFile()) found.push(rel);
15+
}
16+
return found.sort();
17+
}
18+
function sceneFamily(rel) {
19+
// These are generated work packets. Explain the folder once, while retaining
20+
// every member in `files` so its size and hash still cover the whole set.
21+
if (rel.startsWith('.weaver/packets/')) return '.weaver/packets/';
22+
if (/chapter[-_]\d+\/scene[-_]\d+/i.test(rel)) return rel.replace(/chapter[-_]\d+/i, 'chapter-NN').replace(/scene[-_]\d+/i, 'scene-NN');
23+
if (/(^|\/)\d+[-_]\d+\.[^/]+$/.test(rel)) return rel.replace(/\d+[-_]\d+(?=\.[^/]+$)/, 'NN-NN');
24+
return null;
25+
}
26+
async function makeEntry(root, files, display, group) {
27+
const chunks = [];
28+
let single;
29+
let size = 0;
30+
let excerpt = '';
31+
for (const rel of files) {
32+
const buffer = await readFile(path.join(root, rel));
33+
single = buffer;
34+
size += buffer.length;
35+
chunks.push(rel, '\0', buffer, '\0');
36+
if (!excerpt) {
37+
excerpt = /(^|\/)\.env(?:\.|$)/.test(rel) ? '[redacted configuration]' : buffer.includes(0) ? '[binary file; no text excerpt]' : buffer.toString('utf8').split(/\r?\n/).slice(0, 8).map(line => /(api[_-]?key|secret|token|password)\s*[:=]/i.test(line) ? '[redacted sensitive line]' : line).join('\n').slice(0, 900);
38+
}
39+
}
40+
return { path: display, group, size, sha256: files.length === 1 ? sha(single) : sha(Buffer.concat(chunks.map(x => Buffer.isBuffer(x) ? x : Buffer.from(x)))), excerpt, files, update_policy: group === 'The tool' ? 'Do not edit; Weaver updates this.' : 'Your book file.' };
41+
}
42+
export async function inventory(book, toolRoot = path.join(book, 'node_modules', '@pickbitsai', 'weaver')) {
43+
const bookFiles = await walk(book);
44+
const families = new Map();
45+
for (const rel of bookFiles) {
46+
const fam = sceneFamily(rel);
47+
const key = fam || rel;
48+
if (!families.has(key)) families.set(key, []);
49+
families.get(key).push(rel);
50+
}
51+
const entries = [];
52+
for (const [key, files] of families) entries.push(await makeEntry(book, files, key === '.weaver/packets/' ? key : files.length > 1 ? `${key}: one file per scene` : key, 'Your book'));
53+
const toolFiles = await walk(toolRoot);
54+
const toolGroups = new Map();
55+
for (const rel of toolFiles) {
56+
const top = rel.split('/')[0];
57+
if (!['scripts', 'engine', 'studio', 'prompts', 'templates', 'contracts'].includes(top) && rel !== 'integrity.json') continue;
58+
const key = top === 'engine' ? rel : top === 'scripts' && rel === 'scripts/weaver.mjs' ? rel : top === 'scripts' ? 'scripts/' : top === 'integrity.json' ? rel : `${top}/`;
59+
if (!toolGroups.has(key)) toolGroups.set(key, []);
60+
toolGroups.get(key).push(rel);
61+
}
62+
for (const [key, files] of toolGroups) entries.push(await makeEntry(toolRoot, files, `@pickbitsai/weaver/${key}`, 'The tool'));
63+
return entries;
64+
}

0 commit comments

Comments
 (0)