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
106 changes: 105 additions & 1 deletion src/commands/triage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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/<name>/", () => {
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",
]);
});
});
127 changes: 127 additions & 0 deletions src/commands/triage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ export async function cmdTriage(): Promise<boolean> {
if (typeArg === "check-deps") {
return cmdTriageCheckDeps();
}
if (typeArg === "check-skills") {
return cmdTriageCheckSkills();
}
if (typeArg === "mcp") {
return cmdTriageMcp(filtered.slice(1));
}
Expand Down Expand Up @@ -62,6 +65,9 @@ export async function cmdTriage(): Promise<boolean> {
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");
Expand Down Expand Up @@ -572,3 +578,124 @@ async function cmdTriageCheckDeps(): Promise<boolean> {
);
return false;
}

/** A staged path inside a skill directory: `.claude/skills/<name>/…`. 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/<name>` 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<string>();
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<string, number> {
const latest = new Map<string, number>();
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/<name>/…` must have a `kit triage skill <name> --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<boolean> {
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;
}
Loading