@zgeoff/skill-gate 0.2.4 → 0.2.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +53 -16
- package/dist/build-tool-gate-output.d.ts +2 -0
- package/dist/collect-session-loads.d.ts +2 -0
- package/dist/format-unknown-key-warning.d.ts +1 -0
- package/dist/index.js +254 -69
- package/dist/plan-tool-gate.d.ts +2 -0
- package/dist/read-available-references.d.ts +2 -0
- package/dist/types.d.ts +28 -1
- package/package.json +2 -2
- package/dist/collect-loaded-skills.d.ts +0 -2
package/README.md
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
# @zgeoff/skill-gate
|
|
2
2
|
|
|
3
3
|
The skill gate is a Claude Code hook that denies an edit until the session has loaded every skill
|
|
4
|
-
the path needs, and names the missing skills.
|
|
5
|
-
the
|
|
6
|
-
|
|
7
|
-
|
|
4
|
+
the path needs, and names the missing skills. It denies a call to a gated tool, such as an MCP tool,
|
|
5
|
+
the same way until the session has loaded the skills and read the reference files the tool needs.
|
|
6
|
+
After a Bash command, it compares `git status` with the status before the command, and it blocks
|
|
7
|
+
when the command changed a gated file that the session lacks the skills for. The package holds no
|
|
8
|
+
rules: each repo keeps its own in `.claude/skill-gate.json`, and a repo without that file has no
|
|
9
|
+
gate.
|
|
8
10
|
|
|
9
11
|
## Install
|
|
10
12
|
|
|
@@ -23,17 +25,21 @@ and exits the process.
|
|
|
23
25
|
|
|
24
26
|
The entry point fails closed. When the package cannot load, the entry point blocks each edit that a
|
|
25
27
|
gate in the rules file matches, and its error names the load failure. It also blocks every edit
|
|
26
|
-
inside the project when it cannot read the rules file or the file does not parse.
|
|
27
|
-
|
|
28
|
+
inside the project when it cannot read the rules file or the file does not parse. It blocks a call
|
|
29
|
+
to a tool that a tool gate names, and every call other than an edit or a Bash command when it cannot
|
|
30
|
+
read the rules file or the file or its `tools` list does not parse. Any other call runs, and the
|
|
31
|
+
hook reports the load failure as a non-blocking error.
|
|
28
32
|
|
|
29
|
-
Register the entry point in `.claude/settings.json`, before a Bash command and after it
|
|
33
|
+
Register the entry point in `.claude/settings.json`, before a Bash command and after it. The
|
|
34
|
+
`PreToolUse` matcher names each tool that a [tool gate](#tool-gates) names, since the hook never
|
|
35
|
+
sees a call that the matcher skips. This example gates `mcp__tracker__update_ticket`:
|
|
30
36
|
|
|
31
37
|
```json
|
|
32
38
|
{
|
|
33
39
|
"hooks": {
|
|
34
40
|
"PreToolUse": [
|
|
35
41
|
{
|
|
36
|
-
"matcher": "Edit|Write|MultiEdit|Bash",
|
|
42
|
+
"matcher": "Edit|Write|MultiEdit|Bash|mcp__tracker__update_ticket",
|
|
37
43
|
"hooks": [
|
|
38
44
|
{
|
|
39
45
|
"type": "command",
|
|
@@ -87,17 +93,48 @@ so write one gate per pattern.
|
|
|
87
93
|
```
|
|
88
94
|
|
|
89
95
|
The gate skips a skill that a rule names but `.claude/skills/` lacks, and it still requires the
|
|
90
|
-
rule's other skills. A rules file that does not parse denies no edit. In both cases
|
|
91
|
-
the user and the agent on every edit
|
|
96
|
+
rule's other skills. A rules file that does not parse denies no edit and no tool call. In both cases
|
|
97
|
+
the hook warns the user and the agent on every edit, and on every call to a tool that the hook
|
|
98
|
+
matcher names, until the rules file is fixed.
|
|
99
|
+
|
|
100
|
+
The gate skips a key it does not know, at the top level or inside a gate, and keeps the rest of the
|
|
101
|
+
rules. It warns on every edit and every gated tool call, and the key itself denies nothing. A rules
|
|
102
|
+
file written for a later version of the package therefore never blocks every call.
|
|
103
|
+
|
|
104
|
+
### Tool gates
|
|
105
|
+
|
|
106
|
+
The optional `tools` list gates a tool call by its `PreToolUse` tool name. Each gate names the
|
|
107
|
+
`tool`, the `skills` the session loads, and the `references` it reads, and it needs at least one
|
|
108
|
+
skill or reference. A reference is a file path under `.claude/skills/`. A tool gate never names
|
|
109
|
+
`Edit`, `Write`, `MultiEdit` or `Bash`, since path gates cover those tools.
|
|
110
|
+
|
|
111
|
+
```json
|
|
112
|
+
{
|
|
113
|
+
"gates": [],
|
|
114
|
+
"tools": [
|
|
115
|
+
{
|
|
116
|
+
"tool": "mcp__tracker__update_ticket",
|
|
117
|
+
"skills": ["ticket-review"],
|
|
118
|
+
"references": ["ticket-review/references/reasons.md"]
|
|
119
|
+
}
|
|
120
|
+
]
|
|
121
|
+
}
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
The denial names each missing skill and each reference to read. The gate skips a skill or a
|
|
125
|
+
reference that the repo lacks, and warns on each gated call until the rule is fixed.
|
|
92
126
|
|
|
93
127
|
## Which loads count
|
|
94
128
|
|
|
95
|
-
The gate counts the loads of the session that makes the edit
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
`
|
|
100
|
-
|
|
129
|
+
The gate counts the loads of the session that makes the edit or the tool call. A skill loads through
|
|
130
|
+
a Skill tool call or a slash command. A reference counts once a Read tool call of its file succeeds;
|
|
131
|
+
a Bash `cat` of the file does not count. A subagent's tool call carries `agent_id` beside the main
|
|
132
|
+
session's `transcript_path`, and the gate reads that subagent's own transcript,
|
|
133
|
+
`<session>/subagents/agent-<agent_id>.jsonl` beside the main one. A subagent therefore loads the
|
|
134
|
+
skills itself, and the main session's loads never count for it. A compaction writes a
|
|
135
|
+
`compact_boundary` entry, and the loads and reads before it no longer count: after a compaction, the
|
|
136
|
+
gate denies a gated edit or tool call until the session loads the skills and reads the references
|
|
137
|
+
again, and its denial says so.
|
|
101
138
|
|
|
102
139
|
## Bash commands
|
|
103
140
|
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function formatUnknownKeyWarning(key: string): string;
|
package/dist/index.js
CHANGED
|
@@ -2567,7 +2567,7 @@ var require_picomatch2 = __commonJS(function(exports, module) {
|
|
|
2567
2567
|
// src/run-skill-gate.ts
|
|
2568
2568
|
import { statSync } from "fs";
|
|
2569
2569
|
import { mkdir, rm } from "fs/promises";
|
|
2570
|
-
import
|
|
2570
|
+
import path7 from "path";
|
|
2571
2571
|
// ../std/src/is-record.ts
|
|
2572
2572
|
function isRecord(value) {
|
|
2573
2573
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
@@ -11308,12 +11308,18 @@ function buildLoadInstruction(missing, compacted) {
|
|
|
11308
11308
|
return compacted ? ` Load the ${formatSkillList(missing)} again with the Skill tool before the next change. This session was compacted, and a skill loaded before the compaction no longer counts.` : ` Load the ${formatSkillList(missing)} with the Skill tool before the next change.`;
|
|
11309
11309
|
}
|
|
11310
11310
|
|
|
11311
|
+
// src/format-unknown-key-warning.ts
|
|
11312
|
+
function formatUnknownKeyWarning(key) {
|
|
11313
|
+
return `skill-gate: .claude/skill-gate.json holds the key \`${key}\`, which this version of @zgeoff/skill-gate does not know. The gate skips the key and keeps the rest of the rules; update the package or remove the key.`;
|
|
11314
|
+
}
|
|
11315
|
+
|
|
11311
11316
|
// src/build-skill-gate-output.ts
|
|
11312
11317
|
var RULES_PATH3 = ".claude/skill-gate.json";
|
|
11313
11318
|
var EDIT_TOOLS_NOTE = "Change a gated path only with Edit, Write or MultiEdit, never through Bash.";
|
|
11314
11319
|
function buildSkillGateOutput(filePath, plan, context = {}) {
|
|
11315
11320
|
const warnings = [
|
|
11316
11321
|
...context.rulesError === undefined ? [] : [`skill-gate: ${RULES_PATH3} ${context.rulesError}.`],
|
|
11322
|
+
...(context.unknownKeys ?? []).map((key) => formatUnknownKeyWarning(key)),
|
|
11317
11323
|
...plan.unknown.map((entry) => `skill-gate: the rule "${entry.match}" in ${RULES_PATH3} names the skill "${entry.skill}", but .claude/skills/${entry.skill}/SKILL.md does not exist. Fix the rule or add the skill; until then the gate skips that skill.`)
|
|
11318
11324
|
];
|
|
11319
11325
|
const warning = warnings.length === 0 ? undefined : warnings.join(`
|
|
@@ -11339,6 +11345,56 @@ ${warning}`
|
|
|
11339
11345
|
};
|
|
11340
11346
|
}
|
|
11341
11347
|
|
|
11348
|
+
// src/build-tool-gate-output.ts
|
|
11349
|
+
var RULES_PATH4 = ".claude/skill-gate.json";
|
|
11350
|
+
function buildToolGateOutput(toolName, plan, context = {}) {
|
|
11351
|
+
const warnings = [
|
|
11352
|
+
...context.rulesError === undefined ? [] : [`skill-gate: ${RULES_PATH4} ${context.rulesError}.`],
|
|
11353
|
+
...(context.unknownKeys ?? []).map((key) => formatUnknownKeyWarning(key)),
|
|
11354
|
+
...plan.unknown.map((entry) => formatUnknownWarning(entry))
|
|
11355
|
+
];
|
|
11356
|
+
const warning = warnings.length === 0 ? undefined : warnings.join(`
|
|
11357
|
+
`);
|
|
11358
|
+
if (plan.missingSkills.length > 0 || plan.missingReferences.length > 0) {
|
|
11359
|
+
const reason = buildDenyReason(toolName, plan, context.compacted === true);
|
|
11360
|
+
return {
|
|
11361
|
+
...warning === undefined ? {} : { systemMessage: warning },
|
|
11362
|
+
hookSpecificOutput: {
|
|
11363
|
+
hookEventName: "PreToolUse",
|
|
11364
|
+
permissionDecision: "deny",
|
|
11365
|
+
permissionDecisionReason: warning === undefined ? reason : `${reason}
|
|
11366
|
+
${warning}`
|
|
11367
|
+
}
|
|
11368
|
+
};
|
|
11369
|
+
}
|
|
11370
|
+
if (warning === undefined) {
|
|
11371
|
+
return null;
|
|
11372
|
+
}
|
|
11373
|
+
return {
|
|
11374
|
+
systemMessage: warning,
|
|
11375
|
+
hookSpecificOutput: { hookEventName: "PreToolUse", additionalContext: warning }
|
|
11376
|
+
};
|
|
11377
|
+
}
|
|
11378
|
+
function formatUnknownWarning(entry) {
|
|
11379
|
+
return entry.kind === "skill" ? `skill-gate: the tool gate "${entry.tool}" in ${RULES_PATH4} names the skill "${entry.name}", but .claude/skills/${entry.name}/SKILL.md does not exist. Fix the rule or add the skill; until then the gate skips that skill.` : `skill-gate: the tool gate "${entry.tool}" in ${RULES_PATH4} names the reference "${entry.name}", but .claude/skills/${entry.name} does not exist. Fix the rule or add the file; until then the gate skips that reference.`;
|
|
11380
|
+
}
|
|
11381
|
+
function buildDenyReason(toolName, plan, compacted) {
|
|
11382
|
+
const again = compacted ? " again" : "";
|
|
11383
|
+
const steps = [
|
|
11384
|
+
...plan.missingSkills.length === 0 ? [] : [`load the ${formatSkillList(plan.missingSkills)}${again} with the Skill tool`],
|
|
11385
|
+
...plan.missingReferences.length === 0 ? [] : [`read ${formatReferenceList(plan.missingReferences)}${again} with the Read tool`]
|
|
11386
|
+
].join(" and ");
|
|
11387
|
+
const compaction = compacted ? " This session was compacted, and a skill or reference loaded before the compaction no longer counts." : "";
|
|
11388
|
+
return `Before calling ${toolName}, ${steps}, then retry the call.${compaction} ${RULES_PATH4} lists the skills and references each tool needs.`;
|
|
11389
|
+
}
|
|
11390
|
+
function formatReferenceList(references) {
|
|
11391
|
+
const paths = references.map((reference) => `.claude/skills/${reference}`);
|
|
11392
|
+
if (paths.length === 1) {
|
|
11393
|
+
return `${paths[0]}`;
|
|
11394
|
+
}
|
|
11395
|
+
return `${paths.slice(0, -1).join(", ")} and ${paths.at(-1)}`;
|
|
11396
|
+
}
|
|
11397
|
+
|
|
11342
11398
|
// src/collect-bash-candidates.ts
|
|
11343
11399
|
function collectBashCandidates(recorded, gatedPaths) {
|
|
11344
11400
|
const cleanBefore = gatedPaths.filter((relativePath) => !Object.hasOwn(recorded, relativePath));
|
|
@@ -11371,15 +11427,20 @@ function isGlobMatch(pattern, relativePath) {
|
|
|
11371
11427
|
return import_picomatch.default.isMatch(relativePath, pattern, { dot: true });
|
|
11372
11428
|
}
|
|
11373
11429
|
|
|
11374
|
-
// src/collect-
|
|
11375
|
-
function
|
|
11430
|
+
// src/collect-session-loads.ts
|
|
11431
|
+
function collectSessionLoads(transcript) {
|
|
11376
11432
|
const entries = transcript.split(`
|
|
11377
11433
|
`).map((line) => parseEntry(line));
|
|
11378
11434
|
const lastBoundary = entries.findLastIndex((entry) => isCompactBoundary(entry));
|
|
11379
11435
|
const current = entries.slice(lastBoundary + 1);
|
|
11380
11436
|
const succeeded = collectSucceededToolUseIDs(current);
|
|
11381
11437
|
const skills = current.flatMap((entry) => collectEntrySkills(entry, succeeded));
|
|
11382
|
-
|
|
11438
|
+
const readPaths = current.flatMap((entry) => collectContentBlocks(entry, "assistant")).flatMap((block) => collectReadCall(block, succeeded));
|
|
11439
|
+
return {
|
|
11440
|
+
skills: [...new Set(skills)],
|
|
11441
|
+
readPaths: [...new Set(readPaths)],
|
|
11442
|
+
compacted: lastBoundary !== -1
|
|
11443
|
+
};
|
|
11383
11444
|
}
|
|
11384
11445
|
function parseEntry(line) {
|
|
11385
11446
|
try {
|
|
@@ -11425,6 +11486,15 @@ function collectSkillCall(block, succeeded) {
|
|
|
11425
11486
|
const skill = input["skill"];
|
|
11426
11487
|
return typeof skill === "string" && typeof id === "string" && succeeded.includes(id) ? [skill] : [];
|
|
11427
11488
|
}
|
|
11489
|
+
function collectReadCall(block, succeeded) {
|
|
11490
|
+
const input = block["input"];
|
|
11491
|
+
const id = block["id"];
|
|
11492
|
+
if (block["type"] !== "tool_use" || block["name"] !== "Read" || !isRecord(input)) {
|
|
11493
|
+
return [];
|
|
11494
|
+
}
|
|
11495
|
+
const filePath = input["file_path"];
|
|
11496
|
+
return typeof filePath === "string" && typeof id === "string" && succeeded.includes(id) ? [filePath] : [];
|
|
11497
|
+
}
|
|
11428
11498
|
|
|
11429
11499
|
// src/collect-written-paths.ts
|
|
11430
11500
|
import path from "path";
|
|
@@ -12024,6 +12094,9 @@ function parseJSON(text) {
|
|
|
12024
12094
|
return error instanceof Error ? error : new Error(String(error));
|
|
12025
12095
|
}
|
|
12026
12096
|
}
|
|
12097
|
+
var RULES_KEYS = ["ignore", "gates", "tools"];
|
|
12098
|
+
var PATH_GATE_KEYS = ["match", "skills"];
|
|
12099
|
+
var TOOL_GATE_KEYS = ["tool", "skills", "references"];
|
|
12027
12100
|
function parseRulesRecord(value) {
|
|
12028
12101
|
const ignore = value["ignore"] ?? [];
|
|
12029
12102
|
if (!isStringArray(ignore)) {
|
|
@@ -12033,18 +12106,29 @@ function parseRulesRecord(value) {
|
|
|
12033
12106
|
if (!Array.isArray(gates)) {
|
|
12034
12107
|
return { ok: false, error: "`gates` must be an array" };
|
|
12035
12108
|
}
|
|
12036
|
-
|
|
12037
|
-
|
|
12038
|
-
|
|
12039
|
-
|
|
12040
|
-
|
|
12041
|
-
|
|
12042
|
-
const
|
|
12043
|
-
const error = parsed.find((gate) => typeof gate === "string");
|
|
12109
|
+
const tools = value["tools"] ?? [];
|
|
12110
|
+
if (!Array.isArray(tools)) {
|
|
12111
|
+
return { ok: false, error: "`tools` must be an array" };
|
|
12112
|
+
}
|
|
12113
|
+
const parsedGates = gates.map((gate, index) => parseGate(gate, index));
|
|
12114
|
+
const parsedTools = tools.map((gate, index) => parseToolGate(gate, index));
|
|
12115
|
+
const error = [...parsedGates, ...parsedTools].find((gate) => typeof gate === "string");
|
|
12044
12116
|
if (typeof error === "string") {
|
|
12045
12117
|
return { ok: false, error };
|
|
12046
12118
|
}
|
|
12047
|
-
return {
|
|
12119
|
+
return {
|
|
12120
|
+
ok: true,
|
|
12121
|
+
rules: { ignore, gates: parsedGates.filter((gate) => typeof gate !== "string") },
|
|
12122
|
+
tools: parsedTools.filter((gate) => typeof gate !== "string"),
|
|
12123
|
+
unknownKeys: [
|
|
12124
|
+
...collectUnknownKeys(value, RULES_KEYS, ""),
|
|
12125
|
+
...gates.flatMap((gate, index) => collectUnknownKeys(gate, PATH_GATE_KEYS, `gates[${index}].`)),
|
|
12126
|
+
...tools.flatMap((gate, index) => collectUnknownKeys(gate, TOOL_GATE_KEYS, `tools[${index}].`))
|
|
12127
|
+
]
|
|
12128
|
+
};
|
|
12129
|
+
}
|
|
12130
|
+
function isStringArray(value) {
|
|
12131
|
+
return Array.isArray(value) && value.every((item) => typeof item === "string" && item !== "");
|
|
12048
12132
|
}
|
|
12049
12133
|
function parseGate(gate, index) {
|
|
12050
12134
|
if (!isRecord(gate) || typeof gate["match"] !== "string" || gate["match"] === "") {
|
|
@@ -12056,6 +12140,38 @@ function parseGate(gate, index) {
|
|
|
12056
12140
|
}
|
|
12057
12141
|
return { match: gate["match"], skills };
|
|
12058
12142
|
}
|
|
12143
|
+
var PATH_GATED_TOOLS = new Set(["Edit", "Write", "MultiEdit", "Bash"]);
|
|
12144
|
+
function parseToolGate(gate, index) {
|
|
12145
|
+
if (!isRecord(gate) || typeof gate["tool"] !== "string" || gate["tool"] === "") {
|
|
12146
|
+
return `tool gate ${index} needs a non-empty string \`tool\``;
|
|
12147
|
+
}
|
|
12148
|
+
const tool = gate["tool"];
|
|
12149
|
+
if (PATH_GATED_TOOLS.has(tool)) {
|
|
12150
|
+
return `tool gate "${tool}" names a tool that path gates cover; gate its paths in \`gates\``;
|
|
12151
|
+
}
|
|
12152
|
+
const skills = gate["skills"] ?? [];
|
|
12153
|
+
const references = gate["references"] ?? [];
|
|
12154
|
+
if (!isStringArray(skills) || !isStringArray(references)) {
|
|
12155
|
+
return `tool gate "${tool}" needs \`skills\` and \`references\` arrays of non-empty strings`;
|
|
12156
|
+
}
|
|
12157
|
+
if (skills.length === 0 && references.length === 0) {
|
|
12158
|
+
return `tool gate "${tool}" needs at least one skill or reference`;
|
|
12159
|
+
}
|
|
12160
|
+
const outside = references.find((reference) => !isSkillsPath(reference));
|
|
12161
|
+
if (outside !== undefined) {
|
|
12162
|
+
return `tool gate "${tool}" names the reference "${outside}", which is not a path inside .claude/skills/`;
|
|
12163
|
+
}
|
|
12164
|
+
return { tool, skills, references };
|
|
12165
|
+
}
|
|
12166
|
+
function isSkillsPath(reference) {
|
|
12167
|
+
return !reference.startsWith("/") && !reference.split("/").includes("..");
|
|
12168
|
+
}
|
|
12169
|
+
function collectUnknownKeys(value, knownKeys, prefix) {
|
|
12170
|
+
if (!isRecord(value)) {
|
|
12171
|
+
return [];
|
|
12172
|
+
}
|
|
12173
|
+
return Object.keys(value).filter((key) => !knownKeys.includes(key)).map((key) => `${prefix}${key}`);
|
|
12174
|
+
}
|
|
12059
12175
|
|
|
12060
12176
|
// src/pick-commit-range.ts
|
|
12061
12177
|
function pickCommitRange(before, after) {
|
|
@@ -12098,6 +12214,32 @@ function planBashSkillGate(input) {
|
|
|
12098
12214
|
return { gatedPaths: gated.map((entry) => entry.path), missing: [...new Set(missing)] };
|
|
12099
12215
|
}
|
|
12100
12216
|
|
|
12217
|
+
// src/plan-tool-gate.ts
|
|
12218
|
+
import path2 from "path";
|
|
12219
|
+
function planToolGate(input) {
|
|
12220
|
+
const gates = input.tools.filter((gate) => gate.tool === input.toolName);
|
|
12221
|
+
const unknown = gates.flatMap((gate) => [
|
|
12222
|
+
...gate.skills.filter((skill) => !input.availableSkills.includes(skill)).map((skill) => ({ tool: gate.tool, kind: "skill", name: skill })),
|
|
12223
|
+
...gate.references.filter((reference) => !input.availableReferences.includes(reference)).map((reference) => ({ tool: gate.tool, kind: "reference", name: reference }))
|
|
12224
|
+
]);
|
|
12225
|
+
const readPaths = new Set(input.loads.readPaths.map((readPath) => path2.resolve(readPath)));
|
|
12226
|
+
const missingSkills = gates.flatMap((gate) => gate.skills).filter((skill) => input.availableSkills.includes(skill) && !input.loads.skills.includes(skill));
|
|
12227
|
+
const missingReferences = gates.flatMap((gate) => gate.references).filter((reference) => input.availableReferences.includes(reference) && !readPaths.has(path2.resolve(input.skillsDir, reference)));
|
|
12228
|
+
return {
|
|
12229
|
+
missingSkills: [...new Set(missingSkills)],
|
|
12230
|
+
missingReferences: [...new Set(missingReferences)],
|
|
12231
|
+
unknown
|
|
12232
|
+
};
|
|
12233
|
+
}
|
|
12234
|
+
|
|
12235
|
+
// src/read-available-references.ts
|
|
12236
|
+
import path3 from "path";
|
|
12237
|
+
async function readAvailableReferences(readContent, skillsDir, tools) {
|
|
12238
|
+
const references = [...new Set(tools.flatMap((gate) => gate.references))];
|
|
12239
|
+
const contents = await Promise.all(references.map((reference) => readContent(path3.join(skillsDir, reference))));
|
|
12240
|
+
return references.filter((_, index) => contents[index] !== null);
|
|
12241
|
+
}
|
|
12242
|
+
|
|
12101
12243
|
// src/to-content-hash.ts
|
|
12102
12244
|
function toContentHash(bytes) {
|
|
12103
12245
|
return Bun.hash(bytes).toString(16);
|
|
@@ -12119,12 +12261,12 @@ async function readCommitHashes(git, commit, relativePaths) {
|
|
|
12119
12261
|
}
|
|
12120
12262
|
|
|
12121
12263
|
// src/read-committed-paths.ts
|
|
12122
|
-
import
|
|
12264
|
+
import path4 from "path";
|
|
12123
12265
|
async function readCommittedPaths(git, directory, from, to) {
|
|
12124
12266
|
const toRoot = await git.revparse(["--show-cdup"]);
|
|
12125
12267
|
const listArgs = from === null ? ["ls-tree", "-r", "--full-tree", "--name-only", "-z", to] : ["diff", "--name-only", "--no-renames", "-z", from, to];
|
|
12126
12268
|
const names = await git.raw(listArgs);
|
|
12127
|
-
return names.split("\x00").filter((entry) => entry !== "").map((entry) =>
|
|
12269
|
+
return names.split("\x00").filter((entry) => entry !== "").map((entry) => path4.join(directory, toRoot.trim(), entry));
|
|
12128
12270
|
}
|
|
12129
12271
|
|
|
12130
12272
|
// src/read-file-content.ts
|
|
@@ -12143,17 +12285,17 @@ async function readFileContent(filePath) {
|
|
|
12143
12285
|
}
|
|
12144
12286
|
|
|
12145
12287
|
// src/read-file-hashes.ts
|
|
12146
|
-
import
|
|
12288
|
+
import path5 from "path";
|
|
12147
12289
|
async function readFileHashes(readContent, projectDir, relativePaths) {
|
|
12148
12290
|
const entries = await Promise.all(relativePaths.map(async (relativePath) => {
|
|
12149
|
-
const content = await readContent(
|
|
12291
|
+
const content = await readContent(path5.join(projectDir, relativePath));
|
|
12150
12292
|
return [relativePath, content === null ? null : toContentHash(content)];
|
|
12151
12293
|
}));
|
|
12152
12294
|
return Object.fromEntries(entries);
|
|
12153
12295
|
}
|
|
12154
12296
|
|
|
12155
12297
|
// src/read-work-tree.ts
|
|
12156
|
-
import
|
|
12298
|
+
import path6 from "path";
|
|
12157
12299
|
async function readWorkTree(git, directory) {
|
|
12158
12300
|
const isWorkTree = await git.checkIsRepo();
|
|
12159
12301
|
if (!isWorkTree) {
|
|
@@ -12162,7 +12304,7 @@ async function readWorkTree(git, directory) {
|
|
|
12162
12304
|
const toRoot = await git.revparse(["--show-cdup"]);
|
|
12163
12305
|
const status = await git.status();
|
|
12164
12306
|
const head = await git.revparse(["--verify", "HEAD"]).catch(() => null);
|
|
12165
|
-
const dirtyPaths = status.files.flatMap((file) => file.from === undefined ? [file.path] : [file.path, file.from]).map((entry) =>
|
|
12307
|
+
const dirtyPaths = status.files.flatMap((file) => file.from === undefined ? [file.path] : [file.path, file.from]).map((entry) => path6.join(directory, toRoot.trim(), entry));
|
|
12166
12308
|
return { head: head?.trim() ?? null, dirtyPaths };
|
|
12167
12309
|
}
|
|
12168
12310
|
|
|
@@ -12175,8 +12317,16 @@ async function runSkillGate() {
|
|
|
12175
12317
|
}
|
|
12176
12318
|
process.env["GIT_OPTIONAL_LOCKS"] = "0";
|
|
12177
12319
|
const projectDir = process.env["CLAUDE_PROJECT_DIR"] ?? input.cwd;
|
|
12178
|
-
const rulesFile = Bun.file(
|
|
12320
|
+
const rulesFile = Bun.file(path7.join(projectDir, ".claude", "skill-gate.json"));
|
|
12179
12321
|
const hasRules = await rulesFile.exists();
|
|
12322
|
+
if (hasRules && input.toolName !== null && input.event === "PreToolUse") {
|
|
12323
|
+
await checkToolCall({
|
|
12324
|
+
hookInput: input,
|
|
12325
|
+
toolName: input.toolName,
|
|
12326
|
+
projectDir,
|
|
12327
|
+
rulesText: await rulesFile.text()
|
|
12328
|
+
});
|
|
12329
|
+
}
|
|
12180
12330
|
if (hasRules && input.command !== null) {
|
|
12181
12331
|
await checkBash({
|
|
12182
12332
|
hookInput: input,
|
|
@@ -12188,7 +12338,7 @@ async function runSkillGate() {
|
|
|
12188
12338
|
if (input.filePath === null || input.event !== "PreToolUse") {
|
|
12189
12339
|
process.exit(0);
|
|
12190
12340
|
}
|
|
12191
|
-
const filePath =
|
|
12341
|
+
const filePath = path7.resolve(input.cwd, input.filePath);
|
|
12192
12342
|
const relativePath = toProjectPath(projectDir, filePath);
|
|
12193
12343
|
if (!hasRules || isOutsideProject(relativePath)) {
|
|
12194
12344
|
process.exit(0);
|
|
@@ -12199,16 +12349,19 @@ async function runSkillGate() {
|
|
|
12199
12349
|
printOutput(buildSkillGateOutput(filePath, { missing: [], unknown: [] }, { rulesError: parsed.error }));
|
|
12200
12350
|
process.exit(0);
|
|
12201
12351
|
}
|
|
12202
|
-
const availableSkills = await readAvailableSkills(
|
|
12352
|
+
const availableSkills = await readAvailableSkills(path7.join(projectDir, ".claude", "skills"));
|
|
12203
12353
|
const transcript = await readTranscript(resolveSessionTranscriptPath(input));
|
|
12204
|
-
const loaded =
|
|
12354
|
+
const loaded = collectSessionLoads(transcript);
|
|
12205
12355
|
const plan = planSkillGate({
|
|
12206
12356
|
rules: parsed.rules,
|
|
12207
12357
|
relativePath,
|
|
12208
12358
|
loadedSkills: loaded.skills,
|
|
12209
12359
|
availableSkills
|
|
12210
12360
|
});
|
|
12211
|
-
printOutput(buildSkillGateOutput(filePath, plan, {
|
|
12361
|
+
printOutput(buildSkillGateOutput(filePath, plan, {
|
|
12362
|
+
compacted: loaded.compacted,
|
|
12363
|
+
unknownKeys: parsed.unknownKeys
|
|
12364
|
+
}));
|
|
12212
12365
|
process.exit(0);
|
|
12213
12366
|
}
|
|
12214
12367
|
function parseHookInput(value) {
|
|
@@ -12219,14 +12372,16 @@ function parseHookInput(value) {
|
|
|
12219
12372
|
const transcriptPath = value["transcript_path"];
|
|
12220
12373
|
const editPath = value["tool_input"]["file_path"];
|
|
12221
12374
|
const command = value["tool_input"]["command"];
|
|
12375
|
+
const toolName = value["tool_name"];
|
|
12222
12376
|
if (typeof cwd !== "string" || typeof transcriptPath !== "string") {
|
|
12223
12377
|
return null;
|
|
12224
12378
|
}
|
|
12225
|
-
if (typeof editPath !== "string" && typeof command !== "string") {
|
|
12379
|
+
if (typeof editPath !== "string" && typeof command !== "string" && typeof toolName !== "string") {
|
|
12226
12380
|
return null;
|
|
12227
12381
|
}
|
|
12228
12382
|
return {
|
|
12229
12383
|
event: pickHookEvent(value["hook_event_name"]),
|
|
12384
|
+
toolName: typeof toolName === "string" ? toolName : null,
|
|
12230
12385
|
cwd,
|
|
12231
12386
|
filePath: typeof editPath === "string" ? editPath : null,
|
|
12232
12387
|
command: typeof command === "string" ? command : null,
|
|
@@ -12238,6 +12393,69 @@ function parseHookInput(value) {
|
|
|
12238
12393
|
function pickHookEvent(value) {
|
|
12239
12394
|
return value === "PostToolUse" || value === "PostToolUseFailure" ? value : "PreToolUse";
|
|
12240
12395
|
}
|
|
12396
|
+
var PATH_GATED_TOOLS2 = new Set(["Edit", "Write", "MultiEdit", "Bash"]);
|
|
12397
|
+
async function checkToolCall(check) {
|
|
12398
|
+
const parsedRules = parseSkillGateRules(check.rulesText);
|
|
12399
|
+
if (!parsedRules.ok) {
|
|
12400
|
+
if (!PATH_GATED_TOOLS2.has(check.toolName)) {
|
|
12401
|
+
printOutput(buildToolGateOutput(check.toolName, { missingSkills: [], missingReferences: [], unknown: [] }, { rulesError: parsedRules.error }));
|
|
12402
|
+
process.exit(0);
|
|
12403
|
+
}
|
|
12404
|
+
return;
|
|
12405
|
+
}
|
|
12406
|
+
if (!parsedRules.tools.some((gate) => gate.tool === check.toolName)) {
|
|
12407
|
+
return;
|
|
12408
|
+
}
|
|
12409
|
+
const skillsDir = path7.join(check.projectDir, ".claude", "skills");
|
|
12410
|
+
const transcript = await readTranscript(resolveSessionTranscriptPath(check.hookInput));
|
|
12411
|
+
const loads = collectSessionLoads(transcript);
|
|
12412
|
+
const plan = planToolGate({
|
|
12413
|
+
tools: parsedRules.tools,
|
|
12414
|
+
toolName: check.toolName,
|
|
12415
|
+
skillsDir,
|
|
12416
|
+
loads,
|
|
12417
|
+
availableSkills: await readAvailableSkills(skillsDir),
|
|
12418
|
+
availableReferences: await readAvailableReferences(readFileContent, skillsDir, parsedRules.tools)
|
|
12419
|
+
});
|
|
12420
|
+
printOutput(buildToolGateOutput(check.toolName, plan, {
|
|
12421
|
+
compacted: loads.compacted,
|
|
12422
|
+
unknownKeys: parsedRules.unknownKeys
|
|
12423
|
+
}));
|
|
12424
|
+
process.exit(0);
|
|
12425
|
+
}
|
|
12426
|
+
function printOutput(output) {
|
|
12427
|
+
if (output !== null) {
|
|
12428
|
+
console.log(JSON.stringify(output));
|
|
12429
|
+
}
|
|
12430
|
+
}
|
|
12431
|
+
async function readTranscript(transcriptPath) {
|
|
12432
|
+
if (transcriptPath === null) {
|
|
12433
|
+
return "";
|
|
12434
|
+
}
|
|
12435
|
+
const transcriptFile = Bun.file(transcriptPath);
|
|
12436
|
+
const exists = await transcriptFile.exists();
|
|
12437
|
+
return exists ? transcriptFile.text() : "";
|
|
12438
|
+
}
|
|
12439
|
+
function resolveSessionTranscriptPath(edit) {
|
|
12440
|
+
if (edit.agentID === undefined) {
|
|
12441
|
+
return edit.transcriptPath;
|
|
12442
|
+
}
|
|
12443
|
+
if (typeof edit.agentID !== "string" || !/^[\w-]+$/u.test(edit.agentID)) {
|
|
12444
|
+
return null;
|
|
12445
|
+
}
|
|
12446
|
+
const sessionDir = edit.transcriptPath.replace(/\.jsonl$/u, "");
|
|
12447
|
+
return path7.join(sessionDir, "subagents", `agent-${edit.agentID}.jsonl`);
|
|
12448
|
+
}
|
|
12449
|
+
async function readAvailableSkills(skillsDir) {
|
|
12450
|
+
const skills = [];
|
|
12451
|
+
const scan = new Bun.Glob("*/SKILL.md").scan({ cwd: skillsDir, followSymlinks: true });
|
|
12452
|
+
try {
|
|
12453
|
+
for await (const skillFile of scan) {
|
|
12454
|
+
skills.push(path7.dirname(skillFile));
|
|
12455
|
+
}
|
|
12456
|
+
} catch {}
|
|
12457
|
+
return skills;
|
|
12458
|
+
}
|
|
12241
12459
|
async function checkBash(check) {
|
|
12242
12460
|
const parsedRules = parseSkillGateRules(check.rulesText);
|
|
12243
12461
|
if (!parsedRules.ok) {
|
|
@@ -12265,7 +12483,7 @@ function resolveSnapshotPath(hookInput) {
|
|
|
12265
12483
|
return null;
|
|
12266
12484
|
}
|
|
12267
12485
|
const sessionDir = hookInput.transcriptPath.replace(/\.jsonl$/u, "");
|
|
12268
|
-
return
|
|
12486
|
+
return path7.join(sessionDir, "skill-gate", `${hookInput.toolUseID}.json`);
|
|
12269
12487
|
}
|
|
12270
12488
|
async function writeGatedSnapshot(git, snapshotPath, projectDir, rules) {
|
|
12271
12489
|
const snapshot = await readGatedSnapshot(git, projectDir, rules);
|
|
@@ -12273,7 +12491,7 @@ async function writeGatedSnapshot(git, snapshotPath, projectDir, rules) {
|
|
|
12273
12491
|
return;
|
|
12274
12492
|
}
|
|
12275
12493
|
try {
|
|
12276
|
-
await mkdir(
|
|
12494
|
+
await mkdir(path7.dirname(snapshotPath), { recursive: true });
|
|
12277
12495
|
await Bun.write(snapshotPath, JSON.stringify(snapshot));
|
|
12278
12496
|
} catch {
|
|
12279
12497
|
await rm(snapshotPath, { force: true });
|
|
@@ -12298,10 +12516,10 @@ function collectGatedProjectPaths(projectDir, rules, absolutePaths) {
|
|
|
12298
12516
|
return [...new Set(absolutePaths.map((entry) => toProjectPath(projectDir, entry)))].filter((relativePath) => !isOutsideProject(relativePath) && collectGateSkills(rules, relativePath).length > 0);
|
|
12299
12517
|
}
|
|
12300
12518
|
function toProjectPath(projectDir, absolute) {
|
|
12301
|
-
return
|
|
12519
|
+
return path7.relative(projectDir, absolute).split(path7.sep).join("/");
|
|
12302
12520
|
}
|
|
12303
12521
|
function isOutsideProject(fromProject) {
|
|
12304
|
-
return fromProject === ".." || fromProject.startsWith("../") ||
|
|
12522
|
+
return fromProject === ".." || fromProject.startsWith("../") || path7.isAbsolute(fromProject);
|
|
12305
12523
|
}
|
|
12306
12524
|
async function checkBashCommand(check, rules) {
|
|
12307
12525
|
const written = collectWrittenPaths(check.command).map((entry) => readWrittenPath(check.hookInput.cwd, entry));
|
|
@@ -12309,9 +12527,9 @@ async function checkBashCommand(check, rules) {
|
|
|
12309
12527
|
if (candidates.length === 0) {
|
|
12310
12528
|
return;
|
|
12311
12529
|
}
|
|
12312
|
-
const skills = await readAvailableSkills(
|
|
12530
|
+
const skills = await readAvailableSkills(path7.join(check.projectDir, ".claude", "skills"));
|
|
12313
12531
|
const sessionTranscript = await readTranscript(resolveSessionTranscriptPath(check.hookInput));
|
|
12314
|
-
const sessionLoads =
|
|
12532
|
+
const sessionLoads = collectSessionLoads(sessionTranscript);
|
|
12315
12533
|
const bashPlan = planBashSkillGate({
|
|
12316
12534
|
rules,
|
|
12317
12535
|
paths: candidates.map((entry) => ({
|
|
@@ -12326,45 +12544,12 @@ async function checkBashCommand(check, rules) {
|
|
|
12326
12544
|
}));
|
|
12327
12545
|
}
|
|
12328
12546
|
function readWrittenPath(cwd, written) {
|
|
12329
|
-
const absolute =
|
|
12547
|
+
const absolute = path7.resolve(cwd, written.path);
|
|
12330
12548
|
if (written.fileName === undefined) {
|
|
12331
12549
|
return absolute;
|
|
12332
12550
|
}
|
|
12333
12551
|
const isDirectory = statSync(absolute, { throwIfNoEntry: false })?.isDirectory() === true;
|
|
12334
|
-
return isDirectory ?
|
|
12335
|
-
}
|
|
12336
|
-
async function readAvailableSkills(skillsDir) {
|
|
12337
|
-
const skills = [];
|
|
12338
|
-
const scan = new Bun.Glob("*/SKILL.md").scan({ cwd: skillsDir, followSymlinks: true });
|
|
12339
|
-
try {
|
|
12340
|
-
for await (const skillFile of scan) {
|
|
12341
|
-
skills.push(path5.dirname(skillFile));
|
|
12342
|
-
}
|
|
12343
|
-
} catch {}
|
|
12344
|
-
return skills;
|
|
12345
|
-
}
|
|
12346
|
-
async function readTranscript(transcriptPath) {
|
|
12347
|
-
if (transcriptPath === null) {
|
|
12348
|
-
return "";
|
|
12349
|
-
}
|
|
12350
|
-
const transcriptFile = Bun.file(transcriptPath);
|
|
12351
|
-
const exists = await transcriptFile.exists();
|
|
12352
|
-
return exists ? transcriptFile.text() : "";
|
|
12353
|
-
}
|
|
12354
|
-
function resolveSessionTranscriptPath(edit) {
|
|
12355
|
-
if (edit.agentID === undefined) {
|
|
12356
|
-
return edit.transcriptPath;
|
|
12357
|
-
}
|
|
12358
|
-
if (typeof edit.agentID !== "string" || !/^[\w-]+$/u.test(edit.agentID)) {
|
|
12359
|
-
return null;
|
|
12360
|
-
}
|
|
12361
|
-
const sessionDir = edit.transcriptPath.replace(/\.jsonl$/u, "");
|
|
12362
|
-
return path5.join(sessionDir, "subagents", `agent-${edit.agentID}.jsonl`);
|
|
12363
|
-
}
|
|
12364
|
-
function printOutput(output) {
|
|
12365
|
-
if (output !== null) {
|
|
12366
|
-
console.log(JSON.stringify(output));
|
|
12367
|
-
}
|
|
12552
|
+
return isDirectory ? path7.join(absolute, written.fileName) : absolute;
|
|
12368
12553
|
}
|
|
12369
12554
|
async function checkBashResult(check, rules, result) {
|
|
12370
12555
|
const record = await readSnapshot(result.snapshotPath);
|
|
@@ -12397,13 +12582,13 @@ async function runBashResultStep(check, rules, result, step) {
|
|
|
12397
12582
|
}).with({ kind: "gate" }, (gate) => checkChangedPaths(check, rules, result, gate.changedPaths)).exhaustive();
|
|
12398
12583
|
}
|
|
12399
12584
|
async function checkChangedPaths(check, rules, result, changedPaths) {
|
|
12400
|
-
const skills = await readAvailableSkills(
|
|
12585
|
+
const skills = await readAvailableSkills(path7.join(check.projectDir, ".claude", "skills"));
|
|
12401
12586
|
const sessionTranscript = await readTranscript(resolveSessionTranscriptPath(check.hookInput));
|
|
12402
|
-
const sessionLoads =
|
|
12587
|
+
const sessionLoads = collectSessionLoads(sessionTranscript);
|
|
12403
12588
|
const changePlan = planBashSkillGate({
|
|
12404
12589
|
rules,
|
|
12405
12590
|
paths: changedPaths.map((relativePath) => ({
|
|
12406
|
-
path:
|
|
12591
|
+
path: path7.join(check.projectDir, relativePath),
|
|
12407
12592
|
relativePath
|
|
12408
12593
|
})),
|
|
12409
12594
|
loadedSkills: sessionLoads.skills,
|
package/dist/types.d.ts
CHANGED
|
@@ -8,9 +8,16 @@ export interface SkillGateRules {
|
|
|
8
8
|
readonly ignore: readonly string[];
|
|
9
9
|
readonly gates: readonly SkillGate[];
|
|
10
10
|
}
|
|
11
|
+
export interface ToolGate {
|
|
12
|
+
readonly tool: string;
|
|
13
|
+
readonly skills: readonly string[];
|
|
14
|
+
readonly references: readonly string[];
|
|
15
|
+
}
|
|
11
16
|
export type SkillGateRulesResult = {
|
|
12
17
|
readonly ok: true;
|
|
13
18
|
readonly rules: SkillGateRules;
|
|
19
|
+
readonly tools: readonly ToolGate[];
|
|
20
|
+
readonly unknownKeys: readonly string[];
|
|
14
21
|
} | {
|
|
15
22
|
readonly ok: false;
|
|
16
23
|
readonly error: string;
|
|
@@ -19,8 +26,9 @@ export interface UnknownSkill {
|
|
|
19
26
|
readonly match: string;
|
|
20
27
|
readonly skill: string;
|
|
21
28
|
}
|
|
22
|
-
export interface
|
|
29
|
+
export interface SessionLoads {
|
|
23
30
|
readonly skills: readonly string[];
|
|
31
|
+
readonly readPaths: readonly string[];
|
|
24
32
|
readonly compacted: boolean;
|
|
25
33
|
}
|
|
26
34
|
export interface SkillGateInput {
|
|
@@ -69,6 +77,25 @@ export interface WrittenPath {
|
|
|
69
77
|
export interface SkillGateOutputContext {
|
|
70
78
|
readonly compacted?: boolean;
|
|
71
79
|
readonly rulesError?: string;
|
|
80
|
+
readonly unknownKeys?: readonly string[];
|
|
81
|
+
}
|
|
82
|
+
export interface ToolGateInput {
|
|
83
|
+
readonly tools: readonly ToolGate[];
|
|
84
|
+
readonly toolName: string;
|
|
85
|
+
readonly skillsDir: string;
|
|
86
|
+
readonly loads: SessionLoads;
|
|
87
|
+
readonly availableSkills: readonly string[];
|
|
88
|
+
readonly availableReferences: readonly string[];
|
|
89
|
+
}
|
|
90
|
+
export interface UnknownToolRequirement {
|
|
91
|
+
readonly tool: string;
|
|
92
|
+
readonly kind: 'skill' | 'reference';
|
|
93
|
+
readonly name: string;
|
|
94
|
+
}
|
|
95
|
+
export interface ToolGatePlan {
|
|
96
|
+
readonly missingSkills: readonly string[];
|
|
97
|
+
readonly missingReferences: readonly string[];
|
|
98
|
+
readonly unknown: readonly UnknownToolRequirement[];
|
|
72
99
|
}
|
|
73
100
|
export interface SkillGateHookOutput {
|
|
74
101
|
readonly systemMessage?: string;
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zgeoff/skill-gate",
|
|
3
|
-
"version": "0.2.
|
|
4
|
-
"description": "A Claude Code hook that denies an edit until the session loads the skills the
|
|
3
|
+
"version": "0.2.5",
|
|
4
|
+
"description": "A Claude Code hook that denies an edit or a gated tool call until the session loads the skills and reads the reference files it needs, and blocks after a Bash command that changed a gated file without them",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"claude-code",
|
|
7
7
|
"hook",
|