README (53822B)
1 # rhizome 2 3 Global and nested `--help` print static command help and exit successfully 4 before configuration, identity, state, signals or network startup. Malformed 5 arguments retain the fixed redacted error result and nonzero exit status. 6 7 This is the README for `rhi` which listens on Rad Roots networks and maintains 8 a stable activity record for parties buying and selling agricultural goods. 9 10 ## Public API boundary 11 12 The library exposes one curated crate-root API. Every implementation module is 13 private, and public errors use RHI-owned stable classifications with redacted 14 diagnostics and no raw dependency-owned source chain or caller path. The shared 15 runtime-path, service-SQLite, storage, event, and trade values that appear in 16 signatures are deliberate governed contract types; raw SQLx, Serde, transport, 17 filesystem, and task authority never crosses this boundary. 18 19 The shared clock and entropy traits and their source-free error values are also 20 deliberate governed injection contracts. RHI operations normalize their 21 failures into stable RHI classifications; concrete system adapters remain 22 private implementation details. 23 24 Child modules cannot bypass the reviewed root surface: 25 26 ```compile_fail 27 use rhi::features::trade_agreement_attestation::TradeAgreementAttestationPolicy; 28 29 fn bypass(_: TradeAgreementAttestationPolicy) {} 30 ``` 31 32 The reviewed all-features surface is frozen in the 33 [RHI API baseline](contracts/api_baselines/rhi.txt). 34 35 RHI publishes its service kind-0 Profile only through the sealed 36 `radroots_nostr` Profile builder after constructing the strict 37 `RadrootsAuthoredProfile` replacement snapshot. It does not retain a generic 38 kind-0 event-authoring path. 39 40 ## Injected runtime adapters 41 42 `RhiRuntimeAdapters` is the sealed composition boundary for all runtime inputs 43 that must remain replaceable in deterministic tests. It owns distinct injected 44 whole-second wall UTC, process-local monotonic time, and entropy sources; a 45 transport-neutral bounded event source, live subscriber, and publication sink; 46 ordered read-existing credential and independently verified encrypted-identity 47 access; and one private shared join-owning task supervisor. 48 49 Full jitter is measured only in whole milliseconds, is sampled from injected 50 entropy with rejection-sampled multiply-high mapping, is always in the 51 inclusive configured range, and is capped at the exact v1 maximum of 3,600,000 52 milliseconds. Sampling fails closed after sixteen rejected entropy draws, so a 53 bad adapter cannot hang scheduling. Jitter is never derived from wall-clock 54 nanoseconds. Event-authored time remains untrusted input and cannot substitute 55 for an injected observation time or a monotonic deadline. 56 57 Constructing the adapter set performs no clock read, entropy read, identity or 58 credential access, DNS lookup, network operation, or task spawn. Concrete 59 transport handles and the task supervisor remain sealed. The library installs 60 no signal handler, Tokio runtime, logger, or process-exit policy; the final 61 binary checkpoint owns those authorities. The exact machine contract is 62 [`runtime_adapters.v1.json`](contracts/services_hardening/runtime_adapters.v1.json). 63 64 ## Canonical trade-event admission 65 66 `admit_rhi_trade_mutation_event` is the sole accepted-ingest boundary for 67 signed trade mutations. It caps the original UTF-8 event before parsing, 68 measures decoded content, tags, tag elements, aggregate tag bytes, identifiers, 69 and non-authoritative outer extensions before the canonical decoder allocates 70 them, then independently verifies the NIP-01 identifier and Schnorr signature. 71 The promoted Lib contract performs the exact registered-kind, author, 72 canonical content and mutation-ID, and ordered structural-tag validation. 73 74 Observation time is injected. Future skew is an explicit caller-supplied 75 inclusive policy with no implicit default, while old events remain admissible 76 for lineage reconstruction. The sealed accepted value retains the exact 77 bounded input bytes plus the verified event and canonical typed mutation; 78 ordinary Debug output reveals only sizes, kind, authored time, and a redacted 79 identity marker. This pure boundary performs no clock read, network operation, 80 SQLite access, checkpoint update, or dirty-generation change. Its exact 81 machine contract is 82 [`trade_ingest.v1.json`](contracts/services_hardening/trade_ingest.v1.json). 83 84 ## Immutable trade-evidence persistence 85 86 `RhiStateRepositories::persist_trade_evidence` atomically retains three 87 separate immutable facts: one canonical mutation, every distinct valid signed 88 event carrying it, and every accepted configured-source observation. Signed 89 event identity is the verified Nostr event identifier plus its verified 90 signature, so independent valid signatures over the same canonical event are 91 not collapsed. Observation time is the injected admission time and remains 92 distinct from the event-authored time. 93 94 The source observation can be constructed only from a validated RHI 95 configuration and an admitted signed event. Exact replay is idempotent; 96 conflicting durable mutation or signed-event content fails closed; and the 97 three inserts share one SQLx transaction. This operation performs no network 98 I/O and does not advance reconciliation checkpoints or dirty generation. The 99 machine contract is 100 [`trade_evidence_persistence.v1.json`](contracts/services_hardening/trade_evidence_persistence.v1.json). 101 102 ## Bounded relay-source ingestion 103 104 `ingest_rhi_trade_source` resolves one explicit configured `nostr_relay` 105 source and its read-authorized relay, then fetches the exact five trade-mutation 106 kinds under the requested trade's indexed `#d` tag. It uses one absolute 107 configured deadline, pages at no more than 1,000 events, and admits at most 108 4,096 distinct signed-event identities (event ID plus signature) and 8 MiB of 109 original event bytes per attempt. 110 Every returned event still passes the sealed signature, identifier, mutation, 111 tag, trade, and authored-time boundary before it can affect durable state. 112 113 Only exact-target EOSE before the deadline is complete. Cancellation, 114 unavailability, bounded-result exhaustion, partial or malformed results, and 115 unsupported operation remain distinct incomplete outcomes and cannot advance a 116 checkpoint. Checkpoints are scoped by source, selector, evidence-policy digest, 117 and trade; their authored-time plus verified-event-ID cursor uses configured 118 overlap so equal timestamps remain discoverable. One short generation-fenced 119 SQLx transaction persists admitted evidence and an eligible checkpoint. 120 Relevant newly inserted mutation or signed-event evidence advances the 121 per-trade dirty generation; rejection, verified-event replay, repeated source 122 observation, and operational retry do not. Source fetching never occurs inside 123 a database transaction. The exact machine contract is 124 [`trade_source_ingest.v1.json`](contracts/services_hardening/trade_source_ingest.v1.json). 125 126 ## Durable reconciliation jobs 127 128 `RhiReconciliationJobRepository` schedules at most one active job per trade 129 against the exact durable dirty generation and evidence-policy digest. Job IDs 130 are deterministic domain-separated SHA-256 identities, exact scheduling is 131 idempotent, a newer dirty generation atomically supersedes the prior active 132 job, and the configured queue capacity is enforced beneath a fixed 65,536-job 133 hard ceiling. 134 135 Claims and renewals are compare-and-swap transitions over an immutable job 136 identity and monotonic revision. Leases use caller-injected 16-byte owner 137 tokens and integer UTC milliseconds; expired leases can be reclaimed, while 138 an expired final attempt becomes exhausted. Failed attempts persist their next 139 eligible time using caller-injected full jitter bounded by the job's governed 140 exponential backoff. No ambient clock or entropy is read, and no source or 141 network work occurs inside a database transaction. The exact machine contract 142 is 143 [`reconciliation_jobs.v1.json`](contracts/services_hardening/reconciliation_jobs.v1.json). 144 145 ## Bounded reconciliation source attempts 146 147 `RhiReconciliationAttemptPlan` derives one canonical source-request inventory 148 from an unexpired claimed job lease and the exact normalized evidence policy. 149 The attempt, selector, and each source request have domain-separated SHA-256 150 identities. Every request binds the source ID, required/optional authority, 151 trade selector, absolute deadline, lookback, and configured result limits. 152 The claimed job's retained lease, retry, and attempt policy must also equal the 153 exact normalized configuration; queue capacity remains admission authority for 154 new jobs rather than per-attempt identity. The attempt deadline and every 155 source deadline are capped by the retained lease expiry; no implicit clock or 156 deadline is consulted. 157 158 `RhiReconciliationSourceResult` records one stable completion code, explicit 159 start and finish times, and bounded accepted-event count and bytes. Exact EOSE 160 completion must occur before the source deadline, timeout begins at the 161 deadline, unsupported sources cannot report accepted events, and no outcome 162 can be omitted, duplicated, reordered, or appended beyond the configured 163 source inventory. Planning and result validation are pure and perform no 164 SQLite, source, relay, network, filesystem, task, clock, or entropy operation. 165 Cursor derivation, source execution, and durable completion commit remain with 166 their later ordered checkpoints. The exact machine contract is 167 [`reconciliation_attempts.v1.json`](contracts/services_hardening/reconciliation_attempts.v1.json). 168 169 ## Overlap-safe reconciliation replay 170 171 `RhiReconciliationSourceReplayPlan` binds one exact source request to optional 172 sealed prior-cursor evidence, configured overlap, and an inclusive query start 173 under a domain-separated identity. The evidence is sealed to the source, 174 trade, evidence-policy digest, and selector digest, so callers cannot forge or 175 relabel progress. This pure replay model provides no evidence-minting path; the 176 atomic commit boundary below alone constructs it after replay and cursor commit. 177 Initial 178 queries use the configured lookback; resumed queries subtract the configured 179 overlap from the prior authored-time 180 cursor so equal-timestamp events remain discoverable. A cursor becomes 181 eligible only after exact `complete` source evidence, but remains an in-memory 182 candidate that this pure model cannot promote to resumption authority. 183 184 The replay inventory consumes at most the request event limit plus one and 185 bounds all original event bytes before deduplication. It accepts only the 186 request's trade, orders admitted signed events canonically, collapses exact 187 event replay, retains the earliest injected source observation, and rejects 188 conflicting mutation or signed-event identity reuse. Result counts and bytes 189 are derived from the distinct canonical inventory rather than caller claims. 190 It performs no SQLite, source, relay, network, filesystem, task, clock, or 191 entropy operation. Durable scope revalidation, result/completion persistence, 192 and checkpoint advancement belong to the atomic commit boundary below. The 193 exact machine contract is 194 [`reconciliation_replay.v1.json`](contracts/services_hardening/reconciliation_replay.v1.json). 195 196 ## Atomic reconciliation result commit 197 198 `RhiReconciliationAttemptRepository::commit_source_replays` accepts exactly one 199 bounded replay result for every request in a claim-derived attempt. One short 200 SQLx transaction first revalidates the exact live lease, trade dirty generation, 201 evidence-policy digest, and each source-scoped prior checkpoint. It then commits 202 canonical mutations, signed events, first-source observations, the immutable 203 attempt and source-result inventory, a domain-separated digest of every exact 204 ordered persisted fact and provenance value, at most one dirty-generation 205 advance, and only eligible cursor checkpoints as one atomic unit. No source, 206 relay, network, clock, entropy, or task operation occurs inside that 207 transaction. 208 209 Only exact `complete` evidence with a strictly newer candidate advances a 210 checkpoint. Timeout, unavailable, resource-limited, unknown, and unsupported 211 results remain durable but never become progress. Newly inserted canonical 212 mutation or signed-event evidence advances the dirty generation once for the 213 whole attempt; observation-only replay does not. Exact retry of an already 214 committed attempt reconciles idempotently before stale lease or generation 215 fences, while any inventory mismatch fails closed. Sealed source/trade/policy/ 216 selector cursor evidence is minted only after durable commit confirmation. The 217 exact machine contract is 218 [`reconciliation_commit.v1.json`](contracts/services_hardening/reconciliation_commit.v1.json). 219 220 ## Immutable reconciliation manifest 221 222 `RhiReconciliationSourceCommitOutcome::into_evidence_manifest` consumes one 223 sealed, durably confirmed Step 190 outcome and freezes its exact canonical 224 mutation, signed-event, first-provenance, and per-source completion inventory 225 into the shared `radroots.trade.evidence-manifest.v1` encoding. The manifest 226 binds the claimed trade generation and evidence-policy digest. Each source 227 result additionally binds its exact selector digest, detailed completion, 228 timing, cursor inputs, checkpoint eligibility, and Step 190 persisted-inventory 229 digest. Each observation binds the verified mutation and event identities, the 230 SHA-256 of the exact canonical signed-event JSON, and a source/selector/policy/ 231 signature/first-observation provenance digest. 232 233 Sources and observations use the shared canonical ordering, so arrival and 234 insertion order cannot select truth. The explicit whole-second observation 235 time cannot precede any committed source finish, and the explicit closed scope- 236 prerequisite input is included in the immutable bytes. Callers can inspect only 237 the redacted sealed result's identity, counts, canonical bytes, and digest; they 238 cannot construct a manifest from uncommitted replay material or supply its 239 result/provenance digests. Materialization is pure and performs no SQLite, 240 filesystem, source, relay, network, task, clock, or entropy operation. Durable 241 manifest persistence remains deferred to Step 199, and reduction, final 242 coverage/outcome, attestation, and publication retain their later checkpoint 243 owners. The exact machine contract is 244 [`reconciliation_manifest.v1.json`](contracts/services_hardening/reconciliation_manifest.v1.json). 245 246 The Step 192 integration-wave qualification proves that concurrent exact 247 commits converge to one durable attempt and byte-identical manifest, a blocked 248 commit can be cancelled with no authoritative effect and retried, an exact 249 lost-success retry converges after close/reopen, and an infinite replay 250 inventory terminates at configured source count plus one before mutation. The 251 same corpus covers exact source deadlines, incomplete checkpoint exclusion, 252 lease expiry/reclaim, queue and result bounds, stale leases/generations, and 253 durable reopen behavior without adding runtime, scheduler, source, or network 254 authority. 255 256 ## Pure reconciliation reducer 257 258 [`reconciliation_reducer.v1.json`](contracts/services_hardening/reconciliation_reducer.v1.json) 259 binds the promoted shared `radroots.trade.reducer.v1` to one sealed confirmed 260 reconciliation manifest. The manifest privately retains only the bounded 261 canonical mutation material derived from its Step 190 commit; callers cannot 262 inject or replace reducer inputs. Reduction consumes the owned manifest, 263 retains it inside a sealed projection, and binds the shared projection digest 264 to the manifest and evidence-policy digests with a separate domain-separated 265 RHI digest. The projection retains the canonical shared result privately for 266 later checkpoints while exposing only bounded identity, digest, and count 267 evidence. 268 Reduction performs no SQLite, filesystem, source, relay, network, task, clock, 269 or entropy operation. Generation-fenced persistence, reports, attestations, 270 and publication retain their later checkpoint owners. 271 272 [`reconciliation_outcome.v1.json`](contracts/services_hardening/reconciliation_outcome.v1.json) 273 derives one claim-specific evaluation from that sealed projection. 274 Coverage is exactly `Missing`, `Partial`, `ScopeSatisfied`, or `Unsupported`; 275 outcome is 276 exactly `Valid`, `Invalid`, or `Indeterminate`. Missing, partial, unsupported, 277 digest-unavailable, unresolved, ambiguous, or absent-claim evidence is always 278 indeterminate. Only a clean active agreement claim is valid, and only a clean 279 cancelled agreement claim is decisively invalid. Every evaluation retains its 280 projection and exposes exactly one closed stable primary reason code without 281 adding I/O or ambient authority. 282 283 ## Generation-fenced finalization preflight 284 285 `RhiReconciliationAttemptRepository::prepare_finalization` consumes one sealed 286 evaluation plus the exact live claimed lease. The manifest privately retains 287 its Step 190 attempt and job identities without changing canonical manifest 288 bytes or its digest, so an older attempt cannot be relabelled with a reclaimed 289 worker's distinct attempt authority. One bounded read-only SQLite transaction 290 checks the unexpired exact lease, current dirty generation, evidence-policy 291 digest, and immutable committed-attempt row before returning a sealed 292 `RhiReconciliationFinalizationFence`. 293 294 The fence is a preflight capability, not durable commit proof: state may change 295 after it is returned. Step 199 must rerun the same validator inside the final 296 atomic transaction before its first write. This checkpoint writes no manifest, 297 projection, report, signed event, outbox, checkpoint, or job state and performs 298 no source, relay, network, filesystem, task, clock, or entropy operation. The 299 exact machine contract is 300 [`reconciliation_finalization.v1.json`](contracts/services_hardening/reconciliation_finalization.v1.json). 301 302 ## Canonical signed reconciliation attestation 303 304 `build_rhi_signed_evidence_attestation` consumes one sealed Step 195 305 finalization fence and derives the shared canonical RHI evidence report only 306 from its immutable manifest, projection, evaluation, and claim identity. The 307 report issuer is the independently verified encrypted service identity. The 308 optional supersession reference can be derived only from an earlier sealed, 309 verified signed-attestation result, and the shared ordering validator rejects 310 stale or misbound successors. 311 312 The event body and exact kind-3441 structural tags come only from the promoted 313 typed `radroots_event_codec` builder. Authored time and the 32 bytes of Schnorr 314 auxiliary randomness are injected explicitly. The boundary then independently 315 reparses the bounded signed NIP-01 JSON, recomputes its event identifier, 316 verifies its signature and exact plan fields, decodes the typed attestation, 317 reparses the canonical report, and revalidates its exact manifest binding. 318 319 The sealed result owns the finalization fence, canonical report, verified event 320 identifier, exact signed bytes, and the SHA-256 of those bytes. Later 321 persistence must retain those bytes without rebuilding, reserializing, or 322 re-signing them. This checkpoint performs no SQLite, filesystem, relay, 323 network, task, ambient-clock, or ambient-entropy operation. The schema-v7 324 catalog is frozen by Step 198; the generation-fenced write, publication, and 325 job finalization remain with Step 199 and its successors. The exact machine contract is 326 [`reconciliation_attestation.v1.json`](contracts/services_hardening/reconciliation_attestation.v1.json). 327 328 ## Explicit publication authority and durable schema 329 330 `RhiPublicationAuthority::from_config` is the sole public derivation boundary 331 for publication intent. It consumes one complete validated RHI configuration 332 and returns exactly `Required` or `Disabled`. Required authority preserves the 333 explicit ordered write-relay targets, each target's requiredness, the bounded 334 retry policy, and queue capacity under separate domain-separated target-set 335 and complete-authority digests. Disabled authority contains no target or retry 336 state and authorizes no hidden network work. The sealed result exposes no URL, 337 credential, transport, SQLite, clock, entropy, or task authority. 338 339 Schema v7 freezes immutable manifest, projection, report, exact signed-event, 340 and publication-attempt records plus compare-and-swap outbox and target rows. 341 No-update/no-delete triggers protect semantic payload and target identities; 342 the closed target evidence vocabulary distinguishes pending, submitted, 343 accepted, rejected, rate-limited, auth-required, failed, and unknown. This 344 checkpoint defines and verifies the catalog only. Step 199 owns the first 345 atomic finalization write, and Steps 200-203 own claims, relay submission, 346 outcomes, retry, recovery, and wave qualification. The exact machine contract 347 is 348 [`publication_outbox.v1.json`](contracts/services_hardening/publication_outbox.v1.json). 349 350 ## Deterministic durable presence intent 351 352 `RhiPresenceDesiredAuthority::from_config` derives the exact ordered 353 service-profile and application-handler intent from one complete admitted 354 configuration. It binds the verified service public identity, the configured 355 relay-ID order and requiredness, and the bounded presence queue under separate 356 domain-separated target-set and semantic desired-state digests. An independent 357 validator re-derives that authority from the same complete configuration. 358 359 Schema v9 stores only one sealed semantic desired-state snapshot. The first 360 commit creates generation one, exact semantic replay performs no write, and a 361 semantic change advances exactly one compare-and-swap generation. Every commit 362 must still match the latest durable configuration binding. The table stores no 363 relay URL, filesystem path, rendered event, signature, authored time, delivery 364 attempt, or network result, and its triggers reject deletion and ungoverned 365 updates. Rendering, signing, target delivery state, retries, and relay I/O remain 366 separate from this semantic-intent commit. The exact machine contract is 367 [`presence_desired_state.v1.json`](contracts/services_hardening/presence_desired_state.v1.json). 368 369 ## Durable exact-byte presence publication 370 371 `build_rhi_signed_presence_documents` consumes one committed desired-state 372 generation, the independently revalidated complete presence authority, the 373 matching decrypted service identity, caller-injected authored time, and 374 caller-injected Schnorr auxiliary entropy. It builds the kind-0 service profile 375 through the typed `radroots_event` profile plan and cross-checks the kind-31990 376 application-handler plan produced by `radroots_nostr` against the typed 377 `radroots_event` plan. Every signed document is then independently parsed under 378 the bounded NIP-01 wire limits and revalidated for event ID, signature, author, 379 kind, time, ordered tags, and exact content before exposure. 380 381 Schema v10 retains each independently verified exact signed byte sequence, 382 digest, document identity, and complete immutable target inventory. One short 383 SQLx-owned transaction commits those bytes and initial target state before any 384 injected `RhiExactPresenceSink` can observe them. A second short transaction 385 commits `submitted` before remote I/O. The remote await owns no transaction; 386 the first commit borrows rather than consumes its sealed document set, so an 387 unknown commit result can be reconciled by replaying the same retained bytes; 388 the resulting closed outcome, immutable attempt evidence, target schedule, 389 outbox disposition, and lease release are committed together afterward. 390 Cancellation or acknowledgement loss after `submitted` becomes durable 391 `unknown` before the same retained bytes can be retried. Expired work from a 392 superseded desired generation is recorded as `unknown` and the old outbox is 393 superseded without sampling retry entropy, preventing stale leases from 394 blocking the current generation forever. No retry parses, rebuilds, 395 reserializes, or re-signs an event, and no raw relay diagnostic is persisted. 396 The exact machine contract and deterministic signed vectors are 397 [`presence_publication.v1.json`](contracts/services_hardening/presence_publication.v1.json). 398 399 ## Atomic reconciliation finalization commit 400 401 `RhiReconciliationAttemptRepository::commit_finalization` borrows one sealed, 402 independently verified signed attestation and the publication authority derived 403 from the same normalized configuration as the open state host. One short 404 SQLx-owned transaction first reconciles an exact prior success, then reruns the 405 live lease, dirty-generation, policy, committed-attempt, source-inventory, 406 checkpoint, supersession, and publication-capacity fences before its first 407 write. 408 409 The same transaction retains the exact canonical manifest, projection, 410 canonical report, and independently verified signed-event bytes; records the 411 explicit supersession; creates the immutable outbox and ordered target set only 412 when publication is required; and completes the exact reconciliation job. 413 Disabled publication creates no outbox or target row. An exact retry returns 414 `created = false` even after the lease was consumed or expired, while any 415 mismatched durable footprint fails closed. This boundary performs no source or 416 relay I/O, network access, filesystem access, task spawn, ambient clock read, 417 or ambient entropy read. Publication claims and relay submission remain later 418 steps. The exact machine contract is 419 [`reconciliation_finalization_commit.v1.json`](contracts/services_hardening/reconciliation_finalization_commit.v1.json). 420 421 ## Exact committed publication bytes 422 423 `RhiPublicationOutboxRepository::read_committed_publication` joins one immutable 424 schema-v7 outbox to its signed-attestation row in one bounded read-only SQLx 425 transaction. It admits at most 32,768 stored bytes, rechecks the exact outbox, 426 event-identifier, and SHA-256 bindings, and returns a sealed 427 `RhiCommittedPublication`. Repeated reads and reads after a clean close/reopen 428 return the same committed byte string or fail closed. 429 430 The capability is not a relay claim or lease. Its only payload accessor returns 431 the stored bytes unchanged; this path contains no JSON or event parsing, 432 rebuilding, reserialization, signing, relay/network/filesystem work, task 433 spawn, or ambient clock/entropy access. The closed target/attempt evidence model 434 is defined below; durable claims and transitions, relay I/O, retry scheduling, 435 and lease recovery remain with Step 202. The exact machine contract is 436 [`publication_submission.v1.json`](contracts/services_hardening/publication_submission.v1.json). 437 438 ## Bounded publication attempt evidence 439 440 The publication target state is one closed value: pending, submitted, accepted, 441 rejected, rate-limited, auth-required, failed, or unknown. Pending is not an 442 attempt outcome, Accepted is the sole terminal target state, submission alone 443 does not prove relay delivery, and Unknown can be refined only by independent 444 evidence. Attempt outcomes use the same closed vocabulary except Pending and 445 expose no arbitrary result string or upstream diagnostic. 446 447 `RhiPublicationAttemptEvidence` binds the sealed committed outbox identity and 448 exact event digest to a zero-based target ordinal no greater than 31, a 449 one-based attempt number no greater than 100, ordered injected integer UTC 450 milliseconds, and one closed outcome under a domain-separated SHA-256 identity. 451 It is pure bounded evidence rather than claim, transition, or relay authority. 452 Step 202 must revalidate live target, lease, revision, attempt, and exact-byte 453 bindings when it persists Submitted before I/O and later commits an observed 454 outcome. The exact machine contract is 455 [`publication_attempt_evidence.v1.json`](contracts/services_hardening/publication_attempt_evidence.v1.json). 456 457 ## Durable exact-byte publication execution 458 459 `RhiPublicationOutboxRepository` claims one due outbox with an injected 460 nonzero owner and bounded lease only after binding the outbox and complete 461 target inventory to the exact current required-publication authority. It 462 persists the exact target as Submitted before remote I/O and exposes the 463 original committed byte slice only through `RhiExactPublicationSink`. This 464 dedicated boundary deliberately does not pass the payload through the generic 465 typed-event sink: retries never parse, reconstruct, reserialize, or re-sign 466 committed evidence. 467 468 Observed outcomes append one immutable attempt row and compare-and-swap the 469 target, persisted retry schedule, outbox disposition, and lease release in one 470 short SQLx-owned transaction. Full-jitter exponential backoff uses only 471 injected entropy. Cancellation or acknowledgement loss after Submitted remains 472 Unknown; expired-lease recovery appends that conservative evidence before an 473 exact-byte retry or exhaustion. No transaction remains open across relay I/O, 474 and an unknown local commit must be reconciled by exact attempt identity. The 475 exact machine contract is 476 [`publication_execution.v1.json`](contracts/services_hardening/publication_execution.v1.json). 477 478 Step 203 closes this wave with executable crash/reopen, shared transactional 479 failpoint, concurrent-claim, queue-bound, and redaction qualification. Schema 480 v8 first scans every historical reconciliation job and fails closed without 481 repair when a `ready` schedule or `leased` owner/expiry is missing. Only after 482 that scan succeeds does the same governed migration install permanent INSERT 483 and UPDATE state-shape guards. The exact qualification inventory and bounds are 484 [`publication_wave_qualification.v1.json`](contracts/services_hardening/publication_wave_qualification.v1.json). 485 486 ## Existing-state runtime foundation 487 488 `open_rhi_runtime_foundation` opens only an already initialized database from 489 the sealed service-instance intent, discovers its source generation under the 490 retained writer authority, verifies the latest append-only configuration 491 binding, and then resolves the credential before independently opening the 492 encrypted service identity. Missing state is never initialized by ordinary 493 startup. No evidence source, live subscription, or publication sink is 494 contacted before the durable configuration binding is proven. 495 496 The passive readiness snapshot initially proves only existing state, durable 497 configuration, and verified identity. Recovery, source connectivity and 498 subscription, publication recovery, admin and optional operations listeners, 499 and configured presence desired state remain explicitly unsatisfied for their 500 later owning checkpoints. Reading the snapshot performs no filesystem, 501 SQLite, credential, identity, DNS, or network probe. The foundation installs 502 no signals, runtime, logger, or process-exit policy and does not claim the final 503 supervised task graph. Its exact machine contract is 504 [`runtime_foundation.v1.json`](contracts/services_hardening/runtime_foundation.v1.json). 505 506 ## Passive lifecycle status and TCP operations 507 508 `rhi_status_cache` retains exactly one latest immutable RHI lifecycle and 509 detailed-status publication behind a single non-cloneable publisher. Each 510 publication is bounded and validated before it replaces the prior snapshot. 511 Readers clone only passive cache authority; they perform no SQLite, 512 filesystem, evidence-source, relay, DNS, identity, credential, clock, or fresh 513 probe operation. Detailed JSON is reserved for the permissioned Unix-admin 514 surface and contains only the closed service identity, evidence transport, 515 reconciliation, publication, presence, persistence, configuration, build, and 516 stable reason vocabularies. Its exact contract is 517 [`status_cache.v1.json`](contracts/services_hardening/status_cache.v1.json). 518 519 When the validated operations block is enabled, `RhiOperationsServer` exposes 520 exactly HTTP/1.1 `GET /livez`, `GET /readyz`, and `GET /metrics` on its admitted 521 TCP address. Requests read only the latest cached lifecycle/readiness and two 522 fixed bounded metric families; they cannot register another route or reach 523 detailed status. Requests perform no SQLite, filesystem, evidence-source, 524 relay, DNS, identity, credential, clock, or active health probe. The listener 525 is disabled by default and remains a supervisor-owned optional adapter. Its 526 exact contract is 527 [`tcp_operations.v1.json`](contracts/services_hardening/tcp_operations.v1.json). 528 529 ## Hardened v1 configuration contract 530 531 The target service configuration is frozen by 532 `contracts/services_hardening/config.v1.schema.json` and the canonical 533 non-secret `config.v1.example.toml`. It is one strict immutable TOML document 534 with explicit identity, relay, evidence-source, reconciliation, attestation, 535 publication, presence, resource, and retention authority. The evidence fields 536 and maxima consume `evidence_policy.v1.json` without reinterpretation. Only 537 reviewed bounded operational leaves have defaults. Bootstrap profile, 538 instance, repo-local root, and config-path selection are CLI concerns and are 539 not document fields. 540 541 The retired root `config.toml`, transitional runtime loader, JSON state 542 adapter, environment and worker selectors, and prototype smoke/runtime paths 543 are removed. The executable admits one strict CLI invocation and one sealed 544 runtime context, then fails closed until later ordered checkpoints bind each 545 command to its governed state and runtime authority. It never falls back to a 546 prototype execution path. 547 548 `parse_rhi_config_v1` is the strict in-memory admission boundary for the target 549 document. It bounds original bytes before parsing, rejects malformed duplicate 550 or null TOML and unknown fields, validates the bootstrap-selected relay posture 551 and all cross-field relationships, and returns an immutable document with a 552 deterministic bounded redacted effective projection. The projection records the 553 exact `toml` or `safe_default` origin for every leaf and the governed authority 554 behind each safe default. Parsing performs no filesystem, environment, 555 identity, database, clock, entropy, logging, DNS, or network operation. 556 557 ## Hardened v1 command admission 558 559 `parse_rhi_cli_v1_from` parses the bootstrap and closed command tree exactly 560 once. Every invocation explicitly selects `service-host`, `interactive`, or 561 `repo-local`, a validated instance, and optionally an absolute configuration 562 path. Repo-local selection additionally requires one absolute base root and 563 that root is forbidden for the other profiles. Human output is the default; 564 governed JSON output is selected explicitly. 565 566 The command inventory covers daemon run; config init, validate, show, schema, 567 and apply; state init, status, backup, restore, verify, and migrate; service 568 identity init, status, and public export; service status and metrics snapshot; 569 reconciliation status, jobs, and refresh; source listing; trade projection and 570 report queries; publication backlog, targets, and retry; desired-presence 571 inspection, render, and refresh; and doctor. The parser performs no command 572 execution. The admitted invocation projects once into a sealed execution plan: 573 `run` selects daemon authority; config initialization, validation, schema, and 574 apply, exclusive state maintenance, initial identity provisioning, and doctor 575 select offline authority; and the remaining twenty commands map one-to-one to 576 the final twenty permissioned Unix-admin routes. No live command carries an 577 offline or direct-SQLite fallback. Later ordered steps bind each command's exact 578 input and execute the already-selected authority without reparsing arguments. 579 580 Ordinary `run` accepts no identity-generation, identity-path, log-path, 581 database-path, worker, environment-file, or arbitrary path-leaf flag. Identity 582 rekey and replacement are not commands; rotation is a create-new offline 583 artifact plus governed configuration apply. 584 585 ## Bounded active doctor and stable process results 586 587 The doctor runs the governed fifteen checks in exact contract order. Each 588 check has one fixed deadline, required or optional authority, a closed evidence 589 scope, and a safe remediation code. Required checks must pass; required 590 failure, timeout, or an invalid skipped result makes the aggregate `fail`. 591 Optional non-pass makes the aggregate `degraded`, while every passing check 592 makes it `pass`. A timed-out probe is cancelled by dropping its future, and no 593 detached probe work is permitted. 594 595 The compact canonical JSON report is capped at 8,192 UTF-8 bytes. Its summaries 596 come only from the fixed content-free vocabulary and cannot contain paths, raw 597 errors, relay text, identifiers, credentials, or other protected material. 598 Required failure or timeout returns exit code `6`; the complete process-result 599 contract is the closed zero-through-six inventory in 600 [`operator_contract.v1.json`](contracts/services_hardening/operator_contract.v1.json). 601 The executable emits only the stable result code on stderr and never renders a 602 parser, path-resolution, dependency, or internal error. 603 604 ## Unix-admin boundary 605 606 Step 206 bound the seven common RHI routes for detailed status, redacted 607 effective configuration, service-identity status and public export, state 608 status, online backup, and a bounded metrics snapshot to the shared 609 `radroots_service_host` HTTP/1.1-over-Unix server. The public RHI route and 610 document types are closed, response construction admits only bounded compact 611 canonical JSON matching the exact machine model, and public diagnostics retain 612 no path, request, identity, or dependency-owned cause. 613 614 The server projects only the normalized configuration's admitted transport 615 limits, derives `admin.sock` only from the sealed runtime context, acquires the 616 shared writer authority before binding, and uses the shared server's system 617 entropy for absent correlation IDs. Construction does no I/O; binding does not 618 spawn; serving remains a later supervised runtime responsibility. Raw shared 619 routers, listeners, JSON values, and caller-selected socket paths never cross 620 the public RHI boundary. Its historical partial machine contract is 621 [`admin_common.v1.json`](contracts/services_hardening/admin_common.v1.json). 622 623 Step 207 cumulatively activates the thirteen reconciliation, job, source, 624 trade projection/report, publication target/backlog, retry, and presence 625 domain routes. Page sizes stop at 200; query names and duplicates are closed; 626 cursors use canonical base64url without padding and remain authenticated and 627 bound by the handler to the same route, filters, and snapshot. Every decoded 628 `{trade_id}` is exactly 32 lowercase hexadecimal characters. Mutations retain 629 stable operation-ID exact replay and conflicting-reuse rejection, and success 630 still means the handler's contract-defined local effect is durably committed, 631 not relay delivery. The adapter performs no SQLite or relay I/O itself. The 632 Step 208 removes the two never-registered live identity rekey/replace routes, 633 their three mutation-only models, and the unused operator types that could have 634 suggested live provider authority. Identity rotation is only offline create-new 635 envelope plus validated configuration apply and restart. Unix peer authorization 636 remains a transport admission gate and grants neither direct SQLite nor 637 identity-provider mutation authority. Step 209 qualifies the complete 638 20-route/33-model inventory with real Unix-socket original-wire, version, 639 pagination, idempotency, peer-permission, removed-route, and resource negative 640 matrices plus the exact source-locked shared-transport corpus. The cumulative 641 domain contract is 642 [`admin_domain.v1.json`](contracts/services_hardening/admin_domain.v1.json). 643 The offline identity correction is 644 [`admin_identity_offline.v1.json`](contracts/services_hardening/admin_identity_offline.v1.json). 645 The completed admin-wave qualification is 646 [`admin_wave_qualification.v1.json`](contracts/services_hardening/admin_wave_qualification.v1.json). 647 648 ## Sealed service-instance paths 649 650 One validated CLI invocation resolves through `RhiRuntimeContext`, which owns 651 the shared typed `RuntimeContext`, exact common artifacts, the validated 652 `service.identity.ncrypt` encrypted identity artifact path, and the explicit or 653 canonical configuration selection. The service identity is fixed to `rhi`; the instance 654 comes only from `InstanceId`; profile and repo-local-root provenance are the 655 closed `bootstrap_cli` vocabulary. Callers cannot construct or mutate another 656 path set, override artifact names, or obtain a public path report. 657 658 Service-host roots are exactly 659 `/etc/radroots/services/rhi/<instance>`, 660 `/var/lib/radroots/services/rhi/<instance>`, 661 `/var/cache/radroots/services/rhi/<instance>`, 662 `/var/log/radroots/services/rhi/<instance>`, 663 `/run/radroots/services/rhi/<instance>`, and 664 `/etc/radroots/secrets/services/rhi/<instance>`. Interactive roots consume the 665 injected host environment defined by `radroots_runtime_paths`; repo-local uses 666 one explicit absolute base and the same `services/rhi/<instance>` namespace. 667 Path resolution performs no directory creation or filesystem I/O. 668 669 ## Governed SQLite catalog 670 671 RHI owns one `state.sqlite` per service instance. Create-new initialization 672 starts from the shared schema-v1 baseline and immediately applies the pinned 673 schema-v2 configuration migration, schema-v3 immutable trade-evidence 674 migration, schema-v4 source-checkpoint and dirty-generation migration, 675 schema-v5 bounded reconciliation-job migration, schema-v6 immutable 676 reconciliation-result migration, and schema-v7 immutable report, signed-event, 677 publication-workflow migration. Schema v8 adds reconciliation-attempt replay 678 evidence, schema v9 adds durable presence desired state, and schema v10 adds 679 the exact-byte presence outbox, target, and attempt inventory. 680 Version ten contains the six shared immutable service-metadata and 681 migration-ledger objects, the bounded append-only `rhi_config_bindings` table, 682 separate immutable tables for canonical mutations, signed Nostr events, and 683 accepted source observations, and generation-guarded relay checkpoints and 684 per-trade dirty generations with their enforcement triggers and indexes. 685 It also retains immutable attempt, source-result, manifest, projection, report, 686 signed-event, and publication-attempt rows plus compare-and-swap outbox and 687 target state under exact transition and retention triggers. 688 Exact literal SHA-256 values bind both migrations, every schema snapshot, and 689 the schema catalog. RHI validates every identity before it can become database 690 authority. 691 692 The configuration history retains at most 1,024 consecutive generations. Each 693 row stores only normalized configuration and evidence-policy digests, the 694 public service identity, exact contract versions, injected apply time, and 695 bounded build identity. It never stores raw TOML, paths, relay URLs, credential 696 references, or protected identity material. Startup requires the latest row to 697 match the admitted document. `apply_rhi_configuration` obtains exclusive 698 offline authority, verifies the current binding, appends the candidate 699 atomically, treats exact replay idempotently, and explicitly closes state. 700 701 Catalog construction itself performs no filesystem or SQLite I/O and owns no 702 pool, connection, transaction, query, or migration executor. The sealed state 703 host alone executes the governed migrations and typed state transactions. 704 Evidence manifests, reports, attestations, publication state, and final job 705 completion remain reserved for their later owning checkpoints. 706 707 The sealed RHI state-host lifecycle now reserves and initializes a missing 708 canonical database only through an explicit create-new operation. Ordinary 709 writable and immutable inspection modes open existing state only, validate the 710 exact schema and migration identities, and retain mutually exclusive shared 711 authority until explicit idempotent close. Missing state is never initialized 712 by an open operation. No raw host, pool, connection, transaction, executor, or 713 path escapes the RHI wrapper. 714 715 One sealed RHI state-metadata capability now binds that lifecycle to the exact 716 service and instance, nonzero source generation, `RDRH` SQLite application ID, 717 schema version, creation time, fully normalized configuration digest, 718 contract-defined evidence-policy digest, expected service public identity, and 719 configuration/state/admin/status/provider contract versions. Its fields are 720 immutable; ordinary Debug and errors redact paths, identities, generations, 721 and digests. 722 723 The governed encrypted-file identity boundary accepts only the shared 724 version-2 `radroots_secrets` envelope, binds its authenticated context to the 725 service role, expected public key, payload schema, and separately named 726 wrapping-credential reference, and releases a zeroizing identity only after 727 the derived public key matches configuration. Offline provisioning is 728 create-new and caller-supplied; ordinary startup never generates an identity, 729 legacy envelopes are rejected, and RHI state backups contain no envelope, 730 wrapping credential, or plaintext identity. 731 732 The separately governed wrapping-credential resolver derives exactly one 733 validated artifact name from the admitted identity binding and resolves it only 734 beneath the same runtime context's canonical instance secrets root. It accepts 735 only an existing 32-byte, owner-controlled, single-link regular file for 736 service-host and repo-local profiles. It never accepts caller paths or bytes, 737 creates credentials or directories, consults environment or process arguments, 738 or falls back to an adjacent envelope sibling. The former prototype identity 739 and adjacent-key storage APIs are not part of the crate surface. 740 741 The wave-two composition proof binds configuration, runtime paths, immutable 742 state metadata, the encrypted identity, and its separately resolved credential 743 to one service instance. It proves that state initialization and existing-only 744 open do not persist the identity secret, credential, encrypted-envelope wire 745 material, or credential reference in `state.sqlite`. The envelope and 746 credential remain excluded from the state-backup contract. That earlier 747 wave-two boundary proof did not itself execute a backup; the governed 748 resilience boundary below now owns the actual backup and recovery mechanics. 749 750 Explicit state initialization validates runtime identity, build evidence, and 751 the complete migration/schema catalogs before invoking the runtime-path 752 directory plan. That plan alone may provision the exact interactive 753 `services/rhi/<instance>` suffix; service-host deployment roots and suffixes 754 must already exist. The shared service-SQLite initializer owns the one 755 transaction and exposes only its sealed typed SQLx executor. Existing writable 756 and inspection opens never provision directories or create missing state. 757 758 RHI's state surface is partitioned into twenty-one distinct non-forgeable typed 759 repository capabilities bound to one already-opened `RhiStateHost`. Their 760 closed topology covers source results, cursors, completions, admitted signed 761 events, canonical mutations, provenance, dirty generations, reconciliation 762 jobs and attempts, immutable manifests/projections/reports, supersession, 763 signed attestation events, publication outbox/targets/attempts, desired 764 presence, and presence outbox/targets/attempts. Each capability has one exact backing-table identity and an 765 append-only, compare-and-swap, or immutable write class. It exposes no raw 766 pool, connection, transaction, SQL, path, or cloneable write authority. 767 Schema migration and verification, remaining repository behavior, 768 backup/restore, service task ownership, and admin routing remain owned by their 769 later ordered checkpoints. 770 771 RHI now composes the shared SQLx-owned resilience boundary without exposing a 772 second database authority. A writable `RhiStateHost` can capture one governed 773 online backup, and either host mode can run an explicit bounded integrity 774 inspection. Offline verification returns a sealed exact-inode proof; staging 775 retains exclusive writer authority; finalization uses the shared durable 776 marker and atomic replacement protocol; and the next writable existing-state 777 open reconciles interrupted restore evidence before exposing a host. Read-only 778 inspection never performs recovery. Callers inject all times, manifest bytes 779 and digest, and the positive backup-size limit. RHI adds no SQLite dependency, 780 raw connection, background runtime, implicit deadline, or direct file-copy 781 authority. 782 783 ## Failure-resilience qualification 784 785 The machine-readable 786 [`failure_qualification.v1.json`](contracts/services_hardening/failure_qualification.v1.json) 787 contract freezes the Step 214 evidence corpus for resource and backlog bounds, 788 disk and durable-state behavior, corruption and malformed history, 789 cancellation, outage recovery, and safe errors. Every RHI entry names an 790 executable component test, while shared SQLite durability, capacity, 791 corruption, migration-history, cancellation, backup, close, and restore 792 evidence is bound to the exact retained Lib source lock. SQLx remains the sole 793 high-level SQLite authority; no production failpoint or environment-selected 794 test path is introduced. 795 796 This checkpoint is deliberately component-scoped. The actual-process and 797 bounded-soak qualification remains Step 215 ownership, native release 798 artifacts remain Step 216 ownership, and promotion and parent-pin alignment 799 remain Step 217 ownership. Nix, OCI, signing, publication, and deployment are 800 deferred and unclaimed. 801 802 The Step 215 803 [`process_qualification.v1.json`](contracts/services_hardening/process_qualification.v1.json) 804 contract closes wave `130-c` by binding that component corpus to the actual 805 RHI executable. It exercises offline bootstrap and required-dependency outage, 806 the complete supervised task graph against loopback relay sessions, eight 807 concurrent read-only configuration-validation processes, and 32 clean database 808 reopen-and-verify cycles. The live daemon is interrupted, joined, reaped, and 809 checked for socket cleanup. Every child process has a fixed deadline and 810 bounded captured output. The test surface adds no production failpoint, 811 environment selector, detached worker, ambient network dependency, or later 812 release authority. 813 814 ## Standalone native release contract 815 816 The capsule owns a private `cargo xtask native-release` generator and the 817 machine-readable 818 [`native_release.v1.json`](contracts/services_hardening/native_release.v1.json) 819 predecessor and the forward 820 [`native_release.v3.json`](contracts/services_hardening/native_release.v3.json) 821 contract. From one exact clean committed revision, a caller-supplied positive 822 deterministic epoch, and an executable ELF64 binary for one governed GNU/Linux 823 target, the generator creates one external immutable artifact directory. It 824 contains the binary archive, a vendored offline source archive, the non-secret 825 configuration example and schema, the standalone systemd unit, exact source 826 lock, license and notices, CycloneDX SBOM, unsigned provenance input, artifact 827 manifest, and sorted SHA-256 checksums. 828 829 Generation is bounded, deterministic, collision-only, mode checked, and 830 durability ordered. It scans exact tracked source, the selected binary, copied 831 package inputs, and generated documents for governed protected-value patterns, 832 then records that protected material and OCI content are absent while binding 833 bound Nix inputs requiring separate current execution evidence. The 834 source-locked third-party vendor graph is 835 represented separately by checksums, SBOM, and notices. The generator does 836 not sign, tag, publish, deploy, or write artifacts into the source tree. The standalone 837 `scripts/release-acceptance.sh` surface exercises the native Cargo contract; 838 when invoked by the parent monorepo it is itself run through extbuild. 839 SBOM component references are domain-separated hashes of framed Cargo 840 name/version/source/checksum identity, so they neither disclose a checkout path 841 nor vary when the same exact source is built from another directory. 842 843 Current V4 source locks bind the exact public Lib cohort, Cargo/Nix input 844 locks and Rust 1.99.0. Earlier V1/V2 native declarations and the archived V3 845 source lock retain their original scope. Source binding does not qualify 846 current Nix packages, runtime artifacts or a release candidate. 847 848 The standalone Linux systemd boundary is frozen by 849 `contracts/services_hardening/systemd_qualification.v1.json` and checked by 850 `scripts/verify-systemd.sh`. The instance unit uses the canonical service-host 851 paths, fixed unprivileged account, restrictive directory modes and umask, 852 fixed restart delay, bounded stop behavior, empty capabilities, no environment-based secret 853 input, and the reviewed filesystem, kernel, namespace, process, and address- 854 family protections. The Linux-only verifier requires systemd 252 or newer, 855 runs syntax verification, and rejects an offline security exposure above 3.0. 856 Type `simple` remains deliberate: readiness is the cached CLI/admin contract, 857 not `sd_notify`. Compatibility-sensitive `MemoryDenyWriteExecute` and syscall 858 filters remain deferred to the Step 229 integration wave rather than being 859 enabled without real-binary evidence. This qualification does not install, 860 enable, start, stop, or deploy a production service. Native artifact qualification 861 remains Step 216 ownership, and promotion remains Step 217 ownership. 862 863 Validate the standalone crate through extbuild: 864 865 ```text 866 cargo extbuild doctor 867 cargo extbuild run -- ./scripts/verify-boundaries.sh 868 cargo extbuild run -- ./scripts/verify-supply-chain.sh 869 cargo extbuild run -- ./scripts/release-acceptance.sh 870 cargo extbuild run -- cargo fmt --all --check 871 cargo extbuild run -- cargo check --workspace --all-targets --locked 872 cargo extbuild run -- cargo test --workspace --all-targets --locked 873 cargo extbuild run -- cargo clippy --workspace --all-targets --locked -- -D warnings 874 cargo extbuild run -- env RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps --locked 875 ``` 876 877 The flake exposes the RHI package, application, checks, and development shell 878 for `aarch64-darwin` and `x86_64-linux`, plus the NixOS module and unsigned OCI 879 derivation for `x86_64-linux`. Run Nix and narrower ad hoc Cargo commands 880 through `cargo extbuild run --` from this repository root. 881 882 ## Copyright 883 884 Except as otherwise noted, all files in the `rhi` distribution are 885 886 `Copyright (c) 2025 Tyson Lupul` 887 888 ## License 889 890 This repository is licensed under AGPL-3.0-or-later. See LICENSE.