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

# Effects

> Declare a target for work done outside the transaction, submit a task to it, and receive its result in a continuation.

Work outside the transaction, such as an HTTP call, a person's approval or a
second transaction, is a **target**: a contract for work. A mutation
commits intent toward a target with `ctx.submit`, atomically with its writes.
The committed intent is a **task**. The task runs after the
commit, and the task settles with a [`Result`](https://docs.bijection.com/functions/errors). A
continuation named by `then` receives that result in a later transaction.

This example sends a contact to a CRM and records the CRM's key.

## Declare a target

```ts bijection/crm.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { http, label, secret, t, target } from "@bijectionhq/bijection";

/** The CRM's API key. Set it with `bijection secret set crm.apiKey`. */
export const apiKey = secret();

export const createContact = target({
  label: label.public,
  via: http("https://api.crm.example/contacts", { bearer: apiKey }),
  args: { email: t.string },
  returns: { id: t.string },
  refuses: { DuplicateContact: null },
  within: { minutes: 10 },
});
```

| Option | Meaning |
| - | - |
| `via` | How the target runs: an outbound send, a list of roles whose holders answer, or a mutation the host runs |
| `label` | The label the target clears |
| `args` | The value types the task carries |
| `returns` | The value type of a successful result |
| `refuses` | The app codes a result may carry |
| `reply` | Terminal result custody. `erasable: true` gives the reply its own erasure unit, and `lifetime` schedules its closure from settlement. |
| `within` | The deadline, a duration. A task still pending past it settles `Expired`. |

`http(url, { bearer })` sends each task as one JSON `POST` of its args to the
URL, with `Authorization: Bearer <secret>` when configured.

| HTTP answer | Task outcome |
| - | - |
| 2xx | Success with the JSON body as its value |
| 4xx with a declared code in its JSON body | The declared code and the body's message |
| Other 4xx (except 408, 425 and 429) | `Failed` |
| 408, 425 or 429 without a declared code, any 5xx, or no answer | Final `Unknown` |

Redirects fail. For another method, path or headers, use a receiver from
`@bijectionhq/bijection` as shown in [Integrations](https://docs.bijection.com/integrations).

## Submit from a mutation

```ts bijection/contacts.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { mutation, role, t, table } from "@bijectionhq/bijection";
import { createContact } from "./crm";

export const contacts = table({
  email: t.string,
  remote: t.maybe(t.string),
  problem: t.maybe(t.string),
});

export const create = mutation(
  { allow: [role.signedIn], args: { email: t.string } },
  async (ctx, { email }) => {
    const contact = await ctx.insert(contacts, { email, remote: null, problem: null });
    await ctx.submit(createContact, { email }, {
      once: ["crm-contact", contact],
      then: recorded.with({ contact }),
    });
    return contact;
  },
);

/** The continuation: internal, so only the task's delivery runs it. */
export const recorded = mutation(
  { args: { contact: t.key(contacts), result: t.result(createContact) } },
  async (ctx, { contact, result }) => {
    if (result.ok) await ctx.patch(contacts(contact), { remote: result.value.id, problem: null });
    else await ctx.patch(contacts(contact), { problem: result.code });
  },
);
```

The fact and the task commit together: if the mutation refuses, no task
exists.

`ctx.submit(target, args, { once, then, due, within })` returns the `Task`.

| Option | Meaning |
| - | - |
| `once` | The effect's identity, a string or a tuple. The same `once` and args return the original task, settled or not; the same `once` with other args refuses `Invalid`. |
| `then` | The continuation: any mutation with its other args bound, `fn.with(args)`. The delivery fills its `result` argument, declared `t.result(target)`. |
| `due` | The instant the task becomes performable. Absent, now. |
| `within` | The task's deadline, overriding the target's. |

A `once` built from the call's own `once`, its arguments, or ids your handler minted is stable across retries and successor restores. A store counter or another read that a restore can rewind can produce a different `once`.

A continuation reads the task whose result it receives from `ctx.frame.on.task`
after narrowing `ctx.frame.on.kind` to `"then"`. It is
an ordinary mutation and needs no `allow`.

## Read a task

A task is a point in `sys.tasks`. Its address is `sys.tasks/<id>`, where
the kernel mints the opaque id. Store the handle in a `t.task(target)` field.
`ctx.get(task)` returns its state or `null` when the task is absent.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
const state = await ctx.get(task);
// { state: "pending", target, due, until, claim }
// | { state: "settled", target, result }
// | { state: "withheld" }   // the task is above this frame's label
// | null
```

`sys.tasks` holds every task's facts, so a query can select them:
`ctx.list(sys.tasks.where({ target: createContact, state: "pending" }).first(50))`.
To find a task by its original `once`, use a selection such as
`bijection list sys.tasks --where target=payments.charge --where once=charge-1 --first 1`.

## Run a mutation later

A mutation is a target too. Submit it to run it in its own transaction after
this one commits, and add `due` to run it later:

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
await ctx.submit(remind, { order }, {
  once: ["remind", order],
  due: ctx.frame.now.entry.add({ hours: 24 }),
});
```

For work that recurs, declare a [reaction](https://docs.bijection.com/functions/reactions.md) on
`every(duration)` or `cron(expression, zone)` instead.

## Submit work at a higher label

A public request can queue a protected review. The submission records the
request at public and returns its task handle. The review later reads and
writes at `review`, in its own transaction. Set the submit's `under` to the
label the mutation declares.

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

export const review = label();
export const requester = role({});
export const reviewer = role({ clear: [review] });
export const cases = table(
  { request: t.string, ready: t.boolean, checked: t.boolean, approved: t.boolean },
  { key: ["request"], label: review },
);

export const checkCase = mutation(
  { under: review, args: { request: t.string }, returns: { ready: t.boolean } },
  async (ctx, { request }) => {
    const record = await ctx.get(cases(request));
    if (record === null) return ctx.refuse("Absent", "The review case is unavailable.");
    await ctx.patch(cases(request), { checked: true });
    return { ready: record.ready };
  },
);

export const requestCheck = mutation(
  { under: label.public, allow: [requester], args: { request: t.string } },
  (ctx, { request }) => ctx.submit(checkCase, { request }, {
    under: review,
    once: ["check", request],
    within: { minutes: 5 },
  }),
);

export const checkOutcome = query(
  { under: review, allow: [reviewer], args: { task: t.task(checkCase) } },
  async (ctx, { task }) => {
    const state = await ctx.get(task);
    return state?.state === "settled" ? state.result : null;
  },
);
```

Give the submitter a live `requester` grant at public. The app's site can
invoke the internal `checkCase`. The deferred claim re-forms the
submitter's frame and is offered only the grants recorded when the request
was admitted at public that are still live. A target mutation with `allow`
can narrow those offers. Reading the outcome through
`checkOutcome` requires a live `reviewer` grant at `review`.
[Role grants](https://docs.bijection.com/access/grants.md)

For a task from this submission, `ctx.get(task)` at public answers
`{ state: "withheld" }` before and after settlement. The result, including
any refusal, sits at `review`. A `then` handler also runs there and can
declare `result: t.result(checkCase)` to receive it. Use a single higher
entry when the protected change and a lower publication must commit together.
[Atomic decisions and lower publication](https://docs.bijection.com/functions/design-patterns.md#commit-a-protected-decision-and-a-lower-publication-together)

## Running a task with a mutation

`via: mutation` runs a mutation for the target. The host runs it in
its own transaction with the task's args, and its value or refusal settles the
task. A mutation that starts work it cannot finish in one transaction returns
its own task from `ctx.frame.on.task`, which leaves the task open. A function placed in
the subtree that holds the target answers it later with `ctx.answer`, within
the target's `within`.

```ts bijection/jobs.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
export const launch = mutation({ args: { job: t.key(jobs) } }, async (ctx, { job }) => {
  const on = ctx.frame.on;
  if (on?.kind !== "task") throw new Error("Expected a task delivery");
  await ctx.insert(launches, { job, task: on.task }); // `done` answers it later
  return on.task;
});

export const start = target({
  via: launch,
  args: { job: t.key(jobs) },
  returns: { run: t.string },
  refuses: { NoCapacity: null },
  within: { hours: 1 },
});
```

## Answers from people and agents

`via: [roles]` waits for a principal holding one of the roles to answer the
task. Such a target declares `within`, since nobody may ever answer.

```ts bijection/approvals.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
export const approval = target({
  via: [approver],
  args: { order: t.key(orders) },
  returns: { approved: t.boolean },
  within: { days: 3 },
});

export const decide = mutation(
  { allow: [approver], args: { task: t.task(approval), approved: t.boolean } },
  (ctx, { task, approved }) => ctx.answer(task, { ok: true, value: { approved } }),
);
```

`ctx.answer(task, result)` settles a pending task with a result, and
`ctx.withdraw(task, { message })` settles it as `Withdrawn`. Both are
[grave acts](https://docs.bijection.com/functions/grave-acts.md).

## What a task's result can be

A refused result is the same flat refusal a call answers
([refusals](https://docs.bijection.com/functions/errors.md)): its host code with its public `reason` and
`retryAfter`, or one of the target's declared codes with its `data`.

| Result | Meaning |
| - | - |
| `{ ok: true, value }` | The task finished; `value` has the target's `returns` type. |
| a declared code | The task refused with one of the target's `refuses`, with the payload it declares as `data`. A code the target does not declare reads `Failed`. |
| `Unknown` | It may have happened: the reply was lost, or a restore ended the task before this installation could know (reason `InstallationRestored`). The result is final: the host never resends the task, and a submit with the same `once` returns this same settled task. Reconcile with the receiver (below), or record the uncertainty. |
| `Failed` | It definitely did not happen. |
| `Expired` | `within` passed first; with the reason `ExpiredWhileBlocked` when it passed while the task was blocked. |
| `Withdrawn` | The task was withdrawn. |

`Unknown` means something else on a call. A caller that lost the reply to
its own call (`client.mutate`, the CLI, HTTP) calls again with the same
`once`, and the host answers the original commit's result.

### When a task settles `Unknown`

The reply may have been lost. On a successor restore, an unfinished send
with a custody dispatch settles `Unknown` with reason `InstallationRestored`.
The archive may show it as waiting for dispatch if the dispatch happened
after the cut. A send with no custody entry stays pending.

Bijection orders one dispatch per receiver key across the installation's
lineage. Custody acknowledges that dispatch before any byte can leave.
Every HTTP send carries that key and `Bijection-Fencing-Token`. Set
`receiver({ once: { header } })` for a header other than the default
`Idempotency-Key`. Use `receiver({ once: { field } })` to place the key in
a top-level field of an inline JSON body. Leave that field out of the
operation's args and request body so the host can fill it before signing.
GET requests to a body-keyed receiver carry the key in `Idempotency-Key`.
An ordinary Bijection HTTP reaction uses this header as its `once`.
Set `receiver({ delivery: { timeout } })` to bound the wait for an answer.
If the send times out, it settles `Unknown`. The task deadline remains `within`.
The same effect keeps its receiver key across retries, deploys and successor
incarnations. A fenced receiver, including the managed provider,
refuses a kept key presented with a different request digest.

A task's `Unknown` result is final. To reconcile it, declare how the
receiver answers for the send's idempotency key with `operation({ status })` and submit
`reconciled(target)` from `@bijectionhq/library-recovery`. The library's
task can return the receiver's conclusive answer about that
key. See [Reconcile external results](https://docs.bijection.com/operations/reconciliation.md).

The kernel decides a send, run, landing, inbox call or clock tick again at
claim, offered only the submitter's grants recorded at submit that are
still live. A send
that loses an admitting grant settles `Disallowed` and records why.
Submit admits `then` as an obligation at the join of the submitter's
commit label and the target label. The obligation receives the task's
final result using its recorded authority. Acts inside the continuation
decide against live grants when they run. A refused act leaves the
obligation stuck.

## Reply custody

Every external task reply is sealed under its own erasure unit and the
request's units. The delivering continuation can close the reply's unit
with `ctx.erase(task)`. A target or receiver operation can set
`reply: { erasable: true, lifetime: { minutes: 30 } }`. The lifetime uses the same
fixed durations as [table lifetime](https://docs.bijection.com/database/history-and-lifetime.md) and
starts when the task settles. External replies have their own unit even
when `reply` is omitted or `erasable` is false. After the reply closes, task
status stays settled and its result reads as `null` in every version.

## Tasks in a branch

A task submitted in a [branch](https://docs.bijection.com/branches) stays there: external sends occur only at
the head. Landing the branch submits it at the head. To send a request to a real
receiver, use the head of a separate
[development deployment](https://docs.bijection.com/operate/installations/environments.md).

## Test it

The test kernel simulates receiver replies and the clock: it answers tasks and
advances time.

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

test("records the CRM's key after the task settles", async () => {
  const root = app({ crm, contacts });
  const k = kernel(root, { now: Temporal.Instant.from("2026-01-01T00:00:00Z") });
  const alice = k.as("person:alice");
  const created = await alice.mutate(api(root).contacts.create, { email: "ada@example.com" });
  if (!created.ok) throw new Error(created.message);

  const [pending] = await k.list(sys.tasks.where({ state: "pending" }).first(10));
  await k.answer(pending!.task, { ok: true, value: { id: "contact-42" } });
  await k.advance();

  expect(await k.get(root.contacts.contacts(created.value))).toMatchObject({ remote: "contact-42" });
});
```

See [Testing](https://docs.bijection.com/development/testing/test-library.md) for the test kernel.


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