// lib/util/artifact-commit.mjs // Commit an approved artifact in the TARGET repo. The approval log // (lib/util/approval-log.mjs) is always committed; the artifact itself (brief.md, // plan.md) only when the operator chose `artifact_store: git`. With `local` the // artifact's folder is kept out of git through the repo's own .git/info/exclude, // a file that is never committed, so no shared file changes (operator decision // 2026-10-06: «Loggen alltid, briefen etter valg»). // // The commit names its paths (`git commit --only -- `): whatever else the // operator has staged stays staged and uncommitted. A path the repo ignores is // never forced in; the refusal says so. The repo's own git hooks run as usual. // // The commit carries the caller's trailer: `--trailer ""`, one line // matching `Co-Authored-By: <>` (TRAILER_RE), written as the // message's last paragraph (`git commit -m -m `). A missing // trailer, a multi-line one, one that does not match (an unfilled `{model}` // placeholder, no ``, another key) or one holding `Claude-Session:` is // refused with exit 1. Order: the `--store` check first (exit 2), then the // trailer (exit 1), both before commitArtifacts makes any git call (the CLI // only finds the repo root first), so "nothing to commit" cannot mask a bad // trailer. // // CLI: // node lib/util/artifact-commit.mjs --store [--artifact ]... // --trailer "Co-Authored-By: <>" [--message ] [--repo ] // prints {committed, commit?, paths, excluded, warnings, reason?} // exit 0 = committed, or nothing new to commit; 1 = refused (missing or bad // trailer, ignored path, path outside the repo, git add/commit failed); // 2 = could not run (not a git repo, bad arguments, git timed out). 2 is never // green. import { spawnSync } from 'node:child_process'; import { appendFileSync, existsSync, readFileSync, realpathSync } from 'node:fs'; import { isAbsolute, resolve } from 'node:path'; import { LOG_RELPATH, logPath, normalizeSubject } from './approval-log.mjs'; import { isMain } from './is-main.mjs'; export const ARTIFACT_STORES = Object.freeze(['git', 'local']); const DEFAULT_MESSAGE = 'docs(voyage): record approval'; // One `Co-Authored-By:` line; `{`/`}` are refused so an unfilled `{model}` fails. const TRAILER_RE = /^Co-Authored-By: [^<>{}\n]+ <[^\s<>@]+@[^\s<>]+>$/; /** @returns {string|null} why `trailer` is refused, or null when it is valid */ function trailerProblem(trailer) { if (typeof trailer !== 'string' || trailer === '') { return '--trailer "Co-Authored-By: <>" is required — nothing committed'; } if (/[\r\n]/.test(trailer)) return '--trailer must be one line — nothing committed'; if (trailer.includes('Claude-Session:')) return '--trailer must not hold a Claude-Session: line — nothing committed'; if (!TRAILER_RE.test(trailer)) { return `--trailer must read "Co-Authored-By: <>" with every placeholder filled; got "${trailer}" — nothing committed`; } return null; } function git(repo, args, timeout = 60_000) { return spawnSync('git', ['-C', repo, ...args], { encoding: 'utf8', timeout }); } /** Add `//` to the repo's .git/info/exclude once. @returns the pattern */ function excludeLocally(repo, rel) { const slash = rel.lastIndexOf('/'); const pattern = slash > 0 ? `/${rel.slice(0, slash)}/` : `/${rel}`; const where = git(repo, ['rev-parse', '--git-path', 'info/exclude']).stdout.trim(); const file = isAbsolute(where) ? where : resolve(repo, where); const text = existsSync(file) ? readFileSync(file, 'utf8') : ''; if (!text.split('\n').includes(pattern)) { appendFileSync(file, (text && !text.endsWith('\n') ? '\n' : '') + pattern + '\n'); } return pattern; } /** * @returns {{ exit: number, committed: boolean, commit?: string, paths: string[], * excluded: string[], warnings: string[], reason?: string }} */ export function commitArtifacts({ repo, store, artifacts = [], message = DEFAULT_MESSAGE, trailer }) { const res = { committed: false, paths: [], excluded: [], warnings: [] }; if (!ARTIFACT_STORES.includes(store)) { return { ...res, exit: 2, reason: `--store must be one of [${ARTIFACT_STORES.join(', ')}]` }; } const bad = trailerProblem(trailer); if (bad) return { ...res, exit: 1, reason: bad }; if (existsSync(logPath(repo))) res.paths.push(LOG_RELPATH); for (const a of artifacts) { const rel = normalizeSubject(repo, a); if (isAbsolute(rel)) return { ...res, exit: 1, reason: `${a} is outside the repo ${repo}` }; if (store === 'git') { res.paths.push(rel); continue; } if (git(repo, ['ls-files', '--error-unmatch', '--', rel]).status === 0) { res.warnings.push(`${rel} is already tracked; it stays in git (local applies to new files only)`); continue; } res.excluded.push(excludeLocally(repo, rel)); } if (!res.paths.length) return { ...res, exit: 0, reason: 'nothing to commit' }; const add = git(repo, ['add', '--', ...res.paths]); if (add.status !== 0) { const ignored = /ignored/i.test(add.stderr); return { ...res, exit: 1, reason: ignored ? `${res.paths.join(', ')}: ignored by the repo (.gitignore); not forced in — nothing committed` : `git add failed: ${add.stderr.trim()}`, }; } if (git(repo, ['diff', '--cached', '--quiet', '--', ...res.paths]).status === 0) { return { ...res, exit: 0, reason: 'nothing to commit' }; } const c = git(repo, ['commit', '-q', '--only', '-m', message, '-m', trailer, '--', ...res.paths]); if (c.error) return { ...res, exit: 2, reason: `git commit did not finish: ${c.error.message}` }; if (c.status !== 0) return { ...res, exit: 1, reason: `git commit failed: ${(c.stderr || c.stdout).trim()}` }; return { ...res, exit: 0, committed: true, commit: git(repo, ['rev-parse', 'HEAD']).stdout.trim() }; } if (isMain(import.meta.url)) { const args = process.argv.slice(2); const opt = (n) => { const i = args.indexOf(n); return i >= 0 ? args[i + 1] : undefined; }; const artifacts = args.flatMap((a, i) => (a === '--artifact' && args[i + 1] !== undefined ? [args[i + 1]] : [])); const top = spawnSync('git', ['rev-parse', '--show-toplevel'], { cwd: opt('--repo') ? resolve(opt('--repo')) : process.cwd(), encoding: 'utf8', }); let r; if (top.status !== 0 || !top.stdout.trim()) { r = { exit: 2, committed: false, paths: [], excluded: [], warnings: [], reason: 'not a git repository — nothing committed' }; } else { r = commitArtifacts({ repo: realpathSync(top.stdout.trim()), store: opt('--store'), artifacts, message: opt('--message') || DEFAULT_MESSAGE, trailer: opt('--trailer'), }); } const { exit, ...rest } = r; process.stdout.write(JSON.stringify(rest) + '\n'); process.exit(exit); }