> ## 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.

# Ontology views

> Declare keyed object types, their fields, links and actions.

Declare a view with `view` from `@bijectionhq/library-views`. Its identity
determines its keys and existence. Place the view in the app tree to
register its generated queries and mutations.

## Compose a Customer

A Customer exists while its CRM account is active. A billing fact gives
its legal name, and the CRM name is the fallback. The edit marker creates
a typed, erasable write home for a correction. Warehouse orders contribute
landed totals and a link to Order objects.

Start with `accounts` as the key and `name: c.name` as the only view field.
That is enough for a local `lookup({ key })`. The full example adds
Snowflake orders and a local correction. The order rows bind to `crmId`
on the local account. Callers still use the account key for Customer.

```ts customers.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { label, role, secret, t, table } from "@bijectionhq/bijection";
import { virtualTable, warehouse, type ReadBind } from "@bijectionhq/app-sql";
import { derive, edit, link, prefer, view } from "@bijectionhq/library-views";

export const sales = label();
export const rep = role({ clear: [sales] });
export const indexer = role({ clear: [sales] });
export const privacy = role({ clear: [sales], erase: [sales] });

export const accounts = table({
  crmId: t.string,
  name: t.named("customerName", t.string, { title: "Name" }),
  region: t.one("eu", "us", "apac"),
  status: t.one("active", "closed"),
}, {
  label: sales, erasable: true, unique: [["crmId"]],
  index: [["status", "region", "name"]],
});

export const billing = table({
  account: t.key(accounts), legalName: t.string,
}, { label: sales, erasable: true, unique: [["account"]] });

export const contacts = table({
  account: t.key(accounts), email: t.string, since: t.instant,
  slot: t.named("ContactSlot", t.int, { minimum: 0n, maximum: 9n }),
}, { label: sales, erasable: true, unique: [["account", "slot"]], index: [["account", "since"]] });

export const redirects = table({
  from: t.key(accounts), to: t.key(accounts),
}, { label: sales, erasable: true, unique: [["from"]], index: [["to"]] });

export const credential = secret();
export const analytics = warehouse({
  protocol: "sqlSnowflake",
  endpoint: "https://acme.snowflakecomputing.com",
  credential,
  label: sales,
  isolation: "none",
  requests: { retain: { days: 30 }, message: "Configured request-log retention for this receiver." },
});

const orderRows = analytics.relation("SALES.PUBLIC.ORDERS", {
  key: ["order"],
  subject: "customer",
  fields: {
    order: t.string, customer: t.string, state: t.string,
    placed: t.instant, amount: t.decimal,
  },
  columns: { order: "ORDER_ID", customer: "CUSTOMER_ID", state: "STATUS", placed: "PLACED", amount: "AMOUNT" },
});

export const orders = virtualTable(orderRows, {
  label: sales,
  pushdown: { point: true },
  reads: {
    recentForCustomer: {
      kind: "page", where: ["customer"],
      order: [["placed", "desc"], ["order", "desc"]], max: 50,
    },
    openByCustomer: {
      kind: "aggregate", where: ["customer"], fixed: { state: "open" },
      measures: { count: "count", amount: { sum: "amount" } },
    },
  },
  fresh: { minutes: 15 },
  lifetime: { days: 7 },
  evict: { days: 1 },
});

function recentOrdersFor(customer: ReadBind<typeof orderRows, "customer">) {
  return orders.reads.recentForCustomer({ customer });
}

export const Order = view({
  key: orders,
  title: "Order", plural: "Orders", titleField: "order",
  under: sales,
  allow: [rep],
  fields: (o) => ({ order: o.order, state: o.state, placed: o.placed, amount: o.amount }),
});
export const Customer = view({
  key: accounts.where({ status: "active" }),
  title: "Customer", plural: "Customers", titleField: "name",
  under: sales,
  allow: [rep],
  successor: (c) => redirects({ from: c.key }).pick("to"),
  erase: { allow: [privacy] },
  sources: (c) => ({
    billing: billing({ account: c.key }),
    open: orders.reads.openByCustomer({ customer: c.crmId }),
    last: recentOrdersFor(c.crmId).first(1),
    people: contacts.where({ account: c.key }).atMost(10),
  }),
  fields: (c, s) => ({
    name: c.name,
    region: c.region,
    legalName: prefer(edit({ yields: true }), s.billing.legalName, c.name),
    openOrders: s.open.count,
    openAmount: s.open.amount,
    lastOrderAt: s.last.placed,
    contacts: s.people.email,
    badge: derive(t.string, ["name", "openOrders"], (o) => `${o.name} · ${o.openOrders}`),
  }),
  describe: { legalName: "The billing name with a local correction." },
  links: (c) => ({
    orders: link(() => Order, recentOrdersFor(c.crmId)),
  }),
  serve: {
    roles: [indexer],
    find: [{ by: ["region", "name"], pick: ["name", "region", "legalName"] }],
    search: [
      { field: "name", pick: ["name", "region", "legalName"] },
      { field: "legalName", pick: ["name", "region", "legalName"] },
    ],
  },
  basis: { orders },
});

```

`count` reads a selection's cardinality. `sum` uses a declared total. A
`derive` is pure and receives its listed fields. In `prefer`, an entry
after an unwrapped derive, an identity field, a `count`, a `sum` or a list
field can never be reached, and check refuses it with `ViewField`.
`nonNull(term)` lets a present null fall through for that operand and
removes `null` from its type, so `prefer(nonNull(s.crm.phone), c.phone)`
is a `string`. Use `nonNull(derive(…))` to put a derive before other
entries. `nonNull` over a term that is never null, such as a `count`, a
list field or a column declared without `t.maybe`, is a type error, and
check refuses it with `ViewField`. `open(term)` opens a
sealed field when the audience clears it. An ordered `first(1)` source
contributes one row. An ordered `first(n)` with a larger bound contributes
a list in that order. A local `atMost(n)` contributes a complete list and
requires a unique slot constraint on the carrier. Inline lists accept up
to 64 entries. Use a link to page larger collections. On a protected
order, use a bounded `atMost(n)` list
and derive the result, use a structural order, or use a unique point.
A source-owned carrier can contribute a top-n list, a count, or a link.

The second argument to a `sources` builder names contributors in that
declaration. For example, `office: offices(reached.billing.office)`
follows the office key stored in a billing fact reached by the Customer's
key. A chain can follow up to three contributor routes. A referenced
contributor must resolve to a single fact.

## Read objects and follow links

Use `selectView` to bind a view to one SDK client and construct a selection
without making a call. `read`, `watch`, and `explain` are passive. Requesting
the selection at head admits only its required warehouse work.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { selectView } from "@bijectionhq/library-views";

const customer = selectView(client, refs.customers).byKey(customerKey);
const card = customer.pick("name", "openExposure");
const value = await card.read();
await card.request();
```

For a warehouse observation on the Customer card, use `observed` on
a reviewed aggregate in the view's `define(account)` builder. The result
carries the measures in one record with one source witness. A virtual
selection's `aggregate(measures)` and `page()` resolve the matching
reviewed read using its filters, measures or order. The same builder can
return `fields`, `links` and `actions: (self) => ({ ... })` so they can
share a warehouse binding as an ordinary local variable. To follow
contributors, return `sources: (reached) => ({ ... })` and read their
typed fields in `fields: (sources) => ({ ... })`. Pass a View to
`link(Order, route)`. Use a function for an edge whose target is declared
later.

For exact warehouse membership, set `snapshot: true` on a named PostgreSQL
page read. Its reviewed `max` bounds the complete result and can be at most
64 rows. Request the first page with `page({ size: 20 }).request()`. The
receiver reads the whole binding once. Pass the returned cursor to
the selection's `.after(cursor).read()` to serve the next page from the same
observation. Acquisition checks that every member is retained. Each page
checks that coverage still holds and opens only the member rows it returns.
Erasing any captured member invalidates the entire traversal. `explain()`
returns the source cut and the view's read version. The authenticated cursor
binds its position, caller, selection, projection, size, and both read
bases. A changed or expired observation requires a new first page. Target
fields use the first page's Bijection version with current admission and
source retention.

Use `browse({ size: 20 })` for independently acquired pages. Advance either
selection with `.after(cursor)` to retain its size and projection. For larger
exact populations, link to the indexed rows of a complete
[typed snapshot copy](https://docs.bijection.com/sql/federation.md#keep-a-typed-copy) and read the local
selection at a pinned Bijection version.

The SDK offers `page()` on links with a declared exact route. Exact and
browse cursors have separate types. The CLI uses the same coordinates.

```bash theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
bijection object read customers --key CRM-ACME --pick name,openExposure
bijection object explain customers --key CRM-ACME --link orders --mode exact --size 20
bijection object request customers --key CRM-ACME --link orders --mode exact --size 20
```

Use the returned cursor with the same mode, size and projection. Explain
reports the serving route and its basis. For a filtered page, it also
reports how many candidates the view evaluated and whether it checked
range coverage. MCP tools from `tools(Customer)` read landed answers by
default. Set `refresh: "stale"` to acquire the selected observation and
optionally wait.

When a selected field needs a key from a pending SQL lookup in the same
label, that lookup's landing can resume the admitted request after the
client disconnects. The continuation checks the requester's standing
before asking the next source. Other routes may retry within a bounded
window. Read and explain calls use the facts that have already landed.

| Leaf | Input |
| - | - |
| `lookup` | `{ key, pick?, exact? }` |
| `inspect` | `{ key, pick? }` for a passive explanation of the landed state |
| `explain` | `{ read?, key?, pick? }` for derived plans and objectives. Supply a key to include current lookup attainment. |
| `health` | `{ key, pick? }` for the key's current readiness, observation instants and objective attainment |
| `inspectLink` | `{ key, link, size?, cursor?, pick?, exact? }` for a passive explanation of a link page. Reports its observation, cut, and any available request. |
| `find` | `{ where, by?, size, cursor, pick?, behind?: false }` in a declared filter shape |
| `search` | `{ text, first, pick?, behind?: false }` for declared search fields |
| `total` | `{ where, behind?: false }` for a declared `serve.total` group or filter shape. Returns `{ count, sum, basis }` |
| A link name | `{ key, size?, cursor?, pick?, exact? }` |
| `changes` | `{ key, size, cursor, pick? }` for retained changes with their writer |
| `refresh` | `{ keys, at?, over?: { from, to } }` for external sources |
| `request` | Supply `{ key, pick? }` for fields or `{ key, link, size?, cursor?, exact? }` for a link page. At the live head it returns a `RefreshAdmissionReport`. An action refusal can supply its evidence request. |
| `successor` | `{ key }` for the live successor of a retired key |
| `erase` | `{ key }` when declared with `erase: { allow }` |

`pick` narrows field evaluation, its dependencies, and the typed result.
A literal selection gives the named fields and the key. A variable array
makes fields that may be omitted optional. `pick: []` reads only identity
and applicable provenance. A read defaults to its served pick when one is
declared, or to all view fields. Links return target objects or a page of
objects for a many link. A link's roles are the
intersection of the source and target roles. The declaration requires a
shared role for an exposed link and checks that the target label flows
to the source label. A local many link can declare `{ max: n }`.
Bijection installs a guard on the carrier that counts matching rows at
commit. For `where({ account })` with `{ max: 2 }`, the guard checks the
number of rows for that account after all the transaction's writes.
The guard must be able to read the whole group. Omit `max` to page through
a link without a declared cardinality limit.
An association can project a target's typed key with `.pick("customer")`.
A tagged union link takes the full `{ kind, key }` domain.

For an external page link, the same arguments select an observation and
request its refresh. With no size, both use 20 or the address bound, whichever
is smaller. Request the first page with no cursor. After it lands, pass its
`next` cursor with the same key, link and size to request and read the next
page. Refresh admission is separate from the page. A continuation can land at
a newer warehouse observation and carries that page's own `observed` time.
Point-in-time lookups continue to read the observations held at their version.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
await client.mutate(api.customers.request, { key, link: "orders" });
const first = await client.query(api.customers.orders, { key });
if (first.ok && first.value.state === "ready" && first.value.value.next !== null) {
  const cursor = first.value.value.next;
  await client.mutate(api.customers.request, { key, link: "orders", cursor });
  // Query or watch customers.orders with the same key and cursor.
}
```

## Read plans and objectives

Each generated lookup, find, search, total, and link query has a plan in
[bijection.lock](https://docs.bijection.com/development/cli/lock.md#view-read-plans). A local read uses
RTDB facts. Pushdown uses one reviewed receiver statement and can fuse
point routes. A key-route plan evaluates bounded joins over landed
answers. A landed non-aggregate warehouse point can supply a projected
field as the key for another non-aggregate point at a different receiver.
A Trino statement that crosses forwards has snapshot coherence only when
it uses a dated cut and every crossed forward declares travel.
A mixed plan can combine source instants. Query a published dataset
explicitly through its own handle. Generated view reads bind keys into the
reviewed routes. To change a route, update the declaration and review the
new lock before deploying it.

Declare `objectives` on a view or on a `serve` entry. `fresh` is the maximum
age of a landed observation, `volume` bounds the population, `coherence`
selects `snapshot` or `mixed`, and `history` is the required retained duration.
Use `exact: true` to require ready answers. Reads use landed answers at
their Bijection version. Branch deploy stages the reviewed plans with the
candidate Program, and branch review compares them with the installed
Program. Landing promotes the candidate and the branch's writes. Refresh
requests staged on the branch run after landing.

## Serve a view

`serve` maintains read-shaped entries in RTDB as identity and contributor
facts change. A `lookup`, `find`, `search`, or `total` entry can declare a
`pick` and `objectives`. A `find` entry adds an ordered `by` list, a
`search` entry adds a text `field`, and a `total` entry adds its `group`
and optional `sum`. The plan covers the entries of its generated read.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
serve: {
  roles: [indexer],
  objectives: { fresh: { minutes: 15 }, volume: 200 },
  lookup: { pick: ["name", "region", "credit"] },
  find: [{ by: ["region", "name"], pick: ["name", "credit"] }],
  total: [{ group: ["region"], sum: ["credit"] }],
}
```

A total sums an owned decimal or int contribution. Decimal sums take the
contributor's declared scale. `where` fixes a group prefix, so `{ region }`
and `{}` both read a `[region, segment]` group. A declared find shape
also answers a count. An undeclared shape refuses `TotalMissing`, and a
sum over a shared contribution refuses `NonAdditive`.

Find, search and total return `basis.serve` with `through` and `behind` for the
Bijection version, `observed` for the oldest observation the read evaluated,
and `unready` for objects still waiting for a landing.
`populationReady` reports whether a complete census has landed. An unavailable
filter value counts when the object could match. A direct head query can
read the maintained order, rank or count. Pass `behind: false` for exact
coverage. An exact read that encounters an unready object refuses
`SourceUnready`. Mutations and branch or versioned reads use exact
coverage. Corpus-relative scores in exact mode need current coverage.
Exact find, search and total over landed SQL sources page the current
census. They check readiness only for objects and fields that could affect
the requested result, within the host's read and transaction limits.

A served population comes from a local identity or a bounded copy of an
external identity whose virtual table declares `copy: true`. A keyed lookup
can read landed external answers without creating a population.
`volume` bounds a copy. Above the source's reviewed page bound, declare
travel so every page uses one source cut. The copy becomes visible when
all pages have landed, and every source page counts toward the budget.
`ServePopulation` names the route or bound that is missing. When the
population uses external fields, the planner derives standing requests
from its `volume` and `fresh`. It reviews their rate against the warehouse
receiver's `budget: { statements: { perHour } }`. A virtual table can
declare a smaller share with the same shape. To resolve
`FreshnessInfeasible`, increase the interval or budget, narrow the population,
or fuse routes. SQL charges the receiving place. Each private member place
has its own budget account. Lower-priority requests leave capacity for
interactive asks. An exhausted account returns `Limit` with
`BudgetExhausted` in the message.

Member-scoped contributors materialize at their member's label. Keep
each served object within one member. Erasing a contributor or closing its
lifetime or lease also closes dependent serving rows.
When the selected derivative returns `DerivativeBuilding` after a closure,
exact reads that need it refuse `SourceUnready`. Other served queries filter closed
rows and include observed omissions in `basis.serve.unready`. If the
derivative cannot supply its rows, the query reads a bounded set of
visible survivors and reports `populationReady: false`.

## Publish a relational view

`Customer.relation({ pick: ["name", "region"], cut: { coherence: "snapshot" } })`
gives a typed relation a pipeline can publish as a dataset.
Bind each local table to its mirror and each warehouse source to its
installed bulk export target, export dataset and reviewed statement digests.
Choose `coherence: "mixed"` explicitly
for a source that cannot travel. The pipeline's target supplies the engine.
[Publish a view relation](https://docs.bijection.com/transforms/pipelines.md#publish-a-view-relation)

Use a relational `derive` when a computed field must run in that engine.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
totalWithTax: derive(t.number, ["subtotal", "tax"], {
  op: "add",
  left: { op: "field", name: "subtotal" },
  right: { op: "field", name: "tax" },
})
```

Relational derive supports literals, fields, arithmetic, comparison, boolean
operations, `coalesce`, and `case`. A TypeScript callback, a cross-app object
point, or logic depending on `External` state refuses when the relation is used
as a pipeline input.

A second audience can use `Customer.under(label, { allow, sources?, fields? })`.
Inherited fields share the original write homes. A correction made through
the base view also appears in the further audience's lookup. A field
redeclared there keeps its edit, and its terms must admit the stored
value type.

A tagged union uses `view.union({ customer: Customer, supplier: Supplier }, { title })`
and keys shaped as `{ kind, key }`. Members over one table require
disjoint equality selections. A Customer key is retired while its
`redirects` fact is present: a merge writes that fact and nothing else.
A retired key answers null in lookup and leaves the serving population. Its successor leaf follows the declared redirects to a live
Customer key, up to 16 hops. It refuses a repeated key. Links leave retired
targets absent. The client can call `successor` separately.

The first request for a field can depend on an external binding that has not
landed yet. Bijection can resume that admitted request within a bounded task
window. Fusion serves eligible same-receiver point routes in one statement.

## Reviewed effects

A view action can require one observed aggregate using
`require: { openExposure: { snapshot: "source", within: { minutes: 5 } } }`.
The handler receives the plain typed aggregate and its evidence separately.
Use `reviewedMutation` when a caller must confirm a plan before it commits.
Build the plan with `reviewed.insert`, `reviewed.replace`, `reviewed.patch`,
`reviewed.delete`, or `reviewed.submit`. Place
the private receipt table alongside the application's tables. One review call
returns the ordered proposed writes and tasks and records their receipt.
Call `review.rehearse()` to exercise commit guards in a discarded world
before confirmation. Commit evaluates its guards in the deciding transaction.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { selectView } from "@bijectionhq/library-views";

const customer = selectView(client, refs.customers).byKey(customerKey);
const review = await customer.actions.approveExposure().review();
if (review.ok && await operatorConfirms(review.effects)) await review.commit();
if (!review.ok && review.requestEvidence) await review.requestEvidence();
```

The CLI returns the same proposal and receipt.

```bash theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
bijection object review customers --key CRM-ACME --action approveExposure
bijection object commit customers --key CRM-ACME --action approveExposure --receipt "$receipt"
```

An MCP server can explicitly publish the same review and commit with
`actionTools(Customer.actions.approveExposure, { review, commit })`.
The two tools take the action's business arguments. The commit tool
also takes the review receipt.

Commit checks the receipt's caller, subject, evidence, expiry, and plan in
the same transaction that writes the rows, submits tasks and consumes the
receipt. A changed row targeted by a replacement, patch or deletion requires
a new review. Target delivery settles separately.
A lost commit reply can be retried through the same receipt. An evidence
request only acquires evidence. Submit a new review after it lands.

## Edit and restore

Actions are mutations. They take `{ key, …args }` and pass the handler the
key, any declared `reads`, and fields promised by its `evidence`. The action lists the fields it edits or
retracts in `edits`. Its commit label must admit its reads and flow to
those write homes. An action that writes to a lower home lists the
applicable release in `releases`. The home admits just the actions
whose `edits` name that field. An invariant lowers to one write guard
per local table it reads, and every write guard is judged at commit on
the state the transaction leaves. An invariant can read fields from
another table, a separate edit home or another row of the identity table:
a transaction that breaks it across them refuses `Forbidden` with its
message, and one that changes several of its rows and keeps it commits.
Invariants refuse `InvariantOverSource` over external fields, source-owned
tables, another app's object point or a selection other than the
identity.

```ts actions.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { t } from "@bijectionhq/bijection";
import { Customer, rep } from "./customers";

export const correctLegalName = Customer.action(
  { allow: [rep], args: { legalName: t.maybe(t.string) }, edits: ["legalName"] },
  async (ctx, c, { legalName }) => {
    await Customer.edit(ctx, c.key, { legalName });
  },
);

export const restoreLegalName = Customer.action(
  { allow: [rep], edits: ["legalName"] },
  async (ctx, c) => {
    await Customer.retract(ctx, c.key, ["legalName"]);
  },
);

export const customers = Customer.publish({ actions: { correctLegalName, restoreLegalName } });
```

```ts app.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { app } from "@bijectionhq/bijection";
import { ontology } from "@bijectionhq/library-views";
import { customers } from "./actions";
import { accounts, analytics, billing, contacts, credential, indexer, Order,
  orders, privacy, redirects, rep, sales } from "./customers";

export default app({
  sales, rep, indexer, privacy, accounts, billing, contacts, redirects,
  credential, analytics, orders, Order, customers,
  ontology: ontology({ customers, Order }, { allow: [rep] }),
});
```

The published view mounts its named actions together. The catalog describes
actions the caller may attempt, including the argument schema, declared
refusals, field edits, and evidence. Invocation checks current authorization
and the key. A representative can correct the local name while the amount is
still unasked.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
const card = await client.query(api.customers.lookup, { key, pick: ["legalName", "openAmount"] });
await client.mutate(api.customers.actions.correctLegalName, { key, legalName: "Acme SAS" });
```

An edit of `null` is present and wins over a fallback. With
`yields: true`, the edit wins while the current fallback matches the
value recorded when the edit was made. The fallback must be ready to
record that value. A later unknown fallback supplies its unknown state,
and sealed content above the audience cannot be used for yield.
`Customer.edit` removes the earlier edit and writes a fresh one.
`Customer.retract` removes the edit so the source can decide again. The
removal is blind: it retracts the earlier row at its unique point
without reading it, so each edit carries only its own decision's units,
and erasing an earlier edit's inputs leaves the current one standing. A
removal is a closable tombstone that never refuses, so it names no
survival. An action above a lower home lists one release to that home,
which the fresh row and the removal both name. The roles in `erase.allow` can invoke
the generated `Customer.erase({ key })` mutation. It closes the erasable
identity, including a present retired identity, and its owned contributions.
It closes successor facts and walks up to 256 predecessor keys through
the successor table's indexed target field in the same transaction. A
large owned selection is erased in pages: rows past the first page are
erased by follow-up tasks whose generated mutation declares its survival
(`survives:`), so each page outlives what the eraser read. Because `Customer` declares `erase`, a direct
`ctx.erase` of an account, member erasure or expiry also erases its
owned contributions. A view without `erase` deletes nothing of its own.
An
ordinary entry guard can protect the eraser, and an authored mutation can
call it with `ctx.call`. A shared contribution can outlive the object.

An owned virtual-table route can close its warehouse dataset bucket in the
same transaction. [Forwarding the erase to the warehouse](https://docs.bijection.com/sql/application-api.md#forward-a-source-erase)
is designed, not implemented.

`changes` pages the versions at which the object's fields changed, as the
diff of successive lookups. It reads the logs of the object's points,
the carrier selections behind its counts, sums and lists, its edit homes
and the history of its external sources. External field values carry the
landed observation. Each catalog field gives `changes.depth`, the shortest
contributing history, and the view gives the minimum together with
`changes.excludes`, the fields history cannot follow. Past that depth the
call refuses `Expired` with `SourceRetention`.

## Read and refresh warehouse fields

External values are `External<V>`. A `ready` value carries `observed`.
In `prefer`, an absent row falls through. A present row with a null field
supplies the value. The other states are `unasked`, `pending`, `refused`
and `withheld`. `Order.lookup` answers
`External<ObjectOf<typeof Order> | null>`. A derive that uses an external
field uses the first applicable state in the order `withheld`,
`refused`, `unasked`, `pending`. A pending result carries the earliest
pending `since`. Its ready result carries the oldest
observation it uses.

`basis` carries each source's scope, observation time, position, freshness
and refusal. A ready `coherence: "mixed"` object carries the identity's
`observed` time. An individual input's `cut` stays on its own basis entry
or field answer. Two independently fresh observations can straddle a
transfer from balances `(100, 0)` to `(0, 100)` and report `(100, 100)`.

Use `consistent: "source"` for a virtual identity and one fused point chain
on the same PostgreSQL receiver. The inputs must be direct, schema-qualified
local heap tables using the receiver's app credential. Lookup returns
`coherence: "source"` and one opaque `cut` when every reachable point,
including an answered absence, shares the receiver-attested snapshot.
A missing or different witness refuses with `CommonCutMissing` even when
the picked fields omit that point. Refresh takes the receiver's current
snapshot in this mode.

A travelling table can instead refresh a source instant with `at`. Its
receiver must declare `skew`. The default source instant is the frame entry
instant minus that skew. For a timeline source, `over` selects a window of valid
time to land. Reads at a Bijection
version continue to see what had landed there.

Pass the same selection to `useLive` from `@bijectionhq/library-views/react`
to watch it and renew demand at head. The hook returns the current `result`,
the admission state in `request`, and a `retry` function. When
`request.state` is `reported`, the report uses the same admission outcomes
as calling `selection.request()` directly. Unmounting releases future demand.

On a cold read, show the local name and the amount's `unasked` state.
Request the selected dependencies, then watch the lookup for the landed
value. An accepted request can still be pending. Zero is a ready answer.
A ready null means that the source answered without a value for the field.
A withheld observation supplies no value. Explain without requesting work
at head or at a pinned version. The source explanation also lists the row
bound and digest from committed named-read statements when present.

```sh theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
bijection describe orders --read openByCustomer
bijection explain object customers --source --field openAmount
bijection explain object customers --key "$ACCOUNT_KEY" --field openAmount
bijection explain object customers --key "$ACCOUNT_KEY" --field openAmount --in "$VERSION"
bijection explain object customers --source --operation correctLegalName
```

An action can require count and amount from one qualified PostgreSQL
aggregate. On a PostgreSQL-backed Customer view, declare the evidence once
and give the action that declaration. The Snowflake view above can display
landed totals and has no qualified aggregate snapshot witness for this action.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
const exposure = Customer.evidence({
  sameSourceSnapshot: ["openOrders", "openAmount"], within: { minutes: 5 },
});
const approveExposure = Customer.action({ allow: [rep], evidence: exposure }, async (ctx, c) => {
  await ctx.insert(exposureApprovals, {
    customer: c.key, count: c.openOrders.value, amount: c.openAmount.value,
  });
});
```

The handler receives ready values. The mutation checks the shared witness and
the freshness deadline before the local write. An answer can be fresh enough
for display and too old to approve. Handle `SourceStale`, `CommonCutMissing`,
`ObjectUnready`, and `ObjectUnavailable` by code. A permitted recovery names
`request` and its selected fields, age limit, and whether it needs a
new cut. The caller can wait for the fresh answer before submitting again.
For fresh evidence from a single observation, see `ready(ctx, value, { within })`
from `@bijectionhq/library-sources`.

`ontology(views, { allow })` exposes the catalog to admitted roles.
`bijection describe ontology` reads the `ontology` catalog at its default
path. Pass a different path if the catalog is mounted elsewhere.
Focus on an object, field, link or action. The live catalog filters the result
under the selected caller. A link description shows how to follow it and an
action description shows how to trial and submit it.

```sh theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
bijection describe ontology --search customer
bijection describe ontology --object customers
bijection describe ontology --object customers --link orders
bijection describe ontology --object customers --action correctLegalName
bijection describe ontology --object customers --field openAmount --source --format json
bijection explain object customers --key "$ACCOUNT_KEY" --link orders --size 20
```

`--source` shows the source-derived view, field, link, action, serve and erase
records reviewed in `bijection.lock`. Focused source JSON includes named
records and an explicit `origin`. `explain object --link` reads one landed
page using the same size and cursor as the link query. Its refresh example
appears when the selected caller can request the page at the live head.

`bijection trial` shows proposed writes, queued tasks and the validity deadline.
If the action refuses and supplies a recovery, the terminal shows the refresh
and watch commands. Requesting evidence and submitting the action are explicit
calls. The submission checks the current evidence and authority.

Pass `{ allow, sets: { customerOrders } }` to publish an object-set description
too. Read it with `bijection describe ontology --set customerOrders`.

`tools(customers)` derives MCP descriptions for generated view leaves.
The `inspect` tool reads the landed state passively. Publish write tools
through an explicit named tool group. The external lookup
tool accepts `refresh: "stale" | "never"` and `wait` as a duration string.
It can hold a public streamed call for up to 20 seconds by default and
returns the observation states available when it answers. In a branch
the lookup answers without an automatic refresh or wait. A retired key
that redirects answers `{ object: null, successor }`.

To expose the eraser, add
`tools({ eraseCustomer: Customer.erase }, { eraseCustomer: "Erase a customer." })`
as a named tool group. Its descriptor carries `destructiveHint: true`.


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