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 75472e4..edc6125 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 --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 <` 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 22d2db6..856f3f4 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,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 @@ -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 ` 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 ` 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 @@ -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 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/docs/spec-reference.md b/docs/spec-reference.md index 057b624..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 <`, `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/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/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/src/cli.ts b/src/cli.ts index 2094aae..f3f0c47 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, 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"; @@ -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 { baseRefProblem, resolveBaseRef, mergeBase, readFileAtRef, repoRelativePath, repoRoot, isClean } from "./git.js"; import { createPrivatePassProof, generateKeyFiles, @@ -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) @@ -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 @@ -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) { @@ -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 } { @@ -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); @@ -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") { @@ -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) : [] }; @@ -704,13 +689,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); } @@ -734,13 +720,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/command.ts b/src/command.ts index 57401e4..b45dd1d 100644 --- a/src/command.ts +++ b/src/command.ts @@ -40,14 +40,83 @@ function executableName(value: string): string { return base.replace(/\.(exe|cmd|bat)$/i, ""); } -/** Split only on unquoted shell control operators. */ -export function splitCommand(command: string): string[] { +/** A here-document's body: data for the command that reads it, unless a shell reads it. */ +export interface Heredoc { + body: string; + /** A quoted delimiter (`<<'EOF'`) turns off expansion, so the body runs nothing. */ + quoted: boolean; +} + +/** The here-document operator at `start` (`<()]/.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; +} + +/** Read one here-document body from `pos` up to its delimiter line into `heredocs`; returns where the body ends. */ +function readHeredoc(command: string, pos: number, doc: { delimiter: string; strip: boolean; quoted: boolean }, heredocs: Heredoc[]): number { + 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 }); + return pos; +} + +/** + * 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) pos = readHeredoc(command, pos, doc, heredocs); + open.length = 0; + i = pos - 1; + continue; + } if (escaped) { current += ch; escaped = false; @@ -197,6 +266,18 @@ function orderedMatch(tokens: string[], pattern: string[]): boolean { }); } +/** + * A dry run changes nothing, so it does not reach the finish line: `--dry-run` before any + * `--` (`npm publish --dry-run`, `git push --dry-run`, `cargo publish --dry-run`), and + * `git push -n`. Elsewhere `-n` means something else (`git commit -n` skips hooks). + */ +function isDryRun(tokens: string[]): boolean { + const end = tokens.indexOf("--"); + const options = (end < 0 ? tokens : tokens.slice(0, end)).slice(1).map((token) => 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 []; @@ -295,10 +376,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); @@ -317,7 +423,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/src/core.ts b/src/core.ts index cb2b90a..87187df 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); @@ -371,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 re.test(text) + 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 } }; } @@ -385,12 +413,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)` }; } @@ -482,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)); @@ -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/src/files.ts b/src/files.ts index cbff2e4..6b23b66 100644 --- a/src/files.ts +++ b/src/files.ts @@ -3,17 +3,43 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -/** Replace one complete configuration, preserving the old file on failure. */ -export function writeTextAtomic(file: string, text: string): void { - fs.mkdirSync(path.dirname(file), { recursive: true }); - let mode = 0o600; +export interface WriteOptions { + /** Write through a symbolic link to the existing regular file it names, keeping the link. */ + followSymlink?: boolean; +} + +/** + * 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): { file: string; mode: number } { + let stat: fs.Stats; try { - const stat = fs.lstatSync(file); - if (!stat.isFile()) throw new Error(`refusing to replace a non-regular configuration: ${file}`); - mode = stat.mode & 0o777; + stat = fs.lstatSync(file); } catch (error: any) { - if (error?.code !== "ENOENT") throw error; + if (error?.code === "ENOENT") return { file, mode: 0o600 }; + throw error; } + 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; + 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; + } + 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(requested: string, text: string, opts: WriteOptions = {}): void { + const { file, mode } = writeTarget(requested, opts); + fs.mkdirSync(path.dirname(file), { recursive: true }); const temp = `${file}.${crypto.randomUUID()}.tmp`; try { fs.writeFileSync(temp, text, { mode, flag: "wx" }); diff --git a/src/git.ts b/src/git.ts index 72377f9..f5a7149 100644 --- a/src/git.ts +++ b/src/git.ts @@ -13,15 +13,21 @@ import { globSync } from "tinyglobby"; const GIT_OPTS = { stdio: "pipe" as const, encoding: "utf8" as const, maxBuffer: 64 * 1024 * 1024 }; -/** Absolute path of the repo root containing `cwd`, or null when not a repo. */ -export function repoRoot(cwd: string): string | null { +/** Output of a read-only git command, or null when it fails (not a repo, unknown ref, git missing). */ +function gitOutput(cwd: string, args: string[]): string | null { try { - return path.normalize(execFileSync("git", ["rev-parse", "--show-toplevel"], { cwd, ...GIT_OPTS }).trim()); + return execFileSync("git", args, { cwd, ...GIT_OPTS }); } catch { return null; } } +/** Absolute path of the repo root containing `cwd`, or null when not a repo. */ +export function repoRoot(cwd: string): string | null { + const root = gitOutput(cwd, ["rev-parse", "--show-toplevel"]); + return root === null ? null : path.normalize(root.trim()); +} + /** Git-root-relative path for `file`, robust to Windows short/long path aliases. */ export function repoRelativePath(cwd: string, file: string): string | null { try { @@ -35,12 +41,7 @@ export function repoRelativePath(cwd: string, file: string): string | null { } function refExists(cwd: string, ref: string): boolean { - try { - execFileSync("git", ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], { cwd, ...GIT_OPTS }); - return true; - } catch { - return false; - } + return gitOutput(cwd, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`]) !== null; } /** @@ -52,15 +53,12 @@ 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; - const originHead = (() => { - try { - return execFileSync("git", ["symbolic-ref", "refs/remotes/origin/HEAD"], { cwd, ...GIT_OPTS }) - .trim() - .replace(/^refs\/remotes\//, ""); - } catch { - return undefined; - } - })(); + // 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 = 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); @@ -74,6 +72,33 @@ 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"]; + +/** + * 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). */ +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"; @@ -84,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() === ""; } /** @@ -103,10 +124,18 @@ 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 { + 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. */ export function readFileAtRef(cwd: string, ref: string, relPath: string, strict = false): string | null { if (ref === EMPTY_TREE) return null; @@ -177,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() === ""; } /** @@ -192,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; } diff --git a/src/integrations.ts b/src/integrations.ts index 0ff15e7..ee73a6b 100644 --- a/src/integrations.ts +++ b/src/integrations.ts @@ -6,15 +6,20 @@ 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. */ 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; + /** 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 +52,13 @@ export interface DoctorCheck { detail: string; } -function writeJson(file: string, value: unknown): void { - writeTextAtomic(file, JSON.stringify(value, null, 2) + "\n"); +/** 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 { + writeConfig(file, JSON.stringify(value, null, 2) + "\n", opts); } function packageRef(): string { @@ -106,9 +116,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 +137,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 +169,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 +177,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 +190,24 @@ 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); +} + +/** + * 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): 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 +216,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 +254,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); + 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()); + writeConfig(file, actionWorkflow(), opts); return { target: "github-actions", changed: true, file, detail: "installed pull-request workflow" }; } @@ -256,7 +280,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 +303,7 @@ function installPreCommit(cwd: string): InstallResult { }); } if (changed) { - writeTextAtomic(file, stringifyYaml(data)); + writeConfig(file, stringifyYaml(data), opts); } return { target: "pre-commit", changed, file, detail: changed ? "installed or upgraded always-run pre-commit hook" : "hook already installed" }; } @@ -291,18 +315,19 @@ 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 "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); } }); } /** 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 (!TOOL_MATCHER_TARGETS.includes(target)) return []; return gatedTools(root).filter((glob) => !text.includes(JSON.stringify(toolGlobToRegex(glob)).slice(1, -1))); } @@ -327,6 +352,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/src/log.ts b/src/log.ts index 5f785e8..f577e8a 100644 --- a/src/log.ts +++ b/src/log.ts @@ -73,39 +73,127 @@ 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; + 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.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; + summary.add(pending); + return summary.finish(); + } finally { + input.destroy(); + } +} + +/** + * 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. + */ +export function corpusCommands(text: string): { commands: string[]; skipped: number } { + 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 "{" */ + } } - 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); + commands.push(trimmed); } - 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; + return { commands, skipped }; } 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 }]); +}); 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: [ diff --git a/test/release-0161-more.test.ts b/test/release-0161-more.test.ts new file mode 100644 index 0000000..474656a --- /dev/null +++ b/test/release-0161-more.test.ts @@ -0,0 +1,124 @@ +// 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"; +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"]; + +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); +}); + +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); +}); + +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"]) { + 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); + } +}); diff --git a/test/release-0161.test.ts b/test/release-0161.test.ts new file mode 100644 index 0000000..15144e2 --- /dev/null +++ b/test/release-0161.test.ts @@ -0,0 +1,115 @@ +// 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/); +}); + +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 }); +}); + +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"); +}); 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`); + } +});