graceful-handoff/scripts/handoff-pipeline.mjs
Kjell Tore Guttormsen 192d4403eb feat(graceful-handoff): remove hardcoded push window — push is now unconditional (v3.1.0)
The regime-wide push-window restriction (man–tor 08:00–17:00, fre 08:00–16:00)
was lifted permanently, so SKILL.md no longer gates the push on a weekday/time
window — it would otherwise park a push in the middle of working hours.

Two invariants are unchanged: push is Forgejo only (never GitHub), and push
stays user-triggered (the skill is disable-model-invocation: true). The pipeline
script had no window logic — only its header comment was corrected.

If a future repo needs a window again, reintroduce it as per-repo config, never
as a hardcoded default.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BcNX2QdgmXyLd2Bt6Z25GU
2026-06-24 11:00:10 +02:00

248 lines
9.1 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;
}
}
function gitStatus(cwd) {
const o = { cwd };
const branch = gitOk('git branch --show-current', o) || gitOk('git rev-parse --abbrev-ref HEAD', o);
const porcelain = gitOk('git status --porcelain', o) || '';
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';
}
// ---------- 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 = (shouldBeLocalOnly && !stateGitignored)
? `STATE.md er IKKE gitignored, men remote er ${remoteClass} (${remoteUrl || 'ingen'}) — `
+ `legg STATE.md i .gitignore for å unngå å lekke intern state-of-play ved push.`
: null;
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,
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) ----------
function generateCommitMessage(statePath, root) {
const name = root ? basename(root) : basename(dirname(statePath));
return `docs(${name}): oppdater STATE.md (session handoff)`;
}
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.
const stageList = [];
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 gitignored og ingen --also-stier)');
return { mode: 'commit', actions_taken: actions, errors, git_status: git };
}
const message = args.message || generateCommitMessage(statePath, root);
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);
}