浏览代码

Write the documentation in Simplified Technical English

The prose of the repo was terse but it was not controlled. The same
thing had more than one name, a sentence could run past twenty five
words, and a modal verb hid whether a rule was a permission or a
prohibition. `doc/accounts.md` held the clearest case: a balance "may
not go negative", where "may not" reads either way. It is a
prohibition, and it says must not now.

Everything under `doc/` and every doc comment follows ASD-STE100: one
word for one thing, no sentence over twenty five words, no paragraph
over six, the active voice, no `shall`, `should` or `may`, and no `-ing`
form outside a technical name. The lines wrap at eighty columns. A
reader of the book and a reader of the API reference now meet one
vocabulary.

A record keeps the vocabulary it decided in, so ADR-0001 still says
`Active → PendingInactive → Inactive` and ADR-0004 still says
`CappedOverdraft`. The front matter of every record is byte-identical,
the `Date` line included, because this pass updates no decision.

Six claims were wrong and they are corrected: quoted program output
that said `Active` where the dashboard prints `Live`, a validation list
that skipped a number so the prose cited a step that does not exist,
`CANONICAL_VERSION = 4` where the constant is 6, the one dead link of
the book, a schema reference three facts behind migration 015, and a
module header that promised a write-ahead path ADR-0023 removed.
C 3 小时之前
父节点
当前提交
6da2946aaf
共有 100 个文件被更改,包括 4741 次插入 和 3844 次删除
  1. 6 6
      crates/kuatia-core/src/hash.rs
  2. 3 3
      crates/kuatia-core/src/lib.rs
  3. 38 32
      crates/kuatia-core/src/posting_resolution.rs
  4. 48 46
      crates/kuatia-core/src/validate.rs
  5. 5 4
      crates/kuatia-dashboard/src/api.rs
  6. 41 39
      crates/kuatia-dashboard/src/data.rs
  7. 7 6
      crates/kuatia-dashboard/src/main.rs
  8. 10 10
      crates/kuatia-dashboard/src/seed.rs
  9. 44 40
      crates/kuatia-dashboard/src/ui.rs
  10. 43 42
      crates/kuatia-money/src/lib.rs
  11. 2 1
      crates/kuatia-storage-sql/src/account.rs
  12. 21 15
      crates/kuatia-storage-sql/src/commit.rs
  13. 30 29
      crates/kuatia-storage-sql/src/dialect.rs
  14. 30 27
      crates/kuatia-storage-sql/src/lib.rs
  15. 10 9
      crates/kuatia-storage-sql/src/migrate.rs
  16. 24 24
      crates/kuatia-storage-sql/src/posting.rs
  17. 18 17
      crates/kuatia-storage-sql/src/row.rs
  18. 35 32
      crates/kuatia-storage-sql/src/sqlite_ext.rs
  19. 18 17
      crates/kuatia-storage-sql/tests/postgres.rs
  20. 47 41
      crates/kuatia-storage-sql/tests/sqlite.rs
  21. 11 9
      crates/kuatia-storage/src/error.rs
  22. 22 19
      crates/kuatia-storage/src/events.rs
  23. 11 9
      crates/kuatia-storage/src/mem_store.rs
  24. 25 22
      crates/kuatia-storage/src/query.rs
  25. 105 100
      crates/kuatia-storage/src/store.rs
  26. 65 58
      crates/kuatia-storage/src/store_tests.rs
  27. 13 13
      crates/kuatia-storage/tests/concurrency.rs
  28. 31 26
      crates/kuatia-types/src/account.rs
  29. 70 62
      crates/kuatia-types/src/account_code.rs
  30. 37 33
      crates/kuatia-types/src/amount.rs
  31. 9 8
      crates/kuatia-types/src/asset.rs
  32. 16 15
      crates/kuatia-types/src/autoid.rs
  33. 18 13
      crates/kuatia-types/src/book.rs
  34. 20 18
      crates/kuatia-types/src/canonical.rs
  35. 6 5
      crates/kuatia-types/src/envelope.rs
  36. 26 25
      crates/kuatia-types/src/ids.rs
  37. 8 7
      crates/kuatia-types/src/internals.rs
  38. 4 4
      crates/kuatia-types/src/lib.rs
  39. 21 19
      crates/kuatia-types/src/posting.rs
  40. 46 42
      crates/kuatia-types/src/transfer.rs
  41. 7 7
      crates/kuatia-types/src/value_date.rs
  42. 1 1
      crates/kuatia/examples/create_accounts.rs
  43. 5 4
      crates/kuatia/examples/escrow.rs
  44. 5 5
      crates/kuatia/examples/inflight_hold.rs
  45. 25 24
      crates/kuatia/src/error.rs
  46. 74 65
      crates/kuatia/src/inflight.rs
  47. 44 36
      crates/kuatia/src/inflight/projection.rs
  48. 24 23
      crates/kuatia/src/ledger.rs
  49. 15 15
      crates/kuatia/src/ledger/asset.rs
  50. 80 72
      crates/kuatia/src/ledger/balance.rs
  51. 46 38
      crates/kuatia/src/ledger/commit.rs
  52. 4 4
      crates/kuatia/src/ledger/connect.rs
  53. 14 12
      crates/kuatia/src/ledger/lifecycle.rs
  54. 8 8
      crates/kuatia/src/ledger/projection.rs
  55. 9 8
      crates/kuatia/src/ledger/query.rs
  56. 11 11
      crates/kuatia/src/ledger/transition.rs
  57. 8 8
      crates/kuatia/src/lib.rs
  58. 3 3
      crates/kuatia/src/prelude.rs
  59. 11 10
      crates/kuatia/src/workflow.rs
  60. 43 40
      crates/kuatia/tests/concurrency.rs
  61. 30 29
      crates/kuatia/tests/inflight.rs
  62. 27 25
      crates/kuatia/tests/integration.rs
  63. 52 45
      crates/kuatia/tests/projection.rs
  64. 5 5
      crates/kuatia/tests/workflow.rs
  65. 26 24
      doc/README.md
  66. 57 30
      doc/SUMMARY.md
  67. 103 99
      doc/accounting-mapping.md
  68. 147 110
      doc/accounts.md
  69. 85 87
      doc/adr/0001-modified-utxo-signed-postings.md
  70. 80 72
      doc/adr/0002-saga-commit-pipeline.md
  71. 123 95
      doc/adr/0003-dumb-storage-saga-recovery.md
  72. 65 58
      doc/adr/0004-account-policies-overdraft-model.md
  73. 64 57
      doc/adr/0005-intent-api-movements-vs-envelopes.md
  74. 72 62
      doc/adr/0006-reservation-protocol-posting-lifecycle.md
  75. 61 54
      doc/adr/0007-reversal-via-compensating-transfers.md
  76. 60 61
      doc/adr/0008-conformance-tested-storage.md
  77. 117 97
      doc/adr/0009-monetary-representation-integer-minor-units.md
  78. 73 65
      doc/adr/0010-event-stream-vs-transfer-log.md
  79. 95 105
      doc/adr/0011-swappable-money-backing.md
  80. 125 111
      doc/adr/0012-subaccounts.md
  81. 82 64
      doc/adr/0013-journaling-model.md
  82. 164 152
      doc/adr/0014-inflight-holds-via-holding-accounts.md
  83. 89 77
      doc/adr/0015-fixed-width-account-code.md
  84. 70 64
      doc/adr/0016-immutable-postings-index-tables.md
  85. 64 61
      doc/adr/0017-correctness-first-append-only-hot-indexes.md
  86. 77 57
      doc/adr/0018-single-debit-must-not-exceed-credit-flag.md
  87. 92 79
      doc/adr/0019-cached-balance-projection.md
  88. 88 74
      doc/adr/0020-account-transition-recovery.md
  89. 41 35
      doc/adr/0021-commit-safety-map.md
  90. 108 83
      doc/adr/0022-merged-live-postings-hot-index.md
  91. 114 89
      doc/adr/0023-atomic-storage-commit.md
  92. 97 92
      doc/adr/0024-native-money-columns.md
  93. 87 31
      doc/adr/0025-one-live-set-no-reservations.md
  94. 89 33
      doc/adr/0026-public-api-vocabulary.md
  95. 96 30
      doc/adr/0027-value-date-separate-from-commit-time.md
  96. 119 40
      doc/adr/0028-amount-carries-its-asset.md
  97. 102 40
      doc/adr/0029-stored-amounts-and-a-closed-money-surface.md
  98. 76 30
      doc/adr/0030-assets-named-by-code.md
  99. 84 32
      doc/adr/0031-every-read-is-account-scoped.md
  100. 54 49
      doc/adr/README.md

+ 6 - 6
crates/kuatia-core/src/hash.rs

@@ -1,4 +1,4 @@
-//! Hashing and tamper-evidence for the ledger.
+//! Content addresses and tamper-evidence for the ledger.
 //!
 //! Every transfer gets a content-addressed [`TransferId`] (double-SHA256 of its
 //! canonical serialization), which serves as both the idempotency key and the
@@ -12,8 +12,8 @@ use kuatia_types::{Account, AccountSnapshotId, Envelope, ToBytes, TransferId};
 // Double-SHA256
 // ---------------------------------------------------------------------------
 
-/// Double-SHA256 — the standard hash used throughout the ledger.
-/// Prevents length-extension attacks.
+/// Double-SHA256: the standard hash used throughout the ledger. Prevents
+/// length-extension attacks.
 pub fn double_sha256(data: &[u8]) -> [u8; 32] {
     let first = Sha256::digest(data);
     let second = Sha256::digest(first);
@@ -81,9 +81,9 @@ mod tests {
             .build()
     }
 
-    /// A frozen vector, so a change to how an envelope is built or stored shows
-    /// up here rather than silently re-identifying every transfer in a database.
-    /// Only a deliberate `CANONICAL_VERSION` bump may move it.
+    /// A frozen vector. A change to how an envelope is built or stored shows up
+    /// here. It does not silently give every transfer in a database a new id.
+    /// Only a deliberate `CANONICAL_VERSION` bump can move it.
     #[test]
     fn content_hash_matches_its_golden_vector() {
         assert_eq!(

+ 3 - 3
crates/kuatia-core/src/lib.rs

@@ -1,8 +1,8 @@
 //! Pure, sans-IO decision logic for the ledger.
 //!
-//! This crate contains no IO, no async runtime, and near-zero dependencies so that
-//! the auditable heart of the ledger can be tested with golden vectors, replayed
-//! deterministically, and embedded anywhere.
+//! This crate contains no IO, no async runtime, and near-zero dependencies. So
+//! the auditable heart of the ledger can be tested with golden vectors,
+//! replayed deterministically, and embedded anywhere.
 
 pub mod hash;
 pub mod posting_resolution;

+ 38 - 32
crates/kuatia-core/src/posting_resolution.rs

@@ -6,14 +6,15 @@
 //! 1. [`draft_movements`] aggregates movements into output postings and
 //!    per-(account, asset) net debits. It tells the async layer exactly which
 //!    postings to load and which accounts to fetch.
-//! 2. [`resolve_envelope`] selects postings for each debit, computes change, and
-//!    covers an overdraft shortfall with a negative offset posting. Whether an
-//!    account may overdraw is read straight from its [`Account::forbids_overdraft`]
-//!    flag, the same accessor validation reads, so the two passes cannot disagree.
+//! 2. [`resolve_envelope`] selects postings for each debit, computes change,
+//!    and covers an overdraft shortfall with a negative offset posting. The
+//!    [`Account::forbids_overdraft`] flag says whether an account can overdraw,
+//!    and validation reads the same accessor, so the two passes cannot
+//!    disagree.
 //!
-//! The async ledger loads state; this module decides. The change-making and
-//! shortfall branches are the parts most worth property-testing, and living here
-//! they are reachable without standing up a store.
+//! The async ledger loads state; this module decides. The change branch and the
+//! shortfall branch are the parts a property test is most worth on. Here a test
+//! reaches them with no store at all.
 
 use std::collections::HashMap;
 use std::error::Error;
@@ -36,8 +37,8 @@ use kuatia_types::{
 /// When a caller uses `pay` or `withdraw` they specify an amount, not which
 /// postings to consume. Selection picks the postings; when a non-overdraft
 /// account cannot cover the amount it fails with this. Selection has this one
-/// failure mode, so it is a struct, not an enum; overflow is reported separately
-/// by [`ResolveError`].
+/// failure mode, so it is a struct, not an enum; overflow is reported
+/// separately by [`ResolveError`].
 #[derive(Debug, Clone, PartialEq, Eq)]
 pub struct InsufficientFunds {
     /// What the eligible postings came to. Carries the asset, so the pair below
@@ -62,9 +63,10 @@ impl Error for InsufficientFunds {}
 /// Failure from resolution pass 2 ([`resolve_envelope`]).
 #[derive(Debug, Clone, PartialEq, Eq)]
 pub enum ResolveError {
-    /// Posting selection failed: insufficient funds for a non-overdraft account.
+    /// Posting selection failed: insufficient funds for a non-overdraft
+    /// account.
     Selection(InsufficientFunds),
-    /// Monetary arithmetic overflowed while computing change or a shortfall.
+    /// Monetary arithmetic overflowed on change or on a shortfall.
     Overflow,
 }
 
@@ -96,13 +98,13 @@ impl From<OverflowError> for ResolveError {
 // Pass 1: draft
 // ---------------------------------------------------------------------------
 
-/// A positive net debit on one (account, asset) that pass 2 must cover by
-/// selecting postings.
+/// A positive net debit on one (account, asset). Pass 2 must cover it with
+/// selected postings.
 #[derive(Debug, Clone, PartialEq, Eq)]
 pub struct Debit {
-    /// The account (subaccount) being debited.
+    /// The account (subaccount) to debit.
     pub account: AccountId,
-    /// The positive amount owed, carrying the asset it is owed in.
+    /// The positive amount owed, with the asset it is owed in.
     pub amount: Amount,
 }
 
@@ -119,7 +121,8 @@ impl Debit {
 pub struct MovementDraft {
     /// Postings credited to movement destinations.
     pub creates: Vec<NewPosting>,
-    /// Positive net debits, one per (account, asset), each needing selection.
+    /// Positive net debits, one per (account, asset), each in need of
+    /// selection.
     pub debits: Vec<Debit>,
 }
 
@@ -166,26 +169,28 @@ pub fn draft_movements(transfer: &Transfer) -> Result<MovementDraft, AmountError
 /// and `accounts` for the debits produced by [`draft_movements`]; this pass is
 /// pure.
 pub struct ResolveInput<'a> {
-    /// The transfer being resolved (for its book and metadata).
+    /// The transfer to resolve (for its book and metadata).
     pub transfer: &'a Transfer,
     /// Pass 1 output. Consumed here: its `creates` seed the envelope and its
     /// `debits` drive selection.
     pub draft: MovementDraft,
-    /// Active postings available for each debit's (account, asset). A missing or
-    /// empty entry means no positive postings to draw on.
+    /// Active postings available for the (account, asset) of each debit. An
+    /// absent or empty entry means no positive postings to draw on.
     pub available: &'a HashMap<(AccountId, AssetId), Vec<Posting>>,
-    /// The debit accounts, keyed by id. A debit short of positive postings gets a
-    /// negative offset posting only if its account permits overdraft (does *not*
-    /// carry `DEBIT_MUST_NOT_EXCEED_CREDIT`, read via
-    /// [`Account::forbids_overdraft`]); otherwise it fails with
-    /// [`InsufficientFunds`]. This is the same flag validation reads, so resolve
-    /// and validate cannot disagree. A missing account is treated as forbidding
-    /// overdraft, so an unknown account never gets an offset posting.
+    /// The debit accounts, keyed by id. A debit short of positive postings gets
+    /// a negative offset posting only if its account permits overdraft. Such an
+    /// account does *not* carry `DEBIT_MUST_NOT_EXCEED_CREDIT`, read through
+    /// [`Account::forbids_overdraft`]. An account that forbids overdraft fails
+    /// with [`InsufficientFunds`] instead.
+    ///
+    /// This is the same flag validation reads, so resolve and validate cannot
+    /// disagree. An absent account counts as one that forbids overdraft, so an
+    /// unknown account never gets an offset posting.
     pub accounts: &'a HashMap<AccountId, Account>,
 }
 
-/// Pass 2: for each debit, either select postings and compute change, or (for an
-/// overdraft account short of funds) consume every positive posting and create a
+/// Pass 2: for each debit, select postings and compute change. For an overdraft
+/// account short of funds, consume every positive posting instead, and create a
 /// negative offset posting for the shortfall. The floor is enforced later, in
 /// validation. Returns the concrete envelope with no account snapshots pinned;
 /// the caller pins them.
@@ -294,7 +299,7 @@ mod tests {
     use std::sync::Arc;
 
     /// An amount of `asset` in minor units. An amount compares by asset id, so
-    /// building the row here is equivalent to reading it back from a registry.
+    /// a row built here is equivalent to one read back from a registry.
     fn money<V>(asset: AssetId, value: V) -> Amount
     where
         Amount: From<(V, Arc<Asset>)>,
@@ -328,7 +333,8 @@ mod tests {
         list.into_iter().map(|a| (a.id, a)).collect()
     }
 
-    /// An account that forbids overdraft (carries `DEBIT_MUST_NOT_EXCEED_CREDIT`).
+    /// An account that forbids overdraft (carries
+    /// `DEBIT_MUST_NOT_EXCEED_CREDIT`).
     fn no_overdraft(id: AccountId) -> Account {
         Account::debit_must_not_exceed_credit(id)
     }
@@ -382,7 +388,7 @@ mod tests {
         })
         .unwrap();
         assert_eq!(env.consumes().len(), 2);
-        // Only the destination posting is created — no change.
+        // Only the destination posting is created, with no change.
         assert_eq!(env.creates().len(), 1);
         assert_eq!(env.creates()[0].owner, acct(2));
     }
@@ -415,7 +421,7 @@ mod tests {
     #[test]
     fn selects_largest_first_to_minimise_consumed() {
         // With 10, 90 and 50 available, a debit of 80 is covered by the single
-        // 90 posting rather than several smaller ones — one consumed, 10 change.
+        // 90 posting rather than several smaller ones: one consumed, 10 change.
         let transfer = pay(acct(1), acct(2), 80);
         let draft = draft_movements(&transfer).unwrap();
         let available = HashMap::from([(

+ 48 - 46
crates/kuatia-core/src/validate.rs

@@ -1,10 +1,10 @@
-//! Pure, sync validation — the auditable heart of the ledger.
+//! Pure, sync validation: the auditable heart of the ledger.
 //!
 //! [`validate_and_plan`] enforces every invariant (conservation, double-spend,
-//! account state, overdraft, book policy) and produces a [`Plan`] describing the
-//! effects to apply. It takes no IO, no clock, and no randomness, so it is deterministic
-//! and testable with golden vectors. The caller provides pre-loaded state via
-//! [`PlanInput`]; this module never touches storage.
+//! account state, overdraft, book policy). It produces a [`Plan`] that names
+//! the effects to apply. It takes no IO, no clock, and no randomness, so it is
+//! deterministic and testable with golden vectors. The caller provides
+//! pre-loaded state through [`PlanInput`]; this module never touches storage.
 
 use std::collections::{HashMap, HashSet};
 use std::error::Error;
@@ -19,8 +19,8 @@ use kuatia_types::*;
 // Input / Output
 // ---------------------------------------------------------------------------
 
-/// Pre-loaded state the caller must supply. Borrowing avoids copies on the
-/// hot path and keeps this module allocation-free for the validation itself.
+/// Pre-loaded state the caller must supply. A borrow avoids a copy on the hot
+/// path, and it keeps this module allocation-free for the validation itself.
 pub struct PlanInput<'a> {
     /// The envelope to validate.
     pub envelope: &'a Envelope,
@@ -30,15 +30,15 @@ pub struct PlanInput<'a> {
     pub accounts: &'a HashMap<AccountId, Account>,
     /// Current balances keyed by (account, asset).
     pub balances: &'a HashMap<(AccountId, AssetId), Cent>,
-    /// The book gating this transfer, if one is loaded. `Some` enforces the
-    /// book's [`BookPolicy`] (allowed assets/accounts/flags); `None` means the
-    /// implicit unrestricted default book. The async layer is responsible for
-    /// rejecting a *named* book id that has no row before reaching here.
+    /// The book that gates this transfer, if one is loaded. `Some` enforces the
+    /// [`BookPolicy`] of the book (allowed assets/accounts/flags); `None` means
+    /// the implicit unrestricted default book. The async layer must reject a
+    /// *named* book id that has no row, before control gets here.
     pub book: Option<&'a Book>,
 }
 
 /// The validated effects to apply atomically. Produced only when every
-/// invariant holds, so the store can apply it without re-checking.
+/// invariant holds, so the store can apply it and re-check nothing.
 #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
 pub struct Plan {
     /// Content-addressed id of the validated transfer.
@@ -55,12 +55,11 @@ pub struct Plan {
 
 /// The exact stored state [`validate_and_plan`] reads for a given envelope.
 ///
-/// Validation's correctness rests on being handed *complete* state: a missing
-/// balance key silently defaults to zero and would flip an overdraft decision.
-/// Deriving the key-set here, in the pure core, gives that "load everything
-/// validation reads" rule one home and one test surface. The async loader
-/// iterates these keys rather than re-deriving its own, so it cannot
-/// under-fetch.
+/// The correctness of validation rests on *complete* state. An absent balance
+/// key silently defaults to zero, and that would flip an overdraft decision.
+/// The key-set comes from here, in the pure core, so the "load everything
+/// validation reads" rule has one home and one test surface. The async loader
+/// iterates these keys and derives none of its own, so it cannot under-fetch.
 #[derive(Debug, Clone, PartialEq, Eq)]
 pub struct RequiredState {
     /// Posting ids validation reads: exactly `envelope.consumes()`.
@@ -73,19 +72,19 @@ pub struct RequiredState {
     pub balances: Vec<(AccountId, AssetId)>,
 }
 
-/// Accounts and balance keys implied purely by the postings an envelope touches:
-/// owners of its created and consumed postings, plus the `(owner, asset)` balance
-/// key for each. This is the one walk [`required_state`] (what the loader fetches)
-/// and [`validate_and_plan`] (what it reads) both derive from, so the load set and
-/// the read set cannot drift.
+/// Accounts and balance keys implied purely by the postings an envelope
+/// touches. Those are the owners of its created and consumed postings, plus the
+/// `(owner, asset)` balance key for each. This is the one walk that
+/// [`required_state`] (what the loader fetches) and [`validate_and_plan`] (what
+/// it reads) both derive from. So the load set and the read set cannot drift.
 struct PostingKeys {
     owners: Vec<AccountId>,
     balances: Vec<(AccountId, AssetId)>,
 }
 
-/// Add `amount` to its asset's bucket, starting the bucket at zero of that
-/// asset. The add refuses a mismatch, so the bucket cannot end up holding a
-/// sum of two assets even if the key were wrong.
+/// Add `amount` to the bucket of its asset. A new bucket starts at zero of that
+/// asset. The add refuses a mismatch, so the bucket cannot hold a sum of two
+/// assets even if the key were wrong.
 fn fold_by_asset(
     buckets: &mut HashMap<AssetId, Amount>,
     amount: &Amount,
@@ -99,9 +98,9 @@ fn fold_by_asset(
     Ok(())
 }
 
-/// The bucket's sum, or nothing of that asset when the side is empty. Compared
-/// by value, since the two sides are the same asset by construction and a
-/// missing side has no asset handle to build a zero from.
+/// The sum of the bucket, or nothing of that asset when the side is empty.
+/// Compared by value, because the two sides are the same asset by construction.
+/// An absent side has no asset handle to build a zero from.
 fn sum_of(buckets: &HashMap<AssetId, Amount>, asset: &AssetId) -> Cent {
     buckets
         .get(asset)
@@ -129,13 +128,14 @@ fn posting_keys(envelope: &Envelope, consumed_postings: &[Posting]) -> PostingKe
 
 /// Derive the state key-set [`validate_and_plan`] will read.
 ///
-/// The consumed postings must be passed in because their owner and asset (which
-/// drive the account and balance key-sets) live in the store, not the envelope.
-/// The loader therefore fetches `envelope.consumes()` first, then calls this to
-/// own every remaining key. Both this and [`validate_and_plan`] derive their
-/// account and balance keys from one shared `posting_keys` walk, so they cannot
-/// drift; the only
-/// extra keys named here are the snapshot-pinned accounts (validated in step 5b),
+/// The consumed postings must be passed in. Their owner and asset drive the
+/// account and balance key-sets, and both live in the store rather than the
+/// envelope. So the loader fetches `envelope.consumes()` first, then calls this
+/// to own every key that is left.
+///
+/// Both this and [`validate_and_plan`] derive their account and balance keys
+/// from one shared `posting_keys` walk, so they cannot drift. The only extra
+/// keys named here are the snapshot-pinned accounts (validated in step 5b),
 /// which the loader must fetch even when they own no posting.
 pub fn required_state(envelope: &Envelope, consumed_postings: &[Posting]) -> RequiredState {
     let PostingKeys {
@@ -173,7 +173,7 @@ pub enum ValidationError {
     OwnershipViolation {
         /// The posting that failed the ownership check.
         posting_id: PostingId,
-        /// The account that should own the posting.
+        /// The account that must own the posting.
         expected: AccountId,
         /// The account that actually owns the posting.
         actual: AccountId,
@@ -193,9 +193,10 @@ pub enum ValidationError {
         /// Total value of created postings for this asset.
         created_sum: Cent,
     },
-    /// Projected balance would go negative on an account that forbids overdraft.
-    /// The model is binary: an account either permits unbounded overdraft or
-    /// forbids any negative balance, so there is no configurable floor to report.
+    /// Projected balance would go negative on an account that forbids
+    /// overdraft. The model is binary: an account either permits unbounded
+    /// overdraft or forbids any negative balance, so there is no configurable
+    /// floor to report.
     OverdraftExceeded {
         /// The account that would be overdrawn.
         account: AccountId,
@@ -229,7 +230,8 @@ pub enum ValidationError {
         /// The disallowed asset.
         asset: AssetId,
     },
-    /// An account is not permitted to participate by the transfer's book policy.
+    /// An account is not permitted to participate by the transfer's book
+    /// policy.
     BookAccountNotAllowed {
         /// The book whose policy rejected the account.
         book: BookId,
@@ -238,7 +240,7 @@ pub enum ValidationError {
     },
     /// An arithmetic operation overflowed.
     Overflow,
-    /// Two amounts of different assets were combined while folding a side of
+    /// Two amounts of different assets were combined in a fold of one side of
     /// the conservation check, which means a bucket key lost its asset.
     Amount(AmountError),
 }
@@ -337,10 +339,10 @@ impl From<AmountError> for ValidationError {
 
 /// The single entry point for all ledger invariant checks.
 ///
-/// Pure, sync, deterministic — no IO, no clock, no randomness — so the
-/// invariants are testable with golden vectors and replay deterministically.
-/// Returns a [`Plan`] only when every invariant holds; otherwise returns the
-/// specific [`ValidationError`] that was violated.
+/// Pure, sync and deterministic, with no IO, no clock and no randomness. So the
+/// invariants are testable with golden vectors, and they replay
+/// deterministically. Returns a [`Plan`] only when every invariant holds;
+/// otherwise returns the specific [`ValidationError`] that was violated.
 pub fn validate_and_plan(input: PlanInput<'_>) -> Result<Plan, ValidationError> {
     let envelope = input.envelope;
 

+ 5 - 4
crates/kuatia-dashboard/src/api.rs

@@ -1,10 +1,11 @@
 //! REST API over a `Ledger`. Everything is read-only: the dashboard observes
 //! the ledger, it does not mutate it. All monetary values are emitted as
-//! minor-unit strings (the native `Cent` serialization); clients format them
-//! using the asset registry from `/api/assets`.
+//! minor-unit strings (the native `Cent` serialization); a client formats them
+//! with the asset registry from `/api/assets`.
 //!
-//! These handlers are thin wrappers over the shared builders in [`crate::data`];
-//! the server-rendered HTML views in [`crate::ui`] read from the same builders.
+//! These handlers are thin wrappers over the shared builders in
+//! [`crate::data`]; the server-rendered HTML views in [`crate::ui`] read from
+//! the same builders.
 
 use axum::{
     Json, Router,

+ 41 - 39
crates/kuatia-dashboard/src/data.rs

@@ -1,8 +1,8 @@
 //! Shared data layer. Reads the ledger and builds the DTOs consumed by both the
-//! JSON API ([`crate::api`]) and the server-rendered HTML views ([`crate::ui`]).
-//! Everything here is read-only. A monetary value stays an [`Amount`], which
-//! carries the asset it is in, so the presentation layer formats it at that
-//! asset's own scale rather than pairing it with a lookup of its own.
+//! JSON API ([`crate::api`]) and the server-rendered HTML views
+//! ([`crate::ui`]). Everything here is read-only. A monetary value stays an
+//! [`Amount`], which carries the asset it is in. So the presentation layer
+//! formats it at the own scale of that asset, and needs no lookup of its own.
 
 use std::cmp::Reverse;
 use std::collections::HashMap;
@@ -43,14 +43,15 @@ pub struct AppState {
 #[derive(Serialize)]
 pub struct AccountDto {
     pub id: AccountId,
-    /// IBAN-style account code (machine format, checksum-valid) for the full id.
+    /// IBAN-style account code (machine format, checksum-valid) for the full
+    /// id.
     pub code: String,
     /// Subaccount id (`0` is the main account). Mirrors `id.sub` for templates.
     pub sub: i64,
     pub label: Option<&'static str>,
     pub version: u64,
-    /// Whether the account carries the `DEBIT_MUST_NOT_EXCEED_CREDIT` flag
-    /// (balance may not go negative). When `false` the account may overdraw.
+    /// Whether the account carries the `DEBIT_MUST_NOT_EXCEED_CREDIT` flag, so
+    /// its balance must not go negative. When `false` the account can overdraw.
     pub debit_must_not_exceed_credit: bool,
     pub frozen: bool,
     pub closed: bool,
@@ -71,9 +72,9 @@ pub struct PostingDto {
 #[derive(Debug, Serialize, Clone, Copy, PartialEq, Eq)]
 #[serde(rename_all = "snake_case")]
 pub enum EntrySide {
-    /// Value leaving an account.
+    /// Value that leaves an account.
     Debit,
-    /// Value arriving at an account.
+    /// Value that arrives at an account.
     Credit,
 }
 
@@ -89,9 +90,9 @@ pub enum EntryLineKind {
     /// account that was debited. The record cannot tell this apart from the
     /// output of a movement whose `from` and `to` are the same account.
     Change,
-    /// A created posting with no payer and a negative value: the position an
-    /// overdraft-permitting account takes on to fund a shortfall, and the whole
-    /// debit side of a deposit.
+    /// A created posting with no payer and a negative value. An account that
+    /// permits overdraft takes on this position to fund a shortfall, and it is
+    /// also the whole debit side of a deposit.
     Offset,
 }
 
@@ -104,8 +105,8 @@ pub struct EntryLineDto {
     pub owner: AccountId,
     pub label: Option<&'static str>,
     /// Signed, exactly as the posting holds it. The HTML prints the magnitude
-    /// because `side` already carries the direction; a client reading this gets
-    /// the record's own value.
+    /// because `side` already carries the direction, and a client that reads
+    /// this field gets the value of the record itself.
     pub amount: Amount,
     pub payer: Option<AccountId>,
     pub payer_label: Option<&'static str>,
@@ -125,13 +126,13 @@ pub struct EntryAssetDto {
     /// shuffled. Derived from `payer`, which is descriptive provenance, so the
     /// totals above stay the authoritative pair.
     pub moved: Amount,
-    /// The two totals agree whenever the envelope conserved value, so a false
-    /// here is a ledger bug worth seeing rather than a state to design around.
+    /// The two totals agree whenever the envelope conserved value. So a false
+    /// here is a ledger bug a reader must see, and not a state to design for.
     pub balanced: bool,
 }
 
-/// A metadata value as far as it could be read. An enum rather than an
-/// optional string beside an optional hex, so "neither" cannot be expressed.
+/// A metadata value as far as it could be read. An enum rather than an optional
+/// string beside an optional hex, so "neither" cannot be expressed.
 #[derive(Debug, Serialize, PartialEq, Eq)]
 #[serde(rename_all = "snake_case")]
 pub enum MetadataValueDto {
@@ -195,9 +196,9 @@ pub struct OverviewDto {
 #[derive(Serialize)]
 pub struct AccountDetailDto {
     pub account: AccountDto,
-    /// The non-closed subaccounts sharing this account's base id (the viewed
-    /// account included), so a base account and its subaccounts are navigable
-    /// together while never summed.
+    /// The non-closed subaccounts that share the base id of this account, the
+    /// viewed account included. So a base account and its subaccounts are
+    /// navigable together, and never summed.
     pub subaccounts: Vec<AccountDto>,
     pub postings: Vec<PostingDto>,
     pub entries: Vec<EntryDto>,
@@ -244,7 +245,7 @@ const HEX_SAMPLE_BYTES: usize = 32;
 
 /// A metadata value as text, or `None` when the bytes are not text.
 ///
-/// A caller may write any bytes and the reserved `inflight` key holds CBOR, so
+/// A caller can write any bytes and the reserved `inflight` key holds CBOR, so
 /// invalid UTF-8 is an ordinary input here rather than a failure. A control
 /// character disqualifies a value too, because a binary payload can decode as
 /// UTF-8 and still be unreadable.
@@ -275,9 +276,9 @@ fn metadata_hex(value: &[u8]) -> String {
 
 /// The metadata pairs for display.
 ///
-/// The reference is held back only when it reached the entry head, so a
-/// reference whose bytes are not text still appears here rather than vanishing
-/// between the two.
+/// The reference is held back only when it reached the entry head. So a
+/// reference whose bytes are not text still appears here, and falls between the
+/// two nowhere.
 fn metadata_pairs(envelope: &Envelope, reference_shown: bool) -> Vec<MetadataPairDto> {
     envelope
         .metadata()
@@ -296,8 +297,8 @@ fn metadata_pairs(envelope: &Envelope, reference_shown: bool) -> Vec<MetadataPai
         .collect()
 }
 
-/// Classify a created posting from the shape the resolver gave it: a payer is
-/// set only for a movement output between two accounts, and change and offset
+/// Classify a created posting from the shape the resolver gave it. A payer is
+/// set only for a movement output between two accounts. Change and offset
 /// differ by sign alone.
 fn created_kind(posting: &NewPosting) -> EntryLineKind {
     match posting.payer {
@@ -307,13 +308,14 @@ fn created_kind(posting: &NewPosting) -> EntryLineKind {
     }
 }
 
-/// The column a line belongs in. Consuming a positive posting and creating a
-/// negative one are both value leaving an account, so both are debits.
+/// The column a line belongs in. A consume of a positive posting and a create
+/// of a negative one both take value out of an account, so both are debits.
 ///
 /// The two column totals are equal only as a consequence of per-asset
-/// conservation: with `P` and `N` the positive and negative sums of each side,
-/// `debits - credits` is `(P_consumed - N_consumed) - (P_created - N_created)`,
-/// which `sum(consumed) == sum(created)` makes zero.
+/// conservation. Take `P` and `N` as the positive and negative sums of each
+/// side. Then `debits - credits` is
+/// `(P_consumed - N_consumed) - (P_created - N_created)`, which
+/// `sum(consumed) == sum(created)` makes zero.
 fn entry_side(consumed: bool, amount: &Amount) -> EntrySide {
     match (consumed, amount.is_negative()) {
         (true, false) | (false, true) => EntrySide::Debit,
@@ -322,7 +324,7 @@ fn entry_side(consumed: bool, amount: &Amount) -> EntrySide {
 }
 
 /// Sum the magnitudes of one column. The column carries the direction, so a
-/// negative line contributes its absolute value.
+/// negative line adds its absolute value.
 fn magnitude_sum<'a>(
     asset: &Arc<Asset>,
     lines: impl Iterator<Item = &'a EntryLineDto>,
@@ -344,9 +346,9 @@ fn magnitude_sum<'a>(
 /// Build one journal entry from a committed record and the consumed postings
 /// read back for it.
 ///
-/// A consumed id absent from `consumed` is a 500 rather than a partially drawn
-/// entry: a posting row is written once and never deleted, so an envelope
-/// naming one the table does not hold is a corrupt database.
+/// A consumed id absent from `consumed` is a 500, and not a partly drawn entry.
+/// A posting row is written once and never deleted. So an envelope that names
+/// one the table does not hold is a corrupt database.
 fn entry_dto(
     record: &TransferRecord,
     consumed: &HashMap<PostingId, Posting>,
@@ -495,7 +497,7 @@ fn event_dto(event: &LedgerEvent) -> EventDto {
 }
 
 // ---------------------------------------------------------------------------
-// Builders — read the ledger and assemble DTOs.
+// Builders: read the ledger and assemble DTOs.
 // ---------------------------------------------------------------------------
 
 /// Ledger-wide summary: counts and total issued per asset.
@@ -616,8 +618,8 @@ pub async fn events(state: &AppState, after: u64, limit: u32) -> Result<Vec<Even
 // Error handling
 // ---------------------------------------------------------------------------
 
-/// Any handler failure. Rendered as a JSON error body with a 500 (or 404 for a
-/// missing account). Shared by the JSON and HTML handlers.
+/// Any handler failure. Rendered as a JSON error body with a 500, or a 404 for
+/// an account that does not exist. Shared by the JSON and HTML handlers.
 #[derive(Debug)]
 pub struct ApiError {
     status: StatusCode,

+ 7 - 6
crates/kuatia-dashboard/src/main.rs

@@ -1,8 +1,9 @@
 //! Kuatia dashboard server.
 //!
-//! Connects to a ledger database, then serves two views of it: a server-rendered
-//! HTML dashboard (Tera templates, htmx live refresh) and a read-only JSON REST
-//! API under `/api` for anyone who wants to build a richer client.
+//! Connects to a ledger database, then serves two views of it. One is a
+//! server-rendered HTML dashboard (Tera templates, htmx live refresh). The
+//! other is a read-only JSON REST API under `/api`, for anyone who wants to
+//! build a richer client.
 //!
 //! ```sh
 //! cargo run -p kuatia-dashboard -- --seed          # in-memory demo
@@ -51,9 +52,9 @@ struct Cli {
     #[arg(long, env = "KUATIA_DASHBOARD_SEED", default_value_t = false)]
     seed: bool,
 
-    /// Seed keying the account-code obfuscation. Must be stable across a
-    /// deployment: changing it changes every rendered account code. Defaults to
-    /// the built-in `DEFAULT_ID_SEED`.
+    /// The seed that keys the account-code obfuscation. It must be stable
+    /// across a deployment, because a new seed changes every rendered account
+    /// code. Defaults to the built-in `DEFAULT_ID_SEED`.
     #[arg(long, env = "KUATIA_ID_SEED")]
     id_seed: Option<u64>,
 }

+ 10 - 10
crates/kuatia-dashboard/src/seed.rs

@@ -1,6 +1,6 @@
-//! Demo data. Builds an in-memory ledger with a handful of accounts, funds
-//! them from an external boundary account, then runs payments and a
-//! multi-asset trade so the dashboard has something to visualize.
+//! Demo data. Builds an in-memory ledger with a handful of accounts, and funds
+//! them from an external boundary account. It then runs payments and a
+//! multi-asset trade, so the dashboard has something to show.
 
 use std::error::Error;
 use std::sync::Arc;
@@ -20,8 +20,8 @@ pub const CAROL: AccountId = AccountId::new(102);
 pub const MERCHANT: AccountId = AccountId::new(103);
 
 /// Human-readable labels for the seeded accounts, surfaced by the API so the
-/// frontend can show names instead of raw ids. Labels are per base account;
-/// a subaccount (an inflight hold) shares its base account's label.
+/// frontend can show names instead of raw ids. Labels are per base account; a
+/// subaccount (an inflight hold) shares its base account's label.
 pub fn account_label(id: AccountId) -> Option<&'static str> {
     Some(match id.base() {
         TREASURY => "Treasury",
@@ -36,16 +36,16 @@ pub fn account_label(id: AccountId) -> Option<&'static str> {
 }
 
 /// Connect to the ledger database at `db_url` and create the schema. The URL
-/// scheme selects the backend (e.g. `sqlite::memory:`,
-/// `sqlite://kuatia.db`, `postgres://user:pass@host/db`).
+/// scheme selects the backend (e.g. `sqlite::memory:`, `sqlite://kuatia.db`,
+/// `postgres://user:pass@host/db`).
 pub async fn connect(db_url: &str) -> Result<Arc<Ledger>, Box<dyn Error>> {
     Ok(Arc::new(Ledger::connect(db_url).await?))
 }
 
 /// Seed the demo data only if the ledger has no accounts yet. Returns `true` if
-/// it seeded, `false` if the ledger was already populated (so re-running with
-/// `--seed` against a persistent database is a safe no-op rather than a
-/// duplicate-id error).
+/// it seeded, and `false` if the ledger was already populated. So a second run
+/// with `--seed` against a persistent database is a safe no-op, and not a
+/// duplicate-id error.
 pub async fn seed_if_empty(ledger: &Arc<Ledger>) -> Result<bool, Box<dyn Error>> {
     if !ledger.list_accounts().await?.is_empty() {
         return Ok(false);

+ 44 - 40
crates/kuatia-dashboard/src/ui.rs

@@ -24,7 +24,7 @@ use crate::data::{
 use crate::seed::account_label;
 
 // ---------------------------------------------------------------------------
-// Tera setup — templates embedded via include_str!.
+// Tera setup: templates embedded via include_str!.
 // ---------------------------------------------------------------------------
 
 /// Build the Tera instance with all templates registered by name.
@@ -99,7 +99,7 @@ pub fn router(state: AppState) -> Router {
 }
 
 // ---------------------------------------------------------------------------
-// View models — DTOs with money and timestamps pre-formatted for display.
+// View models: DTOs with money and timestamps pre-formatted for display.
 // ---------------------------------------------------------------------------
 
 #[derive(Serialize)]
@@ -111,7 +111,7 @@ struct MoneyView {
 /// How much of an entry to draw.
 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
 enum Detail {
-    /// The movements alone: what the entry did, without the UTXO mechanism
+    /// The movements alone: what the entry did, with none of the UTXO mechanism
     /// that carried it.
     Movements,
     /// Every posting, with the per-asset conservation totals.
@@ -151,19 +151,19 @@ impl Detail {
     }
 }
 
-/// `?details=all`. A `String` rather than a deserialized enum so an
-/// unrecognized value falls back to the default instead of failing the request.
+/// `?details=all`. A `String` rather than a deserialized enum, so an
+/// unrecognized value falls back to the default and does not fail the request.
 #[derive(Deserialize)]
 struct DetailParams {
     details: Option<String>,
 }
 
-/// What a feed page needs to draw its entries and keep the mode across the
-/// htmx poll.
+/// What a feed page needs to draw its entries and keep the mode across the htmx
+/// poll.
 #[derive(Serialize)]
 struct DetailView {
     all: bool,
-    /// The `/ui/*` URL htmx polls, carrying the mode so a swap does not reset
+    /// The `/ui/*` URL htmx polls, with the mode in it so a swap does not reset
     /// it.
     live_url: String,
     /// The same page with the mode flipped.
@@ -195,9 +195,11 @@ struct AccountView {
     /// Raw numeric base id. The display uses `display_id`; routes use `link`.
     id: i64,
     sub: i64,
-    /// The account's IBAN-style code, grouped for display (five blocks of four).
+    /// The account's IBAN-style code, grouped for display (five blocks of
+    /// four).
     display_id: String,
-    /// Full-page detail link, keyed by the machine-format code (`/accounts/<code>`).
+    /// Full-page detail link, keyed by the machine-format code
+    /// (`/accounts/<code>`).
     link: String,
     name: String,
     version: u64,
@@ -214,8 +216,8 @@ struct PostingView {
     money: MoneyView,
 }
 
-/// An account as it appears in a row: a name to read, the full code to hover,
-/// and a link so a counterparty is navigable rather than dead text.
+/// An account as it appears in a row. It holds a name to read, the full code to
+/// hover, and a link, so a counterparty is navigable and not dead text.
 #[derive(Serialize)]
 struct AcctRefView {
     name: String,
@@ -225,14 +227,14 @@ struct AcctRefView {
 
 #[derive(Serialize)]
 struct EntryLineView {
-    /// Also the CSS class on the note, so a kind is styled without the template
-    /// branching on it.
+    /// Also the CSS class on the note, so a kind is styled and the template
+    /// takes no branch on it.
     kind: &'static str,
     note: &'static str,
     posting_short: String,
     account: AcctRefView,
-    /// The funding account of a payer-funded credit, so both accounts on a line
-    /// are navigable.
+    /// The account that funded a payer-funded credit, so both accounts on a
+    /// line are navigable.
     payer: Option<AcctRefView>,
     money: MoneyView,
     /// Marks a line the viewed account owns. False on the ledger-wide feed.
@@ -255,16 +257,16 @@ struct MovementRowView {
 #[derive(Serialize)]
 struct EntryAssetView {
     code: String,
-    /// What the entry did, which is the default reading. Empty for an envelope
-    /// that records no payer anywhere, such as a reversal.
+    /// What the entry did, which is what the default mode shows. Empty for an
+    /// envelope that records no payer at all, such as a reversal.
     movements: Vec<MovementRowView>,
     debits: Vec<EntryLineView>,
     credits: Vec<EntryLineView>,
     debit_total: MoneyView,
     credit_total: MoneyView,
     moved: MoneyView,
-    /// Shown in either mode: a false is a conservation bug in the record, not
-    /// a property of the reading on screen.
+    /// Shown in either mode. A false is a conservation bug in the record, and
+    /// not a property of what the screen shows.
     balanced: bool,
 }
 
@@ -318,12 +320,12 @@ struct IssuedView {
 // Formatting helpers
 // ---------------------------------------------------------------------------
 
-/// Render an amount at its own asset's scale and symbol, grouping the integer
-/// part with thousands separators.
+/// Render an amount at the scale and symbol of its own asset, with thousands
+/// separators in the integer part.
 ///
-/// Works from the minor units and the asset's decimals rather than any money
-/// type: the ledger hands out amounts, and the integer behind one is the only
-/// number a presentation layer needs.
+/// Works from the minor units and the decimals of the asset, and not from any
+/// money type. The ledger hands out amounts, and the integer behind one is the
+/// only number a presentation layer needs.
 fn fmt_amount(amount: &Amount) -> MoneyView {
     let decimals = usize::from(amount.asset().decimals);
     let units = amount.minor_units();
@@ -346,8 +348,8 @@ fn fmt_amount(amount: &Amount) -> MoneyView {
     }
 }
 
-/// The magnitude alone. An entry cell's column already carries its direction,
-/// so a minus sign there would read as a second, contradicting one.
+/// The magnitude alone. The column of an entry cell already carries its
+/// direction, so a minus sign there would read as a second one against it.
 fn fmt_magnitude(amount: &Amount) -> MoneyView {
     MoneyView {
         text: fmt_amount(amount).text.trim_start_matches('-').to_string(),
@@ -380,7 +382,7 @@ fn short_hex(hex: &str) -> String {
 /// Longest caller-supplied string shown in a row, in characters.
 const TEXT_DISPLAY_CHARS: usize = 48;
 
-/// Shorten a caller-supplied string for display, keeping the whole of it for
+/// Shorten a caller-supplied string for display, and keep the whole of it for
 /// the `title` attribute. Counts characters, not bytes, so a multi-byte
 /// character is never cut in half.
 fn truncate(text: &str) -> TruncatedView {
@@ -396,8 +398,9 @@ fn truncate(text: &str) -> TruncatedView {
     }
 }
 
-/// A metadata pair as a row: its text when it has any, else its size, with the
-/// hex sample behind the hover so a value that is not text stays inspectable.
+/// A metadata pair as a row. It shows the text when the value has any, and its
+/// size when not. The hex sample sits behind the hover, so a value that is not
+/// text stays inspectable.
 fn metadata_pair_view(dto: &MetadataPairDto) -> MetadataPairView {
     let (value, title) = match &dto.value {
         MetadataValueDto::Text(text) => (truncate(text).short, text.clone()),
@@ -420,7 +423,8 @@ fn fmt_millis(ms: i64) -> String {
     format!("{y:04}-{mo:02}-{d:02} {h:02}:{m:02}:{s:02} UTC")
 }
 
-/// Days since the Unix epoch to a civil (year, month, day). Hinnant's algorithm.
+/// Days since the Unix epoch to a civil (year, month, day). Hinnant's
+/// algorithm.
 fn civil_from_days(z: i64) -> (i64, u32, u32) {
     let z = z + 719_468;
     let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
@@ -435,7 +439,7 @@ fn civil_from_days(z: i64) -> (i64, u32, u32) {
 }
 
 // ---------------------------------------------------------------------------
-// View builders — DTO -> view model.
+// View builders: DTO to view model.
 // ---------------------------------------------------------------------------
 
 /// Display an account id as its IBAN-style code in grouped (spaced) format.
@@ -501,7 +505,7 @@ fn account_view(dto: &AccountDto) -> AccountView {
     }
 }
 
-/// The word after the amount, naming why the line is on its side. A
+/// The word after the amount, which says why the line is on its side. A
 /// payer-funded credit says "from" and names the payer beside it.
 fn line_note(kind: EntryLineKind, side: EntrySide) -> &'static str {
     match kind {
@@ -537,10 +541,10 @@ fn line_view(dto: &EntryLineDto, viewpoint: Option<AccountId>) -> EntryLineView
 /// The movements of one asset group, each from the payer of a payer-funded
 /// posting to its owner.
 ///
-/// Filtered by kind rather than by column: a `Receive` is a credit in practice,
-/// but the sign is what places a line, and this should not depend on that
-/// holding. A `Receive` without a payer cannot be a movement and is dropped,
-/// which the resolver's contract makes unreachable.
+/// Filtered by kind and not by column. A `Receive` is a credit in practice, but
+/// the sign is what places a line, and this must not depend on that. A
+/// `Receive` with no payer cannot be a movement and is dropped, which the
+/// contract of the resolver makes unreachable.
 fn movement_rows(dto: &EntryAssetDto, viewpoint: Option<AccountId>) -> Vec<MovementRowView> {
     dto.debits
         .iter()
@@ -864,9 +868,9 @@ mod tests {
         }
     }
 
-    /// An asset group holding both readings of the same entry, the way
-    /// `entry_view` builds one. `mechanism` is given as a spec so each column
-    /// gets its own lines without a `Clone` on the view type.
+    /// An asset group with both readings of the same entry, the way
+    /// `entry_view` builds one. `mechanism` is given as a spec, so each column
+    /// gets its own lines and the view type needs no `Clone`.
     fn asset(
         movements: Vec<MovementRowView>,
         mechanism: &[(&'static str, &'static str, &'static str)],

+ 43 - 42
crates/kuatia-money/src/lib.rs

@@ -4,18 +4,18 @@
 //! whose width is an internal detail: the public API never names the backing
 //! type, and no serialized form reveals it. The backing is chosen once at
 //! compile time through the [`Backing`] alias, which defaults to `i64` and
-//! switches to `i128` under the `i128` cargo feature. Adding a new width is a
-//! single [`CentBacking`] impl plus one line on [`Backing`]; nothing downstream
+//! switches to `i128` under the `i128` cargo feature. A new width is a single
+//! [`CentBacking`] impl plus one line on [`Backing`]; nothing downstream
 //! changes.
 //!
-//! All arithmetic is checked: addition, subtraction and negation return
-//! [`OverflowError`] rather than wrapping, so the ledger's conservation sum can
+//! All arithmetic is checked. Addition, subtraction and negation return
+//! [`OverflowError`] and never wrap, so the conservation sum of the ledger can
 //! never silently round or overflow.
 //!
-//! A `Cent` has two fixed 16-byte forms, both independent of the backing and
-//! deliberately different from each other:
+//! A `Cent` has two fixed 16-byte forms. Both are independent of the backing,
+//! and they are deliberately different from each other.
 //! [`to_canonical_bytes`](Cent::to_canonical_bytes) is the content-addressed
-//! hash preimage, and [`to_storage_bytes`](Cent::to_storage_bytes) is what a
+//! hash preimage. [`to_storage_bytes`](Cent::to_storage_bytes) is what a
 //! database stores, ordered so a byte-wise comparison matches the numeric one.
 
 use serde::{Deserialize, Deserializer, Serialize, Serializer};
@@ -46,9 +46,9 @@ pub type Backing = i128;
 /// The contract an integer must satisfy to back a [`Cent`]. Implemented for
 /// `i64` and `i128`; implement it for another integer to add a new money width.
 ///
-/// It carries only the width-dependent primitives [`Cent`] needs (canonical
-/// 16-byte widening, decimal scaling, parsing, and absolute division). Plain
-/// checked add/sub/neg are used directly on the concrete backing.
+/// It carries only the width-dependent primitives [`Cent`] needs: the canonical
+/// 16-byte widen, the decimal scale, the parse, and the absolute division.
+/// Plain checked add/sub/neg are used directly on the concrete backing.
 pub trait CentBacking: Copy + Ord + Default + fmt::Display {
     /// The additive identity (zero) for this backing.
     const ZERO: Self;
@@ -65,8 +65,8 @@ pub trait CentBacking: Copy + Ord + Default + fmt::Display {
     /// Narrow from `i128`, or `None` if the value does not fit this backing.
     fn try_from_i128(v: i128) -> Option<Self>;
 
-    /// Divide the absolute value of `self` by the absolute value of `d`,
-    /// returning `(quotient, remainder)` as unsigned `u128`. Returns `(0, 0)`
+    /// Divide the absolute value of `self` by the absolute value of `d`, and
+    /// give back `(quotient, remainder)` as unsigned `u128`. Returns `(0, 0)`
     /// when `d` is zero. Used to split a value into whole and fractional parts
     /// for display.
     fn div_rem_abs(self, d: Self) -> (u128, u128);
@@ -134,16 +134,16 @@ impl CentBacking for i128 {
 // Storage encoding
 // ---------------------------------------------------------------------------
 
-/// Encode a raw `i128` in the order-preserving 16-byte storage form:
+/// Encode a raw `i128` in the order-preserving 16-byte storage form. It is
 /// two's-complement big-endian with the sign bit flipped, so a byte-wise
-/// (`memcmp`) comparison of two encodings matches the numeric ordering of the
+/// (`memcmp`) comparison of two encodings matches the numeric order of the
 /// values.
 ///
-/// The width is fixed at 128 bits regardless of the active [`Backing`], so a
-/// stored amount does not change shape when the `i128` feature is toggled, and
-/// a backend that folds these encodings (the SQLite `kuatia_i128_sum`
-/// aggregate) can do so at full width. Distinct from the canonical hash
-/// encoding: see [`Cent::to_storage_bytes`].
+/// The width is fixed at 128 bits whatever the active [`Backing`] is. So a
+/// stored amount does not change shape when the `i128` feature is toggled. A
+/// backend that folds these encodings (the SQLite `kuatia_i128_sum` aggregate)
+/// can also do so at full width. Distinct from the canonical hash encoding: see
+/// [`Cent::to_storage_bytes`].
 pub fn encode_storage_i128(value: i128) -> [u8; 16] {
     let mut bytes = value.to_be_bytes();
     bytes[0] ^= 0x80;
@@ -164,9 +164,9 @@ pub fn decode_storage_i128(bytes: &[u8; 16]) -> i128 {
 
 /// A monetary amount in the smallest unit of one asset (cents, satoshis, …).
 ///
-/// The backing integer is private and its width is hidden: read a `Cent` with
-/// [`Display`](fmt::Display)/[`to_string`](ToString::to_string) or parse one
-/// with [`FromStr`], compare with [`Ord`], and do arithmetic only through the
+/// The backing integer is private and its width is hidden. Read a `Cent` with
+/// [`Display`](fmt::Display)/[`to_string`](ToString::to_string), or parse one
+/// with [`FromStr`]. Compare with [`Ord`], and do arithmetic only through the
 /// checked methods. Serde round-trips it as a string, so no serialized form
 /// reveals the width.
 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
@@ -216,22 +216,23 @@ impl Cent {
         self.0 == 0
     }
 
-    /// Checked addition, returning [`OverflowError`] on overflow.
+    /// Checked addition, which returns [`OverflowError`] on overflow.
     pub fn checked_add(self, rhs: Self) -> Result<Self, OverflowError> {
         self.0.checked_add(rhs.0).map(Cent).ok_or(OverflowError)
     }
 
-    /// Checked subtraction, returning [`OverflowError`] on underflow.
+    /// Checked subtraction, which returns [`OverflowError`] on underflow.
     pub fn checked_sub(self, rhs: Self) -> Result<Self, OverflowError> {
         self.0.checked_sub(rhs.0).map(Cent).ok_or(OverflowError)
     }
 
-    /// Checked negation, returning [`OverflowError`] at the backing's minimum.
+    /// Checked negation, which returns [`OverflowError`] at the minimum of the
+    /// backing.
     pub fn checked_neg(self) -> Result<Self, OverflowError> {
         self.0.checked_neg().map(Cent).ok_or(OverflowError)
     }
 
-    /// Sum an iterator of `Cent` values with overflow checking.
+    /// Sum an iterator of `Cent` values, with a check for overflow.
     pub fn checked_sum(iter: impl IntoIterator<Item = Self>) -> Result<Self, OverflowError> {
         let mut sum = Cent::ZERO;
         for x in iter {
@@ -241,20 +242,20 @@ impl Cent {
     }
 
     /// The value as a plain integer in minor units. The widest backing is 128
-    /// bits, so this is lossless whichever one is compiled in, and it is how a
-    /// caller that may not name [`Cent`] still reads the number.
+    /// bits, so this is lossless whichever one is compiled in. It is also how a
+    /// caller that cannot name [`Cent`] still reads the number.
     pub fn minor_units(self) -> i128 {
         self.0.to_i128()
     }
 
-    /// The canonical 16-byte big-endian encoding (sign-extended), used for
-    /// content-addressed hashing. The width is fixed regardless of the backing,
-    /// so the same amount hashes identically under any backing.
+    /// The canonical 16-byte big-endian encoding (sign-extended), used for the
+    /// content address. The width is fixed whatever the backing is, so the same
+    /// amount hashes identically under any backing.
     pub fn to_canonical_bytes(self) -> [u8; 16] {
         self.0.to_i128().to_be_bytes()
     }
 
-    /// Decode a [`Cent`] from its canonical 16-byte encoding, returning
+    /// Decode a [`Cent`] from its canonical 16-byte encoding. Returns
     /// [`OverflowError`] if the value does not fit the active backing.
     pub fn from_canonical_bytes(bytes: &[u8; 16]) -> Result<Self, OverflowError> {
         Backing::try_from_i128(i128::from_be_bytes(*bytes))
@@ -262,9 +263,9 @@ impl Cent {
             .ok_or(OverflowError)
     }
 
-    /// The 16-byte order-preserving storage encoding: two's-complement
+    /// The 16-byte order-preserving storage encoding. It is two's-complement
     /// big-endian with the sign bit flipped, so a byte-wise (`memcmp`)
-    /// comparison of two encodings matches the numeric ordering of the amounts.
+    /// comparison of two encodings matches the numeric order of the amounts.
     /// SQLite compares `BLOB`s that way, which is what lets a stored amount be
     /// ordered and range-filtered.
     ///
@@ -277,10 +278,10 @@ impl Cent {
         encode_storage_i128(self.0.to_i128())
     }
 
-    /// Decode a [`Cent`] from its 16-byte storage encoding, returning
-    /// [`OverflowError`] if the value does not fit the active backing. A
-    /// database written under the `i128` backing therefore fails loudly when
-    /// read under the default `i64` one instead of truncating.
+    /// Decode a [`Cent`] from its 16-byte storage encoding. Returns
+    /// [`OverflowError`] if the value does not fit the active backing. So a
+    /// database written under the `i128` backing fails loudly when it is read
+    /// under the default `i64` one, and it truncates nothing.
     pub fn from_storage_bytes(bytes: &[u8; 16]) -> Result<Self, OverflowError> {
         Backing::try_from_i128(decode_storage_i128(bytes))
             .map(Cent)
@@ -319,8 +320,8 @@ impl From<i8> for Cent {
 }
 
 /// Fallible because the default `i64` backing holds only part of the `i128`
-/// range, and a value that does not fit is a different amount rather than a
-/// roundable one.
+/// range. A value that does not fit is a different amount, and not one to
+/// round.
 impl TryFrom<i128> for Cent {
     type Error = OverflowError;
 
@@ -372,7 +373,7 @@ impl<'de> Deserialize<'de> for Cent {
 // Scale: human-friendly parser/formatter (not stored)
 // ---------------------------------------------------------------------------
 
-/// A fixed number of decimal places, for converting between a decimal string a
+/// A fixed number of decimal places. It converts between a decimal string a
 /// person would write and the [`Cent`] the ledger stores. Never persisted:
 /// scale is a presentation concern and lives neither on the value nor on the
 /// asset (ADR-0009).
@@ -380,7 +381,7 @@ pub struct Scale {
     decimals: u8,
 }
 
-/// Error returned when parsing an amount string fails.
+/// Error returned when a parse of an amount string fails.
 #[derive(Debug, Clone, PartialEq, Eq)]
 pub enum ParseDecimalError {
     /// The input string is not a valid number.

+ 2 - 1
crates/kuatia-storage-sql/src/account.rs

@@ -13,7 +13,8 @@ use crate::row::{row_to_account, serialize_json};
 impl AccountStore for SqlStore {
     async fn get_account(&self, id: &AccountId) -> Result<Account, StoreError> {
         // The head points at the current version, so this is a single indexed
-        // lookup into the immutable history — no scan of the version chain.
+        // lookup into the immutable history, with no scan of the version
+        // chain.
         let row = sqlx::query(
             "SELECT a.* FROM accounts a \
              JOIN account_head h \

+ 21 - 15
crates/kuatia-storage-sql/src/commit.rs

@@ -1,12 +1,14 @@
 //! [`CommitStore`]: the atomic write boundary (ADR-0023).
 //!
 //! A whole transfer, or a whole account-version transition, is applied in one
-//! `BEGIN..COMMIT`. Because the write is all-or-nothing there is no half-applied
-//! state for recovery to reconcile, and the three stateful guards (double-spend,
-//! freeze/close, overdraft floor) are enforced inside the transaction rather than
-//! best-effort before it. On Postgres the account-head reads take `FOR UPDATE`
-//! before the live-posting writes; on SQLite the single write transaction
-//! serializes writers and the delete-affected-count is the double-spend backstop.
+//! `BEGIN..COMMIT`. The write is all-or-nothing, so no half-applied state is
+//! left for recovery to reconcile. The three stateful guards (double-spend,
+//! freeze/close, overdraft floor) are enforced inside the transaction, and not
+//! best-effort before it.
+//!
+//! On Postgres the account-head reads take `FOR UPDATE` before the live-posting
+//! writes. On SQLite the single write transaction serializes writers, and the
+//! delete-affected-count is the double-spend backstop.
 
 use std::collections::HashSet;
 
@@ -34,8 +36,9 @@ fn internal(e: impl std::fmt::Display) -> StoreError {
 }
 
 impl SqlStore {
-    /// Load one account at its head version inside `tx`, taking the pessimistic
-    /// lock (`FOR UPDATE` on Postgres). `None` means no such account.
+    /// Load one account at its head version inside `tx`, and take the
+    /// pessimistic lock (`FOR UPDATE` on Postgres). `None` means no such
+    /// account.
     async fn locked_account(
         &self,
         tx: &mut Transaction<'_, sqlx::Any>,
@@ -62,11 +65,13 @@ impl SqlStore {
     /// Sum the live-posting values for one `(owner, asset)` inside `tx`.
     ///
     /// The database does the addition, in one row rather than one row per
-    /// posting, and it is exact either way: PostgreSQL sums arbitrary-precision
-    /// `NUMERIC`, SQLite folds with `i128::checked_add` and raises on overflow
-    /// (ADR-0024). Deliberately unlocked: an aggregate cannot carry `FOR UPDATE`
-    /// on PostgreSQL, and it does not need to, because the caller already holds
-    /// the account-head lock that serializes the floor check.
+    /// posting. It is exact either way. PostgreSQL sums arbitrary-precision
+    /// `NUMERIC`, and SQLite folds with `i128::checked_add` and raises on
+    /// overflow (ADR-0024).
+    ///
+    /// Deliberately unlocked. An aggregate cannot carry `FOR UPDATE` on
+    /// PostgreSQL, and it does not need to. The caller already holds the
+    /// account-head lock that serializes the floor check.
     async fn live_balance(
         &self,
         tx: &mut Transaction<'_, sqlx::Any>,
@@ -84,8 +89,9 @@ impl SqlStore {
     }
 }
 
-/// Append `event` inside `tx`, deduping on its key. Mirrors the standalone
-/// `EventStore::append_event` but runs on the commit's transaction.
+/// Append `event` inside `tx`, with the dedup on its key. Mirrors the
+/// standalone `EventStore::append_event`, but runs on the transaction of the
+/// commit.
 async fn append_event_tx(
     tx: &mut Transaction<'_, sqlx::Any>,
     autoid: &kuatia_types::autoid::AutoId,

+ 30 - 29
crates/kuatia-storage-sql/src/dialect.rs

@@ -1,25 +1,26 @@
 //! The SQL dialect seam: the one place the SQLite/PostgreSQL divergence lives.
 //!
-//! Resolved once at construction from the pool's connection URL (no query), so
-//! the write paths read a plain enum instead of re-probing the backend. A third
-//! backend becomes a new variant here, not edits across every `impl`.
+//! Resolved once at construction from the connection URL of the pool, with no
+//! query. So the write paths read a plain enum, and nothing probes the backend
+//! again. A third backend becomes a new variant here, and not an edit across
+//! every `impl`.
 
 use sqlx::{Any, Pool};
 
-/// Which SQL backend a [`SqlStore`](crate::SqlStore) is talking to.
+/// Which SQL backend a [`SqlStore`](crate::SqlStore) talks to.
 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
 pub(crate) enum Dialect {
-    /// PostgreSQL: supports `SELECT ... FOR UPDATE` row locking.
+    /// PostgreSQL: supports the `SELECT ... FOR UPDATE` row lock.
     Postgres,
     /// SQLite: no `FOR UPDATE`; it serializes writers itself.
     Sqlite,
 }
 
 impl Dialect {
-    /// Resolve the dialect from the pool's connection URL scheme. Synchronous
-    /// and issues no query. Anything that is not `sqlite` is treated as
-    /// PostgreSQL, matching the prior runtime probe (which classified any
-    /// non-SQLite backend as Postgres).
+    /// Resolve the dialect from the URL scheme of the pool connection.
+    /// Synchronous, and issues no query. Anything that is not `sqlite` counts
+    /// as PostgreSQL, which is what the earlier runtime probe did: it
+    /// classified any non-SQLite backend as Postgres.
     pub(crate) fn from_pool(pool: &Pool<Any>) -> Self {
         match pool.connect_options().database_url.scheme() {
             "sqlite" => Self::Sqlite,
@@ -27,13 +28,13 @@ impl Dialect {
         }
     }
 
-    /// The placeholder for binding an amount, as it must appear in the SQL.
+    /// The placeholder that binds an amount, as it must appear in the SQL.
     ///
-    /// PostgreSQL stores amounts as `NUMERIC(39,0)` and the value arrives as
-    /// text (the `Any` driver has no numeric kind), so the cast is required
-    /// rather than cosmetic: `text` to `numeric` is explicit-only in `pg_cast`,
-    /// and a bare placeholder is rejected. SQLite binds the 16-byte encoding
-    /// straight into a `BLOB`.
+    /// PostgreSQL stores amounts as `NUMERIC(39,0)`, and the value arrives as
+    /// text, because the `Any` driver has no numeric kind. So the cast is
+    /// needed and not cosmetic: `text` to `numeric` is explicit-only in
+    /// `pg_cast`, and a bare placeholder is rejected. SQLite binds the 16-byte
+    /// encoding straight into a `BLOB`.
     pub(crate) fn money_bind(self, n: u32) -> String {
         match self {
             Self::Postgres => format!("CAST(${n} AS NUMERIC)"),
@@ -43,10 +44,10 @@ impl Dialect {
 
     /// How an amount column must be named in a `SELECT` list.
     ///
-    /// The cast is mandatory on PostgreSQL, and not only so the value can be
-    /// parsed: `AnyRow` converts every column's type before any of them is
-    /// read, and it has no mapping for `NUMERIC`, so one uncast amount fails
-    /// the whole row even when nothing reads it.
+    /// The cast is mandatory on PostgreSQL, and not only so the value parses.
+    /// `AnyRow` converts the type of every column before any of them is read,
+    /// and it has no mapping for `NUMERIC`. So one uncast amount fails the
+    /// whole row, even when nothing reads it.
     pub(crate) fn money_read(self, col: &str) -> String {
         match self {
             Self::Postgres => format!("CAST({col} AS TEXT) AS {col}"),
@@ -56,10 +57,10 @@ impl Dialect {
 
     /// An exact sum over an amount column, as a `SELECT` list entry.
     ///
-    /// Both sides are exact and neither wraps: `NUMERIC` is arbitrary
+    /// Both sides are exact and neither wraps. `NUMERIC` is arbitrary
     /// precision, and `kuatia_i128_sum` accumulates with `i128::checked_add`
-    /// and raises rather than overflowing. `COALESCE` and the aggregate's
-    /// zero-for-no-rows make an empty group a real row, so callers never have
+    /// and raises instead of an overflow. `COALESCE` and the zero-for-no-rows
+    /// of the aggregate make an empty group a real row, so a caller never has
     /// to special-case `NULL`.
     pub(crate) fn money_sum(self, col: &str) -> String {
         match self {
@@ -71,10 +72,10 @@ impl Dialect {
     /// The `SELECT` list [`row_to_posting`](crate::row::row_to_posting) reads.
     /// Spelled out rather than `*` because the amount column needs
     /// [`money_read`](Self::money_read); the six columns are shared by
-    /// `postings` and `live_postings`.
-    /// The explicit column list for a posting read, including the asset
-    /// definition joined from the registry: a posting carries an amount, and an
-    /// amount carries its asset. Pair it with [`joined`](crate::posting::joined).
+    /// `postings` and `live_postings`. The explicit column list for a posting
+    /// read. It covers the asset definition joined from the registry, because a
+    /// posting carries an amount and an amount carries its asset. Pair it with
+    /// [`joined`](crate::posting::joined).
     pub(crate) fn posting_columns(self) -> String {
         format!(
             "transfer_id, idx, owner, subaccount, asset, assets.data AS asset_def, {}",
@@ -82,9 +83,9 @@ impl Dialect {
         )
     }
 
-    /// Row-locking clause appended to a `SELECT` that takes a pessimistic lock:
-    /// ` FOR UPDATE` on Postgres, empty on SQLite (which has no such clause and
-    /// serializes writers itself).
+    /// The clause appended to a `SELECT` that takes a pessimistic row lock. It
+    /// is ` FOR UPDATE` on Postgres, and empty on SQLite, which has no such
+    /// clause and serializes writers itself.
     pub(crate) fn lock_clause(self) -> &'static str {
         match self {
             Self::Postgres => " FOR UPDATE",

+ 30 - 27
crates/kuatia-storage-sql/src/lib.rs

@@ -1,22 +1,23 @@
 //! SQL-backed Store implementation for SQLite and PostgreSQL.
 //!
-//! Uses `sqlx::Any` for database-agnostic queries. Enable features
-//! `sqlite` or `postgres` to select the backend.
+//! Uses `sqlx::Any` for database-agnostic queries. Enable features `sqlite` or
+//! `postgres` to select the backend.
 //!
 //! ```text
 //! let store = SqlStore::connect("sqlite::memory:").await?;
 //! ```
 //!
-//! [`SqlStore::connect`] owns the driver install, the pool and the migration.
-//! A caller that needs its own pool uses [`SqlStore::new`] instead, and then
-//! [`install_drivers`] replaces `sqlx::any::install_default_drivers` and has to
-//! run before the pool connects; see its docs for why.
+//! [`SqlStore::connect`] owns the driver install, the pool and the migration. A
+//! caller that needs its own pool uses [`SqlStore::new`] instead. Then
+//! [`install_drivers`] replaces `sqlx::any::install_default_drivers`, and it
+//! has to run before the pool connects. See its docs for why.
 //!
-//! The [`Store`](kuatia_storage::store::Store) sub-traits are each implemented in
-//! their own module (`account`, `posting`, `transfer`, `commit`, `event`,
-//! `book`, `projection`); shared row mappers and codecs live in `row`, the schema
-//! migrations in `migrate`, the SQLite/PostgreSQL divergence behind the
-//! `Dialect` seam in `dialect`, and the SQLite money functions in `sqlite_ext`.
+//! The [`Store`](kuatia_storage::store::Store) sub-traits are each implemented
+//! in their own module (`account`, `posting`, `transfer`, `commit`, `event`,
+//! `book`, `projection`). Shared row mappers and codecs live in `row`, and the
+//! schema migrations in `migrate`. The SQLite/PostgreSQL divergence sits behind
+//! the `Dialect` seam in `dialect`, and the SQLite money functions in
+//! `sqlite_ext`.
 
 use sqlx::any::AnyPoolOptions;
 use sqlx::{Any, Pool};
@@ -44,17 +45,17 @@ mod transfer;
 /// SQLite money functions.
 ///
 /// Call this instead of [`sqlx::any::install_default_drivers`], and call it
-/// **before** connecting any pool: the SQLite functions are registered as an
-/// auto-extension, so a connection opened earlier will not have them and every
-/// statement naming one fails to prepare.
+/// **before** any pool connects. The SQLite functions are registered as an
+/// auto-extension, so a connection opened earlier does not have them. Every
+/// statement that names one then fails to prepare.
 pub fn install_drivers() -> Result<(), StoreError> {
     sqlx::any::install_default_drivers();
     install_sqlite_extensions()
 }
 
 /// Install just the SQLite money functions, for callers that install the
-/// `sqlx::Any` drivers themselves. Idempotent; a no-op without the `sqlite`
-/// feature. See [`install_drivers`] for the ordering requirement.
+/// `sqlx::Any` drivers themselves. Idempotent; a no-op with no `sqlite`
+/// feature. See [`install_drivers`] for the requirement on order.
 pub fn install_sqlite_extensions() -> Result<(), StoreError> {
     #[cfg(feature = "sqlite")]
     {
@@ -72,9 +73,10 @@ pub struct SqlStore {
 }
 
 impl SqlStore {
-    /// Create a new SQL store wrapping an existing connection pool. The backend
-    /// dialect is resolved from the pool's connection URL, so no query is issued
-    /// here; call [`migrate`](Self::migrate) next to apply the schema.
+    /// Create a new SQL store around a connection pool the caller already has.
+    /// The backend dialect comes from the connection URL of the pool, so no
+    /// query is issued here. Call [`migrate`](Self::migrate) next to apply the
+    /// schema.
     pub fn new(pool: Pool<Any>) -> Self {
         let dialect = Dialect::from_pool(&pool);
         Self {
@@ -84,14 +86,15 @@ impl SqlStore {
         }
     }
 
-    /// Open the ledger database at `db_url` and apply the schema. The URL scheme
-    /// selects the backend (`sqlite::memory:`, `sqlite://kuatia.db`,
+    /// Open the ledger database at `db_url` and apply the schema. The URL
+    /// scheme selects the backend (`sqlite::memory:`, `sqlite://kuatia.db`,
     /// `postgres://user:pass@host/db`).
     ///
-    /// The pool is capped at a single connection because `sqlite::memory:` gives
-    /// each connection its own separate database, so a wider pool would split
-    /// the ledger into one copy per connection. Build the pool yourself and pass
-    /// it to [`new`](Self::new) to size it for a file or Postgres backend.
+    /// The pool is capped at a single connection because `sqlite::memory:`
+    /// gives each connection its own separate database. A wider pool would
+    /// split the ledger into one copy per connection. Build the pool yourself
+    /// and pass it to [`new`](Self::new) to size it for a file or Postgres
+    /// backend.
     pub async fn connect(db_url: &str) -> Result<Self, StoreError> {
         install_drivers()?;
         let pool = AnyPoolOptions::new()
@@ -105,8 +108,8 @@ impl SqlStore {
     }
 }
 
-/// A SQLite backend will not create a missing file unless the URL asks for it,
-/// so add `mode=rwc` to a file-backed `sqlite:` URL that does not already set a
+/// A SQLite backend creates an absent file only when the URL asks for it. So
+/// add `mode=rwc` to a file-backed `sqlite:` URL that does not already set a
 /// mode. In-memory and non-SQLite URLs pass through unchanged.
 fn sqlite_creatable(db_url: &str) -> String {
     if !db_url.starts_with("sqlite:") || db_url.contains(":memory:") || db_url.contains("mode=") {

+ 10 - 9
crates/kuatia-storage-sql/src/migrate.rs

@@ -1,5 +1,5 @@
 //! Schema migrations. Idempotent: a `_migrations` ledger records what has been
-//! applied, so re-running is a no-op.
+//! applied, so a second run is a no-op.
 
 use kuatia_storage::error::StoreError;
 
@@ -34,15 +34,16 @@ impl Migration {
 
 impl SqlStore {
     /// Run database migrations. Idempotent: a `_migrations` ledger records what
-    /// has been applied, so re-running is a no-op. Identifier and payload
-    /// columns are text, keeping a row legible for auditing: content-addressed
-    /// ids as hex `TEXT`, JSON payloads as their `TEXT` serialization. Amounts
-    /// are stored natively instead, so their DDL differs by backend (ADR-0024).
+    /// has been applied, so a second run is a no-op. Identifier and payload
+    /// columns are text, which keeps a row legible for an audit:
+    /// content-addressed ids as hex `TEXT`, JSON payloads as their `TEXT`
+    /// serialization. Amounts are stored natively instead, so their DDL differs
+    /// by backend (ADR-0024).
     ///
-    /// On SQLite this first checks that the money functions are installed,
-    /// since [`install_drivers`](crate::install_drivers) has to run before the
-    /// pool connects and a pool built without it would otherwise fail with a
-    /// bare "no such function" partway through a migration.
+    /// On SQLite this first checks that the money functions are installed.
+    /// [`install_drivers`](crate::install_drivers) has to run before the pool
+    /// connects. A pool built without it would otherwise fail with a bare "no
+    /// such function" partway through a migration.
     pub async fn migrate(&self) -> Result<(), StoreError> {
         if self.dialect == Dialect::Sqlite {
             sqlx::query("SELECT kuatia_i128_to_text(kuatia_i128_from_text('1'))")

+ 24 - 24
crates/kuatia-storage-sql/src/posting.rs

@@ -1,10 +1,10 @@
 //! [`PostingStore`]: the immutable posting record plus one `live_postings` hot
 //! table whose membership is each posting's state.
 //!
-//! A posting is in `live_postings` while it is spendable. Once consumed the row
-//! is deleted, leaving the posting only in the immutable `postings` table, so
-//! the two tables never disagree about what is spent. See ADR-0022 (merged hot
-//! index) and ADR-0016.
+//! A posting is in `live_postings` while it is spendable. Once consumed, the
+//! row is deleted and the posting stays only in the immutable `postings` table.
+//! So the two tables never disagree about what is spent. See ADR-0022 (merged
+//! hot index) and ADR-0016.
 
 use std::collections::HashMap;
 
@@ -24,8 +24,8 @@ use crate::dialect::Dialect;
 use crate::row::{row_to_cent, row_to_posting, transfer_id_to_hex};
 
 /// The live-balance aggregate, shared by [`PostingStore::live_balance`] and the
-/// in-transaction overdraft floor in `commit`, so both read the balance the same
-/// way. The sum happens in the database and is exact on both backends
+/// in-transaction overdraft floor in `commit`, so both read the balance the
+/// same way. The sum happens in the database and is exact on both backends
 /// (ADR-0024).
 pub(crate) fn live_balance_sql(dialect: Dialect) -> String {
     format!(
@@ -36,7 +36,7 @@ pub(crate) fn live_balance_sql(dialect: Dialect) -> String {
 }
 
 /// The source table a posting read of the given filter targets. No UNION and no
-/// predicate: the live set is exactly one table's rows.
+/// predicate: the live set is exactly the rows of one table.
 fn filter_source(filter: PostingFilter) -> &'static str {
     match filter {
         PostingFilter::Live => "live_postings",
@@ -48,31 +48,31 @@ fn filter_source(filter: PostingFilter) -> &'static str {
 /// amount and an amount carries its asset.
 ///
 /// Left-joined deliberately. An inner join would silently drop a posting whose
-/// asset is missing from the registry, which is the one outcome worse than an
-/// error; this way the decode fails loudly and says what is wrong. Writing such
-/// a posting is already refused a layer up, where a commit resolves every asset
-/// it names.
+/// asset is absent from the registry, which is the one outcome worse than an
+/// error. This way the decode fails loudly and says what is wrong. A write of
+/// such a posting is already refused a layer up, where a commit resolves every
+/// asset it names.
 pub(crate) fn joined(table: &str) -> String {
     format!("{table} LEFT JOIN assets ON assets.id = {table}.asset")
 }
 
 /// Maximum posting ids matched by a single statement. `id_predicate` expands to
-/// an `OR` of `n` equality pairs, so the binding constraint is SQLite's
-/// expression-tree depth limit (`SQLITE_MAX_EXPR_DEPTH`, default 1000), which a
-/// chain of `n` `OR`s reaches at roughly `n` deep. It caps well before the
-/// bind-parameter limits (SQLite 32766, PostgreSQL 65535) that `2 * n (+1)`
-/// parameters would hit. `500` stays comfortably under the expression-depth
-/// limit; callers that pass more ids are chunked, so the id-batch primitives
-/// have no practical ceiling on batch size.
+/// an `OR` of `n` equality pairs. So the constraint that binds is the
+/// expression-tree depth limit of SQLite (`SQLITE_MAX_EXPR_DEPTH`, default
+/// 1000). A chain of `n` `OR`s reaches that at roughly `n` deep. It caps well
+/// before the bind-parameter limits (SQLite 32766, PostgreSQL 65535) that
+/// `2 * n (+1)` parameters would hit. `500` stays comfortably under the
+/// expression-depth limit; callers that pass more ids are chunked, so the
+/// id-batch primitives have no practical ceiling on batch size.
 pub(crate) const MAX_IDS_PER_QUERY: usize = 500;
 
-/// Build a portable predicate matching a set of posting ids:
+/// Build a portable predicate for a set of posting ids:
 /// `(transfer_id = $s AND idx = $s+1) OR (transfer_id = $s+2 AND idx = $s+3) ...`
-/// starting at placeholder `$start`. Row-value `IN ((a, b), ...)` is not
-/// portable across SQLite and PostgreSQL; an `OR` of equality pairs is. The
-/// caller binds each id as `(hex(transfer), idx as i16)` in order, matching the
-/// placeholder sequence. `ids` must be non-empty and no longer than
-/// [`MAX_IDS_PER_QUERY`]; larger sets are split into chunks by the caller.
+/// from placeholder `$start` on. Row-value `IN ((a, b), ...)` is not portable
+/// across SQLite and PostgreSQL; an `OR` of equality pairs is. The caller binds
+/// each id as `(hex(transfer), idx as i16)` in order, to match the placeholder
+/// sequence. `ids` must be non-empty and no longer than [`MAX_IDS_PER_QUERY`];
+/// larger sets are split into chunks by the caller.
 pub(crate) fn id_predicate(count: usize, start: u32) -> String {
     (0..count)
         .map(|i| {

+ 18 - 17
crates/kuatia-storage-sql/src/row.rs

@@ -2,11 +2,11 @@
 //! columns it stores, and rows back into domain types.
 //!
 //! Identifier and payload columns are text, so a row stays legible in any SQL
-//! client: content-addressed ids as hex `TEXT`, JSON payloads as their `TEXT`
-//! serialization. Amounts are the exception. They are stored natively so the
-//! database can sum and order them (ADR-0024), which means their wire form
-//! depends on the backend, and every amount crosses this module through
-//! [`bind_money`] and [`row_to_cent`] rather than through `Display`/`FromStr`.
+//! client. Content-addressed ids are hex `TEXT`, and a JSON payload is its
+//! `TEXT` serialization. Amounts are the exception. They are stored natively,
+//! so the database can sum and order them (ADR-0024). Their wire form then
+//! depends on the backend, so every amount crosses this module through
+//! [`bind_money`] and [`row_to_cent`], and not through `Display`/`FromStr`.
 
 use std::sync::Arc;
 
@@ -23,10 +23,11 @@ use kuatia_types::*;
 
 use crate::dialect::Dialect;
 
-/// Bind one amount, in whichever form the backend's column takes: the decimal
-/// string for a PostgreSQL `NUMERIC` (the SQL must wrap the placeholder in
-/// [`Dialect::money_bind`]), the 16-byte order-preserving encoding for a SQLite
-/// `BLOB`. `.bind` is typed, so the two arms cannot be collapsed.
+/// Bind one amount, in whichever form the column of the backend takes. A
+/// PostgreSQL `NUMERIC` takes the decimal string, and the SQL must wrap the
+/// placeholder in [`Dialect::money_bind`]. A SQLite `BLOB` takes the 16-byte
+/// order-preserving encoding. `.bind` is typed, so the two arms cannot be
+/// collapsed.
 pub(crate) fn bind_money<'q>(
     q: Query<'q, sqlx::Any, AnyArguments<'q>>,
     dialect: Dialect,
@@ -67,9 +68,9 @@ pub(crate) fn row_to_cent(
     }
 }
 
-/// Serialize a value to a JSON string. Payload columns store JSON as `TEXT` so
-/// the database is directly readable for auditing; the ledger never queries into
-/// the JSON, so no binary or indexed representation is needed.
+/// Serialize a value to a JSON string. Payload columns store JSON as `TEXT`, so
+/// an audit can read the database directly. The ledger never queries into the
+/// JSON, so it needs no binary or indexed representation.
 pub(crate) fn serialize_json<T: serde::Serialize>(val: &T) -> Result<String, StoreError> {
     serde_json::to_string(val).map_err(|e| StoreError::Internal(format!("json serialization: {e}")))
 }
@@ -79,8 +80,8 @@ pub(crate) fn deserialize_json<T: serde::de::DeserializeOwned>(s: &str) -> Resul
 }
 
 /// Lower-case hex encoding. Binary identifiers (content-addressed hashes) are
-/// stored as hex `TEXT` so a row is legible in any SQL client and matches the
-/// hex form used in logs and `Debug` output.
+/// stored as hex `TEXT`, so a row is legible in any SQL client. The form also
+/// matches the hex in logs and in `Debug` output.
 pub(crate) fn to_hex(bytes: &[u8]) -> String {
     const HEX: &[u8; 16] = b"0123456789abcdef";
     let mut s = String::with_capacity(bytes.len() * 2);
@@ -145,9 +146,9 @@ pub(crate) fn row_to_account(row: &AnyRow) -> Result<Account, StoreError> {
     })
 }
 
-/// Decode the asset definition a posting read joins in. The registry row is
-/// the same JSON `AssetStore` writes, so a posting comes back whole without a
-/// second query and without a lookup that could fail.
+/// Decode the asset definition a posting read joins in. The registry row is the
+/// same JSON `AssetStore` writes. So a posting comes back whole, with no second
+/// query and no lookup that could fail.
 pub(crate) fn row_to_asset(row: &AnyRow) -> Result<Arc<Asset>, StoreError> {
     let data: Option<String> = row
         .try_get("asset_def")

+ 35 - 32
crates/kuatia-storage-sql/src/sqlite_ext.rs

@@ -1,18 +1,19 @@
 //! The SQLite money functions, registered as an auto-extension.
 //!
-//! SQLite has no 128-bit integer, so a money column stores the 16-byte
-//! order-preserving encoding from `kuatia-money` and this module teaches the
-//! engine to fold and print it. `kuatia_i128_sum` is what lets the overdraft
-//! floor be one aggregate row instead of one row per posting, and it is exact:
-//! it accumulates with `i128::checked_add` and raises rather than wrapping.
+//! SQLite has no 128-bit integer. So a money column stores the 16-byte
+//! order-preserving encoding from `kuatia-money`, and this module teaches the
+//! engine to fold and print it. `kuatia_i128_sum` is what makes the overdraft
+//! floor one aggregate row instead of one row per posting. It is also exact: it
+//! accumulates with `i128::checked_add`, and it raises instead of a wrap.
 //!
 //! Registration goes through `sqlite3_auto_extension` because `sqlx::Any` never
-//! exposes the underlying `sqlite3*` handle, so there is nowhere to hook a
-//! per-connection callback. That makes it process-global and one-way: every
-//! SQLite connection opened afterwards, by anyone in the process, sees these
+//! exposes the `sqlite3*` handle below it, so there is nowhere to hook a
+//! per-connection callback. That makes it process-global and one-way. Every
+//! SQLite connection opened after it, by anyone in the process, sees these
 //! functions, which is why the names are prefixed. It also has to happen before
-//! the first connection is opened; [`SqlStore::migrate`](crate::SqlStore::migrate)
-//! probes for the functions and reports a typed error if it did not.
+//! the first connection is opened;
+//! [`SqlStore::migrate`](crate::SqlStore::migrate) probes for the functions and
+//! reports a typed error if it did not.
 
 use std::ffi::{CStr, c_char, c_int, c_void};
 use std::sync::Once;
@@ -32,9 +33,9 @@ static INSTALL_RC: AtomicI32 = AtomicI32::new(ffi::SQLITE_OK);
 /// Register the money functions with every SQLite connection this process opens
 /// from now on. Idempotent, and cheap to call again.
 ///
-/// Must run before the first connection is opened: a connection established
-/// earlier does not get the functions, and any statement naming one fails to
-/// prepare.
+/// Must run before the first connection is opened. A connection established
+/// earlier does not get the functions, and any statement that names one fails
+/// to prepare.
 pub fn install() -> Result<(), StoreError> {
     INSTALL.call_once(|| {
         let rc = unsafe { ffi::sqlite3_auto_extension(Some(entry_point)) };
@@ -112,13 +113,15 @@ unsafe extern "C" fn entry_point(
 
 /// The `kuatia_i128_sum` accumulator.
 ///
-/// The sum is held as raw bytes rather than an `i128` field on purpose:
-/// `sqlite3_aggregate_context` returns memory aligned for 8 bytes, not the 16 an
-/// `i128` wants, so a struct carrying one could not be read through the returned
-/// pointer on every target. They are *native* bytes, not the storage encoding,
-/// because SQLite hands back the allocation zeroed and zeroed native bytes are
-/// the zero this fold has to start from. The same 16 zero bytes read as a
-/// storage encoding would be `i128::MIN`.
+/// The sum is held as raw bytes rather than an `i128` field on purpose.
+/// `sqlite3_aggregate_context` returns memory aligned for 8 bytes, and not the
+/// 16 an `i128` wants. A struct with an `i128` field in it could then not be
+/// read through the returned pointer on every target.
+///
+/// They are *native* bytes, and not the storage encoding. SQLite hands back the
+/// allocation zeroed, and zeroed native bytes are the zero this fold has to
+/// start from. The same 16 zero bytes read as a storage encoding would be
+/// `i128::MIN`.
 #[repr(C)]
 #[derive(Clone, Copy)]
 struct Accumulator {
@@ -126,11 +129,11 @@ struct Accumulator {
     failed: c_int,
 }
 
-/// Report `message` as the failure of the running SQL statement.
+/// Report `message` as the failure of the SQL statement in progress.
 ///
 /// # Safety
 ///
-/// `ctx` must be the context SQLite passed to the enclosing callback.
+/// `ctx` must be the context SQLite passed to the callback around this call.
 unsafe fn fail(ctx: *mut ffi::sqlite3_context, message: &CStr) {
     unsafe { ffi::sqlite3_result_error(ctx, message.as_ptr(), -1) }
 }
@@ -140,7 +143,7 @@ unsafe fn fail(ctx: *mut ffi::sqlite3_context, message: &CStr) {
 ///
 /// # Safety
 ///
-/// `value` must be an argument SQLite passed to the enclosing callback.
+/// `value` must be an argument SQLite passed to the callback around this call.
 unsafe fn amount_arg(value: *mut ffi::sqlite3_value) -> Option<i128> {
     if unsafe { ffi::sqlite3_value_type(value) } != ffi::SQLITE_BLOB {
         return None;
@@ -157,12 +160,12 @@ unsafe fn amount_arg(value: *mut ffi::sqlite3_value) -> Option<i128> {
     Some(decode_storage_i128(&bytes))
 }
 
-/// Return a 16-byte amount as the result of the current call. `SQLITE_TRANSIENT`
-/// makes SQLite copy the buffer before this frame goes away.
+/// Return a 16-byte amount as the result of the current call.
+/// `SQLITE_TRANSIENT` makes SQLite copy the buffer before this frame goes away.
 ///
 /// # Safety
 ///
-/// `ctx` must be the context SQLite passed to the enclosing callback.
+/// `ctx` must be the context SQLite passed to the callback around this call.
 unsafe fn result_amount(ctx: *mut ffi::sqlite3_context, value: i128) {
     let bytes = encode_storage_i128(value);
     unsafe {
@@ -175,7 +178,7 @@ unsafe fn result_amount(ctx: *mut ffi::sqlite3_context, value: i128) {
     }
 }
 
-/// Fold one row into the running sum.
+/// Fold one row into the sum so far.
 ///
 /// # Safety
 ///
@@ -212,10 +215,10 @@ unsafe extern "C" fn sum_step(
     unsafe { std::ptr::write_unaligned(raw, acc) };
 }
 
-/// Produce the aggregate's result: the summed amount, or an error if any row
-/// was not a 16-byte amount or the running total left the `i128` range. An
-/// empty group sums to zero rather than to SQL `NULL`, so a caller can decode
-/// the result unconditionally.
+/// Produce the result of the aggregate, which is the summed amount. It is an
+/// error instead if any row was not a 16-byte amount, or if the total so far
+/// left the `i128` range. An empty group sums to zero rather than to SQL
+/// `NULL`, so a caller can decode the result unconditionally.
 ///
 /// # Safety
 ///
@@ -241,7 +244,7 @@ unsafe extern "C" fn sum_final(ctx: *mut ffi::sqlite3_context) {
 
 /// `kuatia_i128_from_text(TEXT) -> BLOB`: the decimal form of an amount to its
 /// stored encoding. Used by the migration that converts the old text columns,
-/// which is also what makes a missing installation fail at prepare time.
+/// which is also what makes an absent installation fail at prepare time.
 ///
 /// # Safety
 ///

+ 18 - 17
crates/kuatia-storage-sql/tests/postgres.rs

@@ -4,16 +4,16 @@
 //! PostgreSQL conformance run.
 //!
 //! The same `store_tests!` suite the SQLite backend passes, driven against a
-//! real PostgreSQL instance so the Postgres-only code paths (the `FOR UPDATE`
-//! row locks behind `lock_clause`, the `ON CONFLICT` upserts) are actually
-//! exercised. Point `DATABASE_URL` at a Postgres database to run it; the CI
+//! real PostgreSQL instance. So the Postgres-only code paths run for real: the
+//! `FOR UPDATE` row locks behind `lock_clause`, and the `ON CONFLICT` upserts.
+//! Point `DATABASE_URL` at a Postgres database to run it, and the CI
 //! `Test (PostgreSQL)` job supplies one.
 //!
 //! Unlike `sqlite::memory:`, where every pool is its own fresh database, all
-//! tests here share one Postgres database and the conformance tests reuse fixed
-//! ids. Each store therefore gets its own uniquely-named schema, and the pool is
-//! pinned to a single connection so the session `search_path` set below persists
-//! for the store's whole lifetime.
+//! tests here share one Postgres database, and the conformance tests reuse
+//! fixed ids. So each store gets its own uniquely-named schema. The pool is
+//! also pinned to a single connection. That is what makes the session
+//! `search_path` set below last for the whole life of the store.
 
 use std::sync::atomic::{AtomicU64, Ordering};
 
@@ -73,10 +73,10 @@ async fn new_store_with_pool() -> (SqlStore, Pool<Any>) {
 
 kuatia_storage::store_tests!(new_store);
 
-/// Amounts are stored as native `NUMERIC`, not text, and round-trip through the
-/// store. The type assertion is the point: under `sqlx::Any` an uncast
-/// `NUMERIC` fails the whole row, so this also proves every money `SELECT`
-/// goes through `Dialect::money_read` (ADR-0024).
+/// Amounts are stored as native `NUMERIC` and not text, and they round-trip
+/// through the store. The type assertion is the point. Under `sqlx::Any` an
+/// uncast `NUMERIC` fails the whole row, so this also proves that every money
+/// `SELECT` goes through `Dialect::money_read` (ADR-0024).
 #[tokio::test]
 async fn amount_columns_are_numeric() {
     let (store, pool) = new_store_with_pool().await;
@@ -123,8 +123,9 @@ async fn amount_columns_are_numeric() {
     }
 }
 
-/// The 013 migration adds the value-date column, and an existing row gets NULL:
-/// an entry booked before the column existed was valued the day it was booked.
+/// The 013 migration adds the value-date column, and a row that is already
+/// there gets NULL. An entry booked before the column existed was valued on the
+/// day it was booked.
 #[tokio::test]
 async fn migration_013_adds_value_date_as_null_for_existing_rows() {
     let (_store, pool) = new_store_with_pool().await;
@@ -153,8 +154,8 @@ async fn migration_013_adds_value_date_as_null_for_existing_rows() {
 }
 
 /// The 012 migration drops the reservation column and leaves every live row
-/// live, including one that still carried a token: it was never consumed, so it
-/// must stay spendable and keep counting toward the balance.
+/// live. That covers a row that still carried a token. It was never consumed,
+/// so it must stay spendable and it must still count toward the balance.
 #[tokio::test]
 async fn migration_012_drops_reservation_and_keeps_rows_live() {
     let (_store, pool) = new_store_with_pool().await;
@@ -191,8 +192,8 @@ async fn migration_012_drops_reservation_and_keeps_rows_live() {
     assert_eq!(row.try_get::<String, _>("s").unwrap(), "350");
 }
 
-/// The 011 migration rewrites the existing text amounts into `NUMERIC`, keeping
-/// their values (including negatives).
+/// The 011 migration rewrites the text amounts already stored into `NUMERIC`,
+/// and it keeps their values, a negative one too.
 #[tokio::test]
 async fn migration_011_converts_text_amounts() {
     let (_store, pool) = new_store_with_pool().await;

+ 47 - 41
crates/kuatia-storage-sql/tests/sqlite.rs

@@ -43,9 +43,11 @@ kuatia_storage::store_tests!(new_store);
 
 /// The point of the schema: no identifier or payload column holds opaque
 /// binary. A content-addressed id is stored as lower-case hex text, and a
-/// structured payload as readable JSON text, so a row can be audited in a plain
-/// SQL client. Amounts are the one exception, stored natively so the database
-/// can sum and order them (ADR-0024); `kuatia_i128_to_text` is how a client that
+/// structured payload as readable JSON text. So an audit can read a row in a
+/// plain SQL client.
+///
+/// Amounts are the one exception. They are stored natively, so the database can
+/// sum and order them (ADR-0024). `kuatia_i128_to_text` is how a client that
 /// registered the money functions reads one back.
 #[tokio::test]
 async fn columns_store_hex_ids_and_json_text() {
@@ -102,8 +104,9 @@ async fn columns_store_hex_ids_and_json_text() {
     assert_eq!(row.try_get::<String, _>("v").unwrap(), "100");
 }
 
-/// The 002 migration adds the subaccount column and a subaccount account/posting
-/// round-trips through the schema, kept distinct from the main account.
+/// The 002 migration adds the subaccount column. A subaccount account and
+/// posting round-trip through the schema, and stay distinct from the main
+/// account.
 #[tokio::test]
 async fn subaccount_columns_round_trip() {
     let store = new_store().await;
@@ -146,9 +149,9 @@ async fn subaccount_columns_round_trip() {
     assert!(by_main.is_empty());
 }
 
-/// A database created under 001 (no subaccount column) upgrades in place: the
-/// 002 migration rebuilds the tables and existing rows default to subaccount 0,
-/// the main account.
+/// A database created under 001, with no subaccount column, upgrades in place.
+/// The 002 migration rebuilds the tables, and a row already stored defaults to
+/// subaccount 0, the main account.
 #[tokio::test]
 async fn migration_upgrades_existing_rows_to_main_account() {
     let pool = new_pool().await;
@@ -228,9 +231,10 @@ async fn migration_upgrades_existing_rows_to_main_account() {
 }
 
 /// The 004 migration splits lifecycle state out of `postings` into the two
-/// id-only index tables: an active (status 0) posting is backfilled into
-/// `active_postings`, a reserved (status 1) posting into `reserved_postings`
-/// with its token, and the `status` column is dropped from `postings`.
+/// id-only index tables. An active posting, status 0, is backfilled into
+/// `active_postings`. A reserved posting, status 1, goes into
+/// `reserved_postings` with its token. The `status` column is dropped from
+/// `postings`.
 #[tokio::test]
 async fn migration_004_backfills_index_tables() {
     let pool = new_pool().await;
@@ -332,9 +336,9 @@ async fn migration_004_backfills_index_tables() {
     );
 }
 
-/// The 005 migration backfills `account_head` with the current (highest)
-/// version of each account, so a subsequent read hits one row per account
-/// without scanning the version history.
+/// The 005 migration backfills `account_head` with the current version of each
+/// account, which is the highest one. So a later read hits one row per account,
+/// and scans no version history.
 #[tokio::test]
 async fn migration_005_backfills_account_head() {
     let pool = new_pool().await;
@@ -404,9 +408,9 @@ async fn migration_005_backfills_account_head() {
 }
 
 /// The 008 migration merges the two index tables into one `live_postings`
-/// table: an active row is backfilled with `reservation` NULL, a reserved row
-/// keeps its token, and the old `active_postings`/`reserved_postings` tables are
-/// dropped.
+/// table. An active row is backfilled with `reservation` NULL, and a reserved
+/// row keeps its token. The old `active_postings` and `reserved_postings`
+/// tables are dropped.
 #[tokio::test]
 async fn migration_008_merges_live_postings() {
     let pool = new_pool().await;
@@ -497,7 +501,7 @@ async fn migration_008_merges_live_postings() {
     );
 }
 
-/// migrate() is idempotent: running it repeatedly on the same DB is a no-op.
+/// migrate() is idempotent, so a second run on the same database is a no-op.
 #[tokio::test]
 async fn migrate_is_idempotent() {
     kuatia_storage_sql::install_drivers().expect("install sqlite money functions");
@@ -512,11 +516,11 @@ async fn migrate_is_idempotent() {
     store.migrate().await.unwrap();
 }
 
-/// The id-batch primitives chunk a large id set so it never exceeds the
-/// backend's bind-parameter limit (SQLite caps a statement at 32766 variables).
-/// A batch larger than one chunk must be created, read, and spent exactly as a
-/// small one is. The commit's consume SELECT and DELETE are the chunked writes
-/// this guards.
+/// The id-batch primitives chunk a large id set, so it never exceeds the
+/// bind-parameter limit of the backend. SQLite caps a statement at 32766
+/// variables. A batch larger than one chunk must be created, read and spent
+/// exactly as a small one is. The consume SELECT and DELETE of the commit are
+/// the chunked writes this guards.
 #[tokio::test]
 async fn id_batches_chunk_across_reads_and_commit() {
     const N: u16 = 9000;
@@ -580,8 +584,8 @@ async fn money_scalars_round_trip() {
     }
 }
 
-/// The aggregate folds mixed signs exactly, and an empty group sums to zero
-/// rather than to SQL NULL, so a caller can decode the result unconditionally.
+/// The aggregate folds mixed signs exactly. An empty group sums to zero rather
+/// than to SQL NULL, so a caller can decode the result unconditionally.
 #[tokio::test]
 async fn i128_sum_folds_and_handles_empty_group() {
     let pool = new_pool().await;
@@ -614,8 +618,8 @@ async fn i128_sum_folds_and_handles_empty_group() {
     assert_eq!(decoded(&row.try_get::<Vec<u8>, _>("s").unwrap()), 0);
 }
 
-/// The aggregate raises rather than wrapping. This is the property that makes
-/// summing in SQL as safe as `Cent::checked_sum`.
+/// The aggregate raises instead of a wrap. That property is what makes a sum in
+/// SQL as safe as `Cent::checked_sum`.
 #[tokio::test]
 async fn i128_sum_overflows_loudly() {
     let pool = new_pool().await;
@@ -640,8 +644,8 @@ async fn i128_sum_overflows_loudly() {
     assert!(err.contains("i128"), "{err}");
 }
 
-/// A value that is not a 16-byte amount fails the statement instead of being
-/// skipped, so a corrupt row can never silently change a balance.
+/// A value that is not a 16-byte amount fails the statement, and the aggregate
+/// skips none. So a corrupt row can never silently change a balance.
 #[tokio::test]
 async fn i128_sum_rejects_non_amount() {
     let pool = new_pool().await;
@@ -655,9 +659,9 @@ async fn i128_sum_rejects_non_amount() {
     assert!(err.contains("16-byte"), "{err}");
 }
 
-/// The storage encoding is order-preserving, so SQLite's byte-wise BLOB
-/// comparison orders amounts numerically. This is what the text columns could
-/// not do (ADR-0011) and the reason the encoding flips the sign bit.
+/// The storage encoding is order-preserving, so the byte-wise BLOB comparison
+/// of SQLite orders amounts numerically. The text columns could not do that
+/// (ADR-0011), and it is the reason the encoding flips the sign bit.
 #[tokio::test]
 async fn blob_order_matches_numeric_order() {
     let pool = new_pool().await;
@@ -719,8 +723,9 @@ async fn value_beyond_i64_round_trips() {
     );
 }
 
-/// The 013 migration adds the value-date column, and an existing row gets NULL:
-/// an entry booked before the column existed was valued the day it was booked.
+/// The 013 migration adds the value-date column, and a row that is already
+/// there gets NULL. An entry booked before the column existed was valued on the
+/// day it was booked.
 #[tokio::test]
 async fn migration_013_adds_value_date_as_null_for_existing_rows() {
     let pool = new_pool().await;
@@ -774,9 +779,9 @@ async fn migration_013_adds_value_date_as_null_for_existing_rows() {
     );
 }
 
-/// The value-date window is a SQL predicate, not a filter applied after loading,
-/// so it has to behave the same as the in-memory backend: an entry with no value
-/// date sits outside an explicit window rather than inside every one.
+/// The value-date window is a SQL predicate, and not a filter applied after the
+/// load. So it has to behave the same as the in-memory backend. An entry with
+/// no value date sits outside an explicit window, and not inside every one.
 #[tokio::test]
 async fn value_date_window_filters_in_sql() {
     let pool = new_pool().await;
@@ -855,8 +860,8 @@ async fn value_date_window_filters_in_sql() {
 }
 
 /// The 012 migration drops the reservation column and leaves every live row
-/// live, including one that still carried a token: it was never consumed, so it
-/// must stay spendable and keep counting toward the balance.
+/// live. That covers a row that still carried a token. It was never consumed,
+/// so it must stay spendable and it must still count toward the balance.
 #[tokio::test]
 async fn migration_012_drops_reservation_and_keeps_rows_live() {
     let pool = new_pool().await;
@@ -924,8 +929,9 @@ async fn migration_012_drops_reservation_and_keeps_rows_live() {
     assert_eq!(decoded(&row.try_get::<Vec<u8>, _>("s").unwrap()), 350);
 }
 
-/// The 011 migration rewrites the existing text amounts into the native blob
-/// encoding, keeping their values (including negatives) and the rest of the row.
+/// The 011 migration rewrites the text amounts already stored into the native
+/// blob encoding. It keeps their values, a negative one too, and the rest of
+/// the row.
 #[tokio::test]
 async fn migration_011_converts_text_amounts() {
     let pool = new_pool().await;

+ 11 - 9
crates/kuatia-storage/src/error.rs

@@ -5,20 +5,22 @@ use std::fmt;
 
 /// Errors produced by [`Store`](crate::store::Store) implementations.
 ///
-/// A `StoreError` is an I/O fault, never a domain verdict: a commit reports a
-/// refusal as a typed [`CommitRejection`](crate::store::CommitRejection) and the
-/// count-returning writes report a count, so there is no "already exists" or
-/// "version conflict" variant for a caller to match on here. [`Misconfigured`](Self::Misconfigured) is not a write
-/// outcome at all: it reports that the backend was never set up correctly, which
-/// no amount of retrying will fix.
+/// A `StoreError` is an I/O fault, and never a domain verdict. A commit reports
+/// a refusal as a typed [`CommitRejection`](crate::store::CommitRejection), and
+/// a write that returns a count reports a count. So there is no "already
+/// exists" or "version conflict" variant for a caller to match on here.
+///
+/// [`Misconfigured`](Self::Misconfigured) is not a write outcome at all. It
+/// reports that the backend was never set up correctly, and no retry fixes
+/// that.
 #[derive(Debug, Clone)]
 pub enum StoreError {
-    /// The requested entity was not found.
+    /// The entity the caller asked for was not found.
     NotFound(String),
     /// Catch-all for unexpected internal errors.
     Internal(String),
-    /// The backend is missing setup the store requires, such as the SQLite
-    /// functions that must be installed before any connection is opened.
+    /// The backend lacks setup the store needs, such as the SQLite functions
+    /// that must be installed before any connection is opened.
     Misconfigured(String),
 }
 

+ 22 - 19
crates/kuatia-storage/src/events.rs

@@ -1,4 +1,4 @@
-//! Ledger event types and storage trait.
+//! The ledger event types and the storage trait for them.
 
 use async_trait::async_trait;
 use serde::{Deserialize, Serialize};
@@ -7,7 +7,7 @@ use kuatia_types::{AccountId, TransferId};
 
 use crate::error::StoreError;
 
-/// The kind of ledger event that occurred.
+/// The kind of a ledger event.
 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 pub enum LedgerEventKind {
     /// A transfer was committed.
@@ -60,20 +60,20 @@ pub struct LedgerEvent {
     pub kind: LedgerEventKind,
 }
 
-/// The idempotency key for an event, if it has a natural one. Replayable events
-/// (re-appended by crash recovery) carry a key so a second append collapses to
-/// the existing row instead of duplicating.
+/// The idempotency key for an event, if it has a natural one. A replayable
+/// event, which crash recovery appends again, carries a key. So a second append
+/// collapses onto the row that is already there, and inserts no duplicate.
 ///
 /// - A committed transfer keys on its content-addressed id (hex).
 /// - An account lifecycle *transition* (freeze/unfreeze/close) keys on the
-///   `(account, version)` it records: each version bump happens exactly once, so
-///   the pair is a stable identity that recovery reproduces verbatim.
-/// - `AccountCreated` has no version-transition identity and is not re-driven, so
-///   it returns `None` and may recur.
+///   `(account, version)` it records. Each version bump happens exactly once,
+///   so the pair is a stable identity that recovery reproduces word for word.
+/// - `AccountCreated` has no version-transition identity and is not re-driven,
+///   so it returns `None` and can recur.
 ///
-/// Keys are strings so both identities share the store's single `dedup_key`
-/// column; the transfer form is the same lowercase hex the column already holds,
-/// so no existing row changes meaning.
+/// A key is a string, so both identities share the single `dedup_key` column of
+/// the store. The transfer form is the same lowercase hex the column already
+/// holds, so the sense of a stored row does not change.
 pub fn event_dedup_key(kind: &LedgerEventKind) -> Option<String> {
     match kind {
         LedgerEventKind::TransferCommitted { transfer_id } => Some(hex(&transfer_id.0)),
@@ -96,8 +96,9 @@ pub fn event_dedup_key(kind: &LedgerEventKind) -> Option<String> {
     }
 }
 
-/// Lower-case hex, matching the SQL backend's `dedup_key` encoding for transfer
-/// events so the key a recovered append produces equals the stored one.
+/// Lower-case hex, to match the `dedup_key` encoding of the SQL backend for a
+/// transfer event. So the key a recovered append produces equals the stored
+/// one.
 fn hex(bytes: &[u8]) -> String {
     let mut s = String::with_capacity(bytes.len() * 2);
     for &b in bytes {
@@ -109,13 +110,15 @@ fn hex(bytes: &[u8]) -> String {
 /// Persistent event log for ledger events.
 #[async_trait]
 pub trait EventStore: Send + Sync {
-    /// Append an event and return its sequence number. Idempotent on the event's
-    /// [`event_dedup_key`]: appending an event whose key already exists does not
-    /// insert a duplicate and returns the existing seq. The `seq` field on the
-    /// input is ignored -- the store assigns it.
+    /// Append an event and return its sequence number. Idempotent on the
+    /// [`event_dedup_key`] of the event. An append of an event whose key is
+    /// already there inserts no duplicate, and returns the seq that is already
+    /// there. The `seq` field on the input is ignored, because the store
+    /// assigns it.
     async fn append_event(&self, event: &LedgerEvent) -> Result<u64, StoreError>;
 
-    /// Return events with sequence numbers greater than `after_seq`, up to `limit`.
+    /// Return events with sequence numbers greater than `after_seq`, up to
+    /// `limit`.
     async fn get_events_since(
         &self,
         after_seq: u64,

+ 11 - 9
crates/kuatia-storage/src/mem_store.rs

@@ -24,9 +24,9 @@ use crate::store::{
     TransferStore, TransitionOutcome, TransitionRejection,
 };
 
-/// Postings held as an immutable record table plus a live index carrying full
-/// row copies, so a live-set read never merges back to the immutable record.
-/// Both sit under one lock so a commit's spend is atomic.
+/// Postings held as an immutable record table plus a live index. The live index
+/// holds full row copies, so a live-set read never merges back to the immutable
+/// record. Both sit under one lock, so the spend of a commit is atomic.
 #[derive(Default)]
 struct PostingTables {
     /// The append-only record of every posting; never mutated or removed.
@@ -35,14 +35,15 @@ struct PostingTables {
     live: HashMap<PostingId, Posting>,
 }
 
-/// In-memory [`Store`](crate::store::Store) implementation backed by `RwLock<HashMap>`.
+/// In-memory [`Store`](crate::store::Store) implementation backed by
+/// `RwLock<HashMap>`.
 pub struct InMemoryStore {
     postings: RwLock<PostingTables>,
     accounts: RwLock<HashMap<AccountId, Vec<Account>>>,
     transfers: RwLock<HashMap<TransferId, TransferRecord>>,
     /// Transfer-participation index: the `involved` set the caller passed to
-    /// the commit, mirroring the SQL `transfer_accounts` table so both backends
-    /// resolve `get_transfers_for_account` from the same instruction.
+    /// the commit. It mirrors the SQL `transfer_accounts` table, so both
+    /// backends resolve `get_transfers_for_account` from the same instruction.
     transfer_accounts: RwLock<HashMap<TransferId, Vec<AccountId>>>,
     events: RwLock<Vec<LedgerEvent>>,
     assets: RwLock<HashMap<AssetId, Asset>>,
@@ -323,9 +324,10 @@ impl TransferStore for InMemoryStore {
 // CommitStore
 // ---------------------------------------------------------------------------
 
-/// Append `event` into an already-locked event log, deduping on its key. Mirrors
-/// [`EventStore::append_event`] but takes the guard the atomic commit already
-/// holds, so the whole commit stays under one set of locks.
+/// Append `event` into an event log that is already locked, with the dedup on
+/// its key. Mirrors [`EventStore::append_event`], but takes the guard the
+/// atomic commit already holds, so the whole commit stays under one set of
+/// locks.
 fn append_event_locked(events: &mut Vec<LedgerEvent>, autoid: &AutoId, event: &LedgerEvent) {
     if let Some(key) = event_dedup_key(&event.kind)
         && events

+ 25 - 22
crates/kuatia-storage/src/query.rs

@@ -1,21 +1,23 @@
-//! Filter and pagination primitives shared by every [`Store`](crate::store::Store)
-//! backend, stated once above the trait seam.
+//! The filter and page primitives every [`Store`](crate::store::Store) backend
+//! shares, stated once above the trait seam.
 //!
-//! A backend's `query_transfers`/`query_postings` implementation does only what
-//! is genuinely backend-specific: load the candidate records (via an account
-//! index, a store-wide scan, or a SQL `LIMIT` push-down). Everything after that,
-//! the time-window/book predicate and the `total` + `skip`/`take` cut, is the
-//! same contract regardless of backend and lives here.
+//! The `query_transfers`/`query_postings` of a backend does only what is
+//! genuinely backend-specific. That is the load of the candidate records,
+//! through an account index, a store-wide scan, or a SQL `LIMIT` push-down.
+//! Everything after that is the same contract on every backend, and it lives
+//! here. That is the time-window and book predicate, plus the `total` and the
+//! `skip`/`take` cut.
 
 use crate::store::{Page, TransferQuery, TransferRecord};
 
-/// Keep only the transfers matching a query's time-window and book predicates.
+/// Keep only the transfers that match the time-window and book predicates of a
+/// query.
 ///
-/// The account/subaccount filter is *not* applied here: a backend narrows to
-/// participating accounts when it loads candidates (an in-memory participation
-/// index or the SQL `transfer_accounts` join), because that filter is what the
-/// backend can push down. This covers every remaining predicate so both
-/// backends agree on the contract.
+/// The account and subaccount filter is *not* applied here. A backend narrows
+/// to the accounts that take part when it loads candidates, through an
+/// in-memory participation index or the SQL `transfer_accounts` join. That
+/// filter is the one a backend can push down. This covers every predicate that
+/// is left, so both backends agree on the contract.
 pub fn filter_transfers(
     records: Vec<TransferRecord>,
     query: &TransferQuery,
@@ -53,21 +55,22 @@ pub fn filter_transfers(
         .collect()
 }
 
-/// The effective `(offset, limit)` window from a query's optional bounds: offset
-/// defaults to 0, limit to unbounded. One definition shared by the in-memory
-/// [`paginate`] cut and the SQL `LIMIT`/`OFFSET` push-down, so the two agree on
-/// what an absent bound means instead of each restating the defaults.
+/// The effective `(offset, limit)` window from the optional bounds of a query.
+/// Offset defaults to 0, and limit to unbounded. One definition, shared by the
+/// in-memory [`paginate`] cut and the SQL `LIMIT`/`OFFSET` push-down. So the
+/// two agree on what an absent bound means, and neither states the defaults
+/// again.
 pub fn window(offset: Option<u32>, limit: Option<u32>) -> (u32, u32) {
     (offset.unwrap_or(0), limit.unwrap_or(u32::MAX))
 }
 
 /// Cut a fully-filtered, ordered record set into one page: `total` is the
-/// pre-pagination count (see [`Page`]), then apply the [`window`] (skip `offset`,
-/// take `limit`).
+/// pre-pagination count (see [`Page`]), then apply the [`window`] (skip
+/// `offset`, take `limit`).
 ///
-/// Callers that push `LIMIT`/`OFFSET` into the store (e.g. SQL `query_postings`)
-/// build their own [`Page`] and skip this; it exists for the backends that hold
-/// the full candidate set in memory.
+/// A caller that pushes `LIMIT`/`OFFSET` into the store (SQL `query_postings`,
+/// for one) builds its own [`Page`] and skips this. It exists for the backends
+/// that hold the full candidate set in memory.
 pub fn paginate<T>(records: Vec<T>, offset: Option<u32>, limit: Option<u32>) -> Page<T> {
     let total = records.len() as u64;
     let (offset, limit) = window(offset, limit);

+ 105 - 100
crates/kuatia-storage/src/store.rs

@@ -1,7 +1,7 @@
-//! Storage abstraction separating the pure decision logic from IO.
+//! The storage abstraction, which holds the pure decision logic apart from IO.
 //!
 //! The [`Store`] trait composes focused sub-traits. Every posting and
-//! account-version write goes through [`CommitStore`], which applies a whole
+//! account-version write goes through [`CommitStore`]. It applies a whole
 //! transfer or a whole transition in one transaction (ADR-0023), so no caller
 //! can leave half of one applied.
 //! - [`AccountStore`]: account creation and version reads
@@ -28,22 +28,22 @@ use crate::events::{EventStore, LedgerEvent};
 pub struct TransferRecord {
     /// The envelope that was committed.
     pub envelope: Envelope,
-    /// The receipt proving commitment.
+    /// The receipt that proves the commit.
     pub receipt: Receipt,
     /// Unix milliseconds when this record was created.
     pub created_at: i64,
 }
 
-/// Pagination and filtering parameters for posting queries.
+/// The page window and the filters a posting query takes.
 #[derive(Debug, Clone)]
 pub struct PostingQuery {
-    /// Filter to postings owned by this base account.
+    /// Keep only the postings this base account owns.
     pub account: i64,
     /// Restrict to one subaccount; `None` spans every subaccount of `account`.
     pub sub: Option<i64>,
-    /// Filter by asset.
+    /// Keep only one asset.
     pub asset: Option<AssetId>,
-    /// Filter by derived lifecycle state.
+    /// Keep only one derived lifecycle state.
     pub filter: PostingFilter,
     /// Max results to return.
     pub limit: Option<u32>,
@@ -51,10 +51,10 @@ pub struct PostingQuery {
     pub offset: Option<u32>,
 }
 
-/// Pagination and filtering parameters for transfer queries.
+/// The page window and the filters a transfer query takes.
 #[derive(Debug, Clone, Default)]
 pub struct TransferQuery {
-    /// Filter to transfers involving this base account.
+    /// Keep only the transfers this base account takes part in.
     pub account: Option<i64>,
     /// Restrict to one subaccount; `None` spans every subaccount of `account`.
     pub sub: Option<i64>,
@@ -62,13 +62,13 @@ pub struct TransferQuery {
     pub from_ts: Option<i64>,
     /// Exclusive upper bound on commit time (unix millis).
     pub to_ts: Option<i64>,
-    /// Inclusive lower bound on the value date. Separate from `from_ts`
-    /// because an entry can be booked in one period and valued in another, and
-    /// a report asks for one or the other, never both at once.
+    /// Inclusive lower bound on the value date. Separate from `from_ts`,
+    /// because an entry can be booked in one period and valued in another. A
+    /// report asks for one or the other, and never both at once.
     pub from_value_date: Option<ValueDate>,
     /// Exclusive upper bound on the value date.
     pub to_value_date: Option<ValueDate>,
-    /// Filter by book.
+    /// Keep only one book.
     pub book: Option<BookId>,
     /// Max results to return.
     pub limit: Option<u32>,
@@ -78,16 +78,16 @@ pub struct TransferQuery {
 
 /// A page of results with total count for pagination.
 ///
-/// The pagination contract every backend implements: `items` is the page cut by
-/// the query's `(offset, limit)` window, and `total` is the count of all matching
-/// rows *ignoring* that window. In-memory backends satisfy it via
-/// [`paginate`](crate::query::paginate); a SQL backend via `LIMIT`/`OFFSET` plus a
-/// separate `COUNT(*)`.
+/// The pagination contract every backend implements. `items` is the page cut by
+/// the `(offset, limit)` window of the query. `total` is the count of every row
+/// that matches, and it takes no account of that window. An in-memory backend
+/// satisfies it through [`paginate`](crate::query::paginate), and a SQL backend
+/// through `LIMIT`/`OFFSET` plus a separate `COUNT(*)`.
 #[derive(Debug, Clone)]
 pub struct Page<T> {
     /// The items in this page (the `(offset, limit)` window).
     pub items: Vec<T>,
-    /// Count of all matching rows, before the page window is applied.
+    /// Count of every row that matches, before the page window applies.
     pub total: u64,
 }
 
@@ -103,10 +103,10 @@ pub trait AccountStore: Send + Sync {
     async fn get_account(&self, id: &AccountId) -> Result<Account, StoreError>;
     /// Fetch multiple accounts by id.
     async fn get_accounts(&self, ids: &[AccountId]) -> Result<Vec<Account>, StoreError>;
-    /// Persist a new account (version 1). A dumb instruction: insert the account
-    /// if absent and return the **number of accounts created** — **1** if this id
-    /// was newly created, **0** if an account with this id already existed. The
-    /// caller decides what `0` means.
+    /// Persist a new account (version 1). A dumb instruction: insert the
+    /// account if absent, and return the **number of accounts created**. That
+    /// is **1** if this id was newly created, and **0** if an account with this
+    /// id was already there. The caller decides what `0` means.
     async fn create_account(&self, account: Account) -> Result<u64, StoreError>;
     /// Return the full version history for an account.
     async fn get_account_history(&self, id: &AccountId) -> Result<Vec<Account>, StoreError>;
@@ -116,20 +116,20 @@ pub trait AccountStore: Send + Sync {
 
 /// Posting reads over an immutable posting table plus an index of the live set.
 ///
-/// A posting is written once and never updated, so [`PostingState`] is derived
-/// from index membership rather than stored: in the index it is spendable, and
-/// out of it (but still in the immutable table) it is spent. Only
+/// A posting is written once and never updated, so [`PostingState`] comes from
+/// index membership and is not stored. In the index it is spendable. Out of the
+/// index, but still in the immutable table, it is spent. Only
 /// [`CommitStore::commit_envelope`] moves a posting between the two.
 #[async_trait]
 pub trait PostingStore: Send + Sync {
-    /// Fetch postings by their ids from the immutable table. Consumed (spent)
-    /// postings still resolve here — immutable rows persist forever.
+    /// Fetch postings by their ids from the immutable table. A consumed (spent)
+    /// posting still resolves here, because an immutable row lives forever.
     async fn get_postings(&self, ids: &[PostingId]) -> Result<Vec<Posting>, StoreError>;
-    /// Return postings owned by a base account, filtered by subaccount, asset,
-    /// and derived lifecycle state (see [`PostingFilter`]). `sub == None` spans
-    /// every subaccount of `id`; `sub == Some(s)` restricts to that one. Results
-    /// are ordered by posting id, so callers and pagination built on top see a
-    /// stable sequence.
+    /// Return postings owned by a base account, cut by subaccount, asset and
+    /// derived lifecycle state (see [`PostingFilter`]). `sub == None` spans
+    /// every subaccount of `id`; `sub == Some(s)` restricts to that one.
+    /// Results are ordered by posting id, so a caller and any pagination on top
+    /// see a stable sequence.
     async fn get_postings_by_account(
         &self,
         id: i64,
@@ -138,23 +138,23 @@ pub trait PostingStore: Send + Sync {
         filter: PostingFilter,
     ) -> Result<Vec<Posting>, StoreError>;
     /// Return the derived [`PostingState`] of each id, aligned to the input
-    /// order. An id absent from the immutable table is `Missing`.
+    /// order. An id that the immutable table does not hold is `Missing`.
     async fn get_posting_states(&self, ids: &[PostingId]) -> Result<Vec<PostingState>, StoreError>;
 
-    /// Sum the live postings of one `(account, asset)` pair: the account's
-    /// balance in that asset.
+    /// Sum the live postings of one `(account, asset)` pair, which is the
+    /// balance of that account in that asset.
     ///
     /// The one place a backend is allowed to add up money itself, and only
-    /// because it can do so exactly (ADR-0024): the SQL store folds native
-    /// amount columns inside the database rather than shipping one row per
-    /// posting to the caller. An overflow is an error, never a wrap.
+    /// because it can do so exactly (ADR-0024). The SQL store folds native
+    /// amount columns inside the database, and sends no row per posting to the
+    /// caller. An overflow is an error, never a wrap.
     async fn live_balance(
         &self,
         account: &AccountId,
         asset: &AssetId,
     ) -> Result<Amount, StoreError>;
 
-    /// Query postings with filtering and pagination.
+    /// Query postings, with the filters and the page window applied.
     async fn query_postings(&self, query: &PostingQuery) -> Result<Page<Posting>, StoreError> {
         // `get_postings_by_account` returns a deterministic id-ordered sequence,
         // so paginating here is stable without an extra sort. A backend that can
@@ -171,23 +171,24 @@ pub trait PostingStore: Send + Sync {
 pub trait TransferStore: Send + Sync {
     /// Fetch a transfer record by its content-addressed id.
     async fn get_transfer(&self, id: &TransferId) -> Result<Option<TransferRecord>, StoreError>;
-    /// Return all transfers involving the given base account. `sub == None`
-    /// spans every subaccount of `id`; `sub == Some(s)` restricts to one.
+    /// Return every transfer the given base account takes part in.
+    /// `sub == None` spans every subaccount of `id`; `sub == Some(s)` restricts
+    /// to one.
     async fn get_transfers_for_account(
         &self,
         id: i64,
         sub: Option<i64>,
     ) -> Result<Vec<TransferRecord>, StoreError>;
 
-    /// Query transfers with filtering and pagination.
+    /// Query transfers, with the filters and the page window applied.
     ///
     /// A backend loads the candidate records, then hands them to
     /// [`filter_transfers`](crate::query::filter_transfers) and
     /// [`paginate`](crate::query::paginate) for the shared time-window/book and
-    /// page cut. There is no default because loading candidates differs by
-    /// backend and, crucially, an `account == None` query must be answered the
-    /// same way everywhere: a store-wide scan, not an error. Every backend does
-    /// exactly that.
+    /// page cut. There is no default, because the load of the candidates
+    /// differs by backend. More to the point, an `account == None` query must
+    /// get the same answer everywhere: a store-wide scan, and not an error.
+    /// Every backend does exactly that.
     async fn query_transfers(
         &self,
         query: &TransferQuery,
@@ -197,17 +198,17 @@ pub trait TransferStore: Send + Sync {
 /// The asset registry: what each [`AssetId`] in a posting means.
 ///
 /// A row is written once and never updated, so a reader can cache one for the
-/// life of the process without going stale.
+/// life of the process and it never goes stale.
 #[async_trait]
 pub trait AssetStore: Send + Sync {
-    /// Register an asset. A dumb instruction: insert it if absent and return
-    /// the **number of assets created**, 1 if newly created and 0 if this id
-    /// was already registered. The caller decides what 0 means.
+    /// Register an asset. A dumb instruction: insert it if absent, and return
+    /// the **number of assets created**. That is 1 if newly created, and 0 if
+    /// this id was already registered. The caller decides what 0 means.
     async fn create_asset(&self, asset: Asset) -> Result<u64, StoreError>;
     /// Fetch one asset by id.
     async fn get_asset(&self, id: &AssetId) -> Result<Asset, StoreError>;
     /// Fetch one asset by its code, which is unique. `None` rather than
-    /// `NotFound`, because the caller asking by code is usually deciding
+    /// `NotFound`, because a caller that asks by code usually wants to know
     /// whether to register it.
     async fn get_asset_by_code(&self, code: &str) -> Result<Option<Asset>, StoreError>;
     /// List every registered asset.
@@ -217,9 +218,10 @@ pub trait AssetStore: Send + Sync {
 /// Book persistence.
 #[async_trait]
 pub trait BookStore: Send + Sync {
-    /// Create a new book. A dumb instruction: insert the book if absent and
-    /// return the **number of books created** — **1** if newly created, **0** if
-    /// a book with this id already existed. The caller decides what `0` means.
+    /// Create a new book. A dumb instruction: insert the book if absent, and
+    /// return the **number of books created**. That is **1** if newly created,
+    /// and **0** if a book with this id was already there. The caller decides
+    /// what `0` means.
     async fn create_book(&self, book: Book) -> Result<u64, StoreError>;
     /// Fetch a book by id.
     async fn get_book(&self, id: &BookId) -> Result<Book, StoreError>;
@@ -227,19 +229,19 @@ pub trait BookStore: Send + Sync {
     async fn list_books(&self) -> Result<Vec<Book>, StoreError>;
 }
 
-/// One append-only cache point (ADR-0019): a balance snapshot for one
-/// `(account, asset)` and the commit-time watermark it covers, tagged with a
-/// monotonic `id`. Cache points are never updated; a read selects the highest
-/// `id`. A disposable, rebuildable accelerator, never the source of truth.
+/// One append-only cache point (ADR-0019). It holds a balance snapshot for one
+/// `(account, asset)`, the commit-time watermark it covers, and a monotonic
+/// `id`. A cache point is never updated, and a read selects the highest `id`. A
+/// disposable, rebuildable accelerator, and never the source of truth.
 #[derive(Debug, Clone, PartialEq, Eq)]
 pub struct BalanceProjection {
     /// Monotonic cache-point id (a store-minted snowflake). Higher means newer.
     pub id: i64,
     /// Account (base id plus subaccount) this cache point is for.
     pub account: AccountId,
-    /// Cached balance, carrying the asset it is in: the sum of every committed
-    /// transfer's delta for this `(account, asset)` with commit time at or
-    /// before `watermark`.
+    /// The cached balance, with the asset it is in. It is the sum of the delta
+    /// of every committed transfer for this `(account, asset)`, with a commit
+    /// time at or before `watermark`.
     pub balance: Amount,
     /// Commit-time cutoff (unix millis) the snapshot covers. A read folds in
     /// committed transfers with a commit time strictly greater than this.
@@ -247,15 +249,15 @@ pub struct BalanceProjection {
 }
 
 /// Append-only balance cache points (ADR-0019). A disposable, rebuildable read
-/// accelerator; the append-only postings stay the source of truth, and this is
-/// never consulted for the validate-time overdraft check. Cache points are only
-/// ever appended (never updated), and a read takes the one closest to (at or
-/// before) the target time, so concurrent appends need no lock.
+/// accelerator. The append-only postings stay the source of truth, and the
+/// validate-time overdraft check never reads this. A cache point is only ever
+/// appended and never updated. A read takes the one closest to the target time,
+/// at or before it, so concurrent appends need no lock.
 #[async_trait]
 pub trait BalanceProjectionStore: Send + Sync {
-    /// Append a new cache point for `(account, asset)`, minting a fresh monotonic
-    /// `id`. A dumb instruction: it inserts one row and never updates an existing
-    /// one.
+    /// Append a new cache point for `(account, asset)`, with a fresh monotonic
+    /// `id`. A dumb instruction: it inserts one row, and it never updates a row
+    /// that is already there.
     async fn append_balance_projection(
         &self,
         account: &AccountId,
@@ -263,12 +265,13 @@ pub trait BalanceProjectionStore: Send + Sync {
         watermark: i64,
     ) -> Result<(), StoreError>;
 
-    /// Fetch the cache point for `(account, asset)` closest to `as_of`: the one
-    /// with the largest `watermark` at or before `as_of` (tie-broken by highest
-    /// `id`). This is the freshest snapshot a read as of `as_of` may use without
-    /// covering transfers committed after `as_of`. Returns `None` if no cache
-    /// point is at or before `as_of`. The caller supplies `as_of` (the store has
-    /// no clock); the ledger passes the current time by default.
+    /// Fetch the cache point for `(account, asset)` closest to `as_of`. That is
+    /// the one with the largest `watermark` at or before `as_of`, tie-broken by
+    /// highest `id`. It is the freshest snapshot a read as of `as_of` can use
+    /// that covers no transfer committed after `as_of`. Returns `None` if no
+    /// cache point is at or before `as_of`. The caller supplies `as_of`,
+    /// because the store has no clock, and the ledger passes the current time
+    /// by default.
     async fn get_closest_balance_projection(
         &self,
         account: &AccountId,
@@ -283,13 +286,13 @@ pub trait BalanceProjectionStore: Send + Sync {
 
 /// Everything one transfer commits, applied in a single store transaction.
 ///
-/// The pure core validates the transfer first; this request carries the
-/// validated effects. The store applies them atomically and re-enforces the
-/// three *stateful* guards inside the transaction (double-spend, freeze/close,
-/// overdraft floor), so a concurrent commit or freeze cannot slip between the
-/// check and the write.
+/// The pure core validates the transfer first, and this request carries the
+/// validated effects. The store applies them atomically. It also re-enforces
+/// the three *stateful* guards inside the transaction: double-spend,
+/// freeze/close and the overdraft floor. So a concurrent commit or freeze
+/// cannot slip between the check and the write.
 pub struct CommitRequest<'a> {
-    /// Content-addressed id of the transfer being committed.
+    /// Content-addressed id of the transfer to commit.
     pub transfer_id: TransferId,
     /// Postings to spend (delete from the live set). Empty for a deposit.
     pub consume: &'a [PostingId],
@@ -297,21 +300,23 @@ pub struct CommitRequest<'a> {
     pub create: &'a [Posting],
     /// The transfer record to persist (envelope + receipt + created_at).
     pub record: TransferRecord,
-    /// Owners of the created and consumed postings: both the transfer's account
-    /// index and the set whose freeze/close/floor the store re-checks.
+    /// Owners of the created and consumed postings. They are both the account
+    /// index of the transfer, and the set whose freeze, close and floor the
+    /// store re-checks.
     pub involved: &'a [AccountId],
     /// The `TransferCommitted` event to append in the same transaction.
     pub event: LedgerEvent,
 }
 
 /// Outcome of an atomic [`CommitStore::commit_envelope`]. A domain rejection is
-/// an `Ok(Rejected(..))` value, not a [`StoreError`]: the store reports a typed
-/// reason and the ledger maps it, keeping `StoreError` IO-only.
+/// an `Ok(Rejected(..))` value, and not a [`StoreError`]. The store reports a
+/// typed reason and the ledger maps it, so `StoreError` stays IO-only.
 #[derive(Debug, Clone, PartialEq, Eq)]
 pub enum CommitOutcome {
     /// The transfer was newly applied in this call.
     Committed(Receipt),
-    /// The transfer id was already present; nothing changed (idempotent replay).
+    /// The transfer id was already present; nothing changed (idempotent
+    /// replay).
     AlreadyCommitted(Receipt),
     /// A stateful guard rejected the commit; nothing was applied.
     Rejected(CommitRejection),
@@ -320,14 +325,14 @@ pub enum CommitOutcome {
 /// Why an atomic commit was refused. Each maps to a typed ledger error.
 #[derive(Debug, Clone, PartialEq, Eq)]
 pub enum CommitRejection {
-    /// A consumed posting was not live (already spent, missing, or taken by a
-    /// concurrent commit). Carries the first offending id.
+    /// A consumed posting was not live: already spent, absent, or taken by a
+    /// concurrent commit. Carries the first id at fault.
     DoubleSpend(PostingId),
     /// An involved account is frozen.
     AccountFrozen(AccountId),
     /// An involved account is closed.
     AccountClosed(AccountId),
-    /// The projected balance of an overdraft-forbidding account would go
+    /// The projected balance of an account that forbids overdraft would go
     /// negative.
     OverdraftExceeded {
         /// The account that would be overdrawn.
@@ -359,7 +364,7 @@ pub enum TransitionRejection {
     VersionConflict {
         /// The account whose version append was rejected.
         account: AccountId,
-        /// The version this attempt targeted.
+        /// The version this call aimed at.
         expected: u64,
     },
 }
@@ -368,20 +373,20 @@ pub enum TransitionRejection {
 /// transition, applied in one store transaction.
 ///
 /// This is what replaces the multi-primitive reserve → finalize saga and its
-/// write-ahead recovery: because each method is all-or-nothing, a crash leaves
-/// no half-applied state to reconcile, and the stateful guards are strict rather
-/// than best-effort (ADR-0023, superseding ADR-0003).
+/// write-ahead recovery. Each method is all-or-nothing, so a crash leaves no
+/// half-applied state to reconcile. The stateful guards are also strict rather
+/// than best-effort (ADR-0023, which supersedes ADR-0003).
 #[async_trait]
 pub trait CommitStore: Send + Sync {
-    /// Commit a validated transfer atomically. Spends `consume`, inserts and
+    /// Commit a validated transfer atomically. It spends `consume`, inserts and
     /// activates `create`, stores the transfer indexed under `involved`, and
-    /// appends `event` — all in one transaction, re-checking double-spend,
-    /// freeze/close, and the overdraft floor inside it.
+    /// appends `event`. All of that is one transaction, which re-checks
+    /// double-spend, freeze/close and the overdraft floor inside itself.
     async fn commit_envelope(&self, req: CommitRequest<'_>) -> Result<CommitOutcome, StoreError>;
 
-    /// Apply one account-version transition atomically: append `next` (a version
-    /// bump with flags flipped) and its lifecycle `event` in one transaction,
-    /// guarding the version chain and a closed account.
+    /// Apply one account-version transition atomically. It appends `next` (a
+    /// version bump with flags flipped) and its lifecycle `event` in one
+    /// transaction. It also guards the version chain and a closed account.
     async fn commit_transition(
         &self,
         next: Account,
@@ -393,7 +398,7 @@ pub trait CommitStore: Send + Sync {
 // Composite trait
 // ---------------------------------------------------------------------------
 
-/// Async storage abstraction composing all sub-traits.
+/// The async storage abstraction, which composes all the sub-traits.
 pub trait Store:
     AccountStore
     + PostingStore

+ 65 - 58
crates/kuatia-storage/src/store_tests.rs

@@ -1,6 +1,7 @@
 //! Generic conformance test suite for [`Store`] implementations.
 //!
-//! Use the [`store_tests!`](crate::store_tests!) macro to generate the full suite for any Store impl.
+//! Use the [`store_tests!`](crate::store_tests!) macro to generate the full
+//! suite for any Store impl.
 //!
 //! ```text
 //! async fn new_store() -> MyStore { MyStore::new() }
@@ -117,13 +118,13 @@ fn make_envelope() -> (Envelope, TransferId) {
             },
         ])
         .build();
-    // Use a fixed TransferId — store tests don't need content-addressing.
+    // Use a fixed TransferId: a store test needs no content address.
     let tid = TransferId([42; 32]);
     (t, tid)
 }
 
-/// Account record for an arbitrary owner, overdraft permitting so a seed can
-/// plant a negative posting without tripping the commit's floor guard.
+/// Account record for an arbitrary owner. It permits overdraft, so a seed can
+/// plant a negative posting and the floor guard of the commit stays quiet.
 fn seed_account(id: AccountId) -> Account {
     Account {
         id,
@@ -134,13 +135,13 @@ fn seed_account(id: AccountId) -> Account {
     }
 }
 
-/// Apply one transfer through `commit_envelope`, the store's only posting write.
-/// Every referenced owner is created first because the commit's freeze/close
-/// guard refuses an unknown account.
+/// Apply one transfer through `commit_envelope`, the store's only posting
+/// write. Every referenced owner is created first because the commit's
+/// freeze/close guard refuses an unknown account.
 ///
-/// Asserts the outcome is `Committed`: a transfer id reused within one test is
-/// an idempotent replay that applies nothing, which would otherwise leave the
-/// test running against an unseeded store.
+/// Asserts the outcome is `Committed`. A transfer id reused within one test is
+/// an idempotent replay that applies nothing. The test would then run against
+/// an unseeded store.
 async fn commit_as(
     store: &(impl Store + 'static),
     tid: TransferId,
@@ -207,7 +208,7 @@ async fn commit_as(
     );
 }
 
-/// Transfer id for a seeding commit, marked so it can never collide with a
+/// Transfer id for a seed commit, marked so it can never collide with a
 /// transfer id a test mints for itself.
 fn seed_tid(marker: u8, tag: u8) -> TransferId {
     let mut bytes = [tag; 32];
@@ -215,11 +216,11 @@ fn seed_tid(marker: u8, tag: u8) -> TransferId {
     TransferId(bytes)
 }
 
-/// Seed `create` as live postings. `tag` distinguishes the seeding transfer, so
-/// two seeds in one test need different tags.
+/// Seed `create` as live postings. `tag` tells one seed transfer from another,
+/// so two seeds in one test need different tags.
 ///
-/// Seeds commit at time zero so they sort before, and stay outside the time
-/// windows of, the transfers a test queries.
+/// A seed commits at time zero. So it sorts before the transfers a test
+/// queries, and it stays outside their time windows.
 pub async fn seed_live(store: &(impl Store + 'static), tag: u8, create: &[Posting]) {
     commit_as(store, seed_tid(0xFE, tag), &[], create, 0, BookId(0)).await;
 }
@@ -235,8 +236,8 @@ pub async fn state_of(store: &(impl Store + 'static), id: PostingId) -> PostingS
     store.get_posting_states(&[id]).await.unwrap()[0]
 }
 
-/// Persist `envelope` as a committed transfer, deriving its created postings the
-/// way the ledger does (`PostingId { transfer: tid, index }`).
+/// Persist `envelope` as a committed transfer, and derive its created postings
+/// the way the ledger does (`PostingId { transfer: tid, index }`).
 async fn commit_record(
     store: &(impl Store + 'static),
     envelope: Envelope,
@@ -353,7 +354,7 @@ pub async fn list_accounts(store: &(impl Store + 'static)) {
 // PostingStore tests
 // ---------------------------------------------------------------------------
 
-/// Committing with empty deactivate creates new postings.
+/// A commit with an empty deactivate creates new postings.
 pub async fn commit_creates_postings(store: &(impl Store + 'static)) {
     let p = make_posting([1; 32], 0, 1, 1, 100);
     seed_live(store, 200, std::slice::from_ref(&p)).await;
@@ -400,7 +401,7 @@ pub async fn get_postings_by_account_filters(store: &(impl Store + 'static)) {
     assert_eq!(active.len(), 2);
 }
 
-/// Postings are segregated by subaccount: reading a base id spans every
+/// Postings are segregated by subaccount. A read of a base id spans every
 /// subaccount, a subaccount filter restricts to one, and no read ever sums
 /// across subaccounts.
 pub async fn get_postings_by_subaccount(store: &(impl Store + 'static)) {
@@ -517,7 +518,7 @@ pub async fn query_postings_pagination(store: &(impl Store + 'static)) {
 }
 
 /// `get_posting_states` reflects live-index membership across every derived
-/// state: active, spent, and missing.
+/// state: active, spent and absent.
 pub async fn get_posting_states_reflect_membership(store: &(impl Store + 'static)) {
     let active = make_posting([9; 32], 0, 1, 1, 100);
     let spent = make_posting([9; 32], 1, 1, 1, 300);
@@ -544,8 +545,8 @@ pub async fn get_posting_states_reflect_membership(store: &(impl Store + 'static
 
 /// `get_posting_states` stays aligned to input order for a larger batch, with
 /// ids interleaved out of insertion order and repeated. This guards the batched
-/// SQL path, which fetches each state table as a set and must reconstruct the
-/// per-id state positionally (duplicates resolve to the same state).
+/// SQL path. That path fetches each state table as a set, and must rebuild the
+/// per-id state by position, where a duplicate resolves to the same state.
 pub async fn get_posting_states_batch_preserves_order(store: &(impl Store + 'static)) {
     let active = make_posting([7; 32], 0, 1, 1, 100);
     let other = make_posting([7; 32], 1, 1, 1, 200);
@@ -588,8 +589,8 @@ pub async fn spent_posting_remains_in_immutable_table(store: &(impl Store + 'sta
     assert_eq!(state_of(store, p.id).await, PostingState::Spent);
 }
 
-/// The `Live` filter returns the balance-bearing postings and excludes spent
-/// ones.
+/// The `Live` filter returns the postings that carry the balance, and excludes
+/// the spent ones.
 pub async fn get_postings_by_account_live_filter(store: &(impl Store + 'static)) {
     let first = make_posting([0xB2; 32], 0, 1, 1, 100);
     let second = make_posting([0xB2; 32], 1, 1, 1, 200);
@@ -606,10 +607,11 @@ pub async fn get_postings_by_account_live_filter(store: &(impl Store + 'static))
     assert_eq!(ids, vec![first.id, second.id]);
 }
 
-/// `live_balance` agrees with summing the same live postings in Rust, and keeps
-/// assets and subaccounts apart. This is the differential check on the backends
-/// that push the sum into the database (ADR-0024): the oracle is the
-/// `get_postings_by_account` + `Cent::checked_sum` path the ledger used before.
+/// `live_balance` agrees with a sum of the same live postings in Rust, and
+/// keeps assets and subaccounts apart. This is the differential check on the
+/// backends that push the sum into the database (ADR-0024). The oracle is the
+/// `get_postings_by_account` plus `Cent::checked_sum` path the ledger used
+/// before.
 pub async fn live_balance_matches_rust_sum(store: &(impl Store + 'static)) {
     let account = AccountId::new(70);
     let asset = AssetId::new(1);
@@ -672,9 +674,9 @@ pub async fn live_balance_matches_rust_sum(store: &(impl Store + 'static)) {
 }
 
 /// A commit indexes its transfer under exactly the `involved` set the caller
-/// supplies and derives participation from nowhere else. Account 7 owns no
-/// posting at all, so the transfer can only be found for it if the backend
-/// trusts `involved`; a backend deriving participation from postings would
+/// supplies, and derives participation from nowhere else. Account 7 owns no
+/// posting at all. So the transfer is found for it only if the backend trusts
+/// `involved`, and a backend that derived participation from the postings would
 /// disagree here.
 pub async fn commit_indexes_involved_accounts(store: &(impl Store + 'static)) {
     let consumed = PostingId {
@@ -722,8 +724,9 @@ pub async fn commit_indexes_involved_accounts(store: &(impl Store + 'static)) {
     assert_eq!(for_created[0].receipt.transfer_id, tid);
 }
 
-/// `append_event` is idempotent on a transfer's dedup key: re-appending the same
-/// `TransferCommitted` returns the existing seq and does not duplicate the row.
+/// `append_event` is idempotent on the dedup key of a transfer. A second append
+/// of the same `TransferCommitted` returns the seq that is already there, and
+/// duplicates no row.
 pub async fn append_event_idempotent(store: &(impl Store + 'static)) {
     let event = LedgerEvent {
         seq: 0,
@@ -738,10 +741,11 @@ pub async fn append_event_idempotent(store: &(impl Store + 'static)) {
     assert_eq!(store.get_events_since(0, 10).await.unwrap().len(), 1);
 }
 
-/// `append_event` is idempotent on a lifecycle transition's `(account, version)`
-/// key: re-appending the same `AccountFrozen` (the crash-recovery replay) returns
-/// the existing seq and does not duplicate the row, while the same account frozen
-/// at a *different* version is a distinct event.
+/// `append_event` is idempotent on the `(account, version)` key of a lifecycle
+/// transition. A second append of the same `AccountFrozen`, which is the
+/// crash-recovery replay, returns the seq that is already there and duplicates
+/// no row. The same account frozen at a *different* version is a distinct
+/// event.
 pub async fn append_event_transition_idempotent(store: &(impl Store + 'static)) {
     let frozen_v2 = LedgerEvent {
         seq: 0,
@@ -983,8 +987,9 @@ pub async fn commit_atomic_creates_and_returns_receipt(store: &(impl Store + 'st
     assert_eq!(store.get_events_since(0, 10).await.unwrap().len(), 1);
 }
 
-/// Committing the same transfer id twice is idempotent: the second call returns
-/// `AlreadyCommitted` and creates no duplicate posting, transfer, or event.
+/// A commit of the same transfer id twice is idempotent. The second call
+/// returns `AlreadyCommitted`, and creates no duplicate posting, transfer or
+/// event.
 pub async fn commit_atomic_idempotent(store: &(impl Store + 'static)) {
     store
         .create_account(make_account(1, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT))
@@ -1084,7 +1089,7 @@ pub async fn commit_atomic_double_spend_rejects_and_applies_nothing(
     assert_eq!(state_of(store, created2.id).await, PostingState::Missing);
 }
 
-/// A commit touching a frozen account is rejected, and nothing is applied.
+/// A commit that touches a frozen account is rejected, and nothing is applied.
 pub async fn commit_atomic_rejects_frozen(store: &(impl Store + 'static)) {
     store
         .create_account(make_account(1, AccountFlags::FROZEN))
@@ -1115,7 +1120,7 @@ pub async fn commit_atomic_rejects_frozen(store: &(impl Store + 'static)) {
     assert_eq!(state_of(store, create.id).await, PostingState::Missing);
 }
 
-/// A commit touching a closed account is rejected, and nothing is applied.
+/// A commit that touches a closed account is rejected, and nothing is applied.
 pub async fn commit_atomic_rejects_closed(store: &(impl Store + 'static)) {
     store
         .create_account(make_account(1, AccountFlags::CLOSED))
@@ -1145,8 +1150,9 @@ pub async fn commit_atomic_rejects_closed(store: &(impl Store + 'static)) {
     assert!(store.get_transfer(&tid).await.unwrap().is_none());
 }
 
-/// The overdraft floor is strict inside the commit: a projected negative balance
-/// on an overdraft-forbidding account is rejected, and nothing is applied.
+/// The overdraft floor is strict inside the commit. A projected negative
+/// balance on an account that forbids overdraft is rejected, and nothing is
+/// applied.
 pub async fn commit_atomic_rejects_overdraft(store: &(impl Store + 'static)) {
     store
         .create_account(make_account(1, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT))
@@ -1209,8 +1215,8 @@ pub async fn commit_transition_applies(store: &(impl Store + 'static)) {
     assert_eq!(store.get_events_since(0, 10).await.unwrap().len(), 1);
 }
 
-/// Replaying an already-applied transition is idempotent: `AlreadyApplied`, no
-/// second version, no duplicate event.
+/// A replay of a transition that is already applied is idempotent. It gives
+/// `AlreadyApplied`, no second version and no duplicate event.
 pub async fn commit_transition_idempotent_replay(store: &(impl Store + 'static)) {
     store
         .create_account(make_account(1, AccountFlags::empty()))
@@ -1422,9 +1428,9 @@ fn make_asset(id: u32, code: &str, decimals: u8) -> Asset {
     Asset::new(AssetId::new(id), code, "$", decimals)
 }
 
-/// An asset for a test that only needs one to exist. The code is derived from
-/// the id because a code is unique (ADR-0030), so a fixed one would collide the
-/// moment a test seeds two assets.
+/// An asset for a test that only needs one to exist. The code comes from the id
+/// because a code is unique (ADR-0030). A fixed one would collide the moment a
+/// test seeds two assets.
 fn seed_asset(id: u32) -> Asset {
     make_asset(id, &format!("T{id}"), 2)
 }
@@ -1437,8 +1443,8 @@ pub async fn create_and_get_asset(store: &(impl Store + 'static)) {
     assert_eq!(got, asset);
 }
 
-/// Registering a known id lands nothing and reports 0, so a caller can tell a
-/// fresh registration from a repeat without reading first.
+/// A register of a known id lands nothing and reports 0. So a caller tells a
+/// fresh registration from a repeat, and reads nothing first.
 pub async fn create_duplicate_asset_reports_zero(store: &(impl Store + 'static)) {
     let asset = make_asset(1, "USD", 2);
     assert_eq!(store.create_asset(asset.clone()).await.unwrap(), 1);
@@ -1459,8 +1465,8 @@ pub async fn get_missing_asset_fails(store: &(impl Store + 'static)) {
     assert!(matches!(err, StoreError::NotFound(_)));
 }
 
-/// A code is unique, so a by-code read finds the one row or none. It returns
-/// an Option rather than NotFound because the caller is usually deciding
+/// A code is unique, so a by-code read finds the one row or none. It returns an
+/// Option rather than NotFound, because the caller usually wants to know
 /// whether to register it.
 pub async fn get_asset_by_code(store: &(impl Store + 'static)) {
     assert!(store.get_asset_by_code("USD").await.unwrap().is_none());
@@ -1549,8 +1555,8 @@ pub async fn balance_projection_absent_is_none(store: &(impl Store + 'static)) {
     assert!(got.is_none());
 }
 
-/// An appended cache point round-trips: value and watermark come back intact and
-/// carry a store-minted id.
+/// An appended cache point round-trips: value and watermark come back intact
+/// and carry a store-minted id.
 pub async fn balance_projection_append_and_get_closest(store: &(impl Store + 'static)) {
     store.create_asset(seed_asset(1)).await.unwrap();
     store
@@ -1568,9 +1574,9 @@ pub async fn balance_projection_append_and_get_closest(store: &(impl Store + 'st
     assert_eq!(got.watermark, 500);
 }
 
-/// Append-only cache points: `get_closest` returns the freshest one at or before
-/// `as_of` (largest watermark), never a cache point covering past `as_of`. Ids
-/// increase across appends.
+/// Append-only cache points. `get_closest` returns the freshest one at or
+/// before `as_of`, which is the largest watermark, and never one that covers
+/// past `as_of`. Ids increase across appends.
 pub async fn balance_projection_closest_at_or_before_as_of(store: &(impl Store + 'static)) {
     let acc = AccountId::new(1);
     let asset = AssetId::new(1);
@@ -1627,7 +1633,8 @@ pub async fn balance_projection_closest_at_or_before_as_of(store: &(impl Store +
 
 /// Generate the full Store conformance test suite.
 ///
-/// `$factory` must be an async fn returning a value that implements [`Store`].
+/// `$factory` must be an async fn that returns a value which implements
+/// [`Store`].
 ///
 /// ```text
 /// async fn new_store() -> InMemoryStore { InMemoryStore::new() }

+ 13 - 13
crates/kuatia-storage/tests/concurrency.rs

@@ -1,9 +1,9 @@
 //! Concurrency tests for `InMemoryStore`.
 //!
 //! The generated conformance suite drives the store through a single `&store`,
-//! so it never exercises two callers racing on the same rows. The atomic commit
-//! is the single-winner claim: of many commits consuming one posting, exactly
-//! one may apply.
+//! so it never puts two callers in a race on the same rows. The atomic commit
+//! is the single-winner claim: of many commits that consume one posting,
+//! exactly one can apply.
 
 #![allow(missing_docs)]
 
@@ -41,10 +41,10 @@ fn account(id: i64) -> Account {
     }
 }
 
-/// The posting every racing commit tries to spend. Its transfer id is marked so
-/// it cannot equal a racing task's own transfer id: a commit that consumed and
-/// re-created the same posting id would leave it spendable again, and a second
-/// task could then legitimately win too.
+/// The posting every commit in the race tries to spend. Its transfer id is
+/// marked, so it cannot equal the own transfer id of a task in that race. A
+/// commit that consumed and re-created the same posting id would leave it
+/// spendable again, and a second task could then win as well.
 fn funded() -> Posting {
     Posting::new(
         PostingId {
@@ -56,9 +56,9 @@ fn funded() -> Posting {
     )
 }
 
-/// Many tasks concurrently commit transfers that all consume the same posting.
-/// The commit's delete is the atomic claim, so exactly one task may apply and
-/// every other must be refused as a double spend.
+/// Many tasks commit transfers at once, and all of them consume the same
+/// posting. The delete inside the commit is the atomic claim, so exactly one
+/// task can apply, and every other must be refused as a double spend.
 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
 async fn concurrent_commits_spend_a_posting_once() {
     const TASKS: u8 = 8;
@@ -125,9 +125,9 @@ async fn concurrent_commits_spend_a_posting_once() {
 }
 
 /// Commits and account transitions race on the same account. Both take the
-/// account guard before any other, so the two atomic writers must not deadlock,
-/// and whichever order they take, the commit either applied before the freeze or
-/// was refused by it: a half-applied state is not reachable.
+/// account guard before any other, so the two atomic writers must not deadlock.
+/// Whichever order they take, the commit either applied before the freeze, or
+/// the freeze refused it. A half-applied state is not reachable.
 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
 async fn concurrent_commit_and_transition_do_not_deadlock() {
     let store = Arc::new(InMemoryStore::new());

+ 31 - 26
crates/kuatia-types/src/account.rs

@@ -7,30 +7,35 @@ use serde::{Deserialize, Serialize};
 bitflags::bitflags! {
     /// Lifecycle and balance-constraint flags for an [`Account`].
     ///
-    /// Bits 0–7 are the system range: bits 0–2 carry lifecycle meaning
-    /// (`FROZEN`, `CLOSED`, `INFLIGHT`), bit 3 is the balance constraint
-    /// (`DEBIT_MUST_NOT_EXCEED_CREDIT`), and bits 4–7
-    /// (`RESERVED_4..RESERVED_7`) are held for future system flags. Bits 8–31
-    /// are the user range (`USER_0..USER_23`), meant to be combined with
+    /// Bits 0 to 7 are the system range. Bits 0 to 2 are the lifecycle
+    /// (`FROZEN`, `CLOSED`, `INFLIGHT`), and bit 3 is the balance constraint
+    /// (`DEBIT_MUST_NOT_EXCEED_CREDIT`). Bits 4 to 7
+    /// (`RESERVED_4..RESERVED_7`) are held for a future system flag.
+    ///
+    /// Bits 8 to 31 are the user range (`USER_0..USER_23`). Combine them with
     /// [`BookPolicy::allowed_flags`](crate::BookPolicy::allowed_flags) to scope
-    /// which accounts may participate in a book.
+    /// which accounts can take part in a book.
     ///
     /// Every bit has a named constant so `from_bits_truncate` never discards a
     /// set bit on the storage read path.
     #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
     pub struct AccountFlags: u32 {
-        /// Account may not be the source or destination of any transfer.
+        /// The account must not be the source or the destination of any
+        /// transfer.
         const FROZEN = 1 << 0;
-        /// Terminal — no further activity.
+        /// Terminal: no activity after this.
         const CLOSED = 1 << 1;
-        /// Holding account for an inflight (authorize/confirm/void) transaction.
-        /// Parks funds between authorize and settlement; closed once drained.
+        /// Holding account for an inflight (authorize, confirm, void)
+        /// transaction. It parks funds between the authorize and the
+        /// settlement, and it is closed once drained.
         const INFLIGHT = 1 << 2;
-        /// The account's debits may never exceed its credits: its balance may
-        /// not go negative and it may not hold a negative posting. When unset
-        /// (the default), the account may overdraw without bound: a shortfall is
-        /// covered by a negative offset posting, and the ledger records the
-        /// transfer as long as it conserves value per asset.
+        /// The debits of the account must never exceed its credits. Its balance
+        /// must not go negative, and it must not hold a negative posting.
+        ///
+        /// When the flag is unset, which is the default, the account can
+        /// overdraw without bound. A negative offset posting covers the
+        /// shortfall, and the ledger records the transfer if it conserves value
+        /// per asset.
         const DEBIT_MUST_NOT_EXCEED_CREDIT = 1 << 3;
         /// Reserved for a future system flag; not for user assignment.
         const RESERVED_4 = 1 << 4;
@@ -96,7 +101,7 @@ bitflags::bitflags! {
 pub struct Account {
     /// Stable identity for this account (base account plus subaccount).
     pub id: AccountId,
-    /// Monotonically increasing version, starts at 1 on creation.
+    /// Version number, one higher on each append, and 1 at creation.
     pub version: u64,
     /// Lifecycle and balance-constraint flags. The balance constraint lives in
     /// [`AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT`].
@@ -108,9 +113,9 @@ pub struct Account {
 }
 
 impl Account {
-    /// Create a version-1 main-subaccount account: no flags, the default book,
-    /// and empty metadata. With no flags the account may overdraw without bound
-    /// (a shortfall becomes a negative offset posting); set
+    /// Create a version-1 main-subaccount account, with no flags, the default
+    /// book and empty metadata. With no flags the account can overdraw without
+    /// bound, and a shortfall becomes a negative offset posting. Set
     /// [`AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT`] to forbid that, or use
     /// [`Account::debit_must_not_exceed_credit`]. Set the other fields
     /// explicitly when you need them.
@@ -118,8 +123,8 @@ impl Account {
         Self::new_ref(id)
     }
 
-    /// Like [`Account::new`] but named for the subaccount-reference case; the
-    /// signature is identical.
+    /// The same as [`Account::new`], named for the subaccount-reference case.
+    /// The signature is identical.
     pub fn new_ref(id: AccountId) -> Self {
         Self {
             id,
@@ -130,8 +135,8 @@ impl Account {
         }
     }
 
-    /// A version-1 account whose debits may never exceed its credits: its
-    /// balance may not go negative and it may not hold a negative posting.
+    /// A version-1 account whose debits must never exceed its credits. Its
+    /// balance must not go negative, and it must not hold a negative posting.
     /// Equivalent to `Account::new(id)` with
     /// [`AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT`] set.
     pub fn debit_must_not_exceed_credit(id: AccountId) -> Self {
@@ -140,9 +145,9 @@ impl Account {
         account
     }
 
-    /// Whether this account forbids overdraft, i.e. carries the
-    /// [`AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT`] flag. When `false` (the
-    /// default) the account may overdraw without bound.
+    /// Whether this account forbids overdraft, which means it carries the
+    /// [`AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT`] flag. When `false`, the
+    /// default, the account can overdraw without bound.
     pub fn forbids_overdraft(&self) -> bool {
         self.flags
             .contains(AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT)

+ 70 - 62
crates/kuatia-types/src/account_code.rs

@@ -2,18 +2,20 @@
 //!
 //! A deep module. The account code is a fixed 20-character string: an
 //! 18-character base-36 body followed by two ISO 7064 mod-97 check digits, with
-//! no country code. It is produced and consumed through a narrow interface of
-//! three methods on [`AccountId`]: [`Display`](fmt::Display) (machine form),
-//! [`FromStr`] (validating parse), and
-//! [`to_grouped`](AccountId::to_grouped) (presentation spacing).
+//! no country code. A narrow interface of three methods on [`AccountId`]
+//! produces and consumes it. [`Display`](fmt::Display) gives the machine form,
+//! [`FromStr`] parses and checks one, and [`to_grouped`](AccountId::to_grouped)
+//! gives the presentation form.
 //!
-//! Everything behind that interface is private: bit-packing the `(id, sub)`
-//! pair, the base-36 rendering, the ISO 7064 mod-97 check digits, and the keyed
-//! Feistel permutation (with cycle-walking) that hides the raw ids. Only the
-//! obfuscation seed controls ([`set_id_seed`], [`id_seed`], [`DEFAULT_ID_SEED`])
-//! and the two bit-width constants ([`ID_BITS`], [`SUB_BITS`]) are exposed
-//! alongside the interface, because callers need them to reason about the
-//! encodable range and to key the deployment's codes.
+//! Everything behind that interface is private. That covers the bit layout of
+//! the `(id, sub)` pair, the base-36 digits and the ISO 7064 mod-97 check
+//! digits. It also covers the keyed Feistel permutation that hides the raw ids,
+//! which cycle-walks.
+//!
+//! Only the obfuscation seed controls ([`set_id_seed`], [`id_seed`],
+//! [`DEFAULT_ID_SEED`]) and the two bit-width constants ([`ID_BITS`],
+//! [`SUB_BITS`]) are exposed beside the interface. A caller needs them to work
+//! out the encodable range, and to key the codes of a deployment.
 
 use crate::AccountId;
 use std::error::Error;
@@ -29,29 +31,30 @@ use std::sync::atomic::{AtomicU64, Ordering};
 /// bit clear, so its value fits in 63 bits.
 pub const ID_BITS: u32 = 63;
 
-/// Bits of the `sub` leg the string form encodes. Together with [`ID_BITS`] this
-/// is the 93-bit packed value the code carries, which fits in the 18 base-36
-/// characters of the code body. A subaccount id must fit in this many bits to
-/// round-trip through the string form.
+/// Bits of the `sub` leg the string form encodes. Together with [`ID_BITS`]
+/// this is the 93-bit packed value the code carries, which fits in the 18
+/// base-36 characters of the code body. A subaccount id must fit in this many
+/// bits to round-trip through the string form.
 pub const SUB_BITS: u32 = 30;
 
 /// Number of base-36 characters in the code body. `36^18 > 2^93`, so the packed
 /// `(id, sub)` value always fits.
 const BODY_LEN: usize = 18;
 
-/// Mask selecting the low [`ID_BITS`] + [`SUB_BITS`] = 93 bits of the packed value.
+/// Mask for the low [`ID_BITS`] + [`SUB_BITS`] = 93 bits of the packed value.
 const PACK_MASK: u128 = (1u128 << (ID_BITS + SUB_BITS)) - 1;
 
-/// Pack `(id, sub)` into the 93-bit value the code encodes: the low [`ID_BITS`]
-/// of `id` in the high part, the low [`SUB_BITS`] of `sub` in the low part.
+/// Pack `(id, sub)` into the 93-bit value the code encodes. The low [`ID_BITS`]
+/// of `id` go in the high part, and the low [`SUB_BITS`] of `sub` in the low
+/// part.
 fn pack(id: i64, sub: i64) -> u128 {
     let id = (id as u128) & ((1u128 << ID_BITS) - 1);
     let sub = (sub as u128) & ((1u128 << SUB_BITS) - 1);
     (id << SUB_BITS) | sub
 }
 
-/// Inverse of [`pack`]: split the 93-bit value back into the two legs. The `id`
-/// part is at most 63 bits, so it is always a non-negative `i64`.
+/// Inverse of [`pack`], which splits the 93-bit value back into the two legs.
+/// The `id` part is at most 63 bits, so it is always a non-negative `i64`.
 fn unpack(p: u128) -> (i64, i64) {
     let sub = (p & ((1u128 << SUB_BITS) - 1)) as i64;
     let id = (p >> SUB_BITS) as i64;
@@ -59,7 +62,7 @@ fn unpack(p: u128) -> (i64, i64) {
 }
 
 /// Encode a value `< 2^93` as exactly [`BODY_LEN`] base-36 digits (`0-9A-Z`),
-/// zero-padded on the left. `36^18 > 2^93`, so this never truncates.
+/// zero-padded on the left. `36^18 > 2^93`, so this truncates nothing.
 fn base36_body(mut v: u128) -> String {
     const D: &[u8; 36] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
     let mut out = [b'0'; BODY_LEN];
@@ -72,8 +75,8 @@ fn base36_body(mut v: u128) -> String {
     out.iter().map(|&b| b as char).collect()
 }
 
-/// Expand an IBAN string to its numeric form for the checksum: digits stay,
-/// letters `A-Z` become `10..35`.
+/// Expand an IBAN string to the numeric form the checksum takes. A digit stays,
+/// and a letter `A-Z` becomes `10..35`.
 fn iban_expand(s: &str) -> String {
     let mut out = String::with_capacity(s.len() * 2);
     for c in s.bytes() {
@@ -97,8 +100,8 @@ fn mod97(digits: &str) -> u32 {
     rem
 }
 
-/// The two mod-97 check digits for a base-36 body, IBAN-style but with no
-/// country code: `98 - (expand(body ++ "00") mod 97)`.
+/// The two mod-97 check digits for a base-36 body, IBAN-style with no country
+/// code: `98 - (expand(body ++ "00") mod 97)`.
 fn check_digits(body: &str) -> u32 {
     98 - mod97(&iban_expand(&format!("{body}00")))
 }
@@ -124,12 +127,12 @@ fn check_digits(body: &str) -> u32 {
 /// startup with [`set_id_seed`], before any code is issued or parsed.
 pub const DEFAULT_ID_SEED: u64 = 0x9E37_79B9_7F4A_7C15;
 
-/// Process-global seed keying the account-code permutation.
+/// The process-global seed that keys the account-code permutation.
 static ID_SEED: AtomicU64 = AtomicU64::new(DEFAULT_ID_SEED);
 
-/// Set the process-global seed that keys the account-code obfuscation. Call once
-/// at startup: every [`AccountId`] string form depends on it, so changing it
-/// after codes are issued invalidates the previously issued ones.
+/// Set the process-global seed that keys the account-code obfuscation. Call it
+/// once at startup. Every [`AccountId`] string form depends on it, so a new
+/// seed invalidates every code already issued.
 pub fn set_id_seed(seed: u64) {
     ID_SEED.store(seed, Ordering::Relaxed);
 }
@@ -141,7 +144,7 @@ pub fn id_seed() -> u64 {
 
 /// Number of Feistel rounds. Four rounds of a strong round function give a
 /// strong pseudo-random permutation (Luby-Rackoff), which is ample for
-/// obfuscation.
+/// obfuscation alone.
 const FEISTEL_ROUNDS: usize = 4;
 
 /// SplitMix64 finalizer: a strong 64-bit avalanche mixer.
@@ -156,17 +159,18 @@ fn round_key(seed: u64, round: usize) -> u64 {
     mix64(seed ^ (round as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15))
 }
 
-/// Bits per Feistel half. Two halves give a 94-bit block, the smallest even
-/// width that covers the 93-bit packed domain (one bit of headroom that
-/// cycle-walking absorbs).
+/// Bits per Feistel half. Two halves give a 94-bit block, which is the smallest
+/// even width that covers the 93-bit packed domain. The cycle-walk absorbs the
+/// one bit of headroom.
 const FEISTEL_HALF_BITS: u32 = 47;
 
-/// Mask selecting one [`FEISTEL_HALF_BITS`]-wide half.
+/// Mask for one [`FEISTEL_HALF_BITS`]-wide half.
 const FEISTEL_HALF_MASK: u128 = (1u128 << FEISTEL_HALF_BITS) - 1;
 
-/// Keyed Feistel permutation over the 94-bit block `(l, r)` (two 47-bit halves).
-/// A balanced Feistel with any round function is a bijection on the full 2^94
-/// space, which is what [`obfuscate`] cycle-walks down to the 93-bit domain.
+/// Keyed Feistel permutation over the 94-bit block `(l, r)`, which is two
+/// 47-bit halves. A balanced Feistel with any round function is a bijection on
+/// the full 2^94 space, and [`obfuscate`] cycle-walks that down to the 93-bit
+/// domain.
 fn feistel94(block: u128, seed: u64) -> u128 {
     let mut l = (block >> FEISTEL_HALF_BITS) & FEISTEL_HALF_MASK;
     let mut r = block & FEISTEL_HALF_MASK;
@@ -192,10 +196,11 @@ fn feistel94_inv(block: u128, seed: u64) -> u128 {
     (l << FEISTEL_HALF_BITS) | r
 }
 
-/// Keyed format-preserving permutation over the 93-bit packed domain. Applies
-/// [`feistel94`] and cycle-walks (re-encrypts while the result exceeds the
-/// domain) so the output is always a valid packed value. Since the domain is
-/// half of 2^94, this averages about two iterations and always terminates.
+/// Keyed format-preserving permutation over the 93-bit packed domain. It
+/// applies [`feistel94`] and cycle-walks, which means it encrypts again while
+/// the result is past the domain. So the output is always a valid packed value.
+/// The domain is half of 2^94, so this takes about two iterations on average,
+/// and it always terminates.
 fn obfuscate(p: u128, seed: u64) -> u128 {
     let mut v = p;
     loop {
@@ -206,7 +211,8 @@ fn obfuscate(p: u128, seed: u64) -> u128 {
     }
 }
 
-/// Inverse of [`obfuscate`] under the same seed: cycle-walk [`feistel94_inv`].
+/// Inverse of [`obfuscate`] under the same seed, which cycle-walks
+/// [`feistel94_inv`].
 fn deobfuscate(y: u128, seed: u64) -> u128 {
     let mut v = y;
     loop {
@@ -222,13 +228,13 @@ fn deobfuscate(y: u128, seed: u64) -> u128 {
 // ---------------------------------------------------------------------------
 
 impl fmt::Display for AccountId {
-    /// IBAN-style machine format: a fixed 20 characters, an 18-character base-36
-    /// body followed by two trailing ISO 7064 mod-97 check digits, with no
-    /// country code. The `(id, sub)` pair is packed into a 93-bit value and run
-    /// through a keyed format-preserving permutation (see [`set_id_seed`]) before
-    /// encoding, so the body does not reveal the raw ids. Round-trips via
-    /// [`FromStr`]; [`to_grouped`](AccountId::to_grouped) adds
-    /// the presentation spacing (five groups of four).
+    /// IBAN-style machine format: a fixed 20 characters, an 18-character
+    /// base-36 body, then two ISO 7064 mod-97 check digits, with no country
+    /// code. The `(id, sub)` pair is packed into a 93-bit value, then run
+    /// through a keyed format-preserving permutation (see [`set_id_seed`]). So
+    /// the body does not reveal the raw ids. Round-trips through [`FromStr`],
+    /// and [`to_grouped`](AccountId::to_grouped) adds the presentation form of
+    /// five groups of four.
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         let body = base36_body(obfuscate(pack(self.id, self.sub), id_seed()));
         write!(f, "{body}{:02}", check_digits(&body))
@@ -237,9 +243,9 @@ impl fmt::Display for AccountId {
 
 impl AccountId {
     /// IBAN-style presentation format: the machine [`Display`](fmt::Display)
-    /// form grouped into blocks of four with a single space. The code is a fixed
-    /// 20 characters, so this is always five groups of four
-    /// (e.g. `K3P9 WM2X Q7ND V8HT 2R47`).
+    /// form grouped into blocks of four with a single space. The code is a
+    /// fixed 20 characters, so this is always five groups of four (e.g.
+    /// `K3P9 WM2X Q7ND V8HT 2R47`).
     pub fn to_grouped(&self) -> String {
         let machine = self.to_string();
         let mut out = String::with_capacity(machine.len() + machine.len() / 4);
@@ -253,8 +259,8 @@ impl AccountId {
     }
 }
 
-/// Returned when a string is not a valid [`AccountId`] code: wrong structure,
-/// non-base-36 body, or a failed mod-97 checksum.
+/// Returned when a string is not a valid [`AccountId`] code. The structure is
+/// wrong, the body is not base-36, or the mod-97 checksum failed.
 #[derive(Debug, Clone, PartialEq, Eq)]
 pub struct ParseAccountIdError;
 
@@ -269,14 +275,16 @@ impl Error for ParseAccountIdError {}
 impl FromStr for AccountId {
     type Err = ParseAccountIdError;
 
-    /// Parse an IBAN-style account code back into the two legs. Any spaces
-    /// (grouped display format) and dashes (URL-safe separator) are ignored and
-    /// the input is upper-cased first, so `K3P9...`, `K3P9 WM2X ...`, and
-    /// `K3P9-WM2X-...` all parse to the same id. The value must reduce to an
-    /// 18-character base-36 body followed by two check digits, the ISO 7064
-    /// mod-97 checksum must pass, and the decoded body must lie in the packable
-    /// domain — so a mistyped or otherwise invalid id is rejected here rather
-    /// than reaching the store.
+    /// Parse an IBAN-style account code back into the two legs. A space, from
+    /// the grouped display form, and a dash, from the URL-safe separator, are
+    /// both ignored, and the input is upper-cased first. So `K3P9...`,
+    /// `K3P9 WM2X ...` and `K3P9-WM2X-...` all parse to the same id.
+    ///
+    /// Three conditions must hold. The value must reduce to an 18-character
+    /// base-36 body followed by two check digits. The ISO 7064 mod-97 checksum
+    /// must pass. The decoded body must lie in the packable domain. So a
+    /// mistyped or otherwise invalid id is rejected here, and never gets to the
+    /// store.
     fn from_str(s: &str) -> Result<Self, Self::Err> {
         let cleaned: String = s
             .chars()

+ 37 - 33
crates/kuatia-types/src/amount.rs

@@ -14,10 +14,10 @@ use kuatia_money::{Cent, OverflowError, ParseDecimalError};
 
 /// A quantity of one asset.
 ///
-/// A bare [`Cent`] adds to and compares with any other, so nothing stopped a
-/// caller holding two balances from summing dollars into euros. Carrying the
-/// asset makes that a rejected operation instead of a wrong number, and gives
-/// a decimal string somewhere to learn its precision from.
+/// A bare [`Cent`] adds to and compares with any other. So nothing stopped a
+/// caller with two balances from an addition of dollars into euros. The asset travels
+/// with the value, which makes that a rejected operation instead of a wrong
+/// number. It also gives a decimal string a source for its precision.
 ///
 /// Built only through conversion, so an amount cannot exist without a
 /// registered asset behind it. The value comes first and the asset second, the
@@ -31,7 +31,8 @@ pub struct Amount {
 }
 
 impl Amount {
-    /// Nothing, of one asset. The identity for [`checked_add`](Self::checked_add).
+    /// Nothing, of one asset. The identity for
+    /// [`checked_add`](Self::checked_add).
     pub fn zero(asset: Arc<Asset>) -> Self {
         Self {
             asset,
@@ -64,8 +65,8 @@ impl Amount {
         self.value.is_positive()
     }
 
-    /// True when the quantity is below zero, which an account permitting
-    /// overdraft may hold.
+    /// True when the quantity is below zero, which an account that permits
+    /// overdraft can hold.
     pub fn is_negative(&self) -> bool {
         self.value.is_negative()
     }
@@ -94,7 +95,7 @@ impl Amount {
         })
     }
 
-    /// Negate, keeping the asset.
+    /// Negate the value, and keep the asset.
     pub fn checked_neg(&self) -> Result<Self, AmountError> {
         Ok(Self {
             asset: Arc::clone(&self.asset),
@@ -127,8 +128,8 @@ impl Amount {
 }
 
 /// Equality is by asset id and value. Two reads of the same asset are the same
-/// asset, so comparing the registry metadata would make equality depend on when
-/// each side was loaded.
+/// asset. A comparison of the registry metadata would make equality depend on
+/// when each side was loaded.
 impl PartialEq for Amount {
     fn eq(&self, other: &Self) -> bool {
         self.asset.id == other.asset.id && self.value == other.value
@@ -143,9 +144,9 @@ impl fmt::Debug for Amount {
     }
 }
 
-/// Formats at the asset's own scale and names it by code, so an amount cannot
-/// be printed at the wrong precision. Grouping separators are a locale
-/// decision and stay with the caller.
+/// Formats at the own scale of the asset and names it by code, so an amount
+/// cannot be printed at the wrong precision. A thousands separator is a locale
+/// decision, and it stays with the caller.
 impl fmt::Display for Amount {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         write!(
@@ -161,9 +162,9 @@ impl fmt::Display for Amount {
 /// read back needs no registry to be whole again (ADR-0029). That is what makes
 /// a stored posting self-describing and its decode infallible.
 ///
-/// The content address is the exception: it hashes the asset's id and the value
-/// alone, so a transfer's identity does not move when a code or a symbol is
-/// written differently.
+/// The content address is the exception. It hashes the id of the asset and the
+/// value alone. So the identity of a transfer does not move when a code or a
+/// symbol is written differently.
 #[derive(Serialize, Deserialize)]
 #[serde(rename = "Amount")]
 struct AmountWire {
@@ -249,18 +250,20 @@ impl From<Infallible> for AmountError {
     }
 }
 
-/// Build an amount of an asset from the asset's side: `usd.amount("100.00")?`,
-/// for a caller holding the asset rather than assembling a tuple.
+/// Build an amount of an asset from the side of the asset:
+/// `usd.amount("100.00")?`. It is for a caller that holds the asset and does
+/// not want to assemble a tuple.
 ///
 /// Implemented for both [`Asset`] and `Arc<Asset>`, so it works on whatever a
-/// caller has: a handle from [`Ledger::asset`](../../kuatia/ledger/struct.Ledger.html)
-/// or a row from a listing. The `Arc` receiver shares the one row; the `Asset`
-/// one clones it, which costs the two strings and nothing in identity, since an
+/// caller has: a handle from
+/// [`Ledger::asset`](../../kuatia/ledger/struct.Ledger.html), or a row the
+/// registry listed. The `Arc` receiver shares the one row. The `Asset` one
+/// clones it, which costs the two strings and nothing in identity, because an
 /// amount compares by asset id.
 ///
 /// This is a trait, so it has to be in scope. `kuatia::prelude::*` and
-/// `kuatia_core::*` both bring it. Not named `new`, which would read as
-/// constructing an [`Asset`].
+/// `kuatia_core::*` both bring it. Not named `new`, which would read as the
+/// construction of an [`Asset`].
 pub trait Denominate {
     /// An amount of this asset, in whichever form the value is already in.
     fn amount<V>(&self, value: V) -> Result<Amount, AmountError>
@@ -301,9 +304,9 @@ impl From<(Cent, &Arc<Asset>)> for Amount {
     }
 }
 
-/// The value comes first, the way the money reads aloud: `("50.00", usd)`.
-/// Each conversion comes in two shapes, one taking the asset handle and one
-/// taking a reference to it, so a caller passing the same asset to several
+/// The value comes first, the way the money reads aloud: `("50.00", usd)`. Each
+/// conversion comes in two shapes. One takes the asset handle and the other
+/// takes a reference to it. So a caller that passes the same asset to several
 /// movements does not clone it at every call.
 macro_rules! amount_conversions {
     (infallible $($value:ty),+) => {
@@ -493,8 +496,8 @@ mod tests {
         );
     }
 
-    /// A reference reaches the same conversions, so a caller passing one asset
-    /// to several movements does not clone the handle at every call.
+    /// A reference reaches the same conversions, so a caller that passes one
+    /// asset to several movements does not clone the handle at every call.
     #[test]
     fn a_reference_to_the_asset_converts_too() {
         let usd = usd();
@@ -508,9 +511,10 @@ mod tests {
         );
     }
 
-    /// `usd.amount(..)` is the same conversion from the other side, for a caller
-    /// holding the asset rather than building a tuple. It reads the same whether
-    /// the caller holds the shared handle or a row of its own.
+    /// `usd.amount(..)` is the same conversion from the other side, for a
+    /// caller that holds the asset and does not want to build a tuple. It reads
+    /// the same whether that caller holds the shared handle or a row of its
+    /// own.
     #[test]
     fn denominate_builds_from_the_asset() {
         let usd = usd();
@@ -529,8 +533,8 @@ mod tests {
         assert_eq!(row.amount(500).unwrap(), Amount::from((500, &usd)));
     }
 
-    /// A fraction shorter than the asset's scale is padded, not rejected: a
-    /// two-decimal asset reads "100.0" as ten thousand minor units.
+    /// A fraction shorter than the scale of the asset is padded and not
+    /// rejected. A two-decimal asset reads "100.0" as ten thousand minor units.
     #[test]
     fn a_short_fraction_pads_to_the_scale() {
         assert_eq!(usd().amount("100.0").unwrap().minor_units(), 10_000);

+ 9 - 8
crates/kuatia-types/src/asset.rs

@@ -11,8 +11,8 @@ use kuatia_money::Scale;
 /// A registered unit of value. Conservation is enforced per asset, so this
 /// names a conservation boundary (ADR-0001) and not merely a label.
 ///
-/// A row is immutable once created. Editing the precision would reinterpret
-/// every amount already recorded against it, since what is stored is minor
+/// A row is immutable once created. An edit to the precision would reinterpret
+/// every amount already recorded against it, because what is stored is minor
 /// units and nothing else.
 #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
 pub struct Asset {
@@ -24,7 +24,8 @@ pub struct Asset {
     /// Symbol for presentation, such as `$`. Never parsed.
     pub symbol: String,
     /// Decimal places between the amount a person writes and the minor units
-    /// stored: 2 for a cent currency, 8 for satoshis, 0 for a countable good.
+    /// stored. It is 2 for a cent currency, 8 for satoshis, and 0 for a
+    /// countable good.
     pub decimals: u8,
 }
 
@@ -44,9 +45,9 @@ impl Asset {
         }
     }
 
-    /// The scale this asset's amounts are written at, for parsing a decimal
-    /// string or formatting one. Crate-internal: an amount parses and formats
-    /// itself, and nothing public hands out a `Scale` (ADR-0029).
+    /// The scale the amounts of this asset are written at, which a decimal
+    /// string parses and formats against. Crate-internal: an amount parses and
+    /// formats itself, and nothing public hands out a `Scale` (ADR-0029).
     pub(crate) fn scale(&self) -> Scale {
         Scale::new(self.decimals)
     }
@@ -54,8 +55,8 @@ impl Asset {
 
 /// An asset names itself, so anything that takes an `impl Into<AssetId>`
 /// accepts the registry row or the shared handle as readily as the id. The
-/// `&AssetId` impl is what keeps a caller that already had the id writing it
-/// the same way.
+/// `&AssetId` impl is what lets a caller that already holds the id write it the
+/// same way as before.
 impl From<&AssetId> for AssetId {
     fn from(id: &AssetId) -> Self {
         *id

+ 16 - 15
crates/kuatia-types/src/autoid.rs

@@ -1,6 +1,6 @@
-//! Auto ID generator — snowflake-inspired i64 ID scheme.
+//! The auto id generator: a snowflake-inspired i64 id scheme.
 //!
-//! Inspired by Twitter's Snowflake ID format (2010), adapted for
+//! Based on the Snowflake id format of Twitter (2010), adapted for
 //! single-process embedded use with CRC32-based disambiguation.
 //!
 //! Bit layout:
@@ -10,15 +10,16 @@
 //! ```
 //!
 //! - Bit 63: always 0 (keeps i64 positive)
-//! - Bits 62–23: milliseconds since [`KUATIA_EPOCH_MS`] (40 bits ≈ 34.8 years)
-//! - Bits 22–0: lower 23 bits of CRC32 of context data, or an internal
-//!   counter that wraps on overflow when no data is provided.
+//! - Bits 62-23: milliseconds since [`KUATIA_EPOCH_MS`] (40 bits is about 34.8
+//!   years)
+//! - Bits 22-0: lower 23 bits of CRC32 of context data, or an internal counter
+//!   that wraps on overflow when no data is provided.
 //!
-//! The millisecond field counts from a fixed recent epoch
-//! ([`KUATIA_EPOCH_MS`] = 2026-01-01T00:00:00Z) rather than the Unix epoch, so
-//! the 40-bit window gives ~34.8 years of range *going forward* (until ~2060)
-//! instead of a window already partly elapsed since 1970. Collision resistance
-//! within a millisecond comes from the CRC32 tail (for content-keyed ids).
+//! The millisecond field counts from a fixed recent epoch, which is
+//! [`KUATIA_EPOCH_MS`] = 2026-01-01T00:00:00Z, and not from the Unix epoch. So
+//! the 40-bit window gives about 34.8 years of range *ahead*, until about 2060.
+//! A window from 1970 would already be partly spent. Resistance to a collision
+//! inside one millisecond comes from the CRC32 tail, for a content-keyed id.
 
 use std::sync::atomic::{AtomicU32, Ordering};
 use std::time::{SystemTime, UNIX_EPOCH};
@@ -40,24 +41,24 @@ pub struct AutoId {
 }
 
 impl AutoId {
-    /// Create a new generator with counter starting at zero.
+    /// Create a new generator whose counter starts at zero.
     ///
-    /// `const` so a single generator can back a process-global `static`, giving
-    /// ids that are unique across threads rather than per-thread.
+    /// `const`, so a single generator can back a process-global `static`. The
+    /// ids are then unique across threads, and not per thread.
     pub const fn new() -> Self {
         Self {
             counter: AtomicU32::new(0),
         }
     }
 
-    /// Generate an ID using the lower 23 bits of CRC32 of `data`.
+    /// Generate an id from the lower 23 bits of CRC32 of `data`.
     pub fn next_with_data(&self, data: &[u8]) -> i64 {
         let ms = Self::now_ms();
         let crc = crc32(data);
         Self::pack(ms, crc & TAIL_MASK)
     }
 
-    /// Generate an ID using the internal auto-incrementing counter.
+    /// Generate an id from the internal counter, which steps by one each time.
     /// The counter wraps to zero on overflow of the 23-bit range.
     pub fn next(&self) -> i64 {
         let ms = Self::now_ms();

+ 18 - 13
crates/kuatia-types/src/book.rs

@@ -1,15 +1,18 @@
-//! [`Book`] — the transfer-policy scope gating account and asset participation.
+//! [`Book`]: the transfer-policy scope that gates which accounts and assets
+//! take part.
 
 use crate::account::AccountFlags;
 use crate::ids::{AccountId, AssetId, BookId};
 use serde::{Deserialize, Serialize};
 
-/// A Book is a transfer policy scope: it gates which accounts and assets may
-/// participate in a transfer. It is not the chronological entry log (the
-/// transfer log plays that role), it does not partition balances, and it is not
-/// a tenancy boundary: balances are global, no read is restricted by book, and a
-/// transfer naming [`DEFAULT_BOOK`](crate::DEFAULT_BOOK) with no such book
-/// stored commits with no policy applied.
+/// A Book is a transfer policy scope. It gates which accounts and assets can
+/// take part in a transfer.
+///
+/// It is not the chronological entry log, because the transfer log plays that
+/// role. It does not partition balances, and it is not a tenancy boundary.
+/// Balances are global, and no book restricts a read. A transfer that names
+/// [`DEFAULT_BOOK`](crate::DEFAULT_BOOK) with no such book stored commits with
+/// no policy applied.
 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 pub struct Book {
     /// Stable identity for this book.
@@ -20,18 +23,19 @@ pub struct Book {
     pub policy: BookPolicy,
 }
 
-/// The participation rules for a [`Book`]. An empty field means "no restriction".
+/// The rules a [`Book`] applies. An empty field means "no restriction".
 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 pub struct BookPolicy {
-    /// If non-empty, only these assets may appear in movements.
+    /// If non-empty, these assets alone can appear in a movement.
     pub allowed_assets: Vec<AssetId>,
-    /// If non-empty, accounts with ANY of these flags may participate.
+    /// If non-empty, an account with ANY of these flags can take part.
     pub allowed_flags: AccountFlags,
-    /// If non-empty, these specific accounts may participate (in addition to flag matches).
+    /// If non-empty, these specific accounts can take part, on top of the ones
+    /// the flags admit.
     pub allowed_accounts: Vec<AccountId>,
 }
 
-/// Builder for constructing [`Book`] values.
+/// The builder that assembles a [`Book`].
 pub struct BookBuilder {
     book: Book,
 }
@@ -64,7 +68,8 @@ impl BookBuilder {
         self
     }
 
-    /// Set allowed account flags — accounts with ANY of these flags may participate.
+    /// Set the allowed account flags. An account with ANY of them can take
+    /// part.
     pub fn allow_flags(mut self, flags: AccountFlags) -> Self {
         self.book.policy.allowed_flags = flags;
         self

+ 20 - 18
crates/kuatia-types/src/canonical.rs

@@ -1,16 +1,19 @@
-//! Canonical binary serialization — the content-addressing contract.
+//! Canonical binary serialization: the contract behind the content address.
 //!
 //! Everything that defines the hash preimage lives here in one place: the
 //! [`ToBytes`] trait, the [`CANONICAL_VERSION`] byte, the big-endian write
 //! helpers, and every `impl ToBytes`. [`TransferId`](crate::TransferId) and the
 //! account snapshot hashes are the double-SHA256 of these bytes, so a change to
-//! any impl below changes those ids. Keeping the trait, the version, and all the
-//! impls together makes the preimage auditable at a glance: what bytes are
-//! hashed, in what order, is visible without holding three windows open.
+//! any impl below changes those ids.
+//!
+//! The trait, the version and all the impls sit together, so one read audits
+//! the preimage. Which bytes are hashed, and in what order, is visible in one
+//! file.
 //!
 //! Encoding rules: integers are big-endian, variable-length sequences are
-//! prefixed with a `u32` length, and the top-level [`Envelope`](crate::Envelope)
-//! and [`Account`](crate::Account) preimages begin with [`CANONICAL_VERSION`].
+//! prefixed with a `u32` length, and the top-level
+//! [`Envelope`](crate::Envelope) and [`Account`](crate::Account) preimages
+//! begin with [`CANONICAL_VERSION`].
 
 use crate::internals;
 use crate::{
@@ -19,23 +22,22 @@ use crate::{
 };
 use kuatia_money::Cent;
 
-/// Deterministic binary serialization. Every domain type can produce its
-/// canonical byte representation.
+/// Deterministic binary serialization. Every domain type can produce its own
+/// canonical bytes.
 pub trait ToBytes {
-    /// Returns the canonical byte representation of this value.
+    /// Returns the canonical bytes of this value.
     fn to_bytes(&self) -> Vec<u8>;
 }
 
-/// Version byte prepended to canonical serializations for forward compatibility.
-/// Bumped to 2 when `Cent` moved to a fixed 16-byte canonical encoding (ADR-0011).
-/// Bumped to 3 when `AccountId` gained a `subaccount` leg folded into its
-/// canonical bytes (ADR-0012).
-/// Bumped to 4 when the vestigial `UserData` fields were removed from the
-/// `Envelope` and `Account` preimages.
+/// Version byte at the front of every canonical serialization, for forward
+/// compatibility. Bumped to 2 when `Cent` moved to a fixed 16-byte canonical
+/// encoding (ADR-0011). Bumped to 3 when `AccountId` gained a `subaccount` leg
+/// folded into its canonical bytes (ADR-0012). Bumped to 4 when the vestigial
+/// `UserData` fields were removed from the `Envelope` and `Account` preimages.
 /// Bumped to 5 when the `policy` field was removed from the `Account` preimage
-/// (ADR-0018): the single balance constraint now lives in `flags`.
-/// Bumped to 6 when the `Envelope` preimage gained `value_date` (ADR-0027), so
-/// two entries that differ only in the day they take effect are two transfers.
+/// (ADR-0018): the single balance constraint now lives in `flags`. Bumped to 6
+/// when the `Envelope` preimage gained `value_date` (ADR-0027), so two entries
+/// that differ only in the day they take effect are two transfers.
 pub const CANONICAL_VERSION: u8 = 6;
 
 /// Append a `u16` in big-endian to `buf`.

+ 6 - 5
crates/kuatia-types/src/envelope.rs

@@ -1,4 +1,5 @@
-//! The [`Envelope`]: the atomic unit a [`Transfer`](crate::Transfer) resolves into.
+//! The [`Envelope`]: the atomic unit a [`Transfer`](crate::Transfer) resolves
+//! into.
 
 use crate::ids::{AccountId, AccountSnapshotId, BookId, PostingId};
 use crate::posting::NewPosting;
@@ -60,9 +61,9 @@ impl Envelope {
         &self.metadata
     }
 
-    /// The caller's reference for this entry, under the reserved
-    /// [`REFERENCE_KEY`](crate::REFERENCE_KEY). Bytes rather than a string: a
-    /// caller writing the map directly is not held to the UTF-8 that
+    /// The reference the caller gave this entry, under the reserved
+    /// [`REFERENCE_KEY`](crate::REFERENCE_KEY). Bytes and not a string, because
+    /// a caller that writes the map directly is not held to the UTF-8 that
     /// [`TransferBuilder::reference`](crate::TransferBuilder::reference)
     /// writes.
     pub fn reference(&self) -> Option<&[u8]> {
@@ -83,7 +84,7 @@ impl Envelope {
     }
 }
 
-/// Builder for constructing [`Envelope`] values.
+/// The builder that assembles an [`Envelope`].
 #[derive(Default)]
 pub struct EnvelopeBuilder {
     envelope: Envelope,

+ 26 - 25
crates/kuatia-types/src/ids.rs

@@ -18,12 +18,13 @@ use std::fmt;
 /// subaccount of the same base id. Each `(id, sub)` is a full account record
 /// with its own flags and lifecycle. See ADR-0012 and ADR-0015.
 ///
-/// Both legs are stored as `i64` (they hash and persist as full `i64`), but the
-/// IBAN-style string form ([`Display`](fmt::Display) / [`FromStr`](std::str::FromStr))
-/// encodes only the low `ID_BITS` of `id` (a 63-bit snowflake never sets the
-/// sign bit) and the low `SUB_BITS` of `sub`. That is what lets the code fit in
-/// a fixed 20 characters. Values outside those ranges still hash, persist, and
-/// compare correctly, but do not round-trip through the string form.
+/// Both legs are stored as `i64`, and they hash and persist as a full `i64`.
+/// The IBAN-style string form ([`Display`](fmt::Display) /
+/// [`FromStr`](std::str::FromStr)) encodes the low `ID_BITS` of `id` and the
+/// low `SUB_BITS` of `sub` alone. A 63-bit snowflake never sets the sign bit.
+/// That is what lets the code fit in a fixed 20 characters. A value outside
+/// those ranges still hashes, persists and compares correctly, and it does not
+/// round-trip through the string form.
 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
 pub struct AccountId {
     /// Base account id (a 63-bit snowflake; the sign bit is always 0).
@@ -34,15 +35,15 @@ pub struct AccountId {
     pub sub: i64,
 }
 
-/// Pairs an [`AccountId`] with a snapshot hash — the double-SHA256 of the
-/// account's state at a point in time. Stored on [`Transfer`](crate::Transfer)
-/// to record which account versions a transfer was executed against. Internal
-/// type — the public API uses [`AccountId`].
+/// Pairs an [`AccountId`] with a snapshot hash, which is the double-SHA256 of
+/// the state of that account at a point in time. Stored on
+/// [`Transfer`](crate::Transfer), to record the account versions a transfer ran
+/// against. An internal type: the public API uses [`AccountId`].
 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 pub struct AccountSnapshotId {
     /// The account (subaccount) this snapshot belongs to.
     pub account: AccountId,
-    /// Double-SHA256 of the account's state at the time of the snapshot.
+    /// Double-SHA256 of the state of the account when the snapshot was taken.
     pub snapshot_id: [u8; 32],
 }
 
@@ -51,24 +52,24 @@ pub struct AccountSnapshotId {
 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
 pub struct AssetId(pub u32);
 
-/// Content-addressed transfer identifier — the double-SHA256 of the canonical
-/// serialization. This makes the id both the idempotency key and the
+/// Content-addressed transfer identifier: the double-SHA256 of the canonical
+/// serialization. That makes the id both the idempotency key and the
 /// tamper-evidence artifact.
 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
 pub struct TransferId(pub [u8; 32]);
 
-/// Uniquely identifies a posting within the ledger. The `(transfer, index)` pair
-/// ties every posting back to the transfer that created it, which is the basis
-/// of the provenance graph.
+/// Uniquely identifies a posting within the ledger. The `(transfer, index)`
+/// pair ties every posting back to the transfer that created it, which is what
+/// the provenance graph is built on.
 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
 pub struct PostingId {
     /// The transfer that created this posting.
     pub transfer: TransferId,
-    /// Zero-based position within the transfer's created postings.
+    /// Zero-based position among the postings the transfer created.
     pub index: u16,
 }
 
-/// Identifies a book — a named scope for transfers.
+/// Identifies a book, which is a named scope for transfers.
 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
 pub struct BookId(pub i64);
 
@@ -171,14 +172,14 @@ impl AssetId {
     }
 }
 
-/// The implicit book used when a transfer does not name one. Fixed so that two
-/// otherwise-identical transfers hash to the same [`TransferId`] — a random
+/// The implicit book a transfer takes when it names none. Fixed, so that two
+/// otherwise-identical transfers hash to the same [`TransferId`]. A random
 /// default would break content-addressed idempotency.
 pub const DEFAULT_BOOK: BookId = BookId(0);
 
 impl Default for BookId {
-    /// Deterministic: returns [`DEFAULT_BOOK`]. Use [`BookId::generate`] to mint
-    /// a fresh unique id for a real book.
+    /// Deterministic: returns [`DEFAULT_BOOK`]. Use [`BookId::generate`] to
+    /// mint a fresh unique id for a real book.
     fn default() -> Self {
         DEFAULT_BOOK
     }
@@ -190,9 +191,9 @@ impl BookId {
         Self(id)
     }
 
-    /// Mint a fresh, process-unique book id. Unlike [`Default`], this is not
-    /// stable across calls — use it when creating a new [`Book`](crate::Book),
-    /// never for the implicit book of a transfer.
+    /// Mint a fresh, process-unique book id. This is not stable across calls,
+    /// where [`Default`] is. Use it for a new [`Book`](crate::Book), and never
+    /// for the implicit book of a transfer.
     pub fn generate() -> Self {
         // Process-global so the "process-unique" contract holds across threads;
         // a per-thread generator can repeat an id on another thread.

+ 8 - 7
crates/kuatia-types/src/internals.rs

@@ -1,12 +1,13 @@
 //! The seam the rest of this workspace uses to reach an amount's integer.
 //!
 //! Not part of the public API. [`Cent`] is deliberately absent from every
-//! public signature, but the storage backends have to bind an integer to a
-//! column and the ledger has to do checked arithmetic, and they are separate
-//! crates, so `pub(crate)` cannot serve them. These two functions are that
-//! route, kept in one place so it stays greppable. The money vocabulary is
-//! re-exported here for the same reason: a caller of the ledger names amounts
-//! and assets, never the integer behind them.
+//! public signature. The storage backends still have to bind an integer to a
+//! column, and the ledger has to do checked arithmetic. They are separate
+//! crates, so `pub(crate)` cannot serve them.
+//!
+//! These two functions are that route, kept in one place so it stays greppable.
+//! The money vocabulary is re-exported here for the same reason: a caller of
+//! the ledger names amounts and assets, and never the integer behind them.
 
 use std::sync::Arc;
 
@@ -16,7 +17,7 @@ pub use kuatia_money::{
     Cent, OverflowError, ParseDecimalError, Scale, decode_storage_i128, encode_storage_i128,
 };
 
-/// The amount's value in minor units.
+/// The value of the amount in minor units.
 pub fn cent(amount: &Amount) -> Cent {
     amount.cent()
 }

+ 4 - 4
crates/kuatia-types/src/lib.rs

@@ -1,9 +1,9 @@
 //! Domain types for the ledger.
 //!
-//! These types model the UTXO-style ledger where value is held as **postings** —
-//! signed amounts owned by exactly one account. An account's balance is simply the
-//! sum of its active postings, which eliminates the need for running balance fields
-//! and makes the system trivially auditable by replaying the transfer log.
+//! These types model the UTXO-style ledger, where value is held as
+//! **postings**. A posting is a signed amount that exactly one account owns.
+//! The balance of an account is the sum of its active postings. So the ledger
+//! needs no mutable balance field, and a replay of the transfer log audits it.
 
 pub mod autoid;
 

+ 21 - 19
crates/kuatia-types/src/posting.rs

@@ -7,14 +7,14 @@ use serde::{Deserialize, Serialize};
 /// Which postings a read returns, by derived state.
 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
 pub enum PostingFilter {
-    /// The unspent, balance-bearing set: present in the live index.
+    /// The unspent set that carries the balance: present in the live index.
     Live,
-    /// Every posting ever created, including spent ones.
+    /// Every posting ever created, the spent ones too.
     All,
 }
 
-/// The derived state of a single [`Posting`]: liveness is index membership, so
-/// a posting is spendable or spent and never both, with no state in between.
+/// The derived state of a single [`Posting`]. Liveness is index membership, so
+/// a posting is spendable or spent, never both, and nothing in between.
 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
 pub enum PostingState {
     /// In the live index: spendable, and counts toward balance.
@@ -27,23 +27,24 @@ pub enum PostingState {
 
 /// A signed amount of one asset, owned by exactly one account.
 ///
-/// A positive posting is value controlled by the account; a negative posting is
-/// an offset position (issuance, external flow, overdraft, or system balancing).
-/// Negative postings are allowed on any account except one that forbids
-/// overdraft (carries [`AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT`](crate::AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT)).
+/// A positive posting is value the account controls. A negative posting is an
+/// offset position: an issuance, an external flow, an overdraft, or a system
+/// counter-entry. A negative posting is allowed on any account except one that
+/// forbids overdraft, which carries
+/// [`AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT`](crate::AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT).
 ///
 /// A `Posting` is an immutable record: once created it is never updated. Its
-/// state is not a field here; it is derived from live-index membership (see
+/// state is no field here. It comes from live-index membership instead (see
 /// [`PostingState`]).
 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 pub struct Posting {
-    /// Unique identifier derived from the creating transfer.
+    /// Unique identifier, derived from the transfer that created it.
     pub id: PostingId,
     /// The account (subaccount) that owns this posting.
     pub owner: AccountId,
-    /// What the account holds here, carrying the asset it is denominated in.
-    /// Signed: positive is value the account controls, negative an offset
-    /// position.
+    /// What the account holds here, with the asset it is denominated in.
+    /// Signed: positive is value the account controls, and negative is an
+    /// offset position.
     pub amount: Amount,
 }
 
@@ -60,8 +61,8 @@ impl Posting {
     }
 }
 
-/// A posting to be created — carries no id yet because the [`PostingId`] depends
-/// on the [`TransferId`](crate::TransferId), which is computed during validation.
+/// A posting to create. It carries no id yet, because the [`PostingId`] depends
+/// on the [`TransferId`](crate::TransferId), which validation computes.
 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 pub struct NewPosting {
     /// The account (subaccount) that will own the created posting.
@@ -69,10 +70,11 @@ pub struct NewPosting {
     /// What the posting will hold. Signed: positive is value the account
     /// controls, negative an offset position.
     pub amount: Amount,
-    /// Provenance — who funded this posting. Descriptive only: it is excluded
-    /// from the content-address preimage (see [`NewPosting`]'s `ToBytes`), so it
-    /// does not affect the [`TransferId`](crate::TransferId) or the idempotency
-    /// key. Persisted on the envelope record for audit, not on the stored
+    /// Provenance: who funded this posting. Descriptive only. The
+    /// content-address preimage leaves it out (see the `ToBytes` of
+    /// [`NewPosting`]), so it affects neither the
+    /// [`TransferId`](crate::TransferId) nor the idempotency key. It is
+    /// persisted on the envelope record for an audit, and not on the stored
     /// [`Posting`].
     pub payer: Option<AccountId>,
 }

+ 46 - 42
crates/kuatia-types/src/transfer.rs

@@ -7,7 +7,7 @@ use crate::ids::{AccountId, BookId, TransferId};
 use crate::value_date::ValueDate;
 use serde::{Deserialize, Serialize};
 
-/// Confirmation of a committed transfer, carrying its content-addressed id.
+/// Confirmation of a committed transfer, with its content-addressed id.
 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 pub struct Receipt {
     /// Content-addressed id of the committed transfer.
@@ -21,20 +21,20 @@ pub struct Receipt {
 /// postings only for accounts with a positive net debit.
 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 pub struct Movement {
-    /// Account (subaccount) being debited.
+    /// The account (subaccount) to debit.
     pub from: AccountId,
-    /// Account (subaccount) being credited.
+    /// The account (subaccount) to credit.
     pub to: AccountId,
-    /// What moves. Negative for the offset leg of a deposit, where value
-    /// enters the ledger rather than moving inside it.
+    /// What moves. Negative for the offset leg of a deposit, where value enters
+    /// the ledger instead of a move inside it.
     pub amount: Amount,
 }
 
 /// A transfer intent: one or more movements to execute atomically.
 ///
 /// `resolve` turns the movements into the concrete postings of an
-/// [`Envelope`](crate::Envelope) at commit time. Callers express *what* should
-/// happen, not *which postings* to consume.
+/// [`Envelope`](crate::Envelope) at commit time. A caller states *what* to do,
+/// and not *which postings* to consume.
 #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
 pub struct Transfer {
     /// Movements to execute atomically.
@@ -48,19 +48,19 @@ pub struct Transfer {
     pub metadata: Metadata,
 }
 
-/// Metadata key holding a transfer's caller-supplied reference. Reserved, so a
-/// reference set through [`TransferBuilder::reference`] and one written straight
-/// into [`Transfer::metadata`] are the same field.
+/// The metadata key for the reference a caller gives a transfer. Reserved, so a
+/// reference set through [`TransferBuilder::reference`] and one written
+/// straight into [`Transfer::metadata`] are the same field.
 pub const REFERENCE_KEY: &str = "reference";
 
-/// Builder for constructing [`Transfer`] values.
+/// The builder that assembles a [`Transfer`].
 ///
-/// Every verb takes one amount rather than an asset beside a number, and takes
+/// Every verb takes one amount, and not an asset beside a number. It accepts
 /// anything that converts into an [`Amount`]: `(500, usd)` for minor units,
-/// `("5.00", usd)` for the written form, `(usd, cent)` for a value already in
-/// hand. A conversion that fails is held until [`build`](Self::build), so the
-/// chain stays fluent and one bad amount cannot be mistaken for a committed
-/// transfer.
+/// `("5.00", usd)` for the written form, and `(usd, cent)` for a value already
+/// in hand. A conversion that fails is held until [`build`](Self::build). So
+/// the chain stays fluent, and one bad amount cannot be mistaken for a
+/// committed transfer.
 #[derive(Default)]
 pub struct TransferBuilder {
     transfer: Transfer,
@@ -75,8 +75,8 @@ impl TransferBuilder {
         Self::default()
     }
 
-    /// Add a movement. The neutral spelling, for a leg that is not a payment:
-    /// each side of an exchange, for instance.
+    /// Add a movement. The neutral form, for a leg that is not a payment, such
+    /// as each side of an exchange.
     pub fn movement<A>(mut self, from: AccountId, to: AccountId, amount: A) -> Self
     where
         A: TryInto<Amount>,
@@ -99,9 +99,9 @@ impl TransferBuilder {
         self.movement(from, to, amount)
     }
 
-    /// Add a deposit: creates an offset posting on the external account and
-    /// credits the target account. Pushes two movements whose net debit on the
-    /// external account is zero.
+    /// Add a deposit. It creates an offset posting on the external account and
+    /// credits the target account. It pushes two movements whose net debit on
+    /// the external account is zero.
     pub fn deposit<A>(mut self, to: AccountId, amount: A, external: AccountId) -> Self
     where
         A: TryInto<Amount>,
@@ -125,7 +125,8 @@ impl TransferBuilder {
             .movement(external, to, amount)
     }
 
-    /// Add a withdrawal: move value from an account to an external destination.
+    /// Add a withdrawal, which moves value from an account to an external
+    /// destination.
     pub fn withdraw<A>(self, from: AccountId, amount: A, external: AccountId) -> Self
     where
         A: TryInto<Amount>,
@@ -146,20 +147,23 @@ impl TransferBuilder {
         self
     }
 
-    /// Attach the caller's own reference for this transfer: a payment reference,
-    /// an order id, whatever identifies the event in the system asking for it.
+    /// Attach the own reference of the caller to this transfer. It is a payment
+    /// reference, an order id, or whatever names the event in the system that
+    /// asks for it.
     ///
-    /// Give every distinct transfer a distinct reference. A transfer's id is the
-    /// hash of its content, so two transfers that are byte-identical *are* one
+    /// Give every distinct transfer a distinct reference. The id of a transfer
+    /// is the hash of its content. So two byte-identical transfers *are* one
     /// transfer, and the second commit is reported as an already-committed
-    /// replay rather than applied. A payment distinguishes itself, because the
-    /// postings it consumes differ from the previous payment's. A transfer that
-    /// consumes nothing cannot: two deposits of the same amount to the same
-    /// account are identical, and without a reference the second is discarded.
+    /// replay rather than applied.
     ///
-    /// Retry safety is the same mechanism read the other way: repeat the
-    /// reference to make a retry idempotent, and a redelivered request collapses
-    /// onto the transfer it already committed.
+    /// A payment tells itself apart, because the postings it consumes differ
+    /// from the ones the payment before it consumed. A transfer that consumes
+    /// nothing cannot. Two deposits of the same amount to the same account are
+    /// identical, and with no reference the second one is discarded.
+    ///
+    /// Retry safety is the same mechanism the other way round. Repeat the
+    /// reference to make a retry idempotent, and a redelivered request
+    /// collapses onto the transfer it already committed.
     ///
     /// Set this before [`metadata`](Self::metadata), which replaces the whole
     /// map.
@@ -170,15 +174,15 @@ impl TransferBuilder {
         self
     }
 
-    /// Set the day this entry takes effect, for an entry booked on a different
-    /// day than it belongs to: a backdated correction, a future-dated standing
-    /// order, a trade settling later.
+    /// Set the day this entry takes effect. Use it for an entry booked on a
+    /// different day than it belongs to. A backdated correction, a future-dated
+    /// standing order and a late trade are all such entries.
     ///
-    /// The value date is part of the transfer's content address, so two
+    /// The value date is part of the content address of the transfer, so two
     /// otherwise identical entries valued on different days are two transfers.
-    /// It follows that a value date cannot be corrected in place: an entry
-    /// valued wrongly is reversed and reposted, which is the trail an auditor
-    /// expects anyway.
+    /// So nothing can correct a value date in place. An entry with the wrong
+    /// value is reversed and reposted, which is the trail an auditor expects
+    /// anyway.
     ///
     /// This does not change when the transfer commits. The commit instant stays
     /// the ledger's own clock, because that is what balance reads are ordered
@@ -188,8 +192,8 @@ impl TransferBuilder {
         self
     }
 
-    /// Set the free-form metadata, replacing the whole map including any
-    /// [`reference`](Self::reference) already set.
+    /// Set the free-form metadata. It replaces the whole map, and that covers
+    /// any [`reference`](Self::reference) already set.
     pub fn metadata(mut self, metadata: Metadata) -> Self {
         self.transfer.metadata = metadata;
         self

+ 7 - 7
crates/kuatia-types/src/value_date.rs

@@ -7,9 +7,9 @@ use serde::{Deserialize, Serialize};
 
 /// The day an entry takes effect, held as days since 1970-01-01.
 ///
-/// A calendar day rather than an instant, because a value date is a business
-/// fact that no timezone should be able to shift: an entry valued 20 November
-/// is valued 20 November wherever it is read.
+/// A calendar day and not an instant, because a value date is a business fact
+/// that no timezone must be able to shift. An entry valued 20 November is
+/// valued 20 November wherever a reader reads it.
 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
 pub struct ValueDate(i64);
 
@@ -48,7 +48,7 @@ fn days_in_month(year: i32, month: u32) -> u32 {
 }
 
 impl ValueDate {
-    /// Build a value date from a calendar date, rejecting one that does not
+    /// Build a value date from a calendar date, and reject one that does not
     /// exist.
     pub fn new(year: i32, month: u32, day: u32) -> Result<Self, InvalidDate> {
         if !(1..=12).contains(&month) {
@@ -90,9 +90,9 @@ impl fmt::Debug for ValueDate {
     }
 }
 
-/// Days from 1970-01-01 to a calendar date, by Howard Hinnant's `days_from_civil`.
-/// Shifting the era to start in March puts the leap day last, so the month-length
-/// pattern repeats and needs no table.
+/// Days from 1970-01-01 to a calendar date, by the `days_from_civil` of Howard
+/// Hinnant. An era that starts in March puts the leap day last, so the
+/// month-length pattern repeats and needs no table.
 fn days_from_civil(year: i32, month: u32, day: u32) -> i64 {
     let y = if month <= 2 { year - 1 } else { year };
     let era = if y >= 0 { y } else { y - 399 } / 400;

+ 1 - 1
crates/kuatia/examples/create_accounts.rs

@@ -20,7 +20,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
     ledger
         .create_account(Account::debit_must_not_exceed_credit(AccountId::new(2)))
         .await?;
-    // A system account (fees, settlement, market-making) — no balance floor.
+    // A system account (fees, settlement, a market maker): no balance floor.
     ledger
         .create_account(Account::new(AccountId::new(50)))
         .await?;

+ 5 - 4
crates/kuatia/examples/escrow.rs

@@ -2,8 +2,8 @@
 //!
 //! Escrow is a pending state, and this ledger has no pending state: every
 //! transfer is final the moment it commits. So the state lives in an account.
-//! Value sits in an escrow account per agreement, and "in escrow" is not a flag
-//! anyone set, it is the balance of that account being non-zero.
+//! Value sits in an escrow account per agreement. "In escrow" is not a flag
+//! anyone set. It is a non-zero balance on that account.
 //!
 //! See `doc/pending-states.md`.
 //!
@@ -14,8 +14,9 @@
 
 use kuatia::prelude::*;
 
-/// Top-level account every agreement's escrow hangs off as a subaccount, so one
-/// agreement's money can never be spent by another and each closes on its own.
+/// The top-level account each agreement hangs its escrow off, as a subaccount.
+/// So no agreement can spend the money of another, and each one closes on its
+/// own.
 const ESCROW: i64 = 50;
 
 fn escrow_for(agreement: i64) -> AccountId {

+ 5 - 5
crates/kuatia/examples/inflight_hold.rs

@@ -1,10 +1,10 @@
 //! Authorize a payment hold, capture it in parts over time, then void the rest.
 //!
-//! This mirrors a card-style authorization: the customer's funds are parked in
-//! per-destination holding accounts up front, captured (confirmed) in slices as
-//! goods ship, and whatever is never captured is released (voided) back to the
-//! customer. The `sleep` calls stand in for the real time that passes between
-//! authorization, each capture, and the final release.
+//! This mirrors a card-style authorization. The funds of the customer are
+//! parked in per-destination holding accounts up front. They are captured
+//! (confirmed) in slices as goods ship. Whatever is never captured is released
+//! (voided) back to the customer. The `sleep` calls stand in for the real time
+//! that passes between the authorization, each capture and the final release.
 //!
 //! Run with:
 //! ```sh

+ 25 - 24
crates/kuatia/src/error.rs

@@ -1,4 +1,4 @@
-//! Error types for the async ledger layer.
+//! The error types of the async ledger layer.
 //!
 //! [`LedgerError`] unifies errors from the pure core (validation, selection)
 //! and from storage, so callers get a single error type from every API.
@@ -15,17 +15,17 @@ use kuatia_storage::error::StoreError;
 
 /// Unified error type for the async ledger API.
 ///
-/// `Clone` so a multi-transfer workflow can box the error that triggered its
-/// unwind and still return the real variant to the caller (an
-/// [`OverdraftExceeded`] detected during commit stays an [`OverdraftExceeded`],
-/// not a stringified internal fault).
+/// `Clone`, so a multi-transfer workflow can box the error that triggered its
+/// unwind and still return the real variant to the caller. An
+/// [`OverdraftExceeded`] found at commit stays an [`OverdraftExceeded`], and
+/// does not become a stringified internal fault.
 ///
 /// [`OverdraftExceeded`]: ValidationError::OverdraftExceeded
 #[derive(Debug, Clone)]
 pub enum LedgerError {
     /// A transfer invariant was violated.
     Validation(ValidationError),
-    /// Storage operation failed.
+    /// A storage operation failed.
     Store(StoreError),
     /// Posting selection failed (e.g. insufficient funds).
     Selection(InsufficientFunds),
@@ -34,8 +34,8 @@ pub enum LedgerError {
     /// The posting cannot be reversed (e.g. already consumed).
     PostingNotReversible(PostingId),
     /// A consumed posting was no longer live at commit time: already spent,
-    /// missing, or taken by a concurrent commit. The atomic commit refused it
-    /// rather than double-spend. Carries the first offending posting.
+    /// absent, or taken by a concurrent commit. The atomic commit refused it,
+    /// and did not double-spend. Carries the first posting at fault.
     DoubleSpend(PostingId),
     /// The referenced account does not exist.
     AccountNotFound(AccountId),
@@ -45,13 +45,13 @@ pub enum LedgerError {
     AccountAlreadyClosed(AccountId),
     /// An account with this id already exists.
     AccountAlreadyExists(AccountId),
-    /// An account-version append did not land: the head was not at
-    /// `expected - 1` when the append was attempted (a concurrent transition
-    /// moved it). Carries the version this attempt targeted.
+    /// An account-version append did not land. The head was not at
+    /// `expected - 1` when the append ran, because a concurrent transition
+    /// moved it. Carries the version this call aimed at.
     AccountVersionConflict {
         /// Account whose version append was rejected.
         account: AccountId,
-        /// Version this attempt targeted (`current + 1` at read time).
+        /// Version this call aimed at (`current + 1` at read time).
         expected: u64,
     },
     /// An amount could not be built, or two assets were combined.
@@ -77,37 +77,38 @@ pub enum LedgerError {
     BookNotFound(BookId),
     /// A book with this id already exists.
     BookAlreadyExists(BookId),
-    /// The referenced inflight transaction does not exist (no authorize record).
+    /// The referenced inflight transaction does not exist (no authorize
+    /// record).
     InflightNotFound(TransferId),
     /// The referenced transfer is not an inflight authorize, or its metadata is
     /// malformed.
     NotInflightTransaction(TransferId),
-    /// The destination already has an open inflight hold; only one is allowed at
-    /// a time per account.
+    /// The destination already has an open inflight hold; only one is allowed
+    /// at a time per account.
     InflightAlreadyOpen(AccountId),
-    /// The inflight transaction has no leg matching this destination and asset.
+    /// The inflight transaction has no leg for this destination and asset.
     InflightLegNotFound {
-        /// The destination account with no matching leg.
+        /// The destination account that has no leg.
         destination: AccountId,
-        /// The asset with no matching leg.
+        /// The asset that has no leg.
         asset: AssetId,
     },
     /// An inflight movement must move between two distinct accounts.
     InflightSelfMovement(AccountId),
     /// Monetary arithmetic overflow.
     Overflow,
-    /// The loader under-fetched: a balance key `validate_and_plan` reads was not
-    /// loaded. Validation would read the missing key as zero and could approve an
-    /// overdraft, so this is failed loudly instead. A load/validate seam bug, not
-    /// a user error. Carries the missing key.
+    /// The loader under-fetched. A balance key `validate_and_plan` reads was
+    /// not loaded. Validation would read an absent key as zero and could
+    /// approve an overdraft, so this fails loudly instead. A bug at the load
+    /// and validate seam, and not a user error. Carries the key that is absent.
     UnderFetchedState {
         /// Account whose balance was not loaded.
         account: AccountId,
         /// Asset whose balance was not loaded.
         asset: AssetId,
     },
-    /// A transfer in a multi-transfer workflow failed and reversing an
-    /// earlier one failed too, so the ledger is left part-applied.
+    /// A transfer in a multi-transfer workflow failed, and so did the reversal
+    /// of an earlier one, so the ledger is left part-applied.
     CompensationFailed {
         /// The error that triggered compensation.
         original: Box<LedgerError>,

+ 74 - 65
crates/kuatia/src/inflight.rs

@@ -1,14 +1,17 @@
 //! Inflight holds: authorize funds now, confirm (fully or partially) or void
 //! later.
 //!
-//! An inflight transaction is an ordinary trade whose every destination is
-//! rewritten to a per-destination holding subaccount (flagged
-//! [`AccountFlags::INFLIGHT`] and forbidding overdraft, keyed by a subaccount
-//! derived from the trade). Committing that rewritten transfer parks the
-//! funds. Confirm and void are ordinary commits that move a hold's balance to
-//! its destination or back to its funder. Nothing new is stored: the authorize
-//! transfer's metadata carries the leg table, and every artifact is tagged with
-//! a CBOR-encoded `InflightMeta` entry so the lifecycle is read, not inferred.
+//! An inflight transaction is an ordinary trade, and the ledger rewrites every
+//! destination of it to a per-destination holding subaccount. That subaccount
+//! carries [`AccountFlags::INFLIGHT`], it forbids overdraft, and its key comes
+//! from the trade. A commit of the rewritten transfer parks the funds. Confirm
+//! and void are ordinary commits that move the balance of a hold to its
+//! destination, or back to its funder.
+//!
+//! Nothing new is stored. The metadata of the authorize transfer carries the
+//! leg table, and every artifact is tagged with a CBOR-encoded `InflightMeta`
+//! entry. So a reader takes the lifecycle from recorded fields and infers
+//! nothing.
 //!
 //! See `doc/adr/0014-inflight-holds-via-holding-accounts.md`.
 
@@ -30,17 +33,17 @@ use projection::{
     encode_meta, group_holds, meta_map, read_meta,
 };
 
-/// One leg of an inflight transaction: an amount of an asset funded by `funder`,
-/// parked in `hold`, destined for `destination`.
+/// One leg of an inflight transaction: an amount of an asset that `funder`
+/// funded, that sits in `hold`, and that `destination` is to receive.
 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 pub struct InflightLeg {
     /// Account the funds settle to on confirm.
     pub destination: AccountId,
-    /// Per-destination holding account parking the funds.
+    /// The per-destination holding account that holds the funds.
     pub hold: AccountId,
     /// Account that funded this leg (the funds return here on void).
     pub funder: AccountId,
-    /// What this leg holds, carrying the asset it is in.
+    /// What this leg holds, with the asset it is in.
     pub amount: Amount,
 }
 
@@ -62,11 +65,11 @@ impl Authorization {
     }
 }
 
-/// Lifecycle state of an inflight transaction, derived from balances and the
-/// settling transfers.
+/// Lifecycle state of an inflight transaction, derived from the balances and
+/// the settling transfers.
 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
 pub enum InflightState {
-    /// Nothing settled yet; the full authorized amount is still held.
+    /// Nothing settled yet, and the full authorized amount is still held.
     Held,
     /// Some funds settled, some still held.
     PartiallyConfirmed,
@@ -118,27 +121,28 @@ impl Ledger {
     // Authorize
     // -----------------------------------------------------------------------
 
-    /// Authorize a trade without settling it. Each movement's destination is
-    /// rewritten to a fresh per-destination holding account, and the rewritten
-    /// transfer is committed, parking the funds. Returns a handle used by
-    /// [`confirm_all`](Self::confirm_all), [`confirm`](Self::confirm), and
+    /// Authorize a trade and settle nothing. The destination of each movement
+    /// is rewritten to a fresh per-destination holding account, and the
+    /// rewritten transfer is committed, which parks the funds. Returns a handle
+    /// for [`confirm_all`](Self::confirm_all), [`confirm`](Self::confirm) and
     /// [`void`](Self::void).
     ///
-    /// Every movement must move between two distinct accounts. All holds share a
-    /// subaccount derived from the trade, so re-authorizing the identical trade is
-    /// rejected (its holds already exist), while different trades to the same
-    /// destination run concurrently under distinct subaccounts.
+    /// Every movement must move between two distinct accounts. All the holds
+    /// share a subaccount derived from the trade. So a second authorize of the
+    /// identical trade is rejected, because its holds are already there.
+    /// Different trades to the same destination run at once, under distinct
+    /// subaccounts.
     pub async fn authorize(&self, transfer: Transfer) -> Result<Authorization, LedgerError> {
         self.authorize_inner(transfer, None).await
     }
 
-    /// Authorize with an expiry: a commit instant in unix milliseconds after
-    /// which [`expire_due`](Self::expire_due) may sweep the holds back to their
-    /// funders.
+    /// Authorize with an expiry, which is a commit instant in unix
+    /// milliseconds. After it, [`expire_due`](Self::expire_due) can sweep the
+    /// holds back to their funders.
     ///
-    /// The expiry is a permission to sweep, not a schedule. Nothing in the
+    /// The expiry is a permission to sweep, and not a schedule. Nothing in the
     /// ledger runs a timer, for the same reason the balance cache does not
-    /// (ADR-0019): a caller decides when to sweep, and an expired hold keeps
+    /// (ADR-0019). A caller decides when to sweep, and an expired hold keeps
     /// its funds parked until something asks.
     pub async fn authorize_until(
         &self,
@@ -223,8 +227,8 @@ impl Ledger {
     // Confirm
     // -----------------------------------------------------------------------
 
-    /// Confirm the entire inflight transaction: sweep every hold's remaining
-    /// balance to its destination and close the drained holds.
+    /// Confirm the whole inflight transaction. It sweeps what each hold still
+    /// holds to its destination, and closes the drained holds.
     pub async fn confirm_all(&self, inflight: &TransferId) -> Result<Vec<Receipt>, LedgerError> {
         let (record, legs) = self.load_inflight(inflight).await?;
         let book = record.envelope.book();
@@ -252,19 +256,20 @@ impl Ledger {
         Ok(receipts)
     }
 
-    /// Confirm one or more legs in a single call. Each movement is expressed with
-    /// the same `(from, to, asset, amount)` shape as [`TransferBuilder::pay`]:
-    /// `from` is the leg's funder, `to` its destination. Build the set with
-    /// `TransferBuilder` and pass the resulting [`Transfer`]; its book, user data,
-    /// and metadata are ignored.
+    /// Confirm one or more legs in a single call. Each movement takes the same
+    /// `(from, to, asset, amount)` shape as [`TransferBuilder::pay`], where
+    /// `from` is the funder of the leg and `to` is its destination. Build the
+    /// set with `TransferBuilder` and pass the [`Transfer`] it returns. Its
+    /// book, user data and metadata are ignored.
     ///
-    /// Each movement delivers `amount` of `asset` from the matching leg's hold to
-    /// its destination. `amount` must not exceed the amount still held; the
-    /// overdraft-forbidding hold makes over-confirmation impossible regardless. A
-    /// hold is closed once fully drained.
+    /// Each movement delivers `amount` of `asset` from the hold of the leg it
+    /// names to that destination. `amount` must not exceed the amount still
+    /// held. The hold forbids overdraft, which makes over-confirmation
+    /// impossible in any case. A hold is closed once it is fully drained.
     ///
-    /// Movements settle in order, each its own commit, so the batch is not atomic:
-    /// a later movement failing leaves earlier confirmations applied.
+    /// Movements settle in order, each in its own commit, so the batch is not
+    /// atomic. A movement that fails leaves the confirmations before it
+    /// applied.
     pub async fn confirm(
         &self,
         inflight: &TransferId,
@@ -317,8 +322,8 @@ impl Ledger {
     // Void
     // -----------------------------------------------------------------------
 
-    /// Void the entire inflight transaction: return every hold's remaining
-    /// balance to the funders recorded in the leg table and close the holds.
+    /// Void the whole inflight transaction. It returns what each hold still
+    /// holds to the funders the leg table records, and closes the holds.
     pub async fn void(&self, inflight: &TransferId) -> Result<Vec<Receipt>, LedgerError> {
         let (record, legs) = self.load_inflight(inflight).await?;
         let book = record.envelope.book();
@@ -354,9 +359,10 @@ impl Ledger {
     // Status / queries
     // -----------------------------------------------------------------------
 
-    /// Derived status of an inflight transaction: per-leg authorized, confirmed,
-    /// voided, and still-held amounts, plus an overall state. All figures come
-    /// from balances and the metadata-tagged settling transfers.
+    /// Derived status of an inflight transaction. It holds the authorized, the
+    /// confirmed, the voided and the still-held amount per leg, plus an overall
+    /// state. Every figure comes from the balances and the metadata-tagged
+    /// settling transfers.
     pub async fn inflight_status(
         &self,
         inflight: &TransferId,
@@ -405,11 +411,12 @@ impl Ledger {
     /// Void one inflight if its holds have expired by `now`, a commit instant
     /// in unix milliseconds.
     ///
-    /// Settles through [`void`](Self::void), so an expiry returns funds by
-    /// exactly the route a caller's own void would, including the partial case:
-    /// what was confirmed stays, what is still held goes back to its funders.
-    /// Returns no receipts when the inflight has no expiry, has not reached it,
-    /// or is already drained, so a sweep can call it without checking first.
+    /// Settles through [`void`](Self::void). So an expiry returns funds by
+    /// exactly the route a void of the caller would take. That covers the
+    /// partial case: what was confirmed stays, and what is still held goes back
+    /// to its funders. Returns no receipt when the inflight has no expiry, has
+    /// not reached it, or is already drained. A sweep can therefore call it and
+    /// check nothing first.
     #[instrument(skip(self), name = "ledger.expire")]
     pub async fn expire(
         &self,
@@ -430,13 +437,13 @@ impl Ledger {
         self.void(inflight).await
     }
 
-    /// Sweep every open hold whose expiry has passed, voiding the inflights
-    /// they belong to, and report which ones were voided.
+    /// Sweep every open hold whose expiry has passed, void the inflights they
+    /// belong to, and report which ones were voided.
     ///
-    /// Reads the expiry off the holding accounts, which is why it lives there:
-    /// the filter costs one account read per open hold and no transfer parsing.
-    /// Only the holds that are actually due pay for the history read that finds
-    /// their inflight.
+    /// Reads the expiry off the holding accounts, which is why it lives there.
+    /// The filter costs one account read per open hold, and it parses no
+    /// transfer. Only the holds that are actually due pay for the history read
+    /// that finds their inflight.
     #[instrument(skip(self), name = "ledger.expire_due")]
     pub async fn expire_due(&self, now: i64) -> Result<Vec<TransferId>, LedgerError> {
         let mut voided = Vec::new();
@@ -466,8 +473,8 @@ impl Ledger {
     }
 
     /// The inflight a holding account belongs to, found by the authorize
-    /// transfer in its history. The hold is created before that transfer is
-    /// committed, so its id cannot be stamped on the account and has to be read
+    /// transfer in its history. The hold is created before that transfer
+    /// commits, so its id cannot be stamped on the account. It has to be read
     /// back from the one record that carries the leg table.
     async fn inflight_of_hold(&self, hold: &AccountId) -> Result<Option<TransferId>, LedgerError> {
         for record in self.history(hold).await? {
@@ -499,7 +506,8 @@ impl Ledger {
         Ok((record, legs))
     }
 
-    /// Commit a `hold -> target` settling transfer tagged with the inflight role.
+    /// Commit a `hold -> target` settling transfer, tagged with the inflight
+    /// role.
     #[allow(clippy::too_many_arguments)]
     async fn settle(
         &self,
@@ -529,8 +537,8 @@ impl Ledger {
         self.commit(tx).await
     }
 
-    /// Close a holding account once it has no unspent postings left. No-op if
-    /// already closed or still holding funds.
+    /// Close a holding account once no unspent posting is left on it. A no-op
+    /// if the account is already closed, or if it still holds funds.
     async fn close_if_drained(&self, hold: &AccountId) -> Result<(), LedgerError> {
         if self.has_live_postings(hold).await? {
             return Ok(());
@@ -543,8 +551,9 @@ impl Ledger {
 }
 
 /// Derive the shared subaccount id for an inflight from the submitted trade.
-/// Deterministic and known before the holds are created (unlike the authorize
-/// transfer's id). The sign bit is masked so the id is always positive.
+/// Deterministic, and known before the holds are created, which the id of the
+/// authorize transfer is not. The sign bit is masked, so the id is always
+/// positive.
 fn inflight_subaccount(transfer: &Transfer) -> i64 {
     let mut buf = Vec::new();
     // Serialization of a fixed `Transfer` is deterministic; the encode cannot
@@ -567,7 +576,7 @@ mod tests {
     use std::sync::Arc;
 
     /// An amount of `asset` in minor units. An amount compares by asset id, so
-    /// building the row here is equivalent to reading it back from the registry.
+    /// a row built here is equivalent to one read back from the registry.
     fn money<V>(asset: AssetId, value: V) -> Amount
     where
         Amount: From<(V, Arc<Asset>)>,

+ 44 - 36
crates/kuatia/src/inflight/projection.rs

@@ -2,12 +2,14 @@
 //! that turn a leg table, the settling transfers, and held balances into an
 //! [`InflightStatus`].
 //!
-//! This is the single owner of the encode/decode halves so they cannot drift,
-//! and of the void funder-distribution arithmetic. Everything here is pure (no
-//! `self`, no IO, no async); the async [`Ledger`](crate::ledger::Ledger)
-//! methods in the parent module only load raw records and call these functions.
-//! It stays in the `kuatia` crate rather than moving to `kuatia-core` because it
-//! reads [`TransferRecord`], a `kuatia-storage` type the pure core avoids.
+//! This is the single owner of the encode and decode halves, so they cannot
+//! drift, and of the funder-distribution arithmetic a void needs. Everything
+//! here is pure: no `self`, no IO, no async. The async
+//! [`Ledger`](crate::ledger::Ledger) methods in the parent module load raw
+//! records and call these functions, and do nothing else.
+//!
+//! It stays in the `kuatia` crate instead of `kuatia-core`, because it reads
+//! [`TransferRecord`], a `kuatia-storage` type the pure core avoids.
 
 use std::collections::{BTreeMap, BTreeSet};
 
@@ -23,24 +25,26 @@ use serde::{Deserialize, Serialize};
 use super::{InflightLeg, InflightLegStatus, InflightState, InflightStatus};
 use crate::error::LedgerError;
 
-/// Single metadata key holding the CBOR-encoded [`InflightMeta`] payload.
+/// The single metadata key that holds the CBOR-encoded [`InflightMeta`]
+/// payload.
 pub(super) const K_INFLIGHT: &str = "inflight";
 
 // ---------------------------------------------------------------------------
 // Metadata: one CBOR-encoded tagged payload under the `inflight` key
 // ---------------------------------------------------------------------------
 
-/// The inflight payload carried in a transfer's or holding account's metadata.
-/// Serialized to CBOR (via `ciborium`) and stored under [`K_INFLIGHT`], so the
-/// whole lifecycle is self-describing and read back, not inferred.
+/// The inflight payload in the metadata of a transfer or a holding account.
+/// Serialized to CBOR through `ciborium` and stored under [`K_INFLIGHT`]. So
+/// the whole lifecycle is self-describing, and a reader takes it from recorded
+/// fields rather than an inference.
 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 pub(super) enum InflightMeta {
     /// Tags the authorize transfer and carries its leg table.
     Authorize { legs: Vec<InflightLeg> },
     /// Tags a per-destination holding subaccount, with the instant after which
-    /// the hold may be swept. The expiry lives here rather than on the
-    /// authorize transfer because a sweep starts from the open holds, and
-    /// because account metadata is written once and never drifts.
+    /// a sweep can take the hold. The expiry lives here and not on the
+    /// authorize transfer, because a sweep starts from the open holds. Account
+    /// metadata is also written once, so it never drifts.
     Hold {
         destination: AccountId,
         expires_at: Option<i64>,
@@ -76,8 +80,8 @@ pub(super) fn meta_map(meta: &InflightMeta) -> Result<Metadata, LedgerError> {
     Ok(m)
 }
 
-/// Decode the [`InflightMeta`] carried by a metadata map, if any. Absent or
-/// malformed metadata yields `None` rather than an error.
+/// Decode the [`InflightMeta`] a metadata map carries, if it has one. Absent or
+/// malformed metadata gives `None`, and not an error.
 pub(super) fn read_meta(meta: &Metadata) -> Option<InflightMeta> {
     let bytes = meta.get(K_INFLIGHT)?;
     ciborium::from_reader(bytes.as_slice()).ok()
@@ -87,19 +91,20 @@ pub(super) fn read_meta(meta: &Metadata) -> Option<InflightMeta> {
 // Hold grouping: the single "walk the holds of an inflight" traversal
 // ---------------------------------------------------------------------------
 
-/// A holding subaccount of an inflight together with its destination and the
-/// assets it carries. Groups a leg table by hold so the confirm, void, and
-/// status paths share one traversal instead of each re-deriving `holds_of` /
-/// `destination_of` / `assets_of` inline.
+/// A holding subaccount of an inflight, with its destination and the assets it
+/// carries. It groups a leg table by hold, so the confirm, void and status
+/// paths share one traversal. None of them derives `holds_of`, `destination_of`
+/// or `assets_of` inline.
 pub(super) struct HoldGroup {
     pub(super) hold: AccountId,
     pub(super) destination: AccountId,
     pub(super) assets: Vec<AssetId>,
 }
 
-/// Group `legs` by holding subaccount, resolving each hold's destination. This
-/// is the single "walk the holds of an inflight" traversal; it is pure over the
-/// leg table and yields holds in sorted order (each with its assets sorted).
+/// Group `legs` by holding subaccount, and resolve the destination of each
+/// hold. This is the single "walk the holds of an inflight" traversal. It is
+/// pure over the leg table, and it gives the holds in sorted order, each with
+/// its assets sorted.
 pub(super) fn group_holds(
     legs: &[InflightLeg],
     inflight: TransferId,
@@ -127,8 +132,8 @@ fn assets_of(legs: &[InflightLeg], hold: AccountId) -> BTreeSet<AssetId> {
         .collect()
 }
 
-/// The asset definition carried by this hold's legs in `asset`. Every leg of one
-/// hold in one asset carries the same definition, so the first is enough.
+/// The asset definition the legs of this hold carry in `asset`. Every leg of
+/// one hold in one asset carries the same definition, so the first is enough.
 fn leg_asset(legs: &[InflightLeg], hold: AccountId, asset: AssetId) -> Option<&Arc<Asset>> {
     legs.iter()
         .find(|l| l.hold == hold && l.amount.asset_id() == asset)
@@ -150,26 +155,29 @@ fn destination_of(
 // Status derivation
 // ---------------------------------------------------------------------------
 
-/// Pre-loaded state for [`derive_status`], mirroring `PlanInput`: the async
-/// layer fetches the raw records and balances, this struct names exactly what
-/// the projection reads.
+/// Pre-loaded state for [`derive_status`], in the shape of `PlanInput`. The
+/// async layer fetches the raw records and balances, and this struct names
+/// exactly what the projection reads.
 pub(super) struct StatusInput<'a> {
     /// The inflight handle.
     pub(super) inflight: TransferId,
     /// The leg table from the authorize transfer.
     pub(super) legs: &'a [InflightLeg],
-    /// Settle transfers found in each hold's history, tagged with that hold.
+    /// Settle transfers found in the history of each hold, tagged with that
+    /// hold.
     pub(super) hold_history: &'a [(AccountId, Vec<TransferRecord>)],
     /// Live held balance per (hold, asset).
     pub(super) held: &'a BTreeMap<(AccountId, AssetId), Amount>,
 }
 
-/// Fold the leg table, settling transfers, and held balances into an
-/// [`InflightStatus`]. Pure: the caller supplies all state via [`StatusInput`].
+/// Fold the leg table, the settling transfers and the held balances into an
+/// [`InflightStatus`]. Pure: the caller supplies every piece of state through
+/// [`StatusInput`].
 ///
-/// Re-derives its own hold grouping via [`group_holds`] rather than trusting a
-/// caller-supplied grouping, the same way `validate_and_plan` re-derives its
-/// account sets; the loader's grouping is only used to decide what to fetch.
+/// It derives its own hold groups again through [`group_holds`], and does not
+/// take a group from the caller. `validate_and_plan` derives its account sets
+/// the same way. The groups the loader built decide what to fetch, and nothing
+/// else.
 pub(super) fn derive_status(input: StatusInput<'_>) -> Result<InflightStatus, LedgerError> {
     let StatusInput {
         inflight,
@@ -282,9 +290,9 @@ pub(super) struct FunderPayout {
 }
 
 /// Split `remaining` back to the funders of `(hold, asset)` in leg order, each
-/// capped at what it funded. Any co-funding rounding leftover lands on the last
-/// funder (its cap is lifted). Returns only positive payouts; an empty funder
-/// set yields no payouts. Pure arithmetic.
+/// capped at what it funded. Any rounding leftover from a co-funded leg lands
+/// on the last funder, whose cap is lifted. Returns the positive payouts alone,
+/// and an empty funder set gives no payout. Pure arithmetic.
 pub(super) fn distribute_to_funders(
     legs: &[InflightLeg],
     hold: AccountId,

+ 24 - 23
crates/kuatia/src/ledger.rs

@@ -1,8 +1,8 @@
-//! The async ledger resource -- the primary entry point for callers.
+//! The async ledger resource, which is the entry point a caller starts from.
 //!
 //! [`Ledger`] is one type over a single [`Store`]. Its methods are grouped into
-//! sibling modules by concern, so the deep commit engine is not buried among
-//! shallow query re-exports:
+//! sibling modules by concern, so the deep commit engine does not sit buried
+//! among shallow query re-exports:
 //!
 //! - `commit`: the commit engine (resolve, validate, atomic apply, reverse).
 //!   This is what a ledger fundamentally *is*.
@@ -11,7 +11,7 @@
 //! - `balance`: per-subaccount balance queries.
 //! - `query`: read-only queries and book CRUD (thin `Store` pass-throughs that
 //!   relabel `StoreError` as [`LedgerError`]).
-//! - `connect`: opening the SQL backend, under the `sql` feature.
+//! - `connect`: how to open the SQL backend, under the `sql` feature.
 //!
 //! The inflight-hold API is a further cluster, in [`crate::inflight`].
 
@@ -38,26 +38,27 @@ mod transition;
 pub use balance::SubAccountBalance;
 pub use projection::Projection;
 
-/// Default grace window (milliseconds) for the balance projection watermark: how
-/// far behind live a snapshot is allowed to advance, covering commit-to-visibility
-/// lag. See ADR-0019.
+/// Default grace window (milliseconds) for the balance projection watermark. It
+/// is how far behind live a snapshot can advance, and it allows for the
+/// commit-to-visibility lag. See ADR-0019.
 pub const DEFAULT_PROJECTION_GRACE_MS: i64 = 60_000;
 
-/// Default number of credits/debits that must accrue for a `(account, asset)`
-/// since its latest cache point before a read appends a new one. See ADR-0019.
+/// Default number of credits and debits that must accrue for a
+/// `(account, asset)` since its latest cache point, before a read appends a new
+/// one. See ADR-0019.
 pub const DEFAULT_SNAPSHOT_INTERVAL: u64 = 128;
 
-/// How the balance projection maintains itself (ADR-0019). Grouped into one type
-/// because these only tune the cache: correctness never depends on them, so a
-/// caller can ignore them entirely.
+/// How the balance projection maintains itself (ADR-0019). One type, because
+/// these tune the cache alone. Correctness never depends on them, so a caller
+/// can ignore them entirely.
 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
 pub struct ProjectionConfig {
-    /// How far behind live (ms) a new cache point's watermark sits, which also
-    /// debounces the background append.
+    /// How far behind live (ms) the watermark of a new cache point sits, which
+    /// also debounces the background append.
     pub grace_ms: i64,
-    /// Credits/debits that must accrue since the latest cache point before a
-    /// read appends a new one. Smaller snapshots more often: shorter read tails,
-    /// more rows.
+    /// Credits and debits that must accrue since the latest cache point, before
+    /// a read appends a new one. A smaller value snapshots more often, which
+    /// shortens a read tail and adds rows.
     pub snapshot_interval: u64,
 }
 
@@ -78,7 +79,7 @@ pub(crate) fn now_millis() -> Result<i64, LedgerError> {
         .as_millis() as i64)
 }
 
-/// Async ledger resource composing the commit pipeline.
+/// The async ledger resource, which composes the commit pipeline.
 pub struct Ledger {
     store: Arc<dyn Store>,
     projection: ProjectionConfig,
@@ -97,20 +98,20 @@ impl Ledger {
         }
     }
 
-    /// Tune how the balance projection maintains itself. Cache behaviour only;
-    /// the defaults suit any ledger that is not measuring its read latency.
+    /// Tune how the balance projection maintains itself. Cache behaviour only,
+    /// and the defaults suit any ledger that does not measure its read latency.
     pub fn with_projection_config(mut self, projection: ProjectionConfig) -> Self {
         self.projection = projection;
         self
     }
 
-    /// The balance projection's maintenance surface, kept off the balance reads
-    /// because nothing here answers what an account holds.
+    /// The maintenance surface of the balance projection, kept off the balance
+    /// reads because nothing here answers what an account holds.
     pub fn projection(&self) -> Projection<'_> {
         Projection::new(self)
     }
 
-    /// Returns a reference to the underlying store.
+    /// Returns a reference to the store below.
     pub fn store(&self) -> &dyn Store {
         self.store.as_ref()
     }

+ 15 - 15
crates/kuatia/src/ledger/asset.rs

@@ -11,8 +11,8 @@ use kuatia_storage::error::StoreError;
 use super::Ledger;
 use crate::error::LedgerError;
 
-/// Tries before a minted id is given up on. Each attempt is one read, and a
-/// clash needs a fresh millisecond or counter step, so a handful is plenty.
+/// Tries before a minted id is given up on. Each try is one read, and a clash
+/// needs a fresh millisecond or counter step, so a handful is plenty.
 const MINT_ATTEMPTS: usize = 8;
 
 /// Ids for assets come from the same generator accounts and books use, folded
@@ -20,10 +20,10 @@ const MINT_ATTEMPTS: usize = 8;
 /// low timestamp bits, which is what makes two registrations in one process
 /// differ.
 ///
-/// Masked to 31 bits because the `asset` columns are a 4-byte signed integer:
-/// an id above that range still round-trips, since the bind and the read cast
-/// the same way, but it sits in the table as a negative number, which is a trap
-/// for anything that later reads the column as a magnitude.
+/// Masked to 31 bits because the `asset` columns are a 4-byte signed integer.
+/// An id above that range still round-trips, because the bind and the read cast
+/// the same way. It sits in the table as a negative number, which is a trap for
+/// anything that later reads the column as a magnitude.
 fn next_asset_id() -> u32 {
     static IDS: AutoId = AutoId::new();
     (IDS.next() as u32) & 0x7fff_ffff
@@ -39,17 +39,17 @@ impl Ledger {
         Ok(())
     }
 
-    /// The asset with this code, registering it if the ledger has not seen it
-    /// before: `ledger.asset("EUR", "\u{20ac}", 2)`.
+    /// The asset with this code. It registers the asset if the ledger has not
+    /// seen it before: `ledger.asset("EUR", "\u{20ac}", 2)`.
     ///
     /// Idempotent, so setup code calls it unconditionally. A code already
-    /// registered with other metadata is [`LedgerError::AssetRedefined`] rather
-    /// than either definition quietly winning: the stored precision is what
-    /// every amount recorded against the asset was written at, and a row is
+    /// registered with other metadata is [`LedgerError::AssetRedefined`], and
+    /// neither definition quietly wins. The stored precision is what every
+    /// amount recorded against the asset was written at, and a row is
     /// immutable.
     ///
-    /// The id is minted here, the way an account's or a book's is, because the
-    /// code is what a caller names and the id is what storage carries
+    /// The id is minted here, the way the id of an account or a book is. The
+    /// code is what a caller names, and the id is what storage carries
     /// (ADR-0030). Pass an id instead through
     /// [`create_asset`](Self::create_asset) to choose it.
     pub async fn asset(
@@ -113,8 +113,8 @@ impl Ledger {
     /// Fetch a registered asset, cached for the life of the process.
     ///
     /// A registry row never changes, so a hit is always current. A miss is
-    /// never cached: an asset registered after a failed lookup would otherwise
-    /// stay missing.
+    /// never cached. An asset registered after a failed lookup would otherwise
+    /// stay absent.
     pub async fn asset_by_id(&self, id: impl Into<AssetId>) -> Result<Arc<Asset>, LedgerError> {
         let id = &id.into();
         if let Some(asset) = self.assets.read().await.get(id) {

+ 80 - 72
crates/kuatia/src/ledger/balance.rs

@@ -3,21 +3,21 @@
 //!
 //! One concept, two computation strategies that must agree:
 //!
-//! - [`balance_exact`](Ledger::balance_exact) is **authoritative**: the sum
-//!   of the live (unspent) postings for one `(account, asset)`, always
-//!   recomputed from the source of truth. It is what validation reads, what the
-//!   projector folds into snapshots, and what reconciliation checks against.
+//! - [`balance_exact`](Ledger::balance_exact) is **authoritative**: the sum of
+//!   the live (unspent) postings for one `(account, asset)`, always recomputed
+//!   from the source of truth. It is what validation reads, what the projector
+//!   folds into snapshots, and what reconciliation checks against.
 //! - [`balance`](Ledger::balance) is the **everyday read**: the closest cache
 //!   point (at or before now) plus the folded tail of transfers committed after
 //!   its watermark. [`balance_as_of`](Ledger::balance_as_of) is that same read
 //!   bounded above by a past commit instant, which no live-posting sum can
 //!   answer because a posting carries no timestamp.
 //!
-//! The module's core contract: summing every one of an account's transfer deltas
-//! equals its live-posting sum, so **`balance` always equals `balance_exact` at
-//! rest**. Cache points are a pure optimization that shortens the tail;
-//! correctness never depends on them, and reconciliation re-derives the
-//! authoritative value to check against a cache point.
+//! The core contract of the module: the sum of every transfer delta of an
+//! account equals its live-posting sum. So **`balance` always equals
+//! `balance_exact` at rest**. Cache points are a pure optimization that
+//! shortens the tail. Correctness never depends on them, and reconciliation
+//! derives the authoritative value again to check it against a cache point.
 //!
 //! Balances are always computed in Rust with checked arithmetic and are never
 //! summed across subaccounts (ADR-0012).
@@ -41,7 +41,7 @@ use crate::error::LedgerError;
 pub struct SubAccountBalance {
     /// The subaccount this balance belongs to.
     pub account: AccountId,
-    /// What that subaccount holds, carrying the asset it is denominated in.
+    /// What that subaccount holds, with the asset it is denominated in.
     pub amount: Amount,
 }
 
@@ -51,11 +51,11 @@ pub struct SubAccountBalance {
 // `Ledger` below.
 // ---------------------------------------------------------------------------
 
-/// Fold the per-`(account, asset)` delta of a set of committed transfers,
-/// `Σ created(+) − Σ consumed(−)` restricted to postings owned by `account` in
-/// `asset`, and count how many such postings (credits + debits) were seen.
-/// Consumed postings are resolved from the immutable table (the envelope carries
-/// only their ids). All arithmetic is checked, in Rust.
+/// Fold the per-`(account, asset)` delta of a set of committed transfers. That
+/// delta is `Σ created(+) − Σ consumed(−)`, over the postings `account` owns in
+/// `asset`. Also count how many such postings (credits plus debits) were seen.
+/// Consumed postings are resolved from the immutable table, because the
+/// envelope carries only their ids. All arithmetic is checked, in Rust.
 async fn fold_account_delta(
     store: &dyn Store,
     account: &AccountId,
@@ -98,10 +98,11 @@ async fn fold_account_delta(
     Ok((delta, count))
 }
 
-/// Load the committed transfers involving `account` with commit time in
-/// `[from_ts, to_ts)` (both optional), then fold their `(account, asset)` delta
-/// and credit/debit count. `from_ts == None` spans from the beginning;
-/// `to_ts == None` spans to the newest committed transfer.
+/// Load the committed transfers that `account` takes part in, with a commit
+/// time in `[from_ts, to_ts)`, where both bounds are optional. Then fold their
+/// `(account, asset)` delta and their credit and debit count. `from_ts == None`
+/// spans from the first transfer; `to_ts == None` spans to the newest committed
+/// one.
 async fn fold_tail(
     store: &dyn Store,
     account: &AccountId,
@@ -120,21 +121,23 @@ async fn fold_tail(
     fold_account_delta(store, account, asset, &records).await
 }
 
-/// Append a fresh cache point for `(account, asset)`: fold the window since the
-/// closest cache point's watermark up to `now − grace` onto its snapshot, and
-/// append the result. Only appends when that window has at least `min_new`
-/// credits/debits, so a hot account that is read constantly does not append a
-/// near-duplicate row on every read (`min_new == 0` forces an append). Append-only
-/// and best effort; a stale or duplicate append is harmless because a read takes
-/// the closest-at-or-before cache point.
+/// Append a fresh cache point for `(account, asset)`. It folds the window from
+/// the watermark of the closest cache point up to `now − grace` onto that
+/// snapshot, then appends the result. It appends only when that window holds at
+/// least `min_new` credits and debits. So a hot account under constant reads
+/// does not append a near-duplicate row on every read. `min_new == 0` forces an
+/// append. Append-only and best effort: a stale or duplicate append is
+/// harmless, because a read takes the closest-at-or-before cache point.
 ///
-/// `debounce_ms` is the storage-based single-flight guard. When the newest cache
-/// point already sits within `debounce_ms` below the target watermark, this
-/// returns before the fold, so a hot account read at high QPS does not fan out a
-/// full fold per read. The guard lives in the shared `balance_projection` rows,
-/// not in process memory, so it dedups across every ledger instance and survives
-/// a restart, and it needs no lease, lock, or CAS (ADR-0019). `debounce_ms == 0`
-/// disables it (the reconcile path forces an append regardless).
+/// `debounce_ms` is the storage-based single-flight guard. It returns before
+/// the fold when the newest cache point already sits within `debounce_ms` below
+/// the target watermark. So a hot account read at high QPS does not fan out a
+/// full fold per read.
+///
+/// The guard lives in the shared `balance_projection` rows and not in process
+/// memory. So it dedups across every ledger instance, it survives a restart,
+/// and it needs no lease, lock or CAS (ADR-0019). `debounce_ms == 0` disables
+/// it, and the reconcile path forces an append whatever it is set to.
 pub(super) async fn append_cache_point(
     store: &dyn Store,
     grace_ms: i64,
@@ -182,12 +185,14 @@ pub(super) async fn append_cache_point(
 
 impl Ledger {
     /// The authoritative balance: the sum of the live (unspent) postings for
-    /// one `(account, asset)`. This bypasses the cached projection
-    /// and always recomputes from the source of truth, so it is what validation
+    /// one `(account, asset)`. It never reads the cached projection, and it
+    /// always computes from the source of truth again. So it is what validation
     /// reads, what the projector folds into snapshots, and what reconciliation
-    /// checks against. Still `O(live postings)`, but the SQL store adds them up
-    /// inside the database rather than shipping every row here; prefer
-    /// [`balance`](Ledger::balance) for the everyday read.
+    /// checks against.
+    ///
+    /// Still `O(live postings)`, but the SQL store adds them up inside the
+    /// database and sends no row here. Prefer [`balance`](Ledger::balance) for
+    /// the everyday read.
     pub async fn balance_exact(
         &self,
         account: &AccountId,
@@ -205,15 +210,17 @@ impl Ledger {
         Ok(self.store.live_balance(account, asset).await?)
     }
 
-    /// The everyday balance read for one subaccount and asset (ADR-0019): the
-    /// closest cache point (at or before now) plus the folded tail of transfers
-    /// committed after its watermark. Always equal to
+    /// The everyday balance read for one subaccount and asset (ADR-0019). It is
+    /// the closest cache point, at or before now, plus the folded tail of the
+    /// transfers committed after its watermark. Always equal to
     /// [`balance_exact`](Ledger::balance_exact) at rest, and faster once a
-    /// cache point keeps the tail short. With no cache point yet it returns the
-    /// authoritative live-posting sum directly (rather than folding the whole
-    /// history) and bootstraps a cache point in the background. Once enough
-    /// credits/debits have accrued since the closest cache point, it also appends
-    /// a new one in the background for later reads.
+    /// cache point keeps the tail short.
+    ///
+    /// With no cache point yet, it returns the authoritative live-posting sum
+    /// straight away and folds no history. It then bootstraps a cache point in
+    /// the background. Once enough credits and debits accrue since the closest
+    /// cache point, it also appends a new one in the background, for a later
+    /// read.
     pub async fn balance(
         &self,
         account: &AccountId,
@@ -263,19 +270,19 @@ impl Ledger {
     }
 
     /// The balance as it stood at `as_of`, a commit instant in unix
-    /// milliseconds: the closest cache point at or before `as_of`, plus the tail
-    /// of transfers committed after that point's watermark and up to `as_of`
-    /// (ADR-0019).
+    /// milliseconds. It is the closest cache point at or before `as_of`, plus
+    /// the tail of the transfers committed after the watermark of that point.
+    /// That tail runs up to `as_of` (ADR-0019).
     ///
-    /// `as_of` is commit time and never the value date, because the cache points
-    /// a read folds against are watermarked by the commit clock.
+    /// `as_of` is commit time and never the value date, because the commit
+    /// clock watermarks the cache points a read folds against.
     ///
-    /// With no cache point at or before `as_of`, this folds the whole history up
-    /// to it instead of taking the live-posting sum that
-    /// [`balance`](Ledger::balance) falls back on: a posting carries no
-    /// timestamp, so that sum is always "now". It also appends no cache point,
-    /// since a new one's watermark comes from the current clock and would
-    /// describe a window this read never looked at.
+    /// With no cache point at or before `as_of`, this folds the whole history
+    /// up to it. It does not take the live-posting sum that
+    /// [`balance`](Ledger::balance) falls back on, because a posting carries no
+    /// timestamp and that sum is always "now". It also appends no cache point.
+    /// The watermark of a new one comes from the current clock, and it would
+    /// name a window this read never looked at.
     pub async fn balance_as_of(
         &self,
         account: &AccountId,
@@ -314,11 +321,11 @@ impl Ledger {
 
     /// Report the per-subaccount balances of a base account for one asset.
     ///
-    /// One entry per non-closed subaccount, each read through the everyday cached
-    /// [`balance`](Ledger::balance) so every balance read goes through one path.
-    /// `sub == None` spans every subaccount of `account`'s base id; `Some(s)`
-    /// restricts to that one. Balances are never summed across subaccounts
-    /// (ADR-0012).
+    /// One entry per non-closed subaccount, each read through the everyday
+    /// cached [`balance`](Ledger::balance), so every balance read takes one
+    /// path. `sub == None` spans every subaccount of the base id of `account`;
+    /// `Some(s)` restricts to that one. Balances are never summed across
+    /// subaccounts (ADR-0012).
     pub async fn balances(
         &self,
         account: &AccountId,
@@ -368,7 +375,7 @@ impl Ledger {
 
     /// List the non-closed subaccounts of a base account.
     ///
-    /// This scans every account row and filters in memory, so it pays for
+    /// This scans every account row and filters in memory, so it pays for the
     /// subaccounts that were created and later closed (ADR-0012).
     #[instrument(skip(self), name = "ledger.list_subaccounts")]
     pub async fn list_subaccounts(
@@ -388,16 +395,17 @@ impl Ledger {
         Ok(subs)
     }
 
-    /// Spawn a best-effort background append gated on `snapshot_interval` new
-    /// credits/debits. Uses only the store handle and config, so it needs no
-    /// `Arc<Self>` and can run from a `&self` read.
+    /// Spawn a best-effort background append, gated on `snapshot_interval` new
+    /// credits and debits. It uses the store handle and the config alone, so it
+    /// needs no `Arc<Self>` and runs from a `&self` read.
     ///
-    /// Redundant spawns are cheap, not suppressed here: the storage-based debounce
-    /// inside [`append_cache_point`] (keyed on the newest shared cache-point row,
-    /// with `debounce_ms == grace`) returns before the fold when a recent cache
-    /// point already exists, so a hot account read at high QPS does at most one
-    /// fold per grace window, coordinated across every instance rather than in
-    /// this process's memory.
+    /// A redundant spawn is cheap, and nothing suppresses it here. The
+    /// storage-based debounce inside [`append_cache_point`] returns before the
+    /// fold when a recent cache point is already there. It keys on the newest
+    /// shared cache-point row, with `debounce_ms == grace`. So a hot account
+    /// read at high QPS does at most one fold per grace window. That is
+    /// coordinated across every instance, and not in the memory of this
+    /// process.
     fn spawn_append(&self, account: AccountId, asset: Arc<Asset>) {
         let store = Arc::clone(&self.store);
         let grace = self.projection.grace_ms;

+ 46 - 38
crates/kuatia/src/ledger/commit.rs

@@ -1,12 +1,14 @@
 //! The commit engine: resolve, validate, apply atomically, reverse.
 //!
 //! This is the deep core of the ledger. Every commit resolves a [`Transfer`]
-//! intent into a concrete [`Envelope`], validates it against loaded state in the
-//! pure core, and hands the validated effects to the store's atomic
-//! [`commit_envelope`](kuatia_storage::store::CommitStore::commit_envelope). The
-//! store applies them in one transaction and re-checks the stateful guards
-//! inside it, so there is no half-applied state and nothing to recover after a
-//! crash (ADR-0023, superseding the write-ahead saga of ADR-0003).
+//! intent into a concrete [`Envelope`], and validates it against loaded state
+//! in the pure core. It then hands the validated effects to the atomic
+//! [`commit_envelope`](kuatia_storage::store::CommitStore::commit_envelope) of
+//! the store.
+//!
+//! The store applies them in one transaction, and re-checks the stateful guards
+//! inside it. So there is no half-applied state, and nothing to recover after a
+//! crash (ADR-0023, which supersedes the write-ahead saga of ADR-0003).
 
 use std::collections::HashMap;
 use std::collections::hash_map::Entry;
@@ -30,13 +32,14 @@ use crate::error::LedgerError;
 
 /// State loaded in phase 1, passed to the pure validation in phase 2.
 struct LoadedState {
-    /// Postings being consumed by the envelope.
+    /// The postings the envelope consumes.
     consumed_postings: Vec<Posting>,
-    /// Accounts referenced by the envelope.
+    /// The accounts the envelope refers to.
     accounts: HashMap<AccountId, Account>,
-    /// Current balances for all referenced (account, asset) pairs.
+    /// Current balances for every (account, asset) pair named.
     balances: HashMap<(AccountId, AssetId), Cent>,
-    /// The book gating this transfer, if one is loaded (`None` = unrestricted default).
+    /// The book that gates this transfer, if one is loaded. `None` is the
+    /// unrestricted default.
     book: Option<Book>,
 }
 
@@ -45,7 +48,7 @@ impl Ledger {
     // Validation phases: load (read state) -> plan (pure validate)
     // -----------------------------------------------------------------------
 
-    /// Load all state needed for validation.
+    /// Load every piece of state validation needs.
     #[instrument(skip(self, envelope), name = "ledger.load")]
     async fn load(&self, envelope: &Envelope) -> Result<LoadedState, LedgerError> {
         let consumed_postings = if envelope.consumes().is_empty() {
@@ -119,15 +122,15 @@ impl Ledger {
     // Resolve: Transfer (intent) -> Envelope (concrete postings)
     // -----------------------------------------------------------------------
 
-    /// Convert a [`Transfer`] intent into a concrete [`Envelope`] by selecting
-    /// postings for each movement and computing change.
+    /// Convert a [`Transfer`] intent into a concrete [`Envelope`]. It selects
+    /// postings for each movement and computes the change.
     ///
-    /// The decision is pure ([`kuatia_core::draft_movements`] +
-    /// [`kuatia_core::resolve_envelope`]); this method only loads the state those
-    /// functions need. Pass 1 aggregates net debits and tells us which postings
-    /// and accounts to load; pass 2 selects postings, computes change, and covers
-    /// any overdraft shortfall (reading each account's own flag, the same one
-    /// validation reads).
+    /// The decision is pure ([`kuatia_core::draft_movements`] plus
+    /// [`kuatia_core::resolve_envelope`]), and this method loads the state
+    /// those functions need and nothing else. Pass 1 aggregates net debits, and
+    /// it names the postings and accounts to load. Pass 2 selects postings,
+    /// computes change, and covers any overdraft shortfall. It reads the own
+    /// flag of each account, which is the flag validation reads.
     #[instrument(skip(self, transfer), name = "ledger.resolve")]
     pub async fn resolve(&self, transfer: &Transfer) -> Result<Envelope, LedgerError> {
         let draft = draft_movements(transfer)?;
@@ -173,23 +176,28 @@ impl Ledger {
     // Commit: resolve (read-only) then apply atomically
     // -----------------------------------------------------------------------
 
-    /// Commit a [`Transfer`] intent. Resolves it into a concrete envelope, then
-    /// validates and applies it atomically. Resolution is read-only, and the
-    /// apply is one store transaction, so a crash leaves no partial state.
+    /// Commit a [`Transfer`] intent. It resolves the transfer into a concrete
+    /// envelope, then validates and applies it atomically. Resolution is
+    /// read-only, and the apply is one store transaction, so a crash leaves no
+    /// partial state.
     #[instrument(skip(self, transfer), fields(book = transfer.book.0), name = "ledger.commit")]
     pub async fn commit(&self, transfer: Transfer) -> Result<Receipt, LedgerError> {
         let envelope = self.resolve(&transfer).await?;
         self.commit_envelope(envelope).await
     }
 
-    /// Commit a pre-resolved [`Envelope`]. Validates it against loaded state,
-    /// then applies the validated effects through the store's atomic
-    /// [`commit_envelope`](kuatia_storage::store::CommitStore::commit_envelope):
-    /// one transaction that spends the consumed postings, creates the new ones,
-    /// stores the transfer, and appends the committed event, re-checking
-    /// double-spend, freeze/close, and the overdraft floor inside it. This is the
-    /// single commit path; `commit()` and `reverse()` both funnel through it, and
-    /// it is idempotent on the content-addressed transfer id.
+    /// Commit a pre-resolved [`Envelope`]. It validates the envelope against
+    /// loaded state, then applies the validated effects through the atomic
+    /// [`commit_envelope`](kuatia_storage::store::CommitStore::commit_envelope)
+    /// of the store.
+    ///
+    /// That is one transaction. It spends the consumed postings, creates the
+    /// new ones, stores the transfer, and appends the committed event. It also
+    /// re-checks double-spend, freeze/close and the overdraft floor inside
+    /// itself.
+    ///
+    /// This is the single commit path. `commit()` and `reverse()` both funnel
+    /// through it, and it is idempotent on the content-addressed transfer id.
     #[instrument(skip(self, envelope), name = "ledger.commit_envelope")]
     pub async fn commit_envelope(&self, mut envelope: Envelope) -> Result<Receipt, LedgerError> {
         if envelope.account_snapshots().is_empty() {
@@ -328,9 +336,9 @@ impl Ledger {
     }
 }
 
-/// Map a store-side [`CommitRejection`] to the typed ledger error callers match
-/// on, so a strict in-transaction guard surfaces the same error a snapshot-time
-/// validation would.
+/// Map a store-side [`CommitRejection`] to the typed ledger error a caller
+/// matches on. So a strict in-transaction guard surfaces the same error a
+/// snapshot-time validation would.
 fn map_rejection(reason: CommitRejection) -> LedgerError {
     match reason {
         CommitRejection::DoubleSpend(id) => LedgerError::DoubleSpend(id),
@@ -360,7 +368,7 @@ mod tests {
     use std::collections::BTreeMap;
 
     /// An amount of `asset` in minor units. An amount compares by asset id, so
-    /// building the row here is equivalent to reading it back from the registry.
+    /// a row built here is equivalent to one read back from the registry.
     fn money<V>(asset: AssetId, value: V) -> Amount
     where
         Amount: From<(V, std::sync::Arc<Asset>)>,
@@ -441,7 +449,7 @@ mod tests {
         );
     }
 
-    /// Committing into a frozen payer is rejected atomically: nothing moves.
+    /// A commit into a frozen payer is rejected atomically, and nothing moves.
     #[tokio::test]
     async fn commit_into_frozen_account_is_rejected() {
         let ledger = funded_ledger().await;
@@ -462,9 +470,9 @@ mod tests {
     }
 
     /// If the loader under-fetches a balance key validation reads, `plan` fails
-    /// loudly rather than letting the missing key default to zero and silently
-    /// approve an overdraft. This guards the async-loader / pure-core seam in
-    /// every build, not just debug.
+    /// loudly. An absent key would otherwise default to zero and silently
+    /// approve an overdraft. This guards the async-loader and pure-core seam in
+    /// every build, and not in a debug build alone.
     #[tokio::test]
     async fn plan_rejects_under_fetched_balance() -> Result<(), LedgerError> {
         let ledger = funded_ledger().await;

+ 4 - 4
crates/kuatia/src/ledger/connect.rs

@@ -1,5 +1,5 @@
-//! Opening a ledger on the SQL backend without naming `sqlx` or the storage
-//! crate: see [`Ledger::connect`].
+//! How to open a ledger on the SQL backend, and name neither `sqlx` nor the
+//! storage crate: see [`Ledger::connect`].
 
 use kuatia_storage_sql::SqlStore;
 
@@ -10,8 +10,8 @@ impl Ledger {
     /// Open the ledger database at `db_url`, apply the schema, and wrap it.
     ///
     /// The URL scheme selects the backend (`sqlite::memory:`,
-    /// `sqlite://kuatia.db`, `postgres://user:pass@host/db`). Pool sizing and
-    /// the SQLite driver setup belong to [`SqlStore::connect`]; build the store
+    /// `sqlite://kuatia.db`, `postgres://user:pass@host/db`). The pool size and
+    /// the SQLite driver setup belong to [`SqlStore::connect`]. Build the store
     /// yourself and pass it to [`new`](Ledger::new) to choose them.
     pub async fn connect(db_url: &str) -> Result<Self, LedgerError> {
         Ok(Self::new(SqlStore::connect(db_url).await?))

+ 14 - 12
crates/kuatia/src/ledger/lifecycle.rs

@@ -1,13 +1,15 @@
 //! Account lifecycle: create, freeze, unfreeze, close.
 //!
-//! Accounts are append-only and versioned: each mutation appends a new version
-//! rather than editing in place. Freeze/close guards are validate-time and
-//! best-effort under concurrency (see the dumb-storage ADR).
+//! Accounts are append-only and versioned: each change appends a new version
+//! and edits nothing in place. The store re-checks the version chain and an
+//! already-closed account inside its own transaction (ADR-0023). The emptiness
+//! test that `close` adds runs before that transaction.
 //!
-//! Freeze, unfreeze, and close are the same version-bump-plus-event shape; they
-//! delegate it to [`Ledger::transition`](super::transition), which carries the
-//! write-ahead / crash-repair path. Each method here supplies only the flag
-//! mutation, the lifecycle event, and any transition-specific guard.
+//! Freeze, unfreeze and close are the same version-bump-plus-event shape, and
+//! they delegate it to [`Ledger::transition`](super::transition). That applies
+//! the version and its event as one atomic store write. Each method here
+//! supplies only the flag mutation, the lifecycle event, and any guard of its
+//! own.
 
 use tracing::instrument;
 
@@ -34,7 +36,7 @@ impl Ledger {
         Ok(())
     }
 
-    /// Freeze an account, preventing all transfers.
+    /// Freeze an account, so every transfer on it fails.
     #[instrument(skip(self), name = "ledger.freeze")]
     pub async fn freeze(&self, id: &AccountId) -> Result<(), LedgerError> {
         self.transition(
@@ -65,10 +67,10 @@ impl Ledger {
     /// Close an account. Must have no live postings.
     #[instrument(skip(self), name = "ledger.close")]
     pub async fn close(&self, id: &AccountId) -> Result<(), LedgerError> {
-        // Emptiness is close's own guard, checked before the transition's
-        // write-ahead so a non-empty account records nothing. A closed account
-        // holds no live postings, so this ordering still surfaces
-        // `AccountAlreadyClosed` (from `transition`) for a re-close.
+        // Emptiness is close's own guard, checked before the transition so a
+        // non-empty account records nothing. A closed account holds no live
+        // postings, so this order still surfaces `AccountAlreadyClosed` (from
+        // `transition`) for a re-close.
         if self.has_live_postings(id).await? {
             return Err(LedgerError::AccountNotEmpty(*id));
         }

+ 8 - 8
crates/kuatia/src/ledger/projection.rs

@@ -1,7 +1,7 @@
 //! The balance projection's maintenance surface (ADR-0019).
 //!
-//! Kept apart from the balance reads in [`balance`](super::balance) because
-//! nothing here answers what an account holds: these operations manage the
+//! Kept apart from the balance reads in [`balance`](super::balance), because
+//! nothing here answers what an account holds. These operations manage the
 //! disposable cache that makes those reads fast.
 
 use kuatia_core::{AccountId, AssetId};
@@ -21,13 +21,13 @@ impl<'a> Projection<'a> {
         Self { ledger }
     }
 
-    /// Append a cache point for one `(account, asset)` now, folding up to
-    /// `now - grace`, whether or not one is due.
+    /// Append a cache point for one `(account, asset)` now, with the fold up to
+    /// `now - grace`, whether one is due or not.
     ///
-    /// Reads already append lazily in the background, so a caller needs this
-    /// only to pin a snapshot at a chosen moment, as an audit or a test does.
-    /// Append-only: a repeat inside the same grace-adjusted millisecond adds
-    /// nothing, since that watermark is already covered.
+    /// A read already appends lazily in the background. So a caller needs this
+    /// only to pin a snapshot at a chosen moment, the way an audit or a test
+    /// does. Append-only: a repeat inside the same grace-adjusted millisecond
+    /// adds nothing, because that watermark is already covered.
     pub async fn append_cache_point(
         &self,
         account: &AccountId,

+ 9 - 8
crates/kuatia/src/ledger/query.rs

@@ -1,9 +1,9 @@
 //! Read-only queries and book CRUD.
 //!
 //! These methods delegate to the [`Store`] and relabel `StoreError` as
-//! [`LedgerError`] so callers get one error type across the whole API. The
-//! underlying store is reachable via [`Ledger::store`] for callers that want the
-//! raw storage error instead.
+//! [`LedgerError`], so a caller gets one error type across the whole API. The
+//! store itself is reachable through [`Ledger::store`], for a caller that wants
+//! the raw storage error instead.
 
 use kuatia_core::{
     Account, AccountId, Book, BookId, Posting, PostingFilter, PostingId, PostingState,
@@ -28,7 +28,8 @@ impl Ledger {
             .map_err(|_| LedgerError::AccountNotFound(*id))
     }
 
-    /// Return all transfers involving the given account (exact subaccount).
+    /// Return every transfer the given account takes part in (exact
+    /// subaccount).
     pub async fn history(&self, account: &AccountId) -> Result<Vec<TransferRecord>, LedgerError> {
         Ok(self
             .store
@@ -36,7 +37,7 @@ impl Ledger {
             .await?)
     }
 
-    /// Query transfers with filtering and pagination.
+    /// Query transfers, with the filters and the page window applied.
     pub async fn query_transfers(
         &self,
         query: &TransferQuery,
@@ -53,8 +54,8 @@ impl Ledger {
     }
 
     /// Postings by id from the immutable record. A consumed posting still
-    /// resolves here, which is what lets a reader show the debit side of a
-    /// committed envelope; the envelope stores consumed ids alone.
+    /// resolves here. That is what lets a reader show the debit side of a
+    /// committed envelope, which stores consumed ids alone.
     pub async fn get_postings(&self, ids: &[PostingId]) -> Result<Vec<Posting>, LedgerError> {
         Ok(self.store.get_postings(ids).await?)
     }
@@ -71,7 +72,7 @@ impl Ledger {
         Ok(postings.into_iter().zip(states).collect())
     }
 
-    /// Query postings with filtering and pagination.
+    /// Query postings, with the filters and the page window applied.
     pub async fn query_postings(&self, query: &PostingQuery) -> Result<Page<Posting>, LedgerError> {
         Ok(self.store.query_postings(query).await?)
     }

+ 11 - 11
crates/kuatia/src/ledger/transition.rs

@@ -1,14 +1,14 @@
 //! One account-version transition, shared by freeze / unfreeze / close.
 //!
-//! Every lifecycle flag change is the same shape: load the account, reject if it
-//! is already closed, then append a new version with the flag flipped and the
-//! matching lifecycle event. This module holds that shape once, parameterized by
-//! the flag mutation and the event.
+//! Every lifecycle flag change is the same shape. Load the account, and reject
+//! it if it is already closed. Then append a new version with the flag flipped,
+//! and the lifecycle event that goes with it. This module holds that shape
+//! once, parameterized by the flag mutation and the event.
 //!
 //! The version append and the event append are one atomic store write
 //! ([`commit_transition`](kuatia_storage::store::CommitStore::commit_transition)),
-//! so a crash cannot leave a version bump with no event. The store re-checks the
-//! version chain and a closed account inside the transaction.
+//! so a crash cannot leave a version bump with no event. The store re-checks
+//! the version chain and a closed account inside the transaction.
 
 use kuatia_core::{AccountFlags, AccountId};
 use kuatia_storage::events::{LedgerEvent, LedgerEventKind};
@@ -18,12 +18,12 @@ use super::{Ledger, now_millis};
 use crate::error::LedgerError;
 
 impl Ledger {
-    /// Append one new account version with `mutate` applied to its flags, then
-    /// emit the lifecycle event produced by `make_event` (given the account id and
-    /// the new version), atomically. Rejects a closed account.
+    /// Append one new account version with `mutate` applied to its flags. Then
+    /// emit the lifecycle event `make_event` produces from the account id and
+    /// the new version. Both land atomically. Rejects a closed account.
     ///
-    /// Callers layer any transition-specific guard (e.g. close's emptiness check)
-    /// before calling this.
+    /// A caller layers any guard of its own, such as the emptiness check of
+    /// `close`, before it calls this.
     pub(super) async fn transition(
         &self,
         id: &AccountId,

+ 8 - 8
crates/kuatia/src/lib.rs

@@ -1,15 +1,15 @@
 //! Kuatia: async ledger resource built on top of [`kuatia_core`].
 //!
-//! This crate adds IO to the pure decision logic: the [`Store`](kuatia_storage::store::Store)
-//! trait abstracts storage, and the [`Ledger`](crate::ledger::Ledger) struct resolves a
-//! transfer and hands it to the store as one atomic commit (ADR-0023) behind an
-//! async API.
+//! This crate adds IO to the pure decision logic. The
+//! [`Store`](kuatia_storage::store::Store) trait abstracts storage. The
+//! [`Ledger`](crate::ledger::Ledger) struct resolves a transfer and hands it to
+//! the store as one atomic commit (ADR-0023), behind an async API.
 //!
-//! It is the only crate an application names in `Cargo.toml`: the whole chain
-//! is re-exported here, the SQL backend as [`sql`] behind the `sqlite` or
+//! It is the only crate an application names in `Cargo.toml`. The whole chain
+//! is re-exported here, and the SQL backend as [`sql`] behind the `sqlite` or
 //! `postgres` feature. The other crates stay published for custom development,
-//! such as a hand-written [`Store`](kuatia_storage::store::Store) or an
-//! embedding of the pure core on its own.
+//! such as a hand-written [`Store`](kuatia_storage::store::Store), or the pure
+//! core embedded on its own.
 
 pub mod error;
 pub mod inflight;

+ 3 - 3
crates/kuatia/src/prelude.rs

@@ -1,7 +1,7 @@
-//! Common imports for building on the ledger.
+//! The common imports an application needs to build on the ledger.
 //!
-//! `use kuatia::prelude::*;` brings the domain types and intent builders from
-//! [`kuatia_core`] into scope, along with the [`Ledger`] resource, the
+//! `use kuatia::prelude::*;` brings the domain types and the intent builders
+//! from [`kuatia_core`] into scope. It also brings the [`Ledger`] resource, the
 //! [`Store`] trait, the [`InMemoryStore`] and, with the `sql` feature, the
 //! [`SqlStore`]. Reach for [`kuatia_core`] or [`crate::sql`] when you need a
 //! type the prelude does not surface.

+ 11 - 10
crates/kuatia/src/workflow.rs

@@ -1,21 +1,22 @@
 //! Multi-transfer composition over the ledger.
 //!
-//! [`run_transfers`] commits a sequence of transfers in order and, on the first
-//! failure, reverses the already-committed ones in LIFO order via
-//! [`Ledger::reverse`], so several transfers behave as one all-or-nothing
-//! workflow (an FX trade, a multi-leg settlement). Each single commit is already
-//! atomic in the store (ADR-0023); this adds only the cross-transfer unwind,
-//! which is why it needs no state of its own.
+//! [`run_transfers`] commits a sequence of transfers in order. On the first
+//! failure it reverses the committed ones in LIFO order, through
+//! [`Ledger::reverse`]. So several transfers behave as one all-or-nothing
+//! workflow, such as an FX trade or a multi-leg settlement.
+//!
+//! Each single commit is already atomic in the store (ADR-0023). This adds the
+//! cross-transfer unwind alone, which is why it needs no state of its own.
 
 use kuatia_core::{Receipt, Transfer};
 
 use crate::error::LedgerError;
 use crate::ledger::Ledger;
 
-/// Commit each transfer in order, returning the receipts. On the first failure,
-/// reverse the already-committed receipts in LIFO order and return the original
-/// error. If a reversal itself fails, return [`LedgerError::CompensationFailed`]
-/// carrying both the original and the compensation error.
+/// Commit each transfer in order and return the receipts. On the first failure,
+/// reverse the committed receipts in LIFO order and return the original error.
+/// If a reversal itself fails, return [`LedgerError::CompensationFailed`],
+/// which carries both the original and the compensation error.
 pub async fn run_transfers(
     ledger: &Ledger,
     transfers: &[Transfer],

+ 43 - 40
crates/kuatia/tests/concurrency.rs

@@ -1,15 +1,15 @@
 //! Concurrency tests for the atomic commit path over `InMemoryStore`.
 //!
 //! A commit resolves and validates read-only, then hands the effects to the
-//! store's atomic `commit_envelope`, which applies them (and re-checks
-//! double-spend, freeze/close, and the floor) under one set of locks. The races
-//! worth testing are therefore between concurrent commits that share one
+//! atomic `commit_envelope` of the store. That applies them under one set of
+//! locks, and it re-checks double-spend, freeze/close and the floor. So the
+//! races worth a test are the ones between concurrent commits that share one
 //! `Arc<Ledger>` and contend on the same postings or account. The generated
-//! conformance suite only drives the store sequentially, so none of this is
-//! covered there.
+//! conformance suite drives the store sequentially alone, so it covers none of
+//! this.
 //!
-//! These tests run on a multi-thread runtime and use `tokio::spawn` so the
-//! commits genuinely interleave rather than run to completion one at a time.
+//! These tests run on a multi-thread runtime and use `tokio::spawn`, so the
+//! commits genuinely interleave and do not run to completion one at a time.
 
 #![allow(missing_docs)]
 
@@ -21,8 +21,8 @@ use kuatia::mem_store::InMemoryStore;
 use kuatia_core::*;
 
 /// An amount of `asset` in minor units. An amount compares by asset id, and the
-/// tests register these same ids, so building the row here is equivalent to
-/// reading it back from the registry.
+/// tests register these same ids. So a row built here is equivalent to one read
+/// back from the registry.
 fn money<V>(asset: AssetId, value: V) -> Amount
 where
     Amount: From<(V, Arc<Asset>)>,
@@ -61,7 +61,8 @@ async fn register_assets(ledger: &Arc<Ledger>) {
         .unwrap();
 }
 
-/// A ledger with overdraft-forbidding accounts `1..=n` plus an external account.
+/// A ledger with accounts `1..=n` that forbid overdraft, plus an external
+/// account.
 async fn ledger_with_accounts(n: i64) -> Arc<Ledger> {
     let ledger = Arc::new(Ledger::new(InMemoryStore::new()));
     for id in 1..=n {
@@ -92,12 +93,11 @@ async fn deposit(ledger: &Arc<Ledger>, to: AccountId, amount: i64) {
 // 1. Double-spend prevention (the headline invariant)
 // ---------------------------------------------------------------------------
 
-/// Many transfers concurrently try to spend the *same* funded posting to
-/// different recipients. Exactly one may win: inside the atomic commit the
-/// winner deletes the single live posting, and every other commit finds it gone
-/// and is rejected with `DoubleSpend`.
-/// The ledger stays conserved: the payer ends at zero and exactly one recipient
-/// receives the full amount.
+/// Many transfers try to spend the *same* funded posting at once, to different
+/// recipients. Exactly one can win. Inside the atomic commit the winner deletes
+/// the single live posting, and every other commit finds it gone and is
+/// rejected with `DoubleSpend`. The ledger stays conserved: the payer ends at
+/// zero and exactly one recipient receives the full amount.
 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
 async fn concurrent_double_spend_has_one_winner() {
     const RECIPIENTS: i64 = 8;
@@ -158,9 +158,9 @@ async fn concurrent_double_spend_has_one_winner() {
 // 2. Idempotency
 // ---------------------------------------------------------------------------
 
-/// Re-committing an already-committed envelope returns the same receipt and does
-/// not move value a second time. This is the sequential idempotency contract
-/// that `commit_envelope` guarantees via its content-addressed short-circuit.
+/// A second commit of an already-committed envelope returns the same receipt
+/// and moves no value again. This is the sequential idempotency contract that
+/// `commit_envelope` guarantees, through its content-addressed short-circuit.
 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
 async fn recommit_same_envelope_is_idempotent() {
     let ledger = ledger_with_accounts(2).await;
@@ -194,11 +194,11 @@ async fn recommit_same_envelope_is_idempotent() {
     );
 }
 
-/// The same envelope committed concurrently from many tasks. Because the
-/// content-addressed id is the idempotency key, value moves exactly once no
-/// matter how the commits interleave: one task applies the transfer and the rest
-/// observe the stored record and return its receipt. Every successful receipt is
-/// identical, and the balances move once.
+/// The same envelope committed at once from many tasks. The content-addressed
+/// id is the idempotency key, so value moves exactly once whatever order the
+/// commits interleave in. One task applies the transfer, and the rest see the
+/// stored record and return its receipt. Every successful receipt is identical,
+/// and the balances move once.
 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
 async fn concurrent_identical_commits_move_value_once() {
     const TASKS: usize = 8;
@@ -266,14 +266,16 @@ async fn concurrent_identical_commits_move_value_once() {
 // 3. Freeze vs. commit race
 // ---------------------------------------------------------------------------
 
-/// Freezing an account concurrently with a payment out of it must leave a
-/// consistent state. The freeze is an atomic transition and the payment is an
-/// atomic commit that re-checks the account's frozen flag inside its
-/// transaction, so the two serialize one way or the other: either the payment
-/// commits first and the freeze lands on top, or the freeze commits first and
-/// the payment's in-transaction freeze check rejects the now-frozen account.
-/// There is no middle ground where value moves out of a frozen account. Value is
-/// always conserved and the payment is all-or-nothing.
+/// A freeze of an account at the same time as a payment out of it must leave a
+/// consistent state. The freeze is an atomic transition. The payment is an
+/// atomic commit that re-checks the frozen flag of the account inside its own
+/// transaction.
+///
+/// So the two serialize one way or the other. Either the payment commits first
+/// and the freeze lands on top, or the freeze commits first. The in-transaction
+/// freeze check of the payment then rejects the account. There is no middle
+/// ground where value moves out of a frozen account. Value is always conserved,
+/// and the payment is all-or-nothing.
 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
 async fn freeze_during_commit_stays_consistent() {
     // Race is timing-dependent; run several fresh rounds to sample interleavings.
@@ -340,10 +342,10 @@ async fn freeze_during_commit_stays_consistent() {
 // 4. Disjoint transfers all commit and conserve
 // ---------------------------------------------------------------------------
 
-/// Concurrent transfers over non-overlapping accounts never contend, so all of
-/// them commit and total value is conserved. This is the throughput counterpart
-/// to the double-spend test: parallelism is only constrained where postings are
-/// actually shared.
+/// Concurrent transfers over accounts that do not overlap never contend, so all
+/// of them commit and total value is conserved. This is the throughput
+/// counterpart to the double-spend test. Only a shared posting constrains the
+/// parallelism.
 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
 async fn disjoint_transfers_all_commit_and_conserve() {
     const PAIRS: i64 = 8;
@@ -386,10 +388,11 @@ async fn disjoint_transfers_all_commit_and_conserve() {
 // 5. Concurrent overdraft conserves value
 // ---------------------------------------------------------------------------
 
-/// An overdraft account (no `DEBIT_MUST_NOT_EXCEED_CREDIT` flag) can be spent
-/// past its balance concurrently; every shortfall becomes a real negative
-/// posting, never minted value. This asserts the invariant that always holds:
-/// per-asset conservation, even under concurrent overdraft.
+/// An overdraft account, which carries no `DEBIT_MUST_NOT_EXCEED_CREDIT` flag,
+/// can be spent past its balance by several tasks at once. Every shortfall
+/// becomes a real negative posting, and never minted value. This asserts the
+/// invariant that always holds: per-asset conservation, under a concurrent
+/// overdraft too.
 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
 async fn concurrent_overdraft_conserves_value() {
     const PAYEES: i64 = 8;

+ 30 - 29
crates/kuatia/tests/inflight.rs

@@ -1,7 +1,7 @@
 //! Integration tests for inflight holds (authorize / confirm / void).
 //!
-//! The running example is the ADR's confirmed trade between A and B with a fee
-//! account, spanning two assets:
+//! The example here is the confirmed trade of the record, between A and B with
+//! a fee account, over two assets:
 //!
 //! ```text
 //! A -> B   -> 100 EUR
@@ -10,8 +10,8 @@
 //! B -> fee ->   1 EUR
 //! ```
 //!
-//! Authorized, the funds park in per-destination holding accounts; `fee`'s hold
-//! collects EUR from B and BTC from A.
+//! Once authorized, the funds park in per-destination holding accounts. The
+//! hold of `fee` collects EUR from B and BTC from A.
 
 use std::collections::BTreeMap;
 use std::sync::Arc;
@@ -19,8 +19,8 @@ use std::sync::Arc;
 use kuatia::prelude::*;
 
 /// An amount of `asset` in minor units. An amount compares by asset id, and the
-/// tests register these same ids, so building the row here is equivalent to
-/// reading it back from the registry.
+/// tests register these same ids. So a row built here is equivalent to one read
+/// back from the registry.
 fn money<V>(asset: AssetId, value: V) -> Amount
 where
     Amount: From<(V, Arc<Asset>)>,
@@ -65,8 +65,8 @@ async fn deposit(ledger: &Arc<Ledger>, to: AccountId, asset: AssetId, amount: i6
     ledger.commit(t).await.unwrap();
 }
 
-/// A ledger with accounts A, B, fee, external; A holds 100 EUR + 1 BTC, B holds
-/// 10 BTC + 1 EUR.
+/// A ledger with accounts A, B, fee and external. A holds 100 EUR plus 1 BTC,
+/// and B holds 10 BTC plus 1 EUR.
 async fn setup() -> Arc<Ledger> {
     let ledger = Arc::new(Ledger::new(InMemoryStore::new()));
     for id in [1, 2, 3] {
@@ -113,7 +113,7 @@ async fn bal(ledger: &Arc<Ledger>, account: AccountId, asset: AssetId) -> i128 {
 }
 
 /// A one-movement confirm set, built with the same `.pay()` interface as a
-/// transfer: `from` is the leg's funder, `to` its destination.
+/// transfer. `from` is the funder of the leg, and `to` is its destination.
 fn confirm_one(from: AccountId, to: AccountId, asset: AssetId, amount: i64) -> Transfer {
     TransferBuilder::new()
         .pay(from, to, money(asset, amount))
@@ -121,8 +121,8 @@ fn confirm_one(from: AccountId, to: AccountId, asset: AssetId, amount: i64) -> T
         .unwrap()
 }
 
-/// After authorize, funds leave the payers and sit in the holds; the payers'
-/// balances drop to zero and nothing has reached the destinations yet.
+/// After an authorize, funds leave the payers and sit in the holds. The
+/// balances of the payers drop to zero, and the destinations have nothing yet.
 #[tokio::test]
 async fn authorize_parks_funds_in_holds() {
     let ledger = setup().await;
@@ -155,7 +155,7 @@ async fn authorize_parks_funds_in_holds() {
     assert_eq!(total_held, total_auth);
 }
 
-/// Confirming the whole transaction settles every leg to its destination and
+/// A confirm of the whole transaction settles every leg to its destination and
 /// closes the holds. The net result equals the original trade.
 #[tokio::test]
 async fn confirm_all_settles_to_destinations() {
@@ -175,8 +175,8 @@ async fn confirm_all_settles_to_destinations() {
     assert_eq!(status.state, InflightState::Confirmed);
 }
 
-/// Voiding returns every held posting to the funder recorded in the leg table,
-/// including the multi-asset fee hold funded by two different accounts.
+/// A void returns every held posting to the funder the leg table records. That
+/// covers the multi-asset fee hold, which two different accounts funded.
 #[tokio::test]
 async fn void_returns_funds_to_funders() {
     let ledger = setup().await;
@@ -197,7 +197,7 @@ async fn void_returns_funds_to_funders() {
     assert_eq!(status.state, InflightState::Voided);
 }
 
-/// A partial confirm delivers a slice and leaves the remainder held. Confirming
+/// A partial confirm delivers a slice and leaves the rest held. A confirm of
 /// the rest drains and closes the hold.
 #[tokio::test]
 async fn partial_confirm_then_confirm_remainder() {
@@ -238,8 +238,8 @@ async fn partial_confirm_then_confirm_remainder() {
     );
 }
 
-/// A partial confirm followed by a void: the slice reaches the destination and
-/// the remainder returns to the funder.
+/// A partial confirm and then a void. The slice reaches the destination, and
+/// the rest returns to the funder.
 #[tokio::test]
 async fn partial_confirm_then_void_remainder() {
     let ledger = setup().await;
@@ -269,7 +269,7 @@ async fn partial_confirm_then_void_remainder() {
     assert_eq!(status.state, InflightState::Mixed);
 }
 
-/// Confirming more than is held is rejected. The `NoOverdraft` hold makes
+/// A confirm of more than is held is rejected. The `NoOverdraft` hold makes
 /// over-confirmation impossible.
 #[tokio::test]
 async fn over_confirm_is_rejected() {
@@ -312,7 +312,7 @@ async fn batch_confirm_multiple_legs() {
     assert_eq!(status.state, InflightState::PartiallyConfirmed);
 }
 
-/// Confirming a movement whose `(from, to, asset)` matches no leg is rejected.
+/// A confirm of a movement whose `(from, to, asset)` has no leg is rejected.
 #[tokio::test]
 async fn confirm_unknown_leg_is_rejected() {
     let ledger = setup().await;
@@ -326,9 +326,9 @@ async fn confirm_unknown_leg_is_rejected() {
     assert!(matches!(err, LedgerError::InflightLegNotFound { .. }));
 }
 
-/// A destination can hold several concurrent inflights (one per distinct trade,
-/// each under its own subaccount), but the *same* trade cannot be authorized
-/// twice while open (its holds already exist).
+/// A destination can hold several inflights at once, one per distinct trade,
+/// each under its own subaccount. The *same* trade cannot be authorized twice
+/// while it is open, because its holds are already there.
 #[tokio::test]
 async fn concurrent_inflights_per_account() {
     let ledger = setup().await;
@@ -378,7 +378,8 @@ async fn reauthorize_after_settlement() {
     assert_eq!(bal(&ledger, fee(), eur()).await, 31);
 }
 
-/// Operating on a non-inflight or unknown transfer id is a clean error.
+/// A call against a transfer id that is unknown, or not an inflight, is a clean
+/// error.
 #[tokio::test]
 async fn unknown_inflight_is_an_error() {
     let ledger = setup().await;
@@ -389,8 +390,8 @@ async fn unknown_inflight_is_an_error() {
     ));
 }
 
-/// Balances are always segregated by subaccount: the account query lists the
-/// main subaccount and each open hold separately, never summed.
+/// Balances are always segregated by subaccount. The account query lists the
+/// main subaccount and each open hold separately, and never sums them.
 #[tokio::test]
 async fn balances_are_segregated_by_subaccount() {
     let ledger = setup().await;
@@ -431,8 +432,8 @@ async fn a_hold_without_an_expiry_is_never_swept() {
     assert_eq!(bal(&ledger, a(), eur()).await, 0, "funds are still held");
 }
 
-/// An expiry in the future is a permission, not a schedule: nothing moves until
-/// the sweep runs with a clock past it.
+/// An expiry in the future is a permission and not a schedule. Nothing moves
+/// until the sweep runs with a clock past it.
 #[tokio::test]
 async fn a_hold_is_swept_only_once_its_expiry_has_passed() {
     let ledger = setup().await;
@@ -481,8 +482,8 @@ async fn expiry_returns_the_remainder_and_leaves_confirmations() {
     );
 }
 
-/// Sweeping twice is not an error and moves nothing the second time: the holds
-/// are drained and closed, so there is no inflight left to find.
+/// A second sweep is not an error, and it moves nothing. The holds are drained
+/// and closed, so no inflight is left to find.
 #[tokio::test]
 async fn sweeping_twice_moves_nothing_the_second_time() {
     let ledger = setup().await;

+ 27 - 25
crates/kuatia/tests/integration.rs

@@ -10,8 +10,8 @@ use kuatia_core::*;
 use std::collections::BTreeMap;
 
 /// An amount of `asset` in minor units. An amount compares by asset id, and the
-/// tests register these same ids, so building the row here is equivalent to
-/// reading it back from the registry.
+/// tests register these same ids. So a row built here is equivalent to one read
+/// back from the registry.
 fn money<V>(asset: AssetId, value: V) -> Amount
 where
     Amount: From<(V, Arc<Asset>)>,
@@ -893,8 +893,9 @@ async fn close_account_with_balance_rejected() {
     );
 }
 
-/// Paying the whole balance leaves no change posting, so the account holds
-/// nothing live and closing it is allowed: spent postings do not block close.
+/// A payment of the whole balance leaves no change posting. So the account
+/// holds nothing live and a close is allowed, because a spent posting does not
+/// block one.
 #[tokio::test]
 async fn close_succeeds_once_postings_are_spent() {
     let ledger = setup_ledger().await;
@@ -1149,7 +1150,7 @@ async fn overdraft_creates_negative_posting() {
             .unwrap();
     }
 
-    // Fund account 10 with 50, then pay 100 — overdraft covers the 50 shortfall.
+    // Fund account 10 with 50, then pay 100: overdraft covers the 50 shortfall.
     deposit(&ledger, account(10), usd(), 50, external()).await;
     pay(&ledger, account(10), account(2), usd(), 100).await;
 
@@ -1446,9 +1447,9 @@ async fn an_unregistered_asset_is_not_found() {
     assert!(matches!(err, LedgerError::AssetNotFound(id) if id == usd()));
 }
 
-/// A second registration is refused rather than merged, because a row is
-/// immutable: changing the precision would reinterpret every amount already
-/// recorded against the asset.
+/// A second registration is refused and not merged, because a row is immutable.
+/// A new precision would reinterpret every amount already recorded against the
+/// asset.
 #[tokio::test]
 async fn registering_a_known_asset_is_refused() {
     let ledger = bare_ledger();
@@ -1497,8 +1498,8 @@ async fn a_balance_carries_the_asset_it_was_read_for() {
     );
 }
 
-/// The bug the type exists to stop: two balances from one ledger, in different
-/// assets, refusing to be added instead of producing a number denominated in
+/// The bug the type exists to stop. Two balances from one ledger, in different
+/// assets, refuse an addition. They do not give back a number denominated in
 /// nothing.
 #[tokio::test]
 async fn two_assets_from_one_ledger_do_not_add() {
@@ -1518,8 +1519,8 @@ async fn two_assets_from_one_ledger_do_not_add() {
     assert_eq!(dollars.checked_add(&dollars).unwrap().minor_units(), 200);
 }
 
-/// A shortfall names the asset that fell short, so a caller reporting it does
-/// not have to guess which one the two values are in.
+/// A shortfall names the asset that fell short. So a caller that reports it
+/// does not have to guess which asset the two values are in.
 #[tokio::test]
 async fn insufficient_funds_names_the_asset() {
     let ledger = setup_ledger().await;
@@ -1566,9 +1567,9 @@ async fn committing_an_unregistered_asset_is_refused() {
     assert!(ledger.history(&account(1)).await.unwrap().is_empty());
 }
 
-/// Every way of naming an asset reaches the same read: the shared handle, the
-/// registry row, and the bare id. A spelling the docs show and nothing compiles
-/// is how two defects on this branch hid, so they are pinned here.
+/// Every way to name an asset reaches the same read: the shared handle, the
+/// registry row and the bare id. Two defects on this branch hid in a form the
+/// docs show and nothing compiles, so each form is pinned here.
 #[tokio::test]
 async fn an_asset_can_be_named_by_handle_row_or_id() {
     let ledger = setup_ledger().await;
@@ -1596,8 +1597,8 @@ async fn an_asset_can_be_named_by_handle_row_or_id() {
     assert_eq!(book.policy.allowed_assets, vec![usd(), usd(), usd()]);
 }
 
-/// Naming an asset by code registers it on first sight and returns the same
-/// handle afterwards, so setup code calls it unconditionally.
+/// A call by code registers the asset on first sight and returns the same
+/// handle after that, so setup code calls it unconditionally.
 #[tokio::test]
 async fn naming_an_asset_by_code_registers_it_once() {
     let ledger = bare_ledger();
@@ -1624,9 +1625,9 @@ async fn naming_an_asset_by_code_registers_it_once() {
     );
 }
 
-/// A code already registered at another precision is refused. Returning the
-/// stored row would format every later amount at a scale the caller did not ask
-/// for, and the row cannot be rewritten.
+/// A code already registered at another precision is refused. A return of the
+/// stored row would format every later amount at the wrong scale, and nothing
+/// can rewrite the row.
 #[tokio::test]
 async fn redefining_an_asset_is_refused() {
     let ledger = bare_ledger();
@@ -1666,9 +1667,10 @@ async fn minted_asset_ids_are_positive() {
 /// Conservation nets to zero in each asset, read one account at a time.
 ///
 /// Value inside the ledger is mirrored by the offset postings that brought it
-/// in, so the accounts in play net to zero. Summed from per-account reads
-/// because that is the only balance read there is (ADR-0031), which also means
-/// a missing account makes the total non-zero rather than quietly shrinking it.
+/// in, so the accounts in play net to zero. The total is summed from
+/// per-account reads, because that is the only balance read there is
+/// (ADR-0031). So an account left out makes the total non-zero, and does not
+/// quietly shrink it.
 #[tokio::test]
 async fn conservation_nets_to_zero_across_the_accounts_in_play() {
     let ledger = setup_ledger().await;
@@ -1698,8 +1700,8 @@ async fn conservation_nets_to_zero_across_the_accounts_in_play() {
     );
 }
 
-/// What one account holds, across every registered asset, skipping the assets
-/// it has no live posting of.
+/// What one account holds, across every registered asset. It leaves out an
+/// asset the account has no live posting of.
 #[tokio::test]
 async fn holdings_lists_every_asset_an_account_holds() {
     let ledger = setup_ledger().await;

+ 52 - 45
crates/kuatia/tests/projection.rs

@@ -1,6 +1,6 @@
-//! Balance-projection correctness (ADR-0019): the projection-aware read must
-//! always equal the authoritative live-posting sum, and the projector must
-//! advance the snapshot without changing the answer.
+//! Balance-projection correctness (ADR-0019). The projection-aware read must
+//! always equal the authoritative live-posting sum. The projector must advance
+//! the snapshot, and the answer must stay the same.
 
 #![allow(missing_docs)]
 
@@ -11,8 +11,8 @@ use kuatia::mem_store::InMemoryStore;
 use kuatia_core::*;
 
 /// An amount of `asset` in minor units. An amount compares by asset id, and the
-/// tests register these same ids, so building the row here is equivalent to
-/// reading it back from the registry.
+/// tests register these same ids. So a row built here is equivalent to one read
+/// back from the registry.
 fn money<V>(asset: AssetId, value: V) -> Amount
 where
     Amount: From<(V, Arc<Asset>)>,
@@ -105,9 +105,9 @@ async fn assert_projection_matches(ledger: &Arc<Ledger>, ids: &[i64]) {
     }
 }
 
-/// With no projector run at all (every projection absent, so the read folds the
-/// whole history), the projection-aware read still equals the live sum through
-/// deposits, change-making pays, and an overdraft offset posting.
+/// The projector never runs here, so every projection is absent and the read
+/// folds the whole history. The projection-aware read still equals the live sum
+/// through deposits, pays that make change, and an overdraft offset posting.
 #[tokio::test]
 async fn projected_balance_matches_live_sum_without_refresh() {
     let ledger = Arc::new(Ledger::new(InMemoryStore::new()));
@@ -129,10 +129,10 @@ async fn projected_balance_matches_live_sum_without_refresh() {
     assert_projection_matches(&ledger, &[1, 2, 10, 99]).await;
 }
 
-/// Appending a cache point stores the balance directly, and the read still equals
-/// the live sum. Appending only after all commits keeps this deterministic: grace
-/// 0 puts the watermark at "now", so every committed transfer folds into the cache
-/// point with an empty tail.
+/// An append of a cache point stores the balance directly, and the read still
+/// equals the live sum. The append runs after every commit, which keeps this
+/// deterministic. Grace 0 puts the watermark at "now", so every committed
+/// transfer folds into the cache point and the tail is empty.
 #[tokio::test]
 async fn append_cache_point_snapshots_balance_and_preserves_answer() {
     let ledger = Arc::new(Ledger::new(InMemoryStore::new()).with_projection_config(
@@ -198,9 +198,9 @@ async fn commit_does_not_write_cache_point() {
     );
 }
 
-/// A read appends a cache point once `snapshot_interval` credits/debits have
-/// accrued (the append is spawned in the background; on the current-thread test
-/// runtime it runs when we yield).
+/// A read appends a cache point once `snapshot_interval` credits and debits
+/// accrue. The append is spawned in the background, and on the current-thread
+/// test runtime it runs at the next yield.
 #[tokio::test]
 async fn read_appends_cache_point_after_interval() {
     let ledger = Arc::new(Ledger::new(InMemoryStore::new()).with_projection_config(
@@ -257,9 +257,10 @@ async fn read_appends_cache_point_after_interval() {
     );
 }
 
-/// A read below the interval never appends a cache point: the background append
-/// gates on new credits/debits, so a low-activity account accrues no rows (this
-/// is what keeps a hot, frequently-read account from appending near-duplicates).
+/// A read below the interval never appends a cache point. The background append
+/// gates on new credits and debits, so an account with little activity accrues
+/// no row. That gate is also what stops a hot, often-read account from an
+/// append of near-duplicates.
 #[tokio::test]
 async fn read_below_interval_appends_nothing() {
     let ledger = Arc::new(Ledger::new(InMemoryStore::new()).with_projection_config(
@@ -307,13 +308,15 @@ async fn read_below_interval_appends_nothing() {
     );
 }
 
-/// Snapshot plus a genuinely non-empty tail. A cache point is pinned to the
-/// boundary between two commit batches, then more commits land strictly after
-/// its watermark, so the read must fold `snapshot + tail`: not a whole-history
-/// live sum (no snapshot) and not a snapshot that already holds everything (empty
-/// tail). This is the watermark boundary the grace-0 and no-snapshot tests never
-/// reach; an off-by-one at `watermark + 1` would drop or double-count a
-/// tail transfer here.
+/// Snapshot plus a tail that is genuinely non-empty. A cache point is pinned to
+/// the boundary between two commit batches, then more commits land strictly
+/// after its watermark. So the read must fold `snapshot + tail`. It is neither
+/// a whole-history live sum, which is the no-snapshot case, nor a snapshot that
+/// already holds everything, which is the empty-tail case.
+///
+/// This is the watermark boundary the grace-0 and no-snapshot tests never
+/// reach. An off-by-one at `watermark + 1` would drop a tail transfer here, or
+/// count one twice.
 #[tokio::test]
 async fn snapshot_plus_nonempty_tail_matches_live_sum() {
     let ledger = Arc::new(Ledger::new(InMemoryStore::new()));
@@ -390,13 +393,14 @@ impl Rng {
     }
 }
 
-/// Property test: across a long random sequence of every UTXO-shaped operation
-/// (deposits, change-making pays, overdraft offsets, multi-asset, subaccounts,
-/// and reversals), the projection-aware read equals the authoritative live-posting
-/// sum for every (account, asset) after every step. This is the empirical form of
-/// the telescoping argument: whole-posting spends plus change-as-new-posting make
-/// `snapshot + tail` fold exactly to the live set, in every shape the ledger can
-/// produce.
+/// Property test over a long random sequence of every UTXO-shaped operation.
+/// That covers deposits, pays that make change, overdraft offsets, several
+/// assets, subaccounts and reversals. After every step, the projection-aware
+/// read equals the authoritative live-posting sum for every (account, asset).
+///
+/// This is the empirical form of the argument that the terms cancel. A spend of
+/// a whole posting, plus change as a new posting, make `snapshot + tail` fold
+/// exactly to the live set. That holds in every shape the ledger can produce.
 #[tokio::test]
 async fn projection_matches_live_sum_across_random_utxo_history() {
     // Default grace (60s) over a sub-second run keeps every watermark before all
@@ -559,9 +563,9 @@ async fn projection_matches_under_concurrent_commits() {
     assert_projection_matches(&ledger, &[1, 2, 3, 4, 5, 6, 7, 8, 9, 99]).await;
 }
 
-/// An as-of read is bounded above by `as_of`: with no cache point anywhere, it
-/// folds the history up to that instant and the later commits are simply absent.
-/// Each batch is separated by a real millisecond, since two commits inside one
+/// An as-of read is bounded above by `as_of`. With no cache point anywhere, it
+/// folds the history up to that instant, and the later commits are absent. A
+/// real millisecond separates each batch, because two commits inside one
 /// millisecond share a stamp and would make the boundary ambiguous.
 #[tokio::test]
 async fn balance_as_of_excludes_later_commits() {
@@ -597,12 +601,15 @@ async fn balance_as_of_excludes_later_commits() {
     );
 }
 
-/// The as-of read takes the closest cache point at or before `as_of` and folds
-/// only the window between that point's watermark and `as_of`, so the two
-/// derivations (pinned snapshot plus bounded tail, and the hand-computed total)
-/// agree while later commits stay out. The `assert_ne!` guards the test itself:
-/// a snapshot that already held the as-of balance would leave the tail empty and
-/// quietly degrade this to a case the other tests cover.
+/// The as-of read takes the closest cache point at or before `as_of`, and folds
+/// the window between the watermark of that point and `as_of` alone. So the two
+/// derivations agree, and the later commits stay out. One derivation is the
+/// pinned snapshot plus the bounded tail, and the other is the hand-computed
+/// total.
+///
+/// The `assert_ne!` guards the test itself. A snapshot that already held the
+/// as-of balance would leave the tail empty, and quietly reduce this to a case
+/// the other tests cover.
 #[tokio::test]
 async fn balance_as_of_folds_a_bounded_tail_onto_its_cache_point() {
     let ledger = Arc::new(Ledger::new(InMemoryStore::new()));
@@ -653,8 +660,8 @@ async fn balance_as_of_folds_a_bounded_tail_onto_its_cache_point() {
     );
 }
 
-/// A cache point whose watermark is above `as_of` covers transfers the read must
-/// not see, so the read falls back to the history below `as_of` instead.
+/// A cache point whose watermark is above `as_of` covers transfers the read
+/// must not see. So the read falls back to the history below `as_of`.
 #[tokio::test]
 async fn balance_as_of_ignores_a_cache_point_above_it() {
     let ledger = Arc::new(Ledger::new(InMemoryStore::new()));
@@ -697,8 +704,8 @@ async fn balance_as_of_ignores_a_cache_point_above_it() {
 }
 
 /// An as-of read appends no cache point, even past the interval that makes the
-/// everyday read append one: a new point's watermark comes from the current
-/// clock, so it would describe a window the as-of read never looked at.
+/// everyday read append one. The watermark of a new point comes from the
+/// current clock, so it would name a window the as-of read never looked at.
 #[tokio::test]
 async fn balance_as_of_appends_no_cache_point() {
     let ledger = Arc::new(Ledger::new(InMemoryStore::new()).with_projection_config(

+ 5 - 5
crates/kuatia/tests/workflow.rs

@@ -10,8 +10,8 @@ use kuatia::workflow::run_transfers;
 use kuatia_core::*;
 
 /// An amount of `asset` in minor units. An amount compares by asset id, and the
-/// tests register these same ids, so building the row here is equivalent to
-/// reading it back from the registry.
+/// tests register these same ids. So a row built here is equivalent to one read
+/// back from the registry.
 fn money<V>(asset: AssetId, value: V) -> Amount
 where
     Amount: From<(V, Arc<Asset>)>,
@@ -118,9 +118,9 @@ async fn workflow_happy_path() {
     );
 }
 
-/// The second movement overspends and fails; the first (deposit) is reversed
-/// LIFO, so the net effect is zero. The typed `InsufficientFunds` reaches the
-/// caller.
+/// The second movement overspends and fails. The first one, the deposit, is
+/// reversed LIFO, so the net effect is zero. The typed `InsufficientFunds`
+/// reaches the caller.
 #[tokio::test]
 async fn workflow_compensation_on_failure() {
     let ledger = setup_ledger().await;

+ 26 - 24
doc/README.md

@@ -4,38 +4,40 @@
 
 An append-only, auditable, multi-asset UTXO-style ledger library in Rust.
 
-Kuatia models value as **postings**: signed amounts of one asset owned by
-exactly one account. A transfer atomically consumes existing postings and
-creates new ones, enforcing per-asset conservation (`sum(consumed) ==
-sum(created)`). That is the same safety guarantee as double-entry bookkeeping,
-`Σ debits = Σ credits`, expressed over signed postings. There are no mutable
-balance fields, so an account's balance is always the sum of its live postings.
+Kuatia models value as **postings**: signed amounts of one asset, where exactly
+one account owns each posting. A transfer atomically consumes the postings that
+exist and creates new ones. Per-asset conservation holds over every transfer:
+`sum(consumed) == sum(created)`. Double-entry bookkeeping gives the same safety
+guarantee as `Σ debits = Σ credits`, and Kuatia states it over signed postings.
+There is no mutable balance field, so an account's balance is always the sum of
+its live postings.
 
 A committed transfer is a journal entry. A transfer with several movements is a
-compound entry, one balanced event touching many accounts and, since each asset
-balances independently, many assets. The append-only transfer log is the
-accounting journal: replaying it reconstructs every balance, so the ledger is
-auditable by construction.
+compound entry: one balanced event that touches many accounts. It can also touch
+many assets, because each asset balances on its own. The append-only transfer
+log is the accounting journal. A replay of that log reconstructs every balance,
+so the ledger is auditable by construction.
 
 ## How this book is laid out
 
-**Concepts** covers the model: the [architecture](architecture.md) and why it
-is shaped that way, [accounts](accounts.md), [transfers](transfers.md) and the
-resolve algorithm, and [inflight holds](inflight.md).
+**Concepts** covers the model: the [architecture](architecture.md) and the
+reason for its shape, [accounts](accounts.md), [transfers](transfers.md) with
+the resolve algorithm, and [inflight holds](inflight.md).
 
-**Examples** are worked walkthroughs: [overdraft](examples/overdraft.md) and the
-shortfall posting, a [currency exchange](examples/exchange.md), a
-[retail point of sale](examples/retail.md), and the
-[runnable programs](examples/runnable.md) you can `cargo run`.
+**Examples** are worked cases: [overdraft](examples/overdraft.md) and the
+shortfall posting, a [currency exchange](examples/exchange.md), and a [retail
+point of sale](examples/retail.md). The [runnable
+programs](examples/runnable.md) start with `cargo run`.
 
-**Accounting** maps the model onto practice, both as
+**Accounting** maps the model onto practice. It does so both as
 [journaling](journaling.md) and as a term-by-term
 [mapping](accounting-mapping.md) from classical double-entry.
 
-**Reference** is the [crate reference](crates.md), the
-[SQL storage schema](storage-schema.md) and the [glossary](glossary.md), which
-defines every term.
+**Reference** is the [crate reference](crates.md), the [SQL storage
+schema](storage-schema.md) and the [glossary](glossary.md), which defines every
+term.
 
-**Decisions** is the [ADR log](adr/README.md): every significant, hard-to-reverse
-design decision, with the options that were rejected and why. An ADR is never
-edited to reverse a decision; a later one supersedes it.
+**Decisions** is the [ADR log](adr/README.md). It holds every significant,
+hard-to-reverse design decision, with the options that it rejected and the
+reason for each. Nobody edits an ADR to reverse a decision. A later ADR
+supersedes it.

+ 57 - 30
doc/SUMMARY.md

@@ -1,7 +1,6 @@
 # Summary
 
-[Kuatia](README.md)
-[Glossary](glossary.md)
+[Kuatia](README.md) [Glossary](glossary.md)
 
 # Concepts
 
@@ -33,35 +32,63 @@
 # Decisions
 
 - [Architecture decision records](adr/README.md)
-  - [0001: Modified UTXO: value as signed postings](adr/0001-modified-utxo-signed-postings.md)
+  - [0001: Modified UTXO: value as signed
+    postings](adr/0001-modified-utxo-signed-postings.md)
   - [0002: Saga commit pipeline](adr/0002-saga-commit-pipeline.md)
-  - [0003: Dumb storage + durable saga recovery](adr/0003-dumb-storage-saga-recovery.md)
-  - [0004: Account policies & overdraft model](adr/0004-account-policies-overdraft-model.md)
-  - [0005: Intent API: movements vs. envelopes](adr/0005-intent-api-movements-vs-envelopes.md)
-  - [0006: Reservation protocol & posting lifecycle](adr/0006-reservation-protocol-posting-lifecycle.md)
-  - [0007: Reversal via compensating transfers](adr/0007-reversal-via-compensating-transfers.md)
+  - [0003: Dumb storage + durable saga
+    recovery](adr/0003-dumb-storage-saga-recovery.md)
+  - [0004: Account policies & overdraft
+    model](adr/0004-account-policies-overdraft-model.md)
+  - [0005: Intent API: movements vs.
+    envelopes](adr/0005-intent-api-movements-vs-envelopes.md)
+  - [0006: Reservation protocol & posting
+    lifecycle](adr/0006-reservation-protocol-posting-lifecycle.md)
+  - [0007: Reversal via compensating
+    transfers](adr/0007-reversal-via-compensating-transfers.md)
   - [0008: Conformance-tested storage](adr/0008-conformance-tested-storage.md)
-  - [0009: Monetary amounts as integer minor units](adr/0009-monetary-representation-integer-minor-units.md)
-  - [0010: Derived event stream vs. transfer log](adr/0010-event-stream-vs-transfer-log.md)
-  - [0011: Swappable integer backing for money, default i64](adr/0011-swappable-money-backing.md)
+  - [0009: Monetary amounts as integer minor
+    units](adr/0009-monetary-representation-integer-minor-units.md)
+  - [0010: Derived event stream vs. transfer
+    log](adr/0010-event-stream-vs-transfer-log.md)
+  - [0011: Swappable integer backing for money, default
+    i64](adr/0011-swappable-money-backing.md)
   - [0012: Subaccount dimension on account identity](adr/0012-subaccounts.md)
-  - [0013: Journaling model: transfer as journal entry](adr/0013-journaling-model.md)
-  - [0014: Inflight holds via per-destination holding accounts](adr/0014-inflight-holds-via-holding-accounts.md)
-  - [0015: Fixed-width 20-character account code](adr/0015-fixed-width-account-code.md)
-  - [0016: Immutable postings with active/reserved index tables](adr/0016-immutable-postings-index-tables.md)
-  - [0017: Correctness-first storage: append-only value tables, disposable hot indexes](adr/0017-correctness-first-append-only-hot-indexes.md)
-  - [0018: Collapse account policy into a single debit-must-not-exceed-credit flag](adr/0018-single-debit-must-not-exceed-credit-flag.md)
-  - [0019: Cached balance projection via append-only cache points](adr/0019-cached-balance-projection.md)
-  - [0020: Crash-safe account-version transitions](adr/0020-account-transition-recovery.md)
-  - [0021: The commit-safety invariant and where each part is enforced](adr/0021-commit-safety-map.md)
-  - [0022: Merge the active/reserved hot indexes into one `live_postings` table](adr/0022-merged-live-postings-hot-index.md)
-  - [0023: Atomic storage commit, retiring the write-ahead saga and `legend`](adr/0023-atomic-storage-commit.md)
-  - [0024: Native money columns, and exact summation in the database](adr/0024-native-money-columns.md)
-  - [0025: One live set: retire the reservation protocol and the saga-era store primitives](adr/0025-one-live-set-no-reservations.md)
-  - [0026: Let the public API speak the caller's vocabulary](adr/0026-public-api-vocabulary.md)
-  - [0027: Value date, separate from commit time and inside the content address](adr/0027-value-date-separate-from-commit-time.md)
-  - [0028: An amount carries its asset, and the ledger owns the asset registry](adr/0028-amount-carries-its-asset.md)
-  - [0029: Stored amounts, and a public surface that never names `Cent`](adr/0029-stored-amounts-and-a-closed-money-surface.md)
-  - [0030: An asset is named by its code, and the ledger mints its id](adr/0030-assets-named-by-code.md)
-  - [0031: Every read is account scoped: no aggregate crosses accounts](adr/0031-every-read-is-account-scoped.md)
+  - [0013: Journaling model: transfer as journal
+    entry](adr/0013-journaling-model.md)
+  - [0014: Inflight holds via per-destination holding
+    accounts](adr/0014-inflight-holds-via-holding-accounts.md)
+  - [0015: Fixed-width 20-character account
+    code](adr/0015-fixed-width-account-code.md)
+  - [0016: Immutable postings with active/reserved index
+    tables](adr/0016-immutable-postings-index-tables.md)
+  - [0017: Correctness-first storage: append-only value tables, disposable hot
+    indexes](adr/0017-correctness-first-append-only-hot-indexes.md)
+  - [0018: Collapse account policy into a single debit-must-not-exceed-credit
+    flag](adr/0018-single-debit-must-not-exceed-credit-flag.md)
+  - [0019: Cached balance projection via append-only cache
+    points](adr/0019-cached-balance-projection.md)
+  - [0020: Crash-safe account-version
+    transitions](adr/0020-account-transition-recovery.md)
+  - [0021: The commit-safety invariant and where each part is
+    enforced](adr/0021-commit-safety-map.md)
+  - [0022: Merge the active/reserved hot indexes into one `live_postings`
+    table](adr/0022-merged-live-postings-hot-index.md)
+  - [0023: Atomic storage commit, retiring the write-ahead saga and
+    `legend`](adr/0023-atomic-storage-commit.md)
+  - [0024: Native money columns, and exact summation in the
+    database](adr/0024-native-money-columns.md)
+  - [0025: One live set: retire the reservation protocol and the saga-era store
+    primitives](adr/0025-one-live-set-no-reservations.md)
+  - [0026: Let the public API speak the caller's
+    vocabulary](adr/0026-public-api-vocabulary.md)
+  - [0027: Value date, separate from commit time and inside the content
+    address](adr/0027-value-date-separate-from-commit-time.md)
+  - [0028: An amount carries its asset, and the ledger owns the asset
+    registry](adr/0028-amount-carries-its-asset.md)
+  - [0029: Stored amounts, and a public surface that never names
+    `Cent`](adr/0029-stored-amounts-and-a-closed-money-surface.md)
+  - [0030: An asset is named by its code, and the ledger mints its
+    id](adr/0030-assets-named-by-code.md)
+  - [0031: Every read is account scoped: no aggregate crosses
+    accounts](adr/0031-every-read-is-account-scoped.md)
   - [ADR template](adr/template.md)

+ 103 - 99
doc/accounting-mapping.md

@@ -1,25 +1,27 @@
 # Accounting Mapping: Classical Double-Entry ↔ Kuatia
 
-Kuatia provides double-entry-style safety using a UTXO-style model. Value is
-held as signed postings, and every committed transfer must satisfy per-asset
-conservation. The accounting goal is the same as classical bookkeeping; the
-mechanical model is different:
+Kuatia gives double-entry-style safety with a UTXO-style model. The ledger holds
+value as signed postings. Every committed transfer must satisfy per-asset
+conservation. The accounting goal is the same as the goal of classical
+bookkeeping. The mechanical model is different:
 
 | Classical double-entry | Kuatia |
 |---|---|
 | `Σ debits = Σ credits` | `sum(consumed) == sum(created)` per asset |
 
-This page maps classical accounting vocabulary onto Kuatia's types and clears
-up the terms that are easy to conflate. For a focused, affirmative walkthrough
-of journaling (single, compound, and multi-asset entries, and the transfer log
-as the journal) see [journaling.md](journaling.md).
+This page maps classical accounting vocabulary onto Kuatia's types. It also
+separates the terms that are easy to confuse. See [journaling.md](journaling.md)
+for a direct description of journaling. That page covers single, compound and
+multi-asset entries, and the transfer log as the journal.
 
-The most important correction: in classical accounting a journal is the
-append-only book of original entry, while a journal entry is one committed
-accounting event. In Kuatia, the closest equivalent to the classical journal
-is the transfer log; the closest equivalent to a journal entry is a committed
-`Transfer`/`Envelope`. Kuatia's `Book` is neither. It is a transfer policy
-scope, not the accounting journal.
+Here is the most important correction. In classical accounting a journal is the
+append-only book of original entry. A journal entry is one committed accounting
+event. In Kuatia the closest equivalent of the classical journal is the transfer
+log.
+
+The closest equivalent of a journal entry is a committed `Transfer` or
+`Envelope`. Kuatia's `Book` is neither. It is a transfer policy scope, not the
+accounting journal.
 
 ## Core mapping
 
@@ -27,25 +29,25 @@ scope, not the accounting journal.
 |---|---|---|
 | **Journal** (book of original entry) | **Transfer log**, `TransferStore` of `TransferRecord`s | Append-only, ordered source of truth for committed transfers. |
 | **Journal entry** (one balanced event) | Committed **`Transfer`** (intent) → **`Envelope`** (resolved) | One atomic accounting event. |
-| **Compound journal entry** | `Transfer` with multiple `Movement`s | One event touching many accounts/assets. |
-| **Entry line / leg** | **`Posting`** effect (often derived from a `Movement`) | A concrete account-level value fragment. A `Movement` is two-sided intent, an amount moving `from` one account `to` another, that resolves into consumed/created postings rather than a 1:1 debit/credit line. |
-| **Σ debits = Σ credits** | **Per-asset conservation** `sum(consumed) == sum(created)` | Enforced in `validate_and_plan`; `ConservationViolation` otherwise. |
-| **Ledger** (accounts + running balances) | **Accounts + live postings** | Balances are projections over the live (unspent) postings, never stored. |
-| **Posting a transaction** (the verb) | **resolve + commit** (`Transfer` → `Envelope` → apply) | Confusing collision: in Kuatia a *posting* is a noun (a value fragment), not the act of recording. |
+| **Compound journal entry** | `Transfer` with multiple `Movement`s | One event that touches many accounts or assets. |
+| **Entry line / leg** | **`Posting`** effect (often derived from a `Movement`) | A concrete account-level value fragment. A `Movement` is two-sided intent, an amount that moves `from` one account `to` another. It resolves into consumed and created postings, not into a 1:1 debit or credit line. |
+| **Σ debits = Σ credits** | **Per-asset conservation** `sum(consumed) == sum(created)` | `validate_and_plan` enforces it, and reports `ConservationViolation` otherwise. |
+| **Ledger** (accounts + running balances) | **Accounts + live postings** | A balance is a projection over the live (unspent) postings. The ledger never stores one. |
+| **Posting a transaction** (the verb) | **resolve + commit** (`Transfer` → `Envelope` → apply) | A collision that confuses: in Kuatia a *posting* is a noun, a value fragment, not the act of a record. |
 | **Accounting book** | *no direct equivalent unless modeled separately* | Kuatia `Book` is **not** this. |
-| **Transfer policy scope** | **`Book`** | Gates which accounts/assets may participate. See [below](#where-book-fits-and-doesnt). |
-| **Chart of accounts** (accounts grouped by class) | *no equivalent* | An account carries no asset/liability/equity/income/expense dimension. See [accounts carry no accounting class](accounts.md#accounts-carry-no-accounting-class). |
+| **Transfer policy scope** | **`Book`** | Gates which accounts and assets can participate. See [below](#where-book-fits-and-doesnt). |
+| **Chart of accounts** (accounts grouped by class) | *no equivalent* | An account carries no asset, liability, equity, income or expense dimension. See [accounts carry no accounting class](accounts.md#accounts-carry-no-accounting-class). |
 
-> A journal entry is one committed accounting event. In many accounting
-> texts this event is also called a transaction, a word that is overloaded
-> in a ledger library (database transaction, business transaction, atomic
-> transfer), so this doc prefers "committed accounting event."
+> A journal entry is one committed accounting event. Many accounting texts also
+> call this event a transaction. That word is overloaded in a ledger library: a
+> database transaction, a business transaction, an atomic transfer. So this
+> document prefers "committed accounting event".
 
 ## A journal entry is multi-account
 
-Double-entry entries are inherently multi-account; that is the entire point.
-A minimal entry has two legs; a compound entry has more. So a Kuatia transfer
-touching many accounts is not a mismatch. It is a (compound) journal entry.
+A double-entry entry is multi-account by nature, and that is the entire point. A
+minimal entry has two legs. A compound entry has more. So a Kuatia transfer that
+touches many accounts is not a mismatch. It is a compound journal entry.
 
 Classical compound journal entry:
 
@@ -56,8 +58,8 @@ Classical compound journal entry:
       Cr  Sales tax payable .      15
 ```
 
-The equivalent business effects as a Kuatia transfer, multiple movements
-committed atomically:
+The same business effects as a Kuatia transfer, with several movements that
+commit atomically:
 
 ```rust
 let transfer = TransferBuilder::new()
@@ -68,91 +70,93 @@ let transfer = TransferBuilder::new()
 // One Transfer → one Envelope → one TransferRecord in the transfer log.
 ```
 
-> Note: this is not a literal debit/credit translation. It shows the business
-> effects as movements. In a production POS model, cash, revenue, and tax
-> might be separate effects routed through system/offset accounts. (A literal
-> multi-hop `customer → cash → revenue` chain inside one transfer would
-> require spending a posting created earlier in the same envelope, which the
-> resolver does not do; it selects from already-committed postings.)
+> Note: this is not a literal debit and credit translation. It shows the
+> business effects as movements. In a production POS model, cash, revenue and
+> tax can be separate effects that pass through system or offset accounts. A
+> literal multi-hop `customer → cash → revenue` chain inside one transfer needs
+> a posting that the same envelope created earlier. The resolver does not do
+> that. It selects from postings that are already committed.
 
-Both are a single balanced event. In the classical entry, `Σ Dr (115) = Σ Cr
-(115)`. In Kuatia, the resolved `Envelope` satisfies per-asset conservation:
+Both are one balanced event. In the classical entry, `Σ Dr (115) = Σ Cr (115)`.
+In Kuatia, the resolved `Envelope` satisfies per-asset conservation:
 `sum(consumed) == sum(created)` for USD.
 
 ## One entry vs the journal: `Transfer`/`Envelope` vs the transfer log
 
-These differ in grain: one record vs. the collection of all records.
-
-- `Transfer` / `Envelope` = one record (one journal entry).
-  - `Transfer` is the intent: `{ movements: Vec<Movement>, book, metadata }`.
-    Callers express what should happen, not which postings.
-  - `Envelope` is the resolved form produced by `resolve()`: `{ consumes:
-    Vec<PostingId>, creates: Vec<NewPosting>, account_snapshots, book, … }`.
-    It names the concrete postings to spend and create.
-  - Committing one (`commit` / `commit_envelope`) returns a `Receipt {
-    transfer_id }` identifying the committed envelope, the `TransferId`, which
-    is content-addressed (the double-SHA-256 of the canonical envelope bytes).
-- Transfer log = the accounting journal. The append-only, ordered sequence of
-  every committed envelope, persisted by `TransferStore` as `TransferRecord {
-  envelope, receipt, created_at }`. Each transfer is one entry in it.
+These differ in grain: one record against the collection of all records.
+
+- `Transfer` / `Envelope` = one record, which is one journal entry.
+  - `Transfer` is the intent: `{ movements: Vec<Movement>, book, metadata }`. A
+    caller expresses what must happen, not which postings.
+  - `Envelope` is the resolved form that `resolve()` produces:
+    `{ consumes: Vec<PostingId>, creates: Vec<NewPosting>, account_snapshots, book, … }`.
+    It names the concrete postings to spend and to create.
+  - A commit through `commit` or `commit_envelope` returns a
+    `Receipt { transfer_id }`. The `TransferId` in it identifies the committed
+    envelope. It is content-addressed: the double-SHA-256 of the canonical
+    envelope bytes.
+- Transfer log = the accounting journal. It is the append-only, ordered sequence
+  of every committed envelope. `TransferStore` persists it as
+  `TransferRecord { envelope, receipt, created_at }`. Each transfer is one entry
+  in it.
 
 > Transfer/Envelope : transfer log :: one journal entry : the journal.
 
-"The system is trivially auditable by replaying the transfer log" means:
-re-apply every `TransferRecord` in order and you reconstruct all balances.
-There is no stored balance that can drift.
+A replay of the transfer log audits the whole system. Re-apply every
+`TransferRecord` in order, and you reconstruct all balances. No stored balance
+can drift, because there is none.
 
 ## Two append-only logs: don't conflate "log"
 
-Kuatia keeps two distinct append-only sequences. Only the first is the
+Kuatia keeps two distinct append-only sequences. Only the first one is the
 accounting journal.
 
 | Log | Type | Records | Role |
 |---|---|---|---|
 | **Transfer log** | `TransferStore` → `TransferRecord` | Full posting-level detail of each committed transfer | The accounting **journal**, the source of truth for balances. |
-| **Event log** | `EventStore` → `LedgerEvent` | High-level lifecycle notifications | Projections / subscribers; *not* the journal. |
+| **Event log** | `EventStore` → `LedgerEvent` | High-level lifecycle notifications | Projections and subscribers. It is *not* the journal. |
 
-`LedgerEvent { seq, timestamp, kind }` carries a monotonic `seq` and a `kind`
-of `TransferCommitted | AccountCreated | AccountFrozen | AccountUnfrozen |
-AccountClosed`. It tells you that something happened; the transfer log tells
-you exactly which postings moved.
+`LedgerEvent { seq, timestamp, kind }` carries a monotonic `seq` and a `kind`.
+The kind is one of
+`TransferCommitted | AccountCreated | AccountFrozen | AccountUnfrozen | AccountClosed`.
+An event tells you that something happened. The transfer log tells you exactly
+which postings moved.
 
 ## The UTXO wrinkle
 
-Classical ledgers post an entry by mutating each account's running balance.
-Kuatia is UTXO-style and posting-based, so the mechanism differs while the
-event grain is identical. Because postings are signed, debit/credit is not the
-native primitive; resolution works in terms of consuming and creating
-postings:
-
-- In a simple movement, the source side is resolved by consuming `Live`
-  postings from the source account, creating a change posting if the selected
-  postings exceed the amount.
-- The destination side is represented by newly created postings on the
-  destination account.
-- An account's balance is the sum of its `Live` postings, computed on demand,
-  never stored.
-
-So an entry line maps to a `Posting` effect, usually derived from a `Movement`
-(two-sided intent) that resolves into one or more postings (a created posting,
-consumed postings, and possibly change). The balancing rule is unchanged: per
-asset, `sum(consumed) == sum(created)`.
+A classical ledger posts an entry and changes each account's balance total.
+Kuatia is UTXO-style and posting-based. So the mechanism differs, and the event
+grain stays identical. Postings are signed, so debit and credit are not the
+native primitive. Resolution works with consumed postings and created postings:
+
+- In a simple movement, the resolver consumes `Live` postings from the source
+  account. It creates a change posting if the selected postings exceed the
+  amount.
+- New postings on the destination account represent the destination side.
+- An account's balance is the sum of its `Live` postings. The ledger computes it
+  on demand and never stores it.
+
+So an entry line maps to a `Posting` effect. A `Movement`, which is two-sided
+intent, usually derives that effect. The movement resolves into one or more
+postings: a created posting, consumed postings, and possibly change. The balance
+rule does not change: per asset, `sum(consumed) == sum(created)`.
 
 ## Where `Book` fits (and doesn't)
 
-`Book` is the one Kuatia concept with no classical counterpart. It is a
-transfer policy scope: it gates which accounts and assets may participate in a
-transfer (`BookPolicy { allowed_assets, allowed_flags, allowed_accounts }`).
+`Book` is the one Kuatia concept with no classical counterpart. It is a transfer
+policy scope. It gates which accounts and assets can participate in a transfer,
+through `BookPolicy { allowed_assets, allowed_flags, allowed_accounts }`.
 
 It is explicitly not:
-- the journal (that is the transfer log),
-- a journal entry (that is a `Transfer`/`Envelope`),
-- a balance partition (balances are global; a Book only gates participation),
-- a tenant boundary (see [books are not a tenancy boundary](glossary.md#books-are-not-a-tenancy-boundary)).
+- the journal, which is the transfer log,
+- a journal entry, which is a `Transfer` or an `Envelope`,
+- a balance partition, because balances are global and a Book only gates
+  participation,
+- a tenant boundary, for which see [books are not a tenancy
+  boundary](glossary.md#books-are-not-a-tenancy-boundary).
 
-> Despite the name, a Kuatia `Book` must not be confused with an accounting
-> book. The accounting journal is the transfer log; `Book` is purely a policy
-> scope.
+> Despite the name, do not confuse a Kuatia `Book` with an accounting book. The
+> accounting journal is the transfer log. `Book` is purely a policy scope.
 
 See the [glossary](glossary.md#book) for the Book model and worked examples.
 
@@ -162,17 +166,17 @@ See the [glossary](glossary.md#book) for the Book model and worked examples.
 |---|---|---|
 | Journal | Transfer log / `TransferStore<TransferRecord>` | Append-only source of truth for committed transfers. |
 | Journal entry | Committed `Transfer` / `Envelope` | One atomic accounting event. |
-| Entry line / leg | `Posting` effect | A concrete account-level value fragment; movements are intent that resolve into postings. |
-| Compound journal entry | `Transfer` with multiple movements | One event touching many accounts/assets. |
+| Entry line / leg | `Posting` effect | A concrete account-level value fragment. A movement is intent that resolves into postings. |
+| Compound journal entry | `Transfer` with multiple movements | One event that touches many accounts or assets. |
 | Σ debits = Σ credits | Per-asset conservation | `sum(consumed) == sum(created)` per asset. |
-| Ledger | Accounts + active postings | Balances are projections over active postings. |
-| Posting a transaction (verb) | Resolve + commit | Avoid confusion: Kuatia `Posting` is a noun. |
+| Ledger | Accounts + live postings | A balance is a projection over the live postings. |
+| Posting a transaction (verb) | Resolve + commit | Avoid the confusion: Kuatia `Posting` is a noun. |
 | Accounting book | No direct equivalent unless modeled separately | Kuatia `Book` is not this. |
-| Transfer policy scope | `Book` | Gates allowed accounts/assets. |
-| Chart of accounts | No equivalent | An account carries no class; a class lives in metadata or a user flag bit. |
-| Proof a txn was recorded | `Receipt { transfer_id }` | Content-addressed `TransferId`. |
+| Transfer policy scope | `Book` | Gates the allowed accounts and assets. |
+| Chart of accounts | No equivalent | An account carries no class. A class lives in metadata or in a user flag bit. |
+| Proof that a transfer was recorded | `Receipt { transfer_id }` | Content-addressed `TransferId`. |
 | Lifecycle notifications | Event log (`LedgerEvent`) | Separate from the transfer log. |
 
-In one line: Kuatia's transfer log is the accounting journal; each committed
-envelope is a journal entry; Kuatia's `Book` is a policy scope, not a journal
-or a balance partition.
+In one line: Kuatia's transfer log is the accounting journal, and each committed
+envelope is a journal entry. Kuatia's `Book` is a policy scope. It is not a
+journal and not a balance partition.

+ 147 - 110
doc/accounts.md

@@ -2,10 +2,11 @@
 
 ## Overview
 
-An account is a versioned entity that owns postings. Balance is never
-stored: it is always computed from postings for a given (account, asset)
-pair. `balance()` sums the live postings, meaning those in the live index;
-spent postings, which remain only in the immutable table, are excluded.
+An account is a versioned entity that owns postings. The ledger never stores a
+balance. It always computes one from the postings of a given (account, asset)
+pair. `balance()` sums the live postings, which are the postings in the live
+index. It excludes a spent posting, because a spent posting stays only in the
+immutable table.
 
 ## Structure
 
@@ -20,78 +21,88 @@ spent postings, which remain only in the immutable table, are excluded.
 ## Subaccounts
 
 An `AccountId` is a base `id` plus a `sub`. `sub = 0` is the account's main
-account; a non-zero `sub` is a subaccount of the same base id. Each `(id, sub)`
-is a full account record with its own flags, book, version, and
-lifecycle, created, versioned, frozen, and closed exactly like any other
-account. A subaccount can forbid overdraft while its base account does not, or
-the reverse, because every check keys on the full `AccountId`.
-
-Subaccounts partition one owner's holdings into several individually addressable
-balances (sub-ledgers, earmarks, reservations) without minting unrelated
-top-level accounts. Helpers on `AccountId`: `new(id)` (main account),
-`with_sub(id, sub)`, `base()` (the main account of an id), and `is_main()`.
-
-`AccountId` also has an IBAN-style string form (`Display` / `FromStr`): a fixed
-20 characters, an 18-character base-36 body then two trailing ISO 7064 mod-97
-check digits, with no country code (e.g. `KUJL QEL8 IX2X GTBK 4425`). The body
-packs the base id (63 bits) and the subaccount (`SUB_BITS` bits) into one 93-bit
-value and runs it through a keyed format-preserving permutation before encoding
-(and inverts it on parse), so a code does not reveal the raw ids; the key is a
-global seed with a default, configurable via `set_id_seed`. Parsing validates the
-checksum, so a mistyped identifier is rejected. This is obfuscation, not security
-(the seed decodes it), and a presentation/routing form only; storage keeps the
-two `i64` legs. The fixed width is what caps the subaccount at `SUB_BITS`; see
-ADR-0015.
-
-Balances are always reported per subaccount and are never summed across them:
+account. A non-zero `sub` is a subaccount of the same base id.
+
+Each `(id, sub)` is a full account record with its own flags, book, version and
+lifecycle. The ledger creates, versions, freezes and closes it exactly like any
+other account. A subaccount can forbid overdraft while its base account permits
+it, or the reverse, because every check keys on the full `AccountId`.
+
+Subaccounts partition one owner's holdings into several balances, and a caller
+can address each one. They serve as sub-ledgers, earmarks and reservations, and
+they need no unrelated top-level account. `AccountId` has these helpers:
+`new(id)` for the main account, `with_sub(id, sub)`, `base()` for the main
+account of an id, and `is_main()`.
+
+`AccountId` also has an IBAN-style string form through `Display` and `FromStr`.
+It is a fixed 20 characters: an 18-character base-36 body, then two ISO 7064
+mod-97 check digits at the end. There is no country code. An example is
+`KUJL QEL8 IX2X GTBK 4425`.
+
+The body packs the base id, which is 63 bits, and the subaccount, which is
+`SUB_BITS` bits, into one 93-bit value. A keyed format-preserving permutation
+then runs over that value before the encode step, and the parse step inverts the
+permutation. So a code does not reveal the raw ids. The key is a global seed
+with a default, and `set_id_seed` configures it.
+
+A parse validates the checksum, so the ledger rejects a mistyped identifier.
+This is obfuscation and not security, because the seed decodes it. The form is
+for display and for routes only, and storage keeps the two `i64` legs. The fixed
+width is what caps the subaccount at `SUB_BITS`. See ADR-0015.
+
+The ledger always reports a balance per subaccount and never sums balances
+across subaccounts:
 
 - `balance(&AccountId, &AssetId)` reads exactly one subaccount.
 - `balances(&AccountId, &AssetId, sub)` returns one entry per non-closed
-  subaccount (`sub = None` spans all, `Some(s)` filters to one).
+  subaccount. `sub = None` spans all of them, and `Some(s)` filters to one.
 - `list_subaccounts(&AccountId)` lists the non-closed subaccounts of a base id.
 
-A base account does **not** roll up its subaccounts: there is deliberately no
-API that sums across them. Aggregate reads take a base `id: i64` plus an
-optional subaccount filter (`get_postings_by_account`,
-`get_transfers_for_account`); exact entity operations take the full
-`&AccountId`. Book membership is scoped by base account: a book that lists a base
-account admits all of that account's subaccounts. See
+A base account does **not** roll up its subaccounts. There is deliberately no
+API that sums across them. An aggregate read takes a base `id: i64` plus an
+optional subaccount filter, as `get_postings_by_account` and
+`get_transfers_for_account` do. An exact entity operation takes the full
+`&AccountId`. Book membership has the base account as its scope, so a book that
+lists a base account admits every subaccount of that account. See
 [adr/0012-subaccounts.md](adr/0012-subaccounts.md).
 
 ## Balance constraint
 
-An account carries one balance rule, held in its flags:
+An account carries one balance rule, and its flags hold that rule:
 
 | State | Balance floor | Negative postings |
 |-------|--------------|-------------------|
 | default (no flag) | none | yes (overdraft allowed, unbounded) |
 | `DEBIT_MUST_NOT_EXCEED_CREDIT` | `>= 0` | no |
 
-By default an account may overdraw without bound. An overdraft is a negative
-posting (an offset position) assigned to the account to cover a shortfall: when
-the account's positive postings are insufficient for a debit, the resolve step
-consumes them all and creates a negative posting for the remainder. The transfer
-is recorded as long as it conserves value per asset.
-
-Setting `DEBIT_MUST_NOT_EXCEED_CREDIT` forbids this: the account's debits may
-never exceed its credits, so its balance may not go negative and it may not hold
-a negative posting. Validation rejects any transfer that would create a negative
-posting on such an account or project its balance below zero. The convenience
-constructor `Account::debit_must_not_exceed_credit(id)` names the invariant
-directly, and `Account::forbids_overdraft()` reports it. There is no bounded
-"credit line" floor between the two: a credit-line limit, if needed, is enforced
-by the application above the ledger.
-
-The zero floor is re-checked inside the commit transaction, over the live rows
-that survive the spend, so it is strict rather than best-effort. Double-spend
-safety comes from the same transaction: deleting a consumed live row is the
-atomic single-winner claim, so a posting cannot be consumed twice. See
+By default an account can overdraw without bound. An overdraft is a negative
+posting, which is an offset position, and the ledger assigns it to the account
+to cover a shortfall. The account's positive postings are sometimes not enough
+for a debit. The resolve step then consumes all of them and creates a negative
+posting for the remainder. The ledger records the transfer if it conserves value
+per asset.
+
+`DEBIT_MUST_NOT_EXCEED_CREDIT` forbids this. The account's debits must never
+exceed its credits, so its balance must not go negative and it must not hold a
+negative posting. Validation rejects any transfer that creates a negative
+posting on such an account, and any transfer that projects its balance below
+zero.
+
+The convenience constructor `Account::debit_must_not_exceed_credit(id)` names
+the invariant directly, and `Account::forbids_overdraft()` reports it. There is
+no bounded "credit line" floor between the two states. The application above the
+ledger enforces a credit-line limit if it needs one.
+
+The commit transaction re-checks the zero floor over the live rows that survive
+the spend, so the check is strict and not best-effort. Double-spend safety comes
+from the same transaction. The delete of a consumed live row is the atomic
+single-winner claim, so nothing can consume a posting twice. See
 [accounting-mapping.md](accounting-mapping.md) and the ADR at
 [adr/0023-atomic-storage-commit.md](adr/0023-atomic-storage-commit.md).
 
 ## Lifecycle
 
-Accounts follow a three-state lifecycle controlled by flags:
+An account follows a three-state lifecycle, and flags control it:
 
 ```
 Created (v1) → Frozen (v2) → Unfrozen (v3) → Closed (v4)
@@ -103,15 +114,16 @@ Created (v1) → Frozen (v2) → Unfrozen (v3) → Closed (v4)
 |-----------|-------------|--------|
 | `freeze(id)` | Not closed | Sets `FROZEN` flag, increments version |
 | `unfreeze(id)` | Frozen | Clears `FROZEN` flag, increments version |
-| `close(id)` | Zero active postings | Sets `CLOSED` flag, increments version |
+| `close(id)` | Zero live postings | Sets `CLOSED` flag, increments version |
 
-- **Frozen** accounts reject all transfers (both debits and credits).
-- **Closed** accounts reject all transfers and cannot be reopened.
-- Closing requires zero active postings for all assets.
+- A **frozen** account rejects every transfer, both a debit and a credit.
+- A **closed** account rejects every transfer, and nothing can reopen it.
+- A close needs zero live postings for every asset.
 
 ## Append-Only Versioning
 
-Accounts are never modified in place. Each mutation appends a new version:
+The ledger never modifies an account in place. Each mutation appends a new
+version:
 
 ```
 Version 1: { flags: DEBIT_MUST_NOT_EXCEED_CREDIT }          ← created
@@ -119,43 +131,47 @@ Version 2: { flags: DEBIT_MUST_NOT_EXCEED_CREDIT | FROZEN } ← frozen
 Version 3: { flags: DEBIT_MUST_NOT_EXCEED_CREDIT }          ← unfrozen
 ```
 
-The store enforces `version_new == version_current + 1`, preventing gaps or
-overwrites. The full history is queryable via `account_history(id)`.
+The store enforces `version_new == version_current + 1`, which prevents a gap
+and prevents an overwrite. `account_history(id)` queries the full history.
 
 ## Snapshot Pinning
 
-Transfers can carry `AccountSnapshotId` values: pairs of `(AccountId,
-snapshot_hash)` recording which account version the transfer was validated
-against.
+A transfer can carry `AccountSnapshotId` values. Each one is a pair of
+`(AccountId, snapshot_hash)`, and it records the account version that the
+transfer validated against.
 
-During validation, if snapshots are present, the current account state is
-hashed and compared. A mismatch produces `AccountVersionMismatch`,
-preventing TOCTOU races where an account is mutated between load and apply.
+During validation, when snapshots are present, the ledger hashes the current
+account state and compares the two. A mismatch produces
+`AccountVersionMismatch`. This prevents a TOCTOU race, where something mutates
+an account between the load and the apply.
 
-`commit()` auto-populates snapshots when none are provided.
+`commit()` fills in the snapshots when a caller provides none.
 
 ## Subaccounts and balances
 
-An account is identified by a base id plus an `i64` **subaccount**, written
-`AccountId { id, sub }`; `sub = 0` is the main account. Each `(id,
-sub)` is its own record with its own flags, book, and version, so a
-subaccount is a full account that happens to share a base id. Subaccounts are how
-one account holds many concurrent inflights: an inflight hold is a subaccount of
-its destination, keyed by a value derived from the trade (see
-[adr/0012-subaccounts.md](adr/0012-subaccounts.md)).
+A base id plus an `i64` **subaccount** identifies an account, written as
+`AccountId { id, sub }`. `sub = 0` is the main account. Each `(id, sub)` is its
+own record with its own flags, book and version, so a subaccount is a full
+account that shares a base id.
 
-Balances are reported **segregated per subaccount**, never summed across them:
+Subaccounts are how one account holds many concurrent inflights. An inflight
+hold is a subaccount of its destination, keyed by a value that the trade
+derives. See [adr/0012-subaccounts.md](adr/0012-subaccounts.md).
+
+The ledger reports a balance **segregated per subaccount** and never sums
+balances across subaccounts:
 
 - `balance(&AccountId, asset)` reads one subaccount.
-- `balances(&AccountId, asset, sub)` returns one entry per non-closed subaccount
-  (`sub = None` spans all; `Some(s)` filters to one). Closed subaccounts are
-  excluded.
+- `balances(&AccountId, asset, sub)` returns one entry per non-closed
+  subaccount. `sub = None` spans all of them, and `Some(s)` filters to one. It
+  excludes a closed subaccount.
 - `list_subaccounts(&AccountId)` lists the non-closed subaccounts of a base
   account.
 
 ## Balance Computation
 
-Balance for an (account reference, asset) pair is computed as:
+The ledger computes the balance for an (account reference, asset) pair like
+this:
 
 ```
 balance(account, asset) = sum(p.value for p in postings
@@ -164,48 +180,69 @@ balance(account, asset) = sum(p.value for p in postings
                               and   p.is_live)
 ```
 
-There is no stored balance field. This eliminates drift between the balance
-and the underlying postings.
+There is no stored balance field. So no drift can appear between the balance and
+the postings under it.
 
-A read returns an [`Amount`](glossary.md#amount): the asset rides along, so two
-balances of different assets cannot be added by the caller that holds them. The
-money type underneath is not public, so what a caller gets is the amount's own
+A read returns an [`Amount`](glossary.md#amount). The asset travels with the
+value, so a caller that holds two balances of different assets cannot add them.
+The money type underneath is not public. A caller gets the amount's own
 `Display`, its checked arithmetic, or `minor_units()` (ADR-0029). The asset must
-be registered, since an unregistered one has no precision to report at.
+be registered, because an unregistered one has no precision to report at.
+
+`balance_as_of(account, asset, as_of)` answers the same question at a past
+instant. It folds only the transfers that committed up to `as_of` onto the
+newest cache point at or before it (ADR-0019). `as_of` is a commit instant in
+unix milliseconds and not a value date.
 
-`balance_as_of(account, asset, as_of)` answers the same question at a past instant, by folding only the transfers committed up to `as_of` onto the newest cache point at or before it (ADR-0019). `as_of` is a commit instant in unix milliseconds, not a value date: the cache points a read folds against are watermarked by the commit clock, so an entry backdated with a [value date](transfers.md#booking-date-and-value-date) still lands at the instant it was committed. A past balance cannot come from the postings themselves, because a posting carries no timestamp.
+The commit clock watermarks the cache points that a read folds against. So an
+entry that a [value date](transfers.md#booking-date-and-value-date) backdates
+still lands at the instant of its commit. A past balance cannot come from the
+postings themselves, because a posting carries no timestamp.
 
 ## Account Types in Practice
 
-The single flag divides accounts into two kinds. Intent (wallet vs. boundary
-vs. system) is a matter of how you use the account, not a distinct type.
+The single flag divides accounts into two kinds. Intent is a matter of how you
+use the account, not a distinct type. A wallet, a boundary and a system account
+are all intents, not types.
 
 ### Overdraft-forbidding accounts (`DEBIT_MUST_NOT_EXCEED_CREDIT`)
 
-Hold positive postings only. Cannot go negative. Used for end-user wallets,
-merchant accounts, and any account that must never spend value it does not hold.
-Construct with `Account::debit_must_not_exceed_credit(id)`.
+These hold a positive posting only, and they cannot go negative. Use them for an
+end-user wallet, a merchant account, and any account that must never spend value
+it does not hold. Construct one with
+`Account::debit_must_not_exceed_credit(id)`.
 
 ### Overdraft-permitting accounts (default)
 
-An ordinary `Account::new(id)` may go negative without bound. This covers:
+An ordinary `Account::new(id)` can go negative without bound. This covers:
 
-- **Issuance / system balancing**: revenue, COGS, fees, or internal balancing
-  accounts that hold offset positions.
-- **Ledger boundary**: the counterparty in deposits and withdrawals, where value
-  enters or leaves the ledger. It takes on a negative balance to offset the value
-  credited elsewhere; this is normal, not a bug.
-- **Credit-like accounts**: where the balance is allowed below zero. The ledger
-  enforces no upper bound on the overdraft; a specific credit limit is the
-  application's responsibility.
+- **Issuance and system balance**: a revenue, COGS or fee account, or an
+  internal account that holds an offset position.
+- **Ledger boundary**: the counterparty in a deposit and in a withdrawal, where
+  value enters or leaves the ledger. It takes on a negative balance to offset
+  the value that the ledger credits elsewhere. This is normal and not a bug.
+- **Credit-like accounts**: an account whose balance can go below zero. The
+  ledger enforces no upper bound on the overdraft. A specific credit limit is
+  the application's responsibility.
 
-When such an account's positive postings are insufficient for a debit, a negative
-posting covers the shortfall.
+The positive postings of such an account are sometimes not enough for a debit. A
+negative posting then covers the shortfall.
 
 ## Accounts carry no accounting class
 
-There is no asset, liability, equity, income or expense dimension on an account. The [structure table](#structure) above is the whole record, and no field classifies it, so the ledger cannot group accounts the way a balance sheet or a profit-and-loss statement does. Those are the reports this blocks, and the only ones: a trial balance is a flat list of every account's balance, so it needs a read across accounts rather than a class.
-
-A class that is only reported on fits in `metadata`, which the ledger stores and never interprets. A class that has to be enforced fits better in one of the user-defined `AccountFlags` bits, because a book policy can gate participation on a flag and cannot gate on metadata. The [retail example](examples/retail.md) marks its revenue and warehouse accounts that way.
-
-> Classical accounting's "asset" names a class of account. Kuatia's [`Asset`](glossary.md#asset) names a currency or a commodity. The two senses are unrelated.
+There is no asset, liability, equity, income or expense dimension on an account.
+The [structure table](#structure) above is the whole record, and no field
+classifies it. So the ledger cannot group accounts the way a balance sheet or a
+profit-and-loss statement does. Those are the reports this blocks, and the only
+ones. A trial balance is a flat list of every account's balance, so it needs a
+read across accounts rather than a class.
+
+A class that something only reports on fits in `metadata`, which the ledger
+stores and never interprets. A class that the ledger has to enforce fits better
+in one of the user-defined `AccountFlags` bits. A book policy can gate
+participation on a flag, and it cannot gate on metadata. The [retail
+example](examples/retail.md) marks its revenue and warehouse accounts that way.
+
+> Classical accounting's "asset" names a class of account. Kuatia's
+> [`Asset`](glossary.md#asset) names a currency or a commodity. The two senses
+> are unrelated.

+ 85 - 87
doc/adr/0001-modified-utxo-signed-postings.md

@@ -8,138 +8,136 @@
 
 ## Context and Problem Statement
 
-A ledger must record value movements so that the result is auditable,
-supports multiple assets, behaves well under concurrency, and can
-represent overdraft or credit lines. How should value be represented at
-rest? The naïve answer, a mutable balance field per `(account, asset)`,
-throws away history and turns every account into a write-contended hot
-row. We want double-entry *safety* (`Σ debits = Σ credits`) without the
-brittleness of mutable running totals.
+A ledger must record value movements. The result must be auditable, must support
+many assets, must behave well under concurrency, and must represent an overdraft
+or a credit line. So how does a ledger hold value at rest?
+
+The naive answer is a mutable balance field per `(account, asset)`. That answer
+throws away history. It also turns every account into a hot row that writers
+contend on. We want double-entry *safety*, `Σ debits = Σ credits`, and we do not
+want the brittleness of a total that the ledger updates in place.
 
 ## Decision Drivers
 
-* **Auditability**: the full financial state should be reconstructible
-  by replaying recorded events, with no "trust me" mutable totals.
-* **Multi-asset**: one model for many assets, not a balance column per
-  asset.
-* **Concurrency**: avoid a single hot balance row that serializes all
-  activity on an account.
-* **Conservation as a structural property**: make "nothing is created
-  or destroyed" a checkable invariant, not a convention.
-* **Overdraft / credit**: represent a negative position naturally,
-  bounded by an account policy.
-* **Embeddability**: pure, deterministic core logic with no database
-  arithmetic.
+* **Auditability**: a replay of the recorded events must reconstruct the full
+  financial state. No mutable total asks a reader to trust it.
+* **Multi-asset**: one model for many assets, not a balance column per asset.
+* **Concurrency**: avoid a single hot balance row that serializes all activity
+  on an account.
+* **Conservation as a structural property**: make "nothing is created or
+  destroyed" a checkable invariant rather than a convention.
+* **Overdraft and credit**: represent a negative position naturally, with an
+  account policy as its bound.
+* **Embeddability**: pure, deterministic core logic with no database arithmetic.
 
 ## Considered Options
 
 #### Option 1: Mutable balance fields per `(account, asset)`
 
-A row holds the current balance; each transfer reads, mutates, and
-writes it.
+A row holds the current balance. Each transfer reads it, mutates it and writes
+it back.
 
 **Pros:**
 
-* Good, because balance reads are O(1): just read the column.
+* Good, because a balance read is O(1). It reads one column.
 * Good, because it is the most familiar model.
 
 **Cons:**
 
-* Bad, because history is lost: you cannot audit how a balance was
-  reached without a separate, independently-trusted journal.
-* Bad, because the balance row is a concurrency hot spot; every transfer
-  on an account contends on it.
-* Bad, because conservation is a convention enforced by application
-  code, not a property of the data.
+* Bad, because the model loses history. You cannot audit how a balance arrived
+  at its value, unless a separate journal that you trust on its own records it.
+* Bad, because the balance row is a concurrency hot spot. Every transfer on an
+  account contends on it.
+* Bad, because conservation is a convention that application code enforces. The
+  data does not hold it as a property.
 
 #### Option 2: Classic (Bitcoin-style) UTXO, non-negative outputs
 
-Value is held as immutable outputs that are consumed and created;
-outputs cannot be negative.
+The model holds value as immutable outputs. A transfer consumes them and creates
+them. An output cannot be negative.
 
 **Pros:**
 
-* Good, because it is auditable (consume/create history) and avoids a
-  hot row.
-* Good, because conservation is naturally expressible
-  (`sum in == sum out`).
+* Good, because it is auditable, through the history of what it consumed and
+  created, and it avoids a hot row.
+* Good, because the model expresses conservation naturally, as
+  `sum in == sum out`.
 
 **Cons:**
 
-* Bad, because non-negative outputs cannot represent overdraft or credit
-  lines.
-* Bad, because the Bitcoin model carries scripting/locking machinery
-  irrelevant to an accounting ledger.
+* Bad, because a non-negative output cannot represent an overdraft or a credit
+  line.
+* Bad, because the Bitcoin model carries script and lock machinery that an
+  accounting ledger does not need.
 
 #### Option 3: Signed postings ("modified UTXO")
 
-Value is held as **signed postings**: an immutable, signed amount of one
-asset owned by one account, with a lifecycle
-(`Active → PendingInactive → Inactive`). A transfer **consumes**
-postings and **creates** postings; a posting may be **negative** (an
-"offset position") to represent an overdraft.
+The model holds value as **signed postings**. A posting is an immutable, signed
+amount of one asset, and one account owns it. It has a lifecycle:
+`Active → PendingInactive → Inactive`. A transfer **consumes** postings and
+**creates** postings. A posting can be **negative**, which is an "offset
+position", and that represents an overdraft.
 
 **Pros:**
 
-* Good, because it keeps full history and is auditable by replaying the
-  transfer log; balances are *projections* over `Active` postings and
-  are never stored.
-* Good, because conservation is enforced directly:
-  `sum(consumed) == sum(created)` per asset on every committed transfer
-  (`validate_and_plan`, `ConservationViolation`).
-* Good, because it is multi-asset by construction (a posting names its
-  asset).
-* Good, because there is no hot balance row: different postings of the
-  same account can be touched independently, enabling UTXO-style
-  concurrency and future sharding.
-* Good, because overdraft is just a negative posting, bounded by account
-  policy (`NoOverdraft`, `CappedOverdraft { floor }`,
-  `UncappedOverdraft`, and so on).
+* Good, because it keeps the full history. A replay of the transfer log audits
+  it. A balance is a *projection* over the `Active` postings, and the ledger
+  never stores one.
+* Good, because the model enforces conservation directly. Every committed
+  transfer satisfies `sum(consumed) == sum(created)` per asset, through
+  `validate_and_plan` and `ConservationViolation`.
+* Good, because it is multi-asset by construction, since a posting names its
+  asset.
+* Good, because there is no hot balance row. Two postings of one account can
+  move on their own, which allows UTXO-style concurrency and a later sharding.
+* Good, because an overdraft is only a negative posting, and an account policy
+  bounds it: `NoOverdraft`, `CappedOverdraft { floor }`, `UncappedOverdraft`,
+  and so on.
 
 **Cons:**
 
-* Bad, because a balance is computed (sum over `Active` postings), not
-  read: a read cost the store must support efficiently.
-* Bad, because the word *posting* (a noun: a value fragment) collides
-  with the accounting verb "to post", a documented source of confusion.
-* Bad, because spending requires **posting selection** and change-making
-  (greedy largest-first), machinery a mutable-balance model would not
-  need.
+* Bad, because the ledger computes a balance as a sum over the `Active` postings
+  and does not read one. That is a read cost the store must carry efficiently.
+* Bad, because the word *posting* is a noun here, a value fragment, and it
+  collides with the accounting verb "to post". The documents record that source
+  of confusion.
+* Bad, because a spend needs **posting selection**, and it must make change, by
+  greedy largest-first. A mutable-balance model needs neither.
 
 ## Decision Outcome
 
-Chosen option: **Option 3, signed postings ("modified UTXO")**, because
-it is the only option that delivers auditability, a hot-row-free
-concurrency model, and natural overdraft, while making per-asset
-conservation a structural, checkable invariant. The "modification" over
-classic UTXO is precisely that postings may be negative (offset
-positions) and there is no scripting layer.
+Chosen option: **Option 3, signed postings ("modified UTXO")**. It is the only
+option that delivers auditability, a concurrency model with no hot row, and
+natural overdraft. It also makes per-asset conservation a structural, checkable
+invariant.
+
+The "modification" over classic UTXO is exactly this: a posting can be negative,
+which is an offset position, and there is no script layer.
 
 ### Positive Consequences
 
-* The transfer log (`TransferStore` of `EnvelopeRecord`s) is the
-  append-only source of truth; balances are derived, so they cannot
-  silently diverge.
-* Double-entry safety is enforced in the pure core and testable with
-  golden vectors, independent of any storage backend.
-* The posting lifecycle (Active/PendingInactive/Inactive) gives the saga
-  a place to reserve inputs without mutating balances. See ADR-0002 and
+* The transfer log, a `TransferStore` of `EnvelopeRecord`s, is the append-only
+  source of truth. A balance is derived, so it cannot diverge quietly.
+* The pure core enforces double-entry safety, and golden vectors can test it,
+  apart from any storage backend.
+* The posting lifecycle, `Active`, `PendingInactive` and `Inactive`, gives the
+  saga a place to reserve inputs with no mutation of a balance. See ADR-0002 and
   ADR-0003.
 
 ### Negative Consequences
 
-* Balance queries sum over `Active` postings; the store indexes
-  `(owner, asset, status)` to keep this cheap, and all such arithmetic
-  is done in Rust with checked operations (never in SQL).
-* Posting selection / change-making is required on the spend path.
-* Terminology must be taught: see
-  [accounting-mapping.md](../accounting-mapping.md) for the
-  classical-accounting to Kuatia mapping and the noun/verb caveat.
+* A balance query sums over the `Active` postings. The store indexes
+  `(owner, asset, status)` to keep that cheap. Rust does all of that arithmetic
+  with checked operations, and SQL does none of it.
+* The spend path needs posting selection, and it must make change.
+* A reader must learn the terminology. See
+  [accounting-mapping.md](../accounting-mapping.md) for the mapping from
+  classical accounting onto Kuatia, and for the noun and verb caveat.
 
 ## Links
 
-* Refined by [ADR-0002](0002-saga-commit-pipeline.md) (how postings are
-  committed) and [ADR-0003](0003-dumb-storage-saga-recovery.md) (the
-  storage/commit contract).
+* Refined by [ADR-0002](0002-saga-commit-pipeline.md), which says how the ledger
+  commits a posting, and by [ADR-0003](0003-dumb-storage-saga-recovery.md),
+  which gives the storage and commit contract.
 * Background: [accounting-mapping.md](../accounting-mapping.md),
   [glossary.md](../glossary.md), [accounts.md](../accounts.md).

+ 80 - 72
doc/adr/0002-saga-commit-pipeline.md

@@ -8,50 +8,54 @@
 
 ## Context and Problem Statement
 
-Committing a transfer is not one write. It must consume input postings, create
-output postings, persist the transfer record, index it under every involved
-account, and emit events, consistently and recoverably if the process crashes
-mid-way. Kuatia is an embeddable library that should not require an external
-transaction coordinator, and it should compose multi-transfer workflows (e.g.
-an FX trade, a multi-leg settlement) without a global lock. How do we make a
-commit both consistent and crash-safe without a single all-encompassing
-transaction?
+A commit of a transfer is not one write. It must consume the input postings and
+create the output postings. It must persist the transfer record and index that
+record under every involved account. It must emit the events. All of this must
+stay consistent, and it must recover if the process crashes part way through.
+
+Kuatia is an embeddable library, so it must not need an external transaction
+coordinator. It must also compose a multi-transfer workflow with no global lock,
+and an FX trade and a multi-leg settlement are two such workflows. So how do we
+make a commit both consistent and crash-safe, without one transaction that
+covers everything?
 
 ## Decision Drivers
 
-* **Crash-safety**: a crash must never leave value created without a recorded
-  transfer (or vice-versa); recovery must converge.
-* **Composability**: several transfers should combine into one logical workflow
-  with rollback across the whole workflow.
-* **No external coordinator**: embeddable, no XA transaction manager or
-  separate service to operate.
-* **Avoid cross-shard / cross-resource transactions**: the model should not
-  depend on a single database transaction spanning everything, so future
-  sharding (UTXO-style) stays open.
-* **Keep storage dumb**: push domain decisions out of the storage layer (see
-  ADR-0003), which a monolithic store-side transaction works against.
+* **Crash-safety**: a crash must never leave created value with no recorded
+  transfer, and must never leave a recorded transfer with no value. Recovery
+  must converge.
+* **Composability**: several transfers must combine into one logical workflow,
+  and a rollback must cover that whole workflow.
+* **No external coordinator**: embeddable, no XA transaction manager or separate
+  service to operate.
+* **Avoid a cross-shard or cross-resource transaction**: the model must not
+  depend on one database transaction that covers everything. A later UTXO-style
+  sharding then stays open.
+* **Keep storage simple**: push the domain decisions out of the storage layer
+  (see ADR-0003). A monolithic transaction on the store side works against that.
 
 ## Considered Options
 
 #### Option 1: One database transaction (monolithic commit)
 
-Do everything (deactivate, insert, store record, index, events) inside a single
-`BEGIN … COMMIT`.
+Do everything inside one `BEGIN … COMMIT`: the deactivate, the insert, the
+record, the index and the events.
 
 **Pros:**
 
-* Good, because it gives strict atomicity on a single database.
-* Good, because recovery is trivial: the DB rolls back a partial commit.
+* Good, because it gives strict atomicity on one database.
+* Good, because recovery is trivial. The database rolls back a partial commit.
 
 **Cons:**
 
-* Bad, because it does not compose across multiple transfers/resources: a
-  multi-leg workflow cannot be one DB transaction without holding locks across
-  all of it.
-* Bad, because it does not span shards/resources; it pins the design to a
-  single transactional store.
-* Bad, because it pulls domain logic (guards, ownership, indexing decisions)
-  into the storage layer, the opposite of the dumb-storage goal (ADR-0003).
+* Bad, because it does not compose across several transfers or resources. A
+  multi-leg workflow cannot be one database transaction unless it holds locks
+  across all of it.
+* Bad, because it spans neither a shard nor another resource. It pins the design
+  to one transactional store.
+* Bad, because it pulls the domain logic into the storage layer, and that covers
+  the guards, the ownership and the index decisions. It is the opposite of the
+  simple-storage goal (ADR-0003).
 
 #### Option 2: Two-phase commit / XA across resources
 
@@ -63,72 +67,76 @@ Coordinate a distributed transaction over the resources involved.
 
 **Cons:**
 
-* Bad, because it needs a coordinator and XA-capable resources: heavy
-  operationally and at odds with "embeddable, no external services."
-* Bad, because 2PC is blocking: a coordinator failure can leave resources
-  locked.
+* Bad, because it needs a coordinator and resources that support XA. That is
+  heavy to operate, and it conflicts with the goal of an embeddable library with
+  no external service.
+* Bad, because 2PC blocks. A coordinator failure can leave the resources locked.
 * Bad, because it is overkill for a library meant to drop into an application.
 
 #### Option 3: Saga with per-step compensation (the `legend` crate)
 
-Model the commit as a pipeline of small steps (reserve → finalize), each with
-a compensating action, driven by `legend`, with automatic retry and LIFO
-compensation. Crash-safety comes from a write-ahead record plus idempotent
-recovery rather than a global transaction.
+Model the commit as a pipeline of small steps, `reserve → finalize`, and give
+each step a compensating action. `legend` drives the pipeline, retries a step by
+itself, and compensates in last-in-first-out order. Crash-safety comes from a
+write-ahead record plus idempotent recovery, rather than from a global
+transaction.
 
 **Pros:**
 
-* Good, because steps compose: higher-level multi-transfer sagas combine the
-  same primitives with workflow-wide compensation.
-* Good, because no global or distributed transaction and no coordinator are
-  required; it suits an embeddable library.
-* Good, because reserving inputs (`Active → PendingInactive`, stamped with a
-  `ReservationId`) gives unconditional double-spend safety without locking
-  balances: a single atomic conditional update per posting.
-* Good, because it keeps storage dumb: each step issues simple instructions and
-  the saga owns the decisions (ADR-0003).
+* Good, because the steps compose. A higher-level multi-transfer saga combines
+  the same primitives, and its compensation covers the whole workflow.
+* Good, because it needs no global transaction, no distributed transaction and
+  no coordinator. That suits an embeddable library.
+* Good, because a reserve of the inputs gives unconditional double-spend safety
+  and locks no balance. It moves a posting `Active → PendingInactive` and stamps
+  it with a `ReservationId`, as one atomic conditional update per posting.
+* Good, because it keeps storage simple. Each step issues a simple instruction,
+  and the saga owns the decisions (ADR-0003).
 
 **Cons:**
 
-* Bad, because a commit passes through brief intermediate states (postings
-  reserved/partially finalized) rather than flipping atomically.
-* Bad, because idempotency and end-state verification become the saga's
-  responsibility, not the database's.
-* Bad, because some cross-cutting guarantees (e.g. the CappedOverdraft floor)
-  can only be made best-effort without a commit-time atomic guard. See
-  ADR-0003.
+* Bad, because a commit passes through brief intermediate states rather than one
+  atomic change. A posting is reserved, or finalized in part, in those states.
+* Bad, because idempotency and the check of the end state become the saga's
+  responsibility and not the database's.
+* Bad, because some guarantees stay best-effort without an atomic guard at
+  commit time. The `CappedOverdraft` floor is one of them, and it cuts across
+  the model. See ADR-0003.
 
 ## Decision Outcome
 
-Chosen option: **Option 3, a saga commit pipeline** (`reserve → finalize`,
-via `legend`), because it is the only option that composes multi-transfer
-workflows, needs no external coordinator, and keeps storage dumb, while still
-providing crash-safety (through a write-ahead record + idempotent recovery)
-and unconditional double-spend safety (through the reservation protocol).
+Chosen option: **Option 3, a saga commit pipeline**, which is
+`reserve → finalize` through `legend`. It is the only option that composes a
+multi-transfer workflow, needs no external coordinator and keeps storage simple.
+
+It still gives crash-safety, through a write-ahead record plus idempotent
+recovery. It still gives unconditional double-spend safety, through the
+reservation protocol.
 
 ### Positive Consequences
 
 * The same steps drive both a single commit and multi-transfer workflows, with
   automatic retry and LIFO compensation on logical failure.
-* Reservation makes consumed-posting double-spend impossible without a global
-  lock, preserving the UTXO concurrency model from ADR-0001.
-* Storage stays a thin record keeper; the commit's correctness lives in one
-  testable place.
+* Reservation makes a double-spend of a consumed posting impossible, and it
+  needs no global lock. So the UTXO concurrency model of ADR-0001 survives.
+* Storage stays a thin record keeper. The correctness of the commit lives in one
+  place that a test can reach.
 
 ### Negative Consequences
 
-* Crash-safety is not "the DB rolls it back" but write-ahead + roll-forward
-  recovery, which the saga must implement idempotently. See ADR-0003.
+* Crash-safety is not a rollback by the database. It is a write-ahead record
+  plus a roll-forward recovery, and the saga must implement that idempotently.
+  See ADR-0003.
 * Within a commit there are observable intermediate posting states.
-* The exact recovery model and the best-effort guards are non-trivial and are
-  the subject of ADR-0003.
+* The exact recovery model and the best-effort guards are not simple, and
+  ADR-0003 covers them.
 
 ## Links
 
-* Refined by [ADR-0003](0003-dumb-storage-saga-recovery.md): the storage
-  contract, count interpretation, and the durable phase-tracked recovery the
-  saga relies on.
-* Builds on [ADR-0001](0001-modified-utxo-signed-postings.md): the posting
-  lifecycle the reserve step uses.
+* Refined by [ADR-0003](0003-dumb-storage-saga-recovery.md). That record gives
+  the storage contract, says how to read a count, and defines the durable
+  recovery with tracked phases that the saga depends on.
+* Builds on [ADR-0001](0001-modified-utxo-signed-postings.md), which gives the
+  posting lifecycle that the reserve step uses.
 * Background: [architecture.md](../architecture.md),
   [transfers.md](../transfers.md).

+ 123 - 95
doc/adr/0003-dumb-storage-saga-recovery.md

@@ -9,138 +9,166 @@
 
 ## Context and Problem Statement
 
-ADR-0002 chose a saga commit pipeline. Its finalize step still funneled
-everything into one monolithic store transaction,
-`CommitStore::commit_transfer`, which bundled ~8 responsibilities (deactivate,
-insert, store record, index both sides, CAS balance guards, account-version
-guards, reservation authorization, event append) into a single database
-transaction. Two problems surfaced: (1) the storage layer carried a lot of
-domain assumptions (it interpreted state, enforced guards, decided idempotency
-and error semantics), undercutting the "dumb record keeper" goal; and (2)
-crash recovery was designed (`SagaStore`, `legend` pause/resume) but never
-wired, so that single transaction was the *only* thing protecting against a
-half-applied commit. What is the right division of responsibility between the
-store and the saga, and how is a commit made crash-safe without that monolithic
-transaction?
+ADR-0002 chose a saga commit pipeline. Its finalize step still sent everything
+into one monolithic store transaction, `CommitStore::commit_transfer`. That one
+database transaction held about eight responsibilities:
+
+* The deactivate and the insert.
+* The record, and the index on both sides.
+* The CAS balance guards and the account-version guards.
+* The reservation authorization.
+* The event append.
+
+Two problems came out of that.
+
+First, the storage layer carried many domain assumptions. It read state,
+enforced guards, and decided both the idempotency and the error semantics. That
+cut against the goal of a simple record keeper.
+
+Second, the crash recovery had a design, through `SagaStore` and the pause and
+resume of `legend`, and nothing had wired it up. So that one transaction was the
+*only* protection against a half-applied commit.
+
+So what is the right division of responsibility between the store and the saga?
+And how does a commit become crash-safe without that monolithic transaction?
 
 ## Decision Drivers
 
-* **Dumb storage**: the store should follow instructions and report results,
-  not make domain decisions; correctness logic should live in one testable
-  place.
-* **Crash-safety without a global transaction**: recovery must converge from a
-  crash at any point and never commit something that did not validate or
-  consume postings it does not own.
-* **No silent divergence / no double-spend**: preserve the unconditional
-  double-spend guarantee from the reservation protocol.
-* **Testability**: per-primitive conformance tests and crash-injection recovery
-  tests over a small, well-defined surface.
+* **Simple storage**: the store must follow an instruction and report the
+  result. It must make no domain decision. The correctness logic must live in
+  one place that a test can reach.
+* **Crash-safety with no global transaction**: recovery must converge from a
+  crash at any point. It must never commit something that failed validation, and
+  never consume a posting that it does not own.
+* **No quiet divergence and no double-spend**: keep the unconditional
+  double-spend guarantee that the reservation protocol gives.
+* **A surface a test can reach**: one conformance test per primitive, and a
+  recovery test that injects a crash. Both run over a small, well-defined
+  surface.
 
 ## Considered Options
 
 #### Option 1: Store is the atomic invariant boundary (`commit_transfer`)
 
-Keep one store method that atomically applies the whole commit and enforces all
-guards inside a single transaction.
+Keep one store method. It applies the whole commit atomically and enforces every
+guard inside one transaction.
 
 **Pros:**
 
-* Good, because atomicity and crash-safety on a single database are trivial.
-* Good, because all guards (floor, version, reservation) are re-checked
-  atomically with the write.
+* Good, because atomicity and crash-safety are trivial on one database.
+* Good, because every guard re-checks atomically with the write, and those are
+  the floor, the version and the reservation.
 
 **Cons:**
 
-* Bad, because the store is no longer dumb: it interprets state, decides
-  idempotency, enforces domain guards, and chooses error semantics.
-* Bad, because it pins crash-safety to one transactional store and does not
-  compose with the saga's multi-step / multi-resource ambitions (ADR-0002).
-* Bad, because the commit/abort logic is split between the saga and a large
-  store method, making correctness hard to locate and test.
+* Bad, because the store is no longer simple. It reads state, decides
+  idempotency, enforces a domain guard, and chooses the error semantics.
+* Bad, because it pins crash-safety to one transactional store. It composes with
+  neither the multi-step ambition nor the multi-resource ambition of the saga
+  (ADR-0002).
+* Bad, because the commit and abort logic sits in two places, the saga and a
+  large store method. Correctness is then hard to find and hard to test.
 
 #### Option 2: Dumb storage + saga interpretation + durable recovery
 
-Storage write methods apply one update and return the **number of affected
-rows** (or an I/O error); they never interpret the count, decide state, enforce
-idempotency, or compensate. The saga interprets counts (full = continue;
-partial = error → compensate; zero = read state and continue only if this same
-envelope/reservation already applied it) and verifies end-states. Crash-safety
-is a **phase-tracked write-ahead record** (`PendingSaga {envelope, reservation,
-phase}`) plus **idempotent roll-forward** in `Ledger::recover()`.
+A storage write method applies one update and returns the **number of affected
+rows**, or an IO error. It never reads that count, never decides state, never
+enforces idempotency and never compensates.
+
+The saga reads the count. A full count means continue. A partial count is an
+error, so it compensates. A zero count means it reads the state, and it
+continues only when this same envelope or reservation already applied the
+update. The saga then verifies every end state.
+
+Crash-safety is a **write-ahead record with tracked phases**, which is
+`PendingSaga {envelope, reservation, phase}`, plus an **idempotent
+roll-forward** in `Ledger::recover()`.
 
 **Pros:**
 
-* Good, because the store is a thin record keeper with no domain logic; all
-  commit correctness lives in the saga and is unit-testable.
-* Good, because it composes with the saga model and does not require a single
-  all-encompassing transaction.
-* Good, because recovery is correct by construction: a `Reserving` saga is
-  re-run and **re-validated**; a `Finalizing` saga (already validated, owns its
-  postings) is rolled forward through a verified path; nothing commits unless
-  all consumed postings are confirmed `Inactive`.
+* Good, because the store is a thin record keeper with no domain logic. Every
+  part of the commit's correctness lives in the saga, where a unit test reaches
+  it.
+* Good, because it composes with the saga model, and it needs no single
+  transaction that covers everything.
+* Good, because recovery is correct by construction. A `Reserving` saga runs
+  again and **validates again**. A `Finalizing` saga already validated and owns
+  its postings, so recovery rolls it forward through a path it verifies. Nothing
+  commits until every consumed posting is confirmed `Inactive`.
 
 **Cons:**
 
-* Bad, because correctness now depends on the saga implementing idempotency and
-  end-state verification precisely (no DB safety net).
-* Bad, because guards that were re-checked atomically inside `commit_transfer`
-  (CappedOverdraft floor, freeze/close) become **best-effort**: re-validated as
-  the last step before the writes, but not strictly atomic with them.
+* Bad, because correctness now depends on the saga. The saga must implement the
+  idempotency and the end-state check exactly, and the database gives no safety
+  net.
+* Bad, because two guards that re-checked atomically inside `commit_transfer`
+  become **best-effort**, and those are the `CappedOverdraft` floor and the
+  freeze and close checks. They validate again as the last step before the
+  writes, and they are not strictly atomic with them.
 
 ## Decision Outcome
 
-Chosen option: **Option 2, dumb storage + saga interpretation + durable
-recovery**, because it is the only option that keeps the storage layer dumb and
-composable with the saga while still providing crash-safety and unconditional
-double-spend safety. Concretely:
-
-* **Storage primitives** return `Result<u64, StoreError>`: `reserve_postings`,
-  `release_postings`, `deactivate_postings`, `insert_postings`,
-  `store_transfer(record, involved)`, and an idempotent `append_event`. The
-  monolithic `commit_transfer` / `CommitStore` / `CommitRequest` and the
-  semantic write-outcome error variants are removed.
-* **The saga owns the commit**: two steps, `reserve → finalize`. Validation
-  runs inside finalize, as its last action before writing, the tightest-window
-  floor and freeze/close re-check. `finalize_envelope` verifies every end-state
-  and never creates/stores unless **all** consumed postings are `Inactive`.
-* **One commit path**: `commit(transfer)` resolves then runs `commit_envelope`;
-  `reverse()` runs the same path; there is no separate raw/atomic entry point.
-* **Durable recovery**: a `PendingSaga` is written before any mutation
-  (`Reserving`), bumped to `Finalizing` at the point of no return. `recover()`
-  branches on the phase; the record is deleted only on commit or a clean
-  pre-finalize abort, and roll-forward (not rollback) means no orphaned
-  `PendingInactive` postings to reconcile.
-
-`legend`'s pause/resume is for external waits, not crash checkpoints, so
-durable recovery is this write-ahead layer around `legend`, not serialization
-of the in-flight execution.
+Chosen option: **Option 2, simple storage, where the saga reads the counts and a
+durable recovery repairs a crash**. It is the only option that keeps the storage
+layer simple and composable with the saga. It still gives crash-safety, and it
+still gives unconditional double-spend safety.
+
+In detail:
+
+* **A storage primitive** returns `Result<u64, StoreError>`. Those primitives
+  are `reserve_postings`, `release_postings`, `deactivate_postings`,
+  `insert_postings`, `store_transfer(record, involved)`, and an idempotent
+  `append_event`. This change removes the monolithic `commit_transfer`,
+  `CommitStore` and `CommitRequest`, and the error variants that carried a write
+  outcome.
+* **The saga owns the commit**, in two steps, `reserve → finalize`. Validation
+  runs inside finalize, as its last action before the write. That gives the
+  narrowest window for the re-check of the floor and of the freeze and close
+  guards. `finalize_envelope` verifies every end state. It creates nothing and
+  stores nothing until **every** consumed posting is `Inactive`.
+* **One commit path**: `commit(transfer)` resolves and then runs
+  `commit_envelope`. `reverse()` runs the same path. There is no separate raw
+  entry point and no separate atomic one.
+* **A durable recovery**: the ledger writes a `PendingSaga` before any mutation,
+  in the `Reserving` phase. It moves that record to `Finalizing` at the point of
+  no return. `recover()` branches on the phase. The ledger deletes the record on
+  a commit, or on a clean abort before finalize, and never otherwise. Recovery
+  rolls forward and does not roll back, so no orphaned `PendingInactive` posting
+  is left to reconcile.
+
+The pause and resume of `legend` exist for an external wait, and not for a crash
+checkpoint. So the durable recovery is this write-ahead layer around `legend`.
+It does not serialize the execution that is in flight.
 
 ### Positive Consequences
 
-* The storage surface is small, uniform (counts, not verdicts), and covered by
-  a shared conformance suite that both the in-memory and SQL backends pass.
-* All commit/abort/recovery correctness is in the saga, exercised by
-  crash-injection tests (re-drive `Reserving`, roll forward a partial finalize,
-  abort+release when an account is frozen, refuse to double-spend a taken
-  posting).
-* Double-spend safety is unconditional (reservation protocol).
+* The storage surface is small and uniform, because it returns a count and never
+  a verdict. One shared conformance suite covers it, and both the in-memory
+  backend and the SQL backend pass that suite.
+* Every part of the correctness of a commit, an abort and a recovery sits in the
+  saga. Tests that inject a crash exercise it. They re-drive `Reserving`. They
+  roll a partial finalize forward. They abort and release when an account is
+  frozen. They refuse to double-spend a posting that something else took.
+* Double-spend safety is unconditional, through the reservation protocol.
 
 ### Negative Consequences
 
-* **CappedOverdraft floor and freeze/close are tightest best-effort, not
-  strictly atomic.** Finalize re-validates immediately before the writes (and
-  on the recovery path), shrinking the check-to-write window to one step, but
-  without folding the check into the write (a CAS) or per-account
-  serialization, a concurrent commit in that last sub-step gap can still breach
-  a floor. If hard floors are ever required, a follow-up ADR should add
-  per-`(account, asset)` serialization or a narrow commit-time CAS.
+* **The `CappedOverdraft` floor and the freeze and close guards are best-effort
+  at their narrowest, and not strictly atomic.** Finalize validates again
+  immediately before the writes, and on the recovery path too. That takes the
+  window from the check to the write down to one step.
+
+The check still does not fold into the write as a CAS, and nothing serializes
+per account. So a concurrent commit inside that last gap can still breach a
+floor. If anything ever needs a hard floor, a later record must add
+serialization per `(account, asset)`, or a narrow CAS at commit time.
 * The saga must keep its idempotency and verification invariants exact; the DB
   no longer provides a rollback safety net.
 
 ## Links
 
-* Refines [ADR-0002](0002-saga-commit-pipeline.md) and supersedes its
-  monolithic `commit_transfer` finalize.
+* Refines [ADR-0002](0002-saga-commit-pipeline.md) and supersedes its monolithic
+  `commit_transfer` finalize.
 * Builds on [ADR-0001](0001-modified-utxo-signed-postings.md).
 * Background: [architecture.md](../architecture.md) (commit pipeline, recovery,
   the floor-under-concurrency section), [accounts.md](../accounts.md).

+ 65 - 58
doc/adr/0004-account-policies-overdraft-model.md

@@ -14,24 +14,26 @@
 
 ## Context and Problem Statement
 
-ADR-0001 makes value *signable*: a posting may be negative ("offset
-position"). But "may be negative" is not a per-account truth. A customer
-wallet must never go negative, a credit line may go negative down to a
-limit, and a system/boundary account is unbounded by design. Something
-must decide, per account, whether a negative posting is allowed and how
-far. Where does that rule live, and what shape does it take?
+ADR-0001 makes value *signable*, so a posting can be negative, which is an
+"offset position". But "can be negative" is not one truth for every account. A
+customer wallet must never go negative. A credit line can go negative down to a
+limit. A system or boundary account is unbounded by design.
+
+Something must decide, per account, whether that account can hold a negative
+posting, and how far it can go. So where does that rule live, and what shape
+does it take?
 
 ## Decision Drivers
 
-* **Per-account semantics**: overdraft permission and floor differ by
-  account kind, not globally.
-* **Validation, not storage**: the rule belongs in the pure validator,
-  checked on every transfer.
-* **Closed, legible taxonomy**: a small set of named intents is easier to
-  reason about and audit than free-form flags.
-* **Boundary/system accounts**: deposits and withdrawals need an account
-  that may be arbitrarily negative (value entering or leaving the ledger)
-  without being a "bug."
+* **Per-account semantics**: the overdraft permission and the floor differ by
+  the kind of account, not across the whole ledger.
+* **Validation, not storage**: the rule belongs in the pure validator, which
+  checks it on every transfer.
+* **A closed, legible taxonomy**: a small set of named intents is easier to
+  reason about and to audit than a free-form flag.
+* **A boundary or system account**: a deposit and a withdrawal need an account
+  that can go negative without limit. Value enters or leaves the ledger there.
+  That must not read as a bug.
 
 ## Considered Options
 
@@ -47,10 +49,10 @@ Two fields on the account control negativity and bound.
 
 * Bad, because illegal combinations are representable (`allow_negative = false`
   with a non-zero floor) and must be guarded.
-* Bad, because intent is implicit. A reader cannot tell a "customer
-  wallet" from a "boundary account" from the fields alone.
-* Bad, because future kinds (e.g. distinct system vs. external semantics)
-  have no natural home.
+* Bad, because the intent stays implicit. A reader cannot tell a "customer
+  wallet" from a "boundary account" by the fields alone.
+* Bad, because a later kind has no natural home, and separate semantics for a
+  system account and an external account are one such kind.
 
 #### Option 2: Per-asset policy on each account
 
@@ -58,68 +60,73 @@ Policy varies by `(account, asset)`.
 
 **Pros:**
 
-* Good, because it allows an account to be NoOverdraft in one asset and a
-  credit line in another.
+* Good, because it lets one account be `NoOverdraft` in one asset and a credit
+  line in another.
 
 **Cons:**
 
-* Bad, because it multiplies configuration and validation surface for a
-  need the domain rarely has.
-* Bad, because it complicates the account model (policy is no longer an
-  account property but an account×asset matrix).
+* Bad, because it multiplies the configuration surface and the validation
+  surface, for a need that the domain has rarely.
+* Bad, because it complicates the account model. The policy is no longer a
+  property of an account and becomes a matrix of account against asset.
 
 #### Option 3: A closed `AccountPolicy` enum per account
 
-`NoOverdraft`, `CappedOverdraft { floor }`, `UncappedOverdraft`,
-`SystemAccount`, `ExternalAccount`. Only `NoOverdraft` forbids negative
-postings; the other four permit them; `CappedOverdraft` bounds them at
-`floor`; the rest are unbounded.
+The variants are `NoOverdraft`, `CappedOverdraft { floor }`,
+`UncappedOverdraft`, `SystemAccount` and `ExternalAccount`. Only `NoOverdraft`
+forbids a negative posting, and the other four permit one. `CappedOverdraft`
+bounds it at `floor`, and the rest are unbounded.
 
 **Pros:**
 
-* Good, because each variant names an intent (customer wallet, credit line, fee
-  pool, value boundary), making accounts self-documenting and auditable.
-* Good, because illegal states are unrepresentable (a floor only exists on
-  `CappedOverdraft`).
-* Good, because validation maps cleanly: reject a negative posting on
-  `NoOverdraft`; enforce `floor` on `CappedOverdraft`; allow the rest.
+* Good, because each variant names an intent: a customer wallet, a credit line,
+  a fee pool, a value boundary. An account then documents itself, and an audit
+  can read it.
+* Good, because an illegal state has no representation. A floor exists on
+  `CappedOverdraft` alone.
+* Good, because validation maps onto it cleanly. Reject a negative posting on
+  `NoOverdraft`. Enforce `floor` on `CappedOverdraft`. Allow the rest.
 
 **Cons:**
 
-* Bad, because adding a new policy is an enum change (a deliberate,
-  reviewed event rather than a config tweak).
-* Bad, because per-asset variation is not expressible without modeling it
-  separately.
+* Bad, because a new policy means a change to the enum. That is a deliberate
+  event that someone reviews, rather than a change to a configuration file.
+* Bad, because the model cannot express a per-asset variation. Something must
+  model that on its own.
 
 ## Decision Outcome
 
-Chosen option: **Option 3, a closed `AccountPolicy` enum per account**,
-because it makes account intent explicit and auditable, keeps illegal
-states unrepresentable, and maps directly onto the two validation rules
-(negative-posting permission and floor). `SystemAccount` and
-`ExternalAccount` give deposits and withdrawals a principled home (value
-boundaries that may run arbitrarily negative), rather than treating an
-unbounded negative as an exception.
+Chosen option: **Option 3, a closed `AccountPolicy` enum per account**. It makes
+the intent of an account explicit, and an audit can read it. It leaves an
+illegal state with no representation. It maps directly onto the two validation
+rules, which are the permission for a negative posting and the floor.
+
+`SystemAccount` and `ExternalAccount` give a deposit and a withdrawal a
+principled home. They are value boundaries that can go negative without limit.
+So an unbounded negative is not an exception here.
 
 ### Positive Consequences
 
-* Validation is a small match on the policy: `validate_and_plan` rejects a
-  negative posting on `NoOverdraft` and enforces the `CappedOverdraft` floor;
-  other policies skip the floor check.
-* Accounts document their own risk posture; an audit can read intent from
-  the type.
+* Validation is a small match on the policy. `validate_and_plan` rejects a
+  negative posting on `NoOverdraft` and enforces the `CappedOverdraft` floor.
+  Another policy skips the floor check.
+* An account documents its own risk posture, and an audit can read the intent
+  from the type.
 
 ### Negative Consequences
 
-* New account kinds require an enum (and validation) change. This is
-  intentional, but not a runtime or config change.
-* Per-asset overdraft, if ever needed, must be modeled on top of this
-  rather than for free.
-* The `CappedOverdraft` floor is only *best-effort* under concurrency, see
+* A new kind of account needs a change to the enum and to the validation. That
+  is deliberate. It is not a change at runtime and not a change to a
+  configuration file.
+* A per-asset overdraft, if anything ever needs one, must sit on top of this
+  model. It does not come free.
+* The `CappedOverdraft` floor is *best-effort* alone under concurrency. See
   [ADR-0003](0003-dumb-storage-saga-recovery.md).
 
 ## Links
 
-* Refines [ADR-0001](0001-modified-utxo-signed-postings.md) (signed postings).
-* Floor-under-concurrency tradeoff: [ADR-0003](0003-dumb-storage-saga-recovery.md).
+* Refines [ADR-0001](0001-modified-utxo-signed-postings.md), which gives the
+  signed postings.
+* The tradeoff for the floor under concurrency:
+  [ADR-0003](0003-dumb-storage-saga-recovery.md).
 * Background: [accounts.md](../accounts.md).

+ 64 - 57
doc/adr/0005-intent-api-movements-vs-envelopes.md

@@ -8,21 +8,22 @@
 
 ## Context and Problem Statement
 
-In a UTXO-style model (ADR-0001) a commit ultimately operates on concrete
-postings: which exact postings to consume, which to create, and the change.
-But making callers assemble that (pick inputs, compute change, balance per
-asset) is error-prone and couples application code to the ledger's internals.
-What should the *public* unit of intent be, and where does the translation to
-concrete postings happen?
+In a UTXO-style model (ADR-0001) a commit works on concrete postings in the end.
+It names the exact postings to consume, the postings to create, and the change.
+
+A caller could assemble that itself: pick the inputs, compute the change and
+balance each asset. That is easy to get wrong, and it couples application code
+to the internals of the ledger. So what is the *public* unit of intent, and
+where does the translation into concrete postings happen?
 
 ## Decision Drivers
 
-* **Ergonomics and safety**: callers should express *what* they want ("pay B
-  40 USD from A"), not hand-select UTXOs.
-* **Keep the UTXO model an implementation detail**: selection and
-  change-making should not leak into application code.
-* **Determinism and idempotency**: the same intent must resolve
-  deterministically, and re-submitting must be a no-op.
+* **Ergonomics and safety**: a caller must express *what* it wants, as in "pay B
+  40 USD from A". It must not select a UTXO by hand.
+* **Keep the UTXO model an implementation detail**: neither the selection nor
+  the change must reach application code.
+* **Determinism and idempotency**: one intent must always resolve the same way,
+  and a second submit of it must do nothing.
 * **Composability**: multi-account, multi-asset events (FX, compound entries)
   must be expressible as one atomic intent.
 
@@ -30,78 +31,84 @@ concrete postings happen?
 
 #### Option 1: Callers build `Envelope`s directly (raw UTXO API)
 
-The public API is the resolved form: callers choose consumed posting ids and
-construct created postings.
+The public API is the resolved form. A caller chooses the consumed posting ids
+and constructs the created postings.
 
 **Pros:**
 
-* Good, because it is maximally explicit and gives full control (useful for FX
-  or hand-tuned flows).
+* Good, because it is as explicit as it can be and gives full control. That
+  helps an FX flow, and a flow tuned by hand.
 
 **Cons:**
 
-* Bad, because every caller re-implements posting selection, change-making, and
-  per-asset balancing, which is easy to get wrong.
+* Bad, because every caller re-implements the posting selection, the change and
+  the per-asset balance. Each of those is easy to get wrong.
 * Bad, because it couples application code to posting ids and the UTXO model.
-* Bad, because there is no natural high-level vocabulary
-  (pay/deposit/withdraw).
+* Bad, because there is no natural high-level vocabulary such as pay, deposit
+  and withdraw.
 
 #### Option 2: A two-layer API: intent (`Movement`/`Transfer`) to resolved (`Envelope`)
 
-Callers express intent as `Movement { from, to, asset, amount }` values grouped
-into a `Transfer` (via `TransferBuilder::pay/deposit/withdraw/movement`). The
-ledger's `resolve()` turns intent into a concrete `Envelope` by selecting
-postings and computing change; the envelope is what gets validated and
-committed. The raw envelope path remains available internally (e.g. for
-`reverse()` and hand-built multi-asset envelopes).
+A caller expresses intent as `Movement { from, to, asset, amount }` values, and
+a `Transfer` groups them. `TransferBuilder::pay/deposit/withdraw/movement`
+builds the group.
+
+The ledger's `resolve()` turns that intent into a concrete `Envelope`. It
+selects the postings and computes the change. The envelope is what the ledger
+validates and commits. The raw envelope path stays available internally, for
+`reverse()` and for a hand-built multi-asset envelope.
 
 **Pros:**
 
-* Good, because the common cases are one call and the UTXO mechanics stay
-  hidden.
-* Good, because intent is small and serializable, and `resolve` is
-  deterministic, so the resolved `Envelope` has a stable content id
-  (idempotency, ADR re: content-addressing).
-* Good, because compound and multi-asset events are just multiple movements
-  committed atomically; deposits and withdrawals are movements against a
-  boundary account.
-* Good, because the escape hatch (build an `Envelope` directly) still exists
-  for flows the intent vocabulary cannot express.
+* Good, because the common case is one call, and the UTXO mechanics stay hidden.
+* Good, because the intent is small and serializable, and `resolve` is
+  deterministic. So the resolved `Envelope` has a stable content id, which gives
+  idempotency. See the record on the content address.
+* Good, because a compound event and a multi-asset event are only several
+  movements that commit atomically. A deposit and a withdrawal are movements
+  against a boundary account.
+* Good, because the escape route still exists for a flow that the intent
+  vocabulary cannot express. Build an `Envelope` directly.
 
 **Cons:**
 
-* Bad, because there are two representations to understand
-  (intent vs. resolved) and the word "posting" is a noun here, not the
-  accounting verb.
-* Bad, because idempotency keys on the *resolved* envelope id, so resolution
-  must be deterministic for re-submits to dedupe, a property the resolver must
-  hold.
+* Bad, because a reader must understand two representations, the intent and the
+  resolved form. The word "posting" is also a noun here and not the accounting
+  verb.
+* Bad, because idempotency keys on the id of the *resolved* envelope. Resolution
+  must therefore be deterministic, or a second submit does not dedupe. The
+  resolver must hold that property.
 
 ## Decision Outcome
 
-Chosen option: **Option 2, the two-layer intent API**, because it keeps the
-UTXO model an internal detail, makes the common operations trivial and safe,
-and yields a deterministic resolved `Envelope` whose content id gives
-idempotency, while still allowing a pre-built envelope for advanced flows.
+Chosen option: **Option 2, the two-layer intent API**. It keeps the UTXO model
+an internal detail. It makes the common operations trivial and safe. It yields a
+deterministic resolved `Envelope`, whose content id gives idempotency.
+
+It also still accepts an envelope that a caller built in advance, for a flow
+that needs one.
 
 ### Positive Consequences
 
-* `TransferBuilder` offers `pay`/`deposit`/`withdraw` (preferred) over raw
-  `movement` construction; one `Transfer` can carry many movements committed
+* `TransferBuilder` offers `pay`, `deposit` and `withdraw`, which are preferred
+  over a raw `movement`. One `Transfer` can carry many movements that commit
   atomically.
-* `commit(transfer)` = `resolve` (read-only) then `commit_envelope`; the saga
-  and recovery operate on the resolved envelope (see ADR-0002/0003).
-* Deposits resolve to two movements that cancel to zero net debit on the system
-  account, so no posting selection is needed.
+* `commit(transfer)` is a read-only `resolve` and then `commit_envelope`. The
+  saga and the recovery both work on the resolved envelope (see ADR-0002 and
+  ADR-0003).
+* A deposit resolves to two movements that cancel to a net debit of zero on the
+  system account. So it needs no posting selection.
 
 ### Negative Consequences
 
-* Two representations to document; the noun/verb "posting" caveat
-  (see [accounting-mapping.md](../accounting-mapping.md)).
-* Resolution must stay deterministic so re-submitting the same intent dedupes.
+* There are two representations to document, and the caveat on "posting" as a
+  noun and as a verb. See [accounting-mapping.md](../accounting-mapping.md).
+* Resolution must stay deterministic, so that a second submit of one intent
+  dedupes.
 
 ## Links
 
-* Builds on [ADR-0001](0001-modified-utxo-signed-postings.md); committed by
+* Builds on [ADR-0001](0001-modified-utxo-signed-postings.md). Committed by
   [ADR-0002](0002-saga-commit-pipeline.md).
-* Background: [transfers.md](../transfers.md), [accounting-mapping.md](../accounting-mapping.md).
+* Background: [transfers.md](../transfers.md),
+  [accounting-mapping.md](../accounting-mapping.md).

+ 72 - 62
doc/adr/0006-reservation-protocol-posting-lifecycle.md

@@ -9,31 +9,34 @@
 
 ## Context and Problem Statement
 
-A commit must consume input postings exactly once, even when many commits run
-concurrently and the commit itself is a multi-step saga (ADR-0002) over a dumb
-store (ADR-0003) with no global transaction. Two sagas must never both spend
-the same posting, and a posting reserved by one saga must not be finalized or
-released by another. How is exclusive, recoverable ownership of inputs achieved
-without locking account balances?
+A commit must consume each input posting exactly once. That holds while many
+commits run at the same time. It also holds because the commit itself is a
+multi-step saga (ADR-0002) over a simple store (ADR-0003), with no global
+transaction.
+
+Two sagas must never both spend one posting. A posting that one saga reserved
+must not be finalized or released by another. So how does a commit get
+exclusive, recoverable ownership of its inputs without a lock on an account
+balance?
 
 ## Decision Drivers
 
 * **Double-spend safety:** a posting can be consumed at most once,
   unconditionally.
-* **No hot-row locking:** preserve the UTXO concurrency of ADR-0001; do not
+* **No lock on a hot row:** keep the UTXO concurrency of ADR-0001, and do not
   serialize on an account balance.
-* **Survives the saga's lifetime:** a reservation must hold across reserve →
-  validate → finalize and across a crash + recovery.
-* **Ownership:** only the saga that reserved a posting may finalize or release
-  it.
-* **Fits dumb storage:** expressible as single atomic conditional updates that
-  return affected-row counts (ADR-0003).
+* **It survives the saga's lifetime:** a reservation must hold across
+  `reserve → validate → finalize`, and across a crash and the recovery after it.
+* **Ownership:** only the saga that reserved a posting can finalize it or
+  release it.
+* **It fits simple storage:** one atomic conditional update expresses it, and
+  that update returns an affected-row count (ADR-0003).
 
 ## Considered Options
 
 #### Option 1: Database row locks (`SELECT … FOR UPDATE`) per posting
 
-Lock the posting rows for the duration of the commit.
+Lock the posting rows for as long as the commit runs.
 
 **Pros:**
 
@@ -42,11 +45,12 @@ Lock the posting rows for the duration of the commit.
 
 **Cons:**
 
-* Bad, because it requires a transaction spanning the whole commit, which the
-  saga model deliberately avoids (ADR-0002/0003).
-* Bad, because held locks block other workers and do not survive a crash
-  (the lock is gone, but no record says the posting was claimed).
-* Bad, because it ties the design to a locking, transactional store.
+* Bad, because it needs a transaction that covers the whole commit, and the saga
+  model avoids that deliberately (ADR-0002 and ADR-0003).
+* Bad, because a held lock blocks another worker, and it does not survive a
+  crash. The lock then goes, and no record says that something claimed the
+  posting.
+* Bad, because it ties the design to a transactional store that takes a lock.
 
 #### Option 2: Optimistic balance CAS per account
 
@@ -58,69 +62,75 @@ Guard each commit with a compare-and-set on the account balance.
 
 **Cons:**
 
-* Bad, because it serializes on a per-account balance (the hot row ADR-0001 set
-  out to avoid) and conflates "did this posting get spent" with "did the
-  balance change."
-* Bad, because it does not, by itself, record exclusive ownership of specific
-  inputs for recovery.
+* Bad, because it serializes on a balance per account, which is the hot row that
+  ADR-0001 set out to avoid. It also mixes two questions: did something spend
+  this posting, and did the balance change.
+* Bad, because on its own it records no exclusive ownership of specific inputs
+  for a recovery to read.
 
 #### Option 3: A three-state posting lifecycle with a reservation token
 
-A posting is `Active → PendingInactive → Inactive`.
-`reserve_postings(ids, rid)` flips `Active → PendingInactive` and stamps each
-with a `ReservationId`, as a single atomic conditional update
-(`… WHERE status = Active`). `release_postings` reverts
-`PendingInactive → Active` for the owning `rid`; finalize flips
-`PendingInactive (owned by rid) → Inactive`. The reservation id is durable
-(persisted with the write-ahead record, ADR-0003), and every later mutation is
-conditioned on ownership.
+A posting moves `Active → PendingInactive → Inactive`.
+`reserve_postings(ids, rid)` moves it `Active → PendingInactive` and stamps each
+one with a `ReservationId`. That is one atomic conditional update, with
+`… WHERE status = Active`.
+
+`release_postings` moves a posting `PendingInactive → Active` for the `rid` that
+owns it. A finalize moves it `PendingInactive (owned by rid) → Inactive`. The
+reservation id is durable, because the write-ahead record persists it
+(ADR-0003). Every later mutation takes ownership as its condition.
 
 **Pros:**
 
-* Good, because reservation is a single atomic conditional update. Two sagas
-  cannot both move the same `Active` posting to `PendingInactive`; the loser
-  sees zero rows affected. Double-spend safety is unconditional and lock-free.
-* Good, because the `PendingInactive` state plus `ReservationId` is durable
-  ownership that survives the multi-step saga and a crash, enabling recovery to
-  tell "reserved by us" from "taken by someone else."
-* Good, because it expresses cleanly over dumb storage (counts, not locks) and
-  keeps balances out of the critical section.
-* Good, because compensation is natural: release reverts the reservation.
+* Good, because a reservation is one atomic conditional update. Two sagas cannot
+  both move one `Active` posting to `PendingInactive`. The second one sees zero
+  affected rows. Double-spend safety is then unconditional, and it needs no
+  lock.
+* Good, because the `PendingInactive` state plus the `ReservationId` is durable
+  ownership. It survives the multi-step saga and a crash, so a recovery can tell
+  a posting this saga reserved from a posting that another one took.
+* Good, because it expresses cleanly over simple storage, through a count rather
+  than a lock. It also keeps a balance out of the critical section.
+* Good, because compensation is natural. A release reverts the reservation.
 
 **Cons:**
 
-* Bad, because a posting carries lifecycle state and an optional reservation
-  column (more than an immutable UTXO).
-* Bad, because a reservation orphaned by a crash must be resolved by recovery
-  (roll-forward) rather than by a lock simply being dropped. ADR-0003 handles
-  this.
+* Bad, because a posting carries a lifecycle state and an optional reservation
+  column. That is more than an immutable UTXO holds.
+* Bad, because a crash can orphan a reservation, and then a recovery must
+  resolve it by a roll-forward. A dropped lock would have resolved itself.
+  ADR-0003 handles this.
 
 ## Decision Outcome
 
-Chosen option: **Option 3: the three-state posting lifecycle with a durable
-`ReservationId`**, because it is the only option that gives unconditional,
-lock-free double-spend safety and durable, recoverable ownership across a
-multi-step saga, while expressing as the atomic, count-returning instructions
-the dumb store provides.
+Chosen option: **Option 3, the three-state posting lifecycle with a durable
+`ReservationId`**. It is the only option that gives unconditional double-spend
+safety with no lock, and durable ownership that a recovery can read across a
+multi-step saga.
+
+It also expresses itself as the atomic instructions that the simple store
+offers, and each of those returns a count.
 
 ### Positive Consequences
 
-* `reserve_postings` is the concurrency gate; the saga reads its affected-row
-  count to know it won the reservation (ADR-0003's count interpretation).
-* Recovery distinguishes "reserved by this saga" / "already finalized by us"
-  from "taken by another transfer," which is what makes phase-tracked
-  roll-forward safe (ADR-0003).
-* Balances never enter the critical section. UTXO concurrency is preserved.
+* `reserve_postings` is the concurrency gate. The saga reads its affected-row
+  count to learn that it took the reservation. See how ADR-0003 reads a count.
+* A recovery tells three cases apart: this saga reserved the posting, this saga
+  already finalized it, or another transfer took it. That is what makes a
+  roll-forward with tracked phases safe (ADR-0003).
+* A balance never enters the critical section, so the UTXO concurrency survives.
 
 ### Negative Consequences
 
-* Postings are not pure immutable UTXOs; they carry `status` + `reservation`.
-* Crash-orphaned reservations are resolved by recovery, not by lock release.
+* A posting is not a pure immutable UTXO. It carries a `status` and a
+  `reservation`.
+* A recovery resolves a reservation that a crash orphaned. No lock release does
+  it.
 
 ## Links
 
-* The primitive behind [ADR-0002](0002-saga-commit-pipeline.md) and the
+* The primitive behind [ADR-0002](0002-saga-commit-pipeline.md), and behind the
   recovery in [ADR-0003](0003-dumb-storage-saga-recovery.md).
 * Builds on [ADR-0001](0001-modified-utxo-signed-postings.md).
-* Background: [architecture.md](../architecture.md) ("Posting Lifecycle"),
-  [glossary.md](../glossary.md) ("Reservation protocol").
+* Background: [architecture.md](../architecture.md), under "Posting Lifecycle",
+  and [glossary.md](../glossary.md), under "Reservation protocol".

+ 61 - 54
doc/adr/0007-reversal-via-compensating-transfers.md

@@ -8,42 +8,44 @@
 
 ## Context and Problem Statement
 
-Sometimes a committed transfer must be undone: a mistaken payment, a saga
-compensating a later failure. The ledger's whole value proposition is being
-auditable by replaying an append-only log (ADR-0001). How do we undo a
-transfer without breaking that property?
+Something must sometimes undo a committed transfer. A mistaken payment is one
+case, and a saga that compensates for a later failure is another.
+
+The whole value of the ledger is that a replay of an append-only log audits it
+(ADR-0001). So how do we undo a transfer and keep that property?
 
 ## Decision Drivers
 
-* **Audit integrity**: history must never be rewritten; "what happened"
-  includes the mistake and its correction.
-* **Consistency with the model**: an undo should use the same machinery as a
-  normal commit, not a special back door.
-* **Idempotency**: undoing twice (e.g. a retried compensation) must not
-  double-undo.
+* **Audit integrity**: nothing must ever rewrite the history. "What happened"
+  covers the mistake and its correction.
+* **Consistency with the model**: an undo must use the same machinery as a
+  normal commit, and not a special back door.
+* **Idempotency**: two undos must not undo twice, and a compensation that
+  something retries is one such case.
 * **Composability**: saga compensation needs a reliable, reusable undo.
 
 ## Considered Options
 
 #### Option 1: Delete or mutate the original postings/record
 
-Physically remove the created postings (and restore consumed ones), or edit the
-transfer record to "undo" it.
+Remove the created postings physically, and restore the consumed ones. Or edit
+the transfer record to undo it.
 
 **Pros:**
 
-* Good, because the post-undo state is "clean", as if it never happened.
+* Good, because the state after the undo is clean, as if the transfer never
+  happened.
 
 **Cons:**
 
-* Bad, because it destroys history: the ledger is no longer reconstructible by
-  replay, defeating ADR-0001.
-* Bad, because it is a privileged mutation path outside the normal commit
-  model, with its own concurrency and crash hazards.
+* Bad, because it destroys the history. A replay can no longer reconstruct the
+  ledger, which defeats ADR-0001.
+* Bad, because it is a privileged mutation path outside the normal commit model.
+  It carries its own concurrency hazard and its own crash hazard.
 
 #### Option 2: A `void`/`reversed` flag on the transfer
 
-Mark the original as voided rather than deleting it.
+Mark the original as voided rather than a delete of it.
 
 **Pros:**
 
@@ -51,61 +53,66 @@ Mark the original as voided rather than deleting it.
 
 **Cons:**
 
-* Bad, because balances now depend on interpreting flags, not just summing
-  postings: the projection is no longer "sum of `Active` postings."
-* Bad, because it adds mutable state to an otherwise append-only record and a
-  second code path for "is this transfer effective?"
+* Bad, because a balance then depends on how something reads a flag, and not on
+  a sum of postings alone. The projection is no longer the sum of the `Active`
+  postings.
+* Bad, because it adds mutable state to a record that is otherwise append-only.
+  It also adds a second code path, to answer whether a transfer is in effect.
 
 #### Option 3: A compensating transfer (an inverse envelope)
 
-`reverse(id)` loads the original transfer and builds an inverse envelope: it
-consumes the original's created postings and recreates the original's consumed
-ones as new postings, then commits it through the normal `commit_envelope`
-path. Nothing is deleted or mutated; the reversal is itself a content-addressed
-transfer.
+`reverse(id)` loads the original transfer and builds an inverse envelope. That
+envelope consumes the postings the original created. It recreates the postings
+the original consumed, as new postings. It then commits through the normal
+`commit_envelope` path.
+
+Nothing is deleted and nothing is mutated. The reversal is itself a
+content-addressed transfer.
 
 **Pros:**
 
-* Good, because history is fully preserved: both the original and its reversal
-  appear in the log; balances remain "sum of `Active` postings."
-* Good, because it reuses the exact commit path (reserve → validate →
-  finalize, recovery, idempotency) with no special undo machinery.
-* Good, because it is idempotent: the reversal envelope is deterministic and
-  content-addressed, so committing it twice returns the same receipt.
-* Good, because it gives saga compensation a reliable, uniform primitive.
+* Good, because the history survives in full. Both the original and its reversal
+  appear in the log, and a balance stays the sum of the `Active` postings.
+* Good, because it reuses the exact commit path, which is
+  `reserve → validate → finalize` with its recovery and its idempotency. It
+  needs no special undo machinery.
+* Good, because it is idempotent. The reversal envelope is deterministic and
+  content-addressed, so a second commit of it returns the same receipt.
+* Good, because it gives saga compensation one reliable primitive.
 
 **Cons:**
 
-* Bad, because the post-undo state is not "as if it never happened": there are
-  now two transfers (intended), which a naive reader might find noisy.
-* Bad, because reversing is a real commit and is subject to the same validation
-  (e.g. it cannot reverse postings already consumed by a later transfer without
-  that surfacing as a normal failure).
+* Bad, because the state after the undo is not as if the transfer never
+  happened. There are two transfers now, which is the intent, and a reader who
+  does not expect that finds it noisy.
+* Bad, because a reversal is a real commit, so the same validation applies to
+  it. It cannot reverse a posting that a later transfer already consumed, and
+  the ledger reports that as a normal failure.
 
 ## Decision Outcome
 
-Chosen option: **Option 3: reversal as a compensating transfer**, because it
-is the only option that preserves the append-only, replayable audit log
-(ADR-0001) while reusing the normal, already-hardened commit and recovery
-path, and is idempotent by content-addressing.
+Chosen option: **Option 3, a reversal as a compensating transfer**. It is the
+only option that keeps the append-only audit log that a replay can read
+(ADR-0001). It reuses the normal commit and recovery path, which is already
+hardened. The content address makes it idempotent.
 
 ### Positive Consequences
 
-* `reverse()` is a thin wrapper over `commit_envelope`; saga finalize
-  compensation uses it to undo a committed step.
-* The audit trail shows the original and the correction; balances stay a pure
-  projection over `Active` postings.
+* `reverse()` is a thin wrapper over `commit_envelope`. The compensation in a
+  saga finalize uses it to undo a committed step.
+* The audit trail shows the original and the correction. A balance stays a pure
+  projection over the `Active` postings.
 
 ### Negative Consequences
 
-* Undo is visible as a second transfer (by design), not an erasure.
-* A reversal is subject to normal validation/availability: it can legitimately
-  fail if the world moved on, surfacing as an ordinary error.
+* An undo is visible as a second transfer, by design, and not as an erasure.
+* Normal validation applies to a reversal, and so does normal availability. It
+  can legitimately fail when the world moved on, and that surfaces as an
+  ordinary error.
 
 ## Links
 
-* Preserves the audit model of
-  [ADR-0001](0001-modified-utxo-signed-postings.md); reuses
-  [ADR-0002](0002-saga-commit-pipeline.md) /
+* Keeps the audit model of [ADR-0001](0001-modified-utxo-signed-postings.md).
+  Reuses [ADR-0002](0002-saga-commit-pipeline.md) and
   [ADR-0003](0003-dumb-storage-saga-recovery.md).
-* Background: [transfers.md](../transfers.md) ("Reversal").
+* Background: [transfers.md](../transfers.md), under "Reversal".

+ 60 - 61
doc/adr/0008-conformance-tested-storage.md

@@ -8,25 +8,25 @@
 
 ## Context and Problem Statement
 
-`Store` is a trait with several sub-traits and multiple backends (an
-in-memory store and a SQL store over SQLite/PostgreSQL), and, since
-ADR-0003, the saga's correctness depends on every backend behaving
-*identically*, down to the affected-row counts each primitive returns.
-How do we guarantee that two independent `Store` implementations have
-exactly the same observable semantics, and keep them in lock-step as the
-trait evolves?
+`Store` is a trait with several sub-traits and more than one backend. There is
+an in-memory store, and a SQL store over SQLite and PostgreSQL. Since ADR-0003,
+the correctness of the saga depends on *identical* behaviour from every backend,
+down to the affected-row count that each primitive returns.
+
+So how do we guarantee that two independent `Store` implementations have exactly
+the same observable semantics? And how do we keep them in step as the trait
+changes?
 
 ## Decision Drivers
 
-* **Semantic equivalence**: InMemory and SQL must return the same counts
-  and state transitions, or the saga's count interpretation (ADR-0003)
-  breaks on one backend.
-* **One source of truth for behavior**: the contract should be
-  executable, not just prose.
-* **Cheap to extend**: adding a backend, or a sub-trait method, should
-  make the obligations obvious.
-* **Fast feedback**: most semantics should be testable without a
-  database.
+* **Semantic equivalence**: the in-memory store and the SQL store must return
+  the same counts and the same state transitions. Otherwise the way the saga
+  reads a count (ADR-0003) breaks on one backend.
+* **One source of truth for behaviour**: the contract must be executable and not
+  prose alone.
+* **Cheap to extend**: a new backend, or a new sub-trait method, must make the
+  obligations obvious.
+* **Fast feedback**: a test must reach most of the semantics with no database.
 
 ## Considered Options
 
@@ -40,14 +40,14 @@ Each `Store` impl has its own hand-written test suite.
 
 **Cons:**
 
-* Bad, because the two suites drift: a behavior tested for one backend
-  may be untested (and divergent) for the other.
-* Bad, because there is no single, enforceable definition of "correct
-  `Store` behavior."
+* Bad, because the two suites drift. A behaviour that one backend tests can go
+  untested on the other, and the two can then diverge.
+* Bad, because there is no single definition of correct `Store` behaviour that
+  anything can enforce.
 
 #### Option 2: Trait documentation only (plus mocks)
 
-Specify semantics in doc comments; let callers mock the store.
+State the semantics in doc comments, and let a caller mock the store.
 
 **Pros:**
 
@@ -55,65 +55,64 @@ Specify semantics in doc comments; let callers mock the store.
 
 **Cons:**
 
-* Bad, because prose is not executable, so nothing prevents a backend
-  from violating it.
-* Bad, because mocks encode an *assumed* contract, which can itself be
-  wrong.
+* Bad, because prose is not executable, so nothing stops a backend from a breach
+  of it.
+* Bad, because a mock encodes an *assumed* contract, and that assumption can
+  itself be wrong.
 
 #### Option 3: A shared conformance suite + an in-memory reference
 
-A `store_tests!` macro generates one suite of `async` tests; every
-backend (`InMemoryStore`, `SqlStore`) runs the same suite via its own
-factory. `InMemoryStore` doubles as the **executable reference** for the
-intended semantics. The convention is that every `Store` sub-trait
-method has a conformance test, so new methods force new tests.
+A `store_tests!` macro generates one suite of `async` tests; every backend
+(`InMemoryStore`, `SqlStore`) runs the same suite via its own factory.
+`InMemoryStore` doubles as the **executable reference** for the intended
+semantics. The convention is that every `Store` sub-trait method has a
+conformance test, so new methods force new tests.
 
 **Pros:**
 
-* Good, because both backends are held to the identical, executable
-  contract, including the affected-row counts ADR-0003 relies on.
-* Good, because `InMemoryStore` is a fast, dependency-free reference for
-  the semantics and a ready test double for higher layers.
-* Good, because adding a backend is "run the macro with your factory,"
-  and adding a sub-trait method is incomplete until its conformance test
-  exists.
+* Good, because the suite holds both backends to one identical, executable
+  contract. That contract covers the affected-row counts that ADR-0003 depends
+  on.
+* Good, because `InMemoryStore` is a fast, dependency-free reference for the
+  semantics and a ready test double for higher layers.
+* Good, because a new backend is "run the macro with your factory," and a new
+  sub-trait method is incomplete until its conformance test exists.
 
 **Cons:**
 
-* Bad, because the macro suite must stay backend-agnostic (no
-  backend-specific assertions), so a few backend-specific behaviors
-  still need separate tests.
-* Bad, because the in-memory reference must be maintained to match the
-  SQL backend exactly, a second implementation to keep honest (which is
-  also the point).
+* Bad, because the macro suite must stay backend-agnostic (no backend-specific
+  assertions), so a few backend-specific behaviors still need separate tests.
+* Bad, because someone must keep the in-memory reference an exact match for the
+  SQL backend. It is a second implementation to keep honest, which is also the
+  point of it.
 
 ## Decision Outcome
 
-Chosen option: **Option 3, a shared `store_tests!` conformance suite
-with `InMemoryStore` as the executable reference**, because it is the
-only option that *enforces* semantic equivalence across backends (a hard
-requirement once the saga interprets counts, ADR-0003), gives a fast
-dependency-free reference/double, and makes the obligations for new
-backends and new methods explicit.
+Chosen option: **Option 3, a shared `store_tests!` conformance suite with
+`InMemoryStore` as the executable reference**. It is the only option that
+*enforces* semantic equivalence across the backends. That became a hard
+requirement once the saga began to read a count (ADR-0003).
+
+It also gives a fast reference and test double, with no dependency. And it makes
+the obligations explicit, both for a new backend and for a new method.
 
 ### Positive Consequences
 
-* Both `InMemoryStore` and the SQL backend pass the same suite; a
-  divergence in counts or transitions fails the build.
-* New `Store` sub-trait methods come with conformance tests by
-  convention.
+* Both `InMemoryStore` and the SQL backend pass the same suite; a divergence in
+  counts or transitions fails the build.
+* New `Store` sub-trait methods come with conformance tests by convention.
 * Higher layers (ledger, saga) test against the fast in-memory store.
 
 ### Negative Consequences
 
-* The conformance suite must remain backend-neutral; genuinely
-  backend-specific behavior needs its own tests.
-* The in-memory reference is a second implementation that must track the
-  SQL one.
+* The conformance suite must remain backend-neutral; genuinely backend-specific
+  behavior needs its own tests.
+* The in-memory reference is a second implementation that must track the SQL
+  one.
 
 ## Links
 
-* Underpins [ADR-0003](0003-dumb-storage-saga-recovery.md) (equivalent
-  count semantics across backends).
-* Background: `crates/kuatia-storage/src/store_tests.rs` and the backend
-  test harnesses.
+* Underpins [ADR-0003](0003-dumb-storage-saga-recovery.md) (equivalent count
+  semantics across backends).
+* Background: `crates/kuatia-storage/src/store_tests.rs` and the backend test
+  harnesses.

+ 117 - 97
doc/adr/0009-monetary-representation-integer-minor-units.md

@@ -8,148 +8,168 @@
 
 ## Context and Problem Statement
 
-Every posting carries an amount of one asset (ADR-0001), and the core invariant
-is per-asset conservation: `sum(consumed) == sum(created)` checked on every
-commit. That sum must be exact. A ledger that rounds is not a ledger. So the
-monetary type has to be exact under addition, subtraction and negation, deny
-silent overflow, hash deterministically for content-addressing, and still
-represent assets with different decimal precision (USD has 2, a token might
-have 8, JPY has 0). What type represents a stored monetary amount, and where
-does an asset's decimal scale live?
+Every posting carries an amount of one asset (ADR-0001). The core invariant is
+per-asset conservation, `sum(consumed) == sum(created)`, and every commit checks
+it. That sum must be exact. A ledger that rounds is not a ledger.
+
+So the monetary type must do four things. It must be exact under addition,
+subtraction and negation. It must refuse a silent overflow. It must hash
+deterministically, for the content address. And it must still represent assets
+at different decimal precisions: USD has 2, a token has 8, and JPY has 0.
+
+So what type represents a stored monetary amount? And where does the decimal
+scale of an asset live?
 
 ## Decision Drivers
 
-* **Exactness**: addition/subtraction/negation must be exact; conservation and
-  floor checks cannot tolerate rounding error.
-* **No silent overflow**: an amount that overflows must surface as an error,
-  not wrap, since wrapping would forge or destroy value.
-* **Deterministic bytes**: amounts are hashed into the content-addressed
-  `EnvelopeId`, so the representation must serialize identically everywhere
-  (no locale, no float bit-pattern ambiguity).
-* **Multi-asset precision**: different assets have different decimal places,
-  but the stored value should stay one uniform type.
-* **No DB arithmetic**: all sums happen in Rust with checked operations; the
-  store never computes on amounts (CLAUDE.md, ADR-0003).
+* **Exactness**: addition, subtraction and negation must each be exact. The
+  conservation check and the floor check tolerate no error from rounding.
+* **No silent overflow**: an amount that overflows must come back as an error
+  and must not wrap. A wrap would forge value or destroy it.
+* **Deterministic bytes**: the content-addressed `EnvelopeId` hashes the
+  amounts. So the representation must serialize identically everywhere, with no
+  locale and no ambiguity in a float bit pattern.
+* **Multi-asset precision**: two assets have two different decimal places, and
+  the stored value must stay one uniform type.
+* **No arithmetic in the database**: every sum happens in Rust, with a checked
+  operation. The store never computes on an amount (CLAUDE.md, ADR-0003).
 
 ## Considered Options
 
 #### Option 1: Floating point (`f64`)
 
-Store amounts as binary floating point.
+Store an amount as a binary floating-point number.
 
 **Pros:**
 
-* Good, because it is built-in and handles fractional values without scaling.
+* Good, because the language has it already, and it holds a fractional value
+  with no scale.
 
 **Cons:**
 
-* Bad, because `f64` cannot represent most decimal fractions exactly
-  (`0.1 + 0.2`), so conservation sums drift and the `Σ consumed == Σ created`
-  check becomes approximate, which disqualifies it for a ledger.
-* Bad, because float bit-patterns and rounding modes make hashing and
-  cross-platform determinism fragile.
+* Bad, because `f64` cannot hold most decimal fractions exactly, as `0.1 + 0.2`
+  shows. So a conservation sum drifts, and the `Σ consumed == Σ created` check
+  becomes approximate. That rules it out for a ledger.
+* Bad, because a float bit pattern and a rounding mode together make the hash
+  fragile, and make the result differ between platforms.
 
 #### Option 2: A decimal / big-integer library (`rust_decimal`, `i128`, rationals)
 
-Use a wider or decimal-aware numeric type that carries its own scale.
+Use a wider numeric type, or one that knows about decimals, and let it carry its
+own scale.
 
 **Pros:**
 
-* Good, because it offers larger range (`i128`) or scale-aware decimal math,
-  and can embed precision in the value itself.
+* Good, because it offers a larger range through `i128`, or decimal arithmetic
+  that knows the scale. It can also hold the precision inside the value.
 
 **Cons:**
 
-* Bad, because it pulls a non-trivial dependency (or wider columns) into the
-  most pervasive type, complicating storage layout and serialization for a
-  need the domain does not yet have.
-* Bad, because a value that carries its own scale invites mixing scales
-  silently and still must be pinned down for deterministic hashing.
-* Bad, because `i64` minor units already cover ~±9.2×10¹⁸ of the smallest
-  unit, ample for realistic balances, so the extra range is mostly unused
-  weight.
+* Bad, because it pulls a large dependency, or a wider column, into the type
+  that appears most often. That complicates both the storage layout and the
+  serialization, for a need the domain does not have yet.
+* Bad, because a value that carries its own scale invites a quiet mix of two
+  scales. Something must still pin the scale down, for a deterministic hash.
+* Bad, because `i64` minor units already cover about ±9.2×10¹⁸ of the smallest
+  unit. That is ample for a realistic balance, so the extra range is weight that
+  almost nothing uses.
 
 #### Option 3: `Cent`, an `i64` newtype of minor units, scale held outside
 
-`Cent(i64)` is a private-field newtype holding an amount in the asset's
-**smallest unit** (cents, satoshis, …). It exposes only checked arithmetic
-(`checked_add`/`checked_sub`/`checked_neg`/`checked_sum` → `OverflowError`),
-serializes as big-endian bytes (`ToBytes`) for hashing, and is `Ord`/`Hash`.
-Decimal **scale is not stored on the value or the asset**: `AssetId(u32)` is an
-opaque identifier, and `Amount { decimals: u8 }` is a presentation-only
-parser/formatter (string ⇄ `Cent`) that is *never persisted*.
+`Cent(i64)` is a newtype with a private field. It holds an amount in the asset's
+**smallest unit**, such as a cent or a satoshi.
+
+It offers checked arithmetic alone, which is `checked_add`, `checked_sub`,
+`checked_neg` and `checked_sum`, and each returns an `OverflowError` on
+overflow. It serializes as big-endian bytes through `ToBytes`, for the hash. It
+is `Ord` and `Hash`.
+
+Neither the value nor the asset **stores the decimal scale**. `AssetId(u32)` is
+an opaque identifier. `Amount { decimals: u8 }` parses and formats for
+presentation alone, between a string and a `Cent`, and nothing *ever* persists
+it.
 
 **Pros:**
 
-* Good, because integer minor units are exact under +, −, negation, so
-  conservation and the overdraft floor are checked on exact integers.
-* Good, because the private field forbids confusing a monetary amount with a
-  plain `i64`, and the only arithmetic offered is checked, so overflow is a
-  `Result`, never a wrap.
-* Good, because big-endian bytes give one deterministic, locale-free
-  representation for content-addressing across backends and platforms.
-* Good, because keeping scale out of the stored value means the persisted
-  ledger is pure integers, with no per-row precision field to migrate, and
-  presentation concerns never touch the conservation math.
-* Good, because `i64` minor units are compact (fixed 8 bytes) and index/sum
-  cheaply in Rust.
+* Good, because integer minor units are exact under addition, subtraction and
+  negation. So the conservation check and the overdraft floor both run on exact
+  integers.
+* Good, because the private field keeps a monetary amount and a plain `i64`
+  apart, so nothing can mistake one for the other. The only arithmetic on offer
+  is checked, so an overflow is a `Result` and never a wrap.
+* Good, because big-endian bytes give one deterministic representation with no
+  locale. The content address then holds across every backend and every
+  platform.
+* Good, because the scale stays out of the stored value. The persisted ledger is
+  then pure integers, with no precision field per row for a migration to move. A
+  presentation concern then never touches the conservation arithmetic.
+* Good, because `i64` minor units are compact, at a fixed 8 bytes. Rust indexes
+  them cheaply and sums them cheaply.
 
 **Cons:**
 
-* Bad, because scale is a convention the *application* must apply
-  consistently. A `Cent` is meaningless without knowing its asset's decimals,
-  and nothing in the type stops formatting a satoshi amount with 2 decimals.
-* Bad, because `i64` caps a single amount/sum at ~±9.2×10¹⁸ minor units; an
-  asset with very high precision and very large supply could in principle
-  exceed it (surfaced as `OverflowError`, not a wrap, but a hard ceiling
-  nonetheless).
-* Bad, because fractional or proportional operations (interest, fees, FX rates)
-  are not closed over `Cent` and must be defined explicitly with an agreed
-  rounding policy when they are introduced.
+* Bad, because the scale is a convention, and the *application* must apply it
+  consistently. A `Cent` means nothing unless a reader knows the decimals of its
+  asset. Nothing in the type stops a format of a satoshi amount at 2 decimals.
+* Bad, because `i64` caps one amount, and one sum, at about ±9.2×10¹⁸ minor
+  units. An asset with very high precision and a very large supply can in
+  principle pass that. The result is an `OverflowError` and not a wrap, and the
+  cap is still hard.
+* Bad, because a fractional or proportional operation is not closed over `Cent`,
+  and interest, a fee and an FX rate are all such operations. Each one needs an
+  explicit definition, with an agreed rounding policy, on the day something adds
+  it.
 
 ## Decision Outcome
 
-Chosen option: **Option 3, `Cent`, an `i64` newtype of minor units with scale
-held outside the value**, because it is the only option that makes the
-conservation sum *exact* and *deterministic* while keeping the stored ledger
-pure integers and overflow an explicit error. Scale lives in `Amount`
-(presentation) rather than on `Cent` or `AssetId` (storage), so precision is an
-edge concern at the application boundary and never leaks into the invariant
-math or the database schema. `i64` is chosen over `i128`/decimal because its
-range is more than adequate and its fixed width keeps the most pervasive type
-small and trivially serializable; widening later is a contained newtype change
-if a real asset ever needs it.
+Chosen option: **Option 3, `Cent`, an `i64` newtype of minor units, with the
+scale held outside the value**. It is the only option that makes the
+conservation sum *exact* and *deterministic*. It also keeps the stored ledger
+pure integers, and keeps an overflow an explicit error.
+
+The scale lives in `Amount`, which is presentation, rather than on `Cent` or
+`AssetId`, which are storage. So precision stays at the edge, on the boundary of
+the application. It never reaches the arithmetic of the invariant, and it never
+reaches the database schema.
+
+`i64` wins over `i128` and over a decimal type. Its range is more than adequate.
+Its fixed width keeps the most common type small and simple to serialize. A
+later move to a wider type is a contained change to the newtype, if a real asset
+ever needs one.
 
 ### Positive Consequences
 
-* All monetary arithmetic is checked and exact; `validate_and_plan`'s
-  conservation and floor checks operate on integers that cannot silently round
-  or wrap.
-* `Cent`'s big-endian `ToBytes` feeds the content-addressed `EnvelopeId`
-  deterministically; the same transfer hashes identically on every backend.
-* The persisted amount is a plain `BIGINT`/`i64` with no precision metadata,
-  consistent with "no DB arithmetic" and with Rust-owned identity (ADR-0003).
-* `Amount` cleanly separates human input/output (with per-asset decimals)
-  from the stored, scale-free value.
+* Every piece of monetary arithmetic is checked and exact. The conservation
+  check and the floor check in `validate_and_plan` both work on integers, and
+  those integers can neither round quietly nor wrap.
+* The big-endian `ToBytes` of a `Cent` feeds the content-addressed `EnvelopeId`
+  deterministically. One transfer then hashes identically on every backend.
+* The persisted amount is a plain `BIGINT`, an `i64`, with no metadata for its
+  precision. That agrees with the rule against arithmetic in the database, and
+  with an identity that Rust owns (ADR-0003).
+* `Amount` keeps two things apart. One is the input and output a person reads,
+  with the decimals of each asset. The other is the stored value, which has no
+  scale.
 
 ### Negative Consequences
 
-* Asset scale is an application-level convention; the type system does not
-  bind a `Cent` to its asset's decimal places, so callers must format/parse
-  with the right `Amount` for the asset.
-* `i64` is a hard magnitude ceiling per amount and per sum (overflow →
-  `Result`, never a wrap); a future high-precision/high-supply asset may force
-  widening the newtype.
-* Multiplicative/fractional operations (fees, interest, FX) need an explicit
-  rounding policy when added; they are deliberately not part of `Cent` today.
+* The scale of an asset is a convention at the application level. The type
+  system does not bind a `Cent` to the decimal places of its asset. So a caller
+  must format and parse through the right `Amount` for that asset.
+* `i64` is a hard ceiling on the magnitude of one amount and of one sum. An
+  overflow gives a `Result` and never a wrap. A later asset with high precision
+  and a high supply can force a move to a wider newtype.
+* A multiplicative or fractional operation needs an explicit rounding policy on
+  the day something adds it. A fee, interest and FX are all such operations.
+  None of them is part of `Cent` today, and that is deliberate.
 
 ## Links
 
 * Makes the conservation invariant of
-  [ADR-0001](0001-modified-utxo-signed-postings.md) exact, and feeds the
-  content-addressed id used for idempotency
-  (ADR-0005 / future "content-addressed transfer ids").
-* Floor checks that rely on exact integers:
+  [ADR-0001](0001-modified-utxo-signed-postings.md) exact. It also feeds the
+  content-addressed id that gives idempotency, which ADR-0005 covers, and which
+  a later record on content-addressed transfer ids will cover.
+* The floor checks that depend on an exact integer:
   [ADR-0004](0004-account-policies-overdraft-model.md).
 * Background: `crates/kuatia-types/src/lib.rs` (`Cent`, `Amount`, `AssetId`),
   [glossary.md](../glossary.md).

+ 73 - 65
doc/adr/0010-event-stream-vs-transfer-log.md

@@ -8,28 +8,29 @@
 
 ## Context and Problem Statement
 
-The transfer log is the append-only source of truth for value (ADR-0001):
-balances are projected by summing `Active` postings, and nothing else is
-authoritative. But applications need to *react* to the ledger (update a read
-model, notify a downstream service, drive an outbox), and not everything worth
-reacting to is a value transfer: accounts are also created, frozen, unfrozen
-and closed. Polling the transfer log misses the lifecycle events and forces
-every consumer to re-derive "what changed." Do we need a second log, what is
-authoritative, and what are its delivery/idempotency semantics?
+The transfer log is the append-only source of truth for value (ADR-0001). A
+balance is the sum of the `Active` postings, and nothing else is authoritative.
+An application must also *react* to the ledger. It updates a read model,
+notifies a downstream service, or drives an outbox.
+
+Not every event worth a reaction is a value transfer. The ledger also creates,
+freezes, unfreezes and closes an account. A consumer that reads only the
+transfer log misses those lifecycle events, and it must work out "what changed"
+for itself. Does the ledger need a second log? What is authoritative in it, and
+what are its delivery and idempotency semantics?
 
 ## Decision Drivers
 
-* **Observability without re-deriving**: consumers want a single ordered feed
-  of "what happened," not a diff of the transfer table.
+* **Observability with no second derivation**: a consumer wants one ordered feed
+  of "what happened," and not a diff of the transfer table.
 * **Non-transfer events exist**: account create/freeze/unfreeze/close are
   meaningful occurrences that are not movements of value.
 * **One source of truth**: value authority must stay with the transfer log
-  (ADR-0001); a notification feed must not become a second, competing
-  authority.
+  (ADR-0001). A notification feed must not become a second authority that
+  competes with it.
 * **Plays with saga recovery**: a committed transfer can be re-driven by
-  recovery (ADR-0003), so the event emitted for it must not duplicate on
-  replay.
-* **Fits dumb storage, mostly**: append should be a simple primitive; any
+  recovery (ADR-0003), so the event emitted for it must not duplicate on replay.
+* **Fits dumb storage, mostly**: append must be a simple primitive. Any
   deviation from "return a count" (ADR-0003) must be deliberate and justified.
 
 ## Considered Options
@@ -46,9 +47,9 @@ Derive all reactions from the append-only transfer records.
 
 * Bad, because account lifecycle changes (freeze/close) are not transfers and
   have nowhere to appear, so a whole class of events is invisible.
-* Bad, because every consumer must re-implement "tail and interpret
-  transfers," coupling them to transfer internals and offering no uniform
-  subscription point.
+* Bad, because every consumer must re-implement "tail and interpret transfers,"
+  which couples it to transfer internals. There is also no uniform subscription
+  point.
 
 #### Option 2: Event log as the source of truth (full event sourcing)
 
@@ -61,85 +62,92 @@ Make an event stream authoritative and fold balances from events.
 
 **Cons:**
 
-* Bad, because it conflicts head-on with ADR-0001: balance would become a fold
-  over events rather than a sum of `Active` postings, and the UTXO/posting
-  model would be demoted to a projection of the event log.
-* Bad, because it creates two ways to be "true" (postings vs. events) that
-  must be kept consistent, exactly the divergence ADR-0001 set out to avoid.
+* Bad, because it conflicts head-on with ADR-0001. A balance would become a fold
+  over events rather than a sum of `Active` postings. The UTXO posting model
+  would drop to a projection of the event log.
+* Bad, because it creates two ways to be "true" (postings vs. events) that must
+  be kept consistent, exactly the divergence ADR-0001 set out to avoid.
 
 #### Option 3: A secondary, derived append-only event stream (outbox-style)
 
-Keep the transfer log authoritative. Add an `EventStore`: `LedgerEvent { seq,
-timestamp, kind }` where `kind` is `TransferCommitted { transfer_id }` or an
-account-lifecycle event. The store assigns a monotonic `seq` and exposes
-`append_event` + `get_events_since(after_seq, limit)`. `append_event` is
-**store-side idempotent** on `event_dedup_key`: replayable events
-(`TransferCommitted`, re-driven by saga recovery) dedup on the transfer id and
-return the existing `seq`; events with no natural identity (account lifecycle)
-return `None` and may recur. The feed is *derived*: it observes what the
-authoritative writes already decided.
+Keep the transfer log authoritative. Add an `EventStore`:
+`LedgerEvent { seq, timestamp, kind }` where `kind` is
+`TransferCommitted { transfer_id }` or an account-lifecycle event. The store
+assigns a monotonic `seq` and exposes `append_event` +
+`get_events_since(after_seq, limit)`. `append_event` is **store-side
+idempotent** on `event_dedup_key`. A replayable event (`TransferCommitted`,
+which saga recovery re-drives) dedups on the transfer id and returns the `seq`
+that is already there. An event with no natural identity (account lifecycle)
+returns `None` and can recur.
+
+The feed is *derived*: it observes what the authoritative writes already
+decided.
 
 **Pros:**
 
 * Good, because value authority stays with the transfer log (ADR-0001); the
   event stream is an observation feed, not a second source of truth.
-* Good, because lifecycle events that are not transfers finally have a home,
-  and consumers get one ordered, tailable feed (`get_events_since`) instead of
-  re-deriving from transfers.
-* Good, because dedup on the transfer id makes `TransferCommitted` survive saga
-  recovery's re-drive without emitting a duplicate: at-least-once upstream
-  becomes effectively-once for the events that carry a content identity.
-* Good, because it is an outbox the saga appends to as its last step,
-  decoupling downstream delivery from the commit's critical path.
+* Good, because a lifecycle event that is not a transfer finally has a home. A
+  consumer gets one ordered, tailable feed (`get_events_since`) and derives
+  nothing from the transfers.
+* Good, because dedup on the transfer id makes `TransferCommitted` survive the
+  re-drive of saga recovery, and it emits no duplicate. At-least-once upstream
+  becomes effectively-once for every event that carries a content identity.
+* Good, because it is an outbox that the saga appends to as its last step. That
+  keeps downstream delivery off the critical path of the commit.
 
 **Cons:**
 
 * Bad, because it is a second append-only log to persist, index by `seq`, and
   retain.
 * Bad, because `append_event` deviates from the dumb-storage "return an
-  affected-row count" rule (ADR-0003): the store assigns `seq` and performs the
-  dedup, since both are storage-native and the key is content-based, not a
+  affected-row count" rule (ADR-0003). The store assigns `seq` and does the
+  dedup. Both are storage-native, and the key is content-based rather than a
   state-machine decision. A deliberate, narrow exception.
-* Bad, because lifecycle events have no dedup key and **may duplicate** on
-  retry/recovery, so consumers must tolerate at-least-once for those.
+* Bad, because lifecycle events have no dedup key and **can duplicate** on retry
+  or recovery. So a consumer must tolerate at-least-once for those.
 * Bad, because `seq` orders events but is not a causal/transactional clock; it
   is an emission order, not a serialization of value state.
 
 ## Decision Outcome
 
 Chosen option: **Option 3, a derived, append-only event stream alongside the
-authoritative transfer log**, because it gives applications a uniform, ordered
-feed (including non-transfer lifecycle events) without challenging ADR-0001's
-"transfer log is the only authority on value." Making `append_event` idempotent
-on a content-based `event_dedup_key` is what lets the saga emit it safely under
-recovery re-drive; accepting that keyless lifecycle events may recur keeps the
-model honest about at-least-once delivery. The store-side `seq` assignment and
-dedup are a consciously scoped exception to dumb storage (ADR-0003), justified
-because both are intrinsic storage concerns rather than domain decisions.
+authoritative transfer log**, because it gives an application one uniform,
+ordered feed. That feed holds the non-transfer lifecycle events too, and it
+challenges nothing in ADR-0001: the transfer log stays the only authority on
+value.
+
+`append_event` is idempotent on a content-based `event_dedup_key`, which is what
+lets the saga emit it safely under a recovery re-drive. A keyless lifecycle
+event can recur, and the model says so, because delivery is at-least-once. The
+store-side `seq` assignment and dedup are a deliberate, narrow exception to dumb
+storage (ADR-0003). Both are intrinsic storage concerns rather than domain
+decisions, which is the justification.
 
 ### Positive Consequences
 
 * One subscription point (`get_events_since`) for read models, outboxes and
   notifications; consumers no longer reverse-engineer the transfer table.
-* `TransferCommitted` is effectively-once thanks to transfer-id dedup, aligning
-  with the saga's idempotent re-drive (ADR-0003) and content-addressed
-  transfers.
-* Balances remain a pure projection of `Active` postings; the event stream adds
-  no competing authority.
+* `TransferCommitted` is effectively-once because of the transfer-id dedup. That
+  matches the idempotent re-drive of the saga (ADR-0003) and the
+  content-addressed transfers.
+* Balances remain a pure projection of `Active` postings. The event stream adds
+  no second authority.
 
 ### Negative Consequences
 
-* A second append-only log to store and retain (no pruning policy is defined
-  yet, a candidate future ADR alongside posting/log retention).
-* `append_event` is a documented exception to the count-returning storage
-  contract.
-* Account-lifecycle events may be delivered more than once; consumers must be
-  idempotent. `seq` is emission order, not a causal clock.
+* A second append-only log to store and retain. No policy for the deletion of
+  old rows exists yet, and that is a candidate for a future ADR beside posting
+  and log retention.
+* `append_event` is a documented exception to the storage contract that returns
+  a count.
+* An account-lifecycle event can arrive more than once, so a consumer must be
+  idempotent. `seq` is emission order and not a causal clock.
 
 ## Links
 
-* Subordinate to [ADR-0001](0001-modified-utxo-signed-postings.md) (transfer
-  log is the source of truth; events are derived).
+* Subordinate to [ADR-0001](0001-modified-utxo-signed-postings.md) (transfer log
+  is the source of truth; events are derived).
 * Idempotent emission under recovery:
   [ADR-0003](0003-dumb-storage-saga-recovery.md); the `append_event` exception
   is scoped against that ADR's dumb-storage contract.

+ 95 - 105
doc/adr/0011-swappable-money-backing.md

@@ -10,35 +10,34 @@
 
 ## Context and Problem Statement
 
-ADR-0009 fixed monetary amounts as `i64` minor units and noted that
-widening to a larger integer "is a contained newtype change if a real
-asset ever needs it." That contained change is now wanted: a runtime
-that defaults to `i64` for the common case but can be compiled with
-`i128` for assets whose precision and supply exceed `i64`'s ~±9.2×10¹⁸
-ceiling. At the same time the concrete width should stop leaking:
-`Cent::value() -> i64`, the 8-byte hash encoding, and the `BIGINT`
-column all hard-code the backing. How do we make the backing a
-swappable, hidden detail without threading a type parameter through
-every posting, movement and store method?
+ADR-0009 fixed monetary amounts as `i64` minor units. It also said that a move
+to a larger integer "is a contained newtype change if a real asset ever needs
+it". A caller now wants that contained change. The runtime must default to `i64`
+for the common case. It must also compile with `i128` for an asset whose
+precision and supply go past the `i64` ceiling of about ±9.2×10¹⁸.
+
+At the same time the concrete width must disappear from the open surface.
+`Cent::value() -> i64`, the 8-byte hash encoding and the `BIGINT` column all
+hard-code the backing. How does the ledger make the backing a swappable, hidden
+detail, and give no posting, movement or store method a type parameter?
 
 ## Decision Drivers
 
-* **Swappable, single choice per build**: i64 by default, i128 by a
-  compile-time switch; one money width per binary (a ledger does not
-  need two at once).
-* **Hidden width**: no public signature, serialized form, or DB column
-  should reveal whether the backing is 64- or 128-bit.
-* **Minimal churn**: postings, movements, validation, the store traits
-  and the saga must not gain a generic parameter; "clarity over
-  cleverness."
+* **Swappable, single choice per build**: i64 by default, i128 by a compile-time
+  switch. One money width per binary, because a ledger does not need two at
+  once.
+* **Hidden width**: no public signature, serialized form or DB column must show
+  whether the backing is 64-bit or 128-bit.
+* **Minimal churn**: postings, movements, validation, the store traits and the
+  saga must not gain a generic parameter; "clarity over cleverness."
 * **Stable content addresses**: amounts feed the double-SHA256
-  `EnvelopeId`/`PostingId`; swapping the width must not silently rehash
-  the ledger.
-* **Backend reality**: Postgres and SQLite have no native 128-bit
-  integer; sqlx cannot bind/get `i128` for them, so the persisted form
-  must not be a native wide integer.
-* **Exact, safe math**: keep checked add/sub/neg/sum with overflow as an
-  error (ADR-0009).
+  `EnvelopeId`/`PostingId`. A change of the width must not silently rehash the
+  ledger.
+* **Backend reality**: Postgres and SQLite have no native 128-bit integer, and
+  sqlx cannot bind or get `i128` for them. So the persisted form must not be a
+  native wide integer.
+* **Exact, safe math**: keep checked add/sub/neg/sum with overflow as an error
+  (ADR-0009).
 
 ## Considered Options
 
@@ -48,47 +47,46 @@ Parameterize the type over its backing and let callers pick.
 
 **Pros:**
 
-* Good, because multiple widths could coexist and the choice is explicit
-  at the type level.
+* Good, because multiple widths could coexist and the choice is explicit at the
+  type level.
 
 **Cons:**
 
 * Bad, because the parameter propagates into `Posting`, `NewPosting`,
-  `Movement`, `Envelope`, `Account` (via `CappedOverdraft`), every
-  builder, all of `kuatia-core`, the `Store` trait family and the saga.
-  That is large churn for no domain benefit, since a build uses exactly
-  one width.
-* Bad, because `Hash`/`Ord`/serde/content-addressing all become generic,
-  the opposite of "clarity over cleverness."
+  `Movement`, `Envelope` and `Account` (via `CappedOverdraft`). It also reaches
+  every builder, all of `kuatia-core`, the `Store` trait family and the saga.
+  That is large churn for no domain benefit, because a build uses exactly one
+  width.
+* Bad, because `Hash`, `Ord`, serde and the content address all become generic.
+  That is the opposite of "clarity over cleverness."
 
 #### Option 2: Non-generic `Cent(Backing)` + `CentBacking` trait + cargo-feature selector
 
-`Cent` stays a concrete newtype over a `Backing` type alias. A
-`CentBacking` trait carries the arithmetic, canonical-byte and string
-primitives, with impls for `i64` and `i128`. A cargo feature flips `type
-Backing` between them. The width never appears in a public signature:
-reads go through `to_string()`/parse and through a fixed-width canonical
-encoding; `value() -> i64` is removed.
+`Cent` stays a concrete newtype over a `Backing` type alias. A `CentBacking`
+trait carries the arithmetic, canonical-byte and string primitives, with impls
+for `i64` and `i128`. A cargo feature flips `type Backing` between them. The
+width never appears in a public signature: reads go through `to_string()`/parse
+and through a fixed-width canonical encoding; `value() -> i64` is removed.
 
 **Pros:**
 
-* Good, because swapping is "write the other impl, flip a feature":
-  `impl CentBacking for i128` plus `--features kuatia-money/i128`, with
-  no change to any downstream crate.
-* Good, because nothing downstream gains a type parameter; `Posting`, the
-  store traits and the saga are untouched.
-* Good, because the public surface (`to_string`, parse, checked math,
-  `Ord`, fixed-width canonical bytes) names no concrete integer type, so
-  the width is hidden.
+* Good, because a swap is "write the other impl, flip a feature":
+  `impl CentBacking for i128` plus `--features kuatia-money/i128`, with no
+  change to any downstream crate.
+* Good, because nothing downstream gains a type parameter; `Posting`, the store
+  traits and the saga are untouched.
+* Good, because the public surface (`to_string`, parse, checked math, `Ord`,
+  fixed-width canonical bytes) names no concrete integer type, so the width is
+  hidden.
 
 **Cons:**
 
-* Bad, because the backing is a workspace-global compile-time choice
-  (cargo feature unification), not a per-value one. That is acceptable,
-  and in fact the intent.
-* Bad, because the `value` column moving to text loses SQL-side numeric
-  ordering on amounts. That is already irrelevant, since all arithmetic
-  is in Rust and no query sorts or ranges on the amount.
+* Bad, because the backing is a workspace-global compile-time choice (cargo
+  feature unification), not a per-value one. That is acceptable, and in fact the
+  intent.
+* Bad, because the `value` column becomes text, and SQL then cannot order
+  numerically on amounts. That is already irrelevant, because all arithmetic is
+  in Rust and no query sorts or ranges on the amount.
 
 #### Option 3: Keep `i64`, just widen the column to `NUMERIC`
 
@@ -100,80 +98,72 @@ Leave the Rust type as `i64` and only make storage wider.
 
 **Cons:**
 
-* Bad, because it does not actually let the runtime compute in `i128`;
-  the in-memory ceiling is still `i64`. It solves none of the request.
+* Bad, because it does not actually let the runtime compute in `i128`; the
+  in-memory ceiling is still `i64`. It solves none of the request.
 
 ## Decision Outcome
 
 Chosen option: **Option 2, a non-generic `Cent(Backing)` newtype with a
-`CentBacking` trait and a cargo-feature selector**, in a new
-`kuatia-money` crate. It delivers the i64↔i128 swap as a second trait
-impl behind a feature flag, keeps the default at `i64`, and hides the
-width from every public and stored form, all without threading a generic
-through the ledger.
+`CentBacking` trait and a cargo-feature selector**, in a new `kuatia-money`
+crate. It gives the i64↔i128 swap as a second trait impl behind a feature flag,
+and it keeps the default at `i64`. It hides the width from every public and
+stored form. No type in the ledger gains a generic parameter.
 
 Concretely:
 
-* **`kuatia-money` crate** (leaf, `serde` only) holds `Cent`,
-  `OverflowError`, `Amount`, `ParseAmountError`, the `CentBacking` trait,
-  `impl CentBacking for i64`/`i128`, and the `Backing` alias.
-  `kuatia-types` depends on it and re-exports (`pub use
-  kuatia_money::{Cent, Amount, …}`), so every existing
-  `kuatia_types::Cent` import keeps compiling.
+* **`kuatia-money` crate** (leaf, `serde` only) holds `Cent`, `OverflowError`,
+  `Amount`, `ParseAmountError`, the `CentBacking` trait,
+  `impl CentBacking for i64`/`i128`, and the `Backing` alias. `kuatia-types`
+  depends on it and re-exports (`pub use kuatia_money::{Cent, Amount, …}`). So
+  every `kuatia_types::Cent` import that exists today still compiles.
 * **Selector:** `#[cfg(not(feature = "i128"))] pub type Backing = i64;` /
-  `#[cfg(feature = "i128")] pub type Backing = i128;`. Default backing is
-  `i64`.
+  `#[cfg(feature = "i128")] pub type Backing = i128;`. Default backing is `i64`.
 * **Hidden width:** `value() -> i64` is removed. The public surface is
-  `to_string()` (minor-unit string), `FromStr`, the
-  `From<i32/u32/u8/i8/i64>` literal constructors, checked math,
-  predicates and `Ord`. Serde for `Cent` is hand-written to
-  (de)serialize the **string** form, so no serialized form reveals the
-  width.
-* **Canonical bytes for hashing are fixed at 16 bytes** (sign-extended
-  big-endian), independent of the backing, so an i64 amount and the same
-  i128 amount hash identically and swapping the backing does not change
-  any `EnvelopeId`/`PostingId`. `CANONICAL_VERSION` is bumped 1→2 to mark
-  the new encoding.
-* **Storage serializes to string:** the `value` column becomes `TEXT`;
-  the codec binds `cent.to_string()` and reads it back with `FromStr`.
-  This both hides the width and avoids native 128-bit integers, which
-  Postgres/SQLite lack.
+  `to_string()` (minor-unit string), `FromStr`, the `From<i32/u32/u8/i8/i64>`
+  literal constructors, checked math, predicates and `Ord`. Serde for `Cent` is
+  hand-written to (de)serialize the **string** form, so no serialized form
+  reveals the width.
+* **Canonical bytes for the hash are fixed at 16 bytes** (sign-extended
+  big-endian), independent of the backing. So an i64 amount and the same i128
+  amount hash identically, and a change of the backing changes no
+  `EnvelopeId`/`PostingId`. `CANONICAL_VERSION` is bumped 1→2 to mark the new
+  encoding.
+* **Storage serializes to string:** the `value` column becomes `TEXT`; the codec
+  binds `cent.to_string()` and reads it back with `FromStr`. This both hides the
+  width and avoids native 128-bit integers, which Postgres/SQLite lack.
 
 ### Positive Consequences
 
-* The default build is behaviorally identical to ADR-0009's `i64`
-  ledger; switching to `i128` is one cargo feature and needs no source
-  edits beyond the (already-written) second trait impl.
+* The default build behaves exactly like ADR-0009's `i64` ledger. A move to
+  `i128` is one cargo feature. It needs no source edit beyond the second trait
+  impl, which is already written.
 * No public signature, serialized blob, or column type names the backing
   integer; the width is an internal detail.
-* Content addresses are stable across the swap, because the hash preimage
-  width is fixed.
-* All arithmetic stays exact and checked; overflow remains an
-  `OverflowError`.
+* Content addresses are stable across the swap, because the hash preimage width
+  is fixed.
+* All arithmetic stays exact and checked; overflow remains an `OverflowError`.
 
 ### Negative Consequences
 
-* The backing is chosen workspace-wide at compile time, not per value
-  (cargo feature unification).
-* Amounts are stored as text, so the database cannot order or
-  range-filter on the amount. This is a non-issue here, since amount
-  math is Rust-only and no query depends on SQL ordering of the value.
-* This supersedes ADR-0009's "persisted amount is a plain `BIGINT`"
-  consequence; the persisted form is now text. Per project convention
-  there are no migrations pre-release: `001_init.sql` is edited in place
-  and the database recreated.
+* The backing is chosen workspace-wide at compile time, not per value (cargo
+  feature unification).
+* Amounts are stored as text, so the database cannot order or range-filter on
+  the amount. That costs nothing here, because amount math is Rust-only and no
+  query depends on how SQL orders the value.
+* This supersedes ADR-0009's "persisted amount is a plain `BIGINT`" consequence;
+  the persisted form is now text. Per project convention there are no migrations
+  pre-release: `001_init.sql` is edited in place and the database recreated.
 
 ## Links
 
-* Refines [ADR-0009](0009-monetary-representation-integer-minor-units.md)
-  (keeps integer minor units; makes the width swappable and hidden, and
-  changes the persisted form from `BIGINT` to text).
+* Refines [ADR-0009](0009-monetary-representation-integer-minor-units.md) (keeps
+  integer minor units; makes the width swappable and hidden, and changes the
+  persisted form from `BIGINT` to text).
 * Feeds the content-addressed id of
   [ADR-0001](0001-modified-utxo-signed-postings.md) /
-  [ADR-0005](0005-intent-api-movements-vs-envelopes.md); fixed-width
-  canonical bytes keep ids stable.
+  [ADR-0005](0005-intent-api-movements-vs-envelopes.md); fixed-width canonical
+  bytes keep ids stable.
 * Floor checks on exact integers:
   [ADR-0004](0004-account-policies-overdraft-model.md).
 * Background: `crates/kuatia-money/src/lib.rs` (new),
-  `crates/kuatia-types/src/lib.rs`,
-  `crates/kuatia-storage-sql/src/lib.rs`.
+  `crates/kuatia-types/src/lib.rs`, `crates/kuatia-storage-sql/src/lib.rs`.

+ 125 - 111
doc/adr/0012-subaccounts.md

@@ -9,24 +9,27 @@
 
 ## Context and Problem Statement
 
-An account was identified by a single `i64` (`AccountId`). Some workloads need to
-partition one account's holdings into several distinct balances under the same
-owner: sub-ledgers, per-purpose buckets, earmarks, or reservations that are
-individually addressable and drained or closed independently, without minting
-unrelated top-level accounts. Classical accounting calls the general shape a
-control account with a subsidiary ledger; payment and banking systems call it a
-sub-ledger or a set of virtual accounts under a master account.
-
-We want that structure as a first-class part of account identity: an account is a
+A single `i64` (`AccountId`) identified an account. Some workloads must
+partition the holdings of one account into several distinct balances under the
+same owner. A sub-ledger, a per-purpose bucket, an earmark and a reservation are
+all such balances. Each one must have its own address. Each one must also drain
+or close on its own, with no unrelated top-level account.
+
+Classical accounting calls the general shape a control account with a subsidiary
+ledger. A payment system or a bank calls it a sub-ledger, or a set of virtual
+accounts under a master account.
+
+That structure must be a first-class part of account identity. An account is a
 base id plus a **subaccount**, and each partition is a full account record with
-its own policy, so no special-case code is needed to give a partition its own
-overdraft rule or lifecycle. The default subaccount (`0`) is the account's main
-account, so existing behaviour is unchanged when subaccounts are not used.
+its own policy. So a partition gets its own overdraft rule and its own
+lifecycle, and no special-case code gives it one. The default subaccount (`0`)
+is the main account of that account. Behaviour does not change for a caller that
+uses no subaccount.
 
 ## Decision Drivers
 
-* **Partitioning and attribution**: several balances under one owner, each
-  addressable and discoverable as a subaccount of the base account.
+* **Partition and attribution**: several balances under one owner, each with its
+  own address and each visible as a subaccount of the base account.
 * **Per-partition policy**: a subaccount must be able to carry its own policy,
   flags, book, and version, independent of the base account.
 * **Segregated balances**: a base account's subaccounts must never be silently
@@ -41,27 +44,28 @@ account, so existing behaviour is unchanged when subaccounts are not used.
 
 #### Option 1: Fold the subaccount into `AccountId` (a composite `{id, sub}`, chosen)
 
-Make the account identity itself two legs: `AccountId { id: i64, sub: i64 }`, with
-`sub = 0` the main account. Aggregate reads take a base `id: i64` plus an optional
-subaccount filter.
+Make the account identity itself two legs: `AccountId { id: i64, sub: i64 }`,
+with `sub = 0` the main account. Aggregate reads take a base `id: i64` plus an
+optional subaccount filter.
 
 **Pros:**
 
-* Good, because there is one identity type: posting owners, movement endpoints,
-  account records, and balance keys are all `AccountId`, so per-subaccount
-  balances fall out of the existing keys with no new wrapper type.
-* Good, because "query by account or by subaccount" is explicit: base reads take
-  `(id: i64, sub: Option<i64>)` — `None` spans every subaccount, `Some(s)`
-  restricts to one — while entity ops take the full `&AccountId`.
+* Good, because there is one identity type. A posting owner, a movement
+  endpoint, an account record and a balance key are all `AccountId`. So a
+  per-subaccount balance falls out of the keys that are already there, with no
+  new wrapper type.
+* Good, because "query by account or by subaccount" is explicit. A base read
+  takes `(id: i64, sub: Option<i64>)`, where `None` spans every subaccount and
+  `Some(s)` restricts to one. An entity operation takes the full `&AccountId`.
 * Good, because each `(id, sub)` is a full account record with its own policy.
 
 **Cons:**
 
-* Bad, because callers that want a base handle read `account.id` rather than
-  passing a distinct base type; the split between base reads (`i64`) and exact
-  entity ops (`&AccountId`) has to be kept clear.
-* Bad, because it is a large, cross-crate change (the identity gains a field, `.0`
-  accesses become `.id`) plus a schema migration.
+* Bad, because a caller that wants a base handle reads `account.id`, and no
+  distinct base type exists to pass. The split between a base read (`i64`) and
+  an exact entity operation (`&AccountId`) has to stay clear.
+* Bad, because it is a large, cross-crate change (the identity gains a field,
+  `.0` accesses become `.id`) plus a schema migration.
 
 #### Option 2: A separate `AccountRef { account, sub }` owner/identity type
 
@@ -77,13 +81,13 @@ owner/endpoint/entity identity.
 
 * Bad, because it adds a second account-identity type (`AccountId` vs
   `AccountRef`) that every layer has to convert between.
-* Bad, because it is the same cross-crate churn as Option 1 without collapsing to
-  a single identity.
+* Bad, because it is the same cross-crate churn as Option 1, and it does not
+  collapse to a single identity.
 
 #### Option 3: Subaccounts as balance buckets that inherit the parent policy
 
-Track a subaccount only on postings, with the account entity keyed by base id and
-its policy shared by all subaccounts.
+Track a subaccount only on postings, with the account entity keyed by base id
+and its policy shared by all subaccounts.
 
 **Pros:**
 
@@ -92,14 +96,16 @@ its policy shared by all subaccounts.
 **Cons:**
 
 * Bad, because a subaccount cannot carry its own policy. A partition that must
-  stay `NoOverdraft` under a `SystemAccount`/overdraft base account could not,
-  so any structural guarantee that depends on the partition's own policy is lost.
+  stay `NoOverdraft` under a `SystemAccount`/overdraft base account then cannot
+  do so. Every structural guarantee that depends on the policy of the partition
+  is lost.
 
 ## Decision Outcome
 
-Chosen option: **Option 1, fold the subaccount into `AccountId`**, because a
-single two-leg identity keeps balances naturally segregated, lets every
-subaccount carry its own policy, and avoids carrying two account-identity types.
+Chosen option: **Option 1, fold the subaccount into `AccountId`**. A single
+two-leg identity keeps balances segregated by itself, and it lets every
+subaccount carry its own policy. The ledger also holds one account-identity type
+and not two.
 
 ### The identity type
 
@@ -108,14 +114,15 @@ account; a non-zero `sub` is a subaccount. `sub` is an `i64`, the same type as
 the base id, so it stores directly in a `BIGINT` column with no cast.
 Constructors and helpers:
 
-* `AccountId::new(id)` — the main account `{ id, sub: 0 }`.
-* `AccountId::with_sub(id, sub)` — a specific subaccount.
-* `base()` — the main account of an id (`sub` set to `0`).
-* `is_main()` — whether `sub == 0`.
+* `AccountId::new(id)`: the main account `{ id, sub: 0 }`.
+* `AccountId::with_sub(id, sub)`: a specific subaccount.
+* `base()`: the main account of an id (`sub` set to `0`).
+* `is_main()`: whether `sub == 0`.
 
-`AccountId` derives `Copy`/`Eq`/`Hash`/`Ord` and its canonical `ToBytes` is the
-base id followed by the subaccount (both big-endian), so the subaccount is folded
-into every content hash (envelope ids, posting ids, account snapshots).
+`AccountId` derives `Copy`/`Eq`/`Hash`/`Ord`. Its canonical `ToBytes` is the
+base id and then the subaccount, both big-endian. So every content hash folds
+the subaccount in, and that covers envelope ids, posting ids and account
+snapshots.
 
 ### IBAN-style account code
 
@@ -125,49 +132,52 @@ is two ISO 7064 mod-97 check digits followed by a 26-character base-36 body,
 with no country code. `to_grouped()` adds a space every four characters for
 display.
 
-The body does not encode the raw legs directly. The `(id, sub)` pair is first
-run through a keyed 128-bit Feistel permutation, then each 64-bit half is
-base-36 encoded (13 characters each). Without this, small sequential ids would
-render as near-zero codes that leak their value and order, and a base account
-and its subaccount would share a visible prefix. After the permutation the codes
-look random and unrelated. Under the default seed, `AccountId { id: 5, sub: 7 }`
-renders `221RDWNSN4VCQNK2NN42KJFSAOLI` (grouped `221R DWNS N4VC QNK2 NN42 KJFS
-AOLI`).
-
-`FromStr` ignores spaces and dashes, upper-cases the input, checks the
-structure, and **validates the mod-97 checksum** (returning `ParseAccountIdError`
-on failure), then inverts the permutation to recover the two legs. Each half is
-read as a `u64` bit pattern and reinterpreted as `i64`, so any value
-round-trips.
-
-The permutation key is a process-global seed with a built-in default, settable
-once at startup with `set_id_seed` (the dashboard exposes it as `--id-seed` /
-`KUATIA_ID_SEED`). Changing the seed changes every code, so it must be stable
-across a deployment. This is obfuscation, not security: anyone with the seed can
-decode a code, so it is not a substitute for authorization.
-
-This is a presentation and edge form only. Storage and low-level usages keep the
-two `i64` legs: the SQL schema, the `Store` trait signatures and query types,
-in-memory keys, `ToBytes`, and serde (`{id, sub}`) are unchanged, so there is no
-migration and no content-hash impact. The dashboard exposes the string as a
-`code` field and routes account pages by the machine form (`/accounts/<code>`),
-parsing and checksum-validating it at the route boundary. `Debug` keeps the short
-`id` / `id.sub` form for logs.
+The body does not encode the raw legs directly. The `(id, sub)` pair first goes
+through a keyed 128-bit Feistel permutation. Each 64-bit half is then base-36
+encoded, at 13 characters each. Without the permutation, a small sequential id
+renders as a near-zero code that leaks its value and its order. A base account
+and its subaccount also share a visible prefix. After the permutation the codes
+look random and unrelated.
+
+Under the default seed, `AccountId { id: 5, sub: 7 }` renders
+`221RDWNSN4VCQNK2NN42KJFSAOLI` (grouped `221R DWNS N4VC QNK2 NN42 KJFS AOLI`).
+
+`FromStr` ignores spaces and dashes, upper-cases the input and checks the
+structure. It then **validates the mod-97 checksum** and returns
+`ParseAccountIdError` on a failure. After that it inverts the permutation to
+recover the two legs. Each half is read as a `u64` bit pattern and reinterpreted
+as `i64`, so any value round-trips.
+
+The permutation key is a process-global seed with a built-in default. A caller
+sets it once at startup with `set_id_seed`, and the dashboard exposes it as
+`--id-seed` / `KUATIA_ID_SEED`. A new seed changes every code, so the seed must
+stay stable across a deployment. This is obfuscation and not security. Anyone
+with the seed can decode a code, so it is no substitute for authorization.
+
+This is a presentation and edge form only. Storage and the low-level uses keep
+the two `i64` legs. The SQL schema, the `Store` trait signatures and query
+types, the in-memory keys, `ToBytes` and serde (`{id, sub}`) are all unchanged.
+So there is no migration and no content-hash impact.
+
+The dashboard exposes the string as a `code` field and routes an account page by
+the machine form (`/accounts/<code>`). It parses the code at the route boundary
+and checks the checksum there. `Debug` keeps the short `id` / `id.sub` form for
+logs.
 
 ### The entity model
 
 Each `(id, sub)` is its own **full account record** with its own `policy`,
 `flags`, `book`, `version`, `user_data`, and `metadata`. The main account is
-`(id, 0)`. A subaccount is created, versioned, frozen, and closed exactly like any
-other account (closing still requires zero live postings), and its policy is
-enforced independently — a subaccount can be `NoOverdraft` while its base account
-is not, or vice versa.
+`(id, 0)`. The ledger creates, versions, freezes and closes a subaccount exactly
+like any other account, and a close still needs zero live postings. The policy
+of a subaccount is enforced on its own. So a subaccount can be `NoOverdraft`
+while its base account is not, or the other way round.
 
 `AccountId` is the owner of a posting (`Posting.owner`, `NewPosting.owner`,
-`NewPosting.payer`), the endpoint of a movement (`Movement.from`/`to`), the id of
-an `Account`, and the subject of an `AccountSnapshotId`. `TransferBuilder::pay` and
-`movement` move between main accounts; `pay_ref` and `movement_ref` move between
-specific subaccounts.
+`NewPosting.payer`) and the endpoint of a movement (`Movement.from`/`to`). It is
+also the id of an `Account` and the subject of an `AccountSnapshotId`.
+`TransferBuilder::pay` and `movement` move between main accounts; `pay_ref` and
+`movement_ref` move between specific subaccounts.
 
 ### Reads: by account or by subaccount
 
@@ -178,8 +188,8 @@ take a base `id: i64` plus an optional subaccount:
 * `get_postings_by_account(id: i64, sub: Option<i64>, asset, status)` and
   `get_transfers_for_account(id: i64, sub: Option<i64>)` span every subaccount
   when `sub` is `None` and one when `Some(s)`.
-* `PostingQuery`/`TransferQuery` carry a base `account: i64` and `sub:
-  Option<i64>`.
+* `PostingQuery`/`TransferQuery` carry a base `account: i64` and
+  `sub: Option<i64>`.
 
 ### Balances are always segregated
 
@@ -193,51 +203,55 @@ Balances are reported per subaccount and never summed across them:
   subaccounts of a base account.
 
 Closed subaccounts are excluded from the aggregate reads. This inverts the
-classical control-account expectation (where a parent's balance is the sum of its
-subsidiaries) on purpose: a base account does **not** roll up its subaccounts.
+classical control-account expectation on purpose, where the balance of a parent
+is the sum of its subsidiaries. A base account does **not** roll up its
+subaccounts.
 
 ### Validation and books
 
-Per-asset conservation and the balance-floor / negative-posting checks operate on
-the full `AccountId` owner, so they are per subaccount and use each subaccount's
-own policy. Book membership is scoped by **base account**: a book that lists a
-base account (or matches its flags) admits all of that account's subaccounts.
+Per-asset conservation and the balance-floor / negative-posting checks operate
+on the full `AccountId` owner, so they are per subaccount and use each
+subaccount's own policy. Book membership is scoped by **base account**: a book
+that lists a base account (or matches its flags) admits all of that account's
+subaccounts.
 
 ### Storage schema and migration
 
 * `accounts` primary key becomes `(id, subaccount, version)`. `postings` gain a
-  `subaccount` column and `idx_postings_owner` widens to `(owner, subaccount,
-  asset, status)`. `transfer_accounts` gains `subaccount` in its key and index.
+  `subaccount` column and `idx_postings_owner` widens to
+  `(owner, subaccount, asset, status)`. `transfer_accounts` gains `subaccount`
+  in its key and index.
 * The subaccount is an `i64`, so it stores directly in a `BIGINT` column with no
-  cast (an opaque id, compared only for equality in SQL, never as a magnitude).
-* A `002_subaccounts` migration adds the column (existing rows default to
-  `subaccount = 0`, the main account) and rebuilds `accounts` /
-  `transfer_accounts` for the widened primary keys, since SQLite cannot alter a
-  primary key. `001_init.sql` is left intact. The in-memory store keys accounts by
-  the composite `AccountId` directly.
+  cast. It is an opaque id: SQL compares it for equality alone, and never as a
+  magnitude.
+* A `002_subaccounts` migration adds the column, and a row that is already there
+  defaults to `subaccount = 0`, the main account. The migration also rebuilds
+  `accounts` / `transfer_accounts` for the widened primary keys, because SQLite
+  cannot alter a primary key. `001_init.sql` is left intact. The in-memory store
+  keys accounts by the composite `AccountId` directly.
 
 ### Positive Consequences
 
-* One account can carry several independent balances, each a full account record
-  with its own policy, discoverable via `list_subaccounts` and attributable by
-  shared base id.
+* One account can carry several independent balances. Each one is a full account
+  record with its own policy, `list_subaccounts` finds it, and the shared base
+  id attributes it.
 * Balances are always presented per subaccount, so a main account and its
   subaccounts are never accidentally summed into one figure.
-* Conservation, double-spend, and floor guarantees are unchanged; they simply key
-  on the full `(id, sub)` owner.
+* Conservation, double-spend, and floor guarantees are unchanged; they simply
+  key on the full `(id, sub)` owner.
 
 ### Negative Consequences
 
-* Every content hash changes (the subaccount is folded into `AccountId`'s
-  canonical bytes) and the schema migrates. Existing data upgrades in place to
-  `subaccount = 0`.
-* Because accounts are append-only and never deleted, each subaccount that is
-  created and later closed leaves a permanent record (its versions plus its
-  inactive postings); the accounts and postings tables grow with the number of
-  subaccounts ever created, not the number currently open.
-* `list_subaccounts` and any "open subaccounts" scan currently read all account
-  rows and filter in memory, so they pay for closed subaccounts; a store with many
-  historical subaccounts would want an index on the not-closed set.
+* Every content hash changes, because the canonical bytes of `AccountId` now
+  fold the subaccount in, and the schema migrates. The data that is already
+  stored upgrades in place to `subaccount = 0`.
+* Accounts are append-only and the ledger deletes none. So a subaccount that is
+  created and later closed leaves a permanent record of its versions and its
+  inactive postings. The accounts and postings tables grow with the number of
+  subaccounts ever created, and not with the number open now.
+* `list_subaccounts` and any "open subaccounts" scan read all account rows today
+  and filter in memory, so they pay for the closed subaccounts. A store with
+  many historical subaccounts wants an index on the not-closed set.
 * The base-id-vs-full-`AccountId` split (aggregate reads take `i64`, entity ops
   take `&AccountId`) has to be kept clear at call sites.
 

+ 82 - 64
doc/adr/0013-journaling-model.md

@@ -8,114 +8,132 @@
 
 ## Context and Problem Statement
 
-Kuatia is presented as a double-entry-style ledger, but it does not have a
-"journal" or "journal entry" type, and it has a `Book` type whose name invites
-confusion with an accounting book or journal. Users ask whether the ledger
-supports journaling, in particular compound entries that touch more than two
-accounts. The mechanics exist already (a `Transfer` is a list of `Movement`s
-committed atomically, and `TransferStore` is an append-only log), so the open
-question is naming and framing: what, in Kuatia's model, is a journal entry,
-what is the journal, and what is `Book`?
+The documents present Kuatia as a double-entry-style ledger. But it has no
+"journal" type and no "journal entry" type. It has a `Book` type, and that name
+invites confusion with an accounting book or a journal.
+
+A user asks whether the ledger supports journaling, and in particular a compound
+entry that touches more than two accounts. The mechanics exist already. A
+`Transfer` is a list of `Movement`s that commits atomically, and `TransferStore`
+is an append-only log.
+
+So the open question is what to call these things, and how to present them. In
+Kuatia's model, what is a journal entry, what is the journal, and what is
+`Book`?
 
 ## Decision Drivers
 
-* Accountants and integrators reason in journal / journal-entry / compound-entry
-  terms; the model should map onto those without a new type.
-* The mapping must be unambiguous about what is and is not the journal, because
-  `Book`, the transfer log, and the event log are all easy to conflate.
-* Per-asset conservation is the safety invariant and must be the stated
-  equivalent of `Σ debits = Σ credits`.
-* Avoid introducing redundant types that duplicate `Transfer` / `Envelope` /
+* An accountant and an integrator both reason in terms of a journal, a journal
+  entry and a compound entry. The model must map onto those terms, and it must
+  need no new type.
+* The mapping must say exactly what the journal is, and what it is not. `Book`,
+  the transfer log and the event log are all easy to confuse.
+* Per-asset conservation is the safety invariant. The documents must state it as
+  the equivalent of `Σ debits = Σ credits`.
+* Add no redundant type. A new type must not duplicate `Transfer`, `Envelope` or
   `TransferStore`.
 
 ## Considered Options
 
 #### Option 1: Model journaling with the existing types, and document the mapping
 
-Declare that a committed `Transfer` (resolved into an `Envelope`) is a journal
-entry, that a `Transfer` with multiple `Movement`s is a compound journal entry,
-and that the transfer log (`TransferStore` of `EnvelopeRecord`s) is the
-accounting journal. Enforce balance through the existing per-asset conservation
-check. Capture the terminology in `accounting-mapping.md` and `journaling.md`.
+State three things. A committed `Transfer`, resolved into an `Envelope`, is a
+journal entry. A `Transfer` with several `Movement`s is a compound journal
+entry. The transfer log, a `TransferStore` of `EnvelopeRecord`s, is the
+accounting journal.
+
+Enforce the balance through the per-asset conservation check that exists. Record
+the terminology in `accounting-mapping.md` and in `journaling.md`.
 
 **Pros:**
 
-* No new types; the intent API (ADR-0005) and transfer log already provide the
-  grain (one entry) and the collection (the journal).
-* Compound and multi-asset entries fall out for free: a transfer is already a
-  list of movements, and conservation is already per asset.
-* Auditability is already structural: replaying the log reconstructs balances,
-  and content-addressed ids give tamper evidence.
+* Good, because it needs no new type. The intent API (ADR-0005) gives the grain,
+  which is one entry, and the transfer log gives the collection, which is the
+  journal.
+* Good, because a compound entry and a multi-asset entry both come free. A
+  transfer is a list of movements already, and conservation is per asset
+  already.
+* Good, because auditability is structural already. A replay of the log
+  reconstructs the balances, and a content-addressed id gives tamper evidence.
 
 **Cons:**
 
-* The word "posting" is a noun in Kuatia (a value fragment) but a verb in
-  classical accounting (the act of recording), a collision that must be called
-  out.
-* `Book` keeps a name that suggests "accounting book"; the docs must repeatedly
-  disclaim it.
+* Bad, because the word "posting" is a noun in Kuatia, a value fragment, and a
+  verb in classical accounting, the act of a record. The documents must name
+  that collision.
+* Bad, because `Book` keeps a name that suggests an accounting book. The
+  documents must disclaim it again and again.
 
 #### Option 2: Add explicit `Journal` and `JournalEntry` types
 
-Introduce dedicated types that wrap the transfer log and a committed transfer.
+Add dedicated types that wrap the transfer log and a committed transfer.
 
 **Pros:**
 
-* The vocabulary is present in the type system, not only in prose.
+* Good, because the vocabulary sits in the type system and not in prose alone.
 
 **Cons:**
 
-* Pure duplication: `JournalEntry` would be a `Transfer`/`Envelope`, `Journal`
-  would be `TransferStore`. Two names for one concept invites drift.
-* A dedicated debit/credit line type would fight the UTXO model, where the
-  primitive is a signed posting, not a one-sided debit or credit line.
+* Bad, because it is pure duplication. `JournalEntry` is a `Transfer` or an
+  `Envelope`, and `Journal` is a `TransferStore`. Two names for one concept
+  invite drift.
+* Bad, because a dedicated debit or credit line type fights the UTXO model. In
+  that model the primitive is a signed posting and not a one-sided line.
 
 #### Option 3: Rename `Book` to something journal-adjacent
 
-Rename `Book` to reduce the accounting-book confusion.
+Rename `Book`, to reduce the confusion with an accounting book.
 
 **Pros:**
 
-* Removes one source of naming conflation.
+* Good, because it removes one source of confusion in the names.
 
 **Cons:**
 
-* `Book` is a transfer policy scope, not a journal; a journal-adjacent name
-  would make the confusion worse, not better. The fix is documentation, not a
-  rename.
+* Bad, because `Book` is a transfer policy scope and not a journal. A name close
+  to "journal" makes the confusion worse rather than better. The fix is
+  documentation and not a rename.
 
 ## Decision Outcome
 
-Chosen option: Option 1. Model journaling with the existing types and document
-the mapping. A committed `Transfer` resolved into an `Envelope` is a journal
-entry; a `Transfer` with multiple `Movement`s is a compound journal entry; the
-transfer log is the accounting journal. Per-asset conservation
-(`sum(consumed) == sum(created)`, enforced in `validate_and_plan`) is the
-equivalent of `Σ debits = Σ credits`. `Book` is a transfer policy scope, not the
-journal, not a journal entry, and not a balance partition. The event log
-(ADR-0010) is for lifecycle notifications and is not the journal.
+Chosen option: Option 1. Model journaling with the types that exist, and
+document the mapping.
+
+A committed `Transfer`, resolved into an `Envelope`, is a journal entry. A
+`Transfer` with several `Movement`s is a compound journal entry. The transfer
+log is the accounting journal.
+
+Per-asset conservation is the equivalent of `Σ debits = Σ credits`. It is
+`sum(consumed) == sum(created)`, and `validate_and_plan` enforces it.
+
+`Book` is a transfer policy scope. It is not the journal, not a journal entry
+and not a balance partition. The event log (ADR-0010) carries lifecycle
+notifications, and it is not the journal.
 
 ### Positive Consequences
 
-* Journaling, including compound and multi-asset entries, is supported with no
-  new types and no schema change.
-* The journal is auditable by replay and tamper-evident by construction.
-* The naming pitfalls (`Book` vs. journal, posting-noun vs. posting-verb,
-  transfer log vs. event log) are documented in one place.
+* The ledger supports journaling, and that covers a compound entry and a
+  multi-asset entry. It needs no new type and no schema change.
+* A replay audits the journal, and the journal is tamper-evident by
+  construction.
+* One place documents the traps in the names. Those are `Book` against the
+  journal, "posting" as a noun against "posting" as a verb, and the transfer log
+  against the event log.
 
 ### Negative Consequences
 
-* The vocabulary lives in documentation rather than in the type system, so it
-  relies on `journaling.md` and `accounting-mapping.md` staying accurate.
-* `Book` retains a name that needs a standing disclaimer.
+* The vocabulary lives in the documentation and not in the type system. So it
+  depends on `journaling.md` and `accounting-mapping.md`, and both must stay
+  accurate.
+* `Book` keeps a name that needs a disclaimer in every document that uses it.
 
 ## Links
 
 * Documented by [journaling.md](../journaling.md) and
   [accounting-mapping.md](../accounting-mapping.md)
-* Builds on [ADR-0001](0001-modified-utxo-signed-postings.md) (value as signed
-  postings, conservation is structural)
-* Builds on [ADR-0005](0005-intent-api-movements-vs-envelopes.md) (a `Transfer`
-  is intent resolved into an `Envelope`)
-* Relates to [ADR-0010](0010-event-stream-vs-transfer-log.md) (the event stream
-  is not the journal)
+* Builds on [ADR-0001](0001-modified-utxo-signed-postings.md), where value is
+  signed postings and conservation is structural
+* Builds on [ADR-0005](0005-intent-api-movements-vs-envelopes.md), where a
+  `Transfer` is intent that resolves into an `Envelope`
+* Relates to [ADR-0010](0010-event-stream-vs-transfer-log.md), which says the
+  event stream is not the journal

+ 164 - 152
doc/adr/0014-inflight-holds-via-holding-accounts.md

@@ -1,10 +1,9 @@
 # Inflight holds via per-destination holding accounts
 
-> Revised by [ADR-0012](0012-subaccounts.md): a hold is now a
-> **subaccount** of its destination rather than a standalone account, and the
-> "one open inflight per account" rule is dropped (a destination hosts many
-> concurrent inflights, one per distinct trade). The rest of this ADR still
-> holds.
+> Revised by [ADR-0012](0012-subaccounts.md). A hold is now a **subaccount** of
+> its destination, and not a standalone account. The "one open inflight per
+> account" rule is dropped, because a destination hosts many concurrent
+> inflights, one per distinct trade. The rest of this record still holds.
 
 * Status: accepted
 * Authors: Cesar Rodas
@@ -14,10 +13,10 @@
 
 ## Context and Problem Statement
 
-Callers need to reserve funds for a trade without settling it yet: authorize the
-whole trade now, then later confirm it (in full or in parts) or void it. This is
-the authorization/capture pattern, applied to a multi-leg trade rather than a
-single payment. A confirmed trade like
+A caller needs to reserve funds for a trade, and to settle it later. The caller
+authorizes the whole trade now, then confirms it (in full or in parts) or voids
+it. This is the authorization/capture pattern, applied to a multi-leg trade
+rather than a single payment. A confirmed trade like
 
 ```
 A -> B   -> 100 EUR
@@ -26,77 +25,81 @@ A -> fee -> 0.0001 BTC
 B -> fee -> 1 EUR
 ```
 
-should be expressible in an inflight form where the funds leave the payers now
-but are parked until each leg is confirmed or returned.
+must be expressible in an inflight form, where the funds leave the payers now
+and are parked until each leg is confirmed or returned.
 
-The tension is with the ledger's core model. Kuatia is append-only and
-UTXO-style: value is signed postings that move between accounts, balances are
-derived (never stored), and there is no mutable state to update in place. The
-only reservation concept today is the transient `PendingInactive` posting status
-stamped with a `ReservationId`. That is a short-lived concurrency primitive owned
-by a single in-flight saga, not a durable, user-facing hold. Recovery
-(`Ledger::recover`) treats any `PendingInactive` posting as a saga to complete or
-release, and a hold can stay open far longer than a saga.
+The tension is with the core model of the ledger. Kuatia is append-only and
+UTXO-style. Value is signed postings that move between accounts, a balance is
+derived and never stored, and there is no mutable state to update in place.
 
-A further constraint: this must use the existing storage. No new `Store`
-sub-trait and no migration. The accounts table and the transactions table have to
-carry everything.
+The only reservation concept today is the transient `PendingInactive` posting
+status, stamped with a `ReservationId`. That is a short-lived concurrency
+primitive owned by a single in-flight saga, and not a durable hold that a user
+sees. Recovery (`Ledger::recover`) treats any `PendingInactive` posting as a
+saga to complete or release, and a hold can stay open far longer than a saga.
 
-How do we represent a durable, partially-confirmable, multi-leg reservation
-without adding mutable state, a parallel recovery mechanism, a new store, or
-domain logic in the storage layer?
+One more constraint: this must use the storage that exists. No new `Store`
+sub-trait and no migration. The accounts table and the transactions table have
+to carry everything.
+
+How does the ledger represent a durable, partially-confirmable, multi-leg
+reservation? It must add no mutable state, no parallel recovery mechanism, no
+new store, and no domain logic in the storage layer.
 
 ## Decision Drivers
 
 * **Append-only**: a hold must be a durable fact recorded in the ledger, not a
   lock held in memory or a transient status.
-* **Reuse the commit path**: authorize, confirm, and void should ride the
-  existing content-addressed, idempotent, crash-safe `commit_envelope` saga and
-  its `recover()` roll-forward, not a second bespoke mechanism.
+* **Reuse the commit path**: authorize, confirm and void must ride the
+  content-addressed, idempotent, crash-safe `commit_envelope` saga that exists,
+  and its `recover()` roll-forward. Not a second bespoke mechanism.
 * **No mutable balance / derive, don't store**: the amount still held must be a
   derived balance, not a counter decremented on each confirmation.
-* **Existing storage only**: state lives in the accounts and transactions tables.
-  No new store, no migration, no arithmetic pushed into SQL.
-* **Self-describing via metadata**: the inflight facts (the transaction id, the
-  leg table, the role of each transfer, the funder per leg) are carried in the
-  metadata of the holding accounts and the transfers, so the lifecycle is read
-  from recorded fields rather than inferred from movement direction.
-* **Safety by construction**: no double-spend, and no confirming more than was
-  authorized, enforced by existing invariants rather than new guards.
-* **Auditability and simplicity**: the full history of a request should be
-  readable from the ledger, and the feature should add as little surface as
-  possible.
+* **The storage that exists, and nothing more**: state lives in the accounts and
+  transactions tables. No new store, no migration, no arithmetic pushed into
+  SQL.
+* **Self-describing via metadata**: the metadata of the holding accounts and the
+  transfers carries the inflight facts. Those are the transaction id, the leg
+  table, the role of each transfer and the funder per leg. So a reader takes the
+  lifecycle from recorded fields, and infers nothing from movement direction.
+* **Safety by construction**: no double-spend, and no confirm of more than the
+  authorized amount. The invariants that exist enforce both, and no new guard
+  does.
+* **Auditability and simplicity**: a reader must be able to read the full
+  history of a request from the ledger. The feature must also add the least
+  surface it can.
 
 ## Considered Options
 
 #### Option 1: Promote the transient `PendingInactive` reservation to a durable hold
 
 Keep the payers' postings in place and hold them as `PendingInactive` for the
-whole authorization window. Available balance already excludes `PendingInactive`,
-so the funds would look reserved.
+whole authorization window. Available balance already excludes
+`PendingInactive`, so the funds would look reserved.
 
 **Pros:**
 
-* Good, because it reuses the existing reservation stamp and moves no funds.
+* Good, because it reuses the reservation stamp that exists, and moves no funds.
 * Good, because the available-vs-ledger balance split already models "reserved
   but not spent."
 
 **Cons:**
 
-* Bad, because it breaks recovery: `recover()` treats every `PendingInactive`
-  posting as an in-flight saga to roll forward or release, so a durable hold would
-  be torn down or double-driven by the first startup recovery pass.
+* Bad, because it breaks recovery. `recover()` treats every `PendingInactive`
+  posting as an in-flight saga to roll forward or release. So the first startup
+  recovery pass tears a durable hold down, or drives it twice.
 * Bad, because a reservation is all-or-nothing on a whole posting. Partial
-  confirmation has no representation, and there is nowhere to keep the change from
-  a partial confirmation.
-* Bad, because it conflates a short-lived concurrency primitive with a long-lived
-  business state, and pins postings under a saga-owned lock for an unbounded time.
+  confirmation has no representation, and there is nowhere to keep the change
+  from a partial confirmation.
+* Bad, because it conflates a short-lived concurrency primitive with a
+  long-lived business state, and pins postings under a saga-owned lock for an
+  unbounded time.
 
 #### Option 2: Add a new posting state (`Held`) for reserved funds
 
-Introduce a fourth posting status that keeps funds attached to the payer but
-marks them reserved for a specific request, with a new primitive to split a held
-posting on partial confirmation.
+Introduce a fourth posting status. It keeps funds attached to the payer, and
+marks them reserved for a specific request. A new primitive splits a held
+posting on a partial confirmation.
 
 **Pros:**
 
@@ -105,17 +108,17 @@ posting on partial confirmation.
 
 **Cons:**
 
-* Bad, because a new state touches every layer: the balance rule, validation, the
-  store trait and both backends, recovery, and the whole conformance suite.
-* Bad, because partial confirmation forces a posting-splitting primitive, which is
-  new domain logic pushed back toward the store.
+* Bad, because a new state touches every layer: the balance rule, validation,
+  the store trait and both backends, recovery, and the whole conformance suite.
+* Bad, because partial confirmation forces a primitive that splits a posting,
+  which is new domain logic pushed back toward the store.
 * Bad, because it grows a special case into a model whose whole point is that
-  value is just postings moving between accounts. Larger surface, higher risk.
+  value is postings that move between accounts. Larger surface, higher risk.
 
 #### Option 3: Rewrite each destination to a per-destination holding account (chosen)
 
-Model an inflight transaction as the ordinary trade with every destination
-`to` rewritten to a fresh holding account created for that destination:
+Model an inflight transaction as the ordinary trade with every destination `to`
+rewritten to a fresh holding account created for that destination:
 
 ```
 A -> B.inflight   -> 100 EUR
@@ -124,18 +127,21 @@ A -> fee.inflight -> 0.0001 BTC
 B -> fee.inflight -> 1 EUR
 ```
 
-Committing that rewritten transfer is the authorize step: one atomic,
-conservation-preserving commit moves the funds out of A and B into the holding
-accounts. That commit is stored in the transactions table like any other, and its
-content-addressed `EnvelopeId` is the inflight handle. The metadata carries the
-record across every artifact: the authorize transfer's metadata declares its role
-and the full leg table `[(destination, hold, funder, asset, amount)]`; each
-holding account's metadata records its role and its destination; each later
-confirm or void transfer's metadata records its role, the inflight handle, and the
-leg it settles. The metadata is therefore the record of what is held and for whom,
-and it is content-addressed into each transfer's id, so it is tamper-evident. A
-hold is keyed by destination,
-so `fee.inflight` legitimately holds two assets funded by two different accounts.
+A commit of that rewritten transfer is the authorize step. One atomic commit
+moves the funds out of A and B into the holding accounts, and it conserves
+value. That commit is stored in the transactions table like any other, and its
+content-addressed `EnvelopeId` is the inflight handle.
+
+The metadata carries the record across every artifact. The metadata of the
+authorize transfer declares its role and the full leg table
+`[(destination, hold, funder, asset, amount)]`. The metadata of each holding
+account records its role and its destination. The metadata of each later confirm
+or void transfer records its role, the inflight handle, and the leg it settles.
+So the metadata is the record of what is held and for whom. It is
+content-addressed into the id of each transfer, which makes it tamper-evident.
+
+A hold is keyed by destination, so `fee.inflight` legitimately holds two assets
+funded by two different accounts.
 
 The lifecycle operations are ordinary commits, each driven from the leg table in
 the authorize transfer's metadata:
@@ -144,101 +150,104 @@ the authorize transfer's metadata:
   to its destination. The net effect equals the original confirmed trade.
 * **Partial confirm**: commit `X.inflight -> X` for a slice. The remainder stays
   held.
-* **Void**: for each leg, return the holding account's remaining balance to the
+* **Void**: for each leg, return what the holding account still holds to the
   funder named in the leg table.
 
-A hold closes when its balance reaches zero; the transaction is terminal when all
-its holds are closed. Whether a leg was confirmed or voided is read from the
-transactions table (the leg's settling transfer goes to the destination on
-confirm, to the funder on void).
+A hold closes when its balance reaches zero; the transaction is terminal when
+all its holds are closed. A reader takes a confirm or a void from the
+transactions table. The settling transfer of the leg goes to the destination on
+a confirm, and to the funder on a void.
 
 Each hold is a **subaccount** of its destination, keyed by a value derived from
-the submitted trade. Because the key is trade-specific, a destination hosts
-**many concurrent inflights at once**, one per distinct trade, each isolated in
-its own subaccount. Re-authorizing the identical trade collides with its own
-existing holds and is rejected, while different trades to the same destination
-run side by side.
+the submitted trade. The key is trade-specific, so a destination hosts **many
+concurrent inflights at once**, one per distinct trade, each isolated in its own
+subaccount. A second authorize of the identical trade collides with the holds
+that trade already has, and the ledger rejects it. Different trades to the same
+destination run side by side.
 
 **Pros:**
 
 * Good, because it adds no posting state, no saga phase, no new store, and no
-  migration. Every operation is an existing `commit`, so idempotency, content
-  addressing, and crash recovery are inherited unchanged.
-* Good, because the amount still held is the holding account's balance, a derived
-  value. Nothing mutable is stored or decremented.
-* Good, because partial confirmation is just another transfer, with change handled
-  by the normal resolve step.
-* Good, because over-confirmation is impossible by construction: the holding
-  account is `NoOverdraft`, so a confirmation exceeding its balance fails
-  validation. The sum of confirmations can never exceed the authorized amount.
-* Good, because concurrent confirmations serialize on the shared holding posting
-  via the reservation protocol, so double-spend safety and the over-confirm bound
-  hold under contention with no new locking.
-* Good, because void routing reads the funder from the stored authorize transfer,
-  so it needs no change to `resolve()` and no reliance on posting provenance.
+  migration. Every operation is a `commit` that exists, so it inherits
+  idempotency, the content address and crash recovery unchanged.
+* Good, because the amount still held is the holding account's balance, a
+  derived value. Nothing mutable is stored or decremented.
+* Good, because partial confirmation is just another transfer, with change
+  handled by the normal resolve step.
+* Good, because over-confirmation is impossible by construction. The holding
+  account is `NoOverdraft`, so a confirmation of more than its balance fails
+  validation. The sum of the confirmations can never exceed the authorized
+  amount.
+* Good, because concurrent confirmations serialize on the shared holding
+  posting, through the reservation protocol. So double-spend safety and the
+  over-confirm bound hold under contention, with no new lock.
+* Good, because a void reads the funder from the stored authorize transfer. It
+  needs no change to `resolve()`, and it does not depend on posting provenance.
 * Good, because the request's entire history is the holds and the transactions
   that touch them: the authorize, each confirmation, and the void.
 
 **Cons:**
 
-* Bad, because it creates one holding account per destination per request.
-  Mitigated by closing terminal holds so they leave the working set. Accounts are
-  cheap, snowflake-keyed rows.
+* Bad, because it creates one holding account per destination per request. A
+  close of a terminal hold takes it out of the working set, which mitigates
+  that. Accounts are cheap, snowflake-keyed rows.
 * Bad, because a single `(hold, asset)` co-funded by two payers cannot cleanly
-  split a partially-confirmed remainder back to each funder on void; out of scope,
-  documented. Each `(destination, asset)` is expected to have a single funder, as
-  in the example.
-* Bad, because voiding returns funds to the original payer, so that account must
+  split a partly confirmed remainder back to each funder on a void. Out of
+  scope, documented. Each `(destination, asset)` is expected to have a single
+  funder, as in the example.
+* Bad, because a void returns funds to the original payer, so that account must
   still be open to receive them.
 
 ## Decision Outcome
 
-Chosen option: **Option 3, per-destination holding accounts, backed by existing
-storage**, because it is the only option that expresses a durable,
-partially-confirmable, multi-leg hold purely as existing ledger primitives, with
-no new store. It adds no mutable state, reuses the commit and recovery path
-wholesale, and gets double-spend and over-confirm safety from invariants the
-ledger already enforces. Concretely:
-
-* **Authorize rewrites destinations.** For an inflight transaction, each movement
-  `from -> to` becomes `from -> hold(to)`, where `hold(to)` is a fresh
-  `NoOverdraft` account flagged `INFLIGHT` whose metadata records its destination.
-  The rewritten transfer is committed normally with the leg table in its metadata,
-  and its content-addressed `EnvelopeId` becomes the inflight handle.
+Chosen option: **Option 3, per-destination holding accounts, backed by the
+storage that exists**. It is the only option that expresses a durable,
+partially-confirmable, multi-leg hold purely as ledger primitives that already
+exist, with no new store. It adds no mutable state and reuses the commit and
+recovery path whole. It takes double-spend and over-confirm safety from
+invariants the ledger already enforces. Concretely:
+
+* **Authorize rewrites destinations.** For an inflight transaction, each
+  movement `from -> to` becomes `from -> hold(to)`, where `hold(to)` is a fresh
+  `NoOverdraft` account flagged `INFLIGHT` whose metadata records its
+  destination. The rewritten transfer is committed normally with the leg table
+  in its metadata, and its content-addressed `EnvelopeId` becomes the inflight
+  handle.
 * **Metadata is the record.** Confirm and void load the authorize transfer with
-  `get_transfer` / `get_transfers_for_account` and read the leg table and funders
-  straight from its metadata, rather than reconstructing them from movement
-  directions. No side record and no new store. Because each hold is a subaccount
-  of its destination (sharing its base id), `get_transfers_for_account` on the
-  destination's base id surfaces its open holds without a side index.
+  `get_transfer` / `get_transfers_for_account`. They read the leg table and the
+  funders straight from its metadata, and they reconstruct nothing from movement
+  directions. No side record and no new store. Each hold is a subaccount of its
+  destination and shares its base id. So `get_transfers_for_account` on the base
+  id of the destination surfaces its open holds with no side index.
 * **Confirm and void are ordinary transfers, tagged in metadata.** Confirm-all
-  commits `hold -> destination` for each leg's balance; partial confirm commits
-  `hold -> destination` for a slice; void commits `hold -> funder` per leg, with
-  the funder taken from the leg table. Each settling transfer carries its role
-  (`confirm` or `void`), the inflight handle, and the leg it settles in metadata.
-  All go through `commit`, so all are idempotent and crash-safe. Confirm accepts a
-  batch of legs to settle in one call, expressed with the same
-  `(from, to, asset, amount)` shape as `TransferBuilder::pay` (`from` the funder,
-  `to` the destination); the movements settle in order, each its own commit, so a
-  batch is not atomic.
+  commits `hold -> destination` for the balance of each leg. A partial confirm
+  commits `hold -> destination` for a slice. A void commits `hold -> funder` per
+  leg, with the funder taken from the leg table. Each settling transfer carries
+  its role (`confirm` or `void`), the inflight handle, and the leg it settles in
+  metadata. All go through `commit`, so all are idempotent and crash-safe.
+
+  Confirm accepts a batch of legs to settle in one call. A leg takes the same
+  `(from, to, asset, amount)` shape as `TransferBuilder::pay`, with `from` the
+  funder and `to` the destination. The movements settle in order, each in its
+  own commit, so a batch is not atomic.
 * **State is derived.** The amount held on a leg is `balance(hold, asset)`. The
   authorized amount is the leg's amount in the metadata leg table. Confirmed is
   authorized minus held. Whether a leg was confirmed or voided is read from the
   role tag on its settling transfer, not inferred from where the funds went.
 * **Termination closes the holds.** When a hold balance reaches zero, close it
-  (legal, since it then has zero active postings). The inflight transaction is done
-  when all its holds are closed.
+  (legal, since it then has zero active postings). The inflight transaction is
+  done when all its holds are closed.
 
-Because void reads the funder from the leg table in metadata rather than from
-posting provenance, `resolve()` is left unchanged (the change posting keeps its
-current `payer: None`).
+A void reads the funder from the leg table in metadata, and not from posting
+provenance. So `resolve()` is left unchanged, and the change posting keeps its
+current `payer: None`.
 
 ### Inflight metadata schema
 
-The payload is a single CBOR-encoded tagged enum stored under one `inflight` key
-in the existing `Metadata` map (`BTreeMap<String, Vec<u8>>`), via `ciborium`.
-This supersedes the earlier per-key big-endian byte layout: one typed value
-instead of hand-packed fields.
+The payload is a single CBOR-encoded tagged enum, stored under one `inflight`
+key in the `Metadata` map that exists (`BTreeMap<String, Vec<u8>>`), through
+`ciborium`. This supersedes the earlier per-key big-endian byte layout: one
+typed value instead of hand-packed fields.
 
 ```rust
 enum InflightMeta {
@@ -253,21 +262,24 @@ Each `InflightLeg` is `{ destination, hold, funder, asset, amount }`. The
 inflight handle is the authorize transfer's content-addressed `EnvelopeId`; the
 `tx` field on a settling transfer back-references it.
 
-Open holds are discovered by scanning `INFLIGHT`-flagged, not-closed accounts and
-reading their `Hold` metadata; the flag is the marker (metadata is carried, not
-queried). Everything semantic (leg table, funders, per-transfer role) is read
-from the enum. Because metadata is hashed as opaque bytes into each transfer id,
-the payload is tamper-evident; `ciborium` is deterministic for a fixed value.
+A scan of the `INFLIGHT`-flagged, not-closed accounts finds the open holds, and
+a read of their `Hold` metadata names them. The flag is the marker, because
+metadata is carried and not queried. Everything semantic (leg table, funders,
+per-transfer role) is read from the enum. Metadata is hashed as opaque bytes
+into each transfer id, so the payload is tamper-evident. `ciborium` is
+deterministic for a fixed value.
 
 ### Positive Consequences
 
 * The feature is a thin layer over `commit`, `create_account`, `get_transfer`,
   `balance`, and `close`. Crash recovery, idempotency, and conservation come for
   free, and no storage schema changes.
-* The over-confirm bound and double-spend safety are structural: they follow from
-  `NoOverdraft` and the reservation protocol, with no request-specific checks.
-* The audit trail is self-describing: a request's holds and the transactions that
-  touch them fully reconstruct what was authorized, confirmed, and returned.
+* The over-confirm bound and double-spend safety are structural: they follow
+  from `NoOverdraft` and the reservation protocol, with no request-specific
+  checks.
+* The audit trail is self-describing: a request's holds and the transactions
+  that touch them fully reconstruct what was authorized, confirmed, and
+  returned.
 
 ### Negative Consequences
 
@@ -276,16 +288,16 @@ the payload is tamper-evident; `ciborium` is deterministic for a fixed value.
   (as postings and transfers already do).
 * A single `(hold, asset)` co-funded by two payers has an ambiguous
   partially-confirmed remainder on void; out of scope, documented.
-* Voiding depends on the payer account remaining open. A policy for holds that
-  outlive their payer is out of scope here.
+* A void depends on the payer account, and that account must stay open. A policy
+  for a hold that outlives its payer is out of scope here.
 
 ## Links
 
 * Builds on [ADR-0001](0001-modified-utxo-signed-postings.md) (signed postings)
   and [ADR-0003](0003-dumb-storage-saga-recovery.md) (dumb storage, saga
-  recovery). Reuses the `commit_envelope` path and `recover()` unchanged, and adds
-  no new store.
+  recovery). Reuses the `commit_envelope` path and `recover()` unchanged, and
+  adds no new store.
 * Background: [architecture.md](../architecture.md) (commit pipeline, posting
-  lifecycle, resolve and change outputs), [accounts.md](../accounts.md) (policies,
-  account lifecycle).
+  lifecycle, resolve and change outputs), [accounts.md](../accounts.md)
+  (policies, account lifecycle).
 * Usage and API to be documented in `doc/inflight.md`.

+ 89 - 77
doc/adr/0015-fixed-width-account-code.md

@@ -9,141 +9,153 @@
 
 ## Context and Problem Statement
 
-ADR-0012 gave `AccountId` an IBAN-style string form: two leading mod-97 check
-digits and a 26-character base-36 body, 28 characters in total. The body encoded
-both `i64` legs at full width (a 128-bit Feistel permutation, then 13 base-36
-characters per 64-bit half). 28 characters is long to read, transcribe, or speak,
-and it does not group evenly, so the presentation form was more awkward than an
+ADR-0012 gave `AccountId` an IBAN-style string form. It was two mod-97 check
+digits at the front and a 26-character base-36 body, so 28 characters in total.
+The body encoded both `i64` legs at full width, through a 128-bit Feistel
+permutation and then 13 base-36 characters per 64-bit half.
+
+28 characters is long. It is long to read, long to transcribe and long to speak.
+It also does not group evenly. So the presentation form was more awkward than an
 IBAN or a card number.
 
-The length is driven by encoding two full 64-bit values. Can the code be
-materially shorter while keeping the checksum, the obfuscation, and round-trip
-parsing?
+The length comes from the encode of two full 64-bit values. So can the code be
+much shorter, and still keep the checksum, the obfuscation and a parse that
+round-trips?
 
 ## Decision Drivers
 
-* **Shorter, evenly grouped**: the human-facing code should be short and group
-  cleanly (an IBAN/card-number feel), not an odd-length 28.
+* **Shorter, and evenly grouped**: the code a person sees must be short, and it
+  must group cleanly, like an IBAN or a card number. 28 is an odd length.
 * **Keep the checksum**: a mistyped id must still be rejected before it reaches
   the store.
-* **Keep the obfuscation**: sequential ids must not produce visibly related
-  codes, and a base account and its subaccount must not share a prefix.
-* **No storage or content-hash impact**: the change is presentation-only;
-  `ToBytes`, serde, the SQL schema, and every content hash keep the two full
-  `i64` legs, so there is no migration.
+* **Keep the obfuscation**: two ids in sequence must not produce two codes that
+  look related. A base account and its subaccount must not share a prefix.
+* **No effect on storage and no effect on a content hash**: the change touches
+  the presentation alone. `ToBytes`, serde, the SQL schema and every content
+  hash keep the two full `i64` legs, so there is no migration.
 
 ## Considered Options
 
 #### Option 1: Fixed 20 characters, an 18-char body plus two trailing check digits (chosen)
 
-Pack the base id (63 bits, since a snowflake never sets the sign bit) and the
-subaccount (30 bits) into one 93-bit value, permute it, and base-36 encode it in
-18 characters, then append two mod-97 check digits. `36^18 > 2^93`, so 18
-characters always fit. Total 20 characters, five groups of four.
+Pack the base id and the subaccount into one 93-bit value. The base id takes 63
+bits, because a snowflake never sets the sign bit, and the subaccount takes 30.
+Permute that value, then encode it in 18 base-36 characters, then append two
+mod-97 check digits.
+
+`36^18 > 2^93`, so 18 characters always fit. The total is 20 characters, in five
+groups of four.
 
 **Pros:**
 
-* Good, because 20 characters group evenly into five blocks of four, reading like
-  an IBAN or a card number.
-* Good, because it keeps the mod-97 checksum and the keyed obfuscation, so
-  mistyped ids are still rejected and codes still look unrelated.
-* Good, because storage and content hashes are untouched (still two full `i64`
-  legs), so there is no migration, exactly as in ADR-0012.
+* Good, because 20 characters group evenly into five blocks of four. The code
+  then reads like an IBAN or a card number.
+* Good, because it keeps the mod-97 checksum and the keyed obfuscation. So the
+  parse still rejects a mistyped id, and two codes still look unrelated.
+* Good, because nothing touches the storage or a content hash. Both still hold
+  two full `i64` legs. So there is no migration, exactly as in ADR-0012.
 
 **Cons:**
 
-* Bad, because the subaccount now encodes only 30 bits, so a subaccount id must
-  fit in that range to round-trip through the string form. Hash-derived inflight
-  subaccounts (ADR-0014) must be masked to 30 bits, which raises their collision
-  domain (see Negative Consequences).
-* Bad, because the string form is now lossy for out-of-range legs: an `id`
-  beyond 63 bits or a `sub` beyond 30 bits truncates rather than round-trips. All
-  real ids (snowflake `id`, masked inflight `sub`, small explicit buckets) are in
-  range.
+* Bad, because the subaccount now encodes 30 bits alone. A subaccount id must
+  fit that range to round-trip through the string form. An inflight subaccount
+  that comes from a hash (ADR-0014) needs a mask to 30 bits, which raises its
+  collision domain. See the Negative Consequences.
+* Bad, because the string form now loses a leg that falls outside its range. An
+  `id` past 63 bits, or a `sub` past 30 bits, truncates rather than round-trips.
+  Every real id is inside the range, and those are a snowflake `id`, a masked
+  inflight `sub`, and a small explicit bucket.
 
 #### Option 2: Keep 28 characters
 
-Leave the ADR-0012 form unchanged.
+Leave the form of ADR-0012 as it is.
 
 **Pros:**
 
-* Good, because it round-trips the entire `(i64, i64)` space and needs no change.
+* Good, because it round-trips the whole `(i64, i64)` space and needs no change.
 
 **Cons:**
 
-* Bad, because 28 characters is long and does not group evenly, which was the
+* Bad, because 28 characters is long and does not group evenly. That was the
   complaint.
 
 #### Option 3: Variable-length (main account short, subaccount long)
 
-Encode only the id leg when `sub == 0` (about 15 characters) and both legs
-otherwise (about 21).
+Encode the id leg alone when `sub == 0`, which takes about 15 characters. Encode
+both legs otherwise, which takes about 21.
 
 **Pros:**
 
-* Good, because a main account, the common case, becomes very short with no range
-  loss on either leg.
+* Good, because a main account is the common case, and it becomes very short.
+  Neither leg loses range.
 
 **Cons:**
 
-* Bad, because codes then have two different lengths, which reads less like a
-  uniform account number and complicates any fixed-width UI or validation.
-* Bad, because 15 is not a clean multiple of four, so the grouping is uneven.
+* Bad, because a code then has one of two lengths. That reads less like a
+  uniform account number, and it complicates a fixed-width UI and a fixed-width
+  validation.
+* Bad, because 15 is not a clean multiple of four, so the groups are uneven.
 
 ## Decision Outcome
 
-Chosen option: **Option 1, a fixed 20-character code**, because it is short, groups
-into a uniform five-by-four, keeps the checksum and the obfuscation, and stays
-presentation-only with no migration. The only real cost is capping the subaccount
-at 30 bits, which is ample for explicit buckets and acceptable for the
-hash-derived inflight subaccounts.
+Chosen option: **Option 1, a fixed 20-character code**. It is short. It groups
+into a uniform five by four. It keeps the checksum and the obfuscation. It
+touches the presentation alone, so there is no migration.
+
+The one real cost is the cap on the subaccount at 30 bits. That is ample for an
+explicit bucket, and acceptable for an inflight subaccount that comes from a
+hash.
 
 ### The encoding
 
-* Constants `ID_BITS = 63` and `SUB_BITS = 30` (93 bits packed) are public on
-  `kuatia-types`. `pack` places the low `ID_BITS` of `id` above the low
-  `SUB_BITS` of `sub`; `unpack` inverts it.
-* Obfuscation is a keyed format-preserving permutation over the 93-bit domain: a
-  Feistel network over two 47-bit halves (a 94-bit block) restricted to the
-  domain by cycle-walking (re-encrypt while the result exceeds `2^93 - 1`). Since
-  the domain is half of `2^94`, this averages about two iterations and is a
-  bijection on exactly the packable values. The seed is still the global
-  `set_id_seed` key.
-* The body is 18 base-36 characters of the permuted value; the two trailing check
-  digits are the same ISO 7064 mod-97 scheme as ADR-0012, moved to the end so the
-  code is body-then-check. `FromStr` strips spaces and dashes, upper-cases,
-  requires 20 characters, validates the checksum, rejects a decoded body outside
-  the 93-bit domain, then inverts the permutation and unpacks.
+* The constants `ID_BITS = 63` and `SUB_BITS = 30` are public on `kuatia-types`,
+  and together they pack 93 bits. `pack` places the low `ID_BITS` of `id` above
+  the low `SUB_BITS` of `sub`, and `unpack` inverts it.
+* The obfuscation is a keyed format-preserving permutation over the 93-bit
+  domain. It is a Feistel network over two 47-bit halves, which is a 94-bit
+  block. A cycle walk restricts it to the domain, so it re-encrypts while the
+  result passes `2^93 - 1`. The domain is half of `2^94`, so that averages about
+  two iterations, and the permutation is a bijection over exactly the packable
+  values. The seed is still the global `set_id_seed` key.
+* The body is 18 base-36 characters of the permuted value. The two check digits
+  at the end use the same ISO 7064 mod-97 scheme as ADR-0012. They moved to the
+  end, so that the code reads as the body and then the check.
+* `FromStr` strips a space and a dash, and upper-cases the text. It then needs
+  20 characters. It validates the checksum. It rejects a decoded body outside
+  the 93-bit domain. It then inverts the permutation and unpacks.
 * Under the default seed, `AccountId { id: 5, sub: 7 }` renders
   `FK9RA6QALU15JZ7DZM81` (grouped `FK9R A6QA LU15 JZ7D ZM81`).
 
 ### Inflight subaccounts
 
 The per-destination inflight hold subaccount (ADR-0014) was a 63-bit truncation
-of a trade hash. It is now masked to the low `SUB_BITS` so every hold has an
-encodable code. It stays deterministic and trade-specific.
+of a trade hash. A mask now takes it to the low `SUB_BITS`, so every hold has a
+code the encoder accepts. It stays deterministic, and it stays specific to its
+trade.
 
 ### Positive Consequences
 
-* The human-facing code drops from 28 to 20 characters and groups evenly.
-* No storage, serde, or content-hash change; no migration. Debug output is
-  unchanged (`id` / `id.sub`).
+* The code a person sees drops from 28 characters to 20, and it groups evenly.
+* Nothing changes in the storage, in serde or in a content hash, so there is no
+  migration. The debug output is the same, as `id` and `id.sub`.
 
 ### Negative Consequences
 
-* The subaccount space is 30 bits (~1.07 billion) instead of a full `i64`.
-  Explicit buckets are unaffected; hash-derived inflight subaccounts collide
-  sooner: at 30 bits the birthday bound is roughly a 1% chance around 4,600
-  concurrent inflight trades to a single destination. Deployments with very high
-  concurrent inflight fan-in to one destination should account for this.
-* The string form is lossy for legs outside the encodable ranges; such values
-  still hash, persist, and compare correctly but do not round-trip through the
-  code. No real id source produces out-of-range legs.
+* The subaccount space is 30 bits, which is about 1.07 billion, rather than a
+  full `i64`. An explicit bucket is unaffected. An inflight subaccount that
+  comes from a hash collides sooner. At 30 bits the birthday bound is about a 1
+  per cent chance at around 4,600 concurrent inflight trades to one destination.
+  A deployment with a very high concurrent inflight fan-in to one destination
+  must account for this.
+* The string form loses a leg outside the range the encoder accepts. Such a
+  value still hashes, still persists and still compares correctly, and it does
+  not round-trip through the code. No real source of an id produces a leg
+  outside the range.
 
 ## Links
 
 * Supersedes the IBAN-style account code section of
-  [ADR-0012](0012-subaccounts.md); the rest of ADR-0012 (the identity model,
-  reads, balances) stands.
+  [ADR-0012](0012-subaccounts.md). The rest of ADR-0012 stands, and that is the
+  identity model, the reads and the balances.
 * Constrains the inflight hold subaccount of
   [ADR-0014](0014-inflight-holds-via-holding-accounts.md).

+ 70 - 64
doc/adr/0016-immutable-postings-index-tables.md

@@ -13,23 +13,24 @@
 ADR-0006 gave every posting a mutable `status` column
 (`Active → PendingInactive → Inactive`) plus a nullable `reservation` token,
 both flipped in place with `UPDATE`. Consumed postings stayed in the table as
-`Inactive` tombstones. That works, but it makes the postings table a
-mutate-in-place table: the commit path needs `UPDATE` rights on it, a
-historical posting's value or state can be rewritten by any code path (or any
-compromised credential) that can issue an `UPDATE`, and every "what can this
-account spend" read scans the full postings history filtered by a partial index
-on `status`, a set that only grows.
-
-The reservation protocol of ADR-0006 does not actually require the state to live
-on the posting. It requires an atomic single-winner claim, durable recoverable
-ownership, and count-returning primitives (ADR-0003). Can we keep those
-guarantees while making a posting an append-only record that is written once and
-never changed?
+`Inactive` tombstones. That works, and it also makes the postings table a
+mutate-in-place table. The commit path needs `UPDATE` rights on it. Any code
+path that can issue an `UPDATE` can rewrite the value or the state of a
+historical posting, and so can any compromised credential.
+
+Every "what can this account spend" read also scans the full postings history,
+filtered by a partial index on `status`. That set only grows.
+
+The reservation protocol of ADR-0006 does not actually need the state to live on
+the posting. It needs an atomic single-winner claim, durable recoverable
+ownership, and primitives that return a count (ADR-0003). Can the ledger keep
+those guarantees, and make a posting an append-only record that is written once
+and never changed?
 
 ## Decision Drivers
 
 * **Append-only integrity.** A posting is a fact about a committed transfer.
-  Once written it should never change, matching the append-only stance of
+  Once written it must never change. That matches the append-only stance of
   ADR-0001 (value as immutable signed postings) and ADR-0007 (undo by
   compensation, never mutation). The postings table becomes the immutable
   record; the transfer + event logs already record every create and consume.
@@ -38,12 +39,13 @@ never changed?
   `DELETE`. No path can rewrite a historical row. Lifecycle churn is confined to
   small index tables that hold ids, not monetary values.
 * **Read performance by segregation, not by partial index.** "Spendable" and
-  "live" are hot reads. Rather than scan a growing history and filter by
-  `status` (a partial index over cold and hot rows mixed together), keep the
-  working set in its own physically separate table. The index is the table.
+  "live" are hot reads. A scan of a history that grows, with a filter by
+  `status`, puts a partial index over cold and hot rows together. Keep the
+  working set in its own physically separate table instead. The index is the
+  table.
 * **Preserve ADR-0006 semantics.** Unconditional, lock-free double-spend safety;
   durable ownership that survives the multi-step saga and a crash; expressible
-  as atomic, count-returning dumb-storage instructions (ADR-0003).
+  as atomic dumb-storage instructions that return a count (ADR-0003).
 
 ## Considered Options
 
@@ -59,12 +61,13 @@ Leave postings as a mutate-in-place table with `status` + `reservation`.
 
 **Cons:**
 
-* Bad, because the commit path requires `UPDATE` on the value-bearing table, so
-  a bug or a compromised credential can rewrite historical postings.
-* Bad, because spendable/live reads scan the full, ever-growing history filtered
-  by `status`; the hot working set is never physically separated from cold
-  tombstones.
-* Bad, because the postings table is not append-only, at odds with ADR-0001/0007.
+* Bad, because the commit path needs `UPDATE` on the table that carries the
+  value. A bug or a compromised credential can then rewrite historical postings.
+* Bad, because spendable/live reads scan the full history, which grows forever,
+  filtered by `status`. The hot working set is never physically separated from
+  the cold tombstones.
+* Bad, because the postings table is not append-only, at odds with
+  ADR-0001/0007.
 
 #### Option 2: Single active table, reservation only in the write-ahead record
 
@@ -77,9 +80,9 @@ the reservation solely in the saga's write-ahead `PendingSaga` blob (ADR-0003).
 
 **Cons:**
 
-* Bad, because reserved (in-flight) postings are no longer observable in storage,
-  so balance (`Active + Reserved`) and `close` (blocks on live) change behavior,
-  and recovery cannot read "reserved by rid" from a row.
+* Bad, because reserved (in-flight) postings are no longer observable in
+  storage. So balance (`Active + Reserved`) and `close` (blocks on live) change
+  behavior, and recovery cannot read "reserved by rid" from a row.
 * Bad, because it silently alters the observable semantics ADR-0006 fixed.
 
 #### Option 3: Immutable postings + two id-only index tables
@@ -94,9 +97,9 @@ insert/delete on an index table; the posting row never changes:
 
 * Create (finalize): `INSERT` into `postings`, then `INSERT` id into
   `active_postings`.
-* Reserve: `DELETE` id from `active_postings`; if it removed a row, `INSERT`
-  id + rid into `reserved_postings`. The delete-returns-one is the atomic
-  single-winner claim.
+* Reserve: `DELETE` id from `active_postings`; if it removed a row, `INSERT` id
+  + rid into `reserved_postings`. The delete-returns-one is the atomic
+    single-winner claim.
 * Consume (finalize): `DELETE` id from `reserved_postings` where reservation =
   rid. The posting stays in `postings` forever, now in neither index = spent.
 * Release (compensation): `DELETE` from `reserved_postings`, `INSERT` back into
@@ -109,41 +112,44 @@ insert/delete on an index table; the posting row never changes:
   immutable table is the audit trail, with history also reconstructable from the
   transfer + event logs.
 * Good, because the active and reserved working sets are physically separate,
-  small, and id-only. Spendable/live reads hit a dedicated table instead of
-  scanning history behind a partial index.
-* Good, because reservation is still a single atomic claim (the delete-CAS picks
-  one winner; the loser sees zero rows), and ownership is still durable and
-  observable: `reserved_postings.reservation` records who holds a posting, so
-  recovery and finalize target only their own rows exactly as in ADR-0006.
-* Good, because it stays within dumb storage: each primitive is one conditional
-  insert/delete returning an affected-row count; the saga interprets it
-  (ADR-0003).
+  small, and id-only. Spendable/live reads hit a dedicated table and scan no
+  history behind a partial index.
+* Good, because reservation is still a single atomic claim. The delete-CAS picks
+  one winner, and the loser sees zero rows. Ownership is still durable and
+  observable, because `reserved_postings.reservation` records who holds a
+  posting. So recovery and finalize target only their own rows, exactly as in
+  ADR-0006.
+* Good, because it stays within dumb storage. Each primitive is one conditional
+  insert or delete that returns an affected-row count, and the saga interprets
+  it (ADR-0003).
 * Good, because balance (`Active ∪ Reserved`) and `close` (blocks on any live)
-  keep their exact prior semantics, now expressed as index membership instead of
+  keep their exact prior semantics. Index membership now expresses them, and not
   a `status` filter.
 
 **Cons:**
 
-* Bad, because a posting's state is no longer co-located with its data: reading
-  state is a membership probe across two tables (`get_posting_states`), and
-  three tables replace one.
-* Bad, because consuming an already-spent posting no longer surfaces as a
-  plan-time validation error; a spent posting is simply absent from the indexes,
-  so the abort moves to the reserve claim / finalize guard (same safety,
-  different surface).
+* Bad, because the state of a posting is no longer co-located with its data. A
+  read of the state is a membership probe across two tables
+  (`get_posting_states`), and three tables replace one.
+* Bad, because a consume of an already-spent posting no longer surfaces as a
+  plan-time validation error. A spent posting is simply absent from the indexes.
+  So the abort moves to the reserve claim / finalize guard, with the same safety
+  and a different surface.
 * Bad, because the schema change is forward-only (migration 004 rebuilds
   `postings` without the `status`/`reservation` columns).
 
 ## Decision Outcome
 
 Chosen option: **Option 3, immutable postings with active/reserved index
-tables**, because it keeps every guarantee of ADR-0006 (lock-free double-spend
-safety, durable recoverable ownership, count-returning primitives) while making
-the value-bearing table append-only. That buys least-privilege security (the
-commit role needs no `UPDATE` on postings, so historical rows are
-tamper-evident by construction) and read performance by segregation (the hot
-active/reserved working set lives in its own id-only tables rather than behind a
-partial index over ever-growing history).
+tables**. It keeps every guarantee of ADR-0006: lock-free double-spend safety,
+durable recoverable ownership, and primitives that return a count. It also makes
+the table that carries the value append-only.
+
+That buys least-privilege security. The commit role needs no `UPDATE` on
+postings, so historical rows are tamper-evident by construction. It also buys
+read performance by segregation. The hot active/reserved working set lives in
+its own id-only tables, and not behind a partial index over a history that grows
+forever.
 
 This supersedes the storage representation of ADR-0006. The reservation protocol
 of ADR-0006 stands; only its physical encoding changes, from an in-place
@@ -154,23 +160,23 @@ of ADR-0006 stands; only its physical encoding changes, from an in-place
 * `postings` is insert-only: grant `INSERT`, withhold `UPDATE`/`DELETE`.
 * Reserve is `DELETE FROM active_postings` as the concurrency gate; the saga
   reads the affected-row count to know it won (ADR-0003).
-* Recovery still distinguishes "reserved by this saga" (row present in
-  `reserved_postings` with our rid) from "spent" (absent from both indexes) and
-  "taken by another" (reserved by a different rid), which is what makes
-  phase-tracked roll-forward safe.
+* Recovery still tells three states apart. "reserved by this saga" is a row
+  present in `reserved_postings` with our rid. "spent" is absent from both
+  indexes, and "taken by another" is reserved by a different rid. That
+  distinction is what makes phase-tracked roll-forward safe.
 * The immutable postings table and the append-only logs can be archived or
-  pruned independently of the live working set, which partly addresses the
-  deferred retention question (README "Recommended future ADRs").
+  pruned independently of the live working set. That partly answers the deferred
+  retention question (README "Recommended future ADRs").
 
 ### Negative Consequences
 
-* Reading a posting's state is a probe across `active_postings` /
-  `reserved_postings` / `postings` rather than one column.
+* A read of the state of a posting is a probe across `active_postings` /
+  `reserved_postings` / `postings`, and not one column.
 * Three tables instead of one; ports of the store must keep the reserve claim
   (delete-from-active + insert-into-reserved) atomic.
-* No `Inactive` tombstone: a spent posting's state is "present in `postings`,
-  absent from the indexes." Consumers that read per-posting state use the
-  derived `PostingState`, not a stored column.
+* No `Inactive` tombstone. The state of a spent posting is "present in
+  `postings`, absent from the indexes". A consumer that reads per-posting state
+  uses the derived `PostingState`, and not a stored column.
 
 ## Links
 

+ 64 - 61
doc/adr/0017-correctness-first-append-only-hot-indexes.md

@@ -9,28 +9,30 @@
 
 ## Context and Problem Statement
 
-The ledger's correctness rests on never losing or corrupting value and audit
-data. Earlier decisions evolved the storage piecemeal: value as immutable signed
-postings (ADR-0001), the reservation lifecycle (ADR-0006), and moving a posting's
-lifecycle state out of a mutable column into separate tables (ADR-0016).
-Accounts followed the same append-only shape, and the separate tables later
-gained full row copies for direct reads.
-
-This ADR states the principle those changes converged on, so the *why* is
-explicit rather than implied across three ADRs: how should the schema be shaped
-so that the correctness of the ledger does not depend on trusting every write
-path to touch mutable state correctly?
+The correctness of the ledger rests on one rule: the ledger must never lose or
+corrupt value and audit data. Earlier decisions built the storage piece by
+piece. ADR-0001 made value immutable signed postings. ADR-0006 added the
+reservation lifecycle. ADR-0016 took the lifecycle state of a posting out of a
+mutable column and put it in separate tables. Accounts took the same append-only
+shape, and the separate tables later gained full row copies for direct reads.
+
+This record states the principle that those changes came to. The *why* is then
+explicit, and not implied across three records. The question is this: what shape
+must the schema have? The correctness of the ledger must not depend on the trust
+that every write path touches mutable state correctly.
 
 ## Decision Drivers
 
-* **Correctness (primary).** The source of truth must not be corruptible or
-  loseable by a bug or a mistaken write. A mistake in a fast-access structure
-  should be recoverable, not a data-loss event.
-* **Least privilege / defense in depth.** The database itself should be able to
-  reject the dangerous operations, not just the application. This is only
-  possible if the write patterns map to a small, grantable set of operations.
+* **Correctness (primary).** A bug or a mistaken write must not corrupt or lose
+  the source of truth. A mistake in a fast-access structure must be recoverable,
+  and not a data-loss event.
+* **Least privilege / defense in depth.** The database itself must be able to
+  reject the dangerous operations, and not the application alone. This is
+  possible only if the write patterns map to a small, grantable set of
+  operations.
 * **Read performance.** The common "what is spendable / what is the current
-  account" reads should hit a small, dedicated structure, not scan history.
+  account" reads must hit a small, dedicated structure, and must not scan
+  history.
 
 ## Considered Options
 
@@ -46,10 +48,10 @@ place with `UPDATE`.
 **Cons:**
 
 * Bad, because the value and audit data lives in a table that is updated in
-  place, so a bug or a compromised credential can silently rewrite or lose
-  history. Correctness depends entirely on every write path being correct.
-* Bad, because the commit role must hold `UPDATE` on the value-bearing table,
-  which cannot then be withheld as a safety net.
+  place. So a bug or a compromised credential can silently rewrite or lose
+  history. Correctness depends entirely on the correctness of every write path.
+* Bad, because the commit role must hold `UPDATE` on the table that carries the
+  value. No one can then withhold that grant as a safety net.
 
 #### Option 2: One table plus a partial index on the mutable column
 
@@ -61,9 +63,9 @@ Keep the single mutable table but add a partial index over the "live" rows.
 
 **Cons:**
 
-* Bad, because the table is still mutated in place (same correctness and
-  privilege problems as Option 1); the hot and cold rows still share one
-  ever-growing, mutable table.
+* Bad, because the table is still mutated in place, with the same correctness
+  and privilege problems as Option 1. The hot and cold rows still share one
+  mutable table that grows forever.
 
 #### Option 3: Append-only value tables plus disposable hot indexes
 
@@ -72,26 +74,26 @@ Split every entity into two kinds of table:
 * An **append-only value / audit table** that is only ever inserted into and
   never updated or deleted. This is the immutable source of truth: `postings`
   (every posting ever created), `accounts` (every account version).
-* Zero or more **disposable hot tables** that index the current / live subset for
-  fast access, maintained only by `INSERT` and `DELETE` (never `UPDATE`), and
-  fully rebuildable from the value tables: `active_postings` and
-  `reserved_postings` (the spendable / in-flight set), `account_head` (each
-  account's current version).
+* Zero or more **disposable hot tables** that index the current / live subset
+  for fast access. `INSERT` and `DELETE` alone maintain them, never `UPDATE`,
+  and the value tables rebuild them in full. They are `active_postings` and
+  `reserved_postings` (the spendable / in-flight set), and `account_head` (the
+  current version of each account).
 
-Derived state (a posting's lifecycle, an account's current version) is read from
-hot-table membership, not from a mutable column. The hot tables carry full row
-copies of the live set, so reads hit them directly without joining back to the
-value tables.
+Derived state (the lifecycle of a posting, the current version of an account) is
+read from hot-table membership, and not from a mutable column. The hot tables
+carry full row copies of the live set. So a read hits them directly and joins
+nothing back to the value tables.
 
 **Pros:**
 
-* Good, because the source of truth is append-only and therefore cannot be
-  corrupted or lost by any write path. Correctness no longer depends on trusting
-  updates to be right.
-* Good, because a bug in a disposable hot table is recoverable: the hot tables
-  are derivable from the value tables and can be dropped and rebuilt.
-* Good, because the entire write path reduces to `INSERT` and `DELETE`, which the
-  database can enforce with grants: the ledger role gets `INSERT` on the value
+* Good, because the source of truth is append-only, so no write path can corrupt
+  or lose it. Correctness no longer depends on the trust that an update is
+  right.
+* Good, because a bug in a disposable hot table is recoverable. The value tables
+  derive the hot tables, so a caller can drop a hot table and rebuild it.
+* Good, because the whole write path reduces to `INSERT` and `DELETE`, and the
+  database enforces that with grants. The ledger role gets `INSERT` on the value
   tables, `INSERT` + `DELETE` on the hot tables, and `UPDATE` on nothing. The
   margin for error is enforced below the application.
 * Good, because the hot tables are small and directly readable, so the common
@@ -108,16 +110,16 @@ value tables.
 ## Decision Outcome
 
 Chosen option: **Option 3, append-only value tables plus disposable hot
-indexes.** Correctness is the deciding driver: making the source of truth
-append-only means no write can corrupt or lose it, and confining all mutation to
-`INSERT` and `DELETE` lets the database enforce that guarantee through grants
-rather than trusting the application. The performance and least-privilege
-benefits follow from the same shape.
+indexes.** Correctness decides it. An append-only source of truth means that no
+write can corrupt or lose it. All mutation stays in `INSERT` and `DELETE`, so
+the database enforces that guarantee through grants and trusts the application
+with nothing. The performance and least-privilege benefits follow from the same
+shape.
 
-The rule going forward: value and audit data lives only in append-only tables;
-anything mutable is a disposable hot table that indexes the current or live
-subset, is maintained by `INSERT` and `DELETE` only, and can be rebuilt from the
-value tables.
+The rule from here on: value and audit data lives only in append-only tables.
+Anything mutable is a disposable hot table that indexes the current or live
+subset. `INSERT` and `DELETE` alone maintain it, and the value tables rebuild
+it.
 
 ### Positive Consequences
 
@@ -132,18 +134,19 @@ value tables.
 ### Negative Consequences
 
 * Live rows are stored twice (value table + hot table).
-* The move primitives (reserve/release/consume) own keeping the hot tables
-  consistent with the value tables.
-* Reading a single entity's state is a membership probe, not one column.
+* The move primitives (reserve/release/consume) own the consistency of the hot
+  tables against the value tables.
+* A read of the state of one entity is a membership probe, and not one column.
 
 ## Links
 
-* Generalizes and refines
-  [ADR-0016](0016-immutable-postings-index-tables.md), and supersedes its
-  "id-only" hot-table detail: the hot tables now carry full row copies so reads
-  do not merge back to the value table.
-* Builds on [ADR-0001](0001-modified-utxo-signed-postings.md) (value as immutable
-  signed postings) and [ADR-0006](0006-reservation-protocol-posting-lifecycle.md)
-  (the reservation lifecycle the hot tables encode).
+* Generalizes and refines [ADR-0016](0016-immutable-postings-index-tables.md),
+  and supersedes its "id-only" hot-table detail. The hot tables now carry full
+  row copies, so a read does not merge back to the value table.
+* Builds on [ADR-0001](0001-modified-utxo-signed-postings.md) (value as
+  immutable signed postings) and
+  [ADR-0006](0006-reservation-protocol-posting-lifecycle.md) (the reservation
+  lifecycle the hot tables encode).
 * Covers `account_head` (the current-version hot table for accounts) and the
-  set-based reserve/release/consume primitives that move rows between hot tables.
+  set-based reserve/release/consume primitives that move rows between hot
+  tables.

+ 77 - 57
doc/adr/0018-single-debit-must-not-exceed-credit-flag.md

@@ -9,27 +9,32 @@
 
 ## Context and Problem Statement
 
-[ADR-0004](0004-account-policies-overdraft-model.md) modeled per-account
-balance rules as a closed `AccountPolicy` enum with five variants
-(`NoOverdraft`, `CappedOverdraft { floor }`, `UncappedOverdraft`,
-`SystemAccount`, `ExternalAccount`). In practice only one distinction earned
-its keep: may this account's balance go negative, or not? The capped floor, the
-`System`/`External` labels, and the `Uncapped` variant all resolved to the same
-runtime behavior (overdraft allowed, no floor), while adding an enum to
-serialize, a SQL column, resolve/validate match arms, and a dashboard DTO.
+[ADR-0004](0004-account-policies-overdraft-model.md) modeled the balance rules
+of an account as a closed `AccountPolicy` enum with five variants. Those were
+`NoOverdraft`, `CappedOverdraft { floor }`, `UncappedOverdraft`, `SystemAccount`
+and `ExternalAccount`.
+
+In practice only one distinction earned its keep. Can this account's balance go
+negative, or can it not? The capped floor, the `System` and `External` labels,
+and the `Uncapped` variant all reached the same runtime behaviour, which is
+overdraft allowed and no floor.
+
+Each of them still cost an enum to serialize, a SQL column, a match arm in
+resolve and in validate, and a dashboard DTO.
 
 We want a single, legible knob for that one question.
 
 ## Decision Drivers
 
-* **One real distinction**: overdraft allowed vs. forbidden is the only balance
-  rule the domain actually enforces once the floor is dropped.
-* **Fewer moving parts**: a flag rides the existing `AccountFlags` round-trip
-  and needs no separate enum, column, or DTO.
+* **One real distinction**: once the floor goes, the only balance rule the
+  domain enforces is overdraft allowed against overdraft forbidden.
+* **Fewer parts**: a flag travels in the `AccountFlags` round-trip that exists.
+  It needs no separate enum, no column and no DTO.
 * **Legible vocabulary**: `debit_must_not_exceed_credit` names the invariant
   directly.
-* **Safe default**: deposits, withdrawals, and system/boundary accounts all need
-  to hold the negative side of value, so the default must permit overdraft.
+* **Safe default**: a deposit, a withdrawal, and a system or boundary account
+  all need to hold the negative side of value. So the default must permit
+  overdraft.
 
 ## Considered Options
 
@@ -37,77 +42,92 @@ We want a single, legible knob for that one question.
 
 **Cons:**
 
-* Bad, because four of five variants are behaviorally identical once the floor
-  is gone.
-* Bad, because it carries a serialized enum, a SQL column, resolve/validate
-  matches, and a dashboard DTO for a single boolean's worth of information.
+* Bad, because four of the five variants behave identically once the floor is
+  gone.
+* Bad, because it carries a serialized enum, a SQL column, a match in resolve
+  and in validate, and a dashboard DTO. All of that holds one boolean of
+  information.
 
 #### Option 2: Keep a bounded floor (`CappedOverdraft`)
 
 **Cons:**
 
-* Bad, because the floor is only best-effort under concurrency (see
-  [ADR-0003](0003-dumb-storage-saga-recovery.md)), so it never was a hard
+* Bad, because the floor is best-effort alone under concurrency, as
+  [ADR-0003](0003-dumb-storage-saga-recovery.md) says. So it never was a hard
   guarantee.
-* Bad, because a credit-line limit, when actually needed, is better enforced by
-  the application above the ledger than by a soft ledger-level bound.
+* Bad, because the application above the ledger enforces a credit-line limit
+  better than a soft bound inside the ledger does, when anything needs one.
 
 #### Option 3: A single `AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT` bit
 
-The account either carries the flag (balance may not go negative, no negative
-posting allowed) or does not (overdraft allowed without bound; a shortfall
-becomes a negative offset posting; the transfer records as long as it conserves
-value per asset). Overdraft is the default.
+The account either carries the flag or does not.
+
+With the flag, the balance must not go negative, and the account must not hold a
+negative posting.
+
+Without it, overdraft is allowed without bound. A shortfall becomes a negative
+offset posting, and the transfer records if it conserves value per asset.
+
+Overdraft is the default.
 
 **Pros:**
 
 * Good, because it keeps the one distinction that matters and drops the rest.
-* Good, because it reuses the `AccountFlags` bitfield and its storage round-trip
-  (a system-range bit), so there is no new column beyond dropping `policy`.
+* Good, because it reuses the `AccountFlags` bitfield and its storage
+  round-trip, as a bit in the system range. So there is no new column, and
+  `policy` goes.
 * Good, because `Account::debit_must_not_exceed_credit(id)` names the invariant.
 
 **Cons:**
 
-* Bad, because the capped credit-line floor is no longer expressible in the
-  ledger (moved to the application, if needed).
-* Bad, because the `System`/`External` intent labels are gone; a boundary
-  account is now just an ordinary overdraft-permitting account.
+* Bad, because the ledger can no longer express the capped credit-line floor.
+  That moves to the application, if anything needs it.
+* Bad, because the `System` and `External` intent labels are gone. A boundary
+  account is now an ordinary account that permits overdraft.
 
 ## Decision Outcome
 
 Chosen option: **Option 3, a single `DEBIT_MUST_NOT_EXCEED_CREDIT` flag**, with
-overdraft allowed by default. Validation forbids a negative posting, and rejects
-a negative projected balance, only for accounts carrying the flag. Resolution
-covers a shortfall with a negative offset posting only for accounts that permit
-overdraft. The `policy` column is dropped from the SQL schema (migration
-`006_drop_policy.sql`).
+overdraft allowed by default.
+
+Validation forbids a negative posting, and rejects a negative projected balance,
+for an account with the flag alone. Resolution covers a shortfall with a
+negative offset posting for an account that permits overdraft alone. Migration
+`006_drop_policy.sql` drops the `policy` column from the SQL schema.
 
 ### Positive Consequences
 
-* One legible knob per account; the ledger enforces exactly one balance rule.
-* Smaller surface: no `AccountPolicy` enum, no policy column, no policy DTO.
+* One legible knob per account. The ledger enforces exactly one balance rule.
+* A smaller surface. There is no `AccountPolicy` enum, no policy column and no
+  policy DTO.
 
 ### Negative Consequences
 
-* No ledger-enforced capped floor (credit lines are an application concern).
-* The mirror constraint (a balance ceiling, where credits may not exceed debits)
-  is still not modeled; balance rules remain floor-only, now with a single floor
-  of zero.
-* Account intent (customer vs. boundary vs. system) is no longer readable from a
-  type; it must be inferred from the flag plus context.
-* A former `SystemAccount`/`ExternalAccount` debited past its available postings
-  now absorbs the shortfall as a negative offset posting instead of failing with
-  `InsufficientFunds`. This is moot for deposits (they net to zero on the
-  boundary account) but is a behavior change for a direct over-debit.
-* Removing `policy` from the `Account` canonical preimage bumps
-  `CANONICAL_VERSION` (4 → 5), changing account snapshot hashes. Persisted
-  transfers keep their original `EnvelopeId`s and stay self-consistent; a saga
-  in flight across the upgrade re-validates on recovery and aborts cleanly (or
-  rolls forward) rather than corrupting state, per ADR-0003.
+* The ledger enforces no capped floor. A credit line is an application concern.
+* The model still holds no mirror constraint, which would be a balance ceiling
+  where credits must not exceed debits. A balance rule is still a floor alone,
+  and that floor is now zero.
+* No type carries the intent of an account any more, whether that intent is a
+  customer, a boundary or a system account. A reader takes it from the flag plus
+  the context.
+* A debit can now go past the available postings of an account that was a
+  `SystemAccount` or an `ExternalAccount`. That account absorbs the shortfall as
+  a negative offset posting, and it no longer fails with `InsufficientFunds`.
+  This changes nothing for a deposit, because a deposit nets to zero on the
+  boundary account. It is a change of behaviour for a direct over-debit.
+* The removal of `policy` from the canonical preimage of `Account` bumps
+  `CANONICAL_VERSION` from 4 to 5. So every account snapshot hash changes. A
+  persisted transfer keeps its original `EnvelopeId` and stays consistent with
+  itself. A saga that is in flight across the upgrade re-validates on recovery.
+  It then either aborts cleanly or rolls forward, and it corrupts no state, as
+  ADR-0003 says.
 
 ## Links
 
 * Supersedes [ADR-0004](0004-account-policies-overdraft-model.md).
-* Builds on [ADR-0001](0001-modified-utxo-signed-postings.md) (signed postings).
-* Floor-under-concurrency background: [ADR-0003](0003-dumb-storage-saga-recovery.md).
-* Background: [accounts.md](../accounts.md), [accounting-mapping.md](../accounting-mapping.md).
+* Builds on [ADR-0001](0001-modified-utxo-signed-postings.md), which gives the
+  signed postings.
+* Background on the floor under concurrency:
+  [ADR-0003](0003-dumb-storage-saga-recovery.md).
+* Background: [accounts.md](../accounts.md),
+  [accounting-mapping.md](../accounting-mapping.md).

+ 92 - 79
doc/adr/0019-cached-balance-projection.md

@@ -11,35 +11,42 @@
 
 ## Context and Problem Statement
 
-Balance is never stored; `compute_balance` (`crates/kuatia/src/ledger/balance.rs`)
-fetches every live posting for a `(account, subaccount, asset)` and sums it in
-Rust on every read. Under the signed-posting UTXO model (ADR-0001) each `pay`
-mints a change posting and nothing coalesces or caps the active set, so a read
-is `O(N live postings)` and `N` grows unbounded for hot accounts. The commit-time
-overdraft check pays the same cost.
+Balance is never stored; `compute_balance`
+(`crates/kuatia/src/ledger/balance.rs`) fetches every live posting for a
+`(account, subaccount, asset)` and sums it in Rust on every read. Under the
+signed-posting UTXO model (ADR-0001) each `pay` mints a change posting, and
+nothing coalesces or caps the active set. So a read is `O(N live postings)`, and
+`N` grows unbounded for a hot account. The commit-time overdraft check pays the
+same cost.
 
-We want fast reads without weakening correctness, without doing arithmetic in the
-store, and without a central authority handing out sequence numbers.
+Reads must be fast. Three constraints hold:
+
+* The fix must not weaken correctness.
+* No arithmetic goes in the store.
+* No central authority hands out sequence numbers.
 
 ## Decision Drivers
 
-* **Read cost**: remove the unbounded `O(N live postings)` sum from the read path.
-* **Correctness independent of the projector**: reads must be correct even if the
-  projection service is stopped, lagging, crashed, or running many instances.
-* **No math in the store**: the store keeps a scalar and serves rows; all summing
-  happens in Rust, in the service (honours the arithmetic-in-Rust rule).
+* **Read cost**: remove the unbounded `O(N live postings)` sum from the read
+  path.
+* **Correctness independent of the projector**: reads must be correct even if
+  the projection service is stopped, behind, crashed, or in many instances at
+  once.
+* **No math in the store**: the store keeps a scalar and serves rows. All the
+  addition happens in Rust, in the service, which honours the arithmetic-in-Rust
+  rule.
 * **No central sequence authority**: keep decentralized, time-ordered snowflake
   ids (AutoId); do not add a global counter every commit must serialize on.
 * **Authority stays with the postings**: the append-only postings remain the
-  source of truth (ADR-0017); the cache is a disposable, rebuildable projection,
-  never authoritative for the validate-time overdraft check.
+  source of truth (ADR-0017). The cache is a disposable, rebuildable projection,
+  and never authoritative for the validate-time overdraft check.
 
 ## Key insight (why no sequence is needed)
 
-A balance fold is commutative: `snapshot + Σcreates − Σconsumes`. Applying
-committed transfers in any order yields the same total, so the cursor needs only
+A balance fold is commutative: `snapshot + Σcreates − Σconsumes`. Committed
+transfers applied in any order give the same total. So the cursor needs only
 **completeness** (never miss a committed transfer) and **exactly-once** (never
-double-apply), never a total order.
+double-apply), and never a total order.
 
 Correctness is carried entirely by the read rule:
 
@@ -49,11 +56,11 @@ balance(account, asset) = projection.snapshot
                               of creates(+) / consumes(−) for (account, asset)
 ```
 
-Both `creates` and `consumes` live on each committed `EnvelopeRecord`, and
+Both `creates` and `consumes` live on each committed `EnvelopeRecord`.
 `transfer_accounts` indexes every transfer under its involved set (created ∪
-consumed owners), so a single per-account stream contains both the create and the
-spend. This read is correct whatever the projector is doing; the projector only
-shortens the tail.
+consumed owners). So a single per-account stream holds both the create and the
+spend. This read is correct whatever state the projector is in, and the
+projector only shortens the tail.
 
 ## Considered Options
 
@@ -64,33 +71,34 @@ shortens the tail.
 
 #### Option 2: Central strictly-increasing commit sequence
 
-* Bad, because it needs a coordination point every commit serializes on, and has
-  an assignment-order-vs-visibility hazard (a slow `seq=5` visible after `seq=6`
-  is skipped by a reader past 6). Rejected: it reintroduces the central authority
-  we are avoiding.
+* Bad, because it needs a coordination point that every commit serializes on. It
+  also has an assignment-order-against-visibility hazard: a reader past 6 skips
+  a slow `seq=5` that becomes visible after `seq=6`. Rejected, because it brings
+  back the central authority this record removes.
 
 #### Option 3: Projection service + per-account locking + commit-time watermark
 
 An out-of-store service maintains a `balance_projection` cache. Reads are
-lock-free (`snapshot + tail`). The service rebuilds an account's snapshot under a
-per-account lease; the watermark is a commit-time cutoff with a grace window, so
-nothing new ever appears below it. No sequence.
+lock-free (`snapshot + tail`). The service rebuilds the snapshot of an account
+under a per-account lease. The watermark is a commit-time cutoff with a grace
+window, so nothing new ever appears below it. No sequence.
 
 * Good, because correctness is independent of the service (reads always work).
-* Good, because there is no central authority: ordering is the existing
-  decentralized AutoId time order, and coordination is per-account, not global.
+* Good, because there is no central authority. The order is the decentralized
+  AutoId time order that is already there, and coordination is per-account
+  rather than global.
 * Good, because it fits ADR-0017 (a disposable, rebuildable hot index) and keeps
   arithmetic out of the store.
-* Bad, because it is the first aggregate cache, adds a lease/coordination
-  primitive, and rests on a bounded commit-to-visibility lag assumption (with the
-  reconciliation rebuild as the backstop).
+* Bad, because it is the first aggregate cache, and it adds a lease and
+  coordination primitive. It also rests on a bounded commit-to-visibility lag
+  assumption, with the reconciliation rebuild as the backstop.
 
 ## Decision Outcome
 
-Chosen option: **append-only cache points with a lazy, volume-based trigger** (a
-refinement of Option 3 that keeps its watermark-with-grace and lock-free reads
-but drops the service, lease, and CAS in favor of append-only rows and a
-read-triggered append). Concretely:
+Chosen option: **append-only cache points with a lazy, volume-based trigger**.
+It refines Option 3. It keeps the watermark-with-grace and the lock-free reads
+of Option 3. It drops the service, the lease and the CAS in favor of append-only
+rows and a read-triggered append. Concretely:
 
 1. **Append-only `balance_projection` table.** One row per cache point:
    `(id, account, subaccount, asset, balance, watermark)`, where `id` is a
@@ -104,50 +112,54 @@ read-triggered append). Concretely:
    uses a snapshot that covers transfers committed after `as_of`. The ledger
    passes the current time by default; a past `as_of` yields an as-of balance.
 
-3. **Commit-time watermark with grace.** A cache point's watermark is
-   `now − Δ`, measured in commit/visibility time (`EnvelopeRecord.created_at`,
-   stamped at `store_transfer`), never intent time, so nothing new appears below
-   it. `Δ` is not business latency: an inflight hold that settles hours later
-   commits (and is stamped) at settlement time, landing in the tail. Default: 60
-   seconds, configurable.
+3. **Commit-time watermark with grace.** A cache point's watermark is `now − Δ`,
+   measured in commit/visibility time (`EnvelopeRecord.created_at`, stamped at
+   `store_transfer`), never intent time, so nothing new appears below it. `Δ` is
+   not business latency. An inflight hold that settles hours later commits at
+   settlement time, is stamped then, and lands in the tail. Default: 60 seconds,
+   configurable.
 
-4. **Lazy, volume-based trigger.** No commit hook, no background loop. When a
-   read folds the tail and finds at least `snapshot_interval` credits/debits
-   (created + consumed postings owned by the account) accrued since the closest
-   cache point, it appends a new one off the read path (a background task). The
-   threshold is configurable (default 128).
+4. **Lazy, volume-based trigger.** No commit hook, no background loop. A read
+   folds the tail and counts the credits and debits since the closest cache
+   point. Those are the created and consumed postings the account owns. At
+   `snapshot_interval` or more, the read appends a new cache point off the read
+   path, in a background task. The threshold is configurable (default 128).
 
 5. **Append-only makes coordination free.** Concurrent appends just add rows; a
    read takes the closest-at-or-before, so there is no lock, CAS, or lease. A
    redundant or slightly-stale append is harmless history that a later read
-   ignores. Reads return `closest snapshot + Rust-folded tail` and are correct
-   regardless of whether any cache point exists; `compute_balance` (the
-   authoritative full live-posting sum) is retained and remains what the validate
-   path reads.
+   ignores. Reads return `closest snapshot + Rust-folded tail`, and they are
+   correct whether a cache point exists or not. `compute_balance` (the
+   authoritative full live-posting sum) is retained, and it remains what the
+   validate path reads.
 
 6. **Authority unchanged; UTXO stays the concurrency control.** The
-   validate-time overdraft check keeps reading the authoritative live-posting
-   (UTXO) sum, never the cache. The projection is a read accelerator only; a
-   stale snapshot must never admit an overdraft. This matters most for an account
-   with `DEBIT_MUST_NOT_EXCEED_CREDIT`: the signed-posting UTXO model plus the
-   reservation protocol (ADR-0006/0016) is what makes the no-overdraft invariant
-   exact under concurrency. A commit atomically reserves the specific postings it
-   spends, so two concurrent debits cannot both consume the same value, and the
-   balance floor is enforced against the real live set at commit time. An
-   eventually-consistent cache cannot provide that guarantee, so the UTXO path is
-   retained internally as the concurrency-control mechanism for these accounts,
-   with the projection layered on top purely to speed up reporting reads.
-
-7. **Reconciliation.** Appending a cache point (or reading with a very small
-   interval) folds from the append-only postings and detects no drift by
-   construction, since a read always equals the live sum. `compute_balance` is
-   the from-scratch recompute available for an explicit audit.
+   validate-time overdraft check still reads the authoritative live-posting
+   (UTXO) sum, and never the cache. The projection is a read accelerator only,
+   and a stale snapshot must never admit an overdraft.
+
+   This matters most for an account with `DEBIT_MUST_NOT_EXCEED_CREDIT`. The
+   signed-posting UTXO model plus the reservation protocol (ADR-0006/0016) is
+   what makes the no-overdraft invariant exact under concurrency. A commit
+   atomically reserves the specific postings it spends, so two concurrent debits
+   cannot both consume the same value. The balance floor is enforced against the
+   real live set at commit time.
+
+   An eventually-consistent cache cannot give that guarantee. So the UTXO path
+   is retained internally as the concurrency-control mechanism for these
+   accounts. The projection sits on top only to speed up a report read.
+
+7. **Reconciliation.** An append of a cache point folds from the append-only
+   postings, and so does a read with a very small interval. Neither detects
+   drift, by construction, because a read always equals the live sum.
+   `compute_balance` is the from-scratch recompute available for an explicit
+   audit.
 
 ### Positive Consequences
 
-* Balance reads drop from `O(N live postings)` toward `O(tail since the latest
-  cache point)`, bounded by how recently a read last appended, not by lifetime
-  fragmentation.
+* Balance reads drop from `O(N live postings)` toward
+  `O(tail since the latest cache point)`, bounded by how recently a read last
+  appended, not by lifetime fragmentation.
 * Correctness lives in "closest snapshot + full tail" over the append-only log;
   the cache points are pure optimization. Best-effort and crash-safe by
   construction: a lost or absent cache point only lengthens a tail.
@@ -157,13 +169,14 @@ read-triggered append). Concretely:
 ### Negative Consequences
 
 * First aggregate cache: more surface than the row-copy hot indexes.
-* Append-only cache points accumulate; pruning old ones (by count or age) is
-  future work.
+* Append-only cache points accumulate, and the deletion of old ones (by count or
+  age) is future work.
 * A write-heavy account that is never read never appends a cache point, so its
-  first read folds a long tail (then appends). Acceptable: the cost tracks reads.
-* Rests on a bounded commit-to-visibility lag assumption (the grace `Δ`); the
-  watermark must be commit-time, not intent time, or a late settlement below the
-  watermark would be lost.
+  first read folds a long tail (then appends). Acceptable: the cost tracks
+  reads.
+* Rests on a bounded commit-to-visibility lag assumption (the grace `Δ`). The
+  watermark must be commit-time and not intent time, or a late settlement below
+  the watermark would be lost.
 * The projection must never become authoritative for the overdraft check.
 
 ## Links
@@ -174,7 +187,7 @@ read-triggered append). Concretely:
 * Balance model: [ADR-0001](0001-modified-utxo-signed-postings.md).
 * Dumb-storage primitives and recovery:
   [ADR-0003](0003-dumb-storage-saga-recovery.md).
-* Inflight settlement timing (why the watermark is commit-time):
+* Inflight settlement time (why the watermark is commit-time):
   [ADR-0014](0014-inflight-holds-via-holding-accounts.md).
 * Background: [accounts.md](../accounts.md), balance read path in
   `crates/kuatia/src/ledger/balance.rs`.

+ 88 - 74
doc/adr/0020-account-transition-recovery.md

@@ -8,106 +8,120 @@
 
 ## Context and Problem Statement
 
-ADR-0003 made the commit path crash-safe with a phase-tracked write-ahead
-record and a roll-forward `recover()`. Account lifecycle transitions
-(`freeze`, `unfreeze`, `close`) never got the same treatment. Each was an
-independent copy of the same shape: load the account, reject if closed, append
-a new account version with the flag flipped, then append the lifecycle event.
-The version append and the event append are two separate store writes with no
-shared transaction, so a crash between them left a durable version bump with no
-event, and nothing repaired it. That is the exact window `recover()` closes for
-`store_transfer → append_event` on the commit path, left open for account
-transitions.
+ADR-0003 made the commit path crash-safe. It used a write-ahead record with
+tracked phases, and a `recover()` that rolls forward. The account lifecycle
+transitions never got the same treatment, and those are `freeze`, `unfreeze` and
+`close`.
+
+Each one was an independent copy of the same shape. Load the account. Reject it
+if it is closed. Append a new account version with the flag flipped. Then append
+the lifecycle event.
+
+The version append and the event append are two separate store writes, and they
+share no transaction. So a crash between them left a durable version bump with
+no event, and nothing repaired it. `recover()` closes exactly that window for
+`store_transfer → append_event` on the commit path. For an account transition it
+stayed open.
 
 A second problem sat underneath the first. ADR-0010 made `append_event`
-idempotent on a content key, but only for `TransferCommitted` (keyed on the
-transfer id). Account lifecycle events had no key, so `event_dedup_key` returned
-`None` and a second append duplicated the row. Any repair path that re-appends
-the event therefore needs the event to first gain a stable identity; without it,
-recovery cannot tell "the event was already written" from "write it now."
+idempotent on a content key, but for `TransferCommitted` alone, keyed on the
+transfer id. An account lifecycle event had no key, so `event_dedup_key`
+returned `None` and a second append duplicated the row.
+
+So a repair path that re-appends the event needs the event to gain a stable
+identity first. Without one, a recovery cannot tell that something already wrote
+the event from the case where it must write it now.
 
-How should a lifecycle transition be made crash-safe, reusing the existing
-recovery machinery rather than inventing a parallel one?
+So how does a lifecycle transition become crash-safe? It must reuse the recovery
+machinery that exists, and not add a parallel one.
 
 ## Decision Drivers
 
-* **Same repair path, not a second one**: reuse the `SagaStore` write-ahead
-  record + startup `recover()` that the commit engine already has.
-* **Idempotent in every crash window**: recovery must converge whether it runs
-  before either write, between the two writes, or after both.
-* **No duplicate events, no double version bump**: rolling a transition forward
-  twice must be a no-op.
-* **Remove the triplication**: one transition primitive parameterized by the
-  flag mutation, not three near-identical copies.
-* **Storage stays dumb** (ADR-0003): the store gains no transition-specific
-  method; it still just appends versions and events and follows instructions.
+* **The same repair path, not a second one**: reuse the `SagaStore` write-ahead
+  record and the `recover()` at startup that the commit engine has.
+* **Idempotent in every crash window**: recovery must converge in each case. It
+  can run before either write, between the two writes, or after both.
+* **No duplicate event and no double version bump**: two roll-forwards of one
+  transition must do nothing the second time.
+* **Remove the three copies**: one transition primitive that takes the flag
+  mutation as a parameter, and not three copies that are almost identical.
+* **Storage stays simple** (ADR-0003): the store gains no method for a
+  transition. It still appends a version and an event, and it follows
+  instructions.
 
 ## Considered Options
 
 #### Option 1: Wrap the two writes in one store transaction
 
-Add a store method that appends the version and the event atomically.
+Add a store method that appends the version and the event in one atomic step.
 
 **Pros:**
 
-* No write-ahead record; the gap cannot open.
+* Good, because it needs no write-ahead record, and the gap cannot open.
 
 **Cons:**
 
-* Reintroduces a monolithic, guard-bearing store method, the exact thing
-  ADR-0003 removed. The store would again bundle domain steps into one
-  transaction.
-* Does not compose with the existing `recover()`; lifecycle durability would
-  diverge from commit durability.
+* Bad, because it brings back a monolithic store method that carries a guard,
+  which is the exact thing ADR-0003 removed. The store then bundles domain steps
+  into one transaction again.
+* Bad, because it does not compose with the `recover()` that exists. The
+  durability of a lifecycle change then diverges from the durability of a
+  commit.
 
 #### Option 2: Write-ahead record + idempotent roll-forward (reuse `recover()`)
 
 Persist a `PendingTransition {next_account, event}` write-ahead record before
-either write, keyed in the same `SagaStore` as commit sagas under a tagged
-`PendingRecord` enum. `recover()` rolls it forward: append the version only when
-it is not yet present (`append_account_version` requires `version == current+1`,
-so a version check is the idempotency test), then re-append the event, then
-delete the record. To make the event re-append idempotent, give the three
-transition events a `version` field and key `event_dedup_key` on
-`(account, version)`.
+either write. Key it in the same `SagaStore` that holds a commit saga, under a
+tagged `PendingRecord` enum.
+
+`recover()` then rolls it forward in three steps. Append the version only when
+it is not present yet. `append_account_version` needs `version == current+1`, so
+a version check is the idempotency test. Re-append the event. Delete the record.
+
+To make that re-append of the event idempotent, give the three transition events
+a `version` field, and key `event_dedup_key` on `(account, version)`.
 
 **Pros:**
 
-* One recovery entry point handles commit sagas and account transitions.
-* Idempotent in every window: the version check guards the append, and the
-  `(account, version)` key collapses a duplicate event.
-* Storage stays dumb; no new transition method.
-* Lets the three lifecycle methods collapse to one `transition` helper.
+* Good, because one recovery entry point handles both a commit saga and an
+  account transition.
+* Good, because it is idempotent in every window. The version check guards the
+  append, and the `(account, version)` key collapses a duplicate event.
+* Good, because storage stays simple. There is no new transition method.
+* Good, because the three lifecycle methods collapse into one `transition`
+  helper.
 
 **Cons:**
 
-* Changes the event schema (a new field) and generalizes the dedup key type
-  from `EnvelopeId` to a string.
-* The write-ahead blob format for in-flight commit sagas changes (now wrapped in
-  `PendingRecord::Envelope`), so a saga persisted by an older binary would not
-  deserialize after upgrade. Acceptable for in-flight, single-lifetime records.
+* Bad, because it changes the event schema, by a new field. It also widens the
+  type of the dedup key from `EnvelopeId` to a string.
+* Bad, because the write-ahead blob format changes for a commit saga that is in
+  flight. `PendingRecord::Envelope` now wraps it, so a saga that an older binary
+  persisted does not deserialize after the upgrade. That is acceptable for a
+  record that lives for one process lifetime.
 
 ## Decision Outcome
 
-Chosen option: **Option 2**. It closes the gap by reusing ADR-0003's machinery
-instead of contradicting it, keeps the store dumb, and removes the triplication
-as a side effect.
+Chosen option: **Option 2**. It closes the gap by a reuse of ADR-0003's
+machinery, rather than a contradiction of it. It keeps the store simple. It also
+removes the three copies as a side effect.
 
 Concretely:
 
-* A single `Ledger::transition(id, mutate, make_event)` holds the shared shape.
-  `freeze`/`unfreeze`/`close` supply only the flag mutation and the event;
-  `close` layers its emptiness guard before the call. Because a closed account
-  holds no live postings, checking emptiness before the shared not-closed guard
-  still surfaces `AccountAlreadyClosed` on a re-close.
+* One `Ledger::transition(id, mutate, make_event)` holds the shared shape.
+  `freeze`, `unfreeze` and `close` supply the flag mutation and the event alone.
+  `close` puts its emptiness guard before the call. A closed account holds no
+  live posting, so that order still surfaces `AccountAlreadyClosed` on a second
+  close.
 * The write-ahead record is a `PendingTransition {next, event}`, stored in the
   `SagaStore` under a tagged `PendingRecord::{Envelope, Transition}` so
   `recover()` dispatches by kind. The transition key is minted from the same
   generator as reservation ids, so it never collides with a commit saga's key.
-* `recover()` rolls a transition forward through `complete_transition`: append
-  the version if `current.version < next.version`, re-append the (now
-  idempotent) event, delete the record. No phase tracking is needed, unlike the
-  commit saga, because both steps are individually idempotent.
+* `recover()` rolls a transition forward through `complete_transition`. It
+  appends the version if `current.version < next.version`. It re-appends the
+  event, which is idempotent now. It deletes the record. It needs no tracked
+  phase, which the commit saga does need, because each step is idempotent on its
+  own.
 * `LedgerEventKind::Account{Frozen,Unfrozen,Closed}` gain a `version` field
   (`#[serde(default)]`, so old event JSON still loads). `event_dedup_key`
   returns `Option<String>`: a transfer's lowercase-hex id (unchanged from what
@@ -117,21 +131,21 @@ Concretely:
 
 ### Positive Consequences
 
-* A lifecycle transition interrupted at any point is repaired on the next
-  `recover()`, matching the commit path's guarantee.
-* Lifecycle events now record which account version they correspond to, so the
-  event stream (ADR-0010) can be correlated with the account history.
+* The next `recover()` repairs a lifecycle transition that stopped at any point.
+  That matches the guarantee of the commit path.
+* A lifecycle event now records the account version it belongs to. So a reader
+  can match the event stream (ADR-0010) against the account history.
 * Three copies become one primitive.
 
 ### Negative Consequences
 
-* The event schema and dedup-key type changed; downstream consumers that
-  exhaustively match the event kinds must account for the new field.
-* An in-flight commit saga's write-ahead blob written before this change will
-  not deserialize afterward. In-flight records have no cross-version durability
-  contract, so this is a one-time, accepted cost.
-* `create_account`'s create-then-`append_event` has the same shape of gap. It is
-  not a version transition and is left for a future change.
+* The event schema changed, and so did the type of the dedup key. A downstream
+  consumer that matches every event kind must account for the new field.
+* A write-ahead blob that an in-flight commit saga wrote before this change does
+  not deserialize after it. An in-flight record has no durability contract
+  across versions, so this is a one-time cost that the record accepts.
+* The create and then `append_event` in `create_account` has a gap of the same
+  shape. It is not a version transition, so a later change covers it.
 
 ## Links
 

+ 41 - 35
doc/adr/0021-commit-safety-map.md

@@ -11,37 +11,40 @@
 
 ## Context and Problem Statement
 
-"What makes a commit safe" had no single place to audit. The invariant was
-split across three modules with no anchor tying them together:
+"What makes a commit safe" had no single place to audit. The invariant was split
+across three modules, and no anchor held them together:
 
 * value / conservation / floor / freeze / snapshot / book-policy checks in
   `validate_and_plan` (`kuatia-core`),
-* the double-spend / reservation-ownership check inlined inside the
-  ~110-line `finalize_envelope` (`kuatia/ledger/commit.rs`),
+* the double-spend / reservation-ownership check inlined inside the ~110-line
+  `finalize_envelope` (`kuatia/ledger/commit.rs`),
 * the affected-row count contract in `apply_and_verify` / `verify_postings`
   (`kuatia/saga.rs`).
 
-A reader auditing `validate_and_plan` in isolation could reasonably but wrongly
-conclude it prevents double-spends; its lifecycle check even carried a comment
-saying the real enforcement happens "elsewhere" with no pointer to where. The
-load-bearing double-spend guard had no name and was reachable only through an
-end-to-end commit, so its unit-test surface was the easy (pure) half only.
+A reader who audits `validate_and_plan` on its own could conclude that it
+prevents a double-spend. That conclusion is reasonable and wrong. Its lifecycle
+check even carried a comment that said the real enforcement happens "elsewhere",
+and the comment named no destination.
 
-Could the whole decision be concentrated into one pure function "given this
-envelope and current state, may it commit"? No: the double-spend property is not
-decidable against a snapshot. In a concurrent ledger the only way to know a
-posting can be spent is to atomically try to spend it and read the result. The
-CAS *is* the decision (ADR-0003 dumb storage), and it must not be hoisted next
-to `validate_and_plan`, which is pure / sync / no-IO by contract.
+The double-spend guard that carries the load had no name. Only an end-to-end
+commit reached it, so its unit-test surface covered the easy pure half alone.
+
+Can one pure function hold the whole decision, as in "given this envelope and
+this current state, can it commit"? No, because a snapshot cannot decide the
+double-spend property. In a concurrent ledger there is one way to know that a
+posting can be spent. Try to spend it atomically, then read the result.
+
+The CAS *is* the decision (ADR-0003, simple storage). It must not move next to
+`validate_and_plan`, which is pure, sync and IO-free by contract.
 
 ## Decision Drivers
 
-* **One audit surface** for the ledger's core safety property, without merging
-  the pure value checks and the stateful CAS into a single function.
-* **Preserve the pure/async boundary** (ADR-0002, ADR-0003): validation stays
-  pure and IO-free; the concurrency authority stays in the saga.
-* **Name and unit-test the double-spend guard** rather than leaving it inline
-  and only end-to-end testable.
+* **One audit surface** for the ledger's core safety property. It must not merge
+  the pure value checks and the stateful CAS into one function.
+* **Keep the boundary between pure and async** (ADR-0002, ADR-0003). Validation
+  stays pure and IO-free, and the authority over concurrency stays in the saga.
+* **Name the double-spend guard and unit-test it.** Do not leave it inline,
+  where only an end-to-end test reaches it.
 
 ## Decision Outcome
 
@@ -57,13 +60,14 @@ with a single home:
 
 Concretely:
 
-* The double-spend guard was extracted out of `finalize_envelope` into
-  `consume_reserved`, co-located with the count-contract helpers it depends on.
-  It consumes only the rows this saga reserved
-  (`deactivate_postings(_, Some(rid))`) and then asserts every consumed id is
-  `Spent`; that assertion can pass only when no id was left active or held by
-  another saga. It has direct unit tests (spends our reservation; refuses an
-  unreserved posting; refuses one held by another saga).
+* The double-spend guard moved out of `finalize_envelope` and into
+  `consume_reserved`, beside the count-contract helpers it depends on. It
+  consumes only the rows that this saga reserved, through
+  `deactivate_postings(_, Some(rid))`. It then asserts that every consumed id is
+  `Spent`. That assertion passes only when no id stayed active and no other saga
+  held one. Three direct unit tests cover it. It spends our own reservation. It
+  refuses a posting with no reservation. It refuses a posting that another saga
+  holds.
 * `validate_and_plan`'s lifecycle comment now points at `consume_reserved` and
   this ADR instead of a vague "elsewhere".
 
@@ -76,13 +80,15 @@ Concretely:
 
 ### Negative Consequences
 
-* The invariant is still physically split across `kuatia-core` and `kuatia`.
-  That split is intentional (pure value checks vs. runtime CAS) and this ADR is
-  the anchor that makes it navigable; it is not a single code seam.
+* The invariant still sits physically in two crates, `kuatia-core` and `kuatia`.
+  That split is deliberate, because the pure value checks and the runtime CAS
+  belong in different layers. This record is the anchor that makes the split
+  navigable. It is not one code seam.
 
 ## Links
 
-* Builds on [ADR-0003](0003-dumb-storage-saga-recovery.md) (dumb storage, the
-  best-effort floor/freeze note) and [ADR-0002](0002-saga-commit-pipeline.md).
-* Relates to [ADR-0006](0006-reservation-protocol-posting-lifecycle.md)
-  (reservation protocol / posting lifecycle).
+* Builds on [ADR-0003](0003-dumb-storage-saga-recovery.md), which covers simple
+  storage and the note on the best-effort floor and freeze, and on
+  [ADR-0002](0002-saga-commit-pipeline.md).
+* Relates to [ADR-0006](0006-reservation-protocol-posting-lifecycle.md), which
+  gives the reservation protocol and the posting lifecycle.

+ 108 - 83
doc/adr/0022-merged-live-postings-hot-index.md

@@ -9,95 +9,114 @@
 
 ## Context and Problem Statement
 
-ADR-0016/0017 split a posting's live state across two disposable hot tables:
-`active_postings` (membership = spendable) and `reserved_postings` (membership +
-`reservation` = claimed by a saga). A "live" read (`Active ∪ Reserved`), which
-`compute_balance` and `has_live_postings` need, therefore has no single table to
-hit: the SQL backend expresses it as a `UNION ALL` of the two tables. Reserve and
-release move a row between the two tables (`DELETE` from one, `INSERT` into the
-other), and `get_posting_states` probes three tables.
-
-Only the SQL encoding forces the `UNION ALL`; the two-table split is not required
-by any correctness guarantee (ADR-0006's reservation protocol needs an atomic
-single-winner claim, durable observable ownership, and count-returning
-primitives, none of which depend on the physical table count). Can the live set
-live in one table so the `UNION ALL` disappears, without losing those
-guarantees?
+ADR-0016 and ADR-0017 split the live state of a posting across two disposable
+hot tables. Membership of `active_postings` means spendable. Membership of
+`reserved_postings`, plus the `reservation` column, means a saga claimed it.
+
+So a "live" read, which is `Active ∪ Reserved`, has no single table to hit.
+`compute_balance` and `has_live_postings` both need that read, and the SQL
+backend expresses it as a `UNION ALL` over the two tables.
+
+A reserve and a release move a row between the two tables, by a `DELETE` from
+one and an `INSERT` into the other. `get_posting_states` probes three tables.
+
+Only the SQL encoding forces the `UNION ALL`. No correctness guarantee needs the
+two-table split. The reservation protocol of ADR-0006 needs an atomic
+single-winner claim, durable ownership that something can observe, and
+primitives that return a count. None of those depend on the number of physical
+tables.
+
+So can the live set live in one table, and the `UNION ALL` disappear, with those
+guarantees intact?
 
 ## Decision Drivers
 
-* **Query clarity and read performance.** The live/spendable reads are hot
-  (`compute_balance` runs per commit in the finalize validation loader). A
-  single-table scan is simpler to reason about and to index than a `UNION ALL`.
-* **Preserve every ADR-0006/0016 guarantee.** Unconditional lock-free
-  double-spend safety; durable, observable, recoverable reservation ownership;
-  atomic count-returning dumb-storage primitives (ADR-0003); balance as
-  `Active ∪ Reserved`; append-only value table.
-* **Keep the source of truth append-only (ADR-0017).** `postings` (the immutable
-  record) must stay INSERT-only and rebuildable-from is the audit trail. Whatever
-  changes may only touch a disposable hot table.
+* **Query clarity and read performance.** The live and spendable reads are hot,
+  because `compute_balance` runs once per commit inside the finalize validation
+  loader. One table scan is simpler to reason about, and simpler to index, than
+  a `UNION ALL`.
+* **Keep every guarantee of ADR-0006 and ADR-0016.** These are the guarantees:
+  - Unconditional double-spend safety, with no lock.
+  - Reservation ownership that is durable, observable and recoverable.
+  - Atomic simple-storage primitives that return a count (ADR-0003).
+  - A balance over `Active ∪ Reserved`.
+  - An append-only value table.
+* **Keep the source of truth append-only (ADR-0017).** `postings` is the
+  immutable record. It must stay INSERT-only, and the audit trail is what a
+  rebuild reads. Any change must touch a disposable hot table alone.
 
 ## Considered Options
 
 #### Option 1: Keep two hot tables (ADR-0016/0017)
 
-`active_postings` + `reserved_postings`, live reads via `UNION ALL`, reserve as
-`DELETE`-from-active + `INSERT`-into-reserved.
+Keep `active_postings` and `reserved_postings`. A live read goes through a
+`UNION ALL`. A reserve is a `DELETE` from the active table and an `INSERT` into
+the reserved one.
 
 **Pros:**
 
-* Good, because the entire hot-table write path is `INSERT` + `DELETE`, so a
-  grant can withhold `UPDATE` on them too.
+* Good, because the whole write path on a hot table is an `INSERT` and a
+  `DELETE`. So a grant can withhold `UPDATE` on those tables too.
 * Good, because it is already implemented and conformance-tested.
 
 **Cons:**
 
 * Bad, because a live read has no single table and is a `UNION ALL`.
-* Bad, because reserve/release are two-statement moves and `get_posting_states`
-  probes three tables.
+* Bad, because a reserve and a release each move a row in two statements, and
+  `get_posting_states` probes three tables.
 
 #### Option 2: One `live_postings` table with a nullable `reservation`
 
-Merge the two hot tables into one: `live_postings (transfer_id, idx, owner,
-subaccount, asset, value, reservation)`, `reservation` NULL = Active, set =
-Reserved by that id. State is still derived from membership + the column: present
-& NULL = Active; present & = rid = Reserved(rid); absent from `live_postings` but
-in `postings` = Spent; absent everywhere = Missing. The primitives become:
+Merge the two hot tables into one,
+`live_postings (transfer_id, idx, owner, subaccount, asset, value, reservation)`.
+A NULL `reservation` means Active. A set one means Reserved by that id.
+
+The ledger still derives the state from membership plus the column. Present with
+NULL is `Active`. Present with `= rid` is `Reserved(rid)`. Absent from
+`live_postings` but present in `postings` is `Spent`. Absent from both is
+`Missing`.
+
+The primitives become:
 
 * Live read: `SELECT ... FROM live_postings WHERE owner/subaccount/asset` (no
-  `UNION`). Active = `... AND reservation IS NULL`, Reserved = `... AND
-  reservation IS NOT NULL`.
-* Reserve: `UPDATE live_postings SET reservation = $rid WHERE <ids> AND
-  reservation IS NULL`. The `IS NULL` guard is the atomic single-winner claim
-  (concurrent reserves serialize on the row lock; the loser's predicate no longer
-  matches → 0 rows). One statement.
-* Release: `UPDATE live_postings SET reservation = NULL WHERE <ids> AND
-  reservation = $rid`.
-* Consume (finalize) / raw deactivate: `DELETE FROM live_postings WHERE <ids> AND
-  reservation = $rid` (or `IS NULL`); the posting stays in `postings` = Spent.
-* `get_posting_states`: two statements (live table + `postings`) instead of three.
+  `UNION`). Active = `... AND reservation IS NULL`, Reserved =
+  `... AND reservation IS NOT NULL`.
+* Reserve:
+  `UPDATE live_postings SET reservation = $rid WHERE <ids> AND reservation IS NULL`.
+  The `IS NULL` guard is the atomic single-winner claim. Two concurrent reserves
+  serialize on the row lock, and the second one's predicate no longer matches,
+  so it affects 0 rows. That is one statement.
+* Release:
+  `UPDATE live_postings SET reservation = NULL WHERE <ids> AND reservation = $rid`.
+* Consume (finalize) / raw deactivate:
+  `DELETE FROM live_postings WHERE <ids> AND reservation = $rid` (or `IS NULL`);
+  the posting stays in `postings` = Spent.
+* `get_posting_states`: two statements (live table + `postings`) instead of
+  three.
 
 **Pros:**
 
-* Good, because the live set is one table: the `UNION ALL` is gone, reserve and
-  release are single statements, and `get_posting_states` drops a statement.
-* Good, because every ADR-0006 guarantee holds: the `UPDATE ... WHERE reservation
-  IS NULL` gives the same single-winner claim as the `DELETE`-CAS; the
-  `reservation` column is still the durable, observable ownership recovery reads;
-  the primitives still return affected-row counts the saga interprets.
-* Good, because the value table `postings` stays append-only INSERT-only, and
-  `live_postings` is still fully rebuildable from `postings` plus the saga
-  write-ahead records, so a corrupt hot table is drop-and-rebuild (ADR-0017's
-  disposability principle is preserved).
+* Good, because the live set is one table. The `UNION ALL` is gone, a reserve
+  and a release are each one statement, and `get_posting_states` drops a
+  statement.
+* Good, because every guarantee of ADR-0006 holds. The
+  `UPDATE ... WHERE reservation IS NULL` gives the same single-winner claim as
+  the `DELETE` CAS did. The `reservation` column is still the durable,
+  observable ownership that a recovery reads. The primitives still return the
+  affected-row count that the saga reads.
+* Good, because the value table `postings` stays append-only and INSERT-only.
+  `live_postings` is still rebuildable in full, from `postings` plus the saga
+  write-ahead records. So a corrupt hot table is a drop and a rebuild, and the
+  disposability principle of ADR-0017 survives.
 
 **Cons:**
 
-* Bad, because the hot table now takes an `UPDATE` (the reservation flip), so the
-  "hot tables are `INSERT`/`DELETE` only, withhold `UPDATE` everywhere" grant
-  story of ADR-0017 no longer holds for `live_postings` (it still holds for the
-  value tables).
-* Bad, because the schema change is forward-only (migration 008 merges the two
-  tables and drops them).
+* Bad, because the hot table now takes an `UPDATE`, which is the reservation
+  flip. ADR-0017 had said that a hot table takes an `INSERT` and a `DELETE`
+  alone, so a grant can withhold `UPDATE` everywhere. That no longer holds for
+  `live_postings`. It still holds for the value tables.
+* Bad, because the schema change goes one way only. Migration 008 merges the two
+  tables and drops them.
 
 #### Option 3: Keep the `UNION ALL` but hide it behind a view
 
@@ -105,39 +124,45 @@ A SQL `VIEW live_postings AS active UNION ALL reserved`.
 
 **Pros:**
 
-* Good, because callers read one name.
+* Good, because a caller reads one name.
 
 **Cons:**
 
-* Bad, because it is the same `UNION ALL` at runtime; nothing is actually saved.
+* Bad, because it is the same `UNION ALL` at runtime. It saves nothing.
 
 ## Decision Outcome
 
 Chosen option: **Option 2, one `live_postings` table with a nullable
-`reservation`.** It removes the `UNION ALL` and collapses reserve/release to a
-single statement while preserving every correctness guarantee of ADR-0006/0016.
-The one concession is that the disposable hot table now takes an `UPDATE` (the
-reservation flip): this is deliberately confined to the rebuildable hot table and
-never touches the append-only `postings` value table, so ADR-0017's core driver
-(the source of truth cannot be corrupted or lost by any write path) is intact.
+`reservation`.** It removes the `UNION ALL`. It collapses a reserve and a
+release to one statement each. Every correctness guarantee of ADR-0006 and
+ADR-0016 survives.
+
+There is one concession. The disposable hot table now takes an `UPDATE`, which
+is the reservation flip. That `UPDATE` stays deliberately inside the rebuildable
+hot table, and it never touches the append-only `postings` value table. So the
+core driver of ADR-0017 is intact: no write path can corrupt or lose the source
+of truth.
 
-This supersedes the two-table hot-index *encoding* of ADR-0016 and ADR-0017. Their
-principle (append-only value tables plus disposable hot indexes) stands; only the
-number of hot tables and the reserve verb change.
+This supersedes the two-table hot-index *encoding* of ADR-0016 and ADR-0017.
+Their principle stands, which is an append-only value table plus a disposable
+hot index. Only the number of hot tables and the reserve verb change.
 
 ### Positive Consequences
 
-* A live/spendable read is one index scan on `idx_live_owner`, no `UNION ALL`.
-* Reserve and release are single `UPDATE` statements; `get_posting_states` is two
-  queries instead of three.
-* `reservation IS NULL` vs `= rid` still expresses Active vs Reserved, so state is
-  still derived, and recovery still reads "reserved by this saga" from the column.
+* A live and spendable read is one index scan on `idx_live_owner`, with no
+  `UNION ALL`.
+* A reserve and a release are each one `UPDATE` statement. `get_posting_states`
+  is two queries rather than three.
+* `reservation IS NULL` against `= rid` still separates Active from Reserved. So
+  the state is still derived, and a recovery still reads from the column that
+  this saga reserved the posting.
 
 ### Negative Consequences
 
-* The `live_postings` hot table takes an `UPDATE`; the grant that withholds
-  `UPDATE` now applies to the value tables only, not the hot table.
-* Forward-only migration (008) that drops `active_postings` / `reserved_postings`.
+* The `live_postings` hot table takes an `UPDATE`. The grant that withholds
+  `UPDATE` now covers the value tables alone and not the hot table.
+* Migration 008 goes one way only, and it drops `active_postings` and
+  `reserved_postings`.
 
 ## Links
 
@@ -146,6 +171,6 @@ number of hot tables and the reserve verb change.
   [ADR-0017](0017-correctness-first-append-only-hot-indexes.md); their
   append-only-value / disposable-hot-index principle is unchanged.
 * Preserves the reservation protocol of
-  [ADR-0006](0006-reservation-protocol-posting-lifecycle.md) and the dumb-storage
-  primitives of [ADR-0003](0003-dumb-storage-saga-recovery.md).
+  [ADR-0006](0006-reservation-protocol-posting-lifecycle.md) and the
+  dumb-storage primitives of [ADR-0003](0003-dumb-storage-saga-recovery.md).
 * Reflected in [storage-schema.md](../storage-schema.md).

+ 114 - 89
doc/adr/0023-atomic-storage-commit.md

@@ -9,36 +9,44 @@
 
 ## Context and Problem Statement
 
-ADR-0003 made storage a set of dumb single-update primitives and moved
-crash-safety into a phase-tracked write-ahead record (`PendingSaga` /
-`PendingTransition`) plus roll-forward recovery (`Ledger::recover`). A commit was
-a sequence of primitives (`reserve → deactivate → insert → store_transfer →
-append_event`) with no shared transaction, so the write-ahead log was the only
-thing protecting against a half-applied commit. That design also left the
-overdraft floor and the freeze/close guards **best-effort** under concurrency,
-re-checked just before the writes but not atomic with them.
-
-Two things prompted revisiting it. The `legend` saga VM had already been reduced
-to two thin adapters used only by tests: the single-commit path was a linear
-method, not a saga. And the whole write-ahead machinery existed only because the
-store could not commit a transfer atomically. If it can, the reservation
-two-step, the write-ahead record, and recovery all become unnecessary.
-
-Should the store apply a whole transfer atomically, reversing ADR-0003's dumb
-per-primitive model?
+ADR-0003 made storage a set of simple single-update primitives. It moved
+crash-safety into a write-ahead record with tracked phases, which is
+`PendingSaga` or `PendingTransition`, plus a roll-forward recovery in
+`Ledger::recover`.
+
+A commit was a sequence of primitives,
+`reserve → deactivate → insert → store_transfer → append_event`, and they shared
+no transaction. So the write-ahead log was the only protection against a
+half-applied commit.
+
+That design also left the overdraft floor and the freeze and close guards
+**best-effort** under concurrency. It re-checked them just before the writes,
+and not atomically with them.
+
+Two things brought that design back up for review.
+
+First, the `legend` saga machine had already shrunk to two thin adapters that
+only a test used. The path for one commit was a linear method and not a saga.
+
+Second, the whole write-ahead machinery existed because the store could not
+commit a transfer atomically. If it can, then the two-step reservation, the
+write-ahead record and the recovery are all unnecessary.
+
+So must the store apply a whole transfer atomically, and reverse the
+per-primitive model of ADR-0003?
 
 ## Decision Drivers
 
 * **Simplicity where it is safe.** Kuatia targets a single transactional
-  database (SQLite or PostgreSQL) or an in-process store. On each, a whole-commit
-  transaction is available and is the simplest correct primitive.
-* **Strict guards.** The overdraft floor and freeze/close checks should be
-  enforced atomically with the write, not best-effort.
+  database (SQLite or PostgreSQL) or an in-process store. On each, a
+  whole-commit transaction is available and is the simplest correct primitive.
+* **Strict guards.** The overdraft floor and the freeze and close checks must
+  hold atomically with the write, and not as a best effort.
 * **No orphaned state.** An all-or-nothing commit leaves nothing for recovery to
   reconcile.
-* **One place for correctness.** Validation stays in the pure core; the store
-  enforces the stateful guards inside its transaction. There is no third home
-  (the saga's count-contract) to keep in sync.
+* **One place for correctness.** Validation stays in the pure core. The store
+  enforces the stateful guards inside its transaction. There is no third home to
+  keep in step, and the saga's count contract was that third home.
 
 ## Considered Options
 
@@ -46,92 +54,109 @@ per-primitive model?
 
 **Pros:**
 
-* Composes across multiple resources/shards without a database transaction.
+* Good, because it composes across several resources and several shards, and it
+  needs no database transaction.
 
 **Cons:**
 
-* The write-ahead record, phase tracking, and roll-forward recovery are a large
-  surface that exists solely to stitch non-atomic primitives together.
-* The floor and freeze/close guards stay best-effort under concurrency.
+* Bad, because the write-ahead record, the tracked phases and the roll-forward
+  recovery are a large surface. That surface exists only to join primitives that
+  are not atomic.
+* Bad, because the floor, the freeze guard and the close guard all stay
+  best-effort under concurrency.
 
 #### Option 2: Atomic storage commit (chosen)
 
-Add one `CommitStore` sub-trait with `commit_envelope` and `commit_transition`,
-each applied in a single store transaction (SQL: one `BEGIN..COMMIT`; in-memory:
-all relevant locks held across the apply). The pure core still validates first;
-the transaction re-checks the three stateful guards inside it: double-spend
-(the delete-affected-count is the atomic single-winner claim), freeze/close, and
-the overdraft floor (summed in Rust from the live rows, never in SQL).
+Add one `CommitStore` sub-trait, with `commit_envelope` and `commit_transition`.
+Each one applies in one store transaction. On SQL that is one `BEGIN..COMMIT`.
+In memory it holds every relevant lock across the apply.
+
+The pure core still validates first. The transaction then re-checks the three
+stateful guards inside itself:
+
+* Double-spend. The delete-affected-count is the atomic single-winner claim.
+* Freeze and close.
+* The overdraft floor. Rust sums it from the live rows, and SQL never does.
 
 **Pros:**
 
-* Deletes the reservation two-step, `PendingSaga`/`PendingTransition`,
-  `Ledger::recover`, and the `SagaStore` keyspace. A crash cannot half-apply a
-  commit, so there is nothing to recover.
-* The floor and freeze/close guards become strict, removing the ADR-0003
-  best-effort consequence.
-* `legend` and the count-contract helpers are removed; multi-transfer
-  composition is a plain LIFO runner (`run_movements`) over `commit` / `reverse`.
+* Good, because it deletes the two-step reservation, `PendingSaga`,
+  `PendingTransition`, `Ledger::recover` and the `SagaStore` keyspace. A crash
+  cannot half-apply a commit, so there is nothing to recover.
+* Good, because the floor, the freeze guard and the close guard all become
+  strict. That removes the best-effort consequence of ADR-0003.
+* Good, because `legend` and the count-contract helpers go. A composition of
+  several transfers is then a plain runner, `run_movements`, over `commit` and
+  `reverse`, which unwinds in last-in-first-out order.
 
 **Cons:**
 
-* Crash-safety is pinned to a per-backend transaction: it does not compose across
-  shards or multiple databases. This forecloses the cross-shard UTXO ambition
-  ADR-0002/0003 kept open, which is an accepted trade for a single-database
-  library.
-* On SQLite, `pool.begin()` is a deferred transaction; the delete-affected-count
-  remains the double-spend backstop, the same property the prior design relied
-  on.
+* Bad, because crash-safety now rests on a transaction inside one backend. It
+  composes across neither a shard nor a second database. That closes the
+  cross-shard UTXO ambition that ADR-0002 and ADR-0003 kept open, and this
+  record accepts that trade for a single-database library.
+* Bad, because `pool.begin()` on SQLite is a deferred transaction. The
+  delete-affected-count stays the backstop against a double-spend, which is the
+  same property the earlier design depended on.
 
 ## Decision Outcome
 
-Chosen: **Option 2.** The store owns the atomic commit boundary; the reservation
-index, write-ahead recovery, `SagaStore`, and `legend` are removed. This
-supersedes ADR-0003 and refines ADR-0002 (there is no longer a saga pipeline for
-a single commit). ADR-0020's transition recovery is subsumed by the atomic
-`commit_transition`, and ADR-0021's commit-safety map moves the double-spend,
-floor, and freeze/close guards into `commit_envelope`.
+Chosen: **Option 2.** The store owns the atomic commit boundary. The reservation
+index, the write-ahead recovery, `SagaStore` and `legend` all go.
+
+This supersedes ADR-0003. It refines ADR-0002, because there is no saga pipeline
+for one commit any more. The atomic `commit_transition` takes over the
+transition recovery of ADR-0020. The commit-safety map of ADR-0021 moves the
+double-spend guard, the floor and the freeze and close guards into
+`commit_envelope`.
 
 ### Positive Consequences
 
-* Fewer moving parts: no write-ahead log, no recovery, no saga VM.
-* Strict floor and freeze/close guards.
-* One validation home (pure core) plus one enforcement home (the store
-  transaction).
+* Fewer parts. There is no write-ahead log, no recovery and no saga machine.
+* The floor, the freeze guard and the close guard are all strict.
+* One home for validation, the pure core, plus one home for enforcement, the
+  store transaction.
 
 ### Negative Consequences
 
-* No cross-shard / multi-resource commit. If that is ever needed, it is a new
-  design, not a tweak to this one (see the next section for where it would live).
-* The generic `reserve_postings` / `release_postings` posting primitives are now
-  unused by the commit path; they remain as conformance-tested plumbing and can
-  be removed in a follow-up.
+* There is no commit across a shard and none across several resources. If
+  anything ever needs one, that is a new design and not a change to this one.
+  The next section says where it belongs.
+* The commit path no longer uses the general `reserve_postings` and
+  `release_postings` primitives. They stay as code that the conformance suite
+  tests, and a later change can remove them.
 
 ## When a saga is the right tool (and why not here)
 
-Removing the saga is not a verdict against the pattern. A saga earns its keep
-when a workflow spans **moving pieces that cannot share one transaction**:
-multiple services, multiple databases, or a sharded store where a single commit
-cannot reach every partition. There it sequences local steps and compensates the
-completed ones on failure, buying atomicity the underlying resources cannot
-provide on their own, and it pays for that with write-ahead records, phase
-tracking, and compensation logic.
-
-Kuatia was not that case. Every primitive the commit saga orchestrated
-(`reserve`, `deactivate`, `insert`, `store_transfer`, `append_event`) lived in
-**one** store behind **one** transactional boundary. The saga was coordinating
-pieces that were already coupled, so it reimplemented in application code the
-atomicity the database already provides for free. When a single ACID transaction
-is available, that transaction is the simpler and stricter primitive, and the
-saga is ceremony around it.
-
-The escape hatch stays open, but it belongs one layer down. If a storage backend
-ever shards its data so that a transfer's postings span partitions no single
-transaction can cover, **that backend** implements
-`CommitStore::commit_envelope` with an internal saga (two-phase commit, per-shard
-local transactions plus compensation, or similar). The `CommitStore` contract,
-apply the whole envelope atomically or reject it, says nothing about *how* a
-backend achieves atomicity. The saga would then live where the moving pieces
-actually are, and the ledger core stays oblivious: it still just calls
-`commit_envelope` and maps the outcome. The pattern moves to the layer that has
-the distribution problem, instead of sitting in the core that does not.
+The removal of the saga is not a verdict against the pattern. A saga earns its
+keep when a workflow spans **separate pieces that cannot share one
+transaction**. Several services are such pieces, and so are several databases,
+and so is a sharded store where one commit cannot reach every partition.
+
+There a saga sequences the local steps, and on a failure it compensates the
+steps that finished. It buys atomicity that the resources underneath cannot give
+on their own. It pays for that with a write-ahead record, tracked phases and
+compensation logic.
+
+Kuatia was not that case. Every primitive that the commit saga drove lived in
+**one** store, behind **one** transactional boundary, and those primitives were
+`reserve`, `deactivate`, `insert`, `store_transfer` and `append_event`.
+
+So the saga coordinated pieces that were coupled already. It re-implemented in
+application code the atomicity that the database gives for free. Where one ACID
+transaction is available, that transaction is the simpler and the stricter
+primitive, and a saga around it is ceremony.
+
+The escape route stays open, and it belongs one layer down. A storage backend
+can one day shard its data, so that the postings of a transfer span partitions
+that no single transaction covers. **That backend** then implements
+`CommitStore::commit_envelope` with a saga inside itself. A two-phase commit is
+one way, and a local transaction per shard plus compensation is another.
+
+The `CommitStore` contract says to apply the whole envelope atomically or to
+reject it. It says nothing about *how* a backend reaches that atomicity.
+
+So the saga then lives where those separate pieces are. The ledger core knows
+nothing of it, and still calls `commit_envelope` and maps the outcome. The
+pattern moves to the layer that has the distribution problem, and it leaves the
+core, which does not have one.

+ 97 - 92
doc/adr/0024-native-money-columns.md

@@ -10,35 +10,36 @@
 
 [ADR-0011](0011-swappable-money-backing.md) made the `Cent` backing a
 compile-time choice between `i64` and `i128`, and stored every amount as a
-decimal `TEXT` column. That hid the width and sidestepped the fact that neither
+decimal `TEXT` column. That hid the width and avoided the fact that neither
 backend has a native 128-bit integer. It also accepted a cost, recorded there:
 "the database cannot order or range-filter on the amount."
 
 That cost is now on the hot path. The in-transaction overdraft floor
 (`commit.rs::live_balance`) fetched every live posting row for an
-`(owner, asset)` pair, parsed each decimal string and folded them in Rust,
-inside the commit transaction, once per overdraft-forbidding account a transfer
-touches. `Ledger::compute_balance` did the same through the `Store` trait. The
-schema could not index, order or aggregate an amount at all.
+`(owner, asset)` pair. It parsed each decimal string and folded them in Rust,
+inside the commit transaction. It did that once for each account that forbids
+overdraft and that a transfer touches. `Ledger::compute_balance` did the same
+through the `Store` trait. The schema could not index, order or aggregate an
+amount at all.
 
-Can amounts be stored in a form the database understands, without reintroducing
-the two things text was protecting against: a width that leaks into the API, and
-inexact or wrapping money arithmetic?
+Can the ledger store an amount in a form the database understands? Text
+protected against two things, and neither must come back. One is a width that
+leaks into the API. The other is money arithmetic that is inexact or that wraps.
 
 ## Decision Drivers
 
-* An amount must survive the `i128` cargo feature being toggled without a
-  migration, so the stored width cannot be the backing's width.
+* An amount must survive a toggle of the `i128` cargo feature, with no
+  migration. So the stored width cannot be the width of the backing.
 * Summation must be exact and must fail loudly, never wrap and never round.
   Whatever does the addition, the guarantee has to match `Cent::checked_sum`.
-* The `Cent` API must keep the backing width out of public signatures, and the
+* The `Cent` API must keep the backing width out of public signatures. The
   content-addressed hash preimage (`to_canonical_bytes`, frozen by
-  `CANONICAL_VERSION`) must not change: switching backings must not rehash the
-  ledger.
+  `CANONICAL_VERSION`) must not change, because a change of the backing must not
+  rehash the ledger.
 * `sqlx::Any` is the whole SQL backend. Its value universe is
-  Bool/Int/Real/Text/Blob, and it never exposes the underlying driver handle.
-* A row should stay auditable. Amounts are where this is conceded, knowingly:
-  see the negative consequences.
+  Bool/Int/Real/Text/Blob, and it never exposes the driver handle below it.
+* A row must stay auditable. Amounts are the one place where this record gives
+  that up, deliberately: see the negative consequences.
 
 ## Considered Options
 
@@ -52,37 +53,37 @@ Change nothing.
 
 **Cons:**
 
-* Bad, because the overdraft floor keeps shipping one row per posting into the
-  commit transaction, which is the cost that motivated this ADR.
-* Bad, because no amount column can ever be indexed, ordered or range-filtered,
-  which also blocks pushing greedy largest-first posting selection
-  (ADR-0001/0005) into SQL later.
+* Bad, because the overdraft floor still sends one row per posting into the
+  commit transaction, which is the cost that motivated this record.
+* Bad, because no amount column can ever be indexed, ordered or range-filtered.
+  That also blocks a later move of greedy largest-first posting selection
+  (ADR-0001/0005) into SQL.
 
 #### Option 2: Native columns, keeping `sqlx::Any`, with casts at the dialect seam
 
 `NUMERIC(39,0)` on PostgreSQL, a fixed 16-byte `BLOB` on SQLite. Amounts cross
-the `Any` boundary as `String` (Postgres) or `Vec<u8>` (SQLite), with the SQL
-carrying `CAST($n AS NUMERIC)` / `CAST(col AS TEXT)` on Postgres. SQLite gets a
+the `Any` boundary as `String` (Postgres) or `Vec<u8>` (SQLite), and the SQL on
+Postgres holds `CAST($n AS NUMERIC)` / `CAST(col AS TEXT)`. SQLite gets a
 registered `kuatia_i128_sum` aggregate; Postgres uses plain `SUM()`.
 
 **Pros:**
 
-* Good, because storage, indexing, ordering and aggregation are all native on
-  both backends.
+* Good, because storage, the index, the order and the aggregate are all native
+  on both backends.
 * Good, because both aggregates are exact: `NUMERIC` is arbitrary precision, and
   `kuatia_i128_sum` folds with `i128::checked_add` and raises on overflow.
-* Good, because the whole divergence lands in the existing `Dialect` seam
-  instead of spreading through the query code.
+* Good, because the whole divergence lands in the `Dialect` seam that is already
+  there, and it does not spread through the query code.
 
 **Cons:**
 
 * Bad, because PostgreSQL money still travels as decimal text, so a read pays a
   numeric → text → parse round trip.
-* Bad, because `AnyRow` converts every column's type before any column is read
-  and has no mapping for `NUMERIC`, so one forgotten cast fails the whole row.
-  `SELECT *` over a money table is therefore no longer allowed.
+* Bad, because `AnyRow` converts the type of every column before any column is
+  read, and it has no mapping for `NUMERIC`. So one forgotten cast fails the
+  whole row, and `SELECT *` over a money table is no longer allowed.
 * Bad, because SQLite function registration has to be process-global (see
-  below), which brings an ordering requirement and the first `unsafe` in the
+  below), which brings a requirement on order and the first `unsafe` in the
   repository.
 
 #### Option 3: Drop `sqlx::Any` for concrete `Pool<Sqlite>` / `Pool<Postgres>`
@@ -94,83 +95,86 @@ Write real `Type`/`Encode`/`Decode` impls per driver, so `Cent` binds as binary
 
 * Good, because money is native end to end, with no casts and no text hop.
 * Good, because `SqliteConnectOptions` can register the aggregate per
-  connection, with no global state and no ordering trap.
-* Good, because `SELECT *` keeps working and compile-time-checked queries
-  become possible.
+  connection, with no global state and no trap about order.
+* Good, because `SELECT *` still works, and compile-time-checked queries become
+  possible.
 
 **Cons:**
 
 * Bad, because every query in `account`/`posting`/`transfer`/`commit`/`event`/
-  `book`/`projection` must be duplicated per backend or made generic over a
-  `Database` bound, whose where-clauses fight "clarity over cleverness".
+  `book`/`projection` must be duplicated per backend, or made generic over a
+  `Database` bound. The where-clauses of that bound fight "clarity over
+  cleverness".
 * Bad, because it is a rewrite of the storage crate for a change whose payload
   is three columns.
 
 #### Option 4: Native columns, but implement `Type`/`Encode`/`Decode<Any>` for a `Cent` wrapper
 
-Instead of binding `String`/`Vec<u8>` and converting by hand, teach `Any` about
-`Cent` directly.
+Teach `Any` about `Cent` directly, rather than a hand-written bind of
+`String`/`Vec<u8>` and a hand-written conversion.
 
 **Pros:**
 
-* Good, because call sites would read `.bind(cent)` and `row.try_get::<Cent, _>()`.
+* Good, because call sites would read `.bind(cent)` and
+  `row.try_get::<Cent, _>()`.
 
 **Cons:**
 
 * Bad, because `AnyValueKind` and `AnyArgumentBuffer` are not re-exported from
-  the `sqlx` facade and are `#[doc(hidden)]` in `sqlx-core`, so this needs a
-  direct dependency on a crate whose own description says "not for direct use".
+  the `sqlx` facade, and they are `#[doc(hidden)]` in `sqlx-core`. So this needs
+  a direct dependency on a crate whose own description says "not for direct
+  use".
 * Bad, because it buys nothing: `AnyValueKind` has no numeric variant either, so
   the Postgres cast is still required.
 
 ## Decision Outcome
 
-Chosen option: **Option 2**. It gets the whole payload (native storage, exact
-in-database summation, orderable amounts) for a diff confined to the `Dialect`
-seam, two `row` helpers and one new module, where Option 3 is a rewrite of the
-storage crate and Option 4 buys nothing for a `#[doc(hidden)]` dependency.
+Chosen option: **Option 2**. It gets the whole payload, which is native storage,
+exact in-database summation and orderable amounts. The diff stays inside the
+`Dialect` seam, two `row` helpers and one new module. Option 3 is a rewrite of
+the storage crate, and Option 4 buys nothing for a `#[doc(hidden)]` dependency.
 
 Concretely:
 
 * **The stored form is always 128 bits wide**, whatever `Backing` is. Postgres
   uses `NUMERIC(39,0)`, which is exactly the decimal width of `i128`. SQLite
-  uses a 16-byte `BLOB`. Toggling the `i128` feature needs no migration, and a
-  database written under `i128` fails loudly when read under `i64` rather than
-  truncating.
+  uses a 16-byte `BLOB`. A toggle of the `i128` feature needs no migration. A
+  database written under `i128` fails loudly when it is read under `i64`, and it
+  truncates nothing.
 * **The SQLite encoding is offset-binary**: two's-complement big-endian with the
   sign bit flipped (`encode_storage_i128` in `kuatia-money`). SQLite compares
-  blobs byte-wise, and all amounts are exactly 16 bytes, so unsigned
+  blobs byte-wise, and all amounts are exactly 16 bytes. So unsigned
   lexicographic order *is* numeric order: `i128::MIN` is all zeros, `0` is
-  `0x80 00…`, `i128::MAX` is all `0xFF`. `ORDER BY value` and
-  `WHERE value > ?` are correct for free, which is what Postgres `NUMERIC` gives
-  natively — so both backends gain the same capability rather than diverging.
+  `0x80 00…`, `i128::MAX` is all `0xFF`. `ORDER BY value` and `WHERE value > ?`
+  are correct for free, which is what Postgres `NUMERIC` gives natively. Both
+  backends gain the same capability, and neither diverges.
 * **It is deliberately not the canonical hash encoding.** Two's-complement would
-  have made `to_storage_bytes` byte-identical to `to_canonical_bytes`, and a
-  cross-use of the frozen hash preimage would then have silently worked until
-  either encoding was touched. The flipped bit makes that mistake fail
+  have made `to_storage_bytes` byte-identical to `to_canonical_bytes`. A
+  cross-use of the frozen hash preimage would then have worked silently, until
+  someone touched either encoding. The flipped bit makes that mistake fail
   immediately.
-* **SQLite gets three registered functions**: `kuatia_i128_sum` (an aggregate
-  folding with `i128::checked_add`, raising on overflow or on any argument that
-  is not a 16-byte amount, and summing an empty group to zero rather than to
-  `NULL`), plus `kuatia_i128_from_text` and `kuatia_i128_to_text`. The scalars
-  do the 011 migration's conversion and let tooling built on this crate read a
-  column that is no longer human-readable.
+* **SQLite gets three registered functions**: the `kuatia_i128_sum` aggregate,
+  plus `kuatia_i128_from_text` and `kuatia_i128_to_text`. The aggregate folds
+  with `i128::checked_add`. It raises on overflow, and on any argument that is
+  not a 16-byte amount. It sums an empty group to zero rather than to `NULL`.
+  The scalars do the conversion in migration 011, and they let a tool built on
+  this crate read a column that is no longer human-readable.
 * **Registration is process-global**, via `sqlite3_auto_extension`, because
   `sqlx::Any` never exposes the `sqlite3*` handle (`AnyConnection.backend` is
-  private, so there is nothing to downcast). Callers use
+  private, so there is nothing to downcast). A caller uses
   `kuatia_storage_sql::install_drivers()` in place of
-  `sqlx::any::install_default_drivers()`, before connecting a pool.
-* **`PostingStore::live_balance` is a `Store` method**, so the ledger's
-  authoritative balance read goes through it too, with the in-memory backend
-  summing in Rust as the conformance oracle.
+  `sqlx::any::install_default_drivers()`, before it connects a pool.
+* **`PostingStore::live_balance` is a `Store` method**, so the authoritative
+  balance read of the ledger goes through it too. The in-memory backend sums in
+  Rust, as the conformance oracle.
 
 ### Positive Consequences
 
 * The in-transaction overdraft floor is one aggregate row instead of one row per
   live posting, and so is `Ledger::compute_balance`.
-* Amount columns can be ordered, compared and indexed on both backends. This
-  retires ADR-0011's accepted negative consequence and unblocks pushing posting
-  selection into SQL.
+* Amount columns can be ordered, compared and indexed on both backends. That
+  retires the negative consequence ADR-0011 accepted, and it unblocks a move of
+  posting selection into SQL.
 * The conformance suite cross-checks the database's sum against
   `Cent::checked_sum` over the same rows on every backend, so the two paths
   cannot drift apart silently.
@@ -179,38 +183,39 @@ Concretely:
 
 * PostgreSQL amounts still travel as decimal text under `sqlx::Any`, so a read
   costs a numeric → text → parse hop. Only the storage is native, not the wire.
-* Every Postgres `SELECT` touching money must go through `Dialect::money_read`.
-  A missed cast fails the entire row, and only the Postgres CI job catches it,
-  never the default SQLite run. `SELECT *` over a money table is banned, so a
-  future column added to `postings` will not be picked up automatically.
-* `install_drivers()` must run before the first connection is opened. `migrate()`
-  probes for the functions on SQLite and returns
-  `StoreError::Misconfigured` rather than a bare "no such function", but the
-  ordering requirement is real.
-* Registration affects every SQLite connection in the process, including ones
-  opened by unrelated libraries. The function names are prefixed accordingly.
+* Every Postgres `SELECT` that touches money must go through
+  `Dialect::money_read`. A cast that is left out fails the entire row, and only
+  the Postgres CI job catches it, never the default SQLite run. `SELECT *` over
+  a money table is banned, so a column added to `postings` later is not picked
+  up automatically.
+* `install_drivers()` must run before the first connection is opened.
+  `migrate()` probes for the functions on SQLite and returns
+  `StoreError::Misconfigured` rather than a bare "no such function", and the
+  requirement on order is still real.
+* Registration affects every SQLite connection in the process, and that covers a
+  connection an unrelated library opened. The function names are prefixed
+  accordingly.
 * A SQLite amount is no longer legible in a plain `sqlite3` CLI, which does not
-  have `kuatia_i128_to_text` and shows a blob. Reading one by hand there means
-  taking `hex(value)`, subtracting `0x80` from the leading byte and decoding a
+  have `kuatia_i128_to_text` and shows a blob. To read one by hand there, take
+  `hex(value)`, subtract `0x80` from the first byte, and read the result as a
   128-bit big-endian two's-complement integer. Identifier and payload columns
   are unaffected, and PostgreSQL `NUMERIC` stays fully legible.
 * `kuatia-storage-sql` now depends directly on `libsqlite3-sys`, a
   `links = "sqlite3"` crate. Only one version can exist in the graph, so the pin
-  must be kept in step with whatever `sqlx-sqlite` depends on; a sqlx bump is now
-  a deliberate event rather than a routine one.
+  must stay in step with whatever `sqlx-sqlite` depends on. A sqlx bump is now a
+  deliberate event rather than a routine one.
 * This introduces the first `unsafe` in the repository. It is confined to
-  `crates/kuatia-storage-sql/src/sqlite_ext.rs`. The one non-obvious hazard
-  there: `sqlite3_aggregate_context` returns memory aligned for 8 bytes, not the
-  16 an `i128` needs, so the accumulator holds raw bytes rather than an `i128`
-  field.
+  `crates/kuatia-storage-sql/src/sqlite_ext.rs`. There is one non-obvious hazard
+  there. `sqlite3_aggregate_context` returns memory aligned for 8 bytes, and not
+  the 16 an `i128` needs, so the accumulator holds raw bytes rather than an
+  `i128` field.
 
 ## Links
 
-* Supersedes the storage clause of
-  [ADR-0011](0011-swappable-money-backing.md) ("Storage serializes to string"),
-  and retires its negative consequence that the database cannot order or
-  range-filter on the amount. The `CentBacking` / cargo-feature decision itself
-  stands.
+* Supersedes the storage clause of [ADR-0011](0011-swappable-money-backing.md)
+  ("Storage serializes to string"). It also retires the negative consequence
+  that the database cannot order or range-filter on the amount. The
+  `CentBacking` / cargo-feature decision itself stands.
 * Amends [ADR-0009](0009-monetary-representation-integer-minor-units.md): the
   persisted form has now gone `BIGINT` → text → backend-native.
 * Amends [ADR-0023](0023-atomic-storage-commit.md): the overdraft floor is still

+ 87 - 31
doc/adr/0025-one-live-set-no-reservations.md

@@ -10,24 +10,46 @@
 
 ## Context and Problem Statement
 
-ADR-0023 made a commit one store transaction and deleted the write-ahead saga, but left the data model that saga had needed. A posting could be `Active`, `Reserved` by a `ReservationId`, or `Spent`, and six `Store` methods (`reserve_postings`, `release_postings`, `deactivate_postings`, `insert_postings`, `append_account_version`, `store_transfer`) remained as single-update primitives whose work the commit transaction now does inline.
+ADR-0023 made a commit one store transaction and deleted the write-ahead saga.
+It left behind the data model that the saga had needed. A posting could be
+`Active`, or `Reserved` by a `ReservationId`, or `Spent`.
 
-Nothing called them. Both backends hard-coded the unreserved side of the column in every commit statement, so `Reserved` was unreachable: the only way to observe one was for a test to reach through `Ledger::store()` and create it. ADR-0023 said as much and deferred the removal to a follow-up.
+Six `Store` methods also stayed as single-update primitives: `reserve_postings`,
+`release_postings`, `deactivate_postings`, `insert_postings`,
+`append_account_version` and `store_transfer`. The commit transaction now does
+their work inline.
 
-That leftover had three costs. `Ledger::store()` returns the whole trait, so the primitives were a public route to spend a posting or append an account version while skipping the double-spend, freeze/close and overdraft guards the commit transaction enforces. Each cost two backend implementations plus a block of conformance tests that pinned a contract with no caller. And `Live` (`Active ∪ Reserved`) and `Active` had become two names for the same rows, so code chose between them by habit rather than meaning.
+Nothing called them. Both backends wrote the unreserved side of the column into
+every commit statement, so nothing could reach `Reserved`. One route remained: a
+test could reach through `Ledger::store()` and create one. ADR-0023 said as much
+and left the removal to a later record.
+
+That leftover had three costs.
+
+`Ledger::store()` returns the whole trait, so the primitives were a public route
+to spend a posting or to append an account version. That route skipped the
+guards the commit transaction enforces, which are double-spend, freeze and
+close, and overdraft.
+
+Each primitive cost two backend implementations, plus a block of conformance
+tests that pinned a contract with no caller.
+
+And `Live`, which was `Active ∪ Reserved`, and `Active` had become two names for
+the same rows. So code chose between them by habit and not by what they say.
 
 ## Decision Drivers
 
-* A guard that can be bypassed by a public API is not a guard.
-* One concept should have one name. The `live_postings` table, the `live_balance` aggregate and `has_live_postings` all already said "live".
-* A backend author should have to implement only what the ledger calls.
+* A guard is not a guard when a public API can go around it.
+* One concept must have one name. The `live_postings` table, the `live_balance`
+  aggregate and `has_live_postings` all said "live" already.
+* A backend author must implement only what the ledger calls.
 * Conformance tests are worth more when they exercise the path production takes.
 
 ## Considered Options
 
 #### Keep the reservation vocabulary as dead but harmless
 
-Leave the types and primitives in place and only fix the documentation.
+Leave the types and the primitives in place, and fix the documentation alone.
 
 **Pros:**
 
@@ -36,59 +58,93 @@ Leave the types and primitives in place and only fix the documentation.
 **Cons:**
 
 * Bad, because the bypass through `Ledger::store()` stays open.
-* Bad, because the next reader has to discover empirically that `Reserved` cannot happen, and the schema keeps a column that nothing writes.
+* Bad, because the next reader has to find out by experiment that `Reserved`
+  cannot happen. The schema also keeps a column that nothing writes.
 
 #### Keep `PostingState::Reserved` for a future hold feature
 
-Retain the state on the theory that durable holds will want it.
+Keep the state, on the theory that a durable hold will want it.
 
 **Pros:**
 
-* Good, because a later hold feature would not need a new migration.
+* Good, because a later hold feature then needs no new migration.
 
 **Cons:**
 
-* Bad, because holds already exist and do not use it. ADR-0014 implements them as per-destination holding subaccounts, precisely so a hold is an ordinary balance rather than a lifecycle state.
-* Bad, because it keeps an unreachable variant in a public enum that every backend and every reader must account for.
+* Bad, because a hold exists already and does not use the state. ADR-0014
+  implements a hold as a per-destination holding subaccount, exactly so that a
+  hold is an ordinary balance rather than a lifecycle state.
+* Bad, because it keeps a variant that nothing can reach, inside a public enum.
+  Every backend and every reader must still account for it.
 
 #### Retire the reservation protocol entirely (chosen)
 
-Collapse `PostingState` to `Live | Spent | Missing` and `PostingFilter` to `Live | All`, delete `ReservationId`, `TransitionId` and the id generator behind them, delete the six primitives, drop `live_postings.reservation`, and seed the conformance suite through `commit_envelope`.
+Collapse `PostingState` to `Live | Spent | Missing`, and `PostingFilter` to
+`Live | All`. Delete `ReservationId`, `TransitionId` and the id generator behind
+them. Delete the six primitives. Drop `live_postings.reservation`. Seed the
+conformance suite through `commit_envelope`.
 
 **Pros:**
 
-* Good, because a posting's liveness becomes one fact: it is in `live_postings` or it is spent.
-* Good, because the atomic commit is the only posting write a backend has, so no caller can leave half a transfer applied.
-* Good, because the conformance suite now proves the commit path rather than a hand-rolled imitation of it.
+* Good, because the liveness of a posting becomes one fact. It is in
+  `live_postings`, or it is spent.
+* Good, because the atomic commit is the only posting write that a backend has.
+  So no caller can leave half a transfer applied.
+* Good, because the conformance suite now proves the commit path, and not an
+  imitation of it that someone wrote by hand.
 
 **Cons:**
 
-* Bad, because it breaks `Store` for any out-of-tree backend, and changes the serde representation of `PostingState`.
-* Bad, because the suite's seeds now require the accounts they reference to exist, which the removed `insert_postings` did not.
+* Bad, because it breaks `Store` for any backend outside this tree. It also
+  changes the serde representation of `PostingState`.
+* Bad, because a seed in the suite now needs the accounts it references to
+  exist. The `insert_postings` that this record removes did not need them.
 
 ## Decision Outcome
 
-Chosen option: retire the reservation protocol entirely. The middle state had no producer, no consumer and no feature waiting on it, and keeping it left a documented bypass of the commit guards.
+Chosen option: retire the reservation protocol entirely. The middle state had no
+producer and no consumer, and no feature waited on it. To keep it was to keep a
+documented route around the commit guards.
+
+`TransitionId` went with it. Nothing outside its own definition had ever
+referenced it.
 
-`TransitionId` went with it, having never been referenced outside its own definition.
+The `kuatia::saga` module becomes `kuatia::workflow`, and `run_movements`
+becomes `run_transfers`, which takes the transfers themselves. The unwind it
+performs across transfers, in last-in-first-out order, is real behaviour.
+Atomicity of one transfer does not give that. So only the name and the inputs
+change.
 
-The `kuatia::saga` module is renamed to `kuatia::workflow` and `run_movements` to `run_transfers`, taking the transfers themselves. The cross-transfer LIFO unwind it performs is real behaviour that single-transfer atomicity does not provide, so only the name and the inputs change; its own `Movement` type had shadowed `kuatia_types::Movement`, which means something else.
+Its own `Movement` type had shadowed `kuatia_types::Movement`, and that type
+means something else.
 
 ### Positive Consequences
 
-* `PostingState` has no unreachable variant, and the SQL state probe reads one column fewer.
-* The in-memory backend holds one live map instead of two, so its commit has no cross-map claim to keep atomic.
-* Migration `012_drop_reservation` releases any row that still carried a token. That row was never consumed, so it always counted toward the balance, and the saga that owned the token no longer exists to finalize or release it.
+* `PostingState` has no variant that nothing can reach, and the SQL state probe
+  reads one column fewer.
+* The in-memory backend holds one live map rather than two. So its commit has no
+  claim across two maps to keep atomic.
+* Migration `012_drop_reservation` releases any row that still carried a token.
+  Nothing ever consumed that row, so it always counted toward the balance. The
+  saga that owned the token no longer exists to finalize it or release it.
 
 ### Negative Consequences
 
-* Breaking for out-of-tree `Store` implementors and for anyone matching on `PostingState::Active` or persisting its serde form.
-* `close_rejects_reserved_postings` asserted a state that is no longer representable and is gone. It is replaced by the half of the close guard that was untested: an account whose postings have all been spent can be closed.
+* This breaks an out-of-tree `Store` implementation. It also breaks any code
+  that matches on `PostingState::Active`, or that persists its serde form.
+* `close_rejects_reserved_postings` asserted a state that has no representation
+  now, so it is gone. In its place is the half of the close guard that no test
+  covered: an account whose postings are all spent can close.
 
 ## Links
 
-* Follows [ADR-0023](0023-atomic-storage-commit.md), which made the commit atomic and deferred this removal.
-* Supersedes [ADR-0006](0006-reservation-protocol-posting-lifecycle.md), the reservation protocol itself.
-* Supersedes the `reservation` column of [ADR-0022](0022-merged-live-postings-hot-index.md).
-* Amends [ADR-0008](0008-conformance-tested-storage.md): the suite seeds through the commit path, not through write primitives.
-* Holds are unaffected: [ADR-0014](0014-inflight-holds-via-holding-accounts.md) uses holding subaccounts, never reserved postings.
+* Follows [ADR-0023](0023-atomic-storage-commit.md), which made the commit
+  atomic and deferred this removal.
+* Supersedes [ADR-0006](0006-reservation-protocol-posting-lifecycle.md), the
+  reservation protocol itself.
+* Supersedes the `reservation` column of
+  [ADR-0022](0022-merged-live-postings-hot-index.md).
+* Amends [ADR-0008](0008-conformance-tested-storage.md). The suite seeds through
+  the commit path and not through a write primitive.
+* A hold is unaffected. [ADR-0014](0014-inflight-holds-via-holding-accounts.md)
+  uses a holding subaccount and never a reserved posting.

+ 89 - 33
doc/adr/0026-public-api-vocabulary.md

@@ -9,28 +9,48 @@
 
 ## Context and Problem Statement
 
-ADR-0025 finished removing the saga-era data model, which left the surface a caller actually touches as the last place still shaped by decisions that no longer hold. Four things in particular made the library read like its own internals:
+ADR-0025 finished the removal of the data model from the saga era. That left the
+surface a caller touches as the last place which decisions that no longer hold
+had shaped. Four things in particular made the library read like its own
+internals:
 
-`commit`, `commit_envelope`, `reverse`, the five inflight entry points and the multi-transfer runner all took the ledger as `&Arc<Self>`, so the first line of every program using the library wrapped one. No body touched the `Arc`: the commit path spawned work under the saga, and the spawning left with it.
+`commit`, `commit_envelope`, `reverse`, the five inflight entry points and the
+multi-transfer runner all took the ledger as `&Arc<Self>`. So the first line of
+every program that used the library wrapped one.
 
-`TransferBuilder` had `movement`, `movement_ref`, `pay` and `pay_ref` pushing the same `Movement`. ADR-0012 introduced the `_ref` pair to move "between specific subaccounts" while the plain spellings moved "between main accounts", but both take a full `AccountId` and `AccountId::new(id)` is `with_sub(id, 0)`, so the distinction had no referent.
+No method body touched the `Arc`. The commit path had spawned work under the
+saga, and that spawn left with the saga.
 
-The API said transfer while its types said envelope: `Receipt.transfer_id` was an `EnvelopeId`, `history()` returned `EnvelopeRecord`s, and `get_transfer` took an `&EnvelopeId`.
+`TransferBuilder` had `movement`, `movement_ref`, `pay` and `pay_ref`, and all
+four pushed the same `Movement`. ADR-0012 added the `_ref` pair to move between
+specific subaccounts, while the plain names moved between main accounts.
 
-Four public methods answered "what is the balance" with nothing to tell a caller which to reach for, one of them (`append_cache_point`) being cache maintenance and two of them (`with_snapshot_interval`, `with_projection_grace_ms`) knobs no caller outside the tests had ever set.
+But both take a full `AccountId`, and `AccountId::new(id)` is `with_sub(id, 0)`.
+So that distinction pointed at nothing.
+
+The API said transfer and its types said envelope. `Receipt.transfer_id` was an
+`EnvelopeId`. `history()` returned `EnvelopeRecord`s. `get_transfer` took an
+`&EnvelopeId`.
+
+Four public methods answered the question "what is the balance", and nothing
+told a caller which one to reach for. One of them, `append_cache_point`, was
+cache maintenance. Two of them, `with_snapshot_interval` and
+`with_projection_grace_ms`, were knobs that no caller outside the tests had ever
+set.
 
 ## Decision Drivers
 
-* Ceremony a caller cannot skip is worse than ceremony they opt into.
-* One concept, one name. Two names for one thing cost every reader the work of learning they are the same.
-* A name should say which of two similar operations a call site got.
-* Removing a published name is cheap now and expensive after 0.4.0 ships.
+* Ceremony that a caller cannot skip is worse than ceremony a caller chooses.
+* One concept, one name. Two names for one thing cost every reader the work to
+  learn that the two are the same.
+* A name must say which of two similar operations a call site reached.
+* The removal of a published name is cheap now, and expensive after 0.4.0 ships.
 
 ## Considered Options
 
 #### Leave the surface and document it better
 
-Write the distinctions down instead of removing them.
+Write the distinctions down rather than remove them.
 
 **Pros:**
 
@@ -38,20 +58,24 @@ Write the distinctions down instead of removing them.
 
 **Cons:**
 
-* Bad, because the `Arc` and the `_ref` pair have nothing true to document: one is unused, the other names a difference that does not exist.
-* Bad, because documentation that exists to explain an avoidable choice is a cost paid on every read.
+* Bad, because the `Arc` and the `_ref` pair have nothing true to document.
+  Nothing uses the first. The second names a difference that does not exist.
+* Bad, because documentation that explains an avoidable choice is a cost on
+  every read.
 
 #### Rename `Envelope` to `Transfer` throughout, collapsing the pair
 
-Make the resolved form and the intent share one word.
+Give the resolved form and the intent one shared word.
 
 **Pros:**
 
-* Good, because one word would cover the whole pipeline.
+* Good, because one word then covers the whole pipeline.
 
 **Cons:**
 
-* Bad, because the two are genuinely different: one is movements a caller wrote, the other is the postings to consume and create. Collapsing them would hide the resolve step that ADR-0005 deliberately exposes.
+* Bad, because the two are genuinely different. One is the movements that a
+  caller wrote. The other is the postings to consume and to create. One word for
+  both hides the resolve step that ADR-0005 exposes on purpose.
 
 #### Collapse `balance` and `compute_balance` into one method
 
@@ -59,36 +83,68 @@ One way to ask for a balance.
 
 **Cons:**
 
-* Bad, because the whole of `tests/projection.rs` is a differential test between two independent derivations of the same number, and `compute_balance` is the oracle. With one method there is nothing left to compare against, and a dropped tail or an off-by-one in the fold stops being observable.
-* Bad, because the commit path must read the authoritative sum to enforce the overdraft floor, never the cache (ADR-0019 item 6).
+* Bad, because all of `tests/projection.rs` is a differential test. It compares
+  two independent derivations of the same number, and `compute_balance` is the
+  reference. With one method there is nothing left to compare against. A dropped
+  tail, or an error of one in the fold, is then no longer observable.
+* Bad, because the commit path must read the authoritative sum to enforce the
+  overdraft floor. It must never read the cache (ADR-0019, item 6).
 
 #### Fix the four separately, keeping every distinction that is real (chosen)
 
 ## Decision Outcome
 
-Chosen option: remove what was unused or duplicated, rename what was misleading, and keep every distinction with something behind it.
-
-* Every method takes `&self`. A caller who wants to share a ledger still wraps it in an `Arc`, which derefs; the signature no longer decides for them.
-* `movement_ref` and `pay_ref` are gone. `movement` and `pay` both stay, the same call under two names, because an exchange commits two legs that are not payments and most callers are paying someone.
-* `EnvelopeId` is `TransferId` and `EnvelopeRecord` is `TransferRecord`. `Envelope` and `EnvelopeBuilder` keep their names, so the everyday surface says transfer and the resolved interior that `resolve` and `commit_envelope` expose says envelope.
-* `compute_balance` is `balance_exact`, beside `balance`. `append_cache_point` moves to a `Projection` handle from `Ledger::projection()`, and the two knobs become one `ProjectionConfig`.
+Chosen option: remove what nothing used and what was a duplicate, rename what
+misled a reader, and keep every distinction that has something behind it.
+
+* Every method takes `&self`. A caller that wants to share a ledger still wraps
+  it in an `Arc`, which derefs. The signature no longer decides that for the
+  caller.
+* `movement_ref` and `pay_ref` are gone. `movement` and `pay` both stay, as the
+  same call under two names. An exchange commits two legs that are not payments,
+  and most callers do pay someone.
+* `EnvelopeId` is `TransferId` now, and `EnvelopeRecord` is `TransferRecord`.
+  `Envelope` and `EnvelopeBuilder` keep their names. So the everyday surface
+  says transfer, and the resolved interior that `resolve` and `commit_envelope`
+  expose says envelope.
+* `compute_balance` is `balance_exact` now, and it sits beside `balance`.
+  `append_cache_point` moves to a `Projection` handle that
+  `Ledger::projection()` returns. The two knobs become one `ProjectionConfig`.
 
 ### Positive Consequences
 
-* The README example lost its first line, and none of the five examples mentions `Arc`.
+* The README example lost its first line, and not one of the five examples
+  mentions `Arc`.
 * A call site says whether it took the cached read or the exact one.
-* The rename changes nothing stored. `TransferId` is a newtype over `[u8; 32]` whose `ToBytes` is a byte passthrough, serde discards a newtype's struct name, the event dedup key hexes the inner bytes, and `TransferRecord` is decomposed into columns rather than serialized. No migration, and the schema already said transfer throughout.
-* `Ledger::projection()` gives the as-of and rebuild reads on the roadmap somewhere to land.
+* The rename changes nothing in storage. `TransferId` is a newtype over
+  `[u8; 32]`, and its `ToBytes` passes the bytes straight through. Serde
+  discards the struct name of a newtype. The event dedup key hexes the inner
+  bytes. `TransferRecord` goes into columns rather than into one serialized
+  blob. So there is no migration, and the schema said transfer everywhere
+  already.
+* `Ledger::projection()` gives the as-of read and the rebuild read on the
+  roadmap a place to land.
 
 ### Negative Consequences
 
-* Breaking on every one of the four counts for anyone already calling the library: the `_ref` methods, both type names, `compute_balance`, `append_cache_point` and the two knobs.
-* `movement` and `pay` remain two names for one call, which is a deliberate exception to the rule this record argues for.
-* The accepted ADRs still say `EnvelopeId` and `compute_balance`. A record is not edited to match later code, so the old spelling stays wherever it was written.
+* This breaks a caller that already uses the library, on each of the four
+  counts. Those are the `_ref` methods, both type names, `compute_balance`,
+  `append_cache_point`, and the two knobs.
+* `movement` and `pay` stay as two names for one call. That is a deliberate
+  exception to the rule this record argues for.
+* The accepted records still say `EnvelopeId` and `compute_balance`. Nobody
+  edits a record to match later code, so each old name stays where its author
+  wrote it.
 
 ## Links
 
-* Follows [ADR-0025](0025-one-live-set-no-reservations.md), which removed the data model these shapes served.
-* Supersedes the `TransferBuilder` clause of [ADR-0012](0012-subaccounts.md): the `_ref` methods it introduced are gone, and subaccount movement needs no separate spelling.
-* Keeps [ADR-0019](0019-cached-balance-projection.md) item 5 intact under a new name, and moves the maintenance call it describes onto `Ledger::projection()`.
-* Leaves [ADR-0005](0005-intent-api-movements-vs-envelopes.md)'s intent/envelope split in place; only the id and record types stop borrowing the internal word.
+* Follows [ADR-0025](0025-one-live-set-no-reservations.md), which removed the
+  data model these shapes served.
+* Supersedes the `TransferBuilder` clause of [ADR-0012](0012-subaccounts.md).
+  The `_ref` methods that it added are gone, and a movement between subaccounts
+  needs no separate name.
+* Keeps [ADR-0019](0019-cached-balance-projection.md) item 5 intact under a new
+  name, and moves the maintenance call it describes onto `Ledger::projection()`.
+* Leaves the split between intent and envelope from
+  [ADR-0005](0005-intent-api-movements-vs-envelopes.md) in place. Only the id
+  type and the record type give up the internal word.

+ 96 - 30
doc/adr/0027-value-date-separate-from-commit-time.md

@@ -10,16 +10,38 @@
 
 ## Context and Problem Statement
 
-Every transfer was stamped with `now_millis()` at commit and nothing else, so the ledger knew when an entry was recorded and never when it takes effect. Banks and fintechs need both: an entry booked today can be valued last week (a correction, a late settlement) or next week (a future-dated standing order), and a period report asks for the entries *valued* in that period, not the ones typed in it. Transfer queries filtered only on the commit clock, so period-correct reporting was not expressible.
+A commit stamped every transfer with `now_millis()` and nothing else. So the
+ledger knew when it recorded an entry, and never knew when that entry takes
+effect.
 
-The obvious shape, letting a caller set `created_at`, is unsafe here. `created_at` is the clock the balance cache folds its tail against: `balance` reads the closest cache point and adds every transfer committed after its watermark. A backdated `created_at` would place a transfer behind an existing watermark, so the cached `balance` would silently omit it while `balance_exact` included it, breaking the invariant the projection suite exists to assert.
+A bank and a fintech both need both dates. An entry that the ledger books today
+can be valued last week, as a correction or a late settlement. It can be valued
+next week, as a standing order with a future date. A report for a period asks
+for the entries *valued* in that period, and not the entries that someone typed
+in it.
+
+A transfer query filtered on the commit clock alone. So nothing could express a
+report that is correct for a period.
+
+The obvious shape is unsafe here, and that shape is a `created_at` that the
+caller sets. `created_at` is the clock that the balance cache folds its tail
+against. `balance` reads the closest cache point, then adds every transfer that
+committed after that point's watermark.
+
+A backdated `created_at` would place a transfer behind a watermark that exists.
+The cached `balance` would then leave that transfer out without a word, and
+`balance_exact` would include it. That breaks the invariant which the projection
+suite exists to assert.
 
 ## Decision Drivers
 
-* A period report is worth nothing if the date it groups by is the typist's clock.
-* The balance cache's correctness depends on one clock meaning one thing.
+* A report for a period is worth nothing when the date it groups by is the clock
+  of the person who typed the entry.
+* The correctness of the balance cache depends on one clock that means one
+  thing.
 * A value date is a business fact that a timezone must not be able to shift.
-* The duplicate-transfer trap (ADR-0026) should not reopen on backdated entries.
+* The trap of a duplicate transfer (ADR-0026) must not reopen on a backdated
+  entry.
 
 ## Considered Options
 
@@ -31,61 +53,105 @@ The obvious shape, letting a caller set `created_at`, is unsafe here. `created_a
 
 **Cons:**
 
-* Bad, because it breaks cached balances, as above. The failure is silent and the two balance reads disagree.
-* Bad, because one column would then mean two things, and no later reader could tell which.
+* Bad, because it breaks a cached balance, as above. The failure says nothing,
+  and the two balance reads then disagree.
+* Bad, because one column would then mean two things, and no later reader could
+  tell which one it meant.
 
 #### A separate `value_date`, outside the content address
 
 **Pros:**
 
-* Good, because a value date entered wrongly could be corrected in place.
+* Good, because a correction could then fix a wrong value date in place.
 
 **Cons:**
 
-* Bad, because two backdated deposits of the same amount to the same account would still collapse into one transfer unless the caller also set a reference, so ADR-0026's trap stays open on exactly the path where a correction is most likely.
-* Bad, because a mutable field on an otherwise immutable record invites a second one.
+* Bad, because two backdated deposits of one amount to one account would still
+  collapse into one transfer, unless the caller also set a reference. So the
+  trap of ADR-0026 stays open on exactly the path where a correction is most
+  likely.
+* Bad, because a mutable field on a record that is otherwise immutable invites a
+  second mutable field.
 
 #### A separate `value_date`, inside the content address (chosen)
 
 **Pros:**
 
-* Good, because the commit clock keeps its single meaning and the balance cache is untouched.
-* Good, because two entries differing only in the day they take effect are two transfers, which closes the duplicate trap for dated entries without a reference.
-* Good, because the date is covered by the same tamper evidence as the rest of the entry.
+* Good, because the commit clock still means one thing, and nothing touches the
+  balance cache.
+* Good, because two entries that differ only in the day they take effect are two
+  transfers. That closes the duplicate trap for a dated entry, and the caller
+  needs no reference.
+* Good, because the same tamper evidence covers the date and the rest of the
+  entry.
 
 **Cons:**
 
-* Bad, because a value date cannot be corrected in place: an entry valued wrongly is reversed and reposted.
-* Bad, because the preimage changed, so `CANONICAL_VERSION` is bumped and content addresses computed under an earlier version do not reproduce.
+* Bad, because nothing can correct a value date in place. The ledger reverses an
+  entry with a wrong value and reposts it.
+* Bad, because the preimage changed. So `CANONICAL_VERSION` moves up, and a
+  content address that something computed under an earlier version does not come
+  back the same.
 
 ## Decision Outcome
 
-Chosen option: a separate `ValueDate` on `Transfer` and `Envelope`, inside the content address.
+Chosen option: a separate `ValueDate` on `Transfer` and `Envelope`, inside the
+content address.
+
+`ValueDate` is a calendar day, held as days since 1970-01-01, and it is not an
+instant. A value date is a business fact. An entry valued 20 November is valued
+20 November wherever a reader reads it, and an instant would tie that to the
+reader's timezone.
 
-`ValueDate` is a calendar day held as days since 1970-01-01, not an instant, because a value date is a business fact: an entry valued 20 November is valued 20 November wherever it is read, and an instant would make that depend on a reader's timezone. `ValueDate::new` rejects a date that does not exist, so `TransferBuilder::value_date` stays infallible and does not repeat the mid-chain `Result` that `deposit` has.
+`ValueDate::new` rejects a date that does not exist. So
+`TransferBuilder::value_date` stays infallible, and it does not repeat the
+`Result` that sits mid-chain on `deposit`.
 
-`None` means the entry takes effect the day it was committed, and is tagged in the preimage rather than omitted, so "no value date" and "valued on day zero" cannot encode identically.
+`None` means the entry takes effect on the day of its commit. The preimage tags
+that case rather than leaves it out. So "no value date" and "valued on day zero"
+cannot encode to the same bytes.
 
-A reversal carries the original's value date, so the period an entry landed in is the period it is undone in. A compensating entry valued later would leave the first period still reporting the amount it is meant to cancel. A caller who wants it dated otherwise builds the envelope and commits that.
+A reversal carries the value date of the original. So the period an entry landed
+in is the period of its reversal. A compensating entry with a later value would
+leave the first period with a report of the amount that the entry is meant to
+cancel. A caller that wants another date builds the envelope and commits that.
 
-`TransferQuery` gains `from_value_date` and `to_value_date`, kept apart from `from_ts` and `to_ts` because a report asks for one clock or the other, never both at once. An entry with no value date falls outside an explicit window rather than inside every one.
+`TransferQuery` gains `from_value_date` and `to_value_date`. They stay apart
+from `from_ts` and `to_ts`, because a report asks for one clock or the other and
+never for both at once. An entry with no value date falls outside an explicit
+window, rather than inside every window.
 
-Migration 013 adds a nullable `transfers.value_date` column with an index. It is a filterable projection of the envelope's field, written at commit and never read back, so the database can answer a period query without loading every candidate row. The `book` column is the same arrangement.
+Migration 013 adds a nullable `transfers.value_date` column, with an index. It
+is a projection of the envelope's field that a filter can use. A commit writes
+it, and nothing reads it back. So the database can answer a query for a period
+and load no candidate row. The `book` column is the same arrangement.
 
 ### Positive Consequences
 
-* Period-correct reporting is expressible, and the as-of balance and trial balance on the roadmap now have a date to group by.
-* A backdated deposit repeats safely without a reference, because the date distinguishes it.
-* The balance projection is untouched: `created_at` still means the instant the ledger committed the entry.
+* A report that is correct for a period is now expressible. The as-of balance
+  and the trial balance on the roadmap both have a date to group by.
+* A backdated deposit repeats safely with no reference, because the date
+  separates it from the first one.
+* Nothing touches the balance projection. `created_at` still means the instant
+  at which the ledger committed the entry.
 
 ### Negative Consequences
 
-* `CANONICAL_VERSION` moves to 6, so every content address changes. Acceptable in an unreleased cycle that has already changed them once, and the version byte exists to gate exactly this.
-* Correcting a value date means reverse and repost, which is more ceremony than an update and is also the trail an auditor expects.
-* The value date is stored twice, in the envelope JSON and in its own column. The column is derived and never read back, the same compromise `book` already makes for the same reason.
+* `CANONICAL_VERSION` moves to 6, so every content address changes. That is
+  acceptable in a cycle that has not shipped, and which already changed them
+  once. The version byte exists to gate exactly this.
+* A correction to a value date means a reverse and a repost. That is more
+  ceremony than an update, and it is also the trail an auditor expects.
+* The ledger stores the value date twice, in the envelope JSON and in its own
+  column. The column is derived, and nothing reads it back. `book` already makes
+  the same compromise, for the same reason.
 
 ## Links
 
-* Follows [ADR-0026](0026-public-api-vocabulary.md), whose `reference` closed the duplicate-transfer trap this extends to dated entries.
-* Constrained by [ADR-0019](0019-cached-balance-projection.md): the cache folds its tail by commit time, which is why the value date had to be a new field.
-* Extends [ADR-0010](0010-event-stream-vs-transfer-log.md)'s transfer log with the second date a reporting caller needs.
+* Follows [ADR-0026](0026-public-api-vocabulary.md). Its `reference` closed the
+  trap of a duplicate transfer, and this record extends that to a dated entry.
+* Constrained by [ADR-0019](0019-cached-balance-projection.md). The cache folds
+  its tail by commit time, which is the reason the value date needed a new
+  field.
+* Extends the transfer log of [ADR-0010](0010-event-stream-vs-transfer-log.md),
+  with the second date that a caller needs for a report.

+ 119 - 40
doc/adr/0028-amount-carries-its-asset.md

@@ -11,15 +11,37 @@
 
 ## Context and Problem Statement
 
-A `Cent` is a signed integer of minor units and nothing else. It adds to and compares with any other `Cent`, so two balances read from one ledger in two assets could be summed into a number denominated in nothing. Inside the ledger that discipline held: conservation buckets by `.entry(posting.asset)`, the resolve algorithm keys net debits on `(from, asset)`, and a wrong fold is caught by the conservation check. The leak was on the way out. `Ledger::balance` returned a bare `Cent` and `SubAccountBalance` dropped the asset entirely, so the mistake happened in the caller, after the ledger had answered, where no invariant could reach it.
+A `Cent` is a signed integer of minor units and nothing else. It adds to and
+compares with any other `Cent`. So a caller could sum two balances of two assets
+from one ledger, and get a number denominated in nothing.
 
-The second half of the problem is precision. ADR-0009 put scale outside the value, in a presentation-only parser named `Amount`, and recorded the consequence it accepted: "the type system does not bind a `Cent` to its asset's decimal places, so callers must format/parse with the right `Amount` for the asset." With no registry in the ledger, an `AssetId` was opaque: 100 of asset 1 could be a dollar or a hundred of them, and the only thing that knew was whichever application was formatting. The demo dashboard carried its own hardcoded table of codes and decimals for exactly that reason.
+Inside the ledger that discipline held. Conservation buckets by
+`.entry(posting.asset)`, and the resolve algorithm keys net debits on
+`(from, asset)`. The conservation check catches a wrong fold. The leak was on
+the way out. `Ledger::balance` returned a bare `Cent`, and `SubAccountBalance`
+dropped the asset. So the mistake happened in the caller, after the ledger
+answered, where no invariant could reach it.
+
+The second half of the problem is precision. ADR-0009 put scale outside the
+value, in a presentation-only parser named `Amount`. It also recorded the
+consequence it accepted:
+
+> the type system does not bind a `Cent` to its asset's decimal places, so
+> callers must format/parse with the right `Amount` for the asset.
+
+The ledger had no registry, so an `AssetId` was opaque. 100 of asset 1 could be
+one dollar or a hundred of them. The only component that knew was the
+application that formatted the value. The demo dashboard carried its own
+hardcoded table of codes and decimals for exactly that reason.
 
 ## Decision Drivers
 
-* The bug the library cannot catch is the one in the caller's hands, so the fix has to be in what the caller is handed.
-* A decimal string a person writes needs a scale to become minor units, and the asset is the only honest place for that scale to come from.
-* The content address and the amount columns are frozen; a vocabulary change must not move either.
+* The bug the library cannot catch is the one in the hands of the caller. So the
+  fix has to be in what the caller gets.
+* A decimal string that a person writes needs a scale to become minor units. The
+  asset is the only honest source of that scale.
+* The content address and the amount columns are frozen; a vocabulary change
+  must not move either.
 * The pure core stays IO-free and deterministic.
 * `kuatia-money` is a leaf crate that cannot see an `AssetId`.
 
@@ -33,12 +55,15 @@ The second half of the problem is precision. ADR-0009 put scale outside the valu
 
 **Cons:**
 
-* Bad, because it is what ADR-0009 already chose, and the hazard it documented is the one that keeps biting.
-* Bad, because a decimal string still has nowhere to learn its precision, so every application rebuilds the dashboard's table.
+* Bad, because it is what ADR-0009 already chose, and the hazard it documented
+  is the one that still happens.
+* Bad, because a decimal string still has nowhere to learn its precision, so
+  every application rebuilds the dashboard's table.
 
 #### An amount that carries scale rather than an asset
 
-`Amount { asset: AssetId, value: Cent, decimals: u8 }`, with the precision copied in at construction.
+`Amount { asset: AssetId, value: Cent, decimals: u8 }`, with the precision
+copied in at construction.
 
 **Pros:**
 
@@ -46,57 +71,111 @@ The second half of the problem is precision. ADR-0009 put scale outside the valu
 
 **Cons:**
 
-* Bad, because it contradicts ADR-0009's outcome by putting scale on the value, and duplicates registry state into every amount in the process.
+* Bad, because it puts scale on the value, which contradicts the outcome of
+  ADR-0009. It also duplicates registry state into every amount.
 * Bad, because two amounts of one asset could disagree about its precision.
 
 #### An amount carrying `Arc<Asset>`, with a registry in the ledger
 
 **Pros:**
 
-* Good, because the asset's own row answers both questions: what the amount is denominated in, and at what scale its written form parses.
-* Good, because an amount cannot be built without a registered asset, so the invariant is structural rather than a validation step.
-* Good, because it absorbs the application-level asset tables that exist only because the ledger had none.
+* Good, because the asset's own row answers both questions: what the amount is
+  denominated in, and at what scale its written form parses.
+* Good, because an amount cannot be built without a registered asset, so the
+  invariant is structural rather than a validation step.
+* Good, because it absorbs the application-level asset tables that exist only
+  because the ledger had none.
 
 **Cons:**
 
-* Bad, because a balance read now depends on the registry, so reading an unregistered asset is an error where it used to be a number.
-* Bad, because `Arc<Asset>` cannot ride through serde without a resolver, which bounds how far it can reach.
+* Bad, because a balance read now depends on the registry. A read of an
+  unregistered asset is an error, where it was a number before.
+* Bad, because `Arc<Asset>` cannot ride through serde without a resolver, which
+  bounds how far it can reach.
 
 ## Decision Outcome
 
-Chosen option: **an amount carrying `Arc<Asset>`, with the registry in the ledger**, bounded to the public API.
-
-1. **`Asset`** is a registry row: `{ id, code, symbol, decimals }`, written once and never updated. Immutability is what makes the precision safe to rely on, since editing it would reinterpret every amount already recorded against the asset, and is also what makes the ledger's cache sound. `AssetStore` adds `create_asset`, `get_asset` and `list_assets`; migration `014_assets` stores the row as JSON beside its id, like books.
-
-2. **`Amount { asset: Arc<Asset>, value: Cent }`** lives in `kuatia-types`, not beside `Cent`, because `kuatia-money` has no dependency on the crate that defines `AssetId`. Conversion is the only way to build one, so no amount exists without an asset behind it. The tuple conversions follow one rule: an integer is minor units, a string is the written form at the asset's own scale. `(usd, 500)` and `(usd, "5.00")` are the same amount, and `(usd, "5.001")` fails rather than rounding.
-
-3. **`Arc<Asset>` stops at the public API.** `Posting`, `NewPosting`, `Movement`, `BalanceProjection`, the pure core's `(account, asset)` map keys and every storage row keep `AssetId`. `NewPosting` is serde-JSON inside the stored `transfers.transfer` column, and serde cannot hydrate an `Arc` without a registry to reach; the `Ledger` hydrates on the way out instead. Nothing stored changes, `CANONICAL_VERSION` stays at 6, and no transfer id moves.
-
-4. **The reads return amounts.** `balance`, `balance_exact` and `balance_as_of` return `Amount`, and `SubAccountBalance` carries one. `InsufficientFunds` gains its asset, so the two values in a shortfall name a quantity. Adding two assets is `AmountError::AssetMismatch`, refused at the call site that tries it.
-
-5. **The builder takes one amount per verb**, as `impl TryInto<Amount>`, and holds the first conversion failure until `build`. That keeps the chain fluent while making `build` fallible, which also retires `deposit`'s mid-chain `Result` (ADR-0026 left it as the one verb that broke the flow).
-
-6. **Commit refuses an unregistered asset.** Conservation puts every asset a transfer touches on the created side, so the created postings are the whole set to check. Validation itself pays nothing: it reads the authoritative live sum from the store, and an amount that reached it was built from a registered asset already.
-
-7. **The scale keeps its own name.** ADR-0009's `Amount` was a decimal-place count that parsed and formatted and was never stored. It is now `Scale`, and `ParseAmountError` is `ParseDecimalError`. ADR-0009 and ADR-0011 still say `Amount`, since an accepted record is not rewritten; this is where the rename lives.
+Chosen option: **an amount that carries `Arc<Asset>`, with the registry in the
+ledger**, bounded to the public API.
+
+1. **`Asset`** is a registry row: `{ id, code, symbol, decimals }`, written once
+   and never updated. Immutability is what makes the precision safe to rely on.
+   An edit would reinterpret every amount already recorded against the asset.
+   Immutability is also what makes the cache of the ledger sound. `AssetStore`
+   adds `create_asset`, `get_asset` and `list_assets`; migration `014_assets`
+   stores the row as JSON beside its id, like books.
+
+2. **`Amount { asset: Arc<Asset>, value: Cent }`** lives in `kuatia-types`, not
+   beside `Cent`, because `kuatia-money` has no dependency on the crate that
+   defines `AssetId`. Conversion is the only way to build one, so no amount
+   exists without an asset behind it. The tuple conversions follow one rule: an
+   integer is minor units, a string is the written form at the asset's own
+   scale. `(usd, 500)` and `(usd, "5.00")` are the same amount, and
+   `(usd, "5.001")` fails rather than rounding.
+
+3. **`Arc<Asset>` stops at the public API.** `Posting`, `NewPosting`,
+   `Movement`, `BalanceProjection`, the pure core's `(account, asset)` map keys
+   and every storage row keep `AssetId`. `NewPosting` is serde-JSON inside the
+   stored `transfers.transfer` column, and serde cannot hydrate an `Arc` with no
+   registry to reach. The `Ledger` hydrates on the way out instead. Nothing
+   stored changes, `CANONICAL_VERSION` stays at 6, and no transfer id moves.
+
+4. **The reads return amounts.** `balance`, `balance_exact` and `balance_as_of`
+   return `Amount`, and `SubAccountBalance` carries one. `InsufficientFunds`
+   gains its asset, so the two values in a shortfall name a quantity. A sum of
+   two assets is `AmountError::AssetMismatch`, refused at the call site that
+   tries it.
+
+5. **The builder takes one amount per verb**, as `impl TryInto<Amount>`, and
+   holds the first conversion failure until `build`. That keeps the chain
+   fluent, and it makes `build` fallible. It also retires the mid-chain `Result`
+   of `deposit`, which ADR-0026 left as the one verb that broke the flow.
+
+6. **Commit refuses an unregistered asset.** Conservation puts every asset a
+   transfer touches on the created side, so the created postings are the whole
+   set to check. Validation itself pays nothing. It reads the authoritative live
+   sum from the store, and an amount that reached it came from a registered
+   asset already.
+
+7. **The scale keeps its own name.** ADR-0009's `Amount` was a decimal-place
+   count that parsed and formatted and was never stored. It is now `Scale`, and
+   `ParseAmountError` is `ParseDecimalError`. ADR-0009 and ADR-0011 still say
+   `Amount`, since an accepted record is not rewritten; this is where the rename
+   lives.
 
 ### Positive Consequences
 
-* The read-side leak closes: a caller holding two balances cannot add them unless they are the same asset.
-* A written amount parses at the right precision without the caller tracking it, which retires the negative consequence ADR-0009 accepted.
-* The snapshot-plus-tail additions in the balance path and the hand-built FX envelopes keep working unchanged, since both operate below the public surface.
-* The dashboard's own asset table is gone, and with it the path that rendered raw minor units for an asset missing from it.
+* The read-side leak closes. A caller with two balances cannot add them unless
+  they are the same asset.
+* A written amount parses at the right precision, and the caller tracks nothing.
+  That retires the negative consequence ADR-0009 accepted.
+* The snapshot-plus-tail additions in the balance path and the hand-built FX
+  envelopes still work unchanged, because both operate below the public surface.
+* The asset table of the dashboard is gone, and with it the path that rendered
+  raw minor units for an asset absent from it.
 
 ### Negative Consequences
 
-* A balance read of an unregistered asset is an error. That is intended, since an unregistered asset has no precision to report at, but it means every test, example and seed registers its assets first.
-* `build` is fallible for every caller, including ones passing a `Cent` that cannot fail. The blanket `From<Infallible>` keeps those call sites writing `(asset, cent)` with no ceremony, but the `Result` is still there.
-* The commit path takes a registry lookup per distinct asset. Cached after the first, uncached on a miss.
-* `Amount` is `Serialize` only. Rebuilding one needs the registry, so nothing deserializes it, and the dashboard's issued figures change key from `issued` to `value`.
+* A balance read of an unregistered asset is an error. That is intended, since
+  an unregistered asset has no precision to report at, but it means every test,
+  example and seed registers its assets first.
+* `build` is fallible for every caller, even one that passes a `Cent` that
+  cannot fail. The blanket `From<Infallible>` lets those call sites write
+  `(asset, cent)` with no ceremony, and the `Result` is still there.
+* The commit path takes a registry lookup per distinct asset. Cached after the
+  first, uncached on a miss.
+* `Amount` is `Serialize` only. A rebuild of one needs the registry, so nothing
+  deserializes it, and the issued figures of the dashboard change key from
+  `issued` to `value`.
 
 ## Links
 
-* Refines [ADR-0009](0009-monetary-representation-integer-minor-units.md), whose accepted negative consequence this retires, and renames the `Amount` it introduced.
-* Follows [ADR-0026](0026-public-api-vocabulary.md): the public surface speaks the caller's vocabulary, and `deposit`'s mid-chain `Result` was the wart it left.
-* Constrained by [ADR-0024](0024-native-money-columns.md) (the amount columns) and the canonical preimage order, both unchanged here.
+* Refines [ADR-0009](0009-monetary-representation-integer-minor-units.md), whose
+  accepted negative consequence this retires, and renames the `Amount` it
+  introduced.
+* Follows [ADR-0026](0026-public-api-vocabulary.md): the public surface speaks
+  the caller's vocabulary, and `deposit`'s mid-chain `Result` was the wart it
+  left.
+* Constrained by [ADR-0024](0024-native-money-columns.md) (the amount columns)
+  and the canonical preimage order, both unchanged here.
 * Conservation per asset: [ADR-0001](0001-modified-utxo-signed-postings.md).

+ 102 - 40
doc/adr/0029-stored-amounts-and-a-closed-money-surface.md

@@ -12,19 +12,35 @@
 
 ## Context and Problem Statement
 
-ADR-0028 gave the ledger an `Amount` and bounded it to the public API: `Posting`, `NewPosting`, `Movement` and `BalanceProjection` kept an `AssetId` beside a `Cent`, and the `Ledger` paired them on the way out. Two things were wrong with stopping there.
-
-The shape being stored was still the shape the type was meant to retire. A reader of the schema or the structs saw the pair, the conversion happened at one edge only, and the accessors that bridged the two (`Posting::value()`, `Amount::value()`) handed the `Cent` straight back. Twenty-six public items still named `Cent` or `AssetId` in a way that let a caller take an amount apart and recombine it wrongly.
-
-The reason ADR-0028 stopped was real: `NewPosting` is serde-JSON inside the stored `transfers.transfer` column, and serde cannot rebuild an `Arc<Asset>` because it has no registry to reach. Any structure holding an `Amount` was therefore undecodable.
+ADR-0028 gave the ledger an `Amount` and bounded it to the public API.
+`Posting`, `NewPosting`, `Movement` and `BalanceProjection` kept an `AssetId`
+beside a `Cent`, and the `Ledger` paired them on the way out. Two things were
+wrong with that boundary.
+
+The stored shape was still the shape the type had to retire. A reader of the
+schema or the structs saw the pair. The conversion happened at one edge only.
+The accessors that bridged the two (`Posting::value()`, `Amount::value()`)
+handed the `Cent` straight back. Twenty-six public items still named `Cent` or
+`AssetId`, and each one let a caller take an amount apart and recombine it
+wrongly.
+
+The reason ADR-0028 stopped was real. `NewPosting` is serde-JSON inside the
+stored `transfers.transfer` column, and serde cannot rebuild an `Arc<Asset>`
+because it has no registry to reach. So no structure with an `Amount` in it
+could decode.
 
 ## Decision Drivers
 
-* The bug class this work exists to remove is a value separated from its asset, so the stored form is where it matters most.
-* Nothing may move the content address: every `TransferId` in every database depends on the preimage byte-for-byte.
-* A read must not be able to fail *silently*; a loud failure is acceptable, a dropped row is not.
-* The amount columns stay native integers, because ADR-0024's exact `SUM()` and the ordering indexes are built on them.
-* `Cent`'s width is a compile-time choice (ADR-0011) and must stay invisible to callers.
+* The bug class this work exists to remove is a value separated from its asset,
+  so the stored form is where it matters most.
+* The content address must not move. Every `TransferId` in every database
+  depends on the preimage byte-for-byte.
+* A read must not be able to fail *silently*; a loud failure is acceptable, a
+  dropped row is not.
+* The amount columns stay native integers, because the exact `SUM()` of ADR-0024
+  and the indexes that order them are built on them.
+* `Cent`'s width is a compile-time choice (ADR-0011) and must stay invisible to
+  callers.
 
 ## Considered Options
 
@@ -38,12 +54,15 @@ The store resolves each row's asset through `AssetStore` with a cache.
 
 **Cons:**
 
-* Bad, because the store starts making domain decisions, against the dumb-storage line from ADR-0003 and ADR-0023.
-* Bad, because a row read becomes dependent on registry state, and the failure mode is a read that cannot answer.
+* Bad, because the store then makes domain decisions, against the dumb-storage
+  line from ADR-0003 and ADR-0023.
+* Bad, because a row read becomes dependent on registry state, and the failure
+  mode is a read that cannot answer.
 
 #### Deserialize into an unresolved placeholder asset
 
-`Amount` gains a `Deserialize` that yields an asset with `decimals: 0` until something re-hydrates it.
+`Amount` gains a `Deserialize` that yields an asset with `decimals: 0` until
+something re-hydrates it.
 
 **Pros:**
 
@@ -51,54 +70,97 @@ The store resolves each row's asset through `AssetStore` with a cache.
 
 **Cons:**
 
-* Bad, because an amount that formats at the wrong scale is exactly the defect this line of work removes, and a placeholder is that defect with a nicer name.
+* Bad, because an amount that formats at the wrong scale is exactly the defect
+  this line of work removes. A placeholder is that defect with a nicer name.
 
 #### Store the asset definition with the amount
 
 **Pros:**
 
-* Good, because an amount decodes with no registry, no resolver and no failure mode.
-* Good, because an append-only audit record becomes self-describing: a stored posting can be read with no other table.
-* Good, because it needs nothing of the store, which keeps serving rows.
+* Good, because an amount decodes with no registry, no resolver and no failure
+  mode.
+* Good, because an append-only audit record becomes self-describing: a stored
+  posting can be read with no other table.
+* Good, because it needs nothing of the store, which still serves rows.
 
 **Cons:**
 
 * Bad, because the definition is repeated in every stored record.
-* Bad, because the column tables cannot do this: an index and an exact sum need the integer and the id in their own columns.
+* Bad, because the column tables cannot do this: an index and an exact sum need
+  the integer and the id in their own columns.
 
 ## Decision Outcome
 
-Chosen option: **store the asset definition with the amount**, and close the public surface behind it.
-
-1. **The serialized form of an `Amount` carries the whole asset**, not its id, so `Amount: Deserialize` exists and cannot fail or come back at the wrong scale. That is what lets `Movement`, `Posting`, `NewPosting` and `BalanceProjection` each hold one amount.
-
-2. **The content address does not carry it.** The preimage still writes the asset's `u32` id then the 16-byte value, so writing a code or a symbol differently cannot re-identify a transfer, and `CANONICAL_VERSION` stays at 6. A golden vector taken before the refactor is asserted in `kuatia-core`'s hash tests and did not move.
-
-3. **The column tables keep an integer beside an asset id** (ADR-0024 is unchanged), and a posting read **left-joins** the registry to rebuild the amount. Left, not inner, and no foreign key: an inner join or a missing FK would silently drop a posting whose asset is absent, while a left join fails the decode loudly and says so. The invariant is enforced where it belongs instead, at the commit, which resolves every asset a transfer moves value in. SQLite also cannot take a foreign key without rebuilding the table and needs the pragma set per connection, so the constraint would have been weaker than the check it replaced.
-
-4. **`Cent` is not public.** No public signature in `kuatia-types`, `kuatia-core`, `kuatia-storage` or `kuatia` names it. An `Amount` gives up `Display` at its asset's scale, `checked_add`/`checked_sub`/`checked_neg`/`checked_sum` that refuse two assets, the predicates, and `minor_units() -> i128` for a caller doing its own formatting. `AssetId` stays public, because an asset must be nameable to be registered, looked up or allowed by a book.
-
-5. **One seam, not an accessor.** The other crates still need the integer, for checked arithmetic and for a column bind, and they are separate crates, so `kuatia_types::internals` (doc(hidden)) holds `cent`, `amount`, `scale` and the money re-exports. One named place, greppable, rather than a public method that a caller would reasonably use.
-
-6. **Conservation sums amounts.** The per-asset buckets in `validate_and_plan` add `Amount`s, so a bucket keyed wrongly fails the addition rather than netting two assets. Posting selection still works in values: it needs an ordering, and two assets have no answer for that.
+Chosen option: **store the asset definition with the amount**, and close the
+public surface behind it.
+
+1. **The serialized form of an `Amount` carries the whole asset**, and not its
+   id. So `Amount: Deserialize` exists, and it cannot fail or come back at the
+   wrong scale. That is what lets `Movement`, `Posting`, `NewPosting` and
+   `BalanceProjection` each hold one amount.
+
+2. **The content address does not carry it.** The preimage still writes the
+   `u32` id of the asset and then the 16-byte value. So a code or a symbol
+   written differently cannot re-identify a transfer, and `CANONICAL_VERSION`
+   stays at 6. A golden vector taken before the refactor is asserted in the hash
+   tests of `kuatia-core`, and it did not move.
+
+3. **The column tables keep an integer beside an asset id** (ADR-0024 is
+   unchanged). A posting read **left-joins** the registry to rebuild the amount,
+   and the schema has no foreign key. An inner join, or an absent FK, silently
+   drops a posting whose asset is absent. A left join fails the decode loudly
+   and says so. The invariant is enforced where it belongs instead, at the
+   commit, which resolves every asset a transfer moves value in. A foreign key
+   in SQLite also needs a table rebuild and a per-connection pragma, so it would
+   have been weaker than the check it replaced.
+
+4. **`Cent` is not public.** No public signature in `kuatia-types`,
+   `kuatia-core`, `kuatia-storage` or `kuatia` names it. An `Amount` offers
+   `Display` at its asset's scale,
+   `checked_add`/`checked_sub`/`checked_neg`/`checked_sum` that refuse two
+   assets, the predicates, and `minor_units() -> i128` for a caller that formats
+   the value itself. `AssetId` stays public, because an asset must be nameable
+   to be registered, looked up or allowed by a book.
+
+5. **One seam, not an accessor.** The other crates still need the integer, for
+   checked arithmetic and for a column bind, and they are separate crates. So
+   `kuatia_types::internals` (doc(hidden)) holds `cent`, `amount`, `scale` and
+   the money re-exports. One named place, greppable, rather than a public method
+   that a caller would reasonably use.
+
+6. **Conservation sums amounts.** The per-asset buckets in `validate_and_plan`
+   add `Amount`s, so a bucket keyed wrongly fails the addition and nets no two
+   assets. Posting selection still works in values, because it must put them in
+   order and two assets have no answer for that.
 
 ### Positive Consequences
 
-* A stored posting is self-describing: its asset, its precision and its value travel together, which is what an append-only audit record should be.
-* The pairing bug is gone from the storage layer, the intent layer and the API at once, not just the edge.
-* The dashboard formats from `minor_units()` and the asset's own decimals, so its last mis-scaling path is gone along with its asset table.
-* `--5` no longer parses as a positive five, which mattered once a string became a way to state a transfer amount.
+* A stored posting is self-describing. Its asset, its precision and its value
+  travel together, which is what an append-only audit record must be.
+* The bug that separates a value from its asset is gone from the storage layer,
+  the intent layer and the API at once. The edge alone is no longer the fix.
+* The dashboard formats from `minor_units()` and the asset's own decimals. Its
+  last path to a wrong scale is gone, and so is its asset table.
+* `--5` no longer parses as a positive five, which mattered once a string became
+  a way to state a transfer amount.
 
 ### Negative Consequences
 
 * Every stored record is larger by its asset definition, repeated per posting.
-* An open inflight authorization cannot be confirmed across the upgrade: the leg table is CBOR inside a transfer's metadata and its shape moved.
-* A database carrying postings in assets that are not registered will fail those reads loudly until the assets are registered. That is the intended direction of the failure, but it makes registration the first step of an upgrade.
+* An open inflight authorization cannot be confirmed across the upgrade: the leg
+  table is CBOR inside a transfer's metadata and its shape moved.
+* A database with postings in assets that are not registered fails those reads
+  loudly until the assets are registered. That is the intended direction of the
+  failure, and it makes registration the first step of an upgrade.
 * `Amount` has no total order, so a comparison is explicit and same-asset only.
 
 ## Links
 
-* Supersedes point 3 of [ADR-0028](0028-amount-carries-its-asset.md), which bounded `Arc<Asset>` to the public API; the rest of 0028 stands.
-* Constrained by [ADR-0024](0024-native-money-columns.md) (native amount columns) and [ADR-0011](0011-swappable-money-backing.md) (the hidden backing width).
-* Keeps the storage layer free of domain decisions, per [ADR-0023](0023-atomic-storage-commit.md).
+* Supersedes point 3 of [ADR-0028](0028-amount-carries-its-asset.md), which
+  bounded `Arc<Asset>` to the public API; the rest of 0028 stands.
+* Constrained by [ADR-0024](0024-native-money-columns.md) (native amount
+  columns) and [ADR-0011](0011-swappable-money-backing.md) (the hidden backing
+  width).
+* Keeps the storage layer free of domain decisions, per
+  [ADR-0023](0023-atomic-storage-commit.md).
 * Conservation per asset: [ADR-0001](0001-modified-utxo-signed-postings.md).

+ 76 - 30
doc/adr/0030-assets-named-by-code.md

@@ -10,21 +10,31 @@
 
 ## Context and Problem Statement
 
-ADR-0028 gave assets caller-supplied ids, reasoning that an asset is named like an account rather than minted. In practice a caller names an asset by its code and has no opinion about its id, so registering one took two steps and an invented number:
+ADR-0028 gave an asset an id that the caller supplied. Its reason was that
+something names an asset the way it names an account, and does not mint it.
+
+In practice a caller names an asset by its code and holds no opinion about its
+id. So a registration took two steps and a number the caller invented:
 
 ```rust
 ledger.create_asset(Asset::new(AssetId::new(2), "EUR", "€", 2)).await?;
 let eur = ledger.asset(&AssetId::new(2)).await?;
 ```
 
-The `2` is the caller keeping a registry of its own alongside the ledger's, which is the thing the registry exists to stop. Every test, example and seed in the tree carried such a table, and nothing but convention kept two of them from disagreeing.
+That `2` is the caller's own registry, beside the ledger's. The ledger's
+registry exists to stop exactly that. Every test, every example and every seed
+in the tree carried such a table, and only convention kept two of them in
+agreement.
 
 ## Decision Drivers
 
 * A caller names money by its code, not by a number.
-* An id must stay stable, because postings, the amount columns and the content address all store it.
-* Precision is the dangerous field: an asset returned at the wrong scale mis-states every amount read through it.
-* Setup code runs repeatedly (tests, seeds, a service starting against an existing database), so registration wants to be idempotent.
+* An id must stay stable. The postings, the amount columns and the content
+  address all store it.
+* Precision is the dangerous field. An asset that comes back at the wrong scale
+  mis-states every amount a caller reads through it.
+* Setup code runs again and again. A test runs it, a seed runs it, and a service
+  runs it against a database that exists. So a registration must be idempotent.
 
 ## Considered Options
 
@@ -32,66 +42,102 @@ The `2` is the caller keeping a registry of its own alongside the ledger's, whic
 
 **Pros:**
 
-* Good, because it is the smallest change and the caller keeps its id space.
+* Good, because it is the smallest change, and the caller keeps its own id
+  space.
 
 **Cons:**
 
-* Bad, because the caller still holds a table mapping codes to numbers, which is what went wrong.
+* Bad, because the caller still holds a table from a code to a number, and that
+  table is what went wrong.
 
 #### Derive the id from the code
 
-An `AssetId` is a hash of the code, so one code is one id in every database.
+An `AssetId` is a hash of the code, so one code gives one id in every database.
 
 **Pros:**
 
-* Good, because two ledgers registering `EUR` agree without coordination, which helps if they are ever compared.
+* Good, because two ledgers that register `EUR` agree with no coordination. That
+  helps if anything ever compares them.
 
 **Cons:**
 
-* Bad, because a 32-bit hash collides, and a collision silently merges two assets into one balance.
-* Bad, because a code could then never be re-spelled.
+* Bad, because a 32-bit hash collides, and a collision merges two assets into
+  one balance without a word.
+* Bad, because nothing could then ever re-spell a code.
 
 #### Name by code, mint the id (chosen)
 
 **Pros:**
 
-* Good, because the caller states what it knows (code, symbol, precision) and nothing it does not.
-* Good, because it matches how accounts and books already get their ids, in Rust through `AutoId`, never from the database.
-* Good, because one call both registers and returns the handle, so setup code is idempotent.
+* Good, because the caller states what it knows, which is the code, the symbol
+  and the precision, and states nothing else.
+* Good, because it matches how an account and a book already get an id, in Rust
+  through `AutoId` and never from the database.
+* Good, because one call registers the asset and returns the handle. So setup
+  code is idempotent.
 
 **Cons:**
 
-* Bad, because the same code has different ids in two databases, so an id is not portable between them.
-* Bad, because it needs a unique index on the code, and a migration to add it.
+* Bad, because one code has two different ids in two databases. So an id does
+  not move between them.
+* Bad, because it needs a unique index on the code, and a migration that adds
+  that index.
 
 ## Decision Outcome
 
 Chosen option: **name by code, mint the id**.
 
-1. **`Ledger::asset(code, symbol, decimals)` is get-or-create** and returns `Arc<Asset>`. The by-id lookup keeps its behaviour as `asset_by_id`. `create_asset` stays for a caller that wants to choose the id.
+1. **`Ledger::asset(code, symbol, decimals)` is a get-or-create** and returns
+   `Arc<Asset>`. The lookup by id keeps its behaviour, as `asset_by_id`.
+   `create_asset` stays, for a caller that wants to choose the id.
 
-2. **A code registered with other metadata is `LedgerError::AssetRedefined`.** Returning the stored row would hand back a precision the caller did not ask for and mis-state every amount formatted through it; rewriting the row is not possible, since a registry row is immutable (ADR-0028). So neither side wins and the disagreement is reported, carrying both decimal counts.
+2. **A code that arrives with other metadata gives
+   `LedgerError::AssetRedefined`.** A return of the stored row would hand back a
+   precision the caller did not ask for. It would then mis-state every amount
+   formatted through it. A rewrite of the row is impossible, because a registry
+   row is immutable (ADR-0028). So neither side wins. The ledger reports the
+   disagreement, and the report carries both decimal counts.
 
-3. **The id comes from `AutoId`**, folded into the `u32` an `AssetId` carries, retried past the small chance that a truncated snowflake lands on an id already taken. A code's uniqueness is the index's job, so a concurrent registration of the same code is caught by re-reading it rather than by locking.
+3. **The id comes from `AutoId`**, folded into the `u32` that an `AssetId`
+   carries. A truncated snowflake has a small chance to land on an id that is
+   taken, and a retry covers that. The index owns the uniqueness of a code. So a
+   re-read catches a second concurrent registration of one code, and no lock
+   does.
 
-4. **`code` is unique** (migration `015_asset_code_unique`). Without it a get-or-create could register a second `EUR` under a different id and split every balance held in it.
+4. **`code` is unique**, through migration `015_asset_code_unique`. Without the
+   index, a get-or-create could register a second `EUR` under another id, and
+   split every balance held in it.
 
-5. **`AssetStore` gains `get_asset_by_code`**, returning an `Option` rather than `NotFound`, because the caller asking by code is deciding whether to register.
+5. **`AssetStore` gains `get_asset_by_code`**. It returns an `Option` rather
+   than a `NotFound`, because a caller that asks by code has yet to decide
+   whether to register.
 
 ### Positive Consequences
 
-* Registering an asset is one line and says only what the caller knows: `ledger.asset("EUR", "€", 2)`.
-* The id-to-code tables in the tests, the examples and the dashboard are gone; the dashboard reads the registry for the list it renders.
-* Setup code is idempotent, so a seed can run against a populated database without an ignore-already-exists dance.
+* A registration of an asset is one line, and it says only what the caller
+  knows: `ledger.asset("EUR", "€", 2)`.
+* The tables from an id to a code are gone from the tests, the examples and the
+  dashboard. The dashboard reads the registry for the list it renders.
+* Setup code is idempotent. So a seed can run against a database that already
+  holds rows, and it needs no step that ignores a row already there.
 
 ### Negative Consequences
 
-* An `AssetId` is no longer portable between databases, which it was when a caller chose it. Nothing in the ledger compares ids across databases, but a tool that did would have to map by code.
-* A code is now part of an asset's identity in practice, so re-spelling one means a new asset.
-* Migration 015 fails on an existing database that already holds two assets sharing a code. That is the condition the index exists to prevent, and it has to be resolved by hand.
+* An `AssetId` no longer moves between two databases, and it did when a caller
+  chose it. Nothing in the ledger compares an id across two databases. A tool
+  that does must map by code.
+* A code is now part of the identity of an asset in practice. So a code written
+  another way gives a new asset.
+* Migration 015 fails on a database that already holds two assets under one
+  code. That is the condition the index exists to prevent, and someone must
+  resolve it by hand.
 
 ## Links
 
-* Supersedes the caller-supplied-id clause of [ADR-0028](0028-amount-carries-its-asset.md); the rest of it, and all of [ADR-0029](0029-stored-amounts-and-a-closed-money-surface.md), stand.
-* Ids minted in Rust, never by the database: the `AutoId` rule in `CLAUDE.md`, as used by accounts and books.
-* Immutable registry rows: [ADR-0028](0028-amount-carries-its-asset.md), point 1.
+* Supersedes the clause of [ADR-0028](0028-amount-carries-its-asset.md) where
+  the caller supplies the id. The rest of that record stands, and so does all of
+  [ADR-0029](0029-stored-amounts-and-a-closed-money-surface.md).
+* Rust mints every id, and the database mints none. That is the `AutoId` rule in
+  `CLAUDE.md`, and an account and a book both follow it.
+* A registry row is immutable: [ADR-0028](0028-amount-carries-its-asset.md),
+  point 1.

+ 84 - 32
doc/adr/0031-every-read-is-account-scoped.md

@@ -9,11 +9,24 @@
 
 ## Context and Problem Statement
 
-The asset registry (ADR-0030) gave a caller the asset list a trial balance needs to iterate, and the roadmap had wanted one since 0.2.0. It was built: `Ledger::trial_balance(asset)` over a new `PostingStore::live_balances(asset)`, one grouped aggregate per asset over the live set, returning every account holding it.
+The asset registry (ADR-0030) gave a caller the list of assets that a trial
+balance walks. The roadmap had asked for a trial balance since 0.2.0.
 
-The read is keyed by an asset. Every other read on the ledger is keyed by an account: `live_balance(account, asset)`, `get_postings_by_account(id, sub, ..)`, and `PostingQuery.account`, which is a plain `i64` and not an option. The trial balance was the first read that asked the store a question no account bounds.
+So someone built it: `Ledger::trial_balance(asset)` over a new
+`PostingStore::live_balances(asset)`. That is one grouped aggregate per asset
+over the live set, and it returns every account that holds the asset.
 
-Its cost shows why that matters. The only index on the live table is `idx_live_owner(owner, subaccount, asset)`, so a filter on `asset` alone cannot seek it. Measured on a populated SQLite database:
+That read is keyed by an asset. Every other read on the ledger is keyed by an
+account. Those are `live_balance(account, asset)`,
+`get_postings_by_account(id, sub, ..)`, and `PostingQuery.account`, which is a
+plain `i64` and not an option.
+
+So the trial balance was the first read to ask the store a question that no
+account bounds.
+
+Its cost shows why that matters. The live table has one index,
+`idx_live_owner(owner, subaccount, asset)`. A filter on `asset` alone cannot
+seek that index. Here is the measurement on a populated SQLite database:
 
 ```
 SCAN live_postings USING COVERING INDEX idx_live_owner      -- live_balances(asset)
@@ -21,58 +34,84 @@ SEARCH live_postings USING COVERING INDEX idx_live_owner    -- live_balance(acco
         (owner=? AND subaccount=? AND asset=?)
 ```
 
-One read reads the whole live set, including the postings of every other asset. The other seeks. An index starting with `asset` would fix the second half of that, which is what made the question worth asking rather than answering with a migration.
+One read reads the whole live set, and that covers the postings of every other
+asset. The other read seeks. An index that starts with `asset` would fix the
+second half of that. So the question was worth a review, rather than an answer
+by migration.
 
 ## Decision Drivers
 
-* An account-scoped read can be routed to the shard that holds the account. A cross-account aggregate has to fan out to every shard, so having one in the public API forecloses splitting the store later.
-* A read's cost should be bounded by one account's data. A cross-account aggregate has no bound: it gets slower every day the ledger runs, in the hot path of whatever asked for it.
-* Aggregating across accounts is reporting, and reporting can be cached, scheduled and denormalized off the event stream (ADR-0010). Inside the ledger it can do none of those things and runs against the write path's tables.
-* An exact aggregate in the database is permitted (ADR-0024), so the rule cannot come from arithmetic safety. This is about which questions the store answers, not how it adds up.
+* A read with an account scope can go to the shard that holds the account. An
+  aggregate across accounts must fan out to every shard. So one of those in the
+  public API closes off a later split of the store.
+* The data of one account must bound the cost of a read. An aggregate across
+  accounts has no bound. It gets slower every day the ledger runs, in the hot
+  path of whatever asked for it.
+* An aggregate across accounts is a report. A report can sit in a cache, run on
+  a schedule, and take a denormalized shape off the event stream (ADR-0010).
+  Inside the ledger it can do none of those, and it runs against the tables of
+  the write path.
+* The database can hold an exact aggregate (ADR-0024), so this rule does not
+  come from the safety of the arithmetic. It is about which questions the store
+  answers, and not about how the store adds up.
 
 ## Considered Options
 
 #### Keep it, and add an asset-first index
 
-A migration adding `(asset, owner, subaccount)` turns the scan into a range seek.
+A migration that adds `(asset, owner, subaccount)` turns the scan into a range
+seek.
 
 **Pros:**
 
-* Good, because the measured cost problem goes away, and the trial balance is a feature a ledger is expected to have.
+* Good, because the cost problem in the measurement goes away. A trial balance
+  is also a feature that a reader expects a ledger to have.
 
 **Cons:**
 
-* Bad, because it fixes only the cost. The fan-out across shards and the coupling to the write path's tables are unchanged.
-* Bad, because it adds an index to the hottest table in the system to serve a read nothing on the commit path makes.
+* Bad, because it fixes the cost alone. The fan-out across shards does not
+  change, and the read still depends on the tables of the write path.
+* Bad, because it adds an index to the hottest table in the system. That index
+  serves one read, and nothing on the commit path makes that read.
 
 #### Keep it behind a feature flag or a documented warning
 
 **Pros:**
 
-* Good, because a caller who has measured their own ledger can opt in.
+* Good, because a caller that measured its own ledger can choose to use it.
 
 **Cons:**
 
-* Bad, because a published method is a published method: it will be called, and the cost lands on whoever called it rather than whoever enabled it.
+* Bad, because a published method is a published method. Something calls it, and
+  the cost lands on the caller rather than on whoever turned it on.
 
 #### No read aggregates value across accounts (chosen)
 
 **Pros:**
 
-* Good, because every read keeps a shard key, so the store can be split by account without changing the API.
-* Good, because a read's cost stays proportional to one account, which is the only bound that does not grow with the ledger.
-* Good, because it is one rule that answers the next proposal of this shape without re-deriving the argument.
+* Good, because every read keeps a shard key. So a split of the store by account
+  needs no change to the API.
+* Good, because the cost of a read stays proportional to one account. That is
+  the only bound which does not grow with the ledger.
+* Good, because it is one rule. It answers the next proposal of this shape, and
+  nobody has to derive the argument again.
 
 **Cons:**
 
-* Bad, because a trial balance, a balance sheet and a P&L are the reports an accounting system is asked for, and the library now answers none of them.
-* Bad, because an application that wants one has to enumerate its own accounts, and only it knows that list.
+* Bad, because a trial balance, a balance sheet and a profit-and-loss statement
+  are the reports that a user asks an accounting system for. The library now
+  answers none of them.
+* Bad, because an application that wants one must enumerate its own accounts. It
+  alone knows that list.
 
 ## Decision Outcome
 
-Chosen option: **no read aggregates value across accounts**. `Ledger::trial_balance` and `PostingStore::live_balances` are removed before 0.4.0 is tagged, so neither was ever published.
+Chosen option: **no read aggregates value across accounts**. This change removes
+`Ledger::trial_balance` and `PostingStore::live_balances` before the 0.4.0 tag,
+so nothing ever published either one.
 
-The line is about aggregating value, not about touching more than one row:
+The line is about an aggregate over value. It is not about a read that touches
+more than one row:
 
 | Shape | Allowed | Why |
 |---|---|---|
@@ -83,24 +122,37 @@ The line is about aggregating value, not about touching more than one row:
 | `list_assets`, `list_books`, `get_asset_by_code` | yes | Definitions, not value. |
 | `expire_due(now)` | yes | It walks holds the ledger created as subaccounts of their destinations (ADR-0014), settling each through `void`. It reads no aggregate. |
 
-Per-asset conservation is still tested, from per-account reads over the accounts a test creates, which is the same invariant and fails the same way if a row goes missing.
+A test still checks per-asset conservation. It reads per account, over the
+accounts that the test creates. That is the same invariant, and it fails the
+same way when a row disappears.
 
 ### Positive Consequences
 
-* Every read in the public API carries an account, so the store can be sharded on it.
+* Every read in the public API carries an account. So a shard key for the store
+  is available.
 * The hot live table needs no second index, and no read scans it.
-* The next cross-account report has an answer to point at instead of an argument to repeat.
+* The next request for a cross-account report has an answer to point at. Nobody
+  repeats the argument.
 
 ### Negative Consequences
 
-* The library answers no cross-account question, so a trial balance, a balance sheet and a P&L are all the application's to build.
-* An application building one enumerates accounts itself and pays a read per account. That is the cost this ADR moves rather than removes, and it moves it somewhere it can be cached.
-* The roadmap item that asked for a trial balance is closed as ruled out rather than done, after the feature was built and removed.
+* The library answers no question across accounts. So a trial balance, a balance
+  sheet and a profit-and-loss statement are all the application's to build.
+* An application that builds one enumerates the accounts itself, and it pays one
+  read per account. This record moves that cost rather than removes it, and it
+  moves the cost somewhere a cache can hold it.
+* The roadmap item that asked for a trial balance closes as ruled out, and not
+  as done. Someone built the feature and then removed it.
 
 ## Links
 
-* The asset registry that unblocked the trial balance: [ADR-0030](0030-assets-named-by-code.md).
-* Exact aggregation is permitted and is not what this restricts: [ADR-0024](0024-native-money-columns.md).
-* Where a cross-account report belongs instead: the derived event stream, [ADR-0010](0010-event-stream-vs-transfer-log.md).
-* Holds as subaccounts, which is why the expiry sweep is account scoped: [ADR-0014](0014-inflight-holds-via-holding-accounts.md).
-* Conservation per asset, the invariant the removed test checked: [ADR-0001](0001-modified-utxo-signed-postings.md).
+* The asset registry that opened the way to a trial balance:
+  [ADR-0030](0030-assets-named-by-code.md).
+* Exact aggregation is permitted and is not what this restricts:
+  [ADR-0024](0024-native-money-columns.md).
+* Where a cross-account report belongs instead: the derived event stream,
+  [ADR-0010](0010-event-stream-vs-transfer-log.md).
+* A hold is a subaccount, which is the reason the expiry sweep has an account
+  scope: [ADR-0014](0014-inflight-holds-via-holding-accounts.md).
+* Conservation per asset, the invariant the removed test checked:
+  [ADR-0001](0001-modified-utxo-signed-postings.md).

+ 54 - 49
doc/adr/README.md

@@ -1,10 +1,14 @@
 # Architecture Decision Records
 
-Significant, hard-to-reverse design decisions for Kuatia, captured so the
-*why* survives. New ADRs follow [`template.md`](template.md) (MADR-style:
-context → drivers → considered options with pros/cons → decision outcome
-→ consequences → links). Numbering is sequential; an ADR is never edited
-to reverse a decision. Instead, a new ADR supersedes it.
+The significant, hard-to-reverse design decisions for Kuatia. They are here so
+that the *why* survives.
+
+A new record follows [`template.md`](template.md), in the MADR style. The
+sections are context, then drivers, then the considered options with their pros
+and cons, then the decision outcome, then the consequences, then the links.
+
+The numbers run in sequence. Nobody edits a record to reverse a decision.
+Instead a new record supersedes it.
 
 ## Index
 
@@ -33,7 +37,7 @@ to reverse a decision. Instead, a new ADR supersedes it.
 | [0021](0021-commit-safety-map.md) | The commit-safety invariant and where each part is enforced | accepted (amended by 0023) | Maps each safety property (conservation, double-spend, floor, freeze/close, snapshot) to the layer that enforces it. Amended by 0023: the double-spend, floor, and freeze/close guards now live in the store's atomic `commit_envelope`. |
 | [0022](0022-merged-live-postings-hot-index.md) | Merge the active/reserved hot indexes into one `live_postings` table | accepted (`reservation` column superseded by 0025) | The `active_postings` and `reserved_postings` hot tables merge into one `live_postings` table whose nullable `reservation` column derives the lifecycle state. Refines 0016/0017. The column itself is dropped by 0025; the merged table stands. |
 | [0023](0023-atomic-storage-commit.md) | Atomic storage commit, retiring the write-ahead saga and `legend` | accepted | The store commits a whole transfer (and a whole account transition) in one transaction, re-checking double-spend, floor, and freeze/close inside it. Removes the reservation two-step, write-ahead recovery, `SagaStore`, and `legend`. Supersedes 0003 and 0020; refines 0002; amends 0021. |
-| [0024](0024-native-money-columns.md) | Native money columns, and exact summation in the database | accepted | Amount columns become `NUMERIC(39,0)` on PostgreSQL and a 16-byte order-preserving `BLOB` on SQLite, stored at full i128 width whatever the backing. The database may now sum them, exactly: plain `SUM()` on Postgres, a registered `kuatia_i128_sum` aggregate on SQLite. Supersedes 0011's text storage; amends 0009 and 0023. |
+| [0024](0024-native-money-columns.md) | Native money columns, and exact summation in the database | accepted | Amount columns become `NUMERIC(39,0)` on PostgreSQL and a 16-byte order-preserving `BLOB` on SQLite, stored at full i128 width whatever the backing. The database can now sum them, exactly: plain `SUM()` on Postgres, a registered `kuatia_i128_sum` aggregate on SQLite. Supersedes 0011's text storage; amends 0009 and 0023. |
 | [0025](0025-one-live-set-no-reservations.md) | One live set: retire the reservation protocol and the saga-era store primitives | accepted | A posting is live or spent, with nothing in between: `PostingState` loses `Reserved`, `PostingFilter` loses `Active`, and `ReservationId`/`TransitionId` go. The six single-update write primitives are removed, leaving the atomic commit as the store's only posting write, and migration 012 drops `live_postings.reservation`. Follows 0023; supersedes 0006; amends 0008. |
 | [0026](0026-public-api-vocabulary.md) | Let the public API speak the caller's vocabulary | accepted | Four shapes left over from earlier designs leave the surface: the `Arc<Ledger>` every commit required and never used, `TransferBuilder`'s duplicate `_ref` methods, the `Envelope` spelling in `EnvelopeId`/`EnvelopeRecord` (now `TransferId`/`TransferRecord`), and the four-way balance surface (`compute_balance` becomes `balance_exact`; cache maintenance moves to `Ledger::projection()`). Nothing stored changes. Follows 0025; supersedes 0012's builder clause. |
 | [0027](0027-value-date-separate-from-commit-time.md) | Value date, separate from commit time and inside the content address | accepted | An entry can be booked one day and take effect another. `ValueDate` is a calendar day on `Transfer` and `Envelope`, inside the content address, so two entries differing only in the day they take effect are two transfers. `created_at` keeps its single meaning as the commit clock the balance cache folds against; migration 013 adds a filterable column and `TransferQuery` gains its own window. Bumps `CANONICAL_VERSION`. Follows 0026; constrained by 0019. |
@@ -44,48 +48,49 @@ to reverse a decision. Instead, a new ADR supersedes it.
 
 ## Recommended future ADRs
 
-Real decisions whose rationale lives in the code/docs but is not yet
-captured as an ADR, roughly in priority order:
+These are real decisions. Their rationale lives in the code and the documents,
+and no record captures it yet. They are in rough order of priority:
 
-1. **Content-addressed transfer ids, and rejecting a sequential hash
-   chain**: `TransferId = double-SHA-256(canonical bytes)` for idempotency
-   + tamper evidence, and why a per-transfer hash chain was rejected (a
-   concurrency bottleneck). See the "No Sequential Hash Chain" section of
-   `architecture.md`.
-2. **Pure core / async layer split**: a zero-IO, deterministic
-   `kuatia-core` (validation, selection, hashing; golden-vector testable)
-   vs. the async storage + saga layer.
-3. **Rust-generated ids (`AutoId`), no `AUTOINCREMENT`/`SERIAL`**: the
-   application owns identity (snowflake-style `i64`), enabling future
-   sharding without DB coordination.
-4. **Append-only, versioned accounts + snapshot pinning**: accounts are
-   never modified in place; snapshot hashes guard against TOCTOU between
-   load and apply.
-5. **Pushing posting selection into SQL**: now that amount columns are
-   orderable (ADR-0024), greedy largest-first selection could run as a
-   query instead of fetching every live posting; whether the resolve
-   decision should move into the store at all is undecided.
-6. **Posting proliferation & consolidation**: greedy largest-first
-   selection (ADR-0001/0005) fragments balances into ever-smaller change
-   postings; whether and how to consolidate, and what to do with dust, is
-   undecided.
-7. **Retention / pruning of spent postings and the append-only logs**: the
-   immutable postings table (ADR-0016), the transfer log, and the derived
-   event stream (ADR-0010) all grow without bound; archival/retention is
-   deferred and currently a conscious omission. ADR-0016 makes the spent
-   history physically separable from the live working set, which is where
-   pruning would apply.
-8. **Read/projection consistency model**: a balance is a non-transactional
-   sum over the live (active or reserved) postings, so a read concurrent
-   with a commit is eventually consistent; the read-side guarantee is
-   implied but never stated.
-9. **An accounting class on an account**: an account has no
-   asset/liability/equity/income/expense dimension, so a balance sheet or
-   a P&L cannot be grouped from the ledger; whether that class belongs on
-   the account, in metadata, or outside the ledger entirely is undecided.
-   See [accounts.md](../accounts.md#accounts-carry-no-accounting-class).
-10. **Whether tenancy belongs in the ledger**: `Book` gates participation
-    and isolates nothing, so today a tenant is a separate `Store`;
-    whether the ledger should own a tenant dimension instead is
-    undecided. See
+1. **A content-addressed transfer id, and the rejection of a sequential hash
+   chain**: `TransferId = double-SHA-256(canonical bytes)` gives idempotency and
+   tamper evidence. The record must also say why the design turned down a hash
+   chain per transfer, which was a concurrency bottleneck. See the "No
+   Sequential Hash Chain" section of `architecture.md`.
+2. **The split between the pure core and the async layer**: `kuatia-core` is
+   deterministic and does no IO. It holds the validation, the selection and the
+   hash, and a golden vector can test it. The async layer holds the storage and
+   the saga.
+3. **An id that Rust generates through `AutoId`, with no `AUTOINCREMENT` and no
+   `SERIAL`**: the application owns the identity, as a snowflake-style `i64`.
+   That allows a later sharding with no coordination by the database.
+4. **An append-only, versioned account, plus snapshot pinning**: nothing
+   modifies an account in place. A snapshot hash guards against a TOCTOU race
+   between the load and the apply.
+5. **A move of the posting selection into SQL**: an amount column orders
+   numerically now (ADR-0024), so a greedy largest-first selection can run as a
+   query. Today the ledger fetches every live posting instead. Nobody has
+   decided whether the resolve decision belongs in the store at all.
+6. **The growth in the number of postings, and their consolidation**: the greedy
+   largest-first selection of ADR-0001 and ADR-0005 breaks a balance into change
+   postings. Those get smaller and smaller. Nobody has decided whether to
+   consolidate them, how to do it, or what to do with dust.
+7. **Retention for the spent postings and the append-only logs**: three things
+   grow without bound. Those are the immutable postings table (ADR-0016), the
+   transfer log, and the derived event stream (ADR-0010). An archive and a
+   retention policy are both deferred, and that omission is deliberate today.
+   ADR-0016 keeps the spent history physically apart from the live set, which is
+   where a retention policy applies.
+8. **The consistency model for a read and a projection**: a balance is a sum
+   over the live postings. Those are the active postings and the reserved ones.
+   That sum takes no transaction. So a read that runs beside a commit is
+   eventually consistent. The documents imply the guarantee on the read side and
+   never state it.
+9. **An accounting class on an account**: an account has no dimension for an
+   asset, a liability, equity, income or an expense. So the ledger cannot group
+   a balance sheet or a profit-and-loss statement. Nobody has decided where that
+   class belongs: on the account, in metadata, or outside the ledger. See
+   [accounts.md](../accounts.md#accounts-carry-no-accounting-class).
+10. **Whether tenancy belongs in the ledger**: `Book` gates participation and
+    isolates nothing, so a tenant is a separate `Store` today. Nobody has
+    decided whether the ledger must own a tenant dimension instead. See
     [glossary.md](../glossary.md#books-are-not-a-tenancy-boundary).

部分文件因为文件数量过多而无法显示