voyage/lib/util/artifact-commit.mjs
Kjell Tore Guttormsen 5244d2e8e8
feat(brief): ceremony by size, one question round, logged and committed approvals
P1 (order 2, wave 1). /trekbrief puts the task in a size class
(ceremony: small|bounded|architectural, K1; heaviest in doubt, said
aloud, overridable, only moved up) that sets the question budget and the
review cap, and asks one round of questions: facts looked up, never
asked; recommendation first; ranked by impact x uncertainty with a
visible Deferred list; stop when the next three answers can be predicted.
"høres bra ut", "gjør som du vil" and an empty answer are not approval.

K2: lib/util/approval-log.mjs, an append-only hash-chained log in the
target repo (.claude/voyage/approvals.jsonl) bound to the approved
content's sha256; append/verify (0/1/2), answer, digest. Committed by
lib/util/artifact-commit.mjs: the log always, the brief and plan only
with artifact_store: git (operator decision 2026-10-06). /trekplan
Phase 1 halts on a broken, diverged, missing or mismatched log entry;
Phase 11 logs and commits an explicit plan approval before any handoff.

Both new brief fields are optional: no brief_version bump. The
main-module guard in intent-approval.mjs and brief-validator.mjs now
compares real paths. Borrowings credited in the prose and module headers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 19:44:42 +02:00

114 lines
5.2 KiB
JavaScript

// 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 -- <paths>`): 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.
//
// CLI:
// node lib/util/artifact-commit.mjs --store <git|local> [--artifact <path>]...
// [--message <msg>] [--repo <dir>]
// prints {committed, commit?, paths, excluded, warnings, reason?}
// exit 0 = committed, or nothing new to commit; 1 = refused (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 { fileURLToPath } from 'node:url';
import { LOG_RELPATH, logPath, normalizeSubject } from './approval-log.mjs';
export const ARTIFACT_STORES = Object.freeze(['git', 'local']);
const DEFAULT_MESSAGE = 'docs(voyage): record approval';
function git(repo, args, timeout = 60_000) {
return spawnSync('git', ['-C', repo, ...args], { encoding: 'utf8', timeout });
}
/** Add `/<dir>/` 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 }) {
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(', ')}]` };
}
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, '--', ...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() };
}
function isMain() {
try {
return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
} catch {
return false;
}
}
if (isMain()) {
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,
});
}
const { exit, ...rest } = r;
process.stdout.write(JSON.stringify(rest) + '\n');
process.exit(exit);
}