# Constitution

The load-bearing rules for `centrs`. Everything else (per-command READMEs, the
matrix, code, tests) must be consistent with this file. If something here is
wrong, fix it here first, then propagate. If a rule needs an exception, add the
exception here — not in scattered prose.

This file is short on purpose. Resist the urge to grow it.

It states the rules for what centrs does today and the invariants new work must
respect. Direction that is agreed but not built lives in `docs/MATRIX.md` →
Parked themes, not here. When a theme is selected and contradicts a rule below,
amend the rule first: before the theme's code, or in the same change.

## What centrs is

The RouterOS hub for agents and the tools they drive: a typed library for
RouterOS analysis and **validated** device access, with CLI and MCP frontends
and structured, actionable diagnostics. The TypeScript API
is the root surface; everything else is an adapter over it. The CLI is the
primary and most-audited surface: it needs no configuration, and its `--help`
and envelopes show what centrs offers. The other surfaces keep the same shapes
and differ only where a surface must. The initial consumers are other TIKOCI
tools (see [Consumers](#consumers)), agents working in a project directory, and
developers building integrations or UIs over centrs.

The product is *not* "REST/SSH/native API wrappers." The product is
**validation + structured envelopes + identity resolution** on top of those
transports. Without those, this is a worse `curl`.

`explain` is shared analysis across transports and a useful offline capability
in its own right. It exposes source structure, facts, uncertainty, and evidence
without executing the input. Those facts can support future diagnostics in
other commands' envelopes; that integration is not implemented by declaring
this boundary. Analysis findings do not grant execution permission or replace
the runners' validation gates.

centrs also speaks a small set of MikroTik **peer protocols** that are *not*
RouterOS-command transports — currently the **bandwidth test** (`btest`), which
mirrors `/tool/bandwidth-test` and `/tool/bandwidth-server`. This is a
deliberate, separate capability axis (*measurement*, not "run a validated
command"): centrs still gives structured envelopes, identity resolution, and
friendly errors, but the "validate a RouterOS-shaped command" gate below does
**not** apply to it (see "Validation is the product" and Protocol selection's
`measure` row).

## Validation is the product

Every RouterOS-shaped operation sent to a device goes through canonicalize →
validate → run → re-validate-server-side. Analysis-only `explain` never runs
the analyzed input; offline analysis opens no connection. Validation on the
runners is not optional polish.

The `validate` step itself has **two stages, in this order** (GH#354):

1. **Offline** — the same corpus-gated analyzer `explain` publishes, run over
   the input with no connection (`src/offline-gate.ts`). A rejection is a byte
   span and no round trip; the protocol adapter is never dialed. This stage runs
   on every transport, for `execute` and for `api`'s `/execute` script mode.
2. **Device** — the RouterOS-side probe below: `:put [:parse "…"]` and/or
   `/console/inspect request=child`, depending on the command shape and the
   transport.

The stages are not interchangeable and neither subsumes the other. Offline has
no per-menu schema (decision 3 — no offline schema snapshot), so it cannot see
an unknown attribute; the device probe is version-fragile (GH#343), so where it
is unsafe the offline stage is what keeps the gate from degrading to nothing. A
clean offline pass is **necessary, never sufficient** — `explain` publishes
`runtimeAcceptance: "not-proven"` for exactly this reason. An offline `warn` is
an ABSTENTION and passes through to the device stage; only a `fail` rejects.
The one exception is `discarded-close`: a stray top-level `}` or `]` that the
device accepts and then silently stops reading at (#504). It is a warning,
because nothing is rejected, and the gate refuses it by code
(`src/offline-gate.ts`), because the device would run a different script.

`meta.validation.stages[]` reports what each stage concluded, including a stage
that was skipped and why. A reader must always be able to tell "the device
accepted it" from "the device was never asked".

`meta.validation.result` is a verdict, so it is present only when the gate
produced one. `failed` means the gate refused the request. A failure after the
gate passed keeps `passed`. When something stopped the gate before it gave a
verdict (a `transport/*` or `auth/*` failure, a device error that is not a
gate answer, or a refusal before the gate ran), `result` and the
`syntax`/`semantic` summaries are absent. Each stage the gate did not reach is
then `skipped` with `reason: "not reached: <error.code>"` (GH#435).

The flat `syntax` / `semantic` fields summarize `stages[]`, and each is present
**only when a stage gave that verdict** (#535). Absent means no stage was
asked, never "passed" and never "failed". So `--validate=false` carries
neither. A script has no `semantic` field, because it has no names to check,
and `api`'s structured requests have no `syntax` field, because they run no
`:parse`. On a rejection, `syntax: true` with `semantic: false` is a
name-level refusal (an unknown attribute in a structured command). A `:parse`
or offline refusal is `syntax: false` with no `semantic`. Every gated success
reports its `stages[]`, retrieve and transfer included. `explain` is not a
gate, because it never runs the input: its `meta.validation` is
`{ enabled: false }` with no `result`, offline and live, and its verdict is
`data.verdict`.

`--validate=false` disables **both** stages — one flag, one meaning. A bypass
that covered only the device stage would leave a caller stranded behind a
stage-1 defect with no escape at all, and the analyzer is demonstrably wrong in
both directions today (GH#355 is a live false accept, GH#351 a live false
reject). That is a reason for the flag to reach both stages, not a license to
use it: the rule below still holds — a wrong rejection is fixed in the
validator, with CHR evidence.

- `retrieve` and other read-shaped calls validate against
  `/console/inspect request=syntax path=...,print` (path joined by commas) and
  attribute inspection. The path syntax (commas, no leading slash, last token
  is the verb) is part of the validator contract.
- `execute` and other CLI-shaped calls validate with `:put [:parse "..."]` plus
  a semantic gate. Grounded on CHR 7.23.3 (GH#230), **`:parse` never throws** —
  it returns a script value whose printed form carries the verdict. For a bare
  menu path a clean parse prints `(evl /canonical/path)` with abbreviations
  expanded; for script-shaped input (e.g. `:put …`, `:global …`, `where …`) the
  accepted return echoes the script body and may contain arbitrary text such as
  `expected`. Rejection forms are `(evl bad parameter <name> (line N column M)
  /path)`, `(<%% bad command name <name> (line N column M) …)`, and the
  line-anchored `expected … (line N column M)` (spellings: `expected end of
  command`, `expected command name`, `expected input value`), `missing … (line
  N column M)` (`missing closing brace`, `missing value for where`; GH#375) and
  `syntax error (line N column M)`. Every bare form is anchored at a line start
  with the position suffix, because an accepted return can echo those words. That text rides the **HTTP-200 `ret` value** (REST,
  `as-string`), the native `as-string` `ret`, and the console's printed output
  alike — so a single `:put [:parse ...]` covers both the syntax and the
  **unknown-attribute** gate on every transport. centrs sends `as-string` and now
  reads the `ret`/printed value (the previous gate ignored it, so it rejected
  nothing). Because the accepted return echoes the body, the matcher must anchor
  on the diagnostic shape (the `(<%%` wrapper, or a trailing `(line N column M)`)
  and never on a bare English word — `expected` is also a real
  `/ip/firewall/connection` field name.
  That unknown-attribute check is **name-level only**: `:parse` does not validate
  parameter *values* (`/ip/address/add address=not-an-ip` parses clean). So a
  clean parse is necessary, not sufficient, and value-type plus the remaining
  semantic validation stay distinct steps — `/console/inspect` or the server's
  own re-validation on the write round-trip.
- **Peer-measurement commands (`btest`) are exempt from this gate** — they issue
  no RouterOS command, so they validate *option-grammar* + the **EC-SRP5** auth
  exchange instead (the envelope, identity-resolution, and friendly-error
  contract still hold; only the RouterOS-command gate is absent). The grammar
  rules are in `commands/btest/README.md`.
- A failing validator is a real result. Surface it with the structured error
  envelope below — do not bypass.

There is no `update` verb: generalizing RouterOS add/set/remove into one abstract
write would need too many heuristics, so writes ride `execute`'s
canonicalize → validate → run path while `retrieve` stays read-only (see Protocol
selection). Several writes run as one named operation are a different shape,
parked in `docs/MATRIX.md` → Provisioning.

**Disabling validation to make a call work is forbidden.** If the validator
rejects something a real router accepts, the validator is wrong; fix the
validator with CHR evidence. If a feature only passes its integration test
with `validate=false`, the feature is not done.

The default is `validate=true`. `--validate=false` exists as an escape hatch
for probing undocumented edges, never as a workaround for a centrs bug.

## Result envelope

Every API/CLI call returns the same shape, regardless of transport:

```ts
{
  ok: boolean,                  // true if the operation succeeded end-to-end
  data?: unknown,               // the payload (array of records, single object, etc.)
  warnings?: Warning[],         // non-fatal anomalies (stale cache, unused --cdb-password, etc.)
  tips?: Tip[],                 // advice, not anomalies (no username set, no CDB found, …)
  error?: CentrsError,          // present iff ok=false
  meta: {
    target: { ... },            // resolved target + provenance (where each field came from)
    via: RouterOsProtocol,      // chosen protocol id
    settings: { ... },          // settings winners + sources (env / cli / cdb / default)
    validation?: { ... },       // validator name + result, if validation ran
    timing?: { ... },           // request/response durations
    truncated?: { ... },        // populated when --max-bytes/--max-rows clipped output
  }
}
```

Notes:

- "Success with footnotes" is supported: `ok: true` may carry warnings.
- `warnings` and `tips` are both always present (`[]` when empty) so consumers
  never branch on existence. They are distinct on purpose: a **warning** is a
  non-fatal anomaly about *this* result (stale cache, unused `--cdb-password`); a
  **tip** is advice that is explicitly *not* an error or anomaly (no username
  set, no CDB found, consider a default device). The "this is not a problem,
  just a pointer" signal is the whole reason tips are a separate channel rather
  than folded into warnings. A `Tip` has the same shape as a warning
  (`{ code, message, fix? }`) with `tip/*` codes, and a `details_url` only
  when the tip has a page (`docs/errors/README.md` → Tips).
- CLI render must be lossless against the JSON envelope; `--format json` and
  `--format yaml` are aliases that select serialization, not different shapes.
  Text mode renders tips under a `Tips:` footer, distinct from warnings. This
  lossless rule applies to **stdout** only: **stderr** carries progress and
  interactive prompts (discover scan progress, write/ambiguity confirmation) and
  is exempt — use it sparingly, since most operations are fast.
- **Text stdout is data** (#470). In text mode a single-target `execute`,
  `api`, `retrieve` or `transfer` writes only `data` (or its error) to stdout.
  The notes around it go to stderr: the `--verbose` header first, then one
  `warning [<code>]: <message>` line per warning, then the `Tips:` footer, on
  success and on failure alike. `transport/provider-trust` is left out of text
  because it rides every quickchr run over TLS or SSH. `--json` keeps
  everything, `api --raw` stays a bare payload, and fan-out text is a report,
  not data, so it keeps its warnings on stdout. A text stream writes only its
  data rows (`frame`, `sample`) to stdout; its `started`, `synced` and
  `summary` lines, tips, warnings and errors go to stderr (#473).
- `data` is the only field whose *shape* varies by command. Everything else —
  including `warnings` and `tips` — is invariant in shape; only contents differ.
- **Shared meta is written once** (#461, #462). A fan-out target's
  `meta.settings` keeps only the keys whose source differs from the outer
  `meta.settings`, and its `meta.operation` drops `request` and `auth` when
  they equal the outer operation's. When every target agrees on `auth`, or
  on a setting the outer `meta.settings` lacks, it moves to the outer
  envelope. A reader takes the target's value, else
  the outer one (`expandFanoutTarget`). A stream (`retrieve --follow`,
  `retrieve --sample`, `api --stream`) opens with a `started` line that
  carries the full meta and any request advice in `tips`, and ends with a
  full-meta `summary` (`--follow`'s `synced` is full too). The data lines
  between (`frame`, `sample`) carry only `meta.operation` (#473).

## Error model

Errors are typed values, not thrown strings. Every error has:

- `code` — slash-namespaced, RouterOS-style, no spaces. Example:
  `routeros/unknown-path`, `transport/connection-refused`,
  `validation/unknown-attribute`, `cdb/decrypt-failed`.
- `message` — one human sentence. No stack trace.
- `fix` — one human sentence describing the next step the caller should take.
- `details_url` — pointer to the canonical **per-code** page (the URL scheme is
  in `docs/errors/README.md`).
- `cause?` — structured sub-error, when relevant (RouterOS nova error,
  transport detail). Stack traces and raw exception text are summarized, not
  embedded raw.
- `position?` — RouterOS's `(line N column M)` parse location, when the fault
  carries one (console `:parse` rejections do). `column` is RouterOS's
  authoritative 1-based **byte** offset — the console is not Unicode-aware — so
  it is carried verbatim, never re-derived into a character index.

Credentials and private key material are always redactable. Private key paths are
configuration values and may appear in `meta.settings`; redact them only when an
error also carries sensitive key material or a caller explicitly marks the path
as sensitive.

Two error sources must be visually distinguishable:

1. **centrs errors** — bad usage, validator rejection, transport plumbing.
2. **RouterOS errors** — surfaced by the router (HTTP 4xx/5xx, parse refusal,
   nova error). Map to a normalized `routeros/*` code, preserving the original
   string.

RouterOS faults map to a normalized `routeros/*` code (preserving the original
string) via a CHR-grounded table shared by REST `detail` and native `!trap`
(`src/core/routeros-errors.ts`). Every error's `details_url` is the stable
`https://tikoci.dev/centrs/errors/<code>/`. The mapping shape, the
ground-on-CHR-evidence rule, and the URL-scheme rules live in
`docs/errors/README.md`.

## Settings precedence

Lowest to highest priority:

1. Built-in defaults
2. Config file: `${XDG_CONFIG_HOME:-~/.config}/tikoci/centrs.env` — optional
   dotenv-style `CENTRS_*=value` **global** defaults (centrs-only preferences
   with no per-device home; **not** an inventory or credential store — per-device
   settings stay in the CDB). Applied as fallbacks, never injected into
   `process.env`. The `centrs settings` command is its front-end; the file
   mechanics, `--skip-env-file`, and the settings-key vocabulary live in
   `commands/settings/README.md`.
3. CDB comment-kv metadata
4. Environment variables (`CENTRS_*`)
5. CLI flags / API call args

`meta.settings` reports the winning source for each resolved setting.

### Identity and CDB

The `<router>` argument may be an IP, a DNS name, a MAC, or an **identity**
(the device's `/system/identity`); centrs resolves it through the CDB (then
through ARP / MNDP-derived metadata as fallbacks, once implemented). Two
principles are load-bearing:

- **Record identity is the `(target, user)` pair** — matching WinBox, the same
  address saved under a different user is a second record, not an update.
  `group` is a flat attribute, never part of the key.
- **The CDB is both the device datastore and the credential store.** The WinBox
  CDB file at its well-known location *is* the inventory, and the only durable
  one. Anything else centrs keeps (today the in-memory MNDP cache) is derived,
  deletable and secret-free, and no code path may require it to exist.
  centrs-specific meaning is overlaid through an allowlist of comment-kv keys —
  the lookup keys `identity=`/`mac=`/`ip=` (the one sanctioned exception to "the
  comment is free text") plus override keys like `via`/`port`/`ssh-key`; every
  other comment token stays inert. **Anything expressible in the CDB must also
  be expressible via env/CLI/API**, so tests and ad-hoc use never require one.
  `dude.db` import is out of scope (→ `tikoci/donny`).

The lookup-key grammar, the CDB resolution and ambiguity rules (`--match`,
`identity/ambiguous`, `--prefer-family`), the comment-kv allowlist, encrypted-CDB
handling, and the atomic write strategy live in `commands/devices/README.md` —
`devices` is the registry command and the CDB's only writer. Every CDB mutation
is checked against the revision it was loaded from, under a cross-process lock:
a stale snapshot is refused with `cdb/conflict`, never two successes with one
change lost (#581).

#### Default-device record (`__default__`)

A reserved CDB record (`target=__default__`) supplies fallback metadata +
credentials, **per field**, for a resolved device whose own record leaves them
unset. Precedence is per-field: per-call args → env (`CENTRS_*`) → matched device
record → `__default__` → built-in default. It is **core** (honored by CLI, API,
and MCP) and **never widens the MCP allowlist**: on MCP an unregistered target is
still `cdb/target-not-registered`, and `__default__` only fills *missing* creds
for an already-registered device. Create/edit it like any record; mechanics and
examples are in `commands/devices/README.md`.

Group selectors (e.g. `--group prod-edge`) target CDB groups so a single
`retrieve`/`execute`/etc. fans out to multiple routers. Group output shape
must round-trip through the same envelope.

#### Target selection grammar

One grammar across every non-terminal command. A call selects targets from any
mix of: `<router>` positionals (one or more), repeatable `--group <name>`,
`--all` (every CDB record, **excluding** the reserved `__default__` record),
`--default` (the `__default__` record), and repeatable `--where <attr>=<value>` —
a **device-class** selector that matches CDB-stored facts/comment-kv **plus core
record fields** (`target`/`identity`/`group`/`mac`; core fields win so a comment
token cannot spoof them), AND-combined across repeats. A call is in **fan-out
mode** when any selector flag is present **or** more than one positional target is
given; a plain single-positional call stays single-target. The union is
**de-duped by CDB record index** (ad-hoc literal targets by host) and run through
the same per-target pipeline. With no `<router>` positional and no selector, the
`--host` **flag** stands in for the target: a single target with no CDB lookup,
so no record credential applies. The env var `CENTRS_HOST` never changes how
positionals split. Each command README states where its `<router>` slot ends.

Fan-out output is the locked **`FanoutData`** envelope: `data = { summary, targets[]
}`, where the outer `ok` reports **orchestration** success and a per-target failure
is an inner `ok:false` envelope (output, not metadata). `targets[]` is reassembled
in resolved record order, not completion order, so repeated runs diff cleanly. The
**process exit code** is granular and uniform across fan-out commands: `0` every
target ok (or an empty selection for a read), `2` partial (some ok, some
failed), `1` orchestration error or every target failed. An empty selection is
a warning for a read and an orchestration error for a write, `--yes` or not,
so a mistyped selector never passes for a successful bulk write (#460).

A multi-target **RouterOS write** (e.g. `execute` / `api` add/set/remove across a
selection) is gated by **`--yes`**, confirmed **once** up front; when it is missing
the error names the blast radius (how many routers). A write that was **sent** is
never retried, because it may already have run; it fails with the warning
`transport/write-outcome-unknown` instead (#448). The separate **`--force`**
gate is scoped to destructive **`devices` CDB mutations** (e.g. `devices remove`
across a group), not RouterOS writes. `terminal`, `api --stream`,
`retrieve --follow` and `retrieve --sample` are single-session, not fan-out
surfaces, and reject N>1 with `usage/fanout-not-supported`; `api --raw` is rejected in fan-out mode with
`usage/conflicting-flags` (it strips the per-target envelope).

`--where` filters *which devices* by CDB-stored facts; keep it distinct from
`retrieve`/`execute`'s `--query`/`--filter`, which filter *RouterOS rows* in the
response. Two layers, two flag families. `--near <lat>,<lon>,<radius>` and
`--bbox <south>,<west>,<north>,<east>` are geo union predicates over device GPS
(**lat-first, decimal degrees**; radius units `m`/`km`/`mi`/`ft`, bare = km);
geo-less devices never match. They join the same union — a device matches when it
falls in `--near`'s radius **or** `--bbox`.

`--group` is purely a **selector** in this grammar; the group *field* is written
by a distinct `--new-group` flag on `devices add`/`set`, so record selection and
field-setting never collide on one flag.

#### Resolution providers

Target resolution has **two independent axes**, and centrs keeps them separate so
the resolver is generalized **once**, not per source (the umbrella plan is #174):

- **Axis A — selection** ("which devices"): the target-selection grammar above.
- **Axis B — connection-fact origin** ("where host/port/auth for a member come
  from"): what a resolved member yields. Today: a **CDB record** or an ad-hoc
  **literal** (+ the `__default__` ladder). Tomorrow: a live descriptor or an
  inventory entry.

Sources fall into two kinds, and the distinction is normative:

- **Selector-source** — participates in the Axis-A grammar. **CDB** is the only
  one today; TikTOML (#137) was closed, and other inventory sources are parked
  under MATRIX → Devices and onboarding. Multiple selector-sources would union
  into one selection; their precedence is decided when a second source lands.
- **Named-live-provider** — addressed *only* by an explicit named flag, **never**
  matched by a selector; fanned out by repeating the flag. Because it owns an
  **ephemeral** endpoint it also **bypasses** the settings/`__default__` ladder and
  **conflicts** with `--host`/`--port`/`--username`/`--password`/`--ssh-key`. These
  are properties of *live/ephemeral* providers, not of any one provider. **quickchr**
  (`--quickchr <name>`, #134) is the first. A named-live-provider selection is
  **exclusive** (v1): mixing it with `<router>` positionals or selector flags is
  `usage/conflicting-flags` — one flag stays single-target, repeating it fans
  out. Relaxing exclusivity later is additive.

Connection facts resolve into one neutral **per-service endpoint map**
(`src/resolver/service-endpoint.ts`: `via → ServiceEndpoint`, each carrying
availability, host, port, TLS, auth, and provenance). A **selector-source** is the
*degenerate single-endpoint* case — one record materialized lazily once `--via` is
known. A **named-live-provider** populates the map directly, since it genuinely
exposes different facts per transport. Providers must **not** be flattened to a
single host/port: that shape is the contract quickchr's descriptor maps onto, and
any later inventory source must too; flattening it forces exactly the
re-plumb #174 exists to prevent. A `--via` whose service key a provider does not supply is a
typed unsupported-provider error, never a silent fallback.

#### Controller-mediated selection (CMR)

A **CMR controller** (RouterOS 7.26beta1+) is a third kind of source: a live
inventory whose members centrs never dials. `execute <controller> --cmr
--labels <expr>` (#450) resolves the **controller** as an ordinary single
target, and only its credentials are used. RouterOS's label expression selects
the members, and the command runs on each through the controller's
`run-script`. Normative:

- CMR is a selection source, **not a protocol**. `--via` pins the controller
  transport, and a CMR failure never falls back to dialing a client.
- A member is bound by the controller's row id, never by its display name. A
  result that cannot be bound to the member it was validated on is not run, or
  is reported as an unknown outcome.
- Validation runs **on each client** (`:parse` through CMR) and must be complete
  before it counts. A client that fails validation is never sent the command,
  and an incomplete selection runs nothing.
- A CMR dispatch is **never retried**. A timeout, cancellation or lost call
  after sending is `cmr/outcome-unknown`, because the client script may still
  be running.
- CMR mode is not on MCP until delegated authorization is designed (#449).
  Registering a controller must not authorize its clients.

The contract and its device evidence are in
[`commands/execute/README.md` → CMR](../commands/execute/README.md#cmr-clients-through-their-controller---cmr).
Which surfaces touch CMR, and how centrs follows its beta builds, is in
[`components/cmr/README.md`](../components/cmr/README.md).

### MCP surface: the CDB is the allowlist

The MCP frontend (`commands/mcp/`) is an adapter over this core, not a new set of
RouterOS semantics. Two boundaries are load-bearing:

- **Authorization is the CDB allowlist.** RouterOS-facing tools resolve targets
  through the CDB only; an unregistered target is rejected
  (`cdb/target-not-registered`), and `__default__` never widens the allowlist (see
  Identity and CDB). The off-by-default `--allow-adhoc-targets` flag is reserved
  for future inline-target flows — today no RouterOS-facing tool exposes an inline
  host+credential schema, so the CDB allowlist is the only active target source.
- **Transport is stdio only.** HTTP/remote access belongs to a separate remote
  surface that fronts the same CDB; none is built yet, and its shape is open
  ([MATRIX → Components](MATRIX.md#components)). The MCP server grows no
  listener of its own, so one surface owns network exposure.

The scoped tool surface (verbs mirroring the CLI/API, never one tool per RouterOS
command), the per-device `mcp=ro|rw` + `confirm: true` write gate, the
`centrs://devices` / `centrs://errors` resources, and the full safety model are in
`commands/mcp/README.md`.

## Protocol selection

Per-operation preferences, downgrade order in parens:

| Operation | Preferred | Downgrade order |
| --------- | --------- | --------------- |
| retrieve  | rest-api, native-api (`--sample` too); `--follow` native-api only | rest-api, native-api (`--follow`: no downgrade) |
| api       | rest-api, native-api; `--stream` and `/listen` native-api only | rest-api, native-api (no silent downgrade) |
| execute   | native-api → rest-api → mac-telnet | native-api, rest-api, mac-telnet, ssh, romon, winbox-terminal |
| terminal  | ssh | mac-telnet (L2 only when ssh fails or MAC given) |
| transfer  | size/direction-aware: rest-api/native-api for ≤60 KB writes & all reads (chunked), sftp for large uploads | sftp ⇄ rest/native by size; scp · fetch · ftp explicit-only |
| discover  | mndp | (not a transport for command operations) |
| measure   | btest | (explicit-only — no downgrade) |

Rules:

- **Read vs write:** `retrieve` is read-only (rest-api/native-api); `execute` is
  the read **and** write surface — writes (add/set/remove) ride `execute`.
- **Never silently downgrade across `--via`.** If the caller pinned a transport
  that cannot do the operation, error out with a `transport/*` code.
  Auto-selection (no `--via`) may downgrade *within* the table, but every hop is
  reported in `meta.warnings` with its reason. For `api`'s fan-out path, this
  and "Validation is the product" above are also checked structurally by
  CodeQL (`.github/codeql-house-rules/missing-required-gate.ql` —
  `apiFanout` must call `assertApiProtocolSupported`/`validateApiRequestShape`;
  scoped to `apiFanout` only today).
- **Execute vs retrieve surfaces:** native-api, rest-api, ssh, mac-telnet (and
  later RoMON / WinBox Terminal) are execute surfaces. mac-telnet is the
  default execute path for an unresolved-MAC target — IP-level access needs
  explicit ARP opt-in.
- **`measure` (btest) is explicit-only** — never in the auto-select/downgrade
  chain, never a substitute, and no other command rides it.
- Per-command selection **depth** lives in the command READMEs: `api`'s
  literal `--stream`/NDJSON contract and the REST-cannot-follow constraint
  (`commands/api/README.md`), `transfer`'s size/direction-aware method
  selection and the explicit-only `scp`/`ftp`/`fetch`
  (`commands/transfer/README.md`), and btest's port/auth
  (`commands/btest/README.md`).

REST-specific constraint: RouterOS REST has a 60-second hard timeout. Do not
let `--timeout` exceed 60s when `via=rest-api`; reject with a clear error.
Other transports may accept longer timeouts, but some RouterOS commands carry
their own reply limit that `--timeout` cannot extend: over native API,
`/execute as-string` (every `execute` script) and `/container/shell` drop
their reply at about 60 s (`routeros/action-timed-out`, #639; measured limits
in `commands/execute/README.md`).

### Transport trust (TLS / SSH host keys)

One opt-out across every transport: `--insecure` (`CENTRS_INSECURE`, CDB
`insecure=` comment-kv). Default is **verify**; `--insecure` disables peer
verification and adds a `transport/insecure-trust` warning to the envelope so the
downgrade is always visible. Because RouterOS ships **self-signed** certificates
and host keys, the *default posture per transport follows that transport's
ecosystem norm* rather than one literal value:

- **TLS** (REST `https`, native-api `api-ssl`) **verifies** by default; a
  self-signed cert fails with `transport/tls-certificate` whose remediation names
  `--insecure`. (Both transports honor the same knob — previously native-api
  silently accepted any cert; that is fixed.)
- **SSH host keys** (sftp/scp) default to **trust-on-first-use**
  (`StrictHostKeyChecking=accept-new` into the user's `known_hosts`): a new key is
  accepted, a *changed* key fails with `transport/host-key-mismatch`. `--insecure`
  disables the check entirely. TOFU is the universal SSH norm, so the SSH default
  is laxer than the TLS default by design.

SSH identity selection: the `sshKey` setting (`--ssh-key`/`CENTRS_SSH_KEY`/CDB
`ssh-key=`) carries a private-key **path only** — never key material; when unset,
the host SSH agent / `~/.ssh/config` is used. Batch SSH clients (sftp, `execute
--via ssh`) run `BatchMode=yes` and never send a password, so key auth is the
only batch path. Separately, RouterOS refuses SSH password login once a user has
a key (`/ip/ssh password-authentication=yes-if-no-key`, the default).

## Done definition

Done requires executable evidence for the capability being claimed. Device
operations and live analysis require **green CHR integration tests** against a
real RouterOS CHR booted by `@tikoci/quickchr`, via `bun run test:integration`.
Code existing or unit tests passing cannot establish live behavior. This is
the **normative** done definition; `AGENTS.md` and
`.github/instructions/done-definition.instructions.md` point here (the latter
carries the Copilot-workflow procedure for satisfying it).

Offline analysis is `verified` when its applicable examples and contract
checks pass without a router, its RouterOS semantic claims have committed
CHR-grounded evidence, and the baseline acceptance criteria in its command or
component README are satisfied. New or changed RouterOS semantics still require live grounding
with accepted and rejected controls plus a reproducible capture/replay path;
offline tests do not establish new device facts. Changes to shared execution
or transport behavior still require `bun run test:integration`. The offline
call itself never needs a router merely to satisfy a workflow label.

`CHR-passed` means every example in a capability's `examples.md` is green via
`bun run test:integration` against CHR. The one exception is a command that
does no network IO (`devices`, `settings`): its examples are fixture-backed
integration tests that need no CHR, under the evidence contract in its command
README. Either way, `CHR-passed` does not mean the capability is finished;
follow-on work is a parked theme, a nit or an issue.

`docs/MATRIX.md` owns capability status, the current track, parked themes and
nits. A capability's acceptance criteria — like `explain`'s Offline baseline
acceptance — live in its `commands/<name>/README.md`, or in
`components/<name>/README.md` for a part that spans commands; GitHub issues own
the actionable tasks that satisfy those criteria, not the criteria themselves.
Status advances only with matching evidence in the same change.
Record test names, fixture provenance, and CHR versions where applicable.
Offline verification never advances a live protocol cell to `CHR-passed`.

## Boundaries

centrs does:

- Analyze RouterOS source independently of a connection, preserving ordered
  structure, source locations, evidence, and ambiguous/unknown readings.
- Resolve devices/groups from explicit input, env, CDB, MNDP cache.
- Choose protocols per the table above and configure them.
- Validate before execute; re-validate server-side immediately before run.
- Return structured envelopes with provenance and warnings.
- Use the WinBox CDB at its well-known location as the durable device
  datastore; overlay centrs metadata via comment-kv and groups.
- Speak MikroTik peer-measurement protocols on explicit request — the bandwidth
  test (`btest`), as both client and server — with the same envelope / identity /
  error contract (but not the RouterOS-command validation gate).

centrs does not:

- Replace RouterOS syntax with high-level configuration helpers. Normalized
  representations that preserve its semantics are in scope; reconstructing
  final device state or predicting network behavior is not an offline parse claim.
- Treat passive discovery (MNDP) as authoritative inventory.
- Run write-shaped operations without an explicit target and validation policy.
- Make generated output the hand-edited source of truth.

### Network listeners

centrs opens a network listener in exactly two sanctioned places: a future
**remote** surface (HTTP / remote access; not built yet) and the **btest server**
(`centrs btest server`, TCP/UDP port 2000). The btest server is an **explicit,
foreground, user-invoked** command — not an always-on daemon, and not the remote surface.
It **binds loopback by default** (`--bind` to expose), **requires auth by
default** (`authenticate=yes`, mirroring RouterOS), and is security-sensitive
surface: treat credentials as redactable (`SECURITY.md`). The MCP server stays
stdio-only and grows no listener of its own.

## Invariants

- One settings vocabulary across API/CLI/MCP and any later surface.
- Friendly, structured errors are part of the API contract — not optional polish.
- Help text, source reporting and redaction are shared-core, not
  per-frontend.
- Integration tests prefer real CHR via `quickchr` over elaborate mocks when
  behavior depends on RouterOS.
- Generated docs are preferred when the source of truth is code, CLI metadata,
  or schema.

## Consumers

Repos that build on centrs and file issues against it:

- `tikoci/routeros-muse` — web console prototype over TIKOCI RouterOS tooling;
  its dashboards raised the transfer-methods theme.
- `tikoci/app-t3code` — a RouterOS `/app` container for T3 Code that uses
  centrs. It is under active testing, so expect issues from it that find gaps.

How their issues become work is in `AGENTS.md` → Where work is tracked.

## Adjacent projects (grounding sources)

- `tikoci/rosetta` — RouterOS docs / RAG.
- `tikoci/restraml` — REST schema and inspect output.
- `tikoci/m2ir` — protocol IR (WinBox, etc.), and the home for the
  declarative "schema-as-data" approach to representing protocol internals
  (consult it when WinBox-terminal / RoMON / heavy protocol work lands, rather
  than hand-rolling protocol knowledge in centrs). Not an accessible source for
  the RouterOS error-string vocabulary; ground error mappings on live CHR
  strings.
- `tikoci/lsp-routeros-ts` — canonicalization, parse-validation patterns.
- `tikoci/vscode-tikbook` — peer RouterOS front-end (notebook UX); a source for
  run-time error-string mapping (faults that pass `:parse` but fail at run).
- `tikoci/quickchr` — CHR-backed integration test harness.

When one of these owns a question, defer to it instead of restating here.

External reference implementations to compare centrs protocol/transport work
against (SSH patterns, native-API behavior, CDB format, WinBox framing) are kept
as bibliography entries in `GLOSSARY.txt` — e.g. `netmiko`,
`terraform-provider-routeros`, `librouteros-api`, `RouterOS_Tools`,
`Winbox_Protocol_Dissector`.

### Canonicalizer ownership

centrs owns the **script-vs-structured execution gate** — the load-bearing
discriminator for validation and transport shape; widening what counts as
`structured` is a product regression. Write confirmation is a separate,
fail-closed safety predicate over the original CLI string: falling back to raw
script transport must never turn a write into a read. The shared,
pure command canonicalizer that `rosetta` / `lsp-routeros-ts` publish is for
canonicalization only, never the structured-mode predicate. The gate contract,
its pinning test, and the parser-vendoring preconditions are documented in
`commands/execute/README.md` and the `canonicalizeExecuteCommand` doc-comment
(`src/execute.ts`).

Richer schema-free analysis must distinguish **ambiguous** (multiple plausible
readings) from **unknown** (no safe reading) and abstain in both cases rather than
inventing a command, path, symbol class, or transport mapping. These explain-only
verdicts never widen or reinterpret the execution gate's `mode`. The execution
safety predicate remains deliberately conservative and independent of richer
explain-only inference.
