rulesync 43.16.0 → 43.17.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.
@@ -3270,6 +3270,8 @@ const ConfigParamsSchema = z.object({
3270
3270
  simulateSubagents: optional(z.boolean()),
3271
3271
  simulateSkills: optional(z.boolean()),
3272
3272
  preserveUnownedHooks: optional(z.boolean()),
3273
+ preserveUnmanagedRuleContent: optional(z.boolean()),
3274
+ preserveUnownedSkills: optional(z.boolean()),
3273
3275
  deriveSubprojectPathFromGlobs: optional(z.boolean()),
3274
3276
  flattenedCommandNaming: optional(FlattenedCommandNamingSchema),
3275
3277
  /**
@@ -3452,6 +3454,8 @@ var Config = class Config {
3452
3454
  simulateSubagents;
3453
3455
  simulateSkills;
3454
3456
  preserveUnownedHooks;
3457
+ preserveUnmanagedRuleContent;
3458
+ preserveUnownedSkills;
3455
3459
  deriveSubprojectPathFromGlobs;
3456
3460
  flattenedCommandNaming;
3457
3461
  language;
@@ -3480,7 +3484,7 @@ var Config = class Config {
3480
3484
  inputRoots;
3481
3485
  configFilePath;
3482
3486
  sources;
3483
- 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 }) {
3487
+ constructor({ outputRoots, targets, features, verbose, delete: isDelete, global, silent, simulateCommands, simulateSubagents, simulateSkills, preserveUnownedHooks, preserveUnmanagedRuleContent, preserveUnownedSkills, deriveSubprojectPathFromGlobs, flattenedCommandNaming, language, gitignoreTargetsOnly, gitignoreDestination, dryRun, check, retireTargets, retireFeatures, inputRoot, inputRoots, configFilePath, sources, configFileTargets, configFileSelection }) {
3484
3488
  assertTargetsFeaturesExclusive({
3485
3489
  targets,
3486
3490
  features
@@ -3514,6 +3518,8 @@ var Config = class Config {
3514
3518
  this.simulateSubagents = simulateSubagents ?? false;
3515
3519
  this.simulateSkills = simulateSkills ?? false;
3516
3520
  this.preserveUnownedHooks = preserveUnownedHooks ?? false;
3521
+ this.preserveUnmanagedRuleContent = preserveUnmanagedRuleContent === true;
3522
+ this.preserveUnownedSkills = preserveUnownedSkills === true;
3517
3523
  this.deriveSubprojectPathFromGlobs = deriveSubprojectPathFromGlobs ?? false;
3518
3524
  this.flattenedCommandNaming = flattenedCommandNaming ?? "basename";
3519
3525
  this.language = language;
@@ -3774,6 +3780,12 @@ var Config = class Config {
3774
3780
  getPreserveUnownedHooks() {
3775
3781
  return this.preserveUnownedHooks;
3776
3782
  }
3783
+ getPreserveUnmanagedRuleContent() {
3784
+ return this.preserveUnmanagedRuleContent;
3785
+ }
3786
+ getPreserveUnownedSkills() {
3787
+ return this.preserveUnownedSkills;
3788
+ }
3777
3789
  getFlattenedCommandNaming() {
3778
3790
  return this.flattenedCommandNaming;
3779
3791
  }
@@ -3839,6 +3851,24 @@ var Config = class Config {
3839
3851
  return this.dryRun || this.check;
3840
3852
  }
3841
3853
  };
3854
+ /**
3855
+ * The `rules` options for `target` in a run, with the `include` rule selection
3856
+ * always read from the configuration file. `--targets` replaces the object
3857
+ * form of `targets`, and with it every per-target option, but a target that
3858
+ * selects its rules there must not receive every rule just because it was
3859
+ * picked with `--targets`: that would write the rules the user deliberately
3860
+ * kept away from it.
3861
+ */
3862
+ function getRulesFeatureOptions(config, target) {
3863
+ const options = config.getFeatureOptions(target, "rules");
3864
+ if (options !== void 0 && "include" in options) return options;
3865
+ const configFileOptions = config.getConfigFileFeatureOptions(target, "rules");
3866
+ if (configFileOptions === void 0 || !("include" in configFileOptions)) return options;
3867
+ return {
3868
+ ...options,
3869
+ include: configFileOptions.include
3870
+ };
3871
+ }
3842
3872
  // src/config/config-resolver.ts
3843
3873
  const getDefaults = () => ({
3844
3874
  targets: ["agentsmd"],
@@ -3853,6 +3883,8 @@ const getDefaults = () => ({
3853
3883
  simulateSubagents: false,
3854
3884
  simulateSkills: false,
3855
3885
  preserveUnownedHooks: false,
3886
+ preserveUnmanagedRuleContent: false,
3887
+ preserveUnownedSkills: false,
3856
3888
  deriveSubprojectPathFromGlobs: false,
3857
3889
  flattenedCommandNaming: "basename",
3858
3890
  gitignoreTargetsOnly: true,
@@ -4191,6 +4223,16 @@ var ConfigResolver = class {
4191
4223
  file: configByFile.preserveUnownedHooks,
4192
4224
  fallback: getDefaults().preserveUnownedHooks
4193
4225
  }),
4226
+ preserveUnmanagedRuleContent: pick({
4227
+ cli: void 0,
4228
+ file: configByFile.preserveUnmanagedRuleContent,
4229
+ fallback: getDefaults().preserveUnmanagedRuleContent
4230
+ }),
4231
+ preserveUnownedSkills: pick({
4232
+ cli: void 0,
4233
+ file: configByFile.preserveUnownedSkills,
4234
+ fallback: getDefaults().preserveUnownedSkills
4235
+ }),
4194
4236
  deriveSubprojectPathFromGlobs: pick({
4195
4237
  cli: deriveSubprojectPathFromGlobs,
4196
4238
  file: configByFile.deriveSubprojectPathFromGlobs,
@@ -4432,6 +4474,33 @@ var AiFile = class {
4432
4474
  return false;
4433
4475
  }
4434
4476
  /**
4477
+ * The content the write phase puts on disk, given what the file holds now
4478
+ * (`null` when it does not exist) and the generated content (already ending
4479
+ * in a newline). Defaults to the generated content; override for a file
4480
+ * that keeps part of the existing content, such as a root rule file under
4481
+ * `preserveUnmanagedRuleContent`. `generate --check` compares the same
4482
+ * composed content, so content kept this way is never reported as drift.
4483
+ */
4484
+ composeWrittenContent({ generatedContent }) {
4485
+ return generatedContent;
4486
+ }
4487
+ /**
4488
+ * Whether removing this file (the `--delete` sweep, `retireTargets`) has to
4489
+ * look at what it holds first, through {@link composeContentAfterRemoval}.
4490
+ */
4491
+ keepsContentOnRemoval() {
4492
+ return false;
4493
+ }
4494
+ /**
4495
+ * How removing this file treats what it holds: `delete` it as a whole (the
4496
+ * default), `rewrite` it with rulesync's own content taken out, or `keep` it
4497
+ * untouched because none of it is rulesync's any more. Only consulted when
4498
+ * {@link keepsContentOnRemoval} is true.
4499
+ */
4500
+ composeContentAfterRemoval(_params) {
4501
+ return { action: "delete" };
4502
+ }
4503
+ /**
4435
4504
  * POSIX mode to apply after writing, or `undefined` to leave the default
4436
4505
  * alone. Override in subclasses whose output the tool executes directly
4437
4506
  * (e.g. Cline's hook scripts, which are spawned by path and therefore need
@@ -12340,6 +12409,1125 @@ function classifyRemoteName(name) {
12340
12409
  };
12341
12410
  return { kind: "safe" };
12342
12411
  }
12412
+ // src/types/git-provider.ts
12413
+ /**
12414
+ * Supported Git providers for fetch command
12415
+ */
12416
+ const ALL_GIT_PROVIDERS = ["github", "gitlab"];
12417
+ z.enum(ALL_GIT_PROVIDERS);
12418
+ // src/lib/source-parser.ts
12419
+ const GITHUB_HOSTS = /* @__PURE__ */ new Set(["github.com", "www.github.com"]);
12420
+ const GITLAB_HOSTS = /* @__PURE__ */ new Set(["gitlab.com", "www.gitlab.com"]);
12421
+ /**
12422
+ * Parse source specification into components
12423
+ * Supports:
12424
+ * - URL format: https://github.com/owner/repo, https://gitlab.com/owner/repo
12425
+ * - Prefix format: github:owner/repo, gitlab:owner/repo
12426
+ * - Shorthand format: owner/repo (defaults to GitHub)
12427
+ * - With ref: owner/repo@ref
12428
+ * - With path: owner/repo:path
12429
+ * - Combined: owner/repo@ref:path
12430
+ */
12431
+ function parseSource(source) {
12432
+ if (source.startsWith("http://") || source.startsWith("https://")) return parseUrl(source);
12433
+ if (source.includes(":") && !source.includes("://")) {
12434
+ const colonIndex = source.indexOf(":");
12435
+ const prefix = source.substring(0, colonIndex);
12436
+ const rest = source.substring(colonIndex + 1);
12437
+ const provider = ALL_GIT_PROVIDERS.find((p) => p === prefix);
12438
+ if (provider) return {
12439
+ provider,
12440
+ ...parseShorthand(rest)
12441
+ };
12442
+ return {
12443
+ provider: "github",
12444
+ ...parseShorthand(source)
12445
+ };
12446
+ }
12447
+ return {
12448
+ provider: "github",
12449
+ ...parseShorthand(source)
12450
+ };
12451
+ }
12452
+ /**
12453
+ * Parse URL format into components
12454
+ */
12455
+ function parseUrl(url) {
12456
+ const urlObj = new URL(url);
12457
+ const host = urlObj.hostname.toLowerCase();
12458
+ let provider;
12459
+ if (GITHUB_HOSTS.has(host)) provider = "github";
12460
+ else if (GITLAB_HOSTS.has(host)) provider = "gitlab";
12461
+ else throw new Error(`Unknown Git provider for host: ${host}. Supported providers: ${ALL_GIT_PROVIDERS.join(", ")}`);
12462
+ const segments = urlObj.pathname.split("/").filter(Boolean);
12463
+ if (segments.length < 2) throw new Error(`Invalid ${provider} URL: ${url}. Expected format: https://${host}/owner/repo`);
12464
+ const owner = segments[0];
12465
+ const repo = segments[1]?.replace(/\.git$/, "");
12466
+ if (segments.length > 2 && (segments[2] === "tree" || segments[2] === "blob")) {
12467
+ const decode = (segment) => decodeUrlSegment({
12468
+ segment,
12469
+ provider,
12470
+ url
12471
+ });
12472
+ const ref = segments[3] === void 0 ? void 0 : decode(segments[3]);
12473
+ const path = segments.length > 4 ? decode(segments.slice(4).join("/")) : void 0;
12474
+ if (path !== void 0 && path.split(/[\\/]/).includes("..")) throw new Error(`Invalid ${provider} URL: ${url}. Path must not contain ".." segments.`);
12475
+ return {
12476
+ provider,
12477
+ owner: owner ?? "",
12478
+ repo: repo ?? "",
12479
+ ref,
12480
+ path
12481
+ };
12482
+ }
12483
+ return {
12484
+ provider,
12485
+ owner: owner ?? "",
12486
+ repo: repo ?? ""
12487
+ };
12488
+ }
12489
+ /**
12490
+ * Percent-decode a URL path segment, turning a malformed escape (e.g. a lone
12491
+ * `%`) into an error that names the offending source.
12492
+ */
12493
+ function decodeUrlSegment({ segment, provider, url }) {
12494
+ try {
12495
+ return decodeURIComponent(segment);
12496
+ } catch (error) {
12497
+ if (error instanceof URIError) throw new Error(`Invalid ${provider} URL: ${url}. Malformed percent-encoding in ref or path.`, { cause: error });
12498
+ throw error;
12499
+ }
12500
+ }
12501
+ /**
12502
+ * Parse shorthand format (without provider prefix)
12503
+ */
12504
+ function parseShorthand(source) {
12505
+ let remaining = source;
12506
+ let path;
12507
+ let ref;
12508
+ const colonIndex = remaining.indexOf(":");
12509
+ if (colonIndex !== -1) {
12510
+ path = remaining.substring(colonIndex + 1);
12511
+ if (!path) throw new Error(`Invalid source: ${source}. Path cannot be empty after ":".`);
12512
+ remaining = remaining.substring(0, colonIndex);
12513
+ }
12514
+ const atIndex = remaining.indexOf("@");
12515
+ if (atIndex !== -1) {
12516
+ ref = remaining.substring(atIndex + 1);
12517
+ if (!ref) throw new Error(`Invalid source: ${source}. Ref cannot be empty after "@".`);
12518
+ remaining = remaining.substring(0, atIndex);
12519
+ }
12520
+ const slashIndex = remaining.indexOf("/");
12521
+ if (slashIndex === -1) throw new Error(`Invalid source: ${source}. Expected format: owner/repo, owner/repo@ref, or owner/repo:path`);
12522
+ const owner = remaining.substring(0, slashIndex);
12523
+ const repo = remaining.substring(slashIndex + 1);
12524
+ if (!owner || !repo) throw new Error(`Invalid source: ${source}. Both owner and repo are required.`);
12525
+ return {
12526
+ owner,
12527
+ repo,
12528
+ ref,
12529
+ path
12530
+ };
12531
+ }
12532
+ /**
12533
+ * Schema for a single locked skill entry with content integrity.
12534
+ */
12535
+ const LockedSkillSchema = z.object({ integrity: z.string() });
12536
+ /** Schema for a single locked rule entry with content integrity. */
12537
+ const LockedRuleSchema = z.object({ integrity: z.string() });
12538
+ /**
12539
+ * Schema for a single locked source entry.
12540
+ */
12541
+ const LockedSourceSchema = z.object({
12542
+ requestedRef: optional(z.string()),
12543
+ resolvedRef: z.string().check(refine((v) => /^[0-9a-f]{40}$/.test(v), "resolvedRef must be a 40-character hex SHA")),
12544
+ resolvedAt: optional(z.string()),
12545
+ skills: z.record(z.string(), LockedSkillSchema),
12546
+ /**
12547
+ * The normalized `skills` selection the entry was written for. Absent from
12548
+ * lockfiles written before the selection was recorded.
12549
+ */
12550
+ skillSelection: optional(z.array(z.string())),
12551
+ /**
12552
+ * The normalized path the skills were read from in the source. Absent from
12553
+ * lockfiles written before the path was recorded.
12554
+ */
12555
+ skillsPath: optional(z.string()),
12556
+ rules: optional(z.record(z.string(), LockedRuleSchema)),
12557
+ ruleSelection: optional(z.array(z.string())),
12558
+ rulesPath: optional(z.string()),
12559
+ resolvedRuleNames: optional(z.array(z.string())),
12560
+ commands: optional(z.record(z.string(), LockedRuleSchema)),
12561
+ commandSelection: optional(z.array(z.string())),
12562
+ commandsPath: optional(z.string()),
12563
+ resolvedCommandNames: optional(z.array(z.string())),
12564
+ subagents: optional(z.record(z.string(), LockedRuleSchema)),
12565
+ subagentSelection: optional(z.array(z.string())),
12566
+ subagentsPath: optional(z.string()),
12567
+ resolvedSubagentNames: optional(z.array(z.string()))
12568
+ });
12569
+ /**
12570
+ * Schema for the full lockfile (current version).
12571
+ */
12572
+ const SourcesLockSchema = z.object({
12573
+ lockfileVersion: z.number(),
12574
+ sources: z.record(z.string(), LockedSourceSchema)
12575
+ });
12576
+ /**
12577
+ * Schema for the legacy v0 lockfile format (skills as string array, no version field).
12578
+ */
12579
+ const LegacyLockedSourceSchema = z.object({
12580
+ resolvedRef: z.string(),
12581
+ skills: z.array(z.string())
12582
+ });
12583
+ const LegacySourcesLockSchema = z.object({ sources: z.record(z.string(), LegacyLockedSourceSchema) });
12584
+ /**
12585
+ * Migrate a legacy lockfile (string[] skills, no version) to the current format.
12586
+ * Skills get empty integrity since we can't compute it retroactively.
12587
+ */
12588
+ function migrateLegacyLock(params) {
12589
+ const { legacy, logger } = params;
12590
+ const sources = {};
12591
+ for (const [key, entry] of Object.entries(legacy.sources)) {
12592
+ const skills = {};
12593
+ for (const name of entry.skills) skills[name] = { integrity: "" };
12594
+ sources[key] = {
12595
+ resolvedRef: entry.resolvedRef,
12596
+ skills
12597
+ };
12598
+ }
12599
+ logger.info("Migrated legacy sources lockfile to version 1. Run 'rulesync install --update' to populate integrity hashes.");
12600
+ return {
12601
+ lockfileVersion: 1,
12602
+ sources
12603
+ };
12604
+ }
12605
+ /**
12606
+ * Create an empty lockfile structure.
12607
+ */
12608
+ function createEmptyLock() {
12609
+ return {
12610
+ lockfileVersion: 1,
12611
+ sources: {}
12612
+ };
12613
+ }
12614
+ /**
12615
+ * Read the lockfile from disk.
12616
+ * @returns The parsed lockfile, or an empty lockfile if it doesn't exist or is invalid.
12617
+ */
12618
+ async function readLockFile(params) {
12619
+ const { logger } = params;
12620
+ const lockPath = join(params.projectRoot, RULESYNC_SOURCES_LOCK_RELATIVE_FILE_PATH);
12621
+ if (!await fileExists(lockPath)) {
12622
+ logger.debug("No sources lockfile found, starting fresh.");
12623
+ return createEmptyLock();
12624
+ }
12625
+ try {
12626
+ const content = await readFileContent(lockPath);
12627
+ const data = JSON.parse(content);
12628
+ const result = SourcesLockSchema.safeParse(data);
12629
+ if (result.success) return result.data;
12630
+ const legacyResult = LegacySourcesLockSchema.safeParse(data);
12631
+ if (legacyResult.success) return migrateLegacyLock({
12632
+ legacy: legacyResult.data,
12633
+ logger
12634
+ });
12635
+ logger.warn(`Invalid sources lockfile format (${RULESYNC_SOURCES_LOCK_RELATIVE_FILE_PATH}). Starting fresh.`);
12636
+ return createEmptyLock();
12637
+ } catch {
12638
+ logger.warn(`Failed to read sources lockfile (${RULESYNC_SOURCES_LOCK_RELATIVE_FILE_PATH}). Starting fresh.`);
12639
+ return createEmptyLock();
12640
+ }
12641
+ }
12642
+ /**
12643
+ * Write the lockfile to disk.
12644
+ */
12645
+ async function writeLockFile(params) {
12646
+ const { logger } = params;
12647
+ const lockPath = join(params.projectRoot, RULESYNC_SOURCES_LOCK_RELATIVE_FILE_PATH);
12648
+ await writeFileContent(lockPath, JSON.stringify(params.lock, null, 2) + "\n");
12649
+ logger.debug(`Wrote sources lockfile to ${lockPath}`);
12650
+ }
12651
+ /**
12652
+ * Compute a SHA-256 integrity hash for a skill's contents.
12653
+ * Takes a sorted list of [relativePath, content] pairs to produce a deterministic hash.
12654
+ */
12655
+ function computeSkillIntegrity(files) {
12656
+ const hash = createHash("sha256");
12657
+ const sorted = files.toSorted((a, b) => a.path.localeCompare(b.path));
12658
+ for (const file of sorted) {
12659
+ hash.update(file.path);
12660
+ hash.update("\0");
12661
+ hash.update(file.content);
12662
+ hash.update("\0");
12663
+ }
12664
+ return `sha256-${hash.digest("hex")}`;
12665
+ }
12666
+ /** Compute a SHA-256 integrity hash for one rule file. */
12667
+ function computeRuleIntegrity(content) {
12668
+ const hash = createHash("sha256");
12669
+ hash.update(content);
12670
+ return `sha256-${hash.digest("hex")}`;
12671
+ }
12672
+ /**
12673
+ * Normalize a source key for consistent lockfile lookups.
12674
+ * Strips URL prefixes, provider prefixes, trailing slashes, .git suffix, and lowercases.
12675
+ */
12676
+ function normalizeSourceKey(source) {
12677
+ let key = source;
12678
+ for (const prefix of [
12679
+ "https://www.github.com/",
12680
+ "https://github.com/",
12681
+ "http://www.github.com/",
12682
+ "http://github.com/",
12683
+ "https://www.gitlab.com/",
12684
+ "https://gitlab.com/",
12685
+ "http://www.gitlab.com/",
12686
+ "http://gitlab.com/"
12687
+ ]) if (key.toLowerCase().startsWith(prefix)) {
12688
+ key = key.substring(prefix.length);
12689
+ break;
12690
+ }
12691
+ for (const provider of ["github:", "gitlab:"]) if (key.startsWith(provider)) {
12692
+ key = key.substring(provider.length);
12693
+ break;
12694
+ }
12695
+ key = key.replace(/\/+$/, "");
12696
+ key = key.replace(/\.git$/, "");
12697
+ key = key.toLowerCase();
12698
+ return key;
12699
+ }
12700
+ /**
12701
+ * Separates the repository part of a lock key from the qualifier that tells
12702
+ * apart several declared entries of the same repository.
12703
+ */
12704
+ const LOCK_KEY_QUALIFIER_SEPARATOR = "#";
12705
+ /**
12706
+ * Normalize a lock key for comparison. The repository part is normalized with
12707
+ * {@link normalizeSourceKey}; a qualifier (see {@link resolveSourceLockKeys})
12708
+ * is kept verbatim, since paths and refs are case-sensitive. A key without a
12709
+ * qualifier normalizes exactly as before qualifiers existed.
12710
+ */
12711
+ function normalizeLockKey(key) {
12712
+ const separatorIndex = key.indexOf(LOCK_KEY_QUALIFIER_SEPARATOR);
12713
+ if (separatorIndex === -1) return normalizeSourceKey(key);
12714
+ return normalizeSourceKey(key.slice(0, separatorIndex)) + key.slice(separatorIndex);
12715
+ }
12716
+ /** The normalized repository part of a lock key, without its qualifier. */
12717
+ function getLockKeyRepository(key) {
12718
+ const separatorIndex = key.indexOf(LOCK_KEY_QUALIFIER_SEPARATOR);
12719
+ return normalizeSourceKey(separatorIndex === -1 ? key : key.slice(0, separatorIndex));
12720
+ }
12721
+ function encodeLockKeyQualifierValue(value) {
12722
+ return encodeURIComponent(value).replace(/%2F/gi, "/");
12723
+ }
12724
+ function normalizeLockKeyDirPath(dirPath) {
12725
+ return normalizePosixDirPath(dirPath);
12726
+ }
12727
+ /**
12728
+ * The location fields of a declared entry that tell it apart from other
12729
+ * entries of the same repository, as a lock key qualifier (empty when the
12730
+ * entry declares none of them).
12731
+ */
12732
+ function buildLockKeyQualifier(sourceEntry) {
12733
+ const parts = [];
12734
+ if (sourceEntry.path !== void 0) parts.push(`path=${encodeLockKeyQualifierValue(normalizeLockKeyDirPath(sourceEntry.path))}`);
12735
+ for (const field of [
12736
+ "rulesPath",
12737
+ "commandsPath",
12738
+ "subagentsPath"
12739
+ ]) {
12740
+ const dirPath = sourceEntry[field];
12741
+ if (dirPath !== void 0) parts.push(`${field}=${encodeLockKeyQualifierValue(normalizeLockKeyDirPath(dirPath))}`);
12742
+ }
12743
+ if (sourceEntry.ref !== void 0) parts.push(`ref=${encodeLockKeyQualifierValue(sourceEntry.ref)}`);
12744
+ return parts.join("&");
12745
+ }
12746
+ /**
12747
+ * The key each declared source's lock entry is stored under, index-aligned
12748
+ * with `sources`.
12749
+ *
12750
+ * A repository declared once keeps the bare {@link normalizeSourceKey} key,
12751
+ * so lockfiles written before multiple entries per repository were supported
12752
+ * stay valid unchanged. Only when several git/GitHub entries normalize to the
12753
+ * same repository does each of them get a qualified key
12754
+ * (`owner/repo#path=plugins/team-a/skills&ref=main`) built from its `path`,
12755
+ * `rulesPath`, `commandsPath`, `subagentsPath` and `ref`, so each entry keeps its own lock entry, its own
12756
+ * curated-artifact cleanup and its own `--frozen` check. An entry declaring
12757
+ * none of those fields keeps the bare key, and entries declaring the same
12758
+ * location are told apart by their order (`entry=2`, `entry=3`, ...).
12759
+ *
12760
+ * npm-transport sources are locked in a separate lockfile by package name;
12761
+ * their key here is unused and left bare.
12762
+ */
12763
+ function resolveSourceLockKeys(sources) {
12764
+ const bareKeys = sources.map((sourceEntry) => normalizeSourceKey(sourceEntry.source));
12765
+ const repositoryCounts = /* @__PURE__ */ new Map();
12766
+ sources.forEach((sourceEntry, index) => {
12767
+ if (getSourceTransport(sourceEntry) === "npm") return;
12768
+ const bareKey = bareKeys[index] ?? "";
12769
+ repositoryCounts.set(bareKey, (repositoryCounts.get(bareKey) ?? 0) + 1);
12770
+ });
12771
+ const qualifierCounts = /* @__PURE__ */ new Map();
12772
+ return sources.map((sourceEntry, index) => {
12773
+ const bareKey = bareKeys[index] ?? "";
12774
+ if (getSourceTransport(sourceEntry) === "npm" || (repositoryCounts.get(bareKey) ?? 0) < 2) return bareKey;
12775
+ const qualifier = buildLockKeyQualifier(sourceEntry);
12776
+ const base = qualifier === "" ? bareKey : `${bareKey}${LOCK_KEY_QUALIFIER_SEPARATOR}${qualifier}`;
12777
+ const occurrence = (qualifierCounts.get(base) ?? 0) + 1;
12778
+ qualifierCounts.set(base, occurrence);
12779
+ if (occurrence === 1) return base;
12780
+ return `${base}${qualifier === "" ? LOCK_KEY_QUALIFIER_SEPARATOR : "&"}entry=${occurrence}`;
12781
+ });
12782
+ }
12783
+ /**
12784
+ * Move a lock entry to another key, keeping its position-independent content
12785
+ * unchanged (immutable — returns a fresh lock object).
12786
+ */
12787
+ function renameLockedSource(params) {
12788
+ const { lock, fromKey, toKey } = params;
12789
+ const entry = getLockedSource(lock, fromKey);
12790
+ if (entry === void 0) return lock;
12791
+ const normalizedFrom = normalizeLockKey(fromKey);
12792
+ const remaining = {};
12793
+ for (const [key, value] of Object.entries(lock.sources)) if (normalizeLockKey(key) !== normalizedFrom) remaining[key] = value;
12794
+ return setLockedSource({
12795
+ lockfileVersion: lock.lockfileVersion,
12796
+ sources: remaining
12797
+ }, toKey, entry);
12798
+ }
12799
+ /**
12800
+ * Get the locked entry for a lock key (see {@link resolveSourceLockKeys}),
12801
+ * if it exists.
12802
+ */
12803
+ function getLockedSource(lock, lockKey) {
12804
+ const normalized = normalizeLockKey(lockKey);
12805
+ for (const [key, value] of Object.entries(lock.sources)) if (normalizeLockKey(key) === normalized) return value;
12806
+ }
12807
+ /**
12808
+ * Set (or update) a locked entry for a lock key.
12809
+ */
12810
+ function setLockedSource(lock, lockKey, entry) {
12811
+ const normalized = normalizeLockKey(lockKey);
12812
+ const filteredSources = {};
12813
+ for (const [key, value] of Object.entries(lock.sources)) if (normalizeLockKey(key) !== normalized) filteredSources[key] = value;
12814
+ return {
12815
+ lockfileVersion: lock.lockfileVersion,
12816
+ sources: {
12817
+ ...filteredSources,
12818
+ [normalized]: entry
12819
+ }
12820
+ };
12821
+ }
12822
+ /**
12823
+ * Get the skill names from a locked source entry.
12824
+ */
12825
+ function getLockedSkillNames(entry) {
12826
+ return Object.keys(entry.skills);
12827
+ }
12828
+ /**
12829
+ * The features a source installs as one Markdown file per item, each locked
12830
+ * with the same four fields (`rules` / `ruleSelection` / `rulesPath` /
12831
+ * `resolvedRuleNames`, and the command and subagent counterparts).
12832
+ */
12833
+ const SOURCE_FILE_FEATURES = [
12834
+ "rules",
12835
+ "commands",
12836
+ "subagents"
12837
+ ];
12838
+ /** Build a value for each per-file feature. */
12839
+ function mapFileFeatures(map) {
12840
+ return {
12841
+ rules: map("rules"),
12842
+ commands: map("commands"),
12843
+ subagents: map("subagents")
12844
+ };
12845
+ }
12846
+ /** Read one per-file feature's lock fields from a lock entry. */
12847
+ function getLockedFileFeatureState(entry, feature) {
12848
+ switch (feature) {
12849
+ case "rules": return {
12850
+ items: entry.rules,
12851
+ selection: entry.ruleSelection,
12852
+ path: entry.rulesPath,
12853
+ resolvedNames: entry.resolvedRuleNames
12854
+ };
12855
+ case "commands": return {
12856
+ items: entry.commands,
12857
+ selection: entry.commandSelection,
12858
+ path: entry.commandsPath,
12859
+ resolvedNames: entry.resolvedCommandNames
12860
+ };
12861
+ case "subagents": return {
12862
+ items: entry.subagents,
12863
+ selection: entry.subagentSelection,
12864
+ path: entry.subagentsPath,
12865
+ resolvedNames: entry.resolvedSubagentNames
12866
+ };
12867
+ }
12868
+ }
12869
+ /** The lock fields that record one per-file feature's state. */
12870
+ function toFileFeatureLockFields(feature, state) {
12871
+ switch (feature) {
12872
+ case "rules": return {
12873
+ rules: state.items,
12874
+ ruleSelection: state.selection,
12875
+ rulesPath: state.path,
12876
+ resolvedRuleNames: state.resolvedNames
12877
+ };
12878
+ case "commands": return {
12879
+ commands: state.items,
12880
+ commandSelection: state.selection,
12881
+ commandsPath: state.path,
12882
+ resolvedCommandNames: state.resolvedNames
12883
+ };
12884
+ case "subagents": return {
12885
+ subagents: state.items,
12886
+ subagentSelection: state.selection,
12887
+ subagentsPath: state.path,
12888
+ resolvedSubagentNames: state.resolvedNames
12889
+ };
12890
+ }
12891
+ }
12892
+ /** The item names one per-file feature of a lock entry locks. */
12893
+ function getLockedFileNames(entry, feature) {
12894
+ return Object.keys(getLockedFileFeatureState(entry, feature).items ?? {});
12895
+ }
12896
+ // src/lib/sources-artifacts.ts
12897
+ const FILE_FEATURE_SPECS = {
12898
+ rules: {
12899
+ noun: "rule",
12900
+ pathField: "rulesPath",
12901
+ defaultPath: "rules",
12902
+ curatedRelativeDirPath: RULESYNC_CURATED_RULES_RELATIVE_DIR_PATH
12903
+ },
12904
+ commands: {
12905
+ noun: "command",
12906
+ pathField: "commandsPath",
12907
+ defaultPath: "commands",
12908
+ curatedRelativeDirPath: RULESYNC_CURATED_COMMANDS_RELATIVE_DIR_PATH
12909
+ },
12910
+ subagents: {
12911
+ noun: "subagent",
12912
+ pathField: "subagentsPath",
12913
+ defaultPath: "subagents",
12914
+ curatedRelativeDirPath: RULESYNC_CURATED_SUBAGENTS_RELATIVE_DIR_PATH
12915
+ }
12916
+ };
12917
+ /** The singular noun of a per-file feature, for messages (`rule`, `command`, `subagent`). */
12918
+ function getFileFeatureNoun(feature) {
12919
+ return FILE_FEATURE_SPECS[feature].noun;
12920
+ }
12921
+ /** Where a per-file feature's fetched copies live, relative to the project root. */
12922
+ function getCuratedFileFeatureRelativeDirPath(feature) {
12923
+ return FILE_FEATURE_SPECS[feature].curatedRelativeDirPath;
12924
+ }
12925
+ /** Every selection field a source entry may declare. */
12926
+ const SOURCE_SELECTION_FIELDS = ["skills", ...SOURCE_FILE_FEATURES];
12927
+ function getSourceFilters(sourceEntry) {
12928
+ const hasExplicitFeature = SOURCE_SELECTION_FIELDS.some((field) => sourceEntry[field] !== void 0);
12929
+ return {
12930
+ skills: sourceEntry.skills ?? (hasExplicitFeature ? void 0 : ["*"]),
12931
+ rules: sourceEntry.rules,
12932
+ commands: sourceEntry.commands,
12933
+ subagents: sourceEntry.subagents
12934
+ };
12935
+ }
12936
+ /** The selection fields a source entry declares as an empty list. */
12937
+ function getEmptySelectionFields(sourceEntry) {
12938
+ return SOURCE_SELECTION_FIELDS.filter((field) => sourceEntry[field]?.length === 0);
12939
+ }
12940
+ function hasEmptySelection(sourceEntry) {
12941
+ return getEmptySelectionFields(sourceEntry).length > 0;
12942
+ }
12943
+ /**
12944
+ * Whether a lock entry was written for the ref the manifest declares now. A
12945
+ * declared ref that differs from the locked `requestedRef` is resolved afresh
12946
+ * (and fails `--frozen`), so editing the ref in the manifest cannot keep
12947
+ * installing the commit resolved for the old one.
12948
+ *
12949
+ * An entry that records no `requestedRef` (a migrated legacy lock, or a
12950
+ * hand-written one) still matches: it says nothing that contradicts the
12951
+ * declared ref, and refusing it would gain nothing, since whoever can edit the
12952
+ * lock can also write any `requestedRef`. The declared ref is recorded on it
12953
+ * the next time the entry is written.
12954
+ *
12955
+ * A source that declares no ref also matches: its locked `requestedRef` is the
12956
+ * default branch it resolved to, which cannot be told apart from a ref that
12957
+ * was dropped from the manifest without asking the remote.
12958
+ */
12959
+ function lockedRefMatchesDeclared(params) {
12960
+ const { locked, declaredRef } = params;
12961
+ return declaredRef === void 0 || locked.requestedRef === void 0 || locked.requestedRef === declaredRef;
12962
+ }
12963
+ /**
12964
+ * Check that every locked skill is on disk in the curated directory with the
12965
+ * content the lockfile records: its files hash to the locked integrity, so a
12966
+ * skill edited, extended or trimmed in place is fetched again, as a rule is.
12967
+ *
12968
+ * The locked hash keys each file by the path the transport reported. The
12969
+ * GitHub API and npm report POSIX paths, while the git transport reports
12970
+ * platform paths, so on Windows both spellings are accepted.
12971
+ *
12972
+ * Only presence is checked for a skill whose content this entry cannot vouch
12973
+ * for: one an earlier source already installed under the same name (the
12974
+ * curated directory then holds that source's copy, which wins), and one locked
12975
+ * with an empty integrity by the migration from the legacy lockfile format.
12976
+ */
12977
+ async function checkLockedSkillsAreValid(params) {
12978
+ const { curatedDir, skills, presenceOnlySkillNames = /* @__PURE__ */ new Set() } = params;
12979
+ for (const [name, entry] of Object.entries(skills)) {
12980
+ const skillDir = join(curatedDir, name);
12981
+ if (!await directoryExists(skillDir)) return false;
12982
+ if (entry.integrity === "" || presenceOnlySkillNames.has(name)) continue;
12983
+ const files = await Promise.all((await listFilePathsRecursively(skillDir, { includeHidden: true })).map(async (relativePath) => ({
12984
+ relativePath,
12985
+ content: await readFileContent(join(skillDir, relativePath))
12986
+ })));
12987
+ if (!(sep === "/" ? [(relativePath) => relativePath] : [toPosixPath, (relativePath) => relativePath]).some((spell) => computeSkillIntegrity(files.map((file) => ({
12988
+ path: spell(file.relativePath),
12989
+ content: file.content
12990
+ }))) === entry.integrity)) return false;
12991
+ }
12992
+ return true;
12993
+ }
12994
+ /**
12995
+ * Check that every item one per-file feature of a lock entry locks is on disk
12996
+ * in its curated directory with the locked content. A locked name that is not
12997
+ * a valid file name (a hand-edited lockfile) never counts as installed, so it
12998
+ * is fetched again rather than read from outside the curated directory.
12999
+ */
13000
+ async function checkLockedFilesAreValid(params) {
13001
+ const { items } = getLockedFileFeatureState(params.locked, params.feature);
13002
+ for (const [name, entry] of Object.entries(items ?? {})) {
13003
+ if (!isValidRuleName(name)) return false;
13004
+ const filePath = join(params.curatedDir, `${name}.md`);
13005
+ if (!await fileExists(filePath)) return false;
13006
+ if (computeRuleIntegrity(await readFileContent(filePath)) !== entry.integrity) return false;
13007
+ }
13008
+ return true;
13009
+ }
13010
+ async function canReuseLockedFiles(params) {
13011
+ const { feature, locked, sourceEntry, lockedNames, localNames, alreadyFetchedNames, curatedDir } = params;
13012
+ if (!lockedFileConfigMatches({
13013
+ feature,
13014
+ locked,
13015
+ sourceEntry
13016
+ })) return false;
13017
+ const { resolvedNames } = getLockedFileFeatureState(locked, feature);
13018
+ if (resolvedNames === void 0) return false;
13019
+ const availableNames = /* @__PURE__ */ new Set([
13020
+ ...lockedNames,
13021
+ ...localNames,
13022
+ ...alreadyFetchedNames
13023
+ ]);
13024
+ if (resolvedNames.some((name) => !availableNames.has(name))) return false;
13025
+ if (lockedNames.some((name) => localNames.has(name) || alreadyFetchedNames.has(name))) return false;
13026
+ return checkLockedFilesAreValid({
13027
+ feature,
13028
+ curatedDir,
13029
+ locked
13030
+ });
13031
+ }
13032
+ /**
13033
+ * Remove previously curated skill directories for a source before re-fetching.
13034
+ * Validates that each path resolves within the curated directory to prevent traversal.
13035
+ */
13036
+ async function cleanPreviousCuratedSkills(params) {
13037
+ const { curatedDir, lockedSkillNames, protectedSkillNames = /* @__PURE__ */ new Set(), logger } = params;
13038
+ const resolvedCuratedDir = resolve(curatedDir);
13039
+ for (const prevSkill of lockedSkillNames) {
13040
+ if (protectedSkillNames.has(prevSkill)) continue;
13041
+ const prevDir = join(curatedDir, prevSkill);
13042
+ if (!resolve(prevDir).startsWith(resolvedCuratedDir + sep)) {
13043
+ logger.warn(`Skipping removal of ${quoteForLog(prevSkill)}: resolved path is outside the curated directory.`);
13044
+ continue;
13045
+ }
13046
+ if (await directoryExists(prevDir)) await removeDirectoryStrict(prevDir);
13047
+ }
13048
+ }
13049
+ /**
13050
+ * Whether `<name>.md` resolves to a file directly inside `curatedDir`. Locked
13051
+ * names come from the lockfile, which can be edited by hand, so they are
13052
+ * checked before anything is read, removed or written under them.
13053
+ */
13054
+ function isCuratedFileInside(params) {
13055
+ const resolvedCuratedDir = resolve(params.curatedDir);
13056
+ return resolve(join(params.curatedDir, `${params.name}.md`)).startsWith(resolvedCuratedDir + sep);
13057
+ }
13058
+ /**
13059
+ * Remove a source's previously curated files (rules, commands or subagents)
13060
+ * before re-fetching. Validates that each path resolves within the curated
13061
+ * directory to prevent traversal.
13062
+ */
13063
+ async function cleanPreviousCuratedFiles(params) {
13064
+ const { curatedDir, lockedNames, protectedNames, logger } = params;
13065
+ for (const prevName of lockedNames) {
13066
+ if (protectedNames.has(prevName)) continue;
13067
+ if (!isCuratedFileInside({
13068
+ curatedDir,
13069
+ name: prevName
13070
+ })) {
13071
+ logger.warn(`Skipping removal of ${quoteForLog(prevName)}: resolved path is outside the curated directory.`);
13072
+ continue;
13073
+ }
13074
+ const prevFile = join(curatedDir, `${prevName}.md`);
13075
+ if (await fileExists(prevFile)) await removeFileStrict(prevFile);
13076
+ }
13077
+ }
13078
+ async function replaceCuratedFiles(params) {
13079
+ const { feature, files, curatedDir, locked, lockedNames, resolvedRef, sourceKey, localNames, alreadyFetchedNames, compareLockedIntegrity, frozen, logger } = params;
13080
+ const protectedNames = alreadyFetchedNames;
13081
+ const installableFiles = files.filter((file) => !shouldSkipFile({
13082
+ feature,
13083
+ name: file.name,
13084
+ sourceKey,
13085
+ localNames,
13086
+ alreadyFetchedNames,
13087
+ logger
13088
+ }));
13089
+ const previousContents = /* @__PURE__ */ new Map();
13090
+ for (const name of lockedNames) {
13091
+ if (protectedNames.has(name) || !isCuratedFileInside({
13092
+ curatedDir,
13093
+ name
13094
+ })) continue;
13095
+ const path = join(curatedDir, `${name}.md`);
13096
+ if (await fileExists(path)) previousContents.set(name, await readFileContent(path));
13097
+ }
13098
+ try {
13099
+ await cleanPreviousCuratedFiles({
13100
+ curatedDir,
13101
+ lockedNames,
13102
+ protectedNames,
13103
+ logger
13104
+ });
13105
+ const fetchedFiles = {};
13106
+ for (const file of installableFiles) fetchedFiles[file.name] = await writeFeatureFileAndComputeIntegrity({
13107
+ feature,
13108
+ file,
13109
+ curatedDir,
13110
+ locked,
13111
+ resolvedRef,
13112
+ sourceKey,
13113
+ compareLockedIntegrity,
13114
+ frozen,
13115
+ logger
13116
+ });
13117
+ return fetchedFiles;
13118
+ } catch (error) {
13119
+ for (const file of installableFiles) await removeFileStrict(join(curatedDir, `${file.name}.md`));
13120
+ for (const [name, content] of previousContents) await writeFileContent(join(curatedDir, `${name}.md`), content);
13121
+ throw error;
13122
+ }
13123
+ }
13124
+ /**
13125
+ * Check whether a skill should be skipped during fetching.
13126
+ * Returns true (with appropriate logging) if the skill should be skipped.
13127
+ */
13128
+ function shouldSkipSkill(params) {
13129
+ const { skillName, sourceKey, localSkillNames, alreadyFetchedSkillNames, logger } = params;
13130
+ if (skillName.includes("..") || skillName.includes("/") || skillName.includes("\\")) {
13131
+ logger.warn(`Skipping skill with invalid name ${quoteForLog(skillName)} from ${sourceKey}: contains path traversal characters.`);
13132
+ return true;
13133
+ }
13134
+ const unsafe = describeUnsafeRemoteName(skillName);
13135
+ if (unsafe !== void 0) {
13136
+ logger.warn(`Skipping skill with unsafe name ${unsafe} from ${sourceKey}.`);
13137
+ return true;
13138
+ }
13139
+ if (localSkillNames.has(skillName)) {
13140
+ logger.debug(`Skipping remote skill ${quoteForLog(skillName)} from ${sourceKey}: local skill takes precedence.`);
13141
+ return true;
13142
+ }
13143
+ if (alreadyFetchedSkillNames.has(skillName)) {
13144
+ logger.warn(`Skipping duplicate skill ${quoteForLog(skillName)} from ${sourceKey}: already fetched from another source.`);
13145
+ return true;
13146
+ }
13147
+ return false;
13148
+ }
13149
+ /**
13150
+ * Check whether a remote rule, command or subagent should be skipped: its
13151
+ * name could escape the curated directory or is unsafe to print, a local file
13152
+ * of the same name takes precedence, or an earlier source already took it.
13153
+ */
13154
+ function shouldSkipFile(params) {
13155
+ const { feature, name, sourceKey, localNames, alreadyFetchedNames, logger } = params;
13156
+ const noun = getFileFeatureNoun(feature);
13157
+ if (!isValidRuleName(name)) {
13158
+ logger.warn(`Skipping ${noun} with invalid name ${quoteForLog(name)} from ${sourceKey}.`);
13159
+ return true;
13160
+ }
13161
+ const unsafe = describeUnsafeRemoteName(name);
13162
+ if (unsafe !== void 0) {
13163
+ logger.warn(`Skipping ${noun} with unsafe name ${unsafe} from ${sourceKey}.`);
13164
+ return true;
13165
+ }
13166
+ if (localNames.has(name)) {
13167
+ logger.debug(`Skipping remote ${noun} ${quoteForLog(name)} from ${sourceKey}: local ${noun} takes precedence.`);
13168
+ return true;
13169
+ }
13170
+ if (alreadyFetchedNames.has(name)) {
13171
+ logger.warn(`Skipping duplicate ${noun} ${quoteForLog(name)} from ${sourceKey}: already fetched from another source.`);
13172
+ return true;
13173
+ }
13174
+ return false;
13175
+ }
13176
+ /**
13177
+ * Why a remote skill or rule name must not be installed, already quoted for a
13178
+ * log line, or `undefined` when it is safe. It applies the same gate as
13179
+ * `rulesync fetch`: a name hiding control or deceptive zero-width characters
13180
+ * could rewrite the terminal when printed, or pass for another name, and a
13181
+ * name Windows folds lands on a different entry than it reads as.
13182
+ */
13183
+ function describeUnsafeRemoteName(name) {
13184
+ const verdict = classifyRemoteName(name);
13185
+ if (verdict.kind === "safe") return;
13186
+ return verdict.reason === "hidden" ? `${quoteForLog(verdict.display)} (it contains hidden or control characters)` : `${quoteForLog(name)} (Windows resolves it to a different name)`;
13187
+ }
13188
+ function isValidRuleName(ruleName) {
13189
+ return !(ruleName.includes("..") || ruleName.includes("/") || ruleName.includes("\\") || ruleName.length === 0 || [
13190
+ "__proto__",
13191
+ "constructor",
13192
+ "prototype"
13193
+ ].includes(ruleName));
13194
+ }
13195
+ /**
13196
+ * A fetched artifact whose content no longer matches the integrity recorded
13197
+ * for the same resolved ref. Under `--frozen` that is fatal — the lockfile is
13198
+ * the contract, and the gh transport refuses the same case — otherwise it is
13199
+ * reported and the new content is taken.
13200
+ */
13201
+ function reportIntegrityMismatch(params) {
13202
+ const { message, frozen, logger } = params;
13203
+ if (frozen) throw new Error(`${message} Refusing to install it under --frozen.`);
13204
+ logger.warn(message);
13205
+ }
13206
+ async function writeFeatureFileAndComputeIntegrity(params) {
13207
+ const { feature, file, curatedDir, locked, resolvedRef, sourceKey, compareLockedIntegrity = true, frozen, logger } = params;
13208
+ const relativePath = `${file.name}.md`;
13209
+ checkPathTraversal({
13210
+ relativePath,
13211
+ intendedRootDir: curatedDir
13212
+ });
13213
+ const integrity = computeRuleIntegrity(file.content);
13214
+ const lockedEntry = locked ? getLockedFileFeatureState(locked, feature).items?.[file.name] : void 0;
13215
+ if (compareLockedIntegrity && lockedEntry?.integrity && lockedEntry.integrity !== integrity && resolvedRef === locked?.resolvedRef) reportIntegrityMismatch({
13216
+ message: `Integrity mismatch for ${getFileFeatureNoun(feature)} ${quoteForLog(file.name)} from ${sourceKey}: expected "${lockedEntry.integrity}", got "${integrity}". Content may have been tampered with.`,
13217
+ frozen,
13218
+ logger
13219
+ });
13220
+ await writeFileContent(join(curatedDir, relativePath), file.content);
13221
+ return { integrity };
13222
+ }
13223
+ /**
13224
+ * Write skill files to disk, compute integrity, and check against the lockfile.
13225
+ * Returns the computed LockedSkill entry.
13226
+ */
13227
+ async function writeSkillAndComputeIntegrity(params) {
13228
+ const { skillName, files, curatedDir, locked, resolvedSha, sourceKey, frozen, logger } = params;
13229
+ for (const file of files) checkPathTraversal({
13230
+ relativePath: file.relativePath,
13231
+ intendedRootDir: join(curatedDir, skillName)
13232
+ });
13233
+ const integrity = computeSkillIntegrity(files.map((file) => ({
13234
+ path: file.relativePath,
13235
+ content: file.content
13236
+ })));
13237
+ const lockedSkillEntry = locked?.skills[skillName];
13238
+ if (lockedSkillEntry?.integrity && lockedSkillEntry.integrity !== integrity && resolvedSha === locked?.resolvedRef) reportIntegrityMismatch({
13239
+ message: `Integrity mismatch for skill ${quoteForLog(skillName)} from ${sourceKey}: expected "${lockedSkillEntry.integrity}", got "${integrity}". Content may have been tampered with.`,
13240
+ frozen,
13241
+ logger
13242
+ });
13243
+ for (const file of files) {
13244
+ const filePath = join(curatedDir, skillName, file.relativePath);
13245
+ await writeFileContent(filePath, file.content);
13246
+ if (file.executable === true) await applyFileMode(filePath, 493);
13247
+ }
13248
+ return { integrity };
13249
+ }
13250
+ /**
13251
+ * Merge back locked skills that still exist in the remote but were skipped
13252
+ * during fetching (due to local precedence, already-fetched, etc.). Skills no
13253
+ * longer present in the remote (e.g. renamed or deleted upstream) are
13254
+ * intentionally dropped. Shared by the git/github and npm lock updates.
13255
+ */
13256
+ function mergeFetchedWithLockedSkills(params) {
13257
+ const { fetchedSkills, lockedSkills, remoteSkillNames } = params;
13258
+ const remoteSet = new Set(remoteSkillNames);
13259
+ const mergedSkills = { ...fetchedSkills };
13260
+ if (lockedSkills) {
13261
+ for (const [skillName, skillEntry] of Object.entries(lockedSkills)) if (!(skillName in mergedSkills) && remoteSet.has(skillName)) mergedSkills[skillName] = skillEntry;
13262
+ }
13263
+ return mergedSkills;
13264
+ }
13265
+ function assertMatchingSkillsFound({ skillNames, source }) {
13266
+ if (skillNames.length === 0) throw new Error(`No matching skills found in ${source}.`);
13267
+ }
13268
+ /**
13269
+ * Merge newly fetched skills with existing locked skills and update the lockfile.
13270
+ */
13271
+ function buildLockUpdate(params) {
13272
+ const { lock, lockKey, sourceKey, fetchedSkills, locked, requestedRef, resolvedSha, skillSelection, skillsPath, remoteSkillNames, logger } = params;
13273
+ const fetchedNames = Object.keys(fetchedSkills);
13274
+ const mergedSkills = mergeFetchedWithLockedSkills({
13275
+ fetchedSkills,
13276
+ lockedSkills: locked?.skills,
13277
+ remoteSkillNames
13278
+ });
13279
+ const updatedLock = setLockedSource(lock, lockKey, {
13280
+ requestedRef,
13281
+ resolvedRef: resolvedSha,
13282
+ resolvedAt: (/* @__PURE__ */ new Date()).toISOString(),
13283
+ skills: mergedSkills,
13284
+ skillSelection,
13285
+ skillsPath,
13286
+ rules: locked?.rules ?? {},
13287
+ ruleSelection: locked?.ruleSelection,
13288
+ rulesPath: locked?.rulesPath,
13289
+ resolvedRuleNames: locked?.resolvedRuleNames,
13290
+ ...pickFileFeatureLockFields({
13291
+ locked,
13292
+ features: ["commands", "subagents"]
13293
+ })
13294
+ });
13295
+ logger.info(`Fetched ${fetchedNames.length} skill(s) from ${sourceKey}: ${fetchedNames.map(stripControlCharacters).join(", ") || "(none)"}`);
13296
+ return {
13297
+ updatedLock,
13298
+ fetchedNames
13299
+ };
13300
+ }
13301
+ /**
13302
+ * The lock fields of the given per-file features, copied from a lock entry
13303
+ * (empty when there is none), so that writing one feature's fields keeps the
13304
+ * others as they were.
13305
+ */
13306
+ function pickFileFeatureLockFields(params) {
13307
+ const { locked, features } = params;
13308
+ if (locked === void 0) return {};
13309
+ return Object.assign({}, ...features.map((feature) => toFileFeatureLockFields(feature, getLockedFileFeatureState(locked, feature))));
13310
+ }
13311
+ function buildFileLockUpdate(params) {
13312
+ const { feature, lock, lockKey, sourceKey, fetchedFiles, locked, requestedRef, resolvedRef, selection, path, resolvedNames, logger } = params;
13313
+ const fetchedNames = Object.keys(fetchedFiles);
13314
+ const updatedLock = setLockedSource(lock, lockKey, {
13315
+ requestedRef,
13316
+ resolvedRef,
13317
+ resolvedAt: (/* @__PURE__ */ new Date()).toISOString(),
13318
+ skills: locked?.skills ?? {},
13319
+ skillSelection: locked?.skillSelection,
13320
+ skillsPath: locked?.skillsPath,
13321
+ ...pickFileFeatureLockFields({
13322
+ locked,
13323
+ features: SOURCE_FILE_FEATURES
13324
+ }),
13325
+ ...toFileFeatureLockFields(feature, {
13326
+ items: fetchedFiles,
13327
+ selection,
13328
+ path,
13329
+ resolvedNames
13330
+ })
13331
+ });
13332
+ logger.info(`Fetched ${fetchedNames.length} ${getFileFeatureNoun(feature)}(s) from ${sourceKey}: ${fetchedNames.map(stripControlCharacters).join(", ") || "(none)"}`);
13333
+ return {
13334
+ updatedLock,
13335
+ fetchedNames
13336
+ };
13337
+ }
13338
+ function getFirstPathSeparatorIndex(path) {
13339
+ const slashIndex = path.indexOf("/");
13340
+ const backslashIndex = path.indexOf("\\");
13341
+ if (slashIndex === -1) return backslashIndex;
13342
+ if (backslashIndex === -1) return slashIndex;
13343
+ return Math.min(slashIndex, backslashIndex);
13344
+ }
13345
+ /**
13346
+ * Decide whether a repository's root-level files should be installed as the
13347
+ * single requested skill (the "root fallback").
13348
+ *
13349
+ * A root fallback fires only when a single, non-wildcard skill was requested,
13350
+ * that skill's own directory is absent, and the repository root actually carries
13351
+ * a `SKILL.md`. Both the git transport (`groupRemoteFilesBySkillRoot`) and the
13352
+ * GitHub transport (`discoverGithubSkillDirs`) gate on these same conditions, so
13353
+ * the decision lives here to keep the two paths from drifting.
13354
+ */
13355
+ function shouldUseRootFallback(params) {
13356
+ const { skillFilter, isWildcard, hasRootSkillFile, hasRequestedSkillDir } = params;
13357
+ const [singleSkillName] = skillFilter;
13358
+ return !isWildcard && skillFilter.length === 1 && singleSkillName !== void 0 && hasRootSkillFile && !hasRequestedSkillDir;
13359
+ }
13360
+ function groupRemoteFilesBySkillRoot(params) {
13361
+ const { remoteFiles, skillFilter, isWildcard } = params;
13362
+ const grouped = /* @__PURE__ */ new Map();
13363
+ const rootLevelFiles = [];
13364
+ for (const file of remoteFiles) {
13365
+ const separatorIndex = getFirstPathSeparatorIndex(file.relativePath);
13366
+ if (separatorIndex === -1) {
13367
+ rootLevelFiles.push(file);
13368
+ continue;
13369
+ }
13370
+ const skillName = file.relativePath.substring(0, separatorIndex);
13371
+ if (skillName.length === 0) continue;
13372
+ const innerPath = file.relativePath.substring(separatorIndex + 1);
13373
+ const groupedFiles = grouped.get(skillName) ?? [];
13374
+ groupedFiles.push({
13375
+ ...file,
13376
+ relativePath: innerPath
13377
+ });
13378
+ grouped.set(skillName, groupedFiles);
13379
+ }
13380
+ const [singleSkillName] = skillFilter;
13381
+ const hasRootSkillFile = rootLevelFiles.some((file) => file.relativePath === SKILL_FILE_NAME);
13382
+ if (singleSkillName !== void 0 && shouldUseRootFallback({
13383
+ skillFilter,
13384
+ isWildcard,
13385
+ hasRootSkillFile,
13386
+ hasRequestedSkillDir: grouped.has(singleSkillName)
13387
+ })) grouped.set(singleSkillName, rootLevelFiles);
13388
+ return grouped;
13389
+ }
13390
+ function normalizeRuleFilterName(name) {
13391
+ return name.replace(/\.md$/i, "");
13392
+ }
13393
+ /** Whether a declared skill or rule selection is the `["*"]` wildcard. */
13394
+ function isWildcardSelection(selection) {
13395
+ return selection.length === 1 && selection[0] === "*";
13396
+ }
13397
+ /**
13398
+ * Pick the remote files a source entry declares for one per-file feature:
13399
+ * Markdown files whose normalized name is selected by the feature's field
13400
+ * (`sourceEntry.rules`, `.commands` or `.subagents`, or the wildcard) and is a
13401
+ * valid file name. Candidate order is preserved.
13402
+ */
13403
+ function selectDeclaredFiles(params) {
13404
+ const { feature, sourceEntry, candidates, getFileName } = params;
13405
+ const ruleFilter = (sourceEntry[feature] ?? []).map(normalizeRuleFilterName);
13406
+ const isWildcard = isWildcardSelection(ruleFilter);
13407
+ return candidates.filter((candidate) => getFileName(candidate).toLowerCase().endsWith(".md")).map((candidate) => ({
13408
+ candidate,
13409
+ name: normalizeRuleFilterName(getFileName(candidate))
13410
+ })).filter(({ name }) => (isWildcard || ruleFilter.includes(name)) && isValidRuleName(name));
13411
+ }
13412
+ function normalizeRuleSelection(rules) {
13413
+ return [...new Set(rules.map(normalizeRuleFilterName))].toSorted();
13414
+ }
13415
+ function normalizeSkillSelection(skills) {
13416
+ return [...new Set(skills)].toSorted();
13417
+ }
13418
+ /**
13419
+ * Whether the locked entry was written for the `skills` selection and skills
13420
+ * path the manifest declares now. Without it, widening the selection or moving
13421
+ * the path after an install is a silent no-op: the ref is unchanged and every
13422
+ * locked skill is on disk, so nothing is fetched and `--frozen` never notices.
13423
+ *
13424
+ * Lockfiles written before the path was recorded carry no `skillsPath`. Such
13425
+ * an entry is handled like one without `skillSelection`: fetched again at its
13426
+ * locked ref to record the path, and accepted as-is under `acceptLegacy`.
13427
+ *
13428
+ * Lockfiles written before the selection was recorded carry no
13429
+ * `skillSelection`. An install that may write the lockfile fetches such an
13430
+ * entry again at its locked ref so the selection gets recorded once; the checks that
13431
+ * cannot write it (`--frozen`, adding a source) pass `acceptLegacy` and fall
13432
+ * back to the locked skill names instead, so a wildcard is taken at face value
13433
+ * and an explicit list is covered only when every name it selects is locked.
13434
+ * An entry that locks no skills at all (a rules-only install) covers nothing:
13435
+ * it was never written for a skill selection.
13436
+ */
13437
+ function lockedSkillConfigMatches(params) {
13438
+ const skills = getSourceFilters(params.sourceEntry).skills;
13439
+ if (skills === void 0) return false;
13440
+ const lockedPath = params.locked.skillsPath;
13441
+ if (lockedPath === void 0 ? !params.acceptLegacy : lockedPath !== resolveSkillsPath(params.sourceEntry)) return false;
13442
+ const selection = normalizeSkillSelection(skills);
13443
+ const lockedSelection = params.locked.skillSelection;
13444
+ if (lockedSelection === void 0) {
13445
+ const lockedSkillNames = new Set(Object.keys(params.locked.skills));
13446
+ if (!params.acceptLegacy || lockedSkillNames.size === 0) return false;
13447
+ if (isWildcardSelection(selection)) return true;
13448
+ return selection.every((skillName) => lockedSkillNames.has(skillName));
13449
+ }
13450
+ return selection.length === lockedSelection.length && selection.every((skillName, index) => skillName === lockedSelection[index]);
13451
+ }
13452
+ /**
13453
+ * Skip the re-fetch when the SHA and the skill selection match the lockfile and
13454
+ * every curated skill the entry locks is still on disk, unmodified.
13455
+ */
13456
+ async function canReuseLockedSkills(params) {
13457
+ const { locked, resolvedSha, updateSources, frozen, sourceEntry, curatedDir, getAlreadyFetchedSkillNames } = params;
13458
+ return locked !== void 0 && resolvedSha === locked.resolvedRef && !updateSources && lockedSkillConfigMatches({
13459
+ locked,
13460
+ sourceEntry,
13461
+ acceptLegacy: frozen
13462
+ }) && await checkLockedSkillsAreValid({
13463
+ curatedDir,
13464
+ skills: locked.skills,
13465
+ presenceOnlySkillNames: await getAlreadyFetchedSkillNames()
13466
+ });
13467
+ }
13468
+ /**
13469
+ * The path the skills of a source are read from, as declared: the source's
13470
+ * `path`, else (for the github transport) the path embedded in the source
13471
+ * spec, else `skills`. Every transport fetches from this path, and the
13472
+ * lockfile records its normalized form ({@link resolveSkillsPath}), so the
13473
+ * fetch and the lock comparison cannot pick different paths.
13474
+ */
13475
+ function resolveSkillsSourcePath(sourceEntry) {
13476
+ const embeddedPath = getSourceTransport(sourceEntry) === "github" ? parseSource(sourceEntry.source).path : void 0;
13477
+ return sourceEntry.path ?? embeddedPath ?? "skills";
13478
+ }
13479
+ /** The skills path of a source in the form the lockfile records and compares. */
13480
+ function resolveSkillsPath(sourceEntry) {
13481
+ return normalizeSourceDirPath(resolveSkillsSourcePath(sourceEntry));
13482
+ }
13483
+ /**
13484
+ * The path one per-file feature of a source is read from, as declared: the
13485
+ * source's `rulesPath` / `commandsPath` / `subagentsPath`, else `rules` /
13486
+ * `commands` / `subagents`. The counterpart of {@link resolveSkillsSourcePath}.
13487
+ */
13488
+ function resolveFileFeatureSourcePath(sourceEntry, feature) {
13489
+ const spec = FILE_FEATURE_SPECS[feature];
13490
+ return sourceEntry[spec.pathField] ?? spec.defaultPath;
13491
+ }
13492
+ /** A per-file feature's path in the form the lockfile records and compares. */
13493
+ function resolveFileFeaturePath(sourceEntry, feature) {
13494
+ return normalizeSourceDirPath(resolveFileFeatureSourcePath(sourceEntry, feature));
13495
+ }
13496
+ /**
13497
+ * The form a source directory path is recorded in the lockfile and compared
13498
+ * in: posix separators, normalized, with no trailing slash.
13499
+ */
13500
+ function normalizeSourceDirPath(dirPath) {
13501
+ return normalizePosixDirPath(dirPath);
13502
+ }
13503
+ /**
13504
+ * Whether a lock entry was written for the selection and path one per-file
13505
+ * feature of the source declares now.
13506
+ */
13507
+ function lockedFileConfigMatches(params) {
13508
+ const { feature, locked, sourceEntry } = params;
13509
+ const declared = getSourceFilters(sourceEntry)[feature];
13510
+ const { selection: lockedSelection, path: lockedPath } = getLockedFileFeatureState(locked, feature);
13511
+ if (declared === void 0 || lockedSelection === void 0) return false;
13512
+ const selection = normalizeRuleSelection(declared);
13513
+ return selection.length === lockedSelection.length && selection.every((name, index) => name === lockedSelection[index]) && resolveFileFeaturePath(sourceEntry, feature) === lockedPath;
13514
+ }
13515
+ function assertMatchingFilesFound(params) {
13516
+ if (params.names.length === 0) throw new Error(`No matching ${params.feature} found in ${params.source}.`);
13517
+ }
13518
+ /**
13519
+ * "N skill(s) and M rule(s)", followed by the command and subagent counts when
13520
+ * any were installed, for the summary lines of `add` and `install`.
13521
+ */
13522
+ function formatInstalledCounts(result) {
13523
+ 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);
13524
+ const parts = [
13525
+ `${result.fetchedSkillCount} skill(s)`,
13526
+ `${result.fetchedRuleCount} rule(s)`,
13527
+ ...extras
13528
+ ];
13529
+ return `${parts.slice(0, -1).join(", ")} and ${parts.at(-1)}`;
13530
+ }
12343
13531
  const SKILL_DESCRIPTION_MAX_LENGTH = 1024;
12344
13532
  const SKILL_NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
12345
13533
  /**
@@ -15462,8 +16650,11 @@ var FeatureProcessor = class extends RulesyncSourceConsumer {
15462
16650
  })) continue;
15463
16651
  const existingFileContent = await readFileContentOrNull(filePath);
15464
16652
  if (existingFileContent !== null && aiFile.shouldMergeExistingFileContent()) aiFile.setFileContent(existingFileContent);
15465
- const contentWithNewline = addTrailingNewline(aiFile.getFileContent());
15466
16653
  const existingContent = existingFileContent;
16654
+ const contentWithNewline = aiFile.composeWrittenContent({
16655
+ existingContent,
16656
+ generatedContent: addTrailingNewline(aiFile.getFileContent())
16657
+ });
15467
16658
  if (existingContent === null && aiFile.shouldSkipCreationWhenPayloadEmpty() && fileContentIsEmptyPayload({
15468
16659
  filePath,
15469
16660
  content: contentWithNewline
@@ -15582,6 +16773,21 @@ var FeatureProcessor = class extends RulesyncSourceConsumer {
15582
16773
  }
15583
16774
  if (refused) continue;
15584
16775
  const loggedPath = stripControlCharacters(filePath);
16776
+ if (aiFile.keepsContentOnRemoval()) {
16777
+ const existingContent = await readFileContentOrNull(filePath);
16778
+ const outcome = existingContent === null ? { action: "delete" } : aiFile.composeContentAfterRemoval({ existingContent });
16779
+ if (outcome.action === "keep") continue;
16780
+ if (outcome.action === "rewrite") {
16781
+ if (this.dryRun) this.logger.info(`[DRY RUN] Would rewrite: ${loggedPath}`);
16782
+ else {
16783
+ await writeFileContent(filePath, outcome.content);
16784
+ this.logger.info(`Removed the generated block from: ${loggedPath}`);
16785
+ }
16786
+ this.sweepWrites.paths.push(aiFile.getRelativePathFromCwd());
16787
+ removedCount++;
16788
+ continue;
16789
+ }
16790
+ }
15585
16791
  if (this.dryRun) this.logger.info(`[DRY RUN] Would delete: ${loggedPath}`);
15586
16792
  else {
15587
16793
  await removeFile(filePath);
@@ -15966,8 +17172,8 @@ var ClaimedIdentities = class {
15966
17172
  };
15967
17173
  // src/utils/curated-frontmatter.ts
15968
17174
  /**
15969
- * The frontmatter fields a command or subagent fetched from a declared source
15970
- * keeps. Only the canonical, tool-neutral fields of the rulesync schema are
17175
+ * The frontmatter fields a command, subagent or skill fetched from a declared
17176
+ * source keeps. Only the canonical, tool-neutral fields of the rulesync schema are
15971
17177
  * listed: none of them grants tools, permissions, hooks or MCP servers.
15972
17178
  *
15973
17179
  * Every tool section (`claudecode`, `codexcli`, `kiro`, `opencode`, ...) is
@@ -15984,6 +17190,30 @@ const CURATED_SUBAGENT_FRONTMATTER_KEYS = [
15984
17190
  "description"
15985
17191
  ];
15986
17192
  /**
17193
+ * A skill also keeps the root invocation flags (`disable-model-invocation`,
17194
+ * `user-invocable`), which only narrow when the skill is loaded, and the Agent
17195
+ * Skills packaging fields (`license`, `compatibility`, `metadata`). Inside
17196
+ * `metadata`, the tool blocks listed in `CURATED_SKILL_DROPPED_METADATA_KEYS`
17197
+ * are dropped, since they gate or install things rather than describe the
17198
+ * skill.
17199
+ */
17200
+ const CURATED_SKILL_FRONTMATTER_KEYS = [
17201
+ "targets",
17202
+ "name",
17203
+ "description",
17204
+ "disable-model-invocation",
17205
+ "user-invocable",
17206
+ "license",
17207
+ "compatibility",
17208
+ "metadata"
17209
+ ];
17210
+ /**
17211
+ * `metadata` keys a tool reads as configuration: OpenClaw's `metadata.openclaw`
17212
+ * (`install`, `always`, `requires`, ...) and Hermes Agent's `metadata.hermes`
17213
+ * (`requires_toolsets`, ...). A skill fetched from a source loses them.
17214
+ */
17215
+ const CURATED_SKILL_DROPPED_METADATA_KEYS = ["openclaw", "hermes"];
17216
+ /**
15987
17217
  * Keep only `allowedKeys` of a frontmatter object. Returns a new frontmatter
15988
17218
  * and the names of the dropped top-level keys, in input order.
15989
17219
  */
@@ -31700,6 +32930,15 @@ const defaultGetFactory$5 = (target) => {
31700
32930
  const skillsProcessorToolTargetsProject = [...toolSkillFactories].filter(([, factory]) => factory.meta.supportsProject).map(([target]) => target);
31701
32931
  const skillsProcessorToolTargetsSimulated = [...toolSkillFactories].filter(([, factory]) => factory.meta.supportsSimulated).map(([target]) => target);
31702
32932
  const skillsProcessorToolTargetsGlobal = [...toolSkillFactories].filter(([, factory]) => factory.meta.supportsGlobal).map(([target]) => target);
32933
+ /**
32934
+ * Whether a skill companion path is the Codex `agents/openai.yaml` sidecar,
32935
+ * compared case-insensitively and with either separator, since a
32936
+ * case-insensitive filesystem or Windows resolves those spellings to it.
32937
+ */
32938
+ function isCodexOpenaiYaml(relativeFilePath) {
32939
+ const normalize = (path) => path.replaceAll("\\", "/").toLowerCase();
32940
+ return normalize(relativeFilePath) === normalize(CODEXCLI_OPENAI_YAML_RELATIVE_PATH);
32941
+ }
31703
32942
  var SkillsProcessor = class extends DirFeatureProcessor {
31704
32943
  toolTarget;
31705
32944
  global;
@@ -31813,16 +33052,59 @@ var SkillsProcessor = class extends DirFeatureProcessor {
31813
33052
  }));
31814
33053
  return false;
31815
33054
  });
31816
- curatedSkills = await Promise.all(nonConflicting.map((dirName) => RulesyncSkill.fromDir({
33055
+ curatedSkills = await Promise.all(nonConflicting.map(async (dirName) => this.withCanonicalFrontmatterOnly(await RulesyncSkill.fromDir({
31817
33056
  outputRoot: treeParent,
31818
33057
  relativeDirPath: treeCuratedSkillsDirPath,
31819
33058
  dirName,
31820
33059
  global: this.global
31821
- })));
33060
+ }))));
31822
33061
  }
31823
33062
  return [...localSkills, ...curatedSkills];
31824
33063
  }
31825
33064
  /**
33065
+ * A skill fetched from a declared source, keeping only the canonical,
33066
+ * tool-neutral frontmatter fields and dropping every tool section, since
33067
+ * those are copied into the generated files and can grant tools or hooks
33068
+ * (Claude Code `allowed-tools` and `hooks`, for example). The tool blocks
33069
+ * inside `metadata` (OpenClaw's `metadata.openclaw`, Hermes Agent's
33070
+ * `metadata.hermes`) and a Codex `agents/openai.yaml` companion file (its
33071
+ * invocation policy and MCP dependencies) go too. The body and the other
33072
+ * companion files are kept. A local skill of the same name keeps its
33073
+ * tool-specific settings.
33074
+ */
33075
+ withCanonicalFrontmatterOnly(skill) {
33076
+ const kept = keepCuratedFrontmatterKeys({
33077
+ frontmatter: skill.getFrontmatter(),
33078
+ allowedKeys: CURATED_SKILL_FRONTMATTER_KEYS
33079
+ });
33080
+ const frontmatter = kept.frontmatter;
33081
+ const droppedKeys = [...kept.droppedKeys];
33082
+ if (frontmatter.metadata !== void 0) {
33083
+ const metadata = { ...frontmatter.metadata };
33084
+ for (const key of CURATED_SKILL_DROPPED_METADATA_KEYS) if (Object.hasOwn(metadata, key)) {
33085
+ delete metadata[key];
33086
+ droppedKeys.push(`metadata.${key}`);
33087
+ }
33088
+ frontmatter.metadata = metadata;
33089
+ }
33090
+ const otherFiles = skill.getOtherFiles();
33091
+ const keptFiles = otherFiles.filter((file) => !isCodexOpenaiYaml(file.relativeFilePathToDirPath));
33092
+ const droppedFiles = otherFiles.length - keptFiles.length;
33093
+ if (droppedKeys.length === 0 && droppedFiles === 0) return skill;
33094
+ const skillPath = quoteForLog(join(skill.getRelativeDirPath(), skill.getDirName()));
33095
+ 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.`);
33096
+ 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.`);
33097
+ return new RulesyncSkill({
33098
+ outputRoot: skill.getOutputRoot(),
33099
+ relativeDirPath: skill.getRelativeDirPath(),
33100
+ dirName: skill.getDirName(),
33101
+ frontmatter,
33102
+ body: skill.getBody(),
33103
+ otherFiles: keptFiles,
33104
+ global: skill.getGlobal()
33105
+ });
33106
+ }
33107
+ /**
31826
33108
  * Implementation of abstract method from DirFeatureProcessor.
31827
33109
  *
31828
33110
  * Load and parse rulesync skill directories from every configured input
@@ -41434,6 +42716,116 @@ var ClaudecodeLanguageSettings = class ClaudecodeLanguageSettings extends ToolFi
41434
42716
  }
41435
42717
  }
41436
42718
  };
42719
+ // src/features/rules/rule-managed-block.ts
42720
+ /**
42721
+ * The fence `preserveUnmanagedRuleContent` wraps around the generated body of
42722
+ * a root rule file, so content a person writes outside it survives the next
42723
+ * `generate`. The wording follows the block `rulesync gitignore` writes
42724
+ * (`# Generated by Rulesync` / `# End of Rulesync`), as Markdown comments so
42725
+ * the tools reading the file do not show it.
42726
+ */
42727
+ const RULE_MANAGED_BLOCK_START = "<!-- Generated by Rulesync -->";
42728
+ const RULE_MANAGED_BLOCK_END = "<!-- End of Rulesync -->";
42729
+ const LEADING_FRONTMATTER_PATTERN = /^---\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/;
42730
+ const splitLeadingFrontmatter = (content) => {
42731
+ const match = LEADING_FRONTMATTER_PATTERN.exec(content);
42732
+ if (!match) return {
42733
+ frontmatter: "",
42734
+ rest: content
42735
+ };
42736
+ return {
42737
+ frontmatter: match[0].endsWith("\n") ? match[0] : `${match[0]}\n`,
42738
+ rest: content.slice(match[0].length)
42739
+ };
42740
+ };
42741
+ const CODE_FENCE_PATTERN = /^ {0,3}(`{3,}|~{3,})/;
42742
+ /**
42743
+ * Locate the first complete fence: a line that is exactly the start marker
42744
+ * (surrounding whitespace aside) followed later by a line that is exactly the
42745
+ * end marker. A start marker without an end marker is not a fence. Marker
42746
+ * lines inside a Markdown code block (```` ``` ```` or `~~~`) do not count, so
42747
+ * a rule that quotes the markers in an example is not mistaken for a fence.
42748
+ */
42749
+ const findFence = (content) => {
42750
+ let startLineBegin;
42751
+ let startLineEnd = 0;
42752
+ let openCodeFence;
42753
+ let offset = 0;
42754
+ while (offset <= content.length) {
42755
+ const newline = content.indexOf("\n", offset);
42756
+ const lineEnd = newline === -1 ? content.length : newline + 1;
42757
+ const rawLine = content.slice(offset, newline === -1 ? content.length : newline);
42758
+ const codeFence = CODE_FENCE_PATTERN.exec(rawLine)?.[1];
42759
+ if (openCodeFence !== void 0) {
42760
+ if (codeFence !== void 0 && codeFence[0] === openCodeFence[0] && codeFence.length >= openCodeFence.length && rawLine.trim() === codeFence) openCodeFence = void 0;
42761
+ } else if (codeFence !== void 0) openCodeFence = codeFence;
42762
+ else {
42763
+ const line = rawLine.trim();
42764
+ if (startLineBegin === void 0) {
42765
+ if (line === "<!-- Generated by Rulesync -->") {
42766
+ startLineBegin = offset;
42767
+ startLineEnd = lineEnd;
42768
+ }
42769
+ } else if (line === "<!-- End of Rulesync -->") return {
42770
+ startLineBegin,
42771
+ startLineEnd,
42772
+ endLineBegin: offset,
42773
+ endLineEnd: lineEnd
42774
+ };
42775
+ }
42776
+ if (newline === -1) break;
42777
+ offset = lineEnd;
42778
+ }
42779
+ };
42780
+ /**
42781
+ * Compose the content to write for a root rule file under
42782
+ * `preserveUnmanagedRuleContent`: the generated frontmatter (if any) first,
42783
+ * then whatever the existing file holds before its fence, the fenced
42784
+ * generated body, and whatever it holds after the fence.
42785
+ *
42786
+ * An existing file without a complete fence is treated as entirely
42787
+ * rulesync's — it is what rulesync wrote before the option was turned on, and
42788
+ * keeping it would duplicate that content outside the fence — so only the
42789
+ * fenced body is written. Hand edits belong outside the fence from then on.
42790
+ *
42791
+ * When the generated content starts with frontmatter, the existing file's
42792
+ * leading frontmatter is rulesync's too and is replaced rather than kept.
42793
+ */
42794
+ const spliceRuleManagedBlock = ({ existingContent, generatedContent }) => {
42795
+ const generated = splitLeadingFrontmatter(generatedContent);
42796
+ const body = generated.rest.replace(/^\n+/, "");
42797
+ const block = `${RULE_MANAGED_BLOCK_START}\n${body}${body === "" || body.endsWith("\n") ? "" : "\n"}${RULE_MANAGED_BLOCK_END}\n`;
42798
+ if (existingContent === null) return generated.frontmatter + block;
42799
+ const eol = (text) => existingContent.includes("\r\n") ? text.replaceAll("\n", "\r\n") : text;
42800
+ const existing = generated.frontmatter === "" ? existingContent : splitLeadingFrontmatter(existingContent).rest;
42801
+ const fence = findFence(existing);
42802
+ if (fence === void 0) return eol(generated.frontmatter + block);
42803
+ const before = existing.slice(0, fence.startLineBegin);
42804
+ let after = existing.slice(fence.endLineEnd);
42805
+ if (fence.endLineEnd === existing.length && !existing.endsWith("\n")) after = "";
42806
+ return eol(generated.frontmatter) + before + eol(block) + after;
42807
+ };
42808
+ /**
42809
+ * `content` with its first complete fence (marker lines included) taken out,
42810
+ * or `undefined` when it has none. Used when a root rule file stops being
42811
+ * generated: the fenced block is rulesync's to remove, the rest is not.
42812
+ */
42813
+ const removeRuleManagedBlock = (content) => {
42814
+ const fence = findFence(content);
42815
+ if (fence === void 0) return;
42816
+ return content.slice(0, fence.startLineBegin) + content.slice(fence.endLineEnd);
42817
+ };
42818
+ /**
42819
+ * The text inside the first complete fence (without the marker lines), or
42820
+ * `undefined` when `content` has none. `import` keeps only this part so
42821
+ * hand-written content outside the fence is not copied into the rulesync
42822
+ * source, where the next `generate` would write it a second time.
42823
+ */
42824
+ const extractRuleManagedBlock = (content) => {
42825
+ const fence = findFence(content);
42826
+ if (fence === void 0) return;
42827
+ return content.slice(fence.startLineEnd, fence.endLineBegin);
42828
+ };
41437
42829
  // src/features/shared/opencode-family-mcp-tool-keys.ts
41438
42830
  /**
41439
42831
  * MCP tool naming shared by OpenCode and its forks (Kilo, MiMo Code):
@@ -43108,6 +44500,46 @@ var ToolRule = class extends ToolFile {
43108
44500
  this.description = description;
43109
44501
  this.globs = globs;
43110
44502
  }
44503
+ /**
44504
+ * Whether the write phase fences the generated content and keeps what the
44505
+ * existing file holds outside the fence (`preserveUnmanagedRuleContent`).
44506
+ * Set by the rules processor on the root rule files it emits.
44507
+ */
44508
+ preservesUnmanagedContent = false;
44509
+ /** See {@link ToolRule.preservesUnmanagedContent}. */
44510
+ enableUnmanagedContentPreservation() {
44511
+ this.preservesUnmanagedContent = true;
44512
+ }
44513
+ isPreservingUnmanagedContent() {
44514
+ return this.preservesUnmanagedContent;
44515
+ }
44516
+ composeWrittenContent({ existingContent, generatedContent }) {
44517
+ if (!this.preservesUnmanagedContent) return generatedContent;
44518
+ return spliceRuleManagedBlock({
44519
+ existingContent,
44520
+ generatedContent
44521
+ });
44522
+ }
44523
+ keepsContentOnRemoval() {
44524
+ return this.preservesUnmanagedContent;
44525
+ }
44526
+ /**
44527
+ * Under `preserveUnmanagedRuleContent`, removing a root rule file takes out
44528
+ * only the fenced block and keeps the hand-written rest; a file with nothing
44529
+ * else left is deleted. A file without a fence is not rulesync's any more —
44530
+ * the hand-written rest of an earlier removal, or a file written before the
44531
+ * option was on — so it is left in place.
44532
+ */
44533
+ composeContentAfterRemoval({ existingContent }) {
44534
+ if (!this.preservesUnmanagedContent) return { action: "delete" };
44535
+ const rest = removeRuleManagedBlock(existingContent);
44536
+ if (rest === void 0) return { action: "keep" };
44537
+ if (rest.trim() === "") return { action: "delete" };
44538
+ return {
44539
+ action: "rewrite",
44540
+ content: rest
44541
+ };
44542
+ }
43111
44543
  static getSettablePaths(_options = {}) {
43112
44544
  throw new Error("Please implement this method in the subclass.");
43113
44545
  }
@@ -53192,6 +54624,23 @@ const resolveBooleanRulesOption = ({ options, key }) => {
53192
54624
  if (!parsed.success) throw new Error(`Invalid options for rules feature: ${parsed.error.message}. \`${key}\` must be a boolean.`);
53193
54625
  return parsed.data[key] ?? true;
53194
54626
  };
54627
+ /**
54628
+ * Resolve the `include` rules option: the names of the rules this target
54629
+ * receives, or `undefined` when the option is unset (every rule is eligible).
54630
+ */
54631
+ const resolveRuleIncludeOption = (options) => {
54632
+ if (!options) return void 0;
54633
+ const parsed = z.looseObject({ include: z.optional(z.array(z.string())) }).safeParse(options);
54634
+ if (!parsed.success) throw new Error(`Invalid options for rules feature: ${parsed.error.message}. \`include\` must be an array of rule names.`);
54635
+ return parsed.data.include;
54636
+ };
54637
+ /**
54638
+ * The name the `include` rules option selects a rule by: its path under
54639
+ * `rules/` (or `rules/.curated/`) without the `.md` extension, normalized the
54640
+ * same way as `sources[].rules`. A rule at the top of the directory is matched
54641
+ * by its file name alone, e.g. `git-safety` for `git-safety.md`.
54642
+ */
54643
+ const getRuleSelectionName = (rule) => normalizeRuleFilterName(toPosixPath(rule.getRelativeFilePath()));
53195
54644
  const allToolTargetKeys$1 = [...toolRuleFactories.keys()];
53196
54645
  const rulesProcessorToolTargets = allToolTargetKeys$1.filter((target) => {
53197
54646
  return toolRuleFactories.get(target)?.meta.supportsProject !== false;
@@ -53234,6 +54683,24 @@ const findFilesWithFallback = async (primaryFilePaths, alternativeRoots, buildAl
53234
54683
  * delete generated files it can no longer regenerate and report success.
53235
54684
  */
53236
54685
  const rootRelativeGlob = (...segments) => posix.join(...segments.filter((segment) => segment !== void 0).map(toPosixPath));
54686
+ /**
54687
+ * Keep only the fenced part of a rule a `preserveUnmanagedRuleContent` run
54688
+ * wrote, so `import` does not copy hand-written content outside the fence into
54689
+ * the rulesync source, where the next `generate` would write it a second time
54690
+ * inside the fence. A rule without a complete fence is returned unchanged.
54691
+ */
54692
+ const extractFencedRule = (rulesyncRule) => {
54693
+ const fenced = extractRuleManagedBlock(rulesyncRule.getBody());
54694
+ if (fenced === void 0) return rulesyncRule;
54695
+ return new RulesyncRule({
54696
+ outputRoot: rulesyncRule.getOutputRoot(),
54697
+ relativeDirPath: rulesyncRule.getRelativeDirPath(),
54698
+ relativeFilePath: rulesyncRule.getRelativeFilePath(),
54699
+ frontmatter: rulesyncRule.getFrontmatter(),
54700
+ body: fenced.trim(),
54701
+ validate: false
54702
+ });
54703
+ };
53237
54704
  const isRootRule = (rule) => Boolean(rule.getFrontmatter().root || rule.getFrontmatter().localRoot);
53238
54705
  var RulesProcessor = class extends FeatureProcessor {
53239
54706
  toolTarget;
@@ -53250,7 +54717,8 @@ var RulesProcessor = class extends FeatureProcessor {
53250
54717
  skills;
53251
54718
  featureOptions;
53252
54719
  deleteOrphans;
53253
- 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 }) {
54720
+ preserveUnmanagedContent;
54721
+ 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 }) {
53254
54722
  super({
53255
54723
  outputRoot,
53256
54724
  inputRoots,
@@ -53270,6 +54738,7 @@ var RulesProcessor = class extends FeatureProcessor {
53270
54738
  this.skills = skills;
53271
54739
  this.featureOptions = featureOptions;
53272
54740
  this.deleteOrphans = deleteOrphans;
54741
+ this.preserveUnmanagedContent = preserveUnmanagedContent;
53273
54742
  }
53274
54743
  async convertRulesyncFilesToToolFiles(rulesyncFiles) {
53275
54744
  const rulesyncRules = rulesyncFiles.filter((file) => file instanceof RulesyncRule);
@@ -53313,6 +54782,9 @@ var RulesProcessor = class extends FeatureProcessor {
53313
54782
  });
53314
54783
  extraFiles.push(...await this.buildLanguageSettingsFiles());
53315
54784
  const outputFiles = [...toolRules, ...extraFiles];
54785
+ if (this.preserveUnmanagedContent) {
54786
+ for (const file of outputFiles) if (file instanceof ToolRule && file.isRoot()) file.enableUnmanagedContentPreservation();
54787
+ }
53316
54788
  this.warnForOutputPathCollisions({
53317
54789
  outputFiles,
53318
54790
  convertedRules
@@ -53747,10 +55219,10 @@ As this project's AI coding tool, you must follow the additional conventions bel
53747
55219
  async convertToolFilesToRulesyncFiles(toolFiles) {
53748
55220
  const toolRules = toolFiles.filter((file) => file instanceof ToolRule);
53749
55221
  const rulesyncRules = toolRules.map((toolRule) => {
53750
- if (toolRule.isLocalRoot()) return toolRule.toLocalRootRulesyncRule({ targets: [this.toolTarget] });
55222
+ if (toolRule.isLocalRoot()) return this.withoutUnmanagedContent(toolRule.toLocalRootRulesyncRule({ targets: [this.toolTarget] }));
53751
55223
  return this.withoutLanguageBlock({
53752
55224
  toolRule,
53753
- rulesyncRule: toolRule.toRulesyncRule()
55225
+ rulesyncRule: this.withoutUnmanagedContent(toolRule.toRulesyncRule())
53754
55226
  });
53755
55227
  });
53756
55228
  const claimedBy = /* @__PURE__ */ new Map();
@@ -53767,6 +55239,13 @@ As this project's AI coding tool, you must follow the additional conventions bel
53767
55239
  return rulesyncRules;
53768
55240
  }
53769
55241
  /**
55242
+ * See {@link extractFencedRule}. Only under `preserveUnmanagedRuleContent`:
55243
+ * without it a file that merely quotes the markers is imported whole.
55244
+ */
55245
+ withoutUnmanagedContent(rulesyncRule) {
55246
+ return this.preserveUnmanagedContent ? extractFencedRule(rulesyncRule) : rulesyncRule;
55247
+ }
55248
+ /**
53770
55249
  * Drop the language block a previous `generate` appended, so that importing
53771
55250
  * a generated root file and generating again yields one block, not two.
53772
55251
  * Every imported rule is checked, not just root ones: Cursor and the
@@ -53888,10 +55367,15 @@ As this project's AI coding tool, you must follow the additional conventions bel
53888
55367
  * copy (case-insensitive, matching the intra-root collision handling).
53889
55368
  */
53890
55369
  async loadRulesyncFiles() {
53891
- const rulesyncRules = await this.loadMergedRulesyncRules();
53892
55370
  const factory = this.getFactory(this.toolTarget);
55371
+ const mergedRules = await this.loadMergedRulesyncRules();
55372
+ const rulesyncRules = this.selectIncludedRules({
55373
+ rules: mergedRules,
55374
+ factory
55375
+ });
53893
55376
  const targetedRootRules = rulesyncRules.filter((rule) => rule.getFrontmatter().root).filter((rule) => factory.class.isTargetedByRulesyncRule(rule));
53894
- 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}.`);
55377
+ const rootRuleLeftOutByInclude = mergedRules.some((rule) => rule.getFrontmatter().root && factory.class.isTargetedByRulesyncRule(rule) && !rulesyncRules.includes(rule));
55378
+ 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}.`);
53895
55379
  const targetedLocalRootRules = rulesyncRules.filter((rule) => rule.getFrontmatter().localRoot).filter((rule) => factory.class.isTargetedByRulesyncRule(rule));
53896
55380
  if (targetedLocalRootRules.length > 1) throw new Error(`Multiple localRoot rules found for target '${this.toolTarget}': ${formatRulePaths(targetedLocalRootRules)}. Only one rule can have localRoot: true`);
53897
55381
  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)})`);
@@ -53909,6 +55393,28 @@ As this project's AI coding tool, you must follow the additional conventions bel
53909
55393
  return [...targetedRootRules, ...nonRootRules];
53910
55394
  }
53911
55395
  /**
55396
+ * Narrow the rules to the ones the target's `include` rules option names.
55397
+ * The option is a pure narrowing filter: a named rule still has to target
55398
+ * this tool through its `targets` frontmatter, which is checked afterwards
55399
+ * as for any other rule. A name that matches no rule (local or curated) is
55400
+ * an error, so a renamed or removed rule does not silently disappear from
55401
+ * the target. `["*"]` selects every rule, as in `sources[].rules`.
55402
+ */
55403
+ selectIncludedRules({ rules, factory, warn = true }) {
55404
+ const include = resolveRuleIncludeOption(this.featureOptions);
55405
+ if (include === void 0) return rules;
55406
+ const names = [...new Set(include.map(normalizeRuleFilterName))];
55407
+ if (isWildcardSelection(names)) return rules;
55408
+ const availableNames = new Set(rules.map(getRuleSelectionName));
55409
+ const unknownNames = names.filter((name) => !availableNames.has(name));
55410
+ 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.`);
55411
+ const selectedNames = new Set(names);
55412
+ const selectedRules = rules.filter((rule) => selectedNames.has(getRuleSelectionName(rule)));
55413
+ const excludedByFrontmatter = selectedRules.filter((rule) => !factory.class.isTargetedByRulesyncRule(rule));
55414
+ 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)}`);
55415
+ return selectedRules;
55416
+ }
55417
+ /**
53912
55418
  * Align the rules with each other through the tool's `alignRulesyncRules`
53913
55419
  * hook, printing its warnings unless `warn` is off.
53914
55420
  */
@@ -53959,7 +55465,16 @@ As this project's AI coding tool, you must follow the additional conventions bel
53959
55465
  async warnForFoldImportDuplicationRisk() {
53960
55466
  const factory = this.getFactory(this.toolTarget);
53961
55467
  if (factory.meta.collisionPolicy !== "fold") return;
53962
- const targetedRules = this.alignRulesyncRules(await this.loadMergedRulesyncRules(), { warn: false }).filter((rule) => factory.class.isTargetedByRulesyncRule(rule));
55468
+ const loadedRules = await this.loadMergedRulesyncRules();
55469
+ let includedRules = loadedRules;
55470
+ try {
55471
+ includedRules = this.selectIncludedRules({
55472
+ rules: loadedRules,
55473
+ factory,
55474
+ warn: false
55475
+ });
55476
+ } catch {}
55477
+ const targetedRules = this.alignRulesyncRules(includedRules, { warn: false }).filter((rule) => factory.class.isTargetedByRulesyncRule(rule));
53963
55478
  let includeLocalRoot = !this.global;
53964
55479
  try {
53965
55480
  includeLocalRoot &&= resolveBooleanRulesOption({
@@ -54024,6 +55539,14 @@ As this project's AI coding tool, you must follow the additional conventions bel
54024
55539
  * Load tool-specific rule configurations and parse them into ToolRule instances
54025
55540
  */
54026
55541
  async loadToolFiles({ forDeletion = false } = {}) {
55542
+ const toolFiles = await this.loadToolFilesUnmarked({ forDeletion });
55543
+ if (forDeletion && this.preserveUnmanagedContent) {
55544
+ const { localRootFileName } = this.getFactory(this.toolTarget).meta;
55545
+ for (const file of toolFiles) if (file instanceof ToolRule && (file.isRoot() || file.isLocalRoot() || localRootFileName !== void 0 && file.getRelativeFilePath() === localRootFileName)) file.enableUnmanagedContentPreservation();
55546
+ }
55547
+ return toolFiles;
55548
+ }
55549
+ async loadToolFilesUnmarked({ forDeletion }) {
54027
55550
  try {
54028
55551
  const factory = this.getFactory(this.toolTarget);
54029
55552
  const settablePaths = factory.class.getSettablePaths({ global: this.global });
@@ -57623,7 +59146,10 @@ function anchorDotPaths({ command, projectDirVar }) {
57623
59146
  * first word, so interpreter-prefixed commands (`python3 "$VAR/x.py"`,
57624
59147
  * `node $VAR/x.js`) do not leak a tool-specific variable into targets that do
57625
59148
  * not define it. The recognized forms, each followed by `/`, are `"$VAR"`,
57626
- * `"${VAR}"`, `$VAR` and `${VAR}`:
59149
+ * `"${VAR}"`, `$VAR` and `${VAR}`, plus the fail-closed `${VAR:?}` in either
59150
+ * spelling when `acceptsFailClosedForm` is set (for a tool that writes that
59151
+ * form itself; elsewhere a hand-written `${VAR:?}` is left as written, so it
59152
+ * keeps failing closed):
57627
59153
  *
57628
59154
  * - a quote around the whole path is kept, so a path containing spaces stays
57629
59155
  * one word (`"$VAR/my hook.sh"` becomes `"./my hook.sh"`);
@@ -57648,9 +59174,9 @@ function anchorDotPaths({ command, projectDirVar }) {
57648
59174
  * later words are not converted (see `convertsLaterWords`) or that starts
57649
59175
  * with another variable — every occurrence after the first word.
57650
59176
  */
57651
- function importProjectDirVariable({ command, projectDirVar, firstWordOnly = false }) {
59177
+ function importProjectDirVariable({ command, projectDirVar, firstWordOnly = false, acceptsFailClosedForm = false }) {
57652
59178
  const escapedName = escapeRegExp(projectDirVar.replace(/^\$/, ""));
57653
- const variable = `\\$(?:${escapedName}|\\{${escapedName}\\})`;
59179
+ const variable = `\\$(?:${escapedName}|\\{${escapedName}${acceptsFailClosedForm ? "(?::\\?)?" : ""}\\})`;
57654
59180
  const pattern = new RegExp(`(?:"${variable}"/(["']?)|${variable}/)`, "g");
57655
59181
  const leading = command.length - command.trimStart().length;
57656
59182
  const inFirstWord = (offset) => offset === leading || offset === leading + 1 && command.charAt(leading) === "\"";
@@ -57761,6 +59287,15 @@ function groupDefinitionsByMatcher({ definitions, eventName, converterConfig, wa
57761
59287
  }
57762
59288
  return byMatcher;
57763
59289
  }
59290
+ /**
59291
+ * The project directory variable as generate writes it into a shell command:
59292
+ * `$DEVIN_PLUGIN_ROOT` -> `${DEVIN_PLUGIN_ROOT:?}` for a tool that opts into
59293
+ * {@link ToolHooksConverterConfig.failsClosedOnEmptyProjectDirVar}.
59294
+ */
59295
+ function emittedProjectDirVar(converterConfig) {
59296
+ const { projectDirVar } = converterConfig;
59297
+ return converterConfig.failsClosedOnEmptyProjectDirVar ? `\${${projectDirVar.replace(/^\$/, "")}:?}` : projectDirVar;
59298
+ }
57764
59299
  /** `$CLAUDE_PROJECT_DIR` -> `${CLAUDE_PROJECT_DIR}`, the form the tool substitutes. */
57765
59300
  function bracePlaceholder(projectDirVar) {
57766
59301
  return `\${${projectDirVar.replace(/^\$/, "")}}`;
@@ -57808,12 +59343,12 @@ function applyCommandPrefix({ def, converterConfig }) {
57808
59343
  converterConfig
57809
59344
  }) ? command : anchorDotPaths({
57810
59345
  command,
57811
- projectDirVar: converterConfig.projectDirVar
59346
+ projectDirVar: emittedProjectDirVar(converterConfig)
57812
59347
  });
57813
59348
  if (!shouldPrefix || typeof trimmedCommand !== "string") return typeof def.command === "string" ? anchorInline(def.command) : def.command;
57814
59349
  const relativeCommand = trimmedCommand.replace(/^(["'])\.\//, "$1").replace(/^\.\//, "");
57815
59350
  if (isExecForm) return `${bracePlaceholder(converterConfig.projectDirVar)}/${stripSurroundingQuotes(relativeCommand)}`;
57816
- return anchorInline(`"${converterConfig.projectDirVar}"/${relativeCommand}`);
59351
+ return anchorInline(`"${emittedProjectDirVar(converterConfig)}"/${relativeCommand}`);
57817
59352
  }
57818
59353
  /** Whether a field restricted to some events applies on this one. */
57819
59354
  function isEventApplicable({ events, eventName }) {
@@ -58463,7 +59998,8 @@ function stripCommandPrefix({ command, args, shell, converterConfig, warn }) {
58463
59998
  }) || !runsInPosixShell({
58464
59999
  shell,
58465
60000
  converterConfig
58466
- })
60001
+ }),
60002
+ acceptsFailClosedForm: converterConfig.failsClosedOnEmptyProjectDirVar ?? false
58467
60003
  });
58468
60004
  stripped = result.command;
58469
60005
  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.`);
@@ -63104,7 +64640,9 @@ var DevinHooks = class extends ToolHooks {
63104
64640
  * anchored to the plugin install directory rather than run against the
63105
64641
  * consumer's workspace. Devin CLI v3000.5.20+ sets `DEVIN_PLUGIN_ROOT` in the
63106
64642
  * environment of hooks contributed by a plugin, and runs `command` as a shell
63107
- * command, so the quoted `"$DEVIN_PLUGIN_ROOT"/...` form expands there. Bare
64643
+ * command, so the quoted `"${DEVIN_PLUGIN_ROOT:?}"/...` form expands there.
64644
+ * The `:?` makes an older CLI, which leaves the variable empty, stop the hook
64645
+ * with an error rather than run `/scripts/...` from the filesystem root. Bare
63108
64646
  * commands such as `npx prettier --write` are left intact.
63109
64647
  *
63110
64648
  * `DEVIN_PLUGIN_ROOT` is chosen over the shorter `PLUGIN_ROOT` (v3000.11.92+)
@@ -63118,6 +64656,7 @@ var DevinHooks = class extends ToolHooks {
63118
64656
  const DEVIN_PLUGIN_CONVERTER_CONFIG = {
63119
64657
  ...DEVIN_CONVERTER_CONFIG,
63120
64658
  projectDirVar: "$DEVIN_PLUGIN_ROOT",
64659
+ failsClosedOnEmptyProjectDirVar: true,
63121
64660
  prefixDotRelativeCommandsOnly: true,
63122
64661
  importedProjectDirVarAliases: ["$PLUGIN_ROOT", "$CLAUDE_PLUGIN_ROOT"]
63123
64662
  };
@@ -63125,7 +64664,7 @@ const DEVIN_PLUGIN_CONVERTER_CONFIG = {
63125
64664
  * Hooks inside a Devin plugin bundle (`<plugin>/hooks.json`). The file is the
63126
64665
  * same bare event map as `.devin/hooks.v1.json` (no `hooks` wrapper key), as
63127
64666
  * in Cognition's plugin templates. Unlike the `devin` target, `./`-relative
63128
- * commands are anchored to `$DEVIN_PLUGIN_ROOT` (see
64667
+ * commands are anchored to `${DEVIN_PLUGIN_ROOT:?}` (see
63129
64668
  * `DEVIN_PLUGIN_CONVERTER_CONFIG`).
63130
64669
  *
63131
64670
  * @see https://docs.devin.ai/cli/extensibility/plugins/overview
@@ -75131,7 +76670,8 @@ var CodewhaleMcp = class CodewhaleMcp extends ToolMcp {
75131
76670
  }
75132
76671
  static async fromRulesyncMcp({ outputRoot = process.cwd(), rulesyncMcp, validate = true, global = false, logger }) {
75133
76672
  const paths = this.getSettablePaths({ global });
75134
- const existingContent = await readFileContentOrNull(join(outputRoot, paths.relativeDirPath, paths.relativeFilePath));
76673
+ const filePath = join(outputRoot, paths.relativeDirPath, paths.relativeFilePath);
76674
+ const existingContent = await readFileContentOrNull(filePath);
75135
76675
  const json = existingContent === null ? {} : parseCodewhaleMcpConfig({
75136
76676
  fileContent: existingContent,
75137
76677
  relativePath: join(paths.relativeDirPath, paths.relativeFilePath)
@@ -75144,7 +76684,11 @@ var CodewhaleMcp = class CodewhaleMcp extends ToolMcp {
75144
76684
  [serversKey]: mcpServers
75145
76685
  };
75146
76686
  const fileContent = JSON.stringify(codewhaleConfig, null, 2);
75147
- if (!global && existingContent?.trim() !== fileContent.trim()) logger?.info(`Codewhale MCP: ${join(paths.relativeDirPath, paths.relativeFilePath)} changed, so Codewhale loads none of its servers until you run /mcp review and /mcp approve <digest> again.`);
76687
+ if (!global && !fileContentsEquivalent({
76688
+ filePath,
76689
+ expected: fileContent,
76690
+ existing: existingContent
76691
+ })) logger?.info(`Codewhale MCP: ${join(paths.relativeDirPath, paths.relativeFilePath)} changed, so Codewhale loads none of its servers until you run /mcp review and /mcp approve <digest> again.`);
75148
76692
  return new CodewhaleMcp({
75149
76693
  outputRoot,
75150
76694
  relativeDirPath: paths.relativeDirPath,
@@ -96055,20 +97599,32 @@ function restrictedByAllToolsCategory(config) {
96055
97599
  record: config.permission,
96056
97600
  key: "*"
96057
97601
  }) ?? {}).filter(([pattern, action]) => !/\s/.test(pattern) && (action === "deny" || action === "ask" && pattern !== "*")).map(([pattern]) => pattern).find((pattern) => {
96058
- const lowered = pattern.toLowerCase();
96059
- if (namesGitDirectory(lowered)) return true;
96060
- const matches = createShadowingRestrictionsTest([{
96061
- pattern: lowered.replace(/^\.?\//, ""),
96062
- fromAllToolsCategory: true
96063
- }]);
96064
- return GIT_WRITTEN_PATHS.some((path) => matches(path).length > 0);
97602
+ return carveOutCheckSpellings(pattern.toLowerCase()).some((spelling) => {
97603
+ if (namesGitDirectory(spelling)) return true;
97604
+ const matches = createShadowingRestrictionsTest([{
97605
+ pattern: spelling.replace(/^\.?\//, ""),
97606
+ fromAllToolsCategory: true
97607
+ }]);
97608
+ return GIT_WRITTEN_PATHS.some((path) => matches(path).length > 0);
97609
+ });
96065
97610
  });
96066
97611
  }
97612
+ function carveOutCheckSpellings(pattern) {
97613
+ const slashed = pattern.replaceAll("\\", "/");
97614
+ return slashed === pattern ? [pattern] : [pattern, slashed];
97615
+ }
96067
97616
  function isRestrictedInWorkspaceRootTable({ pattern, table }) {
96068
97617
  const readRules = {};
96069
97618
  for (const [tablePattern, access] of Object.entries(table)) {
96070
97619
  if (tablePattern === pattern) continue;
96071
- readRules[tablePattern] = access === "write" ? "allow" : "deny";
97620
+ if (access === "write") {
97621
+ readRules[tablePattern] = "allow";
97622
+ continue;
97623
+ }
97624
+ for (const spelling of carveOutCheckSpellings(tablePattern)) {
97625
+ if (spelling === pattern) return true;
97626
+ readRules[spelling] = "deny";
97627
+ }
96072
97628
  }
96073
97629
  return isCoveredByReadRestriction({
96074
97630
  pattern,
@@ -114949,7 +116505,8 @@ function buildRulesStrategy(ctx) {
114949
116505
  global,
114950
116506
  dryRun,
114951
116507
  logger,
114952
- language: config.getLanguage()
116508
+ language: config.getLanguage(),
116509
+ preserveUnmanagedContent: config.getPreserveUnmanagedRuleContent()
114953
116510
  }),
114954
116511
  loadSource: (p) => p.loadToolFiles(),
114955
116512
  toRulesync: (p, files) => p.convertToolFilesToRulesyncFiles(files),
@@ -115586,7 +117143,8 @@ const RETIREMENT_SPECS = {
115586
117143
  ...params,
115587
117144
  simulateCommands: config.getSimulateCommands(),
115588
117145
  simulateSubagents: config.getSimulateSubagents(),
115589
- simulateSkills: config.getSimulateSkills()
117146
+ simulateSkills: config.getSimulateSkills(),
117147
+ preserveUnmanagedContent: config.getPreserveUnmanagedRuleContent()
115590
117148
  }),
115591
117149
  unownedPaths: ({ toolTarget, outputRoot }) => (toolRuleFactories.get(toolTarget)?.class.getSettablePaths().alternativeRoots ?? []).map((alt) => resolve(outputRoot, alt.relativeDirPath, alt.relativeFilePath))
115592
117150
  },
@@ -115710,14 +117268,23 @@ function scheduleRetiredTargetSweeps({ config, logger, sweepPlan, sourceLoadFail
115710
117268
  sweepPlan,
115711
117269
  unownedPaths
115712
117270
  }),
115713
- reportDeleted: () => processor.getRemovedPaths()
117271
+ reportDeleted: () => processor.getRemovedPaths(),
117272
+ reportWritten: () => processor.getSweepWrites()
115714
117273
  });
115715
117274
  } else {
115716
117275
  const processor = spec.create(params, config);
117276
+ const ownershipProcessor = config.getPreserveUnownedSkills() ? spec.create({
117277
+ ...params,
117278
+ logger: new ConsoleLogger({
117279
+ verbose: false,
117280
+ silent: true
117281
+ })
117282
+ }, config) : void 0;
115717
117283
  featurePlan.defer({
115718
117284
  sweep: () => sweepDirs({
115719
117285
  processor,
115720
- sweepPlan
117286
+ sweepPlan,
117287
+ ownershipProcessor
115721
117288
  }),
115722
117289
  reportDeleted: () => processor.getRemovedPaths()
115723
117290
  });
@@ -115734,18 +117301,36 @@ async function sweepFiles({ processor, sweepPlan, unownedPaths }) {
115734
117301
  const present = await Promise.all(candidates.map((f) => fileExists(f.getFilePath())));
115735
117302
  return await processor.removeOrphanAiFiles(candidates.filter((_, index) => present[index]), []) > 0;
115736
117303
  }
115737
- async function sweepDirs({ processor, sweepPlan }) {
115738
- return await processor.removeOrphanAiDirs(await sweepPlan.rejectClaimed({
117304
+ async function sweepDirs({ processor, sweepPlan, ownershipProcessor }) {
117305
+ const isOwned = ownershipProcessor ? await loadSourceOwnedPaths(ownershipProcessor) : void 0;
117306
+ return await processor.removeOrphanAiDirs((await sweepPlan.rejectClaimed({
115739
117307
  items: await processor.loadToolDirsToDelete(),
115740
117308
  getPath: (d) => d.getDirPath()
115741
- }), []) + await processor.removeOrphanFlatFiles({
115742
- existingFlatFiles: await sweepPlan.rejectClaimed({
117309
+ })).filter((d) => isOwned?.(d.getDirPath()) ?? true), []) + await processor.removeOrphanFlatFiles({
117310
+ existingFlatFiles: (await sweepPlan.rejectClaimed({
115743
117311
  items: await processor.loadToolFlatFilesToDelete(),
115744
117312
  getPath: (d) => d.getFlatFilePath() ?? d.getDirPath()
117313
+ })).filter((d) => {
117314
+ if (isOwned === void 0) return true;
117315
+ const flatFilePath = d.getFlatFilePath();
117316
+ return flatFilePath !== void 0 && isOwned(flatFilePath);
115745
117317
  }),
115746
117318
  generatedDirs: []
115747
117319
  }) > 0;
115748
117320
  }
117321
+ /**
117322
+ * The paths the current sources would write for the processor's target — each
117323
+ * directory, and the file a flattening tool writes in its place — as a
117324
+ * case-folded membership test, matching how the sweeps compare paths.
117325
+ */
117326
+ async function loadSourceOwnedPaths(processor) {
117327
+ const sourceDirs = await processor.convertRulesyncDirsToToolDirs(await processor.loadRulesyncDirs());
117328
+ const owned = new Set(sourceDirs.flatMap((d) => {
117329
+ const flatFilePath = d.getFlatFilePath();
117330
+ return [d.getDirPath(), ...flatFilePath === void 0 ? [] : [flatFilePath]].map((path) => caseFoldIdentity(resolve(path)));
117331
+ }));
117332
+ return (path) => owned.has(caseFoldIdentity(resolve(path)));
117333
+ }
115749
117334
  // src/lib/shared-file-derive.ts
115750
117335
  /**
115751
117336
  * The single declaration of the cross-feature write order for shared
@@ -115991,29 +117576,30 @@ async function processDirFeatureGeneration(params) {
115991
117576
  ...d.getOtherFiles().map((f) => join(dirPath, f.relativeFilePathToDirPath))
115992
117577
  ];
115993
117578
  }) });
115994
- if (config.getDelete() && !processor.hasRulesyncSourceLoadFailure()) sweepPlan.defer({
115995
- sweep: async () => {
115996
- const existingToolDirs = await processor.loadToolDirsToDelete();
115997
- const orphanDirCount = await processor.removeOrphanAiDirs(await sweepPlan.rejectClaimed({
115998
- items: existingToolDirs,
115999
- getPath: (d) => d.getDirPath()
116000
- }), toolDirs);
116001
- const existingFlatFiles = await processor.loadToolFlatFilesToDelete();
116002
- const orphanFileCount = await processor.removeOrphanFlatFiles({
116003
- existingFlatFiles: await sweepPlan.rejectClaimed({
116004
- items: existingFlatFiles,
116005
- getPath: (d) => d.getFlatFilePath() ?? d.getDirPath()
116006
- }),
116007
- generatedDirs: toolDirs
116008
- });
116009
- const orphanInDirCount = await processor.removeOrphanFilesInAiDirs({
116010
- generatedDirs: toolDirs,
116011
- isClaimed: (path) => sweepPlan.isGeneratedExactly({ path })
116012
- });
116013
- return orphanDirCount + orphanFileCount + orphanInDirCount > 0;
116014
- },
116015
- reportDeleted: () => processor.getRemovedPaths()
116016
- });
117579
+ if (config.getDelete() && !processor.hasRulesyncSourceLoadFailure()) {
117580
+ const preserveUnownedSkills = config.getPreserveUnownedSkills();
117581
+ sweepPlan.defer({
117582
+ sweep: async () => {
117583
+ const orphanDirCount = preserveUnownedSkills ? 0 : await processor.removeOrphanAiDirs(await sweepPlan.rejectClaimed({
117584
+ items: await processor.loadToolDirsToDelete(),
117585
+ getPath: (d) => d.getDirPath()
117586
+ }), toolDirs);
117587
+ const orphanFileCount = preserveUnownedSkills ? 0 : await processor.removeOrphanFlatFiles({
117588
+ existingFlatFiles: await sweepPlan.rejectClaimed({
117589
+ items: await processor.loadToolFlatFilesToDelete(),
117590
+ getPath: (d) => d.getFlatFilePath() ?? d.getDirPath()
117591
+ }),
117592
+ generatedDirs: toolDirs
117593
+ });
117594
+ const orphanInDirCount = await processor.removeOrphanFilesInAiDirs({
117595
+ generatedDirs: toolDirs,
117596
+ isClaimed: (path) => sweepPlan.isGeneratedExactly({ path })
117597
+ });
117598
+ return orphanDirCount + orphanFileCount + orphanInDirCount > 0;
117599
+ },
117600
+ reportDeleted: () => processor.getRemovedPaths()
117601
+ });
117602
+ }
116017
117603
  return {
116018
117604
  count: totalCount,
116019
117605
  paths: allPaths,
@@ -116652,6 +118238,7 @@ async function generateRulesCore(params) {
116652
118238
  skills: processorSkills,
116653
118239
  featureOptions,
116654
118240
  delete: config.getDelete(),
118241
+ preserveUnmanagedContent: config.getPreserveUnmanagedRuleContent(),
116655
118242
  dryRun: config.isPreviewMode(),
116656
118243
  logger
116657
118244
  });
@@ -116666,7 +118253,7 @@ async function generateRulesCore(params) {
116666
118253
  const processor = createProcessor({
116667
118254
  toolTarget,
116668
118255
  outputRoot,
116669
- featureOptions: config.getFeatureOptions(toolTarget, "rules"),
118256
+ featureOptions: getRulesFeatureOptions(config, toolTarget),
116670
118257
  skills
116671
118258
  });
116672
118259
  const rulesyncFiles = await processor.loadRulesyncFiles();
@@ -117108,7 +118695,8 @@ async function importRulesCore(params) {
117108
118695
  }),
117109
118696
  toolTarget: tool,
117110
118697
  global,
117111
- logger
118698
+ logger,
118699
+ preserveUnmanagedContent: config.getPreserveUnmanagedRuleContent()
117112
118700
  };
117113
118701
  const rulesProcessor = new RulesProcessor(baseParams);
117114
118702
  const toolFiles = await rulesProcessor.loadToolFiles();
@@ -117121,7 +118709,7 @@ async function importRulesCore(params) {
117121
118709
  ...baseParams,
117122
118710
  inputRoots: config.getInputRoots(),
117123
118711
  deriveSubprojectPathFromGlobs: config.getDeriveSubprojectPathFromGlobs(),
117124
- featureOptions: config.getFeatureOptions(tool, "rules")
118712
+ featureOptions: getRulesFeatureOptions(config, tool)
117125
118713
  }).warnForFoldImportDuplicationRisk();
117126
118714
  } catch (error) {
117127
118715
  logger.warn(`Skipped the ${tool} import duplication check: ${formatError(error)}`);
@@ -117380,6 +118968,6 @@ const CHECKS_IMPORT_STRATEGY = {
117380
118968
  missingLabel: "check files",
117381
118969
  createdLabel: "check files"
117382
118970
  };
117383
- export { RulesyncRuleFrontmatterSchema as $, RULESYNC_PERMISSIONS_SCHEMA_URL as $n, getFileSizeAndExecutableBit as $t, AUGMENTCODE_SETTINGS_LOCAL_FILE_NAME as A, ToolTargetSchema as An, fallbackLogger as At, CLAUDECODE_MEMORIES_DIR_NAME as B, RULESYNC_CONFIG_RELATIVE_FILE_PATH as Bn, assertDirectoryIfExists as Bt, FACTORYDROID_DIR as C, toPosixPath as Cn, SourceEntrySchema as Ct, CODEBUDDY_DIR as D, ALL_TOOL_TARGETS as Dn, ConsoleLogger as Dt, COMMANDCODE_SETTINGS_LOCAL_FILE_NAME as E, mapWithConcurrency as En, findControlCharacter as Et, CODEXCLI_BASH_RULES_FILE_NAME as F, FEATURE_SOURCE_TREE_ENTRIES as Fn, CLIError as Ft, getLocalSkillDirNames as G, RULESYNC_CURATED_SUBAGENTS_RELATIVE_DIR_PATH as Gn, assertWritablePathInsideRoot as Gt, CLAUDECODE_SKILLS_DIR_PATH as H, RULESYNC_CURATED_COMMANDS_RELATIVE_DIR_PATH as Hn, assertNoSymlinkBelowRoot as Ht, CODEXCLI_DIR as I, MAX_FILE_SIZE as In, ErrorCodes as It, RulesyncSubagent as J, RULESYNC_LOCAL_CONFIG_RELATIVE_FILE_PATH as Jn, directoryExists as Jt, classifyRemoteName as K, RULESYNC_HOOKS_RELATIVE_FILE_PATH as Kn, checkPathTraversal as Kt, CLAUDECODE_AGENT_MEMORY_LOCAL_DIR_NAME as L, RULESYNC_AIIGNORE_RELATIVE_FILE_PATH as Ln, parseJsonc as Lt, groupSpellingsByCaseFoldedIdentity as M, ALL_FEATURES_WITH_WILDCARD as Mn, withFallbackLoggerTarget as Mt, sweepRefusalReason as N, DEPRECATED_FEATURE_REPLACEMENTS as Nn, resetRunWarningState as Nt, CODEBUDDY_LOCAL_RULE_FILE_NAME as O, ALL_TOOL_TARGETS_WITH_WILDCARD as On, JsonLogger as Ot, loadYaml as P, CURATED_RULES_FEATURE_SUBDIR as Pn, withWarnOnceScope as Pt, RulesyncRule as Q, RULESYNC_PERMISSIONS_RELATIVE_FILE_PATH as Qn, findFilesByGlobs as Qt, CLAUDECODE_DIR as R, RULESYNC_CHECKS_RELATIVE_DIR_PATH as Rn, PathOutsideRootError as Rt, LETTACODE_SETTINGS_LOCAL_FILE_NAME as S, splitPathSegments as Sn, GITIGNORE_DESTINATION_KEY as St, COMMANDCODE_DIR as T, writeFileContent as Tn, getSourceTransport as Tt, findProjectInstructionBudgetFindings as U, RULESYNC_CURATED_RULES_RELATIVE_DIR_PATH as Un, assertPathResolvesInsideRoot as Ut, CLAUDECODE_SETTINGS_LOCAL_FILE_NAME as V, RULESYNC_CONFIG_SCHEMA_URL as Vn, assertLandingOutsideVcsMetadata as Vt, toInstructionBudgetFile as W, RULESYNC_CURATED_SKILLS_RELATIVE_DIR_PATH as Wn, assertTreeContainsNoSymlinks as Wt, RulesyncSkill as X, RULESYNC_MCP_SCHEMA_URL as Xn, fileExists as Xt, RulesyncSubagentFrontmatterSchema as Y, RULESYNC_MCP_RELATIVE_FILE_PATH as Yn, ensureDir as Yt, RulesyncSkillFrontmatterSchema as Z, RULESYNC_NPM_SOURCES_LOCK_RELATIVE_FILE_PATH as Zn, fileExistsStrict as Zt, SkillsProcessor as _, removeFileWithoutFollowingSymlinks as _n, mergeInputRootConfigs as _t, convertFromTool as a, listDirectoryEntryNames as an, RULESYNC_USER_CONFIG_DIR_NAME as ar, RulesyncHooks as at, REASONIX_LOCAL_RULE_FILE_NAME as b, resolvedRelativePath as bn, CONFLICTING_TARGET_PAIRS as bt, ELLIPSIS_WIDTH as c, normalizePosixDirPath as cn, formatError as cr, RulesyncCommand as ct, McpProcessor as d, readFileContent as dn, quoteForLog as dr, RulesyncCheckFrontmatterSchema as dt, getHomeDirectory as en, RULESYNC_RELATIVE_DIR_PATH as er, QWENCODE_DIR as et, IgnoreProcessor as f, readFileContentOrNull as fn, stripControlCharacters as fr, stringifyFrontmatter as ft, SubagentsProcessor as g, removeFileStrict as gn, ConfigResolver as gt, RulesProcessor as h, removeFile as hn, stripHiddenCharacters as hr, SKILL_FILE_NAME as ht, inspectInputRoots as i, isSymlink as in, RULESYNC_SUBAGENTS_RELATIVE_DIR_PATH as ir, RulesyncIgnore as it, caseFoldIdentity as j, ALL_FEATURES as jn, warnOnConflictingFlags as jt, AUGMENTCODE_DIR as k, PACKAGING_TOOL_TARGETS as kn, WarningCollectingLogger as kt, displayWidthOf as l, pathEscapesRoot as ln, truncateText as lr, RulesyncCommandFrontmatterSchema as lt, ChecksProcessor as m, removeDirectoryStrict as mn, stripControlCharactersKeepingLineFeedsAndTabs as mr, SHARED_USER_MANAGED_CONFIG_PATHS as mt, formatSourceLoadFailure as n, isFileSystemError as nn, RULESYNC_SKILLS_RELATIVE_DIR_PATH as nr, RulesyncPermissions as nt, getProcessorRegistryEntry as o, listFilePathsRecursively as on, RULESYNC_XDG_CONFIG_HOME_DEFAULT_DIR_NAME as or, getRulesyncSourceCandidates as ot, HooksProcessor as p, removeDirectory as pn, stripControlCharactersKeepingLineFeeds as pr, isRecord as pt, hasWindowsFoldableName as q, RULESYNC_IGNORE_RELATIVE_FILE_PATH as qn, createTempDirectory as qt, generate as r, isRootDirPath as rn, RULESYNC_SOURCES_LOCK_RELATIVE_FILE_PATH as rr, RulesyncMcp as rt, parseCommaSeparatedList as s, listSubdirectoryNames as sn, formatMegabytes as sr, resolveRulesyncSourceWritePath as st, importFromTool as t, isFileNotFoundError as tn, RULESYNC_RULES_RELATIVE_DIR_PATH as tr, QWENCODE_LOCAL_RULE_FILE_NAME as tt, shortenToWidth as u, posixRelativePathEscapesRoot as un, hasEnclosingMarkOutsideKeycap as ur, RulesyncCheck as ut, CRUSH_LOCAL_RULE_FILE_NAME as v, removeTempDirectory as vn, parseConfigFileContent as vt, FACTORYDROID_SETTINGS_LOCAL_FILE_NAME as w, writeFileBuffer as wn, assertTargetsFeaturesExclusive as wt, LETTACODE_DIR as x, runWithDirectoryRollback as xn, ConfigFileSchema as xt, CommandsProcessor as y, resolvePath as yn, resolveEffectiveInputRoots as yt, CLAUDECODE_LOCAL_RULE_FILE_NAME as z, RULESYNC_COMMANDS_RELATIVE_DIR_PATH as zn, applyFileMode as zt };
118971
+ export { checkLockedSkillsAreValid as $, isFileNotFoundError as $n, RULESYNC_SOURCES_LOCK_RELATIVE_FILE_PATH as $r, QWENCODE_LOCAL_RULE_FILE_NAME as $t, AUGMENTCODE_SETTINGS_LOCAL_FILE_NAME as A, withFallbackLoggerTarget as An, CURATED_RULES_FEATURE_SUBDIR as Ar, getLockedFileFeatureState as At, CLAUDECODE_MEMORIES_DIR_NAME as B, assertNoSymlinkBelowRoot as Bn, RULESYNC_CURATED_SKILLS_RELATIVE_DIR_PATH as Br, setLockedSource as Bt, FACTORYDROID_DIR as C, getSourceTransport as Cn, ALL_TOOL_TARGETS as Cr, selectDeclaredFiles as Ct, CODEBUDDY_DIR as D, WarningCollectingLogger as Dn, ALL_FEATURES as Dr, writeSkillAndComputeIntegrity as Dt, COMMANDCODE_SETTINGS_LOCAL_FILE_NAME as E, JsonLogger as En, ToolTargetSchema as Er, shouldUseRootFallback as Et, CODEXCLI_BASH_RULES_FILE_NAME as F, parseJsonc as Fn, RULESYNC_COMMANDS_RELATIVE_DIR_PATH as Fr, normalizeLockKey as Ft, getLocalSkillDirNames as G, createTempDirectory as Gn, RULESYNC_MCP_RELATIVE_FILE_PATH as Gr, hasWindowsFoldableName as Gt, CLAUDECODE_SKILLS_DIR_PATH as H, assertTreeContainsNoSymlinks as Hn, RULESYNC_HOOKS_RELATIVE_FILE_PATH as Hr, writeLockFile as Ht, CODEXCLI_DIR as I, PathOutsideRootError as In, RULESYNC_CONFIG_RELATIVE_FILE_PATH as Ir, normalizeSourceKey as It, buildFileLockUpdate as J, fileExists as Jn, RULESYNC_PERMISSIONS_RELATIVE_FILE_PATH as Jr, RulesyncSkill as Jt, assertMatchingFilesFound as K, directoryExists as Kn, RULESYNC_MCP_SCHEMA_URL as Kr, RulesyncSubagent as Kt, CLAUDECODE_AGENT_MEMORY_LOCAL_DIR_NAME as L, applyFileMode as Ln, RULESYNC_CONFIG_SCHEMA_URL as Lr, readLockFile as Lt, groupSpellingsByCaseFoldedIdentity as M, withWarnOnceScope as Mn, MAX_FILE_SIZE as Mr, getLockedSkillNames as Mt, sweepRefusalReason as N, CLIError as Nn, RULESYNC_AIIGNORE_RELATIVE_FILE_PATH as Nr, getLockedSource as Nt, CODEBUDDY_LOCAL_RULE_FILE_NAME as O, fallbackLogger as On, ALL_FEATURES_WITH_WILDCARD as Or, SOURCE_FILE_FEATURES as Ot, loadYaml as P, ErrorCodes as Pn, RULESYNC_CHECKS_RELATIVE_DIR_PATH as Pr, mapFileFeatures as Pt, checkLockedFilesAreValid as Q, getHomeDirectory as Qn, RULESYNC_SKILLS_RELATIVE_DIR_PATH as Qr, QWENCODE_DIR as Qt, CLAUDECODE_DIR as R, assertDirectoryIfExists as Rn, RULESYNC_CURATED_COMMANDS_RELATIVE_DIR_PATH as Rr, renameLockedSource as Rt, LETTACODE_SETTINGS_LOCAL_FILE_NAME as S, assertTargetsFeaturesExclusive as Sn, mapWithConcurrency as Sr, resolveSkillsSourcePath as St, COMMANDCODE_DIR as T, ConsoleLogger as Tn, PACKAGING_TOOL_TARGETS as Tr, shouldSkipSkill as Tt, findProjectInstructionBudgetFindings as U, assertWritablePathInsideRoot as Un, RULESYNC_IGNORE_RELATIVE_FILE_PATH as Ur, parseSource as Ut, CLAUDECODE_SETTINGS_LOCAL_FILE_NAME as V, assertPathResolvesInsideRoot as Vn, RULESYNC_CURATED_SUBAGENTS_RELATIVE_DIR_PATH as Vr, toFileFeatureLockFields as Vt, toInstructionBudgetFile as W, checkPathTraversal as Wn, RULESYNC_LOCAL_CONFIG_RELATIVE_FILE_PATH as Wr, classifyRemoteName as Wt, canReuseLockedFiles as X, findFilesByGlobs as Xn, RULESYNC_RELATIVE_DIR_PATH as Xr, RulesyncRule as Xt, buildLockUpdate as Y, fileExistsStrict as Yn, RULESYNC_PERMISSIONS_SCHEMA_URL as Yr, RulesyncSkillFrontmatterSchema as Yt, canReuseLockedSkills as Z, getFileSizeAndExecutableBit as Zn, RULESYNC_RULES_RELATIVE_DIR_PATH as Zr, RulesyncRuleFrontmatterSchema as Zt, SkillsProcessor as _, resolveEffectiveInputRoots as _n, runWithDirectoryRollback as _r, normalizeSkillSelection as _t, convertFromTool as a, truncateText as ai, resolveRulesyncSourceWritePath as an, listSubdirectoryNames as ar, getFileFeatureNoun as at, REASONIX_LOCAL_RULE_FILE_NAME as b, GITIGNORE_DESTINATION_KEY as bn, writeFileBuffer as br, resolveFileFeatureSourcePath as bt, ELLIPSIS_WIDTH as c, stripControlCharacters as ci, RulesyncCheck as cn, posixRelativePathEscapesRoot as cr, groupRemoteFilesBySkillRoot as ct, McpProcessor as d, stripHiddenCharacters as di, isRecord as dn, removeDirectory as dr, lockedFileConfigMatches as dt, RULESYNC_SUBAGENTS_RELATIVE_DIR_PATH as ei, RulesyncPermissions as en, isFileSystemError as er, cleanPreviousCuratedFiles as et, IgnoreProcessor as f, SHARED_USER_MANAGED_CONFIG_PATHS as fn, removeFile as fr, lockedRefMatchesDeclared as ft, SubagentsProcessor as g, parseConfigFileContent as gn, resolvedRelativePath as gr, normalizeRuleSelection as gt, RulesProcessor as h, mergeInputRootConfigs as hn, resolvePath as hr, normalizeRuleFilterName as ht, inspectInputRoots as i, formatError as ii, getRulesyncSourceCandidates as in, listFilePathsRecursively as ir, getEmptySelectionFields as it, caseFoldIdentity as j, resetRunWarningState as jn, FEATURE_SOURCE_TREE_ENTRIES as jr, getLockedFileNames as jt, AUGMENTCODE_DIR as k, warnOnConflictingFlags as kn, DEPRECATED_FEATURE_REPLACEMENTS as kr, getLockKeyRepository as kt, displayWidthOf as l, stripControlCharactersKeepingLineFeeds as li, RulesyncCheckFrontmatterSchema as ln, readFileContent as lr, hasEmptySelection as lt, ChecksProcessor as m, ConfigResolver as mn, removeTempDirectory as mr, mergeFetchedWithLockedSkills as mt, formatSourceLoadFailure as n, RULESYNC_XDG_CONFIG_HOME_DEFAULT_DIR_NAME as ni, RulesyncIgnore as nn, isSymlink as nr, formatInstalledCounts as nt, getProcessorRegistryEntry as o, hasEnclosingMarkOutsideKeycap as oi, RulesyncCommand as on, normalizePosixDirPath as or, getFirstPathSeparatorIndex as ot, HooksProcessor as p, SKILL_FILE_NAME as pn, removeFileWithoutFollowingSymlinks as pr, lockedSkillConfigMatches as pt, assertMatchingSkillsFound as q, ensureDir as qn, RULESYNC_NPM_SOURCES_LOCK_RELATIVE_FILE_PATH as qr, RulesyncSubagentFrontmatterSchema as qt, generate as r, formatMegabytes as ri, RulesyncHooks as rn, listDirectoryEntryNames as rr, getCuratedFileFeatureRelativeDirPath as rt, parseCommaSeparatedList as s, quoteForLog as si, RulesyncCommandFrontmatterSchema as sn, pathEscapesRoot as sr, getSourceFilters as st, importFromTool as t, RULESYNC_USER_CONFIG_DIR_NAME as ti, RulesyncMcp as tn, isRootDirPath as tr, cleanPreviousCuratedSkills as tt, shortenToWidth as u, stripControlCharactersKeepingLineFeedsAndTabs as ui, stringifyFrontmatter as un, readFileContentOrNull as ur, isWildcardSelection as ut, CRUSH_LOCAL_RULE_FILE_NAME as v, CONFLICTING_TARGET_PAIRS as vn, splitPathSegments as vr, replaceCuratedFiles as vt, FACTORYDROID_SETTINGS_LOCAL_FILE_NAME as w, findControlCharacter as wn, ALL_TOOL_TARGETS_WITH_WILDCARD as wr, shouldSkipFile as wt, LETTACODE_DIR as x, SourceEntrySchema as xn, writeFileContent as xr, resolveSkillsPath as xt, CommandsProcessor as y, ConfigFileSchema as yn, toPosixPath as yr, resolveFileFeaturePath as yt, CLAUDECODE_LOCAL_RULE_FILE_NAME as z, assertLandingOutsideVcsMetadata as zn, RULESYNC_CURATED_RULES_RELATIVE_DIR_PATH as zr, resolveSourceLockKeys as zt };
117384
118972
 
117385
- //# sourceMappingURL=import-BZAYr7ab.js.map
118973
+ //# sourceMappingURL=import-C_TEclz6.js.map