# Stoic reference

The whole language and toolchain: every command, the syntax and grammar,
tests, locking, results, verifying, several agents, the gate, CI, editors.
For a first look, read the [README](../README.md); to write a spec quickly,
the [guide](WRITING.md) (`stoic guide`). Every command also prints its own
usage and options: `stoic help COMMAND`.

## Contents

- [Commands](#commands)
- [Syntax](#syntax)
  - [Fine-tuning with notes](#fine-tuning-with-notes)
  - [Kept comments](#kept-comments)
  - [Strictness: strict and can bend](#strictness-strict-and-can-bend)
  - [Binding data](#binding-data)
  - [Nothing is a keyword](#nothing-is-a-keyword)
  - [Beyond UI: data, databases, infra, CI/CD](#beyond-ui-data-databases-infra-cicd)
  - [Frameworks and dependencies](#frameworks-and-dependencies)
  - [Reuse](#reuse)
  - [Grammar](#grammar)
  - [JSON output](#json-output)
- [Tests: locked and enforced](#tests-locked-and-enforced)
  - [Defining tests](#defining-tests)
  - [Or-values: a value the limits don't cover](#or-values-a-value-the-limits-dont-cover)
- [Locking](#locking)
- [What verify can't enforce](#what-verify-cant-enforce)
  - [No rule without a witness](#no-rule-without-a-witness)
- [Results](#results)
  - [Stoic values](#stoic-values)
  - [Reporters](#reporters)
- [Verifying](#verifying)
  - [Diff coverage: new code a locked test must run](#diff-coverage-new-code-a-locked-test-must-run)
- [Working with several agents](#working-with-several-agents)
  - [Segments: who owns what](#segments-who-owns-what)
  - [Claims and fencing tokens](#claims-and-fencing-tokens)
- [Handing a spec to an agent](#handing-a-spec-to-an-agent)
- [Spec first, as agents write: `stoic gate`](#spec-first-as-agents-write-stoic-gate)
- [CI](#ci)
- [Editor support](#editor-support)
- [Starting a project](#starting-a-project)
- [Formatting](#formatting)
- [Architecture](#architecture)
- [Stoic specifies itself](#stoic-specifies-itself)

## Commands

Each release has an installer for macOS and Linux
(`curl --proto '=https' --tlsv1.2 -LsSf https://github.com/stoic-lang/stoic/releases/latest/download/stoic-lang-installer.sh | sh`),
one for Windows
(`powershell -ExecutionPolicy Bypass -c "irm https://github.com/stoic-lang/stoic/releases/latest/download/stoic-lang-installer.ps1 | iex"`),
a Homebrew formula (`brew install stoic-lang/tap/stoic`) and a crate
(`cargo install stoic-lang`, which installs the command `stoic`). They work once
the first release is published; before that, or for an unreleased commit,
build from the repository.

```sh
cargo install --git https://github.com/stoic-lang/stoic stoic-lang  # or, in a clone: cargo install --path .
stoic FILE.stoic                 # prose (default)
stoic FILE.stoic --format spec   # bullet tree
stoic FILE.stoic --format json   # resolved model, for tooling: {"elements": [...], "comments": [...]}
stoic < FILE.stoic               # stdin (a bare `stoic` on a terminal prints the usage instead)
stoic spec/*.stoic               # several files (or a folder), each after a `==> FILE <==` line
stoic --version                  # or -V
stoic tests FILE.stoic           # list the tests FILE defines, by ID
stoic tests .                    # …or every .stoic file under a folder
stoic lock FILE.stoic...         # freeze tests + spec into stoic.lock (files or folders)
stoic lock . --per-test          # …listing each changed test on its own line, never grouped by target
stoic lock . --as agent-b        # …only the segments agent-b owns in stoic.segments (refuses any other change)
stoic lock spec --lock spec/stoic.lock  # …specs in spec/, locked beside them (every command that reads a lock takes --lock)
stoic lock . --force-unlock      # …past a guard another host left over 10 minutes ago (see Locking)
stoic verify results.txt         # check test results against the lock
stoic verify results.txt --strict  # …also failing on unlocked tests and what verify can't enforce (CI's check)
stoic verify results.txt --run CMD   # …running the tests (CMD) first, so only fresh results count
stoic verify results.txt --against origin/main  # …against the lock committed there
stoic verify results.txt --against origin/main --coverage lcov.info  # …and fail on new code no locked test runs (with --strict)
stoic verify /dev/null --no-against  # …the working copy's lock, said explicitly: every test's state
stoic verify results.txt --watch # rerun on every change to the results or specs
stoic verify results.txt --per-test  # one DRIFT line per test, never grouped by target
stoic verify results.txt --as agent-b  # …counting agent-b's tests apart from others'
stoic check spec                 # before relocking: compile, fmt --check and drift, in one call
stoic gate src/app.js            # spec first: may an agent write this file now? exit 0 allow, 2 deny
stoic gate --staged              # …for what git has staged (git's pre-commit hook)
stoic gate --hook claude-code    # …answering an agent tool's pre-write hook event on stdin
stoic gate --install all git     # write those hooks: Claude Code, Codex, Gemini CLI, Factory, AGENTS.md, the skill, git
stoic gate --install skill       # …or just the agent skill (.claude/skills, .agents/skills, .kiro/skills)
stoic gate --refactor "why"      # declare a ticket that changes no behaviour, so code may change
stoic segments                   # who owns what (stoic.segments), claims, and the reuse between segments
stoic claim billing --as agent-a # claim a segment on the stoic-claims branch, with a fencing token
stoic claim billing --as agent-b --take-over  # …once it expired (--ttl 30m sets how long a claim lasts)
stoic release billing --as agent-a  # …and end the claim
stoic review results.txt --as product  # for an owner: what waits in its segments (changes, disputes, WRONG tests)
stoic review results.txt --as product --approve  # …relock them as product (--reject: say what to revert)
stoic review results.txt --as product --accept-observed ID  # …take ID's observed values into the spec, then relock
stoic merge-lock --install       # merge stoic.lock by key when git merges branches (this clone)
stoic merge-lock --check         # …then, once the specs are merged: tests changed only in combination
stoic merge-lock BASE OURS THEIRS [PATH]  # the driver git runs: THEIRS merged into OURS by key
stoic brief FILE.stoic...        # instructions for an AI coding agent (files or folders)
stoic brief FILE.stoic --role owner  # …for an agent that owns the spec and changes it first
stoic brief FILE.stoic --as agent-b  # …saying which elements agent-b owns and must leave alone
stoic harness --lang node        # a results reporter for the tests (node, python or sh)
stoic harness --lang node --out stoic-results.cjs  # …written to a file
stoic fmt .                      # format every .stoic file in place (--check for CI, - for stdin)
stoic init [DIR]                 # start a project: example spec, CI workflow, lock merge rule (--force overwrites)
stoic guide                      # the short guide to writing a spec (docs/WRITING.md)
stoic guide --skill              # the agent skill (SKILL.md) that teaches an agent the loop
stoic lsp                        # language server on stdio (--stdio is accepted, for editors that pass it)
stoic help [COMMAND]             # every command and option, or just COMMAND's (as stoic COMMAND --help)
```

New to writing specs? Start with [the guide](WRITING.md) (`stoic guide`):
the loop, the shape that works for code modules, how many tests to write,
and how to change a spec later.

Diagnostics go to stderr. The exit code is 1 when there are errors (or
`stoic verify` fails) and 2 on bad arguments, which print the error and then
that command's help. Each command takes only its own options, so one meant
for another is a bad argument, not silently ignored: `stoic lock . --strict`
says `stoic lock doesn't take --strict; it takes --lock, --force-unlock,
--per-test, --as`. So does a format a command doesn't print: compiling takes
`--format prose|spec|json`, `stoic tests` and `stoic brief` take `prose` (their
usual output) or `json`. Compiling several files, or a folder, compiles each
in turn: prose and spec print each after a `==> PATH <==` line, json prints
one array of `{"file": …, "spec": …}`, and any file with errors makes the
exit 1 (the others are still printed). `stoic --help` (or `stoic help`) lists every command
and option; `stoic help lock` (or `stoic lock --help`) shows just one
command's usage and options.

## Syntax

| Syntax | Meaning |
| --- | --- |
| `<anything ... />` or `<anything ...> children </anything>` | an element; leaving it unclosed at end of file is a warning |
| `<table="employees">`, `<text=x>` | element bound to data / state (quotes optional for one word) |
| `@click=increment`, `@click="increment x"` | a handler: name or plain-words instruction, passed through verbatim |
| `@clk`, `@swipe_left`, … | any event name; passed through verbatim for the reader to interpret |
| `@*` | every event |
| `@~hover` | an animation on hover; `@~+click` quick, `@~-click` slow |
| `@&submit="save draft"` | runs in the background (doesn't block), like `&` in a shell; combine as `@&~click` |
| `<row* ...>` | repeats once per entry of the parent's data |
| `#id(sort, filter, pin)` | field with capabilities, passed through verbatim: "supports `sort`, `filter`, and `pin`" |
| `#more([add, remove, update])` | actions (on each repeated child, if there is one) |
| `#name(>1, <=32)` | limits: `>` `>=` `<` `<=` `=`; "must be more than 1 and at most 32". Length, count or value is for the reader to infer |
| `#name(!" ")` | must not contain `" "` |
| `#cycles(>=1, \|null)` | or a value: "must be at least 1, or null"; the field takes `null` whatever its limits say (see [Or-values](#or-values-a-value-the-limits-dont-cover)) |
| `#email!("email")`, `<form!>`, `@submit!=save` | strict: "must strictly match", "(strict)" (see [Strictness](#strictness-strict-and-can-bend)) |
| `#bio?(<=500)`, `<form?>`, `@~hover?` | can bend: "should be at most 500 (can bend)" |
| `#email("email")`, `#region("eu-west-1")` | must match, passed through verbatim |
| `#react="^19"`, `#vitest(dev)="^3"` | a value: "Field `react` is `^19`"; `=` goes before or after `( )` |
| `#user=users`, `#database=db.users` | when the value names an element (here or in another file), it's a reference: "refers to `users`", without copying it |
| `#name->"lowercased + sanitized"` | transform, described in words |
| `#lastname->firstname` | inherit `firstname`'s rules and transform |
| `<button:like ...>` | a named element, so it can be reused or tested |
| `<button->like>`, `<button:share->ui.buttons.primary>` | reuse: a copy of `like` (here or in another file), to adjust |
| `<service:worker->api #-database @-crash>` | reuse `api` without its `database` field or `crash` event (see [Reuse](#reuse)) |
| `<button"pill shaped">`, `@click"debounce 300ms"`, `#email"work only"`, `sort"newest first"` | a note: a quoted string touching a word fine-tunes that word, passed through verbatim |
| `#username(+"ada", -"a b")` | examples: "ada" must be accepted, "a b" rejected. Each one is a test |
| `#qty(+=1, -=-1, -=1.5, -=NaN)` | examples that are values, not text: the number 1 must be accepted, -1, 1.5 and NaN rejected (`+"1"` is the text "1") |
| `#qty(^"on a fresh cart, add('penny', value)", +=1)` | how each of the field's examples is tried: a given step (any number, in order) |
| `#qty(+=1, -=0, +=>="{ ok: true }", -=>="{ ok: false }", -=1.5=>="NOPE")` | what accepting and rejecting an example shows, checked like `=>="…"`; an example may say its own |
| `<test:ok=signup #username="ada" @submit =>"account exists" =>!"error shown">` | a test of `signup`: inputs, one action, what must and must not happen |
| `^"ada signed up"`, `@add="'c', 199"` | in a test: a step that has happened before the action (any number, in order), and what the action is called with |
| `<!-- ... -->` | comment: private, never in any output |
| `<!--! ... -->` | a kept comment: guidance shown to the implementer, on the element it's in or before (see [Kept comments](#kept-comments)) |

### Fine-tuning with notes

A quoted string written right against a word, with no space, is a note on
that word. Notes go wherever detail matters: elements, events, fields,
capabilities and actions.

```html
<button"pill shaped, brand color" @~+click"debounce 300ms"="save draft" />
<form=account #email"company domain only"("email") #password"show a strength meter"(>=12) />
<table=orders #created(sort"newest first", filter) #more([refund"needs manager approval", view])>
  <row*"zebra stripes" @~hover"subtle lift" @click="open order" />
</table>
```

> A button ("pill shaped, brand color") that does "save draft" on click
> ("debounce 300ms"), with a quick animation. … Field `created` supports
> `sort` ("newest first") and `filter`. Field `more` provides actions on each
> row: refund ("needs manager approval") and view. …

With a space it isn't a note: `<button "x">` is an error, so you can't
attach one by accident.

### Kept comments

`<!-- … -->` comments are private: they never reach any output. A comment
with a `!` right after the opener, `<!--! … -->`, is **kept**: it's for the
person or agent implementing the spec, for what a rule can't say ("left
open: whether emails are trimmed — your choice", "each test uses a fresh
service"). It belongs to what follows it:

- inside an element's open tag, or right before an element (nothing but
  whitespace and other comments between, no blank line): that element;
- among an element's children, not right before one: the enclosing element;
- at the top level, not right before an element (a blank line after it, or
  the end of the file): the whole file.

```html
<!--! Left open: whether emails are trimmed. Your choice. -->

<!--! Each test starts from an empty list. -->
<service:todos #title(<=80) @add="add a todo">
  <!--! Shown newest first. -->
  <list=todos />
</service>
<!-- private: nobody else sees this -->
```

> A service `todos` that does "add a todo" on add. Note: Each test starts
> from an empty list. Field `title` must be at most 80. It contains a list
> bound to `todos`. Note: Shown newest first.
> Left open: whether emails are trimmed. Your choice.

An element's kept comments read as `Note: …` sentences right after it is
introduced (bullets in the brief), and the file's as plain sentences at the
end; the brief lists those under **Notes**, before the tests. Whitespace
inside one, line breaks included, reads as a single space there. The spec
output has `note: …` lines and JSON a `comments` array on the element, and
the file's in a top-level `comments` array beside `elements` (see [JSON
output](#json-output)). Both keep the text verbatim (trimmed).

A kept comment is guidance, not a test: it's no part of any test's
definition, so editing one never changes a test. It is part of the spec, so
`stoic verify` reports the edit as drift, `the spec changed since it was
locked, but none of its tests did: review the change and relock`.

### Strictness: strict and can bend

A `!` or `?` touching a name says how firmly it holds: `!` is strict (no
exceptions), `?` can bend (a preference). Unmarked is an ordinary "must".
Markers go on field names, element tags (right after the tag, before `*`,
`:name` and notes) and event names, always before a note:

```html
<form:profile #email!"work only"("email") #bio?(<=500) #name(>=1)
  @submit!="save profile" @~hover? />
<form!:payment #amount(>0) #note?(<=140) @submit="charge card" />
```

> A form `profile` that does "save profile" on submit (strict) and has an
> animation on hover (can bend). Field `email` ("work only") must strictly
> match "email". Field `bio` should be at most 500 (can bend). Field `name`
> must be at least 1.
> A form `payment` (strict) that does "charge card" on submit. Field `amount`
> must strictly be more than 0. Field `note` should be at most 140 (can bend).

- On an element, the marker is the default for everything inside it (its
  fields, events and child elements) unless they carry their own. Prose
  tags only what differs from its element; rules always say "must
  strictly", "must never", "should" or "should not".
- Inside `( )`, `!"…"` still means "must not contain": a marker is outside
  the parentheses, touching the name. The order is name, marker, note:
  `#email!"work only"(…)`. A marker after the note, or with a space before
  it, is an error.
- `#a->b` inherits `b`'s marker unless `a` has its own, and `->` reuse
  carries markers like everything else (yours win). Removals take none.
- The spec output adds `strictness: strict` / `strictness: soft` lines where
  it changes; JSON has a `strictness` field (left out when unmarked).
- Tests don't bend: a `?` field's `+`/`-` examples are still tests, checked
  against its rules, and a test's expectations read the same whatever the
  markers. Changing a marker on what a test is bound to still changes the test,
  a field's examples included: they cover how firmly the field's rules hold
  (its marker, or its element's) with the rules.

### Binding data

The language directs rather than programs: state is just a name. Bind an
element to it, mention it in a handler, and the compiler connects them.

```html
<button @click="increment x" @dblclick="reset x" />
<text=x />
```

> A button that does "increment x" on click and does "reset x" on dblclick. A
> text bound to `x`. `x` is shared state: the button does "increment x" on
> click and does "reset x" on dblclick; the text is bound to it.

Only an element's `=binding` is state. A word that is some element's name or
tag (`<method:undo>`, `<list>`) is never linked, tests are neither readers
nor writers, a handler must mention the name as a whole word, and some reader
must be a different element from the writer. So specs written as methods
(`<method:remove @call="… then undo …">`) get no "shared state" sentences
pairing unrelated methods.

### Nothing is a keyword

Tag names, event names, handlers, transforms, capabilities and actions are all
free words, passed through verbatim for the reader (a person or an agent) to interpret.
`<gallery>`, `<chip>`, `@tap` and `@clk` are as valid as `<table>` and `@click`.

Repetition is explicit: `*` after a tag means "one per entry", and the
parent's actions apply to each one.

```html
<gallery=photos #caption(edit) #more([like, share])>
  <card* @~hover @tap="open photo" />
</gallery>
```

> A gallery bound to `photos`. Field `caption` supports `edit`. Field `more`
> provides actions on each card: like and share. Each card has an animation on
> hover and does "open photo" on tap.

### Beyond UI: data, databases, infra, CI/CD

The same pieces describe anything: elements are things, fields are
properties, `=` on a field points at another thing, events are triggers,
and handlers are plain-words instructions.

```html
<!-- database: tables, relations, repeated rows -->
<table:users=postgres #id("uuid", primary) #email("email", unique) />
<table:orders=postgres #id("uuid", primary) #user=users(index) #total(>=0)>
  <row* @update="notify user when status changes" />
</table>

<!-- infra: services refer to what they use instead of copying it -->
<service:api=container #image="ghcr.io/acme/api" #replicas(>=3, <=10) #database=db.users
  @deploy="roll out one zone at a time" @crash="restart and page oncall" />

<!-- CI/CD: a pipeline of steps -->
<pipeline:main @push="run checks" @tag="release to production">
  <step:test @run="cargo test" @fail="block the merge" />
</pipeline>
```

> … A table `orders` bound to `postgres`. … Field `user` refers to `users` and
> supports `index`. Field `total` must be at least 0. Each row does "notify
> user when status changes" on update.

See `tests/fixtures/{db,infra,ci,stack}.stoic` for complete examples.

`=` on a field is a value or a pointer, and `->` is a copy. `#database=db.users`
says "uses the users table" (because `db.stoic` has a `users` element), while
`<button->ui.buttons.like>` pulls in the whole button.

### Frameworks and dependencies

A stack is fields on an element, and dependencies are fields whose values are
versions:

```html
<project:shop #language="typescript" #framework="next.js 15" #runtime="node 22" #database=postgres>
  <dependencies #react="^19" #prisma="^6"(orm, migrations) #zod="^3" />
  <dev_dependencies #vitest="^3" #eslint="^9" />
</project>
<service:postgres #version="17" />
<service:api->shop #runtime="bun 1.2" />
```

> A project `shop`. Field `language` is `typescript`. Field `framework` is
> `next.js 15`. Field `runtime` is `node 22`. Field `database` refers to
> `postgres`. It contains dependencies. Field `react` is `^19`. …

Keep a shared `stack.stoic` and point apps at it with `->stack.shop`,
overriding what differs.

### Reuse

Give an element a name with `:`, then reuse it with `->`, in the same file or
another one. No import line is needed: the reference says where to look.

```html
<!-- ui/buttons.stoic -->
<button:primary @~+click @~hover />
<button:like->primary @click="like post" #count(sort) />
```

```html
<!-- feed.stoic -->
<button->ui.buttons.like />
<button:share->ui.buttons.primary @click="share post" />
```

> A button (like `ui.buttons.like`) that does "like post" on click, with a quick
> animation, and has an animation on hover. Field `count` supports `sort`. …

Reuse copies everything unless you say otherwise. Leave things out with `-`
right after `#` or `@`:

```html
<service:api=container #image="ghcr.io/acme/api" #database=db.users
  @deploy="roll out one zone at a time" @crash="restart and page oncall" />
<service:worker->api #-database @-crash #replicas(>=1) />
```

> A service `worker` (like `api`) bound to `container` that does "roll out one
> zone at a time" on deploy. Field `image` is `ghcr.io/acme/api`. Field
> `replicas` must be at least 1.

`@~-hover` is still a slow animation: a removal is a `-` touching the `@`.

| Removal problem | Error |
| --- | --- |
| the base doesn't have it | `` `api` has no field `databse` to remove (fields: image, database) `` |
| removing and redefining it in one element | `` `#-database` and `#database` on the same element; drop one `` |
| no `->` on the element | `` `#-x` only makes sense on an element that reuses another with `->` `` |
| an inherited field inherits from it (`#a->b`) | `` `#-b` removes `b`, which `a` inherits from; remove it too, or keep `b` `` |

| Reference | Points at |
| --- | --- |
| `->like` | the element named `like` in this file |
| `->buttons.like` | `like` in `buttons.stoic`, next to this file |
| `->ui.buttons.like` | `like` in `ui/buttons.stoic` |
| `->my-ui.2024-set.like` | dashes work when written without spaces: `my-ui/2024-set.stoic` |
| `->"buttons v2".like` | quote any other name: `buttons v2.stoic` |

How the merge works:

- An event you write overrides only what you give it. `@click="share"` over
  `@~+click` keeps the quick animation.
- A field you write replaces the base's field with the same name. New events
  and fields are added.
- Children and the binding are inherited unless you give your own.
- `#-name` leaves out an inherited field and `@-name` an inherited event
  (`@-*` drops an inherited `@*`). Removals apply to the base as resolved,
  before your own fields and events are laid over it, and the result simply
  lacks the item.
- Reuse chains (`danger->primary`) and cycles are detected, including across
  files.
- Names must be unique within a file. Unnamed elements can't be reused.
- Within one lock, a name is defined once (see [Locking](#locking)): another
  file reuses it with `->` or binds tests to it with `=file.name`, rather
  than defining its own.
- Missing files or names are errors at the `->`, and so is a cycle that comes
  back to the element (`a->other.b`, `b->main.a`). Any other problem inside
  another file (a syntax, rule or test error there, or in a file it uses in
  turn) shows up there as one warning: the first problem, and how many more.

### Grammar

```ebnf
document    = node* ;
node        = "<" TAG strict? note? ( "*" note? )? ( ":" NAME note? )? ( "->" ref )? binding? attr*
              ( "/>" | ">" node* "</" TAG ">" | EOF ) ;   (* one note per element *)
ref         = part ( "." part )* ;
part        = WORD ( "-" WORD )* | STRING ;     (* WORD: IDENT or NUMBER; dashes only when touching *)
binding     = "=" ref ;
value       = IDENT | STRING ;
attr        = removal | event | field | expect | given ;
removal     = "#-" IDENT | "@-" ( IDENT | "*" ) ;   (* no spaces; needs "->"; takes nothing else *)
note        = STRING ;                          (* touching the word before it *)
strict      = "!" | "?" ;                       (* touching the name before it *)
event       = "@" modifier* ( IDENT | "*" ) strict? note? ( "=" value )? ;
modifier    = "&"                               (* in the background *)
            | "~" ( "+" | "-" )? ;              (* animation: normal, quick, slow *)
field       = "#" IDENT strict? note? ( "=" ref )? args? ( "=" ref )?   (* one value, before or after args *)
              ( "->" ( STRING | IDENT ) )? ;    (* transform, or a field to inherit from *)
expect      = "=>" "!"? STRING                  (* in a test: must, or must not, happen *)
            | "=>" IDENT? "=" STRING ;          (* in a test: an exact value, reported back *)
given       = "^" STRING ;                      (* in a test: a step before its action;
                                                   in a field's args: how each example is tried *)
args        = "(" ( arg ( "," arg )* )? ")" ;
arg         = IDENT note?                       (* capability *)
            | "[" ( IDENT note? ( "," IDENT note? )* ","? )? "]"   (* actions *)
            | CMP NUMBER                        (* limit *)
            | ( "+" | "-" ) STRING reports?     (* example: accepted, rejected (text) *)
            | ( "+=" | "-=" ) LITERAL reports?  (* example: accepted, rejected (a value) *)
            | ( "+=>" | "-=>" ) "=" STRING      (* what each accepted / rejected example reports *)
            | given                             (* how each example is tried *)
            | "|" LITERAL                       (* or-value: also taken, whatever the limits say *)
            | "!" STRING                        (* must not contain *)
            | STRING ;                          (* must match *)
reports     = "=>" "=" STRING ;                 (* what this example reports *)
CMP         = ">" | ">=" | "<" | "<=" | "=" ;
LITERAL     = [ "+" | "-" ] ( DIGITS [ "." DIGITS ] [ ( "e" | "E" ) [ "+" | "-" ] DIGITS ] | "Infinity" )
            | "true" | "false" | "null" | "NaN" ;
```

`IDENT` is letters, digits and `_` (in any script), not starting with a
digit; `NUMBER` is a whole number up to 4294967295 (`>5.5` is an error:
say a decimal limit in words, `"more than 5.5"`); `STRING` is in `"…"` or `'…'` on one
line, with `\n`, `\t` and `\` before any other character. Comments are
`<!-- … -->`, allowed between any two tokens; `<!--! … -->` (a `!` right
after `<!--`) is a [kept comment](#kept-comments), attached by position
rather than by the grammar:

```ebnf
comment     = "<!--" TEXT "-->" ;               (* private; TEXT has no "-->" *)
kept        = "<!--!" TEXT "-->" ;              (* shown to the implementer *)
```

`+=>` and `-=>` are one token too (no literal starts with `>`).
`+=` and `-=` are one token, read with the value that touches them:
everything up to the next character that isn't a letter, digit, `_`, `.`,
`+` or `-` (so `-=-1.5,` reads `-1.5`). Nothing else in the language puts `=`
right after `+` or `-`: a limit's `=3` stands alone, a removal's `-` follows
`#` or `@` (`#-db`), and a slow animation's follows `~` (`@~-hover`). The
value must touch the `=` and be a `LITERAL`: `+= 1`, `+=abc` and `+="1"`
are errors (text is `+"1"`). `|` is read the same way, with the value
touching it (`|null`, `|-1`): it means nothing else in the language.

Beyond the grammar, the compiler reports mismatched closing tags, unknown or
circular `->` references and contradictory limits (`>10, <5`, `>5, <=5`;
limits contradict only when no number fits them, so `>5, <6` is fine: 5.5
does) as errors,
and events or fields given twice as warnings. Names are never checked
against a vocabulary (see [Nothing is a keyword](#nothing-is-a-keyword)).

### JSON output

`stoic FILE --format json` prints the resolved model as one object, whatever
the file holds:

```json
{
  "elements": [ { "tag": "form", "name": "signup", "fields": [ … ] } ],
  "comments": [ "Left open: whether emails are trimmed." ]
}
```

`elements` is always there (`[]` for an empty file), in document order, each
with what it has (`tag`, `name`, `fields`, `events`, `children`, its own
`comments`, …; empty ones are left out). `comments` holds the file-level
[kept comments](#kept-comments), and is left out when there are none.

The shape of the output is no part of any lock: changing how it is printed
never changes a test.

## Tests: locked and enforced

The spec defines the tests. The agent implements them in whatever language the
project uses, and `stoic verify` checks the run against a lock, so tests can't
be skipped, dropped or quietly loosened.

```html
<form:signup=account
  #username(>=3, <=20, !" ", +"ada", -"a b", -"x")
  #email"company domain only"("email", +"ada@acme.com", -"ada@gmail.com")
  @submit="create account" />

<test:ada_signs_up=signup #username="ada" #email="ada@acme.com"
  @submit =>"account exists" =>"welcome email queued" />
<test:spaces_rejected=signup #username="a b" #email="ada@acme.com"
  @submit =>"shows 'no spaces'" =>!"account exists" />
```

The workflow:

```sh
stoic tests signup.stoic          # the IDs the agent must implement, with a summary of each
stoic lock signup.stoic           # you: freeze tests + spec into stoic.lock (commit it)
# agent: implement the code and the tests; the tests write results.txt
stoic verify results.txt --strict  # the check CI runs
```

### Defining tests

- **Examples** (`+"…"`/`-"…"`) on a field each become a test, with an ID like
  `signup_username_accepts_ada`: letters and digits (in any script, lowercased)
  joined by `_`. What that would lose keeps a word: a sign before a number
  (`-1` → `minus_1`, `+2` → `plus_2`, `-0.5` → `minus_0_5`; a decimal point is
  a `_`, so `1.5` → `1_5`) and whitespace at either end (`" SAVE10"` →
  `space_save10`, `"SAVE10 "` → `save10_space`). When two values give the
  same ID (`"Ada"` and `"ADA"`, or `+=1` and `+"1"`), the later one gets a
  suffix from its value: `signup_username_accepts_ada_8a15fe`.
- **Typed examples**: `+"1.5"` is the text "1.5"; `+=1.5` is the value 1.5.
  A literal is a number (`1`, `-1`, `+2`, `0.5`, `1e3`) or `true`, `false`,
  `null`, `NaN`, `Infinity` (`-Infinity` too). Summaries and prose show text
  quoted and values bare (`rejects "1.5"`, `rejects 1.5`, `rejects NaN`), and
  the kind is part of the test: `+"1"` and `+=1` are two tests.
- **How examples are tried**: a `^"…"` among a field's arguments is a step
  each of its examples is tried after, in plain words, as many as it takes and
  in order. `#qty(^"on a fresh cart, add('penny', value)", >=1, +=1, -=-1)`
  lists `cart_qty_rejects_minus_1  `cart.qty`: given on a fresh cart,
  add('penny', value); rejects -1`, and the prose says "Each example is tried
  given on a fresh cart, add('penny', value)." The steps (and their order) are
  part of each example's test. `#b->a` inherits `a`'s steps along with its
  rules (`a`'s first, then `b`'s own), and `->` reuse carries them like
  everything else. The spec output lists them as `examples given: "…"`, and
  JSON as `givens` on the field.
  Children inherited with `->` are tested in the reusing element too, prefixed
  with its name: `<form:g->f>` tests f's `<input #u(+"b")>` as `g_input_u_accepts_b`.
- **A test** is any element with `=>` expectations. It's bound (`=signup`, or
  `=forms.signup` in another file, whose problems show up as a warning, as
  with `->`) to what it tests, and has a name (its ID),
  `#field="value"` inputs, exactly one `@action`, and what must (`=>"…"`) and
  must not (`=>!"…"`) happen.
- **Checked values** (`=>="…"`) are expectations verify can check: an exact
  value the test reports back as observed (see [Results](#results)), compared
  with the locked one. A test may have any number alongside its `=>"…"`
  ones; with more than one, each needs its own label (`=>total="1800"
  =>cycles="2"`). They read `expect exactly "…" (reported back and compared)`
  (`` expect `total` exactly … `` when labelled) in summaries, prose and the
  spec output, and the value and label are part of the test. `=>!="…"` is an
  error.
- **Only checked values are compared.** A `=>"…"` or `=>!"…"` is guidance
  for whoever writes the test: verify sees only the test's `pass`, so a test
  body can assert something else and still pass. Summaries (and so `stoic
  tests`, the brief and the lock) mark each one `(not checked)`: `expect
  "saved" (not checked)`. A test element with no checked value at all gets a
  warning, ``test `t` has nothing verify can compare; add =>label="…" (what
  the test observes)``, which `stoic verify --strict` makes an error (see
  [What verify can't enforce](#what-verify-cant-enforce)). One checked value
  is enough: `=>"saved" =>status="201"`.
- **What an example reports.** A field says once what accepting and rejecting
  one of its examples shows, as checked values: `+=>="…"` for its accepted
  examples and `-=>="…"` for its rejected ones. An example may say its own,
  right after it: `-=1.5=>="VALIDATION_ERROR"`, `+"x"=>="…"`.

  ```html
  <method:add @call="add(sku, qty)"
    #qty("an integer", ^"add('apple', value)", >=1, <=99, +=1, +=99, -=0, -=100,
      -=1.5=>="{ ok: false, error: 'VALIDATION_ERROR' }",
      +=>="{ ok: true }", -=>="{ ok: false, error: 'QTY' }") />
  ```

  Each example's test then checks that value, as `=>="…"` does on a test
  element: it reports what the code returned (`pass add_qty_rejects_0 = {
  ok: false, error: 'QTY' }`), and verify compares it. So the test body no
  longer decides whether "rejected" happened: if the code accepts 0, the
  test reports `{ ok: true }` and verify says `WRONG    add_qty_rejects_0:
  expected { ok: false, error: 'QTY' }, observed { ok: true }`, whatever the
  body asserted. Summaries add the value (`` `add.qty`: given add('apple',
  value); rejects 0; expect exactly "{ ok: false, error: 'QTY' }" (reported
  back and compared)``), and so does each example's line in the brief.

  `+`, `-` and `=>=` are the signs the language already has for accepted,
  rejected and a checked value, so the verdict needs no word of its own
  (nothing is a keyword: `accept` would be a capability). It's written
  `=>="…"`, never `=>"…"`, because only a checked value is compared:
  `-=>"QTY"` is an error, ``what an example reports is compared, so write it
  as a checked value: `-=>="QTY"` ``, as are a label or `!` there. Each side
  is said once per field (a second `-=>="…"` is an error); `#b->a` inherits
  `a`'s, each side unless `b` says its own, and `->` reuse copies them. The
  verdict is part of each example's test (its own part, so changing it is
  "changed since it was locked"). Prose says ``Each accepted example reports exactly "{ ok: true }";
  each rejected one, exactly "…".`` (an example's own: `1.5 (which reports
  exactly "…")`), the spec output `accepted examples report: "…"`, `rejected
  examples report: "…"` and `rejects: 1.5 (reports exactly "…")`, and JSON
  `"verdicts": {"accepted": "…", "rejected": "…"}` on the field and
  `{"literal": "1.5", "reports": "…"}` (`{"text": "x", "reports": "…"}`) for
  an example with its own.

  A field whose accepted (or rejected) examples report nothing gets a
  warning, ``#qty's rejected examples have nothing verify can compare; add
  -=>="…" (what a rejected example reports)``, and `stoic verify --strict`
  makes it an error. Its examples still count as examples (pass or fail
  only) in the verdict; an example with a verdict counts as checked.
- **Given steps** (`^"…"`) say what has happened before the action, in plain
  words, as many as it takes and in order. They're for state the inputs can't
  set: earlier calls, existing records, the time. Only a test takes them.
- **The action's arguments** (`@add="'c', 199"`) are what it's called with,
  passed through verbatim like any handler.
- **A note** on a test (`<test:taken"usernames ignore case"=…>`) is shown with
  it wherever it's listed.

```html
<test:taken"usernames ignore case"=accounts
  ^"ada signed up" ^"then bob signed up" #username="ADA"
  @signup =>"error taken" =>!"account created" />
<test:wip_limit=kanban ^"c1, c2 and c3 in doing" @move="'c4', 'doing'" =>"error over limit" />
```

> A test `taken` ("usernames ignore case") of `accounts`: given ada signed up,
> then bob signed up, and `username` = "ADA", on signup, expect "error taken"
> and must not "account created".
> A test `wip_limit` of `kanban`: given c1, c2 and c3 in doing, on move with
> "'c4', 'doing'", expect "error over limit".

`stoic tests` (and `stoic brief`) list each one on one line, with its note,
steps and arguments:

```
taken      test of `accounts` ("usernames ignore case"): given ada signed up, then bob signed up, username = "ADA"; on signup; expect "error taken"; must not "account created"
wip_limit  test of `kanban`: given c1, c2 and c3 in doing; on move with "'c4', 'doing'"; expect "error over limit"
```

IDs are padded to the widest in their file by display columns, so the
summaries line up whatever script an ID is in: a character takes one column,
a wide East Asian one (CJK, kana, Hangul, fullwidth forms) or an emoji two,
and a combining mark none.

The steps (and their order), the arguments and the note are all part of the
test: changing any of them changes it in the lock. The spec output lists each
step as a `given "…"` line, and JSON has them as `givens`. A `=>!"…"`
expectation reads `must not "…"` everywhere (`- must not: "…"` in the spec
output).

The compiler checks tests against the spec:

| Problem | Error |
| --- | --- |
| an example that breaks its own field's rules | `example +"a b" breaks `username`'s rule `!" "`` |
| a `-` example nothing can reject | `nothing in `u`'s rules rejects "fine"` (add a rule, or a quoted rule, note or transform) |
| a quoted value after `+=`/`-=` | `` `+=` takes a bare value; for the text "1", write `+"1"` `` |
| a `-=` example its field's `\|null` allows | `` example -=null can't be rejected: null is allowed by `\|null`; drop one of them `` |
| a value that isn't a literal | `` `+=abc` isn't a value: write a number (`1`, `-1.5`, `1e3`) or `true`, `false`, `null`, `NaN` or `Infinity`, or quote text: `+"abc"` `` |
| nothing touching `+=`/`-=` | `` expected a value right after `-=`, like `-=1.5`, `-=-1` or `-=null` `` |
| `^` on an element that isn't a test (in a field's `( )` it's fine) | `` `^` (a given step) only makes sense on a test element `` |
| an input that breaks a rule, with no `=>!` | the test must say what must not happen |
| an unknown target, field or event; an unnamed test; two actions | listed with what exists |
| two tests with the same ID | rename one |

A field's transform (`->"trimmed"`) runs before its rules, and Stoic can't
apply one written in words. So on a field with a transform, an example that
breaks a rule as written is only a warning, and still a test:
`#username(!" ", +"  ada  ")->"trimmed"` gives `+"  ada  " breaks `!" "` as
written; fine if `trimmed` makes it valid`. A `-` example there needs no rule
that rejects it, since the transform may turn it into something the rules do
(`#name(>=3, -"  a  ")->"trimmed"`).

Limits are checked as a length *or* a number. Only a value that fails both
breaks the rule, since the spec doesn't say which it means. Only plain
decimals (`12`, `-3`, `0.5`) count as numbers: `"1e1"`, `"inf"` and `"NaN"`
are checked by their length. A literal example says which: `-=-1` is the
number -1, checked as a number alone (so it breaks `>=1`, though `"-1"` is
two characters long). `NaN` compares false with everything and `true`,
`false` and `null` aren't numbers, so they break every limit; `!"…"` is
about text and doesn't apply to a literal. Since numbers can be decimals or
negative, limits a number can meet never contradict each other: `>5, <6`
takes 5.5 (though no length), and `<0` takes -1.

### Or-values: a value the limits don't cover

A field that takes a number in a range *or* `null` (or `0`, or any other
literal) can't say so with limits alone: `null` breaks every one. Write the
extra value after `|` among its arguments:

```html
<method:changePlan #durationCycles(>=1, |null, +=null, +=3, -=0) @call="changePlan(id, durationCycles)" />
```

> A method `changePlan` that does "changePlan(id, durationCycles)" on call.
> Field `durationCycles` must be at least 1, or null, accepts null and 3, and
> rejects 0. A quoted example is text; a bare one is that value.

- The value is a `LITERAL`, as after `+=` (`null`, `true`, `false`, `NaN`,
  `Infinity` or a number), touching the `|`; give several with several `|`s
  (`|null, |0` reads "or null or 0"). `| null`, `|nil` and `|"none"` are
  errors: text has quoted rules for it.
- A literal example equal to it (the same text, or the same number: `|0`
  covers `+=0.0`) breaks none of the field's rules, so `+=null` is fine. A
  `-=null` beside `|null` is an error: ``example -=null can't be rejected:
  null is allowed by `|null`; drop one of them``. Text is still text:
  `+"null"` is checked by its length. A test input equal to it
  (`#durationCycles=null`) is fine too.
- Like every rule it's prose; only examples become tests. So on a field
  that has examples, an or-value none of them takes gets a warning:
  ``untested-rule: #durationCycles's rule `|null` has no accepted example
  equal to it; add +=null`` (see [No rule without a
  witness](#no-rule-without-a-witness)).
- It's one of the field's rules: `#b->a` inherits it, the spec output lists
  `or: null` after the limits, JSON has `{"kind": "or", "value": "null"}` in
  `rules`, and the brief reads as the prose does. Like any rule, it's part
  of the tests of the field (its examples, and the tests that fill it in),
  so adding or removing one changes them.

## Locking

`stoic tests` and `stoic lock` take files, folders, or both: `stoic lock .`
locks every `*.stoic` file under the folder, sorted, skipping hidden folders,
`target`, `node_modules` and `.git`. Paths in the lock are relative to the
lock's folder, whatever folder you run from: `stoic lock specs/a.stoic` stores
`specs/a.stoic`, and so does `stoic lock a.stoic --lock ../stoic.lock` run in
`specs`. They always use `/` and are never absolute, so the lock works in any
clone, and a lock written on Windows is the one written on macOS or Linux:
line endings don't count either, so a checkout where git writes `\r\n`
(`core.autocrlf` on Windows) hashes, verifies and formats exactly as one
with `\n`. In a path a lock names, `\` separates folders too, on every
platform. A path some platform can't check out is locked, with a warning:
a name Windows refuses (`warning: specs/Aux.stoic can't be checked out on
Windows (Aux is a device name there); rename it, so the lock verifies on
every platform`; also `:`, `*`, `?`, `"`, `<`, `>`, `|` or `\` in a name, or
one ending in `.` or a space), or two that differ only in case, which macOS
and Windows check out as one file.

A lock's specs stay in plain sight: under the lock's folder, and outside
hidden folders (and hidden files), whose names start with `.`. `stoic lock`
refuses any other (`error: can't lock specs/a.stoic: it's outside the lock's
folder (locks); …`), so put the lock in a folder above its specs. A lock that
names one anyway (edited by hand to check a stale copy in `.shadow/`, say) is
an ERROR in `stoic verify`:
`ERROR    stoic.lock names .shadow/a.stoic, in a hidden folder (.shadow): a
lock's specs must be in plain sight under its folder; relock from them`.
`stoic lock` stores the path a symlink leads to, so a locked path never
goes through one; verify gives the same ERROR for a path that does,
wherever the symlink leads (`stoic.lock names vis/a.stoic, through a
symlinked folder (vis): …`, or `a symlink (a.stoic)` for the file itself),
since a committed `vis -> .shadow` would show a reviewer `vis/a.stoic` and
check the hidden copy.

Test IDs must be unique across every file in one lock, since results match
tests by ID alone: one passing `ok` would otherwise satisfy an `ok` in each
file. `stoic lock` refuses a duplicate and names both files; `stoic verify`
fails on one found in a hand-edited lock.

**One definition per name.** A test covers the element it's bound to, so if
two files of one lock each define their own `compile`, a change to one never
reaches the tests of the other, and the two can even contradict each other
unnoticed. So within one lock a name is defined once. A *definition* is a
named element that isn't a test (an element with an expectation is one), at
the top of a file or nested; it is identified by its name alone, whatever its
tag, since `->` and `=` find an element by name. Every other file reuses it
with `->` (directly, or through other files that do) or binds its tests to it
across files (`<test:t=syntax.compile …>`). Otherwise `stoic lock` writes
nothing:

```
error: `compile` is defined in syntax.stoic:6 and gaps.stoic:5; tests of one don't see changes to the other. Define it once and reuse it (`<command:compile->syntax.compile>`) or bind tests to it (`=syntax.compile`), or give them different names.
error: 1 name(s) defined in more than one file; nothing was locked
```

and `stoic verify` fails on the same thing in a lock written before the check
(`ERROR    `compile` is defined in …`). A reuse of a definition from outside
the lock is still a definition of its own. Tests aren't definitions: their
names are IDs, unique on their own terms, so a test `compile` beside an
element `compile` in another file is fine. Two locks may each define the same
name; `stoic FILE` compiles one file and doesn't look at the others. Prefer
binding tests across files to reusing an element that has examples: reuse
copies its examples, and their IDs with them.

**What a lock covers.** A lock records the folders it was built from as its
`roots`, relative to its folder like its file paths (`"roots": ["."]` for
`stoic lock spec --lock spec/stoic.lock`); a lock of files alone has none and
covers just those files. With `--strict`,
`stoic verify` then fails on a `.stoic` file under a root that the lock
doesn't list (`ERROR    sub/b.stoic isn't in the lock, so its tests aren't
enforced; the lock covers its folder, so relock: stoic lock spec --lock
spec/stoic.lock`), and on another lock (any `*.lock` under a root or beside
the lock that is a Stoic lock) of specs under a root: `ERROR    gaps.lock also
locks specs under this lock's roots (b.stoic); keep one lock per root, so one
verify gates them all`. Each verify gates only its own lock, so a spec locked
elsewhere, or nowhere, would otherwise slip past verify. Without
`--strict` both are warnings. With `--against REF`, roots the trusted lock
doesn't have yet don't count as relocking.

Relocking with `stoic lock` prints what changed since the lock it replaced
(`+` added, `~` changed, `-` removed), told apart as `stoic verify` tells its
drift (using the `own` hashes below): a test whose own text changed gets a
line of its own with its summary, and two or more tests of one target that
changed only through it share one line, after the others. A count ends the
list:

```
locked 45 tests from 1 file(s) into stoic.lock
  ~ t2  test of `changePlan`: given plan = "team"; on call; expect "plan is team"
  + t45  test of `changePlan`: given plan = "max"; on call; expect "plan is max"
  ~ f_u_accepts_ada  what it tests changed (its own steps and expectations didn't)
  ~ 42 tests of `changePlan`: what they test changed (their own steps and expectations didn't)
  tests: 1 changed, 43 only through their target, 1 added, 0 removed
```

So an edit to one field doesn't list every test of its element one by
one, and the tests that were edited stand out.

Every checked value the relock changes gets a line too, before the count:
the test (and label), the value before and after (`nothing` on the side
that lacks it), and where it's written now. A relock never fails on one,
since changing behaviour on purpose means changing a value, but it can't
change one quietly, and a hand-edited value it puts back shows the same way.
Where it's written is named from the folder the command runs in (the lock's
folder as `--lock` gives it, then the path the lock records), so with
`--lock spec/stoic.lock` it reads `spec/fees.stoic:5` and opens from there;
`stoic verify` and `stoic check` name the files in their DRIFT, VALUE and
ERROR lines the same way:

```
  ~ fee500  test of `fee`: given nothing; on call with "500"; expect exactly "45" (reported back and compared)
  value fee500: 44 -> 45 (spec/fees.stoic:5)
  value checkout cycles: 2 -> nothing (spec/cart.stoic:31)
```

A test renamed while its values change would otherwise read as one test
removed and an unrelated one added, its old and new values never side by
side. So a test element only the old lock has and one only the new lock has
are paired as one test renamed when they are in the same file, test the same
target, and are the same but for their IDs and checked values: the same
note, steps, inputs, action, unchecked expectations, and checked labels in
the same order. The lock records that as each test element's `skeleton`
hash (its own part without its ID and checked values). The pairing must be
unambiguous: when two removed or two added tests share a skeleton, nothing
pairs, and nothing is matched loosely. A pair prints one line in the new
test's place, and its values are named `OLD -> NEW`:

```
  ~ fee_44 -> fee_45  test of `fee`: given nothing; on call with "500"; expect exactly "45" (reported back and compared)
  value fee_44 -> fee_45: 44 -> 45 (spec/fees.stoic:5)
  tests: 0 changed, 0 only through their target, 0 added, 0 removed, 1 renamed
```

`stoic verify` pairs them the same way (`DRIFT    test `fee_44` in
spec/fees.stoic was renamed `fee_45` (same target and steps)` and `VALUE
fee_44 -> fee_45: 44 -> 45 (spec/fees.stoic:5)`).

`stoic lock --per-test` prints one line per
test instead (`~ ID  what it tests changed …` for those that changed only
through their target). Nothing is printed
after the first line when nothing changed. Keep `stoic.lock` under code
review so only a person can loosen a test.

## What verify can't enforce

Some of a spec compiles fine but leaves verify nothing to compare. Each is a
warning wherever a spec is compiled or locked (`stoic FILE`, `stoic check`,
`stoic lock`, the editor), and an ERROR in `stoic verify --strict`, the check CI runs:

- a test element that checks no value (see [Defining tests](#defining-tests));
- a field whose accepted or rejected examples report no verdict;
- a formal rule of a field with examples that none of them witnesses (below).

`stoic lock` prints the warnings (as compiling does, each with its location)
and locks anyway. `stoic verify --strict` reports each one in a locked file,
`ERROR    a.stoic:2: test `t1` has nothing verify can compare; add =>label="…"
(what the test observes)`; without `--strict` the verdict's counts show them
(asserted only, examples, rules untested). The warnings have stable codes
for tools (`unchecked-test`, `unchecked-examples`, `untested-rule`).

### No rule without a witness

A rule is enforced only if dropping it would fail a test, so each formal rule
of a field with examples needs examples at its edge:

- a limit (`>=1`, `<=99`, `=5`) needs an accepted example that meets it
  (at or inside the bound) and a rejected one *just outside* it: breaking it
  within one unit of the bound, or less than one for `>` and `<`, which fail
  at the bound itself. For whole numbers that's the next integer outside:
  `>= 1` needs 0, `> 1` needs 1, `<= 99` needs 100, `= 5` needs 4 or 6. A
  decimal counts too: `>= 1` takes `-=0.5` or `-=0.99`, not `-=-5`. A text
  example counts by its length (a whole number, so `-"ad"` for `>= 3`), or by
  its value when it's a plain number (`-"2"`), and must break the limit as
  [it's checked](#defining-tests): as both;
- `!"…"` needs a rejected text example that contains the text;
- `|v` needs an accepted example equal to `v`.

A rule without one gets a warning naming the rule and the example to add:

```
warning: untested-rule: #qty's rule `<= 99` has no rejected example just above it; add -=100
warning: untested-rule: #username's rule `>= 3` has no rejected example just below it; add -"ad"
warning: untested-rule: #username's rule `!" "` has no rejected example containing " "; add -"a da"
```

The example to add is a value when the field's examples are values, the
number as text when they're all numbers as text, and otherwise a text of the
right length made from an accepted example's characters (past 32 characters,
it's said in words: `add a rejected example 501 characters long`). Quoted
rules are prose and need nothing. A field without examples gets no warning:
none of it is tested, which the verdict counts.

For each test the lock stores two hashes (sha256, hex). `hash` covers the
test's whole definition: its own text plus, at the end, a `rules:` line (the
rules of the field an example is of, with that field's note and transform,
or the rules of the fields a test element fills in) and, for a test element, a `spec:` line (its target's resolved spec).
`own` covers the same definition cut just before that `rules:` line, so
without the `rules:` and `spec:` lines: the test's ID, target name, note,
steps, inputs (with an input's note, marker and arguments:
`#u"typed"!="ada"`), action (with its markers and note: `@&~go!"twice"`) and
expectations, and for a test element also its tag with its markers when it
isn't a plain `<test>` (`<check!:…>`) and the elements inside it, but the
tests among them (each has its own entry) and kept comments (in the file's
rest); for an example, its field, `accepts` or `rejects` and value, and its
field's steps. A part is written only when present. `hash` is what verify enforces;
`own` only tells it why a test changed (see [Verifying](#verifying)).

The lock is written atomically (to a temporary file beside it, flushed, then
renamed over it, and the folder flushed after the rename on Unix), so a
`stoic verify` running at the same time reads the old lock or the new one,
never a half-written file, and a crash just after `stoic lock` returns can't
lose the new lock either. The lock's folder must exist: `--lock missing/x.lock`
fails with `error: can't write missing/x.lock: its folder missing doesn't
exist (create it first); nothing was locked`. Several `stoic lock` runs on
the same lock compile side by side; each holds the guard `stoic.lock.lock`
only while it reads the current lock (to print what changed) and writes the
new one, a matter of milliseconds, and a run that finds it held waits up to 2
seconds for it, then fails:

```
error: another stoic lock is running (pid 4242 on host-a, started 0s before this run asked): it still held stoic.lock.lock after waiting 2s; retry once it's done
```

The last run to write wins, but never silently: if the lock changed after a
run read it, the run says `note: stoic.lock changed while this run was
compiling; relocked on top of it`, and its `+`/`~`/`-` list is against the
lock it actually replaced.

The guard is an OS file lock (`flock` on Unix, `LockFileEx` on Windows) on
`stoic.lock.lock`. The file holds the run's pid, host and start time (`pid
4242`, `host host-a`, `started 1764312345.120`), but only for that message:
whether the guard is held is the lock's answer alone, never a guess from a
pid. The system releases the lock when its process exits, however it exits,
so a killed run never blocks the next one, and no pid is checked and nothing
is run to check it. A guard file no run holds was left by an interrupted run
and is taken over: `note: removed a stale guard left by pid 4242 on host-a;
no run held it`, even if that pid now belongs to another process. A file
that doesn't say whose it is is never echoed (`note: removed a stale guard
that doesn't say whose it is`), and an empty one, which a run creates a
moment before it locks it, is taken over without a word. A guard a run holds
is never removed, even with `--force-unlock`. When done, a run removes the
file, then releases the lock; on Windows it empties the file instead, and the
empty `stoic.lock.lock` stays.

**Network filesystems.** File locks may not reach across machines: over NFS
they depend on its lock service, and some network and FUSE filesystems lock
only on the machine that asks. So a guard file naming another host is never
taken over on its own, even when no run on this machine holds it:

```
error: another stoic lock may be running on host-b: stoic.lock.lock was written there by pid 77 40s ago, and file locks may not reach across machines (a network filesystem), so this run can't tell. If none is running there, remove stoic.lock.lock, or pass --force-unlock to remove it once it's over 10 minutes old
```

A run there removes its guard within milliseconds, so this run first waits
up to 2 seconds, as for a held one. Where the filesystem refuses file locks
altogether, `stoic lock` fails naming the guard and the error; with
`--force-unlock` it guards with the file alone (created exclusively, removed
when done, an existing one taken over only once it's over 10 minutes old),
which is weaker: two runs taking over the same old file at once could both
write. Containers that share a folder but not a host name (a Docker bind
mount) see each other's guards as another host's, though their locks do
work, so a guard one of them left needs `--force-unlock` (or removing). For
concurrent relocks, keep the lock on a local disk; across machines, use a
clone per machine.

The temporary file is named `.stoic.lock.<pid>-<n>.tmp` (after the lock's
own name, with the writing run's pid). A run killed mid-write can leave one
behind; it is never read as a lock. Only a run holding the guard writes one,
so any found while holding it is a leftover, whatever pid it names: each
`stoic lock` removes them before it compiles (when it can take the guard at once) and again when
it writes, with `note: removed 1 temporary file(s) left by killed runs: …`.
So a run whose spec doesn't compile cleans up too, and a run that finds the
guard held leaves them to the run holding it. Other files are kept.

## Results

Results are in Stoic's own format, written by the tests themselves in
whatever language they're in. Stoic doesn't know or care which test runner,
framework or language produced them:

```text
# results.txt
pass ada_signs_up
fail spaces_rejected: shows no error
skip gmail_rejected: waiting on the mail stub
dispute fee_rounding: the ticket says round half up; the spec says half even
```

One line per test: `pass`, `fail`, `skip` or `dispute`, then the test's exact
ID, then optionally `: message` (a `dispute` must say why). Blank lines and `#` comments are fine; anything else
is an error with its line number (`error: results.txt: line 4: …`, and `line
4: not valid UTF-8` for a line that isn't UTF-8), so a garbled or truncated
file never verifies. IDs match exactly, never by prefix
or naming convention: `suite_ada_signs_up` is not `ada_signs_up`.

An ID may appear more than once: a test that ran twice, or several results
files (`stoic verify a.txt b.txt`) that both ran it. The worst report counts,
in the order **dispute > fail > skip > pass**, whatever order the lines come in:

| reported | verdict |
| --- | --- |
| `pass` + `pass` | pass |
| `pass` + `skip` | SKIPPED |
| `pass` + `fail`, `skip` + `fail` | FAILED |
| `dispute` + anything | DISPUTED |

So a test passes only when every report of it passes. Among reports of the
same kind, the first one's message is shown.

**Disputes.** `dispute ID: why` is the legitimate exit for a locked test (or
a part of the spec) that looks wrong or impossible: the test records it in
place of its result, instead of being weakened, skipped or made to pass
some other way. It never passes, so verify still fails, but it lists every
dispute first (`DISPUTE  fee_rounding: the ticket says round half up; …`)
and counts them apart in the verdict (`NOT verified: 382/383 locked tests
passed (…), 1 disputed (needs an owner)`), for whoever owns the spec to
settle: fix the spec and relock, or tell the implementer why it stands.
`stoic brief` tells agents to use it.

A test with [checked values](#defining-tests) also reports what it observed:
after the ID (and the label, for a labelled value), `=` and the value, to the
end of the line, one line per value:

```text
pass merge_cap = { ok: false, error: 'QTY' }
pass coupon_half total = 500
pass coupon_half couponCyclesLeft = 1
```

The value is compared as a [Stoic value](#stoic-values), below, when both
sides are one, and otherwise as text. A `fail` or `skip`
may carry a value too (it's ignored, since the test failed anyway); a value
can't also have a `: message`. Lines without `=` are plain
results, as for tests without checked values.

### Stoic values

The expected value (from the spec) and the observed one (from the `pass`
line) are each read in Stoic's own value notation, and compared as values. The notation belongs to no programming language, so a
test in any language can write it (`stoic harness` prints reporters that
do):

| Kind | Written | Compared |
| --- | --- | --- |
| literals | `null`, `true`, `false` | as themselves |
| numbers | `0`, `-12`, `1.50`: an optional `-`, digits (no leading zero), optionally `.` and digits; no `+`, no exponent, no leading or trailing point | by value: `1.0` is `1`, `-0` is `0` |
| strings | `'text'` or `"text"`, escapes `\\`, `\'`, `\"`, `\n`, `\t` and `\uXXXX` (not a surrogate), no others | the same string whichever quotes: `"it's"` is `'it\'s'` |
| arrays | `[1, 'a', null]`, no trailing comma | length, then item by item |
| objects | `{ ok: false, 'two words': 1 }`: keys bare names (a letter or `_`, then letters, digits or `_`) or strings, each once, no trailing comma | by key set, in any order |

Whitespace between the parts doesn't matter. So `{"error":"QTY","ok":false}`
(as JSON prints it) matches a spec's `{ ok: false, error: 'QTY' }`, and
`1800.00` matches `1800`, but `'1800'` (a string) doesn't. When two values
differ, the WRONG line shows both in canonical form (single quotes, keys
in the order written, bare when they are ASCII names, numbers without
trailing zeros) and the path to the first difference inside them:

```text
WRONG    t: expected { ok: false, error: 'QTY' }, observed { error: 'STOCK', ok: false } (at .error)
WRONG    t: expected { items: [{ sku: 'a', qty: 1 }] }, observed { items: [{ sku: 'a', qty: 2 }] } (at .items[0].qty)
```

Text that isn't exactly one value (prose like `saved 3 items`, `1e3`,
`NaN`, a bare `QTY`, a trailing comma) is compared as text, after
normalising whitespace: both sides are trimmed, and each run of whitespace
is dropped, except between two letters, digits or `_` (in any script),
where it becomes one space, so `saved 3  items` matches `saved 3 items`;
nothing else is interpreted. When only one side is a value, the WRONG line says so: `WRONG
t: expected QTY, observed 'QTY' (the expected value isn't a Stoic value, so
they were compared as text)`, which usually means the spec should quote it.
A relock lists a `value` line only for a value that changed as a value, so
rewriting `{ ok: false }` as `{"ok": false}` lists none.

### Reporters

`stoic harness --lang node|python|sh` prints a small reporter for the tests,
in their language, so nobody hand-writes one (`--out PATH` writes it to a
file instead, making the folders on the way to it):

```js
// stoic harness --lang node --out stoic-results.cjs   (next to the spec, not under test/)
const { observe, passed, failed, skipped, dispute } = require('../stoic-results.cjs');
observe('merge_cap', mergeCart(a, b));   // pass merge_cap = { ok: false, error: 'QTY' }
observe('checkout', 'total', total);     // pass checkout total = 1800
failed('t', err);                        // fail t: <the error's message>
dispute('fee_rounding', 'the ticket says round half up');
```

`observe(ID, VALUE)` and `observe(ID, LABEL, VALUE)` write the value in
canonical [Stoic value](#stoic-values) form, so it compares with the
spec's however the spec spells it. A value the reporter
can't write faithfully is an error naming it and where in the value it is,
never a lossy line: `stoic: can't write undefined at .a.b as a Stoic value;
report null if that is what it means`. Node refuses `undefined`, functions,
symbols, `Date`, `Map`, `Set`, `NaN`, `Infinity`, `-0`, lone surrogates,
array holes, cycles and class instances (only plain objects are objects);
Python refuses NaN, infinities, `-0.0`, sets, bytes, dates, non-string keys,
cycles, and subclasses of the built-in types (an `IntEnum` isn't an `int`
here); `Decimal`s, tuples and JS bigints are fine. The node reporter is
CommonJS, so keep it as a `.cjs` file (an ES module can `import` it too),
and where `node --test` won't run it as a test file: not under a `test/`
folder and not named `*.test.*`, `*-test.*`, `*_test.*`, `test-*.*` or
`test.*` (`--out` warns about such a path).
POSIX sh has no types, so its `observe ID [LABEL] VALUE` writes VALUE as
given (`observe t 44`, `observe t "{ ok: true }"`), and `observe_text ID
[LABEL] TEXT` writes TEXT as a string; a bad argument prints `stoic: …` and
returns 2. `passed`, `failed`, `skipped` and `dispute` write the other
results, a message's lines joined by ` | `. Every reporter appends to
`results.txt` (or `$STOIC_RESULTS`) one whole line per write, so tests
running in parallel processes can share the file, which `stoic verify --run`
deletes before each run. No reporter empties it (under `node --test` each
test file runs in a process of its own, and none can tell it's the first),
so between plain runs of the tests, delete it yourself, or old lines pile up
and a stale `fail` outranks a fresh `pass`.

On Windows the node and python reporters write the same `\n` lines (python
takes a lock on the file while it appends, since Windows appends by seeking
to the end first). The sh reporter needs a POSIX sh there (Git Bash, MSYS2
or WSL), checked out with `\n` line endings (`*.sh text eol=lf` in
`.gitattributes`); that its appends are atomic there is untested, so run
sh tests one at a time. Text a Windows program prints ends its lines in `\r\n`,
and `observe_text` writes that `\r` faithfully (as `\u000d`): strip it
(`tr -d '\r'`) when the spec doesn't mean it.

[`examples/results/`](../examples/results/) shows the same pattern written out
by hand in plain JavaScript, Python, Rust, Go and POSIX sh, with no
dependencies: a few lines of harness run each test, record `fail ID:
message` for an error or panic, and write the file.

## Verifying

`stoic verify` fails when:

- **DRIFT:** the spec or any test changed, was removed or added since the
  lock. A spec that no longer compiles also fails. A test covers the element
  it's bound to, so changing that element (even in another file) changes the
  test; verify says which kind of change it is (below).
- **DISPUTE:** a test reported `dispute ID: why` (see [Results](#results)).
  Listed first, and counted apart in the verdict.
- **MISSING / SKIPPED / FAILED:** a locked test is absent from the results,
  skipped, or failing.
- **WRONG:** a test with checked values passed, but a value it reported isn't
  the locked one (`WRONG    coupon_half couponCyclesLeft: expected 1, observed
  2`), or one is missing (`…, observed nothing (report it: pass coupon_half
  total = <observed>)`), or it reported a value it doesn't check (`WRONG
  t tax: not a value this test checks (it checks: total, cycles)`). A label
  another test of the same element checks isn't one of those: a test may
  report every value its code returned (`code` on a success, when another
  test checks the failure's `code`), and nothing compares it. Values
  compare as [Stoic values](#stoic-values), and a line for two objects or
  arrays ends with where they first differ (`(at .error)`). Every report
  of a value must match the value the spec states. The lock stores a copy of
  each test's values (`checks`, only for tests that have them), but verify
  never trusts it: the test's hash covers the values, and a copy that differs
  from the spec is drift (`DRIFT    test `fee500`: its checked values in the
  lock don't match the spec; the lock was edited by hand: relock`), with or
  without `--against`.
- **UNKNOWN** (with `--strict`): the results name tests that aren't in the lock,
  each listed once (`UNKNOWN  extra  (not in the lock; reported 3 times)`).
- **ERROR:** a path the lock names out of sight (outside its folder, in a
  hidden folder, through a symlink, or absolute), a name two locked files both define, (with
  `--strict`) what [verify can't enforce](#what-verify-cant-enforce) in a
  locked file (`ERROR    a.stoic:2: test `t1` has nothing verify can
  compare; …`), or (with
  `--strict`, for a lock with roots) a spec under its roots that it doesn't
  list, or another lock of specs under them; see [Locking](#locking). These
  come first, and the verdict counts them: `NOT verified: 3/3 locked tests
  passed (0 checked, 1 asserted only, 2 examples), 1 error(s)`.

The verdict always says how much a pass proves, in parentheses: how many
locked tests check values (verify compares what they observed, so an edited
test body can't fake a pass), how many other test elements are only asserted
(verify sees pass or fail, nothing more) and how many are field examples
(pass or fail too). When some of the locked files' formal rules lack a
witness (see [No rule without a witness](#no-rule-without-a-witness); on a
field without examples, every one), it counts those too: dropping one fails
no test, so it's enforced only as prose.

```
verified: 380/380 locked tests passed (227 checked, 98 asserted only, 55 examples; 12 rules untested)
```

A run that isn't verified ends with one more line, so the end of the output
alone (`stoic verify … | tail`) still says why it failed and what to do:
how many lines of each kind it printed above, then the one next step.
Against a reviewed lock that changed, it's a stop:

```
NOT verified: 18/18 locked tests passed (18 checked, 0 asserted only, 0 examples), 14 change(s) since the lock (tests: 0 changed, 0 only through their target, 0 added, 0 removed, 5 renamed)
next: 14 DRIFT, 5 VALUE, 3 UNKNOWN above. Stop: spec/stoic.lock changed since 3f2a91c (5 value change(s)); this needs review before going on. Report the DRIFT and VALUE lines and wait; don't relock, or edit a spec or a test, to make this pass.
```

The step is the first that applies: report a claim taken over (a STALE line;
see [Claims](#claims-and-fencing-tokens)); that stop (with `--against`, after any
DRIFT); fix the ERROR lines (they're in the specs or the lock); review the
spec's changes and relock (DRIFT without `--against`); leave each DISPUTE to
the spec's owner; with `--as`, leave others' failing tests alone (see
[Working with several agents](#working-with-several-agents)); fix the code
until every locked test passes; or report only locked tests (UNKNOWN). A
verified run ends with its verdict.

It also prints a **WARNING**, without failing, for each `.stoic` file in the
folder of a locked file, or under its roots, that the lock doesn't list: its
tests aren't enforced until you lock it. Without `--strict`, another lock of
specs under its roots is a warning too.

A changed test is one of two kinds, and verify tells them apart:

- **Its own definition changed**: an expectation, input, step, note, the
  action or the target it's bound to. `DRIFT    test `t2` changed since it
  was locked`. Read these closely: this is where a test gets loosened.
- **Only what it tests changed**: its own text is as locked, but its
  target's rules or spec aren't (a rule of a field changes every test of the
  form and every example of the field). `DRIFT    test `t1`: what it tests
  changed (its own steps and expectations didn't)`. Review the spec change
  once, not each test.

Both are drift and both fail verify: after review, relock. Two or more tests
of the same target that changed only through it share one line, after the
others, so the tests that were edited stand out:

```
DRIFT    f.stoic: the spec changed since it was locked
DRIFT    test `t2` changed since it was locked
DRIFT    2 tests of `f.u`: what they test changed (their own steps and expectations didn't): f_u_accepts_ada, f_u_rejects_x
DRIFT    3 tests of `f`: what they test changed (their own steps and expectations didn't): t1, t3, t4
...
NOT verified: 6/6 locked tests passed (0 checked, 4 asserted only, 2 examples), 7 change(s) since the lock (tests: 1 changed, 5 only through their target, 0 added, 0 removed)
```

`--per-test` prints one line per test instead, in lock order, for scripts.
Telling the kinds apart takes the lock's `own` hashes (see
[Locking](#locking)). `own` never decides whether verify passes, only what
it says.

The results file is only as trustworthy as whoever ran the tests. `--run`
makes `stoic verify` run them itself:

```sh
stoic verify results.txt --run "<your test command>" --strict
```

It deletes `results.txt` first, runs the command (with `sh -c`, or on
Windows `cmd /S /C`, so write it for cmd there: `--run "npm test"` works on
both), and fails if the command
didn't write a fresh one, so a stale or hand-placed file can't count. With
one results file, the command runs with `STOIC_RESULTS` set to its absolute
path, so the [reporters](#reporters) write there whatever it's called
(`stoic verify results-a.txt --run "npm test"`) and wherever the tests run. The
command's exit code is reported but doesn't decide anything: the results say
which tests failed. In CI, where the agent doesn't control the machine, this
closes the loop.

An agent can run `stoic lock` too, so in CI verify against the lock that was
reviewed, not the working copy's:

```sh
stoic verify results.txt --strict --against origin/main
```

`--against REF` reads the lock committed in that git ref (`git show
REF:path/to/stoic.lock`) and checks the specs and results against it. If the
working copy's `stoic.lock` differs from it, that's drift too:
`DRIFT    stoic.lock differs from origin/main: relocking needs review`.
Each checked value a drifted test changed since the lock verify trusts gets
a `VALUE` line after the drift, as `stoic lock` lists them (`VALUE
fee500: 44 -> 45 (spec/fees.stoic:5)`), so after another agent, working on a different ticket
in parallel, changed a value and relocked, the next agent sees exactly which
expectation moved; without
`--against` the same lines show the values an unlocked edit changed. If
the ref is missing, as in a shallow CI checkout, the error says how to get it:
`git fetch origin main`, or `fetch-depth: 0` on `actions/checkout`.

### Diff coverage: new code a locked test must run

A spec can only enforce what its tests run. Code that no locked test runs
(a new function, a branch an agent added "while it was there", another agent's
quiet change) passes every test and verifies, unspecified. `--coverage`
catches it, whoever wrote it and in whatever order:

```sh
stoic verify results.txt --strict --against origin/main --coverage lcov.info \
  --run "node --test --experimental-test-coverage --test-reporter=lcov --test-reporter-destination=lcov.info"
```

The tests' run writes its coverage in [LCOV](#lcov-by-test-runner) (`SF:PATH`,
then `DA:LINE,HITS` per executable line, then `end_of_record`), the format
every mainstream coverage tool writes. Git says, without checking anything
out, which lines were added or changed since REF (`git diff REF`, renames
followed, so a file moved unchanged has none; a file git doesn't track, and
doesn't ignore, counts as added whole). Every path is from the *project
root*: the git work tree's top level, wherever the lock is, so a lock kept in
`spec/` checks the code in `src/` and names it `src/cart.js`. Of those
lines, only lines of implementation count:

- with `stoic.code` beside the lock: what it names, one glob per line
  (`*`, `**`, `?`, relative to the project root, so `src/**` from
  `spec/stoic.code` too), `!glob` to exclude, `#` comments; the last line
  that matches a path decides;
- without it: every file of the project except the specs, the lock,
  `stoic.segments`, `stoic.code`, `stoic.refactor`, files under a `test`,
  `tests`, `spec` or `__tests__` folder or named like a test (`*.test.*`,
  `*_test.*`, `test_*`), `*.md`, hidden paths and what git ignores. The results and
  coverage files verify was given never count.

A changed line the report has with zero hits is unspecified; a changed line it
has no `DA` for isn't code (a blank line, a comment, a lone `}` for most tools)
and is left out; a changed file the report lacks is unspecified whole (no
test even loaded it). Each range is one line, after the test lines, then a
summary:

```
pass     t1
UNSPECIFIED  src/cart.js:14-19  (changed since origin/main; no locked test runs it)
UNSPECIFIED  src/coupon.js  (changed since origin/main; not in the coverage report, so no locked test runs any of it)
UNSPECIFIED  package.json  (changed since origin/main; not in the coverage report, which has no .json file: if it isn't code, exclude it in stoic.code)
coverage: 31/40 changed line(s) in 4 implementation file(s) since origin/main run by locked tests

NOT verified: 3/3 locked tests passed (3 checked, 0 asserted only, 0 examples), 9 changed line(s) no locked test runs
next: 3 UNSPECIFIED above. Specify the behaviour first: add or change a test in the spec that runs this code and relock (after review), or remove the code; a test that isn't locked doesn't count.
```

A range spans lines that aren't code, so a new function is one line.
`--strict` fails on any; without it the verdict counts them and adds
`(--strict fails on them)`, and verifies. When a test fails too, the next
line says to fix the code first. And when everything changed is run:
`coverage: 12/12 changed line(s) in 2 implementation file(s) since
origin/main run by locked tests`, or `coverage: no implementation file
changed since origin/main`.

The rules, decided once:

- **It needs `--against REF`**: the lines it checks are those changed since
  REF, the reviewed base (`--against HEAD` for changes not yet committed).
  Without it, `--coverage` is a usage error: a total percentage enforces
  nothing, and counts vendored and generated code with yours.
- **Fresh, as results are**: with `--run`, each coverage file is deleted
  with the results before the command runs, and must be written by it, or
  `error: `CMD` didn't write lcov.info; …` and `NOT verified: no fresh
  coverage`. A report left from another run, or written by hand, can't count.
- **Fail closed**: a report that can't be read whole is `error: lcov.info:
  line 2: expected DA:LINE,HITS with whole numbers, found `DA:two,1`` and
  `NOT verified: lcov.info isn't an LCOV coverage report`. Other LCOV keys
  (`TN`, `FN`, `FNDA`, `BRDA`, `LF`, `LH`…) are read past.
- **Reports add up**: give `--coverage` once per report (a run per
  package, a run per language); hits of the same file, in one report or
  several, add up, so a line any of them ran is run.
- **Paths, from any machine**: an `SF:` path has `\` read as `/` and `.`
  and `..` resolved; a relative one is relative to the folder verify runs in
  (where `--run` runs the tests), and one under the project root is that
  file. A path that names no file there (a Windows `C:\ci\shop\src\cart.js`,
  a Go `example.com/shop/cart/cart.go`) is the changed file it ends with, at a
  `/`, the longest such.

Two limits, by construction. Coverage counts whatever the run executes: a
test that isn't locked, run by the same command, covers code too, so keep
the test command to the locked tests (and `--strict` lists every reported ID
that isn't locked, as UNKNOWN). And a diff is by line: a new line identical
to one it replaced can read as unchanged, so commit a change before adding
the next when you want each checked on its own.

#### LCOV by test runner

Each writes `lcov.info` (or `coverage/lcov.info`: give that path to
`--coverage`); run it with `--run`, so the report is fresh:

| Runner | Command |
| --- | --- |
| node 22+ (`node --test`) | `node --test --experimental-test-coverage --test-reporter=spec --test-reporter-destination=stdout --test-reporter=lcov --test-reporter-destination=lcov.info` |
| c8 (any node runner) | `c8 --reporter=lcovonly --report-dir=coverage npm test` → `coverage/lcov.info` |
| Jest | `jest --coverage --coverageReporters=lcovonly` → `coverage/lcov.info` |
| Vitest | `vitest run --coverage.enabled --coverage.reporter=lcovonly` → `coverage/lcov.info` |
| Python, coverage.py 6.3+ | `coverage run -m pytest && coverage lcov -o lcov.info` |
| Python, pytest-cov | `pytest --cov=. --cov-report=lcov:lcov.info` |
| Rust, [cargo-llvm-cov](https://github.com/taiki-e/cargo-llvm-cov) | `cargo llvm-cov --lcov --output-path lcov.info` |
| Go, with [gcov2lcov](https://github.com/jandelgado/gcov2lcov) | `go test -coverprofile=cover.out ./... && gcov2lcov -infile=cover.out -outfile=lcov.info` |

Node's own coverage lists only the files the tests loaded, so a new file no
test requires is reported as not in the report, which is right: none runs it.
`stoic help verify` prints the same table.

`stoic check PATH... [--lock LOCK]` is the one call to make before
relocking: it compiles every spec given (or under a folder given), checks each
is formatted as `stoic fmt` would write it, and prints the ERROR, DRIFT, VALUE
and WARNING lines verify would print against LOCK, without a line per locked
test, then one summary line:

```
FORMAT   spec/cart.stoic: not formatted (stoic fmt spec/cart.stoic)
checked 9 file(s): 1 not formatted, 3 change(s) since spec/stoic.lock (tests: 1 changed, 0 only through their target, 2 added, 0 removed); review them, then relock: stoic lock spec --lock spec/stoic.lock
```

It exits 0 only when every file compiles, is formatted and matches the lock
(`checked 9 file(s): they compile, are formatted and match spec/stoic.lock`).

`--no-against` says the opposite explicitly: check the working copy's lock,
exactly as with no `--against` at all. It's for scripts that pass one or the
other, and for `stoic verify /dev/null --no-against`, which shows every locked
test's state against an edited spec before you relock (see
[the guide](WRITING.md)). Giving both is a bad argument.

While implementing, `stoic verify results.txt --watch` reruns the check whenever
a results file, the lock or a locked spec changes (polled twice a second, by
modification time, size and a hash of the content, so even a same-size rewrite
is noticed). Ctrl-C stops it.

## Working with several agents

`stoic verify` is a gate, not a reviewer. What it guarantees, and what still
takes people:

- **It checks names, runs and results, not what a test asserts.** A locked test
  passes when a test with its ID ran and passed; `fn ada_signs_up() {}` passes
  too. Someone must review the test bodies against each test's summary (`stoic
  tests` lists them) before merging. [Checked values](#defining-tests) narrow
  the gap: a test that asserts something else than the lock and reports what it
  saw fails as WRONG. They can't stop a test that writes the expected value
  without computing it, so review still matters.
- **`--against` only protects you in CI.** On their own machine an agent
  controls the refs (it can commit a relock, or move `main`), so the trusted
  lock is the one on your protected base branch. Protect the contract with
  branch protection (required review and a required `stoic verify` check) and
  a `CODEOWNERS` file, so changes to specs, the lock, what the gate holds back
  (`stoic.code`), a declared refactor (`stoic.refactor`) or the workflow need an
  owner's approval:

  ```text
  # .github/CODEOWNERS
  *.stoic                            @your-org/spec-owners
  stoic.lock                         @your-org/spec-owners
  **/stoic.lock                      @your-org/spec-owners
  stoic.segments                     @your-org/spec-owners
  stoic.code                         @your-org/spec-owners
  stoic.refactor                     @your-org/spec-owners
  .github/workflows/stoic-verify.yml @your-org/spec-owners
  .github/CODEOWNERS                 @your-org/spec-owners
  ```

- **Adding or changing tests always fails `--against` in that pull request.**
  That's by design (the base lock doesn't have them yet), so plan the path
  around it, or a required check deadlocks:
  1. An owner relocks in a small pull request of its own (the `.stoic` change
     plus `stoic.lock`, no implementation), reviews it, and merges it,
     overriding the failing check as a branch-protection admin if needed.
     Implementation pull requests then rebase onto it and verify cleanly.
  2. Or make the verify check an owner-only path: a separate workflow (for example on
     `workflow_dispatch`, or on a label only owners may apply) that runs
     `stoic verify` without `--against` once the relock is approved.
- **Two branches that both relock will conflict in git.** Resolve the `.stoic`
  files, then run `stoic lock` again on the result; never hand-merge
  `stoic.lock` (a hand-merged lock may carry stale hashes, or one ID twice,
  which `stoic verify` rejects). So git doesn't write conflict markers into
  the JSON, mark the lock as binary in `.gitattributes`:

  ```text
  # .gitattributes
  stoic.lock merge=binary
  ```

  (`stoic.lock -merge` works the same way.) A conflict then keeps one side
  whole and waits for you to relock. A clone can merge the lock by key
  instead, with `stoic merge-lock --install` (see [Segments](#segments-who-owns-what)).

  A `.stoic` file still holding conflict markers (`<<<<<<<`, `|||||||`,
  `=======`, `>>>>>>>` at the start of a line) gives one error per conflict,
  at its `<<<<<<<` line: `unresolved git conflict (lines 3–9): resolve it,
  then relock`. The markers are skipped so the rest still parses (both
  sides' lines are read, a diff3 base section isn't), which usually adds a
  duplicate-name error for an element both sides changed. Such a file doesn't
  compile, so `stoic lock` refuses it, and `stoic fmt` leaves it unchanged.
- **Run parallel agents in separate worktrees or clones** (`git worktree add
  ../agent-a`), one per agent, each with its own results file
  (`results-<agent>.txt`), so no two runs write the same file. `stoic verify`
  takes several results files at once (`stoic verify results-a.txt
  results-b.txt --strict`) when their runs together cover the locked tests.
- **Agents that do share a lock can relock it at the same time.** Each run
  holds the guard for milliseconds and the others wait for it (see
  [Locking](#locking)), so they queue rather than fail, and the last to write
  says what it wrote on top of. An agent killed mid-run (a sandbox timing
  out) never blocks the rest: the system releases its lock on the guard, and
  the next run clears what it left. What the guard can't do is reach across
  machines on a network filesystem: give each machine its own clone.

### Segments: who owns what

The guard keeps the lock file whole, but on its own it's last writer wins:
a relock freezes whatever specs are on disk, another agent's half-done edit
included, and a failing test doesn't say whose it is. `stoic.segments`,
beside the lock, gives each part of the spec an owner:

```text
# segment @owner: top-level elements (nested ones follow their parent)
billing @agent-a: invoice money tax
cart @agent-b:    cart cart_item checkout
```

A segment lists top-level definitions (named elements that aren't tests);
an element nested in one belongs to its segment, and a test to the segment
of what it tests, whichever file it's written in (rebinding a test to
another target changes both segments: the one it leaves, and the one it
joins). Anything listed nowhere is
unassigned. An element in two segments, a nested one, a test or a name no
locked file defines is an error with its line, and every lock refuses a
`stoic.segments` with one, `--as` or not (each problem, then `error:
stoic.segments has problems; fix the lines above, then relock; nothing was
locked`): a broken file never gates less than a sound one. A file's own part (its
file-level kept comments, unnamed elements, and kept comments on tests and on the elements inside them) is in
every segment its definitions and tests are in. The owner is the only agent
whose relock may change a segment, unless a
[claim](#claims-and-fencing-tokens) names another holder. A segment without
an owner, and what no segment holds, are open to any relock.

The lock records what segments need: each definition with a hash (`defs`,
`top` for a nested one), each test's `target`, and `reads`, the definitions
outside a test (or definition) that its hash covers through `->` reuse, so a
change can be traced to a segment. `stoic segments` lists the segments, their
test counts, what's unassigned, and every reuse between segments
(`cart reads billing.money (cart, cart_total)`): draw segments along those
edges, since each one is coordination.

- **Attribution.** With `stoic.segments`, every FAILED, WRONG, MISSING,
  SKIPPED, DISPUTE and DRIFT line of `stoic verify` (and `stoic check`) ends
  with `(segment billing)`. With `--as NAME` (or `STOIC_AGENT=NAME`), the
  verdict counts the agent's own tests apart from others' (`; yours: 30/30
  passed, others': 10/11 passed`), and a last line tells it not to edit a
  failing test that isn't its own: fix the code, or report the ID and owner.
- **Owned segments gate every relock.** A change to a segment someone owns
  (or holds by a claim) is locked only by a relock `--as` that owner:
  `stoic lock spec --as agent-b` recomputes agent-b's segments and what no
  one owns, and copies every other entry from the lock as it is under the
  guard. A relock without `--as` is gated the same way, so it can change
  only what no one owns; when it's refused, a first line says so (`warning:
  stoic.segments gives segments owners; a relock without --as may change
  only what no one owns, and an owner relocks its own with --as NAME`), and
  a relock it doesn't refuse says nothing of owners. When a relock would change what another agent
  holds, including another segment's tests that change only because they
  reuse one of its definitions, nothing is written: each item is listed
  with its file, line and owner, and the last lines say whom to ask:

  ```text
  error: this relock, as engineer, changes what others own, so nothing was locked:
    ~ test `refund_window` (segment rules, owned by product): changed (rules.stoic:2)
  this changes rules, owned by product: ask product (or report each test as `dispute ID: why`); don't relock it as someone else
  ```

  An agent that owns nothing still relocks `--as` itself (what no one owns
  changes), and with no `stoic.segments` or no lock yet, `--as` is a plain
  relock. A relock also refuses when
  something of its agent's reuses a definition another agent's segment is
  changing, rather than freeze that unfinished change into its tests. The
  refusal is strict (it can't tell who made a change), so agents that edit
  at the same time each work in their own worktree; within one, they relock
  in turn. A change that reuses across two owners' segments needs both
  segments under one owner for that relock (a reviewed edit of
  `stoic.segments`).
- **Who relocked it.** A relock `--as` a segment's owner stamps the owner in
  the lock's `fences` (`"fences": {"rules": {"holder": "product"}}`), as a
  claim's relock stamps its token. `stoic verify --against REF` reads who
  owns what from `stoic.segments` as REF has it, and a segment with an owner
  whose entries changed since REF without its owner's fence is `SCOPE
  segment rules: refund_window changed since main, but no relock as its
  owner product made the change; ask product (…)`, with the next line
  `Stop: … and this changes rules, owned by product: ask product (…)`. A
  change to `stoic.segments` itself is DRIFT (`DRIFT    stoic.segments
  changed since main: rules's owner changed from product to none`), so an
  agent can't give itself a segment. `--as` is a name, not a login: the
  lock, its fences and `stoic.segments` are still reviewed (CODEOWNERS on
  them), and the fence only records what the relocking stoic was told.
- **Owner review.** A ticket can legitimately touch what an owner holds: a
  new key changes the shape an owned test pins, or the ticket makes an owned
  test's input obsolete. The implementer can't relock that, so it reports
  `dispute ID: why` or leaves WRONG lines, and the work waits for the owner.
  `stoic review [RESULTS...] --as OWNER` lists what waits, in OWNER's
  segments only: each change the gate would refuse anyone else (`CHANGE`,
  with file and line), each checked value it moves (`VALUE`), each dispute
  with what the test expects now (`DISPUTE`), and each owned test that passed
  with other values (`WRONG`). Its last line says what to do:

  ```text
  $ stoic review results.txt --lock spec/stoic.lock --as product
  WRONG    yanked_listed: expected [{ version: '1.0.0', yanked: true }], observed [{ version: '1.0.0', yanked: true, deprecated: null }] (at [0].deprecated)  (rules.stoic:2)
  next: 1 WRONG above, in product's segments. Decide as product, running stoic review results.txt --lock spec/stoic.lock --as product with: --accept-observed yanked_listed to take the observed values into the spec and relock; --reject to say what stands and what to revert.
  $ stoic review results.txt --lock spec/stoic.lock --as product --accept-observed yanked_listed
  accepted yanked_listed: [{ version: '1.0.0', yanked: true }] -> [{ version: '1.0.0', yanked: true, deprecated: null }] (rules.stoic:4)
  locked 2 tests from 2 file(s) into spec/stoic.lock
    …
  relocked segment rules as product; every other entry is copied from spec/stoic.lock
  next: approved as product; rerun the tests, then stoic verify results.txt --lock spec/stoic.lock.
  ```

  The owner settles it in one step. `--approve` relocks the changes as they
  stand: it is `stoic lock … --as OWNER` over what the lock covers, so the
  gate is the same (another agent's segment changed refuses it all, and
  what no one holds rides along, as in any relock as OWNER). `--reject`
  writes nothing and says what to revert (`REVERT`, with the value to put
  back) and which tests stand (`KEEP`), for the implementer.
  `--accept-observed ID,…` rewrites each of those tests' checked values in
  the spec's source to what the results' `pass` lines observed (canonical
  when it's a Stoic value, quoted as `stoic fmt` quotes, nothing else in the
  file changed, a formatted file kept formatted), then relocks as
  `--approve` does, and puts the files back if that relock is refused. It
  refuses, writing nothing, a test that isn't OWNER's (in the spec or in the
  lock), a value no `pass` line reports or two report differently, a value
  that isn't written once in the test's own element (a field's example's,
  one it takes through `->`), and, unless `--approve` is given too, any other
  change in OWNER's segments, so accepting a value never quietly approves an
  edit of the rule itself. A dispute about a value can carry it: report
  `pass ID = VALUE` beside `dispute ID: why`. review never acts outside
  OWNER's segments, and only as OWNER; like `--as` everywhere, OWNER is a
  name, so CODEOWNERS on the specs and the lock still decide who may push
  the result.
- **Briefs.** `stoic brief FILES --as NAME` adds a last rule to the contract:
  the elements NAME owns, and every other element, which it must not change.
- **Merging locks.** `stoic merge-lock BASE OURS THEIRS [PATH]` merges two
  branches' locks by key, in git's merge-driver order (it writes OURS):
  files by path, definitions by file and name, tests by ID, any other object
  field by its keys. An entry both sides changed differently is a conflict:
  it's listed with its owner, OURS keeps our side so it still parses, and the
  run exits 1, so git marks the lock conflicted. The last line says who
  relocks it once the specs are merged: its owner (`its owner: stoic lock …
  --as agent-a`), since the gate refuses anyone else's relock of an owned
  entry, or, when no one owns it, any `stoic lock …`. `stoic merge-lock --install`
  sets the driver up for one clone (`.git/config` and `.git/info/attributes`,
  never `.gitattributes`, whose `stoic.lock merge=binary` stays the fallback),
  naming this stoic by its full path, quoted for the `sh` git runs drivers
  with (on Windows written with `/`, as Git for Windows' sh takes it:
  `'C:/Program Files/stoic/stoic.exe' merge-lock %O %A %B %P`).
  The driver compiles nothing, since git runs it before the specs are
  merged, so once they are, `stoic merge-lock --check` recomputes every test
  and lists those whose hash neither side locked (`changed only in
  combination`): each side's change was fine alone, and together they change
  what a third test tests (write skew). With HEAD and MERGE_HEAD by default
  while merging, or HEAD's two parents after; `--check OURS THEIRS` names the
  sides (lock files or git refs).

### Claims and fencing tokens

An owner in `stoic.segments` is fixed until someone edits the file. A claim
hands a segment to an agent for a while, and makes a relock that outlived its
claim fail in CI:

```sh
stoic claim billing --as agent-a            # claimed billing as agent-a: claim 1, until 2026-11-28T12:12:03Z
stoic lock spec --as agent-a                # stamps claim 1 into the lock's fences
stoic claim billing --as agent-b --take-over   # once agent-a's claim has expired: claim 2
stoic verify results.txt --against origin/main # on agent-a's branch: STALE
stoic release billing --as agent-b          # CI, once agent-b's change is merged
```

- **Where claims live.** On the `stoic-claims` branch of the repository
  holding the lock (every worktree of it shares the branch; where it doesn't
  exist, `origin/stoic-claims` is read, as in a CI checkout):
  `claims/SEGMENT.json` per claimed segment (`segment`, `holder`, `token`,
  `claimed`, `expires`) and `seq`, the last token issued. Each claim,
  renewal, takeover and release is one commit, stored by compare-and-swap of
  the ref (`git update-ref`), so of two agents claiming at once one wins and
  the other is told who holds it; a claim never waits. Push the branch
  without force (`git push origin stoic-claims`, a compare-and-swap on the
  remote) so CI sees it.
- **Tokens only rise.** A new claim's token is `seq + 1`. Claiming a segment
  you hold renews it and keeps its token; `--ttl` (default `2h`) says when
  another agent may take it over with `--take-over`, which issues a new
  token. Expiry only allows that takeover: it never decides what verifies,
  so a clock can't make a stale change pass. A segment with an owner in
  `stoic.segments` is claimed only by that owner.
- **Holders.** Where a segment has a claim, its holder holds it instead of
  the owner: `stoic lock --as`, `verify --as` and `brief --as` treat it as
  the holder's, attribution says `(segment billing, held by agent-a)`, a
  refused relock names `segment billing, held by agent-a, claim 1`, and
  `stoic segments` ends its line with `, held by agent-a (claim 1, until …)`.
- **Fences.** `stoic lock --as NAME` writes the token of NAME's claim into
  the lock's `fences` (`"fences": {"billing": {"token": 1, "holder":
  "agent-a"}}`) for each claimed segment the relock changes (for a segment
  it owns without a claim, its owner's fence, `{"holder": "agent-a"}`). A
  relock without `--as` keeps only the fences of segments it doesn't change,
  which can only be segments no one holds.
- **STALE and SCOPE.** With claims in use, `stoic verify --against REF`
  checks every segment whose entries differ from REF's lock. One relocked
  under a claim since taken over, or released, or older than REF's fence, is
  `STALE    segment billing: relocked under claim 1 (agent-a), but claim 2
  (agent-b) has taken billing over; these billing changes can't merge. Stop
  and report "my claim 1 on billing was taken over".` One no fence covers (a
  relock without `--as`, a hand edit, or what no segment holds) is `SCOPE
  segment tax: tax, tax_rate changed since main, but no claim on tax fences
  them …`. Either fails verify, and the verdict counts them (`, 1 stale`,
  `, 1 out of scope`). A lock with fences where the branch is missing is an
  ERROR saying to fetch it. The DRIFT line for the relock stays: a claim
  decides who may propose a relock, not whether it needs review. With a
  STALE line, verify's `next:` line is a stop that comes first: `Stop: a
  claim this was relocked under was taken over or released, so these changes
  can't merge. Report "my claim 1 on billing was taken over" and wait; don't
  claim it back, relock, or edit a spec or a test, to make this pass. Only a
  coordinator hands billing back, by taking it over once its claim expires:
  stoic claim billing --as agent-a --take-over.` (with `--lock LOCK` when the
  lock isn't `stoic.lock`): the agent stops, and whoever coordinates decides
  whether its work goes on.

## Handing a spec to an agent

`stoic brief` prints a Markdown block to paste into an AI coding agent's
prompt or a `CLAUDE.md`:

```sh
stoic brief signup.stoic > BRIEF.md       # or several files, or a folder of them (stoic brief spec)
stoic brief signup.stoic --format json    # the same, structured, for tooling
```

It starts with the contract: implement the spec; implement every listed test,
in any language; have the tests write their results (`pass ID`, `fail ID:
why`, `skip ID: why`) to a file of their own (e.g. `results.txt` in the
worktree), pointing at `stoic harness --lang …` for a reporter that does
(see [Reporters](#reporters)) and saying to delete the file before each
run, since reporters append; make `stoic verify` pass; and never edit `.stoic` files or
`stoic.lock`. A spec or test that looks wrong or impossible still isn't
edited, weakened or skipped: the test records `dispute ID: why` as its result
(see [Results](#results)), which verify lists first and fails on until an
owner settles it, and the agent names it in its final report and implements
everything else, so the rule works for an agent running alone too.
That's the rule for an implementer, the default. An agent that owns the spec
(it decides behaviour, not only builds it) gets `--role owner`, whose last
rule says the opposite: change the spec first, review what the edit did with
`stoic check`, relock, and say in the final report which checked values
changed (the relock lists each one), never editing `stoic.lock` by hand. When a test checks a value, a rule after the one about results says to
report it (`pass ID = observed`), as the spec writes it. Then, for each file,
it gives the spec in English, laid out to
scan: a block per top-level element whose first line introduces it, then a
bullet per event and per field, with children as indented bullets (`stoic
FILE` and the JSON brief's `description` keep the plain prose), with any
[kept comments](#kept-comments) as `Note: …` bullets on their element and
the file's under **Notes**. Then its tests,
one per line as `` `ID` — summary ``, after a plain warning to copy each ID
exactly rather than derive it (IDs are slugged: `signup_email_accepts_ada_acme_com`
for `+"ada@acme.com"`, so one rebuilt from the value is easily wrong).

Each test is stated once. Test elements appear only in this list, not also in
the spec above it, and a test's kept comments sit under its line. A field's
examples share one line that says how each is tried, so its `^"…"` steps
appear once rather than on every example:

```markdown
- `cart.qty`, given on a fresh cart, add('penny', value):
  - `cart_qty_accepts_1` — accepts 1
  - `cart_qty_rejects_minus_1` — rejects -1
```

It ends with the exact verify command:

```sh
stoic verify results.txt --strict --against origin/main
```

`--against` is there by default, so the agent is checked against the reviewed lock,
not one it could regenerate itself. The brief adds that CI runs the same check
with `--run`, so the tests must really write the file. Pass `--against REF` to `stoic brief` for
another branch or remote (`--against upstream/release`), `--no-against` to leave
the flag out (the command then checks the working copy's lock), and `--lock PATH` when
the lock isn't `stoic.lock`. Without `--lock` and with no `stoic.lock` in the current
folder, the brief names the `stoic.lock` the files share above them (`stoic brief spec`
with `spec/stoic.lock` gives `--lock spec/stoic.lock`), and `--as` reads
`stoic.segments` beside it. When a spec's folder isn't inside a git work tree,
`--against` could only fail, so the brief leaves it out by itself and says so
in one line ("this folder isn't a git repository, so verify uses the working
copy's lock"; a `note` in the JSON). Inside git but without an `origin/main`
ref (a repository with no remote yet) it does the same, with a note saying so
and that `--against REF` names another committed lock. An explicit
`--against REF` still wins. A file that doesn't compile prints its errors and
nothing else, with exit code 1.

See `tests/fixtures/signup_tests.brief.md` for a complete example, and
`tests/fixtures/kept_comments.brief.md` for one with kept comments.

## Spec first, as agents write: `stoic gate`

"Change the spec first" is a rule in the brief and in a CONTRIBUTING file, and an
agent in a hurry skips it. `stoic gate` enforces it when the agent writes a file,
not later at review:

```text
$ stoic gate src/app.js
deny   src/app.js: implementation code (no stoic.code: not a spec, test, doc, hidden or ignored file), but the spec hasn't changed since the last ticket commit (3e2796e) and there is no results.txt
next: spec first: write this ticket's change in the spec, review it with stoic check spec and relock with stoic lock spec; if the code must change to meet the spec as it is, run the tests so results.txt shows the failing locked test; if nothing it does changes, stoic gate --refactor "WHY".
$ echo $?
2
# … edit spec/app.stoic, stoic check spec, stoic lock spec …
$ stoic gate src/app.js
allow  src/app.js: implementation code (no stoic.code: not a spec, test, doc, hidden or ignored file), and the spec changed since the last ticket commit (3e2796e) and is locked
```

It prints one line per path, then on a deny one `next:` line, in verify's style.
Allowed, everything goes to stdout with exit 0; denied, to stderr with exit 2,
which is what agent tools' hooks read as a block whose reason is shown to the
model. `--format json` prints `{ allow, paths: [{ path, allow, implementation,
says }], next }` instead.

**What may always be written:** anything that isn't implementation code: specs,
the lock, `stoic.segments`, `stoic.code`, `stoic.refactor`, tests, docs, hidden files. **What
implementation code is** is declared in `stoic.code` beside the lock. It holds one
glob per line, relative to the project root (the git work tree's top folder, or
the lock's folder outside git). `*` and `?` match within a name, `**` across
folders, and `!glob` takes matches back out; the last matching line decides:

```text
# spec/stoic.code: Stoic's own
src/**
# unit tests: no locked test runs them
!src/lsp/tests.rs
```

Without it, implementation code is every file in the project but specs, tests (a
`test`, `tests`, `spec` or `__tests__` folder, or `*.test.*`, `*_test.*`,
`test_*`), docs (`*.md`), hidden files and what git ignores. Declare it rather
than rely on that. `stoic verify --coverage` uses the same definition
(`src/codepaths.rs`).

**When implementation code may be written**, the first rule that applies decides:

1. No lock, a lock that can't be read, a spec that doesn't compile, or a spec
   changed since the lock and not relocked: **denied**, with what to do.
2. The lock differs from the lock committed in the *base* (in its files' specs,
   definitions or tests): **allowed**. This ticket's spec change exists and is
   locked. The base is `--against REF`; else the newest commit whose subject (the
   message's first line) starts `T` and a digit (the ticket convention: `T0` further
   down a message doesn't count); else, when `origin/main` exists and its merge base
   with `HEAD` isn't `HEAD` itself, that merge base; else the same with the local
   `main`, so a ticket's branch is measured from where it left `main`; else `HEAD`.
   Outside git there is no base, and a locked spec is enough.
3. `stoic.refactor` declares the base: **allowed**. `stoic gate --refactor "WHY"`
   writes it, for a ticket that changes code but no behaviour (commit it, so the
   review sees the claim). The next ticket's commit ends it.
4. A locked test is FAILED or WRONG in `results.txt` (`--results`): **allowed**.
   The code is being brought to a spec that didn't change, as in a bug fix. A
   missing, skipped or disputed test doesn't count.
5. Otherwise **denied**.

Rules 3 and 4 keep the gate from deadlocking real work: a fix to meet an unchanged
spec runs the tests first, so the failing test shows. The gate checks timing, not
intent. An agent can still hand-write a `fail` line or a refactor declaration to
get through. Both are visible, and `stoic verify --run … --against` in CI remains
the check that can't be talked around.

**Wiring it into agent tools.** `stoic gate --install TOOL...` writes each tool's
project config so the tool runs `stoic gate --hook TOOL` before every file write.
The hook reads the tool's event on stdin, finds the paths written, and answers in
its protocol (exit 2, with the reason on stderr):

| TOOL | Config it writes | Before |
| --- | --- | --- |
| `claude-code` | `.claude/settings.json`, `hooks.PreToolUse` | Write, Edit, MultiEdit, NotebookEdit |
| `codex` | `.codex/hooks.json`, `hooks.PreToolUse` (trust it with `/hooks` in Codex) | apply_patch (its paths read from the patch), Edit, Write |
| `gemini-cli` | `.gemini/settings.json`, `hooks.BeforeTool` | write_file, replace |
| `factory-droid` | `.factory/hooks.json`, `PreToolUse` | Create, Edit, ApplyPatch |
| `git` | the `pre-commit` hook (`core.hooksPath` honoured), running `stoic gate --staged` | each commit |
| `agents-md` | an `AGENTS.md` section saying the rule and the loop | advisory |
| `skill` | the agent skill in `.claude/skills/stoic/`, `.agents/skills/stoic/` and `.kiro/skills/stoic/` | on demand (below) |

`all` is every one but `git`, which you add by name. An existing JSON config keeps
its keys and order, and gets the group appended. A config that already runs the
gate is left alone. An existing `pre-commit` hook is never replaced: you get the
line to add to it instead. Pass `--lock spec/stoic.lock` when the lock isn't
`stoic.lock`, and `--results PATH` when the tests write their results elsewhere, and
the generated commands carry them. A hook names the lock and
results from the project folder: the tool's `CLAUDE_PROJECT_DIR`,
`GEMINI_PROJECT_DIR` or `FACTORY_PROJECT_DIR`, else the git top folder of the
event's `cwd`. Git's hook works the same from a linked work tree (`git worktree
add`): the project root is that work tree's top folder.

**The agent skill.** `stoic gate --install skill` writes an [Agent Skill](https://agentskills.io/specification)
that teaches an agent the loop in under 600 words, so it needn't read this
reference and the guide first. A tool lists only its name and
description, and reads the rest when a task needs it. The skill covers the loop,
an example test that checks a value, reading verify's `next:` line, the gate's
three ways forward, disputes and owners. Its `references/WRITING.md` is `stoic
guide`, and its rules are `stoic brief`'s, verbatim, so the skill and stoic can't
disagree.

- `.claude/skills/` is read by Claude Code (and by Copilot, Cursor, OpenCode
  and Amp).
- `.agents/skills/` is the shared folder, read by Codex, Gemini CLI, Factory,
  Cursor, Copilot, OpenCode, Amp, Windsurf, Roo Code and goose.
- `.kiro/skills/` is Kiro's.

A folder someone edited (its files no longer match the sha256 its `SKILL.md`
records), or one stoic didn't write, is left alone unless you pass `--force`. A
newer stoic's install updates its own. For any other tool, `stoic guide --skill`
prints `SKILL.md`. The skill is guidance; the gate, verify and CI still enforce.
See [`docs/research/07-agent-skills.md`](../docs/research/07-agent-skills.md) for the
format, each tool's folders and sources.

**Unsupported, for now:** Cursor, GitHub Copilot, Windsurf/Devin, Kiro, Qwen Code,
Augment, Antigravity, Cline, Junie, OpenHands and Amp all have some pre-write hook,
but at least one part of the protocol an adapter needs (usually the field that
names the written file) isn't documented. Several of them (Cursor, Copilot CLI,
Devin, Continue) also read `.claude/settings.json`, which may gate them through the
Claude Code adapter. Aider, Zed and Roo Code can't block a write, so for those
tools the gate is git's hook and CI. See
[`docs/research/06-agent-hooks.md`](../docs/research/06-agent-hooks.md) for each
tool's protocol, its sources and how the adapters were tested (Claude Code's
live).

**What a hook can't do.** A hook sees file-writing tools, not what a shell command
writes (`cat > src/x.js`), so shell events are allowed. Most tools let the action
through when the hook itself fails (`stoic` not on PATH, a timeout), and `git
commit --no-verify` skips git's hook. The gate catches an agent that forgot the
order, not one that sets out to evade it. That remains the job of CI.

## CI

`editors/ci/stoic-verify.yml` is the workflow `stoic init` writes to
`.github/workflows/stoic-verify.yml` (or copy it there yourself). It installs stoic and gates the
build by having stoic run your tests itself:

```sh
stoic verify results.txt --run "<your test command>" --strict \
  --against ${{ github.event.pull_request.base.sha }}
```

To fail a pull request that adds code no locked test runs, have the test
command write [LCOV](#lcov-by-test-runner) too and add `--coverage`:

```sh
stoic verify results.txt --strict \
  --against ${{ github.event.pull_request.base.sha }} \
  --coverage lcov.info \
  --run "node --test --experimental-test-coverage --test-reporter=lcov --test-reporter-destination=lcov.info"
```

`--against` checks the run against the `stoic.lock` committed on the base
branch, so that lock is the trusted one: a pull request can't loosen a test by
editing the lock in the same change. CI should pin the base by its SHA, as
here, rather than `origin/<base branch>`: the branch can move (another pull
request merges) while the job runs, and then the lock checked isn't the one
the pull request was opened against. Keep `fetch-depth: 0` on the checkout so
that commit is there to read.

Stoic's own CI does both for itself (`.github/workflows/ci.yml`). The
`self-spec` job verifies the self-spec against the base's lock, and on pull
requests the `diff-coverage` job runs the locked tests with
[cargo-llvm-cov](https://github.com/taiki-e/cargo-llvm-cov) and fails on
any line of `src/` the pull request changes that none of them runs:

```sh
cargo llvm-cov --test self_spec --lcov --output-path lcov.info
stoic verify target/self-spec/results.txt --lock spec/stoic.lock --strict \
  --against "$BASE_SHA" --coverage lcov.info
```

Only `--test self_spec` runs, because the unit tests aren't locked and code
only they run is unspecified. The tests spawn the `stoic` binary, which is
instrumented too, so `src/main.rs` counts. That job runs on pull requests
only. On a push, verifying against the previous commit would report every
reviewed relock as drift.

The gate isn't a CI step: it acts as files are written, through the hooks
`stoic gate --install` writes, and CI's `verify` is the check it can't
talk around. In this repository, the commands are `stoic gate --install
claude-code --lock spec/stoic.lock --results target/self-spec/results.txt`
and the same with `git`. Both are local and not committed; `AGENTS.md` is.

## Editor support

The LSP provides diagnostics, hover (any element, field or event explained in
English; on an example or a field's given step, what that one is; a kept
comment says it's shown to the implementer, and where), completion (tags;
common event names as suggestions; capabilities, rules, examples and formats
inside `( )` (`|null` among them), and a step after `^` there; actions inside `[ ]`; sibling fields after `->`;
the base's fields and events after `#-` and `@-`; nothing inside strings and
comments), go-to-definition on `->field` and `->file.element` (into other
files), and document symbols. When a file changes, its errors refresh along with
those of every open file that reuses it, directly or through other files, so
unsaved edits to a shared file show up at once. Open files are matched by path,
however the editor spells their URI. An untitled buffer resolves
`->file.element` from the workspace folder; without one, references to other
files are skipped with a warning to save the file. Diagnostics carry a stable
`code` where one is assigned (`missing-file`, `unknown-element`,
`circular-reuse`, `contradictory-limits`, `unknown-field`, `unknown-event`, …),
so tools can tell them apart without matching their wording. A malformed message gets a
JSON-RPC error reply instead of stopping the server, and messages over 64 MiB
are refused. `exit` without `shutdown` ends with status 1.

**VS Code**: the extension has no Marketplace listing yet, so build it from
`editors/vscode` and install the `.vsix` that makes:

```sh
cd editors/vscode
npm install && npm run package && code --install-extension stoic-*.vsix
```

It highlights every construct (notes, modifiers, examples, `|null`, expectations, `#-`/`@-`
removals; kept comments as `comment.block.documentation.stoic`, apart from
private ones), gives `.stoic` files the Stoic mark as their icon (a file icon
theme that has its own icon for them takes precedence), and starts
`stoic lsp` for `.stoic` files. Set `stoic.serverPath` if
`stoic` isn't on your `PATH` (`~` is your home folder; a relative path such as
`target/debug/stoic` is relative to the first workspace folder); if the binary
can't be found you get an error with
a link to that setting, and changing it restarts the server. **Stoic: Restart
Server** restarts it by hand (after a `cargo build`, say). For development, open
the folder in VS Code and press F5. `npm test` tokenizes every
`tests/fixtures/*.stoic` with the real TextMate engine (`vscode-textmate` +
Oniguruma), checks each construct's scope, runs `extension.js` against a stubbed
`vscode` API and checks what `vsce` packages. `npm run package` first bundles
`extension.js` and the language client into one minified `dist/extension.js`
with esbuild (`scripts/build.js`), so VS Code loads one file, then runs
`scripts/check-package.js`, which fails if `vsce ls` would leave out
`dist/extension.js` or `package.json` (vsce itself can list nothing and exit 0).

**Tree-sitter**: the grammar is in `editors/tree-sitter-stoic` (corpus tests in
`test/corpus`, plus highlight, fold and indent queries). It accepts and rejects
the same syntax as the compiler's parser: identifiers and whitespace follow
Rust's Unicode `is_alphabetic`/`is_whitespace`, a closing tag must name the
innermost open element, and an element has at most one note. A kept comment
is a `kept_comment` node of its own, highlighted `@comment.documentation`
(ordinary ones are `comment`). A small external
scanner (`src/scanner.c`) keeps the stack of open tag names for that check
(names past 64 bytes compare by prefix; outer levels of extremely deep nesting
that don't fit tree-sitter's 1 KB state accept any closing tag) and emits a
zero-width token at end of file, so an element left unclosed there (no `/>`,
`>` or `</tag>`) parses cleanly, just as the compiler accepts it with a
warning. Checks that aren't syntax stay with the compiler (the LSP reports
them): a number too large to fit (`#n(>99999999999)`), unknown `->` targets,
contradictory limits. Run `make -C editors` to generate the parser and
compile `parser.c` and `scanner.c` into `editors/nvim/parser/stoic.so`, and
`make -C editors test` to run the corpus.

**Neovim** (0.11+): `editors/nvim` is a runtime folder with filetype detection,
Tree-sitter highlighting and folds (falling back to `syntax/stoic.vim` when the
parser isn't built), `lsp/stoic.lua`, and a `.stoic` file icon for
nvim-web-devicons or mini.icons when either is installed (a Nerd Font column,
in Stoic's verdigris). With lazy.nvim:

```lua
{ dir = "~/src/stoic/editors/nvim", lazy = false },
-- then enable the server: vim.lsp.enable("stoic")
-- (AstroNvim: add "stoic" to astrolsp opts.servers)
```

The server asks for incremental sync and agrees to utf-8 positions when the
client offers them (Neovim and Helix do; VS Code and Zed get UTF-16 code
units), so Neovim sends only each edit, as byte columns; `lsp/stoic.lua` sends
edits 50 ms after typing stops instead of Neovim's default 150. Edits that
arrive while the server is checking are applied together and checked once,
and a request cancelled while it waits isn't run. `make -C editors test-nvim`
drives the server from headless Neovim (with `stoic` on your `PATH`) in both
encodings, on a line with an emoji and an `é` before the diagnostic.

## Starting a project

`stoic init [DIR]` (default: the current folder) writes:

| File | What it's for |
| --- | --- |
| `spec.stoic` | a short commented example: a form with rules and `+`/`-` examples, and one test element |
| `.gitattributes` | `stoic.lock merge=binary`: a conflicting lock is relocked, never merged line by line |
| `CODEOWNERS.stoic.example` | lines that make changes to `*.stoic`, `stoic.lock`, `stoic.segments`, `stoic.code`, `stoic.refactor` and the verify workflow need a review; copy them into `.github/CODEOWNERS` (named `.example` so it never takes effect by accident) |
| `.github/workflows/stoic-verify.yml` | the [CI](#ci) workflow from `editors/ci/stoic-verify.yml` |

Existing files are skipped, and the output says which; `--force` overwrites
them. It then prints the next steps: `stoic spec.stoic` to read the spec
back, `stoic lock .` to freeze its tests, have your tests write `results.txt`
(`pass ID` / `fail ID: why` / `skip ID: why`), and
`stoic verify results.txt --run "<your test command>" --strict`, the check CI runs.
The last step, `stoic gate --install all`, makes AI agents' tools ask before
they write code and gives them the agent skill that teaches the loop (see
[Spec first, as agents write](#spec-first-as-agents-write-stoic-gate)).

## Formatting

`stoic fmt PATH...` rewrites files (folders: every `*.stoic` inside, skipping
hidden folders, `target` and `node_modules`) in one canonical layout.
`stoic fmt --check .` writes nothing and exits 1 listing the files that would
change, for CI; `stoic fmt -` formats stdin to stdout. A file with syntax
errors is never touched: its diagnostics are printed and the exit code is 1.

```html
<form:signup=account
  #username(>=3, <=20, !" ", +"ada", -"a b")->"lowercased"
  #password(>=12)
  @submit="create account"
/>
<button @~+click="save" /> <!-- comments stay where they were -->
```

- One element per line, children indented two spaces. An open tag that fits
  in 100 columns stays on one line; a longer one (or one with comments
  inside) gets one attribute per line, indented two more, with `>` or `/>`
  back on a line of its own. An attribute still wider than 100 columns on its
  own line, with two or more parts in its parentheses (a field's rules and
  examples), gets one part per line, one level deeper, each but the last
  ending `,`, and `)` back at the attribute's indent followed by what came
  after it (`)->"lowercased"`).
- Canonical spacing: `#a(>=3, <=20)`, `@~+click="x"`, `=>!"y"`, a space
  before `/>`. Strings are double-quoted with only `\`, `"` and newlines
  escaped. Values keep the author's choice of quoted or bare where both read
  the same (`#n="007"` stays quoted).
- Attribute order is never changed: it can carry meaning.
- Empty elements self-close (`<a></a>` becomes `<a />`); an element left open
  at the end of the file gets its closing tag. A strictness marker stays
  touching the tag (`<form!:pay>`), and a note on a tag goes after `*` and
  `:name`: `<row*:line"zebra">`.
- Comments are kept, in order, with what they follow: a one-line comment
  after something on its line stays at the end of that line, and whatever
  came after it on that line starts the next (`<a /> <!-- x --> <b />`
  becomes `<a /> <!-- x -->` and `<b />`). Any other comment gets a line of
  its own (one inside a tag's name moves above it). Only the layout moves:
  a kept comment still belongs to the element it came before.
- At most one blank line between elements, kept wherever the author left at
  least one; a single trailing newline.
- Line endings are kept: a file whose first line ends in `\r\n` (a Windows
  checkout) is formatted as if it used `\n` and written back with `\r\n`, so
  `stoic fmt --check` passes on a formatted file whatever git checked out.

Formatting never changes meaning: the tests check that every fixture and a
few thousand generated documents parse to the same tree, compile to the same
prose, spec and JSON, keep every comment, and format to themselves.

## Architecture

`lexer` → `parser` (AST with spans, error recovery) → `resolve` (`->` reuse,
across files) → `sema` (the resolved model: merges split events, `#a->b`,
duplicates) → `checks` (tests and their IDs) → `render/{prose,spec}` or JSON.
On top of that pipeline: `lock` (`stoic lock` and `stoic verify`), `coverage`
(what a lock covers: one definition per name, its roots), `diffcov` (`verify
--coverage`: LCOV, the lines changed since REF), `codepaths` (which files are
implementation code: `stoic.code`), `results` (the results format) and
`values` (Stoic values), `segments` (`stoic.segments`, the owner gate,
fences, `stoic segments`), `claims` (the `stoic-claims` branch), `merge`
(`stoic merge-lock`), `review` (`stoic review`), `brief` (`stoic brief`),
`harness` (the reporters, `src/harness/`), `gate` (`stoic gate`), `hooks`
(agent tools' hook events and configs), `jsonedit` (adding a hook to a JSON
config in place), `skill` (the agent skill, `src/skill/`), `fmt`, `init`,
`par` (git reads and jobs started before they're waited for) and `lsp`, a
dependency-free JSON-RPC server.

## Stoic specifies itself

Stoic's behaviour is a Stoic spec, held to the contract Stoic puts on any
project. `spec/` specifies the CLI, a file per area so several people can
edit it at once:

| File | Tests | What it specifies |
| --- | ---: | --- |
| `syntax.stoic` | 100 | what compiles and what errors, IDs, examples, kept comments, strictness, the JSON shape |
| `values.stoic` | 20 | Stoic's value notation: what parses, how values compare, the canonical form |
| `lock.stoic` | 57 | the lock, its hashes, what a relock prints (renamed tests too), the guard and its OS lock, concurrent runs, leftovers |
| `verify.stoic` | 73 | results, verdicts and the next line, drift, `--run`, `--against`, `--watch` |
| `brief.stoic` | 20 | the brief: its contract, sections, verify command, JSON, folders |
| `harness.stoic` | 25 | `stoic harness` and the sh reporter, where the node reporter must not go |
| `cli.stoic` | 44 | fmt, init, guide, help, check, `--version`, compiling several files, the options each command takes, exit codes |
| `segments.stoic` | 58 | `stoic.segments`, attribution, `stoic segments`, the scoped relock and brief `--as` |
| `claims.stoic` | 37 | `stoic claim` and `stoic release` on the claims branch, fences, holders, STALE and SCOPE |
| `review.stoic` | 13 | `stoic review --as OWNER`: what waits for an owner, approve, reject and `--accept-observed` |
| `gaps.stoic` | 17 | `\|VALUE` or-values, the one JSON object, contract rule 5 without a person, grouped relock lines |
| `expectations.stoic` | 49 | checked expectations, and how they meet or-values, target-only drift and the contract |
| `coverage.stoic` | 15 | one definition per name within a lock, and the roots a lock covers |
| `diffcov.stoic` | 14 | `verify --coverage`: LCOV, the lines changed since REF, implementation paths from the project root, UNSPECIFIED |
| `lsp.stoic` | 6 | the language server: range edits, position encodings, coalesced diagnostics, cancellation |
| `gate.stoic` | 25 | `stoic gate`: its rules and base, `--staged`, `--refactor`, `--hook` for each tool, `--install` |
| `codepaths.stoic` | 38 | which files are implementation code: `stoic.code`, the default, the project root |
| `skill.stoic` | 9 | the agent skill: its frontmatter, the commands it names, its word budget, `--install skill` |

One lock, `spec/stoic.lock`, locks all 620 tests (`stoic lock spec --lock
spec/stoic.lock`; counts from `stoic tests spec --format json`), and its roots (`.`) make `--strict` fail on a spec file
left out of it or locked by another lock. Each command is defined once, in
the file of its area: `compile` and `tests` in `syntax.stoic`, `lock` in
`lock.stoic`, `verify` in `verify.stoic`, `brief` in `brief.stoic`, `harness`
in `harness.stoic`, `segments` in `segments.stoic`, `claim` and `release` in `claims.stoic`, `review` in `review.stoic`, `gate` in `gate.stoic`, `guide --skill` and `gate --install skill` in `skill.stoic`, `verify --coverage` (as `diff_coverage`) in `diffcov.stoic`, the rest in `cli.stoic`. Tests in other files bind to them across files
(`<test:or_value_compiles=syntax.compile …>`), so a change to a command
reaches every test of it.

Each locked test is a function named by its ID in `tests/self_spec/<file>.rs`
that drives the real binary in a temporary folder. `tests/self_spec.rs` runs
them all, writes `target/self-spec/results.txt` and gates it with `stoic
verify target/self-spec/results.txt --lock spec/stoic.lock --strict`. It
also fails if a locked test has no function or a function has no locked test.
The tests run on one thread per core (at least 8, at most 24), longest first by the
times the last run saved in `target/self-spec/durations.txt`.
A test with checked values (`=>label="…"`) reports what it saw with
`support::observe(label, value)`, never the expected value: the runner writes
`pass ID label = value` and verify compares it with the lock, so each
expected value is written once, in the spec. Nothing is set aside:
every test checks a value, every field's examples report a verdict, and
every rule has its witness, or `--strict` fails.

```sh
cargo test --test self_spec -- --nocapture   # run them, and print verify's report
stoic tests spec                             # every ID, and what it checks
```

A test of something this reference promises that Stoic doesn't do yet is listed
in `KNOWN_GAPS` in `tests/self_spec.rs`, with why. Verify must fail on exactly
those, so the gaps stay visible while the suite stays green; fix one and its
test passes, and the suite fails until it's taken off the list. CI runs the
same gate, verifying against the base commit's `spec/stoic.lock` on pull
requests (`STOIC_SELF_SPEC_AGAINST=REF` does that locally).

**To change behaviour, edit the spec first.** Add or adjust its tests in
`spec/*.stoic` (a test whose behaviour goes away is deleted, and its
replacement gets a new name), `stoic fmt spec`, check what the edit did with
`stoic check spec --lock spec/stoic.lock` (or every test's state with `stoic
verify /dev/null --lock spec/stoic.lock`), and relock with `stoic lock
spec --lock spec/stoic.lock`. A new spec file goes in `spec/` too, with its
tests in a new `tests/self_spec/<file>.rs` added to `all_tests()`: never a
lock or harness of its own, or behaviour it changes can break another file's
locked tests without the gate noticing (verify fails on either). Its tests
bind to the existing commands (`=lock.lock`), never to a copy of its own:
`stoic lock` refuses a second `compile`. Then implement the new and changed tests in
`tests/self_spec/` and change Stoic until `cargo test --test self_spec`
passes. As in any project, the relock fails `--against` in its own pull
request until it's reviewed (see [Working with several
agents](#working-with-several-agents)).

Running the tests:

```sh
cargo test                     # unit, LSP, stdio and CLI end-to-end (git, when installed), golden fixtures,
                               # examples/results (each whose toolchain is installed), and the self-spec
UPDATE_GOLDEN=1 cargo test     # regenerate tests/fixtures/*.{prose,spec,json} and *.brief.md
cargo test --test integration watch_run::
                               # one file of tests/integration/ (one binary, so its files run side by side)
cargo test --release -- --ignored
                               # the slow tests, the scaling guard among them
```

`.github/workflows/ci.yml` runs on every push and pull request: `cargo fmt
--check`, `cargo clippy --all-targets -- -D warnings` and `cargo test` on
Linux, macOS and Windows (tests that drive `sh` one-liners, and the self-spec,
run on Unix only; on Windows, a clone with `core.autocrlf=true`, every spec
line ending in `\r\n`, must `stoic check` against `spec/stoic.lock` as it
is), the self-spec gate against the pull request's base, [diff
coverage](#ci) of what the pull request changes in `src/` (by the locked
tests only), the tree-sitter corpus (`npm ci && npx tree-sitter test` in
`editors/tree-sitter-stoic`), and the VS Code extension's `npm test` in
`editors/vscode`.
