rulesync 43.12.0 → 43.14.0

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.
@@ -9,8 +9,8 @@ import { intersection, kebabCase, uniq } from "es-toolkit";
9
9
  import { globbySync, isGitIgnoredSync } from "globby";
10
10
  import { AsyncLocalStorage } from "node:async_hooks";
11
11
  import { format, isDeepStrictEqual } from "node:util";
12
- import matter from "gray-matter";
13
12
  import { CORE_SCHEMA, DUMP_SCHEMA, YAMLException, defineScalarTag, dump, load } from "js-yaml";
13
+ import { dump as dump$1, load as load$1 } from "js-yaml-v4";
14
14
  import { omit } from "es-toolkit/object";
15
15
  import { createHash } from "node:crypto";
16
16
  import { encode } from "@toon-format/toon";
@@ -904,6 +904,7 @@ const permissionsProcessorToolTargetTuple = [
904
904
  "deepagents",
905
905
  "devin",
906
906
  "factorydroid",
907
+ "gitlabduo",
907
908
  "goose",
908
909
  "grokcli",
909
910
  "hermesagent",
@@ -1807,6 +1808,32 @@ async function relativeWriteLanding({ rootPath, targetPath }) {
1807
1808
  return relative(rootLanding, targetLanding);
1808
1809
  }
1809
1810
  /**
1811
+ * The first symbolic link on the way from `rootPath` down to `targetPath`, or
1812
+ * `null` when no existing entry below the root is a link. Only the segments
1813
+ * below the root are looked at, so a root that is itself a link (macOS
1814
+ * `/tmp -> /private/tmp`, a linked home directory) does not count; nor does a
1815
+ * target that is not spelled below the root. Once a segment is missing,
1816
+ * nothing below it exists, so the walk stops there.
1817
+ */
1818
+ async function firstLinkBelowRoot({ rootPath, targetPath }) {
1819
+ const relativeTarget = relative(resolve(rootPath), resolve(targetPath));
1820
+ if (relativeTarget === "" || pathEscapesRoot(relativeTarget)) return null;
1821
+ let current = resolve(rootPath);
1822
+ for (const segment of splitPathSegments(relativeTarget)) {
1823
+ if (segment === "") continue;
1824
+ current = join(current, segment);
1825
+ let stats;
1826
+ try {
1827
+ stats = await lstat(current);
1828
+ } catch (error) {
1829
+ if (isFileNotFoundError(error) || isNotADirectoryError(error)) return null;
1830
+ throw error;
1831
+ }
1832
+ if (stats.isSymbolicLink()) return current;
1833
+ }
1834
+ return null;
1835
+ }
1836
+ /**
1810
1837
  * Directory names that hold version-control metadata. Bytes landing in one of
1811
1838
  * them change how the VCS behaves rather than what it tracks: `.git/config`
1812
1839
  * can set `core.fsmonitor`, `.git/hooks/*` run on the next commit.
@@ -4463,37 +4490,6 @@ function toStringArray$1(value) {
4463
4490
  function toRecord(value) {
4464
4491
  return isRecord(value) ? value : {};
4465
4492
  }
4466
- // src/utils/yaml.ts
4467
- /**
4468
- * js-yaml v5's `reason` for an empty document. `load("")` — and any
4469
- * whitespace/comment-only input — throws a `YAMLException` with this reason
4470
- * instead of returning `undefined` the way v4 did.
4471
- */
4472
- const EMPTY_INPUT_REASON = "expected a document, but the input is empty";
4473
- /**
4474
- * Load YAML content while preserving js-yaml v4's behavior of returning
4475
- * `undefined` for empty documents (empty, whitespace-only, or comment-only
4476
- * input).
4477
- *
4478
- * js-yaml v5 changed `load("")` to **throw** ("expected a document, but the
4479
- * input is empty") instead of returning `undefined`. Many call sites here parse
4480
- * config/lock/frontmatter files that can legitimately be empty and rely on the
4481
- * old `undefined` sentinel (`load(input) ?? {}`, `if (loaded === undefined)`,
4482
- * "an empty file parses to undefined/null"). Routing every load through this
4483
- * wrapper keeps that contract in one place so a future js-yaml bump cannot
4484
- * reintroduce the empty-input regression. Genuine parse errors still propagate.
4485
- *
4486
- * @see https://github.com/nodeca/js-yaml/blob/master/docs/migrate_v4_to_v5.md#empty-input-throws
4487
- */
4488
- function loadYaml(content, options) {
4489
- if (content.trim() === "") return;
4490
- try {
4491
- return load(content, options);
4492
- } catch (error) {
4493
- if (error instanceof YAMLException && error.reason === EMPTY_INPUT_REASON) return;
4494
- throw error;
4495
- }
4496
- }
4497
4493
  // src/utils/frontmatter.ts
4498
4494
  /**
4499
4495
  * Upper bound on the number of values a frontmatter document may expand to
@@ -4525,10 +4521,10 @@ const MAX_FRONTMATTER_STRING_CHARS = 4e6;
4525
4521
  * block itself, checked before it is ever handed to the YAML parser.
4526
4522
  *
4527
4523
  * The budgets above only bound the *parsed* document — the walk over
4528
- * `matter()`'s output — but a complex YAML key (an array or mapping used as a
4524
+ * the parser's output — but a complex YAML key (an array or mapping used as a
4529
4525
  * mapping key) is joined into a string by js-yaml while it parses, and a
4530
4526
  * mapping with many such keys can cost real memory before that walk ever
4531
- * starts, or even before `matter()` returns. Capping the raw block size keeps
4527
+ * starts, or even before the parser returns. Capping the raw block size keeps
4532
4528
  * that parse-time cost bounded regardless of what the block contains. Real
4533
4529
  * frontmatter blocks are a few hundred bytes at most; even a large project
4534
4530
  * manifest stays well under this.
@@ -4550,8 +4546,8 @@ function estimateLeafChars(value) {
4550
4546
  /**
4551
4547
  * Copy one parsed value, dropping nullish leaves and cyclic references.
4552
4548
  *
4553
- * Every alias is still written out as an independent copy, as gray-matter's
4554
- * default YAML engine would otherwise serialize shared references as `&ref_0`
4549
+ * Every alias is still written out as an independent copy, as js-yaml's
4550
+ * dumper would otherwise serialize shared references as `&ref_0`
4555
4551
  * anchors that simplified frontmatter parsers cannot read; the expansion is
4556
4552
  * bounded by {@link MAX_FRONTMATTER_VALUES} instead.
4557
4553
  */
@@ -4627,63 +4623,27 @@ function deepFlattenStringsObject(obj) {
4627
4623
  function stringifyFrontmatter(body, frontmatter, options) {
4628
4624
  const { avoidBlockScalars = false } = options ?? {};
4629
4625
  const cleanFrontmatter = avoidBlockScalars ? deepFlattenStringsObject(frontmatter) : deepRemoveNullishObject(frontmatter);
4630
- const file = { content: body };
4631
- if (avoidBlockScalars) return matter.stringify(file, cleanFrontmatter, { engines: { yaml: {
4632
- parse: (input) => loadYaml(input) ?? {},
4633
- stringify: (data) => dump(data, { lineWidth: -1 })
4634
- } } });
4635
- return matter.stringify(file, cleanFrontmatter);
4636
- }
4637
- /**
4638
- * Thrown in place of gray-matter's built-in JavaScript engine.
4639
- *
4640
- * gray-matter picks the parser from the text after the opening fence, so a
4641
- * file that opens with `---js` or `---javascript` has its frontmatter handed
4642
- * to `eval()`. Frontmatter here comes from third-party skills, fetched sources
4643
- * and untrusted repositories, so that would run arbitrary code on the machine
4644
- * of whoever generates or imports it. Every engine name that resolves to code
4645
- * execution is mapped to this refusal; {@link assertYamlFrontmatterLanguage}
4646
- * refuses those fences earlier still, so this is the second line of defense.
4647
- */
4648
- function refuseExecutableFrontmatter() {
4649
- throw new Error("Frontmatter written in an executable language (JavaScript / CoffeeScript) is not supported; use YAML");
4650
- }
4651
- const REFUSED_FRONTMATTER_ENGINE = {
4652
- parse: refuseExecutableFrontmatter,
4653
- stringify: refuseExecutableFrontmatter
4654
- };
4655
- /**
4656
- * Engines passed to every gray-matter parse. Supplying them merges over
4657
- * gray-matter's defaults, so the JavaScript engine (and the CoffeeScript names
4658
- * a plugin could register) can never be reached through an alias.
4659
- *
4660
- * `patches/gray-matter@4.0.3.patch` also deletes the JavaScript engine, but a
4661
- * pnpm patch only applies inside this repository: gray-matter is an external
4662
- * dependency of the published package, so an installed rulesync runs the
4663
- * unpatched gray-matter, and this override plus the language check are what
4664
- * protect it. Exported for the test that pins that.
4665
- */
4666
- const FRONTMATTER_PARSE_OPTIONS = { engines: {
4667
- javascript: REFUSED_FRONTMATTER_ENGINE,
4668
- js: REFUSED_FRONTMATTER_ENGINE,
4669
- coffee: REFUSED_FRONTMATTER_ENGINE,
4670
- coffeescript: REFUSED_FRONTMATTER_ENGINE,
4671
- cson: REFUSED_FRONTMATTER_ENGINE
4672
- } };
4626
+ const yaml = (avoidBlockScalars ? dump(cleanFrontmatter, { lineWidth: -1 }) : dump$1(cleanFrontmatter)).trim();
4627
+ return (yaml === "{}" ? "" : `---\n${yaml}\n---\n`) + withTrailingNewline(body);
4628
+ }
4629
+ function withTrailingNewline(text) {
4630
+ return text.endsWith("\n") ? text : `${text}\n`;
4631
+ }
4673
4632
  /** Frontmatter languages accepted after the opening `---` fence. */
4674
4633
  const ALLOWED_FRONTMATTER_LANGUAGE_PATTERN = /^(?:ya?ml)?$/i;
4675
4634
  /**
4676
- * Read the opening frontmatter fence the way gray-matter does, or return
4677
- * `undefined` when gray-matter would see no frontmatter at all.
4635
+ * Read the opening frontmatter fence, or return `undefined` when the content
4636
+ * carries no frontmatter at all.
4678
4637
  *
4679
- * gray-matter strips one byte order mark, treats `---` as a fence only when a
4680
- * fourth `-` does not follow, and takes the language from the text between the
4681
- * fence and the first `\r?\n`, trimmed — dropping the last character when
4682
- * there is no line break at all. Every check below that has to agree with
4683
- * gray-matter on where the block is (the language check, the size guard, the
4684
- * repair pass) goes through this one reading, so none of them can be bypassed
4685
- * by a fence line gray-matter accepts and a stricter pattern would not (a
4686
- * stray `\r` before the line break, say).
4638
+ * The grammar is gray-matter's, which rulesync used to depend on, kept so that
4639
+ * every file reads the same as before: one byte order mark is skipped, `---`
4640
+ * is a fence only when a fourth `-` does not follow, and the language is the
4641
+ * text between the fence and the first `\r?\n`, trimmed — dropping the last
4642
+ * character when there is no line break at all. Every check that has to agree
4643
+ * with {@link splitFrontmatter} on where the block is (the language check and
4644
+ * the repair pass) goes through this one reading, so none of them
4645
+ * can be bypassed by a fence line the splitter accepts and a stricter pattern
4646
+ * would not (a stray `\r` before the line break, say).
4687
4647
  */
4688
4648
  function readFrontmatterFence(content) {
4689
4649
  const offset = content.startsWith("") ? 1 : 0;
@@ -4702,26 +4662,60 @@ function readFrontmatterFence(content) {
4702
4662
  /**
4703
4663
  * Refuse a frontmatter fence that names any language other than YAML.
4704
4664
  *
4705
- * Only YAML is ever written by rulesync or by the tools it targets, so anything
4706
- * else — `---js` above all, whose block gray-matter would `eval()` — is
4707
- * rejected before gray-matter sees the content.
4665
+ * Only YAML is ever written by rulesync or by the tools it targets. Generic
4666
+ * frontmatter libraries pick a parser from the fence language, and some hand a
4667
+ * `---js` block to `eval()`; rulesync parses everything as YAML, and refusing
4668
+ * any other language keeps a file meant for such a parser from being read as
4669
+ * something it is not.
4708
4670
  */
4709
4671
  function assertYamlFrontmatterLanguage(content) {
4710
4672
  const fence = readFrontmatterFence(content);
4711
4673
  if (fence && !ALLOWED_FRONTMATTER_LANGUAGE_PATTERN.test(fence.language)) throw new Error(`Unsupported frontmatter language ${JSON.stringify(fence.language.slice(0, 40))}; only YAML frontmatter is supported`);
4712
4674
  }
4713
4675
  /**
4714
- * The number of characters gray-matter would hand to the YAML parser as the
4715
- * frontmatter block. Unlike {@link findFrontmatterBlockBounds}, a missing
4716
- * closing fence does not make this zero: gray-matter then parses everything
4717
- * after the fence line, so that is what the size guard has to measure.
4676
+ * Split `content` into its raw frontmatter block and its body, the way
4677
+ * gray-matter 4 did (see {@link readFrontmatterFence}).
4678
+ *
4679
+ * The block ends at the first `\n---`, with no requirement that the delimiter
4680
+ * be alone on its line, and one line break after it is dropped from the body.
4681
+ * A fence nothing closes makes the rest of the file the block and leaves the
4682
+ * body empty. Without a fence, `block` is `""` and the body is the content
4683
+ * minus a leading byte order mark.
4718
4684
  */
4719
- function measureFrontmatterBlockChars(content) {
4720
- const fence = readFrontmatterFence(content);
4721
- if (fence?.lineBreakStart === void 0) return 0;
4722
- const rest = content.slice(fence.lineBreakStart);
4685
+ function splitFrontmatter(content) {
4686
+ const text = content.startsWith("") ? content.slice(1) : content;
4687
+ if (!text.startsWith("---") || text.charAt(3) === "-") return {
4688
+ block: "",
4689
+ body: text
4690
+ };
4691
+ let rest = text.slice(3);
4692
+ const rawLanguage = rest.slice(0, rest.search(/\r?\n/));
4693
+ if (rawLanguage.trim() !== "") rest = rest.slice(rawLanguage.length);
4723
4694
  const closeIndex = rest.indexOf("\n---");
4724
- return closeIndex === -1 ? rest.length : closeIndex;
4695
+ if (closeIndex === -1) return {
4696
+ block: rest,
4697
+ body: ""
4698
+ };
4699
+ let body = rest.slice(closeIndex + 4);
4700
+ if (body.startsWith("\r")) body = body.slice(1);
4701
+ if (body.startsWith("\n")) body = body.slice(1);
4702
+ return {
4703
+ block: rest.slice(0, closeIndex),
4704
+ body
4705
+ };
4706
+ }
4707
+ /**
4708
+ * Whether a raw block holds nothing but blank and comment lines. Checked line
4709
+ * by line rather than with gray-matter's `/^\s*#[^\n]+/gm`, whose `\s*` also
4710
+ * spans line breaks and backtracks quadratically on a long run of blank lines.
4711
+ * The one known difference: a lone `\r` now ends a comment line, as it does
4712
+ * in YAML, where the old pattern let the comment run on past it.
4713
+ */
4714
+ function isBlankFrontmatterBlock(block) {
4715
+ return block.split(/\r\n|\r|\n/).every((line) => {
4716
+ const trimmed = line.trim();
4717
+ return trimmed === "" || trimmed.startsWith("#");
4718
+ });
4725
4719
  }
4726
4720
  function parseFrontmatter(content, filePath) {
4727
4721
  let frontmatter;
@@ -4729,11 +4723,11 @@ function parseFrontmatter(content, filePath) {
4729
4723
  let hasFrontmatter;
4730
4724
  try {
4731
4725
  assertYamlFrontmatterLanguage(content);
4732
- if (measureFrontmatterBlockChars(content) > 65536) throw new Error(`Frontmatter block is larger than ${MAX_FRONTMATTER_RAW_CHARS} characters; refusing to parse it (a complex YAML key can cost memory while parsing, before any post-parse budget applies)`);
4733
- const result = matter(content, FRONTMATTER_PARSE_OPTIONS);
4734
- frontmatter = deepRemoveNullishObject(result.data);
4735
- body = result.content;
4736
- hasFrontmatter = result.matter !== "" || content.trimStart().startsWith("---");
4726
+ const split = splitFrontmatter(content);
4727
+ if (split.block.length > 65536) throw new Error(`Frontmatter block is larger than ${MAX_FRONTMATTER_RAW_CHARS} characters; refusing to parse it (a complex YAML key can cost memory while parsing, before any post-parse budget applies)`);
4728
+ frontmatter = deepRemoveNullishObject(isBlankFrontmatterBlock(split.block) ? {} : load$1(split.block));
4729
+ body = split.body;
4730
+ hasFrontmatter = content === "" || split.block !== "" || content.trimStart().startsWith("---");
4737
4731
  } catch (error) {
4738
4732
  if (filePath) throw new Error(`Failed to parse frontmatter in ${filePath}: ${formatError(error)}`, { cause: error });
4739
4733
  throw error;
@@ -4790,11 +4784,11 @@ function repairFrontmatterLine(line) {
4790
4784
  /**
4791
4785
  * Locate a raw `---`-delimited frontmatter block's bounds within `content`,
4792
4786
  * without parsing it, for the YAML repair pass below and the rule loaders that
4793
- * pre-process `globs:`. The opening fence is read exactly as gray-matter reads
4787
+ * pre-process `globs:`. The opening fence is read exactly as the splitter reads
4794
4788
  * it ({@link readFrontmatterFence}); an explicit `yaml` / `yml` language is
4795
- * still YAML, any other language yields no bounds. gray-matter ends the block
4789
+ * still YAML, any other language yields no bounds. The splitter ends the block
4796
4790
  * at the first `\n---`, with no requirement that the delimiter be alone on its
4797
- * line, so a stricter pattern here would run past gray-matter's delimiter and
4791
+ * line, so a stricter pattern here would run past the splitter's delimiter and
4798
4792
  * act on text that is really the body. A block with no closing fence has no
4799
4793
  * bounds; the size guard measures that case separately.
4800
4794
  */
@@ -5570,20 +5564,57 @@ const CANONICAL_TO_BOB_EVENT_NAMES = {
5570
5564
  stop: "Stop"
5571
5565
  };
5572
5566
  /**
5573
- * Hook events supported by IBM Bob's lifecycle hooks.
5567
+ * Hook events rulesync emits for IBM Bob from the shared `hooks` block.
5574
5568
  *
5575
5569
  * Bob reads `hooks` from `.bob/settings.json` (project) and
5576
5570
  * `~/.bob/settings/settings.json` (user) in the Claude-Code shape and fires
5577
- * seven events: SessionStart, UserPromptSubmit, PreToolUse, PostToolUse,
5578
- * PreCompact, PostCompact and Stop (Bob IDE and Bob Shell list the same
5579
- * seven). Handlers are `command` or `http` hooks. `matcher` is a regex matched
5580
- * against the tool name on PreToolUse / PostToolUse, `source` on SessionStart
5581
- * and `trigger` on PreCompact / PostCompact; the other events ignore it.
5571
+ * seven documented events: SessionStart, UserPromptSubmit, PreToolUse,
5572
+ * PostToolUse, PreCompact, PostCompact and Stop (Bob IDE and Bob Shell list
5573
+ * the same seven). Handlers are `command` or `http` hooks. Bob Shell 2.1.0
5574
+ * adds more events; see {@link BOB_OPT_IN_HOOK_EVENTS} for why they are not
5575
+ * emitted from the shared block.
5582
5576
  *
5583
5577
  * @see https://bob.ibm.com/docs/shell/configuration/lifecycle-hooks
5584
5578
  * @see https://bob.ibm.com/docs/ide/configuration/lifecycle-hooks
5585
5579
  */
5586
5580
  const BOB_HOOK_EVENTS = eventsOf(CANONICAL_TO_BOB_EVENT_NAMES);
5581
+ /**
5582
+ * The {@link BOB_HOOK_EVENTS} whose `matcher` regex Bob applies: the tool name
5583
+ * on PreToolUse / PostToolUse, `source` on SessionStart and `trigger` on
5584
+ * PreCompact / PostCompact. UserPromptSubmit and Stop have no matchable value.
5585
+ */
5586
+ const BOB_MATCHER_HOOK_EVENTS = BOB_HOOK_EVENTS.filter((event) => event !== "beforeSubmitPrompt" && event !== "stop");
5587
+ /**
5588
+ * Canonical events that Bob Shell 2.1.0 (`@ibm/bob` on npm, 2026-11-09) can
5589
+ * fire under the native name given here, next to the override-only
5590
+ * `PermissionResolved`. They are not on the lifecycle-hooks pages yet.
5591
+ *
5592
+ * They are deliberately not emitted from the shared `hooks` block: Bob Shell
5593
+ * before 2.1.0 validates the `hooks` object strictly against the seven
5594
+ * documented keys, and on any unknown key it ignores that settings file's
5595
+ * whole `hooks` block (PreToolUse guards included). Writing them must
5596
+ * therefore be an explicit opt-in under the `bob.hooks` override block, by
5597
+ * their native name, which is emitted verbatim and imported back there.
5598
+ *
5599
+ * @see https://registry.npmjs.org/@ibm/bob/-/bob-2.1.0.tgz
5600
+ */
5601
+ const BOB_OPT_IN_HOOK_EVENTS = {
5602
+ sessionEnd: "SessionEnd",
5603
+ permissionRequest: "PermissionRequest",
5604
+ notification: "Notification"
5605
+ };
5606
+ /**
5607
+ * Every native event key Bob Shell 2.1.0's strict hooks schema accepts: the
5608
+ * seven documented events, the three opt-in ones and `PermissionResolved`,
5609
+ * which has no canonical counterpart. Any other key under `bob.hooks` is
5610
+ * dropped on generate, because one unknown key makes Bob ignore the file's
5611
+ * whole hooks block.
5612
+ */
5613
+ const BOB_NATIVE_HOOK_EVENTS = [
5614
+ ...Object.values(CANONICAL_TO_BOB_EVENT_NAMES),
5615
+ ...Object.values(BOB_OPT_IN_HOOK_EVENTS),
5616
+ "PermissionResolved"
5617
+ ];
5587
5618
  const BOB_TO_CANONICAL_EVENT_NAMES = invertRecord(CANONICAL_TO_BOB_EVENT_NAMES);
5588
5619
  const CANONICAL_TO_TABNINE_EVENT_NAMES = {
5589
5620
  sessionStart: "SessionStart",
@@ -5866,17 +5897,18 @@ const CONTINUE_TO_CANONICAL_EVENT_NAMES = invertRecord(CANONICAL_TO_CONTINUE_EVE
5866
5897
  * observers, `gateway_platform_event` and `transform_api_error_classification`.
5867
5898
  * Shell hooks are gated on the same set.
5868
5899
  *
5869
- * Verified against the tag `v0.23.2`: `VALID_HOOKS` holds 48 entries, grown
5900
+ * Verified against the tag `v0.23.4`: `VALID_HOOKS` holds 50 entries, grown
5870
5901
  * from 23 at `v2026.8.3` (v0.20.0) and 37 at `v2026.8.16` (v0.20.2) — v0.21
5871
5902
  * added `agent_loop_stopped` and `on_room_member_activity`, v0.21.5 added
5872
5903
  * `pre_auxiliary_call` and `post_auxiliary_call`, v0.21.6 added
5873
5904
  * `post_gateway_admission`, `on_human_input_request` and
5874
5905
  * `on_human_input_resolved`, v0.22.3 added `on_session_delete` and
5875
- * `post_compaction`, and v0.23.1 added `on_session_open` and
5876
- * `post_curator_run`. This list holds 47 of them — see
5906
+ * `post_compaction`, v0.23.1 added `on_session_open` and
5907
+ * `post_curator_run`, and v0.23.4 added `on_session_prompt` and
5908
+ * `on_session_prompt_settled`. This list holds 49 of them — see
5877
5909
  * {@link HERMESAGENT_SHELL_UNSUPPORTED_HOOK_EVENTS} for the exclusion.
5878
5910
  *
5879
- * @see https://github.com/NousResearch/hermes-agent/blob/v0.23.2/hermes_cli/plugins.py
5911
+ * @see https://github.com/NousResearch/hermes-agent/blob/v0.23.4/hermes_cli/plugins.py
5880
5912
  */
5881
5913
  const HERMESAGENT_NATIVE_HOOK_EVENTS = [
5882
5914
  "pre_tool_call",
@@ -5902,6 +5934,8 @@ const HERMESAGENT_NATIVE_HOOK_EVENTS = [
5902
5934
  "on_session_reset",
5903
5935
  "on_session_delete",
5904
5936
  "on_session_open",
5937
+ "on_session_prompt",
5938
+ "on_session_prompt_settled",
5905
5939
  "on_skill_lifecycle",
5906
5940
  "subagent_start",
5907
5941
  "subagent_stop",
@@ -5937,8 +5971,8 @@ const HERMESAGENT_NATIVE_HOOK_EVENTS = [
5937
5971
  * rulesync only ever writes shell hooks, so these are excluded from
5938
5972
  * {@link HERMESAGENT_NATIVE_HOOK_EVENTS} and warned about with their own message.
5939
5973
  *
5940
- * @see https://github.com/NousResearch/hermes-agent/blob/v0.23.2/hermes_cli/plugins.py — `SHELL_UNSUPPORTED_HOOKS`
5941
- * @see https://github.com/NousResearch/hermes-agent/blob/v0.23.2/agent/shell_hooks.py — `_parse_hooks_block`
5974
+ * @see https://github.com/NousResearch/hermes-agent/blob/v0.23.4/hermes_cli/plugins.py — `SHELL_UNSUPPORTED_HOOKS`
5975
+ * @see https://github.com/NousResearch/hermes-agent/blob/v0.23.4/agent/shell_hooks.py — `_parse_hooks_block`
5942
5976
  */
5943
5977
  const HERMESAGENT_SHELL_UNSUPPORTED_HOOK_EVENTS = ["transform_api_error_classification"];
5944
5978
  /**
@@ -5958,8 +5992,8 @@ const CANONICAL_TO_HERMESAGENT_EVENT_NAMES = {
5958
5992
  /**
5959
5993
  * Hook events supported by Hermes Agent's native Shell Hooks system.
5960
5994
  *
5961
- * Hermes validates hook events against a fixed `VALID_HOOKS` set — 48 entries as
5962
- * of v0.23.2 (tag `v0.23.2`); see {@link HERMESAGENT_NATIVE_HOOK_EVENTS} for the
5995
+ * Hermes validates hook events against a fixed `VALID_HOOKS` set — 50 entries as
5996
+ * of v0.23.4 (tag `v0.23.4`); see {@link HERMESAGENT_NATIVE_HOOK_EVENTS} for the
5963
5997
  * full list. Only the events with a clean 1:1 canonical equivalent are mapped
5964
5998
  * here. All other native events round-trip through `hermesagent.hooks`.
5965
5999
  * @see https://github.com/NousResearch/hermes-agent/blob/main/website/docs/user-guide/features/hooks.md
@@ -9776,6 +9810,7 @@ const PermissionsConfigSchema = z.looseObject({
9776
9810
  commandcode: z.optional(CommandcodePermissionsOverrideSchema),
9777
9811
  lettacode: z.optional(CanonicalPermissionsOverrideSchema),
9778
9812
  crush: z.optional(CanonicalPermissionsOverrideSchema),
9813
+ gitlabduo: z.optional(CanonicalPermissionsOverrideSchema),
9779
9814
  goose: z.optional(CanonicalPermissionsOverrideSchema),
9780
9815
  omp: z.optional(OmpPermissionsOverrideSchema),
9781
9816
  pool: z.optional(CanonicalPermissionsOverrideSchema),
@@ -12709,6 +12744,37 @@ function serialize(value) {
12709
12744
  function stripStrings(_key, value) {
12710
12745
  return typeof value === "string" ? stripControlCharacters(value) : value;
12711
12746
  }
12747
+ // src/utils/yaml.ts
12748
+ /**
12749
+ * js-yaml v5's `reason` for an empty document. `load("")` — and any
12750
+ * whitespace/comment-only input — throws a `YAMLException` with this reason
12751
+ * instead of returning `undefined` the way v4 did.
12752
+ */
12753
+ const EMPTY_INPUT_REASON = "expected a document, but the input is empty";
12754
+ /**
12755
+ * Load YAML content while preserving js-yaml v4's behavior of returning
12756
+ * `undefined` for empty documents (empty, whitespace-only, or comment-only
12757
+ * input).
12758
+ *
12759
+ * js-yaml v5 changed `load("")` to **throw** ("expected a document, but the
12760
+ * input is empty") instead of returning `undefined`. Many call sites here parse
12761
+ * config/lock/frontmatter files that can legitimately be empty and rely on the
12762
+ * old `undefined` sentinel (`load(input) ?? {}`, `if (loaded === undefined)`,
12763
+ * "an empty file parses to undefined/null"). Routing every load through this
12764
+ * wrapper keeps that contract in one place so a future js-yaml bump cannot
12765
+ * reintroduce the empty-input regression. Genuine parse errors still propagate.
12766
+ *
12767
+ * @see https://github.com/nodeca/js-yaml/blob/master/docs/migrate_v4_to_v5.md#empty-input-throws
12768
+ */
12769
+ function loadYaml(content, options) {
12770
+ if (content.trim() === "") return;
12771
+ try {
12772
+ return load(content, options);
12773
+ } catch (error) {
12774
+ if (error instanceof YAMLException && error.reason === EMPTY_INPUT_REASON) return;
12775
+ throw error;
12776
+ }
12777
+ }
12712
12778
  // src/features/shared/jsonc-object-edit.ts
12713
12779
  /**
12714
12780
  * In-place editing of a JSONC object's text: the engine behind the shared
@@ -14719,7 +14785,7 @@ function tryParseStructured({ filePath, content }) {
14719
14785
  }
14720
14786
  }
14721
14787
  /**
14722
- * gray-matter often includes extra newlines right after the closing ---; strip those so the
14788
+ * The parsed body often starts with extra newlines right after the closing ---; strip those so the
14723
14789
  * body matches across generators vs on-disk formatters. Trailing whitespace is normalized via
14724
14790
  * addTrailingNewline (trimEnd + single newline), same as writes.
14725
14791
  */
@@ -14810,7 +14876,7 @@ function fileContentIsEmptyPayload({ filePath, content }) {
14810
14876
  * Whether on-disk content is equivalent to generated content for --check / dry-run.
14811
14877
  *
14812
14878
  * Uses structured comparison for JSON/JSONC (via jsonc-parser), YAML, TOML, and Markdown-like
14813
- * frontmatter files (.md, .mdc — same gray-matter path as elsewhere).
14879
+ * frontmatter files (.md, .mdc — same frontmatter parser as elsewhere).
14814
14880
  */
14815
14881
  function fileContentsEquivalent({ filePath, expected, existing }) {
14816
14882
  if (existing === null) return false;
@@ -14992,6 +15058,11 @@ var FeatureProcessor = class extends RulesyncSourceConsumer {
14992
15058
  if (fileMode !== void 0 && !this.dryRun) await restoreMissingExecutableBit(filePath, fileMode);
14993
15059
  continue;
14994
15060
  }
15061
+ await warnIfWriteFollowsLink({
15062
+ logger: this.logger,
15063
+ rootPath: aiFile.getOutputRoot(),
15064
+ targetPath: filePath
15065
+ });
14995
15066
  if (this.dryRun) this.logger.info(`[DRY RUN] Would write: ${stripControlCharacters(filePath)}`);
14996
15067
  else {
14997
15068
  await writeFileContent(filePath, contentWithNewline);
@@ -15176,6 +15247,37 @@ async function refusesWriteOutsideRoot({ logger, rootPath, targetPath }) {
15176
15247
  return true;
15177
15248
  }
15178
15249
  /**
15250
+ * Warn, once per run and link, that a write to `targetPath` goes through a
15251
+ * symbolic link below `rootPath`: the warning names the link and the real path
15252
+ * it leads to, so the file the write really changes is visible.
15253
+ *
15254
+ * Links that lead out of the root (or into version-control metadata) are
15255
+ * refused by {@link refusesWriteOutsideRoot} before this is asked; an in-root
15256
+ * link is written through on purpose (dotfiles setups rely on it), but a
15257
+ * committed `AGENTS.md -> .claude/CLAUDE.md` would otherwise have one target
15258
+ * silently replace another target's file. Writers call this only for a file
15259
+ * they are about to change (or, in a dry run, would change), so an unchanged
15260
+ * file reached through a link stays quiet. The warning is keyed on the first
15261
+ * link on the path rather than on the file, so a linked directory such as
15262
+ * `~/.claude -> ~/dotfiles/.claude` is reported once however many files below
15263
+ * it a run writes.
15264
+ */
15265
+ async function warnIfWriteFollowsLink({ logger, rootPath, targetPath }) {
15266
+ const linkPath = await firstLinkBelowRoot({
15267
+ rootPath,
15268
+ targetPath
15269
+ });
15270
+ if (linkPath === null) return;
15271
+ const linkLanding = await writeLandingPath(linkPath);
15272
+ if (linkLanding === null) return;
15273
+ warnOnceWithFallback(logger, `${quoteForLog(linkPath)} is a symbolic link to ${quoteForLog(linkLanding)}; files rulesync writes through it land there`);
15274
+ const restOfPath = relative(linkPath, resolve(targetPath));
15275
+ if (restOfPath === "") return;
15276
+ const targetLanding = await writeLandingPath(targetPath);
15277
+ if (targetLanding === null || targetLanding === join(linkLanding, restOfPath)) return;
15278
+ warnOnceWithFallback(logger, `${quoteForLog(targetPath)} is reached through further symbolic links; rulesync writes it to ${quoteForLog(targetLanding)}`);
15279
+ }
15280
+ /**
15179
15281
  * Why the orphan sweep has to leave the files in `dirPath` alone, or `null`
15180
15282
  * when it may delete them.
15181
15283
  *
@@ -18218,6 +18320,14 @@ const GITLABDUO_DIR = join(".gitlab", "duo");
18218
18320
  const GITLABDUO_RULE_FILE_NAME = "chat-rules.md";
18219
18321
  /** MCP servers. @see https://docs.gitlab.com/user/gitlab_duo/model_context_protocol/mcp_clients/ */
18220
18322
  const GITLABDUO_MCP_FILE_NAME = "mcp.json";
18323
+ /**
18324
+ * Settings. Only the user file `~/.gitlab/duo/settings.json` carries the
18325
+ * `permissions` setting rulesync writes; the project files are deliberately not
18326
+ * read for it.
18327
+ *
18328
+ * @see https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/blob/v10.5.0/packages/core/settings/src/definitions.ts
18329
+ */
18330
+ const GITLABDUO_SETTINGS_FILE_NAME = "settings.json";
18221
18331
  /** Lifecycle hooks (experiment). @see https://docs.gitlab.com/user/gitlab_duo_cli/customize/ */
18222
18332
  const GITLABDUO_HOOKS_FILE_NAME = "hooks.json";
18223
18333
  /** Merge request review instructions. @see https://docs.gitlab.com/user/project/merge_requests/duo_in_merge_requests/ */
@@ -18510,6 +18620,11 @@ var GooseCommand = class GooseCommand extends ToolCommand {
18510
18620
  entries: []
18511
18621
  });
18512
18622
  if (nextContent === currentContent) return 0;
18623
+ await warnIfWriteFollowsLink({
18624
+ logger,
18625
+ rootPath: outputRoot,
18626
+ targetPath: configPath
18627
+ });
18513
18628
  if (dryRun) logger.info(`[DRY RUN] Would write: ${configPath}`);
18514
18629
  else await writeFileContent(configPath, nextContent);
18515
18630
  return 1;
@@ -19692,6 +19807,11 @@ var HermesagentCommand = class HermesagentCommand extends ToolCommand {
19692
19807
  global
19693
19808
  });
19694
19809
  if (nextContent === currentContent) return 0;
19810
+ await warnIfWriteFollowsLink({
19811
+ logger,
19812
+ rootPath: outputRoot,
19813
+ targetPath: configPath
19814
+ });
19695
19815
  if (dryRun) logger.info(`[DRY RUN] Would write: ${configPath}`);
19696
19816
  else await writeFileContent(configPath, nextContent);
19697
19817
  return 1;
@@ -23308,6 +23428,17 @@ var DirFeatureProcessor = class extends RulesyncSourceConsumer {
23308
23428
  });
23309
23429
  }
23310
23430
  /**
23431
+ * Warn about each file of `aiDir` about to be written through a symbolic link
23432
+ * that stays inside the output root (see {@link warnIfWriteFollowsLink}).
23433
+ */
23434
+ async warnIfFilesFollowLinks({ aiDir, filePaths }) {
23435
+ for (const targetPath of filePaths) await warnIfWriteFollowsLink({
23436
+ logger: this.logger,
23437
+ rootPath: aiDir.getOutputRoot(),
23438
+ targetPath
23439
+ });
23440
+ }
23441
+ /**
23311
23442
  * Once converted to rulesync/tool dirs, write them to the filesystem.
23312
23443
  * Returns the number of directories written.
23313
23444
  *
@@ -23360,6 +23491,10 @@ var DirFeatureProcessor = class extends RulesyncSourceConsumer {
23360
23491
  }
23361
23492
  continue;
23362
23493
  }
23494
+ await this.warnIfFilesFollowLinks({
23495
+ aiDir,
23496
+ filePaths: writtenPaths.slice(1)
23497
+ });
23363
23498
  const relativeDir = aiDir.getRelativePathFromCwd();
23364
23499
  if (this.dryRun) {
23365
23500
  this.logger.info(`[DRY RUN] Would create directory: ${stripControlCharacters(dirPath)}`);
@@ -34547,6 +34682,24 @@ function isMissingDescription(value) {
34547
34682
  function nameFromFileName(relativeFilePath) {
34548
34683
  return relativeFilePath.replace(/(\.agent)?\.md$/, "");
34549
34684
  }
34685
+ /**
34686
+ * Normalizes a subagent name the way Junie does: the result is what Junie
34687
+ * accepts for `--agent` and must match `[a-z0-9][a-z0-9_-]*`.
34688
+ *
34689
+ * - Surrounding whitespace is trimmed first, so a quoted `" Code Reviewer "`
34690
+ * (or a file named ` Reviewer.md`) does not start or end with a hyphen,
34691
+ * which the leading-character rule would reject.
34692
+ * - Uppercase letters are lowercased.
34693
+ * - Each run of whitespace (spaces, tabs, ...) becomes a single hyphen. The
34694
+ * upstream docs only say Junie "replaces spaces with hyphens"; collapsing
34695
+ * runs gives `code-reviewer` for `Code Reviewer`, which is the name a user
34696
+ * would expect and still matches the pattern, instead of `code--reviewer`.
34697
+ *
34698
+ * @see https://junie.jetbrains.com/docs/junie-cli-subagents.html
34699
+ */
34700
+ function normalizeJunieName(name) {
34701
+ return name.trim().toLowerCase().replace(/\s+/g, "-");
34702
+ }
34550
34703
  var JunieSubagent = class JunieSubagent extends ToolSubagent {
34551
34704
  frontmatter;
34552
34705
  body;
@@ -34571,14 +34724,30 @@ var JunieSubagent = class JunieSubagent extends ToolSubagent {
34571
34724
  getBody() {
34572
34725
  return this.body;
34573
34726
  }
34727
+ /**
34728
+ * The name Junie resolves after normalization, so `Code Reviewer.md` and
34729
+ * `code-reviewer.md` (both `code-reviewer`) are reported as duplicates on
34730
+ * import instead of becoming two rulesync subagents with the same name.
34731
+ */
34732
+ getImportIdentity() {
34733
+ return this.getNormalizedName();
34734
+ }
34735
+ /**
34736
+ * An empty or whitespace-only `name` would normalize to `""`, which is not a
34737
+ * valid Junie name and would make every such file share one import identity,
34738
+ * so it falls back to the file name just like a missing `name` does.
34739
+ */
34740
+ getNormalizedName() {
34741
+ return (this.frontmatter.name === void 0 ? "" : normalizeJunieName(this.frontmatter.name)) || normalizeJunieName(nameFromFileName(this.getRelativeFilePath()));
34742
+ }
34574
34743
  toRulesyncSubagent() {
34575
- const { name, description, ...restFields } = this.frontmatter;
34744
+ const { name: _name, description, ...restFields } = this.frontmatter;
34576
34745
  const junieSection = { ...restFields };
34577
34746
  return new RulesyncSubagent({
34578
34747
  outputRoot: ".",
34579
34748
  frontmatter: {
34580
34749
  targets: ["*"],
34581
- name: name ?? nameFromFileName(this.getRelativeFilePath()),
34750
+ name: this.getNormalizedName(),
34582
34751
  ...description !== void 0 && { description },
34583
34752
  ...Object.keys(junieSection).length > 0 && { junie: junieSection }
34584
34753
  },
@@ -36949,8 +37118,208 @@ const VIBE_PROMPTS_DIR_PATH = join(".vibe", "prompts");
36949
37118
  * @see https://github.com/mistralai/mistral-vibe/blob/v3.0.3/vibe/core/agents/models.py
36950
37119
  */
36951
37120
  const VIBE_RESERVED_AGENT_NAME = "main";
37121
+ /**
37122
+ * The approval policies Vibe ships since v3.1.4. `AgentRegistry._discover`
37123
+ * never loads an agents-directory file named after one as an agent, whatever
37124
+ * its `agent_type`: from a project's `.vibe/agents/` the file is ignored with
37125
+ * an `approval_policy.project_override_ignored` config issue, and from
37126
+ * `~/.vibe/agents/` it redefines that approval policy for every session. Vibe
37127
+ * compares the file stem exactly (`agent.name in BUILTIN_APPROVAL_POLICIES`).
37128
+ * @see https://github.com/mistralai/mistral-vibe/blob/v3.1.5/vibe/core/agents/registry.py
37129
+ * @see https://github.com/mistralai/mistral-vibe/blob/v3.1.5/vibe/core/agents/models.py
37130
+ */
37131
+ const VIBE_APPROVAL_POLICY_NAMES = /* @__PURE__ */ new Set([
37132
+ "ask",
37133
+ "accept-edits",
37134
+ "smart-approve",
37135
+ "auto-approve"
37136
+ ]);
37137
+ function vibeAgentFileStem(relativeFilePath) {
37138
+ return basename(relativeFilePath).replace(/\.(md|toml)$/, "");
37139
+ }
36952
37140
  function isReservedVibeAgentFileName(relativeFilePath) {
36953
- return basename(relativeFilePath).replace(/\.(md|toml)$/, "").toLowerCase() === VIBE_RESERVED_AGENT_NAME;
37141
+ return vibeAgentFileStem(relativeFilePath).toLowerCase() === VIBE_RESERVED_AGENT_NAME;
37142
+ }
37143
+ function isVibeApprovalPolicyFileName(relativeFilePath) {
37144
+ return VIBE_APPROVAL_POLICY_NAMES.has(vibeAgentFileStem(relativeFilePath));
37145
+ }
37146
+ /**
37147
+ * The keys Vibe ignores on a custom `agent_type = "agent"` profile since
37148
+ * v3.1.4, listing each as a config issue: `_agent_settings` drops every
37149
+ * `VibeConfigSchema` field outside its `_AGENT_KEYS`, plus `safety` and
37150
+ * `approval_policy`, because what runs without asking belongs to the approval
37151
+ * policy, not to the agent. A key outside this list is kept, as Vibe keeps it:
37152
+ * an agent key passes, and an unknown key (a typo such as `disabled_tool`)
37153
+ * stays so Vibe can report it — or refuse it under `strict_config`.
37154
+ * Generated from the `VibeConfigSchema` fields of v3.1.5 minus `_AGENT_KEYS`.
37155
+ * @see https://github.com/mistralai/mistral-vibe/blob/v3.1.5/vibe/core/agents/models.py
37156
+ * @see https://github.com/mistralai/mistral-vibe/blob/v3.1.5/vibe/core/config/vibe_schema.py
37157
+ */
37158
+ const VIBE_AGENT_IGNORED_KEYS = /* @__PURE__ */ new Set([
37159
+ "safety",
37160
+ "approval_policy",
37161
+ "catalog_model_aliases",
37162
+ "catalog_recommended_model",
37163
+ "catalog_default_model",
37164
+ "utility_models",
37165
+ "active_transcribe_model",
37166
+ "transcribe_providers",
37167
+ "transcribe_models",
37168
+ "active_tts_model",
37169
+ "tts_providers",
37170
+ "tts_models",
37171
+ "outside_workdir",
37172
+ "mcp_servers",
37173
+ "enable_connectors",
37174
+ "enable_mcp",
37175
+ "experimental_enable_document_library_connector",
37176
+ "experimental_enable_mistral_mcp_connector",
37177
+ "connectors",
37178
+ "agent_paths",
37179
+ "enabled_agents",
37180
+ "disabled_agents",
37181
+ "installed_agents",
37182
+ "default_agent",
37183
+ "default_approval_policy",
37184
+ "vibe_bot_max_approval_policy",
37185
+ "vibe_bot_local_tools",
37186
+ "vibe_bot_local_tool_max_bytes",
37187
+ "smart_approve_available",
37188
+ "enable_auto_approve",
37189
+ "enabled_plugins",
37190
+ "disabled_plugins",
37191
+ "experimental_enable_remote_plugins",
37192
+ "experimental_enable_registry_skills",
37193
+ "enable_model_catalog",
37194
+ "enable_builtin_models",
37195
+ "experimental_enable_storage_usage",
37196
+ "enable_pr_monitoring",
37197
+ "experimental_local_runtime_session_api",
37198
+ "experimental_target_runtime",
37199
+ "enable_otel",
37200
+ "otel_endpoint",
37201
+ "otel_redaction",
37202
+ "console_base_url",
37203
+ "theme",
37204
+ "applied_migrations",
37205
+ "disable_welcome_banner_animation",
37206
+ "disable_selection_animation",
37207
+ "cursor_blink",
37208
+ "vim_keybindings",
37209
+ "show_dangerous_directory_warning",
37210
+ "autocopy_to_clipboard",
37211
+ "enable_mouse_capture",
37212
+ "enable_sticky_prompt",
37213
+ "collapse_turn_details",
37214
+ "enable_file_autocomplete",
37215
+ "file_watcher_for_autocomplete",
37216
+ "ask_confirmation_on_exit",
37217
+ "displayed_workdir",
37218
+ "context_warnings",
37219
+ "voice_mode_enabled",
37220
+ "narrator_enabled",
37221
+ "show_thinking_nodes",
37222
+ "show_subagent_status_list",
37223
+ "worktree_limit",
37224
+ "auto_worktree",
37225
+ "worktree_copy_on_write",
37226
+ "bypass_tool_permissions",
37227
+ "raise_on_compaction_failure",
37228
+ "enable_telemetry",
37229
+ "managed_shell_tools_enabled",
37230
+ "enable_background_processes",
37231
+ "enable_subagents",
37232
+ "max_subagents",
37233
+ "max_concurrent_subagents",
37234
+ "compaction_prompt_id",
37235
+ "title_prompt_id",
37236
+ "include_commit_signature",
37237
+ "include_model_info",
37238
+ "include_project_context",
37239
+ "include_prompt_detail",
37240
+ "strict_config",
37241
+ "enable_update_checks",
37242
+ "enable_auto_update",
37243
+ "enable_notifications",
37244
+ "keep_awake",
37245
+ "experimental_enable_tab_status",
37246
+ "enable_system_trust_store",
37247
+ "api_timeout",
37248
+ "api_retry_max_elapsed_time",
37249
+ "max_goal_token_budget",
37250
+ "api_stream_idle_timeout",
37251
+ "agent_max_output_tokens",
37252
+ "compaction_max_output_tokens",
37253
+ "compaction_reasoning_limit_tokens",
37254
+ "output_limit_retries",
37255
+ "api_connect_timeout",
37256
+ "api_write_timeout",
37257
+ "api_pool_timeout",
37258
+ "vibe_base_url",
37259
+ "vibe_code_sessions_base_url",
37260
+ "log_level",
37261
+ "project_context",
37262
+ "session_logging",
37263
+ "experiments"
37264
+ ]);
37265
+ /**
37266
+ * The legacy key Vibe folds into `disabled_tools` before it filters an agent
37267
+ * profile (`migrate_agent_profile_config`).
37268
+ * @see https://github.com/mistralai/mistral-vibe/blob/v3.1.5/vibe/core/agents/_migration.py
37269
+ */
37270
+ const VIBE_LEGACY_BASE_DISABLED_KEY = "base_disabled";
37271
+ /** Per tool, an agent keeps only the shell timeouts and a narrowing `permission`. */
37272
+ const VIBE_AGENT_TOOL_KEYS = /* @__PURE__ */ new Set(["default_timeout", "max_timeout_seconds"]);
37273
+ const VIBE_AGENT_NARROWING_PERMISSIONS = /* @__PURE__ */ new Set(["ask", "never"]);
37274
+ /**
37275
+ * Fold a legacy `base_disabled` list into `disabled_tools` the way Vibe's
37276
+ * `migrate_agent_profile_config` does, so the restriction it carries is kept.
37277
+ */
37278
+ function migrateVibeBaseDisabled(tomlObj) {
37279
+ const legacyDisabled = tomlObj[VIBE_LEGACY_BASE_DISABLED_KEY];
37280
+ if (!Array.isArray(legacyDisabled)) return tomlObj;
37281
+ const rest = Object.fromEntries(Object.entries(tomlObj).filter(([key]) => key !== VIBE_LEGACY_BASE_DISABLED_KEY));
37282
+ const disabledTools = rest.disabled_tools;
37283
+ return {
37284
+ ...rest,
37285
+ disabled_tools: Array.isArray(disabledTools) ? [.../* @__PURE__ */ new Set([...disabledTools, ...legacyDisabled])] : legacyDisabled
37286
+ };
37287
+ }
37288
+ /**
37289
+ * Drop the settings Vibe ignores on an `agent_type = "agent"` profile, so the
37290
+ * generated file does not pretend to grant what Vibe refuses. Mirrors Vibe's
37291
+ * `_agent_settings`; returns the kept TOML object and the dotted keys that
37292
+ * were dropped.
37293
+ */
37294
+ function stripVibeAgentIgnoredSettings(tomlObj) {
37295
+ const kept = {};
37296
+ const dropped = [];
37297
+ for (const [key, value] of Object.entries(migrateVibeBaseDisabled(tomlObj))) {
37298
+ if (VIBE_AGENT_IGNORED_KEYS.has(key)) {
37299
+ dropped.push(key);
37300
+ continue;
37301
+ }
37302
+ if (key !== "tools" || typeof value !== "object" || value === null || Array.isArray(value)) {
37303
+ kept[key] = value;
37304
+ continue;
37305
+ }
37306
+ const tools = {};
37307
+ for (const [tool, settings] of Object.entries(value)) {
37308
+ if (typeof settings !== "object" || settings === null || Array.isArray(settings)) {
37309
+ dropped.push(`tools.${tool}`);
37310
+ continue;
37311
+ }
37312
+ const own = {};
37313
+ for (const [setting, settingValue] of Object.entries(settings)) if (VIBE_AGENT_TOOL_KEYS.has(setting) || setting === "permission" && VIBE_AGENT_NARROWING_PERMISSIONS.has(settingValue)) own[setting] = settingValue;
37314
+ else dropped.push(`tools.${tool}.${setting}`);
37315
+ if (Object.keys(own).length > 0) tools[tool] = own;
37316
+ }
37317
+ if (Object.keys(tools).length > 0) kept.tools = tools;
37318
+ }
37319
+ return {
37320
+ kept,
37321
+ dropped: dropped.toSorted()
37322
+ };
36954
37323
  }
36955
37324
  /**
36956
37325
  * Vibe resolves a `system_prompt_id` by file name, and
@@ -37030,7 +37399,7 @@ var VibeSubagent = class VibeSubagent extends ToolSubagent {
37030
37399
  validate: true
37031
37400
  });
37032
37401
  }
37033
- static fromRulesyncSubagent({ outputRoot = process.cwd(), rulesyncSubagent, validate = true, global = false }) {
37402
+ static fromRulesyncSubagent({ outputRoot = process.cwd(), rulesyncSubagent, validate = true, global = false, logger }) {
37034
37403
  const frontmatter = rulesyncSubagent.getFrontmatter();
37035
37404
  const rawSection = frontmatter.vibe ?? {};
37036
37405
  const vibeSection = this.filterToolSpecificSection(rawSection, [
@@ -37048,7 +37417,13 @@ var VibeSubagent = class VibeSubagent extends ToolSubagent {
37048
37417
  ...vibeSection,
37049
37418
  ...promptBody ? { system_prompt_id: slug } : {}
37050
37419
  };
37051
- const body = smolToml.stringify(tomlObj);
37420
+ let finalToml = tomlObj;
37421
+ if (tomlObj.agent_type === "agent") {
37422
+ const { kept, dropped } = stripVibeAgentIgnoredSettings(tomlObj);
37423
+ if (dropped.length > 0) logger?.warn(`Vibe subagent ${rulesyncSubagent.getRelativeFilePath()}: dropped ${dropped.map((key) => `'${key}'`).join(", ")}, which Vibe v3.1.4+ ignores on an agent_type = "agent" profile and reports as a config issue. What runs without asking belongs to the approval policy: set default_approval_policy and [tools.*] in config.toml, or use agent_type = "subagent".`);
37424
+ finalToml = kept;
37425
+ }
37426
+ const body = smolToml.stringify(finalToml);
37052
37427
  const paths = this.getSettablePaths({ global });
37053
37428
  const relativeFilePath = rulesyncSubagent.getRelativeFilePath().replace(/\.md$/, ".toml");
37054
37429
  return new VibeSubagent({
@@ -37069,7 +37444,10 @@ var VibeSubagent = class VibeSubagent extends ToolSubagent {
37069
37444
  * with a warning.
37070
37445
  *
37071
37446
  * A subagent named `main` is skipped with a warning: Vibe reserves that name
37072
- * for hook matching and does not load an agent file called `main.toml`.
37447
+ * for hook matching and does not load an agent file called `main.toml`. So is
37448
+ * one named after an approval policy (`ask`, `accept-edits`, `smart-approve`,
37449
+ * `auto-approve`): Vibe ignores such a file in a project and treats it as a
37450
+ * redefinition of that policy in `~/.vibe/agents/`, never as an agent.
37073
37451
  */
37074
37452
  static fromRulesyncSubagents({ rulesyncSubagents, outputRoot = process.cwd(), global = false, logger }) {
37075
37453
  return rulesyncSubagents.flatMap((rulesyncSubagent) => {
@@ -37078,11 +37456,17 @@ var VibeSubagent = class VibeSubagent extends ToolSubagent {
37078
37456
  logger?.warn(`Skipping Vibe subagent ${sourcePath}: Vibe reserves the agent name '${VIBE_RESERVED_AGENT_NAME}' for hook matching and does not load an agent file named '${VIBE_RESERVED_AGENT_NAME}'. Rename the subagent file.`);
37079
37457
  return [];
37080
37458
  }
37459
+ if (isVibeApprovalPolicyFileName(sourcePath)) {
37460
+ const policy = vibeAgentFileStem(sourcePath);
37461
+ logger?.warn(`Skipping Vibe subagent ${sourcePath}: '${policy}' is a Vibe approval policy name (v3.1.4+), so Vibe never loads an agent file of that name — a project's .vibe/agents/ file is ignored and a ~/.vibe/agents/ file redefines the approval policy instead. Rename the subagent file.`);
37462
+ return [];
37463
+ }
37081
37464
  const agentFile = VibeSubagent.fromRulesyncSubagent({
37082
37465
  outputRoot,
37083
37466
  relativeDirPath: VibeSubagent.getSettablePaths({ global }).relativeDirPath,
37084
37467
  rulesyncSubagent,
37085
- global
37468
+ global,
37469
+ logger
37086
37470
  });
37087
37471
  const promptBody = rulesyncSubagent.getBody();
37088
37472
  if (!promptBody) return [agentFile];
@@ -37158,6 +37542,22 @@ var VibeSubagent = class VibeSubagent extends ToolSubagent {
37158
37542
  if (typeof promptId !== "string" || promptId === "" || /[\\/]/.test(promptId)) return;
37159
37543
  return await readFileContentOrNull(join(outputRoot, VIBE_PROMPTS_DIR_PATH, `${promptId}.md`)) ?? void 0;
37160
37544
  }
37545
+ /**
37546
+ * A file in `.vibe/agents/` named after an approval policy is not an agent:
37547
+ * in `~/.vibe/agents/` it is the user's override of that policy (often a
37548
+ * narrower one), and in a project Vibe ignores it. It is therefore neither
37549
+ * imported as a subagent (with a warning) nor swept as an orphan, since
37550
+ * deleting a narrowing override would fall back to the broader builtin.
37551
+ */
37552
+ static async isFileOwned({ relativeFilePath, forDeletion = false, logger }) {
37553
+ if (!isVibeApprovalPolicyFileName(relativeFilePath)) return true;
37554
+ if (!forDeletion) logger?.warn(`Skipping Vibe agent file ${relativeFilePath}: '${vibeAgentFileStem(relativeFilePath)}' is a Vibe approval policy name (v3.1.4+), so the file overrides that approval policy rather than defining an agent, and it is not imported as a subagent.`);
37555
+ return false;
37556
+ }
37557
+ /** Never delete an approval-policy override; see {@link VibeSubagent.isFileOwned}. */
37558
+ isDeletable() {
37559
+ return this.promptFile || !isVibeApprovalPolicyFileName(this.getRelativeFilePath());
37560
+ }
37161
37561
  static forDeletion({ outputRoot = process.cwd(), relativeDirPath, relativeFilePath, global = false }) {
37162
37562
  return new VibeSubagent({
37163
37563
  outputRoot,
@@ -38331,7 +38731,9 @@ var SubagentsProcessor = class extends FeatureProcessor {
38331
38731
  const ownership = await Promise.all(subagentFilePaths.map((path) => factory.class.isFileOwned({
38332
38732
  outputRoot: rootOutputRoot,
38333
38733
  relativeDirPath: dirPath,
38334
- relativeFilePath: toRelativeFilePath(path)
38734
+ relativeFilePath: toRelativeFilePath(path),
38735
+ forDeletion,
38736
+ logger: this.logger
38335
38737
  })));
38336
38738
  ownedFilePaths = subagentFilePaths.filter((_, index) => ownership[index]);
38337
38739
  }
@@ -46360,10 +46762,18 @@ var MimocodeRule = class extends OpenCodeRule {
46360
46762
  * from the working directory to the `.git` boundary and loads one instruction
46361
46763
  * file per directory level, preferring `AGENTS.md` over `CLAUDE.md` when both
46362
46764
  * exist. rulesync emits the project-root `AGENTS.md` (the same shared root file
46363
- * the agentsmd/codexcli targets write). Muse Code has user/global rules, but
46364
- * their path is not documented, so no global scope is supported here.
46365
- * (Verified against the official docs:
46366
- * https://dev.meta.ai/docs/muse-code/configuration.md)
46765
+ * the agentsmd/codexcli targets write). Muse Code also loads machine-wide user
46766
+ * rules; since 1.4.23 its changelog names `~/.claude/CLAUDE.md` as that file
46767
+ * (the filename of the alternative under Muse's own config directory is not
46768
+ * published). `~/.claude/CLAUDE.md` is exactly what the `claudecode` target
46769
+ * writes in global mode, so no global scope is supported here: emitting the
46770
+ * same file from two targets would make the result depend on target order.
46771
+ * `rulesync generate --targets claudecode --global` feeds Muse Code's user
46772
+ * rules instead, but only for the root rule (global non-root rules go to
46773
+ * `~/.claude/rules/*.md`, which Muse Code is not documented to read) and only
46774
+ * for rules that target `claudecode`. (Verified against the official docs:
46775
+ * https://dev.meta.ai/docs/muse-code/configuration and
46776
+ * https://dev.meta.ai/docs/muse-code/changelog)
46367
46777
  *
46368
46778
  * rulesync's topic-based non-root rules have no project subdirectory to map
46369
46779
  * onto, so their bodies are folded into the single root `AGENTS.md` by the
@@ -48358,8 +48768,8 @@ var TraeRule = class TraeRule extends ToolRule {
48358
48768
  * before parsing, inside the frontmatter block only so the body is never
48359
48769
  * rewritten. A quoted value, a YAML flow list, a null or boolean keyword and a
48360
48770
  * block scalar indicator (`|`, `>`) are left alone. The block bounds are
48361
- * gray-matter's own (it closes the block at the first `\n---`, even inside a
48362
- * `----` line), so the quoting never reaches text gray-matter reads as body.
48771
+ * `parseFrontmatter`'s own (it closes the block at the first `\n---`, even
48772
+ * inside a `----` line), so the quoting never reaches text it reads as body.
48363
48773
  */
48364
48774
  static parseTraeFrontmatter(fileContent, filePath) {
48365
48775
  const bounds = findFrontmatterBlockBounds(fileContent);
@@ -50778,9 +51188,10 @@ const AmpCheckFrontmatterSchema = z.looseObject({
50778
51188
  * Amp reads code review checks as Markdown files with YAML frontmatter,
50779
51189
  * scoped to the project (`.agents/checks/`) and user-wide (`~/.config/amp/checks/`;
50780
51190
  * Amp also reads `~/.config/agents/checks/`, which rulesync does not write).
50781
- * Since the docs rebuild the supported runner is the official
50782
- * `@amp/review-checks` plugin (`amp review` is deprecated); existing checks in
50783
- * this format continue to apply.
51191
+ * Amp has since removed `amp review` and deprecated project-defined checks
51192
+ * in `.agents/checks/`, together with the `@amp/review-checks` plugin that runs
51193
+ * them. rulesync keeps writing this format because Goose discovers the same
51194
+ * `.agents/checks/` directory and existing setups may still load the plugin.
50784
51195
  * @see https://ampcode.com/docs/review
50785
51196
  */
50786
51197
  var AmpCheck = class extends ToolCheck {
@@ -51664,19 +52075,17 @@ var CursorCheck = class extends AggregatedToolCheck {
51664
52075
  *
51665
52076
  * rulesync never writes frontmatter here, but a user who authored this path as
51666
52077
  * an ordinary skill did, and that block is the skill's metadata rather than
51667
- * review instructions. Writing the check back out hands the body to
51668
- * gray-matter's `stringify`, which re-parses whatever leads it and *merges*
51669
- * those keys into the frontmatter it is given — so a `severity: bogus` copied
51670
- * out of a skill would fail `.rulesync/checks/` validation for a file rulesync
51671
- * had just written, and a stray `name: [unclosed` would make the import throw
51672
- * a raw YAML error.
51673
- *
51674
- * The block is therefore found the way gray-matter finds it rather than by
51675
- * parsing it, so that what gray-matter would have swallowed is what goes: the
51676
- * opening delimiter may carry a language name (`---yaml`), but four dashes are
51677
- * a horizontal rule gray-matter itself skips. The one deliberate difference is
51678
- * a fence nothing closes: gray-matter would swallow the rest of the file, so
51679
- * only the rule line goes and the prose under it is kept.
52078
+ * review instructions. Left in place it would be carried into the body of
52079
+ * the check written to `.rulesync/checks/` as a block of YAML right behind
52080
+ * that file's own frontmatter, where a `severity: bogus` copied out of a skill
52081
+ * looks like the check's own setting to anyone reading or editing it.
52082
+ *
52083
+ * The block is therefore found the way `parseFrontmatter` finds it rather than
52084
+ * by parsing it, so that what the parser would have read as frontmatter is
52085
+ * what goes: the opening delimiter may carry a language name (`---yaml`), but
52086
+ * four dashes are a horizontal rule the parser itself skips. The one
52087
+ * deliberate difference is a fence nothing closes: the parser would take the
52088
+ * rest of the file, so only the rule line goes and the prose under it is kept.
51680
52089
  */
51681
52090
  const FRONTMATTER_OPEN_PATTERN = /^\uFEFF?---(?!-)[^\r\n]*\r?\n/;
51682
52091
  const FRONTMATTER_CLOSE_PATTERN = /^---|\r?\n---/;
@@ -56361,9 +56770,12 @@ var SettingsJsonHooks = class extends ToolHooks {
56361
56770
  const config = rulesyncHooks.getJson();
56362
56771
  const generatedHooks = canonicalToToolHooks({
56363
56772
  config,
56364
- toolOverrideHooks: overrideHooksOf({
56365
- config,
56366
- overrideKey: this.getSpec().overrideKey
56773
+ toolOverrideHooks: knownOverrideHooks({
56774
+ hooks: overrideHooksOf({
56775
+ config,
56776
+ overrideKey: this.getSpec().overrideKey
56777
+ }),
56778
+ spec: this.getSpec()
56367
56779
  }),
56368
56780
  converterConfig: this.getConverterConfig(),
56369
56781
  logger
@@ -56426,6 +56838,16 @@ var SettingsJsonHooks = class extends ToolHooks {
56426
56838
  }
56427
56839
  };
56428
56840
  /**
56841
+ * The override hooks the tool can take: all of them, unless the spec lists
56842
+ * {@link SettingsJsonHooksSpec.knownOverrideEvents}, in which case only those
56843
+ * native names and the canonical supported events are kept.
56844
+ */
56845
+ function knownOverrideHooks({ hooks, spec }) {
56846
+ if (hooks === void 0 || spec.knownOverrideEvents === void 0) return hooks;
56847
+ const known = /* @__PURE__ */ new Set([...spec.converterConfig.supportedEvents, ...spec.knownOverrideEvents]);
56848
+ return Object.fromEntries(Object.entries(hooks).filter(([event]) => known.has(event)));
56849
+ }
56850
+ /**
56429
56851
  * The `hooks` map of a tool's override block (`config.<overrideKey>.hooks`),
56430
56852
  * or `undefined` when the block states none. The schema keeps every override
56431
56853
  * block loose, so the lookup goes through the record form.
@@ -56439,7 +56861,6 @@ function overrideHooksOf({ config, overrideKey }) {
56439
56861
  const hooks = override.hooks;
56440
56862
  return isPlainObject(hooks) ? hooks : void 0;
56441
56863
  }
56442
- // src/features/hooks/bob-hooks.ts
56443
56864
  const BOB_SPEC = {
56444
56865
  displayName: "Bob",
56445
56866
  overrideKey: "bob",
@@ -56448,11 +56869,12 @@ const BOB_SPEC = {
56448
56869
  canonicalToToolEventNames: CANONICAL_TO_BOB_EVENT_NAMES,
56449
56870
  toolToCanonicalEventNames: BOB_TO_CANONICAL_EVENT_NAMES,
56450
56871
  projectDirVar: "",
56451
- noMatcherEvents: /* @__PURE__ */ new Set(["beforeSubmitPrompt", "stop"]),
56872
+ noMatcherEvents: new Set(BOB_HOOK_EVENTS.filter((event) => !BOB_MATCHER_HOOK_EVENTS.includes(event))),
56452
56873
  supportedHookTypes: /* @__PURE__ */ new Set(["command", "http"]),
56453
56874
  importedHookTypeAliases: { https: "http" },
56454
56875
  wildcardMatcherMeansAll: true
56455
- }
56876
+ },
56877
+ knownOverrideEvents: BOB_NATIVE_HOOK_EVENTS
56456
56878
  };
56457
56879
  /**
56458
56880
  * IBM Bob lifecycle hooks.
@@ -59867,7 +60289,7 @@ function canonicalToHermesHooks({ config, toolOverrideHooks, logger }) {
59867
60289
  for (const [nativeEvent, definitions] of Object.entries(toolOverrideHooks ?? {})) {
59868
60290
  if (HERMESAGENT_CANONICAL_EVENTS.has(nativeEvent)) continue;
59869
60291
  if (HERMESAGENT_SHELL_UNSUPPORTED_EVENTS.has(nativeEvent)) logger?.warn(`Hermes hook event "${nativeEvent}" is Python-plugin-only; Hermes Agent refuses it for shell hooks, so the generated entry will never run.`);
59870
- else if (!HERMESAGENT_NATIVE_EVENTS.has(nativeEvent)) logger?.warn(`Hermes hook event "${nativeEvent}" is not documented by Hermes Agent v0.23.2; preserving it for forward compatibility.`);
60292
+ else if (!HERMESAGENT_NATIVE_EVENTS.has(nativeEvent)) logger?.warn(`Hermes hook event "${nativeEvent}" is not documented by Hermes Agent v0.23.4; preserving it for forward compatibility.`);
59871
60293
  setHermesHookEntries({
59872
60294
  result,
59873
60295
  event: nativeEvent,
@@ -60544,7 +60966,9 @@ function buildRunHelperLinesFor(cwdExpression) {
60544
60966
  * hook denies it:
60545
60967
  * - exit code 2 → deny, with the command's stderr as the reason;
60546
60968
  * - exit code 0 with JSON stdout whose `hookSpecificOutput.permissionDecision`
60547
- * is `"deny"` → deny, with `permissionDecisionReason` as the reason;
60969
+ * is `"deny"` → deny, with `permissionDecisionReason` as the reason; when it
60970
+ * sets no `permissionDecision`, the deprecated top-level `decision: "block"`
60971
+ * that Claude Code still honors denies too, with `reason` as the reason;
60548
60972
  * - exit code 0 otherwise → allow;
60549
60973
  * - any other non-zero exit → deny too, with stderr or the exit code;
60550
60974
  * - more than 1 MiB of stdout → deny, without parsing it;
@@ -60579,12 +61003,13 @@ const PRE_TOOL_USE_RESULT_HELPER_LINES = [
60579
61003
  " } catch {",
60580
61004
  " return;",
60581
61005
  " }",
60582
- " const specific = parsed && typeof parsed === \"object\" ? parsed.hookSpecificOutput : undefined;",
60583
- " if (specific && typeof specific === \"object\" && specific.permissionDecision === \"deny\") {",
61006
+ " if (!parsed || typeof parsed !== \"object\") return;",
61007
+ " const specific = parsed.hookSpecificOutput;",
61008
+ " const hasDecision = typeof specific === \"object\" && specific !== null && specific.permissionDecision !== undefined;",
61009
+ " const reason = hasDecision ? specific.permissionDecisionReason : parsed.reason;",
61010
+ " if (hasDecision ? specific.permissionDecision === \"deny\" : parsed.decision === \"block\") {",
60584
61011
  " throw new Error(",
60585
- " (typeof specific.permissionDecisionReason === \"string\" &&",
60586
- " sanitizeBlockReason(specific.permissionDecisionReason)) ||",
60587
- " \"Blocked by a preToolUse hook.\",",
61012
+ " (typeof reason === \"string\" && sanitizeBlockReason(reason)) || \"Blocked by a preToolUse hook.\",",
60588
61013
  " );",
60589
61014
  " }",
60590
61015
  " return;",
@@ -60737,6 +61162,51 @@ function warnIgnoredFailClosed({ config, supportedEvents, toolConfigKey, logger
60737
61162
  }
60738
61163
  }
60739
61164
  }
61165
+ /**
61166
+ * Canonical (Claude Code) tool names mapped to the lowercase tool ids OpenCode
61167
+ * 1.x and its forks (Kilo, MiMo Code) pass as `input.tool`, which a matcher is
61168
+ * tested against case-sensitively. The shell tool is `bash` here, the same id
61169
+ * the shell events gate on (see {@link SHELL_EVENT_TOOL_GATES}).
61170
+ * @see https://opencode.ai/docs/plugins/
61171
+ */
61172
+ const CANONICAL_TO_OPENCODE_V1_TOOL_NAMES = {
61173
+ Bash: "bash",
61174
+ Read: "read",
61175
+ Write: "write",
61176
+ Edit: "edit"
61177
+ };
61178
+ /**
61179
+ * A matcher made only of plain names joined by `|`, which Claude Code matches
61180
+ * as an exact tool name list rather than as a regex.
61181
+ */
61182
+ const PLAIN_NAME_MATCHER_PATTERN = /^[A-Za-z0-9_]+(?:\|[A-Za-z0-9_]+)*$/;
61183
+ /**
61184
+ * Build a translator that rewrites the canonical tool names in a matcher
61185
+ * through `toolNames` and warns about a capitalized name left over
61186
+ * (`MultiEdit`, `Glob`), which no lowercase tool id can match. Each distinct
61187
+ * matcher of an event is translated once, so hooks sharing one do not repeat
61188
+ * its warning.
61189
+ *
61190
+ * The plugins test the matcher unanchored, so a translated plain-name matcher
61191
+ * is anchored as `^(?:...)$` to keep Claude Code's exact-name semantics:
61192
+ * otherwise `write` would also match OpenCode's `todowrite`. Regex-style and
61193
+ * untranslated matchers are left as written.
61194
+ */
61195
+ function createOpencodeMatcherTranslator({ toolNames, toolConfigKey, logger }) {
61196
+ const label = FAIL_CLOSED_TOOL_LABELS[toolConfigKey];
61197
+ const translated = /* @__PURE__ */ new Map();
61198
+ return (matcher, eventName) => {
61199
+ const key = `${eventName}\0${matcher}`;
61200
+ const cached = translated.get(key);
61201
+ if (cached !== void 0) return cached;
61202
+ const replaced = replaceMatcherNames(matcher, toolNames);
61203
+ const result = replaced !== matcher && PLAIN_NAME_MATCHER_PATTERN.test(stripControlChars(matcher)) ? `^(?:${replaced})$` : replaced;
61204
+ const unmatched = capitalizedMatcherNames(result);
61205
+ if (unmatched.length > 0) logger?.warn(`${label} matches hook matchers case-sensitively against lowercase tool names, and ${unmatched.map((name) => quoteValueForWarning(name)).join(", ")} in the ${quoteValueForWarning(eventName)} matcher ${quoteValueForWarning(matcher)} is not translated by rulesync, so it is written as-is and will likely never match. Use the tool name ${label} reports instead.`);
61206
+ translated.set(key, result);
61207
+ return result;
61208
+ };
61209
+ }
60740
61210
  /** Whether any handler is a `sessionStart` one, whose stdout becomes session context. */
60741
61211
  function usesSessionContext(handlers) {
60742
61212
  return handlers.some((handler) => handler.context);
@@ -60762,7 +61232,7 @@ function handlerExtrasFor(canonicalEvent) {
60762
61232
  * Group the effective hooks into named (tool.execute.*) and generic event
60763
61233
  * handler groups, keyed by tool event name. Mutates the supplied groups.
60764
61234
  */
60765
- function collectOpencodeStyleHandlers({ effectiveHooks, eventMap, namedEventHandlers, genericEventHandlers }) {
61235
+ function collectOpencodeStyleHandlers({ effectiveHooks, eventMap, namedEventHandlers, genericEventHandlers, translateMatcher }) {
60766
61236
  for (const [canonicalEvent, definitions] of Object.entries(effectiveHooks)) {
60767
61237
  const shellGate = SHELL_EVENT_TOOL_GATES[canonicalEvent];
60768
61238
  const extras = handlerExtrasFor(canonicalEvent);
@@ -60770,6 +61240,7 @@ function collectOpencodeStyleHandlers({ effectiveHooks, eventMap, namedEventHand
60770
61240
  if (!toolEvent) continue;
60771
61241
  const isNamedHook = Object.hasOwn(NAMED_HOOK_MATCHER_SUBJECTS, toolEvent);
60772
61242
  const matcherSupported = !shellGate && isNamedHook && NAMED_HOOK_MATCHER_SUBJECTS[toolEvent] !== null;
61243
+ const matchesToolName = NAMED_HOOK_MATCHER_SUBJECTS[toolEvent] === "input.tool";
60773
61244
  const handlers = [];
60774
61245
  for (const def of definitions) {
60775
61246
  if ((def.type ?? "command") !== "command") continue;
@@ -60777,7 +61248,7 @@ function collectOpencodeStyleHandlers({ effectiveHooks, eventMap, namedEventHand
60777
61248
  if (def.matcher && !matcherSupported) continue;
60778
61249
  handlers.push({
60779
61250
  command: def.command,
60780
- matcher: def.matcher ? def.matcher : void 0,
61251
+ matcher: def.matcher ? matchesToolName ? translateMatcher(def.matcher, canonicalEvent) : def.matcher : void 0,
60781
61252
  blocking: BLOCKING_HOOKS.has(toolEvent),
60782
61253
  ...hookTimingOf(def),
60783
61254
  inProcess: !isNamedHook,
@@ -60941,7 +61412,7 @@ function wrapInExportShape({ preambleLines, bodyLines, exportStyle }) {
60941
61412
  lines.push("");
60942
61413
  return lines;
60943
61414
  }
60944
- function generateOpencodeStylePluginCode(config, supportedEvents, toolConfigKey, eventMap, exportStyle = "named") {
61415
+ function generateOpencodeStylePluginCode(config, supportedEvents, toolConfigKey, eventMap, exportStyle = "named", logger) {
60945
61416
  const supported = new Set(supportedEvents);
60946
61417
  const configHooks = {
60947
61418
  ...config.hooks,
@@ -60955,7 +61426,12 @@ function generateOpencodeStylePluginCode(config, supportedEvents, toolConfigKey,
60955
61426
  effectiveHooks,
60956
61427
  eventMap,
60957
61428
  namedEventHandlers,
60958
- genericEventHandlers
61429
+ genericEventHandlers,
61430
+ translateMatcher: createOpencodeMatcherTranslator({
61431
+ toolNames: CANONICAL_TO_OPENCODE_V1_TOOL_NAMES,
61432
+ toolConfigKey,
61433
+ logger
61434
+ })
60959
61435
  });
60960
61436
  const usesContext = Object.values(genericEventHandlers).some(usesSessionContext);
60961
61437
  const bodyLines = [
@@ -61009,7 +61485,7 @@ var KiloHooks = class KiloHooks extends ToolHooks {
61009
61485
  toolConfigKey: "kilo",
61010
61486
  logger
61011
61487
  });
61012
- const fileContent = generateOpencodeStylePluginCode(config, KILO_HOOK_EVENTS, "kilo", CANONICAL_TO_KILO_EVENT_NAMES, "default");
61488
+ const fileContent = generateOpencodeStylePluginCode(config, KILO_HOOK_EVENTS, "kilo", CANONICAL_TO_KILO_EVENT_NAMES, "default", logger);
61013
61489
  const paths = KiloHooks.getSettablePaths({ global });
61014
61490
  return new KiloHooks({
61015
61491
  outputRoot,
@@ -61873,6 +62349,21 @@ var LettacodeHooks = class LettacodeHooks extends ToolHooks {
61873
62349
  /** Tool name OpenCode V2 gives its shell tool (V1 called it `bash`). */
61874
62350
  const OPENCODE_V2_SHELL_TOOL = "shell";
61875
62351
  /**
62352
+ * Canonical (Claude Code) tool names mapped to the lowercase names OpenCode 2.x
62353
+ * reports in `event.tool`, which a matcher is tested against case-sensitively.
62354
+ * Observed on OpenCode 2.3.2: a `preToolUse` hook fires with `read`, `write`,
62355
+ * `edit` and `shell`, so a canonical `Read|Edit|Write` or `Bash` never matched.
62356
+ * `Bash` becomes the V2 name `shell`; the generated helper still accepts the
62357
+ * V1 name `bash` for a matcher written that way.
62358
+ * https://opencode.ai/v2/docs/build/plugins/
62359
+ */
62360
+ const CANONICAL_TO_OPENCODE_V2_TOOL_NAMES = {
62361
+ Bash: OPENCODE_V2_SHELL_TOOL,
62362
+ Read: "read",
62363
+ Write: "write",
62364
+ Edit: "edit"
62365
+ };
62366
+ /**
61876
62367
  * Per-canonical-event conditions the generated handler gates on, because the
61877
62368
  * hook point or event it shares fires more broadly than the canonical event:
61878
62369
  * - the shell events run only for the `shell` tool's calls;
@@ -62049,7 +62540,7 @@ function isBlockingOpencodeV2Target(target) {
62049
62540
  return !target.startsWith("event:") && target !== "tool:execute.after";
62050
62541
  }
62051
62542
  /** Build the handlers of one canonical event's command definitions. */
62052
- function buildHandlersFor({ canonicalEvent, definitions, target }) {
62543
+ function buildHandlersFor({ canonicalEvent, definitions, target, translateMatcher }) {
62053
62544
  const gate = OPENCODE_V2_HANDLER_GATES[canonicalEvent];
62054
62545
  const payload = OPENCODE_V2_STDIN_PAYLOADS[canonicalEvent];
62055
62546
  const matcherSupported = !(canonicalEvent === "beforeShellExecution" || canonicalEvent === "afterShellExecution") && OPENCODE_V2_MATCHABLE_HOOKS.has(target);
@@ -62063,7 +62554,7 @@ function buildHandlersFor({ canonicalEvent, definitions, target }) {
62063
62554
  event: canonicalEvent,
62064
62555
  blocking: isBlockingOpencodeV2Target(target),
62065
62556
  ...hookTimingOf(def),
62066
- ...def.matcher ? { matcher: def.matcher } : {},
62557
+ ...def.matcher ? { matcher: translateMatcher(def.matcher, canonicalEvent) } : {},
62067
62558
  ...gate ? { gate } : {},
62068
62559
  ...payload ? { payload } : {},
62069
62560
  ...sessionContextExtrasFor(canonicalEvent)
@@ -62099,12 +62590,17 @@ function buildSetupBodyLines({ hookHandlers, eventHandlers }) {
62099
62590
  body.push("", "return async () => {", ...cleanup, "};");
62100
62591
  return body;
62101
62592
  }
62102
- function generateOpencodeV2PluginCode({ config, supportedEvents, toolConfigKey, eventMap }) {
62593
+ function generateOpencodeV2PluginCode({ config, supportedEvents, toolConfigKey, eventMap, logger }) {
62103
62594
  const supported = new Set(supportedEvents);
62104
62595
  const configHooks = {
62105
62596
  ...config.hooks,
62106
62597
  ...config[toolConfigKey]?.hooks
62107
62598
  };
62599
+ const translateMatcher = createOpencodeMatcherTranslator({
62600
+ toolNames: CANONICAL_TO_OPENCODE_V2_TOOL_NAMES,
62601
+ toolConfigKey,
62602
+ logger
62603
+ });
62108
62604
  const hookHandlers = /* @__PURE__ */ new Map();
62109
62605
  const eventHandlers = /* @__PURE__ */ new Map();
62110
62606
  for (const [canonicalEvent, definitions] of Object.entries(configHooks)) {
@@ -62114,7 +62610,8 @@ function generateOpencodeV2PluginCode({ config, supportedEvents, toolConfigKey,
62114
62610
  const handlers = buildHandlersFor({
62115
62611
  canonicalEvent,
62116
62612
  definitions,
62117
- target
62613
+ target,
62614
+ translateMatcher
62118
62615
  });
62119
62616
  if (handlers.length === 0) continue;
62120
62617
  const isEvent = target.startsWith("event:");
@@ -62169,8 +62666,9 @@ var OpencodeHooks = class extends ToolHooks {
62169
62666
  config,
62170
62667
  supportedEvents: OPENCODE_V2_HOOK_EVENTS,
62171
62668
  toolConfigKey: this.layout.toolTarget,
62172
- eventMap: CANONICAL_TO_OPENCODE_V2_EVENT_NAMES
62173
- }) : generateOpencodeStylePluginCode(config, OPENCODE_HOOK_EVENTS, this.layout.toolTarget, CANONICAL_TO_OPENCODE_EVENT_NAMES);
62669
+ eventMap: CANONICAL_TO_OPENCODE_V2_EVENT_NAMES,
62670
+ logger
62671
+ }) : generateOpencodeStylePluginCode(config, OPENCODE_HOOK_EVENTS, this.layout.toolTarget, CANONICAL_TO_OPENCODE_EVENT_NAMES, "named", logger);
62174
62672
  const paths = this.getSettablePaths({ global });
62175
62673
  return new this({
62176
62674
  outputRoot,
@@ -62287,11 +62785,123 @@ const PI_SETTLE_BLOCKING_EVENT = "agent_before_settle";
62287
62785
  * @see https://github.com/can1357/oh-my-pi/blob/fa5ff4a3a977a28b93d025f4cf50f046e019f18c/packages/coding-agent/src/session/agent-session.ts
62288
62786
  */
62289
62787
  const OMP_SESSION_STOP_BLOCKING_EVENT = "session_stop";
62788
+ /**
62789
+ * Pi's `resolveToCwd` (`core/tools/path-utils.ts`), which calls
62790
+ * `resolvePath(path, cwd, { normalizeUnicodeSpaces: true, stripAtPrefix: true })`
62791
+ * from `utils/paths.ts`: Unicode spaces become plain spaces, a leading `@` is
62792
+ * dropped, on Windows Git Bash / WSL drive paths are converted, `~` is
62793
+ * expanded, a `file://` URL is converted, and the result is resolved against
62794
+ * cwd. Pi has no URL passthrough, so any other `scheme://` text is a relative
62795
+ * path too.
62796
+ *
62797
+ * @see https://github.com/earendil-works/pi/blob/v1.6.0/packages/coding-agent/src/utils/paths.ts
62798
+ */
62799
+ const PI_PATH_RESOLVER_LINES = [
62800
+ "function absoluteToolPath(path: unknown, cwd: string): unknown {",
62801
+ " if (typeof path !== \"string\") return path;",
62802
+ " let normalized = path.replace(/[\\u00A0\\u2000-\\u200A\\u202F\\u205F\\u3000]/g, \" \");",
62803
+ " if (normalized.startsWith(\"@\")) normalized = normalized.slice(1);",
62804
+ " if (process.platform === \"win32\" && normalized.startsWith(\"/\") && !normalized.startsWith(\"//\") && !normalized.includes(\"\\\\\")) {",
62805
+ " const drive = normalized.match(/^\\/(?:mnt\\/|cygdrive\\/)?([a-z])(?:\\/(.*))?$/i);",
62806
+ " if (drive?.[1]) normalized = `${drive[1].toUpperCase()}:\\\\${drive[2]?.replaceAll(\"/\", \"\\\\\") ?? \"\"}`;",
62807
+ " }",
62808
+ " if (normalized === \"~\") normalized = homedir();",
62809
+ " else if (normalized.startsWith(\"~/\") || (process.platform === \"win32\" && normalized.startsWith(\"~\\\\\"))) {",
62810
+ " normalized = joinPath(homedir(), normalized.slice(2));",
62811
+ " } else if (/^file:\\/\\//.test(normalized)) {",
62812
+ " try {",
62813
+ " normalized = fileURLToPath(normalized);",
62814
+ " } catch {",
62815
+ " return path;",
62816
+ " }",
62817
+ " }",
62818
+ " return resolvePath(cwd, normalized);",
62819
+ "}"
62820
+ ];
62821
+ /**
62822
+ * oh-my-pi's `resolveToCwd` (`tools/path-utils.ts`): `expandPath` strips a
62823
+ * stray leading `:` before a path shape, strips a leading `@` only before an
62824
+ * absolute path, `~` or an internal URL, turns Unicode spaces into plain
62825
+ * spaces, converts a `file://` URL and expands `~`; an internal URL is not a
62826
+ * filesystem path, a bare root (`/`) is the workspace root, and anything else
62827
+ * is resolved against cwd. Windows drive-alias handling is not mirrored.
62828
+ *
62829
+ * @see https://github.com/can1357/oh-my-pi/blob/76b7d843d59bc83cc40cd5decadc89dc808a14e6/packages/coding-agent/src/tools/path-utils.ts
62830
+ */
62831
+ const OMP_PATH_RESOLVER_LINES = [
62832
+ `const INTERNAL_URL_SCHEME = /^(?:${[
62833
+ "skill",
62834
+ "rule",
62835
+ "memory",
62836
+ "out",
62837
+ "agent",
62838
+ "history",
62839
+ "local",
62840
+ "proc",
62841
+ "cfg",
62842
+ "ssh",
62843
+ "security",
62844
+ "vault",
62845
+ "issue",
62846
+ "pr",
62847
+ "mr",
62848
+ "mcp",
62849
+ "omp",
62850
+ "help",
62851
+ "attachment",
62852
+ "conflict"
62853
+ ].join("|")}):\\/\\/?/i;`,
62854
+ "",
62855
+ "function absoluteToolPath(path: unknown, cwd: string): unknown {",
62856
+ " if (typeof path !== \"string\") return path;",
62857
+ " let normalized = /^:(?=[/\\\\~]|\\.\\.?[/\\\\]|[A-Za-z]:)/.test(path) ? path.slice(1) : path;",
62858
+ " if (normalized.startsWith(\"@\")) {",
62859
+ " const rest = normalized.slice(1);",
62860
+ " if (rest.startsWith(\"/\") || rest === \"~\" || rest.startsWith(\"~/\") || win32Path.isAbsolute(rest) || INTERNAL_URL_SCHEME.test(rest)) {",
62861
+ " normalized = rest;",
62862
+ " }",
62863
+ " }",
62864
+ " normalized = normalized.replace(/[\\u00A0\\u2000-\\u200A\\u202F\\u205F\\u3000]/g, \" \");",
62865
+ " if (normalized.toLowerCase().startsWith(\"file://\")) {",
62866
+ " try {",
62867
+ " normalized = fileURLToPath(normalized);",
62868
+ " } catch {",
62869
+ " // oh-my-pi keeps an unconvertible `file://` text as written.",
62870
+ " }",
62871
+ " }",
62872
+ " if (normalized === \"~\") normalized = homedir();",
62873
+ " else if (normalized.startsWith(\"~/\")) normalized = joinPath(homedir(), normalized.slice(2));",
62874
+ " if (INTERNAL_URL_SCHEME.test(normalized)) return normalized;",
62875
+ " if (/^\\/+$/.test(normalized)) return resolvePath(cwd);",
62876
+ " return resolvePath(cwd, normalized);",
62877
+ "}"
62878
+ ];
62879
+ /**
62880
+ * Tool names both Pi and oh-my-pi share with a canonical counterpart. Pi's
62881
+ * `powershell` tool is deliberately left out: Rulesync has no canonical name
62882
+ * for it, so it keeps its own.
62883
+ */
62884
+ const SHARED_CANONICAL_TOOL_NAMES = {
62885
+ bash: "Bash",
62886
+ read: "Read",
62887
+ write: "Write",
62888
+ edit: "Edit",
62889
+ grep: "Grep"
62890
+ };
62290
62891
  const PI_EXTENSION_DIALECT = {
62291
62892
  overrideKey: "pi",
62292
62893
  typesPackage: "@earendil-works/pi-coding-agent",
62293
62894
  promptPassLine: "return { action: \"continue\" };",
62294
- promptCancelLine: "return { action: \"handled\" };"
62895
+ promptCancelLine: "return { action: \"handled\" };",
62896
+ toolNames: {
62897
+ ...SHARED_CANONICAL_TOOL_NAMES,
62898
+ find: "Glob"
62899
+ },
62900
+ editTextKeys: {
62901
+ old: "oldText",
62902
+ new: "newText"
62903
+ },
62904
+ pathResolverLines: PI_PATH_RESOLVER_LINES
62295
62905
  };
62296
62906
  /**
62297
62907
  * oh-my-pi's `emitInput` stops at the first result with `handled` set and
@@ -62303,7 +62913,16 @@ const OMP_EXTENSION_DIALECT = {
62303
62913
  overrideKey: "omp",
62304
62914
  typesPackage: "@oh-my-pi/pi-coding-agent",
62305
62915
  promptPassLine: "return {};",
62306
- promptCancelLine: "return { handled: true };"
62916
+ promptCancelLine: "return { handled: true };",
62917
+ toolNames: {
62918
+ ...SHARED_CANONICAL_TOOL_NAMES,
62919
+ glob: "Glob"
62920
+ },
62921
+ editTextKeys: {
62922
+ old: "old_string",
62923
+ new: "new_string"
62924
+ },
62925
+ pathResolverLines: OMP_PATH_RESOLVER_LINES
62307
62926
  };
62308
62927
  const PI_BLOCKING_MODE_BY_EVENT = {
62309
62928
  [PI_BLOCKING_EVENT]: "tool",
@@ -62327,7 +62946,284 @@ function failureLinesByMode(dialect) {
62327
62946
  };
62328
62947
  }
62329
62948
  /**
62330
- * Helper emitted alongside blocking handlers. `promisify(exec)` rejects on a
62949
+ * Canonical events whose command receives Claude Code's JSON input for the
62950
+ * event on stdin, mapped to its `hook_event_name`; every other command gets an
62951
+ * empty stdin, as in the OpenCode-style plugin (`STDIN_PAYLOADS` in
62952
+ * `opencode-style-generator.ts`). All three ride on Pi's tool events, whose
62953
+ * `event.toolName`, `event.toolCallId` and `event.input` the payload is built
62954
+ * from. A payload is serialized lazily, once per invocation, by the first
62955
+ * handler that runs.
62956
+ *
62957
+ * @see https://github.com/earendil-works/pi/blob/v1.6.0/packages/coding-agent/docs/extensions.md#tool_call
62958
+ * @see https://code.claude.com/docs/en/hooks
62959
+ */
62960
+ const STDIN_PAYLOAD_EVENTS = {
62961
+ preToolUse: "PreToolUse",
62962
+ postToolUse: "PostToolUse",
62963
+ postToolUseFailure: "PostToolUseFailure"
62964
+ };
62965
+ /**
62966
+ * The fields each payload adds to the tool call's own (`session_id`, `cwd`,
62967
+ * `hook_event_name`, `tool_name`, `tool_input`, `tool_use_id`), as TypeScript
62968
+ * object entries evaluated against the `tool_result` event.
62969
+ */
62970
+ const STDIN_PAYLOAD_EXTRA_FIELDS = {
62971
+ PreToolUse: "",
62972
+ PostToolUse: "tool_response: { content: event.content, details: event.details }",
62973
+ PostToolUseFailure: "error: toolResultText(event.content)"
62974
+ };
62975
+ /**
62976
+ * Helpers emitted when a handler receives a stdin payload or tests a matcher.
62977
+ *
62978
+ * `claudeToolName` maps the dialect's built-in tool names to the canonical
62979
+ * Claude Code names Rulesync uses elsewhere (`bash` → `Bash`, ...). MCP tools
62980
+ * are already named `mcp__<server>__<tool>` by Pi, and other tools keep their
62981
+ * own name.
62982
+ *
62983
+ * `claudeToolInput` passes the tool's arguments through, except for the file
62984
+ * tools: `path` becomes Claude Code's absolute `file_path`, resolved against
62985
+ * the session cwd the way Pi's `resolveToCwd` does, and on Pi each `edits`
62986
+ * entry's `oldText` / `newText` becomes `old_string` / `new_string` (oh-my-pi
62987
+ * already uses those, see `editTextKeys`). When the call has no top-level
62988
+ * `old_string` / `new_string`, every edit's text is joined into them, as
62989
+ * Claude Code's `Edit` input carries, so a guard reading those sees every
62990
+ * change. The mapped keys are written last and any same-named key the model
62991
+ * added is dropped, so an extra argument (Pi's schemas allow them) cannot make
62992
+ * a guard check a different file or text than the one the tool acts on.
62993
+ */
62994
+ function buildToolPayloadHelperLines(dialect) {
62995
+ return [
62996
+ `const CLAUDE_TOOL_NAMES: Record<string, string> = ${JSON.stringify(dialect.toolNames)};`,
62997
+ "",
62998
+ "function claudeToolName(toolName: string): string {",
62999
+ " return Object.hasOwn(CLAUDE_TOOL_NAMES, toolName) ? (CLAUDE_TOOL_NAMES[toolName] ?? toolName) : toolName;",
63000
+ "}",
63001
+ "",
63002
+ "function matchesTool(matcher: RegExp, toolName: string): boolean {",
63003
+ " return matcher.test(toolName) || matcher.test(claudeToolName(toolName));",
63004
+ "}",
63005
+ "",
63006
+ ...dialect.pathResolverLines,
63007
+ "",
63008
+ `const EDIT_TEXT_KEYS = ${JSON.stringify(dialect.editTextKeys)};`,
63009
+ "const CLAUDE_EDIT_TEXT_KEYS = EDIT_TEXT_KEYS.old === \"old_string\";",
63010
+ "",
63011
+ "function claudeEditEntry(edit: unknown): unknown {",
63012
+ " if (CLAUDE_EDIT_TEXT_KEYS || !edit || typeof edit !== \"object\") return edit;",
63013
+ " const {",
63014
+ " [EDIT_TEXT_KEYS.old]: oldText,",
63015
+ " [EDIT_TEXT_KEYS.new]: newText,",
63016
+ " old_string: _old,",
63017
+ " new_string: _new,",
63018
+ " ...others",
63019
+ " } = edit as Record<string, unknown>;",
63020
+ " return { ...others, old_string: oldText, new_string: newText };",
63021
+ "}",
63022
+ "",
63023
+ "function joinedEditText(edits: unknown[], key: string): string | undefined {",
63024
+ " const texts = edits",
63025
+ " .map((edit: unknown) => (edit as Record<string, unknown> | null)?.[key])",
63026
+ " .filter((text): text is string => typeof text === \"string\");",
63027
+ " return texts.length > 0 ? texts.join(\"\\n\") : undefined;",
63028
+ "}",
63029
+ "",
63030
+ "function claudeToolInput(toolName: string, input: unknown, cwd: string): unknown {",
63031
+ " if (![\"read\", \"write\", \"edit\"].includes(toolName)) return input;",
63032
+ " if (!input || typeof input !== \"object\" || Array.isArray(input)) return input;",
63033
+ " const { path, file_path: _filePath, ...rest } = input as Record<string, unknown>;",
63034
+ " if (!CLAUDE_EDIT_TEXT_KEYS) {",
63035
+ " delete rest.old_string;",
63036
+ " delete rest.new_string;",
63037
+ " }",
63038
+ " // The raw `path` stays, so a guard can check what the model wrote too.",
63039
+ " const claudeInput: Record<string, unknown> = { ...rest, path, file_path: absoluteToolPath(path, cwd) };",
63040
+ " if (!Array.isArray(rest.edits)) return claudeInput;",
63041
+ " const edits = rest.edits.map(claudeEditEntry);",
63042
+ " return {",
63043
+ " ...claudeInput,",
63044
+ " edits,",
63045
+ " old_string: claudeInput.old_string ?? joinedEditText(edits, \"old_string\"),",
63046
+ " new_string: claudeInput.new_string ?? joinedEditText(edits, \"new_string\"),",
63047
+ " };",
63048
+ "}",
63049
+ "",
63050
+ "function toolResultText(content: unknown): string {",
63051
+ " if (!Array.isArray(content)) return \"\";",
63052
+ " return content",
63053
+ " .map((block: unknown) => {",
63054
+ " const part = block as { type?: unknown; text?: unknown } | null;",
63055
+ " return part?.type === \"text\" && typeof part.text === \"string\" ? part.text : \"\";",
63056
+ " })",
63057
+ " .filter(Boolean)",
63058
+ " .join(\"\\n\");",
63059
+ "}",
63060
+ "",
63061
+ "type ToolHookEvent = { toolName: string; toolCallId?: string; input?: unknown };",
63062
+ "",
63063
+ "function toolHookInput(",
63064
+ " hookEventName: string,",
63065
+ " event: ToolHookEvent,",
63066
+ " ctx: ExtensionContext | undefined,",
63067
+ " extra: Record<string, unknown> = {},",
63068
+ "): string {",
63069
+ " const cwd = ctx?.cwd ?? process.cwd();",
63070
+ " return JSON.stringify({",
63071
+ " session_id: ctx?.sessionManager?.getSessionId?.(),",
63072
+ " cwd,",
63073
+ " hook_event_name: hookEventName,",
63074
+ " tool_name: claudeToolName(event.toolName),",
63075
+ " tool_input: claudeToolInput(event.toolName, event.input, cwd),",
63076
+ " tool_use_id: event.toolCallId,",
63077
+ " ...extra,",
63078
+ " });",
63079
+ "}"
63080
+ ];
63081
+ }
63082
+ /**
63083
+ * Helpers emitted alongside `tool_call` handlers. A command that exits 0 may
63084
+ * still decide the call the way Claude Code reads a `PreToolUse` hook's JSON
63085
+ * stdout: `hookSpecificOutput.permissionDecision` `"deny"` or `"ask"` (with
63086
+ * `permissionDecisionReason`) or, when no `permissionDecision` is given, the
63087
+ * deprecated top-level `decision: "block"` (with `reason`). Output that is not
63088
+ * such JSON allows the call, so hooks that print plain text keep working. The
63089
+ * deny side is the OpenCode-style plugin's `__rulesyncEnforcePreToolUseResult`
63090
+ * contract, plus the deprecated form Claude Code still honors.
63091
+ *
63092
+ * Pi has no permission prompt of its own, so `"ask"` is put to the user with
63093
+ * `ctx.ui.confirm` when a UI is attached, and denies the call when none is (print
63094
+ * and JSON modes) or the dialog fails: a hook asking for a human must not pass
63095
+ * silently.
63096
+ */
63097
+ const TOOL_DECISION_HELPER_LINES = [
63098
+ "type ToolHookDecision = { kind: \"deny\" | \"ask\"; reason: string };",
63099
+ "",
63100
+ "function toolHookDecision(stdout: string): ToolHookDecision | undefined {",
63101
+ " let parsed: unknown;",
63102
+ " try {",
63103
+ " parsed = JSON.parse(stdout);",
63104
+ " } catch {",
63105
+ " return undefined;",
63106
+ " }",
63107
+ " if (!parsed || typeof parsed !== \"object\") return undefined;",
63108
+ " const output = parsed as { decision?: unknown; reason?: unknown; hookSpecificOutput?: unknown };",
63109
+ " const specific = output.hookSpecificOutput as",
63110
+ " | { permissionDecision?: unknown; permissionDecisionReason?: unknown }",
63111
+ " | null",
63112
+ " | undefined;",
63113
+ " const hasDecision = typeof specific === \"object\" && specific !== null && specific.permissionDecision !== undefined;",
63114
+ " const decision = hasDecision ? specific?.permissionDecision : output.decision === \"block\" ? \"deny\" : undefined;",
63115
+ " if (decision !== \"deny\" && decision !== \"ask\") return undefined;",
63116
+ " const reason = hasDecision ? specific?.permissionDecisionReason : output.reason;",
63117
+ " return {",
63118
+ " kind: decision,",
63119
+ " reason:",
63120
+ " (typeof reason === \"string\" && sanitizeBlockReason(reason)) ||",
63121
+ " (decision === \"ask\" ? \"A preToolUse hook asked for confirmation.\" : \"Blocked by a preToolUse hook.\"),",
63122
+ " };",
63123
+ "}",
63124
+ "",
63125
+ "async function allowsToolCall(",
63126
+ " decision: ToolHookDecision,",
63127
+ " ctx: ExtensionContext | undefined,",
63128
+ "): Promise<boolean> {",
63129
+ " if (decision.kind !== \"ask\" || !ctx?.hasUI) return false;",
63130
+ " try {",
63131
+ " return await ctx.ui.confirm(\"Allow this tool call?\", decision.reason);",
63132
+ " } catch {",
63133
+ " return false;",
63134
+ " }",
63135
+ "}"
63136
+ ];
63137
+ /**
63138
+ * Runs a hook command through the platform shell with `input` as its stdin
63139
+ * (empty when the event has no payload, so a command that reads stdin never
63140
+ * waits on Pi's own), bounded by the hook's `timeout` in seconds (Claude
63141
+ * Code's default of 600 when unset, as in the OpenCode-style plugin). A stdin
63142
+ * the command never reads is not an error.
63143
+ *
63144
+ * The command runs in its own process group (except on Windows), so a command
63145
+ * past its timeout is killed together with everything it started, and the
63146
+ * call rejects with a `HookTimeoutError` right away rather than waiting for a
63147
+ * descendant still holding its output open. Like `promisify(exec)`, which
63148
+ * earlier versions used, a non-zero exit rejects with an error carrying
63149
+ * `code`, `stdout` and `stderr`, and more than 1 MiB on either stream rejects
63150
+ * and kills the command.
63151
+ *
63152
+ * A detached group does not get the terminal's Ctrl+C, so the extension
63153
+ * kills every command still running on `session_shutdown`, after the other
63154
+ * handlers (including a `sessionEnd` hook's) have run: Pi awaits them in
63155
+ * registration order. A Pi process killed outright never fires it, and since
63156
+ * the timeout timer lives in that process too, its commands then keep running
63157
+ * with no deadline until they exit on their own.
63158
+ */
63159
+ const RUN_HELPER_LINES = [
63160
+ "const MAX_HOOK_OUTPUT_LENGTH = 1024 * 1024;",
63161
+ "",
63162
+ "class HookTimeoutError extends Error {}",
63163
+ "",
63164
+ "// Kills of the commands still running, for `session_shutdown`.",
63165
+ "const runningHookCommands = new Set<() => void>();",
63166
+ "",
63167
+ "function run(",
63168
+ " command: string,",
63169
+ " { input = \"\", seconds }: { input?: string; seconds: number },",
63170
+ "): Promise<{ stdout: string; stderr: string }> {",
63171
+ " return new Promise((resolve, reject) => {",
63172
+ " const detached = process.platform !== \"win32\";",
63173
+ " const child = spawn(command, { shell: true, detached, windowsHide: true });",
63174
+ " const output = { stdout: \"\", stderr: \"\" };",
63175
+ " let settled = false;",
63176
+ " const finish = (error?: Error) => {",
63177
+ " if (settled) return;",
63178
+ " settled = true;",
63179
+ " clearTimeout(timer);",
63180
+ " runningHookCommands.delete(killTree);",
63181
+ " if (error) reject(error);",
63182
+ " else resolve(output);",
63183
+ " };",
63184
+ " const killTree = () => {",
63185
+ " try {",
63186
+ " if (detached && child.pid !== undefined) process.kill(-child.pid, \"SIGKILL\");",
63187
+ " else child.kill(\"SIGKILL\");",
63188
+ " } catch {",
63189
+ " // Already gone.",
63190
+ " }",
63191
+ " child.stdout?.destroy();",
63192
+ " child.stderr?.destroy();",
63193
+ " };",
63194
+ " runningHookCommands.add(killTree);",
63195
+ " const timer = setTimeout(() => {",
63196
+ " killTree();",
63197
+ " finish(new HookTimeoutError(`Hook command timed out after ${seconds} seconds.`));",
63198
+ " }, seconds * 1000);",
63199
+ " for (const stream of [\"stdout\", \"stderr\"] as const) {",
63200
+ " child[stream]?.setEncoding(\"utf8\");",
63201
+ " child[stream]?.on(\"data\", (chunk: string) => {",
63202
+ " output[stream] += chunk;",
63203
+ " if (output[stream].length <= MAX_HOOK_OUTPUT_LENGTH) return;",
63204
+ " killTree();",
63205
+ " finish(new Error(`Hook command wrote more than 1 MiB to ${stream}.`));",
63206
+ " });",
63207
+ " }",
63208
+ " child.on(\"error\", (error) => finish(error));",
63209
+ " child.on(\"close\", (code, signal) => {",
63210
+ " if (code === 0) return finish();",
63211
+ " finish(",
63212
+ " Object.assign(new Error(`Command failed: ${command}`), {",
63213
+ " code,",
63214
+ " signal,",
63215
+ " stdout: output.stdout,",
63216
+ " stderr: output.stderr,",
63217
+ " }),",
63218
+ " );",
63219
+ " });",
63220
+ " child.stdin?.on(\"error\", () => {});",
63221
+ " child.stdin?.end(input);",
63222
+ " });",
63223
+ "}"
63224
+ ];
63225
+ /**
63226
+ * Helper emitted alongside blocking handlers. `run` rejects on a
62331
63227
  * non-zero exit with an error carrying `stdout` / `stderr` / `code`, so the
62332
63228
  * reason is derived from the rejection rather than from a resolved exit code.
62333
63229
  * A command that could not be run at all (spawn failure, `maxBuffer` overflow)
@@ -62431,7 +63327,9 @@ function collectPiHandlers({ effectiveHooks, eventMap }) {
62431
63327
  handlers.push({
62432
63328
  command: def.command,
62433
63329
  matcher: def.matcher ? def.matcher : void 0,
62434
- onlyOnError: PI_ERROR_GATED_CANONICAL_EVENTS.has(canonicalEvent)
63330
+ onlyOnError: PI_ERROR_GATED_CANONICAL_EVENTS.has(canonicalEvent),
63331
+ ...hookTimingOf(def),
63332
+ ...PI_TOOL_EVENTS.has(piEvent) && STDIN_PAYLOAD_EVENTS[canonicalEvent] ? { payload: STDIN_PAYLOAD_EVENTS[canonicalEvent] } : {}
62435
63333
  });
62436
63334
  }
62437
63335
  if (handlers.length > 0) {
@@ -62446,22 +63344,63 @@ function buildCommandLines({ handler, usesToolName, blocking, dialect }) {
62446
63344
  const lines = [];
62447
63345
  const conditions = [];
62448
63346
  if (handler.onlyOnError) conditions.push("event.isError");
62449
- if (usesToolName && handler.matcher) conditions.push(`new RegExp(${matcherToEmbeddedLiteral(handler.matcher)}).test(event.toolName)`);
63347
+ if (usesToolName && handler.matcher) conditions.push(`matchesTool(new RegExp(${matcherToEmbeddedLiteral(handler.matcher)}), event.toolName)`);
62450
63348
  const gated = conditions.length > 0;
62451
63349
  const indent = gated ? " " : " ";
62452
- const embeddedCommand = JSON.stringify(handler.command);
63350
+ const options = [...handler.payload ? [`input: ${payloadAccessorName(handler.payload)}()`] : [], `seconds: ${handler.timeout}`];
63351
+ const runCall = `run(${JSON.stringify(handler.command)}, { ${options.join(", ")} })`;
62453
63352
  if (gated) lines.push(` if (${conditions.join(" && ")}) {`);
62454
63353
  const onFailure = failureLinesByMode(dialect)[blocking];
62455
- if (onFailure.length > 0) {
63354
+ if (blocking === "tool") {
63355
+ lines.push(`${indent}try {`);
63356
+ lines.push(`${indent} const decision = toolHookDecision((await ${runCall}).stdout);`);
63357
+ lines.push(`${indent} if (decision && !(await allowsToolCall(decision, ctx))) return { block: true, reason: decision.reason };`);
63358
+ lines.push(`${indent}} catch (error) {`);
63359
+ if (handler.failClosed === false) {
63360
+ lines.push(`${indent} if (error instanceof HookTimeoutError) {`);
63361
+ lines.push(`${indent} console.error("[rulesync-hooks] preToolUse hook timed out");`);
63362
+ lines.push(`${indent} } else {`);
63363
+ for (const line of onFailure) lines.push(`${indent} ${line}`);
63364
+ lines.push(`${indent} }`);
63365
+ } else for (const line of onFailure) lines.push(`${indent} ${line}`);
63366
+ lines.push(`${indent}}`);
63367
+ } else if (onFailure.length > 0) {
62456
63368
  lines.push(`${indent}try {`);
62457
- lines.push(`${indent} await run(${embeddedCommand});`);
63369
+ lines.push(`${indent} await ${runCall};`);
62458
63370
  lines.push(`${indent}} catch (error) {`);
62459
63371
  for (const line of onFailure) lines.push(`${indent} ${line}`);
62460
63372
  lines.push(`${indent}}`);
62461
- } else lines.push(`${indent}await run(${embeddedCommand});`);
63373
+ } else lines.push(`${indent}await ${runCall};`);
62462
63374
  if (gated) lines.push(" }");
62463
63375
  return lines;
62464
63376
  }
63377
+ /** The per-invocation closure a handler calls for its serialized payload. */
63378
+ function payloadAccessorName(hookEventName) {
63379
+ return `${hookEventName.charAt(0).toLowerCase()}${hookEventName.slice(1)}Input`;
63380
+ }
63381
+ /** Lazily serialized payloads the handlers of one subscription use. */
63382
+ function buildPayloadLines(handlers) {
63383
+ const payloads = [...new Set(handlers.flatMap((h) => h.payload ? [h.payload] : []))];
63384
+ const lines = [];
63385
+ for (const payload of payloads) {
63386
+ const accessor = payloadAccessorName(payload);
63387
+ const extra = STDIN_PAYLOAD_EXTRA_FIELDS[payload] ?? "";
63388
+ const extraArgument = extra ? `, { ${extra} }` : "";
63389
+ lines.push(` let ${accessor}Cache: string | undefined;`);
63390
+ lines.push(` const ${accessor} = () => (${accessor}Cache ??= toolHookInput(${JSON.stringify(payload)}, event, ctx${extraArgument}));`);
63391
+ }
63392
+ return lines;
63393
+ }
63394
+ /**
63395
+ * The handler's parameter list. `ctx` is the second handler argument, so the
63396
+ * prompt gate and the payload builders (which read the session id and cwd)
63397
+ * name both.
63398
+ */
63399
+ function handlerParams({ handlers, readsEvent, isPromptGate }) {
63400
+ const usesPayload = handlers.some((h) => h.payload);
63401
+ if (isPromptGate || usesPayload) return "event, ctx";
63402
+ return readsEvent || handlers.some((h) => h.onlyOnError) ? "event" : "";
63403
+ }
62465
63404
  function buildSubscriptionLines(handlerGroups, dialect) {
62466
63405
  const lines = [];
62467
63406
  for (const [piEvent, handlers] of Object.entries(handlerGroups)) {
@@ -62471,13 +63410,17 @@ function buildSubscriptionLines(handlerGroups, dialect) {
62471
63410
  const isSessionStopGate = blocking === "sessionStop";
62472
63411
  const collectsStopFailures = isSettleGate || isSessionStopGate;
62473
63412
  const usesToolName = PI_TOOL_EVENTS.has(piEvent) && handlers.some((h) => h.matcher);
62474
- const usesErrorFlag = handlers.some((h) => h.onlyOnError);
62475
63413
  const gatesOnAssistant = PI_ASSISTANT_MESSAGE_EVENTS.has(piEvent);
62476
- const params = isPromptGate ? "event, ctx" : usesToolName || usesErrorFlag || gatesOnAssistant || isPromptGate || collectsStopFailures ? "event" : "";
63414
+ const params = handlerParams({
63415
+ handlers,
63416
+ readsEvent: usesToolName || gatesOnAssistant || collectsStopFailures,
63417
+ isPromptGate
63418
+ });
62477
63419
  lines.push(` pi.on(${JSON.stringify(piEvent)}, async (${params}) => {`);
62478
63420
  if (gatesOnAssistant) lines.push(` if (event.message.role !== "assistant") return;`);
62479
63421
  if (isPromptGate) lines.push(` if (event.source === "extension") ${dialect.promptPassLine}`);
62480
63422
  if (collectsStopFailures) lines.push(" const stopHookFailures: unknown[] = [];");
63423
+ lines.push(...buildPayloadLines(handlers));
62481
63424
  for (const handler of handlers) lines.push(...buildCommandLines({
62482
63425
  handler,
62483
63426
  usesToolName,
@@ -62513,6 +63456,10 @@ function buildSubscriptionLines(handlerGroups, dialect) {
62513
63456
  }
62514
63457
  return lines;
62515
63458
  }
63459
+ /** Whether a handler belongs to a tool event, where its matcher is tested. */
63460
+ function handlerGroupHasToolEvent(handlerGroups, handler) {
63461
+ return Object.entries(handlerGroups).some(([piEvent, handlers]) => PI_TOOL_EVENTS.has(piEvent) && handlers.includes(handler));
63462
+ }
62516
63463
  /**
62517
63464
  * Generate the rulesync-owned Pi extension (a TypeScript module with a
62518
63465
  * default-export factory receiving Pi's ExtensionAPI) that subscribes to the
@@ -62527,6 +63474,12 @@ function buildSubscriptionLines(handlerGroups, dialect) {
62527
63474
  * command's output as feedback.
62528
63475
  * `postToolUse` and `postToolUseFailure` share Pi's `tool_result` event; the
62529
63476
  * latter's commands run only when `event.isError` is set.
63477
+ * Commands on the tool events receive Claude Code's hook input on stdin (see
63478
+ * `STDIN_PAYLOAD_EVENTS`), and a tool matcher is tested against both Pi's tool
63479
+ * name and its canonical Claude Code name. On `tool_call`, a command that exits
63480
+ * 0 with a JSON deny decision also denies the call, and one past its `timeout`
63481
+ * denies it unless the hook sets `failClosed: false`, mirroring the
63482
+ * OpenCode-style plugin.
62530
63483
  *
62531
63484
  * @see https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/extensions.md
62532
63485
  */
@@ -62546,7 +63499,9 @@ function generatePiExtensionCode({ config, supportedEvents, eventMap, dialect =
62546
63499
  const hasPromptGate = Boolean(handlerGroups[PI_PROMPT_BLOCKING_EVENT]);
62547
63500
  const hasSettleGate = Boolean(handlerGroups[PI_SETTLE_BLOCKING_EVENT]);
62548
63501
  const hasSessionStopGate = Boolean(handlerGroups[OMP_SESSION_STOP_BLOCKING_EVENT]);
62549
- const needsBlockReasonHelper = Boolean(handlerGroups[PI_BLOCKING_EVENT]) || hasPromptGate || hasSettleGate || hasSessionStopGate;
63502
+ const needsToolHelpers = Object.values(handlerGroups).flat().some((h) => h.payload || h.matcher && handlerGroupHasToolEvent(handlerGroups, h));
63503
+ const hasToolGate = Boolean(handlerGroups[PI_BLOCKING_EVENT]);
63504
+ const needsBlockReasonHelper = hasToolGate || hasPromptGate || hasSettleGate || hasSessionStopGate;
62550
63505
  const lines = ["// Generated by rulesync. Do not edit manually."];
62551
63506
  if (subscriptionLines.length === 0) {
62552
63507
  lines.push("export default function () {}");
@@ -62556,34 +63511,33 @@ function generatePiExtensionCode({ config, supportedEvents, eventMap, dialect =
62556
63511
  const importedTypes = [
62557
63512
  ...hasSettleGate ? ["AgentBeforeSettleEvent", "AgentBeforeSettleEventResult"] : [],
62558
63513
  "ExtensionAPI",
62559
- ...hasPromptGate ? ["ExtensionContext"] : []
63514
+ ...hasPromptGate || needsToolHelpers ? ["ExtensionContext"] : []
62560
63515
  ].join(", ");
62561
- lines.push("import { exec } from \"node:child_process\";");
62562
- lines.push("import { promisify } from \"node:util\";");
63516
+ lines.push("import { spawn } from \"node:child_process\";");
63517
+ if (needsToolHelpers) {
63518
+ lines.push("import { homedir } from \"node:os\";");
63519
+ lines.push(dialect.pathResolverLines === OMP_PATH_RESOLVER_LINES ? "import { join as joinPath, resolve as resolvePath, win32 as win32Path } from \"node:path\";" : "import { join as joinPath, resolve as resolvePath } from \"node:path\";");
63520
+ lines.push("import { fileURLToPath } from \"node:url\";");
63521
+ }
62563
63522
  lines.push("");
62564
63523
  lines.push(`import type { ${importedTypes} } from ${JSON.stringify(dialect.typesPackage)};`);
62565
63524
  lines.push("");
62566
- lines.push("const run = promisify(exec);");
62567
- lines.push("");
62568
- if (needsBlockReasonHelper) {
62569
- lines.push(...BLOCK_REASON_HELPER_LINES);
62570
- lines.push("");
62571
- }
62572
- if (hasPromptGate) {
62573
- lines.push(...PROMPT_GATE_HELPER_LINES);
62574
- lines.push("");
62575
- }
62576
- if (hasSettleGate || hasSessionStopGate) {
62577
- lines.push(...STOP_HOOK_BLOCK_HELPER_LINES);
62578
- lines.push("");
62579
- }
62580
- if (hasSettleGate) {
62581
- lines.push(...STOP_HOOK_HELPER_LINES);
62582
- lines.push("");
62583
- }
63525
+ const helperBlocks = [
63526
+ [true, RUN_HELPER_LINES],
63527
+ [needsBlockReasonHelper, BLOCK_REASON_HELPER_LINES],
63528
+ [hasToolGate, TOOL_DECISION_HELPER_LINES],
63529
+ [needsToolHelpers, needsToolHelpers ? buildToolPayloadHelperLines(dialect) : []],
63530
+ [hasPromptGate, PROMPT_GATE_HELPER_LINES],
63531
+ [hasSettleGate || hasSessionStopGate, STOP_HOOK_BLOCK_HELPER_LINES],
63532
+ [hasSettleGate, STOP_HOOK_HELPER_LINES]
63533
+ ];
63534
+ for (const [included, block] of helperBlocks) if (included) lines.push(...block, "");
62584
63535
  lines.push("export default function (pi: ExtensionAPI) {");
62585
63536
  if (hasSettleGate) lines.push(" let stopHookContinued = false;");
62586
63537
  lines.push(...subscriptionLines);
63538
+ lines.push(" pi.on(\"session_shutdown\", async () => {");
63539
+ lines.push(" for (const kill of [...runningHookCommands]) kill();");
63540
+ lines.push(" });");
62587
63541
  lines.push("}");
62588
63542
  lines.push("");
62589
63543
  return lines.join("\n");
@@ -65008,7 +65962,13 @@ const toolHooksFactories = /* @__PURE__ */ new Map([
65008
65962
  },
65009
65963
  ...converterCapabilities(BobHooks.getConverterConfig()),
65010
65964
  supportsMatcher: true,
65011
- matcherEvents: ["preToolUse", "postToolUse"]
65965
+ matcherEvents: BOB_MATCHER_HOOK_EVENTS,
65966
+ dropsUnknownOverrideEvents: true,
65967
+ overrideOnlyEvents: BOB_NATIVE_HOOK_EVENTS,
65968
+ overrideOptIn: {
65969
+ events: BOB_OPT_IN_HOOK_EVENTS,
65970
+ note: "They need Bob Shell 2.1.0 or later, and an older Bob Shell ignores the whole hooks block of a settings file that names them."
65971
+ }
65012
65972
  }],
65013
65973
  ["continue", {
65014
65974
  class: ContinueHooks,
@@ -65334,12 +66294,26 @@ var HooksProcessor = class extends FeatureProcessor {
65334
66294
  ...overrideHooks
65335
66295
  };
65336
66296
  {
65337
- const skipped = unsupportedEventNames({
66297
+ const optInEvents = factory.overrideOptIn?.events ?? {};
66298
+ const isOptIn = (e) => Object.hasOwn(optInEvents, e);
66299
+ const overrideKeys = new Set(Object.keys(overrideHooks));
66300
+ const skippedEvents = unsupportedEventNames({
65338
66301
  factory,
65339
66302
  sharedHooks,
65340
66303
  effectiveHooks
65341
66304
  });
66305
+ const skipped = skippedEvents.filter((e) => !isOptIn(e));
66306
+ const optIn = skippedEvents.filter(isOptIn).filter((e) => Object.hasOwn(sharedHooks, e) && !overrideKeys.has(optInEvents[e] ?? ""));
66307
+ const misnamed = skippedEvents.filter(isOptIn).filter((e) => overrideKeys.has(e));
65342
66308
  if (skipped.length > 0) this.logger.warn(`Skipped hook event(s) for ${this.toolTarget} (not supported): ${skipped.join(", ")}`);
66309
+ if (optIn.length > 0) {
66310
+ const nativeNames = optIn.map((e) => optInEvents[e]).join(", ");
66311
+ this.logger.warn(`Skipped hook event(s) for ${this.toolTarget}: ${optIn.join(", ")}. ${factory.overrideOptIn?.note} To opt in, author them under the "${overrideKey}.hooks" override with the native name(s) ${nativeNames}.`);
66312
+ }
66313
+ if (misnamed.length > 0) {
66314
+ const nativeNames = misnamed.map((e) => optInEvents[e]).join(", ");
66315
+ this.logger.warn(`Skipped "${overrideKey}.hooks" key(s) for ${this.toolTarget}: ${misnamed.join(", ")}. Use the native name(s) ${nativeNames} instead.`);
66316
+ }
65343
66317
  }
65344
66318
  {
65345
66319
  const supportedHookTypes = new Set(factory.supportedHookTypes);
@@ -73299,7 +74273,8 @@ const HERMES_OPAQUE_MAPPING_KEYS = [
73299
74273
  * alias — `auth` (`oauth` for OAuth 2.1/PKCE), mTLS `client_cert` (string PEM
73300
74274
  * path, or `[cert, key]`/`[cert, key, password]` list) and `client_key`,
73301
74275
  * `connect_timeout` (seconds), `supports_parallel_tool_calls`, `protocol`,
73302
- * `lazy`, `events` (see {@link copyHermesBoolLikeFields}), `keepalive_interval`,
74276
+ * `lazy`, `events` (see {@link copyHermesBoolLikeFields}), `single_instance`,
74277
+ * `keepalive_interval`,
73303
74278
  * `elicitation`, `trust`, `identity_header`, and
73304
74279
  * the cost keys (see {@link copyHermesCostFields}) —
73305
74280
  * verbatim from `source` to `target`. Field names are identical on both sides
@@ -73350,6 +74325,10 @@ function copyHermesAdvancedFields(source, target, logger) {
73350
74325
  target.skip_preflight = source.skip_preflight;
73351
74326
  copied = true;
73352
74327
  }
74328
+ if (typeof source.single_instance === "boolean") {
74329
+ target.single_instance = source.single_instance;
74330
+ copied = true;
74331
+ }
73353
74332
  if (typeof source.keepalive_interval === "number") {
73354
74333
  target.keepalive_interval = source.keepalive_interval;
73355
74334
  copied = true;
@@ -83941,7 +84920,7 @@ function buildVscodeCommandLists({ rules, toolLabel, logger, prefixSemantics = "
83941
84920
  };
83942
84921
  }
83943
84922
  // src/features/permissions/bob-permissions.ts
83944
- const TOOL_LABEL = "IBM Bob";
84923
+ const TOOL_LABEL$1 = "IBM Bob";
83945
84924
  /** The top-level settings key holding Bob's auto-approval configuration. */
83946
84925
  const APPROVAL_KEY$1 = "approval";
83947
84926
  /** The top-level settings key holding Bob's per-feature auto-approve toggles. */
@@ -84023,7 +85002,7 @@ function warnAboutSkippedCategories({ permission, bashStated, authorsGroupSwitch
84023
85002
  if (skipped.length === 0) return;
84024
85003
  const names = skipped.map((category) => `'${category}'`).join(", ");
84025
85004
  const hint = authorsGroupSwitches ? "" : ` ${GROUP_SWITCH_HINT}`;
84026
- warnWithFallback(logger, bashStated ? `${TOOL_LABEL} only models shell-command permissions (${SURFACE_LABEL}); ${names} allow rules cannot be represented and were skipped.${hint}` : `${TOOL_LABEL} only models shell-command permissions (${SURFACE_LABEL}), and .rulesync/permissions.jsonc states no 'bash' category, so ${names} ${skipped.length === 1 ? "was" : "were"} skipped and the command lists were left untouched.${hint}`);
85005
+ warnWithFallback(logger, bashStated ? `${TOOL_LABEL$1} only models shell-command permissions (${SURFACE_LABEL}); ${names} allow rules cannot be represented and were skipped.${hint}` : `${TOOL_LABEL$1} only models shell-command permissions (${SURFACE_LABEL}), and .rulesync/permissions.jsonc states no 'bash' category, so ${names} ${skipped.length === 1 ? "was" : "were"} skipped and the command lists were left untouched.${hint}`);
84027
85006
  }
84028
85007
  /**
84029
85008
  * Warn about what the `bob` override writes that Bob does not document: an
@@ -84043,7 +85022,7 @@ function warnAboutUndocumentedSettings({ override, logger }) {
84043
85022
  ...outsideWorkspace.length > 0 ? [`'enableOutsideWorkspace' for group(s) ${quoteAll(outsideWorkspace)}`] : []
84044
85023
  ];
84045
85024
  if (parts.length === 0) return;
84046
- warnWithFallback(logger, `${TOOL_LABEL} permissions: the bob override sets ${parts.join("; ")}, which Bob does not document; they were written as authored. Bob documents the groups ${quoteAll(BOB_PERMISSION_GROUP_IDS)}, the '${AUTO_APPROVE_KEY}' toggle(s) ${quoteAll(BOB_AUTO_APPROVE_KEYS)}, and 'enableOutsideWorkspace' for the '${OUTSIDE_WORKSPACE_GROUP_ID}' group only.`);
85025
+ warnWithFallback(logger, `${TOOL_LABEL$1} permissions: the bob override sets ${parts.join("; ")}, which Bob does not document; they were written as authored. Bob documents the groups ${quoteAll(BOB_PERMISSION_GROUP_IDS)}, the '${AUTO_APPROVE_KEY}' toggle(s) ${quoteAll(BOB_AUTO_APPROVE_KEYS)}, and 'enableOutsideWorkspace' for the '${OUTSIDE_WORKSPACE_GROUP_ID}' group only.`);
84047
85026
  }
84048
85027
  /**
84049
85028
  * Name what the `bob` override newly auto-approves. The settings file is Bob's
@@ -84062,7 +85041,7 @@ function warnAboutNewAutoApprovals({ settings, override, filePath, logger }) {
84062
85041
  ...Object.entries(override?.autoApprove ?? {}).filter(([key, value]) => value === true && existingAutoApprove[key] !== true).map(([key]) => quoteValueForWarning(`${AUTO_APPROVE_KEY}.${key}`))
84063
85042
  ]);
84064
85043
  if (added.size === 0) return;
84065
- warnWithFallback(logger, `${TOOL_LABEL} permissions: the bob override now auto-approves ${[...added].join(", ")} in ${filePath}, Bob's user settings, so this applies to every project on this machine. Check it if .rulesync/permissions.jsonc arrived with a repository you cloned.`);
85044
+ warnWithFallback(logger, `${TOOL_LABEL$1} permissions: the bob override now auto-approves ${[...added].join(", ")} in ${filePath}, Bob's user settings, so this applies to every project on this machine. Check it if .rulesync/permissions.jsonc arrived with a repository you cloned.`);
84066
85045
  }
84067
85046
  /**
84068
85047
  * Split the canonical `bash` rules — plus the restricting rules of the
@@ -84079,7 +85058,7 @@ function buildBobCommandLists({ permission, logger }) {
84079
85058
  normalizePattern: widenToPrefixGlob$1
84080
85059
  });
84081
85060
  warnAboutUnwrittenCommandRules({
84082
- toolLabel: TOOL_LABEL,
85061
+ toolLabel: TOOL_LABEL$1,
84083
85062
  surfaceLabel: SURFACE_LABEL,
84084
85063
  foreignRestrictingCategories,
84085
85064
  shadowedAllowPatterns,
@@ -84094,7 +85073,7 @@ function buildBobCommandLists({ permission, logger }) {
84094
85073
  for (const pattern of deny) lists[pattern] = "deny";
84095
85074
  return buildVscodeCommandLists({
84096
85075
  rules: lists,
84097
- toolLabel: TOOL_LABEL,
85076
+ toolLabel: TOOL_LABEL$1,
84098
85077
  logger,
84099
85078
  prefixSemantics: "documented-prefix"
84100
85079
  });
@@ -84266,7 +85245,7 @@ var BobPermissions = class BobPermissions extends ToolPermissions {
84266
85245
  const rules = importVscodeCommandLists({
84267
85246
  allowed: toStringArray$1(entry?.approvedCommands),
84268
85247
  denied: toStringArray$1(entry?.deniedCommands),
84269
- toolLabel: TOOL_LABEL,
85248
+ toolLabel: TOOL_LABEL$1,
84270
85249
  logger,
84271
85250
  prefixSemantics: "documented-prefix"
84272
85251
  });
@@ -85063,6 +86042,7 @@ const CLAUDECODE_UNHONORED_KEY_SOURCES = {
85063
86042
  disableMobileSimulatorTools: "managed settings",
85064
86043
  disableRemotePreviewScripts: "managed settings",
85065
86044
  disableSideloadFlags: "managed settings",
86045
+ enforceAnthropicSignIn: "managed settings",
85066
86046
  externalEditorContext: "~/.claude.json",
85067
86047
  forceRemoteSettingsRefresh: "managed settings",
85068
86048
  gatewayInternalNetworks: "managed settings",
@@ -85215,12 +86195,14 @@ const CLAUDECODE_ENV_IGNORED_IN_EVERY_FILE = /* @__PURE__ */ new Set([
85215
86195
  "CLAUDE_CODE_DISABLE_MOUNTED_DRIVE_RM_PROMPT",
85216
86196
  "CLAUDE_CODE_DISABLE_POWERSHELL_CMD_RM_DENY",
85217
86197
  "CLAUDE_CODE_DISABLE_SUBSTITUTION_RM_PROMPT",
86198
+ "CLAUDE_CODE_DISABLE_ULTRAREVIEW_TRUST_CHECK",
85218
86199
  "CLAUDE_CODE_EVEN_MORE_DANGEROUSLY_SKIP_PERMISSIONS",
85219
86200
  "CLAUDE_CODE_MESSAGING_SOCKET",
85220
86201
  "CLAUDE_CODE_MESSAGING_TOKEN",
85221
86202
  "CLAUDE_CODE_PROJECT_DIR_NAME",
85222
86203
  "CLAUDE_CODE_REMOTE",
85223
86204
  "CLAUDE_CODE_RESTRICTED",
86205
+ "CLAUDE_CODE_STRICT_INLINE_SHELL_RM_PROMPT",
85224
86206
  "CLAUDE_CODE_WARN_DISK_FREE_GIB",
85225
86207
  "CLAUDE_CODE_WARN_MEMORY_FREE_GIB"
85226
86208
  ]);
@@ -85232,6 +86214,13 @@ const CLAUDECODE_ENV_IGNORED_IN_EVERY_FILE = /* @__PURE__ */ new Set([
85232
86214
  * dialog, and whether it processes attachments or expands `@` file mentions,
85233
86215
  * and the screen reader (`CLAUDE_AX_*`) variables. Claude Code drops them there, so they are skipped at project scope and emitted only under `--global`.
85234
86216
  *
86217
+ * `OTEL_RESOURCE_INCLUDE_HOST` (Claude Code v2.1.326+) adds the machine's name
86218
+ * and ID to telemetry, so it sits with the telemetry group. The reference lists
86219
+ * `CLAUDE_CODE_EXPERIMENTAL_CODE_MODE` separately: Code Mode follows it only
86220
+ * from the shell, user settings or a `--settings` file, and a project `0` does
86221
+ * not keep Code Mode off either, so any project value is skipped while user
86222
+ * settings (`--global`) still honor it.
86223
+ *
85235
86224
  * Only the names the settings reference lists are covered; its directory,
85236
86225
  * Windows and sign-in groups are introduced with "such as", so an unlisted member of those
85237
86226
  * families is still written. Windows variable names are case-insensitive, so
@@ -85250,6 +86239,7 @@ const CLAUDECODE_ENV_PROJECT_IGNORED_NAMES = /* @__PURE__ */ new Set([
85250
86239
  "CLAUDE_CODE_DISABLE_FILE_MENTIONS",
85251
86240
  "CLAUDE_CODE_ENABLE_TELEMETRY",
85252
86241
  "CLAUDE_CODE_ENHANCED_TELEMETRY_BETA",
86242
+ "CLAUDE_CODE_EXPERIMENTAL_CODE_MODE",
85253
86243
  "CLAUDE_CODE_OAUTH_REFRESH_TOKEN",
85254
86244
  "CLAUDE_CODE_OAUTH_SCOPES",
85255
86245
  "CLAUDE_CODE_OAUTH_TOKEN",
@@ -85268,6 +86258,7 @@ const CLAUDECODE_ENV_PROJECT_IGNORED_NAMES = /* @__PURE__ */ new Set([
85268
86258
  "OTEL_EXPORTER_PROMETHEUS_PORT",
85269
86259
  "OTEL_LOG_ASSISTANT_RESPONSES",
85270
86260
  "OTEL_LOG_RAW_API_BODIES",
86261
+ "OTEL_RESOURCE_INCLUDE_HOST",
85271
86262
  "TEMP",
85272
86263
  "TMP",
85273
86264
  "TMPDIR"
@@ -92779,6 +93770,263 @@ function convertFactorydroidToRulesyncPermissions({ allow, deny }) {
92779
93770
  for (const pattern of deny) bash[pattern] = "deny";
92780
93771
  return { permission: Object.keys(bash).length > 0 ? { bash } : {} };
92781
93772
  }
93773
+ // src/features/permissions/gitlabduo-permissions.ts
93774
+ const GITLABDUO_GLOBAL_ONLY_MESSAGE = "GitLab Duo CLI reads the permissions setting only from the user settings file; use --global to sync ~/.gitlab/duo/settings.json";
93775
+ const TOOL_LABEL = "GitLab Duo CLI";
93776
+ const PERMISSIONS_KEY = "permissions";
93777
+ /** The Duo tool that runs a shell command; the only one rulesync writes statements for. */
93778
+ const COMMAND_TOOL_NAME = "run_command";
93779
+ /** The server refuses a pattern longer than this (`MAX_PATTERN_LENGTH`). */
93780
+ const MAX_PATTERN_LENGTH = 256;
93781
+ /**
93782
+ * Characters a written pattern must not hold:
93783
+ * - `; & | < > $ \` ( ) { }` and line breaks are shell metacharacters the
93784
+ * server refuses in a command-tool pattern.
93785
+ * - Quotes and the backslash are taken off by the shell-style word split the
93786
+ * server reads a pattern through, so the pattern would be matched as
93787
+ * something other than what it says.
93788
+ * - `[` and `]` start an `fnmatch` character class inside a token, which the
93789
+ * canonical glob does not read the same way.
93790
+ */
93791
+ const UNSUPPORTED_PATTERN_CHARACTERS = /[;&|<>$`(){}\n\r'"\\[\]]/;
93792
+ /** Quotes and the backslash escape, which a shell-style word split takes off. */
93793
+ const SHELL_QUOTING_CHARACTERS = /['"\\]/g;
93794
+ /** A canonical pattern may spell "any arguments" as a trailing `:*` (`git:*`). */
93795
+ const TRAILING_ARGUMENT_WILDCARD = /:\*$/;
93796
+ /** Glob characters that make a Duo pattern match more than its literal spelling. */
93797
+ const GLOB_CHARACTERS = /[*?[\]]/;
93798
+ /**
93799
+ * Permissions adapter for GitLab Duo CLI.
93800
+ *
93801
+ * Duo CLI 10.5.0 reads a `permissions` array of
93802
+ * `{ action, resource, effect }` statements from the managed settings file and
93803
+ * the user's `~/.gitlab/duo/settings.json`. The project files
93804
+ * (`.gitlab/duo/settings.json`, `.gitlab/duo/settings.local.json`) are
93805
+ * deliberately not read for it, so this surface is **global only**.
93806
+ * @see https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/blob/v10.5.0/packages/core/settings/src/definitions.ts
93807
+ * @see https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/blob/v10.5.0/packages/core/settings/src/tool_permissions.ts
93808
+ *
93809
+ * Only `allow` is enforced: each allow statement is submitted to the GitLab
93810
+ * instance as a session pattern approval when a session starts. `ask` and
93811
+ * `deny` statements are accepted but only logged. rulesync therefore writes
93812
+ * allow statements only, and never one that could auto-approve something the
93813
+ * canonical file restricts:
93814
+ *
93815
+ * - Only canonical `bash` `allow` rules are written, as
93816
+ * `{ action: "run_command", resource: <pattern>, effect: "allow" }`. Other
93817
+ * categories have no Duo spelling that is known to match no wider than the
93818
+ * canonical rule (the server matches other tools' patterns against their raw
93819
+ * JSON arguments), so their allow rules are skipped with a warning.
93820
+ * - Every `deny` and `ask` rule under `bash` or the all-tools `*` category
93821
+ * withholds the allow rules that could match the same command, because Duo
93822
+ * cannot enforce the restriction itself. A deny is also reported: the command
93823
+ * is asked about, not blocked.
93824
+ * - The GitLab server matches a command-tool pattern token by token
93825
+ * (`CommandPatternMatcher`): a literal token must match exactly, `*` is one
93826
+ * token that does not start with `-`, and a token holding a glob is matched
93827
+ * on its own. That is never wider than the canonical glob, where `*` spans
93828
+ * any characters. A trailing `:*` is written as ` *`. A pattern the server
93829
+ * refuses (a lone `*`, `**`, shell metacharacters, more than 256 characters)
93830
+ * or would read differently (quotes, escapes, character classes) is skipped
93831
+ * with a warning.
93832
+ * @see https://gitlab.com/gitlab-org/gitlab/-/blob/master/ee/app/models/ai/duo_workflows/command_pattern_matcher.rb
93833
+ *
93834
+ * On generate, the statements rulesync owns — those for `run_command` — are
93835
+ * replaced, and every other statement and key of the file is kept, with the
93836
+ * comments outside the `permissions` array (the array is rewritten whole).
93837
+ * On import, `run_command` statements come back under `bash`. An allow is
93838
+ * skipped when its resource holds a glob, which the canonical glob would read
93839
+ * more widely than Duo does, or when the server would refuse it, since it
93840
+ * approves nothing in Duo but would approve the command for other tools.
93841
+ */
93842
+ var GitlabduoPermissions = class GitlabduoPermissions extends ToolPermissions {
93843
+ constructor(params) {
93844
+ super({
93845
+ ...params,
93846
+ fileContent: params.fileContent ?? "{}"
93847
+ });
93848
+ }
93849
+ /**
93850
+ * `settings.json` holds every Duo CLI setting, so rulesync never brings it
93851
+ * into existence just to hold nothing.
93852
+ */
93853
+ shouldSkipCreationWhenPayloadEmpty() {
93854
+ return true;
93855
+ }
93856
+ static getSettablePaths(_options = {}) {
93857
+ return {
93858
+ relativeDirPath: GITLABDUO_DIR,
93859
+ relativeFilePath: GITLABDUO_SETTINGS_FILE_NAME
93860
+ };
93861
+ }
93862
+ static async fromFile({ outputRoot = process.cwd(), validate = true, global = false }) {
93863
+ if (!global) throw new Error(GITLABDUO_GLOBAL_ONLY_MESSAGE);
93864
+ const paths = GitlabduoPermissions.getSettablePaths({ global });
93865
+ const fileContent = await readFileContentOrNull(join(outputRoot, paths.relativeDirPath, paths.relativeFilePath)) ?? "{}";
93866
+ return new GitlabduoPermissions({
93867
+ outputRoot,
93868
+ relativeDirPath: paths.relativeDirPath,
93869
+ relativeFilePath: paths.relativeFilePath,
93870
+ fileContent,
93871
+ validate,
93872
+ global: true
93873
+ });
93874
+ }
93875
+ static async fromRulesyncPermissions({ outputRoot = process.cwd(), rulesyncPermissions, logger, global = false }) {
93876
+ if (!global) throw new Error(GITLABDUO_GLOBAL_ONLY_MESSAGE);
93877
+ const paths = GitlabduoPermissions.getSettablePaths({ global });
93878
+ const filePath = join(outputRoot, paths.relativeDirPath, paths.relativeFilePath);
93879
+ const existingContent = await readFileContentOrNull(filePath) ?? "";
93880
+ const baseContent = existingContent.trim() === "" ? "{}" : existingContent;
93881
+ const existing = parseSettings({
93882
+ content: baseContent,
93883
+ filePath
93884
+ })[PERMISSIONS_KEY];
93885
+ const generated = convertRulesyncToGitlabduoStatements({
93886
+ config: rulesyncPermissions.getJson(),
93887
+ logger
93888
+ });
93889
+ let fileContent = baseContent;
93890
+ if (existing !== void 0 && !Array.isArray(existing)) warnWithFallback(logger, `${TOOL_LABEL}: '${PERMISSIONS_KEY}' in ${filePath} is not an array, so it was left untouched rather than overwritten, and no rule was written.`);
93891
+ else {
93892
+ const statements = [...(existing ?? []).filter((statement) => !(isPlainObject(statement) && statement.action === COMMAND_TOOL_NAME)), ...generated];
93893
+ if (statements.length > 0 || existing !== void 0) {
93894
+ const edits = modify(baseContent, [PERMISSIONS_KEY], statements.length > 0 ? statements : void 0, { formattingOptions: {
93895
+ insertSpaces: true,
93896
+ tabSize: 2
93897
+ } });
93898
+ fileContent = applyEdits(baseContent, edits);
93899
+ }
93900
+ }
93901
+ return new GitlabduoPermissions({
93902
+ outputRoot,
93903
+ relativeDirPath: paths.relativeDirPath,
93904
+ relativeFilePath: paths.relativeFilePath,
93905
+ fileContent,
93906
+ validate: true,
93907
+ global: true
93908
+ });
93909
+ }
93910
+ toRulesyncPermissions() {
93911
+ const selfPath = join(this.getRelativeDirPath(), this.getRelativeFilePath());
93912
+ const raw = parseSettings({
93913
+ content: this.getFileContent() || "{}",
93914
+ filePath: selfPath
93915
+ })[PERMISSIONS_KEY];
93916
+ const statements = Array.isArray(raw) ? raw : [];
93917
+ if (raw !== void 0 && !Array.isArray(raw)) warnWithFallback(void 0, `${TOOL_LABEL} ignores '${PERMISSIONS_KEY}' unless it is an array, so nothing was imported from ${selfPath}.`);
93918
+ const bash = {};
93919
+ const skippedAllows = [];
93920
+ for (const statement of statements) {
93921
+ if (!isDuoPermissionStatement(statement) || statement.action !== COMMAND_TOOL_NAME) continue;
93922
+ const { resource, effect } = statement;
93923
+ if (effect === "allow" && (GLOB_CHARACTERS.test(resource) || toGitlabduoCommandResource(resource) !== resource)) {
93924
+ skippedAllows.push(resource);
93925
+ continue;
93926
+ }
93927
+ const previous = bash[resource];
93928
+ if (previous === void 0 || rank(effect) > rank(previous)) bash[resource] = effect;
93929
+ }
93930
+ if (skippedAllows.length > 0) warnWithFallback(void 0, `The run_command allow statement(s) for ${uniq(skippedAllows).join(", ")} in ${selfPath} were not imported: a glob matches more as a canonical pattern than in ${TOOL_LABEL} (where '*' is one argument that is not a flag), and a pattern the GitLab server refuses approves nothing in Duo but would for other tools.`);
93931
+ const config = { permission: Object.keys(bash).length > 0 ? { [SHELL_PERMISSION_CATEGORY]: bash } : {} };
93932
+ return RulesyncPermissions.fromImportedFileContent({
93933
+ outputRoot: this.outputRoot,
93934
+ sourcePath: this.getRelativePathFromCwd(),
93935
+ fileContent: JSON.stringify(config, null, 2)
93936
+ });
93937
+ }
93938
+ };
93939
+ function rank(effect) {
93940
+ return effect === "deny" ? 2 : effect === "ask" ? 1 : 0;
93941
+ }
93942
+ function isDuoPermissionStatement(value) {
93943
+ return isPlainObject(value) && typeof value.action === "string" && value.action.length > 0 && typeof value.resource === "string" && (value.effect === "allow" || value.effect === "ask" || value.effect === "deny");
93944
+ }
93945
+ function parseSettings({ content, filePath }) {
93946
+ let parsed;
93947
+ try {
93948
+ parsed = parseJsonc(content);
93949
+ } catch (error) {
93950
+ throw new Error(`Failed to parse GitLab Duo CLI settings at ${filePath}: ${formatError(error)}`, { cause: error });
93951
+ }
93952
+ if (!isPlainObject(parsed)) throw new Error(`GitLab Duo CLI settings at ${filePath} must contain a JSON object.`);
93953
+ return parsed;
93954
+ }
93955
+ /**
93956
+ * A canonical command pattern as Duo's token matcher reads it: trimmed, runs
93957
+ * of whitespace collapsed to one space (Duo splits a command into words, so
93958
+ * `git push` and `git push` are one command), and a trailing `:*` ("any
93959
+ * arguments") spelled ` *`.
93960
+ */
93961
+ function normalizeGitlabduoCommandPattern(pattern) {
93962
+ let normalized = pattern.trim();
93963
+ if (TRAILING_ARGUMENT_WILDCARD.test(normalized)) normalized = `${normalized.slice(0, -2)} *`;
93964
+ return normalized.trim().split(/\s+/).join(" ");
93965
+ }
93966
+ /**
93967
+ * The Duo `resource` for a canonical `bash` allow pattern, or `null` when the
93968
+ * server would refuse it or read it differently from what it says. The result
93969
+ * never matches a command the canonical pattern does not match.
93970
+ */
93971
+ function toGitlabduoCommandResource(pattern) {
93972
+ const resource = normalizeGitlabduoCommandPattern(pattern);
93973
+ if (resource === "" || resource === "*" || resource.length > MAX_PATTERN_LENGTH) return null;
93974
+ if (UNSUPPORTED_PATTERN_CHARACTERS.test(resource)) return null;
93975
+ if (resource.includes("**")) return null;
93976
+ return resource;
93977
+ }
93978
+ /**
93979
+ * Convert the canonical config into the `run_command` allow statements Duo CLI
93980
+ * enforces, reporting every rule that could not be carried.
93981
+ */
93982
+ function convertRulesyncToGitlabduoStatements({ config, logger }) {
93983
+ const { rules, foreignRestrictingCategories, ignoredAllToolsAllowPatterns } = collectShellCommandRules(config.permission);
93984
+ const restrictions = uniq(rules.filter(({ action }) => action !== "allow").flatMap(({ pattern }) => [
93985
+ pattern,
93986
+ normalizeGitlabduoCommandPattern(pattern),
93987
+ normalizeGitlabduoCommandPattern(pattern.replaceAll(SHELL_QUOTING_CHARACTERS, ""))
93988
+ ]).filter((pattern) => pattern !== "")).map((pattern) => ({
93989
+ pattern,
93990
+ fromAllToolsCategory: false
93991
+ }));
93992
+ const budget = createIntersectionBudget();
93993
+ const shadowingRestrictions = createShadowingRestrictionsTest(restrictions, { budget });
93994
+ const resources = [];
93995
+ const shadowedAllowPatterns = [];
93996
+ const unsupportedPatterns = [];
93997
+ for (const { pattern, action } of rules) {
93998
+ if (action !== "allow") continue;
93999
+ const resource = toGitlabduoCommandResource(pattern);
94000
+ if (resource === null) {
94001
+ unsupportedPatterns.push(pattern);
94002
+ continue;
94003
+ }
94004
+ if (shadowingRestrictions(resource).length > 0) {
94005
+ shadowedAllowPatterns.push(pattern);
94006
+ continue;
94007
+ }
94008
+ resources.push(resource);
94009
+ }
94010
+ warnAboutUnwrittenCommandRules({
94011
+ toolLabel: TOOL_LABEL,
94012
+ surfaceLabel: `${PERMISSIONS_KEY} statements for ${COMMAND_TOOL_NAME}`,
94013
+ foreignRestrictingCategories,
94014
+ shadowedAllowPatterns: uniq(shadowedAllowPatterns),
94015
+ ignoredAllToolsAllowPatterns,
94016
+ intersectionBudgetExhausted: budget.remaining === 0,
94017
+ logger
94018
+ });
94019
+ const denyPatterns = uniq(rules.filter(({ action }) => action === "deny").map(({ pattern }) => pattern));
94020
+ if (denyPatterns.length > 0) warnWithFallback(logger, `${TOOL_LABEL} enforces only allow statements in '${PERMISSIONS_KEY}' (ask and deny are logged and ignored), so the deny rule(s) for ${denyPatterns.join(", ")} were not written. Those commands are asked about rather than blocked.`);
94021
+ const foreignAllowCategories = Object.entries(config.permission).filter(([category, categoryRules]) => category !== "bash" && category !== "*" && Object.values(categoryRules).includes("allow")).map(([category]) => category);
94022
+ if (foreignAllowCategories.length > 0) warnWithFallback(logger, `${TOOL_LABEL}: only 'bash' allow rules are written (as ${COMMAND_TOOL_NAME} statements), so the allow rules of '${foreignAllowCategories.join("', '")}' were skipped.`);
94023
+ if (unsupportedPatterns.length > 0) warnWithFallback(logger, `${TOOL_LABEL} refuses a ${COMMAND_TOOL_NAME} pattern that is a lone '*', holds '**' or a shell metacharacter, or is longer than ${MAX_PATTERN_LENGTH} characters, and reads quotes, escapes and '[...]' differently from the canonical glob, so the allow rule(s) for ${uniq(unsupportedPatterns).join(", ")} were skipped.`);
94024
+ return uniq(resources).map((resource) => ({
94025
+ action: COMMAND_TOOL_NAME,
94026
+ resource,
94027
+ effect: "allow"
94028
+ }));
94029
+ }
92782
94030
  // src/features/permissions/goose-permissions.ts
92783
94031
  const GOOSE_GLOBAL_ONLY_MESSAGE = "Goose permissions are global-only; use --global to sync ~/.config/goose/permission.yaml";
92784
94032
  const GOOSE_USER_KEY = "user";
@@ -105097,6 +106345,13 @@ const toolPermissionsFactories = /* @__PURE__ */ new Map([
105097
106345
  supportsGlobal: true
105098
106346
  }
105099
106347
  }],
106348
+ ["gitlabduo", {
106349
+ class: GitlabduoPermissions,
106350
+ meta: {
106351
+ supportsProject: false,
106352
+ supportsGlobal: true
106353
+ }
106354
+ }],
105100
106355
  ["goose", {
105101
106356
  class: GoosePermissions,
105102
106357
  meta: {
@@ -105880,6 +107135,11 @@ async function ensureAntigravityPluginManifests({ outputRoots, dryRun, logger })
105880
107135
  if (name !== dirName) warnOnceWithFallback(logger, `The Antigravity plugin directory ${quoteForLog(dirName)} is not lowercase kebab-case, which \`agy plugin validate --strict\` and the Marketplace reject, so ${quoteForLog(filePath)} names the plugin ${quoteForLog(name)}.`);
105881
107136
  noteName(name, filePath);
105882
107137
  const content = addTrailingNewline(JSON.stringify({ name }, null, 2));
107138
+ await warnIfWriteFollowsLink({
107139
+ logger,
107140
+ rootPath: outputRoot,
107141
+ targetPath: filePath
107142
+ });
105883
107143
  if (dryRun) logger.info(`[DRY RUN] Would write: ${stripControlCharacters(filePath)}`);
105884
107144
  else await writeFileContent(filePath, content);
105885
107145
  paths.push(ANTIGRAVITY_PLUGIN_MANIFEST_FILE_NAME);
@@ -105928,7 +107188,7 @@ function mergeEnabledPlugins({ existingContent, filePath, pluginNames }) {
105928
107188
  }
105929
107189
  });
105930
107190
  }
105931
- async function writeActivationFile({ filePath, relativePath, expectedContent, dryRun, logger }) {
107191
+ async function writeActivationFile({ rootPath, filePath, relativePath, expectedContent, dryRun, logger }) {
105932
107192
  const existingContent = await readFileContentOrNull(filePath);
105933
107193
  const normalizedExpected = addTrailingNewline(expectedContent);
105934
107194
  if (fileContentsEquivalent({
@@ -105936,6 +107196,11 @@ async function writeActivationFile({ filePath, relativePath, expectedContent, dr
105936
107196
  expected: normalizedExpected,
105937
107197
  existing: existingContent
105938
107198
  })) return false;
107199
+ await warnIfWriteFollowsLink({
107200
+ logger,
107201
+ rootPath,
107202
+ targetPath: filePath
107203
+ });
105939
107204
  if (dryRun) logger.info(`[DRY RUN] Would write: ${filePath}`);
105940
107205
  else await writeFileContent(filePath, normalizedExpected);
105941
107206
  logger.debug(`Hermes project-plugin activation requires ${relativePath}`);
@@ -105972,6 +107237,7 @@ async function activateHermesProjectPlugins({ pluginNames, dryRun, logger }) {
105972
107237
  const paths = [];
105973
107238
  logger.warn(`Hermes project plugins require explicit trust. Run Hermes from this trusted repository with ${HERMESAGENT_PROJECT_PLUGINS_ENV_VAR}=true. RuleSync does not persist this global setting.`);
105974
107239
  if (await writeActivationFile({
107240
+ rootPath: configRoot,
105975
107241
  filePath: configPath,
105976
107242
  relativePath: relativeConfigPath,
105977
107243
  expectedContent: expectedConfig,
@@ -107992,6 +109258,6 @@ const CHECKS_IMPORT_STRATEGY = {
107992
109258
  missingLabel: "check files",
107993
109259
  createdLabel: "check files"
107994
109260
  };
107995
- export { RulesyncRule as $, RULESYNC_RULES_RELATIVE_DIR_PATH as $n, getFileSizeAndExecutableBit as $t, CODEBUDDY_LOCAL_RULE_FILE_NAME as A, ToolTargetSchema as An, fallbackLogger as At, CLAUDECODE_LOCAL_RULE_FILE_NAME as B, RULESYNC_CONFIG_RELATIVE_FILE_PATH as Bn, assertDirectoryIfExists as Bt, LETTACODE_DIR as C, toPosixPath as Cn, SourceEntrySchema as Ct, COMMANDCODE_DIR as D, ALL_TOOL_TARGETS as Dn, ConsoleLogger as Dt, FACTORYDROID_SETTINGS_LOCAL_FILE_NAME as E, mapWithConcurrency as En, findControlCharacter as Et, sweepRefusalReason as F, FEATURE_SOURCE_TREE_ENTRIES as Fn, CLIError as Ft, toInstructionBudgetFile as G, RULESYNC_IGNORE_RELATIVE_FILE_PATH as Gn, assertWritablePathInsideRoot as Gt, CLAUDECODE_SETTINGS_LOCAL_FILE_NAME as H, RULESYNC_CURATED_RULES_RELATIVE_DIR_PATH as Hn, assertNoSymlinkBelowRoot as Ht, CODEXCLI_BASH_RULES_FILE_NAME as I, MAX_FILE_SIZE as In, ErrorCodes as It, getLocalSkillDirNames as J, RULESYNC_MCP_SCHEMA_URL as Jn, directoryExists as Jt, classifyRemoteName as K, RULESYNC_LOCAL_CONFIG_RELATIVE_FILE_PATH as Kn, checkPathTraversal as Kt, CODEXCLI_DIR as L, RULESYNC_AIIGNORE_RELATIVE_FILE_PATH as Ln, parseJsonc as Lt, AUGMENTCODE_SETTINGS_LOCAL_FILE_NAME as M, ALL_FEATURES_WITH_WILDCARD as Mn, withFallbackLoggerTarget as Mt, caseFoldIdentity as N, DEPRECATED_FEATURE_REPLACEMENTS as Nn, resetRunWarningState as Nt, COMMANDCODE_SETTINGS_LOCAL_FILE_NAME as O, ALL_TOOL_TARGETS_WITH_WILDCARD as On, JsonLogger as Ot, groupSpellingsByCaseFoldedIdentity as P, CURATED_RULES_FEATURE_SUBDIR as Pn, withWarnOnceScope as Pt, RulesyncSkillFrontmatterSchema as Q, RULESYNC_RELATIVE_DIR_PATH as Qn, findFilesByGlobs as Qt, CLAUDECODE_AGENT_MEMORY_LOCAL_DIR_NAME as R, RULESYNC_CHECKS_RELATIVE_DIR_PATH as Rn, PathOutsideRootError as Rt, QWENCODE_LOCAL_RULE_FILE_NAME as S, splitPathSegments as Sn, GITIGNORE_DESTINATION_KEY as St, FACTORYDROID_DIR as T, writeFileContent as Tn, getSourceTransport as Tt, CLAUDECODE_SKILLS_DIR_PATH as U, RULESYNC_CURATED_SKILLS_RELATIVE_DIR_PATH as Un, assertPathResolvesInsideRoot as Ut, CLAUDECODE_MEMORIES_DIR_NAME as V, RULESYNC_CONFIG_SCHEMA_URL as Vn, assertLandingOutsideVcsMetadata as Vt, findProjectInstructionBudgetFindings as W, RULESYNC_HOOKS_RELATIVE_FILE_PATH as Wn, assertTreeContainsNoSymlinks as Wt, RulesyncSubagentFrontmatterSchema as X, RULESYNC_PERMISSIONS_RELATIVE_FILE_PATH as Xn, fileExists as Xt, RulesyncSubagent as Y, RULESYNC_NPM_SOURCES_LOCK_RELATIVE_FILE_PATH as Yn, ensureDir as Yt, RulesyncSkill as Z, RULESYNC_PERMISSIONS_SCHEMA_URL as Zn, fileExistsStrict as Zt, SkillsProcessor as _, removeFileWithoutFollowingSymlinks as _n, mergeInputRootConfigs as _t, convertFromTool as a, listDirectoryEntryNames as an, formatMegabytes as ar, getRulesyncSourceCandidates as at, REASONIX_LOCAL_RULE_FILE_NAME as b, resolvedRelativePath as bn, CONFLICTING_TARGET_PAIRS as bt, ELLIPSIS_WIDTH as c, normalizePosixDirPath as cn, hasEnclosingMarkOutsideKeycap as cr, RulesyncCommandFrontmatterSchema as ct, McpProcessor as d, readFileContent as dn, stripControlCharactersKeepingLineFeeds as dr, stringifyFrontmatter as dt, getHomeDirectory as en, RULESYNC_SKILLS_RELATIVE_DIR_PATH as er, RulesyncRuleFrontmatterSchema as et, IgnoreProcessor as f, readFileContentOrNull as fn, stripControlCharactersKeepingLineFeedsAndTabs as fr, loadYaml as ft, SubagentsProcessor as g, removeFileStrict as gn, ConfigResolver as gt, RulesProcessor as h, removeFile as hn, SKILL_FILE_NAME as ht, inspectInputRoots as i, isSymlink as in, RULESYNC_XDG_CONFIG_HOME_DEFAULT_DIR_NAME as ir, RulesyncHooks as it, AUGMENTCODE_DIR as j, ALL_FEATURES as jn, warnOnConflictingFlags as jt, CODEBUDDY_DIR as k, PACKAGING_TOOL_TARGETS as kn, WarningCollectingLogger as kt, displayWidthOf as l, pathEscapesRoot as ln, quoteForLog as lr, RulesyncCheck as lt, ChecksProcessor as m, removeDirectoryStrict as mn, SHARED_USER_MANAGED_CONFIG_PATHS as mt, formatSourceLoadFailure as n, isFileSystemError as nn, RULESYNC_SUBAGENTS_RELATIVE_DIR_PATH as nr, RulesyncMcp as nt, getProcessorRegistryEntry as o, listFilePathsRecursively as on, formatError as or, resolveRulesyncSourceWritePath as ot, HooksProcessor as p, removeDirectory as pn, stripHiddenCharacters as pr, isRecord as pt, hasWindowsFoldableName as q, RULESYNC_MCP_RELATIVE_FILE_PATH as qn, createTempDirectory as qt, generate as r, isRootDirPath as rn, RULESYNC_USER_CONFIG_DIR_NAME as rr, RulesyncIgnore as rt, parseCommaSeparatedList as s, listSubdirectoryNames as sn, truncateText as sr, RulesyncCommand as st, importFromTool as t, isFileNotFoundError as tn, RULESYNC_SOURCES_LOCK_RELATIVE_FILE_PATH as tr, RulesyncPermissions as tt, shortenToWidth as u, posixRelativePathEscapesRoot as un, stripControlCharacters as ur, RulesyncCheckFrontmatterSchema as ut, CRUSH_LOCAL_RULE_FILE_NAME as v, removeTempDirectory as vn, parseConfigFileContent as vt, LETTACODE_SETTINGS_LOCAL_FILE_NAME as w, writeFileBuffer as wn, assertTargetsFeaturesExclusive as wt, QWENCODE_DIR as x, runWithDirectoryRollback as xn, ConfigFileSchema as xt, CommandsProcessor as y, resolvePath as yn, resolveEffectiveInputRoots as yt, CLAUDECODE_DIR as z, RULESYNC_COMMANDS_RELATIVE_DIR_PATH as zn, applyFileMode as zt };
109261
+ export { RulesyncSkillFrontmatterSchema as $, RULESYNC_RULES_RELATIVE_DIR_PATH as $n, getFileSizeAndExecutableBit as $t, CODEBUDDY_LOCAL_RULE_FILE_NAME as A, ToolTargetSchema as An, fallbackLogger as At, CLAUDECODE_DIR as B, RULESYNC_CONFIG_RELATIVE_FILE_PATH as Bn, assertDirectoryIfExists as Bt, LETTACODE_DIR as C, toPosixPath as Cn, SourceEntrySchema as Ct, COMMANDCODE_DIR as D, ALL_TOOL_TARGETS as Dn, ConsoleLogger as Dt, FACTORYDROID_SETTINGS_LOCAL_FILE_NAME as E, mapWithConcurrency as En, findControlCharacter as Et, sweepRefusalReason as F, FEATURE_SOURCE_TREE_ENTRIES as Fn, CLIError as Ft, findProjectInstructionBudgetFindings as G, RULESYNC_IGNORE_RELATIVE_FILE_PATH as Gn, assertWritablePathInsideRoot as Gt, CLAUDECODE_MEMORIES_DIR_NAME as H, RULESYNC_CURATED_RULES_RELATIVE_DIR_PATH as Hn, assertNoSymlinkBelowRoot as Ht, loadYaml as I, MAX_FILE_SIZE as In, ErrorCodes as It, hasWindowsFoldableName as J, RULESYNC_MCP_SCHEMA_URL as Jn, directoryExists as Jt, toInstructionBudgetFile as K, RULESYNC_LOCAL_CONFIG_RELATIVE_FILE_PATH as Kn, checkPathTraversal as Kt, CODEXCLI_BASH_RULES_FILE_NAME as L, RULESYNC_AIIGNORE_RELATIVE_FILE_PATH as Ln, parseJsonc as Lt, AUGMENTCODE_SETTINGS_LOCAL_FILE_NAME as M, ALL_FEATURES_WITH_WILDCARD as Mn, withFallbackLoggerTarget as Mt, caseFoldIdentity as N, DEPRECATED_FEATURE_REPLACEMENTS as Nn, resetRunWarningState as Nt, COMMANDCODE_SETTINGS_LOCAL_FILE_NAME as O, ALL_TOOL_TARGETS_WITH_WILDCARD as On, JsonLogger as Ot, groupSpellingsByCaseFoldedIdentity as P, CURATED_RULES_FEATURE_SUBDIR as Pn, withWarnOnceScope as Pt, RulesyncSkill as Q, RULESYNC_RELATIVE_DIR_PATH as Qn, findFilesByGlobs as Qt, CODEXCLI_DIR as R, RULESYNC_CHECKS_RELATIVE_DIR_PATH as Rn, PathOutsideRootError as Rt, QWENCODE_LOCAL_RULE_FILE_NAME as S, splitPathSegments as Sn, GITIGNORE_DESTINATION_KEY as St, FACTORYDROID_DIR as T, writeFileContent as Tn, getSourceTransport as Tt, CLAUDECODE_SETTINGS_LOCAL_FILE_NAME as U, RULESYNC_CURATED_SKILLS_RELATIVE_DIR_PATH as Un, assertPathResolvesInsideRoot as Ut, CLAUDECODE_LOCAL_RULE_FILE_NAME as V, RULESYNC_CONFIG_SCHEMA_URL as Vn, assertLandingOutsideVcsMetadata as Vt, CLAUDECODE_SKILLS_DIR_PATH as W, RULESYNC_HOOKS_RELATIVE_FILE_PATH as Wn, assertTreeContainsNoSymlinks as Wt, RulesyncSubagent as X, RULESYNC_PERMISSIONS_RELATIVE_FILE_PATH as Xn, fileExists as Xt, getLocalSkillDirNames as Y, RULESYNC_NPM_SOURCES_LOCK_RELATIVE_FILE_PATH as Yn, ensureDir as Yt, RulesyncSubagentFrontmatterSchema as Z, RULESYNC_PERMISSIONS_SCHEMA_URL as Zn, fileExistsStrict as Zt, SkillsProcessor as _, removeFileWithoutFollowingSymlinks as _n, mergeInputRootConfigs as _t, convertFromTool as a, listDirectoryEntryNames as an, formatMegabytes as ar, RulesyncHooks as at, REASONIX_LOCAL_RULE_FILE_NAME as b, resolvedRelativePath as bn, CONFLICTING_TARGET_PAIRS as bt, ELLIPSIS_WIDTH as c, normalizePosixDirPath as cn, hasEnclosingMarkOutsideKeycap as cr, RulesyncCommand as ct, McpProcessor as d, readFileContent as dn, stripControlCharactersKeepingLineFeeds as dr, RulesyncCheckFrontmatterSchema as dt, getHomeDirectory as en, RULESYNC_SKILLS_RELATIVE_DIR_PATH as er, RulesyncRule as et, IgnoreProcessor as f, readFileContentOrNull as fn, stripControlCharactersKeepingLineFeedsAndTabs as fr, stringifyFrontmatter as ft, SubagentsProcessor as g, removeFileStrict as gn, ConfigResolver as gt, RulesProcessor as h, removeFile as hn, SKILL_FILE_NAME as ht, inspectInputRoots as i, isSymlink as in, RULESYNC_XDG_CONFIG_HOME_DEFAULT_DIR_NAME as ir, RulesyncIgnore as it, AUGMENTCODE_DIR as j, ALL_FEATURES as jn, warnOnConflictingFlags as jt, CODEBUDDY_DIR as k, PACKAGING_TOOL_TARGETS as kn, WarningCollectingLogger as kt, displayWidthOf as l, pathEscapesRoot as ln, quoteForLog as lr, RulesyncCommandFrontmatterSchema as lt, ChecksProcessor as m, removeDirectoryStrict as mn, SHARED_USER_MANAGED_CONFIG_PATHS as mt, formatSourceLoadFailure as n, isFileSystemError as nn, RULESYNC_SUBAGENTS_RELATIVE_DIR_PATH as nr, RulesyncPermissions as nt, getProcessorRegistryEntry as o, listFilePathsRecursively as on, formatError as or, getRulesyncSourceCandidates as ot, HooksProcessor as p, removeDirectory as pn, stripHiddenCharacters as pr, isRecord as pt, classifyRemoteName as q, RULESYNC_MCP_RELATIVE_FILE_PATH as qn, createTempDirectory as qt, generate as r, isRootDirPath as rn, RULESYNC_USER_CONFIG_DIR_NAME as rr, RulesyncMcp as rt, parseCommaSeparatedList as s, listSubdirectoryNames as sn, truncateText as sr, resolveRulesyncSourceWritePath as st, importFromTool as t, isFileNotFoundError as tn, RULESYNC_SOURCES_LOCK_RELATIVE_FILE_PATH as tr, RulesyncRuleFrontmatterSchema as tt, shortenToWidth as u, posixRelativePathEscapesRoot as un, stripControlCharacters as ur, RulesyncCheck as ut, CRUSH_LOCAL_RULE_FILE_NAME as v, removeTempDirectory as vn, parseConfigFileContent as vt, LETTACODE_SETTINGS_LOCAL_FILE_NAME as w, writeFileBuffer as wn, assertTargetsFeaturesExclusive as wt, QWENCODE_DIR as x, runWithDirectoryRollback as xn, ConfigFileSchema as xt, CommandsProcessor as y, resolvePath as yn, resolveEffectiveInputRoots as yt, CLAUDECODE_AGENT_MEMORY_LOCAL_DIR_NAME as z, RULESYNC_COMMANDS_RELATIVE_DIR_PATH as zn, applyFileMode as zt };
107996
109262
 
107997
- //# sourceMappingURL=import-Ctgal4jT.js.map
109263
+ //# sourceMappingURL=import-yOMJuum5.js.map