# Feature: Operational Reporting

<!-- toc -->
- [1. What is sent, and what never is](#1-what-is-sent-and-what-never-is)
- [2. When it is sent](#2-when-it-is-sent)
- [3. The reporting identity](#3-the-reporting-identity)
- [4. The server side](#4-the-server-side)
- [5. The token](#5-the-token)
- [6. Opting out, and the two silences](#6-opting-out-and-the-two-silences)
- [6b. Feedback is not telemetry](#6b-feedback-is-not-telemetry)
- [6c. The access check](#6c-the-access-check)
- [7. The half-configured case](#7-the-half-configured-case)
- [8. Where it is NOT called](#8-where-it-is-not-called)
- [9. Local skill usage is not reporting](#9-local-skill-usage-is-not-reporting)
- [10. Local MCP failures and calls are not reporting](#10-local-mcp-failures-and-calls-are-not-reporting)
- [11. The local logs and their previous generation](#11-the-local-logs-and-their-previous-generation)
- [12. Which commands are typed](#12-which-commands-are-typed)
<!-- /toc -->

Reporting needs three things: `usageLog.enabled` true, a token that resolves,
and a GitHub account on this machine that can read the pipeline repository. The token
is arranged by one call (`$HOME/.claude/scripts/usage-register.mjs`) made from
the three places a machine can first become real: **setup**, **update**, and
**the Phase 0 exit gate** of a run on a machine that reached neither. Asserted by
`smoke-usage-register.sh`.

## 1. What is sent, and what never is

`usage-report.mjs` emits coarse run metadata, one record per run, upserted by
run id. Never prompts, never code, never diffs, never token values, never
absolute paths, never the repository name (a keyed digest stands in for it).
The one hook that sees a typed prompt (`note-command-use.sh`, section 12) keeps
only the name of a shipped `/multi-agent` command, or the constant `other`:
no argument, no text, no length.

**The rule behind the table.** Every field of the record is one of four things:
a number or a boolean; a value from a closed list shipped in the code
(`lib/usage-vocab.mjs` and the data files named below); a keyed digest; or an
explicitly opt-in field that is reduced to a summary or to a known host (`ti`, `pru`). Whatever a state file,
the preferences or a machine configuration hold, a value that is not on its
list is dropped or replaced by a constant (`other`, `private`, `unknown`);
nothing is sent because it merely looked harmless.

A closed list is built when the package is packed and travels inside it;
nothing found on the machine that runs the pipeline extends it. Command, skill
and tool names come from `lib/usage-names.generated.mjs`, which
`scripts/gen-usage-names.mjs` writes (from `prepack`) from the package's own
git-tracked trees (`commands/multi-agent`, `skills/shared/{core,external}` and
the tool list of this product's MCP server in `schemas/toolkit-path-params.json`;
a directory that exists only on a disk is not tracked) and which `npm test`
checks with `--check`; the public plugins come from the stack
routing table, the public MCP servers from `lib/public-mcp-servers.mjs`, the
credential names from `prefs.schema.json`, the models from `cost-table.json`,
the modes from `phases.json`. A routine saved on the machine, a local wrapper
command, an installed marketplace plugin or a registered server is on none of
them. `test/usage-body-closed.test.mjs` builds every body from a state full of
ticket keys, mail addresses, host names and private server, plugin, command and
key names (a routine with such a name exists on disk), and checks every field
against the same shipped lists the code uses, never a pattern. It does this for
the run record and for the lifecycle, registration, failure-beacon, access-check
and feedback bodies. The
registration call sends the reporting login and a label for the machine, plus the
signed challenge when the account was found by an SSH key (section 4).

Each record carries:

| Field | Meaning |
|-------|---------|
| `id` | the run key: `r` plus 16 hex characters, an HMAC-SHA256 of the run id (a ticket key in practice) under a per-install secret. The same machine and run always give the same value, so the events of one run join; the raw id never leaves the machine and stays in the local logs. The secret is 32 random bytes in `~/.claude/logs/multi-agent/usage-run-key`, created on first use (the directory 0700 when it is made, the file 0600 through an exclusive link, so two processes end with one value), never logged and never sent. A file that is not a regular file of this user's, that others can read, or that is short or damaged is replaced by a new key through a rename (a link at the name is swapped, never written through; a key others could read may have been seen, so it is never repaired in place). Replacing changes the id of runs in flight: their next event joins as a new run, once. A directory at the name cannot be replaced. A plain hash would be reversible by hashing every plausible ticket key, so there is no unkeyed form: when the secret cannot be read or created the send is skipped and `usage-last-send.json` records `skipped` with reason `run-key-unavailable`. `--dry-run` never reads, creates or repairs the file: it shows the shape of the record with a throwaway secret, so its `id` is not the id a real send carries. Upgrading from a version that sent the raw run id changes the id of every run: a run in flight at the upgrade joins as a new run, and its earlier events stay under the raw id. Creating or replacing the key happens under `usage-run-key.lock`, which holds a random token naming its holder: a holder removes the lock only while the token is still its own, and a lock older than 10 seconds is moved aside by exactly one waiter (a rename), so neither two waiters nor a slow holder can displace a live lock. |
| `u` | not part of a run or lifecycle record: the server names every record after the login pinned to the ingest token and ignores the body's, so none is sent. The login travels only where it is what the request is about: the registration (and its challenge), the failure beacon, and the access check (`login`) |
| `ap` / `lo` | booleans: the run was autopilot / local mode |
| `in` | where the run came from: `jira`, `github-issue` or `free-text` |
| `rp` | the repository, as `p` plus 16 hex characters: an HMAC-SHA256 of the project name under the install secret, with a domain label different from `id`'s, so the same name never gives the same digest as a run id. One repository on one machine always gives the same value (the panel can group a repository's runs); the name cannot be recovered by hashing candidate names without the secret. The digest changes once when a machine first sends the keyed form: runs sent before and after that point are not joined to each other |
| `ri` | the number of review iterations, a number |
| `tt` | task type, one of `component`, `bugfix`, `feature`, `refactor`, `chore` (the values `agent-state.schema.json` allows); anything else is left out |
| `ev` | the event that sent it: `phase`, `completed`, `halted`, `parked` |
| `st` | run status: `in_progress`, `completed`, `halted`, `parked`, `failed` |
| `ph` | current phase number, from the tracker (the phase in progress, else the last one reached) |
| `phs` | every tracker phase as exactly four keys, `{p, st, du, tk}`: `p` a phase number (a tracker entry whose id is not a number is left out), `st` one of `pending`, `in_progress`, `completed`, `done`, `failed`, `skipped` (any other status is `null`), `du` the duration in seconds (strict ISO timestamps or a millisecond count, at most 30 days, else `null`) and `tk` tokens, both numbers |
| `rc` / `hr` | a closed cause code, never text from the run: `<phase>:<cause>` for a halt (the cause alone when the reason names no phase), the waiting cause for a park. The cause is one of `circuit-breaker`, `retry-cap`, `stop-guard`, `research`, `reviewer-json`, `review-blocking`, `cancelled`, `disk-full`, `rate-limit`, `timeout`, `budget`, `auth`, `network`, `permission`, `conflict`, `not-found`, `dispatch`, `lock`, `verification`, `build`, `test`, `approval`, `maturity`, `channels`, `awaiting-input`, `validation`, `run-failed`, `unknown`, chosen by matching the reason against fixed patterns in that order; a reason that matches none is `unknown`. Ticket keys, hosts, addresses, remotes, mail addresses and every other identifier a free-text reason can carry are therefore not sent, whatever their shape. The full reason stays in the local errors ledger (`errors-ledger.jsonl`, field `reason`), which is where debugging reads it |
| `pr` | whether a PR was opened |
| `pru` | the PR URL, only when `usageLog.includePrUrl` is true (it names the repository), and only for `github.com`, `gitlab.com`, `bitbucket.org` and `dev.azure.com`: https, no port, reduced to host and path (credentials, query string and fragment dropped), and dropped when still over 200 characters. A pull request on any other host sends nothing; `pr` already says one exists |
| `ti` | only when `usageLog.includeTitle` is true (off by default): a summary of the task title, never the title. Free text cannot be scrubbed reliably, so none of it is sent. The first of the run state's title fields (`title`, the Jira summary, the issue title) is percent-decoded and normalised with NFKC (fullwidth and compatibility forms fold to plain ones) and reduced to `{w, k, l}`: `w` the number of words (at most 99), `k` whether it has the shape of a ticket key (letters then digits, with a hyphen, underscore, space or nothing between, or a `#number`), `l` the language by the shipped lists of common English and Turkish words and the Turkish letters (`en`, `tr` or `other`). That is everything the opt-in sends; no word of the title leaves the machine |
| `m`, `c` | mode and command. `m` is always one of the modes `schemas/phases.json` declares, or `unknown`. `c` is `/multi-agent:<name>` only when `<name>` is a command the package itself ships (the generated list built when the package is packed), otherwise the mode. A routine saved on the machine, a local wrapper or a command an older version shipped is not on the list |
| `t`, `t0`, `du` | time of this event, run start, run duration. `t` and `t0` are complete ISO 8601 timestamps between 2020 and 2100, written as UTC rounded down to the minute (a value of any other shape, such as `acme-4711` that a lenient parser would read as a year, is dropped: `t` then falls back to the send time, `t0` to the tracker's start). `du` is the difference of two such timestamps, at most 30 days, else `null` |
| `tk`, `cost`, `models` | token totals, estimated cost, models used. A model is named only when it is an id of `cost-table.json`; any other id is sent as `other` |
| `os`, `cli`, `lang`, `stack`, `plug`, `apps`, `creds`, `calls`, `errs`, `v` | environment and credential-health summary, each from a closed list. `os` one of `macos`, `linux`, `windows`, `other`; `cli` one of `claude`, `codex`, `copilot`; `lang` one of the two `outputLanguage` codes `en`, `tr`; `stack` only the stacks the pipeline knows (`KNOWN_STACKS`). `plug` names a plugin only when it is one of the public plugins of the stack routing table (`ai-common-toolkit`, `ai-analyst-toolkit` and one `ai-<stack>-toolkit` per known stack), else `private`; the plugins installed on the machine do not matter. `apps` names a remote only from a closed set (`github`, `gitlab`, `bitbucket`, `azure`, `azure-devops`, `gitea`) and an MCP server only by its exact registered name from the shipped public list (below), else `private`. `creds` is `{on, svc, np}`: `on` the logical credential keys that are mapped, but a key is named only when `prefs.schema.json` documents it as a `keychainMapping` key; every other mapped name is folded into `private` and counted once in `np`; `svc` holds the last check per key as `{s, at}` with `s` one of `ok`, `fail` or `expired` (the worst among the folded keys for `private`) and `at` a complete ISO timestamp or `null`. `calls` lists the skills invoked as `<plugin>:<skill>` when the plugin is public and the skill is one the package ships (the generated skill list), `<plugin>:other` when the plugin is public and the skill is not on the list, `multi-agent:<command>` for a shipped command and `multi-agent:other` otherwise; a skill of any other plugin is `private`, a repo-local one `repo-local`, one of an unlisted marketplace fallback `marketplace-fallback`. `errs` holds the same closed codes as `hr` plus `phase-<n>-failed` (numeric phase ids only) and `run-failed`. `v` is the installed version in the one release shape, `<n>.<n>.<n>` (each at most three digits) with an optional `-rc.<n>`, `-beta.<n>` or `-alpha.<n>`; anything else, a leading `v` and any other prerelease text included, is `unknown`, and the same validator applies to `vf` and to every other body that carries a version |
| `tools` | optional, at most 40 `{n, k}` rows for the MCP tools one run called: `n` is `<server>:<tool>`, `k` the number of calls, capped at 9999, most used first. A server is named only by its exact registered name from the shipped public list (`lib/public-mcp-servers.mjs`: this product's own `multi-agent`, `claude_ai_Figma`, `figma`, `XcodeBuildMCP`); every other server, an internal service or a ticket-named helper, is sent as `private:private` with the tool dropped and the counts summed. A tool is named only when it is on the shipped tool list of its server, which exists for this product's own server (the generated `TOOLKIT_TOOLS`); any other tool of a public server is `<server>:other`. A private server deliberately registered under a public name is therefore counted as that public server with the tool `other`, which reveals nothing. The numbers are the run's own: the run's `telemetry.mcpCalls` and the counter delta below, the larger per name. Names and counts only; never arguments or results |
| `services` | the apps this machine is connected to, at most 40 `{name, kind, connected}` rows: each logical key of `keychainMapping` (`kind: "token"`, `connected` while it is mapped and its last `serviceStatus` check did not fail) and each MCP server registered with Claude Code (`~/.claude.json`, user and project scope) or Copilot CLI (`~/.copilot/mcp-config.json`) (`kind: "mcp"`). The same rules as `creds` and `apps` hold here: a credential name is sent only when `prefs.schema.json` documents it, an MCP server only by its exact registered name from the shipped public list; every other name is folded into one `{name: "private", kind, connected, n}` row per kind, `n` the number of distinct names folded in. Names only: never a credential value, a server config or a path; a missing or unreadable config adds nothing |
| `cmds` | which `/multi-agent` commands were typed on this machine since the last accepted send, at most 80 `{n, k}` rows: `n` the name of a command the package ships (the generated `SHIPPED_COMMANDS`) or the constant `other`, `k` an integer from 1 to 9999, most used first. The rows are deltas, not totals: the server adds them to what it holds for the machine, once per `cb` (below). A count above 9999 is sent as 9999 and the remainder goes in the next batch. An empty list means none were typed. Counted from the Claude Code `UserPromptSubmit` hook only (section 12); Copilot CLI and Codex have no counter, so their commands are not in it |
| `cb` | present only with a non-empty `cmds`: the id of that batch of counts, 16 lowercase hex characters from `crypto.randomBytes`, made when the batch is claimed and sent again, unchanged, with the same counts, whenever that batch is sent again. It is a random nonce; nothing on the machine is hashed into it. The server adds a batch to the machine's totals once per `cb`: when it has already stored a `cb` for the machine it answers as accepted without adding the counts again, so a reply that was lost does not double them |
| `health` | optional machine-health summary, `{generatedAt, overall, items: [{id, status, reason}]}`: one item per `health-report.mjs` section (`services`, `toolkit`, `install`, `sessions`, `autopilot`, `office`, `disk`, `gate`, `errors`; at most 30), `status` and `overall` one of `green`, `yellow`, `red`, `reason` the id of the section's message in `lib/health-messages.mjs` (for example `errors.recurring`), taken only from that catalogue's section families, otherwise `other`. A section built from several parts (services, install, sessions, autopilot, disk) sends the id of the part that decided its colour, carried as `lead` on the joined message in the report document and chosen by `summaryFromReport`. No sentence and no message parameter (a service, host or branch name, a count) is sent; the panel renders the id in its own language. Read from a cache (`~/.claude/logs/multi-agent/usage-health.json`, 30-minute TTL). On a stale cache the event tries to create `usage-health.json.lock` exclusively with a random owner token; only when it gets the lock does it start a detached refresher (`usage-health.mjs --refresh --token <owner>`, never `--probe`) and wait for it, at most 5 seconds. An event waits only when it starts the refresh: one that finds the lock held sends at once without the field. A lock older than 3 minutes is taken over; a refresher exits at once when the lock is fresh and carries another token; a successful refresh removes the lock and a failed one rewrites it, so a failing report is retried at most every 3 minutes. The field is left out when no fresh summary is ready in time or anything fails; the panel then keeps the last one it had. `MULTI_AGENT_USAGE_HEALTH=cache` uses the cache without starting a refresher, `off` never sends the field |

`st` comes from the event when one is given (`--event`), otherwise from the
state file: `haltReason` or `paused` is halted, `awaiting_input` or a
`waitingFor` step is parked, `complete` is completed, anything else is in
progress.

**Transport.** Every send (the run record, the lifecycle record, registration
and its challenge, the access check, the failure beacon and feedback) goes
through `scripts/_http-post.mjs`: `node:https` with an explicit
`rejectUnauthorized: true` on the request and on a dedicated agent, which is
not the global one and so uses no environment proxy. The trust store is Node's
bundled roots plus the file `NODE_EXTRA_CA_CERTS` names, passed as `ca`;
`NODE_EXTRA_CA_CERTS` is the documented way to trust a corporate TLS-inspecting
CA. `NODE_TLS_REJECT_UNAUTHORIZED=0`, `SSL_CERT_FILE`, `SSL_CERT_DIR`,
`CURL_CA_BUNDLE` and `HTTPS_PROXY` do not change what is trusted or where the
token goes. A transport or certificate failure is reported as it is and is
never retried through another client: there is no curl fallback, because
`node:https` is part of every supported Node (`engines` is `>=20.11.0`).
Redirects are never followed, and plain http is allowed for a loopback address
only. `test/http-post.test.mjs` runs a child process for each variable against a
self-signed server.

**Timestamps.** Every timestamp a body carries (`t`, `t0`, `creds.svc.*.at`,
`health.generatedAt`, the lifecycle `t` and the feedback `at`) is written as UTC
ISO text rounded down to the minute, whatever offset or seconds it came with;
the seconds of a start time could be joined against public activity. Durations
(`du`, `phs[].du`) are computed from the full-precision instants, and
timestamps are compared as instants, never as text.

## 2. When it is sent

| Event | Where |
|-------|-------|
| `phase` | `phase-tracker.sh init` and every `update` to a status other than `pending`, detached so it never blocks a boundary; plus the Phase 0 exit gate |
| `completed` | Phase 5, after it writes `status: complete` and `finishedAt` to the state; the analysis render step |
| `halted` | the halt-visibility step in `phases/operations.md` |
| `parked` | the park-visibility step in `phases/operations.md`, after a run writes `awaiting_input` or `waitingFor` |
| `install`, `update` | registration, setup and update, and every accepted run event, when the installed version was not reported yet (see below) |

**Install and update records.** Derived, never written by the installer (see
section 8): the version stamp `install.js` writes (`.pipeline-version`, Claude
Code's first) says which version is installed and, by its modification time,
since when; prefs keep the last version reported (`usageLog.reportedVersion`).
When they differ, `usage-report.mjs --lifecycle` sends one record: `ev`
(`update` from the reported version; without one, `install` on a machine that
registered after the stamp and `update` from an unknown version on one that
registered before it), `v`, `vf`, `hs` (the host trees at that version, from
`claude`, `copilot`, `codex`), `t` (the stamp time), and `os` and `cli`; it carries
no login, and no record is sent when the installed version is not in the release
shape (`vf` is `null` for a reported version that is not), and moves `reportedVersion` forward once the server accepted
it. The id is derived from the version and the stamp time, so a resend replaces
the record. The installer starts it, detached, right after it writes the stamps
(`MULTI_AGENT_SKIP_USAGE_REPORT=1` turns that off); it also runs after a
successful registration, after setup or update finds a token already onboarded,
and after every accepted run event. The panel lists
the records under "Kurulumlar" and keeps them out of the run counts.

The panel derives a run's status from the last event it received. A run still
`in_progress` with no event for **6 hours** is shown as abandoned; a parked run
is waiting on a person and is never shown as abandoned. The threshold is
`STALE_RUN_MS` on the server side.

**Calls from a phase document never wait.** The shell lines in the phase
documents pass `--detach` to `usage-report.mjs` (and `usage-register.mjs`): the
script starts a second copy of itself with the same arguments in its own
session, with no stdio, and returns at once, so a slow or unreachable endpoint
cannot hold a run. The copy knows it is the detached one and never detaches
again. The copy has a hard overall limit of 120 seconds: a small watchdog
process outside it polls for the copy and kills its whole process group when
the limit passes (every read inside the copy has its own timeout, but the sum is
not bounded and a blocked synchronous call cannot fire a timer of its own), then
leaves; it leaves at once when the copy ends first. The unattended guard refuses
`&` and subshells in documented lines, which is why the script does the
detaching. The Phase 0 line adds `--register-first`:
the detached process runs the quiet registration to its end, in the same
process, and only then reads prefs and the token and sends, so the first report
on a machine that has never registered goes out after the registration and
carries the token it stored. Registration keeps its own rules: it is a no-op
once a token resolves, off under `usageLog.optOut`, and `deferred` in a context
that cannot see the accounts.

**The endpoint is held to a host list on the ingest path too.** The ingest
token rides in a header, so a send goes out only to the endpoint's host when it
is the reporting site's own host or one in `usageLog.trustedHosts` over https,
or loopback over http. Anything else is `skipped` with `endpoint-not-allowed`
and nothing is sent. A 3xx answer is never followed.

## 3. The reporting identity

The login is the GitHub login of **the account on this machine that can read the
pipeline repository** (`usageLog.accessRepo`, default `multi-agent-ecosystem/multi-agent-pipeline`):
access to that repository is what grants use of the pipeline, so it also decides
whose name a run carries. `usage-identity.mjs` finds it with no question asked,
stopping at the first account that can read the repository:

| Order | Method (`usageLog.loginMethod`) | Candidates | Access check |
|-------|------|------------|--------------|
| 1 | `gh` | every github.com account `gh auth status` lists: `usageLog.reportAs` (when logged in), the active account, then the rest | `gh api repos/<accessRepo>` with that account's token in the child's environment as `GH_TOKEN` |
| 2 | `credential` | the token git's credential helper holds for https://github.com: `git credential fill` with `protocol=https`, `host=github.com` on stdin, `GIT_TERMINAL_PROMPT=0`, `GCM_INTERACTIVE=never`, askpass disabled, a timeout | `GET /user` names the login, `GET /repos/<accessRepo>` proves access; through `gh api` with `GH_TOKEN`, or straight to the GitHub API from a child process when gh is not installed |
| 3 | `ssh` | the private keys `ssh -G github.com` lists (`identityfile`, `~` expanded) and `~/.ssh/id_ed25519`, `id_ecdsa`, `id_rsa`, each only when its `.pub` exists; a `.pub` listed on its own stands for a key held by an agent | `ssh -T git@github.com` names the login (`Hi <login>!`; a deploy key's `owner/repo` is skipped), `git ls-remote git@github.com:<accessRepo>.git HEAD` proves access. Both with `-i <key> -o IdentitiesOnly=yes -o BatchMode=yes -o ConnectTimeout=8 -o StrictHostKeyChecking=accept-new` |

No token is ever put on an argv, logged or stored: gh and git print it on their
own stdout, and it travels on only in a child's environment. Batch mode means a
key that needs a passphrase and is not in ssh-agent is skipped, never prompted
for. A missing gh, git or ssh binary, a timeout or a failed check only means
"no candidate"; nothing here fails a caller.

Never `identity.name`, which carries a person's real name and sometimes a
corporate title, and never simply the active `gh` account, which on a machine
with a work account and a personal account is often the one without access.

The answer is cached in prefs (`usageLog.login`, `loginMethod`, `loginKey` for
the SSH key path, `loginRepo`, `loginCheckedAt`, `loginReason`) for 7 days, or
1 day when no account was found, so a phase boundary costs no network call. A
cached SSH login whose key file is gone is re-checked. Refresh it after changing
accounts or keys, or being granted access:

```bash
node "$HOME/.claude/scripts/usage-identity.mjs" --refresh
```

**No account with access, no report.** Nothing is reported under an account
that cannot read the repository: the server accepts only the repository owner
and its collaborators. The emitter sends nothing and writes one line to stderr
(`usage-report: not sent - no GitHub account on this machine can read ...`,
naming what was tried); registration is skipped with the same reason. A cache
entry or registration written by 20.17.0 with `loginFallback` /
`registeredFallback` set is treated as no account: it is re-checked at once and
replaced as soon as an account with access is found.

**`--quiet` still speaks once.** The Phase 0 backstop discards stdout, so a
registration that leaves reporting off for a reason the user can fix (a refused
login, no account with access, a key that cannot sign, an unreachable endpoint)
prints one stderr line, `multi-agent: usage reporting is off - <reason>`, on
every run until it is fixed.

### Personal account

A registration is pinned: the server binds the token to the login it verified,
and the machine keeps that login in `usageLog.registeredAs`. Every later record
is named after it, with no identity check, and finding no account later does not
undo it (`decideRegistration`). So the personal account has to be reachable only
once, at the moment of registration.

A pin holds only while its token works. When a token is stored,
`usage-register.mjs` first asks the server whether it still does (see "The
stored-token check" below). A token the server rejects counts as no token: the
machine registers again in the usual order (a proof first, else the stored
`usageLog.declaredLogin`, else the pinned `registeredAs` as a declared name),
with no question, and the new token overwrites the old one in its
credential-store entry. The same declared registration under `registeredAs`
runs when the pinned machine has no stored token at all.

`usage-register.mjs --json` reports `needsPersonalAccount: true` only when the
machine is not pinned, no account with access was found (no gh account, no
credential-helper token, no SSH key) and no name was declared. A stored
`declaredLogin` or a pinned `registeredAs` keeps it false. Setup and update
ask a question only on `needsPersonalAccount: true`: once, for the person's
GitHub username (free text; Skip leaves reporting off). A `refusal`
(`not_collaborator` or `proof_required`) only prints its status line. The site
answers a declared name the same way whether or not it is a collaborator, so
typing the name again would change nothing. On an answer they run:

```bash
node "$HOME/.claude/scripts/usage-register.mjs" --login "$GITHUB_LOGIN" --json
```

`$GITHUB_LOGIN` is the name the person typed. `--login` keeps it as
`usageLog.declaredLogin` and prefers it. When this
machine can prove that account (gh, credential helper or SSH key), the proof is
used as below. When it cannot, which is the usual case on a machine signed in
with a work account only, the name is registered as declared: the server issues
a token only for a collaborator (the repository owner registers with a proof),
and marks its row `claimed:<machine>`. Later runs (the Phase 0 backstop) register a declared name
the same way, without asking again. A declared name the server refuses
(`not_collaborator`, or `proof_required` for the owner's name) is forgotten,
and setup and update print the status line without a question; the next setup
or update asks once more only when it reports `needsPersonalAccount: true`.
When the refused name was registered under a token the server had rejected,
the pin (`registeredAs`) is dropped too, so the same run reports
`needsPersonalAccount: true`, which is then the one question asked. The site
can hold a declared registration, or the records sent with it, until its owner
approves the login (`pending-approval`, `pendingApproval: true`). After a
`--login` registration setup and update say in one line that the owner
approves the name and that logs start after approval.

An unattended run never asks. `usage-register.mjs` in an unattended run
records `deferred` instead of "no account" (see "A context that cannot see the
accounts" below) and reports `needsPersonalAccount: false`, and doctor and the
final run report carry the line `registration waiting: enter your GitHub
username with /multi-agent:setup` (in outputLanguage) for a machine that
proves no account.

A declared name never replaces a proof: it is used only when the machine proves
no account, and never over a stored token that was issued for a proven login
(`usageLog.registeredClaim` marks a declared one, which a later proof replaces).
Declared registrations are run records only. The server refuses one for the
repository owner, rate-limits each login, caps declared tokens per login apart
from proven ones, marks their run records `claimed`, and does not accept them
for `/multi-agent:feedback`, which needs a proven registration.

## 4. The server side

`/api/usage/register` requires proof that the caller owns the login it names.
The proof depends on how the account was found:

- **gh**: `gh auth token --user <login>` (gh prints it on its own stdout), sent
  as `Authorization: Bearer <token>`.
- **credential**: the credential helper's token, fetched again at registration
  (never kept from the identity check), sent the same way.
- **ssh**: no token at all. (a) `POST <register url>/challenge` with
  `{ "u": <login> }` returns `{ challenge, namespace, expiresAt }`. (b) The exact
  challenge bytes (UTF-8, no trailing newline) are written to a `0600` file in a
  fresh temp dir and signed with `ssh-keygen -Y sign -f <key> -n <namespace>`,
  stdin closed and askpass disabled, so a key that needs a passphrase fails at
  once; then with `-f <key>.pub`, which signs through ssh-agent when the key is
  loaded there. The temp dir is removed afterwards. (c) `POST <register url>`
  with `{ "u", "c", "ssh": { "challenge", "signature" } }` and no
  Authorization header.

- **The machine label.** `c` is never the host name. It is `m` plus 10 hex
  characters: an HMAC-SHA256 of the short host name under the install secret,
  with a label of its own, so the panel can tell one of a person's machines from
  another and nothing else; the name cannot be recovered without the secret.
  Without the secret it is the constant `unknown`. The server binds a label to
  its row (a claim or rotation with a different label is refused), so a machine
  that registered before the digest existed registers once more as a new row
  after the upgrade.
- **declared**: no proof. `{ "u", "c", "claim": true }`, no Authorization header.

For a bearer, the server resolves the token to a GitHub login and refuses a
mismatch. For an SSH proof, the challenge is stateless and HMAC-bound to the
login, valid for five minutes; the server checks it, then accepts the signature
only from one of the login's public keys on GitHub
(`https://github.com/<login>.keys`; ed25519, rsa-sha2-256/512, ecdsa nistp256). Either way it then checks that login with a
server-side token (the repository owner, or a collaborator of the repository)
before it issues a token, and pins the login to that token. The body's `u` is a
hint for a bearer and the claim being proven for a signature.

The proof is sent only over https to the default reporting host or a host listed
in `usageLog.trustedHosts`, or plain http to loopback (`127.0.0.1`, `localhost`,
`[::1]`) for local development; any other endpoint is refused before any token
is read or any key is used. Redirects are not followed by any of the calls, so
neither a GitHub token, a signature nor the ingest token can be carried to
another host.

### The stored-token check

`POST <register url>/check` with an empty JSON body and the stored ingest token
in the `x-usage-token` header, read from the credential store into memory and
never put on an argv, in a log or in the body. It goes only where the login
proof may go (the trusted-host rule above) and is never sent for an opted-out
machine, a token in `$MULTI_AGENT_USAGE_TOKEN` or `usageLog.token`, a dry run,
or a machine with no stored token. The timeout is 4 seconds.

| Answer | `tokenCheck` in `--json` | Effect |
|--------|--------------------------|--------|
| `200 { ok: true, valid: true, u, claimed }` | `valid` | the token is kept |
| `200 { ok: true, valid: false }` | `invalid` | treated as no token: register again, replace the stored token |
| `5xx`, any other status, no verdict, timeout, network failure, redirect | `unknown` | the token is kept (no churn on an outage) |
| not sent | `skipped` | unchanged behaviour |

A rejected token that cannot be replaced (no proof, no known name) leaves the
reason as `stored token rejected; <why>`, which `--quiet` prints on stderr.
`--json` also carries `refusal` (`not_collaborator` or `proof_required`) when
a declared name was refused for that reason.

### Register answers

| Answer | Status line |
|--------|-------------|
| `401` / `403` `login_mismatch` | the login that could not be confirmed (for gh: `gh auth status` must list it) |
| `401` `ssh_signature_invalid` | the signature did not verify |
| `401` `ssh_key_not_on_account` | the key is not on that account; add its `.pub` to it |
| `401` `ssh_key_unsupported` | the key type is not accepted; use an ed25519, rsa or ecdsa-p256 key |
| `403` `not_collaborator` | the login is not a collaborator; the owner adds it (a declared name is forgotten; setup and update only print this line) |
| `403` `proof_required` | the declared name is the repository owner's, which registers only with a proof (gh or an SSH key); the name is forgotten |
| challenge `404` / `405` | the endpoint does not accept an SSH key as proof yet |
| signing failed | the key needs a passphrase and is not in ssh-agent: `ssh-add <key>` |
| `accepted: false` | `declined` |
| `accepted: false`, `pending_approval` | `pending-approval`: the site holds the registration until its owner approves it |

gh or the credential helper having no token for the login sends nothing.
`/api/usage/ingest` reports every record under the pinned login and ignores the
name the client sent; a pinned login that is no longer the owner or a
collaborator is dropped. Records from any other account are hidden from the
panel. `usage-register.mjs` replaces a stored token whose `registeredAs` differs
from the verified login, that predates verification, or that a 20.17.0 fallback
registration left, because a token reports under the login it was issued for.

### Member account

The site may open a member account for the registering login and name it in
`account` on a register or check answer: `{ username, temporaryPassword,
loginUrl }` once for a new account (or a password waiting on the site), else
`{ username, exists: true }` or `{ username, blocked: true }`. The script asks
for the password (`x-account-delivery: 1` on register and check) only when
its output is seen, never under `--quiet`; an unasked password waits on the
site. The password is printed once as a block (username, temporary password,
sign-in URL, change it at first login), or under `--json` carried only in the
stdout line, and is never written to a file, a log, prefs or telemetry.
Setup and update show it to the person once and never repeat, store or pass
it on.

Limit: the one-time block (or the `--json` line setup and update read)
appears in the host session transcript on disk, which the script cannot
reach or clear. The password stops working at the first sign-in, where the
site requires a new one, and expires after 7 days unused; the site enforces
both. Tell the person to sign in promptly.

### A registration that keeps failing

Every attempt overwrites `~/.claude/logs/multi-agent/usage-last-register.json`
(`t`, `status`, `detail`, `reason`). An `unavailable` or `declined` outcome
keeps the `failingSince` of the failure before it, so the record says how long
registration has failed; any other outcome clears it. `--json` carries
`failingSince` while failing, the plain output adds `usage registration
failing since <date>: <detail>` from the second failure on, and doctor's
`usage-register` check reports the same. The register request carries `v`
(the installed version) and `os`, so a 5xx the site answers itself (a missing
server secret, a store failure) is recorded on the site with them.

When the last ingest send was held for the owner's approval
(`usage-last-send.json`: `not-accepted`, `pending_approval`), the next
non-quiet run says so in one line, once per held send, and `--json` carries
`pendingApproval: true`.

### A rejected token heals itself

A token the server no longer knows makes ingest answer 401. `usage-report.mjs`
then runs one registration attempt in-process (the `register` export of
`usage-register.mjs`, quiet, never prompting) with the ingest's answer in hand,
so only a stored-token check that calls the token valid keeps it. When the
attempt stores a new token, the same record is sent once more with it. Nothing
loops: a second 401 is recorded as it is. A 5xx, a timeout, a redirect or a
`not-accepted` answer never starts a registration, and an opted-out machine
sends nothing at all. At most one heal runs per 10 minutes on a machine: a
send takes the right to heal by a compare-and-set on
`~/.claude/logs/multi-agent/usage-heal.json` under its file lock, so two
concurrent sends never both register, and an ingest that keeps answering 401
cannot make every send mint a token. A context that cannot see the machine's
accounts (an unattended run, gh tokens out of reach) takes no window, because
its registration can only be `deferred`; the next attended send still heals.
A send that finds a heal inside the
window records `heal: "throttled"` and resends only when another heal already
stored a different token. `usage-last-send.json` then carries `first` (the 401),
`heal` (the registration status, such as `registered` or `deferred`),
`healDetail` for anything but `registered`, `healed` (the resend was accepted)
and the outcome of the resend.

### A context that cannot see the accounts

An unattended run is sandboxed away from the Keychain, `~/.ssh` and the git
credential store (`schemas/unattended-profile.json` `denyRead`), so gh lists
the accounts in its config but reads no token for them (`tokenSource:
"default"`, "Failed to log in ... (default)"), and no SSH key or credential is
visible. `usage-identity.mjs` answers `hidden: true` there, with a reason that
starts "identity not visible in this context", whenever it finds no account in
an unattended run or gh lists accounts whose token it cannot read. It writes
nothing to the identity cache then. `usage-register.mjs` records `deferred`
with that reason: it sends nothing, sends no declared or pinned name in place
of a proof, keeps the cached and pinned logins, starts no claim back-off, and
the next run in a normal terminal registers. A usable, pinned token is not
affected. The same holds for a cached gh or credential login whose token the
context cannot read.

### The state line

`usage-register.mjs --status-line` prints the machine's reporting state in one
line when the person has something to do or know, and nothing otherwise
(`--json` prints the state object). It sends nothing and reads no credential.
Doctor's `usage-report` check carries the same line: registered with the last
send accepted, the token rejected with the self-heal result, deferred, waiting
for the owner's approval, or `registration waiting: enter your GitHub username
with /multi-agent:setup` (Turkish under `outputLanguage: tr`: `kayıt bekliyor:
GitHub kullanıcı adını /multi-agent:setup ile gir`), each with the last send
time. The last three are reported while reporting is still off, because a
machine that never registered is that case.

## 5. The token

Requested, never shipped. `/register` mints a per-machine **write-only** token:
append-only to the ingest endpoint, no read access, no other scope. Only its
sha256 hash is stored server-side, so a database leak exposes no usable
credential, and the owner can revoke one row without touching anyone else.

It lands in the OS credential store under `<user>_Usage_Ingest_Token`. Prefs hold
the NAME of that entry (`keychainMapping.usage_ingest`) and the on-switch, never
the secret. Every prefs write here (the cached login, the entry name, the
switch) holds the prefs file's lock and replaces the file atomically at mode
`0600`, the same helper `migrate-prefs.mjs` uses. Resolution order at emit time: `$MULTI_AGENT_USAGE_TOKEN`, then
`usageLog.token`, then the credential-store entry.

## 6. Opting out, and the two silences

`usageLog.optOut: true` blocks registration permanently and is checked before
anything else - before the identity check, the network call and any credential
read (the credential store, `gh auth token`, `git credential fill` and any SSH
key).

The other silence is not a choice: offline, endpoint down, ingest disabled by the
admin, no account with access, or a credential store that refuses the write. That
leaves reporting off with one status line and exit 0. **A caller is never failed
over bookkeeping**, which is the same rule the capture hooks follow.

Both are reported distinguishably (`--json` gives `status`: `skipped` with the
reason, `unavailable` with the cause, `declined`, `registered`, `enabled`, `dry-run`) because
"you turned it off" and "we could not reach the endpoint" are different facts
about the same empty panel.

Every send attempt past the on-switch overwrites
`~/.claude/logs/multi-agent/usage-last-send.json` with its outcome: `accepted`,
`not-accepted` (the server answered but did not keep the record), `rejected`
(with the status code), `redirected` (with the host it pointed to; a redirect is
never followed, because the token would ride along), `failed` (network or
timeout), or `skipped` (`no-token`, `no-login`, `endpoint-not-allowed`, `run-key-unavailable`). It
carries the run id, the event and the endpoint host, never the token. The
phase-tracker ping discards the emitter's output, so `/multi-agent:doctor`
reads this file (check `usage-report`) and turns anything but `accepted` into a
WARN with one step. `migrate-prefs.mjs` rewrites an endpoint on the platform
host to the site's domain, so a stored redirecting endpoint does not outlive an
update.

A registration that ends `unavailable` also sends one failure report, detached
so it never delays or fails the caller (`usage-register-beacon.mjs`): `POST
<register URL>/failure` with `{ u, v, reason, os }` and nothing else, no token
and no header beyond Content-Type. `u` is the login this run had (proven or
declared; with no login nothing is sent), `v` the installed version, `reason`
one word from a fixed list (`endpoint-unreachable`, `tls-untrusted`,
`proxy-refused`, `timeout`, `redirected`, `not-collaborator`,
`gh-account-mismatch`, `proof-rejected`, `proof-required`, `no-proof`,
`rate-limited`, `server-error`, `credential-store`, `prefs-write`, `other`) and
`os` darwin. It is never sent for an opted-out machine (feedback runs
included), on a dry run, for a decline, or to a register URL the login proof
may not go to. Each (reason, version) goes at most once a day; one that was not
delivered is tried again on the next failed registration. The state is
`~/.claude/logs/multi-agent/usage-register-beacon.json`, and doctor's
`usage-register` check reads it next to `usage-last-register.json`. The server
keeps the report only for the owner or a collaborator of the access repository.

`prefs.global.usageLog.endpoint` overrides where both calls go - the register URL
is derived from it, so a self-hosted ingest gets its own registration rather than
this one's. Absent means the shipped default, and every shipped default names the
same host, so a machine never registers against one host and reports to another.

## 6b. Feedback is not telemetry

`/multi-agent:feedback` rides the same token, and `optOut` does not silence it:
passive collection is a choice, a message somebody typed to be read is not. So a
feedback run may register (`--feedback`) on a machine that opted out - and when it
does, it writes the credential-store entry and **leaves `usageLog.enabled` alone**.
The opt-out still holds for everything it was about; the person just gets their
message delivered. What it sends: the typed text (by design), `kind` (`bug`,
`idea` or `question`), `host` (`claude`, `copilot`, `codex` or `unknown`), `at`
(the time it was sent) and `v` in the release shape; the same rules as every
other body apply to the fields that are not the typed text.

## 6c. The access check

The access check is the one request that ignores `usageLog.optOut`. It does not
report anything about a run: it asks the owner of the reporting site whether
this login may use the pipeline, and the product cannot honour a block without
asking. It sends the login (or null) and the version in the release shape
(`unknown` otherwise), nothing else, and runs even for a machine that opted out
of reporting. `accessBody` in `usage-access.mjs` is the exact body.

Before a run does any work, its entry point runs `usage-access.mjs`: the
`/multi-agent` dispatcher for every route except `status`, `log` and `help`
(a task input, `jira`, `issue`, `resume`, `autopilot`, `kill`, `purge` and
`review` included; Claude Code and Copilot CLI); the `jira` and `issue` launchers
before their first picker, since they can assign an issue and post a maturity
comment before Phase 0; `resume` on both hosts, since a resumed run skips
Phase 0; Phase 0 itself (Step −2); the autopilot runner (before each item it
would take); the autopilot loop (before each iteration); the office (before it
starts a job); and, first, every standalone command that writes outside the
machine: `address-review`, `analysis`, `analysis-jira`, `channels`, `complaint-analysis`,
`create-jira`, `design-check`, `kill`, `purge`, `refactor`,
`review`, `review-analysis`, `review-issue`, `review-jira`, `review-priority`,
`routines-share`, `routines-browse`, `routines-import`, `routines-update`,
`routines-delete`, `scaffold` and `sync`, on both hosts. `feedback` stays open so a
closed login can still report a problem, `setup` and `update` stay open
because they are how a refused login gets access, and the office commands
(`office-on`, `office-off`, `office-status`) stay open because they talk only
to the office server on loopback. The list lives in
`test/usage-access-callers.test.mjs` (`GATED`, `EXEMPT`), whose lint fails a
command that writes outward and is in neither. It reads the command's SKILL.md
on both hosts, everything under `multi-agent-refs/<command>/`,
`multi-agent-refs/features/<command>.md` and every ref the command links to
(a contract linked by more than five commands excepted), and it scans the
scripts the command runs for an HTTP write:

```
POST <site>/api/usage/access   X-Usage-Token: <token, when one resolves>
{"login": "<registeredAs, declaredLogin or cached login, else null>", "v": "<version>"}
```

The URL is the ingest endpoint with `/access` in place of `/ingest`, under the
same rule as registration (https to the site's hosts or `trustedHosts`, http
only to loopback), and a redirect is never followed. The site answers
`{"allowed": true}` or `{"allowed": false, "reason": "blocked" |
"invite-pending" | "no-access", "message"?, "url"?, "invitation"?}`; it uses the
token's login when the token is valid and the body's login otherwise, and a
body login only ever gets the generic `no-access` with the request page and
the organization's invitation page, so nobody reads another person's block. A refusal exits 3 and
prints one line in outputLanguage, and the run ends there before it writes
any run state. The check itself records its answer in `access-state.json`
(below), and the autopilot runner puts the line into its queue's
`blockedReason`, so its status shows why nothing was taken.
`blocked` adds the owner's message, `invite-pending` asks the person
to accept the organization invitation and restart the task, `no-access` says
where to ask for access and, with `invitation`, where to accept an invitation.
A `url` is printed only when it is https on github.com or on the endpoint's
host, and an `invitation` only on github.com.

It fails open: a network error, a timeout, a non-200 answer, a body without a
verdict or a refusal reason it does not know all let the run start. The
request has one 2-second deadline, and there is one attempt: no second client
is tried after a failure; reading the token from the credential store comes
before it. A `blocked` answer is kept in
`~/.claude/logs/multi-agent/access-state.json` (mode 0600: the login, the time
and the owner's message, no token) and honoured for 7 days, for that login
only, while the site cannot be reached; a later answer for the same login that
is not `blocked` clears it.
`invite-pending` and `no-access` are not kept: the person fixes those, and the
next run that reaches the site must pass. Doctor's `access` check reads the
same file.

It runs whatever `usageLog.optOut` says, because opting out of reporting must
not open a closed account. It sends only the login and the version: no run
data, no machine name, nothing else.

## 7. The half-configured case

A token in the credential store with `enabled: false` produces exactly the same
silence as no token at all, and it happens whenever a run is interrupted between
the two writes. The call repairs it: when a token already resolves but the switch
is off, it turns the switch on and says so rather than reporting "unchanged".

## 8. Where it is NOT called

The installer. `install.js` never registers: seeding state is the one thing the
install contract forbids, and a fresh machine has no preferences file for the
registration to write into. Setup creates it; registration follows. The only
reporting the installer starts is `usage-report.mjs --lifecycle`, which sends the
install record with a token that already resolves and registers nothing.

## 9. Local skill usage is not reporting

A second record stays on this machine and is never sent anywhere:
`note-skill-use.sh`, a Claude Code PostToolUse and PostToolUseFailure hook on
the `Skill` tool that `install` registers, appends one row per skill call to
`~/.claude/logs/multi-agent/skill-usage.jsonl` (`LOGS_ROOT` overrides the
directory). A row holds five facts plus a format version:

| Field | Value |
| --- | --- |
| `skill` | the skill name, kept only when it is one to three `:`-joined segments of `[A-Za-z0-9._-]`, at most 96 characters, with no credential pattern in it; any other name drops the call |
| `outcome` | `ok` or `error` |
| `ts` | when the hook ran |
| `host` | `claude` |
| `repo` | the main repository's folder name, null outside a git repository and for a repository in `memory.excludeProjects`; never a path |
| `v` | the row format version, a constant (`1.0.0`) |

The skill's arguments, the prompt, the rest of the tool input and its output or
error text are never read into a row. Past 1 MiB the log moves to
`skill-usage.jsonl.1`, replacing the generation before it; one writer rotates
at a time, under an exclusive `skill-usage.jsonl.lock`, so two hooks firing
together never move a fresh log over `.1`. The hook reads stdin
for at most 1.5 s and exits 0 with no output on every path, so a slow or broken
log never holds the call.

It is on by default because it is local. `skillUsage.enabled: false` stops it,
and so does `usageLog.optOut: true`: an opt-out from passive collection covers
the local log too. Rows written earlier stay until `uninstall --all-data`, which
removes the log directory, or until removed by hand; a plain uninstall takes the
hook out of `settings.json` and keeps the log.

`node ~/.claude/scripts/skill-usage.mjs summary [--days N] [--json]` counts calls,
failures and last use per skill, lists the installed skills not seen in the
window and says where the log starts (`coverageStart`, `coversWindow`);
`prune-candidates [--days N]` lists only the unseen skills, with their last use
ever, and deletes nothing. The installed list covers `~/.claude/skills`,
`~/.claude/commands` and every skill of every plugin the multi-agent-plugins
marketplace lists, at any depth under the plugin's `skills/`, named
`<plugin>:<folder>` as the host shows it.

Three rules keep a candidate honest:

- The log only knows what happened since its oldest row. While that row is
  younger than the window (right after install, after capture was off, after a
  long rotation), `prune-candidates` names no skill and says when the log
  starts; rerun with a shorter `--days` or wait.
- A slash command the user types expands in the prompt without a Skill tool
  call, so the hook never sees it. Everything under `~/.claude/commands` is
  reported as not observable and is never a candidate.
- A rename alias (a `SKILL.md` carrying `renamed-to:`) left by an earlier
  release is not listed, and a call under the old name counts as a use of the
  skill it points at.

The office server room shows the 30-day counts (`GET /v1/server-room` `skills`,
local-only, never leaves this machine).

Codex CLI has no Skill tool call to hook, it reads skill files directly, and the
pipeline installs no Copilot CLI hooks, so on those hosts nothing is counted.

## 10. Local MCP failures and calls are not reporting

A third record stays on this machine too: `note-mcp-failure.sh`, a Claude Code
PostToolUseFailure hook on `mcp__.*` that `install` registers, appends one row
per failed MCP tool call to `~/.claude/logs/multi-agent/mcp-failures.jsonl`.

| Field | Value |
| --- | --- |
| `server` | the server part of `mcp__<server>__<tool>`, kept only when it matches `[A-Za-z0-9][A-Za-z0-9._-]`, at most 96 characters, with no credential pattern; otherwise the call is dropped |
| `tool` | the tool part, under the same rule |
| `ts` | when the hook ran |
| `errorClass` | one of `denied`, `disk-full`, `timeout`, `rate-limit`, `auth`, `connection`, `invalid-input`, `not-found`, `server-error`, `interrupted`, `other`, chosen in this order: the host's interrupt flag (`interrupted`), then a refusal by the user or the permission layer (`denied`), then a JSON-RPC error code in the error text (`-32603` and the implementation range `-32000..-32099` are the server's, with the MCP SDK's `-32000` read as connection and `-32001` as timeout; `-32602`, `-32600` and `-32700` are the caller's input; `-32601` and `-32002` are not found), then a message that opens with `invalid` or `validation` (the caller's input), then an HTTP status written as a status rather than a number in a path, a bare three-digit number counting only after `HTTP`, `status` or a request line, or before a reason phrase (5xx server, 401 and 403 auth, 404 not found, 429 rate limit), then fixed wording patterns that try `disk-full` (`ENOSPC`, no space left on device) first and the other server-side classes before `invalid-input` |
| `v` | the row format version, a constant (`1.0.0`) |

The arguments, the output and the error text are never written; the text is
only read to choose the class. No server is probed. The log is written by the
same code as the skill-usage log, so it has the same 1 MiB cap and `.1`
generation, and rotates under its own `mcp-failures.jsonl.lock`: the two logs
never wait on each other. Both are opened without following a symlink and
without blocking, and a row is dropped when the path is not a regular file.
`mcpFailures.enabled: false` stops it and so does `usageLog.optOut: true`; it
also stays off while the preferences file exists but does not parse, since an
opt-out in it cannot be read.

`node ~/.claude/scripts/note-mcp-failure.mjs summary [--hours N] [--json]`
counts failed calls per server, per tool and per class in the window (default
24 hours). `doctor`'s `mcp-failures` check lights INFO for a server with five or
more failures there; `invalid-input`, `denied` and `interrupted` are the
caller's or the user's and never count toward it. Any `disk-full` row in the
window also lights INFO with `/multi-agent:clean-disk` as its step, whatever the
count, because a full disk fails every server at once.

`note-mcp-call.sh`, registered on PostToolUse for `mcp__.*` with `async: true`
(the host's hook schema defines `async`: if true, the hook runs in the background
without blocking), counts the calls that succeeded for the usage record's
`tools` field. It is read by usage reporting and, on the machine only, by `mcp-health.mjs` (`GET /v1/mcp-health`, the office server room), which never sends it. It is bash only and cannot
parse the preferences, so it never reads the opt-out from them. It writes
nothing unless the marker file `<log root>/mcp-counting-on` exists, is not a
symlink, and is not older than the preferences file. The marker is written, and
its time renewed, by `syncCountingSentinel` (in `note-mcp-failure.mjs`) with a
real JSON parser: at every `usage-report.mjs` run and in the failure hook, and
only while `usageLog.enabled` is true and neither `usageLog.optOut: true` nor
`mcpFailures.enabled: false` is set and the preferences parse; in every other
case it is removed. Any later edit of the preferences makes the marker older
than them, so an opt-out stops the hook at once; counting resumes when the next
report or failure hook renews the marker. A machine that has never reported has
no marker, so nothing is counted before the first report, which is also when a
run's base is written. The hook reads only the first 8 KiB of the payload, takes
`session_id`, `hook_event_name` and `tool_name` from it, accepts only a
`PostToolUse` event, a session id of `[A-Za-z0-9_-]` (8 to 64) and a tool name of
`mcp__[A-Za-z0-9_-]` (up to 100), and appends one line, `<session id> <tool
name>`, to `<log root>/mcp-calls.log` (owner-only, never through a symlink, no
more than 2 MiB). It does no counting, no JSON and no locking.

Counting stops being recorded the moment it is off: when `syncCountingSentinel`
finds it off (opt-out, `usageLog.enabled` false, `mcpFailures.enabled: false` or
preferences that do not parse), it also deletes `mcp-calls.log` and any leftover
of a fold and empties the counter's sessions and per-run bases, so calls seen
while it was off are never sent after it is turned back on. The hook reads only
the top-level keys of the payload (a depth-aware scan of the first 8 KiB); a
`session_id` or `tool_name` inside `tool_input` is not read.

The counting happens when a report is built. `foldCalls` moves the lines of
`mcp-calls.log` into `<log root>/mcp-calls.json` (the failure log's directory,
`LOGS_ROOT` honoured by the hook and by the report) under the counter file's lock.
The whole fold runs under that lock: the log is renamed, the renamed file and
any leftover of an interrupted fold are read, the counts added, the files
deleted and the counter written, so folds that run at the same time take turns
and never read the same lines. The counter key is `<server as registered>:<tool, lowercase>`. The same
switches stop it, with a real parser, and it also stays off
while the preferences file exists but does not parse. The file holds `{"v": 2,
"sessions": {"<host session id>": {"t": ..., "calls": {"<server>:<tool>": n}}},
"bases": {"<run id>": {"sid": ..., "calls": {...}}}}`. A call is counted under
the session that made it. A run's numbers are the session total minus the
counts the session had when the run was first reported (its base, written once,
by the report); a run never carries the machine's lifetime total. At most 200
names per session, a count capped at 1,000,000, and only the 20 newest sessions
and the 20 newest bases are kept. Nothing else about a call is read or stored.

Two limits of the numbers. A run that resumes in a new host session starts a
new session total, so its `tools` counts only the calls made since the report
that follows the resume and undercount the calls of the earlier session. A line
appended in the instant the fold replaces the log can be lost.

## 11. The local logs and their previous generation

`metrics.jsonl`, `errors-ledger.jsonl` and `session-notes.jsonl` are written
owner-only and move to a single `<name>.1` generation past 1 MiB. Every writer
rotates under the file's `<name>.lock` and reads the size again once it holds
it, so two writers that saw the same full file do not move the fresh one over
the generation the first made: the node writers and `run-write.mjs rotate`
(which `log-metric.sh` uses on both of its paths) take the same lock file, and
`note-session.sh` takes it with the same create-exclusive protocol. The first
write after an older version also makes an existing 0644 file owner-only.
Their readers (`aggregate-metrics`, `learning-curve`, `token-budget-report`,
`route-learn`, the health report's errors section and the office memory shelf)
read `.1` and then the current file through `lib/rotated-log.mjs`, so a
rotation does not cost them history and rows stay in the order they were
written.

## 12. Which commands are typed

A run only reports its own command (`c`). Commands that are not runs (`status`,
`doctor`, `office-on`, `help`, `route-status`, and so on) leave no run, so the
panel could not tell which commands are never used. `note-command-use.sh`, a
Claude Code `UserPromptSubmit` hook that `install` registers with `async: true`
(the prompt never waits for it) and `uninstall` removes with its script, counts
them.

What the host sends: the payload carries the typed prompt in the top-level
`prompt` key beside `hook_event_name` (`UserPromptSubmit`), `session_id`,
`transcript_path`, `cwd` and `prompt_id`. For a slash command it is the text as
typed, `/multi-agent:<name> <arguments>` or `/multi-agent <name>`, with the
arguments in it; this was captured from a real `claude -p` run with a capture
hook, for both spellings.

What the hook keeps: a prompt counts only when its first token is
`/multi-agent:<name>`, or when it is `/multi-agent` followed by a shipped
command name. The name is looked up in the shipped list
(`lib/usage-names.generated.mjs`); a shipped name is appended to
`<log root>/cmd-calls.log`, and a colon-form name that is not on the list is
appended as `other`. A `/multi-agent <word>` whose word is not a shipped command
is free text for the dispatcher, not a command name, and is not counted. Nothing
else is read past the first two tokens or stored: no argument, no text, no
length, no time. It reads the first 8 KiB of the payload and scans only the
top-level `hook_event_name` and `prompt` keys (a `prompt` inside a nested object
is never read), starts no node process, appends one short line (atomic, owner-
only file, never through a symlink, no more than 1 MiB until it is folded),
prints nothing and exits 0 on every path.

When it is off: it writes nothing unless the marker `<log root>/cmd-counting-on`
exists, is not a symlink, and is not older than the preferences file. The marker
is written, and its time renewed, by `syncCommandSentinel` (in
`note-command-use.mjs`, called from `syncCountingSentinel`, so at every
`usage-report.mjs` run and in the failure hook) with a real JSON parser, only
while `usageLog.enabled` is true, `usageLog.optOut` is not and the preferences
parse; otherwise it is removed and the log and the counter are emptied, so what
was typed while counting was off is never sent after it is turned back on. This
counter has its own switches and does not depend on `mcpFailures.enabled`.

How it travels: `cmds` rides on the run record, which is the periodic send, not
on a request of its own. The counter `cmd-counts.json` holds `pending` counts
and one `inflight` batch. Everything that changes it, the fold of the log
included, runs under the file's lock. A send claims the pending counts as one
batch with an id; while that batch is out no other sender is handed it;
the batch is cleared when the server accepted the record, made available again
when it did not, and offered again by itself after 10 minutes if no sender
answered, with the same id and the same counts; what was typed in between waits
for the next batch. A dry run only looks. A sender that is killed after the
server accepted its record but before it acknowledged re-sends that one batch
once, and the server, seeing the same `cb`, does not add it a second time.
