feat(graceful-handoff)!: integrate with STATE.md continuity system (v3.0.0)
BREAKING: replace the NEXT-SESSION artifact + 3 hooks with a STATE.md-centric, skill-only design. /graceful-handoff now overwrites the nearest STATE.md (with the mandatory 👉 NESTE block) instead of writing a separate handover file. - Remove hooks/ entirely: Stop auto-trigger (operator choice), SessionStart loader (redundant with global session-start.sh), statusLine hint (dead — user settings win). - Invert the pipeline: the model writes STATE.md (only it has the context for 👉 NESTE); handoff-pipeline.mjs becomes a slim deterministic helper (--plan / --commit / --dry-run). - Remote-aware policy: STATE.md tracked on private remotes, local-only (gitignored) on public/open mirrors. Authoritative signal: git check-ignore STATE.md. - SKILL.md rewritten as the Session-Slutt ritual; dropped the Sonnet model pin. - Docs (README, CLAUDE.md, CHANGELOG), plugin.json 2.1.0→3.0.0, .gitignore cleanup. - Tests rewritten for --plan/--commit; no-`git add -A` regression preserved. 30/30 green. Release-cut (tag v3.0.0 + catalog ref bump) pending — separate gated action. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019SiKr4c6GAzQH5n6E6f5NA
This commit is contained in:
parent
a6f3ad4e93
commit
2c4e5e425b
18 changed files with 694 additions and 1656 deletions
|
|
@ -1,53 +1,50 @@
|
|||
#!/usr/bin/env node
|
||||
// handoff-pipeline.mjs — Deterministic JSON pipeline for graceful-handoff v2.0.
|
||||
// handoff-pipeline.mjs — Deterministic STATE.md helper for graceful-handoff v3.0.
|
||||
//
|
||||
// Detects handoff type, classifies state, writes NEXT-SESSION artifact, optionally
|
||||
// commits and pushes. Returns structured JSON to stdout. Designed to be called both
|
||||
// by the SKILL.md (interactive) and the Stop hook (auto-execute).
|
||||
// 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:
|
||||
//
|
||||
// Usage:
|
||||
// node handoff-pipeline.mjs [topic-slug] [--dry-run] [--no-commit] [--no-push]
|
||||
// [--auto] [--non-interactive] [--json]
|
||||
// --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 window-gated + user-triggered).
|
||||
// --dry-run : never writes, never touches git.
|
||||
//
|
||||
// Output (JSON to stdout):
|
||||
// {
|
||||
// "handoff_type": "multi-sesjon | plugin-arbeid | enkelt-oppgave",
|
||||
// "write_dir": "/abs/path",
|
||||
// "artifact_path": "/abs/path/NEXT-SESSION-...",
|
||||
// "next_steps": [...],
|
||||
// "git_status": { branch, dirty, ahead },
|
||||
// "commit_message": "...",
|
||||
// "actions_taken": [...],
|
||||
// "errors": [...]
|
||||
// }
|
||||
// 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, spawnSync } from 'node:child_process';
|
||||
import { existsSync, readFileSync, writeFileSync, mkdirSync, statSync, readdirSync } from 'node:fs';
|
||||
import { dirname, join, basename, resolve } from 'node:path';
|
||||
import { createInterface } from 'node:readline';
|
||||
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 = {
|
||||
slug: null,
|
||||
mode: 'plan', // 'plan' | 'commit'
|
||||
dryRun: false,
|
||||
noCommit: false,
|
||||
noPush: false,
|
||||
auto: false,
|
||||
nonInteractive: false,
|
||||
json: true,
|
||||
message: null,
|
||||
also: [],
|
||||
};
|
||||
for (const a of argv) {
|
||||
if (a === '--dry-run') args.dryRun = true;
|
||||
else if (a === '--no-commit') args.noCommit = true;
|
||||
else if (a === '--no-push') args.noPush = true;
|
||||
else if (a === '--auto') args.auto = true;
|
||||
else if (a === '--non-interactive') args.nonInteractive = true;
|
||||
else if (a === '--json') args.json = true;
|
||||
else if (!a.startsWith('--') && !args.slug) args.slug = a;
|
||||
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;
|
||||
}
|
||||
|
|
@ -62,320 +59,190 @@ function gitOk(cmd, opts = {}) {
|
|||
}
|
||||
}
|
||||
|
||||
function gitStatus() {
|
||||
const branch = gitOk('git branch --show-current') || gitOk('git rev-parse --abbrev-ref HEAD');
|
||||
const porcelain = gitOk('git status --porcelain') || '';
|
||||
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');
|
||||
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`);
|
||||
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';
|
||||
return { branch, dirty, ahead, upstream, detached, porcelain };
|
||||
const dirtyFiles = porcelain.split('\n').filter(Boolean).map(line => line.slice(3));
|
||||
return { branch, dirty, ahead, upstream, detached, porcelain, dirtyFiles };
|
||||
}
|
||||
|
||||
// ---------- Plugin-root detection ----------
|
||||
function repoRoot(cwd) {
|
||||
return gitOk('git rev-parse --show-toplevel', { cwd });
|
||||
}
|
||||
|
||||
function findPluginRoot(startDir) {
|
||||
let cur = startDir;
|
||||
for (let i = 0; i < 5; i++) {
|
||||
if (existsSync(join(cur, '.claude-plugin', 'plugin.json'))) return cur;
|
||||
// ---------- 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 null;
|
||||
return { path: join(stop, 'STATE.md'), exists: false };
|
||||
}
|
||||
|
||||
// ---------- Multi-session detection ----------
|
||||
// ---------- 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);
|
||||
|
||||
function findActiveProject(cwd) {
|
||||
// Look for .claude/projects/*/progress.json that is not completed
|
||||
try {
|
||||
const out = execSync(
|
||||
`find . -maxdepth 5 -path '*/.claude/projects/*/progress.json' 2>/dev/null | sort -r`,
|
||||
{ cwd, encoding: 'utf-8', stdio: ['ignore', 'pipe', 'ignore'] }
|
||||
).trim().split('\n').filter(Boolean);
|
||||
for (const rel of out) {
|
||||
const abs = resolve(cwd, rel);
|
||||
try {
|
||||
const data = JSON.parse(readFileSync(abs, 'utf-8'));
|
||||
if (data.status && data.status !== 'completed' && data.status !== 'failed') {
|
||||
return { progressPath: abs, projectDir: dirname(abs), status: data.status };
|
||||
}
|
||||
} catch { /* skip malformed */ }
|
||||
}
|
||||
} catch { /* find failed */ }
|
||||
return null;
|
||||
}
|
||||
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)}`);
|
||||
}
|
||||
|
||||
// ---------- Classification ----------
|
||||
|
||||
function classifyHandoff(cwd) {
|
||||
const project = findActiveProject(cwd);
|
||||
if (project) return { type: 'multi-sesjon', writeDir: project.projectDir, projectDir: project.projectDir };
|
||||
|
||||
const pluginRoot = findPluginRoot(cwd);
|
||||
if (pluginRoot) return { type: 'plugin-arbeid', writeDir: pluginRoot, pluginRoot };
|
||||
|
||||
return { type: 'enkelt-oppgave', writeDir: cwd };
|
||||
}
|
||||
|
||||
// ---------- Commit-message generation ----------
|
||||
|
||||
function generateCommitMessage(status) {
|
||||
const files = status.porcelain.split('\n').filter(Boolean).map(line => line.slice(3));
|
||||
const tests = files.filter(f => f.includes('/tests/') || f.endsWith('.test.mjs') || f.endsWith('.test.js')).length;
|
||||
const docs = files.filter(f => /\.(md|mdx)$/i.test(f) && !f.includes('/tests/')).length;
|
||||
const code = files.length - tests - docs;
|
||||
|
||||
let type = 'chore';
|
||||
if (code > 0 && code >= tests + docs) type = 'feat';
|
||||
else if (tests > 0 && tests >= code) type = 'test';
|
||||
else if (docs > 0 && docs >= code) type = 'docs';
|
||||
|
||||
// Scope = plugin name if all files in single plugin
|
||||
const pluginMatch = files
|
||||
.map(f => f.match(/^plugins\/([^/]+)/))
|
||||
.filter(Boolean)
|
||||
.map(m => m[1]);
|
||||
const uniquePlugins = [...new Set(pluginMatch)];
|
||||
const scope = uniquePlugins.length === 1 ? uniquePlugins[0] : '';
|
||||
|
||||
const subject = `wip: pågående arbeid (${files.length} fil${files.length === 1 ? '' : 'er'})`;
|
||||
return scope ? `${type}(${scope}): ${subject}` : `${type}: ${subject}`;
|
||||
}
|
||||
|
||||
// ---------- Artifact rendering ----------
|
||||
|
||||
function renderArtifact(state, classification) {
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
const branch = state.git.branch || 'HEAD';
|
||||
const lastCommits = (gitOk('git log --oneline -5') || '').split('\n').filter(Boolean);
|
||||
|
||||
const lines = [];
|
||||
lines.push(`# NEXT-SESSION-PROMPT — ${basename(classification.writeDir)} ${today}`);
|
||||
lines.push('');
|
||||
lines.push('## Hvorfor dette eksisterer');
|
||||
lines.push('');
|
||||
lines.push(`Sesjons-handoff produsert av graceful-handoff v2.0 ${state.auto ? '(auto-trigget av Stop hook)' : '(manuell trigger)'}.`);
|
||||
lines.push(`Type: \`${classification.type}\`. Branch: \`${branch}\`.`);
|
||||
if (state.git.dirty) lines.push('Hadde ucommitted endringer ved handoff-tidspunkt.');
|
||||
lines.push('');
|
||||
lines.push('## Status ved sesjonshåndoff');
|
||||
lines.push('');
|
||||
lines.push('### ✅ Ferdig');
|
||||
lines.push('');
|
||||
if (lastCommits.length === 0) lines.push('- Ingen commits funnet.');
|
||||
else for (const c of lastCommits) lines.push(`- \`${c}\``);
|
||||
lines.push('');
|
||||
lines.push('### ⏳ Ikke startet / delvis');
|
||||
lines.push('');
|
||||
lines.push('- Fyll inn av neste sesjon (graceful-handoff v2.0 pipeline genererer ikke dette automatisk; bruk manuell trigger for spesifikk plan-progresjon).');
|
||||
lines.push('');
|
||||
lines.push('### ⚠️ Brutt / kjent risiko');
|
||||
lines.push('');
|
||||
lines.push(state.git.dirty ? '- Uncommitted endringer ved handoff-tidspunkt — sjekk `git status`.' : '- Ingen kjente broken tester ved handoff.');
|
||||
lines.push('');
|
||||
lines.push('## Slik fortsetter du');
|
||||
lines.push('');
|
||||
lines.push(`1. \`cd ${classification.writeDir}\``);
|
||||
lines.push(`2. \`cat ${state.artifactName}\` — les denne filen igjen`);
|
||||
lines.push('3. `git log --oneline -5` og `git status`');
|
||||
lines.push('4. Fortsett fra siste pågående arbeid');
|
||||
lines.push('');
|
||||
lines.push('## Push-policy');
|
||||
lines.push('');
|
||||
lines.push('- Direkte push til `main` på Forgejo er pre-autorisert');
|
||||
lines.push('- Aldri GitHub — kun Forgejo (`git.fromaitochitta.com`)');
|
||||
lines.push('');
|
||||
lines.push('## Verifiseringskommandoer');
|
||||
lines.push('');
|
||||
lines.push('```bash');
|
||||
lines.push('git log --oneline -5');
|
||||
lines.push('git status');
|
||||
lines.push('```');
|
||||
lines.push('');
|
||||
lines.push('## Husk');
|
||||
lines.push('');
|
||||
lines.push('- Opus 4.7 fyller kontekst raskt — auto-trigger ved estimert 70% er enabled i graceful-handoff v2.0');
|
||||
lines.push('- Push gjenstår hvis dette var auto-handoff (Stop hook bruker `--no-push`)');
|
||||
lines.push('');
|
||||
return lines.join('\n');
|
||||
return { mode: 'commit', actions_taken: actions, committed_paths: stageList, commit_message: message, errors, git_status: git };
|
||||
}
|
||||
|
||||
// ---------- Main ----------
|
||||
|
||||
async function main() {
|
||||
function main() {
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
const cwd = process.cwd();
|
||||
const errors = [];
|
||||
const actionsTaken = [];
|
||||
|
||||
// Validate flag combos
|
||||
if (args.nonInteractive && !args.auto && !args.dryRun && !args.noCommit) {
|
||||
errors.push('--non-interactive uten --auto er ikke gyldig (commit-bekreftelse må enten være interaktiv, auto-godkjent, eller skipped via --no-commit)');
|
||||
output({ args, cwd, classification: null, errors, actionsTaken });
|
||||
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;
|
||||
}
|
||||
|
||||
// 1. Get git state
|
||||
const git = gitStatus();
|
||||
if (!git.branch && !args.dryRun) {
|
||||
errors.push('Kunne ikke detektere git-state — er denne mappen et git-repo?');
|
||||
output({ args, cwd, classification: null, git, errors, actionsTaken });
|
||||
return;
|
||||
}
|
||||
|
||||
// 2. Classify handoff
|
||||
const classification = classifyHandoff(cwd);
|
||||
|
||||
// 3. Determine artifact path
|
||||
const artifactName = args.slug ? `NEXT-SESSION-${args.slug}.local.md` : 'NEXT-SESSION-PROMPT.local.md';
|
||||
const artifactPath = join(classification.writeDir, artifactName);
|
||||
|
||||
// 4. Idempotency check: if artifact exists and was modified < 60s ago, and no new git changes, no-op
|
||||
if (!args.dryRun && existsSync(artifactPath) && !git.dirty) {
|
||||
try {
|
||||
const stat = statSync(artifactPath);
|
||||
const ageMs = Date.now() - stat.mtimeMs;
|
||||
if (ageMs < 60_000) {
|
||||
output({
|
||||
args, cwd, classification, git,
|
||||
artifactPath, commitMessage: '',
|
||||
errors, actionsTaken: ['idempotent-no-op (recent artifact, clean tree)'],
|
||||
nextSteps: nextStepsFor(classification, artifactName),
|
||||
});
|
||||
return;
|
||||
}
|
||||
} catch { /* statSync failed; proceed */ }
|
||||
}
|
||||
|
||||
// 5. Generate commit message
|
||||
const commitMessage = git.dirty ? generateCommitMessage(git) : '';
|
||||
|
||||
// 6. Build state for rendering
|
||||
const state = {
|
||||
git,
|
||||
auto: args.auto,
|
||||
artifactName,
|
||||
};
|
||||
|
||||
// 7. Write artifact
|
||||
const artifactContent = renderArtifact(state, classification);
|
||||
if (!args.dryRun) {
|
||||
try {
|
||||
mkdirSync(classification.writeDir, { recursive: true });
|
||||
writeFileSync(artifactPath, artifactContent, 'utf-8');
|
||||
actionsTaken.push(`wrote-artifact: ${artifactPath}`);
|
||||
} catch (e) {
|
||||
errors.push(`artifact write failed: ${e.message}`);
|
||||
}
|
||||
let result;
|
||||
if (args.mode === 'commit') {
|
||||
result = doCommit(cwd, args, errors);
|
||||
} else {
|
||||
actionsTaken.push(`dry-run: would write artifact to ${artifactPath}`);
|
||||
result = buildPlan(cwd, errors);
|
||||
}
|
||||
|
||||
// 8. Commit (unless --no-commit / --dry-run / nothing to commit)
|
||||
if (!args.dryRun && !args.noCommit && (git.dirty || existsSync(artifactPath))) {
|
||||
// Check robustness: detached HEAD, no remote
|
||||
if (git.detached) {
|
||||
errors.push('detached HEAD — skipping commit (no branch to commit on)');
|
||||
} else {
|
||||
// Confirmation gate
|
||||
let proceed = false;
|
||||
if (args.auto) {
|
||||
proceed = true;
|
||||
} else if (args.nonInteractive) {
|
||||
errors.push('non-interactive without --auto cannot confirm commit');
|
||||
} else {
|
||||
// Interactive: print message to stderr, read y/n from stdin
|
||||
process.stderr.write(`\nCommit-melding:\n---\n${commitMessage}\n---\nFortsett med commit? (y/n): `);
|
||||
proceed = await readYesNo();
|
||||
}
|
||||
if (proceed) {
|
||||
try {
|
||||
// CRITICAL: never `git add -A` — that scoops up unrelated work-in-progress.
|
||||
// Stage ONLY the handoff artifact + optional REMEMBER.md/TODO.md if present.
|
||||
// Other dirty files stay in working tree for the user.
|
||||
const stageList = [artifactPath];
|
||||
for (const candidate of ['REMEMBER.md', 'TODO.md']) {
|
||||
const p = join(classification.writeDir, candidate);
|
||||
if (existsSync(p)) stageList.push(p);
|
||||
}
|
||||
execFileSync('git', ['add', '--', ...stageList], { cwd, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
// git commit with -- pathspec limits commit to those paths from index.
|
||||
execFileSync('git', ['commit', '-m', commitMessage, '--', ...stageList], { cwd, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
actionsTaken.push('committed');
|
||||
} catch (e) {
|
||||
errors.push(`commit failed: ${(e.stderr || e.message || '').toString().slice(0, 200)}`);
|
||||
}
|
||||
} else {
|
||||
actionsTaken.push('commit-cancelled-by-user');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 9. Push (unless --no-push / --dry-run / no commit happened)
|
||||
if (!args.dryRun && !args.noPush && actionsTaken.includes('committed')) {
|
||||
if (!git.upstream) {
|
||||
errors.push('no upstream branch — skipping push (set with: git push -u origin <branch>)');
|
||||
} else {
|
||||
try {
|
||||
execFileSync('git', ['push', 'origin', git.branch], { cwd, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
actionsTaken.push('pushed');
|
||||
} catch (e) {
|
||||
errors.push(`push failed: ${(e.stderr || e.message || '').toString().slice(0, 200)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
output({
|
||||
args, cwd, classification, git,
|
||||
artifactPath, commitMessage,
|
||||
errors, actionsTaken,
|
||||
nextSteps: nextStepsFor(classification, artifactName),
|
||||
});
|
||||
}
|
||||
|
||||
function nextStepsFor(classification, artifactName) {
|
||||
return [
|
||||
`cd ${classification.writeDir}`,
|
||||
`cat ${artifactName}`,
|
||||
'git log --oneline -5',
|
||||
'git status',
|
||||
'Fortsett fra siste pågående arbeid (se artefakt-fil).',
|
||||
];
|
||||
}
|
||||
|
||||
function output({ args, cwd, classification, git, artifactPath, commitMessage, errors, actionsTaken, nextSteps }) {
|
||||
const result = {
|
||||
handoff_type: classification?.type || 'unknown',
|
||||
write_dir: classification?.writeDir || cwd,
|
||||
artifact_path: artifactPath || null,
|
||||
next_steps: nextSteps || [],
|
||||
git_status: git ? { branch: git.branch, dirty: git.dirty, ahead: git.ahead, detached: git.detached } : null,
|
||||
commit_message: commitMessage || '',
|
||||
actions_taken: actionsTaken,
|
||||
errors,
|
||||
args: { dryRun: args.dryRun, noCommit: args.noCommit, noPush: args.noPush, auto: args.auto, slug: args.slug },
|
||||
};
|
||||
process.stdout.write(JSON.stringify(result, null, 2) + '\n');
|
||||
}
|
||||
|
||||
function readYesNo() {
|
||||
return new Promise((resolveP) => {
|
||||
const rl = createInterface({ input: process.stdin, output: process.stderr, terminal: false });
|
||||
rl.question('', (answer) => {
|
||||
rl.close();
|
||||
const normalized = (answer || '').trim().toLowerCase();
|
||||
resolveP(normalized === 'y' || normalized === 'yes' || normalized === 'ja' || normalized === 'j');
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
main().catch((e) => {
|
||||
try {
|
||||
main();
|
||||
} catch (e) {
|
||||
process.stderr.write(`pipeline-fatal: ${e.message}\n${e.stack}\n`);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue