# Failures and exit codes

A failure is a run that stopped before it could report findings: bad flags, a broken config, a missing input or a thrown error. readerly turns each one into a `Failure` and prints it in the reader's format, with an exit code that says what to do next.

## Exit codes

| Code | Meaning | Comes from |
| --- | --- | --- |
| `0` | ok | `out.end()` with status `ok` |
| `1` | failed | errors in the run, a `config` or `runtime` failure |
| `2` | change the invocation | a `usage` failure or `action_required` |
| `3+` | your tool's own | `failure(kind, message, { exitCode })` |

`exitCodes` from `readerly/envelope` holds the first three as `{ ok: 0, failed: 1, usage: 2 }`. Code 2 means the caller has to change the command, because running it again as is gives the same result. An agent reads the `fix:`, `missing:` and `rerun:` lines and changes the command.

## The Failure envelope

```ts [types.ts]
type FailureKind = "usage" | "config" | "runtime" | "action_required";

interface Failure {
  schema?: string;
  kind: FailureKind;
  status: Status;
  exitCode: number;
  error: { code?: string; message: string; why?: string; fix?: string; docs?: string; file?: string };
  missing?: Missing[];
  rerun?: string;
}
```

| Kind | For | `status` | `exitCode` |
| --- | --- | --- | --- |
| `usage` | a bad flag or value | `failed` | `2` |
| `config` | a config file that can't be used | `failed` | `1` |
| `runtime` | anything that broke while running | `failed` | `1` |
| `action_required` | an input only the caller can give | `action_required` | `2` |

`missing` lists the inputs an `action_required` failure needs, each as `{ field, flag?, env?, choices? }`. `rerun` is the command to run instead. `schema` replaces the run's schema in `json` output.

## Building failures

`failure(kind, message, extra?)` returns a `Failure`. `extra` takes the error fields (`code`, `why`, `fix`, `docs`, `file`) and can override `schema`, `status`, `exitCode`, `missing` and `rerun`.

To stop a command from deep inside it, throw a `FailureError`, which carries the failure on `.failure`. `actionRequired(message, missing, extra?)` returns one ready to throw.

```ts [build.ts]
import { createOut } from "readerly";
import { FailureError, actionRequired, failure } from "readerly/envelope";

export async function build(argv: string[]): Promise<number> {
  const out = createOut({ tool: "acme", command: "build", argv });
  try {
    out.log("Reading config");
    const config = await loadConfig();
    if (!config.entry) {
      throw new FailureError(
        failure("config", "acme.config.ts has no entry.", {
          code: "ACME_CONFIG",
          why: "The build needs one entry point",
          fix: 'Add entry: "src/index.ts" to acme.config.ts',
          docs: "https://acme.dev/config#entry",
          file: "acme.config.ts",
        }),
      );
    }
    if (!config.target) {
      throw actionRequired("Target is required.", [{ field: "target", flag: "--target" }], {
        rerun: "acme build --target <target>",
      });
    }
    // …
    return out.end();
  } catch (error) {
    return out.fail(error);
  }
}
```

`out.fail(error)` takes anything thrown, renders it and returns the exit code. Return that code from your command. `out.ask` and `out.confirm` throw `action_required` and usage failures, so the same `catch` reports those too. See [Prompts and input](https://readerly.loadsheet.dev/guide/prompts).

`toFailure(error)` is the conversion `out.fail` uses:

- a `FailureError` keeps its own failure,
- an `Error` becomes `runtime` with the error's message,
- anything else becomes `runtime` with `String(value)` as the message, or `Unknown error.` when that throws.

Call `out.fail` or `out.end` once. A second call throws `out.end or out.fail was already called.`

## Where failures go

In `text`, a failure goes to stderr, so `acme build > report.txt` doesn't write it into the report. Logs already printed stay on stdout.

In `agent`, `json` and `jsonl`, the failure goes to stdout. A program that parses stdout gets one document either way, and `status` tells it which kind.

## How each format prints a failure

The `config` failure from the example above, with exit code 1.

::code-group

```text [text (stderr)]
✖ acme.config.ts has no entry.
├▶ why: The build needs one entry point
├▶ fix: Add entry: "src/index.ts" to acme.config.ts
╰▶ see: https://acme.dev/config#entry
```

```text [agent]
acme build: failed. acme.config.ts has no entry.
fix: Add entry: "src/index.ts" to acme.config.ts
```

```json [json]
{
  "schema": "acme.build/v1",
  "status": "failed",
  "error": {
    "code": "ACME_CONFIG",
    "why": "The build needs one entry point",
    "fix": "Add entry: \"src/index.ts\" to acme.config.ts",
    "docs": "https://acme.dev/config#entry",
    "file": "acme.config.ts",
    "message": "acme.config.ts has no entry."
  }
}
```

```text [jsonl]
{"type":"version","schema":"acme.build/v1","tool":"acme"}
{"type":"log","message":"Reading config"}
{"type":"error","code":"ACME_CONFIG","why":"The build needs one entry point","fix":"Add entry: \"src/index.ts\" to acme.config.ts","docs":"https://acme.dev/config#entry","file":"acme.config.ts","message":"acme.config.ts has no entry."}
{"type":"result","status":"failed","message":"acme.config.ts has no entry.","data":{}}
```

::

The person at a terminal sees `why:` and `see:` every time. A coding agent gets `why:` and `docs:` only with `--full`, and under a tight [budget](https://readerly.loadsheet.dev/guide/budget) readerly drops `docs`, then `why`, then `fix`, but never the verdict, `missing:` or `rerun:`.

A thrown `Error("ENOSPC: no space left on device")` is a `runtime` failure. A person at a terminal gets `✖ ENOSPC: no space left on device` on stderr, and a coding agent gets:

```text
acme build: failed. ENOSPC: no space left on device.
```

With `--json`, the document has the message only:

```json
{
  "schema": "acme.build/v1",
  "status": "failed",
  "error": {
    "message": "ENOSPC: no space left on device"
  }
}
```

## action_required in every format

[`test/golden.test.ts`](https://github.com/loadsheet/readerly/blob/main/test/golden.test.ts) runs `acme deploy --prod` without an account, which exits with code 2. A person at a terminal gets this on stderr, with stdout empty:

```text
✖ Account is required.
├▶ fix: Pass --account.
├▶ missing: --account (ACME_ACCOUNT), one of personal, team
╰▶ rerun: acme deploy --prod --account <account>
```

A coding agent gets the same lines on stdout, after a verdict:

```text
acme deploy: action required. Account is required.
fix: Pass --account.
missing: --account (ACME_ACCOUNT), one of personal, team
rerun: acme deploy --prod --account <account>
```

`json` prints `status: "action_required"` with `error`, `missing` and `rerun`. `jsonl` prints a `version` record, an `error` record with the same fields, and a `result` record with `"status":"action_required"`. Both are on the [JSON page](https://readerly.loadsheet.dev/guide/json#failures).

## Bad reader flags

A bad `--format` or `--max-chars` doesn't throw from `createOut`. readerly stores the usage failure and prints it at `out.end()` or `out.fail()`, with exit code 2. A person at a terminal who passes `--format yaml` gets:

```text
✖ --format yaml is not a format. Use one of: text, agent, json, jsonl.
╰▶ fix: Pass --format with one of: text, agent, json, jsonl.
```

The list names every format the tool accepts, including the ones it adds with `formats`. See [Formats](https://readerly.loadsheet.dev/guide/formats).

## Your own exit codes

Pass `exitCode` to give a failure a code above 2:

```ts [build.ts]
throw new FailureError(failure("runtime", "Tests failed to start.", { exitCode: 3 }));
```

`out.fail` returns `3`, and a coding agent running `acme build` gets `acme build: failed. Tests failed to start.` readerly reserves 0, 1 and 2, so document what your other codes mean.

Next: [JSON and JSONL](https://readerly.loadsheet.dev/guide/json).

<!-- vitehub-docs:section-links -->
## In this section

- [Introduction](https://readerly.loadsheet.dev/raw/guide.md)
- [Installation](https://readerly.loadsheet.dev/raw/guide/installation.md)
- [Readers](https://readerly.loadsheet.dev/raw/guide/readers.md)
- [Coding agents](https://readerly.loadsheet.dev/raw/guide/agents.md)
- [Formats](https://readerly.loadsheet.dev/raw/guide/formats.md)
- [Shared flags](https://readerly.loadsheet.dev/raw/guide/flags.md)
- [Color and glyphs](https://readerly.loadsheet.dev/raw/guide/color.md)
- [Diagnostics](https://readerly.loadsheet.dev/raw/guide/diagnostics.md)
- [Budget](https://readerly.loadsheet.dev/raw/guide/budget.md)
- [Prompts and input](https://readerly.loadsheet.dev/raw/guide/prompts.md)
- [Failures and exit codes](https://readerly.loadsheet.dev/raw/guide/failures.md) (this page)
- [JSON and JSONL](https://readerly.loadsheet.dev/raw/guide/json.md)
- [Custom renderers](https://readerly.loadsheet.dev/raw/guide/renderers.md)
- [API](https://readerly.loadsheet.dev/raw/guide/api.md)

Next: [JSON and JSONL](https://readerly.loadsheet.dev/raw/guide/json.md)

All pages: [llms.txt](https://readerly.loadsheet.dev/llms.txt)
