Metadata-Version: 2.5
Name: alr-emit
Version: 0.1.0
Summary: Reference emitter for OpenALR Agent Labor Records (alr/0.1).
Project-URL: Documentation, https://openalr.org/
Author: Kochab Agentics LLC
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: agent,claude-code,labor-record,openalr,telemetry
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Requires-Python: >=3.10
Provides-Extra: dev
Requires-Dist: cryptography>=3.1; extra == 'dev'
Requires-Dist: hatchling==1.33.0; extra == 'dev'
Requires-Dist: jsonschema; extra == 'dev'
Requires-Dist: pytest; extra == 'dev'
Requires-Dist: pytest-xdist; extra == 'dev'
Description-Content-Type: text/markdown

# alr-emit

Reference emitter for OpenALR Agent Labor Records (`alr/0.1`): one
metadata-only JSON record per executed agent request/task — tokens,
cost, models, turns, outcome. Never prompt or response content. The
record format and its frozen JSON Schemas are defined by the OpenALR 0.1
specification ("SPEC" on this page), at
[https://openalr.org/](https://openalr.org/).

`alr-emit` is developed by Kochab Agentics LLC as a personal,
independent project: written and tested on personal equipment, on
personal time. It has no institutional sponsor and no affiliation with
any employer.

Pure Python, zero runtime dependencies, Python 3.10+. Windows, macOS, and
Linux are all first-class targets.

Supported harness versions (each the earliest version OpenALR was built and
tested against):

- Claude Code 2.1.296 or later (transcripts written by 2.1.251 or later are
  read);
- Grok Build 1.0.53 or later, interactive (the headless `alr-emit-grok` reads
  the results of Grok Build 1.0.41 or later);
- Hermes 0.21 or later.

alr-emit is on PyPI:

```
uv tool install alr-emit
alr --version                    # OpenALR alr-emit 0.1.0
```

Or install a wheel file (`alr_emit-0.1.0-py3-none-any.whl`, from `uv build --wheel`
or one you were given):

```
uv tool install ./alr_emit-0.1.0-py3-none-any.whl
alr --version                    # OpenALR alr-emit 0.1.0
```

The per-OS walkthrough (uv, the hash check, PATH) is on the OpenALR site,
[https://openalr.org/](https://openalr.org/).

## Claude Code hook

Wire the emitter into Claude Code's `settings.json`; `alr install claude-code` writes
exactly this (and the tag hooks below). Turn grain (the default) wants three hooks:
`Stop` (a turn just finished), `SubagentStop` (a subagent just finished), and `SessionEnd`
(the session is over):

```json
{
  "hooks": {
    "Stop": [
      {"hooks": [{"type": "command", "command": "alr hook claude-code --event Stop"}]}
    ],
    "SubagentStop": [
      {"hooks": [{"type": "command", "command": "alr hook claude-code --event SubagentStop"}]}
    ],
    "SessionEnd": [
      {"hooks": [{"type": "command", "command": "alr hook claude-code --event SessionEnd"}]}
    ]
  }
}
```

(`alr hook claude-code` hands the event to `alr-emit-claude`, which can be named
directly with the same arguments. `--event` names which events the command acts on; with
none it acts on `SessionEnd` only. Registering just `SessionEnd` still works: it emits
every turn at the end, and `alr-emit-claude backfill` covers the rest.)

Anyone who shares their output (a report, a dashboard, records) should set the agent id
the records carry: `--agent-id` on the emitters and tag hooks, or `ALR_EMIT_AGENT_ID` (see Sink), else
it is your user name.

For a Claude Code session whose cost you will report:

- **The agent.** A turn record's `agent` is your login name unless `ALR_EMIT_AGENT_ID` or
  `--agent-id` names the agent. `ALR_PRINCIPAL` names who issues or accepts a plan, and
  `ALR_TAGGER` who tags; neither changes the records' `agent`.
- **The cost basis.** The transcript does not say how the session was billed, so the records'
  basis is `unstated` unless `ALR_EMIT_COST_BASIS` or `--cost-basis` states it. A session
  billed to an API key is metered: set `ALR_EMIT_COST_BASIS=metered` before `claude` starts.
- **Planned value.** A task planned for one day counts toward PV only once that UTC day has
  ended; a task over several days accrues from the start of its first UTC day to the end of its
  last (see `alr ev` under Plans and acceptances).

The hook reads the event JSON on stdin, parses the transcript named by
`transcript_path` (never by globbing), and appends records to the sink.
It always exits 0 — a broken emitter must never break your session; a
missed emit is an accounting gap, not an incident.

- `Stop` emits every turn that has no record yet.
- `SubagentStop` emits that subagent's turns. The event names one
  subagent (`agent_id`, `agent_transcript_path`) over the parent's
  `session_id` and `transcript_path`; `agent_id` must match the
  transcript's `agent-<agentId>.jsonl` name, or the event is skipped
  with a note. The event's `agent_type` and `last_assistant_message`
  are never recorded.
- `SessionEnd` does the same as `Stop` and also writes the session's cost
  record (below).

`Stop` and `SessionEnd` also sweep the session's subagent transcripts.
The sink is the idempotency store: a record already there with the same
figures is never written again, so running all three hooks, or
`backfill`, never duplicates a record.

### Turn grain (default) and session grain

`--grain turn` is the default; `--grain session` records a coarser unit,
one record per session plus one per subagent transcript (described at
the end of this section). Do not mix the two grains in one sink.

**Turns.** A turn opens on a user line whose `message.content` is a
string, or a list holding a `text` block or a non-blank bare string. A
list of `tool_result` blocks alone is the harness returning tool output,
not a turn. Custom-title lines never split a turn. Assistant lines
before the first turn belong to no turn; the emitter counts them in its
stderr note and records nothing for them.

A prompt that never reaches the model opens no turn and takes no
`turn_index`. The transcript decides, not a list of command names: the
lines Claude Code writes for a slash command or a background-task notice
(`<command-name>`, `<local-command-caveat>`, `<local-command-stdout>`,
`<task-notification>`, ...) open a turn only when an assistant reply
follows them before the next prompt (a custom command, `/compact`'s
summary call, a notice the model answers). Claude Code writes a prompt it
injects (a message from another session, a background-task notice) as two
user lines with one `promptId`: a harness note (`isMeta`, no `origin`) and
then the message or the notice. The pair is one prompt and opens at most
one turn, so a notice the model does not answer takes no index. The tag
hook skips the built-ins it knows (`/cost`, `/exit`, ...) at once; for
one it does not know, it journals a turn and the next hook corrects the journal from the
transcript, so the next prompt keeps its index and a tag change keeps
its `effective_from_turn`.

One record per turn:

- `request_id` = `<session id>:t<NNNN>`, `turn_index` = that 1-based
  number over the session (turns that end up with no record still count),
  `session_id` set, `turns` = 1. The `alr_id` is deterministic from the
  request and the restatement ordinal.
- `started_at` = the opening user line, `finished_at` = the last
  assistant line of the turn, `wall_ms` from those two.
- Tokens: the LAST occurrence of a `message.id` wins (streamed
  rewrites); a rewrite that lands after the next turn has opened is
  dropped and the earlier turn keeps its message. `cache_write` is
  5m + 1h; the split is in the extension object
  `claude_code_usage: {cache_write_5m, cache_write_1h}`. `reasoning`
  stays absent.
- A `<synthetic>` placeholder message with all-zero usage is dropped; a
  turn left with no message emits no record. A `<synthetic>` message WITH
  usage is an ordinary message.
- `llm_calls` = the deduplicated messages, `tool_call_count` = the
  `tool_use` blocks, `model` = the model with the most output tokens,
  `models` = all of them.
- `cost_usd: null`, `pricing_source: "unknown"`,
  `parent_request_id` = the session id, `parent_inclusion:
  "cost_in_parent"`: the turn's tokens count; its cost is inside the
  session's record. When a figure for the turn is known (see "Per-turn
  cost" below) it is written as `cost_share_usd`, never as `cost_usd`.
- `origin_kind` is `human` for every turn, including a turn the harness
  opened itself: a background subagent's hand-back arrives as a prompt
  and opens a turn (as of Claude Code 2.1.296). Known limitation: such
  a turn is recorded `origin_kind: human`.
  Its tokens are real and its cost is inside the session's record, counted
  once.

**The session cost record.** Claude Code writes its cumulative
`cost-state` line only when a session exits or resumes, never after an
ordinary turn, so the transcript holds no harness cost for a turn when it
ends. (With `alr otel-sink` running, each turn's record carries its own cost
figure at turn end, from the harness's telemetry: see "Per-turn cost" below.) The
session carries the cost: one record with `request_id` = the session id,
no tokens, `turns` = the number of turns recorded, `cost_usd` = the LAST
`cost-state` line's `totalCostUSD` (`pricing_source: "harness_reported"`;
`hasUnknownModelCost` sets `cost_is_partial`) and `cost_basis` from
`--cost-basis` / `$ALR_EMIT_COST_BASIS`. `SessionEnd`, a later hook run
on the same transcript, and `backfill` all write it, whenever a
`cost-state` line exists, whether or not `SessionEnd` fired. The same
figure writes nothing new; a higher one (the session resumed and exited
again) restates the record with `supersedes` and the next `attempt` —
this may happen more than once, and each restatement carries the later
cumulative figure. With no `cost-state` line, or a figure of 0, there is no
session record. Without the sink, a killed process's cost is not in a later
figure: see Known limits.
Totals over the sink then add every turn's and child's tokens, and the
session's cost once.

**Growth.** A turn that grew after it was emitted (more messages or
tokens, for example a late line) is superseded ONCE, with `supersedes`
and `attempt` 2. Growth after that writes a one-line note on stderr and
no record.

**Subagents.** Each `subagents/agent-<agentId>.jsonl` is split into turns
by the same rules: `request_id` = `<session id>:sub:<agentId>:t<NNNN>`,
`session_id` = the parent's, `parent_request_id` = the parent turn whose
window (its opening line up to the next turn's) holds the subagent's
first line — the session id if none does — `parent_inclusion:
"cost_in_parent"`, cost null. A subagent turn carries no `turn_index`
(the index orders a session's own turns). Messages the parent transcript
also carries are left out; a subagent whose `sessionId` is not its
parent's is skipped with a note.

### Session grain (`--grain session`)

One record per session, PLUS one record per subagent transcript.

- A session's record has `request_id` = the session UUID. A session with
  no model call at all (it only ran local commands such as `/cost`) gets
  no record, as at turn grain.
- Claude Code writes each subagent's transcript to its own file,
  `<project>/<session>/subagents/[<subdir>/...]agent-<agentId>.jsonl`
  (an `agent-<agentId>.meta.json` beside it is metadata, not a
  transcript). Its record has `request_id` =
  `<session UUID>:sub:<agentId>`, `session_id` = the parent session's
  UUID, and the same `agent_id` as the session. Tokens, models, turns,
  tool calls, and timing come from the subagent's own transcript.
  The file is recognized by its path; its lines carry the parent's
  `sessionId`, and one whose `sessionId` is not its parent session's
  is skipped with a note on stderr.
- Older Claude Code builds wrote subagent messages inline in the session
  transcript (`isSidechain` lines); those are counted in the session's
  record. A message present in BOTH layouts (the same assistant
  `message.id` in the session transcript and in a subagent's file) is
  counted once, in the session: the subagent's record leaves it out,
  and a note on stderr says how many messages were left out.

**Cost rule.** This package never computes a cost; the only figure is
the total the harness reports in a session transcript: the LAST
`cost-state` line's `totalCostUSD` (a cumulative snapshot, never summed;
`hasUnknownModelCost: true` sets `cost_is_partial`). A `result` line's
`total_cost_usd` is read only when no `cost-state` line carries a figure;
Claude Code 2.1.296 transcripts carry none. That total is the
whole session's cost, its subagents INCLUDED. So a subagent's record
always has `cost_usd: null` and `pricing_source: "unknown"`, even if its
transcript carries a cost line, while its tokens, models, and timing
still count: it carries the token breakdown of the session's cost, and
the session's record carries the figure. No cost is counted twice, on
either layout.

In hook mode the subagent directory is derived from the event's
`transcript_path` (`<transcript dir>/<session>/subagents/`), never
searched for. If the session transcript cannot be parsed, its subagents
are still emitted, found from the event's `session_id`. A subagent whose
transcript is unchanged since its last record in the sink (same token
totals and `finished_at`) is not re-emitted; each subagent is handled
separately, so one bad file never blocks the others or the session's
record.

Backfill has no hook event, so it works out the layout from the files
alone (see Backfill below). Two edge cases follow from that, for a
`subagents/` directory whose session can no longer be identified,
because its `<session>.jsonl` has been deleted or moved and the file's
lines carry no `sessionId`:

- An `agent-<agentId>.jsonl` there is skipped with a note. There is no
  session to attach it to, so it is not booked under a guessed one.
  Hook mode, which knows the session from its event, still emits it.
- Any other `*.jsonl` there is mined as a session of its own, as it
  would be anywhere else. A directory may be named `subagents` without
  being part of this layout (for example a backup folder that holds a
  whole `projects` tree), and the session transcripts inside it must
  still be counted.

### Supersede semantics

A request that continues after an emit re-emits with the same
`request_id`, a fresh `alr_id`, and `supersedes` set to the previous
record's `alr_id` — the new record restates the whole transcript, so it
explicitly replaces the old one. `attempt` numbers a request's records
1, 2, … in emission order. Both are read from the JSONL sink at emit
time, keyed by `request_id`, so a subagent's re-emits chain among
themselves and never into the session's series. Records are
append-only; under the spec, records sharing a `request_id` WITHOUT a
`supersedes` link are distinct work and are summed, so the link is what
keeps a re-emit from being counted twice.

Emits can run at the same time: a `Stop` and a `SessionEnd` hook, a
backfill during a hook, or one session resumed in two terminals. Each
one holds an exclusive advisory lock on a sidecar file, `<sink>.lock`,
from the moment it reads the sink until its last append. The lock is named
from the record file's real path, so a symlink and its target (or any two
configured paths that reach one file through symlinks) share one lock.
So emits that reach the sink by one real path take turns, and each
chains to the records written before it.
Two hard links to one file are not one sink in this sense. They have two
real paths and so get two locks, and emits through different links do
not wait for each other, so a record may not chain to one written through
the other link at the same moment. A purge (`alr uninstall <harness>
--purge`) writes a new file and moves it into place under the name it
was given, so the other link keeps the old file and stops being the
sink. Name a sink by one path, or by symlinks to it, never by a second
hard link.
A backfill holds the lock for its whole run, and waits for it without a
limit (it is an operator command).

Every transcript is read only once the lock is held. Whichever emit
takes the lock last therefore restates the freshest copy of the
transcript, and its record is the current one.

As a further guard, a restatement whose `finished_at` is EARLIER than
the current record for its `request_id` is not written at all; a note on
stderr says so.

- The guard applies in hook mode and in backfill. In a backfill,
  "current" means the sink's record or one this same run has already
  written. So an older copy of a transcript, such as one restored from
  a backup or a duplicate that sorts later, never replaces a fresher
  record. The backfill's summary line counts the refusals.
- Only an end time taken from the transcript can block. A record whose
  transcript had no timestamped line has no `started_at`, and its
  `finished_at` is just the time it was emitted. Such a record never
  blocks a later restatement.
- A transcript that ends at the same time is not blocked: the session
  re-emits, and in hook mode an unchanged subagent is skipped.

A hook never stalls your session on the lock. A hook is `SessionEnd`,
`Stop`, or `SubagentStop`, and it waits at most `ALR_EMIT_LOCK_TIMEOUT_S`
seconds for the lock. The default is 10, and a value that isn't a
number ≥ 0 also means 10. If the lock is still held then, for example by
a long backfill, the hook:

- emits NOTHING (it never writes without the lock);
- prints a one-line note naming the session on stderr;
- exits 0.

That is an accounting gap, never a double count: the next `SessionEnd`
for the session, or a backfill, restates it.

The lock is a `msvcrt.locking` byte-range lock on Windows and `fcntl.flock`
on macOS and Linux; both are released when the holder exits,
even if it crashes. Writers pointed at different sink files share no
lock. Two such concurrent emits for one request can then both read the sink before
either writes, and both write the same `attempt`:

- If a previous record exists, both supersede it. That is a fork;
  consumers resolve it by `emitted_at`, keeping only the later record
  current (SPEC section 4.1), so the work is still counted once.
- On a FIRST emit there is nothing to supersede, so neither record names
  the other. Under the spec they are distinct work, and the request is
  counted twice.

Without the lock, avoid running emitters at the same time against one
sink.

### Backfill

Mine every existing transcript into the sink in one shot. At turn grain
it replays the hook logic over each transcript and is idempotent by
`request_id` — run it twice and the second run adds nothing — so it is
the backstop for turns whose `Stop` never fired and for sessions that
ended without a `SessionEnd`. (The paragraphs below describe session
grain.)

```
alr-emit-claude backfill               # default root: ~/.claude/projects
alr-emit-claude backfill /path/to/projects
```

Each file is routed by its absolute path, so any root works, including
one inside a session's `subagents/` directory. An
`agent-<agentId>.jsonl` file is a subagent transcript when it sits under
a session's `subagents/` directory. A directory counts as a session's
when the directory above it is named by the transcript's `sessionId`,
or sits next to a `<name>.jsonl` session transcript. The subagent is
deduplicated against that session transcript when it exists.

Two kinds of file are skipped with a note: an `agent-<agentId>.jsonl`
that is under a `subagents/` directory but not under any session's, and
any other file in a session's `subagents/` directory. Every other
`*.jsonl` file is a session, even under a directory that just happens to
be named `subagents`. Re-running a backfill appends records
that supersede the earlier ones for each `request_id`; it never edits or
deduplicates the sink.

## Hermes gateway plugin

`alr_emit.adapters.hermes.AlrEmitObserver` emits one record per gateway
turn (usage and tool-call capture, per-turn flush, session-finalize
backstop). Emit failures never propagate — a broken emitter must never
break the gateway's reply; a missed record is an accounting gap, not an
incident. Install it into a Hermes gateway with `alr install hermes`, which
puts the shipped plugin in Hermes's plugins folder.

- **Turn grain.** Every record for a gateway turn carries `turn_index`
  (1, 2, … per agent and session, fixed at emission) and `session_id`.
  A new gateway process continues a session's count: the first time it
  sees a session it reads the default JSONL sink once (the last 8 MiB,
  bad lines skipped) for the highest `turn_index` already there. Known
  limitations: with a custom `record_sink` callable there is nothing to
  read back, and a session whose records all lie before the last 8 MiB
  is not found; either way a resumed session's count starts again at 1,
  and a child turn's request id (which carries its index) repeats. An
  auxiliary call outside a turn is not a turn and has no `turn_index`.
- **Subagents.** A `delegate_task` child is its own Hermes session.
  `subagent_start` links it to its parent, and each turn of the child is
  its own record: `session_id` = the root session (through any nesting),
  `request_id` = `<root session>:sub:<child session>:t<NNNN>`, and
  `turn_index` counted within the child session. `parent_request_id` is
  the request id of the parent turn that spawned the child: the turn
  named by `parent_turn_id` in `subagent_start` when the plugin holds it
  (for a child of a child, the immediate parent's turn), otherwise the
  parent session's most recently active open turn, in which case the
  child's `hermes_subagent` object carries `"parent_turn": "inferred"`.
  `parent_inclusion` is `separate`: the child's API calls are
  its own. That turn's request id is fixed when the child is linked, so
  a different id given later when the turn completes is not used for
  it. If no parent turn was open, the record has neither field and its
  `hermes_subagent` object carries `"parent_turn": "not-open-at-link"`.
  Booking under the root is the Claude Code adapter's convention and
  counts nothing twice. The immediate parent session is also recorded in
  a `hermes_subagent` extension object (SPEC section 5):
  `{"parent_session_id": …, "child_session_id": …}`; for a child of a
  child, `parent_session_id` names the child that spawned it, not the
  root. Hermes reports no cost, so these records carry `cost_usd: null`.
- **xAI models** (a call whose `provider` is xAI or whose model is
  `grok-...` / `x-ai/grok-...`, as through Nous): the call's reasoning
  tokens are added into `output` and kept as `reasoning` (see xAI
  reasoning tokens under Grok Build). A `cost_in_usd_ticks` in a call's
  usage, if Hermes ever passes one, is read as its cost; Hermes 0.21
  passes none.
- **Tool calls** count under their open turn. A `post_tool_call` that
  arrives after its turn's record was emitted is dropped, as late
  auxiliary usage is folded only into open turns: it never opens a
  zero-token record of its own.
- **Auxiliary calls** (titling, compression, vision, approval, MoA)
  fire `post_auxiliary_call`. Inside an open turn their tokens fold into
  that turn (their model is listed in `models`). Outside a turn, or after
  the turn's record was emitted, each call is its own record with
  `request_id` = its `api_request_id` and `task_class` = `aux:<task>`.
  A late call naming an emitted turn the observer still remembers (the
  last 1024) carries that turn's tags, never a tag set after it; with no
  turn named, or one not remembered, it carries the tags in force when
  it is recorded.
- **Orphan turns** (interrupted, or a background fork that never sees
  `post_llm_call`) are flushed by `on_session_finalize`, by
  `subagent_stop` for a child, at process exit, or after
  `ALR_EMIT_HERMES_TURN_TTL_S` idle seconds (default 3600; 0 disables).
- **Plugin-host isolation.** The plugin reads only documented scalar
  hook fields and the `usage` dict, so it runs unchanged under
  `plugins.isolation: host`, where live objects arrive as placeholders.
- **Commands.** The plugin registers `/alr-tag`, `/alr-ctl`, `/alr-turns`,
  `/alr-grade`, `/alr-help`, and `/alr` (see [Commands](#commands)), answered
  inline with no model call. The help screen answers before the session's
  first turn too: `/alr-help`, `/alr`, and `help` after any command
  (`/alr-ctl help`, `/alr-tag help`, ...); every other use needs a turn to
  have started.
  `/alr-grade` never grades an auxiliary (title) record.

## Grok Build

Run the CLI with JSON result output, then feed the result document to
`alr-emit-grok` (a file argument, or the document on stdin):

```
alr-emit-grok result.json --agent-id my-agent
alr-emit-grok --agent-id my-agent < result.json
```

Like the Claude Code hook, it always exits 0 and reports skips on
stderr. The adapter reads `sessionId`, `total_cost_usd_ticks` (the billed
figure, USD x 10^10; `total_cost_usd` when it is absent), `num_turns`,
the `usage` token counters, `modelUsage`, and the two completeness flags;
the answer (`text`), `thought`, and `requestId` are never read or emitted.
A `--resume` run keeps its `sessionId` and
reports per-invocation `usage`, so its records share a `request_id` and
are summed, not superseded.

**xAI reasoning tokens.** xAI reports reasoning tokens BESIDE the output
(completion) tokens, not inside them, and bills them at the output rate
(documented for the current grok-4.x models). Every adapter that reads xAI
usage (`alr-emit-grok`, `alr-emit-grok-tui`, and the Hermes plugin for a
call whose provider is xAI or whose model is an xAI model, `grok-...`, or
`x-ai/grok-...`) therefore writes `output` = output + reasoning and keeps
`reasoning` as the breakdown, so on every record `reasoning` is a breakdown
of `output`, never an addition to it, and an estimate prices reasoning at
the output rate. The rule is keyed on the provider or model field, never
on the counts. A cost Grok Build reports is unchanged by it.

## Grok Build interactive (TUI)

The interactive Grok Build keeps each session under
`$GROK_HOME/sessions/<url-encoded cwd>/<session id>/` (`GROK_HOME`
defaults to `~/.grok`). `alr-emit-grok-tui` reads `usage.json` and emits
**one record per turn**; the session total is the sum of its turns. Install
its hooks with `alr install grok`: it shows what it would write and changes
nothing, and `alr install grok --yes` writes it. It writes one hook file of its
own, `~/.grok/hooks/alr-emit.json` (Grok Build trusts its global hooks
directory), and the `/alr-plan` and `/alr-prices` skills under
`~/.grok/skills/`; it never edits your `config.toml`. The hook file holds five
hooks:

```json
{
  "hooks": {
    "Stop": [
      {"hooks": [{"type": "command", "command": "alr hook grok", "timeout": 30}]}
    ],
    "SessionEnd": [
      {"hooks": [{"type": "command", "command": "alr hook grok", "timeout": 30}]}
    ],
    "UserPromptSubmit": [
      {"hooks": [{"type": "command", "command": "alr hook grok-tag", "timeout": 5}]}
    ],
    "SubagentStart": [
      {"hooks": [{"type": "command", "command": "alr hook grok-tag", "timeout": 5}]}
    ],
    "SubagentStop": [
      {"hooks": [{"type": "command", "command": "alr hook grok", "timeout": 30}]}
    ]
  }
}
```

`alr hook grok` hands the event to `alr-emit-grok-tui`, and `alr hook grok-tag`
to `alr-emit-grok-tag` (the `/alr-*` commands, and each turn's start, so a turn
keeps the tags in force when it started); either can be named directly
with the same arguments. To wire it by hand, write this file yourself; the
emit hooks alone (`Stop`, `SessionEnd`, `SubagentStop`) give records with no
`/alr-*` commands, no session tags, and no turn journal.

The hook payload is read from stdin (`sessionId`, `cwd`; the
`GROK_SESSION_ID` environment variable is the fallback). `Stop` and
`SessionEnd` emit every turn not yet in the sink and the session's
subagents. A subagent is also written as soon as it finishes: at
`SubagentStop`, or at the child's own `SessionEnd`, whichever comes first
(the second finds it already written).

A turn's identity is Grok Build's own. Its `request_id` is `<session id>:t<NNNN>`
with Grok Build's `turnNumber` (each record also carries it as
`x_grok_turn_number`), the same whatever numbering the session's
`turn_index` is in. Whether a turn is already recorded is decided by its
session, its Grok Build turn number, and its end instant against the record
file, and a recorded turn keeps its record's `request_id` and `turn_index` (SPEC section 2.2:
`turn_index` is fixed at emission). Re-running is therefore idempotent: a
turn whose figures changed after emission is restated once (`supersedes`,
next `attempt`), and a further change is left alone with a stderr note. A
restatement always names the same Grok Build turn, with the same end, as the
record it replaces; one that would not is refused. A subagent written as
finished is never restated as partial. Should Grok Build's number come around
again within one session id (see
[Known limitations](#known-limitations)), the later turn's id adds its end
instant: `<session id>:t<NNNN>~<end, UTC>`.

The emitter's numbering decides only `turn_index`, and every turn record
says which numbering that is, in `turn_index_space`. It is `eager`: the
session's real turns (the turns with a model call, tokens, or a cost; a
prompt the tag hook answered is not one) are numbered 1, 2, 3, ... from Grok
Build's own `usage.json` entries in order, and a turn the record file holds
re-anchors the count on the index it was recorded with. The record file the
emitter writes is the authority: a record file a pre-release build wrote can
also hold a session numbered by Grok Build's own `turnNumber`, and that session
keeps those numbers (see
[If you installed a pre-release build](#if-you-installed-a-pre-release-build)).
Neither the
session state (in the state directory) nor the tag hook's journal decides
an id or an index, and the tag hook does not read the record file. So
re-running, with the session state or without it (cleared, or another
state directory), into the same record file never gives recorded work a
second `request_id`, and a re-run with neither the state nor the record
file writes the same ids and indices again. Records the emitter does not
read (another file than the one it now writes to) cannot be taken into
account. To write what a killed Grok Build left unwritten:

```
alr-emit-grok-tui backfill              # default: $GROK_HOME or ~/.grok
alr-emit-grok-tui backfill /path/to/grok-home
alr-emit-grok-tui backfill --session <session id>
alr-emit-grok-tui backfill --since 2026-11-05
alr-emit-grok-tui backfill --all
```

By default `backfill` replays only the sessions whose turn journal holds a
metered turn with no record (the hook journaled it and nothing wrote it:
Grok Build was killed before exit). `--session` replays one session, `--since`
every session with a turn that ended since that date (UTC) or RFC 3339
instant, `--all` every session under the Grok Build home. Each run is idempotent
and ends with one summary line (turns that made no model call are counted
there, not named one by one). A record `alr uninstall grok --purge` deleted
is never written again: the purge keeps its time in the state directory
(`purges.json`), and no backfill or hook writes a record of a turn that
ended at or before it; `--include-purged` writes them again.

Cost is `costUsdTicks` / 10^10 as `harness_reported` (zero is
unreported, as for headless). Tokens follow the headless convention:
`input` excludes cache reads (the TUI files count them inside
`inputTokens`, so the adapter subtracts `cachedReadTokens`);
`cache_read` is carried separately; `output` is `outputTokens` +
`reasoningTokens` (xAI reasoning tokens, above). A subagent is a sibling session; its
turns are emitted as `<session>:sub:<child id>:t<NNNN>` with
`parent_request_id` set to the parent turn that spawned it and
`parent_inclusion: "included_in_parent"`, because the parent's
`usage.json` already counts the child's calls. A fork (`/fork`) records
only its own turns, numbered from 1; the parent's turns Grok Build copies into
it are not recorded again, and before Grok Build writes the fork's link they
are held with a noted problem (see
[Known limitations](#known-limitations)). The adapter never writes
to Grok Build's files and always exits 0.

A turn with no model calls, tokens, or cost (a prompt blocked by a hook,
such as `/alr-tag`) emits no record and takes no turn index: the real
turns are indexed 1, 2, 3, ... with no gaps. (A session a pre-release build
numbered by Grok Build's own `turnNumber` keeps that number, gaps included.)
The tag hook journals each
submit in order (a command it answered as a line with no index). The
emitter joins the journal to Grok Build's turns by identity, never by a number
of another numbering: a journal a pre-release build kept on Grok Build's
`turnNumber` names each turn by it, and a journal of real turns (the one 0.1.0
keeps), which holds every submit in order as
`events.jsonl` holds one span per submit, is lined up with those spans,
anchored on the last turn whose record id the emitter kept on it (with
none yet: from the session's first submit, or, when the record file
already holds turns of the session, from its last: the journal began
later, after a lost session state or a late hook). The journal gives
a turn only its tags, the eager marker, and its cancelled or pairing marks.
A disagreement with
what `usage.json` suggests is noted on stderr and kept where a reader sees
it: on the turn's record as `x_grok_pairing`, or, for a turn with no
record, on its journal line as `pairing`. `/alr-turns` shows either beside
the turn.
`started_at`, `wall_ms`, and `tool_call_count` come from `events.jsonl`,
which has one turn span per submit, blocked and cancelled ones included. A
`usage.json` turn is paired with its span by its end (within a second),
not by `turn_number`, which does not count a blocked attempt. A turn
cancelled before Grok Build wrote any usage has a span and no `usage.json`
entry: it is closed as cancelled and the later turns keep their own
spans. A cancelled turn keeps its journal index (`/alr-turns` shows it
`cancelled`) and never has a record of its own, so the next turn's record
carries the index the journal gave that turn, in `alr turns` as in
`/alr-turns`. Usage Grok Build reported for the cancelled turn (an entry it
closes at the cancel, or when the next prompt arrives) is added to the next
turn's record, so its totals hold every token and cent. That record's
`x_grok_cancelled_turns` lists each cancelled turn it carries with that
turn's own figures: `{"turn_number", "tokens", "cost_usd", "llm_calls"}`
(`turn_number` is Grok Build's; `cost_usd` is null when Grok Build reported none, and
then it was never added: subtract nothing for it). The record's `tokens`,
`cost_usd`, and `llm_calls` less the listed ones are the turn's own. The
figures are decimals, so do the subtraction in decimal arithmetic, or round
to the cent: in binary floating point `0.011 - 0.001 - 0.003` gives
`0.006999999999999998`, not `0.007`. A record whose cost has an unknown part,
the turn's own or a carried turn's (no figure, or 0, which is unreported),
is `cost_is_partial: true` with the known amount as a lower bound, so that
flag may come from a carried turn rather than the turn itself; with every
part unknown its `cost_usd` is null. If the session ends with no later turn, that
usage is booked on its own at `SessionEnd` (or by `backfill`), with
`outcome: "interrupted"` and no `turn_index`. A turn no span's end matches
is left without timing rather than given another turn's.

## Anthropic SDK

`record_from_sdk_usage` accepts a response usage object directly —
attribute-shaped SDK objects and plain dicts both work:

```python
from alr_emit import JsonlSink
from alr_emit.adapters.sdk import record_from_sdk_usage

record_from_sdk_usage(
    response.usage, agent_id="my-agent", model=response.model,
    sink=JsonlSink(),
)
```

Tokens map from `input_tokens`, `output_tokens`,
`cache_read_input_tokens`, and `cache_creation_input_tokens`, plus
`output_tokens_details.thinking_tokens` as `reasoning`. `reasoning` is a
breakdown of `output`, as the API counts it, never an addition to it.
A beta `iterations` entry of type `compaction` is added to the tokens,
because the API documents compaction as excluded from the top-level
counters. Facts with no `alr/0.1` field ride in an `anthropic_usage`
extension object (SPEC section 5): `service_tier`, `speed`, `inference_geo`,
the `cache_write_5m` / `cache_write_1h` split, `server_tool_use`
request counts, and the per-entry `iterations`. Pass `session_id=` to
link the per-call records of your own agent loop.

### Turn grain: `SdkSession`

A caller running its own agent loop (one user turn = several API calls
around tool executions) gets one record per turn:

```python
from alr_emit import JsonlSink
from alr_emit.adapters.sdk import SdkSession

session = SdkSession("my-agent", sink=JsonlSink())
turn = session.turn()              # turn_index 1, request_id <session>:t0001
turn.add(first_response.usage)     # once per API call in the tool loop
turn.add(second_response.usage)
turn.end()                         # ONE record, llm_calls 2
```

Tokens are summed over the calls (the `iterations` rules apply per
call), `model` is the call model with the most output tokens (ties: the
first seen) and `models` lists every model seen. The `anthropic_usage`
extension is `{"calls": [...]}`, one object per call in order, each with
that call's `model` and its own facts. `end(cost_usd=...)` maps a dollar
figure you supply yourself; the adapter never prices, so the default is
null/unknown. A turn with no call of its own (one that only ran a child loop, say) still emits a
record with zero tokens and `llm_calls: 0`, so turn indexes never skip and a child's parent link always
names a record.
A turn's `started_at` is when `turn()` was called (call it before the
first API request) and `wall_ms` runs to `end()`.
`end()` twice, or `add()` after `end()`, raises `ValueError`. Emitted
records are also kept in `session.records`.

`session.child(parent=turn)` returns a session for a sub-loop whose turns
carry `parent_request_id` (the spawning turn) and `parent_inclusion`
(`separate` by default; `cost_in_parent` or `included_in_parent`). Use
`included_in_parent` only if you also added the child's usage to the
parent turn: it tells consumers the parent's figures already hold the
child's calls, so none of the child's tokens are added. `close()` refuses
while a turn is still open.

If you have one cost figure for the whole loop, create
`SdkSession(..., cost_in_session=True)`: every turn then links to the
session id as `cost_in_parent` with null cost (a turn-level cost is
refused), and `session.close(cost_usd=...)` writes the session record
(`request_id` = the session id, zero tokens, that figure). `close()`
without the flag, or twice, raises `ValueError`. Children of such a
session are `cost_in_parent` to the spawning turn. If you never call
`close()`, the turns point at a session record that does not exist and a
consumer reads their cost as unknown.

`record_from_sdk_usage` also takes `turn_index`, `parent_request_id`, and
`parent_inclusion` (an inclusion without a parent is refused).

All adapters emit `outcome: "ok"` — the record meters labor performed,
it does not judge task success; callers building records themselves may
pass any other schema outcome to `build_record`.

## Commands

Six in-session commands are installed on every harness that takes them
(Claude Code, interactive Grok Build, and Hermes). Each one is answered by a hook or
a plugin before any model call, so it costs no model turn and its text
never reaches the model. Two more, [`/alr-plan`](#alr-plan) and
[`/alr-prices`](#alr-prices), are the exceptions: agent interviews, so model
turns.

On Claude Code the hook answers a command with a block decision, so Claude Code
prints its own label, `UserPromptSubmit operation blocked by hook:`, above OpenALR's
reply. That is Claude Code's wording for a command OpenALR answered, not an error. The
first OpenALR reply of each Claude Code session ends with one line saying so; later
replies in that session do not repeat it.

```
/alr-tag                          # the tags in force, then numbered choices
/alr-tag <N>                      # pick choice N of that listing (= add that tag)
/alr-tag list
/alr-tag set <tag> [<tag>...]     # replace the WHOLE session tag set, atomically
/alr-tag add <tag> [<tag>...]     # add; on a single-valued key, replace that key's value
/alr-tag rm <tag|key:> [...]      # remove one tag, or every tag of a key ("team:")
/alr-tag clear                    # empty the session layer (config/env tags still apply)
/alr-tag undo                     # the tags in force before the last change, back
/alr-ctl                          # = status
/alr-ctl status
/alr-ctl start
/alr-ctl stop [<reason>]
/alr-ctl config [<key> [<value>]]
/alr-turns [<n>]                  # last n turns of this session (default 5)
/alr-grade                        # list this session's ungraded finished turns
/alr-grade <1-5> [<comment>]      # grade this session's last finished turn
/alr-grade <1-5> turn <N>         # grade turn N of this session (also: t <N>, -t <N>)
/alr-help                         # the help screen
/alr                              # the same screen (an alias; it runs nothing else)
/alr-plan                         # an agent interview that writes a plan (a model turn)
/alr-prices                       # an agent interview that saves a local rate (a model turn)
```

`help` after any command (`/alr-ctl help`, `/alr-turns help`, `/alr-grade help`,
`/alr-tag help`) prints the help screen too.

**Recognition.** A prompt is a command only when it is a single line that,
after leading spaces and tabs, starts with `/` and a command name
(`/alr-tag`, `/alr-ctl`, `/alr-turns`, `/alr-grade`, `/alr-help`, or `/alr`)
followed by a space or the end of the line. The spellings `alr-tag:`,
`alr-ctl:`, `alr-turns:`, `alr-grade:`, `alr-help:`, and the bare words
(`alr-turns 2`) are accepted too, for a harness that treats `/` specially;
`/alr` has no such spelling, so a prompt that starts with the word `alr` is
an ordinary prompt. `please /alr-tag x`, a second line, and `/alr-tagx` are
ordinary prompts.

### `/alr-help` and `/alr`

The help screen, generated from the installer's command table and each
command's verbs: the version, profile, and metering on its first line
(`alr-emit <version> · profile <p> · metering on|off`), each command with each
verb on a line of its own (`/alr-tag clear` and `/alr-tag undo`, which take no
arguments, are named in the `rm` row's text, so that `/alr-tag move` has a row
of its own), `/alr-plan` in an entry of its own, the main `alr`
shell verbs (as many as fit), and a last line pointing here and to
`alr <verb> --help`. It fits 24 rows of 80 columns. Under the
managed profile, the verbs that profile locks (`/alr-ctl stop`, and setting a
value with `/alr-ctl config`) are marked `locked`, and `/alr-ctl start <reason>`
shows the reason as required.

`/alr-help <anything>` and `/alr <anything>` print `unknown: <anything>` and
then the screen; `/alr help` prints just the screen. `/alr` dispatches
nothing: `/alr tag add x` tags nothing. A bare `/alr-tag help` prints the
screen and adds no tag; `/alr-tag add help` still adds the tag `help`.

### `/alr-grade`

`/alr-grade <1-5> [<comment>]` grades this session's last finished turn:
the latest turn whose record is in the record file, by its turn index as
`/alr-turns` shows it. An auxiliary record (Hermes's title call, `task_class`
`aux:<task>`) and a subagent's turn are never graded this way.
`/alr-grade <1-5> turn <N>` grades turn N; `t` and `-t` are short forms of
`turn` (`/alr-grade 4 t 3`, `/alr-grade 4 -t 3`) when exactly one whole number
follows and nothing else. The grade is an `alr-grade/0.1`
event, written by the same code as `alr grade`, into the record file this
session's records go to (graded by `$ALR_GRADER`, else your user name), and
the reply names the turn and the grade:
`alr grade: turn 3 graded 4/5`. A grade that is not a whole number from 1
to 5 (`bad_grade`), a session with no finished turn yet (`no_finished_turn`),
a turn with no finished record (`unknown_turn`), and a turn number that is not
one whole number of 1 or more (`usage`: `turn` alone, `turn 0`, `t 0`,
`-t 0`) are refused with `nothing changed`. A comment cannot start with the
word `turn`, and a comment of `t` or `-t` and one whole number alone is read
as a turn; any other words
are a comment (`/alr-grade 3 4` grades the last turn 3 with the comment `4`).
A resent `/alr-grade` (an older Grok Build's modal offers resend) writes the grade
again; the latest grade of a request wins, so the result is the same.

`/alr-grade` alone lists this session's finished turns that no grade names
yet, newest first, at most 20 (and how many more), one line each: the turn
number N (the N of `/alr-grade <1-5> turn <N>` and of `/alr-turns`), when it
finished (local time, to the minute), its `task:` tag (or `no task tag`), its
cost share as `/alr-turns` shows it or, when there is no share, the turn's own
cost with `+` for a lower bound and ` alloc.` for an allocated cost (or
`cost unknown`), and the ready command
`/alr-grade <G> turn <N>`; the last line reads `Grade one with /alr-grade 1-5
turn N`. OpenALR keeps no prompt or reply text of a turn, so a turn's first words
are not shown. The listing, like every `/alr-grade` reply, is answered
before any model turn and takes no turn number.

### `/alr-tag`

A tag matches `^[A-Za-z0-9:_.-]{1,128}$`. Its key is the text before the
first `:`. `effort:` (an `<PREFIX>-YY-C-NNNN` / `<PREFIX>-YY-H-NNNN` id or
`overhead:<class>`) holds one value, so `add` replaces it. In an effort id, `<PREFIX>` is a short name you
choose, 2 to 16 characters long: an upper-case letter first, then upper-case
letters or digits only (no lower case, hyphen, or underscore). The grammar checks
that shape and nothing more; it does not look the prefix up. `YY` is a
two-digit year and `NNNN` a four-digit number. The spec's reserved keys
`project:`, `task:`, `client:`, `cost_center:`, and `work_type:` hold one value
each too (a record never carries two tags with one reserved key), so `add`
replaces the value, as an `add` tag event does: `/alr-tag add project:alpha project:beta`
leaves `project:beta`, `/alr-tag add work_type:review` replaces `work_type:build`
(no `rm` first), and `set` with two values of one such key is refused
(`single_valued_conflict`). Every other key and every tag without a `:`
can hold many. `phase:` is one of them: an ordinary tag, with no rule of
its own and no tie to `effort:`.

The tags in force are layered, lowest first: project config `default_tags`
and the repository's `.alr-tags` file < user config `default_tags` <
`ALR_TAGS` < the session layer. `list` shows the session layer, then the
lower layers in brackets; `rm` of a lower-layer tag writes a tombstone for
this session.

`/alr-tag` with no arguments shows the tags in force and then numbered choices:
the projects of the issued plans the record file holds, the current project's
planned tasks (the latest version in each cost basis), and the work types (the
starter list, then the configured `work_types`). `/alr-tag <N>` picks choice N and
applies it exactly as `/alr-tag add <that tag>` would: the same checks, the same
session event. The listing is kept in the session's state directory, so a number
means what this session's last listing showed. A pick with no listing yet
(`no_listing`), a number the listing does not hold or one below 1 (`not_a_choice`),
anything else that starts like a number, such as `3 4`, `1.5`, `0x1`, or `-3`
(`not_a_choice`: it is never added as a tag; use `/alr-tag add <tag>`), and a choice that is no longer offered, such as a task of a project that is no
longer current (`stale_listing`), are refused and change nothing. A listing numbers
at most 40 choices, shows a choice longer than 60 characters cut and marked `...`
(a pick still adds the whole tag), and never offers a configured value that cannot
be a tag. The hook answers it, with no model turn.

`move <old> <new> turn <N>[-<M>] [from-now] <reason>` moves a tag on turns
already done, through the writer `alr tag --move` uses (see "Retagging turns
already done: `alr tag --move`"); without `from-now` the tags in force stay.

`undo` puts back the tags in force before the last change: the whole set that
change's session event recorded as its `from` state, not a difference. There is
no confirm prompt (a hook answers the command before any model turn, so it
cannot ask). The undo is itself a session event, with `x_undoes` naming the
event it reverted, so a second `undo` walks back the change before that; with
nothing left to undo it answers `nothing to undo` and writes nothing: no session
event and no line in the session's reply journal (`replies.jsonl`). Changes
of metering (`/alr-ctl`) are not tag changes and are never undone here. Undo
does not undo a move: when the last change is a `from-now` move, it refuses
(`move_not_undone`); move the tag back instead.

Four reserved keys have their values checked, and by default a check only warns.
The checks find:

- a `task:` that is not a task of its project's issued plan (the latest version
  in each cost basis, as the record file holds it). With no `project:` tag, or no
  issued plan for the project, nothing is judged. A change of `project:` judges the
  `task:` in force against the new project's plan, as a task added then would be;
- a `work_type:` on neither the starter list (`plan`, `build`, `test`, `review`,
  `docs`, `support`, and `research`) nor the configured `work_types` list;
- a `client:` or `cost_center:` on neither its list file's codes nor its config
  list (when it has a list at all, as described with the lists below).

Each prints one
`(warning: ...; accepted)` line and the change is made, on every profile, the
managed one included. A provisioned config that sets `tag_checks = "refuse"`
(the default is `"warn"`) makes any of them a refusal instead (`task_not_in_plan`,
`work_type_unlisted`, `client_unlisted`, `cost_center_unlisted`, and
`client_list_problem` or `cost_center_list_problem` when the key's list file holds a
problem) and nothing changes. A warning or a refusal names the
key, never the value typed. An `undo` is not checked: it
restores tags the session already held. `tag_checks`, `work_types`, `clients`, and `cost_centers` are set
by the provisioned (user) config; an `ALR_*` variable or a flag never sets
any of them (it is ignored and listed by `/alr-ctl config`). On the personal
profile a trusted project `.alr/config.toml` may only tighten `tag_checks`
(`warn` to `refuse`, never back) and only add values to `work_types`, `clients`, and `cost_centers`, never
remove one; a `work_types` list that adds nothing new changes nothing and is not
listed; any other value it sets for them is ignored and listed. On the
managed profile the provisioned config decides all four, and a project file's
value for any of them is ignored and listed.

```
/alr-tag add effort:ACME-26-C-1201 review
  alr tags: (none) → effort:ACME-26-C-1201 review (from turn 1)
/alr-tag add review
  alr tags: unchanged (effort:ACME-26-C-1201 review)
/alr-tag add phase:ACME-26-C-1201:b3
/alr-tag rm phase:
/alr-tag set team:alpha
/alr-tag clear
```

A change answers `tags before → tags after (from turn N)`, each side the whole
set in force, and `unchanged` when the
tags in force would not change. It takes effect from the NEXT turn opened
(`from turn N`): each turn
takes the tags in force when it started, journaled at the harness's
turn-start hook, however late its record is written.

### `/alr-ctl`

- `status`: one line that starts with the installed version, e.g.
  `alr-emit 0.1.0 · emitting · session <id> · harness claude-code · profile personal · last turn 7 emitted, 8 open · sink file <your home>/.alr-emit/records.jsonl`.
- `stop [<reason>]` / `start`: on the personal profile, `stop` stops
  metering as a recorded gap: the stop is a record, and each turn opened
  while stopped is journaled as unmetered with the reason, and no turn
  record is written for it. `start` resumes from the next turn.
- `config`: the help screen's first line
  (`alr-emit <version> · profile <p> · metering on|off`), then every key with
  its value and its source
  (`default|user|project|env|flag|session`), and every refused attempt to
  set `profile` from a lower layer. `config <key>` shows one key.
  `config <key> <value>` sets a session override, on the personal profile
  only, and only for `transmit`, `destination`, and `task_class`;
  `log_dir` and `profile` never change mid-session
  (`not_session_settable`).

### `/alr-turns [n]`

The last `n` turns of this session (default 5), by their 1-based turn
index, oldest first:

```
#  started  model  in/out tok  cost  tags
3  hh:mm:ss  grok-4  1210/233  $0.0131  effort:ACME-26-C-1201
4  hh:mm:ss  grok-4  1302/101  —  effort:ACME-26-C-1201 review
5  hh:mm:ss  (not yet emitted)  effort:ACME-26-C-1201 review
turn 5 not yet emitted
```

`started` is the turn's start time, UTC, as `hh:mm:ss`. The tags are the
ones in force when the turn started. `—` is a turn with
no reported cost of its own (a Claude Code turn's cost is inside its
session's: without `alr otel-sink`, Claude Code reports cost only at session
exit; with the sink running, each turn's record carries its own figure at
turn end in `cost_share_usd`). A turn whose record states its share of the
session's cost shows it as `alr turns` does, `share $0.0300 m` (`alloc.`
after it when the share was allocated, not the turn's own figure). A turn
whose record has not reached the record file is flagged `not yet emitted`
(Grok Build writes a turn's record one `Stop` late); a turn opened while
metering was stopped shows `unmetered: <reason>`. The command reads the
same record file the emitters write (see [Sink](#sink)), and lists only
this session's records of this harness that carry a turn index and its
space (`turn_index_space`). A Grok Build turn's
journal line is joined to its record by identity: once the emitter has
written or found the turn's record it keeps the record's `request_id` on
the journal, and the row shows that record (its `turn_index`, cost, and the
line's tags). A Grok Build record is never paired with a journal line by number,
so after a lost session state each row still shows its own turn's tags;
records written before the journal began are listed first, with their own
tags.

### `/alr-plan`

`/alr-plan` is an agent interview that writes a plan (see
[Plans and acceptances](#plans-and-acceptances)). Unlike the six commands
above, no hook answers it: it reaches the model, so it is a model turn,
metered, and recorded like any other turn. It adds nothing of its own to the
records: it never writes the record file and never tags the turn.

The agent runs `alr plan template --format json` to learn the plan file's
shape, then asks about the project, the cost basis (metered or
api-equivalent), each task with its dates and budget, its client, cost center,
and type of work (each optional, offered as numbered choices from
`alr plan lists`; a blank answer leaves the project's default to apply, and it
never asks for an effort), and the hours, role, and
hourly rate of the people who would otherwise do the work. It shows the
finished `plan.json` and the budget total and asks before it writes the file
in the current directory; it never overwrites a file of that name without an
explicit yes, and offers another name instead. On a yes it issues the plan
with `alr plan new` (or `alr plan revise` with your reason, when
`alr plan show` already shows a plan for the project) and shows OpenALR's own
output. It runs no other `alr` command that writes.

`alr install` adds one file for it on each harness:

| Harness | File |
|---|---|
| Claude Code | `~/.claude/commands/alr-plan.md`, a command file beside the stubs |
| Grok Build | `~/.grok/skills/alr-plan/SKILL.md`, a user-invocable skill |
| Hermes | `~/.hermes/skills/alr-plan/SKILL.md` (on Windows `%LOCALAPPDATA%\hermes\skills\alr-plan\SKILL.md`; with `--hermes-home DIR`, `DIR/skills/alr-plan/SKILL.md`), a skill |

Menus: Claude Code and Hermes can offer the closed questions (the cost basis,
another task, the baseline method, save, issue) as choices, with Claude
Code's `AskUserQuestion` tool and Hermes's `clarify` tool; where that tool is
not available, the questions are numbered. On Grok Build the questions are
numbered.

### `/alr-prices`

`/alr-prices` is an agent interview that saves one local rate (see Local
rates under [Viewing records](#viewing-records-alr)). Like `/alr-plan`, no
hook answers it: it reaches the model, so it is a model turn, metered, and
recorded like any other turn, and it asks its closed questions the same way
on each harness (menus on Claude Code and Hermes, numbered questions on Grok
Build).

It asks, in this order: the model (or a provider, for a discount on every
model of it), a rate or a discount, and whether that is the rate you pay. It
then runs `alr prices local add ... --dry-run` and shows OpenALR's preview of the
entry exactly as OpenALR printed it; only on your yes does it run the same
command without `--dry-run` and with `--confirm` and the preview's entry
digest, so the entry is written by `alr prices local add` itself, and OpenALR
refuses to save any entry but the one you said yes to. A value OpenALR refuses (a control character, a negative, huge, or
non-number rate) is shown with OpenALR's own refusal line and asked again. After
the save it stops: it runs no other `alr` command, and it never writes the
local rates file or the record file itself.

`alr install` adds one file for it on each harness, beside `/alr-plan`'s:

| Harness | File |
|---|---|
| Claude Code | `~/.claude/commands/alr-prices.md`, a command file beside the stubs |
| Grok Build | `~/.grok/skills/alr-prices/SKILL.md`, a user-invocable skill |
| Hermes | `~/.hermes/skills/alr-prices/SKILL.md` (on Windows `%LOCALAPPDATA%\hermes\skills\alr-prices\SKILL.md`; with `--hermes-home DIR`, `DIR/skills/alr-prices/SKILL.md`), a skill |

### What each command emits

A command that changes the tags, `task_class`, or metering writes ONE
`alr-session/0.1` event (`seq`, `prev_seq`, `effective_from_turn`,
`from`, `to`, `cause`, `changed_by`, `changed_at`, `reason`, `x_command`) to the session's
`changes.jsonl` outbox. `list`, `status`, `config` with no value,
`/alr-turns`, the help screen, and every command that changes nothing write
nothing to it; `/alr-grade` writes only its `alr-grade/0.1` event, to the
record file. A
`transmit` or `destination` override changes only the session state. In this release nothing sends the outbox anywhere (see
[Known limitations](#known-limitations)).

**Resend-safe.** A command that changes nothing answers `unchanged` and
writes nothing, so running the same command twice (the blocked-prompt
modal of a Grok Build before 1.0.70 offers "resend") is harmless.

### Personal and managed profiles

The profile comes ONLY from the user config
(`~/.config/openalr/config.toml`, `profile = "personal" | "managed"`;
default `personal`). A `profile` in a project config or in `ALR_PROFILE`
is refused and shown by `/alr-ctl config`; a session saved as personal
before the machine was provisioned as a managed install is managed from
its next command. Any other value (a different case, a space, a look-alike
character) is not a profile and is refused. If a session's saved state names a profile OpenALR
cannot use, every `/alr-*` command in that session refuses with an error
naming its `state.json`; remove that file to recover, and the session's tags
and settings start over from the config.

| | personal | managed |
|---|---|---|
| `/alr-ctl stop` | stops metering, as a recorded gap | refused: `alr: metering cannot be turned off under the managed profile` |
| `/alr-ctl start` | a reason is optional | needs a reason (`reason_required`); only a session stopped before the install became managed is stopped |
| `/alr-ctl config <key> <value>` | `transmit`, `destination`, `task_class` | refused (`config_locked_managed`) |
| `transmit`, `destination` | the user config, `ALR_*`, or the session; a project file only by your `[routing]` table | the user config; a trusted project file only where the user config's `[routing]` table takes `transmit` or `destination` `"from_project_file"` |
| a new `phase:` tag | an ordinary tag, as any other tag | the same: an ordinary tag |
| `who` on the record | the OS user | left empty, for the sink to stamp |

Under the managed profile the environment and the session cannot set
`transmit` or `destination`: `ALR_TRANSMIT`, `ALR_DESTINATION`, and a
session value are ignored, and the user config's value (else the default)
stays in force, except where the user config's `[routing]` table takes
`transmit` or `destination` `"from_project_file"`: there a trusted project file's value applies,
within your limits. The other `ALR_*` variables still apply.

### Configuration

TOML, in `$XDG_CONFIG_HOME/openalr/config.toml` (default
`~/.config/openalr/config.toml`) and a project `.alr/config.toml`. The
project file is the nearest one from the working directory up to the
nearest directory holding `.git`; the walk never enters `$HOME`.
Under Hermes the working directory is the session's (`ctx.session_cwd()`),
else `$ALR_EMIT_PROJECT_DIR`; with neither, the project layer is skipped
(a one-line note says why), never read from the gateway process's own
directory. Precedence: session > flag (a library caller's `flags`) > env (`ALR_TRANSMIT`, `ALR_DESTINATION`,
`ALR_TASK_CLASS`, `ALR_LOG_DIR`, `ALR_PROVIDER`, `ALR_CREDENTIAL_LABEL`,
`ALR_CREDENTIAL_KIND`, `ALR_CREDENTIAL_ID`) > user > project > default,
where the user config is above the project file for every key, and a
project file reaches only the keys a project may set. The one exception
is your own `[routing]` table: where it takes `transmit`, `destination`,
or `log_dir` `"from_project_file"`, a trusted project file's value
applies within your limits (the environment and a flag still win; see
below).

A repository's `.alr/config.toml` can set project facts; it can never set
your billing labels, and it moves your records only where your own
`[routing]` table lets it (below). See
https://openalr.org/concepts/configuration/

```toml
profile      = "personal"        # personal | managed (user config only)
log_dir      = "~/.alr-emit"     # the record file is <log_dir>/records.jsonl
transmit     = false
destination  = ""
default_tags = ["team:alpha"]
required_tags = ["project"]      # keys every record should carry; warn only
work_types   = ["pairing"]       # work_type values beside the starter list (user config; a trusted project file only adds)
tag_checks   = "warn"            # warn | refuse, for the value checks of every form that adds a tag (user config; a trusted project file only tightens)
task_class   = "interactive"
# Who billed the work (SPEC sections 2.2 and 2.4). All four default to "" (unset).
provider         = ""            # overrides the provider the adapter detected
credential_label = "team-a-prod" # your own alias for the key, plan or workspace
credential_kind  = "api_key"     # api_key | subscription | workspace | other
credential_id    = ""            # the provider's NON-secret id; opt-in only
# An organization's price-book key, trusted beside the built-in one (user config only).
price_book_keys = ["acme:<the public key: 44 characters of base64>"]
```

`price_book_keys` is read from your user config only (the provisioned config,
on a managed install): a repository's project file, an `ALR_*` variable or a
flag never adds a price-book key, and each attempt is refused and listed. See
**Organization price books** under `alr prices` below.

`required_tags` lists tag KEYS (`project` and `project:` both name the
key). `alr summary` and `alr check` warn about records that carry none of
a required key, and count them; they never drop or refuse a record. The
viewer finds the policy like any key: the user config, then the project
file nearest the directory `alr` runs in, so run it from the project whose
policy you want. A config that cannot be read is reported on stderr
(`required_tags not checked`) and the rest of the output is unchanged.

#### Routing from a project: `[routing]`

Where your records go (`log_dir`, `transmit`, `destination`) is yours. A
team without central provisioning can let its repository supply it, but
only where your own user (or provisioned) config says so, key by key:

```toml
[routing]
log_dir     = "~/.alr-emit"           # your own value
transmit    = "from_project_file"
destination = "from_project_file"
allow_destinations = ["syslog+tls://*.corp.example:6514"]
allow_log_dirs     = ["/srv/alr/*"]
```

Each key takes one of: `"disable"` (no layer sets it: transmit off,
destination empty, `log_dir` the default); your own value (an ordinary user
setting, over the top-level key); or `"from_project_file"`. With no entry a
key keeps your value or the default, so a fresh install takes nothing about
where records go from a repository. `[routing]` names only those three keys
and the two allow lists; any other name is refused, and a repository's own
`[routing]` table is refused.

A project value is used only when all of these hold; otherwise it is refused
and listed, and your value (or the default) stays:

- the project file is held by your `alr trust` record, by its SHA-256 (a
  blanket `repo_settings = "trusted"` never supplies a route);
- `destination` matches `allow_destinations`: the same scheme, port (no
  port matches only no port), and path, and the host, where `*` stands for one
  or more whole host labels (`*.corp.example` matches `log.corp.example` and
  `a.b.corp.example`, never `corp.example` or `evilcorp.example`). Scheme and
  host compare in ASCII lower case; a `user@` part, a trailing dot, a query, or
  a non-ASCII host is never matched, and an IP literal matches only itself.
  An empty list allows nothing;
- `log_dir` is absolute and, resolved through `..` and links, matches
  `allow_log_dirs` part for part (`*` matches within one part, never across
  `/`), and is not inside any worktree of the repository or its git
  directory;
- `transmit` turns on only with a destination in force (from the same file
  or your own); it can always turn off.

`ALR_*`, a flag, and the session still win over a routed value. `alr check`
and `/alr-ctl config` show a routed value as `from <repo>/.alr/config.toml
(trusted, sha256 <16 hex>); allowed by <your rule>` and list every refused
attempt with its reason, and `alr trust` shows the routes a file would take
before you trust it. The first turn of each session in that repository says
so once, on stderr: `alr: records go to <destination> per
<repo>/.alr/config.toml` (or `alr: records are written to <log_dir> per
...`). Nothing in this release transmits by these keys: `transmit` and
`destination` are recorded and shown only.

#### `provider` and `credential`

`provider` names the service that served and billed the model calls, as
an OpenTelemetry `gen_ai.provider.name` value where one applies. Each
adapter sets it only from what the harness or its process environment
already exposes, and omits it otherwise; it never guesses:

| harness | `provider` | from |
|---|---|---|
| Claude Code (hook) | `anthropic`; `aws.bedrock` with `CLAUDE_CODE_USE_BEDROCK`, `gcp.vertex_ai` with `CLAUDE_CODE_USE_VERTEX` (truthy); omitted for any other or more than one `CLAUDE_CODE_USE_*` switch | the hook's process environment |
| Claude Code (`claude -p` result) | `firstParty` -> `anthropic`, `bedrock` -> `aws.bedrock`, `vertex` -> `gcp.vertex_ai` | `modelUsage[*].provider`, when every row carries it and they agree on a known name; omitted when the rows disagree, name something else, or only some carry it; the environment as above only when no row carries it |
| Claude Code (backfill) | omitted | today's environment says nothing about an old session |
| Grok Build, Grok Build TUI | `x_ai` | the harness (xAI's own client) |
| Hermes | the hook payload's `provider` (`xai` -> `x_ai`, `anthropic`, `openai`, ...; another id verbatim) | `post_api_request` / `post_auxiliary_call`; omitted when a call of the turn names none, `custom`, or `auto`, or two calls differ |
| Anthropic SDK | what the caller passes: `provider=`, or `client=` (`Anthropic` -> `anthropic`, `AnthropicBedrock` -> `aws.bedrock`, `AnthropicVertex` -> `gcp.vertex_ai`) | the caller; otherwise omitted |

The `provider` key overrides every row (an LLM gateway in front of the
harness is the usual reason).

`credential` names the billing credential, never holds it. It is emitted
only when `credential_label` or `credential_id` is set; `credential_kind`
alone emits nothing. `credential_id` is emitted only because you set it:
the emitter never derives or defaults one, since a subscription's or a
workspace's id can identify an account. A label alone is always enough.

Never key material: a configured label or id that looks like a key (a
known key prefix such as `sk-`, `sk-ant-`, `xai-`, `ghp_`, an AWS
`AKIA...` id, a long high-entropy token, a hex digest, a PEM block) is
dropped with one warning on stderr, without echoing it, and never emitted;
the rest of the record is. This is a backstop, not a license: do not put
a key, its hash, or its first or last characters in any of these keys.

The emitter learns all of this passively: it makes no network call and
opens no credential store (`~/.claude/.credentials.json`, Hermes's
`auth.json`, a keychain, a secrets manager) to learn any field. The only
files it reads for them are its own config files.

Session state lives in the state directory (see
[Where OpenALR keeps its files](#where-openalr-keeps-its-files-the-openalr-home-and-the-state-directory)),
under `sessions/<harness>/<session id>/`: `state.json`, the turn journal
`turns.jsonl`, the outbox `changes.jsonl`, and the reply journal `replies.jsonl`. The state
survives resume and compaction; a new session starts with the config layers
only. The journal is internal: a
turn's lines carry its index `n`, but a Grok Build command the hook answered is
journaled as a line with no `n` (`{"blocked": ..., "at": ...}`), and the
Grok Build emitter keeps each turn's record id as a line with no `n`
(`{"bound": n, "request_id": ..., "at": ...}`), so a reader of the file
skips lines without one.

#### `replies.jsonl`: what OpenALR answered

Beside `changes.jsonl`, one line per reply OpenALR itself printed to a
command (`/alr-tag`, `/alr-ctl`, `/alr-turns`, `/alr-grade`, `/alr-help`, `/alr`), so you can read back what it
said and from which turn it applied:

```json
{"schema":"alr-replies/0.1","seq":2,"at":"2026-10-27T10:00:07.123Z","session_id":"...","harness":"claude-code","command":"/alr-tag add","applies_from_turn":3,"reply":"alr tags: (none) → project:x (from turn 3)"}
```

- `command` is the command name plus, when the first word is one of its own
  verbs (`list set add rm clear`, `status start stop config`) or `help`, that word.
  What you typed after it is never kept.
- `reply` is OpenALR's own sentence. A value that came from outside OpenALR (a model
  name or tags in a record, a path or value from a config file, a stop reason)
  appears as one inert token: letters, digits, and `. _ : / @ + = -` only,
  anything else turned into `?`, cut to 128 characters, the longest a tag may be (256 for a path). A
  refusal keeps its code and drops its detail unless the detail is OpenALR's fixed
  wording. A reply that echoes input and has no such form is not kept.
- Nothing a model wrote, no prompt, no transcript line, and no tool result is
  ever written: a prompt that is not one of the commands writes
  nothing, and a model message that merely looks like a command or a reply
  is not a command.
- It is written under the session lock like the other journals (append,
  flush, fsync). The file name is fixed under the session's directory (ids
  holding `/`, `\`, or `..` are refused) and a symlink in its place is not
  followed.
- Size rule: a reply is cut to 4000 characters and 60 lines. The file never
  passes 256 KiB: an append that would pass it first rewrites the file
  (temp file, rename) with only the newest entries that fit in 128 KiB.
  `seq` keeps rising across that trim.

#### Where OpenALR keeps its files: the OpenALR home and the state directory

OpenALR keeps its own files in two directories, and this README calls them by
these two names:

- **The OpenALR home**, `~/.alr-emit` (on Windows `%USERPROFILE%\.alr-emit`): the
  default record file `records.jsonl`, the kit state with its kept Hermes wheels
  (`kit/`), the stored price books (`prices/`), your local rates, the list files
  (`alr-projects.csv`, `alr-clients.csv`, and `alr-cost-centers.csv`), and the
  `alr syslog send` checkpoints (`syslog/`), and the per-session tag files the
  headless adapters read (`sessions/`).
- **The state directory**, `$XDG_STATE_HOME/openalr` (default
  `~/.local/state/openalr`): each session's state (`sessions/`), the
  `alr otel-sink` files (`otel/`), your `alr trust` records, and the purge times
  (`purges.json`).

`ALR_EMIT_HOME` names one directory that takes the place of both, for tests and
isolated installs. One module (`alr_emit.paths`) resolves every such path:

| What | Unset | `ALR_EMIT_HOME=/x` |
|---|---|---|
| the state directory | `$XDG_STATE_HOME/openalr` (default `~/.local/state/openalr`) | `/x/state` |
| default record file | `~/.alr-emit/records.jsonl` | `/x/records.jsonl` |
| kit state, kept Hermes wheels | `<home>/.alr-emit/kit` | `/x/kit/<digest of the resolved --home>` |
| stored price books | `~/.alr-emit/prices` | `/x/prices` |
| per-session tag files | `~/.alr-emit/sessions` | `/x/sessions` |

An explicit setting still wins over the relocated default: `--sink`,
`ALR_EMIT_SINK`, a configured `log_dir`, or `ALR_EMIT_PRICES_DIR`. Config files
(`$XDG_CONFIG_HOME/openalr/config.toml`) are read from where they are; the
variable moves what OpenALR writes, not what you wrote.

**If you set `ALR_EMIT_HOME` after using OpenALR without it.** The variable moves the
default record file, the session state, the kit state with its kept Hermes
wheels, and the stored price books. OpenALR does not read the files already at
the old places (`~/.alr-emit/records.jsonl`, `~/.alr-emit/kit/state.json`,
`~/.alr-emit/prices`, and `$XDG_STATE_HOME/openalr/sessions`): records there stop being summarized by
default, and a kit uninstall no longer finds the state that restores a file
byte for byte. Move those files under `ALR_EMIT_HOME` (same relative names,
session state under `state/`; kit state under `kit/<digest>/`, so one `--home`
never reads another's), or unset the variable. The `<digest>` is the first 16
hex characters of the sha256 of the resolved `--home` path (the home you
installed the kit into, `~` by default). This prints the directory name for
your own home:

```sh
python3 -c 'import hashlib, os, pathlib, sys; print(hashlib.sha256(os.fsencode(pathlib.Path(sys.argv[1]).expanduser().resolve())).hexdigest()[:16])' "$HOME"
```

When OpenALR resolves its
default record file and finds such files outside the variable with nothing of
the kind under it yet, it prints one line to stderr naming them; the line
stops by itself once the files are moved or new ones are written.

### How a command reaches no model, per harness

| Harness | Mechanism | Operator sees |
|---|---|---|
| Hermes 0.21 or later | the plugin registers the six commands (`register_command`) | the answer inline; interactive CLI and gateway only (one-shot `hermes -q` sends commands to the model) |
| Grok Build 1.0.53 or later | ONE `UserPromptSubmit` hook blocks the prompt with the answer as its reason | Grok Build 1.0.70 and later: the answer under the prompt, and the session goes on; before 1.0.70: a modal, so read the answer, then choose **discard** (resend is safe) |
| Claude Code 2.1.296 or later | `UserPromptExpansion` (with the six stub commands) and `UserPromptSubmit`, blocking | the answer as the block reason |
| Anthropic SDK | none (no hooks) | no commands: tags are passed per call |

## Tagging at emit

Records can carry the spec's `tags` field (strings matching
`^[A-Za-z0-9:_.-]{1,128}$`, compared byte-wise and case-sensitively).
A turn of Claude Code, interactive Grok Build, or Hermes takes the
tags in force when the TURN STARTED (see [Commands](#commands)): its
turn-start hook journals them, and the record takes them from that line
however late it is written. A record with no journal line (a turn whose
start hook did not run, a session record) and every record of the other
adapters resolve the tag set **at the moment they build the record**. Both
ways read the same layers in the same order, lowest first (the order in
[Commands](#commands)), so a `project:` or `task:` tag resolves to the same
value either way:

1. **Project config `default_tags` and `.alr-tags`.** A project config file
   applies only once you trust it (see [Configuration](#configuration)).
   `.alr-tags` is a
   per-project file, one tag per line, `#` starts a comment. It is read
   from the session's working directory, else from the nearest ancestor
   that holds a `.git` entry; the walk stops at the filesystem root and
   never climbs into `$HOME`. The file is UTF-8, with or without a byte
   order mark (BOM), with LF or CRLF line ends. A line that is not valid
   UTF-8 (a file saved in a legacy code page) is an invalid tag: that line
   is dropped with a note and the rest of the file still applies. If the
   working directory has been deleted (possible on macOS and Linux;
   Windows does not allow deleting a directory a process is using), this
   layer is skipped and the record is still emitted.
2. **User config `default_tags`.**
3. **`ALR_TAGS`** -- comma or whitespace separated.
4. **The session layer** the [commands](#commands) keep, in
   `sessions/<harness>/<session id>/state.json` in the state directory.
   The headless Grok Build and Anthropic SDK adapters, which keep no
   session state, read a per-session tag file instead:
   `sessions/<harness>/<session id>.tags` in the OpenALR home. Session ids
   containing `/`, `\`, or `..` are refused.

An invalid tag is dropped with one stderr note that gives its line or entry
number, never its text; it never fails emission. A reserved key (`project:`,
`task:`, `client:`, `cost_center:`, `work_type:`) keeps one value: the tag
from the higher layer (within one layer, the later line) replaces the other,
which is named once on stderr. The same rule holds for `build_record`.
A record with no tags has no `tags` field.

If your user config cannot be read when a record's tags are resolved (it is
not valid TOML, or it holds a bad value), the record is left untagged: it has
no `tags` field, not even the `ALR_TAGS` or session tags, and one stderr note
says tagging failed. The record is still written. This holds on both paths:
a record built at emission (the headless Grok Build and Anthropic SDK
adapters) and a turn's record that takes the tags in force now (a turn with no
journal line, a session record).

A project config never leaves a record untagged. One that cannot be read, or
is not valid TOML, contributes nothing; a bad value in one drops that key only.
Either way the other layers still apply, with no note, on both paths.

Because resolution happens at emission, a tag added mid-session lands on
every **later** record. Records already written are never rewritten; to tag
the past, use the separate post-hoc `alr-tag/0.1` event.

### The commands in a session

`/alr-tag`, `/alr-ctl`, `/alr-turns`, `/alr-grade`, `/alr-help`, and `/alr`
are described under [Commands](#commands). They work on Claude Code, the
interactive Grok Build, and Hermes. On headless Grok Build and the Anthropic SDK, tag with
the lower layers (config `default_tags`, `.alr-tags`, `ALR_TAGS`) or the session's tag
file. The Claude Code expansion hook also accepts a
plugin-namespaced command name ending in `:` and one of those names
(`:alr-tag`, say).

### Claude Code

`alr-emit-claude-tag` (installed by `alr install claude-code` as
`alr hook claude-code-tag`) is one hook command for two events. Add both
to `settings.json` (merge with the emit hooks above):

```json
{
  "hooks": {
    "UserPromptExpansion": [
      {"matcher": "alr-tag|alr-ctl|alr-turns|alr-grade|alr-help|alr",
       "hooks": [{"type": "command", "command": "alr hook claude-code-tag"}]}
    ],
    "UserPromptSubmit": [
      {"hooks": [{"type": "command", "command": "alr hook claude-code-tag"}]}
    ]
  }
}
```

In the interactive CLI an unregistered command can be rejected as an
unknown command before any hook runs. Install the six stub commands so
they are registered (`alr install claude-code` does this):

```
mkdir -p ~/.claude/commands            # or <project>/.claude/commands
cp plugins/claude-code/commands/alr*.md ~/.claude/commands/
```

The stub's body is never reached while the hook is installed. The
`alr-tag: add a` spelling needs no stub. An ordinary prompt's
`UserPromptSubmit` journals the turn's start (its index and tags) and
prints nothing. With `claude -p` (print or SDK
runs) an unmatched `/alr-tag` is sent to the model as text unless the
`UserPromptSubmit` hook blocks it, so register that hook there and prefer
`ALR_TAGS` or the project file.

The hook acts only on an exact command form: Claude Code also starts
prompts itself (scheduled tasks, background reports), and those pass
through untouched. On an internal error it writes one stderr line and
exits 0, so a prompt is never blocked by a broken tagger.

### Grok Build

`alr-emit-grok-tag` is the ONE `UserPromptSubmit` dispatcher, and also a
`SubagentStart` hook (a child takes its parent's tags at spawn). It answers
every command, `/alr-help`, `/alr`, and `/alr-grade` included, so Grok Build needs no
file per command; `alr uninstall grok` removes the hook file, and with it
every command.
`alr install grok` writes both into `~/.grok/hooks/alr-emit.json` as
`alr hook grok-tag` (the whole file is shown in
[Grok Build interactive (TUI)](#grok-build-interactive-tui)).

A command takes no turn index: real turns are
numbered consecutively from 1, which is the turn index the journal uses,
whatever Grok Build's own `turnNumber` counts. The journal numbers only
itself: a record's `request_id` is Grok Build's own turn number, and its
`turn_index` is counted by the emitter. Grok Build
hands a typed `/alr-tag` to the hook and honors its block:
the prompt never reaches the model and is not added to the conversation.
Grok Build does record
the blocked prompt as a cancelled turn: a `usage.json` `turns[]` entry
with `modelCalls` 0 and an `events.jsonl` `turn_ended` with
`outcome: cancelled`, `cancellation_category: hook_denied`, and the
hook's reason. `alr-emit-grok-tui` emits no record for it and gives it no
index (see [Grok Build interactive (TUI)](#grok-build-interactive-tui)). A real turn you
cancel is closed in the journal as `cancelled` (`/alr-turns`), with no record
of its own; any usage Grok Build reported for it goes on the next turn's record. A subagent's records are written when it
stops (`SubagentStop`), or at the parent's next `Stop`.

### Other harnesses

Headless Grok Build (`alr-emit-grok`) and the Anthropic SDK adapter have no
prompt hook. They read the same layers as a harness turn: a trusted project
config's `default_tags` and `.alr-tags` (both found from the process working
directory), the user config's `default_tags`, `ALR_TAGS`, and the session's
tag file, which you write by hand. Hermes takes the commands
through its plugin (`register_command`) and journals each turn at
`pre_llm_call`.
`alr-emit-claude backfill` and `alr-emit-grok-tui backfill` replay old
sessions with the user config's `default_tags`, `ALR_TAGS`, and each
session's own tags (its journal and tag changes). They never read a project
config or `.alr-tags`: today's working directory says nothing about an old
session.

### Privacy

Tags are free text and travel with every record they are stamped on. Do not
put anything in a tag you would not publish, and redact before sharing a
sink.

## Sink

Records are appended one JSON document per line. The sink path resolves
in order:

1. `--sink PATH` (CLI) / explicit path argument (library)
2. `ALR_EMIT_SINK` environment variable
3. `<log_dir>/records.jsonl`, when your user `config.toml` or
   `ALR_LOG_DIR` sets `log_dir` (see [Configuration](#configuration))
4. `records.jsonl` in the OpenALR home, `~/.alr-emit` (the default `log_dir`)

The emitters, the `alr` viewer, `/alr-ctl status`, and `/alr-turns`
resolve it the same way, so they read and write one file. A project
file moves it only where your own `[routing]` table takes `log_dir` from a
trusted project file, within your `allow_log_dirs` and never inside the
repository's worktree; any other `log_dir` in a repository's
`.alr/config.toml` is refused, and `alr check` lists it (see the project
config note under [Configuration](#configuration)).

Writes are whole-line appends. The Claude Code adapter's CLI takes an
exclusive advisory lock on `<sink>.lock` (`JsonlSink.locked()`) around
each read-then-append, so its own concurrent emits take turns
(`msvcrt.locking` on Windows, `flock` on macOS and Linux). For heavy
multi-writer setups, point writers at separate files and concatenate
downstream. `alr_emit.sink.Sink` is a one-method protocol (any callable
accepting a dict, a plain function included), so custom transports slot
in without touching the adapters. The Claude Code adapter's CLI also
reads its sink back to chain re-emits, which only `JsonlSink` offers.

The agent id on emitted records resolves as `--agent-id` >
`ALR_EMIT_AGENT_ID` > local username. Session events (`alr-session/0.1`)
resolve it the same way: the tag hooks `alr-emit-claude-tag` and
`alr-emit-grok-tag` take `--agent-id` too, and Hermes uses the observer's,
so give a tag hook the same `--agent-id` as its emitter (or set
`ALR_EMIT_AGENT_ID` for both) and its events join its records.

## How costs are computed

Every cost figure answers two separate questions:

- **How it was obtained.** *Own figure*: the figure belongs to the unit itself (a session's total as the harness reported it, or a task built from its own turns' costs: Claude Code with `alr otel-sink`, Grok Build, Hermes, or one session per task). *Allocated share*: split from a session's own total by its tokens at list price (`cost_allocation: "price-weighted"`: each token type at its rate in the price book in use, for the turn's model on the turn's UTC date), or, when a turn of the session has no price there, by raw token count (`cost_allocation: "token-weighted"`, and the emitter says so on stderr); the shares add up to the total, but a task's share is not its priced cost. *Estimate*: no cost was reported, so OpenALR priced the tokens from the signed price book (the bundled book is `alr-prices/0.3`), shown in its own column and never added to a reported figure.
- **What kind of dollars.** The record's `cost_basis`: `metered` is money charged (an API key), `api-equivalent` is the same work at API list prices (a subscription). The two are never added.

Measured does not mean "your bill": the tokens are measured, the dollars are the harness's own figure (or a share of it) or a list-price estimate, without your discounts, credits, or plan terms. Why these words and the remainder row: https://openalr.org/concepts/costing/

## Cost honesty

A record's emitted `cost_usd` is only ever the harness's own figure or
`null`; the emitter never computes or invents one. OpenALR's allocated shares
and read-time estimates are labeled as such (see "How costs are computed"
above):

| Harness reports                  | Emitted `cost_usd` | `pricing_source`    |
| -------------------------------- | ------------------ | ------------------- |
| `total_cost_usd > 0`             | that figure        | `harness_reported`  |
| `total_cost_usd == 0.0`          | `null` (unmetered) | `unknown`           |
| no cost field at all             | `null`             | `unknown`           |
| partial figure flagged partial   | figure, `cost_is_partial: true` | `harness_reported` |
| Grok Build `usage_is_incomplete: true`, cost omitted | `null`, `cost_is_partial: true` | `unknown` |

A reported `0.0` means the harness did not meter (subscription auth,
no price book) — it is treated as unreported, never emitted as a real
zero cost. Known token counters are always carried even when the cost
is unknown.

`cost_basis` says what a figure is: `metered` (money charged for the
work) or `api-equivalent` (a valuation at API list prices — e.g. a
subscription seat, where no money changed hands per call). A harness's
cost field reads the same either way, so the basis is never guessed:
declare it with `--cost-basis` (CLI), the `cost_basis` argument
(library), or `ALR_EMIT_COST_BASIS`; with none of them the field is
omitted. Consumers summing spend keep the two bases apart.

## Per-turn cost for Claude Code: `alr otel-sink`

Claude Code writes its cost into the transcript only for the whole session, at
exit. With this sink running, each turn's record carries its own cost figure at
turn end instead. Claude Code also
exports one `claude_code.api_request` OpenTelemetry event per model call,
carrying `prompt.id`, `cost_usd`, and `query_source`. The join is ASSUMED:
the telemetry `prompt.id` is taken to equal the hooks' `prompt_id`; the
emitter detects and records a `prompt.id` that matches no prompt of the
session (below).

**One-command setup: `alr otel start`.** On Windows, macOS, and Linux one command
does the setup below:

```
alr otel start         # runs the sink in the background and sets Claude Code's telemetry settings for it
alr otel status        # the sink, each setting and what overrides it; read-only
alr otel stop          # stops that sink and removes the settings OpenALR set
```

`alr otel start` runs `alr otel-sink` in the background (port 4318, or `--port N`)
and writes the four variables below into the `env` object of Claude Code's user
settings file, `~/.claude/settings.json` (`$CLAUDE_CONFIG_DIR/settings.json` when
that is set; `--home DIR` names another home, as for `alr install`), the endpoint
as the sink's full address with the token in it. It touches no other key and never
a project or local settings file (Claude Code does not take these variables from
them), and it writes nothing when the four keys already hold its values.
OpenALR rewrites the file with two-space indentation; your keys and their order are kept.
A file it cannot read as one JSON object is refused and left as it is, and so is a
symbolic link at the settings file itself; a linked settings directory (`~/.claude`,
or the directory `CLAUDE_CONFIG_DIR` names) is followed, as Claude Code follows it.
It records which keys it set, and any value of yours it replaced
(`<state>/otel/settings-owned.json`, where `<state>` is the state directory):
`alr otel stop` stops that sink and removes
only the keys whose values you have not changed since, putting back a value of
yours that `alr otel start` replaced (a key you changed is left and named; a key
you had already set to the same value is yours and stays). A settings file that
`alr otel start` created is removed by `alr otel stop` when nothing else is left in
it; a file that was there before is never removed. `alr otel status` prints one line each and never
the token: the settings file it used, whether the sink is running, each of the four
keys (set by OpenALR, set by OpenALR then changed, set by you, or missing), any managed
settings file or drop-in that sets a telemetry variable (managed settings win over
OpenALR's), a `remote-settings.json` beside your settings as a hint of server-managed
settings, and each telemetry variable of your shell that differs from the settings
file; then the probe lines `alr check` prints. Claude Code reads these settings
when it starts: after `alr otel start` or `alr otel stop`, restart any running
`claude`. The sink writes to `<state>/otel/sink.log` and holds `<state>/otel/sink.pid`
while it runs; it does not start again after a reboot (run `alr otel start` again).
On Windows the sink runs detached with no console window (under `pythonw.exe` when
that is beside your Python), and `alr otel stop` ends it (TerminateProcess, never a
console break) and removes the pid file it leaves behind. A Windows stop leaves a
`.sink.pid.*.tmp` file in `<state>/otel` (the second name the sink gave that pid
file): stop does not sweep it; the next `alr otel start` removes it.

By hand, run the sink and point Claude Code at it:

```
alr otel-sink &        # listens on the loopback interface, port 4318, keeps the events in the state directory
export CLAUDE_CODE_ENABLE_TELEMETRY=1 OTEL_LOGS_EXPORTER=otlp \
  OTEL_EXPORTER_OTLP_LOGS_PROTOCOL=http/json \
  OTEL_EXPORTER_OTLP_LOGS_ENDPOINT=<the address alr otel-sink prints, with the text of its token file in place of <token>>
```

To keep these settings in a file, let OpenALR write it: `alr otel-env` writes the
four variables above, the endpoint with the token in its place, to `otel.env`
beside the token file (`<state>/otel/otel.env`; `--file FILE` names another),
created 0600 so only you can read it. It never prints the token: it prints the
file's path and the line that loads it.

```
alr otel-env           # writes <state>/otel/otel.env and prints: . <its path>
. ~/.local/state/openalr/otel/otel.env   # the line it printed, in the shell you start claude from
```

It writes the file atomically, never through a symbolic link, and refuses to
replace anything at that path that is not a regular file of yours. For the
default file, a link at `<state>` or at `<state>/otel` is refused too, and so is
one at the directory `<state>` is named from (`ALR_EMIT_HOME` or `XDG_STATE_HOME`,
when set), by `alr otel-env` and by the `alr check` probe below. The file
names the sink's default address (the loopback interface, port 4318); with no
token yet it makes one, as `alr otel-sink` does.

Once that file exists, `alr check` tests it against the running sink (the
default `<state>/otel/otel.env` only, and in text output only: see Known
limitations) and prints one line each: the sink is reachable, the token is accepted, and
`/v1/logs` answers. It contacts the address only when its host is `localhost`,
the IPv4 loopback address, or `::1` (any other is refused with a line and never contacted).
It reads the file only in the shape `alr otel-env` writes: comment lines and
`export KEY=VALUE` lines for its four variables, each once, with no space or
shell syntax in a value. A file in any other shape, which a shell could read
differently, is refused with one line and nothing is contacted.
Loopback does not mean your sink: the probe sends the token to whatever listens on that
local port, as Claude Code itself does when it exports. It waits about a second, and never prints the token. Its one request is an OTLP
logs request with no events, which the sink answers and stores nothing for. No
sink running is an informational line, and none of these lines changes the
exit status. Run it in a plain shell, not as `!` inside Claude Code (that costs
a model turn).

On Windows (PowerShell), set the same four variables with `$env:NAME = "value"` in the
window you start `claude` from (or as user variables), then check them with:

```
Get-ChildItem Env:OTEL*
```

The address carries this install's random token as its first path segment
(its path is `/<token>/v1/logs`). The sink makes the token once and
keeps it in `sink.token` under the state directory (`<state>/otel/`, created
0700; the token file and the spool files are created 0600, so only you can read
them on macOS and Linux), so the address stays the same across restarts. The sink's startup
line never prints the token: it prints the address with `<token>` in its
place and names the token file. The first time it stores events of a
session it prints one quiet line, `alr otel-sink: receiving events for session
<the first 8 characters of the session id>`, and nothing more for that
session, so you can see telemetry arriving; it never prints a prompt, an event,
or the token, and a refused request prints nothing. Every request
must carry it, in the path or as `Authorization: Bearer <token>`
(`OTEL_EXPORTER_OTLP_HEADERS`); any other gets 401 and stores nothing, so
another user on the machine cannot post cost rows into your spool.

A turn record then carries `cost_share_usd` = the sum over its `prompt.id`
(`cost_usd` stays null: the turn's cost is inside the session's),
background calls (session title, prompt suggestion) included, with the sum
by `query_source` in `claude_code_cost`. A telemetry event that arrives after the
turn's `Stop` restates the record. The turn record stays `cost_in_parent`: the
session record's total is the authority. Without telemetry, the session record's
cost is shared over the turns when the session ends, weighted by each turn's tokens at
list price (input, output, cache read, and cache write, each at its rate in the price book
in use, for the turn's model on the turn's UTC date: the book and lookup the cost estimate
uses); those turn shares carry `cost_allocation: "price-weighted"`. When a turn's model or
date has no price in that book, the whole session is shared by raw token count instead, its
shares carry `cost_allocation: "token-weighted"`, and the emitter says why on stderr. A turn metered off
(`/alr-ctl stop`) is weighted too but has no record, so its share is withheld:
the session record states it in `claude_code_cost` as `unallocated_usd`, with
`unallocated_reason: "metering_stopped"` and the `unallocated_turns` it
belongs to, so the turn shares plus that amount add up to the session's cost.
A turn's own figure (from the telemetry) carries no
`cost_allocation`. `pricing_source` is `harness_reported` on both: it says where
the session figure the share is a part of, or was allocated from, came from.
A share is a breakdown of the session's cost and is never added to a total;
the session record keeps the total in `cost_usd` and holds no turn tokens. The sink keeps only the
session id, `prompt.id`, `cost_usd`, `query_source`, model, and time of each
event, and the call's identity (`event.sequence`, else the record's time), so
an OTLP retry of a batch counts once; an event with no identity is never
merged with another. `ALR_EMIT_COST_ALLOCATION=off` turns the fallback off.

The join assumes Claude Code's telemetry `prompt.id` is the hooks'
`prompt_id` (the transcript's `promptId`); the emitter checks it on every
emission. A `prompt.id` that matches no prompt of the transcript or the turn
journal is recorded on the session's turn records as
`claude_code_cost.problems: [{"problem": "telemetry_prompt_unmatched",
"unmatched_prompts": N, "unmatched_cost_usd": X}]` and noted on stderr; its
cost stays in the session total, which the allocation shares
at session end, so it is never dropped. When no `prompt.id` matches at all,
every turn takes the allocation.

The sink is bounded: a client has 10 seconds to send its request (each read,
and the whole body, at most 4 MiB), at most 8 connections are served at once
(one past that is closed unanswered), and the spool keeps at most 16 MiB per
session and 256 MiB in all. Events past a cap are dropped; the session's
`<session>.problem.json` in the spool counts them, the sink says so on
stderr, and the session's turn records carry the problem in
`claude_code_cost.problems`.

## Viewing records: `alr`

`alr` reads record files on your machine and prints what they add up to.
It uses the standard library only. Three commands can open a network
connection, and only when you type them: `alr prices update` fetches a price
book, `alr syslog send` sends records to a receiver you name, and
`alr install hermes --yes` runs Hermes's own package manager, which may fetch
packages (see the Hermes plugin's install). `alr otel-sink` only listens on the
loopback interface (below), and `alr check`, `alr otel start`, and
`alr otel status` probe that sink on the loopback interface only, once `alr otel-env` has written its settings file. With no file named, `alr` reads the sink
above. A directory contributes its `*.jsonl` files.

```
alr --version                   # OpenALR alr-emit and its installed version
alr summary                     # by day (local time); --by model|harness|agent|tag
alr summary --by project        # ... or --by task|client|cost_center|work_type: one row per record
alr summary --by tag --json     # machine-readable
alr turns last                  # the records of the latest session, in order
alr turns 0826d7                # ... of a session or request, by a unique prefix
alr tail -f                     # print records as they are appended
alr report --html report.html   # one self-contained page: no script, nothing fetched
alr grade last 4 --comment "solid"     # append an alr-grade/0.1 event
alr tag last project:alpha             # append an alr-tag/0.1 event
alr tag last project:alpha --remove
alr tag last sprint-3 --session        # every request of the session
alr tag last --session --turns 3-7 --move task:a task:b --reason "wrong task"   # retag turns done
alr check                       # lines and documents that could not be used
alr projects check             # project codes in the records against alr-projects.csv
alr plan show --project P       # a project's plan per cost basis (Plans and acceptances)
alr accept --project P --task T # append an alr-acceptance/0.1 document
alr ev [--project P] [--as-of T] # earned value per plan: BAC, EV, AC, PV, CPI, SPI
alr prices show                 # which price book estimates use, its source and signing key
alr prices update               # fetch a newer signed price book over https (uses the network)
alr prices update --dry-run     # ... fetch and check it, and store nothing
alr prices import FILE          # store a signed price book from a local file (FILE.sig beside it)
alr prices reset                # remove the stored books; the bundled one is used again
alr prices local add MODEL --input USD --output USD --paid   # your own rate (local rates, below)
alr prices local list           # your local rates, and the file they are in
alr otel-sink                   # receive Claude Code's own per-turn cost figure (loopback only)
alr otel-env                    # write Claude Code's settings for the sink to a 0600 file to source
alr otel start                  # run the sink in the background and set Claude Code's settings for it
alr otel status                 # the sink, each setting and what overrides it (read-only)
alr otel stop                   # stop that sink and remove the settings OpenALR set
alr syslog send --to tls://logs.example.com:6514 --dry-run   # see the syslog frames first
```

What the numbers mean:

- **Only current records count.** Supersession is resolved as SPEC section 4.1
  says, and cost corrections are applied per SPEC section 3.2.1. The test suite
  checks this against the spec's reference consumer.
- **Reported cost stays per basis.** `metered`, `api-equivalent`, and
  unstated figures sit in separate columns and are never added together.
  A `+` marks a lower bound (a figure in it is unknown or partial), and
  `?` means no figure is known. A basis is shown only when the record
  states one: a cost the harness reported (`harness_reported`) with no
  `cost_basis` shows `?`, because the viewer never infers a basis
  (SPEC section 2.2); an emitter that knows the basis writes it.
- **One zone for turns.** `/alr-turns` (column `started (UTC)`) and `alr turns`
  (column `finished (UTC)`) both print UTC; `alr turns --tz local` prints local
  time, names the zone (`local` plus its IANA name when known) once in its
  header, and gives every cell its own UTC offset, so rows on either side of a
  DST change are each correct.
- **`alr tail` prints local time.** Each line's time ends with its own UTC
  offset (`--tz utc` prints UTC, with none).
- **`alr turns` numbers its rows by turn.** The `#` cell is the record's
  turn index; a session's own record reads `session` and a subagent's
  record `sub`. A bare number is always the record `/alr-turns`,
  `/alr-grade`, and `alr tag --turns` name by it (one numbering: of two
  records with one index, the later finished); the other reads `(3)`, and
  a record with no turn index reads `-` (or `aux` for an auxiliary call).
- **Subagent records follow `parent_inclusion`.** `separate` adds the
  child's tokens and cost, `cost_in_parent` adds its tokens only, and
  `included_in_parent` adds neither.
- **Estimates are separate and labeled.** The `est.` column prices
  records with no reported cost from an `alr-prices/0.3` or
  `alr-prices/0.2` price book (or an older `alr-prices/0.1` one;
  `--price-book FILE`; format in
  `alr_emit/viewer/pricebook.py`). It is a read-time estimate
  at the book's rates, never a bill, and it is never added to reported
  cost. Each price in a 0.2 book has the date it takes effect; a record is
  priced at the rate in force on the UTC date of its `finished_at`, and a
  record that finished before a model's first listed price has no rate. A record whose cost is inside a known figure is never estimated.
  Turn records whose cost is reported once on their session
  (`cost_in_parent`) are estimated only while that session's cost is
  unknown: the `(for parent)` estimate stands in for it, and gives way to
  the reported cost once that arrives. The bundled book holds public API list rates for current
  Claude and Grok models, as of the date it names; run
  `alr summary` to see that date in the `est.` note.
- **Turn shares.** A turn's `cost_share_usd` is its share of its session's
  cost. `alr summary --by tag` reports it on the turn's own tags and takes it
  off the session's tags, which keep the remainder (printed when non-zero,
  and flagged when the shares exceed the session's cost: a negative
  remainder, never clamped); `--by project`, `--by task`, `--by client`,
  `--by cost_center`, `--by work_type`, and `alr ev` split a session the same way (see
  Reserved keys); the `turns` listing shows it as `share`. A share is
  counted only in the basis its session holds. A share whose
  `cost_allocation` is set (`price-weighted`: the session's cost split over
  its turns by their tokens at list price; `token-weighted`: split by raw
  tokens, when a turn had no price) is an allocated part of the session's
  own figure, not the turn's own figure, and a
  reserved-key row or an `alr ev` figure that holds one says
  `includes price-weighted allocation` (or `includes token-weighted allocation`); a turn's own figure (from
  `alr otel-sink`) says nothing. A share is never added to a total. A numeric
  `cost_usd` on a `cost_in_parent` record (this emitter never writes one) is shown
  in the `turns` listing as `in parent` (its figure is not printed), and
  it is never added and never read as a share.
- **Tags** are a record's own `tags`, then any `alr-tag/0.1` events.
  For each tag, the latest event wins. A record with several tags counts
  in each tag's row, so tag rows do not add up to the total.
- **Reserved keys.** `alr summary --by project`, `--by task`, `--by client`,
  `--by cost_center`, and `--by work_type` put each record in exactly one row: its value of
  that key (`project:alpha` is in the row `alpha`, and the tag `project:`
  in the row `""`). A record with two different values of the key is in
  the row `(ambiguous)`, never split or guessed, and a record without the
  key is in `(none)`. A record with two or more `work_type:` values is
  non-conforming (one kind of work per record): the dashboard books it in
  its ambiguous row too, and `alr check` warns with the number of such
  records and the first five ids (`--json`: `nonconforming_work_type`,
  all of them). Turn shares then split a session across the values
  its turns carry, with the arithmetic `--by tag` uses: a turn's share is
  in the row of the turn's own value (`(ambiguous)` or `(none)` as above),
  and the session record keeps its cost minus its turns' shares (the
  remainder) in the row of its own value, or `(none)` when it has none. So
  one Claude Code session that worked on two tasks shows each task's turns'
  shares under that task, not its whole cost under the last one. A
  non-zero remainder is printed; a negative one (shares above the
  session's cost) is flagged, never clamped. A session with no turn records,
  or whose turns carry no share, is booked whole under
  its own value. The rows add up to the total, and the `alpha` row equals
  the `project:alpha` row of `--by tag`. With `--json` a row a share moved
  also holds `share_records` and `remainder`, and `share_allocation`
  (`{"price-weighted": n}`, or `token-weighted`) when it holds allocated shares.
- **Synthetic records** (`synthetic: true`) are left out unless you pass
  `--include-synthetic`.
- **Nothing is dropped silently.** A line that is not JSON, a record
  that is invalid, a repeated `alr_id` (every copy is left out), and a
  tag event that matches no record are all counted in a footer and
  listed by `alr check`.

`alr prices update` fetches from a URL, and only when you run it. (`alr otel-sink` accepts connections from this machine only.) It fetches the gzip book `https://prices.openalr.org/prices/v2/latest.json.gz`
(or `--url` / `ALR_EMIT_PRICES_URL`) and its detached signature, the same URL
with `.sig` added; the book is unzipped before anything else is checked. Only `https` is fetched: a plain `http` or `file:` URL, from
the flag, the variable, or a redirect, is refused. A redirect is followed only to
the same host and port over `https`; a redirect to another host is refused before
it is followed.

Three limits hold, and they are never raised: the book is refused past 8 MiB
downloaded (`PRICE_BOOK_MAX_DOWNLOAD_BYTES`, 8388608 bytes), the unzip is a
stream refused past 32 MiB unzipped (`PRICE_BOOK_MAX_BYTES`, 33554432 bytes,
the same cap as a plain book), and the signature file is refused past 4 KiB
(`PRICE_SIG_MAX_BYTES`, 4096 bytes); each has its own refusal message.

Each fetch (the book and the signature file) also has a wall-clock
deadline of 60 seconds (`FETCH_DEADLINE_S`) over the whole exchange: connecting
(the host name lookup included: the clock starts before it, and the lookup has no
timeout of its own, so a slow one can run past the deadline and the fetch is then
refused), the TLS handshake, sending the request, and every byte of the reply
(the status line, the headers, and the body, chunked or not, with its chunk-size
lines and trailers), redirects included. Each of those
network operations is given its own 20-second timeout (`TIMEOUT_S`) or the time
left before the deadline, whichever is less (when the host has several addresses,
each one tried gets its own timeout, worked out from the time left when that attempt starts), so a server that sends a few bytes
at a time cannot hold the command open; past the deadline the update is refused
and nothing is stored. A gzip file is told from a plain one by its first bytes
(`1f 8b`), never by the URL or the file name; a corrupt or truncated gzip
stream, and any bytes after the first gzip member, are refused. The book must
be signed (Ed25519) by the key built into this release, checked over the
exact bytes of the UNZIPPED book before the book is read; then it must be a valid
book and newer than the one in use (an equal book is already current and is not
stored). A book that fails any check is not
stored. A newer book is stored, unzipped, with its `.sig`, in `prices/` in the
OpenALR home (or in `ALR_EMIT_PRICES_DIR`). It sends nothing about your records.

`alr prices import FILE [--sig SIGFILE]` does the same from a local file, for a
machine without network access or a local mirror: the file is a gzip book or a
plain one (a gzip file is read up to 8 MiB, a plain one up to 32 MiB), the
signature is `FILE.sig` (`latest.json.gz.sig` for `latest.json.gz`)
unless `--sig` names it, and the checks and the store are the same as
`update`'s. An unsigned or wrongly signed file is refused.

**Organization price books.** An organization that publishes its own price
book signs it with its own Ed25519 key. To trust that key, name it in your own
user config (on a managed install, the provisioned config):

```toml
price_book_keys = ["acme:<the public key: 44 characters of standard padded base64>"]
```

Each entry is `NAME:KEY`. NAME (1 to 32 letters, digits, `.`, `_`, or `-`,
starting with a letter or digit) is how OpenALR names the key; KEY is the raw
32-byte public key in standard padded base64, the form of the built-in key. The
key is added beside the key built into this release, never in its place: a book
is checked against the built-in key first, then against the organization key.
`alr prices import` and `alr prices update` store a book that either key signed,
and refuse one signed by any other key. OpenALR trusts at most two
price-book keys, the built-in key included, so one organization key fits. With
two or more configured, OpenALR says so in one line that names each by its name and
key id, and trusts none of them; the built-in key still verifies. A malformed
entry (not `NAME:KEY`, a key that is not 44 characters of base64 for 32 bytes,
a key or a name given twice, the built-in key given again) is refused with its
own line; `alr check`, `/alr-ctl config`, and `alr prices show` list it. Only
your user config is read for this key: a repository's `.alr/config.toml`
(whatever `repo_settings` says, with or without `alr trust`), an `ALR_*`
variable, or a flag never adds a key, and each attempt is refused and listed. A
key is shown by its name and its key id, never in full. A stored book is checked
again whenever it is read, so once you remove the key, the books it signed are
no longer used.

`--price-book FILE` (on `alr summary`, `alr turns`, `alr dashboard`, `alr prices
show`, and the other commands that estimate) uses a book for that run only. It
need not be signed and is never stored: that is how you use your own prices.

Without `--price-book`, the viewer uses the newest valid book (by `as_of`, then
`published_at`) of the bundled one and the stored ones. A stored book is checked
again whenever it is read: one whose `.sig` is missing or no longer verifies
is skipped, and `alr prices show` names it. That holds for every stored book,
an `alr-prices/0.1` one too: to use an unsigned book, name it with
`--price-book`.

`alr prices show` names the book in use, then two lines that say where it came
from and who signed it: `source:` (`bundled`, `stored` by `alr prices update` or
`alr prices import`, or `--price-book`) and `signing key:` (the id of the key its
signature verifies with; `unsigned` for a `--price-book` file). On a fresh
install it prints, among its lines:

```
source: bundled (shipped with this release)
signing key: ef70aea38947ec91 (key id: the first 16 hex digits of the SHA-256 of the built-in public key's 32 raw bytes)
```

A stored book signed by your organization key is named by the key's name in
your config and its key id:

```
source: stored (by alr prices update or alr prices import)
signing key: 21fe31dfa154a261, the organization key acme from your config (key id: the first 16 hex digits of the SHA-256 of its public key's 32 raw bytes)
```

`alr prices update --dry-run` fetches and checks a book exactly as `update` does,
prints the version available beside the one in use, and stores nothing.
`alr prices reset` removes the stored books (each book and its `.sig`, nothing
else), so the bundled book is used again; it uses no network.

**Local rates.** Your own rates (a negotiated rate, a discount, a model the
signed book does not list) go in a local rates file, never signed:
`local-rates.json` in the OpenALR home, or the file the user config's `local_rates` names
(an absolute path, or one that starts with `~/`; a relative path is refused,
because it would be read from the directory OpenALR runs in). `alr prices local add`
writes it (with `--dry-run` it checks the entry, shows it as it would be saved,
and writes nothing), `alr prices local list` shows it, and
`alr prices local rm N` removes entry N:

```
$ alr prices local add acme-large --vendor acme --input 1 --output 4 --paid --dry-run
would add 1. model acme-large (acme): rate input 1, output 4, cache_read none, cache_write none USD per million tokens; paid: you pay this rate
dry run: nothing written; without --dry-run, alr writes ~/.alr-emit/local-rates.json
entry digest: 555dd71827d5dacd868ac985cecb069b24f3c9a5025b36dfbc1c04cc30e48147 (to save exactly this entry, run the same command without --dry-run and with --confirm 555dd71827d5dacd868ac985cecb069b24f3c9a5025b36dfbc1c04cc30e48147)
$ alr prices local add acme-large --vendor acme --input 1 --output 4 --paid --confirm 555dd71827d5dacd868ac985cecb069b24f3c9a5025b36dfbc1c04cc30e48147
added 1. model acme-large (acme): rate input 1, output 4, cache_read none, cache_write none USD per million tokens; paid: you pay this rate
wrote ~/.alr-emit/local-rates.json
$ alr prices local add --provider xai --discount 10 --paid
added 2. provider xai: discount 10% off the signed book; paid: you pay this rate
wrote ~/.alr-emit/local-rates.json
$ alr prices local list
local rates file: ~/.alr-emit/local-rates.json (yours)
  1. model acme-large (acme): rate input 1, output 4, cache_read none, cache_write none USD per million tokens; paid: you pay this rate
  2. provider xai: discount 10% off the signed book; paid: you pay this rate
```

The examples in this README show your home folder as `~`; OpenALR itself prints
the full path.

The preview's entry digest is the SHA-256 of the entry exactly as it would be
saved. Given `--confirm DIGEST`, the save writes only the entry with that
digest; any other entry is refused, and nothing is written. Without
`--confirm` (and without `--interview`), `alr prices local add` saves the entry
it was given.

In a harness, [`/alr-prices`](#alr-prices), beside [`/alr-plan`](#alr-plan),
asks for one entry, shows OpenALR's preview (`alr prices local add ... --dry-run`)
and, on your yes, saves it with `alr prices local add`. It runs both steps
with `--interview`, and saves with `--confirm` and the digest from its own
preview; with `--interview`, OpenALR refuses a save that has no `--confirm`.

A local rate prices only a `metered` figure (money charged), and only from an
entry you declare you pay (`--paid`); without it the entry prices nothing. That
figure is shown beside the list-price estimate, labeled `local rate`, with
`pricing_source` `computed` and a `pricing_version` of
`local-rates:<the file's SHA-256> (<its file name>)`, and it is never added to the
estimate or to reported cost. An `api-equivalent` figure is valued at API list
prices, so a local rate never changes it. `alr prices show` lists your entries
beside the signed book, and `alr check` names the rates file in use and each
entry or setting it refused.

A local rate is a view: it is shown beside the list-price figure in
`alr summary` and `alr turns --json`, it is never written into a record, and
`alr journal` never posts it. On a subscription a local rate changes nothing:
a subscription's figures are valued from the signed book, and a model the
book does not list shows its cost as unknown.

`alr grade` and `alr tag` refuse, and write nothing, when the target
matches no record or matches more than one. `alr tag --remove` also
refuses when the tag is not on the target. A grader or tagger defaults
to `$ALR_GRADER` / `$ALR_TAGGER`, else your user name.

### Retagging turns already done: `alr tag --move`

"I booked turns 3-7 to the wrong task." Move the tag on those turns, in the
shell or in the session:

```
alr tag last --session --turns 3-7 --move task:a task:b --reason "wrong task"
/alr-tag move task:a task:b turn 3-7 wrong task
```

Both write the same lines, through one writer. `--turns N` or `--turns N-M`
(with `--session`; `turn N[-M]` in the session, where `t` and `-t` also mean
`turn`, as in `/alr-grade`) names the turns by the numbers `alr turns` and
`/alr-turns` show. Number N is the session's current record with turn index N
that is a finished turn of the session (never an auxiliary call or a
subagent's record; of two with one number, the later finished), and the lines
name that record's `alr_id`, so they apply to that record and its restatements
(and to the records it started, below). In the session only this harness's
records count toward the turn numbers (the records a turn started move with it
whatever their harness or session). A number the session
does not have is refused with the numbers it has, and so is a session with no
numbered turns, a session whose turns are another harness's, and (in the
shell) a session whose turns come from more than one harness. Without
`--turns`, a move takes the targets `alr tag` takes: a request id, record id,
unique prefix, or `last`, or with `--session` every request of a session.

- **Past turns only, unless `--from-now`.** A move changes the turns already
  done and leaves the session's tags in force alone. `--from-now` (in the
  session, the word `from-now` before the reason) also changes the tags in
  force from the next turn, as `/alr-tag rm <old>` then `/alr-tag add <new>`
  would, with one session event. From the shell `--from-now` needs `--session`
  and the session's state on this machine, and it reads the configuration of
  the directory you run it in.
- **What is written: two linked lines per turn, never a rewrite.** For each
  turn, an `alr-tag/0.1` `remove` of the old tag and an `add` of the new one,
  each with the reason and one shared `x_move` id (an extension field), all
  appended together under one lock in one write. Nothing already in the file
  changes. The tags a reader computes for a moved turn are its old tags with
  the old one replaced by the new one: `alr turns`, `alr summary`, and the
  dashboard show that. Every other tag on the turn stays.
- **The records a turn started move with it.** A move also covers every
  record whose `parent_request_id` chain leads to a moved turn (its
  subagents' records, and theirs), because their cost was spent on that
  turn's work: each gets its own two lines, right after its turn's, so
  `alr summary` books all of the turn's tokens under the new tag. The reply
  says so ("turns 3-5 and the 4 subagent records they started"). A started
  record that does not carry the old tag is skipped, never a refusal, and the
  reply says how many were skipped; one that already carries the new tag is
  left alone. The shell and the session move the same records.
- **One key, any key.** The two tags share a key (`task:`, `project:`,
  `phase:`, or both without a key); a move to another key is refused and names
  `--remove` and then an add. One-value and many-value keys move alike.
- **All or nothing.** When any target does not carry the old tag (as the record
  file stands now, amendments applied), nothing is written, and the refusal
  names those turns, as `--remove` does. A turn that already carries the new
  tag is not an error, and it is left alone: no line is written for it, and
  the reply names it "already on, not changed", so the tags it held stay
  exactly as they were. When every target already carries the new tag, the
  move would change nothing and is refused, unless it is a `from-now` move
  that changes the tags in force: then it writes no tag line, only its
  session event, and says so. A reason is required; an empty
  one is refused.
- **The new tag is checked like an added one.** A move checks the NEW tag exactly as `/alr-tag add` does, past turns and `from-now` alike, in `/alr-tag move` and in `alr tag --move`: a `task:` that is not a task of its project's issued plan, a `client:` or `cost_center:` on neither its list file nor its config list, or a `work_type:` on neither the starter list nor `work_types`. Under `tag_checks = "warn"` (the default) the move is made and each problem is one `(warning: ...; accepted)` line; under `"refuse"` it is refused with the check's code (`task_not_in_plan`, `client_unlisted`, `cost_center_unlisted`, `work_type_unlisted`, `client_list_problem`, `cost_center_list_problem`) and nothing is written (no tag line and no session event). Every form that adds a tag makes these checks: `/alr-tag add`, `/alr-tag move`, a plain `alr tag TARGET TAG` (with or without `--session`), and `alr tag --move`; `alr tag --remove` is never checked, and neither is the old tag of a move. A key with no list is unchecked. A configuration the shell cannot read refuses the add or the move by name (`config_error`) and writes nothing. A `task:` is judged against one project. In `/alr-tag add`, `/alr-tag move`, and `alr tag --move --from-now`, that is the session's project in force. In a plain `alr tag` and in `alr tag --move` without `--from-now`, it is the one `project:` every targeted turn carries; with none, or several, no task is judged.
- **`/alr-tag undo` does not undo a move.** Undo walks the session's own tag
  changes; when the last one is a `from-now` move it refuses
  (`move_not_undone`). A move is undone by moving back:
  `/alr-tag move task:b task:a turn 3-7 <reason>`. Because a turn that
  already carried the new tag was left alone, moving back restores every
  moved turn's tags exactly. (One case is not exact: a subagent record that
  carried the new tag but not the old one was skipped by the move, and the
  move back moves it.)
- **For syslog and SIEM readers.** `alr syslog send` forwards the move's lines
  like any other line, with the same cursor: each turn's two lines arrive
  adjacent, sharing `x_move`. A reader that ignores `x_` fields still applies
  both lines and gets the same totals.

Contrast `/alr-tag add task:b` on a one-value key: it replaces `task:a` in the
tags in force from the next turn only, with one session event, and turns
already done keep `task:a`. A move changes the turns already done, with two
tag lines each, and changes the tags in force only with `--from-now`.

### Machine-readable output: `--json`

`alr summary`, `alr turns`, and `alr check` take `--json`: one JSON document
on stdout (2-space indent, sorted keys) instead of the text. The text output
does not change. Every document has a `schema` string, `alr-<command>/<n>`:
a change that removes or retypes a key raises `<n>`; a new key does not, so a
reader ignores keys it does not know. The figures are the ones the text
prints, from the same code: `tokens` are whole numbers (the text shortens
them to `1.5k`), costs are dollars as numbers (the text rounds them), and
`*.text` fields hold the text cell itself. Exit status is the text command's.
A refusal (no such session, no records file) writes its message to stderr and
nothing to stdout, as without `--json`.

`alr summary --json` (`"schema": "alr-summary/1"`):

| key | value |
|---|---|
| `by`, `tz` | the grouping and the zone (`local` or `utc`) |
| `price_book` | `{schema, as_of, published_at, label, origin, models}` |
| `rows[]`, `total` | `{key, records, requests, tokens{input,output,cache_read,cache_write}, reported{<basis>: {cost_usd, complete, records}}, unknown_cost_records, included_in_parent_records, estimate{cost_usd, records, lower_bound, unpriced_records, inside_reported_session, for_parent_records, for_parent_cost_usd, no_token_records}}`; `<basis>` is `metered`, `api-equivalent`, or `unstated`; with `--by tag` or a reserved key (`--by project`, `task`, `client`, `cost_center`, `work_type`) a row may also hold `share_records` and `remainder`, and with a reserved key `share_allocation` |
| `synthetic_left_out` | records left out as synthetic |
| `problems[]`, `other_schemas{}`, `unmatched_tag_events`, `required_tags[]`, `required_tags_missing{}`, `ambiguous_tag_records{}` | what `alr check` lists, in short |

`alr turns SESSION --json` (`"schema": "alr-turns/1"`):

| key | value |
|---|---|
| `session`, `harnesses[]`, `agent_ids[]`, `record_count` | the heading line |
| `tz`, `tz_label` | the zone and its column label (`UTC`, `local CEST +0200`) |
| `price_book` | as in the summary |
| `turns[]` | one per table row, in order: `label` (`1`, `(1)`, `sub`, `session`, `aux`, `-`), `alr_id`, `request_id`, `turn_index` or null, `finished_at` (as recorded), `finished` (as the table shows it), `model` or null, `tokens{input,output,cache_read,cache_write}`, `cost{text, bookings[{cost_usd, basis, correction_id}], share_usd, inclusion}`, `estimate{kind, text, cost_usd, lower_bound}` (`kind`: `booked`, `own`, `for-parent`, `in-parent`, `included`, `empty`, `in-reported-session`), `outcome`, `grade` or null, `tags[]` |
| `footer[]` | the lines printed under the table about files and records OpenALR could not use |

`alr check --json` (`"schema": "alr-check/1"`):

| key | value |
|---|---|
| `ok` | true when the exit status is 0 |
| `records`, `current`, `grades`, `cost_corrections`, `tag_events` | the counts on the first text line |
| `other_schemas{}` | documents of another schema, by schema, with a count |
| `problems[]` | lines and documents that could not be used, as the text prints after `problem: ` and in its order: an invalid plan or acceptance and a plan or acceptance conflict first, then the records' |
| `ignored_supersedes[]`, `ambiguous_cost_corrections[]`, `ignored_cost_corrections[]` | `{alr_id or correction_id, reason}` |
| `unmatched_tag_events[]` | `{tag_id, reason, action, tag, request_id, alr_id or null}` |
| `notes[]` | `{alr_id, note}` |
| `required_tags_missing[]` | `{key, alr_ids[]}` (all of them; the text shows five) |
| `ambiguous_reserved_tags[]` | `{alr_id, keys[{key, values[]}]}` |
| `nonconforming_work_type[]` | the `alr_id` of every record with two or more `work_type:` values (all of them; the text gives the count and the first five) |
| `list_problems[]` | `{key, file, line, message, level}`: each problem and warning of `alr-clients.csv` and `alr-cost-centers.csv` (`file` and `line` null for a named file that cannot be found); a `problem` makes `ok` false |
| `plan_tag_mismatches[]` | `{project, task, key, planned[], carried{value: records}, records}`: the turns of a planned task whose `client:`, `cost_center:`, or `work_type:` is not the plan's (after the project-list default); a warning, never a problem |
| `hermes` | `{checked, lines[{level, text}]}`; `level` is `problem` or `ok` |
| `config` | `{checked, lines[]}`. Each line is one config value refused where it was set, as the text output prints it: `config: <key> = <value> from <layer> (<file>): refused (<reason>)`. A refusal from the environment has no file: `config: <key> = <value> from env: refused (<reason>)`. `checked` is false for a check of named files with neither `--home` nor `--hermes-home` (it reads no config), and true when either is given. With `--home DIR`, the lines are that home's user config (`DIR/.config/openalr/config.toml`) and the environment's. With `--hermes-home DIR` and no `--home`, they are your own user config's and the environment's. Neither reads the project file of the directory you run `alr` in. A refusal does not change `ok`. |

When there are no records and Hermes was checked, `alr check --json` writes
`{schema, ok, records_unavailable, hermes, config}` instead.

## The dashboard's Data Health screen

The dashboard's Data Health screen lists the gaps in the records, ordered by the spend at
stake. Each item shows its count and its dollars per basis (metered, API-equivalent,
and unstated), and the three are never added together. Untagged spend (a record with no
`project` tag) names the sessions that contribute the most, each linked to that session's
drill-down. A record whose cost is partial, a record whose cost is unknown, a record
booked on no stated basis, an ambiguous reserved key, and a line that could not be
loaded are each their own item. An item that has no dollars, such as a line
that failed to load, shows its count. A figure the engine marks incomplete is shown
with that mark.

The dashboard reads the configured `required_tags` list the way `alr check` does. Each
required key that at least one record lacks is one more item, `Spend missing <key>:`, with
its record count and its dollars per basis. A key no record lacks shows nothing, and with no
`required_tags` configured nothing is added. A record that holds two values for a required
key counts as carrying it. `--redact` keeps the key names, which are configuration.

## Project names

Records keep the project **code** (the `project:` tag's value). To see a readable
name beside a code in `alr summary --by project`, the dashboard, and the `/alr-tag`
picker, list the names in a `[projects]` table of your **user** config
(`~/.config/openalr/config.toml`):

```toml
[projects]
acme-web = "ACME website rebuild"
"acme:mobile" = "ACME mobile app"
```

A code that holds a `.` or a `:` is quoted in double quotes (TOML), and is read the
same on every Python. On Python 3.10, whose built-in reader takes only the subset
OpenALR writes, a dotted code (`acme.web = ...`) or one in single quotes is not read:
that one entry is skipped, `/alr-ctl config` and `alr check` name its line, and the
rest of the config is read as usual. The names are
display only: no record, event, or figure changes, and the rows stay one per code.
Only the user config is read: a `[projects]` table in a repository's
`.alr/config.toml` is never read, so a repository cannot rename a project (`alr check`
and `/alr-ctl config` show one line, `ignored: [projects] is read from user config
only`). An entry
whose code is not a project code, or whose name is not text, is skipped; a name is
shown with every control character as `?`, its runs of spaces as one, and cut to 60
characters. `alr summary --by project` adds a `name` column when a row has a name
(and `--json` a `project_names` object); a redacted dashboard carries no names. An
issued plan carries no project name. This table is where `alr summary`, the
dashboard, and the `/alr-tag` picker take a project's name from; the `name`
column of the project list file (below) is shown only by `alr projects check`.

## Project list

Records carry only the project **code** (the `project:` tag). The project
list, `alr-projects.csv`, is a file you keep by hand, so a controller or a
project manager can maintain it in a spreadsheet: one row per project, with
its default client and cost center, owner, status, and dates. A header row is
required; the column order is free:

| column | meaning |
|---|---|
| `project` | the code, as tagged (required) |
| `name` | readable project name (shown by `alr projects check`) |
| `client` | default client |
| `cost_center` | default cost center |
| `owner` | who owns the project |
| `status` | `open` or `closed`, or empty |
| `opened`, `closed` | dates as `YYYY-MM-DD`, or empty; `closed` is not before `opened` |

The file is UTF-8 (a byte order mark, as Excel writes, is fine) with LF or
CRLF line ends. A column not listed above is ignored, with one warning
naming it. A duplicate `project` code, a missing `project` column, a bad
`status` or date, or a code that cannot be a tag value is a **problem**
named by file and line; nothing is silently fixed or dropped. A duplicated
code is used by none of its rows, and `alr projects check` reports it once,
as the duplicate problem, never also as missing. A quote that is never closed is a problem
at the row where it opens, and no row from there on is read. A cell that
holds a line break is a **warning** naming its lines: a quoted cell may
hold one (a spreadsheet's Alt-Enter), but two stray quotes that pair up
are valid CSV too and join the rows between them into one cell.

`alr` looks for the file in this order: `--projects FILE`, then the
`ALR_PROJECTS` environment variable, then `alr-projects.csv` in the OpenALR
home (`ALR_EMIT_HOME`, else `~/.alr-emit`). A missing default file
means there is no list; a missing file you named with the option or the
variable is an error, and so is an empty `--projects` (an empty
`ALR_PROJECTS` reads as unset). A default path that is a symbolic link out of the
OpenALR home is followed, and `alr projects check` lists that as a
problem.

Two rules keep the file harmless:

- **Names never come from records.** A record's tags hold the code and
  nothing else about the project; a code with no name is shown as the bare
  code.
- **File defaults never override a record.** `client` and `cost_center`
  are defaults for display and journal mapping only. A record's own
  `client:` or `cost_center:` tag always wins, and the file never rewrites
  a record. Nothing here writes the CSV.

```
alr projects check                       # the file found as above, the emitters' records
alr projects check --projects P.csv f.jsonl
alr projects check --json                # the same, as data (projects_check_version 1)
```

**Client and cost-center lists.** Beside the project list, two more files
you keep by hand give the clients and cost centers their codes and names, with
the same reader rules (header required, column order free, UTF-8 with or
without a byte order mark, LF or CRLF line ends, every problem and warning named
by file and line, and a duplicate code used by none of its rows):

| file | columns |
|---|---|
| `alr-clients.csv` | `client` (the code, required), `name` |
| `alr-cost-centers.csv` | `cost_center` (the code, required), `name` |

They are found as the project list is: `--clients FILE`, then
`ALR_CLIENTS`, then `alr-clients.csv` in the OpenALR home (and
`--cost-centers FILE`, `ALR_COST_CENTERS`, then `alr-cost-centers.csv`), with the
same rules for an empty option, a missing named file, and a symbolic link.
`alr summary --by client` and `--by cost_center` add a `name` column from them
when a row has a name (`--json`: `client_names`, `cost_center_names`). There are
two name sources, each for its own key: project names come from the
`[projects]` table of your user config (Project names, above), client and
cost-center names from these files; there is no TOML table of client or
cost-center names, and names never come from records or repositories.

The valid values of `client:` are the codes of `alr-clients.csv` plus the
config list `clients = [...]`; of `cost_center:`, the codes of
`alr-cost-centers.csv` plus `cost_centers = [...]`; of `work_type:`, the
spec's starter list plus `work_types`. The config keys `clients` and `cost_centers` follow the
`work_types` rule exactly: your (provisioned) config sets them, a trusted
repository's `.alr/config.toml` may only add to them on the personal profile,
the managed profile's provisioned config decides alone, and `ALR_*` and
flags never set them (`ALR_CLIENTS` and `ALR_COST_CENTERS` name the files).
`tag_checks` (`warn` or `refuse`) decides what happens to a value that is none of
its key's valid values, in every form that adds a tag (`/alr-tag add`, `/alr-tag move`, a plain `alr tag`,
and `alr tag --move`; never `--remove`) and when a plan is issued (`alr plan new|revise`, for
the `client`, `cost_center`, and `work_type` the plan file gives); the warning
or refusal names the key, never the value, and the list file it was checked
against by its path (the `--clients` / `ALR_CLIENTS` file, or the one in the
OpenALR home; likewise for cost centers).

**When the lists are empty.** No list kept means no check: while
`alr-clients.csv` holds no client code and `clients` lists none, any `client:`
value is accepted with no word (the same for
cost centers). The first code you add, in the file or in the config list (a
trusted repository's `clients = [...]` addition counts), turns the check on, and
from then on every client on neither list is warned of or refused. A list file
that holds its header row and no code is a list kept empty: no check. A list file
of zero bytes (not even a header) is a problem, below: it fails closed. `work_type`
always has the starter list, so it is always checked.

**When a list file is broken.** A broken file never turns a check off unseen.
`alr check` lists each problem and warning of `alr-clients.csv` and
`alr-cost-centers.csv` by file and line (a problem fails it), and so does `alr
plan lists` (exit 1 on a problem). While a list file that exists holds a
problem (an empty file with no header row, a header without its code column, a
duplicate code, a code that cannot be a tag value), or `ALR_CLIENTS` / `ALR_COST_CENTERS` names a file that cannot
be found, a `client:` or `cost_center:` value cannot be checked: under
`tag_checks = "refuse"` it is refused, and under `"warn"` warned of, naming the
file, never the value (every form that adds a tag, and `alr plan new|revise` for
a plan that gives the key).

`alr projects check` lists (a) the project codes the records carry that the
file lacks, with their record counts and spend per cost basis (the bases
are never added; biggest first), (b) the file's rows that no record
carries, and (c) the file's problems. A record that carries two or more
`project:` values is allocated to neither (SPEC section 2.3): it has its own line and is
never counted under either code. A code the file lacks is still listed in
(a) when only such records carry it, marked "ambiguous only", with no spend
of its own (its spend stays unallocated), and its line names the other
`project:` values those records carry; it fails the gate, and the header's
count of project codes in records includes it. Codes are
read from each record's effective tags, after the tag amendments.

The exit status is for gating: **0** when no code is missing and the file
has no problem (warnings and unused rows do not fail it), **1** when a code
is missing or the file has a problem (with no list at all, every code is
missing), **2** on a usage error or when a list you named does not exist.
In the human output, control, bidirectional, and other invisible characters
(Hangul fillers and variation selectors among them) from the file or a
record are shown as `\uXXXX`, and a cell that starts with
`=`, `+`, `-`, or `@` is shown as plain text; `--json` carries every
string as it is.

## Plans and acceptances

A **plan** is a project's budget in one cost basis, and an **acceptance** says
that a task of it is done (SPEC section 9, `alr-plan/0.1` and
`alr-acceptance/0.1`). A plan names its project and tasks by the values of
their `project:` and `task:` tags. This release writes, shows, and checks the
documents, and computes earned value from them (`alr ev`, below).

```
alr plan                                      # on a terminal: asks for the plan, question by question
alr plan template --format json > plan.json   # an example plan file to start from
alr plan template --format csv > plan.csv     # the same plan as CSV, for a spreadsheet
alr plan lists --project ACME-2026-14         # the clients, cost centers, and work types a task may name
alr plan workbook                             # plan.xlsx: a Plan tab with drop-downs, and its Lists
alr plan new    --project ACME-2026-14 --basis api-equivalent --from plan.json --by owner-1
alr plan new    --project ACME-2026-14 --basis api-equivalent --from plan.csv --by owner-1
alr plan revise --project ACME-2026-14 --basis api-equivalent --from plan.json \
                --reason "build starts a day late" --by owner-1
alr plan show   --project ACME-2026-14 [--basis metered|api-equivalent] [--json] [FILES...]
alr accept --project ACME-2026-14 --task ACME-2026-14:design --grade 4 \
           --evidence https://git.example.com/acme/design/commit/5f2c9a1 --by reviewer-1
alr accept --withdraw --project ACME-2026-14 --task ACME-2026-14:design \
           --reason "review found gaps" --by reviewer-1
```

`plan new` issues version 1 and refuses when the project already has a plan
in that basis (run again with the same content while version 1 is the only
version, it writes nothing and says so). `plan revise` issues the next version: every task that differs
from the previous version (new, or a changed budget, dates, baseline, or
baseline method) carries a `change` (`scope`, `re_estimate`, `basis`, or
`schedule`; `schedule` only when no money moved), a task that does not differ
carries none, and the tasks the file no longer holds are dropped, each listed
in `dropped_tasks` with its `change` (never `schedule`). A revision
that changes nothing is refused. `plan show` prints the latest version in each
basis; the two bases are separate plans and their budgets are never added.
Beside the version it says which versions of that plan the files it read hold
(`version 2 (the files hold versions 1, 2)`); a version missing below the latest
is listed on its own line.
`alr accept` takes the next `seq` of the task; a withdrawal needs `--reason`
and carries no grade, and a task no plan of the project holds is accepted
with a warning.

**`alr plan` on its own** asks for a plan, one question at a time, when
standard input and output are a terminal: the project (default
`$ALR_PROJECT`), the cost basis (default `$ALR_EMIT_COST_BASIS`), then each
task: its name (a bare name becomes `PROJECT:NAME`), its budget in US
dollars, its planned start and finish (UTC days, optional), its client, cost
center, and type of work (each optional: the configured values are listed as
numbered choices, the client and cost-center codes with their names, the
config lists, and the starter work types; a number picks one, a value of your
own is checked as a plan file's is, and a blank answer leaves it unset; the
question says when the project list gives the project a default client or cost
center, which then applies), the hours, role,
and hourly rate of the people who would otherwise do it (none is a fine
answer), the baseline method (default `estimate`), and a note. Each answer is
checked as you give it, by the same rules as a plan file, and asked again
with the reason. It then prints the plan file and the budget total, asks
where to save it (default `./plan.json`; an existing file is overwritten
only on an explicit yes) and whether to issue it now: version 1 as
`plan new --from` issues it, or, when the project already has a plan in that
basis, the next version as `plan revise` does, with your reason (a task that
is new or differs, and a task left out, each asks its `change`). Who issues
it is `--by`, else `$ALR_PRINCIPAL`, else it asks. Nothing is written until
the last question is answered: Ctrl-C writes nothing (exit 130), and so does
the end of input (exit 1). Without a terminal `alr plan` alone exits 2 and
names `alr plan new --from FILE` and `alr plan template`, so a script never
waits on it.

`alr ev [--project P] [--as-of TIMESTAMP] [--json] [FILES...]` reports earned
value per plan (SPEC section 9.3), as of now or the instant given (shown in
UTC to the second, as `YYYY-MM-DD HH:MM:SS UTC`):

- BAC, and EV by the 0/100 rule;
- AC in the plan's basis, marked a lower bound when a cost is null or partial,
  or when a correction issued after that instant covers records on both sides
  of it;
- PV, CPI, and SPI. A zero divisor is `undefined` in `--json` and the
  dashboard data, and is shown as `n/a` with the reason beside it: CPI
  `n/a (no spend yet)` while AC is 0, or `n/a (spend not known)` while AC is 0
  only as a lower bound, and SPI `n/a (nothing planned yet)` while PV is 0. PV
  and SPI are `unavailable` when a task has no dates. A task planned for one
  day adds its whole budget to PV only once that UTC day has ended, and a task
  over several days accrues from the start of its first UTC day to the end of
  its last;
- EV and CPI against version 1;
- each accepted task's human baseline beside its AC.

A task's AC is split by
turn shares, as `alr summary --by task` splits it: a turn's share of its
session's cost is AC of the turn's own task (and project), and the session's
own task keeps the remainder (unassigned when the session has no task), so
a session that worked on two tasks charges each its own turns. A turn's
share counts once its session record is held as of that instant, and only
in the basis its session holds; a session with no turn records, or whose
turns carry no share, is booked whole. An AC that holds
allocated shares says so by method, `includes price-weighted allocation`, or
`includes token-weighted allocation` (`share_allocation` in `--json`); one that holds a session whose turns'
shares exceed its cost says `turn shares exceed a session's cost`
(`over_share_sessions`), and its negative remainder is never clamped. A
partial turn's share makes its AC a lower bound. It writes nothing. Its text
shows every money figure and every ratio to two decimal places (rounded
half to even, the same on every row); `--json` keeps every digit. The
dashboard data carries the same report under `ev`, and the dashboard's Earned
Value screen shows it as of the build: one block per plan (each basis
its own), every figure the report's own, to two decimal places, with its bounds said beside it,
each task's status (planned, in progress, accepted, or withdrawn), the AC in no
planned task, the first-plan comparison, and the Worth It figures. A project
with spend and no plan shows "no plan on record" and the `alr plan new` commands
that would create its plans, one per basis its spend holds (both when it holds
neither or both). A redacted build (`--redact`) names such a project by its
token, which no plan can be issued for, so it prints no command and no hint
there. One build is one as-of point: a series over time needs
one build per date.

The plan file is JSON (`plan.json`), on every Python. The project, the basis,
the version, who issues it, and when come from the command line, never from
the file. A member given as `null` is the member left out:

```json
{"tasks": [
  {"task": "ACME-2026-14:design", "budget_usd": "6.00",
   "planned_start": "2026-10-23", "planned_finish": "2026-10-24",
   "human_baseline": [{"role": "senior engineer", "hours": 8, "rate_usd": "150"}],
   "baseline_method": "estimate", "baseline_note": "contractor rate"},
  {"task": "ACME-2026-14:orchestration", "budget_usd": "2",
   "human_baseline": [], "baseline_method": "estimate",
   "baseline_note": "counted in the design task"}
]}
```

`planned_start` and `planned_finish` are a date or a date-time with an
offset, both or neither. A planned date is a UTC day: it starts at 00:00 UTC and
ends at the next midnight UTC, so "today" for a plan is the UTC day, which can
differ from your local day; `baseline_method` is `estimate`, `historical`,
`quote`, or `measured`; `human_baseline: []` states that the task has no
human effort of its own and needs a `baseline_note`. On a re-plan a task
carries `"change"`, and `"dropped_tasks": [{"task": ..., "change": ...}]`
lists what the file drops.

A plan's free text (a task's `baseline_note`, a baseline role's `role`, the
plan's `--reason` and its `issued_by`) is at most 1000 characters
in every form: JSON, TOML, CSV, a workbook, and the
interview's answers. Longer is refused, naming the field and the task, never
quoting the text, and nothing is written. An acceptance's free text (`alr
accept`'s `--evidence` and `--reason`, and its `accepted_by`) has the same cap.
A `task`, `client`, `cost_center`, or
`work_type` value is a tag value, so the tag grammar bounds it: at most 128
characters with its key.

On Python 3.11 or later (the standard library's `tomllib`), the same plan can
be a TOML file (`plan.toml`; `alr plan template --format toml`). On Python
3.10 a `.toml` file is refused (exit 2) and the message names the JSON form:
OpenALR takes no dependency and carries no TOML reader of its own.

```toml
[[tasks]]
task = "ACME-2026-14:design"
budget_usd = "6.00"
planned_start = "2026-10-23"
planned_finish = "2026-10-24"
baseline_method = "estimate"
baseline_note = "contractor rate"

[[tasks.human_baseline]]
role = "senior engineer"
hours = 8
rate_usd = "150"

[[tasks]]
task = "ACME-2026-14:orchestration"
budget_usd = "2"
human_baseline = []
baseline_method = "estimate"
baseline_note = "counted in the design task"
```

On every Python the same plan can also be a CSV file (`plan.csv`; `alr plan
template --format csv`, and `kit/plan-template.csv` in the source), for
people who start from a spreadsheet: save the sheet as CSV (UTF-8; the
byte order mark a spreadsheet writes first is dropped). CSV is an input form
of the command line only: the plan written is the same document as from
JSON.

```csv
task,budget_usd,planned_start,planned_finish,baseline_method,baseline_note,change,role,hours,rate_usd,dropped
ACME-2026-14:design,6.00,2026-10-23,2026-10-24,estimate,contractor rate,,senior engineer,8,150,
ACME-2026-14:orchestration,2,,,estimate,counted in the design task,,,,,
```

The first row names the columns, in any order, from `project`, `task`, `budget_usd`,
`planned_start`, `planned_finish`, `baseline_method`, `baseline_note`, `change`,
`client`, `cost_center`, `work_type`,
`role`, `hours`, `rate_usd`, and `dropped` (`task` and `budget_usd` are required;
`role`, `hours`, and `rate_usd` come together, and `dropped` needs `change`); an
unknown or repeated name is refused. Then
one row per task and baseline role: rows with the same `task`, next to each
other or not, are one task, whose other cells are given on its first row and
are blank or the same on its later rows. A row whose `role`, `hours`, and
`rate_usd` are blank adds no role, and a task with no role states no human
effort of its own (`human_baseline: []`, which needs a `baseline_method` and
a `baseline_note`). A blank cell is a member left out, a blank row is
skipped, and a figure keeps the digits you typed (`6.00` stays `6.00`). The
plan then passes the same checks as a JSON plan. A refusal of the file's
rows names the file, the line and, where there is one, the column
(`plan.csv line 4, column hours: ...`), and exits 2; a file that is not
UTF-8 or not valid CSV is named with the line only.

**A planning workbook.** `alr plan workbook [--out FILE]` writes `plan.xlsx`
(never over an existing file), and `alr plan new|revise --from plan.xlsx` reads
it, with the standard library only (no dependency, no macros, no VBA). Its
**Plan** tab holds the CSV columns above, in their order, in a bold header row
that stays in view (frozen); every column is formatted as text, so a figure
keeps the digits you type (`6.00` stays `6.00`) and a date stays as typed.
`client`, `cost_center`, `work_type`, `baseline_method`, `change`, and `dropped`
have drop-downs of warning style: a value off the list is warned of by the
spreadsheet, never blocked, and OpenALR checks it when the plan is issued. Its
**Lists** tab has one column per list, each client's and cost center's name
beside its code, filled from your `alr-clients.csv`, `alr-cost-centers.csv`,
and config lists, and from the starter work types (`--clients` and `--cost-centers`
name other files). Each drop-down reads a whole-column range of Lists below its
header (`Lists!$A$2:$A$1048576`, by a defined name such as `list_client`), so a
value added in any row of that column joins its drop-down with no table to
extend, in Excel and in other spreadsheet programs alike (an Excel table would
need a table part and an `INDIRECT` reference, which not every program reads);
the drop-down then also shows the column's blank cells after its last value.
`kit/plan-template.xlsx` in the source is that workbook with the spec's starter
lists only, generated by `tools/gen_plan_workbook.py`. OpenALR reads only the tab
named `Plan` (a workbook without one is refused, naming it; so is a damaged
workbook holding two parts of one name, or a Plan tab holding one row number
twice, naming the part or the row). It reads each cell as the
text it holds (a shared or inline string, a boolean as `true` or `false`, a
number's digits as the file holds them, a date cell's text, a formula's stored
result), by the CSV rules. A refusal names
the file, the tab, the row, and the column (`plan.xlsx Plan tab row 4, column
budget_usd: ...`, exit 2). A formula with no stored value is refused, naming its
cell (open and save the workbook in your spreadsheet app so the value is
stored), and so are an error value, a boolean other than 0 or 1, a cell type OpenALR
does not know, and a shared string the workbook does not hold.

The read is bounded in every part, and each limit is refused with its own message:

- **The file and its parts.** A workbook over 8 MiB; the workbook part or its
  relationships part over 1 MiB, or any other part over 32 MiB, by the size its
  entry declares or by what it really decompresses to (a zip bomb).
- **Compression.** A part compressed by any method but stored or deflated (the
  two methods spreadsheet apps save with), an encrypted part, or a part flagged
  as holding compressed patch data (flag `0x20`) is refused before it is opened,
  naming the part and its method or flag. Python's zip reader inflates bzip2 and
  LZMA a whole read at once, with no limit, so a part using either is never
  opened.
- **Rows and columns.** A part nesting deeper than 64 or holding more than
  1000000 elements; a Plan tab of more than 20000 rows; a value past column AF
  or past the header's last column.
- **Shared strings.** More than 200000 shared strings, or shared strings taking
  more than 16 MiB of memory once read. Memory is counted as Python lays strings
  out, the same on every Python version: 64 bytes a string plus 1, 2, or 4 bytes
  a character by its widest character, so a string with one emoji in it takes 4
  bytes a character.
- **Text.** A cell whose text is longer than 4096 characters (a longer shared
  string is refused only where a Plan cell names it), and more than 2000000
  bytes of text across the Plan tab, counted as the plan record holds it (the
  record's JSON writes a character past ASCII as an escape, up to 12 bytes for
  one emoji). A shared string is counted in full at every cell that names it,
  so one long string named by every row cannot grow a workbook of a few KB into
  a plan of gigabytes.
- **XML names.** An element of more than 64 attributes (namespace declarations
  included); an element or attribute name longer than 256 characters, or an
  attribute value longer than 4096; a part using more than 512 distinct element,
  attribute, and processing-instruction names (namespace prefixes and
  instruction targets included). The XML parser keeps each name for the whole
  read of the part; a real part uses a few dozen, and an instruction target is
  capped at 256 characters as a name is. The parser's own tables of raw
  `prefix:local` names are bounded by the part's 32 MiB, not by this cap.
- **Parse events and markup.** A part of more than 4000000 parse events
  (elements, namespace declarations, runs of text, comments, processing
  instructions, and CDATA sections, adjacent text merged into one run first);
  and more than 1 MiB of markup the XML parser reports nothing for (one long
  tag, comment, or other piece of markup, or several in a row, counted from the
  start of the last thing it reported), refused as it arrives, before the XML
  parser has held it whole.

No one cap bounds the memory a read takes; together they do. Peak memory,
measured in a fresh `alr plan new --from` process (Python 3.14, then 3.11 and
3.10 in brackets where measured; every workbook deflated):

- a one-row workbook peaks at 29 MB [29 MB, 26 MB];
- millions of distinct instruction targets are refused at 34 MB [34 MB, 31 MB]
  in under 0.3 s, and a bzip2 or LZMA part at 28 MB [29 MB, 25 MB];
- a 20000-row plan of short text reads in 1.8 s [2.1 s, 2.9 s] at 57 MB
  [56 MB, 58 MB].

The larger probes, measured before release with the largest hostile workbooks
we could build (Python 3.11, then 3.10 in brackets), reach more: the worst
accepted workbook peaks at 158.0 MB [156.3 MB], a workbook that hits every cap
at once at 133.0 MB [131.3 MB], and the worst refused workbook at 132.6 MB
[131.2 MB]; the slowest accepted one takes 13.41 s on 3.10. Python's zip reader
parses the archive's central directory whole and holds it for the whole read
(about 90 MB at the 8 MiB file cap).

A plan's record line is at most its text (the 2000000 bytes above) plus 213
bytes of JSON keys and punctuation for each task (not counted against the
text): 6,259,787 bytes at 19999 tasks, plus the record's own few hundred bytes
and a revision's reason. A revision of 19998 tasks with every column filled and
its text at the budget writes a 6,180,485-byte line (98 MB [96 MB, 101 MB]).

Every part (stored or deflated) is streamed 64 KiB at a time, never held whole
or built into a tree, and each row's cells are kept sparse. A row counts only
where a spreadsheet app shows it, as a row of the sheet's data in the main
namespace: a row inside an extension block or in another namespace is never
read. Every part is parsed with its document type and entity declarations
refused by the XML parser itself, so no entity is ever expanded. A part that is
not UTF-8 (UTF-16 or UTF-32, bytes that are not UTF-8, or a declared encoding
other than UTF-8, by name) is refused, and a part that is not XML is refused
naming its line and column. Any damage OpenALR cannot read is a refusal that
names it, never a traceback.

**A task's accounting tags.** A task may name its `client`, `cost_center`, and
`work_type` (the type of work), each optional, in every form (in CSV as task
columns on the task's first row). Each is a bare value of that tag key, checked
as `/alr-tag` checks a tag (letters, digits, and `: _ . -`); anything else is
refused, naming the task and the key. They are planned facts: OpenALR checks and
reports them (plan against actual, and `alr check` warns when turns of the task
carry another value), and never applies them to a turn. A task with no
`client` or `cost_center` takes its project's from the project list
(`alr-projects.csv`) when it is reported or checked; the plan written keeps only
what the file gave, never a looked-up value. `work_type` has no default.
`effort` is not a planning field. A revision that changes only a task's
`client`, `cost_center`, or `work_type` is accepted with no `change` on that task
(no money moved); its `--reason` says why. A CSV file may also carry a
`project` column: every cell that is not blank must equal `--project`, and
without `--project` the column names the plan's project; two different
projects, or one that is not `--project`, are refused naming the line. A JSON
or TOML file keeps the project on the command line only.

A CSV file revises a plan as a JSON file does (`alr plan revise --from
plan.csv`). A task that is new or differs from the previous version gives its
`change` in the `change` column, on its first row (blank on version 1). Each
task of the previous version that the file drops is a row of its own: its
`task`, `dropped` set to `true`, and its `change` (`scope`, `re_estimate`, or
`basis`), every other cell blank, so a spreadsheet filter on `dropped` lists
them; it is read as that task's `dropped_tasks` entry. On every other row
`dropped` is blank or `false` (any case, as a spreadsheet checkbox column
writes on each unchecked row); any other value is refused, naming the line
and the column:

```csv
task,budget_usd,change,role,hours,rate_usd,baseline_method,baseline_note,dropped
ACME-2026-14:design,8.00,re_estimate,senior engineer,8,150,estimate,contractor rate,
ACME-2026-14:docs,1,scope,,,,estimate,written by the model,
ACME-2026-14:orchestration,,scope,,,,,,true
```

A revision refusal (a changed task without a `change`, a `schedule` change on
a task whose money moved) names the file, the task's line, and the `change`
column (`plan.csv line 2, column change: ...`) and exits 1, as for a JSON
plan; a dropped task with no `dropped` row names the file and the task and
exits 1 too; a revision that changes nothing (`nothing changed from version N`)
names the file only and exits 1 too.

**Money is exact.** Write `budget_usd`, `hours`, and `rate_usd` as a string
(`"1234.50"`) or an integer (`8`). In JSON a number with a fraction
(`1234.5`) is also fine: it is read from the digits you wrote, never through a
binary float, by the same rule as the string form (ASCII digits 0-9, a point,
digits; an exponent such as `1e3`, `NaN`, and `Infinity` are refused). In TOML a float
(`1234.5`) is refused, because the TOML reader has already made a binary
number of it, which may not be the decimal you wrote. In both forms a negative
figure, a `budget_usd` with more than two decimal places, and a figure with
more than 15 significant digits are refused. A figure is written as the number
you gave (`1234.5`, never `1234.4999999`). A planned finish is never before
its start (a date covers its whole UTC day). Figures, dates, and `--grade`
take the ASCII digits 0-9 only.

**Who.** `issued_by` and `accepted_by` are `--by`, else `$ALR_PRINCIPAL`;
with neither the command exits 2. They are never taken from your user name,
the host name, or a credential. A name may hold inner spaces (`--by "Ada
Lovelace"`); leading or trailing whitespace, and a control, bidirectional, or
invisible character, exit 2.

**Where.** Each document is one JSON line appended to the record file the
emitters write (`--file` names another), under the same lock and append
rules as the records, after it is checked against the spec; an invalid
document is never written. Running a command again with the same content as
the latest document (the newest version, or the task's greatest `seq`)
writes nothing and says so; the same content as an earlier one is written
anew (accepting again after a withdrawal takes the next `seq`). A different
document is never written under a version or `seq` the file already holds,
and two writers at once take turns (the second takes the next version or
`seq`, or is refused). A damaged line of the file that could still be a plan
or an acceptance (not valid UTF-8, not JSON, nested too deeply, repeating a
key, or holding text that is not valid Unicode: see Damaged files)
makes `plan new`, `plan revise`, and
`alr accept` refuse, naming its file and line, because it could hold a plan
or an acceptance; `alr check` lists it, and `plan show` reads past it.

**Plan against actual by client, cost center, and type of work.** `alr summary
--by client`, `--by cost_center`, and `--by work_type` add, after the table, each
plan in force with its planned budget beside its actual cost per planned value:
a task's own value, or for `client` and `cost_center` its project's from the
project list, and `(none planned)` for the tasks with neither. The actual cost
is each task's AC as `alr ev` reports it, joined to the task by its `task:` tag;
each basis is its own plan and the two are never added (`--json`:
`plan_vs_actual`). The same rows are in `alr ev --json` and the dashboard data,
under each plan's `by_tag`, and the dashboard's Earned Value screen shows them in
one table per plan. `alr check` warns, one line per task and key, when turns
tagged `task:X` carry a `client:`, `cost_center:`, or `work_type:` other than
X's planned value (after the project-list default), for example
`warning: 3 turns on task ACME-2026-14:build carry client:globex; the plan says
acme` (`--json`: `plan_tag_mismatches`); a turn with no value of the key, or two,
and a task with no planned value are not compared, and nothing is changed or
written.

**Totals never change.** Plans and acceptances are read beside the records
and are not records: `alr summary`, `alr report`, and the dashboard show the
same figures with or without them. `alr check` validates them, lists two
different documents under one key (a conflict: that version or `seq` counts
as missing) as a problem, and warns of a missing version and of a change a
re-plan does not explain.

## The dashboard's breakdown and its CSV export

`alr dashboard --out DIR` writes a static page: four files (`index.html`, `dashboard.js`,
`dashboard.css`, `data.js`) that work only together. Open the whole directory: open
`DIR/index.html` where it was written, and to move or share the page copy the whole
directory, never `index.html` alone. Its Breakdown groups the records the
viewer engine has already resolved, by one or two row dimensions and an optional column
dimension, and adds columns up; it resolves nothing itself. Metered, API-Equivalent, and
unstated-basis cost and the estimate are separate columns and are never added. Reasoning
tokens are shown as part of the output tokens, never added to them. Synthetic records are
left out of the table (the page says how many).

**What the page shows, and how it writes numbers.** The page opens with a header. Its top line
holds the OpenALR logo, the title, and a sun/moon button (a sun in light mode, a moon in dark
mode) that switches the page, charts included, between light and dark; the page follows the
system setting until you pick, and your browser keeps the pick when it allows storage. The
header shows three facts: the project tags the records use, each input's path, and when the
page was generated. Below it come the
**contents**, one column: the five groups, numbered (Overview, Breakdown, Sessions, Earned
Value, and Reference), each with its sections lettered under it, and every entry a link to
its section; an Overview section that the chosen period does not draw is listed as plain
text, not a link. Then a **Build
Details** section (closed until you open it) holds everything else about the build, once:
the data and engine versions, the time zone, the document schemas read, whether the build is
redacted, the record counts, each input with its sha256 and size, and the price book in use
by its label and version, format, as-of date, published-at time, origin, model count, sha256, and signing
key (the built-in key, or an organization key by its configured name and key id, as
`alr prices show` names it; never the key itself). The Headline Figures' "Estimate priced
from" row names the same book in short: format, as-of date, the start of its sha256, and its
signing key, a list price and not a bill. A redacted build keeps the book's sha256 and the
key's id and leaves out an organization key's name. Totals and headline figures are in
dollars to the cent (`$1.29`); the Session Drill-Down, which lists each record and turn,
keeps four decimals (`$1.2887`), because a turn can cost less than a cent. Every count has
its thousands grouped (`1,322,992`). Where there is no figure the page writes `n/a`: no
record in the period has that kind of cost, which is not `$0.00`. The Cost panel says so
once. The Overview's Cost names the four kinds of cost, one bullet each (Metered,
API-Equivalent, Unstated Basis, and Estimate), and says they are never added together. Under
the Overview's period dropdown one line says the period applies to Cost, For What, Worth It,
Headline Figures, Cost Per Day, and Trust, the six sections of the Overview group. The page spells the basis one way, "API-Equivalent", in its headings, tables, notes,
and Build Details. A table's or chart's notes are a bulleted list right below it.

**Links within the page.** The Overview's Worth It panel links down to the Earned Value
screen, and the Earned Value screen links back up to it ("Back to Worth It", with an up
arrow, under its heading) while the Overview draws Worth It; while the Overview's period is
refused (the page says why under the period dropdown), Worth It is not drawn and the link
is hidden.
Worth It counts the period's graded replies ("2 of 15 replies
graded (grading is optional)") and says what a grade is; its line "Task acceptance grades: see
Earned Value" links to the Earned Value screen, which holds the acceptances. Under each plan's Figures table, "What these mean" links to the
**Glossary**, which is part of the page, so it works offline: one line for each earned value
term (BAC, PV, EV, AC, CPI, and SPI) with its formula and what it means. When a plan in force
draws its Figures table, the Glossary links back to the first such table ("Back to Earned
Value Figures"); with no plan in force there is no such link. Every section heading ends with
a "Back to Top" link (with an up arrow) to the page's title. A group heading is larger than
the sections under it and has an orange rule above it; Reference holds the Glossary, the
totals, the counts, Data Health, and Quality. The Overview's Cost, For What, and Worth It
panels stack in one full-width column. Trust says what holds ("Records with a complete cost",
"Records tagged with a project", the metered and API-Equivalent cost tagged with a project, and
"Records file: every line read" when no line had a problem). Each Trust line links to its own row in Data Health:
the complete-cost line to "Incomplete cost", the three project-tag lines to "Untagged spend (no
project)", and the records-file line to "Problem lines from loading". The complete-cost line
leaves out more than the "Partial cost" row counts: a record is left out when its cost is
partial, unknown, estimated for a parent the input does not price, or unpriced (a record of
more than one kind once). "Partial cost" counts only the partial ones and "Unknown cost" the
unknown ones; "Incomplete cost", first in Data Health, counts every kind the line leaves out,
in the chosen period and in all records, with the period's per-kind counts under it. The row you land on is
outlined and carries a way back to Trust and to the top, and Data Health has "Back to Trust"
under its heading (while the Overview draws Trust). The gaps line is plain text, not a link.
These are in-page links: following one leaves the Breakdown as it is.

**Projects come from the records; names are shown beside them.** A project is the value of
the record's `project` tag (`project:p1` is the project `p1`), so two spellings of one
project are two rows. A name configured for a code in the `[projects]` table of your user
config (see [Project names](#project-names)) is shown after the code, in parentheses;
the rows and every figure stay one per code, and the records keep the code. The page says so in a note under
any table grouped by project. A redacted build carries no names.

**Project, Task, Client, Cost center, and Work type are split by turn shares.** These dimensions (labeled
"split by turn shares") equal `alr summary --by project` and its siblings: a turn's share of
its session's cost is under the turn's own value and the session's own value keeps the
remainder, as the Tag rows move the same shares; a session whose turns state no share counts
whole. The Overview's projects and the Quality screen's projects are split the same way. A
table of one of these dimensions says how many of its rows hold allocated (price-weighted or
token-weighted) shares and how many hold a negative remainder (turn shares above the session's cost). No other
dimension and no total moves a share.

**Money is added exactly.** Each record's cost, a USD float in the data document, is
rounded once to a whole nano-dollar (`Math.round(usd * 1e9)`), and those integers are
added (as a Number below 2^52, then in a BigInt), so a total does not drift with the
order of the rows or the number of them. A total is shown to the cent and the Session
Drill-Down to four decimals, each rounded half away from zero from the exact sum. The
Overview adds and shows money the same way, so every place on the page that shows the same
total shows the same digits. A single cost above 2^52 nano-dollars (about 4.5 million dollars) cannot be
added exactly, so it is neither rounded nor added: every cell that would add it says
"cannot be added exactly", the table says how many of its records hold one, and the
health section counts them over the whole input. The rest of the page is shown as usual.

**The CSV holds the table you see.** The Breakdown and the Session Drill-Down each have a
"Download CSV" button. The file holds the table's rows and columns, its figures in the
CSV's own form: dollars to four decimals, counts as plain digits (`1322992`), and
`no figure` where there is none, whatever the page shows. Its column names keep the data's
spelling (`API-equivalent (USD)`, where the page writes "API-Equivalent"). It is built in the page (a
`blob:` address where the browser has one, otherwise a `data:` address) and nothing is
sent anywhere. It follows RFC 4180: fields
with a comma, a double quote, or a line break are quoted, quotes are doubled, and lines end
in CRLF. The file's first row names the view (row and column dimensions, measure, period, time zone,
whether synthetic records are included, and each filter value in a cell of its own); the
table follows. Those cells go through the same writer as every other cell.

**Controls, filters, and the address.** The Breakdown has a control for its row dimensions
(one or two), column dimension, measure, and period, and a value picker (with a search box)
for every dimension; "untagged" and "ambiguous" are values of their own. A switch to
include synthetic records is shown only when the loaded records hold some.
The controls and filters sit in one "Table Controls" panel (Sessions has the same panel for
its period and filters), and a "Showing: ..." bar directly above each table names one chip
per filter in use, or "No filters".
With no column dimension the Breakdown shows its primary columns (the group, Records,
Metered, Estimate, Turns, Grade Mean); a +/- button on each row opens a second row with
the other figures, and "Expand all" opens every one. The CSV still holds every column.
The Session Drill-Down does the same with its primary columns (Row, Turn Index, Outcome, Tags,
Metered, Estimate), and its CSV also holds every column.
Quality draws each dimension's two tables in two rows too, at every width: its summary keeps
the group, Records, Graded Records, and Metered (USD) in the row, and its cost-by-grade table
the group, Grade, Records, and Metered (USD). The summary's second row holds Ungraded Records,
Metered Ungraded Share, API-Equivalent (USD), API-Equivalent Ungraded Share, Unstated Basis
(USD), and Unstated Ungraded Share; the cost-by-grade table's holds API-Equivalent (USD) and
Unstated Basis (USD). At phone width (40rem or narrower) three more tables are drawn in two rows, and a wider
screen keeps them whole: Sessions (Session, Records, and Metered (USD) stay in the row), and
the Earned Value screen's Tasks table (Task, Status, Budget (USD), and AC (USD)) and Worth It
table (Task, Baseline Value (USD), AC (USD), and Leverage (Baseline / AC)).
A filter keeps the records that hold at least one picked value; filters on different
dimensions all apply, together with the period. The view is kept in the address fragment
(`#v1;d=model.agent;a=day;m=metered;s=1;p=custom,2026-10-01,2026-10-31;f=model:0.1`), made
only of the page's own words, numbers, and days: a filter value is its dictionary index, never
the record's text. An address that starts `#v1` but cannot be read is ignored, and the
Breakdown says so; any other address (an in-page link such as `#health`) is left
alone and changes nothing.

**Formula neutralization.** A spreadsheet may run a cell that begins with `=`, `+`, `-`,
`@`, `|`, a tab, a carriage return, or a line feed. Every cell of the file (a record's text
in a row label or a column heading among them) that begins with one of these is written
with a single quote in front (`=1+1` becomes `'=1+1`), so the spreadsheet shows the text.
The same is done when leading white space comes before `=`, `+`, `-`, `@`, or `|` (` =1`
becomes `' =1`), and for the full-width forms `＝`, `＋`, `－`, and `＠` (U+FF1D, U+FF0B,
U+FF0D, U+FF20), with or without leading white space. White space here is JavaScript's
`\s`: the space, tab, line breaks, NBSP, U+3000, every other Unicode space separator, and
U+FEFF. This goes beyond the usual list of formula characters, because some spreadsheets
trim leading spaces or read full-width signs on import; it is defense in depth. Nothing
else in a cell is changed, and a cell that begins with a quote is left alone.

## Damaged files

Every reader here keeps going when a file is damaged. A line it cannot use is
counted and named by file and line number (never by its text), and the lines
around it are still read. Nothing is dropped without being counted.

What counts as a damaged line: not valid UTF-8, not JSON, not a JSON object (a
bare number, string, or array), nested more than 64 levels deep (objects and
arrays together, the line itself being level 1; the limit is OpenALR's own, so a
line gets the same answer on every Python version), holding text that is not
valid Unicode (a `\u` escape of a lone surrogate, which no reader could print),
holding a number that is not finite (`NaN`, `Infinity`, `1e999`) or has more digits than the
interpreter will read, or repeating a key inside one object (it would otherwise
silently pick one of the two values). A record that parses but breaks the
record rules (a missing field, a field of the wrong type, a timestamp with no
offset or one with no UTC form) is reported the same way, with the rule and no
value. A blank line is skipped. A byte order mark at the start of a file and
Windows line ends are accepted. A last line cut short by a crash is damaged
like any other. A document of another schema family or version is not damage:
it is counted by name and left out (`alr check` lists them).

A value from a file that a message has to name (the name of an unknown schema,
a tag in an `alr check` line) is shown as it is only when it is short and
printable. Otherwise its control characters, line breaks, and other
non-printable characters are written as `\xNN` or `\uNNNN` escapes (and a
backslash as `\\`), it is cut to 40 characters, and ` (escaped)` follows it, so
it can never start a line of its own or reach the terminal as a control sequence.

An id (of a record, request, tag event, or cost correction) is shown whole and
unmarked when it is plain printable ASCII and at most 128 characters long, the
length a tag may have, so the request ids the adapters write
(`<session id>:t0001`) are always shown whole. Only an id holding any other
character (a control, a line break, anything outside printable ASCII), or one
longer than 128 characters, is escaped, cut to 40 characters, and marked
` (escaped)` as above. `alr check --json` always carries every id in full.

What each reader does with a damaged line:

| reader | damaged line | exit status |
|---|---|---|
| `alr summary`, `alr turns`, `alr report` | counted in the footer (`N lines or records could not be used`) and in the `problems` list of `--json`; the other lines are summed as usual | 0 (`alr turns` is 1 when no readable record is left) |
| `alr check` | listed as `problem: <file>:<line>: <reason>` | 1 when any line is damaged |
| `alr tail` | not shown; named on stderr as `alr: <file>:<line>: skipped: <reason>`, also while following | 0 |
| the record file as the emitters read it back (to number attempts and skip a repeated re-emit) | passed over | the emit goes on |
| the session journals (`turns.jsonl`, `changes.jsonl`, `replies.jsonl`) | passed over by the readers that fill a turn table or resend events; the `*_checked()` methods of `SessionStore` return the skipped lines as `<file>:<line>: <reason>`. A turn line whose `n` is not a positive integer or whose field has the wrong type (`tags` that are not a list of text, say) is such a line. So is one of the two lines with no `n`: a command line (`blocked`) whose command is not text or is empty (nothing left once whitespace, format characters such as a zero-width space or a byte order mark, and the invisible combining grapheme joiner and Hangul fillers are stripped), a binding line (`bound`) whose turn is not a positive integer or whose `request_id` is not text, or a line that holds both `blocked` and `bound` (which counts as neither a command nor a binding). So is a turn line (one with an `n`) that also holds `blocked`, `bound`, or `request_id` (`a turn line that also holds blocked, bound or request_id`), which counts as no turn, no command, and no binding. Each reader takes a line's fields only from a line of the kind it reads (a turn, a command, or a binding); `/alr-turns` ends with `N turn journal lines could not be used: turns.jsonl:<line>: <reason>` | n/a |
| the kit state file and a session's `state.json` | an unreadable or non-object file, one nested past the same 64 levels, or one holding a lone surrogate, is an error that names it; it is never read as an empty state | the install or uninstall stops; an `/alr-*` command answers with the error, and a turn start is not journaled and names the file on stderr |

A line is split on the newline character only. A lone carriage return inside a
line, or a Unicode line separator inside a JSON string, does not start a new
line.

## If you installed a pre-release build

0.1.0 is the first release. If you ran a pre-release build before it, install
0.1.0 over it with `--reinstall` (a pre-release build may carry the same version
number), then run `alr install <harness>` again for each harness you use; the
preview shows what it adds or refreshes, or says it is already installed:

```
uv tool install --reinstall alr-emit     # or: uv tool install --reinstall ./alr_emit-0.1.0-py3-none-any.whl
alr --version                            # OpenALR alr-emit 0.1.0
alr install <harness>
alr install <harness> --yes
```

Your records and session state are kept, and 0.1.0 reads what a pre-release
build wrote:

- **Records** without the optional fields added later (such as `cost_share_usd`,
  `provider`, or `credential`) are read and summed as they are. A turn record
  that states its numbering space in the `x_turn_index_space` extension instead
  of `turn_index_space` is read as the standard field; `/alr-turns` shows both
  alike, and only a restatement of such a record still carries the extension.
- **Turn numbering.** A pre-release build gave every Claude Code prompt a turn
  index, those that make no model call included. A session keeps the numbering
  its records were written under, so a turn already emitted keeps its
  `request_id` and is never counted twice: the session's turn records already in
  the sink decide; failing that, the session's state (`turn_numbering`:
  `model-call`, or `every-prompt`, which a state written before that field
  existed also means). A backfill over such a sink therefore restates nothing.
  For Grok Build, a pre-release build numbered a session's turns by Grok Build's
  own `turnNumber` (its records say `turn_index_space: "grok-turn-number"`, or
  state no space), where 0.1.0 numbers real turns only (the turns with a model
  call, tokens, or a cost). A session the record file already holds in that
  numbering keeps it to its end, so its recorded turns keep their ids and
  indices; every other session is numbered by real turns.
- **Session state** (`state.json`, `turns.jsonl`) is read as it is; a turn
  journaled with two values of one reserved key keeps the later one. A
  per-session tag file (`sessions/<harness>/<session id>.tags` in the OpenALR
  home) is read while the session has no session state yet: its tags become the
  session layer, its `-tag` lines tombstones, and the result is saved on the
  session's first change or turn start. The old file is left in place.
- **`changes.jsonl`** entries written as `alr-tag-change/0.1` are kept in the
  file as they are: they are not rewritten, and since nothing sends the outbox
  anywhere, they are not sent either. A tag or control command run after the
  upgrade numbers its event on from the highest sequence number in the file.
  `SessionStore.changes_checked()` names any line of the file that cannot be
  used, an `alr-session/0.1` event whose `seq` is not an integer among them;
  such an event is never counted as pending.
- **Claude Code records with no cost.** A pre-release build's hook mode read the
  session cost only from `result` lines, which real transcripts do not carry
  (they carry it in `cost-state` lines), so a record it made from a real
  transcript has `cost_usd: null`. Run `alr-emit-claude backfill` over the same
  transcripts: it restates them with the cost, superseding the null-cost
  records. It also restates `cost_in_parent` turn records as the next attempt
  (with their `cost_share_usd` where a figure is held); totals are unchanged,
  because a share is never added.
- **Grok Build forks.** Records a pre-release build wrote for a fork's copied
  parent turns stay in the record file and still count twice; every run names
  them ("a record written earlier for a copied parent turn stays and counts
  twice"). Such a fork's own records can keep a "possible fork copy" note in
  `/alr-turns`, while every figure on them is correct.
- **Dashboards.** A dashboard page a pre-release build wrote refuses this
  release's data document (version 8); build the page again with `alr dashboard`.
- **Spellings kept for this release only.** `/alr-tag a b` means `add a b` and
  `/alr-tag -a` means `rm a` (the answer carries a deprecation note); `clear` is
  unchanged, and `/alr-tag undo` is the verb (use `/alr-tag add undo` for a tag
  named `undo`). The pre-release profile name, `profile = "fabric"`, is a deprecated spelling of `managed`:
  with it in the user config every protection of the managed profile holds,
  `/alr-ctl status` and `/alr-ctl config` end with the line
  `alr: profile "fabric" is deprecated; use "managed" (accepted until the next release)`,
  and an `alr` command that reads the config writes that line once to stderr when
  it ends, even when it is refused or fails (`alr hook` never does). Set
  `profile = "managed"` instead.

## Journal export: `alr journal`

`alr journal` turns a period of resolved records into a balanced journal
CSV for an accounting system. It reads record files and a GL-mapping
file, and writes one file. It uses the standard library only and opens no
network connection.

```
alr journal --period 2026-10-01..2026-10-31 --map gl-map.toml --out october.csv
alr journal --period 2026-10-01..2026-10-31 --map gl-map.toml --profile generic [FILES...]
```

- **The records are the viewer's.** The journal reads the same current
  records `alr summary` does, resolved by the same code: supersession
  (SPEC section 4.1), cost corrections (SPEC section 3.2.1), and parent
  inclusion (SPEC section 4). Nothing is resolved a second time.
- **The period** is `START..END`, two ISO dates, both days included. A
  record belongs to the day of its `finished_at` in the zone `--tz`
  names (`utc` by default, so the same files give the same journal on any
  machine; `local` is available). The entry is dated the last day of the
  period. Synthetic records are left out.
- **Files** are named as for `alr summary`: files, directories of
  `*.jsonl`, or none for the emitters' file.
- **Output** goes to `--out`, written whole or not at all, else to
  standard output (with the report on standard error). A bad period, a
  bad map, or a period with nothing to post is refused and writes
  nothing. "Nothing to post" means exactly this: the period's exact
  metered total, rounded half to even, is `0.00` (see Money below).

### The GL-mapping file

The map says which general-ledger account a cost posts to. It is a TOML
file; the version string names the map in every entry reference, so
change the version whenever you change the map.

```toml
version = "2026-10"                         # 1-64 of A-Z a-z 0-9 . _ -
default_account = "AI Compute"              # records no map line matches
offset_account = "Accrued AI Spend"         # the credit side of the entry
ambiguous_account = "AI Spend Ambiguous"
rounding_account = "AI Spend Rounding"

[acme]                                      # one table per map line; any name
key = "project"                             # project | task | cost_center | client | provider
value = "ACME-2026-14"                      # the tag value after the colon, or the provider
account = "AI Compute Acme"
dimension = "Delivery"                      # optional; carried in the dimension column

[engineering]
key = "cost_center"
value = "engineering"
account = "AI Compute Engineering"

[payable]                                   # optional; marks an account as A/P or A/R
account = "Accrued AI Spend"                # an account the journal uses
account_type = "ap"                         # ap = Accounts Payable, ar = Accounts Receivable
name = "Example Vendor"                     # the vendor (A/P) or customer (A/R)
```

Account names are written exactly as the accounting system names them.
For QuickBooks Online that means by name, with no account number in
front (it asks for account numbers to be turned off before an import),
and a `:` only where you mean a sub-account: `Parent:Child` names the
sub-account `Child` under `Parent`, so `AI Compute: Acme` would name a
sub-account ` Acme`. Every account must already exist in the chart of
accounts.

- A table with an `account_type` is an **account mark**, not a map line: it
  says the account is Accounts Payable (`ap`) or Accounts Receivable (`ar`)
  and gives the vendor or customer `name`. Only the `qbo` profile uses it
  (see QuickBooks Online below); an account can be marked once.
- The five top-level fields are required. No other top-level entry is
  accepted, and every table is either a map line or an account mark (above);
  write `[name]`, with no dots; arrays of tables are refused.
- A record's `project:`, `task:`, `cost_center:`, and `client:` values are
  its reserved tags (SPEC section 2.3); `provider` is its `provider` field. The
  first line, in file order, whose key and value the record carries
  decides its account.
- `offset_account` must differ from every account the journal debits,
  and no key and value may be mapped twice.
- A bad map is refused with a message naming the file and the first
  problem, and nothing is written.

### Posting rules

- **Metered cost posts.** A figure booked under `cost_basis: metered`
  becomes a debit, grouped by account and by the record's project, task,
  cost center, client, and provider.
- **API-equivalent value never posts.** It is no money spent (SPEC section 2.2).
  It appears only as a memo figure on the offset line and in the report.
- **An unstated basis never posts.** The report names those records and
  their figures. So does a metered record whose cost is unknown.
- **Partial cost is flagged.** A line that includes records with
  `cost_is_partial` says `PARTIAL cost on N of M records` in its memo.
- **A correction takes the corrected figure and drops the partial flag.**
  A cost correction replaces the record's cost figure (SPEC section 3.2), so the
  journal posts the correction's figure under the correction's basis, and
  the replaced record's `cost_is_partial` no longer applies: the line is
  not flagged and the report does not list the record as partial.
- **An ambiguous reserved key posts whole to `ambiguous_account`**, never
  split between its values (SPEC section 2.3), and its dimension column reads
  `(ambiguous)`. Any of the four reserved keys with two values makes the
  record ambiguous. The report lists the records. Until the viewer
  applies SPEC section 3.3.1's replacement of a reserved key's value, a record
  re-tagged with a new `project:` also reads as ambiguous.
- **A record no map line matches posts to `default_account`** and is
  listed in the report.
- **Reserved keys are read by the engine's one resolver.** The journal
  reads a record's effective tags into its four dimension columns
  (`project`, `task`, `cost_center`, `client`) through
  `resolve.reserved_tags`, the reading `alr summary`, `alr check`, and the
  dashboard use, so a record they call ambiguous for one of those keys is
  ambiguous here too. An empty value (`project:`) is a value, so `project:` beside
  `project:ACME-1` is ambiguous; a key in another case (`Project:x`) is
  not reserved. The reserved key `work_type:` is not a ledger dimension:
  the journal has no column for it, the GL map cannot match on it, and two
  values of it do not make a record ambiguous here.
- Every caveat above is printed in the report with the record ids (the
  first 20 of each), on standard output when `--out` is given and on
  standard error otherwise.

### Money

- **Decimal only.** Every figure is read into a `Decimal` the moment it
  is taken from a record (a number from a JSON file is read through its
  shortest text, so `0.1` is one tenth, never its binary neighbor), and
  no float takes part in any sum.
- **Cents rounding.** Costs are summed exactly, per journal line, and each
  line is rounded to whole cents **once**, half to even (`0.125` is
  `0.12`, `0.135` is `0.14`). Records are never rounded one by one.
- **The offset line** is the exact total of all lines, rounded once the
  same way. The difference between it and the sum of the rounded lines
  (including any line that was under half a cent and so has no line of
  its own) is posted to the `rounding_account` as a line of its own, a
  debit when the lines fall short and a credit when they overshoot. It is
  never dropped, and it is named in the report.
- **When every line rounds to `0.00`** but the exact total rounds to a
  cent or more, the entry is still posted: the rounding line carries the
  whole amount and the offset credits it (three lines of `0.004` are
  `0.012` exactly, so `0.01` is debited to `rounding_account` and
  credited to `offset_account`). The export is refused as "nothing to
  post" only when the exact total itself rounds to `0.00` (`0.004` and
  `0.001` are `0.005`, which is `0.00` half to even). That holds when lines
  survive too: figures of both signs (a negative cost, a correction) whose
  exact total is `0.00` are refused, since there would be no amount for the
  offset line.
- **The journal always balances.** The debits equal the credits exactly,
  in the entry and in the file. If they could not, the export is refused
  and nothing is written.
- Amounts are written as plain digits with two places, one of `debit` or
  `credit` filled per line.

### Re-exporting a period

Exporting the same period over the same records gives a byte-identical
file. Lines are sorted, nothing in the file comes from the clock, the
machine's zone, or the file paths, and the entry reference is derived from
what the entry holds:

```
ALR-<start>-<end>-<12 hex>
```

The 12 hex digits are the start of `sha256("<start>|<end>|<map version>|<set hash>")`
(dates as `YYYY-MM-DD`). The set hash is the sha256 of the sorted
fingerprints of the period's current records, one per line (UTF-8, `\n`
between them). A fingerprint is the compact JSON array `[alr_id, day, bookings,
cost_is_partial, sorted effective tags, provider]`, where `day` is the
record's day in `--tz`, and `bookings` is the sorted list of
`[cost basis, cost, correction id]` the viewer resolved for it (`cost`
without trailing zeros, `null` when unknown). So the reference changes
when a cost, a correction, a tag, the period, or the map version changes,
and does not change for records outside the period, superseded records,
or synthetic ones. **Change the map's `version` whenever you change the
map**: the reference does not read the rest of the map.

### Profiles

`--profile generic` (the default) writes a journal any spreadsheet or
importer can read, one row per journal line:

```
date, entry_ref, account, project, task, cost_center, client, provider, dimension, debit, credit, memo
```

`--profile qbo` writes the QuickBooks Online journal-entry CSV import
layout, described next.

#### QuickBooks Online

The columns are `Journal No.`, `Journal Date`, `Account Name`,
`Journal/Description`, `Debits`, `Credits`, and `Name`: `Journal No.` is the
entry reference (shortened, see below), `Journal Date` the last day of the
period, and the other four
are the account, the memo with the line's dimensions appended
(`project=...`, `task=...`), and the two amounts, one of them blank per row.
`Journal/Description` is the US spelling (the UK and Canadian pages say
`Description`). QuickBooks Online maps the headers of the file to its fields
on import, so the exact spelling is not enforced and a renamed column can be
mapped by hand.

**Journal number.** The generic profile's entry reference is long
(`ALR-<start>-<end>-<12 hex>`), so the qbo `Journal No.` is `ALR-<12 hex>`,
the same 12 hex digits, 16 characters, and with `--split` each entry gets
`-1`, `-2`, and so on after it (21 characters at most, which allows 9999
entries). The 21-character limit is an inference: the page does not give a
length for the import's Journal No., and 21 is the QuickBooks Online API's
limit on a journal entry's `DocNumber`, applied here to the import. The
number is derived from the period, the map version, and the record set, so it
is stable on a re-export and differs when any of them changes, and it is
unique to each entry within an export, files of a split included.

`Name` is the seventh column. It is filled only on lines whose account the
map marks as Accounts Payable or Receivable (an `account_type` table, see
above). QuickBooks Online requests a Name (a vendor or customer) on those
lines; Name is not in the page's list of required columns. So when such a
line has no `name`, the export writes the line with an empty Name and warns on
standard error, naming the account and the map table to add `name = "..."` to.
Intuit's US text asks for a vendor in the Name column on those lines, even for
Accounts Receivable; the UK and Canadian pages say supplier.
Source for this rule, Intuit's help article "Import journal entries" (QuickBooks
Online, US):
https://quickbooks.intuit.com/learn-support/en-us/help-article/import-export-data-files/import-journal-entries-quickbooks-online/L4tQBwbs7_US_en_US

Accounts go by name. QuickBooks Online asks for account numbers to be
turned off before an import, so `Account Name` is the map's account name as
written: a name with a colon, `Parent:Child`, is written as it is and names
the sub-account `Child` under `Parent` (a child name alone is rejected by
QuickBooks as an invalid account), and the account must already exist in the
chart of accounts. When a map account name starts with a number (`6110 Acme`),
`alr journal --profile qbo` writes the file and warns on standard error,
naming each such account. Source for these rules, Intuit's help article "Import journal entries" (QuickBooks
Online, US):
https://quickbooks.intuit.com/learn-support/en-us/help-article/import-export-data-files/import-journal-entries-quickbooks-online/L4tQBwbs7_US_en_US

**The row limit.** QuickBooks Online imports fewer than 1,000 rows per
spreadsheet (Intuit's "common questions about importing data" page:
https://quickbooks.intuit.com/learn-support/en-us/help-article/import-export-data-files/common-questions-importing-data-quickbooks-online/L4OYJRFdj_US_en_US ).
Whether the header row counts toward that number is not stated, so this
is an assumption: the header is taken to count, and the limit used is 998
data rows, so a file of 998 data rows and its header is 999 lines, under
1,000 either way. When the file has more than 998 data rows,
`alr journal --profile qbo` still writes it and warns on standard error.
`--split` (needs `--out`) writes numbered files instead, `october-001.csv`,
`october-002.csv`, and so on for `--out october.csv`, each of at most 998 data
rows. A split run cuts the
journal into several entries, each with its own offset line and its own
journal number, so that each entry balances on its own and no entry spans
two files; the files together post the same net amount to every account as the
single file. The gross Debits and Credits columns can be larger: a run that
nets negative gets a debit offset line, so the column totals of a split set
can exceed the single file's.

**Never import both forms of one period.** The split journal numbers are the
single-file number with `-1`, `-2`, and so on after it, so they are different
numbers. What Intuit's "Import journal entries" page says about duplicates is
that, with its "Warn if duplicate journal number is used" setting turned on
(the UK and Canadian pages call it "Warn me if duplicate journal number is
used"), some entries will not upload: those whose journal numbers already
exist. It does not say what happens with the setting off,
nor whether the check compares whole numbers or a stem. Assuming whole numbers, it will not flag a split set imported after the
single file, or the other way round, and the period would post twice.
`alr journal --split` prints this warning on standard error. An
older numbered file from an earlier export that is not part of the new set
is named and the export refused, so a stale part cannot be imported by
mistake. The page does not say how many entries a file may hold or what the
file-size limit is.

**Date format and separator: assumptions, not cited.** Intuit's US pages
say nothing about the date format or the separator of the file, so these
are assumptions, and two flags let you match your company's settings. They
apply to both profiles and change only how the file is spelled, never an
amount, an account, or an entry reference.

- `--date-format YYYY-MM-DD|MM/DD/YYYY|DD/MM/YYYY` (default `YYYY-MM-DD`,
  ISO) writes the entry date in the `Journal Date` column. The default is
  an assumption: the US pages do not say which format the import takes, so
  check the first import and pick the format your company uses.
- `--delimiter comma|semicolon` (default `comma`) is the cell separator.
  Comma is the safe US default. The UK and Canadian pages say the separator
  depends on the operating system (a comma on Windows, a semicolon on
  macOS), which the US page does not say. The two pages are Intuit's UK
  help page on importing journal entries and its Canadian one (their exact
  page titles are not recorded here):
  https://quickbooks.intuit.com/learn-support/en-uk/help-articles/import-journal-entries-in-quickbooks-online/00/507742
  and
  https://quickbooks.intuit.com/learn-support/en-ca/help-article/import-export-data-files/import-journal-entries-quickbooks-online/L4tQBwbs7_CA_en_CA

Source for the required columns and the header mapping, Intuit's help
article "Import journal entries" (QuickBooks Online, US):
https://quickbooks.intuit.com/learn-support/en-us/help-article/import-export-data-files/import-journal-entries-quickbooks-online/L4tQBwbs7_US_en_US

How far to trust this profile. The required columns, the Name rule, the
sub-account form, the account-number setting, and the row limit above come
from Intuit's own help pages (linked where each is used), read for this
profile. The sample import file can be downloaded only inside QuickBooks
Online, so the optional column names are not confirmed against it: test-import
a small file before relying on this profile. These are **not cited, and not
written**: the column names QuickBooks uses for Class and Location, the
Currency column, the limit on file size, the number of entries a file may
hold, what happens to a repeated journal number when the duplicate warning is
turned off, and the rule that lines sharing a journal number form one entry
(the layout implies it; it is not stated). The journal number length is an
inference (above), and the date format and the separator are assumptions with
flags of their own.

**Known limit: the dimensions are text in `Journal/Description`.** The project,
task, cost center, client, provider, and dimension label of each line are
appended to its `Journal/Description`. This is an inference from the columns
that are not written, not a statement by Intuit: no Class or Location column
is written, so QuickBooks Online will not read them as
Class, Location, or any other field, and after an import they are only words
in the line's description. Filter or report on them in QuickBooks by
account, or use the generic profile, which writes each one in a column
of its own.

Text cells get a leading `'` in both profiles, so a spreadsheet does not run
them as formulas, when they start with a tab, a carriage return, or a line
feed, or when their first character after any leading white space is `=`,
`+`, `-`, `@`, or `|`, or one of the full-width forms of `=`, `+`, `-`, and
`@` (U+FF1D, U+FF0B, U+FF0D, U+FF20). This is the dashboard's CSV rule: the
"Formula neutralization" paragraph under "The dashboard's breakdown and its
CSV export" says which characters count as white space.

### Corrections after a period was exported

A posted period is closed: a correction to it is never an edit of the
entry already posted. It becomes an **adjusting entry in the open
period**. `alr journal` does not generate that adjusting entry; it detects the case and reports it. When a cost
correction that was made after the last day of the period (by its
`occurred_at`, in `--tz`) applies to a record inside the period, the
report says `correction after the period: N`, and for each one prints the
correction id, the record, and the figure before and after.

The export always shows the records as they stand now, so re-exporting a
period after such a correction gives a different file with a different
entry reference (the correction is part of the set hash). Keep the file
you posted, and post the difference in the open period by hand. Do not
post the re-exported period a second time.

## Forwarding records to syslog: `alr syslog send`

```
alr syslog send --to tls://logs.example.com:6514 [--ca-file CA.pem] [--facility N] [--hostname NAME] [--dry-run] [FILE...]
alr syslog send --to tcp://syslog.example.com:514 records.jsonl
```

`alr syslog send` forwards records that are already on disk to a syslog
receiver. It is a reader like the rest of `alr`: it takes the same files
(none named means the emitters' file; a directory contributes its `*.jsonl`
files) and sends what they hold. Nothing is added to any hook, adapter, or
emit path: recording a turn never touches the network, and the code that
opens a socket is loaded only when you run this command.

The spec (section 8, Transports) says a record is the same JSON object
whatever carries it, and that when records travel as syslog the MSG part of
each message is exactly one record or event. This command does exactly
that, using

- [RFC 5424, The Syslog Protocol](https://www.rfc-editor.org/rfc/rfc5424) for the message,
- [RFC 5425, Transport Layer Security (TLS) Transport Mapping for Syslog](https://www.rfc-editor.org/rfc/rfc5425)
  for `tls://`, and
- [RFC 6587, Transmission of Syslog Messages over TCP](https://www.rfc-editor.org/rfc/rfc6587)
  for `tcp://`.

**Targets.** `tcp://HOST:PORT` or `tls://HOST:PORT`; the port is required,
an IPv6 host goes in brackets (`tls://[::1]:6514`). Nothing else is accepted
in the target: no user name, password, path, or query. There is no option for
a credential.

**UDP is not offered.** The spec says producers SHOULD use a stream transport (TCP or TLS) rather than UDP, because a record can exceed
datagram size limits and RFC 5424 lets a receiver truncate an over-long
message. A truncated record is not a record, so a `udp://` target is refused
with that reason and nothing is sent.

**Framing.** Messages are framed by octet counting (RFC 6587 section 3.4.1,
RFC 5425 section 4.3): the message length in octets, a space, then the message.
There is no size limit of its own; a record over 64 KiB is sent whole.

**The message.**

```
<14>1 2026-03-04T05:06:07.25Z - alr - alr - {"alr_schema":"alr/0.1",...}
```

| Part | Value |
|---|---|
| PRI | facility * 8 + 6 (informational); `--facility N`, 0 to 23, default 1 (user) |
| VERSION | 1 |
| TIMESTAMP | the record's own end time (`finished_at`; for a grade, tag, or cost event, its own time) if it is a valid RFC 3339 timestamp, written in RFC 5424's form; otherwise `-` |
| HOSTNAME | `-` unless `--hostname NAME` is given |
| APP-NAME | `alr` |
| PROCID | `-` |
| MSGID | the record's schema family (`alr`, `alr-session`, `alr-grade`, ...), or `-` |
| STRUCTURED-DATA | `-` |
| MSG | the record's line from the file |

The MSG is the line's bytes exactly as they are on disk, without the line
terminator: not re-serialized, so a receiver that parses it reads precisely
the object that is in your file. It carries no byte order mark (RFC 5424
allows one in MSG, but RFC 8259 says a JSON text must not begin with one, and
the spec's rule is that the MSG is one JSON object). Every header field is printable ASCII within
RFC 5424's length limit (HOSTNAME 255, APP-NAME 48, PROCID 128, MSGID 32).

**The machine's name stays home.** HOSTNAME is `-` unless you pass
`--hostname`. Nothing else about this machine is sent: no process id, no
user, no path.

**A line that is not one complete JSON object is not sent.** It is counted
and named by `file:line` with a fixed reason (never the line's content), the
other records still go, and the exit status is nonzero. Blank lines are
skipped and counted. A last line with no line terminator may still be being
written, so it is left for a later run.

**TLS** always verifies. The server's certificate must chain to the system
trust store, or to the CA bundle you give with `--ca-file`, and must name the
host you typed; TLS 1.2 is the minimum. There is no option to turn any of
this off. A refused certificate sends nothing and moves no cursor. A send
over `tls://` needs Python 3.11 or later: on an older Python it refuses with
one line and sends nothing (`--dry-run` and `tcp://` still work). `alr check`
prints one warning when this Python is linked with an OpenSSL older than 3.0.

**Clear text.** `tcp://` carries records unencrypted. Unless the address the
connection actually reached is a loopback address, `alr syslog send` prints
one warning on standard error that records travel in clear text. It judges the
connected address, not the name you typed: even `localhost` warns if the
system resolves it elsewhere. Use `tls://` anywhere you do not control the
path.

**What "sent" means.** Syslog over TCP and TLS (RFC 6587, RFC 5425) has no
acknowledgement of its own, so no sender can promise that a receiver
processed a record. `alr syslog send` counts a record as sent, and moves its
cursor past it, only at a confirmed checkpoint: the moment every byte up to
the end of that record's frame is known to have left this machine for the
receiver. There are two kinds of checkpoint:

- **Acknowledged by the receiver's TCP.** Where the operating system reports
  a TCP socket's unacknowledged send-queue bytes (Linux `SIOCOUTQ`; for
  `tls://` the count is read from the TCP socket underneath, and the check is
  made on the socket at run time, never assumed), `alr` checks after each
  batch of at most 256 frames or 1 MiB, whichever comes first. The checkpoint
  is reached when that count drains to 0 within the send timeout.
- **A clean close.** At the end of the run, `alr` ends the stream (for
  `tls://`, TLS close_notify first, then the TCP write side) and waits,
  bounded by the send timeout, for the receiver to close the connection in
  turn. A clean close confirms every byte sent. Where the send queue cannot
  be read, this is the only checkpoint. The close is clean only if the
  receiver answers with its TLS close_notify, or with an orderly TCP end of
  stream; a reset, or any error, while `alr` waits for it is never a clean
  close, on every supported Python. `alr` reads that TCP end of stream on
  the TCP socket itself, because the TLS layer of some Python versions
  reports a reset as an ordinary end of stream. When the TLS layer meets the
  end of stream itself (behind TLS records still waiting to be read), `alr`
  proves it orderly from the TCP state and then the socket's pending error
  where the platform reports the TCP state (Linux), and elsewhere (Windows
  and macOS) only from OpenSSL's record that its read of the TCP socket
  returned the end of stream (OpenSSL 3.0 or newer). Where neither can prove
  an orderly end, the close is treated as not clean: the run fails and a
  re-run resends the records (duplicates, never a gap). A receiver that
  answers with its TLS close_notify always confirms.
- **Clean means after ours.** The close is clean only if the receiver
  closes after it has seen the end of `alr`'s stream. An end of stream
  from the receiver (a TCP EOF, or TLS close_notify) that is already there
  before `alr` ends its own confirms nothing: `alr` looks for one, without
  blocking, before each batch and just before it ends the stream. Where the
  send queue cannot be read, finding one fails the run with a nonzero
  status, and the cursor stays at the last confirmed checkpoint (the start,
  if there was none). That last look is what orders the two ends, for
  `tls://` as for `tcp://`: an end of stream that arrives after it, even
  one met while `alr`'s TLS close_notify is still being sent, is judged as
  an answer, by the rules above (a reset, or an end that cannot be proved
  orderly, still fails). Where the send queue can be read, the drain after
  the receiver's EOF decides, as above. A syslog receiver sends no data, so
  where the send queue cannot be read, the first byte of data `alr`
  receives from it, at any point in the run (TLS session tickets are not
  data), makes the close not clean and fails the run the same way.

If the connection is reset or times out, or a drain or the close fails, the
run stops with a nonzero status and the cursor stays at the last confirmed
checkpoint; the next run sends everything after it again. So there can be
duplicates (every record written after the last checkpoint is resent), but
`alr` never skips a record it could not confirm (what confirming cannot
cover is stated below). The run reports two counts, never one number: `sent N records to TARGET; written, unconfirmed: M`, on standard
output when the run succeeds (M is then 0) and on standard error when it
fails (the M records are the ones a re-run sends again). If the cursor itself
cannot be saved, the line says how many records a re-run sends again: every
record since the last saved cursor, sent ones included.

What remains: a receiver whose TCP acknowledged the bytes, or that read them,
and that then dies before processing them can still lose them. Only a
receiver-side acknowledgement protocol closes that, and syslog has none. So
delivery is at-least-once only for the failures `alr` can observe, and a
receiver that must not count a record twice should deduplicate on `alr_id`.
One race also remains where the send queue cannot be read: an end of
stream that reaches `alr` after its last look, just before it ends its own,
is taken as the answer, whether or not the receiver read that end. So a
receiver EOF that is already on its way, but has not arrived, at that look,
and one that a receiver sends just after it without having read `alr`'s
end, cannot be told from a clean close that answers it, and both confirm
the run. Under `tls://` the window runs from that look to the end of the
close_notify exchange; on a loaded Linux test host, with one record a run,
that took a median between 44 and 173 microseconds and at most 3.6
milliseconds (100 runs for each case, on Python 3.11 and 3.14, with and
without the TCP state; a `tls://` send needs Python 3.11 or later). Nothing on the socket can narrow it: only the receiver's own
close_notify proves an answer. Against a receiver in another process that
reads to the end of the stream and closes at once, with no close_notify of
its own, all 100 one-record runs confirmed in each of those cases, between
44 and 63 of them with its end met inside that exchange; when that receiver reset
the connection instead, all 100 failed.

**Resume.** A cursor per target (the target's URL, hashed) is kept in `syslog/`
in the OpenALR home (`$ALR_EMIT_HOME/syslog/`, default `~/.alr-emit/syslog/`).
For each file it holds the file's identity (device, inode, and a hash of its
first bytes), the byte offset just after the last line passed at a confirmed
checkpoint, and a hash of the bytes just before that offset (up to 4 KiB,
ending in the line terminator). It is replaced atomically and is never
followed through a symbolic link (a cursor that is one is refused). If a file
has shrunk or been replaced, or the bytes before the offset are no longer the
ones sent (a rewrite in place, even one that keeps the file's start), it is
sent again from the start, with a warning on standard error. Two runs to one
target do not overlap.

**`--dry-run`** prints the frames to standard output, from the start of each
file, and touches no cursor and no network.

## Installing into a harness: `alr install`

```
alr install <harness>            # shows a preview: each file it would change, as a diff
alr install <harness> --yes      # applies it, keeping <file>.alr-backup-<time> beside each file
alr uninstall <harness> --yes    # removes only the hooks the install added
alr uninstall <harness> --purge --yes   # ... and deletes that harness's records, no one else's
```

Without `--yes`, `alr install` and `alr uninstall` change nothing: the preview
opens with a heading line, for example `Install preview: alr install claude-code
would make these changes. Nothing is written until you run it with --yes.`
(`Uninstall preview: ...` for an uninstall), and ends `nothing changed; run
again with --yes to apply these changes`.

`--purge` deletes only the named harness's records from the shared record file (and the grades, cost
corrections, and tag events that name only those records' requests); every other harness's records stay,
byte for byte. Without `--yes` it previews: per file, how many documents it would delete and how many stay,
listing the first few. A line the purge cannot read (a repeated key, a number that is not finite, nested too
deeply, not valid UTF-8, text that is not valid Unicode, not JSON, not a JSON object) is never deleted, since
that line might be another harness's record: it stays byte for byte, and the purge names it
(`<file>:<line>: kept, <reason>; alr check lists it`). A line the purge can read but `alr check` judges
schema-invalid (a grade without its `grader`, say) is judged like any other line. A grade, cost correction, or
tag event goes only when its owner is proven to be the purged records alone: in a file that holds a line the
purge cannot read, one that no readable kept record owns stays, since its owner might be that line, and the
purge names it once (`<file>:<line>: kept, owner unknown (a line here could not be read)`).
The file (and its lock) is removed only when nothing but blank
lines would be left. A record file reached through a symlink is purged where it really lives: the link stays a
link, and when the last records go, the target file and its lock are removed and the link is left dangling. OpenALR
refuses to append through a dangling link and creates nothing where it points: create the target file, or remove the
link, before OpenALR writes there again. A purge keeps its time in the state directory
(`purges.json`, by record file and harness), and `alr-emit-grok-tui` never writes again, from a hook or a
`backfill`, a record of a Grok Build turn that ended at or before it; the `--purge` reply for Grok Build says so.

Every hook the installer adds runs `alr hook <harness> ...`, which hands the event to that harness's emitter.
`alr uninstall` removes exactly the hooks whose command starts with `alr hook` and leaves every other hook alone.
`--home DIR` points the whole thing at another home directory, which is useful for a trial. Records are never touched
without `--purge`. The one-page walkthrough is on the OpenALR site,
[https://openalr.org/](https://openalr.org/).

| harness | what `alr install` does |
|---|---|
| `claude-code` | adds the `Stop`, `SubagentStop`, and `SessionEnd` hooks (emit) and the `UserPromptExpansion` (matcher `alr-tag\|alr-ctl\|alr-turns\|alr-grade\|alr-help\|alr`) and `UserPromptSubmit` hooks (commands and turn start) to `~/.claude/settings.json`; adds `~/.claude/commands/alr-tag.md`, `alr-ctl.md`, `alr-turns.md`, `alr-grade.md`, `alr-help.md`, `alr.md`, `alr-plan.md` ([`/alr-plan`](#alr-plan)), and `alr-prices.md` ([`/alr-prices`](#alr-prices)) |
| `grok` | adds its own hook file `~/.grok/hooks/alr-emit.json` (`Stop`, `SessionEnd`, `UserPromptSubmit`, `SubagentStart`, `SubagentStop`) and the [`/alr-plan`](#alr-plan) and [`/alr-prices`](#alr-prices) skills `~/.grok/skills/alr-plan/SKILL.md` and `~/.grok/skills/alr-prices/SKILL.md`; `config.toml` is never edited |
| `claude-sdk` | writes nothing; prints the call to add after each request |
| `hermes` | copies the plugin to Hermes's own home: `~/.hermes/plugins/alr-emit/`, on Windows `%LOCALAPPDATA%\hermes\plugins\alr-emit\`, and the [`/alr-plan`](#alr-plan) and [`/alr-prices`](#alr-prices) skills to `skills/alr-plan/SKILL.md` and `skills/alr-prices/SKILL.md` in the same home; then runs the rest of the install itself: `hermes plugins enable alr-emit` (Hermes's own package manager installs alr-emit into Hermes's Python), restarts a running gateway, and proves the load. With a wheel (`--wheel`, the copy a former install kept, or the one OpenALR was installed from) it keeps the wheel and hands Hermes that folder as the only package source; with none (OpenALR installed from PyPI: `uv tool install alr-emit`) it keeps nothing and Hermes's package manager installs `alr-emit==<this version>` from PyPI, and the preview says so |

A file the installer adds whole is written only where no file of that name exists, and `alr uninstall` removes it,
and any directory it created for it, only while it is unchanged. The installer always writes under `--home`
(default: your home directory); if `GROK_HOME` or `HERMES_HOME` points elsewhere, the preview says so. For a Hermes kept
outside its default home (`~/.hermes`; on Windows `%LOCALAPPDATA%\hermes`), name it: `alr install hermes --hermes-home DIR` copies the plugin to `DIR/plugins/alr-emit` (the
directory must exist; the kit never reads `HERMES_HOME` to decide), and `alr uninstall hermes --hermes-home DIR` removes it.
The Hermes uninstall runs `hermes plugins disable alr-emit`, removes the plugin's `__pycache__` and then the
emptied plugin folder, takes `alr-emit` out of `plugins.disabled` in Hermes's `config.yaml` (Hermes has no verb for
it, so this is an edit the preview names, with a copy kept beside the file), and restarts a running gateway. After it,
`alr check` says nothing about Hermes: it reports on Hermes only while the plugin folder holds the plugin or OpenALR's
kit state records an install there, and reads Hermes's `errors.log` only from the offset the last successful install
recorded.

## Library use

```python
from alr_emit import JsonlSink, build_record

record = build_record(
    request_id="…", agent_id="my-agent", outcome="ok",
    finished_at="2026-01-06T12:00:00+00:00",
    tokens={"input": 900, "output": 210},
    cost_usd=None, pricing_source="unknown",
)
JsonlSink()(record)
```

`build_record` exposes exactly the public `alr/0.1` field set — there
is no pass-through parameter, so nothing the schema doesn't name can
enter a record. `build_grade` / `build_cost_correction` produce the
append-only amendment events (pass `alr_id` to a cost correction to name
the one record it corrects, and `cost_basis` when the corrected figure's
basis differs from that record's), and `validate_record` /
`validate_grade` / `validate_cost_correction` / `validate_tag_event` are stdlib-only
`(ok, reason)` validators mirroring the frozen JSON Schemas.
`alr_emit.validate.readable_record` is what the viewer reads by: it refuses
what `validate_record` refuses except a `cost_share_usd` on a record that is
not `cost_in_parent`, which the spec tells a consumer to ignore and report,
and two tags with one reserved key, which make that key ambiguous for the
record (reported, and allocated to neither value).

## Known limitations

Each of these is a documented gap, not a silent one:

- **How `/alr-tag` reaches a hook, per harness.** Claude Code delivers the
  registered `/alr-tag` command as a `UserPromptExpansion` (as of 2.1.296),
  and Grok Build delivers it as a `UserPromptSubmit` prompt, with a leading
  space when the prompt was pasted (a typed one has none), and honors the hook's
  block decision.
- **Tags apply going forward only.** A tag set mid-session stamps the
  turns STARTED after it; records already written are never rewritten.
  This holds under Grok Build interactive's one-`Stop`-late
  emission too: the turn just before an `/alr-tag` keeps the tags it
  started with. Headless Grok Build and the Anthropic SDK tag at emission.
- **Command limits**: the Hermes
  command handler is given no session id, so a command binds to the
  latest root session that started a turn in that gateway process (two
  concurrent sessions in one process can cross); records do not stamp `task_class`; the
  `alr-session/0.1` outbox (`changes.jsonl`) is written but nothing in this
  release sends it.
- **Cost only at session exit (Claude Code without `alr otel-sink`).**
  This applies only when the sink is not running: with `alr otel-sink`
  running, each turn's record carries its own cost figure at turn end
  (`cost_share_usd`, from the harness's telemetry). Without it, the harness writes its
  cost snapshot only when a session exits or resumes, so a turn record
  carries tokens but no cost, and the session record carries the cost
  once that snapshot exists; until then a viewer must estimate a turn's
  cost from its own price list. A session that crashes and is never
  resumed has no `cost-state` line: no session record, and its turn
  records stand with null cost.
- **A killed Claude Code process loses its cost (without `alr otel-sink`).**
  With the sink running, each turn's record already carries its own cost
  figure from turn end, and a turn the session's later figure leaves out keeps
  that figure as its own (`parent_inclusion: "separate"`). Without
  the sink, a process killed
  before it exits (`kill -9`, a closed terminal) writes no `cost-state`
  line, and the figure a later resumed process reports does not include
  it. The emitter tells this from each `cost-state` line's `startTime`
  (the process that wrote it): a turn that every later `cost-state` line
  postdates is outside the reported figure. The session record is then
  `cost_is_partial: true`, the figure is shared only over the turns of the
  processes it covers, and each turn before the kill is restated
  `parent_inclusion: "separate"` with a null cost (`alr` shows its own
  estimate in the `est.` column) and
  `claude_code_cost.problems: [{"problem": "process_ended_without_cost_report"}]`.
  A resume that runs no turn and reports 0 writes no session record: a
  null-cost session record is never written.
- **`alr check` probes only the default sink settings file.** It tests the
  sink from the default `<state>/otel/otel.env` only, in text output only
  (not under `--json`). It never probes a file written elsewhere with
  `alr otel-env --file`. With `--home DIR` it probes the default file of
  that home's state directory, never your own; with `--hermes-home DIR`
  and no `--home` it does not probe, and says so in one `otel-sink: not
  probed` line (a Hermes directory holds no sink settings file), and a
  check of named FILES with no home named does not probe.
- **An answered background-task notice turn may be skipped as a "finished
  turn" (Claude Code).** Its record exists and `alr turns` lists it, but
  `/alr-turns` may omit it, and so may `/alr-grade` (which then grades the
  turn before it), `alr grade last` and `alr tag last` (which take the turn
  before it); `/alr-grade <g> turn <N>` may refuse it as unknown. Give its
  request id to `alr grade <request-id> <grade>` to grade it directly;
  `alr turns <session> --json` shows each turn's `request_id`.
- **Hermes: `/alr-turns` may show a subagent's row in place of turn 1.** A
  `delegate_task` subagent's record carries the root session's id and its own
  turn number, counted within the subagent and starting at 1, and `/alr-turns`
  lists records by that number, so the subagent's model, tokens, and cost may
  appear on the row for turn 1. The records and `alr turns` are correct.
- **A Claude Code session a pre-release build started may number its
  later turns out of order.** Start a new session after you install 0.1.0.
- **Claude Code auxiliary calls.** Side calls Claude
  Code makes outside the conversation (titling, summaries, other
  side-model calls) are not proven to reach the session or subagent
  transcripts this adapter reads, so their tokens may be missing. Two
  `claude -p` sessions on 2.1.296 do not settle it: in both, `modelUsage` lists one
  model whose token totals equal the session and subagent transcripts'
  summed assistant usage, so nothing the harness counted was missing from
  the transcripts there, but no side call is visible either way.
- **`claude -p` tokens leave out subagents** (2.1.296, observed). The
  result object's top-level `usage` is the parent conversation's tokens
  only; `modelUsage` and `total_cost_usd` include the subagents. A
  `claude -p` record therefore carries the whole session's cost with the
  parent's tokens; the transcript records (session plus one per
  subagent) carry every token.
- **Grok Build auxiliary calls (headless)** (1.0.41, 1.0.50). Grok Build excludes compaction
  and side-model calls from the result JSON's `usage`, so a Grok Build record
  does not carry their tokens.
- **Grok Build subagents (headless): not applicable to a managed install.**
  The headless adapter is proven on 1.0.50 results for two models, all run
  with `--no-subagents` (one `modelUsage` row each). The one run with
  subagents enabled did not spawn one: its `spawn_subagent` call was denied
  under the `dontAsk` permission mode ("tool not pre-approved"). Grok Build
  1.0.50 documents no permission rule that pre-approves that tool alone (only
  a bare `*`, `auto`, or bypass would, each loosening every tool), so no
  managed install of Grok Build can produce a subagent result. That `usage`
  includes finished subagents is therefore Grok Build's documented behavior,
  not an observed one.
- **Grok Build interactive: a per-turn `Stop` runs just before its turn is
  written.** `Stop` can fire about 20 ms before the turn reaches
  `usage.json`, so each `Stop` emits the turns up to the previous
  one. The shutdown `Stop`, `SessionEnd`, or a `backfill` emits the rest.
  If Grok Build is killed before exit, run `alr-emit-grok-tui backfill`: it
  writes only the sessions whose journaled turns have no record, and it
  is idempotent.
- **Grok Build interactive: a turn's identity assumes Grok Build's `turnNumber` does
  not repeat within one session id.** In the single uninterrupted sessions
  OpenALR was tested on,
  `usage.json` numbers `turns[]` 1, 2, 3, ... with no repeat, blocked
  prompts included, `session.turnCount` equals the number of entries, and
  `summary.json` keeps `next_trace_turn` on disk. None of those sessions shows
  a resumed session, a compaction, or a `/clear` that keeps the id (the one
  `SessionStart` payload tested had `source` `new`; a
  fork takes a new id, see below), and `events.jsonl`'s own `turn_number` does repeat (it
  does not count blocked attempts). So a repeat is not ruled out: a turn
  whose number the record file already holds with another end instant is
  taken as a different turn and given `<session id>:t<NNNN>~<end, UTC>`.
- **Grok Build interactive requires Grok Build 1.0.53 or later.** Before
  1.0.53, two windows writing one session could lose turns in Grok Build's own
  usage file (`usage.json`), and a turn Grok Build never wrote there cannot be
  recorded.
- **Grok Build interactive: a fork records only its own turns.** A forked Grok Build
  session (`/fork` or `--fork-session`) gets a new session id, and Grok Build
  copies the parent's turns into the fork's usage file (`usage.json`). The
  fork's `summary.json` names its parent (`parent_session_id`) and when it
  was made (`forked_at`). A fork's turn that ended at or before `forked_at`
  is the parent's and is never recorded again; an exact match of its end
  time and cost with the parent's own turn confirms it. If that link is
  missing or malformed, or the parent's usage file cannot be read, no turn
  from before the fork is recorded and the problem is noted on stderr and
  on the fork's turns (`x_grok_pairing`, which `/alr-turns` shows); with no
  usable `forked_at` nothing of the fork is recorded. With a link or
  without one, a turn that ended at or before the session's first
  `turn_started` in `events.jsonl` is never recorded as the session's own:
  a turn ends after it starts, and a fork's `events.jsonl` begins at the
  fork's own first turn. So a fork whose `summary.json` is not written
  yet, or has no link, records only its own turns: the copied ones are
  held, not recorded, and every run notes what was held and why ("no fork
  link in summary.json yet") on stderr and where `/alr-turns` shows it
  (a subagent's held turn is shown on the turn that spawned it). They
  stay held if the link never appears, and stay unrecorded when it does.
  The fork's own records written before the link appeared are not
  rewritten when it does: they can keep their superseded note in
  `/alr-turns` (what was held and why), while every figure on them is correct. A turn that
  ends at the very instant the first turn starts is held too (a visible
  under-count, never a silent double count). A session whose
  `events.jsonl` is missing, unreadable, or holds no usable `turn_started`
  records nothing until it has one, unless its fork link is confirmed
  against a readable parent. This rests on Grok Build's own `events.jsonl`: one
  whose first `turn_started` is dated too early would let a copy through
  when there is no link.
- **Grok Build interactive: `/rewind` (or `/undo`) keeps the rewound turn.** In
  Grok Build 1.0.70 a rewind appends: the rewound turn stays in Grok Build's
  usage file (`usage.json`) with its cost, and the new turn is added after
  it, so both are recorded (both were spent) and nothing is lost. Caution:
  a Grok Build version whose rewind removes turns from `usage.json` has not been
  observed; on one, a turn removed before it was recorded would be lost.
- **Grok Build interactive: after `/rewind` (or `/undo`), `events.jsonl` reuses
  the turn number.** In 1.0.70 the new turn's `turn_number` repeats the
  rewound one's (`usage.json`'s `turnNumber` does not repeat). OpenALR
  pairs a turn with its span by when it ended, never by `turn_number`, so
  no recorded turn is counted twice; should Grok Build's `turnNumber` ever repeat,
  the later turn's id carries its end time.
- **Grok Build interactive: a turn whose end time moves is counted twice.** A
  turn whose recorded end time later moves by more than one second is
  recorded as a second turn. No case is known (Grok Build has not been seen to
  change a turn's end time once written); this is noted for completeness.
- **Grok Build interactive: `/alr-ctl status` counts the journal.** Its "last
  turn N emitted, M open" is in the tag hook's own journal numbering, not
  the records' `turn_index` or ids, and after a lost session state it counts
  only the journal begun since. Display only: no id or total depends on it.
- **Grok Build interactive: a hand-merged record file.** The emitter never writes a
  session's turns in two numberings. A record in no stated space or in
  `grok-turn-number` comes only from a pre-release build (see "If you
  installed a pre-release build" above).
  If a file merged by hand holds one such record of a session beside that
  session's `eager` ones, recorded turns keep their ids and indices (they are
  matched by Grok Build's turn number and end), but that one record puts the
  session's turns not yet recorded on Grok Build's numbers: their
  `turn_index` is Grok Build's `turnNumber`.
- **Grok Build interactive: no `harness_version`.** The session files do not
  carry the CLI version; pass `--harness-version` (or set
  `ALR_EMIT_HARNESS_VERSION`) or it is omitted.
- **Grok Build interactive: subagents are detail.** Their records are
  `included_in_parent`: the parent's `usage.json` already includes the
  child's calls, so the child's own tokens and cost are never added to a
  total. A subagent that had not completed when it was read is marked
  `cost_is_partial`. `cacheCreationTokens` was 0 in every session OpenALR
  was tested on, and it is not subtracted from `input`.
- **Grok Build cost-zero and incomplete-usage paths.** No Grok Build run
  OpenALR was tested on has reported `total_cost_usd: 0.0`, `cost_is_partial`, or
  `usage_is_incomplete` (API-key runs always report a positive figure), so
  those three paths are tested only on synthetic inputs.
- **Hermes cost.** Hermes hook usage carries no cost, so Hermes records
  are `cost_usd: null`, `pricing_source: "unknown"` unless a cost is
  passed in.
- **Hermes streamed and failed auxiliary attempts.** An auxiliary
  attempt that is handed back as a stream (MoA) or that raises reaches
  `post_auxiliary_call` with no usage, so its tokens are not recorded.
- **Hermes subagent links live in memory.** A child that starts before
  a gateway restart, or whose `subagent_start` carries no child session
  id, is recorded under its own session, unlinked.
- **Hermes late tool events.** A `post_tool_call` for a turn whose
  record was already emitted is dropped, so that call is missing from
  `tool_call_count` (never double-counted).
- **Hermes long turns.** A turn idle for longer than the TTL is flushed
  and, if it resumes, continues in a second record: split, never
  double-counted. A process killed without exit handlers loses its
  open turns.
- **SDK fallback iterations.** Whether the top-level counters include
  `fallback_message` iterations is not settled (no recorded response
  carries one), so their tokens are carried only in
  `anthropic_usage.iterations`, not in `tokens`; their models are listed
  in `models`. `advisor_message` iterations are settled: a recorded
  response shows the top-level counters exclude them, so their tokens
  are added to `tokens`, like `compaction`.
- **SDK per-request charges.** `server_tool_use` counts (web search and
  fetch requests) are carried as counts; no cost is derived from them.
- **SDK `fallback_credit`** (beta) is not mapped.
- **`alr journal` does not generate adjusting entries.** It reports a correction made after a period you exported; post the difference in the open period by hand.
- **The QuickBooks Online profile:** the line's dimensions are text in `Journal/Description`; the date format and the separator are assumptions. Test-import a small file first.
- **`alr syslog send` is at-least-once** for the failures it can observe: a receiver that must not count twice should deduplicate on `alr_id`.
- `alr summary --by tag` (and the dashboard's Tag view) does not mark a tag row as a lower bound when the row holds a partial turn share (`cost_is_partial`); the reserved-key views and `alr ev` do.
- `alr prices update` fetches https://prices.openalr.org/prices/v2/latest.json.gz (and its .sig); until that address serves a signed book, the update reports that it cannot fetch, stores nothing, and OpenALR keeps using the book in use (the bundled book, unless a newer book was stored by `alr prices update` or `alr prices import`).
- Every estimate from a price-book entry with a higher rate above a prompt-token threshold (`higher_tier_above_prompt_tokens`), or from an entry that does not say whether it has one, is marked a lower bound: the price book has no field for the higher rate, and a record does not say how large each request's prompt was.
- A session whose turns state no share (or that has no turn records) still books whole under the session's own value, its last task, in `--by task`, `alr ev`, and the dashboard.
- Claude Code's turn shares are allocations of the session's cost (price-weighted, or token-weighted when a turn has no price), not each turn's own figure (a turn's own figure needs `alr otel-sink`); the figures say so.
- A Claude Code turn's tokens of other models are priced at the turn's primary model when its share is weighted, as the estimate does.
- A turn share whose `cost_basis` differs from its session's moves nothing; the session keeps it.
- OpenALR splits a task's AC by turn shares, while the published SPEC section 9.3 item 3 reads a task's AC per record: for a session that worked on several tasks, another consumer that follows the SPEC can report a different AC per task than `alr ev`.
- On the dashboard's Worth It rows, a leverage over an AC of 0 that is only a lower bound reads "n/a (no spend yet)", not that the spend is not known.
- `alr plan new` and `alr accept` print the record file's path on one line as it was given: a relative `--file` stays relative, and a long path makes a long line.
- In Claude Code, an `/alr-*` command is shown with Claude Code's own label `UserPromptSubmit operation blocked by hook` beside OpenALR's answer. The OpenALR hook blocks the prompt on purpose, so the command takes no model turn and writes no turn record; the label is not an error.
- **`alr syslog send` over TLS needs Python 3.11 or later, and may not certify a clean close on a Python linked to OpenSSL older than 3.0.** On Python 3.10 a `tls://` send refuses with one line and sends nothing, whatever OpenSSL it is linked with. A Python 3.11 or later linked to an OpenSSL older than 3.0 still sends, and `alr check` prints one warning for it. On such a Python, when a receiver closes at once without its own close_notify, the end of the stream cannot be told from a reset there, so some good runs fail as "did not close the connection cleanly". Nothing is lost: the cursor stays and a re-run sends the records again. To check your Python, run `python -c "import ssl; print(ssl.OPENSSL_VERSION)"`.
- The dashboard's Overview projects table marks no lower bound: a project whose cost holds a partial turn share or a record with a partial cost is shown without the '+' that `alr summary` and `alr ev` give it.
- Table cell rules and the open filter picker's frame are light decorative lines (about 1.3:1 against the page in the light scheme, 1.5:1 in the dark one). Every control keeps its own native boundary; the lines were left as they are so the dashboard keeps its look.
- When a panel scrolls sideways, the focus ring of a control at the panel's left or top edge can be partly cut off by the panel's edge; the ring stays visible on its other sides.
- The dashboard uses the browser's own page and text colors (light and dark follow the system setting until the reader picks one with the sun/moon button). Contrast was checked against the default colors of Chromium, Firefox, and Safari; Windows high-contrast (forced colors) mode and user style sheets were not checked.
- The dashboard was checked by reading its source and by automated tests; it has not yet been checked with a screen reader.
- `alr dashboard` has no `--as-of`: its Earned Value screen is always as of the build's clock.
- The plan template's `PROJECT:` placeholder in task names is accepted as it is, with no warning.
- The demo kit's step 12 refuses a second plan with different dates on a later day (`alr plan new` is a no-op only for the same content). Reset the demo to show it again.
- The dashboard groups thousands in counts (1,322,992) but not in money (1200.00), while `alr ev` text does ($1,200.00).
- `/alr-plan` on Grok Build asks its closed questions (cost basis, another task, baseline method, a revised or dropped task's change, save, issue) as numbered questions: Grok Build documents no menu tool, so it offers no choices. Claude Code and Hermes offer them as choices where their menu tool is available (Hermes asks the cost basis as numbered text, so that no choice is marked recommended), and fall back to numbered questions otherwise.
- In a CSV plan every task states a baseline: a task with no role row is `human_baseline: []` (no human effort of its own) and needs a `baseline_method` and a `baseline_note`. A task whose baseline is not stated is written as JSON or TOML.
- A CSV file that is not valid UTF-8, or that has a quote CSV cannot read, is refused naming its line but not its column.
- `alr plan` on its own saves the plan as JSON only (a name ending in `.json`).
- The record file may still be reached through a configured symlink (a supported setup: the lock is named from the real path). The append opens the resolved real path with no-follow, so a link swapped in at the final real path is refused, but the configured link itself is followed by design.
- On Windows, POSIX modes do not apply; a link already at a journal path is refused before the open, but one placed between that check and the open is followed.
- A live symlink target is resolved once before its temporary file is written, so a link retargeted in that window writes the old target.
- It is not yet proven against a real Hermes that its installer honors `UV_NO_INDEX` and `PIP_NO_INDEX`.
- The PyPI path is not yet proven against a real Hermes: with no wheel at hand, that Hermes's package manager installs the pinned `alr-emit==<this version>` from PyPI.
- After `alr uninstall --purge` removes the last records behind a configured symlink, the link is left dangling and OpenALR refuses to write through it; recreate the target file (or remove the link) before OpenALR writes there again.
- Someone who can write the prices folder can still delete stored books. That only falls back to the bundled book.
- A non-ASCII session id (none of the supported harnesses sends one) gets no session tags or session state.
- alr-emit ships the spec files from OpenALR spec commit 09dee8b (named in spec/PROVENANCE.json).
- Two `work_type:` values on one record (written by another producer) are ambiguous in `alr summary` and the dashboard, but the journal posts the record normally, since `work_type` is not a journal column.
- The `task:` check reads the record file on each `/alr-tag` change that adds a task, so a very large record file makes that command slower. A task is not judged without a `project:` tag or an issued plan for the project. A warning or refusal names the key but not the value, so a change that adds several tags of one key does not say which one failed.
- `validate_session_event` is reached as `alr_emit.validate.validate_session_event`; it is not exported from the `alr_emit` package top level and is not among the documented library functions. The spec's reference validator does not check the two plan rules (the spec states them in text only); OpenALR's own plan validator does.
- `alr prices reset` leaves a temporary `*.tmp` file that an interrupted `update` or `import` may have left in the price-book directory; delete it by hand.
- The `alr-prices/0.3` reader checks each metadata key on its own entry only; the rules across a model's entries (the same `added` on every entry, `confirmed` only on the newest) are left to the book's generator.
- The `alr-prices/0.3` reader accepts an explicit null on any of the five entry keys, an empty `redirects_to` (read as no redirect), and a `note` of any length, as the specification allows a reader to; OpenALR never writes such a book itself.
- The dashboard does not display the `alr-prices/0.3` metadata yet.
- `redirects_to` is informational only: an alias with no entry of its own for a date has no rate then, even when its target has one.
- OpenALR makes no edition-to-edition comparison of price books: keeping past periods' rates unchanged between editions is the generator's rule, not checked by the reader.
- The sink token stays under the state directory: `$ALR_EMIT_HOME/state/otel/sink.token` when `ALR_EMIT_HOME` is set, else `$XDG_STATE_HOME/openalr/otel/sink.token`.
- The QuickBooks Online Name and duplicate-number wording follows Intuit's pages as they were read when this profile was written; which entries the duplicate check blocks ("those whose journal numbers already exist") was not checked against them again before this release.
- The top-level `alr --help` is wider than 80 columns. At 80 columns it wraps the longer command summaries onto a second or third line, but its two lines that list the commands are each over 150 characters long and are not wrapped, so they run past the edge of an 80-column terminal.
- On Python 3.10, a `record_file_mode` written as a number that is not a TOML integer (such as `640.0` or `inf`) makes the whole user config unreadable, with a message that it must be "0600" or "0640" written in quotes; Python 3.11 and later read the file and refuse only that key. Record files stay 0600 either way.
- `ALR_EMIT_SINK` (a record file path) still overrides `log_dir`, even when `[routing]` sets `log_dir = "disable"`; with it set the record file is never resolved, so no route notice is printed, even for a routed `transmit` or `destination`.
- The worktree check reads git's own files (`.git`, `commondir`, `worktrees/*/gitdir`) at each load and never runs git; a worktree git does not list there is not seen. A routed `log_dir` is checked and applied as its resolved path at load, so a link changed after the load is not followed; it is checked again at the next load.
- The emitters' once-per-session note is keyed by the parent process id. On Windows, and on POSIX when the hook's shell does not exec the command, the note may repeat every turn; the marker files under `<state>/notes` are never pruned; and a reused process id can suppress a later session's note.
- On Python 3.10 the built-in TOML reader does not read literal-quoted (`'key'`) or dotted (`a.b`) keys. A project file using either is set aside whole as unreadable (nothing applies), while on 3.11 and later such keys are refused one by one.
- A repository's `.alr-tags` file is filtered to project-scoped tags but is not covered by `alr trust`: it is read under `repo_settings = "ask"` without a trust record, and `"off"` skips it.
- `plan_file` is the default `--from` of `alr plan` and the file the plan interview offers; `alr plan show`, `alr ev`, and `/alr-plan` do not read it yet.
- `record_file_mode` has no effect on Windows.
- `/alr-prices` is not on the `/alr-help` screen.
- For a local rate, the save is bound to its preview only through `/alr-prices` (`--interview --confirm`); a plain add binds to nothing.
- The local rates file is always 0600; its directory is made 0700 only when OpenALR creates it, and an existing directory keeps its mode.
- A local rate is a read-time figure only: no record is written with `pricing_source` `computed`.
- One organization price-book key at a time: OpenALR trusts at most two keys, the built-in one included. With two or more organization keys configured, none of them is trusted until the list is cut to one.
- `alr prices update`'s 60-second deadline (`FETCH_DEADLINE_S`) can be passed in one case: the host-name lookup has no time limit (Python gives it none), so a slow lookup can run past `FETCH_DEADLINE_S`; the fetch is refused as soon as the lookup returns, and nothing is stored. A host with several addresses does not pass it: each connect attempt gets the 20-second timeout (`TIMEOUT_S`) or the time left as it starts, whichever is less.
- On Python 3.10 a multi-line `price_book_keys` array is not read: the whole user config fails to load. Write it on one line.
- Nothing in this release transmits by `transmit` and `destination`: a routed `transmit` or `destination` is recorded and shown only; the notice "records go to `<destination>`" names the configured route.
- The Hermes plugin resolves its record file once, when it loads, from the gateway's working directory, so its route notice is once per gateway process.
- `allow_log_dirs` is matched case-sensitively against the resolved path; on a case-folding file system a pattern spelled in another case does not match (it fails closed). An IPv6 destination matches only the identical spelling.
- A comment that is exactly `t <N>` or `-t <N>` (one whole number) cannot be written with `/alr-grade`; it is read as a turn number. `alr grade --comment` can still write it.
- A turn's first words are not kept: no record or local state holds a turn's prompt or reply text, so the `/alr-grade` listing keys each turn by its time, task tag, and cost instead.
- `alr check`'s summary line for a project file's refusals says "(a repository may not set these)" for any refusal, including a project fact refused only in part (for example a `default_tags` tag outside `project:`, `task:`, `client:`, and `cost_center:`).
- There is no automated accessibility scan in CI; the dashboard's checks are source-level contrast, keyboard, and label tests.
- An issued plan carries no project name (the spec has no such field); `alr summary`, the dashboard, and the `/alr-tag` picker take names only from the user config's `[projects]` table.
- On Python 3.10 a dotted `[projects]` code (`acme.web = ...`) or one in single quotes is not read: that entry is skipped and its line named. Write such a code in double quotes (`"acme.web" = ...`) to read it there.
- `alr otel-env` writes the sink's default address (`localhost`, port 4318); a sink started with `--port` or another `--host` needs the endpoint edited by hand.
- On Windows, the sink's token file and otel.env are protected only by your user profile's default access controls: OpenALR sets private permissions and checks the file's owner on macOS and Linux only. `alr otel-env` writes `export` lines for a POSIX shell; there is no PowerShell form.
- `alr otel-sink` listens on IPv4 only: `alr otel-sink --host ::1` fails to start.
- `alr otel-env --file FILE` does not check FILE's parent directories for links: that is a path you name.
- The sink `alr otel start` runs does not start again after a reboot, on Windows, macOS, or Linux: run `alr otel start` again.
- A running `claude` keeps the telemetry settings it started with until it is restarted.
- Managed settings win over the settings `alr otel start` writes.
- `alr otel status` does not detect a macOS MDM profile (`com.anthropic.claudecode`), and a `remote-settings.json` is only a hint of server-managed settings.
- With `CLAUDE_CONFIG_DIR` set, `alr otel` uses `$CLAUDE_CONFIG_DIR/settings.json`, but `alr install claude-code` still writes its hooks under `<home>/.claude`, which Claude Code does not read then.
- `alr otel start` rewrites Claude Code's settings file with two-space indentation (keys and their order kept; a byte order mark and CRLF line ends are not), and refuses a file with a duplicate key.
- **A move can outrank later plain tags.** This happens only when a tag event is dated later than now (a clock set back, or a future-dated record) and that event gave the old tag or names the new one. `alr tag --move` then dates its own line for that tag just after that event. Until the clock passes that time, a plain `alr tag` on those turns, stamped now, loses to that line. If the event gave the old tag, the move's remove of the old tag is so dated, so a later plain add of the old tag loses. On a one-value key (`task:`, `effort:`) the move's add of the new tag is so dated too, since that event's add would otherwise take the new tag off again. If the event names the new tag (an add or a remove of it, on any key), the move's add of the new tag is so dated. While the add of the new tag is so dated, a later plain `--remove` of the new tag on those turns loses, and the turns keep the new tag. On a one-value key, EVERY later plain tag of that key on those turns loses: an add of any value (the old one included) and a `--remove` of the new tag. On a many-value key (`phase:`), a later plain add of another value still wins, and so does a later plain tag of the new tag when no event dated later than now names it. Nothing is refused.

## Maintainer tools

The tools for working on alr-emit itself (the live harness test, the
generator of the docs site's reference pages, and the release checks) are
not part of the installed package. They are described in `tools/README.md`
in the source distribution (the sdist, `alr_emit-<version>.tar.gz` on PyPI).

## License

Apache-2.0.
