Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
47 changes: 47 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,54 @@

## Unreleased

## 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 <target> --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
- 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
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 <<EOF` no longer counts
as a finish line because a line of it mentions `git push`. The body still counts when a
shell may run it (`bash <<EOF`, `cat <<EOF | sh`, `ssh host <<EOF`), and the `$(...)`
and backtick substitutions of an unquoted body still count.
- 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.
**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.
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 <log>` 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`.

Expand Down
21 changes: 19 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -180,6 +181,14 @@ 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
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
Expand Down Expand Up @@ -365,8 +374,12 @@ 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 <file>` replays a command list, or the log
itself, against the current `finishLine` before you change it.
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 <file>` replays a command list, or the log
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
Expand Down Expand Up @@ -501,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
Expand Down
2 changes: 2 additions & 0 deletions contrib/github-action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
11 changes: 9 additions & 2 deletions docs/spec-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <<EOF`, `cat <<EOF | sh`, `ssh host <<EOF`); the `$(...)`
substitutions of an unquoted body still count. A dry run (`--dry-run` before any `--`,
or `git push -n`) does not cross the finish line. Run
`skillgate explain --command "..."` to inspect the decision without executing gates.

Runtime loading enforces the same closed shape as the JSON Schema: unknown fields,
Expand Down Expand Up @@ -232,7 +236,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 <ref>`, `SKILLGATE_BASE`, or origin's default branch). Without a resolvable
(`--base <ref>`, `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.

Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@reneza/skillgate",
"version": "0.16.0",
"version": "0.16.1",
"publishConfig": {
"access": "public"
},
Expand Down
16 changes: 16 additions & 0 deletions scripts/run-tests.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
49 changes: 17 additions & 32 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@ 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, 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";
import { doctor, installIntegration, INTEGRATION_TARGETS, STOP_TARGETS, type IntegrationTarget } from "./integrations.js";
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 { baseRefProblem, resolveBaseRef, mergeBase, readFileAtRef, repoRelativePath, repoRoot, isClean } from "./git.js";
import {
createPrivatePassProof,
generateKeyFiles,
Expand Down Expand Up @@ -99,7 +99,7 @@ Usage:
skillgate init [--preset <name>] 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 <target|all> 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 <target|all> verify policy discovery and one or more integrations
skillgate explain --command <cmd> show structural finish-line matching without running gates
skillgate explain --commands <f> replay a command corpus (lines or a decision log; - = stdin)
Expand Down Expand Up @@ -128,6 +128,7 @@ Flags:
--tool <name> gate: judge an agent tool call (gatedTools) instead of a command
--gate <id> 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 <ms> check/gate: cap the complete gate run (overrides spec timeout)
--cache check: reuse a passing result only for the exact repo snapshot
--receipt <file> check: write a machine-readable execution receipt
Expand Down Expand Up @@ -299,9 +300,8 @@ function resolveSpecAndBase(specPath: string | null): Resolved {
const specPathHint = specPath && fs.existsSync(specPath) ? specPath : null;
const workspace = workspaceRoot(specPathHint, cwd);
const rawBase = resolveBaseRef(workspace, baseArg);
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 baseProblem = rawBase ? null : baseRefProblem(baseArg);
if (baseProblem) throw new Error(baseProblem);
const gateBase = rawBase ? mergeBase(workspace, rawBase) : undefined;

if (!pin) {
Expand All @@ -328,7 +328,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 } {
Expand Down Expand Up @@ -646,10 +646,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);
Expand All @@ -665,25 +666,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`). */
function readCorpus(source: string): string[] {
const text = source === "-" ? fs.readFileSync(0, "utf8") : fs.readFileSync(path.resolve(cwd, source), "utf8");
const commands: string[] = [];
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 {
/* a command that starts with "{" */
}
}
commands.push(trimmed);
}
return commands;
/** Commands from a corpus file or stdin (`-`); see corpusCommands for the line rules. */
function readCorpus(source: string): { commands: string[]; skipped: number } {
return corpusCommands(source === "-" ? fs.readFileSync(0, "utf8") : fs.readFileSync(path.resolve(cwd, source), "utf8"));
}

if (cmd === "explain") {
Expand All @@ -695,7 +680,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) : [] };
Expand All @@ -704,13 +689,14 @@ if (cmd === "explain") {
const byPattern = new Map<string, number>();
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);
}
Expand All @@ -734,13 +720,12 @@ if (cmd === "explain") {
if (cmd === "log") {
const file = positionalPath() ?? logPath(undefined, cwd);
if (!file) die(2, "usage: skillgate log <file> (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);
Expand Down
Loading