Folders and files
| Name | Name | Last commit date | ||
|---|---|---|---|---|
Repository files navigation
# rhizome
This is the README for `rhi` which listens on Rad Roots networks and maintains
a stable activity record for parties buying and selling agricultural goods.
## Public API boundary
The library exposes one curated crate-root API. Every implementation module is
private, and public errors use RHI-owned stable classifications with redacted
diagnostics and no raw dependency-owned source chain or caller path. The shared
runtime-path, service-SQLite, storage, event, and trade values that appear in
signatures are deliberate governed contract types; raw SQLx, Serde, transport,
filesystem, and task authority never crosses this boundary.
The shared clock and entropy traits and their source-free error values are also
deliberate governed injection contracts. RHI operations normalize their
failures into stable RHI classifications; concrete system adapters remain
private implementation details.
Child modules cannot bypass the reviewed root surface:
```compile_fail
use rhi::features::trade_agreement_attestation::TradeAgreementAttestationPolicy;
fn bypass(_: TradeAgreementAttestationPolicy) {}
```
The reviewed all-features surface is frozen in the
[RHI API baseline](contracts/api_baselines/rhi.txt).
RHI publishes its service kind-0 Profile only through the sealed
`radroots_nostr` Profile builder after constructing the strict
`RadrootsAuthoredProfile` replacement snapshot. It does not retain a generic
kind-0 event-authoring path.
## Injected runtime adapters
`RhiRuntimeAdapters` is the sealed composition boundary for all runtime inputs
that must remain replaceable in deterministic tests. It owns distinct injected
whole-second wall UTC, process-local monotonic time, and entropy sources; a
transport-neutral bounded event source, live subscriber, and publication sink;
ordered read-existing credential and independently verified encrypted-identity
access; and one private shared join-owning task supervisor.
Full jitter is measured only in whole milliseconds, is sampled from injected
entropy with rejection-sampled multiply-high mapping, is always in the
inclusive configured range, and is capped at the exact v1 maximum of 3,600,000
milliseconds. Sampling fails closed after sixteen rejected entropy draws, so a
bad adapter cannot hang scheduling. Jitter is never derived from wall-clock
nanoseconds. Event-authored time remains untrusted input and cannot substitute
for an injected observation time or a monotonic deadline.
Constructing the adapter set performs no clock read, entropy read, identity or
credential access, DNS lookup, network operation, or task spawn. Concrete
transport handles and the task supervisor remain sealed. The library installs
no signal handler, Tokio runtime, logger, or process-exit policy; the final
binary checkpoint owns those authorities. The exact machine contract is
[`runtime_adapters.v1.json`](contracts/services_hardening/runtime_adapters.v1.json).
## Canonical trade-event admission
`admit_rhi_trade_mutation_event` is the sole accepted-ingest boundary for
signed trade mutations. It caps the original UTF-8 event before parsing,
measures decoded content, tags, tag elements, aggregate tag bytes, identifiers,
and non-authoritative outer extensions before the canonical decoder allocates
them, then independently verifies the NIP-01 identifier and Schnorr signature.
The promoted Lib contract performs the exact registered-kind, author,
canonical content and mutation-ID, and ordered structural-tag validation.
Observation time is injected. Future skew is an explicit caller-supplied
inclusive policy with no implicit default, while old events remain admissible
for lineage reconstruction. The sealed accepted value retains the exact
bounded input bytes plus the verified event and canonical typed mutation;
ordinary Debug output reveals only sizes, kind, authored time, and a redacted
identity marker. This pure boundary performs no clock read, network operation,
SQLite access, checkpoint update, or dirty-generation change. Its exact
machine contract is
[`trade_ingest.v1.json`](contracts/services_hardening/trade_ingest.v1.json).
## Immutable trade-evidence persistence
`RhiStateRepositories::persist_trade_evidence` atomically retains three
separate immutable facts: one canonical mutation, every distinct valid signed
event carrying it, and every accepted configured-source observation. Signed
event identity is the verified Nostr event identifier plus its verified
signature, so independent valid signatures over the same canonical event are
not collapsed. Observation time is the injected admission time and remains
distinct from the event-authored time.
The source observation can be constructed only from a validated RHI
configuration and an admitted signed event. Exact replay is idempotent;
conflicting durable mutation or signed-event content fails closed; and the
three inserts share one SQLx transaction. This operation performs no network
I/O and does not advance reconciliation checkpoints or dirty generation. The
machine contract is
[`trade_evidence_persistence.v1.json`](contracts/services_hardening/trade_evidence_persistence.v1.json).
## Bounded relay-source ingestion
`ingest_rhi_trade_source` resolves one explicit configured `nostr_relay`
source and its read-authorized relay, then fetches the exact five trade-mutation
kinds under the requested trade's indexed `#d` tag. It uses one absolute
configured deadline, pages at no more than 1,000 events, and admits at most
4,096 distinct signed-event identities (event ID plus signature) and 8 MiB of
original event bytes per attempt.
Every returned event still passes the sealed signature, identifier, mutation,
tag, trade, and authored-time boundary before it can affect durable state.
Only exact-target EOSE before the deadline is complete. Cancellation,
unavailability, bounded-result exhaustion, partial or malformed results, and
unsupported operation remain distinct incomplete outcomes and cannot advance a
checkpoint. Checkpoints are scoped by source, selector, evidence-policy digest,
and trade; their authored-time plus verified-event-ID cursor uses configured
overlap so equal timestamps remain discoverable. One short generation-fenced
SQLx transaction persists admitted evidence and an eligible checkpoint.
Relevant newly inserted mutation or signed-event evidence advances the
per-trade dirty generation; rejection, verified-event replay, repeated source
observation, and operational retry do not. Source fetching never occurs inside
a database transaction. The exact machine contract is
[`trade_source_ingest.v1.json`](contracts/services_hardening/trade_source_ingest.v1.json).
## Durable reconciliation jobs
`RhiReconciliationJobRepository` schedules at most one active job per trade
against the exact durable dirty generation and evidence-policy digest. Job IDs
are deterministic domain-separated SHA-256 identities, exact scheduling is
idempotent, a newer dirty generation atomically supersedes the prior active
job, and the configured queue capacity is enforced beneath a fixed 65,536-job
hard ceiling.
Claims and renewals are compare-and-swap transitions over an immutable job
identity and monotonic revision. Leases use caller-injected 16-byte owner
tokens and integer UTC milliseconds; expired leases can be reclaimed, while
an expired final attempt becomes exhausted. Failed attempts persist their next
eligible time using caller-injected full jitter bounded by the job's governed
exponential backoff. No ambient clock or entropy is read, and no source or
network work occurs inside a database transaction. The exact machine contract
is
[`reconciliation_jobs.v1.json`](contracts/services_hardening/reconciliation_jobs.v1.json).
## Bounded reconciliation source attempts
`RhiReconciliationAttemptPlan` derives one canonical source-request inventory
from an unexpired claimed job lease and the exact normalized evidence policy.
The attempt, selector, and each source request have domain-separated SHA-256
identities. Every request binds the source ID, required/optional authority,
trade selector, absolute deadline, lookback, and configured result limits.
The claimed job's retained lease, retry, and attempt policy must also equal the
exact normalized configuration; queue capacity remains admission authority for
new jobs rather than per-attempt identity. The attempt deadline and every
source deadline are capped by the retained lease expiry; no implicit clock or
deadline is consulted.
`RhiReconciliationSourceResult` records one stable completion code, explicit
start and finish times, and bounded accepted-event count and bytes. Exact EOSE
completion must occur before the source deadline, timeout begins at the
deadline, unsupported sources cannot report accepted events, and no outcome
can be omitted, duplicated, reordered, or appended beyond the configured
source inventory. Planning and result validation are pure and perform no
SQLite, source, relay, network, filesystem, task, clock, or entropy operation.
Cursor derivation, source execution, and durable completion commit remain with
their later ordered checkpoints. The exact machine contract is
[`reconciliation_attempts.v1.json`](contracts/services_hardening/reconciliation_attempts.v1.json).
## Overlap-safe reconciliation replay
`RhiReconciliationSourceReplayPlan` binds one exact source request to optional
sealed prior-cursor evidence, configured overlap, and an inclusive query start
under a domain-separated identity. The evidence is sealed to the source,
trade, evidence-policy digest, and selector digest, so callers cannot forge or
relabel progress. This pure replay model provides no evidence-minting path; the
atomic commit boundary below alone constructs it after replay and cursor commit.
Initial
queries use the configured lookback; resumed queries subtract the configured
overlap from the prior authored-time
cursor so equal-timestamp events remain discoverable. A cursor becomes
eligible only after exact `complete` source evidence, but remains an in-memory
candidate that this pure model cannot promote to resumption authority.
The replay inventory consumes at most the request event limit plus one and
bounds all original event bytes before deduplication. It accepts only the
request's trade, orders admitted signed events canonically, collapses exact
event replay, retains the earliest injected source observation, and rejects
conflicting mutation or signed-event identity reuse. Result counts and bytes
are derived from the distinct canonical inventory rather than caller claims.
It performs no SQLite, source, relay, network, filesystem, task, clock, or
entropy operation. Durable scope revalidation, result/completion persistence,
and checkpoint advancement belong to the atomic commit boundary below. The
exact machine contract is
[`reconciliation_replay.v1.json`](contracts/services_hardening/reconciliation_replay.v1.json).
## Atomic reconciliation result commit
`RhiReconciliationAttemptRepository::commit_source_replays` accepts exactly one
bounded replay result for every request in a claim-derived attempt. One short
SQLx transaction first revalidates the exact live lease, trade dirty generation,
evidence-policy digest, and each source-scoped prior checkpoint. It then commits
canonical mutations, signed events, first-source observations, the immutable
attempt and source-result inventory, a domain-separated digest of every exact
ordered persisted fact and provenance value, at most one dirty-generation
advance, and only eligible cursor checkpoints as one atomic unit. No source,
relay, network, clock, entropy, or task operation occurs inside that
transaction.
Only exact `complete` evidence with a strictly newer candidate advances a
checkpoint. Timeout, unavailable, resource-limited, unknown, and unsupported
results remain durable but never become progress. Newly inserted canonical
mutation or signed-event evidence advances the dirty generation once for the
whole attempt; observation-only replay does not. Exact retry of an already
committed attempt reconciles idempotently before stale lease or generation
fences, while any inventory mismatch fails closed. Sealed source/trade/policy/
selector cursor evidence is minted only after durable commit confirmation. The
exact machine contract is
[`reconciliation_commit.v1.json`](contracts/services_hardening/reconciliation_commit.v1.json).
## Immutable reconciliation manifest
`RhiReconciliationSourceCommitOutcome::into_evidence_manifest` consumes one
sealed, durably confirmed Step 190 outcome and freezes its exact canonical
mutation, signed-event, first-provenance, and per-source completion inventory
into the shared `radroots.trade.evidence-manifest.v1` encoding. The manifest
binds the claimed trade generation and evidence-policy digest. Each source
result additionally binds its exact selector digest, detailed completion,
timing, cursor inputs, checkpoint eligibility, and Step 190 persisted-inventory
digest. Each observation binds the verified mutation and event identities, the
SHA-256 of the exact canonical signed-event JSON, and a source/selector/policy/
signature/first-observation provenance digest.
Sources and observations use the shared canonical ordering, so arrival and
insertion order cannot select truth. The explicit whole-second observation
time cannot precede any committed source finish, and the explicit closed scope-
prerequisite input is included in the immutable bytes. Callers can inspect only
the redacted sealed result's identity, counts, canonical bytes, and digest; they
cannot construct a manifest from uncommitted replay material or supply its
result/provenance digests. Materialization is pure and performs no SQLite,
filesystem, source, relay, network, task, clock, or entropy operation. Durable
manifest persistence remains deferred to Step 199, and reduction, final
coverage/outcome, attestation, and publication retain their later checkpoint
owners. The exact machine contract is
[`reconciliation_manifest.v1.json`](contracts/services_hardening/reconciliation_manifest.v1.json).
The Step 192 integration-wave qualification proves that concurrent exact
commits converge to one durable attempt and byte-identical manifest, a blocked
commit can be cancelled with no authoritative effect and retried, an exact
lost-success retry converges after close/reopen, and an infinite replay
inventory terminates at configured source count plus one before mutation. The
same corpus covers exact source deadlines, incomplete checkpoint exclusion,
lease expiry/reclaim, queue and result bounds, stale leases/generations, and
durable reopen behavior without adding runtime, scheduler, source, or network
authority.
## Pure reconciliation reducer
[`reconciliation_reducer.v1.json`](contracts/services_hardening/reconciliation_reducer.v1.json)
binds the promoted shared `radroots.trade.reducer.v1` to one sealed confirmed
reconciliation manifest. The manifest privately retains only the bounded
canonical mutation material derived from its Step 190 commit; callers cannot
inject or replace reducer inputs. Reduction consumes the owned manifest,
retains it inside a sealed projection, and binds the shared projection digest
to the manifest and evidence-policy digests with a separate domain-separated
RHI digest. The projection retains the canonical shared result privately for
later checkpoints while exposing only bounded identity, digest, and count
evidence.
Reduction performs no SQLite, filesystem, source, relay, network, task, clock,
or entropy operation. Generation-fenced persistence, reports, attestations,
and publication retain their later checkpoint owners.
[`reconciliation_outcome.v1.json`](contracts/services_hardening/reconciliation_outcome.v1.json)
derives one claim-specific evaluation from that sealed projection.
Coverage is exactly `Missing`, `Partial`, `ScopeSatisfied`, or `Unsupported`;
outcome is
exactly `Valid`, `Invalid`, or `Indeterminate`. Missing, partial, unsupported,
digest-unavailable, unresolved, ambiguous, or absent-claim evidence is always
indeterminate. Only a clean active agreement claim is valid, and only a clean
cancelled agreement claim is decisively invalid. Every evaluation retains its
projection and exposes exactly one closed stable primary reason code without
adding I/O or ambient authority.
## Generation-fenced finalization preflight
`RhiReconciliationAttemptRepository::prepare_finalization` consumes one sealed
evaluation plus the exact live claimed lease. The manifest privately retains
its Step 190 attempt and job identities without changing canonical manifest
bytes or its digest, so an older attempt cannot be relabelled with a reclaimed
worker's distinct attempt authority. One bounded read-only SQLite transaction
checks the unexpired exact lease, current dirty generation, evidence-policy
digest, and immutable committed-attempt row before returning a sealed
`RhiReconciliationFinalizationFence`.
The fence is a preflight capability, not durable commit proof: state may change
after it is returned. Step 199 must rerun the same validator inside the final
atomic transaction before its first write. This checkpoint writes no manifest,
projection, report, signed event, outbox, checkpoint, or job state and performs
no source, relay, network, filesystem, task, clock, or entropy operation. The
exact machine contract is
[`reconciliation_finalization.v1.json`](contracts/services_hardening/reconciliation_finalization.v1.json).
## Canonical signed reconciliation attestation
`build_rhi_signed_evidence_attestation` consumes one sealed Step 195
finalization fence and derives the shared canonical RHI evidence report only
from its immutable manifest, projection, evaluation, and claim identity. The
report issuer is the independently verified encrypted service identity. The
optional supersession reference can be derived only from an earlier sealed,
verified signed-attestation result, and the shared ordering validator rejects
stale or misbound successors.
The event body and exact kind-3441 structural tags come only from the promoted
typed `radroots_event_codec` builder. Authored time and the 32 bytes of Schnorr
auxiliary randomness are injected explicitly. The boundary then independently
reparses the bounded signed NIP-01 JSON, recomputes its event identifier,
verifies its signature and exact plan fields, decodes the typed attestation,
reparses the canonical report, and revalidates its exact manifest binding.
The sealed result owns the finalization fence, canonical report, verified event
identifier, exact signed bytes, and the SHA-256 of those bytes. Later
persistence must retain those bytes without rebuilding, reserializing, or
re-signing them. This checkpoint performs no SQLite, filesystem, relay,
network, task, ambient-clock, or ambient-entropy operation. The schema-v7
catalog is frozen by Step 198; the generation-fenced write, publication, and
job finalization remain with Step 199 and its successors. The exact machine contract is
[`reconciliation_attestation.v1.json`](contracts/services_hardening/reconciliation_attestation.v1.json).
## Explicit publication authority and durable schema
`RhiPublicationAuthority::from_config` is the sole public derivation boundary
for publication intent. It consumes one complete validated RHI configuration
and returns exactly `Required` or `Disabled`. Required authority preserves the
explicit ordered write-relay targets, each target's requiredness, the bounded
retry policy, and queue capacity under separate domain-separated target-set
and complete-authority digests. Disabled authority contains no target or retry
state and authorizes no hidden network work. The sealed result exposes no URL,
credential, transport, SQLite, clock, entropy, or task authority.
Schema v7 freezes immutable manifest, projection, report, exact signed-event,
and publication-attempt records plus compare-and-swap outbox and target rows.
No-update/no-delete triggers protect semantic payload and target identities;
the closed target evidence vocabulary distinguishes pending, submitted,
accepted, rejected, rate-limited, auth-required, failed, and unknown. This
checkpoint defines and verifies the catalog only. Step 199 owns the first
atomic finalization write, and Steps 200-203 own claims, relay submission,
outcomes, retry, recovery, and wave qualification. The exact machine contract
is
[`publication_outbox.v1.json`](contracts/services_hardening/publication_outbox.v1.json).
## Deterministic durable presence intent
`RhiPresenceDesiredAuthority::from_config` derives the exact ordered
service-profile and application-handler intent from one complete admitted
configuration. It binds the verified service public identity, the configured
relay-ID order and requiredness, and the bounded presence queue under separate
domain-separated target-set and semantic desired-state digests. An independent
validator re-derives that authority from the same complete configuration.
Schema v9 stores only one sealed semantic desired-state snapshot. The first
commit creates generation one, exact semantic replay performs no write, and a
semantic change advances exactly one compare-and-swap generation. Every commit
must still match the latest durable configuration binding. The table stores no
relay URL, filesystem path, rendered event, signature, authored time, delivery
attempt, or network result, and its triggers reject deletion and ungoverned
updates. Rendering, signing, target delivery state, retries, and relay I/O remain
separate from this semantic-intent commit. The exact machine contract is
[`presence_desired_state.v1.json`](contracts/services_hardening/presence_desired_state.v1.json).
## Durable exact-byte presence publication
`build_rhi_signed_presence_documents` consumes one committed desired-state
generation, the independently revalidated complete presence authority, the
matching decrypted service identity, caller-injected authored time, and
caller-injected Schnorr auxiliary entropy. It builds the kind-0 service profile
through the typed `radroots_event` profile plan and cross-checks the kind-31990
application-handler plan produced by `radroots_nostr` against the typed
`radroots_event` plan. Every signed document is then independently parsed under
the bounded NIP-01 wire limits and revalidated for event ID, signature, author,
kind, time, ordered tags, and exact content before exposure.
Schema v10 retains each independently verified exact signed byte sequence,
digest, document identity, and complete immutable target inventory. One short
SQLx-owned transaction commits those bytes and initial target state before any
injected `RhiExactPresenceSink` can observe them. A second short transaction
commits `submitted` before remote I/O. The remote await owns no transaction;
the first commit borrows rather than consumes its sealed document set, so an
unknown commit result can be reconciled by replaying the same retained bytes;
the resulting closed outcome, immutable attempt evidence, target schedule,
outbox disposition, and lease release are committed together afterward.
Cancellation or acknowledgement loss after `submitted` becomes durable
`unknown` before the same retained bytes can be retried. Expired work from a
superseded desired generation is recorded as `unknown` and the old outbox is
superseded without sampling retry entropy, preventing stale leases from
blocking the current generation forever. No retry parses, rebuilds,
reserializes, or re-signs an event, and no raw relay diagnostic is persisted.
The exact machine contract and deterministic signed vectors are
[`presence_publication.v1.json`](contracts/services_hardening/presence_publication.v1.json).
## Atomic reconciliation finalization commit
`RhiReconciliationAttemptRepository::commit_finalization` borrows one sealed,
independently verified signed attestation and the publication authority derived
from the same normalized configuration as the open state host. One short
SQLx-owned transaction first reconciles an exact prior success, then reruns the
live lease, dirty-generation, policy, committed-attempt, source-inventory,
checkpoint, supersession, and publication-capacity fences before its first
write.
The same transaction retains the exact canonical manifest, projection,
canonical report, and independently verified signed-event bytes; records the
explicit supersession; creates the immutable outbox and ordered target set only
when publication is required; and completes the exact reconciliation job.
Disabled publication creates no outbox or target row. An exact retry returns
`created = false` even after the lease was consumed or expired, while any
mismatched durable footprint fails closed. This boundary performs no source or
relay I/O, network access, filesystem access, task spawn, ambient clock read,
or ambient entropy read. Publication claims and relay submission remain later
steps. The exact machine contract is
[`reconciliation_finalization_commit.v1.json`](contracts/services_hardening/reconciliation_finalization_commit.v1.json).
## Exact committed publication bytes
`RhiPublicationOutboxRepository::read_committed_publication` joins one immutable
schema-v7 outbox to its signed-attestation row in one bounded read-only SQLx
transaction. It admits at most 32,768 stored bytes, rechecks the exact outbox,
event-identifier, and SHA-256 bindings, and returns a sealed
`RhiCommittedPublication`. Repeated reads and reads after a clean close/reopen
return the same committed byte string or fail closed.
The capability is not a relay claim or lease. Its only payload accessor returns
the stored bytes unchanged; this path contains no JSON or event parsing,
rebuilding, reserialization, signing, relay/network/filesystem work, task
spawn, or ambient clock/entropy access. The closed target/attempt evidence model
is defined below; durable claims and transitions, relay I/O, retry scheduling,
and lease recovery remain with Step 202. The exact machine contract is
[`publication_submission.v1.json`](contracts/services_hardening/publication_submission.v1.json).
## Bounded publication attempt evidence
The publication target state is one closed value: pending, submitted, accepted,
rejected, rate-limited, auth-required, failed, or unknown. Pending is not an
attempt outcome, Accepted is the sole terminal target state, submission alone
does not prove relay delivery, and Unknown can be refined only by independent
evidence. Attempt outcomes use the same closed vocabulary except Pending and
expose no arbitrary result string or upstream diagnostic.
`RhiPublicationAttemptEvidence` binds the sealed committed outbox identity and
exact event digest to a zero-based target ordinal no greater than 31, a
one-based attempt number no greater than 100, ordered injected integer UTC
milliseconds, and one closed outcome under a domain-separated SHA-256 identity.
It is pure bounded evidence rather than claim, transition, or relay authority.
Step 202 must revalidate live target, lease, revision, attempt, and exact-byte
bindings when it persists Submitted before I/O and later commits an observed
outcome. The exact machine contract is
[`publication_attempt_evidence.v1.json`](contracts/services_hardening/publication_attempt_evidence.v1.json).
## Durable exact-byte publication execution
`RhiPublicationOutboxRepository` claims one due outbox with an injected
nonzero owner and bounded lease only after binding the outbox and complete
target inventory to the exact current required-publication authority. It
persists the exact target as Submitted before remote I/O and exposes the
original committed byte slice only through `RhiExactPublicationSink`. This
dedicated boundary deliberately does not pass the payload through the generic
typed-event sink: retries never parse, reconstruct, reserialize, or re-sign
committed evidence.
Observed outcomes append one immutable attempt row and compare-and-swap the
target, persisted retry schedule, outbox disposition, and lease release in one
short SQLx-owned transaction. Full-jitter exponential backoff uses only
injected entropy. Cancellation or acknowledgement loss after Submitted remains
Unknown; expired-lease recovery appends that conservative evidence before an
exact-byte retry or exhaustion. No transaction remains open across relay I/O,
and an unknown local commit must be reconciled by exact attempt identity. The
exact machine contract is
[`publication_execution.v1.json`](contracts/services_hardening/publication_execution.v1.json).
Step 203 closes this wave with executable crash/reopen, shared transactional
failpoint, concurrent-claim, queue-bound, and redaction qualification. Schema
v8 first scans every historical reconciliation job and fails closed without
repair when a `ready` schedule or `leased` owner/expiry is missing. Only after
that scan succeeds does the same governed migration install permanent INSERT
and UPDATE state-shape guards. The exact qualification inventory and bounds are
[`publication_wave_qualification.v1.json`](contracts/services_hardening/publication_wave_qualification.v1.json).
## Existing-state runtime foundation
`open_rhi_runtime_foundation` opens only an already initialized database from
the sealed service-instance intent, discovers its source generation under the
retained writer authority, verifies the latest append-only configuration
binding, and then resolves the credential before independently opening the
encrypted service identity. Missing state is never initialized by ordinary
startup. No evidence source, live subscription, or publication sink is
contacted before the durable configuration binding is proven.
The passive readiness snapshot initially proves only existing state, durable
configuration, and verified identity. Recovery, source connectivity and
subscription, publication recovery, admin and optional operations listeners,
and configured presence desired state remain explicitly unsatisfied for their
later owning checkpoints. Reading the snapshot performs no filesystem,
SQLite, credential, identity, DNS, or network probe. The foundation installs
no signals, runtime, logger, or process-exit policy and does not claim the final
supervised task graph. Its exact machine contract is
[`runtime_foundation.v1.json`](contracts/services_hardening/runtime_foundation.v1.json).
## Passive lifecycle status and TCP operations
`rhi_status_cache` retains exactly one latest immutable RHI lifecycle and
detailed-status publication behind a single non-cloneable publisher. Each
publication is bounded and validated before it replaces the prior snapshot.
Readers clone only passive cache authority; they perform no SQLite,
filesystem, evidence-source, relay, DNS, identity, credential, clock, or fresh
probe operation. Detailed JSON is reserved for the permissioned Unix-admin
surface and contains only the closed service identity, evidence transport,
reconciliation, publication, presence, persistence, configuration, build, and
stable reason vocabularies. Its exact contract is
[`status_cache.v1.json`](contracts/services_hardening/status_cache.v1.json).
When the validated operations block is enabled, `RhiOperationsServer` exposes
exactly HTTP/1.1 `GET /livez`, `GET /readyz`, and `GET /metrics` on its admitted
TCP address. Requests read only the latest cached lifecycle/readiness and two
fixed bounded metric families; they cannot register another route or reach
detailed status. Requests perform no SQLite, filesystem, evidence-source,
relay, DNS, identity, credential, clock, or active health probe. The listener
is disabled by default and remains a supervisor-owned optional adapter. Its
exact contract is
[`tcp_operations.v1.json`](contracts/services_hardening/tcp_operations.v1.json).
## Hardened v1 configuration contract
The target service configuration is frozen by
`contracts/services_hardening/config.v1.schema.json` and the canonical
non-secret `config.v1.example.toml`. It is one strict immutable TOML document
with explicit identity, relay, evidence-source, reconciliation, attestation,
publication, presence, resource, and retention authority. The evidence fields
and maxima consume `evidence_policy.v1.json` without reinterpretation. Only
reviewed bounded operational leaves have defaults. Bootstrap profile,
instance, repo-local root, and config-path selection are CLI concerns and are
not document fields.
The retired root `config.toml`, transitional runtime loader, JSON state
adapter, environment and worker selectors, and prototype smoke/runtime paths
are removed. The executable admits one strict CLI invocation and one sealed
runtime context, then fails closed until later ordered checkpoints bind each
command to its governed state and runtime authority. It never falls back to a
prototype execution path.
`parse_rhi_config_v1` is the strict in-memory admission boundary for the target
document. It bounds original bytes before parsing, rejects malformed duplicate
or null TOML and unknown fields, validates the bootstrap-selected relay posture
and all cross-field relationships, and returns an immutable document with a
deterministic bounded redacted effective projection. The projection records the
exact `toml` or `safe_default` origin for every leaf and the governed authority
behind each safe default. Parsing performs no filesystem, environment,
identity, database, clock, entropy, logging, DNS, or network operation.
## Hardened v1 command admission
`parse_rhi_cli_v1_from` parses the bootstrap and closed command tree exactly
once. Every invocation explicitly selects `service-host`, `interactive`, or
`repo-local`, a validated instance, and optionally an absolute configuration
path. Repo-local selection additionally requires one absolute base root and
that root is forbidden for the other profiles. Human output is the default;
governed JSON output is selected explicitly.
The command inventory covers daemon run; config init, validate, show, schema,
and apply; state init, status, backup, restore, verify, and migrate; service
identity init, status, and public export; service status and metrics snapshot;
reconciliation status, jobs, and refresh; source listing; trade projection and
report queries; publication backlog, targets, and retry; desired-presence
inspection, render, and refresh; and doctor. The parser performs no command
execution. The admitted invocation projects once into a sealed execution plan:
`run` selects daemon authority; config initialization, validation, schema, and
apply, exclusive state maintenance, initial identity provisioning, and doctor
select offline authority; and the remaining twenty commands map one-to-one to
the final twenty permissioned Unix-admin routes. No live command carries an
offline or direct-SQLite fallback. Later ordered steps bind each command's exact
input and execute the already-selected authority without reparsing arguments.
Ordinary `run` accepts no identity-generation, identity-path, log-path,
database-path, worker, environment-file, or arbitrary path-leaf flag. Identity
rekey and replacement are not commands; rotation is a create-new offline
artifact plus governed configuration apply.
## Bounded active doctor and stable process results
The doctor runs the governed fifteen checks in exact contract order. Each
check has one fixed deadline, required or optional authority, a closed evidence
scope, and a safe remediation code. Required checks must pass; required
failure, timeout, or an invalid skipped result makes the aggregate `fail`.
Optional non-pass makes the aggregate `degraded`, while every passing check
makes it `pass`. A timed-out probe is cancelled by dropping its future, and no
detached probe work is permitted.
The compact canonical JSON report is capped at 8,192 UTF-8 bytes. Its summaries
come only from the fixed content-free vocabulary and cannot contain paths, raw
errors, relay text, identifiers, credentials, or other protected material.
Required failure or timeout returns exit code `6`; the complete process-result
contract is the closed zero-through-six inventory in
[`operator_contract.v1.json`](contracts/services_hardening/operator_contract.v1.json).
The executable emits only the stable result code on stderr and never renders a
parser, path-resolution, dependency, or internal error.
## Unix-admin boundary
Step 206 bound the seven common RHI routes for detailed status, redacted
effective configuration, service-identity status and public export, state
status, online backup, and a bounded metrics snapshot to the shared
`radroots_service_host` HTTP/1.1-over-Unix server. The public RHI route and
document types are closed, response construction admits only bounded compact
canonical JSON matching the exact machine model, and public diagnostics retain
no path, request, identity, or dependency-owned cause.
The server projects only the normalized configuration's admitted transport
limits, derives `admin.sock` only from the sealed runtime context, acquires the
shared writer authority before binding, and uses the shared server's system
entropy for absent correlation IDs. Construction does no I/O; binding does not
spawn; serving remains a later supervised runtime responsibility. Raw shared
routers, listeners, JSON values, and caller-selected socket paths never cross
the public RHI boundary. Its historical partial machine contract is
[`admin_common.v1.json`](contracts/services_hardening/admin_common.v1.json).
Step 207 cumulatively activates the thirteen reconciliation, job, source,
trade projection/report, publication target/backlog, retry, and presence
domain routes. Page sizes stop at 200; query names and duplicates are closed;
cursors use canonical base64url without padding and remain authenticated and
bound by the handler to the same route, filters, and snapshot. Every decoded
`{trade_id}` is exactly 32 lowercase hexadecimal characters. Mutations retain
stable operation-ID exact replay and conflicting-reuse rejection, and success
still means the handler's contract-defined local effect is durably committed,
not relay delivery. The adapter performs no SQLite or relay I/O itself. The
Step 208 removes the two never-registered live identity rekey/replace routes,
their three mutation-only models, and the unused operator types that could have
suggested live provider authority. Identity rotation is only offline create-new
envelope plus validated configuration apply and restart. Unix peer authorization
remains a transport admission gate and grants neither direct SQLite nor
identity-provider mutation authority. Step 209 qualifies the complete
20-route/33-model inventory with real Unix-socket original-wire, version,
pagination, idempotency, peer-permission, removed-route, and resource negative
matrices plus the exact source-locked shared-transport corpus. The cumulative
domain contract is
[`admin_domain.v1.json`](contracts/services_hardening/admin_domain.v1.json).
The offline identity correction is
[`admin_identity_offline.v1.json`](contracts/services_hardening/admin_identity_offline.v1.json).
The completed admin-wave qualification is
[`admin_wave_qualification.v1.json`](contracts/services_hardening/admin_wave_qualification.v1.json).
## Sealed service-instance paths
One validated CLI invocation resolves through `RhiRuntimeContext`, which owns
the shared typed `RuntimeContext`, exact common artifacts, the validated
`service.identity.ncrypt` encrypted identity artifact path, and the explicit or
canonical configuration selection. The service identity is fixed to `rhi`; the instance
comes only from `InstanceId`; profile and repo-local-root provenance are the
closed `bootstrap_cli` vocabulary. Callers cannot construct or mutate another
path set, override artifact names, or obtain a public path report.
Service-host roots are exactly
`/etc/radroots/services/rhi/<instance>`,
`/var/lib/radroots/services/rhi/<instance>`,
`/var/cache/radroots/services/rhi/<instance>`,
`/var/log/radroots/services/rhi/<instance>`,
`/run/radroots/services/rhi/<instance>`, and
`/etc/radroots/secrets/services/rhi/<instance>`. Interactive roots consume the
injected host environment defined by `radroots_runtime_paths`; repo-local uses
one explicit absolute base and the same `services/rhi/<instance>` namespace.
Path resolution performs no directory creation or filesystem I/O.
## Governed SQLite catalog
RHI owns one `state.sqlite` per service instance. Create-new initialization
starts from the shared schema-v1 baseline and immediately applies the pinned
schema-v2 configuration migration, schema-v3 immutable trade-evidence
migration, schema-v4 source-checkpoint and dirty-generation migration,
schema-v5 bounded reconciliation-job migration, schema-v6 immutable
reconciliation-result migration, and schema-v7 immutable report, signed-event,
publication-workflow migration. Schema v8 adds reconciliation-attempt replay
evidence, schema v9 adds durable presence desired state, and schema v10 adds
the exact-byte presence outbox, target, and attempt inventory.
Version ten contains the six shared immutable service-metadata and
migration-ledger objects, the bounded append-only `rhi_config_bindings` table,
separate immutable tables for canonical mutations, signed Nostr events, and
accepted source observations, and generation-guarded relay checkpoints and
per-trade dirty generations with their enforcement triggers and indexes.
It also retains immutable attempt, source-result, manifest, projection, report,
signed-event, and publication-attempt rows plus compare-and-swap outbox and
target state under exact transition and retention triggers.
Exact literal SHA-256 values bind both migrations, every schema snapshot, and
the schema catalog. RHI validates every identity before it can become database
authority.
The configuration history retains at most 1,024 consecutive generations. Each
row stores only normalized configuration and evidence-policy digests, the
public service identity, exact contract versions, injected apply time, and
bounded build identity. It never stores raw TOML, paths, relay URLs, credential
references, or protected identity material. Startup requires the latest row to
match the admitted document. `apply_rhi_configuration` obtains exclusive
offline authority, verifies the current binding, appends the candidate
atomically, treats exact replay idempotently, and explicitly closes state.
Catalog construction itself performs no filesystem or SQLite I/O and owns no
pool, connection, transaction, query, or migration executor. The sealed state
host alone executes the governed migrations and typed state transactions.
Evidence manifests, reports, attestations, publication state, and final job
completion remain reserved for their later owning checkpoints.
The sealed RHI state-host lifecycle now reserves and initializes a missing
canonical database only through an explicit create-new operation. Ordinary
writable and immutable inspection modes open existing state only, validate the
exact schema and migration identities, and retain mutually exclusive shared
authority until explicit idempotent close. Missing state is never initialized
by an open operation. No raw host, pool, connection, transaction, executor, or
path escapes the RHI wrapper.
One sealed RHI state-metadata capability now binds that lifecycle to the exact
service and instance, nonzero source generation, `RDRH` SQLite application ID,
schema version, creation time, fully normalized configuration digest,
contract-defined evidence-policy digest, expected service public identity, and
configuration/state/admin/status/provider contract versions. Its fields are
immutable; ordinary Debug and errors redact paths, identities, generations,
and digests.
The governed encrypted-file identity boundary accepts only the shared
version-2 `radroots_secrets` envelope, binds its authenticated context to the
service role, expected public key, payload schema, and separately named
wrapping-credential reference, and releases a zeroizing identity only after
the derived public key matches configuration. Offline provisioning is
create-new and caller-supplied; ordinary startup never generates an identity,
legacy envelopes are rejected, and RHI state backups contain no envelope,
wrapping credential, or plaintext identity.
The separately governed wrapping-credential resolver derives exactly one
validated artifact name from the admitted identity binding and resolves it only
beneath the same runtime context's canonical instance secrets root. It accepts
only an existing 32-byte, owner-controlled, single-link regular file for
service-host and repo-local profiles. It never accepts caller paths or bytes,
creates credentials or directories, consults environment or process arguments,
or falls back to an adjacent envelope sibling. The former prototype identity
and adjacent-key storage APIs are not part of the crate surface.
The wave-two composition proof binds configuration, runtime paths, immutable
state metadata, the encrypted identity, and its separately resolved credential
to one service instance. It proves that state initialization and existing-only
open do not persist the identity secret, credential, encrypted-envelope wire
material, or credential reference in `state.sqlite`. The envelope and
credential remain excluded from the state-backup contract. That earlier
wave-two boundary proof did not itself execute a backup; the governed
resilience boundary below now owns the actual backup and recovery mechanics.
Explicit state initialization validates runtime identity, build evidence, and
the complete migration/schema catalogs before invoking the runtime-path
directory plan. That plan alone may provision the exact interactive
`services/rhi/<instance>` suffix; service-host deployment roots and suffixes
must already exist. The shared service-SQLite initializer owns the one
transaction and exposes only its sealed typed SQLx executor. Existing writable
and inspection opens never provision directories or create missing state.
RHI's state surface is partitioned into twenty-one distinct non-forgeable typed
repository capabilities bound to one already-opened `RhiStateHost`. Their
closed topology covers source results, cursors, completions, admitted signed
events, canonical mutations, provenance, dirty generations, reconciliation
jobs and attempts, immutable manifests/projections/reports, supersession,
signed attestation events, publication outbox/targets/attempts, desired
presence, and presence outbox/targets/attempts. Each capability has one exact backing-table identity and an
append-only, compare-and-swap, or immutable write class. It exposes no raw
pool, connection, transaction, SQL, path, or cloneable write authority.
Schema migration and verification, remaining repository behavior,
backup/restore, service task ownership, and admin routing remain owned by their
later ordered checkpoints.
RHI now composes the shared SQLx-owned resilience boundary without exposing a
second database authority. A writable `RhiStateHost` can capture one governed
online backup, and either host mode can run an explicit bounded integrity
inspection. Offline verification returns a sealed exact-inode proof; staging
retains exclusive writer authority; finalization uses the shared durable
marker and atomic replacement protocol; and the next writable existing-state
open reconciles interrupted restore evidence before exposing a host. Read-only
inspection never performs recovery. Callers inject all times, manifest bytes
and digest, and the positive backup-size limit. RHI adds no SQLite dependency,
raw connection, background runtime, implicit deadline, or direct file-copy
authority.
## Failure-resilience qualification
The machine-readable
[`failure_qualification.v1.json`](contracts/services_hardening/failure_qualification.v1.json)
contract freezes the Step 214 evidence corpus for resource and backlog bounds,
disk and durable-state behavior, corruption and malformed history,
cancellation, outage recovery, and safe errors. Every RHI entry names an
executable component test, while shared SQLite durability, capacity,
corruption, migration-history, cancellation, backup, close, and restore
evidence is bound to the exact retained Lib source lock. SQLx remains the sole
high-level SQLite authority; no production failpoint or environment-selected
test path is introduced.
This checkpoint is deliberately component-scoped. The actual-process and
bounded-soak qualification remains Step 215 ownership, native release
artifacts remain Step 216 ownership, and promotion and parent-pin alignment
remain Step 217 ownership. Nix, OCI, signing, publication, and deployment are
deferred and unclaimed.
The Step 215
[`process_qualification.v1.json`](contracts/services_hardening/process_qualification.v1.json)
contract closes wave `130-c` by binding that component corpus to the actual
RHI executable. It exercises offline bootstrap and required-dependency outage,
the complete supervised task graph against loopback relay sessions, eight
concurrent read-only configuration-validation processes, and 32 clean database
reopen-and-verify cycles. The live daemon is interrupted, joined, reaped, and
checked for socket cleanup. Every child process has a fixed deadline and
bounded captured output. The test surface adds no production failpoint,
environment selector, detached worker, ambient network dependency, or later
release authority.
## Standalone native release contract
The capsule owns a private `cargo xtask native-release` generator and the
machine-readable
[`native_release.v1.json`](contracts/services_hardening/native_release.v1.json)
predecessor and the forward
[`native_release.v2.json`](contracts/services_hardening/native_release.v2.json)
contract. From one exact clean committed revision, a caller-supplied positive
deterministic epoch, and an executable ELF64 binary for one governed GNU/Linux
target, the generator creates one external immutable artifact directory. It
contains the binary archive, a vendored offline source archive, the non-secret
configuration example and schema, the standalone systemd unit, exact source
lock, license and notices, CycloneDX SBOM, unsigned provenance input, artifact
manifest, and sorted SHA-256 checksums.
Generation is bounded, deterministic, collision-only, mode checked, and
durability ordered. It scans exact tracked source, the selected binary, copied
package inputs, and generated documents for governed protected-value patterns,
then records that protected material and OCI content are absent while binding
the qualified Nix posture. The source-locked third-party vendor graph is
represented separately by checksums, SBOM, and notices. The generator does
not sign, tag, publish, deploy, or write artifacts into the source tree. The standalone
`scripts/release-acceptance.sh` surface exercises the native Cargo contract;
when invoked by the parent monorepo it is itself run through extbuild.
SBOM component references are domain-separated hashes of framed Cargo
name/version/source/checksum identity, so they neither disclose a checkout path
nor vary when the same exact source is built from another directory.
The standalone Linux systemd boundary is frozen by
`contracts/services_hardening/systemd_qualification.v1.json` and checked by
`scripts/verify-systemd.sh`. The instance unit uses the canonical service-host
paths, fixed unprivileged account, restrictive directory modes and umask,
fixed restart delay, bounded stop behavior, empty capabilities, no environment-based secret
input, and the reviewed filesystem, kernel, namespace, process, and address-
family protections. The Linux-only verifier requires systemd 252 or newer,
runs syntax verification, and rejects an offline security exposure above 3.0.
Type `simple` remains deliberate: readiness is the cached CLI/admin contract,
not `sd_notify`. Compatibility-sensitive `MemoryDenyWriteExecute` and syscall
filters remain deferred to the Step 229 integration wave rather than being
enabled without real-binary evidence. This qualification does not install,
enable, start, stop, or deploy a production service. Native artifact qualification
remains Step 216 ownership, and promotion remains Step 217 ownership.
Validate the standalone crate through extbuild:
```text
cargo extbuild doctor
cargo extbuild run -- ./scripts/verify-boundaries.sh
cargo extbuild run -- ./scripts/verify-supply-chain.sh
cargo extbuild run -- ./scripts/release-acceptance.sh
cargo extbuild run -- cargo fmt --all --check
cargo extbuild run -- cargo check --workspace --all-targets --locked
cargo extbuild run -- cargo test --workspace --all-targets --locked
cargo extbuild run -- cargo clippy --workspace --all-targets --locked -- -D warnings
cargo extbuild run -- env RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps --locked
```
The flake exposes the RHI package, application, checks, and development shell
for `aarch64-darwin` and `x86_64-linux`, plus the NixOS module and unsigned OCI
derivation for `x86_64-linux`. Run Nix and narrower ad hoc Cargo commands
through `cargo extbuild run --` from this repository root.
## Copyright
Except as otherwise noted, all files in the `rhi` distribution are
`Copyright (c) 2025 Tyson Lupul`
## License
This repository is licensed under AGPL-3.0-or-later. See LICENSE.