feat(hooks): wave-1 guards -- approval ask, plan gate, test lock, post-edit check
Wave-1 order 4 (P7, P12, the P9 test lock, the P3 plan-approval guard). All command hooks; none runs a model. - P12: pre-bash-executor answers permissionDecision "ask" before merge into main, push, tag/publish and destructive git (holds in auto mode). post-approval-log writes exactly what the person was asked to the K2 approval log: merge/push to main as `merge`, tag/publish as `release`, with a one-hour expiry; nothing when no person was asked. - P3: pre-plan-gate runs the K3 plan gate on a Voyage plan leaving plan mode and sends a refused plan back; "not measured" asks, never passes. - P9: lib/util/test-lock.mjs (K8). pre-write-executor refuses edits to locked test files; stop-test-lock refuses "done" for the locking session (stop_hook_active guarded). - P7: post-edit-check runs the target repo's own formatter/linter per edit, only during a Voyage plan run or after opt-in (.claude/voyage-guards.json); lib/verification/step-check.mjs (K9) fails the step on findings; no tool reads "not measured", never green. - STORM cap matcher also names `Agent` (the tool's name since 2.1.63). - Mod precondition stated in README, SECURITY.md and every PreToolUse stop guard: Voyage's guards are deterministic only when no installed mod handles `tool.check`. K2, K3 and K5 are stubbed in tests until orders 2 and 3 are merged. Two independent review rounds; every finding has a regression test. Suite 1600 (1598 pass / 0 fail / 2 skipped). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
2c89a6b580
commit
2ee8137e7c
31 changed files with 3278 additions and 107 deletions
60
hooks/lib/approval-record.mjs
Normal file
60
hooks/lib/approval-record.mjs
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
// hooks/lib/approval-record.mjs
|
||||
// What the person was asked. pre-bash-executor.mjs writes one record per
|
||||
// asked call, keyed by session_id + tool_use_id (both in PreToolUse and
|
||||
// PostToolUse input); post-approval-log.mjs takes it after the call ran and
|
||||
// logs exactly that -- never a re-reading of the command afterwards, which
|
||||
// can see another branch than the one the question named. No record = the
|
||||
// person was not asked = nothing is logged.
|
||||
//
|
||||
// Records live in the OS temp dir (voyage-approvals-<uid>/), are removed when taken,
|
||||
// and anything older than a day is swept on the next write.
|
||||
|
||||
import { mkdirSync, writeFileSync, readFileSync, rmSync, readdirSync, statSync } from 'node:fs';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
|
||||
// One directory per user: another user's directory in a shared /tmp is never ours.
|
||||
const DIR = join(tmpdir(), `voyage-approvals-${process.getuid ? process.getuid() : 'u'}`);
|
||||
const MAX_AGE_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
function pathFor(sessionId, toolUseId) {
|
||||
const key = createHash('sha256').update(`${sessionId || ''}\n${toolUseId}`).digest('hex').slice(0, 32);
|
||||
return join(DIR, `${key}.json`);
|
||||
}
|
||||
|
||||
function sweep() {
|
||||
try {
|
||||
const now = Date.now();
|
||||
for (const f of readdirSync(DIR)) {
|
||||
const p = join(DIR, f);
|
||||
try { if (now - statSync(p).mtimeMs > MAX_AGE_MS) rmSync(p, { force: true }); } catch { /* raced */ }
|
||||
}
|
||||
} catch { /* no dir yet */ }
|
||||
}
|
||||
|
||||
/** @returns {boolean} written */
|
||||
export function writeApprovalRecord(sessionId, toolUseId, record) {
|
||||
if (!toolUseId) return false;
|
||||
try {
|
||||
mkdirSync(DIR, { recursive: true });
|
||||
sweep();
|
||||
writeFileSync(pathFor(sessionId, toolUseId), JSON.stringify(record));
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Read and remove the record; null when there is none. */
|
||||
export function takeApprovalRecord(sessionId, toolUseId) {
|
||||
if (!toolUseId) return null;
|
||||
const p = pathFor(sessionId, toolUseId);
|
||||
try {
|
||||
const rec = JSON.parse(readFileSync(p, 'utf8'));
|
||||
rmSync(p, { force: true });
|
||||
return rec;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
130
hooks/lib/bash-view.mjs
Normal file
130
hooks/lib/bash-view.mjs
Normal file
|
|
@ -0,0 +1,130 @@
|
|||
// hooks/lib/bash-view.mjs
|
||||
// How the Bash guards read a command. Moved out of pre-bash-executor.mjs so
|
||||
// the guard that asks before a call (pre-bash-executor.mjs) and the hook that
|
||||
// logs the approval after it (post-approval-log.mjs) read a command the same
|
||||
// way. Behavior unchanged from the inline copy.
|
||||
//
|
||||
// Bash normalization from llm-security/scanners/lib/bash-normalize.mjs (MIT,
|
||||
// same author); lib/parsers/bash-normalize.mjs keeps the test-suite copy.
|
||||
|
||||
// Strips bash evasion techniques: empty quotes, ${} expansion, backslash splitting.
|
||||
export function normalizeBashExpansion(cmd) {
|
||||
if (!cmd || typeof cmd !== 'string') return cmd || '';
|
||||
|
||||
let result = cmd
|
||||
// Strip empty single quotes: w''get -> wget
|
||||
.replace(/''/g, '')
|
||||
// Strip empty double quotes: r""m -> rm
|
||||
.replace(/""/g, '')
|
||||
// Single-char ${x} -> x (evasion: c${u}rl -> curl, assumes x=x)
|
||||
.replace(/\$\{(\w)\}/g, '$1')
|
||||
// Multi-char ${ANYTHING} -> '' (unknown value, strip entirely)
|
||||
.replace(/\$\{[^}]*\}/g, '')
|
||||
// Strip backtick subshell with empty/whitespace content
|
||||
.replace(/`\s*`/g, '');
|
||||
|
||||
// Iteratively strip backslash between word chars (c\u\r\l needs 2 passes)
|
||||
let prev;
|
||||
do {
|
||||
prev = result;
|
||||
result = result.replace(/(\w)\\(\w)/g, '$1$2');
|
||||
} while (result !== prev);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// Strip ANSI, collapse whitespace.
|
||||
export function normalizeCommand(cmd) {
|
||||
return cmd
|
||||
.replace(/\x1B\[[0-9;]*m/g, '')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Command-position view -- for rules that must distinguish a command from data
|
||||
// that merely names one. Whitespace is NOT collapsed, so newline stays a
|
||||
// separator. Quoted spans and heredoc bodies become data; the argument of a
|
||||
// shell wrapper stays a command; backslash-escaped names are seen through.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// `out` ends with the `-c` of a shell invocation -- the next quoted span is a
|
||||
// command string, not data. Optional leading `sudo` and absolute path.
|
||||
const SHELL_C_TAIL =
|
||||
/(?:^|[\s;|&])(?:sudo\s+(?:-[a-zA-Z]+\s+)*)?(?:[\w./-]*\/)?(?:ba|z|k|da|a)?sh\s+(?:-[a-zA-Z]+\s+)*-c\s*$/;
|
||||
|
||||
// Drop heredoc bodies, keeping the operator line. Their newlines are not
|
||||
// command separators, and without this every heredoc line that happens to
|
||||
// start with a matched word reads as command position. Runs before the quote
|
||||
// scan, since a body may contain quotes that would desync it.
|
||||
export function stripHeredocBodies(cmd) {
|
||||
return cmd.replace(
|
||||
/(<<-?\s*(['"]?)(\w+)\2[^\n]*\n)[\s\S]*?(?:\n[ \t]*\3[ \t]*(?=\n|$)|$)/g,
|
||||
(_match, head) => head,
|
||||
);
|
||||
}
|
||||
|
||||
// `out` ends with `eval` -- like `sh -c`, its quoted argument is run as a command.
|
||||
const EVAL_TAIL = /(?:^|[\s;|&])eval\s*$/;
|
||||
|
||||
// A quoted span that is one plain word ("push", 'git', "main").
|
||||
const PLAIN_WORD = /^[^\s'"`$;|&()<>{}\\]+$/;
|
||||
|
||||
// opts.keepWords: a quoted plain word stays that word (`git "push"` reads as
|
||||
// `git push`); without it every quoted span is data, as the BLOCK rules have
|
||||
// always read it. Quoted text with spaces is data either way.
|
||||
export function commandPositionView(cmd, opts = {}) {
|
||||
const src = stripHeredocBodies(cmd);
|
||||
let out = '';
|
||||
let i = 0;
|
||||
while (i < src.length) {
|
||||
const ch = src[i];
|
||||
if (ch === '\\' && i + 1 < src.length) {
|
||||
// An escaped character is literal: `don\'t` opens no quote, and an
|
||||
// escaped space stays inside its word (so `a\ #b` starts no comment).
|
||||
// A backslash-newline continues the line.
|
||||
const next = src[i + 1];
|
||||
out += next === '\n' ? ' ' : /\s/.test(next) ? '_' : next;
|
||||
i += 2;
|
||||
} else if (ch === '#' && (out === '' || /[\s;|&(]$/.test(out))) {
|
||||
// A comment runs to the end of the line; its apostrophes are not quotes.
|
||||
const nl = src.indexOf('\n', i);
|
||||
i = nl === -1 ? src.length : nl;
|
||||
} else if (ch === "'" || ch === '"') {
|
||||
// Inside double quotes a backslash escapes the next character (`"a \" b"`
|
||||
// is one span); inside single quotes nothing is escaped.
|
||||
let close = i + 1;
|
||||
while (close < src.length && src[close] !== ch) close += ch === '"' && src[close] === '\\' ? 2 : 1;
|
||||
if (close >= src.length) close = -1;
|
||||
if (close === -1) {
|
||||
// Unterminated quote: the shell would not run this as written, so
|
||||
// read the rest as code rather than hide it as data.
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
const inner = src.slice(i + 1, close);
|
||||
if (SHELL_C_TAIL.test(out) || EVAL_TAIL.test(out)) out += `;${inner};`;
|
||||
else out += opts.keepWords && PLAIN_WORD.test(inner) ? inner : ' ';
|
||||
i = close + 1;
|
||||
} else {
|
||||
out += ch;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
return (
|
||||
out
|
||||
// `xargs [flags] <cmd>` puts <cmd> at command position with no separator
|
||||
// in front of it. Flags taking a separate argument (`-I {}`) are not
|
||||
// parsed -- the separator lands before the argument, not the command.
|
||||
.replace(/\bxargs((?:\s+-[a-zA-Z0-9-]+)*)/g, 'xargs$1 ;')
|
||||
// `\name` runs name -- the backslash only suppresses alias expansion.
|
||||
// normalizeBashExpansion covers the between-word-chars case; this covers
|
||||
// a backslash at command position.
|
||||
.replace(/\\(\w)/g, '$1')
|
||||
);
|
||||
}
|
||||
|
||||
// The command-position view of a raw command string, as the guards build it.
|
||||
export function viewOf(command, opts = {}) {
|
||||
return commandPositionView(normalizeBashExpansion(command).replace(/\x1B\[[0-9;]*m/g, ''), opts);
|
||||
}
|
||||
39
hooks/lib/contract-cli.mjs
Normal file
39
hooks/lib/contract-cli.mjs
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
// hooks/lib/contract-cli.mjs
|
||||
// Runs a contract CLI that another wave-1 order owns (K2 approval log, K3 plan
|
||||
// gate, K5 arch rules) and maps its answer. A CLI that is not there yet, or
|
||||
// that cannot run, is "not measured" / "not logged" -- never green.
|
||||
|
||||
import { existsSync } from 'node:fs';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
export const PLUGIN_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
|
||||
|
||||
export const CONTRACTS = {
|
||||
K2: join(PLUGIN_ROOT, 'lib', 'util', 'approval-log.mjs'),
|
||||
K3: join(PLUGIN_ROOT, 'lib', 'validators', 'plan-gate.mjs'),
|
||||
K5: join(PLUGIN_ROOT, 'lib', 'verification', 'arch-rules.mjs'),
|
||||
};
|
||||
|
||||
/**
|
||||
* @returns {{ ran: boolean, code: number|null, stdout: string, stderr: string, why?: string }}
|
||||
* ran=false when the CLI file is missing or could not be started.
|
||||
*/
|
||||
export function runContract(id, args, { cwd, timeout = 60_000 } = {}) {
|
||||
const cli = CONTRACTS[id];
|
||||
if (!existsSync(cli)) return { ran: false, code: null, stdout: '', stderr: '', why: `${id} CLI not present (${cli})` };
|
||||
// No shell: every argument is passed as-is, so no text is ever spliced into a command line.
|
||||
const r = spawnSync(process.execPath, [cli, ...args], { cwd, encoding: 'utf8', timeout });
|
||||
if (r.error || r.status === null) {
|
||||
return { ran: false, code: null, stdout: r.stdout || '', stderr: r.stderr || '', why: `${id} could not run (${r.error?.message || 'signal'})` };
|
||||
}
|
||||
return { ran: true, code: r.status, stdout: r.stdout || '', stderr: r.stderr || '' };
|
||||
}
|
||||
|
||||
// A Voyage plan carries `plan_version` in its leading frontmatter block.
|
||||
export function isVoyagePlan(text) {
|
||||
if (typeof text !== 'string') return false;
|
||||
const m = text.replace(/^\uFEFF/, '').match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/);
|
||||
return !!m && /^plan_version\s*:/m.test(m[1]);
|
||||
}
|
||||
382
hooks/lib/git-approval.mjs
Normal file
382
hooks/lib/git-approval.mjs
Normal file
|
|
@ -0,0 +1,382 @@
|
|||
// hooks/lib/git-approval.mjs
|
||||
// P12 -- which shell commands need a person's approval before they run, and
|
||||
// which of those approvals go into the approval log (contract K2).
|
||||
//
|
||||
// The four classes (merge into main, push, tag/release, destructive git) are
|
||||
// Superpowers' (MIT, `8ca22db`); "a block names the way forward" is
|
||||
// agent-skills' (MIT, `9d0c60d`); guard + log is ai-native-sdlc's (MIT,
|
||||
// `11fb8d7`). Ideas only; no code is copied.
|
||||
//
|
||||
// Log kinds (operator decision 06.10): merge into main and push to main are
|
||||
// logged as `merge`; a tag, a pushed tag and a package publish as `release`.
|
||||
// A push of another branch and destructive git are asked about but not logged
|
||||
// (kind null): K2 has no kind for them, and the contract stays as it is.
|
||||
//
|
||||
// Read on the command-position view (bash-view.mjs), so a quoted commit
|
||||
// message or an `echo` that names `git push` is data, not a command. The
|
||||
// command is followed segment by segment: `cd <dir>`, `git -C <dir>` and
|
||||
// `git checkout|switch <branch>` change which repo and branch the next git
|
||||
// call acts on. Not seen: git aliases (`git p`), commands assembled in
|
||||
// variables, and `git worktree remove --force` (routine executor cleanup,
|
||||
// Hard Rule 12).
|
||||
|
||||
import { existsSync, readFileSync, statSync } from 'node:fs';
|
||||
import { dirname, join, resolve, isAbsolute } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import { viewOf } from './bash-view.mjs';
|
||||
|
||||
// How long a logged P12 approval stays valid (K2 `--expires`).
|
||||
export const APPROVAL_TTL_MS = 60 * 60 * 1000;
|
||||
|
||||
const MAIN = /^(?:main|master)$/;
|
||||
|
||||
// Wrapper programs that run the command after them, with the options of each
|
||||
// that take a separate value.
|
||||
const WRAPPERS = {
|
||||
sudo: ['-u', '-g', '-C', '-D', '-h', '-p', '-r', '-t', '-U', '-T'],
|
||||
env: ['-u', '-S', '-C', '--unset', '--chdir', '--split-string'],
|
||||
timeout: ['-s', '-k', '--signal', '--kill-after'],
|
||||
nice: ['-n', '--adjustment'],
|
||||
time: ['-f', '-o', '--format', '--output'],
|
||||
exec: ['-a'],
|
||||
xargs: ['-n', '-I', '-L', '-P', '-d', '-E', '-s', '-a', '--max-args', '--max-procs', '--delimiter', '--arg-file', '--replace'],
|
||||
stdbuf: ['-i', '-o', '-e'],
|
||||
command: [], builtin: [], nohup: [], eval: [], then: [], do: [], else: [], '!': [],
|
||||
if: [], elif: [], while: [], until: [],
|
||||
};
|
||||
|
||||
// git options that take a separate value before the subcommand.
|
||||
const GIT_OPTS_WITH_VALUE = new Set(['-C', '-c', '--git-dir', '--work-tree', '--namespace', '--exec-path', '--config-env']);
|
||||
|
||||
const base = (p) => String(p || '').split('/').pop();
|
||||
|
||||
// Redirections are not arguments: `git checkout main 2>/dev/null` names one
|
||||
// branch, not a branch and a path. An operator standing alone takes the next
|
||||
// token as its target.
|
||||
function dropRedirects(tokens) {
|
||||
const out = [];
|
||||
for (let i = 0; i < tokens.length; i += 1) {
|
||||
const t = tokens[i];
|
||||
if (/^\d*(?:>>?|<<?|>\|)$/.test(t)) { i += 1; continue; }
|
||||
if (/^\d*(?:>>?|<<?)\S/.test(t)) continue;
|
||||
out.push(t);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function segments(view) {
|
||||
return view
|
||||
// `2>&1`, `>&2`, `&>file` would otherwise split at their `&`.
|
||||
.replace(/\d*>&\d*-?/g, ' ')
|
||||
.replace(/&>>?/g, ' > ')
|
||||
.split(/\$\(|[\n;|&()`{}]/)
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean)
|
||||
.map((s) => dropRedirects(s.split(/\s+/)))
|
||||
.filter((t) => t.length);
|
||||
}
|
||||
|
||||
// Drop env assignments and wrapper words (with their options); return the
|
||||
// tokens from the real program on.
|
||||
function programTokens(tokens) {
|
||||
let i = 0;
|
||||
while (i < tokens.length) {
|
||||
const t = tokens[i];
|
||||
if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(t) || /^\d+$/.test(t)) { i += 1; continue; }
|
||||
const w = WRAPPERS[base(t)];
|
||||
if (!w) break;
|
||||
const name = base(t);
|
||||
i += 1;
|
||||
while (i < tokens.length && tokens[i].startsWith('-') && tokens[i] !== '-') {
|
||||
i += w.includes(tokens[i]) ? 2 : 1;
|
||||
}
|
||||
if (name === 'timeout' && i < tokens.length) i += 1; // the duration
|
||||
}
|
||||
return tokens.slice(i);
|
||||
}
|
||||
|
||||
// For `git [global opts] <sub> <args...>`, return { sub, args, dir }.
|
||||
function gitCall(tokens) {
|
||||
if (base(tokens[0]) !== 'git') return null;
|
||||
let i = 1;
|
||||
let dir = null;
|
||||
while (i < tokens.length && tokens[i].startsWith('-')) {
|
||||
const t = tokens[i];
|
||||
if (t === '-C' && tokens[i + 1]) dir = dir ? join(dir, tokens[i + 1]) : tokens[i + 1];
|
||||
i += GIT_OPTS_WITH_VALUE.has(t) ? 2 : 1;
|
||||
}
|
||||
if (i >= tokens.length) return null;
|
||||
return { sub: tokens[i], args: tokens.slice(i + 1), dir };
|
||||
}
|
||||
|
||||
const hasFlag = (args, ...flags) => args.some((a) => flags.includes(a));
|
||||
// A short-flag cluster such as -fdx contains `ch`.
|
||||
const shortHas = (args, ch) => args.some((a) => /^-[A-Za-z]+$/.test(a) && a.includes(ch));
|
||||
const positional = (args) => args.filter((a) => !a.startsWith('-'));
|
||||
// Positionals, skipping the values of the options that take one.
|
||||
function positionalSkipping(args, valued) {
|
||||
const out = [];
|
||||
for (let i = 0; i < args.length; i += 1) {
|
||||
if (valued.includes(args[i])) { i += 1; continue; }
|
||||
if (!args[i].startsWith('-')) out.push(args[i]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
const PUSH_VALUED = ['-o', '--push-option', '--repo', '--receive-pack', '--exec'];
|
||||
|
||||
const WAY = {
|
||||
merge: 'approve to merge now; deny and Claude stops here. A merge into main is recorded in the approval log.',
|
||||
push: 'approve to push now; deny and Claude stops here. A push to main is recorded in the approval log.',
|
||||
release: 'approve to tag or publish now; deny and Claude stops here. The release is recorded in the approval log.',
|
||||
destructive: 'approve only if losing that work is intended; deny and Claude stops here. Nothing is logged.',
|
||||
};
|
||||
|
||||
const destructive = (name) => ({ cls: 'destructive', name, kind: null });
|
||||
|
||||
function classifyPush(args, ctx) {
|
||||
if (hasFlag(args, '-n', '--dry-run') || shortHas(args, 'n')) return [];
|
||||
const tags = hasFlag(args, '--tags', '--follow-tags');
|
||||
const del = hasFlag(args, '--delete', '-d');
|
||||
const force = hasFlag(args, '--force', '--force-with-lease', '--mirror') ||
|
||||
args.some((a) => a.startsWith('--force-with-lease=') || a.startsWith('+')) || shortHas(args, 'f');
|
||||
const refspecs = positionalSkipping(args, PUSH_VALUED).slice(1); // the first positional is the remote
|
||||
const out = [];
|
||||
let toMain = false;
|
||||
let other = false;
|
||||
let tagPush = tags;
|
||||
for (const r of refspecs) {
|
||||
if (del || r.startsWith(':')) { out.push(destructive('delete a remote branch or tag')); continue; }
|
||||
const dst = (r.includes(':') ? r.split(':').pop() : r).replace(/^\+/, '');
|
||||
const name = dst.replace(/^refs\/heads\//, '');
|
||||
if (dst.startsWith('refs/tags/') || (!dst.startsWith('refs/') && tagExists(ctx.cwd, name) && !MAIN.test(name))) tagPush = true;
|
||||
else if (MAIN.test(name) || (name === 'HEAD' && MAIN.test(ctx.branch || ''))) toMain = true;
|
||||
else other = true;
|
||||
}
|
||||
if (refspecs.length === 0 && !tags) {
|
||||
if (MAIN.test(ctx.branch || '')) toMain = true;
|
||||
else other = true;
|
||||
}
|
||||
if (toMain) out.push({ cls: 'push', name: force ? 'force push to main' : 'push to main', kind: 'merge' });
|
||||
if (other) out.push({ cls: 'push', name: force ? 'force push' : 'push', kind: null });
|
||||
if (tagPush) out.push({ cls: 'release', name: 'push of tags', kind: 'release' });
|
||||
return out;
|
||||
}
|
||||
|
||||
function classifyGit(call, ctx) {
|
||||
const { sub, args } = call;
|
||||
switch (sub) {
|
||||
case 'push':
|
||||
return classifyPush(args, ctx);
|
||||
case 'merge':
|
||||
if (hasFlag(args, '--abort', '--continue', '--quit')) return [];
|
||||
return MAIN.test(ctx.branch || '') ? [{ cls: 'merge', name: 'merge into main', kind: 'merge' }] : [];
|
||||
case 'tag': {
|
||||
if (hasFlag(args, '-l', '--list', '-v', '--verify') || shortHas(args, 'l')) return [];
|
||||
if (hasFlag(args, '-d', '--delete')) return [{ cls: 'release', name: 'delete a tag', kind: null }];
|
||||
// Options that take a value: their value is not a tag name.
|
||||
const valued = new Set(['-m', '-F', '-u', '--message', '--file', '--local-user', '--sort', '--contains', '--no-contains', '--points-at', '--merged', '--no-merged', '--format', '--cleanup']);
|
||||
const names = [];
|
||||
for (let i = 0; i < args.length; i += 1) {
|
||||
if (valued.has(args[i])) { i += 1; continue; }
|
||||
if (!args[i].startsWith('-')) names.push(args[i]);
|
||||
}
|
||||
return names.length > 0 ? [{ cls: 'release', name: 'create a tag', kind: 'release' }] : [];
|
||||
}
|
||||
case 'reset':
|
||||
return hasFlag(args, '--hard') ? [destructive('hard reset')] : [];
|
||||
case 'clean':
|
||||
if (hasFlag(args, '-n', '--dry-run') || shortHas(args, 'n')) return [];
|
||||
return hasFlag(args, '--force') || shortHas(args, 'f') ? [destructive('clean with force')] : [];
|
||||
case 'branch': {
|
||||
const del = hasFlag(args, '-d', '--delete') || shortHas(args, 'd');
|
||||
const force = hasFlag(args, '-f', '--force') || shortHas(args, 'f');
|
||||
if (hasFlag(args, '-D') || shortHas(args, 'D') || (del && force)) return [destructive('force-delete a branch')];
|
||||
if (hasFlag(args, '-M') || shortHas(args, 'M')) return [destructive('force-rename a branch')];
|
||||
return [];
|
||||
}
|
||||
case 'stash':
|
||||
return args[0] === 'drop' || args[0] === 'clear' ? [destructive(`stash ${args[0]}`)] : [];
|
||||
case 'checkout': {
|
||||
if (hasFlag(args, '-b', '-B', '--orphan')) return [];
|
||||
const pos = positional(args);
|
||||
const discard = hasFlag(args, '--', '-f', '--force') || pos.includes('.') || pos.length >= 2;
|
||||
return discard ? [destructive('discard working-tree changes')] : [];
|
||||
}
|
||||
case 'switch':
|
||||
return hasFlag(args, '-f', '--force', '--discard-changes') ? [destructive('discard working-tree changes')] : [];
|
||||
case 'restore': {
|
||||
const staged = hasFlag(args, '--staged', '-S');
|
||||
const worktree = hasFlag(args, '--worktree', '-W');
|
||||
return !staged || worktree ? [destructive('discard working-tree changes')] : [];
|
||||
}
|
||||
case 'filter-branch':
|
||||
case 'filter-repo':
|
||||
return [destructive('history rewrite')];
|
||||
case 'update-ref':
|
||||
return hasFlag(args, '-d') ? [destructive('delete a ref')] : [];
|
||||
case 'reflog':
|
||||
return args[0] === 'expire' || args[0] === 'delete' ? [destructive('reflog expiry')] : [];
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
// The branch a checkout/switch leaves the repo on, or undefined if it does not move.
|
||||
function branchAfter(call) {
|
||||
const { sub, args } = call;
|
||||
if (sub !== 'checkout' && sub !== 'switch') return undefined;
|
||||
if (hasFlag(args, '--detach') || (sub === 'switch' && hasFlag(args, '-d'))) return null; // detached: no branch
|
||||
const create = sub === 'checkout' ? ['-b', '-B', '--orphan'] : ['-c', '-C', '--create', '--force-create', '--orphan'];
|
||||
for (let i = 0; i < args.length; i += 1) if (create.includes(args[i]) && args[i + 1]) return args[i + 1];
|
||||
if (hasFlag(args, '--')) return undefined;
|
||||
const pos = positional(args);
|
||||
return pos.length === 1 && pos[0] !== '.' ? pos[0] : undefined;
|
||||
}
|
||||
|
||||
function classifyPublish(tokens) {
|
||||
let t = tokens;
|
||||
if (['npx', 'pnpx', 'bunx'].includes(base(t[0]))) t = t.slice(1);
|
||||
const prog = base(t[0]);
|
||||
if (['npm', 'pnpm', 'yarn', 'bun', 'cargo'].includes(prog)) {
|
||||
const rest = t.slice(1);
|
||||
// The subcommand is the first positional (option values skipped);
|
||||
// `yarn npm publish` is Yarn Berry's form.
|
||||
const pos = positionalSkipping(rest, ['--tag', '--registry', '--access', '--otp', '-w', '--workspace',
|
||||
'--filter', '--cwd', '-C', '--prefix', '--manifest-path', '--package', '-p', '--token']);
|
||||
const sub = prog === 'yarn' && pos[0] === 'npm' ? pos[1] : pos[0];
|
||||
if (sub === 'publish' && !hasFlag(rest, '--dry-run', '-n')) {
|
||||
return [{ cls: 'release', name: `${prog} publish`, kind: 'release' }];
|
||||
}
|
||||
}
|
||||
if (prog === 'gh' && t[1] === 'release' && t[2] === 'create') {
|
||||
return [{ cls: 'release', name: 'gh release create', kind: 'release' }];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
const expandHome = (p) => (p === '~' ? homedir() : p.startsWith('~/') ? join(homedir(), p.slice(2)) : p);
|
||||
|
||||
/**
|
||||
* Which approvals a command needs.
|
||||
* @param {string} command raw Bash command
|
||||
* @param {{ cwd?: string, branch?: string|null }} ctx where the command runs; `branch`
|
||||
* overrides the branch read from `cwd` for the first segment (tests).
|
||||
* @returns {Array<{cls, name, kind: 'merge'|'release'|null, way, subject}>}
|
||||
* `subject` is the top of the repo the matched call acts on.
|
||||
*/
|
||||
export function classifyGitApproval(command, ctx = {}) {
|
||||
if (!command || typeof command !== 'string') return [];
|
||||
let cwd = resolve(ctx.cwd || process.cwd());
|
||||
let branch = ctx.branch !== undefined ? ctx.branch : currentBranch(cwd);
|
||||
const out = [];
|
||||
for (const seg of segments(viewOf(command, { keepWords: true }))) {
|
||||
const tokens = programTokens(seg);
|
||||
if (base(tokens[0]) === 'cd') {
|
||||
const to = tokens[1] && tokens[1] !== '-' ? tokens[1] : null;
|
||||
if (to) { cwd = resolve(cwd, expandHome(to)); branch = currentBranch(cwd); }
|
||||
continue;
|
||||
}
|
||||
const call = gitCall(tokens);
|
||||
if (call) {
|
||||
const callCwd = call.dir ? resolve(cwd, expandHome(call.dir)) : cwd;
|
||||
const callBranch = call.dir ? currentBranch(callCwd) : branch;
|
||||
const subject = repoRootOf(callCwd);
|
||||
for (const m of classifyGit(call, { branch: callBranch, cwd: callCwd })) out.push({ ...m, subject });
|
||||
const next = branchAfter(call);
|
||||
if (next !== undefined && !call.dir) branch = next;
|
||||
continue;
|
||||
}
|
||||
for (const m of classifyPublish(tokens)) out.push({ ...m, subject: repoRootOf(cwd) });
|
||||
}
|
||||
return out.map((m) => ({ ...m, way: WAY[m.cls] }));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// The repository a command runs in -- read from the filesystem, no git spawn.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function findDotGit(start) {
|
||||
let dir = resolve(start);
|
||||
while (!existsSync(dir)) {
|
||||
const up = dirname(dir);
|
||||
if (up === dir) return null;
|
||||
dir = up;
|
||||
}
|
||||
for (;;) {
|
||||
const p = join(dir, '.git');
|
||||
if (existsSync(p)) return { root: dir, dotGit: p };
|
||||
const up = dirname(dir);
|
||||
if (up === dir) return null;
|
||||
dir = up;
|
||||
}
|
||||
}
|
||||
|
||||
function gitDirOf(found) {
|
||||
try {
|
||||
if (statSync(found.dotGit).isDirectory()) return found.dotGit;
|
||||
const m = readFileSync(found.dotGit, 'utf8').match(/^gitdir:\s*(.+?)\s*$/m);
|
||||
if (!m) return null;
|
||||
return isAbsolute(m[1]) ? m[1] : resolve(found.root, m[1]);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// A worktree's git dir names the shared one in `commondir`; refs live there.
|
||||
function commonDirOf(gitDir) {
|
||||
try {
|
||||
const c = readFileSync(join(gitDir, 'commondir'), 'utf8').trim();
|
||||
return isAbsolute(c) ? c : resolve(gitDir, c);
|
||||
} catch {
|
||||
return gitDir;
|
||||
}
|
||||
}
|
||||
|
||||
// The checked-out branch of the repo at `cwd`, or null (detached, no repo).
|
||||
export function currentBranch(cwd) {
|
||||
try {
|
||||
const found = findDotGit(cwd || process.cwd());
|
||||
if (!found) return null;
|
||||
const gitDir = gitDirOf(found);
|
||||
if (!gitDir) return null;
|
||||
const head = readFileSync(join(gitDir, 'HEAD'), 'utf8').trim();
|
||||
const m = head.match(/^ref:\s*refs\/heads\/(.+)$/);
|
||||
return m ? m[1] : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Does tag `name` exist in the repo at `cwd` (loose or packed)?
|
||||
export function tagExists(cwd, name) {
|
||||
if (!name || name.includes('..')) return false;
|
||||
try {
|
||||
const found = findDotGit(cwd || process.cwd());
|
||||
if (!found) return false;
|
||||
const gitDir = gitDirOf(found);
|
||||
if (!gitDir) return false;
|
||||
const common = commonDirOf(gitDir);
|
||||
if (existsSync(join(common, 'refs', 'tags', name))) return true;
|
||||
const packed = join(common, 'packed-refs');
|
||||
return existsSync(packed) && readFileSync(packed, 'utf8').split('\n').some((l) => l.endsWith(` refs/tags/${name}`));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// The top of the repo at `cwd` (the approval's subject), or cwd itself.
|
||||
export function repoRootOf(cwd) {
|
||||
const found = findDotGit(cwd || process.cwd());
|
||||
return found ? found.root : resolve(cwd || process.cwd());
|
||||
}
|
||||
|
||||
// The prompt text for an ask. Names Voyage, the classes, and the way forward.
|
||||
export function askReason(matches) {
|
||||
const names = [...new Set(matches.map((m) => m.name))].join('; ');
|
||||
const ways = [...new Set(matches.map((m) => m.way))].join(' ');
|
||||
return (
|
||||
`Voyage asks before this command (P12 approval guard): ${names}. ` +
|
||||
'It changes something outside this working copy or throws work away, so a person decides. ' +
|
||||
`Way forward: ${ways}`
|
||||
);
|
||||
}
|
||||
76
hooks/lib/post-edit.mjs
Normal file
76
hooks/lib/post-edit.mjs
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
// hooks/lib/post-edit.mjs
|
||||
// Shared by the post-edit guard (P7, hooks/scripts/post-edit-check.mjs) and
|
||||
// the step check (K9, lib/verification/step-check.mjs): when the guard is on,
|
||||
// and where its log lives.
|
||||
//
|
||||
// On (operator decision 06.10): while Voyage executes a plan in the repo -- a
|
||||
// `.claude/projects/*/progress.json` (or legacy `.trekexecute-progress-*.json`)
|
||||
// with status "in_progress" -- or when the repo has switched it on with
|
||||
// `.claude/voyage-guards.json` = { "post_edit_check": true }. Off everywhere
|
||||
// else, because the guard is wired for every session in every repo.
|
||||
|
||||
import { existsSync, readFileSync, readdirSync, mkdirSync, appendFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
|
||||
export const OPT_IN_FILE = join('.claude', 'voyage-guards.json');
|
||||
|
||||
function readJson(p) {
|
||||
try { return JSON.parse(readFileSync(p, 'utf8')); } catch { return null; }
|
||||
}
|
||||
|
||||
function inProgress(p) {
|
||||
return readJson(p)?.status === 'in_progress';
|
||||
}
|
||||
|
||||
export function executingPlan(root) {
|
||||
const projects = join(root, '.claude', 'projects');
|
||||
try {
|
||||
for (const d of readdirSync(projects, { withFileTypes: true })) {
|
||||
if (d.isDirectory() && inProgress(join(projects, d.name, 'progress.json'))) return true;
|
||||
}
|
||||
} catch { /* no projects dir */ }
|
||||
try {
|
||||
for (const f of readdirSync(root)) {
|
||||
if (/^\.trekexecute-progress-.+\.json$/.test(f) && inProgress(join(root, f))) return true;
|
||||
}
|
||||
} catch { /* unreadable root */ }
|
||||
return false;
|
||||
}
|
||||
|
||||
export function optedIn(root) {
|
||||
const p = join(root, OPT_IN_FILE);
|
||||
return existsSync(p) && readJson(p)?.post_edit_check === true;
|
||||
}
|
||||
|
||||
/** @returns {'plan'|'opt-in'|null} why the guard is on, or null when it is off */
|
||||
export function postEditActive(root) {
|
||||
if (optedIn(root)) return 'opt-in';
|
||||
if (executingPlan(root)) return 'plan';
|
||||
return null;
|
||||
}
|
||||
|
||||
export function postEditLogPath(gitDir) {
|
||||
return join(gitDir, 'voyage', 'post-edit.jsonl');
|
||||
}
|
||||
|
||||
export function appendPostEditLog(gitDir, record) {
|
||||
const p = postEditLogPath(gitDir);
|
||||
mkdirSync(join(gitDir, 'voyage'), { recursive: true });
|
||||
appendFileSync(p, JSON.stringify(record) + '\n');
|
||||
return p;
|
||||
}
|
||||
|
||||
// The latest record per file (repo-relative path).
|
||||
export function latestPostEditRecords(gitDir) {
|
||||
const p = postEditLogPath(gitDir);
|
||||
const out = new Map();
|
||||
if (!existsSync(p)) return out;
|
||||
for (const line of readFileSync(p, 'utf8').split('\n')) {
|
||||
if (!line.trim()) continue;
|
||||
try {
|
||||
const r = JSON.parse(line);
|
||||
if (r && typeof r.file === 'string') out.set(r.file, r);
|
||||
} catch { /* a torn line is skipped, never read as clean */ }
|
||||
}
|
||||
return out;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue