rulesync 43.16.0 → 43.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/index.cjs +246 -1359
- package/dist/cli/index.js +63 -1176
- package/dist/cli/index.js.map +1 -1
- package/dist/{import-BZAYr7ab.js → import-1IIVv7h3.js} +1909 -89
- package/dist/{import-BZAYr7ab.js.map → import-1IIVv7h3.js.map} +1 -1
- package/dist/{import-B2rJ3SBE.cjs → import-T-69RQxs.cjs} +2238 -118
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/package.json +14 -14
|
@@ -3270,6 +3270,9 @@ 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()),
|
|
3275
|
+
preserveUnownedMcpServers: optional(z.boolean()),
|
|
3273
3276
|
deriveSubprojectPathFromGlobs: optional(z.boolean()),
|
|
3274
3277
|
flattenedCommandNaming: optional(FlattenedCommandNamingSchema),
|
|
3275
3278
|
/**
|
|
@@ -3452,6 +3455,9 @@ var Config = class Config {
|
|
|
3452
3455
|
simulateSubagents;
|
|
3453
3456
|
simulateSkills;
|
|
3454
3457
|
preserveUnownedHooks;
|
|
3458
|
+
preserveUnmanagedRuleContent;
|
|
3459
|
+
preserveUnownedSkills;
|
|
3460
|
+
preserveUnownedMcpServers;
|
|
3455
3461
|
deriveSubprojectPathFromGlobs;
|
|
3456
3462
|
flattenedCommandNaming;
|
|
3457
3463
|
language;
|
|
@@ -3480,7 +3486,7 @@ var Config = class Config {
|
|
|
3480
3486
|
inputRoots;
|
|
3481
3487
|
configFilePath;
|
|
3482
3488
|
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 }) {
|
|
3489
|
+
constructor({ outputRoots, targets, features, verbose, delete: isDelete, global, silent, simulateCommands, simulateSubagents, simulateSkills, preserveUnownedHooks, preserveUnmanagedRuleContent, preserveUnownedSkills, preserveUnownedMcpServers, deriveSubprojectPathFromGlobs, flattenedCommandNaming, language, gitignoreTargetsOnly, gitignoreDestination, dryRun, check, retireTargets, retireFeatures, inputRoot, inputRoots, configFilePath, sources, configFileTargets, configFileSelection }) {
|
|
3484
3490
|
assertTargetsFeaturesExclusive({
|
|
3485
3491
|
targets,
|
|
3486
3492
|
features
|
|
@@ -3514,6 +3520,9 @@ var Config = class Config {
|
|
|
3514
3520
|
this.simulateSubagents = simulateSubagents ?? false;
|
|
3515
3521
|
this.simulateSkills = simulateSkills ?? false;
|
|
3516
3522
|
this.preserveUnownedHooks = preserveUnownedHooks ?? false;
|
|
3523
|
+
this.preserveUnmanagedRuleContent = preserveUnmanagedRuleContent === true;
|
|
3524
|
+
this.preserveUnownedSkills = preserveUnownedSkills === true;
|
|
3525
|
+
this.preserveUnownedMcpServers = preserveUnownedMcpServers === true;
|
|
3517
3526
|
this.deriveSubprojectPathFromGlobs = deriveSubprojectPathFromGlobs ?? false;
|
|
3518
3527
|
this.flattenedCommandNaming = flattenedCommandNaming ?? "basename";
|
|
3519
3528
|
this.language = language;
|
|
@@ -3774,6 +3783,15 @@ var Config = class Config {
|
|
|
3774
3783
|
getPreserveUnownedHooks() {
|
|
3775
3784
|
return this.preserveUnownedHooks;
|
|
3776
3785
|
}
|
|
3786
|
+
getPreserveUnmanagedRuleContent() {
|
|
3787
|
+
return this.preserveUnmanagedRuleContent;
|
|
3788
|
+
}
|
|
3789
|
+
getPreserveUnownedSkills() {
|
|
3790
|
+
return this.preserveUnownedSkills;
|
|
3791
|
+
}
|
|
3792
|
+
getPreserveUnownedMcpServers() {
|
|
3793
|
+
return this.preserveUnownedMcpServers;
|
|
3794
|
+
}
|
|
3777
3795
|
getFlattenedCommandNaming() {
|
|
3778
3796
|
return this.flattenedCommandNaming;
|
|
3779
3797
|
}
|
|
@@ -3839,6 +3857,24 @@ var Config = class Config {
|
|
|
3839
3857
|
return this.dryRun || this.check;
|
|
3840
3858
|
}
|
|
3841
3859
|
};
|
|
3860
|
+
/**
|
|
3861
|
+
* The `rules` options for `target` in a run, with the `include` rule selection
|
|
3862
|
+
* always read from the configuration file. `--targets` replaces the object
|
|
3863
|
+
* form of `targets`, and with it every per-target option, but a target that
|
|
3864
|
+
* selects its rules there must not receive every rule just because it was
|
|
3865
|
+
* picked with `--targets`: that would write the rules the user deliberately
|
|
3866
|
+
* kept away from it.
|
|
3867
|
+
*/
|
|
3868
|
+
function getRulesFeatureOptions(config, target) {
|
|
3869
|
+
const options = config.getFeatureOptions(target, "rules");
|
|
3870
|
+
if (options !== void 0 && "include" in options) return options;
|
|
3871
|
+
const configFileOptions = config.getConfigFileFeatureOptions(target, "rules");
|
|
3872
|
+
if (configFileOptions === void 0 || !("include" in configFileOptions)) return options;
|
|
3873
|
+
return {
|
|
3874
|
+
...options,
|
|
3875
|
+
include: configFileOptions.include
|
|
3876
|
+
};
|
|
3877
|
+
}
|
|
3842
3878
|
// src/config/config-resolver.ts
|
|
3843
3879
|
const getDefaults = () => ({
|
|
3844
3880
|
targets: ["agentsmd"],
|
|
@@ -3853,6 +3889,9 @@ const getDefaults = () => ({
|
|
|
3853
3889
|
simulateSubagents: false,
|
|
3854
3890
|
simulateSkills: false,
|
|
3855
3891
|
preserveUnownedHooks: false,
|
|
3892
|
+
preserveUnmanagedRuleContent: false,
|
|
3893
|
+
preserveUnownedSkills: false,
|
|
3894
|
+
preserveUnownedMcpServers: false,
|
|
3856
3895
|
deriveSubprojectPathFromGlobs: false,
|
|
3857
3896
|
flattenedCommandNaming: "basename",
|
|
3858
3897
|
gitignoreTargetsOnly: true,
|
|
@@ -4191,6 +4230,21 @@ var ConfigResolver = class {
|
|
|
4191
4230
|
file: configByFile.preserveUnownedHooks,
|
|
4192
4231
|
fallback: getDefaults().preserveUnownedHooks
|
|
4193
4232
|
}),
|
|
4233
|
+
preserveUnmanagedRuleContent: pick({
|
|
4234
|
+
cli: void 0,
|
|
4235
|
+
file: configByFile.preserveUnmanagedRuleContent,
|
|
4236
|
+
fallback: getDefaults().preserveUnmanagedRuleContent
|
|
4237
|
+
}),
|
|
4238
|
+
preserveUnownedSkills: pick({
|
|
4239
|
+
cli: void 0,
|
|
4240
|
+
file: configByFile.preserveUnownedSkills,
|
|
4241
|
+
fallback: getDefaults().preserveUnownedSkills
|
|
4242
|
+
}),
|
|
4243
|
+
preserveUnownedMcpServers: pick({
|
|
4244
|
+
cli: void 0,
|
|
4245
|
+
file: configByFile.preserveUnownedMcpServers,
|
|
4246
|
+
fallback: getDefaults().preserveUnownedMcpServers
|
|
4247
|
+
}),
|
|
4194
4248
|
deriveSubprojectPathFromGlobs: pick({
|
|
4195
4249
|
cli: deriveSubprojectPathFromGlobs,
|
|
4196
4250
|
file: configByFile.deriveSubprojectPathFromGlobs,
|
|
@@ -4432,6 +4486,33 @@ var AiFile = class {
|
|
|
4432
4486
|
return false;
|
|
4433
4487
|
}
|
|
4434
4488
|
/**
|
|
4489
|
+
* The content the write phase puts on disk, given what the file holds now
|
|
4490
|
+
* (`null` when it does not exist) and the generated content (already ending
|
|
4491
|
+
* in a newline). Defaults to the generated content; override for a file
|
|
4492
|
+
* that keeps part of the existing content, such as a root rule file under
|
|
4493
|
+
* `preserveUnmanagedRuleContent`. `generate --check` compares the same
|
|
4494
|
+
* composed content, so content kept this way is never reported as drift.
|
|
4495
|
+
*/
|
|
4496
|
+
composeWrittenContent({ generatedContent }) {
|
|
4497
|
+
return generatedContent;
|
|
4498
|
+
}
|
|
4499
|
+
/**
|
|
4500
|
+
* Whether removing this file (the `--delete` sweep, `retireTargets`) has to
|
|
4501
|
+
* look at what it holds first, through {@link composeContentAfterRemoval}.
|
|
4502
|
+
*/
|
|
4503
|
+
keepsContentOnRemoval() {
|
|
4504
|
+
return false;
|
|
4505
|
+
}
|
|
4506
|
+
/**
|
|
4507
|
+
* How removing this file treats what it holds: `delete` it as a whole (the
|
|
4508
|
+
* default), `rewrite` it with rulesync's own content taken out, or `keep` it
|
|
4509
|
+
* untouched because none of it is rulesync's any more. Only consulted when
|
|
4510
|
+
* {@link keepsContentOnRemoval} is true.
|
|
4511
|
+
*/
|
|
4512
|
+
composeContentAfterRemoval(_params) {
|
|
4513
|
+
return { action: "delete" };
|
|
4514
|
+
}
|
|
4515
|
+
/**
|
|
4435
4516
|
* POSIX mode to apply after writing, or `undefined` to leave the default
|
|
4436
4517
|
* alone. Override in subclasses whose output the tool executes directly
|
|
4437
4518
|
* (e.g. Cline's hook scripts, which are spawned by path and therefore need
|
|
@@ -12340,6 +12421,1125 @@ function classifyRemoteName(name) {
|
|
|
12340
12421
|
};
|
|
12341
12422
|
return { kind: "safe" };
|
|
12342
12423
|
}
|
|
12424
|
+
// src/types/git-provider.ts
|
|
12425
|
+
/**
|
|
12426
|
+
* Supported Git providers for fetch command
|
|
12427
|
+
*/
|
|
12428
|
+
const ALL_GIT_PROVIDERS = ["github", "gitlab"];
|
|
12429
|
+
z.enum(ALL_GIT_PROVIDERS);
|
|
12430
|
+
// src/lib/source-parser.ts
|
|
12431
|
+
const GITHUB_HOSTS = /* @__PURE__ */ new Set(["github.com", "www.github.com"]);
|
|
12432
|
+
const GITLAB_HOSTS = /* @__PURE__ */ new Set(["gitlab.com", "www.gitlab.com"]);
|
|
12433
|
+
/**
|
|
12434
|
+
* Parse source specification into components
|
|
12435
|
+
* Supports:
|
|
12436
|
+
* - URL format: https://github.com/owner/repo, https://gitlab.com/owner/repo
|
|
12437
|
+
* - Prefix format: github:owner/repo, gitlab:owner/repo
|
|
12438
|
+
* - Shorthand format: owner/repo (defaults to GitHub)
|
|
12439
|
+
* - With ref: owner/repo@ref
|
|
12440
|
+
* - With path: owner/repo:path
|
|
12441
|
+
* - Combined: owner/repo@ref:path
|
|
12442
|
+
*/
|
|
12443
|
+
function parseSource(source) {
|
|
12444
|
+
if (source.startsWith("http://") || source.startsWith("https://")) return parseUrl(source);
|
|
12445
|
+
if (source.includes(":") && !source.includes("://")) {
|
|
12446
|
+
const colonIndex = source.indexOf(":");
|
|
12447
|
+
const prefix = source.substring(0, colonIndex);
|
|
12448
|
+
const rest = source.substring(colonIndex + 1);
|
|
12449
|
+
const provider = ALL_GIT_PROVIDERS.find((p) => p === prefix);
|
|
12450
|
+
if (provider) return {
|
|
12451
|
+
provider,
|
|
12452
|
+
...parseShorthand(rest)
|
|
12453
|
+
};
|
|
12454
|
+
return {
|
|
12455
|
+
provider: "github",
|
|
12456
|
+
...parseShorthand(source)
|
|
12457
|
+
};
|
|
12458
|
+
}
|
|
12459
|
+
return {
|
|
12460
|
+
provider: "github",
|
|
12461
|
+
...parseShorthand(source)
|
|
12462
|
+
};
|
|
12463
|
+
}
|
|
12464
|
+
/**
|
|
12465
|
+
* Parse URL format into components
|
|
12466
|
+
*/
|
|
12467
|
+
function parseUrl(url) {
|
|
12468
|
+
const urlObj = new URL(url);
|
|
12469
|
+
const host = urlObj.hostname.toLowerCase();
|
|
12470
|
+
let provider;
|
|
12471
|
+
if (GITHUB_HOSTS.has(host)) provider = "github";
|
|
12472
|
+
else if (GITLAB_HOSTS.has(host)) provider = "gitlab";
|
|
12473
|
+
else throw new Error(`Unknown Git provider for host: ${host}. Supported providers: ${ALL_GIT_PROVIDERS.join(", ")}`);
|
|
12474
|
+
const segments = urlObj.pathname.split("/").filter(Boolean);
|
|
12475
|
+
if (segments.length < 2) throw new Error(`Invalid ${provider} URL: ${url}. Expected format: https://${host}/owner/repo`);
|
|
12476
|
+
const owner = segments[0];
|
|
12477
|
+
const repo = segments[1]?.replace(/\.git$/, "");
|
|
12478
|
+
if (segments.length > 2 && (segments[2] === "tree" || segments[2] === "blob")) {
|
|
12479
|
+
const decode = (segment) => decodeUrlSegment({
|
|
12480
|
+
segment,
|
|
12481
|
+
provider,
|
|
12482
|
+
url
|
|
12483
|
+
});
|
|
12484
|
+
const ref = segments[3] === void 0 ? void 0 : decode(segments[3]);
|
|
12485
|
+
const path = segments.length > 4 ? decode(segments.slice(4).join("/")) : void 0;
|
|
12486
|
+
if (path !== void 0 && path.split(/[\\/]/).includes("..")) throw new Error(`Invalid ${provider} URL: ${url}. Path must not contain ".." segments.`);
|
|
12487
|
+
return {
|
|
12488
|
+
provider,
|
|
12489
|
+
owner: owner ?? "",
|
|
12490
|
+
repo: repo ?? "",
|
|
12491
|
+
ref,
|
|
12492
|
+
path
|
|
12493
|
+
};
|
|
12494
|
+
}
|
|
12495
|
+
return {
|
|
12496
|
+
provider,
|
|
12497
|
+
owner: owner ?? "",
|
|
12498
|
+
repo: repo ?? ""
|
|
12499
|
+
};
|
|
12500
|
+
}
|
|
12501
|
+
/**
|
|
12502
|
+
* Percent-decode a URL path segment, turning a malformed escape (e.g. a lone
|
|
12503
|
+
* `%`) into an error that names the offending source.
|
|
12504
|
+
*/
|
|
12505
|
+
function decodeUrlSegment({ segment, provider, url }) {
|
|
12506
|
+
try {
|
|
12507
|
+
return decodeURIComponent(segment);
|
|
12508
|
+
} catch (error) {
|
|
12509
|
+
if (error instanceof URIError) throw new Error(`Invalid ${provider} URL: ${url}. Malformed percent-encoding in ref or path.`, { cause: error });
|
|
12510
|
+
throw error;
|
|
12511
|
+
}
|
|
12512
|
+
}
|
|
12513
|
+
/**
|
|
12514
|
+
* Parse shorthand format (without provider prefix)
|
|
12515
|
+
*/
|
|
12516
|
+
function parseShorthand(source) {
|
|
12517
|
+
let remaining = source;
|
|
12518
|
+
let path;
|
|
12519
|
+
let ref;
|
|
12520
|
+
const colonIndex = remaining.indexOf(":");
|
|
12521
|
+
if (colonIndex !== -1) {
|
|
12522
|
+
path = remaining.substring(colonIndex + 1);
|
|
12523
|
+
if (!path) throw new Error(`Invalid source: ${source}. Path cannot be empty after ":".`);
|
|
12524
|
+
remaining = remaining.substring(0, colonIndex);
|
|
12525
|
+
}
|
|
12526
|
+
const atIndex = remaining.indexOf("@");
|
|
12527
|
+
if (atIndex !== -1) {
|
|
12528
|
+
ref = remaining.substring(atIndex + 1);
|
|
12529
|
+
if (!ref) throw new Error(`Invalid source: ${source}. Ref cannot be empty after "@".`);
|
|
12530
|
+
remaining = remaining.substring(0, atIndex);
|
|
12531
|
+
}
|
|
12532
|
+
const slashIndex = remaining.indexOf("/");
|
|
12533
|
+
if (slashIndex === -1) throw new Error(`Invalid source: ${source}. Expected format: owner/repo, owner/repo@ref, or owner/repo:path`);
|
|
12534
|
+
const owner = remaining.substring(0, slashIndex);
|
|
12535
|
+
const repo = remaining.substring(slashIndex + 1);
|
|
12536
|
+
if (!owner || !repo) throw new Error(`Invalid source: ${source}. Both owner and repo are required.`);
|
|
12537
|
+
return {
|
|
12538
|
+
owner,
|
|
12539
|
+
repo,
|
|
12540
|
+
ref,
|
|
12541
|
+
path
|
|
12542
|
+
};
|
|
12543
|
+
}
|
|
12544
|
+
/**
|
|
12545
|
+
* Schema for a single locked skill entry with content integrity.
|
|
12546
|
+
*/
|
|
12547
|
+
const LockedSkillSchema = z.object({ integrity: z.string() });
|
|
12548
|
+
/** Schema for a single locked rule entry with content integrity. */
|
|
12549
|
+
const LockedRuleSchema = z.object({ integrity: z.string() });
|
|
12550
|
+
/**
|
|
12551
|
+
* Schema for a single locked source entry.
|
|
12552
|
+
*/
|
|
12553
|
+
const LockedSourceSchema = z.object({
|
|
12554
|
+
requestedRef: optional(z.string()),
|
|
12555
|
+
resolvedRef: z.string().check(refine((v) => /^[0-9a-f]{40}$/.test(v), "resolvedRef must be a 40-character hex SHA")),
|
|
12556
|
+
resolvedAt: optional(z.string()),
|
|
12557
|
+
skills: z.record(z.string(), LockedSkillSchema),
|
|
12558
|
+
/**
|
|
12559
|
+
* The normalized `skills` selection the entry was written for. Absent from
|
|
12560
|
+
* lockfiles written before the selection was recorded.
|
|
12561
|
+
*/
|
|
12562
|
+
skillSelection: optional(z.array(z.string())),
|
|
12563
|
+
/**
|
|
12564
|
+
* The normalized path the skills were read from in the source. Absent from
|
|
12565
|
+
* lockfiles written before the path was recorded.
|
|
12566
|
+
*/
|
|
12567
|
+
skillsPath: optional(z.string()),
|
|
12568
|
+
rules: optional(z.record(z.string(), LockedRuleSchema)),
|
|
12569
|
+
ruleSelection: optional(z.array(z.string())),
|
|
12570
|
+
rulesPath: optional(z.string()),
|
|
12571
|
+
resolvedRuleNames: optional(z.array(z.string())),
|
|
12572
|
+
commands: optional(z.record(z.string(), LockedRuleSchema)),
|
|
12573
|
+
commandSelection: optional(z.array(z.string())),
|
|
12574
|
+
commandsPath: optional(z.string()),
|
|
12575
|
+
resolvedCommandNames: optional(z.array(z.string())),
|
|
12576
|
+
subagents: optional(z.record(z.string(), LockedRuleSchema)),
|
|
12577
|
+
subagentSelection: optional(z.array(z.string())),
|
|
12578
|
+
subagentsPath: optional(z.string()),
|
|
12579
|
+
resolvedSubagentNames: optional(z.array(z.string()))
|
|
12580
|
+
});
|
|
12581
|
+
/**
|
|
12582
|
+
* Schema for the full lockfile (current version).
|
|
12583
|
+
*/
|
|
12584
|
+
const SourcesLockSchema = z.object({
|
|
12585
|
+
lockfileVersion: z.number(),
|
|
12586
|
+
sources: z.record(z.string(), LockedSourceSchema)
|
|
12587
|
+
});
|
|
12588
|
+
/**
|
|
12589
|
+
* Schema for the legacy v0 lockfile format (skills as string array, no version field).
|
|
12590
|
+
*/
|
|
12591
|
+
const LegacyLockedSourceSchema = z.object({
|
|
12592
|
+
resolvedRef: z.string(),
|
|
12593
|
+
skills: z.array(z.string())
|
|
12594
|
+
});
|
|
12595
|
+
const LegacySourcesLockSchema = z.object({ sources: z.record(z.string(), LegacyLockedSourceSchema) });
|
|
12596
|
+
/**
|
|
12597
|
+
* Migrate a legacy lockfile (string[] skills, no version) to the current format.
|
|
12598
|
+
* Skills get empty integrity since we can't compute it retroactively.
|
|
12599
|
+
*/
|
|
12600
|
+
function migrateLegacyLock(params) {
|
|
12601
|
+
const { legacy, logger } = params;
|
|
12602
|
+
const sources = {};
|
|
12603
|
+
for (const [key, entry] of Object.entries(legacy.sources)) {
|
|
12604
|
+
const skills = {};
|
|
12605
|
+
for (const name of entry.skills) skills[name] = { integrity: "" };
|
|
12606
|
+
sources[key] = {
|
|
12607
|
+
resolvedRef: entry.resolvedRef,
|
|
12608
|
+
skills
|
|
12609
|
+
};
|
|
12610
|
+
}
|
|
12611
|
+
logger.info("Migrated legacy sources lockfile to version 1. Run 'rulesync install --update' to populate integrity hashes.");
|
|
12612
|
+
return {
|
|
12613
|
+
lockfileVersion: 1,
|
|
12614
|
+
sources
|
|
12615
|
+
};
|
|
12616
|
+
}
|
|
12617
|
+
/**
|
|
12618
|
+
* Create an empty lockfile structure.
|
|
12619
|
+
*/
|
|
12620
|
+
function createEmptyLock() {
|
|
12621
|
+
return {
|
|
12622
|
+
lockfileVersion: 1,
|
|
12623
|
+
sources: {}
|
|
12624
|
+
};
|
|
12625
|
+
}
|
|
12626
|
+
/**
|
|
12627
|
+
* Read the lockfile from disk.
|
|
12628
|
+
* @returns The parsed lockfile, or an empty lockfile if it doesn't exist or is invalid.
|
|
12629
|
+
*/
|
|
12630
|
+
async function readLockFile(params) {
|
|
12631
|
+
const { logger } = params;
|
|
12632
|
+
const lockPath = join(params.projectRoot, RULESYNC_SOURCES_LOCK_RELATIVE_FILE_PATH);
|
|
12633
|
+
if (!await fileExists(lockPath)) {
|
|
12634
|
+
logger.debug("No sources lockfile found, starting fresh.");
|
|
12635
|
+
return createEmptyLock();
|
|
12636
|
+
}
|
|
12637
|
+
try {
|
|
12638
|
+
const content = await readFileContent(lockPath);
|
|
12639
|
+
const data = JSON.parse(content);
|
|
12640
|
+
const result = SourcesLockSchema.safeParse(data);
|
|
12641
|
+
if (result.success) return result.data;
|
|
12642
|
+
const legacyResult = LegacySourcesLockSchema.safeParse(data);
|
|
12643
|
+
if (legacyResult.success) return migrateLegacyLock({
|
|
12644
|
+
legacy: legacyResult.data,
|
|
12645
|
+
logger
|
|
12646
|
+
});
|
|
12647
|
+
logger.warn(`Invalid sources lockfile format (${RULESYNC_SOURCES_LOCK_RELATIVE_FILE_PATH}). Starting fresh.`);
|
|
12648
|
+
return createEmptyLock();
|
|
12649
|
+
} catch {
|
|
12650
|
+
logger.warn(`Failed to read sources lockfile (${RULESYNC_SOURCES_LOCK_RELATIVE_FILE_PATH}). Starting fresh.`);
|
|
12651
|
+
return createEmptyLock();
|
|
12652
|
+
}
|
|
12653
|
+
}
|
|
12654
|
+
/**
|
|
12655
|
+
* Write the lockfile to disk.
|
|
12656
|
+
*/
|
|
12657
|
+
async function writeLockFile(params) {
|
|
12658
|
+
const { logger } = params;
|
|
12659
|
+
const lockPath = join(params.projectRoot, RULESYNC_SOURCES_LOCK_RELATIVE_FILE_PATH);
|
|
12660
|
+
await writeFileContent(lockPath, JSON.stringify(params.lock, null, 2) + "\n");
|
|
12661
|
+
logger.debug(`Wrote sources lockfile to ${lockPath}`);
|
|
12662
|
+
}
|
|
12663
|
+
/**
|
|
12664
|
+
* Compute a SHA-256 integrity hash for a skill's contents.
|
|
12665
|
+
* Takes a sorted list of [relativePath, content] pairs to produce a deterministic hash.
|
|
12666
|
+
*/
|
|
12667
|
+
function computeSkillIntegrity(files) {
|
|
12668
|
+
const hash = createHash("sha256");
|
|
12669
|
+
const sorted = files.toSorted((a, b) => a.path.localeCompare(b.path));
|
|
12670
|
+
for (const file of sorted) {
|
|
12671
|
+
hash.update(file.path);
|
|
12672
|
+
hash.update("\0");
|
|
12673
|
+
hash.update(file.content);
|
|
12674
|
+
hash.update("\0");
|
|
12675
|
+
}
|
|
12676
|
+
return `sha256-${hash.digest("hex")}`;
|
|
12677
|
+
}
|
|
12678
|
+
/** Compute a SHA-256 integrity hash for one rule file. */
|
|
12679
|
+
function computeRuleIntegrity(content) {
|
|
12680
|
+
const hash = createHash("sha256");
|
|
12681
|
+
hash.update(content);
|
|
12682
|
+
return `sha256-${hash.digest("hex")}`;
|
|
12683
|
+
}
|
|
12684
|
+
/**
|
|
12685
|
+
* Normalize a source key for consistent lockfile lookups.
|
|
12686
|
+
* Strips URL prefixes, provider prefixes, trailing slashes, .git suffix, and lowercases.
|
|
12687
|
+
*/
|
|
12688
|
+
function normalizeSourceKey(source) {
|
|
12689
|
+
let key = source;
|
|
12690
|
+
for (const prefix of [
|
|
12691
|
+
"https://www.github.com/",
|
|
12692
|
+
"https://github.com/",
|
|
12693
|
+
"http://www.github.com/",
|
|
12694
|
+
"http://github.com/",
|
|
12695
|
+
"https://www.gitlab.com/",
|
|
12696
|
+
"https://gitlab.com/",
|
|
12697
|
+
"http://www.gitlab.com/",
|
|
12698
|
+
"http://gitlab.com/"
|
|
12699
|
+
]) if (key.toLowerCase().startsWith(prefix)) {
|
|
12700
|
+
key = key.substring(prefix.length);
|
|
12701
|
+
break;
|
|
12702
|
+
}
|
|
12703
|
+
for (const provider of ["github:", "gitlab:"]) if (key.startsWith(provider)) {
|
|
12704
|
+
key = key.substring(provider.length);
|
|
12705
|
+
break;
|
|
12706
|
+
}
|
|
12707
|
+
key = key.replace(/\/+$/, "");
|
|
12708
|
+
key = key.replace(/\.git$/, "");
|
|
12709
|
+
key = key.toLowerCase();
|
|
12710
|
+
return key;
|
|
12711
|
+
}
|
|
12712
|
+
/**
|
|
12713
|
+
* Separates the repository part of a lock key from the qualifier that tells
|
|
12714
|
+
* apart several declared entries of the same repository.
|
|
12715
|
+
*/
|
|
12716
|
+
const LOCK_KEY_QUALIFIER_SEPARATOR = "#";
|
|
12717
|
+
/**
|
|
12718
|
+
* Normalize a lock key for comparison. The repository part is normalized with
|
|
12719
|
+
* {@link normalizeSourceKey}; a qualifier (see {@link resolveSourceLockKeys})
|
|
12720
|
+
* is kept verbatim, since paths and refs are case-sensitive. A key without a
|
|
12721
|
+
* qualifier normalizes exactly as before qualifiers existed.
|
|
12722
|
+
*/
|
|
12723
|
+
function normalizeLockKey(key) {
|
|
12724
|
+
const separatorIndex = key.indexOf(LOCK_KEY_QUALIFIER_SEPARATOR);
|
|
12725
|
+
if (separatorIndex === -1) return normalizeSourceKey(key);
|
|
12726
|
+
return normalizeSourceKey(key.slice(0, separatorIndex)) + key.slice(separatorIndex);
|
|
12727
|
+
}
|
|
12728
|
+
/** The normalized repository part of a lock key, without its qualifier. */
|
|
12729
|
+
function getLockKeyRepository(key) {
|
|
12730
|
+
const separatorIndex = key.indexOf(LOCK_KEY_QUALIFIER_SEPARATOR);
|
|
12731
|
+
return normalizeSourceKey(separatorIndex === -1 ? key : key.slice(0, separatorIndex));
|
|
12732
|
+
}
|
|
12733
|
+
function encodeLockKeyQualifierValue(value) {
|
|
12734
|
+
return encodeURIComponent(value).replace(/%2F/gi, "/");
|
|
12735
|
+
}
|
|
12736
|
+
function normalizeLockKeyDirPath(dirPath) {
|
|
12737
|
+
return normalizePosixDirPath(dirPath);
|
|
12738
|
+
}
|
|
12739
|
+
/**
|
|
12740
|
+
* The location fields of a declared entry that tell it apart from other
|
|
12741
|
+
* entries of the same repository, as a lock key qualifier (empty when the
|
|
12742
|
+
* entry declares none of them).
|
|
12743
|
+
*/
|
|
12744
|
+
function buildLockKeyQualifier(sourceEntry) {
|
|
12745
|
+
const parts = [];
|
|
12746
|
+
if (sourceEntry.path !== void 0) parts.push(`path=${encodeLockKeyQualifierValue(normalizeLockKeyDirPath(sourceEntry.path))}`);
|
|
12747
|
+
for (const field of [
|
|
12748
|
+
"rulesPath",
|
|
12749
|
+
"commandsPath",
|
|
12750
|
+
"subagentsPath"
|
|
12751
|
+
]) {
|
|
12752
|
+
const dirPath = sourceEntry[field];
|
|
12753
|
+
if (dirPath !== void 0) parts.push(`${field}=${encodeLockKeyQualifierValue(normalizeLockKeyDirPath(dirPath))}`);
|
|
12754
|
+
}
|
|
12755
|
+
if (sourceEntry.ref !== void 0) parts.push(`ref=${encodeLockKeyQualifierValue(sourceEntry.ref)}`);
|
|
12756
|
+
return parts.join("&");
|
|
12757
|
+
}
|
|
12758
|
+
/**
|
|
12759
|
+
* The key each declared source's lock entry is stored under, index-aligned
|
|
12760
|
+
* with `sources`.
|
|
12761
|
+
*
|
|
12762
|
+
* A repository declared once keeps the bare {@link normalizeSourceKey} key,
|
|
12763
|
+
* so lockfiles written before multiple entries per repository were supported
|
|
12764
|
+
* stay valid unchanged. Only when several git/GitHub entries normalize to the
|
|
12765
|
+
* same repository does each of them get a qualified key
|
|
12766
|
+
* (`owner/repo#path=plugins/team-a/skills&ref=main`) built from its `path`,
|
|
12767
|
+
* `rulesPath`, `commandsPath`, `subagentsPath` and `ref`, so each entry keeps its own lock entry, its own
|
|
12768
|
+
* curated-artifact cleanup and its own `--frozen` check. An entry declaring
|
|
12769
|
+
* none of those fields keeps the bare key, and entries declaring the same
|
|
12770
|
+
* location are told apart by their order (`entry=2`, `entry=3`, ...).
|
|
12771
|
+
*
|
|
12772
|
+
* npm-transport sources are locked in a separate lockfile by package name;
|
|
12773
|
+
* their key here is unused and left bare.
|
|
12774
|
+
*/
|
|
12775
|
+
function resolveSourceLockKeys(sources) {
|
|
12776
|
+
const bareKeys = sources.map((sourceEntry) => normalizeSourceKey(sourceEntry.source));
|
|
12777
|
+
const repositoryCounts = /* @__PURE__ */ new Map();
|
|
12778
|
+
sources.forEach((sourceEntry, index) => {
|
|
12779
|
+
if (getSourceTransport(sourceEntry) === "npm") return;
|
|
12780
|
+
const bareKey = bareKeys[index] ?? "";
|
|
12781
|
+
repositoryCounts.set(bareKey, (repositoryCounts.get(bareKey) ?? 0) + 1);
|
|
12782
|
+
});
|
|
12783
|
+
const qualifierCounts = /* @__PURE__ */ new Map();
|
|
12784
|
+
return sources.map((sourceEntry, index) => {
|
|
12785
|
+
const bareKey = bareKeys[index] ?? "";
|
|
12786
|
+
if (getSourceTransport(sourceEntry) === "npm" || (repositoryCounts.get(bareKey) ?? 0) < 2) return bareKey;
|
|
12787
|
+
const qualifier = buildLockKeyQualifier(sourceEntry);
|
|
12788
|
+
const base = qualifier === "" ? bareKey : `${bareKey}${LOCK_KEY_QUALIFIER_SEPARATOR}${qualifier}`;
|
|
12789
|
+
const occurrence = (qualifierCounts.get(base) ?? 0) + 1;
|
|
12790
|
+
qualifierCounts.set(base, occurrence);
|
|
12791
|
+
if (occurrence === 1) return base;
|
|
12792
|
+
return `${base}${qualifier === "" ? LOCK_KEY_QUALIFIER_SEPARATOR : "&"}entry=${occurrence}`;
|
|
12793
|
+
});
|
|
12794
|
+
}
|
|
12795
|
+
/**
|
|
12796
|
+
* Move a lock entry to another key, keeping its position-independent content
|
|
12797
|
+
* unchanged (immutable — returns a fresh lock object).
|
|
12798
|
+
*/
|
|
12799
|
+
function renameLockedSource(params) {
|
|
12800
|
+
const { lock, fromKey, toKey } = params;
|
|
12801
|
+
const entry = getLockedSource(lock, fromKey);
|
|
12802
|
+
if (entry === void 0) return lock;
|
|
12803
|
+
const normalizedFrom = normalizeLockKey(fromKey);
|
|
12804
|
+
const remaining = {};
|
|
12805
|
+
for (const [key, value] of Object.entries(lock.sources)) if (normalizeLockKey(key) !== normalizedFrom) remaining[key] = value;
|
|
12806
|
+
return setLockedSource({
|
|
12807
|
+
lockfileVersion: lock.lockfileVersion,
|
|
12808
|
+
sources: remaining
|
|
12809
|
+
}, toKey, entry);
|
|
12810
|
+
}
|
|
12811
|
+
/**
|
|
12812
|
+
* Get the locked entry for a lock key (see {@link resolveSourceLockKeys}),
|
|
12813
|
+
* if it exists.
|
|
12814
|
+
*/
|
|
12815
|
+
function getLockedSource(lock, lockKey) {
|
|
12816
|
+
const normalized = normalizeLockKey(lockKey);
|
|
12817
|
+
for (const [key, value] of Object.entries(lock.sources)) if (normalizeLockKey(key) === normalized) return value;
|
|
12818
|
+
}
|
|
12819
|
+
/**
|
|
12820
|
+
* Set (or update) a locked entry for a lock key.
|
|
12821
|
+
*/
|
|
12822
|
+
function setLockedSource(lock, lockKey, entry) {
|
|
12823
|
+
const normalized = normalizeLockKey(lockKey);
|
|
12824
|
+
const filteredSources = {};
|
|
12825
|
+
for (const [key, value] of Object.entries(lock.sources)) if (normalizeLockKey(key) !== normalized) filteredSources[key] = value;
|
|
12826
|
+
return {
|
|
12827
|
+
lockfileVersion: lock.lockfileVersion,
|
|
12828
|
+
sources: {
|
|
12829
|
+
...filteredSources,
|
|
12830
|
+
[normalized]: entry
|
|
12831
|
+
}
|
|
12832
|
+
};
|
|
12833
|
+
}
|
|
12834
|
+
/**
|
|
12835
|
+
* Get the skill names from a locked source entry.
|
|
12836
|
+
*/
|
|
12837
|
+
function getLockedSkillNames(entry) {
|
|
12838
|
+
return Object.keys(entry.skills);
|
|
12839
|
+
}
|
|
12840
|
+
/**
|
|
12841
|
+
* The features a source installs as one Markdown file per item, each locked
|
|
12842
|
+
* with the same four fields (`rules` / `ruleSelection` / `rulesPath` /
|
|
12843
|
+
* `resolvedRuleNames`, and the command and subagent counterparts).
|
|
12844
|
+
*/
|
|
12845
|
+
const SOURCE_FILE_FEATURES = [
|
|
12846
|
+
"rules",
|
|
12847
|
+
"commands",
|
|
12848
|
+
"subagents"
|
|
12849
|
+
];
|
|
12850
|
+
/** Build a value for each per-file feature. */
|
|
12851
|
+
function mapFileFeatures(map) {
|
|
12852
|
+
return {
|
|
12853
|
+
rules: map("rules"),
|
|
12854
|
+
commands: map("commands"),
|
|
12855
|
+
subagents: map("subagents")
|
|
12856
|
+
};
|
|
12857
|
+
}
|
|
12858
|
+
/** Read one per-file feature's lock fields from a lock entry. */
|
|
12859
|
+
function getLockedFileFeatureState(entry, feature) {
|
|
12860
|
+
switch (feature) {
|
|
12861
|
+
case "rules": return {
|
|
12862
|
+
items: entry.rules,
|
|
12863
|
+
selection: entry.ruleSelection,
|
|
12864
|
+
path: entry.rulesPath,
|
|
12865
|
+
resolvedNames: entry.resolvedRuleNames
|
|
12866
|
+
};
|
|
12867
|
+
case "commands": return {
|
|
12868
|
+
items: entry.commands,
|
|
12869
|
+
selection: entry.commandSelection,
|
|
12870
|
+
path: entry.commandsPath,
|
|
12871
|
+
resolvedNames: entry.resolvedCommandNames
|
|
12872
|
+
};
|
|
12873
|
+
case "subagents": return {
|
|
12874
|
+
items: entry.subagents,
|
|
12875
|
+
selection: entry.subagentSelection,
|
|
12876
|
+
path: entry.subagentsPath,
|
|
12877
|
+
resolvedNames: entry.resolvedSubagentNames
|
|
12878
|
+
};
|
|
12879
|
+
}
|
|
12880
|
+
}
|
|
12881
|
+
/** The lock fields that record one per-file feature's state. */
|
|
12882
|
+
function toFileFeatureLockFields(feature, state) {
|
|
12883
|
+
switch (feature) {
|
|
12884
|
+
case "rules": return {
|
|
12885
|
+
rules: state.items,
|
|
12886
|
+
ruleSelection: state.selection,
|
|
12887
|
+
rulesPath: state.path,
|
|
12888
|
+
resolvedRuleNames: state.resolvedNames
|
|
12889
|
+
};
|
|
12890
|
+
case "commands": return {
|
|
12891
|
+
commands: state.items,
|
|
12892
|
+
commandSelection: state.selection,
|
|
12893
|
+
commandsPath: state.path,
|
|
12894
|
+
resolvedCommandNames: state.resolvedNames
|
|
12895
|
+
};
|
|
12896
|
+
case "subagents": return {
|
|
12897
|
+
subagents: state.items,
|
|
12898
|
+
subagentSelection: state.selection,
|
|
12899
|
+
subagentsPath: state.path,
|
|
12900
|
+
resolvedSubagentNames: state.resolvedNames
|
|
12901
|
+
};
|
|
12902
|
+
}
|
|
12903
|
+
}
|
|
12904
|
+
/** The item names one per-file feature of a lock entry locks. */
|
|
12905
|
+
function getLockedFileNames(entry, feature) {
|
|
12906
|
+
return Object.keys(getLockedFileFeatureState(entry, feature).items ?? {});
|
|
12907
|
+
}
|
|
12908
|
+
// src/lib/sources-artifacts.ts
|
|
12909
|
+
const FILE_FEATURE_SPECS = {
|
|
12910
|
+
rules: {
|
|
12911
|
+
noun: "rule",
|
|
12912
|
+
pathField: "rulesPath",
|
|
12913
|
+
defaultPath: "rules",
|
|
12914
|
+
curatedRelativeDirPath: RULESYNC_CURATED_RULES_RELATIVE_DIR_PATH
|
|
12915
|
+
},
|
|
12916
|
+
commands: {
|
|
12917
|
+
noun: "command",
|
|
12918
|
+
pathField: "commandsPath",
|
|
12919
|
+
defaultPath: "commands",
|
|
12920
|
+
curatedRelativeDirPath: RULESYNC_CURATED_COMMANDS_RELATIVE_DIR_PATH
|
|
12921
|
+
},
|
|
12922
|
+
subagents: {
|
|
12923
|
+
noun: "subagent",
|
|
12924
|
+
pathField: "subagentsPath",
|
|
12925
|
+
defaultPath: "subagents",
|
|
12926
|
+
curatedRelativeDirPath: RULESYNC_CURATED_SUBAGENTS_RELATIVE_DIR_PATH
|
|
12927
|
+
}
|
|
12928
|
+
};
|
|
12929
|
+
/** The singular noun of a per-file feature, for messages (`rule`, `command`, `subagent`). */
|
|
12930
|
+
function getFileFeatureNoun(feature) {
|
|
12931
|
+
return FILE_FEATURE_SPECS[feature].noun;
|
|
12932
|
+
}
|
|
12933
|
+
/** Where a per-file feature's fetched copies live, relative to the project root. */
|
|
12934
|
+
function getCuratedFileFeatureRelativeDirPath(feature) {
|
|
12935
|
+
return FILE_FEATURE_SPECS[feature].curatedRelativeDirPath;
|
|
12936
|
+
}
|
|
12937
|
+
/** Every selection field a source entry may declare. */
|
|
12938
|
+
const SOURCE_SELECTION_FIELDS = ["skills", ...SOURCE_FILE_FEATURES];
|
|
12939
|
+
function getSourceFilters(sourceEntry) {
|
|
12940
|
+
const hasExplicitFeature = SOURCE_SELECTION_FIELDS.some((field) => sourceEntry[field] !== void 0);
|
|
12941
|
+
return {
|
|
12942
|
+
skills: sourceEntry.skills ?? (hasExplicitFeature ? void 0 : ["*"]),
|
|
12943
|
+
rules: sourceEntry.rules,
|
|
12944
|
+
commands: sourceEntry.commands,
|
|
12945
|
+
subagents: sourceEntry.subagents
|
|
12946
|
+
};
|
|
12947
|
+
}
|
|
12948
|
+
/** The selection fields a source entry declares as an empty list. */
|
|
12949
|
+
function getEmptySelectionFields(sourceEntry) {
|
|
12950
|
+
return SOURCE_SELECTION_FIELDS.filter((field) => sourceEntry[field]?.length === 0);
|
|
12951
|
+
}
|
|
12952
|
+
function hasEmptySelection(sourceEntry) {
|
|
12953
|
+
return getEmptySelectionFields(sourceEntry).length > 0;
|
|
12954
|
+
}
|
|
12955
|
+
/**
|
|
12956
|
+
* Whether a lock entry was written for the ref the manifest declares now. A
|
|
12957
|
+
* declared ref that differs from the locked `requestedRef` is resolved afresh
|
|
12958
|
+
* (and fails `--frozen`), so editing the ref in the manifest cannot keep
|
|
12959
|
+
* installing the commit resolved for the old one.
|
|
12960
|
+
*
|
|
12961
|
+
* An entry that records no `requestedRef` (a migrated legacy lock, or a
|
|
12962
|
+
* hand-written one) still matches: it says nothing that contradicts the
|
|
12963
|
+
* declared ref, and refusing it would gain nothing, since whoever can edit the
|
|
12964
|
+
* lock can also write any `requestedRef`. The declared ref is recorded on it
|
|
12965
|
+
* the next time the entry is written.
|
|
12966
|
+
*
|
|
12967
|
+
* A source that declares no ref also matches: its locked `requestedRef` is the
|
|
12968
|
+
* default branch it resolved to, which cannot be told apart from a ref that
|
|
12969
|
+
* was dropped from the manifest without asking the remote.
|
|
12970
|
+
*/
|
|
12971
|
+
function lockedRefMatchesDeclared(params) {
|
|
12972
|
+
const { locked, declaredRef } = params;
|
|
12973
|
+
return declaredRef === void 0 || locked.requestedRef === void 0 || locked.requestedRef === declaredRef;
|
|
12974
|
+
}
|
|
12975
|
+
/**
|
|
12976
|
+
* Check that every locked skill is on disk in the curated directory with the
|
|
12977
|
+
* content the lockfile records: its files hash to the locked integrity, so a
|
|
12978
|
+
* skill edited, extended or trimmed in place is fetched again, as a rule is.
|
|
12979
|
+
*
|
|
12980
|
+
* The locked hash keys each file by the path the transport reported. The
|
|
12981
|
+
* GitHub API and npm report POSIX paths, while the git transport reports
|
|
12982
|
+
* platform paths, so on Windows both spellings are accepted.
|
|
12983
|
+
*
|
|
12984
|
+
* Only presence is checked for a skill whose content this entry cannot vouch
|
|
12985
|
+
* for: one an earlier source already installed under the same name (the
|
|
12986
|
+
* curated directory then holds that source's copy, which wins), and one locked
|
|
12987
|
+
* with an empty integrity by the migration from the legacy lockfile format.
|
|
12988
|
+
*/
|
|
12989
|
+
async function checkLockedSkillsAreValid(params) {
|
|
12990
|
+
const { curatedDir, skills, presenceOnlySkillNames = /* @__PURE__ */ new Set() } = params;
|
|
12991
|
+
for (const [name, entry] of Object.entries(skills)) {
|
|
12992
|
+
const skillDir = join(curatedDir, name);
|
|
12993
|
+
if (!await directoryExists(skillDir)) return false;
|
|
12994
|
+
if (entry.integrity === "" || presenceOnlySkillNames.has(name)) continue;
|
|
12995
|
+
const files = await Promise.all((await listFilePathsRecursively(skillDir, { includeHidden: true })).map(async (relativePath) => ({
|
|
12996
|
+
relativePath,
|
|
12997
|
+
content: await readFileContent(join(skillDir, relativePath))
|
|
12998
|
+
})));
|
|
12999
|
+
if (!(sep === "/" ? [(relativePath) => relativePath] : [toPosixPath, (relativePath) => relativePath]).some((spell) => computeSkillIntegrity(files.map((file) => ({
|
|
13000
|
+
path: spell(file.relativePath),
|
|
13001
|
+
content: file.content
|
|
13002
|
+
}))) === entry.integrity)) return false;
|
|
13003
|
+
}
|
|
13004
|
+
return true;
|
|
13005
|
+
}
|
|
13006
|
+
/**
|
|
13007
|
+
* Check that every item one per-file feature of a lock entry locks is on disk
|
|
13008
|
+
* in its curated directory with the locked content. A locked name that is not
|
|
13009
|
+
* a valid file name (a hand-edited lockfile) never counts as installed, so it
|
|
13010
|
+
* is fetched again rather than read from outside the curated directory.
|
|
13011
|
+
*/
|
|
13012
|
+
async function checkLockedFilesAreValid(params) {
|
|
13013
|
+
const { items } = getLockedFileFeatureState(params.locked, params.feature);
|
|
13014
|
+
for (const [name, entry] of Object.entries(items ?? {})) {
|
|
13015
|
+
if (!isValidRuleName(name)) return false;
|
|
13016
|
+
const filePath = join(params.curatedDir, `${name}.md`);
|
|
13017
|
+
if (!await fileExists(filePath)) return false;
|
|
13018
|
+
if (computeRuleIntegrity(await readFileContent(filePath)) !== entry.integrity) return false;
|
|
13019
|
+
}
|
|
13020
|
+
return true;
|
|
13021
|
+
}
|
|
13022
|
+
async function canReuseLockedFiles(params) {
|
|
13023
|
+
const { feature, locked, sourceEntry, lockedNames, localNames, alreadyFetchedNames, curatedDir } = params;
|
|
13024
|
+
if (!lockedFileConfigMatches({
|
|
13025
|
+
feature,
|
|
13026
|
+
locked,
|
|
13027
|
+
sourceEntry
|
|
13028
|
+
})) return false;
|
|
13029
|
+
const { resolvedNames } = getLockedFileFeatureState(locked, feature);
|
|
13030
|
+
if (resolvedNames === void 0) return false;
|
|
13031
|
+
const availableNames = /* @__PURE__ */ new Set([
|
|
13032
|
+
...lockedNames,
|
|
13033
|
+
...localNames,
|
|
13034
|
+
...alreadyFetchedNames
|
|
13035
|
+
]);
|
|
13036
|
+
if (resolvedNames.some((name) => !availableNames.has(name))) return false;
|
|
13037
|
+
if (lockedNames.some((name) => localNames.has(name) || alreadyFetchedNames.has(name))) return false;
|
|
13038
|
+
return checkLockedFilesAreValid({
|
|
13039
|
+
feature,
|
|
13040
|
+
curatedDir,
|
|
13041
|
+
locked
|
|
13042
|
+
});
|
|
13043
|
+
}
|
|
13044
|
+
/**
|
|
13045
|
+
* Remove previously curated skill directories for a source before re-fetching.
|
|
13046
|
+
* Validates that each path resolves within the curated directory to prevent traversal.
|
|
13047
|
+
*/
|
|
13048
|
+
async function cleanPreviousCuratedSkills(params) {
|
|
13049
|
+
const { curatedDir, lockedSkillNames, protectedSkillNames = /* @__PURE__ */ new Set(), logger } = params;
|
|
13050
|
+
const resolvedCuratedDir = resolve(curatedDir);
|
|
13051
|
+
for (const prevSkill of lockedSkillNames) {
|
|
13052
|
+
if (protectedSkillNames.has(prevSkill)) continue;
|
|
13053
|
+
const prevDir = join(curatedDir, prevSkill);
|
|
13054
|
+
if (!resolve(prevDir).startsWith(resolvedCuratedDir + sep)) {
|
|
13055
|
+
logger.warn(`Skipping removal of ${quoteForLog(prevSkill)}: resolved path is outside the curated directory.`);
|
|
13056
|
+
continue;
|
|
13057
|
+
}
|
|
13058
|
+
if (await directoryExists(prevDir)) await removeDirectoryStrict(prevDir);
|
|
13059
|
+
}
|
|
13060
|
+
}
|
|
13061
|
+
/**
|
|
13062
|
+
* Whether `<name>.md` resolves to a file directly inside `curatedDir`. Locked
|
|
13063
|
+
* names come from the lockfile, which can be edited by hand, so they are
|
|
13064
|
+
* checked before anything is read, removed or written under them.
|
|
13065
|
+
*/
|
|
13066
|
+
function isCuratedFileInside(params) {
|
|
13067
|
+
const resolvedCuratedDir = resolve(params.curatedDir);
|
|
13068
|
+
return resolve(join(params.curatedDir, `${params.name}.md`)).startsWith(resolvedCuratedDir + sep);
|
|
13069
|
+
}
|
|
13070
|
+
/**
|
|
13071
|
+
* Remove a source's previously curated files (rules, commands or subagents)
|
|
13072
|
+
* before re-fetching. Validates that each path resolves within the curated
|
|
13073
|
+
* directory to prevent traversal.
|
|
13074
|
+
*/
|
|
13075
|
+
async function cleanPreviousCuratedFiles(params) {
|
|
13076
|
+
const { curatedDir, lockedNames, protectedNames, logger } = params;
|
|
13077
|
+
for (const prevName of lockedNames) {
|
|
13078
|
+
if (protectedNames.has(prevName)) continue;
|
|
13079
|
+
if (!isCuratedFileInside({
|
|
13080
|
+
curatedDir,
|
|
13081
|
+
name: prevName
|
|
13082
|
+
})) {
|
|
13083
|
+
logger.warn(`Skipping removal of ${quoteForLog(prevName)}: resolved path is outside the curated directory.`);
|
|
13084
|
+
continue;
|
|
13085
|
+
}
|
|
13086
|
+
const prevFile = join(curatedDir, `${prevName}.md`);
|
|
13087
|
+
if (await fileExists(prevFile)) await removeFileStrict(prevFile);
|
|
13088
|
+
}
|
|
13089
|
+
}
|
|
13090
|
+
async function replaceCuratedFiles(params) {
|
|
13091
|
+
const { feature, files, curatedDir, locked, lockedNames, resolvedRef, sourceKey, localNames, alreadyFetchedNames, compareLockedIntegrity, frozen, logger } = params;
|
|
13092
|
+
const protectedNames = alreadyFetchedNames;
|
|
13093
|
+
const installableFiles = files.filter((file) => !shouldSkipFile({
|
|
13094
|
+
feature,
|
|
13095
|
+
name: file.name,
|
|
13096
|
+
sourceKey,
|
|
13097
|
+
localNames,
|
|
13098
|
+
alreadyFetchedNames,
|
|
13099
|
+
logger
|
|
13100
|
+
}));
|
|
13101
|
+
const previousContents = /* @__PURE__ */ new Map();
|
|
13102
|
+
for (const name of lockedNames) {
|
|
13103
|
+
if (protectedNames.has(name) || !isCuratedFileInside({
|
|
13104
|
+
curatedDir,
|
|
13105
|
+
name
|
|
13106
|
+
})) continue;
|
|
13107
|
+
const path = join(curatedDir, `${name}.md`);
|
|
13108
|
+
if (await fileExists(path)) previousContents.set(name, await readFileContent(path));
|
|
13109
|
+
}
|
|
13110
|
+
try {
|
|
13111
|
+
await cleanPreviousCuratedFiles({
|
|
13112
|
+
curatedDir,
|
|
13113
|
+
lockedNames,
|
|
13114
|
+
protectedNames,
|
|
13115
|
+
logger
|
|
13116
|
+
});
|
|
13117
|
+
const fetchedFiles = {};
|
|
13118
|
+
for (const file of installableFiles) fetchedFiles[file.name] = await writeFeatureFileAndComputeIntegrity({
|
|
13119
|
+
feature,
|
|
13120
|
+
file,
|
|
13121
|
+
curatedDir,
|
|
13122
|
+
locked,
|
|
13123
|
+
resolvedRef,
|
|
13124
|
+
sourceKey,
|
|
13125
|
+
compareLockedIntegrity,
|
|
13126
|
+
frozen,
|
|
13127
|
+
logger
|
|
13128
|
+
});
|
|
13129
|
+
return fetchedFiles;
|
|
13130
|
+
} catch (error) {
|
|
13131
|
+
for (const file of installableFiles) await removeFileStrict(join(curatedDir, `${file.name}.md`));
|
|
13132
|
+
for (const [name, content] of previousContents) await writeFileContent(join(curatedDir, `${name}.md`), content);
|
|
13133
|
+
throw error;
|
|
13134
|
+
}
|
|
13135
|
+
}
|
|
13136
|
+
/**
|
|
13137
|
+
* Check whether a skill should be skipped during fetching.
|
|
13138
|
+
* Returns true (with appropriate logging) if the skill should be skipped.
|
|
13139
|
+
*/
|
|
13140
|
+
function shouldSkipSkill(params) {
|
|
13141
|
+
const { skillName, sourceKey, localSkillNames, alreadyFetchedSkillNames, logger } = params;
|
|
13142
|
+
if (skillName.includes("..") || skillName.includes("/") || skillName.includes("\\")) {
|
|
13143
|
+
logger.warn(`Skipping skill with invalid name ${quoteForLog(skillName)} from ${sourceKey}: contains path traversal characters.`);
|
|
13144
|
+
return true;
|
|
13145
|
+
}
|
|
13146
|
+
const unsafe = describeUnsafeRemoteName(skillName);
|
|
13147
|
+
if (unsafe !== void 0) {
|
|
13148
|
+
logger.warn(`Skipping skill with unsafe name ${unsafe} from ${sourceKey}.`);
|
|
13149
|
+
return true;
|
|
13150
|
+
}
|
|
13151
|
+
if (localSkillNames.has(skillName)) {
|
|
13152
|
+
logger.debug(`Skipping remote skill ${quoteForLog(skillName)} from ${sourceKey}: local skill takes precedence.`);
|
|
13153
|
+
return true;
|
|
13154
|
+
}
|
|
13155
|
+
if (alreadyFetchedSkillNames.has(skillName)) {
|
|
13156
|
+
logger.warn(`Skipping duplicate skill ${quoteForLog(skillName)} from ${sourceKey}: already fetched from another source.`);
|
|
13157
|
+
return true;
|
|
13158
|
+
}
|
|
13159
|
+
return false;
|
|
13160
|
+
}
|
|
13161
|
+
/**
|
|
13162
|
+
* Check whether a remote rule, command or subagent should be skipped: its
|
|
13163
|
+
* name could escape the curated directory or is unsafe to print, a local file
|
|
13164
|
+
* of the same name takes precedence, or an earlier source already took it.
|
|
13165
|
+
*/
|
|
13166
|
+
function shouldSkipFile(params) {
|
|
13167
|
+
const { feature, name, sourceKey, localNames, alreadyFetchedNames, logger } = params;
|
|
13168
|
+
const noun = getFileFeatureNoun(feature);
|
|
13169
|
+
if (!isValidRuleName(name)) {
|
|
13170
|
+
logger.warn(`Skipping ${noun} with invalid name ${quoteForLog(name)} from ${sourceKey}.`);
|
|
13171
|
+
return true;
|
|
13172
|
+
}
|
|
13173
|
+
const unsafe = describeUnsafeRemoteName(name);
|
|
13174
|
+
if (unsafe !== void 0) {
|
|
13175
|
+
logger.warn(`Skipping ${noun} with unsafe name ${unsafe} from ${sourceKey}.`);
|
|
13176
|
+
return true;
|
|
13177
|
+
}
|
|
13178
|
+
if (localNames.has(name)) {
|
|
13179
|
+
logger.debug(`Skipping remote ${noun} ${quoteForLog(name)} from ${sourceKey}: local ${noun} takes precedence.`);
|
|
13180
|
+
return true;
|
|
13181
|
+
}
|
|
13182
|
+
if (alreadyFetchedNames.has(name)) {
|
|
13183
|
+
logger.warn(`Skipping duplicate ${noun} ${quoteForLog(name)} from ${sourceKey}: already fetched from another source.`);
|
|
13184
|
+
return true;
|
|
13185
|
+
}
|
|
13186
|
+
return false;
|
|
13187
|
+
}
|
|
13188
|
+
/**
|
|
13189
|
+
* Why a remote skill or rule name must not be installed, already quoted for a
|
|
13190
|
+
* log line, or `undefined` when it is safe. It applies the same gate as
|
|
13191
|
+
* `rulesync fetch`: a name hiding control or deceptive zero-width characters
|
|
13192
|
+
* could rewrite the terminal when printed, or pass for another name, and a
|
|
13193
|
+
* name Windows folds lands on a different entry than it reads as.
|
|
13194
|
+
*/
|
|
13195
|
+
function describeUnsafeRemoteName(name) {
|
|
13196
|
+
const verdict = classifyRemoteName(name);
|
|
13197
|
+
if (verdict.kind === "safe") return;
|
|
13198
|
+
return verdict.reason === "hidden" ? `${quoteForLog(verdict.display)} (it contains hidden or control characters)` : `${quoteForLog(name)} (Windows resolves it to a different name)`;
|
|
13199
|
+
}
|
|
13200
|
+
function isValidRuleName(ruleName) {
|
|
13201
|
+
return !(ruleName.includes("..") || ruleName.includes("/") || ruleName.includes("\\") || ruleName.length === 0 || [
|
|
13202
|
+
"__proto__",
|
|
13203
|
+
"constructor",
|
|
13204
|
+
"prototype"
|
|
13205
|
+
].includes(ruleName));
|
|
13206
|
+
}
|
|
13207
|
+
/**
|
|
13208
|
+
* A fetched artifact whose content no longer matches the integrity recorded
|
|
13209
|
+
* for the same resolved ref. Under `--frozen` that is fatal — the lockfile is
|
|
13210
|
+
* the contract, and the gh transport refuses the same case — otherwise it is
|
|
13211
|
+
* reported and the new content is taken.
|
|
13212
|
+
*/
|
|
13213
|
+
function reportIntegrityMismatch(params) {
|
|
13214
|
+
const { message, frozen, logger } = params;
|
|
13215
|
+
if (frozen) throw new Error(`${message} Refusing to install it under --frozen.`);
|
|
13216
|
+
logger.warn(message);
|
|
13217
|
+
}
|
|
13218
|
+
async function writeFeatureFileAndComputeIntegrity(params) {
|
|
13219
|
+
const { feature, file, curatedDir, locked, resolvedRef, sourceKey, compareLockedIntegrity = true, frozen, logger } = params;
|
|
13220
|
+
const relativePath = `${file.name}.md`;
|
|
13221
|
+
checkPathTraversal({
|
|
13222
|
+
relativePath,
|
|
13223
|
+
intendedRootDir: curatedDir
|
|
13224
|
+
});
|
|
13225
|
+
const integrity = computeRuleIntegrity(file.content);
|
|
13226
|
+
const lockedEntry = locked ? getLockedFileFeatureState(locked, feature).items?.[file.name] : void 0;
|
|
13227
|
+
if (compareLockedIntegrity && lockedEntry?.integrity && lockedEntry.integrity !== integrity && resolvedRef === locked?.resolvedRef) reportIntegrityMismatch({
|
|
13228
|
+
message: `Integrity mismatch for ${getFileFeatureNoun(feature)} ${quoteForLog(file.name)} from ${sourceKey}: expected "${lockedEntry.integrity}", got "${integrity}". Content may have been tampered with.`,
|
|
13229
|
+
frozen,
|
|
13230
|
+
logger
|
|
13231
|
+
});
|
|
13232
|
+
await writeFileContent(join(curatedDir, relativePath), file.content);
|
|
13233
|
+
return { integrity };
|
|
13234
|
+
}
|
|
13235
|
+
/**
|
|
13236
|
+
* Write skill files to disk, compute integrity, and check against the lockfile.
|
|
13237
|
+
* Returns the computed LockedSkill entry.
|
|
13238
|
+
*/
|
|
13239
|
+
async function writeSkillAndComputeIntegrity(params) {
|
|
13240
|
+
const { skillName, files, curatedDir, locked, resolvedSha, sourceKey, frozen, logger } = params;
|
|
13241
|
+
for (const file of files) checkPathTraversal({
|
|
13242
|
+
relativePath: file.relativePath,
|
|
13243
|
+
intendedRootDir: join(curatedDir, skillName)
|
|
13244
|
+
});
|
|
13245
|
+
const integrity = computeSkillIntegrity(files.map((file) => ({
|
|
13246
|
+
path: file.relativePath,
|
|
13247
|
+
content: file.content
|
|
13248
|
+
})));
|
|
13249
|
+
const lockedSkillEntry = locked?.skills[skillName];
|
|
13250
|
+
if (lockedSkillEntry?.integrity && lockedSkillEntry.integrity !== integrity && resolvedSha === locked?.resolvedRef) reportIntegrityMismatch({
|
|
13251
|
+
message: `Integrity mismatch for skill ${quoteForLog(skillName)} from ${sourceKey}: expected "${lockedSkillEntry.integrity}", got "${integrity}". Content may have been tampered with.`,
|
|
13252
|
+
frozen,
|
|
13253
|
+
logger
|
|
13254
|
+
});
|
|
13255
|
+
for (const file of files) {
|
|
13256
|
+
const filePath = join(curatedDir, skillName, file.relativePath);
|
|
13257
|
+
await writeFileContent(filePath, file.content);
|
|
13258
|
+
if (file.executable === true) await applyFileMode(filePath, 493);
|
|
13259
|
+
}
|
|
13260
|
+
return { integrity };
|
|
13261
|
+
}
|
|
13262
|
+
/**
|
|
13263
|
+
* Merge back locked skills that still exist in the remote but were skipped
|
|
13264
|
+
* during fetching (due to local precedence, already-fetched, etc.). Skills no
|
|
13265
|
+
* longer present in the remote (e.g. renamed or deleted upstream) are
|
|
13266
|
+
* intentionally dropped. Shared by the git/github and npm lock updates.
|
|
13267
|
+
*/
|
|
13268
|
+
function mergeFetchedWithLockedSkills(params) {
|
|
13269
|
+
const { fetchedSkills, lockedSkills, remoteSkillNames } = params;
|
|
13270
|
+
const remoteSet = new Set(remoteSkillNames);
|
|
13271
|
+
const mergedSkills = { ...fetchedSkills };
|
|
13272
|
+
if (lockedSkills) {
|
|
13273
|
+
for (const [skillName, skillEntry] of Object.entries(lockedSkills)) if (!(skillName in mergedSkills) && remoteSet.has(skillName)) mergedSkills[skillName] = skillEntry;
|
|
13274
|
+
}
|
|
13275
|
+
return mergedSkills;
|
|
13276
|
+
}
|
|
13277
|
+
function assertMatchingSkillsFound({ skillNames, source }) {
|
|
13278
|
+
if (skillNames.length === 0) throw new Error(`No matching skills found in ${source}.`);
|
|
13279
|
+
}
|
|
13280
|
+
/**
|
|
13281
|
+
* Merge newly fetched skills with existing locked skills and update the lockfile.
|
|
13282
|
+
*/
|
|
13283
|
+
function buildLockUpdate(params) {
|
|
13284
|
+
const { lock, lockKey, sourceKey, fetchedSkills, locked, requestedRef, resolvedSha, skillSelection, skillsPath, remoteSkillNames, logger } = params;
|
|
13285
|
+
const fetchedNames = Object.keys(fetchedSkills);
|
|
13286
|
+
const mergedSkills = mergeFetchedWithLockedSkills({
|
|
13287
|
+
fetchedSkills,
|
|
13288
|
+
lockedSkills: locked?.skills,
|
|
13289
|
+
remoteSkillNames
|
|
13290
|
+
});
|
|
13291
|
+
const updatedLock = setLockedSource(lock, lockKey, {
|
|
13292
|
+
requestedRef,
|
|
13293
|
+
resolvedRef: resolvedSha,
|
|
13294
|
+
resolvedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
13295
|
+
skills: mergedSkills,
|
|
13296
|
+
skillSelection,
|
|
13297
|
+
skillsPath,
|
|
13298
|
+
rules: locked?.rules ?? {},
|
|
13299
|
+
ruleSelection: locked?.ruleSelection,
|
|
13300
|
+
rulesPath: locked?.rulesPath,
|
|
13301
|
+
resolvedRuleNames: locked?.resolvedRuleNames,
|
|
13302
|
+
...pickFileFeatureLockFields({
|
|
13303
|
+
locked,
|
|
13304
|
+
features: ["commands", "subagents"]
|
|
13305
|
+
})
|
|
13306
|
+
});
|
|
13307
|
+
logger.info(`Fetched ${fetchedNames.length} skill(s) from ${sourceKey}: ${fetchedNames.map(stripControlCharacters).join(", ") || "(none)"}`);
|
|
13308
|
+
return {
|
|
13309
|
+
updatedLock,
|
|
13310
|
+
fetchedNames
|
|
13311
|
+
};
|
|
13312
|
+
}
|
|
13313
|
+
/**
|
|
13314
|
+
* The lock fields of the given per-file features, copied from a lock entry
|
|
13315
|
+
* (empty when there is none), so that writing one feature's fields keeps the
|
|
13316
|
+
* others as they were.
|
|
13317
|
+
*/
|
|
13318
|
+
function pickFileFeatureLockFields(params) {
|
|
13319
|
+
const { locked, features } = params;
|
|
13320
|
+
if (locked === void 0) return {};
|
|
13321
|
+
return Object.assign({}, ...features.map((feature) => toFileFeatureLockFields(feature, getLockedFileFeatureState(locked, feature))));
|
|
13322
|
+
}
|
|
13323
|
+
function buildFileLockUpdate(params) {
|
|
13324
|
+
const { feature, lock, lockKey, sourceKey, fetchedFiles, locked, requestedRef, resolvedRef, selection, path, resolvedNames, logger } = params;
|
|
13325
|
+
const fetchedNames = Object.keys(fetchedFiles);
|
|
13326
|
+
const updatedLock = setLockedSource(lock, lockKey, {
|
|
13327
|
+
requestedRef,
|
|
13328
|
+
resolvedRef,
|
|
13329
|
+
resolvedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
13330
|
+
skills: locked?.skills ?? {},
|
|
13331
|
+
skillSelection: locked?.skillSelection,
|
|
13332
|
+
skillsPath: locked?.skillsPath,
|
|
13333
|
+
...pickFileFeatureLockFields({
|
|
13334
|
+
locked,
|
|
13335
|
+
features: SOURCE_FILE_FEATURES
|
|
13336
|
+
}),
|
|
13337
|
+
...toFileFeatureLockFields(feature, {
|
|
13338
|
+
items: fetchedFiles,
|
|
13339
|
+
selection,
|
|
13340
|
+
path,
|
|
13341
|
+
resolvedNames
|
|
13342
|
+
})
|
|
13343
|
+
});
|
|
13344
|
+
logger.info(`Fetched ${fetchedNames.length} ${getFileFeatureNoun(feature)}(s) from ${sourceKey}: ${fetchedNames.map(stripControlCharacters).join(", ") || "(none)"}`);
|
|
13345
|
+
return {
|
|
13346
|
+
updatedLock,
|
|
13347
|
+
fetchedNames
|
|
13348
|
+
};
|
|
13349
|
+
}
|
|
13350
|
+
function getFirstPathSeparatorIndex(path) {
|
|
13351
|
+
const slashIndex = path.indexOf("/");
|
|
13352
|
+
const backslashIndex = path.indexOf("\\");
|
|
13353
|
+
if (slashIndex === -1) return backslashIndex;
|
|
13354
|
+
if (backslashIndex === -1) return slashIndex;
|
|
13355
|
+
return Math.min(slashIndex, backslashIndex);
|
|
13356
|
+
}
|
|
13357
|
+
/**
|
|
13358
|
+
* Decide whether a repository's root-level files should be installed as the
|
|
13359
|
+
* single requested skill (the "root fallback").
|
|
13360
|
+
*
|
|
13361
|
+
* A root fallback fires only when a single, non-wildcard skill was requested,
|
|
13362
|
+
* that skill's own directory is absent, and the repository root actually carries
|
|
13363
|
+
* a `SKILL.md`. Both the git transport (`groupRemoteFilesBySkillRoot`) and the
|
|
13364
|
+
* GitHub transport (`discoverGithubSkillDirs`) gate on these same conditions, so
|
|
13365
|
+
* the decision lives here to keep the two paths from drifting.
|
|
13366
|
+
*/
|
|
13367
|
+
function shouldUseRootFallback(params) {
|
|
13368
|
+
const { skillFilter, isWildcard, hasRootSkillFile, hasRequestedSkillDir } = params;
|
|
13369
|
+
const [singleSkillName] = skillFilter;
|
|
13370
|
+
return !isWildcard && skillFilter.length === 1 && singleSkillName !== void 0 && hasRootSkillFile && !hasRequestedSkillDir;
|
|
13371
|
+
}
|
|
13372
|
+
function groupRemoteFilesBySkillRoot(params) {
|
|
13373
|
+
const { remoteFiles, skillFilter, isWildcard } = params;
|
|
13374
|
+
const grouped = /* @__PURE__ */ new Map();
|
|
13375
|
+
const rootLevelFiles = [];
|
|
13376
|
+
for (const file of remoteFiles) {
|
|
13377
|
+
const separatorIndex = getFirstPathSeparatorIndex(file.relativePath);
|
|
13378
|
+
if (separatorIndex === -1) {
|
|
13379
|
+
rootLevelFiles.push(file);
|
|
13380
|
+
continue;
|
|
13381
|
+
}
|
|
13382
|
+
const skillName = file.relativePath.substring(0, separatorIndex);
|
|
13383
|
+
if (skillName.length === 0) continue;
|
|
13384
|
+
const innerPath = file.relativePath.substring(separatorIndex + 1);
|
|
13385
|
+
const groupedFiles = grouped.get(skillName) ?? [];
|
|
13386
|
+
groupedFiles.push({
|
|
13387
|
+
...file,
|
|
13388
|
+
relativePath: innerPath
|
|
13389
|
+
});
|
|
13390
|
+
grouped.set(skillName, groupedFiles);
|
|
13391
|
+
}
|
|
13392
|
+
const [singleSkillName] = skillFilter;
|
|
13393
|
+
const hasRootSkillFile = rootLevelFiles.some((file) => file.relativePath === SKILL_FILE_NAME);
|
|
13394
|
+
if (singleSkillName !== void 0 && shouldUseRootFallback({
|
|
13395
|
+
skillFilter,
|
|
13396
|
+
isWildcard,
|
|
13397
|
+
hasRootSkillFile,
|
|
13398
|
+
hasRequestedSkillDir: grouped.has(singleSkillName)
|
|
13399
|
+
})) grouped.set(singleSkillName, rootLevelFiles);
|
|
13400
|
+
return grouped;
|
|
13401
|
+
}
|
|
13402
|
+
function normalizeRuleFilterName(name) {
|
|
13403
|
+
return name.replace(/\.md$/i, "");
|
|
13404
|
+
}
|
|
13405
|
+
/** Whether a declared skill or rule selection is the `["*"]` wildcard. */
|
|
13406
|
+
function isWildcardSelection(selection) {
|
|
13407
|
+
return selection.length === 1 && selection[0] === "*";
|
|
13408
|
+
}
|
|
13409
|
+
/**
|
|
13410
|
+
* Pick the remote files a source entry declares for one per-file feature:
|
|
13411
|
+
* Markdown files whose normalized name is selected by the feature's field
|
|
13412
|
+
* (`sourceEntry.rules`, `.commands` or `.subagents`, or the wildcard) and is a
|
|
13413
|
+
* valid file name. Candidate order is preserved.
|
|
13414
|
+
*/
|
|
13415
|
+
function selectDeclaredFiles(params) {
|
|
13416
|
+
const { feature, sourceEntry, candidates, getFileName } = params;
|
|
13417
|
+
const ruleFilter = (sourceEntry[feature] ?? []).map(normalizeRuleFilterName);
|
|
13418
|
+
const isWildcard = isWildcardSelection(ruleFilter);
|
|
13419
|
+
return candidates.filter((candidate) => getFileName(candidate).toLowerCase().endsWith(".md")).map((candidate) => ({
|
|
13420
|
+
candidate,
|
|
13421
|
+
name: normalizeRuleFilterName(getFileName(candidate))
|
|
13422
|
+
})).filter(({ name }) => (isWildcard || ruleFilter.includes(name)) && isValidRuleName(name));
|
|
13423
|
+
}
|
|
13424
|
+
function normalizeRuleSelection(rules) {
|
|
13425
|
+
return [...new Set(rules.map(normalizeRuleFilterName))].toSorted();
|
|
13426
|
+
}
|
|
13427
|
+
function normalizeSkillSelection(skills) {
|
|
13428
|
+
return [...new Set(skills)].toSorted();
|
|
13429
|
+
}
|
|
13430
|
+
/**
|
|
13431
|
+
* Whether the locked entry was written for the `skills` selection and skills
|
|
13432
|
+
* path the manifest declares now. Without it, widening the selection or moving
|
|
13433
|
+
* the path after an install is a silent no-op: the ref is unchanged and every
|
|
13434
|
+
* locked skill is on disk, so nothing is fetched and `--frozen` never notices.
|
|
13435
|
+
*
|
|
13436
|
+
* Lockfiles written before the path was recorded carry no `skillsPath`. Such
|
|
13437
|
+
* an entry is handled like one without `skillSelection`: fetched again at its
|
|
13438
|
+
* locked ref to record the path, and accepted as-is under `acceptLegacy`.
|
|
13439
|
+
*
|
|
13440
|
+
* Lockfiles written before the selection was recorded carry no
|
|
13441
|
+
* `skillSelection`. An install that may write the lockfile fetches such an
|
|
13442
|
+
* entry again at its locked ref so the selection gets recorded once; the checks that
|
|
13443
|
+
* cannot write it (`--frozen`, adding a source) pass `acceptLegacy` and fall
|
|
13444
|
+
* back to the locked skill names instead, so a wildcard is taken at face value
|
|
13445
|
+
* and an explicit list is covered only when every name it selects is locked.
|
|
13446
|
+
* An entry that locks no skills at all (a rules-only install) covers nothing:
|
|
13447
|
+
* it was never written for a skill selection.
|
|
13448
|
+
*/
|
|
13449
|
+
function lockedSkillConfigMatches(params) {
|
|
13450
|
+
const skills = getSourceFilters(params.sourceEntry).skills;
|
|
13451
|
+
if (skills === void 0) return false;
|
|
13452
|
+
const lockedPath = params.locked.skillsPath;
|
|
13453
|
+
if (lockedPath === void 0 ? !params.acceptLegacy : lockedPath !== resolveSkillsPath(params.sourceEntry)) return false;
|
|
13454
|
+
const selection = normalizeSkillSelection(skills);
|
|
13455
|
+
const lockedSelection = params.locked.skillSelection;
|
|
13456
|
+
if (lockedSelection === void 0) {
|
|
13457
|
+
const lockedSkillNames = new Set(Object.keys(params.locked.skills));
|
|
13458
|
+
if (!params.acceptLegacy || lockedSkillNames.size === 0) return false;
|
|
13459
|
+
if (isWildcardSelection(selection)) return true;
|
|
13460
|
+
return selection.every((skillName) => lockedSkillNames.has(skillName));
|
|
13461
|
+
}
|
|
13462
|
+
return selection.length === lockedSelection.length && selection.every((skillName, index) => skillName === lockedSelection[index]);
|
|
13463
|
+
}
|
|
13464
|
+
/**
|
|
13465
|
+
* Skip the re-fetch when the SHA and the skill selection match the lockfile and
|
|
13466
|
+
* every curated skill the entry locks is still on disk, unmodified.
|
|
13467
|
+
*/
|
|
13468
|
+
async function canReuseLockedSkills(params) {
|
|
13469
|
+
const { locked, resolvedSha, updateSources, frozen, sourceEntry, curatedDir, getAlreadyFetchedSkillNames } = params;
|
|
13470
|
+
return locked !== void 0 && resolvedSha === locked.resolvedRef && !updateSources && lockedSkillConfigMatches({
|
|
13471
|
+
locked,
|
|
13472
|
+
sourceEntry,
|
|
13473
|
+
acceptLegacy: frozen
|
|
13474
|
+
}) && await checkLockedSkillsAreValid({
|
|
13475
|
+
curatedDir,
|
|
13476
|
+
skills: locked.skills,
|
|
13477
|
+
presenceOnlySkillNames: await getAlreadyFetchedSkillNames()
|
|
13478
|
+
});
|
|
13479
|
+
}
|
|
13480
|
+
/**
|
|
13481
|
+
* The path the skills of a source are read from, as declared: the source's
|
|
13482
|
+
* `path`, else (for the github transport) the path embedded in the source
|
|
13483
|
+
* spec, else `skills`. Every transport fetches from this path, and the
|
|
13484
|
+
* lockfile records its normalized form ({@link resolveSkillsPath}), so the
|
|
13485
|
+
* fetch and the lock comparison cannot pick different paths.
|
|
13486
|
+
*/
|
|
13487
|
+
function resolveSkillsSourcePath(sourceEntry) {
|
|
13488
|
+
const embeddedPath = getSourceTransport(sourceEntry) === "github" ? parseSource(sourceEntry.source).path : void 0;
|
|
13489
|
+
return sourceEntry.path ?? embeddedPath ?? "skills";
|
|
13490
|
+
}
|
|
13491
|
+
/** The skills path of a source in the form the lockfile records and compares. */
|
|
13492
|
+
function resolveSkillsPath(sourceEntry) {
|
|
13493
|
+
return normalizeSourceDirPath(resolveSkillsSourcePath(sourceEntry));
|
|
13494
|
+
}
|
|
13495
|
+
/**
|
|
13496
|
+
* The path one per-file feature of a source is read from, as declared: the
|
|
13497
|
+
* source's `rulesPath` / `commandsPath` / `subagentsPath`, else `rules` /
|
|
13498
|
+
* `commands` / `subagents`. The counterpart of {@link resolveSkillsSourcePath}.
|
|
13499
|
+
*/
|
|
13500
|
+
function resolveFileFeatureSourcePath(sourceEntry, feature) {
|
|
13501
|
+
const spec = FILE_FEATURE_SPECS[feature];
|
|
13502
|
+
return sourceEntry[spec.pathField] ?? spec.defaultPath;
|
|
13503
|
+
}
|
|
13504
|
+
/** A per-file feature's path in the form the lockfile records and compares. */
|
|
13505
|
+
function resolveFileFeaturePath(sourceEntry, feature) {
|
|
13506
|
+
return normalizeSourceDirPath(resolveFileFeatureSourcePath(sourceEntry, feature));
|
|
13507
|
+
}
|
|
13508
|
+
/**
|
|
13509
|
+
* The form a source directory path is recorded in the lockfile and compared
|
|
13510
|
+
* in: posix separators, normalized, with no trailing slash.
|
|
13511
|
+
*/
|
|
13512
|
+
function normalizeSourceDirPath(dirPath) {
|
|
13513
|
+
return normalizePosixDirPath(dirPath);
|
|
13514
|
+
}
|
|
13515
|
+
/**
|
|
13516
|
+
* Whether a lock entry was written for the selection and path one per-file
|
|
13517
|
+
* feature of the source declares now.
|
|
13518
|
+
*/
|
|
13519
|
+
function lockedFileConfigMatches(params) {
|
|
13520
|
+
const { feature, locked, sourceEntry } = params;
|
|
13521
|
+
const declared = getSourceFilters(sourceEntry)[feature];
|
|
13522
|
+
const { selection: lockedSelection, path: lockedPath } = getLockedFileFeatureState(locked, feature);
|
|
13523
|
+
if (declared === void 0 || lockedSelection === void 0) return false;
|
|
13524
|
+
const selection = normalizeRuleSelection(declared);
|
|
13525
|
+
return selection.length === lockedSelection.length && selection.every((name, index) => name === lockedSelection[index]) && resolveFileFeaturePath(sourceEntry, feature) === lockedPath;
|
|
13526
|
+
}
|
|
13527
|
+
function assertMatchingFilesFound(params) {
|
|
13528
|
+
if (params.names.length === 0) throw new Error(`No matching ${params.feature} found in ${params.source}.`);
|
|
13529
|
+
}
|
|
13530
|
+
/**
|
|
13531
|
+
* "N skill(s) and M rule(s)", followed by the command and subagent counts when
|
|
13532
|
+
* any were installed, for the summary lines of `add` and `install`.
|
|
13533
|
+
*/
|
|
13534
|
+
function formatInstalledCounts(result) {
|
|
13535
|
+
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);
|
|
13536
|
+
const parts = [
|
|
13537
|
+
`${result.fetchedSkillCount} skill(s)`,
|
|
13538
|
+
`${result.fetchedRuleCount} rule(s)`,
|
|
13539
|
+
...extras
|
|
13540
|
+
];
|
|
13541
|
+
return `${parts.slice(0, -1).join(", ")} and ${parts.at(-1)}`;
|
|
13542
|
+
}
|
|
12343
13543
|
const SKILL_DESCRIPTION_MAX_LENGTH = 1024;
|
|
12344
13544
|
const SKILL_NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
12345
13545
|
/**
|
|
@@ -15462,8 +16662,11 @@ var FeatureProcessor = class extends RulesyncSourceConsumer {
|
|
|
15462
16662
|
})) continue;
|
|
15463
16663
|
const existingFileContent = await readFileContentOrNull(filePath);
|
|
15464
16664
|
if (existingFileContent !== null && aiFile.shouldMergeExistingFileContent()) aiFile.setFileContent(existingFileContent);
|
|
15465
|
-
const contentWithNewline = addTrailingNewline(aiFile.getFileContent());
|
|
15466
16665
|
const existingContent = existingFileContent;
|
|
16666
|
+
const contentWithNewline = aiFile.composeWrittenContent({
|
|
16667
|
+
existingContent,
|
|
16668
|
+
generatedContent: addTrailingNewline(aiFile.getFileContent())
|
|
16669
|
+
});
|
|
15467
16670
|
if (existingContent === null && aiFile.shouldSkipCreationWhenPayloadEmpty() && fileContentIsEmptyPayload({
|
|
15468
16671
|
filePath,
|
|
15469
16672
|
content: contentWithNewline
|
|
@@ -15582,6 +16785,21 @@ var FeatureProcessor = class extends RulesyncSourceConsumer {
|
|
|
15582
16785
|
}
|
|
15583
16786
|
if (refused) continue;
|
|
15584
16787
|
const loggedPath = stripControlCharacters(filePath);
|
|
16788
|
+
if (aiFile.keepsContentOnRemoval()) {
|
|
16789
|
+
const existingContent = await readFileContentOrNull(filePath);
|
|
16790
|
+
const outcome = existingContent === null ? { action: "delete" } : aiFile.composeContentAfterRemoval({ existingContent });
|
|
16791
|
+
if (outcome.action === "keep") continue;
|
|
16792
|
+
if (outcome.action === "rewrite") {
|
|
16793
|
+
if (this.dryRun) this.logger.info(`[DRY RUN] Would rewrite: ${loggedPath}`);
|
|
16794
|
+
else {
|
|
16795
|
+
await writeFileContent(filePath, outcome.content);
|
|
16796
|
+
this.logger.info(`Removed the generated block from: ${loggedPath}`);
|
|
16797
|
+
}
|
|
16798
|
+
this.sweepWrites.paths.push(aiFile.getRelativePathFromCwd());
|
|
16799
|
+
removedCount++;
|
|
16800
|
+
continue;
|
|
16801
|
+
}
|
|
16802
|
+
}
|
|
15585
16803
|
if (this.dryRun) this.logger.info(`[DRY RUN] Would delete: ${loggedPath}`);
|
|
15586
16804
|
else {
|
|
15587
16805
|
await removeFile(filePath);
|
|
@@ -15966,8 +17184,8 @@ var ClaimedIdentities = class {
|
|
|
15966
17184
|
};
|
|
15967
17185
|
// src/utils/curated-frontmatter.ts
|
|
15968
17186
|
/**
|
|
15969
|
-
* The frontmatter fields a command or
|
|
15970
|
-
* keeps. Only the canonical, tool-neutral fields of the rulesync schema are
|
|
17187
|
+
* The frontmatter fields a command, subagent or skill fetched from a declared
|
|
17188
|
+
* source keeps. Only the canonical, tool-neutral fields of the rulesync schema are
|
|
15971
17189
|
* listed: none of them grants tools, permissions, hooks or MCP servers.
|
|
15972
17190
|
*
|
|
15973
17191
|
* Every tool section (`claudecode`, `codexcli`, `kiro`, `opencode`, ...) is
|
|
@@ -15984,6 +17202,30 @@ const CURATED_SUBAGENT_FRONTMATTER_KEYS = [
|
|
|
15984
17202
|
"description"
|
|
15985
17203
|
];
|
|
15986
17204
|
/**
|
|
17205
|
+
* A skill also keeps the root invocation flags (`disable-model-invocation`,
|
|
17206
|
+
* `user-invocable`), which only narrow when the skill is loaded, and the Agent
|
|
17207
|
+
* Skills packaging fields (`license`, `compatibility`, `metadata`). Inside
|
|
17208
|
+
* `metadata`, the tool blocks listed in `CURATED_SKILL_DROPPED_METADATA_KEYS`
|
|
17209
|
+
* are dropped, since they gate or install things rather than describe the
|
|
17210
|
+
* skill.
|
|
17211
|
+
*/
|
|
17212
|
+
const CURATED_SKILL_FRONTMATTER_KEYS = [
|
|
17213
|
+
"targets",
|
|
17214
|
+
"name",
|
|
17215
|
+
"description",
|
|
17216
|
+
"disable-model-invocation",
|
|
17217
|
+
"user-invocable",
|
|
17218
|
+
"license",
|
|
17219
|
+
"compatibility",
|
|
17220
|
+
"metadata"
|
|
17221
|
+
];
|
|
17222
|
+
/**
|
|
17223
|
+
* `metadata` keys a tool reads as configuration: OpenClaw's `metadata.openclaw`
|
|
17224
|
+
* (`install`, `always`, `requires`, ...) and Hermes Agent's `metadata.hermes`
|
|
17225
|
+
* (`requires_toolsets`, ...). A skill fetched from a source loses them.
|
|
17226
|
+
*/
|
|
17227
|
+
const CURATED_SKILL_DROPPED_METADATA_KEYS = ["openclaw", "hermes"];
|
|
17228
|
+
/**
|
|
15987
17229
|
* Keep only `allowedKeys` of a frontmatter object. Returns a new frontmatter
|
|
15988
17230
|
* and the names of the dropped top-level keys, in input order.
|
|
15989
17231
|
*/
|
|
@@ -31700,6 +32942,15 @@ const defaultGetFactory$5 = (target) => {
|
|
|
31700
32942
|
const skillsProcessorToolTargetsProject = [...toolSkillFactories].filter(([, factory]) => factory.meta.supportsProject).map(([target]) => target);
|
|
31701
32943
|
const skillsProcessorToolTargetsSimulated = [...toolSkillFactories].filter(([, factory]) => factory.meta.supportsSimulated).map(([target]) => target);
|
|
31702
32944
|
const skillsProcessorToolTargetsGlobal = [...toolSkillFactories].filter(([, factory]) => factory.meta.supportsGlobal).map(([target]) => target);
|
|
32945
|
+
/**
|
|
32946
|
+
* Whether a skill companion path is the Codex `agents/openai.yaml` sidecar,
|
|
32947
|
+
* compared case-insensitively and with either separator, since a
|
|
32948
|
+
* case-insensitive filesystem or Windows resolves those spellings to it.
|
|
32949
|
+
*/
|
|
32950
|
+
function isCodexOpenaiYaml(relativeFilePath) {
|
|
32951
|
+
const normalize = (path) => path.replaceAll("\\", "/").toLowerCase();
|
|
32952
|
+
return normalize(relativeFilePath) === normalize(CODEXCLI_OPENAI_YAML_RELATIVE_PATH);
|
|
32953
|
+
}
|
|
31703
32954
|
var SkillsProcessor = class extends DirFeatureProcessor {
|
|
31704
32955
|
toolTarget;
|
|
31705
32956
|
global;
|
|
@@ -31813,16 +33064,59 @@ var SkillsProcessor = class extends DirFeatureProcessor {
|
|
|
31813
33064
|
}));
|
|
31814
33065
|
return false;
|
|
31815
33066
|
});
|
|
31816
|
-
curatedSkills = await Promise.all(nonConflicting.map((dirName) => RulesyncSkill.fromDir({
|
|
33067
|
+
curatedSkills = await Promise.all(nonConflicting.map(async (dirName) => this.withCanonicalFrontmatterOnly(await RulesyncSkill.fromDir({
|
|
31817
33068
|
outputRoot: treeParent,
|
|
31818
33069
|
relativeDirPath: treeCuratedSkillsDirPath,
|
|
31819
33070
|
dirName,
|
|
31820
33071
|
global: this.global
|
|
31821
|
-
})));
|
|
33072
|
+
}))));
|
|
31822
33073
|
}
|
|
31823
33074
|
return [...localSkills, ...curatedSkills];
|
|
31824
33075
|
}
|
|
31825
33076
|
/**
|
|
33077
|
+
* A skill fetched from a declared source, keeping only the canonical,
|
|
33078
|
+
* tool-neutral frontmatter fields and dropping every tool section, since
|
|
33079
|
+
* those are copied into the generated files and can grant tools or hooks
|
|
33080
|
+
* (Claude Code `allowed-tools` and `hooks`, for example). The tool blocks
|
|
33081
|
+
* inside `metadata` (OpenClaw's `metadata.openclaw`, Hermes Agent's
|
|
33082
|
+
* `metadata.hermes`) and a Codex `agents/openai.yaml` companion file (its
|
|
33083
|
+
* invocation policy and MCP dependencies) go too. The body and the other
|
|
33084
|
+
* companion files are kept. A local skill of the same name keeps its
|
|
33085
|
+
* tool-specific settings.
|
|
33086
|
+
*/
|
|
33087
|
+
withCanonicalFrontmatterOnly(skill) {
|
|
33088
|
+
const kept = keepCuratedFrontmatterKeys({
|
|
33089
|
+
frontmatter: skill.getFrontmatter(),
|
|
33090
|
+
allowedKeys: CURATED_SKILL_FRONTMATTER_KEYS
|
|
33091
|
+
});
|
|
33092
|
+
const frontmatter = kept.frontmatter;
|
|
33093
|
+
const droppedKeys = [...kept.droppedKeys];
|
|
33094
|
+
if (frontmatter.metadata !== void 0) {
|
|
33095
|
+
const metadata = { ...frontmatter.metadata };
|
|
33096
|
+
for (const key of CURATED_SKILL_DROPPED_METADATA_KEYS) if (Object.hasOwn(metadata, key)) {
|
|
33097
|
+
delete metadata[key];
|
|
33098
|
+
droppedKeys.push(`metadata.${key}`);
|
|
33099
|
+
}
|
|
33100
|
+
frontmatter.metadata = metadata;
|
|
33101
|
+
}
|
|
33102
|
+
const otherFiles = skill.getOtherFiles();
|
|
33103
|
+
const keptFiles = otherFiles.filter((file) => !isCodexOpenaiYaml(file.relativeFilePathToDirPath));
|
|
33104
|
+
const droppedFiles = otherFiles.length - keptFiles.length;
|
|
33105
|
+
if (droppedKeys.length === 0 && droppedFiles === 0) return skill;
|
|
33106
|
+
const skillPath = quoteForLog(join(skill.getRelativeDirPath(), skill.getDirName()));
|
|
33107
|
+
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.`);
|
|
33108
|
+
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.`);
|
|
33109
|
+
return new RulesyncSkill({
|
|
33110
|
+
outputRoot: skill.getOutputRoot(),
|
|
33111
|
+
relativeDirPath: skill.getRelativeDirPath(),
|
|
33112
|
+
dirName: skill.getDirName(),
|
|
33113
|
+
frontmatter,
|
|
33114
|
+
body: skill.getBody(),
|
|
33115
|
+
otherFiles: keptFiles,
|
|
33116
|
+
global: skill.getGlobal()
|
|
33117
|
+
});
|
|
33118
|
+
}
|
|
33119
|
+
/**
|
|
31826
33120
|
* Implementation of abstract method from DirFeatureProcessor.
|
|
31827
33121
|
*
|
|
31828
33122
|
* Load and parse rulesync skill directories from every configured input
|
|
@@ -41434,6 +42728,125 @@ var ClaudecodeLanguageSettings = class ClaudecodeLanguageSettings extends ToolFi
|
|
|
41434
42728
|
}
|
|
41435
42729
|
}
|
|
41436
42730
|
};
|
|
42731
|
+
// src/features/rules/rule-managed-block.ts
|
|
42732
|
+
/**
|
|
42733
|
+
* The fence `preserveUnmanagedRuleContent` wraps around the generated body of
|
|
42734
|
+
* a root rule file, so content a person writes outside it survives the next
|
|
42735
|
+
* `generate`. The wording follows the block `rulesync gitignore` writes
|
|
42736
|
+
* (`# Generated by Rulesync` / `# End of Rulesync`), as Markdown comments so
|
|
42737
|
+
* the tools reading the file do not show it.
|
|
42738
|
+
*/
|
|
42739
|
+
const RULE_MANAGED_BLOCK_START = "<!-- Generated by Rulesync -->";
|
|
42740
|
+
const RULE_MANAGED_BLOCK_END = "<!-- End of Rulesync -->";
|
|
42741
|
+
const LEADING_FRONTMATTER_PATTERN = /^---\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/;
|
|
42742
|
+
const splitLeadingFrontmatter = (content) => {
|
|
42743
|
+
const match = LEADING_FRONTMATTER_PATTERN.exec(content);
|
|
42744
|
+
if (!match) return {
|
|
42745
|
+
frontmatter: "",
|
|
42746
|
+
rest: content
|
|
42747
|
+
};
|
|
42748
|
+
return {
|
|
42749
|
+
frontmatter: match[0].endsWith("\n") ? match[0] : `${match[0]}\n`,
|
|
42750
|
+
rest: content.slice(match[0].length)
|
|
42751
|
+
};
|
|
42752
|
+
};
|
|
42753
|
+
const CODE_FENCE_PATTERN = /^ {0,3}(`{3,}|~{3,})/;
|
|
42754
|
+
/**
|
|
42755
|
+
* Locate the first complete fence: a line that is exactly the start marker
|
|
42756
|
+
* (surrounding whitespace aside) followed later by a line that is exactly the
|
|
42757
|
+
* end marker. A start marker without an end marker is not a fence. Marker
|
|
42758
|
+
* lines inside a Markdown code block (```` ``` ```` or `~~~`) do not count, so
|
|
42759
|
+
* a rule that quotes the markers in an example is not mistaken for a fence.
|
|
42760
|
+
*/
|
|
42761
|
+
const findFence = (content) => {
|
|
42762
|
+
let startLineBegin;
|
|
42763
|
+
let startLineEnd = 0;
|
|
42764
|
+
let openCodeFence;
|
|
42765
|
+
let offset = 0;
|
|
42766
|
+
while (offset <= content.length) {
|
|
42767
|
+
const newline = content.indexOf("\n", offset);
|
|
42768
|
+
const lineEnd = newline === -1 ? content.length : newline + 1;
|
|
42769
|
+
const rawLine = content.slice(offset, newline === -1 ? content.length : newline);
|
|
42770
|
+
const codeFence = CODE_FENCE_PATTERN.exec(rawLine)?.[1];
|
|
42771
|
+
if (openCodeFence !== void 0) {
|
|
42772
|
+
if (codeFence !== void 0 && codeFence[0] === openCodeFence[0] && codeFence.length >= openCodeFence.length && rawLine.trim() === codeFence) openCodeFence = void 0;
|
|
42773
|
+
} else if (codeFence !== void 0) openCodeFence = codeFence;
|
|
42774
|
+
else {
|
|
42775
|
+
const line = rawLine.trim();
|
|
42776
|
+
if (startLineBegin === void 0) {
|
|
42777
|
+
if (line === "<!-- Generated by Rulesync -->") {
|
|
42778
|
+
startLineBegin = offset;
|
|
42779
|
+
startLineEnd = lineEnd;
|
|
42780
|
+
}
|
|
42781
|
+
} else if (line === "<!-- End of Rulesync -->") return {
|
|
42782
|
+
startLineBegin,
|
|
42783
|
+
startLineEnd,
|
|
42784
|
+
endLineBegin: offset,
|
|
42785
|
+
endLineEnd: lineEnd
|
|
42786
|
+
};
|
|
42787
|
+
}
|
|
42788
|
+
if (newline === -1) break;
|
|
42789
|
+
offset = lineEnd;
|
|
42790
|
+
}
|
|
42791
|
+
};
|
|
42792
|
+
/**
|
|
42793
|
+
* Compose the content to write for a root rule file under
|
|
42794
|
+
* `preserveUnmanagedRuleContent`: the generated frontmatter (if any) first,
|
|
42795
|
+
* then whatever the existing file holds before its fence, the fenced
|
|
42796
|
+
* generated body, and whatever it holds after the fence.
|
|
42797
|
+
*
|
|
42798
|
+
* An existing file without a complete fence is treated as entirely
|
|
42799
|
+
* rulesync's — it is what rulesync wrote before the option was turned on, and
|
|
42800
|
+
* keeping it would duplicate that content outside the fence — so only the
|
|
42801
|
+
* fenced body is written. Hand edits belong outside the fence from then on.
|
|
42802
|
+
*
|
|
42803
|
+
* When the generated content starts with frontmatter, the existing file's
|
|
42804
|
+
* leading frontmatter is rulesync's too and is replaced rather than kept.
|
|
42805
|
+
*
|
|
42806
|
+
* When the generated content has no frontmatter, an existing leading
|
|
42807
|
+
* frontmatter block is kept as part of the content before the fence, even if
|
|
42808
|
+
* rulesync wrote it on an earlier run (a target or rule that no longer emits
|
|
42809
|
+
* frontmatter). Nothing in the file tells such a block apart from one a person
|
|
42810
|
+
* wrote: a hand-written block also sits right above the start marker, since
|
|
42811
|
+
* the fence opens the file rulesync writes. Keeping it never loses hand-written
|
|
42812
|
+
* content, and the result is stable across runs; a stale block is removed by
|
|
42813
|
+
* hand once.
|
|
42814
|
+
*/
|
|
42815
|
+
const spliceRuleManagedBlock = ({ existingContent, generatedContent }) => {
|
|
42816
|
+
const generated = splitLeadingFrontmatter(generatedContent);
|
|
42817
|
+
const body = generated.rest.replace(/^\n+/, "");
|
|
42818
|
+
const block = `${RULE_MANAGED_BLOCK_START}\n${body}${body === "" || body.endsWith("\n") ? "" : "\n"}${RULE_MANAGED_BLOCK_END}\n`;
|
|
42819
|
+
if (existingContent === null) return generated.frontmatter + block;
|
|
42820
|
+
const eol = (text) => existingContent.includes("\r\n") ? text.replaceAll("\n", "\r\n") : text;
|
|
42821
|
+
const existing = generated.frontmatter === "" ? existingContent : splitLeadingFrontmatter(existingContent).rest;
|
|
42822
|
+
const fence = findFence(existing);
|
|
42823
|
+
if (fence === void 0) return eol(generated.frontmatter + block);
|
|
42824
|
+
const before = existing.slice(0, fence.startLineBegin);
|
|
42825
|
+
let after = existing.slice(fence.endLineEnd);
|
|
42826
|
+
if (fence.endLineEnd === existing.length && !existing.endsWith("\n")) after = "";
|
|
42827
|
+
return eol(generated.frontmatter) + before + eol(block) + after;
|
|
42828
|
+
};
|
|
42829
|
+
/**
|
|
42830
|
+
* `content` with its first complete fence (marker lines included) taken out,
|
|
42831
|
+
* or `undefined` when it has none. Used when a root rule file stops being
|
|
42832
|
+
* generated: the fenced block is rulesync's to remove, the rest is not.
|
|
42833
|
+
*/
|
|
42834
|
+
const removeRuleManagedBlock = (content) => {
|
|
42835
|
+
const fence = findFence(content);
|
|
42836
|
+
if (fence === void 0) return;
|
|
42837
|
+
return content.slice(0, fence.startLineBegin) + content.slice(fence.endLineEnd);
|
|
42838
|
+
};
|
|
42839
|
+
/**
|
|
42840
|
+
* The text inside the first complete fence (without the marker lines), or
|
|
42841
|
+
* `undefined` when `content` has none. `import` keeps only this part so
|
|
42842
|
+
* hand-written content outside the fence is not copied into the rulesync
|
|
42843
|
+
* source, where the next `generate` would write it a second time.
|
|
42844
|
+
*/
|
|
42845
|
+
const extractRuleManagedBlock = (content) => {
|
|
42846
|
+
const fence = findFence(content);
|
|
42847
|
+
if (fence === void 0) return;
|
|
42848
|
+
return content.slice(fence.startLineEnd, fence.endLineBegin);
|
|
42849
|
+
};
|
|
41437
42850
|
// src/features/shared/opencode-family-mcp-tool-keys.ts
|
|
41438
42851
|
/**
|
|
41439
42852
|
* MCP tool naming shared by OpenCode and its forks (Kilo, MiMo Code):
|
|
@@ -43108,6 +44521,46 @@ var ToolRule = class extends ToolFile {
|
|
|
43108
44521
|
this.description = description;
|
|
43109
44522
|
this.globs = globs;
|
|
43110
44523
|
}
|
|
44524
|
+
/**
|
|
44525
|
+
* Whether the write phase fences the generated content and keeps what the
|
|
44526
|
+
* existing file holds outside the fence (`preserveUnmanagedRuleContent`).
|
|
44527
|
+
* Set by the rules processor on the root rule files it emits.
|
|
44528
|
+
*/
|
|
44529
|
+
preservesUnmanagedContent = false;
|
|
44530
|
+
/** See {@link ToolRule.preservesUnmanagedContent}. */
|
|
44531
|
+
enableUnmanagedContentPreservation() {
|
|
44532
|
+
this.preservesUnmanagedContent = true;
|
|
44533
|
+
}
|
|
44534
|
+
isPreservingUnmanagedContent() {
|
|
44535
|
+
return this.preservesUnmanagedContent;
|
|
44536
|
+
}
|
|
44537
|
+
composeWrittenContent({ existingContent, generatedContent }) {
|
|
44538
|
+
if (!this.preservesUnmanagedContent) return generatedContent;
|
|
44539
|
+
return spliceRuleManagedBlock({
|
|
44540
|
+
existingContent,
|
|
44541
|
+
generatedContent
|
|
44542
|
+
});
|
|
44543
|
+
}
|
|
44544
|
+
keepsContentOnRemoval() {
|
|
44545
|
+
return this.preservesUnmanagedContent;
|
|
44546
|
+
}
|
|
44547
|
+
/**
|
|
44548
|
+
* Under `preserveUnmanagedRuleContent`, removing a root rule file takes out
|
|
44549
|
+
* only the fenced block and keeps the hand-written rest; a file with nothing
|
|
44550
|
+
* else left is deleted. A file without a fence is not rulesync's any more —
|
|
44551
|
+
* the hand-written rest of an earlier removal, or a file written before the
|
|
44552
|
+
* option was on — so it is left in place.
|
|
44553
|
+
*/
|
|
44554
|
+
composeContentAfterRemoval({ existingContent }) {
|
|
44555
|
+
if (!this.preservesUnmanagedContent) return { action: "delete" };
|
|
44556
|
+
const rest = removeRuleManagedBlock(existingContent);
|
|
44557
|
+
if (rest === void 0) return { action: "keep" };
|
|
44558
|
+
if (rest.trim() === "") return { action: "delete" };
|
|
44559
|
+
return {
|
|
44560
|
+
action: "rewrite",
|
|
44561
|
+
content: rest
|
|
44562
|
+
};
|
|
44563
|
+
}
|
|
43111
44564
|
static getSettablePaths(_options = {}) {
|
|
43112
44565
|
throw new Error("Please implement this method in the subclass.");
|
|
43113
44566
|
}
|
|
@@ -53192,6 +54645,23 @@ const resolveBooleanRulesOption = ({ options, key }) => {
|
|
|
53192
54645
|
if (!parsed.success) throw new Error(`Invalid options for rules feature: ${parsed.error.message}. \`${key}\` must be a boolean.`);
|
|
53193
54646
|
return parsed.data[key] ?? true;
|
|
53194
54647
|
};
|
|
54648
|
+
/**
|
|
54649
|
+
* Resolve the `include` rules option: the names of the rules this target
|
|
54650
|
+
* receives, or `undefined` when the option is unset (every rule is eligible).
|
|
54651
|
+
*/
|
|
54652
|
+
const resolveRuleIncludeOption = (options) => {
|
|
54653
|
+
if (!options) return void 0;
|
|
54654
|
+
const parsed = z.looseObject({ include: z.optional(z.array(z.string())) }).safeParse(options);
|
|
54655
|
+
if (!parsed.success) throw new Error(`Invalid options for rules feature: ${parsed.error.message}. \`include\` must be an array of rule names.`);
|
|
54656
|
+
return parsed.data.include;
|
|
54657
|
+
};
|
|
54658
|
+
/**
|
|
54659
|
+
* The name the `include` rules option selects a rule by: its path under
|
|
54660
|
+
* `rules/` (or `rules/.curated/`) without the `.md` extension, normalized the
|
|
54661
|
+
* same way as `sources[].rules`. A rule at the top of the directory is matched
|
|
54662
|
+
* by its file name alone, e.g. `git-safety` for `git-safety.md`.
|
|
54663
|
+
*/
|
|
54664
|
+
const getRuleSelectionName = (rule) => normalizeRuleFilterName(toPosixPath(rule.getRelativeFilePath()));
|
|
53195
54665
|
const allToolTargetKeys$1 = [...toolRuleFactories.keys()];
|
|
53196
54666
|
const rulesProcessorToolTargets = allToolTargetKeys$1.filter((target) => {
|
|
53197
54667
|
return toolRuleFactories.get(target)?.meta.supportsProject !== false;
|
|
@@ -53234,6 +54704,24 @@ const findFilesWithFallback = async (primaryFilePaths, alternativeRoots, buildAl
|
|
|
53234
54704
|
* delete generated files it can no longer regenerate and report success.
|
|
53235
54705
|
*/
|
|
53236
54706
|
const rootRelativeGlob = (...segments) => posix.join(...segments.filter((segment) => segment !== void 0).map(toPosixPath));
|
|
54707
|
+
/**
|
|
54708
|
+
* Keep only the fenced part of a rule a `preserveUnmanagedRuleContent` run
|
|
54709
|
+
* wrote, so `import` does not copy hand-written content outside the fence into
|
|
54710
|
+
* the rulesync source, where the next `generate` would write it a second time
|
|
54711
|
+
* inside the fence. A rule without a complete fence is returned unchanged.
|
|
54712
|
+
*/
|
|
54713
|
+
const extractFencedRule = (rulesyncRule) => {
|
|
54714
|
+
const fenced = extractRuleManagedBlock(rulesyncRule.getBody());
|
|
54715
|
+
if (fenced === void 0) return rulesyncRule;
|
|
54716
|
+
return new RulesyncRule({
|
|
54717
|
+
outputRoot: rulesyncRule.getOutputRoot(),
|
|
54718
|
+
relativeDirPath: rulesyncRule.getRelativeDirPath(),
|
|
54719
|
+
relativeFilePath: rulesyncRule.getRelativeFilePath(),
|
|
54720
|
+
frontmatter: rulesyncRule.getFrontmatter(),
|
|
54721
|
+
body: fenced.trim(),
|
|
54722
|
+
validate: false
|
|
54723
|
+
});
|
|
54724
|
+
};
|
|
53237
54725
|
const isRootRule = (rule) => Boolean(rule.getFrontmatter().root || rule.getFrontmatter().localRoot);
|
|
53238
54726
|
var RulesProcessor = class extends FeatureProcessor {
|
|
53239
54727
|
toolTarget;
|
|
@@ -53250,7 +54738,13 @@ var RulesProcessor = class extends FeatureProcessor {
|
|
|
53250
54738
|
skills;
|
|
53251
54739
|
featureOptions;
|
|
53252
54740
|
deleteOrphans;
|
|
53253
|
-
|
|
54741
|
+
preserveUnmanagedContent;
|
|
54742
|
+
/**
|
|
54743
|
+
* Whether the last `loadRulesyncFiles` call's `include` option left out a
|
|
54744
|
+
* rule that targets this tool.
|
|
54745
|
+
*/
|
|
54746
|
+
includeNarrowedSelection = false;
|
|
54747
|
+
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
54748
|
super({
|
|
53255
54749
|
outputRoot,
|
|
53256
54750
|
inputRoots,
|
|
@@ -53270,6 +54764,7 @@ var RulesProcessor = class extends FeatureProcessor {
|
|
|
53270
54764
|
this.skills = skills;
|
|
53271
54765
|
this.featureOptions = featureOptions;
|
|
53272
54766
|
this.deleteOrphans = deleteOrphans;
|
|
54767
|
+
this.preserveUnmanagedContent = preserveUnmanagedContent;
|
|
53273
54768
|
}
|
|
53274
54769
|
async convertRulesyncFilesToToolFiles(rulesyncFiles) {
|
|
53275
54770
|
const rulesyncRules = rulesyncFiles.filter((file) => file instanceof RulesyncRule);
|
|
@@ -53313,6 +54808,9 @@ var RulesProcessor = class extends FeatureProcessor {
|
|
|
53313
54808
|
});
|
|
53314
54809
|
extraFiles.push(...await this.buildLanguageSettingsFiles());
|
|
53315
54810
|
const outputFiles = [...toolRules, ...extraFiles];
|
|
54811
|
+
if (this.preserveUnmanagedContent) {
|
|
54812
|
+
for (const file of outputFiles) if (file instanceof ToolRule && file.isRoot()) file.enableUnmanagedContentPreservation();
|
|
54813
|
+
}
|
|
53316
54814
|
this.warnForOutputPathCollisions({
|
|
53317
54815
|
outputFiles,
|
|
53318
54816
|
convertedRules
|
|
@@ -53747,10 +55245,10 @@ As this project's AI coding tool, you must follow the additional conventions bel
|
|
|
53747
55245
|
async convertToolFilesToRulesyncFiles(toolFiles) {
|
|
53748
55246
|
const toolRules = toolFiles.filter((file) => file instanceof ToolRule);
|
|
53749
55247
|
const rulesyncRules = toolRules.map((toolRule) => {
|
|
53750
|
-
if (toolRule.isLocalRoot()) return toolRule.toLocalRootRulesyncRule({ targets: [this.toolTarget] });
|
|
55248
|
+
if (toolRule.isLocalRoot()) return this.withoutUnmanagedContent(toolRule.toLocalRootRulesyncRule({ targets: [this.toolTarget] }));
|
|
53751
55249
|
return this.withoutLanguageBlock({
|
|
53752
55250
|
toolRule,
|
|
53753
|
-
rulesyncRule: toolRule.toRulesyncRule()
|
|
55251
|
+
rulesyncRule: this.withoutUnmanagedContent(toolRule.toRulesyncRule())
|
|
53754
55252
|
});
|
|
53755
55253
|
});
|
|
53756
55254
|
const claimedBy = /* @__PURE__ */ new Map();
|
|
@@ -53767,6 +55265,13 @@ As this project's AI coding tool, you must follow the additional conventions bel
|
|
|
53767
55265
|
return rulesyncRules;
|
|
53768
55266
|
}
|
|
53769
55267
|
/**
|
|
55268
|
+
* See {@link extractFencedRule}. Only under `preserveUnmanagedRuleContent`:
|
|
55269
|
+
* without it a file that merely quotes the markers is imported whole.
|
|
55270
|
+
*/
|
|
55271
|
+
withoutUnmanagedContent(rulesyncRule) {
|
|
55272
|
+
return this.preserveUnmanagedContent ? extractFencedRule(rulesyncRule) : rulesyncRule;
|
|
55273
|
+
}
|
|
55274
|
+
/**
|
|
53770
55275
|
* Drop the language block a previous `generate` appended, so that importing
|
|
53771
55276
|
* a generated root file and generating again yields one block, not two.
|
|
53772
55277
|
* Every imported rule is checked, not just root ones: Cursor and the
|
|
@@ -53888,10 +55393,17 @@ As this project's AI coding tool, you must follow the additional conventions bel
|
|
|
53888
55393
|
* copy (case-insensitive, matching the intra-root collision handling).
|
|
53889
55394
|
*/
|
|
53890
55395
|
async loadRulesyncFiles() {
|
|
53891
|
-
const rulesyncRules = await this.loadMergedRulesyncRules();
|
|
53892
55396
|
const factory = this.getFactory(this.toolTarget);
|
|
55397
|
+
const mergedRules = await this.loadMergedRulesyncRules();
|
|
55398
|
+
const rulesyncRules = this.selectIncludedRules({
|
|
55399
|
+
rules: mergedRules,
|
|
55400
|
+
factory
|
|
55401
|
+
});
|
|
55402
|
+
const isTargeted = (rule) => factory.class.isTargetedByRulesyncRule(rule);
|
|
55403
|
+
this.includeNarrowedSelection = rulesyncRules.filter(isTargeted).length < mergedRules.filter(isTargeted).length;
|
|
53893
55404
|
const targetedRootRules = rulesyncRules.filter((rule) => rule.getFrontmatter().root).filter((rule) => factory.class.isTargetedByRulesyncRule(rule));
|
|
53894
|
-
|
|
55405
|
+
const rootRuleLeftOutByInclude = mergedRules.some((rule) => rule.getFrontmatter().root && factory.class.isTargetedByRulesyncRule(rule) && !rulesyncRules.includes(rule));
|
|
55406
|
+
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
55407
|
const targetedLocalRootRules = rulesyncRules.filter((rule) => rule.getFrontmatter().localRoot).filter((rule) => factory.class.isTargetedByRulesyncRule(rule));
|
|
53896
55408
|
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
55409
|
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 +55421,36 @@ As this project's AI coding tool, you must follow the additional conventions bel
|
|
|
53909
55421
|
return [...targetedRootRules, ...nonRootRules];
|
|
53910
55422
|
}
|
|
53911
55423
|
/**
|
|
55424
|
+
* Whether the target's `include` rules option left out at least one rule
|
|
55425
|
+
* that targets this tool in the last `loadRulesyncFiles` call. `["*"]`, or a
|
|
55426
|
+
* list naming every rule the tool would receive, narrows nothing.
|
|
55427
|
+
*/
|
|
55428
|
+
didIncludeNarrowSelection() {
|
|
55429
|
+
return this.includeNarrowedSelection;
|
|
55430
|
+
}
|
|
55431
|
+
/**
|
|
55432
|
+
* Narrow the rules to the ones the target's `include` rules option names.
|
|
55433
|
+
* The option is a pure narrowing filter: a named rule still has to target
|
|
55434
|
+
* this tool through its `targets` frontmatter, which is checked afterwards
|
|
55435
|
+
* as for any other rule. A name that matches no rule (local or curated) is
|
|
55436
|
+
* an error, so a renamed or removed rule does not silently disappear from
|
|
55437
|
+
* the target. `["*"]` selects every rule, as in `sources[].rules`.
|
|
55438
|
+
*/
|
|
55439
|
+
selectIncludedRules({ rules, factory, warn = true }) {
|
|
55440
|
+
const include = resolveRuleIncludeOption(this.featureOptions);
|
|
55441
|
+
if (include === void 0) return rules;
|
|
55442
|
+
const names = [...new Set(include.map(normalizeRuleFilterName))];
|
|
55443
|
+
if (isWildcardSelection(names)) return rules;
|
|
55444
|
+
const availableNames = new Set(rules.map(getRuleSelectionName));
|
|
55445
|
+
const unknownNames = names.filter((name) => !availableNames.has(name));
|
|
55446
|
+
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.`);
|
|
55447
|
+
const selectedNames = new Set(names);
|
|
55448
|
+
const selectedRules = rules.filter((rule) => selectedNames.has(getRuleSelectionName(rule)));
|
|
55449
|
+
const excludedByFrontmatter = selectedRules.filter((rule) => !factory.class.isTargetedByRulesyncRule(rule));
|
|
55450
|
+
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)}`);
|
|
55451
|
+
return selectedRules;
|
|
55452
|
+
}
|
|
55453
|
+
/**
|
|
53912
55454
|
* Align the rules with each other through the tool's `alignRulesyncRules`
|
|
53913
55455
|
* hook, printing its warnings unless `warn` is off.
|
|
53914
55456
|
*/
|
|
@@ -53959,7 +55501,16 @@ As this project's AI coding tool, you must follow the additional conventions bel
|
|
|
53959
55501
|
async warnForFoldImportDuplicationRisk() {
|
|
53960
55502
|
const factory = this.getFactory(this.toolTarget);
|
|
53961
55503
|
if (factory.meta.collisionPolicy !== "fold") return;
|
|
53962
|
-
const
|
|
55504
|
+
const loadedRules = await this.loadMergedRulesyncRules();
|
|
55505
|
+
let includedRules = loadedRules;
|
|
55506
|
+
try {
|
|
55507
|
+
includedRules = this.selectIncludedRules({
|
|
55508
|
+
rules: loadedRules,
|
|
55509
|
+
factory,
|
|
55510
|
+
warn: false
|
|
55511
|
+
});
|
|
55512
|
+
} catch {}
|
|
55513
|
+
const targetedRules = this.alignRulesyncRules(includedRules, { warn: false }).filter((rule) => factory.class.isTargetedByRulesyncRule(rule));
|
|
53963
55514
|
let includeLocalRoot = !this.global;
|
|
53964
55515
|
try {
|
|
53965
55516
|
includeLocalRoot &&= resolveBooleanRulesOption({
|
|
@@ -54024,6 +55575,14 @@ As this project's AI coding tool, you must follow the additional conventions bel
|
|
|
54024
55575
|
* Load tool-specific rule configurations and parse them into ToolRule instances
|
|
54025
55576
|
*/
|
|
54026
55577
|
async loadToolFiles({ forDeletion = false } = {}) {
|
|
55578
|
+
const toolFiles = await this.loadToolFilesUnmarked({ forDeletion });
|
|
55579
|
+
if (forDeletion && this.preserveUnmanagedContent) {
|
|
55580
|
+
const { localRootFileName } = this.getFactory(this.toolTarget).meta;
|
|
55581
|
+
for (const file of toolFiles) if (file instanceof ToolRule && (file.isRoot() || file.isLocalRoot() || localRootFileName !== void 0 && file.getRelativeFilePath() === localRootFileName)) file.enableUnmanagedContentPreservation();
|
|
55582
|
+
}
|
|
55583
|
+
return toolFiles;
|
|
55584
|
+
}
|
|
55585
|
+
async loadToolFilesUnmarked({ forDeletion }) {
|
|
54027
55586
|
try {
|
|
54028
55587
|
const factory = this.getFactory(this.toolTarget);
|
|
54029
55588
|
const settablePaths = factory.class.getSettablePaths({ global: this.global });
|
|
@@ -57623,7 +59182,10 @@ function anchorDotPaths({ command, projectDirVar }) {
|
|
|
57623
59182
|
* first word, so interpreter-prefixed commands (`python3 "$VAR/x.py"`,
|
|
57624
59183
|
* `node $VAR/x.js`) do not leak a tool-specific variable into targets that do
|
|
57625
59184
|
* not define it. The recognized forms, each followed by `/`, are `"$VAR"`,
|
|
57626
|
-
* `"${VAR}"`, `$VAR` and `${VAR}
|
|
59185
|
+
* `"${VAR}"`, `$VAR` and `${VAR}`, plus the fail-closed `${VAR:?}` in either
|
|
59186
|
+
* spelling when `acceptsFailClosedForm` is set (for a tool that writes that
|
|
59187
|
+
* form itself; elsewhere a hand-written `${VAR:?}` is left as written, so it
|
|
59188
|
+
* keeps failing closed):
|
|
57627
59189
|
*
|
|
57628
59190
|
* - a quote around the whole path is kept, so a path containing spaces stays
|
|
57629
59191
|
* one word (`"$VAR/my hook.sh"` becomes `"./my hook.sh"`);
|
|
@@ -57648,9 +59210,9 @@ function anchorDotPaths({ command, projectDirVar }) {
|
|
|
57648
59210
|
* later words are not converted (see `convertsLaterWords`) or that starts
|
|
57649
59211
|
* with another variable — every occurrence after the first word.
|
|
57650
59212
|
*/
|
|
57651
|
-
function importProjectDirVariable({ command, projectDirVar, firstWordOnly = false }) {
|
|
59213
|
+
function importProjectDirVariable({ command, projectDirVar, firstWordOnly = false, acceptsFailClosedForm = false }) {
|
|
57652
59214
|
const escapedName = escapeRegExp(projectDirVar.replace(/^\$/, ""));
|
|
57653
|
-
const variable = `\\$(?:${escapedName}|\\{${escapedName}\\})`;
|
|
59215
|
+
const variable = `\\$(?:${escapedName}|\\{${escapedName}${acceptsFailClosedForm ? "(?::\\?)?" : ""}\\})`;
|
|
57654
59216
|
const pattern = new RegExp(`(?:"${variable}"/(["']?)|${variable}/)`, "g");
|
|
57655
59217
|
const leading = command.length - command.trimStart().length;
|
|
57656
59218
|
const inFirstWord = (offset) => offset === leading || offset === leading + 1 && command.charAt(leading) === "\"";
|
|
@@ -57761,6 +59323,15 @@ function groupDefinitionsByMatcher({ definitions, eventName, converterConfig, wa
|
|
|
57761
59323
|
}
|
|
57762
59324
|
return byMatcher;
|
|
57763
59325
|
}
|
|
59326
|
+
/**
|
|
59327
|
+
* The project directory variable as generate writes it into a shell command:
|
|
59328
|
+
* `$DEVIN_PLUGIN_ROOT` -> `${DEVIN_PLUGIN_ROOT:?}` for a tool that opts into
|
|
59329
|
+
* {@link ToolHooksConverterConfig.failsClosedOnEmptyProjectDirVar}.
|
|
59330
|
+
*/
|
|
59331
|
+
function emittedProjectDirVar(converterConfig) {
|
|
59332
|
+
const { projectDirVar } = converterConfig;
|
|
59333
|
+
return converterConfig.failsClosedOnEmptyProjectDirVar ? `\${${projectDirVar.replace(/^\$/, "")}:?}` : projectDirVar;
|
|
59334
|
+
}
|
|
57764
59335
|
/** `$CLAUDE_PROJECT_DIR` -> `${CLAUDE_PROJECT_DIR}`, the form the tool substitutes. */
|
|
57765
59336
|
function bracePlaceholder(projectDirVar) {
|
|
57766
59337
|
return `\${${projectDirVar.replace(/^\$/, "")}}`;
|
|
@@ -57808,12 +59379,12 @@ function applyCommandPrefix({ def, converterConfig }) {
|
|
|
57808
59379
|
converterConfig
|
|
57809
59380
|
}) ? command : anchorDotPaths({
|
|
57810
59381
|
command,
|
|
57811
|
-
projectDirVar: converterConfig
|
|
59382
|
+
projectDirVar: emittedProjectDirVar(converterConfig)
|
|
57812
59383
|
});
|
|
57813
59384
|
if (!shouldPrefix || typeof trimmedCommand !== "string") return typeof def.command === "string" ? anchorInline(def.command) : def.command;
|
|
57814
59385
|
const relativeCommand = trimmedCommand.replace(/^(["'])\.\//, "$1").replace(/^\.\//, "");
|
|
57815
59386
|
if (isExecForm) return `${bracePlaceholder(converterConfig.projectDirVar)}/${stripSurroundingQuotes(relativeCommand)}`;
|
|
57816
|
-
return anchorInline(`"${converterConfig
|
|
59387
|
+
return anchorInline(`"${emittedProjectDirVar(converterConfig)}"/${relativeCommand}`);
|
|
57817
59388
|
}
|
|
57818
59389
|
/** Whether a field restricted to some events applies on this one. */
|
|
57819
59390
|
function isEventApplicable({ events, eventName }) {
|
|
@@ -58463,7 +60034,8 @@ function stripCommandPrefix({ command, args, shell, converterConfig, warn }) {
|
|
|
58463
60034
|
}) || !runsInPosixShell({
|
|
58464
60035
|
shell,
|
|
58465
60036
|
converterConfig
|
|
58466
|
-
})
|
|
60037
|
+
}),
|
|
60038
|
+
acceptsFailClosedForm: converterConfig.failsClosedOnEmptyProjectDirVar ?? false
|
|
58467
60039
|
});
|
|
58468
60040
|
stripped = result.command;
|
|
58469
60041
|
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 +64676,9 @@ var DevinHooks = class extends ToolHooks {
|
|
|
63104
64676
|
* anchored to the plugin install directory rather than run against the
|
|
63105
64677
|
* consumer's workspace. Devin CLI v3000.5.20+ sets `DEVIN_PLUGIN_ROOT` in the
|
|
63106
64678
|
* environment of hooks contributed by a plugin, and runs `command` as a shell
|
|
63107
|
-
* command, so the quoted `"$DEVIN_PLUGIN_ROOT"/...` form expands there.
|
|
64679
|
+
* command, so the quoted `"${DEVIN_PLUGIN_ROOT:?}"/...` form expands there.
|
|
64680
|
+
* The `:?` makes an older CLI, which leaves the variable empty, stop the hook
|
|
64681
|
+
* with an error rather than run `/scripts/...` from the filesystem root. Bare
|
|
63108
64682
|
* commands such as `npx prettier --write` are left intact.
|
|
63109
64683
|
*
|
|
63110
64684
|
* `DEVIN_PLUGIN_ROOT` is chosen over the shorter `PLUGIN_ROOT` (v3000.11.92+)
|
|
@@ -63118,6 +64692,7 @@ var DevinHooks = class extends ToolHooks {
|
|
|
63118
64692
|
const DEVIN_PLUGIN_CONVERTER_CONFIG = {
|
|
63119
64693
|
...DEVIN_CONVERTER_CONFIG,
|
|
63120
64694
|
projectDirVar: "$DEVIN_PLUGIN_ROOT",
|
|
64695
|
+
failsClosedOnEmptyProjectDirVar: true,
|
|
63121
64696
|
prefixDotRelativeCommandsOnly: true,
|
|
63122
64697
|
importedProjectDirVarAliases: ["$PLUGIN_ROOT", "$CLAUDE_PLUGIN_ROOT"]
|
|
63123
64698
|
};
|
|
@@ -63125,7 +64700,7 @@ const DEVIN_PLUGIN_CONVERTER_CONFIG = {
|
|
|
63125
64700
|
* Hooks inside a Devin plugin bundle (`<plugin>/hooks.json`). The file is the
|
|
63126
64701
|
* same bare event map as `.devin/hooks.v1.json` (no `hooks` wrapper key), as
|
|
63127
64702
|
* in Cognition's plugin templates. Unlike the `devin` target, `./`-relative
|
|
63128
|
-
* commands are anchored to `$DEVIN_PLUGIN_ROOT` (see
|
|
64703
|
+
* commands are anchored to `${DEVIN_PLUGIN_ROOT:?}` (see
|
|
63129
64704
|
* `DEVIN_PLUGIN_CONVERTER_CONFIG`).
|
|
63130
64705
|
*
|
|
63131
64706
|
* @see https://docs.devin.ai/cli/extensibility/plugins/overview
|
|
@@ -64508,7 +66083,9 @@ const BLOCKING_HOOKS = new Set(Object.keys(NAMED_HOOK_MATCHER_SUBJECTS).filter((
|
|
|
64508
66083
|
* Shell echoed them; a `preToolUse` command's are read, 1 MiB each kept (more
|
|
64509
66084
|
* stdout denies; on the Bun Shell fallback the whole output is buffered before
|
|
64510
66085
|
* that check), and a `sessionStart` command's stdout is read the same way while
|
|
64511
|
-
* its stderr goes to the host's (after the command, on Bun Shell)
|
|
66086
|
+
* its stderr goes to the host's (after the command, on Bun Shell); an OpenCode
|
|
66087
|
+
* 2.x `postToolUse` command is the other way round, its stderr read and its
|
|
66088
|
+
* stdout going to the host's. Output
|
|
64512
66089
|
* pipes a background process keeps open are read for 1 s after the command
|
|
64513
66090
|
* exits; what arrived by then is kept, and the reads are then cancelled, as
|
|
64514
66091
|
* they are at a timeout. The OpenCode 1.x-style `event` hooks (`inProcess`)
|
|
@@ -64657,28 +66234,37 @@ function buildRunHelperLinesFor(cwdExpression) {
|
|
|
64657
66234
|
" if (inProcess || !(await __rulesyncCanExec)) {",
|
|
64658
66235
|
` const run = Bun.$\`echo \${input} | \${{ raw: command }}\`.cwd(${cwdExpression}).nothrow();`,
|
|
64659
66236
|
" // A sessionStart command's stderr reaches the host when it ends, even after its timeout.",
|
|
64660
|
-
"
|
|
66237
|
+
" // A postToolUse command's (`echo: \"stdout\"`) stdout and stderr reach it when it ends, too.",
|
|
66238
|
+
" const finished = echo === true ? run : run.quiet().then((done) => {",
|
|
66239
|
+
" if (echo === \"stdout\") process.stdout.write(done.stdout);",
|
|
66240
|
+
" if (echo) process.stderr.write(done.stderr);",
|
|
66241
|
+
" return done;",
|
|
66242
|
+
" });",
|
|
64661
66243
|
" const result = await Promise.race([finished, timeout()]).finally(() => clearTimeout(timer));",
|
|
64662
66244
|
" if (!result || echo === true) return result && { exitCode: result.exitCode };",
|
|
64663
66245
|
" const { exitCode, stdout, stderr } = result;",
|
|
64664
66246
|
" return { exitCode, stdout: stdout.toString(), stderr: stderr.toString(), overflow: stdout.length > 1048576 };",
|
|
64665
66247
|
" }",
|
|
64666
|
-
" // An ordinary command writes to the host's stdout and stderr; a preToolUse one is read,
|
|
64667
|
-
" // a sessionStart one (`echo: \"stderr\"`) has its stdout read
|
|
64668
|
-
|
|
64669
|
-
|
|
64670
|
-
" const
|
|
66248
|
+
" // An ordinary command writes to the host's stdout and stderr; a preToolUse one is read,",
|
|
66249
|
+
" // a sessionStart one (`echo: \"stderr\"`) has its stdout read, and a postToolUse one",
|
|
66250
|
+
" // (`echo: \"stdout\"`) its stderr.",
|
|
66251
|
+
` const proc = ${spawn("\"export BUN_BE_BUN=\\n\" + command", "new TextEncoder().encode(input + \"\\n\")", "echo === true || echo === \"stdout\" ? \"inherit\" : \"pipe\"", "echo === true || echo === \"stderr\" ? \"inherit\" : \"pipe\"")};`,
|
|
66252
|
+
" const stdout = echo === true || echo === \"stdout\" ? undefined : __rulesyncRead(proc.stdout);",
|
|
66253
|
+
" const stderr = echo === true || echo === \"stderr\" ? undefined : __rulesyncRead(proc.stderr);",
|
|
64671
66254
|
" const exitCode = await Promise.race([proc.exited, timeout()]).finally(() => clearTimeout(timer));",
|
|
64672
66255
|
" if (exitCode === null) {",
|
|
64673
66256
|
" stdout?.stop(), stderr?.stop();",
|
|
66257
|
+
" // A postToolUse command's stderr is read, so what it wrote before the timeout reaches the host here.",
|
|
66258
|
+
" if (echo === \"stdout\") process.stderr.write(stderr.text());",
|
|
64674
66259
|
" if (process.platform === \"win32\") __rulesyncKillWindowsTree(proc);",
|
|
64675
66260
|
" else __rulesyncKillTree(proc);",
|
|
64676
66261
|
" return null;",
|
|
64677
66262
|
" }",
|
|
64678
66263
|
" if (echo === true) return { exitCode };",
|
|
64679
|
-
" await Promise.race([Promise.all([stdout
|
|
64680
|
-
" stdout
|
|
64681
|
-
"
|
|
66264
|
+
" await Promise.race([Promise.all([stdout?.done, stderr?.done]), Bun.sleep(1000)]);",
|
|
66265
|
+
" stdout?.stop(), stderr?.stop();",
|
|
66266
|
+
" if (echo === \"stdout\") process.stderr.write(stderr.text());",
|
|
66267
|
+
" return { exitCode, stdout: stdout?.text() ?? \"\", stderr: stderr?.text() ?? \"\", overflow: stdout?.overflow() ?? false };",
|
|
64682
66268
|
"};",
|
|
64683
66269
|
"const __rulesyncRunHook = async ({ label, command, input, blocking, seconds, inProcess = false, context = false }) => {",
|
|
64684
66270
|
" let result;",
|
|
@@ -66207,6 +67793,92 @@ function wrapInConditions(handler, statement, indent) {
|
|
|
66207
67793
|
`${indent}}`
|
|
66208
67794
|
];
|
|
66209
67795
|
}
|
|
67796
|
+
/**
|
|
67797
|
+
* Helpers the generated plugin defines when a `postToolUse` handler is present,
|
|
67798
|
+
* giving it Claude Code's `PostToolUse` exit-code contract: the tool already
|
|
67799
|
+
* ran, so nothing is blocked, but a command that exits with code 2 has its
|
|
67800
|
+
* stderr (sanitized, see `hook-block-reason.ts`) shown to the model with the
|
|
67801
|
+
* tool result. Any other non-zero exit, a timeout or a command that cannot be
|
|
67802
|
+
* run is only logged, as before. The command's stdout still streams to the
|
|
67803
|
+
* host's; its stderr is read (1 MiB kept) and written to the host's by
|
|
67804
|
+
* `__rulesyncRunCommand` when the command ends or times out, so it stays
|
|
67805
|
+
* visible there too.
|
|
67806
|
+
*
|
|
67807
|
+
* OpenCode 2.x lets an `execute.after` hook replace a completed call's
|
|
67808
|
+
* `event.result` (`{ output?, content?, metadata? }`), which the host
|
|
67809
|
+
* normalizes again before the model sees it; its own tool-repair plugin adds a
|
|
67810
|
+
* note the same way. The text goes into both fields, since the model reads the
|
|
67811
|
+
* result from either: `output` when it is a string, and `content` whether it
|
|
67812
|
+
* is a string or an array of parts. A missing or empty `content` stands for
|
|
67813
|
+
* the output upstream, so that output is kept ahead of the text. A failure
|
|
67814
|
+
* here is logged: a hook that throws would fail the call.
|
|
67815
|
+
*
|
|
67816
|
+
* `postToolUseFailure` stays observe-only. Claude Code shows its exit-2 stderr
|
|
67817
|
+
* to the model too, but a failed call's `event.error` is the host's typed tool
|
|
67818
|
+
* error (`ToolFailure` / `Tool.Error`), which the host yields after the hook;
|
|
67819
|
+
* a plugin cannot build one, and anything else in its place would turn the
|
|
67820
|
+
* call's failure into a defect.
|
|
67821
|
+
*
|
|
67822
|
+
* @see https://github.com/anomalyco/opencode/blob/v2.4.3/packages/core/src/tool.ts
|
|
67823
|
+
* @see https://github.com/anomalyco/opencode/blob/v2.4.3/packages/plugin/src/promise/adapter.ts
|
|
67824
|
+
* @see https://code.claude.com/docs/en/hooks
|
|
67825
|
+
*/
|
|
67826
|
+
const POST_TOOL_USE_HELPER_LINES = [
|
|
67827
|
+
"const __rulesyncRunPostToolUseHook = async ({ command, input, seconds }) => {",
|
|
67828
|
+
" let result;",
|
|
67829
|
+
" try {",
|
|
67830
|
+
" result = await __rulesyncRunCommand({ command, input, seconds, echo: \"stdout\" });",
|
|
67831
|
+
" } catch (error) {",
|
|
67832
|
+
" console.error(\"[rulesync-hooks] postToolUse hook failed:\", error);",
|
|
67833
|
+
" return undefined;",
|
|
67834
|
+
" }",
|
|
67835
|
+
" if (result === null) {",
|
|
67836
|
+
" console.error(\"[rulesync-hooks] postToolUse hook timed out after \" + seconds + \"s\");",
|
|
67837
|
+
" return undefined;",
|
|
67838
|
+
" }",
|
|
67839
|
+
" const stderr = String(result.stderr ?? \"\");",
|
|
67840
|
+
" if (result.exitCode === 0) return undefined;",
|
|
67841
|
+
" if (result.exitCode === 2) return sanitizeBlockReason(stderr) || \"postToolUse hook exited with code 2.\";",
|
|
67842
|
+
" console.error(\"[rulesync-hooks] postToolUse hook exited with code \" + result.exitCode);",
|
|
67843
|
+
" return undefined;",
|
|
67844
|
+
"};",
|
|
67845
|
+
"// Like OpenCode's own `stringify`: a value JSON cannot hold (a BigInt, a cycle) falls back to `String`.",
|
|
67846
|
+
"const __rulesyncStringify = (value) => {",
|
|
67847
|
+
" try {",
|
|
67848
|
+
" return JSON.stringify(value) ?? String(value);",
|
|
67849
|
+
" } catch {",
|
|
67850
|
+
" return String(value);",
|
|
67851
|
+
" }",
|
|
67852
|
+
"};",
|
|
67853
|
+
"const __rulesyncAppendToolResult = (event, reason) => {",
|
|
67854
|
+
" if (!reason || event.status !== \"completed\") return;",
|
|
67855
|
+
" try {",
|
|
67856
|
+
" const text = \"PostToolUse hook feedback:\\n\" + reason;",
|
|
67857
|
+
" const result = event.result ?? {};",
|
|
67858
|
+
" const next = { ...result };",
|
|
67859
|
+
" if (typeof result.output === \"string\") next.output = result.output + \"\\n\\n\" + text;",
|
|
67860
|
+
" if (typeof result.content === \"string\") next.content = result.content + \"\\n\\n\" + text;",
|
|
67861
|
+
" else if (Array.isArray(result.content) && result.content.length > 0) next.content = [...result.content, { type: \"text\", text }];",
|
|
67862
|
+
" else {",
|
|
67863
|
+
" const output = result.output;",
|
|
67864
|
+
" const kept = output === undefined ? \"\" : typeof output === \"string\" ? output : __rulesyncStringify(output);",
|
|
67865
|
+
" next.content = [...(kept ? [{ type: \"text\", text: kept }] : []), { type: \"text\", text }];",
|
|
67866
|
+
" }",
|
|
67867
|
+
" event.result = next;",
|
|
67868
|
+
" } catch (error) {",
|
|
67869
|
+
" console.error(\"[rulesync-hooks] could not add postToolUse feedback to the tool result:\", error);",
|
|
67870
|
+
" }",
|
|
67871
|
+
"};"
|
|
67872
|
+
];
|
|
67873
|
+
/** The statement that runs a `postToolUse` handler and passes its feedback on. */
|
|
67874
|
+
function buildPostToolUseRunStatement(handler) {
|
|
67875
|
+
const { command, input } = commandAndInputOf(handler);
|
|
67876
|
+
return `__rulesyncAppendToolResult(event, await __rulesyncRunPostToolUseHook({ command: ${command}, input: ${input}, seconds: ${handler.timeout} }));`;
|
|
67877
|
+
}
|
|
67878
|
+
/** Whether a handler is a `postToolUse` one, which reports back to the model. */
|
|
67879
|
+
function isPostToolUseHandler(handler) {
|
|
67880
|
+
return handler.payload?.name === "PostToolUse";
|
|
67881
|
+
}
|
|
66210
67882
|
/** Emit one `ctx.<domain>.hook(name, ...)` registration. */
|
|
66211
67883
|
function buildHookRegistrationLines(hookPoint, handlers) {
|
|
66212
67884
|
const separator = hookPoint.indexOf(":");
|
|
@@ -66219,7 +67891,10 @@ function buildHookRegistrationLines(hookPoint, handlers) {
|
|
|
66219
67891
|
handlers,
|
|
66220
67892
|
cwdExpression: "directory"
|
|
66221
67893
|
}).map((line) => ` ${line}`));
|
|
66222
|
-
for (const handler of handlers)
|
|
67894
|
+
for (const handler of handlers) {
|
|
67895
|
+
const statement = isPostToolUseHandler(handler) ? buildPostToolUseRunStatement(handler) : buildRunStatement(handler);
|
|
67896
|
+
lines.push(...wrapInConditions(handler, statement, " "));
|
|
67897
|
+
}
|
|
66223
67898
|
lines.push(" }),");
|
|
66224
67899
|
lines.push(");");
|
|
66225
67900
|
return lines;
|
|
@@ -66468,10 +68143,12 @@ function buildSetupBodyLines({ hookHandlers, eventHandlers, stopHandlers }) {
|
|
|
66468
68143
|
cwdExpression: "directory"
|
|
66469
68144
|
})
|
|
66470
68145
|
];
|
|
66471
|
-
|
|
68146
|
+
const usesPostToolUse = allHandlers.some(isPostToolUseHandler);
|
|
68147
|
+
if (stopHandlers.length > 0 || usesPostToolUse) {
|
|
66472
68148
|
if (!allHandlers.some((handler) => handler.payload?.name === "PreToolUse")) body.push("", ...buildBlockReasonSanitizerLines({ typed: false }));
|
|
66473
|
-
body.push("", ...STOP_HOOK_HELPER_LINES$1);
|
|
66474
68149
|
}
|
|
68150
|
+
if (stopHandlers.length > 0) body.push("", ...STOP_HOOK_HELPER_LINES$1);
|
|
68151
|
+
if (usesPostToolUse) body.push("", ...POST_TOOL_USE_HELPER_LINES);
|
|
66475
68152
|
if ([...hookHandlers.values()].some((handlers) => handlers.some((handler) => handler.matcher !== void 0))) body.push("", ...TOOL_MATCHER_HELPER_LINES);
|
|
66476
68153
|
const usesContext = [...eventHandlers.values()].some(usesSessionContext);
|
|
66477
68154
|
const registers = hookHandlers.size > 0 || usesContext || stopHandlers.length > 0;
|
|
@@ -75131,7 +76808,8 @@ var CodewhaleMcp = class CodewhaleMcp extends ToolMcp {
|
|
|
75131
76808
|
}
|
|
75132
76809
|
static async fromRulesyncMcp({ outputRoot = process.cwd(), rulesyncMcp, validate = true, global = false, logger }) {
|
|
75133
76810
|
const paths = this.getSettablePaths({ global });
|
|
75134
|
-
const
|
|
76811
|
+
const filePath = join(outputRoot, paths.relativeDirPath, paths.relativeFilePath);
|
|
76812
|
+
const existingContent = await readFileContentOrNull(filePath);
|
|
75135
76813
|
const json = existingContent === null ? {} : parseCodewhaleMcpConfig({
|
|
75136
76814
|
fileContent: existingContent,
|
|
75137
76815
|
relativePath: join(paths.relativeDirPath, paths.relativeFilePath)
|
|
@@ -75144,7 +76822,11 @@ var CodewhaleMcp = class CodewhaleMcp extends ToolMcp {
|
|
|
75144
76822
|
[serversKey]: mcpServers
|
|
75145
76823
|
};
|
|
75146
76824
|
const fileContent = JSON.stringify(codewhaleConfig, null, 2);
|
|
75147
|
-
if (!global &&
|
|
76825
|
+
if (!global && !fileContentsEquivalent({
|
|
76826
|
+
filePath,
|
|
76827
|
+
expected: fileContent,
|
|
76828
|
+
existing: existingContent
|
|
76829
|
+
})) 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
76830
|
return new CodewhaleMcp({
|
|
75149
76831
|
outputRoot,
|
|
75150
76832
|
relativeDirPath: paths.relativeDirPath,
|
|
@@ -75777,7 +77459,7 @@ var CodexcliMcp = class CodexcliMcp extends ToolMcp {
|
|
|
75777
77459
|
validate
|
|
75778
77460
|
});
|
|
75779
77461
|
}
|
|
75780
|
-
static async fromRulesyncMcp({ outputRoot = process.cwd(), rulesyncMcp, validate = true, global = false }) {
|
|
77462
|
+
static async fromRulesyncMcp({ outputRoot = process.cwd(), rulesyncMcp, validate = true, global = false, preserveUnowned = false }) {
|
|
75781
77463
|
const paths = this.getSettablePaths({ global });
|
|
75782
77464
|
const configTomlFilePath = join(outputRoot, paths.relativeDirPath, paths.relativeFilePath);
|
|
75783
77465
|
const configTomlFileContent = await readFileContentOrNull(configTomlFilePath) ?? "";
|
|
@@ -75788,7 +77470,7 @@ var CodexcliMcp = class CodexcliMcp extends ToolMcp {
|
|
|
75788
77470
|
throw new Error(`Failed to parse existing Codex CLI config at ${configTomlFilePath}: ${formatError(error)}`, { cause: error });
|
|
75789
77471
|
}
|
|
75790
77472
|
const strippedMcpServers = rulesyncMcp.getMcpServers();
|
|
75791
|
-
const
|
|
77473
|
+
const mcpServersWithCodexFields = Object.fromEntries(Object.entries(strippedMcpServers).map(([serverName, serverConfig]) => {
|
|
75792
77474
|
const rawServer = rulesyncMcp.getRawMcpServer(serverName);
|
|
75793
77475
|
return [serverName, {
|
|
75794
77476
|
...serverConfig,
|
|
@@ -75797,7 +77479,8 @@ var CodexcliMcp = class CodexcliMcp extends ToolMcp {
|
|
|
75797
77479
|
...isRecord(rawServer) && typeof rawServer.experimentalEnvironment === "string" ? { experimentalEnvironment: rawServer.experimentalEnvironment } : {},
|
|
75798
77480
|
...isRecord(rawServer) && rawServer.codexcliTools !== void 0 ? { codexcliTools: rawServer.codexcliTools } : {}
|
|
75799
77481
|
}];
|
|
75800
|
-
}))
|
|
77482
|
+
}));
|
|
77483
|
+
const converted = convertToCodexFormat(mcpServersWithCodexFields);
|
|
75801
77484
|
const filteredMcpServers = this.removeEmptyEntries(converted);
|
|
75802
77485
|
for (const name of Object.keys(converted)) if (!Object.hasOwn(filteredMcpServers, name)) warnWithFallback(void 0, `MCP server "${name}" had no non-empty configuration and was dropped from the codex CLI config`);
|
|
75803
77486
|
const existingMcpServers = isRecord(configToml["mcp_servers"]) ? configToml["mcp_servers"] : {};
|
|
@@ -75821,6 +77504,11 @@ var CodexcliMcp = class CodexcliMcp extends ToolMcp {
|
|
|
75821
77504
|
}
|
|
75822
77505
|
return [name, serverConfig];
|
|
75823
77506
|
}));
|
|
77507
|
+
const declaredCodexNames = new Set(Object.keys(mcpServersWithCodexFields).map((name) => normalizeCodexMcpServerName(name).codexName));
|
|
77508
|
+
const outputMcpServers = preserveUnowned ? {
|
|
77509
|
+
...Object.fromEntries(Object.entries(omitPrototypePollutionKeys(existingMcpServers)).filter(([name]) => !declaredCodexNames.has(name))),
|
|
77510
|
+
...mergedMcpServers
|
|
77511
|
+
} : mergedMcpServers;
|
|
75824
77512
|
return new CodexcliMcp({
|
|
75825
77513
|
outputRoot,
|
|
75826
77514
|
relativeDirPath: paths.relativeDirPath,
|
|
@@ -75829,7 +77517,7 @@ var CodexcliMcp = class CodexcliMcp extends ToolMcp {
|
|
|
75829
77517
|
fileKey: sharedConfigFileKey(paths),
|
|
75830
77518
|
feature: "mcp",
|
|
75831
77519
|
existingContent: configTomlFileContent,
|
|
75832
|
-
patch: { mcp_servers: Object.keys(
|
|
77520
|
+
patch: { mcp_servers: Object.keys(outputMcpServers).length > 0 ? outputMcpServers : void 0 },
|
|
75833
77521
|
filePath: configTomlFilePath
|
|
75834
77522
|
}),
|
|
75835
77523
|
validate
|
|
@@ -87669,7 +89357,8 @@ var McpProcessor = class extends FeatureProcessor {
|
|
|
87669
89357
|
}
|
|
87670
89358
|
getFactory;
|
|
87671
89359
|
featureOptions;
|
|
87672
|
-
|
|
89360
|
+
preserveUnownedMcpServers;
|
|
89361
|
+
constructor({ outputRoot = process.cwd(), inputRoots, toolTarget, global = false, getFactory = defaultGetFactory, dryRun = false, logger, featureOptions, preserveUnownedMcpServers = false }) {
|
|
87673
89362
|
super({
|
|
87674
89363
|
outputRoot,
|
|
87675
89364
|
inputRoots,
|
|
@@ -87682,6 +89371,7 @@ var McpProcessor = class extends FeatureProcessor {
|
|
|
87682
89371
|
this.global = global;
|
|
87683
89372
|
this.getFactory = getFactory;
|
|
87684
89373
|
this.featureOptions = featureOptions;
|
|
89374
|
+
this.preserveUnownedMcpServers = preserveUnownedMcpServers;
|
|
87685
89375
|
}
|
|
87686
89376
|
/**
|
|
87687
89377
|
* Implementation of abstract method from FeatureProcessor
|
|
@@ -87763,7 +89453,8 @@ var McpProcessor = class extends FeatureProcessor {
|
|
|
87763
89453
|
rulesyncMcp: filteredRulesyncMcp,
|
|
87764
89454
|
global: this.global,
|
|
87765
89455
|
logger: this.logger,
|
|
87766
|
-
featureOptions: this.featureOptions
|
|
89456
|
+
featureOptions: this.featureOptions,
|
|
89457
|
+
preserveUnowned: this.preserveUnownedMcpServers
|
|
87767
89458
|
}), ...await factory.class.getAuxiliaryFiles?.({
|
|
87768
89459
|
outputRoot: this.outputRoot,
|
|
87769
89460
|
global: this.global,
|
|
@@ -96055,20 +97746,32 @@ function restrictedByAllToolsCategory(config) {
|
|
|
96055
97746
|
record: config.permission,
|
|
96056
97747
|
key: "*"
|
|
96057
97748
|
}) ?? {}).filter(([pattern, action]) => !/\s/.test(pattern) && (action === "deny" || action === "ask" && pattern !== "*")).map(([pattern]) => pattern).find((pattern) => {
|
|
96058
|
-
|
|
96059
|
-
|
|
96060
|
-
|
|
96061
|
-
|
|
96062
|
-
|
|
96063
|
-
|
|
96064
|
-
|
|
97749
|
+
return carveOutCheckSpellings(pattern.toLowerCase()).some((spelling) => {
|
|
97750
|
+
if (namesGitDirectory(spelling)) return true;
|
|
97751
|
+
const matches = createShadowingRestrictionsTest([{
|
|
97752
|
+
pattern: spelling.replace(/^\.?\//, ""),
|
|
97753
|
+
fromAllToolsCategory: true
|
|
97754
|
+
}]);
|
|
97755
|
+
return GIT_WRITTEN_PATHS.some((path) => matches(path).length > 0);
|
|
97756
|
+
});
|
|
96065
97757
|
});
|
|
96066
97758
|
}
|
|
97759
|
+
function carveOutCheckSpellings(pattern) {
|
|
97760
|
+
const slashed = pattern.replaceAll("\\", "/");
|
|
97761
|
+
return slashed === pattern ? [pattern] : [pattern, slashed];
|
|
97762
|
+
}
|
|
96067
97763
|
function isRestrictedInWorkspaceRootTable({ pattern, table }) {
|
|
96068
97764
|
const readRules = {};
|
|
96069
97765
|
for (const [tablePattern, access] of Object.entries(table)) {
|
|
96070
97766
|
if (tablePattern === pattern) continue;
|
|
96071
|
-
|
|
97767
|
+
if (access === "write") {
|
|
97768
|
+
readRules[tablePattern] = "allow";
|
|
97769
|
+
continue;
|
|
97770
|
+
}
|
|
97771
|
+
for (const spelling of carveOutCheckSpellings(tablePattern)) {
|
|
97772
|
+
if (spelling === pattern) return true;
|
|
97773
|
+
readRules[spelling] = "deny";
|
|
97774
|
+
}
|
|
96072
97775
|
}
|
|
96073
97776
|
return isCoveredByReadRestriction({
|
|
96074
97777
|
pattern,
|
|
@@ -114949,7 +116652,8 @@ function buildRulesStrategy(ctx) {
|
|
|
114949
116652
|
global,
|
|
114950
116653
|
dryRun,
|
|
114951
116654
|
logger,
|
|
114952
|
-
language: config.getLanguage()
|
|
116655
|
+
language: config.getLanguage(),
|
|
116656
|
+
preserveUnmanagedContent: config.getPreserveUnmanagedRuleContent()
|
|
114953
116657
|
}),
|
|
114954
116658
|
loadSource: (p) => p.loadToolFiles(),
|
|
114955
116659
|
toRulesync: (p, files) => p.convertToolFilesToRulesyncFiles(files),
|
|
@@ -115406,14 +117110,20 @@ function createFoldRootOverwriteWatch({ logger }) {
|
|
|
115406
117110
|
writesByPath.set(path, writes);
|
|
115407
117111
|
}
|
|
115408
117112
|
},
|
|
115409
|
-
report: () => {
|
|
117113
|
+
report: ({ skip } = {}) => {
|
|
117114
|
+
const warnedPaths = /* @__PURE__ */ new Set();
|
|
115410
117115
|
for (const [path, writes] of writesByPath) {
|
|
115411
117116
|
const last = writes.at(-1);
|
|
115412
117117
|
if (last === void 0 || last.folds) continue;
|
|
115413
117118
|
const fold = writes.findLast((write) => write.folds && write.content !== last.content);
|
|
115414
|
-
if (fold === void 0
|
|
117119
|
+
if (fold === void 0 || skip?.({
|
|
117120
|
+
path,
|
|
117121
|
+
foldTarget: fold.target
|
|
117122
|
+
})) continue;
|
|
117123
|
+
warnedPaths.add(path);
|
|
115415
117124
|
logger.warn(`Target '${last.target}' overwrites ${displayPath({ filePath: path })}, the file target '${fold.target}' folds every non-root rule into, so '${fold.target}' is left with the root rule only. The last target in config order wins a shared file: list '${fold.target}' after '${last.target}' to keep the folded content (see "Target Order and File Conflicts" in the configuration guide).`);
|
|
115416
117125
|
}
|
|
117126
|
+
return warnedPaths;
|
|
115417
117127
|
}
|
|
115418
117128
|
};
|
|
115419
117129
|
}
|
|
@@ -115586,7 +117296,8 @@ const RETIREMENT_SPECS = {
|
|
|
115586
117296
|
...params,
|
|
115587
117297
|
simulateCommands: config.getSimulateCommands(),
|
|
115588
117298
|
simulateSubagents: config.getSimulateSubagents(),
|
|
115589
|
-
simulateSkills: config.getSimulateSkills()
|
|
117299
|
+
simulateSkills: config.getSimulateSkills(),
|
|
117300
|
+
preserveUnmanagedContent: config.getPreserveUnmanagedRuleContent()
|
|
115590
117301
|
}),
|
|
115591
117302
|
unownedPaths: ({ toolTarget, outputRoot }) => (toolRuleFactories.get(toolTarget)?.class.getSettablePaths().alternativeRoots ?? []).map((alt) => resolve(outputRoot, alt.relativeDirPath, alt.relativeFilePath))
|
|
115592
117303
|
},
|
|
@@ -115710,14 +117421,23 @@ function scheduleRetiredTargetSweeps({ config, logger, sweepPlan, sourceLoadFail
|
|
|
115710
117421
|
sweepPlan,
|
|
115711
117422
|
unownedPaths
|
|
115712
117423
|
}),
|
|
115713
|
-
reportDeleted: () => processor.getRemovedPaths()
|
|
117424
|
+
reportDeleted: () => processor.getRemovedPaths(),
|
|
117425
|
+
reportWritten: () => processor.getSweepWrites()
|
|
115714
117426
|
});
|
|
115715
117427
|
} else {
|
|
115716
117428
|
const processor = spec.create(params, config);
|
|
117429
|
+
const ownershipProcessor = config.getPreserveUnownedSkills() ? spec.create({
|
|
117430
|
+
...params,
|
|
117431
|
+
logger: new ConsoleLogger({
|
|
117432
|
+
verbose: false,
|
|
117433
|
+
silent: true
|
|
117434
|
+
})
|
|
117435
|
+
}, config) : void 0;
|
|
115717
117436
|
featurePlan.defer({
|
|
115718
117437
|
sweep: () => sweepDirs({
|
|
115719
117438
|
processor,
|
|
115720
|
-
sweepPlan
|
|
117439
|
+
sweepPlan,
|
|
117440
|
+
ownershipProcessor
|
|
115721
117441
|
}),
|
|
115722
117442
|
reportDeleted: () => processor.getRemovedPaths()
|
|
115723
117443
|
});
|
|
@@ -115734,18 +117454,36 @@ async function sweepFiles({ processor, sweepPlan, unownedPaths }) {
|
|
|
115734
117454
|
const present = await Promise.all(candidates.map((f) => fileExists(f.getFilePath())));
|
|
115735
117455
|
return await processor.removeOrphanAiFiles(candidates.filter((_, index) => present[index]), []) > 0;
|
|
115736
117456
|
}
|
|
115737
|
-
async function sweepDirs({ processor, sweepPlan }) {
|
|
115738
|
-
|
|
117457
|
+
async function sweepDirs({ processor, sweepPlan, ownershipProcessor }) {
|
|
117458
|
+
const isOwned = ownershipProcessor ? await loadSourceOwnedPaths(ownershipProcessor) : void 0;
|
|
117459
|
+
return await processor.removeOrphanAiDirs((await sweepPlan.rejectClaimed({
|
|
115739
117460
|
items: await processor.loadToolDirsToDelete(),
|
|
115740
117461
|
getPath: (d) => d.getDirPath()
|
|
115741
|
-
}), []) + await processor.removeOrphanFlatFiles({
|
|
115742
|
-
existingFlatFiles: await sweepPlan.rejectClaimed({
|
|
117462
|
+
})).filter((d) => isOwned?.(d.getDirPath()) ?? true), []) + await processor.removeOrphanFlatFiles({
|
|
117463
|
+
existingFlatFiles: (await sweepPlan.rejectClaimed({
|
|
115743
117464
|
items: await processor.loadToolFlatFilesToDelete(),
|
|
115744
117465
|
getPath: (d) => d.getFlatFilePath() ?? d.getDirPath()
|
|
117466
|
+
})).filter((d) => {
|
|
117467
|
+
if (isOwned === void 0) return true;
|
|
117468
|
+
const flatFilePath = d.getFlatFilePath();
|
|
117469
|
+
return flatFilePath !== void 0 && isOwned(flatFilePath);
|
|
115745
117470
|
}),
|
|
115746
117471
|
generatedDirs: []
|
|
115747
117472
|
}) > 0;
|
|
115748
117473
|
}
|
|
117474
|
+
/**
|
|
117475
|
+
* The paths the current sources would write for the processor's target — each
|
|
117476
|
+
* directory, and the file a flattening tool writes in its place — as a
|
|
117477
|
+
* case-folded membership test, matching how the sweeps compare paths.
|
|
117478
|
+
*/
|
|
117479
|
+
async function loadSourceOwnedPaths(processor) {
|
|
117480
|
+
const sourceDirs = await processor.convertRulesyncDirsToToolDirs(await processor.loadRulesyncDirs());
|
|
117481
|
+
const owned = new Set(sourceDirs.flatMap((d) => {
|
|
117482
|
+
const flatFilePath = d.getFlatFilePath();
|
|
117483
|
+
return [d.getDirPath(), ...flatFilePath === void 0 ? [] : [flatFilePath]].map((path) => caseFoldIdentity(resolve(path)));
|
|
117484
|
+
}));
|
|
117485
|
+
return (path) => owned.has(caseFoldIdentity(resolve(path)));
|
|
117486
|
+
}
|
|
115749
117487
|
// src/lib/shared-file-derive.ts
|
|
115750
117488
|
/**
|
|
115751
117489
|
* The single declaration of the cross-feature write order for shared
|
|
@@ -115891,6 +117629,73 @@ const deriveSharedWriteSteps = () => {
|
|
|
115891
117629
|
});
|
|
115892
117630
|
return steps;
|
|
115893
117631
|
};
|
|
117632
|
+
// src/lib/shared-root-selection-watch.ts
|
|
117633
|
+
const selectionKeyOf = (rulesyncFiles) => [...new Set(rulesyncFiles.map((file) => toPosixPath(join(file.getRelativeDirPath(), file.getRelativeFilePath()))))].toSorted().join("\n");
|
|
117634
|
+
/**
|
|
117635
|
+
* Watches for targets that write the same root rule file (`AGENTS.md` for
|
|
117636
|
+
* `codexcli` and `opencode`, for example) with different contents because at
|
|
117637
|
+
* least one of them narrows its rules through the per-target `include` rules
|
|
117638
|
+
* option.
|
|
117639
|
+
*
|
|
117640
|
+
* A shared file holds one target's output only: the last target in config
|
|
117641
|
+
* order wins, as for any shared file. That is documented, but nothing in the
|
|
117642
|
+
* output said so when the targets disagree. The watch does not change what is
|
|
117643
|
+
* written; it names the file, the targets and the winner, once per file.
|
|
117644
|
+
*
|
|
117645
|
+
* It stays quiet when the file would be the same whoever writes it: many
|
|
117646
|
+
* targets keep non-root rules in their own directories, so a different
|
|
117647
|
+
* selection of non-root rules does not change the shared root file. It also
|
|
117648
|
+
* stays quiet when no sharing target's `include` actually leaves a rule out
|
|
117649
|
+
* (`["*"]`, a list naming every rule, or no option): a difference there comes
|
|
117650
|
+
* from the rules' own `targets` frontmatter, which has always worked this way.
|
|
117651
|
+
*
|
|
117652
|
+
* When a fold target's content is overwritten and that fold target folded at
|
|
117653
|
+
* least one non-root rule into it, the folded rules are lost because of the
|
|
117654
|
+
* target order: the fold-root overwrite warning names it with the reordering
|
|
117655
|
+
* that fixes it, and this watch skips the file (`skipPaths`), so each file
|
|
117656
|
+
* gets one warning. Only a fold target that folded nothing (its `include`
|
|
117657
|
+
* left it the root rule alone) is handed to this watch (`foldedNothing`).
|
|
117658
|
+
*
|
|
117659
|
+
* `observe` records what each target resolved and writes; `report` decides
|
|
117660
|
+
* once every target has been seen. Files are keyed by their resolved output
|
|
117661
|
+
* path, so each output root is compared on its own.
|
|
117662
|
+
*/
|
|
117663
|
+
function createSharedRootSelectionWatch({ logger }) {
|
|
117664
|
+
const writesByPath = /* @__PURE__ */ new Map();
|
|
117665
|
+
return {
|
|
117666
|
+
observe: ({ toolTarget, includeNarrowed, rulesyncFiles, toolFiles }) => {
|
|
117667
|
+
for (const file of toolFiles) {
|
|
117668
|
+
if (!(file instanceof ToolRule) || !file.isRoot()) continue;
|
|
117669
|
+
const path = resolve(file.getFilePath());
|
|
117670
|
+
const writes = writesByPath.get(path) ?? [];
|
|
117671
|
+
if (!writes.some((write) => write.target === toolTarget)) writes.push({
|
|
117672
|
+
target: toolTarget,
|
|
117673
|
+
includeNarrowed,
|
|
117674
|
+
rulesyncFiles,
|
|
117675
|
+
content: file.getFileContent()
|
|
117676
|
+
});
|
|
117677
|
+
writesByPath.set(path, writes);
|
|
117678
|
+
}
|
|
117679
|
+
},
|
|
117680
|
+
foldedNothing: ({ path, target }) => {
|
|
117681
|
+
const write = writesByPath.get(path)?.find((entry) => entry.target === target);
|
|
117682
|
+
return write !== void 0 && write.rulesyncFiles.every((file) => file instanceof RulesyncRule && (file.getFrontmatter().root === true || file.getFrontmatter().localRoot === true));
|
|
117683
|
+
},
|
|
117684
|
+
report: ({ skipPaths } = {}) => {
|
|
117685
|
+
for (const [path, writes] of writesByPath) {
|
|
117686
|
+
if (skipPaths?.has(path)) continue;
|
|
117687
|
+
const last = writes.at(-1);
|
|
117688
|
+
if (last === void 0 || writes.length < 2) continue;
|
|
117689
|
+
if (writes.every((write) => write.content === last.content)) continue;
|
|
117690
|
+
if (!writes.some((write) => write.includeNarrowed())) continue;
|
|
117691
|
+
const lastKey = selectionKeyOf(last.rulesyncFiles);
|
|
117692
|
+
if (writes.every((write) => selectionKeyOf(write.rulesyncFiles) === lastKey)) continue;
|
|
117693
|
+
const targets = writes.map((write) => `'${write.target}'`).join(", ");
|
|
117694
|
+
logger.warn(`Targets ${targets} write ${displayPath({ filePath: path })} with different contents, and the \`include\` rules option narrows the rule selection of at least one of them. A shared file holds one target's output: '${last.target}' wins as the last target in config order. Give targets that share a file the same \`include\` list (or none); see "Selecting rules per target" in the configuration guide.`);
|
|
117695
|
+
}
|
|
117696
|
+
}
|
|
117697
|
+
};
|
|
117698
|
+
}
|
|
115894
117699
|
// src/lib/generate.ts
|
|
115895
117700
|
/**
|
|
115896
117701
|
* The message to report when a run left some `.rulesync/` source unread, or
|
|
@@ -115991,29 +117796,30 @@ async function processDirFeatureGeneration(params) {
|
|
|
115991
117796
|
...d.getOtherFiles().map((f) => join(dirPath, f.relativeFilePathToDirPath))
|
|
115992
117797
|
];
|
|
115993
117798
|
}) });
|
|
115994
|
-
if (config.getDelete() && !processor.hasRulesyncSourceLoadFailure())
|
|
115995
|
-
|
|
115996
|
-
|
|
115997
|
-
|
|
115998
|
-
|
|
115999
|
-
|
|
116000
|
-
|
|
116001
|
-
|
|
116002
|
-
|
|
116003
|
-
|
|
116004
|
-
|
|
116005
|
-
|
|
116006
|
-
|
|
116007
|
-
|
|
116008
|
-
|
|
116009
|
-
|
|
116010
|
-
|
|
116011
|
-
|
|
116012
|
-
|
|
116013
|
-
|
|
116014
|
-
|
|
116015
|
-
|
|
116016
|
-
|
|
117799
|
+
if (config.getDelete() && !processor.hasRulesyncSourceLoadFailure()) {
|
|
117800
|
+
const preserveUnownedSkills = config.getPreserveUnownedSkills();
|
|
117801
|
+
sweepPlan.defer({
|
|
117802
|
+
sweep: async () => {
|
|
117803
|
+
const orphanDirCount = preserveUnownedSkills ? 0 : await processor.removeOrphanAiDirs(await sweepPlan.rejectClaimed({
|
|
117804
|
+
items: await processor.loadToolDirsToDelete(),
|
|
117805
|
+
getPath: (d) => d.getDirPath()
|
|
117806
|
+
}), toolDirs);
|
|
117807
|
+
const orphanFileCount = preserveUnownedSkills ? 0 : await processor.removeOrphanFlatFiles({
|
|
117808
|
+
existingFlatFiles: await sweepPlan.rejectClaimed({
|
|
117809
|
+
items: await processor.loadToolFlatFilesToDelete(),
|
|
117810
|
+
getPath: (d) => d.getFlatFilePath() ?? d.getDirPath()
|
|
117811
|
+
}),
|
|
117812
|
+
generatedDirs: toolDirs
|
|
117813
|
+
});
|
|
117814
|
+
const orphanInDirCount = await processor.removeOrphanFilesInAiDirs({
|
|
117815
|
+
generatedDirs: toolDirs,
|
|
117816
|
+
isClaimed: (path) => sweepPlan.isGeneratedExactly({ path })
|
|
117817
|
+
});
|
|
117818
|
+
return orphanDirCount + orphanFileCount + orphanInDirCount > 0;
|
|
117819
|
+
},
|
|
117820
|
+
reportDeleted: () => processor.getRemovedPaths()
|
|
117821
|
+
});
|
|
117822
|
+
}
|
|
116017
117823
|
return {
|
|
116018
117824
|
count: totalCount,
|
|
116019
117825
|
paths: allPaths,
|
|
@@ -116627,6 +118433,7 @@ async function generateRulesCore(params) {
|
|
|
116627
118433
|
logger
|
|
116628
118434
|
});
|
|
116629
118435
|
const foldRootOverwriteWatch = createFoldRootOverwriteWatch({ logger });
|
|
118436
|
+
const sharedRootSelectionWatch = createSharedRootSelectionWatch({ logger });
|
|
116630
118437
|
let fullRunSkills;
|
|
116631
118438
|
const loadFullRunSkills = () => {
|
|
116632
118439
|
fullRunSkills ??= loadConfigFileSkills({
|
|
@@ -116652,6 +118459,7 @@ async function generateRulesCore(params) {
|
|
|
116652
118459
|
skills: processorSkills,
|
|
116653
118460
|
featureOptions,
|
|
116654
118461
|
delete: config.getDelete(),
|
|
118462
|
+
preserveUnmanagedContent: config.getPreserveUnmanagedRuleContent(),
|
|
116655
118463
|
dryRun: config.isPreviewMode(),
|
|
116656
118464
|
logger
|
|
116657
118465
|
});
|
|
@@ -116666,7 +118474,7 @@ async function generateRulesCore(params) {
|
|
|
116666
118474
|
const processor = createProcessor({
|
|
116667
118475
|
toolTarget,
|
|
116668
118476
|
outputRoot,
|
|
116669
|
-
featureOptions: config
|
|
118477
|
+
featureOptions: getRulesFeatureOptions(config, toolTarget),
|
|
116670
118478
|
skills
|
|
116671
118479
|
});
|
|
116672
118480
|
const rulesyncFiles = await processor.loadRulesyncFiles();
|
|
@@ -116685,6 +118493,12 @@ async function generateRulesCore(params) {
|
|
|
116685
118493
|
toolTarget,
|
|
116686
118494
|
toolFiles
|
|
116687
118495
|
});
|
|
118496
|
+
sharedRootSelectionWatch.observe({
|
|
118497
|
+
toolTarget,
|
|
118498
|
+
includeNarrowed: () => processor.didIncludeNarrowSelection(),
|
|
118499
|
+
rulesyncFiles,
|
|
118500
|
+
toolFiles
|
|
118501
|
+
});
|
|
116688
118502
|
skippedRootFileCheck.observe({
|
|
116689
118503
|
toolTarget,
|
|
116690
118504
|
outputRoot,
|
|
@@ -116713,7 +118527,11 @@ async function generateRulesCore(params) {
|
|
|
116713
118527
|
if (skippedResult.hasDiff) hasDiff = true;
|
|
116714
118528
|
if (skippedResult.sourceLoadFailed) sourceLoadFailed = true;
|
|
116715
118529
|
}
|
|
116716
|
-
foldRootOverwriteWatch.report()
|
|
118530
|
+
const foldWarnedPaths = foldRootOverwriteWatch.report({ skip: ({ path, foldTarget }) => sharedRootSelectionWatch.foldedNothing({
|
|
118531
|
+
path,
|
|
118532
|
+
target: foldTarget
|
|
118533
|
+
}) });
|
|
118534
|
+
sharedRootSelectionWatch.report({ skipPaths: foldWarnedPaths });
|
|
116717
118535
|
return {
|
|
116718
118536
|
count: totalCount,
|
|
116719
118537
|
paths: allPaths,
|
|
@@ -116830,7 +118648,8 @@ function generateMcpCore(params) {
|
|
|
116830
118648
|
supportedTargets: McpProcessor.getToolTargets({ global: config.getGlobal() }),
|
|
116831
118649
|
createProcessor: (options) => new McpProcessor({
|
|
116832
118650
|
...options,
|
|
116833
|
-
featureOptions: config.getFeatureOptions(options.toolTarget, "mcp")
|
|
118651
|
+
featureOptions: config.getFeatureOptions(options.toolTarget, "mcp"),
|
|
118652
|
+
preserveUnownedMcpServers: config.getPreserveUnownedMcpServers()
|
|
116834
118653
|
})
|
|
116835
118654
|
});
|
|
116836
118655
|
}
|
|
@@ -117108,7 +118927,8 @@ async function importRulesCore(params) {
|
|
|
117108
118927
|
}),
|
|
117109
118928
|
toolTarget: tool,
|
|
117110
118929
|
global,
|
|
117111
|
-
logger
|
|
118930
|
+
logger,
|
|
118931
|
+
preserveUnmanagedContent: config.getPreserveUnmanagedRuleContent()
|
|
117112
118932
|
};
|
|
117113
118933
|
const rulesProcessor = new RulesProcessor(baseParams);
|
|
117114
118934
|
const toolFiles = await rulesProcessor.loadToolFiles();
|
|
@@ -117121,7 +118941,7 @@ async function importRulesCore(params) {
|
|
|
117121
118941
|
...baseParams,
|
|
117122
118942
|
inputRoots: config.getInputRoots(),
|
|
117123
118943
|
deriveSubprojectPathFromGlobs: config.getDeriveSubprojectPathFromGlobs(),
|
|
117124
|
-
featureOptions: config
|
|
118944
|
+
featureOptions: getRulesFeatureOptions(config, tool)
|
|
117125
118945
|
}).warnForFoldImportDuplicationRisk();
|
|
117126
118946
|
} catch (error) {
|
|
117127
118947
|
logger.warn(`Skipped the ${tool} import duplication check: ${formatError(error)}`);
|
|
@@ -117380,6 +119200,6 @@ const CHECKS_IMPORT_STRATEGY = {
|
|
|
117380
119200
|
missingLabel: "check files",
|
|
117381
119201
|
createdLabel: "check files"
|
|
117382
119202
|
};
|
|
117383
|
-
export {
|
|
119203
|
+
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
119204
|
|
|
117385
|
-
//# sourceMappingURL=import-
|
|
119205
|
+
//# sourceMappingURL=import-1IIVv7h3.js.map
|