@zgeoff/skill-gate 0.2.0 → 0.2.2
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/dist/index.js +1118 -0
- package/package.json +5 -9
- package/src/build-bash-skill-gate-output.ts +0 -41
- package/src/build-skill-gate-output.ts +0 -54
- package/src/collect-gate-skills.ts +0 -19
- package/src/collect-loaded-skills.ts +0 -98
- package/src/collect-written-paths.ts +0 -451
- package/src/format-skill-list.ts +0 -10
- package/src/index.ts +0 -1
- package/src/parse-shell-commands.ts +0 -429
- package/src/parse-skill-gate-rules.ts +0 -72
- package/src/plan-bash-skill-gate.ts +0 -21
- package/src/plan-skill-gate.ts +0 -21
- package/src/run-skill-gate.ts +0 -235
- package/src/types.ts +0 -96
package/dist/index.js
ADDED
|
@@ -0,0 +1,1118 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// src/run-skill-gate.ts
|
|
3
|
+
import { statSync } from "fs";
|
|
4
|
+
import path2 from "path";
|
|
5
|
+
// ../std/src/is-record.ts
|
|
6
|
+
function isRecord(value) {
|
|
7
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
8
|
+
}
|
|
9
|
+
// src/format-skill-list.ts
|
|
10
|
+
function formatSkillList(skills) {
|
|
11
|
+
const names = skills.map((skill) => `\`${skill}\``);
|
|
12
|
+
const noun = names.length === 1 ? "skill" : "skills";
|
|
13
|
+
if (names.length === 1) {
|
|
14
|
+
return `${names[0]} ${noun}`;
|
|
15
|
+
}
|
|
16
|
+
return `${names.slice(0, -1).join(", ")} and ${names.at(-1)} ${noun}`;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// src/build-bash-skill-gate-output.ts
|
|
20
|
+
var RULES_PATH = ".claude/skill-gate.json";
|
|
21
|
+
function buildBashSkillGateOutput(gatedPaths, missing, context = {}) {
|
|
22
|
+
if (gatedPaths.length === 0) {
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
const subject = gatedPaths.length === 1 ? `${gatedPaths[0]} is a gated path, so change it` : `${gatedPaths.join(", ")} are gated paths, so change them`;
|
|
26
|
+
const load = buildLoadInstruction(missing, context.compacted === true);
|
|
27
|
+
const rule = `${subject} with the Edit, Write or MultiEdit tool, never through Bash.`;
|
|
28
|
+
return {
|
|
29
|
+
hookSpecificOutput: {
|
|
30
|
+
hookEventName: "PreToolUse",
|
|
31
|
+
additionalContext: `skill-gate: this Bash command writes a gated path and runs anyway.${load} ${rule} ${RULES_PATH} lists the skills each path needs.`
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
function buildLoadInstruction(missing, compacted) {
|
|
36
|
+
if (missing.length === 0) {
|
|
37
|
+
return "";
|
|
38
|
+
}
|
|
39
|
+
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.`;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// src/build-skill-gate-output.ts
|
|
43
|
+
var RULES_PATH2 = ".claude/skill-gate.json";
|
|
44
|
+
var EDIT_TOOLS_NOTE = "Change a gated path only with Edit, Write or MultiEdit, never through Bash.";
|
|
45
|
+
function buildSkillGateOutput(filePath, plan, context = {}) {
|
|
46
|
+
const warnings = [
|
|
47
|
+
...context.rulesError === undefined ? [] : [`skill-gate: ${RULES_PATH2} ${context.rulesError}.`],
|
|
48
|
+
...plan.unknown.map((entry) => `skill-gate: the rule "${entry.match}" in ${RULES_PATH2} 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.`)
|
|
49
|
+
];
|
|
50
|
+
const warning = warnings.length === 0 ? undefined : warnings.join(`
|
|
51
|
+
`);
|
|
52
|
+
if (plan.missing.length > 0) {
|
|
53
|
+
const reason = context.compacted === true ? `Load the ${formatSkillList(plan.missing)} again with the Skill tool before editing ${filePath}, then retry the edit. This session was compacted, and a skill loaded before the compaction no longer counts. ${EDIT_TOOLS_NOTE} ${RULES_PATH2} lists the skills each path needs.` : `Load the ${formatSkillList(plan.missing)} with the Skill tool before editing ${filePath}, then retry the edit. ${EDIT_TOOLS_NOTE} ${RULES_PATH2} lists the skills each path needs.`;
|
|
54
|
+
return {
|
|
55
|
+
...warning === undefined ? {} : { systemMessage: warning },
|
|
56
|
+
hookSpecificOutput: {
|
|
57
|
+
hookEventName: "PreToolUse",
|
|
58
|
+
permissionDecision: "deny",
|
|
59
|
+
permissionDecisionReason: warning === undefined ? reason : `${reason}
|
|
60
|
+
${warning}`
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
if (warning === undefined) {
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
return {
|
|
68
|
+
systemMessage: warning,
|
|
69
|
+
hookSpecificOutput: { hookEventName: "PreToolUse", additionalContext: warning }
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// src/collect-loaded-skills.ts
|
|
74
|
+
function collectLoadedSkills(transcript) {
|
|
75
|
+
const entries = transcript.split(`
|
|
76
|
+
`).map((line) => parseEntry(line));
|
|
77
|
+
const lastBoundary = entries.findLastIndex((entry) => isCompactBoundary(entry));
|
|
78
|
+
const current = entries.slice(lastBoundary + 1);
|
|
79
|
+
const succeeded = collectSucceededToolUseIDs(current);
|
|
80
|
+
const skills = current.flatMap((entry) => collectEntrySkills(entry, succeeded));
|
|
81
|
+
return { skills: [...new Set(skills)], compacted: lastBoundary !== -1 };
|
|
82
|
+
}
|
|
83
|
+
function parseEntry(line) {
|
|
84
|
+
try {
|
|
85
|
+
return JSON.parse(line);
|
|
86
|
+
} catch {
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
function isCompactBoundary(entry) {
|
|
91
|
+
return isRecord(entry) && entry["type"] === "system" && entry["subtype"] === "compact_boundary";
|
|
92
|
+
}
|
|
93
|
+
function collectSucceededToolUseIDs(entries) {
|
|
94
|
+
return entries.flatMap((entry) => collectContentBlocks(entry, "user")).filter((block) => block["type"] === "tool_result" && block["is_error"] !== true).flatMap((block) => typeof block["tool_use_id"] === "string" ? [block["tool_use_id"]] : []);
|
|
95
|
+
}
|
|
96
|
+
function collectContentBlocks(entry, type) {
|
|
97
|
+
if (!isRecord(entry) || entry["type"] !== type || !isRecord(entry["message"])) {
|
|
98
|
+
return [];
|
|
99
|
+
}
|
|
100
|
+
const content = entry["message"]["content"];
|
|
101
|
+
return Array.isArray(content) ? content.filter((block) => isRecord(block)) : [];
|
|
102
|
+
}
|
|
103
|
+
function collectEntrySkills(entry, succeeded) {
|
|
104
|
+
const command = findSlashCommand(entry);
|
|
105
|
+
if (command !== undefined) {
|
|
106
|
+
return [command];
|
|
107
|
+
}
|
|
108
|
+
return collectContentBlocks(entry, "assistant").flatMap((block) => collectSkillCall(block, succeeded));
|
|
109
|
+
}
|
|
110
|
+
var SLASH_COMMAND_PATTERN = /^\s*(?:<command-message>[^<]*<\/command-message>\s*)?<command-name>\/(?<skill>[^<\s]+)<\/command-name>/u;
|
|
111
|
+
function findSlashCommand(entry) {
|
|
112
|
+
if (!isRecord(entry) || entry["type"] !== "user" || entry["isSidechain"] === true || !isRecord(entry["message"])) {
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
const content = entry["message"]["content"];
|
|
116
|
+
return typeof content === "string" ? SLASH_COMMAND_PATTERN.exec(content)?.groups?.["skill"] : undefined;
|
|
117
|
+
}
|
|
118
|
+
function collectSkillCall(block, succeeded) {
|
|
119
|
+
const input = block["input"];
|
|
120
|
+
const id = block["id"];
|
|
121
|
+
if (block["type"] !== "tool_use" || block["name"] !== "Skill" || !isRecord(input)) {
|
|
122
|
+
return [];
|
|
123
|
+
}
|
|
124
|
+
const skill = input["skill"];
|
|
125
|
+
return typeof skill === "string" && typeof id === "string" && succeeded.includes(id) ? [skill] : [];
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// src/collect-written-paths.ts
|
|
129
|
+
import path from "path";
|
|
130
|
+
|
|
131
|
+
// ../../node_modules/.bun/ts-pattern@5.9.0/node_modules/ts-pattern/dist/index.js
|
|
132
|
+
var t = Symbol.for("@ts-pattern/matcher");
|
|
133
|
+
var e = Symbol.for("@ts-pattern/isVariadic");
|
|
134
|
+
var n = "@ts-pattern/anonymous-select-key";
|
|
135
|
+
var r = (t) => Boolean(t && typeof t == "object");
|
|
136
|
+
var i = (e) => e && !!e[t];
|
|
137
|
+
var o = (n, s, c) => {
|
|
138
|
+
if (i(n)) {
|
|
139
|
+
const e = n[t](), { matched: r, selections: i } = e.match(s);
|
|
140
|
+
return r && i && Object.keys(i).forEach((t) => c(t, i[t])), r;
|
|
141
|
+
}
|
|
142
|
+
if (r(n)) {
|
|
143
|
+
if (!r(s))
|
|
144
|
+
return false;
|
|
145
|
+
if (Array.isArray(n)) {
|
|
146
|
+
if (!Array.isArray(s))
|
|
147
|
+
return false;
|
|
148
|
+
let t = [], r = [], u = [];
|
|
149
|
+
for (const o of n.keys()) {
|
|
150
|
+
const s = n[o];
|
|
151
|
+
i(s) && s[e] ? u.push(s) : u.length ? r.push(s) : t.push(s);
|
|
152
|
+
}
|
|
153
|
+
if (u.length) {
|
|
154
|
+
if (u.length > 1)
|
|
155
|
+
throw new Error("Pattern error: Using `...P.array(...)` several times in a single pattern is not allowed.");
|
|
156
|
+
if (s.length < t.length + r.length)
|
|
157
|
+
return false;
|
|
158
|
+
const e = s.slice(0, t.length), n = r.length === 0 ? [] : s.slice(-r.length), i = s.slice(t.length, r.length === 0 ? Infinity : -r.length);
|
|
159
|
+
return t.every((t, n) => o(t, e[n], c)) && r.every((t, e) => o(t, n[e], c)) && (u.length === 0 || o(u[0], i, c));
|
|
160
|
+
}
|
|
161
|
+
return n.length === s.length && n.every((t, e) => o(t, s[e], c));
|
|
162
|
+
}
|
|
163
|
+
return Reflect.ownKeys(n).every((e) => {
|
|
164
|
+
const r = n[e];
|
|
165
|
+
return ((e in s) || i(u = r) && u[t]().matcherType === "optional") && o(r, s[e], c);
|
|
166
|
+
var u;
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
return Object.is(s, n);
|
|
170
|
+
};
|
|
171
|
+
var s = (e) => {
|
|
172
|
+
var n, o, u;
|
|
173
|
+
return r(e) ? i(e) ? (n = (o = (u = e[t]()).getSelectionKeys) == null ? undefined : o.call(u)) != null ? n : [] : Array.isArray(e) ? c(e, s) : c(Object.values(e), s) : [];
|
|
174
|
+
};
|
|
175
|
+
var c = (t, e) => t.reduce((t, n) => t.concat(e(n)), []);
|
|
176
|
+
function a(t) {
|
|
177
|
+
return Object.assign(t, { optional: () => h(t), and: (e) => d(t, e), or: (e) => y(t, e), select: (e) => e === undefined ? v(t) : v(e, t) });
|
|
178
|
+
}
|
|
179
|
+
function h(e) {
|
|
180
|
+
return a({ [t]: () => ({ match: (t) => {
|
|
181
|
+
let n = {};
|
|
182
|
+
const r = (t, e) => {
|
|
183
|
+
n[t] = e;
|
|
184
|
+
};
|
|
185
|
+
return t === undefined ? (s(e).forEach((t) => r(t, undefined)), { matched: true, selections: n }) : { matched: o(e, t, r), selections: n };
|
|
186
|
+
}, getSelectionKeys: () => s(e), matcherType: "optional" }) });
|
|
187
|
+
}
|
|
188
|
+
function d(...e) {
|
|
189
|
+
return a({ [t]: () => ({ match: (t) => {
|
|
190
|
+
let n = {};
|
|
191
|
+
const r = (t, e) => {
|
|
192
|
+
n[t] = e;
|
|
193
|
+
};
|
|
194
|
+
return { matched: e.every((e) => o(e, t, r)), selections: n };
|
|
195
|
+
}, getSelectionKeys: () => c(e, s), matcherType: "and" }) });
|
|
196
|
+
}
|
|
197
|
+
function y(...e) {
|
|
198
|
+
return a({ [t]: () => ({ match: (t) => {
|
|
199
|
+
let n = {};
|
|
200
|
+
const r = (t, e) => {
|
|
201
|
+
n[t] = e;
|
|
202
|
+
};
|
|
203
|
+
return c(e, s).forEach((t) => r(t, undefined)), { matched: e.some((e) => o(e, t, r)), selections: n };
|
|
204
|
+
}, getSelectionKeys: () => c(e, s), matcherType: "or" }) });
|
|
205
|
+
}
|
|
206
|
+
function p(e) {
|
|
207
|
+
return { [t]: () => ({ match: (t) => ({ matched: Boolean(e(t)) }) }) };
|
|
208
|
+
}
|
|
209
|
+
function v(...e) {
|
|
210
|
+
const r = typeof e[0] == "string" ? e[0] : undefined, i = e.length === 2 ? e[1] : typeof e[0] == "string" ? undefined : e[0];
|
|
211
|
+
return a({ [t]: () => ({ match: (t) => {
|
|
212
|
+
let e = { [r != null ? r : n]: t };
|
|
213
|
+
return { matched: i === undefined || o(i, t, (t, n) => {
|
|
214
|
+
e[t] = n;
|
|
215
|
+
}), selections: e };
|
|
216
|
+
}, getSelectionKeys: () => [r != null ? r : n].concat(i === undefined ? [] : s(i)) }) });
|
|
217
|
+
}
|
|
218
|
+
function b(t) {
|
|
219
|
+
return true;
|
|
220
|
+
}
|
|
221
|
+
function w(t) {
|
|
222
|
+
return typeof t == "number";
|
|
223
|
+
}
|
|
224
|
+
function S(t) {
|
|
225
|
+
return typeof t == "string";
|
|
226
|
+
}
|
|
227
|
+
function j(t) {
|
|
228
|
+
return typeof t == "bigint";
|
|
229
|
+
}
|
|
230
|
+
var K = a(p(b));
|
|
231
|
+
var O = a(p(b));
|
|
232
|
+
var x = (t) => Object.assign(a(t), { startsWith: (e) => {
|
|
233
|
+
return x(d(t, (n = e, p((t) => S(t) && t.startsWith(n)))));
|
|
234
|
+
var n;
|
|
235
|
+
}, endsWith: (e) => {
|
|
236
|
+
return x(d(t, (n = e, p((t) => S(t) && t.endsWith(n)))));
|
|
237
|
+
var n;
|
|
238
|
+
}, minLength: (e) => x(d(t, ((t) => p((e) => S(e) && e.length >= t))(e))), length: (e) => x(d(t, ((t) => p((e) => S(e) && e.length === t))(e))), maxLength: (e) => x(d(t, ((t) => p((e) => S(e) && e.length <= t))(e))), includes: (e) => {
|
|
239
|
+
return x(d(t, (n = e, p((t) => S(t) && t.includes(n)))));
|
|
240
|
+
var n;
|
|
241
|
+
}, regex: (e) => {
|
|
242
|
+
return x(d(t, (n = e, p((t) => S(t) && Boolean(t.match(n))))));
|
|
243
|
+
var n;
|
|
244
|
+
} });
|
|
245
|
+
var A = x(p(S));
|
|
246
|
+
var N = (t) => Object.assign(a(t), { between: (e, n) => N(d(t, ((t, e) => p((n) => w(n) && t <= n && e >= n))(e, n))), lt: (e) => N(d(t, ((t) => p((e) => w(e) && e < t))(e))), gt: (e) => N(d(t, ((t) => p((e) => w(e) && e > t))(e))), lte: (e) => N(d(t, ((t) => p((e) => w(e) && e <= t))(e))), gte: (e) => N(d(t, ((t) => p((e) => w(e) && e >= t))(e))), int: () => N(d(t, p((t) => w(t) && Number.isInteger(t)))), finite: () => N(d(t, p((t) => w(t) && Number.isFinite(t)))), positive: () => N(d(t, p((t) => w(t) && t > 0))), negative: () => N(d(t, p((t) => w(t) && t < 0))) });
|
|
247
|
+
var P = N(p(w));
|
|
248
|
+
var k = (t) => Object.assign(a(t), { between: (e, n) => k(d(t, ((t, e) => p((n) => j(n) && t <= n && e >= n))(e, n))), lt: (e) => k(d(t, ((t) => p((e) => j(e) && e < t))(e))), gt: (e) => k(d(t, ((t) => p((e) => j(e) && e > t))(e))), lte: (e) => k(d(t, ((t) => p((e) => j(e) && e <= t))(e))), gte: (e) => k(d(t, ((t) => p((e) => j(e) && e >= t))(e))), positive: () => k(d(t, p((t) => j(t) && t > 0))), negative: () => k(d(t, p((t) => j(t) && t < 0))) });
|
|
249
|
+
var T = k(p(j));
|
|
250
|
+
var B = a(p(function(t) {
|
|
251
|
+
return typeof t == "boolean";
|
|
252
|
+
}));
|
|
253
|
+
var _ = a(p(function(t) {
|
|
254
|
+
return typeof t == "symbol";
|
|
255
|
+
}));
|
|
256
|
+
var W = a(p(function(t) {
|
|
257
|
+
return t == null;
|
|
258
|
+
}));
|
|
259
|
+
var $ = a(p(function(t) {
|
|
260
|
+
return t != null;
|
|
261
|
+
}));
|
|
262
|
+
class I extends Error {
|
|
263
|
+
constructor(t) {
|
|
264
|
+
let e;
|
|
265
|
+
try {
|
|
266
|
+
e = JSON.stringify(t);
|
|
267
|
+
} catch (n) {
|
|
268
|
+
e = t;
|
|
269
|
+
}
|
|
270
|
+
super(`Pattern matching error: no pattern matches value ${e}`), this.input = undefined, this.input = t;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
var L = { matched: false, value: undefined };
|
|
274
|
+
function M(t) {
|
|
275
|
+
return new R(t, L);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
class R {
|
|
279
|
+
constructor(t, e) {
|
|
280
|
+
this.input = undefined, this.state = undefined, this.input = t, this.state = e;
|
|
281
|
+
}
|
|
282
|
+
with(...t) {
|
|
283
|
+
if (this.state.matched)
|
|
284
|
+
return this;
|
|
285
|
+
const e = t[t.length - 1], r = [t[0]];
|
|
286
|
+
let i;
|
|
287
|
+
t.length === 3 && typeof t[1] == "function" ? i = t[1] : t.length > 2 && r.push(...t.slice(1, t.length - 1));
|
|
288
|
+
let s = false, c = {};
|
|
289
|
+
const u = (t, e) => {
|
|
290
|
+
s = true, c[t] = e;
|
|
291
|
+
}, a = !r.some((t) => o(t, this.input, u)) || i && !Boolean(i(this.input)) ? L : { matched: true, value: e(s ? n in c ? c[n] : c : this.input, this.input) };
|
|
292
|
+
return new R(this.input, a);
|
|
293
|
+
}
|
|
294
|
+
when(t, e) {
|
|
295
|
+
if (this.state.matched)
|
|
296
|
+
return this;
|
|
297
|
+
const n = Boolean(t(this.input));
|
|
298
|
+
return new R(this.input, n ? { matched: true, value: e(this.input, this.input) } : L);
|
|
299
|
+
}
|
|
300
|
+
otherwise(t) {
|
|
301
|
+
return this.state.matched ? this.state.value : t(this.input);
|
|
302
|
+
}
|
|
303
|
+
exhaustive(t = F) {
|
|
304
|
+
return this.state.matched ? this.state.value : t(this.input);
|
|
305
|
+
}
|
|
306
|
+
run() {
|
|
307
|
+
return this.exhaustive();
|
|
308
|
+
}
|
|
309
|
+
returnType() {
|
|
310
|
+
return this;
|
|
311
|
+
}
|
|
312
|
+
narrow() {
|
|
313
|
+
return this;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
function F(t) {
|
|
317
|
+
throw new I(t);
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// src/parse-shell-commands.ts
|
|
321
|
+
function parseShellCommands(text) {
|
|
322
|
+
const tokens = splitShellTokens(text);
|
|
323
|
+
return tokens === null ? null : buildShellCommands(tokens);
|
|
324
|
+
}
|
|
325
|
+
function splitShellTokens(text) {
|
|
326
|
+
const tokens = [];
|
|
327
|
+
const heredocs = [];
|
|
328
|
+
let heredocOperator = null;
|
|
329
|
+
let index = 0;
|
|
330
|
+
while (index < text.length) {
|
|
331
|
+
const char = text.charAt(index);
|
|
332
|
+
if (char === " " || char === "\t") {
|
|
333
|
+
index += 1;
|
|
334
|
+
} else if (char === "\\" && text.charAt(index + 1) === `
|
|
335
|
+
`) {
|
|
336
|
+
index += 2;
|
|
337
|
+
} else if (char === `
|
|
338
|
+
`) {
|
|
339
|
+
index += 1;
|
|
340
|
+
for (const heredoc of heredocs.splice(0)) {
|
|
341
|
+
const end = getHeredocEndOrTextEnd(text, index, heredoc);
|
|
342
|
+
tokens.push({ kind: "heredoc", body: text.slice(index, end.bodyEnd) });
|
|
343
|
+
index = end.next;
|
|
344
|
+
}
|
|
345
|
+
tokens.push({ kind: "separator", operator: `
|
|
346
|
+
` });
|
|
347
|
+
} else if (char === "#") {
|
|
348
|
+
const lineEnd = text.indexOf(`
|
|
349
|
+
`, index);
|
|
350
|
+
index = lineEnd === -1 ? text.length : lineEnd;
|
|
351
|
+
} else {
|
|
352
|
+
const operator = findOperator(text, index);
|
|
353
|
+
if (operator === null) {
|
|
354
|
+
const parsed = parseShellWord(text, index);
|
|
355
|
+
if (parsed === null) {
|
|
356
|
+
return null;
|
|
357
|
+
}
|
|
358
|
+
index = parsed.end;
|
|
359
|
+
if (heredocOperator !== null) {
|
|
360
|
+
heredocs.push({ delimiter: parsed.word.text, stripTabs: heredocOperator === "<<-" });
|
|
361
|
+
heredocOperator = null;
|
|
362
|
+
}
|
|
363
|
+
if (!(isFileDescriptor(parsed.word) && isRedirectStart(text.charAt(index)))) {
|
|
364
|
+
tokens.push({ kind: "word", word: parsed.word });
|
|
365
|
+
}
|
|
366
|
+
} else {
|
|
367
|
+
index += operator.length;
|
|
368
|
+
heredocOperator = operator === "<<" || operator === "<<-" ? operator : null;
|
|
369
|
+
tokens.push(buildOperatorToken(operator));
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
return tokens;
|
|
374
|
+
}
|
|
375
|
+
function getHeredocEndOrTextEnd(text, start, heredoc) {
|
|
376
|
+
let lineStart = start;
|
|
377
|
+
while (lineStart < text.length) {
|
|
378
|
+
const newline = text.indexOf(`
|
|
379
|
+
`, lineStart);
|
|
380
|
+
const lineEnd = newline === -1 ? text.length : newline;
|
|
381
|
+
const line = text.slice(lineStart, lineEnd);
|
|
382
|
+
if ((heredoc.stripTabs ? line.replace(/^\t+/u, "") : line) === heredoc.delimiter) {
|
|
383
|
+
return { bodyEnd: lineStart, next: lineEnd };
|
|
384
|
+
}
|
|
385
|
+
lineStart = lineEnd + 1;
|
|
386
|
+
}
|
|
387
|
+
return { bodyEnd: text.length, next: text.length };
|
|
388
|
+
}
|
|
389
|
+
var OPERATORS = [
|
|
390
|
+
"&>>",
|
|
391
|
+
"<<-",
|
|
392
|
+
"<<<",
|
|
393
|
+
">>",
|
|
394
|
+
">|",
|
|
395
|
+
"&>",
|
|
396
|
+
">&",
|
|
397
|
+
"<&",
|
|
398
|
+
"<>",
|
|
399
|
+
"<<",
|
|
400
|
+
"&&",
|
|
401
|
+
"||",
|
|
402
|
+
"|&",
|
|
403
|
+
";;",
|
|
404
|
+
">",
|
|
405
|
+
"<",
|
|
406
|
+
"|",
|
|
407
|
+
"&",
|
|
408
|
+
";",
|
|
409
|
+
"(",
|
|
410
|
+
")"
|
|
411
|
+
];
|
|
412
|
+
function findOperator(text, index) {
|
|
413
|
+
return OPERATORS.find((operator) => text.startsWith(operator, index)) ?? null;
|
|
414
|
+
}
|
|
415
|
+
var GLOB_CHARS = "*?[{";
|
|
416
|
+
function parseShellWord(text, start) {
|
|
417
|
+
let value = "";
|
|
418
|
+
let literal = true;
|
|
419
|
+
let index = start;
|
|
420
|
+
while (index < text.length && !isWordEnd(text.charAt(index))) {
|
|
421
|
+
const char = text.charAt(index);
|
|
422
|
+
if (char === "\\") {
|
|
423
|
+
value += text.charAt(index + 1);
|
|
424
|
+
index += 2;
|
|
425
|
+
} else if (char === "'") {
|
|
426
|
+
const close = text.indexOf("'", index + 1);
|
|
427
|
+
if (close === -1) {
|
|
428
|
+
return null;
|
|
429
|
+
}
|
|
430
|
+
value += text.slice(index + 1, close);
|
|
431
|
+
index = close + 1;
|
|
432
|
+
} else if (char === '"') {
|
|
433
|
+
const quoted = parseDoubleQuoted(text, index + 1);
|
|
434
|
+
if (quoted === null) {
|
|
435
|
+
return null;
|
|
436
|
+
}
|
|
437
|
+
value += quoted.value;
|
|
438
|
+
literal &&= quoted.literal;
|
|
439
|
+
index = quoted.end;
|
|
440
|
+
} else if (char === "$" || char === "`") {
|
|
441
|
+
const end = findExpansionEnd(text, index);
|
|
442
|
+
if (end === null) {
|
|
443
|
+
return null;
|
|
444
|
+
}
|
|
445
|
+
literal = false;
|
|
446
|
+
index = end;
|
|
447
|
+
} else {
|
|
448
|
+
if (GLOB_CHARS.includes(char) || char === "~" && index === start) {
|
|
449
|
+
literal = false;
|
|
450
|
+
}
|
|
451
|
+
value += char;
|
|
452
|
+
index += 1;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
return { word: { text: value, literal }, end: index };
|
|
456
|
+
}
|
|
457
|
+
function isWordEnd(char) {
|
|
458
|
+
return `
|
|
459
|
+
;&|<>()`.includes(char);
|
|
460
|
+
}
|
|
461
|
+
function parseDoubleQuoted(text, start) {
|
|
462
|
+
let value = "";
|
|
463
|
+
let literal = true;
|
|
464
|
+
let index = start;
|
|
465
|
+
while (index < text.length) {
|
|
466
|
+
const char = text.charAt(index);
|
|
467
|
+
if (char === '"') {
|
|
468
|
+
return { value, literal, end: index + 1 };
|
|
469
|
+
}
|
|
470
|
+
if (char === "\\" && '"\\$`\n'.includes(text.charAt(index + 1))) {
|
|
471
|
+
value += text.charAt(index + 1);
|
|
472
|
+
index += 2;
|
|
473
|
+
} else if (char === "$" || char === "`") {
|
|
474
|
+
const end = findExpansionEnd(text, index);
|
|
475
|
+
if (end === null) {
|
|
476
|
+
return null;
|
|
477
|
+
}
|
|
478
|
+
literal = false;
|
|
479
|
+
index = end;
|
|
480
|
+
} else {
|
|
481
|
+
value += char;
|
|
482
|
+
index += 1;
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
return null;
|
|
486
|
+
}
|
|
487
|
+
function findExpansionEnd(text, index) {
|
|
488
|
+
if (text.charAt(index) === "`") {
|
|
489
|
+
const close = text.indexOf("`", index + 1);
|
|
490
|
+
return close === -1 ? null : close + 1;
|
|
491
|
+
}
|
|
492
|
+
const next = text.charAt(index + 1);
|
|
493
|
+
if (next === "(" || next === "{") {
|
|
494
|
+
return findGroupEnd(text, index + 1);
|
|
495
|
+
}
|
|
496
|
+
const name = /^(?:[A-Za-z_]\w*|[0-9?#@*$!-])/u.exec(text.slice(index + 1));
|
|
497
|
+
return index + 1 + (name?.[0].length ?? 0);
|
|
498
|
+
}
|
|
499
|
+
function findGroupEnd(text, index) {
|
|
500
|
+
let depth = 0;
|
|
501
|
+
let cursor = index;
|
|
502
|
+
while (cursor < text.length) {
|
|
503
|
+
const char = text.charAt(cursor);
|
|
504
|
+
if (char === "'") {
|
|
505
|
+
const close = text.indexOf("'", cursor + 1);
|
|
506
|
+
if (close === -1) {
|
|
507
|
+
return null;
|
|
508
|
+
}
|
|
509
|
+
cursor = close + 1;
|
|
510
|
+
} else {
|
|
511
|
+
depth += getDepthChange(char);
|
|
512
|
+
cursor += char === "\\" ? 2 : 1;
|
|
513
|
+
if (depth === 0) {
|
|
514
|
+
return cursor;
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
return null;
|
|
519
|
+
}
|
|
520
|
+
function getDepthChange(char) {
|
|
521
|
+
if ("({".includes(char)) {
|
|
522
|
+
return 1;
|
|
523
|
+
}
|
|
524
|
+
return ")}".includes(char) ? -1 : 0;
|
|
525
|
+
}
|
|
526
|
+
function isFileDescriptor(word) {
|
|
527
|
+
return word.literal && /^\d+$/u.test(word.text);
|
|
528
|
+
}
|
|
529
|
+
function isRedirectStart(char) {
|
|
530
|
+
return char === "<" || char === ">";
|
|
531
|
+
}
|
|
532
|
+
var SEPARATORS = new Set(["&&", "||", "|&", ";;", "|", "&", ";"]);
|
|
533
|
+
function buildOperatorToken(operator) {
|
|
534
|
+
if (operator === "(" || operator === ")") {
|
|
535
|
+
return { kind: "subshell", opens: operator === "(" };
|
|
536
|
+
}
|
|
537
|
+
return SEPARATORS.has(operator) ? { kind: "separator", operator } : { kind: "redirect", operator };
|
|
538
|
+
}
|
|
539
|
+
var LIST_ENDS = new Set(["&", ";", ";;", `
|
|
540
|
+
`]);
|
|
541
|
+
function buildShellCommands(tokens) {
|
|
542
|
+
const commands = [];
|
|
543
|
+
const heredocOwners = [];
|
|
544
|
+
let draft = buildCommandDraft();
|
|
545
|
+
let operator = null;
|
|
546
|
+
let pipedIn = false;
|
|
547
|
+
const listStarts = [0];
|
|
548
|
+
const collectDraft = (separator) => {
|
|
549
|
+
const pipedOut = separator === "|" || separator === "|&";
|
|
550
|
+
if (draft.words.length > 0 || draft.redirects.length > 0) {
|
|
551
|
+
const piped = pipedIn || pipedOut;
|
|
552
|
+
draft.enters += piped ? 1 : 0;
|
|
553
|
+
draft.leaves += piped ? 1 : 0;
|
|
554
|
+
commands.push(draft);
|
|
555
|
+
draft = buildCommandDraft();
|
|
556
|
+
}
|
|
557
|
+
operator = null;
|
|
558
|
+
pipedIn = pipedOut;
|
|
559
|
+
const listStart = listStarts.at(-1) ?? 0;
|
|
560
|
+
const first = commands[listStart];
|
|
561
|
+
const last = commands.at(-1);
|
|
562
|
+
if (separator === "&" && first !== undefined && last !== undefined) {
|
|
563
|
+
first.enters += 1;
|
|
564
|
+
last.leaves += 1;
|
|
565
|
+
}
|
|
566
|
+
if (separator !== null && LIST_ENDS.has(separator)) {
|
|
567
|
+
listStarts[listStarts.length - 1] = commands.length;
|
|
568
|
+
}
|
|
569
|
+
};
|
|
570
|
+
const collectToken = (token) => {
|
|
571
|
+
M(token).with({ kind: "separator" }, (separator) => {
|
|
572
|
+
collectDraft(separator.operator);
|
|
573
|
+
}).with({ kind: "subshell" }, (subshell) => {
|
|
574
|
+
collectDraft(null);
|
|
575
|
+
const last = commands.at(-1);
|
|
576
|
+
if (subshell.opens) {
|
|
577
|
+
draft.enters += 1;
|
|
578
|
+
listStarts.push(commands.length);
|
|
579
|
+
} else {
|
|
580
|
+
listStarts.pop();
|
|
581
|
+
if (last !== undefined) {
|
|
582
|
+
last.leaves += 1;
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
}).with({ kind: "heredoc" }, (heredoc) => {
|
|
586
|
+
const owner = heredocOwners.shift();
|
|
587
|
+
if (owner !== undefined) {
|
|
588
|
+
owner.stdin = heredoc.body;
|
|
589
|
+
}
|
|
590
|
+
}).with({ kind: "redirect" }, (redirect) => {
|
|
591
|
+
operator = redirect.operator;
|
|
592
|
+
if (operator === "<<" || operator === "<<-") {
|
|
593
|
+
heredocOwners.push(draft);
|
|
594
|
+
}
|
|
595
|
+
}).with({ kind: "word" }, (word) => {
|
|
596
|
+
if (operator === null) {
|
|
597
|
+
draft.words.push(word.word);
|
|
598
|
+
} else {
|
|
599
|
+
draft.redirects.push({ operator, target: word.word });
|
|
600
|
+
operator = null;
|
|
601
|
+
}
|
|
602
|
+
}).exhaustive();
|
|
603
|
+
};
|
|
604
|
+
for (const token of tokens) {
|
|
605
|
+
collectToken(token);
|
|
606
|
+
}
|
|
607
|
+
collectDraft(null);
|
|
608
|
+
return commands;
|
|
609
|
+
}
|
|
610
|
+
function buildCommandDraft() {
|
|
611
|
+
return { words: [], redirects: [], stdin: null, enters: 0, leaves: 0 };
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
// src/collect-written-paths.ts
|
|
615
|
+
function collectWrittenPaths(command) {
|
|
616
|
+
return collectTextPaths(command, "");
|
|
617
|
+
}
|
|
618
|
+
function collectTextPaths(text, directory) {
|
|
619
|
+
const commands = parseShellCommands(text) ?? [];
|
|
620
|
+
const paths = [];
|
|
621
|
+
const parentDirs = [];
|
|
622
|
+
let current = directory;
|
|
623
|
+
for (const command of commands) {
|
|
624
|
+
const enteredFrom = current;
|
|
625
|
+
parentDirs.push(...Array.from({ length: command.enters }, () => enteredFrom));
|
|
626
|
+
paths.push(...collectCommandPaths(command, current));
|
|
627
|
+
current = resolveNextDir(command, current);
|
|
628
|
+
for (let left = 0;left < command.leaves && parentDirs.length > 0; left += 1) {
|
|
629
|
+
current = parentDirs.pop() ?? null;
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
return paths;
|
|
633
|
+
}
|
|
634
|
+
function collectCommandPaths(command, directory) {
|
|
635
|
+
const redirected = command.redirects.filter((redirect) => isWriteRedirect(redirect.operator, redirect.target)).flatMap((redirect) => resolveWordPath(redirect.target, directory));
|
|
636
|
+
const words = getProgramWords(command.words);
|
|
637
|
+
const [program] = words;
|
|
638
|
+
if (program === undefined || !program.literal) {
|
|
639
|
+
return redirected;
|
|
640
|
+
}
|
|
641
|
+
const name = path.basename(program.text);
|
|
642
|
+
const args = words.slice(1);
|
|
643
|
+
return [...redirected, ...collectProgramPaths(name, args, command.stdin, directory)];
|
|
644
|
+
}
|
|
645
|
+
var WRITE_REDIRECTS = new Set([">", ">>", ">|", "&>", "&>>", "<>"]);
|
|
646
|
+
function isWriteRedirect(operator, target) {
|
|
647
|
+
return WRITE_REDIRECTS.has(operator) || operator === ">&" && !/^(?:\d+|-)$/u.test(target.text);
|
|
648
|
+
}
|
|
649
|
+
function resolveWordPath(word, directory) {
|
|
650
|
+
if (word === undefined || !word.literal || word.text === "" || word.text === "-") {
|
|
651
|
+
return [];
|
|
652
|
+
}
|
|
653
|
+
if (path.isAbsolute(word.text)) {
|
|
654
|
+
return [{ path: word.text }];
|
|
655
|
+
}
|
|
656
|
+
return directory === null ? [] : [{ path: path.join(directory, word.text) }];
|
|
657
|
+
}
|
|
658
|
+
var ASSIGNMENT = /^[A-Za-z_]\w*=/u;
|
|
659
|
+
var WRAPPER_VALUE_OPTIONS = new Map([
|
|
660
|
+
["sudo", new Set(["-u", "-g", "-C", "-D", "-p", "-r", "-t", "-T", "-U"])],
|
|
661
|
+
["env", new Set(["-u", "-C", "-S", "--unset", "--chdir", "--split-string"])],
|
|
662
|
+
["nice", new Set(["-n", "--adjustment"])],
|
|
663
|
+
["time", new Set(["-f", "-o", "--format", "--output"])],
|
|
664
|
+
["exec", new Set(["-a"])],
|
|
665
|
+
["command", new Set],
|
|
666
|
+
["builtin", new Set],
|
|
667
|
+
["nohup", new Set]
|
|
668
|
+
]);
|
|
669
|
+
function getProgramWords(words) {
|
|
670
|
+
let index = 0;
|
|
671
|
+
while (index < words.length) {
|
|
672
|
+
const word = words[index];
|
|
673
|
+
if (word === undefined) {
|
|
674
|
+
break;
|
|
675
|
+
}
|
|
676
|
+
if (ASSIGNMENT.test(word.text)) {
|
|
677
|
+
index += 1;
|
|
678
|
+
} else if (word.literal && WRAPPER_VALUE_OPTIONS.has(word.text)) {
|
|
679
|
+
const valueOptions = WRAPPER_VALUE_OPTIONS.get(word.text) ?? new Set;
|
|
680
|
+
index += 1;
|
|
681
|
+
while (words[index]?.text.startsWith("-") === true) {
|
|
682
|
+
index += valueOptions.has(words[index]?.text ?? "") ? 2 : 1;
|
|
683
|
+
}
|
|
684
|
+
} else {
|
|
685
|
+
break;
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
return words.slice(index);
|
|
689
|
+
}
|
|
690
|
+
var SHELLS = new Set(["bash", "sh", "zsh", "dash"]);
|
|
691
|
+
var INTERPRETERS = new Set(["python", "python3", "node", "bun", "deno", "ruby"]);
|
|
692
|
+
var JS_RUNTIMES = new Set(["node", "bun", "deno"]);
|
|
693
|
+
var SED_SCRIPT_FLAGS = new Set(["e", "f"]);
|
|
694
|
+
function collectProgramPaths(name, args, stdin, directory) {
|
|
695
|
+
if (name === "sed" || name === "gsed") {
|
|
696
|
+
return collectInPlacePaths(args, SED_SCRIPT_FLAGS).flatMap((word) => resolveWordPath(word, directory));
|
|
697
|
+
}
|
|
698
|
+
if (name === "perl") {
|
|
699
|
+
return collectPerlPaths(args, stdin, directory);
|
|
700
|
+
}
|
|
701
|
+
if (name === "tee") {
|
|
702
|
+
return collectOperands(args).flatMap((word) => resolveWordPath(word, directory));
|
|
703
|
+
}
|
|
704
|
+
if (name === "cp" || name === "mv") {
|
|
705
|
+
return collectCopyPaths(args, directory);
|
|
706
|
+
}
|
|
707
|
+
if (SHELLS.has(name)) {
|
|
708
|
+
const script = findShellScript(args, stdin);
|
|
709
|
+
return script === null ? [] : collectTextPaths(script, directory);
|
|
710
|
+
}
|
|
711
|
+
if (INTERPRETERS.has(name)) {
|
|
712
|
+
const script = findInlineScript(args, stdin);
|
|
713
|
+
const commentStart = JS_RUNTIMES.has(name) ? "//" : "#";
|
|
714
|
+
return script === null ? [] : collectScriptPaths(script, commentStart, directory);
|
|
715
|
+
}
|
|
716
|
+
return [];
|
|
717
|
+
}
|
|
718
|
+
function collectInPlacePaths(args, scriptFlags) {
|
|
719
|
+
let inPlace = false;
|
|
720
|
+
let hasScriptFlag = false;
|
|
721
|
+
let optionsEnded = false;
|
|
722
|
+
const operands = [];
|
|
723
|
+
for (let index = 0;index < args.length; index += 1) {
|
|
724
|
+
const arg = args[index];
|
|
725
|
+
if (arg === undefined) {
|
|
726
|
+
break;
|
|
727
|
+
}
|
|
728
|
+
if (optionsEnded || !arg.text.startsWith("-") || arg.text === "-") {
|
|
729
|
+
operands.push(arg);
|
|
730
|
+
} else if (arg.text === "--") {
|
|
731
|
+
optionsEnded = true;
|
|
732
|
+
} else if (arg.text.startsWith("--")) {
|
|
733
|
+
inPlace ||= arg.text === "--in-place" || arg.text.startsWith("--in-place=");
|
|
734
|
+
if (/^--(?:expression|file)(?:=|$)/u.test(arg.text)) {
|
|
735
|
+
hasScriptFlag = true;
|
|
736
|
+
index += arg.text.includes("=") ? 0 : 1;
|
|
737
|
+
}
|
|
738
|
+
} else {
|
|
739
|
+
const flags = parseShortFlags(arg.text, scriptFlags);
|
|
740
|
+
inPlace ||= flags.inPlace;
|
|
741
|
+
hasScriptFlag ||= flags.script;
|
|
742
|
+
index += flags.takesNext ? 1 : 0;
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
if (!inPlace) {
|
|
746
|
+
return [];
|
|
747
|
+
}
|
|
748
|
+
return hasScriptFlag ? operands : operands.slice(1);
|
|
749
|
+
}
|
|
750
|
+
function parseShortFlags(bundle, scriptFlags) {
|
|
751
|
+
for (let index = 1;index < bundle.length; index += 1) {
|
|
752
|
+
const flag = bundle.charAt(index);
|
|
753
|
+
if (flag === "i") {
|
|
754
|
+
return { inPlace: true, script: false, takesNext: false };
|
|
755
|
+
}
|
|
756
|
+
if (scriptFlags.has(flag)) {
|
|
757
|
+
return { inPlace: false, script: true, takesNext: index === bundle.length - 1 };
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
return { inPlace: false, script: false, takesNext: false };
|
|
761
|
+
}
|
|
762
|
+
var PERL_SCRIPT_FLAGS = new Set(["e", "E"]);
|
|
763
|
+
function collectPerlPaths(args, stdin, directory) {
|
|
764
|
+
const inPlace = collectInPlacePaths(args, PERL_SCRIPT_FLAGS);
|
|
765
|
+
if (inPlace.length > 0) {
|
|
766
|
+
return inPlace.flatMap((word) => resolveWordPath(word, directory));
|
|
767
|
+
}
|
|
768
|
+
const script = findInlineScript(args, stdin);
|
|
769
|
+
return script === null ? [] : collectScriptPaths(script, "#", directory);
|
|
770
|
+
}
|
|
771
|
+
var INLINE_FLAGS = new Set(["-c", "-e", "-E", "--eval", "-p", "--print", "eval"]);
|
|
772
|
+
function findInlineScript(args, stdin) {
|
|
773
|
+
const flagIndex = args.findIndex((arg) => INLINE_FLAGS.has(arg.text));
|
|
774
|
+
const code = flagIndex === -1 ? undefined : args[flagIndex + 1];
|
|
775
|
+
if (code !== undefined) {
|
|
776
|
+
return code.literal ? code.text : null;
|
|
777
|
+
}
|
|
778
|
+
const readsStdin = args.length === 0 || args.some((arg) => arg.text === "-");
|
|
779
|
+
return readsStdin ? stdin : null;
|
|
780
|
+
}
|
|
781
|
+
var SCRIPT_WRITE_PATTERNS = [
|
|
782
|
+
/\b(?:writeFile|writeFileSync|appendFile|appendFileSync|createWriteStream)\(\s*(?<quote>['"`])(?<path>[^'"`]+)\k<quote>/gu,
|
|
783
|
+
/\bBun\.write\(\s*(?<quote>['"`])(?<path>[^'"`]+)\k<quote>/gu,
|
|
784
|
+
/\bopen\(\s*(?<quote>['"])(?<path>[^'"]+)\k<quote>\s*,\s*(?:mode\s*=\s*)?(?<modeQuote>['"])[^'"]*[wax+][^'"]*\k<modeQuote>/gu,
|
|
785
|
+
/\bPath\(\s*(?<quote>['"])(?<path>[^'"]+)\k<quote>\s*\)\.write_(?:text|bytes)\(/gu,
|
|
786
|
+
/\bFile\.write\(\s*(?<quote>['"])(?<path>[^'"]+)\k<quote>/gu,
|
|
787
|
+
/\bopen\s*\(?\s*(?:my\s+)?\$?\w+\s*,\s*['"](?:>|>>|\+<)['"]\s*,\s*(?<quote>['"])(?<path>[^'"]+)\k<quote>/gu
|
|
788
|
+
];
|
|
789
|
+
function collectScriptPaths(script, commentStart, directory) {
|
|
790
|
+
const textRanges = collectScriptTextRanges(script, commentStart);
|
|
791
|
+
return SCRIPT_WRITE_PATTERNS.flatMap((pattern) => [...script.matchAll(pattern)].flatMap((match) => {
|
|
792
|
+
const written = match.groups?.["path"] ?? "";
|
|
793
|
+
const isText = textRanges.some((range) => match.index > range.start && match.index < range.end);
|
|
794
|
+
return isText || /[$*?{]/u.test(written) ? [] : resolveWordPath({ text: written, literal: true }, directory);
|
|
795
|
+
}));
|
|
796
|
+
}
|
|
797
|
+
function collectScriptTextRanges(script, commentStart) {
|
|
798
|
+
const ranges = [];
|
|
799
|
+
let index = 0;
|
|
800
|
+
while (index < script.length) {
|
|
801
|
+
const char = script.charAt(index);
|
|
802
|
+
if (commentStart === "//" && script.startsWith("/*", index)) {
|
|
803
|
+
const close = script.indexOf("*/", index + 2);
|
|
804
|
+
const end = close === -1 ? script.length : close + 2;
|
|
805
|
+
ranges.push({ start: index, end });
|
|
806
|
+
index = end;
|
|
807
|
+
} else if (script.startsWith(commentStart, index)) {
|
|
808
|
+
const newline = script.indexOf(`
|
|
809
|
+
`, index);
|
|
810
|
+
const end = newline === -1 ? script.length : newline;
|
|
811
|
+
ranges.push({ start: index, end });
|
|
812
|
+
index = end;
|
|
813
|
+
} else if (char === "'" || char === '"' || char === "`") {
|
|
814
|
+
const end = getQuoteEndOrScriptEnd(script, index);
|
|
815
|
+
ranges.push({ start: index, end });
|
|
816
|
+
index = end;
|
|
817
|
+
} else {
|
|
818
|
+
index += 1;
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
return ranges;
|
|
822
|
+
}
|
|
823
|
+
function getQuoteEndOrScriptEnd(script, start) {
|
|
824
|
+
const quote = script.charAt(start);
|
|
825
|
+
let index = start + 1;
|
|
826
|
+
while (index < script.length && script.charAt(index) !== quote) {
|
|
827
|
+
index += script.charAt(index) === "\\" ? 2 : 1;
|
|
828
|
+
}
|
|
829
|
+
return Math.min(index + 1, script.length);
|
|
830
|
+
}
|
|
831
|
+
function collectOperands(args) {
|
|
832
|
+
return args.filter((arg) => !arg.text.startsWith("-"));
|
|
833
|
+
}
|
|
834
|
+
function collectCopyPaths(args, directory) {
|
|
835
|
+
const operands = [];
|
|
836
|
+
let targetDir;
|
|
837
|
+
let optionsEnded = false;
|
|
838
|
+
for (let index = 0;index < args.length; index += 1) {
|
|
839
|
+
const arg = args[index];
|
|
840
|
+
if (arg === undefined) {
|
|
841
|
+
break;
|
|
842
|
+
}
|
|
843
|
+
if (optionsEnded || !arg.text.startsWith("-") || arg.text === "-") {
|
|
844
|
+
operands.push(arg);
|
|
845
|
+
} else if (arg.text === "--") {
|
|
846
|
+
optionsEnded = true;
|
|
847
|
+
} else if (arg.text.startsWith("--target-directory=")) {
|
|
848
|
+
targetDir = { ...arg, text: arg.text.slice("--target-directory=".length) };
|
|
849
|
+
} else if (arg.text === "--target-directory" || /^-[^-]*t$/u.test(arg.text)) {
|
|
850
|
+
targetDir = args[index + 1];
|
|
851
|
+
index += 1;
|
|
852
|
+
} else if (arg.text === "-S" || arg.text === "--suffix") {
|
|
853
|
+
index += 1;
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
if (targetDir !== undefined) {
|
|
857
|
+
return collectIntoDirPaths(targetDir, operands, directory);
|
|
858
|
+
}
|
|
859
|
+
const destination = operands.at(-1);
|
|
860
|
+
const sources = operands.slice(0, -1);
|
|
861
|
+
const [source] = sources;
|
|
862
|
+
if (destination === undefined || source === undefined) {
|
|
863
|
+
return [];
|
|
864
|
+
}
|
|
865
|
+
if (sources.length > 1 || destination.text.endsWith("/")) {
|
|
866
|
+
return collectIntoDirPaths(destination, sources, directory);
|
|
867
|
+
}
|
|
868
|
+
const fileName = source.literal ? path.basename(source.text) : undefined;
|
|
869
|
+
return resolveWordPath(destination, directory).map((written) => fileName === undefined ? written : { path: written.path, fileName });
|
|
870
|
+
}
|
|
871
|
+
function collectIntoDirPaths(target, sources, directory) {
|
|
872
|
+
return resolveWordPath(target, directory).flatMap((written) => sources.filter((source) => source.literal).map((source) => ({ path: path.join(written.path, path.basename(source.text)) })));
|
|
873
|
+
}
|
|
874
|
+
function findShellScript(args, stdin) {
|
|
875
|
+
const hasCommandFlag = args.some((arg) => /^-[A-Za-z]*c[A-Za-z]*$/u.test(arg.text));
|
|
876
|
+
const [script] = collectOperands(args);
|
|
877
|
+
if (hasCommandFlag) {
|
|
878
|
+
return script?.literal === true ? script.text : null;
|
|
879
|
+
}
|
|
880
|
+
return script === undefined ? stdin : null;
|
|
881
|
+
}
|
|
882
|
+
function resolveNextDir(command, directory) {
|
|
883
|
+
const [program, ...args] = command.words;
|
|
884
|
+
if (program?.text !== "cd") {
|
|
885
|
+
return directory;
|
|
886
|
+
}
|
|
887
|
+
const [target] = collectOperands(args);
|
|
888
|
+
if (target === undefined || !target.literal) {
|
|
889
|
+
return null;
|
|
890
|
+
}
|
|
891
|
+
if (path.isAbsolute(target.text)) {
|
|
892
|
+
return target.text;
|
|
893
|
+
}
|
|
894
|
+
return directory === null ? null : path.join(directory, target.text);
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
// src/parse-skill-gate-rules.ts
|
|
898
|
+
function parseSkillGateRules(text) {
|
|
899
|
+
const value = parseJSON(text);
|
|
900
|
+
if (value instanceof Error) {
|
|
901
|
+
return { ok: false, error: `is not valid JSON: ${value.message}` };
|
|
902
|
+
}
|
|
903
|
+
if (!isRecord(value)) {
|
|
904
|
+
return { ok: false, error: "must hold a JSON object" };
|
|
905
|
+
}
|
|
906
|
+
return parseRulesRecord(value);
|
|
907
|
+
}
|
|
908
|
+
function parseJSON(text) {
|
|
909
|
+
try {
|
|
910
|
+
return JSON.parse(text);
|
|
911
|
+
} catch (error) {
|
|
912
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
function parseRulesRecord(value) {
|
|
916
|
+
const ignore = value["ignore"] ?? [];
|
|
917
|
+
if (!isStringArray(ignore)) {
|
|
918
|
+
return { ok: false, error: "`ignore` must be an array of non-empty strings" };
|
|
919
|
+
}
|
|
920
|
+
const gates = value["gates"];
|
|
921
|
+
if (!Array.isArray(gates)) {
|
|
922
|
+
return { ok: false, error: "`gates` must be an array" };
|
|
923
|
+
}
|
|
924
|
+
return parseGates(ignore, gates);
|
|
925
|
+
}
|
|
926
|
+
function isStringArray(value) {
|
|
927
|
+
return Array.isArray(value) && value.every((item) => typeof item === "string" && item !== "");
|
|
928
|
+
}
|
|
929
|
+
function parseGates(ignore, gates) {
|
|
930
|
+
const parsed = gates.map((gate, index) => parseGate(gate, index));
|
|
931
|
+
const error = parsed.find((gate) => typeof gate === "string");
|
|
932
|
+
if (typeof error === "string") {
|
|
933
|
+
return { ok: false, error };
|
|
934
|
+
}
|
|
935
|
+
return { ok: true, rules: { ignore, gates: parsed.filter((gate) => typeof gate !== "string") } };
|
|
936
|
+
}
|
|
937
|
+
function parseGate(gate, index) {
|
|
938
|
+
if (!isRecord(gate) || typeof gate["match"] !== "string" || gate["match"] === "") {
|
|
939
|
+
return `gate ${index} needs a non-empty string \`match\``;
|
|
940
|
+
}
|
|
941
|
+
const skills = gate["skills"];
|
|
942
|
+
if (!isStringArray(skills) || skills.length === 0) {
|
|
943
|
+
return `gate "${gate["match"]}" needs a non-empty \`skills\` array of non-empty strings`;
|
|
944
|
+
}
|
|
945
|
+
return { match: gate["match"], skills };
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
// src/collect-gate-skills.ts
|
|
949
|
+
function collectGateSkills(rules, relativePath) {
|
|
950
|
+
if (rules.ignore.some((segment) => relativePath.includes(segment))) {
|
|
951
|
+
return [];
|
|
952
|
+
}
|
|
953
|
+
return rules.gates.filter((gate) => isGlobMatch(gate.match, relativePath)).flatMap((gate) => gate.skills);
|
|
954
|
+
}
|
|
955
|
+
function isGlobMatch(pattern, relativePath) {
|
|
956
|
+
const glob = new Bun.Glob(pattern);
|
|
957
|
+
return glob.match(relativePath);
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
// src/plan-skill-gate.ts
|
|
961
|
+
function planSkillGate(input) {
|
|
962
|
+
const unknown = input.rules.gates.flatMap((gate) => gate.skills.filter((skill) => !input.availableSkills.includes(skill)).map((skill) => ({ match: gate.match, skill })));
|
|
963
|
+
const needed = collectGateSkills(input.rules, input.relativePath);
|
|
964
|
+
const missing = needed.filter((skill) => input.availableSkills.includes(skill) && !input.loadedSkills.includes(skill));
|
|
965
|
+
return { missing: [...new Set(missing)], unknown };
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
// src/plan-bash-skill-gate.ts
|
|
969
|
+
function planBashSkillGate(input) {
|
|
970
|
+
const gated = input.paths.filter((entry) => collectGateSkills(input.rules, entry.relativePath).length > 0);
|
|
971
|
+
const missing = gated.flatMap((entry) => planSkillGate({
|
|
972
|
+
rules: input.rules,
|
|
973
|
+
relativePath: entry.relativePath,
|
|
974
|
+
loadedSkills: input.loadedSkills,
|
|
975
|
+
availableSkills: input.availableSkills
|
|
976
|
+
}).missing);
|
|
977
|
+
return { gatedPaths: gated.map((entry) => entry.path), missing: [...new Set(missing)] };
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
// src/run-skill-gate.ts
|
|
981
|
+
async function runSkillGate() {
|
|
982
|
+
const payload = await Bun.stdin.json().catch(() => null);
|
|
983
|
+
const input = parseHookInput(payload);
|
|
984
|
+
if (input === null) {
|
|
985
|
+
process.exit(0);
|
|
986
|
+
}
|
|
987
|
+
const projectDir = process.env["CLAUDE_PROJECT_DIR"] ?? input.cwd;
|
|
988
|
+
const rulesFile = Bun.file(path2.join(projectDir, ".claude", "skill-gate.json"));
|
|
989
|
+
const hasRules = await rulesFile.exists();
|
|
990
|
+
if (hasRules && input.command !== null) {
|
|
991
|
+
await checkBashCommand({ hookInput: input, command: input.command, projectDir, rulesFile });
|
|
992
|
+
}
|
|
993
|
+
if (input.filePath === null) {
|
|
994
|
+
process.exit(0);
|
|
995
|
+
}
|
|
996
|
+
const filePath = path2.resolve(input.cwd, input.filePath);
|
|
997
|
+
const relativePath = toProjectPath(projectDir, filePath);
|
|
998
|
+
if (!hasRules || isOutsideProject(relativePath)) {
|
|
999
|
+
process.exit(0);
|
|
1000
|
+
}
|
|
1001
|
+
const rulesText = await rulesFile.text();
|
|
1002
|
+
const parsed = parseSkillGateRules(rulesText);
|
|
1003
|
+
if (!parsed.ok) {
|
|
1004
|
+
printOutput(buildSkillGateOutput(filePath, { missing: [], unknown: [] }, { rulesError: parsed.error }));
|
|
1005
|
+
process.exit(0);
|
|
1006
|
+
}
|
|
1007
|
+
const availableSkills = await readAvailableSkills(path2.join(projectDir, ".claude", "skills"));
|
|
1008
|
+
const transcript = await readTranscript(resolveSessionTranscriptPath(input));
|
|
1009
|
+
const loaded = collectLoadedSkills(transcript);
|
|
1010
|
+
const plan = planSkillGate({
|
|
1011
|
+
rules: parsed.rules,
|
|
1012
|
+
relativePath,
|
|
1013
|
+
loadedSkills: loaded.skills,
|
|
1014
|
+
availableSkills
|
|
1015
|
+
});
|
|
1016
|
+
printOutput(buildSkillGateOutput(filePath, plan, { compacted: loaded.compacted }));
|
|
1017
|
+
process.exit(0);
|
|
1018
|
+
}
|
|
1019
|
+
function parseHookInput(value) {
|
|
1020
|
+
if (!isRecord(value) || !isRecord(value["tool_input"])) {
|
|
1021
|
+
return null;
|
|
1022
|
+
}
|
|
1023
|
+
const cwd = value["cwd"];
|
|
1024
|
+
const transcriptPath = value["transcript_path"];
|
|
1025
|
+
const editPath = value["tool_input"]["file_path"];
|
|
1026
|
+
const command = value["tool_input"]["command"];
|
|
1027
|
+
if (typeof cwd !== "string" || typeof transcriptPath !== "string") {
|
|
1028
|
+
return null;
|
|
1029
|
+
}
|
|
1030
|
+
if (typeof editPath !== "string" && typeof command !== "string") {
|
|
1031
|
+
return null;
|
|
1032
|
+
}
|
|
1033
|
+
return {
|
|
1034
|
+
cwd,
|
|
1035
|
+
filePath: typeof editPath === "string" ? editPath : null,
|
|
1036
|
+
command: typeof command === "string" ? command : null,
|
|
1037
|
+
transcriptPath,
|
|
1038
|
+
agentID: value["agent_id"]
|
|
1039
|
+
};
|
|
1040
|
+
}
|
|
1041
|
+
async function checkBashCommand(check) {
|
|
1042
|
+
const written = collectWrittenPaths(check.command).map((entry) => readWrittenPath(check.hookInput.cwd, entry));
|
|
1043
|
+
const candidates = [...new Set(written)].filter((entry) => !isOutsideProject(toProjectPath(check.projectDir, entry)));
|
|
1044
|
+
if (candidates.length === 0) {
|
|
1045
|
+
process.exit(0);
|
|
1046
|
+
}
|
|
1047
|
+
const text = await check.rulesFile.text();
|
|
1048
|
+
const parsedRules = parseSkillGateRules(text);
|
|
1049
|
+
if (!parsedRules.ok) {
|
|
1050
|
+
process.exit(0);
|
|
1051
|
+
}
|
|
1052
|
+
const skills = await readAvailableSkills(path2.join(check.projectDir, ".claude", "skills"));
|
|
1053
|
+
const sessionTranscript = await readTranscript(resolveSessionTranscriptPath(check.hookInput));
|
|
1054
|
+
const sessionLoads = collectLoadedSkills(sessionTranscript);
|
|
1055
|
+
const bashPlan = planBashSkillGate({
|
|
1056
|
+
rules: parsedRules.rules,
|
|
1057
|
+
paths: candidates.map((entry) => ({
|
|
1058
|
+
path: entry,
|
|
1059
|
+
relativePath: toProjectPath(check.projectDir, entry)
|
|
1060
|
+
})),
|
|
1061
|
+
loadedSkills: sessionLoads.skills,
|
|
1062
|
+
availableSkills: skills
|
|
1063
|
+
});
|
|
1064
|
+
printOutput(buildBashSkillGateOutput(bashPlan.gatedPaths, bashPlan.missing, {
|
|
1065
|
+
compacted: sessionLoads.compacted
|
|
1066
|
+
}));
|
|
1067
|
+
process.exit(0);
|
|
1068
|
+
}
|
|
1069
|
+
function readWrittenPath(cwd, written) {
|
|
1070
|
+
const absolute = path2.resolve(cwd, written.path);
|
|
1071
|
+
if (written.fileName === undefined) {
|
|
1072
|
+
return absolute;
|
|
1073
|
+
}
|
|
1074
|
+
const isDirectory = statSync(absolute, { throwIfNoEntry: false })?.isDirectory() === true;
|
|
1075
|
+
return isDirectory ? path2.join(absolute, written.fileName) : absolute;
|
|
1076
|
+
}
|
|
1077
|
+
function isOutsideProject(fromProject) {
|
|
1078
|
+
return fromProject === ".." || fromProject.startsWith("../") || path2.isAbsolute(fromProject);
|
|
1079
|
+
}
|
|
1080
|
+
function toProjectPath(projectDir, absolute) {
|
|
1081
|
+
return path2.relative(projectDir, absolute).split(path2.sep).join("/");
|
|
1082
|
+
}
|
|
1083
|
+
async function readAvailableSkills(skillsDir) {
|
|
1084
|
+
const skills = [];
|
|
1085
|
+
const scan = new Bun.Glob("*/SKILL.md").scan({ cwd: skillsDir, followSymlinks: true });
|
|
1086
|
+
try {
|
|
1087
|
+
for await (const match of scan) {
|
|
1088
|
+
skills.push(path2.dirname(match));
|
|
1089
|
+
}
|
|
1090
|
+
} catch {}
|
|
1091
|
+
return skills;
|
|
1092
|
+
}
|
|
1093
|
+
async function readTranscript(transcriptPath) {
|
|
1094
|
+
if (transcriptPath === null) {
|
|
1095
|
+
return "";
|
|
1096
|
+
}
|
|
1097
|
+
const transcriptFile = Bun.file(transcriptPath);
|
|
1098
|
+
const exists = await transcriptFile.exists();
|
|
1099
|
+
return exists ? transcriptFile.text() : "";
|
|
1100
|
+
}
|
|
1101
|
+
function resolveSessionTranscriptPath(edit) {
|
|
1102
|
+
if (edit.agentID === undefined) {
|
|
1103
|
+
return edit.transcriptPath;
|
|
1104
|
+
}
|
|
1105
|
+
if (typeof edit.agentID !== "string" || !/^[\w-]+$/u.test(edit.agentID)) {
|
|
1106
|
+
return null;
|
|
1107
|
+
}
|
|
1108
|
+
const sessionDir = edit.transcriptPath.replace(/\.jsonl$/u, "");
|
|
1109
|
+
return path2.join(sessionDir, "subagents", `agent-${edit.agentID}.jsonl`);
|
|
1110
|
+
}
|
|
1111
|
+
function printOutput(output) {
|
|
1112
|
+
if (output !== null) {
|
|
1113
|
+
console.log(JSON.stringify(output));
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
export {
|
|
1117
|
+
runSkillGate
|
|
1118
|
+
};
|