Skip to content

Claude Code is an agentic coding tool that lives in your terminal, understands your codebase, and helps you code faster by executing routine tasks, explaining complex code, and handling git workflows - all through natural language commands.

TypeScript

chore: Update mods/

GitHub Actions (publish-mods)3deb87368737
diff --git a/mods/README.md b/mods/README.md
index 49bf21ee..4d94c749 100644
--- a/mods/README.md
+++ b/mods/README.md
@@ -7,7 +7,7 @@ source, published as it is built into the binary.
| Mod | What it does | Seated |
| --- | --- | --- |
-| [`sec-default`](sec-default) | Keeps an organization's classic hooks, prompt content, managed settings, tool policy and deny rules out of reach of the plugins a person installs; adds no policy of its own. | Outermost, on a machine with managed settings or for a Team or Enterprise organization, unless managed `prependPlugins` says otherwise |
+| [`sec-default`](sec-default) | Keeps an organization's classic hooks, prompt content, managed settings, tool policy, permission rules and pinned environment out of reach of the plugins a person installs; adds no policy of its own. | Outermost, on a machine with managed settings or a managed-mcp.json, or for a Team or Enterprise organization, and from then on for the session, unless managed `prependPlugins` says otherwise |
| [`diff`](diff) | `/diff`: the session's uncommitted changes in a pane beside the transcript, file by file with their hunks, refreshed as Claude edits files and runs commands. | Built in |
| [`telemetry`](telemetry) | Hooks `$.telemetry`'s two events (`log`, `mark`), adding the noun in the `engine.create` fold where the engine has none, so a built-in plugin can record an event as a first-party analytics row, sent in batches; refuses installed plugins; sends nothing wherever Claude Code's analytics are off. | Built in |
| [`agents-md`](agents-md) | `AGENTS.md` as project instructions, by one option: loaded where the project has no `CLAUDE.md` of its own (`claude-md-or-agents-md`, the default) or beside it (`claude-md-and-agents-md`), placed and framed exactly as the engine places `CLAUDE.md`, nested ones on a `Read`; or the project's and the person's instruction files dropped and the organization's kept (`managed-only`); or `CLAUDE.md` alone, as the engine reads it (`claude-md`). | Built in |
diff --git a/mods/sec-default/.claude-plugin/plugin.json b/mods/sec-default/.claude-plugin/plugin.json
index 5cffa260..32efacde 100644
--- a/mods/sec-default/.claude-plugin/plugin.json
+++ b/mods/sec-default/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "sec-default",
"version": "0.1.0",
- "description": "Security default for organizations: seated outermost, it keeps the organization's classic hooks, prompt content, settings and tool policy out of reach of the plugins a person installs, and adds no policy of its own; one managed option, allowManagedModsOnly, limits mods to the organization's.",
+ "description": "Security default for organizations: seated outermost, it keeps the organization's classic hooks, prompt content, settings, tool policy and pinned environment out of reach of the plugins a person installs, and adds no policy of its own; one managed option, allowManagedModsOnly, limits mods to the organization's.",
"author": {
"name": "Anthropic"
}
diff --git a/mods/sec-default/README.md b/mods/sec-default/README.md
index 98bbc1c2..994ca8b6 100644
--- a/mods/sec-default/README.md
+++ b/mods/sec-default/README.md
@@ -26,15 +26,20 @@ settings it decides by.
| event | from the outermost seat |
| --- | --- |
| `classic.*` | Continue past the user tier: the organization's settings hooks see the engine's input and their answer stands. |
-| `prompt.section`, `prompt.context`, `skill.prompt`, `attribution.text` | Continue past the user tier: managed CLAUDE.md, rules and policy skills reach the model as written. A person's plugins keep `prompt.submit` and its additive context. |
+| `prompt.section`, `prompt.context`, `prompt.attachment`, `skill.prompt`, `attribution.text` | Continue past the user tier: managed CLAUDE.md, rules and policy skills, and what the engine injects for the model beside them (a settings hook's note, the instruction files, a mode's reminder), are not a person's plugin's to reword at these events. A person's plugins keep `prompt.submit` and its additive context. |
+| `session.append` | For a row the engine injects for the model (the `attachment` and `hook-context` doors: a reminder, a settings hook's context), for a compaction's rows (the `compaction` door: its summary and boundary), for a skill's body as a call of the Skill tool hands it over (the `tool-message` door, that tool's rows alone, since the row does not say whose skill it is) and for a note an organization's plugin appends, continue past the user tier: the row is kept as made, so what passed `prompt.attachment` whole is not blanked or reworded on its way into the conversation. For a skill the hold does that much and no more: it stops rewording of the row in transit. A person's `tool.call` hook can still answer for a Skill call or swap `input.skill`, as it can for any tool; `allowManagedModsOnly` closes that. Every other row (a prompt, a response, a tool result, another tool's message, a delivery, a command's row, a notice, a note of a person's plugin, and a note the engine itself makes, a Stop hook's feedback among them) passes as the chain leaves it. What is held of a hook is its verdict and the context it adds; the words a hook's block feeds back to the model are such an engine-made note. |
+| `session.compact` | Continue past the user tier, whole: a conversation a person's plugin answers in place of a compaction is never installed, so the conversation a compaction leaves is the engine's or the organization's own making, and its summary is stored as made (the `session.append` row). A person's own compaction hook does not run where this plugin is seated; a plugin of theirs may still ask for a compaction, which the engine then makes. |
| `prompt.compose` | Continue past the user tier: the system prompt's list of sections is what the organization's tiers, the built-ins and the engine's own composition make it. A person's plugin neither drops, reorders nor rewrites a section, nor changes the facts the list is composed from, nor answers a list of its own in its place. The engine raises this event only when some loaded plugin hooks it, so where this plugin is seated every render of the system prompt runs the chain. |
| `settings.read` | Continue past the user tier: no user hook rewrites what any caller reads as settings, this plugin's own policy reads included. |
| `tool.describe`, `command.describe`, `agent.offer`, `agent.spawn` | When the subject's pinned `e.provider.tier` is `prepend` or `append` (a policy-installed plugin, the managed folder, a policy MCP server), continue past the user tier; a subject provided by `user`, `builtin` or `core` passes. |
-| `tool.register` | A caller in `prepend` or `append` continues past the user tier. A `user`-tier caller is refused by name while managed settings hold `allowedMcpServers` (set at all, empty included); otherwise it passes. |
-| `tool.list` | The tools of the organization's managed MCP servers are listed as the organization's tiers listed them; every other tool as the user tier left it. With no policy to read, or a refusal from either listing, the organization's listing stands whole. |
-| `tool.check` | A deny that a settings rule decided holds over the user tier: when a person's plugin loosened the verdict it was handed, the dispatch is run again past the user tier, and if that verdict is a deny naming its rule, it is the answer. See [Deny rules hold](#deny-rules-hold). Every other verdict passes as the chain left it. |
+| `tool.register` | A caller in `prepend` or `append` continues past the user tier. A `user`-tier caller is refused by name while managed settings hold `allowedMcpServers` (set at all, empty included). With no allowlist, one is still refused whose tool, called `mcp__<plugin>__<tool>`, would read as a tool of a server the organization delivers: a `managedMcpServers` entry, or a server of the enterprise `managed-mcp.json`, which the policy read names under that key. So is one whose name reads as a plugin the organization seats itself (`prependPlugins`, `appendPlugins`, or an id managed `enabledPlugins` turns on, by `true` or by a version list, as the engine reads an entry), or as an MCP server such a plugin's own manifest declares, which the engine spells under the plugin's scope (`mcp__plugin_<plugin>_<server>__`). A `user`-tier plugin keeps its own name exactly when the id the engine recorded for it (`<name>@<marketplace>`: the settings key the loader resolved, never the plugin's manifest) is one managed `enabledPlugins` turn on, compared as the engine compares ids (NFC, then lower case). That is how an organization's own plugin registers its tools where the engine leaves it in the `user` tier: only a copy read in place from a local folder marketplace that managed settings name is vouched for, so a plugin from a remote marketplace (git, GitHub, npm) can never be vouched for in this release, and neither is one a version list turns on. For an organization that means such a plugin runs among a person's plugins in the chain, not ahead of them, and keeps its tools by this exemption alone. A plugin loaded with `--plugin-dir` is always `<name>@inline` and never matches; nor does a same-named plugin from another marketplace, one whose name only folds to the organization's, or an id policy lists only in `prependPlugins` or `appendPlugins`. A person who registers a marketplace of their own under the organization's marketplace name gets an equal id, and so the exemption: it gives that plugin what every plugin had before this hold existed, and `strictKnownMarketplaces` in managed settings closes it today by allowing no other marketplace source. The mod hears a plugin's id at its admission, so after a load that seats the mod afresh while other plugins stay seated (a load that folds again, as a policy change mid-session can cause) the organization's own plugin is refused its name until the session restarts. A plugin's own MCP servers are connected by the engine from its manifest, not registered through `tool.register`, so they are unaffected. An id's name is everything before its last at-sign, as the engine parts ids, so a scoped `@scope/name@npm` counts. A `managed-mcp.json` that is present and cannot be read whole names nobody: the policy read marks it (`managedMcpServersUnreadable`) and every such registration is refused while it stands, its servers never taken for none; the only other reader of the mark is `tool.list` (the next row), so a person's plugins still load and still set what is not pinned. A server the file names and the engine dropped with a warning is still named; a warning about a server that loads is no failure. Names are compared folded, as a model reads them (spelled as the engine spells a name inside a tool's name, every character outside letters, digits, `-` and `_` a `_` and nothing normalized; then lower case, every run of `-` and `_` one `_`; a seated plugin counts under its name composed and decomposed, since the engine spells its tools from its manifest's own form): a plugin named as the server in any case or with other separators, one whose name and tool together spell it, and one whose tool's own name folds to nothing, is refused. A server whose name folds to nothing (no letter or digit in it) cannot be told from any name, so while the policy names one every `user`-tier registration is refused. The engine pins the tool's name at this event (a hook beneath that hands on another name fails, and the chain goes on without it), so the name judged is the name registered. Otherwise it passes. |
+| `tool.list` | The tools of the organization's managed MCP servers, of the plugins it seats itself and of the MCP servers those plugins' own manifests declare (told by the name whole, as the engine spells it inside a tool's name: `mcp__<server>__`, never by a fold, so another server whose name only begins like the organization's is not taken for it; a seated plugin and its own servers, under its scope `mcp__plugin_<plugin>_`, fold to fold as the registration check compares, so policy may list its id in another letter case, and another plugin whose name begins with the seated one's and a `-` or `_` reads the same) are listed as the organization's tiers listed them; every other tool as the user tier left it. Where the server file cannot be read, every `mcp__` tool counts as the organization's. With no policy to read, or a refusal from either listing, the organization's listing stands whole. |
+| `tool.check` | A deny, and an ask a settings rule, a classic hook or an organization's ceiling on the tool stands behind, hold whole over the user tier: when a person's plugin rewrote the verdict it was handed without tightening it (a more permissive decision, or the same decision under another reason, rule or hook), the dispatch is run again past the user tier, and unless the chain's answer is the stricter, that verdict, if it is a deny or names the rule, the hook or the ceiling behind it, is the answer as the engine gave it. See [Deny rules hold](#deny-rules-hold). Every other verdict passes as the chain left it. |
+| `ui.log` | A line a plugin in `prepend` or `append` logs, this one's included, continues past the user tier: no user hook rewrites or drops it, and none runs inside the hook that logged it. Every other line passes. |
+| `env.get` | A read by a plugin in `prepend` or `append` continues past the user tier: no user hook answers what the organization's own plugin reads. Every other read passes. |
+| `env.set` | A write by a plugin in `prepend` or `append` continues past the user tier, whatever the variable: no user hook rewrites or drops what the organization's own plugin sets. A variable managed settings set in `env` (its name in any case) is pinned, and so are `CLAUDE_CODE_PROCESS_WRAPPER` where they name a launcher with `processWrapper` and, always, the nine variables that move where policy and sign-in are read from or how policy's tiers compose (`CLAUDE_CODE_MANAGED_SETTINGS_PATH`, `CLAUDE_CODE_REMOTE_SETTINGS_PATH`, `CLAUDE_CODE_MOCK_REMOTE_SETTINGS`, `CLAUDE_CODE_DISABLE_ADMIN_ENV_UNION`, `CLAUDE_CONFIG_DIR`, `CLAUDE_SECURESTORAGE_CONFIG_DIR`, `USE_LOCAL_OAUTH`, `USE_STAGING_OAUTH` and `CLAUDE_LOCAL_OAUTH_API_BASE`, which choose the server sign-in goes to; all nine on every build): setting or unsetting it, a `user`-tier caller is refused by name and a built-in's write continues past the user tier. Any other variable is a person's plugin's to set. With no policy to read, every variable counts as pinned. `allowModsToOverrideDenyRules` does not unpin. See [Pinned variables](#pinned-variables). |
| `plugin.register` | A hooks module in the `user` tier (one a person installed, named with `--plugin-dir`, or keeps in their mods folder) is refused while managed settings set this plugin's `allowManagedModsOnly` option; otherwise it passes. Modules in `prepend`, `append` and `builtin` are never asked about. |
-| everything else | Passes: `prompt.submit`, `turn.*`, `tool.call`, `command.run`, `command.register`, `session.*`, `ui.*`, `fs.*`, `http.fetch`, `process.run`, `store.*`, `clock.*`, `model.*`, `mcp.call`, `audio.*`, `agent.list`, `engine.create`. |
+| everything else | Passes: `prompt.submit`, `turn.*`, `tool.call`, `command.run`, `command.register`, `command.list`, `agent.register`, `config.*`, `prompt.fill`, `prompt.suggest`, `prompt.edit`, `prompt.read`, `session.*` but `session.append` and `session.compact`, `ui.*` but `ui.log`, `fs.*`, `http.fetch`, `process.run`, `store.*`, `clock.*`, `model.*`, `mcp.call`, `audio.*`, `agent.list`, `engine.create`. |
## Options an administrator sets
@@ -87,25 +92,30 @@ not loaded. Settings hooks, status lines and `/goal` are not touched by it.
`allowModsToOverrideDenyRules`: the plugins a person installs may answer
over a settings deny rule on `tool.check`, as they could before this plugin
-held deny rules. Off unless it is the literal `true`; an option that reads
-as unset leaves deny rules holding. See [Deny rules hold](#deny-rules-hold).
+held deny rules, and over every other deny, an ask rule or a classic hook's
+ask with it: the one option covers all that holds there. Off unless it is the
+literal `true`; an option that reads as unset leaves them holding. See
+[Deny rules hold](#deny-rules-hold).
## What it hooks
-`classic.*`, `prompt.section`, `prompt.context`, `prompt.compose`, `skill.prompt`,
-`attribution.text`, `settings.read`, `tool.describe`, `command.describe`,
+`classic.*`, `prompt.section`, `prompt.context`, `prompt.attachment`,
+`prompt.compose`, `skill.prompt`,
+`attribution.text`, `session.append`, `session.compact`, `settings.read`, `tool.describe`, `command.describe`,
`agent.offer`, `agent.spawn`, `tool.register`, `tool.list`, `tool.check`,
-`plugin.register`.
+`ui.log`, `env.get`, `env.set`, `plugin.register`.
Hooking `tool.check` has a cost: the engine raises that event only when some
loaded plugin hooks it, so where this plugin is seated every tool call now
runs the `tool.check` chain, where before only a session with such a plugin
-did.
+did. So has hooking `ui.log`, `env.get` and `env.set`: each such call of any
+plugin's now runs a chain, and an `env.set` from outside the organization's tiers waits on
+the policy read.
## What it calls on `$`
`settings.read`, and `ui.log`: to the debug log, and for the one line a
-person reads when a deny rule held over a plugin of theirs. It continues to
+person reads when something held over a plugin of theirs. It continues to
the `append` tier with `next.to`, which only a plugin in a managed tier may
do.
@@ -113,52 +123,79 @@ do.
On `tool.check` any hook may answer any verdict, so a plugin a person
installs to stop the permission prompts (`() => ({ decision: "allow" })`)
-would also lift a deny rule, a managed one included. Where this plugin is
-seated it does not:
+would also lift a deny rule, an ask rule or a `PreToolUse` hook's ask, a
+managed one included. Where this plugin is seated it does not:
-- The hook first runs the chain as it is. If the answer is a deny, or no
- link that may hold a person's plugin answered more permissively than the
- verdict handed up to it, the answer passes: nothing of the person's
- loosened anything, and a plugin that only listens adds no run of its own.
+- The hook first runs the chain as it is. If no link that may hold a
+ person's plugin rewrote the verdict handed up to it (a more permissive
+ decision, or the same decision under another reason, rule or hook; a
+ tightening is no rewrite), the answer passes: nothing of the person's
+ changed anything, and a plugin that only listens, or only tightens, adds no
+ run of its own.
This is read off `next.trace`, whose tiers the engine pins: a link that never
called `next` is measured against a deny, and since the engine lists
neighbouring plugins that share a worker as one batch under its first
member's tier, a `prepend` entry beneath this plugin counts as well as a
- `user` one. Whether a person's plugin did the loosening is never settled
+ `user` one. Whether a person's plugin did the rewriting is never settled
here, only by the next step.
- Otherwise it runs the dispatch once more with the user tier left out
(`next.to(e, "append")`). That verdict never passed through a person's
plugin, so neither the decision nor the rule it names can have been
rewritten or erased, and a plugin that answered without calling `next`
changes nothing: the rules are evaluated in this run. The two runs differ
- by the user tier alone, so a deny here that names its rule is a deny rule
- the user tier loosened, and it is returned in place of the chain's answer.
-- Any deny rule counts, whatever settings file it came from: a verdict
- carries the rule as written, never where it was read from. A deny that
- names no rule (a settings hook's, a tool's own check) is not held.
+ by the user tier alone, so where they differ and the chain's answer is not
+ the stricter, the user tier rewrote it. A deny is returned in place of the
+ chain's answer whatever decided it; an ask, when it names what decided it:
+ a settings rule (`rule`), a classic hook (`hook`) or an organization's ask
+ cap on the tool (`ceiling`). It is returned whole,
+ so the reason this event answers, which a person reads in the prompt and the
+ engine writes into a refusal, is the engine's, and the rule or hook is still
+ named. (The refusal then enters the conversation as a tool result, a row a
+ person's plugin may still reword at `session.append`.) A stricter answer of
+ theirs (a deny over an ask) stands.
+- Any rule and any classic hook counts, whoever configured it: a verdict
+ carries the rule as written and the hook's event, never where either was
+ read from. A deny holds unnamed because it can stand in front of a rule's or
+ a hook's ask: lifted, the call would run with nobody asked. An ask that names
+ neither (the mode's own, a check of the engine's own) is not held.
- An organization's plugin (prepend or append) or a built-in that allows
over a deny rule takes part in both runs, so its answer stands (a prepended
one that loosens is what brings the second run about, so its hooks run
- twice on such a call). An ask
- that a person's plugin turns into an allow, with no deny rule behind it,
+ twice on such a call). The mode's own ask
+ that a person's plugin turns into an allow, with no rule or hook behind it,
stands: that is what such a plugin is for.
- `tool.check` pins the question (`tool`, `input`, `tool_use_id`), so no hook
can have the rules evaluated on one command and another run; a rewrite
belongs to `tool.call`, which runs before any of this.
-- The person is told once for each name in a session, in the transcript
- and the debug log: `<plugin> tried to lift a deny rule in your settings
- from a <tool> call (<rule>); the deny rule holds over the plugins you
- install (allowModsToOverrideDenyRules)`. Plugins the engine ran as one
+- The person is told once for each name and kind in a session, in the
+ transcript and the debug log: `<plugin> tried to lift a deny rule in your
+ settings from a <tool> call (<rule>); the deny rule holds over the plugins
+ you install (allowModsToOverrideDenyRules)`, or `tried to reword` where
+ the decision was kept and its words or its rule were not. The kinds are `a deny rule`,
+ `an ask rule`, `a <event> hook's ask` and `a refusal` (a deny that names no
+ rule); the last two carry neither `in your settings` nor a rule. Plugins the
+ engine ran as one
batch are named together, as it names them (`audit+easy`). A plain `-p`
- run has it in the debug log alone; the call is still denied with the
- rule's own message.
+ run has it in the debug log alone; the call is still denied, or asked
+ about, with its own message. The line goes past the user tier (the `ui.log`
+ row): a hook of theirs that heard it would run inside this plugin's own
+ `tool.check` hook, and the engine leaves a hook out of whatever is raised
+ from inside it.
+- What this does not reach: a held ask is still an ask, so whatever answers
+ asks for the person answers it, a classic `PermissionRequest` hook of
+ theirs included (`allowManagedHooksOnly` is the control for those). Nor an
+ ask that names neither a rule nor a hook though the engine's own check
+ raised it (the read block's ask on a shell command, a dangerous removal's):
+ the verdict does not tell it from the mode's own, so a person's plugin may
+ still answer it.
- If the hook itself fails, its `.catch` answers from the one run it can
- read: a deny stands; a verdict no plugin of the person's loosened stands;
- one they loosened, or a run that rejected, is refused, since the deny
- rules were never consulted.
+ read: a verdict no plugin of the person's rewrote stands, one they
+ tightened included; one they rewrote, or a run that rejected, is refused
+ in this plugin's own words, since the rules and hooks were never consulted.
An organization that wants the plugins its people install to override deny
-rules says so in managed settings, under this plugin's own options:
+rules, and all else that holds with them, says so in managed settings, under
+this plugin's own options:
```json
{
@@ -173,16 +210,61 @@ rules says so in managed settings, under this plugin's own options:
Only the managed source is read (`$.settings.read({ source: "policy" })`),
so the same key in a person's, a project's or a local settings file, or in
`--settings`, is never consulted; only the literal `true` counts, and a
-policy that cannot be read leaves deny rules holding.
+policy that cannot be read leaves them all holding. So does a policy no
+administrator composed: where the only policy is a document the person can
+write themselves (the Windows `HKCU` hive), or a remote policy the server
+has not yet confirmed this session, the option is not taken from it.
+That policy still holds what it holds; it grants nothing.
+
+## Pinned variables
+
+`$.env.set` writes the session's own environment. A variable managed
+settings set in `env` is the organization's to decide, so this plugin
+refuses a person's plugin that sets or unsets one (the `env.set` row). It
+refuses the same of the launcher's variable where policy names a launcher,
+and, on every build and whatever managed settings hold, of the nine
+variables that move where policy and sign-in are read from: a write of one
+would point a later load or launch at another policy. An
+organization's own plugin's reads, writes and log lines continue past the
+user tier's hooks (the `env.get`, `env.set` and `ui.log` rows).
+
+- At a load, from the first admission until the set serves, an op a plugin
+ makes (one it left running between the load's steps too) is raised through
+ the plugins admitted so far, this one first: a pinned variable is
+ refused to a person's `plugin.register` hook then as at any later time.
+- What this does not reach: a variable that managed `env` does not set and
+ that is not among those names is a person's plugin's to write, and every
+ child the engine starts, a managed
+ hook's command among them, starts from the environment as written. A
+ person already decides the environment Claude Code starts in (`PATH`,
+ `LD_PRELOAD`, `CLAUDE_CODE_SHELL_PREFIX` are theirs to set before launch,
+ and in their own settings files), so a plugin of theirs that sets one
+ gains nothing they lack. The same holds for the proxy and certificate,
+ credential, provider and home variables (`HTTPS_PROXY`,
+ `NODE_EXTRA_CA_CERTS`, `ANTHROPIC_API_KEY`, `HOME` and their like): they are
+ not pinned, because a person sets the same ones in their own settings and
+ shell, so a pin on `env.set` would not close that road. An organization pins the variables its hooks rely
+ on by setting them in managed `env`. An
+ organization's plugin's `$.env.get` is answered past the user tier's hooks,
+ with the environment as written.
## Where it is seated
The CLI seats it first in the prepend tier wherever hooks modules load on a
-machine with managed settings or for a Team or Enterprise organization,
+machine with managed settings or a managed-mcp.json, or for a Team or
+Enterprise organization,
unless managed settings define `prependPlugins`: then that list is the
whole prepend tier, and the organization names `sec-default@builtin` in it
at the position it wants, e.g. `"prependPlugins": ["acme-guard@acme-tools",
-"sec-default@builtin"]`, or leaves it out. It is a plugin folder like any
+"sec-default@builtin"]`, or leaves it out. Once seated by the machine's
+managed settings or by the plan, it stays seated until the session ends: a
+plan that reads differently at a later reload (a token variable a plugin
+set, an `apiKeyHelper` that appeared in a person's settings, another
+sign-in) does not unseat it. How a person signs in before a launch is
+theirs, so a seat that rests on the plan alone follows the sign-in at the
+next launch; managed settings on the machine are what hold it there. The
+organization's own `prependPlugins` list still decides at every reload. It
+is a plugin folder like any
other, but its one move that matters, `next.to`, is refused outside a
managed tier, so loading it with `--plugin-dir` seats a plugin that can
only pass.
diff --git a/mods/sec-default/hooks/held-verdict/caught-answer.ts b/mods/sec-default/hooks/held-verdict/caught-answer.ts
index 0ece9424..021f4208 100644
--- a/mods/sec-default/hooks/held-verdict/caught-answer.ts
+++ b/mods/sec-default/hooks/held-verdict/caught-answer.ts
@@ -6,8 +6,8 @@ import Verdicts from './verdicts'
* What the `tool.check` hook's failure handler answers from the one run it
* can read, the failed hook's last: that run's verdict, or a refusal.
*
- * A deny stands, and so does a verdict no link that may hold a person's
- * plugin loosened. A loosened one, or none at all, met no deny rule.
+ * A verdict stands that no link that may hold a person's plugin rewrote
+ * without tightening. A rewritten one, or none at all, met no rule or hook.
*
* @param last what that run settled on; undefined when it rejected
* @param trace that run's `next.trace`
@@ -18,8 +18,7 @@ export function caughtAnswer(
trace: readonly TraceEntry<'tool.check'>[],
) {
const isVouched =
- last !== undefined &&
- (last.decision === 'deny' || Verdicts.loosenedByUsers(trace).length === 0)
+ last !== undefined && Verdicts.rewrittenByUsers(trace).length === 0
return isVouched ? last : Verdicts.UNCHECKED_DENY
}
diff --git a/mods/sec-default/hooks/held-verdict/held-kind.ts b/mods/sec-default/hooks/held-verdict/held-kind.ts
new file mode 100644
index 00000000..40eefad3
--- /dev/null
+++ b/mods/sec-default/hooks/held-verdict/held-kind.ts
@@ -0,0 +1,26 @@
+import type { EventResult } from 'claude-code'
+
+/**
+ * What kind of thing held over a person's plugin, as the notice calls it:
+ * `deny rule`, `ask rule`, `<event> hook's ask`, `ask cap`, or `refusal`.
+ *
+ * A deny that names no rule is a refusal even when it names a hook: the hook
+ * may only have asked, and something else refused. An ask that names neither
+ * holds by the ceiling an organization set on the tool.
+ *
+ * @param held the verdict that holds
+ * @returns the kind
+ */
+export function heldKind(held: EventResult<'tool.check'>): string {
+ const isRuled = held.rule !== undefined
+ const isRefused = held.decision === 'deny'
+ const isHooked = held.hook !== undefined
+
+ return isRuled
+ ? `${held.decision} rule`
+ : isRefused
+ ? 'refusal'
+ : isHooked
+ ? `${held.hook} hook's ask`
+ : 'ask cap'
+}
diff --git a/mods/sec-default/hooks/held-verdict/held-notice.ts b/mods/sec-default/hooks/held-verdict/held-notice.ts
index deb65f4e..14af2885 100644
--- a/mods/sec-default/hooks/held-verdict/held-notice.ts
+++ b/mods/sec-default/hooks/held-verdict/held-notice.ts
@@ -1,15 +1,34 @@
+import type { EventResult } from 'claude-code'
+
+import { heldKind } from './held-kind.js'
+
/**
- * What a person reads, once for each plugin in a session, when a plugin they
- * installed answered allow or ask over a deny rule in their settings.
+ * What a person reads, once for each plugin and kind in a session, when a
+ * plugin they installed rewrote a verdict that holds over it.
*
* It names the option an administrator sets to let such plugins override.
*
* @param plugin the plugin's name, or its batch's, as the trace names it
* @param tool the tool the call named
- * @param rule the deny rule that decided, as written
+ * @param held the verdict that holds, naming the rule behind it if one is
+ * @param attempt what the plugin did: answered looser, or the same reworded
* @returns the line
*/
-export const heldNotice = (plugin: string, tool: string, rule: string) =>
- `${plugin} tried to lift a deny rule in your settings from a ${tool} ` +
- `call (${rule}); the deny rule holds over the plugins you install ` +
- '(allowModsToOverrideDenyRules)'
+export function heldNotice(
+ plugin: string,
+ tool: string,
+ held: EventResult<'tool.check'>,
+ attempt: 'lift' | 'reword',
+): string {
+ const kind = heldKind(held)
+ const article = kind.startsWith('a') ? 'an' : 'a'
+ const changed =
+ held.rule === undefined
+ ? `${article} ${kind} from a ${tool} call`
+ : `${article} ${kind} in your settings from a ${tool} call (${held.rule})`
+
+ return (
+ `${plugin} tried to ${attempt} ${changed}; the ${kind} holds over the ` +
+ 'plugins you install (allowModsToOverrideDenyRules)'
+ )
+}
diff --git a/mods/sec-default/hooks/held-verdict/index.ts b/mods/sec-default/hooks/held-verdict/index.ts
index b6587e24..5727e8f7 100644
--- a/mods/sec-default/hooks/held-verdict/index.ts
+++ b/mods/sec-default/hooks/held-verdict/index.ts
@@ -1,4 +1,5 @@
export * from './caught-answer.js'
+export * from './held-kind.js'
export * from './held-notice.js'
export * from './verdicts'
diff --git a/mods/sec-default/hooks/held-verdict/verdicts/holds-over.ts b/mods/sec-default/hooks/held-verdict/verdicts/holds-over.ts
new file mode 100644
index 00000000..889159bf
--- /dev/null
+++ b/mods/sec-default/hooks/held-verdict/verdicts/holds-over.ts
@@ -0,0 +1,28 @@
+import type { EventResult } from 'claude-code'
+
+import { isSameVerdict } from './is-same-verdict.js'
+import Ranking from './ranking'
+
+/**
+ * Whether the verdict reached past the user tier holds whole over the
+ * chain's answer: a deny, or an ask a rule, a hook or a ceiling stands behind.
+ *
+ * It holds over a more permissive answer and over the same decision reworded
+ * or stripped of its rule or hook; a stricter answer stands. Any rule or
+ * classic hook counts, whoever configured it, and so does the ceiling an
+ * organization set on the tool. The mode's own ask, with none, never holds.
+ *
+ * @param held what the run past the user tier settled on
+ * @param answer what the whole chain settled on
+ * @returns true when the held verdict is the one to return, as it is
+ */
+export const holdsOver = (
+ held: EventResult<'tool.check'>,
+ answer: EventResult<'tool.check'>,
+) =>
+ !Ranking.isLooser(held, answer) &&
+ !isSameVerdict(held, answer) &&
+ (held.decision === 'deny' ||
+ held.rule !== undefined ||
+ held.hook !== undefined ||
+ held.ceiling !== undefined)
diff --git a/mods/sec-default/hooks/held-verdict/verdicts/index.ts b/mods/sec-default/hooks/held-verdict/verdicts/index.ts
index 648e4d68..75775793 100644
--- a/mods/sec-default/hooks/held-verdict/verdicts/index.ts
+++ b/mods/sec-default/hooks/held-verdict/verdicts/index.ts
@@ -1,7 +1,7 @@
-export * from './is-rule-deny.js'
-export * from './loosened-by-users.js'
+export * from './holds-over.js'
+export * from './is-same-verdict.js'
export * from './ranking'
-export * from './types'
+export * from './rewritten-by-users.js'
export * from './unchecked-deny.js'
export * as default from '.'
diff --git a/mods/sec-default/hooks/held-verdict/verdicts/is-rule-deny.ts b/mods/sec-default/hooks/held-verdict/verdicts/is-rule-deny.ts
deleted file mode 100644
index 6e99a468..00000000
--- a/mods/sec-default/hooks/held-verdict/verdicts/is-rule-deny.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-import type { EventResult } from 'claude-code'
-
-import type { RuleDeny } from './types'
-
-/**
- * Whether a `tool.check` verdict is a deny that a settings rule decided: the
- * one verdict the plugins a person installs may not loosen.
- *
- * Any deny rule counts, whatever settings file it came from: a verdict
- * carries the rule as written and never where it was read from.
- *
- * @param verdict what a run of the chain settled on
- * @returns true for a deny that names the rule behind it
- */
-export const isRuleDeny = (
- verdict: EventResult<'tool.check'>,
-): verdict is RuleDeny =>
- verdict.decision === 'deny' && verdict.rule !== undefined
diff --git a/mods/sec-default/hooks/held-verdict/verdicts/is-same-verdict.ts b/mods/sec-default/hooks/held-verdict/verdicts/is-same-verdict.ts
new file mode 100644
index 00000000..508f3374
--- /dev/null
+++ b/mods/sec-default/hooks/held-verdict/verdicts/is-same-verdict.ts
@@ -0,0 +1,24 @@
+import type { EventResult } from 'claude-code'
+
+/**
+ * Whether two `tool.check` verdicts say the same in every field: decision,
+ * reason, and the rule, hook or ceiling either names.
+ *
+ * @param one a verdict
+ * @param other another, or undefined when nothing settled
+ * @returns true when no field differs
+ */
+export const isSameVerdict = (
+ one: EventResult<'tool.check'>,
+ other: EventResult<'tool.check'> | undefined,
+) =>
+ other !== undefined &&
+ [one, other]
+ .map(verdict =>
+ JSON.stringify(
+ Object.entries(verdict)
+ .filter(([, value]) => value !== undefined)
+ .toSorted(([left], [right]) => (left < right ? -1 : 1)),
+ ),
+ )
+ .every((line, _, lines) => line === lines[0])
diff --git a/mods/sec-default/hooks/held-verdict/verdicts/loosened-by-users.ts b/mods/sec-default/hooks/held-verdict/verdicts/loosened-by-users.ts
deleted file mode 100644
index 5b491e8e..00000000
--- a/mods/sec-default/hooks/held-verdict/verdicts/loosened-by-users.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import type { TraceEntry } from 'claude-code'
-
-import Ranking from './ranking'
-
-/**
- * The links of one run of `tool.check` that may hold a plugin a person
- * installed and that answered more permissively than they were handed.
- *
- * Read off `next.trace`, whose `tier` the engine pins. A batch is named as
- * the engine names it, its members joined; whether a person's plugin did
- * the loosening is settled by the run past the user tier, never here.
- *
- * @param trace what settled beneath the hook on its latest `next` call
- * @returns their names, nearest the caller first; none when none loosened
- */
-export const loosenedByUsers = (
- trace: readonly TraceEntry<'tool.check'>[],
-): readonly string[] =>
- trace
- .filter(
- (link, at) =>
- Ranking.TIERS_HOLDING_USERS.includes(link.tier) &&
- Ranking.isLooser(link.returned, Ranking.handedTo(trace, at)),
- )
- .map(link => link.plugin)
diff --git a/mods/sec-default/hooks/held-verdict/verdicts/rewritten-by-users.ts b/mods/sec-default/hooks/held-verdict/verdicts/rewritten-by-users.ts
new file mode 100644
index 00000000..81223a29
--- /dev/null
+++ b/mods/sec-default/hooks/held-verdict/verdicts/rewritten-by-users.ts
@@ -0,0 +1,31 @@
+import type { TraceEntry } from 'claude-code'
+
+import { isSameVerdict } from './is-same-verdict.js'
+import Ranking from './ranking'
+
+/**
+ * The links of one run of `tool.check` that may hold a plugin a person
+ * installed and that rewrote the verdict handed to them without tightening.
+ *
+ * A more permissive decision counts, and so does the same decision under
+ * another reason, rule or hook. Read off `next.trace`, whose `tier` the
+ * engine pins; a batch is named as the engine names it, its members joined.
+ *
+ * @param trace what settled beneath the hook on its latest `next` call
+ * @returns their names, nearest the caller first; none when none rewrote
+ */
+export const rewrittenByUsers = (
+ trace: readonly TraceEntry<'tool.check'>[],
+): readonly string[] =>
+ trace
+ .filter((link, at) => {
+ const handed = Ranking.handedTo(trace, at)
+
+ return (
+ Ranking.TIERS_HOLDING_USERS.includes(link.tier) &&
+ link.returned !== undefined &&
+ !Ranking.isLooser(handed, link.returned) &&
+ !isSameVerdict(link.returned, handed)
+ )
+ })
+ .map(link => link.plugin)
diff --git a/mods/sec-default/hooks/held-verdict/verdicts/types/index.ts b/mods/sec-default/hooks/held-verdict/verdicts/types/index.ts
deleted file mode 100644
index 5a372464..00000000
--- a/mods/sec-default/hooks/held-verdict/verdicts/types/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-export type * from './rule-deny.js'
-
-export * as default from '.'
diff --git a/mods/sec-default/hooks/held-verdict/verdicts/types/rule-deny.ts b/mods/sec-default/hooks/held-verdict/verdicts/types/rule-deny.ts
deleted file mode 100644
index 42bbd44f..00000000
--- a/mods/sec-default/hooks/held-verdict/verdicts/types/rule-deny.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import type { EventResult } from 'claude-code'
-
-/**
- * A `tool.check` deny that names the settings rule behind it.
- */
-export type RuleDeny = EventResult<'tool.check'> & {
- readonly decision: 'deny'
- readonly rule: string
-}
diff --git a/mods/sec-default/hooks/held-verdict/verdicts/unchecked-deny.ts b/mods/sec-default/hooks/held-verdict/verdicts/unchecked-deny.ts
index 3a5a30f9..d7ae399b 100644
--- a/mods/sec-default/hooks/held-verdict/verdicts/unchecked-deny.ts
+++ b/mods/sec-default/hooks/held-verdict/verdicts/unchecked-deny.ts
@@ -1,12 +1,12 @@
import type { EventResult } from 'claude-code'
/**
- * What the failure handler answers when a verdict was loosened, or never
- * reached, and no deny rule check vouches for it: absent counts as deny.
+ * What the failure handler answers when a verdict was rewritten, or never
+ * reached, and no check of the rules and hooks vouches for it: a deny.
*/
export const UNCHECKED_DENY: EventResult<'tool.check'> = Object.freeze({
decision: 'deny',
reason:
- 'the deny rules in your settings could not be checked for this call, ' +
- 'so it is refused',
+ 'the rules and hooks in your settings could not be checked for this ' +
+ 'call, so it is refused',
})
diff --git a/mods/sec-default/hooks/hooks.json b/mods/sec-default/hooks/hooks.json
index 4a70fc2d..a65403e1 100644
--- a/mods/sec-default/hooks/hooks.json
+++ b/mods/sec-default/hooks/hooks.json
@@ -1,4 +1,4 @@
{
- "description": "Security default: from the outermost seat, continues past the user tier on the organization's classic hooks, prompt content, settings and subjects, refuses a user-tier tool.register under an MCP allowlist, restores the organization's tools in tool.list, holds a settings deny rule over a user-tier allow or ask on tool.check, and refuses a user-tier hooks module at plugin.register while managed settings set its allowManagedModsOnly option",
+ "description": "Security default: from the outermost seat, continues past the user tier on the organization's classic hooks, prompt content, settings and subjects, at session.append for the rows the engine injects, a compaction's rows, a skill the Skill tool hands over and an organization plugin's notes, and at session.compact, refuses a user-tier tool.register under an MCP allowlist or under a name that reads as one of the organization's servers or plugins, restores the organization's tools in tool.list, holds a deny, and an ask a settings rule, a classic hook or an organization's ask cap decided, whole over what the user tier makes of it on tool.check, continues past the user tier's hooks for an organization plugin's log lines and its reads and writes of the environment, refuses a user-tier write of a variable managed env sets, of the launcher's variable where policy names a launcher and of the variables that move where policy and sign-in are read from, and refuses a user-tier hooks module at plugin.register while managed settings set its allowManagedModsOnly option",
"modules": ["./register.ts"]
}
diff --git a/mods/sec-default/hooks/index.ts b/mods/sec-default/hooks/index.ts
index bd91ec39..c5fffdbc 100644
--- a/mods/sec-default/hooks/index.ts
+++ b/mods/sec-default/hooks/index.ts
@@ -2,8 +2,10 @@ export * from './admission-failure'
export * from './held-verdict'
export * from './managed-mods-only-refusal'
export * from './past-users'
+export * from './pinned-variable-refusal'
export * from './policy'
export * from './register.js'
+export * from './skill-row'
export * from './tool-register-refusal'
export * as default from '.'
diff --git a/mods/sec-default/hooks/pinned-variable-refusal/index.ts b/mods/sec-default/hooks/pinned-variable-refusal/index.ts
new file mode 100644
index 00000000..e902a124
--- /dev/null
+++ b/mods/sec-default/hooks/pinned-variable-refusal/index.ts
@@ -0,0 +1,3 @@
+export * from './pinned-variable-refusal.js'
+
+export * as default from '.'
diff --git a/mods/sec-default/hooks/pinned-variable-refusal/pinned-variable-refusal.ts b/mods/sec-default/hooks/pinned-variable-refusal/pinned-variable-refusal.ts
new file mode 100644
index 00000000..9ad794b8
--- /dev/null
+++ b/mods/sec-default/hooks/pinned-variable-refusal/pinned-variable-refusal.ts
@@ -0,0 +1,12 @@
+/**
+ * Why a plugin a person installed may not set or unset an environment
+ * variable their organization pins: the setting, then the rule.
+ *
+ * Said too when the policy cannot be read and every variable counts as
+ * pinned, so it does not say who set this one.
+ *
+ * @param name the variable, as the plugin named it
+ * @returns the refusal
+ */
+export const pinnedVariableRefusal = (name: string) =>
+ `env (managed): ${name} is not for plugins outside policy to change`
diff --git a/mods/sec-default/hooks/policy/deny-rules-hold.ts b/mods/sec-default/hooks/policy/deny-rules-hold.ts
index 9667a09b..754026e7 100644
--- a/mods/sec-default/hooks/policy/deny-rules-hold.ts
+++ b/mods/sec-default/hooks/policy/deny-rules-hold.ts
@@ -1,16 +1,19 @@
import type { Settings } from 'claude-code'
+import { isPersonWritable } from './is-person-writable.js'
import { ownOption } from './own-option'
/**
* Whether deny rules hold over the plugins a person installs: they do unless
- * managed policy sets `allowModsToOverrideDenyRules` to the literal `true`.
+ * an administrator's policy sets `allowModsToOverrideDenyRules` to `true`.
*
- * A value mistyped (`"true"`, `1`) loosens nothing. Only the policy source
- * is handed in, so a person's settings never reach this.
+ * Ask rules and classic hooks' answers hold or not with them. A value mistyped
+ * (`"true"`, `1`) loosens nothing, and neither does the option in a policy the
+ * person could have written (isPersonWritable).
*
* @param policy the managed settings, as `$.settings.read` answers them
* @returns false only when the organization let a person's plugins override
*/
export const denyRulesHold = (policy: Settings) =>
+ isPersonWritable(policy) ||
ownOption(policy, 'allowModsToOverrideDenyRules') !== true
diff --git a/mods/sec-default/hooks/policy/index.ts b/mods/sec-default/hooks/policy/index.ts
index 8e6f5a8c..6708088d 100644
--- a/mods/sec-default/hooks/policy/index.ts
+++ b/mods/sec-default/hooks/policy/index.ts
@@ -3,9 +3,15 @@ export * from './decided-by-policy.js'
export * from './deny-rules-hold.js'
export * from './has-mcp-allowlist.js'
export * from './is-managed-mods-only.js'
+export * from './is-person-writable.js'
+export * from './is-pinned-variable.js'
export * from './managed-tools-restored'
+export * from './names-org-tool.js'
export * from './own-option'
+export * from './pinned-names.js'
export * from './policy-memo-ms.js'
+export * from './policy-source-variables.js'
+export * from './process-wrapper-variable.js'
export * from './source.js'
export * as default from '.'
diff --git a/mods/sec-default/hooks/policy/is-person-writable.ts b/mods/sec-default/hooks/policy/is-person-writable.ts
new file mode 100644
index 00000000..6dd3b762
--- /dev/null
+++ b/mods/sec-default/hooks/policy/is-person-writable.ts
@@ -0,0 +1,13 @@
+import type { Settings } from 'claude-code'
+
+/**
+ * Whether the policy read is one the person could have written: the host
+ * marks it where no administrator's document composes it.
+ *
+ * Such a policy may hold; no grant is taken from it.
+ *
+ * @param policy the managed settings, as `$.settings.read` answers them
+ * @returns true for a policy so marked
+ */
+export const isPersonWritable = (policy: Settings): boolean =>
+ policy.personWritablePolicy === true
diff --git a/mods/sec-default/hooks/policy/is-pinned-variable.ts b/mods/sec-default/hooks/policy/is-pinned-variable.ts
new file mode 100644
index 00000000..e0040b43
--- /dev/null
+++ b/mods/sec-default/hooks/policy/is-pinned-variable.ts
@@ -0,0 +1,16 @@
+import type { Settings } from 'claude-code'
+
+import { pinnedNames } from './pinned-names.js'
+
+/**
+ * Whether managed policy pins an environment variable: it sets the name
+ * (pinnedNames), in any case (some systems read `Path` and `PATH` as one).
+ *
+ * @param policy the managed settings, as `$.settings.read` answers them
+ * @param name the variable a plugin would set or unset
+ * @returns true when the organization set it
+ */
+export const isPinnedVariable = (policy: Settings, name: string): boolean =>
+ pinnedNames(policy).some(
+ pinned => pinned.toUpperCase() === name.toUpperCase(),
+ )
diff --git a/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/index.ts b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/index.ts
index 92b1cef6..5d529869 100644
--- a/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/index.ts
+++ b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/index.ts
@@ -1,4 +1,9 @@
export * from './is-org-tool.js'
+export * from './is-server-file-unreadable'
+export * from './org-names'
+export * from './org-plugin-names'
export * from './org-server-names'
+export * from './spellings-of'
+export * from './tool-prefix-of'
export * as default from '.'
diff --git a/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/is-org-tool.ts b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/is-org-tool.ts
index 65e46726..60442580 100644
--- a/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/is-org-tool.ts
+++ b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/is-org-tool.ts
@@ -1,14 +1,33 @@
import type { Settings } from 'claude-code'
+import { isServerFileUnreadable } from './is-server-file-unreadable'
+import { orgPluginNames } from './org-plugin-names'
import { orgServerNames } from './org-server-names'
+import { spellingsOf } from './spellings-of'
+import { toolPrefixOf } from './tool-prefix-of'
+import { foldedName } from './tool-prefix-of/folded-name'
/**
- * Whether a tool is one of a managed MCP server's: `mcp__<server>__...` for
- * a server the policy's allowlist names.
+ * Whether a tool is the organization's: `mcp__<name>__...` for a server its
+ * policy names or delivers, and a tool under a seated plugin's name or
+ * scope (`plugin_<name>`, which holds its own manifest's servers).
+ *
+ * A server is told by its name whole, as the engine spells it (spellingsOf),
+ * never by a fold: another server whose name only begins like it is not it.
+ * A seated plugin is told fold to fold, as the registration check tells it
+ * (foldedName), since policy may list its id in another letter case. Where
+ * the server file cannot be read, every `mcp__` tool counts.
*
* @param policy the managed settings, as `$.settings.read` answers them
- * @param tool the tool's name as the model calls it
- * @returns true for a managed server's tool
+ * @param tool the tool's name, as the model sees it
+ * @returns true when the tool is the organization's
*/
-export const isOrgTool = (policy: Settings, tool: string) =>
- orgServerNames(policy).some(server => tool.startsWith(`mcp__${server}__`))
+export const isOrgTool = (policy: Settings, tool: string): boolean =>
+ (isServerFileUnreadable(policy) && tool.startsWith('mcp__')) ||
+ orgServerNames(policy)
+ .flatMap(spellingsOf)
+ .some(spelt => tool.startsWith(`mcp__${spelt}__`)) ||
+ orgPluginNames(policy)
+ .filter(name => foldedName(name) !== '')
+ .flatMap(name => [name, `plugin_${name}`])
+ .some(owner => `${foldedName(tool)}_`.startsWith(toolPrefixOf(owner)))
diff --git a/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/is-server-file-unreadable/index.ts b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/is-server-file-unreadable/index.ts
new file mode 100644
index 00000000..88420f37
--- /dev/null
+++ b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/is-server-file-unreadable/index.ts
@@ -0,0 +1,3 @@
+export * from './is-server-file-unreadable.js'
+
+export * as default from '.'
diff --git a/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/is-server-file-unreadable/is-server-file-unreadable.ts b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/is-server-file-unreadable/is-server-file-unreadable.ts
new file mode 100644
index 00000000..b55cd42c
--- /dev/null
+++ b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/is-server-file-unreadable/is-server-file-unreadable.ts
@@ -0,0 +1,11 @@
+import type { Settings } from 'claude-code'
+
+/**
+ * Whether the policy read marks the organization's server file
+ * (managed-mcp.json) as present and unreadable: its servers cannot be named.
+ *
+ * @param policy the managed settings, as `$.settings.read` answers them
+ * @returns true when the mark is set
+ */
+export const isServerFileUnreadable = (policy: Settings): boolean =>
+ policy.managedMcpServersUnreadable === true
diff --git a/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/org-names/index.ts b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/org-names/index.ts
new file mode 100644
index 00000000..dc0ee592
--- /dev/null
+++ b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/org-names/index.ts
@@ -0,0 +1,3 @@
+export * from './org-names.js'
+
+export * as default from '.'
diff --git a/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/org-names/org-names.ts b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/org-names/org-names.ts
new file mode 100644
index 00000000..669421d4
--- /dev/null
+++ b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/org-names/org-names.ts
@@ -0,0 +1,22 @@
+import type { Settings } from 'claude-code'
+
+import { orgPluginNames } from '../org-plugin-names'
+import { orgServerNames } from '../org-server-names'
+
+/**
+ * Every name whose tools are the organization's: the MCP servers its policy
+ * names or delivers, and the plugins it seats itself.
+ *
+ * Each seated plugin counts twice: by its name, and by its scope
+ * (`plugin_<name>`), under which the engine spells the MCP servers the
+ * plugin's own manifest declares.
+ *
+ * @param policy the managed settings, as `$.settings.read` answers them
+ * @param own the engine-recorded id of the plugin that asks for itself,
+ * whose own name is left out (orgPluginNames)
+ * @returns the names, servers first
+ */
+export const orgNames = (policy: Settings, own?: string): string[] => [
+ ...orgServerNames(policy),
+ ...orgPluginNames(policy, own).flatMap(name => [name, `plugin_${name}`]),
+]
diff --git a/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/org-plugin-names/folded-id.ts b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/org-plugin-names/folded-id.ts
new file mode 100644
index 00000000..e293beb8
--- /dev/null
+++ b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/org-plugin-names/folded-id.ts
@@ -0,0 +1,11 @@
+/**
+ * A plugin's id as the engine compares ids: NFC, then lower case.
+ *
+ * A mod imports nothing from the engine, so its rule is copied here; a test
+ * in the engine's tree holds the copy equal to it.
+ *
+ * @param id an id as written, `<name>@<source>`
+ * @returns the fold
+ */
+export const foldedId = (id: string): string =>
+ id.normalize('NFC').toLowerCase()
diff --git a/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/org-plugin-names/forms-of.ts b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/org-plugin-names/forms-of.ts
new file mode 100644
index 00000000..46ab8e11
--- /dev/null
+++ b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/org-plugin-names/forms-of.ts
@@ -0,0 +1,16 @@
+/**
+ * A plugin's name in each form the engine may spell its tools from: composed
+ * and decomposed, one entry where the two are the same.
+ *
+ * The engine takes a listed id for a plugin by the composed form of both, and
+ * spells the plugin's tools from its manifest's name as written.
+ *
+ * @param name a plugin's name, as policy lists it
+ * @returns the name composed, and decomposed where that differs
+ */
+export const formsOf = (name: string): string[] => {
+ const composed = name.normalize('NFC')
+ const decomposed = name.normalize('NFD')
+
+ return composed === decomposed ? [composed] : [composed, decomposed]
+}
diff --git a/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/org-plugin-names/index.ts b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/org-plugin-names/index.ts
new file mode 100644
index 00000000..62461c36
--- /dev/null
+++ b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/org-plugin-names/index.ts
@@ -0,0 +1,7 @@
+export * from './folded-id.js'
+export * from './forms-of.js'
+export * from './is-enabled-entry.js'
+export * from './name-of-id.js'
+export * from './org-plugin-names.js'
+
+export * as default from '.'
diff --git a/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/org-plugin-names/is-enabled-entry.ts b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/org-plugin-names/is-enabled-entry.ts
new file mode 100644
index 00000000..2f43f703
--- /dev/null
+++ b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/org-plugin-names/is-enabled-entry.ts
@@ -0,0 +1,9 @@
+/**
+ * Whether an `enabledPlugins` entry turns its plugin on: `true`, or a list
+ * of version constraints, as the engine reads one.
+ *
+ * @param value the entry's value
+ * @returns true when the entry turns the plugin on
+ */
+export const isEnabledEntry = (value: unknown): boolean =>
+ value === true || Array.isArray(value)
diff --git a/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/org-plugin-names/name-of-id.ts b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/org-plugin-names/name-of-id.ts
new file mode 100644
index 00000000..25ad0e01
--- /dev/null
+++ b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/org-plugin-names/name-of-id.ts
@@ -0,0 +1,12 @@
+/**
+ * The name half of a plugin id: everything before its LAST at-sign, as the
+ * engine parts ids, so a scoped id (`@scope/name@npm`) keeps its scope.
+ *
+ * @param id a plugin id as policy lists it (`<name>@<marketplace>`)
+ * @returns the name; the whole id where no at-sign follows a name
+ */
+export function nameOfId(id: string): string {
+ const at = id.lastIndexOf('@')
+
+ return at > 0 ? id.slice(0, at) : id
+}
diff --git a/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/org-plugin-names/org-plugin-names.ts b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/org-plugin-names/org-plugin-names.ts
new file mode 100644
index 00000000..9bc044ed
--- /dev/null
+++ b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/org-plugin-names/org-plugin-names.ts
@@ -0,0 +1,44 @@
+import type { Settings } from 'claude-code'
+
+import { foldedId } from './folded-id.js'
+import { formsOf } from './forms-of.js'
+import { isEnabledEntry } from './is-enabled-entry.js'
+import { nameOfId } from './name-of-id.js'
+
+/**
+ * The names of the plugins the organization itself seats, as their tools
+ * are prefixed: an id's name half (nameOfId), in each form the engine may
+ * spell it from (formsOf).
+ *
+ * Those are the ids of prependPlugins and appendPlugins, and every id
+ * managed enabledPlugins turns on (isEnabledEntry) but a built-in's, which
+ * the engine names.
+ *
+ * The asking plugin's own id is left out, in every list, exactly when it is
+ * one managed enabledPlugins turns on: its name is then its own to use.
+ *
+ * @param policy the managed settings, as `$.settings.read` answers them
+ * @param own the id the engine recorded for the plugin that asks for itself
+ * (`<name>@<source>`), compared as the engine compares ids
+ * @returns each such plugin's name, in each form; none where no key names
+ * one
+ */
+export function orgPluginNames(policy: Settings, own?: string): string[] {
+ const enabled = Object.entries(policy.enabledPlugins ?? {}).flatMap(
+ ([id, value]) =>
+ isEnabledEntry(value) && !id.endsWith('@builtin') ? [id] : [],
+ )
+ const isOwn = (id: string) =>
+ typeof own === 'string' && foldedId(id) === foldedId(own)
+ const isExempt = enabled.some(isOwn)
+
+ return [policy.prependPlugins, policy.appendPlugins, enabled].flatMap(
+ (listed: unknown) =>
+ (Array.isArray(listed) ? listed : []).flatMap((id: unknown) => {
+ const name = typeof id === 'string' ? nameOfId(id) : ''
+ const isLeftOut = typeof id === 'string' && isExempt && isOwn(id)
+
+ return name !== '' && !isLeftOut ? formsOf(name) : []
+ }),
+ )
+}
diff --git a/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/spellings-of/index.ts b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/spellings-of/index.ts
new file mode 100644
index 00000000..6d60a04e
--- /dev/null
+++ b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/spellings-of/index.ts
@@ -0,0 +1,3 @@
+export * from './spellings-of.js'
+
+export * as default from '.'
diff --git a/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/spellings-of/spellings-of.ts b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/spellings-of/spellings-of.ts
new file mode 100644
index 00000000..9990cf0f
--- /dev/null
+++ b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/spellings-of/spellings-of.ts
@@ -0,0 +1,16 @@
+/**
+ * How the engine spells a server's name inside its tools' names: every
+ * character that is not a letter, digit, `_` or `-` becomes `_`.
+ *
+ * A claude.ai connector's runs of `_` are also joined and trimmed, so both
+ * spellings are answered; one that comes out empty is left out.
+ *
+ * @param server the server's name as the policy spells it
+ * @returns the spellings, without repeats
+ */
+export function spellingsOf(server: string): string[] {
+ const spelt = server.replace(/[^a-zA-Z0-9_-]/g, '_')
+ const joined = spelt.replace(/_+/g, '_').replace(/^_|_$/g, '')
+
+ return [...new Set([spelt, joined])].filter(one => one !== '')
+}
diff --git a/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/tool-prefix-of/folded-name/folded-name.ts b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/tool-prefix-of/folded-name/folded-name.ts
new file mode 100644
index 00000000..2518ddcc
--- /dev/null
+++ b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/tool-prefix-of/folded-name/folded-name.ts
@@ -0,0 +1,17 @@
+/**
+ * A server's or a tool's name as look-alike checks compare it: spelled as
+ * the engine spells a name inside a tool's (every other character a `_`,
+ * no normalization), lower-cased, runs of `-` and `_` one `_`, trimmed.
+ *
+ * `Corp__Tools`, `corp-tools` and `corp.tools` all fold to `corp_tools`: a
+ * model reads them as one name, so one of them may not pass for another.
+ *
+ * @param name the name as written
+ * @returns the fold
+ */
+export const foldedName = (name: string) =>
+ name
+ .replace(/[^a-zA-Z0-9_-]/g, '_')
+ .toLowerCase()
+ .replace(/[-_]+/g, '_')
+ .replace(/^_|_$/g, '')
diff --git a/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/tool-prefix-of/folded-name/index.ts b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/tool-prefix-of/folded-name/index.ts
new file mode 100644
index 00000000..b2f79bb4
--- /dev/null
+++ b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/tool-prefix-of/folded-name/index.ts
@@ -0,0 +1,3 @@
+export * from './folded-name.js'
+
+export * as default from '.'
diff --git a/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/tool-prefix-of/index.ts b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/tool-prefix-of/index.ts
new file mode 100644
index 00000000..c71edd7b
--- /dev/null
+++ b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/tool-prefix-of/index.ts
@@ -0,0 +1,3 @@
+export * from './tool-prefix-of.js'
+
+export * as default from '.'
diff --git a/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/tool-prefix-of/tool-prefix-of.ts b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/tool-prefix-of/tool-prefix-of.ts
new file mode 100644
index 00000000..f58ee487
--- /dev/null
+++ b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/tool-prefix-of/tool-prefix-of.ts
@@ -0,0 +1,13 @@
+import { foldedName } from './folded-name'
+
+/**
+ * What the folded name of every tool under an MCP server, or of a plugin's
+ * own registered tools, begins with: `mcp_<folded name>_`.
+ *
+ * Compared fold to fold (foldedName), never as written: a name in another
+ * case, or with other separators, is the same server to a model.
+ *
+ * @param name a server's name, or a registering plugin's
+ * @returns the folded prefix
+ */
+export const toolPrefixOf = (name: string) => `mcp_${foldedName(name)}_`
diff --git a/mods/sec-default/hooks/policy/names-org-tool.ts b/mods/sec-default/hooks/policy/names-org-tool.ts
new file mode 100644
index 00000000..58c5ab29
--- /dev/null
+++ b/mods/sec-default/hooks/policy/names-org-tool.ts
@@ -0,0 +1,44 @@
+import type { Settings } from 'claude-code'
+
+import { isServerFileUnreadable } from './managed-tools-restored/is-org-tool/is-server-file-unreadable'
+import { orgNames } from './managed-tools-restored/is-org-tool/org-names'
+import { toolPrefixOf } from './managed-tools-restored/is-org-tool/tool-prefix-of'
+import { foldedName } from './managed-tools-restored/is-org-tool/tool-prefix-of/folded-name'
+
+/**
+ * Whether the tool a plugin registers would read as the organization's: it
+ * is called `mcp__<plugin>__<tool>`, compared fold to fold with the prefix
+ * of each server the policy names, each plugin it seats, and each seated
+ * plugin's scope, which holds the servers its own manifest declares.
+ *
+ * So a plugin named as one of them in any case or with other separators, one
+ * whose name and tool together spell a prefix, and one whose tool's own name
+ * folds to nothing all count. A name of the organization's that folds to
+ * nothing cannot be told from any name, and a server file that cannot be
+ * read names nobody: every registration then reads as the organization's.
+ * The plugin whose engine-recorded id managed enabledPlugins turn on keeps
+ * its own name; an unreadable server file holds it all the same.
+ *
+ * @param policy the managed settings, as `$.settings.read` answers them
+ * @param plugin the registering plugin's name
+ * @param tool the tool's own name, as the plugin registers it
+ * @param id the id the engine recorded for the registering plugin
+ * (`<name>@<source>`), where the mod heard its admission
+ * @returns true when the tool would read as the organization's
+ */
+export function namesOrgTool(
+ policy: Settings,
+ plugin: string,
+ tool: string,
+ id?: string,
+): boolean {
+ const registered = `${foldedName(`mcp__${plugin}__${tool}`)}_`
+
+ return (
+ isServerFileUnreadable(policy) ||
+ orgNames(policy, id).some(
+ owner =>
+ foldedName(owner) === '' || registered.startsWith(toolPrefixOf(owner)),
+ )
+ )
+}
diff --git a/mods/sec-default/hooks/policy/pinned-names.ts b/mods/sec-default/hooks/policy/pinned-names.ts
new file mode 100644
index 00000000..b0b65b69
--- /dev/null
+++ b/mods/sec-default/hooks/policy/pinned-names.ts
@@ -0,0 +1,23 @@
+import type { Settings } from 'claude-code'
+
+import { POLICY_SOURCE_VARIABLES } from './policy-source-variables.js'
+import { PROCESS_WRAPPER_VARIABLE } from './process-wrapper-variable.js'
+
+/**
+ * The environment variables managed policy sets: every name of its `env`,
+ * and the launcher's variable where it names one with `processWrapper`.
+ *
+ * Always among them: the variables that say where policy is read from.
+ *
+ * @param policy the managed settings, as `$.settings.read` answers them
+ * @returns the names, as the policy spells them
+ */
+export function pinnedNames(policy: Settings): string[] {
+ const isWrapped = policy.processWrapper !== undefined
+
+ return [
+ ...Object.keys(policy.env ?? {}),
+ ...(isWrapped ? [PROCESS_WRAPPER_VARIABLE] : []),
+ ...POLICY_SOURCE_VARIABLES,
+ ]
+}
diff --git a/mods/sec-default/hooks/policy/policy-source-variables.ts b/mods/sec-default/hooks/policy/policy-source-variables.ts
new file mode 100644
index 00000000..febd5c66
--- /dev/null
+++ b/mods/sec-default/hooks/policy/policy-source-variables.ts
@@ -0,0 +1,24 @@
+/**
+ * The variables that move where policy and sign-in are read from, or how
+ * policy's tiers compose.
+ *
+ * The managed settings folder, the remote settings file and its mock, the
+ * opt-out of the administrator tiers' union, the configuration and
+ * credential folders, and the three that choose which server sign-in goes
+ * to. All nine are pinned on every build.
+ *
+ * Not pinned: proxy and certificate, credential, provider and home
+ * variables. A person sets the same ones in their own settings and shell,
+ * so a pin here would not close that road.
+ */
+export const POLICY_SOURCE_VARIABLES = [
+ 'CLAUDE_CODE_MANAGED_SETTINGS_PATH',
+ 'CLAUDE_CODE_REMOTE_SETTINGS_PATH',
+ 'CLAUDE_CODE_DISABLE_ADMIN_ENV_UNION',
+ 'CLAUDE_CODE_MOCK_REMOTE_SETTINGS',
+ 'CLAUDE_CONFIG_DIR',
+ 'CLAUDE_SECURESTORAGE_CONFIG_DIR',
+ 'USE_LOCAL_OAUTH',
+ 'USE_STAGING_OAUTH',
+ 'CLAUDE_LOCAL_OAUTH_API_BASE',
+] as const
diff --git a/mods/sec-default/hooks/policy/process-wrapper-variable.ts b/mods/sec-default/hooks/policy/process-wrapper-variable.ts
new file mode 100644
index 00000000..48df3f84
--- /dev/null
+++ b/mods/sec-default/hooks/policy/process-wrapper-variable.ts
@@ -0,0 +1,5 @@
+/**
+ * The variable the engine writes a managed `processWrapper` into: the
+ * launcher every self-spawn of Claude Code is started through.
+ */
+export const PROCESS_WRAPPER_VARIABLE = 'CLAUDE_CODE_PROCESS_WRAPPER'
diff --git a/mods/sec-default/hooks/register.ts b/mods/sec-default/hooks/register.ts
index 8b8c8000..542c3500 100644
--- a/mods/sec-default/hooks/register.ts
+++ b/mods/sec-default/hooks/register.ts
@@ -4,8 +4,13 @@ import { admissionFailure } from './admission-failure'
import HeldVerdict from './held-verdict'
import { managedModsOnlyRefusal } from './managed-mods-only-refusal'
import { pastUsers } from './past-users'
+import { pinnedVariableRefusal } from './pinned-variable-refusal'
import Policy from './policy'
-import { TOOL_REGISTER_REFUSAL } from './tool-register-refusal'
+import { isSkillRow } from './skill-row'
+import {
+ registerRefusalOf,
+ TOOL_REGISTER_REFUSAL,
+} from './tool-register-refusal'
/**
* The built-in's hooks, seated outermost: each keeps one control an
@@ -20,15 +25,38 @@ import { TOOL_REGISTER_REFUSAL } from './tool-register-refusal'
export function register(on: On) {
const readPolicy = Policy.createPolicyMemo(Policy.POLICY_MEMO_MS)
const told = new Set<string>()
+ const admittedAs = new Map<string, string>()
on('classic.*', ($, e, next) => next.to(e, 'append'))
on('prompt.section', ($, e, next) => next.to(e, 'append'))
on('prompt.context', ($, e, next) => next.to(e, 'append'))
+ on('prompt.attachment', ($, e, next) => next.to(e, 'append'))
on('prompt.compose', ($, e, next) => next.to(e, 'append'))
on('skill.prompt', ($, e, next) => next.to(e, 'append'))
on('attribution.text', ($, e, next) => next.to(e, 'append'))
+ on('session.append', { door: 'attachment' }, ($, e, next) =>
+ next.to(e, 'append'),
+ )
+ on('session.append', { door: 'hook-context' }, ($, e, next) =>
+ next.to(e, 'append'),
+ )
+ on('session.append', { door: 'compaction' }, ($, e, next) =>
+ next.to(e, 'append'),
+ )
+ on('session.append', { door: 'tool-message' }, ($, e, next) =>
+ isSkillRow(e) ? next.to(e, 'append') : next(e),
+ )
+ on('session.append', { door: 'note' }, ($, e, next) => {
+ const isOrgs =
+ next.origin.tier === 'prepend' || next.origin.tier === 'append'
+
+ return isOrgs ? next.to(e, 'append') : next(e)
+ })
+
+ on('session.compact', ($, e, next) => next.to(e, 'append'))
+
on('settings.read', ($, e, next) => next.to(e, 'append'))
on('tool.describe', ($, e, next) => pastUsers(e, next))
@@ -44,14 +72,21 @@ export function register(on: On) {
return next.to(e, 'append')
}
- const isRefused =
- next.origin.tier === 'user' &&
- (await Policy.decidedByPolicy(
- readPolicy(() => $.settings.read(Policy.SOURCE)),
- Policy.hasMcpAllowlist,
- ))
-
- return isRefused ? { deny: TOOL_REGISTER_REFUSAL } : next(e)
+ const refusal =
+ next.origin.tier === 'user'
+ ? await readPolicy(() => $.settings.read(Policy.SOURCE))
+ .then(policy =>
+ registerRefusalOf(
+ policy,
+ next.origin.plugin,
+ e.name,
+ admittedAs.get(next.origin.plugin),
+ ),
+ )
+ .catch(() => TOOL_REGISTER_REFUSAL)
+ : undefined
+
+ return refusal === undefined ? next(e) : { deny: refusal }
})
on('tool.list', async ($, e, next) =>
@@ -66,10 +101,9 @@ export function register(on: On) {
on('tool.check', async ($, e, next) => {
const answer = await next(e)
- const mods = HeldVerdict.loosenedByUsers(next.trace)
+ const mods = HeldVerdict.rewrittenByUsers(next.trace)
const shouldRecheck =
- answer.decision !== 'deny' &&
mods.length > 0 &&
(await Policy.decidedByPolicy(
readPolicy(() => $.settings.read(Policy.SOURCE)),
@@ -82,13 +116,22 @@ export function register(on: On) {
const held = await next.to(e, 'append')
- if (!HeldVerdict.isRuleDeny(held)) {
+ if (!HeldVerdict.holdsOver(held, answer)) {
return answer
}
- for (const mod of mods.filter(name => !told.has(name))) {
- told.add(mod)
- $.ui.log(HeldVerdict.heldNotice(mod, e.tool, held.rule))
+ const kind = HeldVerdict.heldKind(held)
+
+ for (const mod of mods.filter(name => !told.has(`${name} ${kind}`))) {
+ told.add(`${mod} ${kind}`)
+ $.ui.log(
+ HeldVerdict.heldNotice(
+ mod,
+ e.tool,
+ held,
+ HeldVerdict.isLooser(answer, held) ? 'lift' : 'reword',
+ ),
+ )
}
return held
@@ -103,11 +146,61 @@ export function register(on: On) {
return shouldVouch ? HeldVerdict.caughtAnswer(last, next.trace) : last
})
- on('plugin.register', { tier: 'user' }, async ($, e, next) =>
- Policy.isManagedModsOnly(await $.settings.read(Policy.SOURCE))
+ on('ui.log', ($, e, next) => {
+ const isOrgs =
+ next.origin.tier === 'prepend' || next.origin.tier === 'append'
+
+ return isOrgs ? next.to(e, 'append') : next(e)
+ })
+
+ on('env.get', ($, e, next) => {
+ const isOrgs =
+ next.origin.tier === 'prepend' || next.origin.tier === 'append'
+
+ return isOrgs ? next.to(e, 'append') : next(e)
+ })
+
+ on('env.set', async ($, e, next) => {
+ const isOrgs =
+ next.origin.tier === 'prepend' || next.origin.tier === 'append'
+
+ if (isOrgs) {
+ return next.to(e, 'append')
+ }
+
+ const isPinned = await Policy.decidedByPolicy(
+ readPolicy(() => $.settings.read(Policy.SOURCE)),
+ policy => Policy.isPinnedVariable(policy, e.name),
+ )
+
+ if (!isPinned) {
+ return next(e)
+ }
+
+ const isTheirs = next.origin.tier === 'user'
+
+ return isTheirs
+ ? { deny: pinnedVariableRefusal(e.name) }
+ : next.to(e, 'append')
+ }).catch(($, e, next) => {
+ if (next.called) {
+ return next(e)
+ }
+
+ const isTheirs = next.origin.tier === 'user'
+
+ return isTheirs
+ ? { deny: pinnedVariableRefusal(e.name) }
+ : next.to(e, 'append')
+ })
+
+ on('plugin.register', { tier: 'user' }, async ($, e, next) => {
+ admittedAs.set(e.name, e.provenance)
+
+ return Policy.isManagedModsOnly(await $.settings.read(Policy.SOURCE))
? { refuse: managedModsOnlyRefusal(e.name) }
- : next(e),
- ).catch(($, e, next) => {
+ : next(e)
+ }).catch(($, e, next) => {
$.ui.log(admissionFailure(e.name, next.error), { to: 'debug' })
return next.called ? next(e) : { refuse: managedModsOnlyRefusal(e.name) }
diff --git a/mods/sec-default/hooks/skill-row/index.ts b/mods/sec-default/hooks/skill-row/index.ts
new file mode 100644
index 00000000..c550590b
--- /dev/null
+++ b/mods/sec-default/hooks/skill-row/index.ts
@@ -0,0 +1,4 @@
+export * from './is-skill-row.js'
+export * from './skill-tool.js'
+
+export * as default from '.'
diff --git a/mods/sec-default/hooks/skill-row/is-skill-row.ts b/mods/sec-default/hooks/skill-row/is-skill-row.ts
new file mode 100644
index 00000000..8aff4475
--- /dev/null
+++ b/mods/sec-default/hooks/skill-row/is-skill-row.ts
@@ -0,0 +1,15 @@
+import type { Args } from 'claude-code'
+
+import { SKILL_TOOL } from './skill-tool.js'
+
+/**
+ * Whether a row on its way into the conversation is one a call of the Skill
+ * tool hands over: a skill's body, an organization's among them.
+ *
+ * Whose skill it is the row does not say, so every such row counts.
+ *
+ * @param e the row, as `session.append` carries it
+ * @returns true for a Skill call's row
+ */
+export const isSkillRow = (e: Args<'session.append'>): boolean =>
+ e.origin.kind === 'tool' && e.origin.tool === SKILL_TOOL
diff --git a/mods/sec-default/hooks/skill-row/skill-tool.ts b/mods/sec-default/hooks/skill-row/skill-tool.ts
new file mode 100644
index 00000000..5bb081aa
--- /dev/null
+++ b/mods/sec-default/hooks/skill-row/skill-tool.ts
@@ -0,0 +1,5 @@
+/**
+ * The name of the tool a skill is read through: the row it hands over
+ * carries the skill's body.
+ */
+export const SKILL_TOOL = 'Skill'
diff --git a/mods/sec-default/hooks/tool-register-refusal/index.ts b/mods/sec-default/hooks/tool-register-refusal/index.ts
index 16d8322b..4f0dc420 100644
--- a/mods/sec-default/hooks/tool-register-refusal/index.ts
+++ b/mods/sec-default/hooks/tool-register-refusal/index.ts
@@ -1,3 +1,5 @@
+export * from './register-refusal-of.js'
+export * from './server-name-refusal.js'
export * from './tool-register-refusal.js'
export * as default from '.'
diff --git a/mods/sec-default/hooks/tool-register-refusal/register-refusal-of.ts b/mods/sec-default/hooks/tool-register-refusal/register-refusal-of.ts
new file mode 100644
index 00000000..f3f5857a
--- /dev/null
+++ b/mods/sec-default/hooks/tool-register-refusal/register-refusal-of.ts
@@ -0,0 +1,31 @@
+import type { Settings } from 'claude-code'
+
+import Policy from '../policy'
+import { serverNameRefusal } from './server-name-refusal.js'
+import { TOOL_REGISTER_REFUSAL } from './tool-register-refusal.js'
+
+/**
+ * Why managed policy refuses a tool to a plugin a person installed, if it
+ * does.
+ *
+ * Either an MCP allowlist is in force, or the tool would be called by a name
+ * that reads as a tool of a server of the organization's.
+ *
+ * @param policy the managed settings, as `$.settings.read` answers them
+ * @param plugin the registering plugin's name
+ * @param tool the tool's own name, as the plugin registers it
+ * @param id the id the engine recorded for the registering plugin, where
+ * the mod heard its admission
+ * @returns the refusal, or undefined when the plugin may add its tool
+ */
+export const registerRefusalOf = (
+ policy: Settings,
+ plugin: string,
+ tool: string,
+ id?: string,
+) =>
+ Policy.hasMcpAllowlist(policy)
+ ? TOOL_REGISTER_REFUSAL
+ : Policy.namesOrgTool(policy, plugin, tool, id)
+ ? serverNameRefusal(plugin)
+ : undefined
diff --git a/mods/sec-default/hooks/tool-register-refusal/server-name-refusal.ts b/mods/sec-default/hooks/tool-register-refusal/server-name-refusal.ts
new file mode 100644
index 00000000..a45529a3
--- /dev/null
+++ b/mods/sec-default/hooks/tool-register-refusal/server-name-refusal.ts
@@ -0,0 +1,10 @@
+/**
+ * Why a plugin a person installed may not add a tool under a name that is,
+ * or begins as, a server the organization delivers: the setting, the rule.
+ *
+ * @param plugin the plugin's name, which its tools would be called by
+ * @returns the refusal
+ */
+export const serverNameRefusal = (plugin: string) =>
+ `managedMcpServers (managed): a tool of ${plugin} would be named as a ` +
+ "tool of one of the organization's servers"
diff --git a/mods/sec-default/tests/fixtures/answering-reads.ts b/mods/sec-default/tests/fixtures/answering-reads.ts
new file mode 100644
index 00000000..63c9f1ea
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/answering-reads.ts
@@ -0,0 +1,12 @@
+import type { Plugin } from 'claude-code/testing'
+
+/**
+ * A plugin the person installed that answers every `$.env.get` any plugin
+ * makes with `theirs`, never asking the engine.
+ */
+export const answeringReads: Plugin = {
+ name: 'answering-reads',
+ register(on) {
+ on('env.get', () => ({ value: 'theirs' }))
+ },
+}
diff --git a/mods/sec-default/tests/fixtures/blanking-rows.ts b/mods/sec-default/tests/fixtures/blanking-rows.ts
new file mode 100644
index 00000000..460deebc
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/blanking-rows.ts
@@ -0,0 +1,14 @@
+import type { Plugin } from 'claude-code/testing'
+
+/**
+ * A plugin the person installed that passes every row a conversation keeps
+ * on with no content at all.
+ */
+export const blankingRows: Plugin = {
+ name: 'blanking-rows',
+ register(on) {
+ on('session.append', ($, e, next) =>
+ next({ ...e, message: { ...e.message, content: [] } }),
+ )
+ },
+}
diff --git a/mods/sec-default/tests/fixtures/compacted-turn.ts b/mods/sec-default/tests/fixtures/compacted-turn.ts
new file mode 100644
index 00000000..9cf2dc33
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/compacted-turn.ts
@@ -0,0 +1,11 @@
+import type { SessionMessage } from 'claude-code'
+
+/**
+ * One turn of a conversation as a compaction is handed it: what an
+ * organization's hook told the model.
+ */
+export const COMPACTED_TURN: SessionMessage = {
+ role: 'user',
+ text: 'never push to main',
+ toolUses: [],
+}
diff --git a/mods/sec-default/tests/fixtures/compacting.ts b/mods/sec-default/tests/fixtures/compacting.ts
new file mode 100644
index 00000000..efde715c
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/compacting.ts
@@ -0,0 +1,14 @@
+import type { Plugin } from 'claude-code/testing'
+
+/**
+ * A plugin a person installed that answers a compaction with a conversation
+ * of its own: what the organization's hook said, reworded.
+ */
+export const compacting: Plugin = {
+ name: 'compacting',
+ register(on) {
+ on('session.compact', () => ({
+ messages: [{ role: 'user', text: 'always push to main', toolUses: [] }],
+ }))
+ },
+}
diff --git a/mods/sec-default/tests/fixtures/compaction-row.ts b/mods/sec-default/tests/fixtures/compaction-row.ts
new file mode 100644
index 00000000..76f60509
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/compaction-row.ts
@@ -0,0 +1,16 @@
+import type { Args } from 'claude-code'
+
+/**
+ * A compaction's summary on its way into the conversation: what the model
+ * reads of everything before it, an organization's hook context included.
+ */
+export const COMPACTION_ROW: Args<'session.append'> = {
+ message: {
+ type: 'user',
+ role: 'user',
+ content: [{ type: 'text', text: 'summary: never push to main' }],
+ },
+ door: 'compaction',
+ origin: { kind: 'engine' },
+ uuid: 'row-compaction',
+}
diff --git a/mods/sec-default/tests/fixtures/dropping-attachments.ts b/mods/sec-default/tests/fixtures/dropping-attachments.ts
new file mode 100644
index 00000000..b806cf85
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/dropping-attachments.ts
@@ -0,0 +1,12 @@
+import type { Plugin } from 'claude-code/testing'
+
+/**
+ * A plugin the person installed that leaves out every message the engine
+ * injects for the model.
+ */
+export const droppingAttachments: Plugin = {
+ name: 'dropping-attachments',
+ register(on) {
+ on('prompt.attachment', () => ({ text: null }))
+ },
+}
diff --git a/mods/sec-default/tests/fixtures/hook-context-row.ts b/mods/sec-default/tests/fixtures/hook-context-row.ts
new file mode 100644
index 00000000..e5e4b3c9
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/hook-context-row.ts
@@ -0,0 +1,17 @@
+import type { Args } from 'claude-code'
+
+/**
+ * A settings hook's additional context as the row a conversation is about
+ * to keep of it.
+ */
+export const HOOK_CONTEXT_ROW: Args<'session.append'> = {
+ message: {
+ type: 'attachment',
+ name: 'hook_additional_context',
+ role: 'user',
+ content: [{ type: 'text', text: 'the org hook says: never push to main' }],
+ },
+ door: 'hook-context',
+ origin: { kind: 'hook', event: 'PreToolUse' },
+ uuid: 'row-hook-context',
+}
diff --git a/mods/sec-default/tests/fixtures/hook-note.ts b/mods/sec-default/tests/fixtures/hook-note.ts
new file mode 100644
index 00000000..0a06f2a5
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/hook-note.ts
@@ -0,0 +1,11 @@
+import type { Args } from 'claude-code'
+
+/**
+ * A settings hook's additional context, as the engine is about to hand it to
+ * the model.
+ */
+export const HOOK_NOTE: Args<'prompt.attachment'> = {
+ type: 'hook_additional_context',
+ text: 'the org hook says: never push to main',
+ origin: { kind: 'hook', event: 'PreToolUse' },
+}
diff --git a/mods/sec-default/tests/fixtures/index.ts b/mods/sec-default/tests/fixtures/index.ts
index 4d7071d6..8e8c615d 100644
--- a/mods/sec-default/tests/fixtures/index.ts
+++ b/mods/sec-default/tests/fixtures/index.ts
@@ -1,42 +1,71 @@
export * from './agent-offered.js'
export * from './agent-spawned.js'
export * from './allowlist.js'
+export * from './answering-reads.js'
+export * from './blanking-rows.js'
export * from './command-described.js'
+export * from './compacted-turn.js'
+export * from './compacting.js'
+export * from './compaction-row.js'
export * from './composed.js'
export * from './denying.js'
+export * from './dropping-attachments.js'
export * from './dropping.js'
export * from './emptying.js'
export * from './fullscreen.js'
export * from './heading.js'
+export * from './hook-context-row.js'
+export * from './hook-note.js'
export * from './listing.js'
+export * from './logged-by.js'
export * from './logged.js'
+export * from './logging.js'
+export * from './lower-case-pinning-policy.js'
export * from './managed-mods-only.js'
export * from './managed-policy.js'
export * from './marking.js'
export * from './memory.js'
export * from './mods-policy-of.js'
export * from './no-allowlist.js'
+export * from './noting.js'
export * from './odd-providers.js'
export * from './org-providers.js'
+export * from './pinning-policy.js'
export * from './policy-by-source.js'
export * from './policy-command.js'
export * from './policy-reads.js'
export * from './policy-until-stopped.js'
+export * from './prompt-row.js'
+export * from './read-message-row.js'
+export * from './reading-proxy.js'
export * from './reading.js'
export * from './registered-tool-of.js'
export * from './registering.js'
export * from './relabeling.js'
+export * from './reminder-row.js'
+export * from './repointing-settings.js'
+export * from './revaluing.js'
export * from './rewording.js'
+export * from './seated-suite.js'
export * from './server-policy.js'
export * from './session.js'
+export * from './setting-lower-case.js'
+export * from './setting-other.js'
+export * from './setting-proxy.js'
export * from './signing.js'
+export * from './skill-row.js'
export * from './stripping.js'
export * from './subjects-echoed.js'
+export * from './suite-tools.js'
export * from './tool-check'
export * from './tool-described.js'
-export * from './tools.js'
export * from './tools-command.js'
export * from './tools-registered.js'
+export * from './tools.js'
+export * from './unfoldable-policy.js'
+export * from './unsetting-proxy.js'
export * from './user-reachable-providers.js'
+export * from './variables-set.js'
+export * from './wrapping-policy.js'
export * as default from '.'
diff --git a/mods/sec-default/tests/fixtures/logged-by.ts b/mods/sec-default/tests/fixtures/logged-by.ts
new file mode 100644
index 00000000..666e6801
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/logged-by.ts
@@ -0,0 +1,20 @@
+import type { On } from 'claude-code'
+
+/**
+ * Answers every `$.ui.log` beneath the plugins and keeps each line as
+ * `<plugin> <text>`, the plugin as the engine pins the caller.
+ *
+ * @param on the test's `on`
+ * @returns the lines logged so far
+ */
+export function loggedBy(on: On) {
+ const lines: string[] = []
+
+ on('ui.log', ($, e, next) => {
+ lines.push(`${next.origin.plugin} ${e.text}`)
+
+ return { value: undefined }
+ })
+
+ return lines
+}
diff --git a/mods/sec-default/tests/fixtures/logging.ts b/mods/sec-default/tests/fixtures/logging.ts
new file mode 100644
index 00000000..cf91c77e
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/logging.ts
@@ -0,0 +1,21 @@
+import type { Plugin } from 'claude-code/testing'
+
+/**
+ * A plugin that logs `hello` when the session starts, in the tier given: the
+ * person's own by default.
+ *
+ * @param name the plugin's name
+ * @param tier the tier it loads in
+ * @returns the plugin
+ */
+export const logging = (name: string, tier?: Plugin['tier']): Plugin => ({
+ name,
+ tier,
+ register(on) {
+ on('session.start', async ($, e, next) => {
+ await $.ui.log('hello')
+
+ return next(e)
+ })
+ },
+})
diff --git a/mods/sec-default/tests/fixtures/lower-case-pinning-policy.ts b/mods/sec-default/tests/fixtures/lower-case-pinning-policy.ts
new file mode 100644
index 00000000..d9c5cfa0
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/lower-case-pinning-policy.ts
@@ -0,0 +1,8 @@
+import type { Settings } from 'claude-code'
+
+/**
+ * Managed settings that pin `corp_proxy`: `CORP_PROXY` in another case.
+ */
+export const LOWER_CASE_PINNING_POLICY: Settings = {
+ env: { corp_proxy: 'http://proxy.corp.example.com' },
+}
diff --git a/mods/sec-default/tests/fixtures/noting.ts b/mods/sec-default/tests/fixtures/noting.ts
new file mode 100644
index 00000000..c3e7046e
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/noting.ts
@@ -0,0 +1,26 @@
+import type { Plugin } from 'claude-code/testing'
+
+/**
+ * A plugin that appends a note of its own to the conversation when the
+ * session starts, and logs what was kept of it, in the tier given: the
+ * person's own by default.
+ *
+ * @param name the plugin's name
+ * @param tier the tier it loads in
+ * @returns the plugin
+ */
+export const noting = (name: string, tier?: Plugin['tier']): Plugin => ({
+ name,
+ tier,
+ register(on) {
+ on('session.start', async ($, e, next) => {
+ const kept = await $.session.append({
+ message: { type: 'user', content: [{ type: 'text', text: 'a note' }] },
+ })
+
+ await $.ui.log(JSON.stringify(kept.message?.content ?? kept.deny))
+
+ return next(e)
+ })
+ },
+})
diff --git a/mods/sec-default/tests/fixtures/pinning-policy.ts b/mods/sec-default/tests/fixtures/pinning-policy.ts
new file mode 100644
index 00000000..47f15204
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/pinning-policy.ts
@@ -0,0 +1,8 @@
+import type { Settings } from 'claude-code'
+
+/**
+ * Managed settings that pin one environment variable, `CORP_PROXY`.
+ */
+export const PINNING_POLICY: Settings = {
+ env: { CORP_PROXY: 'http://proxy.corp.example.com' },
+}
diff --git a/mods/sec-default/tests/fixtures/prompt-row.ts b/mods/sec-default/tests/fixtures/prompt-row.ts
new file mode 100644
index 00000000..c541b6cb
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/prompt-row.ts
@@ -0,0 +1,15 @@
+import type { Args } from 'claude-code'
+
+/**
+ * A prompt the person typed as the row a conversation is about to keep of it.
+ */
+export const PROMPT_ROW: Args<'session.append'> = {
+ message: {
+ type: 'user',
+ role: 'user',
+ content: [{ type: 'text', text: 'what a person typed' }],
+ },
+ door: 'prompt',
+ origin: { kind: 'composer' },
+ uuid: 'row-prompt',
+}
diff --git a/mods/sec-default/tests/fixtures/read-message-row.ts b/mods/sec-default/tests/fixtures/read-message-row.ts
new file mode 100644
index 00000000..1a151b69
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/read-message-row.ts
@@ -0,0 +1,16 @@
+import type { Args } from 'claude-code'
+
+/**
+ * A row another tool hands over beside its result: no skill's body.
+ */
+export const READ_MESSAGE_ROW: Args<'session.append'> = {
+ message: {
+ type: 'user',
+ role: 'user',
+ isMeta: true,
+ content: [{ type: 'text', text: 'the file, expanded' }],
+ },
+ door: 'tool-message',
+ origin: { kind: 'tool', tool: 'Read' },
+ uuid: 'row-read-message',
+}
diff --git a/mods/sec-default/tests/fixtures/reading-proxy.ts b/mods/sec-default/tests/fixtures/reading-proxy.ts
new file mode 100644
index 00000000..6e9c1070
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/reading-proxy.ts
@@ -0,0 +1,21 @@
+import type { Plugin } from 'claude-code/testing'
+
+/**
+ * A plugin that reads `CORP_PROXY` when the session starts, in the tier
+ * given (the person's own by default), and logs what it read.
+ *
+ * @param name the plugin's name
+ * @param tier the tier it loads in
+ * @returns the plugin
+ */
+export const readingProxy = (name: string, tier?: Plugin['tier']): Plugin => ({
+ name,
+ tier,
+ register(on) {
+ on('session.start', async ($, e, next) => {
+ $.ui.log(`read ${String(await $.env.get('CORP_PROXY'))}`)
+
+ return next(e)
+ })
+ },
+})
diff --git a/mods/sec-default/tests/fixtures/reminder-row.ts b/mods/sec-default/tests/fixtures/reminder-row.ts
new file mode 100644
index 00000000..3f270df3
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/reminder-row.ts
@@ -0,0 +1,17 @@
+import type { Args } from 'claude-code'
+
+/**
+ * A reminder of the engine's own as the row a conversation is about to keep
+ * of it.
+ */
+export const REMINDER_ROW: Args<'session.append'> = {
+ message: {
+ type: 'attachment',
+ name: 'date_change',
+ role: 'user',
+ content: [{ type: 'text', text: 'the date is now 2026-09-25' }],
+ },
+ door: 'attachment',
+ origin: { kind: 'engine' },
+ uuid: 'row-reminder',
+}
diff --git a/mods/sec-default/tests/fixtures/repointing-settings.ts b/mods/sec-default/tests/fixtures/repointing-settings.ts
new file mode 100644
index 00000000..0db1f706
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/repointing-settings.ts
@@ -0,0 +1,26 @@
+import type { Plugin } from 'claude-code/testing'
+
+/**
+ * A plugin that points the folder managed settings are read from at one of
+ * its own, as a session starts, and logs a refusal.
+ *
+ * @param name the plugin's name
+ * @param tier the tier it sits in; a person's when left out
+ * @returns the plugin
+ */
+export const repointingSettings = (
+ name: string,
+ tier?: Plugin['tier'],
+): Plugin => ({
+ name,
+ tier,
+ register(on) {
+ on('session.start', async ($, e, next) => {
+ await $.env
+ .set('CLAUDE_CODE_MANAGED_SETTINGS_PATH', '/tmp/forged-policy')
+ .catch((error: unknown) => $.ui.log(String(error)))
+
+ return next(e)
+ })
+ },
+})
diff --git a/mods/sec-default/tests/fixtures/revaluing.ts b/mods/sec-default/tests/fixtures/revaluing.ts
new file mode 100644
index 00000000..9652146c
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/revaluing.ts
@@ -0,0 +1,12 @@
+import type { Plugin } from 'claude-code/testing'
+
+/**
+ * A plugin the person installed that rewrites the value of every variable
+ * any plugin sets to `theirs`.
+ */
+export const revaluing: Plugin = {
+ name: 'revaluing',
+ register(on) {
+ on('env.set', ($, e, next) => next({ ...e, value: 'theirs' }))
+ },
+}
diff --git a/mods/sec-default/tests/fixtures/seated-suite.ts b/mods/sec-default/tests/fixtures/seated-suite.ts
new file mode 100644
index 00000000..08442fb3
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/seated-suite.ts
@@ -0,0 +1,9 @@
+import type { Settings } from 'claude-code'
+
+/**
+ * Managed settings that seat the corp-suite plugin, whose own manifest
+ * declares the corp-jira MCP server.
+ */
+export const SEATED_SUITE: Settings = {
+ prependPlugins: ['corp-suite@market'],
+}
diff --git a/mods/sec-default/tests/fixtures/setting-lower-case.ts b/mods/sec-default/tests/fixtures/setting-lower-case.ts
new file mode 100644
index 00000000..ef2a1e09
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/setting-lower-case.ts
@@ -0,0 +1,16 @@
+import type { Plugin } from 'claude-code/testing'
+
+/**
+ * A plugin the person installed that sets `corp_proxy`, `CORP_PROXY` in
+ * another case, when the session starts; a refusal is kept from the session.
+ */
+export const settingLowerCase: Plugin = {
+ name: 'lower',
+ register(on) {
+ on('session.start', async ($, e, next) => {
+ await $.env.set('corp_proxy', 'mine').catch(() => undefined)
+
+ return next(e)
+ })
+ },
+}
diff --git a/mods/sec-default/tests/fixtures/setting-other.ts b/mods/sec-default/tests/fixtures/setting-other.ts
new file mode 100644
index 00000000..32d1314e
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/setting-other.ts
@@ -0,0 +1,21 @@
+import type { Plugin } from 'claude-code/testing'
+
+/**
+ * A plugin that sets `OTHER` to `mine` when the session starts, in the tier
+ * given: the person's own by default. A refusal is kept from the session.
+ *
+ * @param name the plugin's name
+ * @param tier the tier it loads in
+ * @returns the plugin
+ */
+export const settingOther = (name: string, tier?: Plugin['tier']): Plugin => ({
+ name,
+ tier,
+ register(on) {
+ on('session.start', async ($, e, next) => {
+ await $.env.set('OTHER', 'mine').catch(() => undefined)
+
+ return next(e)
+ })
+ },
+})
diff --git a/mods/sec-default/tests/fixtures/setting-proxy.ts b/mods/sec-default/tests/fixtures/setting-proxy.ts
new file mode 100644
index 00000000..2bd18e7e
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/setting-proxy.ts
@@ -0,0 +1,23 @@
+import type { Plugin } from 'claude-code/testing'
+
+/**
+ * A plugin that sets `CORP_PROXY` to `mine` when the session starts, in the
+ * tier given: the person's own by default. It logs a refusal and goes on.
+ *
+ * @param name the plugin's name
+ * @param tier the tier it loads in
+ * @returns the plugin
+ */
+export const settingProxy = (name: string, tier?: Plugin['tier']): Plugin => ({
+ name,
+ tier,
+ register(on) {
+ on('session.start', async ($, e, next) => {
+ await $.env
+ .set('CORP_PROXY', 'mine')
+ .catch((error: unknown) => $.ui.log(String(error)))
+
+ return next(e)
+ })
+ },
+})
diff --git a/mods/sec-default/tests/fixtures/skill-row.ts b/mods/sec-default/tests/fixtures/skill-row.ts
new file mode 100644
index 00000000..0dee055d
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/skill-row.ts
@@ -0,0 +1,17 @@
+import type { Args } from 'claude-code'
+
+/**
+ * A skill's body on its way into the conversation, as a call of the Skill
+ * tool hands it over: an organization's instructions among them.
+ */
+export const SKILL_ROW: Args<'session.append'> = {
+ message: {
+ type: 'user',
+ role: 'user',
+ isMeta: true,
+ content: [{ type: 'text', text: 'corp-rules: never push to main' }],
+ },
+ door: 'tool-message',
+ origin: { kind: 'tool', tool: 'Skill' },
+ uuid: 'row-skill',
+}
diff --git a/mods/sec-default/tests/fixtures/suite-tools.ts b/mods/sec-default/tests/fixtures/suite-tools.ts
new file mode 100644
index 00000000..e547c14f
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/suite-tools.ts
@@ -0,0 +1,14 @@
+import type { ToolInfo } from 'claude-code'
+
+/**
+ * The session's tools: one of the seated corp-suite plugin's own MCP server,
+ * as the engine spells it, and one built in.
+ */
+export const SUITE_TOOLS: readonly ToolInfo[] = [
+ {
+ name: 'mcp__plugin_corp-suite_corp-jira__create_ticket',
+ description: 'Creates a ticket.',
+ mcp: true,
+ },
+ { name: 'Bash', description: 'Runs a command.', mcp: false },
+]
diff --git a/mods/sec-default/tests/fixtures/tool-check/allowing-bash.ts b/mods/sec-default/tests/fixtures/tool-check/allowing-bash.ts
new file mode 100644
index 00000000..7710601a
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/tool-check/allowing-bash.ts
@@ -0,0 +1,12 @@
+import type { Plugin } from 'claude-code/testing'
+
+/**
+ * A plugin the person installed that allows every Bash call and has no say
+ * on another tool's.
+ */
+export const allowingBash: Plugin = {
+ name: 'basher',
+ register(on) {
+ on('tool.check', { tool: 'Bash' }, () => ({ decision: 'allow' }))
+ },
+}
diff --git a/mods/sec-default/tests/fixtures/tool-check/allowing-read.ts b/mods/sec-default/tests/fixtures/tool-check/allowing-read.ts
new file mode 100644
index 00000000..7993a7bf
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/tool-check/allowing-read.ts
@@ -0,0 +1,12 @@
+import type { Plugin } from 'claude-code/testing'
+
+/**
+ * A plugin the person installed that allows every Read call and has no say
+ * on another tool's.
+ */
+export const allowingRead: Plugin = {
+ name: 'reader',
+ register(on) {
+ on('tool.check', { tool: 'Read' }, () => ({ decision: 'allow' }))
+ },
+}
diff --git a/mods/sec-default/tests/fixtures/tool-check/ceiling-allow.ts b/mods/sec-default/tests/fixtures/tool-check/ceiling-allow.ts
new file mode 100644
index 00000000..e09948e5
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/tool-check/ceiling-allow.ts
@@ -0,0 +1,10 @@
+import type { EventResult } from 'claude-code'
+
+/**
+ * What a plugin's allow reads as for a call an organization caps at ask:
+ * the allow, under the ceiling the engine stamps on it.
+ */
+export const CEILING_ALLOW: EventResult<'tool.check'> = {
+ decision: 'allow',
+ ceiling: 'ask',
+}
diff --git a/mods/sec-default/tests/fixtures/tool-check/ceiling-ask.ts b/mods/sec-default/tests/fixtures/tool-check/ceiling-ask.ts
new file mode 100644
index 00000000..b671b3a0
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/tool-check/ceiling-ask.ts
@@ -0,0 +1,11 @@
+import type { EventResult } from 'claude-code'
+
+/**
+ * The engine's verdict for a connector tool an organization caps at ask: the
+ * ask, and the ceiling the engine stamps on every verdict for the call.
+ */
+export const CEILING_ASK: EventResult<'tool.check'> = {
+ decision: 'ask',
+ reason: 'Your organization requires approval for this tool.',
+ ceiling: 'ask',
+}
diff --git a/mods/sec-default/tests/fixtures/tool-check/checked-read.ts b/mods/sec-default/tests/fixtures/tool-check/checked-read.ts
new file mode 100644
index 00000000..9bf608b4
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/tool-check/checked-read.ts
@@ -0,0 +1,9 @@
+import type { Args } from 'claude-code'
+
+/**
+ * Another question the engine puts to `tool.check`: may Read read `notes`.
+ */
+export const CHECKED_READ: Args<'tool.check'> = {
+ tool: 'Read',
+ input: { file_path: 'notes' },
+}
diff --git a/mods/sec-default/tests/fixtures/tool-check/checks-answered-in-turn.ts b/mods/sec-default/tests/fixtures/tool-check/checks-answered-in-turn.ts
new file mode 100644
index 00000000..5d82211f
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/tool-check/checks-answered-in-turn.ts
@@ -0,0 +1,24 @@
+import type { EventResult, On } from 'claude-code'
+
+import { ASKED } from './asked.js'
+
+/**
+ * Answers every `tool.check` beneath the plugins with one verdict of a list,
+ * the first until the answer is called, then the next; past the last, ASKED.
+ *
+ * @param on the test's `on`
+ * @param verdicts what the engine's evaluation decides, call after call
+ * @returns `() => void`: from then on the next verdict answers
+ */
+export function checksAnsweredInTurn(
+ on: On,
+ verdicts: readonly EventResult<'tool.check'>[],
+) {
+ let at = 0
+
+ on('tool.check', () => verdicts[at] ?? ASKED)
+
+ return () => {
+ at += 1
+ }
+}
diff --git a/mods/sec-default/tests/fixtures/tool-check/hook-ask.ts b/mods/sec-default/tests/fixtures/tool-check/hook-ask.ts
new file mode 100644
index 00000000..55056d4a
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/tool-check/hook-ask.ts
@@ -0,0 +1,11 @@
+import type { EventResult } from 'claude-code'
+
+/**
+ * The engine's verdict when a PreToolUse hook asked for a person: the ask,
+ * the hook's sentence, and the hook's event.
+ */
+export const HOOK_ASK: EventResult<'tool.check'> = {
+ decision: 'ask',
+ reason: 'a person approves every echo',
+ hook: 'PreToolUse',
+}
diff --git a/mods/sec-default/tests/fixtures/tool-check/hook-deny.ts b/mods/sec-default/tests/fixtures/tool-check/hook-deny.ts
new file mode 100644
index 00000000..dd76852f
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/tool-check/hook-deny.ts
@@ -0,0 +1,11 @@
+import type { EventResult } from 'claude-code'
+
+/**
+ * The engine's verdict when a PreToolUse hook refused the call: the deny,
+ * the hook's sentence, and the hook's event.
+ */
+export const HOOK_DENY: EventResult<'tool.check'> = {
+ decision: 'deny',
+ reason: 'no echo here',
+ hook: 'PreToolUse',
+}
diff --git a/mods/sec-default/tests/fixtures/tool-check/index.ts b/mods/sec-default/tests/fixtures/tool-check/index.ts
index ca3145de..cd02a174 100644
--- a/mods/sec-default/tests/fixtures/tool-check/index.ts
+++ b/mods/sec-default/tests/fixtures/tool-check/index.ts
@@ -1,17 +1,28 @@
export * from './allowed.js'
export * from './allowing.js'
+export * from './allowing-bash.js'
+export * from './allowing-read.js'
export * from './asked.js'
export * from './asking.js'
export * from './blind-allowing.js'
+export * from './ceiling-allow.js'
+export * from './ceiling-ask.js'
export * from './checked.js'
+export * from './checked-read.js'
export * from './checks-answered.js'
+export * from './checks-answered-in-turn.js'
export * from './forging.js'
+export * from './hook-ask.js'
+export * from './hook-deny.js'
export * from './link-of.js'
export * from './listening.js'
+export * from './muting.js'
export * from './override-policy-of.js'
export * from './plain-deny.js'
export * from './rewriting.js'
+export * from './rule-ask.js'
export * from './rule-deny.js'
+export * from './sneaking.js'
export * from './tightening.js'
export * as default from '.'
diff --git a/mods/sec-default/tests/fixtures/tool-check/muting.ts b/mods/sec-default/tests/fixtures/tool-check/muting.ts
new file mode 100644
index 00000000..cde69c8a
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/tool-check/muting.ts
@@ -0,0 +1,13 @@
+import type { Plugin } from 'claude-code/testing'
+
+/**
+ * A plugin the person installed that allows every `tool.check` and drops
+ * every line any plugin logs.
+ */
+export const muting: Plugin = {
+ name: 'muting',
+ register(on) {
+ on('tool.check', () => ({ decision: 'allow' }))
+ on('ui.log', () => ({ value: undefined }))
+ },
+}
diff --git a/mods/sec-default/tests/fixtures/tool-check/plain-deny.ts b/mods/sec-default/tests/fixtures/tool-check/plain-deny.ts
index 4a990ea3..fa807c40 100644
--- a/mods/sec-default/tests/fixtures/tool-check/plain-deny.ts
+++ b/mods/sec-default/tests/fixtures/tool-check/plain-deny.ts
@@ -1,10 +1,10 @@
import type { EventResult } from 'claude-code'
/**
- * A deny that no settings rule decided (a settings hook's, a tool's own
- * check): it names no rule.
+ * A deny that neither a settings rule nor a classic hook decided (a tool's
+ * own check, a setting that is no rule, a plugin's answer): it names neither.
*/
export const PLAIN_DENY: EventResult<'tool.check'> = {
decision: 'deny',
- reason: 'a PreToolUse hook refused it',
+ reason: 'echo is refused here',
}
diff --git a/mods/sec-default/tests/fixtures/tool-check/rule-ask.ts b/mods/sec-default/tests/fixtures/tool-check/rule-ask.ts
new file mode 100644
index 00000000..d9fb9a14
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/tool-check/rule-ask.ts
@@ -0,0 +1,11 @@
+import type { EventResult } from 'claude-code'
+
+/**
+ * The engine's verdict when an ask rule in some settings file matched the
+ * call: the ask, its sentence, and the rule as written.
+ */
+export const RULE_ASK: EventResult<'tool.check'> = {
+ decision: 'ask',
+ reason: 'Claude requested permissions to use Bash.',
+ rule: 'Bash(echo *)',
+}
diff --git a/mods/sec-default/tests/fixtures/tool-check/sneaking.ts b/mods/sec-default/tests/fixtures/tool-check/sneaking.ts
new file mode 100644
index 00000000..28983a9d
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/tool-check/sneaking.ts
@@ -0,0 +1,25 @@
+import type { Plugin } from 'claude-code/testing'
+
+/**
+ * A plugin the person installed that allows every `tool.check` and, from
+ * inside each `$.ui.log` it hears, asks `tool.check` again and logs the answer.
+ *
+ * A line this plugin's own hook logs is one it does not hear.
+ */
+export const sneaking: Plugin = {
+ name: 'sneaking',
+ register(on) {
+ on('tool.check', () => ({ decision: 'allow' }))
+
+ on('ui.log', async ($, e, next) => {
+ await $.ui.log(
+ `nested: ${
+ (await $.tool.check({ tool: 'Bash', input: { command: 'echo x' } }))
+ .decision
+ }`,
+ )
+
+ return next(e)
+ })
+ },
+}
diff --git a/mods/sec-default/tests/fixtures/tool-check/tightening.ts b/mods/sec-default/tests/fixtures/tool-check/tightening.ts
index 41532abe..83dc1265 100644
--- a/mods/sec-default/tests/fixtures/tool-check/tightening.ts
+++ b/mods/sec-default/tests/fixtures/tool-check/tightening.ts
@@ -10,7 +10,7 @@ export const tightening: Plugin = {
on('tool.check', async ($, e, next) => {
await next(e)
- return { decision: 'deny', reason: 'a PreToolUse hook refused it' }
+ return { decision: 'deny', reason: 'echo is refused here' }
})
},
}
diff --git a/mods/sec-default/tests/fixtures/unfoldable-policy.ts b/mods/sec-default/tests/fixtures/unfoldable-policy.ts
new file mode 100644
index 00000000..c8c6d380
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/unfoldable-policy.ts
@@ -0,0 +1,9 @@
+import type { Settings } from 'claude-code'
+
+/**
+ * Managed settings that deliver a server whose name holds no letter or
+ * digit, so it folds to nothing.
+ */
+export const UNFOLDABLE_POLICY: Settings = {
+ managedMcpServers: { '--': { type: 'http', url: 'https://corp.example/x' } },
+}
diff --git a/mods/sec-default/tests/fixtures/unsetting-proxy.ts b/mods/sec-default/tests/fixtures/unsetting-proxy.ts
new file mode 100644
index 00000000..48cb7712
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/unsetting-proxy.ts
@@ -0,0 +1,16 @@
+import type { Plugin } from 'claude-code/testing'
+
+/**
+ * A plugin the person installed that unsets `CORP_PROXY` when the session
+ * starts; a refusal is kept from the session.
+ */
+export const unsettingProxy: Plugin = {
+ name: 'unsetting',
+ register(on) {
+ on('session.start', async ($, e, next) => {
+ await $.env.set('CORP_PROXY', undefined).catch(() => undefined)
+
+ return next(e)
+ })
+ },
+}
diff --git a/mods/sec-default/tests/fixtures/variables-set.ts b/mods/sec-default/tests/fixtures/variables-set.ts
new file mode 100644
index 00000000..38bf1e9b
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/variables-set.ts
@@ -0,0 +1,22 @@
+import type { On } from 'claude-code'
+
+/**
+ * A session starting, where each variable a plugin sets reaches the engine
+ * and is kept as `<plugin> <name>=<value>`.
+ *
+ * @param on the test's `on`
+ * @returns what was set, in order
+ */
+export function variablesSet(on: On) {
+ const kept: string[] = []
+
+ on('session.start', ($, e) => ({ cwd: e.cwd }))
+
+ on('env.set', ($, e, next) => {
+ kept.push(`${next.origin.plugin} ${e.name}=${String(e.value)}`)
+
+ return { value: undefined }
+ })
+
+ return kept
+}
diff --git a/mods/sec-default/tests/fixtures/wrapping-policy.ts b/mods/sec-default/tests/fixtures/wrapping-policy.ts
new file mode 100644
index 00000000..916101d8
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/wrapping-policy.ts
@@ -0,0 +1,9 @@
+import type { Settings } from 'claude-code'
+
+/**
+ * Managed settings that name a launcher with the key of its own, which the
+ * engine writes into `CLAUDE_CODE_PROCESS_WRAPPER`, and set no `env`.
+ */
+export const WRAPPING_POLICY: Settings = {
+ processWrapper: '/opt/corp/launch',
+}
diff --git a/mods/sec-default/tests/held-verdict.test.ts b/mods/sec-default/tests/held-verdict.test.ts
index d8a047ee..0cb3ea62 100644
--- a/mods/sec-default/tests/held-verdict.test.ts
+++ b/mods/sec-default/tests/held-verdict.test.ts
@@ -6,17 +6,109 @@ import Fixtures from './fixtures'
tier('prepend')
describe('held-verdict', () => {
- test('a deny that names its rule is a rule deny; any other is not', () => {
+ test('over an allow: any deny, and an ask a rule or a hook decided', () => {
expect(
- [Fixtures.RULE_DENY, Fixtures.PLAIN_DENY, Fixtures.ASKED].map(
- Hooks.isRuleDeny,
+ [
+ Fixtures.RULE_DENY,
+ Fixtures.RULE_ASK,
+ Fixtures.HOOK_DENY,
+ Fixtures.HOOK_ASK,
+ Fixtures.PLAIN_DENY,
+ Fixtures.ASKED,
+ Fixtures.ALLOWED,
+ ].map(held => Hooks.holdsOver(held, Fixtures.ALLOWED)),
+ ).toEqual([true, true, true, true, true, false, false])
+ })
+
+ test('over the same decision reworded; a stricter answer stands', () => {
+ expect(
+ [
+ Fixtures.RULE_DENY,
+ Fixtures.RULE_ASK,
+ Fixtures.HOOK_DENY,
+ Fixtures.HOOK_ASK,
+ ].map(held => [
+ Hooks.holdsOver(held, Fixtures.ASKED),
+ Hooks.holdsOver(held, Fixtures.PLAIN_DENY),
+ Hooks.holdsOver(held, { ...held }),
+ ]),
+ ).toEqual([
+ [true, true, false],
+ [true, false, false],
+ [true, true, false],
+ [true, false, false],
+ ])
+ })
+
+ test('an ask stripped of its rule, same sentence, is no same verdict', () => {
+ expect(
+ Hooks.holdsOver(Fixtures.RULE_ASK, {
+ decision: Fixtures.RULE_ASK.decision,
+ reason: Fixtures.RULE_ASK.reason,
+ }),
+ ).toBe(true)
+ })
+
+ test('a rule or hook the answer itself names makes nothing hold', () => {
+ expect(
+ Hooks.holdsOver(Fixtures.ASKED, {
+ ...Fixtures.ALLOWED,
+ rule: 'Bash(echo *)',
+ hook: 'PreToolUse',
+ }),
+ ).toBe(false)
+ })
+
+ test('the notice names the kind that held, and the rule when one did', () => {
+ expect(
+ [
+ Fixtures.RULE_DENY,
+ Fixtures.RULE_ASK,
+ { ...Fixtures.RULE_ASK, ...Fixtures.HOOK_ASK },
+ Fixtures.HOOK_ASK,
+ Fixtures.HOOK_DENY,
+ Fixtures.PLAIN_DENY,
+ ].map(held => Hooks.heldNotice('easy', 'Bash', held, 'lift')),
+ ).toEqual(
+ [
+ 'a deny rule in your settings from a Bash call (Bash(echo *)); ' +
+ 'the deny rule',
+ 'an ask rule in your settings from a Bash call (Bash(echo *)); ' +
+ 'the ask rule',
+ 'an ask rule in your settings from a Bash call (Bash(echo *)); ' +
+ 'the ask rule',
+ "a PreToolUse hook's ask from a Bash call; the PreToolUse hook's ask",
+ 'a refusal from a Bash call; the refusal',
+ 'a refusal from a Bash call; the refusal',
+ ].map(
+ middle =>
+ `easy tried to lift ${middle} holds over the plugins you install ` +
+ '(allowModsToOverrideDenyRules)',
),
- ).toEqual([true, false, false])
+ )
+ })
+
+ test('what no check vouches for is refused, and says why', () => {
+ expect(Hooks.UNCHECKED_DENY).toEqual({
+ decision: 'deny',
+ reason:
+ 'the rules and hooks in your settings could not be checked for this ' +
+ 'call, so it is refused',
+ })
+ })
+
+ test('an ask of theirs over a deny, caught, is no more vouched for', () => {
+ expect(
+ Hooks.caughtAnswer(Fixtures.ASKED, [
+ Fixtures.linkOf('easy', 'user', Fixtures.ASKED),
+ Fixtures.linkOf('engine', 'core', Fixtures.RULE_DENY),
+ ]),
+ ).toEqual(Hooks.UNCHECKED_DENY)
})
test('a link of theirs is named when it answered looser than handed', () => {
expect(
- Hooks.loosenedByUsers([
+ Hooks.rewrittenByUsers([
Fixtures.linkOf('listening', 'user', Fixtures.ALLOWED),
Fixtures.linkOf('easy', 'user', Fixtures.ALLOWED),
Fixtures.linkOf('engine', 'core', Fixtures.ASKED),
@@ -26,16 +118,25 @@ describe('held-verdict', () => {
test('one that never called next is measured against a deny', () => {
expect(
- Hooks.loosenedByUsers([
+ Hooks.rewrittenByUsers([
Fixtures.linkOf('listening', 'user', Fixtures.ALLOWED),
Fixtures.linkOf('blind', 'user', Fixtures.ALLOWED),
]),
).toEqual(['blind'])
})
+ test('one that reworded the same decision is named too', () => {
+ expect(
+ Hooks.rewrittenByUsers([
+ Fixtures.linkOf('reworder', 'user', Fixtures.ASKED),
+ Fixtures.linkOf('engine', 'core', Fixtures.RULE_ASK),
+ ]),
+ ).toEqual(['reworder'])
+ })
+
test('a tightening, a skipped link and links beneath theirs are not', () => {
expect(
- Hooks.loosenedByUsers([
+ Hooks.rewrittenByUsers([
Fixtures.linkOf('strict', 'user', Fixtures.PLAIN_DENY),
Fixtures.linkOf('passed-over', 'user'),
Fixtures.linkOf('suite', 'append', Fixtures.ALLOWED),
@@ -47,25 +148,33 @@ describe('held-verdict', () => {
test('a batch listed under prepend may hold a plugin of theirs', () => {
expect(
- Hooks.loosenedByUsers([
+ Hooks.rewrittenByUsers([
Fixtures.linkOf('audit+easy', 'prepend', Fixtures.ALLOWED),
Fixtures.linkOf('engine', 'core', Fixtures.RULE_DENY),
]),
).toEqual(['audit+easy'])
})
- test('the handler keeps a deny, and a verdict none of theirs made', () => {
- const pastUsers = [
- Fixtures.linkOf('easy', 'user'),
- Fixtures.linkOf('engine', 'core', Fixtures.ASKED),
- ]
-
+ test('the handler keeps a verdict none of theirs made, or tightened', () => {
expect([
- Hooks.caughtAnswer(Fixtures.RULE_DENY, [
- Fixtures.linkOf('easy', 'user', Fixtures.ALLOWED),
+ Hooks.caughtAnswer(Fixtures.PLAIN_DENY, [
+ Fixtures.linkOf('strict', 'user', Fixtures.PLAIN_DENY),
+ Fixtures.linkOf('engine', 'core', Fixtures.ASKED),
+ ]),
+ Hooks.caughtAnswer(Fixtures.ASKED, [
+ Fixtures.linkOf('easy', 'user'),
+ Fixtures.linkOf('engine', 'core', Fixtures.ASKED),
+ ]),
+ ]).toEqual([Fixtures.PLAIN_DENY, Fixtures.ASKED])
+ })
+
+ test('a deny of the rules they reworded is refused in our words', () => {
+ expect(
+ Hooks.caughtAnswer(Fixtures.PLAIN_DENY, [
+ Fixtures.linkOf('reworder', 'user', Fixtures.PLAIN_DENY),
+ Fixtures.linkOf('engine', 'core', Fixtures.RULE_DENY),
]),
- Hooks.caughtAnswer(Fixtures.ASKED, pastUsers),
- ]).toEqual([Fixtures.RULE_DENY, Fixtures.ASKED])
+ ).toEqual(Hooks.UNCHECKED_DENY)
})
test('the handler refuses a verdict they loosened, and no verdict', () => {
diff --git a/mods/sec-default/tests/register.test.ts b/mods/sec-default/tests/register.test.ts
index f30648c8..ed5d38f5 100644
--- a/mods/sec-default/tests/register.test.ts
+++ b/mods/sec-default/tests/register.test.ts
@@ -85,6 +85,59 @@ describe('register', () => {
},
)
+ test(
+ "a plugin of theirs named as an organization's server adds no tool",
+ {
+ plugins: [
+ Fixtures.registering('corp'),
+ Fixtures.registering('mine'),
+ Fixtures.registering('bundled', 'builtin'),
+ ],
+ },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.SERVER_POLICY }))
+
+ const registered = Fixtures.toolsRegistered(on)
+
+ await $.session.start(Fixtures.SESSION)
+
+ expect(registered).toEqual(['mine', 'bundled'])
+ },
+ )
+
+ test(
+ "a plugin of theirs named as a seated plugin's own server adds no tool",
+ {
+ plugins: [
+ Fixtures.registering('plugin-corp-suite-corp-jira'),
+ Fixtures.registering('mine'),
+ ],
+ },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.SEATED_SUITE }))
+
+ const registered = Fixtures.toolsRegistered(on)
+
+ await $.session.start(Fixtures.SESSION)
+
+ expect(registered).toEqual(['mine'])
+ },
+ )
+
+ test(
+ "the organization's own plugin under such a name still adds its tool",
+ { plugins: [Fixtures.registering('corp', 'append')] },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.SERVER_POLICY }))
+
+ const registered = Fixtures.toolsRegistered(on)
+
+ await $.session.start(Fixtures.SESSION)
+
+ expect(registered).toEqual(['corp'])
+ },
+ )
+
test(
'the organization tools are listed as its tiers listed them',
{ plugins: [Fixtures.relabeling, Fixtures.listing] },
@@ -101,6 +154,61 @@ describe('register', () => {
},
)
+ test(
+ "a seated plugin's own server tools are listed as its tiers listed them",
+ { plugins: [Fixtures.relabeling, Fixtures.listing] },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.SEATED_SUITE }))
+ on('tool.list', () => ({ value: [...Fixtures.SUITE_TOOLS] }))
+
+ const { text } = await $.command.run(Fixtures.TOOLS_COMMAND)
+
+ expect(text?.split('\n')).toEqual([
+ 'mcp__plugin_corp-suite_corp-jira__create_ticket: Creates a ticket.',
+ 'Bash: relabeled',
+ ])
+ },
+ )
+
+ test(
+ 'a seated plugin listed in another case has its server tools listed too',
+ { plugins: [Fixtures.relabeling, Fixtures.listing] },
+ async ($, on) => {
+ on('settings.read', () => ({
+ value: { prependPlugins: ['Corp-Suite@market'] },
+ }))
+ on('tool.list', () => ({ value: [...Fixtures.SUITE_TOOLS] }))
+
+ const { text } = await $.command.run(Fixtures.TOOLS_COMMAND)
+
+ expect(text?.split('\n')).toEqual([
+ 'mcp__plugin_corp-suite_corp-jira__create_ticket: Creates a ticket.',
+ 'Bash: relabeled',
+ ])
+ },
+ )
+
+ test(
+ 'a plugin named as one a version-pinned entry turns on adds no tool',
+ {
+ plugins: [
+ Fixtures.registering('corp-suite'),
+ Fixtures.registering('mine'),
+ ],
+ },
+ async ($, on) => {
+ on('settings.read', () => ({
+ value: { enabledPlugins: { 'corp-suite@market': ['^1.0.0'] } },
+ }))
+
+ const registered = Fixtures.toolsRegistered(on)
+
+ await $.session.start(Fixtures.SESSION)
+
+ expect(registered).toEqual(['mine'])
+ },
+ )
+
test(
'a server policy delivers itself counts as a tool policy, unlisted',
{ plugins: [Fixtures.relabeling, Fixtures.listing] },
@@ -155,6 +263,76 @@ describe('register', () => {
},
)
+ test(
+ 'what the engine attaches passes over the plugins the person installed',
+ { plugins: [Fixtures.droppingAttachments] },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.NO_ALLOWLIST }))
+ on('prompt.attachment', ($, e) => ({ text: e.text }))
+
+ expect(await $.prompt.attachment(Fixtures.HOOK_NOTE)).toEqual({
+ text: Fixtures.HOOK_NOTE.text,
+ })
+ },
+ )
+
+ test(
+ 'a row the engine injects is kept whole over the plugins they installed',
+ { plugins: [Fixtures.blankingRows] },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.NO_ALLOWLIST }))
+
+ expect(await $.session.append(Fixtures.HOOK_CONTEXT_ROW)).toMatchObject({
+ message: { content: Fixtures.HOOK_CONTEXT_ROW.message.content },
+ })
+ expect(await $.session.append(Fixtures.REMINDER_ROW)).toMatchObject({
+ message: { content: Fixtures.REMINDER_ROW.message.content },
+ })
+ },
+ )
+
+ test(
+ 'any other row is theirs to shape as before',
+ { plugins: [Fixtures.blankingRows] },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.NO_ALLOWLIST }))
+
+ expect(await $.session.append(Fixtures.PROMPT_ROW)).not.toMatchObject({
+ message: { content: Fixtures.PROMPT_ROW.message.content },
+ })
+ },
+ )
+
+ test(
+ "an organization plugin's note is not theirs to blank; their own is",
+ {
+ plugins: [
+ Fixtures.blankingRows,
+ Fixtures.noting('mine'),
+ Fixtures.noting('suite', 'append'),
+ ],
+ },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.NO_ALLOWLIST }))
+ on('session.start', ($, e) => ({ cwd: e.cwd }))
+
+ const kept: string[] = []
+
+ on('ui.log', ($, e, next) => {
+ kept.push(`${next.origin.plugin} kept ${e.text}`)
+
+ return { value: undefined }
+ })
+
+ await $.session.start(Fixtures.SESSION)
+
+ expect(kept.toSorted()).toEqual([
+ 'mine kept []',
+ 'suite kept [{"type":"text","text":"a note"}]',
+ ])
+ },
+ )
+
test(
"the system prompt's sections pass over the plugins the person installed",
{ plugins: [Fixtures.emptying, Fixtures.heading] },
@@ -507,7 +685,7 @@ describe('register', () => {
expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Fixtures.RULE_DENY)
expect(lines).toEqual([
- `transcript: ${Hooks.heldNotice('easy', 'Bash', 'Bash(echo *)')}`,
+ `transcript: ${Hooks.heldNotice('easy', 'Bash', Fixtures.RULE_DENY, 'lift')}`,
])
},
)
@@ -528,8 +706,8 @@ describe('register', () => {
expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Fixtures.RULE_DENY)
expect(lines.toSorted()).toEqual([
- `transcript: ${Hooks.heldNotice('first', 'Bash', 'Bash(echo *)')}`,
- `transcript: ${Hooks.heldNotice('second', 'Bash', 'Bash(echo *)')}`,
+ `transcript: ${Hooks.heldNotice('first', 'Bash', Fixtures.RULE_DENY, 'lift')}`,
+ `transcript: ${Hooks.heldNotice('second', 'Bash', Fixtures.RULE_DENY, 'lift')}`,
])
},
)
@@ -597,190 +775,153 @@ describe('register', () => {
)
test(
- 'an ask a plugin of the person allows, no deny rule behind it, stands',
+ 'an ask rule holds over an allow from a plugin the person installed',
{ plugins: [Fixtures.allowing('easy')] },
async ($, on) => {
on('settings.read', () => ({ value: Fixtures.MANAGED_POLICY }))
const lines = Fixtures.logged(on)
- Fixtures.checksAnswered(on, Fixtures.ASKED)
+ Fixtures.checksAnswered(on, Fixtures.RULE_ASK)
- expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Fixtures.ALLOWED)
- expect(lines).toEqual([])
+ expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Fixtures.RULE_ASK)
+
+ expect(lines).toEqual([
+ `transcript: ${Hooks.heldNotice('easy', 'Bash', Fixtures.RULE_ASK, 'lift')}`,
+ ])
},
)
test(
- 'a deny no rule decided is still theirs to answer over',
+ "a classic hook's ask holds over an allow from a plugin of the person",
{ plugins: [Fixtures.allowing('easy')] },
async ($, on) => {
on('settings.read', () => ({ value: Fixtures.MANAGED_POLICY }))
const lines = Fixtures.logged(on)
- Fixtures.checksAnswered(on, Fixtures.PLAIN_DENY)
+ Fixtures.checksAnswered(on, Fixtures.HOOK_ASK)
- expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Fixtures.ALLOWED)
- expect(lines).toEqual([])
+ expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Fixtures.HOOK_ASK)
+
+ expect(lines).toEqual([
+ `transcript: ${Hooks.heldNotice('easy', 'Bash', Fixtures.HOOK_ASK, 'lift')}`,
+ ])
},
)
test(
- 'a plugin of the person that tightens is heard, with one evaluation',
- { plugins: [Fixtures.tightening] },
+ "a classic hook's deny holds over their allow",
+ { plugins: [Fixtures.allowing('easy')] },
async ($, on) => {
- const reads = Fixtures.policyReads(on, Fixtures.MANAGED_POLICY)
- const evaluations = Fixtures.checksAnswered(on, Fixtures.ASKED)
+ on('settings.read', () => ({ value: Fixtures.MANAGED_POLICY }))
- await $.tool.check(Fixtures.CHECKED)
+ const lines = Fixtures.logged(on)
- const loaded = { reads: reads(), evaluations: evaluations() }
+ Fixtures.checksAnswered(on, Fixtures.HOOK_DENY)
- expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Fixtures.PLAIN_DENY)
+ expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Fixtures.HOOK_DENY)
- expect(
- {
- reads: reads() - loaded.reads,
- evaluations: evaluations() - loaded.evaluations,
- },
- 'once its plugins have loaded, a check reads no policy',
- ).toEqual({ reads: 0, evaluations: 1 })
+ expect(lines).toEqual([
+ `transcript: ${Hooks.heldNotice('easy', 'Bash', Fixtures.HOOK_DENY, 'lift')}`,
+ ])
},
)
test(
- "a deny rule holds when an organization's plugin listens above theirs",
- {
- plugins: [
- Fixtures.listening('audit', 'prepend'),
- Fixtures.allowing('easy'),
- ],
- },
+ "a classic hook's deny holds over their ask",
+ { plugins: [Fixtures.asking('easy')] },
async ($, on) => {
on('settings.read', () => ({ value: Fixtures.MANAGED_POLICY }))
+ Fixtures.logged(on)
+ Fixtures.checksAnswered(on, Fixtures.HOOK_DENY)
- const lines = Fixtures.logged(on)
-
- Fixtures.checksAnswered(on, Fixtures.RULE_DENY)
-
- expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Fixtures.RULE_DENY)
-
- expect(
- lines.map(line => line.includes('easy')),
- 'one line, naming the plugin of theirs, alone or in its batch',
- ).toEqual([true])
+ expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Fixtures.HOOK_DENY)
},
)
test(
- 'a plugin of the person that only listens costs no second evaluation',
- { plugins: [Fixtures.listening('listening')] },
+ 'an allow that never called next meets the ask rule all the same',
+ { plugins: [Fixtures.blindAllowing] },
async ($, on) => {
- const reads = Fixtures.policyReads(on, Fixtures.MANAGED_POLICY)
- const evaluations = Fixtures.checksAnswered(on, Fixtures.ASKED)
-
- await $.tool.check(Fixtures.CHECKED)
-
- const loaded = { reads: reads(), evaluations: evaluations() }
+ on('settings.read', () => ({ value: Fixtures.MANAGED_POLICY }))
+ Fixtures.logged(on)
- expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Fixtures.ASKED)
+ const evaluations = Fixtures.checksAnswered(on, Fixtures.RULE_ASK)
- expect(
- {
- reads: reads() - loaded.reads,
- evaluations: evaluations() - loaded.evaluations,
- },
- 'once its plugins have loaded, a check reads no policy',
- ).toEqual({ reads: 0, evaluations: 1 })
+ expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Fixtures.RULE_ASK)
+ expect(evaluations()).toBe(1)
},
)
- test('with none of their plugins the verdict passes once', async ($, on) => {
- const reads = Fixtures.policyReads(on, Fixtures.MANAGED_POLICY)
- const evaluations = Fixtures.checksAnswered(on, Fixtures.RULE_DENY)
-
- expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Fixtures.RULE_DENY)
-
- expect({ reads: reads(), evaluations: evaluations() }).toEqual({
- reads: 0,
- evaluations: 1,
- })
- })
-
test(
- 'an allow that never called next meets the deny rule all the same',
- { plugins: [Fixtures.blindAllowing] },
+ "an organization plugin's allow over an ask rule stands",
+ {
+ plugins: [
+ Fixtures.allowing('suite', 'append'),
+ Fixtures.allowing('easy'),
+ ],
+ },
async ($, on) => {
on('settings.read', () => ({ value: Fixtures.MANAGED_POLICY }))
const lines = Fixtures.logged(on)
- const evaluations = Fixtures.checksAnswered(on, Fixtures.RULE_DENY)
- expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Fixtures.RULE_DENY)
+ Fixtures.checksAnswered(on, Fixtures.RULE_ASK)
- expect({ lines, evaluations: evaluations() }).toEqual({
- lines: [
- `transcript: ${Hooks.heldNotice('blind', 'Bash', 'Bash(echo *)')}`,
- ],
- evaluations: 1,
- })
+ expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Fixtures.ALLOWED)
+ expect(lines).toEqual([])
},
)
test(
- 'a rule a plugin of the person writes into its answer is never read',
- { plugins: [Fixtures.forging] },
+ "an ask of theirs over an ask rule is the rule's ask again, whole",
+ { plugins: [Fixtures.asking('easy')] },
async ($, on) => {
on('settings.read', () => ({ value: Fixtures.MANAGED_POLICY }))
const lines = Fixtures.logged(on)
- Fixtures.checksAnswered(on, Fixtures.RULE_DENY)
+ Fixtures.checksAnswered(on, Fixtures.RULE_ASK)
- expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Fixtures.RULE_DENY)
+ expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Fixtures.RULE_ASK)
expect(lines).toEqual([
- `transcript: ${Hooks.heldNotice('forging', 'Bash', 'Bash(echo *)')}`,
+ 'transcript: ' +
+ Hooks.heldNotice('easy', 'Bash', Fixtures.RULE_ASK, 'reword'),
])
},
)
test(
- 'a plugin of the person asking about another command is left out',
- { plugins: [Fixtures.rewriting] },
+ "a deny of theirs over a deny rule is the rule's deny again, whole",
+ { plugins: [Fixtures.tightening] },
async ($, on) => {
on('settings.read', () => ({ value: Fixtures.MANAGED_POLICY }))
- Fixtures.logged(on)
-
- const asked: unknown[] = []
- on('tool.check', ($, e) => {
- asked.push(e.input)
+ const lines = Fixtures.logged(on)
- return Fixtures.RULE_DENY
- })
+ Fixtures.checksAnswered(on, Fixtures.RULE_DENY)
expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Fixtures.RULE_DENY)
- expect(
- asked,
- 'the rules were asked about the command that would run, only',
- ).toEqual([Fixtures.CHECKED.input])
+ expect(lines).toEqual([
+ 'transcript: ' +
+ Hooks.heldNotice('strict', 'Bash', Fixtures.RULE_DENY, 'reword'),
+ ])
},
)
test(
- 'managed settings may let the plugins a person installs override',
- { plugins: [Fixtures.allowing('easy')] },
+ 'an ask of theirs that says what it heard costs no second look',
+ { plugins: [Fixtures.asking('easy')] },
async ($, on) => {
- on('settings.read', () => ({ value: Fixtures.overridePolicyOf(true) }))
+ on('settings.read', () => ({ value: Fixtures.MANAGED_POLICY }))
const lines = Fixtures.logged(on)
- const evaluations = Fixtures.checksAnswered(on, Fixtures.RULE_DENY)
-
- expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Fixtures.ALLOWED)
+ const evaluations = Fixtures.checksAnswered(on, Fixtures.ASKED)
+ expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Fixtures.ASKED)
expect({ lines, evaluations: evaluations() }).toEqual({
lines: [],
evaluations: 1,
@@ -789,70 +930,1286 @@ describe('register', () => {
)
test(
- "only managed settings are asked: a person's own cannot lift a deny rule",
+ 'the option that lets them override deny rules lets them override these',
{ plugins: [Fixtures.allowing('easy')] },
async ($, on) => {
- Fixtures.policyBySource(
- on,
- Fixtures.MANAGED_POLICY,
- Fixtures.overridePolicyOf(true),
- )
+ on('settings.read', () => ({ value: Fixtures.overridePolicyOf(true) }))
- Fixtures.logged(on)
- Fixtures.checksAnswered(on, Fixtures.RULE_DENY)
+ const lines = Fixtures.logged(on)
- expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Fixtures.RULE_DENY)
+ Fixtures.checksAnswered(on, Fixtures.RULE_ASK)
+
+ expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Fixtures.ALLOWED)
+ expect(lines).toEqual([])
},
)
test(
- 'the option mistyped lifts nothing: only the literal true does',
+ "the mode's own ask, no rule or hook behind it, is theirs to allow",
{ plugins: [Fixtures.allowing('easy')] },
async ($, on) => {
- on('settings.read', () => ({ value: Fixtures.overridePolicyOf('true') }))
- Fixtures.logged(on)
+ on('settings.read', () => ({ value: Fixtures.MANAGED_POLICY }))
+
+ const lines = Fixtures.logged(on)
+
+ Fixtures.checksAnswered(on, Fixtures.ASKED)
+
+ expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Fixtures.ALLOWED)
+ expect(lines).toEqual([])
+ },
+ )
+
+ test(
+ 'a deny holds whatever decided it: it may stand before a rule or a hook',
+ { plugins: [Fixtures.allowing('easy')] },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.MANAGED_POLICY }))
+
+ const lines = Fixtures.logged(on)
+
+ Fixtures.checksAnswered(on, Fixtures.PLAIN_DENY)
+
+ expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Fixtures.PLAIN_DENY)
+
+ expect(lines).toEqual([
+ `transcript: ${Hooks.heldNotice('easy', 'Bash', Fixtures.PLAIN_DENY, 'lift')}`,
+ ])
+ },
+ )
+
+ test(
+ 'the notice is no door: a plugin of theirs never runs inside this hook',
+ { plugins: [Fixtures.sneaking] },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.MANAGED_POLICY }))
+
+ const lines = Fixtures.logged(on)
+
Fixtures.checksAnswered(on, Fixtures.RULE_DENY)
expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Fixtures.RULE_DENY)
+
+ expect(lines).toEqual([
+ 'transcript: ' +
+ Hooks.heldNotice('sneaking', 'Bash', Fixtures.RULE_DENY, 'lift'),
+ ])
},
)
test(
- 'with a policy that cannot be read the deny rule holds: fails closed',
+ 'nor is the notice theirs to drop',
+ { plugins: [Fixtures.muting] },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.MANAGED_POLICY }))
+
+ const lines = Fixtures.logged(on)
+
+ Fixtures.checksAnswered(on, Fixtures.RULE_ASK)
+
+ expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Fixtures.RULE_ASK)
+
+ expect(lines).toEqual([
+ `transcript: ${Hooks.heldNotice('muting', 'Bash', Fixtures.RULE_ASK, 'lift')}`,
+ ])
+ },
+ )
+
+ test(
+ "an organization's line is not theirs to drop; a line of their own is",
+ {
+ plugins: [
+ Fixtures.muting,
+ Fixtures.logging('mine'),
+ Fixtures.logging('bundled', 'builtin'),
+ Fixtures.logging('suite', 'append'),
+ ],
+ },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.MANAGED_POLICY }))
+ on('session.start', ($, e) => ({ cwd: e.cwd }))
+
+ const heard: string[] = []
+
+ on('ui.log', ($, e, next) => {
+ heard.push(next.origin.plugin)
+
+ return { value: undefined }
+ })
+
+ await $.session.start(Fixtures.SESSION)
+
+ expect(heard).toEqual(['suite'])
+ },
+ )
+
+ test(
+ 'each plugin is told of a kind, by the tool it answered on',
+ { plugins: [Fixtures.allowingBash, Fixtures.allowingRead] },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.MANAGED_POLICY }))
+
+ const lines = Fixtures.logged(on)
+
+ Fixtures.checksAnswered(on, Fixtures.RULE_DENY)
+
+ await $.tool.check(Fixtures.CHECKED)
+ await $.tool.check(Fixtures.CHECKED_READ)
+
+ expect(lines).toEqual([
+ `transcript: ${Hooks.heldNotice('basher', 'Bash', Fixtures.RULE_DENY, 'lift')}`,
+ `transcript: ${Hooks.heldNotice('reader', 'Read', Fixtures.RULE_DENY, 'lift')}`,
+ ])
+ },
+ )
+
+ test(
+ "an organization's appended plugin has its say in the run past theirs",
+ {
+ plugins: [Fixtures.allowing('suite', 'append'), Fixtures.blindAllowing],
+ },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.MANAGED_POLICY }))
+
+ const lines = Fixtures.logged(on)
+
+ Fixtures.checksAnswered(on, Fixtures.RULE_ASK)
+
+ expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Fixtures.ALLOWED)
+ expect(lines).toEqual([])
+ },
+ )
+
+ test(
+ 'a plugin is told once of each kind of thing that held over it',
{ plugins: [Fixtures.allowing('easy')] },
async ($, on) => {
- const stopPolicy = Fixtures.policyUntilStopped(
- on,
- Fixtures.overridePolicyOf(true),
- 'managed settings unreadable',
+ on('settings.read', () => ({ value: Fixtures.MANAGED_POLICY }))
+
+ const lines = Fixtures.logged(on)
+ const verdicts = [
+ Fixtures.RULE_DENY,
+ Fixtures.RULE_ASK,
+ Fixtures.RULE_ASK,
+ Fixtures.HOOK_ASK,
+ Fixtures.PLAIN_DENY,
+ Fixtures.RULE_DENY,
+ ]
+ const turn = Fixtures.checksAnsweredInTurn(on, verdicts)
+
+ for (const verdict of verdicts) {
+ expect(await $.tool.check(Fixtures.CHECKED)).toEqual(verdict)
+ turn()
+ }
+
+ expect(lines).toEqual(
+ [
+ Fixtures.RULE_DENY,
+ Fixtures.RULE_ASK,
+ Fixtures.HOOK_ASK,
+ Fixtures.PLAIN_DENY,
+ ].map(
+ held =>
+ `transcript: ${Hooks.heldNotice('easy', 'Bash', held, 'lift')}`,
+ ),
)
+ },
+ )
+
+ test(
+ 'a plugin of the person that tightens is heard, with one evaluation',
+ { plugins: [Fixtures.tightening] },
+ async ($, on) => {
+ const reads = Fixtures.policyReads(on, Fixtures.MANAGED_POLICY)
+ const evaluations = Fixtures.checksAnswered(on, Fixtures.ASKED)
+
+ await $.tool.check(Fixtures.CHECKED)
+
+ const loaded = { reads: reads(), evaluations: evaluations() }
+
+ expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Fixtures.PLAIN_DENY)
+
+ expect(
+ {
+ reads: reads() - loaded.reads,
+ evaluations: evaluations() - loaded.evaluations,
+ },
+ 'once its plugins have loaded, a check reads no policy',
+ ).toEqual({ reads: 0, evaluations: 1 })
+ },
+ )
+
+ test(
+ "a deny rule holds when an organization's plugin listens above theirs",
+ {
+ plugins: [
+ Fixtures.listening('audit', 'prepend'),
+ Fixtures.allowing('easy'),
+ ],
+ },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.MANAGED_POLICY }))
+
+ const lines = Fixtures.logged(on)
- Fixtures.logged(on)
Fixtures.checksAnswered(on, Fixtures.RULE_DENY)
- on('prompt.section', ($, e) => ({ text: e.text }))
- await $.prompt.section(Fixtures.MEMORY)
- stopPolicy()
+ expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Fixtures.RULE_DENY)
expect(
- await $.tool.check(Fixtures.CHECKED),
- 'the policy that read let plugins override; unread, the rule holds',
- ).toEqual(Fixtures.RULE_DENY)
+ lines.map(line => line.includes('easy')),
+ 'one line, naming the plugin of theirs, alone or in its batch',
+ ).toEqual([true])
},
)
test(
- "when the rules cannot be evaluated the call is refused: the hook's catch",
+ 'a plugin of the person that only listens costs no second evaluation',
+ { plugins: [Fixtures.listening('listening')] },
+ async ($, on) => {
+ const reads = Fixtures.policyReads(on, Fixtures.MANAGED_POLICY)
+ const evaluations = Fixtures.checksAnswered(on, Fixtures.ASKED)
+
+ await $.tool.check(Fixtures.CHECKED)
+
+ const loaded = { reads: reads(), evaluations: evaluations() }
+
+ expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Fixtures.ASKED)
+
+ expect(
+ {
+ reads: reads() - loaded.reads,
+ evaluations: evaluations() - loaded.evaluations,
+ },
+ 'once its plugins have loaded, a check reads no policy',
+ ).toEqual({ reads: 0, evaluations: 1 })
+ },
+ )
+
+ test('with none of their plugins the verdict passes once', async ($, on) => {
+ const reads = Fixtures.policyReads(on, Fixtures.MANAGED_POLICY)
+ const evaluations = Fixtures.checksAnswered(on, Fixtures.RULE_DENY)
+
+ expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Fixtures.RULE_DENY)
+
+ expect({ reads: reads(), evaluations: evaluations() }).toEqual({
+ reads: 0,
+ evaluations: 1,
+ })
+ })
+
+ test(
+ 'an allow that never called next meets the deny rule all the same',
{ plugins: [Fixtures.blindAllowing] },
async ($, on) => {
on('settings.read', () => ({ value: Fixtures.MANAGED_POLICY }))
- Fixtures.logged(on)
- on('tool.check', () => {
- throw new Error('the evaluation failed')
+ const lines = Fixtures.logged(on)
+ const evaluations = Fixtures.checksAnswered(on, Fixtures.RULE_DENY)
+
+ expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Fixtures.RULE_DENY)
+
+ expect({ lines, evaluations: evaluations() }).toEqual({
+ lines: [
+ 'transcript: ' +
+ Hooks.heldNotice('blind', 'Bash', Fixtures.RULE_DENY, 'lift'),
+ ],
+ evaluations: 1,
})
+ },
+ )
- expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Hooks.UNCHECKED_DENY)
+ test(
+ 'a rule a plugin of the person writes into its answer is never read',
+ { plugins: [Fixtures.forging] },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.MANAGED_POLICY }))
+
+ const lines = Fixtures.logged(on)
+
+ Fixtures.checksAnswered(on, Fixtures.RULE_DENY)
+
+ expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Fixtures.RULE_DENY)
+
+ expect(lines).toEqual([
+ 'transcript: ' +
+ Hooks.heldNotice('forging', 'Bash', Fixtures.RULE_DENY, 'lift'),
+ ])
},
)
+
+ test(
+ 'a plugin of the person asking about another command is left out',
+ { plugins: [Fixtures.rewriting] },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.MANAGED_POLICY }))
+ Fixtures.logged(on)
+
+ const asked: unknown[] = []
+
+ on('tool.check', ($, e) => {
+ asked.push(e.input)
+
+ return Fixtures.RULE_DENY
+ })
+
+ expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Fixtures.RULE_DENY)
+
+ expect(
+ asked,
+ 'the rules were asked about the command that would run, only',
+ ).toEqual([Fixtures.CHECKED.input])
+ },
+ )
+
+ test(
+ 'managed settings may let the plugins a person installs override',
+ { plugins: [Fixtures.allowing('easy')] },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.overridePolicyOf(true) }))
+
+ const lines = Fixtures.logged(on)
+ const evaluations = Fixtures.checksAnswered(on, Fixtures.RULE_DENY)
+
+ expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Fixtures.ALLOWED)
+
+ expect({ lines, evaluations: evaluations() }).toEqual({
+ lines: [],
+ evaluations: 1,
+ })
+ },
+ )
+
+ test(
+ "only managed settings are asked: a person's own cannot lift a deny rule",
+ { plugins: [Fixtures.allowing('easy')] },
+ async ($, on) => {
+ Fixtures.policyBySource(
+ on,
+ Fixtures.MANAGED_POLICY,
+ Fixtures.overridePolicyOf(true),
+ )
+
+ Fixtures.logged(on)
+ Fixtures.checksAnswered(on, Fixtures.RULE_DENY)
+
+ expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Fixtures.RULE_DENY)
+ },
+ )
+
+ test(
+ 'the option mistyped lifts nothing: only the literal true does',
+ { plugins: [Fixtures.allowing('easy')] },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.overridePolicyOf('true') }))
+ Fixtures.logged(on)
+ Fixtures.checksAnswered(on, Fixtures.RULE_DENY)
+
+ expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Fixtures.RULE_DENY)
+ },
+ )
+
+ test(
+ 'with a policy that cannot be read the deny rule holds: fails closed',
+ { plugins: [Fixtures.allowing('easy')] },
+ async ($, on) => {
+ const stopPolicy = Fixtures.policyUntilStopped(
+ on,
+ Fixtures.overridePolicyOf(true),
+ 'managed settings unreadable',
+ )
+
+ Fixtures.logged(on)
+ Fixtures.checksAnswered(on, Fixtures.RULE_DENY)
+ on('prompt.section', ($, e) => ({ text: e.text }))
+
+ await $.prompt.section(Fixtures.MEMORY)
+ stopPolicy()
+
+ expect(
+ await $.tool.check(Fixtures.CHECKED),
+ 'the policy that read let plugins override; unread, the rule holds',
+ ).toEqual(Fixtures.RULE_DENY)
+ },
+ )
+
+ test(
+ "when the rules cannot be evaluated the call is refused: the hook's catch",
+ { plugins: [Fixtures.blindAllowing] },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.MANAGED_POLICY }))
+ Fixtures.logged(on)
+
+ on('tool.check', () => {
+ throw new Error('the evaluation failed')
+ })
+
+ expect(await $.tool.check(Fixtures.CHECKED)).toEqual(Hooks.UNCHECKED_DENY)
+ },
+ )
+
+ test('the refusal of a pinned variable names the setting and it', () => {
+ expect(Hooks.pinnedVariableRefusal('CORP_PROXY')).toBe(
+ 'env (managed): CORP_PROXY is not for plugins outside policy to change',
+ )
+ })
+
+ test('a name managed env sets is pinned, in any case; no other is', () => {
+ expect(
+ ['CORP_PROXY', 'corp_proxy', 'Corp_Proxy', 'CORP', 'CORP_PROXY_2'].map(
+ name => Hooks.isPinnedVariable(Fixtures.PINNING_POLICY, name),
+ ),
+ ).toEqual([true, true, true, false, false])
+ })
+
+ test('whichever case managed env itself spells it in', () => {
+ expect(
+ ['CORP_PROXY', 'corp_proxy', 'CORP'].map(name =>
+ Hooks.isPinnedVariable(Fixtures.LOWER_CASE_PINNING_POLICY, name),
+ ),
+ ).toEqual([true, true, false])
+ })
+
+ test('a name managed env sets to nothing is pinned all the same', () => {
+ expect(
+ Hooks.isPinnedVariable({ env: { CORP_PROXY: '' } }, 'CORP_PROXY'),
+ ).toBe(true)
+ })
+
+ test('settings with no env pin nothing', () => {
+ expect(
+ [Fixtures.MANAGED_POLICY, {}, { env: {} }].map(policy =>
+ Hooks.isPinnedVariable(policy, 'CORP_PROXY'),
+ ),
+ ).toEqual([false, false, false])
+ })
+
+ test(
+ 'a variable managed settings pin is not for a plugin of the person to set',
+ {
+ plugins: [
+ Fixtures.settingProxy('suite', 'prepend'),
+ Fixtures.settingProxy('mine'),
+ Fixtures.settingProxy('bundled', 'builtin'),
+ ],
+ },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.PINNING_POLICY }))
+
+ const lines = Fixtures.logged(on)
+ const set = Fixtures.variablesSet(on)
+
+ await $.session.start(Fixtures.SESSION)
+
+ expect(set).toEqual(['suite CORP_PROXY=mine', 'bundled CORP_PROXY=mine'])
+ expect(lines).toHaveLength(1)
+ expect(lines[0]).toContain(Hooks.pinnedVariableRefusal('CORP_PROXY'))
+ },
+ )
+
+ test(
+ 'nor to unset',
+ { plugins: [Fixtures.unsettingProxy] },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.PINNING_POLICY }))
+
+ const set = Fixtures.variablesSet(on)
+
+ await $.session.start(Fixtures.SESSION)
+
+ expect(set).toEqual([])
+ },
+ )
+
+ test(
+ 'nor under another case, which some systems read as the same name',
+ { plugins: [Fixtures.settingLowerCase] },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.PINNING_POLICY }))
+ Fixtures.logged(on)
+
+ const set = Fixtures.variablesSet(on)
+
+ await $.session.start(Fixtures.SESSION)
+
+ expect(set).toEqual([])
+ },
+ )
+
+ test(
+ "what an organization's plugin reads is not theirs to answer",
+ {
+ plugins: [
+ Fixtures.answeringReads,
+ Fixtures.readingProxy('mine'),
+ Fixtures.readingProxy('suite', 'append'),
+ Fixtures.readingProxy('guard', 'prepend'),
+ ],
+ },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.PINNING_POLICY }))
+ on('session.start', ($, e) => ({ cwd: e.cwd }))
+ on('env.get', () => ({ value: 'as the engine holds it' }))
+
+ const lines = Fixtures.loggedBy(on)
+
+ await $.session.start(Fixtures.SESSION)
+
+ expect(lines.toSorted()).toEqual([
+ 'guard read as the engine holds it',
+ 'mine read theirs',
+ 'suite read as the engine holds it',
+ ])
+ },
+ )
+
+ test(
+ "nor to rewrite what an organization's plugin sets, pinned or not",
+ {
+ plugins: [
+ Fixtures.revaluing,
+ Fixtures.settingProxy('suite', 'append'),
+ Fixtures.settingOther('audit', 'append'),
+ Fixtures.settingOther('guard', 'prepend'),
+ ],
+ },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.PINNING_POLICY }))
+
+ const set = Fixtures.variablesSet(on)
+
+ await $.session.start(Fixtures.SESSION)
+
+ expect(set.toSorted()).toEqual([
+ 'audit OTHER=mine',
+ 'guard OTHER=mine',
+ 'suite CORP_PROXY=mine',
+ ])
+ },
+ )
+
+ test(
+ "an organization's write waits on no policy read, so none can fail it",
+ {
+ plugins: [Fixtures.revaluing, Fixtures.settingOther('audit', 'append')],
+ },
+ async ($, on) => {
+ const stopPolicy = Fixtures.policyUntilStopped(
+ on,
+ Fixtures.MANAGED_POLICY,
+ 'managed settings unreadable',
+ )
+
+ Fixtures.logged(on)
+
+ on('prompt.section', ($, e) => ({ text: e.text }))
+
+ const set = Fixtures.variablesSet(on)
+
+ await $.prompt.section(Fixtures.MEMORY)
+ stopPolicy()
+ await $.session.start(Fixtures.SESSION)
+
+ expect(set).toEqual(['audit OTHER=mine'])
+ },
+ )
+
+ test(
+ "a built-in's write of a variable nobody pins still passes their hooks",
+ {
+ plugins: [
+ Fixtures.revaluing,
+ Fixtures.settingOther('bundled', 'builtin'),
+ ],
+ },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.PINNING_POLICY }))
+
+ const set = Fixtures.variablesSet(on)
+
+ await $.session.start(Fixtures.SESSION)
+
+ expect(set).toEqual(['bundled OTHER=theirs'])
+ },
+ )
+
+ test(
+ 'the option that lets them override deny rules unpins nothing',
+ { plugins: [Fixtures.settingProxy('mine')] },
+ async ($, on) => {
+ on('settings.read', () => ({
+ value: {
+ ...Fixtures.overridePolicyOf(true),
+ ...Fixtures.PINNING_POLICY,
+ },
+ }))
+ Fixtures.logged(on)
+
+ const set = Fixtures.variablesSet(on)
+
+ await $.session.start(Fixtures.SESSION)
+
+ expect(set).toEqual([])
+ },
+ )
+
+ test(
+ 'a variable managed settings do not pin is theirs to set',
+ { plugins: [Fixtures.settingOther('mine')] },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.PINNING_POLICY }))
+
+ const set = Fixtures.variablesSet(on)
+
+ await $.session.start(Fixtures.SESSION)
+
+ expect(set).toEqual(['mine OTHER=mine'])
+ },
+ )
+
+ test(
+ "only managed settings pin: a person's own env binds no plugin",
+ { plugins: [Fixtures.settingProxy('mine')] },
+ async ($, on) => {
+ Fixtures.policyBySource(
+ on,
+ Fixtures.MANAGED_POLICY,
+ Fixtures.PINNING_POLICY,
+ )
+
+ const set = Fixtures.variablesSet(on)
+
+ await $.session.start(Fixtures.SESSION)
+
+ expect(set).toEqual(['mine CORP_PROXY=mine'])
+ },
+ )
+
+ test(
+ 'with a policy that cannot be read they set no variable: fails closed',
+ { plugins: [Fixtures.settingOther('mine')] },
+ async ($, on) => {
+ const stopPolicy = Fixtures.policyUntilStopped(
+ on,
+ Fixtures.MANAGED_POLICY,
+ 'managed settings unreadable',
+ )
+
+ Fixtures.logged(on)
+
+ on('prompt.section', ($, e) => ({ text: e.text }))
+
+ const set = Fixtures.variablesSet(on)
+
+ await $.prompt.section(Fixtures.MEMORY)
+ stopPolicy()
+ await $.session.start(Fixtures.SESSION)
+
+ expect(set).toEqual([])
+ },
+ )
+
+ test("a server's own name, and any name under its tools' prefix", () => {
+ expect(
+ ['corp', 'corp__x', 'corp__x__y', 'corp._x'].map(plugin =>
+ Hooks.namesOrgTool(Fixtures.SERVER_POLICY, plugin, 'greet'),
+ ),
+ ).toEqual([true, true, true, true])
+ })
+
+ test('a name that only begins like one is no server of theirs', () => {
+ expect(
+ ['corporate', 'corpx', 'x__corp', 'x-corp', 'mine'].map(plugin =>
+ Hooks.namesOrgTool(Fixtures.SERVER_POLICY, plugin, 'greet'),
+ ),
+ ).toEqual([false, false, false, false, false])
+ })
+
+ test('another case or other separators spell the same server', () => {
+ expect(
+ ['Corp', 'CORP', 'corp_x', 'corp-x', 'corp.x', '_corp_'].map(plugin =>
+ Hooks.namesOrgTool(Fixtures.SERVER_POLICY, plugin, 'greet'),
+ ),
+ ).toEqual([true, true, true, true, true, true])
+ })
+
+ test('a claude.ai server with a run of spaces folds as its tools do', () => {
+ expect(
+ ['mcp__claude_ai_tools__x', 'mcp__claude_ai__tools__x'].map(tool =>
+ Hooks.isOrgTool(
+ { managedMcpServers: { 'claude.ai tools': {} } },
+ tool,
+ ),
+ ),
+ ).toEqual([true, true])
+ })
+
+ test('a plugin and its tool that spell a server together count too', () => {
+ expect(
+ [
+ ['corp', 'prod__deploy'],
+ ['corp', 'deploy'],
+ ['corp_tools', 'greet'],
+ ['corp', 'tools__greet'],
+ ].map(([plugin = '', tool = '']) =>
+ Hooks.namesOrgTool(
+ { managedMcpServers: { corp__prod: {}, 'corp.tools': {} } },
+ plugin,
+ tool,
+ ),
+ ),
+ ).toEqual([true, false, true, true])
+ })
+
+ test("a seated plugin's own servers are the organization's", () => {
+ expect([
+ Hooks.namesOrgTool(
+ Fixtures.SEATED_SUITE,
+ 'plugin_corp-suite_corp-jira',
+ 'create_ticket',
+ ),
+ Hooks.namesOrgTool(Fixtures.SEATED_SUITE, 'Plugin.Corp_Suite.x', 'y'),
+ Hooks.isOrgTool(
+ Fixtures.SEATED_SUITE,
+ 'mcp__plugin_corp-suite_corp-jira__create_ticket',
+ ),
+ ]).toEqual([true, true, true])
+ })
+
+ test('a seated plugin is told in any case, as the engine seats it', () => {
+ const listed = { prependPlugins: ['Corp-Suite@market'] }
+
+ expect([
+ Hooks.isOrgTool(listed, 'mcp__plugin_corp-suite_corp-jira__x'),
+ Hooks.isOrgTool(listed, 'mcp__corp-suite__greet'),
+ Hooks.isOrgTool(Fixtures.SEATED_SUITE, 'mcp__plugin_Corp-Suite_j__x'),
+ Hooks.isOrgTool(listed, 'mcp__plugin_corp-suites_j__x'),
+ Hooks.isOrgTool(Fixtures.SERVER_POLICY, 'mcp__Corp__search'),
+ ]).toEqual([true, true, true, false, false])
+ })
+
+ test('an entry that pins versions turns its plugin on, as true does', () => {
+ const pinned = { enabledPlugins: { 'corp-suite@market': ['^1.0.0'] } }
+ const off = { enabledPlugins: { 'corp-suite@market': false } }
+
+ expect([
+ Hooks.namesOrgTool(pinned, 'corp-suite', 'greet'),
+ Hooks.isOrgTool(pinned, 'mcp__corp-suite__greet'),
+ Hooks.namesOrgTool(off, 'corp-suite', 'greet'),
+ Hooks.namesOrgTool(pinned, 'mine', 'greet'),
+ ]).toEqual([true, true, false, false])
+ })
+
+ test('a name in the other normalization form is the same name', () => {
+ const policy = { prependPlugins: ['caf\u00e9-suite@market'] }
+
+ expect([
+ Hooks.namesOrgTool(policy, 'cafe\u0301-suite', 'x'),
+ Hooks.isOrgTool(policy, 'mcp__plugin_cafe\u0301-suite_jira__x'),
+ Hooks.isOrgTool(policy, 'mcp__cafe\u0301-suite__x'),
+ ]).toEqual([true, true, true])
+ })
+
+ test('only the id managed settings turn on keeps its own name', () => {
+ const policy = {
+ enabledPlugins: { 'corp-guard@corp-market': true },
+ appendPlugins: ['corp-guard@corp-market'],
+ }
+ const asked = (id?: string) =>
+ Hooks.namesOrgTool(policy, 'corp-guard', 'x', id)
+
+ expect([
+ asked('corp-guard@corp-market'),
+ asked('Corp-Guard@Corp-Market'),
+ asked('corp-guard@inline'),
+ asked('corp-guard@elsewhere'),
+ asked('corp_guard@corp-market'),
+ asked(),
+ Hooks.namesOrgTool(
+ { ...policy, managedMcpServersUnreadable: true },
+ 'corp-guard',
+ 'x',
+ 'corp-guard@corp-market',
+ ),
+ Hooks.namesOrgTool({}, 'corp-guard', 'x', 'corp-guard@inline'),
+ ]).toEqual([false, false, true, true, true, true, true, false])
+ })
+
+ test('an accented name is told as the engine spells it in a tool', () => {
+ const composed = { prependPlugins: ['caf\u00e9-suite@market'] }
+ const decomposed = { prependPlugins: ['cafe\u0301-suite@market'] }
+
+ expect([
+ Hooks.isOrgTool(composed, 'mcp__caf_-suite__x'),
+ Hooks.isOrgTool(composed, 'mcp__cafe_-suite__x'),
+ Hooks.isOrgTool(decomposed, 'mcp__caf_-suite__x'),
+ Hooks.isOrgTool(decomposed, 'mcp__cafe_-suite__x'),
+ Hooks.isOrgTool(composed, 'mcp__plugin_caf_-suite_jira__x'),
+ Hooks.namesOrgTool(composed, 'caf.-suite', 'x'),
+ Hooks.namesOrgTool(composed, 'cafe\u0301-suite', 'x'),
+ Hooks.namesOrgTool(decomposed, 'caf\u00e9-suite', 'x'),
+ ]).toEqual([true, true, true, true, true, true, true, true])
+ })
+
+ test('a combining mark on a plain letter does not part a name', () => {
+ const decomposed = { prependPlugins: ['cafe\u0301-suite@market'] }
+
+ expect([
+ Hooks.namesOrgTool(Fixtures.SEATED_SUITE, 'corp-suite\u0301', 'x'),
+ Hooks.isOrgTool(
+ Fixtures.SEATED_SUITE,
+ 'mcp__plugin_corp-suite\u0301_jira__x',
+ ),
+ Hooks.namesOrgTool(decomposed, 'cafe\u0301-suite', 'x'),
+ Hooks.isOrgTool(decomposed, 'mcp__cafe\u0301-suite__x'),
+ ]).toEqual([true, true, true, true])
+ })
+
+ test('a name in plain letters folds exactly as before', () => {
+ expect(
+ ['Corp__Tools', 'corp-tools', 'corp.tools', 'CORP TOOLS'].map(
+ Hooks.toolPrefixOf,
+ ),
+ ).toEqual([
+ 'mcp_corp_tools_',
+ 'mcp_corp_tools_',
+ 'mcp_corp_tools_',
+ 'mcp_corp_tools_',
+ ])
+ })
+
+ test("a name unlike a seated plugin's servers is nobody else's", () => {
+ expect([
+ Hooks.namesOrgTool(Fixtures.SEATED_SUITE, 'mine', 'greet'),
+ Hooks.namesOrgTool(Fixtures.SEATED_SUITE, 'plugin_mine_jira', 'x'),
+ Hooks.namesOrgTool(Fixtures.SEATED_SUITE, 'plugin_corp-suites', 'x'),
+ Hooks.isOrgTool(Fixtures.SEATED_SUITE, 'mcp__plugin_mine_jira__x'),
+ Hooks.isOrgTool(Fixtures.SEATED_SUITE, 'mcp__plugin_corp-suites_j__x'),
+ Hooks.isOrgTool(Fixtures.SEATED_SUITE, 'mcp__mine__greet'),
+ ]).toEqual([false, false, false, false, false, false])
+ })
+
+ test('a server the allowlist names counts as one it delivers does', () => {
+ expect(
+ [Fixtures.ALLOWLIST, Fixtures.NO_ALLOWLIST, {}].map(policy =>
+ Hooks.namesOrgTool(policy, 'corp__x', 'greet'),
+ ),
+ ).toEqual([true, false, false])
+ })
+
+ test('a server named with a dot or a space owns its tools', () => {
+ expect(
+ ['mcp__corp_tools__x', 'mcp__my_wiki__x', 'mcp__corp__x'].map(tool =>
+ Hooks.isOrgTool(
+ { managedMcpServers: { 'corp.tools': {}, 'my wiki': {} } },
+ tool,
+ ),
+ ),
+ ).toEqual([true, true, false])
+ })
+
+ test("an organization's ask cap holds over a plugin's allow", () => {
+ expect(Hooks.holdsOver(Fixtures.CEILING_ASK, Fixtures.CEILING_ALLOW)).toBe(
+ true,
+ )
+ })
+
+ test('the launcher variable is pinned where policy names a launcher', () => {
+ expect(
+ [
+ 'CLAUDE_CODE_PROCESS_WRAPPER',
+ 'claude_code_process_wrapper',
+ 'CORP_PROXY',
+ ].map(name => Hooks.isPinnedVariable(Fixtures.WRAPPING_POLICY, name)),
+ ).toEqual([true, true, false])
+ })
+
+ test('a server whose name folds to nothing refuses every name', () => {
+ expect(
+ ['mine', 'corp', 'x__y'].map(plugin =>
+ Hooks.namesOrgTool(Fixtures.UNFOLDABLE_POLICY, plugin, 'greet'),
+ ),
+ ).toEqual([true, true, true])
+ })
+
+ test("a server's tools are told by its name whole, as the engine spells it", () => {
+ expect(
+ ['mcp__corp__x', 'mcp__corp-tools__x', 'mcp__Corp__x', 'mcp__--__x'].map(
+ tool =>
+ Hooks.isOrgTool({ managedMcpServers: { corp: {}, '--': {} } }, tool),
+ ),
+ ).toEqual([true, false, false, true])
+ })
+
+ test(
+ 'a compaction is not theirs to answer',
+ { plugins: [Fixtures.compacting] },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.NO_ALLOWLIST }))
+ on('session.compact', ($, e) => ({ messages: e.messages }))
+
+ expect(
+ await $.session.compact({
+ trigger: 'plugin',
+ messages: [Fixtures.COMPACTED_TURN],
+ }),
+ ).toEqual({ messages: [Fixtures.COMPACTED_TURN] })
+ },
+ )
+
+ test("a tool whose own name folds to nothing reads as the server's too", () => {
+ expect(
+ [
+ ['Corp', '-'],
+ ['Corp', '_'],
+ ['other', '-'],
+ ].map(([plugin = '', tool = '']) =>
+ Hooks.namesOrgTool({ managedMcpServers: { corp: {} } }, plugin, tool),
+ ),
+ ).toEqual([true, true, false])
+ })
+
+ test("an organization's own plugins' names are refused like its servers'", () => {
+ const policy = {
+ prependPlugins: ['corp-guard@market'],
+ appendPlugins: ['corp-audit@market', 'plain'],
+ }
+
+ expect(
+ [
+ ['Corp_Audit', 'x'],
+ ['corp.guard', 'x'],
+ ['PLAIN', 'x'],
+ ['mine', 'x'],
+ ].map(([plugin = '', tool = '']) =>
+ Hooks.namesOrgTool(policy, plugin, tool),
+ ),
+ ).toEqual([true, true, true, false])
+ expect(
+ ['mcp__corp-audit__x', 'mcp__plain__x', 'mcp__mine__x'].map(tool =>
+ Hooks.isOrgTool(policy, tool),
+ ),
+ ).toEqual([true, true, false])
+ })
+
+ test('an unreadable server file refuses every name and owns every server tool', () => {
+ const policy = { managedMcpServersUnreadable: true }
+
+ expect(Hooks.namesOrgTool(policy, 'mine', 'greet')).toBe(true)
+ expect(
+ ['mcp__any__x', 'Bash'].map(tool => Hooks.isOrgTool(policy, tool)),
+ ).toEqual([true, false])
+ expect(Hooks.isPinnedVariable(policy, 'CORP_PROXY')).toBe(false)
+ })
+
+ test(
+ "a compaction's summary is kept whole over the plugins they installed",
+ { plugins: [Fixtures.blankingRows] },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.NO_ALLOWLIST }))
+
+ expect(await $.session.append(Fixtures.COMPACTION_ROW)).toMatchObject({
+ message: { content: Fixtures.COMPACTION_ROW.message.content },
+ })
+ },
+ )
+
+ test("a plugin managed settings turn on is the organization's by name too", () => {
+ const policy = {
+ enabledPlugins: {
+ 'corp-guard@corp-market': true,
+ 'left-off@corp-market': false,
+ 'diff@builtin': true,
+ },
+ }
+
+ expect(
+ ['Corp_Guard', 'left-off', 'diff', 'mine'].map(plugin =>
+ Hooks.namesOrgTool(policy, plugin, 'x'),
+ ),
+ ).toEqual([true, false, false, false])
+ expect(
+ ['mcp__corp-guard__x', 'mcp__left-off__x'].map(tool =>
+ Hooks.isOrgTool(policy, tool),
+ ),
+ ).toEqual([true, false])
+ })
+
+ test(
+ "a skill the Skill tool hands over is kept whole; another tool's row is theirs",
+ { plugins: [Fixtures.blankingRows] },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.NO_ALLOWLIST }))
+
+ expect(await $.session.append(Fixtures.SKILL_ROW)).toMatchObject({
+ message: { content: Fixtures.SKILL_ROW.message.content },
+ })
+ expect(
+ await $.session.append(Fixtures.READ_MESSAGE_ROW),
+ ).not.toMatchObject({
+ message: { content: Fixtures.READ_MESSAGE_ROW.message.content },
+ })
+ },
+ )
+
+ test(
+ "the organization's own plugin in the user tier keeps its name",
+ {
+ plugins: [
+ Fixtures.registering('corp-guard'),
+ Fixtures.registering('mine'),
+ ],
+ },
+ async ($, on) => {
+ on('settings.read', () => ({
+ value: { enabledPlugins: { 'corp-guard@claude-plugin-test': true } },
+ }))
+
+ const registered = Fixtures.toolsRegistered(on)
+
+ await $.session.start(Fixtures.SESSION)
+
+ expect(registered).toEqual(['corp-guard', 'mine'])
+ },
+ )
+
+ test(
+ 'and keeps it when a version list turns it on',
+ {
+ plugins: [
+ Fixtures.registering('corp-guard'),
+ Fixtures.registering('mine'),
+ ],
+ },
+ async ($, on) => {
+ on('settings.read', () => ({
+ value: {
+ enabledPlugins: { 'corp-guard@claude-plugin-test': ['^1.0.0'] },
+ },
+ }))
+
+ const registered = Fixtures.toolsRegistered(on)
+
+ await $.session.start(Fixtures.SESSION)
+
+ expect(registered).toEqual(['corp-guard', 'mine'])
+ },
+ )
+
+ test(
+ 'an id in another letter case is the same id, as the engine folds one',
+ {
+ plugins: [
+ Fixtures.registering('corp-guard'),
+ Fixtures.registering('mine'),
+ ],
+ },
+ async ($, on) => {
+ on('settings.read', () => ({
+ value: { enabledPlugins: { 'Corp-Guard@Claude-Plugin-Test': true } },
+ }))
+
+ const registered = Fixtures.toolsRegistered(on)
+
+ await $.session.start(Fixtures.SESSION)
+
+ expect(registered).toEqual(['corp-guard', 'mine'])
+ },
+ )
+
+ test(
+ 'an id listed only for its place exempts nobody',
+ {
+ plugins: [
+ Fixtures.registering('corp-guard'),
+ Fixtures.registering('mine'),
+ ],
+ },
+ async ($, on) => {
+ on('settings.read', () => ({
+ value: { prependPlugins: ['corp-guard@claude-plugin-test'] },
+ }))
+
+ const registered = Fixtures.toolsRegistered(on)
+
+ await $.session.start(Fixtures.SESSION)
+
+ expect(registered).toEqual(['mine'])
+ },
+ )
+
+ test(
+ 'an id managed settings turn off exempts nobody',
+ {
+ plugins: [
+ Fixtures.registering('corp-guard'),
+ Fixtures.registering('mine'),
+ ],
+ },
+ async ($, on) => {
+ on('settings.read', () => ({
+ value: {
+ enabledPlugins: { 'corp-guard@claude-plugin-test': false },
+ appendPlugins: ['corp-guard@claude-plugin-test'],
+ },
+ }))
+
+ const registered = Fixtures.toolsRegistered(on)
+
+ await $.session.start(Fixtures.SESSION)
+
+ expect(registered).toEqual(['mine'])
+ },
+ )
+
+ test(
+ "a plugin whose name only folds to the organization's is refused",
+ {
+ plugins: [
+ Fixtures.registering('corp--guard'),
+ Fixtures.registering('mine'),
+ ],
+ },
+ async ($, on) => {
+ on('settings.read', () => ({
+ value: { enabledPlugins: { 'corp-guard@claude-plugin-test': true } },
+ }))
+
+ const registered = Fixtures.toolsRegistered(on)
+
+ await $.session.start(Fixtures.SESSION)
+
+ expect(registered).toEqual(['mine'])
+ },
+ )
+
+ test(
+ 'the plugin the engine seats as the organization keeps its own name',
+ { plugins: [Fixtures.registering('corp-guard', 'prepend')] },
+ async ($, on) => {
+ on('settings.read', () => ({
+ value: { enabledPlugins: { 'corp-guard@claude-plugin-test': true } },
+ }))
+
+ const registered = Fixtures.toolsRegistered(on)
+
+ await $.session.start(Fixtures.SESSION)
+
+ expect(registered).toEqual(['corp-guard'])
+ },
+ )
+
+ test(
+ 'a plugin of the same name from another source is refused it',
+ {
+ plugins: [
+ Fixtures.registering('corp-guard'),
+ Fixtures.registering('mine'),
+ ],
+ },
+ async ($, on) => {
+ on('settings.read', () => ({
+ value: { enabledPlugins: { 'corp-guard@corp-market': true } },
+ }))
+
+ const registered = Fixtures.toolsRegistered(on)
+
+ await $.session.start(Fixtures.SESSION)
+
+ expect(registered).toEqual(['mine'])
+ },
+ )
+
+ test(
+ 'the folder managed settings are read from is not theirs to repoint',
+ { plugins: [Fixtures.repointingSettings('mine')] },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.NO_ALLOWLIST }))
+ Fixtures.logged(on)
+
+ const set = Fixtures.variablesSet(on)
+
+ await $.session.start(Fixtures.SESSION)
+
+ expect(set).toEqual([])
+ },
+ )
+
+ test('that variable is pinned whatever managed settings hold, in any case', () => {
+ expect(
+ [
+ 'CLAUDE_CODE_MANAGED_SETTINGS_PATH',
+ 'claude_code_managed_settings_path',
+ 'CORP_PROXY',
+ ].map(name => Hooks.isPinnedVariable({}, name)),
+ ).toEqual([true, true, false])
+ })
+
+ test('a scoped id is parted at its last at-sign', () => {
+ const policy = { prependPlugins: ['@scope/corp-guard@npm'] }
+
+ expect(
+ ['scope-corp-guard', 'Scope.Corp.Guard', 'mine'].map(plugin =>
+ Hooks.namesOrgTool(policy, plugin, 'x'),
+ ),
+ ).toEqual([true, true, false])
+ expect(Hooks.isOrgTool(policy, 'mcp__scope_corp-guard__x')).toBe(true)
+ })
+
+ test('the override switch in a policy the person can write lifts nothing', () => {
+ const written = {
+ pluginConfigs: {
+ 'cc-plugin-sec-default@builtin': {
+ options: { allowModsToOverrideDenyRules: true },
+ },
+ },
+ }
+
+ expect(
+ [written, { ...written, personWritablePolicy: true }].map(policy =>
+ Hooks.denyRulesHold(policy),
+ ),
+ ).toEqual([false, true])
+ })
+
+ test('every variable that says where policy is read from is pinned', () => {
+ expect(
+ [
+ 'CLAUDE_CODE_MANAGED_SETTINGS_PATH',
+ 'CLAUDE_CODE_REMOTE_SETTINGS_PATH',
+ 'CLAUDE_CODE_DISABLE_ADMIN_ENV_UNION',
+ 'CLAUDE_CODE_MOCK_REMOTE_SETTINGS',
+ 'CLAUDE_CONFIG_DIR',
+ 'CLAUDE_SECURESTORAGE_CONFIG_DIR',
+ 'USE_LOCAL_OAUTH',
+ 'USE_STAGING_OAUTH',
+ 'CLAUDE_LOCAL_OAUTH_API_BASE',
+ ].map(name => Hooks.isPinnedVariable({}, name)),
+ ).toEqual([true, true, true, true, true, true, true, true, true])
+ })
+
+ test(
+ 'a listed id that is one at-sign refuses every registration of theirs',
+ {
+ plugins: [Fixtures.registering('mine'), Fixtures.registering('other')],
+ },
+ async ($, on) => {
+ on('settings.read', () => ({ value: { prependPlugins: ['@'] } }))
+
+ const registered = Fixtures.toolsRegistered(on)
+
+ await $.session.start(Fixtures.SESSION)
+
+ expect(registered).toEqual([])
+ },
+ )
+
+ test('a listed id with no name half protects what follows its at-sign', () => {
+ const policy = { prependPlugins: ['@market'] }
+
+ expect(
+ ['market', 'Market', 'mine'].map(plugin =>
+ Hooks.namesOrgTool(policy, plugin, 'x'),
+ ),
+ ).toEqual([true, true, false])
+ })
})
diff --git a/mods/types/claude-code.d.ts b/mods/types/claude-code.d.ts
index 757b350d..6aba39da 100644
--- a/mods/types/claude-code.d.ts
+++ b/mods/types/claude-code.d.ts
@@ -2457,6 +2457,18 @@ declare module 'claude-code' {
* const { skip } = await $.session.compact({ instructions: "the plan" })
*/
compact: EventCalls['session']['compact'];
+ /**
+ * Appends a row to a conversation of the session: the event
+ * `session.append`, the engine's own call for every row it keeps.
+ *
+ * A user-role row the person does not see as typed or a notice, of text
+ * blocks alone in this release (else refused with the reason): listed at
+ * once. `{ deny: reason }` when a plugin above refused it, nothing stored.
+ *
+ * @example
+ * await $.session.append({ message: { type: "user", content: [note] } })
+ */
+ append: (args: SessionAppendArgs) => Promise<SessionAppendResult>;
/**
* Holds the session's Anthropic credential on the host and answers an
* opaque handle and its kind; the secret never reaches the plugin.
@@ -3561,6 +3573,18 @@ declare module 'claude-code' {
* on("session.receive", { origin: "peer" }, () => ({ consumed: "muted" }))
*/
'session.receive': SessionReceiveInput;
+ /**
+ * Fires once per row a conversation of this session keeps (a prompt, a
+ * response block, a tool result, a notice), before it is stored.
+ *
+ * `next({ ...e, message })` rewrites `content`: stored and sent after. The
+ * screen, an SDK stream or Remote Control may show the row just before its
+ * rewrite; the model and the transcript file never read that form.
+ *
+ * @example
+ * on("session.append", { door: "tool-result" }, ($, e, n) => n(scrub(e)))
+ */
+ 'session.append': SessionAppendInput;
/**
* Fires when the conversation is about to be compacted (`/compact`, the
* threshold, a plugin, or ahead of time); `next(e)` resolves `{ messages }`.
@@ -3695,7 +3719,7 @@ declare module 'claude-code' {
*/
'tool.call': ToolCallResult;
/**
- * `{ decision, reason?, rule? }`.
+ * `{ decision, reason?, rule?, hook?, ceiling? }`.
*/
'tool.check': ToolCheckResult;
/**
@@ -3810,6 +3834,10 @@ declare module 'claude-code' {
* `{ text }`, or `{ consumed }`.
*/
'session.receive': SessionReceiveResult;
+ /**
+ * `{ message, uuid }`, the row as stored.
+ */
+ 'session.append': SessionAppendResult;
/**
* `{ messages, tokensBefore?, tokensAfter? }`, or `{ skip }`.
*/
@@ -3897,6 +3925,7 @@ declare module 'claude-code' {
session: {
start: (input: SessionStartInput) => Promise<SessionStartResult>;
receive: (input: SessionReceiveInput) => Promise<SessionReceiveResult>;
+ append: (input: SessionAppendInput) => Promise<SessionAppendResult>;
compact: (input?: SessionCompactArgs) => Promise<SessionCompactResult>;
attach: (input: SessionAttachInput) => Promise<SessionAttachResult>;
detach: (input: SessionDetachInput) => Promise<SessionDetachResult>;
@@ -8588,6 +8617,192 @@ declare module 'claude-code' {
kind: 'bearer' | 'api-key';
} | null;
+ /**
+ * One content block of an ApiMessage: `type` names its kind (`text`,
+ * `tool_use`, `tool_result`, `image`, `document`, `thinking`, ...).
+ *
+ * The other fields are that kind's as the Messages API defines them (see its
+ * reference); the engine hands the block over as it holds it, nothing renamed
+ * or dropped.
+ */
+ type ApiContentBlock = {
+ /**
+ * The block's kind; the rest of the block is that kind's fields.
+ */
+ type: string;
+ [field: string]: unknown;
+ };
+
+ /**
+ * `session.append`'s input as a plugin's `$.session.append(args)` takes it:
+ * the row's kind and text, and the loop it joins.
+ *
+ * Its door (`note`), origin (the calling plugin) and id are the engine's to
+ * set; a hook above, or the organization's policy plugin, may rewrite or
+ * refuse it like any call on `$`.
+ */
+ export type SessionAppendArgs = {
+ /**
+ * The row: `type: "user"` for a user-role row the person does not see as
+ * typed (the model reads it), `"system"` for a notice the model never reads.
+ *
+ * Its `content` is text blocks alone (one, for a notice): the bottom
+ * refuses any other block, and any other row type, with the reason.
+ */
+ message: {
+ type: 'user' | 'system';
+ content: ApiContentBlock[];
+ };
+ /**
+ * The running subagent whose conversation the row joins; absent for main.
+ * One that names no running loop is refused.
+ */
+ agentId?: string;
+ };
+
+ /**
+ * Which door a row came in by, decided from the row alone; a closed set,
+ * pinned on the event and the key a matcher narrows on.
+ */
+ export type SessionAppendDoor = 'prompt' | 'command' | 'response' | 'tool-result' | 'tool-message' | 'delivery' | 'attachment' | 'hook-context' | 'note' | 'compaction' | 'notice';
+
+ /**
+ * The input of `session.append`: one row being appended to a conversation of
+ * this session, by the engine site that originates it or by a plugin's call.
+ *
+ * Not on `e`, so stored as made: a tool result's structured record, the row's
+ * timestamps, parent links and provenance stamps, an attachment's payload
+ * (the model reads its recorded rendering, which `content` rewrites).
+ */
+ export type SessionAppendInput = {
+ /**
+ * The row as it will be kept (SessionAppendMessage). Its `content` is a
+ * hook's to rewrite; the engine puts back what it pins.
+ */
+ message: SessionAppendMessage;
+ /**
+ * Which door the row came in by (SessionAppendDoor); the key a matcher
+ * narrows on. Pinned.
+ */
+ door: SessionAppendDoor;
+ /**
+ * Who caused the row (SessionAppendOrigin): the person, the model, a tool,
+ * the engine, a settings hook, a plugin. Pinned.
+ */
+ origin: SessionAppendOrigin;
+ /**
+ * The row's id, the same in the transcript file and on every later read,
+ * so a hook can keep a table by row before calling `next`. Pinned.
+ */
+ uuid: string;
+ /**
+ * The loop whose conversation keeps the row: a subagent's id, as `turn.step`
+ * and `tool.call` carry it; absent on main.
+ *
+ * Pinned: a different value is refused, one left out is kept.
+ */
+ agentId?: string;
+ };
+
+ /**
+ * One row of a conversation as `session.append` hands it: how the transcript
+ * files it, under which role a request carries it, and its blocks.
+ *
+ * `{ role, content }` of a row a request carries is an ApiMessage, so code
+ * written for `$.session.messages({ as: "api" })` reads it unchanged.
+ */
+ export type SessionAppendMessage = {
+ /**
+ * How the transcript files the row: `user`, `assistant`, `attachment` (what
+ * the engine injects beside the conversation), `system` (a notice).
+ *
+ * Pinned, as `name`, `role` and `isMeta` are: left out it is kept, changed
+ * it fails the hook.
+ */
+ type: 'user' | 'assistant' | 'attachment' | 'system';
+ /**
+ * An attachment's type (`queued_command`, `nested_memory`, ...) or a
+ * notice's subtype (`compact_boundary`, `local_command`, ...). Pinned.
+ *
+ * Absent on user and assistant rows. Builds add and retire names.
+ */
+ name?: string;
+ /**
+ * Under which role a request carries the row; absent when none does (a
+ * notice, a record with no bytes on the wire, a virtual row). Pinned.
+ */
+ role?: 'user' | 'assistant';
+ /**
+ * True on a user-side row the person does not see as typed (a reminder, a
+ * nudge, a delivery's text). Pinned.
+ */
+ isMeta?: true;
+ /**
+ * The row's blocks in order (ApiContentBlock): an attachment's as the
+ * engine recorded its rendering, a notice's as one text block.
+ *
+ * Rewritable: text blocks, a tool_result's `content` and `is_error`. Media
+ * blocks may be dropped or moved, not changed or added. Thinking, tool_use,
+ * unknown kinds and every tool_result's `tool_use_id` are put back.
+ */
+ content: ApiContentBlock[];
+ };
+
+ /**
+ * Who caused a row, as the engine knows it from the row itself: a submission's
+ * sender, an injected row's author, the model, or the tool that was called.
+ */
+ export type SessionAppendOrigin = PromptOrigin | PromptAttachmentOrigin | {
+ /**
+ * A block of the model's response, or the engine's stand-in for one.
+ */
+ kind: 'model';
+ /**
+ * Whose response it is: the id the response names.
+ */
+ model: string;
+ } | {
+ /**
+ * A tool call's result, or a row a tool handed over beside it.
+ */
+ kind: 'tool';
+ /**
+ * Which one was called, by name; `unknown` when no call of that id is
+ * found.
+ */
+ tool: string;
+ };
+
+ /**
+ * What a `session.append` hook returns and what `next(e)` resolves to: the
+ * row as the session stored it, or `{ deny: reason }` for a plugin's own call.
+ *
+ * `next(e)` resolves once the row is kept. A hook relays it unchanged: one
+ * that answers without `next`, or another row, is skipped. Only a plugin's own
+ * append (door `note`) may be refused, in place of `next`: nothing is stored.
+ */
+ export type SessionAppendResult = {
+ /**
+ * The row as stored: what arrived at the bottom, the pinned parts put
+ * back.
+ */
+ message: SessionAppendMessage;
+ /**
+ * The stored row's id: the same in the transcript file and on every
+ * later read.
+ */
+ uuid: string;
+ deny?: undefined;
+ } | {
+ /**
+ * Refuses a plugin's own append, so nothing is stored: the call
+ * resolves to this, the reason the refusing hook gave.
+ */
+ deny: string;
+ message?: undefined;
+ uuid?: undefined;
+ };
+
/**
* `session.compact`'s input as a plugin's `$.session.compact(args)` takes
* it: `trigger` (`plugin`), `messages` and `agentId` are the engine's.
@@ -9943,7 +10158,7 @@ declare module 'claude-code' {
/**
* What a `tool.check` hook returns and what `next(e)` resolves to: the
- * verdict, why, and the settings rule behind it when one decided.
+ * verdict, why, and the rule, classic hook or ceiling behind it, if any.
*
* From core, the engine's declarative decision for the session's mode and
* rules. A hook may answer any verdict in either direction; the last word up
@@ -9966,6 +10181,22 @@ declare module 'claude-code' {
* Absent for a mode or a tool's own check.
*/
rule?: string;
+ /**
+ * The classic hook event that decided, or whose ask the verdict was reached
+ * under (`PreToolUse`), whoever configured the hook.
+ *
+ * Absent on a `$.tool.check` query, which runs no classic hook.
+ */
+ hook?: string;
+ /**
+ * The most permissive verdict the organization lets a call of the tool
+ * reach (`ask`), as its administrators set it on a connector's tool.
+ *
+ * The question's own (`e.ceiling`), set by the engine, from the tool, on
+ * every verdict for it, core's and each hook's alike: a hook's own
+ * `ceiling` is dropped. Absent where none is set.
+ */
+ ceiling?: ToolCheckDecision;
};
/**