From 2b55f2a12b50ecf421a45ba748d1df2d75357d08 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Zander?= <96420681+renezander030@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:55:11 +0000 Subject: [PATCH 01/13] Fix streaming decision-log summaries and malformed records --- CHANGELOG.md | 4 ++ README.md | 5 +- package-lock.json | 4 +- package.json | 2 +- src/cli.ts | 7 ++- src/log.ts | 118 ++++++++++++++++++++++++++++++++++------------ test/log.test.ts | 96 +++++++++++++++++++++++++++++++++++++ 7 files changed, 198 insertions(+), 38 deletions(-) create mode 100644 test/log.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 75472e4..41b2604 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,11 @@ ## Unreleased +## 0.16.1 - 2026-11-23 + ### Fixed +- `skillgate log` streams decision logs, skips invalid record shapes without losing + valid neighboring records, and counts event names such as `__proto__` correctly. - The `commit-messages` gate drops the `g` and `y` flags, as `absent` and `no-new` do, so a matching subject no longer fails because the previous match moved `lastIndex`. diff --git a/README.md b/README.md index 22d2db6..ebc0a5f 100644 --- a/README.md +++ b/README.md @@ -365,7 +365,10 @@ editing the snapshot, the expected output or the CI workflow instead of the code **See what the gate did.** Set `SKILLGATE_LOG=.git/skillgate/decisions.jsonl` (or pass `--log`) and every `gate` and `check` verdict is appended as one JSON line. `skillgate log` summarizes it: how often each gate blocked and which commands it -stopped. `skillgate explain --commands ` replays a command list, or the log +stopped. It streams the file and counts malformed JSON or invalid record shapes +as skipped lines, preserving valid neighboring decisions. Memory grows with the +longest line and the number of distinct events, gates and actions. +`skillgate explain --commands ` replays a command list, or the log itself, against the current `finishLine` before you change it. **Phases, checked live.** A `phase` gate orders work (plan → build → review) and diff --git a/package-lock.json b/package-lock.json index 3ae7914..2bda011 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@reneza/skillgate", - "version": "0.16.0", + "version": "0.16.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@reneza/skillgate", - "version": "0.16.0", + "version": "0.16.1", "license": "MIT", "dependencies": { "@mattrglobal/pairing-crypto": "^0.4.2", diff --git a/package.json b/package.json index 8f00617..e6d64c8 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@reneza/skillgate", - "version": "0.16.0", + "version": "0.16.1", "publishConfig": { "access": "public" }, diff --git a/src/cli.ts b/src/cli.ts index 2094aae..000a085 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -6,7 +6,7 @@ import { spawnSync } from "node:child_process"; import { fileURLToPath } from "node:url"; import { findSpecPath, loadSpec, parseSpec, specRoot, workspaceRoot, DEFAULT_SPEC_PATHS, DEFAULT_PHASE_FILE, DEFAULT_RUN_TIMEOUT_MS, type Spec, type PhaseGate } from "./spec.js"; import { runGates, decideCommand, decideTool, currentPhase, evaluatePhase, gatesForCommand, type GateResult, type RunResult } from "./core.js"; -import { appendLog, logPath, logPathProblem, summarizeLog, toFailed, type LogRecord } from "./log.js"; +import { appendLog, logPath, logPathProblem, summarizeLogFile, toFailed, type LogRecord } from "./log.js"; import { checkDrift, driftDiffs, DEFAULT_THRESHOLD, setCanonical } from "./drift.js"; import { runSync } from "./link.js"; import { runScaffold, templateHelp } from "./scaffold.js"; @@ -734,13 +734,12 @@ if (cmd === "explain") { if (cmd === "log") { const file = positionalPath() ?? logPath(undefined, cwd); if (!file) die(2, "usage: skillgate log (or set SKILLGATE_LOG)"); - let text: string; + let summary; try { - text = fs.readFileSync(file, "utf8"); + summary = await summarizeLogFile(file); } catch (error: any) { die(2, `cannot read ${file}: ${error.message}`); } - const summary = summarizeLog(text); if (json) { console.log(JSON.stringify(summary, null, 2)); process.exit(0); diff --git a/src/log.ts b/src/log.ts index 5f785e8..18784d1 100644 --- a/src/log.ts +++ b/src/log.ts @@ -73,39 +73,97 @@ export interface LogSummary { errors: number; } -/** Summarize a decision log. Malformed lines are counted, never fatal. */ -export function summarizeLog(text: string, top = 10): LogSummary { +// Validate only fields consumed by the summary. Older logs may omit workspace, +// via, or failed; unknown metadata remains forward-compatible. +type SummaryRecord = Pick & { + failed?: { id: string }[] | null; +}; + +function isSummaryRecord(value: unknown): value is SummaryRecord { + if (!value || typeof value !== "object" || Array.isArray(value)) return false; + const r = value as Record; + return (r.decision === "allow" || r.decision === "block") + && typeof r.ts === "string" && typeof r.event === "string" && typeof r.reason === "string" + && (r.command === undefined || typeof r.command === "string") + && (r.tool === undefined || typeof r.tool === "string") + && (r.failed == null || (Array.isArray(r.failed) && r.failed.every( + (f: unknown) => !!f && typeof f === "object" && !Array.isArray(f) && typeof (f as { id?: unknown }).id === "string", + ))); +} + +/** Shared aggregation for in-memory and streamed logs; invalid records are atomic. */ +function logSummary(top: number) { const summary: LogSummary = { records: 0, malformed: 0, allowed: 0, blocked: 0, byEvent: {}, blockingGates: [], blockedActions: [], errors: 0 }; + const events = new Map(); const gates = new Map(); const actions = new Map(); - for (const line of text.split(/\r?\n/)) { - if (!line.trim()) continue; - let record: LogRecord; - try { - record = JSON.parse(line); - if (!record || (record.decision !== "allow" && record.decision !== "block")) throw new Error("not a decision"); - } catch { - summary.malformed++; - continue; - } - summary.records++; - if (!summary.first || record.ts < summary.first) summary.first = record.ts; - if (!summary.last || record.ts > summary.last) summary.last = record.ts; - const event = (summary.byEvent[record.event] ??= { allowed: 0, blocked: 0 }); - if (record.decision === "allow") { - summary.allowed++; - event.allowed++; - continue; + return { + add(line: string): void { + if (!line.trim()) return; + let record: unknown; + try { + record = JSON.parse(line); + } catch { + summary.malformed++; + return; + } + if (!isSummaryRecord(record)) { + summary.malformed++; + return; + } + summary.records++; + if (!summary.first || record.ts < summary.first) summary.first = record.ts; + if (!summary.last || record.ts > summary.last) summary.last = record.ts; + let event = events.get(record.event); + if (!event) events.set(record.event, event = { allowed: 0, blocked: 0 }); + if (record.decision === "allow") { + summary.allowed++; + event.allowed++; + return; + } + summary.blocked++; + event.blocked++; + if (!record.failed?.length && /^error: /.test(record.reason)) summary.errors++; + for (const f of record.failed ?? []) gates.set(f.id, (gates.get(f.id) ?? 0) + 1); + const action = record.tool ?? record.command ?? record.event; + if (action) actions.set(action, (actions.get(action) ?? 0) + 1); + }, + finish(): LogSummary { + const ranked = (m: Map) => [...m].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, top); + summary.byEvent = Object.fromEntries(events); + summary.blockingGates = ranked(gates).map(([id, count]) => ({ id, count })); + summary.blockedActions = ranked(actions).map(([action, count]) => ({ action, count })); + return summary; + }, + }; +} + +/** Summarize a decision log. Malformed lines are counted, never fatal. */ +export function summarizeLog(text: string, top = 10): LogSummary { + const summary = logSummary(top); + for (const line of text.split(/\r?\n/)) summary.add(line); + return summary.finish(); +} + +/** Read incrementally. Memory grows with the longest line and distinct groups. */ +export async function summarizeLogFile(file: string, top = 10): Promise { + const summary = logSummary(top); + const input = fs.createReadStream(file, { encoding: "utf8" }); + let pending = ""; + try { + for await (const chunk of input) { + pending += chunk; + let start = 0; + let end: number; + while ((end = pending.indexOf("\n", start)) !== -1) { + summary.add(pending.slice(start, end)); + start = end + 1; + } + pending = pending.slice(start); } - summary.blocked++; - event.blocked++; - if (!record.failed?.length && /^error: /.test(record.reason ?? "")) summary.errors++; - for (const f of record.failed ?? []) gates.set(f.id, (gates.get(f.id) ?? 0) + 1); - const action = record.tool ?? record.command ?? record.event; - if (action) actions.set(action, (actions.get(action) ?? 0) + 1); + summary.add(pending); + return summary.finish(); + } finally { + input.destroy(); } - const ranked = (m: Map) => [...m].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, top); - summary.blockingGates = ranked(gates).map(([id, count]) => ({ id, count })); - summary.blockedActions = ranked(actions).map(([action, count]) => ({ action, count })); - return summary; } diff --git a/test/log.test.ts b/test/log.test.ts new file mode 100644 index 0000000..08dcb44 --- /dev/null +++ b/test/log.test.ts @@ -0,0 +1,96 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { spawnSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import { summarizeLog, summarizeLogFile } from "../src/log.js"; + +const cli = fileURLToPath(new URL("../src/cli.js", import.meta.url)); +const record = { ts: "2026-01-01", event: "command", decision: "block", reason: "failed", failed: [{ id: "c1" }], command: "git push" }; +const json = (value: unknown) => JSON.stringify(value); + +test("log: invalid shapes count once and preserve valid neighboring decisions", () => { + const invalid = [null, [], 1, "text", {}, { ...record, decision: "maybe" }, + { ...record, ts: 1 }, { ...record, event: {} }, { ...record, reason: [] }, + { ...record, command: {} }, { ...record, tool: 1 }, { ...record, failed: {} }, + { ...record, failed: [null] }, { ...record, failed: [{ id: 1 }] }, + { ...record, failed: [[], { id: "c1" }] }]; + const s = summarizeLog([json(record), ...invalid.map(json), "broken", json({ ...record, decision: "allow" })].join("\n")); + assert.equal(s.records, 2); + assert.equal(s.malformed, invalid.length + 1); + assert.equal(s.blocked, 1); + assert.equal(s.allowed, 1); + assert.deepEqual(s.blockingGates, [{ id: "c1", count: 1 }]); + assert.deepEqual(s.byEvent, { command: { allowed: 1, blocked: 1 } }); +}); + +test("log: legacy optional metadata and unknown fields remain readable", () => { + const { failed, ...older } = record; + const s = summarizeLog([older, { ...older, failed: null }, { ...older, failed: [], reason: "error: unavailable", future: {} }].map(json).join("\n")); + assert.equal(s.records, 3); + assert.equal(s.malformed, 0); + assert.equal(s.errors, 1); +}); + +test("log: reserved event names survive JSON output without inherited counters", () => { + const names = ["__proto__", "constructor", "toString"]; + const s = JSON.parse(json(summarizeLog(names.flatMap((event) => [ + { ...record, event }, { ...record, event, decision: "allow" }, + ]).map(json).join("\n")))); + assert.deepEqual(Object.keys(s.byEvent), names); + for (const event of names) assert.deepEqual(s.byEvent[event], { blocked: 1, allowed: 1 }); + assert.equal(Object.hasOwn(Object.prototype, "blocked"), false); +}); + +test("log: stream matches text aggregation across CRLF, UTF-8 and final unterminated line", async (t) => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "skillgate-log-")); + t.after(() => fs.rmSync(dir, { recursive: true, force: true })); + const file = path.join(dir, "decisions.jsonl"); + const text = [" ", json({ ...record, command: "ä".repeat(40000) }), json({ ...record, ts: "2026-01-03", tool: "publish" }), + "broken", json({ ...record, ts: "2025-12-30", failed: [{ id: "c2" }], command: "git commit" })].join("\r\n"); + fs.writeFileSync(file, text); + const s = await summarizeLogFile(file, 1); + assert.deepEqual(s, summarizeLog(text, 1)); + assert.equal(s.first, "2025-12-30"); + assert.equal(s.last, "2026-01-03"); + assert.deepEqual(s.blockingGates, [{ id: "c1", count: 2 }]); + assert.equal(s.blockedActions.length, 1); + const bareCr = [json(record), json(record)].join("\r"); + fs.writeFileSync(file, bareCr); + assert.deepEqual(await summarizeLogFile(file), summarizeLog(bareCr)); + fs.writeFileSync(file, ""); + assert.deepEqual(await summarizeLogFile(file), summarizeLog("")); +}); + +test("log: unavailable files reject and CLI reports a read error with exit 2", async (t) => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "skillgate-log-")); + t.after(() => fs.rmSync(dir, { recursive: true, force: true })); + const file = path.join(dir, "missing.jsonl"); + await assert.rejects(summarizeLogFile(file), { code: "ENOENT" }); + const out = spawnSync(process.execPath, [cli, "log", file, "--json"], { encoding: "utf8" }); + assert.equal(out.status, 2, out.stderr); + assert.match(out.stderr, /cannot read/); + assert.equal(out.stdout, ""); +}); + +test("log: CLI summarizes a file larger than its heap budget", { timeout: 30000 }, (t) => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "skillgate-log-")); + t.after(() => fs.rmSync(dir, { recursive: true, force: true })); + const file = path.join(dir, "large.jsonl"); + const line = json({ ...record, metadata: "x".repeat(4096) }) + "\n"; + const fd = fs.openSync(file, "w"); + try { + const chunk = line.repeat(100); + for (let i = 0; i < 200; i++) fs.writeSync(fd, chunk); + fs.writeSync(fd, "not json\n"); + } finally { fs.closeSync(fd); } + assert.ok(fs.statSync(file).size > 64 * 1024 * 1024); + const out = spawnSync(process.execPath, ["--max-old-space-size=64", cli, "log", file, "--json"], { encoding: "utf8", timeout: 25000 }); + assert.equal(out.status, 0, out.stderr); + const s = JSON.parse(out.stdout); + assert.equal(s.records, 20000); + assert.equal(s.malformed, 1); + assert.deepEqual(s.blockingGates, [{ id: "c1", count: 20000 }]); +}); From 93637d312a0b7b2a4eed5f88985fb2ec5f855595 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Zander?= <96420681+renezander030@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:55:12 +0000 Subject: [PATCH 02/13] Skip truncated decision-log records in explain --commands A line that opens like a JSON object but does not parse is a truncated or corrupt decision-log record. explain --commands now counts it as skipped instead of replaying its JSON text as a shell command; --json reports the count as skipped. Shell brace groups such as { git push; } still replay. --- CHANGELOG.md | 3 +++ README.md | 3 ++- src/cli.ts | 21 ++++++++++++++++----- test/release-014.test.ts | 28 ++++++++++++++++++++++++++++ 4 files changed, 49 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 41b2604..f8f3b17 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,9 @@ ### Fixed - `skillgate log` streams decision logs, skips invalid record shapes without losing valid neighboring records, and counts event names such as `__proto__` correctly. +- `skillgate explain --commands ` skips a truncated or corrupt decision-log record + instead of replaying its JSON text as a command, and reports how many lines it skipped + (`skipped` in `--json`). - The `commit-messages` gate drops the `g` and `y` flags, as `absent` and `no-new` do, so a matching subject no longer fails because the previous match moved `lastIndex`. diff --git a/README.md b/README.md index ebc0a5f..0b97671 100644 --- a/README.md +++ b/README.md @@ -369,7 +369,8 @@ stopped. It streams the file and counts malformed JSON or invalid record shapes as skipped lines, preserving valid neighboring decisions. Memory grows with the longest line and the number of distinct events, gates and actions. `skillgate explain --commands ` replays a command list, or the log -itself, against the current `finishLine` before you change it. +itself, against the current `finishLine` before you change it; truncated log +records are skipped and counted, never replayed as commands. **Phases, checked live.** A `phase` gate orders work (plan → build → review) and requires each phase's gates, plus every earlier phase's, to pass at the moment diff --git a/src/cli.ts b/src/cli.ts index 000a085..005f324 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -665,10 +665,16 @@ if (cmd === "doctor") { process.exit(checks.every((check) => check.ok) ? 0 : 1); } -/** Commands from a corpus: one per line, or decision-log JSON lines (their `command`). */ -function readCorpus(source: string): string[] { +/** + * Commands from a corpus: one per line, or decision-log JSON lines (their `command`). + * A line that opens like a JSON object (`{"`) but does not parse is a truncated or + * corrupt log record: it is counted in `skipped`, never replayed as a command. A + * shell brace group such as `{ git push; }` is still a command. + */ +function readCorpus(source: string): { commands: string[]; skipped: number } { const text = source === "-" ? fs.readFileSync(0, "utf8") : fs.readFileSync(path.resolve(cwd, source), "utf8"); const commands: string[] = []; + let skipped = 0; for (const line of text.split(/\r?\n/)) { const trimmed = line.trim(); if (!trimmed || trimmed.startsWith("#")) continue; @@ -678,12 +684,16 @@ function readCorpus(source: string): string[] { if (typeof record?.command === "string" && record.command.trim() && !record.tool) commands.push(record.command.trim()); continue; } catch { + if (/^\{\s*"/.test(trimmed)) { + skipped++; + continue; + } /* a command that starts with "{" */ } } commands.push(trimmed); } - return commands; + return { commands, skipped }; } if (cmd === "explain") { @@ -695,7 +705,7 @@ if (cmd === "explain") { try { const spec = loadSpec(specPath); if (corpus) { - const commands = readCorpus(corpus); + const { commands, skipped } = readCorpus(corpus); const rows = commands.map((cmdText) => { const analysis = analyzeCommand(cmdText, spec.finishLine ?? []); return { command: cmdText, matched: analysis.matched, patterns: analysis.patterns, gates: analysis.matched ? gatesForCommand(spec, cmdText) : [] }; @@ -704,13 +714,14 @@ if (cmd === "explain") { const byPattern = new Map(); for (const row of gated) for (const p of row.patterns) byPattern.set(p, (byPattern.get(p) ?? 0) + 1); if (json) { - console.log(JSON.stringify({ finishLine: spec.finishLine ?? [], total: rows.length, gated: gated.length, byPattern: Object.fromEntries(byPattern), commands: rows }, null, 2)); + console.log(JSON.stringify({ finishLine: spec.finishLine ?? [], total: rows.length, gated: gated.length, skipped, byPattern: Object.fromEntries(byPattern), commands: rows }, null, 2)); } else { for (const row of rows) { console.log(`${row.matched ? c(C.red, "MATCH ") : c(C.dim, "no match")} ${row.command}${row.matched ? c(C.dim, ` → ${row.gates.join(", ") || "no gates"}`) : ""}`); } console.log(""); console.log(`${gated.length} of ${rows.length} commands cross the finish line` + (byPattern.size ? c(C.dim, ` (${[...byPattern].map(([p, n]) => `${p}: ${n}`).join(", ")})`) : "")); + if (skipped) console.log(c(C.dim, `${skipped} malformed log line${skipped === 1 ? "" : "s"} skipped`)); } process.exit(0); } diff --git a/test/release-014.test.ts b/test/release-014.test.ts index ee21a78..de8d9a4 100644 --- a/test/release-014.test.ts +++ b/test/release-014.test.ts @@ -405,6 +405,34 @@ gates: assert.match(sg(["explain", "--command", "git push"], dir).stdout, /gates: fast, full/); }); +test("explain --commands: a truncated decision-log record is skipped, not replayed as a command", () => { + const dir = tmpProject({ + ".skillgate/done.yaml": `finishLine: ["git push"] +gates: + - id: full + type: file-exists + file: .skillgate/done.yaml +`, + "decisions.jsonl": [ + '{"ts":"1","via":"gate","event":"command","decision":"allow","reason":"ok","command":"git status","failed":[]}', + '{"ts":"2","via":"gate","event":"command","decision":"block","reason":"full failed","command":"git push origin ma', + "{ git push; }", + "", + ].join("\n"), + }); + const out = sg(["explain", "--commands", "decisions.jsonl", "--json"], dir); + assert.equal(out.status, 0, out.stderr); + const report = JSON.parse(out.stdout); + assert.deepEqual(report.commands.map((c: any) => c.command), ["git status", "{ git push; }"]); + assert.equal(report.total, 2); + assert.equal(report.skipped, 1); + + const text = sg(["explain", "--commands", "decisions.jsonl"], dir); + assert.equal(text.status, 0, text.stderr); + assert.match(text.stdout, /1 malformed log line skipped/); + assert.doesNotMatch(text.stdout, /"ts":"2"/); +}); + test("gatesForCommand: tool-only gates do not apply to commands", () => { const spec: Spec = { gates: [ From 203f48bd6f876be131e45cc09c7e691445a3b3f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Zander?= <96420681+renezander030@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:55:12 +0000 Subject: [PATCH 03/13] install --follow-symlinks writes through a symlinked agent config --- CHANGELOG.md | 6 ++++ README.md | 5 +++ src/cli.ts | 4 ++- src/files.ts | 38 ++++++++++++++++++++--- src/integrations.ts | 44 ++++++++++++++------------- test/release-0161.test.ts | 64 +++++++++++++++++++++++++++++++++++++++ 6 files changed, 135 insertions(+), 26 deletions(-) create mode 100644 test/release-0161.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index f8f3b17..ad8390d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ ## 0.16.1 - 2026-11-23 +### Added +- `skillgate install --follow-symlinks` writes through a symlinked agent + configuration (a dotfiles `.claude/settings.json`, say) to the regular file it names + and keeps the link. Without the flag a link is still refused, now with a hint; a + dangling link or a link to a non-file is refused either way. + ### Fixed - `skillgate log` streams decision logs, skips invalid record shapes without losing valid neighboring records, and counts event names such as `__proto__` correctly. diff --git a/README.md b/README.md index 0b97671..3a13989 100644 --- a/README.md +++ b/README.md @@ -180,6 +180,11 @@ Skillgate hook when re-run. Installations are serialized per project and replace complete config files atomically while preserving existing permissions and other hooks. If another installation is active, retry after it finishes. +A symlinked config file (a dotfiles `.claude/settings.json`, say) is refused by +default, so a link committed to a repository cannot redirect the install into a +file elsewhere. Pass `--follow-symlinks` to write through the link to the regular +file it names; the link stays in place. A dangling link is refused either way. + Agent hooks are installed **fail-closed**: if the gate itself cannot run (npx missing, offline, registry error), the hook blocks instead of letting the command through, and it gets a 10-minute budget so a slow test suite doesn't time out into diff --git a/src/cli.ts b/src/cli.ts index 005f324..1d57386 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -128,6 +128,7 @@ Flags: --tool gate: judge an agent tool call (gatedTools) instead of a command --gate phase: which phase gate, when the spec has more than one --stop install: also register the Stop hook (claude-code, codex, copilot-cli) + --follow-symlinks install: write through a symlinked agent config to the file it names --timeout check/gate: cap the complete gate run (overrides spec timeout) --cache check: reuse a passing result only for the exact repo snapshot --receipt check: write a machine-readable execution receipt @@ -646,10 +647,11 @@ function integrationTargets(value: string | undefined): IntegrationTarget[] { if (cmd === "install") { const targets = integrationTargets(args[1]); const stop = args.includes("--stop"); + const followSymlinks = args.includes("--follow-symlinks"); if (stop && !targets.some((target) => STOP_TARGETS.includes(target))) die(2, `--stop applies to the ${STOP_TARGETS.join(", ")} targets`); try { for (const target of targets) { - const result = installIntegration(target, cwd, { stop }); + const result = installIntegration(target, cwd, { stop, followSymlinks }); console.log(`${result.changed ? c(C.green, "✓") : c(C.dim, "·")} ${target} ${result.detail} (${path.relative(cwd, result.file)})`); } process.exit(0); diff --git a/src/files.ts b/src/files.ts index cbff2e4..684f903 100644 --- a/src/files.ts +++ b/src/files.ts @@ -3,14 +3,44 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; +export interface WriteOptions { + /** Write through a symbolic link to the existing regular file it names, keeping the link. */ + followSymlink?: boolean; +} + +/** + * The file a configuration write lands in: `file` itself, or with `followSymlink` the + * existing regular file its link resolves to. A dangling link or one to a non-file is refused. + */ +function writeTarget(file: string, opts: WriteOptions): string { + let stat: fs.Stats; + try { + stat = fs.lstatSync(file); + } catch (error: any) { + if (error?.code === "ENOENT") return file; + throw error; + } + if (stat.isFile()) return file; + if (!stat.isSymbolicLink()) throw new Error(`refusing to replace a non-regular configuration: ${file}`); + if (!opts.followSymlink) throw new Error(`refusing to replace a non-regular configuration: ${file} is a symbolic link (pass --follow-symlinks to write through it)`); + let real: string; + try { + real = fs.realpathSync(file); + } catch (error: any) { + if (error?.code === "ENOENT") throw new Error(`refusing to write through a dangling symbolic link: ${file}`); + throw error; + } + if (!fs.statSync(real).isFile()) throw new Error(`refusing to write through a symbolic link to a non-regular file: ${file} -> ${real}`); + return real; +} + /** Replace one complete configuration, preserving the old file on failure. */ -export function writeTextAtomic(file: string, text: string): void { +export function writeTextAtomic(file: string, text: string, opts: WriteOptions = {}): void { + file = writeTarget(file, opts); fs.mkdirSync(path.dirname(file), { recursive: true }); let mode = 0o600; try { - const stat = fs.lstatSync(file); - if (!stat.isFile()) throw new Error(`refusing to replace a non-regular configuration: ${file}`); - mode = stat.mode & 0o777; + mode = fs.lstatSync(file).mode & 0o777; } catch (error: any) { if (error?.code !== "ENOENT") throw error; } diff --git a/src/integrations.ts b/src/integrations.ts index 0ff15e7..0fba886 100644 --- a/src/integrations.ts +++ b/src/integrations.ts @@ -15,6 +15,8 @@ export const STOP_TARGETS: readonly IntegrationTarget[] = ["claude-code", "codex export interface InstallOptions { /** claude-code, codex, copilot-cli: also gate the agent's Stop event, so it cannot end a turn with unmet gates. */ stop?: boolean; + /** Write through a symlinked configuration file to the regular file it names (dotfiles setups). */ + followSymlinks?: boolean; } /** Hook budget in seconds. Long enough for a test suite; a hook that times out fails open in most agents. */ @@ -47,8 +49,8 @@ export interface DoctorCheck { detail: string; } -function writeJson(file: string, value: unknown): void { - writeTextAtomic(file, JSON.stringify(value, null, 2) + "\n"); +function writeJson(file: string, value: unknown, opts: InstallOptions): void { + writeTextAtomic(file, JSON.stringify(value, null, 2) + "\n", { followSymlink: opts.followSymlinks }); } function packageRef(): string { @@ -106,9 +108,9 @@ function upsertHook(hooks: Record, event: string, entry: unknow return "updated"; } -function hookResult(target: IntegrationTarget, file: string, outcomes: Upsert[], what: string, data: unknown): InstallResult { +function hookResult(target: IntegrationTarget, file: string, outcomes: Upsert[], what: string, data: unknown, opts: InstallOptions): InstallResult { const changed = outcomes.some((o) => o !== "unchanged"); - if (changed) writeJson(file, data); + if (changed) writeJson(file, data, opts); const detail = !changed ? `${what} already registered` : outcomes.includes("updated") ? `updated ${what} to the fail-closed form` : `registered fail-closed ${what}`; @@ -127,7 +129,7 @@ function installGateHooks(target: IntegrationTarget, file: string, cwd: string, data.hooks ??= {}; const outcomes = [upsertHook(data.hooks, "PreToolUse", entry(gateCommand(), toolMatcher("Bash", cwd)), file)]; if (opts.stop) outcomes.push(upsertHook(data.hooks, "Stop", entry(gateCommand(STOP_GATE)), file)); - return hookResult(target, file, outcomes, opts.stop ? "PreToolUse and Stop hooks" : "PreToolUse hook", data); + return hookResult(target, file, outcomes, opts.stop ? "PreToolUse and Stop hooks" : "PreToolUse hook", data, opts); } function installClaude(cwd: string, opts: InstallOptions): InstallResult { @@ -159,7 +161,7 @@ function installCopilot(cwd: string, opts: InstallOptions): InstallResult { }), (data) => { data.version ??= 1; }); } -function installGemini(cwd: string): InstallResult { +function installGemini(cwd: string, opts: InstallOptions): InstallResult { const file = path.join(cwd, ".gemini", "settings.json"); const data = readJson(file); data.hooks ??= {}; @@ -167,10 +169,10 @@ function installGemini(cwd: string): InstallResult { matcher: toolMatcher("run_shell_command", cwd), hooks: [{ name: "skillgate", type: "command", command: gateCommand(" --format gemini"), timeout: HOOK_TIMEOUT_SECONDS * 1000 }], }, file); - return hookResult("gemini-cli", file, [outcome], "BeforeTool hook", data); + return hookResult("gemini-cli", file, [outcome], "BeforeTool hook", data, opts); } -function installCursor(cwd: string): InstallResult { +function installCursor(cwd: string, opts: InstallOptions): InstallResult { const file = path.join(cwd, ".cursor", "hooks.json"); const data = readJson(file); data.version ??= 1; @@ -180,10 +182,10 @@ function installCursor(cwd: string): InstallResult { timeout: HOOK_TIMEOUT_SECONDS, failClosed: true, }, file); - return hookResult("cursor", file, [outcome], "beforeShellExecution hook", data); + return hookResult("cursor", file, [outcome], "beforeShellExecution hook", data, opts); } -function installOpenCode(cwd: string): InstallResult { +function installOpenCode(cwd: string, opts: InstallOptions): InstallResult { const file = path.join(cwd, "opencode.json"); const data = readJson(file); data.$schema ??= "https://opencode.ai/config.json"; @@ -192,7 +194,7 @@ function installOpenCode(cwd: string): InstallResult { const exists = data.plugin.includes(PACKAGE); if (!exists) { data.plugin.push(PACKAGE); - writeJson(file, data); + writeJson(file, data, opts); } return { target: "opencode", changed: !exists, file, detail: exists ? "plugin already registered" : "registered Skillgate plugin" }; } @@ -230,17 +232,17 @@ jobs: `; } -function installGitHubActions(cwd: string): InstallResult { +function installGitHubActions(cwd: string, opts: InstallOptions): InstallResult { const file = path.join(cwd, ".github", "workflows", "skillgate.yml"); if (fs.existsSync(file)) { const old = fs.readFileSync(file, "utf8"); if (!old.includes(PACKAGE)) throw new Error(`${file} already exists and is not a Skillgate workflow`); const upgraded = upgradeWorkflow(old); if (upgraded === old) return { target: "github-actions", changed: false, file, detail: "workflow already installed" }; - writeTextAtomic(file, upgraded); + writeTextAtomic(file, upgraded, { followSymlink: opts.followSymlinks }); return { target: "github-actions", changed: true, file, detail: "upgraded workflow to this Skillgate version and its pinned actions" }; } - writeTextAtomic(file, actionWorkflow()); + writeTextAtomic(file, actionWorkflow(), { followSymlink: opts.followSymlinks }); return { target: "github-actions", changed: true, file, detail: "installed pull-request workflow" }; } @@ -256,7 +258,7 @@ function upgradeWorkflow(text: string): string { return out.replace(/^(\s*node-version:\s*)(['"]?)(?:18|20)\2[ \t]*$/m, `$1'${WORKFLOW_NODE}'`); } -function installPreCommit(cwd: string): InstallResult { +function installPreCommit(cwd: string, opts: InstallOptions): InstallResult { const file = path.join(cwd, ".pre-commit-config.yaml"); const data: any = fs.existsSync(file) ? parseYaml(fs.readFileSync(file, "utf8")) : {}; if (!data || typeof data !== "object" || Array.isArray(data)) throw new Error(`${file}: expected a YAML object`); @@ -279,7 +281,7 @@ function installPreCommit(cwd: string): InstallResult { }); } if (changed) { - writeTextAtomic(file, stringifyYaml(data)); + writeTextAtomic(file, stringifyYaml(data), { followSymlink: opts.followSymlinks }); } return { target: "pre-commit", changed, file, detail: changed ? "installed or upgraded always-run pre-commit hook" : "hook already installed" }; } @@ -291,11 +293,11 @@ export function installIntegration(target: IntegrationTarget, cwd: string, opts: case "claude-code": return installClaude(root, opts); case "codex": return installCodex(root, opts); case "copilot-cli": return installCopilot(root, opts); - case "gemini-cli": return installGemini(root); - case "cursor": return installCursor(root); - case "opencode": return installOpenCode(root); - case "github-actions": return installGitHubActions(root); - case "pre-commit": return installPreCommit(root); + case "gemini-cli": return installGemini(root, opts); + case "cursor": return installCursor(root, opts); + case "opencode": return installOpenCode(root, opts); + case "github-actions": return installGitHubActions(root, opts); + case "pre-commit": return installPreCommit(root, opts); } }); } diff --git a/test/release-0161.test.ts b/test/release-0161.test.ts new file mode 100644 index 0000000..4685366 --- /dev/null +++ b/test/release-0161.test.ts @@ -0,0 +1,64 @@ +// Tests for 0.16.1: symlinked agent configs, bounded regex matching, the devin target +// and doctor's last-decision check. Fixtures are real throwaway directories. +import test from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { spawnSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import { installIntegration } from "../src/integrations.js"; +import { writeTextAtomic } from "../src/files.js"; + +const CLI = fileURLToPath(new URL("../src/cli.js", import.meta.url)); + +function project(t: { after: (fn: () => void) => void }, files: Record = {}): string { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "skillgate-0161-")); + t.after(() => fs.rmSync(dir, { recursive: true, force: true })); + const all = { ".skillgate/done.yaml": "finishLine: [\"git push\"]\ngates:\n - id: readme\n type: file-exists\n file: README.md\n", "README.md": "hi\n", ...files }; + for (const [rel, content] of Object.entries(all)) { + fs.mkdirSync(path.dirname(path.join(dir, rel)), { recursive: true }); + fs.writeFileSync(path.join(dir, rel), content); + } + return dir; +} + +function sg(dir: string, args: string[], input = "") { + return spawnSync(process.execPath, [CLI, ...args], { cwd: dir, encoding: "utf8", input }); +} + +const posixOnly = { skip: process.platform === "win32" }; + +test("install --follow-symlinks writes through a symlinked settings file and keeps the link", posixOnly, t => { + const dir = project(t, { "dotfiles/settings.json": "{\"model\":\"x\"}\n" }); + fs.mkdirSync(path.join(dir, ".claude")); + const link = path.join(dir, ".claude", "settings.json"); + fs.symlinkSync(path.join("..", "dotfiles", "settings.json"), link); + fs.chmodSync(path.join(dir, "dotfiles", "settings.json"), 0o640); + + const refused = sg(dir, ["install", "claude-code"]); + assert.equal(refused.status, 2); + assert.match(refused.stderr, /symbolic link \(pass --follow-symlinks/); + + const out = sg(dir, ["install", "claude-code", "--follow-symlinks"]); + assert.equal(out.status, 0, out.stderr); + assert.ok(fs.lstatSync(link).isSymbolicLink(), "the link is kept"); + const data = JSON.parse(fs.readFileSync(path.join(dir, "dotfiles", "settings.json"), "utf8")); + assert.equal(data.model, "x"); + assert.match(JSON.stringify(data.hooks.PreToolUse), /@reneza\/skillgate@/); + assert.equal(fs.statSync(path.join(dir, "dotfiles", "settings.json")).mode & 0o777, 0o640); + assert.equal(installIntegration("claude-code", dir, { followSymlinks: true }).changed, false); + assert.equal(fs.readdirSync(path.join(dir, "dotfiles")).some(f => f.endsWith(".tmp")), false); +}); + +test("--follow-symlinks still refuses a dangling link or a link to a directory", posixOnly, t => { + const dir = project(t); + const dangling = path.join(dir, "dangling.json"); + fs.symlinkSync("missing.json", dangling); + assert.throws(() => writeTextAtomic(dangling, "{}", { followSymlink: true }), /dangling symbolic link/); + assert.equal(fs.existsSync(path.join(dir, "missing.json")), false); + fs.mkdirSync(path.join(dir, "d")); + const toDir = path.join(dir, "dir.json"); + fs.symlinkSync("d", toDir); + assert.throws(() => writeTextAtomic(toDir, "{}", { followSymlink: true }), /non-regular file/); +}); From 3f88d9fbc2ae42a72a13bd0cd39b48b4cf98d128 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Zander?= <96420681+renezander030@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:55:12 +0000 Subject: [PATCH 04/13] Pattern gates match under the run deadline --- CHANGELOG.md | 4 +++ src/core.ts | 74 ++++++++++++++++++++++++++------------- test/release-0161.test.ts | 28 +++++++++++++++ 3 files changed, 81 insertions(+), 25 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ad8390d..f8b7bfc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,10 @@ dangling link or a link to a non-file is refused either way. ### Fixed +- Pattern gates (`absent`, `file-contains`, `no-new`, `no-fewer`, `commit-messages`) + match under the run deadline: a pattern that backtracks catastrophically fails its + gate with a reason naming the file instead of wedging the hook past its timeout. + Matching costs about 0.35 ms more per scanned file. - `skillgate log` streams decision logs, skips invalid record shapes without losing valid neighboring records, and counts event names such as `__proto__` correctly. - `skillgate explain --commands ` skips a truncated or corrupt decision-log record diff --git a/src/core.ts b/src/core.ts index cb2b90a..cc0774c 100644 --- a/src/core.ts +++ b/src/core.ts @@ -1,4 +1,5 @@ import fs from "node:fs"; +import vm from "node:vm"; import os from "node:os"; import path from "node:path"; import { spawnSync } from "node:child_process"; @@ -137,19 +138,6 @@ function runOne(gate: Gate, cwd: string, opts: RunOptions): GateResult { const DEFAULT_TRIVY_SCANNERS: NonNullable = ["vuln", "secret"]; const DEFAULT_TRIVY_SEVERITY: NonNullable = ["CRITICAL"]; -/** Count lines of `text` that match `re`; calls `onFirst` with the 0-based index of the first hit. */ -function countMatchingLines(text: string, re: RegExp, onFirst?: (i: number) => void): number { - const lines = text.split("\n"); - let n = 0; - for (let i = 0; i < lines.length; i++) { - if (re.test(lines[i])) { - if (n === 0 && onFirst) onFirst(i); - n++; - } - } - return n; -} - /** * Changed files for a command gate: `SKILLGATE_CHANGED_FILES` names a temporary * file listing the existing files changed versus the base (one per line, filtered @@ -175,6 +163,14 @@ function changedFilesEnv(gate: CommandGate, cwd: string, baseRef: string | undef }; } +/** Line matching and whole-text matching, run in a context the deadline can interrupt. */ +const LINES = new vm.Script(`(() => { + const lines = text.split("\\n"), hits = []; + for (let i = 0; i < lines.length && hits.length < limit; i++) if (re.test(lines[i])) hits.push(i); + return hits; +})()`); +const TEST = new vm.Script("re.test(text)"); + /** A pattern gate hit a read limit; the gate fails with this message. */ class ScanLimit extends Error {} @@ -217,6 +213,37 @@ class Scanner { return fs.readFileSync(full, "utf8"); } + /** + * 0-based indexes of the lines of `text` that match `re`, at most `limit` of them. Matching + * runs under the run deadline, so a pattern that backtracks catastrophically fails the gate + * instead of wedging the hook past its host's timeout. + */ + matchingLines(text: string, re: RegExp, label: string, limit = Number.POSITIVE_INFINITY): number[] { + return Array.from(this.bounded(LINES, { text, re, limit }, re, label) as number[]); + } + + /** Whether `re` matches anywhere in `text`, under the run deadline. */ + test(text: string, re: RegExp, label: string): boolean { + return this.bounded(TEST, { text, re }, re, label) as boolean; + } + + private context?: vm.Context; + + private bounded(script: vm.Script, values: Record, re: RegExp, label: string): unknown { + const left = this.deadline - Date.now(); + if (left <= 0) throw new ScanLimit(`timed out before matching ${label}`); + const context = Object.assign(this.context ??= vm.createContext({}), values); + if (left === Number.POSITIVE_INFINITY) return script.runInContext(context); + try { + return script.runInContext(context, { timeout: Math.max(1, Math.ceil(left)) }); + } catch (error: any) { + if (error?.code === "ERR_SCRIPT_EXECUTION_TIMEOUT") { + throw new ScanLimit(`/${re.source}/ did not finish matching ${label} before the run deadline — simplify the pattern (nested quantifiers backtrack) or raise timeout`); + } + throw error; + } + } + /** Text as of a git ref, or null when the file did not exist there. */ atRef(cwd: string, ref: string, rel: string, total: number): string | null { this.tick(total); @@ -373,7 +400,7 @@ function checkGate(gate: Gate, cwd: string, opts: RunOptions): GateResult { const re = new RegExp(gate.pattern, gate.flags ?? ""); const text = new Scanner(gate.maxBytes, opts.remainingMs).file(cwd, gate.file, 1); if (text == null) return { ...base, ok: false, reason: `file could not be read: ${gate.file}`, location: { file: gate.file } }; - return re.test(text) + return new Scanner(gate.maxBytes, opts.remainingMs).test(text, re, gate.file) ? { ...base, ok: true, reason: `${gate.file} matches /${gate.pattern}/` } : { ...base, ok: false, reason: `${gate.file} missing /${gate.pattern}/`, location: { file: gate.file } }; } @@ -385,12 +412,8 @@ function checkGate(gate: Gate, cwd: string, opts: RunOptions): GateResult { for (const f of files) { const text = scan.file(cwd, f, files.length); if (text == null) return { ...base, ok: false, reason: `matched file disappeared: ${f}`, location: { file: f } }; - const lines = text.split("\n"); - for (let i = 0; i < lines.length; i++) { - if (re.test(lines[i])) { - return { ...base, ok: false, reason: `${f}:${i + 1} matches /${gate.pattern}/`, location: { file: f, line: i + 1 } }; - } - } + const [hit] = scan.matchingLines(text, re, f, 1); + if (hit != null) return { ...base, ok: false, reason: `${f}:${hit + 1} matches /${gate.pattern}/`, location: { file: f, line: hit + 1 } }; } return { ...base, ok: true, reason: `no /${gate.pattern}/ in ${gate.glob} (${files.length} files)` }; } @@ -497,12 +520,12 @@ function checkGate(gate: Gate, cwd: string, opts: RunOptions): GateResult { let firstLost: string | undefined; for (const f of union) { const baseText = scan.atRef(cwd, diffBase, f, union.length); - const fileBase = baseText == null ? 0 : countMatchingLines(baseText, re()); + const fileBase = baseText == null ? 0 : scan.matchingLines(baseText, re(), `${f} at ${baseLabel(diffBase)}`).length; const text = scan.file(cwd, f, union.length); // A file gone from the working tree contributes 0; no-deleted covers the file itself. - const fileWork = text == null ? 0 : countMatchingLines(text, re(), (i) => { - if (!firstNew) firstNew = { file: f, line: i + 1 }; - }); + const hits = text == null ? [] : scan.matchingLines(text, re(), f); + if (hits.length && !firstNew) firstNew = { file: f, line: hits[0] + 1 }; + const fileWork = hits.length; if (fileWork < fileBase && !firstLost) firstLost = f; baseCount += fileBase; workCount += fileWork; @@ -693,7 +716,8 @@ function checkGate(gate: Gate, cwd: string, opts: RunOptions): GateResult { const commits = commitSubjects(cwd, diffBase); const short = baseLabel(diffBase); if (commits.length === 0) return { ...base, ok: true, reason: `no commits since ${short}` }; - const bad = commits.filter((commit) => !re.test(commit.subject)); + const scan = new Scanner(undefined, opts.remainingMs); + const bad = commits.filter((commit) => !scan.test(commit.subject, re, "a commit subject")); return bad.length ? { ...base, ok: false, reason: `${bad.length} of ${commits.length} commit message(s) since ${short} do not match /${gate.pattern}/: ${sample(bad, 3, (c) => commitLabel(c))}` } : { ...base, ok: true, reason: `${commits.length} commit message(s) since ${short} match` }; diff --git a/test/release-0161.test.ts b/test/release-0161.test.ts index 4685366..2ff43e0 100644 --- a/test/release-0161.test.ts +++ b/test/release-0161.test.ts @@ -62,3 +62,31 @@ test("--follow-symlinks still refuses a dangling link or a link to a directory", fs.symlinkSync("d", toDir); assert.throws(() => writeTextAtomic(toDir, "{}", { followSymlink: true }), /non-regular file/); }); + +test("a catastrophically backtracking pattern fails its gate at the run deadline instead of wedging", { timeout: 30000 }, t => { + const dir = project(t, { + ".skillgate/done.yaml": "timeout: 1000\ngates:\n - id: no-bad\n type: absent\n pattern: \"^(a+)+$\"\n glob: \"data/*.txt\"\n - id: header\n type: file-contains\n file: data/x.txt\n pattern: \"^(a|aa)+$\"\n", + "data/x.txt": "a".repeat(40) + "b\n", + }); + const started = Date.now(); + const out = spawnSync(process.execPath, [CLI, "check", "--json"], { cwd: dir, encoding: "utf8", timeout: 20000 }); + assert.notEqual(out.signal, "SIGTERM", "check was killed instead of answering"); + assert.equal(out.status, 1, out.stderr); + assert.ok(Date.now() - started < 15000); + const report = JSON.parse(out.stdout); + const bad = report.results.find((r: any) => r.id === "no-bad"); + assert.equal(bad.ok, false); + assert.match(bad.reason, /did not finish matching data\/x\.txt before the run deadline/); +}); + +test("bounded matching keeps first-hit lines and counts", t => { + const dir = project(t, { + ".skillgate/done.yaml": "gates:\n - id: todo\n type: absent\n pattern: TODO\n glob: \"src/*.ts\"\n", + "src/a.ts": "one\ntwo // TODO\nthree TODO\n", + }); + const out = sg(dir, ["check", "--json"]); + assert.equal(out.status, 1, out.stderr); + const r = JSON.parse(out.stdout).results[0]; + assert.equal(r.reason, "src/a.ts:2 matches /TODO/"); + assert.deepEqual(r.location, { file: "src/a.ts", line: 2 }); +}); From a3055aaa634941334d3e4214fe8baaa270e414d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Zander?= <96420681+renezander030@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:55:13 +0000 Subject: [PATCH 05/13] install devin: gate Devin Desktop and the Devin CLI --- CHANGELOG.md | 4 ++++ README.md | 4 ++++ src/cli.ts | 4 ++-- src/integrations.ts | 20 ++++++++++++++++++-- test/release-0161.test.ts | 23 +++++++++++++++++++++++ 5 files changed, 51 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f8b7bfc..c902458 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,10 @@ ## 0.16.1 - 2026-11-23 ### Added +- `skillgate install devin` gates Devin Desktop (formerly Windsurf) and the Devin CLI: + a fail-closed `PreToolUse` hook on the `exec` shell tool in `.devin/hooks.v1.json`, + checked by `doctor devin`. `gate` now judges an `exec` tool call as a shell command; + before, it allowed it as an ungated tool. - `skillgate install --follow-symlinks` writes through a symlinked agent configuration (a dotfiles `.claude/settings.json`, say) to the regular file it names and keeps the link. Without the flag a link is still refused, now with a hint; a diff --git a/README.md b/README.md index 3a13989..52415d1 100644 --- a/README.md +++ b/README.md @@ -165,6 +165,7 @@ skillgate install codex # --stop works here too skillgate install copilot-cli # GitHub Copilot CLI and its cloud agent; --stop works here too skillgate install gemini-cli skillgate install cursor +skillgate install devin # Devin Desktop (formerly Windsurf) and the Devin CLI skillgate install opencode skillgate install github-actions skillgate install pre-commit @@ -180,6 +181,9 @@ Skillgate hook when re-run. Installations are serialized per project and replace complete config files atomically while preserving existing permissions and other hooks. If another installation is active, retry after it finishes. +`install devin` writes `.devin/hooks.v1.json` with a `PreToolUse` hook on Devin's +`exec` shell tool; `gate` judges an `exec` call as a shell command. + A symlinked config file (a dotfiles `.claude/settings.json`, say) is refused by default, so a link committed to a repository cannot redirect the install into a file elsewhere. Pass `--follow-symlinks` to write through the link to the regular diff --git a/src/cli.ts b/src/cli.ts index 1d57386..8d81a4c 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -99,7 +99,7 @@ Usage: skillgate init [--preset ] write an example .skillgate/done.yaml (presets: no-secrets, regression) skillgate review-snapshot print the snapshot to bind an optional review report to skillgate install install agent hooks (claude-code, codex, copilot-cli, gemini-cli, - cursor, opencode), github-actions, or pre-commit enforcement + cursor, devin, opencode), github-actions, or pre-commit enforcement skillgate doctor verify policy discovery and one or more integrations skillgate explain --command show structural finish-line matching without running gates skillgate explain --commands replay a command corpus (lines or a decision log; - = stdin) @@ -329,7 +329,7 @@ function resolveSpecAndBase(specPath: string | null): Resolved { } /** Shell tool names across agents; their calls are judged as commands by `finishLine`. */ -const SHELL_TOOLS = new Set(["Bash", "bash", "run_shell_command", "shell", "local_shell", "exec_command"]); +const SHELL_TOOLS = new Set(["Bash", "bash", "run_shell_command", "shell", "local_shell", "exec_command", "exec"]); /** Read a hook payload from stdin: parsed JSON when it is JSON, else the raw text. */ function readStdinPayload(): { raw: string; data?: any } { diff --git a/src/integrations.ts b/src/integrations.ts index 0fba886..290e06f 100644 --- a/src/integrations.ts +++ b/src/integrations.ts @@ -6,7 +6,7 @@ import { findSpecPath, loadSpec, specRoot, workspaceRoot } from "./spec.js"; import { writeTextAtomic, withInstallLock } from "./files.js"; import { EVALUATOR_VERSION } from "./receipt.js"; -export const INTEGRATION_TARGETS = ["claude-code", "codex", "copilot-cli", "gemini-cli", "cursor", "opencode", "github-actions", "pre-commit"] as const; +export const INTEGRATION_TARGETS = ["claude-code", "codex", "copilot-cli", "gemini-cli", "cursor", "devin", "opencode", "github-actions", "pre-commit"] as const; export type IntegrationTarget = (typeof INTEGRATION_TARGETS)[number]; /** Agents whose Stop hook takes Claude's `decision: "block"` answer, so `--stop` can gate the end of a turn. */ @@ -185,6 +185,20 @@ function installCursor(cwd: string, opts: InstallOptions): InstallResult { return hookResult("cursor", file, [outcome], "beforeShellExecution hook", data, opts); } +/** + * Devin Desktop (formerly Windsurf) and the Devin CLI load `.devin/hooks.v1.json`, whose whole + * file is the hooks object. Its shell tool is `exec`; a command hook that exits 2 denies the call. + */ +function installDevin(cwd: string, opts: InstallOptions): InstallResult { + const file = path.join(cwd, ".devin", "hooks.v1.json"); + const data = readJson(file); + const outcome = upsertHook(data, "PreToolUse", { + matcher: toolMatcher("exec", cwd), + hooks: [{ type: "command", command: gateCommand(), timeout: HOOK_TIMEOUT_SECONDS }], + }, file); + return hookResult("devin", file, [outcome], "PreToolUse hook", data, opts); +} + function installOpenCode(cwd: string, opts: InstallOptions): InstallResult { const file = path.join(cwd, "opencode.json"); const data = readJson(file); @@ -295,6 +309,7 @@ export function installIntegration(target: IntegrationTarget, cwd: string, opts: case "copilot-cli": return installCopilot(root, opts); case "gemini-cli": return installGemini(root, opts); case "cursor": return installCursor(root, opts); + case "devin": return installDevin(root, opts); case "opencode": return installOpenCode(root, opts); case "github-actions": return installGitHubActions(root, opts); case "pre-commit": return installPreCommit(root, opts); @@ -304,7 +319,7 @@ export function installIntegration(target: IntegrationTarget, cwd: string, opts: /** Gated tools a target's hook matcher does not include (only agents whose hooks match tool names). */ function uncovered(target: IntegrationTarget, text: string, root: string): string[] { - if (!["claude-code", "codex", "copilot-cli", "gemini-cli"].includes(target)) return []; + if (!["claude-code", "codex", "copilot-cli", "gemini-cli", "devin"].includes(target)) return []; return gatedTools(root).filter((glob) => !text.includes(JSON.stringify(toolGlobToRegex(glob)).slice(1, -1))); } @@ -329,6 +344,7 @@ export function doctor(cwd: string, targets: readonly IntegrationTarget[] = INTE "copilot-cli": [path.join(root, ".github", "hooks", "skillgate.json"), MARKER, FAIL_CLOSED.trim()], "gemini-cli": [path.join(root, ".gemini", "settings.json"), MARKER, FAIL_CLOSED.trim()], "cursor": [path.join(root, ".cursor", "hooks.json"), MARKER, '"failClosed": true'], + "devin": [path.join(root, ".devin", "hooks.v1.json"), MARKER, FAIL_CLOSED.trim()], "opencode": [path.join(root, "opencode.json"), PACKAGE], "github-actions": [path.join(root, ".github", "workflows", "skillgate.yml"), PACKAGE], "pre-commit": [path.join(root, ".pre-commit-config.yaml"), PACKAGE], diff --git a/test/release-0161.test.ts b/test/release-0161.test.ts index 2ff43e0..faba0f2 100644 --- a/test/release-0161.test.ts +++ b/test/release-0161.test.ts @@ -90,3 +90,26 @@ test("bounded matching keeps first-hit lines and counts", t => { assert.equal(r.reason, "src/a.ts:2 matches /TODO/"); assert.deepEqual(r.location, { file: "src/a.ts", line: 2 }); }); + +test("install devin registers a fail-closed exec hook and gate judges Devin's exec payload as a command", t => { + const dir = project(t, { ".devin/hooks.v1.json": "{\"SessionStart\":[{\"hooks\":[{\"type\":\"command\",\"command\":\"echo hi\"}]}]}\n" }); + fs.rmSync(path.join(dir, "README.md")); + const out = sg(dir, ["install", "devin"]); + assert.equal(out.status, 0, out.stderr); + const hooks = JSON.parse(fs.readFileSync(path.join(dir, ".devin", "hooks.v1.json"), "utf8")); + assert.equal(hooks.SessionStart.length, 1, "other hooks are kept"); + assert.equal(hooks.PreToolUse[0].matcher, "exec"); + assert.match(hooks.PreToolUse[0].hooks[0].command, /@reneza\/skillgate@\S+ gate --timeout 540000 \|\| exit 2$/); + assert.equal(sg(dir, ["install", "devin"]).stdout.includes("already registered"), true); + assert.match(sg(dir, ["doctor", "devin"]).stdout, /devin\s+configured in \.devin\/hooks\.v1\.json/); + + const payload = JSON.stringify({ hook_event_name: "PreToolUse", tool_name: "exec", tool_input: { command: "git push origin main" }, session_id: "s1" }); + const blocked = sg(dir, ["gate"], payload); + assert.equal(blocked.status, 2, blocked.stdout); + assert.match(blocked.stdout + blocked.stderr, /readme/); + fs.writeFileSync(path.join(dir, "README.md"), "hi\n"); + assert.equal(sg(dir, ["gate"], payload).status, 0); + const other = JSON.stringify({ hook_event_name: "PreToolUse", tool_name: "exec", tool_input: { command: "ls" } }); + fs.rmSync(path.join(dir, "README.md")); + assert.equal(sg(dir, ["gate"], other).status, 0, "a command off the finish line is allowed"); +}); From ddf8a7d6fea0e1877426746f61c710b3f5d556f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Zander?= <96420681+renezander030@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:55:13 +0000 Subject: [PATCH 06/13] Tidy-up: 6 behavior-preserving refactors of the new install and matching code --- src/cli.ts | 32 +++----------------------------- src/core.ts | 14 +++++++------- src/files.ts | 26 +++++++++++--------------- src/integrations.ts | 18 +++++++++++++----- src/log.ts | 30 ++++++++++++++++++++++++++++++ 5 files changed, 64 insertions(+), 56 deletions(-) diff --git a/src/cli.ts b/src/cli.ts index 8d81a4c..5e07429 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -6,7 +6,7 @@ import { spawnSync } from "node:child_process"; import { fileURLToPath } from "node:url"; import { findSpecPath, loadSpec, parseSpec, specRoot, workspaceRoot, DEFAULT_SPEC_PATHS, DEFAULT_PHASE_FILE, DEFAULT_RUN_TIMEOUT_MS, type Spec, type PhaseGate } from "./spec.js"; import { runGates, decideCommand, decideTool, currentPhase, evaluatePhase, gatesForCommand, type GateResult, type RunResult } from "./core.js"; -import { appendLog, logPath, logPathProblem, summarizeLogFile, toFailed, type LogRecord } from "./log.js"; +import { appendLog, corpusCommands, logPath, logPathProblem, summarizeLogFile, toFailed, type LogRecord } from "./log.js"; import { checkDrift, driftDiffs, DEFAULT_THRESHOLD, setCanonical } from "./drift.js"; import { runSync } from "./link.js"; import { runScaffold, templateHelp } from "./scaffold.js"; @@ -667,35 +667,9 @@ if (cmd === "doctor") { process.exit(checks.every((check) => check.ok) ? 0 : 1); } -/** - * Commands from a corpus: one per line, or decision-log JSON lines (their `command`). - * A line that opens like a JSON object (`{"`) but does not parse is a truncated or - * corrupt log record: it is counted in `skipped`, never replayed as a command. A - * shell brace group such as `{ git push; }` is still a command. - */ +/** Commands from a corpus file or stdin (`-`); see corpusCommands for the line rules. */ function readCorpus(source: string): { commands: string[]; skipped: number } { - const text = source === "-" ? fs.readFileSync(0, "utf8") : fs.readFileSync(path.resolve(cwd, source), "utf8"); - const commands: string[] = []; - let skipped = 0; - for (const line of text.split(/\r?\n/)) { - const trimmed = line.trim(); - if (!trimmed || trimmed.startsWith("#")) continue; - if (trimmed.startsWith("{")) { - try { - const record = JSON.parse(trimmed); - if (typeof record?.command === "string" && record.command.trim() && !record.tool) commands.push(record.command.trim()); - continue; - } catch { - if (/^\{\s*"/.test(trimmed)) { - skipped++; - continue; - } - /* a command that starts with "{" */ - } - } - commands.push(trimmed); - } - return { commands, skipped }; + return corpusCommands(source === "-" ? fs.readFileSync(0, "utf8") : fs.readFileSync(path.resolve(cwd, source), "utf8")); } if (cmd === "explain") { diff --git a/src/core.ts b/src/core.ts index cc0774c..87187df 100644 --- a/src/core.ts +++ b/src/core.ts @@ -398,9 +398,10 @@ function checkGate(gate: Gate, cwd: string, opts: RunOptions): GateResult { const full = path.resolve(cwd, gate.file); if (!fs.existsSync(full)) return { ...base, ok: false, reason: `file not found: ${gate.file}`, location: { file: gate.file } }; const re = new RegExp(gate.pattern, gate.flags ?? ""); - const text = new Scanner(gate.maxBytes, opts.remainingMs).file(cwd, gate.file, 1); + const scan = new Scanner(gate.maxBytes, opts.remainingMs); + const text = scan.file(cwd, gate.file, 1); if (text == null) return { ...base, ok: false, reason: `file could not be read: ${gate.file}`, location: { file: gate.file } }; - return new Scanner(gate.maxBytes, opts.remainingMs).test(text, re, gate.file) + return scan.test(text, re, gate.file) ? { ...base, ok: true, reason: `${gate.file} matches /${gate.pattern}/` } : { ...base, ok: false, reason: `${gate.file} missing /${gate.pattern}/`, location: { file: gate.file } }; } @@ -505,9 +506,8 @@ function checkGate(gate: Gate, cwd: string, opts: RunOptions): GateResult { } case "no-new": case "no-fewer": { - // Fresh regex per line (drop g/y so lastIndex can't advance between .test calls). - const flags = (gate.flags ?? "").replace(/[gy]/g, ""); - const re = () => new RegExp(gate.pattern, flags); + // Drop g/y so lastIndex can't advance between .test calls; one regex then serves every line. + const re = new RegExp(gate.pattern, (gate.flags ?? "").replace(/[gy]/g, "")); const ignore = gate.ignore ?? []; const workFiles = scanFiles(cwd, gate.glob, ignore); const baseFiles = listFilesAtRef(cwd, diffBase, true).filter((p) => inScan(p, gate.glob, ignore)); @@ -520,10 +520,10 @@ function checkGate(gate: Gate, cwd: string, opts: RunOptions): GateResult { let firstLost: string | undefined; for (const f of union) { const baseText = scan.atRef(cwd, diffBase, f, union.length); - const fileBase = baseText == null ? 0 : scan.matchingLines(baseText, re(), `${f} at ${baseLabel(diffBase)}`).length; + const fileBase = baseText == null ? 0 : scan.matchingLines(baseText, re, `${f} at ${baseLabel(diffBase)}`).length; const text = scan.file(cwd, f, union.length); // A file gone from the working tree contributes 0; no-deleted covers the file itself. - const hits = text == null ? [] : scan.matchingLines(text, re(), f); + const hits = text == null ? [] : scan.matchingLines(text, re, f); if (hits.length && !firstNew) firstNew = { file: f, line: hits[0] + 1 }; const fileWork = hits.length; if (fileWork < fileBase && !firstLost) firstLost = f; diff --git a/src/files.ts b/src/files.ts index 684f903..6b23b66 100644 --- a/src/files.ts +++ b/src/files.ts @@ -9,18 +9,19 @@ export interface WriteOptions { } /** - * The file a configuration write lands in: `file` itself, or with `followSymlink` the - * existing regular file its link resolves to. A dangling link or one to a non-file is refused. + * Where a configuration write lands and the permissions it keeps: `file` itself, or with + * `followSymlink` the existing regular file its link resolves to. A new file gets 0600. A + * dangling link, a link to a non-file, or any other non-regular path is refused. */ -function writeTarget(file: string, opts: WriteOptions): string { +function writeTarget(file: string, opts: WriteOptions): { file: string; mode: number } { let stat: fs.Stats; try { stat = fs.lstatSync(file); } catch (error: any) { - if (error?.code === "ENOENT") return file; + if (error?.code === "ENOENT") return { file, mode: 0o600 }; throw error; } - if (stat.isFile()) return file; + if (stat.isFile()) return { file, mode: stat.mode & 0o777 }; if (!stat.isSymbolicLink()) throw new Error(`refusing to replace a non-regular configuration: ${file}`); if (!opts.followSymlink) throw new Error(`refusing to replace a non-regular configuration: ${file} is a symbolic link (pass --follow-symlinks to write through it)`); let real: string; @@ -30,20 +31,15 @@ function writeTarget(file: string, opts: WriteOptions): string { if (error?.code === "ENOENT") throw new Error(`refusing to write through a dangling symbolic link: ${file}`); throw error; } - if (!fs.statSync(real).isFile()) throw new Error(`refusing to write through a symbolic link to a non-regular file: ${file} -> ${real}`); - return real; + const target = fs.statSync(real); + if (!target.isFile()) throw new Error(`refusing to write through a symbolic link to a non-regular file: ${file} -> ${real}`); + return { file: real, mode: target.mode & 0o777 }; } /** Replace one complete configuration, preserving the old file on failure. */ -export function writeTextAtomic(file: string, text: string, opts: WriteOptions = {}): void { - file = writeTarget(file, opts); +export function writeTextAtomic(requested: string, text: string, opts: WriteOptions = {}): void { + const { file, mode } = writeTarget(requested, opts); fs.mkdirSync(path.dirname(file), { recursive: true }); - let mode = 0o600; - try { - mode = fs.lstatSync(file).mode & 0o777; - } catch (error: any) { - if (error?.code !== "ENOENT") throw error; - } const temp = `${file}.${crypto.randomUUID()}.tmp`; try { fs.writeFileSync(temp, text, { mode, flag: "wx" }); diff --git a/src/integrations.ts b/src/integrations.ts index 290e06f..ee73a6b 100644 --- a/src/integrations.ts +++ b/src/integrations.ts @@ -12,6 +12,9 @@ export type IntegrationTarget = (typeof INTEGRATION_TARGETS)[number]; /** Agents whose Stop hook takes Claude's `decision: "block"` answer, so `--stop` can gate the end of a turn. */ export const STOP_TARGETS: readonly IntegrationTarget[] = ["claude-code", "codex", "copilot-cli"]; +/** Agents whose hook matcher names tools, so it must also list the policy's `gatedTools`. */ +const TOOL_MATCHER_TARGETS: readonly IntegrationTarget[] = ["claude-code", "codex", "copilot-cli", "gemini-cli", "devin"]; + export interface InstallOptions { /** claude-code, codex, copilot-cli: also gate the agent's Stop event, so it cannot end a turn with unmet gates. */ stop?: boolean; @@ -49,8 +52,13 @@ export interface DoctorCheck { detail: string; } +/** Replace one agent or CI configuration file under the install's symlink policy. */ +function writeConfig(file: string, text: string, opts: InstallOptions): void { + writeTextAtomic(file, text, { followSymlink: opts.followSymlinks }); +} + function writeJson(file: string, value: unknown, opts: InstallOptions): void { - writeTextAtomic(file, JSON.stringify(value, null, 2) + "\n", { followSymlink: opts.followSymlinks }); + writeConfig(file, JSON.stringify(value, null, 2) + "\n", opts); } function packageRef(): string { @@ -253,10 +261,10 @@ function installGitHubActions(cwd: string, opts: InstallOptions): InstallResult if (!old.includes(PACKAGE)) throw new Error(`${file} already exists and is not a Skillgate workflow`); const upgraded = upgradeWorkflow(old); if (upgraded === old) return { target: "github-actions", changed: false, file, detail: "workflow already installed" }; - writeTextAtomic(file, upgraded, { followSymlink: opts.followSymlinks }); + writeConfig(file, upgraded, opts); return { target: "github-actions", changed: true, file, detail: "upgraded workflow to this Skillgate version and its pinned actions" }; } - writeTextAtomic(file, actionWorkflow(), { followSymlink: opts.followSymlinks }); + writeConfig(file, actionWorkflow(), opts); return { target: "github-actions", changed: true, file, detail: "installed pull-request workflow" }; } @@ -295,7 +303,7 @@ function installPreCommit(cwd: string, opts: InstallOptions): InstallResult { }); } if (changed) { - writeTextAtomic(file, stringifyYaml(data), { followSymlink: opts.followSymlinks }); + writeConfig(file, stringifyYaml(data), opts); } return { target: "pre-commit", changed, file, detail: changed ? "installed or upgraded always-run pre-commit hook" : "hook already installed" }; } @@ -319,7 +327,7 @@ export function installIntegration(target: IntegrationTarget, cwd: string, opts: /** Gated tools a target's hook matcher does not include (only agents whose hooks match tool names). */ function uncovered(target: IntegrationTarget, text: string, root: string): string[] { - if (!["claude-code", "codex", "copilot-cli", "gemini-cli", "devin"].includes(target)) return []; + if (!TOOL_MATCHER_TARGETS.includes(target)) return []; return gatedTools(root).filter((glob) => !text.includes(JSON.stringify(toolGlobToRegex(glob)).slice(1, -1))); } diff --git a/src/log.ts b/src/log.ts index 18784d1..f577e8a 100644 --- a/src/log.ts +++ b/src/log.ts @@ -167,3 +167,33 @@ export async function summarizeLogFile(file: string, top = 10): Promise Date: Mon, 23 Nov 2026 13:55:13 +0000 Subject: [PATCH 07/13] Judge a pull request against the branch it targets Diff-aware gates read the pull request's target branch from GITHUB_BASE_REF, CI_MERGE_REQUEST_TARGET_BRANCH_NAME or BITBUCKET_PR_DESTINATION_BRANCH instead of origin's default branch. A target that is not in the checkout fails closed. --- CHANGELOG.md | 6 +++ docs/spec-reference.md | 5 ++- src/cli.ts | 6 ++- src/git.ts | 17 ++++++++ test/release-0161-more.test.ts | 79 ++++++++++++++++++++++++++++++++++ 5 files changed, 111 insertions(+), 2 deletions(-) create mode 100644 test/release-0161-more.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index c902458..dbf082c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,12 @@ dangling link or a link to a non-file is refused either way. ### Fixed +- Diff-aware gates in a pull request are judged against the branch the request targets + (`GITHUB_BASE_REF`, GitLab's `CI_MERGE_REQUEST_TARGET_BRANCH_NAME`, Bitbucket's + `BITBUCKET_PR_DESTINATION_BRANCH`), not origin's default branch. A request stacked on + another branch could pass a `no-fewer` gate after dropping test cases, because the + count was compared with the default branch. A target that is not in the checkout + fails closed with a fetch hint; `--base` and `SKILLGATE_BASE` still win. - Pattern gates (`absent`, `file-contains`, `no-new`, `no-fewer`, `commit-messages`) match under the run deadline: a pattern that backtracks catastrophically fails its gate with a reason naming the file instead of wedging the hook past its timeout. diff --git a/docs/spec-reference.md b/docs/spec-reference.md index 057b624..bd5c2c3 100644 --- a/docs/spec-reference.md +++ b/docs/spec-reference.md @@ -232,7 +232,10 @@ judged. `ignore` also matches script names (`ignore: ["test:*"]`). ### `no-new`, `no-fewer`, `no-deleted` (diff-aware) These gates compare the working tree with the commit the change forked from -(`--base `, `SKILLGATE_BASE`, or origin's default branch). Without a resolvable +(`--base `, `SKILLGATE_BASE`, the branch a CI pull request targets, or origin's +default branch). The pull request's target comes from `GITHUB_BASE_REF`, +`CI_MERGE_REQUEST_TARGET_BRANCH_NAME` or `BITBUCKET_PR_DESTINATION_BRANCH` and must +be in the checkout (`fetch-depth: 0`). Without a resolvable base they fail closed. The one exception is a repository with no commits at all: its first commit is judged against the empty tree. diff --git a/src/cli.ts b/src/cli.ts index 5e07429..0a0d88b 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -14,7 +14,7 @@ import { doctor, installIntegration, INTEGRATION_TARGETS, STOP_TARGETS, type Int import { analyzeCommand } from "./command.js"; import { reviewSnapshot } from "./review.js"; import { EVALUATOR_VERSION, cacheDisabledReason, receiptPathIsInput, readCachedResult, runSnapshot, verifyReceipt, writeCachedResult, writeReceipt } from "./receipt.js"; -import { resolveBaseRef, mergeBase, readFileAtRef, repoRelativePath, repoRoot, isClean } from "./git.js"; +import { ciTargetBranch, resolveBaseRef, mergeBase, readFileAtRef, repoRelativePath, repoRoot, isClean } from "./git.js"; import { createPrivatePassProof, generateKeyFiles, @@ -303,6 +303,10 @@ function resolveSpecAndBase(specPath: string | null): Resolved { if (!rawBase && (baseArg?.trim() || process.env.SKILLGATE_BASE?.trim())) { throw new Error("requested base ref cannot be resolved — refusing to use a different baseline"); } + const target = ciTargetBranch(); + if (!rawBase && target) { + throw new Error(`the pull request's target branch ${target} is not in this checkout (fetch it, e.g. actions/checkout with fetch-depth: 0) — refusing to use a different baseline`); + } const gateBase = rawBase ? mergeBase(workspace, rawBase) : undefined; if (!pin) { diff --git a/src/git.ts b/src/git.ts index 72377f9..5a4473a 100644 --- a/src/git.ts +++ b/src/git.ts @@ -52,6 +52,11 @@ function refExists(cwd: string, ref: string): boolean { export function resolveBaseRef(cwd: string, requested?: string): string | null { const explicit = requested?.trim() || process.env.SKILLGATE_BASE?.trim(); if (explicit) return refExists(cwd, explicit) ? explicit : null; + // A pull or merge request is judged against the branch it targets, which is not + // always origin's default branch (stacked changes, release branches). The target + // must resolve: falling back to the default branch would judge the wrong diff. + const target = ciTargetBranch(); + if (target) return [`origin/${target}`, target].find((ref) => refExists(cwd, ref)) ?? null; const originHead = (() => { try { return execFileSync("git", ["symbolic-ref", "refs/remotes/origin/HEAD"], { cwd, ...GIT_OPTS }) @@ -74,6 +79,18 @@ export function resolveBaseRef(cwd: string, requested?: string): string | null { return null; } +/** CI variables naming the branch a pull or merge request targets, in lookup order. */ +const CI_TARGET_VARS = ["GITHUB_BASE_REF", "CI_MERGE_REQUEST_TARGET_BRANCH_NAME", "BITBUCKET_PR_DESTINATION_BRANCH"]; + +/** The branch the CI run's pull or merge request targets, or undefined outside one (push events leave it empty). */ +export function ciTargetBranch(): string | undefined { + for (const name of CI_TARGET_VARS) { + const value = process.env[name]?.trim(); + if (value) return value; + } + return undefined; +} + /** Git's well-known empty tree object. */ export const EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"; diff --git a/test/release-0161-more.test.ts b/test/release-0161-more.test.ts new file mode 100644 index 0000000..7ca4714 --- /dev/null +++ b/test/release-0161-more.test.ts @@ -0,0 +1,79 @@ +// Tests for 0.16.1: the pull request's target branch as the diff base, heredoc bodies +// as data, dry runs that are not finish lines, and shallow-clone base errors. +// Fixtures are real throwaway Git repositories. +import test from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { execFileSync, spawnSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; + +const CLI = fileURLToPath(new URL("../src/cli.js", import.meta.url)); +const CI_VARS = ["GITHUB_BASE_REF", "CI_MERGE_REQUEST_TARGET_BRANCH_NAME", "BITBUCKET_PR_DESTINATION_BRANCH", "SKILLGATE_BASE"]; + +function cleanEnv(extra: Record = {}): NodeJS.ProcessEnv { + const env = { ...process.env }; + for (const name of CI_VARS) delete env[name]; + return { ...env, ...extra }; +} + +function git(dir: string, ...args: string[]): string { + return execFileSync("git", args, { cwd: dir, encoding: "utf8", env: cleanEnv() }).trim(); +} + +function sg(dir: string, args: string[], env: Record = {}) { + return spawnSync(process.execPath, [CLI, ...args], { cwd: dir, encoding: "utf8", env: cleanEnv(env) }); +} + +function tmp(t: { after: (fn: () => void) => void }): string { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "skillgate-0161b-")); + t.after(() => fs.rmSync(dir, { recursive: true, force: true })); + return dir; +} + +const POLICY = "finishLine: [\"git push\"]\ngates:\n - id: tests-kept\n type: no-fewer\n glob: \"test/**\"\n pattern: \"it\\\\(\"\n"; + +/** main has one test case, develop three; the feature branch, stacked on develop, drops one. */ +function stacked(t: { after: (fn: () => void) => void }): string { + const dir = tmp(t); + git(dir, "init", "-q", "-b", "main"); + git(dir, "config", "user.email", "t@example.com"); + git(dir, "config", "user.name", "t"); + git(dir, "config", "commit.gpgsign", "false"); + fs.mkdirSync(path.join(dir, ".skillgate")); + fs.mkdirSync(path.join(dir, "test")); + fs.writeFileSync(path.join(dir, ".skillgate", "done.yaml"), POLICY); + fs.writeFileSync(path.join(dir, "test", "a.js"), "it(1)\n"); + git(dir, "add", "-A"); + git(dir, "commit", "-qm", "m1"); + git(dir, "checkout", "-qb", "develop"); + fs.writeFileSync(path.join(dir, "test", "a.js"), "it(1)\nit(2)\nit(3)\n"); + git(dir, "commit", "-qam", "d1"); + git(dir, "checkout", "-qb", "feature"); + fs.writeFileSync(path.join(dir, "test", "a.js"), "it(1)\nit(2)\n"); + git(dir, "commit", "-qam", "drop a test"); + return dir; +} + +test("check judges a pull request against the branch it targets, not the default branch", t => { + const dir = stacked(t); + const github = sg(dir, ["check"], { GITHUB_BASE_REF: "develop" }); + assert.equal(github.status, 1, github.stdout + github.stderr); + assert.match(github.stdout, /tests-kept.*base 3, now 2/); + const gitlab = sg(dir, ["check"], { CI_MERGE_REQUEST_TARGET_BRANCH_NAME: "develop" }); + assert.equal(gitlab.status, 1, gitlab.stdout + gitlab.stderr); + // A push event leaves GITHUB_BASE_REF empty: the default branch stays the base. + const push = sg(dir, ["check"], { GITHUB_BASE_REF: "" }); + assert.equal(push.status, 0, push.stdout + push.stderr); +}); + +test("check refuses a pull request whose target branch is not in the checkout", t => { + const dir = stacked(t); + const out = sg(dir, ["check"], { GITHUB_BASE_REF: "release-9" }); + assert.equal(out.status, 2); + assert.match(out.stderr, /target branch release-9 is not in this checkout/); + // An explicit base still wins over the CI target. + const explicit = sg(dir, ["check", "--base", "main"], { GITHUB_BASE_REF: "release-9" }); + assert.equal(explicit.status, 0, explicit.stdout + explicit.stderr); +}); From 3aa462a5ebb61238aeb7598d20c782cd5ea6ae7f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Zander?= <96420681+renezander030@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:55:14 +0000 Subject: [PATCH 08/13] Read here-document bodies as data in finish-line matching A commit message or note written through a here-document no longer counts as a finish line because one of its lines names one. The body still counts when a shell may read it, and an unquoted body's command substitutions still count. --- CHANGELOG.md | 5 ++ src/command.ts | 96 ++++++++++++++++++++++++++++++++-- test/release-0161-more.test.ts | 17 ++++++ 3 files changed, 115 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dbf082c..f7bd9ec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,11 @@ dangling link or a link to a non-file is refused either way. ### Fixed +- Finish-line matching reads a here-document body as data: a commit message passed with + `git commit -F- <<'EOF'` or a note written with `cat > notes.md <()]/.test(command[j]); j++) { + const ch = command[j]; + if (ch === "'" || ch === '"') { + quoted = true; + const close = command.indexOf(ch, j + 1); + if (close < 0) return null; + word += command.slice(j + 1, close); + j = close; + } else if (ch === "\\") { + quoted = true; + word += command[++j] ?? ""; + } else word += ch; + } + return word ? { end: j, delimiter: word, strip, quoted } : null; +} + +/** + * Split only on unquoted shell control operators. Here-document bodies are not + * commands of the line that opens them: they are collected into `heredocs` and + * left out of the segments. + */ +export function splitCommand(command: string, heredocs: Heredoc[] = []): string[] { const out: string[] = []; let current = ""; let quote = ""; let escaped = false; + const open: { delimiter: string; strip: boolean; quoted: boolean }[] = []; for (let i = 0; i < command.length; i++) { const ch = command[i]; + if (!escaped && !quote && ch === "<") { + const doc = heredocAt(command, i); + if (doc) { + open.push(doc); + current += command.slice(i, doc.end); + i = doc.end - 1; + continue; + } + } + if (!escaped && !quote && ch === "\n" && open.length) { + if (current.trim()) out.push(current.trim()); + current = ""; + let pos = i + 1; + for (const doc of open) { + const lines: string[] = []; + while (pos < command.length) { + const eol = command.indexOf("\n", pos); + const line = command.slice(pos, eol < 0 ? command.length : eol).replace(/\r$/, ""); + pos = eol < 0 ? command.length : eol + 1; + if ((doc.strip ? line.replace(/^\t+/, "") : line) === doc.delimiter) break; + lines.push(line); + } + heredocs.push({ body: lines.join("\n"), quoted: doc.quoted }); + } + open.length = 0; + i = pos - 1; + continue; + } if (escaped) { current += ch; escaped = false; @@ -295,10 +360,35 @@ function commandSubstitutions(raw: string): string[] { return out; } +/** + * True when a shell (or a remote one, through ssh) may be reading commands from stdin, + * so a here-document fed to the line could run: `bash < { + const tokens = tokenizeCommand(raw); + return tokens.some((token, i) => { + const name = executableName(token); + if (name === "ssh") return true; + if (!SHELLS.has(name) || name === "eval") return false; + return nestedShellCommands(tokens.slice(i)).length === 0; + }); + }); +} + +/** Commands an unquoted here-document still runs: its `$(...)` and backtick substitutions. Quotes are literal there. */ +function heredocCommands(heredocs: Heredoc[], segments: string[]): string[] { + if (shellReadsStdin(segments)) return heredocs.flatMap((doc) => splitCommand(doc.body)); + return heredocs.filter((doc) => !doc.quoted).flatMap((doc) => commandSubstitutions(doc.body.replace(/['"]/g, " "))); +} + export function analyzeCommand(command: string, patterns: string[] = []): CommandMatch { const segments: CommandSegment[] = []; const vars = new Map(); - const pending = splitCommand(command); + const heredocs: Heredoc[] = []; + const pending = splitCommand(command, heredocs); + pending.push(...heredocCommands(heredocs, pending)); for (let i = 0; i < pending.length; i++) { const raw = pending[i]; const tokens = tokenizeCommand(raw); diff --git a/test/release-0161-more.test.ts b/test/release-0161-more.test.ts index 7ca4714..74420f6 100644 --- a/test/release-0161-more.test.ts +++ b/test/release-0161-more.test.ts @@ -8,6 +8,7 @@ import os from "node:os"; import path from "node:path"; import { execFileSync, spawnSync } from "node:child_process"; import { fileURLToPath } from "node:url"; +import { isStructuredCommandMatch } from "../src/command.js"; const CLI = fileURLToPath(new URL("../src/cli.js", import.meta.url)); const CI_VARS = ["GITHUB_BASE_REF", "CI_MERGE_REQUEST_TARGET_BRANCH_NAME", "BITBUCKET_PR_DESTINATION_BRANCH", "SKILLGATE_BASE"]; @@ -77,3 +78,19 @@ test("check refuses a pull request whose target branch is not in the checkout", const explicit = sg(dir, ["check", "--base", "main"], { GITHUB_BASE_REF: "release-9" }); assert.equal(explicit.status, 0, explicit.stdout + explicit.stderr); }); + +test("a here-document body is data unless a shell reads it", () => { + const push = ["git push"]; + // Data: a commit message or a note that mentions the finish line. + assert.equal(isStructuredCommandMatch("git commit -F- <<'EOF'\nfix: retry\ngit push follows after review\nEOF", push), false); + assert.equal(isStructuredCommandMatch("cat > notes.md < n.md\nsee $(git push)\nEOF", push), false); + assert.equal(isStructuredCommandMatch("cat < n.md\nsee $(git push)\nEOF", push), true); + assert.equal(isStructuredCommandMatch("bash < n\n\tgit push\n\tEOF\ngit push", push), true); + assert.equal(isStructuredCommandMatch("git push <<< y", push), true); +}); From 4f563b72539db0cf607a8c3650851182a66a9209 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Zander?= <96420681+renezander030@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:55:14 +0000 Subject: [PATCH 09/13] A dry run is not a finish line npm publish --dry-run, git push --dry-run, git push -n and other matched commands with --dry-run before -- are allowed while gates are unmet. --- CHANGELOG.md | 5 +++++ src/command.ts | 14 +++++++++++++- test/release-0161-more.test.ts | 11 +++++++++++ 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f7bd9ec..ddcff00 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,11 @@ dangling link or a link to a non-file is refused either way. ### Fixed +- A dry run is not a finish line: `npm publish --dry-run`, `git push --dry-run`, + `git push -n`, `git commit --dry-run` and any matched command with `--dry-run` before + `--` are allowed while gates are unmet, so an agent can check a release before it is + done. `git commit -n` (which skips hooks) and `npm run release -- --dry-run` are still + finish lines. - Finish-line matching reads a here-document body as data: a commit message passed with `git commit -F- <<'EOF'` or a note written with `cat > notes.md < token.toLowerCase()); + if (options.includes("--dry-run")) return true; + return executableName(tokens[0] ?? "") === "git" && options[0] === "push" && options.includes("-n"); +} + /** Commands `find` runs through -exec/-execdir/-ok/-okdir. */ function findExecCommands(tokens: string[]): string[] { if (!tokens.length || executableName(tokens[0]) !== "find") return []; @@ -407,7 +419,7 @@ export function analyzeCommand(command: string, patterns: string[] = []): Comman const matchedPatterns: string[] = []; for (const pattern of patterns) { const wanted = canonicalize(unwrap(tokenizeCommand(pattern))); - if (segments.some((segment) => orderedMatch(segment.normalized, wanted))) matchedPatterns.push(pattern); + if (segments.some((segment) => !isDryRun(segment.normalized) && orderedMatch(segment.normalized, wanted))) matchedPatterns.push(pattern); } return { matched: matchedPatterns.length > 0, patterns: matchedPatterns, segments }; } diff --git a/test/release-0161-more.test.ts b/test/release-0161-more.test.ts index 74420f6..61a51d3 100644 --- a/test/release-0161-more.test.ts +++ b/test/release-0161-more.test.ts @@ -94,3 +94,14 @@ test("a here-document body is data unless a shell reads it", () => { assert.equal(isStructuredCommandMatch("cat <<-EOF > n\n\tgit push\n\tEOF\ngit push", push), true); assert.equal(isStructuredCommandMatch("git push <<< y", push), true); }); + +test("a dry run does not reach the finish line", () => { + const line = ["git push", "git commit", "npm publish", "cargo publish", "npm run release"]; + for (const command of ["git push --dry-run", "git push -n origin main", "git commit --dry-run -m x", "npm publish --dry-run", "cargo publish --dry-run"]) { + assert.equal(isStructuredCommandMatch(command, line), false, command); + } + // Real finish lines stay gated, dry run or not elsewhere on the line. + for (const command of ["git push", "git commit -n -m x", "git push --dry-run && git push", "npm run release -- --dry-run", "npm publish --tag next"]) { + assert.equal(isStructuredCommandMatch(command, line), true, command); + } +}); From 828efd153f0a3bf3172b430f6a2bcf4b1064001c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Zander?= <96420681+renezander030@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:55:14 +0000 Subject: [PATCH 10/13] Name the fetch that fixes a shallow clone's missing fork point Diff-aware gates in a shallow clone without the fork point say the clone is shallow and how to fetch its history. The run still fails closed. --- CHANGELOG.md | 4 ++++ src/git.ts | 12 ++++++++++++ test/release-0161-more.test.ts | 17 +++++++++++++++++ 3 files changed, 33 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ddcff00..577aa25 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,10 @@ dangling link or a link to a non-file is refused either way. ### Fixed +- In a shallow clone whose history stops before the fork point, diff-aware gates now say + so and name the fetch that fixes it (`fetch-depth: 0`, `GIT_DEPTH: 0`, or + `git fetch --unshallow`) instead of calling the baseline unrelated or unreadable. The + run still fails closed. - A dry run is not a finish line: `npm publish --dry-run`, `git push --dry-run`, `git push -n`, `git commit --dry-run` and any matched command with `--dry-run` before `--` are allowed while gates are unmet, so an agent can check a release before it is diff --git a/src/git.ts b/src/git.ts index 5a4473a..1971f6e 100644 --- a/src/git.ts +++ b/src/git.ts @@ -120,10 +120,22 @@ export function mergeBase(cwd: string, ref: string): string { try { return execFileSync("git", ["merge-base", ref, "HEAD"], { cwd, ...GIT_OPTS }).trim(); } catch { + if (isShallow(cwd)) { + throw new Error(`cannot determine a common ancestor with ${ref} — this clone is shallow, so the fork point is not in it; fetch the history (actions/checkout with fetch-depth: 0, GIT_DEPTH: 0 in GitLab, or git fetch --unshallow)`); + } throw new Error(`cannot determine a common ancestor with ${ref} — refusing an unrelated or unreadable baseline`); } } +/** True in a shallow clone, whose history may stop before the fork point. */ +function isShallow(cwd: string): boolean { + try { + return execFileSync("git", ["rev-parse", "--is-shallow-repository"], { cwd, ...GIT_OPTS }).trim() === "true"; + } catch { + return false; + } +} + /** Contents of `relPath` (repo-root-relative, posix) at `ref`, or null if it did not exist there. */ export function readFileAtRef(cwd: string, ref: string, relPath: string, strict = false): string | null { if (ref === EMPTY_TREE) return null; diff --git a/test/release-0161-more.test.ts b/test/release-0161-more.test.ts index 61a51d3..474656a 100644 --- a/test/release-0161-more.test.ts +++ b/test/release-0161-more.test.ts @@ -95,6 +95,23 @@ test("a here-document body is data unless a shell reads it", () => { assert.equal(isStructuredCommandMatch("git push <<< y", push), true); }); +test("a shallow clone without the fork point names the fetch that fixes it", t => { + const src = stacked(t); + git(src, "checkout", "-q", "main"); + fs.writeFileSync(path.join(src, "x"), "x\n"); + git(src, "add", "x"); + git(src, "commit", "-qm", "m2"); + const dir = path.join(tmp(t), "clone"); + execFileSync("git", ["clone", "-q", "--depth", "1", "--branch", "feature", "--no-single-branch", `file://${src}`, dir], { env: cleanEnv() }); + const out = sg(dir, ["check"]); + assert.equal(out.status, 2); + assert.match(out.stderr, /this clone is shallow.*fetch-depth: 0/); + // A full clone is judged as before. + const full = path.join(tmp(t), "full"); + execFileSync("git", ["clone", "-q", "--branch", "feature", src, full], { env: cleanEnv() }); + assert.equal(sg(full, ["check"]).status, 0); +}); + test("a dry run does not reach the finish line", () => { const line = ["git push", "git commit", "npm publish", "cargo publish", "npm run release"]; for (const command of ["git push --dry-run", "git push -n origin main", "git commit --dry-run -m x", "npm publish --dry-run", "cargo publish --dry-run"]) { From 389f1b4364d6cc2909474892bc179e8f3589563a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Zander?= <96420681+renezander030@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:55:15 +0000 Subject: [PATCH 11/13] Tidy-up: 3 behavior-preserving refactors and the finish-line reference One best-effort git runner behind the git module's null-on-failure contract, the base-ref refusal rules next to the resolution order, and the here-document body reader outside the command splitter loop. The spec reference documents the here-document and dry-run matching rules. --- docs/spec-reference.md | 6 +++- src/cli.ts | 11 ++---- src/command.ts | 26 +++++++++------ src/git.ts | 76 +++++++++++++++++++----------------------- 4 files changed, 58 insertions(+), 61 deletions(-) diff --git a/docs/spec-reference.md b/docs/spec-reference.md index bd5c2c3..a241758 100644 --- a/docs/spec-reference.md +++ b/docs/spec-reference.md @@ -24,7 +24,11 @@ launchers without matching quoted prose. Process wrappers (`timeout`, `nice`, `ionice`, `stdbuf`, `xargs`, `watch`, `doas`) and `find -exec`/`-execdir` are unwrapped too. A program or subcommand the shell only decides at run time fails closed: `git $(echo push)` and `git "$SUB"` match every `git` pattern, and -`g=git; $g push` or `"$(which git)" push` resolve to `git push`. Run +`g=git; $g push` or `"$(which git)" push` resolve to `git push`. A here-document +body is data (`git commit -F- <<'EOF'` with a message that names `git push`) unless a +shell may read it (`bash < refExists(cwd, ref)) ?? null; - const originHead = (() => { - try { - return execFileSync("git", ["symbolic-ref", "refs/remotes/origin/HEAD"], { cwd, ...GIT_OPTS }) - .trim() - .replace(/^refs\/remotes\//, ""); - } catch { - return undefined; - } - })(); + const originHead = gitOutput(cwd, ["symbolic-ref", "refs/remotes/origin/HEAD"])?.trim().replace(/^refs\/remotes\//, ""); const candidates = [originHead, "origin/main", "origin/master", "main", "master"] .map((r) => r?.trim()) .filter((r): r is string => !!r); @@ -82,8 +75,23 @@ export function resolveBaseRef(cwd: string, requested?: string): string | null { /** CI variables naming the branch a pull or merge request targets, in lookup order. */ const CI_TARGET_VARS = ["GITHUB_BASE_REF", "CI_MERGE_REQUEST_TARGET_BRANCH_NAME", "BITBUCKET_PR_DESTINATION_BRANCH"]; +/** + * Why no base resolved when the caller named one, or null when falling back is + * allowed: an explicit `--base`/`SKILLGATE_BASE`, or the branch a CI pull request + * targets, must resolve; Skillgate never judges against a different branch. + */ +export function baseRefProblem(requested?: string): string | null { + if (requested?.trim() || process.env.SKILLGATE_BASE?.trim()) { + return "requested base ref cannot be resolved — refusing to use a different baseline"; + } + const target = ciTargetBranch(); + return target + ? `the pull request's target branch ${target} is not in this checkout (fetch it, e.g. actions/checkout with fetch-depth: 0) — refusing to use a different baseline` + : null; +} + /** The branch the CI run's pull or merge request targets, or undefined outside one (push events leave it empty). */ -export function ciTargetBranch(): string | undefined { +function ciTargetBranch(): string | undefined { for (const name of CI_TARGET_VARS) { const value = process.env[name]?.trim(); if (value) return value; @@ -101,12 +109,8 @@ export function baseLabel(ref: string): string { /** True inside a git repository that has no commits on any ref. */ function hasNoCommits(cwd: string): boolean { - try { - execFileSync("git", ["rev-parse", "--git-dir"], { cwd, ...GIT_OPTS }); - return execFileSync("git", ["rev-list", "-n", "1", "--all"], { cwd, ...GIT_OPTS }).trim() === ""; - } catch { - return false; - } + if (gitOutput(cwd, ["rev-parse", "--git-dir"]) === null) return false; + return gitOutput(cwd, ["rev-list", "-n", "1", "--all"])?.trim() === ""; } /** @@ -129,11 +133,7 @@ export function mergeBase(cwd: string, ref: string): string { /** True in a shallow clone, whose history may stop before the fork point. */ function isShallow(cwd: string): boolean { - try { - return execFileSync("git", ["rev-parse", "--is-shallow-repository"], { cwd, ...GIT_OPTS }).trim() === "true"; - } catch { - return false; - } + return gitOutput(cwd, ["rev-parse", "--is-shallow-repository"])?.trim() === "true"; } /** Contents of `relPath` (repo-root-relative, posix) at `ref`, or null if it did not exist there. */ @@ -206,11 +206,8 @@ export function changedFiles(cwd: string, ref: string): string[] | null { /** True when the worktree has no staged, unstaged or untracked changes. Null outside git. */ export function isClean(cwd: string): boolean | null { - try { - return execFileSync("git", ["status", "--porcelain"], { cwd, ...GIT_OPTS }).trim() === ""; - } catch { - return null; - } + const status = gitOutput(cwd, ["status", "--porcelain"]); + return status === null ? null : status.trim() === ""; } /** @@ -221,12 +218,9 @@ export function isClean(cwd: string): boolean | null { export function currentBranch(cwd: string): string | undefined { const fromEnv = process.env.SKILLGATE_BRANCH?.trim(); if (fromEnv) return fromEnv; - try { - const name = execFileSync("git", ["symbolic-ref", "--quiet", "--short", "HEAD"], { cwd, ...GIT_OPTS }).trim(); - if (name) return name; - } catch { - /* detached HEAD or not a repo */ - } + // Null on a detached HEAD or outside a repository. + const name = gitOutput(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"])?.trim(); + if (name) return name; return process.env.GITHUB_HEAD_REF?.trim() || process.env.GITHUB_REF_NAME?.trim() || undefined; } From 988c4c67405daa0ebc36459d406367dd7b782568 Mon Sep 17 00:00:00 2001 From: Rene Zander <96420681+renezander030@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:32:11 +0100 Subject: [PATCH 12/13] Tests run without the CI run's pull-request branch variables A pull_request run sets GITHUB_BASE_REF (and GITHUB_HEAD_REF/GITHUB_REF_NAME); skillgate now judges a pull request against that target branch, so every throwaway fixture repo, which has neither branch, failed closed: PR #62, 41 of 275 tests on every OS, the coverage gate too. scripts/run-tests.mjs starts the tests without those variables (and SKILLGATE_BASE); a test keeps it that way. Co-Authored-By: Claude Opus 5.5 Session: claude:18a53163-916a-41e1-9aa7-a20e56ad87c1 --- scripts/run-tests.mjs | 16 ++++++++++++++++ test/test-env.test.ts | 11 +++++++++++ 2 files changed, 27 insertions(+) create mode 100644 test/test-env.test.ts diff --git a/scripts/run-tests.mjs b/scripts/run-tests.mjs index 0a94f08..f2524d2 100644 --- a/scripts/run-tests.mjs +++ b/scripts/run-tests.mjs @@ -13,8 +13,24 @@ if (!files.length) { process.exit(1); } +// A CI pull-request run names the branches of the repository under test (GITHUB_BASE_REF and its GitLab/Bitbucket +// twins, GITHUB_HEAD_REF, GITHUB_REF_NAME). Skillgate judges a pull request against that target branch, so in the +// tests every throwaway fixture repo, which has neither branch, failed closed: release 0.16.1, PR #62, 41 of 275 +// tests on every OS. The tests run without them; SKILLGATE_BASE too, as a test sets it where it means it. +export const CI_REPO_VARS = [ + "GITHUB_BASE_REF", + "GITHUB_HEAD_REF", + "GITHUB_REF_NAME", + "CI_MERGE_REQUEST_TARGET_BRANCH_NAME", + "BITBUCKET_PR_DESTINATION_BRANCH", + "SKILLGATE_BASE", +]; +const env = { ...process.env }; +for (const name of CI_REPO_VARS) delete env[name]; + const result = spawnSync(process.execPath, [...process.argv.slice(2), "--test", ...files], { stdio: "inherit", + env, }); if (result.error) throw result.error; process.exit(result.status ?? 1); diff --git a/test/test-env.test.ts b/test/test-env.test.ts new file mode 100644 index 0000000..f279f32 --- /dev/null +++ b/test/test-env.test.ts @@ -0,0 +1,11 @@ +// The tests never see the branches of the repository a CI run builds: skillgate reads them, and a fixture repo has +// none of them (release 0.16.1, PR #62: GITHUB_BASE_REF=master made 41 tests fail closed on every OS). +import test from "node:test"; +import assert from "node:assert/strict"; + +test("a CI run's pull-request branch variables never reach the tests", () => { + for (const name of ["GITHUB_BASE_REF", "GITHUB_HEAD_REF", "GITHUB_REF_NAME", "CI_MERGE_REQUEST_TARGET_BRANCH_NAME", + "BITBUCKET_PR_DESTINATION_BRANCH", "SKILLGATE_BASE"]) { + assert.equal(process.env[name], undefined, `${name} reached the tests`); + } +}); From 739452ed3d4f3c370dfc55fbb38eefb602bc8c09 Mon Sep 17 00:00:00 2001 From: Rene Zander <96420681+renezander030@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:45:57 +0100 Subject: [PATCH 13/13] CI's self-check fetches the target branch; the Devin doctor test reads either path separator; 0.16.1 says how to upgrade a shallow PR checkout PR #62 on 988c4c674: the dogfood 'skillgate check' in ci.yml's test job ran in a shallow checkout and failed closed (exit 2) under 0.16.1's new rule that a pull request is judged against its target branch; the test job now checks out with fetch-depth: 0, and contrib/github-action.yml does the same. The Devin doctor test expected '/' and Windows prints '.devin\hooks.v1.json'. The CHANGELOG entry carries an upgrade note and the README's CI section says what the checkout needs. Co-Authored-By: Claude Opus 5.5 Session: claude:18a53163-916a-41e1-9aa7-a20e56ad87c1 --- .github/workflows/ci.yml | 2 ++ CHANGELOG.md | 6 ++++++ README.md | 4 ++++ contrib/github-action.yml | 2 ++ test/release-0161.test.ts | 2 +- 5 files changed, 15 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3027895..8d26cdd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -15,6 +15,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 # the dogfood check below judges a pull request against its target branch - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: '20' diff --git a/CHANGELOG.md b/CHANGELOG.md index 577aa25..edc6125 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,12 @@ another branch could pass a `no-fewer` gate after dropping test cases, because the count was compared with the default branch. A target that is not in the checkout fails closed with a fetch hint; `--base` and `SKILLGATE_BASE` still win. + **Upgrade note:** a pull-request CI job that runs `skillgate check` from a shallow + checkout (`actions/checkout`'s default `fetch-depth: 1`) now stops with exit 2 and + "the pull request's target branch ... is not in this checkout". Fix: set + `fetch-depth: 0` on `actions/checkout`, or fetch the target branch before the check + (`git fetch origin "$GITHUB_BASE_REF"`). The workflow from + `skillgate install github-actions` already fetches full history. - Pattern gates (`absent`, `file-contains`, `no-new`, `no-fewer`, `commit-messages`) match under the run deadline: a pattern that backtracks catastrophically fails its gate with a reason naming the file instead of wedging the hook past its timeout. diff --git a/README.md b/README.md index 52415d1..856f3f4 100644 --- a/README.md +++ b/README.md @@ -514,6 +514,10 @@ These need no harness integration at all, which makes them the universal backsto In GitHub Actions, `skillgate check --format github` turns each failing gate into an error annotation on the file and line it names, so the PR shows the problem in place, and writes a result table to the job summary. The workflow from `skillgate install github-actions` uses it. +In a pull request, diff-aware gates are judged against the branch the request targets, so +the checkout must contain it: use `actions/checkout` with `fetch-depth: 0` (the installed +workflow does), or fetch the target branch first. A shallow checkout fails closed with +exit 2 and says which branch to fetch. Native Windows hook files are included in [`contrib/claude-code`](contrib/claude-code/): the PowerShell adapter resolves `npx.cmd`, preserves the hook payload on stdin, and diff --git a/contrib/github-action.yml b/contrib/github-action.yml index cb0ee9b..d22338f 100644 --- a/contrib/github-action.yml +++ b/contrib/github-action.yml @@ -12,6 +12,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + with: + fetch-depth: 0 # a pull request is judged against its target branch - uses: actions/setup-node@v4 with: node-version: '20' diff --git a/test/release-0161.test.ts b/test/release-0161.test.ts index faba0f2..15144e2 100644 --- a/test/release-0161.test.ts +++ b/test/release-0161.test.ts @@ -101,7 +101,7 @@ test("install devin registers a fail-closed exec hook and gate judges Devin's ex assert.equal(hooks.PreToolUse[0].matcher, "exec"); assert.match(hooks.PreToolUse[0].hooks[0].command, /@reneza\/skillgate@\S+ gate --timeout 540000 \|\| exit 2$/); assert.equal(sg(dir, ["install", "devin"]).stdout.includes("already registered"), true); - assert.match(sg(dir, ["doctor", "devin"]).stdout, /devin\s+configured in \.devin\/hooks\.v1\.json/); + assert.match(sg(dir, ["doctor", "devin"]).stdout, /devin\s+configured in \.devin[\\/]hooks\.v1\.json/); const payload = JSON.stringify({ hook_event_name: "PreToolUse", tool_name: "exec", tool_input: { command: "git push origin main" }, session_id: "s1" }); const blocked = sg(dir, ["gate"], payload);