---
title: "State machines"
description: "Drive a state machine from a workflow, with Procore's submittal workflow rebuilt as a plain reducer and as an XState machine."
---

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

# State machines

A workflow that moves something through states, such as a submittal that goes from its submitter to its approvers and back, is a state machine. Forge has no state machine API of its own. Write the transitions as a pure function, or define them with a library such as [XState](https://stately.ai/docs/xstate), and drive them from the workflow's body.

This page sets out the rules that keep a machine correct in a workflow, and then rebuilds Procore's submittal workflow twice: once as a plain reducer and once as an XState machine.

## Rules for a machine in a workflow

The body runs again from the top after every sleep and signal wait (see [Steps and replay](https://buildrforge.com/docs/extensions/workflows/steps-and-replay/)). These rules keep a machine correct across those replays:

- **Pure transitions**: The body recomputes each transition from the signal answers that the run recorded. A transition that reads the clock, a random number, or the network can reach a different state on replay.
- **Effects in steps**: Run each effect, such as an email or a write to Forge, inside `step.do`, so that a replay answers its recorded result instead of running it again.
- **Step names that count turns**: A machine can enter a state more than once, such as a submittal that returns to an earlier approval step. A step named only for its state reuses the name and rejects with a `TypeError`. Number the turns of the body's loop and put the turn in each step's name.
- **One signal for every event**: A run waits for one signal at a time, so declare one signal, such as `event`, whose payload is the machine's event, as in `{ "type": "respond", "response": "approved" }`. The signal's `sentBy` tells the machine who sent it, so a transition can check that the sender may act.
- **Failures that don't stop the machine**: A step whose work throws on every retry fails the whole run. Catch a failure that the machine should outlive, such as an email that can't go out, inside the step's work and return it as the step's result.
- **Timeouts as events**: To act when nobody answers in time, pass `timeout` to `step.waitForSignal` and turn the `WorkflowSignalTimeoutError` into an event, such as `{ type: "overdue" }`.

A run's record shows that it's `waiting` and which signal it waits for, but not the machine's state. Tell people where a run stands from a step, as the example does by email.

## Procore's submittal workflow

In Procore, a submittal is a document, such as shop drawings or product data, that a subcontractor sends for the design team to review before work goes ahead. Procore's Submittals tool moves each submittal through a workflow ([Best Practices: Submittals](https://support.procore.com/products/online/user-guide/project-level/submittals/best-practices-submittals)):

- **Roles**: The submittal manager runs the workflow. An optional first step names the submitters, who send the documents. Then come one or more approval steps in order, each with one or more approvers, and each approver is required or optional.
- **Ball in court**: Whoever must act next holds the ball in court, and Procore emails them that action is required. A step is done once each of its required approvers has responded, and the ball moves to the next step. After the last step, it returns to the submittal manager.
- **Responses**: An approver responds with one of Procore's [default responses](https://support.procore.com/faq/what-are-the-default-submittal-responses-in-procore). _Approved_, _Approved as Noted_, and _For Record Only_ let work proceed. _Revise and Resubmit_ and _Rejected_ don't.
- **Reject workflow**: With the reject workflow setting on, a _Revise and Resubmit_ or _Rejected_ response sends the ball to the submittal manager, who closes the submittal, resumes the workflow, or returns the ball to the previous step. A resumed workflow stays on the step while other required approvers haven't responded, and otherwise moves on.
- **Due dates**: Each step has a number of days to respond, and Procore sends overdue notifications when they pass.
- **Close, distribute, and revise**: The submittal manager closes the submittal and distributes the response to the people who need it. A rejected submittal gets a revision, a copy with the next revision number whose workflow starts again from the first step.

Procore's API exposes the same model: a submittal's `approvers`, `ball_in_court`, and `is_rejected`, and the steps of its [workflow data](https://developers.procore.com/reference/rest/submittals?version=1.1). The example rebuilds the workflow itself in Forge: the run holds the state, and steps email the ball in court.

The example keeps the roles, ordered steps with required and optional approvers, the five responses above, the reject workflow, one overdue reminder for each wait, closing, distribution, and revisions. It leaves out forwarding to reviewers, custom responses, packages, and attachments.

### States and events

The machine has six states. A revision is a new run with the next revision number, so `distributed` ends the run:

| State | Ball in court | Events that move it |
| --- | --- | --- |
| `awaitingSubmission` | The submitters | `submit` from a submitter goes to the first approval step. |
| `inReview` | The approvers on the step who haven't responded: the required ones, or anyone on a step with none required | `respond` from one of them records the response. A rejecting response goes to `managerReview`. A response that finishes the step goes to the next step, or to `workflowComplete` after the last one. |
| `managerReview` | The submittal manager | `resume` moves on if the step is done, and otherwise goes back to `inReview` on the same step. `returnToPreviousStep` goes back a step, or to `awaitingSubmission` from the first step, and clears the rejection. |
| `workflowComplete` | The submittal manager | Only `close`. |
| `closed` | The submittal manager | `distribute` goes to `distributed`. |
| `distributed` | Nobody | None. The run ends with the revision and its rejection, if any. |

In every state before `closed`, `close` from the submittal manager goes to `closed`. An event from anyone else, or one that the state doesn't accept, changes nothing. In `awaitingSubmission` and `inReview`, a wait that runs past its due date raises `overdue`, which emails a reminder once.

## The shared model

Both machines share one file: the submittal's types, its events, its states, and the rules that don't depend on how the machine is written. `ballInCourt` says who must act, `finishesStep` says whether a step is done, and the email builders say what each state tells people.

```ts title="submittal.ts"
// The submittal, its people, and the rules both machines share.

export interface Person {
  readonly userId: string;
  readonly email: string;
}

export interface Approver extends Person {
  readonly required: boolean;
}

export interface ApprovalStep {
  readonly daysToRespond: number;
  readonly approvers: ReadonlyArray<Approver>;
}

export interface Submittal {
  readonly number: string;
  readonly title: string;
  readonly revision: number;
  readonly manager: Person;
  readonly submitters: ReadonlyArray<Person>;
  readonly daysToSubmit: number;
  readonly steps: ReadonlyArray<ApprovalStep>;
  readonly distribution: ReadonlyArray<string>;
}

export type Response =
  | "approved"
  | "approvedAsNoted"
  | "forRecordOnly"
  | "reviseAndResubmit"
  | "rejected";

export const rejects = (response: Response) =>
  response === "reviseAndResubmit" || response === "rejected";

export type SubmittalEvent =
  | { readonly type: "submit"; readonly sentBy: string }
  | {
      readonly type: "respond";
      readonly response: Response;
      readonly comment?: string;
      readonly sentBy: string;
    }
  | {
      readonly type: "resume" | "returnToPreviousStep" | "close" | "distribute";
      readonly sentBy: string;
    }
  | { readonly type: "overdue" };

export type Status =
  | "awaitingSubmission"
  | "inReview"
  | "managerReview"
  | "workflowComplete"
  | "closed"
  | "distributed";

export interface Rejection {
  readonly approver: string;
  readonly response: Response;
}

/** Where a submittal stands. `step` and `responses` describe the approval step under review. */
export interface SubmittalState {
  readonly status: Status;
  readonly step: number;
  readonly responses: Readonly<Record<string, Response>>;
  readonly rejection: Rejection | null;
  readonly overdue: boolean;
}

/** Whether the responses so far finish `step`: every required approver, or anyone on a step with none. */
export const finishesStep = (
  submittal: Submittal,
  step: number,
  responses: Readonly<Record<string, Response>>,
) => {
  const required = submittal.steps[step].approvers.filter((approver) => approver.required);
  return required.length > 0
    ? required.every((approver) => approver.userId in responses)
    : Object.keys(responses).length > 0;
};

/** Who must act next. */
export const ballInCourt = (submittal: Submittal, state: SubmittalState): ReadonlyArray<Person> => {
  switch (state.status) {
    case "awaitingSubmission":
      return submittal.submitters;
    case "inReview": {
      const waiting = submittal.steps[state.step].approvers.filter(
        (approver) => !(approver.userId in state.responses),
      );
      const required = waiting.filter((approver) => approver.required);
      return required.length > 0 ? required : waiting;
    }
    case "managerReview":
    case "workflowComplete":
    case "closed":
      return [submittal.manager];
    case "distributed":
      return [];
  }
};

/** How many days the ball in court has before the workflow reminds them, or null for no reminder. */
export const daysToAct = (submittal: Submittal, state: SubmittalState): number | null => {
  if (state.overdue) return null;
  if (state.status === "awaitingSubmission") return submittal.daysToSubmit;
  if (state.status === "inReview") return submittal.steps[state.step].daysToRespond;
  return null;
};

export interface Email {
  readonly to: ReadonlyArray<string>;
  readonly subject: string;
  readonly text: string;
}

const responseNames: Record<Response, string> = {
  approved: "Approved",
  approvedAsNoted: "Approved as Noted",
  forRecordOnly: "For Record Only",
  reviseAndResubmit: "Revise and Resubmit",
  rejected: "Rejected",
};

const label = (submittal: Submittal) =>
  `Submittal #${submittal.number} rev ${submittal.revision}: ${submittal.title}`;

const emailOf = (submittal: Submittal, userId: string) =>
  [
    submittal.manager,
    ...submittal.submitters,
    ...submittal.steps.flatMap((step) => step.approvers),
  ].find((person) => person.userId === userId)?.email ?? userId;

/** The email that tells the ball in court what to do on entering `state`. */
export const actionRequired = (submittal: Submittal, state: SubmittalState): Email | null => {
  const to = ballInCourt(submittal, state).map((person) => person.email);
  const name = label(submittal);
  switch (state.status) {
    case "awaitingSubmission":
      return { to, subject: `Action required: submit ${name}`, text: `Submit ${name}.` };
    case "inReview":
      return {
        to,
        subject: `Action required: review ${name}`,
        text: `Review ${name}, step ${state.step + 1} of ${submittal.steps.length}.`,
      };
    case "managerReview": {
      const rejection = state.rejection!;
      return {
        to,
        subject: `${name} was returned`,
        text: `${emailOf(submittal, rejection.approver)} responded ${responseNames[rejection.response]}. Close it, resume the workflow, or return it to the previous step.`,
      };
    }
    case "workflowComplete":
      return {
        to,
        subject: `${name} finished its workflow`,
        text: `Close and distribute ${name}.`,
      };
    case "closed":
      return { to, subject: `${name} is closed`, text: `Distribute ${name}.` };
    case "distributed":
      return null;
  }
};

export const overdueReminder = (submittal: Submittal, state: SubmittalState): Email => ({
  to: ballInCourt(submittal, state).map((person) => person.email),
  subject: `Overdue: ${label(submittal)}`,
  text: `${label(submittal)} is waiting for you.`,
});

export const distribution = (submittal: Submittal, state: SubmittalState): Email => ({
  to: submittal.distribution,
  subject: `Distributed: ${label(submittal)}`,
  text:
    state.rejection === null
      ? `${label(submittal)} is approved.`
      : `${label(submittal)} came back ${responseNames[state.rejection.response]} and needs a revision.`,
});
```

`SubmittalState` is plain data, so the reducer returns it as is, and the XState machine keeps the same fields in its context.

## The reducer

The reducer is two pure functions. `transition` takes the submittal, the state, and an event, and returns the next state. `emails` compares two states and returns the emails that the change sends: a state entered emails its ball in court, an `overdue` emails a reminder, and `distributed` emails the distribution list.

```ts title="reducer.ts"
import {
  actionRequired,
  distribution,
  finishesStep,
  overdueReminder,
  rejects,
  type Email,
  type Submittal,
  type SubmittalEvent,
  type SubmittalState,
} from "./submittal.ts";

/** The first approval step after `step`, or the end of the workflow. */
const advance = (submittal: Submittal, state: SubmittalState, step: number): SubmittalState =>
  step + 1 < submittal.steps.length
    ? { ...state, status: "inReview", step: step + 1, responses: {}, overdue: false }
    : { ...state, status: "workflowComplete", responses: {}, overdue: false };

export const initialState = (submittal: Submittal): SubmittalState => {
  const draft: SubmittalState = {
    status: "awaitingSubmission",
    step: 0,
    responses: {},
    rejection: null,
    overdue: false,
  };
  return submittal.submitters.length > 0 ? draft : advance(submittal, draft, -1);
};

/** The state after `event`. An event that the state doesn't accept, or from the wrong person, returns `state`. */
export const transition = (
  submittal: Submittal,
  state: SubmittalState,
  event: SubmittalEvent,
): SubmittalState => {
  if (event.type === "overdue") return { ...state, overdue: true };
  const fromManager = event.sentBy === submittal.manager.userId;
  if (
    event.type === "close" &&
    fromManager &&
    state.status !== "closed" &&
    state.status !== "distributed"
  ) {
    return { ...state, status: "closed", overdue: false };
  }
  switch (state.status) {
    case "awaitingSubmission":
      return event.type === "submit" &&
        submittal.submitters.some((submitter) => submitter.userId === event.sentBy)
        ? advance(submittal, state, -1)
        : state;
    case "inReview": {
      const approvers = submittal.steps[state.step].approvers;
      if (
        event.type !== "respond" ||
        event.sentBy in state.responses ||
        !approvers.some((approver) => approver.userId === event.sentBy)
      ) {
        return state;
      }
      const responses = { ...state.responses, [event.sentBy]: event.response };
      if (rejects(event.response)) {
        return {
          ...state,
          status: "managerReview",
          responses,
          rejection: { approver: event.sentBy, response: event.response },
          overdue: false,
        };
      }
      return finishesStep(submittal, state.step, responses)
        ? advance(submittal, state, state.step)
        : { ...state, responses };
    }
    case "managerReview":
      if (!fromManager) return state;
      if (event.type === "resume") {
        return finishesStep(submittal, state.step, state.responses)
          ? advance(submittal, state, state.step)
          : { ...state, status: "inReview", overdue: false };
      }
      if (event.type === "returnToPreviousStep") {
        const reset = { ...state, responses: {}, rejection: null, overdue: false };
        if (state.step > 0) return { ...reset, status: "inReview", step: state.step - 1 };
        if (submittal.submitters.length > 0) return { ...reset, status: "awaitingSubmission" };
      }
      return state;
    case "closed":
      return event.type === "distribute" && fromManager
        ? { ...state, status: "distributed" }
        : state;
    case "workflowComplete":
    case "distributed":
      return state;
  }
};

/** The emails that going from `before` to `after` sends; `before` is null at the start. */
export const emails = (
  submittal: Submittal,
  before: SubmittalState | null,
  after: SubmittalState,
): ReadonlyArray<Email> => {
  if (after.status === "distributed") return [distribution(submittal, after)];
  if (before === null || before.status !== after.status || before.step !== after.step) {
    const email = actionRequired(submittal, after);
    return email === null ? [] : [email];
  }
  return !before.overdue && after.overdue ? [overdueReminder(submittal, after)] : [];
};
```

An event that the state doesn't accept returns the same `state`, and `emails` returns no email for it. A response from an approver who already responded, a `distribute` before `closed`, and a `submit` from anyone but a submitter all fall through that way.

## The workflow

The workflow declares the submittal as its input and one `event` signal whose payload is the event without its sender. Its body holds the state, waits for the next event, applies `transition`, and sends what `emails` returns:

```ts title="index.ts"
import {
  array,
  ForgeError,
  boolean,
  defineExtension,
  integer,
  literal,
  object,
  string,
  tool,
  workflow,
  WorkflowSignalTimeoutError,
  type WorkflowStep,
} from "@buildr/sdk";
import { emails, initialState, transition } from "./reducer.ts";
import { daysToAct, type Email, type Response, type SubmittalEvent } from "./submittal.ts";

const person = object({ userId: string(), email: string() });
const response = literal(
  "approved",
  "approvedAsNoted",
  "forRecordOnly",
  "reviseAndResubmit",
  "rejected",
);

const submittalType = object({
  number: string(),
  title: string(),
  revision: integer(),
  manager: person,
  submitters: array(person),
  daysToSubmit: integer(),
  steps: array(
    object({
      daysToRespond: integer(),
      approvers: array(object({ userId: string(), email: string(), required: boolean() })),
    }),
  ),
  distribution: array(string()),
});

const actions = [
  "submit",
  "respond",
  "resume",
  "returnToPreviousStep",
  "close",
  "distribute",
] as const;

const signals = {
  event: object({
    type: literal(...actions),
    response: response.optional(),
    comment: string().optional(),
  }),
};

const output = object({
  revision: integer(),
  rejection: object({ approver: string(), response }).nullable(),
});

interface EventPayload {
  readonly type: (typeof actions)[number];
  readonly response?: Response;
  readonly comment?: string;
}

/**
 * Waits for the next event, for `days` when the ball in court has a due date.
 * A response without a `response` is no event, and neither is the end of a wait
 * without a due date, which Forge ends after 365 days: the body waits again.
 */
const nextEvent = async (
  step: WorkflowStep,
  days: number | null,
): Promise<SubmittalEvent | null> => {
  try {
    const signal = await step.waitForSignal<EventPayload>(
      "event",
      days === null ? {} : { timeout: `${days} days` },
    );
    const payload = signal.payload;
    if (payload.type !== "respond") return { type: payload.type, sentBy: signal.sentBy };
    return payload.response === undefined
      ? null
      : {
          type: "respond",
          response: payload.response,
          comment: payload.comment,
          sentBy: signal.sentBy,
        };
  } catch (error) {
    if (!(error instanceof WorkflowSignalTimeoutError)) throw error;
    return days === null ? null : { type: "overdue" };
  }
};

/**
 * Sends each email in a step of its own, named for the turn that sent it. An email that
 * can't go out mustn't stop the submittal, so the step returns why and the run moves on.
 * A rate limit throws, and the step tries again later.
 */
const sendEmails = async (step: WorkflowStep, turn: number, list: ReadonlyArray<Email>) => {
  for (const [index, email] of list.entries()) {
    if (email.to.length === 0) continue;
    await step.do(
      `${turn}-email-${index}`,
      async (s) => {
        try {
          return await s.email.send({ to: [...email.to], subject: email.subject, text: email.text });
        } catch (error) {
          if (error instanceof ForgeError && error.status !== 429) return { unsent: error.message };
          throw error;
        }
      },
      { retries: { limit: 5, delay: "1 minute", backoff: "exponential" } },
    );
  }
};

const reviewSubmittal = workflow(
  {
    description: "Runs a submittal through submission, approval steps, close, and distribution",
    input: submittalType,
    output,
    signals,
  },
  async ({ step }, submittal) => {
    let state = initialState(submittal);
    await sendEmails(step, 0, emails(submittal, null, state));
    for (let turn = 1; state.status !== "distributed"; turn++) {
      const event = await nextEvent(step, daysToAct(submittal, state));
      if (event === null) continue;
      const next = transition(submittal, state, event);
      await sendEmails(step, turn, emails(submittal, state, next));
      state = next;
    }
    return { revision: submittal.revision, rejection: state.rejection };
  },
);

const startSubmittal = tool(
  {
    description: "Sends a submittal to its workflow: the submitters first, then each approval step",
    input: submittalType,
    output: object({ runId: string() }),
  },
  async (ctx, input) => {
    const started = await ctx.workflows.start("reviewSubmittal", input, {
      key: `${input.number}-rev-${input.revision}`,
    });
    return { runId: started.runId };
  },
);

const actOnSubmittal = tool(
  {
    description:
      "Submits, responds to, resumes, returns, closes, or distributes a submittal, as the caller",
    input: object({
      runId: string(),
      type: literal(...actions),
      response: response.optional(),
      comment: string().optional(),
    }),
  },
  async (ctx, input) => {
    // A payload is JSON, which has no undefined, so pass on only the fields the caller sent.
    const { runId, ...payload } = input;
    const answered = await ctx.workflows.signal({ run: runId, signal: "event", payload });
    return { sequence: answered.sequence };
  },
);

export default defineExtension(
  {},
  {
    tools: { startSubmittal, actOnSubmittal },
    workflows: { reviewSubmittal },
  },
);
```

These parts of the code carry the rules from the start of this page:

- `nextEvent` waits with the due date of the state, which `daysToAct` reads from the submittal, and turns a `WorkflowSignalTimeoutError` into `overdue`. Once a state has reminded its ball in court, it waits without a due date. Forge ends any wait after 365 days, so `nextEvent` turns that end into no event, and the body waits again rather than ending the run `errored`.
- `sendEmails` names each step for its turn and its index, as in `3-email-0`, so that a submittal that goes back to an earlier step sends its emails again under new names.
- `sendEmails` catches a send that Forge refuses, such as `EmailUnavailable` when the day's quota is spent, and returns it as the step's result. Uncaught, the step would fail on every retry and end the run `errored`, with the submittal stuck where it was. Only `EmailRateLimited` (HTTP 429) throws, so the step retries it with backoff. See [Errors](https://buildrforge.com/docs/extensions/email/#errors).
- A `respond` without a `response` is no event, and the body waits again.
- `actOnSubmittal` passes on only the fields that its caller sent. A payload is JSON, so `ctx.workflows.signal` rejects a field whose value is `undefined` with a `TypeError`.

The timeout starts again with each wait, so a step with two required approvers gives the second one a fresh number of days after the first responds. To count from when the state began, record the time in a step and wait until then with a timeout that you compute from it.

## The XState machine

The XState version keeps `submittal.ts` and replaces the reducer with a machine. Each state's `entry` emails its ball in court through an `email` action with params, guards check who sent the event, and `assign` keeps the step, the responses, and the rejection in the context:

```ts title="machine.ts"
import { and, assign, setup } from "xstate";
import {
  actionRequired,
  distribution,
  finishesStep,
  overdueReminder,
  rejects,
  type Email,
  type Response,
  type Submittal,
  type SubmittalEvent,
  type SubmittalState,
} from "./submittal.ts";

type SubmittalContext = Omit<SubmittalState, "status"> & { readonly submittal: Submittal };

/** The context as the shared helpers read it, in the state that XState is entering. */
const stateOf = (context: SubmittalContext, status: SubmittalState["status"]): SubmittalState => ({
  ...context,
  status,
});

const sentBy = (event: SubmittalEvent) => ("sentBy" in event ? event.sentBy : null);

/** This step's responses with the event's response added. */
const withResponse = (context: SubmittalContext, event: SubmittalEvent) =>
  event.type === "respond"
    ? { ...context.responses, [event.sentBy]: event.response }
    : context.responses;

/** Sends `actionRequired` for the state being entered. */
const announce = (status: SubmittalState["status"]) => ({
  type: "email" as const,
  params: ({ context }: { context: SubmittalContext }) =>
    actionRequired(context.submittal, stateOf(context, status))!,
});

export const submittalMachine = setup({
  types: {
    input: {} as Submittal,
    context: {} as SubmittalContext,
    events: {} as SubmittalEvent,
  },
  actions: {
    email: (_, _params: Email) => {},
    nextStep: assign({ step: ({ context }) => context.step + 1, responses: {} }),
    clearOverdue: assign({ overdue: false }),
  },
  guards: {
    hasSubmitters: ({ context }) => context.submittal.submitters.length > 0,
    hasSteps: ({ context }) => context.submittal.steps.length > 0,
    fromManager: ({ context, event }) => sentBy(event) === context.submittal.manager.userId,
    fromSubmitter: ({ context, event }) =>
      context.submittal.submitters.some((submitter) => submitter.userId === sentBy(event)),
    fromWaitingApprover: ({ context, event }) =>
      !(sentBy(event)! in context.responses) &&
      context.submittal.steps[context.step].approvers.some(
        (approver) => approver.userId === sentBy(event),
      ),
    rejects: ({ event }) => event.type === "respond" && rejects(event.response),
    finishesStep: ({ context, event }) =>
      finishesStep(context.submittal, context.step, withResponse(context, event)),
    isLastStep: ({ context }) => context.step + 1 >= context.submittal.steps.length,
  },
}).createMachine({
  context: ({ input }) => ({
    submittal: input,
    step: 0,
    responses: {},
    rejection: null,
    overdue: false,
  }),
  initial: "draft",
  on: {
    close: { guard: "fromManager", target: ".closed" },
  },
  states: {
    draft: {
      always: [
        { guard: "hasSubmitters", target: "awaitingSubmission" },
        { guard: "hasSteps", target: "inReview" },
        { target: "workflowComplete" },
      ],
    },
    awaitingSubmission: {
      entry: ["clearOverdue", announce("awaitingSubmission")],
      on: {
        overdue: {
          actions: [
            assign({ overdue: true }),
            {
              type: "email",
              params: ({ context }) =>
                overdueReminder(context.submittal, stateOf(context, "awaitingSubmission")),
            },
          ],
        },
        submit: [
          { guard: and(["fromSubmitter", "hasSteps"]), target: "inReview" },
          { guard: "fromSubmitter", target: "workflowComplete" },
        ],
      },
    },
    inReview: {
      entry: ["clearOverdue", announce("inReview")],
      on: {
        overdue: {
          actions: [
            assign({ overdue: true }),
            {
              type: "email",
              params: ({ context }) =>
                overdueReminder(context.submittal, stateOf(context, "inReview")),
            },
          ],
        },
        respond: [
          {
            guard: and(["fromWaitingApprover", "rejects"]),
            target: "managerReview",
            actions: assign({
              responses: ({ context, event }) => withResponse(context, event),
              rejection: ({ event }) => ({
                approver: event.sentBy,
                response: event.response as Response,
              }),
            }),
          },
          {
            guard: and(["fromWaitingApprover", "finishesStep", "isLastStep"]),
            target: "workflowComplete",
          },
          {
            guard: and(["fromWaitingApprover", "finishesStep"]),
            target: "inReview",
            reenter: true,
            actions: "nextStep",
          },
          {
            guard: "fromWaitingApprover",
            actions: assign({ responses: ({ context, event }) => withResponse(context, event) }),
          },
        ],
      },
    },
    managerReview: {
      entry: ["clearOverdue", announce("managerReview")],
      on: {
        resume: [
          { guard: and(["fromManager", "finishesStep", "isLastStep"]), target: "workflowComplete" },
          { guard: and(["fromManager", "finishesStep"]), target: "inReview", actions: "nextStep" },
          { guard: "fromManager", target: "inReview" },
        ],
        returnToPreviousStep: [
          {
            guard: and(["fromManager", ({ context }) => context.step > 0]),
            target: "inReview",
            actions: assign({
              step: ({ context }) => context.step - 1,
              responses: {},
              rejection: null,
            }),
          },
          {
            guard: and(["fromManager", "hasSubmitters"]),
            target: "awaitingSubmission",
            actions: assign({ responses: {}, rejection: null }),
          },
        ],
      },
    },
    workflowComplete: {
      entry: ["clearOverdue", assign({ responses: {} }), announce("workflowComplete")],
    },
    closed: {
      entry: ["clearOverdue", announce("closed")],
      on: {
        close: {},
        distribute: { guard: "fromManager", target: "distributed" },
      },
    },
    distributed: {
      type: "final",
      entry: {
        type: "email",
        params: ({ context }) => distribution(context.submittal, stateOf(context, "distributed")),
      },
    },
  },
  output: ({ context }) => ({ revision: context.submittal.revision, rejection: context.rejection }),
});
```

The `email` action has an empty implementation, because the body sends each email in a step. A machine run through `createActor` runs its actions and its delayed `after` transitions in memory, which a replay doesn't keep, so drive the machine with XState's pure `initialTransition` and `transition` functions instead. They return the next snapshot and the actions to run, run nothing themselves, and apply each `assign` as they compute the snapshot. Use the wait's timeout in place of `after`.

In `index.ts`, import the machine in place of the reducer, and replace `reviewSubmittal`:

```ts title="index.ts (excerpt)"
import { initialTransition, transition as machineTransition } from "xstate";
import { submittalMachine } from "./machine.ts";
import type { Status } from "./submittal.ts";

const emailsIn = (actions: ReadonlyArray<{ type: string; params?: unknown }>) =>
  actions.filter((action) => action.type === "email").map((action) => action.params as Email);

const reviewSubmittal = workflow(
  {
    description: "Runs a submittal through submission, approval steps, close, and distribution",
    input: submittalType,
    output,
    signals,
  },
  async ({ step }, submittal) => {
    let [snapshot, actions] = initialTransition(submittalMachine, submittal);
    await sendEmails(step, 0, emailsIn(actions));
    for (let turn = 1; snapshot.status !== "done"; turn++) {
      // The machine's states are flat, so its value is the name of one.
      const state = { ...snapshot.context, status: snapshot.value as Status };
      const event = await nextEvent(step, daysToAct(submittal, state));
      if (event === null) continue;
      [snapshot, actions] = machineTransition(submittalMachine, snapshot, event);
      await sendEmails(step, turn, emailsIn(actions));
    }
    return snapshot.output;
  },
);
```

The `draft` state decides where the workflow starts with `always` transitions, so the snapshot that `initialTransition` returns already rests in `awaitingSubmission`, `inReview`, or `workflowComplete`.

Declare XState in the extension's `package.json` with an exact version, so that each build installs the XState that your tests ran. A run keeps the build of the version that it started on, so its replays always use the same XState. See [npm packages and Node built-ins](https://buildrforge.com/docs/extensions/builds-and-runtime/#npm-packages-and-node-built-ins).

```json title="package.json"
{ "dependencies": { "@buildr/sdk": "^1.0.0", "xstate": "5.33.3" } }
```

### Choosing between them

Both versions run the same workflow and send the same emails. The reducer needs no package, and TypeScript's narrowing checks each state's fields. The XState machine states its transitions as data that XState's visual tools can draw, at the cost of a dependency and guards that read the event's sender.

## Submittals in use

The submittal manager starts a submittal with `startSubmittal`. Its key is the submittal's number and revision, so starting the same revision twice returns the first run:

```sh
forge extensions call-extension-installation-tool --repo "$PROJECT_REPO" \
  --name project-controls.submittals --tool startSubmittal \
  --data '{"number":"05 12 00-3","title":"Structural steel shop drawings","revision":0,
    "manager":{"userId":"user_…","email":"gc@example.com"},
    "submitters":[{"userId":"user_…","email":"steel@example.com"}],"daysToSubmit":5,
    "steps":[{"daysToRespond":10,"approvers":[{"userId":"user_…","email":"architect@example.com","required":true}]}],
    "distribution":["steel@example.com"]}'
```

Each person's `userId` is their Forge user ID, which the run compares with the `sentBy` of each answer.

Each person acts by answering the run's `event` signal, through `actOnSubmittal` or directly. An approver who responds _Revise and Resubmit_ sends:

```sh
forge extensions create-extension-installation-workflow-run-signal --repo "$PROJECT_REPO" \
  --name project-controls.submittals --run "$RUN_ID" --signal event \
  --data '{"payload":{"type":"respond","response":"reviseAndResubmit","comment":"Show the connection details at grid C"}}'
```

The run reads the approver as `sentBy`, so nobody can respond for someone else. A signal from someone who doesn't hold the ball in court is accepted and changes nothing. To tell the sender, have `actOnSubmittal` read the run and refuse first.

Once the run is `complete`, its `output` holds the revision and the rejection. When `rejection` isn't `null`, start the next revision with `startSubmittal` and the revision number raised by one. Its workflow starts again from the submitters.

## Testing the workflow

Test it on a scratch branch, as [Testing an extension](https://buildrforge.com/docs/extensions/testing/) describes: start a submittal with `startSubmittal`, read the run until it is `waiting`, answer each wait with `forge extensions create-branch-extension-workflow-run-signal`, and read the run after each answer. An answer the workflow accepts only from a named member needs that member to send it. The reducer is plain TypeScript, so test its transitions locally by calling it with a state and an event, without a run.

Source: https://buildrforge.com/docs/extensions/workflows/state-machines/index.mdx
