# Diagnostics

URL: /docs/agents/diagnostics
Markdown: /docs/agents/diagnostics.md

> Reference for the JSON Lines diagnostics produced by sakura check --json, including record kinds, error codes, and fix impact classes.

When a tool or an agent reads compiler output, it reads these records. This page shows what
`sakura check --json` and the other `--json` commands print, what each field means, and the
error codes and exit codes to expect.

A **diagnostic** is one problem the compiler found: an error, a warning or a note. Every
diagnostic has a stable code (such as `V3001`), exact byte positions in the source, the expected
and actual values, links to the problem that caused it, and fixes that say what they change.
The CLI, the editor language server and the [MCP server](/docs/agents/mcp) report the same data,
each in its own packaging.

```bash
sakura check --json
sakura test --json
```

`--json` writes **JSON Lines**: one JSON object (a **record**) per line. The human-readable
output is rendered from the same data.

## An example [#an-example]

A function's **effect row**, written after `!`, lists the side effects it may perform. The program below prints with `Console` but leaves `Console` out of `greet`'s effect row:

```sakura expect=V3001
fn greet(name: String) -> Unit {
  Console.print("hello, {name}")
}
```

`sakura check --json` reports it as one line. Here it is spread over several lines, with example paths, shortened hashes and ids, and only the first fix:

```json
{
  "schema_version": "1.0",
  "kind": "diagnostic",
  "id": "d:7f3a",
  "code": "V3001",
  "severity": "error",
  "phase": "effect",
  "message": "function `greet` performs `Console`, which its signature does not allow (allowed: `{}`)",
  "snapshot": "sha256:91c0",
  "symbol_id": "hello::main::greet",
  "spans": [
    { "uri": "file:///work/hello/src/main.sak", "content_hash": "sha256:4be2",
      "start_byte": 3, "end_byte": 8, "role": "primary" },
    { "uri": "file:///work/hello/src/main.sak", "content_hash": "sha256:4be2",
      "start_byte": 35, "end_byte": 65, "role": "cause", "label": "`Console.print` performs `Console` here" }
  ],
  "related_ids": [],
  "expected": { "render": "{}", "row": { "labels": [], "tail": null } },
  "actual": { "render": "{Console}", "row": { "labels": [{ "effect": "std::Console", "args": [] }], "tail": null } },
  "obligation": null,
  "counterexample": null,
  "explanation_uri": "sakura://explain/V3001",
  "fixes": [
    { "id": "f:01", "title": "Add `Console` to the signature",
      "applicability": "suggested", "impact": "interface_change",
      "edits": [ { "span": { "uri": "file:///work/hello/src/main.sak", "content_hash": "sha256:4be2",
                             "start_byte": 30, "end_byte": 30, "role": "primary" },
                   "replacement": " ! {Console}" } ] }
  ]
}
```

For `V3001` the compiler offers two fixes: add the effect to the signature (impact `interface_change`), or handle it inside the function with `with` (impact `local`). The local fix is `incomplete`: the agent must supply a suitable handler. The tables below explain every field.

## Record kinds [#record-kinds]

Every record has a `kind` field that says what it is:

| `kind` | Meaning |
| --- | --- |
| `diagnostic` | An error, warning or note, as in the example above. |
| `hole` | A [typed hole](/docs/agents/typed-holes) with its context. |
| `obligation` | Emitted by `sakura verify --json`: `proved`, `disproved`, `unknown` or `unsupported`. See [verify](/docs/agents/verify). |
| `test` | A test result from `sakura test --json`. |
| `audit` | A trust, totality, refinement or external site from `sakura audit --json`. See [Trust audit](/docs/agents/audit). |
| `symbol_query` | The single record `sakura doc --json` writes. See [Offline API search](/docs/agents/doc). |
| `summary` | End of `check`, `fix` and `build` (and of a `test` run that does not compile). `summary.truncated` is `true` if output hit the cap. |
| `test_summary` | End of `sakura test --json`. |
| `audit_summary` | End of `sakura audit --json`. |
| `verify_summary` | End of `sakura verify --json`. |

Three more records are not on stdout: `target/sakura/manifest.json` (`kind: "manifest"`, from
`sakura build --manifest` and `sakura verify`), the runtime `defect` record on stderr
(below) and the `regression` record that `sakura test --contracts` stores in
`tests/regressions/<fn>.json` ([Testing](/docs/tour/testing#catching-an-ensures-bug)). Every
record carries `kind` and `schema_version`; the fields of each kind and
version are listed in [`compiler/contracts/json.txt`](https://github.com/icantcodefyi/sakuralang/blob/main/compiler/contracts/json.txt),
which a test checks every command's output against. A usage error (a wrong flag, a missing
file) is text on stderr with exit `2`, even with `--json`.

Each closing record has one shape, every field present: `summary` has `snapshot`, `errors`,
`warnings`, `notes`, `total`, `emitted`, `truncated` and `holes`; `test_summary` has
`passed`, `failed`, `skipped`, `total` and `seed`; `audit_summary` has `snapshot`, `sites`
and `by_site`; `verify_summary` (version 1.0, while verify's other records are 1.1) has the
`summary` counts without `holes`, plus `proved`, `disproved`, `unknown`, `unsupported` and
`reused`. Up to 0.1.0, all four were `kind: "summary"` (verify's at 1.1); since
1.0.0-beta.1 each command ends with its own kind.

For the `V1002`, `V2002` and `V4004` changes in 0.1.0 and syntax-error suppression by
source location, see [0.1.0's changes](/docs/changes#diagnostics-and-json).

## Fields [#fields]

| Field | Type | Meaning |
| --- | --- | --- |
| `schema_version` | string | Version of this record format: `"1.0"`. |
| `kind` | string | `"diagnostic"`. |
| `id` | string | Unique per occurrence in this run. |
| `code` | string | Stable class, such as `V3001`. See [codes](#error-codes). |
| `severity` | string | `error`, `warning`, or `note`. |
| `phase` | string | `lex`, `parse`, `resolve`, `type`, `effect`, `pattern`, `contract`, `capability`, `verify`, `package`, or `internal`. |
| `message` | string | One sentence naming the symbols involved in backticks. |
| `snapshot` | string | Hash of the workspace snapshot that was checked. |
| `symbol_id` | string or null | The symbol the diagnostic is about. |
| `spans` | array | Source locations, each with `uri`, `content_hash`, `start_byte`, `end_byte`, `role`, `label`. |
| `related_ids` | array | Ids of root-cause diagnostics this one cascades from. Empty for a root cause. |
| `expected` | object or null | What was required: a `render` string, and a structured `row` for effect rows. |
| `actual` | object or null | What was found, in the same shape. |
| `obligation` | object or null | `id`, `clause` (for example `"ensures bounded"`), and `status`. |
| `counterexample` | object or null | `inputs` and a `trace`, when one is known. |
| `explanation_uri` | string | `sakura://explain/<code>`. Same content as `sakura explain <code>` and the MCP `explain_diagnostic` tool. |
| `fixes` | array | Zero or more fixes. See below. |

A **span** is a range of bytes in one file. Its `role` is one of `primary` (where the problem is), `cause`, `definition` or `use`.

### Rules [#rules]

- Byte offsets are zero-based, half-open, and count UTF-8 bytes. There are no line or column numbers.
- `content_hash` must match the file before any edit is applied.
- The edits in one fix are applied atomically and rejected if they overlap.
- Records are ordered root causes first (empty `related_ids`), then by position.
- Output is capped at 200 diagnostics per run, with `summary.truncated: true`.

## Fixes [#fixes]

| Field | Meaning |
| --- | --- |
| `id` | Fix id, accepted by `sakura fix --apply`. |
| `title` | Short imperative description. |
| `applicability` | `machine_applicable`, `suggested`, or `incomplete`. |
| `impact` | What the fix changes. See below. |
| `edits` | List of `{ span, replacement }`. A span with equal start and end is an insertion. |

### Impact classes [#impact-classes]

| `impact` | Changes | Suggested agent policy |
| --- | --- | --- |
| `local` | Code inside one body; no signature changes. | Apply if `machine_applicable`. |
| `behavior_change` | What the code does, without changing its signature. | Apply only if it matches the task. |
| `interface_change` | A signature, effect row, or error union. | Apply only if the task needs it, and report it for review. |
| `contract_change` | A `requires`, `ensures`, or `where` clause. | Never apply unless a human asks. |
| `authority_change` | Permissions or capabilities. | Never apply unless a human asks. |

Compiler fixes with `interface_change`, `contract_change`, or `authority_change` impact are never `machine_applicable`. No fix ever widens authority or weakens a contract by itself.

`sakura fix` lists fixes with their impact class. It applies only `machine_applicable` fixes unless given ids with `--apply id,…`, and it never applies `contract_change` or `authority_change`. `--preview` shows the edits without writing.

### Frozen specs [#frozen-specs]

With `--frozen-specs <symbols|all>`, `sakura check` and `sakura fix` compare selected signatures, effect rows, error unions, contracts, test/property bodies and permissions against Git `HEAD` (or `--since <rev>`). MCP `check_patch` reports violations against its base snapshot, and `apply_patch` rejects them, only when each call receives the optional `frozen_specs` argument. The diagnostic is `V8020 spec_frozen` and names the clause. This stops an agent from passing a check by editing the spec.

## Error codes [#error-codes]

Codes are `V` + a phase digit + three digits for errors, `W` for warnings, and `D` for runtime defects. Codes are never reused or renumbered; retired codes stay documented. `sakura explain <code>` reads the diagnostic registry. Each code has a generated [error page](/docs/errors) with its explanation, a program that triggers it and, for most codes, the fixed program; `explanation_uri` (`sakura://explain/<code>`) maps to `/docs/errors/<code>`, and `sakura explain` prints that URL after its text.

| Phase digit | Area | Examples |
| --- | --- | --- |
| `0` | Lexing and parsing | `V0001` syntax error, `V0007` reserved keyword, `V0010` chained comparison, `V0011` call-site type arguments, `V0014` named argument |
| `1` | Resolution and modules | `V1002` unresolved name (offers the import as a fix), `V1004` wrong casing, `V1006` item not `pub` or opaque constructor, `V1007` wrong kind of name, `V1010` unknown attribute, `V1030` import cycle, `V1040` assignment to a `let`, `V1041` jump outside a loop |
| `2` | Types | `V2031` `Secret` is not `Show`, `V2032` constraint not satisfied, `V2040` unused value, `V2041` lambda or `try` body assigns an outer `var`, `V2050` hole in build |
| `3` | Effects and handlers | `V3001` effect not allowed, `V3011` handler clauses do not match the operations, `V3020` test needs a handler |
| `4` | Patterns | `V4001` non-exhaustive match, `V4002` redundant arm |
| `5` | Contracts and refinements | `V5001` predicate outside the contract subset |
| `6` | Capabilities, resources, escape | `V6002` capability escapes its scope, `V6003` resource escapes, `V6010` non-std effect in `main` |
| `7` | Tests and verification | `W7001` property discard budget, `W7002` vacuous obligation |
| `8` | Packages, manifest, runtime version, frozen specs | `V8001` no entry point, `V8002` reserved package name, `V8003` WebAssembly module and host from different releases, `V8004` external unsupported on the target, `V8005` `[dependencies]` refused, `V8006` invalid manifest, `V8020` spec frozen |
| `9` | Internal | Compiler bugs |

Other warnings include `W1002` (a local shadows an import), `W4010` (catch-all `_` on an open error union), `W5005` (an O(n) contract on a hot path), `W7001` (property generator discard budget exceeded), `W7002` (a proof over impossible assumptions), and `W8001` (a `List`, `Map` or `Set` update must copy because an earlier version is still in use).

A **defect** is an error found while the program runs, not by `sakura check`. It ends the running task; if `main` defects, the program writes one `defect` record to stderr and exits with status 70:

```json
{"schema_version":"1.0","kind":"defect","code":"D002","message":"division by zero"}
```

| Code | Raised by |
| --- | --- |
| `D001` | `Int` overflow |
| `D002` | `/` or `%` by zero |
| `D003` | `Int` beyond ±(2^53−1) on the JavaScript backend |
| `D004` | `Float.round` or `Float.to_int_checked` of NaN or ±∞ |
| `D010` | failed refinement in a checked introduction (`T.from`) |
| `D011` | a contract predicate itself defected |
| `D020`, `D021` | `requires` violated (caller blamed), `ensures` violated (callee blamed) |
| `D030` | `Option.expect` on `None` |
| `D031` | `String.slice` off a character boundary |
| `D090`, `D091` | runtime-internal error, host operation failed |
| `D092`–`D095` | WebAssembly runtime limits: a reference count overflow, a failed finalizer, a callback after its handler ended, a join on a retired fiber (`D095` is also a `Task.join` after `Task.cancel`, on every backend) |
| `D096` | the WebAssembly heap limit was reached or memory could not grow |

## Exit codes [#exit-codes]

| Code | Meaning |
| --- | --- |
| `0` | OK. |
| `1` | Diagnostics with errors, a disproved obligation, formatting differences under `fmt --check`, or `main` ended with an uncaught `Fail` (stderr: `error: main failed with <Show of the error>`). |
| `2` | Usage error. |
| `3` | Test failures. |
| `70` | Defect at runtime. |
| `75` | Permission denied at startup. |

## Stability [#stability]

Diagnostic codes are **stable from v1.0.0-beta.1** under [RFC 0001](/docs/stability): a code is never reused or renumbered, and a retired code stays reserved. The `--json` records, their fields and the exit codes are proposed as stable from the same version, with fields only added within a major; each command's own closing kind (above) dates from 1.0.0-beta.1. Messages, labels and the terminal rendering are not a contract and keep improving.

## Next [#next]

[Typed holes](/docs/agents/typed-holes): writing a program one `?hole` at a time.
