#!/usr/bin/env node // Builds the exact tree that becomes the single initial commit of the public repository, in a // scratch directory OUTSIDE the working tree, and checks it. Re-runnable: it always starts from // the committed HEAD (git archive), never from the working tree. // // node scripts/public-tree.mjs [--out ] [--fw-commit ] [--fw-url ] [--no-history-scan] // // Default --out is %USERPROFILE%/Desktop/twttr/public-dryrun. It writes // /tree/ the file set (no .git) // /repo/ the same set as one commit, authored as CRT (a throwaway repository) // /REPORT.md file count, size, exclusions and why, scan results, the commands to publish // // Nothing is pushed or uploaded. The privacy scan uses the framework's `waybetter privacy-scan` // with the terms file named in waybetter.release.json; no term is ever printed (hits are masked) // and the machine user's name is masked in every path this script prints. import { execFileSync, spawnSync } from 'node:child_process'; import { createHash } from 'node:crypto'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; process.on('uncaughtException', error => { console.error(`public-tree: ${String(error?.message ?? error).replace(process.env.USERNAME || 'no-user', '')}`); process.exit(1); }); const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); const args = process.argv.slice(2); const opt = (name, fallback) => { const at = args.indexOf(`--${name}`); return at >= 0 && args[at + 1] ? args[at + 1] : fallback; }; const out = path.resolve(opt('out', path.join(os.homedir(), 'Desktop', 'twttr', 'public-dryrun'))); const PUBLIC_REPO = 'https://git.crt.fyi/CRT/waybetter-for-x.git'; const FW_URL = opt('fw-url', 'https://git.crt.fyi/CRT/waybetter.git'); const UPDATE = args.includes('--update'); const MESSAGE = opt('message', ''); if (UPDATE && !MESSAGE) throw new Error('--update needs --message ""'); const AUTHOR = { name: 'CRT', email: 'hi@crt.fyi' }; const MAX_FILE = 3_000_000; // bytes; larger files are listed for review // Never print the machine user's name or the home folder. const user = os.userInfo().username; const mask = text => String(text) .split(os.homedir()).join('%USERPROFILE%') .split(os.homedir().replace(/\\/g, '/')).join('%USERPROFILE%') .replace(new RegExp(user.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi'), ''); const show = p => mask(p); const git = (cwd, ...a) => execFileSync('git', a, { cwd, encoding: 'utf8', maxBuffer: 1 << 28 }).trim(); const head = git(root, 'rev-parse', 'HEAD'); // --------------------------------------------------------------------------------------------- // What is left out, and why. First match wins. Keep the reasons honest: they go in the report. const EXCLUDE = [ [/^\.omc\//, 'agent plans, research and notes (local tool state)'], [/^\.claude\//, 'agent worktrees and local settings'], [/^(HANDOFF|CLAUDE)\.md$/, 'private working notes for the maintainer\'s tools'], [/^verification\//, 'screenshots, recordings and QA reports from live sessions on real accounts (about 87 MB); they can show account content and are not part of the product'], [/^releases\//, 'built installers and old private builds'], [/^ecosystem\.config\.cjs$/, 'the maintainer\'s own server process configuration'], [/^docs\/IMPLEMENTATION-CONTRACT\.md$/, 'the first private working contract (says "Private local working repository"); superseded by the code and the other docs'], [/^apps\/desktop\/(tmp|test-results)\//, 'scratch output'], [/^main\.bundle$/, 'a git bundle'], [/\.(log|db|sqlite3?|pem|key|p12|pfx)$/i, 'logs, databases and key material'], // The reviewed allowlist names the context around each hit, and a context can give the private // word away (a well-known header name with the word cut out is the word): never public. [/(^|\/)privacy-allowlist[^/]*\.txt$/, 'the privacy scan\'s reviewed contexts (a context can reveal the private term)'], ]; // Files that must exist in the tree because a public doc links to them (checked below). const files = execFileSync('git', ['ls-tree', '-r', '-z', head], { cwd: root, encoding: 'utf8', maxBuffer: 1 << 28 }) .split('\0').filter(Boolean).map(line => { const tab = line.indexOf('\t'); const [mode, type, sha] = line.slice(0, tab).split(' '); return { mode, type, sha, path: line.slice(tab + 1) }; }); const gitlink = files.find(f => f.mode === '160000' && f.path === 'waybetter'); const fwCommit = opt('fw-commit', gitlink?.sha); if (!fwCommit) throw new Error('no waybetter gitlink at HEAD'); const kept = []; const excluded = new Map(); // reason -> { count, bytes, samples } for (const file of files) { if (file.type === 'commit') continue; // the submodule: re-added below as a gitlink const rule = EXCLUDE.find(([re]) => re.test(file.path)); if (rule) { const entry = excluded.get(rule[1]) ?? { count: 0, bytes: 0, samples: [] }; entry.count++; if (entry.samples.length < 3) entry.samples.push(file.path); excluded.set(rule[1], entry); } else kept.push(file); } // --------------------------------------------------------------------------------------------- // Extract HEAD into /tree, then delete what is excluded. fs.rmSync(out, { recursive: true, force: true }); fs.mkdirSync(path.join(out, 'tree'), { recursive: true }); const tree = path.join(out, 'tree'); { const archive = spawnSync('git', ['archive', '--format=tar', head], { cwd: root, maxBuffer: 1 << 30 }); if (archive.status !== 0) throw new Error('git archive failed'); const untar = spawnSync('tar', ['-x'], { cwd: tree, input: archive.stdout, maxBuffer: 1 << 28 }); if (untar.status !== 0) throw new Error(`tar failed: ${mask(untar.stderr)}`); } const keepSet = new Set(kept.map(f => f.path)); let removed = 0; const walk = dir => { for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { const full = path.join(dir, entry.name); const rel = path.relative(tree, full).split(path.sep).join('/'); if (entry.isDirectory()) walk(full); else if (!keepSet.has(rel)) { fs.rmSync(full); removed++; } } }; walk(tree); // Empty directories left by the exclusions (and the empty submodule folder). const prune = dir => { for (const entry of fs.readdirSync(dir, { withFileTypes: true })) if (entry.isDirectory()) prune(path.join(dir, entry.name)); if (dir !== tree && fs.readdirSync(dir).length === 0) fs.rmdirSync(dir); }; prune(tree); // .gitmodules: the public framework URL, no comments about the maintainer's servers. fs.writeFileSync(path.join(tree, '.gitmodules'), `[submodule "waybetter"]\n\tpath = waybetter\n\turl = ${FW_URL}\n\tbranch = main\n`); // --------------------------------------------------------------------------------------------- // Inventory const all = []; const scanDir = dir => { for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { const full = path.join(dir, entry.name); if (entry.isDirectory()) scanDir(full); else all.push({ rel: path.relative(tree, full).split(path.sep).join('/'), full, size: fs.statSync(full).size }); } }; scanDir(tree); const totalBytes = all.reduce((sum, f) => sum + f.size, 0); for (const [, entry] of excluded) entry.bytes = 0; const big = all.filter(f => f.size > MAX_FILE).sort((a, b) => b.size - a.size); const images = all.filter(f => /\.(png|jpe?g|webp|gif|svg|ico|icns|mp4|webm)$/i.test(f.rel)); const reviewedFile = path.join(root, 'scripts', 'public-tree.reviewed-images.json'); const reviewed = fs.existsSync(reviewedFile) ? JSON.parse(fs.readFileSync(reviewedFile, 'utf8')).reviewed : {}; const unreviewed = images.filter(f => !/^apps\/web\/public\/(og\/items|store\/previews)\//.test(f.rel) && reviewed[f.rel] !== createHash('sha256').update(fs.readFileSync(f.full)).digest('hex')).map(f => f.rel); // --------------------------------------------------------------------------------------------- // Checks on the tree const textFile = f => !/\.(png|jpe?g|webp|gif|ico|icns|mp4|webm|woff2?|ttf|otf|zip|gz|exe|dll|bin|pdf)$/i.test(f.rel) && f.size < 5_000_000; const pathPatterns = [ [/C:\\Users\\[^\\\s"'`]+/g], [/C:\/Users\/[^/\s"'`]+/g], [/\/Users\/(?!<)[A-Za-z0-9._-]+/g], [/\/home\/(?!<)[A-Za-z0-9._-]+/g, '/home/'], ]; const pathHits = []; for (const f of all.filter(textFile)) { const text = fs.readFileSync(f.full, 'utf8'); if (!/Users|home/.test(text)) continue; text.split('\n').forEach((line, i) => { for (const [re] of pathPatterns) { re.lastIndex = 0; const m = line.match(re); if (m) pathHits.push(`${f.rel}:${i + 1}: ${m.map(x => mask(x)).join(', ')}`); } }); } // Relative links in kept Markdown that point at something the tree does not have. const present = new Set(all.map(f => f.rel)); const dirs = new Set(); for (const rel of present) for (let d = path.posix.dirname(rel); d !== '.'; d = path.posix.dirname(d)) dirs.add(d); const deadLinks = []; for (const f of all.filter(f => f.rel.endsWith('.md'))) { const text = fs.readFileSync(f.full, 'utf8'); for (const m of text.matchAll(/\]\(([^)\s#]+)(?:#[^)]*)?\)/g)) { const target = m[1]; if (/^([a-z]+:|\/\/|#|mailto:)/i.test(target)) continue; const resolved = path.posix.normalize(path.posix.join(path.posix.dirname(f.rel), target)); if (resolved.startsWith('waybetter/')) continue; // the submodule if (!present.has(resolved) && !dirs.has(resolved.replace(/\/$/, ''))) deadLinks.push(`${f.rel}: ${target}`); } } // Names of files and the whole tree through the framework's scan (terms from the keys folder). const cli = path.join(root, 'waybetter', 'packages', 'waybetter', 'bin', 'waybetter.mjs'); const { TERMS_ENV, privacyConfig } = await import(pathToFileURL(path.join(root, 'waybetter', 'packages', 'waybetter', 'cli', 'privacy.mjs')).href); const configured = process.env[TERMS_ENV] || privacyConfig(root).forbiddenTerms; const termsArgs = configured && fs.existsSync(configured) ? ['--terms', configured] : []; const allowArgs = ['--allow', path.join(root, 'privacy-allowlist.txt')]; const runScan = (cwd, ...scanArgs) => { const r = spawnSync(process.execPath, [cli, 'privacy-scan', ...scanArgs, ...termsArgs, ...allowArgs], { cwd, encoding: 'utf8', maxBuffer: 1 << 28, }); return { status: r.status, text: mask(`${r.stdout ?? ''}${r.stderr ?? ''}`).trim(), terms: termsArgs.length > 0 }; }; const scanTree = runScan(root, tree); // --------------------------------------------------------------------------------------------- // The single commit, authored as CRT, in a throwaway repository next to the tree. const repo = path.join(out, 'repo'); const emptyConfig = path.join(out, 'empty.gitconfig'); fs.writeFileSync(emptyConfig, ''); const env = { ...process.env, GIT_AUTHOR_NAME: AUTHOR.name, GIT_AUTHOR_EMAIL: AUTHOR.email, GIT_COMMITTER_NAME: AUTHOR.name, GIT_COMMITTER_EMAIL: AUTHOR.email, GIT_CONFIG_GLOBAL: emptyConfig, GIT_CONFIG_NOSYSTEM: '1' }; const g = (...a) => execFileSync('git', a, { cwd: repo, env, encoding: 'utf8', maxBuffer: 1 << 28 }).trim(); if (UPDATE) { // One new commit on top of the public repository's current main: its history is the only history. execFileSync('git', ['clone', '-q', '--branch', 'main', PUBLIC_REPO, repo], { env, encoding: 'utf8', maxBuffer: 1 << 28 }); g('config', 'core.autocrlf', 'false'); for (const entry of fs.readdirSync(repo)) if (entry !== '.git') fs.rmSync(path.join(repo, entry), { recursive: true, force: true }); fs.cpSync(tree, repo, { recursive: true }); } else { fs.cpSync(tree, repo, { recursive: true }); g('init', '-q', '-b', 'main'); g('config', 'core.autocrlf', 'false'); } g('add', '-A'); g('update-index', '--add', '--cacheinfo', `160000,${fwCommit},waybetter`); if (UPDATE && !g('status', '--porcelain')) throw new Error('nothing changed: the public main already has this tree'); g('commit', '-q', '-m', UPDATE ? MESSAGE : 'wayBetter for X'); const commit = g('rev-parse', 'HEAD'); const parent = UPDATE ? g('rev-parse', 'HEAD~1') : null; const changed = UPDATE ? g('diff', '--stat', 'HEAD~1', 'HEAD').split('\n').pop() : ''; const identity = g('log', '-1', '--format=%an <%ae> | %cn <%ce>'); const scanHistory = args.includes('--no-history-scan') ? { status: null, text: 'skipped' } : runScan(repo, '--history', '.'); const subStatus = g('ls-tree', 'HEAD', 'waybetter'); const gitmodules = g('show', 'HEAD:.gitmodules'); // --------------------------------------------------------------------------------------------- // The framework's unpushed commits: authors, messages and the diff range through the same scan. const fwDir = path.join(root, 'waybetter'); const fwGit = (...a) => execFileSync('git', a, { cwd: fwDir, encoding: 'utf8', maxBuffer: 1 << 28 }).trim(); let fwSection; try { try { fwGit('fetch', 'origin'); } catch { /* offline: use the refs as they are */ } const upstream = fwGit('rev-parse', '--abbrev-ref', '@{upstream}'); const base = fwGit('merge-base', 'HEAD', upstream); const ahead = fwGit('rev-list', '--count', `${base}..HEAD`); const behind = fwGit('rev-list', '--count', `HEAD..${upstream}`); const idents = fwGit('log', '--format=%an <%ae> | %cn <%ce>', `${base}..HEAD`).split('\n').filter(Boolean); const counts = [...new Set(idents)].map(i => `${idents.filter(x => x === i).length} x ${i}`); const tmp = path.join(out, 'fw-range'); fs.mkdirSync(tmp, { recursive: true }); fs.writeFileSync(path.join(tmp, 'range.patch'), fwGit('log', '-p', '--format=commit %H%nAuthor: %an <%ae>%nCommitter: %cn <%ce>%n%n%B', `${base}..HEAD`)); fs.writeFileSync(path.join(tmp, 'names.txt'), fwGit('diff', '--name-only', `${base}..HEAD`)); const scanRange = runScan(root, tmp); const scanAll = runScan(fwDir, '--history', '.'); const log = fwGit('log', '--format=- %h %s', `${base}..HEAD`).split('\n').map(l => l.slice(0, 160)); fwSection = ['', '## Framework unpushed commits', '', `Local branch is ${ahead} ahead and ${behind} behind ${upstream} (base ${base.slice(0, 10)}, head ${fwGit('rev-parse', 'HEAD').slice(0, 10)}).`, '', `Authors and committers: ${counts.join('; ')}`, '', `- Privacy scan over the patch text (messages, authors, every added and removed line) and the changed file names: exit ${scanRange.status}`, '', '```', scanRange.text, '```', '', `- Privacy scan over the framework's whole history (every blob, path, message, identity): exit ${scanAll.status}`, '', '```', scanAll.text, '```', '', '
Commits', '', ...log, '', '
']; fs.rmSync(tmp, { recursive: true, force: true }); } catch (error) { fwSection = ['', '## Framework unpushed commits', '', `Could not be computed: ${mask(error.message).split('\n')[0]}`]; } // --------------------------------------------------------------------------------------------- // Report const mb = n => (n / 1e6).toFixed(1); const lines = []; const p = (...t) => lines.push(...t); p('# Public tree dry run', '', `Generated by \`node scripts/public-tree.mjs\` from app HEAD \`${head.slice(0, 12)}\` and framework commit \`${fwCommit.slice(0, 12)}\` (the gitlink at HEAD unless \`--fw-commit\` was given). Re-run it whenever HEAD moves.`, '', '## Result', '', `- Files: **${all.length}** (HEAD has ${files.length - 1} plus the submodule; ${files.length - 1 - kept.length} excluded)`, `- Size: **${mb(totalBytes)} MB** (git objects will be smaller: compressed)`, `- Images and media in the set: ${images.length}`, `- Initial commit: \`${commit.slice(0, 12)}\`, author and committer: ${identity}`, `- Submodule entry: \`${subStatus}\``, '', '```', gitmodules, '```', '', '## Excluded, and why', '', '| Files | Reason | Examples |', '| ---: | --- | --- |'); for (const [reason, entry] of excluded) p(`| ${entry.count} | ${reason} | ${entry.samples.map(s => `\`${s}\``).join(', ')} |`); p('', 'Everything else tracked at HEAD is in the set. `.gitmodules` is rewritten to the public framework URL.', '', '## Scans', '', `- Forbidden-terms file: ${scanTree.terms ? 'present and used' : 'MISSING (only the machine account name was checked)'}`, `- Privacy scan over the tree (file contents, binaries, archives and file names): exit ${scanTree.status}`, '', '```', scanTree.text || '(no output)', '```', '', `- Privacy scan over the new repository's history (blobs, paths, commit message, identity): exit ${scanHistory.status}`, '', '```', scanHistory.text || '(no output)', '```', '', `- Absolute user paths (\`C:\\Users\\\`, \`/Users/\`, \`/home/\`): **${pathHits.length}** hit(s), user names masked`); if (pathHits.length) p('', '```', ...pathHits.slice(0, 60), pathHits.length > 60 ? `... ${pathHits.length - 60} more` : '', '```'); p('', `- Relative Markdown links to files that are not in the set: **${deadLinks.length}**`); if (deadLinks.length) p('', '```', ...deadLinks, '```'); p('', `- Files over ${mb(MAX_FILE)} MB (review): ${big.length}`); if (big.length) p('', ...big.map(f => ` - \`${f.rel}\` ${mb(f.size)} MB`)); p('', '## Images', '', `${images.length} image and media files; ${images.length - unreviewed.length} match the reviewed list (scripts/public-tree.reviewed-images.json: path and sha256 of what a person looked at, or a generated card). Unreviewed or changed, to look at before publishing: **${unreviewed.length}**`, '', ...unreviewed.map(r => '- ' + r), '', '## Publish (the coordinator runs these)', '', 'The framework goes first: push it, then use its pushed commit as the submodule pointer. Re-run this script with `--fw-commit ` if it differs from the gitlink above.', '', ...(UPDATE ? ['Update mode: one new commit on top of the public main (' + parent.slice(0, 12) + '): ' + changed + '. Push it with:', '', '```sh', `cd "${show(repo)}"`, 'git push origin main', '```', ''] : []), '```sh', '# 1. framework (already public; its remote is behind the local branch)', '# after reading section "Framework unpushed commits" of the report and fixing what it lists:', '# git -C waybetter push origin main', '', `# 2. re-run the dry run and read the report again`, `node scripts/public-tree.mjs`, '', '# 3. the new repository: an empty repo at ' + PUBLIC_REPO + ' first (created on the forge by the owner or coordinator), then', `cd "${show(repo)}"`, `git remote add origin ${PUBLIC_REPO}`, 'git push -u origin main', '```', '', `The commit in \`${show(repo)}\` is already authored as ${AUTHOR.name} <${AUTHOR.email}> with the message "wayBetter for X". To use another message or a date, amend it there before pushing (\`git commit --amend\` with the same identity in the environment).`, ''); lines.push(...fwSection, ''); fs.writeFileSync(path.join(out, 'REPORT.md'), lines.join('\n')); fs.writeFileSync(path.join(out, 'images.txt'), images.map(f => `${f.rel}\t${f.size}`).join('\n') + '\n'); if (UPDATE) console.log(`update commit ${commit.slice(0, 12)} on public main ${parent.slice(0, 12)}: ${changed}\npush: cd "${show(repo)}" && git push origin main`); console.log(`public tree: ${all.length} files, ${mb(totalBytes)} MB, commit ${commit.slice(0, 12)}`); console.log(`scan tree: exit ${scanTree.status}; scan history: exit ${scanHistory.status}; path hits: ${pathHits.length}; dead links: ${deadLinks.length}`); console.log(`report: ${show(path.join(out, 'REPORT.md'))}`);