graceful-handoff/scripts/handoff-pipeline.mjs
Kjell Tore Guttormsen 5334097c84 fix(graceful-handoff): two defects found by the first real smoke test (v3.2.1)
The pipeline had never been run against an actual repository — every test in
the suite is either a prose-grep over SKILL.md or a unit test that asserts key
presence. Running it against scratch repos (private remote, and public `open/`
remote with and without a gitignored STATE.md) found two defects living under
a 42/42-green suite.

1. dirty_files truncated the first path. gitOk() trims every command's output,
   but `git status --porcelain` puts the worktree status in column 2, so a
   modified-but-unstaged file is " M path". The trim ate the leading space and
   the fixed slice(3) then ate the first character: app.js was reported as
   pp.js. Only the first line is affected, which is why it survived — no test
   asserted dirty_files VALUES, only that the key existed. Porcelain now goes
   through a non-trimming gitOkRaw().

2. The commit message claimed a STATE.md update it did not contain. The
   message was hardcoded to "oppdater STATE.md" regardless of what was staged.
   On every `open/` repo STATE.md is gitignored, so the handoff commit carries
   only the --also paths. Git history is the regime's long-term log; it was
   systematically wrong about its own contents.

Also promotes the leak condition from advisory to hard gate. A public remote
whose STATE.md is not yet gitignored is the state a FRESH open/ repo starts
in, and should_commit_state was true there — the ritual only mentioned
leak_warning, then committed. It now lands in errors[] (step 2 stops on a
non-empty errors[]), should_commit_state is false, and --commit refuses to
stage STATE.md. Explicit --also paths are still honoured: the gate protects
STATE.md, not the commit as a whole.

And corrects SKILL.md's justification for the single-line rule. It claimed a
wrapped rationale= replaces the board's next step with garbage; board.sh in
repo-mailbox 0.20.3 tracks a comment to its closer, so that no longer follows.
The rule stands, restated with the risk that is still real: a rationale
containing the closer sequence ends its own comment early.

Tests 42 -> 48, all six written failing first.

Still unverified: that /graceful-handoff loads as a user command (#26251), and
that a cross-plugin Skill invocation of repo-mailbox:route passes from a
sub-scoped skill. Both need the catalog ref bumped so the version is installed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RvLY4FwbzY157oVqwnkHD8
2026-08-09 21:49:08 +02:00

290 lines
12 KiB
JavaScript

#!/usr/bin/env node
// handoff-pipeline.mjs — Deterministic STATE.md helper for graceful-handoff v3.0.
//
// graceful-handoff is now a thin executor of the global "Session Slutt" ritual,
// centred on STATE.md (the three-layer continuity system). The MODEL writes the
// STATE.md content — only it has the session context needed to fill the mandatory
// "👉 NESTE — START HER" block. This script does ONLY the deterministic parts:
//
// --plan (default): resolve the nearest STATE.md, classify the remote
// (private → tracked, public/open → local-only), gather git
// facts. Read-only. Output JSON. The model uses this to write
// STATE.md.
// --commit : stage STATE.md (ONLY if it is NOT gitignored) plus any
// explicit --also paths, then commit. NEVER `git add -A`.
// Never pushes (push stays user-triggered — no window gate).
// --dry-run : never writes, never touches git.
//
// Why STATE.md must never be auto-committed on a public mirror: a repo whose only
// remote is the public `open/` Forgejo would leak internal state-of-play on push.
// Per the global rule, such repos keep STATE.md local-only (gitignored). The
// authoritative signal here is `git check-ignore STATE.md`; remote_class is the
// advisory that warns on misconfiguration (public repo, STATE.md NOT gitignored).
//
// Output (JSON to stdout): see buildPlan() / commit result below.
// Exit codes: 0 = success (even if errors[] non-empty); 1 = unrecoverable internal error.
import { execSync, execFileSync } from 'node:child_process';
import { existsSync } from 'node:fs';
import { dirname, join, basename } from 'node:path';
// ---------- Argument parsing ----------
function parseArgs(argv) {
const args = {
mode: 'plan', // 'plan' | 'commit'
dryRun: false,
message: null,
also: [],
};
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
if (a === '--plan') args.mode = 'plan';
else if (a === '--commit') args.mode = 'commit';
else if (a === '--dry-run') args.dryRun = true;
else if (a === '--message' || a === '-m') args.message = argv[++i] || null;
else if (a === '--also') args.also.push(argv[++i]);
// unknown flags ignored for forward-compat
}
return args;
}
// ---------- Git helpers ----------
function gitOk(cmd, opts = {}) {
try {
return execSync(cmd, { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'], ...opts }).trim();
} catch {
return null;
}
}
// Same as gitOk, but WITHOUT trim(). `git status --porcelain` puts the worktree
// status in column 2, so a modified-but-unstaged file is " M path" — a leading
// space that carries meaning. Trimming it shifted the first line left, and the
// fixed slice(3) below then ate the first character of the first path ("app.js"
// → "pp.js"). Only ever use this where leading whitespace is significant.
function gitOkRaw(cmd, opts = {}) {
try {
return execSync(cmd, { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'], ...opts });
} catch {
return null;
}
}
function gitStatus(cwd) {
const o = { cwd };
const branch = gitOk('git branch --show-current', o) || gitOk('git rev-parse --abbrev-ref HEAD', o);
const porcelain = (gitOkRaw('git status --porcelain', o) || '').replace(/\n+$/, '');
const dirty = porcelain.length > 0;
let ahead = 0;
const upstream = gitOk('git rev-parse --abbrev-ref @{u} 2>/dev/null', o);
if (upstream) {
const counts = gitOk(`git rev-list --left-right --count ${upstream}...HEAD`, o);
if (counts) ahead = parseInt(counts.split(/\s+/)[1] || '0', 10);
}
const detached = !branch || branch === 'HEAD';
const dirtyFiles = porcelain.split('\n').filter(Boolean).map(line => line.slice(3));
return { branch, dirty, ahead, upstream, detached, porcelain, dirtyFiles };
}
function repoRoot(cwd) {
return gitOk('git rev-parse --show-toplevel', { cwd });
}
// ---------- STATE.md resolution ----------
// Walk from cwd up to (and including) the git repo root, returning the nearest
// existing STATE.md. Mirrors the global session-start hook's "nearest STATE.md
// from cwd up to repo root". If none exists, the target is <repoRoot>/STATE.md.
function resolveStatePath(cwd, root) {
const stop = root || cwd;
let cur = cwd;
for (let i = 0; i < 12; i++) {
const candidate = join(cur, 'STATE.md');
if (existsSync(candidate)) return { path: candidate, exists: true };
if (cur === stop) break;
const parent = dirname(cur);
if (parent === cur) break;
cur = parent;
}
return { path: join(stop, 'STATE.md'), exists: false };
}
// ---------- Remote classification ----------
// STATE.md must never reach a public mirror. Private remote → STATE tracked.
// Public (`github.com`, or the `open/` Forgejo mirror) or no remote → local-only.
export function classifyRemote(url) {
if (!url) return 'none';
if (/github\.com|github\.io/i.test(url)) return 'public';
// `open/<repo>` is the public mirror namespace; `ktg/<repo>` etc. is private.
if (/[:/]open\//i.test(url)) return 'public';
return 'private';
}
// The leak gate. A public remote whose STATE.md is NOT gitignored is not an
// advisory condition — it is the single state in which continuing the ritual is
// itself what causes the leak, and it is exactly the state a fresh `open/` repo
// starts in. Both --plan and --commit consult this one function so they cannot
// disagree about whether STATE.md may be staged.
export function leakBlock({ shouldBeLocalOnly, stateGitignored, remoteClass, remoteUrl }) {
if (!shouldBeLocalOnly || stateGitignored) return null;
return `BLOKKERT: STATE.md er IKKE gitignored, men remote er ${remoteClass} (${remoteUrl || 'ingen'}) — `
+ `å committe den ville lekket intern state-of-play ved push. Legg 'STATE.md' i .gitignore `
+ `(den skal være local-only på denne remoten), så kjør rituelet på nytt.`;
}
// ---------- Plan (read-only) ----------
function buildPlan(cwd, errors) {
const root = repoRoot(cwd);
if (!root) {
errors.push('ikke et git-repo (git rev-parse --show-toplevel feilet) — kan ikke resolvere STATE.md-sti');
}
const base = root || cwd;
const { path: statePath, exists: stateExists } = resolveStatePath(cwd, base);
const remoteUrl = gitOk('git remote get-url origin 2>/dev/null', { cwd })
|| gitOk('git remote get-url --all origin 2>/dev/null', { cwd });
const remoteClass = classifyRemote(remoteUrl);
const shouldBeLocalOnly = remoteClass !== 'private';
// Authoritative commit signal: is STATE.md gitignored?
const stateGitignored = !!gitOk(
`git check-ignore -- ${JSON.stringify(basename(statePath))}`,
{ cwd: dirname(statePath) }
);
const leakWarning = leakBlock({ shouldBeLocalOnly, stateGitignored, remoteClass, remoteUrl });
// Blocking, not advisory: step 2 of the ritual stops on a non-empty errors[].
if (leakWarning) errors.push(leakWarning);
const git = gitStatus(cwd);
const recentCommits = (gitOk('git log --oneline -8', { cwd }) || '').split('\n').filter(Boolean);
return {
mode: 'plan',
repo_root: root,
state_path: statePath,
state_name: basename(dirname(statePath)), // dir holding STATE.md → title "# STATE — <name>"
state_exists: stateExists,
state_gitignored: stateGitignored,
remote_url: remoteUrl,
remote_class: remoteClass,
should_be_local_only: shouldBeLocalOnly,
should_commit_state: !stateGitignored && !leakWarning,
leak_warning: leakWarning,
git_status: { branch: git.branch, dirty: git.dirty, ahead: git.ahead, detached: git.detached, upstream: git.upstream },
dirty_files: git.dirtyFiles,
recent_commits: recentCommits,
line_budget: 60,
errors,
};
}
// ---------- Commit (write) ----------
// The message must describe what the commit actually contains. On every `open/`
// repo STATE.md is gitignored, so the handoff commit carries only the explicit
// --also paths — claiming a STATE.md update there made git history, the regime's
// long-term log, systematically wrong about its own contents.
function generateCommitMessage(statePath, root, includesState) {
const name = root ? basename(root) : basename(dirname(statePath));
return includesState
? `docs(${name}): oppdater STATE.md (session handoff)`
: `chore(${name}): session handoff (STATE.md local-only, ikke committet)`;
}
function doCommit(cwd, args, errors) {
const actions = [];
const root = repoRoot(cwd);
const base = root || cwd;
const { path: statePath } = resolveStatePath(cwd, base);
const git = gitStatus(cwd);
if (git.detached) {
errors.push('detached HEAD — hopper over commit (ingen branch å committe på)');
return { mode: 'commit', actions_taken: actions, errors, git_status: git };
}
const stateGitignored = !!gitOk(
`git check-ignore -- ${JSON.stringify(basename(statePath))}`,
{ cwd: dirname(statePath) }
);
// Build the stage list. CRITICAL: never `git add -A` — stage ONLY STATE.md
// (when it is tracked, i.e. not gitignored) plus any explicit --also paths.
// Same gate as --plan: never stage STATE.md onto a public remote. --also paths
// stay honoured — the operator named those explicitly, and the gate protects
// STATE.md specifically, not the commit as a whole.
const remoteUrl = gitOk('git remote get-url origin 2>/dev/null', { cwd });
const remoteClass = classifyRemote(remoteUrl);
const leakWarning = leakBlock({
shouldBeLocalOnly: remoteClass !== 'private', stateGitignored, remoteClass, remoteUrl,
});
const stageList = [];
if (leakWarning) {
errors.push(leakWarning);
actions.push('state-leak-blocked (STATE.md ikke gitignored på offentlig remote — ikke staget)');
} else if (!stateGitignored) {
if (existsSync(statePath)) stageList.push(statePath);
else errors.push(`STATE.md finnes ikke på ${statePath} — skriv den før commit`);
} else {
actions.push('state-local-only-skipped (STATE.md gitignored — committes ikke)');
}
for (const p of args.also) {
const abs = p.startsWith('/') ? p : join(cwd, p);
if (existsSync(abs)) stageList.push(abs);
else errors.push(`--also sti finnes ikke: ${p}`);
}
if (stageList.length === 0) {
actions.push('intet-å-committe (STATE.md ikke committerbar og ingen --also-stier)');
return { mode: 'commit', actions_taken: actions, errors, git_status: git };
}
const message = args.message || generateCommitMessage(statePath, root, stageList.includes(statePath));
try {
execFileSync('git', ['add', '--', ...stageList], { cwd, stdio: ['ignore', 'pipe', 'pipe'] });
execFileSync('git', ['commit', '-m', message, '--', ...stageList], { cwd, stdio: ['ignore', 'pipe', 'pipe'] });
actions.push('committed');
} catch (e) {
errors.push(`commit feilet: ${(e.stderr || e.message || '').toString().slice(0, 200)}`);
}
return { mode: 'commit', actions_taken: actions, committed_paths: stageList, commit_message: message, errors, git_status: git };
}
// ---------- Main ----------
function main() {
const args = parseArgs(process.argv.slice(2));
const cwd = process.cwd();
const errors = [];
if (args.dryRun) {
const plan = buildPlan(cwd, errors);
plan.mode = 'dry-run';
plan.note = 'dry-run: ingen skriving, ingen git-mutasjon';
process.stdout.write(JSON.stringify(plan, null, 2) + '\n');
return;
}
let result;
if (args.mode === 'commit') {
result = doCommit(cwd, args, errors);
} else {
result = buildPlan(cwd, errors);
}
process.stdout.write(JSON.stringify(result, null, 2) + '\n');
}
try {
main();
} catch (e) {
process.stderr.write(`pipeline-fatal: ${e.message}\n${e.stack}\n`);
process.exit(1);
}