rulesync 43.11.0 → 43.13.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.
@@ -41,9 +41,8 @@ let es_toolkit = require("es-toolkit");
41
41
  let globby = require("globby");
42
42
  let node_async_hooks = require("node:async_hooks");
43
43
  let node_util = require("node:util");
44
- let gray_matter = require("gray-matter");
45
- gray_matter = __toESM(gray_matter, 1);
46
44
  let js_yaml = require("js-yaml");
45
+ let js_yaml_v4 = require("js-yaml-v4");
47
46
  let es_toolkit_object = require("es-toolkit/object");
48
47
  let node_crypto = require("node:crypto");
49
48
  let _toon_format_toon = require("@toon-format/toon");
@@ -1829,6 +1828,32 @@ async function relativeWriteLanding({ rootPath, targetPath }) {
1829
1828
  return (0, node_path.relative)(rootLanding, targetLanding);
1830
1829
  }
1831
1830
  /**
1831
+ * The first symbolic link on the way from `rootPath` down to `targetPath`, or
1832
+ * `null` when no existing entry below the root is a link. Only the segments
1833
+ * below the root are looked at, so a root that is itself a link (macOS
1834
+ * `/tmp -> /private/tmp`, a linked home directory) does not count; nor does a
1835
+ * target that is not spelled below the root. Once a segment is missing,
1836
+ * nothing below it exists, so the walk stops there.
1837
+ */
1838
+ async function firstLinkBelowRoot({ rootPath, targetPath }) {
1839
+ const relativeTarget = (0, node_path.relative)((0, node_path.resolve)(rootPath), (0, node_path.resolve)(targetPath));
1840
+ if (relativeTarget === "" || pathEscapesRoot(relativeTarget)) return null;
1841
+ let current = (0, node_path.resolve)(rootPath);
1842
+ for (const segment of splitPathSegments(relativeTarget)) {
1843
+ if (segment === "") continue;
1844
+ current = (0, node_path.join)(current, segment);
1845
+ let stats;
1846
+ try {
1847
+ stats = await (0, node_fs_promises.lstat)(current);
1848
+ } catch (error) {
1849
+ if (isFileNotFoundError(error) || isNotADirectoryError(error)) return null;
1850
+ throw error;
1851
+ }
1852
+ if (stats.isSymbolicLink()) return current;
1853
+ }
1854
+ return null;
1855
+ }
1856
+ /**
1832
1857
  * Directory names that hold version-control metadata. Bytes landing in one of
1833
1858
  * them change how the VCS behaves rather than what it tracks: `.git/config`
1834
1859
  * can set `core.fsmonitor`, `.git/hooks/*` run on the next commit.
@@ -4485,37 +4510,6 @@ function toStringArray$1(value) {
4485
4510
  function toRecord(value) {
4486
4511
  return isRecord(value) ? value : {};
4487
4512
  }
4488
- // src/utils/yaml.ts
4489
- /**
4490
- * js-yaml v5's `reason` for an empty document. `load("")` — and any
4491
- * whitespace/comment-only input — throws a `YAMLException` with this reason
4492
- * instead of returning `undefined` the way v4 did.
4493
- */
4494
- const EMPTY_INPUT_REASON = "expected a document, but the input is empty";
4495
- /**
4496
- * Load YAML content while preserving js-yaml v4's behavior of returning
4497
- * `undefined` for empty documents (empty, whitespace-only, or comment-only
4498
- * input).
4499
- *
4500
- * js-yaml v5 changed `load("")` to **throw** ("expected a document, but the
4501
- * input is empty") instead of returning `undefined`. Many call sites here parse
4502
- * config/lock/frontmatter files that can legitimately be empty and rely on the
4503
- * old `undefined` sentinel (`load(input) ?? {}`, `if (loaded === undefined)`,
4504
- * "an empty file parses to undefined/null"). Routing every load through this
4505
- * wrapper keeps that contract in one place so a future js-yaml bump cannot
4506
- * reintroduce the empty-input regression. Genuine parse errors still propagate.
4507
- *
4508
- * @see https://github.com/nodeca/js-yaml/blob/master/docs/migrate_v4_to_v5.md#empty-input-throws
4509
- */
4510
- function loadYaml(content, options) {
4511
- if (content.trim() === "") return;
4512
- try {
4513
- return (0, js_yaml.load)(content, options);
4514
- } catch (error) {
4515
- if (error instanceof js_yaml.YAMLException && error.reason === EMPTY_INPUT_REASON) return;
4516
- throw error;
4517
- }
4518
- }
4519
4513
  // src/utils/frontmatter.ts
4520
4514
  /**
4521
4515
  * Upper bound on the number of values a frontmatter document may expand to
@@ -4547,10 +4541,10 @@ const MAX_FRONTMATTER_STRING_CHARS = 4e6;
4547
4541
  * block itself, checked before it is ever handed to the YAML parser.
4548
4542
  *
4549
4543
  * The budgets above only bound the *parsed* document — the walk over
4550
- * `matter()`'s output — but a complex YAML key (an array or mapping used as a
4544
+ * the parser's output — but a complex YAML key (an array or mapping used as a
4551
4545
  * mapping key) is joined into a string by js-yaml while it parses, and a
4552
4546
  * mapping with many such keys can cost real memory before that walk ever
4553
- * starts, or even before `matter()` returns. Capping the raw block size keeps
4547
+ * starts, or even before the parser returns. Capping the raw block size keeps
4554
4548
  * that parse-time cost bounded regardless of what the block contains. Real
4555
4549
  * frontmatter blocks are a few hundred bytes at most; even a large project
4556
4550
  * manifest stays well under this.
@@ -4572,8 +4566,8 @@ function estimateLeafChars(value) {
4572
4566
  /**
4573
4567
  * Copy one parsed value, dropping nullish leaves and cyclic references.
4574
4568
  *
4575
- * Every alias is still written out as an independent copy, as gray-matter's
4576
- * default YAML engine would otherwise serialize shared references as `&ref_0`
4569
+ * Every alias is still written out as an independent copy, as js-yaml's
4570
+ * dumper would otherwise serialize shared references as `&ref_0`
4577
4571
  * anchors that simplified frontmatter parsers cannot read; the expansion is
4578
4572
  * bounded by {@link MAX_FRONTMATTER_VALUES} instead.
4579
4573
  */
@@ -4649,63 +4643,27 @@ function deepFlattenStringsObject(obj) {
4649
4643
  function stringifyFrontmatter(body, frontmatter, options) {
4650
4644
  const { avoidBlockScalars = false } = options ?? {};
4651
4645
  const cleanFrontmatter = avoidBlockScalars ? deepFlattenStringsObject(frontmatter) : deepRemoveNullishObject(frontmatter);
4652
- const file = { content: body };
4653
- if (avoidBlockScalars) return gray_matter.default.stringify(file, cleanFrontmatter, { engines: { yaml: {
4654
- parse: (input) => loadYaml(input) ?? {},
4655
- stringify: (data) => (0, js_yaml.dump)(data, { lineWidth: -1 })
4656
- } } });
4657
- return gray_matter.default.stringify(file, cleanFrontmatter);
4658
- }
4659
- /**
4660
- * Thrown in place of gray-matter's built-in JavaScript engine.
4661
- *
4662
- * gray-matter picks the parser from the text after the opening fence, so a
4663
- * file that opens with `---js` or `---javascript` has its frontmatter handed
4664
- * to `eval()`. Frontmatter here comes from third-party skills, fetched sources
4665
- * and untrusted repositories, so that would run arbitrary code on the machine
4666
- * of whoever generates or imports it. Every engine name that resolves to code
4667
- * execution is mapped to this refusal; {@link assertYamlFrontmatterLanguage}
4668
- * refuses those fences earlier still, so this is the second line of defense.
4669
- */
4670
- function refuseExecutableFrontmatter() {
4671
- throw new Error("Frontmatter written in an executable language (JavaScript / CoffeeScript) is not supported; use YAML");
4672
- }
4673
- const REFUSED_FRONTMATTER_ENGINE = {
4674
- parse: refuseExecutableFrontmatter,
4675
- stringify: refuseExecutableFrontmatter
4676
- };
4677
- /**
4678
- * Engines passed to every gray-matter parse. Supplying them merges over
4679
- * gray-matter's defaults, so the JavaScript engine (and the CoffeeScript names
4680
- * a plugin could register) can never be reached through an alias.
4681
- *
4682
- * `patches/gray-matter@4.0.3.patch` also deletes the JavaScript engine, but a
4683
- * pnpm patch only applies inside this repository: gray-matter is an external
4684
- * dependency of the published package, so an installed rulesync runs the
4685
- * unpatched gray-matter, and this override plus the language check are what
4686
- * protect it. Exported for the test that pins that.
4687
- */
4688
- const FRONTMATTER_PARSE_OPTIONS = { engines: {
4689
- javascript: REFUSED_FRONTMATTER_ENGINE,
4690
- js: REFUSED_FRONTMATTER_ENGINE,
4691
- coffee: REFUSED_FRONTMATTER_ENGINE,
4692
- coffeescript: REFUSED_FRONTMATTER_ENGINE,
4693
- cson: REFUSED_FRONTMATTER_ENGINE
4694
- } };
4646
+ const yaml = (avoidBlockScalars ? (0, js_yaml.dump)(cleanFrontmatter, { lineWidth: -1 }) : (0, js_yaml_v4.dump)(cleanFrontmatter)).trim();
4647
+ return (yaml === "{}" ? "" : `---\n${yaml}\n---\n`) + withTrailingNewline(body);
4648
+ }
4649
+ function withTrailingNewline(text) {
4650
+ return text.endsWith("\n") ? text : `${text}\n`;
4651
+ }
4695
4652
  /** Frontmatter languages accepted after the opening `---` fence. */
4696
4653
  const ALLOWED_FRONTMATTER_LANGUAGE_PATTERN = /^(?:ya?ml)?$/i;
4697
4654
  /**
4698
- * Read the opening frontmatter fence the way gray-matter does, or return
4699
- * `undefined` when gray-matter would see no frontmatter at all.
4655
+ * Read the opening frontmatter fence, or return `undefined` when the content
4656
+ * carries no frontmatter at all.
4700
4657
  *
4701
- * gray-matter strips one byte order mark, treats `---` as a fence only when a
4702
- * fourth `-` does not follow, and takes the language from the text between the
4703
- * fence and the first `\r?\n`, trimmed — dropping the last character when
4704
- * there is no line break at all. Every check below that has to agree with
4705
- * gray-matter on where the block is (the language check, the size guard, the
4706
- * repair pass) goes through this one reading, so none of them can be bypassed
4707
- * by a fence line gray-matter accepts and a stricter pattern would not (a
4708
- * stray `\r` before the line break, say).
4658
+ * The grammar is gray-matter's, which rulesync used to depend on, kept so that
4659
+ * every file reads the same as before: one byte order mark is skipped, `---`
4660
+ * is a fence only when a fourth `-` does not follow, and the language is the
4661
+ * text between the fence and the first `\r?\n`, trimmed — dropping the last
4662
+ * character when there is no line break at all. Every check that has to agree
4663
+ * with {@link splitFrontmatter} on where the block is (the language check and
4664
+ * the repair pass) goes through this one reading, so none of them
4665
+ * can be bypassed by a fence line the splitter accepts and a stricter pattern
4666
+ * would not (a stray `\r` before the line break, say).
4709
4667
  */
4710
4668
  function readFrontmatterFence(content) {
4711
4669
  const offset = content.startsWith("") ? 1 : 0;
@@ -4724,26 +4682,60 @@ function readFrontmatterFence(content) {
4724
4682
  /**
4725
4683
  * Refuse a frontmatter fence that names any language other than YAML.
4726
4684
  *
4727
- * Only YAML is ever written by rulesync or by the tools it targets, so anything
4728
- * else — `---js` above all, whose block gray-matter would `eval()` — is
4729
- * rejected before gray-matter sees the content.
4685
+ * Only YAML is ever written by rulesync or by the tools it targets. Generic
4686
+ * frontmatter libraries pick a parser from the fence language, and some hand a
4687
+ * `---js` block to `eval()`; rulesync parses everything as YAML, and refusing
4688
+ * any other language keeps a file meant for such a parser from being read as
4689
+ * something it is not.
4730
4690
  */
4731
4691
  function assertYamlFrontmatterLanguage(content) {
4732
4692
  const fence = readFrontmatterFence(content);
4733
4693
  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`);
4734
4694
  }
4735
4695
  /**
4736
- * The number of characters gray-matter would hand to the YAML parser as the
4737
- * frontmatter block. Unlike {@link findFrontmatterBlockBounds}, a missing
4738
- * closing fence does not make this zero: gray-matter then parses everything
4739
- * after the fence line, so that is what the size guard has to measure.
4696
+ * Split `content` into its raw frontmatter block and its body, the way
4697
+ * gray-matter 4 did (see {@link readFrontmatterFence}).
4698
+ *
4699
+ * The block ends at the first `\n---`, with no requirement that the delimiter
4700
+ * be alone on its line, and one line break after it is dropped from the body.
4701
+ * A fence nothing closes makes the rest of the file the block and leaves the
4702
+ * body empty. Without a fence, `block` is `""` and the body is the content
4703
+ * minus a leading byte order mark.
4740
4704
  */
4741
- function measureFrontmatterBlockChars(content) {
4742
- const fence = readFrontmatterFence(content);
4743
- if (fence?.lineBreakStart === void 0) return 0;
4744
- const rest = content.slice(fence.lineBreakStart);
4705
+ function splitFrontmatter(content) {
4706
+ const text = content.startsWith("") ? content.slice(1) : content;
4707
+ if (!text.startsWith("---") || text.charAt(3) === "-") return {
4708
+ block: "",
4709
+ body: text
4710
+ };
4711
+ let rest = text.slice(3);
4712
+ const rawLanguage = rest.slice(0, rest.search(/\r?\n/));
4713
+ if (rawLanguage.trim() !== "") rest = rest.slice(rawLanguage.length);
4745
4714
  const closeIndex = rest.indexOf("\n---");
4746
- return closeIndex === -1 ? rest.length : closeIndex;
4715
+ if (closeIndex === -1) return {
4716
+ block: rest,
4717
+ body: ""
4718
+ };
4719
+ let body = rest.slice(closeIndex + 4);
4720
+ if (body.startsWith("\r")) body = body.slice(1);
4721
+ if (body.startsWith("\n")) body = body.slice(1);
4722
+ return {
4723
+ block: rest.slice(0, closeIndex),
4724
+ body
4725
+ };
4726
+ }
4727
+ /**
4728
+ * Whether a raw block holds nothing but blank and comment lines. Checked line
4729
+ * by line rather than with gray-matter's `/^\s*#[^\n]+/gm`, whose `\s*` also
4730
+ * spans line breaks and backtracks quadratically on a long run of blank lines.
4731
+ * The one known difference: a lone `\r` now ends a comment line, as it does
4732
+ * in YAML, where the old pattern let the comment run on past it.
4733
+ */
4734
+ function isBlankFrontmatterBlock(block) {
4735
+ return block.split(/\r\n|\r|\n/).every((line) => {
4736
+ const trimmed = line.trim();
4737
+ return trimmed === "" || trimmed.startsWith("#");
4738
+ });
4747
4739
  }
4748
4740
  function parseFrontmatter(content, filePath) {
4749
4741
  let frontmatter;
@@ -4751,11 +4743,11 @@ function parseFrontmatter(content, filePath) {
4751
4743
  let hasFrontmatter;
4752
4744
  try {
4753
4745
  assertYamlFrontmatterLanguage(content);
4754
- 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)`);
4755
- const result = (0, gray_matter.default)(content, FRONTMATTER_PARSE_OPTIONS);
4756
- frontmatter = deepRemoveNullishObject(result.data);
4757
- body = result.content;
4758
- hasFrontmatter = result.matter !== "" || content.trimStart().startsWith("---");
4746
+ const split = splitFrontmatter(content);
4747
+ 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)`);
4748
+ frontmatter = deepRemoveNullishObject(isBlankFrontmatterBlock(split.block) ? {} : (0, js_yaml_v4.load)(split.block));
4749
+ body = split.body;
4750
+ hasFrontmatter = content === "" || split.block !== "" || content.trimStart().startsWith("---");
4759
4751
  } catch (error) {
4760
4752
  if (filePath) throw new Error(`Failed to parse frontmatter in ${filePath}: ${formatError(error)}`, { cause: error });
4761
4753
  throw error;
@@ -4812,11 +4804,11 @@ function repairFrontmatterLine(line) {
4812
4804
  /**
4813
4805
  * Locate a raw `---`-delimited frontmatter block's bounds within `content`,
4814
4806
  * without parsing it, for the YAML repair pass below and the rule loaders that
4815
- * pre-process `globs:`. The opening fence is read exactly as gray-matter reads
4807
+ * pre-process `globs:`. The opening fence is read exactly as the splitter reads
4816
4808
  * it ({@link readFrontmatterFence}); an explicit `yaml` / `yml` language is
4817
- * still YAML, any other language yields no bounds. gray-matter ends the block
4809
+ * still YAML, any other language yields no bounds. The splitter ends the block
4818
4810
  * at the first `\n---`, with no requirement that the delimiter be alone on its
4819
- * line, so a stricter pattern here would run past gray-matter's delimiter and
4811
+ * line, so a stricter pattern here would run past the splitter's delimiter and
4820
4812
  * act on text that is really the body. A block with no closing fence has no
4821
4813
  * bounds; the size guard measures that case separately.
4822
4814
  */
@@ -5888,16 +5880,17 @@ const CONTINUE_TO_CANONICAL_EVENT_NAMES = invertRecord(CANONICAL_TO_CONTINUE_EVE
5888
5880
  * observers, `gateway_platform_event` and `transform_api_error_classification`.
5889
5881
  * Shell hooks are gated on the same set.
5890
5882
  *
5891
- * Verified against the tag `v0.22.3`: `VALID_HOOKS` holds 46 entries, grown
5883
+ * Verified against the tag `v0.23.2`: `VALID_HOOKS` holds 48 entries, grown
5892
5884
  * from 23 at `v2026.8.3` (v0.20.0) and 37 at `v2026.8.16` (v0.20.2) — v0.21
5893
5885
  * added `agent_loop_stopped` and `on_room_member_activity`, v0.21.5 added
5894
5886
  * `pre_auxiliary_call` and `post_auxiliary_call`, v0.21.6 added
5895
5887
  * `post_gateway_admission`, `on_human_input_request` and
5896
- * `on_human_input_resolved`, and v0.22.3 added `on_session_delete` and
5897
- * `post_compaction`. This list holds 45 of them — see
5888
+ * `on_human_input_resolved`, v0.22.3 added `on_session_delete` and
5889
+ * `post_compaction`, and v0.23.1 added `on_session_open` and
5890
+ * `post_curator_run`. This list holds 47 of them — see
5898
5891
  * {@link HERMESAGENT_SHELL_UNSUPPORTED_HOOK_EVENTS} for the exclusion.
5899
5892
  *
5900
- * @see https://github.com/NousResearch/hermes-agent/blob/v0.22.3/hermes_cli/plugins.py
5893
+ * @see https://github.com/NousResearch/hermes-agent/blob/v0.23.2/hermes_cli/plugins.py
5901
5894
  */
5902
5895
  const HERMESAGENT_NATIVE_HOOK_EVENTS = [
5903
5896
  "pre_tool_call",
@@ -5922,6 +5915,7 @@ const HERMESAGENT_NATIVE_HOOK_EVENTS = [
5922
5915
  "on_session_finalize",
5923
5916
  "on_session_reset",
5924
5917
  "on_session_delete",
5918
+ "on_session_open",
5925
5919
  "on_skill_lifecycle",
5926
5920
  "subagent_start",
5927
5921
  "subagent_stop",
@@ -5944,7 +5938,8 @@ const HERMESAGENT_NATIVE_HOOK_EVENTS = [
5944
5938
  "on_kanban_dispatch_tick",
5945
5939
  "gateway_platform_event",
5946
5940
  "pre_command",
5947
- "post_compaction"
5941
+ "post_compaction",
5942
+ "post_curator_run"
5948
5943
  ];
5949
5944
  /**
5950
5945
  * `VALID_HOOKS` entries a SHELL hook may not register for. `VALID_HOOKS` doubles
@@ -5956,8 +5951,8 @@ const HERMESAGENT_NATIVE_HOOK_EVENTS = [
5956
5951
  * rulesync only ever writes shell hooks, so these are excluded from
5957
5952
  * {@link HERMESAGENT_NATIVE_HOOK_EVENTS} and warned about with their own message.
5958
5953
  *
5959
- * @see https://github.com/NousResearch/hermes-agent/blob/v0.22.3/hermes_cli/plugins.py — `SHELL_UNSUPPORTED_HOOKS`
5960
- * @see https://github.com/NousResearch/hermes-agent/blob/v0.22.3/agent/shell_hooks.py — `_parse_hooks_block`
5954
+ * @see https://github.com/NousResearch/hermes-agent/blob/v0.23.2/hermes_cli/plugins.py — `SHELL_UNSUPPORTED_HOOKS`
5955
+ * @see https://github.com/NousResearch/hermes-agent/blob/v0.23.2/agent/shell_hooks.py — `_parse_hooks_block`
5961
5956
  */
5962
5957
  const HERMESAGENT_SHELL_UNSUPPORTED_HOOK_EVENTS = ["transform_api_error_classification"];
5963
5958
  /**
@@ -5977,8 +5972,8 @@ const CANONICAL_TO_HERMESAGENT_EVENT_NAMES = {
5977
5972
  /**
5978
5973
  * Hook events supported by Hermes Agent's native Shell Hooks system.
5979
5974
  *
5980
- * Hermes validates hook events against a fixed `VALID_HOOKS` set — 46 entries as
5981
- * of v0.22.3 (tag `v0.22.3`); see {@link HERMESAGENT_NATIVE_HOOK_EVENTS} for the
5975
+ * Hermes validates hook events against a fixed `VALID_HOOKS` set — 48 entries as
5976
+ * of v0.23.2 (tag `v0.23.2`); see {@link HERMESAGENT_NATIVE_HOOK_EVENTS} for the
5982
5977
  * full list. Only the events with a clean 1:1 canonical equivalent are mapped
5983
5978
  * here. All other native events round-trip through `hermesagent.hooks`.
5984
5979
  * @see https://github.com/NousResearch/hermes-agent/blob/main/website/docs/user-guide/features/hooks.md
@@ -6771,6 +6766,7 @@ const CANONICAL_TO_KIRO_IDE_EVENT_NAMES = {
6771
6766
  beforeSubmitPrompt: "UserPromptSubmit",
6772
6767
  preToolUse: "PreToolUse",
6773
6768
  postToolUse: "PostToolUse",
6769
+ permissionRequest: "PermissionRequest",
6774
6770
  stop: "Stop"
6775
6771
  };
6776
6772
  /**
@@ -6779,7 +6775,9 @@ const CANONICAL_TO_KIRO_IDE_EVENT_NAMES = {
6779
6775
  *
6780
6776
  * Kiro exposes PascalCase triggers. rulesync maps the canonical lifecycle
6781
6777
  * events that have a clean 1:1 equivalent: `SessionStart`, `Stop`,
6782
- * `UserPromptSubmit`, `PreToolUse`, and `PostToolUse`. Kiro also documents
6778
+ * `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, and `PermissionRequest`
6779
+ * (Kiro IDE 1.4.236+ and CLI V3 3.4.0+; it takes a Pre Tool Use–style tool
6780
+ * matcher). Kiro also documents
6783
6781
  * file-event (`PostFileCreate`/`PostFileSave`/`PostFileDelete`) and spec-task
6784
6782
  * (`PreTaskExec`/`PostTaskExec`) triggers that have no canonical equivalent;
6785
6783
  * those can still be emitted verbatim via the shared `kiro` override block
@@ -8208,6 +8206,15 @@ const CopilotSandboxUserConfiguredPathsSchema = zod_mini.z.strictObject({
8208
8206
  deniedPaths: zod_mini.z.optional(zod_mini.z.array(zod_mini.z.string()))
8209
8207
  });
8210
8208
  /**
8209
+ * `chat.agent.sandbox.credentials.envVars` (VS Code 1.146+): environment
8210
+ * variable names (never their secret values) mapped to the HTTPS hosts the
8211
+ * Agent Host sandbox may inject each value into. Inside the sandbox the
8212
+ * variable is masked.
8213
+ *
8214
+ * @see https://code.visualstudio.com/docs/agents/run/agent-sandboxing
8215
+ */
8216
+ const CopilotSandboxCredentialEnvVarsSchema = zod_mini.z.record(zod_mini.z.string(), zod_mini.z.strictObject({ injectHosts: zod_mini.z.array(zod_mini.z.string()) }));
8217
+ /**
8211
8218
  * The Agent Host sandbox settings VS Code 1.141 settled on, as a nested object
8212
8219
  * whose path mirrors the dotted setting key under `chat.agent.sandbox.` — e.g.
8213
8220
  * `network.allowNetwork` writes `chat.agent.sandbox.network.allowNetwork`.
@@ -8229,7 +8236,8 @@ const CopilotSandboxSchema = zod_mini.z.strictObject({
8229
8236
  lspServers: zod_mini.z.optional(zod_mini.z.boolean()),
8230
8237
  credentials: zod_mini.z.optional(zod_mini.z.strictObject({
8231
8238
  authenticategit: zod_mini.z.optional(zod_mini.z.boolean()),
8232
- authenticategh: zod_mini.z.optional(zod_mini.z.boolean())
8239
+ authenticategh: zod_mini.z.optional(zod_mini.z.boolean()),
8240
+ envVars: zod_mini.z.optional(CopilotSandboxCredentialEnvVarsSchema)
8233
8241
  })),
8234
8242
  fileSystem: zod_mini.z.optional(zod_mini.z.strictObject({
8235
8243
  allowDevToolAccess: zod_mini.z.optional(zod_mini.z.boolean()),
@@ -9548,15 +9556,20 @@ const CodexcliPermissionsOverrideSchema = zod_mini.z.looseObject({
9548
9556
  /**
9549
9557
  * The `[auto_review]` table of `config.toml`, which configures the reviewer
9550
9558
  * that `approvals_reviewer = "auto_review"` (Rulesync's default) selects:
9551
- * `policy` / `extra_policy` (text inserted into the reviewer prompt),
9559
+ * `policy` / `extra_policy` (text inserted into the reviewer prompt;
9560
+ * `extra_policy` only up to Codex 0.168.0),
9552
9561
  * `timeout_ms` (the review budget, Codex 0.165.0+; `0` waits without a
9553
9562
  * deadline), `circuit_break_action` (`default` | `strict`) and
9554
9563
  * `conversation_history_max_output_tokens` (a positive token cap). Codex
9555
9564
  * rejects the whole config file when one of these has the wrong type or is
9556
9565
  * out of range (`timeout_ms` is a `u32`, the token cap a `NonZeroUsize`), so
9557
9566
  * they are checked here; every other key passes through verbatim.
9567
+ * `extra_policy` and `experimental_policy_template` were removed in Codex
9568
+ * 0.169.0 (openai/codex PR #60646): newer Codex ignores them and warns at
9569
+ * startup (only `--strict-config` rejects them), so they are still accepted
9570
+ * and written for older Codex, and generate warns when they are authored.
9558
9571
  *
9559
- * @see https://github.com/openai/codex/blob/rust-v0.166.0/codex-rs/config/src/config_toml.rs (`AutoReviewToml`)
9572
+ * @see https://github.com/openai/codex/blob/rust-v0.169.0/codex-rs/config/src/config_toml.rs (`AutoReviewToml`)
9560
9573
  */
9561
9574
  auto_review: zod_mini.z.optional(zod_mini.z.looseObject({
9562
9575
  policy: zod_mini.z.optional(zod_mini.z.string()),
@@ -12710,6 +12723,37 @@ function serialize(value) {
12710
12723
  function stripStrings(_key, value) {
12711
12724
  return typeof value === "string" ? stripControlCharacters(value) : value;
12712
12725
  }
12726
+ // src/utils/yaml.ts
12727
+ /**
12728
+ * js-yaml v5's `reason` for an empty document. `load("")` — and any
12729
+ * whitespace/comment-only input — throws a `YAMLException` with this reason
12730
+ * instead of returning `undefined` the way v4 did.
12731
+ */
12732
+ const EMPTY_INPUT_REASON = "expected a document, but the input is empty";
12733
+ /**
12734
+ * Load YAML content while preserving js-yaml v4's behavior of returning
12735
+ * `undefined` for empty documents (empty, whitespace-only, or comment-only
12736
+ * input).
12737
+ *
12738
+ * js-yaml v5 changed `load("")` to **throw** ("expected a document, but the
12739
+ * input is empty") instead of returning `undefined`. Many call sites here parse
12740
+ * config/lock/frontmatter files that can legitimately be empty and rely on the
12741
+ * old `undefined` sentinel (`load(input) ?? {}`, `if (loaded === undefined)`,
12742
+ * "an empty file parses to undefined/null"). Routing every load through this
12743
+ * wrapper keeps that contract in one place so a future js-yaml bump cannot
12744
+ * reintroduce the empty-input regression. Genuine parse errors still propagate.
12745
+ *
12746
+ * @see https://github.com/nodeca/js-yaml/blob/master/docs/migrate_v4_to_v5.md#empty-input-throws
12747
+ */
12748
+ function loadYaml(content, options) {
12749
+ if (content.trim() === "") return;
12750
+ try {
12751
+ return (0, js_yaml.load)(content, options);
12752
+ } catch (error) {
12753
+ if (error instanceof js_yaml.YAMLException && error.reason === EMPTY_INPUT_REASON) return;
12754
+ throw error;
12755
+ }
12756
+ }
12713
12757
  // src/features/shared/jsonc-object-edit.ts
12714
12758
  /**
12715
12759
  * In-place editing of a JSONC object's text: the engine behind the shared
@@ -14023,6 +14067,7 @@ const SHARED_CONFIG_OWNERSHIP = {
14023
14067
  "chat.agent.sandbox.lspServers",
14024
14068
  "chat.agent.sandbox.credentials.authenticategit",
14025
14069
  "chat.agent.sandbox.credentials.authenticategh",
14070
+ "chat.agent.sandbox.credentials.envVars",
14026
14071
  "chat.agent.sandbox.fileSystem.allowDevToolAccess",
14027
14072
  "chat.agent.sandbox.fileSystem.userConfiguredPaths",
14028
14073
  "zoo-code.allowedCommands",
@@ -14719,7 +14764,7 @@ function tryParseStructured({ filePath, content }) {
14719
14764
  }
14720
14765
  }
14721
14766
  /**
14722
- * gray-matter often includes extra newlines right after the closing ---; strip those so the
14767
+ * The parsed body often starts with extra newlines right after the closing ---; strip those so the
14723
14768
  * body matches across generators vs on-disk formatters. Trailing whitespace is normalized via
14724
14769
  * addTrailingNewline (trimEnd + single newline), same as writes.
14725
14770
  */
@@ -14810,7 +14855,7 @@ function fileContentIsEmptyPayload({ filePath, content }) {
14810
14855
  * Whether on-disk content is equivalent to generated content for --check / dry-run.
14811
14856
  *
14812
14857
  * 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).
14858
+ * frontmatter files (.md, .mdc — same frontmatter parser as elsewhere).
14814
14859
  */
14815
14860
  function fileContentsEquivalent({ filePath, expected, existing }) {
14816
14861
  if (existing === null) return false;
@@ -14992,6 +15037,11 @@ var FeatureProcessor = class extends RulesyncSourceConsumer {
14992
15037
  if (fileMode !== void 0 && !this.dryRun) await restoreMissingExecutableBit(filePath, fileMode);
14993
15038
  continue;
14994
15039
  }
15040
+ await warnIfWriteFollowsLink({
15041
+ logger: this.logger,
15042
+ rootPath: aiFile.getOutputRoot(),
15043
+ targetPath: filePath
15044
+ });
14995
15045
  if (this.dryRun) this.logger.info(`[DRY RUN] Would write: ${stripControlCharacters(filePath)}`);
14996
15046
  else {
14997
15047
  await writeFileContent(filePath, contentWithNewline);
@@ -15176,6 +15226,37 @@ async function refusesWriteOutsideRoot({ logger, rootPath, targetPath }) {
15176
15226
  return true;
15177
15227
  }
15178
15228
  /**
15229
+ * Warn, once per run and link, that a write to `targetPath` goes through a
15230
+ * symbolic link below `rootPath`: the warning names the link and the real path
15231
+ * it leads to, so the file the write really changes is visible.
15232
+ *
15233
+ * Links that lead out of the root (or into version-control metadata) are
15234
+ * refused by {@link refusesWriteOutsideRoot} before this is asked; an in-root
15235
+ * link is written through on purpose (dotfiles setups rely on it), but a
15236
+ * committed `AGENTS.md -> .claude/CLAUDE.md` would otherwise have one target
15237
+ * silently replace another target's file. Writers call this only for a file
15238
+ * they are about to change (or, in a dry run, would change), so an unchanged
15239
+ * file reached through a link stays quiet. The warning is keyed on the first
15240
+ * link on the path rather than on the file, so a linked directory such as
15241
+ * `~/.claude -> ~/dotfiles/.claude` is reported once however many files below
15242
+ * it a run writes.
15243
+ */
15244
+ async function warnIfWriteFollowsLink({ logger, rootPath, targetPath }) {
15245
+ const linkPath = await firstLinkBelowRoot({
15246
+ rootPath,
15247
+ targetPath
15248
+ });
15249
+ if (linkPath === null) return;
15250
+ const linkLanding = await writeLandingPath(linkPath);
15251
+ if (linkLanding === null) return;
15252
+ warnOnceWithFallback(logger, `${quoteForLog(linkPath)} is a symbolic link to ${quoteForLog(linkLanding)}; files rulesync writes through it land there`);
15253
+ const restOfPath = (0, node_path.relative)(linkPath, (0, node_path.resolve)(targetPath));
15254
+ if (restOfPath === "") return;
15255
+ const targetLanding = await writeLandingPath(targetPath);
15256
+ if (targetLanding === null || targetLanding === (0, node_path.join)(linkLanding, restOfPath)) return;
15257
+ warnOnceWithFallback(logger, `${quoteForLog(targetPath)} is reached through further symbolic links; rulesync writes it to ${quoteForLog(targetLanding)}`);
15258
+ }
15259
+ /**
15179
15260
  * Why the orphan sweep has to leave the files in `dirPath` alone, or `null`
15180
15261
  * when it may delete them.
15181
15262
  *
@@ -18510,6 +18591,11 @@ var GooseCommand = class GooseCommand extends ToolCommand {
18510
18591
  entries: []
18511
18592
  });
18512
18593
  if (nextContent === currentContent) return 0;
18594
+ await warnIfWriteFollowsLink({
18595
+ logger,
18596
+ rootPath: outputRoot,
18597
+ targetPath: configPath
18598
+ });
18513
18599
  if (dryRun) logger.info(`[DRY RUN] Would write: ${configPath}`);
18514
18600
  else await writeFileContent(configPath, nextContent);
18515
18601
  return 1;
@@ -19692,6 +19778,11 @@ var HermesagentCommand = class HermesagentCommand extends ToolCommand {
19692
19778
  global
19693
19779
  });
19694
19780
  if (nextContent === currentContent) return 0;
19781
+ await warnIfWriteFollowsLink({
19782
+ logger,
19783
+ rootPath: outputRoot,
19784
+ targetPath: configPath
19785
+ });
19695
19786
  if (dryRun) logger.info(`[DRY RUN] Would write: ${configPath}`);
19696
19787
  else await writeFileContent(configPath, nextContent);
19697
19788
  return 1;
@@ -23308,6 +23399,17 @@ var DirFeatureProcessor = class extends RulesyncSourceConsumer {
23308
23399
  });
23309
23400
  }
23310
23401
  /**
23402
+ * Warn about each file of `aiDir` about to be written through a symbolic link
23403
+ * that stays inside the output root (see {@link warnIfWriteFollowsLink}).
23404
+ */
23405
+ async warnIfFilesFollowLinks({ aiDir, filePaths }) {
23406
+ for (const targetPath of filePaths) await warnIfWriteFollowsLink({
23407
+ logger: this.logger,
23408
+ rootPath: aiDir.getOutputRoot(),
23409
+ targetPath
23410
+ });
23411
+ }
23412
+ /**
23311
23413
  * Once converted to rulesync/tool dirs, write them to the filesystem.
23312
23414
  * Returns the number of directories written.
23313
23415
  *
@@ -23360,6 +23462,10 @@ var DirFeatureProcessor = class extends RulesyncSourceConsumer {
23360
23462
  }
23361
23463
  continue;
23362
23464
  }
23465
+ await this.warnIfFilesFollowLinks({
23466
+ aiDir,
23467
+ filePaths: writtenPaths.slice(1)
23468
+ });
23363
23469
  const relativeDir = aiDir.getRelativePathFromCwd();
23364
23470
  if (this.dryRun) {
23365
23471
  this.logger.info(`[DRY RUN] Would create directory: ${stripControlCharacters(dirPath)}`);
@@ -34547,6 +34653,24 @@ function isMissingDescription(value) {
34547
34653
  function nameFromFileName(relativeFilePath) {
34548
34654
  return relativeFilePath.replace(/(\.agent)?\.md$/, "");
34549
34655
  }
34656
+ /**
34657
+ * Normalizes a subagent name the way Junie does: the result is what Junie
34658
+ * accepts for `--agent` and must match `[a-z0-9][a-z0-9_-]*`.
34659
+ *
34660
+ * - Surrounding whitespace is trimmed first, so a quoted `" Code Reviewer "`
34661
+ * (or a file named ` Reviewer.md`) does not start or end with a hyphen,
34662
+ * which the leading-character rule would reject.
34663
+ * - Uppercase letters are lowercased.
34664
+ * - Each run of whitespace (spaces, tabs, ...) becomes a single hyphen. The
34665
+ * upstream docs only say Junie "replaces spaces with hyphens"; collapsing
34666
+ * runs gives `code-reviewer` for `Code Reviewer`, which is the name a user
34667
+ * would expect and still matches the pattern, instead of `code--reviewer`.
34668
+ *
34669
+ * @see https://junie.jetbrains.com/docs/junie-cli-subagents.html
34670
+ */
34671
+ function normalizeJunieName(name) {
34672
+ return name.trim().toLowerCase().replace(/\s+/g, "-");
34673
+ }
34550
34674
  var JunieSubagent = class JunieSubagent extends ToolSubagent {
34551
34675
  frontmatter;
34552
34676
  body;
@@ -34571,14 +34695,30 @@ var JunieSubagent = class JunieSubagent extends ToolSubagent {
34571
34695
  getBody() {
34572
34696
  return this.body;
34573
34697
  }
34698
+ /**
34699
+ * The name Junie resolves after normalization, so `Code Reviewer.md` and
34700
+ * `code-reviewer.md` (both `code-reviewer`) are reported as duplicates on
34701
+ * import instead of becoming two rulesync subagents with the same name.
34702
+ */
34703
+ getImportIdentity() {
34704
+ return this.getNormalizedName();
34705
+ }
34706
+ /**
34707
+ * An empty or whitespace-only `name` would normalize to `""`, which is not a
34708
+ * valid Junie name and would make every such file share one import identity,
34709
+ * so it falls back to the file name just like a missing `name` does.
34710
+ */
34711
+ getNormalizedName() {
34712
+ return (this.frontmatter.name === void 0 ? "" : normalizeJunieName(this.frontmatter.name)) || normalizeJunieName(nameFromFileName(this.getRelativeFilePath()));
34713
+ }
34574
34714
  toRulesyncSubagent() {
34575
- const { name, description, ...restFields } = this.frontmatter;
34715
+ const { name: _name, description, ...restFields } = this.frontmatter;
34576
34716
  const junieSection = { ...restFields };
34577
34717
  return new RulesyncSubagent({
34578
34718
  outputRoot: ".",
34579
34719
  frontmatter: {
34580
34720
  targets: ["*"],
34581
- name: name ?? nameFromFileName(this.getRelativeFilePath()),
34721
+ name: this.getNormalizedName(),
34582
34722
  ...description !== void 0 && { description },
34583
34723
  ...Object.keys(junieSection).length > 0 && { junie: junieSection }
34584
34724
  },
@@ -48358,8 +48498,8 @@ var TraeRule = class TraeRule extends ToolRule {
48358
48498
  * before parsing, inside the frontmatter block only so the body is never
48359
48499
  * rewritten. A quoted value, a YAML flow list, a null or boolean keyword and a
48360
48500
  * 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.
48501
+ * `parseFrontmatter`'s own (it closes the block at the first `\n---`, even
48502
+ * inside a `----` line), so the quoting never reaches text it reads as body.
48363
48503
  */
48364
48504
  static parseTraeFrontmatter(fileContent, filePath) {
48365
48505
  const bounds = findFrontmatterBlockBounds(fileContent);
@@ -51664,19 +51804,17 @@ var CursorCheck = class extends AggregatedToolCheck {
51664
51804
  *
51665
51805
  * rulesync never writes frontmatter here, but a user who authored this path as
51666
51806
  * 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.
51807
+ * review instructions. Left in place it would be carried into the body of
51808
+ * the check written to `.rulesync/checks/` as a block of YAML right behind
51809
+ * that file's own frontmatter, where a `severity: bogus` copied out of a skill
51810
+ * looks like the check's own setting to anyone reading or editing it.
51811
+ *
51812
+ * The block is therefore found the way `parseFrontmatter` finds it rather than
51813
+ * by parsing it, so that what the parser would have read as frontmatter is
51814
+ * what goes: the opening delimiter may carry a language name (`---yaml`), but
51815
+ * four dashes are a horizontal rule the parser itself skips. The one
51816
+ * deliberate difference is a fence nothing closes: the parser would take the
51817
+ * rest of the file, so only the rule line goes and the prose under it is kept.
51680
51818
  */
51681
51819
  const FRONTMATTER_OPEN_PATTERN = /^\uFEFF?---(?!-)[^\r\n]*\r?\n/;
51682
51820
  const FRONTMATTER_CLOSE_PATTERN = /^---|\r?\n---/;
@@ -51941,9 +52079,14 @@ const GooseCheckFrontmatterSchema = zod_mini.z.extend(AmpCheckFrontmatterSchema,
51941
52079
  "turn-limit": zod_mini.z.optional(zod_mini.z.int().check(zod_mini.z.nonnegative()))
51942
52080
  });
51943
52081
  /**
51944
- * Represents a Goose review check (`goose review`), written to the user-wide
52082
+ * Represents a Goose review check, written to the user-wide
51945
52083
  * `~/.config/goose/checks/` (global scope only).
51946
52084
  *
52085
+ * Goose v1.60.0 removed the `goose review` subcommand that ran these checks
52086
+ * (aaif-goose/goose#13469). Goose still discovers them, but only lists them as
52087
+ * agent sources (`properties.kind = "check"`), so `model` and `turn-limit`
52088
+ * have no runtime effect there.
52089
+ *
51947
52090
  * Goose discovers repository checks in `.agents/checks/*.md`, the same
51948
52091
  * cross-tool directory the `amp` checks target already writes (Goose's
51949
52092
  * `tools` and `severity-default` fields exist for parity with Amp's), so the
@@ -56546,7 +56689,11 @@ const CLAUDE_SPEC = {
56546
56689
  tool: "onFailure",
56547
56690
  trueValue: "block",
56548
56691
  falseValue: "continue",
56549
- hookTypes: /* @__PURE__ */ new Set(["command", "http"]),
56692
+ hookTypes: /* @__PURE__ */ new Set([
56693
+ "command",
56694
+ "http",
56695
+ "mcp_tool"
56696
+ ]),
56550
56697
  ignoredEvents: /* @__PURE__ */ new Set([
56551
56698
  "stop",
56552
56699
  "subagentStop",
@@ -59858,7 +60005,7 @@ function canonicalToHermesHooks({ config, toolOverrideHooks, logger }) {
59858
60005
  for (const [nativeEvent, definitions] of Object.entries(toolOverrideHooks ?? {})) {
59859
60006
  if (HERMESAGENT_CANONICAL_EVENTS.has(nativeEvent)) continue;
59860
60007
  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.`);
59861
- else if (!HERMESAGENT_NATIVE_EVENTS.has(nativeEvent)) logger?.warn(`Hermes hook event "${nativeEvent}" is not documented by Hermes Agent v0.22.3; preserving it for forward compatibility.`);
60008
+ 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.`);
59862
60009
  setHermesHookEntries({
59863
60010
  result,
59864
60011
  event: nativeEvent,
@@ -60334,7 +60481,8 @@ const BLOCKING_HOOKS = new Set(Object.keys(NAMED_HOOK_MATCHER_SUBJECTS).filter((
60334
60481
  * 5 minutes). Ordinary commands write to the host's stdout and stderr, as Bun
60335
60482
  * Shell echoed them; a `preToolUse` command's are read, 1 MiB each kept (more
60336
60483
  * stdout denies; on the Bun Shell fallback the whole output is buffered before
60337
- * that check). Output
60484
+ * that check), and a `sessionStart` command's stdout is read the same way while
60485
+ * its stderr goes to the host's (after the command, on Bun Shell). Output
60338
60486
  * pipes a background process keeps open are read for 1 s after the command
60339
60487
  * exits; what arrived by then is kept, and the reads are then cancelled, as
60340
60488
  * they are at a timeout. The OpenCode 1.x-style `event` hooks (`inProcess`)
@@ -60482,15 +60630,18 @@ function buildRunHelperLinesFor(cwdExpression) {
60482
60630
  " const timeout = () => new Promise((resolve) => (timer = setTimeout(resolve, seconds * 1000, null)));",
60483
60631
  " if (inProcess || !(await __rulesyncCanExec)) {",
60484
60632
  ` const run = Bun.$\`echo \${input} | \${{ raw: command }}\`.cwd(${cwdExpression}).nothrow();`,
60485
- " const result = await Promise.race([echo ? run : run.quiet(), timeout()]).finally(() => clearTimeout(timer));",
60486
- " if (!result || echo) return result && { exitCode: result.exitCode };",
60633
+ " // A sessionStart command's stderr reaches the host when it ends, even after its timeout.",
60634
+ " const finished = echo === true ? run : run.quiet().then((done) => (echo && process.stderr.write(done.stderr), done));",
60635
+ " const result = await Promise.race([finished, timeout()]).finally(() => clearTimeout(timer));",
60636
+ " if (!result || echo === true) return result && { exitCode: result.exitCode };",
60487
60637
  " const { exitCode, stdout, stderr } = result;",
60488
60638
  " return { exitCode, stdout: stdout.toString(), stderr: stderr.toString(), overflow: stdout.length > 1048576 };",
60489
60639
  " }",
60490
- " // An ordinary command writes to the host's stdout and stderr; a preToolUse one is read.",
60491
- " const output = echo ? \"inherit\" : \"pipe\";",
60492
- ` const proc = ${spawn("\"export BUN_BE_BUN=\\n\" + command", "new TextEncoder().encode(input + \"\\n\")", "output")};`,
60493
- " const [stdout, stderr] = echo ? [] : [__rulesyncRead(proc.stdout), __rulesyncRead(proc.stderr)];",
60640
+ " // An ordinary command writes to the host's stdout and stderr; a preToolUse one is read, and",
60641
+ " // a sessionStart one (`echo: \"stderr\"`) has its stdout read.",
60642
+ ` const proc = ${spawn("\"export BUN_BE_BUN=\\n\" + command", "new TextEncoder().encode(input + \"\\n\")", "echo === true ? \"inherit\" : \"pipe\"", "echo ? \"inherit\" : \"pipe\"")};`,
60643
+ " const stdout = echo === true ? undefined : __rulesyncRead(proc.stdout);",
60644
+ " const stderr = echo ? undefined : __rulesyncRead(proc.stderr);",
60494
60645
  " const exitCode = await Promise.race([proc.exited, timeout()]).finally(() => clearTimeout(timer));",
60495
60646
  " if (exitCode === null) {",
60496
60647
  " stdout?.stop(), stderr?.stop();",
@@ -60498,15 +60649,15 @@ function buildRunHelperLinesFor(cwdExpression) {
60498
60649
  " else __rulesyncKillTree(proc);",
60499
60650
  " return null;",
60500
60651
  " }",
60501
- " if (echo) return { exitCode };",
60502
- " await Promise.race([Promise.all([stdout.done, stderr.done]), Bun.sleep(1000)]);",
60503
- " stdout.stop(), stderr.stop();",
60504
- " return { exitCode, stdout: stdout.text(), stderr: stderr.text(), overflow: stdout.overflow() };",
60652
+ " if (echo === true) return { exitCode };",
60653
+ " await Promise.race([Promise.all([stdout.done, stderr?.done]), Bun.sleep(1000)]);",
60654
+ " stdout.stop(), stderr?.stop();",
60655
+ " return { exitCode, stdout: stdout.text(), stderr: stderr?.text() ?? \"\", overflow: stdout.overflow() };",
60505
60656
  "};",
60506
- "const __rulesyncRunHook = async ({ label, command, input, blocking, seconds, inProcess = false }) => {",
60657
+ "const __rulesyncRunHook = async ({ label, command, input, blocking, seconds, inProcess = false, context = false }) => {",
60507
60658
  " let result;",
60508
60659
  " try {",
60509
- " result = await __rulesyncRunCommand({ command, input, seconds, inProcess, echo: true });",
60660
+ " result = await __rulesyncRunCommand({ command, input, seconds, inProcess, echo: context ? \"stderr\" : true });",
60510
60661
  " } catch (error) {",
60511
60662
  " if (blocking) throw error;",
60512
60663
  " console.error(\"[rulesync-hooks] \" + label + \" hook failed:\", error);",
@@ -60517,7 +60668,7 @@ function buildRunHelperLinesFor(cwdExpression) {
60517
60668
  " if (blocking) throw new Error(message);",
60518
60669
  " return console.error(message);",
60519
60670
  " }",
60520
- " if (result.exitCode === 0) return;",
60671
+ " if (result.exitCode === 0) return result;",
60521
60672
  " const message = \"[rulesync-hooks] \" + label + \" hook exited with code \" + result.exitCode;",
60522
60673
  " if (blocking) throw new Error(message);",
60523
60674
  " console.error(message);",
@@ -60585,6 +60736,85 @@ const PRE_TOOL_USE_RESULT_HELPER_LINES = [
60585
60736
  " );",
60586
60737
  "};"
60587
60738
  ];
60739
+ /**
60740
+ * Helpers the generated plugin defines when a `sessionStart` handler is
60741
+ * present, so the command's stdout reaches the model as Claude Code's
60742
+ * `SessionStart` stdout does:
60743
+ * - `__rulesyncSessionStart(sessionID, run)` runs a session's `sessionStart`
60744
+ * commands (`run` pushes each command's result) and keeps the pending context
60745
+ * for that session. It always settles, since every command is bounded by its
60746
+ * timeout.
60747
+ * - `__rulesyncSessionContext(sessionID)` waits for that context, which the
60748
+ * host's system-prompt hook then adds to each model request of the session.
60749
+ *
60750
+ * A command's context is its stdout on exit code 0, or the
60751
+ * `hookSpecificOutput.additionalContext` string of a JSON object it prints,
60752
+ * trimmed and capped at Claude Code's 10,000 characters; more than 1 MiB of
60753
+ * stdout is logged and ignored. Only sessions whose context is not empty are
60754
+ * kept, the 100 whose context was used or became ready most recently, and a
60755
+ * deleted session is dropped.
60756
+ */
60757
+ const SESSION_CONTEXT_HELPER_LINES = [
60758
+ "const __rulesyncSessionContexts = new Map();",
60759
+ "const __rulesyncKept = new WeakSet();",
60760
+ "const __rulesyncContextOf = (result) => {",
60761
+ " if (typeof result?.stdout !== \"string\") return \"\";",
60762
+ " if (result.overflow) {",
60763
+ " console.error(\"[rulesync-hooks] sessionStart hook wrote more than 1 MiB to stdout; it is ignored\");",
60764
+ " return \"\";",
60765
+ " }",
60766
+ " let text = result.stdout;",
60767
+ " try {",
60768
+ " const parsed = JSON.parse(text);",
60769
+ " // Like Claude Code, only a JSON object counts as JSON output; anything else is plain text.",
60770
+ " if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) text = parsed.hookSpecificOutput?.additionalContext;",
60771
+ " } catch {}",
60772
+ " return typeof text === \"string\" ? text.trim().slice(0, 10000) : \"\";",
60773
+ "};",
60774
+ "const __rulesyncSessionStart = (sessionID, run) => {",
60775
+ " const results = [];",
60776
+ " const pending = run(results)",
60777
+ " .catch(() => {})",
60778
+ " .then(() => results.map(__rulesyncContextOf).filter(Boolean).join(\"\\n\\n\"));",
60779
+ " if (typeof sessionID === \"string\") {",
60780
+ " __rulesyncSessionContexts.delete(sessionID);",
60781
+ " __rulesyncSessionContexts.set(sessionID, pending);",
60782
+ " // Only a non-empty context is kept, and only it counts towards the 100: a running",
60783
+ " // or empty one never evicts another session's context.",
60784
+ " pending.then((context) => {",
60785
+ " if (__rulesyncSessionContexts.get(sessionID) !== pending) return;",
60786
+ " if (!context) return void __rulesyncSessionContexts.delete(sessionID);",
60787
+ " __rulesyncKept.add(pending);",
60788
+ " // Evict in completion order: a context counts as used once it is ready.",
60789
+ " __rulesyncSessionContexts.delete(sessionID);",
60790
+ " __rulesyncSessionContexts.set(sessionID, pending);",
60791
+ " const kept = [...__rulesyncSessionContexts].filter(([, entry]) => __rulesyncKept.has(entry));",
60792
+ " if (kept.length > 100) __rulesyncSessionContexts.delete(kept[0][0]);",
60793
+ " });",
60794
+ " }",
60795
+ " return pending;",
60796
+ "};",
60797
+ "const __rulesyncSessionContext = async (sessionID) => {",
60798
+ " const pending = __rulesyncSessionContexts.get(sessionID);",
60799
+ " if (!pending) return \"\";",
60800
+ " __rulesyncSessionContexts.delete(sessionID);",
60801
+ " __rulesyncSessionContexts.set(sessionID, pending);",
60802
+ " return pending;",
60803
+ "};"
60804
+ ];
60805
+ /**
60806
+ * The statements of a `sessionStart` group, run through `__rulesyncSessionStart`.
60807
+ * `__rulesyncSessionStart` registers the session's pending context before its
60808
+ * first `await`, so `"void"` (used by the serial V2 event loop) registers it
60809
+ * as soon as the event is read without waiting for the commands.
60810
+ */
60811
+ function wrapSessionStartLines(sessionIdExpression, statements, operator = "await") {
60812
+ return [
60813
+ `${operator} __rulesyncSessionStart(${sessionIdExpression}, async (__rulesyncResults) => {`,
60814
+ ...statements.map((line) => ` ${line}`),
60815
+ "});"
60816
+ ];
60817
+ }
60588
60818
  function escapeForTemplateLiteral(command) {
60589
60819
  return command.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$\{/g, "\\${");
60590
60820
  }
@@ -60645,6 +60875,59 @@ function warnIgnoredFailClosed({ config, supportedEvents, toolConfigKey, logger
60645
60875
  }
60646
60876
  }
60647
60877
  }
60878
+ /**
60879
+ * Canonical (Claude Code) tool names mapped to the lowercase tool ids OpenCode
60880
+ * 1.x and its forks (Kilo, MiMo Code) pass as `input.tool`, which a matcher is
60881
+ * tested against case-sensitively. The shell tool is `bash` here, the same id
60882
+ * the shell events gate on (see {@link SHELL_EVENT_TOOL_GATES}).
60883
+ * @see https://opencode.ai/docs/plugins/
60884
+ */
60885
+ const CANONICAL_TO_OPENCODE_V1_TOOL_NAMES = {
60886
+ Bash: "bash",
60887
+ Read: "read",
60888
+ Write: "write",
60889
+ Edit: "edit"
60890
+ };
60891
+ /**
60892
+ * A matcher made only of plain names joined by `|`, which Claude Code matches
60893
+ * as an exact tool name list rather than as a regex.
60894
+ */
60895
+ const PLAIN_NAME_MATCHER_PATTERN = /^[A-Za-z0-9_]+(?:\|[A-Za-z0-9_]+)*$/;
60896
+ /**
60897
+ * Build a translator that rewrites the canonical tool names in a matcher
60898
+ * through `toolNames` and warns about a capitalized name left over
60899
+ * (`MultiEdit`, `Glob`), which no lowercase tool id can match. Each distinct
60900
+ * matcher of an event is translated once, so hooks sharing one do not repeat
60901
+ * its warning.
60902
+ *
60903
+ * The plugins test the matcher unanchored, so a translated plain-name matcher
60904
+ * is anchored as `^(?:...)$` to keep Claude Code's exact-name semantics:
60905
+ * otherwise `write` would also match OpenCode's `todowrite`. Regex-style and
60906
+ * untranslated matchers are left as written.
60907
+ */
60908
+ function createOpencodeMatcherTranslator({ toolNames, toolConfigKey, logger }) {
60909
+ const label = FAIL_CLOSED_TOOL_LABELS[toolConfigKey];
60910
+ const translated = /* @__PURE__ */ new Map();
60911
+ return (matcher, eventName) => {
60912
+ const key = `${eventName}\0${matcher}`;
60913
+ const cached = translated.get(key);
60914
+ if (cached !== void 0) return cached;
60915
+ const replaced = replaceMatcherNames(matcher, toolNames);
60916
+ const result = replaced !== matcher && PLAIN_NAME_MATCHER_PATTERN.test(stripControlChars(matcher)) ? `^(?:${replaced})$` : replaced;
60917
+ const unmatched = capitalizedMatcherNames(result);
60918
+ 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.`);
60919
+ translated.set(key, result);
60920
+ return result;
60921
+ };
60922
+ }
60923
+ /** Whether any handler is a `sessionStart` one, whose stdout becomes session context. */
60924
+ function usesSessionContext(handlers) {
60925
+ return handlers.some((handler) => handler.context);
60926
+ }
60927
+ /** The handler fields a canonical event's `sessionStart`-ness adds. */
60928
+ function sessionContextExtrasFor(canonicalEvent) {
60929
+ return canonicalEvent === "sessionStart" ? { context: true } : {};
60930
+ }
60648
60931
  /** The per-canonical-event gates and payload every handler of it carries. */
60649
60932
  function handlerExtrasFor(canonicalEvent) {
60650
60933
  const shellGate = SHELL_EVENT_TOOL_GATES[canonicalEvent];
@@ -60654,14 +60937,15 @@ function handlerExtrasFor(canonicalEvent) {
60654
60937
  event: canonicalEvent,
60655
60938
  ...shellGate ? { toolGate: shellGate.tool } : {},
60656
60939
  ...propertyGate ? { propertyGate } : {},
60657
- ...payload ? { payload } : {}
60940
+ ...payload ? { payload } : {},
60941
+ ...sessionContextExtrasFor(canonicalEvent)
60658
60942
  };
60659
60943
  }
60660
60944
  /**
60661
60945
  * Group the effective hooks into named (tool.execute.*) and generic event
60662
60946
  * handler groups, keyed by tool event name. Mutates the supplied groups.
60663
60947
  */
60664
- function collectOpencodeStyleHandlers({ effectiveHooks, eventMap, namedEventHandlers, genericEventHandlers }) {
60948
+ function collectOpencodeStyleHandlers({ effectiveHooks, eventMap, namedEventHandlers, genericEventHandlers, translateMatcher }) {
60665
60949
  for (const [canonicalEvent, definitions] of Object.entries(effectiveHooks)) {
60666
60950
  const shellGate = SHELL_EVENT_TOOL_GATES[canonicalEvent];
60667
60951
  const extras = handlerExtrasFor(canonicalEvent);
@@ -60669,6 +60953,7 @@ function collectOpencodeStyleHandlers({ effectiveHooks, eventMap, namedEventHand
60669
60953
  if (!toolEvent) continue;
60670
60954
  const isNamedHook = Object.hasOwn(NAMED_HOOK_MATCHER_SUBJECTS, toolEvent);
60671
60955
  const matcherSupported = !shellGate && isNamedHook && NAMED_HOOK_MATCHER_SUBJECTS[toolEvent] !== null;
60956
+ const matchesToolName = NAMED_HOOK_MATCHER_SUBJECTS[toolEvent] === "input.tool";
60672
60957
  const handlers = [];
60673
60958
  for (const def of definitions) {
60674
60959
  if ((def.type ?? "command") !== "command") continue;
@@ -60676,7 +60961,7 @@ function collectOpencodeStyleHandlers({ effectiveHooks, eventMap, namedEventHand
60676
60961
  if (def.matcher && !matcherSupported) continue;
60677
60962
  handlers.push({
60678
60963
  command: def.command,
60679
- matcher: def.matcher ? def.matcher : void 0,
60964
+ matcher: def.matcher ? matchesToolName ? translateMatcher(def.matcher, canonicalEvent) : def.matcher : void 0,
60680
60965
  blocking: BLOCKING_HOOKS.has(toolEvent),
60681
60966
  ...hookTimingOf(def),
60682
60967
  inProcess: !isNamedHook,
@@ -60696,22 +60981,22 @@ function buildGenericEventBodyLines(genericEventHandlers) {
60696
60981
  const bodyLines = [];
60697
60982
  if (Object.keys(genericEventHandlers).length === 0) return bodyLines;
60698
60983
  bodyLines.push(" event: async ({ event }) => {");
60984
+ if (Object.values(genericEventHandlers).some(usesSessionContext)) bodyLines.push(` if (event.type === "session.deleted") __rulesyncSessionContexts.delete(${V1_SESSION_ID_EXPRESSION});`);
60699
60985
  let isFirst = true;
60700
60986
  for (const [eventName, handlers] of Object.entries(genericEventHandlers)) {
60701
60987
  bodyLines.push(` ${isFirst ? "if" : "else if"} (event.type === "${eventName}") {`);
60702
60988
  isFirst = false;
60703
- for (const line of buildPayloadClosureLines({
60989
+ const statements = buildPayloadClosureLines({
60704
60990
  handlers,
60705
60991
  cwdExpression: V1_CWD_EXPRESSION
60706
- })) bodyLines.push(` ${line}`);
60992
+ });
60707
60993
  for (const handler of handlers) {
60708
60994
  const runStatement = buildRunStatement(handler);
60709
- if (handler.propertyGate) {
60710
- bodyLines.push(` if (${handler.propertyGate}) {`);
60711
- bodyLines.push(` ${runStatement}`);
60712
- bodyLines.push(" }");
60713
- } else bodyLines.push(` ${runStatement}`);
60995
+ if (handler.propertyGate) statements.push(`if (${handler.propertyGate}) {`, ` ${runStatement}`, "}");
60996
+ else statements.push(runStatement);
60714
60997
  }
60998
+ const lines = usesSessionContext(handlers) ? wrapSessionStartLines(V1_SESSION_ID_EXPRESSION, statements) : statements;
60999
+ bodyLines.push(...lines.map((line) => ` ${line}`));
60715
61000
  bodyLines.push(" }");
60716
61001
  }
60717
61002
  bodyLines.push(" },");
@@ -60722,6 +61007,19 @@ function stdinPayloadVariable(stdinEvent) {
60722
61007
  }
60723
61008
  /** The `cwd` a V1 payload reports: the session directory, else the process's. */
60724
61009
  const V1_CWD_EXPRESSION = "directory ?? process.cwd()";
61010
+ /** The session a V1 `session.created` / `session.deleted` event is about. */
61011
+ const V1_SESSION_ID_EXPRESSION = "event.properties?.info?.id";
61012
+ /**
61013
+ * The V1 named hook that adds a session's `sessionStart` context to the system
61014
+ * prompt of each of its model requests. OpenCode 1.x, Kilo and MiMo Code all
61015
+ * call it with the request's `sessionID`.
61016
+ */
61017
+ const V1_SYSTEM_TRANSFORM_LINES = [
61018
+ " \"experimental.chat.system.transform\": async (input, output) => {",
61019
+ " const context = await __rulesyncSessionContext(input?.sessionID);",
61020
+ " if (context && Array.isArray(output?.system)) output.system.push(context);",
61021
+ " },"
61022
+ ];
60725
61023
  /** Lazily serialized closures for the payloads the handlers use (internal tables only). */
60726
61024
  function buildPayloadClosureLines({ handlers, cwdExpression }) {
60727
61025
  const payloads = /* @__PURE__ */ new Map();
@@ -60749,20 +61047,27 @@ function buildRunStatement(handler) {
60749
61047
  const failClosed = handler.failClosed === void 0 ? "" : `, ${handler.failClosed}`;
60750
61048
  return `${PRE_TOOL_USE_RESULT_HELPER}(await __rulesyncRunCommand({ command: ${command}, input: ${input}, seconds: ${handler.timeout} })${failClosed});`;
60751
61049
  }
60752
- return `await __rulesyncRunHook({ ${[
61050
+ const run = `await __rulesyncRunHook({ ${[
60753
61051
  `label: ${JSON.stringify(handler.event)}`,
60754
61052
  `command: ${command}`,
60755
61053
  `input: ${input}`,
60756
61054
  `blocking: ${handler.blocking}`,
60757
61055
  `seconds: ${handler.timeout}`,
60758
- ...handler.inProcess ? ["inProcess: true"] : []
60759
- ].join(", ")} });`;
61056
+ ...handler.inProcess ? ["inProcess: true"] : [],
61057
+ ...handler.context ? ["context: true"] : []
61058
+ ].join(", ")} })`;
61059
+ return handler.context ? `__rulesyncResults.push(${run});` : `${run};`;
60760
61060
  }
60761
61061
  /** The helpers a plugin body defines before its handlers, run in `cwdExpression`. */
60762
61062
  function buildRunHelperLines({ handlers, cwdExpression }) {
60763
61063
  if (handlers.length === 0) return [];
60764
61064
  const usesPreToolUse = handlers.some((handler) => handler.payload?.name === "PreToolUse");
60765
- return [...buildRunHelperLinesFor(cwdExpression), ...usesPreToolUse ? ["", ...PRE_TOOL_USE_RESULT_HELPER_LINES] : []];
61065
+ const usesContext = usesSessionContext(handlers);
61066
+ return [
61067
+ ...buildRunHelperLinesFor(cwdExpression),
61068
+ ...usesPreToolUse ? ["", ...PRE_TOOL_USE_RESULT_HELPER_LINES] : [],
61069
+ ...usesContext ? ["", ...SESSION_CONTEXT_HELPER_LINES] : []
61070
+ ];
60766
61071
  }
60767
61072
  /** Emit the named (`tool.execute.*`) handler blocks. */
60768
61073
  function buildNamedEventBodyLines(namedEventHandlers) {
@@ -60820,7 +61125,7 @@ function wrapInExportShape({ preambleLines, bodyLines, exportStyle }) {
60820
61125
  lines.push("");
60821
61126
  return lines;
60822
61127
  }
60823
- function generateOpencodeStylePluginCode(config, supportedEvents, toolConfigKey, eventMap, exportStyle = "named") {
61128
+ function generateOpencodeStylePluginCode(config, supportedEvents, toolConfigKey, eventMap, exportStyle = "named", logger) {
60824
61129
  const supported = new Set(supportedEvents);
60825
61130
  const configHooks = {
60826
61131
  ...config.hooks,
@@ -60834,9 +61139,19 @@ function generateOpencodeStylePluginCode(config, supportedEvents, toolConfigKey,
60834
61139
  effectiveHooks,
60835
61140
  eventMap,
60836
61141
  namedEventHandlers,
60837
- genericEventHandlers
61142
+ genericEventHandlers,
61143
+ translateMatcher: createOpencodeMatcherTranslator({
61144
+ toolNames: CANONICAL_TO_OPENCODE_V1_TOOL_NAMES,
61145
+ toolConfigKey,
61146
+ logger
61147
+ })
60838
61148
  });
60839
- const bodyLines = [...buildGenericEventBodyLines(genericEventHandlers), ...buildNamedEventBodyLines(namedEventHandlers)];
61149
+ const usesContext = Object.values(genericEventHandlers).some(usesSessionContext);
61150
+ const bodyLines = [
61151
+ ...buildGenericEventBodyLines(genericEventHandlers),
61152
+ ...buildNamedEventBodyLines(namedEventHandlers),
61153
+ ...usesContext ? V1_SYSTEM_TRANSFORM_LINES : []
61154
+ ];
60840
61155
  return wrapInExportShape({
60841
61156
  preambleLines: buildRunHelperLines({
60842
61157
  handlers: [...Object.values(namedEventHandlers), ...Object.values(genericEventHandlers)].flat(),
@@ -60883,7 +61198,7 @@ var KiloHooks = class KiloHooks extends ToolHooks {
60883
61198
  toolConfigKey: "kilo",
60884
61199
  logger
60885
61200
  });
60886
- const fileContent = generateOpencodeStylePluginCode(config, KILO_HOOK_EVENTS, "kilo", CANONICAL_TO_KILO_EVENT_NAMES, "default");
61201
+ const fileContent = generateOpencodeStylePluginCode(config, KILO_HOOK_EVENTS, "kilo", CANONICAL_TO_KILO_EVENT_NAMES, "default", logger);
60887
61202
  const paths = KiloHooks.getSettablePaths({ global });
60888
61203
  return new KiloHooks({
60889
61204
  outputRoot,
@@ -61149,6 +61464,37 @@ const KiroIdeHooksFileSchema = zod_mini.z.looseObject({
61149
61464
  hooks: zod_mini.z.optional(zod_mini.z.array(KiroIdeHookEntrySchema))
61150
61465
  });
61151
61466
  /**
61467
+ * Triggers on which Kiro runs only `command` actions.
61468
+ * @see https://kiro.dev/docs/hooks/types/#permission-request
61469
+ */
61470
+ const KIRO_COMMAND_ONLY_TRIGGERS = /* @__PURE__ */ new Set(["PermissionRequest"]);
61471
+ /**
61472
+ * Whether an imported entry is an `agent` action on a command-only trigger
61473
+ * (Kiro also accepts the camelCase `permissionRequest` spelling). Kiro never
61474
+ * runs such a hook, so importing it would hand other targets an LLM
61475
+ * permission hook the user never had in effect.
61476
+ */
61477
+ function isAgentActionOnCommandOnlyTrigger(entry) {
61478
+ if (entry.action?.type !== "agent" || entry.trigger === void 0) return false;
61479
+ const trigger = lookupOwn({
61480
+ record: CANONICAL_TO_KIRO_IDE_EVENT_NAMES,
61481
+ key: entry.trigger
61482
+ }) ?? entry.trigger;
61483
+ return KIRO_COMMAND_ONLY_TRIGGERS.has(trigger);
61484
+ }
61485
+ /**
61486
+ * Drop `prompt` definitions on a {@link KIRO_COMMAND_ONLY_TRIGGERS} trigger with
61487
+ * a warning, rather than writing an `agent` action Kiro never runs.
61488
+ */
61489
+ function dropPromptHooksOnCommandOnlyTrigger(trigger, definitions, logger) {
61490
+ if (!KIRO_COMMAND_ONLY_TRIGGERS.has(trigger)) return definitions;
61491
+ return definitions.filter((def) => {
61492
+ if (def.type !== "prompt") return true;
61493
+ logger?.warn(`Skipped a prompt hook on Kiro's "${trigger}" trigger: Kiro runs only command actions on it.`);
61494
+ return false;
61495
+ });
61496
+ }
61497
+ /**
61152
61498
  * Build the Kiro IDE hook entries for a single canonical event's definitions.
61153
61499
  *
61154
61500
  * `command`-type definitions become `{ type: "command", command }` actions and
@@ -61203,7 +61549,7 @@ const KIRO_HOOKS_OVERRIDE_KEY = "kiro";
61203
61549
  * that is actually read.
61204
61550
  */
61205
61551
  const KIRO_HOOKS_IGNORED_OVERRIDE_KEYS = ["kiro-ide", "kiro-cli"];
61206
- function canonicalToKiroIdeHooks(config) {
61552
+ function canonicalToKiroIdeHooks(config, logger) {
61207
61553
  const kiroIdeSupported = new Set(KIRO_IDE_HOOK_EVENTS);
61208
61554
  const sharedHooks = {};
61209
61555
  for (const [event, defs] of Object.entries(config.hooks)) if (kiroIdeSupported.has(event)) sharedHooks[event] = defs;
@@ -61220,7 +61566,7 @@ function canonicalToKiroIdeHooks(config) {
61220
61566
  record: KIRO_LEGACY_TO_KIRO_IDE_TRIGGER_NAMES,
61221
61567
  key: eventName
61222
61568
  }) ?? eventName;
61223
- entries.push(...buildKiroIdeEntriesForEvent(trigger, definitions));
61569
+ entries.push(...buildKiroIdeEntriesForEvent(trigger, dropPromptHooksOnCommandOnlyTrigger(trigger, definitions, logger)));
61224
61570
  }
61225
61571
  return entries;
61226
61572
  }
@@ -61232,25 +61578,35 @@ function copyOptionalHookFields({ entry, def }) {
61232
61578
  if (entry.enabled === false) def.enabled = false;
61233
61579
  if (entry.confirm !== void 0 && entry.confirm !== null) def.confirm = omitPrototypePollutionKeysDeep(entry.confirm);
61234
61580
  }
61235
- function kiroIdeHooksToCanonical(entries) {
61581
+ /**
61582
+ * The canonical `type` plus `command` / `prompt` of an imported Kiro action, or
61583
+ * `undefined` when the action carries nothing to run.
61584
+ */
61585
+ function toCanonicalAction(action) {
61586
+ if (action.type === "command") return action.command ? {
61587
+ type: "command",
61588
+ command: action.command
61589
+ } : void 0;
61590
+ return action.prompt ? {
61591
+ type: "prompt",
61592
+ prompt: action.prompt
61593
+ } : void 0;
61594
+ }
61595
+ function kiroIdeHooksToCanonical(entries, logger) {
61236
61596
  const canonical = {};
61237
61597
  for (const entry of entries) {
61238
61598
  if (entry.trigger === void 0 || entry.action === void 0) continue;
61599
+ if (isAgentActionOnCommandOnlyTrigger(entry)) {
61600
+ logger?.warn(`Skipped an agent hook on Kiro's "${entry.trigger}" trigger: Kiro runs only command actions on it.`);
61601
+ continue;
61602
+ }
61239
61603
  const eventName = lookupOwn({
61240
61604
  record: KIRO_IDE_TO_CANONICAL_EVENT_NAMES,
61241
61605
  key: entry.trigger
61242
61606
  }) ?? entry.trigger;
61243
61607
  if (isPrototypePollutionKey(eventName)) continue;
61244
- const def = {};
61245
- if (entry.action.type === "command") {
61246
- if (!entry.action.command) continue;
61247
- def.type = "command";
61248
- def.command = entry.action.command;
61249
- } else {
61250
- if (!entry.action.prompt) continue;
61251
- def.type = "prompt";
61252
- def.prompt = entry.action.prompt;
61253
- }
61608
+ const def = toCanonicalAction(entry.action);
61609
+ if (def === void 0) continue;
61254
61610
  if (entry.name !== void 0 && entry.name !== null) def.name = entry.name;
61255
61611
  if (entry.description !== void 0 && entry.description !== null) def.description = entry.description;
61256
61612
  if (entry.matcher !== void 0 && entry.matcher !== null && entry.matcher !== "") def.matcher = entry.matcher;
@@ -61316,7 +61672,7 @@ var KiroIdeHooks = class extends ToolHooks {
61316
61672
  if (config[ignoredKey]?.hooks === void 0) continue;
61317
61673
  logger?.warn(`The "${ignoredKey}.hooks" block in ${(0, node_path.join)(rulesyncHooks.getRelativeDirPath(), rulesyncHooks.getRelativeFilePath())} is ignored. Author it under the "${KIRO_HOOKS_OVERRIDE_KEY}.hooks" key instead: the Kiro IDE and Kiro CLI targets write the same hooks file, so they read one shared block.`);
61318
61674
  }
61319
- const hooks = canonicalToKiroIdeHooks(config);
61675
+ const hooks = canonicalToKiroIdeHooks(config, logger);
61320
61676
  const fileContent = JSON.stringify({
61321
61677
  version: "v1",
61322
61678
  hooks
@@ -61333,7 +61689,7 @@ var KiroIdeHooks = class extends ToolHooks {
61333
61689
  const hooks = kiroIdeHooksToCanonical(this.parseFileContentOrThrow({
61334
61690
  displayName: "Kiro IDE",
61335
61691
  parse: (fileContent) => KiroIdeHooksFileSchema.parse(JSON.parse(fileContent))
61336
- }).hooks ?? []);
61692
+ }).hooks ?? [], logger);
61337
61693
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
61338
61694
  logger,
61339
61695
  hooks,
@@ -61706,6 +62062,21 @@ var LettacodeHooks = class LettacodeHooks extends ToolHooks {
61706
62062
  /** Tool name OpenCode V2 gives its shell tool (V1 called it `bash`). */
61707
62063
  const OPENCODE_V2_SHELL_TOOL = "shell";
61708
62064
  /**
62065
+ * Canonical (Claude Code) tool names mapped to the lowercase names OpenCode 2.x
62066
+ * reports in `event.tool`, which a matcher is tested against case-sensitively.
62067
+ * Observed on OpenCode 2.3.2: a `preToolUse` hook fires with `read`, `write`,
62068
+ * `edit` and `shell`, so a canonical `Read|Edit|Write` or `Bash` never matched.
62069
+ * `Bash` becomes the V2 name `shell`; the generated helper still accepts the
62070
+ * V1 name `bash` for a matcher written that way.
62071
+ * https://opencode.ai/v2/docs/build/plugins/
62072
+ */
62073
+ const CANONICAL_TO_OPENCODE_V2_TOOL_NAMES = {
62074
+ Bash: OPENCODE_V2_SHELL_TOOL,
62075
+ Read: "read",
62076
+ Write: "write",
62077
+ Edit: "edit"
62078
+ };
62079
+ /**
61709
62080
  * Per-canonical-event conditions the generated handler gates on, because the
61710
62081
  * hook point or event it shares fires more broadly than the canonical event:
61711
62082
  * - the shell events run only for the `shell` tool's calls;
@@ -61765,6 +62136,27 @@ const TOOL_MATCHER_HELPER_LINES = [
61765
62136
  ];
61766
62137
  /** Hook points whose `matcher` is tested against the tool name. */
61767
62138
  const OPENCODE_V2_MATCHABLE_HOOKS = /* @__PURE__ */ new Set(["tool:execute.before", "tool:execute.after"]);
62139
+ /** The session a V2 `session.created` / `session.deleted` event is about. */
62140
+ const V2_SESSION_ID_EXPRESSION = "event.data?.sessionID";
62141
+ /**
62142
+ * The `session:context` registration that adds a session's `sessionStart`
62143
+ * context to the system prompt of each of its agent-loop model requests. A
62144
+ * host that cannot register it (no `ctx.session.hook`, or no `context` hook
62145
+ * point) gets a logged error instead of a setup throw, so the plugin's other
62146
+ * hooks, `preToolUse` guards included, still load.
62147
+ */
62148
+ const SESSION_CONTEXT_HOOK_LINES = [
62149
+ "try {",
62150
+ " __rulesyncRegistrations.push(",
62151
+ " await ctx.session.hook(\"context\", async (event) => {",
62152
+ " const context = await __rulesyncSessionContext(event?.sessionID);",
62153
+ " if (context && Array.isArray(event?.system)) event.system.push({ type: \"text\", text: context });",
62154
+ " }),",
62155
+ " );",
62156
+ "} catch (error) {",
62157
+ " console.error(\"[rulesync-hooks] could not register the session context hook; sessionStart output does not reach the model:\", error);",
62158
+ "}"
62159
+ ];
61768
62160
  /** Wrap a statement in the handler's gate and matcher conditions. */
61769
62161
  function wrapInConditions(handler, statement, indent) {
61770
62162
  const conditions = [];
@@ -61801,32 +62193,52 @@ function buildHookRegistrationLines(hookPoint, handlers) {
61801
62193
  * in its own try/catch, so a throw while evaluating its gate or building its
61802
62194
  * payload, outside `__rulesyncRunHook`, is logged the same way. The
61803
62195
  * subscription passes `types` so the server delivers only the handled events.
62196
+ *
62197
+ * The loop itself never waits for a command, so a slow handler cannot hold back
62198
+ * the events after it: handlers run one after another on
62199
+ * `__rulesyncEventQueue`, in event order, while `sessionStart` starts right
62200
+ * away, outside the queue (so it can overlap other event commands), and its
62201
+ * session's pending context is registered before that session's first model
62202
+ * request asks for it. Handlers still queued at dispose are skipped.
61804
62203
  */
61805
- function buildEventLoopLines(eventHandlers) {
62204
+ function buildEventLoopLines(eventHandlers, usesContext) {
61806
62205
  const lines = [];
61807
- const types = [...eventHandlers.keys()].map((eventType) => JSON.stringify(eventType)).join(", ");
62206
+ const eventTypes = new Set(eventHandlers.keys());
62207
+ if (usesContext) eventTypes.add("session.deleted");
62208
+ const types = [...eventTypes].map((eventType) => JSON.stringify(eventType)).join(", ");
61808
62209
  lines.push("const __rulesyncEvents = new AbortController();");
62210
+ lines.push("let __rulesyncEventQueue = Promise.resolve();");
61809
62211
  lines.push("void (async () => {");
61810
62212
  lines.push(" for await (const event of ctx.event.subscribe({");
61811
62213
  lines.push(` types: [${types}],`);
61812
62214
  lines.push(" signal: __rulesyncEvents.signal,");
61813
62215
  lines.push(" })) {");
62216
+ if (usesContext) lines.push(` if (event.type === "session.deleted") __rulesyncSessionContexts.delete(${V2_SESSION_ID_EXPRESSION});`);
61814
62217
  let isFirst = true;
61815
62218
  for (const [eventType, handlers] of eventHandlers) {
61816
62219
  lines.push(` ${isFirst ? "if" : "} else if"} (event.type === "${eventType}") {`);
61817
62220
  isFirst = false;
61818
- lines.push(...buildPayloadClosureLines({
62221
+ const statements = buildPayloadClosureLines({
61819
62222
  handlers,
61820
62223
  cwdExpression: "directory"
61821
- }).map((line) => ` ${line}`));
62224
+ });
61822
62225
  for (const handler of handlers) {
61823
- lines.push(" try {");
61824
- lines.push(...wrapInConditions(handler, buildRunStatement(handler), " "));
61825
- lines.push(" } catch (error) {");
62226
+ statements.push("try {");
62227
+ statements.push(...wrapInConditions(handler, buildRunStatement(handler), " "));
62228
+ statements.push("} catch (error) {");
61826
62229
  const message = JSON.stringify(`[rulesync-hooks] ${handler.event} hook failed:`);
61827
- lines.push(` console.error(${message}, error);`);
61828
- lines.push(" }");
61829
- }
62230
+ statements.push(` console.error(${message}, error);`);
62231
+ statements.push("}");
62232
+ }
62233
+ const body = usesSessionContext(handlers) ? wrapSessionStartLines(V2_SESSION_ID_EXPRESSION, statements, "void") : [
62234
+ "__rulesyncEventQueue = __rulesyncEventQueue",
62235
+ " .then(async () => {",
62236
+ " if (__rulesyncEvents.signal.aborted) return;",
62237
+ ...statements.map((line) => ` ${line}`),
62238
+ " })",
62239
+ ` .catch((error) => console.error(${JSON.stringify(`[rulesync-hooks] ${eventType} event hook failed:`)}, error));`
62240
+ ];
62241
+ lines.push(...body.map((line) => ` ${line}`));
61830
62242
  }
61831
62243
  lines.push(" }");
61832
62244
  lines.push(" }");
@@ -61841,7 +62253,7 @@ function isBlockingOpencodeV2Target(target) {
61841
62253
  return !target.startsWith("event:") && target !== "tool:execute.after";
61842
62254
  }
61843
62255
  /** Build the handlers of one canonical event's command definitions. */
61844
- function buildHandlersFor({ canonicalEvent, definitions, target }) {
62256
+ function buildHandlersFor({ canonicalEvent, definitions, target, translateMatcher }) {
61845
62257
  const gate = OPENCODE_V2_HANDLER_GATES[canonicalEvent];
61846
62258
  const payload = OPENCODE_V2_STDIN_PAYLOADS[canonicalEvent];
61847
62259
  const matcherSupported = !(canonicalEvent === "beforeShellExecution" || canonicalEvent === "afterShellExecution") && OPENCODE_V2_MATCHABLE_HOOKS.has(target);
@@ -61855,9 +62267,10 @@ function buildHandlersFor({ canonicalEvent, definitions, target }) {
61855
62267
  event: canonicalEvent,
61856
62268
  blocking: isBlockingOpencodeV2Target(target),
61857
62269
  ...hookTimingOf(def),
61858
- ...def.matcher ? { matcher: def.matcher } : {},
62270
+ ...def.matcher ? { matcher: translateMatcher(def.matcher, canonicalEvent) } : {},
61859
62271
  ...gate ? { gate } : {},
61860
- ...payload ? { payload } : {}
62272
+ ...payload ? { payload } : {},
62273
+ ...sessionContextExtrasFor(canonicalEvent)
61861
62274
  });
61862
62275
  }
61863
62276
  return handlers;
@@ -61874,25 +62287,33 @@ function buildSetupBodyLines({ hookHandlers, eventHandlers }) {
61874
62287
  })
61875
62288
  ];
61876
62289
  if ([...hookHandlers.values()].some((handlers) => handlers.some((handler) => handler.matcher !== void 0))) body.push("", ...TOOL_MATCHER_HELPER_LINES);
62290
+ const usesContext = [...eventHandlers.values()].some(usesSessionContext);
62291
+ const registers = hookHandlers.size > 0 || usesContext;
61877
62292
  const cleanup = [];
61878
- if (hookHandlers.size > 0) {
62293
+ if (registers) {
61879
62294
  body.push("", "const __rulesyncRegistrations = [];");
61880
62295
  for (const [hookPoint, handlers] of hookHandlers) body.push(...buildHookRegistrationLines(hookPoint, handlers));
62296
+ if (usesContext) body.push(...SESSION_CONTEXT_HOOK_LINES);
61881
62297
  }
61882
62298
  if (eventHandlers.size > 0) {
61883
- body.push("", ...buildEventLoopLines(eventHandlers));
62299
+ body.push("", ...buildEventLoopLines(eventHandlers, usesContext));
61884
62300
  cleanup.push(" __rulesyncEvents.abort();");
61885
62301
  }
61886
- if (hookHandlers.size > 0) cleanup.push(" await Promise.all(__rulesyncRegistrations.map((registration) => registration.dispose()));");
62302
+ if (registers) cleanup.push(" await Promise.all(__rulesyncRegistrations.map((registration) => registration.dispose()));");
61887
62303
  body.push("", "return async () => {", ...cleanup, "};");
61888
62304
  return body;
61889
62305
  }
61890
- function generateOpencodeV2PluginCode({ config, supportedEvents, toolConfigKey, eventMap }) {
62306
+ function generateOpencodeV2PluginCode({ config, supportedEvents, toolConfigKey, eventMap, logger }) {
61891
62307
  const supported = new Set(supportedEvents);
61892
62308
  const configHooks = {
61893
62309
  ...config.hooks,
61894
62310
  ...config[toolConfigKey]?.hooks
61895
62311
  };
62312
+ const translateMatcher = createOpencodeMatcherTranslator({
62313
+ toolNames: CANONICAL_TO_OPENCODE_V2_TOOL_NAMES,
62314
+ toolConfigKey,
62315
+ logger
62316
+ });
61896
62317
  const hookHandlers = /* @__PURE__ */ new Map();
61897
62318
  const eventHandlers = /* @__PURE__ */ new Map();
61898
62319
  for (const [canonicalEvent, definitions] of Object.entries(configHooks)) {
@@ -61902,7 +62323,8 @@ function generateOpencodeV2PluginCode({ config, supportedEvents, toolConfigKey,
61902
62323
  const handlers = buildHandlersFor({
61903
62324
  canonicalEvent,
61904
62325
  definitions,
61905
- target
62326
+ target,
62327
+ translateMatcher
61906
62328
  });
61907
62329
  if (handlers.length === 0) continue;
61908
62330
  const isEvent = target.startsWith("event:");
@@ -61957,8 +62379,9 @@ var OpencodeHooks = class extends ToolHooks {
61957
62379
  config,
61958
62380
  supportedEvents: OPENCODE_V2_HOOK_EVENTS,
61959
62381
  toolConfigKey: this.layout.toolTarget,
61960
- eventMap: CANONICAL_TO_OPENCODE_V2_EVENT_NAMES
61961
- }) : generateOpencodeStylePluginCode(config, OPENCODE_HOOK_EVENTS, this.layout.toolTarget, CANONICAL_TO_OPENCODE_EVENT_NAMES);
62382
+ eventMap: CANONICAL_TO_OPENCODE_V2_EVENT_NAMES,
62383
+ logger
62384
+ }) : generateOpencodeStylePluginCode(config, OPENCODE_HOOK_EVENTS, this.layout.toolTarget, CANONICAL_TO_OPENCODE_EVENT_NAMES, "named", logger);
61962
62385
  const paths = this.getSettablePaths({ global });
61963
62386
  return new this({
61964
62387
  outputRoot,
@@ -72723,12 +73146,22 @@ const MAX_REMOVE_EMPTY_ENTRIES_DEPTH = 32;
72723
73146
  */
72724
73147
  const GROK_DISABLED_MCP_TOOLS_KEY = "disabled_mcp_tools";
72725
73148
  /**
73149
+ * Grok 1.0.88+ runs a command that prints JSON headers at every connect of an
73150
+ * HTTP/SSE server. In `config.toml` the key is `headers_helper`; the camelCase
73151
+ * `headersHelper` (rulesync's canonical spelling) is documented for
73152
+ * `.mcp.json` only, so it is renamed in both directions.
73153
+ * (Grok user guide `07-mcp-servers.md`, "Headers from a command".)
73154
+ */
73155
+ const CANONICAL_HEADERS_HELPER_KEY = "headersHelper";
73156
+ const GROK_HEADERS_HELPER_KEY = "headers_helper";
73157
+ /**
72726
73158
  * Grok Build stores MCP servers in `config.toml` under a `[mcp_servers.<name>]`
72727
73159
  * table. Verified against `grok mcp add` (grok 0.2.54): a stdio server emits
72728
73160
  * `command`, `args`, `enabled = true`, and an `[mcp_servers.<name>.env]` table;
72729
73161
  * a remote server emits `url` and `enabled`. Unlike Codex CLI, Grok uses a
72730
- * literal `env` table (not the `env_vars` passthrough list), so the only field
72731
- * rename is `disabled` (rulesync) ↔ `enabled = false` (grok). `disabledTools`
73162
+ * literal `env` table (not the `env_vars` passthrough list), so the field
73163
+ * renames are `disabled` (rulesync) ↔ `enabled = false` (grok) and
73164
+ * `headersHelper` ↔ `headers_helper`. `disabledTools`
72732
73165
  * never lands in the server table: it is lifted into the top-level
72733
73166
  * `[disabled_mcp_tools]` table by `buildDisabledMcpTools`.
72734
73167
  */
@@ -72742,6 +73175,8 @@ function convertToGrokFormat(mcpServers) {
72742
73175
  if (PROTOTYPE_POLLUTION_KEYS.has(key) || key === "disabledTools") continue;
72743
73176
  if (key === "disabled") {
72744
73177
  if (value === true) converted["enabled"] = false;
73178
+ } else if (key === CANONICAL_HEADERS_HELPER_KEY) {
73179
+ if (!Object.hasOwn(config, GROK_HEADERS_HELPER_KEY)) converted[GROK_HEADERS_HELPER_KEY] = value;
72745
73180
  } else converted[key] = value;
72746
73181
  }
72747
73182
  result[name] = converted;
@@ -72757,6 +73192,9 @@ function convertFromGrokFormat(grokMcp) {
72757
73192
  if (PROTOTYPE_POLLUTION_KEYS.has(key)) continue;
72758
73193
  if (key === "enabled") {
72759
73194
  if (value === false) converted["disabled"] = true;
73195
+ } else if (key === GROK_HEADERS_HELPER_KEY) converted[CANONICAL_HEADERS_HELPER_KEY] = value;
73196
+ else if (key === CANONICAL_HEADERS_HELPER_KEY) {
73197
+ if (!Object.hasOwn(config, GROK_HEADERS_HELPER_KEY)) converted[CANONICAL_HEADERS_HELPER_KEY] = value;
72760
73198
  } else converted[key] = value;
72761
73199
  }
72762
73200
  result[name] = converted;
@@ -73872,6 +74310,21 @@ function fromKiroMcpServers(servers) {
73872
74310
  }];
73873
74311
  }));
73874
74312
  }
74313
+ /**
74314
+ * Parse an existing user-level `~/.kiro/settings/mcp.json` so a global generate
74315
+ * can merge into it. An unparseable file is refused instead of overwritten:
74316
+ * it is unversioned, so replacing it would lose whatever the user had there.
74317
+ */
74318
+ function parseExistingKiroMcpConfig(fileContent, configPath) {
74319
+ let parsed;
74320
+ try {
74321
+ parsed = JSON.parse(fileContent);
74322
+ } catch (error) {
74323
+ throw new Error(`Failed to parse Kiro MCP config at ${configPath}: ${formatError(error)}`, { cause: error });
74324
+ }
74325
+ if (!isPlainObject(parsed)) throw new Error(`Failed to parse Kiro MCP config at ${configPath}: expected a JSON object`);
74326
+ return parsed;
74327
+ }
73875
74328
  var KiroMcp = class KiroMcp extends ToolMcp {
73876
74329
  json;
73877
74330
  constructor(params) {
@@ -73881,13 +74334,26 @@ var KiroMcp = class KiroMcp extends ToolMcp {
73881
74334
  getJson() {
73882
74335
  return this.json;
73883
74336
  }
74337
+ /**
74338
+ * The user-level `~/.kiro/settings/mcp.json` also holds settings rulesync
74339
+ * does not manage (such as the top-level `identityProvider` block for
74340
+ * organization sign-in, which Kiro reads only from this file), so it is never
74341
+ * deleted in global mode. The project file is rulesync-managed and may be.
74342
+ * The sweep has no in-place retraction, so a global `--delete` run without a
74343
+ * source leaves the generated `mcpServers` behind; an empty source
74344
+ * (`{ "mcpServers": {} }`) retracts them through the normal merge.
74345
+ * @see https://kiro.dev/docs/mcp/configuration/
74346
+ */
74347
+ isDeletable() {
74348
+ return !this.global;
74349
+ }
73884
74350
  static getSettablePaths() {
73885
74351
  return {
73886
74352
  relativeDirPath: KIRO_SETTINGS_DIR_PATH,
73887
74353
  relativeFilePath: KIRO_MCP_FILE_NAME
73888
74354
  };
73889
74355
  }
73890
- static async fromFile({ outputRoot = process.cwd(), validate = true }) {
74356
+ static async fromFile({ outputRoot = process.cwd(), validate = true, global = false }) {
73891
74357
  const paths = this.getSettablePaths();
73892
74358
  const fileContent = await readFileContentOrNull((0, node_path.join)(outputRoot, paths.relativeDirPath, paths.relativeFilePath)) ?? "{\"mcpServers\":{}}";
73893
74359
  return new KiroMcp({
@@ -73895,18 +74361,34 @@ var KiroMcp = class KiroMcp extends ToolMcp {
73895
74361
  relativeDirPath: paths.relativeDirPath,
73896
74362
  relativeFilePath: paths.relativeFilePath,
73897
74363
  fileContent,
73898
- validate
74364
+ validate,
74365
+ global
73899
74366
  });
73900
74367
  }
73901
- static fromRulesyncMcp({ outputRoot = process.cwd(), rulesyncMcp, validate = true }) {
74368
+ /**
74369
+ * In global mode the generated `mcpServers` are merged into the existing
74370
+ * user-level file, keeping every other top-level key (for example
74371
+ * `identityProvider`). The project file is written from scratch.
74372
+ */
74373
+ static async fromRulesyncMcp({ outputRoot = process.cwd(), rulesyncMcp, validate = true, global = false }) {
73902
74374
  const paths = this.getSettablePaths();
73903
- const fileContent = JSON.stringify({ mcpServers: toKiroMcpServers(rulesyncMcp.getMcpServers()) }, null, 2);
74375
+ const mcpServers = toKiroMcpServers(rulesyncMcp.getMcpServers());
74376
+ let existing = {};
74377
+ if (global) {
74378
+ const configPath = (0, node_path.join)(outputRoot, paths.relativeDirPath, paths.relativeFilePath);
74379
+ const existingContent = await readFileContentOrNull(configPath);
74380
+ if (existingContent !== null) existing = parseExistingKiroMcpConfig(existingContent, configPath);
74381
+ }
73904
74382
  return new KiroMcp({
73905
74383
  outputRoot,
73906
74384
  relativeDirPath: paths.relativeDirPath,
73907
74385
  relativeFilePath: paths.relativeFilePath,
73908
- fileContent,
73909
- validate
74386
+ fileContent: JSON.stringify({
74387
+ ...existing,
74388
+ mcpServers
74389
+ }, null, 2),
74390
+ validate,
74391
+ global
73910
74392
  });
73911
74393
  }
73912
74394
  toRulesyncMcp() {
@@ -73914,13 +74396,14 @@ var KiroMcp = class KiroMcp extends ToolMcp {
73914
74396
  const translated = isMcpServers(mcpServers) ? fromKiroMcpServers(mcpServers) : {};
73915
74397
  return this.toRulesyncMcpDefault({ fileContent: JSON.stringify({ mcpServers: translated }, null, 2) });
73916
74398
  }
73917
- static forDeletion({ outputRoot = process.cwd(), relativeDirPath, relativeFilePath }) {
74399
+ static forDeletion({ outputRoot = process.cwd(), relativeDirPath, relativeFilePath, global = false }) {
73918
74400
  return new KiroMcp({
73919
74401
  outputRoot,
73920
74402
  relativeDirPath,
73921
74403
  relativeFilePath,
73922
74404
  fileContent: "{}",
73923
- validate: false
74405
+ validate: false,
74406
+ global
73924
74407
  });
73925
74408
  }
73926
74409
  };
@@ -84370,6 +84853,29 @@ const CLAUDECODE_WIDENING_DEFAULT_MODES = {
84370
84853
  */
84371
84854
  const CLAUDECODE_PROJECT_SCOPE_IGNORED_DEFAULT_MODES = /* @__PURE__ */ new Set(["auto", "bypassPermissions"]);
84372
84855
  /**
84856
+ * The `permissions` fields Claude Code reads only from user or managed settings
84857
+ * (and `--settings`), never from a repository's `.claude/settings.json`, so
84858
+ * they are dropped at project scope and written only under `--global`.
84859
+ * `denyInsteadOfPrompting` (v2.1.319+) only restricts, but committing it to a
84860
+ * project file would promise unattended denials that never happen.
84861
+ *
84862
+ * @see https://code.claude.com/docs/en/settings-reference#permissions-denyinsteadofprompting
84863
+ */
84864
+ const CLAUDECODE_USER_SCOPE_ONLY_PERMISSIONS_FIELDS = /* @__PURE__ */ new Set(["denyInsteadOfPrompting"]);
84865
+ /**
84866
+ * Drop the project-scope `permissions` fields in
84867
+ * {@link CLAUDECODE_USER_SCOPE_ONLY_PERMISSIONS_FIELDS}, warning once per field
84868
+ * in the same voice as the user-scope-only top-level keys.
84869
+ */
84870
+ function stripUserScopeOnlyPermissionsFields({ fields, global, relativeFilePath, logger }) {
84871
+ if (global) return;
84872
+ for (const key of CLAUDECODE_USER_SCOPE_ONLY_PERMISSIONS_FIELDS) {
84873
+ if (!Object.hasOwn(fields, key)) continue;
84874
+ logger?.warn(`Claude Code permissions: 'permissions.${key}' is not honored in the project-scoped ${relativeFilePath}, so it is not written there — Claude Code reads it from user or managed settings only. Author it in the global scope instead, and remove any value an earlier generate may have left in ${relativeFilePath}.`);
84875
+ delete fields[key];
84876
+ }
84877
+ }
84878
+ /**
84373
84879
  * Drop a project-scope `permissions.defaultMode` Claude Code ignores there (see
84374
84880
  * {@link CLAUDECODE_PROJECT_SCOPE_IGNORED_DEFAULT_MODES}), warning in the same
84375
84881
  * voice as the other values the project-scoped file cannot honor.
@@ -84463,7 +84969,7 @@ const CLAUDECODE_TRUST_AFFECTING_SANDBOX_PATHS = [
84463
84969
  },
84464
84970
  {
84465
84971
  path: ["enabled"],
84466
- reason: "turns the sandbox on, and sandboxed Bash commands then run without a permission prompt unless `autoAllowBashIfSandboxed` is false",
84972
+ reason: "turns the sandbox on, and sandboxed Bash commands then run without a permission prompt wherever `autoAllowBashIfSandboxed` is true (it defaults to false since Claude Code v2.1.324)",
84467
84973
  widens: isNotFalse
84468
84974
  },
84469
84975
  {
@@ -84766,6 +85272,7 @@ const CLAUDECODE_UNHONORED_KEY_SOURCES = {
84766
85272
  disableCommandPluginSources: "managed settings",
84767
85273
  disableDesktopLocalSessions: "managed settings",
84768
85274
  disableMobileSimulatorTools: "managed settings",
85275
+ disableRemotePreviewScripts: "managed settings",
84769
85276
  disableSideloadFlags: "managed settings",
84770
85277
  externalEditorContext: "~/.claude.json",
84771
85278
  forceRemoteSettingsRefresh: "managed settings",
@@ -85259,6 +85766,12 @@ var ClaudecodePermissions = class ClaudecodePermissions extends ToolPermissions
85259
85766
  relativeFilePath: paths.relativeFilePath,
85260
85767
  logger
85261
85768
  });
85769
+ stripUserScopeOnlyPermissionsFields({
85770
+ fields: nonListFields,
85771
+ global,
85772
+ relativeFilePath: paths.relativeFilePath,
85773
+ logger
85774
+ });
85262
85775
  trustAffecting.push(...collectWideningPermissionFields({ fields: nonListFields }));
85263
85776
  settings.permissions = {
85264
85777
  ...settings.permissions,
@@ -87236,6 +87749,7 @@ const CODEX_DEFAULT_APPROVAL_POLICY = "on-request";
87236
87749
  const CODEX_DEFAULT_APPROVALS_REVIEWER = "auto_review";
87237
87750
  const CODEX_RETIRED_APPROVAL_POLICY = "untrusted";
87238
87751
  const CODEX_DEPRECATED_APPROVAL_POLICY = "on-failure";
87752
+ const CODEX_REMOVED_AUTO_REVIEW_KEYS = ["extra_policy", "experimental_policy_template"];
87239
87753
  const CODEX_GLOB_SCAN_MAX_DEPTH = 8;
87240
87754
  const CODEX_MINIMAL_KEY = ":minimal";
87241
87755
  const CODEX_GIT_WRITE_RULES = { ".git/**": "write" };
@@ -87837,6 +88351,10 @@ function computeCodexcliOverridePatch({ existing, override, logger }) {
87837
88351
  value,
87838
88352
  logger
87839
88353
  })) continue;
88354
+ if (key === "auto_review" && isRecord(value)) warnAboutRemovedAutoReviewKeys({
88355
+ value,
88356
+ logger
88357
+ });
87840
88358
  if (key === "sandbox_mode" || key === "sandbox_workspace_write") logger?.warn(`Codex CLI permission override key "${key}" is deprecated. Codex prioritizes the legacy sandbox settings over permission profiles when both are present, so it disables the generated "${RULESYNC_PROFILE_NAME}" permissions profile. Use "base_permission_profile" and the shared "permission" block instead.`);
87841
88359
  const existingValue = existing[key];
87842
88360
  patch[key] = isRecord(existingValue) && isRecord(value) ? {
@@ -87876,6 +88394,12 @@ function isWritableApprovalPolicy({ value, logger }) {
87876
88394
  if (value === CODEX_DEPRECATED_APPROVAL_POLICY) logger?.warn(`Codex CLI permission override "approval_policy": "${CODEX_DEPRECATED_APPROVAL_POLICY}" is deprecated; Codex reads it as "${CODEX_DEFAULT_APPROVAL_POLICY}". Use "${CODEX_DEFAULT_APPROVAL_POLICY}" instead.`);
87877
88395
  return true;
87878
88396
  }
88397
+ function warnAboutRemovedAutoReviewKeys({ value, logger }) {
88398
+ for (const key of CODEX_REMOVED_AUTO_REVIEW_KEYS) {
88399
+ if (!Object.hasOwn(value, key)) continue;
88400
+ logger?.warn(`Codex CLI permission override "auto_review.${key}" was removed in Codex 0.169.0: newer Codex ignores it and warns at startup (it is rejected only under --strict-config). It is still written for older Codex. Move the text to "auto_review.policy", or to guardian_extra_policy in a managed requirements.toml.`);
88401
+ }
88402
+ }
87879
88403
  function extractCodexcliOverride(table) {
87880
88404
  const override = {};
87881
88405
  for (const key of CODEXCLI_OVERRIDE_KEYS) if (table[key] !== void 0) override[key] = table[key];
@@ -89250,6 +89774,17 @@ const AUTO_APPROVE_KEYS = {
89250
89774
  webfetch: "chat.tools.urls.autoApprove"
89251
89775
  };
89252
89776
  /**
89777
+ * VS Code registers `chat.tools.edits.autoApprove` with
89778
+ * `ConfigurationScope.APPLICATION` (user settings only) and ignores the value
89779
+ * in a workspace `.vscode/settings.json`, so canonical `edit` rules written
89780
+ * there have no effect. The terminal and URL maps are honored in the workspace
89781
+ * only by the Local harness, which VS Code removes in February 2027.
89782
+ *
89783
+ * @see https://github.com/microsoft/vscode/blob/1.147.0/src/vs/workbench/contrib/chat/browser/chat.shared.contribution.ts
89784
+ * @see https://code.visualstudio.com/docs/agents/run/approvals
89785
+ */
89786
+ const EDITS_KEY_IGNORED_WARNING = "GitHub Copilot: canonical `edit` rules are written to `chat.tools.edits.autoApprove` in .vscode/settings.json, but VS Code reads that setting from user settings only and ignores it in the workspace. Set edit approvals in your VS Code user settings instead.";
89787
+ /**
89253
89788
  * The workspace setting holding the starting permission level of new Local
89254
89789
  * (`local` harness) chat sessions, authored through the
89255
89790
  * `copilot.defaultPermissionMode` override. VS Code 1.144 narrowed it to Local
@@ -89407,6 +89942,10 @@ const SANDBOX_LEAVES = [
89407
89942
  path: ["credentials", "authenticategh"],
89408
89943
  schema: zod_mini.z.boolean()
89409
89944
  },
89945
+ {
89946
+ path: ["credentials", "envVars"],
89947
+ schema: CopilotSandboxCredentialEnvVarsSchema
89948
+ },
89410
89949
  {
89411
89950
  path: ["fileSystem", "allowDevToolAccess"],
89412
89951
  schema: zod_mini.z.boolean()
@@ -89466,6 +90005,11 @@ const COPILOT_TRUST_AFFECTING_SANDBOX_PATHS = [
89466
90005
  reason: "hands your GitHub CLI authentication to sandboxed commands",
89467
90006
  widens: isNotFalse
89468
90007
  },
90008
+ {
90009
+ path: ["credentials", "envVars"],
90010
+ reason: "lets the sandbox send the named environment variables' values to the listed hosts",
90011
+ widens: isNonEmptyMap
90012
+ },
89469
90013
  {
89470
90014
  path: ["fileSystem", "allowDevToolAccess"],
89471
90015
  reason: "grants sandboxed commands developer-tool directories, which can hold credentials such as registry tokens",
@@ -89491,6 +90035,27 @@ const COPILOT_TRUST_AFFECTING_SANDBOX_PATHS = [
89491
90035
  }
89492
90036
  ];
89493
90037
  const COPILOT_TOOL_LABEL = "GitHub Copilot";
90038
+ /** The trust-warning label of the `credentials.envVars` leaf. */
90039
+ const ENV_VARS_LABEL = "sandbox.credentials.envVars";
90040
+ /**
90041
+ * Every `VAR -> host, host` pair of a `credentials.envVars` map, so a
90042
+ * developer generating from a cloned repository can spot an unexpected host
90043
+ * without opening the file. Names and hosts are JSON-quoted so control
90044
+ * characters in authored values cannot forge log lines.
90045
+ */
90046
+ function describeEnvVars(envVars) {
90047
+ return Object.entries(envVars).map(([name, { injectHosts }]) => `${JSON.stringify(name)} -> ${injectHosts.length > 0 ? injectHosts.map((host) => JSON.stringify(host)).join(", ") : "(no hosts)"}`).join("; ");
90048
+ }
90049
+ /**
90050
+ * A separate, stronger warning for `injectHosts` entries containing `*`: the
90051
+ * sandbox may then send the credential to any host the pattern matches.
90052
+ */
90053
+ function warnOnWildcardInjectHosts({ envVars, relativeFilePath, logger }) {
90054
+ if (envVars === void 0) return;
90055
+ const wildcards = Object.entries(envVars).flatMap(([name, { injectHosts }]) => injectHosts.filter((host) => host.includes("*")).map((host) => `${JSON.stringify(name)} -> ${JSON.stringify(host)}`));
90056
+ if (wildcards.length === 0) return;
90057
+ logger?.warn(`${COPILOT_TOOL_LABEL}: '${ENV_VARS_LABEL}' in ${relativeFilePath} lets the sandbox send credentials to any host matching a wildcard: ${wildcards.join("; ")}. Review these patterns, since the credential can reach every matching host.`);
90058
+ }
89494
90059
  function sandboxKey(path) {
89495
90060
  return `${SANDBOX_KEY_PREFIX}${path.join(".")}`;
89496
90061
  }
@@ -89683,14 +90248,16 @@ var CopilotPermissions = class CopilotPermissions extends ToolPermissions {
89683
90248
  const patch = {};
89684
90249
  for (const [category, settingKey] of Object.entries(AUTO_APPROVE_KEYS)) {
89685
90250
  if (!Object.hasOwn(config.permission, category)) continue;
90251
+ const rules = category === "bash" ? bashRulesHonoringAllTools(config.permission) : honorCopilotAllToolsRestrictions({
90252
+ permission: config.permission,
90253
+ category,
90254
+ logger
90255
+ });
89686
90256
  patch[settingKey] = buildAutoApproveValue({
89687
90257
  category,
89688
- rules: category === "bash" ? bashRulesHonoringAllTools(config.permission) : honorCopilotAllToolsRestrictions({
89689
- permission: config.permission,
89690
- category,
89691
- logger
89692
- })
90258
+ rules
89693
90259
  });
90260
+ if (category === "edit" && Object.keys(rules).length > 0) logger?.warn(EDITS_KEY_IGNORED_WARNING);
89694
90261
  }
89695
90262
  const existingSettings = () => parseSharedConfig({
89696
90263
  format: "jsonc",
@@ -89711,13 +90278,23 @@ var CopilotPermissions = class CopilotPermissions extends ToolPermissions {
89711
90278
  sandbox,
89712
90279
  existingSettings: existingSettings()
89713
90280
  }));
90281
+ const relativeFilePath = (0, node_path.join)(paths.relativeDirPath, paths.relativeFilePath);
90282
+ const envVars = sandbox.credentials?.envVars;
89714
90283
  warnOnTrustAffectingEntries({
89715
90284
  toolLabel: COPILOT_TOOL_LABEL,
89716
90285
  entries: collectTrustAffectingSandboxPaths({
89717
90286
  sandbox,
89718
90287
  paths: COPILOT_TRUST_AFFECTING_SANDBOX_PATHS
89719
- }),
89720
- relativeFilePath: (0, node_path.join)(paths.relativeDirPath, paths.relativeFilePath),
90288
+ }).map((entry) => entry.label === ENV_VARS_LABEL && envVars !== void 0 ? {
90289
+ ...entry,
90290
+ reason: `${entry.reason}: ${describeEnvVars(envVars)}`
90291
+ } : entry),
90292
+ relativeFilePath,
90293
+ logger
90294
+ });
90295
+ warnOnWildcardInjectHosts({
90296
+ envVars,
90297
+ relativeFilePath,
89721
90298
  logger
89722
90299
  });
89723
90300
  }
@@ -92605,7 +93182,7 @@ function convertGoosePermissionConfigToRulesync(userPermission) {
92605
93182
  const GROKCLI_UI_KEY = "ui";
92606
93183
  const GROKCLI_PERMISSION_MODE_KEY = "permission_mode";
92607
93184
  const GROKCLI_PERMISSION_KEY = "permission";
92608
- const GROKCLI_AUTO_PERMISSION_MODE = "auto";
93185
+ const GROKCLI_DERIVED_PERMISSION_MODES = /* @__PURE__ */ new Set(["ask", "always-approve"]);
92609
93186
  const CATEGORY_TO_GROK_TOOL = {
92610
93187
  bash: "Bash",
92611
93188
  read: "Read",
@@ -92832,12 +93409,15 @@ function parseGrokRule(rule) {
92832
93409
  * compact arrays, so a user-authored `rules` array is preserved verbatim
92833
93410
  * but not reconciled against them.
92834
93411
  *
92835
- * The coarse `[ui] permission_mode` toggle is still written for backward
92836
- * compatibility with older Grok versions: `always-approve` when the config is
92837
- * pure-`allow`, otherwise `ask` (conservative — it is never `always-approve`
93412
+ * The coarse `[ui] permission_mode` toggle is kept in sync for backward
93413
+ * compatibility with older Grok versions, but only when the config already
93414
+ * sets it to `ask` or `always-approve`: `always-approve` only when the config
93415
+ * has the all-tools catch-all allow (`"*": { "*": "allow" }`) and no
93416
+ * `deny`/`ask` rule, otherwise `ask` (conservative — it is never `always-approve`
92838
93417
  * while any `deny`/`ask` rule exists, so it never contradicts the fine-grained
92839
- * arrays). It is a user-level UI setting, so it is only written in global scope
92840
- * (see below).
93418
+ * arrays). A missing key is not added, so Grok's own default mode applies. It
93419
+ * is a user-level UI setting, so it is only touched in global scope (see
93420
+ * below).
92841
93421
  *
92842
93422
  * Both scopes are supported: the adapter syncs the project-level
92843
93423
  * `./.grok/config.toml` (default) and the user-level `~/.grok/config.toml`
@@ -92898,7 +93478,7 @@ var GrokcliPermissions = class GrokcliPermissions extends ToolPermissions {
92898
93478
  ask: buckets.ask
92899
93479
  };
92900
93480
  const existingUi = toRecord(parsed[GROKCLI_UI_KEY]);
92901
- const uiPatch = global && existingUi[GROKCLI_PERMISSION_MODE_KEY] !== GROKCLI_AUTO_PERMISSION_MODE ? { [GROKCLI_UI_KEY]: {
93481
+ const uiPatch = global && GROKCLI_DERIVED_PERMISSION_MODES.has(existingUi[GROKCLI_PERMISSION_MODE_KEY]) ? { [GROKCLI_UI_KEY]: {
92902
93482
  ...existingUi,
92903
93483
  [GROKCLI_PERMISSION_MODE_KEY]: deriveGrokPermissionMode(config)
92904
93484
  } } : {};
@@ -93079,22 +93659,30 @@ function parseGrokPermissionArrays(permission) {
93079
93659
  /**
93080
93660
  * Legacy coarse fallback: map `[ui] permission_mode` to a canonical action.
93081
93661
  * `always-approve` ⇒ `allow`; anything else (including a missing mode) ⇒ `ask`.
93662
+ * A missing mode now means Grok's own default (`auto` in the TUI since 1.0.80),
93663
+ * which has no canonical counterpart, so the narrower `ask` reading is kept.
93082
93664
  */
93083
93665
  function legacyModeAction(parsed) {
93084
93666
  return toRecord(parsed[GROKCLI_UI_KEY])[GROKCLI_PERMISSION_MODE_KEY] === "always-approve" ? "allow" : "ask";
93085
93667
  }
93086
93668
  /**
93087
93669
  * Collapse a rulesync permissions config into Grok's single coarse mode.
93088
- * Any `deny`/`ask` rule anywhere keeps prompting (`ask`); otherwise an existing
93089
- * `allow` rule opts into `always-approve`; an empty config defaults to `ask`.
93670
+ * `always-approve` lets every tool run without a prompt, so it is derived only
93671
+ * from a true catch-all allow — the all-tools rule `"*": { "*": "allow" }` —
93672
+ * with no `deny`/`ask` rule anywhere. Narrow allows (e.g. `bash: { "git *":
93673
+ * "allow" }`, or even `bash: { "*": "allow" }`) never widen into it; they and
93674
+ * an empty config map to `ask`.
93090
93675
  */
93091
93676
  function deriveGrokPermissionMode(config) {
93092
- let hasAllow = false;
93093
- for (const rules of Object.values(config.permission)) for (const action of Object.values(rules)) {
93094
- if (action === "deny" || action === "ask") return "ask";
93095
- if (action === "allow") hasAllow = true;
93096
- }
93097
- return hasAllow ? "always-approve" : "ask";
93677
+ for (const rules of Object.values(config.permission)) for (const action of Object.values(rules)) if (action === "deny" || action === "ask") return "ask";
93678
+ const allTools = lookupOwn({
93679
+ record: config.permission,
93680
+ key: "*"
93681
+ });
93682
+ return allTools !== void 0 && lookupOwn({
93683
+ record: allTools,
93684
+ key: "*"
93685
+ }) === "allow" ? "always-approve" : "ask";
93098
93686
  }
93099
93687
  // src/features/permissions/hermesagent-permissions.ts
93100
93688
  /** Collect the glob patterns in a canonical category that carry a given action. */
@@ -94397,13 +94985,71 @@ function canonicalToKimiCodeRules({ config, logger }) {
94397
94985
  });
94398
94986
  }
94399
94987
  }
94400
- return [...overrideRules, ...sortKimiCodeRulesFailClosed(canonicalRules)];
94988
+ const rules = [...overrideRules, ...sortKimiCodeRulesFailClosed(canonicalRules)];
94989
+ warnAboutIgnoredKimiCodeRuleScopes({
94990
+ rules: overrideRules,
94991
+ logger
94992
+ });
94993
+ warnAboutShadowedKimiCodeRules({
94994
+ rules,
94995
+ logger
94996
+ });
94997
+ return rules;
94401
94998
  }
94402
- function getKimiCodePatternSpecificity(pattern) {
94999
+ /**
95000
+ * Scopes Kimi silently ignores on a rule in the user `config.toml`.
95001
+ *
95002
+ * @see https://moonshotai.github.io/kimi-code/en/configuration/config-files.html#permission
95003
+ */
95004
+ const KIMI_CODE_IGNORED_USER_RULE_SCOPES = /* @__PURE__ */ new Set(["turn-override", "session-runtime"]);
95005
+ function warnAboutIgnoredKimiCodeRuleScopes({ rules, logger }) {
95006
+ for (const rule of rules) if (rule.scope !== void 0 && KIMI_CODE_IGNORED_USER_RULE_SCOPES.has(rule.scope)) logger?.warn(`Kimi Code permissions: the ${rule.decision} rule for "${rule.pattern}" has scope "${rule.scope}", which Kimi ignores in ${KIMI_CODE_CONFIG_SHARED_FILE_KEY}. Use "user" or "project" for it to take effect.`);
95007
+ }
95008
+ /** Split a Kimi rule pattern (`Tool` or `Tool(arg)`) into its tool and argument. */
95009
+ function splitKimiCodePattern(pattern) {
94403
95010
  const opening = pattern.indexOf("(");
94404
95011
  const hasArguments = opening >= 0 && pattern.endsWith(")");
94405
- const tool = hasArguments ? pattern.slice(0, opening) : pattern;
94406
- const argument = hasArguments ? pattern.slice(opening + 1, -1) : "";
95012
+ return {
95013
+ tool: hasArguments ? pattern.slice(0, opening) : pattern,
95014
+ argument: hasArguments ? pattern.slice(opening + 1, -1) : "",
95015
+ hasArguments
95016
+ };
95017
+ }
95018
+ /**
95019
+ * Whether `stricter` certainly matches every call `rule` matches: the same
95020
+ * pattern, or the bare name of the same tool (which matches every call of
95021
+ * it). Wildcard overlaps are not detected, so this never reports a false
95022
+ * shadow but can miss one.
95023
+ */
95024
+ function kimiCodeRuleCovers({ stricter, rule }) {
95025
+ return stricter.pattern === rule.pattern || stricter.pattern === splitKimiCodePattern(rule.pattern).tool;
95026
+ }
95027
+ /**
95028
+ * Kimi does not let the first matching rule win: a matching `deny` beats a
95029
+ * matching `ask`, which beats a matching `allow` (Kimi Code 2.6.0 docs). An
95030
+ * `allow` or `ask` meant to carve an exception out of a broader, stricter
95031
+ * rule therefore never takes effect, whether it comes from `kimi-code.rules`
95032
+ * or from a canonical category, so say so instead of letting the authored
95033
+ * order suggest otherwise. A rule whose own scope Kimi ignores already got
95034
+ * its warning and is skipped here.
95035
+ *
95036
+ * @see https://moonshotai.github.io/kimi-code/en/configuration/config-files.html#permission
95037
+ */
95038
+ function warnAboutShadowedKimiCodeRules({ rules, logger }) {
95039
+ for (const rule of rules) {
95040
+ if (rule.decision === "deny" || KIMI_CODE_IGNORED_USER_RULE_SCOPES.has(rule.scope ?? "")) continue;
95041
+ const shadowing = rules.find((other) => isStricterAction({
95042
+ action: other.decision,
95043
+ existing: rule.decision
95044
+ }) && !KIMI_CODE_IGNORED_USER_RULE_SCOPES.has(other.scope ?? "") && kimiCodeRuleCovers({
95045
+ stricter: other,
95046
+ rule
95047
+ }));
95048
+ if (shadowing) logger?.warn(`Kimi Code permissions: the ${rule.decision} rule for "${rule.pattern}" never takes effect: the matching ${shadowing.decision} rule "${shadowing.pattern}" outranks it, because Kimi ranks matching rules deny > ask > allow regardless of their order.`);
95049
+ }
95050
+ }
95051
+ function getKimiCodePatternSpecificity(pattern) {
95052
+ const { tool, argument, hasArguments } = splitKimiCodePattern(pattern);
94407
95053
  return {
94408
95054
  tool,
94409
95055
  toolLiteralLength: tool.replaceAll("*", "").replaceAll("?", "").length,
@@ -100469,6 +101115,14 @@ const TAKT_SECURITY_POLICIES = {
100469
101115
  const TAKT_SECURITY_POLICY_KEYS = Object.keys(TAKT_SECURITY_POLICIES);
100470
101116
  const TAKT_DEFAULT_PROVIDER = "claude-sdk";
100471
101117
  const TAKT_LEGACY_DEFAULT_PROVIDER = "claude";
101118
+ const TAKT_CLAUDE_READ_DENY_PROVIDERS = [
101119
+ "claude-sdk",
101120
+ "claude",
101121
+ "claude-headless"
101122
+ ];
101123
+ const TAKT_CLAUDE_PROVIDER_OPTIONS_KEY = "claude";
101124
+ const TAKT_CLAUDE_PERMISSIONS_KEY = "permissions";
101125
+ const TAKT_CLAUDE_PERMISSIONS_DENY_KEY = "deny";
100472
101126
  /**
100473
101127
  * Permissions adapter for Takt (`.takt/config.yaml`).
100474
101128
  *
@@ -100507,6 +101161,12 @@ const TAKT_LEGACY_DEFAULT_PROVIDER = "claude";
100507
101161
  * (a top-level per-provider sandbox/network table). Both are authored on
100508
101162
  * generate and re-extracted on import.
100509
101163
  *
101164
+ * Canonical `read` deny rules are also kept per path where the active provider
101165
+ * is Claude-family (Takt 0.76.0+): they are written as `Read(<pattern>)`
101166
+ * entries into `provider_options.claude.permissions.deny`, in addition to the
101167
+ * `readonly` mode they already derive. The list is only ever added to, so a
101168
+ * deny never turns into a broader allow.
101169
+ *
100510
101170
  * Takt 0.56.0 moved provider configuration into a separate `runtime.yaml`
100511
101171
  * (`.takt/runtime.yaml`, `~/.takt/runtime.yaml`). Once its `provider:` section
100512
101172
  * carries an assignment ("runtime mode" — the state a freshly installed Takt is
@@ -100571,7 +101231,8 @@ var TaktPermissions = class TaktPermissions extends ToolPermissions {
100571
101231
  outputRoot,
100572
101232
  logger
100573
101233
  });
100574
- const inheritedProvider = global ? void 0 : await readGlobalTaktProvider({
101234
+ const globalLayer = await readGlobalTaktLayer({
101235
+ global,
100575
101236
  projectFilePath: filePath,
100576
101237
  logger
100577
101238
  });
@@ -100579,7 +101240,7 @@ var TaktPermissions = class TaktPermissions extends ToolPermissions {
100579
101240
  const provider = resolveActiveProvider({
100580
101241
  config,
100581
101242
  runtime: runtime.active ? runtime.config : void 0,
100582
- inheritedProvider
101243
+ inheritedProvider: globalLayer.provider
100583
101244
  });
100584
101245
  const mode = deriveTaktPermissionMode(rulesyncJson);
100585
101246
  const override = isPlainObject(rulesyncJson.takt) ? rulesyncJson.takt : void 0;
@@ -100587,9 +101248,20 @@ var TaktPermissions = class TaktPermissions extends ToolPermissions {
100587
101248
  const authoredProviderOptions = isPlainObject(override?.[TAKT_PROVIDER_OPTIONS_KEY]) ? override[TAKT_PROVIDER_OPTIONS_KEY] : void 0;
100588
101249
  const runtimeModeRefusesProviderOptions = authoredProviderOptions !== void 0 && runtime.active;
100589
101250
  if (runtimeModeRefusesProviderOptions) logger?.warn(`Takt permissions: not writing "${TAKT_PROVIDER_OPTIONS_KEY}" to ${filePath} because ${runtime.filePaths.join(" + ")} puts Takt in runtime provider mode (Takt 0.56.0+), where any legacy provider setting in config.yaml makes Takt fail with "Mixed provider configuration detected". Move those options to \`provider.profiles.<profile>.options\` in runtime.yaml, and remove them from the \`takt\` block of the rulesync source. A "${TAKT_PROVIDER_OPTIONS_KEY}" already in ${filePath} is left untouched — rulesync does not own that key.`);
100590
- const overrideProviderOptions = runtimeModeRefusesProviderOptions ? void 0 : dropUntrustedProviderOptions({
100591
- providerOptions: authoredProviderOptions,
100592
- global,
101251
+ const overrideProviderOptions = addClaudeReadDenyRules({
101252
+ providerOptions: runtimeModeRefusesProviderOptions ? void 0 : dropUntrustedProviderOptions({
101253
+ providerOptions: authoredProviderOptions,
101254
+ global,
101255
+ filePath,
101256
+ logger
101257
+ }),
101258
+ readDenyRules: collectReadDenyRules(rulesyncJson),
101259
+ existingProviderOptions: config[TAKT_PROVIDER_OPTIONS_KEY],
101260
+ globalProviderOptions: globalLayer.providerOptions,
101261
+ globalFilePath: globalLayer.filePath,
101262
+ provider,
101263
+ runtimeActive: runtime.active,
101264
+ runtimeFilePaths: runtime.filePaths,
100593
101265
  filePath,
100594
101266
  logger
100595
101267
  });
@@ -100702,11 +101374,34 @@ function readProviderName(config) {
100702
101374
  return typeof provider === "string" && provider.trim() !== "" ? provider : void 0;
100703
101375
  }
100704
101376
  /**
100705
- * The top-level `provider:` of the global `~/.takt/config.yaml`, read for a
100706
- * project-scope generate. An unresolvable home directory, a missing or
100707
- * unparsable file, or one that names no provider all mean "nothing inherited".
101377
+ * What a project-scope generate inherits from the global `~/.takt/config.yaml`:
101378
+ * its provider and its `provider_options`. Nothing at global scope, where that
101379
+ * file is the one being generated.
100708
101380
  */
100709
- async function readGlobalTaktProvider({ projectFilePath, logger }) {
101381
+ async function readGlobalTaktLayer({ global, projectFilePath, logger }) {
101382
+ const globalConfig = global ? void 0 : await readGlobalTaktConfig({
101383
+ projectFilePath,
101384
+ logger
101385
+ });
101386
+ if (globalConfig === void 0) return {
101387
+ provider: void 0,
101388
+ providerOptions: void 0,
101389
+ filePath: void 0
101390
+ };
101391
+ return {
101392
+ provider: readProviderName(globalConfig.config),
101393
+ providerOptions: globalConfig.config[TAKT_PROVIDER_OPTIONS_KEY],
101394
+ filePath: globalConfig.filePath
101395
+ };
101396
+ }
101397
+ /**
101398
+ * The global `~/.takt/config.yaml`, read for a project-scope generate: its
101399
+ * top-level `provider:` is inherited by a project config that names none, and
101400
+ * its `provider_options.claude.permissions.deny` is the list a project list
101401
+ * would replace. An unresolvable home directory or a missing or unparsable file
101402
+ * all mean "nothing inherited".
101403
+ */
101404
+ async function readGlobalTaktConfig({ projectFilePath, logger }) {
100710
101405
  let globalPath;
100711
101406
  try {
100712
101407
  globalPath = (0, node_path.join)(getHomeDirectory(), TAKT_DIR, TAKT_CONFIG_FILE_NAME);
@@ -100717,12 +101412,15 @@ async function readGlobalTaktProvider({ projectFilePath, logger }) {
100717
101412
  try {
100718
101413
  const content = await readFileContentOrNull(globalPath);
100719
101414
  if (content === null) return;
100720
- return readProviderName(parseSharedConfig({
100721
- format: "yaml",
100722
- fileContent: content,
101415
+ return {
100723
101416
  filePath: globalPath,
100724
- invalidRootPolicy: "error"
100725
- }));
101417
+ config: parseSharedConfig({
101418
+ format: "yaml",
101419
+ fileContent: content,
101420
+ filePath: globalPath,
101421
+ invalidRootPolicy: "error"
101422
+ })
101423
+ };
100726
101424
  } catch (error) {
100727
101425
  logger?.warn(`Takt permissions: could not read the provider from ${globalPath} (${formatError(error)}); falling back to the project config alone.`);
100728
101426
  return;
@@ -101085,6 +101783,70 @@ function taktModeToRulesyncConfig(mode) {
101085
101783
  default: return { permission: { bash: { ["*"]: "deny" } } };
101086
101784
  }
101087
101785
  }
101786
+ /**
101787
+ * The canonical `read` deny rules as Claude Code `Read(...)` entries, in the
101788
+ * form the Claude Code permissions and ignore adapters write them: the pattern
101789
+ * verbatim, and a bare `Read` for the catch-all.
101790
+ */
101791
+ function collectReadDenyRules(config) {
101792
+ const rules = config.permission.read ?? {};
101793
+ return Object.entries(rules).filter(([, action]) => action === "deny").map(([pattern]) => pattern === "*" ? "Read" : buildReadDenyEntry(pattern));
101794
+ }
101795
+ /**
101796
+ * Add the canonical `read` deny rules to `provider_options.claude.permissions.deny`
101797
+ * (Takt 0.76.0+), which Takt passes to `claude-sdk` / `claude-headless` as
101798
+ * Claude Code `permissions.deny` rules.
101799
+ *
101800
+ * Takt replaces a `deny` list wholesale rather than concatenating it, so the
101801
+ * rules are merged into the list that would otherwise be in force: the one the
101802
+ * `takt` block states (which replaces a hand-written config.yaml list, as any
101803
+ * authored `provider_options` leaf does), else the one already in config.yaml.
101804
+ * Without an authored list nothing is removed from config.yaml's — a rule
101805
+ * written by hand, or by an earlier generate, is kept.
101806
+ *
101807
+ * At project scope the written list also replaces a global `~/.takt/config.yaml`
101808
+ * deny list for this project. That list usually holds personal paths, so it is
101809
+ * not copied into the (committed) project file; a warning names it instead.
101810
+ *
101811
+ * Skipped when the active provider is not Claude-family (no other provider
101812
+ * reads the list) and, with a warning, in runtime mode, where `provider_options`
101813
+ * in config.yaml stops Takt with "Mixed provider configuration detected".
101814
+ * https://github.com/nrslib/takt/blob/main/docs/configuration.md#claude-read-deny-rules
101815
+ */
101816
+ function addClaudeReadDenyRules({ providerOptions, readDenyRules, existingProviderOptions, globalProviderOptions, globalFilePath, provider, runtimeActive, runtimeFilePaths, filePath, logger }) {
101817
+ if (readDenyRules.length === 0 || !TAKT_CLAUDE_READ_DENY_PROVIDERS.includes(provider)) return providerOptions;
101818
+ if (runtimeActive) {
101819
+ logger?.warn(`Takt permissions: not writing the read deny rules (${readDenyRules.join(", ")}) to "${TAKT_PROVIDER_OPTIONS_KEY}.${TAKT_CLAUDE_PROVIDER_OPTIONS_KEY}.${TAKT_CLAUDE_PERMISSIONS_KEY}.${TAKT_CLAUDE_PERMISSIONS_DENY_KEY}" in ${filePath} because ${runtimeFilePaths.join(" + ")} puts Takt in runtime provider mode. They still make the mode readonly; to have Claude enforce them per path, add them under \`${TAKT_CLAUDE_PERMISSIONS_KEY}.${TAKT_CLAUDE_PERMISSIONS_DENY_KEY}\` in the options of a Claude profile in runtime.yaml.`);
101820
+ return providerOptions;
101821
+ }
101822
+ const authoredClaude = providerOptions?.[TAKT_CLAUDE_PROVIDER_OPTIONS_KEY];
101823
+ const authoredDeny = readClaudeDenyList(authoredClaude);
101824
+ const existingDeny = isPlainObject(existingProviderOptions) ? readClaudeDenyList(existingProviderOptions[TAKT_CLAUDE_PROVIDER_OPTIONS_KEY]) : void 0;
101825
+ const deny = [.../* @__PURE__ */ new Set([...authoredDeny ?? existingDeny ?? [], ...readDenyRules])];
101826
+ const shadowedGlobalDeny = ((isPlainObject(globalProviderOptions) ? readClaudeDenyList(globalProviderOptions[TAKT_CLAUDE_PROVIDER_OPTIONS_KEY]) : void 0) ?? []).filter((rule) => !deny.includes(rule));
101827
+ if (shadowedGlobalDeny.length > 0) logger?.warn(`Takt permissions: the read deny rules written to "${TAKT_PROVIDER_OPTIONS_KEY}.${TAKT_CLAUDE_PROVIDER_OPTIONS_KEY}.${TAKT_CLAUDE_PERMISSIONS_KEY}.${TAKT_CLAUDE_PERMISSIONS_DENY_KEY}" in ${filePath} replace the list in ${globalFilePath ?? "the global config.yaml"} for this project, because Takt does not concatenate deny lists across layers. Claude will no longer apply ${shadowedGlobalDeny.join(", ")} here unless you add them to the project list (the \`takt.provider_options.claude.permissions.deny\` block of the rulesync source) or to the canonical \`read\` rules.`);
101828
+ const claude = isPlainObject(authoredClaude) ? authoredClaude : {};
101829
+ const permissions = isPlainObject(claude[TAKT_CLAUDE_PERMISSIONS_KEY]) ? claude[TAKT_CLAUDE_PERMISSIONS_KEY] : {};
101830
+ return {
101831
+ ...providerOptions,
101832
+ [TAKT_CLAUDE_PROVIDER_OPTIONS_KEY]: {
101833
+ ...claude,
101834
+ [TAKT_CLAUDE_PERMISSIONS_KEY]: {
101835
+ ...permissions,
101836
+ [TAKT_CLAUDE_PERMISSIONS_DENY_KEY]: deny
101837
+ }
101838
+ }
101839
+ };
101840
+ }
101841
+ /** The string entries of `<claude options>.permissions.deny`, when it is a list. */
101842
+ function readClaudeDenyList(claudeOptions) {
101843
+ if (!isPlainObject(claudeOptions)) return;
101844
+ const permissions = claudeOptions[TAKT_CLAUDE_PERMISSIONS_KEY];
101845
+ if (!isPlainObject(permissions)) return;
101846
+ const deny = permissions[TAKT_CLAUDE_PERMISSIONS_DENY_KEY];
101847
+ if (!Array.isArray(deny)) return;
101848
+ return deny.filter((entry) => typeof entry === "string" && entry !== "");
101849
+ }
101088
101850
  const TAKT_BASE_URL_PROVIDERS = [
101089
101851
  "codex",
101090
101852
  "claude",
@@ -104109,6 +104871,32 @@ function buildZedToolPermissions({ permission, logger }) {
104109
104871
  inertMcpCategories
104110
104872
  };
104111
104873
  }
104874
+ /**
104875
+ * Zed's file-edit tools whose `confirm` default does not prompt for files inside
104876
+ * the project.
104877
+ */
104878
+ const ZED_IN_PROJECT_EDIT_TOOLS = ["edit_file", "write_file"];
104879
+ /**
104880
+ * Zed's `edit_file` and `write_file` skip the permission prompt for files inside
104881
+ * the project when the settings decision is `confirm`: only Zed settings
104882
+ * folders, `.agents/skills/` and paths a symlink places outside the project
104883
+ * still prompt (`authorize_file_edit` in `crates/agent/src/tools/tool_permissions.rs`,
104884
+ * documented under "File Edits Inside the Project" since zed-industries/zed#67037).
104885
+ * A canonical catch-all `ask` on `edit`/`write` — or an all-tools `*` ask those
104886
+ * tools fall back to — therefore lets the agent edit in-project files without
104887
+ * asking, so say so at generate time rather than implying a prompt.
104888
+ *
104889
+ * The check runs on the merged `tools` result: a tool whose entry is a
104890
+ * preserved, hand-written one (not managed by rulesync) is skipped, since its
104891
+ * decision is the user's own. Only the literal `.*` ask pattern counts as
104892
+ * "prompt for every file" and silences the warning; any narrower pattern still
104893
+ * leaves other in-project files unprompted, so the warning stays.
104894
+ */
104895
+ function warnInProjectEditConfirm({ managedDefault, managedTools, preservedToolNames, logger }) {
104896
+ const confirmTools = ZED_IN_PROJECT_EDIT_TOOLS.filter((tool) => !preservedToolNames.has(tool) && (managedTools[tool]?.default ?? managedDefault) === "confirm" && !managedTools[tool]?.always_confirm?.some((entry) => entry.pattern === ".*"));
104897
+ if (confirmTools.length === 0) return;
104898
+ logger?.warn(`Zed permissions: the catch-all "ask" for ${confirmTools.map((tool) => `"${tool}"`).join(" and ")} becomes Zed's "confirm" default, which does not prompt for edits to files inside the project (only Zed settings folders, ".agents/skills/" and files outside the project still prompt). To be asked before in-project edits, add the "ask" pattern ".*" to the category (only that exact pattern silences this warning; an "always_confirm" match outranks "always_allow" patterns). Zed honors such patterns for in-project files from v1.30 on. Canonical patterns are shared by every target: in glob-matching targets (such as Claude Code's "Edit(.*)") ".*" matches dotfiles only, so there it adds an extra "ask" for those files and loosens nothing.`);
104899
+ }
104112
104900
  function asRecord(value) {
104113
104901
  if (value === null || typeof value !== "object" || Array.isArray(value)) return {};
104114
104902
  return Object.fromEntries(Object.entries(value));
@@ -104254,6 +105042,12 @@ var ZedPermissions = class ZedPermissions extends ToolPermissions {
104254
105042
  if ("*" in config.permission) managedToolNames.add("*");
104255
105043
  for (const toolName of Object.keys(existingTools)) if (toolName.startsWith("mcp__")) managedToolNames.add(toolName);
104256
105044
  const preservedTools = Object.fromEntries(Object.entries(existingTools).filter(([toolName]) => !managedToolNames.has(toolName)));
105045
+ warnInProjectEditConfirm({
105046
+ managedDefault,
105047
+ managedTools,
105048
+ preservedToolNames: new Set(Object.keys(preservedTools)),
105049
+ logger
105050
+ });
104257
105051
  return new ZedPermissions({
104258
105052
  outputRoot,
104259
105053
  relativeDirPath: paths.relativeDirPath,
@@ -105297,6 +106091,11 @@ async function ensureAntigravityPluginManifests({ outputRoots, dryRun, logger })
105297
106091
  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)}.`);
105298
106092
  noteName(name, filePath);
105299
106093
  const content = addTrailingNewline(JSON.stringify({ name }, null, 2));
106094
+ await warnIfWriteFollowsLink({
106095
+ logger,
106096
+ rootPath: outputRoot,
106097
+ targetPath: filePath
106098
+ });
105300
106099
  if (dryRun) logger.info(`[DRY RUN] Would write: ${stripControlCharacters(filePath)}`);
105301
106100
  else await writeFileContent(filePath, content);
105302
106101
  paths.push(ANTIGRAVITY_PLUGIN_MANIFEST_FILE_NAME);
@@ -105345,7 +106144,7 @@ function mergeEnabledPlugins({ existingContent, filePath, pluginNames }) {
105345
106144
  }
105346
106145
  });
105347
106146
  }
105348
- async function writeActivationFile({ filePath, relativePath, expectedContent, dryRun, logger }) {
106147
+ async function writeActivationFile({ rootPath, filePath, relativePath, expectedContent, dryRun, logger }) {
105349
106148
  const existingContent = await readFileContentOrNull(filePath);
105350
106149
  const normalizedExpected = addTrailingNewline(expectedContent);
105351
106150
  if (fileContentsEquivalent({
@@ -105353,6 +106152,11 @@ async function writeActivationFile({ filePath, relativePath, expectedContent, dr
105353
106152
  expected: normalizedExpected,
105354
106153
  existing: existingContent
105355
106154
  })) return false;
106155
+ await warnIfWriteFollowsLink({
106156
+ logger,
106157
+ rootPath,
106158
+ targetPath: filePath
106159
+ });
105356
106160
  if (dryRun) logger.info(`[DRY RUN] Would write: ${filePath}`);
105357
106161
  else await writeFileContent(filePath, normalizedExpected);
105358
106162
  logger.debug(`Hermes project-plugin activation requires ${relativePath}`);
@@ -105389,6 +106193,7 @@ async function activateHermesProjectPlugins({ pluginNames, dryRun, logger }) {
105389
106193
  const paths = [];
105390
106194
  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.`);
105391
106195
  if (await writeActivationFile({
106196
+ rootPath: configRoot,
105392
106197
  filePath: configPath,
105393
106198
  relativePath: relativeConfigPath,
105394
106199
  expectedContent: expectedConfig,