@serfab/cadre-core 1.7.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. package/README.md +8 -6
  2. package/dist/cadre-node.d.ts +527 -206
  3. package/dist/cadre-node.js +1084 -528
  4. package/dist/cadre-node.js.map +1 -1
  5. package/dist/control-authorization.d.ts +2 -2
  6. package/dist/control-authorization.js +1 -0
  7. package/dist/control-authorization.js.map +1 -1
  8. package/dist/control-cohort.d.ts +6 -0
  9. package/dist/control-cohort.js +6 -0
  10. package/dist/control-cohort.js.map +1 -1
  11. package/dist/control-database.d.ts +46 -8
  12. package/dist/control-database.js +97 -18
  13. package/dist/control-database.js.map +1 -1
  14. package/dist/control-formation-recorder.d.ts +37 -14
  15. package/dist/control-formation-recorder.js +60 -10
  16. package/dist/control-formation-recorder.js.map +1 -1
  17. package/dist/control-read-retry.d.ts +13 -12
  18. package/dist/control-read-retry.js +14 -12
  19. package/dist/control-read-retry.js.map +1 -1
  20. package/dist/control-schema.d.ts +1 -1
  21. package/dist/control-schema.js +67 -5
  22. package/dist/control-schema.js.map +1 -1
  23. package/dist/control-stream.d.ts +9 -1
  24. package/dist/control-stream.js +24 -1
  25. package/dist/control-stream.js.map +1 -1
  26. package/dist/control-write-retry.d.ts +12 -2
  27. package/dist/control-write-retry.js +13 -2
  28. package/dist/control-write-retry.js.map +1 -1
  29. package/dist/delegate-admission.d.ts +11 -8
  30. package/dist/delegate-admission.js +19 -11
  31. package/dist/delegate-admission.js.map +1 -1
  32. package/dist/diagnostics/connection-path.d.ts +0 -7
  33. package/dist/diagnostics/connection-path.js +0 -7
  34. package/dist/diagnostics/connection-path.js.map +1 -1
  35. package/dist/formation-approval.d.ts +7 -0
  36. package/dist/formation-approval.js +9 -3
  37. package/dist/formation-approval.js.map +1 -1
  38. package/dist/fs-atomic.d.ts +11 -2
  39. package/dist/fs-atomic.js +13 -3
  40. package/dist/fs-atomic.js.map +1 -1
  41. package/dist/hibernation-manager.d.ts +111 -8
  42. package/dist/hibernation-manager.js +234 -49
  43. package/dist/hibernation-manager.js.map +1 -1
  44. package/dist/index.d.ts +10 -10
  45. package/dist/index.js +25 -20
  46. package/dist/index.js.map +1 -1
  47. package/dist/joined-strand-store.d.ts +90 -25
  48. package/dist/joined-strand-store.js +223 -55
  49. package/dist/joined-strand-store.js.map +1 -1
  50. package/dist/key-store-file.js +14 -5
  51. package/dist/key-store-file.js.map +1 -1
  52. package/dist/link-budget.d.ts +367 -69
  53. package/dist/link-budget.js +375 -72
  54. package/dist/link-budget.js.map +1 -1
  55. package/dist/membership-connection-gater.d.ts +30 -43
  56. package/dist/membership-connection-gater.js +31 -42
  57. package/dist/membership-connection-gater.js.map +1 -1
  58. package/dist/node-local-snapshot.d.ts +6 -4
  59. package/dist/node-local-snapshot.js +7 -3
  60. package/dist/node-local-snapshot.js.map +1 -1
  61. package/dist/peer-dial.d.ts +24 -4
  62. package/dist/peer-dial.js +74 -5
  63. package/dist/peer-dial.js.map +1 -1
  64. package/dist/peer-join-backfill.d.ts +2 -10
  65. package/dist/peer-join-backfill.js +8 -8
  66. package/dist/peer-join-backfill.js.map +1 -1
  67. package/dist/push-fanout.d.ts +6 -0
  68. package/dist/push-fanout.js +6 -0
  69. package/dist/push-fanout.js.map +1 -1
  70. package/dist/relay-reservation.d.ts +3 -1
  71. package/dist/relay-reservation.js +3 -1
  72. package/dist/relay-reservation.js.map +1 -1
  73. package/dist/relay-server.d.ts +79 -0
  74. package/dist/relay-server.js +74 -0
  75. package/dist/relay-server.js.map +1 -0
  76. package/dist/seed-bootstrap.d.ts +57 -4
  77. package/dist/seed-bootstrap.js +107 -83
  78. package/dist/seed-bootstrap.js.map +1 -1
  79. package/dist/storage-scope.d.ts +33 -17
  80. package/dist/storage-scope.js +44 -23
  81. package/dist/storage-scope.js.map +1 -1
  82. package/dist/strand-addr-protocol.d.ts +58 -21
  83. package/dist/strand-addr-protocol.js +133 -85
  84. package/dist/strand-addr-protocol.js.map +1 -1
  85. package/dist/strand-database.d.ts +20 -2
  86. package/dist/strand-database.js +42 -5
  87. package/dist/strand-database.js.map +1 -1
  88. package/dist/strand-first-sync-gate.d.ts +59 -21
  89. package/dist/strand-first-sync-gate.js +58 -19
  90. package/dist/strand-first-sync-gate.js.map +1 -1
  91. package/dist/strand-formation-deadlines.d.ts +151 -0
  92. package/dist/strand-formation-deadlines.js +171 -0
  93. package/dist/strand-formation-deadlines.js.map +1 -0
  94. package/dist/strand-formation-manager.d.ts +63 -30
  95. package/dist/strand-formation-manager.js +67 -41
  96. package/dist/strand-formation-manager.js.map +1 -1
  97. package/dist/strand-formation-protocol.d.ts +45 -46
  98. package/dist/strand-formation-protocol.js +62 -126
  99. package/dist/strand-formation-protocol.js.map +1 -1
  100. package/dist/strand-fret-addrs.d.ts +54 -0
  101. package/dist/strand-fret-addrs.js +108 -0
  102. package/dist/strand-fret-addrs.js.map +1 -0
  103. package/dist/strand-instance-manager.d.ts +122 -44
  104. package/dist/strand-instance-manager.js +270 -114
  105. package/dist/strand-instance-manager.js.map +1 -1
  106. package/dist/strand-membership-writer.d.ts +6 -0
  107. package/dist/strand-membership-writer.js +11 -0
  108. package/dist/strand-membership-writer.js.map +1 -1
  109. package/dist/strand-network-state-file.d.ts +12 -0
  110. package/dist/strand-network-state-file.js +38 -0
  111. package/dist/strand-network-state-file.js.map +1 -0
  112. package/dist/strand-network-state.d.ts +111 -0
  113. package/dist/strand-network-state.js +191 -0
  114. package/dist/strand-network-state.js.map +1 -0
  115. package/dist/strand-revocation-enforcer.js +2 -1
  116. package/dist/strand-revocation-enforcer.js.map +1 -1
  117. package/dist/strand-solicitation.d.ts +36 -20
  118. package/dist/strand-solicitation.js +4 -4
  119. package/dist/strand-solicitation.js.map +1 -1
  120. package/dist/strand-wake-protocol.d.ts +80 -23
  121. package/dist/strand-wake-protocol.js +89 -64
  122. package/dist/strand-wake-protocol.js.map +1 -1
  123. package/dist/types.d.ts +148 -61
  124. package/dist/types.js +4 -3
  125. package/dist/types.js.map +1 -1
  126. package/package.json +11 -10
  127. package/src/cadre-node.ts +8400 -7776
  128. package/src/control-authorization.ts +2 -1
  129. package/src/control-cohort.ts +6 -0
  130. package/src/control-database.ts +122 -18
  131. package/src/control-formation-recorder.ts +354 -305
  132. package/src/control-read-retry.ts +14 -12
  133. package/src/control-schema.ts +67 -5
  134. package/src/control-stream.ts +25 -1
  135. package/src/control-write-retry.ts +13 -2
  136. package/src/delegate-admission.ts +23 -13
  137. package/src/diagnostics/connection-path.ts +0 -7
  138. package/src/formation-approval.ts +610 -604
  139. package/src/fs-atomic.ts +14 -4
  140. package/src/hibernation-manager.ts +638 -437
  141. package/src/index.ts +43 -65
  142. package/src/joined-strand-store.ts +247 -57
  143. package/src/key-store-file.ts +14 -5
  144. package/src/link-budget.ts +393 -74
  145. package/src/membership-connection-gater.ts +31 -45
  146. package/src/node-local-snapshot.ts +12 -7
  147. package/src/peer-dial.ts +81 -7
  148. package/src/peer-join-backfill.ts +10 -9
  149. package/src/push-fanout.ts +6 -0
  150. package/src/relay-reservation.ts +3 -1
  151. package/src/relay-server.ts +98 -0
  152. package/src/seed-bootstrap.ts +133 -91
  153. package/src/storage-scope.ts +44 -23
  154. package/src/strand-addr-protocol.ts +547 -458
  155. package/src/strand-database.ts +287 -242
  156. package/src/strand-first-sync-gate.ts +58 -19
  157. package/src/strand-formation-deadlines.ts +227 -0
  158. package/src/strand-formation-manager.ts +700 -647
  159. package/src/strand-formation-protocol.ts +106 -154
  160. package/src/strand-fret-addrs.ts +145 -0
  161. package/src/strand-instance-manager.ts +307 -140
  162. package/src/strand-membership-writer.ts +12 -0
  163. package/src/strand-network-state-file.ts +40 -0
  164. package/src/strand-network-state.ts +243 -0
  165. package/src/strand-revocation-enforcer.ts +2 -1
  166. package/src/strand-solicitation.ts +519 -500
  167. package/src/strand-wake-protocol.ts +401 -355
  168. package/src/types.ts +150 -61
  169. package/dist/strand-peer-book-file.d.ts +0 -12
  170. package/dist/strand-peer-book-file.js +0 -37
  171. package/dist/strand-peer-book-file.js.map +0 -1
  172. package/dist/strand-peer-book-protocol.d.ts +0 -159
  173. package/dist/strand-peer-book-protocol.js +0 -360
  174. package/dist/strand-peer-book-protocol.js.map +0 -1
  175. package/dist/strand-peer-book-swap.d.ts +0 -104
  176. package/dist/strand-peer-book-swap.js +0 -284
  177. package/dist/strand-peer-book-swap.js.map +0 -1
  178. package/dist/strand-peer-book.d.ts +0 -159
  179. package/dist/strand-peer-book.js +0 -354
  180. package/dist/strand-peer-book.js.map +0 -1
  181. package/dist/strand-peer-observer.d.ts +0 -88
  182. package/dist/strand-peer-observer.js +0 -180
  183. package/dist/strand-peer-observer.js.map +0 -1
  184. package/src/strand-peer-book-file.ts +0 -39
  185. package/src/strand-peer-book-protocol.ts +0 -463
  186. package/src/strand-peer-book-swap.ts +0 -338
  187. package/src/strand-peer-book.ts +0 -468
  188. package/src/strand-peer-observer.ts +0 -235
@@ -9,4 +9,4 @@
9
9
  * build if they drift. Any edit here must be mirrored in `schemas/control.qsql`
10
10
  * and vice versa.
11
11
  */
12
- export declare const CONTROL_SCHEMA = "-- This manages a Sereus party's cadre, or set of nodes, and their participation in strands (networks)\ndeclare schema CadreControl {\n -- A key that can authorize various control changes\n table OwnerKey (\n Key text primary key,\n StampId text not null unique, -- per-row authorization nonce, bound into the signed digests below.\n -- `unique` holds over LIVE rows only; a removed row's stamp is retired\n -- permanently into Revocation (NotRevoked below), so the never-expiring\n -- enrollment signature cannot resurrect a removed owner.\n -- A removed row's StampId is retired into Revocation, and this refuses any insert\n -- naming a retired stamp: the approval that seated this row can never re-seat it after\n -- removal. `unique` alone did not do this \u2014 it only holds over LIVE rows, so a delete\n -- freed the stamp and the original never-expiring signature verified again. A\n -- legitimate re-add mints a FRESH StampId and a fresh signature, so it is unaffected.\n constraint NotRevoked check on insert (\n not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = new.StampId)\n ),\n -- Retirement is MANDATORY: a delete must carry the matching Revocation row in the same\n -- transaction, or the stamp would free up again. Deferred (subquery), so the sibling\n -- insert is visible at commit regardless of statement order. The tombstone must also\n -- name the removed ROW, not just its stamp \u2014 see Revocation.RowKey.\n constraint RevocationRecorded check on delete (\n exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = old.StampId and R.RowKey = old.Key)\n ),\n -- A party must never lose its last owner key: every other CadreControl table's\n -- CHECK requires an OwnerKey row, so an owner-less control database can never\n -- authorize anything again \u2014 emptying this table is a permanent denial of the\n -- party's control plane. Deferred (subquery), so the count is the POST-delete count.\n -- NOTE: this is a per-transaction check against locally visible rows. Two\n -- partitioned nodes that concurrently remove different owners can each see a\n -- survivor and still converge to zero; if partitioned rotation ever becomes a real\n -- workflow, the floor needs a cross-node guard, not a local count.\n constraint MinOneOwner check on delete (\n (select count(1) from OwnerKey) >= 1\n ),\n -- Enrollment is insert + delete only; rotation is add-then-remove. No writer\n -- updates an OwnerKey row, and a self-rotation branch would double as a sole-owner\n -- takeover: a deferred post-image count is also true of an update that re-points\n -- the only row at an attacker key. Mirrors Strand.Manager.NoUpdate.\n constraint NoUpdate check on update (false),\n -- NOTE: the domain tag scopes an approval to a table and an action, not to a PARTY. Two\n -- parties that share an owner key would accept each other's approvals. Fine today (each\n -- party has its own owner key); if shared-owner multi-party ever ships, bind a party\n -- identity row into these digests.\n constraint Authorized check on insert, delete (\n -- Every authorizer is read from the PRE-transaction snapshot (committed.*):\n -- this CHECK auto-defers to commit (it has a subquery), by which point the row\n -- being inserted \u2014 and any sibling inserted alongside it \u2014 is live, so a plain\n -- from-OwnerKey would let a row authorize itself, or two strangers seat each\n -- other. committed.* excludes both, stating the rule directly: the authorizer\n -- must have existed BEFORE this transaction.\n\n -- Every signed digest below (and in every other CadreControl table) leads with two\n -- fixed literals \u2014 a 'CadreControl.<Table>' domain tag and an 'add'/'remove'/\n -- 'vouch'/'publish' action tag (cadre-core control-authorization.ts) \u2014 so an\n -- approval verifies ONLY against the one rule it was minted for. Without them,\n -- e.g. a ValidationKey enrollment approval covered the identical bytes as an\n -- OwnerKey enrollment: a narrow grant that doubled as full ownership.\n\n -- Bootstrap: the FOUNDING transaction \u2014 one whose pre-transaction owner set is\n -- empty \u2014 needs no authorization, and every row it inserts rides this branch\n -- (whoever writes it already owns the party outright, so a co-founder row grants\n -- nothing a single row would not). Gated on the PRE-transaction count, so a\n -- same-transaction swap of the sole owner (delete the founder, insert the\n -- attacker \u2014 post-image count still 1) cannot ride it.\n (old.Key is null and (select count(1) from committed.OwnerKey) = 0)\n\n -- or a pre-existing owner authorizes by signing over THIS row (Key, StampId)\n or (old.Key is null and exists (select 1 from committed.OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.OwnerKey', 'add', new.Key, new.StampId), context.Signature, A.Key, 'ed25519')))\n\n -- or a removal authorized by ANOTHER pre-existing owner over the DISTINCT\n -- 'remove'-tagged digest bound to the stored row's StampId, so an enrollment\n -- signature can never be replayed as a removal (cf. CadrePeer.AuthorizedDelete).\n -- A.Key <> old.Key: an owner cannot sign its own removal (no self-resignation).\n or (new.Key is null and exists (select 1 from committed.OwnerKey A where A.Key = context.OwnerKey and A.Key <> old.Key and verify(digest('CadreControl.OwnerKey', 'remove', old.Key, old.StampId), context.Signature, A.Key, 'ed25519')))\n )\n ) with context (OwnerKey text null, Signature text null);\n\n -- A key that can validate a strand formation disclosure\n table ValidationKey (\n Key text primary key,\n StampId text not null unique, -- single-use authorization nonce (anti-replay).\n -- `unique` holds over LIVE rows only; a removed row's stamp is retired\n -- permanently into Revocation (NotRevoked below), so the never-expiring\n -- enrollment signature cannot resurrect a removed key.\n -- A removed row's StampId is retired into Revocation, and this refuses any insert naming\n -- a retired stamp: the approval that seated this row can never re-seat it after removal.\n -- Same rationale as OwnerKey.NotRevoked, stated in full there.\n -- NOTE: this table gained a consumer \u2014 FormationUsage.Authorized reads it to gate redemption of\n -- a ValidationUrl invite \u2014 so the convergence gap noted on Strand.StampId now has teeth here: on\n -- a node that has not yet seen the tombstone, a replayed enrollment re-seats the key and it can\n -- approve redemptions there until the Revocation row arrives. Still no per-request READ surface to\n -- filter (the gate is a write-time CHECK), so there is nothing to add today; if one appears, filter\n -- retired stamps there.\n constraint NotRevoked check on insert (\n not exists (select 1 from Revocation R where R.TableName = 'ValidationKey' and R.StampId = new.StampId)\n ),\n -- Retirement is MANDATORY: a delete must carry the matching Revocation row in the same\n -- transaction, or the stamp would free up again. Deferred (subquery), so the sibling\n -- insert is visible at commit regardless of statement order. The tombstone must also\n -- name the removed ROW, not just its stamp \u2014 see Revocation.RowKey.\n constraint RevocationRecorded check on delete (\n exists (select 1 from Revocation R where R.TableName = 'ValidationKey' and R.StampId = old.StampId and R.RowKey = old.Key)\n ),\n -- Enrollment is insert + delete only; rotation is add-then-remove. No writer in the repo\n -- updates a ValidationKey row. Required because the AuthorizedInsert / AuthorizedDelete\n -- pair below covers neither update \u2014 and a bare `check`, which is what this rule used to\n -- be, covers insert+update but NOT delete. Mirrors OwnerKey.NoUpdate.\n constraint NoUpdate check on update (false),\n constraint AuthorizedInsert check on insert (\n -- Owners authorize by signing over THIS row (Key, StampId); single-use via unique StampId\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.ValidationKey', 'add', new.Key, new.StampId), context.Signature, A.Key, 'ed25519'))\n ),\n constraint AuthorizedDelete check on delete (\n -- Delete is authorized by a signature over the DISTINCT 'remove'-tagged digest bound to\n -- the STORED row (Key, StampId), so an enrollment approval \u2014 which never expires \u2014 can\n -- never be replayed as a removal. Same shape as CadrePeer.AuthorizedDelete.\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.ValidationKey', 'remove', old.Key, old.StampId), context.Signature, A.Key, 'ed25519'))\n\n -- or REAP: a COMMITTED tombstone already retires this exact row incarnation, so a node\n -- that was offline at removal time may delete the stale row locally with no owner key.\n -- Why committed.* and why the stamp must be bound: stated in full on\n -- CadrePeer.AuthorizedDelete.\n or exists (select 1 from committed.Revocation R where R.TableName = 'ValidationKey' and R.RowKey = old.Key and R.StampId = old.StampId)\n )\n ) with context (OwnerKey text, Signature text);\n\n -- A network of members sharing an sApp database, each contributing peer nodes (their cadre) to the overall cohort\n -- Cadre peers should participate in each of these strands\n table Strand (\n Id text primary key, -- UUID\n MemberPrivateKey text null unique, -- Our private key as a member of this strand\n Type text, -- Types: 'o' = Open, 'c' = Closed -- Open can still control writes in the sApp, but only Closed controls reads\n FounderOwnerKey text null, -- ed25519 (base64url) owner key of the MACHINE that published this row\n -- (== insert context.OwnerKey; in the reference model each machine's\n -- owner key is the key behind its PeerId, so this names the founding\n -- machine \u2014 the one machine that runs the strand's one-time founder\n -- bootstrap). cadre-core derives \"am I the founder?\" at launch by\n -- comparing it to the node's own owner key (cadre-node.ts\n -- launchStrand). Null on a consent-seated strand \u2014 the consent branch\n -- of AuthorizedInsert carries no signature, so there is no\n -- trustworthy signer to record (see the NOTE on that branch below).\n -- Provenance, not content: cadre-node.ts strandRowMismatches\n -- deliberately excludes it from the identical-content comparison.\n StampId text not null unique, -- single-use authorization nonce (anti-replay).\n -- `unique` holds over LIVE rows only; a removed row's stamp is retired\n -- permanently into Revocation (NotRevoked below).\n -- NOTE: NotRevoked is a per-transaction check against LOCALLY VISIBLE rows, so a node that\n -- has not yet converged on the Revocation row can still accept a replayed add and end up\n -- holding the resurrected strand alongside its tombstone. CadrePeer has a read-side\n -- mitigation for this class (ControlDatabase.queryCadrePeers drops rows whose stamp is\n -- retired, so every membership reader inherits it); Strand and ValidationKey deliberately\n -- do NOT, because neither has a\n -- per-request authorization surface today. If one ever gains one, filter it there.\n constraint NotRevoked check on insert (\n not exists (select 1 from Revocation R where R.TableName = 'Strand' and R.StampId = new.StampId)\n ),\n -- Retirement is MANDATORY: a delete must carry the matching Revocation row in the same\n -- transaction, or the stamp would free up again. Deferred (subquery), so the sibling\n -- insert is visible at commit regardless of statement order. The tombstone must also\n -- name the removed ROW, not just its stamp \u2014 see Revocation.RowKey. That is what makes\n -- the consent branch of AuthorizedInsert below trustworthy: a removal cannot file a\n -- tombstone that omits or misnames the id it retires.\n constraint RevocationRecorded check on delete (\n exists (select 1 from Revocation R where R.TableName = 'Strand' and R.StampId = old.StampId and R.RowKey = old.Id)\n ),\n -- Strand rows are insert + delete only. Required: the consent branch of AuthorizedInsert\n -- below authorizes by the EXISTENCE of a FormationUsage row naming (new.Id, new.StampId)\n -- and carries no signature, so while this rule was a bare `check` (insert+update) it also\n -- said \"anyone may REWRITE any consent-formed strand, unsigned\" \u2014 flipping Type to 'o' and\n -- nulling MemberPrivateKey destroys the party's own membership key for that network in place.\n -- Mirrors OwnerKey.NoUpdate / FormationInvite.Immutable.\n constraint NoUpdate check on update (false),\n constraint AuthorizedInsert check on insert (\n -- Authorized by an owner signing over THIS row (Id, Type, MemberPrivateKey, StampId); single-use via unique StampId.\n -- FounderOwnerKey persists WHO published the row, so the founding machine can later\n -- recognise its own strand (founder derivation, cadre-node.ts launchStrand). The\n -- equality pins the stored column to the VERIFIED signer \u2014 same shape as\n -- CadrePeer.VouchOwner \u2014 so a writer cannot record a founder it is not. Deliberately\n -- NOT added to the signed digest: the equality already binds it to the signature's\n -- context.OwnerKey, and widening the digest would churn every existing\n -- insertStrand field-order contract for nothing.\n (exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.Strand', 'add', new.Id, new.Type, coalesce(new.MemberPrivateKey, ''), new.StampId), context.Signature, A.Key, 'ed25519'))\n and new.FounderOwnerKey = context.OwnerKey)\n\n -- or authorized WITHOUT a signature by a redemption record naming THIS EXACT ROW: a\n -- FormationUsage row carrying both this strand's Id and its one-off StampId\n -- (control-database.ts:redeemInvitation writes the pair in one transaction; both\n -- CHECKs defer, so each sees the other's row at commit).\n --\n -- Matching the STAMP, not the id alone, is what makes a removal stick. FormationUsage\n -- is append-only, so a redemption record outlives the strand it formed forever; keyed\n -- on the id alone it re-authorized ANY later insert of that id, so after a legitimate\n -- owner-signed, tombstoned removal any writer could re-seat the strand unsigned with a\n -- fresh StampId (sidestepping NotRevoked, which retires only the removed row's stamp)\n -- and an ATTACKER-CHOSEN MemberPrivateKey \u2014 the party's own secret for that network.\n -- Bound to the stamp, the removal retires that stamp into Revocation and NotRevoked\n -- closes this consent record's branch permanently.\n --\n -- Beyond the stamp match, the branch is deliberately NARROW \u2014 each clause closes one door:\n -- * Type = 'o' / MemberPrivateKey null \u2014 a consent-seated strand looks exactly like\n -- what the unbound redemption path writes (open, keyless). A closed strand carrying\n -- a caller-chosen member key (the party's own read-gating secret for that network)\n -- has no legitimate producer. MemberKeyClosedOnly already implies the second clause\n -- from the first today; both are stated so this rule does not silently depend on\n -- another constraint staying as it is.\n -- * the inner FI.StrandId is null \u2014 only an UNBOUND invite may seat a strand at all.\n -- A bound invite's host strand is owner-provisioned up front; letting the invite\n -- consent-seat that id would allow an open, keyless downgrade of the real (possibly\n -- closed, key-bearing) host row on a node where it has not converged yet. The bound\n -- path records usage only (resolveStrand reports an absent host as missing and the\n -- formation manager rejects cleanly).\n -- * the not-exists over OTHER stamps \u2014 a strand id may be consent-seated once, EVER.\n -- FormationUsage is append-only, so the first redemption's record survives a later\n -- owner-signed removal and permanently forecloses a second consent-seating of the\n -- id (a spare use of the same token minted a new stamp and rode this branch to\n -- re-seat the id with an attacker-chosen row). Re-joining a removed id is\n -- owner-gated: the owner re-seats it signed (fresh stamp, fresh signature) and\n -- issues a BOUND invite the returning party records consent against \u2014 the id is\n -- not blacklisted, only its unsigned re-seat is. This cannot be weaponised to\n -- pre-block a legitimate id: StrandExists refuses a usage row naming a strand that\n -- does not exist, so no usage row can be pre-planted for an unseated id \u2014 and ids\n -- are 128 random bytes anyway.\n -- * the not-exists over Revocation \u2014 a strand id may be consent-seated once EVER\n -- and never after ANY removal of that id, however it was seated. The usage-row\n -- rule above binds only ids that ever carried a consent record; an id seated\n -- purely owner-signed (insertStrand, no usage row) leaves nothing behind on\n -- removal, so its removal needs its own trace. Every removal files a Revocation\n -- row naming the removed row's key (RowKey), and this clause refuses any id\n -- that has ever been tombstoned. RevocationRecorded above makes that trace\n -- mandatory AND correctly named, so no removal can slip past this clause. The\n -- usage-row clause is arguably subsumed by this one (a usage row implies the\n -- strand row existed, and its removal must file a tombstone), but it reaches\n -- the same conclusion without depending on Revocation at all; both are stated,\n -- per the style note above. The owner-signed branch is deliberately unaffected,\n -- so re-join stays owner-gated exactly as described.\n -- What is NOT schema-verified is a STANDALONE tombstone (one with no\n -- accompanying delete \u2014 see Revocation.Authorized): an owner can file one\n -- naming an id that never existed and thereby permanently foreclose\n -- consent-seating of that id \u2014 owner-only, the owner already controls invite\n -- issuance, and unbound ids are 128 random bytes minted at redemption, so no\n -- escalation (same reasoning as the pre-plant note above).\n -- NOTE: like NotRevoked above, this is a write-time check against LOCALLY\n -- VISIBLE rows \u2014 a node that has not yet converged on the Revocation row still\n -- accepts the re-seat. Fails in the safe direction: the tombstone wins after\n -- merge for the STAMP, and the resurrected row coexists with it (same class as\n -- the StampId note above).\n or (\n new.Type = 'o'\n and new.MemberPrivateKey is null\n -- NOTE: a consent-seated strand records NO founder machine \u2014 this branch\n -- carries no signature, so there is no trustworthy signer to persist.\n -- Consequence: the restart-before-founding orphan shape (a relaunch cannot\n -- derive founder-ness from the row) persists for consent-formed strands\n -- only; the responder that provisions one must keep passing an explicit\n -- founder flag at launch. Revisit if consent-formed strands ever hit the\n -- empty-Header symptom in practice: FormationUsage names the redeeming\n -- peer (PeerKey), which is the candidate derivation source.\n and new.FounderOwnerKey is null\n and exists (\n select 1 from FormationUsage FU\n where FU.StrandId = new.Id\n and FU.StrandStampId = new.StampId\n and exists (select 1 from FormationInvite FI where FI.Token = FU.Token and FI.StrandId is null)\n )\n and not exists (\n select 1 from FormationUsage FU2\n where FU2.StrandId = new.Id and FU2.StrandStampId <> new.StampId\n )\n and not exists (\n select 1 from Revocation R\n where R.TableName = 'Strand' and R.RowKey = new.Id\n )\n )\n ),\n constraint AuthorizedDelete check on delete (\n -- Delete is authorized by a signature over the DISTINCT 'remove'-tagged digest bound to\n -- the STORED row (Id, StampId), so the add approval \u2014 which never expires \u2014 can never be\n -- replayed as a removal. Note the consent branch above is deliberately NOT mirrored\n -- here: an invitation authorizes forming a strand, never destroying one.\n --\n -- DELIBERATELY no REAP branch (cf. CadrePeer.AuthorizedDelete): this row carries\n -- MemberPrivateKey \u2014 the party's own membership secret for that network, stored nowhere\n -- else \u2014 so this is the one guarded delete whose effect is unrecoverable, and a stale\n -- row is already inert for the purpose a tombstone serves (the consent branch of\n -- AuthorizedInsert above refuses any id ever tombstoned). Do not \"fix\" the asymmetry;\n -- tickets/backlog/debt-strand-tombstone-reap.md owns any future change.\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.Strand', 'remove', old.Id, old.StampId), context.Signature, A.Key, 'ed25519'))\n ),\n constraint MemberKeyClosedOnly check (\n -- An open strand ('o') has no membership gate, so it must not carry a\n -- member key. A non-null MemberPrivateKey requires a closed strand ('c').\n new.MemberPrivateKey is null or new.Type = 'c'\n )\n ) with context (OwnerKey text, Signature text);\n\n -- ONE party's own membership identity for one strand: the private key whose public\n -- half seats this party's `Strand.Member` / `Strand.Manager` rows. Deliberately a\n -- SEPARATE key from Strand.MemberPrivateKey \u2014 that column is the strand-wide read\n -- secret formation hands to EVERY joining party, so an identity derived from it is\n -- one every joiner can forge (gotchoices/sereus#4). A side table rather than a\n -- Strand column because a JOINER holds no control Strand row at all (reference apps\n -- attach formed strands from an in-memory row) yet must persist its own party key\n -- too; keyed by strand id it serves founder and joiner uniformly, and it leaves the\n -- heavily-audited Strand insert digest untouched. Deliberately NO closed-strands-only\n -- cross-table check: the joiner writes this row with no local Strand row to check\n -- against. Party-private in the same sense as MemberPrivateKey \u2014 replicated in\n -- plaintext to every machine the party owns (docs/strands.md \u2192 \"Closed-Strand Member\n -- Key Handling\"; that replication is what lets any of the party's machines sign\n -- membership writes) \u2014 but unlike MemberPrivateKey it is NEVER put on the formation\n -- wire.\n table StrandPartyKey (\n Id text primary key, -- the strand id this key is for\n PrivateKey text not null, -- THIS party's ed25519 strand member private key, base64\n -- protobuf \u2014 the same encoding as Strand.MemberPrivateKey;\n -- decode with cadre-core's strandMemberKeyPair.\n StampId text not null unique, -- single-use authorization nonce (anti-replay).\n -- `unique` holds over LIVE rows only; a removed row's stamp is\n -- retired permanently into Revocation (NotRevoked below).\n -- A removed row's StampId is retired into Revocation, and this refuses any insert\n -- naming a retired stamp: the approval that seated this row can never re-seat it\n -- after removal. Same rationale as OwnerKey.NotRevoked, stated in full there.\n constraint NotRevoked check on insert (\n not exists (select 1 from Revocation R where R.TableName = 'StrandPartyKey' and R.StampId = new.StampId)\n ),\n -- Retirement is MANDATORY: a delete must carry the matching Revocation row in the same\n -- transaction, or the stamp would free up again. Deferred (subquery), so the sibling\n -- insert is visible at commit regardless of statement order. The tombstone must also\n -- name the removed ROW, not just its stamp \u2014 see Revocation.RowKey.\n constraint RevocationRecorded check on delete (\n exists (select 1 from Revocation R where R.TableName = 'StrandPartyKey' and R.StampId = old.StampId and R.RowKey = old.Id)\n ),\n -- Insert + delete only; a rotation is remove-then-insert (fresh stamp, fresh\n -- signature). Required because AuthorizedInsert / AuthorizedDelete below cover\n -- neither update \u2014 an in-place rewrite would swap the party's identity key with\n -- no signature at all. Mirrors ValidationKey.NoUpdate.\n constraint NoUpdate check on update (false),\n constraint AuthorizedInsert check on insert (\n -- Owners authorize by signing over THIS row (Id, PrivateKey, StampId);\n -- single-use via unique StampId. Binding PrivateKey means a captured approval\n -- can only ever reproduce the exact key it approved, never seat an\n -- attacker-chosen identity under the party's name.\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.StrandPartyKey', 'add', new.Id, new.PrivateKey, new.StampId), context.Signature, A.Key, 'ed25519'))\n ),\n constraint AuthorizedDelete check on delete (\n -- Delete is authorized by a signature over the DISTINCT 'remove'-tagged digest\n -- bound to the STORED row (Id, StampId), so the enrollment approval \u2014 which\n -- never expires \u2014 can never be replayed as a removal.\n -- DELIBERATELY no REAP branch (cf. ValidationKey.AuthorizedDelete): like\n -- Strand.MemberPrivateKey, PrivateKey is a secret stored nowhere else, so this\n -- delete's effect is unrecoverable and stays strictly owner-signed. Same\n -- reasoning as Strand.AuthorizedDelete.\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.StrandPartyKey', 'remove', old.Id, old.StampId), context.Signature, A.Key, 'ed25519'))\n )\n ) with context (OwnerKey text, Signature text);\n\n -- A peer (node) that is part of the cadre, carrying a self-published,\n -- freshness-stamped, self-signed address record (see PeerAddressRecord in cadre-core).\n -- The row IS the peer-address record: a resolver reads it, re-verifies Sig against\n -- PublicKey, checks freshness (UpdatedAt) and trust, then dials the addrs.\n table CadrePeer (\n PeerId text primary key,\n PublicKey text null, -- ed25519 (base64url) whose libp2p identity == PeerId (null if non-Ed25519)\n Multiaddr text, -- comma-joined current addrs (signaling / p2p-circuit first)\n UpdatedAt int null, -- epoch ms; strictly increases per self-update (replay/rollback guard)\n Sig text null, -- ed25519 self-signature over the signed payload (base64url); null until self-published\n StampId text not null unique, -- per-row authorization nonce, bound into the voucher/remove digests; rotates on\n -- (re)insert. A removed row's stamp is retired permanently into Revocation\n -- (NotRevoked below), so a captured admission approval cannot re-seat a removed peer.\n VouchOwner text null, -- ed25519 (base64url) owner key that vouched this membership (== insert context.OwnerKey)\n VouchSig text null, -- that owner's signature over the 'vouch'-tagged digest below (== insert context.Signature). A reader checks VouchOwner against its NODE-LOCAL trusted-owner anchor (not this replicated table, which a self-owner can pollute) to decide authorized membership. The domain/action tags keep this STORED, REPLICATED signature useless against every other rule (pre-tag it satisfied OwnerKey/ValidationKey inserts for Key = PeerId).\n -- A removed row's StampId is retired into Revocation, and this refuses any insert\n -- naming a retired stamp: the approval that seated this row can never re-seat it after\n -- removal. `unique` alone did not do this \u2014 it only holds over LIVE rows, so a delete\n -- freed the stamp and the original never-expiring signature verified again. A\n -- legitimate re-add mints a FRESH StampId and a fresh signature, so it is unaffected.\n constraint NotRevoked check on insert (\n not exists (select 1 from Revocation R where R.TableName = 'CadrePeer' and R.StampId = new.StampId)\n ),\n -- Retirement is MANDATORY: a delete must carry the matching Revocation row in the same\n -- transaction, or the stamp would free up again. Deferred (subquery), so the sibling\n -- insert is visible at commit regardless of statement order. The tombstone must also\n -- name the removed ROW, not just its stamp \u2014 see Revocation.RowKey.\n constraint RevocationRecorded check on delete (\n exists (select 1 from Revocation R where R.TableName = 'CadrePeer' and R.StampId = old.StampId and R.RowKey = old.PeerId)\n ),\n constraint AuthorizedInsert check on insert (\n -- Authorized by an owner key, which vouches both membership and the\n -- PublicKey<->PeerId binding (cadre-core derives PublicKey from PeerId before insert).\n -- The digest binds PeerId + the single-use StampId nonce (two TEXT fields),\n -- matching cadre-core peer-authorization.ts:cadrePeerVoucherDigest. The same\n -- 'vouch'-tagged digest is DELIBERATELY shared with the owner branch of\n -- AuthorizedUpdate below: both mean \"this owner vouches this membership row\".\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.CadrePeer', 'vouch', new.PeerId, new.StampId), context.Signature, A.Key, 'ed25519'))\n -- Persist the vouching (owner, signature) onto the row so a reader can later\n -- re-check VouchOwner against its node-local anchor. The stored pair MUST equal\n -- the pair the verify above validated, so a writer cannot store a voucher it did\n -- not actually receive a signature for.\n and new.VouchOwner = context.OwnerKey\n and new.VouchSig = context.Signature\n ),\n constraint AuthorizedDelete check on delete (\n -- Delete is authorized by a signature over the DISTINCT 'remove'-tagged digest bound\n -- to the row's StampId (cadre-core peer-authorization.ts:cadrePeerRemoveDigest), so\n -- the stored voucher (a signature over the 'vouch'-tagged digest) can NEVER be\n -- replayed to authorize a delete. The remove signature rides in context and is never stored.\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.CadrePeer', 'remove', old.PeerId, old.StampId), context.Signature, A.Key, 'ed25519'))\n\n -- or REAP: this node already holds a COMMITTED tombstone retiring THIS EXACT row\n -- incarnation, so the party owner has already authorized this row's removal and this\n -- node is merely catching up. That is what lets a node which was offline at\n -- revocation time delete the stale row locally, with no owner private key\n -- (control-database.ts:reapRevokedRow). Same shape as the consent branch of\n -- Strand.AuthorizedInsert: authorization by the EXISTENCE of a row rather than by a\n -- signature \u2014 and that row is itself owner-signed (Revocation.Authorized), so this\n -- widens WHO may execute a removal, never WHO may decide one. RevocationRecorded is\n -- satisfied by the same committed tombstone, so a reap files no second one.\n --\n -- committed.Revocation, NOT Revocation \u2014 and the stamp clause \u2014 are both load-bearing:\n -- * committed.* : this CHECK defers to commit (it has a subquery), by which point a\n -- tombstone written in the SAME transaction is live. Reading plain Revocation\n -- would therefore let deleteGuardedRow's own sibling tombstone satisfy this\n -- branch, making the 'remove'-tagged delete signature above dead weight and\n -- collapsing two domain-separated approvals into one. committed.* states the rule\n -- exactly: the tombstone must have existed BEFORE this transaction.\n -- * R.StampId = old.StampId : binds the ROW INCARNATION, not the name. One name may\n -- legitimately carry several tombstones over its life (seat -> delete -> owner\n -- re-seat -> delete). Without this clause a tombstone from a PREVIOUS incarnation\n -- would authorize deleting the CURRENT row, which the owner never removed.\n or exists (select 1 from committed.Revocation R where R.TableName = 'CadrePeer' and R.RowKey = old.PeerId and R.StampId = old.StampId)\n ),\n constraint AuthorizedUpdate check on update (\n -- Peer self-updates its own addrs + freshness, signing with its OWN ed25519 key\n -- (the key behind PeerId). PeerId/PublicKey/StampId/voucher are immutable on\n -- self-update, UpdatedAt must strictly increase (replay guard), and Sig is verified\n -- against the stored PublicKey over the same payload the publish path signs\n -- (cadre-core peer-record.ts:peerRecordSignedPayload).\n (\n new.PeerId = old.PeerId\n and new.PublicKey = old.PublicKey\n and new.StampId = old.StampId\n and new.VouchOwner = old.VouchOwner\n and new.VouchSig = old.VouchSig\n and new.UpdatedAt > coalesce(old.UpdatedAt, 0)\n and verify(\n digest('CadreControl.CadrePeer', 'publish', new.PeerId, new.Multiaddr, cast(new.UpdatedAt as text)),\n new.Sig, new.PublicKey, 'ed25519')\n )\n -- or an owner re-authorizes (rotation / correction): re-vouches the row over\n -- its current StampId, so the stored voucher is re-bound to the re-authorizing owner.\n -- StampId is immutable here too: an update that rotated it would leave the OLD\n -- stamp live-free and untombstoned (RevocationRecorded only retires the stamp a\n -- delete carries), so the original admission approval \u2014 which is stored on the\n -- replicated row as VouchSig \u2014 would resurrect the peer after a later removal.\n -- Retiring a stamp is delete + Revocation row, never an update.\n or (\n new.StampId = old.StampId\n and exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.CadrePeer', 'vouch', new.PeerId, new.StampId), context.Signature, A.Key, 'ed25519'))\n and new.VouchOwner = context.OwnerKey\n and new.VouchSig = context.Signature\n )\n )\n ) with context (OwnerKey text null, Signature text);\n\n -- A mobile cadre peer's platform push token (FCM/APNs), self-published so a\n -- server peer can deliver a push-wake to a suspended app over the platform push\n -- channel (a control-network dial cannot reach an OS-suspended process). The row\n -- mirrors CadrePeer: a resolver re-verifies Sig against the CadrePeer.PublicKey for\n -- this PeerId (see device-token.ts:deviceTokenSignedPayload), checks freshness, then\n -- hands the token to the push sender.\n table DeviceToken (\n PeerId text primary key, -- the CadrePeer this token belongs to\n Platform text not null, -- 'fcm' | 'apns'\n Token text not null, -- opaque platform device/registration token\n UpdatedAt int null, -- epoch ms; strictly increases per self-update (replay guard)\n Sig text null, -- ed25519 self-sig over (PeerId|Platform|Token|UpdatedAt)\n StampId text not null unique, -- single-use authorization nonce, bound into the add/remove digests;\n -- rotates on (re)insert. A cleared token's stamp is retired permanently\n -- into Revocation (NotRevoked below), so the approval that published a\n -- token cannot re-seat it after the owner cleared it (logout).\n -- A removed row's StampId is retired into Revocation, and this refuses any insert\n -- naming a retired stamp: the approval that seated this row can never re-seat it after\n -- the clear. `unique` alone did not do this \u2014 it only holds over LIVE rows, so a delete\n -- freed the stamp and the original never-expiring signature verified again. A legitimate\n -- re-register mints a FRESH StampId and a fresh signature, so it is unaffected. This\n -- matters more here than the stored-approval case (CadrePeer.VouchSig): a resurrected\n -- push token has NO freshness ceiling to retire it \u2014 cadre-node.ts:resolveDeviceToken\n -- defaults maxAgeMs to infinity by design \u2014 so retirement is the only thing that sticks.\n constraint NotRevoked check on insert (\n not exists (select 1 from Revocation R where R.TableName = 'DeviceToken' and R.StampId = new.StampId)\n ),\n -- Retirement is MANDATORY: a delete must carry the matching Revocation row in the same\n -- transaction, or the stamp would free up again. Deferred (subquery), so the sibling\n -- insert is visible at commit regardless of statement order. The tombstone must also\n -- name the removed ROW, not just its stamp \u2014 see Revocation.RowKey.\n constraint RevocationRecorded check on delete (\n exists (select 1 from Revocation R where R.TableName = 'DeviceToken' and R.StampId = old.StampId and R.RowKey = old.PeerId)\n ),\n constraint AuthorizedInsert check on insert (\n -- Authorized by an owner key (membership vouch), exactly like CadrePeer.\n -- The digest binds the WHOLE row behind the domain/action tags \u2014 every column,\n -- with the nullable UpdatedAt/Sig signing as '' when absent (the shape\n -- FormationInvite and Strand already use) \u2014 so a replayed approval can only ever\n -- reproduce the row it approved, never one carrying attacker-chosen\n -- Platform/Token/UpdatedAt; NotRevoked above then refuses even that exact row\n -- once it has been cleared. The DISTINCT 'remove'-tagged digest below keeps a\n -- captured insert approval from doubling as a delete (and vice versa).\n -- Mirrors cadre-core peer-authorization.ts:deviceTokenAddDigest.\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(\n digest(\n 'CadreControl.DeviceToken', 'add',\n new.PeerId,\n new.Platform,\n new.Token,\n coalesce(cast(new.UpdatedAt as text), ''),\n coalesce(new.Sig, ''),\n new.StampId\n ),\n context.Signature, A.Key, 'ed25519'))\n ),\n constraint AuthorizedDelete check on delete (\n -- Bound to the STORED row's (PeerId, StampId) \u2014 cadre-core\n -- peer-authorization.ts:deviceTokenRemoveDigest \u2014 so the never-expiring insert\n -- approval can never be replayed as a clear, and a captured clear approval is\n -- dead once the stamp it names is retired.\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.DeviceToken', 'remove', old.PeerId, old.StampId), context.Signature, A.Key, 'ed25519'))\n\n -- or REAP: a COMMITTED tombstone already retires this exact row incarnation, so a node\n -- that was offline at removal time may delete the stale row locally with no owner key.\n -- Why committed.* and why the stamp must be bound: stated in full on\n -- CadrePeer.AuthorizedDelete.\n or exists (select 1 from committed.Revocation R where R.TableName = 'DeviceToken' and R.RowKey = old.PeerId and R.StampId = old.StampId)\n ),\n constraint AuthorizedUpdate check on update (\n -- Peer self-updates its own token, signing with its OWN ed25519 key (the key\n -- behind PeerId). PeerId and StampId are immutable, UpdatedAt must strictly\n -- increase (replay guard), and Sig is verified against the stored\n -- CadrePeer.PublicKey over the signed payload (cadre-core\n -- device-token.ts:deviceTokenSignedPayload). Platform and Token may change on\n -- self-update (platform switch / reinstall / rotation).\n -- StampId is immutable for the reason CadrePeer spells out: an update that\n -- rotated it would leave the OLD stamp live-free and untombstoned, so retiring a\n -- stamp stays delete + Revocation row, never an update.\n -- This is the ONLY branch: there is deliberately NO owner re-touch. The branch\n -- that used to sit beside it verified an owner signature over the peer id alone\n -- and sat OUTSIDE the monotonicity requirement, so one captured owner approval\n -- rewrote Platform/Token and rolled UpdatedAt BACKWARDS \u2014 and seating a\n -- far-future UpdatedAt wedged the peer's own self-updates permanently. No writer\n -- used it. An owner that must correct a row deletes it (retiring the stamp) and\n -- inserts a fresh one, the same path it already takes for CadrePeer.\n new.PeerId = old.PeerId\n and new.StampId = old.StampId\n and new.UpdatedAt > coalesce(old.UpdatedAt, 0)\n and exists (select 1 from CadrePeer P where P.PeerId = new.PeerId and verify(\n digest('CadreControl.DeviceToken', 'publish', new.PeerId, new.Platform, new.Token, cast(new.UpdatedAt as text)),\n new.Sig, P.PublicKey, 'ed25519'))\n )\n ) with context (OwnerKey text null, Signature text);\n\n -- An open invitation to form a strand with this party\n table FormationInvite (\n Token text primary key, -- Just a random string\n sAppId text, -- The app for the strand that will be formed\n ExpiresAt datetime null,\n TotalUses int null check (TotalUses >= 0),\n ValidationUrl text null, -- Web hook - send disclosure, IP address...\n StrandId text null, -- Host strand this invite binds to (provision-then-record). Non-null => the responder records consent against this pre-existing strand; null => unbound invite: the responder provisions a fresh open strand and atomically records its one consent row.\n StampId text not null unique, -- single-use authorization nonce (anti-replay)\n constraint AuthorizedInsert check on insert (\n -- Authorized by an owner signing over THIS row\n -- (Token, sAppId, ExpiresAt, TotalUses, ValidationUrl, StrandId, StampId); single-use via unique StampId.\n -- Nullable bound fields (ExpiresAt/TotalUses/ValidationUrl/StrandId) sign as '' when absent.\n -- The 'remove'-tagged AuthorizedDelete digest below is DISTINCT, so a captured\n -- insert approval can never be replayed to revoke-then-reissue an invite (or vice versa).\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(\n digest(\n 'CadreControl.FormationInvite', 'add',\n new.Token,\n new.sAppId,\n coalesce(cast(new.ExpiresAt as text), ''),\n coalesce(cast(new.TotalUses as text), ''),\n coalesce(new.ValidationUrl, ''),\n coalesce(new.StrandId, ''),\n new.StampId\n ),\n context.Signature, A.Key, 'ed25519'))\n ),\n constraint AuthorizedDelete check on delete (\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(\n digest(\n 'CadreControl.FormationInvite', 'remove',\n old.Token,\n old.sAppId,\n coalesce(cast(old.ExpiresAt as text), ''),\n coalesce(cast(old.TotalUses as text), ''),\n coalesce(old.ValidationUrl, ''),\n coalesce(old.StrandId, ''),\n old.StampId\n ),\n context.Signature, A.Key, 'ed25519'))\n ),\n -- Invites are insert/delete only: forbid in-place mutation so the row-bound\n -- AuthorizedInsert signature cannot be sidestepped by updating consent\n -- parameters (TotalUses/ExpiresAt/...) after a legitimate insert. A bare check\n -- defaults to insert+update; the checks on insert / on delete above exclude update,\n -- so this guard is required. Mirrors FormationUsage.InsertOnly.\n constraint Immutable check on update (false)\n ) with context (OwnerKey text, Signature text);\n\n table FormationUsage (\n Token text not null, -- the FormationInvite this acceptance redeems. Stated explicitly because\n -- Token is no longer a primary-key prefix; Authorized below would refuse a\n -- null anyway (null = null is never true, so its FormationInvite\n -- exists-clause cannot match), but the column carries the invariant rather\n -- than leaving it to a CHECK.\n UsageStampId text not null, -- single-use nonce for THIS redemption, and this table's PRIMARY KEY.\n -- The JOINING peer mints it and sends it in its contact message, having\n -- signed it into its own 'consent' digest (PeerConsented below); the\n -- responder inserts that same value and asks the approver about it, so it\n -- is bound into the 'vouch' digest below too and one sign-off is spendable\n -- exactly once. Neither side can swap it: a substituted nonce fails the\n -- joiner's consent signature.\n -- As the row key, a verbatim replay of an approval collides on the\n -- primary key locally instead of on a column `unique`. Unlike every other\n -- StampId in this schema, this table is append-only (InsertOnly below),\n -- so the nonce is never freed by a delete: the key alone makes it\n -- permanent and there is deliberately NO NotRevoked / RevocationRecorded\n -- pair here \u2014 do not go looking for the missing one.\n -- NOTE: the key is evaluated against LOCALLY VISIBLE rows, so two nodes\n -- that have not yet converged could each admit the same nonce and both\n -- rows survive the merge. Same class as the NotRevoked convergence notes\n -- on OwnerKey / Strand / ValidationKey; the digest binding still holds on\n -- both nodes, so the outcome is a duplicated audit row, never a join\n -- nobody approved.\n PeerKey text not null, -- the joining peer's own ed25519 public key (base64url, 32 bytes), bound\n -- into BOTH the approver's 'vouch' digest and the joiner's 'consent'\n -- digest below, so an approval cannot be re-filed under a different\n -- joiner's name and the named joiner provably agreed (PeerConsented).\n -- The key IS the joiner's identity \u2014 its libp2p peer id is derivable\n -- (identity multihash of these bytes), never stored here.\n PeerSig text not null, -- the joining peer's signature over the 'consent' digest \u2014 see\n -- PeerConsented below for what it proves and why it is stored on the row.\n Disclosure text,\n StrandId text,\n StrandStampId text not null, -- the Strand.StampId this consent record authorizes. Consent is\n -- bound to ONE strand ROW, not to a strand id forever \u2014 see\n -- Strand.AuthorizedInsert's consent branch for why. NOT unique:\n -- in the bound (provision-then-record) path several invitees\n -- each write a usage row against the SAME host strand, so many\n -- usage rows legitimately share one stamp.\n primary key (UsageStampId),\n constraint InsertOnly check on update, delete (false),\n constraint Authorized check on insert (\n -- Satisfies an invitation\n exists (\n select 1 from FormationInvite FI\n where FI.Token = new.Token\n -- The use cap is COUNTED against the pre-transaction snapshot, never\n -- sequenced. This CHECK auto-defers to commit (it has a subquery), by\n -- which point the in-flight row is live; committed.* is what excludes\n -- it, so a sequentially exhausted invite \u2014 every seat already committed\n -- on this node \u2014 is still refused here. What is deliberately NOT\n -- refused: concurrent redeemers on separate nodes (or nodes that have\n -- not yet converged) each count the same committed snapshot and both\n -- land, over-admitting by at most the number of concurrent redeemers.\n -- Both rows survive in this append-only record, so the overage is\n -- auditable, and removal is owner-gated (member removal + Revocation).\n -- Same class as the convergence note on UsageStampId above.\n -- One rule for FUTURE writers: two FormationUsage rows for one token\n -- inserted in ONE transaction each read the same committed count, so\n -- they can jointly exceed the cap. No writer in this repo does that; it\n -- is a constraint on new writers, not a case to engineer for.\n -- Do not \"fix\" this into a per-token sequence number to restore a\n -- strict cap \u2014 that trade was weighed and rejected (2026-08-04): a\n -- fought-over sequence key turns a concurrent redemption into a silent,\n -- unrecoverable loss of a consented join, which is strictly worse than\n -- a visible, reversible over-admission.\n and (FI.TotalUses is null or FI.TotalUses > (select count(1) from committed.FormationUsage U where U.Token = new.Token))\n and (FI.ExpiresAt is null or FI.ExpiresAt > context.Now)\n -- An invite carrying a ValidationUrl demands a sign-off from a key the party\n -- ENROLLED in ValidationKey. The signature is verified against the STORED VK.Key,\n -- NOT against context.ValidationKey \u2014 that distinction is the whole point:\n -- context.ValidationKey is a plain insert parameter, so verifying against it asked\n -- only \"did the redeemer sign its own disclosure with SOME key it holds?\", which any\n -- redeemer answers by minting a throwaway keypair. context.ValidationKey survives\n -- purely to SELECT which enrolled row is being claimed; naming an enrolled key while\n -- signing with a different one fails the verify against VK.Key.\n --\n -- Deliberate: CHECKs run on write only, so removing a validation key later does NOT\n -- re-examine the FormationUsage rows it already approved. The sign-off was valid when\n -- given and the strand it authorized stays formed; removal narrows who may approve\n -- FUTURE redemptions, it is not a retroactive revocation of past ones.\n --\n -- What ONE sign-off buys: exactly ONE row. The digest covers\n -- (Token, UsageStampId, StrandId, PeerKey, Disclosure), so an approval is NOT\n -- transferable across invitations, redemptions, networks, joiners, or disclosure\n -- text. Replay is closed twice over, by two independent mechanisms: presenting an\n -- approval VERBATIM repeats its UsageStampId and is refused by this table's\n -- primary key; presenting it under any OTHER redemption changes a signed field\n -- and fails this verify.\n -- Every signed field is supplied by the redeeming side \u2014 nothing derived from\n -- the table's current state is bound \u2014 so no concurrent write can invalidate an\n -- approval between the sign-off and the row landing.\n -- Why StrandStampId is deliberately NOT bound: it names the strand ROW\n -- incarnation, which the unbound path (redeemInvitation) mints inside its own\n -- transaction, and it adds nothing on top of a strictly single-use approval \u2014\n -- StrandId already pins WHICH network the approver approved joining.\n and (FI.ValidationUrl is null or exists (\n select 1 from ValidationKey VK\n where VK.Key = context.ValidationKey\n and verify(digest('CadreControl.FormationUsage', 'vouch', new.Token, new.UsageStampId, new.StrandId, new.PeerKey, new.Disclosure), context.ValidationSignature, VK.Key, 'ed25519')))\n -- A bound invite (non-null StrandId) may only ever name its own host strand:\n -- without this, any holder of a bound token could record consent against an\n -- arbitrary strand id \u2014 annotating an unrelated strand, or (before\n -- Strand.AuthorizedInsert's consent branch was narrowed to unbound invites)\n -- consent-seating that id outright.\n -- NOTE: an UNBOUND invite is deliberately left free to name any strand, so a\n -- holder can spend a use appending a consent row to an unrelated existing\n -- strand. Harmless today (the row grants nothing, it only burns a use and\n -- forecloses that id's consent-seating, which is the safe direction); if\n -- unlimited-TotalUses invites ever become common, this is an append-only\n -- growth surface worth bounding.\n and (FI.StrandId is null or FI.StrandId = new.StrandId)\n )\n ),\n -- Matched on the (id, stamp) PAIR, the same key Strand.AuthorizedInsert's consent branch\n -- reads back: a usage row may only ever name a strand ROW that exists, so a consent record\n -- can never be filed against a stamp of the writer's choosing and held in reserve to\n -- re-seat the id after a removal.\n constraint StrandExists check (exists (select 1 from Strand S where S.Id = new.StrandId and S.StampId = new.StrandStampId)),\n -- The JOINING peer proves it consented to this redemption: PeerKey is its own ed25519\n -- public key and PeerSig is its signature over the 'consent'-tagged digest below.\n -- Unlike the approver's sign-off (context.ValidationSignature, checked against a STORED\n -- ValidationKey row), the identity here IS the key, so there is no enrolled row to look\n -- up and nothing for a writer to substitute: a forged joiner would need that joiner's\n -- private key. Stored rather than passed in context so any later reader can re-check it\n -- (verifyFormationConsent); the 'consent' action tag keeps this replicated signature\n -- useless against every other rule in this schema (notably the approver's 'vouch'\n -- digest over the same table).\n -- NOTE: StrandId is deliberately NOT in this digest \u2014 the joiner cannot know it when it\n -- signs (a bound invite's host strand arrives only in the result frame; an unbound\n -- strand is responder-minted). The responder cannot substitute a strand anyway: bound\n -- invites are pinned by Authorized's FI.StrandId check, unbound invites mint fresh.\n constraint PeerConsented check on insert (\n verify(digest('CadreControl.FormationUsage', 'consent',\n new.Token, new.UsageStampId, new.PeerKey, new.Disclosure),\n new.PeerSig, new.PeerKey, 'ed25519')\n ),\n -- Context here is only what the approver-side rules read: Now for expiry, and the\n -- ValidationKey/ValidationSignature pair for the 'vouch' check in Authorized. The joiner's\n -- signature is NOT context \u2014 it lives on the row (PeerSig, verified by PeerConsented above).\n ) with context (Now datetime, ValidationKey text null, ValidationSignature text null);\n\n -- Token is no longer a primary-key prefix (the key is the redemption nonce), so the\n -- per-token filters \u2014 the cap count in Authorized above, and cadre-core's\n -- countFormationUsage / isTokenUsed / hasOutstandingFormationInvite \u2014 are served by this\n -- index rather than by a full scan of a table that is append-only and grows for the life\n -- of the party.\n --\n -- The cap count is only ever as correct as this index's convergence across machines. That\n -- convergence failed once: from 2026-08-04 to 2026-08-25 a descent on a second machine\n -- returned only the rows THAT machine wrote, so the index was removed and the reads went\n -- back to the scan. The engine defect was fixed upstream and re-measured here on\n -- 2026-09-17, so the index is declared again. Its guard is the integration-tests scenario\n -- `strand-formation-concurrent-redemption`, which asserts BOTH machines' views of a raced\n -- redemption and therefore goes red if that convergence regresses.\n --\n -- NOTE: the write side has its own exposure. Every FormationUsage insert now maintains this\n -- sub-collection as well as the table, and an intermittent engine failure once hit exactly that\n -- step on other tables (a table's rows committed while its index did not; closed 2026-09-17 with\n -- the upstream sync fixes, `tickets/complete/strand-unique-index-sync-stale-revision`). Nothing\n -- has been observed here, and redemptions are rare writes; but if joins start failing\n -- intermittently with an index-sync error naming FormationUsage, this declaration is the first\n -- thing to suspect.\n index FormationUsageByToken on FormationUsage (Token);\n\n -- Append-only retirement record for the one-off StampId nonces of removed OwnerKey /\n -- CadrePeer / ValidationKey / Strand rows. Without it a removal was undoable: the add\n -- approval is a signature over\n -- (row key, stamp) that never expires, and deleting the row freed the stamp, so anyone who\n -- kept a copy of the approval could resurrect the row.\n -- Each tombstone also records WHICH row was retired (RowKey below): the consent branch of\n -- Strand.AuthorizedInsert reads it to refuse consent-seating any strand id that has ever\n -- been removed, whichever way it was seated.\n -- NOTE: the guarded tables' NotRevoked CHECK runs against locally visible rows, so a node\n -- that has not yet converged on a Revocation row can still accept the replayed add, and the\n -- resurrected row coexists with the tombstone after merge \u2014 same class as the MinOneOwner\n -- note on OwnerKey. The read-side mitigation is ControlDatabase.queryCadrePeers, which\n -- drops any CadrePeer row whose StampId appears here; every membership reader inherits it.\n -- NOTE: append-only, so this table only ever grows. Every append is owner-signed\n -- (Authorized below), so the growth surface is the owner keys, not every writer that can\n -- reach the control database. Cadres are a handful of peers and owner rotation is rare, so\n -- unbounded growth is fine today; revisit if either changes.\n -- A tombstone committed while the node was alone is local-only (never broadcast); the\n -- ReissuedAt counter below exists so an owner can re-write \u2014 and therefore re-broadcast \u2014\n -- such a tombstone once peers are reachable, without changing what it means.\n -- One row retires nothing: the singleton ledger marker ('Revocation', 'ledger', 'opened'),\n -- filed once by an owner's connected reconcile pass (ControlDatabase.openRevocationLedger).\n -- It exists only so this table is never a never-written block. The storage layer consults\n -- a block's cohort on EVERY read of a block it does not hold, and every membership lookup\n -- and every guarded insert (NotRevoked) reads this table; once any row exists the block is\n -- held and re-checked on the storage layer's normal read-repair schedule, like every other\n -- populated table. It cannot read as a retirement: every reader of this table filters on\n -- its own guarded TableName, 'Revocation' is not one, and ControlDatabase.queryRevocations\n -- skips the marker, so nothing reaps or re-issues it.\n table Revocation (\n TableName text, -- 'OwnerKey' | 'CadrePeer' | 'ValidationKey' | 'Strand' | 'StrandPartyKey' | 'DeviceToken',\n -- or 'Revocation' for the ledger marker only (all confined by RowIsGone below)\n RowKey text not null, -- primary key of the removed row: OwnerKey.Key / ValidationKey.Key /\n -- CadrePeer.PeerId / DeviceToken.PeerId / Strand.Id / StrandPartyKey.Id\n -- Every guarded table's RevocationRecorded CHECK requires the\n -- accompanying tombstone to carry the removed row's key here, so\n -- a REMOVAL cannot file a misnamed tombstone. A tombstone with no\n -- accompanying delete is not covered by that (see Authorized).\n StampId text, -- the retired nonce\n -- Bumped by an owner-signed re-issue so a tombstone written while the node was alone\n -- (committed local-only, never broadcast) can be re-written and therefore re-broadcast\n -- on cohort growth. Carries NO semantics: nothing reads it, and retirement is decided\n -- by the row's existence, not by this value.\n ReissuedAt integer not null default 0,\n -- Keyed on the stamp, not the RowKey: stamps are unique per row incarnation, and one\n -- name may legitimately carry several tombstones over its life (seat -> delete ->\n -- owner re-seat -> delete).\n primary key (TableName, StampId),\n -- Retirement is permanent: a tombstone may never be withdrawn.\n constraint NoDelete check on delete (false),\n -- Pinned at 0 on insert so an owner cannot seat a tombstone at a saturated counter and\n -- thereby freeze its own later re-issues (ReissueOnly below). Deliberately NOT folded\n -- into the Authorized digest: the value is fixed by this rule, so signing over it would\n -- only widen the signed surface for no gain, and would invalidate every existing\n -- insert-side digest.\n constraint FreshTombstone check on insert (new.ReissuedAt = 0),\n -- A re-issue may move NOTHING but the counter, and only upward. Without the identity\n -- clause an \"update\" would be a way to re-point a tombstone at a different row,\n -- restoring exactly the replay this table exists to stop.\n constraint ReissueOnly check on update (\n new.TableName = old.TableName and new.RowKey = old.RowKey\n and new.StampId = old.StampId and new.ReissuedAt > old.ReissuedAt\n ),\n -- A stamp may only be retired once its row is actually gone. Deferred (subquery), so a\n -- delete in the same transaction has already landed. Retiring a stamp that never\n -- existed is permitted and harmless: a stamp carries 128 bits of CSPRNG output\n -- (control-database.ts:generateStampId \u2014 16 bytes of sha256(PeerId) followed by 16\n -- random bytes), so a future legitimate one cannot be guessed and pre-planted.\n -- Deliberately keyed on the STAMP only, not RowKey: checking \"no live row named\n -- new.RowKey\" breaks under out-of-order convergence \u2014 a peer removed (tombstone names\n -- it, stamp1) then re-admitted (stamp2) would leave a node that converges on the\n -- re-add FIRST rejecting the stamp1 tombstone forever, never learning that stamp is\n -- retired. The stamp-only form passes there (stamp1 is not live).\n -- The last branch admits the ledger marker (see the table comment) and nothing else under\n -- TableName 'Revocation': the whole triple is pinned, so with the primary key\n -- (TableName, StampId) it is a singleton and the append-only growth surface is unchanged.\n -- 'opened' cannot collide with a real stamp (43 base64url characters, generateStampId),\n -- and the primary key includes TableName anyway.\n constraint RowIsGone check on insert (\n (new.TableName = 'OwnerKey' and not exists (select 1 from OwnerKey K where K.StampId = new.StampId))\n or (new.TableName = 'CadrePeer' and not exists (select 1 from CadrePeer P where P.StampId = new.StampId))\n or (new.TableName = 'ValidationKey' and not exists (select 1 from ValidationKey V where V.StampId = new.StampId))\n or (new.TableName = 'Strand' and not exists (select 1 from Strand S where S.StampId = new.StampId))\n or (new.TableName = 'StrandPartyKey' and not exists (select 1 from StrandPartyKey K where K.StampId = new.StampId))\n or (new.TableName = 'DeviceToken' and not exists (select 1 from DeviceToken D where D.StampId = new.StampId))\n or (new.TableName = 'Revocation' and new.RowKey = 'ledger' and new.StampId = 'opened')\n ),\n -- Appending a tombstone is an OWNER action, like every other write in this schema.\n -- Ungated, any writer that could reach the control database could retire a stamp:\n -- filing one against a CadrePeer row not visible locally (RowIsGone reads LOCALLY\n -- VISIBLE rows \u2014 see the convergence note above) evicted that peer party-wide AND\n -- permanently blocked the owner's own later re-admission of it (NotRevoked), and\n -- filing arbitrary stamps flooded a table whose rows never go away.\n -- The digest binds the WHOLE row (TableName, RowKey, StampId); the 'CadreControl.Revocation'\n -- domain tag keeps it disjoint from every other rule \u2014 including the\n -- 'CadreControl.CadrePeer' 'remove' digest the same owner signs in the SAME\n -- transaction for the delete this tombstone accompanies.\n -- RowKey is not cross-checked HERE against the retired row: positively binding it (e.g.\n -- requiring a committed.Strand row carrying the pair) would reject a tombstone re-issued\n -- in a LATER transaction \u2014 which the delete-while-alone durability path\n -- (docs/architecture.md) plans to do \u2014 and reject it outright on a node that never\n -- converged on the removed row. The binding lives on the other side instead: each\n -- guarded table's RevocationRecorded requires the tombstone accompanying a DELETE to\n -- name that row's key, which the re-issue path never trips (it files no delete).\n -- Residual: a STANDALONE tombstone \u2014 owner-signed, naming a stamp no live row holds \u2014\n -- is still accepted, so an owner can name an id that never existed and thereby\n -- permanently foreclose CONSENT-seating of that id (Strand.AuthorizedInsert).\n -- Owner-only, the owner already controls invite issuance, and unbound ids are 128\n -- random bytes minted at redemption \u2014 no escalation (same reasoning as the pre-plant\n -- note on RowIsGone).\n -- Reads LIVE OwnerKey (like ValidationKey / Strand / CadrePeer / DeviceToken), not\n -- committed.OwnerKey. The one difference that makes: a founding transaction on an\n -- owner-less database could seat an owner key and file a tombstone in one go. An\n -- owner-less control database is already a total loss, and a second transaction\n -- achieves the same thing under committed.*, so consistency with the siblings is\n -- worth more than the distinction \u2014 do not \"tighten\" this without a reason other\n -- than that one.\n -- RowIsGone and NoDelete are unchanged: they guard an owner retiring a stamp early\n -- or withdrawing one later, which authorization does not cover.\n -- The ledger marker is signed under this same rule, over\n -- digest('CadreControl.Revocation', 'remove', 'Revocation', 'ledger', 'opened'). The\n -- 'remove' tag on a row that retires nothing is deliberate: reusing the one append rule\n -- keeps every append owner-signed without adding an unsigned or differently tagged\n -- branch, and a captured marker signature can only re-file the identical row, whose\n -- primary key is already taken.\n constraint Authorized check on insert (\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.Revocation', 'remove', new.TableName, new.RowKey, new.StampId), context.Signature, A.Key, 'ed25519'))\n ),\n -- A re-issue is an OWNER action, like the original append. Distinct 'reissue' action\n -- tag, so an append approval can never be replayed as a re-issue and vice versa. The\n -- digest adds ReissuedAt so a captured re-issue signature cannot bump the counter to\n -- any other value. Reads LIVE OwnerKey, matching Authorized above.\n constraint AuthorizedReissue check on update (\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey\n and verify(digest('CadreControl.Revocation', 'reissue',\n new.TableName, new.RowKey, new.StampId, cast(new.ReissuedAt as text)),\n context.Signature, A.Key, 'ed25519'))\n )\n ) with context (OwnerKey text, Signature text);\n}\n\napply schema CadreControl;";
12
+ export declare const CONTROL_SCHEMA = "-- This manages a Sereus party's cadre, or set of nodes, and their participation in strands (networks)\ndeclare schema CadreControl {\n -- A key that can authorize various control changes\n table OwnerKey (\n Key text primary key,\n StampId text not null unique, -- per-row authorization nonce, bound into the signed digests below.\n -- `unique` holds over LIVE rows only; a removed row's stamp is retired\n -- permanently into Revocation (NotRevoked below), so the never-expiring\n -- enrollment signature cannot resurrect a removed owner.\n -- A removed row's StampId is retired into Revocation, and this refuses any insert\n -- naming a retired stamp: the approval that seated this row can never re-seat it after\n -- removal. `unique` alone did not do this \u2014 it only holds over LIVE rows, so a delete\n -- freed the stamp and the original never-expiring signature verified again. A\n -- legitimate re-add mints a FRESH StampId and a fresh signature, so it is unaffected.\n constraint NotRevoked check on insert (\n not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = new.StampId)\n ),\n -- Retirement is MANDATORY: a delete must carry the matching Revocation row in the same\n -- transaction, or the stamp would free up again. Deferred (subquery), so the sibling\n -- insert is visible at commit regardless of statement order. The tombstone must also\n -- name the removed ROW, not just its stamp \u2014 see Revocation.RowKey.\n constraint RevocationRecorded check on delete (\n exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = old.StampId and R.RowKey = old.Key)\n ),\n -- A party must never lose its last owner key: every other CadreControl table's\n -- CHECK requires an OwnerKey row, so an owner-less control database can never\n -- authorize anything again \u2014 emptying this table is a permanent denial of the\n -- party's control plane. Deferred (subquery), so the count is the POST-delete count.\n -- NOTE: this is a per-transaction check against locally visible rows. Two\n -- partitioned nodes that concurrently remove different owners can each see a\n -- survivor and still converge to zero; if partitioned rotation ever becomes a real\n -- workflow, the floor needs a cross-node guard, not a local count.\n constraint MinOneOwner check on delete (\n (select count(1) from OwnerKey) >= 1\n ),\n -- Enrollment is insert + delete only; rotation is add-then-remove. No writer\n -- updates an OwnerKey row, and a self-rotation branch would double as a sole-owner\n -- takeover: a deferred post-image count is also true of an update that re-points\n -- the only row at an attacker key. Mirrors Strand.Manager.NoUpdate.\n constraint NoUpdate check on update (false),\n -- NOTE: the domain tag scopes an approval to a table and an action, not to a PARTY. Two\n -- parties that share an owner key would accept each other's approvals. Fine today (each\n -- party has its own owner key); if shared-owner multi-party ever ships, bind a party\n -- identity row into these digests.\n constraint Authorized check on insert, delete (\n -- Every authorizer is read from the PRE-transaction snapshot (committed.*):\n -- this CHECK auto-defers to commit (it has a subquery), by which point the row\n -- being inserted \u2014 and any sibling inserted alongside it \u2014 is live, so a plain\n -- from-OwnerKey would let a row authorize itself, or two strangers seat each\n -- other. committed.* excludes both, stating the rule directly: the authorizer\n -- must have existed BEFORE this transaction.\n\n -- Every signed digest below (and in every other CadreControl table) leads with two\n -- fixed literals \u2014 a 'CadreControl.<Table>' domain tag and an 'add'/'remove'/\n -- 'vouch'/'publish' action tag (cadre-core control-authorization.ts) \u2014 so an\n -- approval verifies ONLY against the one rule it was minted for. Without them,\n -- e.g. a ValidationKey enrollment approval covered the identical bytes as an\n -- OwnerKey enrollment: a narrow grant that doubled as full ownership.\n\n -- Bootstrap: the FOUNDING transaction \u2014 one whose pre-transaction owner set is\n -- empty \u2014 needs no authorization, and every row it inserts rides this branch\n -- (whoever writes it already owns the party outright, so a co-founder row grants\n -- nothing a single row would not). Gated on the PRE-transaction count, so a\n -- same-transaction swap of the sole owner (delete the founder, insert the\n -- attacker \u2014 post-image count still 1) cannot ride it.\n (old.Key is null and (select count(1) from committed.OwnerKey) = 0)\n\n -- or a pre-existing owner authorizes by signing over THIS row (Key, StampId)\n or (old.Key is null and exists (select 1 from committed.OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.OwnerKey', 'add', new.Key, new.StampId), context.Signature, A.Key, 'ed25519')))\n\n -- or a removal authorized by ANOTHER pre-existing owner over the DISTINCT\n -- 'remove'-tagged digest bound to the stored row's StampId, so an enrollment\n -- signature can never be replayed as a removal (cf. CadrePeer.AuthorizedDelete).\n -- A.Key <> old.Key: an owner cannot sign its own removal (no self-resignation).\n or (new.Key is null and exists (select 1 from committed.OwnerKey A where A.Key = context.OwnerKey and A.Key <> old.Key and verify(digest('CadreControl.OwnerKey', 'remove', old.Key, old.StampId), context.Signature, A.Key, 'ed25519')))\n )\n ) with context (OwnerKey text null, Signature text null);\n\n -- A key that can validate a strand formation disclosure\n table ValidationKey (\n Key text primary key,\n StampId text not null unique, -- single-use authorization nonce (anti-replay).\n -- `unique` holds over LIVE rows only; a removed row's stamp is retired\n -- permanently into Revocation (NotRevoked below), so the never-expiring\n -- enrollment signature cannot resurrect a removed key.\n -- A removed row's StampId is retired into Revocation, and this refuses any insert naming\n -- a retired stamp: the approval that seated this row can never re-seat it after removal.\n -- Same rationale as OwnerKey.NotRevoked, stated in full there.\n -- NOTE: this table gained a consumer \u2014 FormationUsage.Authorized reads it to gate redemption of\n -- a ValidationUrl invite \u2014 so the convergence gap noted on Strand.StampId now has teeth here: on\n -- a node that has not yet seen the tombstone, a replayed enrollment re-seats the key and it can\n -- approve redemptions there until the Revocation row arrives. Still no per-request READ surface to\n -- filter (the gate is a write-time CHECK), so there is nothing to add today; if one appears, filter\n -- retired stamps there.\n constraint NotRevoked check on insert (\n not exists (select 1 from Revocation R where R.TableName = 'ValidationKey' and R.StampId = new.StampId)\n ),\n -- Retirement is MANDATORY: a delete must carry the matching Revocation row in the same\n -- transaction, or the stamp would free up again. Deferred (subquery), so the sibling\n -- insert is visible at commit regardless of statement order. The tombstone must also\n -- name the removed ROW, not just its stamp \u2014 see Revocation.RowKey.\n constraint RevocationRecorded check on delete (\n exists (select 1 from Revocation R where R.TableName = 'ValidationKey' and R.StampId = old.StampId and R.RowKey = old.Key)\n ),\n -- Enrollment is insert + delete only; rotation is add-then-remove. No writer in the repo\n -- updates a ValidationKey row. Required because the AuthorizedInsert / AuthorizedDelete\n -- pair below covers neither update \u2014 and a bare `check`, which is what this rule used to\n -- be, covers insert+update but NOT delete. Mirrors OwnerKey.NoUpdate.\n constraint NoUpdate check on update (false),\n constraint AuthorizedInsert check on insert (\n -- Owners authorize by signing over THIS row (Key, StampId); single-use via unique StampId\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.ValidationKey', 'add', new.Key, new.StampId), context.Signature, A.Key, 'ed25519'))\n ),\n constraint AuthorizedDelete check on delete (\n -- Delete is authorized by a signature over the DISTINCT 'remove'-tagged digest bound to\n -- the STORED row (Key, StampId), so an enrollment approval \u2014 which never expires \u2014 can\n -- never be replayed as a removal. Same shape as CadrePeer.AuthorizedDelete.\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.ValidationKey', 'remove', old.Key, old.StampId), context.Signature, A.Key, 'ed25519'))\n\n -- or REAP: a COMMITTED tombstone already retires this exact row incarnation, so a node\n -- that was offline at removal time may delete the stale row locally with no owner key.\n -- Why committed.* and why the stamp must be bound: stated in full on\n -- CadrePeer.AuthorizedDelete.\n or exists (select 1 from committed.Revocation R where R.TableName = 'ValidationKey' and R.RowKey = old.Key and R.StampId = old.StampId)\n )\n ) with context (OwnerKey text, Signature text);\n\n -- A network of members sharing an sApp database, each contributing peer nodes (their cadre) to the overall cohort\n -- Cadre peers should participate in each of these strands\n table Strand (\n Id text primary key, -- UUID\n MemberPrivateKey text null unique, -- Our private key as a member of this strand\n Type text, -- Types: 'o' = Open, 'c' = Closed -- Open can still control writes in the sApp, but only Closed controls reads\n FounderOwnerKey text null, -- ed25519 (base64url) owner key of the MACHINE that published this row\n -- (== insert context.OwnerKey; in the reference model each machine's\n -- owner key is the key behind its PeerId, so this names the founding\n -- machine \u2014 the one machine that runs the strand's one-time founder\n -- bootstrap). cadre-core derives \"am I the founder?\" at launch by\n -- comparing it to the node's own owner key (cadre-node.ts\n -- launchStrand). Null on a consent-seated strand \u2014 the consent branch\n -- of AuthorizedInsert carries no signature, so there is no\n -- trustworthy signer to record (see the NOTE on that branch below).\n -- Provenance, not content: cadre-node.ts strandRowMismatches\n -- deliberately excludes it from the identical-content comparison.\n StampId text not null unique, -- single-use authorization nonce (anti-replay).\n -- `unique` holds over LIVE rows only; a removed row's stamp is retired\n -- permanently into Revocation (NotRevoked below).\n -- NOTE: NotRevoked is a per-transaction check against LOCALLY VISIBLE rows, so a node that\n -- has not yet converged on the Revocation row can still accept a replayed add and end up\n -- holding the resurrected strand alongside its tombstone. CadrePeer has a read-side\n -- mitigation for this class (ControlDatabase.queryCadrePeers drops rows whose stamp is\n -- retired, so every membership reader inherits it); Strand and ValidationKey deliberately\n -- do NOT, because neither has a\n -- per-request authorization surface today. If one ever gains one, filter it there.\n constraint NotRevoked check on insert (\n not exists (select 1 from Revocation R where R.TableName = 'Strand' and R.StampId = new.StampId)\n ),\n -- Retirement is MANDATORY: a delete must carry the matching Revocation row in the same\n -- transaction, or the stamp would free up again. Deferred (subquery), so the sibling\n -- insert is visible at commit regardless of statement order. The tombstone must also\n -- name the removed ROW, not just its stamp \u2014 see Revocation.RowKey. That is what makes\n -- the consent branch of AuthorizedInsert below trustworthy: a removal cannot file a\n -- tombstone that omits or misnames the id it retires.\n constraint RevocationRecorded check on delete (\n exists (select 1 from Revocation R where R.TableName = 'Strand' and R.StampId = old.StampId and R.RowKey = old.Id)\n ),\n -- Strand rows are insert + delete only. Required: the consent branch of AuthorizedInsert\n -- below authorizes by the EXISTENCE of a FormationUsage row naming (new.Id, new.StampId)\n -- and carries no signature, so while this rule was a bare `check` (insert+update) it also\n -- said \"anyone may REWRITE any consent-formed strand, unsigned\" \u2014 flipping Type to 'o' and\n -- nulling MemberPrivateKey destroys the party's own membership key for that network in place.\n -- Mirrors OwnerKey.NoUpdate / FormationInvite.Immutable.\n constraint NoUpdate check on update (false),\n constraint AuthorizedInsert check on insert (\n -- Authorized by an owner signing over THIS row (Id, Type, MemberPrivateKey, StampId); single-use via unique StampId.\n -- FounderOwnerKey persists WHO published the row, so the founding machine can later\n -- recognise its own strand (founder derivation, cadre-node.ts launchStrand). The\n -- equality pins the stored column to the VERIFIED signer \u2014 same shape as\n -- CadrePeer.VouchOwner \u2014 so a writer cannot record a founder it is not. Deliberately\n -- NOT added to the signed digest: the equality already binds it to the signature's\n -- context.OwnerKey, and widening the digest would churn every existing\n -- insertStrand field-order contract for nothing.\n (exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.Strand', 'add', new.Id, new.Type, coalesce(new.MemberPrivateKey, ''), new.StampId), context.Signature, A.Key, 'ed25519'))\n and new.FounderOwnerKey = context.OwnerKey)\n\n -- or authorized WITHOUT a signature by a redemption record naming THIS EXACT ROW: a\n -- FormationUsage row carrying both this strand's Id and its one-off StampId\n -- (control-database.ts:redeemInvitation writes the pair in one transaction; both\n -- CHECKs defer, so each sees the other's row at commit).\n --\n -- Matching the STAMP, not the id alone, is what makes a removal stick. FormationUsage\n -- is append-only, so a redemption record outlives the strand it formed forever; keyed\n -- on the id alone it re-authorized ANY later insert of that id, so after a legitimate\n -- owner-signed, tombstoned removal any writer could re-seat the strand unsigned with a\n -- fresh StampId (sidestepping NotRevoked, which retires only the removed row's stamp)\n -- and an ATTACKER-CHOSEN MemberPrivateKey \u2014 the party's own secret for that network.\n -- Bound to the stamp, the removal retires that stamp into Revocation and NotRevoked\n -- closes this consent record's branch permanently.\n --\n -- Beyond the stamp match, the branch is deliberately NARROW \u2014 each clause closes one door:\n -- * Type = 'o' / MemberPrivateKey null \u2014 a consent-seated strand looks exactly like\n -- what the unbound redemption path writes (open, keyless). A closed strand carrying\n -- a caller-chosen member key (the party's own read-gating secret for that network)\n -- has no legitimate producer. MemberKeyClosedOnly already implies the second clause\n -- from the first today; both are stated so this rule does not silently depend on\n -- another constraint staying as it is.\n -- * the inner FI.StrandId is null \u2014 only an UNBOUND invite may seat a strand at all.\n -- A bound invite's host strand is owner-provisioned up front; letting the invite\n -- consent-seat that id would allow an open, keyless downgrade of the real (possibly\n -- closed, key-bearing) host row on a node where it has not converged yet. The bound\n -- path records usage only (resolveStrand reports an absent host as missing and the\n -- formation manager rejects cleanly).\n -- * the not-exists over OTHER stamps \u2014 a strand id may be consent-seated once, EVER.\n -- FormationUsage is append-only, so the first redemption's record survives a later\n -- owner-signed removal and permanently forecloses a second consent-seating of the\n -- id (a spare use of the same token minted a new stamp and rode this branch to\n -- re-seat the id with an attacker-chosen row). Re-joining a removed id is\n -- owner-gated: the owner re-seats it signed (fresh stamp, fresh signature) and\n -- issues a BOUND invite the returning party records consent against \u2014 the id is\n -- not blacklisted, only its unsigned re-seat is. This cannot be weaponised to\n -- pre-block a legitimate id: StrandExists refuses a usage row naming a strand that\n -- does not exist, so no usage row can be pre-planted for an unseated id \u2014 and ids\n -- are 128 random bytes anyway.\n -- * the not-exists over Revocation \u2014 a strand id may be consent-seated once EVER\n -- and never after ANY removal of that id, however it was seated. The usage-row\n -- rule above binds only ids that ever carried a consent record; an id seated\n -- purely owner-signed (insertStrand, no usage row) leaves nothing behind on\n -- removal, so its removal needs its own trace. Every removal files a Revocation\n -- row naming the removed row's key (RowKey), and this clause refuses any id\n -- that has ever been tombstoned. RevocationRecorded above makes that trace\n -- mandatory AND correctly named, so no removal can slip past this clause. The\n -- usage-row clause is arguably subsumed by this one (a usage row implies the\n -- strand row existed, and its removal must file a tombstone), but it reaches\n -- the same conclusion without depending on Revocation at all; both are stated,\n -- per the style note above. The owner-signed branch is deliberately unaffected,\n -- so re-join stays owner-gated exactly as described.\n -- What is NOT schema-verified is a STANDALONE tombstone (one with no\n -- accompanying delete \u2014 see Revocation.Authorized): an owner can file one\n -- naming an id that never existed and thereby permanently foreclose\n -- consent-seating of that id \u2014 owner-only, the owner already controls invite\n -- issuance, and unbound ids are 128 random bytes minted at redemption, so no\n -- escalation (same reasoning as the pre-plant note above).\n -- NOTE: like NotRevoked above, this is a write-time check against LOCALLY\n -- VISIBLE rows \u2014 a node that has not yet converged on the Revocation row still\n -- accepts the re-seat. Fails in the safe direction: the tombstone wins after\n -- merge for the STAMP, and the resurrected row coexists with it (same class as\n -- the StampId note above).\n or (\n new.Type = 'o'\n and new.MemberPrivateKey is null\n -- NOTE: a consent-seated strand records NO founder machine \u2014 this branch\n -- carries no signature, so there is no trustworthy signer to persist.\n -- Consequence: the restart-before-founding orphan shape (a relaunch cannot\n -- derive founder-ness from the row) persists for consent-formed strands\n -- only; the responder that provisions one must keep passing an explicit\n -- founder flag at launch. Revisit if consent-formed strands ever hit the\n -- empty-Header symptom in practice: FormationUsage names the redeeming\n -- peer (PeerKey), which is the candidate derivation source.\n and new.FounderOwnerKey is null\n and exists (\n select 1 from FormationUsage FU\n where FU.StrandId = new.Id\n and FU.StrandStampId = new.StampId\n and exists (select 1 from FormationInvite FI where FI.Token = FU.Token and FI.StrandId is null)\n )\n and not exists (\n select 1 from FormationUsage FU2\n where FU2.StrandId = new.Id and FU2.StrandStampId <> new.StampId\n )\n and not exists (\n select 1 from Revocation R\n where R.TableName = 'Strand' and R.RowKey = new.Id\n )\n )\n ),\n constraint AuthorizedDelete check on delete (\n -- Delete is authorized by a signature over the DISTINCT 'remove'-tagged digest bound to\n -- the STORED row (Id, StampId), so the add approval \u2014 which never expires \u2014 can never be\n -- replayed as a removal. Note the consent branch above is deliberately NOT mirrored\n -- here: an invitation authorizes forming a strand, never destroying one.\n --\n -- DELIBERATELY no REAP branch (cf. CadrePeer.AuthorizedDelete): this row carries\n -- MemberPrivateKey \u2014 the party's own membership secret for that network, stored nowhere\n -- else \u2014 so this is the one guarded delete whose effect is unrecoverable, and a stale\n -- row is already inert for the purpose a tombstone serves (the consent branch of\n -- AuthorizedInsert above refuses any id ever tombstoned). Do not \"fix\" the asymmetry;\n -- tickets/backlog/debt-strand-tombstone-reap.md owns any future change.\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.Strand', 'remove', old.Id, old.StampId), context.Signature, A.Key, 'ed25519'))\n ),\n constraint MemberKeyClosedOnly check (\n -- An open strand ('o') has no membership gate, so it must not carry a\n -- member key. A non-null MemberPrivateKey requires a closed strand ('c').\n new.MemberPrivateKey is null or new.Type = 'c'\n )\n ) with context (OwnerKey text, Signature text);\n\n -- ONE party's own membership identity for one strand: the private key whose public\n -- half seats this party's `Strand.Member` / `Strand.Manager` rows. Deliberately a\n -- SEPARATE key from Strand.MemberPrivateKey \u2014 that column is the strand-wide read\n -- secret formation hands to EVERY joining party, so an identity derived from it is\n -- one every joiner can forge (gotchoices/sereus#4). A side table rather than a\n -- Strand column because a JOINER holds no control Strand row at all (reference apps\n -- attach formed strands from an in-memory row) yet must persist its own party key\n -- too; keyed by strand id it serves founder and joiner uniformly, and it leaves the\n -- heavily-audited Strand insert digest untouched. Deliberately NO closed-strands-only\n -- cross-table check: the joiner writes this row with no local Strand row to check\n -- against. Party-private in the same sense as MemberPrivateKey \u2014 replicated in\n -- plaintext to every machine the party owns (docs/strands.md \u2192 \"Closed-Strand Member\n -- Key Handling\"; that replication is what lets any of the party's machines sign\n -- membership writes) \u2014 but unlike MemberPrivateKey it is NEVER put on the formation\n -- wire.\n table StrandPartyKey (\n Id text primary key, -- the strand id this key is for\n PrivateKey text not null, -- THIS party's ed25519 strand member private key, base64\n -- protobuf \u2014 the same encoding as Strand.MemberPrivateKey;\n -- decode with cadre-core's strandMemberKeyPair.\n StampId text not null unique, -- single-use authorization nonce (anti-replay).\n -- `unique` holds over LIVE rows only; a removed row's stamp is\n -- retired permanently into Revocation (NotRevoked below).\n -- A removed row's StampId is retired into Revocation, and this refuses any insert\n -- naming a retired stamp: the approval that seated this row can never re-seat it\n -- after removal. Same rationale as OwnerKey.NotRevoked, stated in full there.\n constraint NotRevoked check on insert (\n not exists (select 1 from Revocation R where R.TableName = 'StrandPartyKey' and R.StampId = new.StampId)\n ),\n -- Retirement is MANDATORY: a delete must carry the matching Revocation row in the same\n -- transaction, or the stamp would free up again. Deferred (subquery), so the sibling\n -- insert is visible at commit regardless of statement order. The tombstone must also\n -- name the removed ROW, not just its stamp \u2014 see Revocation.RowKey.\n constraint RevocationRecorded check on delete (\n exists (select 1 from Revocation R where R.TableName = 'StrandPartyKey' and R.StampId = old.StampId and R.RowKey = old.Id)\n ),\n -- Insert + delete only; a rotation is remove-then-insert (fresh stamp, fresh\n -- signature). Required because AuthorizedInsert / AuthorizedDelete below cover\n -- neither update \u2014 an in-place rewrite would swap the party's identity key with\n -- no signature at all. Mirrors ValidationKey.NoUpdate.\n constraint NoUpdate check on update (false),\n constraint AuthorizedInsert check on insert (\n -- Owners authorize by signing over THIS row (Id, PrivateKey, StampId);\n -- single-use via unique StampId. Binding PrivateKey means a captured approval\n -- can only ever reproduce the exact key it approved, never seat an\n -- attacker-chosen identity under the party's name.\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.StrandPartyKey', 'add', new.Id, new.PrivateKey, new.StampId), context.Signature, A.Key, 'ed25519'))\n ),\n constraint AuthorizedDelete check on delete (\n -- Delete is authorized by a signature over the DISTINCT 'remove'-tagged digest\n -- bound to the STORED row (Id, StampId), so the enrollment approval \u2014 which\n -- never expires \u2014 can never be replayed as a removal.\n -- DELIBERATELY no REAP branch (cf. ValidationKey.AuthorizedDelete): like\n -- Strand.MemberPrivateKey, PrivateKey is a secret stored nowhere else, so this\n -- delete's effect is unrecoverable and stays strictly owner-signed. Same\n -- reasoning as Strand.AuthorizedDelete.\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.StrandPartyKey', 'remove', old.Id, old.StampId), context.Signature, A.Key, 'ed25519'))\n )\n ) with context (OwnerKey text, Signature text);\n\n -- A strand THIS party joined from ANOTHER party. The founding party's control database\n -- holds its Strand row, so without this table only the machine that joined would know of\n -- it. Every machine of the party reads it (the strand watcher offers each row like a\n -- Strand row), so a replica host keeps a copy and the party's other machines can attach.\n -- A separate table rather than a Strand row with a provenance marker: Strand means \"this\n -- party's own strand\" to every reader of it (founder derivation, FormationUsage.StrandExists,\n -- unpublish, the consent branch of Strand.AuthorizedInsert), and each would need a\n -- provenance check. MemberPrivateKey is the closed strand's shared read secret the\n -- formation delivered \u2014 replicated in plaintext to every machine the party owns, under the\n -- same accepted risk as Strand.MemberPrivateKey (docs/strands.md \u2192 \"Closed-Strand Member\n -- Key Handling\"). Unlike that column it is not held only here: the founding party and\n -- every member hold it, so a removed row is recoverable by re-forming, which is why this\n -- table (unlike Strand) carries a REAP branch.\n table JoinedStrand (\n Id text primary key, -- the joined strand's id (the founder's Strand.Id)\n Type text not null, -- 'o' | 'c', as Strand.Type\n MemberPrivateKey text null, -- closed strand's shared read secret; null for open\n StampId text not null unique, -- single-use authorization nonce (anti-replay).\n -- `unique` holds over LIVE rows only; a removed row's stamp is\n -- retired permanently into Revocation (NotRevoked below).\n -- The approval that seated a removed row can never re-seat it. Same rationale as\n -- OwnerKey.NotRevoked, stated in full there.\n constraint NotRevoked check on insert (\n not exists (select 1 from Revocation R where R.TableName = 'JoinedStrand' and R.StampId = new.StampId)\n ),\n -- A delete must file its correctly named tombstone in the same transaction. Same\n -- rationale as StrandPartyKey.RevocationRecorded.\n constraint RevocationRecorded check on delete (\n exists (select 1 from Revocation R where R.TableName = 'JoinedStrand' and R.StampId = old.StampId and R.RowKey = old.Id)\n ),\n -- Insert + delete only: neither Authorized rule below covers update, so an in-place\n -- rewrite would swap the read secret unsigned. Mirrors StrandPartyKey.NoUpdate.\n constraint NoUpdate check on update (false),\n -- Readers cast Type to 'o' | 'c' (ControlDatabase.queryJoinedStrands).\n constraint KnownType check (new.Type = 'o' or new.Type = 'c'),\n -- An open strand has no read gate, so no read secret. Same rule as Strand.MemberKeyClosedOnly.\n constraint MemberKeyClosedOnly check (new.MemberPrivateKey is null or new.Type = 'c'),\n constraint AuthorizedInsert check on insert (\n -- Owners authorize by signing over THIS row (Id, Type, MemberPrivateKey, StampId),\n -- MemberPrivateKey signing as '' when null, so a captured approval can only reproduce\n -- the exact secret it approved. Owner-signed, deliberately NOT self-signable by an\n -- enrolled CadrePeer: every always-on machine of the party downloads the strands this\n -- table names, so a non-owner machine could otherwise make them all host an arbitrary\n -- strand. A machine that is not an owner keeps its joins machine-local.\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.JoinedStrand', 'add', new.Id, new.Type, coalesce(new.MemberPrivateKey, ''), new.StampId), context.Signature, A.Key, 'ed25519'))\n ),\n constraint AuthorizedDelete check on delete (\n -- 'remove'-tagged digest over the STORED row (Id, StampId), so the add approval can\n -- never be replayed as a removal.\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.JoinedStrand', 'remove', old.Id, old.StampId), context.Signature, A.Key, 'ed25519'))\n\n -- or REAP: a COMMITTED tombstone already retires this exact row incarnation.\n -- Why committed.* and why the stamp is bound: stated in full on\n -- CadrePeer.AuthorizedDelete. Allowed here, unlike Strand / StrandPartyKey,\n -- because MemberPrivateKey is recoverable (see the table comment).\n or exists (select 1 from committed.Revocation R where R.TableName = 'JoinedStrand' and R.RowKey = old.Id and R.StampId = old.StampId)\n )\n ) with context (OwnerKey text, Signature text);\n\n -- A peer (node) that is part of the cadre, carrying a self-published,\n -- freshness-stamped, self-signed address record (see PeerAddressRecord in cadre-core).\n -- The row IS the peer-address record: a resolver reads it, re-verifies Sig against\n -- PublicKey, checks freshness (UpdatedAt) and trust, then dials the addrs.\n table CadrePeer (\n PeerId text primary key,\n PublicKey text null, -- ed25519 (base64url) whose libp2p identity == PeerId (null if non-Ed25519)\n Multiaddr text, -- comma-joined current addrs (signaling / p2p-circuit first)\n UpdatedAt int null, -- epoch ms; strictly increases per self-update (replay/rollback guard)\n Sig text null, -- ed25519 self-signature over the signed payload (base64url); null until self-published\n StampId text not null unique, -- per-row authorization nonce, bound into the voucher/remove digests; rotates on\n -- (re)insert. A removed row's stamp is retired permanently into Revocation\n -- (NotRevoked below), so a captured admission approval cannot re-seat a removed peer.\n VouchOwner text null, -- ed25519 (base64url) owner key that vouched this membership (== insert context.OwnerKey)\n VouchSig text null, -- that owner's signature over the 'vouch'-tagged digest below (== insert context.Signature). A reader checks VouchOwner against its NODE-LOCAL trusted-owner anchor (not this replicated table, which a self-owner can pollute) to decide authorized membership. The domain/action tags keep this STORED, REPLICATED signature useless against every other rule (pre-tag it satisfied OwnerKey/ValidationKey inserts for Key = PeerId).\n -- A removed row's StampId is retired into Revocation, and this refuses any insert\n -- naming a retired stamp: the approval that seated this row can never re-seat it after\n -- removal. `unique` alone did not do this \u2014 it only holds over LIVE rows, so a delete\n -- freed the stamp and the original never-expiring signature verified again. A\n -- legitimate re-add mints a FRESH StampId and a fresh signature, so it is unaffected.\n constraint NotRevoked check on insert (\n not exists (select 1 from Revocation R where R.TableName = 'CadrePeer' and R.StampId = new.StampId)\n ),\n -- Retirement is MANDATORY: a delete must carry the matching Revocation row in the same\n -- transaction, or the stamp would free up again. Deferred (subquery), so the sibling\n -- insert is visible at commit regardless of statement order. The tombstone must also\n -- name the removed ROW, not just its stamp \u2014 see Revocation.RowKey.\n constraint RevocationRecorded check on delete (\n exists (select 1 from Revocation R where R.TableName = 'CadrePeer' and R.StampId = old.StampId and R.RowKey = old.PeerId)\n ),\n constraint AuthorizedInsert check on insert (\n -- Authorized by an owner key, which vouches both membership and the\n -- PublicKey<->PeerId binding (cadre-core derives PublicKey from PeerId before insert).\n -- The digest binds PeerId + the single-use StampId nonce (two TEXT fields),\n -- matching cadre-core peer-authorization.ts:cadrePeerVoucherDigest. The same\n -- 'vouch'-tagged digest is DELIBERATELY shared with the owner branch of\n -- AuthorizedUpdate below: both mean \"this owner vouches this membership row\".\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.CadrePeer', 'vouch', new.PeerId, new.StampId), context.Signature, A.Key, 'ed25519'))\n -- Persist the vouching (owner, signature) onto the row so a reader can later\n -- re-check VouchOwner against its node-local anchor. The stored pair MUST equal\n -- the pair the verify above validated, so a writer cannot store a voucher it did\n -- not actually receive a signature for.\n and new.VouchOwner = context.OwnerKey\n and new.VouchSig = context.Signature\n ),\n constraint AuthorizedDelete check on delete (\n -- Delete is authorized by a signature over the DISTINCT 'remove'-tagged digest bound\n -- to the row's StampId (cadre-core peer-authorization.ts:cadrePeerRemoveDigest), so\n -- the stored voucher (a signature over the 'vouch'-tagged digest) can NEVER be\n -- replayed to authorize a delete. The remove signature rides in context and is never stored.\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.CadrePeer', 'remove', old.PeerId, old.StampId), context.Signature, A.Key, 'ed25519'))\n\n -- or REAP: this node already holds a COMMITTED tombstone retiring THIS EXACT row\n -- incarnation, so the party owner has already authorized this row's removal and this\n -- node is merely catching up. That is what lets a node which was offline at\n -- revocation time delete the stale row locally, with no owner private key\n -- (control-database.ts:reapRevokedRow). Same shape as the consent branch of\n -- Strand.AuthorizedInsert: authorization by the EXISTENCE of a row rather than by a\n -- signature \u2014 and that row is itself owner-signed (Revocation.Authorized), so this\n -- widens WHO may execute a removal, never WHO may decide one. RevocationRecorded is\n -- satisfied by the same committed tombstone, so a reap files no second one.\n --\n -- committed.Revocation, NOT Revocation \u2014 and the stamp clause \u2014 are both load-bearing:\n -- * committed.* : this CHECK defers to commit (it has a subquery), by which point a\n -- tombstone written in the SAME transaction is live. Reading plain Revocation\n -- would therefore let deleteGuardedRow's own sibling tombstone satisfy this\n -- branch, making the 'remove'-tagged delete signature above dead weight and\n -- collapsing two domain-separated approvals into one. committed.* states the rule\n -- exactly: the tombstone must have existed BEFORE this transaction.\n -- * R.StampId = old.StampId : binds the ROW INCARNATION, not the name. One name may\n -- legitimately carry several tombstones over its life (seat -> delete -> owner\n -- re-seat -> delete). Without this clause a tombstone from a PREVIOUS incarnation\n -- would authorize deleting the CURRENT row, which the owner never removed.\n or exists (select 1 from committed.Revocation R where R.TableName = 'CadrePeer' and R.RowKey = old.PeerId and R.StampId = old.StampId)\n ),\n constraint AuthorizedUpdate check on update (\n -- Peer self-updates its own addrs + freshness, signing with its OWN ed25519 key\n -- (the key behind PeerId). PeerId/PublicKey/StampId/voucher are immutable on\n -- self-update, UpdatedAt must strictly increase (replay guard), and Sig is verified\n -- against the stored PublicKey over the same payload the publish path signs\n -- (cadre-core peer-record.ts:peerRecordSignedPayload).\n (\n new.PeerId = old.PeerId\n and new.PublicKey = old.PublicKey\n and new.StampId = old.StampId\n and new.VouchOwner = old.VouchOwner\n and new.VouchSig = old.VouchSig\n and new.UpdatedAt > coalesce(old.UpdatedAt, 0)\n and verify(\n digest('CadreControl.CadrePeer', 'publish', new.PeerId, new.Multiaddr, cast(new.UpdatedAt as text)),\n new.Sig, new.PublicKey, 'ed25519')\n )\n -- or an owner re-authorizes (rotation / correction): re-vouches the row over\n -- its current StampId, so the stored voucher is re-bound to the re-authorizing owner.\n -- StampId is immutable here too: an update that rotated it would leave the OLD\n -- stamp live-free and untombstoned (RevocationRecorded only retires the stamp a\n -- delete carries), so the original admission approval \u2014 which is stored on the\n -- replicated row as VouchSig \u2014 would resurrect the peer after a later removal.\n -- Retiring a stamp is delete + Revocation row, never an update.\n or (\n new.StampId = old.StampId\n and exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.CadrePeer', 'vouch', new.PeerId, new.StampId), context.Signature, A.Key, 'ed25519'))\n and new.VouchOwner = context.OwnerKey\n and new.VouchSig = context.Signature\n )\n )\n ) with context (OwnerKey text null, Signature text);\n\n -- A mobile cadre peer's platform push token (FCM/APNs), self-published so a\n -- server peer can deliver a push-wake to a suspended app over the platform push\n -- channel (a control-network dial cannot reach an OS-suspended process). The row\n -- mirrors CadrePeer: a resolver re-verifies Sig against the CadrePeer.PublicKey for\n -- this PeerId (see device-token.ts:deviceTokenSignedPayload), checks freshness, then\n -- hands the token to the push sender.\n table DeviceToken (\n PeerId text primary key, -- the CadrePeer this token belongs to\n Platform text not null, -- 'fcm' | 'apns'\n Token text not null, -- opaque platform device/registration token\n UpdatedAt int null, -- epoch ms; strictly increases per self-update (replay guard)\n Sig text null, -- ed25519 self-sig over (PeerId|Platform|Token|UpdatedAt)\n StampId text not null unique, -- single-use authorization nonce, bound into the add/remove digests;\n -- rotates on (re)insert. A cleared token's stamp is retired permanently\n -- into Revocation (NotRevoked below), so the approval that published a\n -- token cannot re-seat it after the owner cleared it (logout).\n -- A removed row's StampId is retired into Revocation, and this refuses any insert\n -- naming a retired stamp: the approval that seated this row can never re-seat it after\n -- the clear. `unique` alone did not do this \u2014 it only holds over LIVE rows, so a delete\n -- freed the stamp and the original never-expiring signature verified again. A legitimate\n -- re-register mints a FRESH StampId and a fresh signature, so it is unaffected. This\n -- matters more here than the stored-approval case (CadrePeer.VouchSig): a resurrected\n -- push token has NO freshness ceiling to retire it \u2014 cadre-node.ts:resolveDeviceToken\n -- defaults maxAgeMs to infinity by design \u2014 so retirement is the only thing that sticks.\n constraint NotRevoked check on insert (\n not exists (select 1 from Revocation R where R.TableName = 'DeviceToken' and R.StampId = new.StampId)\n ),\n -- Retirement is MANDATORY: a delete must carry the matching Revocation row in the same\n -- transaction, or the stamp would free up again. Deferred (subquery), so the sibling\n -- insert is visible at commit regardless of statement order. The tombstone must also\n -- name the removed ROW, not just its stamp \u2014 see Revocation.RowKey.\n constraint RevocationRecorded check on delete (\n exists (select 1 from Revocation R where R.TableName = 'DeviceToken' and R.StampId = old.StampId and R.RowKey = old.PeerId)\n ),\n constraint AuthorizedInsert check on insert (\n -- Authorized by an owner key (membership vouch), exactly like CadrePeer.\n -- The digest binds the WHOLE row behind the domain/action tags \u2014 every column,\n -- with the nullable UpdatedAt/Sig signing as '' when absent (the shape\n -- FormationInvite and Strand already use) \u2014 so a replayed approval can only ever\n -- reproduce the row it approved, never one carrying attacker-chosen\n -- Platform/Token/UpdatedAt; NotRevoked above then refuses even that exact row\n -- once it has been cleared. The DISTINCT 'remove'-tagged digest below keeps a\n -- captured insert approval from doubling as a delete (and vice versa).\n -- Mirrors cadre-core peer-authorization.ts:deviceTokenAddDigest.\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(\n digest(\n 'CadreControl.DeviceToken', 'add',\n new.PeerId,\n new.Platform,\n new.Token,\n coalesce(cast(new.UpdatedAt as text), ''),\n coalesce(new.Sig, ''),\n new.StampId\n ),\n context.Signature, A.Key, 'ed25519'))\n ),\n constraint AuthorizedDelete check on delete (\n -- Bound to the STORED row's (PeerId, StampId) \u2014 cadre-core\n -- peer-authorization.ts:deviceTokenRemoveDigest \u2014 so the never-expiring insert\n -- approval can never be replayed as a clear, and a captured clear approval is\n -- dead once the stamp it names is retired.\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.DeviceToken', 'remove', old.PeerId, old.StampId), context.Signature, A.Key, 'ed25519'))\n\n -- or REAP: a COMMITTED tombstone already retires this exact row incarnation, so a node\n -- that was offline at removal time may delete the stale row locally with no owner key.\n -- Why committed.* and why the stamp must be bound: stated in full on\n -- CadrePeer.AuthorizedDelete.\n or exists (select 1 from committed.Revocation R where R.TableName = 'DeviceToken' and R.RowKey = old.PeerId and R.StampId = old.StampId)\n ),\n constraint AuthorizedUpdate check on update (\n -- Peer self-updates its own token, signing with its OWN ed25519 key (the key\n -- behind PeerId). PeerId and StampId are immutable, UpdatedAt must strictly\n -- increase (replay guard), and Sig is verified against the stored\n -- CadrePeer.PublicKey over the signed payload (cadre-core\n -- device-token.ts:deviceTokenSignedPayload). Platform and Token may change on\n -- self-update (platform switch / reinstall / rotation).\n -- StampId is immutable for the reason CadrePeer spells out: an update that\n -- rotated it would leave the OLD stamp live-free and untombstoned, so retiring a\n -- stamp stays delete + Revocation row, never an update.\n -- This is the ONLY branch: there is deliberately NO owner re-touch. The branch\n -- that used to sit beside it verified an owner signature over the peer id alone\n -- and sat OUTSIDE the monotonicity requirement, so one captured owner approval\n -- rewrote Platform/Token and rolled UpdatedAt BACKWARDS \u2014 and seating a\n -- far-future UpdatedAt wedged the peer's own self-updates permanently. No writer\n -- used it. An owner that must correct a row deletes it (retiring the stamp) and\n -- inserts a fresh one, the same path it already takes for CadrePeer.\n new.PeerId = old.PeerId\n and new.StampId = old.StampId\n and new.UpdatedAt > coalesce(old.UpdatedAt, 0)\n and exists (select 1 from CadrePeer P where P.PeerId = new.PeerId and verify(\n digest('CadreControl.DeviceToken', 'publish', new.PeerId, new.Platform, new.Token, cast(new.UpdatedAt as text)),\n new.Sig, P.PublicKey, 'ed25519'))\n )\n ) with context (OwnerKey text null, Signature text);\n\n -- An open invitation to form a strand with this party\n table FormationInvite (\n Token text primary key, -- Just a random string\n sAppId text, -- The app for the strand that will be formed\n ExpiresAt datetime null,\n TotalUses int null check (TotalUses >= 0),\n ValidationUrl text null, -- Web hook - send disclosure, IP address...\n StrandId text null, -- Host strand this invite binds to (provision-then-record). Non-null => the responder records consent against this pre-existing strand; null => unbound invite: the responder provisions a fresh open strand and atomically records its one consent row.\n StampId text not null unique, -- single-use authorization nonce (anti-replay)\n constraint AuthorizedInsert check on insert (\n -- Authorized by an owner signing over THIS row\n -- (Token, sAppId, ExpiresAt, TotalUses, ValidationUrl, StrandId, StampId); single-use via unique StampId.\n -- Nullable bound fields (ExpiresAt/TotalUses/ValidationUrl/StrandId) sign as '' when absent.\n -- The 'remove'-tagged AuthorizedDelete digest below is DISTINCT, so a captured\n -- insert approval can never be replayed to revoke-then-reissue an invite (or vice versa).\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(\n digest(\n 'CadreControl.FormationInvite', 'add',\n new.Token,\n new.sAppId,\n coalesce(cast(new.ExpiresAt as text), ''),\n coalesce(cast(new.TotalUses as text), ''),\n coalesce(new.ValidationUrl, ''),\n coalesce(new.StrandId, ''),\n new.StampId\n ),\n context.Signature, A.Key, 'ed25519'))\n ),\n constraint AuthorizedDelete check on delete (\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(\n digest(\n 'CadreControl.FormationInvite', 'remove',\n old.Token,\n old.sAppId,\n coalesce(cast(old.ExpiresAt as text), ''),\n coalesce(cast(old.TotalUses as text), ''),\n coalesce(old.ValidationUrl, ''),\n coalesce(old.StrandId, ''),\n old.StampId\n ),\n context.Signature, A.Key, 'ed25519'))\n ),\n -- Invites are insert/delete only: forbid in-place mutation so the row-bound\n -- AuthorizedInsert signature cannot be sidestepped by updating consent\n -- parameters (TotalUses/ExpiresAt/...) after a legitimate insert. A bare check\n -- defaults to insert+update; the checks on insert / on delete above exclude update,\n -- so this guard is required. Mirrors FormationUsage.InsertOnly.\n constraint Immutable check on update (false)\n ) with context (OwnerKey text, Signature text);\n\n table FormationUsage (\n Token text not null, -- the FormationInvite this acceptance redeems. Stated explicitly because\n -- Token is no longer a primary-key prefix; Authorized below would refuse a\n -- null anyway (null = null is never true, so its FormationInvite\n -- exists-clause cannot match), but the column carries the invariant rather\n -- than leaving it to a CHECK.\n UsageStampId text not null, -- single-use nonce for THIS redemption, and this table's PRIMARY KEY.\n -- The JOINING peer mints it and sends it in its contact message, having\n -- signed it into its own 'consent' digest (PeerConsented below); the\n -- responder inserts that same value and asks the approver about it, so it\n -- is bound into the 'vouch' digest below too and one sign-off is spendable\n -- exactly once. Neither side can swap it: a substituted nonce fails the\n -- joiner's consent signature.\n -- As the row key, a verbatim replay of an approval collides on the\n -- primary key locally instead of on a column `unique`. Unlike every other\n -- StampId in this schema, this table is append-only (InsertOnly below),\n -- so the nonce is never freed by a delete: the key alone makes it\n -- permanent and there is deliberately NO NotRevoked / RevocationRecorded\n -- pair here \u2014 do not go looking for the missing one.\n -- NOTE: the key is evaluated against LOCALLY VISIBLE rows, so two nodes\n -- that have not yet converged could each admit the same nonce and both\n -- rows survive the merge. Same class as the NotRevoked convergence notes\n -- on OwnerKey / Strand / ValidationKey; the digest binding still holds on\n -- both nodes, so the outcome is a duplicated audit row, never a join\n -- nobody approved.\n PeerKey text not null, -- the joining peer's own ed25519 public key (base64url, 32 bytes), bound\n -- into BOTH the approver's 'vouch' digest and the joiner's 'consent'\n -- digest below, so an approval cannot be re-filed under a different\n -- joiner's name and the named joiner provably agreed (PeerConsented).\n -- The key IS the joiner's identity \u2014 its libp2p peer id is derivable\n -- (identity multihash of these bytes), never stored here.\n PeerSig text not null, -- the joining peer's signature over the 'consent' digest \u2014 see\n -- PeerConsented below for what it proves and why it is stored on the row.\n Disclosure text,\n StrandId text,\n StrandStampId text not null, -- the Strand.StampId this consent record authorizes. Consent is\n -- bound to ONE strand ROW, not to a strand id forever \u2014 see\n -- Strand.AuthorizedInsert's consent branch for why. NOT unique:\n -- in the bound (provision-then-record) path several invitees\n -- each write a usage row against the SAME host strand, so many\n -- usage rows legitimately share one stamp.\n primary key (UsageStampId),\n constraint InsertOnly check on update, delete (false),\n constraint Authorized check on insert (\n -- Satisfies an invitation\n exists (\n select 1 from FormationInvite FI\n where FI.Token = new.Token\n -- The use cap is COUNTED against the pre-transaction snapshot, never\n -- sequenced. This CHECK auto-defers to commit (it has a subquery), by\n -- which point the in-flight row is live; committed.* is what excludes\n -- it, so a sequentially exhausted invite \u2014 every seat already committed\n -- on this node \u2014 is still refused here. What is deliberately NOT\n -- refused: concurrent redeemers on separate nodes (or nodes that have\n -- not yet converged) each count the same committed snapshot and both\n -- land, over-admitting by at most the number of concurrent redeemers.\n -- Both rows survive in this append-only record, so the overage is\n -- auditable, and removal is owner-gated (member removal + Revocation).\n -- Same class as the convergence note on UsageStampId above.\n -- One rule for FUTURE writers: two FormationUsage rows for one token\n -- inserted in ONE transaction each read the same committed count, so\n -- they can jointly exceed the cap. No writer in this repo does that; it\n -- is a constraint on new writers, not a case to engineer for.\n -- Do not \"fix\" this into a per-token sequence number to restore a\n -- strict cap \u2014 that trade was weighed and rejected (2026-08-04): a\n -- fought-over sequence key turns a concurrent redemption into a silent,\n -- unrecoverable loss of a consented join, which is strictly worse than\n -- a visible, reversible over-admission.\n and (FI.TotalUses is null or FI.TotalUses > (select count(1) from committed.FormationUsage U where U.Token = new.Token))\n and (FI.ExpiresAt is null or FI.ExpiresAt > context.Now)\n -- An invite carrying a ValidationUrl demands a sign-off from a key the party\n -- ENROLLED in ValidationKey. The signature is verified against the STORED VK.Key,\n -- NOT against context.ValidationKey \u2014 that distinction is the whole point:\n -- context.ValidationKey is a plain insert parameter, so verifying against it asked\n -- only \"did the redeemer sign its own disclosure with SOME key it holds?\", which any\n -- redeemer answers by minting a throwaway keypair. context.ValidationKey survives\n -- purely to SELECT which enrolled row is being claimed; naming an enrolled key while\n -- signing with a different one fails the verify against VK.Key.\n --\n -- Deliberate: CHECKs run on write only, so removing a validation key later does NOT\n -- re-examine the FormationUsage rows it already approved. The sign-off was valid when\n -- given and the strand it authorized stays formed; removal narrows who may approve\n -- FUTURE redemptions, it is not a retroactive revocation of past ones.\n --\n -- What ONE sign-off buys: exactly ONE row. The digest covers\n -- (Token, UsageStampId, StrandId, PeerKey, Disclosure), so an approval is NOT\n -- transferable across invitations, redemptions, networks, joiners, or disclosure\n -- text. Replay is closed twice over, by two independent mechanisms: presenting an\n -- approval VERBATIM repeats its UsageStampId and is refused by this table's\n -- primary key; presenting it under any OTHER redemption changes a signed field\n -- and fails this verify.\n -- Every signed field is supplied by the redeeming side \u2014 nothing derived from\n -- the table's current state is bound \u2014 so no concurrent write can invalidate an\n -- approval between the sign-off and the row landing.\n -- Why StrandStampId is deliberately NOT bound: it names the strand ROW\n -- incarnation, which the unbound path (redeemInvitation) mints inside its own\n -- transaction, and it adds nothing on top of a strictly single-use approval \u2014\n -- StrandId already pins WHICH network the approver approved joining.\n and (FI.ValidationUrl is null or exists (\n select 1 from ValidationKey VK\n where VK.Key = context.ValidationKey\n and verify(digest('CadreControl.FormationUsage', 'vouch', new.Token, new.UsageStampId, new.StrandId, new.PeerKey, new.Disclosure), context.ValidationSignature, VK.Key, 'ed25519')))\n -- A bound invite (non-null StrandId) may only ever name its own host strand:\n -- without this, any holder of a bound token could record consent against an\n -- arbitrary strand id \u2014 annotating an unrelated strand, or (before\n -- Strand.AuthorizedInsert's consent branch was narrowed to unbound invites)\n -- consent-seating that id outright.\n -- NOTE: an UNBOUND invite is deliberately left free to name any strand, so a\n -- holder can spend a use appending a consent row to an unrelated existing\n -- strand. Harmless today (the row grants nothing, it only burns a use and\n -- forecloses that id's consent-seating, which is the safe direction); if\n -- unlimited-TotalUses invites ever become common, this is an append-only\n -- growth surface worth bounding.\n and (FI.StrandId is null or FI.StrandId = new.StrandId)\n )\n ),\n -- Matched on the (id, stamp) PAIR, the same key Strand.AuthorizedInsert's consent branch\n -- reads back: a usage row may only ever name a strand ROW that exists, so a consent record\n -- can never be filed against a stamp of the writer's choosing and held in reserve to\n -- re-seat the id after a removal.\n constraint StrandExists check (exists (select 1 from Strand S where S.Id = new.StrandId and S.StampId = new.StrandStampId)),\n -- The JOINING peer proves it consented to this redemption: PeerKey is its own ed25519\n -- public key and PeerSig is its signature over the 'consent'-tagged digest below.\n -- Unlike the approver's sign-off (context.ValidationSignature, checked against a STORED\n -- ValidationKey row), the identity here IS the key, so there is no enrolled row to look\n -- up and nothing for a writer to substitute: a forged joiner would need that joiner's\n -- private key. Stored rather than passed in context so any later reader can re-check it\n -- (verifyFormationConsent); the 'consent' action tag keeps this replicated signature\n -- useless against every other rule in this schema (notably the approver's 'vouch'\n -- digest over the same table).\n -- NOTE: StrandId is deliberately NOT in this digest \u2014 the joiner cannot know it when it\n -- signs (a bound invite's host strand arrives only in the result frame; an unbound\n -- strand is responder-minted). The responder cannot substitute a strand anyway: bound\n -- invites are pinned by Authorized's FI.StrandId check, unbound invites mint fresh.\n constraint PeerConsented check on insert (\n verify(digest('CadreControl.FormationUsage', 'consent',\n new.Token, new.UsageStampId, new.PeerKey, new.Disclosure),\n new.PeerSig, new.PeerKey, 'ed25519')\n ),\n -- Context here is only what the approver-side rules read: Now for expiry, and the\n -- ValidationKey/ValidationSignature pair for the 'vouch' check in Authorized. The joiner's\n -- signature is NOT context \u2014 it lives on the row (PeerSig, verified by PeerConsented above).\n ) with context (Now datetime, ValidationKey text null, ValidationSignature text null);\n\n -- Token is no longer a primary-key prefix (the key is the redemption nonce), so the\n -- per-token filters \u2014 the cap count in Authorized above, and cadre-core's\n -- countFormationUsage / isTokenUsed / hasOutstandingFormationInvite \u2014 are served by this\n -- index rather than by a full scan of a table that is append-only and grows for the life\n -- of the party.\n --\n -- The cap count is only ever as correct as this index's convergence across machines. That\n -- convergence failed once: from 2026-08-04 to 2026-08-25 a descent on a second machine\n -- returned only the rows THAT machine wrote, so the index was removed and the reads went\n -- back to the scan. The engine defect was fixed upstream and re-measured here on\n -- 2026-09-17, so the index is declared again. Its guard is the integration-tests scenario\n -- `strand-formation-concurrent-redemption`, which asserts BOTH machines' views of a raced\n -- redemption and therefore goes red if that convergence regresses.\n --\n -- NOTE: the write side has its own exposure. Every FormationUsage insert now maintains this\n -- sub-collection as well as the table, and an intermittent engine failure once hit exactly that\n -- step on other tables (a table's rows committed while its index did not; closed 2026-09-17 with\n -- the upstream sync fixes, `tickets/complete/strand-unique-index-sync-stale-revision`). Nothing\n -- has been observed here, and redemptions are rare writes; but if joins start failing\n -- intermittently with an index-sync error naming FormationUsage, this declaration is the first\n -- thing to suspect.\n index FormationUsageByToken on FormationUsage (Token);\n\n -- Append-only retirement record for the one-off StampId nonces of removed rows of every\n -- guarded table (listed on TableName below). Without it a removal was undoable: the add\n -- approval is a signature over\n -- (row key, stamp) that never expires, and deleting the row freed the stamp, so anyone who\n -- kept a copy of the approval could resurrect the row.\n -- Each tombstone also records WHICH row was retired (RowKey below): the consent branch of\n -- Strand.AuthorizedInsert reads it to refuse consent-seating any strand id that has ever\n -- been removed, whichever way it was seated.\n -- NOTE: the guarded tables' NotRevoked CHECK runs against locally visible rows, so a node\n -- that has not yet converged on a Revocation row can still accept the replayed add, and the\n -- resurrected row coexists with the tombstone after merge \u2014 same class as the MinOneOwner\n -- note on OwnerKey. The read-side mitigation is ControlDatabase.queryCadrePeers, which\n -- drops any CadrePeer row whose StampId appears here; every membership reader inherits it.\n -- NOTE: append-only, so this table only ever grows. Every append is owner-signed\n -- (Authorized below), so the growth surface is the owner keys, not every writer that can\n -- reach the control database. Cadres are a handful of peers and owner rotation is rare, so\n -- unbounded growth is fine today; revisit if either changes.\n -- A tombstone committed while the node was alone is local-only (never broadcast); the\n -- ReissuedAt counter below exists so an owner can re-write \u2014 and therefore re-broadcast \u2014\n -- such a tombstone once peers are reachable, without changing what it means.\n -- One row retires nothing: the singleton ledger marker ('Revocation', 'ledger', 'opened'),\n -- filed once by an owner's connected reconcile pass (ControlDatabase.openRevocationLedger).\n -- It exists only so this table is never a never-written block. The storage layer consults\n -- a block's cohort on EVERY read of a block it does not hold, and every membership lookup\n -- and every guarded insert (NotRevoked) reads this table; once any row exists the block is\n -- held and re-checked on the storage layer's normal read-repair schedule, like every other\n -- populated table. It cannot read as a retirement: every reader of this table filters on\n -- its own guarded TableName, 'Revocation' is not one, and ControlDatabase.queryRevocations\n -- skips the marker, so nothing reaps or re-issues it.\n table Revocation (\n TableName text, -- 'OwnerKey' | 'CadrePeer' | 'ValidationKey' | 'Strand' | 'StrandPartyKey' |\n -- 'JoinedStrand' | 'DeviceToken', or 'Revocation' for the ledger marker only\n -- (all confined by RowIsGone below)\n RowKey text not null, -- primary key of the removed row: OwnerKey.Key / ValidationKey.Key /\n -- CadrePeer.PeerId / DeviceToken.PeerId / Strand.Id / StrandPartyKey.Id /\n -- JoinedStrand.Id\n -- Every guarded table's RevocationRecorded CHECK requires the\n -- accompanying tombstone to carry the removed row's key here, so\n -- a REMOVAL cannot file a misnamed tombstone. A tombstone with no\n -- accompanying delete is not covered by that (see Authorized).\n StampId text, -- the retired nonce\n -- Bumped by an owner-signed re-issue so a tombstone written while the node was alone\n -- (committed local-only, never broadcast) can be re-written and therefore re-broadcast\n -- on cohort growth. Carries NO semantics: nothing reads it, and retirement is decided\n -- by the row's existence, not by this value.\n ReissuedAt integer not null default 0,\n -- Keyed on the stamp, not the RowKey: stamps are unique per row incarnation, and one\n -- name may legitimately carry several tombstones over its life (seat -> delete ->\n -- owner re-seat -> delete).\n primary key (TableName, StampId),\n -- Retirement is permanent: a tombstone may never be withdrawn.\n constraint NoDelete check on delete (false),\n -- Pinned at 0 on insert so an owner cannot seat a tombstone at a saturated counter and\n -- thereby freeze its own later re-issues (ReissueOnly below). Deliberately NOT folded\n -- into the Authorized digest: the value is fixed by this rule, so signing over it would\n -- only widen the signed surface for no gain, and would invalidate every existing\n -- insert-side digest.\n constraint FreshTombstone check on insert (new.ReissuedAt = 0),\n -- A re-issue may move NOTHING but the counter, and only upward. Without the identity\n -- clause an \"update\" would be a way to re-point a tombstone at a different row,\n -- restoring exactly the replay this table exists to stop.\n constraint ReissueOnly check on update (\n new.TableName = old.TableName and new.RowKey = old.RowKey\n and new.StampId = old.StampId and new.ReissuedAt > old.ReissuedAt\n ),\n -- A stamp may only be retired once its row is actually gone. Deferred (subquery), so a\n -- delete in the same transaction has already landed. Retiring a stamp that never\n -- existed is permitted and harmless: a stamp carries 128 bits of CSPRNG output\n -- (control-database.ts:generateStampId \u2014 16 bytes of sha256(PeerId) followed by 16\n -- random bytes), so a future legitimate one cannot be guessed and pre-planted.\n -- Deliberately keyed on the STAMP only, not RowKey: checking \"no live row named\n -- new.RowKey\" breaks under out-of-order convergence \u2014 a peer removed (tombstone names\n -- it, stamp1) then re-admitted (stamp2) would leave a node that converges on the\n -- re-add FIRST rejecting the stamp1 tombstone forever, never learning that stamp is\n -- retired. The stamp-only form passes there (stamp1 is not live).\n -- The last branch admits the ledger marker (see the table comment) and nothing else under\n -- TableName 'Revocation': the whole triple is pinned, so with the primary key\n -- (TableName, StampId) it is a singleton and the append-only growth surface is unchanged.\n -- 'opened' cannot collide with a real stamp (43 base64url characters, generateStampId),\n -- and the primary key includes TableName anyway.\n constraint RowIsGone check on insert (\n (new.TableName = 'OwnerKey' and not exists (select 1 from OwnerKey K where K.StampId = new.StampId))\n or (new.TableName = 'CadrePeer' and not exists (select 1 from CadrePeer P where P.StampId = new.StampId))\n or (new.TableName = 'ValidationKey' and not exists (select 1 from ValidationKey V where V.StampId = new.StampId))\n or (new.TableName = 'Strand' and not exists (select 1 from Strand S where S.StampId = new.StampId))\n or (new.TableName = 'StrandPartyKey' and not exists (select 1 from StrandPartyKey K where K.StampId = new.StampId))\n or (new.TableName = 'JoinedStrand' and not exists (select 1 from JoinedStrand J where J.StampId = new.StampId))\n or (new.TableName = 'DeviceToken' and not exists (select 1 from DeviceToken D where D.StampId = new.StampId))\n or (new.TableName = 'Revocation' and new.RowKey = 'ledger' and new.StampId = 'opened')\n ),\n -- Appending a tombstone is an OWNER action, like every other write in this schema.\n -- Ungated, any writer that could reach the control database could retire a stamp:\n -- filing one against a CadrePeer row not visible locally (RowIsGone reads LOCALLY\n -- VISIBLE rows \u2014 see the convergence note above) evicted that peer party-wide AND\n -- permanently blocked the owner's own later re-admission of it (NotRevoked), and\n -- filing arbitrary stamps flooded a table whose rows never go away.\n -- The digest binds the WHOLE row (TableName, RowKey, StampId); the 'CadreControl.Revocation'\n -- domain tag keeps it disjoint from every other rule \u2014 including the\n -- 'CadreControl.CadrePeer' 'remove' digest the same owner signs in the SAME\n -- transaction for the delete this tombstone accompanies.\n -- RowKey is not cross-checked HERE against the retired row: positively binding it (e.g.\n -- requiring a committed.Strand row carrying the pair) would reject a tombstone re-issued\n -- in a LATER transaction \u2014 which the delete-while-alone durability path\n -- (docs/architecture.md) plans to do \u2014 and reject it outright on a node that never\n -- converged on the removed row. The binding lives on the other side instead: each\n -- guarded table's RevocationRecorded requires the tombstone accompanying a DELETE to\n -- name that row's key, which the re-issue path never trips (it files no delete).\n -- Residual: a STANDALONE tombstone \u2014 owner-signed, naming a stamp no live row holds \u2014\n -- is still accepted, so an owner can name an id that never existed and thereby\n -- permanently foreclose CONSENT-seating of that id (Strand.AuthorizedInsert).\n -- Owner-only, the owner already controls invite issuance, and unbound ids are 128\n -- random bytes minted at redemption \u2014 no escalation (same reasoning as the pre-plant\n -- note on RowIsGone).\n -- Reads LIVE OwnerKey (like ValidationKey / Strand / CadrePeer / DeviceToken), not\n -- committed.OwnerKey. The one difference that makes: a founding transaction on an\n -- owner-less database could seat an owner key and file a tombstone in one go. An\n -- owner-less control database is already a total loss, and a second transaction\n -- achieves the same thing under committed.*, so consistency with the siblings is\n -- worth more than the distinction \u2014 do not \"tighten\" this without a reason other\n -- than that one.\n -- RowIsGone and NoDelete are unchanged: they guard an owner retiring a stamp early\n -- or withdrawing one later, which authorization does not cover.\n -- The ledger marker is signed under this same rule, over\n -- digest('CadreControl.Revocation', 'remove', 'Revocation', 'ledger', 'opened'). The\n -- 'remove' tag on a row that retires nothing is deliberate: reusing the one append rule\n -- keeps every append owner-signed without adding an unsigned or differently tagged\n -- branch, and a captured marker signature can only re-file the identical row, whose\n -- primary key is already taken.\n constraint Authorized check on insert (\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.Revocation', 'remove', new.TableName, new.RowKey, new.StampId), context.Signature, A.Key, 'ed25519'))\n ),\n -- A re-issue is an OWNER action, like the original append. Distinct 'reissue' action\n -- tag, so an append approval can never be replayed as a re-issue and vice versa. The\n -- digest adds ReissuedAt so a captured re-issue signature cannot bump the counter to\n -- any other value. Reads LIVE OwnerKey, matching Authorized above.\n constraint AuthorizedReissue check on update (\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey\n and verify(digest('CadreControl.Revocation', 'reissue',\n new.TableName, new.RowKey, new.StampId, cast(new.ReissuedAt as text)),\n context.Signature, A.Key, 'ed25519'))\n )\n ) with context (OwnerKey text, Signature text);\n}\n\napply schema CadreControl;";
@@ -365,6 +365,65 @@ declare schema CadreControl {
365
365
  )
366
366
  ) with context (OwnerKey text, Signature text);
367
367
 
368
+ -- A strand THIS party joined from ANOTHER party. The founding party's control database
369
+ -- holds its Strand row, so without this table only the machine that joined would know of
370
+ -- it. Every machine of the party reads it (the strand watcher offers each row like a
371
+ -- Strand row), so a replica host keeps a copy and the party's other machines can attach.
372
+ -- A separate table rather than a Strand row with a provenance marker: Strand means "this
373
+ -- party's own strand" to every reader of it (founder derivation, FormationUsage.StrandExists,
374
+ -- unpublish, the consent branch of Strand.AuthorizedInsert), and each would need a
375
+ -- provenance check. MemberPrivateKey is the closed strand's shared read secret the
376
+ -- formation delivered — replicated in plaintext to every machine the party owns, under the
377
+ -- same accepted risk as Strand.MemberPrivateKey (docs/strands.md → "Closed-Strand Member
378
+ -- Key Handling"). Unlike that column it is not held only here: the founding party and
379
+ -- every member hold it, so a removed row is recoverable by re-forming, which is why this
380
+ -- table (unlike Strand) carries a REAP branch.
381
+ table JoinedStrand (
382
+ Id text primary key, -- the joined strand's id (the founder's Strand.Id)
383
+ Type text not null, -- 'o' | 'c', as Strand.Type
384
+ MemberPrivateKey text null, -- closed strand's shared read secret; null for open
385
+ StampId text not null unique, -- single-use authorization nonce (anti-replay).
386
+ -- \`unique\` holds over LIVE rows only; a removed row's stamp is
387
+ -- retired permanently into Revocation (NotRevoked below).
388
+ -- The approval that seated a removed row can never re-seat it. Same rationale as
389
+ -- OwnerKey.NotRevoked, stated in full there.
390
+ constraint NotRevoked check on insert (
391
+ not exists (select 1 from Revocation R where R.TableName = 'JoinedStrand' and R.StampId = new.StampId)
392
+ ),
393
+ -- A delete must file its correctly named tombstone in the same transaction. Same
394
+ -- rationale as StrandPartyKey.RevocationRecorded.
395
+ constraint RevocationRecorded check on delete (
396
+ exists (select 1 from Revocation R where R.TableName = 'JoinedStrand' and R.StampId = old.StampId and R.RowKey = old.Id)
397
+ ),
398
+ -- Insert + delete only: neither Authorized rule below covers update, so an in-place
399
+ -- rewrite would swap the read secret unsigned. Mirrors StrandPartyKey.NoUpdate.
400
+ constraint NoUpdate check on update (false),
401
+ -- Readers cast Type to 'o' | 'c' (ControlDatabase.queryJoinedStrands).
402
+ constraint KnownType check (new.Type = 'o' or new.Type = 'c'),
403
+ -- An open strand has no read gate, so no read secret. Same rule as Strand.MemberKeyClosedOnly.
404
+ constraint MemberKeyClosedOnly check (new.MemberPrivateKey is null or new.Type = 'c'),
405
+ constraint AuthorizedInsert check on insert (
406
+ -- Owners authorize by signing over THIS row (Id, Type, MemberPrivateKey, StampId),
407
+ -- MemberPrivateKey signing as '' when null, so a captured approval can only reproduce
408
+ -- the exact secret it approved. Owner-signed, deliberately NOT self-signable by an
409
+ -- enrolled CadrePeer: every always-on machine of the party downloads the strands this
410
+ -- table names, so a non-owner machine could otherwise make them all host an arbitrary
411
+ -- strand. A machine that is not an owner keeps its joins machine-local.
412
+ exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.JoinedStrand', 'add', new.Id, new.Type, coalesce(new.MemberPrivateKey, ''), new.StampId), context.Signature, A.Key, 'ed25519'))
413
+ ),
414
+ constraint AuthorizedDelete check on delete (
415
+ -- 'remove'-tagged digest over the STORED row (Id, StampId), so the add approval can
416
+ -- never be replayed as a removal.
417
+ exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.JoinedStrand', 'remove', old.Id, old.StampId), context.Signature, A.Key, 'ed25519'))
418
+
419
+ -- or REAP: a COMMITTED tombstone already retires this exact row incarnation.
420
+ -- Why committed.* and why the stamp is bound: stated in full on
421
+ -- CadrePeer.AuthorizedDelete. Allowed here, unlike Strand / StrandPartyKey,
422
+ -- because MemberPrivateKey is recoverable (see the table comment).
423
+ or exists (select 1 from committed.Revocation R where R.TableName = 'JoinedStrand' and R.RowKey = old.Id and R.StampId = old.StampId)
424
+ )
425
+ ) with context (OwnerKey text, Signature text);
426
+
368
427
  -- A peer (node) that is part of the cadre, carrying a self-published,
369
428
  -- freshness-stamped, self-signed address record (see PeerAddressRecord in cadre-core).
370
429
  -- The row IS the peer-address record: a resolver reads it, re-verifies Sig against
@@ -785,8 +844,8 @@ declare schema CadreControl {
785
844
  -- thing to suspect.
786
845
  index FormationUsageByToken on FormationUsage (Token);
787
846
 
788
- -- Append-only retirement record for the one-off StampId nonces of removed OwnerKey /
789
- -- CadrePeer / ValidationKey / Strand rows. Without it a removal was undoable: the add
847
+ -- Append-only retirement record for the one-off StampId nonces of removed rows of every
848
+ -- guarded table (listed on TableName below). Without it a removal was undoable: the add
790
849
  -- approval is a signature over
791
850
  -- (row key, stamp) that never expires, and deleting the row freed the stamp, so anyone who
792
851
  -- kept a copy of the approval could resurrect the row.
@@ -815,10 +874,12 @@ declare schema CadreControl {
815
874
  -- its own guarded TableName, 'Revocation' is not one, and ControlDatabase.queryRevocations
816
875
  -- skips the marker, so nothing reaps or re-issues it.
817
876
  table Revocation (
818
- TableName text, -- 'OwnerKey' | 'CadrePeer' | 'ValidationKey' | 'Strand' | 'StrandPartyKey' | 'DeviceToken',
819
- -- or 'Revocation' for the ledger marker only (all confined by RowIsGone below)
877
+ TableName text, -- 'OwnerKey' | 'CadrePeer' | 'ValidationKey' | 'Strand' | 'StrandPartyKey' |
878
+ -- 'JoinedStrand' | 'DeviceToken', or 'Revocation' for the ledger marker only
879
+ -- (all confined by RowIsGone below)
820
880
  RowKey text not null, -- primary key of the removed row: OwnerKey.Key / ValidationKey.Key /
821
- -- CadrePeer.PeerId / DeviceToken.PeerId / Strand.Id / StrandPartyKey.Id
881
+ -- CadrePeer.PeerId / DeviceToken.PeerId / Strand.Id / StrandPartyKey.Id /
882
+ -- JoinedStrand.Id
822
883
  -- Every guarded table's RevocationRecorded CHECK requires the
823
884
  -- accompanying tombstone to carry the removed row's key here, so
824
885
  -- a REMOVAL cannot file a misnamed tombstone. A tombstone with no
@@ -869,6 +930,7 @@ declare schema CadreControl {
869
930
  or (new.TableName = 'ValidationKey' and not exists (select 1 from ValidationKey V where V.StampId = new.StampId))
870
931
  or (new.TableName = 'Strand' and not exists (select 1 from Strand S where S.StampId = new.StampId))
871
932
  or (new.TableName = 'StrandPartyKey' and not exists (select 1 from StrandPartyKey K where K.StampId = new.StampId))
933
+ or (new.TableName = 'JoinedStrand' and not exists (select 1 from JoinedStrand J where J.StampId = new.StampId))
872
934
  or (new.TableName = 'DeviceToken' and not exists (select 1 from DeviceToken D where D.StampId = new.StampId))
873
935
  or (new.TableName = 'Revocation' and new.RowKey = 'ledger' and new.StampId = 'opened')
874
936
  ),
@@ -1 +1 @@
1
- {"version":3,"file":"control-schema.js","sourceRoot":"","sources":["../src/control-schema.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2BAm9BH,CAAC"}
@@ -13,7 +13,8 @@
13
13
  * deadline, write one frame, half-close, read one response, reset the stream on
14
14
  * any failure — so that shape lives here too, as {@link withDeadline} +
15
15
  * {@link exchangeFrame}; each protocol supplies only its dial options, its
16
- * request object, and its response decoder.
16
+ * request object, and its response decoder. The receiver's half — one reply
17
+ * frame, then close — is {@link replyAndClose}.
17
18
  *
18
19
  * Dependency-free by design: it imports nothing from the protocol modules, so
19
20
  * the import graph stays acyclic (`control-stream` ← `seed-bootstrap` ←
@@ -32,6 +33,13 @@ export interface ControlStream extends AsyncIterable<Uint8Array> {
32
33
  }
33
34
  /** Write a JSON object as a single 4-byte big-endian length-prefixed frame. */
34
35
  export declare function writeFrame(stream: ControlStream, obj: unknown): void;
36
+ /**
37
+ * Receiver side: write one reply frame and close the stream, best-effort on both and never
38
+ * throwing. A peer that has already gone away cannot be answered, and nothing the receiver
39
+ * decided depends on whether it heard. The close is what releases the sender, which reads the
40
+ * reply to end-of-stream ({@link exchangeFrame}).
41
+ */
42
+ export declare function replyAndClose(stream: ControlStream, reply: unknown, label: string): Promise<void>;
35
43
  /**
36
44
  * Reject if `op` does not settle within `ms`. On timeout, invoke `onTimeout`
37
45
  * before rejecting — a hook for releasing whatever the op is parked on. A
@@ -13,7 +13,8 @@
13
13
  * deadline, write one frame, half-close, read one response, reset the stream on
14
14
  * any failure — so that shape lives here too, as {@link withDeadline} +
15
15
  * {@link exchangeFrame}; each protocol supplies only its dial options, its
16
- * request object, and its response decoder.
16
+ * request object, and its response decoder. The receiver's half — one reply
17
+ * frame, then close — is {@link replyAndClose}.
17
18
  *
18
19
  * Dependency-free by design: it imports nothing from the protocol modules, so
19
20
  * the import graph stays acyclic (`control-stream` ← `seed-bootstrap` ←
@@ -21,6 +22,8 @@
21
22
  * {@link readStreamToEnd} rather than decoding a frame — callers own the
22
23
  * `decodeLengthPrefixedFrame` guard.
23
24
  */
25
+ import debug from 'debug';
26
+ const log = debug('sereus:cadre:control-stream');
24
27
  /** Write a JSON object as a single 4-byte big-endian length-prefixed frame. */
25
28
  export function writeFrame(stream, obj) {
26
29
  const body = new TextEncoder().encode(JSON.stringify(obj));
@@ -29,6 +32,26 @@ export function writeFrame(stream, obj) {
29
32
  stream.send(prefix);
30
33
  stream.send(body);
31
34
  }
35
+ /**
36
+ * Receiver side: write one reply frame and close the stream, best-effort on both and never
37
+ * throwing. A peer that has already gone away cannot be answered, and nothing the receiver
38
+ * decided depends on whether it heard. The close is what releases the sender, which reads the
39
+ * reply to end-of-stream ({@link exchangeFrame}).
40
+ */
41
+ export async function replyAndClose(stream, reply, label) {
42
+ try {
43
+ writeFrame(stream, reply);
44
+ }
45
+ catch (error) {
46
+ log('%s: failed to write reply: %o', label, error);
47
+ }
48
+ try {
49
+ await stream.close();
50
+ }
51
+ catch (error) {
52
+ log('%s: failed to close stream: %o', label, error);
53
+ }
54
+ }
32
55
  /**
33
56
  * Reject if `op` does not settle within `ms`. On timeout, invoke `onTimeout`
34
57
  * before rejecting — a hook for releasing whatever the op is parked on. A
@@ -1 +1 @@
1
- {"version":3,"file":"control-stream.js","sourceRoot":"","sources":["../src/control-stream.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAYH,+EAA+E;AAC/E,MAAM,UAAU,UAAU,CAAC,MAAqB,EAAE,GAAY;IAC5D,MAAM,IAAI,GAAG,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC;IAC3D,MAAM,MAAM,GAAG,IAAI,UAA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MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC;QAC7B,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACnB,KAAK,IAAI,KAAK,CAAC,MAAM,CAAC;QACtB,IAAI,KAAK,GAAG,QAAQ,EAAE,CAAC;YACrB,MAAM,IAAI,KAAK,CAAC,GAAG,KAAK,uBAAuB,KAAK,sBAAsB,QAAQ,EAAE,CAAC,CAAC;QACxF,CAAC;IACH,CAAC;IAED,MAAM,IAAI,GAAG,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC;IACnC,IAAI,MAAM,GAAG,CAAC,CAAC;IACf,KAAK,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;QAC3B,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QACxB,MAAM,IAAI,KAAK,CAAC,MAAM,CAAC;IACzB,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC"}
@@ -70,11 +70,21 @@ export declare const SCHEMA_INIT_ATTEMPTS = 5;
70
70
  * This budget — not the attempt count — is what makes the policy safe to sit under every
71
71
  * control write. A transient failure (stream reset while a connection is still forming)
72
72
  * surfaces in well under a second, so it is retried and the loop adds at most ~2.2 s. A
73
- * genuinely silent cohort member fails at ~20 s (two 10 s `ClusterClient` response-deadline
74
- * attempts, measured in `control-write-degraded-cohort-member.integration.ts`), which
73
+ * genuinely silent cohort member fails at ~21 s per pend round (two `ClusterClient`
74
+ * response-deadline attempts, 10.5 s each at the default declared link; a two-round write
75
+ * measured 42.2 s in `control-write-degraded-cohort-member.integration.ts`), which
75
76
  * already exceeds this budget when attempt 1 returns — so that case is surfaced immediately
76
77
  * and retry adds ZERO latency to the case where it cannot help.
77
78
  *
79
+ * It cuts the loop off by design, so it does not grow with the link: its job is to end the
80
+ * retries of slow attempts, and the caller gets the last attempt's error unchanged. An attempt
81
+ * whose read phase consulted a silent peer ends at about one per-peer read deadline
82
+ * (`cohortReadDeadlineMs` in `link-budget.ts`: 7 s at the default declared link, 5 s before it
83
+ * was derived, 1 s at Optimystic's own default), so it still gets one retry inside this budget
84
+ * where it once got two; an attempt that runs into the `ClusterClient` response deadline
85
+ * (10.5 s at the default declared link) still gets none. See `docs/cadre-consistency.md` →
86
+ * "Deadlines Over Optimystic's Reads and Commits".
87
+ *
78
88
  * NOTE: a failed commit attempt now also pays a cancel discharge before its error returns
79
89
  * (optimystic `TransactorSource.transact`'s catch, added by upstream
80
90
  * `1-a-failed-attempt-must-discharge-its-own-pend`) — bounded by six rounds and