@zgeoff/skill-gate 0.2.7 → 0.2.9

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 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 path7 from "path";
2571
- // ../std/src/is-record.ts
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) {
@@ -5575,7 +5572,7 @@ var wo = (t, e) => {
5575
5572
  return Array.isArray(r.config) && n.add(qs(r.config)), n.add(zs(r.unsafe)), n.add(Ws(r.completion)), r.abort && n.add(Is(r.abort)), r.progress && n.add(so(r.progress)), r.timeout && n.add(uo(r.timeout)), r.spawnOptions && n.add(io(r.spawnOptions)), n.add(ao()), n.add(no(r.input)), n.add(Mt(to(true))), r.errors && n.add(Mt(r.errors)), Xs(n, r.binary, r.unsafe?.allowUnsafeCustomBinary), n.add(Fs(r.allowEnvironment ?? [], r.unsafe?.allowAbbreviatedOptions)), new f2(r, n);
5576
5573
  };
5577
5574
 
5578
- // ../../node_modules/.bun/ts-pattern@5.9.0/node_modules/ts-pattern/dist/index.js
5575
+ // ../../node_modules/.bun/ts-pattern@5.9.2/node_modules/ts-pattern/dist/index.js
5579
5576
  var t2 = Symbol.for("@ts-pattern/matcher");
5580
5577
  var e = Symbol.for("@ts-pattern/isVariadic");
5581
5578
  var n = "@ts-pattern/anonymous-select-key";
@@ -5764,7 +5761,7 @@ function F3(t) {
5764
5761
  throw new I3(t);
5765
5762
  }
5766
5763
 
5767
- // ../../node_modules/.bun/zod@4.6.6/node_modules/zod/v4/core/util.js
5764
+ // ../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/util.js
5768
5765
  function getEnumValues(entries) {
5769
5766
  const numericValues = Object.values(entries).filter((v) => typeof v === "number");
5770
5767
  const values = Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v);
@@ -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 pick2(schema, mask) {
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;
@@ -6311,7 +6308,7 @@ function constantCatch(value) {
6311
6308
  return fn;
6312
6309
  }
6313
6310
 
6314
- // ../../node_modules/.bun/zod@4.6.6/node_modules/zod/v4/core/core.js
6311
+ // ../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/core.js
6315
6312
  var _a;
6316
6313
  var _zodDesc = { value: undefined, enumerable: false };
6317
6314
  var _E = "captureStackTrace" in Error ? Error : null;
@@ -6429,7 +6426,7 @@ function config(newConfig) {
6429
6426
  Object.assign(globalConfig, newConfig);
6430
6427
  return globalConfig;
6431
6428
  }
6432
- // ../../node_modules/.bun/zod@4.6.6/node_modules/zod/v4/core/errors.js
6429
+ // ../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/errors.js
6433
6430
  function _getMessage() {
6434
6431
  const internals = this._zod;
6435
6432
  internals.message ?? (internals.message = JSON.stringify(internals.def, jsonStringifyReplacer, 2));
@@ -6544,7 +6541,7 @@ function formatError(error, mapper = (issue) => issue.message) {
6544
6541
  return fieldErrors;
6545
6542
  }
6546
6543
 
6547
- // ../../node_modules/.bun/zod@4.6.6/node_modules/zod/v4/core/parse.js
6544
+ // ../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/parse.js
6548
6545
  function finalizeParams(callee, params) {
6549
6546
  return { callee: params?.callee ?? callee, Err: params?.Err };
6550
6547
  }
@@ -6691,7 +6688,7 @@ var _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {
6691
6688
  var _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {
6692
6689
  return _safeParseAsync(_Err)(schema, value, _ctx);
6693
6690
  };
6694
- // ../../node_modules/.bun/zod@4.6.6/node_modules/zod/v4/core/regexes.js
6691
+ // ../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/regexes.js
6695
6692
  var cuid = /^[cC][0-9a-z]{6,}$/;
6696
6693
  var cuid2 = /^[0-9a-z]+$/;
6697
6694
  var ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/;
@@ -6745,10 +6742,11 @@ 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
 
6751
- // ../../node_modules/.bun/zod@4.6.6/node_modules/zod/v4/core/checks.js
6749
+ // ../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/checks.js
6752
6750
  var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => {
6753
6751
  var _a;
6754
6752
  inst._zod ?? (inst._zod = {});
@@ -6934,7 +6932,7 @@ var $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (ins
6934
6932
  };
6935
6933
  });
6936
6934
 
6937
- // ../../node_modules/.bun/zod@4.6.6/node_modules/zod/v4/core/doc.js
6935
+ // ../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/doc.js
6938
6936
  class Doc {
6939
6937
  constructor(args = [], closed = {}) {
6940
6938
  this.content = [];
@@ -6976,14 +6974,14 @@ ${content.join(`
6976
6974
  }
6977
6975
  }
6978
6976
 
6979
- // ../../node_modules/.bun/zod@4.6.6/node_modules/zod/v4/core/versions.js
6977
+ // ../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/versions.js
6980
6978
  var version = {
6981
6979
  major: 4,
6982
6980
  minor: 6,
6983
- patch: 6
6981
+ patch: 7
6984
6982
  };
6985
6983
 
6986
- // ../../node_modules/.bun/zod@4.6.6/node_modules/zod/v4/core/schemas.js
6984
+ // ../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/schemas.js
6987
6985
  var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
6988
6986
  var _a;
6989
6987
  inst ?? (inst = {});
@@ -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;
@@ -8572,7 +8590,7 @@ function handleRefineResult(result, payload, input, inst) {
8572
8590
  payload.issues.push(issue(_iss));
8573
8591
  }
8574
8592
  }
8575
- // ../../node_modules/.bun/zod@4.6.6/node_modules/zod/v4/core/memoizer.js
8593
+ // ../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/memoizer.js
8576
8594
  class $ZodCyclicError extends Error {
8577
8595
  constructor() {
8578
8596
  super(`Cannot parse a reference cycle that closes through a transform`);
@@ -8841,7 +8859,7 @@ function isBackEdge(ctx, value) {
8841
8859
  const backEdges = ctx[STATE]?.backEdges;
8842
8860
  return backEdges !== undefined && isRef(value) && backEdges.has(value);
8843
8861
  }
8844
- // ../../node_modules/.bun/zod@4.6.6/node_modules/zod/v4/locales/en.js
8862
+ // ../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/locales/en.js
8845
8863
  var error = () => {
8846
8864
  const Sizable = {
8847
8865
  string: { unit: "characters", verb: "to have" },
@@ -8963,7 +8981,7 @@ function en_default() {
8963
8981
  localeError: error()
8964
8982
  };
8965
8983
  }
8966
- // ../../node_modules/.bun/zod@4.6.6/node_modules/zod/v4/core/registries.js
8984
+ // ../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/registries.js
8967
8985
  var _a2;
8968
8986
  class $ZodRegistry {
8969
8987
  constructor() {
@@ -9010,7 +9028,7 @@ function registry() {
9010
9028
  }
9011
9029
  (_a2 = globalThis).__zod_globalRegistry ?? (_a2.__zod_globalRegistry = registry());
9012
9030
  var globalRegistry = globalThis.__zod_globalRegistry;
9013
- // ../../node_modules/.bun/zod@4.6.6/node_modules/zod/v4/core/api.js
9031
+ // ../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/api.js
9014
9032
  function snapshotChecks(def) {
9015
9033
  if (def.checks)
9016
9034
  def.checks = [...def.checks];
@@ -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"
@@ -9401,7 +9425,7 @@ function _check(fn, params) {
9401
9425
  ch._zod.check = fn;
9402
9426
  return ch;
9403
9427
  }
9404
- // ../../node_modules/.bun/zod@4.6.6/node_modules/zod/v4/core/to-json-schema.js
9428
+ // ../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/to-json-schema.js
9405
9429
  function assignProps(target, ...sources) {
9406
9430
  for (const source of sources) {
9407
9431
  for (const key of Reflect.ownKeys(source)) {
@@ -9924,7 +9948,7 @@ var createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) =
9924
9948
  extractDefs(ctx, schema);
9925
9949
  return finalize(ctx, schema);
9926
9950
  };
9927
- // ../../node_modules/.bun/zod@4.6.6/node_modules/zod/v4/core/json-schema-processors.js
9951
+ // ../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/json-schema-processors.js
9928
9952
  var narrowMin = (agg, key, value) => {
9929
9953
  if (agg[key] === undefined || value > agg[key])
9930
9954
  agg[key] = value;
@@ -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
  };
@@ -10404,7 +10431,7 @@ var optionalProcessor = (schema, ctx, _json, params) => {
10404
10431
  const seen = ctx.seen.get(schema);
10405
10432
  seen.ref = def.innerType;
10406
10433
  };
10407
- // ../../node_modules/.bun/zod@4.6.6/node_modules/zod/v4/classic/errors.js
10434
+ // ../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/classic/errors.js
10408
10435
  var _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);
10409
10436
  function _lazyMethod(proto, key, make) {
10410
10437
  Object.defineProperty(proto, key, {
@@ -10449,7 +10476,7 @@ var ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer2, undefi
10449
10476
  Parent: Error
10450
10477
  });
10451
10478
 
10452
- // ../../node_modules/.bun/zod@4.6.6/node_modules/zod/v4/classic/parse.js
10479
+ // ../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/classic/parse.js
10453
10480
  var parse2 = /* @__PURE__ */ _parse(ZodRealError);
10454
10481
  var parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError);
10455
10482
  var safeParse = /* @__PURE__ */ _safeParse(ZodRealError);
@@ -10463,7 +10490,7 @@ var safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError);
10463
10490
  var safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError);
10464
10491
  var safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError);
10465
10492
 
10466
- // ../../node_modules/.bun/zod@4.6.6/node_modules/zod/v4/classic/schemas.js
10493
+ // ../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/classic/schemas.js
10467
10494
  function _ensureDefaultLocale() {
10468
10495
  if (!globalConfig.localeError)
10469
10496
  config(en_default());
@@ -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 pick2(this, mask);
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 with the Skill tool, ${review} This session was compacted, and a skill loaded before the compaction no longer counts.` : `Load the ${formatSkillList(missing)} with the Skill tool, ${review}`;
11309
- const reason = `skill-gate: this Bash command ${subject} before the session loaded the skills it needs. ${load} Change a gated path only with Edit, Write or MultiEdit, never through Bash. ${RULES_PATH} lists the skills each path needs.`;
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 load = buildLoadInstruction(missing, context.compacted === true);
11332
- const rule = `${subject} with the Edit, Write or MultiEdit tool, never through Bash.`;
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 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.`;
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/build-skill-gate-output.ts
11402
+ // src/collect-rule-warnings.ts
11353
11403
  var RULES_PATH3 = ".claude/skill-gate.json";
11354
- var EDIT_TOOLS_NOTE = "Change a gated path only with Edit, Write or MultiEdit, never through Bash.";
11355
- function buildSkillGateOutput(filePath, plan, context = {}) {
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
- ...plan.unknown.map((entry) => `skill-gate: the rule "${entry.match}" in ${RULES_PATH3} names the skill "${entry.skill}", but .claude/skills/${entry.skill}/SKILL.md does not exist. Fix the rule or add the skill; until then the gate skips that skill.`)
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 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_PATH3} 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_PATH3} lists the skills each path needs.`;
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 RULES_PATH4 = ".claude/skill-gate.json";
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: ${RULES_PATH4} ${context.rulesError}.`],
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 ${RULES_PATH4} names the skill "${entry.name}", but .claude/skills/${entry.name}/SKILL.md does not exist. Fix the rule or add the skill; until then the gate skips that skill.` : `skill-gate: the tool gate "${entry.tool}" in ${RULES_PATH4} names the reference "${entry.name}", but .claude/skills/${entry.name} does not exist. Fix the rule or add the file; until then the gate skips that reference.`;
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} with the Skill tool`],
11421
- ...plan.missingReferences.length === 0 ? [] : [`read ${formatReferenceList(plan.missingReferences)}${again} with the Read tool`]
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} ${RULES_PATH4} lists the skills and references each tool needs.`;
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
- return tokens === null ? null : buildShellCommands(tokens);
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 path4 from "path";
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) => path4.join(directory, toRoot.trim(), 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 path5 from "path";
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(path5.join(projectDir, relativePath));
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 path6 from "path";
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) => path6.join(directory, toRoot.trim(), 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 input = parseHookInput(payload);
12351
- if (input === null) {
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 = process.env["CLAUDE_PROJECT_DIR"] ?? input.cwd;
12356
- const rulesFile = Bun.file(path7.join(projectDir, ".claude", "skill-gate.json"));
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 checkBash({
12368
- hookInput: input,
12369
- command: input.command,
12370
- projectDir,
12371
- rulesText: await rulesFile.text()
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.filePath === null || input.event !== "PreToolUse") {
12908
+ if (input.editPaths.length === 0 || input.event !== "PreToolUse") {
12375
12909
  process.exit(0);
12376
12910
  }
12377
- const filePath = path7.resolve(input.cwd, input.filePath);
12378
- const relativePath = toProjectPath(projectDir, filePath);
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
- printOutput(buildSkillGateOutput(filePath, { missing: [], unknown: [] }, { rulesError: parsed.error }));
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(path7.join(projectDir, ".claude", "skills"));
12389
- const transcript = await readSessionTranscript(input);
12390
- const loaded = collectSessionLoads(transcript);
12391
- const plan = planSkillGate({
12392
- rules: parsed.rules,
12393
- relativePath,
12394
- loadedSkills: loaded.skills,
12395
- availableSkills
12396
- });
12397
- printOutput(buildSkillGateOutput(filePath, plan, {
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
- function parseHookInput(value) {
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 = path7.join(check.projectDir, ".claude", "skills");
12446
- const transcript = await readSessionTranscript(check.hookInput);
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 sessionDir = hookInput.transcriptPath.replace(/\.jsonl$/u, "");
12535
- return path7.join(sessionDir, "skill-gate", `${hookInput.toolUseID}.json`);
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 mkdir(path7.dirname(snapshotPath), { recursive: true });
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 path7.relative(projectDir, absolute).split(path7.sep).join("/");
13035
+ return path15.relative(projectDir, absolute).split(path15.sep).join("/");
12569
13036
  }
12570
13037
  function isOutsideProject(fromProject) {
12571
- return fromProject === ".." || fromProject.startsWith("../") || path7.isAbsolute(fromProject);
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(path7.join(check.projectDir, ".claude", "skills"));
12580
- const sessionTranscript = await readSessionTranscript(check.hookInput);
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 = path7.resolve(cwd, written.path);
13063
+ const absolute = path15.resolve(cwd, written.path);
12597
13064
  if (written.fileName === undefined) {
12598
13065
  return absolute;
12599
13066
  }
12600
- const isDirectory = statSync(absolute, { throwIfNoEntry: false })?.isDirectory() === true;
12601
- return isDirectory ? path7.join(absolute, written.fileName) : absolute;
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(path7.join(check.projectDir, ".claude", "skills"));
12635
- const sessionTranscript = await readSessionTranscript(check.hookInput);
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: path7.join(check.projectDir, relativePath),
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
  }