rulesync 43.7.0 → 43.8.1

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.
@@ -1815,28 +1815,6 @@ function splitAbsolutePath(absolutePath) {
1815
1815
  };
1816
1816
  }
1817
1817
  /**
1818
- * Whether writing `targetPath` would land outside `rootPath` once every link on
1819
- * the way there is resolved. Both sides are taken to where a write to them
1820
- * would land (see {@link writeLandingPath}), so a root that does not fully
1821
- * exist yet is judged the same way as the target below it.
1822
- *
1823
- * A link that stays inside the root passes. That is what sets this apart from
1824
- * the stricter {@link assertWritablePathInsideRoot} the sweep paths use: a
1825
- * dotfiles checkout linked from inside the home directory is a common shape for
1826
- * a global write target, and refusing it would refuse `--global` outright.
1827
- *
1828
- * A link chain that cycles is reported as an escape: the write could not get
1829
- * through it, and refusing it is the answer that never writes somewhere
1830
- * unexpected.
1831
- */
1832
- async function writablePathEscapesRoot({ rootPath, targetPath }) {
1833
- const relativeLanding = await relativeWriteLanding({
1834
- rootPath,
1835
- targetPath
1836
- });
1837
- return relativeLanding === null || pathEscapesRoot(relativeLanding);
1838
- }
1839
- /**
1840
1818
  * Where a write to `targetPath` lands relative to where a write to `rootPath`
1841
1819
  * lands, both taken through {@link writeLandingPath}: `""` when the two land on
1842
1820
  * the same directory, and `null` when either side's links form a cycle. Errors
@@ -1849,6 +1827,59 @@ async function relativeWriteLanding({ rootPath, targetPath }) {
1849
1827
  return (0, node_path.relative)(rootLanding, targetLanding);
1850
1828
  }
1851
1829
  /**
1830
+ * Directory names that hold version-control metadata. Bytes landing in one of
1831
+ * them change how the VCS behaves rather than what it tracks: `.git/config`
1832
+ * can set `core.fsmonitor`, `.git/hooks/*` run on the next commit.
1833
+ */
1834
+ const VCS_METADATA_DIR_NAMES = /* @__PURE__ */ new Set([
1835
+ ".git",
1836
+ ".hg",
1837
+ ".svn",
1838
+ ".jj"
1839
+ ]);
1840
+ function hasVcsMetadataSegment(path) {
1841
+ return splitPathSegments(path).some((segment) => {
1842
+ const folded = segment.replace(/:.*$/, "").replace(/[. ]+$/, "").toLowerCase();
1843
+ return VCS_METADATA_DIR_NAMES.has(folded) || /^(git|hg|svn|jj)~\d+$/.test(folded);
1844
+ });
1845
+ }
1846
+ /**
1847
+ * Whether a link on the way to `targetPath` carries it into version-control
1848
+ * metadata (`.git/` and its siblings) that its spelling does not name.
1849
+ *
1850
+ * {@link writablePathEscapesRoot} lets a link that stays inside the root
1851
+ * through, but a checked-out repository can commit `CLAUDE.md -> .git/config`:
1852
+ * the landing is inside the root, yet a write there hands the repository author
1853
+ * the operator's next `git` command. `git clone` never transfers `.git/`, so a
1854
+ * path spelled into it is never something the repository chose; only a write
1855
+ * that lands exactly where it is spelled may touch it.
1856
+ *
1857
+ * `relativeLanding` is {@link relativeWriteLanding}'s answer for the same pair,
1858
+ * passed in so a caller that already has it does not resolve the links twice.
1859
+ */
1860
+ function landingEntersVcsMetadata({ rootPath, targetPath, relativeLanding }) {
1861
+ return hasVcsMetadataSegment(relativeLanding) && relativeLanding !== (0, node_path.relative)((0, node_path.resolve)(rootPath), (0, node_path.resolve)(targetPath));
1862
+ }
1863
+ /**
1864
+ * Refuse a write target that a symbolic link carries into version-control
1865
+ * metadata (see {@link landingEntersVcsMetadata}). Meant for writes of remote
1866
+ * bytes, next to {@link assertPathResolvesInsideRoot}: an in-root link (a
1867
+ * skill directory linked to a shared one) stays allowed, but not one that
1868
+ * hands the bytes to `.git/config` or `.git/hooks/`.
1869
+ */
1870
+ async function assertLandingOutsideVcsMetadata({ rootPath, targetPath }) {
1871
+ const relativeLanding = await relativeWriteLanding({
1872
+ rootPath,
1873
+ targetPath
1874
+ });
1875
+ if (relativeLanding === null) throw new PathOutsideRootError(`Refusing to write through a link cycle: ${targetPath}.`);
1876
+ if (landingEntersVcsMetadata({
1877
+ rootPath,
1878
+ targetPath,
1879
+ relativeLanding
1880
+ })) throw new PathOutsideRootError(`Refusing to write ${targetPath}: a symbolic link leads it into version-control metadata.`);
1881
+ }
1882
+ /**
1852
1883
  * How many trailing segments `filePath` and `identity` have in common.
1853
1884
  *
1854
1885
  * A path that walked through no link at all shares all of its own segments with
@@ -5452,7 +5483,8 @@ const QWENCODE_HOOK_EVENTS = [
5452
5483
  "todoCreated",
5453
5484
  "todoCompleted",
5454
5485
  "messageDisplay",
5455
- "sessionDelete"
5486
+ "sessionDelete",
5487
+ "fileChanged"
5456
5488
  ];
5457
5489
  const CANONICAL_TO_KIMI_CODE_EVENT_NAMES = {
5458
5490
  sessionStart: "SessionStart",
@@ -6786,6 +6818,7 @@ const CANONICAL_TO_JUNIE_EVENT_NAMES = {
6786
6818
  sessionStart: "SessionStart",
6787
6819
  beforeSubmitPrompt: "UserPromptSubmit",
6788
6820
  preToolUse: "PreToolUse",
6821
+ postToolUse: "PostToolUse",
6789
6822
  stop: "Stop",
6790
6823
  stopFailure: "StopFailure",
6791
6824
  permissionRequest: "PermissionRequest",
@@ -6794,11 +6827,12 @@ const CANONICAL_TO_JUNIE_EVENT_NAMES = {
6794
6827
  /**
6795
6828
  * Hook events supported by JetBrains Junie CLI.
6796
6829
  *
6797
- * Junie CLI exposes seven lifecycle events under the `"hooks"` key of
6830
+ * Junie CLI exposes eight lifecycle events under the `"hooks"` key of
6798
6831
  * `~/.junie/config.json`: `SessionStart`, `UserPromptSubmit`, `PreToolUse`,
6799
- * `Stop`, `StopFailure`, `PermissionRequest`, and `SessionEnd`. Matchers apply
6800
- * to `SessionStart` (source), `PreToolUse` (tool name), `StopFailure` (error
6801
- * type), `PermissionRequest` (tool name), and `SessionEnd` (reason);
6832
+ * `PostToolUse`, `Stop`, `StopFailure`, `PermissionRequest`, and `SessionEnd`.
6833
+ * Matchers apply to `SessionStart` (source), `PreToolUse` and `PostToolUse`
6834
+ * (tool name), `StopFailure` (error type), `PermissionRequest` (tool name), and
6835
+ * `SessionEnd` (reason);
6802
6836
  * `UserPromptSubmit` and `Stop` are matcher-less and always run. Only
6803
6837
  * `type: "command"` hooks are supported. Project-local hooks are ignored for
6804
6838
  * safety.
@@ -6977,7 +7011,8 @@ const CANONICAL_TO_QWENCODE_EVENT_NAMES = {
6977
7011
  todoCreated: "TodoCreated",
6978
7012
  todoCompleted: "TodoCompleted",
6979
7013
  messageDisplay: "MessageDisplay",
6980
- sessionDelete: "SessionDelete"
7014
+ sessionDelete: "SessionDelete",
7015
+ fileChanged: "FileChanged"
6981
7016
  };
6982
7017
  /**
6983
7018
  * Map Qwen Code PascalCase event names to canonical camelCase.
@@ -9232,7 +9267,8 @@ const AntigravityCliPermissionsOverrideSchema = zod_mini.z.looseObject({
9232
9267
  * The same override also carries the two plugin-consumption keys Auggie reads
9233
9268
  * from `settings.json`: `recommendedMarketplaces` (`"owner/repo"` marketplaces
9234
9269
  * a workspace prompts its contributors to install; honored only in the
9235
- * project's `.augment/settings.json`) and `enabledPlugins` (plugin ids of the
9270
+ * project's `.augment/settings.json`, and only by Auggie 0.x — 1.x no longer
9271
+ * reads it) and `enabledPlugins` (plugin ids of the
9236
9272
  * form `"plugin@marketplace"` mapped to on/off, deep-merged across the user,
9237
9273
  * project and local tiers).
9238
9274
  *
@@ -9416,6 +9452,14 @@ const CodexBasePermissionProfileSchema = zod_mini.z.enum(CODEX_BASE_PERMISSION_P
9416
9452
  * `true`; only an explicit `false` suppresses it. Like
9417
9453
  * `base_permission_profile` it is consumed by the profile builder, not
9418
9454
  * written as a top-level config key.
9455
+ * - `bash_canonical_matching` — when `true`, the `forbidden` (deny) and
9456
+ * `prompt` (ask) rules generated from `permission.bash` into
9457
+ * `.codex/rules/rulesync.rules` carry `canonical_matching = True`, so Codex
9458
+ * compares their tokens after Unicode canonical case-insensitive folding (`rm` also
9459
+ * matches `RM`). `allow` rules stay exact so the opt-in never widens what is
9460
+ * auto-approved. Requires Codex 0.167.0 or later — an older Codex rejects the
9461
+ * keyword and fails to load the rules file — so it defaults to `false`. Not
9462
+ * written as a config key.
9419
9463
  *
9420
9464
  * The keys written to `config.toml` are an **allowlist**, not verbatim
9421
9465
  * passthrough: only `CODEXCLI_OVERRIDE_KEYS`
@@ -9423,8 +9467,8 @@ const CodexBasePermissionProfileSchema = zod_mini.z.enum(CODEX_BASE_PERMISSION_P
9423
9467
  * `sandbox_workspace_write`, `apps`, `approvals_reviewer`, `auto_review`,
9424
9468
  * `tui`) are emitted, and
9425
9469
  * `computeCodexcliOverridePatch` skips anything else with a warning.
9426
- * `base_permission_profile` and `git_write_rules` are consumed by the profile
9427
- * builder rather than written, as described above, and `permission` is the
9470
+ * `base_permission_profile`, `git_write_rules` and `bash_canonical_matching`
9471
+ * are consumed by the generators rather than written, as described above, and `permission` is the
9428
9472
  * tool-scoped canonical block, which `RulesyncPermissions.forTarget` strips out
9429
9473
  * of the override before it ever reaches the patch. The allowlist is what keeps
9430
9474
  * the override from clobbering a feature-owned key: `mcp_servers.*` per-MCP
@@ -9481,7 +9525,8 @@ const CodexcliPermissionsOverrideSchema = zod_mini.z.looseObject({
9481
9525
  * @see https://developers.openai.com/codex/config-reference
9482
9526
  */
9483
9527
  tui: zod_mini.z.optional(zod_mini.z.looseObject({})),
9484
- git_write_rules: zod_mini.z.optional(zod_mini.z.boolean())
9528
+ git_write_rules: zod_mini.z.optional(zod_mini.z.boolean()),
9529
+ bash_canonical_matching: zod_mini.z.optional(zod_mini.z.boolean())
9485
9530
  });
9486
9531
  /**
9487
9532
  * Tool-scoped override block for Zed. These Zed `agent` keys sit outside the
@@ -9565,6 +9610,14 @@ const ZedPermissionsOverrideSchema = zod_mini.z.looseObject({
9565
9610
  * { "sandbox": { "excluded": { "allow": ["Exec(git status *)"], "deny": ["Exec(git tag *)"] } } }
9566
9611
  * @example
9567
9612
  * { "forbiddenPlugins": ["*"], "optionalPlugins": ["acme/approved"] }
9613
+ *
9614
+ * `permission_mode` (CLI v3000.12.17+) is the mode new local sessions start in
9615
+ * (`normal`, the upstream default, `accept-edits`, `smart` or `dangerous`).
9616
+ * Like `sandbox` it is a **User Config Only** key, so it is emitted at global
9617
+ * scope only. It is never derived from the canonical rules.
9618
+ *
9619
+ * @example
9620
+ * { "permission_mode": "accept-edits" }
9568
9621
  * @see https://docs.devin.ai/cli/sandbox
9569
9622
  * @see https://docs.devin.ai/cli/reference/configuration/config-file
9570
9623
  * @see https://docs.devin.ai/cli/extensibility/plugins/overview
@@ -9580,12 +9633,25 @@ const DEVIN_PLUGIN_GOVERNANCE_SCHEMAS = {
9580
9633
  optionalPlugins: DevinPluginSourceListSchema,
9581
9634
  forbiddenPlugins: zod_mini.z.array(zod_mini.z.string())
9582
9635
  };
9636
+ /**
9637
+ * Values Devin accepts for the user-config `permission_mode` key. Shared by the
9638
+ * override schema and the import, which drops a value that would not pass it.
9639
+ *
9640
+ * @see https://docs.devin.ai/cli/reference/configuration/config-file
9641
+ */
9642
+ const DevinPermissionModeSchema = zod_mini.z.enum([
9643
+ "normal",
9644
+ "accept-edits",
9645
+ "smart",
9646
+ "dangerous"
9647
+ ]);
9583
9648
  const DevinPermissionsOverrideSchema = zod_mini.z.looseObject({
9584
9649
  permission: zod_mini.z.optional(ToolScopedPermissionSchema),
9585
9650
  sandbox: zod_mini.z.optional(zod_mini.z.looseObject({})),
9586
9651
  requiredPlugins: zod_mini.z.optional(DEVIN_PLUGIN_GOVERNANCE_SCHEMAS.requiredPlugins),
9587
9652
  optionalPlugins: zod_mini.z.optional(DEVIN_PLUGIN_GOVERNANCE_SCHEMAS.optionalPlugins),
9588
- forbiddenPlugins: zod_mini.z.optional(DEVIN_PLUGIN_GOVERNANCE_SCHEMAS.forbiddenPlugins)
9653
+ forbiddenPlugins: zod_mini.z.optional(DEVIN_PLUGIN_GOVERNANCE_SCHEMAS.forbiddenPlugins),
9654
+ permission_mode: zod_mini.z.optional(DevinPermissionModeSchema)
9589
9655
  });
9590
9656
  /**
9591
9657
  * Permissions configuration.
@@ -11997,6 +12063,98 @@ function resolveStandardSkillFields({ rootFrontmatter, section }) {
11997
12063
  })
11998
12064
  });
11999
12065
  }
12066
+ // src/utils/remote-name.ts
12067
+ /**
12068
+ * Name checks for a directory or file name chosen by a remote source (a
12069
+ * fetched repository, an installed git, GitHub or npm source). Shared by
12070
+ * `rulesync fetch` and `rulesync install`, so a name one of them turns away is
12071
+ * not written, or printed raw, by the other.
12072
+ */
12073
+ /** A name with no character in it that draws anything of its own. */
12074
+ const NOTHING_DRAWN_PATTERN = /^[\s\p{M}]*$/u;
12075
+ /**
12076
+ * The marks a name begins with. A mark is drawn over the character before it,
12077
+ * and a name has nothing before it of its own: a leading one is drawn over
12078
+ * whatever the terminal printed last — the checkbox, the quote around a name
12079
+ * in a warning — while the name reads as if it began with its first letter.
12080
+ */
12081
+ const LEADING_MARKS_PATTERN = /^\p{M}+/u;
12082
+ /**
12083
+ * A name ending in a dot or an ASCII space, which Win32 strips before it opens
12084
+ * the path. Only the plain space (U+0020): Win32 keeps every other trailing
12085
+ * blank, so a name ending in a no-break or an ideographic space is written
12086
+ * where it says, and is left to the whitespace note of the confusable-name
12087
+ * check rather than dropped here with Windows named as the reason.
12088
+ */
12089
+ const TRAILING_DOT_OR_SPACE_PATTERN = /[. ]$/;
12090
+ /** A name ending in the `NAME~1` shape of a Windows 8.3 short name, extension included. */
12091
+ const SHORT_NAME_ALIAS_PATTERN = /~\d+(?:\.[^.]*)?$/;
12092
+ /**
12093
+ * A name Win32 reserves for a device — `CON`, `PRN`, `AUX`, `NUL`, `CONIN$`,
12094
+ * `CONOUT$`, `COM1`–`COM9`, `LPT1`–`LPT9` — in any case and with any
12095
+ * extension: `nul.md` is the null device too, since the reservation is decided
12096
+ * on the part before the first dot, with any spaces before that dot dropped
12097
+ * first, so `nul .md` is the null device as well. The port digit may also be
12098
+ * one of the superscript digits ¹ ² ³, which Win32 reads as 1, 2 and 3
12099
+ * (`RtlIsDosDeviceName_U`; CPython's `ntpath.isreserved` follows the same
12100
+ * rules).
12101
+ */
12102
+ const RESERVED_DEVICE_NAME_PATTERN = /^(?:CON|PRN|AUX|NUL|CONIN\$|CONOUT\$|COM[1-9\u00B9\u00B2\u00B3]|LPT[1-9\u00B9\u00B2\u00B3]) *(?:\..*)?$/i;
12103
+ /**
12104
+ * Whether Windows resolves a path segment to something other than the entry it
12105
+ * reads as.
12106
+ *
12107
+ * Win32 drops a trailing dot or ASCII space when it resolves a path, so a remote
12108
+ * `skills/deploy.` is the existing `skills/deploy` there. A name ending in the
12109
+ * `NAME~1` shape is the same class of problem: on a volume that generates
12110
+ * short names, it opens whatever long name it stands for. The shape only
12111
+ * means that at the end of a name, so `data~2parser` and `v1.0` are ordinary
12112
+ * names. A reserved device name is the extreme case: `nul` and `nul.md` are
12113
+ * not entries in any directory but the null device itself, so a write to one
12114
+ * lands nowhere, and a directory of that name cannot be created at all.
12115
+ *
12116
+ * The predicate is asked of every segment of a written path — the skill
12117
+ * directory, but equally a nested `references/notes. ` or a `scripts/con.sh`
12118
+ * — since a folded segment anywhere in a path lands the file beside, or on top
12119
+ * of, a sibling the repository never published. The check is not gated on the
12120
+ * platform: the same repository is checked out on several of them, and a name
12121
+ * that lands somewhere else on any one of them is one this tool would rather
12122
+ * turn away everywhere than write differently depending on where it runs.
12123
+ */
12124
+ function hasWindowsFoldableName(name) {
12125
+ return TRAILING_DOT_OR_SPACE_PATTERN.test(name) || SHORT_NAME_ALIAS_PATTERN.test(name) || RESERVED_DEVICE_NAME_PATTERN.test(name);
12126
+ }
12127
+ /**
12128
+ * Whether a remote name is safe to write and to print as it is.
12129
+ *
12130
+ * A name of nothing but blank space is shown as the empty string, the same as
12131
+ * one that strips down to nothing: both draw as a row with no name on it. So
12132
+ * is a name of nothing but combining marks, which have no character of their
12133
+ * own to sit on and draw as a smear over whatever the terminal puts beside
12134
+ * them. A name that merely begins with a mark is turned away for the same
12135
+ * reason, and shown without it: the mark sits on nothing the name owns. A name
12136
+ * carrying control characters (an ANSI, C1 or OSC sequence) or deceptive
12137
+ * zero-width characters is turned away too, so it can neither rewrite the
12138
+ * terminal nor pass for another name. The Windows-folding check comes after
12139
+ * the hidden characters, so a name that is both is reported by the reason that
12140
+ * keeps its raw form off the terminal.
12141
+ */
12142
+ function classifyRemoteName(name) {
12143
+ const stripped = stripHiddenCharacters(name);
12144
+ const beginsWithMark = LEADING_MARKS_PATTERN.test(stripped);
12145
+ const display = NOTHING_DRAWN_PATTERN.test(stripped) ? "" : stripped.replace(LEADING_MARKS_PATTERN, "");
12146
+ if (display === "" || beginsWithMark || hasDeceptiveHiddenCharacters(name)) return {
12147
+ kind: "unsafe",
12148
+ display,
12149
+ reason: "hidden"
12150
+ };
12151
+ if (hasWindowsFoldableName(name)) return {
12152
+ kind: "unsafe",
12153
+ display,
12154
+ reason: "foldable"
12155
+ };
12156
+ return { kind: "safe" };
12157
+ }
12000
12158
  // src/features/rules/instruction-budget.ts
12001
12159
  /**
12002
12160
  * Normalizes a relative directory path for comparison: POSIX separators, no
@@ -13884,7 +14042,11 @@ const SHARED_CONFIG_OWNERSHIP = {
13884
14042
  },
13885
14043
  permissions: {
13886
14044
  kind: "replace-owned-keys",
13887
- ownedKeys: ["permissions", "sandbox"]
14045
+ ownedKeys: [
14046
+ "permissions",
14047
+ "sandbox",
14048
+ "permission_mode"
14049
+ ]
13888
14050
  }
13889
14051
  }
13890
14052
  },
@@ -14658,6 +14820,16 @@ var RulesyncSourceConsumer = class {
14658
14820
  this.dryRun = dryRun;
14659
14821
  this.logger = logger;
14660
14822
  }
14823
+ /**
14824
+ * Whether the orphan sweep may follow a symbolic link that stays inside the
14825
+ * output root. Only global scope answers true: its root is the operator's
14826
+ * own home directory, where a dotfiles checkout linked in (`~/.claude ->
14827
+ * ~/dotfiles/claude`) is a common shape. A project checkout may carry links
14828
+ * its author committed, so the default refuses them.
14829
+ */
14830
+ sweepsThroughInRootLinks() {
14831
+ return false;
14832
+ }
14661
14833
  recordRulesyncSourceLoadFailure() {
14662
14834
  this.rulesyncSourceLoadFailed = true;
14663
14835
  }
@@ -14790,7 +14962,8 @@ var FeatureProcessor = class extends RulesyncSourceConsumer {
14790
14962
  refused = await refusesDeleteOutsideRoot({
14791
14963
  logger: this.logger,
14792
14964
  rootPath,
14793
- dirPath
14965
+ dirPath,
14966
+ allowInRootLinks: this.sweepsThroughInRootLinks()
14794
14967
  });
14795
14968
  refusedDirs.set(cacheKey, refused);
14796
14969
  }
@@ -14890,27 +15063,45 @@ function mergeByIdentity({ perRoot, identity }) {
14890
15063
  return order.map((key) => winnerByKey.get(key));
14891
15064
  }
14892
15065
  /**
14893
- * Whether a write to `targetPath` has to be refused because a link on the way
14894
- * there leads out of `rootPath`, warning about the refusal.
15066
+ * Why a write to `targetPath` has to be refused, or `null` when it may go
15067
+ * ahead: a link on the way there leads out of `rootPath`, or into
15068
+ * version-control metadata that the path as spelled does not name.
14895
15069
  *
14896
15070
  * A checked-out repository can carry a symbolic link at an output path
14897
- * (`AGENTS.md -> ~/.bashrc`, a tool directory linked to `/etc`), and a write
14898
- * through it would land wherever the link points. Every writer that lets the
14899
- * OS follow links — file, directory, and config-rewrite alike — asks this first
14900
- * so that one warning describes the one behavior.
15071
+ * (`AGENTS.md -> ~/.bashrc`, a tool directory linked to `/etc`, `CLAUDE.md ->
15072
+ * .git/config`), and a write through it would land wherever the link points.
15073
+ */
15074
+ async function writeRefusalReason({ rootPath, targetPath }) {
15075
+ const relativeLanding = await relativeWriteLanding({
15076
+ rootPath,
15077
+ targetPath
15078
+ });
15079
+ if (relativeLanding === null || pathEscapesRoot(relativeLanding)) return `it resolves outside ${quoteForLog(rootPath)} through a symbolic link`;
15080
+ if (landingEntersVcsMetadata({
15081
+ rootPath,
15082
+ targetPath,
15083
+ relativeLanding
15084
+ })) return "it resolves into version-control metadata through a symbolic link";
15085
+ return null;
15086
+ }
15087
+ /**
15088
+ * Whether a write to `targetPath` has to be refused (see
15089
+ * {@link writeRefusalReason}), warning about the refusal. Every writer that
15090
+ * lets the OS follow links — file, directory, and config-rewrite alike — asks
15091
+ * this first so that one warning describes the one behavior.
14901
15092
  */
14902
15093
  async function refusesWriteOutsideRoot({ logger, rootPath, targetPath }) {
14903
- if (!await writablePathEscapesRoot({
15094
+ const reason = await writeRefusalReason({
14904
15095
  rootPath,
14905
15096
  targetPath
14906
- })) return false;
14907
- logger.warn(`Refusing to write ${quoteForLog(targetPath)}: it resolves outside ${quoteForLog(rootPath)} through a symbolic link`);
15097
+ });
15098
+ if (reason === null) return false;
15099
+ logger.warn(`Refusing to write ${quoteForLog(targetPath)}: ${reason}`);
14908
15100
  return true;
14909
15101
  }
14910
15102
  /**
14911
- * Whether deleting the files in `dirPath` has to be refused because a link on
14912
- * the way to that directory leads out of `rootPath`, warning about the refusal
14913
- * once for the whole directory.
15103
+ * Why the orphan sweep has to leave the files in `dirPath` alone, or `null`
15104
+ * when it may delete them.
14914
15105
  *
14915
15106
  * Deletion candidates are enumerated without following links *inside* the
14916
15107
  * scanned directory, but the scanned directory itself is reached through
@@ -14919,13 +15110,40 @@ async function refusesWriteOutsideRoot({ logger, rootPath, targetPath }) {
14919
15110
  * an orphan. Only the directory is judged, never the file in it, because
14920
15111
  * removing a file that is itself a link unlinks the link where it is spelled
14921
15112
  * and never touches its target.
15113
+ *
15114
+ * Beyond the write rules, a project checkout is content another party may
15115
+ * control: a committed `.claude/rules -> ..` would make every untracked `*.md`
15116
+ * in the project read as an orphan. Unless `allowInRootLinks` (global scope,
15117
+ * where the root is the operator's own home directory) the swept directory
15118
+ * must therefore be the one its path spells, with no link on the way.
14922
15119
  */
14923
- async function refusesDeleteOutsideRoot({ logger, rootPath, dirPath }) {
14924
- if (!await writablePathEscapesRoot({
15120
+ async function sweepRefusalReason({ rootPath, dirPath, allowInRootLinks }) {
15121
+ const relativeLanding = await relativeWriteLanding({
14925
15122
  rootPath,
14926
15123
  targetPath: dirPath
14927
- })) return false;
14928
- logger.warn(`Refusing to delete files in ${quoteForLog(dirPath)}: it resolves outside ${quoteForLog(rootPath)} through a symbolic link`);
15124
+ });
15125
+ if (relativeLanding === null || pathEscapesRoot(relativeLanding)) return `it resolves outside ${quoteForLog(rootPath)} through a symbolic link`;
15126
+ if (landingEntersVcsMetadata({
15127
+ rootPath,
15128
+ targetPath: dirPath,
15129
+ relativeLanding
15130
+ })) return "it resolves into version-control metadata through a symbolic link";
15131
+ if (!allowInRootLinks && relativeLanding !== (0, node_path.relative)((0, node_path.resolve)(rootPath), (0, node_path.resolve)(dirPath))) return "it is reached through a symbolic link";
15132
+ return null;
15133
+ }
15134
+ /**
15135
+ * Whether deleting the files in `dirPath` has to be refused (see
15136
+ * {@link sweepRefusalReason}), warning about the refusal once for the whole
15137
+ * directory.
15138
+ */
15139
+ async function refusesDeleteOutsideRoot({ logger, rootPath, dirPath, allowInRootLinks }) {
15140
+ const reason = await sweepRefusalReason({
15141
+ rootPath,
15142
+ dirPath,
15143
+ allowInRootLinks
15144
+ });
15145
+ if (reason === null) return false;
15146
+ logger.warn(`Refusing to delete files in ${quoteForLog(dirPath)}: ${reason}`);
14929
15147
  return true;
14930
15148
  }
14931
15149
  /**
@@ -22636,6 +22854,9 @@ const commandsProcessorToolTargetsGlobal = allToolTargetKeys$3.filter((target) =
22636
22854
  var CommandsProcessor = class extends FeatureProcessor {
22637
22855
  toolTarget;
22638
22856
  global;
22857
+ sweepsThroughInRootLinks() {
22858
+ return this.global;
22859
+ }
22639
22860
  getFactory;
22640
22861
  flattenedCommandNaming;
22641
22862
  constructor({ outputRoot = process.cwd(), inputRoots, toolTarget, global = false, getFactory = defaultGetFactory$6, dryRun = false, flattenedCommandNaming = "basename", logger }) {
@@ -23207,6 +23428,15 @@ var DirFeatureProcessor = class extends RulesyncSourceConsumer {
23207
23428
  this.logger.warn(`Refusing to sweep ${quotedDirPath}: ${stripControlCharacters(formatError(error))}`);
23208
23429
  continue;
23209
23430
  }
23431
+ const sweepRefusal = await sweepRefusalReason({
23432
+ rootPath: this.outputRoot,
23433
+ dirPath,
23434
+ allowInRootLinks: this.sweepsThroughInRootLinks()
23435
+ });
23436
+ if (sweepRefusal !== null) {
23437
+ this.logger.warn(`Refusing to sweep ${quotedDirPath}: ${sweepRefusal}`);
23438
+ continue;
23439
+ }
23210
23440
  const generatedNames = /* @__PURE__ */ new Set();
23211
23441
  const mainFile = aiDir.getMainFile();
23212
23442
  if (mainFile) generatedNames.add(toPosixPath(mainFile.name));
@@ -25290,6 +25520,8 @@ const CRUSH_CONFIG_FILE_NAME = "crush.json";
25290
25520
  const CRUSH_HIDDEN_CONFIG_FILE_NAME = ".crush.json";
25291
25521
  const CRUSH_PERMISSIONS_KEY = "permissions";
25292
25522
  const CRUSH_ALLOWED_TOOLS_KEY = "allowed_tools";
25523
+ const CRUSH_SAFE_COMMANDS_KEY = "safe_commands";
25524
+ const CRUSH_BLOCKED_COMMANDS_KEY = "blocked_commands";
25293
25525
  const CRUSH_OPTIONS_KEY = "options";
25294
25526
  const CRUSH_DISABLED_TOOLS_KEY = "disabled_tools";
25295
25527
  const CRUSH_HOOKS_KEY = "hooks";
@@ -29970,6 +30202,9 @@ var SkillsProcessor = class extends DirFeatureProcessor {
29970
30202
  global: this.global
29971
30203
  });
29972
30204
  }
30205
+ sweepsThroughInRootLinks() {
30206
+ return this.global;
30207
+ }
29973
30208
  /**
29974
30209
  * The tool's skills roots that exist on disk, each paired with its absolute
29975
30210
  * path and vetted as writable inside this run's output root. Shared by the
@@ -29999,6 +30234,15 @@ var SkillsProcessor = class extends DirFeatureProcessor {
29999
30234
  this.logger.warn(`Skipping the orphan sweep for ${quoteForLog(skillsDirPath)}; nothing under it is deleted: ${stripControlCharacters(formatError(error))}`);
30000
30235
  continue;
30001
30236
  }
30237
+ const sweepRefusal = await sweepRefusalReason({
30238
+ rootPath: this.outputRoot,
30239
+ dirPath: skillsDirPath,
30240
+ allowInRootLinks: this.sweepsThroughInRootLinks()
30241
+ });
30242
+ if (sweepRefusal !== null) {
30243
+ this.logger.warn(`Skipping the orphan sweep for ${quoteForLog(skillsDirPath)}; nothing under it is deleted: ${sweepRefusal}`);
30244
+ continue;
30245
+ }
30002
30246
  existingRoots.push({
30003
30247
  root,
30004
30248
  skillsDirPath
@@ -33225,11 +33469,17 @@ var FirebenderSubagent = class FirebenderSubagent extends ToolSubagent {
33225
33469
  */
33226
33470
  static async fromRulesyncSubagents({ outputRoot = process.cwd(), rulesyncSubagents, global = false, logger, deleteOrphans = false }) {
33227
33471
  const agentsDirPath = this.getSettablePaths({ global }).relativeDirPath;
33228
- const agentsDirEscapesRoot = await writablePathEscapesRoot({
33472
+ const agentsDirFullPath = (0, node_path.join)(outputRoot, agentsDirPath);
33473
+ const writeRefused = await writeRefusalReason({
33229
33474
  rootPath: outputRoot,
33230
- targetPath: (0, node_path.join)(outputRoot, agentsDirPath, "agent.md")
33231
- });
33232
- const existingAgentFileNames = new Set(agentsDirEscapesRoot ? [] : await listDirectoryEntryNames((0, node_path.join)(outputRoot, agentsDirPath)));
33475
+ targetPath: (0, node_path.join)(agentsDirFullPath, "agent.md")
33476
+ }) !== null;
33477
+ const sweepRefused = deleteOrphans && await sweepRefusalReason({
33478
+ rootPath: outputRoot,
33479
+ dirPath: agentsDirFullPath,
33480
+ allowInRootLinks: global
33481
+ }) !== null;
33482
+ const existingAgentFileNames = new Set(writeRefused ? [] : await listDirectoryEntryNames(agentsDirFullPath));
33233
33483
  const subagents = rulesyncSubagents.map((rulesyncSubagent) => this.fromRulesyncSubagent({
33234
33484
  outputRoot,
33235
33485
  relativeDirPath: this.getSettablePaths({ global }).relativeDirPath,
@@ -33245,8 +33495,8 @@ var FirebenderSubagent = class FirebenderSubagent extends ToolSubagent {
33245
33495
  global
33246
33496
  })),
33247
33497
  existingAgentFileNames,
33248
- deleteOrphans,
33249
- frozen: agentsDirEscapesRoot,
33498
+ deleteOrphans: deleteOrphans && !sweepRefused,
33499
+ frozen: writeRefused,
33250
33500
  global,
33251
33501
  logger
33252
33502
  });
@@ -37364,6 +37614,9 @@ function compareRelativePathsShallowestFirst(left, right) {
37364
37614
  var SubagentsProcessor = class extends FeatureProcessor {
37365
37615
  toolTarget;
37366
37616
  global;
37617
+ sweepsThroughInRootLinks() {
37618
+ return this.global;
37619
+ }
37367
37620
  deleteOrphans;
37368
37621
  getFactory;
37369
37622
  /**
@@ -38085,6 +38338,39 @@ function warnAndSkipMcpServer({ toolName, serverName, reason, logger }) {
38085
38338
  return null;
38086
38339
  }
38087
38340
  /**
38341
+ * Drops every server whose `enabledTools` allowlist is empty, warning about
38342
+ * each one, for a tool that reads an empty (or missing) allowlist as "no
38343
+ * filter". Canonically an empty allowlist allows no tools at all, so emitting
38344
+ * the server unfiltered would expose every tool it reports. With
38345
+ * `ignoreBlankNames`, blank entries count as absent, for a tool that drops
38346
+ * them before applying the list. `productName` names the tool in the reason
38347
+ * when it differs from the `toolName` the warning starts with.
38348
+ */
38349
+ function skipServersWithEmptyEnabledTools({ mcpServers, toolName, logger, ignoreBlankNames = false, productName = toolName }) {
38350
+ const kept = {};
38351
+ for (const [name, server] of Object.entries(mcpServers)) {
38352
+ const { enabledTools } = server;
38353
+ if (Array.isArray(enabledTools)) {
38354
+ if ((ignoreBlankNames ? enabledTools.filter((tool) => typeof tool !== "string" || tool.trim() !== "") : enabledTools).length === 0) {
38355
+ warnAndSkipMcpServer({
38356
+ toolName,
38357
+ serverName: name,
38358
+ reason: `an empty enabledTools list, which allows no tools at all but which ${productName} treats as no filter`,
38359
+ logger
38360
+ });
38361
+ continue;
38362
+ }
38363
+ }
38364
+ Object.defineProperty(kept, name, {
38365
+ value: server,
38366
+ enumerable: true,
38367
+ writable: true,
38368
+ configurable: true
38369
+ });
38370
+ }
38371
+ return kept;
38372
+ }
38373
+ /**
38088
38374
  * The `tools` map Kilo and OpenCode keep beside `mcp` is keyed `<server>_<tool>`
38089
38375
  * and reaches servers `mcp` does not list — ones the global config or a
38090
38376
  * marketplace defines — so entries naming no listed
@@ -38646,7 +38932,11 @@ var KiloMcp = class KiloMcp extends ToolMcp {
38646
38932
  const existingMcp = readExistingKiloMcpEntries(fileContent);
38647
38933
  const parsedExisting = (0, jsonc_parser.parse)(fileContent || "{}");
38648
38934
  const existingDocument = isRecord(parsedExisting) ? parsedExisting : {};
38649
- const mcpServers = rulesyncMcp.getMcpServers();
38935
+ const mcpServers = skipServersWithEmptyEnabledTools({
38936
+ mcpServers: rulesyncMcp.getMcpServers(),
38937
+ toolName: "Kilo",
38938
+ logger
38939
+ });
38650
38940
  const { mcp: convertedMcp, toolPermissions } = convertToKiloFormat(resolveKiloEnvVarRefs({
38651
38941
  mcpServers,
38652
38942
  global,
@@ -38775,7 +39065,8 @@ const OPENCODE_PASSTHROUGH_SERVER_FIELDS = [
38775
39065
  "timeout",
38776
39066
  "oauth",
38777
39067
  "protocol",
38778
- "codemode"
39068
+ "codemode",
39069
+ "pool"
38779
39070
  ];
38780
39071
  const OPENCODE_MCP_TRANSPORT_KEYS = [
38781
39072
  ...Object.keys(OpencodeMcpLocalServerSchema.def.shape),
@@ -38938,7 +39229,7 @@ function warnAboutToggleDroppedKeys(serverName, serverConfig, logger) {
38938
39229
  * - env -> environment
38939
39230
  * - disabled -> enabled (inverted)
38940
39231
  * - enabledTools/disabledTools -> top-level tools map (with server name prefix)
38941
- * - OpenCode-supported extras (timeout, oauth, protocol, codemode) -> passed through verbatim
39232
+ * - OpenCode-supported extras (timeout, oauth, protocol, codemode, pool) -> passed through verbatim
38942
39233
  */
38943
39234
  function convertServerToOpencodeFormat(serverName, serverConfig, existingEntry, configShape, logger) {
38944
39235
  const serverRecord = serverConfig;
@@ -39178,7 +39469,11 @@ var OpencodeMcp = class extends ToolMcp {
39178
39469
  if (fileContent) relativeFilePath = this.layout.jsonFileName;
39179
39470
  }
39180
39471
  const transformedServers = convertEnvVarRefsToToolFormat({
39181
- mcpServers: rulesyncMcp.getMcpServers(),
39472
+ mcpServers: skipServersWithEmptyEnabledTools({
39473
+ mcpServers: rulesyncMcp.getMcpServers(),
39474
+ toolName: "OpenCode",
39475
+ logger
39476
+ }),
39182
39477
  replacement: "{env:$1}"
39183
39478
  });
39184
39479
  const existingJson = (0, jsonc_parser.parse)(fileContent || "{}");
@@ -48774,6 +49069,9 @@ var RulesProcessor = class extends FeatureProcessor {
48774
49069
  language;
48775
49070
  deriveSubprojectPathFromGlobs;
48776
49071
  global;
49072
+ sweepsThroughInRootLinks() {
49073
+ return this.global;
49074
+ }
48777
49075
  getFactory;
48778
49076
  skills;
48779
49077
  featureOptions;
@@ -51358,12 +51656,29 @@ var HermesagentCheck = class HermesagentCheck extends ToolCheck {
51358
51656
  };
51359
51657
  }
51360
51658
  }
51659
+ /**
51660
+ * The `.rulesync/checks/<stem>.md` name an imported spec gets. The slug is
51661
+ * read from a spec file that may come from a fetched or cloned repository,
51662
+ * so it is kept as written only when it is a single plain file name; a slug
51663
+ * such as `../../docs/OPERATOR` would otherwise move the write out of
51664
+ * `.rulesync/checks/`. Anything else is slugified, and an empty result falls
51665
+ * back to the spec file's own name.
51666
+ */
51667
+ importedCheckStem(slug) {
51668
+ const isPlainFileName = (name) => name !== "" && name !== "." && name !== ".." && !/[/\\<>:"|?*]/.test(name) && !hasWindowsFoldableName(name) && stripControlCharacters(name) === name;
51669
+ if (isPlainFileName(slug)) return slug;
51670
+ for (const candidate of [slugifyCheckName(slug), slugifyCheckName((0, node_path.basename)(this.relativeFilePath, ".json"))]) {
51671
+ if (candidate === "") continue;
51672
+ return isPlainFileName(candidate) ? candidate : `${candidate}-check`;
51673
+ }
51674
+ return "check";
51675
+ }
51361
51676
  toRulesyncCheck() {
51362
51677
  const spec = HermesCheckSpecSchema.parse(JSON.parse(this.fileContent));
51363
51678
  return new RulesyncCheck({
51364
51679
  outputRoot: ".",
51365
51680
  relativeDirPath: RULESYNC_CHECKS_RELATIVE_DIR_PATH,
51366
- relativeFilePath: `${spec.slug}.md`,
51681
+ relativeFilePath: `${this.importedCheckStem(spec.slug)}.md`,
51367
51682
  frontmatter: {
51368
51683
  targets: ["*"],
51369
51684
  description: spec.description,
@@ -51871,6 +52186,9 @@ const checksProcessorToolTargetsGlobal = allToolTargetKeys.filter((target) => {
51871
52186
  var ChecksProcessor = class extends FeatureProcessor {
51872
52187
  toolTarget;
51873
52188
  global;
52189
+ sweepsThroughInRootLinks() {
52190
+ return this.global;
52191
+ }
51874
52192
  getFactory;
51875
52193
  constructor({ outputRoot = process.cwd(), inputRoots, toolTarget, global = false, getFactory = defaultGetFactory$2, dryRun = false, logger }) {
51876
52194
  super({
@@ -54182,6 +54500,10 @@ function definingFields({ h, rawEntry, hookType, converterConfig }) {
54182
54500
  field: "tool",
54183
54501
  value: h.tool
54184
54502
  });
54503
+ for (const { canonical, tool } of converterConfig.stringPassthroughFields ?? []) if (canonical === "if" && h[tool] !== "") fields.push({
54504
+ field: "if",
54505
+ value: h[tool]
54506
+ });
54185
54507
  return fields;
54186
54508
  }
54187
54509
  /**
@@ -62958,10 +63280,12 @@ function emittedEventsWithHook(params) {
62958
63280
  function converterCapabilities(config) {
62959
63281
  if (!config.supportedHookTypes) throw new Error("Hooks converter config must declare its supportedHookTypes");
62960
63282
  const passesThroughEnabled = (config.booleanPassthroughFields ?? []).some((field) => field.canonical === "enabled");
63283
+ const passesThroughIf = (config.stringPassthroughFields ?? []).some((field) => field.canonical === "if") && !(config.skippedWhenFields ?? []).includes("if");
62961
63284
  return {
62962
63285
  supportedEvents: config.supportedEvents,
62963
63286
  supportedHookTypes: [...config.supportedHookTypes],
62964
- ...passesThroughEnabled ? { supportsPerHookEnabled: true } : {}
63287
+ ...passesThroughEnabled ? { supportsPerHookEnabled: true } : {},
63288
+ ...passesThroughIf ? { supportsPerHookIf: true } : {}
62965
63289
  };
62966
63290
  }
62967
63291
  const toolHooksFactories = /* @__PURE__ */ new Map([
@@ -63606,6 +63930,9 @@ const hooksProcessorToolTargetsGlobalImportable = [...toolHooksFactories.entries
63606
63930
  var HooksProcessor = class extends FeatureProcessor {
63607
63931
  toolTarget;
63608
63932
  global;
63933
+ sweepsThroughInRootLinks() {
63934
+ return this.global;
63935
+ }
63609
63936
  preserveUnownedHooks;
63610
63937
  constructor({ outputRoot = process.cwd(), inputRoots, toolTarget, global = false, dryRun = false, preserveUnownedHooks = false, logger }) {
63611
63938
  super({
@@ -63684,7 +64011,8 @@ var HooksProcessor = class extends FeatureProcessor {
63684
64011
  if (!factory) throw new Error(`Unsupported tool target: ${this.toolTarget}`);
63685
64012
  const config = rulesyncHooks.getJson();
63686
64013
  const sharedHooks = config.hooks;
63687
- const overrideHooks = config[HOOKS_OVERRIDE_KEY_ALIASES[this.toolTarget] ?? this.toolTarget]?.hooks ?? {};
64014
+ const overrideKey = HOOKS_OVERRIDE_KEY_ALIASES[this.toolTarget] ?? this.toolTarget;
64015
+ const overrideHooks = config[overrideKey]?.hooks ?? {};
63688
64016
  const effectiveHooks = {
63689
64017
  ...sharedHooks,
63690
64018
  ...overrideHooks
@@ -63722,7 +64050,10 @@ var HooksProcessor = class extends FeatureProcessor {
63722
64050
  if (eventsWithUnsupportedMatcher.length > 0) this.logger.warn(`Skipped matcher hook(s) for ${this.toolTarget} (not supported): ${eventsWithUnsupportedMatcher.join(", ")}`);
63723
64051
  const toolHooks = await factory.class.fromRulesyncHooks({
63724
64052
  outputRoot: this.outputRoot,
63725
- rulesyncHooks,
64053
+ rulesyncHooks: factory.supportsPerHookIf ? rulesyncHooks : this.withoutConditionalHooks({
64054
+ rulesyncHooks,
64055
+ overrideKey
64056
+ }),
63726
64057
  validate: true,
63727
64058
  global: this.global,
63728
64059
  preserveUnowned: this.preserveUnownedHooks,
@@ -63745,6 +64076,53 @@ var HooksProcessor = class extends FeatureProcessor {
63745
64076
  return result;
63746
64077
  }
63747
64078
  /**
64079
+ * Returns the hooks source without the definitions that carry a per-hook
64080
+ * `if` condition, warning about each one. Used for targets that cannot
64081
+ * express `if`: emitting such a hook without its condition would make it
64082
+ * fire on every call its matcher selects, so a permission-granting hook
64083
+ * scoped by `if` would approve far more than its author meant.
64084
+ */
64085
+ withoutConditionalHooks(params) {
64086
+ const { rulesyncHooks, overrideKey } = params;
64087
+ const config = rulesyncHooks.getJson();
64088
+ const skipped = [];
64089
+ const filterHooks = (hooks) => {
64090
+ if (!isPlainObject(hooks)) return hooks;
64091
+ const filtered = {};
64092
+ for (const [event, defs] of Object.entries(hooks)) {
64093
+ if (!Array.isArray(defs)) {
64094
+ filtered[event] = defs;
64095
+ continue;
64096
+ }
64097
+ filtered[event] = defs.filter((def) => {
64098
+ const condition = isPlainObject(def) ? def.if : void 0;
64099
+ if (typeof condition !== "string" || condition.trim() === "") return true;
64100
+ skipped.push(`${event} (${quoteValueForWarning(condition)})`);
64101
+ return false;
64102
+ });
64103
+ }
64104
+ return filtered;
64105
+ };
64106
+ const filteredConfig = {
64107
+ ...config,
64108
+ hooks: filterHooks(config.hooks)
64109
+ };
64110
+ const override = config[overrideKey];
64111
+ if (Object.hasOwn(config, overrideKey) && isPlainObject(override)) filteredConfig[overrideKey] = {
64112
+ ...override,
64113
+ hooks: filterHooks(override.hooks)
64114
+ };
64115
+ if (skipped.length === 0) return rulesyncHooks;
64116
+ this.logger.warn(`Skipped hook(s) with an "if" condition for ${this.toolTarget} (only the ${targetsSupporting("supportsPerHookIf")} hooks formats support it, and without it the hook would run on every call its matcher selects): ${skipped.join(", ")}`);
64117
+ return new RulesyncHooks({
64118
+ outputRoot: rulesyncHooks.getOutputRoot(),
64119
+ relativeDirPath: rulesyncHooks.getRelativeDirPath(),
64120
+ relativeFilePath: rulesyncHooks.getRelativeFilePath(),
64121
+ fileContent: JSON.stringify(filteredConfig),
64122
+ validate: false
64123
+ });
64124
+ }
64125
+ /**
63748
64126
  * Warns about canonical per-hook fields that this target's hooks format
63749
64127
  * cannot express, so a hook does not silently change behavior on generation.
63750
64128
  * Only canonical definitions are considered: a tool-native field inside an
@@ -63989,6 +64367,35 @@ var BobIgnore = class extends PlainToolIgnore {
63989
64367
  };
63990
64368
  }
63991
64369
  };
64370
+ // src/features/ignore/claude-read-deny-pattern.ts
64371
+ /**
64372
+ * Translate the path of a Claude Code style `Read(<path>)` deny into the
64373
+ * gitignore syntax of `.rulesync/.aiignore`.
64374
+ *
64375
+ * Claude Code reads the path forms differently from gitignore: `./path` is
64376
+ * relative to the current directory, `/path` to the project root, `//path` is
64377
+ * absolute and `~/path` is under the home directory. Copied verbatim, the
64378
+ * common `Read(./.env)` idiom would become `./.env`, which matches nothing in
64379
+ * a gitignore-syntax ignore file, so every other tool would lose the deny.
64380
+ *
64381
+ * - `./path` is anchored to the project root as `/path`.
64382
+ * - `//path` and `~/path` (or a bare `~`) name locations a project-relative
64383
+ * ignore file cannot express; they are skipped with a warning and `null` is
64384
+ * returned.
64385
+ * - Every other path (`.env`, `secrets/**`, `/path`) already means the same
64386
+ * project files in gitignore syntax and is kept as is.
64387
+ */
64388
+ function claudeReadDenyPathToIgnorePattern({ path, toolLabel, logger }) {
64389
+ if (path.startsWith("//") || path === "~" || path.startsWith("~/")) {
64390
+ warnWithFallback(logger, `Skipping ${toolLabel} read deny ${quoteValueForWarning(path)} on ignore import: an absolute or home-directory path cannot be expressed in the project-relative .rulesync/.aiignore.`);
64391
+ return null;
64392
+ }
64393
+ if (path.startsWith("./")) {
64394
+ const rest = path.slice(2).replace(/^(?:\.\/)+/, "");
64395
+ return rest.length > 0 ? `/${rest}` : null;
64396
+ }
64397
+ return path;
64398
+ }
63992
64399
  // src/features/ignore/claudecode-ignore.ts
63993
64400
  const DEFAULT_FILE_MODE = "shared";
63994
64401
  /**
@@ -64047,9 +64454,12 @@ var ClaudecodeIgnore = class ClaudecodeIgnore extends ToolIgnore {
64047
64454
  }
64048
64455
  toRulesyncIgnore() {
64049
64456
  const fileContent = this.patterns.map((pattern) => {
64050
- if (isReadDenyEntry(pattern)) return pattern.slice(5, -1);
64457
+ if (isReadDenyEntry(pattern)) return claudeReadDenyPathToIgnorePattern({
64458
+ path: pattern.slice(5, -1),
64459
+ toolLabel: "Claude Code"
64460
+ });
64051
64461
  return pattern;
64052
- }).filter((pattern) => pattern.length > 0).join("\n");
64462
+ }).filter((pattern) => pattern !== null && pattern.length > 0).join("\n");
64053
64463
  return new RulesyncIgnore({
64054
64464
  outputRoot: this.outputRoot,
64055
64465
  relativeDirPath: RulesyncIgnore.getSettablePaths().recommended.relativeDirPath,
@@ -64324,7 +64734,7 @@ var FirebenderIgnore = class FirebenderIgnore extends ToolIgnore {
64324
64734
  const paths = this.getSettablePaths({ global });
64325
64735
  const filePath = (0, node_path.join)(outputRoot, paths.relativeDirPath, paths.relativeFilePath);
64326
64736
  const existingContent = await readFileContentOrNull(filePath) ?? "{}";
64327
- const managedPatterns = [...new Set(patterns)];
64737
+ const managedPatterns = patterns.filter((pattern, index) => patterns.lastIndexOf(pattern) === index);
64328
64738
  return new FirebenderIgnore({
64329
64739
  outputRoot,
64330
64740
  relativeDirPath: paths.relativeDirPath,
@@ -64979,7 +65389,10 @@ const asClaudeStyleSettings = (document) => {
64979
65389
  };
64980
65390
  /** The pattern of a `read_file(...)` (or legacy `Read(...)`) deny, else null. */
64981
65391
  const readDenyPatternOf = (entry) => {
64982
- for (const toolName of [REASONIX_READ_TOOL_NAME, REASONIX_LEGACY_READ_TOOL_NAME]) if (isReadDenyEntry(entry, toolName)) return entry.slice(toolName.length + 1, -1);
65392
+ for (const toolName of [REASONIX_READ_TOOL_NAME, REASONIX_LEGACY_READ_TOOL_NAME]) if (isReadDenyEntry(entry, toolName)) return claudeReadDenyPathToIgnorePattern({
65393
+ path: entry.slice(toolName.length + 1, -1),
65394
+ toolLabel: "Reasonix"
65395
+ });
64983
65396
  return null;
64984
65397
  };
64985
65398
  /**
@@ -65319,6 +65732,9 @@ var IgnoreProcessor = class extends FeatureProcessor {
65319
65732
  getFactory;
65320
65733
  featureOptions;
65321
65734
  global;
65735
+ sweepsThroughInRootLinks() {
65736
+ return this.global;
65737
+ }
65322
65738
  constructor({ outputRoot = process.cwd(), inputRoots, toolTarget, getFactory = defaultGetFactory$1, global = false, dryRun = false, logger, featureOptions }) {
65323
65739
  super({
65324
65740
  outputRoot,
@@ -65652,30 +66068,71 @@ function isEmptyValue(value) {
65652
66068
  if (Array.isArray(value)) return value.length === 0;
65653
66069
  return isPlainObject(value) && Object.keys(value).length === 0;
65654
66070
  }
66071
+ const MILLISECONDS_PER_SECOND$4 = 1e3;
65655
66072
  /**
65656
- * Antigravity uses `serverUrl` (not the canonical `url`) for HTTP/SSE MCP
66073
+ * Convert the canonical `timeout` (milliseconds) into Antigravity's
66074
+ * `timeoutSeconds` (integer seconds), rounding up so a sub-second timeout does
66075
+ * not become `0`. A negative value disables the timeout upstream, so it is
66076
+ * written as `-1`. An authored native `timeoutSeconds` wins over `timeout`.
66077
+ */
66078
+ function convertTimeoutToAntigravity({ serverName, config, logger }) {
66079
+ if (!("timeout" in config)) return config;
66080
+ const { timeout, ...rest } = config;
66081
+ if (rest.timeoutSeconds !== void 0) {
66082
+ logger?.warn(`Antigravity MCP: ${quoteValueForWarning(serverName)} sets both "timeout" and "timeoutSeconds"; keeping "timeoutSeconds" and dropping "timeout".`);
66083
+ return rest;
66084
+ }
66085
+ if (typeof timeout !== "number" || !Number.isFinite(timeout)) {
66086
+ logger?.warn(`Antigravity MCP: dropping the "timeout" of ${quoteValueForWarning(serverName)}: expected a number of milliseconds.`);
66087
+ return rest;
66088
+ }
66089
+ const timeoutSeconds = timeout < 0 ? -1 : Math.ceil(timeout / MILLISECONDS_PER_SECOND$4);
66090
+ return Object.fromEntries(Object.entries(config).map(([key, value]) => key === "timeout" ? ["timeoutSeconds", timeoutSeconds] : [key, value]));
66091
+ }
66092
+ /**
66093
+ * Antigravity uses `serverUrl` (not the canonical `url`) for remote MCP
65657
66094
  * servers. Convert the canonical shape into Antigravity's on the way out, and
65658
66095
  * back to canonical on the way in.
65659
66096
  *
65660
66097
  * Antigravity documents no `type` field: the transport follows from `command`
65661
- * (stdio) or `serverUrl` (Streamable HTTP / SSE), and `agy plugin validate`
66098
+ * (stdio) or `serverUrl` (Streamable HTTP), and `agy plugin validate`
65662
66099
  * reports the canonical `type` as an unknown field, so it is not written. A
65663
66100
  * remote server that carries `command`, `args` or `env` was also observed to be
65664
66101
  * refused at startup (runtime behavior reported by `agy plugin validate` 1.4.4,
65665
66102
  * not documented), so an empty `args` / `env` left on a `serverUrl` server is
65666
66103
  * dropped.
66104
+ *
66105
+ * Remote servers must use Streamable HTTP: the legacy HTTP+SSE transport is
66106
+ * not supported, so a canonical `sse` server is still written but warned
66107
+ * about. The canonical `timeout` (milliseconds) becomes `timeoutSeconds`.
65667
66108
  * https://antigravity.google/docs/mcp
65668
66109
  */
65669
- function toAntigravityMcpServers(servers) {
66110
+ function toAntigravityMcpServers(servers, logger) {
65670
66111
  const renamed = renameServerField(servers, "url", "serverUrl");
65671
66112
  return Object.fromEntries(Object.entries(renamed).map(([name, config]) => {
65672
66113
  if (!isPlainObject(config)) return [name, config];
66114
+ if (config.type === "sse" || config.transport === "sse") logger?.warn(`Antigravity MCP: ${quoteValueForWarning(name)} uses the SSE transport, which Antigravity does not support (remote servers must use Streamable HTTP); it is written as "serverUrl" and may fail to connect.`);
65673
66115
  const isRemote = typeof config.serverUrl === "string";
65674
- return [name, Object.fromEntries(Object.entries(config).filter(([key, value]) => key !== "type" && !(isRemote && (key === "args" || key === "env") && isEmptyValue(value))))];
66116
+ return [name, convertTimeoutToAntigravity({
66117
+ serverName: name,
66118
+ config: Object.fromEntries(Object.entries(config).filter(([key, value]) => key !== "type" && !(isRemote && (key === "args" || key === "env") && isEmptyValue(value)))),
66119
+ logger
66120
+ })];
65675
66121
  }));
65676
66122
  }
66123
+ /**
66124
+ * Convert Antigravity servers back to the canonical shape: `serverUrl` becomes
66125
+ * `url`, and `timeoutSeconds` becomes the canonical `timeout` in milliseconds
66126
+ * (a negative value, which disables the timeout upstream, stays `-1`).
66127
+ */
65677
66128
  function toCanonicalMcpServers(servers) {
65678
- return renameServerField(servers, "serverUrl", "url");
66129
+ const renamed = renameServerField(servers, "serverUrl", "url");
66130
+ return Object.fromEntries(Object.entries(renamed).map(([name, config]) => {
66131
+ if (!isPlainObject(config) || typeof config.timeoutSeconds !== "number") return [name, config];
66132
+ const timeoutSeconds = config.timeoutSeconds;
66133
+ const timeout = timeoutSeconds < 0 ? -1 : timeoutSeconds * MILLISECONDS_PER_SECOND$4;
66134
+ return [name, Object.fromEntries(Object.entries(config).filter(([key]) => key !== "timeout").map(([key, value]) => key === "timeoutSeconds" ? ["timeout", timeout] : [key, value]))];
66135
+ }));
65679
66136
  }
65680
66137
  /**
65681
66138
  * Parse `mcp_config.json` as JSONC and require a top-level object, so a file
@@ -65693,7 +66150,8 @@ function parseAntigravityMcpConfig(fileContent) {
65693
66150
  * the IDE and the CLI.
65694
66151
  *
65695
66152
  * Antigravity writes a dedicated `mcp_config.json` whose `mcpServers` map lives
65696
- * at the top level (`disabledTools` per server is supported). Unlike Gemini
66153
+ * at the top level (`enabledTools` / `disabledTools` per server are supported
66154
+ * under the same names). Unlike Gemini
65697
66155
  * CLI's shared `settings.json`, this file is dedicated to MCP, so it is safely
65698
66156
  * deletable. HTTP servers use `serverUrl` rather than the canonical `url`, so
65699
66157
  * the field is translated in both directions.
@@ -65746,11 +66204,11 @@ var AntigravityMcp = class extends ToolMcp {
65746
66204
  global
65747
66205
  });
65748
66206
  }
65749
- static async fromRulesyncMcp({ outputRoot = process.cwd(), rulesyncMcp, validate = true, global = false }) {
66207
+ static async fromRulesyncMcp({ outputRoot = process.cwd(), rulesyncMcp, validate = true, global = false, logger }) {
65750
66208
  const paths = this.getSettablePaths({ global });
65751
66209
  const newJson = {
65752
66210
  ...parseAntigravityMcpConfig(await readFileContentOrNull((0, node_path.join)(outputRoot, paths.relativeDirPath, paths.relativeFilePath)) ?? JSON.stringify({ mcpServers: {} }, null, 2)),
65753
- mcpServers: toAntigravityMcpServers(rulesyncMcp.getMcpServers())
66211
+ mcpServers: toAntigravityMcpServers(rulesyncMcp.getMcpServers(), logger)
65754
66212
  };
65755
66213
  return new this({
65756
66214
  outputRoot,
@@ -69419,7 +69877,11 @@ var CrushMcp = class CrushMcp extends ToolMcp {
69419
69877
  ownedPaths: [["mcp"]],
69420
69878
  logger
69421
69879
  });
69422
- const converted = convertToCrushFormat(Object.fromEntries(Object.entries(rulesyncMcp.getMcpServers()).map(([serverName, serverConfig]) => [serverName, {
69880
+ const converted = convertToCrushFormat(Object.fromEntries(Object.entries(skipServersWithEmptyEnabledTools({
69881
+ mcpServers: rulesyncMcp.getMcpServers(),
69882
+ toolName: "Crush",
69883
+ logger
69884
+ })).map(([serverName, serverConfig]) => [serverName, {
69423
69885
  ...serverConfig,
69424
69886
  ...readCrushOnlyKeys({
69425
69887
  serverName,
@@ -70379,31 +70841,6 @@ var DshMcp = class DshMcp extends ToolMcp {
70379
70841
  };
70380
70842
  // src/features/mcp/factorydroid-mcp.ts
70381
70843
  const TOOL_NAME = "factorydroid";
70382
- /**
70383
- * Drop servers whose `enabledTools` allowlist is empty.
70384
- *
70385
- * Canonically an empty allowlist allows no tools, but Droid applies
70386
- * `enabledTools` only "when the list is non-empty"
70387
- * (https://docs.factory.com/harness/mcp), so writing `[]` would load every
70388
- * tool the server reports. Skipping the server is the only form that does not
70389
- * hand the model more tools than the canonical config allows.
70390
- */
70391
- function skipEmptyAllowlistServers({ mcpServers, logger }) {
70392
- const kept = {};
70393
- for (const [name, server] of Object.entries(mcpServers)) {
70394
- if (server.enabledTools?.length === 0) {
70395
- warnAndSkipMcpServer({
70396
- toolName: TOOL_NAME,
70397
- serverName: name,
70398
- reason: "an empty enabledTools list, which allows no tools at all but which Factory Droid treats as no filter",
70399
- logger
70400
- });
70401
- continue;
70402
- }
70403
- kept[name] = server;
70404
- }
70405
- return kept;
70406
- }
70407
70844
  var FactorydroidMcp = class FactorydroidMcp extends ToolMcp {
70408
70845
  json;
70409
70846
  constructor(params) {
@@ -70430,8 +70867,10 @@ var FactorydroidMcp = class FactorydroidMcp extends ToolMcp {
70430
70867
  });
70431
70868
  }
70432
70869
  static fromRulesyncMcp({ outputRoot = process.cwd(), rulesyncMcp, validate = true, logger }) {
70433
- const factorydroidConfig = { mcpServers: skipEmptyAllowlistServers({
70870
+ const factorydroidConfig = { mcpServers: skipServersWithEmptyEnabledTools({
70434
70871
  mcpServers: rulesyncMcp.getMcpServers(),
70872
+ toolName: TOOL_NAME,
70873
+ productName: "Factory Droid",
70435
70874
  logger
70436
70875
  }) };
70437
70876
  const fileContent = JSON.stringify(factorydroidConfig, null, 2);
@@ -71862,19 +72301,42 @@ function normalizeKimiCodeTransport({ transport, hasCommand }) {
71862
72301
  return hasCommand ? "stdio" : "http";
71863
72302
  }
71864
72303
  /**
71865
- * The only `executor` value Kimi Code accepts on a stdio server. 2.2.0 removed
71866
- * the never-implemented `kaos` option and narrowed the schema to
71867
- * `z.enum(['local'])`, so any other value makes Kimi fail validation when it
71868
- * loads `mcp.json`.
72304
+ * The only `executor` value every current Kimi Code release accepts on a stdio
72305
+ * server. 2.2.0 removed the never-implemented `kaos` option and narrowed the
72306
+ * schema to `z.enum(['local'])`, so 2.2.0 through 2.4.x fail validation on any
72307
+ * other value when they load `mcp.json`. 2.5.0 widened the enum back to
72308
+ * `'local' | 'kaos'`, but `kaos` is still undocumented and would break the
72309
+ * older releases, so it keeps being dropped.
71869
72310
  * @see https://github.com/MoonshotAI/kimi-code/pull/4184
72311
+ * @see https://github.com/MoonshotAI/kimi-code/pull/4062
71870
72312
  */
71871
72313
  const KIMI_CODE_MCP_EXECUTOR = "local";
71872
72314
  /** Remove, with a warning, an `executor` value Kimi Code would reject. Mutates `server`. */
71873
72315
  function dropUnsupportedKimiCodeExecutor({ name, server, logger }) {
71874
72316
  if (server.executor === void 0 || server.executor === KIMI_CODE_MCP_EXECUTOR) return;
71875
- warnWithFallback(logger, `Kimi Code MCP: dropping executor ${JSON.stringify(server.executor)} from "${name}" because Kimi Code only accepts "${KIMI_CODE_MCP_EXECUTOR}".`);
72317
+ warnWithFallback(logger, `Kimi Code MCP: dropping executor ${JSON.stringify(server.executor)} from "${name}" because Kimi Code 2.2.0 through 2.4.x accept only "${KIMI_CODE_MCP_EXECUTOR}".`);
71876
72318
  delete server.executor;
71877
72319
  }
72320
+ /**
72321
+ * Remove, with a warning, an `environment_id` Kimi Code cannot use. Kimi Code
72322
+ * 2.5.0 added it to stdio servers only, as a non-empty string naming an
72323
+ * `[environments.<id>]` entry of `config.toml`; an empty or non-string value
72324
+ * fails Kimi's validation. Mutates `server`.
72325
+ * @see https://github.com/MoonshotAI/kimi-code/pull/4062
72326
+ */
72327
+ function dropUnsupportedKimiCodeEnvironmentId({ name, server, isStdio, logger }) {
72328
+ const environmentId = server.environment_id;
72329
+ if (environmentId === void 0) return;
72330
+ if (!isStdio) {
72331
+ warnWithFallback(logger, `Kimi Code MCP: dropping environment_id from "${name}" because Kimi Code only accepts it on stdio servers.`);
72332
+ delete server.environment_id;
72333
+ return;
72334
+ }
72335
+ if (typeof environmentId !== "string" || environmentId.length === 0) {
72336
+ warnWithFallback(logger, `Kimi Code MCP: dropping environment_id ${JSON.stringify(environmentId)} from "${name}" because Kimi Code requires a non-empty string.`);
72337
+ delete server.environment_id;
72338
+ }
72339
+ }
71878
72340
  function toKimiCodeServer({ name, server, logger }) {
71879
72341
  const transport = server.transport ?? server.type;
71880
72342
  if (transport === "ws") {
@@ -71902,6 +72364,7 @@ function toKimiCodeServer({ name, server, logger }) {
71902
72364
  for (const field of [
71903
72365
  "env",
71904
72366
  "cwd",
72367
+ "environment_id",
71905
72368
  "executor",
71906
72369
  "runtime_id",
71907
72370
  "headers",
@@ -71918,6 +72381,12 @@ function toKimiCodeServer({ name, server, logger }) {
71918
72381
  server: converted,
71919
72382
  logger
71920
72383
  });
72384
+ dropUnsupportedKimiCodeEnvironmentId({
72385
+ name,
72386
+ server: converted,
72387
+ isStdio: normalizedTransport === "stdio",
72388
+ logger
72389
+ });
71921
72390
  if (server.disabled === true) converted.enabled = false;
71922
72391
  return converted;
71923
72392
  }
@@ -71942,6 +72411,15 @@ function fromKimiCodeServers({ servers, logger }) {
71942
72411
  logger
71943
72412
  });
71944
72413
  const type = transport === "stdio" || transport === "sse" || transport === "http" ? transport : void 0;
72414
+ dropUnsupportedKimiCodeEnvironmentId({
72415
+ name,
72416
+ server: rest,
72417
+ isStdio: normalizeKimiCodeTransport({
72418
+ transport,
72419
+ hasCommand: rest.command !== void 0
72420
+ }) === "stdio",
72421
+ logger
72422
+ });
71945
72423
  return [name, {
71946
72424
  ...rest,
71947
72425
  ...type && { type },
@@ -73110,7 +73588,12 @@ var OpenclawMcp = class OpenclawMcp extends ToolMcp {
73110
73588
  const existingMcp = isRecord(existing["mcp"]) ? existing["mcp"] : {};
73111
73589
  const existingServers = isRecord(existingMcp["servers"]) ? existingMcp[OPENCLAW_MCP_SERVERS_KEY] : {};
73112
73590
  const converted = convertToOpenclawFormat({
73113
- mcpServers: rulesyncMcp.getMcpServers(),
73591
+ mcpServers: skipServersWithEmptyEnabledTools({
73592
+ mcpServers: rulesyncMcp.getMcpServers(),
73593
+ toolName: "OpenClaw",
73594
+ ignoreBlankNames: true,
73595
+ logger
73596
+ }),
73114
73597
  logger
73115
73598
  });
73116
73599
  const servers = {
@@ -73738,7 +74221,11 @@ var PoolMcp = class PoolMcp extends ToolMcp {
73738
74221
  const paths = this.getSettablePaths({ global });
73739
74222
  const filePath = (0, node_path.join)(outputRoot, paths.relativeDirPath, paths.relativeFilePath);
73740
74223
  const existingContent = await readFileContentOrNull(filePath) ?? "";
73741
- const converted = convertToPoolFormat(Object.fromEntries(Object.entries(rulesyncMcp.getMcpServers()).map(([serverName, serverConfig]) => {
74224
+ const converted = convertToPoolFormat(Object.fromEntries(Object.entries(skipServersWithEmptyEnabledTools({
74225
+ mcpServers: rulesyncMcp.getMcpServers(),
74226
+ toolName: "Pool",
74227
+ logger
74228
+ })).map(([serverName, serverConfig]) => {
73742
74229
  const rawServer = rulesyncMcp.getRawMcpServer(serverName);
73743
74230
  const poolAllow = isRecord(rawServer) ? rawServer.poolAllow : void 0;
73744
74231
  return [serverName, {
@@ -77264,7 +77751,7 @@ const toolMcpFactories = /* @__PURE__ */ new Map([
77264
77751
  meta: {
77265
77752
  supportsProject: true,
77266
77753
  supportsGlobal: true,
77267
- supportsEnabledTools: false,
77754
+ supportsEnabledTools: true,
77268
77755
  supportsDisabledTools: true
77269
77756
  }
77270
77757
  }],
@@ -77273,7 +77760,7 @@ const toolMcpFactories = /* @__PURE__ */ new Map([
77273
77760
  meta: {
77274
77761
  supportsProject: true,
77275
77762
  supportsGlobal: true,
77276
- supportsEnabledTools: false,
77763
+ supportsEnabledTools: true,
77277
77764
  supportsDisabledTools: true
77278
77765
  }
77279
77766
  }],
@@ -77282,7 +77769,7 @@ const toolMcpFactories = /* @__PURE__ */ new Map([
77282
77769
  meta: {
77283
77770
  supportsProject: true,
77284
77771
  supportsGlobal: false,
77285
- supportsEnabledTools: false,
77772
+ supportsEnabledTools: true,
77286
77773
  supportsDisabledTools: true
77287
77774
  }
77288
77775
  }],
@@ -77849,6 +78336,9 @@ function warnStrippedMcpServerFields({ mcpServers, fields, toolTarget, logger })
77849
78336
  var McpProcessor = class extends FeatureProcessor {
77850
78337
  toolTarget;
77851
78338
  global;
78339
+ sweepsThroughInRootLinks() {
78340
+ return this.global;
78341
+ }
77852
78342
  getFactory;
77853
78343
  featureOptions;
77854
78344
  constructor({ outputRoot = process.cwd(), inputRoots, toolTarget, global = false, getFactory = defaultGetFactory, dryRun = false, logger, featureOptions }) {
@@ -78990,6 +79480,30 @@ function maxRangeCount(steps) {
78990
79480
  return most;
78991
79481
  }
78992
79482
  /**
79483
+ * Whether any one value matches both globs — that is, whether the two patterns
79484
+ * overlap at all. The answer is exact up to `MAX_INTERSECTION_CELLS`; a pair
79485
+ * longer than that is reported as overlapping without being compared, so a
79486
+ * caller that reads a `true` as a reason to restrict stays on the safe side and
79487
+ * one that would read it as a reason to permit must not use this. What a pair
79488
+ * costs counts the ranges a `[a-z]` class carries, not only the two lengths.
79489
+ *
79490
+ * This answers the question an adapter really has when it holds a restriction
79491
+ * and an `allow`: is there a command both of them name? Asking instead whether
79492
+ * either pattern covers the other's *text* misses the ordinary crossing pair —
79493
+ * `* --force` and `git *` cover none of each other's spellings, yet they share
79494
+ * every `git … --force` command.
79495
+ *
79496
+ * The two step lists are walked as a table rather than by backtracking, so no
79497
+ * input makes the time blow up the way a translated regex would. Only two rows
79498
+ * of that table are ever held, and the shorter pattern is the one that sizes
79499
+ * them, so the memory is linear in the shorter pattern however long the other
79500
+ * one is. Where a `[...]` class meets another `[...]` class the answer is
79501
+ * assumed to be yes, which over-reports rather than misses.
79502
+ */
79503
+ function globsIntersect(left, right) {
79504
+ return parsedGlobsIntersect(parseGlobPattern(left), parseGlobPattern(right));
79505
+ }
79506
+ /**
78993
79507
  * `globsIntersect` for two globs already parsed, optionally spending a budget
78994
79508
  * shared with the rest of the caller's run — see `createIntersectionBudget`.
78995
79509
  * Once that budget is exhausted every further pair answers `true` without being
@@ -79617,6 +80131,11 @@ function collectShellCommandRules(permission) {
79617
80131
  function widenToPrefixGlob$1(pattern) {
79618
80132
  return pattern.endsWith("*") ? pattern : `${pattern}*`;
79619
80133
  }
80134
+ function widenForOverlap(pattern) {
80135
+ if (/\{[^}]*,[^}]*\}/.test(pattern)) return "*";
80136
+ const widened = pattern.replaceAll("**/", "*").replaceAll("/**", "*");
80137
+ return widened.endsWith(" *") ? `${widened.slice(0, -2)}*` : widened;
80138
+ }
79620
80139
  /**
79621
80140
  * Build the test an adapter applies to an `allow` pattern before writing it:
79622
80141
  * which restrictions it cannot write name some of the same commands? The
@@ -79648,11 +80167,11 @@ function widenToPrefixGlob$1(pattern) {
79648
80167
  function createShadowingRestrictionsTest(restrictions, { normalizePattern = (pattern) => pattern, budget = createIntersectionBudget() } = {}) {
79649
80168
  const normalized = restrictions.map(({ pattern, fromAllToolsCategory }) => ({
79650
80169
  pattern,
79651
- glob: parseGlobPattern(fromAllToolsCategory ? pattern : normalizePattern(pattern))
80170
+ glob: parseGlobPattern(widenForOverlap(fromAllToolsCategory ? pattern : normalizePattern(pattern)))
79652
80171
  }));
79653
80172
  return (allowPattern) => {
79654
80173
  if (budget.remaining === 0) return normalized.map(({ pattern }) => pattern);
79655
- const allowGlob = parseGlobPattern(normalizePattern(allowPattern));
80174
+ const allowGlob = parseGlobPattern(widenForOverlap(normalizePattern(allowPattern)));
79656
80175
  return normalized.filter(({ pattern, glob }) => pattern === allowPattern || parsedGlobsIntersect(glob, allowGlob, budget)).map(({ pattern }) => pattern);
79657
80176
  };
79658
80177
  }
@@ -79815,6 +80334,336 @@ function honorAllToolsOnBash(permission) {
79815
80334
  bash: bashRulesHonoringAllTools(permission)
79816
80335
  };
79817
80336
  }
80337
+ // src/features/permissions/shadowed-allows.ts
80338
+ /** The canonical category whose patterns are URLs or domains. */
80339
+ const WEBFETCH_CATEGORY$2 = "webfetch";
80340
+ /**
80341
+ * A URL or domain pattern lowercased and without its scheme, so `HTTPS://Evil.example/*`
80342
+ * and `evil.example/*` are compared as the same host. Hosts are case-insensitive
80343
+ * and a scheme-less allow covers every scheme.
80344
+ */
80345
+ function normalizeUrlPattern(pattern) {
80346
+ return pattern.toLowerCase().replace(/^[a-z][a-z0-9+.-]*:\/\//, "");
80347
+ }
80348
+ /**
80349
+ * A URL pattern with its scheme stripped and only its host lowercased, for
80350
+ * writing it into a tool that matches paths case-sensitively (Copilot in VS
80351
+ * Code). A scheme spelled as a glob (a `*` scheme, `http*`, or a bare double
80352
+ * slash after a `*`) is stripped too.
80353
+ */
80354
+ function stripUrlSchemeKeepingPathCase(pattern) {
80355
+ const withoutScheme = pattern.replace(/^[a-z0-9+.*-]*:?\/\//i, "");
80356
+ const slash = withoutScheme.indexOf("/");
80357
+ return slash === -1 ? withoutScheme.toLowerCase() : `${withoutScheme.slice(0, slash).toLowerCase()}${withoutScheme.slice(slash)}`;
80358
+ }
80359
+ /** Split a lowercased, scheme-less URL or domain pattern into host, port and path. */
80360
+ function splitUrlPattern(pattern) {
80361
+ const normalized = stripUrlSchemeKeepingPathCase(pattern).toLowerCase();
80362
+ const slash = normalized.indexOf("/");
80363
+ const hostPort = slash === -1 ? normalized : normalized.slice(0, slash);
80364
+ const path = slash === -1 ? void 0 : normalized.slice(slash);
80365
+ const port = /:([0-9*]+)$/.exec(hostPort);
80366
+ return port === null ? {
80367
+ host: hostPort,
80368
+ port: void 0,
80369
+ path
80370
+ } : {
80371
+ host: hostPort.slice(0, port.index),
80372
+ port: port[1],
80373
+ path
80374
+ };
80375
+ }
80376
+ /**
80377
+ * Whether two URL or domain patterns can name one URL. Both are compared
80378
+ * lowercased and without their scheme, part by part, so a `*` in one part
80379
+ * never reaches into another (`*.github.com` does not overlap
80380
+ * `example.org/private/*`). A pathless pattern is a host, which domain-only
80381
+ * tools read as every URL on it, on any port, and on its subdomains, so a
80382
+ * missing path or port matches every path or port, and each host also stands
80383
+ * for `*.<host>`. Because a glob can also match across those parts, the
80384
+ * whole strings are compared as well, and an overlap from either counts. A
80385
+ * pattern holding whitespace names no URL.
80386
+ */
80387
+ function urlPatternsOverlap(left, right) {
80388
+ if (left === right) return true;
80389
+ if (/\s/.test(left) || /\s/.test(right)) return false;
80390
+ return urlPartsOverlap(left, right) || wholeStringsOverlap(left, right);
80391
+ }
80392
+ /**
80393
+ * The whole-string comparison a `*` restriction also gets, since a glob there
80394
+ * matches the whole URL (`*.pdf` names `https://example.com/doc.pdf`): the two
80395
+ * patterns compared as written and lowercased without a scheme, each widened
80396
+ * by `createShadowingRestrictionsTest`.
80397
+ */
80398
+ function wholeStringsOverlap(left, right) {
80399
+ return [[left, right], [normalizeUrlPattern(left), normalizeUrlPattern(right)]].some(([restriction = "", allow = ""]) => createShadowingRestrictionsTest([{
80400
+ pattern: restriction,
80401
+ fromAllToolsCategory: false
80402
+ }])(allow).length > 0);
80403
+ }
80404
+ function urlPartsOverlap(left, right) {
80405
+ const a = splitUrlPattern(left);
80406
+ const b = splitUrlPattern(right);
80407
+ const hosts = (host) => [host, `*.${host}`];
80408
+ if (!hosts(a.host).some((x) => hosts(b.host).some((y) => globsIntersect(x, y)))) return false;
80409
+ if (a.port !== void 0 && b.port !== void 0 && !globsIntersect(a.port, b.port)) return false;
80410
+ return a.path === void 0 || b.path === void 0 || globsIntersect(a.path, b.path);
80411
+ }
80412
+ /**
80413
+ * Whether any of `restrictions` overlaps an allow pattern of `category`. For
80414
+ * `webfetch` the patterns are compared as URLs (see `urlPatternsOverlap`).
80415
+ */
80416
+ function createCategoryShadowTest({ restrictions, category }) {
80417
+ if (category === WEBFETCH_CATEGORY$2) return (allowPattern) => restrictions.some(({ pattern }) => urlPatternsOverlap(pattern, allowPattern));
80418
+ const asWritten = createShadowingRestrictionsTest(restrictions);
80419
+ return (allowPattern) => asWritten(allowPattern).length > 0;
80420
+ }
80421
+ /** One allow rule left out of a tool's config, named as `<category>: <pattern>`. */
80422
+ function describeRule(category, pattern) {
80423
+ return `${category}: ${pattern}`;
80424
+ }
80425
+ /**
80426
+ * The `*` category with only its catch-all entries left, warning about the
80427
+ * pattern-specific ones dropped.
80428
+ */
80429
+ function keepAllToolsCatchAll({ rules, isCatchAll, toolLabel, logger }) {
80430
+ const kept = {};
80431
+ const dropped = [];
80432
+ for (const [pattern, action] of Object.entries(rules)) if (isCatchAll(pattern)) kept[pattern] = action;
80433
+ else dropped.push(`${pattern} (${action})`);
80434
+ if (dropped.length > 0) warnWithFallback(logger, `${toolLabel} has no rule that scopes a pattern to every tool, so the all-tools '*' rule(s) for ${dropped.join(", ")} were not written as such; a deny or ask among them is honored by withholding the allow rules it covers in the other categories.`);
80435
+ return kept;
80436
+ }
80437
+ /**
80438
+ * Apply the all-tools `*` category's restrictions to every other category, for
80439
+ * a tool that cannot write a pattern-specific rule spanning every tool.
80440
+ *
80441
+ * A `deny` or `ask` written under `*` covers every tool — `{"*": {".env":
80442
+ * "deny"}}` denies reading `.env` as surely as `{"read": {".env": "deny"}}`
80443
+ * does. A tool with no such rule would otherwise keep a `read: {"*": "allow"}`
80444
+ * beside it and auto-approve the very file the author denied. So:
80445
+ *
80446
+ * - `bash` gets the restrictions copied in, exactly as `honorAllToolsOnBash`
80447
+ * does, since a command list can carry them.
80448
+ * - Every other category loses each `allow` that names an input a `*`
80449
+ * restriction also names (see `createShadowingRestrictionsTest`); the tool
80450
+ * then falls back to its own prompt or default for it, the safe direction.
80451
+ * (AugmentCode instead applies its blanket all-tools fallback to a tool left
80452
+ * with no entries, since its own default would auto-run the tool.) Width
80453
+ * does not matter: a shell-only `{"*": {"git push *": "ask"}}` withholds a
80454
+ * `read: {"*": "allow"}` too, because the catch-all names every input.
80455
+ * - With `dropAllToolsPatterns`, the pattern-specific entries of `*` itself are
80456
+ * removed, for a tool that would otherwise write them as an inert literal
80457
+ * `*(<pattern>)` rule. They are honored by the withholding above.
80458
+ *
80459
+ * `restateAs` says which pattern-specific `*` restrictions the tool can write
80460
+ * as a rule of the category itself (`Read(.env)`), for a tool whose default for
80461
+ * an input with no rule would auto-approve it: such a restriction is copied
80462
+ * into each stated category it applies to (see `restatesAsCategoryRule`), so
80463
+ * the input stays restricted after its allow is withheld.
80464
+ * `downgradeWithheldCatchAll` writes a withheld catch-all `*` allow as `ask`
80465
+ * (`deny` under a catch-all `*` deny) rather than dropping it, for a tool that keeps a stale `always` otherwise.
80466
+ *
80467
+ * `writesAllToolsCatchAll` says the tool already enforces a `*` catch-all
80468
+ * (`{"*": {"*": "ask"}}`) natively over its per-tool allows, so the catch-all
80469
+ * is left out of the withholding. `isCatchAll` says which spellings the tool
80470
+ * reads as that catch-all (by default only `*`).
80471
+ *
80472
+ * Every withheld allow is named in one warning.
80473
+ */
80474
+ function honorAllToolsRestrictions({ permission, toolLabel, logger, writesAllToolsCatchAll = false, dropAllToolsPatterns = false, isCatchAll = (pattern) => pattern === "*", restateAs = () => false, downgradeWithheldCatchAll = false }) {
80475
+ const allToolsRules = Object.hasOwn(permission, "*") ? permission["*"] : void 0;
80476
+ if (allToolsRules === void 0) return permission;
80477
+ const restrictions = Object.entries(allToolsRules).filter(([pattern, action]) => action !== "allow" && !isPrototypePollutionKey(pattern) && !(writesAllToolsCatchAll && isCatchAll(pattern))).map(([pattern]) => ({
80478
+ pattern,
80479
+ fromAllToolsCategory: true
80480
+ }));
80481
+ const result = {};
80482
+ const withheld = [];
80483
+ for (const [category, rules] of Object.entries(permission)) {
80484
+ if (category === "*") {
80485
+ const kept = dropAllToolsPatterns ? keepAllToolsCatchAll({
80486
+ rules,
80487
+ isCatchAll,
80488
+ toolLabel,
80489
+ logger
80490
+ }) : rules;
80491
+ if (!dropAllToolsPatterns || Object.keys(kept).length > 0) result[category] = kept;
80492
+ continue;
80493
+ }
80494
+ if (restrictions.length === 0) {
80495
+ result[category] = rules;
80496
+ continue;
80497
+ }
80498
+ if (category === "bash") {
80499
+ const bash = bashRulesHonoringAllTools({
80500
+ ...permission,
80501
+ ["*"]: Object.fromEntries(restrictions.map(({ pattern }) => [pattern, allToolsRules[pattern] ?? "deny"]))
80502
+ });
80503
+ for (const [pattern, action] of Object.entries(rules)) if (action === "allow" && bash[pattern] !== "allow") withheld.push(describeRule(category, pattern));
80504
+ result[category] = bash;
80505
+ continue;
80506
+ }
80507
+ result[category] = honorInCategory({
80508
+ category,
80509
+ rules,
80510
+ restrictions: restrictions.map(({ pattern }) => ({
80511
+ pattern,
80512
+ action: allToolsRules[pattern] ?? "deny"
80513
+ })),
80514
+ restateAs,
80515
+ downgradeWithheldCatchAll,
80516
+ withheld
80517
+ });
80518
+ }
80519
+ if (withheld.length > 0) warnWithFallback(logger, `${toolLabel} was not given the allow rule(s) for ${withheld.join(", ")} because a deny or ask rule under the all-tools '*' category restricts the same inputs, and the stricter rule wins whatever its width.`);
80520
+ return result;
80521
+ }
80522
+ /** File categories whose patterns are paths. */
80523
+ const PATH_CATEGORIES = /* @__PURE__ */ new Set([
80524
+ "read",
80525
+ "edit",
80526
+ "write"
80527
+ ]);
80528
+ /**
80529
+ * The common `restateAs`: a restriction is restated under a path category when
80530
+ * it reads as a path (no whitespace, so not a command such as `git push *`),
80531
+ * and under `webfetch` when it reads as a URL or domain. `actions` limits it to
80532
+ * the actions the tool can write per pattern.
80533
+ */
80534
+ function restatesAsCategoryRule(actions = ["deny", "ask"]) {
80535
+ return ({ category, pattern, action }) => {
80536
+ if (!actions.includes(action) || pattern === "*") return false;
80537
+ if (PATH_CATEGORIES.has(category)) return !/\s/.test(pattern);
80538
+ if (category === WEBFETCH_CATEGORY$2) return /^([a-z][a-z0-9+.-]*:\/\/)?[\w*-]+(\.[\w*-]+)+(:[\w*]+)?(\/\S*)?$/i.test(pattern);
80539
+ return false;
80540
+ };
80541
+ }
80542
+ /** One non-shell category with the `*` restrictions honored; see the caller. */
80543
+ function honorInCategory({ category, rules, restrictions, restateAs, downgradeWithheldCatchAll, withheld }) {
80544
+ const shadowingRestrictions = createCategoryShadowTest({
80545
+ restrictions: restrictions.map(({ pattern }) => ({
80546
+ pattern,
80547
+ fromAllToolsCategory: true
80548
+ })),
80549
+ category
80550
+ });
80551
+ const downgradedAction = restrictions.some(({ pattern, action }) => pattern === "*" && action === "deny") ? "deny" : "ask";
80552
+ const kept = {};
80553
+ for (const [pattern, action] of Object.entries(rules)) {
80554
+ if (action === "allow" && shadowingRestrictions(pattern)) {
80555
+ withheld.push(describeRule(category, pattern));
80556
+ if (downgradeWithheldCatchAll && pattern === "*") kept[pattern] = downgradedAction;
80557
+ continue;
80558
+ }
80559
+ kept[pattern] = action;
80560
+ }
80561
+ return restateInCategory({
80562
+ category,
80563
+ rules: kept,
80564
+ restrictions,
80565
+ restateAs
80566
+ });
80567
+ }
80568
+ function restateInCategory({ category, rules, restrictions, restateAs }) {
80569
+ const restated = { ...rules };
80570
+ for (const { pattern, action } of restrictions) {
80571
+ if (isPrototypePollutionKey(pattern) || !restateAs({
80572
+ category,
80573
+ pattern,
80574
+ action
80575
+ })) continue;
80576
+ if (isStricterAction({
80577
+ action,
80578
+ existing: Object.hasOwn(restated, pattern) ? restated[pattern] : void 0
80579
+ })) restated[pattern] = action;
80580
+ }
80581
+ return restated;
80582
+ }
80583
+ /**
80584
+ * One category's rules with the pattern-specific `*` restrictions `restateAs`
80585
+ * accepts copied in as its own rules (the stricter action wins on a shared
80586
+ * spelling), for a tool that can write them there and needs no allow
80587
+ * withheld, because its own ordering already lets the copied rule win.
80588
+ */
80589
+ function restateAllToolsRestrictionsInCategory({ permission, category, restateAs }) {
80590
+ const rules = lookupOwn({
80591
+ record: permission,
80592
+ key: category
80593
+ }) ?? {};
80594
+ const allToolsRules = lookupOwn({
80595
+ record: permission,
80596
+ key: "*"
80597
+ }) ?? {};
80598
+ return restateInCategory({
80599
+ category,
80600
+ rules,
80601
+ restrictions: Object.entries(allToolsRules).filter(([, action]) => action !== "allow").map(([pattern, action]) => ({
80602
+ pattern,
80603
+ action
80604
+ })),
80605
+ restateAs
80606
+ });
80607
+ }
80608
+ /**
80609
+ * Withhold every `allow` that an `ask` the tool cannot write also covers, for a
80610
+ * tool with no ask tier on some surface.
80611
+ *
80612
+ * Such a tool prompts for whatever it does not auto-approve, so skipping the
80613
+ * `ask` alone is right — but only if no `allow` beside it auto-approves the
80614
+ * same input. The canonical order is `deny > ask > allow`, so `{"git *":
80615
+ * "allow", "git push *": "ask"}` must not leave `git *` auto-approved.
80616
+ *
80617
+ * Within each group (categories the tool folds into one surface share a group;
80618
+ * by default each category is its own), a pattern-specific `allow` an `ask`
80619
+ * overlaps is removed. A catch-all `*` `allow` is downgraded to `ask` instead,
80620
+ * so a tool that has a coarse prompting default for the whole surface (Vibe's
80621
+ * `permission = "ask"`) uses it; a tool that skips `ask` drops it either way.
80622
+ *
80623
+ * `isSkippedAsk` picks the `ask` rules the tool cannot write (by default every
80624
+ * one). Every withheld allow is named in one warning.
80625
+ */
80626
+ function withholdAllowsShadowedByAsks({ permission, toolLabel, logger, isSkippedAsk = () => true, groupOf = (category) => category }) {
80627
+ const asksByGroup = /* @__PURE__ */ new Map();
80628
+ for (const [category, rules] of Object.entries(permission)) for (const [pattern, action] of Object.entries(rules)) {
80629
+ if (action !== "ask" || isPrototypePollutionKey(pattern)) continue;
80630
+ if (!isSkippedAsk({
80631
+ category,
80632
+ pattern
80633
+ })) continue;
80634
+ const group = groupOf(category);
80635
+ asksByGroup.set(group, [...asksByGroup.get(group) ?? [], pattern]);
80636
+ }
80637
+ if (asksByGroup.size === 0) return permission;
80638
+ const result = {};
80639
+ const withheld = [];
80640
+ for (const [category, rules] of Object.entries(permission)) {
80641
+ const asks = asksByGroup.get(groupOf(category));
80642
+ if (asks === void 0) {
80643
+ result[category] = rules;
80644
+ continue;
80645
+ }
80646
+ const shadowingAsks = createCategoryShadowTest({
80647
+ restrictions: asks.map((pattern) => ({
80648
+ pattern,
80649
+ fromAllToolsCategory: false
80650
+ })),
80651
+ category
80652
+ });
80653
+ const kept = {};
80654
+ for (const [pattern, action] of Object.entries(rules)) {
80655
+ if (action !== "allow" || !shadowingAsks(pattern)) {
80656
+ kept[pattern] = action;
80657
+ continue;
80658
+ }
80659
+ withheld.push(describeRule(category, pattern));
80660
+ if (pattern === "*") kept[pattern] = "ask";
80661
+ }
80662
+ result[category] = kept;
80663
+ }
80664
+ if (withheld.length > 0) warnWithFallback(logger, `${toolLabel} has no "ask" tier there, so the allow rule(s) for ${withheld.join(", ")} were withheld (a catch-all '*' allow falls back to the tool's prompt): an ask rule covers the same inputs, and an allow kept beside it would auto-approve what the ask should prompt for.`);
80665
+ return result;
80666
+ }
79818
80667
  // src/features/permissions/tool-pattern-entry.ts
79819
80668
  /**
79820
80669
  * Parse a `Tool(pattern)` permission entry (e.g. `Bash(npm run *)`) into its
@@ -79900,7 +80749,7 @@ const MATCH_ALL_PATH_GLOBS = /* @__PURE__ */ new Set([
79900
80749
  "**/*"
79901
80750
  ]);
79902
80751
  const DIRECTORY_CONTENTS_SUFFIX = /\/\*\*(?:\/\*)?$/;
79903
- const HOME_OR_VARIABLE_PATH = /^~(?:\/|$)|^\$[A-Za-z_]|\$\{[A-Za-z_]/;
80752
+ const HOME_OR_VARIABLE_PATH = /^~(?:[A-Za-z_][\w.-]*)?(?:[/\\]|$)|^\$[A-Za-z_]|^%[A-Za-z_]\w*%|\$\{[A-Za-z_]/;
79904
80753
  const LEADING_HOME = /^~(?:\/|$)/;
79905
80754
  /**
79906
80755
  * The home directory as an Antigravity path: forward slashes, no trailing
@@ -79915,7 +80764,7 @@ function toAntigravityHomePath(homeDirectory) {
79915
80764
  * apply (rulesync#3324). Only a file the user's own home holds, such as the
79916
80765
  * global Antigravity CLI settings, may carry a machine-specific path, so the
79917
80766
  * caller passes `homeDirectory` only then. `$HOME`, `${HOME}`, `%VAR%` and
79918
- * `~user/` are left as written (the variable forms are still warned about).
80767
+ * `~user/` are left as written and still warned about.
79919
80768
  */
79920
80769
  function expandLeadingHome(target, homeDirectory) {
79921
80770
  if (homeDirectory === void 0 || !LEADING_HOME.test(target)) return target;
@@ -79958,12 +80807,30 @@ function toPathTarget(pattern) {
79958
80807
  "**",
79959
80808
  "**/*"
79960
80809
  ].includes(path)) return { target: "." };
79961
- const directory = path.replace(DIRECTORY_CONTENTS_SUFFIX, "") || (path.startsWith("/") ? "/" : "");
80810
+ const stripped = path.replace(DIRECTORY_CONTENTS_SUFFIX, "");
80811
+ const directory = stripped === "" && path.startsWith("/") ? "/" : /^[A-Za-z]:$/.test(stripped) && stripped !== path ? `${stripped}/` : stripped;
79962
80812
  if (directory !== path && directory.length > 0 && !hasGlob(directory)) return { target: directory };
79963
80813
  if (!hasGlob(path)) return { target: path };
79964
80814
  return { skipReason: "Antigravity file targets are paths, not globs. Only a plain path, `dir/**` or `*` can be expressed" };
79965
80815
  }
79966
80816
  /**
80817
+ * The canonical patterns a `read_file` / `write_file` target imports as. A
80818
+ * target can name a file or a directory, and a directory covers everything
80819
+ * inside it, but the target alone does not say which. A plain path such as
80820
+ * `src` imports as both `src` and `src/**`, so re-exporting it to a tool whose
80821
+ * plain path matches only that one path keeps covering the subtree; regenerating
80822
+ * collapses both back into one target. The bare `*`, and a target that already
80823
+ * holds glob characters (verbatim output of an older Rulesync), stay as written.
80824
+ */
80825
+ function fromPathTarget(target) {
80826
+ if (target === "*" || hasGlob(target) || /^[A-Za-z]:$/.test(target)) return [target];
80827
+ if (target === ".") return [".", "./**"];
80828
+ const root = /^((?:[A-Za-z]:)?\/)\/*$/.exec(target)?.[1];
80829
+ if (root !== void 0) return [root, `${root}**`];
80830
+ const path = target.replace(/\/+$/, "");
80831
+ return [path, `${path}/**`];
80832
+ }
80833
+ /**
79967
80834
  * A URL or domain pattern becomes its hostname. A leading `*.` is dropped,
79968
80835
  * since a domain already covers its subdomains, and the URL path is ignored.
79969
80836
  * Claude Code's `domain:` form is read as well.
@@ -80139,30 +81006,84 @@ function convertRulesyncToAntigravityPermissions({ config, toAction, toolLabel,
80139
81006
  const allow = [];
80140
81007
  const ask = [];
80141
81008
  const deny = [];
80142
- for (const [category, rules] of Object.entries(honorAllToolsOnBash(config.permission))) {
81009
+ const permission = honorAllToolsRestrictions({
81010
+ permission: config.permission,
81011
+ toolLabel,
81012
+ logger
81013
+ });
81014
+ const translated = [];
81015
+ for (const [category, rules] of Object.entries(permission)) {
80143
81016
  const action = toAction(category);
80144
- for (const [pattern, permissionAction] of Object.entries(rules)) {
81017
+ for (const [pattern, decision] of Object.entries(rules)) {
80145
81018
  const entry = buildAntigravityPermissionEntry({
80146
81019
  action,
80147
81020
  category,
80148
81021
  pattern,
80149
- decision: permissionAction,
81022
+ decision,
80150
81023
  logger,
80151
81024
  toolLabel,
80152
81025
  homeDirectory
80153
81026
  });
80154
- if (entry === void 0) continue;
80155
- switch (permissionAction) {
80156
- case "allow":
80157
- allow.push(entry);
80158
- break;
80159
- case "ask":
80160
- ask.push(entry);
81027
+ translated.push({
81028
+ action,
81029
+ category,
81030
+ pattern,
81031
+ decision,
81032
+ entry
81033
+ });
81034
+ }
81035
+ }
81036
+ const skippedRestrictionsByAction = /* @__PURE__ */ new Map();
81037
+ const groupOf = ({ action, category }) => category.startsWith("mcp__") ? category : action;
81038
+ for (const { action, category, pattern, decision, entry } of translated) if (entry === void 0 && decision !== "allow") {
81039
+ const group = groupOf({
81040
+ action,
81041
+ category
81042
+ });
81043
+ skippedRestrictionsByAction.set(group, [...skippedRestrictionsByAction.get(group) ?? [], pattern]);
81044
+ }
81045
+ const allToolsRestrictions = Object.entries(lookupOwn({
81046
+ record: config.permission,
81047
+ key: "*"
81048
+ }) ?? {}).filter(([pattern, decision]) => decision !== "allow" && pattern !== "*" && !isPrototypePollutionKey(pattern)).map(([pattern]) => pattern);
81049
+ const shadowingTests = /* @__PURE__ */ new Map();
81050
+ const shadowingTestOf = (group) => {
81051
+ const cached = shadowingTests.get(group);
81052
+ if (cached !== void 0) return cached;
81053
+ const patterns = [...skippedRestrictionsByAction.get(group) ?? [], ...allToolsRestrictions];
81054
+ let test;
81055
+ if (URL_ACTIONS.has(group)) test = (allowPattern) => patterns.some((pattern) => urlPatternsOverlap(pattern, allowPattern));
81056
+ else {
81057
+ const asGlobs = createShadowingRestrictionsTest([.../* @__PURE__ */ new Set([...patterns, ...patterns.map(normalizeUrlPattern)])].map((pattern) => ({
81058
+ pattern,
81059
+ fromAllToolsCategory: false
81060
+ })));
81061
+ test = (allowPattern) => asGlobs(allowPattern).length > 0 || asGlobs(normalizeUrlPattern(allowPattern)).length > 0;
81062
+ }
81063
+ shadowingTests.set(group, test);
81064
+ return test;
81065
+ };
81066
+ const withheld = [];
81067
+ for (const { action, category, pattern, decision, entry } of translated) {
81068
+ if (entry === void 0) continue;
81069
+ switch (decision) {
81070
+ case "allow":
81071
+ if ([pattern, effectiveTargetScope(entry)].some((candidate) => shadowingTestOf(groupOf({
81072
+ action,
81073
+ category
81074
+ }))(candidate))) {
81075
+ withheld.push(`${category}: ${pattern}`);
80161
81076
  break;
80162
- case "deny": deny.push(entry);
80163
- }
81077
+ }
81078
+ allow.push(entry);
81079
+ break;
81080
+ case "ask":
81081
+ ask.push(entry);
81082
+ break;
81083
+ case "deny": deny.push(entry);
80164
81084
  }
80165
81085
  }
81086
+ if (withheld.length > 0) logger.warn(`${toolLabel} permissions: the allow rule(s) for ${withheld.join(", ")} were not written because a deny or ask rule ${toolLabel} cannot express (skipped above) covers the same inputs, and the stricter rule wins.`);
80166
81087
  return {
80167
81088
  allow: [...new Set(allow)],
80168
81089
  ask: [...new Set(ask)],
@@ -80170,6 +81091,24 @@ function convertRulesyncToAntigravityPermissions({ config, toAction, toolLabel,
80170
81091
  };
80171
81092
  }
80172
81093
  /**
81094
+ * The widest glob an emitted entry grants, for comparing an allow against the
81095
+ * restrictions Antigravity cannot express. The emitted target can grant more
81096
+ * than the canonical pattern it came from: a path target also covers
81097
+ * everything inside it (and `.` the whole workspace), a command target is a
81098
+ * word prefix (`git push` approves `git push --force`), and a domain target
81099
+ * covers its subdomains and every URL on it. Widening only ever withholds more.
81100
+ */
81101
+ function effectiveTargetScope(entry) {
81102
+ const { toolName, pattern: target } = parseToolPatternEntry(entry);
81103
+ if (target === "*") return "*";
81104
+ if (PATH_ACTIONS.has(toolName)) {
81105
+ const path = target.replace(/\/+$/, "");
81106
+ return path === "." || path === "" ? "*" : `${path}/**`;
81107
+ }
81108
+ if (ANTIGRAVITY_COMMAND_ACTIONS.has(toolName)) return target.endsWith("*") ? target : `${target}*`;
81109
+ return target;
81110
+ }
81111
+ /**
80173
81112
  * Convert Antigravity allow/ask/deny arrays to rulesync permissions config,
80174
81113
  * shared by the CLI and IDE adapters; `toCategory` maps the target's tool or
80175
81114
  * action name back to a canonical category.
@@ -80180,19 +81119,21 @@ function convertAntigravityToRulesyncPermissions({ allow, ask, deny, toCategory,
80180
81119
  for (const entry of entries) {
80181
81120
  const { toolName, pattern: target } = parseToolPatternEntry(entry);
80182
81121
  const canonical = toCategory(toolName);
80183
- const pattern = ANTIGRAVITY_COMMAND_ACTIONS.has(toolName) ? importAntigravityCommandTarget({
81122
+ const patterns = ANTIGRAVITY_COMMAND_ACTIONS.has(toolName) ? [importAntigravityCommandTarget({
80184
81123
  target,
80185
81124
  entry,
80186
81125
  decision: action,
80187
81126
  logger,
80188
81127
  toolLabel
80189
- }) : PATH_ACTIONS.has(toolName) ? collapseLeadingHome(target, homeDirectory) : target;
80190
- if (isPrototypePollutionKey(canonical) || isPrototypePollutionKey(pattern)) continue;
80191
- getOrCreateOwn({
80192
- record: permission,
80193
- key: canonical,
80194
- create: () => ({})
80195
- })[pattern] = action;
81128
+ })] : PATH_ACTIONS.has(toolName) ? fromPathTarget(collapseLeadingHome(target, homeDirectory)) : [target];
81129
+ for (const pattern of patterns) {
81130
+ if (isPrototypePollutionKey(canonical) || isPrototypePollutionKey(pattern)) continue;
81131
+ getOrCreateOwn({
81132
+ record: permission,
81133
+ key: canonical,
81134
+ create: () => ({})
81135
+ })[pattern] = action;
81136
+ }
80196
81137
  }
80197
81138
  };
80198
81139
  processEntries(allow, "allow");
@@ -80963,6 +81904,10 @@ var AugmentcodePermissions = class AugmentcodePermissions extends ToolPermission
80963
81904
  * in global mode it is dropped with a warning instead of written somewhere it
80964
81905
  * does nothing.
80965
81906
  *
81907
+ * Only Auggie 0.x reads `recommendedMarketplaces`: the 1.x plugin settings
81908
+ * reference lists `enabledPlugins` alone. The key is still written because the
81909
+ * stable CLI is 0.x, and the write warning says it is 0.x-only.
81910
+ *
80966
81911
  * Both make Auggie load code the repository did not ship — a recommended
80967
81912
  * marketplace is one prompt away from being cloned, and an enabled plugin can
80968
81913
  * carry its own hooks and MCP servers — so writing either is logged, unless
@@ -80982,7 +81927,7 @@ function buildPluginConsumptionPatch({ override, existing, global, logger }) {
80982
81927
  else {
80983
81928
  patch.recommendedMarketplaces = recommendedMarketplaces;
80984
81929
  const existingMarketplaces = existingKeys.recommendedMarketplaces;
80985
- if (recommendedMarketplaces.length > 0 && !(0, node_util.isDeepStrictEqual)(recommendedMarketplaces, existingMarketplaces)) logger?.warn(`Writing AugmentCode \`recommendedMarketplaces\` (${recommendedMarketplaces.map(quoteValueForWarning).join(", ")}): Auggie prompts everyone who opens this workspace to install these plugin marketplaces.`);
81930
+ if (recommendedMarketplaces.length > 0 && !(0, node_util.isDeepStrictEqual)(recommendedMarketplaces, existingMarketplaces)) logger?.warn(`Writing AugmentCode \`recommendedMarketplaces\` (${recommendedMarketplaces.map(quoteValueForWarning).join(", ")}): Auggie 0.x prompts everyone who opens this workspace to install these plugin marketplaces (Auggie 1.x no longer reads this key).`);
80986
81931
  warnAboutRemovedPluginIds({
80987
81932
  key: "recommendedMarketplaces",
80988
81933
  removed: (existingMarketplaces ?? []).filter((marketplace) => !recommendedMarketplaces.includes(marketplace)),
@@ -81064,15 +82009,21 @@ async function withBaseEnabledPlugins({ mergedContent, baseFilePath }) {
81064
82009
  function convertRulesyncToAugmentEntries({ config, logger }) {
81065
82010
  const entries = [];
81066
82011
  const resolvedBashRules = bashRulesHonoringAllTools(config.permission);
82012
+ const honoredPermission = honorAllToolsRestrictions({
82013
+ permission: config.permission,
82014
+ toolLabel: "AugmentCode",
82015
+ logger,
82016
+ writesAllToolsCatchAll: true
82017
+ });
81067
82018
  const permission = config.permission.bash !== void 0 || Object.keys(resolvedBashRules).length > 0 ? {
81068
- ...config.permission,
82019
+ ...honoredPermission,
81069
82020
  bash: resolvedBashRules
81070
- } : config.permission;
82021
+ } : honoredPermission;
81071
82022
  const allToolsFailClosedType = computeAllToolsFailClosedType(config.permission["*"]);
81072
82023
  const categoriesWithOwnEntries = /* @__PURE__ */ new Set();
81073
82024
  for (const [category, rules] of Object.entries(permission)) {
81074
82025
  if (category === "*") {
81075
- logger?.warn("AugmentCode permissions: the all-tools '*' category cannot be emitted as a single entry because AugmentCode has no wildcard toolName. Deny/ask rules are folded into 'launch-process' and, for any other managed tool that has no explicit rules of its own, applied as a blanket deny/ask; all-tools allow rules and tools that already define their own rules are left untouched.");
82026
+ logger?.warn("AugmentCode permissions: the all-tools '*' category cannot be emitted as a single entry because AugmentCode has no wildcard toolName. Deny/ask rules are folded into 'launch-process' and, for any other managed tool that has no explicit rules of its own (or whose allow rules were all withheld because a '*' deny/ask covers them), applied as a blanket deny/ask; all-tools allow rules and tools that still define rules of their own are left untouched.");
81076
82027
  continue;
81077
82028
  }
81078
82029
  const augmentToolName = toAugmentToolName(category);
@@ -81131,9 +82082,10 @@ function computeAllToolsFailClosedType(allToolsRules) {
81131
82082
  * other managed tools: one that produced no entries of its own above must not fall back to
81132
82083
  * AugmentCode's own default just because it has no per-input matcher to narrow the all-tools
81133
82084
  * restriction onto. A category can be stated yet still emit nothing (e.g. only non-`*` allow/ask
81134
- * patterns, dropped with a warning), so this checks emitted entries rather than whether the
81135
- * category was merely present in the source config. A tool whose own rules did emit entries is
81136
- * left untouched here.
82085
+ * patterns, dropped with a warning, or only allows withheld by `honorAllToolsRestrictions`), so
82086
+ * this checks emitted entries rather than whether the category was merely present in the source
82087
+ * config. Falling back to AugmentCode's own default instead would let a read-only tool run on the
82088
+ * input the restriction names. A tool whose own rules did emit entries is left untouched here.
81137
82089
  */
81138
82090
  function synthesizeManagedToolFallbackEntries(categoriesWithOwnEntries, allToolsFailClosedType) {
81139
82091
  if (allToolsFailClosedType === void 0) return [];
@@ -81211,12 +82163,12 @@ function convertAugmentToRulesyncPermissions({ entries, logger }) {
81211
82163
  const regex = entry.shellInputRegex;
81212
82164
  if (isShellRegexRoundtrippable(regex)) pattern = shellRegexToGlob(regex);
81213
82165
  else {
81214
- if (action !== "deny" && !canApproximateShellRegexWithoutWidening(regex)) {
81215
- logger?.warn(`AugmentCode permissions: skipping ${action} entry for tool '${entry.toolName}': shellInputRegex '${regex}' uses a quantifier or a literal '*' / '?' that a glob cannot express, and converting it would widen the rule. The entry is not imported.`);
82166
+ if (action === "allow" && !canApproximateShellRegexWithoutWidening(regex)) {
82167
+ logger?.warn(`AugmentCode permissions: skipping allow entry for tool '${entry.toolName}': shellInputRegex '${regex}' uses a quantifier or a literal '*' / '?' that a glob cannot express, and converting it would widen the rule. The entry is not imported.`);
81216
82168
  continue;
81217
82169
  }
81218
- if (action === "deny") {
81219
- logger?.warn(`AugmentCode permissions: shellInputRegex '${regex}' on tool '${entry.toolName}' is not faithfully roundtrippable to a glob. Importing as the catch-all '*' pattern (fail-closed) so the deny rule cannot be silently narrowed on regenerate.`);
82170
+ if (action !== "allow") {
82171
+ logger?.warn(`AugmentCode permissions: shellInputRegex '${regex}' on tool '${entry.toolName}' is not faithfully roundtrippable to a glob. Importing the ${action} rule as the catch-all '*' pattern (fail-closed) so it cannot be silently narrowed on regenerate.`);
81220
82172
  pattern = "*";
81221
82173
  } else {
81222
82174
  pattern = shellRegexToGlob(regex);
@@ -81302,6 +82254,62 @@ function classifyPattern(pattern, bareStarIsWildcard) {
81302
82254
  };
81303
82255
  return { kind: "literal" };
81304
82256
  }
82257
+ /** The trimmed spellings of the literal (prefix) deny entries, minus the bare wildcard. */
82258
+ function collectLiteralDenyStems({ rules, bareStarIsWildcard }) {
82259
+ const stems = /* @__PURE__ */ new Set();
82260
+ for (const [pattern, action] of Object.entries(rules)) {
82261
+ if (action !== "deny" || pattern === "*") continue;
82262
+ const stem = pattern.trimEnd();
82263
+ if (stem.length > 0 && classifyPattern(pattern, bareStarIsWildcard).kind === "literal") stems.add(stem);
82264
+ }
82265
+ return stems;
82266
+ }
82267
+ function isCoveredByLiteralDeny({ pattern, literalDenyStems }) {
82268
+ if (!pattern.endsWith(" *")) return false;
82269
+ const stem = pattern.slice(0, -2).trimEnd();
82270
+ return stem.length > 0 && literalDenyStems.has(stem);
82271
+ }
82272
+ /**
82273
+ * Lower a VS Code style command allow/deny list pair into canonical `bash`
82274
+ * rules on import.
82275
+ *
82276
+ * The native entries are compared as literal command prefixes, while canonical
82277
+ * patterns are globs, so a verbatim copy changes their meaning:
82278
+ *
82279
+ * - A prefix deny such as `curl` blocks `curl https://…` natively but would
82280
+ * only block the exact command `curl` canonically, so a broad allow beside
82281
+ * it would auto-approve what the native config blocked. Each deny that does
82282
+ * not already end in `*` is imported as itself plus `<deny> *`.
82283
+ * - An allow holding glob syntax (`npm *`) is literal prefix text natively and
82284
+ * approves almost nothing, but canonically it is a wildcard. Such an allow is
82285
+ * not imported (with a warning) rather than imported wider than it matched.
82286
+ * The Roo Code lineage's bare `*` is a real wildcard natively and is kept.
82287
+ *
82288
+ * A pattern in both lists imports as `deny`, matching both tools' precedence
82289
+ * for identical entries.
82290
+ */
82291
+ function importVscodeCommandLists({ allowed, denied, toolLabel, logger, prefixSemantics = "roo-lineage" }) {
82292
+ const isRooLineage = prefixSemantics === "roo-lineage";
82293
+ const rules = {};
82294
+ const skippedAllows = [];
82295
+ for (const pattern of allowed) {
82296
+ if (!(isRooLineage && pattern === "*") && /[*?]/.test(pattern)) {
82297
+ skippedAllows.push(pattern);
82298
+ continue;
82299
+ }
82300
+ rules[pattern] = "allow";
82301
+ }
82302
+ for (const pattern of denied) {
82303
+ rules[pattern] = "deny";
82304
+ const stem = pattern.trimEnd();
82305
+ if (!pattern.endsWith("*") && stem.length > 0) rules[`${stem} *`] = "deny";
82306
+ }
82307
+ if (skippedAllows.length > 0) {
82308
+ const count = skippedAllows.length;
82309
+ warnWithFallback(logger, `${toolLabel}: allow ${pluralize(count, "pattern", "patterns")} ${formatPatterns(skippedAllows)} ${pluralize(count, "was", "were")} not imported. ${toolLabel} compares ${pluralize(count, "it", "them")} as literal command prefix text, while a rulesync pattern is a glob, so importing ${pluralize(count, "it", "them")} would approve more commands than the native config does.` + (isRooLineage ? ` Only a bare "*" is a wildcard there.` : ""));
82310
+ }
82311
+ return rules;
82312
+ }
81305
82313
  function pluralize(count, singular, plural) {
81306
82314
  return count === 1 ? singular : plural;
81307
82315
  }
@@ -81396,8 +82404,16 @@ function buildVscodeCommandLists({ rules, toolLabel, logger, prefixSemantics = "
81396
82404
  const matcherAllows = [];
81397
82405
  const widenedDenies = [];
81398
82406
  const inertDenies = [];
82407
+ const literalDenyStems = collectLiteralDenyStems({
82408
+ rules,
82409
+ bareStarIsWildcard: isRooLineage
82410
+ });
81399
82411
  for (const [pattern, action] of Object.entries(rules)) {
81400
82412
  if (action !== "allow" && action !== "deny") continue;
82413
+ if (action === "deny" && isCoveredByLiteralDeny({
82414
+ pattern,
82415
+ literalDenyStems
82416
+ })) continue;
81401
82417
  const shape = classifyPattern(pattern, isRooLineage);
81402
82418
  if (action === "allow") {
81403
82419
  allowed.push(pattern);
@@ -81760,16 +82776,20 @@ var BobPermissions = class BobPermissions extends ToolPermissions {
81760
82776
  validate: true
81761
82777
  });
81762
82778
  }
81763
- toRulesyncPermissions() {
82779
+ toRulesyncPermissions({ logger } = {}) {
81764
82780
  const settings = parseBobSettings({
81765
82781
  fileContent: this.getFileContent(),
81766
82782
  filePath: (0, node_path.join)(this.getRelativeDirPath(), this.getRelativeFilePath())
81767
82783
  });
81768
82784
  const approval = settings[APPROVAL_KEY$1];
81769
82785
  const entry = (isPlainObject(approval) && Array.isArray(approval.allowedExecutors) ? approval.allowedExecutors : []).find(isExecuteCommandEntry);
81770
- const rules = {};
81771
- for (const pattern of toStringArray$1(entry?.approvedCommands)) rules[pattern] = "allow";
81772
- for (const pattern of toStringArray$1(entry?.deniedCommands)) rules[pattern] = "deny";
82786
+ const rules = importVscodeCommandLists({
82787
+ allowed: toStringArray$1(entry?.approvedCommands),
82788
+ denied: toStringArray$1(entry?.deniedCommands),
82789
+ toolLabel: TOOL_LABEL,
82790
+ logger,
82791
+ prefixSemantics: "documented-prefix"
82792
+ });
81773
82793
  const permission = {};
81774
82794
  if (Object.keys(rules).length > 0) permission[SHELL_PERMISSION_CATEGORY] = rules;
81775
82795
  const bob = readBobOverride(settings);
@@ -83529,8 +84549,10 @@ function categoryOfRule$2(rule) {
83529
84549
  * - MCP rules take no specifier, so a scoped `mcp__<...>` category is written
83530
84550
  * for its catch-all pattern only.
83531
84551
  * - The all-tools `*` category is CodeBuddy's documented standalone `*` rule
83532
- * for its catch-all pattern. Narrower `*` patterns are shell restrictions
83533
- * and reach the `Bash` rules through `honorAllToolsOnBash`.
84552
+ * for its catch-all pattern. A narrower `*` pattern reaches the `Bash`
84553
+ * rules through `honorAllToolsRestrictions`, which also withholds every
84554
+ * allow it overlaps in the other categories — a `{"*": "allow"}` included,
84555
+ * even for a shell-only pattern such as `git push *`.
83534
84556
  */
83535
84557
  function buildCodebuddyRule({ category, pattern, action, logger }) {
83536
84558
  const catchAll = pattern === "*";
@@ -83578,7 +84600,13 @@ function parseCodebuddyRule(rule) {
83578
84600
  * manage (and every entry rulesync cannot parse).
83579
84601
  */
83580
84602
  function buildCodebuddyRuleLists({ config, existingPermissions, logger }) {
83581
- const permission = honorAllToolsOnBash(config.permission);
84603
+ const permission = honorAllToolsRestrictions({
84604
+ permission: config.permission,
84605
+ toolLabel: "CodeBuddy",
84606
+ logger,
84607
+ restateAs: restatesAsCategoryRule(),
84608
+ writesAllToolsCatchAll: true
84609
+ });
83582
84610
  const ranked = /* @__PURE__ */ new Map();
83583
84611
  const managedCategories = /* @__PURE__ */ new Set();
83584
84612
  for (const [category, rules] of Object.entries(permission)) {
@@ -85173,6 +86201,44 @@ function addCodexWebfetchRules({ rules, domains, logger }) {
85173
86201
  domains[pattern] = action;
85174
86202
  }
85175
86203
  }
86204
+ /**
86205
+ * Copy the all-tools `*` path restrictions into the `read` rules, when the
86206
+ * config states a filesystem category at all: Codex has no all-tools rule, so
86207
+ * `{"*": {".env": "deny"}, "edit": {"*": "allow"}}` would otherwise grant
86208
+ * write access to `.env`. Both a `deny` and an `ask` land under `read`, where
86209
+ * they are handled exactly like a directly written read rule (an ask becomes
86210
+ * `"deny"`, since Codex cannot prompt for a path), so a narrower write allow
86211
+ * they cover is denied as well. A catch-all `*` deny is copied too and
86212
+ * withholds every filesystem allow, so `{"*": {"*": "deny"}, "edit": {"src":
86213
+ * "allow"}}` grants nothing; a catch-all
86214
+ * ask is the documented default idiom and is left alone. Other patterns are
86215
+ * copied only when they read as a path — `git push *` is a command, not a
86216
+ * path — so the sandbox gains nothing but these restrictions.
86217
+ */
86218
+ function restateAllToolsPathRestrictions({ config, filesystemCategoryRules }) {
86219
+ if (Object.keys(filesystemCategoryRules).length === 0) return;
86220
+ if (lookupOwn({
86221
+ record: config.permission,
86222
+ key: "*"
86223
+ })?.["*"] === "deny") for (const category of [
86224
+ "read",
86225
+ "edit",
86226
+ "write"
86227
+ ]) {
86228
+ const rules = filesystemCategoryRules[category];
86229
+ if (rules === void 0) continue;
86230
+ filesystemCategoryRules[category] = Object.fromEntries(Object.entries(rules).filter(([, action]) => action !== "allow"));
86231
+ }
86232
+ const isPath = restatesAsCategoryRule(["deny", "ask"]);
86233
+ filesystemCategoryRules.read = restateAllToolsRestrictionsInCategory({
86234
+ permission: {
86235
+ ...config.permission,
86236
+ read: filesystemCategoryRules.read ?? {}
86237
+ },
86238
+ category: "read",
86239
+ restateAs: (params) => params.pattern === "*" ? params.action === "deny" : isPath(params)
86240
+ });
86241
+ }
85176
86242
  function convertRulesyncToCodexProfile({ config, logger }) {
85177
86243
  const filesystem = { [CODEX_MINIMAL_KEY]: "read" };
85178
86244
  const workspaceRootFilesystem = {};
@@ -85184,8 +86250,24 @@ function convertRulesyncToCodexProfile({ config, logger }) {
85184
86250
  continue;
85185
86251
  }
85186
86252
  if (toolName === "webfetch") {
86253
+ const allToolsRules = lookupOwn({
86254
+ record: config.permission,
86255
+ key: "*"
86256
+ });
86257
+ const { webfetch: webfetchRules = {} } = withholdAllowsShadowedByAsks({
86258
+ permission: { webfetch: honorAllToolsRestrictions({
86259
+ permission: allToolsRules === void 0 ? { webfetch: rules } : {
86260
+ ["*"]: allToolsRules,
86261
+ webfetch: rules
86262
+ },
86263
+ toolLabel: "Codex CLI network domains",
86264
+ logger
86265
+ }).webfetch ?? {} },
86266
+ toolLabel: "Codex CLI network domains",
86267
+ logger
86268
+ });
85187
86269
  addCodexWebfetchRules({
85188
- rules,
86270
+ rules: webfetchRules,
85189
86271
  domains,
85190
86272
  logger
85191
86273
  });
@@ -85194,6 +86276,10 @@ function convertRulesyncToCodexProfile({ config, logger }) {
85194
86276
  if (toolName === "bash") continue;
85195
86277
  logger?.warn(`Codex CLI permission profiles support only read/edit/write/webfetch categories (bash goes to .codex/rules/rulesync.rules). Skipping: ${toolName}`);
85196
86278
  }
86279
+ restateAllToolsPathRestrictions({
86280
+ config,
86281
+ filesystemCategoryRules
86282
+ });
85197
86283
  addCodexFilesystemRules({
85198
86284
  categoryRules: filesystemCategoryRules,
85199
86285
  filesystem,
@@ -85533,7 +86619,7 @@ function computeCodexcliOverridePatch({ existing, override, logger }) {
85533
86619
  const patch = {};
85534
86620
  const allowed = new Set(CODEXCLI_OVERRIDE_KEYS);
85535
86621
  for (const [key, value] of Object.entries(override ?? {})) {
85536
- if (key === "base_permission_profile" || key === "git_write_rules") continue;
86622
+ if (key === "base_permission_profile" || key === "git_write_rules" || key === "bash_canonical_matching") continue;
85537
86623
  if (!allowed.has(key)) {
85538
86624
  logger?.warn(`Codex CLI permission override key "${key}" is not managed and was skipped. "permissions"/"default_permissions" are owned by the canonical permission model and "mcp_servers" gating by the MCP feature.`);
85539
86625
  continue;
@@ -85822,6 +86908,7 @@ function stripTrailingSlash(pattern) {
85822
86908
  function buildCodexBashRulesContent({ config, logger }) {
85823
86909
  const bashRules = bashRulesHonoringAllTools(config.permission);
85824
86910
  const entries = Object.entries(bashRules);
86911
+ const canonicalMatching = config.codexcli?.bash_canonical_matching === true;
85825
86912
  const header = ["# Generated by Rulesync from .rulesync/permissions.jsonc (permission.bash)", "# https://developers.openai.com/codex/rules"];
85826
86913
  if (entries.length === 0) return [...header, "# No bash permission rules were configured."].join("\n");
85827
86914
  const ruleBlocks = entries.map(([pattern, action]) => {
@@ -85840,6 +86927,7 @@ function buildCodexBashRulesContent({ config, logger }) {
85840
86927
  ` pattern = [${serializedTokens}],`,
85841
86928
  ` decision = ${JSON.stringify(decision)},`,
85842
86929
  ` justification = ${JSON.stringify(`Generated from Rulesync permission.bash: ${pattern}`)},`,
86930
+ ...canonicalMatching && decision !== "allow" ? [" canonical_matching = True,"] : [],
85843
86931
  ")"
85844
86932
  ].join("\n");
85845
86933
  }).filter((block) => block !== null);
@@ -85935,8 +87023,10 @@ const PADDED_SHELL_WILDCARD_REASON = "a pattern narrower than the bare 'Shell' (
85935
87023
  * server or tool). A pattern on an MCP category is still written as the
85936
87024
  * `(specifier)` here; `writableCommandcodeRule` decides what to do with it,
85937
87025
  * because Command Code ignores it. The all-tools `*` category is only
85938
- * written for its catch-all pattern; narrower `*` patterns are shell
85939
- * restrictions and reach the `Shell` entries through `honorAllToolsOnBash`.
87026
+ * written for its catch-all pattern; a narrower `*` pattern reaches the `Shell`
87027
+ * entries through `honorAllToolsRestrictions`, which also withholds every allow
87028
+ * it overlaps in the other categories — a `{"*": "allow"}` included, even for a
87029
+ * shell-only pattern such as `git push *`.
85940
87030
  */
85941
87031
  function buildCommandcodeRule(category, pattern) {
85942
87032
  const catchAll = pattern === "*" || pattern === "";
@@ -86230,7 +87320,13 @@ function rankCommandcodeRule({ ranked, rule, action, logger }) {
86230
87320
  * rewritten by `writableCommandcodeRule`.
86231
87321
  */
86232
87322
  function buildCommandcodeRuleLists({ config, existingPermissions, logger }) {
86233
- const permission = honorAllToolsOnBash(config.permission);
87323
+ const permission = honorAllToolsRestrictions({
87324
+ permission: config.permission,
87325
+ toolLabel: "Command Code",
87326
+ logger,
87327
+ restateAs: restatesAsCategoryRule(),
87328
+ writesAllToolsCatchAll: true
87329
+ });
86234
87330
  const ranked = /* @__PURE__ */ new Map();
86235
87331
  const managedCategories = /* @__PURE__ */ new Set();
86236
87332
  for (const [category, rules] of Object.entries(permission)) {
@@ -86690,7 +87786,13 @@ function convertRulesyncToContinuePermissions({ config, logger }) {
86690
87786
  allow: []
86691
87787
  };
86692
87788
  const actionByEntry = /* @__PURE__ */ new Map();
86693
- for (const [category, rules] of Object.entries(honorAllToolsOnBash(config.permission))) {
87789
+ for (const [category, rules] of Object.entries(honorAllToolsRestrictions({
87790
+ permission: config.permission,
87791
+ toolLabel: "Continue",
87792
+ logger,
87793
+ writesAllToolsCatchAll: true,
87794
+ isCatchAll: (pattern) => normalizeCatchAllPattern$1(pattern) === "*"
87795
+ }))) {
86694
87796
  if (isPrototypePollutionKey(category)) continue;
86695
87797
  const toolName = category === "*" ? "*" : toContinueToolName(category);
86696
87798
  for (const [rawPattern, action] of Object.entries(rules)) {
@@ -87062,6 +88164,58 @@ function asAutoApproveMap(value) {
87062
88164
  return result;
87063
88165
  }
87064
88166
  /**
88167
+ * The edits or urls map's rules with the all-tools `*` restrictions honored.
88168
+ * A restriction that reads as a path (edits) or URL (urls), and the catch-all
88169
+ * `*`, is written as a `false` entry of its own, which `buildAutoApproveValue`
88170
+ * places where it wins; a URL is written without its scheme and with only its host lowercased,
88171
+ * since VS Code matches paths case-sensitively.
88172
+ * Every other restriction (a command, an odd URL pattern) cannot be written
88173
+ * there, so each `true` entry it overlaps is withheld instead.
88174
+ */
88175
+ function honorCopilotAllToolsRestrictions({ permission, category, logger }) {
88176
+ const allToolsRules = lookupOwn({
88177
+ record: permission,
88178
+ key: "*"
88179
+ }) ?? {};
88180
+ const isWritable = restatesAsCategoryRule();
88181
+ const restateAs = (params) => params.pattern === "*" || isWritable(params);
88182
+ const writable = {};
88183
+ const notWritable = {};
88184
+ for (const [pattern, action] of Object.entries(allToolsRules)) {
88185
+ if (action === "allow") continue;
88186
+ if (restateAs({
88187
+ category,
88188
+ pattern,
88189
+ action
88190
+ })) {
88191
+ const key = category === "webfetch" && pattern !== "*" ? stripUrlSchemeKeepingPathCase(pattern) : pattern;
88192
+ writable[key] = action;
88193
+ } else notWritable[pattern] = action;
88194
+ }
88195
+ const restated = restateAllToolsRestrictionsInCategory({
88196
+ permission: {
88197
+ ["*"]: writable,
88198
+ [category]: lookupOwn({
88199
+ record: permission,
88200
+ key: category
88201
+ }) ?? {}
88202
+ },
88203
+ category,
88204
+ restateAs: () => true
88205
+ });
88206
+ return lookupOwn({
88207
+ record: honorAllToolsRestrictions({
88208
+ permission: {
88209
+ ["*"]: notWritable,
88210
+ [category]: restated
88211
+ },
88212
+ toolLabel: COPILOT_TOOL_LABEL,
88213
+ logger
88214
+ }),
88215
+ key: category
88216
+ }) ?? {};
88217
+ }
88218
+ /**
87065
88219
  * Render one canonical category's rules as a VS Code auto-approve map. Returns
87066
88220
  * `undefined` when the category contributes nothing, so the key is retracted
87067
88221
  * rather than written as an empty object.
@@ -87139,11 +88293,14 @@ var CopilotPermissions = class CopilotPermissions extends ToolPermissions {
87139
88293
  const config = rulesyncPermissions.getJson();
87140
88294
  const patch = {};
87141
88295
  for (const [category, settingKey] of Object.entries(AUTO_APPROVE_KEYS)) {
87142
- const rules = config.permission[category];
87143
- if (rules === void 0) continue;
88296
+ if (!Object.hasOwn(config.permission, category)) continue;
87144
88297
  patch[settingKey] = buildAutoApproveValue({
87145
88298
  category,
87146
- rules
88299
+ rules: category === "bash" ? bashRulesHonoringAllTools(config.permission) : honorCopilotAllToolsRestrictions({
88300
+ permission: config.permission,
88301
+ category,
88302
+ logger
88303
+ })
87147
88304
  });
87148
88305
  }
87149
88306
  const existingSettings = () => parseSharedConfig({
@@ -87244,6 +88401,15 @@ const DEFAULT_PERMISSION_MODE_KEY = "defaultPermissionMode";
87244
88401
  function isCopilotcliDefaultPermissionMode(value) {
87245
88402
  return COPILOTCLI_DEFAULT_PERMISSION_MODES.some((mode) => mode === value);
87246
88403
  }
88404
+ /** The given categories of a permission block, those it states. */
88405
+ function pickOwnCategories(permission, categories) {
88406
+ const picked = {};
88407
+ for (const category of categories) {
88408
+ const rules = Object.hasOwn(permission, category) ? permission[category] : void 0;
88409
+ if (rules !== void 0) picked[category] = rules;
88410
+ }
88411
+ return picked;
88412
+ }
87247
88413
  function toUrlList(value) {
87248
88414
  if (!Array.isArray(value)) return [];
87249
88415
  return value.filter((entry) => typeof entry === "string");
@@ -87328,7 +88494,15 @@ var CopilotcliPermissions = class CopilotcliPermissions extends ToolPermissions
87328
88494
  const filePath = (0, node_path.join)(outputRoot, paths.relativeDirPath, paths.relativeFilePath);
87329
88495
  const existingContent = await readFileContentOrNull(filePath) ?? "{}";
87330
88496
  const config = rulesyncPermissions.getJson();
87331
- const rules = config.permission[WEBFETCH_CATEGORY$1];
88497
+ const rules = withholdAllowsShadowedByAsks({
88498
+ permission: honorAllToolsRestrictions({
88499
+ permission: pickOwnCategories(config.permission, ["*", WEBFETCH_CATEGORY$1]),
88500
+ toolLabel: "Copilot CLI",
88501
+ logger
88502
+ }),
88503
+ toolLabel: "Copilot CLI",
88504
+ logger
88505
+ })[WEBFETCH_CATEGORY$1];
87332
88506
  const patch = {};
87333
88507
  if (rules !== void 0) {
87334
88508
  const { allowedUrls, deniedUrls } = splitUrlRules(rules);
@@ -87424,9 +88598,126 @@ function toCanonicalToolName$5(crushName) {
87424
88598
  function isMcpToolName(crushName) {
87425
88599
  return crushName.startsWith(MCP_CRUSH_PREFIX) && crushName.length > 4;
87426
88600
  }
88601
+ const CRUSH_COMMAND_WRAPPERS = /* @__PURE__ */ new Set([
88602
+ "env",
88603
+ "nohup",
88604
+ "nice",
88605
+ "timeout"
88606
+ ]);
88607
+ const CRUSH_COMMAND_PREFIXES = [...CRUSH_COMMAND_WRAPPERS, "time"];
88608
+ const CRUSH_COMMAND_NAME = /^[a-z0-9_][a-z0-9_.+-]*$/;
88609
+ const CRUSH_COMMAND_ARGUMENT = /^[A-Za-z0-9_@%+=:,./-]+$/;
88610
+ const CRUSH_COMMAND_NAME_SUFFIXES = [
88611
+ ".exe",
88612
+ ".bat",
88613
+ ".cmd"
88614
+ ];
88615
+ function isCrushCommandName(name) {
88616
+ return CRUSH_COMMAND_NAME.test(name) && !CRUSH_COMMAND_NAME_SUFFIXES.some((suffix) => name.endsWith(suffix)) && !isPrototypePollutionKey(name);
88617
+ }
88618
+ /**
88619
+ * Reduce a command name the way Crush matches it (`shell.NormalizeCommandName`):
88620
+ * trimmed, without its directory, lower-cased, and without a Windows
88621
+ * executable suffix.
88622
+ */
88623
+ function normalizeCrushCommandName(raw) {
88624
+ const base = (raw.trim().split(/[\\/]/).at(-1) ?? "").toLowerCase();
88625
+ const suffix = CRUSH_COMMAND_NAME_SUFFIXES.find((candidate) => base.length > candidate.length && base.endsWith(candidate));
88626
+ return suffix === void 0 ? base : base.slice(0, -suffix.length);
88627
+ }
88628
+ /**
88629
+ * Whether a canonical pattern is a literal command line that a Crush
88630
+ * `safe_commands` entry reproduces exactly: Crush matches an entry only when
88631
+ * the command is written with exactly those tokens, no extra arguments and no
88632
+ * flags, which is what a wildcard-free glob means. A leading wrapper is
88633
+ * refused, since Crush would resolve it away and approve the bare command.
88634
+ */
88635
+ function isExactCrushCommandLine(pattern) {
88636
+ const [name, ...args] = pattern.split(" ");
88637
+ return name !== void 0 && isCrushCommandName(name) && !CRUSH_COMMAND_WRAPPERS.has(name) && args.every((arg) => CRUSH_COMMAND_ARGUMENT.test(arg));
88638
+ }
88639
+ /**
88640
+ * The command name a canonical `<name>` / `<name> *` pattern names as a
88641
+ * whole, i.e. the `blocked_commands` entry for it, or undefined.
88642
+ */
88643
+ function wholeCommandName(pattern) {
88644
+ const name = pattern.endsWith(" *") ? pattern.slice(0, -2) : pattern;
88645
+ return isCrushCommandName(name) ? name : void 0;
88646
+ }
88647
+ /**
88648
+ * The line a Crush `safe_commands` entry effectively stands for, in canonical
88649
+ * form (whitespace collapsed, command name normalized), or undefined when the
88650
+ * entry has no exact canonical spelling (wildcards, quoting, a wrapper, ...).
88651
+ */
88652
+ function effectiveSafeCommandLine(entry) {
88653
+ const [name, ...args] = entry.trim().split(/\s+/);
88654
+ if (name === void 0 || name === "") return void 0;
88655
+ const line = [normalizeCrushCommandName(name), ...args].join(" ");
88656
+ return isExactCrushCommandLine(line) ? line : void 0;
88657
+ }
88658
+ /**
88659
+ * A restriction pattern with its command word reduced the way Crush reduces a
88660
+ * wrapper's name before peeling it (`shell.NormalizeCommandName`): any
88661
+ * directory dropped (`./nice`, `bin\env.exe`, `/usr/bin/env`), lower-cased,
88662
+ * and without a Windows executable suffix. A `*` in the command word may
88663
+ * stand for a directory and part of a name, so when what follows it is the
88664
+ * tail of a wrapper name, everything before it collapses into `*`
88665
+ * (`b*nice` -> `*nice`, `/u*v` -> `*v`; `rm*` is left alone). The rest of the pattern is lower-cased as well, for a
88666
+ * nested wrapper spelled in another case. Used only to compare against the
88667
+ * wrapper spellings of a safe line, where it can only withhold more.
88668
+ */
88669
+ function normalizeRestrictionCommandWord(pattern) {
88670
+ const space = pattern.indexOf(" ");
88671
+ let head = space < 0 ? pattern : pattern.slice(0, space);
88672
+ const rest = space < 0 ? "" : pattern.slice(space);
88673
+ head = normalizeCrushCommandName(head);
88674
+ const star = head.lastIndexOf("*");
88675
+ const tail = head.slice(star + 1);
88676
+ if (star > 0 && tail !== "" && CRUSH_COMMAND_PREFIXES.some((prefix) => prefix.endsWith(tail))) head = `*${tail}`;
88677
+ return `${head}${rest.toLowerCase()}`;
88678
+ }
88679
+ /**
88680
+ * Build the test for a `safe_commands` line: which canonical `deny`/`ask`
88681
+ * rules govern a command Crush would approve through it? Besides the line
88682
+ * itself, Crush approves it followed by `--` and behind a wrapper (or the
88683
+ * `time` keyword), whose name it normalizes (`./nice`, `/usr/bin/env`, `NICE`,
88684
+ * `nohup.exe`). The line and its wrapper spellings are compared against the
88685
+ * restrictions as written, and the wrapper spellings also against the
88686
+ * restrictions with their command word normalized the same way — which keeps
88687
+ * an unrelated `rm *` from withholding the line, as a leading wildcard on the
88688
+ * spelling would. Canonically the stricter rule wins whatever its width
88689
+ * (`deny > ask > allow`), so any overlap withholds the line.
88690
+ *
88691
+ * Crush also approves a line composed with other safe lines (`&&`, `||`, `|`,
88692
+ * `;`, a parenthesized group); those compositions are not compared, the way
88693
+ * other tools' per-subcommand matching treats an allowed command.
88694
+ */
88695
+ function createSafeCommandShadowTest(permission) {
88696
+ const restrictions = collectShellCommandRules(permission).rules.filter(({ action }) => action !== "allow");
88697
+ const test = createShadowingRestrictionsTest(restrictions);
88698
+ const normalized = restrictions.map((rule) => ({
88699
+ ...rule,
88700
+ pattern: normalizeRestrictionCommandWord(rule.pattern)
88701
+ }));
88702
+ const testNormalized = createShadowingRestrictionsTest(normalized);
88703
+ const originalOf = /* @__PURE__ */ new Map();
88704
+ normalized.forEach((rule, index) => {
88705
+ const original = restrictions[index]?.pattern;
88706
+ if (original !== void 0 && !originalOf.has(rule.pattern)) originalOf.set(rule.pattern, original);
88707
+ });
88708
+ const withSeparator = (spellings) => spellings.flatMap((spelling) => [spelling, `${spelling} --*`]);
88709
+ const wrapped = (base) => CRUSH_COMMAND_PREFIXES.map((prefix) => `${prefix}*${base}`);
88710
+ return (line) => uniq$11([...withSeparator([line, ...wrapped(line)]).flatMap((spelling) => test(spelling)), ...withSeparator(wrapped(line.toLowerCase())).flatMap((spelling) => testNormalized(spelling).map((pattern) => originalOf.get(pattern) ?? pattern))]);
88711
+ }
87427
88712
  function uniq$11(values) {
87428
88713
  return [...new Set(values)];
87429
88714
  }
88715
+ function stringList(value) {
88716
+ return isStringArray(value) ? value : [];
88717
+ }
88718
+ function listOrUndefined(values) {
88719
+ return values.length > 0 ? values : void 0;
88720
+ }
87430
88721
  /**
87431
88722
  * Permissions adapter for Crush.
87432
88723
  *
@@ -87448,8 +88739,24 @@ function uniq$11(values) {
87448
88739
  * `webfetch` -> `fetch`, `mcp__<server>__<tool>` -> `mcp_<server>_<tool>`;
87449
88740
  * any other category passes through verbatim.
87450
88741
  *
87451
- * A pattern-specific rule cannot be expressed and is reported and skipped.
87452
- * Because Crush cannot narrow an allowed tool, a category's catch-all `allow`
88742
+ * Crush v0.100.0+ also carries two command lists, which the `bash` category's
88743
+ * pattern rules map onto (see `convertBashCommandRules`):
88744
+ * - `permissions.safe_commands`: exact command lines that skip the prompt
88745
+ * (no extra arguments, no flags) <- an `allow` on a literal command line
88746
+ * that no canonical `deny`/`ask` overlaps.
88747
+ * - `permissions.blocked_commands`: command names added to the dangerous
88748
+ * list <- a `deny` on `<name>` or `<name> *`. Not a full deny: a direct
88749
+ * invocation is still prompted for (and auto-approved in yolo mode or
88750
+ * through `allowed_tools: ["bash"]`); only the forms Crush would not
88751
+ * prompt for (its read-only commands, `safe_commands`) and indirect
88752
+ * invocations are refused at exec time. An `ask` is not written there,
88753
+ * since it would turn the read-only forms into a refusal.
88754
+ * `permissions.allowed_commands` only drops names from the dangerous list (the
88755
+ * commands keep prompting), so it has no canonical counterpart and is left
88756
+ * untouched.
88757
+ *
88758
+ * Any other pattern-specific rule cannot be expressed and is reported and
88759
+ * skipped. Because Crush cannot narrow an allowed tool, a category's catch-all `allow`
87453
88760
  * is not written while the same category carries a pattern-specific `deny` or
87454
88761
  * `ask`: the tool keeps prompting (fail closed) rather than being widened to
87455
88762
  * everything. The all-tools `*` category is mirrored onto `bash` by
@@ -87513,7 +88820,12 @@ var CrushPermissions = class CrushPermissions extends ToolPermissions {
87513
88820
  const existingContent = location.fileContent ?? "";
87514
88821
  warnCrushTwinLeftovers({
87515
88822
  location,
87516
- ownedPaths: [[CRUSH_PERMISSIONS_KEY, CRUSH_ALLOWED_TOOLS_KEY], [CRUSH_OPTIONS_KEY, CRUSH_DISABLED_TOOLS_KEY]],
88823
+ ownedPaths: [
88824
+ [CRUSH_PERMISSIONS_KEY, CRUSH_ALLOWED_TOOLS_KEY],
88825
+ [CRUSH_PERMISSIONS_KEY, CRUSH_SAFE_COMMANDS_KEY],
88826
+ [CRUSH_PERMISSIONS_KEY, CRUSH_BLOCKED_COMMANDS_KEY],
88827
+ [CRUSH_OPTIONS_KEY, CRUSH_DISABLED_TOOLS_KEY]
88828
+ ],
87517
88829
  logger
87518
88830
  });
87519
88831
  const existing = parseCrushConfig(existingContent, location.filePath);
@@ -87525,12 +88837,22 @@ var CrushPermissions = class CrushPermissions extends ToolPermissions {
87525
88837
  logger
87526
88838
  });
87527
88839
  const managedToolNames = managedCrushToolNames(config);
88840
+ const commands = rebuildCrushCommandLists({
88841
+ config,
88842
+ existingPermissions,
88843
+ logger
88844
+ });
87528
88845
  const preservedAllowed = (isStringArray(existingPermissions?.["allowed_tools"]) ? existingPermissions[CRUSH_ALLOWED_TOOLS_KEY] : []).filter((entry) => entry.includes(":") || !managedToolNames.has(entry));
87529
88846
  const preservedDisabled = (isStringArray(existingOptions?.["disabled_tools"]) ? existingOptions[CRUSH_DISABLED_TOOLS_KEY] : []).filter((entry) => !managedToolNames.has(entry));
87530
88847
  const allowedList = uniq$11([...preservedAllowed, ...generated.allowed]);
87531
88848
  const disabledList = uniq$11([...preservedDisabled, ...generated.disabled]);
88849
+ const permissionsHasContent = allowedList.length > 0 || commands.safe.length > 0 || commands.blocked.length > 0;
87532
88850
  const patch = {};
87533
- if (allowedList.length > 0 || existingPermissions !== void 0) patch[CRUSH_PERMISSIONS_KEY] = { [CRUSH_ALLOWED_TOOLS_KEY]: allowedList.length > 0 ? allowedList : void 0 };
88851
+ if (permissionsHasContent || existingPermissions !== void 0) patch[CRUSH_PERMISSIONS_KEY] = {
88852
+ [CRUSH_ALLOWED_TOOLS_KEY]: listOrUndefined(allowedList),
88853
+ [CRUSH_SAFE_COMMANDS_KEY]: listOrUndefined(commands.safe),
88854
+ [CRUSH_BLOCKED_COMMANDS_KEY]: listOrUndefined(commands.blocked)
88855
+ };
87534
88856
  if (disabledList.length > 0 || existingOptions !== void 0) patch[CRUSH_OPTIONS_KEY] = { [CRUSH_DISABLED_TOOLS_KEY]: disabledList.length > 0 ? disabledList : void 0 };
87535
88857
  return new CrushPermissions({
87536
88858
  outputRoot,
@@ -87548,17 +88870,79 @@ var CrushPermissions = class CrushPermissions extends ToolPermissions {
87548
88870
  global
87549
88871
  });
87550
88872
  }
87551
- toRulesyncPermissions() {
88873
+ toRulesyncPermissions({ logger } = {}) {
87552
88874
  const permissions = isRecord(this.json["permissions"]) ? this.json[CRUSH_PERMISSIONS_KEY] : {};
87553
88875
  const options = toRecord(this.json[CRUSH_OPTIONS_KEY]);
87554
88876
  const rulesyncConfig = convertCrushListsToRulesync({
87555
- allowed: isStringArray(permissions["allowed_tools"]) ? permissions[CRUSH_ALLOWED_TOOLS_KEY] : [],
87556
- disabled: isStringArray(options["disabled_tools"]) ? options[CRUSH_DISABLED_TOOLS_KEY] : []
88877
+ allowed: stringList(permissions[CRUSH_ALLOWED_TOOLS_KEY]),
88878
+ disabled: stringList(options[CRUSH_DISABLED_TOOLS_KEY]),
88879
+ safe: stringList(permissions[CRUSH_SAFE_COMMANDS_KEY]),
88880
+ blocked: stringList(permissions[CRUSH_BLOCKED_COMMANDS_KEY]),
88881
+ logger
87557
88882
  });
87558
88883
  return this.toRulesyncPermissionsDefault({ fileContent: JSON.stringify(rulesyncConfig, null, 2) });
87559
88884
  }
87560
88885
  };
87561
88886
  /**
88887
+ * The `safe_commands` / `blocked_commands` lists a generate writes: the
88888
+ * existing entries rulesync keeps, followed by the ones derived from the
88889
+ * canonical `bash` rules. Existing `blocked_commands` entries are all kept:
88890
+ * rulesync cannot tell its own from hand-written ones, and dropping one only
88891
+ * ever loosens. A derived blocked name that is the command of a written safe
88892
+ * line is withheld, since Crush would refuse that line at exec time.
88893
+ */
88894
+ function rebuildCrushCommandLists({ config, existingPermissions, logger }) {
88895
+ const bashRules = honorAllToolsOnBash(config.permission)["bash"] ?? {};
88896
+ const shadowTest = createSafeCommandShadowTest(config.permission);
88897
+ const generated = convertBashCommandRules({
88898
+ bashRules,
88899
+ shadowTest,
88900
+ logger
88901
+ });
88902
+ const safe = uniq$11([...preserveSafeCommands({
88903
+ existing: stringList(existingPermissions?.[CRUSH_SAFE_COMMANDS_KEY]),
88904
+ bashRules,
88905
+ shadowTest,
88906
+ logger
88907
+ }), ...generated.safe]);
88908
+ const safeCommandNames = new Set(safe.flatMap((entry) => {
88909
+ const name = entry.trim().split(/\s+/)[0];
88910
+ return name === void 0 || name === "" ? [] : [normalizeCrushCommandName(name)];
88911
+ }));
88912
+ const blocked = generated.blocked.filter((name) => {
88913
+ if (!safeCommandNames.has(name)) return true;
88914
+ logger?.warn(`The "deny" rule for "bash" on ${quoteValueForWarning(name)} is not added to permissions.blocked_commands because Crush would then refuse the allowed permissions.safe_commands line(s) for that command; Crush keeps prompting for it.`);
88915
+ return false;
88916
+ });
88917
+ const existingBlocked = stringList(existingPermissions?.[CRUSH_BLOCKED_COMMANDS_KEY]);
88918
+ for (const entry of existingBlocked) {
88919
+ if (!safeCommandNames.has(normalizeCrushCommandName(entry))) continue;
88920
+ logger?.warn(`The existing permissions.blocked_commands entry ${quoteValueForWarning(entry)} is kept, but Crush will refuse the permissions.safe_commands line(s) for that command at exec time; remove one of them by hand.`);
88921
+ }
88922
+ return {
88923
+ safe,
88924
+ blocked: uniq$11([...existingBlocked, ...blocked])
88925
+ };
88926
+ }
88927
+ /**
88928
+ * The existing `safe_commands` entries a generate keeps: those the canonical
88929
+ * `bash` rules do not spell out themselves (an entry they do spell is rebuilt
88930
+ * from them), minus any entry a canonical `deny`/`ask` governs, which would
88931
+ * otherwise auto-approve what the config restricts. An entry whose exact
88932
+ * meaning cannot be read is dropped whenever the config restricts anything.
88933
+ */
88934
+ function preserveSafeCommands({ existing, bashRules, shadowTest, logger }) {
88935
+ const managedLines = new Set(Object.keys(bashRules));
88936
+ const restricts = shadowTest("*").length > 0;
88937
+ return existing.filter((entry) => {
88938
+ if (managedLines.has(entry)) return false;
88939
+ const line = effectiveSafeCommandLine(entry);
88940
+ const shadowed = line === void 0 ? restricts : shadowTest(line).length > 0;
88941
+ if (shadowed) logger?.warn(`Crush permissions.safe_commands entry ${quoteValueForWarning(entry)} was removed because a canonical deny/ask rule may cover the commands it approves.`);
88942
+ return !shadowed;
88943
+ });
88944
+ }
88945
+ /**
87562
88946
  * The Crush tool names the canonical config manages, i.e. the names its
87563
88947
  * categories map to. Entries naming any other tool are the user's and survive
87564
88948
  * a generate. The all-tools `*` category names no Crush tool of its own.
@@ -87583,7 +88967,7 @@ function resolveCategoryAction({ category, toolName, rules, logger }) {
87583
88967
  catchAllAction = action;
87584
88968
  continue;
87585
88969
  }
87586
- logger?.warn(`Crush permissions are tool-wide (no argument patterns), so the "${action}" rule for "${category}" (pattern ${quoteValueForWarning(pattern)}) was skipped.`);
88970
+ if (category !== "bash") logger?.warn(`Crush permissions are tool-wide (no argument patterns), so the "${action}" rule for "${category}" (pattern ${quoteValueForWarning(pattern)}) was skipped.`);
87587
88971
  if (action !== "allow") restricted = true;
87588
88972
  }
87589
88973
  if (catchAllAction === "allow" && restricted) {
@@ -87597,6 +88981,26 @@ function resolveCategoryAction({ category, toolName, rules, logger }) {
87597
88981
  return catchAllAction;
87598
88982
  }
87599
88983
  /**
88984
+ * The canonical rules with the all-tools `*` restrictions applied the way
88985
+ * Crush can carry them. Crush has no all-tools list, so a `*` deny or ask
88986
+ * withholds every `allow` it covers in the other categories (`{"*": {".env":
88987
+ * "deny"}, "read": {"*": "allow"}}` keeps `view` out of `allowed_tools`, and
88988
+ * Crush prompts for it), named in one warning. `bash` keeps the
88989
+ * `honorAllToolsOnBash` treatment: its allow lines become `safe_commands`, and
88990
+ * the safe-command and blocked-command logic reports what it withholds itself.
88991
+ */
88992
+ function honorCrushAllToolsRestrictions({ config, logger }) {
88993
+ const withShell = honorAllToolsOnBash(config.permission);
88994
+ const honored = honorAllToolsRestrictions({
88995
+ permission: Object.fromEntries(Object.entries(config.permission).filter(([category]) => category !== SHELL_PERMISSION_CATEGORY)),
88996
+ toolLabel: "Crush",
88997
+ logger
88998
+ });
88999
+ const permission = {};
89000
+ for (const [category, rules] of Object.entries(withShell)) permission[category] = category !== "bash" && Object.hasOwn(honored, category) ? honored[category] ?? rules : rules;
89001
+ return permission;
89002
+ }
89003
+ /**
87600
89004
  * Convert a rulesync permissions config into Crush's two tool lists.
87601
89005
  */
87602
89006
  function convertRulesyncToCrushLists({ config, logger }) {
@@ -87605,7 +89009,10 @@ function convertRulesyncToCrushLists({ config, logger }) {
87605
89009
  disabled: []
87606
89010
  };
87607
89011
  const actionByTool = /* @__PURE__ */ new Map();
87608
- for (const [category, rules] of Object.entries(honorAllToolsOnBash(config.permission))) {
89012
+ for (const [category, rules] of Object.entries(honorCrushAllToolsRestrictions({
89013
+ config,
89014
+ logger
89015
+ }))) {
87609
89016
  if (isPrototypePollutionKey(category)) continue;
87610
89017
  if (category === "*") {
87611
89018
  for (const [rawPattern, action] of Object.entries(rules)) {
@@ -87634,11 +89041,71 @@ function convertRulesyncToCrushLists({ config, logger }) {
87634
89041
  };
87635
89042
  }
87636
89043
  /**
89044
+ * Map the `bash` category's pattern rules onto Crush's command lists:
89045
+ * - `allow` on a literal command line -> `permissions.safe_commands`, which
89046
+ * Crush matches exactly (no extra arguments, no flags). It is withheld
89047
+ * when a canonical `deny`/`ask` governs any command Crush would approve
89048
+ * through it.
89049
+ * - `deny` on `<name>` / `<name> *` -> `permissions.blocked_commands`, the
89050
+ * strictest Crush can say about a single command: a direct invocation is
89051
+ * still prompted for, while the forms Crush would not prompt for and
89052
+ * indirect invocations are refused at exec time. Reported, since it is
89053
+ * not a full deny.
89054
+ * - Anything else is reported and skipped. A pattern `ask` is never written
89055
+ * to `blocked_commands`, which would refuse the command's read-only forms
89056
+ * outright, and an `allow` with a wildcard has no list that auto-approves
89057
+ * it.
89058
+ */
89059
+ function convertBashCommandRules({ bashRules, shadowTest, logger }) {
89060
+ const lists = {
89061
+ safe: [],
89062
+ blocked: []
89063
+ };
89064
+ for (const [rawPattern, action] of Object.entries(bashRules)) {
89065
+ if (isPrototypePollutionKey(rawPattern)) continue;
89066
+ const pattern = normalizeCatchAllPattern(rawPattern);
89067
+ if (pattern === "*") continue;
89068
+ const quoted = quoteValueForWarning(pattern);
89069
+ if (action === "allow") {
89070
+ if (!isExactCrushCommandLine(pattern)) {
89071
+ logger?.warn(`Crush auto-approves a command only as an exact line in permissions.safe_commands (no wildcards or shell syntax), so the "allow" rule for "bash" (pattern ${quoted}) was skipped; Crush keeps prompting for it.`);
89072
+ continue;
89073
+ }
89074
+ const shadows = shadowTest(pattern);
89075
+ if (shadows.length > 0) {
89076
+ logger?.warn(`The "allow" rule for "bash" (pattern ${quoted}) is not added to permissions.safe_commands because the deny/ask rule(s) ${shadows.map(quoteValueForWarning).join(", ")} also cover commands Crush would approve through it; Crush keeps prompting for it.`);
89077
+ continue;
89078
+ }
89079
+ lists.safe.push(pattern);
89080
+ continue;
89081
+ }
89082
+ if (action === "ask") {
89083
+ logger?.warn(`Crush has no per-command prompt list (permissions.blocked_commands would refuse the command's read-only forms outright), so the "ask" rule for "bash" (pattern ${quoted}) was skipped; Crush still prompts for it unless it is one of Crush's built-in read-only commands.`);
89084
+ continue;
89085
+ }
89086
+ const name = wholeCommandName(pattern);
89087
+ if (name !== void 0 && CRUSH_COMMAND_PREFIXES.includes(name)) {
89088
+ logger?.warn(`Crush resolves the command wrapper or keyword ${quoteValueForWarning(name)} before matching permissions.blocked_commands, so an entry for it would have no effect; the "deny" rule for "bash" (pattern ${quoted}) was skipped and Crush still prompts for it.`);
89089
+ continue;
89090
+ }
89091
+ if (name === void 0) {
89092
+ logger?.warn(`Crush can only restrict a whole command (permissions.blocked_commands), so the "deny" rule for "bash" (pattern ${quoted}) was skipped; Crush still prompts for it unless it is one of Crush's built-in read-only commands.`);
89093
+ continue;
89094
+ }
89095
+ logger?.warn(`The "deny" rule for "bash" (pattern ${quoted}) is written as permissions.blocked_commands entry ${quoteValueForWarning(name)}, which is not a full deny: Crush still prompts for a direct invocation (and runs it unprompted in yolo mode or with "bash" in allowed_tools).`);
89096
+ lists.blocked.push(name);
89097
+ }
89098
+ return {
89099
+ safe: uniq$11(lists.safe),
89100
+ blocked: uniq$11(lists.blocked)
89101
+ };
89102
+ }
89103
+ /**
87637
89104
  * Convert Crush's two tool lists back into a rulesync config. A `tool:action`
87638
89105
  * entry scopes an allow to one action of a tool, which the canonical model
87639
89106
  * cannot express, so it is left out rather than widened to the whole tool.
87640
89107
  */
87641
- function convertCrushListsToRulesync({ allowed, disabled }) {
89108
+ function convertCrushListsToRulesync({ allowed, disabled, safe, blocked, logger }) {
87642
89109
  const permission = {};
87643
89110
  const bucketFor = (category) => {
87644
89111
  const own = lookupOwn({
@@ -87654,6 +89121,29 @@ function convertCrushListsToRulesync({ allowed, disabled }) {
87654
89121
  if (entry === "" || isPrototypePollutionKey(entry)) continue;
87655
89122
  bucketFor(toCanonicalToolName$5(entry))["*"] = "deny";
87656
89123
  }
89124
+ const setBashRule = (pattern, action) => {
89125
+ const bucket = bucketFor(SHELL_PERMISSION_CATEGORY);
89126
+ if (!Object.hasOwn(bucket, pattern)) bucket[pattern] = action;
89127
+ };
89128
+ for (const entry of blocked) {
89129
+ const name = normalizeCrushCommandName(entry);
89130
+ if (name === "") continue;
89131
+ if (!isCrushCommandName(name)) {
89132
+ logger?.warn(`Crush permissions.blocked_commands entry ${quoteValueForWarning(entry)} is not a plain command name, so it was not imported.`);
89133
+ continue;
89134
+ }
89135
+ setBashRule(name, "deny");
89136
+ setBashRule(`${name} *`, "deny");
89137
+ }
89138
+ for (const entry of safe) {
89139
+ if (entry.trim() === "") continue;
89140
+ const line = effectiveSafeCommandLine(entry);
89141
+ if (line === void 0) {
89142
+ logger?.warn(`Crush permissions.safe_commands entry ${quoteValueForWarning(entry)} has no exact rulesync pattern (wildcards, shell syntax or a command wrapper), so it was not imported.`);
89143
+ continue;
89144
+ }
89145
+ setBashRule(line, "allow");
89146
+ }
87657
89147
  for (const entry of allowed) {
87658
89148
  if (entry === "" || entry.includes(":") || isPrototypePollutionKey(entry)) continue;
87659
89149
  bucketFor(toCanonicalToolName$5(entry))["*"] ??= "allow";
@@ -87967,7 +89457,17 @@ var CursorPermissions = class CursorPermissions extends ToolPermissions {
87967
89457
  function convertRulesyncToCursorPermissions(config, logger) {
87968
89458
  const allow = [];
87969
89459
  const deny = [];
87970
- for (const [category, rules] of Object.entries(honorAllToolsOnBash(config.permission))) {
89460
+ const permission = withholdAllowsShadowedByAsks({
89461
+ permission: honorAllToolsRestrictions({
89462
+ permission: config.permission,
89463
+ toolLabel: "Cursor CLI",
89464
+ logger
89465
+ }),
89466
+ toolLabel: "Cursor CLI",
89467
+ logger,
89468
+ groupOf: (category) => isMcpScopedCategory(category) ? category : toCursorType(category)
89469
+ });
89470
+ for (const [category, rules] of Object.entries(permission)) {
87971
89471
  const cursorType = toCursorType(category);
87972
89472
  for (const [pattern, action] of Object.entries(rules)) {
87973
89473
  const entry = buildToolPatternEntry({
@@ -89033,8 +90533,8 @@ const DEVIN_RESTRICTION_LOSING_SANDBOX_PATHS = [
89033
90533
  * In global mode the config file is shared with the hooks (`hooks`) feature
89034
90534
  * (MCP moved to the dedicated mcp_config.json in v3000.3), so reads and writes
89035
90535
  * merge into the existing JSON and the file is never deleted; only the keys
89036
- * this feature manages are rewritten — `permissions`, plus `sandbox` in global
89037
- * mode and the plugin governance lists (`requiredPlugins` / `optionalPlugins` /
90536
+ * this feature manages are rewritten — `permissions`, plus `sandbox` and
90537
+ * `permission_mode` in global mode and the plugin governance lists (`requiredPlugins` / `optionalPlugins` /
89038
90538
  * `forbiddenPlugins`) in project mode when the `devin` override authors them.
89039
90539
  *
89040
90540
  * The sibling `sandbox` block — which decides what a permitted command may
@@ -89142,6 +90642,12 @@ var DevinPermissions = class DevinPermissions extends ToolPermissions {
89142
90642
  });
89143
90643
  } else if (Object.keys(authoredSandboxRecord).length > 0) logger?.warn("Devin reads 'sandbox' from the user config only, so the 'devin.sandbox' override was dropped from the project config. Generate with --global to author it.");
89144
90644
  }
90645
+ applyPermissionModeOverride({
90646
+ permissionMode: config.devin?.permission_mode,
90647
+ patch,
90648
+ global,
90649
+ logger
90650
+ });
89145
90651
  applyPluginGovernanceOverride({
89146
90652
  override: config.devin,
89147
90653
  settings,
@@ -89185,6 +90691,12 @@ var DevinPermissions = class DevinPermissions extends ToolPermissions {
89185
90691
  if (DEVIN_PLUGIN_GOVERNANCE_SCHEMAS[key].safeParse(value).success) devinOverride[key] = value;
89186
90692
  else logger?.warn(`Skipped Devin \`${key}\` on import: ${key === "forbiddenPlugins" ? "expected an array of strings" : "expected an array of plugin sources (strings or objects)"}.`);
89187
90693
  }
90694
+ const permissionMode = importPermissionMode({
90695
+ value: settings.permission_mode,
90696
+ isGlobalFile: toPosixPath(this.getRelativeDirPath()) === toPosixPath(DevinPermissions.getSettablePaths({ global: true }).relativeDirPath),
90697
+ logger
90698
+ });
90699
+ if (permissionMode !== void 0) devinOverride.permission_mode = permissionMode;
89188
90700
  const result = { ...config };
89189
90701
  if (Object.keys(devinOverride).length > 0) result.devin = devinOverride;
89190
90702
  return this.toRulesyncPermissionsDefault({ fileContent: JSON.stringify(result, null, 2) });
@@ -89201,6 +90713,48 @@ const DEVIN_PLUGIN_GOVERNANCE_KEYS = [
89201
90713
  "forbiddenPlugins"
89202
90714
  ];
89203
90715
  /**
90716
+ * Decide what an imported `permission_mode` contributes to the `devin`
90717
+ * override. It is lifted from the user config only: unlike `sandbox`, a
90718
+ * project value Devin ignores is skipped with a warning rather than surfaced,
90719
+ * so it cannot slip into a `--global` generate later. `null` is Devin's
90720
+ * spelling of the default and carries nothing to keep; any other value the
90721
+ * override schema would reject is dropped with a warning so the next generate
90722
+ * cannot fail. `dangerous` is lifted but named, as on generate.
90723
+ */
90724
+ function importPermissionMode({ value, isGlobalFile, logger }) {
90725
+ if (value === void 0 || value === null) return void 0;
90726
+ if (!isGlobalFile) {
90727
+ logger?.warn("Skipped Devin `permission_mode` on import: Devin reads it from the user config only, so the project config's value has no effect. Import with --global to lift it.");
90728
+ return;
90729
+ }
90730
+ const parsed = DevinPermissionModeSchema.safeParse(value);
90731
+ if (!parsed.success) {
90732
+ logger?.warn(`Skipped Devin \`permission_mode\` ${quoteValueForWarning(value)} on import: expected one of ${DevinPermissionModeSchema.options.join(", ")}.`);
90733
+ return;
90734
+ }
90735
+ if (parsed.data === "dangerous") logger?.warn("Imported Devin `permission_mode: \"dangerous\"`: every new local session starts with all permission prompts bypassed, and the next --global generate writes it back.");
90736
+ return parsed.data;
90737
+ }
90738
+ /**
90739
+ * Patch the `permission_mode` the `devin` override authors into the user
90740
+ * `config.json`. It sets the mode new local sessions start in, and Devin reads
90741
+ * it from the user config only, so in project mode it is dropped with a
90742
+ * warning. It is only ever written as authored — never derived from the
90743
+ * canonical rules — and `dangerous` is named in a warning, because every new
90744
+ * session then starts with all permission prompts bypassed.
90745
+ *
90746
+ * @see https://docs.devin.ai/cli/reference/configuration/config-file
90747
+ */
90748
+ function applyPermissionModeOverride({ permissionMode, patch, global, logger }) {
90749
+ if (permissionMode === void 0) return;
90750
+ if (!global) {
90751
+ logger?.warn("Devin reads 'permission_mode' from the user config only, so the 'devin.permission_mode' override was dropped from the project config. Generate with --global to author it.");
90752
+ return;
90753
+ }
90754
+ patch.permission_mode = permissionMode;
90755
+ if (permissionMode === "dangerous") logger?.warn("Writing Devin `permission_mode: \"dangerous\"` to the user config: every new local session then starts with all permission prompts bypassed.");
90756
+ }
90757
+ /**
89204
90758
  * Patch the plugin governance lists the `devin` override authors into the
89205
90759
  * project `.devin/config.json`. Each authored list replaces the file's list
89206
90760
  * whole; a list it does not author is left as the file holds it. Devin reads these
@@ -89258,7 +90812,11 @@ function convertRulesyncToDevinPermissions({ config, logger }) {
89258
90812
  case "deny": deny.push(entry);
89259
90813
  }
89260
90814
  };
89261
- for (const [category, rules] of Object.entries(honorAllToolsOnBash(config.permission))) {
90815
+ for (const [category, rules] of Object.entries(honorAllToolsRestrictions({
90816
+ permission: config.permission,
90817
+ toolLabel: "Devin",
90818
+ logger
90819
+ }))) {
89262
90820
  const scope = toDevinScope(category);
89263
90821
  if (DEVIN_BARE_ONLY_SCOPES.has(scope)) {
89264
90822
  const action = collapseBareOnlyScopeRules({
@@ -90002,7 +91560,12 @@ function unmanagedEntries(existingPermission, key) {
90002
91560
  */
90003
91561
  function buildGrokPermissionArrays(config, existingPermission, logger) {
90004
91562
  const ranked = /* @__PURE__ */ new Map();
90005
- for (const [category, rules] of Object.entries(honorAllToolsOnBash(config.permission))) for (const [pattern, action] of Object.entries(rules)) {
91563
+ for (const [category, rules] of Object.entries(honorAllToolsRestrictions({
91564
+ permission: config.permission,
91565
+ toolLabel: "Grok CLI",
91566
+ logger,
91567
+ writesAllToolsCatchAll: true
91568
+ }))) for (const [pattern, action] of Object.entries(rules)) {
90006
91569
  const entry = buildGrokEntry(category, pattern);
90007
91570
  if (entry === null) {
90008
91571
  if (category === "*") {
@@ -90061,7 +91624,7 @@ function warnRemovedAllToolsRestrictions({ existingPermission, ranked, logger })
90061
91624
  * Warn about entries that a bare `*` `deny`/`ask` makes ineffective: Grok
90062
91625
  * evaluates by severity (`deny > ask > allow`), so a specific `allow` (and,
90063
91626
  * under a `*` deny, a specific `ask`) never takes effect next to it. Shell
90064
- * rules are already folded by `honorAllToolsOnBash`, so this covers the other
91627
+ * rules are already folded by `honorAllToolsRestrictions`, so this covers the other
90065
91628
  * tools.
90066
91629
  */
90067
91630
  function warnEntriesShadowedByAllTools({ ranked, logger }) {
@@ -90818,7 +92381,12 @@ var JuniePermissions = class JuniePermissions extends ToolPermissions {
90818
92381
  */
90819
92382
  function convertRulesyncToJunieRules({ config, logger, existingRules, overrideSecretFile, overrideRuleDefaults }) {
90820
92383
  const ruleLists = {};
90821
- for (const [category, patterns] of Object.entries(honorAllToolsOnBash(config.permission))) {
92384
+ const permission = honorAllToolsRestrictions({
92385
+ permission: config.permission,
92386
+ toolLabel: "Junie allowlist",
92387
+ logger
92388
+ });
92389
+ for (const [category, patterns] of Object.entries(permission)) {
90822
92390
  const group = lookupOwn({
90823
92391
  record: CANONICAL_TO_JUNIE_GROUP,
90824
92392
  key: category
@@ -90846,13 +92414,16 @@ function convertRulesyncToJunieRules({ config, logger, existingRules, overrideSe
90846
92414
  if (list === void 0 && groupDefault === void 0) continue;
90847
92415
  rules[group] = {
90848
92416
  ...groupDefault !== void 0 && { default: groupDefault },
90849
- rules: list ?? []
92417
+ rules: list === void 0 ? [] : sortRestrictionsFirst(list)
90850
92418
  };
90851
92419
  }
90852
92420
  const secretFile = overrideSecretFile ?? toRuleSet(existingRules[JUNIE_SECRET_FILE_GROUP]);
90853
92421
  if (secretFile !== void 0) rules[JUNIE_SECRET_FILE_GROUP] = sanitizeRuleSet(secretFile);
90854
92422
  return rules;
90855
92423
  }
92424
+ function sortRestrictionsFirst(list) {
92425
+ return [...list.filter((rule) => rule.action !== "allow"), ...list.filter((rule) => rule.action === "allow")];
92426
+ }
90856
92427
  /**
90857
92428
  * Map a canonical action onto a valid Junie allowlist action. Junie supports
90858
92429
  * only `allow` and `ask`; a canonical `deny` is downgraded to `ask` (the
@@ -90898,6 +92469,69 @@ function convertJunieToRulesyncPermissions({ allowlist }) {
90898
92469
  readSecretFile
90899
92470
  };
90900
92471
  }
92472
+ // src/features/permissions/last-match-restate.ts
92473
+ /**
92474
+ * OpenCode (and its forks: Kilo, MiMo Code) applies the last matching rule,
92475
+ * and the `*` key comes first in the usual file, so a later key's allow overrides a pattern-specific `*` deny or
92476
+ * ask: `{"*": {".env": "deny"}, "read": {"*": "allow"}}` would read `.env`
92477
+ * freely. Canonically the stricter rule wins whatever its width, so each such
92478
+ * restriction is restated at the end of every other key that holds a looser
92479
+ * rule it overlaps, where it is matched after that rule. A `*` catch-all
92480
+ * (`{"*": {"*": "ask"}}` followed by per-tool allows) is the documented way to
92481
+ * set an OpenCode default, so it is left where it is.
92482
+ *
92483
+ * A restated rule must never land after an overlapping stricter one, or it
92484
+ * would loosen what that rule says. The tail of a key is therefore written
92485
+ * asks first, then denies: every restated ask, then each of the key's own
92486
+ * denies and each `*` deny that overlaps one of those asks (moved after them),
92487
+ * then the restated `*` denies. A key whose own catch-all is a deny covers
92488
+ * every input of a restated ask already, so such an ask is restated as a deny.
92489
+ */
92490
+ function restateAllToolsRestrictionsLast(sharedPermission) {
92491
+ const allToolsRules = Object.hasOwn(sharedPermission, "*") ? sharedPermission["*"] : void 0;
92492
+ const restrictions = Object.entries(allToolsRules ?? {}).filter(([pattern, action]) => action !== "allow" && pattern !== "*" && !isPrototypePollutionKey(pattern));
92493
+ if (restrictions.length === 0) return sharedPermission;
92494
+ const result = {};
92495
+ for (const [key, rules] of Object.entries(sharedPermission)) result[key] = key === "*" ? rules : restateInKey({
92496
+ rules,
92497
+ restrictions
92498
+ });
92499
+ return result;
92500
+ }
92501
+ function globsOverlap(left, right) {
92502
+ return createShadowingRestrictionsTest([{
92503
+ pattern: left,
92504
+ fromAllToolsCategory: true
92505
+ }])(right).length > 0;
92506
+ }
92507
+ /** One key's rules with the `*` restrictions restated at its end; see the caller. */
92508
+ function restateInKey({ rules, restrictions }) {
92509
+ const own = Object.entries(rules);
92510
+ const ownAction = (pattern) => Object.hasOwn(rules, pattern) ? rules[pattern] : void 0;
92511
+ const overlapsLooserOwnRule = (pattern, action) => own.some(([ownPattern, existing]) => isStricterAction({
92512
+ action,
92513
+ existing
92514
+ }) && globsOverlap(pattern, ownPattern));
92515
+ const allToolsDenies = restrictions.filter(([, action]) => action === "deny").map(([pattern]) => pattern);
92516
+ let asks = restrictions.filter(([pattern, action]) => action === "ask" && overlapsLooserOwnRule(pattern, action)).map(([pattern]) => pattern);
92517
+ const denies = new Set(allToolsDenies.filter((pattern) => overlapsLooserOwnRule(pattern, "deny")));
92518
+ if (ownAction("*") === "deny") {
92519
+ for (const pattern of asks) denies.add(pattern);
92520
+ asks = [];
92521
+ }
92522
+ for (const pattern of asks) if (ownAction(pattern) === "deny") denies.add(pattern);
92523
+ asks = asks.filter((pattern) => ownAction(pattern) !== "deny");
92524
+ const overlapsAnAsk = (pattern) => asks.some((ask) => globsOverlap(ask, pattern));
92525
+ const ownDenies = own.filter(([pattern, action]) => action === "deny" && pattern !== "*").map(([pattern]) => pattern);
92526
+ for (const pattern of [...ownDenies, ...allToolsDenies]) if (overlapsAnAsk(pattern)) denies.add(pattern);
92527
+ if (asks.length === 0 && denies.size === 0) return rules;
92528
+ const tail = /* @__PURE__ */ new Set([...asks, ...denies]);
92529
+ const restated = {};
92530
+ for (const [pattern, action] of own) if (!tail.has(pattern)) restated[pattern] = action;
92531
+ for (const pattern of asks) restated[pattern] = "ask";
92532
+ for (const pattern of denies) restated[pattern] = "deny";
92533
+ return restated;
92534
+ }
90901
92535
  // src/features/permissions/kilo-permissions.ts
90902
92536
  const KiloPermissionSchema = zod_mini.z.union([zod_mini.z.enum([
90903
92537
  "allow",
@@ -91113,7 +92747,7 @@ var KiloPermissions = class KiloPermissions extends ToolPermissions {
91113
92747
  const rulesyncJson = rulesyncPermissions.getJson();
91114
92748
  const kiloOverride = rulesyncJson.kilo;
91115
92749
  const incomingPermission = {
91116
- ...honorAllToolsOnBash(rulesyncJson.permission),
92750
+ ...restateAllToolsRestrictionsLast(honorAllToolsOnBash(rulesyncJson.permission)),
91117
92751
  ...kiloOverride?.permission
91118
92752
  };
91119
92753
  if (!global && Object.hasOwn(incomingPermission, KILO_MARKDOWN_SOURCE_KEY)) {
@@ -91318,7 +92952,12 @@ function warnAboutMistypedToolLists(section) {
91318
92952
  function canonicalToKimiCodeRules({ config, logger }) {
91319
92953
  const canonicalRules = [];
91320
92954
  const overrideRules = config["kimi-code"]?.rules ?? [];
91321
- for (const [category, rules] of Object.entries(config.permission)) {
92955
+ const permission = honorAllToolsRestrictions({
92956
+ permission: config.permission,
92957
+ toolLabel: "Kimi Code",
92958
+ logger
92959
+ });
92960
+ for (const [category, rules] of Object.entries(permission)) {
91322
92961
  if (!(category === "mcp" || category.startsWith("mcp__") || lookupOwn({
91323
92962
  record: CATEGORY_TO_KIMI_CODE_TOOL,
91324
92963
  key: category
@@ -92165,7 +93804,11 @@ var KiroCapabilityPermissions = class KiroCapabilityPermissions extends ToolPerm
92165
93804
  */
92166
93805
  function buildKiroCapabilityRules({ config, logger }) {
92167
93806
  const buckets = /* @__PURE__ */ new Map();
92168
- for (const [category, rules] of Object.entries(honorAllToolsOnBash(config.permission))) {
93807
+ for (const [category, rules] of Object.entries(honorAllToolsRestrictions({
93808
+ permission: config.permission,
93809
+ toolLabel: "Kiro",
93810
+ logger
93811
+ }))) {
92169
93812
  const capability = lookupOwn({
92170
93813
  record: CANONICAL_TO_KIRO_CAPABILITY,
92171
93814
  key: category
@@ -92373,7 +94016,12 @@ function fromLettacodeRule(rule) {
92373
94016
  * absent from the config).
92374
94017
  */
92375
94018
  function buildLettacodeRuleLists({ config, existingPermissions, logger }) {
92376
- const permission = honorAllToolsOnBash(config.permission);
94019
+ const permission = honorAllToolsRestrictions({
94020
+ permission: config.permission,
94021
+ toolLabel: "Letta Code",
94022
+ logger,
94023
+ restateAs: restatesAsCategoryRule()
94024
+ });
92377
94025
  const ranked = /* @__PURE__ */ new Map();
92378
94026
  const managedCategories = /* @__PURE__ */ new Set();
92379
94027
  for (const [category, rules] of Object.entries(permission)) {
@@ -92793,7 +94441,7 @@ function toOpencodeSharedPermission({ permission, toolTarget, logger }) {
92793
94441
  sharedPermission[key] = merged;
92794
94442
  } else sharedPermission[key] = value;
92795
94443
  }
92796
- return sharedPermission;
94444
+ return restateAllToolsRestrictionsLast(sharedPermission);
92797
94445
  }
92798
94446
  const OpencodePermissionsConfigSchema = zod_mini.z.looseObject({
92799
94447
  permission: zod_mini.z.optional(zod_mini.z.union([zod_mini.z.enum([
@@ -93618,7 +95266,7 @@ function listPatterns(patterns) {
93618
95266
  * - `mcp__<server>__<tool>` is skipped: Pool approves MCP tools per server
93619
95267
  * under `mcp_servers.<server>.allow`, authored as `poolAllow` in
93620
95268
  * `.rulesync/mcp.json`. The all-tools `*` category is mirrored onto
93621
- * `bash` by `honorAllToolsOnBash` and otherwise skipped.
95269
+ * `bash` by `honorAllToolsRestrictions` and otherwise skipped.
93622
95270
  *
93623
95271
  * Project settings take project-relative paths and the user settings absolute
93624
95272
  * or `~` paths, so a path of the other kind is skipped with a warning at each
@@ -93711,7 +95359,11 @@ var PoolPermissions = class PoolPermissions extends ToolPermissions {
93711
95359
  * `tools: {}` / `paths: {}`.
93712
95360
  */
93713
95361
  function buildPoolPermissionsPatch({ config, existing, global, logger }) {
93714
- const permission = honorAllToolsOnBash(config.permission);
95362
+ const permission = honorAllToolsRestrictions({
95363
+ permission: config.permission,
95364
+ toolLabel: "Pool",
95365
+ logger
95366
+ });
93715
95367
  const existingTools = isRecord(existing["tools"]) ? existing[POOL_TOOLS_KEY] : void 0;
93716
95368
  const existingPaths = isRecord(existing["paths"]) ? existing[POOL_PATHS_KEY] : void 0;
93717
95369
  const patch = {};
@@ -94151,8 +95803,10 @@ function categoryOfRule(rule) {
94151
95803
  * when Qoder has no spelling for it.
94152
95804
  *
94153
95805
  * - The all-tools `*` category is Qoder's bare `*` rule; a narrower pattern
94154
- * under it names no single tool and is skipped (its shell restrictions
94155
- * already reached `bash` through `honorAllToolsOnBash`).
95806
+ * under it names no single tool and is skipped. `honorAllToolsRestrictions`
95807
+ * already carried it onto `bash` and withheld every allow it overlaps in the
95808
+ * other categories — a `{"*": "allow"}` included, even for a shell-only
95809
+ * pattern such as `git push *`.
94156
95810
  * - An `mcp__...` category is a fully qualified MCP tool name (or a Qoder MCP
94157
95811
  * wildcard like `mcp__github__*`) and only takes the catch-all pattern.
94158
95812
  * - Every other category maps to its Qoder tool name; `*` is the bare tool
@@ -94204,7 +95858,13 @@ function fromQoderRule(rule) {
94204
95858
  * ...). An existing entry this run writes is moved to its new list.
94205
95859
  */
94206
95860
  function buildQoderRuleLists({ config, existingPermissions, logger }) {
94207
- const permission = honorAllToolsOnBash(config.permission);
95861
+ const permission = honorAllToolsRestrictions({
95862
+ permission: config.permission,
95863
+ toolLabel: "Qoder",
95864
+ logger,
95865
+ restateAs: restatesAsCategoryRule(),
95866
+ writesAllToolsCatchAll: true
95867
+ });
94208
95868
  const ranked = /* @__PURE__ */ new Map();
94209
95869
  const managedCategories = /* @__PURE__ */ new Set();
94210
95870
  for (const [category, rules] of Object.entries(permission)) {
@@ -95017,7 +96677,10 @@ var QwencodePermissions = class QwencodePermissions extends ToolPermissions {
95017
96677
  }
95018
96678
  const displayPath = toPosixPath((0, node_path.join)(global ? "~" : ".", paths.relativeDirPath, paths.relativeFilePath));
95019
96679
  const config = rulesyncPermissions.getJson();
95020
- const { allow, ask, deny } = convertRulesyncToQwenPermissions(config);
96680
+ const { allow, ask, deny } = convertRulesyncToQwenPermissions({
96681
+ config,
96682
+ logger
96683
+ });
95021
96684
  const managedToolNames = new Set(Object.keys(config.permission).map((category) => toQwenToolName(category)));
95022
96685
  const existingPermissions = settings.permissions ?? {};
95023
96686
  const preservedAllow = (existingPermissions.allow ?? []).filter((entry) => !managedToolNames.has(parseQwenPermissionEntry(entry, { logger }).toolName));
@@ -95122,11 +96785,17 @@ var QwencodePermissions = class QwencodePermissions extends ToolPermissions {
95122
96785
  }
95123
96786
  }
95124
96787
  };
95125
- function convertRulesyncToQwenPermissions(config) {
96788
+ function convertRulesyncToQwenPermissions({ config, logger }) {
95126
96789
  const allow = [];
95127
96790
  const ask = [];
95128
96791
  const deny = [];
95129
- for (const [category, rules] of Object.entries(config.permission)) {
96792
+ const permission = honorAllToolsRestrictions({
96793
+ permission: config.permission,
96794
+ toolLabel: "Qwen Code",
96795
+ logger,
96796
+ restateAs: restatesAsCategoryRule()
96797
+ });
96798
+ for (const [category, rules] of Object.entries(permission)) {
95130
96799
  const qwenToolName = toQwenToolName(category);
95131
96800
  for (const [pattern, action] of Object.entries(rules)) {
95132
96801
  const entry = buildToolPatternEntry({
@@ -95190,7 +96859,8 @@ function convertQwenToRulesyncPermissions(params) {
95190
96859
  *
95191
96860
  * Reasonix matches a rule's tool exactly against its registered tools, which
95192
96861
  * are snake_case (`read_file`, `write_file`, `grep`, `glob`, `web_fetch`,
95193
- * `web_search`, `notebook_edit`, `task`). Only `Bash`, `Edit` (every file
96862
+ * `web_search`, `notebook_edit`, and `task` up to v2.57.x / `spawn_agents` from
96863
+ * v2.58.0). Only `Bash`, `Edit` (every file
95194
96864
  * writer: `write_file`, `edit_file`, `multi_edit`, `notebook_edit`, ...),
95195
96865
  * `Browser` and `Computer` are Claude-Code-style family aliases
95196
96866
  * (`canonicalRuleTool` / `groupOf`), so a `Read(...)` or `Write(...)` rule
@@ -95213,6 +96883,21 @@ const CANONICAL_TO_REASONIX_TOOL_NAMES = {
95213
96883
  agent: "task"
95214
96884
  };
95215
96885
  /**
96886
+ * Reasonix tool names a canonical category writes beside its primary name, for
96887
+ * a tool Reasonix renamed. studio-v2.58.0 replaced the `task` delegation family
96888
+ * with `spawn_agents` (commit ad2c96347), while the 1.x line and v2 up to
96889
+ * v2.57.x still register `task`. When Reasonix loads the config file it checks
96890
+ * only a rule's syntax: a rule naming a tool the running build lacks matches
96891
+ * nothing (v2.34.0+ reports it as dormant) and is not rejected. (The v2 Web UI
96892
+ * permissions editor refuses to newly add such a rule with `ErrUnknownTool`,
96893
+ * but keeps the ones already in the file.) So writing both names keeps an
96894
+ * `agent` rule in force on old and new builds alike. Both names are read back
96895
+ * to the same category.
96896
+ * @see https://github.com/esengine/DeepSeek-Reasonix/blob/studio-v2.58.0/internal/runtime/delegation/spawn.go
96897
+ * @see https://github.com/esengine/DeepSeek-Reasonix/blob/studio-v2.57.0/internal/runtime/delegation/task.go
96898
+ */
96899
+ const CANONICAL_TO_EXTRA_REASONIX_TOOL_NAMES = { agent: ["spawn_agents"] };
96900
+ /**
95216
96901
  * The Claude-Code-style spellings rulesync emitted before it followed the
95217
96902
  * Reasonix tool vocabulary. None of them reaches a Reasonix tool, so they are
95218
96903
  * read back on import (a file generated by an older rulesync still imports)
@@ -95235,7 +96920,8 @@ const CANONICAL_TO_LEGACY_REASONIX_TOOL_NAMES = {
95235
96920
  */
95236
96921
  const REASONIX_TO_CANONICAL_TOOL_NAMES = {
95237
96922
  ...invertRecord(CANONICAL_TO_LEGACY_REASONIX_TOOL_NAMES),
95238
- ...invertRecord(CANONICAL_TO_REASONIX_TOOL_NAMES)
96923
+ ...invertRecord(CANONICAL_TO_REASONIX_TOOL_NAMES),
96924
+ ...Object.fromEntries(Object.entries(CANONICAL_TO_EXTRA_REASONIX_TOOL_NAMES).flatMap(([canonical, names]) => names.map((name) => [name, canonical])))
95239
96925
  };
95240
96926
  /** Every Reasonix tool name a canonical category owns on generate. */
95241
96927
  function reasonixToolNamesOf(canonical) {
@@ -95243,14 +96929,20 @@ function reasonixToolNamesOf(canonical) {
95243
96929
  record: CANONICAL_TO_LEGACY_REASONIX_TOOL_NAMES,
95244
96930
  key: canonical
95245
96931
  });
95246
- const current = toReasonixToolName(canonical);
95247
- return legacy === void 0 ? [current] : [current, legacy];
96932
+ const current = toReasonixToolNames(canonical);
96933
+ return legacy === void 0 ? current : [...current, legacy];
95248
96934
  }
95249
- function toReasonixToolName(canonical) {
95250
- return lookupOwn({
96935
+ /** The Reasonix tool names a canonical category's rules are written under. */
96936
+ function toReasonixToolNames(canonical) {
96937
+ const primary = lookupOwn({
95251
96938
  record: CANONICAL_TO_REASONIX_TOOL_NAMES,
95252
96939
  key: canonical
95253
96940
  }) ?? canonical;
96941
+ const extra = lookupOwn({
96942
+ record: CANONICAL_TO_EXTRA_REASONIX_TOOL_NAMES,
96943
+ key: canonical
96944
+ });
96945
+ return extra === void 0 ? [primary] : [primary, ...extra];
95254
96946
  }
95255
96947
  function toCanonicalToolName$2(reasonixName) {
95256
96948
  return lookupOwn({
@@ -95632,7 +97324,10 @@ var ReasonixPermissions = class ReasonixPermissions extends ToolPermissions {
95632
97324
  const existingContent = await readFileContentOrNull(filePath) ?? "";
95633
97325
  const parsed = parseReasonixConfig(existingContent);
95634
97326
  const config = rulesyncPermissions.getJson();
95635
- const { allow, ask, deny } = convertRulesyncToReasonixPermissions(config);
97327
+ const { allow, ask, deny } = convertRulesyncToReasonixPermissions({
97328
+ config,
97329
+ logger
97330
+ });
95636
97331
  const managedToolNames = new Set(Object.keys(config.permission).flatMap((category) => reasonixToolNamesOf(category)));
95637
97332
  const override = config.reasonix;
95638
97333
  const rawAllow = toStringArray$1(override?.rawAllow);
@@ -95658,6 +97353,17 @@ var ReasonixPermissions = class ReasonixPermissions extends ToolPermissions {
95658
97353
  });
95659
97354
  if (droppedReadDenyEntries.length > 0) logger.warn(`Permissions feature manages '${REASONIX_READ_TOOL_NAME}' tool and will overwrite ${droppedReadDenyEntries.length} existing read deny entries (possibly from ignore feature). Permissions take precedence.`);
95660
97355
  }
97356
+ warnOnLoosenedAgentEntries({
97357
+ existingPermissions,
97358
+ managedToolNames,
97359
+ generated: {
97360
+ allow: [...allow, ...rawAllow],
97361
+ ask: [...ask, ...rawAsk],
97362
+ deny: [...deny, ...rawDeny]
97363
+ },
97364
+ relativeFilePath: relativeFilePathForLog,
97365
+ logger
97366
+ });
95661
97367
  const mergedPermissions = { ...existingPermissions };
95662
97368
  setOrDeleteEntries(mergedPermissions, "allow", [
95663
97369
  ...preservedAllow,
@@ -95833,6 +97539,55 @@ function preserveExistingEntries({ existingPermissions, managedToolNames, rawOwn
95833
97539
  deny
95834
97540
  };
95835
97541
  }
97542
+ /**
97543
+ * `spawn_agents` became a managed name with Reasonix v2.58.0 support, so a
97544
+ * stricter rule the user wrote for it by hand (e.g. a v2.58-era
97545
+ * `deny = ["spawn_agents"]` next to an older `agent: allow` source) would be
97546
+ * silently replaced by a looser one. Name every such loosening.
97547
+ */
97548
+ function warnOnLoosenedAgentEntries({ existingPermissions, managedToolNames, generated, relativeFilePath, logger }) {
97549
+ if (!logger || !managedToolNames.has("spawn_agents")) return;
97550
+ const loosened = findLoosenedEntries({
97551
+ existingPermissions,
97552
+ toolNames: new Set(reasonixToolNamesOf("agent")),
97553
+ generated
97554
+ });
97555
+ if (loosened.length === 0) return;
97556
+ logger.warn(`Permissions feature manages the Reasonix delegation tools ('task', 'spawn_agents') through the 'agent' category and will replace ${loosened.length} stricter existing entries in ${relativeFilePath}: ${loosened.join(", ")}. To keep them, tighten the 'agent' category in ${RULESYNC_RELATIVE_DIR_PATH}/${RULESYNC_PERMISSIONS_FILE_NAME} or move them to 'reasonix.rawDeny' / 'reasonix.rawAsk'.`);
97557
+ }
97558
+ const PERMISSION_STRICTNESS = {
97559
+ allow: 0,
97560
+ ask: 1,
97561
+ deny: 2
97562
+ };
97563
+ /**
97564
+ * Existing entries for `toolNames` whose action is stricter than the one the
97565
+ * generated lists give the same entry, formatted `<list> "<entry>"`. An entry
97566
+ * the generated lists drop counts as no stricter than `allow`.
97567
+ */
97568
+ function findLoosenedEntries({ existingPermissions, toolNames, generated }) {
97569
+ const generatedStrictness = /* @__PURE__ */ new Map();
97570
+ for (const list of [
97571
+ "allow",
97572
+ "ask",
97573
+ "deny"
97574
+ ]) for (const entry of generated[list]) {
97575
+ const key = normalizeToolPatternEntry(entry);
97576
+ generatedStrictness.set(key, Math.max(generatedStrictness.get(key) ?? 0, PERMISSION_STRICTNESS[list]));
97577
+ }
97578
+ const loosened = [];
97579
+ for (const list of ["ask", "deny"]) for (const entry of toStringArray$1(existingPermissions[list])) {
97580
+ if (isReasonixExactCommandEntry(entry)) continue;
97581
+ if (!toolNames.has(parseToolPatternEntry(entry).toolName)) continue;
97582
+ const key = normalizeToolPatternEntry(entry);
97583
+ if ((generatedStrictness.get(key) ?? 0) < PERMISSION_STRICTNESS[list]) loosened.push(`${list} "${entry}"`);
97584
+ }
97585
+ return loosened;
97586
+ }
97587
+ /** Spell an entry the way rulesync writes it, so `name(*)` equals `name`. */
97588
+ function normalizeToolPatternEntry(entry) {
97589
+ return buildToolPatternEntry(parseToolPatternEntry(entry));
97590
+ }
95836
97591
  /** Sort, dedupe and set a permissions array key, deleting it when empty. */
95837
97592
  function setOrDeleteEntries(table, key, entries) {
95838
97593
  const merged = (0, es_toolkit.uniq)(entries.toSorted());
@@ -95842,26 +97597,28 @@ function setOrDeleteEntries(table, key, entries) {
95842
97597
  /**
95843
97598
  * Convert rulesync permissions config to Reasonix allow/ask/deny arrays.
95844
97599
  */
95845
- function convertRulesyncToReasonixPermissions(config) {
97600
+ function convertRulesyncToReasonixPermissions({ config, logger }) {
95846
97601
  const allow = [];
95847
97602
  const ask = [];
95848
97603
  const deny = [];
95849
- for (const [category, rules] of Object.entries(config.permission)) {
95850
- const reasonixToolName = toReasonixToolName(category);
95851
- for (const [pattern, action] of Object.entries(rules)) {
95852
- const entry = buildToolPatternEntry({
95853
- toolName: reasonixToolName,
95854
- pattern
95855
- });
95856
- switch (action) {
95857
- case "allow":
95858
- allow.push(entry);
95859
- break;
95860
- case "ask":
95861
- ask.push(entry);
95862
- break;
95863
- case "deny": deny.push(entry);
95864
- }
97604
+ const permission = honorAllToolsRestrictions({
97605
+ permission: config.permission,
97606
+ toolLabel: "Reasonix",
97607
+ logger
97608
+ });
97609
+ for (const [category, rules] of Object.entries(permission)) for (const reasonixToolName of toReasonixToolNames(category)) for (const [pattern, action] of Object.entries(rules)) {
97610
+ const entry = buildToolPatternEntry({
97611
+ toolName: reasonixToolName,
97612
+ pattern
97613
+ });
97614
+ switch (action) {
97615
+ case "allow":
97616
+ allow.push(entry);
97617
+ break;
97618
+ case "ask":
97619
+ ask.push(entry);
97620
+ break;
97621
+ case "deny": deny.push(entry);
95865
97622
  }
95866
97623
  }
95867
97624
  return {
@@ -96088,7 +97845,7 @@ var RooPermissions = class extends ToolPermissions {
96088
97845
  validate: true
96089
97846
  });
96090
97847
  }
96091
- toRulesyncPermissions() {
97848
+ toRulesyncPermissions({ logger } = {}) {
96092
97849
  const constructor = this.constructor;
96093
97850
  let settings;
96094
97851
  try {
@@ -96102,9 +97859,12 @@ var RooPermissions = class extends ToolPermissions {
96102
97859
  } catch (error) {
96103
97860
  throw new Error(`Failed to parse ${constructor.getToolLabel()} VS Code settings in ${(0, node_path.join)(this.getRelativeDirPath(), this.getRelativeFilePath())}: ${formatError(error)}`, { cause: error });
96104
97861
  }
96105
- const rules = {};
96106
- for (const pattern of toStringArray$1(settings[constructor.getAllowedCommandsKey()])) rules[pattern] = "allow";
96107
- for (const pattern of toStringArray$1(settings[constructor.getDeniedCommandsKey()])) rules[pattern] = "deny";
97862
+ const rules = importVscodeCommandLists({
97863
+ allowed: toStringArray$1(settings[constructor.getAllowedCommandsKey()]),
97864
+ denied: toStringArray$1(settings[constructor.getDeniedCommandsKey()]),
97865
+ toolLabel: constructor.getToolLabel(),
97866
+ logger
97867
+ });
96108
97868
  const permission = {};
96109
97869
  if (Object.keys(rules).length > 0) permission[COMMAND_CATEGORY] = rules;
96110
97870
  return this.toRulesyncPermissionsDefault({ fileContent: JSON.stringify({ permission }, null, 2) });
@@ -97866,14 +99626,19 @@ async function readTaktRuntimeConfig({ outputRoot, logger }) {
97866
99626
  /**
97867
99627
  * Collapse a rulesync permissions config into Takt's single coarse mode.
97868
99628
  *
97869
- * Precedence: any `deny` ⇒ `readonly`; else an `edit`/`write` `allow` ⇒ `edit`;
97870
- * else a `bash` `allow` ⇒ `full`; else the safe default `readonly`.
99629
+ * Precedence: any `deny` or `ask` ⇒ `readonly`; else an `edit`/`write` `allow`
99630
+ * ⇒ `edit`; else a `bash` `allow` ⇒ `full`; else the safe default `readonly`.
99631
+ *
99632
+ * An `ask` restricts like a `deny` here: Takt's coarse modes have no prompting
99633
+ * tier, so a mode derived from the allows beside it (`full` for `{"git *":
99634
+ * "allow", "git push *": "ask"}`) would auto-approve what the ask should prompt
99635
+ * for — the canonical order is `deny > ask > allow`.
97871
99636
  */
97872
99637
  function deriveTaktPermissionMode(config) {
97873
99638
  let hasEditAllow = false;
97874
99639
  let hasBashAllow = false;
97875
99640
  for (const [category, rules] of Object.entries(config.permission)) for (const action of Object.values(rules)) {
97876
- if (action === "deny") return "readonly";
99641
+ if (action === "deny" || action === "ask") return "readonly";
97877
99642
  if (action === "allow") {
97878
99643
  if (category === "edit" || category === "write") hasEditAllow = true;
97879
99644
  else if (category === "bash") hasBashAllow = true;
@@ -98156,7 +99921,12 @@ function buildMcpRules({ permission, existing, logger }) {
98156
99921
  /** Split the canonical `webfetch` rules into TRAE's network allow/deny lists. */
98157
99922
  function buildNetworkLists({ webfetchRules, logger }) {
98158
99923
  const ranked = /* @__PURE__ */ new Map();
98159
- for (const [pattern, action] of Object.entries(webfetchRules)) {
99924
+ const { webfetch: rules = {} } = withholdAllowsShadowedByAsks({
99925
+ permission: { webfetch: webfetchRules },
99926
+ toolLabel: "TRAE resourceAuthorization.network",
99927
+ logger
99928
+ });
99929
+ for (const [pattern, action] of Object.entries(rules)) {
98160
99930
  if (isPrototypePollutionKey(pattern)) continue;
98161
99931
  if (pattern === "*") {
98162
99932
  logger?.warn(`TRAE permissions: skipping the 'webfetch' rule '*' — TRAE sets the default network policy in the custom permission mode ('customProfiles.defaultCustomProfile.network.default'), not in resourceAuthorization.`);
@@ -98284,7 +100054,11 @@ var TraePermissions = class TraePermissions extends ToolPermissions {
98284
100054
  fileContent: existingContent,
98285
100055
  relativePath
98286
100056
  });
98287
- const permission = honorAllToolsOnBash(rulesyncPermissions.getJson().permission);
100057
+ const permission = honorAllToolsRestrictions({
100058
+ permission: rulesyncPermissions.getJson().permission,
100059
+ toolLabel: "TRAE",
100060
+ logger
100061
+ });
98288
100062
  warnUnmappedCategories({
98289
100063
  permission,
98290
100064
  logger
@@ -98533,7 +100307,18 @@ var VibePermissions = class VibePermissions extends ToolPermissions {
98533
100307
  const filePath = (0, node_path.join)(outputRoot, paths.relativeDirPath, paths.relativeFilePath);
98534
100308
  const existingContent = await readFileContentOrNull(filePath) ?? "";
98535
100309
  const config = parseVibeConfig(existingContent);
98536
- const permission = honorAllToolsOnBash(rulesyncPermissions.getJson().permission);
100310
+ const permission = withholdAllowsShadowedByAsks({
100311
+ permission: honorAllToolsRestrictions({
100312
+ permission: rulesyncPermissions.getJson().permission,
100313
+ toolLabel: "Vibe",
100314
+ logger,
100315
+ restateAs: restatesAsCategoryRule(["deny"]),
100316
+ downgradeWithheldCatchAll: true
100317
+ }),
100318
+ toolLabel: "Vibe",
100319
+ logger,
100320
+ isSkippedAsk: ({ pattern }) => pattern !== "*"
100321
+ });
98537
100322
  const vibeOverride = rulesyncPermissions.getJson().vibe;
98538
100323
  const tools = toVibeToolsRecord(config.tools);
98539
100324
  const diskShellPatterns = new Map([VIBE_SHELL_CATEGORY, ...VIBE_SHELL_ALIAS_TOOL_NAMES].map((vibeToolName) => [vibeToolName, toStringArray$1(readVibeToolConfig({
@@ -98582,6 +100367,12 @@ var VibePermissions = class VibePermissions extends ToolPermissions {
98582
100367
  logger
98583
100368
  });
98584
100369
  const tableCategories = Object.entries(permission).filter(([category]) => category !== VIBE_SUBAGENT_CATEGORY && category !== VIBE_OUTSIDE_WORKDIR_CATEGORY);
100370
+ retireWithheldAllows({
100371
+ source: rulesyncPermissions.getJson().permission,
100372
+ permission,
100373
+ tools,
100374
+ resolveNames
100375
+ });
98585
100376
  for (const [category, rules] of tableCategories) {
98586
100377
  const vibeToolNames = resolveNames(category);
98587
100378
  if (vibeToolNames === void 0) {
@@ -98966,6 +100757,49 @@ function applyCategoryRulesToTool({ vibeToolName, category, rules, tools, enable
98966
100757
  tools[vibeToolName] = nextTool;
98967
100758
  }
98968
100759
  /**
100760
+ * Remove from the existing tables what the current restrictions forbid. The
100761
+ * per-tool pass merges into the `allowlist` already on disk and only sets
100762
+ * `permission` when the category states a `*` rule, so a regenerate would
100763
+ * otherwise keep an `allowlist` entry (an earlier generate's, or a
100764
+ * hand-written one) that auto-approves what a canonical ask or deny now
100765
+ * covers, or the `permission = "always"` an earlier config wrote for an allow
100766
+ * that is now withheld. Only the tables of categories the config manages are
100767
+ * touched, and only entries that overlap a restriction are removed. A
100768
+ * category's own catch-all ask is the documented default its allowlist carves
100769
+ * out of, so it removes nothing.
100770
+ */
100771
+ function retireWithheldAllows({ source, permission, tools, resolveNames }) {
100772
+ const allToolsRestrictions = Object.entries(lookupOwn({
100773
+ record: source,
100774
+ key: "*"
100775
+ }) ?? {}).filter(([pattern, action]) => action === "deny" || action === "ask" && pattern !== "*");
100776
+ for (const [category, rules] of Object.entries(source)) {
100777
+ if (category === "*") continue;
100778
+ const honored = lookupOwn({
100779
+ record: permission,
100780
+ key: category
100781
+ }) ?? {};
100782
+ const withheld = new Set(Object.entries(rules).filter(([pattern, action]) => action === "allow" && honored[pattern] !== "allow").map(([pattern]) => pattern));
100783
+ const restrictions = [...Object.entries(honored).filter(([pattern, action]) => action !== "allow" && pattern !== "*"), ...allToolsRestrictions].map(([pattern]) => ({
100784
+ pattern,
100785
+ fromAllToolsCategory: false
100786
+ }));
100787
+ const globShadowed = createShadowingRestrictionsTest(restrictions);
100788
+ const shadowed = (pattern) => category === "webfetch" ? restrictions.some((restriction) => urlPatternsOverlap(restriction.pattern, pattern)) : globShadowed(pattern).length > 0;
100789
+ const retires = (pattern) => withheld.has(pattern) || restrictions.length > 0 && honored[pattern] !== "allow" && shadowed(pattern);
100790
+ for (const vibeToolName of resolveNames(category) ?? []) {
100791
+ if (!Object.hasOwn(tools, vibeToolName)) continue;
100792
+ const tool = readVibeToolConfig({
100793
+ tools,
100794
+ vibeToolName
100795
+ });
100796
+ for (const key of ["allow", "allowlist"]) if (tool[key] !== void 0) tool[key] = toStringArray$1(tool[key]).filter((pattern) => !retires(pattern));
100797
+ if (withheld.size > 0 && tool.permission === "always" && !Object.hasOwn(honored, "*")) tool.permission = "ask";
100798
+ tools[vibeToolName] = tool;
100799
+ }
100800
+ }
100801
+ }
100802
+ /**
98969
100803
  * `enabled_tools` is an exclusive allowlist and therefore only ever
98970
100804
  * rulesync-authored explicitly, through `vibe.enabled_tools`. When the
98971
100805
  * override declares it (even empty), rulesync owns the whole list; when it
@@ -101428,6 +103262,9 @@ const toolPermissionsFactories = /* @__PURE__ */ new Map([
101428
103262
  var PermissionsProcessor = class extends FeatureProcessor {
101429
103263
  toolTarget;
101430
103264
  global;
103265
+ sweepsThroughInRootLinks() {
103266
+ return this.global;
103267
+ }
101431
103268
  constructor({ outputRoot = process.cwd(), inputRoots, toolTarget, global = false, dryRun = false, logger }) {
101432
103269
  super({
101433
103270
  outputRoot,
@@ -104671,6 +106508,12 @@ Object.defineProperty(exports, "assertDirectoryIfExists", {
104671
106508
  return assertDirectoryIfExists;
104672
106509
  }
104673
106510
  });
106511
+ Object.defineProperty(exports, "assertLandingOutsideVcsMetadata", {
106512
+ enumerable: true,
106513
+ get: function() {
106514
+ return assertLandingOutsideVcsMetadata;
106515
+ }
106516
+ });
104674
106517
  Object.defineProperty(exports, "assertNoSymlinkBelowRoot", {
104675
106518
  enumerable: true,
104676
106519
  get: function() {
@@ -104713,6 +106556,12 @@ Object.defineProperty(exports, "checkPathTraversal", {
104713
106556
  return checkPathTraversal;
104714
106557
  }
104715
106558
  });
106559
+ Object.defineProperty(exports, "classifyRemoteName", {
106560
+ enumerable: true,
106561
+ get: function() {
106562
+ return classifyRemoteName;
106563
+ }
106564
+ });
104716
106565
  Object.defineProperty(exports, "convertFromTool", {
104717
106566
  enumerable: true,
104718
106567
  get: function() {
@@ -104845,16 +106694,16 @@ Object.defineProperty(exports, "groupSpellingsByCaseFoldedIdentity", {
104845
106694
  return groupSpellingsByCaseFoldedIdentity;
104846
106695
  }
104847
106696
  });
104848
- Object.defineProperty(exports, "hasDeceptiveHiddenCharacters", {
106697
+ Object.defineProperty(exports, "hasEnclosingMarkOutsideKeycap", {
104849
106698
  enumerable: true,
104850
106699
  get: function() {
104851
- return hasDeceptiveHiddenCharacters;
106700
+ return hasEnclosingMarkOutsideKeycap;
104852
106701
  }
104853
106702
  });
104854
- Object.defineProperty(exports, "hasEnclosingMarkOutsideKeycap", {
106703
+ Object.defineProperty(exports, "hasWindowsFoldableName", {
104855
106704
  enumerable: true,
104856
106705
  get: function() {
104857
- return hasEnclosingMarkOutsideKeycap;
106706
+ return hasWindowsFoldableName;
104858
106707
  }
104859
106708
  });
104860
106709
  Object.defineProperty(exports, "importFromTool", {
@@ -105103,6 +106952,12 @@ Object.defineProperty(exports, "stripHiddenCharacters", {
105103
106952
  return stripHiddenCharacters;
105104
106953
  }
105105
106954
  });
106955
+ Object.defineProperty(exports, "sweepRefusalReason", {
106956
+ enumerable: true,
106957
+ get: function() {
106958
+ return sweepRefusalReason;
106959
+ }
106960
+ });
105106
106961
  Object.defineProperty(exports, "toInstructionBudgetFile", {
105107
106962
  enumerable: true,
105108
106963
  get: function() {