> ## Documentation Index
> Fetch the complete documentation index at: https://docs.bijection.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Guards

> Refuse acts with forbid: scopes, the analyzable where: tier and the tested when: tier, per-grant decisions, the lock and the analyzer.

A guard refuses acts that positive authority would otherwise allow. It never
grants anything: a yes is a live grant of a role in the function's `allow`. Declare a guard
with `forbid(scope, { message, where })` and place it anywhere in the app
tree. The host enforces it at the act, whichever function does it.

```ts bijection/invoices.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { act, forbid, mutation, t, table } from "@bijectionhq/bijection";
import { biller, finance } from "./access";

export const invoices = table({ number: t.string, currency: t.string, amount: t.int }, {
  key: ["number"],
  label: finance,
});

export const setAmount = mutation(
  { under: finance, allow: [biller], args: { number: t.string, amount: t.int } },
  (ctx, { number, amount }) => ctx.patch(invoices(number), { amount }),
);

/** The currency never changes once an invoice exists. */
export const fixedCurrency = forbid(act.write(invoices, { transition: "update", fields: ["currency"] }), {
  message: "An invoice's currency is fixed after creation.",
  where: (a) => a.true,
});

/** No negative amounts, whoever writes them. */
export const nonnegative = forbid(act.write(invoices), {
  message: "An invoice amount cannot be negative.",
  where: (a) => a.after.amount.lessThan(0n),
});
```

A refused act fails the transaction with `Forbidden`. The refusal's `message`
is the guard's `reason`, and its `guard` is the guard's tree path
(`invoices.fixedCurrency`): the path is the guard's identity.

## Scopes

A scope names its declaration by value. Use `act.grant` to guard
`ctx.grant`, and `act.write` to guard changes to a table's facts.

| Scope | Acts it covers | Roots it adds |
| - | - | - |
| `act.write(table, { transition, fields })` | Changed facts on the table. The optional filters select a row transition and require at least one listed field to differ. | `before`, `after`, `writer` |
| `act.insert(table)`, `act.replace`, `act.patch`, `act.delete`, `act.put`, `act.retract` | Changed facts whose last staged write used that verb. They take the same optional filters as `act.write`. | `before`, `after`, `writer` |
| `act.register(family)` | Founding a member of the family. | `member` (the founded member) |
| `act.retire(family)` | Member retirement. | none |
| `act.store()` | File storage. A File's erasure is judged by `act.erase`. | `before`, `after`, `writer` |
| `act.enter(fn)` | Entering the function, from outside or by `ctx.call`. | `args` |
| `act.enter(subtree)` | Entering any function of a subtree, such as a mounted app. | none |
| `act.grant(role)`, `act.revoke(role)` | Issuing the role (including a delegation, an invitation or an issuer trust) or revoking it. | `grant` (`role`, `chain`, `to`, `under`, `scope`, `parent`, `until`) |
| `act.disclose(release)` | A disclosure through the release. | `release` |
| `act.submit(target)` | A submit to the target or function. | `target`, `args` |
| `act.answer(target)`, `act.withdraw(target)` | Settling a task of the target. | `target`, `args` |
| `act.erase()` | Any erasure. | `unit` |
| `act.branch()`, `act.land()`, `act.discard()` | The branch acts. | `branch`, `seen` |
| `act.pin()`, `act.unpin()` | The pin acts. | `version`, `until` |

Pass an array to cover several scopes with one guard,
`forbid([act.grant(hr), act.disclose(payroll)], …)`. It sees only the roots
the scopes have in common.

Write guards share one commit-time act per changed fact. Its `before`
is the committed image at the transaction's basis, and its `after` is the
final staged image. Use `act.write(table, { transition: "create" })` to
guard an absent fact becoming present, `"update"` for a present fact
changing, and `"remove"` for a present fact becoming absent. A write
followed by a patch of its new fact is still a creation. A keyed `put`
can create or update, and a retraction of a present keyed fact removes
it. Equal images and an insert followed by a deletion of the same fact
produce no write act. A `fields` filter compares only the two final
decision images, as does a guard on a machine's edge.

The staged verb still matters to verb-specific scopes. The creation
followed by a patch also matches `act.patch`. The SDK stages keyed
patches and replacements as puts, and keyed deletes as retractions.
The last staged write supplies `writer` (the function's tree path) and
the grants offered for all matching scopes, including when that write
came from a nested call.

## Roots

Every guard reads one record of the act: the same values as
[`ctx.frame`](https://docs.bijection.com/functions#the-frame), the grant being decided, and the roots
of its act. The `where:` tier describes comparisons over those values.

| Root | Example |
| - | - |
| `a.as` | `a.as.email.isNull()`; `a.as.for` is the person an agent acts for |
| `a.offer` | `a.offer.role.equals(clerk)`: the grant being decided, with its `id`, `holder`, `position` (`credential`, `actor` or `code`), `role`, role `chain`, `scope` (its member, null at installation scope), `label`, `until`, `parent` and `covers` |
| `a.holdings` | `a.holdings.has(requester)`: the roles on the live grants of the offer's holder, and for the caller also those of the person it acts for |
| `a.chain` | `a.chain.contains(principal)`: the principals on the call chain |
| `a.on` | `a.on.kind.equals("task")` |
| `a.caller` | `a.caller.equals(open)` |
| `a.now` | `a.now.lessThan(deadline)`: the host's clock |
| `a.mfaAge` | `a.mfaAge.greaterThan(600n)`: seconds since the caller's last second factor, from the verified credential, or null |
| `a.readSet` | `a.readSet.contains(place)`: the places (`<table>/<fact id>`) the transaction read before this act; not offered on `act.grant` and `act.revoke` |
| `a.after` | `a.after.amount.lessThan(0n)`: the value an act writes |

The host computes `a.now`, `a.mfaAge`, `a.holdings` and `a.readSet`; the
caller cannot supply them. `a.args` and `a.after` are chosen by the caller,
so a guard may read them only to refuse.

Field types follow the declared value types: `t.boolean` is a boolean, `t.int`
an integer, `t.string`, `t.key(table)` and `t.principal` strings, `t.instant`
an instant, `t.one(...)` of literals an enum, and `t.maybe(x)` nullable. A
field of any other type is out of the `where:` tier; read it in `when:`.

## Purpose of use

A sensitive function can declare `why` as an argument using
`purposeArgs` from `@bijectionhq/library-sensitive-data`. Apply the
library's ordinary `where:` guard to the function's entry.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { act, query, role } from "@bijectionhq/bijection";
import { purposeArgs, recordPurpose, requirePurpose } from "@bijectionhq/library-sensitive-data";

export const readCase = query({ allow: [role.signedIn], args: purposeArgs },
  (ctx, { why }) => recordPurpose(ctx, why).reference,
);

export const caseReview = requirePurpose(
  act.enter(readCase), "case-review", "Enter a case reference.",
);
```

Supply `{ why: { purpose: "case-review", reference: "CASE-42" } }` to
the call. A null or mismatched purpose returns the guard's `Forbidden`
prompt. Inside the guarded handler, call `recordPurpose(ctx, why)` before
the sensitive operation to record the evidence in Deployment History under
the run's label.

## A guard judges each offered grant

An act is offered through each live grant of each party: the caller, its
code and its credential. Every guard in scope judges each grant on its own,
with `a.offer` bound to that grant and its whole role chain. A grant some
guard refuses is removed; the act is admitted if the grants that survive
still cover it together ([how an act is decided](https://docs.bijection.com/access/decisions.md)).

* **A guard only removes grants.** Adding a guard never admits an act, and a
  guard about one role refuses only the grants of that role: it never
  removes a right another grant holds.
* `a.offer.role.equals(manager)` and `a.offer.role.oneOf([clerk, manager])`
  take role values and refuse exactly the grants of those roles.
  `a.offer.chain` includes the roles of the grants it was issued from, so a
  delegated or invited grant still answers for its origin.
* [Open entries](https://docs.bijection.com/access/decisions.md#open-entries) (`allow: [role.anyone]`,
  `allow: [role.signedIn]`) are class grants, judged like any other grant.
* A rule about the actor uses `a.as`, `a.holdings` or a fact read. An
  actor-wide rule refuses the act through every grant.
* Session-bound roles (break-glass, fresh sign-in) are short grants plus
  guards on `act.grant` and on the entry
  ([example](https://docs.bijection.com/access/grants.md#session-bound-roles)).
* When guards remove every grant that would cover the act, the refusal is
  the first grant's (by grant order) that reached a guard refusal:
  `Forbidden`, with that `guard`. With no covering grant at all it is
  `Disallowed`.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
export const largePayments = forbid(act.enter(pay), {
  message: "Payments over 10,000 go through the treasury desk.",
  where: (a) => a.args.amount.greaterThan(10_000n).and(a.offer.role.equals(treasury).not()),
});
```

A treasurer who also holds `clerk` pays through the treasury grant; the same
person acting only as a clerk is refused.

## Two tiers

| Tier | Condition | Analysis |
| - | - | - |
| `where:` | A declarative `Predicate` built from the act's terms. | Analyzable: `bijection check` reports vacuity, policy diffs and reachability. The lock prints its predicate. |
| `when:` | A TypeScript function returning `boolean` or `Promise<boolean>`. | Tested, not proved. The lock marks it `tested`. |

Give a guard exactly one of them. Prefer `where:`; use `when:` for a
condition the builder cannot state.

### The `where:` builder

| On | Methods |
| - | - |
| Every term | `.equals(x)`, `.notEquals(x)`, `.oneOf([...])` |
| Integers and instants | `.lessThan`, `.lessOrEqual`, `.greaterThan`, `.greaterOrEqual`; `.add(x)` and `.subtract(x)` with a constant, or a duration such as `{ minutes: 15 }` for an instant |
| Strings | `.startsWith(s)`, `.endsWith(s)` |
| Sets | `.contains(s)`; `a.under.contains(label)`; `.has(role)` on `a.holdings` and `a.offer.chain` |
| Nullable terms | `.isNull()`, `.isNotNull()` |
| Predicates | `.and(p)`, `.or(p)`, `.not()`, `.implies(p)`, `.ifElse(whenTrue, whenFalse)`; `a.true`, `a.false` |

There is no multiplication, no sum of two terms and no call. A `where:` that
returns a JavaScript boolean is a type error (`WhereNotTerms`): build it from
terms, `a.after.state.equals("paid")`, not `===`.

**Nulls.** A field read through null is null. Every comparison with a null
operand is false, except `.isNull()`, `.isNotNull()` and `.equals(null)`.
Use `.isNotNull()` to test presence. To make another predicate depend on
presence, use `a.before.isNotNull().ifElse(whenPresent, a.false)`.

### Read facts

Every scope offers the frame's roots: `a.as`, `a.offer`, `a.holdings`, `a.chain`, `a.mfaAge`, `a.readSet`, `a.on`, `a.now`,
`a.under` (the act's commit label, as a set of tags), `a.in` (its world,
null at the head) and `a.at` (its valid instant).

A `where:` guard reads one fact with `a.get(point)` and tests presence with
`a.has(point)`. A point is `table(key)` or `table({ uniqueFields })`, and its
key may be a term. A rule about the roles a person holds reads
`a.holdings.has(role)`, not `sys.grants`.

### Bounded arrays and deliveries

An array whose schema declares a maximum length (`t.named(…, { length: {
maximum } })`) offers `xs.every((x) => …)` and `xs.length.lessOrEqual(n)`
(and the other comparisons with an integer literal). Both unroll into one
conjunct per possible element, which counts against the guard's budget, and
the lock prints the unrolled form. An element's fields are nullable terms.
An array without a declared maximum offers neither; deploy refuses a rule
over one.

A write a claimed reply lands reads `a.delivery`: the delivered task
record, taken from the stored task, never from args. It holds `tid`,
`replyTo` (the reply function and the place it writes at), `observed`,
`start` and the delivered `rows`, bounded by the receiver's page size. On
any other act, a rule that reads `a.delivery` refuses.

### Holdings rules

To block approval by a requester, read the caller's holdings when they
enter. `a.holdings` holds the roles of the caller's live grants and, for an
agent, those of the person it acts for, so a delegate cannot approve what its
delegator could not. A requester grant committed after an earlier successful
entry makes the next entry refuse through every grant, including a
still-eligible approver grant.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
export const separateDuties = forbid(act.enter(approveExpense), {
  message: "A requester cannot approve expenses.",
  under: finance,
  where: (a) => a.holdings.has(requester),
});
```

The library rule `separationOfDuties` states the same rule per role
([library rules](#library-rules)).

A rule that reads holdings is the one kind of guard that a new grant can make
stricter, so the lock marks it `[reads holdings]`. Every `when:` guard is
marked too, since it may read them.

A guard on a fact's fact reads it the same way:

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
export const incidentOnly = forbid(act.grant(emergency), {
  message: "Emergency access needs an open incident, for at most one hour.",
  where: (a) =>
    a.get(incidents("current")).status.equals("open").not()
      .or(a.grant.until.isNull())
      .or(a.grant.until.greaterThan(a.now.add({ hours: 1 }))),
  under: oncall,
});
```

* Give every guard that reads facts an explicit `under`, including
  `under: label.public` for public facts.
* If the table can place facts above that label, the read refuses. The guard
  cannot mistake an unreadable fact for an absent one. A grant presence
  check also refuses when its role can place grants outside the lookup scope.
* The reads join the transaction's read set: a conflicting change to a fact a
  guard read invalidates the decision.
* Read a family table, series, timeline or other `sys` fact in `when:`.

### The `when:` tier

A `when:` function receives the act's roots as plain values, and the read
verbs `get`, `has` and `list` at the guard's `under`. It has no other `ctx`
verb. Use `a.list(selection.atMost(n))` to require a complete result within the stated bound.

* It runs inside the transaction it judges: at its version, as its caller,
  over the facts the transaction has written so far. At commit, that is the
  state the transaction leaves. Its reads of facts the transaction did not
  write join that transaction's read set, so a conflicting change to what it
  read invalidates the decision, as for `where:` facts.
* A write in a branch is judged in the branch: the guard reads the branch
  at the version the call entered. When the branch lands, its writes are
  judged again at head, where the land reads; a conflicting change there
  makes the land run again.
* A refused read refuses the act, even when the function catches it.
* A guard whose `under` is above the caller's label refuses without running:
  a guard never reads what its caller cannot.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
export const ownExpense = forbid(act.enter(approveExpense), {
  message: "Nobody approves an expense they filed.",
  under: finance,
  when: async (a) => (await a.get(expenses(a.args.expense)))?.filer === a.as.id,
});
```

### One transaction, several acts

A guard on a write, or on a grant, revocation, disclosure, submit or
erasure, is judged at commit against the state the transaction leaves,
with every write and grant of the transaction in it:

* two inserts that a write guard counts against a bound both count;
* a transaction that updates two facts one guard compares commits only if
  the pair it leaves passes the guard. Raising an `amount` and its `limit`
  together commits when the new `amount` is within the new `limit`.

The guard sees its own act's fact in that state too: a bound counts the
inserted fact with the others. Who may act is still decided at the
transaction's start, so a transaction gains no authority from a grant it
issues itself. A value a guard admitted before commit, such as a release
opened with `ctx.open`, is judged again at commit, which can only refuse
more.

An `act.enter` guard is judged when the call enters, over what the
transaction has written so far, and is not judged again at commit: it
decides the entry, and the writes its function then makes are its own.

Separation of duties takes two forms. "A holder of requester may not
approve" is the entry rule above, over the caller's holdings. "No one holds
requester and approver together" is enforced at issuance: `act.grant` and
`act.revoke` offer `a.grant.holdings`, the roles of the recipient's
(`a.grant.to`) live grants read at the grant's label, plus the issued
grant's own chain. Guard each role's issue with the other. Here `finance`
covers both roles' grants and flows to the label of each guarded act.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
export const requesterGrant = forbid(act.grant(requester), {
  message: "An approver cannot also hold requester.",
  under: finance,
  where: (a) => a.grant.holdings.has(approver),
});

export const approverGrant = forbid(act.grant(approver), {
  message: "A requester cannot also hold approver.",
  under: finance,
  where: (a) => a.grant.holdings.has(requester),
});
```

Both rules read the recipient's grants as the transaction leaves them, so
issuing both roles to one recipient in one transaction refuses. A failed
read refuses. The lock marks both `[reads holdings]`.

### Fail closed

A guard refuses when its predicate holds or a required read fails or exceeds
its budget. A `when:` function also refuses if it throws or returns a
non-boolean. The Boolean connectives `.and()`, `.or()`, and `.implies()`
are strict. `condition.ifElse(whenTrue, whenFalse)` evaluates the condition
first and reads only the selected branch. Deploy checks the condition and both
branches. A live evaluation can request up to 16 distinct fact points from
the condition and the branch it selects.

The condition and branch read from the same held view at the guard's
`under` label. The commit validates those reads, including an observed
absence. If the condition's read changes before ordering, the attempt must
retry and select a branch again. Adding a guard can only narrow admission
when the other decision inputs are fixed.

## Library rules

`@bijectionhq/library-policies` states the common policies as guards. Each
helper returns one guard (two for `breakGlass`) to place in the tree, judged
per offered grant like any other:

```ts bijection/policies.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { breakGlass, coverAlone, freshMfa, purposeOfUse, rate, separationOfDuties, timeWindow } from "@bijectionhq/library-policies";

export const marginAlone = coverAlone(act.enter(margin));
export const bandRate = rate(bands, { uses: 100, per: { days: 1 } });
export const caseReview = purposeOfUse(act.enter(readFile), { role: hr, purposes: ["case-review", "audit"] });
export const deskHours = timeWindow(act.enter(pay), { role: treasury, from: "08:00", to: "18:00", zone: "Europe/Paris" });
export const freshFactor = freshMfa(act.enter(readFile), { role: hr, within: { minutes: 10 } });
export const emergencyUse = breakGlass(act.enter(readFile), { role: emergency, within: { minutes: 5 } });
export const duties = separationOfDuties(act.enter(approveExpense), { holds: requester, excludes: approver });
```

| Helper | Refuses |
| - | - |
| `coverAlone(scope)` | An offered grant that does not cover the act on its own (`a.offer.covers` is false). By default the surviving grants of a party cover together. |
| `rate(release, { uses, per })` | A use of the release once it was used `uses` times within the window `per`, counted over its [disclosure records](https://docs.bijection.com/access/disclosure.md#guard-a-disclosure). |
| `purposeOfUse(scope, { role, purposes, field? })` | Acting as `role` unless the args' `field` (default `purpose`) names one of `purposes`. |
| `timeWindow(scope, { role, from, to, zone })` | Acting as `role` outside the daily window from `from` to `to` (`"HH:MM"`) in `zone`, read from the host's clock. |
| `freshMfa(scope, { role, within })` | Acting as `role` unless the caller's last second factor is at most `within` old (`a.mfaAge`, from the verified credential). |
| `breakGlass(scope, { role, within, reason? })` | Acting as the emergency `role` without a fresh second factor (`mfa`) or without a stated reason in the args' `reason` field (`reason`). Issue the role with a short `until`. |
| `separationOfDuties(scope, { holds, excludes })` | Acting as `excludes` when the caller, or the person it acts for, holds `holds`. It reads holdings, so the lock marks it `[reads holdings]`. |

The [purpose of use](#purpose-of-use) guard of
`@bijectionhq/library-sensitive-data` also records the stated purpose.

A table's `writers: () => [record, pay]` is a guard on `act.write(table)`
that refuses every write not made by one of those functions. It has no
exception: the host, operators and other functions are refused alike. An
operator correction is a mutation of the app that the table's `writers`
name.

## Guards over a mounted app

A mountable app is a function from its capabilities to `app(...)`. Its own
guards travel with it, at paths under the mount (`billing.ledgerWriters`).
The installer can add guards over the mounted app's acts, naming them by
value through the mounted subtree:

```ts bijection/app.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { act, app, forbid } from "@bijectionhq/bijection";
import billing from "@acme/billing";
import { clerk, treasury } from "./access";

const ledger = billing({ clerk });

export default app({
  billing: ledger,
  guards: {
    largePayments: forbid(act.enter(ledger.payments.pay), {
      message: "Payments over 10,000 go through the treasury desk.",
      where: (a) => a.args.amount.greaterThan(10_000n).and(a.offer.role.equals(treasury).not()),
    }),
    directLedger: forbid(act.write(ledger.ledger), {
      message: "Ledger facts change only through a submitted task.",
      where: (a) => a.on.isNull(),
    }),
    noRefunds: forbid(act.enter(ledger.refunds), {
      message: "Refunds are closed during the audit.",
      where: (a) => a.true,
    }),
  },
});
```

## The lock

`bijection check --write-lock` writes `bijection.lock` beside
`app.ts`. Each guarded path lists its guards, and each guard
has one line, sorted by path:

```text theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
path invoices.invoices table guards invoices.fixedCurrency,invoices.nonnegative
role access.biller enter{invoices.setAmount} clear{access.finance} erase{} hold{} include{} attest{} register{}
guard <path> where on <scope> [<scope> …] under <label|public> pred <canonical predicate> [reads holdings]
guard <path> when on <scope> [<scope> …] under <label|public> tested [reads holdings]
fact <name> table <table> by <id|key> pick <field> type <type>
```

A `where` line carries the guard's canonical predicate; a `when` line says
`tested`. `[reads holdings]` marks a guard that reads the caller's holdings:
every `when:` guard, and a `where:` guard whose predicate reads `a.holdings`. The `fact` lines are the reads `where:` guards make. Review the lock
diff with the source change: it is the reviewable list of everything an
installation exposes and every guard on it.

## The analyzer

`bijection check` lists every guard with its scopes, label and tier, and
under "Guard inputs" the tables each guard reads (with `GuardReadAbove` for a read
above the guard's `under`). With `cvc5` or `z3` on `PATH` it translates each
`where:` predicate and answers:

| Question | What it reports |
| - | - |
| Vacuity | A guard that can never refuse. |
| Policy diff | Against the committed lock: acts newly refused and newly allowed, each with a witness act, or that the guards are unchanged in meaning. |
| Reachability | `bijection check --prove '{"scope": …, "where": …}'`: whether an act matching the query can still be allowed. |

Each question is posed per grant: a witness is a grant of a role and an act. Facts are
unknown values, so a witness may name a value no current fact holds. Vacuity
and reachability hold even when reads fail; a policy diff compares decisions
whose reads succeed. Without a solver, `check` prints
`analysis unavailable: no SMT solver (cvc5 or z3) on PATH` and checks the
rest of the app.

## Review a guard change

1. Change the guard in source and run `bijection check`.
2. Read the policy diff: every newly refused and newly allowed act, with a
   witness. Ask `--prove` for the acts that must stay refused.
3. For a `when:` guard, test it on the real kernel with
   [`kernel(app)`](https://docs.bijection.com/development/testing): an act it refuses, one it allows, one
   outside its scope and a failing read.
4. Review each `reason`: it is the sentence the caller reads.
5. Write the lock with `--write-lock`, review its diff and commit both.

## Trial a call

`client.trial(fn, args)` runs a call in a discarded world, under the caller's
own authority, and commits nothing:

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { api } from "@bijectionhq/bijection/client";
const { result, writes, tasks } = await client.trial(api().invoices.setAmount, { number: "A-1", amount: -5n });
if (!result.ok && result.code === "Forbidden") console.log(result.guard, result.message);
```

`writes` lists the facts the call would write and `tasks` the tasks it would
submit. From the terminal, `bijection trial invoices.setAmount number=A-1 amount=-5`.
A trial's result is labelled by the join of everything it read, so it never
reveals data above the caller's clearance.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.