Skip to main content

Sentin8:CLI - Detailed Design Document

Wire-level construction of sentin8-cli. The overview lives in README.md; the operator capability list in BUSINESS.md.

1. Scope & Context​

The CLI is the bootstrap + enrollment + control starter. It links ONLY the SDK plane (invariant - starters never link services) and executes two kinds of authority:

  • Database-plane authority (pre-identity): db bootstrap and vertical init run SQL directly as the DDL superuser - the only credential available before Sentin8:Auth exists. db bootstrap is the ONLY command that applies platform SQL; it refuses when the sys.platform_bootstrap scout exists (the database has exactly two states).
  • Identity-plane authority (post-identity): every other command (enroll, captain control, secrets, service commands) requires a signed-in operator (device-flow bearer) and calls owner APIs / the captain API - never direct SQL.

2. Runtime Architecture​

ModuleRole
main.rs / lib.rsCommand tree (clap); boot-time helpers.
auth.rsDevice-flow operator sign-in (PKCE, token persistence + refresh); get_valid_token_blocking.
db.rsdb bootstrap (migrations/platform.sql + public_helpers.sql, scout-gated), db migrate (--sql-dir service SQL), db seed-listings.
vertical_registry.rsComposable enrollment: read --print-registration -section=… JSON from each repo, merge fragments per vertical, upsert registry tables (sentin8_vertical_services, admin scopes, policies, relations, schedules (SDD §2.4), error codes, consent providers, app store listings, captain catalog entries, Valkey keys) - idempotent.
captain.rsFleet control: start/stop/restart, per-instance restart/stop/start/upgrade (+ UDS transport), status tables, autoscaler view + approve/reject, captain place (hand placement).
transport.rsCaptain transport resolution: local UDS (SO_PEERCRED) when on the same machine; HTTP for remote hosts.
commands.rsDeclarative service commands - subcommands resolved from the registry (service_commands table), no hardcoded per-service command list.
secrets.rs, func.rs, infra.rsSecret-reference management, func tooling, infra helpers.
infra.rs (status probe)Direct PostgreSQL + Valkey probes behind captain services' instance table (never through captain - see §5). PostgreSQL renders version/connection-census/db-size from pg_stat_activity; Valkey renders version/clients/memory/keys/uptime parsed from the INFO reply. The Valkey decode is RESP3-aware: GLIDE negotiates RESP3 by default and INFO replies as a VerbatimString - the parser accepts VerbatimString/BulkString/SimpleString and treats ANY other reply shape as a probe error (a visible unreachable (…) line), never a silent empty summary. Both probes carry a 3s timeout and degrade to a one-line unreachable (reason) - make status never aborts on a down backend; connection URLs render with passwords masked.
call.rsGeneric authenticated HTTP call plumbing.

3. Data Model - what the CLI writes​

The CLI owns no tables of its own; it is the provisioning WRITER for:

TargetWritten byIdempotency
sys.platform_bootstrapdb bootstrap (scout - written ONCE)refuses re-run
Platform roles/schemas/grantsplatform.sql (bootstrap, DO-block guarded)converges (re-run safe)
Vertical databases + schemas + RLSvertical init from per-repo sql/converge-on-apply
sentin8_vertical_services + friendsvertical enrollupsert per (vertical, service)
cron.schedulesvertical enroll -section=schedulesupsert idempotent (SDD §2.4)
Valkey captain:* catalog keysvertical enrollupsert
Operator device tokenslocal credential store (user-scoped)rotate on refresh

4. API/Command Surface​

Command families (see README.md §4): db, vertical, captain, per-service registry-declared commands, secrets.

4.1 captain start [TYPES] - the scope argument contract​

captain start optionally takes ONE comma-separated token string naming the service types to ensure (sentin8:captain,sentin8:acme,auth,bff - legacy hyphen forms are accepted and canonicalized, whitespace is trimmed, empty segments dropped). The handler resolves the typed list and routes it by captain state:

  • API path (captain up): the SPLIT list is posted - the handler looks each token up in the live catalog and spawns missing types. Posting the raw comma-joined string as one element would match nothing ("not in catalog" skip per token) and no-op the whole call - the defect this section forbids.
  • Cold-boot path (captain down): the typed list is re-joined with commas into SENTIN8_SERVICES for the spawned captain - the boot allow-list filters ONLY the boot-spawn loop (D6); the catalog stays the full union so later start-services/per-instance actions can join pruned-at-boot types without a captain restart.
  • Group Makefiles (sentin8 core, the six vertical groups, per-service repos) pass their scope as one comma-joined argument in both branches - the contract here is what makes that argument reach the right consumer every time ('s three-level rule rides on it).
  • captain itself may appear in a passed list without risk: the boot loop skips its own type, and the singleton placement gate refuses any second supervisor spawn.

4.2a The binary-path registration contract (BINPATH-1)​

vertical enroll is the sole resolver and writer of where a service's executable lives. The captain consumes and never searches.

  • Resolve at enroll. Each service's absolute binary path is resolved from the entry's OWN repo dir (RegistryService::source_dir) or a DECLARED path in the fragment (the packaged shape, /usr/bin/{binary}). The SENTIN8_CAPTAIN_BINARY_PREFIX colon-chain is deleted - resolution by probing directories does not exist.
  • Write captain:binary:{service_type}. The resolved absolute path is written beside the other captain:* registration keys, in the same transaction-shaped pass. One writer, one projection, one consumer.
  • Refuse unresolvable. An enroll that cannot resolve a path fails, naming the service and the locations probed. An empty path is never recorded: fail at the contract, not at the process.
  • Platform and verticals, one surface. The platform's own 21 services carry service-registration.json fragments like every vertical, so make enroll and provision-on-boot register them identically. No compiled-in location exists anywhere.
  • provision-on-boot derives from enrollment records, not an env var. The cold-boot pass reads the last-enrolled platform fragment set from the registry (its own Valkey record), then re-runs the same enroll surface; it no longer walks a prefix chain.

4.2 provision-on-boot - declarative enrollment converges at cold boot​

Every cold-boot path of captain start / captain restart (both start_captain_server call sites) runs the platform's declarative enrollment pass BEFORE spawning the captain, so identity rows can never be forgotten after a reset:

  • Why on the cold-boot path: a reset (dev-destroy.sh) destroys the database AND wipes .run/secrets; the identity rows that every cert-auth connection needs (pg_ident.conf pgm map, auth.m2m_scope_grants, Valkey ACL users) all live on the destroyed plane. Provisioning them inside the boot the operator already runs removes the entire "forgot to enroll repo X" class (SIGNENROLL-1/2, the 2026-10-27/28/29 sign + cli-producer crash-loops after every reset).
  • Derivation, not a list: the fragment set comes from the binary prefix the invoking Makefile already exports. A repo joins the boot provisioning by carrying service-registration.json + building - no inventory to update (the enroll lists kept going stale; the derivation cannot).
  • The pass enrolls the PLATFORM's fragments and nothing else. The binary prefix is the captain's whole search path, and a vertical group's prefix legitimately carries that group's own repos, so prefix membership is not the ownership test. Each candidate fragment is therefore filtered by the vertical it declares: sentin8 fragments converge here, every other vertical's fragment is skipped and left to that vertical's own make enroll. Two reasons, both structural. The platform's database is the only one this pass has a DSN for, so a vertical fragment would resolve its binary and then fail to reach its own database mid-boot (observed: email8:mta migration stall aborting the whole pass and leaving the platform unenrolled). And vertical knowledge in the core boot is exactly what principles §4.14 forbids - one vertical's broken migration must never decide whether the platform starts.
  • Idempotent + converged: the pass is the same vertical enroll surface make enroll calls - safe to repeat on every boot (role upserts, file-append dedupe, ACL refresh).
  • The CLI self-describes: the CLI repo now carries its own service-registration.json + --print-registration handler (the same self-registration contract every service rides); its m2m_grants declare cli-producer / cli-delegator / sentin8-cli-tls, so the CLI's workloads provision in the same pass. e2e fixtures seed nothing.

4.3 per-key transport routing - instance ops reach the OWNING captain​

(Captain DESIGN §11.11 - the core appliance profile.) With two captains sharing one registry (the appliance container's on 127.0.0.1, the host's on the LAN IP), an instance key {ip}:{port} names its OWNING machine, and every per-instance operation (stop-instance, start-instance, restart-instance, upgrade-instance) must reach that machine's captain - signaling a process id only works in the captain that owns the pid namespace.

  • Routing rule (the CLI is the router): for a key whose ip matches the appliance identity, the request goes to the appliance captain - over its bind-mounted UDS socket when present (SENTIN8_CORE_CAPTAIN_SOCK, default {run}/core-sock/captain.sock - peer-cred authorized, no bearer), else over TCP (SENTIN8_CORE_CAPTAIN_URL, default http://127.0.0.1:18000 - bearer-gated). Any other key goes to the locally-resolved transport (UDS first, TCP fallback) - the same resolution every other command uses.
  • Enabling: the appliance identity is opt-in via SENTIN8_CORE_APPLIANCE_IP (the Makefile core-up profile exports it). Unset - the default, and every existing single-machine fleet - the appliance branch never engages and routing is byte-identical to today.
  • Captain-side backstop: the appliance captain refuses per-instance actions for keys it does not own (409 naming the owner) - the guard is the direct-API misuse catch, the CLI routing is the well-formed path.
  • captain place needs no change: it already builds a per-machine transport from an explicit target IP (§11.4 remote-spawn path).

5. Cross-Cutting Concerns​

  • The CLI dials fleets it did not start (TLSCLI-1). The CLI installs the CLIENT-shaped TLS provider (install_client_provider, tls README "Two installers, two postures"), not the mode-keyed platform one. The difference is the key-exchange OFFER: the platform provider matches the fleet it runs inside and reads SENTIN8_TLS_PQ_MODE from its environment, but the CLI is an operator tool that may be installed on a provisioned host with no env file - config::pq_mode() falls back to exclusive (ML-KEM only), and against a classical fleet that offered no shared group: every HTTPS call died with alert 40 (handshake_failure) while openssl s_client reached the same host instantly. The client provider offers the SUPERSET (ML-KEM first, classical fallback) and reads no environment, so one binary negotiates with every posture. Verification posture is unchanged in both: the PQ algorithms are grafted in either way, and an untrusted anchor fails closed.

  • Auth states: 's two-state contract - pre-identity commands work only with the DDL superuser; post-identity, every CLI action requires the signed-in operator. db bootstrap refuses to run on an initialized platform (the scout + table-presence guard also catches half-finished bootstraps).

  • SQL loading: platform SQL is embedded (include_str!); service SQL is runtime-loaded from --sql-dir paths (the CLI binary stays decoupled from any service's schema).

  • Registration consumption: the CLI never hardcodes a service's surface - every service self-describes via --print-registration sections (service, admin_scopes, policies, relations, m2m_grants, schedules, admin_ui, error_codes, consent, pg_roles, commands).

    A probe is never silently skipped. The probe returns one of three outcomes and only the first two are non-fatal:

    OutcomeMeaningEnrollment
    Some(json)the binary answered; [] means the service declares nothingcontinues
    None (binary absent)the declared binary is not built on this host - the legacy registry-JSON row covers the servicecontinues, reported
    errorthe binary resolved but did not answer correctly (non-zero exit, timeout, non-JSON, or empty stdout)aborts

    An empty stdout is fatal because the shell's printer always emits JSON - a Vec serializes to [] for a section the service does not populate - so zero bytes can only mean the binary never ran the flag. A service that resolves its binary and then contributes no self-described section is also fatal: it appears in the registry but described nothing.

    The fragment's directory is retained for binary resolution. Composable enrollment merges fragments into a temporary aggregate, so the aggregate's parent is not any service's repo. RegistryService::source_dir is stamped from the fragment's own directory at load time (mirroring RegistryApp::source_dir) and is the FIRST candidate in resolve_binary_path; this is what makes a repo-scoped make enroll resolve {repo}/target/<profile>/<binary> without depending on an exported prefix. The field is omitted from serialization when empty, so legacy aggregate files stay byte-stable.

  • Captain control channel: UDS with kernel-proven SO_PEERCRED for same-machine control; Shield-gated HTTP for remote; captain place builds a per-machine HTTP call .

  • Secrets posture: the CLI never stores DSNs or secrets it provisions

    • they live in the operator env (.env) and flow via database_env_vars declarations at spawn; the device-flow token store is user-scoped.
  • Operator env loading: every CLI subcommand loads the tree-root operator .env via dotenvy::dotenv() - and scripts/dev-destroy.sh (the destructive local reset,) sources the SAME file explicitly before its first step, refusing loudly when absent: the script's maintenance connection (certificate identity, postgres-ops pair) and its captain stop precondition must behave identically from a fresh shell and an operator session, and a half-destroyed workspace (fleet stopped, databases untouched) must never result from a missing environment.

  • The dev reset drops ALL data but re-initializes ONLY the platform core (boot scope from / RS §4.5.2): dev-destroy.sh is a FULL-TREE data reset - every non-template database on the dev cluster is dropped: vertical databases (bank8, hotel8, …) first, enumerated vertically-agnostically from pg_database (the script never names a vertical, AGENTS rule 1), then the sentin8 platform database is dropped and recreated. The platform database carries the registry tables, so the reset also un-enrolls every vertical by construction. Vertical _service ROLES survive on the cluster (they are passwordless certificate-identity rows; the vertical's own vertical init/vertical enroll converges them idempotently), while the sentin8_*_service platform roles are dropped for re-seeding. Re-initialization covers the CORE PLATFORM ONLY: db bootstrap, the platform-fragment enrollment, and the post-bootstrap captain start - which runs under the platform-core SENTIN8_SERVICES pin (spawning a vertical service against its dropped database would crash-loop it). A vertical re-joins the fresh platform via its own group vertical init && make enroll && make start at the operator's choice; the dropped vertical state is disposable by design (greenfield data).

  • The dev reset is a PURE INFRA reset (the 2026-10-30 reset-friction revision - RESETS §4.9a): dev-destroy.sh owns ONLY the infrastructure plane. Its four steps are (1) stop the fleet (captain graceful, never pkill), (2) docker compose down -v for the tree's compose project - the named sentin8-pgdata/sentin8-valkeydata volumes are DELETED, so the cluster comes back virgin (fresh initdb, role sentin8 + db sentin8, zero service schemas, zero Valkey ACL state), (3) re-run the infra-TLS material pass (make infra-tls semantics: re-mint/confirm leaves + republish the CA chain + RESEED pg_hba.conf/pg_ident.conf, which the enroll pass appends to at runtime), (4) docker compose up -d and wait for BOTH healthchecks green. The script touches NO database content, runs NO psql, NO db bootstrap, NO vertical enroll, NO db finalize, and NO captain start - database convergence moved to the operator's normal flow, which now bootstraps automatically: make enroll and make start both run a bootstrap-if-needed step (db bootstrap when the sys.platform_bootstrap scout is absent) and then converge enrollment (the cold-boot provision-on-boot pass / the explicit enroll pass). Rationale: the OLD script interleaved infra-destroy with database-converge, so a failure in one poisoned both planes and every retry re-entered a half-destroyed workspace with no clean re-entry point. The new split gives every plane ONE owner - destroy owns infra, enroll/start own convergence - and the two commands become individually re-runnable: a failed enroll is retried by running make enroll again (idempotent upserts), a failed boot by make start again (provision-on-boot re-runs the same pass).

  • Fresh volume ownership (the initdb EPERM class): compose named volumes are created root-owned while both infra containers run as the HOST user (user: "1000:1000" - the 0600 TLS material demands it), so a virgin PostgreSQL volume crash-loops initdb with Operation not permitted and Valkey cannot open its AOF. The reset fixes the ownership deterministically between up -d and the health wait (docker run --rm -v <vol>:/d alpine chown 1000:1000 /d for both volumes, then one container restart so initdb re-runs against the fixed permissions) - never by hand after a crash-loop.

  • Enrollment is ORDER-INDEPENDENT (the phase split): registry order is not a dependency order - for migrations the same way it already was for grants and policy seeding. vertical enroll now runs in phases: phase 1 creates every role and COLLECTS each service's --print-registration sections; phase 1.5 applies every service's pending SQL migrations in a FIXED-POINT convergence loop (a migration failing because a sibling's table does not exist yet - ai seeds stat.properties, stat sorts later - is DEFERRED and retried; a full round with zero progress fails loudly naming the stalled service(s), never a silent partial enroll); phase 2 registers the rows (sys.vertical_services, admin scopes, error codes, consent, findings, actions, auth.m2m_scope_grants, CLI commands, Valkey ACL users + registry map entries) AFTER the SQL converged - the m2m grant upsert targets auth.m2m_scope_grants, a table auth's own init.sql creates, so registering inline on a fresh database skipped every grant row with a warning and left the workloads DCR-dead until a second enroll run. The convergence loop replaces the old hand-curated enroll order (the stale-list class): make enroll derives its fragment list from the repos carrying service-registration.json, and any new service enrolls correctly regardless of sort position.

  • Role search_path is a VALUE check, never a row check (the inverted guard defect): enroll fills a fresh service role's search_path (ALTER ROLE … SET search_path = {leaf}, {vertical}, public) only when the role has no search_path VALUE. The former row-shaped check (fetch_optional on pg_roles) always returned Some((None,)) for every existing role - the ALTER never ran for a fresh role, every reset re-created the platform's service roles with NO search_path, and every unqualified query in the service binaries crashed (FROM signing_keys on auth, the recurring post-reset crash-loop). The fill is also LOUD: the ALTER result is printed or warned, never swallowed. Roles whose search_path platform.sql declares (acme/web/proxy/captain, the bootstrap tier) keep theirs - the fill never clobbers an owned path.

  • **The dev reset force-recreates BOTH infra containers : ** the reset recreates the whole .run/secrets tree (infra TLS material, CAs), and Docker Desktop/WSL bind-mount hashes freeze at container-creation time - a container whose bind-mount source was replaced underneath it sees empty/stale mounts until recreated (observed: postgres initdb EPERM crash-loop; valkey unhealthy probe streak with an empty /tls). The script therefore runs docker compose up -d -force-recreate for the group's compose project (both services) after the drop phase - never a per-container patch, and never from a service process.

  • Infra probes bypass captain by design (infra.rs): captain owns the Valkey service registry and intentionally has no PostgreSQL dependency - it must boot and report status even when PostgreSQL is down. The CLI probes the backends directly over the operator env (DATABASE_URL / VALKEY_URL), so a saturated or unreachable backend surfaces as a readable unreachable (…) line inside the status table instead of breaking the supervisor or hiding the problem (early signal for pool exhaustion). The Valkey probe connects through the shared certificate-identity GLIDE factory with the read-only control identity; the RESP3 INFO decode contract is in §2.

6. Failure Modes & Recovery​

FailureBehavior
db bootstrap on an initialized platformRefuse (scout exists) - never a second window
Half-finished bootstrap (tables present, scout absent)Treated as initialized; recovery = repo dev-destroy.sh (dev-guarded), never a destructive CLI command
Enroll against an unreachable Auth/DBClear error; upserts are idempotent - re-run converges
Captain unreachable over UDSTransport falls back / errors distinctly (401/403 surface as auth, not transport)
Device token expiredRefresh; on refresh failure, re-run device flow

7. Concurrency & Performance Model​

Single-process, request-scoped - no daemons. sqlx pools created per command run; enrollment merges fragments in memory before upserting (one connection per target database).

8. Invariants​

  1. db bootstrap is the only platform-SQL applier and refuses re-initialization.
  2. No destructive command exists in the shipped CLI (dev reset is the guarded repo script).
  3. Starters link no service binary; every service surface is registry-declared.
  4. All enrollment upserts are idempotent - convergence on re-run.
  5. The operator token never leaves the local store; secrets flow by-reference.

9. Testing Strategy​

  • Unit: enrollment fragment merging, schedule upsert SQL shapes, transport resolution, bootstrap scout logic.
  • Integration (DB/Valkey-gated): bootstrap convergence on a fresh database; enroll upsert idempotency (run twice → same rows).
  • Deliberately NOT tested here: cloud provisioning modules, real device flows.

10. Open Questions​

  • Packaged-install enrollment (the vendored-registry path) tracks with the packaged-install rollout.
  • A captain enroll-remote convenience (drive a fresh machine's enroll from the CLI) may follow the FLEET E2E story.

Architecture & Design: sentin8:cli and its underlying concepts were designed by Hamid Jahanzad.