rulesync 43.17.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.
@@ -3272,6 +3272,7 @@ const ConfigParamsSchema = z.object({
3272
3272
  preserveUnownedHooks: optional(z.boolean()),
3273
3273
  preserveUnmanagedRuleContent: optional(z.boolean()),
3274
3274
  preserveUnownedSkills: optional(z.boolean()),
3275
+ preserveUnownedMcpServers: optional(z.boolean()),
3275
3276
  deriveSubprojectPathFromGlobs: optional(z.boolean()),
3276
3277
  flattenedCommandNaming: optional(FlattenedCommandNamingSchema),
3277
3278
  /**
@@ -3456,6 +3457,7 @@ var Config = class Config {
3456
3457
  preserveUnownedHooks;
3457
3458
  preserveUnmanagedRuleContent;
3458
3459
  preserveUnownedSkills;
3460
+ preserveUnownedMcpServers;
3459
3461
  deriveSubprojectPathFromGlobs;
3460
3462
  flattenedCommandNaming;
3461
3463
  language;
@@ -3484,7 +3486,7 @@ var Config = class Config {
3484
3486
  inputRoots;
3485
3487
  configFilePath;
3486
3488
  sources;
3487
- constructor({ outputRoots, targets, features, verbose, delete: isDelete, global, silent, simulateCommands, simulateSubagents, simulateSkills, preserveUnownedHooks, preserveUnmanagedRuleContent, preserveUnownedSkills, deriveSubprojectPathFromGlobs, flattenedCommandNaming, language, gitignoreTargetsOnly, gitignoreDestination, dryRun, check, retireTargets, retireFeatures, inputRoot, inputRoots, configFilePath, sources, configFileTargets, configFileSelection }) {
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 }) {
3488
3490
  assertTargetsFeaturesExclusive({
3489
3491
  targets,
3490
3492
  features
@@ -3520,6 +3522,7 @@ var Config = class Config {
3520
3522
  this.preserveUnownedHooks = preserveUnownedHooks ?? false;
3521
3523
  this.preserveUnmanagedRuleContent = preserveUnmanagedRuleContent === true;
3522
3524
  this.preserveUnownedSkills = preserveUnownedSkills === true;
3525
+ this.preserveUnownedMcpServers = preserveUnownedMcpServers === true;
3523
3526
  this.deriveSubprojectPathFromGlobs = deriveSubprojectPathFromGlobs ?? false;
3524
3527
  this.flattenedCommandNaming = flattenedCommandNaming ?? "basename";
3525
3528
  this.language = language;
@@ -3786,6 +3789,9 @@ var Config = class Config {
3786
3789
  getPreserveUnownedSkills() {
3787
3790
  return this.preserveUnownedSkills;
3788
3791
  }
3792
+ getPreserveUnownedMcpServers() {
3793
+ return this.preserveUnownedMcpServers;
3794
+ }
3789
3795
  getFlattenedCommandNaming() {
3790
3796
  return this.flattenedCommandNaming;
3791
3797
  }
@@ -3885,6 +3891,7 @@ const getDefaults = () => ({
3885
3891
  preserveUnownedHooks: false,
3886
3892
  preserveUnmanagedRuleContent: false,
3887
3893
  preserveUnownedSkills: false,
3894
+ preserveUnownedMcpServers: false,
3888
3895
  deriveSubprojectPathFromGlobs: false,
3889
3896
  flattenedCommandNaming: "basename",
3890
3897
  gitignoreTargetsOnly: true,
@@ -4233,6 +4240,11 @@ var ConfigResolver = class {
4233
4240
  file: configByFile.preserveUnownedSkills,
4234
4241
  fallback: getDefaults().preserveUnownedSkills
4235
4242
  }),
4243
+ preserveUnownedMcpServers: pick({
4244
+ cli: void 0,
4245
+ file: configByFile.preserveUnownedMcpServers,
4246
+ fallback: getDefaults().preserveUnownedMcpServers
4247
+ }),
4236
4248
  deriveSubprojectPathFromGlobs: pick({
4237
4249
  cli: deriveSubprojectPathFromGlobs,
4238
4250
  file: configByFile.deriveSubprojectPathFromGlobs,
@@ -42790,6 +42802,15 @@ const findFence = (content) => {
42790
42802
  *
42791
42803
  * When the generated content starts with frontmatter, the existing file's
42792
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.
42793
42814
  */
42794
42815
  const spliceRuleManagedBlock = ({ existingContent, generatedContent }) => {
42795
42816
  const generated = splitLeadingFrontmatter(generatedContent);
@@ -54718,6 +54739,11 @@ var RulesProcessor = class extends FeatureProcessor {
54718
54739
  featureOptions;
54719
54740
  deleteOrphans;
54720
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;
54721
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 }) {
54722
54748
  super({
54723
54749
  outputRoot,
@@ -55373,6 +55399,8 @@ As this project's AI coding tool, you must follow the additional conventions bel
55373
55399
  rules: mergedRules,
55374
55400
  factory
55375
55401
  });
55402
+ const isTargeted = (rule) => factory.class.isTargetedByRulesyncRule(rule);
55403
+ this.includeNarrowedSelection = rulesyncRules.filter(isTargeted).length < mergedRules.filter(isTargeted).length;
55376
55404
  const targetedRootRules = rulesyncRules.filter((rule) => rule.getFrontmatter().root).filter((rule) => factory.class.isTargetedByRulesyncRule(rule));
55377
55405
  const rootRuleLeftOutByInclude = mergedRules.some((rule) => rule.getFrontmatter().root && factory.class.isTargetedByRulesyncRule(rule) && !rulesyncRules.includes(rule));
55378
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}.`);
@@ -55393,6 +55421,14 @@ As this project's AI coding tool, you must follow the additional conventions bel
55393
55421
  return [...targetedRootRules, ...nonRootRules];
55394
55422
  }
55395
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
+ /**
55396
55432
  * Narrow the rules to the ones the target's `include` rules option names.
55397
55433
  * The option is a pure narrowing filter: a named rule still has to target
55398
55434
  * this tool through its `targets` frontmatter, which is checked afterwards
@@ -66047,7 +66083,9 @@ const BLOCKING_HOOKS = new Set(Object.keys(NAMED_HOOK_MATCHER_SUBJECTS).filter((
66047
66083
  * Shell echoed them; a `preToolUse` command's are read, 1 MiB each kept (more
66048
66084
  * stdout denies; on the Bun Shell fallback the whole output is buffered before
66049
66085
  * that check), and a `sessionStart` command's stdout is read the same way while
66050
- * its stderr goes to the host's (after the command, on Bun Shell). Output
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
66051
66089
  * pipes a background process keeps open are read for 1 s after the command
66052
66090
  * exits; what arrived by then is kept, and the reads are then cancelled, as
66053
66091
  * they are at a timeout. The OpenCode 1.x-style `event` hooks (`inProcess`)
@@ -66196,28 +66234,37 @@ function buildRunHelperLinesFor(cwdExpression) {
66196
66234
  " if (inProcess || !(await __rulesyncCanExec)) {",
66197
66235
  ` const run = Bun.$\`echo \${input} | \${{ raw: command }}\`.cwd(${cwdExpression}).nothrow();`,
66198
66236
  " // A sessionStart command's stderr reaches the host when it ends, even after its timeout.",
66199
- " const finished = echo === true ? run : run.quiet().then((done) => (echo && process.stderr.write(done.stderr), done));",
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
+ " });",
66200
66243
  " const result = await Promise.race([finished, timeout()]).finally(() => clearTimeout(timer));",
66201
66244
  " if (!result || echo === true) return result && { exitCode: result.exitCode };",
66202
66245
  " const { exitCode, stdout, stderr } = result;",
66203
66246
  " return { exitCode, stdout: stdout.toString(), stderr: stderr.toString(), overflow: stdout.length > 1048576 };",
66204
66247
  " }",
66205
- " // An ordinary command writes to the host's stdout and stderr; a preToolUse one is read, and",
66206
- " // a sessionStart one (`echo: \"stderr\"`) has its stdout read.",
66207
- ` const proc = ${spawn("\"export BUN_BE_BUN=\\n\" + command", "new TextEncoder().encode(input + \"\\n\")", "echo === true ? \"inherit\" : \"pipe\"", "echo ? \"inherit\" : \"pipe\"")};`,
66208
- " const stdout = echo === true ? undefined : __rulesyncRead(proc.stdout);",
66209
- " const stderr = echo ? undefined : __rulesyncRead(proc.stderr);",
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);",
66210
66254
  " const exitCode = await Promise.race([proc.exited, timeout()]).finally(() => clearTimeout(timer));",
66211
66255
  " if (exitCode === null) {",
66212
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());",
66213
66259
  " if (process.platform === \"win32\") __rulesyncKillWindowsTree(proc);",
66214
66260
  " else __rulesyncKillTree(proc);",
66215
66261
  " return null;",
66216
66262
  " }",
66217
66263
  " if (echo === true) return { exitCode };",
66218
- " await Promise.race([Promise.all([stdout.done, stderr?.done]), Bun.sleep(1000)]);",
66219
- " stdout.stop(), stderr?.stop();",
66220
- " return { exitCode, stdout: stdout.text(), stderr: stderr?.text() ?? \"\", overflow: stdout.overflow() };",
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 };",
66221
66268
  "};",
66222
66269
  "const __rulesyncRunHook = async ({ label, command, input, blocking, seconds, inProcess = false, context = false }) => {",
66223
66270
  " let result;",
@@ -67746,6 +67793,92 @@ function wrapInConditions(handler, statement, indent) {
67746
67793
  `${indent}}`
67747
67794
  ];
67748
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
+ }
67749
67882
  /** Emit one `ctx.<domain>.hook(name, ...)` registration. */
67750
67883
  function buildHookRegistrationLines(hookPoint, handlers) {
67751
67884
  const separator = hookPoint.indexOf(":");
@@ -67758,7 +67891,10 @@ function buildHookRegistrationLines(hookPoint, handlers) {
67758
67891
  handlers,
67759
67892
  cwdExpression: "directory"
67760
67893
  }).map((line) => ` ${line}`));
67761
- for (const handler of handlers) lines.push(...wrapInConditions(handler, buildRunStatement(handler), " "));
67894
+ for (const handler of handlers) {
67895
+ const statement = isPostToolUseHandler(handler) ? buildPostToolUseRunStatement(handler) : buildRunStatement(handler);
67896
+ lines.push(...wrapInConditions(handler, statement, " "));
67897
+ }
67762
67898
  lines.push(" }),");
67763
67899
  lines.push(");");
67764
67900
  return lines;
@@ -68007,10 +68143,12 @@ function buildSetupBodyLines({ hookHandlers, eventHandlers, stopHandlers }) {
68007
68143
  cwdExpression: "directory"
68008
68144
  })
68009
68145
  ];
68010
- if (stopHandlers.length > 0) {
68146
+ const usesPostToolUse = allHandlers.some(isPostToolUseHandler);
68147
+ if (stopHandlers.length > 0 || usesPostToolUse) {
68011
68148
  if (!allHandlers.some((handler) => handler.payload?.name === "PreToolUse")) body.push("", ...buildBlockReasonSanitizerLines({ typed: false }));
68012
- body.push("", ...STOP_HOOK_HELPER_LINES$1);
68013
68149
  }
68150
+ if (stopHandlers.length > 0) body.push("", ...STOP_HOOK_HELPER_LINES$1);
68151
+ if (usesPostToolUse) body.push("", ...POST_TOOL_USE_HELPER_LINES);
68014
68152
  if ([...hookHandlers.values()].some((handlers) => handlers.some((handler) => handler.matcher !== void 0))) body.push("", ...TOOL_MATCHER_HELPER_LINES);
68015
68153
  const usesContext = [...eventHandlers.values()].some(usesSessionContext);
68016
68154
  const registers = hookHandlers.size > 0 || usesContext || stopHandlers.length > 0;
@@ -77321,7 +77459,7 @@ var CodexcliMcp = class CodexcliMcp extends ToolMcp {
77321
77459
  validate
77322
77460
  });
77323
77461
  }
77324
- 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 }) {
77325
77463
  const paths = this.getSettablePaths({ global });
77326
77464
  const configTomlFilePath = join(outputRoot, paths.relativeDirPath, paths.relativeFilePath);
77327
77465
  const configTomlFileContent = await readFileContentOrNull(configTomlFilePath) ?? "";
@@ -77332,7 +77470,7 @@ var CodexcliMcp = class CodexcliMcp extends ToolMcp {
77332
77470
  throw new Error(`Failed to parse existing Codex CLI config at ${configTomlFilePath}: ${formatError(error)}`, { cause: error });
77333
77471
  }
77334
77472
  const strippedMcpServers = rulesyncMcp.getMcpServers();
77335
- const converted = convertToCodexFormat(Object.fromEntries(Object.entries(strippedMcpServers).map(([serverName, serverConfig]) => {
77473
+ const mcpServersWithCodexFields = Object.fromEntries(Object.entries(strippedMcpServers).map(([serverName, serverConfig]) => {
77336
77474
  const rawServer = rulesyncMcp.getRawMcpServer(serverName);
77337
77475
  return [serverName, {
77338
77476
  ...serverConfig,
@@ -77341,7 +77479,8 @@ var CodexcliMcp = class CodexcliMcp extends ToolMcp {
77341
77479
  ...isRecord(rawServer) && typeof rawServer.experimentalEnvironment === "string" ? { experimentalEnvironment: rawServer.experimentalEnvironment } : {},
77342
77480
  ...isRecord(rawServer) && rawServer.codexcliTools !== void 0 ? { codexcliTools: rawServer.codexcliTools } : {}
77343
77481
  }];
77344
- })));
77482
+ }));
77483
+ const converted = convertToCodexFormat(mcpServersWithCodexFields);
77345
77484
  const filteredMcpServers = this.removeEmptyEntries(converted);
77346
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`);
77347
77486
  const existingMcpServers = isRecord(configToml["mcp_servers"]) ? configToml["mcp_servers"] : {};
@@ -77365,6 +77504,11 @@ var CodexcliMcp = class CodexcliMcp extends ToolMcp {
77365
77504
  }
77366
77505
  return [name, serverConfig];
77367
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;
77368
77512
  return new CodexcliMcp({
77369
77513
  outputRoot,
77370
77514
  relativeDirPath: paths.relativeDirPath,
@@ -77373,7 +77517,7 @@ var CodexcliMcp = class CodexcliMcp extends ToolMcp {
77373
77517
  fileKey: sharedConfigFileKey(paths),
77374
77518
  feature: "mcp",
77375
77519
  existingContent: configTomlFileContent,
77376
- patch: { mcp_servers: Object.keys(mergedMcpServers).length > 0 ? mergedMcpServers : void 0 },
77520
+ patch: { mcp_servers: Object.keys(outputMcpServers).length > 0 ? outputMcpServers : void 0 },
77377
77521
  filePath: configTomlFilePath
77378
77522
  }),
77379
77523
  validate
@@ -89213,7 +89357,8 @@ var McpProcessor = class extends FeatureProcessor {
89213
89357
  }
89214
89358
  getFactory;
89215
89359
  featureOptions;
89216
- constructor({ outputRoot = process.cwd(), inputRoots, toolTarget, global = false, getFactory = defaultGetFactory, dryRun = false, logger, featureOptions }) {
89360
+ preserveUnownedMcpServers;
89361
+ constructor({ outputRoot = process.cwd(), inputRoots, toolTarget, global = false, getFactory = defaultGetFactory, dryRun = false, logger, featureOptions, preserveUnownedMcpServers = false }) {
89217
89362
  super({
89218
89363
  outputRoot,
89219
89364
  inputRoots,
@@ -89226,6 +89371,7 @@ var McpProcessor = class extends FeatureProcessor {
89226
89371
  this.global = global;
89227
89372
  this.getFactory = getFactory;
89228
89373
  this.featureOptions = featureOptions;
89374
+ this.preserveUnownedMcpServers = preserveUnownedMcpServers;
89229
89375
  }
89230
89376
  /**
89231
89377
  * Implementation of abstract method from FeatureProcessor
@@ -89307,7 +89453,8 @@ var McpProcessor = class extends FeatureProcessor {
89307
89453
  rulesyncMcp: filteredRulesyncMcp,
89308
89454
  global: this.global,
89309
89455
  logger: this.logger,
89310
- featureOptions: this.featureOptions
89456
+ featureOptions: this.featureOptions,
89457
+ preserveUnowned: this.preserveUnownedMcpServers
89311
89458
  }), ...await factory.class.getAuxiliaryFiles?.({
89312
89459
  outputRoot: this.outputRoot,
89313
89460
  global: this.global,
@@ -116963,14 +117110,20 @@ function createFoldRootOverwriteWatch({ logger }) {
116963
117110
  writesByPath.set(path, writes);
116964
117111
  }
116965
117112
  },
116966
- report: () => {
117113
+ report: ({ skip } = {}) => {
117114
+ const warnedPaths = /* @__PURE__ */ new Set();
116967
117115
  for (const [path, writes] of writesByPath) {
116968
117116
  const last = writes.at(-1);
116969
117117
  if (last === void 0 || last.folds) continue;
116970
117118
  const fold = writes.findLast((write) => write.folds && write.content !== last.content);
116971
- if (fold === void 0) continue;
117119
+ if (fold === void 0 || skip?.({
117120
+ path,
117121
+ foldTarget: fold.target
117122
+ })) continue;
117123
+ warnedPaths.add(path);
116972
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).`);
116973
117125
  }
117126
+ return warnedPaths;
116974
117127
  }
116975
117128
  };
116976
117129
  }
@@ -117476,6 +117629,73 @@ const deriveSharedWriteSteps = () => {
117476
117629
  });
117477
117630
  return steps;
117478
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
+ }
117479
117699
  // src/lib/generate.ts
117480
117700
  /**
117481
117701
  * The message to report when a run left some `.rulesync/` source unread, or
@@ -118213,6 +118433,7 @@ async function generateRulesCore(params) {
118213
118433
  logger
118214
118434
  });
118215
118435
  const foldRootOverwriteWatch = createFoldRootOverwriteWatch({ logger });
118436
+ const sharedRootSelectionWatch = createSharedRootSelectionWatch({ logger });
118216
118437
  let fullRunSkills;
118217
118438
  const loadFullRunSkills = () => {
118218
118439
  fullRunSkills ??= loadConfigFileSkills({
@@ -118272,6 +118493,12 @@ async function generateRulesCore(params) {
118272
118493
  toolTarget,
118273
118494
  toolFiles
118274
118495
  });
118496
+ sharedRootSelectionWatch.observe({
118497
+ toolTarget,
118498
+ includeNarrowed: () => processor.didIncludeNarrowSelection(),
118499
+ rulesyncFiles,
118500
+ toolFiles
118501
+ });
118275
118502
  skippedRootFileCheck.observe({
118276
118503
  toolTarget,
118277
118504
  outputRoot,
@@ -118300,7 +118527,11 @@ async function generateRulesCore(params) {
118300
118527
  if (skippedResult.hasDiff) hasDiff = true;
118301
118528
  if (skippedResult.sourceLoadFailed) sourceLoadFailed = true;
118302
118529
  }
118303
- foldRootOverwriteWatch.report();
118530
+ const foldWarnedPaths = foldRootOverwriteWatch.report({ skip: ({ path, foldTarget }) => sharedRootSelectionWatch.foldedNothing({
118531
+ path,
118532
+ target: foldTarget
118533
+ }) });
118534
+ sharedRootSelectionWatch.report({ skipPaths: foldWarnedPaths });
118304
118535
  return {
118305
118536
  count: totalCount,
118306
118537
  paths: allPaths,
@@ -118417,7 +118648,8 @@ function generateMcpCore(params) {
118417
118648
  supportedTargets: McpProcessor.getToolTargets({ global: config.getGlobal() }),
118418
118649
  createProcessor: (options) => new McpProcessor({
118419
118650
  ...options,
118420
- featureOptions: config.getFeatureOptions(options.toolTarget, "mcp")
118651
+ featureOptions: config.getFeatureOptions(options.toolTarget, "mcp"),
118652
+ preserveUnownedMcpServers: config.getPreserveUnownedMcpServers()
118421
118653
  })
118422
118654
  });
118423
118655
  }
@@ -118970,4 +119202,4 @@ const CHECKS_IMPORT_STRATEGY = {
118970
119202
  };
118971
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 };
118972
119204
 
118973
- //# sourceMappingURL=import-C_TEclz6.js.map
119205
+ //# sourceMappingURL=import-1IIVv7h3.js.map