rulesync 43.16.0 → 43.18.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.
@@ -381,40 +381,40 @@ function formatError(error) {
381
381
  return boundErrorMessage(String(error));
382
382
  }
383
383
  // src/constants/rulesync-paths.ts
384
- const { join: join$384 } = node_path.posix;
384
+ const { join: join$387 } = node_path.posix;
385
385
  const RULESYNC_CONFIG_RELATIVE_FILE_PATH = "rulesync.jsonc";
386
386
  const RULESYNC_LOCAL_CONFIG_RELATIVE_FILE_PATH = "rulesync.local.jsonc";
387
387
  const RULESYNC_USER_CONFIG_DIR_NAME = "rulesync";
388
388
  const RULESYNC_XDG_CONFIG_HOME_DEFAULT_DIR_NAME = ".config";
389
389
  const RULESYNC_RELATIVE_DIR_PATH = ".rulesync";
390
390
  const RULES_FEATURE_SUBDIR = "rules";
391
- const CURATED_RULES_FEATURE_SUBDIR = join$384(RULES_FEATURE_SUBDIR, ".curated");
391
+ const CURATED_RULES_FEATURE_SUBDIR = join$387(RULES_FEATURE_SUBDIR, ".curated");
392
392
  const COMMANDS_FEATURE_SUBDIR = "commands";
393
- const CURATED_COMMANDS_FEATURE_SUBDIR = join$384(COMMANDS_FEATURE_SUBDIR, ".curated");
393
+ const CURATED_COMMANDS_FEATURE_SUBDIR = join$387(COMMANDS_FEATURE_SUBDIR, ".curated");
394
394
  const SUBAGENTS_FEATURE_SUBDIR = "subagents";
395
- const CURATED_SUBAGENTS_FEATURE_SUBDIR = join$384(SUBAGENTS_FEATURE_SUBDIR, ".curated");
395
+ const CURATED_SUBAGENTS_FEATURE_SUBDIR = join$387(SUBAGENTS_FEATURE_SUBDIR, ".curated");
396
396
  const CHECKS_FEATURE_SUBDIR = "checks";
397
397
  const SKILLS_FEATURE_SUBDIR = "skills";
398
- const CURATED_SKILLS_FEATURE_SUBDIR = join$384(SKILLS_FEATURE_SUBDIR, ".curated");
399
- const RULESYNC_RULES_RELATIVE_DIR_PATH = join$384(RULESYNC_RELATIVE_DIR_PATH, RULES_FEATURE_SUBDIR);
400
- const RULESYNC_CURATED_RULES_RELATIVE_DIR_PATH = join$384(RULESYNC_RELATIVE_DIR_PATH, CURATED_RULES_FEATURE_SUBDIR);
401
- const RULESYNC_COMMANDS_RELATIVE_DIR_PATH = join$384(RULESYNC_RELATIVE_DIR_PATH, COMMANDS_FEATURE_SUBDIR);
402
- const RULESYNC_CURATED_COMMANDS_RELATIVE_DIR_PATH = join$384(RULESYNC_RELATIVE_DIR_PATH, CURATED_COMMANDS_FEATURE_SUBDIR);
403
- const RULESYNC_SUBAGENTS_RELATIVE_DIR_PATH = join$384(RULESYNC_RELATIVE_DIR_PATH, SUBAGENTS_FEATURE_SUBDIR);
404
- const RULESYNC_CURATED_SUBAGENTS_RELATIVE_DIR_PATH = join$384(RULESYNC_RELATIVE_DIR_PATH, CURATED_SUBAGENTS_FEATURE_SUBDIR);
405
- const RULESYNC_CHECKS_RELATIVE_DIR_PATH = join$384(RULESYNC_RELATIVE_DIR_PATH, CHECKS_FEATURE_SUBDIR);
406
- const RULESYNC_MCP_RELATIVE_FILE_PATH = join$384(RULESYNC_RELATIVE_DIR_PATH, "mcp.jsonc");
407
- const RULESYNC_HOOKS_RELATIVE_FILE_PATH = join$384(RULESYNC_RELATIVE_DIR_PATH, "hooks.jsonc");
408
- const RULESYNC_PERMISSIONS_RELATIVE_FILE_PATH = join$384(RULESYNC_RELATIVE_DIR_PATH, "permissions.jsonc");
409
- join$384(RULESYNC_RELATIVE_DIR_PATH, "mcp.json");
410
- const RULESYNC_HOOKS_LEGACY_RELATIVE_FILE_PATH = join$384(RULESYNC_RELATIVE_DIR_PATH, "hooks.json");
411
- const RULESYNC_PERMISSIONS_LEGACY_RELATIVE_FILE_PATH = join$384(RULESYNC_RELATIVE_DIR_PATH, "permissions.json");
398
+ const CURATED_SKILLS_FEATURE_SUBDIR = join$387(SKILLS_FEATURE_SUBDIR, ".curated");
399
+ const RULESYNC_RULES_RELATIVE_DIR_PATH = join$387(RULESYNC_RELATIVE_DIR_PATH, RULES_FEATURE_SUBDIR);
400
+ const RULESYNC_CURATED_RULES_RELATIVE_DIR_PATH = join$387(RULESYNC_RELATIVE_DIR_PATH, CURATED_RULES_FEATURE_SUBDIR);
401
+ const RULESYNC_COMMANDS_RELATIVE_DIR_PATH = join$387(RULESYNC_RELATIVE_DIR_PATH, COMMANDS_FEATURE_SUBDIR);
402
+ const RULESYNC_CURATED_COMMANDS_RELATIVE_DIR_PATH = join$387(RULESYNC_RELATIVE_DIR_PATH, CURATED_COMMANDS_FEATURE_SUBDIR);
403
+ const RULESYNC_SUBAGENTS_RELATIVE_DIR_PATH = join$387(RULESYNC_RELATIVE_DIR_PATH, SUBAGENTS_FEATURE_SUBDIR);
404
+ const RULESYNC_CURATED_SUBAGENTS_RELATIVE_DIR_PATH = join$387(RULESYNC_RELATIVE_DIR_PATH, CURATED_SUBAGENTS_FEATURE_SUBDIR);
405
+ const RULESYNC_CHECKS_RELATIVE_DIR_PATH = join$387(RULESYNC_RELATIVE_DIR_PATH, CHECKS_FEATURE_SUBDIR);
406
+ const RULESYNC_MCP_RELATIVE_FILE_PATH = join$387(RULESYNC_RELATIVE_DIR_PATH, "mcp.jsonc");
407
+ const RULESYNC_HOOKS_RELATIVE_FILE_PATH = join$387(RULESYNC_RELATIVE_DIR_PATH, "hooks.jsonc");
408
+ const RULESYNC_PERMISSIONS_RELATIVE_FILE_PATH = join$387(RULESYNC_RELATIVE_DIR_PATH, "permissions.jsonc");
409
+ join$387(RULESYNC_RELATIVE_DIR_PATH, "mcp.json");
410
+ const RULESYNC_HOOKS_LEGACY_RELATIVE_FILE_PATH = join$387(RULESYNC_RELATIVE_DIR_PATH, "hooks.json");
411
+ const RULESYNC_PERMISSIONS_LEGACY_RELATIVE_FILE_PATH = join$387(RULESYNC_RELATIVE_DIR_PATH, "permissions.json");
412
412
  const RULESYNC_AIIGNORE_FILE_NAME = ".aiignore";
413
- const RULESYNC_AIIGNORE_RELATIVE_FILE_PATH = join$384(RULESYNC_RELATIVE_DIR_PATH, ".aiignore");
413
+ const RULESYNC_AIIGNORE_RELATIVE_FILE_PATH = join$387(RULESYNC_RELATIVE_DIR_PATH, ".aiignore");
414
414
  const RULESYNC_IGNORE_RELATIVE_FILE_PATH = ".rulesyncignore";
415
415
  const RULESYNC_OVERVIEW_FILE_NAME = "overview.md";
416
- const RULESYNC_SKILLS_RELATIVE_DIR_PATH = join$384(RULESYNC_RELATIVE_DIR_PATH, SKILLS_FEATURE_SUBDIR);
417
- const RULESYNC_CURATED_SKILLS_RELATIVE_DIR_PATH = join$384(RULESYNC_RELATIVE_DIR_PATH, CURATED_SKILLS_FEATURE_SUBDIR);
416
+ const RULESYNC_SKILLS_RELATIVE_DIR_PATH = join$387(RULESYNC_RELATIVE_DIR_PATH, SKILLS_FEATURE_SUBDIR);
417
+ const RULESYNC_CURATED_SKILLS_RELATIVE_DIR_PATH = join$387(RULESYNC_RELATIVE_DIR_PATH, CURATED_SKILLS_FEATURE_SUBDIR);
418
418
  const RULESYNC_SOURCES_LOCK_RELATIVE_FILE_PATH = "rulesync.lock";
419
419
  const RULESYNC_NPM_SOURCES_LOCK_RELATIVE_FILE_PATH = "rulesync-npm.lock.json";
420
420
  const RULESYNC_MCP_FILE_NAME = "mcp.jsonc";
@@ -3291,6 +3291,9 @@ const ConfigParamsSchema = zod_mini.z.object({
3291
3291
  simulateSubagents: (0, zod_mini.optional)(zod_mini.z.boolean()),
3292
3292
  simulateSkills: (0, zod_mini.optional)(zod_mini.z.boolean()),
3293
3293
  preserveUnownedHooks: (0, zod_mini.optional)(zod_mini.z.boolean()),
3294
+ preserveUnmanagedRuleContent: (0, zod_mini.optional)(zod_mini.z.boolean()),
3295
+ preserveUnownedSkills: (0, zod_mini.optional)(zod_mini.z.boolean()),
3296
+ preserveUnownedMcpServers: (0, zod_mini.optional)(zod_mini.z.boolean()),
3294
3297
  deriveSubprojectPathFromGlobs: (0, zod_mini.optional)(zod_mini.z.boolean()),
3295
3298
  flattenedCommandNaming: (0, zod_mini.optional)(FlattenedCommandNamingSchema),
3296
3299
  /**
@@ -3473,6 +3476,9 @@ var Config = class Config {
3473
3476
  simulateSubagents;
3474
3477
  simulateSkills;
3475
3478
  preserveUnownedHooks;
3479
+ preserveUnmanagedRuleContent;
3480
+ preserveUnownedSkills;
3481
+ preserveUnownedMcpServers;
3476
3482
  deriveSubprojectPathFromGlobs;
3477
3483
  flattenedCommandNaming;
3478
3484
  language;
@@ -3501,7 +3507,7 @@ var Config = class Config {
3501
3507
  inputRoots;
3502
3508
  configFilePath;
3503
3509
  sources;
3504
- constructor({ outputRoots, targets, features, verbose, delete: isDelete, global, silent, simulateCommands, simulateSubagents, simulateSkills, preserveUnownedHooks, deriveSubprojectPathFromGlobs, flattenedCommandNaming, language, gitignoreTargetsOnly, gitignoreDestination, dryRun, check, retireTargets, retireFeatures, inputRoot, inputRoots, configFilePath, sources, configFileTargets, configFileSelection }) {
3510
+ constructor({ outputRoots, targets, features, verbose, delete: isDelete, global, silent, simulateCommands, simulateSubagents, simulateSkills, preserveUnownedHooks, preserveUnmanagedRuleContent, preserveUnownedSkills, preserveUnownedMcpServers, deriveSubprojectPathFromGlobs, flattenedCommandNaming, language, gitignoreTargetsOnly, gitignoreDestination, dryRun, check, retireTargets, retireFeatures, inputRoot, inputRoots, configFilePath, sources, configFileTargets, configFileSelection }) {
3505
3511
  assertTargetsFeaturesExclusive({
3506
3512
  targets,
3507
3513
  features
@@ -3535,6 +3541,9 @@ var Config = class Config {
3535
3541
  this.simulateSubagents = simulateSubagents ?? false;
3536
3542
  this.simulateSkills = simulateSkills ?? false;
3537
3543
  this.preserveUnownedHooks = preserveUnownedHooks ?? false;
3544
+ this.preserveUnmanagedRuleContent = preserveUnmanagedRuleContent === true;
3545
+ this.preserveUnownedSkills = preserveUnownedSkills === true;
3546
+ this.preserveUnownedMcpServers = preserveUnownedMcpServers === true;
3538
3547
  this.deriveSubprojectPathFromGlobs = deriveSubprojectPathFromGlobs ?? false;
3539
3548
  this.flattenedCommandNaming = flattenedCommandNaming ?? "basename";
3540
3549
  this.language = language;
@@ -3795,6 +3804,15 @@ var Config = class Config {
3795
3804
  getPreserveUnownedHooks() {
3796
3805
  return this.preserveUnownedHooks;
3797
3806
  }
3807
+ getPreserveUnmanagedRuleContent() {
3808
+ return this.preserveUnmanagedRuleContent;
3809
+ }
3810
+ getPreserveUnownedSkills() {
3811
+ return this.preserveUnownedSkills;
3812
+ }
3813
+ getPreserveUnownedMcpServers() {
3814
+ return this.preserveUnownedMcpServers;
3815
+ }
3798
3816
  getFlattenedCommandNaming() {
3799
3817
  return this.flattenedCommandNaming;
3800
3818
  }
@@ -3860,6 +3878,24 @@ var Config = class Config {
3860
3878
  return this.dryRun || this.check;
3861
3879
  }
3862
3880
  };
3881
+ /**
3882
+ * The `rules` options for `target` in a run, with the `include` rule selection
3883
+ * always read from the configuration file. `--targets` replaces the object
3884
+ * form of `targets`, and with it every per-target option, but a target that
3885
+ * selects its rules there must not receive every rule just because it was
3886
+ * picked with `--targets`: that would write the rules the user deliberately
3887
+ * kept away from it.
3888
+ */
3889
+ function getRulesFeatureOptions(config, target) {
3890
+ const options = config.getFeatureOptions(target, "rules");
3891
+ if (options !== void 0 && "include" in options) return options;
3892
+ const configFileOptions = config.getConfigFileFeatureOptions(target, "rules");
3893
+ if (configFileOptions === void 0 || !("include" in configFileOptions)) return options;
3894
+ return {
3895
+ ...options,
3896
+ include: configFileOptions.include
3897
+ };
3898
+ }
3863
3899
  // src/config/config-resolver.ts
3864
3900
  const getDefaults = () => ({
3865
3901
  targets: ["agentsmd"],
@@ -3874,6 +3910,9 @@ const getDefaults = () => ({
3874
3910
  simulateSubagents: false,
3875
3911
  simulateSkills: false,
3876
3912
  preserveUnownedHooks: false,
3913
+ preserveUnmanagedRuleContent: false,
3914
+ preserveUnownedSkills: false,
3915
+ preserveUnownedMcpServers: false,
3877
3916
  deriveSubprojectPathFromGlobs: false,
3878
3917
  flattenedCommandNaming: "basename",
3879
3918
  gitignoreTargetsOnly: true,
@@ -4212,6 +4251,21 @@ var ConfigResolver = class {
4212
4251
  file: configByFile.preserveUnownedHooks,
4213
4252
  fallback: getDefaults().preserveUnownedHooks
4214
4253
  }),
4254
+ preserveUnmanagedRuleContent: pick({
4255
+ cli: void 0,
4256
+ file: configByFile.preserveUnmanagedRuleContent,
4257
+ fallback: getDefaults().preserveUnmanagedRuleContent
4258
+ }),
4259
+ preserveUnownedSkills: pick({
4260
+ cli: void 0,
4261
+ file: configByFile.preserveUnownedSkills,
4262
+ fallback: getDefaults().preserveUnownedSkills
4263
+ }),
4264
+ preserveUnownedMcpServers: pick({
4265
+ cli: void 0,
4266
+ file: configByFile.preserveUnownedMcpServers,
4267
+ fallback: getDefaults().preserveUnownedMcpServers
4268
+ }),
4215
4269
  deriveSubprojectPathFromGlobs: pick({
4216
4270
  cli: deriveSubprojectPathFromGlobs,
4217
4271
  file: configByFile.deriveSubprojectPathFromGlobs,
@@ -4453,6 +4507,33 @@ var AiFile = class {
4453
4507
  return false;
4454
4508
  }
4455
4509
  /**
4510
+ * The content the write phase puts on disk, given what the file holds now
4511
+ * (`null` when it does not exist) and the generated content (already ending
4512
+ * in a newline). Defaults to the generated content; override for a file
4513
+ * that keeps part of the existing content, such as a root rule file under
4514
+ * `preserveUnmanagedRuleContent`. `generate --check` compares the same
4515
+ * composed content, so content kept this way is never reported as drift.
4516
+ */
4517
+ composeWrittenContent({ generatedContent }) {
4518
+ return generatedContent;
4519
+ }
4520
+ /**
4521
+ * Whether removing this file (the `--delete` sweep, `retireTargets`) has to
4522
+ * look at what it holds first, through {@link composeContentAfterRemoval}.
4523
+ */
4524
+ keepsContentOnRemoval() {
4525
+ return false;
4526
+ }
4527
+ /**
4528
+ * How removing this file treats what it holds: `delete` it as a whole (the
4529
+ * default), `rewrite` it with rulesync's own content taken out, or `keep` it
4530
+ * untouched because none of it is rulesync's any more. Only consulted when
4531
+ * {@link keepsContentOnRemoval} is true.
4532
+ */
4533
+ composeContentAfterRemoval(_params) {
4534
+ return { action: "delete" };
4535
+ }
4536
+ /**
4456
4537
  * POSIX mode to apply after writing, or `undefined` to leave the default
4457
4538
  * alone. Override in subclasses whose output the tool executes directly
4458
4539
  * (e.g. Cline's hook scripts, which are spawned by path and therefore need
@@ -12361,6 +12442,1125 @@ function classifyRemoteName(name) {
12361
12442
  };
12362
12443
  return { kind: "safe" };
12363
12444
  }
12445
+ // src/types/git-provider.ts
12446
+ /**
12447
+ * Supported Git providers for fetch command
12448
+ */
12449
+ const ALL_GIT_PROVIDERS = ["github", "gitlab"];
12450
+ zod_mini.z.enum(ALL_GIT_PROVIDERS);
12451
+ // src/lib/source-parser.ts
12452
+ const GITHUB_HOSTS = /* @__PURE__ */ new Set(["github.com", "www.github.com"]);
12453
+ const GITLAB_HOSTS = /* @__PURE__ */ new Set(["gitlab.com", "www.gitlab.com"]);
12454
+ /**
12455
+ * Parse source specification into components
12456
+ * Supports:
12457
+ * - URL format: https://github.com/owner/repo, https://gitlab.com/owner/repo
12458
+ * - Prefix format: github:owner/repo, gitlab:owner/repo
12459
+ * - Shorthand format: owner/repo (defaults to GitHub)
12460
+ * - With ref: owner/repo@ref
12461
+ * - With path: owner/repo:path
12462
+ * - Combined: owner/repo@ref:path
12463
+ */
12464
+ function parseSource(source) {
12465
+ if (source.startsWith("http://") || source.startsWith("https://")) return parseUrl(source);
12466
+ if (source.includes(":") && !source.includes("://")) {
12467
+ const colonIndex = source.indexOf(":");
12468
+ const prefix = source.substring(0, colonIndex);
12469
+ const rest = source.substring(colonIndex + 1);
12470
+ const provider = ALL_GIT_PROVIDERS.find((p) => p === prefix);
12471
+ if (provider) return {
12472
+ provider,
12473
+ ...parseShorthand(rest)
12474
+ };
12475
+ return {
12476
+ provider: "github",
12477
+ ...parseShorthand(source)
12478
+ };
12479
+ }
12480
+ return {
12481
+ provider: "github",
12482
+ ...parseShorthand(source)
12483
+ };
12484
+ }
12485
+ /**
12486
+ * Parse URL format into components
12487
+ */
12488
+ function parseUrl(url) {
12489
+ const urlObj = new URL(url);
12490
+ const host = urlObj.hostname.toLowerCase();
12491
+ let provider;
12492
+ if (GITHUB_HOSTS.has(host)) provider = "github";
12493
+ else if (GITLAB_HOSTS.has(host)) provider = "gitlab";
12494
+ else throw new Error(`Unknown Git provider for host: ${host}. Supported providers: ${ALL_GIT_PROVIDERS.join(", ")}`);
12495
+ const segments = urlObj.pathname.split("/").filter(Boolean);
12496
+ if (segments.length < 2) throw new Error(`Invalid ${provider} URL: ${url}. Expected format: https://${host}/owner/repo`);
12497
+ const owner = segments[0];
12498
+ const repo = segments[1]?.replace(/\.git$/, "");
12499
+ if (segments.length > 2 && (segments[2] === "tree" || segments[2] === "blob")) {
12500
+ const decode = (segment) => decodeUrlSegment({
12501
+ segment,
12502
+ provider,
12503
+ url
12504
+ });
12505
+ const ref = segments[3] === void 0 ? void 0 : decode(segments[3]);
12506
+ const path = segments.length > 4 ? decode(segments.slice(4).join("/")) : void 0;
12507
+ if (path !== void 0 && path.split(/[\\/]/).includes("..")) throw new Error(`Invalid ${provider} URL: ${url}. Path must not contain ".." segments.`);
12508
+ return {
12509
+ provider,
12510
+ owner: owner ?? "",
12511
+ repo: repo ?? "",
12512
+ ref,
12513
+ path
12514
+ };
12515
+ }
12516
+ return {
12517
+ provider,
12518
+ owner: owner ?? "",
12519
+ repo: repo ?? ""
12520
+ };
12521
+ }
12522
+ /**
12523
+ * Percent-decode a URL path segment, turning a malformed escape (e.g. a lone
12524
+ * `%`) into an error that names the offending source.
12525
+ */
12526
+ function decodeUrlSegment({ segment, provider, url }) {
12527
+ try {
12528
+ return decodeURIComponent(segment);
12529
+ } catch (error) {
12530
+ if (error instanceof URIError) throw new Error(`Invalid ${provider} URL: ${url}. Malformed percent-encoding in ref or path.`, { cause: error });
12531
+ throw error;
12532
+ }
12533
+ }
12534
+ /**
12535
+ * Parse shorthand format (without provider prefix)
12536
+ */
12537
+ function parseShorthand(source) {
12538
+ let remaining = source;
12539
+ let path;
12540
+ let ref;
12541
+ const colonIndex = remaining.indexOf(":");
12542
+ if (colonIndex !== -1) {
12543
+ path = remaining.substring(colonIndex + 1);
12544
+ if (!path) throw new Error(`Invalid source: ${source}. Path cannot be empty after ":".`);
12545
+ remaining = remaining.substring(0, colonIndex);
12546
+ }
12547
+ const atIndex = remaining.indexOf("@");
12548
+ if (atIndex !== -1) {
12549
+ ref = remaining.substring(atIndex + 1);
12550
+ if (!ref) throw new Error(`Invalid source: ${source}. Ref cannot be empty after "@".`);
12551
+ remaining = remaining.substring(0, atIndex);
12552
+ }
12553
+ const slashIndex = remaining.indexOf("/");
12554
+ if (slashIndex === -1) throw new Error(`Invalid source: ${source}. Expected format: owner/repo, owner/repo@ref, or owner/repo:path`);
12555
+ const owner = remaining.substring(0, slashIndex);
12556
+ const repo = remaining.substring(slashIndex + 1);
12557
+ if (!owner || !repo) throw new Error(`Invalid source: ${source}. Both owner and repo are required.`);
12558
+ return {
12559
+ owner,
12560
+ repo,
12561
+ ref,
12562
+ path
12563
+ };
12564
+ }
12565
+ /**
12566
+ * Schema for a single locked skill entry with content integrity.
12567
+ */
12568
+ const LockedSkillSchema = zod_mini.z.object({ integrity: zod_mini.z.string() });
12569
+ /** Schema for a single locked rule entry with content integrity. */
12570
+ const LockedRuleSchema = zod_mini.z.object({ integrity: zod_mini.z.string() });
12571
+ /**
12572
+ * Schema for a single locked source entry.
12573
+ */
12574
+ const LockedSourceSchema = zod_mini.z.object({
12575
+ requestedRef: (0, zod_mini.optional)(zod_mini.z.string()),
12576
+ resolvedRef: zod_mini.z.string().check((0, zod_mini.refine)((v) => /^[0-9a-f]{40}$/.test(v), "resolvedRef must be a 40-character hex SHA")),
12577
+ resolvedAt: (0, zod_mini.optional)(zod_mini.z.string()),
12578
+ skills: zod_mini.z.record(zod_mini.z.string(), LockedSkillSchema),
12579
+ /**
12580
+ * The normalized `skills` selection the entry was written for. Absent from
12581
+ * lockfiles written before the selection was recorded.
12582
+ */
12583
+ skillSelection: (0, zod_mini.optional)(zod_mini.z.array(zod_mini.z.string())),
12584
+ /**
12585
+ * The normalized path the skills were read from in the source. Absent from
12586
+ * lockfiles written before the path was recorded.
12587
+ */
12588
+ skillsPath: (0, zod_mini.optional)(zod_mini.z.string()),
12589
+ rules: (0, zod_mini.optional)(zod_mini.z.record(zod_mini.z.string(), LockedRuleSchema)),
12590
+ ruleSelection: (0, zod_mini.optional)(zod_mini.z.array(zod_mini.z.string())),
12591
+ rulesPath: (0, zod_mini.optional)(zod_mini.z.string()),
12592
+ resolvedRuleNames: (0, zod_mini.optional)(zod_mini.z.array(zod_mini.z.string())),
12593
+ commands: (0, zod_mini.optional)(zod_mini.z.record(zod_mini.z.string(), LockedRuleSchema)),
12594
+ commandSelection: (0, zod_mini.optional)(zod_mini.z.array(zod_mini.z.string())),
12595
+ commandsPath: (0, zod_mini.optional)(zod_mini.z.string()),
12596
+ resolvedCommandNames: (0, zod_mini.optional)(zod_mini.z.array(zod_mini.z.string())),
12597
+ subagents: (0, zod_mini.optional)(zod_mini.z.record(zod_mini.z.string(), LockedRuleSchema)),
12598
+ subagentSelection: (0, zod_mini.optional)(zod_mini.z.array(zod_mini.z.string())),
12599
+ subagentsPath: (0, zod_mini.optional)(zod_mini.z.string()),
12600
+ resolvedSubagentNames: (0, zod_mini.optional)(zod_mini.z.array(zod_mini.z.string()))
12601
+ });
12602
+ /**
12603
+ * Schema for the full lockfile (current version).
12604
+ */
12605
+ const SourcesLockSchema = zod_mini.z.object({
12606
+ lockfileVersion: zod_mini.z.number(),
12607
+ sources: zod_mini.z.record(zod_mini.z.string(), LockedSourceSchema)
12608
+ });
12609
+ /**
12610
+ * Schema for the legacy v0 lockfile format (skills as string array, no version field).
12611
+ */
12612
+ const LegacyLockedSourceSchema = zod_mini.z.object({
12613
+ resolvedRef: zod_mini.z.string(),
12614
+ skills: zod_mini.z.array(zod_mini.z.string())
12615
+ });
12616
+ const LegacySourcesLockSchema = zod_mini.z.object({ sources: zod_mini.z.record(zod_mini.z.string(), LegacyLockedSourceSchema) });
12617
+ /**
12618
+ * Migrate a legacy lockfile (string[] skills, no version) to the current format.
12619
+ * Skills get empty integrity since we can't compute it retroactively.
12620
+ */
12621
+ function migrateLegacyLock(params) {
12622
+ const { legacy, logger } = params;
12623
+ const sources = {};
12624
+ for (const [key, entry] of Object.entries(legacy.sources)) {
12625
+ const skills = {};
12626
+ for (const name of entry.skills) skills[name] = { integrity: "" };
12627
+ sources[key] = {
12628
+ resolvedRef: entry.resolvedRef,
12629
+ skills
12630
+ };
12631
+ }
12632
+ logger.info("Migrated legacy sources lockfile to version 1. Run 'rulesync install --update' to populate integrity hashes.");
12633
+ return {
12634
+ lockfileVersion: 1,
12635
+ sources
12636
+ };
12637
+ }
12638
+ /**
12639
+ * Create an empty lockfile structure.
12640
+ */
12641
+ function createEmptyLock() {
12642
+ return {
12643
+ lockfileVersion: 1,
12644
+ sources: {}
12645
+ };
12646
+ }
12647
+ /**
12648
+ * Read the lockfile from disk.
12649
+ * @returns The parsed lockfile, or an empty lockfile if it doesn't exist or is invalid.
12650
+ */
12651
+ async function readLockFile(params) {
12652
+ const { logger } = params;
12653
+ const lockPath = (0, node_path.join)(params.projectRoot, RULESYNC_SOURCES_LOCK_RELATIVE_FILE_PATH);
12654
+ if (!await fileExists(lockPath)) {
12655
+ logger.debug("No sources lockfile found, starting fresh.");
12656
+ return createEmptyLock();
12657
+ }
12658
+ try {
12659
+ const content = await readFileContent(lockPath);
12660
+ const data = JSON.parse(content);
12661
+ const result = SourcesLockSchema.safeParse(data);
12662
+ if (result.success) return result.data;
12663
+ const legacyResult = LegacySourcesLockSchema.safeParse(data);
12664
+ if (legacyResult.success) return migrateLegacyLock({
12665
+ legacy: legacyResult.data,
12666
+ logger
12667
+ });
12668
+ logger.warn(`Invalid sources lockfile format (${RULESYNC_SOURCES_LOCK_RELATIVE_FILE_PATH}). Starting fresh.`);
12669
+ return createEmptyLock();
12670
+ } catch {
12671
+ logger.warn(`Failed to read sources lockfile (${RULESYNC_SOURCES_LOCK_RELATIVE_FILE_PATH}). Starting fresh.`);
12672
+ return createEmptyLock();
12673
+ }
12674
+ }
12675
+ /**
12676
+ * Write the lockfile to disk.
12677
+ */
12678
+ async function writeLockFile(params) {
12679
+ const { logger } = params;
12680
+ const lockPath = (0, node_path.join)(params.projectRoot, RULESYNC_SOURCES_LOCK_RELATIVE_FILE_PATH);
12681
+ await writeFileContent(lockPath, JSON.stringify(params.lock, null, 2) + "\n");
12682
+ logger.debug(`Wrote sources lockfile to ${lockPath}`);
12683
+ }
12684
+ /**
12685
+ * Compute a SHA-256 integrity hash for a skill's contents.
12686
+ * Takes a sorted list of [relativePath, content] pairs to produce a deterministic hash.
12687
+ */
12688
+ function computeSkillIntegrity(files) {
12689
+ const hash = (0, node_crypto.createHash)("sha256");
12690
+ const sorted = files.toSorted((a, b) => a.path.localeCompare(b.path));
12691
+ for (const file of sorted) {
12692
+ hash.update(file.path);
12693
+ hash.update("\0");
12694
+ hash.update(file.content);
12695
+ hash.update("\0");
12696
+ }
12697
+ return `sha256-${hash.digest("hex")}`;
12698
+ }
12699
+ /** Compute a SHA-256 integrity hash for one rule file. */
12700
+ function computeRuleIntegrity(content) {
12701
+ const hash = (0, node_crypto.createHash)("sha256");
12702
+ hash.update(content);
12703
+ return `sha256-${hash.digest("hex")}`;
12704
+ }
12705
+ /**
12706
+ * Normalize a source key for consistent lockfile lookups.
12707
+ * Strips URL prefixes, provider prefixes, trailing slashes, .git suffix, and lowercases.
12708
+ */
12709
+ function normalizeSourceKey(source) {
12710
+ let key = source;
12711
+ for (const prefix of [
12712
+ "https://www.github.com/",
12713
+ "https://github.com/",
12714
+ "http://www.github.com/",
12715
+ "http://github.com/",
12716
+ "https://www.gitlab.com/",
12717
+ "https://gitlab.com/",
12718
+ "http://www.gitlab.com/",
12719
+ "http://gitlab.com/"
12720
+ ]) if (key.toLowerCase().startsWith(prefix)) {
12721
+ key = key.substring(prefix.length);
12722
+ break;
12723
+ }
12724
+ for (const provider of ["github:", "gitlab:"]) if (key.startsWith(provider)) {
12725
+ key = key.substring(provider.length);
12726
+ break;
12727
+ }
12728
+ key = key.replace(/\/+$/, "");
12729
+ key = key.replace(/\.git$/, "");
12730
+ key = key.toLowerCase();
12731
+ return key;
12732
+ }
12733
+ /**
12734
+ * Separates the repository part of a lock key from the qualifier that tells
12735
+ * apart several declared entries of the same repository.
12736
+ */
12737
+ const LOCK_KEY_QUALIFIER_SEPARATOR = "#";
12738
+ /**
12739
+ * Normalize a lock key for comparison. The repository part is normalized with
12740
+ * {@link normalizeSourceKey}; a qualifier (see {@link resolveSourceLockKeys})
12741
+ * is kept verbatim, since paths and refs are case-sensitive. A key without a
12742
+ * qualifier normalizes exactly as before qualifiers existed.
12743
+ */
12744
+ function normalizeLockKey(key) {
12745
+ const separatorIndex = key.indexOf(LOCK_KEY_QUALIFIER_SEPARATOR);
12746
+ if (separatorIndex === -1) return normalizeSourceKey(key);
12747
+ return normalizeSourceKey(key.slice(0, separatorIndex)) + key.slice(separatorIndex);
12748
+ }
12749
+ /** The normalized repository part of a lock key, without its qualifier. */
12750
+ function getLockKeyRepository(key) {
12751
+ const separatorIndex = key.indexOf(LOCK_KEY_QUALIFIER_SEPARATOR);
12752
+ return normalizeSourceKey(separatorIndex === -1 ? key : key.slice(0, separatorIndex));
12753
+ }
12754
+ function encodeLockKeyQualifierValue(value) {
12755
+ return encodeURIComponent(value).replace(/%2F/gi, "/");
12756
+ }
12757
+ function normalizeLockKeyDirPath(dirPath) {
12758
+ return normalizePosixDirPath(dirPath);
12759
+ }
12760
+ /**
12761
+ * The location fields of a declared entry that tell it apart from other
12762
+ * entries of the same repository, as a lock key qualifier (empty when the
12763
+ * entry declares none of them).
12764
+ */
12765
+ function buildLockKeyQualifier(sourceEntry) {
12766
+ const parts = [];
12767
+ if (sourceEntry.path !== void 0) parts.push(`path=${encodeLockKeyQualifierValue(normalizeLockKeyDirPath(sourceEntry.path))}`);
12768
+ for (const field of [
12769
+ "rulesPath",
12770
+ "commandsPath",
12771
+ "subagentsPath"
12772
+ ]) {
12773
+ const dirPath = sourceEntry[field];
12774
+ if (dirPath !== void 0) parts.push(`${field}=${encodeLockKeyQualifierValue(normalizeLockKeyDirPath(dirPath))}`);
12775
+ }
12776
+ if (sourceEntry.ref !== void 0) parts.push(`ref=${encodeLockKeyQualifierValue(sourceEntry.ref)}`);
12777
+ return parts.join("&");
12778
+ }
12779
+ /**
12780
+ * The key each declared source's lock entry is stored under, index-aligned
12781
+ * with `sources`.
12782
+ *
12783
+ * A repository declared once keeps the bare {@link normalizeSourceKey} key,
12784
+ * so lockfiles written before multiple entries per repository were supported
12785
+ * stay valid unchanged. Only when several git/GitHub entries normalize to the
12786
+ * same repository does each of them get a qualified key
12787
+ * (`owner/repo#path=plugins/team-a/skills&ref=main`) built from its `path`,
12788
+ * `rulesPath`, `commandsPath`, `subagentsPath` and `ref`, so each entry keeps its own lock entry, its own
12789
+ * curated-artifact cleanup and its own `--frozen` check. An entry declaring
12790
+ * none of those fields keeps the bare key, and entries declaring the same
12791
+ * location are told apart by their order (`entry=2`, `entry=3`, ...).
12792
+ *
12793
+ * npm-transport sources are locked in a separate lockfile by package name;
12794
+ * their key here is unused and left bare.
12795
+ */
12796
+ function resolveSourceLockKeys(sources) {
12797
+ const bareKeys = sources.map((sourceEntry) => normalizeSourceKey(sourceEntry.source));
12798
+ const repositoryCounts = /* @__PURE__ */ new Map();
12799
+ sources.forEach((sourceEntry, index) => {
12800
+ if (getSourceTransport(sourceEntry) === "npm") return;
12801
+ const bareKey = bareKeys[index] ?? "";
12802
+ repositoryCounts.set(bareKey, (repositoryCounts.get(bareKey) ?? 0) + 1);
12803
+ });
12804
+ const qualifierCounts = /* @__PURE__ */ new Map();
12805
+ return sources.map((sourceEntry, index) => {
12806
+ const bareKey = bareKeys[index] ?? "";
12807
+ if (getSourceTransport(sourceEntry) === "npm" || (repositoryCounts.get(bareKey) ?? 0) < 2) return bareKey;
12808
+ const qualifier = buildLockKeyQualifier(sourceEntry);
12809
+ const base = qualifier === "" ? bareKey : `${bareKey}${LOCK_KEY_QUALIFIER_SEPARATOR}${qualifier}`;
12810
+ const occurrence = (qualifierCounts.get(base) ?? 0) + 1;
12811
+ qualifierCounts.set(base, occurrence);
12812
+ if (occurrence === 1) return base;
12813
+ return `${base}${qualifier === "" ? LOCK_KEY_QUALIFIER_SEPARATOR : "&"}entry=${occurrence}`;
12814
+ });
12815
+ }
12816
+ /**
12817
+ * Move a lock entry to another key, keeping its position-independent content
12818
+ * unchanged (immutable — returns a fresh lock object).
12819
+ */
12820
+ function renameLockedSource(params) {
12821
+ const { lock, fromKey, toKey } = params;
12822
+ const entry = getLockedSource(lock, fromKey);
12823
+ if (entry === void 0) return lock;
12824
+ const normalizedFrom = normalizeLockKey(fromKey);
12825
+ const remaining = {};
12826
+ for (const [key, value] of Object.entries(lock.sources)) if (normalizeLockKey(key) !== normalizedFrom) remaining[key] = value;
12827
+ return setLockedSource({
12828
+ lockfileVersion: lock.lockfileVersion,
12829
+ sources: remaining
12830
+ }, toKey, entry);
12831
+ }
12832
+ /**
12833
+ * Get the locked entry for a lock key (see {@link resolveSourceLockKeys}),
12834
+ * if it exists.
12835
+ */
12836
+ function getLockedSource(lock, lockKey) {
12837
+ const normalized = normalizeLockKey(lockKey);
12838
+ for (const [key, value] of Object.entries(lock.sources)) if (normalizeLockKey(key) === normalized) return value;
12839
+ }
12840
+ /**
12841
+ * Set (or update) a locked entry for a lock key.
12842
+ */
12843
+ function setLockedSource(lock, lockKey, entry) {
12844
+ const normalized = normalizeLockKey(lockKey);
12845
+ const filteredSources = {};
12846
+ for (const [key, value] of Object.entries(lock.sources)) if (normalizeLockKey(key) !== normalized) filteredSources[key] = value;
12847
+ return {
12848
+ lockfileVersion: lock.lockfileVersion,
12849
+ sources: {
12850
+ ...filteredSources,
12851
+ [normalized]: entry
12852
+ }
12853
+ };
12854
+ }
12855
+ /**
12856
+ * Get the skill names from a locked source entry.
12857
+ */
12858
+ function getLockedSkillNames(entry) {
12859
+ return Object.keys(entry.skills);
12860
+ }
12861
+ /**
12862
+ * The features a source installs as one Markdown file per item, each locked
12863
+ * with the same four fields (`rules` / `ruleSelection` / `rulesPath` /
12864
+ * `resolvedRuleNames`, and the command and subagent counterparts).
12865
+ */
12866
+ const SOURCE_FILE_FEATURES = [
12867
+ "rules",
12868
+ "commands",
12869
+ "subagents"
12870
+ ];
12871
+ /** Build a value for each per-file feature. */
12872
+ function mapFileFeatures(map) {
12873
+ return {
12874
+ rules: map("rules"),
12875
+ commands: map("commands"),
12876
+ subagents: map("subagents")
12877
+ };
12878
+ }
12879
+ /** Read one per-file feature's lock fields from a lock entry. */
12880
+ function getLockedFileFeatureState(entry, feature) {
12881
+ switch (feature) {
12882
+ case "rules": return {
12883
+ items: entry.rules,
12884
+ selection: entry.ruleSelection,
12885
+ path: entry.rulesPath,
12886
+ resolvedNames: entry.resolvedRuleNames
12887
+ };
12888
+ case "commands": return {
12889
+ items: entry.commands,
12890
+ selection: entry.commandSelection,
12891
+ path: entry.commandsPath,
12892
+ resolvedNames: entry.resolvedCommandNames
12893
+ };
12894
+ case "subagents": return {
12895
+ items: entry.subagents,
12896
+ selection: entry.subagentSelection,
12897
+ path: entry.subagentsPath,
12898
+ resolvedNames: entry.resolvedSubagentNames
12899
+ };
12900
+ }
12901
+ }
12902
+ /** The lock fields that record one per-file feature's state. */
12903
+ function toFileFeatureLockFields(feature, state) {
12904
+ switch (feature) {
12905
+ case "rules": return {
12906
+ rules: state.items,
12907
+ ruleSelection: state.selection,
12908
+ rulesPath: state.path,
12909
+ resolvedRuleNames: state.resolvedNames
12910
+ };
12911
+ case "commands": return {
12912
+ commands: state.items,
12913
+ commandSelection: state.selection,
12914
+ commandsPath: state.path,
12915
+ resolvedCommandNames: state.resolvedNames
12916
+ };
12917
+ case "subagents": return {
12918
+ subagents: state.items,
12919
+ subagentSelection: state.selection,
12920
+ subagentsPath: state.path,
12921
+ resolvedSubagentNames: state.resolvedNames
12922
+ };
12923
+ }
12924
+ }
12925
+ /** The item names one per-file feature of a lock entry locks. */
12926
+ function getLockedFileNames(entry, feature) {
12927
+ return Object.keys(getLockedFileFeatureState(entry, feature).items ?? {});
12928
+ }
12929
+ // src/lib/sources-artifacts.ts
12930
+ const FILE_FEATURE_SPECS = {
12931
+ rules: {
12932
+ noun: "rule",
12933
+ pathField: "rulesPath",
12934
+ defaultPath: "rules",
12935
+ curatedRelativeDirPath: RULESYNC_CURATED_RULES_RELATIVE_DIR_PATH
12936
+ },
12937
+ commands: {
12938
+ noun: "command",
12939
+ pathField: "commandsPath",
12940
+ defaultPath: "commands",
12941
+ curatedRelativeDirPath: RULESYNC_CURATED_COMMANDS_RELATIVE_DIR_PATH
12942
+ },
12943
+ subagents: {
12944
+ noun: "subagent",
12945
+ pathField: "subagentsPath",
12946
+ defaultPath: "subagents",
12947
+ curatedRelativeDirPath: RULESYNC_CURATED_SUBAGENTS_RELATIVE_DIR_PATH
12948
+ }
12949
+ };
12950
+ /** The singular noun of a per-file feature, for messages (`rule`, `command`, `subagent`). */
12951
+ function getFileFeatureNoun(feature) {
12952
+ return FILE_FEATURE_SPECS[feature].noun;
12953
+ }
12954
+ /** Where a per-file feature's fetched copies live, relative to the project root. */
12955
+ function getCuratedFileFeatureRelativeDirPath(feature) {
12956
+ return FILE_FEATURE_SPECS[feature].curatedRelativeDirPath;
12957
+ }
12958
+ /** Every selection field a source entry may declare. */
12959
+ const SOURCE_SELECTION_FIELDS = ["skills", ...SOURCE_FILE_FEATURES];
12960
+ function getSourceFilters(sourceEntry) {
12961
+ const hasExplicitFeature = SOURCE_SELECTION_FIELDS.some((field) => sourceEntry[field] !== void 0);
12962
+ return {
12963
+ skills: sourceEntry.skills ?? (hasExplicitFeature ? void 0 : ["*"]),
12964
+ rules: sourceEntry.rules,
12965
+ commands: sourceEntry.commands,
12966
+ subagents: sourceEntry.subagents
12967
+ };
12968
+ }
12969
+ /** The selection fields a source entry declares as an empty list. */
12970
+ function getEmptySelectionFields(sourceEntry) {
12971
+ return SOURCE_SELECTION_FIELDS.filter((field) => sourceEntry[field]?.length === 0);
12972
+ }
12973
+ function hasEmptySelection(sourceEntry) {
12974
+ return getEmptySelectionFields(sourceEntry).length > 0;
12975
+ }
12976
+ /**
12977
+ * Whether a lock entry was written for the ref the manifest declares now. A
12978
+ * declared ref that differs from the locked `requestedRef` is resolved afresh
12979
+ * (and fails `--frozen`), so editing the ref in the manifest cannot keep
12980
+ * installing the commit resolved for the old one.
12981
+ *
12982
+ * An entry that records no `requestedRef` (a migrated legacy lock, or a
12983
+ * hand-written one) still matches: it says nothing that contradicts the
12984
+ * declared ref, and refusing it would gain nothing, since whoever can edit the
12985
+ * lock can also write any `requestedRef`. The declared ref is recorded on it
12986
+ * the next time the entry is written.
12987
+ *
12988
+ * A source that declares no ref also matches: its locked `requestedRef` is the
12989
+ * default branch it resolved to, which cannot be told apart from a ref that
12990
+ * was dropped from the manifest without asking the remote.
12991
+ */
12992
+ function lockedRefMatchesDeclared(params) {
12993
+ const { locked, declaredRef } = params;
12994
+ return declaredRef === void 0 || locked.requestedRef === void 0 || locked.requestedRef === declaredRef;
12995
+ }
12996
+ /**
12997
+ * Check that every locked skill is on disk in the curated directory with the
12998
+ * content the lockfile records: its files hash to the locked integrity, so a
12999
+ * skill edited, extended or trimmed in place is fetched again, as a rule is.
13000
+ *
13001
+ * The locked hash keys each file by the path the transport reported. The
13002
+ * GitHub API and npm report POSIX paths, while the git transport reports
13003
+ * platform paths, so on Windows both spellings are accepted.
13004
+ *
13005
+ * Only presence is checked for a skill whose content this entry cannot vouch
13006
+ * for: one an earlier source already installed under the same name (the
13007
+ * curated directory then holds that source's copy, which wins), and one locked
13008
+ * with an empty integrity by the migration from the legacy lockfile format.
13009
+ */
13010
+ async function checkLockedSkillsAreValid(params) {
13011
+ const { curatedDir, skills, presenceOnlySkillNames = /* @__PURE__ */ new Set() } = params;
13012
+ for (const [name, entry] of Object.entries(skills)) {
13013
+ const skillDir = (0, node_path.join)(curatedDir, name);
13014
+ if (!await directoryExists(skillDir)) return false;
13015
+ if (entry.integrity === "" || presenceOnlySkillNames.has(name)) continue;
13016
+ const files = await Promise.all((await listFilePathsRecursively(skillDir, { includeHidden: true })).map(async (relativePath) => ({
13017
+ relativePath,
13018
+ content: await readFileContent((0, node_path.join)(skillDir, relativePath))
13019
+ })));
13020
+ if (!(node_path.sep === "/" ? [(relativePath) => relativePath] : [toPosixPath, (relativePath) => relativePath]).some((spell) => computeSkillIntegrity(files.map((file) => ({
13021
+ path: spell(file.relativePath),
13022
+ content: file.content
13023
+ }))) === entry.integrity)) return false;
13024
+ }
13025
+ return true;
13026
+ }
13027
+ /**
13028
+ * Check that every item one per-file feature of a lock entry locks is on disk
13029
+ * in its curated directory with the locked content. A locked name that is not
13030
+ * a valid file name (a hand-edited lockfile) never counts as installed, so it
13031
+ * is fetched again rather than read from outside the curated directory.
13032
+ */
13033
+ async function checkLockedFilesAreValid(params) {
13034
+ const { items } = getLockedFileFeatureState(params.locked, params.feature);
13035
+ for (const [name, entry] of Object.entries(items ?? {})) {
13036
+ if (!isValidRuleName(name)) return false;
13037
+ const filePath = (0, node_path.join)(params.curatedDir, `${name}.md`);
13038
+ if (!await fileExists(filePath)) return false;
13039
+ if (computeRuleIntegrity(await readFileContent(filePath)) !== entry.integrity) return false;
13040
+ }
13041
+ return true;
13042
+ }
13043
+ async function canReuseLockedFiles(params) {
13044
+ const { feature, locked, sourceEntry, lockedNames, localNames, alreadyFetchedNames, curatedDir } = params;
13045
+ if (!lockedFileConfigMatches({
13046
+ feature,
13047
+ locked,
13048
+ sourceEntry
13049
+ })) return false;
13050
+ const { resolvedNames } = getLockedFileFeatureState(locked, feature);
13051
+ if (resolvedNames === void 0) return false;
13052
+ const availableNames = /* @__PURE__ */ new Set([
13053
+ ...lockedNames,
13054
+ ...localNames,
13055
+ ...alreadyFetchedNames
13056
+ ]);
13057
+ if (resolvedNames.some((name) => !availableNames.has(name))) return false;
13058
+ if (lockedNames.some((name) => localNames.has(name) || alreadyFetchedNames.has(name))) return false;
13059
+ return checkLockedFilesAreValid({
13060
+ feature,
13061
+ curatedDir,
13062
+ locked
13063
+ });
13064
+ }
13065
+ /**
13066
+ * Remove previously curated skill directories for a source before re-fetching.
13067
+ * Validates that each path resolves within the curated directory to prevent traversal.
13068
+ */
13069
+ async function cleanPreviousCuratedSkills(params) {
13070
+ const { curatedDir, lockedSkillNames, protectedSkillNames = /* @__PURE__ */ new Set(), logger } = params;
13071
+ const resolvedCuratedDir = (0, node_path.resolve)(curatedDir);
13072
+ for (const prevSkill of lockedSkillNames) {
13073
+ if (protectedSkillNames.has(prevSkill)) continue;
13074
+ const prevDir = (0, node_path.join)(curatedDir, prevSkill);
13075
+ if (!(0, node_path.resolve)(prevDir).startsWith(resolvedCuratedDir + node_path.sep)) {
13076
+ logger.warn(`Skipping removal of ${quoteForLog(prevSkill)}: resolved path is outside the curated directory.`);
13077
+ continue;
13078
+ }
13079
+ if (await directoryExists(prevDir)) await removeDirectoryStrict(prevDir);
13080
+ }
13081
+ }
13082
+ /**
13083
+ * Whether `<name>.md` resolves to a file directly inside `curatedDir`. Locked
13084
+ * names come from the lockfile, which can be edited by hand, so they are
13085
+ * checked before anything is read, removed or written under them.
13086
+ */
13087
+ function isCuratedFileInside(params) {
13088
+ const resolvedCuratedDir = (0, node_path.resolve)(params.curatedDir);
13089
+ return (0, node_path.resolve)((0, node_path.join)(params.curatedDir, `${params.name}.md`)).startsWith(resolvedCuratedDir + node_path.sep);
13090
+ }
13091
+ /**
13092
+ * Remove a source's previously curated files (rules, commands or subagents)
13093
+ * before re-fetching. Validates that each path resolves within the curated
13094
+ * directory to prevent traversal.
13095
+ */
13096
+ async function cleanPreviousCuratedFiles(params) {
13097
+ const { curatedDir, lockedNames, protectedNames, logger } = params;
13098
+ for (const prevName of lockedNames) {
13099
+ if (protectedNames.has(prevName)) continue;
13100
+ if (!isCuratedFileInside({
13101
+ curatedDir,
13102
+ name: prevName
13103
+ })) {
13104
+ logger.warn(`Skipping removal of ${quoteForLog(prevName)}: resolved path is outside the curated directory.`);
13105
+ continue;
13106
+ }
13107
+ const prevFile = (0, node_path.join)(curatedDir, `${prevName}.md`);
13108
+ if (await fileExists(prevFile)) await removeFileStrict(prevFile);
13109
+ }
13110
+ }
13111
+ async function replaceCuratedFiles(params) {
13112
+ const { feature, files, curatedDir, locked, lockedNames, resolvedRef, sourceKey, localNames, alreadyFetchedNames, compareLockedIntegrity, frozen, logger } = params;
13113
+ const protectedNames = alreadyFetchedNames;
13114
+ const installableFiles = files.filter((file) => !shouldSkipFile({
13115
+ feature,
13116
+ name: file.name,
13117
+ sourceKey,
13118
+ localNames,
13119
+ alreadyFetchedNames,
13120
+ logger
13121
+ }));
13122
+ const previousContents = /* @__PURE__ */ new Map();
13123
+ for (const name of lockedNames) {
13124
+ if (protectedNames.has(name) || !isCuratedFileInside({
13125
+ curatedDir,
13126
+ name
13127
+ })) continue;
13128
+ const path = (0, node_path.join)(curatedDir, `${name}.md`);
13129
+ if (await fileExists(path)) previousContents.set(name, await readFileContent(path));
13130
+ }
13131
+ try {
13132
+ await cleanPreviousCuratedFiles({
13133
+ curatedDir,
13134
+ lockedNames,
13135
+ protectedNames,
13136
+ logger
13137
+ });
13138
+ const fetchedFiles = {};
13139
+ for (const file of installableFiles) fetchedFiles[file.name] = await writeFeatureFileAndComputeIntegrity({
13140
+ feature,
13141
+ file,
13142
+ curatedDir,
13143
+ locked,
13144
+ resolvedRef,
13145
+ sourceKey,
13146
+ compareLockedIntegrity,
13147
+ frozen,
13148
+ logger
13149
+ });
13150
+ return fetchedFiles;
13151
+ } catch (error) {
13152
+ for (const file of installableFiles) await removeFileStrict((0, node_path.join)(curatedDir, `${file.name}.md`));
13153
+ for (const [name, content] of previousContents) await writeFileContent((0, node_path.join)(curatedDir, `${name}.md`), content);
13154
+ throw error;
13155
+ }
13156
+ }
13157
+ /**
13158
+ * Check whether a skill should be skipped during fetching.
13159
+ * Returns true (with appropriate logging) if the skill should be skipped.
13160
+ */
13161
+ function shouldSkipSkill(params) {
13162
+ const { skillName, sourceKey, localSkillNames, alreadyFetchedSkillNames, logger } = params;
13163
+ if (skillName.includes("..") || skillName.includes("/") || skillName.includes("\\")) {
13164
+ logger.warn(`Skipping skill with invalid name ${quoteForLog(skillName)} from ${sourceKey}: contains path traversal characters.`);
13165
+ return true;
13166
+ }
13167
+ const unsafe = describeUnsafeRemoteName(skillName);
13168
+ if (unsafe !== void 0) {
13169
+ logger.warn(`Skipping skill with unsafe name ${unsafe} from ${sourceKey}.`);
13170
+ return true;
13171
+ }
13172
+ if (localSkillNames.has(skillName)) {
13173
+ logger.debug(`Skipping remote skill ${quoteForLog(skillName)} from ${sourceKey}: local skill takes precedence.`);
13174
+ return true;
13175
+ }
13176
+ if (alreadyFetchedSkillNames.has(skillName)) {
13177
+ logger.warn(`Skipping duplicate skill ${quoteForLog(skillName)} from ${sourceKey}: already fetched from another source.`);
13178
+ return true;
13179
+ }
13180
+ return false;
13181
+ }
13182
+ /**
13183
+ * Check whether a remote rule, command or subagent should be skipped: its
13184
+ * name could escape the curated directory or is unsafe to print, a local file
13185
+ * of the same name takes precedence, or an earlier source already took it.
13186
+ */
13187
+ function shouldSkipFile(params) {
13188
+ const { feature, name, sourceKey, localNames, alreadyFetchedNames, logger } = params;
13189
+ const noun = getFileFeatureNoun(feature);
13190
+ if (!isValidRuleName(name)) {
13191
+ logger.warn(`Skipping ${noun} with invalid name ${quoteForLog(name)} from ${sourceKey}.`);
13192
+ return true;
13193
+ }
13194
+ const unsafe = describeUnsafeRemoteName(name);
13195
+ if (unsafe !== void 0) {
13196
+ logger.warn(`Skipping ${noun} with unsafe name ${unsafe} from ${sourceKey}.`);
13197
+ return true;
13198
+ }
13199
+ if (localNames.has(name)) {
13200
+ logger.debug(`Skipping remote ${noun} ${quoteForLog(name)} from ${sourceKey}: local ${noun} takes precedence.`);
13201
+ return true;
13202
+ }
13203
+ if (alreadyFetchedNames.has(name)) {
13204
+ logger.warn(`Skipping duplicate ${noun} ${quoteForLog(name)} from ${sourceKey}: already fetched from another source.`);
13205
+ return true;
13206
+ }
13207
+ return false;
13208
+ }
13209
+ /**
13210
+ * Why a remote skill or rule name must not be installed, already quoted for a
13211
+ * log line, or `undefined` when it is safe. It applies the same gate as
13212
+ * `rulesync fetch`: a name hiding control or deceptive zero-width characters
13213
+ * could rewrite the terminal when printed, or pass for another name, and a
13214
+ * name Windows folds lands on a different entry than it reads as.
13215
+ */
13216
+ function describeUnsafeRemoteName(name) {
13217
+ const verdict = classifyRemoteName(name);
13218
+ if (verdict.kind === "safe") return;
13219
+ return verdict.reason === "hidden" ? `${quoteForLog(verdict.display)} (it contains hidden or control characters)` : `${quoteForLog(name)} (Windows resolves it to a different name)`;
13220
+ }
13221
+ function isValidRuleName(ruleName) {
13222
+ return !(ruleName.includes("..") || ruleName.includes("/") || ruleName.includes("\\") || ruleName.length === 0 || [
13223
+ "__proto__",
13224
+ "constructor",
13225
+ "prototype"
13226
+ ].includes(ruleName));
13227
+ }
13228
+ /**
13229
+ * A fetched artifact whose content no longer matches the integrity recorded
13230
+ * for the same resolved ref. Under `--frozen` that is fatal — the lockfile is
13231
+ * the contract, and the gh transport refuses the same case — otherwise it is
13232
+ * reported and the new content is taken.
13233
+ */
13234
+ function reportIntegrityMismatch(params) {
13235
+ const { message, frozen, logger } = params;
13236
+ if (frozen) throw new Error(`${message} Refusing to install it under --frozen.`);
13237
+ logger.warn(message);
13238
+ }
13239
+ async function writeFeatureFileAndComputeIntegrity(params) {
13240
+ const { feature, file, curatedDir, locked, resolvedRef, sourceKey, compareLockedIntegrity = true, frozen, logger } = params;
13241
+ const relativePath = `${file.name}.md`;
13242
+ checkPathTraversal({
13243
+ relativePath,
13244
+ intendedRootDir: curatedDir
13245
+ });
13246
+ const integrity = computeRuleIntegrity(file.content);
13247
+ const lockedEntry = locked ? getLockedFileFeatureState(locked, feature).items?.[file.name] : void 0;
13248
+ if (compareLockedIntegrity && lockedEntry?.integrity && lockedEntry.integrity !== integrity && resolvedRef === locked?.resolvedRef) reportIntegrityMismatch({
13249
+ message: `Integrity mismatch for ${getFileFeatureNoun(feature)} ${quoteForLog(file.name)} from ${sourceKey}: expected "${lockedEntry.integrity}", got "${integrity}". Content may have been tampered with.`,
13250
+ frozen,
13251
+ logger
13252
+ });
13253
+ await writeFileContent((0, node_path.join)(curatedDir, relativePath), file.content);
13254
+ return { integrity };
13255
+ }
13256
+ /**
13257
+ * Write skill files to disk, compute integrity, and check against the lockfile.
13258
+ * Returns the computed LockedSkill entry.
13259
+ */
13260
+ async function writeSkillAndComputeIntegrity(params) {
13261
+ const { skillName, files, curatedDir, locked, resolvedSha, sourceKey, frozen, logger } = params;
13262
+ for (const file of files) checkPathTraversal({
13263
+ relativePath: file.relativePath,
13264
+ intendedRootDir: (0, node_path.join)(curatedDir, skillName)
13265
+ });
13266
+ const integrity = computeSkillIntegrity(files.map((file) => ({
13267
+ path: file.relativePath,
13268
+ content: file.content
13269
+ })));
13270
+ const lockedSkillEntry = locked?.skills[skillName];
13271
+ if (lockedSkillEntry?.integrity && lockedSkillEntry.integrity !== integrity && resolvedSha === locked?.resolvedRef) reportIntegrityMismatch({
13272
+ message: `Integrity mismatch for skill ${quoteForLog(skillName)} from ${sourceKey}: expected "${lockedSkillEntry.integrity}", got "${integrity}". Content may have been tampered with.`,
13273
+ frozen,
13274
+ logger
13275
+ });
13276
+ for (const file of files) {
13277
+ const filePath = (0, node_path.join)(curatedDir, skillName, file.relativePath);
13278
+ await writeFileContent(filePath, file.content);
13279
+ if (file.executable === true) await applyFileMode(filePath, 493);
13280
+ }
13281
+ return { integrity };
13282
+ }
13283
+ /**
13284
+ * Merge back locked skills that still exist in the remote but were skipped
13285
+ * during fetching (due to local precedence, already-fetched, etc.). Skills no
13286
+ * longer present in the remote (e.g. renamed or deleted upstream) are
13287
+ * intentionally dropped. Shared by the git/github and npm lock updates.
13288
+ */
13289
+ function mergeFetchedWithLockedSkills(params) {
13290
+ const { fetchedSkills, lockedSkills, remoteSkillNames } = params;
13291
+ const remoteSet = new Set(remoteSkillNames);
13292
+ const mergedSkills = { ...fetchedSkills };
13293
+ if (lockedSkills) {
13294
+ for (const [skillName, skillEntry] of Object.entries(lockedSkills)) if (!(skillName in mergedSkills) && remoteSet.has(skillName)) mergedSkills[skillName] = skillEntry;
13295
+ }
13296
+ return mergedSkills;
13297
+ }
13298
+ function assertMatchingSkillsFound({ skillNames, source }) {
13299
+ if (skillNames.length === 0) throw new Error(`No matching skills found in ${source}.`);
13300
+ }
13301
+ /**
13302
+ * Merge newly fetched skills with existing locked skills and update the lockfile.
13303
+ */
13304
+ function buildLockUpdate(params) {
13305
+ const { lock, lockKey, sourceKey, fetchedSkills, locked, requestedRef, resolvedSha, skillSelection, skillsPath, remoteSkillNames, logger } = params;
13306
+ const fetchedNames = Object.keys(fetchedSkills);
13307
+ const mergedSkills = mergeFetchedWithLockedSkills({
13308
+ fetchedSkills,
13309
+ lockedSkills: locked?.skills,
13310
+ remoteSkillNames
13311
+ });
13312
+ const updatedLock = setLockedSource(lock, lockKey, {
13313
+ requestedRef,
13314
+ resolvedRef: resolvedSha,
13315
+ resolvedAt: (/* @__PURE__ */ new Date()).toISOString(),
13316
+ skills: mergedSkills,
13317
+ skillSelection,
13318
+ skillsPath,
13319
+ rules: locked?.rules ?? {},
13320
+ ruleSelection: locked?.ruleSelection,
13321
+ rulesPath: locked?.rulesPath,
13322
+ resolvedRuleNames: locked?.resolvedRuleNames,
13323
+ ...pickFileFeatureLockFields({
13324
+ locked,
13325
+ features: ["commands", "subagents"]
13326
+ })
13327
+ });
13328
+ logger.info(`Fetched ${fetchedNames.length} skill(s) from ${sourceKey}: ${fetchedNames.map(stripControlCharacters).join(", ") || "(none)"}`);
13329
+ return {
13330
+ updatedLock,
13331
+ fetchedNames
13332
+ };
13333
+ }
13334
+ /**
13335
+ * The lock fields of the given per-file features, copied from a lock entry
13336
+ * (empty when there is none), so that writing one feature's fields keeps the
13337
+ * others as they were.
13338
+ */
13339
+ function pickFileFeatureLockFields(params) {
13340
+ const { locked, features } = params;
13341
+ if (locked === void 0) return {};
13342
+ return Object.assign({}, ...features.map((feature) => toFileFeatureLockFields(feature, getLockedFileFeatureState(locked, feature))));
13343
+ }
13344
+ function buildFileLockUpdate(params) {
13345
+ const { feature, lock, lockKey, sourceKey, fetchedFiles, locked, requestedRef, resolvedRef, selection, path, resolvedNames, logger } = params;
13346
+ const fetchedNames = Object.keys(fetchedFiles);
13347
+ const updatedLock = setLockedSource(lock, lockKey, {
13348
+ requestedRef,
13349
+ resolvedRef,
13350
+ resolvedAt: (/* @__PURE__ */ new Date()).toISOString(),
13351
+ skills: locked?.skills ?? {},
13352
+ skillSelection: locked?.skillSelection,
13353
+ skillsPath: locked?.skillsPath,
13354
+ ...pickFileFeatureLockFields({
13355
+ locked,
13356
+ features: SOURCE_FILE_FEATURES
13357
+ }),
13358
+ ...toFileFeatureLockFields(feature, {
13359
+ items: fetchedFiles,
13360
+ selection,
13361
+ path,
13362
+ resolvedNames
13363
+ })
13364
+ });
13365
+ logger.info(`Fetched ${fetchedNames.length} ${getFileFeatureNoun(feature)}(s) from ${sourceKey}: ${fetchedNames.map(stripControlCharacters).join(", ") || "(none)"}`);
13366
+ return {
13367
+ updatedLock,
13368
+ fetchedNames
13369
+ };
13370
+ }
13371
+ function getFirstPathSeparatorIndex(path) {
13372
+ const slashIndex = path.indexOf("/");
13373
+ const backslashIndex = path.indexOf("\\");
13374
+ if (slashIndex === -1) return backslashIndex;
13375
+ if (backslashIndex === -1) return slashIndex;
13376
+ return Math.min(slashIndex, backslashIndex);
13377
+ }
13378
+ /**
13379
+ * Decide whether a repository's root-level files should be installed as the
13380
+ * single requested skill (the "root fallback").
13381
+ *
13382
+ * A root fallback fires only when a single, non-wildcard skill was requested,
13383
+ * that skill's own directory is absent, and the repository root actually carries
13384
+ * a `SKILL.md`. Both the git transport (`groupRemoteFilesBySkillRoot`) and the
13385
+ * GitHub transport (`discoverGithubSkillDirs`) gate on these same conditions, so
13386
+ * the decision lives here to keep the two paths from drifting.
13387
+ */
13388
+ function shouldUseRootFallback(params) {
13389
+ const { skillFilter, isWildcard, hasRootSkillFile, hasRequestedSkillDir } = params;
13390
+ const [singleSkillName] = skillFilter;
13391
+ return !isWildcard && skillFilter.length === 1 && singleSkillName !== void 0 && hasRootSkillFile && !hasRequestedSkillDir;
13392
+ }
13393
+ function groupRemoteFilesBySkillRoot(params) {
13394
+ const { remoteFiles, skillFilter, isWildcard } = params;
13395
+ const grouped = /* @__PURE__ */ new Map();
13396
+ const rootLevelFiles = [];
13397
+ for (const file of remoteFiles) {
13398
+ const separatorIndex = getFirstPathSeparatorIndex(file.relativePath);
13399
+ if (separatorIndex === -1) {
13400
+ rootLevelFiles.push(file);
13401
+ continue;
13402
+ }
13403
+ const skillName = file.relativePath.substring(0, separatorIndex);
13404
+ if (skillName.length === 0) continue;
13405
+ const innerPath = file.relativePath.substring(separatorIndex + 1);
13406
+ const groupedFiles = grouped.get(skillName) ?? [];
13407
+ groupedFiles.push({
13408
+ ...file,
13409
+ relativePath: innerPath
13410
+ });
13411
+ grouped.set(skillName, groupedFiles);
13412
+ }
13413
+ const [singleSkillName] = skillFilter;
13414
+ const hasRootSkillFile = rootLevelFiles.some((file) => file.relativePath === SKILL_FILE_NAME);
13415
+ if (singleSkillName !== void 0 && shouldUseRootFallback({
13416
+ skillFilter,
13417
+ isWildcard,
13418
+ hasRootSkillFile,
13419
+ hasRequestedSkillDir: grouped.has(singleSkillName)
13420
+ })) grouped.set(singleSkillName, rootLevelFiles);
13421
+ return grouped;
13422
+ }
13423
+ function normalizeRuleFilterName(name) {
13424
+ return name.replace(/\.md$/i, "");
13425
+ }
13426
+ /** Whether a declared skill or rule selection is the `["*"]` wildcard. */
13427
+ function isWildcardSelection(selection) {
13428
+ return selection.length === 1 && selection[0] === "*";
13429
+ }
13430
+ /**
13431
+ * Pick the remote files a source entry declares for one per-file feature:
13432
+ * Markdown files whose normalized name is selected by the feature's field
13433
+ * (`sourceEntry.rules`, `.commands` or `.subagents`, or the wildcard) and is a
13434
+ * valid file name. Candidate order is preserved.
13435
+ */
13436
+ function selectDeclaredFiles(params) {
13437
+ const { feature, sourceEntry, candidates, getFileName } = params;
13438
+ const ruleFilter = (sourceEntry[feature] ?? []).map(normalizeRuleFilterName);
13439
+ const isWildcard = isWildcardSelection(ruleFilter);
13440
+ return candidates.filter((candidate) => getFileName(candidate).toLowerCase().endsWith(".md")).map((candidate) => ({
13441
+ candidate,
13442
+ name: normalizeRuleFilterName(getFileName(candidate))
13443
+ })).filter(({ name }) => (isWildcard || ruleFilter.includes(name)) && isValidRuleName(name));
13444
+ }
13445
+ function normalizeRuleSelection(rules) {
13446
+ return [...new Set(rules.map(normalizeRuleFilterName))].toSorted();
13447
+ }
13448
+ function normalizeSkillSelection(skills) {
13449
+ return [...new Set(skills)].toSorted();
13450
+ }
13451
+ /**
13452
+ * Whether the locked entry was written for the `skills` selection and skills
13453
+ * path the manifest declares now. Without it, widening the selection or moving
13454
+ * the path after an install is a silent no-op: the ref is unchanged and every
13455
+ * locked skill is on disk, so nothing is fetched and `--frozen` never notices.
13456
+ *
13457
+ * Lockfiles written before the path was recorded carry no `skillsPath`. Such
13458
+ * an entry is handled like one without `skillSelection`: fetched again at its
13459
+ * locked ref to record the path, and accepted as-is under `acceptLegacy`.
13460
+ *
13461
+ * Lockfiles written before the selection was recorded carry no
13462
+ * `skillSelection`. An install that may write the lockfile fetches such an
13463
+ * entry again at its locked ref so the selection gets recorded once; the checks that
13464
+ * cannot write it (`--frozen`, adding a source) pass `acceptLegacy` and fall
13465
+ * back to the locked skill names instead, so a wildcard is taken at face value
13466
+ * and an explicit list is covered only when every name it selects is locked.
13467
+ * An entry that locks no skills at all (a rules-only install) covers nothing:
13468
+ * it was never written for a skill selection.
13469
+ */
13470
+ function lockedSkillConfigMatches(params) {
13471
+ const skills = getSourceFilters(params.sourceEntry).skills;
13472
+ if (skills === void 0) return false;
13473
+ const lockedPath = params.locked.skillsPath;
13474
+ if (lockedPath === void 0 ? !params.acceptLegacy : lockedPath !== resolveSkillsPath(params.sourceEntry)) return false;
13475
+ const selection = normalizeSkillSelection(skills);
13476
+ const lockedSelection = params.locked.skillSelection;
13477
+ if (lockedSelection === void 0) {
13478
+ const lockedSkillNames = new Set(Object.keys(params.locked.skills));
13479
+ if (!params.acceptLegacy || lockedSkillNames.size === 0) return false;
13480
+ if (isWildcardSelection(selection)) return true;
13481
+ return selection.every((skillName) => lockedSkillNames.has(skillName));
13482
+ }
13483
+ return selection.length === lockedSelection.length && selection.every((skillName, index) => skillName === lockedSelection[index]);
13484
+ }
13485
+ /**
13486
+ * Skip the re-fetch when the SHA and the skill selection match the lockfile and
13487
+ * every curated skill the entry locks is still on disk, unmodified.
13488
+ */
13489
+ async function canReuseLockedSkills(params) {
13490
+ const { locked, resolvedSha, updateSources, frozen, sourceEntry, curatedDir, getAlreadyFetchedSkillNames } = params;
13491
+ return locked !== void 0 && resolvedSha === locked.resolvedRef && !updateSources && lockedSkillConfigMatches({
13492
+ locked,
13493
+ sourceEntry,
13494
+ acceptLegacy: frozen
13495
+ }) && await checkLockedSkillsAreValid({
13496
+ curatedDir,
13497
+ skills: locked.skills,
13498
+ presenceOnlySkillNames: await getAlreadyFetchedSkillNames()
13499
+ });
13500
+ }
13501
+ /**
13502
+ * The path the skills of a source are read from, as declared: the source's
13503
+ * `path`, else (for the github transport) the path embedded in the source
13504
+ * spec, else `skills`. Every transport fetches from this path, and the
13505
+ * lockfile records its normalized form ({@link resolveSkillsPath}), so the
13506
+ * fetch and the lock comparison cannot pick different paths.
13507
+ */
13508
+ function resolveSkillsSourcePath(sourceEntry) {
13509
+ const embeddedPath = getSourceTransport(sourceEntry) === "github" ? parseSource(sourceEntry.source).path : void 0;
13510
+ return sourceEntry.path ?? embeddedPath ?? "skills";
13511
+ }
13512
+ /** The skills path of a source in the form the lockfile records and compares. */
13513
+ function resolveSkillsPath(sourceEntry) {
13514
+ return normalizeSourceDirPath(resolveSkillsSourcePath(sourceEntry));
13515
+ }
13516
+ /**
13517
+ * The path one per-file feature of a source is read from, as declared: the
13518
+ * source's `rulesPath` / `commandsPath` / `subagentsPath`, else `rules` /
13519
+ * `commands` / `subagents`. The counterpart of {@link resolveSkillsSourcePath}.
13520
+ */
13521
+ function resolveFileFeatureSourcePath(sourceEntry, feature) {
13522
+ const spec = FILE_FEATURE_SPECS[feature];
13523
+ return sourceEntry[spec.pathField] ?? spec.defaultPath;
13524
+ }
13525
+ /** A per-file feature's path in the form the lockfile records and compares. */
13526
+ function resolveFileFeaturePath(sourceEntry, feature) {
13527
+ return normalizeSourceDirPath(resolveFileFeatureSourcePath(sourceEntry, feature));
13528
+ }
13529
+ /**
13530
+ * The form a source directory path is recorded in the lockfile and compared
13531
+ * in: posix separators, normalized, with no trailing slash.
13532
+ */
13533
+ function normalizeSourceDirPath(dirPath) {
13534
+ return normalizePosixDirPath(dirPath);
13535
+ }
13536
+ /**
13537
+ * Whether a lock entry was written for the selection and path one per-file
13538
+ * feature of the source declares now.
13539
+ */
13540
+ function lockedFileConfigMatches(params) {
13541
+ const { feature, locked, sourceEntry } = params;
13542
+ const declared = getSourceFilters(sourceEntry)[feature];
13543
+ const { selection: lockedSelection, path: lockedPath } = getLockedFileFeatureState(locked, feature);
13544
+ if (declared === void 0 || lockedSelection === void 0) return false;
13545
+ const selection = normalizeRuleSelection(declared);
13546
+ return selection.length === lockedSelection.length && selection.every((name, index) => name === lockedSelection[index]) && resolveFileFeaturePath(sourceEntry, feature) === lockedPath;
13547
+ }
13548
+ function assertMatchingFilesFound(params) {
13549
+ if (params.names.length === 0) throw new Error(`No matching ${params.feature} found in ${params.source}.`);
13550
+ }
13551
+ /**
13552
+ * "N skill(s) and M rule(s)", followed by the command and subagent counts when
13553
+ * any were installed, for the summary lines of `add` and `install`.
13554
+ */
13555
+ function formatInstalledCounts(result) {
13556
+ const extras = [result.fetchedCommandCount > 0 ? `${result.fetchedCommandCount} command(s)` : void 0, result.fetchedSubagentCount > 0 ? `${result.fetchedSubagentCount} subagent(s)` : void 0].filter((part) => part !== void 0);
13557
+ const parts = [
13558
+ `${result.fetchedSkillCount} skill(s)`,
13559
+ `${result.fetchedRuleCount} rule(s)`,
13560
+ ...extras
13561
+ ];
13562
+ return `${parts.slice(0, -1).join(", ")} and ${parts.at(-1)}`;
13563
+ }
12364
13564
  const SKILL_DESCRIPTION_MAX_LENGTH = 1024;
12365
13565
  const SKILL_NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
12366
13566
  /**
@@ -15483,8 +16683,11 @@ var FeatureProcessor = class extends RulesyncSourceConsumer {
15483
16683
  })) continue;
15484
16684
  const existingFileContent = await readFileContentOrNull(filePath);
15485
16685
  if (existingFileContent !== null && aiFile.shouldMergeExistingFileContent()) aiFile.setFileContent(existingFileContent);
15486
- const contentWithNewline = addTrailingNewline(aiFile.getFileContent());
15487
16686
  const existingContent = existingFileContent;
16687
+ const contentWithNewline = aiFile.composeWrittenContent({
16688
+ existingContent,
16689
+ generatedContent: addTrailingNewline(aiFile.getFileContent())
16690
+ });
15488
16691
  if (existingContent === null && aiFile.shouldSkipCreationWhenPayloadEmpty() && fileContentIsEmptyPayload({
15489
16692
  filePath,
15490
16693
  content: contentWithNewline
@@ -15603,6 +16806,21 @@ var FeatureProcessor = class extends RulesyncSourceConsumer {
15603
16806
  }
15604
16807
  if (refused) continue;
15605
16808
  const loggedPath = stripControlCharacters(filePath);
16809
+ if (aiFile.keepsContentOnRemoval()) {
16810
+ const existingContent = await readFileContentOrNull(filePath);
16811
+ const outcome = existingContent === null ? { action: "delete" } : aiFile.composeContentAfterRemoval({ existingContent });
16812
+ if (outcome.action === "keep") continue;
16813
+ if (outcome.action === "rewrite") {
16814
+ if (this.dryRun) this.logger.info(`[DRY RUN] Would rewrite: ${loggedPath}`);
16815
+ else {
16816
+ await writeFileContent(filePath, outcome.content);
16817
+ this.logger.info(`Removed the generated block from: ${loggedPath}`);
16818
+ }
16819
+ this.sweepWrites.paths.push(aiFile.getRelativePathFromCwd());
16820
+ removedCount++;
16821
+ continue;
16822
+ }
16823
+ }
15606
16824
  if (this.dryRun) this.logger.info(`[DRY RUN] Would delete: ${loggedPath}`);
15607
16825
  else {
15608
16826
  await removeFile(filePath);
@@ -15987,8 +17205,8 @@ var ClaimedIdentities = class {
15987
17205
  };
15988
17206
  // src/utils/curated-frontmatter.ts
15989
17207
  /**
15990
- * The frontmatter fields a command or subagent fetched from a declared source
15991
- * keeps. Only the canonical, tool-neutral fields of the rulesync schema are
17208
+ * The frontmatter fields a command, subagent or skill fetched from a declared
17209
+ * source keeps. Only the canonical, tool-neutral fields of the rulesync schema are
15992
17210
  * listed: none of them grants tools, permissions, hooks or MCP servers.
15993
17211
  *
15994
17212
  * Every tool section (`claudecode`, `codexcli`, `kiro`, `opencode`, ...) is
@@ -16005,6 +17223,30 @@ const CURATED_SUBAGENT_FRONTMATTER_KEYS = [
16005
17223
  "description"
16006
17224
  ];
16007
17225
  /**
17226
+ * A skill also keeps the root invocation flags (`disable-model-invocation`,
17227
+ * `user-invocable`), which only narrow when the skill is loaded, and the Agent
17228
+ * Skills packaging fields (`license`, `compatibility`, `metadata`). Inside
17229
+ * `metadata`, the tool blocks listed in `CURATED_SKILL_DROPPED_METADATA_KEYS`
17230
+ * are dropped, since they gate or install things rather than describe the
17231
+ * skill.
17232
+ */
17233
+ const CURATED_SKILL_FRONTMATTER_KEYS = [
17234
+ "targets",
17235
+ "name",
17236
+ "description",
17237
+ "disable-model-invocation",
17238
+ "user-invocable",
17239
+ "license",
17240
+ "compatibility",
17241
+ "metadata"
17242
+ ];
17243
+ /**
17244
+ * `metadata` keys a tool reads as configuration: OpenClaw's `metadata.openclaw`
17245
+ * (`install`, `always`, `requires`, ...) and Hermes Agent's `metadata.hermes`
17246
+ * (`requires_toolsets`, ...). A skill fetched from a source loses them.
17247
+ */
17248
+ const CURATED_SKILL_DROPPED_METADATA_KEYS = ["openclaw", "hermes"];
17249
+ /**
16008
17250
  * Keep only `allowedKeys` of a frontmatter object. Returns a new frontmatter
16009
17251
  * and the names of the dropped top-level keys, in input order.
16010
17252
  */
@@ -31721,6 +32963,15 @@ const defaultGetFactory$5 = (target) => {
31721
32963
  const skillsProcessorToolTargetsProject = [...toolSkillFactories].filter(([, factory]) => factory.meta.supportsProject).map(([target]) => target);
31722
32964
  const skillsProcessorToolTargetsSimulated = [...toolSkillFactories].filter(([, factory]) => factory.meta.supportsSimulated).map(([target]) => target);
31723
32965
  const skillsProcessorToolTargetsGlobal = [...toolSkillFactories].filter(([, factory]) => factory.meta.supportsGlobal).map(([target]) => target);
32966
+ /**
32967
+ * Whether a skill companion path is the Codex `agents/openai.yaml` sidecar,
32968
+ * compared case-insensitively and with either separator, since a
32969
+ * case-insensitive filesystem or Windows resolves those spellings to it.
32970
+ */
32971
+ function isCodexOpenaiYaml(relativeFilePath) {
32972
+ const normalize = (path) => path.replaceAll("\\", "/").toLowerCase();
32973
+ return normalize(relativeFilePath) === normalize(CODEXCLI_OPENAI_YAML_RELATIVE_PATH);
32974
+ }
31724
32975
  var SkillsProcessor = class extends DirFeatureProcessor {
31725
32976
  toolTarget;
31726
32977
  global;
@@ -31834,16 +33085,59 @@ var SkillsProcessor = class extends DirFeatureProcessor {
31834
33085
  }));
31835
33086
  return false;
31836
33087
  });
31837
- curatedSkills = await Promise.all(nonConflicting.map((dirName) => RulesyncSkill.fromDir({
33088
+ curatedSkills = await Promise.all(nonConflicting.map(async (dirName) => this.withCanonicalFrontmatterOnly(await RulesyncSkill.fromDir({
31838
33089
  outputRoot: treeParent,
31839
33090
  relativeDirPath: treeCuratedSkillsDirPath,
31840
33091
  dirName,
31841
33092
  global: this.global
31842
- })));
33093
+ }))));
31843
33094
  }
31844
33095
  return [...localSkills, ...curatedSkills];
31845
33096
  }
31846
33097
  /**
33098
+ * A skill fetched from a declared source, keeping only the canonical,
33099
+ * tool-neutral frontmatter fields and dropping every tool section, since
33100
+ * those are copied into the generated files and can grant tools or hooks
33101
+ * (Claude Code `allowed-tools` and `hooks`, for example). The tool blocks
33102
+ * inside `metadata` (OpenClaw's `metadata.openclaw`, Hermes Agent's
33103
+ * `metadata.hermes`) and a Codex `agents/openai.yaml` companion file (its
33104
+ * invocation policy and MCP dependencies) go too. The body and the other
33105
+ * companion files are kept. A local skill of the same name keeps its
33106
+ * tool-specific settings.
33107
+ */
33108
+ withCanonicalFrontmatterOnly(skill) {
33109
+ const kept = keepCuratedFrontmatterKeys({
33110
+ frontmatter: skill.getFrontmatter(),
33111
+ allowedKeys: CURATED_SKILL_FRONTMATTER_KEYS
33112
+ });
33113
+ const frontmatter = kept.frontmatter;
33114
+ const droppedKeys = [...kept.droppedKeys];
33115
+ if (frontmatter.metadata !== void 0) {
33116
+ const metadata = { ...frontmatter.metadata };
33117
+ for (const key of CURATED_SKILL_DROPPED_METADATA_KEYS) if (Object.hasOwn(metadata, key)) {
33118
+ delete metadata[key];
33119
+ droppedKeys.push(`metadata.${key}`);
33120
+ }
33121
+ frontmatter.metadata = metadata;
33122
+ }
33123
+ const otherFiles = skill.getOtherFiles();
33124
+ const keptFiles = otherFiles.filter((file) => !isCodexOpenaiYaml(file.relativeFilePathToDirPath));
33125
+ const droppedFiles = otherFiles.length - keptFiles.length;
33126
+ if (droppedKeys.length === 0 && droppedFiles === 0) return skill;
33127
+ const skillPath = quoteForLog((0, node_path.join)(skill.getRelativeDirPath(), skill.getDirName()));
33128
+ if (droppedKeys.length > 0) this.logger.warn(`Dropped frontmatter from source-installed skill ${skillPath}: ${droppedKeys.map(stripControlCharacters).join(", ")}. A skill installed from a source keeps only these frontmatter fields: ${CURATED_SKILL_FRONTMATTER_KEYS.join(", ")} (without ${CURATED_SKILL_DROPPED_METADATA_KEYS.map((key) => `metadata.${key}`).join(" or ")}). It cannot grant tools or hooks; copy it into .rulesync/skills/ locally to keep tool-specific settings.`);
33129
+ if (droppedFiles > 0) this.logger.warn(`Dropped ${CODEXCLI_OPENAI_YAML_RELATIVE_PATH} from source-installed skill ${skillPath}: a skill installed from a source cannot set a Codex CLI invocation policy or MCP dependencies; copy it into .rulesync/skills/ locally to keep them.`);
33130
+ return new RulesyncSkill({
33131
+ outputRoot: skill.getOutputRoot(),
33132
+ relativeDirPath: skill.getRelativeDirPath(),
33133
+ dirName: skill.getDirName(),
33134
+ frontmatter,
33135
+ body: skill.getBody(),
33136
+ otherFiles: keptFiles,
33137
+ global: skill.getGlobal()
33138
+ });
33139
+ }
33140
+ /**
31847
33141
  * Implementation of abstract method from DirFeatureProcessor.
31848
33142
  *
31849
33143
  * Load and parse rulesync skill directories from every configured input
@@ -41455,6 +42749,125 @@ var ClaudecodeLanguageSettings = class ClaudecodeLanguageSettings extends ToolFi
41455
42749
  }
41456
42750
  }
41457
42751
  };
42752
+ // src/features/rules/rule-managed-block.ts
42753
+ /**
42754
+ * The fence `preserveUnmanagedRuleContent` wraps around the generated body of
42755
+ * a root rule file, so content a person writes outside it survives the next
42756
+ * `generate`. The wording follows the block `rulesync gitignore` writes
42757
+ * (`# Generated by Rulesync` / `# End of Rulesync`), as Markdown comments so
42758
+ * the tools reading the file do not show it.
42759
+ */
42760
+ const RULE_MANAGED_BLOCK_START = "<!-- Generated by Rulesync -->";
42761
+ const RULE_MANAGED_BLOCK_END = "<!-- End of Rulesync -->";
42762
+ const LEADING_FRONTMATTER_PATTERN = /^---\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/;
42763
+ const splitLeadingFrontmatter = (content) => {
42764
+ const match = LEADING_FRONTMATTER_PATTERN.exec(content);
42765
+ if (!match) return {
42766
+ frontmatter: "",
42767
+ rest: content
42768
+ };
42769
+ return {
42770
+ frontmatter: match[0].endsWith("\n") ? match[0] : `${match[0]}\n`,
42771
+ rest: content.slice(match[0].length)
42772
+ };
42773
+ };
42774
+ const CODE_FENCE_PATTERN = /^ {0,3}(`{3,}|~{3,})/;
42775
+ /**
42776
+ * Locate the first complete fence: a line that is exactly the start marker
42777
+ * (surrounding whitespace aside) followed later by a line that is exactly the
42778
+ * end marker. A start marker without an end marker is not a fence. Marker
42779
+ * lines inside a Markdown code block (```` ``` ```` or `~~~`) do not count, so
42780
+ * a rule that quotes the markers in an example is not mistaken for a fence.
42781
+ */
42782
+ const findFence = (content) => {
42783
+ let startLineBegin;
42784
+ let startLineEnd = 0;
42785
+ let openCodeFence;
42786
+ let offset = 0;
42787
+ while (offset <= content.length) {
42788
+ const newline = content.indexOf("\n", offset);
42789
+ const lineEnd = newline === -1 ? content.length : newline + 1;
42790
+ const rawLine = content.slice(offset, newline === -1 ? content.length : newline);
42791
+ const codeFence = CODE_FENCE_PATTERN.exec(rawLine)?.[1];
42792
+ if (openCodeFence !== void 0) {
42793
+ if (codeFence !== void 0 && codeFence[0] === openCodeFence[0] && codeFence.length >= openCodeFence.length && rawLine.trim() === codeFence) openCodeFence = void 0;
42794
+ } else if (codeFence !== void 0) openCodeFence = codeFence;
42795
+ else {
42796
+ const line = rawLine.trim();
42797
+ if (startLineBegin === void 0) {
42798
+ if (line === "<!-- Generated by Rulesync -->") {
42799
+ startLineBegin = offset;
42800
+ startLineEnd = lineEnd;
42801
+ }
42802
+ } else if (line === "<!-- End of Rulesync -->") return {
42803
+ startLineBegin,
42804
+ startLineEnd,
42805
+ endLineBegin: offset,
42806
+ endLineEnd: lineEnd
42807
+ };
42808
+ }
42809
+ if (newline === -1) break;
42810
+ offset = lineEnd;
42811
+ }
42812
+ };
42813
+ /**
42814
+ * Compose the content to write for a root rule file under
42815
+ * `preserveUnmanagedRuleContent`: the generated frontmatter (if any) first,
42816
+ * then whatever the existing file holds before its fence, the fenced
42817
+ * generated body, and whatever it holds after the fence.
42818
+ *
42819
+ * An existing file without a complete fence is treated as entirely
42820
+ * rulesync's — it is what rulesync wrote before the option was turned on, and
42821
+ * keeping it would duplicate that content outside the fence — so only the
42822
+ * fenced body is written. Hand edits belong outside the fence from then on.
42823
+ *
42824
+ * When the generated content starts with frontmatter, the existing file's
42825
+ * leading frontmatter is rulesync's too and is replaced rather than kept.
42826
+ *
42827
+ * When the generated content has no frontmatter, an existing leading
42828
+ * frontmatter block is kept as part of the content before the fence, even if
42829
+ * rulesync wrote it on an earlier run (a target or rule that no longer emits
42830
+ * frontmatter). Nothing in the file tells such a block apart from one a person
42831
+ * wrote: a hand-written block also sits right above the start marker, since
42832
+ * the fence opens the file rulesync writes. Keeping it never loses hand-written
42833
+ * content, and the result is stable across runs; a stale block is removed by
42834
+ * hand once.
42835
+ */
42836
+ const spliceRuleManagedBlock = ({ existingContent, generatedContent }) => {
42837
+ const generated = splitLeadingFrontmatter(generatedContent);
42838
+ const body = generated.rest.replace(/^\n+/, "");
42839
+ const block = `${RULE_MANAGED_BLOCK_START}\n${body}${body === "" || body.endsWith("\n") ? "" : "\n"}${RULE_MANAGED_BLOCK_END}\n`;
42840
+ if (existingContent === null) return generated.frontmatter + block;
42841
+ const eol = (text) => existingContent.includes("\r\n") ? text.replaceAll("\n", "\r\n") : text;
42842
+ const existing = generated.frontmatter === "" ? existingContent : splitLeadingFrontmatter(existingContent).rest;
42843
+ const fence = findFence(existing);
42844
+ if (fence === void 0) return eol(generated.frontmatter + block);
42845
+ const before = existing.slice(0, fence.startLineBegin);
42846
+ let after = existing.slice(fence.endLineEnd);
42847
+ if (fence.endLineEnd === existing.length && !existing.endsWith("\n")) after = "";
42848
+ return eol(generated.frontmatter) + before + eol(block) + after;
42849
+ };
42850
+ /**
42851
+ * `content` with its first complete fence (marker lines included) taken out,
42852
+ * or `undefined` when it has none. Used when a root rule file stops being
42853
+ * generated: the fenced block is rulesync's to remove, the rest is not.
42854
+ */
42855
+ const removeRuleManagedBlock = (content) => {
42856
+ const fence = findFence(content);
42857
+ if (fence === void 0) return;
42858
+ return content.slice(0, fence.startLineBegin) + content.slice(fence.endLineEnd);
42859
+ };
42860
+ /**
42861
+ * The text inside the first complete fence (without the marker lines), or
42862
+ * `undefined` when `content` has none. `import` keeps only this part so
42863
+ * hand-written content outside the fence is not copied into the rulesync
42864
+ * source, where the next `generate` would write it a second time.
42865
+ */
42866
+ const extractRuleManagedBlock = (content) => {
42867
+ const fence = findFence(content);
42868
+ if (fence === void 0) return;
42869
+ return content.slice(fence.startLineEnd, fence.endLineBegin);
42870
+ };
41458
42871
  // src/features/shared/opencode-family-mcp-tool-keys.ts
41459
42872
  /**
41460
42873
  * MCP tool naming shared by OpenCode and its forks (Kilo, MiMo Code):
@@ -43129,6 +44542,46 @@ var ToolRule = class extends ToolFile {
43129
44542
  this.description = description;
43130
44543
  this.globs = globs;
43131
44544
  }
44545
+ /**
44546
+ * Whether the write phase fences the generated content and keeps what the
44547
+ * existing file holds outside the fence (`preserveUnmanagedRuleContent`).
44548
+ * Set by the rules processor on the root rule files it emits.
44549
+ */
44550
+ preservesUnmanagedContent = false;
44551
+ /** See {@link ToolRule.preservesUnmanagedContent}. */
44552
+ enableUnmanagedContentPreservation() {
44553
+ this.preservesUnmanagedContent = true;
44554
+ }
44555
+ isPreservingUnmanagedContent() {
44556
+ return this.preservesUnmanagedContent;
44557
+ }
44558
+ composeWrittenContent({ existingContent, generatedContent }) {
44559
+ if (!this.preservesUnmanagedContent) return generatedContent;
44560
+ return spliceRuleManagedBlock({
44561
+ existingContent,
44562
+ generatedContent
44563
+ });
44564
+ }
44565
+ keepsContentOnRemoval() {
44566
+ return this.preservesUnmanagedContent;
44567
+ }
44568
+ /**
44569
+ * Under `preserveUnmanagedRuleContent`, removing a root rule file takes out
44570
+ * only the fenced block and keeps the hand-written rest; a file with nothing
44571
+ * else left is deleted. A file without a fence is not rulesync's any more —
44572
+ * the hand-written rest of an earlier removal, or a file written before the
44573
+ * option was on — so it is left in place.
44574
+ */
44575
+ composeContentAfterRemoval({ existingContent }) {
44576
+ if (!this.preservesUnmanagedContent) return { action: "delete" };
44577
+ const rest = removeRuleManagedBlock(existingContent);
44578
+ if (rest === void 0) return { action: "keep" };
44579
+ if (rest.trim() === "") return { action: "delete" };
44580
+ return {
44581
+ action: "rewrite",
44582
+ content: rest
44583
+ };
44584
+ }
43132
44585
  static getSettablePaths(_options = {}) {
43133
44586
  throw new Error("Please implement this method in the subclass.");
43134
44587
  }
@@ -53213,6 +54666,23 @@ const resolveBooleanRulesOption = ({ options, key }) => {
53213
54666
  if (!parsed.success) throw new Error(`Invalid options for rules feature: ${parsed.error.message}. \`${key}\` must be a boolean.`);
53214
54667
  return parsed.data[key] ?? true;
53215
54668
  };
54669
+ /**
54670
+ * Resolve the `include` rules option: the names of the rules this target
54671
+ * receives, or `undefined` when the option is unset (every rule is eligible).
54672
+ */
54673
+ const resolveRuleIncludeOption = (options) => {
54674
+ if (!options) return void 0;
54675
+ const parsed = zod_mini.z.looseObject({ include: zod_mini.z.optional(zod_mini.z.array(zod_mini.z.string())) }).safeParse(options);
54676
+ if (!parsed.success) throw new Error(`Invalid options for rules feature: ${parsed.error.message}. \`include\` must be an array of rule names.`);
54677
+ return parsed.data.include;
54678
+ };
54679
+ /**
54680
+ * The name the `include` rules option selects a rule by: its path under
54681
+ * `rules/` (or `rules/.curated/`) without the `.md` extension, normalized the
54682
+ * same way as `sources[].rules`. A rule at the top of the directory is matched
54683
+ * by its file name alone, e.g. `git-safety` for `git-safety.md`.
54684
+ */
54685
+ const getRuleSelectionName = (rule) => normalizeRuleFilterName(toPosixPath(rule.getRelativeFilePath()));
53216
54686
  const allToolTargetKeys$1 = [...toolRuleFactories.keys()];
53217
54687
  const rulesProcessorToolTargets = allToolTargetKeys$1.filter((target) => {
53218
54688
  return toolRuleFactories.get(target)?.meta.supportsProject !== false;
@@ -53255,6 +54725,24 @@ const findFilesWithFallback = async (primaryFilePaths, alternativeRoots, buildAl
53255
54725
  * delete generated files it can no longer regenerate and report success.
53256
54726
  */
53257
54727
  const rootRelativeGlob = (...segments) => node_path.posix.join(...segments.filter((segment) => segment !== void 0).map(toPosixPath));
54728
+ /**
54729
+ * Keep only the fenced part of a rule a `preserveUnmanagedRuleContent` run
54730
+ * wrote, so `import` does not copy hand-written content outside the fence into
54731
+ * the rulesync source, where the next `generate` would write it a second time
54732
+ * inside the fence. A rule without a complete fence is returned unchanged.
54733
+ */
54734
+ const extractFencedRule = (rulesyncRule) => {
54735
+ const fenced = extractRuleManagedBlock(rulesyncRule.getBody());
54736
+ if (fenced === void 0) return rulesyncRule;
54737
+ return new RulesyncRule({
54738
+ outputRoot: rulesyncRule.getOutputRoot(),
54739
+ relativeDirPath: rulesyncRule.getRelativeDirPath(),
54740
+ relativeFilePath: rulesyncRule.getRelativeFilePath(),
54741
+ frontmatter: rulesyncRule.getFrontmatter(),
54742
+ body: fenced.trim(),
54743
+ validate: false
54744
+ });
54745
+ };
53258
54746
  const isRootRule = (rule) => Boolean(rule.getFrontmatter().root || rule.getFrontmatter().localRoot);
53259
54747
  var RulesProcessor = class extends FeatureProcessor {
53260
54748
  toolTarget;
@@ -53271,7 +54759,13 @@ var RulesProcessor = class extends FeatureProcessor {
53271
54759
  skills;
53272
54760
  featureOptions;
53273
54761
  deleteOrphans;
53274
- constructor({ outputRoot = process.cwd(), inputRoots, toolTarget, simulateCommands = false, simulateSubagents = false, simulateSkills = false, language, deriveSubprojectPathFromGlobs = false, global = false, getFactory = defaultGetFactory$3, skills, featureOptions, delete: deleteOrphans = false, dryRun = false, logger }) {
54762
+ preserveUnmanagedContent;
54763
+ /**
54764
+ * Whether the last `loadRulesyncFiles` call's `include` option left out a
54765
+ * rule that targets this tool.
54766
+ */
54767
+ includeNarrowedSelection = false;
54768
+ constructor({ outputRoot = process.cwd(), inputRoots, toolTarget, simulateCommands = false, simulateSubagents = false, simulateSkills = false, language, deriveSubprojectPathFromGlobs = false, global = false, getFactory = defaultGetFactory$3, skills, featureOptions, delete: deleteOrphans = false, preserveUnmanagedContent = false, dryRun = false, logger }) {
53275
54769
  super({
53276
54770
  outputRoot,
53277
54771
  inputRoots,
@@ -53291,6 +54785,7 @@ var RulesProcessor = class extends FeatureProcessor {
53291
54785
  this.skills = skills;
53292
54786
  this.featureOptions = featureOptions;
53293
54787
  this.deleteOrphans = deleteOrphans;
54788
+ this.preserveUnmanagedContent = preserveUnmanagedContent;
53294
54789
  }
53295
54790
  async convertRulesyncFilesToToolFiles(rulesyncFiles) {
53296
54791
  const rulesyncRules = rulesyncFiles.filter((file) => file instanceof RulesyncRule);
@@ -53334,6 +54829,9 @@ var RulesProcessor = class extends FeatureProcessor {
53334
54829
  });
53335
54830
  extraFiles.push(...await this.buildLanguageSettingsFiles());
53336
54831
  const outputFiles = [...toolRules, ...extraFiles];
54832
+ if (this.preserveUnmanagedContent) {
54833
+ for (const file of outputFiles) if (file instanceof ToolRule && file.isRoot()) file.enableUnmanagedContentPreservation();
54834
+ }
53337
54835
  this.warnForOutputPathCollisions({
53338
54836
  outputFiles,
53339
54837
  convertedRules
@@ -53768,10 +55266,10 @@ As this project's AI coding tool, you must follow the additional conventions bel
53768
55266
  async convertToolFilesToRulesyncFiles(toolFiles) {
53769
55267
  const toolRules = toolFiles.filter((file) => file instanceof ToolRule);
53770
55268
  const rulesyncRules = toolRules.map((toolRule) => {
53771
- if (toolRule.isLocalRoot()) return toolRule.toLocalRootRulesyncRule({ targets: [this.toolTarget] });
55269
+ if (toolRule.isLocalRoot()) return this.withoutUnmanagedContent(toolRule.toLocalRootRulesyncRule({ targets: [this.toolTarget] }));
53772
55270
  return this.withoutLanguageBlock({
53773
55271
  toolRule,
53774
- rulesyncRule: toolRule.toRulesyncRule()
55272
+ rulesyncRule: this.withoutUnmanagedContent(toolRule.toRulesyncRule())
53775
55273
  });
53776
55274
  });
53777
55275
  const claimedBy = /* @__PURE__ */ new Map();
@@ -53788,6 +55286,13 @@ As this project's AI coding tool, you must follow the additional conventions bel
53788
55286
  return rulesyncRules;
53789
55287
  }
53790
55288
  /**
55289
+ * See {@link extractFencedRule}. Only under `preserveUnmanagedRuleContent`:
55290
+ * without it a file that merely quotes the markers is imported whole.
55291
+ */
55292
+ withoutUnmanagedContent(rulesyncRule) {
55293
+ return this.preserveUnmanagedContent ? extractFencedRule(rulesyncRule) : rulesyncRule;
55294
+ }
55295
+ /**
53791
55296
  * Drop the language block a previous `generate` appended, so that importing
53792
55297
  * a generated root file and generating again yields one block, not two.
53793
55298
  * Every imported rule is checked, not just root ones: Cursor and the
@@ -53909,10 +55414,17 @@ As this project's AI coding tool, you must follow the additional conventions bel
53909
55414
  * copy (case-insensitive, matching the intra-root collision handling).
53910
55415
  */
53911
55416
  async loadRulesyncFiles() {
53912
- const rulesyncRules = await this.loadMergedRulesyncRules();
53913
55417
  const factory = this.getFactory(this.toolTarget);
55418
+ const mergedRules = await this.loadMergedRulesyncRules();
55419
+ const rulesyncRules = this.selectIncludedRules({
55420
+ rules: mergedRules,
55421
+ factory
55422
+ });
55423
+ const isTargeted = (rule) => factory.class.isTargetedByRulesyncRule(rule);
55424
+ this.includeNarrowedSelection = rulesyncRules.filter(isTargeted).length < mergedRules.filter(isTargeted).length;
53914
55425
  const targetedRootRules = rulesyncRules.filter((rule) => rule.getFrontmatter().root).filter((rule) => factory.class.isTargetedByRulesyncRule(rule));
53915
- if (targetedRootRules.length === 0 && rulesyncRules.length > 0) this.logger.warn(`No root rulesync rule file found for target '${this.toolTarget}'. Consider adding 'root: true' to one of your rule files in ${RULESYNC_RULES_RELATIVE_DIR_PATH}.`);
55426
+ const rootRuleLeftOutByInclude = mergedRules.some((rule) => rule.getFrontmatter().root && factory.class.isTargetedByRulesyncRule(rule) && !rulesyncRules.includes(rule));
55427
+ if (targetedRootRules.length === 0 && rulesyncRules.length > 0 && !rootRuleLeftOutByInclude) this.logger.warn(`No root rulesync rule file found for target '${this.toolTarget}'. Consider adding 'root: true' to one of your rule files in ${RULESYNC_RULES_RELATIVE_DIR_PATH}.`);
53916
55428
  const targetedLocalRootRules = rulesyncRules.filter((rule) => rule.getFrontmatter().localRoot).filter((rule) => factory.class.isTargetedByRulesyncRule(rule));
53917
55429
  if (targetedLocalRootRules.length > 1) throw new Error(`Multiple localRoot rules found for target '${this.toolTarget}': ${formatRulePaths(targetedLocalRootRules)}. Only one rule can have localRoot: true`);
53918
55430
  if (targetedLocalRootRules.length > 0 && targetedRootRules.length === 0) throw new Error(`localRoot: true requires a root: true rule to exist for target '${this.toolTarget}' (found in ${formatRulePaths(targetedLocalRootRules)})`);
@@ -53930,6 +55442,36 @@ As this project's AI coding tool, you must follow the additional conventions bel
53930
55442
  return [...targetedRootRules, ...nonRootRules];
53931
55443
  }
53932
55444
  /**
55445
+ * Whether the target's `include` rules option left out at least one rule
55446
+ * that targets this tool in the last `loadRulesyncFiles` call. `["*"]`, or a
55447
+ * list naming every rule the tool would receive, narrows nothing.
55448
+ */
55449
+ didIncludeNarrowSelection() {
55450
+ return this.includeNarrowedSelection;
55451
+ }
55452
+ /**
55453
+ * Narrow the rules to the ones the target's `include` rules option names.
55454
+ * The option is a pure narrowing filter: a named rule still has to target
55455
+ * this tool through its `targets` frontmatter, which is checked afterwards
55456
+ * as for any other rule. A name that matches no rule (local or curated) is
55457
+ * an error, so a renamed or removed rule does not silently disappear from
55458
+ * the target. `["*"]` selects every rule, as in `sources[].rules`.
55459
+ */
55460
+ selectIncludedRules({ rules, factory, warn = true }) {
55461
+ const include = resolveRuleIncludeOption(this.featureOptions);
55462
+ if (include === void 0) return rules;
55463
+ const names = [...new Set(include.map(normalizeRuleFilterName))];
55464
+ if (isWildcardSelection(names)) return rules;
55465
+ const availableNames = new Set(rules.map(getRuleSelectionName));
55466
+ const unknownNames = names.filter((name) => !availableNames.has(name));
55467
+ if (unknownNames.length > 0) throw new Error(`Unknown rule name${unknownNames.length > 1 ? "s" : ""} in the \`include\` rules option of target '${this.toolTarget}': ${unknownNames.map(quoteForLog).join(", ")}. Each name must match a rule file under ${RULESYNC_RULES_RELATIVE_DIR_PATH} (including fetched rules in .curated/), without the .md extension, e.g. "git-safety" for git-safety.md.`);
55468
+ const selectedNames = new Set(names);
55469
+ const selectedRules = rules.filter((rule) => selectedNames.has(getRuleSelectionName(rule)));
55470
+ const excludedByFrontmatter = selectedRules.filter((rule) => !factory.class.isTargetedByRulesyncRule(rule));
55471
+ if (warn && excludedByFrontmatter.length > 0) this.logger.warn(`The \`include\` rules option of target '${this.toolTarget}' names rules whose \`targets\` frontmatter excludes it, so they are not generated: ${formatRulePaths(excludedByFrontmatter)}`);
55472
+ return selectedRules;
55473
+ }
55474
+ /**
53933
55475
  * Align the rules with each other through the tool's `alignRulesyncRules`
53934
55476
  * hook, printing its warnings unless `warn` is off.
53935
55477
  */
@@ -53980,7 +55522,16 @@ As this project's AI coding tool, you must follow the additional conventions bel
53980
55522
  async warnForFoldImportDuplicationRisk() {
53981
55523
  const factory = this.getFactory(this.toolTarget);
53982
55524
  if (factory.meta.collisionPolicy !== "fold") return;
53983
- const targetedRules = this.alignRulesyncRules(await this.loadMergedRulesyncRules(), { warn: false }).filter((rule) => factory.class.isTargetedByRulesyncRule(rule));
55525
+ const loadedRules = await this.loadMergedRulesyncRules();
55526
+ let includedRules = loadedRules;
55527
+ try {
55528
+ includedRules = this.selectIncludedRules({
55529
+ rules: loadedRules,
55530
+ factory,
55531
+ warn: false
55532
+ });
55533
+ } catch {}
55534
+ const targetedRules = this.alignRulesyncRules(includedRules, { warn: false }).filter((rule) => factory.class.isTargetedByRulesyncRule(rule));
53984
55535
  let includeLocalRoot = !this.global;
53985
55536
  try {
53986
55537
  includeLocalRoot &&= resolveBooleanRulesOption({
@@ -54045,6 +55596,14 @@ As this project's AI coding tool, you must follow the additional conventions bel
54045
55596
  * Load tool-specific rule configurations and parse them into ToolRule instances
54046
55597
  */
54047
55598
  async loadToolFiles({ forDeletion = false } = {}) {
55599
+ const toolFiles = await this.loadToolFilesUnmarked({ forDeletion });
55600
+ if (forDeletion && this.preserveUnmanagedContent) {
55601
+ const { localRootFileName } = this.getFactory(this.toolTarget).meta;
55602
+ for (const file of toolFiles) if (file instanceof ToolRule && (file.isRoot() || file.isLocalRoot() || localRootFileName !== void 0 && file.getRelativeFilePath() === localRootFileName)) file.enableUnmanagedContentPreservation();
55603
+ }
55604
+ return toolFiles;
55605
+ }
55606
+ async loadToolFilesUnmarked({ forDeletion }) {
54048
55607
  try {
54049
55608
  const factory = this.getFactory(this.toolTarget);
54050
55609
  const settablePaths = factory.class.getSettablePaths({ global: this.global });
@@ -57644,7 +59203,10 @@ function anchorDotPaths({ command, projectDirVar }) {
57644
59203
  * first word, so interpreter-prefixed commands (`python3 "$VAR/x.py"`,
57645
59204
  * `node $VAR/x.js`) do not leak a tool-specific variable into targets that do
57646
59205
  * not define it. The recognized forms, each followed by `/`, are `"$VAR"`,
57647
- * `"${VAR}"`, `$VAR` and `${VAR}`:
59206
+ * `"${VAR}"`, `$VAR` and `${VAR}`, plus the fail-closed `${VAR:?}` in either
59207
+ * spelling when `acceptsFailClosedForm` is set (for a tool that writes that
59208
+ * form itself; elsewhere a hand-written `${VAR:?}` is left as written, so it
59209
+ * keeps failing closed):
57648
59210
  *
57649
59211
  * - a quote around the whole path is kept, so a path containing spaces stays
57650
59212
  * one word (`"$VAR/my hook.sh"` becomes `"./my hook.sh"`);
@@ -57669,9 +59231,9 @@ function anchorDotPaths({ command, projectDirVar }) {
57669
59231
  * later words are not converted (see `convertsLaterWords`) or that starts
57670
59232
  * with another variable — every occurrence after the first word.
57671
59233
  */
57672
- function importProjectDirVariable({ command, projectDirVar, firstWordOnly = false }) {
59234
+ function importProjectDirVariable({ command, projectDirVar, firstWordOnly = false, acceptsFailClosedForm = false }) {
57673
59235
  const escapedName = escapeRegExp(projectDirVar.replace(/^\$/, ""));
57674
- const variable = `\\$(?:${escapedName}|\\{${escapedName}\\})`;
59236
+ const variable = `\\$(?:${escapedName}|\\{${escapedName}${acceptsFailClosedForm ? "(?::\\?)?" : ""}\\})`;
57675
59237
  const pattern = new RegExp(`(?:"${variable}"/(["']?)|${variable}/)`, "g");
57676
59238
  const leading = command.length - command.trimStart().length;
57677
59239
  const inFirstWord = (offset) => offset === leading || offset === leading + 1 && command.charAt(leading) === "\"";
@@ -57782,6 +59344,15 @@ function groupDefinitionsByMatcher({ definitions, eventName, converterConfig, wa
57782
59344
  }
57783
59345
  return byMatcher;
57784
59346
  }
59347
+ /**
59348
+ * The project directory variable as generate writes it into a shell command:
59349
+ * `$DEVIN_PLUGIN_ROOT` -> `${DEVIN_PLUGIN_ROOT:?}` for a tool that opts into
59350
+ * {@link ToolHooksConverterConfig.failsClosedOnEmptyProjectDirVar}.
59351
+ */
59352
+ function emittedProjectDirVar(converterConfig) {
59353
+ const { projectDirVar } = converterConfig;
59354
+ return converterConfig.failsClosedOnEmptyProjectDirVar ? `\${${projectDirVar.replace(/^\$/, "")}:?}` : projectDirVar;
59355
+ }
57785
59356
  /** `$CLAUDE_PROJECT_DIR` -> `${CLAUDE_PROJECT_DIR}`, the form the tool substitutes. */
57786
59357
  function bracePlaceholder(projectDirVar) {
57787
59358
  return `\${${projectDirVar.replace(/^\$/, "")}}`;
@@ -57829,12 +59400,12 @@ function applyCommandPrefix({ def, converterConfig }) {
57829
59400
  converterConfig
57830
59401
  }) ? command : anchorDotPaths({
57831
59402
  command,
57832
- projectDirVar: converterConfig.projectDirVar
59403
+ projectDirVar: emittedProjectDirVar(converterConfig)
57833
59404
  });
57834
59405
  if (!shouldPrefix || typeof trimmedCommand !== "string") return typeof def.command === "string" ? anchorInline(def.command) : def.command;
57835
59406
  const relativeCommand = trimmedCommand.replace(/^(["'])\.\//, "$1").replace(/^\.\//, "");
57836
59407
  if (isExecForm) return `${bracePlaceholder(converterConfig.projectDirVar)}/${stripSurroundingQuotes(relativeCommand)}`;
57837
- return anchorInline(`"${converterConfig.projectDirVar}"/${relativeCommand}`);
59408
+ return anchorInline(`"${emittedProjectDirVar(converterConfig)}"/${relativeCommand}`);
57838
59409
  }
57839
59410
  /** Whether a field restricted to some events applies on this one. */
57840
59411
  function isEventApplicable({ events, eventName }) {
@@ -58484,7 +60055,8 @@ function stripCommandPrefix({ command, args, shell, converterConfig, warn }) {
58484
60055
  }) || !runsInPosixShell({
58485
60056
  shell,
58486
60057
  converterConfig
58487
- })
60058
+ }),
60059
+ acceptsFailClosedForm: converterConfig.failsClosedOnEmptyProjectDirVar ?? false
58488
60060
  });
58489
60061
  stripped = result.command;
58490
60062
  if (warn && result.unrestored && !converterConfig.stripsProjectDirVarOnImportOnly) warn(`Hook command ${quoteValueForWarning(cmd)} was imported as ${quoteValueForWarning(stripped)}: a ${variable} path that is not a script the command runs becomes relative to the hook's working directory and is not restored on generate. Put the exact command in a tool-specific hooks override (such as "claudecode.hooks") to keep the variable.`);
@@ -63125,7 +64697,9 @@ var DevinHooks = class extends ToolHooks {
63125
64697
  * anchored to the plugin install directory rather than run against the
63126
64698
  * consumer's workspace. Devin CLI v3000.5.20+ sets `DEVIN_PLUGIN_ROOT` in the
63127
64699
  * environment of hooks contributed by a plugin, and runs `command` as a shell
63128
- * command, so the quoted `"$DEVIN_PLUGIN_ROOT"/...` form expands there. Bare
64700
+ * command, so the quoted `"${DEVIN_PLUGIN_ROOT:?}"/...` form expands there.
64701
+ * The `:?` makes an older CLI, which leaves the variable empty, stop the hook
64702
+ * with an error rather than run `/scripts/...` from the filesystem root. Bare
63129
64703
  * commands such as `npx prettier --write` are left intact.
63130
64704
  *
63131
64705
  * `DEVIN_PLUGIN_ROOT` is chosen over the shorter `PLUGIN_ROOT` (v3000.11.92+)
@@ -63139,6 +64713,7 @@ var DevinHooks = class extends ToolHooks {
63139
64713
  const DEVIN_PLUGIN_CONVERTER_CONFIG = {
63140
64714
  ...DEVIN_CONVERTER_CONFIG,
63141
64715
  projectDirVar: "$DEVIN_PLUGIN_ROOT",
64716
+ failsClosedOnEmptyProjectDirVar: true,
63142
64717
  prefixDotRelativeCommandsOnly: true,
63143
64718
  importedProjectDirVarAliases: ["$PLUGIN_ROOT", "$CLAUDE_PLUGIN_ROOT"]
63144
64719
  };
@@ -63146,7 +64721,7 @@ const DEVIN_PLUGIN_CONVERTER_CONFIG = {
63146
64721
  * Hooks inside a Devin plugin bundle (`<plugin>/hooks.json`). The file is the
63147
64722
  * same bare event map as `.devin/hooks.v1.json` (no `hooks` wrapper key), as
63148
64723
  * in Cognition's plugin templates. Unlike the `devin` target, `./`-relative
63149
- * commands are anchored to `$DEVIN_PLUGIN_ROOT` (see
64724
+ * commands are anchored to `${DEVIN_PLUGIN_ROOT:?}` (see
63150
64725
  * `DEVIN_PLUGIN_CONVERTER_CONFIG`).
63151
64726
  *
63152
64727
  * @see https://docs.devin.ai/cli/extensibility/plugins/overview
@@ -64529,7 +66104,9 @@ const BLOCKING_HOOKS = new Set(Object.keys(NAMED_HOOK_MATCHER_SUBJECTS).filter((
64529
66104
  * Shell echoed them; a `preToolUse` command's are read, 1 MiB each kept (more
64530
66105
  * stdout denies; on the Bun Shell fallback the whole output is buffered before
64531
66106
  * that check), and a `sessionStart` command's stdout is read the same way while
64532
- * its stderr goes to the host's (after the command, on Bun Shell). Output
66107
+ * its stderr goes to the host's (after the command, on Bun Shell); an OpenCode
66108
+ * 2.x `postToolUse` command is the other way round, its stderr read and its
66109
+ * stdout going to the host's. Output
64533
66110
  * pipes a background process keeps open are read for 1 s after the command
64534
66111
  * exits; what arrived by then is kept, and the reads are then cancelled, as
64535
66112
  * they are at a timeout. The OpenCode 1.x-style `event` hooks (`inProcess`)
@@ -64678,28 +66255,37 @@ function buildRunHelperLinesFor(cwdExpression) {
64678
66255
  " if (inProcess || !(await __rulesyncCanExec)) {",
64679
66256
  ` const run = Bun.$\`echo \${input} | \${{ raw: command }}\`.cwd(${cwdExpression}).nothrow();`,
64680
66257
  " // A sessionStart command's stderr reaches the host when it ends, even after its timeout.",
64681
- " const finished = echo === true ? run : run.quiet().then((done) => (echo && process.stderr.write(done.stderr), done));",
66258
+ " // A postToolUse command's (`echo: \"stdout\"`) stdout and stderr reach it when it ends, too.",
66259
+ " const finished = echo === true ? run : run.quiet().then((done) => {",
66260
+ " if (echo === \"stdout\") process.stdout.write(done.stdout);",
66261
+ " if (echo) process.stderr.write(done.stderr);",
66262
+ " return done;",
66263
+ " });",
64682
66264
  " const result = await Promise.race([finished, timeout()]).finally(() => clearTimeout(timer));",
64683
66265
  " if (!result || echo === true) return result && { exitCode: result.exitCode };",
64684
66266
  " const { exitCode, stdout, stderr } = result;",
64685
66267
  " return { exitCode, stdout: stdout.toString(), stderr: stderr.toString(), overflow: stdout.length > 1048576 };",
64686
66268
  " }",
64687
- " // An ordinary command writes to the host's stdout and stderr; a preToolUse one is read, and",
64688
- " // a sessionStart one (`echo: \"stderr\"`) has its stdout read.",
64689
- ` const proc = ${spawn("\"export BUN_BE_BUN=\\n\" + command", "new TextEncoder().encode(input + \"\\n\")", "echo === true ? \"inherit\" : \"pipe\"", "echo ? \"inherit\" : \"pipe\"")};`,
64690
- " const stdout = echo === true ? undefined : __rulesyncRead(proc.stdout);",
64691
- " const stderr = echo ? undefined : __rulesyncRead(proc.stderr);",
66269
+ " // An ordinary command writes to the host's stdout and stderr; a preToolUse one is read,",
66270
+ " // a sessionStart one (`echo: \"stderr\"`) has its stdout read, and a postToolUse one",
66271
+ " // (`echo: \"stdout\"`) its stderr.",
66272
+ ` const proc = ${spawn("\"export BUN_BE_BUN=\\n\" + command", "new TextEncoder().encode(input + \"\\n\")", "echo === true || echo === \"stdout\" ? \"inherit\" : \"pipe\"", "echo === true || echo === \"stderr\" ? \"inherit\" : \"pipe\"")};`,
66273
+ " const stdout = echo === true || echo === \"stdout\" ? undefined : __rulesyncRead(proc.stdout);",
66274
+ " const stderr = echo === true || echo === \"stderr\" ? undefined : __rulesyncRead(proc.stderr);",
64692
66275
  " const exitCode = await Promise.race([proc.exited, timeout()]).finally(() => clearTimeout(timer));",
64693
66276
  " if (exitCode === null) {",
64694
66277
  " stdout?.stop(), stderr?.stop();",
66278
+ " // A postToolUse command's stderr is read, so what it wrote before the timeout reaches the host here.",
66279
+ " if (echo === \"stdout\") process.stderr.write(stderr.text());",
64695
66280
  " if (process.platform === \"win32\") __rulesyncKillWindowsTree(proc);",
64696
66281
  " else __rulesyncKillTree(proc);",
64697
66282
  " return null;",
64698
66283
  " }",
64699
66284
  " if (echo === true) return { exitCode };",
64700
- " await Promise.race([Promise.all([stdout.done, stderr?.done]), Bun.sleep(1000)]);",
64701
- " stdout.stop(), stderr?.stop();",
64702
- " return { exitCode, stdout: stdout.text(), stderr: stderr?.text() ?? \"\", overflow: stdout.overflow() };",
66285
+ " await Promise.race([Promise.all([stdout?.done, stderr?.done]), Bun.sleep(1000)]);",
66286
+ " stdout?.stop(), stderr?.stop();",
66287
+ " if (echo === \"stdout\") process.stderr.write(stderr.text());",
66288
+ " return { exitCode, stdout: stdout?.text() ?? \"\", stderr: stderr?.text() ?? \"\", overflow: stdout?.overflow() ?? false };",
64703
66289
  "};",
64704
66290
  "const __rulesyncRunHook = async ({ label, command, input, blocking, seconds, inProcess = false, context = false }) => {",
64705
66291
  " let result;",
@@ -66228,6 +67814,92 @@ function wrapInConditions(handler, statement, indent) {
66228
67814
  `${indent}}`
66229
67815
  ];
66230
67816
  }
67817
+ /**
67818
+ * Helpers the generated plugin defines when a `postToolUse` handler is present,
67819
+ * giving it Claude Code's `PostToolUse` exit-code contract: the tool already
67820
+ * ran, so nothing is blocked, but a command that exits with code 2 has its
67821
+ * stderr (sanitized, see `hook-block-reason.ts`) shown to the model with the
67822
+ * tool result. Any other non-zero exit, a timeout or a command that cannot be
67823
+ * run is only logged, as before. The command's stdout still streams to the
67824
+ * host's; its stderr is read (1 MiB kept) and written to the host's by
67825
+ * `__rulesyncRunCommand` when the command ends or times out, so it stays
67826
+ * visible there too.
67827
+ *
67828
+ * OpenCode 2.x lets an `execute.after` hook replace a completed call's
67829
+ * `event.result` (`{ output?, content?, metadata? }`), which the host
67830
+ * normalizes again before the model sees it; its own tool-repair plugin adds a
67831
+ * note the same way. The text goes into both fields, since the model reads the
67832
+ * result from either: `output` when it is a string, and `content` whether it
67833
+ * is a string or an array of parts. A missing or empty `content` stands for
67834
+ * the output upstream, so that output is kept ahead of the text. A failure
67835
+ * here is logged: a hook that throws would fail the call.
67836
+ *
67837
+ * `postToolUseFailure` stays observe-only. Claude Code shows its exit-2 stderr
67838
+ * to the model too, but a failed call's `event.error` is the host's typed tool
67839
+ * error (`ToolFailure` / `Tool.Error`), which the host yields after the hook;
67840
+ * a plugin cannot build one, and anything else in its place would turn the
67841
+ * call's failure into a defect.
67842
+ *
67843
+ * @see https://github.com/anomalyco/opencode/blob/v2.4.3/packages/core/src/tool.ts
67844
+ * @see https://github.com/anomalyco/opencode/blob/v2.4.3/packages/plugin/src/promise/adapter.ts
67845
+ * @see https://code.claude.com/docs/en/hooks
67846
+ */
67847
+ const POST_TOOL_USE_HELPER_LINES = [
67848
+ "const __rulesyncRunPostToolUseHook = async ({ command, input, seconds }) => {",
67849
+ " let result;",
67850
+ " try {",
67851
+ " result = await __rulesyncRunCommand({ command, input, seconds, echo: \"stdout\" });",
67852
+ " } catch (error) {",
67853
+ " console.error(\"[rulesync-hooks] postToolUse hook failed:\", error);",
67854
+ " return undefined;",
67855
+ " }",
67856
+ " if (result === null) {",
67857
+ " console.error(\"[rulesync-hooks] postToolUse hook timed out after \" + seconds + \"s\");",
67858
+ " return undefined;",
67859
+ " }",
67860
+ " const stderr = String(result.stderr ?? \"\");",
67861
+ " if (result.exitCode === 0) return undefined;",
67862
+ " if (result.exitCode === 2) return sanitizeBlockReason(stderr) || \"postToolUse hook exited with code 2.\";",
67863
+ " console.error(\"[rulesync-hooks] postToolUse hook exited with code \" + result.exitCode);",
67864
+ " return undefined;",
67865
+ "};",
67866
+ "// Like OpenCode's own `stringify`: a value JSON cannot hold (a BigInt, a cycle) falls back to `String`.",
67867
+ "const __rulesyncStringify = (value) => {",
67868
+ " try {",
67869
+ " return JSON.stringify(value) ?? String(value);",
67870
+ " } catch {",
67871
+ " return String(value);",
67872
+ " }",
67873
+ "};",
67874
+ "const __rulesyncAppendToolResult = (event, reason) => {",
67875
+ " if (!reason || event.status !== \"completed\") return;",
67876
+ " try {",
67877
+ " const text = \"PostToolUse hook feedback:\\n\" + reason;",
67878
+ " const result = event.result ?? {};",
67879
+ " const next = { ...result };",
67880
+ " if (typeof result.output === \"string\") next.output = result.output + \"\\n\\n\" + text;",
67881
+ " if (typeof result.content === \"string\") next.content = result.content + \"\\n\\n\" + text;",
67882
+ " else if (Array.isArray(result.content) && result.content.length > 0) next.content = [...result.content, { type: \"text\", text }];",
67883
+ " else {",
67884
+ " const output = result.output;",
67885
+ " const kept = output === undefined ? \"\" : typeof output === \"string\" ? output : __rulesyncStringify(output);",
67886
+ " next.content = [...(kept ? [{ type: \"text\", text: kept }] : []), { type: \"text\", text }];",
67887
+ " }",
67888
+ " event.result = next;",
67889
+ " } catch (error) {",
67890
+ " console.error(\"[rulesync-hooks] could not add postToolUse feedback to the tool result:\", error);",
67891
+ " }",
67892
+ "};"
67893
+ ];
67894
+ /** The statement that runs a `postToolUse` handler and passes its feedback on. */
67895
+ function buildPostToolUseRunStatement(handler) {
67896
+ const { command, input } = commandAndInputOf(handler);
67897
+ return `__rulesyncAppendToolResult(event, await __rulesyncRunPostToolUseHook({ command: ${command}, input: ${input}, seconds: ${handler.timeout} }));`;
67898
+ }
67899
+ /** Whether a handler is a `postToolUse` one, which reports back to the model. */
67900
+ function isPostToolUseHandler(handler) {
67901
+ return handler.payload?.name === "PostToolUse";
67902
+ }
66231
67903
  /** Emit one `ctx.<domain>.hook(name, ...)` registration. */
66232
67904
  function buildHookRegistrationLines(hookPoint, handlers) {
66233
67905
  const separator = hookPoint.indexOf(":");
@@ -66240,7 +67912,10 @@ function buildHookRegistrationLines(hookPoint, handlers) {
66240
67912
  handlers,
66241
67913
  cwdExpression: "directory"
66242
67914
  }).map((line) => ` ${line}`));
66243
- for (const handler of handlers) lines.push(...wrapInConditions(handler, buildRunStatement(handler), " "));
67915
+ for (const handler of handlers) {
67916
+ const statement = isPostToolUseHandler(handler) ? buildPostToolUseRunStatement(handler) : buildRunStatement(handler);
67917
+ lines.push(...wrapInConditions(handler, statement, " "));
67918
+ }
66244
67919
  lines.push(" }),");
66245
67920
  lines.push(");");
66246
67921
  return lines;
@@ -66489,10 +68164,12 @@ function buildSetupBodyLines({ hookHandlers, eventHandlers, stopHandlers }) {
66489
68164
  cwdExpression: "directory"
66490
68165
  })
66491
68166
  ];
66492
- if (stopHandlers.length > 0) {
68167
+ const usesPostToolUse = allHandlers.some(isPostToolUseHandler);
68168
+ if (stopHandlers.length > 0 || usesPostToolUse) {
66493
68169
  if (!allHandlers.some((handler) => handler.payload?.name === "PreToolUse")) body.push("", ...buildBlockReasonSanitizerLines({ typed: false }));
66494
- body.push("", ...STOP_HOOK_HELPER_LINES$1);
66495
68170
  }
68171
+ if (stopHandlers.length > 0) body.push("", ...STOP_HOOK_HELPER_LINES$1);
68172
+ if (usesPostToolUse) body.push("", ...POST_TOOL_USE_HELPER_LINES);
66496
68173
  if ([...hookHandlers.values()].some((handlers) => handlers.some((handler) => handler.matcher !== void 0))) body.push("", ...TOOL_MATCHER_HELPER_LINES);
66497
68174
  const usesContext = [...eventHandlers.values()].some(usesSessionContext);
66498
68175
  const registers = hookHandlers.size > 0 || usesContext || stopHandlers.length > 0;
@@ -75152,7 +76829,8 @@ var CodewhaleMcp = class CodewhaleMcp extends ToolMcp {
75152
76829
  }
75153
76830
  static async fromRulesyncMcp({ outputRoot = process.cwd(), rulesyncMcp, validate = true, global = false, logger }) {
75154
76831
  const paths = this.getSettablePaths({ global });
75155
- const existingContent = await readFileContentOrNull((0, node_path.join)(outputRoot, paths.relativeDirPath, paths.relativeFilePath));
76832
+ const filePath = (0, node_path.join)(outputRoot, paths.relativeDirPath, paths.relativeFilePath);
76833
+ const existingContent = await readFileContentOrNull(filePath);
75156
76834
  const json = existingContent === null ? {} : parseCodewhaleMcpConfig({
75157
76835
  fileContent: existingContent,
75158
76836
  relativePath: (0, node_path.join)(paths.relativeDirPath, paths.relativeFilePath)
@@ -75165,7 +76843,11 @@ var CodewhaleMcp = class CodewhaleMcp extends ToolMcp {
75165
76843
  [serversKey]: mcpServers
75166
76844
  };
75167
76845
  const fileContent = JSON.stringify(codewhaleConfig, null, 2);
75168
- if (!global && existingContent?.trim() !== fileContent.trim()) logger?.info(`Codewhale MCP: ${(0, node_path.join)(paths.relativeDirPath, paths.relativeFilePath)} changed, so Codewhale loads none of its servers until you run /mcp review and /mcp approve <digest> again.`);
76846
+ if (!global && !fileContentsEquivalent({
76847
+ filePath,
76848
+ expected: fileContent,
76849
+ existing: existingContent
76850
+ })) logger?.info(`Codewhale MCP: ${(0, node_path.join)(paths.relativeDirPath, paths.relativeFilePath)} changed, so Codewhale loads none of its servers until you run /mcp review and /mcp approve <digest> again.`);
75169
76851
  return new CodewhaleMcp({
75170
76852
  outputRoot,
75171
76853
  relativeDirPath: paths.relativeDirPath,
@@ -75798,7 +77480,7 @@ var CodexcliMcp = class CodexcliMcp extends ToolMcp {
75798
77480
  validate
75799
77481
  });
75800
77482
  }
75801
- static async fromRulesyncMcp({ outputRoot = process.cwd(), rulesyncMcp, validate = true, global = false }) {
77483
+ static async fromRulesyncMcp({ outputRoot = process.cwd(), rulesyncMcp, validate = true, global = false, preserveUnowned = false }) {
75802
77484
  const paths = this.getSettablePaths({ global });
75803
77485
  const configTomlFilePath = (0, node_path.join)(outputRoot, paths.relativeDirPath, paths.relativeFilePath);
75804
77486
  const configTomlFileContent = await readFileContentOrNull(configTomlFilePath) ?? "";
@@ -75809,7 +77491,7 @@ var CodexcliMcp = class CodexcliMcp extends ToolMcp {
75809
77491
  throw new Error(`Failed to parse existing Codex CLI config at ${configTomlFilePath}: ${formatError(error)}`, { cause: error });
75810
77492
  }
75811
77493
  const strippedMcpServers = rulesyncMcp.getMcpServers();
75812
- const converted = convertToCodexFormat(Object.fromEntries(Object.entries(strippedMcpServers).map(([serverName, serverConfig]) => {
77494
+ const mcpServersWithCodexFields = Object.fromEntries(Object.entries(strippedMcpServers).map(([serverName, serverConfig]) => {
75813
77495
  const rawServer = rulesyncMcp.getRawMcpServer(serverName);
75814
77496
  return [serverName, {
75815
77497
  ...serverConfig,
@@ -75818,7 +77500,8 @@ var CodexcliMcp = class CodexcliMcp extends ToolMcp {
75818
77500
  ...isRecord(rawServer) && typeof rawServer.experimentalEnvironment === "string" ? { experimentalEnvironment: rawServer.experimentalEnvironment } : {},
75819
77501
  ...isRecord(rawServer) && rawServer.codexcliTools !== void 0 ? { codexcliTools: rawServer.codexcliTools } : {}
75820
77502
  }];
75821
- })));
77503
+ }));
77504
+ const converted = convertToCodexFormat(mcpServersWithCodexFields);
75822
77505
  const filteredMcpServers = this.removeEmptyEntries(converted);
75823
77506
  for (const name of Object.keys(converted)) if (!Object.hasOwn(filteredMcpServers, name)) warnWithFallback(void 0, `MCP server "${name}" had no non-empty configuration and was dropped from the codex CLI config`);
75824
77507
  const existingMcpServers = isRecord(configToml["mcp_servers"]) ? configToml["mcp_servers"] : {};
@@ -75842,6 +77525,11 @@ var CodexcliMcp = class CodexcliMcp extends ToolMcp {
75842
77525
  }
75843
77526
  return [name, serverConfig];
75844
77527
  }));
77528
+ const declaredCodexNames = new Set(Object.keys(mcpServersWithCodexFields).map((name) => normalizeCodexMcpServerName(name).codexName));
77529
+ const outputMcpServers = preserveUnowned ? {
77530
+ ...Object.fromEntries(Object.entries(omitPrototypePollutionKeys(existingMcpServers)).filter(([name]) => !declaredCodexNames.has(name))),
77531
+ ...mergedMcpServers
77532
+ } : mergedMcpServers;
75845
77533
  return new CodexcliMcp({
75846
77534
  outputRoot,
75847
77535
  relativeDirPath: paths.relativeDirPath,
@@ -75850,7 +77538,7 @@ var CodexcliMcp = class CodexcliMcp extends ToolMcp {
75850
77538
  fileKey: sharedConfigFileKey(paths),
75851
77539
  feature: "mcp",
75852
77540
  existingContent: configTomlFileContent,
75853
- patch: { mcp_servers: Object.keys(mergedMcpServers).length > 0 ? mergedMcpServers : void 0 },
77541
+ patch: { mcp_servers: Object.keys(outputMcpServers).length > 0 ? outputMcpServers : void 0 },
75854
77542
  filePath: configTomlFilePath
75855
77543
  }),
75856
77544
  validate
@@ -87690,7 +89378,8 @@ var McpProcessor = class extends FeatureProcessor {
87690
89378
  }
87691
89379
  getFactory;
87692
89380
  featureOptions;
87693
- constructor({ outputRoot = process.cwd(), inputRoots, toolTarget, global = false, getFactory = defaultGetFactory, dryRun = false, logger, featureOptions }) {
89381
+ preserveUnownedMcpServers;
89382
+ constructor({ outputRoot = process.cwd(), inputRoots, toolTarget, global = false, getFactory = defaultGetFactory, dryRun = false, logger, featureOptions, preserveUnownedMcpServers = false }) {
87694
89383
  super({
87695
89384
  outputRoot,
87696
89385
  inputRoots,
@@ -87703,6 +89392,7 @@ var McpProcessor = class extends FeatureProcessor {
87703
89392
  this.global = global;
87704
89393
  this.getFactory = getFactory;
87705
89394
  this.featureOptions = featureOptions;
89395
+ this.preserveUnownedMcpServers = preserveUnownedMcpServers;
87706
89396
  }
87707
89397
  /**
87708
89398
  * Implementation of abstract method from FeatureProcessor
@@ -87784,7 +89474,8 @@ var McpProcessor = class extends FeatureProcessor {
87784
89474
  rulesyncMcp: filteredRulesyncMcp,
87785
89475
  global: this.global,
87786
89476
  logger: this.logger,
87787
- featureOptions: this.featureOptions
89477
+ featureOptions: this.featureOptions,
89478
+ preserveUnowned: this.preserveUnownedMcpServers
87788
89479
  }), ...await factory.class.getAuxiliaryFiles?.({
87789
89480
  outputRoot: this.outputRoot,
87790
89481
  global: this.global,
@@ -96076,20 +97767,32 @@ function restrictedByAllToolsCategory(config) {
96076
97767
  record: config.permission,
96077
97768
  key: "*"
96078
97769
  }) ?? {}).filter(([pattern, action]) => !/\s/.test(pattern) && (action === "deny" || action === "ask" && pattern !== "*")).map(([pattern]) => pattern).find((pattern) => {
96079
- const lowered = pattern.toLowerCase();
96080
- if (namesGitDirectory(lowered)) return true;
96081
- const matches = createShadowingRestrictionsTest([{
96082
- pattern: lowered.replace(/^\.?\//, ""),
96083
- fromAllToolsCategory: true
96084
- }]);
96085
- return GIT_WRITTEN_PATHS.some((path) => matches(path).length > 0);
97770
+ return carveOutCheckSpellings(pattern.toLowerCase()).some((spelling) => {
97771
+ if (namesGitDirectory(spelling)) return true;
97772
+ const matches = createShadowingRestrictionsTest([{
97773
+ pattern: spelling.replace(/^\.?\//, ""),
97774
+ fromAllToolsCategory: true
97775
+ }]);
97776
+ return GIT_WRITTEN_PATHS.some((path) => matches(path).length > 0);
97777
+ });
96086
97778
  });
96087
97779
  }
97780
+ function carveOutCheckSpellings(pattern) {
97781
+ const slashed = pattern.replaceAll("\\", "/");
97782
+ return slashed === pattern ? [pattern] : [pattern, slashed];
97783
+ }
96088
97784
  function isRestrictedInWorkspaceRootTable({ pattern, table }) {
96089
97785
  const readRules = {};
96090
97786
  for (const [tablePattern, access] of Object.entries(table)) {
96091
97787
  if (tablePattern === pattern) continue;
96092
- readRules[tablePattern] = access === "write" ? "allow" : "deny";
97788
+ if (access === "write") {
97789
+ readRules[tablePattern] = "allow";
97790
+ continue;
97791
+ }
97792
+ for (const spelling of carveOutCheckSpellings(tablePattern)) {
97793
+ if (spelling === pattern) return true;
97794
+ readRules[spelling] = "deny";
97795
+ }
96093
97796
  }
96094
97797
  return isCoveredByReadRestriction({
96095
97798
  pattern,
@@ -114970,7 +116673,8 @@ function buildRulesStrategy(ctx) {
114970
116673
  global,
114971
116674
  dryRun,
114972
116675
  logger,
114973
- language: config.getLanguage()
116676
+ language: config.getLanguage(),
116677
+ preserveUnmanagedContent: config.getPreserveUnmanagedRuleContent()
114974
116678
  }),
114975
116679
  loadSource: (p) => p.loadToolFiles(),
114976
116680
  toRulesync: (p, files) => p.convertToolFilesToRulesyncFiles(files),
@@ -115427,14 +117131,20 @@ function createFoldRootOverwriteWatch({ logger }) {
115427
117131
  writesByPath.set(path, writes);
115428
117132
  }
115429
117133
  },
115430
- report: () => {
117134
+ report: ({ skip } = {}) => {
117135
+ const warnedPaths = /* @__PURE__ */ new Set();
115431
117136
  for (const [path, writes] of writesByPath) {
115432
117137
  const last = writes.at(-1);
115433
117138
  if (last === void 0 || last.folds) continue;
115434
117139
  const fold = writes.findLast((write) => write.folds && write.content !== last.content);
115435
- if (fold === void 0) continue;
117140
+ if (fold === void 0 || skip?.({
117141
+ path,
117142
+ foldTarget: fold.target
117143
+ })) continue;
117144
+ warnedPaths.add(path);
115436
117145
  logger.warn(`Target '${last.target}' overwrites ${displayPath({ filePath: path })}, the file target '${fold.target}' folds every non-root rule into, so '${fold.target}' is left with the root rule only. The last target in config order wins a shared file: list '${fold.target}' after '${last.target}' to keep the folded content (see "Target Order and File Conflicts" in the configuration guide).`);
115437
117146
  }
117147
+ return warnedPaths;
115438
117148
  }
115439
117149
  };
115440
117150
  }
@@ -115607,7 +117317,8 @@ const RETIREMENT_SPECS = {
115607
117317
  ...params,
115608
117318
  simulateCommands: config.getSimulateCommands(),
115609
117319
  simulateSubagents: config.getSimulateSubagents(),
115610
- simulateSkills: config.getSimulateSkills()
117320
+ simulateSkills: config.getSimulateSkills(),
117321
+ preserveUnmanagedContent: config.getPreserveUnmanagedRuleContent()
115611
117322
  }),
115612
117323
  unownedPaths: ({ toolTarget, outputRoot }) => (toolRuleFactories.get(toolTarget)?.class.getSettablePaths().alternativeRoots ?? []).map((alt) => (0, node_path.resolve)(outputRoot, alt.relativeDirPath, alt.relativeFilePath))
115613
117324
  },
@@ -115731,14 +117442,23 @@ function scheduleRetiredTargetSweeps({ config, logger, sweepPlan, sourceLoadFail
115731
117442
  sweepPlan,
115732
117443
  unownedPaths
115733
117444
  }),
115734
- reportDeleted: () => processor.getRemovedPaths()
117445
+ reportDeleted: () => processor.getRemovedPaths(),
117446
+ reportWritten: () => processor.getSweepWrites()
115735
117447
  });
115736
117448
  } else {
115737
117449
  const processor = spec.create(params, config);
117450
+ const ownershipProcessor = config.getPreserveUnownedSkills() ? spec.create({
117451
+ ...params,
117452
+ logger: new ConsoleLogger({
117453
+ verbose: false,
117454
+ silent: true
117455
+ })
117456
+ }, config) : void 0;
115738
117457
  featurePlan.defer({
115739
117458
  sweep: () => sweepDirs({
115740
117459
  processor,
115741
- sweepPlan
117460
+ sweepPlan,
117461
+ ownershipProcessor
115742
117462
  }),
115743
117463
  reportDeleted: () => processor.getRemovedPaths()
115744
117464
  });
@@ -115755,18 +117475,36 @@ async function sweepFiles({ processor, sweepPlan, unownedPaths }) {
115755
117475
  const present = await Promise.all(candidates.map((f) => fileExists(f.getFilePath())));
115756
117476
  return await processor.removeOrphanAiFiles(candidates.filter((_, index) => present[index]), []) > 0;
115757
117477
  }
115758
- async function sweepDirs({ processor, sweepPlan }) {
115759
- return await processor.removeOrphanAiDirs(await sweepPlan.rejectClaimed({
117478
+ async function sweepDirs({ processor, sweepPlan, ownershipProcessor }) {
117479
+ const isOwned = ownershipProcessor ? await loadSourceOwnedPaths(ownershipProcessor) : void 0;
117480
+ return await processor.removeOrphanAiDirs((await sweepPlan.rejectClaimed({
115760
117481
  items: await processor.loadToolDirsToDelete(),
115761
117482
  getPath: (d) => d.getDirPath()
115762
- }), []) + await processor.removeOrphanFlatFiles({
115763
- existingFlatFiles: await sweepPlan.rejectClaimed({
117483
+ })).filter((d) => isOwned?.(d.getDirPath()) ?? true), []) + await processor.removeOrphanFlatFiles({
117484
+ existingFlatFiles: (await sweepPlan.rejectClaimed({
115764
117485
  items: await processor.loadToolFlatFilesToDelete(),
115765
117486
  getPath: (d) => d.getFlatFilePath() ?? d.getDirPath()
117487
+ })).filter((d) => {
117488
+ if (isOwned === void 0) return true;
117489
+ const flatFilePath = d.getFlatFilePath();
117490
+ return flatFilePath !== void 0 && isOwned(flatFilePath);
115766
117491
  }),
115767
117492
  generatedDirs: []
115768
117493
  }) > 0;
115769
117494
  }
117495
+ /**
117496
+ * The paths the current sources would write for the processor's target — each
117497
+ * directory, and the file a flattening tool writes in its place — as a
117498
+ * case-folded membership test, matching how the sweeps compare paths.
117499
+ */
117500
+ async function loadSourceOwnedPaths(processor) {
117501
+ const sourceDirs = await processor.convertRulesyncDirsToToolDirs(await processor.loadRulesyncDirs());
117502
+ const owned = new Set(sourceDirs.flatMap((d) => {
117503
+ const flatFilePath = d.getFlatFilePath();
117504
+ return [d.getDirPath(), ...flatFilePath === void 0 ? [] : [flatFilePath]].map((path) => caseFoldIdentity((0, node_path.resolve)(path)));
117505
+ }));
117506
+ return (path) => owned.has(caseFoldIdentity((0, node_path.resolve)(path)));
117507
+ }
115770
117508
  // src/lib/shared-file-derive.ts
115771
117509
  /**
115772
117510
  * The single declaration of the cross-feature write order for shared
@@ -115912,6 +117650,73 @@ const deriveSharedWriteSteps = () => {
115912
117650
  });
115913
117651
  return steps;
115914
117652
  };
117653
+ // src/lib/shared-root-selection-watch.ts
117654
+ const selectionKeyOf = (rulesyncFiles) => [...new Set(rulesyncFiles.map((file) => toPosixPath((0, node_path.join)(file.getRelativeDirPath(), file.getRelativeFilePath()))))].toSorted().join("\n");
117655
+ /**
117656
+ * Watches for targets that write the same root rule file (`AGENTS.md` for
117657
+ * `codexcli` and `opencode`, for example) with different contents because at
117658
+ * least one of them narrows its rules through the per-target `include` rules
117659
+ * option.
117660
+ *
117661
+ * A shared file holds one target's output only: the last target in config
117662
+ * order wins, as for any shared file. That is documented, but nothing in the
117663
+ * output said so when the targets disagree. The watch does not change what is
117664
+ * written; it names the file, the targets and the winner, once per file.
117665
+ *
117666
+ * It stays quiet when the file would be the same whoever writes it: many
117667
+ * targets keep non-root rules in their own directories, so a different
117668
+ * selection of non-root rules does not change the shared root file. It also
117669
+ * stays quiet when no sharing target's `include` actually leaves a rule out
117670
+ * (`["*"]`, a list naming every rule, or no option): a difference there comes
117671
+ * from the rules' own `targets` frontmatter, which has always worked this way.
117672
+ *
117673
+ * When a fold target's content is overwritten and that fold target folded at
117674
+ * least one non-root rule into it, the folded rules are lost because of the
117675
+ * target order: the fold-root overwrite warning names it with the reordering
117676
+ * that fixes it, and this watch skips the file (`skipPaths`), so each file
117677
+ * gets one warning. Only a fold target that folded nothing (its `include`
117678
+ * left it the root rule alone) is handed to this watch (`foldedNothing`).
117679
+ *
117680
+ * `observe` records what each target resolved and writes; `report` decides
117681
+ * once every target has been seen. Files are keyed by their resolved output
117682
+ * path, so each output root is compared on its own.
117683
+ */
117684
+ function createSharedRootSelectionWatch({ logger }) {
117685
+ const writesByPath = /* @__PURE__ */ new Map();
117686
+ return {
117687
+ observe: ({ toolTarget, includeNarrowed, rulesyncFiles, toolFiles }) => {
117688
+ for (const file of toolFiles) {
117689
+ if (!(file instanceof ToolRule) || !file.isRoot()) continue;
117690
+ const path = (0, node_path.resolve)(file.getFilePath());
117691
+ const writes = writesByPath.get(path) ?? [];
117692
+ if (!writes.some((write) => write.target === toolTarget)) writes.push({
117693
+ target: toolTarget,
117694
+ includeNarrowed,
117695
+ rulesyncFiles,
117696
+ content: file.getFileContent()
117697
+ });
117698
+ writesByPath.set(path, writes);
117699
+ }
117700
+ },
117701
+ foldedNothing: ({ path, target }) => {
117702
+ const write = writesByPath.get(path)?.find((entry) => entry.target === target);
117703
+ return write !== void 0 && write.rulesyncFiles.every((file) => file instanceof RulesyncRule && (file.getFrontmatter().root === true || file.getFrontmatter().localRoot === true));
117704
+ },
117705
+ report: ({ skipPaths } = {}) => {
117706
+ for (const [path, writes] of writesByPath) {
117707
+ if (skipPaths?.has(path)) continue;
117708
+ const last = writes.at(-1);
117709
+ if (last === void 0 || writes.length < 2) continue;
117710
+ if (writes.every((write) => write.content === last.content)) continue;
117711
+ if (!writes.some((write) => write.includeNarrowed())) continue;
117712
+ const lastKey = selectionKeyOf(last.rulesyncFiles);
117713
+ if (writes.every((write) => selectionKeyOf(write.rulesyncFiles) === lastKey)) continue;
117714
+ const targets = writes.map((write) => `'${write.target}'`).join(", ");
117715
+ logger.warn(`Targets ${targets} write ${displayPath({ filePath: path })} with different contents, and the \`include\` rules option narrows the rule selection of at least one of them. A shared file holds one target's output: '${last.target}' wins as the last target in config order. Give targets that share a file the same \`include\` list (or none); see "Selecting rules per target" in the configuration guide.`);
117716
+ }
117717
+ }
117718
+ };
117719
+ }
115915
117720
  // src/lib/generate.ts
115916
117721
  /**
115917
117722
  * The message to report when a run left some `.rulesync/` source unread, or
@@ -116012,29 +117817,30 @@ async function processDirFeatureGeneration(params) {
116012
117817
  ...d.getOtherFiles().map((f) => (0, node_path.join)(dirPath, f.relativeFilePathToDirPath))
116013
117818
  ];
116014
117819
  }) });
116015
- if (config.getDelete() && !processor.hasRulesyncSourceLoadFailure()) sweepPlan.defer({
116016
- sweep: async () => {
116017
- const existingToolDirs = await processor.loadToolDirsToDelete();
116018
- const orphanDirCount = await processor.removeOrphanAiDirs(await sweepPlan.rejectClaimed({
116019
- items: existingToolDirs,
116020
- getPath: (d) => d.getDirPath()
116021
- }), toolDirs);
116022
- const existingFlatFiles = await processor.loadToolFlatFilesToDelete();
116023
- const orphanFileCount = await processor.removeOrphanFlatFiles({
116024
- existingFlatFiles: await sweepPlan.rejectClaimed({
116025
- items: existingFlatFiles,
116026
- getPath: (d) => d.getFlatFilePath() ?? d.getDirPath()
116027
- }),
116028
- generatedDirs: toolDirs
116029
- });
116030
- const orphanInDirCount = await processor.removeOrphanFilesInAiDirs({
116031
- generatedDirs: toolDirs,
116032
- isClaimed: (path) => sweepPlan.isGeneratedExactly({ path })
116033
- });
116034
- return orphanDirCount + orphanFileCount + orphanInDirCount > 0;
116035
- },
116036
- reportDeleted: () => processor.getRemovedPaths()
116037
- });
117820
+ if (config.getDelete() && !processor.hasRulesyncSourceLoadFailure()) {
117821
+ const preserveUnownedSkills = config.getPreserveUnownedSkills();
117822
+ sweepPlan.defer({
117823
+ sweep: async () => {
117824
+ const orphanDirCount = preserveUnownedSkills ? 0 : await processor.removeOrphanAiDirs(await sweepPlan.rejectClaimed({
117825
+ items: await processor.loadToolDirsToDelete(),
117826
+ getPath: (d) => d.getDirPath()
117827
+ }), toolDirs);
117828
+ const orphanFileCount = preserveUnownedSkills ? 0 : await processor.removeOrphanFlatFiles({
117829
+ existingFlatFiles: await sweepPlan.rejectClaimed({
117830
+ items: await processor.loadToolFlatFilesToDelete(),
117831
+ getPath: (d) => d.getFlatFilePath() ?? d.getDirPath()
117832
+ }),
117833
+ generatedDirs: toolDirs
117834
+ });
117835
+ const orphanInDirCount = await processor.removeOrphanFilesInAiDirs({
117836
+ generatedDirs: toolDirs,
117837
+ isClaimed: (path) => sweepPlan.isGeneratedExactly({ path })
117838
+ });
117839
+ return orphanDirCount + orphanFileCount + orphanInDirCount > 0;
117840
+ },
117841
+ reportDeleted: () => processor.getRemovedPaths()
117842
+ });
117843
+ }
116038
117844
  return {
116039
117845
  count: totalCount,
116040
117846
  paths: allPaths,
@@ -116648,6 +118454,7 @@ async function generateRulesCore(params) {
116648
118454
  logger
116649
118455
  });
116650
118456
  const foldRootOverwriteWatch = createFoldRootOverwriteWatch({ logger });
118457
+ const sharedRootSelectionWatch = createSharedRootSelectionWatch({ logger });
116651
118458
  let fullRunSkills;
116652
118459
  const loadFullRunSkills = () => {
116653
118460
  fullRunSkills ??= loadConfigFileSkills({
@@ -116673,6 +118480,7 @@ async function generateRulesCore(params) {
116673
118480
  skills: processorSkills,
116674
118481
  featureOptions,
116675
118482
  delete: config.getDelete(),
118483
+ preserveUnmanagedContent: config.getPreserveUnmanagedRuleContent(),
116676
118484
  dryRun: config.isPreviewMode(),
116677
118485
  logger
116678
118486
  });
@@ -116687,7 +118495,7 @@ async function generateRulesCore(params) {
116687
118495
  const processor = createProcessor({
116688
118496
  toolTarget,
116689
118497
  outputRoot,
116690
- featureOptions: config.getFeatureOptions(toolTarget, "rules"),
118498
+ featureOptions: getRulesFeatureOptions(config, toolTarget),
116691
118499
  skills
116692
118500
  });
116693
118501
  const rulesyncFiles = await processor.loadRulesyncFiles();
@@ -116706,6 +118514,12 @@ async function generateRulesCore(params) {
116706
118514
  toolTarget,
116707
118515
  toolFiles
116708
118516
  });
118517
+ sharedRootSelectionWatch.observe({
118518
+ toolTarget,
118519
+ includeNarrowed: () => processor.didIncludeNarrowSelection(),
118520
+ rulesyncFiles,
118521
+ toolFiles
118522
+ });
116709
118523
  skippedRootFileCheck.observe({
116710
118524
  toolTarget,
116711
118525
  outputRoot,
@@ -116734,7 +118548,11 @@ async function generateRulesCore(params) {
116734
118548
  if (skippedResult.hasDiff) hasDiff = true;
116735
118549
  if (skippedResult.sourceLoadFailed) sourceLoadFailed = true;
116736
118550
  }
116737
- foldRootOverwriteWatch.report();
118551
+ const foldWarnedPaths = foldRootOverwriteWatch.report({ skip: ({ path, foldTarget }) => sharedRootSelectionWatch.foldedNothing({
118552
+ path,
118553
+ target: foldTarget
118554
+ }) });
118555
+ sharedRootSelectionWatch.report({ skipPaths: foldWarnedPaths });
116738
118556
  return {
116739
118557
  count: totalCount,
116740
118558
  paths: allPaths,
@@ -116851,7 +118669,8 @@ function generateMcpCore(params) {
116851
118669
  supportedTargets: McpProcessor.getToolTargets({ global: config.getGlobal() }),
116852
118670
  createProcessor: (options) => new McpProcessor({
116853
118671
  ...options,
116854
- featureOptions: config.getFeatureOptions(options.toolTarget, "mcp")
118672
+ featureOptions: config.getFeatureOptions(options.toolTarget, "mcp"),
118673
+ preserveUnownedMcpServers: config.getPreserveUnownedMcpServers()
116855
118674
  })
116856
118675
  });
116857
118676
  }
@@ -117129,7 +118948,8 @@ async function importRulesCore(params) {
117129
118948
  }),
117130
118949
  toolTarget: tool,
117131
118950
  global,
117132
- logger
118951
+ logger,
118952
+ preserveUnmanagedContent: config.getPreserveUnmanagedRuleContent()
117133
118953
  };
117134
118954
  const rulesProcessor = new RulesProcessor(baseParams);
117135
118955
  const toolFiles = await rulesProcessor.loadToolFiles();
@@ -117142,7 +118962,7 @@ async function importRulesCore(params) {
117142
118962
  ...baseParams,
117143
118963
  inputRoots: config.getInputRoots(),
117144
118964
  deriveSubprojectPathFromGlobs: config.getDeriveSubprojectPathFromGlobs(),
117145
- featureOptions: config.getFeatureOptions(tool, "rules")
118965
+ featureOptions: getRulesFeatureOptions(config, tool)
117146
118966
  }).warnForFoldImportDuplicationRisk();
117147
118967
  } catch (error) {
117148
118968
  logger.warn(`Skipped the ${tool} import duplication check: ${formatError(error)}`);
@@ -117923,6 +119743,12 @@ Object.defineProperty(exports, "SKILL_FILE_NAME", {
117923
119743
  return SKILL_FILE_NAME;
117924
119744
  }
117925
119745
  });
119746
+ Object.defineProperty(exports, "SOURCE_FILE_FEATURES", {
119747
+ enumerable: true,
119748
+ get: function() {
119749
+ return SOURCE_FILE_FEATURES;
119750
+ }
119751
+ });
117926
119752
  Object.defineProperty(exports, "SkillsProcessor", {
117927
119753
  enumerable: true,
117928
119754
  get: function() {
@@ -117977,6 +119803,18 @@ Object.defineProperty(exports, "assertLandingOutsideVcsMetadata", {
117977
119803
  return assertLandingOutsideVcsMetadata;
117978
119804
  }
117979
119805
  });
119806
+ Object.defineProperty(exports, "assertMatchingFilesFound", {
119807
+ enumerable: true,
119808
+ get: function() {
119809
+ return assertMatchingFilesFound;
119810
+ }
119811
+ });
119812
+ Object.defineProperty(exports, "assertMatchingSkillsFound", {
119813
+ enumerable: true,
119814
+ get: function() {
119815
+ return assertMatchingSkillsFound;
119816
+ }
119817
+ });
117980
119818
  Object.defineProperty(exports, "assertNoSymlinkBelowRoot", {
117981
119819
  enumerable: true,
117982
119820
  get: function() {
@@ -118007,12 +119845,48 @@ Object.defineProperty(exports, "assertWritablePathInsideRoot", {
118007
119845
  return assertWritablePathInsideRoot;
118008
119846
  }
118009
119847
  });
119848
+ Object.defineProperty(exports, "buildFileLockUpdate", {
119849
+ enumerable: true,
119850
+ get: function() {
119851
+ return buildFileLockUpdate;
119852
+ }
119853
+ });
119854
+ Object.defineProperty(exports, "buildLockUpdate", {
119855
+ enumerable: true,
119856
+ get: function() {
119857
+ return buildLockUpdate;
119858
+ }
119859
+ });
119860
+ Object.defineProperty(exports, "canReuseLockedFiles", {
119861
+ enumerable: true,
119862
+ get: function() {
119863
+ return canReuseLockedFiles;
119864
+ }
119865
+ });
119866
+ Object.defineProperty(exports, "canReuseLockedSkills", {
119867
+ enumerable: true,
119868
+ get: function() {
119869
+ return canReuseLockedSkills;
119870
+ }
119871
+ });
118010
119872
  Object.defineProperty(exports, "caseFoldIdentity", {
118011
119873
  enumerable: true,
118012
119874
  get: function() {
118013
119875
  return caseFoldIdentity;
118014
119876
  }
118015
119877
  });
119878
+ Object.defineProperty(exports, "checkLockedFilesAreValid", {
119879
+ enumerable: true,
119880
+ get: function() {
119881
+ return checkLockedFilesAreValid;
119882
+ }
119883
+ });
119884
+ Object.defineProperty(exports, "checkLockedSkillsAreValid", {
119885
+ enumerable: true,
119886
+ get: function() {
119887
+ return checkLockedSkillsAreValid;
119888
+ }
119889
+ });
118016
119890
  Object.defineProperty(exports, "checkPathTraversal", {
118017
119891
  enumerable: true,
118018
119892
  get: function() {
@@ -118025,6 +119899,18 @@ Object.defineProperty(exports, "classifyRemoteName", {
118025
119899
  return classifyRemoteName;
118026
119900
  }
118027
119901
  });
119902
+ Object.defineProperty(exports, "cleanPreviousCuratedFiles", {
119903
+ enumerable: true,
119904
+ get: function() {
119905
+ return cleanPreviousCuratedFiles;
119906
+ }
119907
+ });
119908
+ Object.defineProperty(exports, "cleanPreviousCuratedSkills", {
119909
+ enumerable: true,
119910
+ get: function() {
119911
+ return cleanPreviousCuratedSkills;
119912
+ }
119913
+ });
118028
119914
  Object.defineProperty(exports, "convertFromTool", {
118029
119915
  enumerable: true,
118030
119916
  get: function() {
@@ -118097,6 +119983,12 @@ Object.defineProperty(exports, "formatError", {
118097
119983
  return formatError;
118098
119984
  }
118099
119985
  });
119986
+ Object.defineProperty(exports, "formatInstalledCounts", {
119987
+ enumerable: true,
119988
+ get: function() {
119989
+ return formatInstalledCounts;
119990
+ }
119991
+ });
118100
119992
  Object.defineProperty(exports, "formatMegabytes", {
118101
119993
  enumerable: true,
118102
119994
  get: function() {
@@ -118115,12 +120007,36 @@ Object.defineProperty(exports, "generate", {
118115
120007
  return generate;
118116
120008
  }
118117
120009
  });
120010
+ Object.defineProperty(exports, "getCuratedFileFeatureRelativeDirPath", {
120011
+ enumerable: true,
120012
+ get: function() {
120013
+ return getCuratedFileFeatureRelativeDirPath;
120014
+ }
120015
+ });
120016
+ Object.defineProperty(exports, "getEmptySelectionFields", {
120017
+ enumerable: true,
120018
+ get: function() {
120019
+ return getEmptySelectionFields;
120020
+ }
120021
+ });
120022
+ Object.defineProperty(exports, "getFileFeatureNoun", {
120023
+ enumerable: true,
120024
+ get: function() {
120025
+ return getFileFeatureNoun;
120026
+ }
120027
+ });
118118
120028
  Object.defineProperty(exports, "getFileSizeAndExecutableBit", {
118119
120029
  enumerable: true,
118120
120030
  get: function() {
118121
120031
  return getFileSizeAndExecutableBit;
118122
120032
  }
118123
120033
  });
120034
+ Object.defineProperty(exports, "getFirstPathSeparatorIndex", {
120035
+ enumerable: true,
120036
+ get: function() {
120037
+ return getFirstPathSeparatorIndex;
120038
+ }
120039
+ });
118124
120040
  Object.defineProperty(exports, "getHomeDirectory", {
118125
120041
  enumerable: true,
118126
120042
  get: function() {
@@ -118133,6 +120049,36 @@ Object.defineProperty(exports, "getLocalSkillDirNames", {
118133
120049
  return getLocalSkillDirNames;
118134
120050
  }
118135
120051
  });
120052
+ Object.defineProperty(exports, "getLockKeyRepository", {
120053
+ enumerable: true,
120054
+ get: function() {
120055
+ return getLockKeyRepository;
120056
+ }
120057
+ });
120058
+ Object.defineProperty(exports, "getLockedFileFeatureState", {
120059
+ enumerable: true,
120060
+ get: function() {
120061
+ return getLockedFileFeatureState;
120062
+ }
120063
+ });
120064
+ Object.defineProperty(exports, "getLockedFileNames", {
120065
+ enumerable: true,
120066
+ get: function() {
120067
+ return getLockedFileNames;
120068
+ }
120069
+ });
120070
+ Object.defineProperty(exports, "getLockedSkillNames", {
120071
+ enumerable: true,
120072
+ get: function() {
120073
+ return getLockedSkillNames;
120074
+ }
120075
+ });
120076
+ Object.defineProperty(exports, "getLockedSource", {
120077
+ enumerable: true,
120078
+ get: function() {
120079
+ return getLockedSource;
120080
+ }
120081
+ });
118136
120082
  Object.defineProperty(exports, "getProcessorRegistryEntry", {
118137
120083
  enumerable: true,
118138
120084
  get: function() {
@@ -118145,18 +120091,36 @@ Object.defineProperty(exports, "getRulesyncSourceCandidates", {
118145
120091
  return getRulesyncSourceCandidates;
118146
120092
  }
118147
120093
  });
120094
+ Object.defineProperty(exports, "getSourceFilters", {
120095
+ enumerable: true,
120096
+ get: function() {
120097
+ return getSourceFilters;
120098
+ }
120099
+ });
118148
120100
  Object.defineProperty(exports, "getSourceTransport", {
118149
120101
  enumerable: true,
118150
120102
  get: function() {
118151
120103
  return getSourceTransport;
118152
120104
  }
118153
120105
  });
120106
+ Object.defineProperty(exports, "groupRemoteFilesBySkillRoot", {
120107
+ enumerable: true,
120108
+ get: function() {
120109
+ return groupRemoteFilesBySkillRoot;
120110
+ }
120111
+ });
118154
120112
  Object.defineProperty(exports, "groupSpellingsByCaseFoldedIdentity", {
118155
120113
  enumerable: true,
118156
120114
  get: function() {
118157
120115
  return groupSpellingsByCaseFoldedIdentity;
118158
120116
  }
118159
120117
  });
120118
+ Object.defineProperty(exports, "hasEmptySelection", {
120119
+ enumerable: true,
120120
+ get: function() {
120121
+ return hasEmptySelection;
120122
+ }
120123
+ });
118160
120124
  Object.defineProperty(exports, "hasEnclosingMarkOutsideKeycap", {
118161
120125
  enumerable: true,
118162
120126
  get: function() {
@@ -118211,6 +120175,12 @@ Object.defineProperty(exports, "isSymlink", {
118211
120175
  return isSymlink;
118212
120176
  }
118213
120177
  });
120178
+ Object.defineProperty(exports, "isWildcardSelection", {
120179
+ enumerable: true,
120180
+ get: function() {
120181
+ return isWildcardSelection;
120182
+ }
120183
+ });
118214
120184
  Object.defineProperty(exports, "listDirectoryEntryNames", {
118215
120185
  enumerable: true,
118216
120186
  get: function() {
@@ -118235,24 +120205,84 @@ Object.defineProperty(exports, "loadYaml", {
118235
120205
  return loadYaml;
118236
120206
  }
118237
120207
  });
120208
+ Object.defineProperty(exports, "lockedFileConfigMatches", {
120209
+ enumerable: true,
120210
+ get: function() {
120211
+ return lockedFileConfigMatches;
120212
+ }
120213
+ });
120214
+ Object.defineProperty(exports, "lockedRefMatchesDeclared", {
120215
+ enumerable: true,
120216
+ get: function() {
120217
+ return lockedRefMatchesDeclared;
120218
+ }
120219
+ });
120220
+ Object.defineProperty(exports, "lockedSkillConfigMatches", {
120221
+ enumerable: true,
120222
+ get: function() {
120223
+ return lockedSkillConfigMatches;
120224
+ }
120225
+ });
120226
+ Object.defineProperty(exports, "mapFileFeatures", {
120227
+ enumerable: true,
120228
+ get: function() {
120229
+ return mapFileFeatures;
120230
+ }
120231
+ });
118238
120232
  Object.defineProperty(exports, "mapWithConcurrency", {
118239
120233
  enumerable: true,
118240
120234
  get: function() {
118241
120235
  return mapWithConcurrency;
118242
120236
  }
118243
120237
  });
120238
+ Object.defineProperty(exports, "mergeFetchedWithLockedSkills", {
120239
+ enumerable: true,
120240
+ get: function() {
120241
+ return mergeFetchedWithLockedSkills;
120242
+ }
120243
+ });
118244
120244
  Object.defineProperty(exports, "mergeInputRootConfigs", {
118245
120245
  enumerable: true,
118246
120246
  get: function() {
118247
120247
  return mergeInputRootConfigs;
118248
120248
  }
118249
120249
  });
120250
+ Object.defineProperty(exports, "normalizeLockKey", {
120251
+ enumerable: true,
120252
+ get: function() {
120253
+ return normalizeLockKey;
120254
+ }
120255
+ });
118250
120256
  Object.defineProperty(exports, "normalizePosixDirPath", {
118251
120257
  enumerable: true,
118252
120258
  get: function() {
118253
120259
  return normalizePosixDirPath;
118254
120260
  }
118255
120261
  });
120262
+ Object.defineProperty(exports, "normalizeRuleFilterName", {
120263
+ enumerable: true,
120264
+ get: function() {
120265
+ return normalizeRuleFilterName;
120266
+ }
120267
+ });
120268
+ Object.defineProperty(exports, "normalizeRuleSelection", {
120269
+ enumerable: true,
120270
+ get: function() {
120271
+ return normalizeRuleSelection;
120272
+ }
120273
+ });
120274
+ Object.defineProperty(exports, "normalizeSkillSelection", {
120275
+ enumerable: true,
120276
+ get: function() {
120277
+ return normalizeSkillSelection;
120278
+ }
120279
+ });
120280
+ Object.defineProperty(exports, "normalizeSourceKey", {
120281
+ enumerable: true,
120282
+ get: function() {
120283
+ return normalizeSourceKey;
120284
+ }
120285
+ });
118256
120286
  Object.defineProperty(exports, "parseCommaSeparatedList", {
118257
120287
  enumerable: true,
118258
120288
  get: function() {
@@ -118271,6 +120301,12 @@ Object.defineProperty(exports, "parseJsonc", {
118271
120301
  return parseJsonc$6;
118272
120302
  }
118273
120303
  });
120304
+ Object.defineProperty(exports, "parseSource", {
120305
+ enumerable: true,
120306
+ get: function() {
120307
+ return parseSource;
120308
+ }
120309
+ });
118274
120310
  Object.defineProperty(exports, "pathEscapesRoot", {
118275
120311
  enumerable: true,
118276
120312
  get: function() {
@@ -118301,16 +120337,16 @@ Object.defineProperty(exports, "readFileContentOrNull", {
118301
120337
  return readFileContentOrNull;
118302
120338
  }
118303
120339
  });
118304
- Object.defineProperty(exports, "removeDirectory", {
120340
+ Object.defineProperty(exports, "readLockFile", {
118305
120341
  enumerable: true,
118306
120342
  get: function() {
118307
- return removeDirectory;
120343
+ return readLockFile;
118308
120344
  }
118309
120345
  });
118310
- Object.defineProperty(exports, "removeDirectoryStrict", {
120346
+ Object.defineProperty(exports, "removeDirectory", {
118311
120347
  enumerable: true,
118312
120348
  get: function() {
118313
- return removeDirectoryStrict;
120349
+ return removeDirectory;
118314
120350
  }
118315
120351
  });
118316
120352
  Object.defineProperty(exports, "removeFile", {
@@ -118319,12 +120355,6 @@ Object.defineProperty(exports, "removeFile", {
118319
120355
  return removeFile;
118320
120356
  }
118321
120357
  });
118322
- Object.defineProperty(exports, "removeFileStrict", {
118323
- enumerable: true,
118324
- get: function() {
118325
- return removeFileStrict;
118326
- }
118327
- });
118328
120358
  Object.defineProperty(exports, "removeFileWithoutFollowingSymlinks", {
118329
120359
  enumerable: true,
118330
120360
  get: function() {
@@ -118337,6 +120367,18 @@ Object.defineProperty(exports, "removeTempDirectory", {
118337
120367
  return removeTempDirectory;
118338
120368
  }
118339
120369
  });
120370
+ Object.defineProperty(exports, "renameLockedSource", {
120371
+ enumerable: true,
120372
+ get: function() {
120373
+ return renameLockedSource;
120374
+ }
120375
+ });
120376
+ Object.defineProperty(exports, "replaceCuratedFiles", {
120377
+ enumerable: true,
120378
+ get: function() {
120379
+ return replaceCuratedFiles;
120380
+ }
120381
+ });
118340
120382
  Object.defineProperty(exports, "resetRunWarningState", {
118341
120383
  enumerable: true,
118342
120384
  get: function() {
@@ -118349,6 +120391,18 @@ Object.defineProperty(exports, "resolveEffectiveInputRoots", {
118349
120391
  return resolveEffectiveInputRoots;
118350
120392
  }
118351
120393
  });
120394
+ Object.defineProperty(exports, "resolveFileFeaturePath", {
120395
+ enumerable: true,
120396
+ get: function() {
120397
+ return resolveFileFeaturePath;
120398
+ }
120399
+ });
120400
+ Object.defineProperty(exports, "resolveFileFeatureSourcePath", {
120401
+ enumerable: true,
120402
+ get: function() {
120403
+ return resolveFileFeatureSourcePath;
120404
+ }
120405
+ });
118352
120406
  Object.defineProperty(exports, "resolvePath", {
118353
120407
  enumerable: true,
118354
120408
  get: function() {
@@ -118361,6 +120415,24 @@ Object.defineProperty(exports, "resolveRulesyncSourceWritePath", {
118361
120415
  return resolveRulesyncSourceWritePath;
118362
120416
  }
118363
120417
  });
120418
+ Object.defineProperty(exports, "resolveSkillsPath", {
120419
+ enumerable: true,
120420
+ get: function() {
120421
+ return resolveSkillsPath;
120422
+ }
120423
+ });
120424
+ Object.defineProperty(exports, "resolveSkillsSourcePath", {
120425
+ enumerable: true,
120426
+ get: function() {
120427
+ return resolveSkillsSourcePath;
120428
+ }
120429
+ });
120430
+ Object.defineProperty(exports, "resolveSourceLockKeys", {
120431
+ enumerable: true,
120432
+ get: function() {
120433
+ return resolveSourceLockKeys;
120434
+ }
120435
+ });
118364
120436
  Object.defineProperty(exports, "resolvedRelativePath", {
118365
120437
  enumerable: true,
118366
120438
  get: function() {
@@ -118373,12 +120445,42 @@ Object.defineProperty(exports, "runWithDirectoryRollback", {
118373
120445
  return runWithDirectoryRollback;
118374
120446
  }
118375
120447
  });
120448
+ Object.defineProperty(exports, "selectDeclaredFiles", {
120449
+ enumerable: true,
120450
+ get: function() {
120451
+ return selectDeclaredFiles;
120452
+ }
120453
+ });
120454
+ Object.defineProperty(exports, "setLockedSource", {
120455
+ enumerable: true,
120456
+ get: function() {
120457
+ return setLockedSource;
120458
+ }
120459
+ });
118376
120460
  Object.defineProperty(exports, "shortenToWidth", {
118377
120461
  enumerable: true,
118378
120462
  get: function() {
118379
120463
  return shortenToWidth;
118380
120464
  }
118381
120465
  });
120466
+ Object.defineProperty(exports, "shouldSkipFile", {
120467
+ enumerable: true,
120468
+ get: function() {
120469
+ return shouldSkipFile;
120470
+ }
120471
+ });
120472
+ Object.defineProperty(exports, "shouldSkipSkill", {
120473
+ enumerable: true,
120474
+ get: function() {
120475
+ return shouldSkipSkill;
120476
+ }
120477
+ });
120478
+ Object.defineProperty(exports, "shouldUseRootFallback", {
120479
+ enumerable: true,
120480
+ get: function() {
120481
+ return shouldUseRootFallback;
120482
+ }
120483
+ });
118382
120484
  Object.defineProperty(exports, "splitPathSegments", {
118383
120485
  enumerable: true,
118384
120486
  get: function() {
@@ -118421,6 +120523,12 @@ Object.defineProperty(exports, "sweepRefusalReason", {
118421
120523
  return sweepRefusalReason;
118422
120524
  }
118423
120525
  });
120526
+ Object.defineProperty(exports, "toFileFeatureLockFields", {
120527
+ enumerable: true,
120528
+ get: function() {
120529
+ return toFileFeatureLockFields;
120530
+ }
120531
+ });
118424
120532
  Object.defineProperty(exports, "toInstructionBudgetFile", {
118425
120533
  enumerable: true,
118426
120534
  get: function() {
@@ -118469,3 +120577,15 @@ Object.defineProperty(exports, "writeFileContent", {
118469
120577
  return writeFileContent;
118470
120578
  }
118471
120579
  });
120580
+ Object.defineProperty(exports, "writeLockFile", {
120581
+ enumerable: true,
120582
+ get: function() {
120583
+ return writeLockFile;
120584
+ }
120585
+ });
120586
+ Object.defineProperty(exports, "writeSkillAndComputeIntegrity", {
120587
+ enumerable: true,
120588
+ get: function() {
120589
+ return writeSkillAndComputeIntegrity;
120590
+ }
120591
+ });