# URI policies (https://docs.neuralisapp.com/package-system/uri-policies)

URI policies are the platform's path-protection unit. Every file artifact lives
at a URI (`data://...`, `packages://...`, `brain://...`), and one evaluator
decides per caller and URI whether `read`, `write` and `exec` are allowed.
Packages ship baselines for their own namespace, sources persist the merged
result, and the same evaluation runs at every layer that can touch a path.

## Declaring baselines in the manifest [#declaring-baselines-in-the-manifest]

A package declares `uriPolicies` under its `neuralis` block. Patterns must stay
inside the package's **own** URI namespace, written with the literal `<self>`
placeholder:

```json
"uriPolicies": {
  "data://<self>/**": {
    "default": { "read": true, "write": true, "exec": false }
  },
  "packages://<self>/**": {
    "default": { "read": true, "write": false, "exec": false },
    "paths": [
      { "pattern": "packages://<self>/src/**", "permissions": { "read": true, "write": false } }
    ]
  }
}
```

Two prefixes are recognised: `packages://<self>/` (the package's installed
root) and `data://<self>/` (its per-project data). Anything else — a foreign
namespace, an absolute OS path, another scheme — is **rejected at manifest
load**, and the package does not register. The same check covers every nested
`paths[]` `pattern` (relative patterns without `://` are allowed), and each
top-level entry needs a complete `default: { read, write, exec }` triple.

`policies[]` is a separate, older field: `{ id, kind, config }` entries
(`safety`, `permission`, `trust`, `access`, `visibility`) the agent runtime
compiles into tool allowlists, blocklists and per-tool timeouts. It does not
touch paths.

## The permission shape [#the-permission-shape]

Every pattern maps to a hierarchical permission tree — the same
`ConnectorHierarchicalPermissions` shape [source connectors](https://docs.neuralisapp.com/package-system/connectors.md) use:

```ts
{
  default: { read: boolean, write: boolean, exec: boolean },
  byRole?:  Record<roleName, Partial<{ read, write, exec }>>,
  byUser?:  Record<userId,   Partial<{ read, write, exec }>>,
  byAgent?: Record<agentId,  Partial<{ read, write, exec }>>,
  paths?: Array<{
    pattern: string,              // glob: **, *, ?
    permissions: Partial<{ read, write, exec }>,
    priority?: number,            // the caller's role priority, n or stronger — grant rules only
    users?: string[],             // these requesters ('$owner' allowed) — grant rules only
    roles?: string[],             // these role names — a project's stored rules only
    agents?: string[],            // these agents ('$self' allowed)
    override?: boolean,           // flips deny-wins to allow-wins for this rule
    floor?: true,                 // immutable, restrict-only — see below
    except?: string[],            // floor rows of a native source declaration only — see below
  }>,
}
```

**`byRole` is resolved by role strength** (ordinal priority, lower = stronger;
scale on [roles](https://docs.neuralisapp.com/enterprise/roles.md)). The first of: an entry matching the
caller's role name; else the entry at the caller's **exact priority** (a custom
role at owner strength receives an `owner`-keyed entry); else every entry of a
role **at least as strong** contributes only its explicit denials — so a role
weaker than `viewer` inherits `viewer`'s restrictions instead of escaping them.

Evaluation resolves in a fixed order: `default` → `byRole` → `byUser` →
`byAgent` → `paths[]`, then a final pass for immutable rules. Path rules are
**deny-wins**: a later allow does not restore a denied capability. A rule with
`override: true` applies unconditionally, re-allowing too — use it sparingly,
on the narrowest pattern.

<Callout type="warn">
A pattern is matched against the whole URI, anchored at both ends. `dir/**`
matches what is **inside** `dir`, not the node `dir` itself. To deny a directory
*and* keep its name out of a listing of the parent, write both rows — `dir` and
`dir/**`. With only the `/**` half, a listing of the parent still shows the
folder name and listing the folder itself returns an empty `200` rather than a
`403`.

Matching is done on the **canonical** URI: the evaluator collapses slash runs
and resolves `.` / `..` segments in both the pattern and the URI under test, so
every spelling of one path reaches the same verdict. A trailing slash is
preserved, because `dir/**` matches `dir/` but not `dir`.

Letter case is one more spelling — on Windows and macOS `CONVERSATIONS/x`
opens `conversations/x`. A rule's **deny** bits therefore match every letter
case of its pattern, on every operating system, while its **allow** bits match
only the exact spelling, so the case of a name can never open more than the
written rule does. On Linux, where `Notes/` and `notes/` can be two folders, a
deny on one also covers the other. Other aliases a filesystem accepts — a
Windows 8.3 short name, an NTFS stream suffix such as `::$DATA`, another
Unicode normalization of a name — are refused by the server's own folder
access exactly like a path that does not exist.
</Callout>

## Naming the requester [#naming-the-requester]

A path rule names who it applies to with up to four subjects. Every subject
present on one rule must hold; to say "A or B", write two rules.

**`priority` — by strength.** `"priority": 2` matches a caller whose role
priority is n or stronger: priority 2 or stronger, where lower = stronger
(owner 1, admin 2, manager 10, member 20, viewer 30). It is the caller's role
strength, not the rule's order. A project role at admin strength under another
name passes it; a weaker role does not. The value is a whole number from 1 to
99; anything else is rejected, and a caller without a priority never matches.
`priority` is grant-only — allowed only on a rule with `override: true` and
every listed capability `true` — and never on a deny rule or an immutable rule.

**`users` — by person.** Literal user ids, or `$owner`: the user who created the
**resource** the URI addresses. The owning package tells the platform who that
is (agent-core answers it for its conversations), so the path does not have to
carry it. `users` is grant-only too; an owner the platform cannot determine
never matches, which on a grant rule only withholds the grant:

```jsonc
{ "pattern": "data://<self>/*/conversations/**", "permissions": { "read": false } },
{ "pattern": "data://<self>/$self/conversations/**", "permissions": { "read": true },
  "users": ["$owner"], "override": true }
```

**`roles` — by role name, in a project's stored rules only.** A package cannot
know a project's role names, so a **package manifest** that uses `roles` is
rejected at load; it names a subject by strength with `priority` (`2` = admin
or stronger), or by person with `users`. A project's own **stored** rules may name the project's roles in
`roles`; the names are validated against the project's roles when the rule is
written, and an unknown name is refused with a `400`. A name the stored
configuration already contains stays accepted, so a rule naming a role that
was later deleted matches nobody.

**`agents` — by agent.** Agent ids, or `$self` for the evaluating agent.

The manifest validator, the policy editor and the source routes all reject a
grant-only subject on any other shape, and the evaluator ignores such a row if
one is ever stored. Existing installs that stored grant rules naming
`roles: ["owner", "admin"]` move to `priority` with one offline upgrade step on a
stopped app (`neuralis upgrade --apply`; an updated install refuses to start
until it has run): a grant rule naming only those built-in roles takes the
weakest one's priority (`2` when admin is named, `1` for owner alone); rules naming a project's own role, and
every rule that is not a grant rule, keep their `roles` unchanged, and a second
run writes nothing.

## Immutable rules [#immutable-floors]

A normal rule, even a denial, can later be edited or overridden by an owner or
admin. For protection that **cannot be edited away at all**, a package manifest
marks a rule `floor: true`. Such a rule is deliberately narrow:

- It may carry **only** `false` capabilities. One that tries to *grant*
  anything, or pairs the marker with `override`, `roles`, `agents`, `users` or
  `priority`, is rejected at manifest load.
- It is applied in a **separate, final pass**, so no `override: true` or admin
  edit can re-enable what it took away.
- Its provenance is **trusted package manifests only**. The policy editor and the
  source routes reject any caller-supplied marker and refuse to remove or alter
  an existing one (a stable `409` / `immutable_policy_floor` error).
- It governs the **vector index** as well as reads: a path whose immutable rule
  denies `read` is never newly embedded, so one declaration protects both axes.
  Only `read` matters there — a rule that denies just `write` leaves the file
  searchable.
- It may list `except`, the paths it does **not** clear — only on a native
  package's source declaration whose root is a platform folder token. Each entry
  is `$source://` followed by literal or whole-`*` segments, with an optional
  final `/**` (the subtree) or `/` (exactly the folder itself); the floor's own
  pattern must be relative to `$source`. Anything else is rejected at manifest
  load, and so is `except` in `uriPolicies`, on a connector's rows or on a rule
  that is not a floor. An exception matches its **exact spelling**: the floor
  matches every letter-case variant of a path, so a case variant of an excepted
  path stays denied.

A trusted manifest declares one in `uriPolicies` (its own `data://` and
`packages://` namespaces) or, for a connector that owns a different URI scheme,
in the connector kind's `defaultPermissions.paths`. Connector rows marked
`floor: true` are copied into a source config when the source is attached, and
the boot reconcile applies them to existing sources; the connector's ordinary
rows stay a display baseline. Shipped examples: machine-core's browser-profile
and dotfile-credential denials ([machine sources](https://docs.neuralisapp.com/machine-core/sources.md)), and
agent-core's conversation transcripts, writable only by their managing service
while other files in the namespace stay editable.

Three tokens are substituted into path patterns at evaluation time: `$self`
(the evaluating agent's id), `$creator` (the user who created the **source**) and
`$source` (the source slug). `data://<self>/$self/**` gives each agent a private
subtree. A token is substituted only when its value is a single, literal path
segment; missing, containing `/`, or exactly `.` or `..`, the rule **matches
nothing**, so path structure can never re-aim a confining rule. Skipping is safe
both ways: a grant falls back to the source `default`, and an immutable rule can
only remove a capability.

## From manifest baseline to persisted policy [#from-manifest-baseline-to-persisted-policy]

At bootstrap the loader substitutes `<self>` with each package's slug and
aggregates every loaded package's policies. When a source is first attached,
the filesystem layer unions the matching baselines into the source's persisted
configuration. A baseline is keyed by its **pattern**, and its `default` block
becomes a path rule on that pattern — not the source's default — so N packages
each restricting their own subtree never compound into a restriction on the
whole source.

**From then on the persisted source config is authoritative** — a holder of
`sources.policy` (or a device's owner, on a folder on that device) edits the
rules in the source UI or through the policy routes; the baseline is only a
seed. A brain-core skill reads and patches them conversationally
([brain-core skills](https://docs.neuralisapp.com/brain-core/skills.md)), every successful edit leaves one
`source.config.write` audit row, and *Check access* answers why a path is open
or closed ([brain-core URI policies](https://docs.neuralisapp.com/brain-core/uri-policies.md)).

## Four enforcement layers, one evaluator [#four-enforcement-layers-one-evaluator]

The same evaluator (`evaluateUriPolicy` / `assertUriCapability` from
`@neuralis/package-system`) runs with identical semantics at every layer:

1. **Route** — package route handlers assert the capability before calling
   filesystem services.
2. **UI** — the rule editor edits the stored rules and evaluates nothing;
   *Check access* asks the server, which runs the evaluator. The server
   re-verifies on every route and never trusts the client copy.
3. **Index** — before the sync pipeline embeds a path it evaluates the persisted
   immutable rules alone, `read` only. They are role-independent, so this layer
   needs no caller; a per-role deny is filtered per caller at query time.
4. **Tool** — the `fs_*` tools, the terminal working directory, and the
   sandboxed `execute` shell. The shell gate requires `exec` on the working
   directory itself, judged as a folder (a rule on `X/**` also covers a
   working directory of `X`), evaluates absolute path tokens (and cwd-resolved
   relative writes) against the owning source's policy, and **fails closed**
   without a policy. `exec` decides where a command starts, not what it runs:
   a command started in an allowed folder can run a script it can read from
   another folder, so a folder is sealed by denying `read` there too. Only `server.unconfined` holders bypass it, and only for
   container commands; a device-plane command stays confined and clamped by an
   operator-owned allowlist, never relaxed by a feature. Details: [security](https://docs.neuralisapp.com/enterprise/security.md).

Filesystem **connectors are deliberately not a layer**: a connector is a
scheme's raw transport, policy is enforced above it — so cross-package access
goes through a typed `getPackageApi()` adapter onto a gated service, never a
connector.

A denied capability surfaces as a structured `UriPolicyDeniedError` (`uri`,
`capability`, `code: 'uri_policy_denied'`) — routes map it to HTTP 403 and tools
render a policy-denied result without leaking internal detail.

<Callout type="info" title="Policy and the enabled toggle are orthogonal">
URI policy answers "which URIs may this caller touch". The source
enabled/disabled toggle answers "is this source live at all". A disabled source
returns `code: 'source_disabled'` from filesystem tools whatever the policy says.
</Callout>

## Evaluator API [#evaluator-api]

| Export | Purpose |
| --- | --- |
| `evaluateUriPolicy(config, uri, ctx)` | Resolve effective `{ read, write, exec }` for a URI |
| `assertUriCapability(config, uri, capability, ctx)` | Throw `UriPolicyDeniedError` when denied |
| `evaluateSourceLevelUriPolicy(config, ctx)` | Source-level resolution without path rules |
| `validateManifestUriPolicies(policies, packageId)` | The load-time checks: foreign namespace, `roles` in a manifest, a `priority` that is not a whole number from 1 to 99 |
| `resolveSelfPlaceholders(policies, slug)` | Substitute `<self>` against a package slug |
| `pickManifestBaselinesForSource(policies, scheme)` | Select and pattern-scope the baselines for a `data` or `packages` source |
| `mergeBaselines(baselines)` | AND-merge defaults, union paths (source seeding) |
| `pickConnectorFloorRules(defaultPermissions)` | The immutable rows a connector declares on its own kind |
| `containsPolicyFloorMarker(permissions)` | Whether a payload carries the `floor` key at all |
| `validatePolicyFloorRule(rule)` / `validatePolicyUsersRule(rule)` / `validatePolicyAtLeastRule(rule)` | Authoring errors for one rule's marker or subject |
| `assertImmutablePolicyFloorsPreserved(existing, proposed)` | Immutable rows must round-trip a full replacement unchanged |
| `reconcileImmutablePolicyFloors(current, trustedBaselines)` | Boot-time re-derivation from the trusted manifests |
| `applyTrustedSourceBaselines(input)` | Hold one source config to its trusted baselines, before it is first written and at boot |
| `stripPolicyFloorMarkers(policies)` | Drop markers from a non-trusted package's baselines |
| `resolvePolicyPatternTokens(pattern, ctx)` | Substitute `$self` / `$creator` / `$source`; `null` when unsafe |
| `registerResourceOwnerResolver(resolver)` / `resolveResourceOwner({ projectId, uri })` | Who created the resource a URI addresses, for `$owner` |
| `normalizePolicyUri(value)` / `globToRegExp(pattern)` | Canonicalization and anchored glob compilation |
| `UriPolicyDeniedError` · `ImmutablePolicyFloorError` · `CallerPolicyFloorError` | Denied capability · malformed or altered immutable rule · caller-supplied marker |

The evaluation context (`UriPolicyContext`) carries `userId`, `role`, the
caller's `priority` and the project's role priorities, `agentId`, the optional
`source` / `creatorUserId` for token substitution, and the optional
`resourceOwnerUserId` behind `$owner` — all derived from the verified
[session](https://docs.neuralisapp.com/package-system/sessions.md), never from caller input.