rulesync 43.12.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
  */
@@ -12731,6 +12723,37 @@ function serialize(value) {
12731
12723
  function stripStrings(_key, value) {
12732
12724
  return typeof value === "string" ? stripControlCharacters(value) : value;
12733
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
+ }
12734
12757
  // src/features/shared/jsonc-object-edit.ts
12735
12758
  /**
12736
12759
  * In-place editing of a JSONC object's text: the engine behind the shared
@@ -14741,7 +14764,7 @@ function tryParseStructured({ filePath, content }) {
14741
14764
  }
14742
14765
  }
14743
14766
  /**
14744
- * 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
14745
14768
  * body matches across generators vs on-disk formatters. Trailing whitespace is normalized via
14746
14769
  * addTrailingNewline (trimEnd + single newline), same as writes.
14747
14770
  */
@@ -14832,7 +14855,7 @@ function fileContentIsEmptyPayload({ filePath, content }) {
14832
14855
  * Whether on-disk content is equivalent to generated content for --check / dry-run.
14833
14856
  *
14834
14857
  * Uses structured comparison for JSON/JSONC (via jsonc-parser), YAML, TOML, and Markdown-like
14835
- * frontmatter files (.md, .mdc — same gray-matter path as elsewhere).
14858
+ * frontmatter files (.md, .mdc — same frontmatter parser as elsewhere).
14836
14859
  */
14837
14860
  function fileContentsEquivalent({ filePath, expected, existing }) {
14838
14861
  if (existing === null) return false;
@@ -15014,6 +15037,11 @@ var FeatureProcessor = class extends RulesyncSourceConsumer {
15014
15037
  if (fileMode !== void 0 && !this.dryRun) await restoreMissingExecutableBit(filePath, fileMode);
15015
15038
  continue;
15016
15039
  }
15040
+ await warnIfWriteFollowsLink({
15041
+ logger: this.logger,
15042
+ rootPath: aiFile.getOutputRoot(),
15043
+ targetPath: filePath
15044
+ });
15017
15045
  if (this.dryRun) this.logger.info(`[DRY RUN] Would write: ${stripControlCharacters(filePath)}`);
15018
15046
  else {
15019
15047
  await writeFileContent(filePath, contentWithNewline);
@@ -15198,6 +15226,37 @@ async function refusesWriteOutsideRoot({ logger, rootPath, targetPath }) {
15198
15226
  return true;
15199
15227
  }
15200
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
+ /**
15201
15260
  * Why the orphan sweep has to leave the files in `dirPath` alone, or `null`
15202
15261
  * when it may delete them.
15203
15262
  *
@@ -18532,6 +18591,11 @@ var GooseCommand = class GooseCommand extends ToolCommand {
18532
18591
  entries: []
18533
18592
  });
18534
18593
  if (nextContent === currentContent) return 0;
18594
+ await warnIfWriteFollowsLink({
18595
+ logger,
18596
+ rootPath: outputRoot,
18597
+ targetPath: configPath
18598
+ });
18535
18599
  if (dryRun) logger.info(`[DRY RUN] Would write: ${configPath}`);
18536
18600
  else await writeFileContent(configPath, nextContent);
18537
18601
  return 1;
@@ -19714,6 +19778,11 @@ var HermesagentCommand = class HermesagentCommand extends ToolCommand {
19714
19778
  global
19715
19779
  });
19716
19780
  if (nextContent === currentContent) return 0;
19781
+ await warnIfWriteFollowsLink({
19782
+ logger,
19783
+ rootPath: outputRoot,
19784
+ targetPath: configPath
19785
+ });
19717
19786
  if (dryRun) logger.info(`[DRY RUN] Would write: ${configPath}`);
19718
19787
  else await writeFileContent(configPath, nextContent);
19719
19788
  return 1;
@@ -23330,6 +23399,17 @@ var DirFeatureProcessor = class extends RulesyncSourceConsumer {
23330
23399
  });
23331
23400
  }
23332
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
+ /**
23333
23413
  * Once converted to rulesync/tool dirs, write them to the filesystem.
23334
23414
  * Returns the number of directories written.
23335
23415
  *
@@ -23382,6 +23462,10 @@ var DirFeatureProcessor = class extends RulesyncSourceConsumer {
23382
23462
  }
23383
23463
  continue;
23384
23464
  }
23465
+ await this.warnIfFilesFollowLinks({
23466
+ aiDir,
23467
+ filePaths: writtenPaths.slice(1)
23468
+ });
23385
23469
  const relativeDir = aiDir.getRelativePathFromCwd();
23386
23470
  if (this.dryRun) {
23387
23471
  this.logger.info(`[DRY RUN] Would create directory: ${stripControlCharacters(dirPath)}`);
@@ -34569,6 +34653,24 @@ function isMissingDescription(value) {
34569
34653
  function nameFromFileName(relativeFilePath) {
34570
34654
  return relativeFilePath.replace(/(\.agent)?\.md$/, "");
34571
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
+ }
34572
34674
  var JunieSubagent = class JunieSubagent extends ToolSubagent {
34573
34675
  frontmatter;
34574
34676
  body;
@@ -34593,14 +34695,30 @@ var JunieSubagent = class JunieSubagent extends ToolSubagent {
34593
34695
  getBody() {
34594
34696
  return this.body;
34595
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
+ }
34596
34714
  toRulesyncSubagent() {
34597
- const { name, description, ...restFields } = this.frontmatter;
34715
+ const { name: _name, description, ...restFields } = this.frontmatter;
34598
34716
  const junieSection = { ...restFields };
34599
34717
  return new RulesyncSubagent({
34600
34718
  outputRoot: ".",
34601
34719
  frontmatter: {
34602
34720
  targets: ["*"],
34603
- name: name ?? nameFromFileName(this.getRelativeFilePath()),
34721
+ name: this.getNormalizedName(),
34604
34722
  ...description !== void 0 && { description },
34605
34723
  ...Object.keys(junieSection).length > 0 && { junie: junieSection }
34606
34724
  },
@@ -48380,8 +48498,8 @@ var TraeRule = class TraeRule extends ToolRule {
48380
48498
  * before parsing, inside the frontmatter block only so the body is never
48381
48499
  * rewritten. A quoted value, a YAML flow list, a null or boolean keyword and a
48382
48500
  * block scalar indicator (`|`, `>`) are left alone. The block bounds are
48383
- * gray-matter's own (it closes the block at the first `\n---`, even inside a
48384
- * `----` 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.
48385
48503
  */
48386
48504
  static parseTraeFrontmatter(fileContent, filePath) {
48387
48505
  const bounds = findFrontmatterBlockBounds(fileContent);
@@ -51686,19 +51804,17 @@ var CursorCheck = class extends AggregatedToolCheck {
51686
51804
  *
51687
51805
  * rulesync never writes frontmatter here, but a user who authored this path as
51688
51806
  * an ordinary skill did, and that block is the skill's metadata rather than
51689
- * review instructions. Writing the check back out hands the body to
51690
- * gray-matter's `stringify`, which re-parses whatever leads it and *merges*
51691
- * those keys into the frontmatter it is given — so a `severity: bogus` copied
51692
- * out of a skill would fail `.rulesync/checks/` validation for a file rulesync
51693
- * had just written, and a stray `name: [unclosed` would make the import throw
51694
- * a raw YAML error.
51695
- *
51696
- * The block is therefore found the way gray-matter finds it rather than by
51697
- * parsing it, so that what gray-matter would have swallowed is what goes: the
51698
- * opening delimiter may carry a language name (`---yaml`), but four dashes are
51699
- * a horizontal rule gray-matter itself skips. The one deliberate difference is
51700
- * a fence nothing closes: gray-matter would swallow the rest of the file, so
51701
- * 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.
51702
51818
  */
51703
51819
  const FRONTMATTER_OPEN_PATTERN = /^\uFEFF?---(?!-)[^\r\n]*\r?\n/;
51704
51820
  const FRONTMATTER_CLOSE_PATTERN = /^---|\r?\n---/;
@@ -60759,6 +60875,51 @@ function warnIgnoredFailClosed({ config, supportedEvents, toolConfigKey, logger
60759
60875
  }
60760
60876
  }
60761
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
+ }
60762
60923
  /** Whether any handler is a `sessionStart` one, whose stdout becomes session context. */
60763
60924
  function usesSessionContext(handlers) {
60764
60925
  return handlers.some((handler) => handler.context);
@@ -60784,7 +60945,7 @@ function handlerExtrasFor(canonicalEvent) {
60784
60945
  * Group the effective hooks into named (tool.execute.*) and generic event
60785
60946
  * handler groups, keyed by tool event name. Mutates the supplied groups.
60786
60947
  */
60787
- function collectOpencodeStyleHandlers({ effectiveHooks, eventMap, namedEventHandlers, genericEventHandlers }) {
60948
+ function collectOpencodeStyleHandlers({ effectiveHooks, eventMap, namedEventHandlers, genericEventHandlers, translateMatcher }) {
60788
60949
  for (const [canonicalEvent, definitions] of Object.entries(effectiveHooks)) {
60789
60950
  const shellGate = SHELL_EVENT_TOOL_GATES[canonicalEvent];
60790
60951
  const extras = handlerExtrasFor(canonicalEvent);
@@ -60792,6 +60953,7 @@ function collectOpencodeStyleHandlers({ effectiveHooks, eventMap, namedEventHand
60792
60953
  if (!toolEvent) continue;
60793
60954
  const isNamedHook = Object.hasOwn(NAMED_HOOK_MATCHER_SUBJECTS, toolEvent);
60794
60955
  const matcherSupported = !shellGate && isNamedHook && NAMED_HOOK_MATCHER_SUBJECTS[toolEvent] !== null;
60956
+ const matchesToolName = NAMED_HOOK_MATCHER_SUBJECTS[toolEvent] === "input.tool";
60795
60957
  const handlers = [];
60796
60958
  for (const def of definitions) {
60797
60959
  if ((def.type ?? "command") !== "command") continue;
@@ -60799,7 +60961,7 @@ function collectOpencodeStyleHandlers({ effectiveHooks, eventMap, namedEventHand
60799
60961
  if (def.matcher && !matcherSupported) continue;
60800
60962
  handlers.push({
60801
60963
  command: def.command,
60802
- matcher: def.matcher ? def.matcher : void 0,
60964
+ matcher: def.matcher ? matchesToolName ? translateMatcher(def.matcher, canonicalEvent) : def.matcher : void 0,
60803
60965
  blocking: BLOCKING_HOOKS.has(toolEvent),
60804
60966
  ...hookTimingOf(def),
60805
60967
  inProcess: !isNamedHook,
@@ -60963,7 +61125,7 @@ function wrapInExportShape({ preambleLines, bodyLines, exportStyle }) {
60963
61125
  lines.push("");
60964
61126
  return lines;
60965
61127
  }
60966
- function generateOpencodeStylePluginCode(config, supportedEvents, toolConfigKey, eventMap, exportStyle = "named") {
61128
+ function generateOpencodeStylePluginCode(config, supportedEvents, toolConfigKey, eventMap, exportStyle = "named", logger) {
60967
61129
  const supported = new Set(supportedEvents);
60968
61130
  const configHooks = {
60969
61131
  ...config.hooks,
@@ -60977,7 +61139,12 @@ function generateOpencodeStylePluginCode(config, supportedEvents, toolConfigKey,
60977
61139
  effectiveHooks,
60978
61140
  eventMap,
60979
61141
  namedEventHandlers,
60980
- genericEventHandlers
61142
+ genericEventHandlers,
61143
+ translateMatcher: createOpencodeMatcherTranslator({
61144
+ toolNames: CANONICAL_TO_OPENCODE_V1_TOOL_NAMES,
61145
+ toolConfigKey,
61146
+ logger
61147
+ })
60981
61148
  });
60982
61149
  const usesContext = Object.values(genericEventHandlers).some(usesSessionContext);
60983
61150
  const bodyLines = [
@@ -61031,7 +61198,7 @@ var KiloHooks = class KiloHooks extends ToolHooks {
61031
61198
  toolConfigKey: "kilo",
61032
61199
  logger
61033
61200
  });
61034
- 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);
61035
61202
  const paths = KiloHooks.getSettablePaths({ global });
61036
61203
  return new KiloHooks({
61037
61204
  outputRoot,
@@ -61895,6 +62062,21 @@ var LettacodeHooks = class LettacodeHooks extends ToolHooks {
61895
62062
  /** Tool name OpenCode V2 gives its shell tool (V1 called it `bash`). */
61896
62063
  const OPENCODE_V2_SHELL_TOOL = "shell";
61897
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
+ /**
61898
62080
  * Per-canonical-event conditions the generated handler gates on, because the
61899
62081
  * hook point or event it shares fires more broadly than the canonical event:
61900
62082
  * - the shell events run only for the `shell` tool's calls;
@@ -62071,7 +62253,7 @@ function isBlockingOpencodeV2Target(target) {
62071
62253
  return !target.startsWith("event:") && target !== "tool:execute.after";
62072
62254
  }
62073
62255
  /** Build the handlers of one canonical event's command definitions. */
62074
- function buildHandlersFor({ canonicalEvent, definitions, target }) {
62256
+ function buildHandlersFor({ canonicalEvent, definitions, target, translateMatcher }) {
62075
62257
  const gate = OPENCODE_V2_HANDLER_GATES[canonicalEvent];
62076
62258
  const payload = OPENCODE_V2_STDIN_PAYLOADS[canonicalEvent];
62077
62259
  const matcherSupported = !(canonicalEvent === "beforeShellExecution" || canonicalEvent === "afterShellExecution") && OPENCODE_V2_MATCHABLE_HOOKS.has(target);
@@ -62085,7 +62267,7 @@ function buildHandlersFor({ canonicalEvent, definitions, target }) {
62085
62267
  event: canonicalEvent,
62086
62268
  blocking: isBlockingOpencodeV2Target(target),
62087
62269
  ...hookTimingOf(def),
62088
- ...def.matcher ? { matcher: def.matcher } : {},
62270
+ ...def.matcher ? { matcher: translateMatcher(def.matcher, canonicalEvent) } : {},
62089
62271
  ...gate ? { gate } : {},
62090
62272
  ...payload ? { payload } : {},
62091
62273
  ...sessionContextExtrasFor(canonicalEvent)
@@ -62121,12 +62303,17 @@ function buildSetupBodyLines({ hookHandlers, eventHandlers }) {
62121
62303
  body.push("", "return async () => {", ...cleanup, "};");
62122
62304
  return body;
62123
62305
  }
62124
- function generateOpencodeV2PluginCode({ config, supportedEvents, toolConfigKey, eventMap }) {
62306
+ function generateOpencodeV2PluginCode({ config, supportedEvents, toolConfigKey, eventMap, logger }) {
62125
62307
  const supported = new Set(supportedEvents);
62126
62308
  const configHooks = {
62127
62309
  ...config.hooks,
62128
62310
  ...config[toolConfigKey]?.hooks
62129
62311
  };
62312
+ const translateMatcher = createOpencodeMatcherTranslator({
62313
+ toolNames: CANONICAL_TO_OPENCODE_V2_TOOL_NAMES,
62314
+ toolConfigKey,
62315
+ logger
62316
+ });
62130
62317
  const hookHandlers = /* @__PURE__ */ new Map();
62131
62318
  const eventHandlers = /* @__PURE__ */ new Map();
62132
62319
  for (const [canonicalEvent, definitions] of Object.entries(configHooks)) {
@@ -62136,7 +62323,8 @@ function generateOpencodeV2PluginCode({ config, supportedEvents, toolConfigKey,
62136
62323
  const handlers = buildHandlersFor({
62137
62324
  canonicalEvent,
62138
62325
  definitions,
62139
- target
62326
+ target,
62327
+ translateMatcher
62140
62328
  });
62141
62329
  if (handlers.length === 0) continue;
62142
62330
  const isEvent = target.startsWith("event:");
@@ -62191,8 +62379,9 @@ var OpencodeHooks = class extends ToolHooks {
62191
62379
  config,
62192
62380
  supportedEvents: OPENCODE_V2_HOOK_EVENTS,
62193
62381
  toolConfigKey: this.layout.toolTarget,
62194
- eventMap: CANONICAL_TO_OPENCODE_V2_EVENT_NAMES
62195
- }) : 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);
62196
62385
  const paths = this.getSettablePaths({ global });
62197
62386
  return new this({
62198
62387
  outputRoot,
@@ -105902,6 +106091,11 @@ async function ensureAntigravityPluginManifests({ outputRoots, dryRun, logger })
105902
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)}.`);
105903
106092
  noteName(name, filePath);
105904
106093
  const content = addTrailingNewline(JSON.stringify({ name }, null, 2));
106094
+ await warnIfWriteFollowsLink({
106095
+ logger,
106096
+ rootPath: outputRoot,
106097
+ targetPath: filePath
106098
+ });
105905
106099
  if (dryRun) logger.info(`[DRY RUN] Would write: ${stripControlCharacters(filePath)}`);
105906
106100
  else await writeFileContent(filePath, content);
105907
106101
  paths.push(ANTIGRAVITY_PLUGIN_MANIFEST_FILE_NAME);
@@ -105950,7 +106144,7 @@ function mergeEnabledPlugins({ existingContent, filePath, pluginNames }) {
105950
106144
  }
105951
106145
  });
105952
106146
  }
105953
- async function writeActivationFile({ filePath, relativePath, expectedContent, dryRun, logger }) {
106147
+ async function writeActivationFile({ rootPath, filePath, relativePath, expectedContent, dryRun, logger }) {
105954
106148
  const existingContent = await readFileContentOrNull(filePath);
105955
106149
  const normalizedExpected = addTrailingNewline(expectedContent);
105956
106150
  if (fileContentsEquivalent({
@@ -105958,6 +106152,11 @@ async function writeActivationFile({ filePath, relativePath, expectedContent, dr
105958
106152
  expected: normalizedExpected,
105959
106153
  existing: existingContent
105960
106154
  })) return false;
106155
+ await warnIfWriteFollowsLink({
106156
+ logger,
106157
+ rootPath,
106158
+ targetPath: filePath
106159
+ });
105961
106160
  if (dryRun) logger.info(`[DRY RUN] Would write: ${filePath}`);
105962
106161
  else await writeFileContent(filePath, normalizedExpected);
105963
106162
  logger.debug(`Hermes project-plugin activation requires ${relativePath}`);
@@ -105994,6 +106193,7 @@ async function activateHermesProjectPlugins({ pluginNames, dryRun, logger }) {
105994
106193
  const paths = [];
105995
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.`);
105996
106195
  if (await writeActivationFile({
106196
+ rootPath: configRoot,
105997
106197
  filePath: configPath,
105998
106198
  relativePath: relativeConfigPath,
105999
106199
  expectedContent: expectedConfig,