@zgeoff/skill-gate 0.2.7 → 0.2.8
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 +15 -7
- package/dist/build-bash-change-output.d.ts +2 -0
- package/dist/build-bash-skill-gate-output.d.ts +2 -0
- package/dist/build-edit-output.d.ts +3 -0
- package/dist/build-patch-gate-output.d.ts +2 -0
- package/dist/classify-command-reads.d.ts +5 -0
- package/dist/collect-command-reads.d.ts +1 -0
- package/dist/collect-prompt-skills.d.ts +1 -0
- package/dist/collect-rule-warnings.d.ts +2 -0
- package/dist/harness.d.ts +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +689 -222
- package/dist/load-ledger.d.ts +6 -0
- package/dist/parse-hook-input.d.ts +3 -0
- package/dist/parse-patch-paths.d.ts +1 -0
- package/dist/parse-shell-commands.d.ts +3 -1
- package/dist/pick-harness-wording.d.ts +3 -0
- package/dist/read-available-skills.d.ts +1 -0
- package/dist/read-project-dir.d.ts +1 -0
- package/dist/read-session-loads.d.ts +2 -0
- package/dist/read-session-transcript.d.ts +2 -0
- package/dist/record-codex-loads.d.ts +3 -0
- package/dist/resolve-state-dir.d.ts +3 -0
- package/dist/run-skill-gate.d.ts +2 -1
- package/dist/types.d.ts +41 -0
- package/dist/with-ledger-lock.d.ts +1 -0
- package/package.json +3 -2
package/dist/index.js
CHANGED
|
@@ -2565,13 +2565,10 @@ var require_picomatch2 = __commonJS(function(exports, module) {
|
|
|
2565
2565
|
});
|
|
2566
2566
|
|
|
2567
2567
|
// src/run-skill-gate.ts
|
|
2568
|
-
import { statSync } from "fs";
|
|
2569
|
-
import { mkdir, rm } from "fs/promises";
|
|
2570
|
-
import
|
|
2571
|
-
|
|
2572
|
-
function isRecord(value) {
|
|
2573
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2574
|
-
}
|
|
2568
|
+
import { statSync as statSync2 } from "fs";
|
|
2569
|
+
import { mkdir as mkdir3, rm } from "fs/promises";
|
|
2570
|
+
import path15 from "path";
|
|
2571
|
+
|
|
2575
2572
|
// ../../node_modules/.bun/@simple-git+args-pathspec@1.0.4/node_modules/@simple-git/args-pathspec/dist/index.mjs
|
|
2576
2573
|
var t = /* @__PURE__ */ new WeakMap;
|
|
2577
2574
|
function c(...n) {
|
|
@@ -5971,7 +5968,7 @@ var BIGINT_FORMAT_RANGES = {
|
|
|
5971
5968
|
int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")],
|
|
5972
5969
|
uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")]
|
|
5973
5970
|
};
|
|
5974
|
-
function
|
|
5971
|
+
function pick(schema, mask) {
|
|
5975
5972
|
const currDef = schema._zod.def;
|
|
5976
5973
|
const checks = currDef.checks;
|
|
5977
5974
|
const hasChecks = checks && checks.length > 0;
|
|
@@ -6745,6 +6742,7 @@ function datetime(args) {
|
|
|
6745
6742
|
var anyString = /^[\s\S]{0,}$/;
|
|
6746
6743
|
var integer = /^-?\d+$/;
|
|
6747
6744
|
var number = /^-?\d+(?:\.\d+)?$/;
|
|
6745
|
+
var boolean = /^(?:true|false)$/i;
|
|
6748
6746
|
var lowercase = /^[^A-Z]*$/;
|
|
6749
6747
|
var uppercase = /^[^a-z]*$/;
|
|
6750
6748
|
|
|
@@ -7469,6 +7467,26 @@ var $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def) => {
|
|
|
7469
7467
|
});
|
|
7470
7468
|
};
|
|
7471
7469
|
});
|
|
7470
|
+
var $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => {
|
|
7471
|
+
$ZodType.init(inst, def);
|
|
7472
|
+
inst._zod.pattern = boolean;
|
|
7473
|
+
inst._zod.parse = (payload, _ctx) => {
|
|
7474
|
+
if (def.coerce)
|
|
7475
|
+
try {
|
|
7476
|
+
payload.value = Boolean(payload.value);
|
|
7477
|
+
} catch (_) {}
|
|
7478
|
+
const input = payload.value;
|
|
7479
|
+
if (typeof input === "boolean")
|
|
7480
|
+
return payload;
|
|
7481
|
+
payload.issues.push({
|
|
7482
|
+
expected: "boolean",
|
|
7483
|
+
code: "invalid_type",
|
|
7484
|
+
input,
|
|
7485
|
+
inst
|
|
7486
|
+
});
|
|
7487
|
+
return payload;
|
|
7488
|
+
};
|
|
7489
|
+
});
|
|
7472
7490
|
var $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => {
|
|
7473
7491
|
$ZodType.init(inst, def);
|
|
7474
7492
|
inst._zod.parse = (payload) => payload;
|
|
@@ -9256,6 +9274,12 @@ function _isoDuration(Class, params) {
|
|
|
9256
9274
|
...normalizeParams(params)
|
|
9257
9275
|
});
|
|
9258
9276
|
}
|
|
9277
|
+
function _boolean(Class, params) {
|
|
9278
|
+
return new Class({
|
|
9279
|
+
type: "boolean",
|
|
9280
|
+
...normalizeParams(params)
|
|
9281
|
+
});
|
|
9282
|
+
}
|
|
9259
9283
|
function _unknown(Class) {
|
|
9260
9284
|
return new Class({
|
|
9261
9285
|
type: "unknown"
|
|
@@ -10057,6 +10081,9 @@ var stringProcessor = (schema, ctx, _json, _params) => {
|
|
|
10057
10081
|
}
|
|
10058
10082
|
}
|
|
10059
10083
|
};
|
|
10084
|
+
var booleanProcessor = (_schema, _ctx, json, _params) => {
|
|
10085
|
+
json.type = "boolean";
|
|
10086
|
+
};
|
|
10060
10087
|
var neverProcessor = (_schema, _ctx, json, _params) => {
|
|
10061
10088
|
json.not = {};
|
|
10062
10089
|
};
|
|
@@ -10880,6 +10907,14 @@ var ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => {
|
|
|
10880
10907
|
$ZodJWT.init(inst, def);
|
|
10881
10908
|
ZodStringFormat.init(inst, def);
|
|
10882
10909
|
});
|
|
10910
|
+
var ZodBoolean = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => {
|
|
10911
|
+
$ZodBoolean.init(inst, def);
|
|
10912
|
+
ZodType.init(inst, def);
|
|
10913
|
+
inst._zod.processJSONSchema = (ctx, json, params) => booleanProcessor(inst, ctx, json, params);
|
|
10914
|
+
});
|
|
10915
|
+
function boolean2(params) {
|
|
10916
|
+
return _boolean(ZodBoolean, params);
|
|
10917
|
+
}
|
|
10883
10918
|
var ZodUnknown = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => {
|
|
10884
10919
|
$ZodUnknown.init(inst, def);
|
|
10885
10920
|
ZodType.init(inst, def);
|
|
@@ -10957,7 +10992,7 @@ var ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => {
|
|
|
10957
10992
|
return merge(this, other);
|
|
10958
10993
|
},
|
|
10959
10994
|
pick(mask) {
|
|
10960
|
-
return
|
|
10995
|
+
return pick(this, mask);
|
|
10961
10996
|
},
|
|
10962
10997
|
omit(mask) {
|
|
10963
10998
|
return omit(this, mask);
|
|
@@ -11296,6 +11331,19 @@ function formatSkillList(skills) {
|
|
|
11296
11331
|
return `${names.slice(0, -1).join(", ")} and ${names.at(-1)} ${noun}`;
|
|
11297
11332
|
}
|
|
11298
11333
|
|
|
11334
|
+
// src/pick-harness-wording.ts
|
|
11335
|
+
function pickHarnessWording(harness) {
|
|
11336
|
+
return M3(harness ?? "claude-code").returnType().with("claude-code", () => ({
|
|
11337
|
+
loadSkill: "with the Skill tool",
|
|
11338
|
+
readFile: "with the Read tool",
|
|
11339
|
+
editTools: "Edit, Write or MultiEdit"
|
|
11340
|
+
})).with("codex", () => ({
|
|
11341
|
+
loadSkill: "by reading its SKILL.md with cat, for example `cat .agents/skills/<name>/SKILL.md`",
|
|
11342
|
+
readFile: "with cat",
|
|
11343
|
+
editTools: "apply_patch"
|
|
11344
|
+
})).exhaustive();
|
|
11345
|
+
}
|
|
11346
|
+
|
|
11299
11347
|
// src/build-bash-change-output.ts
|
|
11300
11348
|
var RULES_PATH = ".claude/skill-gate.json";
|
|
11301
11349
|
function buildBashChangeOutput(event, changedPaths, missing, context = {}) {
|
|
@@ -11303,10 +11351,11 @@ function buildBashChangeOutput(event, changedPaths, missing, context = {}) {
|
|
|
11303
11351
|
return null;
|
|
11304
11352
|
}
|
|
11305
11353
|
const subject = changedPaths.length === 1 ? `changed the gated path ${changedPaths[0]}` : `changed the gated paths ${changedPaths.join(", ")}`;
|
|
11354
|
+
const wording = pickHarnessWording(context.harness);
|
|
11306
11355
|
const pronoun = missing.length === 1 ? "it" : "them";
|
|
11307
11356
|
const review = `then review what the command changed against ${pronoun} and fix what breaks a rule.`;
|
|
11308
|
-
const load = context.compacted === true ? `Load the ${formatSkillList(missing)} again
|
|
11309
|
-
const reason = `skill-gate: this Bash command ${subject} before the session loaded the skills it needs. ${load} Change a gated path only with
|
|
11357
|
+
const load = context.compacted === true ? `Load the ${formatSkillList(missing)} again ${wording.loadSkill}, ${review} This session was compacted, and a skill loaded before the compaction no longer counts.` : `Load the ${formatSkillList(missing)} ${wording.loadSkill}, ${review}`;
|
|
11358
|
+
const reason = `skill-gate: this Bash command ${subject} before the session loaded the skills it needs. ${load} Change a gated path only with ${wording.editTools}, never through Bash. ${RULES_PATH} lists the skills each path needs.`;
|
|
11310
11359
|
return M3(event).returnType().with("PostToolUse", () => ({ decision: "block", reason })).with("PostToolUseFailure", () => ({
|
|
11311
11360
|
hookSpecificOutput: { hookEventName: "PostToolUseFailure", additionalContext: reason }
|
|
11312
11361
|
})).exhaustive();
|
|
@@ -11328,8 +11377,9 @@ function buildBashSkillGateOutput(gatedPaths, missing, context = {}) {
|
|
|
11328
11377
|
return null;
|
|
11329
11378
|
}
|
|
11330
11379
|
const subject = gatedPaths.length === 1 ? `${gatedPaths[0]} is a gated path, so change it` : `${gatedPaths.join(", ")} are gated paths, so change them`;
|
|
11331
|
-
const
|
|
11332
|
-
const
|
|
11380
|
+
const wording = pickHarnessWording(context.harness);
|
|
11381
|
+
const load = buildLoadInstruction(missing, context.compacted === true, wording.loadSkill);
|
|
11382
|
+
const rule = `${subject} with the ${wording.editTools} tool, never through Bash.`;
|
|
11333
11383
|
return {
|
|
11334
11384
|
hookSpecificOutput: {
|
|
11335
11385
|
hookEventName: "PreToolUse",
|
|
@@ -11337,11 +11387,11 @@ function buildBashSkillGateOutput(gatedPaths, missing, context = {}) {
|
|
|
11337
11387
|
}
|
|
11338
11388
|
};
|
|
11339
11389
|
}
|
|
11340
|
-
function buildLoadInstruction(missing, compacted) {
|
|
11390
|
+
function buildLoadInstruction(missing, compacted, loadSkill) {
|
|
11341
11391
|
if (missing.length === 0) {
|
|
11342
11392
|
return "";
|
|
11343
11393
|
}
|
|
11344
|
-
return compacted ? ` Load the ${formatSkillList(missing)} again
|
|
11394
|
+
return compacted ? ` Load the ${formatSkillList(missing)} again ${loadSkill} before the next change. This session was compacted, and a skill loaded before the compaction no longer counts.` : ` Load the ${formatSkillList(missing)} ${loadSkill} before the next change.`;
|
|
11345
11395
|
}
|
|
11346
11396
|
|
|
11347
11397
|
// src/format-unknown-key-warning.ts
|
|
@@ -11349,19 +11399,58 @@ function formatUnknownKeyWarning(key) {
|
|
|
11349
11399
|
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.`;
|
|
11350
11400
|
}
|
|
11351
11401
|
|
|
11352
|
-
// src/
|
|
11402
|
+
// src/collect-rule-warnings.ts
|
|
11353
11403
|
var RULES_PATH3 = ".claude/skill-gate.json";
|
|
11354
|
-
|
|
11355
|
-
|
|
11356
|
-
const warnings = [
|
|
11404
|
+
function collectRuleWarnings(unknown, context) {
|
|
11405
|
+
return [
|
|
11357
11406
|
...context.rulesError === undefined ? [] : [`skill-gate: ${RULES_PATH3} ${context.rulesError}.`],
|
|
11358
11407
|
...(context.unknownKeys ?? []).map((key) => formatUnknownKeyWarning(key)),
|
|
11359
|
-
...
|
|
11408
|
+
...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.`)
|
|
11360
11409
|
];
|
|
11410
|
+
}
|
|
11411
|
+
|
|
11412
|
+
// src/build-patch-gate-output.ts
|
|
11413
|
+
var RULES_PATH4 = ".claude/skill-gate.json";
|
|
11414
|
+
function buildPatchGateOutput(entries, context = {}) {
|
|
11415
|
+
const wording = pickHarnessWording(context.harness);
|
|
11416
|
+
const warnings = collectRuleWarnings(entries.flatMap((entry) => entry.plan.unknown), context);
|
|
11417
|
+
const warning = warnings.length === 0 ? undefined : [...new Set(warnings)].join(`
|
|
11418
|
+
`);
|
|
11419
|
+
const blocked = entries.filter((entry) => entry.plan.missing.length > 0);
|
|
11420
|
+
if (blocked.length > 0) {
|
|
11421
|
+
const needs = blocked.map((entry) => `${entry.filePath} needs the ${formatSkillList(entry.plan.missing)}`).join("; ");
|
|
11422
|
+
const again = context.compacted === true ? " again" : "";
|
|
11423
|
+
const compaction = context.compacted === true ? " This session was compacted, and a skill loaded before the compaction no longer counts." : "";
|
|
11424
|
+
const reason = `This patch changes a gated path before the session loaded the skills it needs: ${needs}. Load each missing skill${again} ${wording.loadSkill}, then retry the patch.${compaction} Change a gated path only with ${wording.editTools}, never through Bash. ${RULES_PATH4} lists the skills each path needs.`;
|
|
11425
|
+
return {
|
|
11426
|
+
...warning === undefined ? {} : { systemMessage: warning },
|
|
11427
|
+
hookSpecificOutput: {
|
|
11428
|
+
hookEventName: "PreToolUse",
|
|
11429
|
+
permissionDecision: "deny",
|
|
11430
|
+
permissionDecisionReason: warning === undefined ? reason : `${reason}
|
|
11431
|
+
${warning}`
|
|
11432
|
+
}
|
|
11433
|
+
};
|
|
11434
|
+
}
|
|
11435
|
+
if (warning === undefined) {
|
|
11436
|
+
return null;
|
|
11437
|
+
}
|
|
11438
|
+
return {
|
|
11439
|
+
systemMessage: warning,
|
|
11440
|
+
hookSpecificOutput: { hookEventName: "PreToolUse", additionalContext: warning }
|
|
11441
|
+
};
|
|
11442
|
+
}
|
|
11443
|
+
|
|
11444
|
+
// src/build-skill-gate-output.ts
|
|
11445
|
+
var RULES_PATH5 = ".claude/skill-gate.json";
|
|
11446
|
+
function buildSkillGateOutput(filePath, plan, context = {}) {
|
|
11447
|
+
const wording = pickHarnessWording(context.harness);
|
|
11448
|
+
const editToolsNote = `Change a gated path only with ${wording.editTools}, never through Bash.`;
|
|
11449
|
+
const warnings = collectRuleWarnings(plan.unknown, context);
|
|
11361
11450
|
const warning = warnings.length === 0 ? undefined : warnings.join(`
|
|
11362
11451
|
`);
|
|
11363
11452
|
if (plan.missing.length > 0) {
|
|
11364
|
-
const reason = context.compacted === true ? `Load the ${formatSkillList(plan.missing)} again
|
|
11453
|
+
const reason = context.compacted === true ? `Load the ${formatSkillList(plan.missing)} again ${wording.loadSkill} before editing ${filePath}, then retry the edit. This session was compacted, and a skill loaded before the compaction no longer counts. ${editToolsNote} ${RULES_PATH5} lists the skills each path needs.` : `Load the ${formatSkillList(plan.missing)} ${wording.loadSkill} before editing ${filePath}, then retry the edit. ${editToolsNote} ${RULES_PATH5} lists the skills each path needs.`;
|
|
11365
11454
|
return {
|
|
11366
11455
|
...warning === undefined ? {} : { systemMessage: warning },
|
|
11367
11456
|
hookSpecificOutput: {
|
|
@@ -11381,18 +11470,26 @@ ${warning}`
|
|
|
11381
11470
|
};
|
|
11382
11471
|
}
|
|
11383
11472
|
|
|
11473
|
+
// src/build-edit-output.ts
|
|
11474
|
+
function buildEditOutput(harness, entries, context) {
|
|
11475
|
+
return M3(harness).with("claude-code", () => {
|
|
11476
|
+
const [first] = entries;
|
|
11477
|
+
return first === undefined ? null : buildSkillGateOutput(first.filePath, first.plan, context);
|
|
11478
|
+
}).with("codex", () => buildPatchGateOutput(entries, { ...context, harness })).exhaustive();
|
|
11479
|
+
}
|
|
11480
|
+
|
|
11384
11481
|
// src/build-tool-gate-output.ts
|
|
11385
|
-
var
|
|
11482
|
+
var RULES_PATH6 = ".claude/skill-gate.json";
|
|
11386
11483
|
function buildToolGateOutput(toolName, plan, context = {}) {
|
|
11387
11484
|
const warnings = [
|
|
11388
|
-
...context.rulesError === undefined ? [] : [`skill-gate: ${
|
|
11485
|
+
...context.rulesError === undefined ? [] : [`skill-gate: ${RULES_PATH6} ${context.rulesError}.`],
|
|
11389
11486
|
...(context.unknownKeys ?? []).map((key) => formatUnknownKeyWarning(key)),
|
|
11390
11487
|
...plan.unknown.map((entry) => formatUnknownWarning(entry))
|
|
11391
11488
|
];
|
|
11392
11489
|
const warning = warnings.length === 0 ? undefined : warnings.join(`
|
|
11393
11490
|
`);
|
|
11394
11491
|
if (plan.missingSkills.length > 0 || plan.missingReferences.length > 0) {
|
|
11395
|
-
const reason = buildDenyReason(toolName, plan, context.compacted === true);
|
|
11492
|
+
const reason = buildDenyReason(toolName, plan, context.compacted === true, context.harness);
|
|
11396
11493
|
return {
|
|
11397
11494
|
...warning === undefined ? {} : { systemMessage: warning },
|
|
11398
11495
|
hookSpecificOutput: {
|
|
@@ -11412,16 +11509,17 @@ ${warning}`
|
|
|
11412
11509
|
};
|
|
11413
11510
|
}
|
|
11414
11511
|
function formatUnknownWarning(entry) {
|
|
11415
|
-
return entry.kind === "skill" ? `skill-gate: the tool gate "${entry.tool}" in ${
|
|
11512
|
+
return entry.kind === "skill" ? `skill-gate: the tool gate "${entry.tool}" in ${RULES_PATH6} 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_PATH6} 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.`;
|
|
11416
11513
|
}
|
|
11417
|
-
function buildDenyReason(toolName, plan, compacted) {
|
|
11514
|
+
function buildDenyReason(toolName, plan, compacted, harness) {
|
|
11515
|
+
const wording = pickHarnessWording(harness);
|
|
11418
11516
|
const again = compacted ? " again" : "";
|
|
11419
11517
|
const steps = [
|
|
11420
|
-
...plan.missingSkills.length === 0 ? [] : [`load the ${formatSkillList(plan.missingSkills)}${again}
|
|
11421
|
-
...plan.missingReferences.length === 0 ? [] : [`read ${formatReferenceList(plan.missingReferences)}${again}
|
|
11518
|
+
...plan.missingSkills.length === 0 ? [] : [`load the ${formatSkillList(plan.missingSkills)}${again} ${wording.loadSkill}`],
|
|
11519
|
+
...plan.missingReferences.length === 0 ? [] : [`read ${formatReferenceList(plan.missingReferences)}${again} ${wording.readFile}`]
|
|
11422
11520
|
].join(" and ");
|
|
11423
11521
|
const compaction = compacted ? " This session was compacted, and a skill or reference loaded before the compaction no longer counts." : "";
|
|
11424
|
-
return `Before calling ${toolName}, ${steps}, then retry the call.${compaction} ${
|
|
11522
|
+
return `Before calling ${toolName}, ${steps}, then retry the call.${compaction} ${RULES_PATH6} lists the skills and references each tool needs.`;
|
|
11425
11523
|
}
|
|
11426
11524
|
function formatReferenceList(references) {
|
|
11427
11525
|
const paths = references.map((reference) => `.claude/skills/${reference}`);
|
|
@@ -11463,82 +11561,23 @@ function isGlobMatch(pattern, relativePath) {
|
|
|
11463
11561
|
return import_picomatch.default.isMatch(relativePath, pattern, { dot: true });
|
|
11464
11562
|
}
|
|
11465
11563
|
|
|
11466
|
-
// src/collect-session-loads.ts
|
|
11467
|
-
function collectSessionLoads(transcript) {
|
|
11468
|
-
const entries = transcript.split(`
|
|
11469
|
-
`).map((line) => parseEntry(line));
|
|
11470
|
-
const lastBoundary = entries.findLastIndex((entry) => isCompactBoundary(entry));
|
|
11471
|
-
const current = entries.slice(lastBoundary + 1);
|
|
11472
|
-
const succeeded = collectSucceededToolUseIDs(current);
|
|
11473
|
-
const skills = current.flatMap((entry) => collectEntrySkills(entry, succeeded));
|
|
11474
|
-
const readPaths = current.flatMap((entry) => collectContentBlocks(entry, "assistant")).flatMap((block) => collectReadCall(block, succeeded));
|
|
11475
|
-
return {
|
|
11476
|
-
skills: [...new Set(skills)],
|
|
11477
|
-
readPaths: [...new Set(readPaths)],
|
|
11478
|
-
compacted: lastBoundary !== -1
|
|
11479
|
-
};
|
|
11480
|
-
}
|
|
11481
|
-
function parseEntry(line) {
|
|
11482
|
-
try {
|
|
11483
|
-
return JSON.parse(line);
|
|
11484
|
-
} catch {
|
|
11485
|
-
return null;
|
|
11486
|
-
}
|
|
11487
|
-
}
|
|
11488
|
-
function isCompactBoundary(entry) {
|
|
11489
|
-
return isRecord(entry) && entry["type"] === "system" && entry["subtype"] === "compact_boundary";
|
|
11490
|
-
}
|
|
11491
|
-
function collectSucceededToolUseIDs(entries) {
|
|
11492
|
-
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"]] : []);
|
|
11493
|
-
}
|
|
11494
|
-
function collectContentBlocks(entry, type) {
|
|
11495
|
-
if (!isRecord(entry) || entry["type"] !== type || !isRecord(entry["message"])) {
|
|
11496
|
-
return [];
|
|
11497
|
-
}
|
|
11498
|
-
const content = entry["message"]["content"];
|
|
11499
|
-
return Array.isArray(content) ? content.filter((block) => isRecord(block)) : [];
|
|
11500
|
-
}
|
|
11501
|
-
function collectEntrySkills(entry, succeeded) {
|
|
11502
|
-
const command = findSlashCommand(entry);
|
|
11503
|
-
if (command !== undefined) {
|
|
11504
|
-
return [command];
|
|
11505
|
-
}
|
|
11506
|
-
return collectContentBlocks(entry, "assistant").flatMap((block) => collectSkillCall(block, succeeded));
|
|
11507
|
-
}
|
|
11508
|
-
var SLASH_COMMAND_PATTERN = /^\s*(?:<command-message>[^<]*<\/command-message>\s*)?<command-name>\/(?<skill>[^<\s]+)<\/command-name>/u;
|
|
11509
|
-
function findSlashCommand(entry) {
|
|
11510
|
-
if (!isRecord(entry) || entry["type"] !== "user" || entry["isSidechain"] === true || !isRecord(entry["message"])) {
|
|
11511
|
-
return;
|
|
11512
|
-
}
|
|
11513
|
-
const content = entry["message"]["content"];
|
|
11514
|
-
return typeof content === "string" ? SLASH_COMMAND_PATTERN.exec(content)?.groups?.["skill"] : undefined;
|
|
11515
|
-
}
|
|
11516
|
-
function collectSkillCall(block, succeeded) {
|
|
11517
|
-
const input = block["input"];
|
|
11518
|
-
const id = block["id"];
|
|
11519
|
-
if (block["type"] !== "tool_use" || block["name"] !== "Skill" || !isRecord(input)) {
|
|
11520
|
-
return [];
|
|
11521
|
-
}
|
|
11522
|
-
const skill = input["skill"];
|
|
11523
|
-
return typeof skill === "string" && typeof id === "string" && succeeded.includes(id) ? [skill] : [];
|
|
11524
|
-
}
|
|
11525
|
-
function collectReadCall(block, succeeded) {
|
|
11526
|
-
const input = block["input"];
|
|
11527
|
-
const id = block["id"];
|
|
11528
|
-
if (block["type"] !== "tool_use" || block["name"] !== "Read" || !isRecord(input)) {
|
|
11529
|
-
return [];
|
|
11530
|
-
}
|
|
11531
|
-
const filePath = input["file_path"];
|
|
11532
|
-
return typeof filePath === "string" && typeof id === "string" && succeeded.includes(id) ? [filePath] : [];
|
|
11533
|
-
}
|
|
11534
|
-
|
|
11535
11564
|
// src/collect-written-paths.ts
|
|
11536
11565
|
import path from "path";
|
|
11537
11566
|
|
|
11538
11567
|
// src/parse-shell-commands.ts
|
|
11539
|
-
function parseShellCommands(text) {
|
|
11568
|
+
function parseShellCommands(text, options = {}) {
|
|
11540
11569
|
const tokens = splitShellTokens(text);
|
|
11541
|
-
|
|
11570
|
+
if (tokens === null) {
|
|
11571
|
+
return null;
|
|
11572
|
+
}
|
|
11573
|
+
const commands = buildShellCommands(tokens);
|
|
11574
|
+
return options.withGuards === true ? commands : commands.map((command) => ({
|
|
11575
|
+
words: command.words,
|
|
11576
|
+
redirects: command.redirects,
|
|
11577
|
+
stdin: command.stdin,
|
|
11578
|
+
enters: command.enters,
|
|
11579
|
+
leaves: command.leaves
|
|
11580
|
+
}));
|
|
11542
11581
|
}
|
|
11543
11582
|
function splitShellTokens(text) {
|
|
11544
11583
|
const tokens = [];
|
|
@@ -11763,15 +11802,28 @@ function buildShellCommands(tokens) {
|
|
|
11763
11802
|
let operator = null;
|
|
11764
11803
|
let pipedIn = false;
|
|
11765
11804
|
const listStarts = [0];
|
|
11805
|
+
let chain = [];
|
|
11806
|
+
let viaOr = false;
|
|
11807
|
+
let inherited = { chain: [], viaOr: false };
|
|
11808
|
+
const outerStates = [];
|
|
11766
11809
|
const collectDraft = (separator) => {
|
|
11767
11810
|
const pipedOut = separator === "|" || separator === "|&";
|
|
11768
11811
|
if (draft.words.length > 0 || draft.redirects.length > 0) {
|
|
11769
11812
|
const piped = pipedIn || pipedOut;
|
|
11770
11813
|
draft.enters += piped ? 1 : 0;
|
|
11771
11814
|
draft.leaves += piped ? 1 : 0;
|
|
11815
|
+
draft.guard = chain.length > 0 || viaOr ? { viaOr, before: [...chain] } : null;
|
|
11816
|
+
if (separator === "&&" || separator === "||") {
|
|
11817
|
+
chain.push(draft.words);
|
|
11818
|
+
viaOr ||= separator === "||";
|
|
11819
|
+
}
|
|
11772
11820
|
commands.push(draft);
|
|
11773
11821
|
draft = buildCommandDraft();
|
|
11774
11822
|
}
|
|
11823
|
+
if (separator !== null && LIST_ENDS.has(separator)) {
|
|
11824
|
+
chain = [...inherited.chain];
|
|
11825
|
+
viaOr = inherited.viaOr;
|
|
11826
|
+
}
|
|
11775
11827
|
operator = null;
|
|
11776
11828
|
pipedIn = pipedOut;
|
|
11777
11829
|
const listStart = listStarts.at(-1) ?? 0;
|
|
@@ -11794,8 +11846,14 @@ function buildShellCommands(tokens) {
|
|
|
11794
11846
|
if (subshell.opens) {
|
|
11795
11847
|
draft.enters += 1;
|
|
11796
11848
|
listStarts.push(commands.length);
|
|
11849
|
+
outerStates.push({ chain, viaOr, inherited });
|
|
11850
|
+
inherited = { chain: [...chain], viaOr };
|
|
11797
11851
|
} else {
|
|
11798
11852
|
listStarts.pop();
|
|
11853
|
+
const outer = outerStates.pop();
|
|
11854
|
+
if (outer !== undefined) {
|
|
11855
|
+
({ chain, viaOr, inherited } = outer);
|
|
11856
|
+
}
|
|
11799
11857
|
if (last !== undefined) {
|
|
11800
11858
|
last.leaves += 1;
|
|
11801
11859
|
}
|
|
@@ -11826,7 +11884,7 @@ function buildShellCommands(tokens) {
|
|
|
11826
11884
|
return commands;
|
|
11827
11885
|
}
|
|
11828
11886
|
function buildCommandDraft() {
|
|
11829
|
-
return { words: [], redirects: [], stdin: null, enters: 0, leaves: 0 };
|
|
11887
|
+
return { words: [], redirects: [], stdin: null, enters: 0, leaves: 0, guard: null };
|
|
11830
11888
|
}
|
|
11831
11889
|
|
|
11832
11890
|
// src/collect-written-paths.ts
|
|
@@ -12111,6 +12169,95 @@ function resolveNextDir(command, directory) {
|
|
|
12111
12169
|
}
|
|
12112
12170
|
return directory === null ? null : path.join(directory, target.text);
|
|
12113
12171
|
}
|
|
12172
|
+
// ../std/src/is-record.ts
|
|
12173
|
+
function isRecord(value) {
|
|
12174
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
12175
|
+
}
|
|
12176
|
+
// src/parse-patch-paths.ts
|
|
12177
|
+
var PATCH_HEADER = /^\*\*\* (?:Add File|Update File|Delete File|Move to): (?<path>.+)$/u;
|
|
12178
|
+
function parsePatchPaths(patch) {
|
|
12179
|
+
const paths = patch.split(`
|
|
12180
|
+
`).flatMap((line) => PATCH_HEADER.exec(line.replace(/\r$/u, ""))?.groups?.["path"]?.trim() ?? []);
|
|
12181
|
+
return [...new Set(paths)];
|
|
12182
|
+
}
|
|
12183
|
+
|
|
12184
|
+
// src/parse-hook-input.ts
|
|
12185
|
+
function parseHookInput(harness, value) {
|
|
12186
|
+
return M3(harness).with("claude-code", () => parseClaudeInput(value)).with("codex", () => parseCodexInput(value)).exhaustive();
|
|
12187
|
+
}
|
|
12188
|
+
function parseClaudeInput(value) {
|
|
12189
|
+
if (!isRecord(value) || !isRecord(value["tool_input"])) {
|
|
12190
|
+
return null;
|
|
12191
|
+
}
|
|
12192
|
+
const cwd = value["cwd"];
|
|
12193
|
+
const transcriptPath = value["transcript_path"];
|
|
12194
|
+
const editPath = value["tool_input"]["file_path"];
|
|
12195
|
+
const command = value["tool_input"]["command"];
|
|
12196
|
+
const toolName = value["tool_name"];
|
|
12197
|
+
if (typeof cwd !== "string" || typeof transcriptPath !== "string") {
|
|
12198
|
+
return null;
|
|
12199
|
+
}
|
|
12200
|
+
if (typeof editPath !== "string" && typeof command !== "string" && typeof toolName !== "string") {
|
|
12201
|
+
return null;
|
|
12202
|
+
}
|
|
12203
|
+
return {
|
|
12204
|
+
kind: "tool",
|
|
12205
|
+
harness: "claude-code",
|
|
12206
|
+
event: pickHookEvent(value["hook_event_name"]),
|
|
12207
|
+
toolName: typeof toolName === "string" ? toolName : null,
|
|
12208
|
+
cwd,
|
|
12209
|
+
editPaths: typeof editPath === "string" ? [editPath] : [],
|
|
12210
|
+
command: typeof command === "string" ? command : null,
|
|
12211
|
+
transcriptPath,
|
|
12212
|
+
sessionID: null,
|
|
12213
|
+
toolUseID: value["tool_use_id"],
|
|
12214
|
+
agentID: value["agent_id"]
|
|
12215
|
+
};
|
|
12216
|
+
}
|
|
12217
|
+
function pickHookEvent(value) {
|
|
12218
|
+
return value === "PostToolUse" || value === "PostToolUseFailure" ? value : "PreToolUse";
|
|
12219
|
+
}
|
|
12220
|
+
function parseCodexInput(value) {
|
|
12221
|
+
if (!isRecord(value) || typeof value["cwd"] !== "string") {
|
|
12222
|
+
return null;
|
|
12223
|
+
}
|
|
12224
|
+
const cwd = value["cwd"];
|
|
12225
|
+
const transcriptPath = pickString(value["transcript_path"]);
|
|
12226
|
+
const sessionID = pickString(value["session_id"]);
|
|
12227
|
+
const event = value["hook_event_name"];
|
|
12228
|
+
if (event === "UserPromptSubmit" || event === "PostCompact") {
|
|
12229
|
+
return {
|
|
12230
|
+
kind: "lifecycle",
|
|
12231
|
+
event,
|
|
12232
|
+
cwd,
|
|
12233
|
+
transcriptPath,
|
|
12234
|
+
sessionID,
|
|
12235
|
+
prompt: pickString(value["prompt"])
|
|
12236
|
+
};
|
|
12237
|
+
}
|
|
12238
|
+
const toolName = value["tool_name"];
|
|
12239
|
+
if (event !== "PreToolUse" && event !== "PostToolUse" || typeof toolName !== "string") {
|
|
12240
|
+
return null;
|
|
12241
|
+
}
|
|
12242
|
+
const toolInput = value["tool_input"];
|
|
12243
|
+
const text = isRecord(toolInput) ? pickString(toolInput["command"]) : null;
|
|
12244
|
+
return {
|
|
12245
|
+
kind: "tool",
|
|
12246
|
+
harness: "codex",
|
|
12247
|
+
event,
|
|
12248
|
+
toolName,
|
|
12249
|
+
cwd,
|
|
12250
|
+
editPaths: toolName === "apply_patch" && text !== null ? parsePatchPaths(text) : [],
|
|
12251
|
+
command: toolName === "Bash" ? text : null,
|
|
12252
|
+
transcriptPath,
|
|
12253
|
+
sessionID,
|
|
12254
|
+
toolUseID: value["tool_use_id"],
|
|
12255
|
+
agentID: undefined
|
|
12256
|
+
};
|
|
12257
|
+
}
|
|
12258
|
+
function pickString(value) {
|
|
12259
|
+
return typeof value === "string" ? value : null;
|
|
12260
|
+
}
|
|
12114
12261
|
|
|
12115
12262
|
// src/parse-skill-gate-rules.ts
|
|
12116
12263
|
function parseSkillGateRules(text) {
|
|
@@ -12276,6 +12423,19 @@ async function readAvailableReferences(readContent, skillsDir, tools) {
|
|
|
12276
12423
|
return references.filter((_, index) => contents[index] !== null);
|
|
12277
12424
|
}
|
|
12278
12425
|
|
|
12426
|
+
// src/read-available-skills.ts
|
|
12427
|
+
import path4 from "path";
|
|
12428
|
+
async function readAvailableSkills(skillsDir) {
|
|
12429
|
+
const skills = [];
|
|
12430
|
+
const scan = new Bun.Glob("*/SKILL.md").scan({ cwd: skillsDir, followSymlinks: true });
|
|
12431
|
+
try {
|
|
12432
|
+
for await (const skillFile of scan) {
|
|
12433
|
+
skills.push(path4.dirname(skillFile));
|
|
12434
|
+
}
|
|
12435
|
+
} catch {}
|
|
12436
|
+
return skills;
|
|
12437
|
+
}
|
|
12438
|
+
|
|
12279
12439
|
// src/to-content-hash.ts
|
|
12280
12440
|
function toContentHash(bytes) {
|
|
12281
12441
|
return Bun.hash(bytes).toString(16);
|
|
@@ -12297,12 +12457,12 @@ async function readCommitHashes(git, commit, relativePaths) {
|
|
|
12297
12457
|
}
|
|
12298
12458
|
|
|
12299
12459
|
// src/read-committed-paths.ts
|
|
12300
|
-
import
|
|
12460
|
+
import path5 from "path";
|
|
12301
12461
|
async function readCommittedPaths(git, directory, from, to) {
|
|
12302
12462
|
const toRoot = await git.revparse(["--show-cdup"]);
|
|
12303
12463
|
const listArgs = from === null ? ["ls-tree", "-r", "--full-tree", "--name-only", "-z", to] : ["diff", "--name-only", "--no-renames", "-z", from, to];
|
|
12304
12464
|
const names = await git.raw(listArgs);
|
|
12305
|
-
return names.split("\x00").filter((entry) => entry !== "").map((entry) =>
|
|
12465
|
+
return names.split("\x00").filter((entry) => entry !== "").map((entry) => path5.join(directory, toRoot.trim(), entry));
|
|
12306
12466
|
}
|
|
12307
12467
|
|
|
12308
12468
|
// src/read-file-content.ts
|
|
@@ -12321,17 +12481,215 @@ async function readFileContent(filePath) {
|
|
|
12321
12481
|
}
|
|
12322
12482
|
|
|
12323
12483
|
// src/read-file-hashes.ts
|
|
12324
|
-
import
|
|
12484
|
+
import path6 from "path";
|
|
12325
12485
|
async function readFileHashes(readContent, projectDir, relativePaths) {
|
|
12326
12486
|
const entries = await Promise.all(relativePaths.map(async (relativePath) => {
|
|
12327
|
-
const content = await readContent(
|
|
12487
|
+
const content = await readContent(path6.join(projectDir, relativePath));
|
|
12328
12488
|
return [relativePath, content === null ? null : toContentHash(content)];
|
|
12329
12489
|
}));
|
|
12330
12490
|
return Object.fromEntries(entries);
|
|
12331
12491
|
}
|
|
12332
12492
|
|
|
12493
|
+
// src/read-project-dir.ts
|
|
12494
|
+
async function readProjectDir(cwd) {
|
|
12495
|
+
const fromEnv = process.env["CLAUDE_PROJECT_DIR"];
|
|
12496
|
+
if (fromEnv !== undefined && fromEnv !== "") {
|
|
12497
|
+
return fromEnv;
|
|
12498
|
+
}
|
|
12499
|
+
try {
|
|
12500
|
+
const output = await wo(cwd).revparse(["--show-toplevel"]);
|
|
12501
|
+
const topLevel = output.trim();
|
|
12502
|
+
return topLevel === "" ? cwd : topLevel;
|
|
12503
|
+
} catch {
|
|
12504
|
+
return cwd;
|
|
12505
|
+
}
|
|
12506
|
+
}
|
|
12507
|
+
|
|
12508
|
+
// src/collect-session-loads.ts
|
|
12509
|
+
function collectSessionLoads(transcript) {
|
|
12510
|
+
const entries = transcript.split(`
|
|
12511
|
+
`).map((line) => parseEntry(line));
|
|
12512
|
+
const lastBoundary = entries.findLastIndex((entry) => isCompactBoundary(entry));
|
|
12513
|
+
const current = entries.slice(lastBoundary + 1);
|
|
12514
|
+
const succeeded = collectSucceededToolUseIDs(current);
|
|
12515
|
+
const skills = current.flatMap((entry) => collectEntrySkills(entry, succeeded));
|
|
12516
|
+
const readPaths = current.flatMap((entry) => collectContentBlocks(entry, "assistant")).flatMap((block) => collectReadCall(block, succeeded));
|
|
12517
|
+
return {
|
|
12518
|
+
skills: [...new Set(skills)],
|
|
12519
|
+
readPaths: [...new Set(readPaths)],
|
|
12520
|
+
compacted: lastBoundary !== -1
|
|
12521
|
+
};
|
|
12522
|
+
}
|
|
12523
|
+
function parseEntry(line) {
|
|
12524
|
+
try {
|
|
12525
|
+
return JSON.parse(line);
|
|
12526
|
+
} catch {
|
|
12527
|
+
return null;
|
|
12528
|
+
}
|
|
12529
|
+
}
|
|
12530
|
+
function isCompactBoundary(entry) {
|
|
12531
|
+
return isRecord(entry) && entry["type"] === "system" && entry["subtype"] === "compact_boundary";
|
|
12532
|
+
}
|
|
12533
|
+
function collectSucceededToolUseIDs(entries) {
|
|
12534
|
+
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"]] : []);
|
|
12535
|
+
}
|
|
12536
|
+
function collectContentBlocks(entry, type) {
|
|
12537
|
+
if (!isRecord(entry) || entry["type"] !== type || !isRecord(entry["message"])) {
|
|
12538
|
+
return [];
|
|
12539
|
+
}
|
|
12540
|
+
const content = entry["message"]["content"];
|
|
12541
|
+
return Array.isArray(content) ? content.filter((block) => isRecord(block)) : [];
|
|
12542
|
+
}
|
|
12543
|
+
function collectEntrySkills(entry, succeeded) {
|
|
12544
|
+
const command = findSlashCommand(entry);
|
|
12545
|
+
if (command !== undefined) {
|
|
12546
|
+
return [command];
|
|
12547
|
+
}
|
|
12548
|
+
return collectContentBlocks(entry, "assistant").flatMap((block) => collectSkillCall(block, succeeded));
|
|
12549
|
+
}
|
|
12550
|
+
var SLASH_COMMAND_PATTERN = /^\s*(?:<command-message>[^<]*<\/command-message>\s*)?<command-name>\/(?<skill>[^<\s]+)<\/command-name>/u;
|
|
12551
|
+
function findSlashCommand(entry) {
|
|
12552
|
+
if (!isRecord(entry) || entry["type"] !== "user" || entry["isSidechain"] === true || !isRecord(entry["message"])) {
|
|
12553
|
+
return;
|
|
12554
|
+
}
|
|
12555
|
+
const content = entry["message"]["content"];
|
|
12556
|
+
return typeof content === "string" ? SLASH_COMMAND_PATTERN.exec(content)?.groups?.["skill"] : undefined;
|
|
12557
|
+
}
|
|
12558
|
+
function collectSkillCall(block, succeeded) {
|
|
12559
|
+
const input = block["input"];
|
|
12560
|
+
const id = block["id"];
|
|
12561
|
+
if (block["type"] !== "tool_use" || block["name"] !== "Skill" || !isRecord(input)) {
|
|
12562
|
+
return [];
|
|
12563
|
+
}
|
|
12564
|
+
const skill = input["skill"];
|
|
12565
|
+
return typeof skill === "string" && typeof id === "string" && succeeded.includes(id) ? [skill] : [];
|
|
12566
|
+
}
|
|
12567
|
+
function collectReadCall(block, succeeded) {
|
|
12568
|
+
const input = block["input"];
|
|
12569
|
+
const id = block["id"];
|
|
12570
|
+
if (block["type"] !== "tool_use" || block["name"] !== "Read" || !isRecord(input)) {
|
|
12571
|
+
return [];
|
|
12572
|
+
}
|
|
12573
|
+
const filePath = input["file_path"];
|
|
12574
|
+
return typeof filePath === "string" && typeof id === "string" && succeeded.includes(id) ? [filePath] : [];
|
|
12575
|
+
}
|
|
12576
|
+
|
|
12577
|
+
// src/load-ledger.ts
|
|
12578
|
+
import { mkdir, rename } from "fs/promises";
|
|
12579
|
+
import path7 from "path";
|
|
12580
|
+
var loadLedgerSchema = object({
|
|
12581
|
+
skills: array(string2()),
|
|
12582
|
+
readPaths: array(string2()),
|
|
12583
|
+
compacted: boolean2()
|
|
12584
|
+
});
|
|
12585
|
+
var EMPTY_LEDGER = { skills: [], readPaths: [], compacted: false };
|
|
12586
|
+
async function readLoadLedger(ledgerPath) {
|
|
12587
|
+
if (ledgerPath === null) {
|
|
12588
|
+
return EMPTY_LEDGER;
|
|
12589
|
+
}
|
|
12590
|
+
const text = await Bun.file(ledgerPath).text().catch(() => null);
|
|
12591
|
+
if (text === null) {
|
|
12592
|
+
return EMPTY_LEDGER;
|
|
12593
|
+
}
|
|
12594
|
+
try {
|
|
12595
|
+
const parsed = loadLedgerSchema.safeParse(JSON.parse(text));
|
|
12596
|
+
return parsed.success ? parsed.data : EMPTY_LEDGER;
|
|
12597
|
+
} catch {
|
|
12598
|
+
return EMPTY_LEDGER;
|
|
12599
|
+
}
|
|
12600
|
+
}
|
|
12601
|
+
async function writeLoadLedger(ledgerPath, ledger) {
|
|
12602
|
+
if (ledgerPath === null) {
|
|
12603
|
+
return;
|
|
12604
|
+
}
|
|
12605
|
+
try {
|
|
12606
|
+
await mkdir(path7.dirname(ledgerPath), { recursive: true });
|
|
12607
|
+
const tempPath = `${ledgerPath}.${process.pid}.tmp`;
|
|
12608
|
+
await Bun.write(tempPath, JSON.stringify(ledger));
|
|
12609
|
+
await rename(tempPath, ledgerPath);
|
|
12610
|
+
} catch {}
|
|
12611
|
+
}
|
|
12612
|
+
function addLoads(ledger, loads) {
|
|
12613
|
+
return {
|
|
12614
|
+
skills: [...new Set([...ledger.skills, ...loads.skills])],
|
|
12615
|
+
readPaths: [...new Set([...ledger.readPaths, ...loads.readPaths])],
|
|
12616
|
+
compacted: ledger.compacted
|
|
12617
|
+
};
|
|
12618
|
+
}
|
|
12619
|
+
function voidLoads() {
|
|
12620
|
+
return { skills: [], readPaths: [], compacted: true };
|
|
12621
|
+
}
|
|
12622
|
+
|
|
12623
|
+
// src/read-session-transcript.ts
|
|
12624
|
+
import path8 from "path";
|
|
12625
|
+
async function readSessionTranscript(hookInput) {
|
|
12626
|
+
if (hookInput.transcriptPath === null) {
|
|
12627
|
+
return "";
|
|
12628
|
+
}
|
|
12629
|
+
if (hookInput.agentID === undefined) {
|
|
12630
|
+
return readTranscript(hookInput.transcriptPath);
|
|
12631
|
+
}
|
|
12632
|
+
if (typeof hookInput.agentID !== "string" || !/^[\w-]+$/u.test(hookInput.agentID)) {
|
|
12633
|
+
return "";
|
|
12634
|
+
}
|
|
12635
|
+
const subagentsDir = path8.join(hookInput.transcriptPath.replace(/\.jsonl$/u, ""), "subagents");
|
|
12636
|
+
const transcriptName = `agent-${hookInput.agentID}.jsonl`;
|
|
12637
|
+
const agentTranscript = await readTranscript(path8.join(subagentsDir, transcriptName));
|
|
12638
|
+
if (agentTranscript !== "") {
|
|
12639
|
+
return agentTranscript;
|
|
12640
|
+
}
|
|
12641
|
+
return readWorkflowAgentTranscript(subagentsDir, transcriptName);
|
|
12642
|
+
}
|
|
12643
|
+
async function readTranscript(transcriptPath) {
|
|
12644
|
+
const transcriptFile = Bun.file(transcriptPath);
|
|
12645
|
+
const exists = await transcriptFile.exists();
|
|
12646
|
+
return exists ? transcriptFile.text() : "";
|
|
12647
|
+
}
|
|
12648
|
+
async function readWorkflowAgentTranscript(subagentsDir, transcriptName) {
|
|
12649
|
+
const scan = new Bun.Glob(`workflows/*/${transcriptName}`).scan({ cwd: subagentsDir });
|
|
12650
|
+
let transcriptPath = null;
|
|
12651
|
+
try {
|
|
12652
|
+
for await (const scannedPath of scan) {
|
|
12653
|
+
transcriptPath = scannedPath;
|
|
12654
|
+
break;
|
|
12655
|
+
}
|
|
12656
|
+
} catch {}
|
|
12657
|
+
return transcriptPath === null ? "" : readTranscript(path8.join(subagentsDir, transcriptPath));
|
|
12658
|
+
}
|
|
12659
|
+
|
|
12660
|
+
// src/resolve-state-dir.ts
|
|
12661
|
+
import { tmpdir } from "os";
|
|
12662
|
+
import path9 from "path";
|
|
12663
|
+
function resolveStateDir(hookInput) {
|
|
12664
|
+
if (hookInput.transcriptPath !== null) {
|
|
12665
|
+
const sessionDir = hookInput.transcriptPath.replace(/\.jsonl$/u, "");
|
|
12666
|
+
const folder = sessionDir === hookInput.transcriptPath ? `${sessionDir}.d` : sessionDir;
|
|
12667
|
+
return path9.join(folder, "skill-gate");
|
|
12668
|
+
}
|
|
12669
|
+
if (hookInput.sessionID === null || !/^[\w-]+$/u.test(hookInput.sessionID)) {
|
|
12670
|
+
return null;
|
|
12671
|
+
}
|
|
12672
|
+
return path9.join(tmpdir(), "skill-gate", hookInput.sessionID);
|
|
12673
|
+
}
|
|
12674
|
+
function resolveLedgerPath(hookInput) {
|
|
12675
|
+
const stateDir = resolveStateDir(hookInput);
|
|
12676
|
+
if (stateDir === null || hookInput.sessionID === null || !/^[\w-]+$/u.test(hookInput.sessionID)) {
|
|
12677
|
+
return null;
|
|
12678
|
+
}
|
|
12679
|
+
return path9.join(stateDir, `loads-${hookInput.sessionID}.json`);
|
|
12680
|
+
}
|
|
12681
|
+
|
|
12682
|
+
// src/read-session-loads.ts
|
|
12683
|
+
function readSessionLoads(hookInput) {
|
|
12684
|
+
return M3(hookInput.harness).with("claude-code", () => readClaudeLoads(hookInput)).with("codex", () => readLoadLedger(resolveLedgerPath(hookInput))).exhaustive();
|
|
12685
|
+
}
|
|
12686
|
+
async function readClaudeLoads(hookInput) {
|
|
12687
|
+
const transcript = await readSessionTranscript(hookInput);
|
|
12688
|
+
return collectSessionLoads(transcript);
|
|
12689
|
+
}
|
|
12690
|
+
|
|
12333
12691
|
// src/read-work-tree.ts
|
|
12334
|
-
import
|
|
12692
|
+
import path10 from "path";
|
|
12335
12693
|
async function readWorkTree(git, directory) {
|
|
12336
12694
|
const isWorkTree = await git.checkIsRepo();
|
|
12337
12695
|
if (!isWorkTree) {
|
|
@@ -12340,21 +12698,198 @@ async function readWorkTree(git, directory) {
|
|
|
12340
12698
|
const toRoot = await git.revparse(["--show-cdup"]);
|
|
12341
12699
|
const status = await git.status();
|
|
12342
12700
|
const head = await git.revparse(["--verify", "HEAD"]).catch(() => null);
|
|
12343
|
-
const dirtyPaths = status.files.flatMap((file) => file.from === undefined ? [file.path] : [file.path, file.from]).map((entry) =>
|
|
12701
|
+
const dirtyPaths = status.files.flatMap((file) => file.from === undefined ? [file.path] : [file.path, file.from]).map((entry) => path10.join(directory, toRoot.trim(), entry));
|
|
12344
12702
|
return { head: head?.trim() ?? null, dirtyPaths };
|
|
12345
12703
|
}
|
|
12346
12704
|
|
|
12705
|
+
// src/record-codex-loads.ts
|
|
12706
|
+
import { statSync } from "fs";
|
|
12707
|
+
import path14 from "path";
|
|
12708
|
+
|
|
12709
|
+
// src/classify-command-reads.ts
|
|
12710
|
+
import path11 from "path";
|
|
12711
|
+
function classifyCommandReads(readFiles, projectDir, references) {
|
|
12712
|
+
const skillRoots = [
|
|
12713
|
+
path11.join(projectDir, ".agents", "skills"),
|
|
12714
|
+
path11.join(projectDir, ".claude", "skills")
|
|
12715
|
+
];
|
|
12716
|
+
const claudeRoot = path11.join(projectDir, ".claude", "skills");
|
|
12717
|
+
const skills = readFiles.flatMap((file) => skillRoots.flatMap((root) => {
|
|
12718
|
+
const parts = path11.relative(root, file).split(path11.sep);
|
|
12719
|
+
const [name, fileName] = parts;
|
|
12720
|
+
return parts.length === 2 && name !== ".." && fileName === "SKILL.md" && name !== undefined ? [name] : [];
|
|
12721
|
+
}));
|
|
12722
|
+
const readPaths = readFiles.flatMap((file) => references.filter((reference) => skillRoots.some((root) => path11.resolve(root, reference) === file)).map((reference) => path11.resolve(claudeRoot, reference)));
|
|
12723
|
+
return { skills: [...new Set(skills)], readPaths: [...new Set(readPaths)] };
|
|
12724
|
+
}
|
|
12725
|
+
|
|
12726
|
+
// src/collect-command-reads.ts
|
|
12727
|
+
import path12 from "path";
|
|
12728
|
+
function collectCommandReads(command, cwd) {
|
|
12729
|
+
const commands = parseShellCommands(command, { withGuards: true }) ?? [];
|
|
12730
|
+
const reads = [];
|
|
12731
|
+
const parentDirs = [];
|
|
12732
|
+
let current = cwd;
|
|
12733
|
+
for (const entry of commands) {
|
|
12734
|
+
const enteredFrom = current;
|
|
12735
|
+
parentDirs.push(...Array.from({ length: entry.enters }, () => enteredFrom));
|
|
12736
|
+
if (current !== null && isSureToRun(entry)) {
|
|
12737
|
+
const directory = current;
|
|
12738
|
+
reads.push(...collectReaderPaths(entry).map((word) => path12.resolve(directory, word)));
|
|
12739
|
+
}
|
|
12740
|
+
current = resolveNextDir2(entry, current);
|
|
12741
|
+
for (let left = 0;left < entry.leaves && parentDirs.length > 0; left += 1) {
|
|
12742
|
+
current = parentDirs.pop() ?? null;
|
|
12743
|
+
}
|
|
12744
|
+
}
|
|
12745
|
+
return [...new Set(reads)];
|
|
12746
|
+
}
|
|
12747
|
+
function isSureToRun(command) {
|
|
12748
|
+
const guard = command.guard ?? null;
|
|
12749
|
+
return guard === null || !guard.viaOr && guard.before.every((words) => isSureToSucceed(words));
|
|
12750
|
+
}
|
|
12751
|
+
var SURE_PROGRAMS = new Set(["cd", "pushd", "true", ":", "export"]);
|
|
12752
|
+
var ASSIGNMENT2 = /^[A-Za-z_]\w*=/u;
|
|
12753
|
+
function isSureToSucceed(words) {
|
|
12754
|
+
const firstWord = words.find((word) => !ASSIGNMENT2.test(word.text));
|
|
12755
|
+
return firstWord !== undefined && firstWord.literal && SURE_PROGRAMS.has(firstWord.text);
|
|
12756
|
+
}
|
|
12757
|
+
var READERS = new Set(["cat", "head", "tail", "sed", "nl", "less", "bat"]);
|
|
12758
|
+
function collectReaderPaths(command) {
|
|
12759
|
+
const firstWord = command.words.findIndex((word) => !ASSIGNMENT2.test(word.text));
|
|
12760
|
+
const words = firstWord === -1 ? [] : command.words.slice(firstWord);
|
|
12761
|
+
const [program, ...args] = words;
|
|
12762
|
+
if (program === undefined || !program.literal) {
|
|
12763
|
+
return [];
|
|
12764
|
+
}
|
|
12765
|
+
const name = path12.basename(program.text);
|
|
12766
|
+
if (!READERS.has(name)) {
|
|
12767
|
+
return [];
|
|
12768
|
+
}
|
|
12769
|
+
const quiet = args.some((arg) => /^-[A-Za-z]*n[A-Za-z]*$/u.test(arg.text) || arg.text === "--quiet" || arg.text === "--silent");
|
|
12770
|
+
if (name === "sed" && !quiet) {
|
|
12771
|
+
return [];
|
|
12772
|
+
}
|
|
12773
|
+
const operands = args.filter((arg) => arg.literal && arg.text !== "" && !arg.text.startsWith("-")).map((arg) => arg.text);
|
|
12774
|
+
const redirected = command.redirects.filter((redirect) => redirect.operator === "<" && redirect.target.literal).map((redirect) => redirect.target.text);
|
|
12775
|
+
return [...operands, ...redirected];
|
|
12776
|
+
}
|
|
12777
|
+
function resolveNextDir2(command, directory) {
|
|
12778
|
+
const firstWord = command.words.findIndex((word) => !ASSIGNMENT2.test(word.text));
|
|
12779
|
+
const [program, ...args] = firstWord === -1 ? [] : command.words.slice(firstWord);
|
|
12780
|
+
if (program?.text !== "cd" || !program.literal) {
|
|
12781
|
+
return directory;
|
|
12782
|
+
}
|
|
12783
|
+
const target = args.find((arg) => !arg.text.startsWith("-"));
|
|
12784
|
+
if (target === undefined || !target.literal) {
|
|
12785
|
+
return null;
|
|
12786
|
+
}
|
|
12787
|
+
return directory === null && !path12.isAbsolute(target.text) ? null : path12.resolve(directory ?? "/", target.text);
|
|
12788
|
+
}
|
|
12789
|
+
|
|
12790
|
+
// src/collect-prompt-skills.ts
|
|
12791
|
+
var SKILL_MENTION = /(?<![\w$])\$(?<skill>[\w][\w:.-]*)/gu;
|
|
12792
|
+
function collectPromptSkills(prompt) {
|
|
12793
|
+
const names = [...prompt.matchAll(SKILL_MENTION)].flatMap((found) => {
|
|
12794
|
+
const name = found.groups?.["skill"]?.replace(/[.:-]+$/u, "");
|
|
12795
|
+
return name === undefined || name === "" ? [] : [name];
|
|
12796
|
+
});
|
|
12797
|
+
return [...new Set(names)];
|
|
12798
|
+
}
|
|
12799
|
+
|
|
12800
|
+
// src/with-ledger-lock.ts
|
|
12801
|
+
import { mkdir as mkdir2, rmdir, stat } from "fs/promises";
|
|
12802
|
+
import path13 from "path";
|
|
12803
|
+
async function withLedgerLock(ledgerPath, job) {
|
|
12804
|
+
if (ledgerPath === null) {
|
|
12805
|
+
return job();
|
|
12806
|
+
}
|
|
12807
|
+
const lockPath = `${ledgerPath}.lock`;
|
|
12808
|
+
const held = await acquireLock(lockPath);
|
|
12809
|
+
try {
|
|
12810
|
+
return await job();
|
|
12811
|
+
} finally {
|
|
12812
|
+
if (held) {
|
|
12813
|
+
await rmdir(lockPath).catch(() => null);
|
|
12814
|
+
}
|
|
12815
|
+
}
|
|
12816
|
+
}
|
|
12817
|
+
var RETRY_MS = 10;
|
|
12818
|
+
var GIVE_UP_MS = 5000;
|
|
12819
|
+
var STALE_MS = 30000;
|
|
12820
|
+
async function acquireLock(lockPath) {
|
|
12821
|
+
try {
|
|
12822
|
+
await mkdir2(path13.dirname(lockPath), { recursive: true });
|
|
12823
|
+
} catch {
|
|
12824
|
+
return false;
|
|
12825
|
+
}
|
|
12826
|
+
const deadline = Date.now() + GIVE_UP_MS;
|
|
12827
|
+
while (Date.now() < deadline) {
|
|
12828
|
+
try {
|
|
12829
|
+
await mkdir2(lockPath);
|
|
12830
|
+
return true;
|
|
12831
|
+
} catch {
|
|
12832
|
+
const info = await stat(lockPath).catch(() => null);
|
|
12833
|
+
const isStale = info !== null && Date.now() - info.mtimeMs > STALE_MS;
|
|
12834
|
+
await (isStale ? rmdir(lockPath).catch(() => null) : Bun.sleep(RETRY_MS));
|
|
12835
|
+
}
|
|
12836
|
+
}
|
|
12837
|
+
return false;
|
|
12838
|
+
}
|
|
12839
|
+
|
|
12840
|
+
// src/record-codex-loads.ts
|
|
12841
|
+
async function recordLifecycle(input, projectDir) {
|
|
12842
|
+
const ledgerPath = resolveLedgerPath(input);
|
|
12843
|
+
await M3(input.event).with("PostCompact", () => withLedgerLock(ledgerPath, () => writeLoadLedger(ledgerPath, voidLoads()))).with("UserPromptSubmit", async () => {
|
|
12844
|
+
const mentioned = collectPromptSkills(input.prompt ?? "");
|
|
12845
|
+
if (mentioned.length === 0) {
|
|
12846
|
+
return;
|
|
12847
|
+
}
|
|
12848
|
+
const present = new Set([
|
|
12849
|
+
...await readAvailableSkills(path14.join(projectDir, ".agents", "skills")),
|
|
12850
|
+
...await readAvailableSkills(path14.join(projectDir, ".claude", "skills"))
|
|
12851
|
+
]);
|
|
12852
|
+
const skills = mentioned.filter((skill) => present.has(skill));
|
|
12853
|
+
if (skills.length > 0) {
|
|
12854
|
+
await addLedgerLoads(ledgerPath, { skills, readPaths: [] });
|
|
12855
|
+
}
|
|
12856
|
+
}).exhaustive();
|
|
12857
|
+
}
|
|
12858
|
+
async function recordCommandReads(input, command, projectDir, rulesText) {
|
|
12859
|
+
const parsedRules = parseSkillGateRules(rulesText);
|
|
12860
|
+
const references = parsedRules.ok ? parsedRules.tools.flatMap((gate) => gate.references) : [];
|
|
12861
|
+
const readFiles = collectCommandReads(command, input.cwd).filter((file) => statSync(file, { throwIfNoEntry: false })?.isFile() === true);
|
|
12862
|
+
const reads = classifyCommandReads(readFiles, projectDir, references);
|
|
12863
|
+
if (reads.skills.length === 0 && reads.readPaths.length === 0) {
|
|
12864
|
+
return;
|
|
12865
|
+
}
|
|
12866
|
+
await addLedgerLoads(resolveLedgerPath(input), reads);
|
|
12867
|
+
}
|
|
12868
|
+
async function addLedgerLoads(ledgerPath, loads) {
|
|
12869
|
+
await withLedgerLock(ledgerPath, async () => {
|
|
12870
|
+
const ledger = await readLoadLedger(ledgerPath);
|
|
12871
|
+
await writeLoadLedger(ledgerPath, addLoads(ledger, loads));
|
|
12872
|
+
});
|
|
12873
|
+
}
|
|
12874
|
+
|
|
12347
12875
|
// src/run-skill-gate.ts
|
|
12348
|
-
async function runSkillGate() {
|
|
12876
|
+
async function runSkillGate(harness = "claude-code") {
|
|
12349
12877
|
const payload = await Bun.stdin.json().catch(() => null);
|
|
12350
|
-
const
|
|
12351
|
-
if (
|
|
12878
|
+
const parsedInput = parseHookInput(harness, payload);
|
|
12879
|
+
if (parsedInput === null) {
|
|
12352
12880
|
process.exit(0);
|
|
12353
12881
|
}
|
|
12354
12882
|
process.env["GIT_OPTIONAL_LOCKS"] = "0";
|
|
12355
|
-
const projectDir =
|
|
12356
|
-
const rulesFile = Bun.file(
|
|
12883
|
+
const projectDir = await readProjectDir(parsedInput.cwd);
|
|
12884
|
+
const rulesFile = Bun.file(path15.join(projectDir, ".claude", "skill-gate.json"));
|
|
12357
12885
|
const hasRules = await rulesFile.exists();
|
|
12886
|
+
if (parsedInput.kind === "lifecycle") {
|
|
12887
|
+
if (hasRules) {
|
|
12888
|
+
await recordLifecycle(parsedInput, projectDir);
|
|
12889
|
+
}
|
|
12890
|
+
process.exit(0);
|
|
12891
|
+
}
|
|
12892
|
+
const input = parsedInput;
|
|
12358
12893
|
if (hasRules && input.toolName !== null && input.event === "PreToolUse") {
|
|
12359
12894
|
await checkToolCall({
|
|
12360
12895
|
hookInput: input,
|
|
@@ -12364,72 +12899,45 @@ async function runSkillGate() {
|
|
|
12364
12899
|
});
|
|
12365
12900
|
}
|
|
12366
12901
|
if (hasRules && input.command !== null) {
|
|
12367
|
-
await
|
|
12368
|
-
|
|
12369
|
-
|
|
12370
|
-
|
|
12371
|
-
|
|
12372
|
-
});
|
|
12902
|
+
const rulesText = await rulesFile.text();
|
|
12903
|
+
if (input.harness === "codex" && input.event === "PostToolUse") {
|
|
12904
|
+
await recordCommandReads(input, input.command, projectDir, rulesText);
|
|
12905
|
+
}
|
|
12906
|
+
await checkBash({ hookInput: input, command: input.command, projectDir, rulesText });
|
|
12373
12907
|
}
|
|
12374
|
-
if (input.
|
|
12908
|
+
if (input.editPaths.length === 0 || input.event !== "PreToolUse") {
|
|
12375
12909
|
process.exit(0);
|
|
12376
12910
|
}
|
|
12377
|
-
const
|
|
12378
|
-
|
|
12379
|
-
if (!hasRules || isOutsideProject(relativePath)) {
|
|
12911
|
+
const edits = input.editPaths.map((editPath) => path15.resolve(input.cwd, editPath)).map((filePath) => ({ filePath, relativePath: toProjectPath(projectDir, filePath) })).filter((edit) => !isOutsideProject(edit.relativePath));
|
|
12912
|
+
if (!hasRules || edits.length === 0) {
|
|
12380
12913
|
process.exit(0);
|
|
12381
12914
|
}
|
|
12382
12915
|
const rulesText = await rulesFile.text();
|
|
12383
12916
|
const parsed = parseSkillGateRules(rulesText);
|
|
12384
12917
|
if (!parsed.ok) {
|
|
12385
|
-
|
|
12918
|
+
const emptyPlan = { missing: [], unknown: [] };
|
|
12919
|
+
const unchecked = edits.map((edit) => ({ filePath: edit.filePath, plan: emptyPlan }));
|
|
12920
|
+
printOutput(buildEditOutput(input.harness, unchecked, { rulesError: parsed.error }));
|
|
12386
12921
|
process.exit(0);
|
|
12387
12922
|
}
|
|
12388
|
-
const availableSkills = await readAvailableSkills(
|
|
12389
|
-
const
|
|
12390
|
-
const
|
|
12391
|
-
|
|
12392
|
-
|
|
12393
|
-
|
|
12394
|
-
|
|
12395
|
-
|
|
12396
|
-
|
|
12397
|
-
|
|
12923
|
+
const availableSkills = await readAvailableSkills(path15.join(projectDir, ".claude", "skills"));
|
|
12924
|
+
const loaded = await readSessionLoads(input);
|
|
12925
|
+
const entries = edits.map((edit) => ({
|
|
12926
|
+
filePath: edit.filePath,
|
|
12927
|
+
plan: planSkillGate({
|
|
12928
|
+
rules: parsed.rules,
|
|
12929
|
+
relativePath: edit.relativePath,
|
|
12930
|
+
loadedSkills: loaded.skills,
|
|
12931
|
+
availableSkills
|
|
12932
|
+
})
|
|
12933
|
+
}));
|
|
12934
|
+
printOutput(buildEditOutput(input.harness, entries, {
|
|
12398
12935
|
compacted: loaded.compacted,
|
|
12399
12936
|
unknownKeys: parsed.unknownKeys
|
|
12400
12937
|
}));
|
|
12401
12938
|
process.exit(0);
|
|
12402
12939
|
}
|
|
12403
|
-
|
|
12404
|
-
if (!isRecord(value) || !isRecord(value["tool_input"])) {
|
|
12405
|
-
return null;
|
|
12406
|
-
}
|
|
12407
|
-
const cwd = value["cwd"];
|
|
12408
|
-
const transcriptPath = value["transcript_path"];
|
|
12409
|
-
const editPath = value["tool_input"]["file_path"];
|
|
12410
|
-
const command = value["tool_input"]["command"];
|
|
12411
|
-
const toolName = value["tool_name"];
|
|
12412
|
-
if (typeof cwd !== "string" || typeof transcriptPath !== "string") {
|
|
12413
|
-
return null;
|
|
12414
|
-
}
|
|
12415
|
-
if (typeof editPath !== "string" && typeof command !== "string" && typeof toolName !== "string") {
|
|
12416
|
-
return null;
|
|
12417
|
-
}
|
|
12418
|
-
return {
|
|
12419
|
-
event: pickHookEvent(value["hook_event_name"]),
|
|
12420
|
-
toolName: typeof toolName === "string" ? toolName : null,
|
|
12421
|
-
cwd,
|
|
12422
|
-
filePath: typeof editPath === "string" ? editPath : null,
|
|
12423
|
-
command: typeof command === "string" ? command : null,
|
|
12424
|
-
transcriptPath,
|
|
12425
|
-
toolUseID: value["tool_use_id"],
|
|
12426
|
-
agentID: value["agent_id"]
|
|
12427
|
-
};
|
|
12428
|
-
}
|
|
12429
|
-
function pickHookEvent(value) {
|
|
12430
|
-
return value === "PostToolUse" || value === "PostToolUseFailure" ? value : "PreToolUse";
|
|
12431
|
-
}
|
|
12432
|
-
var PATH_GATED_TOOLS2 = new Set(["Edit", "Write", "MultiEdit", "Bash"]);
|
|
12940
|
+
var PATH_GATED_TOOLS2 = new Set(["Edit", "Write", "MultiEdit", "Bash", "apply_patch"]);
|
|
12433
12941
|
async function checkToolCall(check) {
|
|
12434
12942
|
const parsedRules = parseSkillGateRules(check.rulesText);
|
|
12435
12943
|
if (!parsedRules.ok) {
|
|
@@ -12442,9 +12950,8 @@ async function checkToolCall(check) {
|
|
|
12442
12950
|
if (!parsedRules.tools.some((gate) => gate.tool === check.toolName)) {
|
|
12443
12951
|
return;
|
|
12444
12952
|
}
|
|
12445
|
-
const skillsDir =
|
|
12446
|
-
const
|
|
12447
|
-
const loads = collectSessionLoads(transcript);
|
|
12953
|
+
const skillsDir = path15.join(check.projectDir, ".claude", "skills");
|
|
12954
|
+
const loads = await readSessionLoads(check.hookInput);
|
|
12448
12955
|
const plan = planToolGate({
|
|
12449
12956
|
tools: parsedRules.tools,
|
|
12450
12957
|
toolName: check.toolName,
|
|
@@ -12454,6 +12961,7 @@ async function checkToolCall(check) {
|
|
|
12454
12961
|
availableReferences: await readAvailableReferences(readFileContent, skillsDir, parsedRules.tools)
|
|
12455
12962
|
});
|
|
12456
12963
|
printOutput(buildToolGateOutput(check.toolName, plan, {
|
|
12964
|
+
harness: check.hookInput.harness,
|
|
12457
12965
|
compacted: loads.compacted,
|
|
12458
12966
|
unknownKeys: parsedRules.unknownKeys
|
|
12459
12967
|
}));
|
|
@@ -12464,47 +12972,6 @@ function printOutput(output) {
|
|
|
12464
12972
|
console.log(JSON.stringify(output));
|
|
12465
12973
|
}
|
|
12466
12974
|
}
|
|
12467
|
-
async function readSessionTranscript(hookInput) {
|
|
12468
|
-
if (hookInput.agentID === undefined) {
|
|
12469
|
-
return readTranscript(hookInput.transcriptPath);
|
|
12470
|
-
}
|
|
12471
|
-
if (typeof hookInput.agentID !== "string" || !/^[\w-]+$/u.test(hookInput.agentID)) {
|
|
12472
|
-
return "";
|
|
12473
|
-
}
|
|
12474
|
-
const subagentsDir = path7.join(hookInput.transcriptPath.replace(/\.jsonl$/u, ""), "subagents");
|
|
12475
|
-
const transcriptName = `agent-${hookInput.agentID}.jsonl`;
|
|
12476
|
-
const agentTranscript = await readTranscript(path7.join(subagentsDir, transcriptName));
|
|
12477
|
-
if (agentTranscript !== "") {
|
|
12478
|
-
return agentTranscript;
|
|
12479
|
-
}
|
|
12480
|
-
return readWorkflowAgentTranscript(subagentsDir, transcriptName);
|
|
12481
|
-
}
|
|
12482
|
-
async function readTranscript(transcriptPath) {
|
|
12483
|
-
const transcriptFile = Bun.file(transcriptPath);
|
|
12484
|
-
const exists = await transcriptFile.exists();
|
|
12485
|
-
return exists ? transcriptFile.text() : "";
|
|
12486
|
-
}
|
|
12487
|
-
async function readWorkflowAgentTranscript(subagentsDir, transcriptName) {
|
|
12488
|
-
const scan = new Bun.Glob(`workflows/*/${transcriptName}`).scan({ cwd: subagentsDir });
|
|
12489
|
-
let transcriptPath = null;
|
|
12490
|
-
try {
|
|
12491
|
-
for await (const scannedPath of scan) {
|
|
12492
|
-
transcriptPath = scannedPath;
|
|
12493
|
-
break;
|
|
12494
|
-
}
|
|
12495
|
-
} catch {}
|
|
12496
|
-
return transcriptPath === null ? "" : readTranscript(path7.join(subagentsDir, transcriptPath));
|
|
12497
|
-
}
|
|
12498
|
-
async function readAvailableSkills(skillsDir) {
|
|
12499
|
-
const skills = [];
|
|
12500
|
-
const scan = new Bun.Glob("*/SKILL.md").scan({ cwd: skillsDir, followSymlinks: true });
|
|
12501
|
-
try {
|
|
12502
|
-
for await (const skillFile of scan) {
|
|
12503
|
-
skills.push(path7.dirname(skillFile));
|
|
12504
|
-
}
|
|
12505
|
-
} catch {}
|
|
12506
|
-
return skills;
|
|
12507
|
-
}
|
|
12508
12975
|
async function checkBash(check) {
|
|
12509
12976
|
const parsedRules = parseSkillGateRules(check.rulesText);
|
|
12510
12977
|
if (!parsedRules.ok) {
|
|
@@ -12531,8 +12998,8 @@ function resolveSnapshotPath(hookInput) {
|
|
|
12531
12998
|
if (typeof hookInput.toolUseID !== "string" || !/^[\w-]+$/u.test(hookInput.toolUseID)) {
|
|
12532
12999
|
return null;
|
|
12533
13000
|
}
|
|
12534
|
-
const
|
|
12535
|
-
return
|
|
13001
|
+
const stateDir = resolveStateDir(hookInput);
|
|
13002
|
+
return stateDir === null ? null : path15.join(stateDir, `${hookInput.toolUseID}.json`);
|
|
12536
13003
|
}
|
|
12537
13004
|
async function writeGatedSnapshot(git, snapshotPath, projectDir, rules) {
|
|
12538
13005
|
const snapshot = await readGatedSnapshot(git, projectDir, rules);
|
|
@@ -12540,7 +13007,7 @@ async function writeGatedSnapshot(git, snapshotPath, projectDir, rules) {
|
|
|
12540
13007
|
return;
|
|
12541
13008
|
}
|
|
12542
13009
|
try {
|
|
12543
|
-
await
|
|
13010
|
+
await mkdir3(path15.dirname(snapshotPath), { recursive: true });
|
|
12544
13011
|
await Bun.write(snapshotPath, JSON.stringify(snapshot));
|
|
12545
13012
|
} catch {
|
|
12546
13013
|
await rm(snapshotPath, { force: true });
|
|
@@ -12565,10 +13032,10 @@ function collectGatedProjectPaths(projectDir, rules, absolutePaths) {
|
|
|
12565
13032
|
return [...new Set(absolutePaths.map((entry) => toProjectPath(projectDir, entry)))].filter((relativePath) => !isOutsideProject(relativePath) && collectGateSkills(rules, relativePath).length > 0);
|
|
12566
13033
|
}
|
|
12567
13034
|
function toProjectPath(projectDir, absolute) {
|
|
12568
|
-
return
|
|
13035
|
+
return path15.relative(projectDir, absolute).split(path15.sep).join("/");
|
|
12569
13036
|
}
|
|
12570
13037
|
function isOutsideProject(fromProject) {
|
|
12571
|
-
return fromProject === ".." || fromProject.startsWith("../") ||
|
|
13038
|
+
return fromProject === ".." || fromProject.startsWith("../") || path15.isAbsolute(fromProject);
|
|
12572
13039
|
}
|
|
12573
13040
|
async function checkBashCommand(check, rules) {
|
|
12574
13041
|
const written = collectWrittenPaths(check.command).map((entry) => readWrittenPath(check.hookInput.cwd, entry));
|
|
@@ -12576,9 +13043,8 @@ async function checkBashCommand(check, rules) {
|
|
|
12576
13043
|
if (candidates.length === 0) {
|
|
12577
13044
|
return;
|
|
12578
13045
|
}
|
|
12579
|
-
const skills = await readAvailableSkills(
|
|
12580
|
-
const
|
|
12581
|
-
const sessionLoads = collectSessionLoads(sessionTranscript);
|
|
13046
|
+
const skills = await readAvailableSkills(path15.join(check.projectDir, ".claude", "skills"));
|
|
13047
|
+
const sessionLoads = await readSessionLoads(check.hookInput);
|
|
12582
13048
|
const bashPlan = planBashSkillGate({
|
|
12583
13049
|
rules,
|
|
12584
13050
|
paths: candidates.map((entry) => ({
|
|
@@ -12589,16 +13055,17 @@ async function checkBashCommand(check, rules) {
|
|
|
12589
13055
|
availableSkills: skills
|
|
12590
13056
|
});
|
|
12591
13057
|
printOutput(buildBashSkillGateOutput(bashPlan.gatedPaths, bashPlan.missing, {
|
|
13058
|
+
harness: check.hookInput.harness,
|
|
12592
13059
|
compacted: sessionLoads.compacted
|
|
12593
13060
|
}));
|
|
12594
13061
|
}
|
|
12595
13062
|
function readWrittenPath(cwd, written) {
|
|
12596
|
-
const absolute =
|
|
13063
|
+
const absolute = path15.resolve(cwd, written.path);
|
|
12597
13064
|
if (written.fileName === undefined) {
|
|
12598
13065
|
return absolute;
|
|
12599
13066
|
}
|
|
12600
|
-
const isDirectory =
|
|
12601
|
-
return isDirectory ?
|
|
13067
|
+
const isDirectory = statSync2(absolute, { throwIfNoEntry: false })?.isDirectory() === true;
|
|
13068
|
+
return isDirectory ? path15.join(absolute, written.fileName) : absolute;
|
|
12602
13069
|
}
|
|
12603
13070
|
async function checkBashResult(check, rules, result) {
|
|
12604
13071
|
const record = await readSnapshot(result.snapshotPath);
|
|
@@ -12631,19 +13098,19 @@ async function runBashResultStep(check, rules, result, step) {
|
|
|
12631
13098
|
}).with({ kind: "gate" }, (gate) => checkChangedPaths(check, rules, result, gate.changedPaths)).exhaustive();
|
|
12632
13099
|
}
|
|
12633
13100
|
async function checkChangedPaths(check, rules, result, changedPaths) {
|
|
12634
|
-
const skills = await readAvailableSkills(
|
|
12635
|
-
const
|
|
12636
|
-
const sessionLoads = collectSessionLoads(sessionTranscript);
|
|
13101
|
+
const skills = await readAvailableSkills(path15.join(check.projectDir, ".claude", "skills"));
|
|
13102
|
+
const sessionLoads = await readSessionLoads(check.hookInput);
|
|
12637
13103
|
const changePlan = planBashSkillGate({
|
|
12638
13104
|
rules,
|
|
12639
13105
|
paths: changedPaths.map((relativePath) => ({
|
|
12640
|
-
path:
|
|
13106
|
+
path: path15.join(check.projectDir, relativePath),
|
|
12641
13107
|
relativePath
|
|
12642
13108
|
})),
|
|
12643
13109
|
loadedSkills: sessionLoads.skills,
|
|
12644
13110
|
availableSkills: skills
|
|
12645
13111
|
});
|
|
12646
13112
|
printOutput(buildBashChangeOutput(result.event, changePlan.gatedPaths, changePlan.missing, {
|
|
13113
|
+
harness: check.hookInput.harness,
|
|
12647
13114
|
compacted: sessionLoads.compacted
|
|
12648
13115
|
}));
|
|
12649
13116
|
}
|