diff --git a/src/commands/triage.test.ts b/src/commands/triage.test.ts index 341f3e43..398bcd66 100644 --- a/src/commands/triage.test.ts +++ b/src/commands/triage.test.ts @@ -3,7 +3,12 @@ import assert from "node:assert/strict"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { cmdTriage } from "./triage.js"; +import { + cmdTriage, + parseStagedSkillNames, + latestDeepSkillTriage, + missingDeepSkillTriage, +} from "./triage.js"; // Only the honest-skip path of `kit triage plugin` is exercised here — the happy path calls the // live npm registry triage (network), which is out of scope for a unit test. @@ -38,3 +43,102 @@ describe("kit triage plugin (no plugins declared → honest skip)", () => { assert.match(logs.join("\n"), /no kitPlugins declared/); }); }); + +// A triage-log entry shaped like the ones recordTriageRun writes. +const logEntry = (o: { target: string; deep?: boolean; type?: string; timestamp?: string }) => ({ + timestamp: o.timestamp ?? "2026-07-10T12:00:00Z", + type: o.type ?? "skill", + target: o.target, + sandbox: false, + deep: o.deep, + granter: "tester", +}); + +describe("check-skills gate — parseStagedSkillNames", () => { + it("extracts unique skill names from staged files inside .claude/skills//", () => { + const names = parseStagedSkillNames([ + ".claude/skills/searxng/SKILL.md", + ".claude/skills/searxng/scripts/run.sh", + ".claude/skills/triage/SKILL.md", + "src/unrelated.ts", + ".claude/skills/README.md", // a file directly in skills/, not inside a skill dir + "", + ]); + assert.deepEqual(names.sort(), ["searxng", "triage"]); + }); + + it("returns [] when no skill files are staged", () => { + assert.deepEqual(parseStagedSkillNames(["package.json", "src/x.ts"]), []); + }); +}); + +describe("check-skills gate — latestDeepSkillTriage", () => { + const NOW = Date.parse("2026-07-11T12:00:00Z"); + + it("counts only type:skill + deep:true, keeps the most recent, normalizes path targets", () => { + const latest = latestDeepSkillTriage([ + logEntry({ target: ".claude/skills/searxng", deep: true, timestamp: "2026-07-05T00:00:00Z" }), + logEntry({ target: "searxng", deep: true, timestamp: "2026-07-09T00:00:00Z" }), // newer + logEntry({ target: "searxng", deep: false, timestamp: "2026-07-10T00:00:00Z" }), // shallow — ignored + logEntry({ target: "express", deep: true, type: "npm" }), // not a skill — ignored + ]); + assert.equal(latest.size, 1); + assert.equal(latest.get("searxng"), Date.parse("2026-07-09T00:00:00Z")); + }); + + it("drops entries with a forged/unparseable timestamp (never counts as fresh)", () => { + const latest = latestDeepSkillTriage([ + logEntry({ target: "searxng", deep: true, timestamp: "not-a-date" }), + ]); + assert.equal(latest.has("searxng"), false); + // and such a skill therefore reads as missing + assert.deepEqual( + missingDeepSkillTriage( + ["searxng"], + [logEntry({ target: "searxng", deep: true, timestamp: "not-a-date" })], + NOW, + ), + ["searxng"], + ); + }); +}); + +describe("check-skills gate — missingDeepSkillTriage (fail-closed)", () => { + const NOW = Date.parse("2026-07-11T12:00:00Z"); + + it("a fresh deep entry satisfies the gate (path-form target matches the skill name)", () => { + const entries = [ + logEntry({ target: ".claude/skills/searxng", deep: true, timestamp: "2026-07-10T00:00:00Z" }), + ]; + assert.deepEqual(missingDeepSkillTriage(["searxng"], entries, NOW), []); + }); + + it("a shallow-only entry does NOT satisfy the deep gate", () => { + const entries = [ + logEntry({ target: "searxng", deep: false, timestamp: "2026-07-10T00:00:00Z" }), + ]; + assert.deepEqual(missingDeepSkillTriage(["searxng"], entries, NOW), ["searxng"]); + }); + + it("a stale deep entry (older than the max age) does NOT satisfy the gate", () => { + const entries = [ + logEntry({ target: "searxng", deep: true, timestamp: "2026-06-01T00:00:00Z" }), + ]; + assert.deepEqual(missingDeepSkillTriage(["searxng"], entries, NOW), ["searxng"]); + }); + + it("no triage log at all ⇒ every staged skill is missing", () => { + assert.deepEqual(missingDeepSkillTriage(["a", "b"], [], NOW).sort(), ["a", "b"]); + }); + + it("mixes satisfied and missing skills correctly", () => { + const entries = [ + logEntry({ target: "searxng", deep: true, timestamp: "2026-07-10T00:00:00Z" }), // fresh deep + logEntry({ target: "triage", deep: false, timestamp: "2026-07-10T00:00:00Z" }), // shallow + ]; + assert.deepEqual(missingDeepSkillTriage(["searxng", "triage", "new"], entries, NOW).sort(), [ + "new", + "triage", + ]); + }); +}); diff --git a/src/commands/triage.ts b/src/commands/triage.ts index d44bb0cd..e290728c 100644 --- a/src/commands/triage.ts +++ b/src/commands/triage.ts @@ -19,6 +19,9 @@ export async function cmdTriage(): Promise { if (typeArg === "check-deps") { return cmdTriageCheckDeps(); } + if (typeArg === "check-skills") { + return cmdTriageCheckSkills(); + } if (typeArg === "mcp") { return cmdTriageMcp(filtered.slice(1)); } @@ -62,6 +65,9 @@ export async function cmdTriage(): Promise { console.log( " kit triage check-deps Pre-commit gate: fail if staged deps lack triage entries", ); + console.log( + " kit triage check-skills Pre-commit gate: fail if staged skills lack a --deep triage entry", + ); console.log(""); console.log("Examples:"); console.log(" kit triage npm express"); @@ -572,3 +578,124 @@ async function cmdTriageCheckDeps(): Promise { ); return false; } + +/** A staged path inside a skill directory: `.claude/skills//…`. Group 1 = skill name. */ +const SKILL_PATH_RE = /^\.claude\/skills\/([^/]+)\/.+/; + +/** + * Parse `git diff --cached --name-only` output into the unique set of agent-skill names touched. + * Only files *inside* a skill dir count; the bare `.claude/skills/` dir entry never appears in + * a name-only diff, so a skill is "staged" exactly when one of its files is. + */ +export function parseStagedSkillNames(files: string[]): string[] { + const names = new Set(); + for (const f of files) { + const m = SKILL_PATH_RE.exec(f.trim()); + if (m) names.add(m[1]!); + } + return [...names]; +} + +/** Normalize a triage-log skill target (a path or a bare name) to its skill name (last segment). */ +function skillTargetName(target: string): string { + const trimmed = target.replace(/\/+$/, ""); + return trimmed.split("/").pop() || trimmed; +} + +/** + * Most-recent DEEP skill-triage timestamp (ms) per skill name, from the triage log. Only + * `type:"skill"` entries with `deep === true` count — a shallow skill triage never satisfies the + * deep gate. A forged/unparseable timestamp is dropped (it can't count as fresh). Pure. + */ +export function latestDeepSkillTriage(entries: TriageLogEntry[]): Map { + const latest = new Map(); + for (const e of entries) { + if (e.type !== "skill" || e.deep !== true) continue; + const ts = Date.parse(e.timestamp); + if (!Number.isFinite(ts)) continue; // fail-closed: garbage ts is never "fresh" + const name = skillTargetName(e.target); + const prev = latest.get(name); + if (prev === undefined || ts > prev) latest.set(name, ts); + } + return latest; +} + +/** + * Pure gate core: which staged skills lack a fresh (≤ `maxAgeDays`) deep triage entry. A missing + * entry, a shallow-only entry, or a stale/forged timestamp all count as "missing" (fail-closed). + */ +export function missingDeepSkillTriage( + stagedSkillNames: string[], + entries: TriageLogEntry[], + nowMs: number, + maxAgeDays = TRIAGE_MAX_AGE_DAYS, +): string[] { + const latest = latestDeepSkillTriage(entries); + const cutoff = nowMs - maxAgeDays * 24 * 3600 * 1000; + const missing: string[] = []; + for (const name of stagedSkillNames) { + const ts = latest.get(name); + if (ts === undefined || ts < cutoff) missing.push(name); + } + return missing; +} + +/** + * `kit triage check-skills` — pre-commit gate (increment 2b). Any agent skill with staged changes + * under `.claude/skills//…` must have a `kit triage skill --deep` entry in the triage + * log within the last `TRIAGE_MAX_AGE_DAYS` days. A shallow triage does NOT satisfy the gate: agent + * skills ship executable scripts, so the deep STATIC pass (SkillSpector Stage 1 — no LLM, no egress) + * is required before they enter history. Fail-CLOSED: no log, a stale entry, or a shallow-only entry + * all block the commit. Exits non-zero on any missing skill so the pre-commit hook fails. + */ +async function cmdTriageCheckSkills(): Promise { + const { execFileSync } = await import("node:child_process"); + const { readFile } = await import("node:fs/promises"); + const { resolve } = await import("node:path"); + + let staged: string[]; + try { + const out = execFileSync("git", ["diff", "--cached", "--name-only", "--diff-filter=ACMR"], { + encoding: "utf-8", + stdio: ["pipe", "pipe", "ignore"], + }); + staged = out.split("\n"); + } catch { + return true; // not a git repo / nothing staged — nothing to gate + } + + const skillNames = parseStagedSkillNames(staged); + if (skillNames.length === 0) return true; + + const entries: TriageLogEntry[] = []; + try { + const text = await readFile(resolve(process.cwd(), TRIAGE_LOG_FILE), "utf-8"); + for (const line of text.split("\n")) { + if (!line.trim()) continue; + try { + entries.push(JSON.parse(line) as TriageLogEntry); + } catch { + /* skip malformed line */ + } + } + } catch { + /* no triage log yet — every staged skill is missing */ + } + + const missing = missingDeepSkillTriage(skillNames, entries, Date.now()); + if (missing.length === 0) return true; + + console.error(`${c.red}✗ Deep triage missing for ${missing.length} staged skill(s):${c.reset}`); + for (const name of missing) { + console.error(` - ${name} (run: kit triage skill ${name} --deep)`); + } + console.error(""); + console.error( + `${c.dim}Agent skills ship executable scripts — the deep static scan (no LLM, no egress) is`, + ); + console.error( + `required before they enter history. Run the command(s) above, then re-stage and commit.`, + ); + console.error(`Bypass with --no-verify is recorded to ${SKIPPED_COMMITS_LOG}.${c.reset}`); + return false; +}