#!/usr/bin/env node
// Assemble a body file. The save skill owns summary judgment and publication.
import { existsSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
import { basename, isAbsolute, relative, resolve, sep } from 'node:path';
import { readPacked } from '../../../scripts/archive.mjs';
import { isMain } from '../../../scripts/lib/cli.mjs';
function webUrl(value) {
const url = new URL(value);
if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
throw new Error('expected an HTTP(S) URL without credentials, query, or fragment');
}
return url.href.replace(/\/$/, '');
}
export function renderPrBody({ repoRoot = '.', changeRoot, mode, repoUrl, branch, summaryFile, previewUrl }) {
if (!changeRoot || !summaryFile || !branch || !['active', 'archive'].includes(mode)) throw new Error('change root, mode, branch, and summary file are required');
const root = resolve(repoRoot);
// A shipped change is one packed file, named by it or by its old folder path: each part is read inside it.
const folder = resolve(root, changeRoot);
const packed = mode === 'archive' && (folder.endsWith('.md') || (!existsSync(folder) && existsSync(`${folder}.md`)));
const selected = packed && !folder.endsWith('.md') ? `${folder}.md` : folder;
const path = relative(root, selected).split(sep).join('/');
if (!path || path === '..' || path.startsWith('../') || isAbsolute(path)) throw new Error('change must be inside the selected repository');
const part = file => {
if (!packed) return readFileSync(resolve(selected, file), 'utf8');
const text = readPacked(selected, file);
if (text === null) throw new Error(`${path} holds no ${file}`);
return text;
};
const proposal = part('proposal.md');
const status = proposal.match(/^\*\*Status:\*\*[ \t]*([^\r\n]*)/m)?.[1].trim();
if (!status) throw new Error('proposal is missing Status');
const tasks = part('tasks.md');
const summary = readFileSync(summaryFile, 'utf8').trim();
if (!summary || !tasks.trim()) throw new Error('summary and tasks must not be empty');
const repo = webUrl(repoUrl);
const preview = previewUrl ? webUrl(previewUrl) : null;
const encodedPath = path.split('/').map(encodeURIComponent).join('/');
const link = `${repo}/blob/${encodeURIComponent(branch)}/${encodedPath}`;
const name = mode === 'archive' ? basename(selected).replace(/\.md$/, '').replace(/^\d{4}-\d{2}-\d{2}-/, '') : basename(selected);
let body = `## Summary\n\n**Status:** ${status}\n\n${summary}\n\n## Tasks\n\n${tasks}`;
if (!body.endsWith('\n')) body += '\n';
if (packed && readPacked(selected, 'review.html') !== null) {
body += `\n## Review\n\n[Review page](${link}), packed with the plan — in a clone, \`node .claude/plugins/loop/scripts/archive.mjs unpack ${name}\` opens it; GitHub shows the source.\n`;
} else if (!packed && existsSync(resolve(selected, 'review.html'))) {
body += `\n## Review\n\n[Interactive review](${link}/review.html) — open from a clone to view and annotate offline; GitHub shows the source.\n`;
}
if (preview) body += `\n## Preview\n\n[${preview}](${preview})\n`;
body += `\n---\n_Handoff: [${path}](${link})${mode === 'active' ? ` — pick it up with \`/apply ${name}\`` : ''}. This body is regenerated by every /save; comment rather than editing it._\n`;
return body;
}
export function writePrBody(options, outputFile) {
if (!outputFile) throw new Error('output file is required');
const selected = resolve(options.repoRoot ?? '.', options.changeRoot ?? '.');
const output = resolve(outputFile);
const forbidden = ['proposal.md', 'tasks.md', 'review.html', 'app.json'].map(p => resolve(selected, p));
if (forbidden.includes(output) || output === resolve(options.summaryFile ?? '.')) throw new Error('output must not replace an input artifact');
const body = renderPrBody(options);
if (existsSync(output) && readFileSync(output, 'utf8') === body) return false;
const temporary = `${output}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
try { writeFileSync(temporary, body, { flag: 'wx' }); renameSync(temporary, output); }
finally { rmSync(temporary, { force: true }); }
return true;
}
if (isMain(import.meta.url)) {
const keys = { '--repo-root': 'repoRoot', '--change-root': 'changeRoot', '--mode': 'mode', '--repo-url': 'repoUrl', '--branch': 'branch', '--summary-file': 'summaryFile', '--preview-url': 'previewUrl', '--output': 'output' };
const usage = `usage: render-pr-body.mjs ${Object.keys(keys).map(key => `${key} <value>`).join(' ')}`;
const args = process.argv.slice(2);
if (args[0] === '--help') { console.log(usage); process.exit(0); }
const options = {};
for (let i = 0; i < args.length; i += 2) {
if (!keys[args[i]] || !args[i + 1]) { console.error(`PR body: invalid option or missing value\n${usage}`); process.exit(2); }
options[keys[args[i]]] = args[i + 1];
}
try {
console.log(`PR body: ${writePrBody(options, options.output) ? 'updated' : 'unchanged'}`);
} catch (error) { console.error(`PR body: ${error.message}`); process.exitCode = 1; }
}