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

# Branch workflow

> Open a branch, stage a change in it, review the exact version and land it, with the server and client code in one place.

This page walks one workflow from open to land. The code comes from the
[`supplier-decisions` example](https://github.com/bijectionhq/bijection/tree/main/examples/supplier-decisions).
An operator stages a retroactive revocation of a supplier certification in a
branch. A different person reviews the branch and lands the exact version they
reviewed.

The client code uses two clients from `connect(url, { token })`,
one per person: `operator` and `reviewer`.

## The five steps

| Step | Act | Where |
| - | - | - |
| Open | `ctx.branch({ until })` | a mutation at the head |
| Stage | ordinary writes | the same mutations, called with `client.in(branch)` |
| Review | `.changes.in(branch)` and `.in(branch)` reads | a query at the head |
| Land | `ctx.land(branch, { seen, then })` | a mutation at the head |
| Settle | the landing's continuation receives `t.result(sys.land)` | a later transaction |

`ctx.branch`, `ctx.land` and `ctx.discard` are [grave acts](https://docs.bijection.com/functions/grave-acts.md):
`bijection check` lists every function that performs them.

## 1. Open the branch

`ctx.branch({ until })` begins a writable world over the head and returns the
`Branch`. It ends at `until` unless something keeps it: here the
`correctionBranches` table's `pin` option keeps the branch readable while its
fact exists, and the correction fact records the version the branch began over
(`sys.branches(branch).from`). A branch lives at most as long as its version
stays inside every table's history (the shortest `history`, at most 30
days): one asking to live longer is refused `BeyondHistory`, and one naming no
`until` lives exactly that long. Nothing a branch does holds history back.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
async function openCorrection(
  ctx: MutationCtx,
  { supplier, from, to }: { supplier: string } & Interval,
  invited: PrincipalId | null,
) {
  requireLive(ctx);
  requirePeriod(ctx, from, to);
  if (ctx.frame.as.kind === "anonymous") return ctx.refuse("SignedOut", "Sign in to propose a correction.");
  const branch = await ctx.branch({ until: ctx.frame.now.entry.add({ hours: 24 * 7 }) });
  const base = (await ctx.get(sys.branches(branch)))?.from ?? null;
  const branchPin = await ctx.insert(correctionBranches, { branch });
  const id = await ctx.insert(corrections, {
    supplier, from, to, branch, branchPin, version: base, reviewer: invited,
    author: ctx.frame.as.id, review: null, changed: [], landingTask: null, state: "draft", refusal: null,
  });
  return { id, branch };
}

/** Open a correction any reviewer other than its author may review. */
export const propose = mutation(
  { allow: [operator], args: revocation, refuses: { ...opening } },
  (ctx, args) => openCorrection(ctx, args, null),
);
```

To name the one person who may review, the author invites them:

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
export const openProposalForReview = mutation(
  { allow: [operator], args: { ...revocation, reviewer: t.principal }, refuses: { ...opening, IndependentReview: null } },
  async (ctx, { reviewer: invited, ...args }) => {
    if (invited === ctx.frame.as.id) return ctx.refuse("IndependentReview", "Invite a different person to review the proposal.");
    return openCorrection(ctx, args, invited);
  },
);
```

`requireLive` refuses unless the call runs at the head (`ctx.frame.in === null`):
branches open there.

## 2. Work in the branch

Branch work is ordinary application code. The client selects the branch with
`client.in(branch)`, and every write lands in the branch. This mutation refuses
at the head, so the change can only be staged:

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
export const revokeInBranch = mutation(
  { allow: [operator, reviewer], args: supplierPeriod, refuses: { BranchOnly: null, InvalidPeriod: null } },
  async (ctx, { supplier, from, to }) => {
    if (ctx.frame.in === null && ctx.frame.on?.kind !== "landing")
      ctx.refuse("BranchOnly", "Stage the correction in its proposal branch.");
    requirePeriod(ctx, from, to);
    await ctx.put(certifications(supplier).over({ from, to }), { supplier, active: false });
    return null;
  },
);
```

The exception is the landing's replay of the branch's calls: then
`ctx.frame.on` carries `{ kind: "landing", branch }`.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
await operator.in(branch).mutate(app.certifications.revokeInBranch, revocation);
```

A task submitted in a branch stays in the branch: performers act only at the
head, and landing submits it there.

## 3. Review the branch

The review reads what the branch changed since it began. Each table's change
log in the branch is `table.changes.in(branch).since(base)`, and staged tasks
are `sys.tasks.changes.in(branch)`:

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
const certified = await ctx.list(certifications.changes.in(branch).since(base).first(2));
const tasks = await ctx.list(sys.tasks.changes.in(branch).since(base).first(1));
```

`sys.branches(branch).changes` is the branch's whole log across every table
of the app, each entry `{ table, key, before, after, version }`. It is a log,
not a net diff: fold it by `table` and `key` (the first `before`, the last
`after`) for the net effect. A review that must prove the branch holds nothing
else reads it whole. It never holds a `sys` table: staged tasks are read from
`sys.tasks.changes.in(branch)`, as above.

An entry is a `BranchChange`. Register the app once and it is a union
discriminated by `table`, whose `before` and `after` are that table's facts:

```ts bijection/register.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import type tree from "./app";

declare module "@bijectionhq/bijection" {
  interface Register { readonly app: typeof tree }
}
```

The invited reviewer's query answers the diff, the supplier's segments at the
head and in the branch, and `seen`, the branch version of the latest change.
`seen` is what the reviewer approves:

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
export const compareProposalForReview = query(
  { allow: [reviewer], args: idArg, refuses: { ...reviewRefusals } },
  async (ctx, { id }) => {
    requireLive(ctx);
    const fact = await reviewable(ctx, id);
    const diff = await branchDiff(ctx, fact);
    const period = certifications(fact.supplier).over({ from: fact.from, to: fact.to });
    const [latest] = await ctx.list(certifications.changes.in(fact.branch).since(fact.version).descending().first(1));
    return {
      ...diff,
      head: await ctx.list(period.first(64)),
      branch: await ctx.list(period.in(fact.branch).first(64)),
      seen: latest?.version ?? null,
    };
  },
);
```

## 4. Land the exact version

`ctx.land(branch, { seen, then })` applies the branch to its parent. It is
one task submitted with the mutation's writes, so it exists only if the
mutation commits. `seen` is the branch version the lander reviewed: if the
branch already moved past it, `ctx.land` refuses `Conflict`; if it moves
before the landing, the landing settles `Conflict`. Either way nothing lands. Landing checks each root against the parent and earlier
roots in commit order. A root whose reads and time premises still hold can use
its recorded writes. The parent carries those reads and writes through total
schema lenses. A table ending or a changed dependency sends the affected root
through head's code again. Head judges each root's grants and guards. All roots
land in one append. If it conflicts, the next attempt revalidates at a fresh
parent version while the landing's deadline lasts.

A branch opened with `under` (see [the lifecycle](https://docs.bijection.com/branches/lifecycle.md#open-a-branch))
can hold calls at several labels. The lander's `ctx.frame.under` must clear
that ceiling, and the lander's live grants must still clear its
`ctx.frame.under` when the landing is decided (`LandClearance`). When the landing writes a place below or
beside the lander's label, name a `release` from the landing function's
`releases:`: `ctx.land(branch, { seen, then, release })`. That place learns
its own landed writes, its own version token and the commit's public instant,
and the release is recorded in `sys.disclosures`. A refused landing writes,
moves and wakes nothing there.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
export const approveProposal = mutation(
  {
    allow: [reviewer],
    args: { ...idArg, seen: t.version },
    refuses: { ...reviewRefusals, CorrectionScopeChanged: null, NoEffect: null, ReviewMoved: null },
  },
  async (ctx, { id, seen }) => {
    requireLive(ctx);
    const fact = await reviewable(ctx, id);
    const exact = await exactRevocation(ctx, fact);
    if (exact.seen !== seen) return ctx.refuse("ReviewMoved", "The branch moved past the compared version: compare it again.");
    const review = { seen, revision: String(seen) };
    const task = await ctx.land(fact.branch, { seen, then: settled.with({ id }) });
    const landingTask = { address: task.address };
    await ctx.patch(corrections(id), { review, changed: exact.changed, state: "landing", landingTask });
    return { id, revision: review.revision, changed: exact.changed, task: landingTask };
  },
);
```

Without an invitation, a reviewer can review and land in two steps:
`prepareReview` records the reviewed `seen`, and `landReviewed` lands it.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
export const prepareReview = mutation(
  { allow: [reviewer], args: idArg, refuses: { ...reviewRefusals, CorrectionScopeChanged: null, NoEffect: null } },
  async (ctx, { id }) => {
    requireLive(ctx);
    const fact = await reviewable(ctx, id);
    const { seen, changed } = await exactRevocation(ctx, fact);
    const review = { seen, revision: String(seen) };
    await ctx.patch(corrections(id), { review, changed });
    return { revision: review.revision, changed };
  },
);

/** Land the exact revision `prepareReview` answered. `land` refuses
 * `Conflict` if the branch moved past it; asking again with the same
 * `once` returns the same task. */
export const landReviewed = mutation(
  { allow: [reviewer], args: { ...idArg, revision: t.string }, refuses: { ...reviewRefusals, ReviewMoved: null } },
  async (ctx, { id, revision }) => {
    requireLive(ctx);
    const fact = await reviewable(ctx, id);
    if (fact.review === null || fact.review.revision !== revision)
      return ctx.refuse("ReviewMoved", "Land the exact revision returned by prepareReview.");
    const task = await ctx.land(fact.branch, { seen: fact.review.seen, then: settled.with({ id }) });
    const landingTask = { address: task.address };
    await ctx.patch(corrections(id), { state: "landing", landingTask });
    return { id, revision, task: landingTask };
  },
);
```

## 5. Settle

Landing is a task. Its continuation receives `t.result(sys.land)`: the
version the landing committed, as the lander's own version token, or
`Conflict`.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
export const settled = mutation(
  { args: { ...idArg, result: t.result(sys.land) } },
  async (ctx, { id, result }) => {
    const fact = await ctx.get(corrections(id));
    if (fact === null || fact.state !== "landing") return null;
    if (result.ok) await ctx.patch(corrections(id), { version: result.value, state: "landed" });
    else await ctx.patch(corrections(id), { state: "refused", version: null, refusal: result.code });
    await ctx.delete(correctionBranches(fact.branchPin));
    return null;
  },
);
```

The app tree places all of it:

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
export default app({
  certifications,
  corrections,
  decisions,
  team,
  roles: { operator, reviewer, administrator },
});
```

## The client flow

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
const revocation = { supplier, from: day(10), to: day(20) };
const correction = await operator.mutate(app.corrections.propose, revocation);
if (!correction.ok) throw new Error(correction.message);
await operator.in(correction.value.branch).mutate(app.certifications.revokeInBranch, revocation);

const review = await reviewer.mutate(app.corrections.prepareReview, { id: correction.value.id });
if (!review.ok) throw new Error(review.message);
// The review shows the valid-time intervals where active becomes revoked.
const once = `land-${correction.value.id}`;
let submitted = await reviewer.mutate(app.corrections.landReviewed, {
  id: correction.value.id,
  revision: review.value.revision,
}, { once });
// A lost reply answers Unknown: ask again with the same once.
while (!submitted.ok && submitted.code === "Unknown")
  submitted = await reviewer.mutate(app.corrections.landReviewed, {
    id: correction.value.id,
    revision: review.value.revision,
  }, { once });
```

Asking again with the same `once` returns the same landing task, so a lost
reply (`Unknown`) is safe to retry. With an invited reviewer:

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
const invited = await operator.mutate(app.corrections.openProposalForReview, { ...revocation, reviewer: reviewerPrincipal });
if (!invited.ok) throw new Error(invited.message);
await operator.in(invited.value.branch).mutate(app.certifications.revokeInBranch, revocation);

const compared = await reviewer.query(app.corrections.compareProposalForReview, { id: invited.value.id });
if (!compared.ok || compared.value.seen === null) throw new Error("nothing to review");
// compared.value lists the branch's changes, the segments at head and in the branch, and seen.
const approved = await reviewer.mutate(app.corrections.approveProposal, {
  id: invited.value.id,
  seen: compared.value.seen,
}, { once: ["land", invited.value.id] });
```

## Refusals you can meet

| Code | When |
| - | - |
| `LiveOnly` | Opening, reviewing or landing in a branch or at a version (app code) |
| `BranchOnly` | Staging the revocation at the head (app code) |
| `IndependentReview`, `NotInvited` | The author reviewing their own correction, or anyone but the invited reviewer (app codes) |
| `ReviewMoved` | The branch moved past the compared version before approval (app code) |
| `BranchLabelSpan` | A call into the branch commits outside the label span its `ctx.branch({ upTo })` fixed |
| `LandClearance` | The lander's `under` does not clear the branch's ceiling, or the lander's grants no longer clear its `under` |
| `Conflict` | The branch moved past `seen` after approval |
| `Forbidden` | A guard on `act.land()` or on a replayed write matched |
| `GrantRequired` | A call's caller no longer holds the grants its sealed author inputs recorded, a grant on its chain to the credential is no longer live, or its surviving grants no longer enter its function |
| `ProgramContractChanged` | A call runs again at the head (its reads changed, or code was deployed at the head since the branch was created), and its function's arguments or result changed |
| `FunctionNotFound` | A call runs again at the head, and the head's program no longer has its function |
| `LandConsent` | The branch carries a candidate program, and the lander holds no deployment authority to install it |
| `LandSchema` | The branch carries a candidate program, and the head deployed since the branch was created or the candidate's tables don't admit the facts at head |
| `Expired` | The landing kept losing races with other commits until its `within` ended |

To end a branch without landing it, call `ctx.discard(branch)`.


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