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

# Test on the real kernel

> Install an app in memory, seed fixtures, call declared functions as a principal, and advance the clock.

`kernel(app, { now })` from `@bijectionhq/bijection/test` installs your app on
the real kernel, in memory. The kernel admits each call (exposure, `allow`,
clearance and `act.enter` guards), runs the handler, judges its writes against
the guards at commit, and commits or refuses the transaction, exactly as a
deployment does.

Install [Vitest](https://vitest.dev/) in a project that already uses the
[Bijection SDK](https://docs.bijection.com/start/install.md):

```sh theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
npm install --save-dev vitest
```

Configure Vitest with the SDK's preset:

```ts vitest.config.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { defineConfig } from "vitest/config";
import { vitestPreset } from "@bijectionhq/bijection/test";

export default defineConfig(vitestPreset());
```

The preset installs a Vite plugin that records the module each app is
declared in (see [the app module](#the-app-module)), and runs the test
workers with Node's vm modules and, on a Node without Temporal,
`--harmony-temporal`. Add your own options with `mergeConfig`:

```ts vitest.config.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { defineConfig, mergeConfig } from "vitest/config";
import { vitestPreset } from "@bijectionhq/bijection/test";

export default mergeConfig(vitestPreset(), defineConfig({ test: { include: ["tests/**/*.test.ts"] } }));
```

## The app module

The kernel runs your handlers the way a deployment does: in a fresh guest
context per call, with the same deterministic globals (the frame's clock for
`Date` and `Temporal.Now`, seeded `Math.random` and `crypto`, the guest
console, no timers or `fetch`). It loads them from the module that declares
the app, as a deployment loads `app`. So pass `kernel` an app
that is the default export of its own module, declared at that module's top
level:

```ts fixtures/notes.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { app, mutation, query, role, t, table } from "@bijectionhq/bijection";

const notes = table({ text: t.string });
const add = mutation({ args: { text: t.string }, allow: [role.signedIn] }, (ctx, { text }) => ctx.insert(notes, { text }));
const list = query({ allow: [role.anyone] }, (ctx) => ctx.list(notes.first(100)));

export default app({ notes, add, list });
```

```ts notes.test.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { kernel } from "@bijectionhq/bijection/test";
import notes from "./fixtures/notes";

const k = kernel(notes);
```

The preset's plugin finds the module when Vitest transforms it: each
`app(…)` call written at a module's top level, outside every function and
class body, with `app` imported from `@bijectionhq/bijection`, is rewritten
to pass its module's `import.meta.url` to `app()`. Nothing is read from stack
traces, so the module is the same under every runner configuration and
source map.

`kernel` refuses an app it has no module for, with a `TypeError` that names
the fix:

* An app built inside a test, or inside a function, has no module. Move it to
  a fixture module's default export, as above.
* Without the preset, Vitest does not record the module. Add
  `vitestPreset()` to `vitest.config.ts`.

The module runs in the guest, so it imports no Node.js built-in (`node:fs`,
`node:crypto` and the like). It imports no `vitest` either: keep test code
in the test file.

### Outside Vitest

`kernel` runs under Vitest only. The app's module is a fact the preset's
plugin records at transform time, and only a transform pipeline knows it.
Under `node --test`, Bun or Deno no plugin runs, and `kernel(app)` refuses
with a `TypeError` that says to run the test under Vitest with the preset.
Tests that call no `kernel`, such as pure functions an app imports, run under
any runner.

## A first test

The kernel's tables and functions come from the app tree. This test uses the
notes app of the [default starter](https://docs.bijection.com/start/quickstart.md).

```ts tests/notes.test.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { api } from "@bijectionhq/bijection/client";
import { expect, test } from "vitest";
import { kernel } from "@bijectionhq/bijection/test";
import app from "../bijection/app";

test("lists the newest note first", async () => {
  const k = kernel(app, { now: Temporal.Instant.from("2026-01-01T00:00:00Z") });
  const alice = k.as("person:alice");

  await alice.mutate(api(app).notes.add, { text: "first" });
  await k.advance({ seconds: 1 });
  await alice.mutate(api(app).notes.add, { text: "second" });

  const listed = await alice.query(api(app).notes.recentNotes, {});
  expect(listed.ok && listed.value.map((note) => note.text)).toEqual(["second", "first"]);
});
```

Run the tests with `npm test`, the starter's `vitest run`. Make a new kernel
in each test: each one is an independent installation with its own clock.

## Kernel options

| Option | Default | Sets |
| - | - | - |
| `now` | `2026-01-01T00:00:00Z` | The clock's start. Move it with `k.advance`. |
| `within` | one second | Each transaction's deadline, `ctx.frame.within`: the span after which it is `Expired`. |
| `origin` | `https://installation.test` | The installation's origin: `ctx.get(file.url)` answers `<origin>/api/storage/<file>`. |
| `founder` | `"person:founder"` | The person principal that receives the roles selected by the app's `founders` declaration. |
| `secrets` | Unset | Maps declared secret names to fixture values and key paths to fixture key material. |
| `installation` | A fresh name | Fixture kernels with the same name share custody. Each kernel owns its store. |

## Callers: `k.as(principal)`

`k.as(principal)` is the client a browser gets, connected to this kernel. It
has `query`, `mutate`, `watch` and `trial`, the frame methods `.under`,
`.in` and `.at`. Pass references from `api<typeof App>()` or `api(App)`
to its verbs. A client call answers a `Result`.

| Principal | Acts as |
| - | - |
| `"person:alice"` | That person's own development credential, written in full. There is no bare name such as `"alice"`; `k.as("person:alice").id` is `"person:alice"`. |
| `"anonymous:test"` | A signed-out caller: each call is admitted as its own `anonymous:<token>` principal, of kind `anonymous`. |
| `{ id, kind }` | A development principal of that id and kind. It has no issuer, so its `ctx.frame.as.email` and `as.phone` are `null`. |

## Signing in: `k.signIn(issuer, claims)`

`k.signIn(issuer, claims)` signs a person in through an issuer the app
declares, with the kernel playing the identity provider. It answers the same
client as `k.as`, for the person the identity binding names: the same
`subject` signs in as the same id. `claims` are the provider's: `subject`,
and optionally `email`, `emailVerified`, `phone`, `phoneVerified` and
`authenticatedAt`. An email becomes `ctx.frame.as.email` only when the
provider verified it and the issuer trusts verified email
(`trustVerifiedEmail: true`), exactly as a deployment decides; the kernel
then also matches it against an invitation's addressee. Pass a tenant
trust's grant point (`sys.grants(id)` for the id returned by the Sessions issue call) as `issuer` to
sign in through that tenant: its
email never enters `as.email`, and redeems only that tenant's invitations.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
const ada = await k.signIn(app.signIn, { subject: "ada", email: "Ada@Example.com", emailVerified: true });
const eve = await k.signIn(app.signIn, { subject: "eve", email: "ada@example.com", emailVerified: false });   // as.email: null
```

A caller holds an app role through a grant. In this example, the app's
founder role can issue `clerk`.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { api } from "@bijectionhq/bijection/client";
import { label, sys } from "@bijectionhq/bijection";

const k = kernel(app);
const bob = k.as("person:bob");
expect(await bob.mutate(api(app).ledger.record, { amount: 1 })).toMatchObject({ ok: false, code: "Disallowed" });

await k.seed(sys.grants, [{ role: app.ledger.clerk, to: "person:bob", under: label.public }]);
expect(await bob.mutate(api(app).ledger.record, { amount: 1 })).toMatchObject({ ok: true });
```

A family member's grant is `under: tenant.of("acme")`, and the caller then
acts in that member with `bob.under(tenant.of("acme"))`.

`role.anyone` and `role.signedIn` are class grants the program issues at
install. They enter functions and clear no label, so entry through them
clears only public data. If such an entry requires more clearance, it
refuses `Disallowed` with reason `NotCleared`.
Give such an entry a role that clears the label.

## Refusals

A client call answers the refusal as a value. Here `add` refuses an empty
note with `EmptyNote`, as the [quickstart](https://docs.bijection.com/start/quickstart.md#refuse-an-empty-note)
adds it, and the app also declares the guard `guards.noSpam: forbid(act.enter(notes.add), { message: "Spam is not a note", where: (a) => a.args.text.equals("spam") })`:

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { api } from "@bijectionhq/bijection/client";
expect(await alice.mutate(api(app).notes.add, { text: "" })).toMatchObject({ ok: false, code: "EmptyNote" });
expect(await alice.mutate(api(app).notes.add, { text: "spam" })).toEqual({
  ok: false, code: "Forbidden", message: "Spam is not a note", guard: "guards.noSpam",
});
```

A guard's refusal carries `guard`, the guard's tree path.

## The kernel's own verbs

Use `k.as(principal)` to call an app function under its real admission
rules. Use `k.seed(table, facts)` to prepare app data. The shell stages
the batch in a branch as the founder and lands it with an ordinary land,
which orders every fact together. Pass `{ by, under }` to choose another
performer or a labelled commit. `k.seed(sys.files, files, { by, under })`
runs the ordinary File store act and defaults to the installation's founder.

Grant and member seeds prepare starting state in the memory shell. Every
grant in a batch uses the same `under` label. Choose a label visible to the
app call that uses the grant. The owning program's live grant bounds each
grant's rights and lifetime. Member seeds create public registry
rows, including keyed lookup and family limits. Seed any member role
separately. The shell commits all the facts in a batch together and records
fixture provenance. Authorization tests call the declared app function
through `k.as(principal)` or `k.signIn`.

The memory shell's reads inspect committed facts outside function admission.
A refused seed throws `Refused` with the failure as `result`.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { kernel, Refused } from "@bijectionhq/bijection/test";

const k = kernel(app);
await k.seed(app.prices.prices, [{ sku: "s1", cents: 100 }]);
await expect(k.seed(app.prices.prices, [{ sku: "s1", cents: 200 }]))
  .rejects.toThrow(Refused);
await expect(k.seed(app.prices.prices, [{ sku: "s1", cents: 200 }]))
  .rejects.toMatchObject({ result: { code: "Exists" } });
expect(await k.count(app.prices.prices)).toBe(1);
```

## Tasks: the test performs

Read task facts with `k.list(sys.tasks.where({ state: "pending" }).first(n))`.
Use `k.answer` to simulate an external receiver's reply. `k.advance` runs function tasks and
due continuations. For a target answered by a mutation, call that mutation
with `k.as(principal)`.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { api } from "@bijectionhq/bijection/client";
const placed = await alice.mutate(api(app).place, { cents: 100 });
const [charge] = await k.list(sys.tasks.where({ state: "pending" }).first(10));

await k.answer(charge.task, { ok: true, value: { id: "pi_1" } });
expect(await k.advance()).toBe(1); // the continuation ran
expect(await k.get(app.orders(placed.ok ? placed.value : ""))).toMatchObject({ state: "paid" });
```

A declared mutation can withdraw a task with `ctx.withdraw(task)`. Its
continuation receives `Withdrawn`. A task still pending at its `within`
deadline settles `Expired`.

## The clock: `k.advance`

`k.advance(duration)` moves the clock and runs everything then due: expiries,
`due` tasks, function tasks, continuations, `every` and `cron` sources and
change reactions, until nothing is due. `k.advance({ to: instant })` moves it
to an instant. It answers how many pieces of work ran. `k.now` is the clock.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
const k = kernel(app, { now: START });
expect(await k.advance({ minutes: 1 })).toBe(1); // one every({ minutes: 1 }) firing
expect(k.now.equals(START.add({ minutes: 1 }))).toBe(true);
```

`k.refusals` lists, in order, the work that ran and refused: a continuation, a
task's run, a cron or a change reaction, each `{ on, refusal }`.

## Restore an installation

`await k.restore()` archives the installation at head and restores it
through the kernel's restore path. Later calls use the restored store
under the same test handle. Kernels explicitly given the same
`installation` name share custody and keep separate stores.

## Trial deployment

`k.deploy(next, { trial: true })` runs deploy's check against the facts
this kernel holds and discards the candidate. The check uses the candidate's
[declared column changes](https://docs.bijection.com/database/changing-tables.md#declare-a-column-rename-or-cast)
and reports the table changes or a refusal such as `DeclarationBreaksFacts`.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { api } from "@bijectionhq/bijection/client";
import app from "./app";
import next from "./next/app"; // the app with `notes.title` removed

const k = kernel(app);
const alice = k.as("person:alice");
await alice.mutate(api(app).notes.add, { text: "hi", title: "draft" });
const blocked = await k.deploy(next, { trial: true });
expect(blocked.ok).toBe(false); // a fact still holds `title`: DeclarationBreaksFacts
await alice.mutate(api(app).notes.clearTitles, {});
const changes = await k.deploy(next, { trial: true });
expect(changes.ok && changes.value.changes.map((c) => c.change.kind)).toEqual(["fieldRemoved"]);
```

Each change is `{ table, change: { kind, field? }, verdict }`. A verdict is
`safe`, or `breaksFactsUnless` with the condition that makes it safe
(`unless.facts`: `tableEmpty`, or `fieldEmpty` with its `field`). `next` only
supplies its declarations; its handlers never run, and the kernel keeps
running the app it was created with.

## Routes: `k.route`

`k.route(reaction, { method, body, file, headers, query, as })` delivers a
request through the declared route reaction’s verifier. The route's `allow` admits `as` (signed out by default), the
reaction holds its `roles`, and its value or refusal answers as a `Result`.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
const reply = await k.route(app.stripe, { body: { type: "charge.succeeded" } });
expect(reply.ok).toBe(true);
```

An upload is a request with `file: { bytes, contentType }` in place of
`body`. The kernel stores it at ingress, as the host does, and the reaction
receives the `File` point as `request.file`:

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
const stored = await k.route(app.receipts, {
  as: "person:alice",
  file: { bytes: new Uint8Array([0x25, 0x50, 0x44, 0x46]), contentType: "application/pdf" },
});
expect(stored.ok).toBe(true);
```

## Trials and watches

`client.trial(fn, args)` runs the call in a discarded world and answers
`{ result, writes, tasks, validUntil }`. Nothing commits.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { api } from "@bijectionhq/bijection/client";
const trial = await alice.trial(api(app).notes.add, { text: "draft" });
expect(trial.writes).toMatchObject([{ verb: "insert", table: "notes.items", after: { text: "draft" } }]);
```

`client.watch(fn, args)` is an async iterable of `Result`s that stays current
across commits. Stop it with `watch.stop()`.

## Mounted apps

Test a mountable app the way an installer uses it: mount it at a path of a
root app, and call its functions at their paths. The root is a test app like
any other, so it is the default export of its own module:

```ts fixtures/installer.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { app, role } from "@bijectionhq/bijection";
import comments from "../app";

export default app({ blog: comments({ allow: [role.signedIn] }) });
```

```ts comments.test.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { api } from "@bijectionhq/bijection/client";
import { expect } from "vitest";
import { kernel } from "@bijectionhq/bijection/test";
import root from "./fixtures/installer";

const k = kernel(root);
const alice = k.as("person:alice");
await alice.mutate(api(root).blog.add, { target: "post-1", text: "first" });
expect(await k.count(root.blog.comments)).toBe(1);
```


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