Sentin8:CLI - Detailed Design Document
Wire-level construction of
sentin8-cli. The overview lives inREADME.md; the operator capability list inBUSINESS.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 bootstrapandvertical initrun SQL directly as the DDL superuser - the only credential available before Sentin8:Auth exists.db bootstrapis the ONLY command that applies platform SQL; it refuses when thesys.platform_bootstrapscout 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
| Module | Role |
|---|---|
main.rs / lib.rs | Command tree (clap); boot-time helpers. |
auth.rs | Device-flow operator sign-in (PKCE, token persistence + refresh); get_valid_token_blocking. |
db.rs | db bootstrap (migrations/platform.sql + public_helpers.sql, scout-gated), db migrate (--sql-dir service SQL), db seed-listings. |
vertical_registry.rs | Composable 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.rs | Fleet control: start/stop/restart, per-instance restart/stop/start/upgrade (+ UDS transport), status tables, autoscaler view + approve/reject, captain place (hand placement). |
transport.rs | Captain transport resolution: local UDS (SO_PEERCRED) when on the same machine; HTTP for remote hosts. |
commands.rs | Declarative service commands - subcommands resolved from the registry (service_commands table), no hardcoded per-service command list. |
secrets.rs, func.rs, infra.rs | Secret-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.rs | Generic 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:
| Target | Written by | Idempotency |
|---|---|---|
sys.platform_bootstrap | db bootstrap (scout - written ONCE) | refuses re-run |
| Platform roles/schemas/grants | platform.sql (bootstrap, DO-block guarded) | converges (re-run safe) |
| Vertical databases + schemas + RLS | vertical init from per-repo sql/ | converge-on-apply |
sentin8_vertical_services + friends | vertical enroll | upsert per (vertical, service) |
cron.schedules | vertical enroll -section=schedules | upsert idempotent (SDD §2.4) |
Valkey captain:* catalog keys | vertical enroll | upsert |
| Operator device tokens | local 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_SERVICESfor the spawned captain - the boot allow-list filters ONLY the boot-spawn loop (D6); the catalog stays the full union so laterstart-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).
captainitself 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}). TheSENTIN8_CAPTAIN_BINARY_PREFIXcolon-chain is deleted - resolution by probing directories does not exist. - Write
captain:binary:{service_type}. The resolved absolute path is written beside the othercaptain:*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.jsonfragments like every vertical, somake enrolland 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.confpgmmap,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
verticalit declares:sentin8fragments converge here, every other vertical's fragment is skipped and left to that vertical's ownmake 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:mtamigration 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 enrollsurfacemake enrollcalls - 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-registrationhandler (the same self-registration contract every service rides); itsm2m_grantsdeclarecli-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, defaulthttp://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 Makefilecore-upprofile 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 placeneeds 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 readsSENTIN8_TLS_PQ_MODEfrom 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 toexclusive(ML-KEM only), and against aclassicalfleet that offered no shared group: every HTTPS call died withalert 40 (handshake_failure)whileopenssl s_clientreached 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 bootstraprefuses 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-dirpaths (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-registrationsections (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:
Outcome Meaning Enrollment 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 service continues, reported error the 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
Vecserializes 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_diris stamped from the fragment's own directory at load time (mirroringRegistryApp::source_dir) and is the FIRST candidate inresolve_binary_path; this is what makes a repo-scopedmake enrollresolve{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_PEERCREDfor same-machine control; Shield-gated HTTP for remote;captain placebuilds 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 viadatabase_env_varsdeclarations at spawn; the device-flow token store is user-scoped.
- they live in the operator env (
-
Operator env loading: every CLI subcommand loads the tree-root operator
.envviadotenvy::dotenv()- andscripts/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-opspair) and itscaptain stopprecondition 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.shis a FULL-TREE data reset - every non-template database on the dev cluster is dropped: vertical databases (bank8,hotel8, …) first, enumerated vertically-agnostically frompg_database(the script never names a vertical, AGENTS rule 1), then thesentin8platform database is dropped and recreated. The platform database carries the registry tables, so the reset also un-enrolls every vertical by construction. Vertical_serviceROLES survive on the cluster (they are passwordless certificate-identity rows; the vertical's ownvertical init/vertical enrollconverges them idempotently), while thesentin8_*_serviceplatform roles are dropped for re-seeding. Re-initialization covers the CORE PLATFORM ONLY:db bootstrap, the platform-fragment enrollment, and the post-bootstrapcaptain start- which runs under the platform-coreSENTIN8_SERVICESpin (spawning a vertical service against its dropped database would crash-loop it). A vertical re-joins the fresh platform via its own groupvertical init && make enroll && make startat 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.showns ONLY the infrastructure plane. Its four steps are (1) stop the fleet (captain graceful, never pkill), (2)docker compose down -vfor the tree's compose project - the namedsentin8-pgdata/sentin8-valkeydatavolumes are DELETED, so the cluster comes back virgin (fresh initdb, rolesentin8+ dbsentin8, zero service schemas, zero Valkey ACL state), (3) re-run the infra-TLS material pass (make infra-tlssemantics: re-mint/confirm leaves + republish the CA chain + RESEEDpg_hba.conf/pg_ident.conf, which the enroll pass appends to at runtime), (4)docker compose up -dand wait for BOTH healthchecks green. The script touches NO database content, runs NO psql, NOdb bootstrap, NOvertical enroll, NOdb finalize, and NOcaptain start- database convergence moved to the operator's normal flow, which now bootstraps automatically:make enrollandmake startboth run a bootstrap-if-needed step (db bootstrapwhen thesys.platform_bootstrapscout 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 runningmake enrollagain (idempotent upserts), a failed boot bymake startagain (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 withOperation not permittedand Valkey cannot open its AOF. The reset fixes the ownership deterministically betweenup -dand the health wait (docker run --rm -v <vol>:/d alpine chown 1000:1000 /dfor 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 enrollnow runs in phases: phase 1 creates every role and COLLECTS each service's--print-registrationsections; 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 seedsstat.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 targetsauth.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 enrollderives its fragment list from the repos carryingservice-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_optionalonpg_roles) always returnedSome((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_keyson 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/secretstree (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; valkeyunhealthyprobe streak with an empty/tls). The script therefore runsdocker compose up -d -force-recreatefor 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 readableunreachable (…)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 RESP3INFOdecode contract is in §2.
6. Failure Modes & Recovery
| Failure | Behavior |
|---|---|
db bootstrap on an initialized platform | Refuse (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/DB | Clear error; upserts are idempotent - re-run converges |
| Captain unreachable over UDS | Transport falls back / errors distinctly (401/403 surface as auth, not transport) |
| Device token expired | Refresh; 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
db bootstrapis the only platform-SQL applier and refuses re-initialization.- No destructive command exists in the shipped CLI (dev reset is the guarded repo script).
- Starters link no service binary; every service surface is registry-declared.
- All enrollment upserts are idempotent - convergence on re-run.
- 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-remoteconvenience (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.