|
| 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 | +} |
0 commit comments