# Soma rubric · gate exit codes

Source: https://usecns.dev/contract-rubric/

## 5. `Soma` → `Thalamus` System 1 Oracle and the `cns gate` Exit Contract

### 5.1 What a rubric verdict measures

`soma concerns check --systemone` sends the concern's question text verbatim through Thalamus, using the model discovered through `/admin/v1/status` and criteria derived from `expect`. Pass rates from a different model, prompt or evaluation path do not establish the reliability of these verdicts.

### 5.2 Request (writer: Soma `soma-systemone`; reader: Thalamus `/v1/systemone`, proxied verbatim to the System 1 server)

`THALAMUS_URL` is required: Soma names no model host, so unset means **not evaluated**. There is no default relay address (§1.1). `--systemone-timeout-ms` (default 45000) is one budget measured from the start of `soma concerns check`: the status read and the call share its deadline.

1. `GET ${THALAMUS_URL}/admin/v1/status`. The model is `models[0]` of the first (by `name`) entry of `planes.verification[]` with `healthy == true`, `draining == false`, `"system1.decide"` in `capabilities`, and a non-empty `models`. None: **not evaluated**. `/v1/classify` (the rerank handler) is never called.
2. `POST ${THALAMUS_URL}/v1/systemone`, header `x-request-id: <32 hex>`, body:

   ```
   {"model": "<models[0]>",
    "state": {"git_diff": "<unified diff base..head or working tree>", "changed_files": "<paths, newline-separated>"},
    "questions": {"<concern-id>/<n>": {"type": "noul", "instructions": "<question text verbatim>",
                                       "criteria": {"true": "yes", "false": "no"}}}}
   ```

   `<n>` is 1-based within the concern. Only questions of concerns that fired are sent; nothing fired means no call (`rubric: vacuous`). Section 1.2's example key `question` is not what Soma sends; Soma sends `instructions` + `criteria`.
3. **Polarity.** A Questions bullet may start with `[expect: yes]` or `[expect: no]` (default `yes`). The marker is removed from the text. **This is the one accepted syntax**: exactly `[expect: yes]` or `[expect: no]`, lowercase, one space after the colon, first in the bullet, followed by whitespace and the question. Any other text that starts like a marker (`[expect`, in any case or spacing) anywhere in the bullet, including a trailing `... [expect: no]`, is an `unrecognised polarity marker`: `soma concerns validate` fails, `soma concerns check` refuses (exit 2), and `soma concerns lint --polarity` lists every one and exits 2. Nothing marker-like is ever sent as question wording or read as a silent `yes`. The one fixed mapping (`soma_systemone::criteria_for`) is `yes -> {true: "yes", false: "no"}`, `no -> {true: "no", false: "yes"}`; its canonical JSON `{"no":{"false":"yes","true":"no"},"yes":{"false":"no","true":"yes"}}` hashes to `expect_map_sha = dac6eaec67864d2e8f89f3e7df411f20d7918d24a50cf05d6c8a9a53c82fae5c`.

### 5.3 Response and verdict

* `200` body `{"model", "answers": {"<key>": {"type": "noul", "noul": <p>}}, "usage"}`; `noul` is P(`criteria.true`), i.e. already on the `expect` side. `x-thalamus-node` names the member that served it.
* A question **fails** when `noul < threshold` or its answer is malformed (non-numeric, not in [0, 1], not an object). The default threshold is **0.50**; `--rubric-threshold` accepts finite values in (0, 1] with `--systemone` and is reserved for calibration.
* A concern's rubric verdict is conjunctive over its questions. **A rubric failure adds red; a rubric pass never clears a structural fire.** With `--check`, `critical`/`warning` fires are red regardless of the rubric; a `question`-severity concern is red only when its rubric fails.
* A `2xx` reply is read only when its `content-type` is `application/json` or `application/*+json` (case and parameters ignored). Any other content type, or none, is **not evaluated** even when the body parses: an HTML error page or portal is never judged. This holds for `/admin/v1/status` and `/v1/systemone`. Thalamus' status route is axum `Json` (`application/json`); `/v1/systemone` passes the System 1 server's header through. This contract does not establish that a live upstream response has been observed.
* **Not evaluated** (exit 3): status unreachable / non-2xx / not JSON / not served as JSON, no healthy member, `/v1/systemone` unreachable / timeout (default 45 s, `--systemone-timeout-ms`) / non-2xx / not JSON / not served as JSON, `answers` absent or empty, any requested key missing, or the verdict log unwritable (`<generated_dir>/rubric-verdicts.jsonl could not be written: <error>`; the answers were fetched but cannot serve as recorded evidence). Extra unrequested answer keys are ignored and counted.

### 5.4 `soma concerns check` exit codes and output

| Exit | Meaning |
| --- | --- |
| `0` | Every requested oracle ran; with `--check`, nothing red |
| `1` | With `--check`: a critical/warning fire, an invalidated pin, or a rubric-red concern |
| `2` | Refused (bad arguments, invalid registry) |
| `3` | `--systemone` requested and not evaluated, whatever the structural result |

Markdown output ends with `## Oracles`, one line `oracles: structural; rubric: not evaluated (not requested)` | `oracles: structural; rubric: vacuous` | `oracles: structural; rubric: not evaluated (<reason>)` | `oracles: structural, systemone; rubric: pass|fail (...)`, then `structural: pass` | `structural: red (<gating concern ids>[; pinned anchor invalidated])`, and `fired: <n>`. The `structural:` line states the structural result on its own, because exit 3 outranks it. JSON output carries `oracles`, `rubric` and `structural: {red, gating, pinInvalidated}`.

### 5.5 Verdict log (writer: Soma; reader: concern census)

`<generated_dir>/rubric-verdicts.jsonl` (default `.soma/rubric-verdicts.jsonl`, git-excluded), one row per evaluated question, appended:
`{ts, concern_id, question_idx, expect, score (null when malformed), pass, delta_sha (sha256 of state.git_diff), model, threshold, expect_map_sha, thalamus_url, thalamus_node (x-thalamus-node or null), request_id (= x-request-id sent)}`. Unanswered questions are not logged (the run is exit 3).

### 5.6 `cns gate` (writer of a `vitals.v1` row; reader: `cns status` [5])

* **The rubric oracle is off unless the operator enables it.** Enabling it explicitly authorizes live inference for this gate path: `CNS_ORACLES=structural,rubric` in the environment, or a **top-level** `oracles = ["structural", "rubric"]` in `.cns/config.toml`. The environment wins over the file; an unknown oracle name is exit 3 and contacts nothing.
  + Only a top-level TOML key counts. One inside any `[table]` is ignored and the gate prints `note: ignored the oracles key inside [table] ...`; a key inside a string or comment is not a key.
  + Multi-line arrays, comments, quoted keys and literal strings are accepted. A duplicate key, a value that is not an array of strings, or an unterminated string or array is exit 3 with a named reason.
  + Disabled: no Thalamus request of any kind (not even `/admin/v1/status`); the gate prints `rubric: not evaluated (disabled by default)` and exits by the structural result. `cns gate --systemone` without the opt-in exits 3. This covers the Pi extension's automatic gate and every harness Stop hook (5.7).
* **Deterministic oracles `typecheck` and `tests`** are requested the same way (`CNS_ORACLES=structural,typecheck,tests,rubric`, or the same names in the top-level `oracles`). Each requested one reads its `[gate.typecheck]` / `[gate.tests]` table from `.cns/config.toml` and runs after `axon index`, before the publication bracket, `soma verify`, `soma concerns check` and the rubric, in that order.
  + Keys: `cmd` (required, a non-empty array of strings: argv, executed from the repository root with no shell), `timeout_ms` (positive integer), `globs` (array of `fnmatch` patterns over repository-relative paths; `*` crosses `/`), `diagnostics` (`"phpstan-json"`), and for `tests` only `require_integration_on_http_surface` and `require_integration_on_dispatched_surfaces` (booleans). An unknown key, a missing table, or a wrong type is not evaluated (exit 3).
  + Placeholders, each a whole `cmd` element that expands to one argument per existing repository file (never split, never shell-parsed, deduplicated, a path starting with `-` prefixed `./`): `{changed_files}` is `git diff --name-only --diff-filter=d <merge base>` against Soma's base (`--base`, else `soma.toml` `default_base`, else `HEAD`; `--head` diffs that committed range), plus untracked files for the working tree outside `.cns/`, `.soma/`, `.axon/` and `.engram/`. `{impacted_files}` adds the `filePath` of every `downstream.symbols` entry with `hops: 1` in `axon delta --base <merge base> --json` (`--committed-only` with `--head`), or the caller's `--delta <file>`. `{impacted_tests}` is the `file_path` of each `impacted_tests[]` entry of that delta, in its order (Axon issue [ivannovak/axon#30 (repository access may be required)](https://github.com/ivannovak/axon/issues/30); camelCase `impactedTests`/`filePath` is read too; shapes and the full list of fields the gate reads in §2.2). When every placeholder in `cmd` expands to nothing, the oracle passes without running the command.
  + `diagnostics = "phpstan-json"` follows auctic-core's `.github/scripts/phpstan-pr-gate.php`: `cmd` analyses the whole configured project with `--error-format=json` (so the baseline, stubs, custom rules and cross-file collectors stay correct; passing PHPStan a file list breaks them), stdout is read as the report and stderr kept apart, and only messages in files of `{changed_files}` (after `globs`; a trait's `path (in context of class …)` counts as `path`) are red. PHPStan exit other than 0 or 1, a stdout that is not a report with `totals` and `files`, or a non-empty top-level `errors` array is not evaluated. With no changed files the command is not run and the oracle passes.
  + `require_integration_on_http_surface = true` is red when the delta lists an HTTP surface in `untested_surfaces` or `mock_only_surfaces` (by the entry's `kind`, §2.2). `require_integration_on_dispatched_surfaces` (default: the value of `require_integration_on_http_surface`) does the same for `job` and `event` boundaries, such as a queued job only a `Bus::fake()` test reaches. A console command is neither, even when its name contains `:http:`.
  + Verdicts: command exit `0` passes; any other exit is red (exit 1) and the first 150 lines of its combined output are printed. Not evaluated (exit 3): the binary is missing or not executable, it exits 126 or 127, it outlives `min(timeout_ms, budget left)` (its process group is killed), no Axon delta is available for an impacted placeholder, or the delta lacks the field a placeholder or option needs.
  + A typecheck or tests red skips the rubric (`rubric: skipped (<oracle> red; System 1 not called)`), which then stays requested and not evaluated without raising exit 3.
  + `cns init` writes `.cns/config.toml` when absent, for the first of `composer.json`, `tsconfig.json` (`tsc --noEmit`), `Cargo.toml` (`cargo check`) and `pyproject.toml` (pyright, mypy, ruff). For `composer.json` the analyzer is the one the repository configures, never one CNS prefers: `phpstan.neon` or `phpstan.neon.dist` is whole-project PHPStan with `diagnostics = "phpstan-json"`, `psalm.xml` or `psalm.xml.dist` is Psalm over `{impacted_files}`, and with neither the table is commented out. `[gate.typecheck]` is active only when that analyzer is installed, `[gate.tests]` is a commented example, and the `oracles` line stays commented: typecheck is enabled by the operator once it exits 0 on HEAD.
  + What typecheck does not catch. A named argument to a method that forwards `func_get_args()`, such as Laravel's pre-11 `Dispatchable::dispatch()` (`InvoiceLineItemUpdated::dispatch($item, $qty, recalculateFees: $fees)`, a PHP 8 `Error: Unknown named parameter` at runtime), passes stock PHPStan at every level (phpstan/phpstan#13719); Larastan checks `dispatch()` arguments against `__construct`, so it rejects unknown names but accepts `recalculateFees:` because the constructor declares it. That bug is covered by the `tests` oracle running the impacted feature tests and by Axon's `untested_surfaces` / `mock_only_surfaces` with `require_integration_on_http_surface`, not by typecheck. Stock PHPStan does catch an unknown named argument on a declared signature, for example `new InvoiceLineItemUpdated($item, $qty, recalculateFee: $fees)` (`argument.unknown`).
* **Budget.** The gate answers within `CNS_GATE_BUDGET_MS` (default 30000, the Pi `soma_verify` tool's timeout). The typecheck and tests commands are capped at `budget − elapsed − 2000` ms (not started under 1000 ms). The `/admin/v1/status` probe is paid from it (`budget − elapsed − 2000` ms), and soma then gets `--systemone-timeout-ms = budget − elapsed − 2000` measured again after the probe; under 1000 ms left at either point, the oracle is not attempted. A slow oracle therefore yields exit 3 `not evaluated (... timed out ...)`, not a caller kill. A caller `--systemone-timeout-ms` can only shorten it.
* Soma-initialised repo (`docs/soma` or `.soma/codemap.md`): `axon index` when `.axon/axon.db` exists, then `soma verify` and `soma concerns check --check [--axon <AXON_BIN>] [--systemone --systemone-timeout-ms <ms>] [args]`, all unconditionally. `--check` is never dropped by caller arguments; `--axon-db` is never passed.
* **With the opt-in, the rubric is a requested oracle**. `--systemone` is appended when the caller passes it, or when `/admin/v1/status` reports a healthy System 1 member (same predicate as 5.2). Otherwise the gate prints `rubric: not evaluated (<reason>)` and **exits 3**, never 0 and never `PASSED`: Thalamus unreachable, status non-2xx, not served as JSON, body not JSON, no healthy member (including a System 1 member registered only on another plane), status slower than the budget, or too little budget left. Fail-closed is the point: an operator who wants structural-only gating turns the opt-in off. Only with the opt-in off does the gate exit by the structural result alone.
* With the opt-in and `THALAMUS_URL` unset, the gate contacts nothing, prints `rubric: not evaluated (THALAMUS_URL not set)` and exits 3; there is no default address.
* Exit `0` only when every requested oracle ran and passed; `1` structural, typecheck, tests or rubric red (including `soma verify` failing); `3` a requested oracle was not evaluated: soma binary missing, repo not Soma-initialised, `axon index` failed, soma refused, soma exited 3, a requested typecheck or tests oracle could not run, or the opted-in rubric could not run. `3` wins over `1` whichever is raised first. When both occur the final line names both: `==> CNS Gate NOT EVALUATED (exit 3: <reason>; also red: <red reason>)`; a red that only soma saw (soma exit 3) is taken from its `structural: red (...)` line.
* Appends one `vitals.v1` row with the `cns hook` key set plus `concerns_fired` (a count, or `null` when soma did not run; read from Soma's `fired: <n>` line, which since Soma 1.1.9 may end in a coverage note such as `fired: 0 (no_code_hunks)`), `oracles_requested` and `oracles_evaluated` (arrays of oracle names in pipeline order `structural`, `typecheck`, `tests`, `rubric`; `rubric` is requested when opted in or when the caller passed `--systemone`; an unknown requested name is listed last), and `evaluated_red` (true when an evaluated oracle was red, even if the exit is 3). `cns status` prints both lists after the `soma/gate` line and renders a row with `oracles_requested` not contained in `oracles_evaluated`, or either field not an array, as `NOT_EVALUATED` (red) unless its `exit` is 1 (a red verdict, such as a rubric skipped after a typecheck red), which renders `FAILED`; rows without `oracles_requested` (hook rows, older gate rows) are judged by `exit`. The row also has `organ: "soma"`, `event: "gate"`, `exit` = the gate's exit, `missing_binary: true` when soma is absent. **A quiet gate (`concerns_fired: 0`, exit 0) is a genuine clean result and renders `PASSED` (green).** `vacuous: true` is reserved for a requested oracle that produced no verdict (every exit-3 gate), which renders red.
* The row also carries `tree_sha256`: SHA-256 of `HEAD`, the binary diff against it and each untracked file's path and content, outside `.cns/`, `.soma/`, `.axon/` and `.engram/` (`null` outside Git). It is also `null` when the caller passed any argument Soma receives (`--base`, `--head`, `--delta`, `--axon`, `--format` ...): such a gate did not gate the tree as a plain `cns gate` does, so 5.7 cannot reuse it. 5.7 reads it.

### 5.7 `cns gate --stop-hook` (writer of `soma/stop-gate` rows and `.cns/stop-gate-state.json`; reader: the harness)

`cns gate --stop-hook --harness <claude|codex|agy|pi>` reads the harness's Stop payload on stdin (`session_id`/`conversationId`, `stop_hook_active`/`continuationActive`, `cwd`/`workspacePaths[0]`, `terminationReason`, `fullyIdle`, `error`), runs from the Git top level of that directory, always exits 0 and prints only the harness's decision on stdout.

| Situation | Decision | Runs |
| --- | --- | --- |
| A non-empty `error`; `fullyIdle: false`; a `terminationReason` other than `NO_TOOL_CALL` (Antigravity: `USER_CANCELED`, `MAX_INVOCATIONS`, `MAX_FORCED_INVOCATIONS`, `MAX_TOKEN_BUDGET_EXCEEDED`, `ERROR`, `EARLY_CONTINUE`, `TERMINAL_STEP_TYPE`, `TERMINAL_CUSTOM_HOOK`, `INJECTED_RESPONSE`) | allow | nothing, no row |
| Not Git; no change outside CNS state | allow | nothing, no row |
| No change outside CNS state, and the stored count is above 0 or the newest `stop-gate` row did not exit 0 (fixed and committed after a blocked or released stop) | allow | nothing; count reset, an `allow` row with exit 0 |
| The newest `soma/gate` row with this `tree_sha256` exited 0 with the same `oracles_requested` | allow | nothing; a `stop-gate` row |
| Not Soma-initialised, or no authored concern | allow | nothing, no row (the gate could only exit 3) |
| `cns gate` exits 0 | allow | the gate; attempt count reset |
| `cns gate` exits 1 or 3, attempt ≤ `CNS_STOP_GATE_MAX_RETRIES` (default 3) | block with the gate report | the gate |
| The attempt after that | allow with a warning, `stop_gate_exhausted: true` | the gate; count reset |

* Block: Claude Code and Codex `{"decision":"block","reason":"<report>"}`; Antigravity `{"decision":"continue","reason":"<report>"}`; Pi (`harnesses/pi/cns-extension.ts`, `agent_before_settle`) a `cns-gate` custom message and `continue: true`. Allow: no output (Antigravity `{"decision":"stop"}`); a warning is `{"systemMessage":"..."}`.
* The count is per session in `.cns/stop-gate-state.json` (`session_id`, `attempts`, `last_tree_sha256`). It restarts when the session changes, when the payload says `stop_hook_active: false` or `continuationActive: false` (a new stop sequence or user turn, not a continuation), after a pass, after a release and on a clean tree. A payload with an empty session id reuses the stored count only when it says it is a continuation (`true`), so unrelated sessionless stops never share one.
* Row: `{v, ts, organ: "soma", event: "stop-gate", harness, exit (the gate's, 0 when skipped), duration_ms, decision: allow|block|release, attempt, max_retries, tree_sha256, stop_gate_exhausted, usage_error: false, nonce}`.

---