@941design/marmot 0.0.0-stage → 0.2.0-alpha.1

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 (206) hide show
  1. package/CHANGELOG.md +739 -0
  2. package/LICENSE +21 -0
  3. package/README.md +33 -2
  4. package/dist/account/admin.d.ts +72 -0
  5. package/dist/account/admin.js +209 -0
  6. package/dist/account/device-deps.d.ts +379 -0
  7. package/dist/account/device-deps.js +36 -0
  8. package/dist/account/device-lineage.d.ts +199 -0
  9. package/dist/account/device-lineage.js +390 -0
  10. package/dist/account/device-registry.d.ts +93 -0
  11. package/dist/account/device-registry.js +1290 -0
  12. package/dist/account/device-rotation.d.ts +61 -0
  13. package/dist/account/device-rotation.js +827 -0
  14. package/dist/account/enrolment.d.ts +339 -0
  15. package/dist/account/enrolment.js +1247 -0
  16. package/dist/account/identity-proof.d.ts +79 -0
  17. package/dist/account/identity-proof.js +264 -0
  18. package/dist/account/index.d.ts +17 -0
  19. package/dist/account/index.js +16 -0
  20. package/dist/account/restore-rotation.d.ts +21 -0
  21. package/dist/account/restore-rotation.js +22 -0
  22. package/dist/account/same-account-authorization.d.ts +86 -0
  23. package/dist/account/same-account-authorization.js +180 -0
  24. package/dist/account/teardown.d.ts +190 -0
  25. package/dist/account/teardown.js +878 -0
  26. package/dist/client/admission-cleanup.d.ts +197 -0
  27. package/dist/client/admission-cleanup.js +635 -0
  28. package/dist/client/adoption-proof.d.ts +39 -0
  29. package/dist/client/adoption-proof.js +102 -0
  30. package/dist/client/before-create-group.d.ts +18 -0
  31. package/dist/client/before-create-group.js +65 -0
  32. package/dist/client/before-publish-hooks.d.ts +121 -0
  33. package/dist/client/before-publish-hooks.js +182 -0
  34. package/dist/client/client-config.d.ts +42 -0
  35. package/dist/client/client-config.js +13 -0
  36. package/dist/client/commit-redrive.d.ts +92 -0
  37. package/dist/client/commit-redrive.js +274 -0
  38. package/dist/client/component-update.d.ts +43 -0
  39. package/dist/client/component-update.js +53 -0
  40. package/dist/client/confirm-hooks.d.ts +55 -0
  41. package/dist/client/confirm-hooks.js +74 -0
  42. package/dist/client/create-client.d.ts +1126 -0
  43. package/dist/client/create-client.js +1232 -0
  44. package/dist/client/group-availability.d.ts +182 -0
  45. package/dist/client/group-availability.js +301 -0
  46. package/dist/client/group-disband.d.ts +28 -0
  47. package/dist/client/group-disband.js +64 -0
  48. package/dist/client/group-history.d.ts +461 -0
  49. package/dist/client/group-history.js +1365 -0
  50. package/dist/client/group-profile.d.ts +31 -0
  51. package/dist/client/group-profile.js +62 -0
  52. package/dist/client/group-records.d.ts +522 -0
  53. package/dist/client/group-records.js +1117 -0
  54. package/dist/client/group-removal.d.ts +36 -0
  55. package/dist/client/group-removal.js +127 -0
  56. package/dist/client/group-remove-member.d.ts +49 -0
  57. package/dist/client/group-remove-member.js +163 -0
  58. package/dist/client/group-runtime.d.ts +415 -0
  59. package/dist/client/group-runtime.js +2811 -0
  60. package/dist/client/group-snapshot.d.ts +104 -0
  61. package/dist/client/group-snapshot.js +474 -0
  62. package/dist/client/history-pages.d.ts +107 -0
  63. package/dist/client/history-pages.js +194 -0
  64. package/dist/client/inbox-send.d.ts +19 -0
  65. package/dist/client/inbox-send.js +71 -0
  66. package/dist/client/index.d.ts +24 -0
  67. package/dist/client/index.js +13 -0
  68. package/dist/client/ingest.d.ts +82 -0
  69. package/dist/client/ingest.js +1584 -0
  70. package/dist/client/invitation-outcomes.d.ts +50 -0
  71. package/dist/client/invitation-outcomes.js +135 -0
  72. package/dist/client/lifecycle-events.d.ts +63 -0
  73. package/dist/client/lifecycle-events.js +35 -0
  74. package/dist/client/opaque-candidates.d.ts +82 -0
  75. package/dist/client/opaque-candidates.js +170 -0
  76. package/dist/client/own-change-outbox.d.ts +66 -0
  77. package/dist/client/own-change-outbox.js +158 -0
  78. package/dist/client/pending-leaf.d.ts +116 -0
  79. package/dist/client/pending-leaf.js +378 -0
  80. package/dist/client/permissions.d.ts +9 -0
  81. package/dist/client/permissions.js +12 -0
  82. package/dist/client/pipeline.d.ts +583 -0
  83. package/dist/client/pipeline.js +3666 -0
  84. package/dist/client/reentrancy-guard.d.ts +102 -0
  85. package/dist/client/reentrancy-guard.js +159 -0
  86. package/dist/client/rekey.d.ts +58 -0
  87. package/dist/client/rekey.js +149 -0
  88. package/dist/client/transport-policy.d.ts +181 -0
  89. package/dist/client/transport-policy.js +214 -0
  90. package/dist/history/admission-lineage.d.ts +186 -0
  91. package/dist/history/admission-lineage.js +589 -0
  92. package/dist/history/equivocation.d.ts +55 -0
  93. package/dist/history/equivocation.js +113 -0
  94. package/dist/history/fencing.d.ts +66 -0
  95. package/dist/history/fencing.js +121 -0
  96. package/dist/history/hex.d.ts +3 -0
  97. package/dist/history/hex.js +10 -0
  98. package/dist/history/index.d.ts +74 -0
  99. package/dist/history/index.js +32 -0
  100. package/dist/history/notifications.d.ts +270 -0
  101. package/dist/history/notifications.js +264 -0
  102. package/dist/history/ordering-key.d.ts +24 -0
  103. package/dist/history/ordering-key.js +101 -0
  104. package/dist/history/own-change-fork.d.ts +112 -0
  105. package/dist/history/own-change-fork.js +196 -0
  106. package/dist/history/own-change.d.ts +118 -0
  107. package/dist/history/own-change.js +146 -0
  108. package/dist/history/policy.d.ts +48 -0
  109. package/dist/history/policy.js +52 -0
  110. package/dist/history/retained-window.d.ts +215 -0
  111. package/dist/history/retained-window.js +565 -0
  112. package/dist/inbox/demux.d.ts +90 -0
  113. package/dist/inbox/demux.js +78 -0
  114. package/dist/inbox/handler-registry.d.ts +42 -0
  115. package/dist/inbox/handler-registry.js +37 -0
  116. package/dist/inbox/index.d.ts +11 -0
  117. package/dist/inbox/index.js +10 -0
  118. package/dist/inbox/seen-set.d.ts +82 -0
  119. package/dist/inbox/seen-set.js +202 -0
  120. package/dist/inbox/subscription.d.ts +236 -0
  121. package/dist/inbox/subscription.js +644 -0
  122. package/dist/index.d.ts +10 -0
  123. package/dist/index.js +9 -0
  124. package/dist/invitations/competing-welcome.d.ts +223 -0
  125. package/dist/invitations/competing-welcome.js +128 -0
  126. package/dist/invitations/decline.d.ts +67 -0
  127. package/dist/invitations/decline.js +149 -0
  128. package/dist/invitations/delivery-evidence.d.ts +288 -0
  129. package/dist/invitations/delivery-evidence.js +766 -0
  130. package/dist/invitations/expect-welcome.d.ts +66 -0
  131. package/dist/invitations/expect-welcome.js +138 -0
  132. package/dist/invitations/index.d.ts +18 -0
  133. package/dist/invitations/index.js +18 -0
  134. package/dist/invitations/invitation-outcome.d.ts +110 -0
  135. package/dist/invitations/invitation-outcome.js +210 -0
  136. package/dist/invitations/invite.d.ts +358 -0
  137. package/dist/invitations/invite.js +1102 -0
  138. package/dist/invitations/offers.d.ts +79 -0
  139. package/dist/invitations/offers.js +115 -0
  140. package/dist/invitations/on-proposal.d.ts +47 -0
  141. package/dist/invitations/on-proposal.js +40 -0
  142. package/dist/invitations/pending-proposal-policy.d.ts +52 -0
  143. package/dist/invitations/pending-proposal-policy.js +139 -0
  144. package/dist/invitations/proposal-deadline.d.ts +133 -0
  145. package/dist/invitations/proposal-deadline.js +164 -0
  146. package/dist/invitations/relay-planes.d.ts +43 -0
  147. package/dist/invitations/relay-planes.js +70 -0
  148. package/dist/invitations/welcome-processor.d.ts +272 -0
  149. package/dist/invitations/welcome-processor.js +1241 -0
  150. package/dist/key-packages/device-key.d.ts +131 -0
  151. package/dist/key-packages/device-key.js +272 -0
  152. package/dist/key-packages/device-rotation-records.d.ts +83 -0
  153. package/dist/key-packages/device-rotation-records.js +173 -0
  154. package/dist/key-packages/group-refs.d.ts +40 -0
  155. package/dist/key-packages/group-refs.js +79 -0
  156. package/dist/key-packages/index.d.ts +18 -0
  157. package/dist/key-packages/index.js +18 -0
  158. package/dist/key-packages/key-package-ref.d.ts +16 -0
  159. package/dist/key-packages/key-package-ref.js +21 -0
  160. package/dist/key-packages/observation-stream.d.ts +4 -0
  161. package/dist/key-packages/observation-stream.js +120 -0
  162. package/dist/key-packages/offer-rumor.d.ts +26 -0
  163. package/dist/key-packages/offer-rumor.js +69 -0
  164. package/dist/key-packages/publisher.d.ts +174 -0
  165. package/dist/key-packages/publisher.js +1247 -0
  166. package/dist/key-packages/select-key-package.d.ts +24 -0
  167. package/dist/key-packages/select-key-package.js +90 -0
  168. package/dist/key-packages/slot-manager.d.ts +167 -0
  169. package/dist/key-packages/slot-manager.js +327 -0
  170. package/dist/key-packages/validate-key-package-event.d.ts +3 -0
  171. package/dist/key-packages/validate-key-package-event.js +49 -0
  172. package/dist/media/cache.d.ts +14 -0
  173. package/dist/media/cache.js +10 -0
  174. package/dist/media/index.d.ts +52 -0
  175. package/dist/media/index.js +71 -0
  176. package/dist/mls.d.ts +15 -0
  177. package/dist/mls.js +15 -0
  178. package/dist/shared/account-pubkey.d.ts +4 -0
  179. package/dist/shared/account-pubkey.js +10 -0
  180. package/dist/shared/errors.d.ts +28 -0
  181. package/dist/shared/errors.js +96 -0
  182. package/dist/shared/hex.d.ts +4 -0
  183. package/dist/shared/hex.js +13 -0
  184. package/dist/shared/index.d.ts +14 -0
  185. package/dist/shared/index.js +14 -0
  186. package/dist/shared/kinds.d.ts +8 -0
  187. package/dist/shared/kinds.js +28 -0
  188. package/dist/shared/publish-classification.d.ts +26 -0
  189. package/dist/shared/publish-classification.js +31 -0
  190. package/dist/storage/envelope.d.ts +39 -0
  191. package/dist/storage/envelope.js +201 -0
  192. package/dist/storage/index.d.ts +237 -0
  193. package/dist/storage/index.js +491 -0
  194. package/dist/storage/indexeddb/idb-types.d.ts +68 -0
  195. package/dist/storage/indexeddb/idb-types.js +1 -0
  196. package/dist/storage/indexeddb/index.d.ts +17 -0
  197. package/dist/storage/indexeddb/index.js +141 -0
  198. package/dist/storage/lease.d.ts +54 -0
  199. package/dist/storage/lease.js +168 -0
  200. package/dist/storage/memory/deterministic-signer.d.ts +27 -0
  201. package/dist/storage/memory/deterministic-signer.js +65 -0
  202. package/dist/storage/memory/index.d.ts +32 -0
  203. package/dist/storage/memory/index.js +87 -0
  204. package/dist/storage/memory/lock-manager.d.ts +8 -0
  205. package/dist/storage/memory/lock-manager.js +71 -0
  206. package/package.json +66 -3
@@ -0,0 +1,635 @@
1
+ /**
2
+ * Cleanup disposition — the read side (epic marmot-invitation-outcomes S4; ADR-019 D1, D4; architecture SC-3 I9–I9c,
3
+ * SC-9, SC-12).
4
+ *
5
+ * `invitations.cleanupDisposition(ref)` answers, for the scoped cleanup reference of one decline candidate, what the
6
+ * durable evidence of this store proves about the admission that delivery made:
7
+ *
8
+ * - `insufficient-evidence` / `unresolved-selector` or `ambiguous-legacy` — the candidate is ambiguous (an
9
+ * unqualified or pre-upgrade decline of a Welcome several KeyPackages of the account received);
10
+ * - `insufficient-evidence` / `no-anchor` — actionable, but neither the delivery's Add anchor nor a lazy resolution of
11
+ * its retained invite commit (I9b) names the admission;
12
+ * - `insufficient-evidence` / `lineage-gap` — the admission's lineage cannot be proven on the selected path (AR-6:
13
+ * fail closed — never a false present);
14
+ * - `absent` / `add-off-path` or `occupancy-ended` — the Add is not on the selected path, or the admission ended;
15
+ * - `eligible` — the proven original admission is present.
16
+ *
17
+ * The read is pure over one instant of durable state (the reader-transaction rule): one read-only group transaction
18
+ * (window, state, fence marker, lineage) awaiting one read-only account transaction (evidence), both write-free; no
19
+ * runtime, no queue, no publication, no intent. On a fenced group it reports the stored (last-known) disposition,
20
+ * which no longer advances (`lastKnown`). A reference confers no authority: it is decoded, checked against the
21
+ * signer's account (I9c) and resolved against the evidence on every read.
22
+ *
23
+ * Owned by hunk (stories.json): S4 owns the read side here — {@link cleanupDispositionOf} with an empty ledger input,
24
+ * {@link readCleanupDisposition}, {@link resolveLegacyAnchor}; S5 adds the cleanup ledger ({@link CleanupLedgerEntry}, SC-5),
25
+ * {@link matchingCleanupRecord} (I15a), the `pending` / `removed-*` dispositions, the removal ladder
26
+ * ({@link removeAdmissionIntent}, SC-11), the confirm-time ledger write and the best-effort `cleanupDisposition` event.
27
+ *
28
+ * Attribution (I14): `removed-revisable` / `removed-settled` only when the selected path ends the admission at a commit this
29
+ * candidate's ledger confirmed AND that end is an inline Remove; a by-reference or replaced end is `absent`, never attributed.
30
+ * `removed-settled` once `REWIND_HORIZON` later commits follow it on the selected path, i.e. the Remove has left the retained window (or its end was carried out of the
31
+ * window by a checkpoint of `transition` provenance); a proof that starts at an imported snapshot checkpoint is never settled.
32
+ */
33
+ import { deserializeClientState, getCredentialPubkey, getMarmotGroupView, getPubkeyLeafNodeIndexes, GROUP_ADMIN_POLICY_COMPONENT_ID } from '@941design/marmot-engine/core';
34
+ import { contentTypes, decode, defaultProposalTypes, mlsMessageDecoder, nodeTypes, proposalOrRefTypes, wireformats } from '@941design/marmot-engine/mls';
35
+ import { ADMISSION_LINEAGE_EXTENSION, commitOf, deriveAdmission, FENCE_EXTENSION, lineageKey, linkRestorable, loadFenceMarker, readLineageRecord, readLineageRecords, readWindow, REWIND_HORIZON, seedLineageRecords, tagOf, windowFor, } from '../history/index.js';
36
+ import { addAnchorsOf, candidateIdOf, cleanupCandidateExists, cleanupCandidateOf, decodeCleanupReference } from '../invitations/index.js';
37
+ import { computeKeyPackageRefHex } from '../key-packages/index.js';
38
+ import { isActiveAdmin } from '../account/index.js';
39
+ import { isMalformedRowError, isMarmotError, MarmotError } from '../shared/index.js';
40
+ import { cleanupTargetRefusal, stagedCleanupConflict } from './commit-redrive.js';
41
+ import { stagesComponentUpdate } from './component-update.js';
42
+ import { assertNotDisbanded } from './group-disband.js';
43
+ import { assertNotFenced } from './group-history.js';
44
+ import { decodeAdmissionTarget, encodeAdmissionTarget, listPendingIntentRecords, readGroupState, } from './group-records.js';
45
+ import { applyProposalPolicy, assertLocalAdmin, assertMember, assertNoOwnCommitPending, assertNotDisposed, assertSendGateOpen, callSignerForGroup, preflight, recordIntent, resumePendingInBackground, } from './pipeline.js';
46
+ import { RECOVERY_READ_INBOX_SURFACES } from './invitation-outcomes.js';
47
+ import { ACCOUNT_SCOPE, GROUP_CONSUMER_SURFACES } from './reentrancy-guard.js';
48
+ // ---------------------------------------------------------------------------
49
+ // AddAnchor → LineageAnchor (SC-1 I3: client maps between the two)
50
+ // ---------------------------------------------------------------------------
51
+ export function lineageAnchorOf(anchor) {
52
+ return { addDigest: anchor.addDigest, addTag: anchor.addTag, commitEventId: anchor.commitEventId, leafIndex: anchor.leafIndex, leafKey: anchor.leafKey };
53
+ }
54
+ /**
55
+ * The lineage seeds of one confirmed invite commit: its anchors (by KeyPackageRef) grouped by lineage key, each with
56
+ * the candidates (deliveries of invite `inviteId`) it admitted.
57
+ */
58
+ export function lineageSeedsOf(groupId, inviteId, anchors) {
59
+ const seeds = new Map();
60
+ for (const [inviteeRef, addAnchor] of anchors) {
61
+ const anchor = lineageAnchorOf(addAnchor);
62
+ const key = lineageKey(anchor);
63
+ const seed = seeds.get(key) ?? { anchor, candidateIds: [] };
64
+ seed.candidateIds.push(candidateIdOf(groupId, inviteId, inviteeRef));
65
+ seeds.set(key, seed);
66
+ }
67
+ return seeds;
68
+ }
69
+ /** Group extension holding one {@link CleanupLedgerEntry} per candidate, keyed by `candidateId`. */
70
+ export const ADMISSION_CLEANUP_EXTENSION = 'marmot.admission-cleanup';
71
+ function malformedEntry(key) {
72
+ return (detail) => new MarmotError('store-failed', `${ADMISSION_CLEANUP_EXTENSION}/${key}: malformed record (${detail})`, { details: { key, malformed: true } });
73
+ }
74
+ const isHex = (v) => typeof v === 'string' && v.length > 0 && v.length % 2 === 0 && /^[0-9a-f]+$/.test(v);
75
+ /** Strict decoder of the ledger row `key` (its candidate id). */
76
+ export function decodeCleanupLedgerEntry(key, raw) {
77
+ const fail = malformedEntry(key);
78
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
79
+ throw fail('record not an object');
80
+ const r = raw;
81
+ for (const k of Object.keys(r))
82
+ if (r[k] !== undefined && !['v', 'rootIntentId', 'target', 'confirmed'].includes(k))
83
+ throw fail(`${k} not allowed`);
84
+ if (r['v'] !== 1)
85
+ throw fail('v mismatch');
86
+ if (typeof r['rootIntentId'] !== 'string' || r['rootIntentId'].length === 0)
87
+ throw fail('rootIntentId invalid');
88
+ const target = decodeAdmissionTarget(r['target'], 'target', fail);
89
+ if (target.candidateId !== key)
90
+ throw fail('target names another candidate');
91
+ const confirmed = r['confirmed'];
92
+ if (!Array.isArray(confirmed))
93
+ throw fail('confirmed invalid');
94
+ const out = confirmed.map((c) => {
95
+ if (typeof c !== 'object' || c === null)
96
+ throw fail('confirmed entry invalid');
97
+ const { digest, tag, ...rest } = c;
98
+ if (Object.keys(rest).length > 0 || !isHex(digest) || !isHex(tag))
99
+ throw fail('confirmed entry invalid');
100
+ return { digest, tag };
101
+ });
102
+ if (new Set(out.map((c) => c.digest)).size !== out.length)
103
+ throw fail('confirmed digest repeated');
104
+ return { v: 1, rootIntentId: r['rootIntentId'], target, confirmed: out };
105
+ }
106
+ export function encodeCleanupLedgerEntry(entry) {
107
+ const fail = malformedEntry(entry.target.candidateId);
108
+ const raw = {
109
+ v: 1,
110
+ rootIntentId: entry.rootIntentId,
111
+ target: encodeAdmissionTarget(entry.target, fail),
112
+ confirmed: entry.confirmed.map((c) => ({ digest: c.digest, tag: c.tag })),
113
+ };
114
+ decodeCleanupLedgerEntry(entry.target.candidateId, raw);
115
+ return raw;
116
+ }
117
+ /**
118
+ * The ledger entry of `candidateId`, or `undefined`. A row that does not decode reads as none: no entry means no attribution and
119
+ * no in-flight root, which only ever makes the disposition LESS positive (fail closed); any other read error propagates.
120
+ */
121
+ export async function readCleanupLedgerEntry(view, candidateId) {
122
+ const raw = await view.get(candidateId);
123
+ if (raw === undefined)
124
+ return undefined;
125
+ try {
126
+ return decodeCleanupLedgerEntry(candidateId, raw);
127
+ }
128
+ catch (error) {
129
+ if (isMalformedRowError(error))
130
+ return undefined;
131
+ throw error;
132
+ }
133
+ }
134
+ export async function writeCleanupLedgerEntry(view, entry) {
135
+ await view.put(entry.target.candidateId, encodeCleanupLedgerEntry(entry));
136
+ }
137
+ /** The cleanup target a pending record drives: an original's intent target, or a re-drive's (not yet lost) `admission-removed` change's. */
138
+ export function cleanupTargetOf(record) {
139
+ if (record.intent.type === 'commit' && record.intent.removeAdmission !== undefined)
140
+ return record.intent.removeAdmission;
141
+ const change = record.changes?.find((c) => c.change.type === 'admission-removed' && (c.verdict === undefined || c.verdict === 'reapplied'));
142
+ return change?.target;
143
+ }
144
+ /**
145
+ * I15a — the ONLY definition of "a cleanup for `cid` is in flight": the first `pendingIntents` record (in `records`' order, `seq`)
146
+ * that is (original) a `commit` record whose intent's `removeAdmission` names `cid`, in any state (`pending-confirm` included), or
147
+ * (re-drive) a record re-enqueued from the entry's root whose `changes` hold an `admission-removed` change of `cid`. Without an entry
148
+ * (none written yet, or a row that did not decode) a re-drive record naming `cid` still matches: coalescing never removes twice.
149
+ */
150
+ export function matchingCleanupRecord(records, entry, cid) {
151
+ return records.find((r) => (r.kind === 'commit' && r.intent.type === 'commit' && r.intent.removeAdmission?.candidateId === cid) ||
152
+ ((entry === undefined || r.reenqueuedFrom === entry.rootIntentId) && r.reenqueuedFrom !== undefined && (r.changes ?? []).some((c) => c.change.type === 'admission-removed' && c.change.candidateId === cid)));
153
+ }
154
+ /** The root intent id a matching record reports under: the entry's root, else the record's own root. */
155
+ function inFlightRootOf(record, entry) {
156
+ return entry?.rootIntentId ?? record.reenqueuedFrom ?? record.intentId;
157
+ }
158
+ /**
159
+ * SC-3 I9a: the disposition as a pure function of durable evidence and lineage. A cleanup in flight (I15a) is `pending`
160
+ * under its root intent id, whatever else holds (S5). An ambiguous candidate is insufficient evidence (`ambiguous-legacy`
161
+ * when only a pre-upgrade decline covers it, else `unresolved-selector`); an actionable one without an anchor is
162
+ * `no-anchor`; otherwise the admission's occupancy decides — `occupying` → `eligible`, `ended` → `removed-revisable` /
163
+ * `removed-settled` when the end is this candidate's own confirmed INLINE Remove (I14), else `absent`
164
+ * (`occupancy-ended`), `add-off-path` → `absent`, a `gap` → `lineage-gap`.
165
+ */
166
+ export function cleanupDispositionOf(input) {
167
+ const base = { groupId: input.groupId, candidateId: input.candidate.candidateId, lastKnown: input.lastKnown };
168
+ const insufficient = (cause) => ({ ...base, disposition: 'insufficient-evidence', cause });
169
+ if (input.inFlight !== undefined)
170
+ return { groupId: base.groupId, candidateId: base.candidateId, intentId: input.inFlight.intentId, disposition: 'pending', lastKnown: base.lastKnown };
171
+ if (input.candidate.status !== 'actionable')
172
+ return insufficient(input.candidate.basis === 'legacy' ? 'ambiguous-legacy' : 'unresolved-selector');
173
+ if (input.anchor === undefined || input.admission === undefined)
174
+ return insufficient('no-anchor');
175
+ const occupancy = input.admission.occupancy;
176
+ switch (occupancy.kind) {
177
+ case 'occupying':
178
+ return { ...base, disposition: 'eligible' };
179
+ case 'ended': {
180
+ const entry = input.ledger.find((e) => e.target.candidateId === input.candidate.candidateId);
181
+ if (entry !== undefined && occupancy.by === 'inline-remove' && entry.confirmed.some((c) => c.digest === occupancy.digest)) {
182
+ // Decision 4: settled once ordinary branch selection can no longer withdraw it — REWIND_HORIZON later commits follow the
183
+ // Remove on the selected path (the Remove has left the retained window), or its end left the window in a checkpoint this store derived from transitions. A proof
184
+ // resting on an imported snapshot checkpoint is never settled (it must be re-proven first).
185
+ const depth = input.admission.endedDepth;
186
+ const settled = input.admission.provenance === 'transition' && (depth === undefined || depth >= REWIND_HORIZON);
187
+ return {
188
+ groupId: base.groupId,
189
+ candidateId: base.candidateId,
190
+ intentId: entry.rootIntentId,
191
+ disposition: settled ? 'removed-settled' : 'removed-revisable',
192
+ commitDigest: occupancy.digest,
193
+ lastKnown: base.lastKnown,
194
+ };
195
+ }
196
+ return { ...base, disposition: 'absent', cause: 'occupancy-ended' };
197
+ }
198
+ case 'add-off-path':
199
+ return { ...base, disposition: 'absent', cause: 'add-off-path' };
200
+ case 'gap':
201
+ return insufficient('lineage-gap');
202
+ }
203
+ }
204
+ // ---------------------------------------------------------------------------
205
+ // Lazy legacy anchor resolution (SC-3 I9b)
206
+ // ---------------------------------------------------------------------------
207
+ function stateOfNode(window, tipState, tag) {
208
+ if (tag === window.tipTag)
209
+ return tipState;
210
+ const snapshot = window.nodes.get(tag)?.snapshot;
211
+ if (snapshot === undefined)
212
+ return undefined;
213
+ try {
214
+ return deserializeClientState(snapshot);
215
+ }
216
+ catch {
217
+ return undefined;
218
+ }
219
+ }
220
+ /**
221
+ * I9b: the anchor of a delivery recorded without one (a pre-upgrade or unanchorable delivery), found in the retained
222
+ * window. Succeeds only when the invite commit's node (`commitTag`) is still in the window with its link, its commit
223
+ * decodes as a framed PublicMessage commit, exactly one Add carried by value in it holds a KeyPackage whose ref is
224
+ * `inviteeRef`, and that KeyPackage's leaf is the unique new KeyPackage-sourced leaf of the commit's state (SC-1 I1).
225
+ * A pruned, absent, undecodable or by-reference commit, or zero or several matching Adds: `undefined` (`no-anchor`).
226
+ * Never throws.
227
+ */
228
+ export async function resolveLegacyAnchor(input) {
229
+ try {
230
+ const node = input.window.nodes.get(input.commitTag);
231
+ if (node?.parentTag === undefined || node.digest === undefined || !linkRestorable(node))
232
+ return undefined;
233
+ const commit = commitOf(node);
234
+ if (commit === undefined || commit.message.wireformat !== wireformats.mls_public_message)
235
+ return undefined;
236
+ const content = commit.message.publicMessage.content;
237
+ if (content.contentType !== contentTypes.commit)
238
+ return undefined;
239
+ const parentState = stateOfNode(input.window, input.tipState, node.parentTag);
240
+ const newState = stateOfNode(input.window, input.tipState, node.tag);
241
+ if (parentState === undefined || newState === undefined)
242
+ return undefined;
243
+ const matching = [];
244
+ for (const entry of content.commit.proposals) {
245
+ if (entry.proposalOrRefType !== proposalOrRefTypes.proposal || entry.proposal.proposalType !== defaultProposalTypes.add || !('add' in entry.proposal))
246
+ continue;
247
+ let ref;
248
+ try {
249
+ ref = await computeKeyPackageRefHex(entry.proposal.add.keyPackage);
250
+ }
251
+ catch {
252
+ continue;
253
+ }
254
+ if (ref === input.inviteeRef)
255
+ matching.push(entry.proposal.add.keyPackage);
256
+ }
257
+ if (matching.length !== 1)
258
+ return undefined;
259
+ const anchors = await addAnchorsOf({ parentState, newState, addDigest: node.digest, addTag: node.tag, commitEventId: input.commitEventId, keyPackages: matching });
260
+ const anchor = anchors.get(input.inviteeRef);
261
+ return anchor === undefined ? undefined : lineageAnchorOf(anchor);
262
+ }
263
+ catch {
264
+ return undefined;
265
+ }
266
+ }
267
+ // ---------------------------------------------------------------------------
268
+ // The reader (SC-9 guard, reader-transaction rule)
269
+ // ---------------------------------------------------------------------------
270
+ const OPERATION = 'invitations.cleanupDisposition';
271
+ function refuse(scope, surface) {
272
+ return new MarmotError('reentrant', `${OPERATION}: re-entrant call from inside ${surface} (scope ${JSON.stringify(scope)}); read it from an event listener instead`, {
273
+ details: { scope, operation: OPERATION, surface },
274
+ });
275
+ }
276
+ /**
277
+ * SC-9 for `invitations.cleanupDisposition`, evaluated synchronously: `reentrant` (naming the surface) inside any live
278
+ * account-scope frame other than an inbox surface (store, signer, verifier, …: the read's account transaction would
279
+ * queue behind it), inside a group-scope `onConfirm` / `onBeforePublish` / `verifier` / `onProposal` frame (its group
280
+ * transaction is open), or inside a group-scope consumer `store` frame. An inbox handler or `onApplicationRumor` frame
281
+ * holds no store transaction: the read proceeds from it, as from an event listener.
282
+ */
283
+ export function assertCleanupDispositionAllowed(guard) {
284
+ try {
285
+ guard.assertNotReentrant(ACCOUNT_SCOPE, OPERATION);
286
+ }
287
+ catch (error) {
288
+ const surface = isMarmotError(error, 'reentrant') ? error.details?.['surface'] : undefined;
289
+ if (typeof surface !== 'string' || !RECOVERY_READ_INBOX_SURFACES.includes(surface))
290
+ throw error;
291
+ }
292
+ for (const surface of GROUP_CONSUMER_SURFACES) {
293
+ const frame = guard.withinGroupScope(surface);
294
+ if (frame !== undefined)
295
+ throw refuse(frame.scope, surface);
296
+ }
297
+ const store = guard.withinGroupScope('store');
298
+ if (store !== undefined)
299
+ throw refuse(store.scope, 'store');
300
+ }
301
+ function invalidReference(reason, message, details = {}) {
302
+ return new MarmotError('invalid-options', `${OPERATION}: ${message}`, { details: { reason, ...details } });
303
+ }
304
+ /** The stored tip state, `undefined` when none — or when it does not open (no state proves nothing). */
305
+ async function readTipState(view) {
306
+ try {
307
+ return await readGroupState(view);
308
+ }
309
+ catch (error) {
310
+ if (isMalformedRowError(error))
311
+ return undefined;
312
+ throw error;
313
+ }
314
+ }
315
+ /**
316
+ * `invitations.cleanupDisposition(ref)`. The guard runs synchronously (a refused call returns an already rejected
317
+ * promise, before any store access). Then: a reference that does not decode → `invalid-options`
318
+ * `malformed-reference`; one of another account than the signer's → `foreign-reference` (I9c: the reference's
319
+ * account part is never trusted as authority); one naming no candidate of this store (an unknown or purged group
320
+ * included) → `unknown-reference`. None of them reads a group store, writes, publishes or resumes anything.
321
+ */
322
+ export function readCleanupDisposition(deps, ref) {
323
+ try {
324
+ assertCleanupDispositionAllowed(deps.guard);
325
+ }
326
+ catch (error) {
327
+ return Promise.reject(error);
328
+ }
329
+ const decoded = decodeCleanupReference(ref);
330
+ if (decoded === undefined)
331
+ return Promise.reject(invalidReference('malformed-reference', 'not a cleanup reference'));
332
+ const { guard } = deps;
333
+ const { groupId, candidateId } = decoded;
334
+ return (async () => {
335
+ const account = await deps.accountKey();
336
+ if (decoded.account !== account)
337
+ throw invalidReference('foreign-reference', 'the reference names another account', { groupId });
338
+ // Routing: an unknown reference never opens a group store. Existence only — the candidate itself (a covered one's
339
+ // set included) is resolved once, inside the one-instant read below, since the evidence may change in between.
340
+ const routed = await guard.call(ACCOUNT_SCOPE, 'store', () => deps.account.transaction((tx) => cleanupCandidateExists(tx, { groupId, candidateId })));
341
+ if (!routed)
342
+ throw invalidReference('unknown-reference', 'no decline candidate of this store has that reference', { groupId, candidateId });
343
+ return (await deriveCleanupDisposition(deps, { account, groupId, candidateId })).report;
344
+ })();
345
+ }
346
+ /**
347
+ * The one-instant read behind {@link readCleanupDisposition} and the ladder's D3 (G9: the same derivation, so a submit's report equals
348
+ * the read's): one read-only group transaction (window, state, fence marker, lineage, the candidate's ledger entry, `pendingIntents`)
349
+ * awaiting one read-only account transaction (evidence); the derivation is pure, after both closed. `unknown-reference` when the
350
+ * evidence names no candidate. Runs no guard check of its own (the callers did).
351
+ */
352
+ export async function deriveCleanupDisposition(deps, scope) {
353
+ const { guard } = deps;
354
+ const { account, groupId, candidateId } = scope;
355
+ // One instant: the group's rows in a read-only group transaction that awaits the account's (group → account).
356
+ const store = deps.groupStore(groupId);
357
+ const read = await guard.call(groupId, 'store', () => store.transaction(async (gtx) => {
358
+ const stored = await readWindow(gtx.artifact('rewindTree'));
359
+ const tip = await readTipState(gtx.artifact('clientState'));
360
+ const fence = await loadFenceMarker(gtx.extension(FENCE_EXTENSION));
361
+ const entry = await readCleanupLedgerEntry(gtx.extension(ADMISSION_CLEANUP_EXTENSION), candidateId);
362
+ const records = await listPendingIntentRecords(gtx.artifact('pendingIntents'));
363
+ const evidence = await guard.call(ACCOUNT_SCOPE, 'store', () => deps.account.transaction((tx) => cleanupCandidateOf(tx, { account, groupId, candidateId })));
364
+ const lineageView = gtx.extension(ADMISSION_LINEAGE_EXTENSION);
365
+ const anchor = evidence?.delivery.anchor;
366
+ const lineage = anchor === undefined ? await readLineageRecords(lineageView) : ((record) => (record === undefined ? [] : [record]))(await readLineageRecord(lineageView, lineageKey(anchor)));
367
+ return { window: tip === undefined ? undefined : windowFor(stored, tip), tip, fenced: fence.kind !== 'absent', evidence, lineage, entry, records };
368
+ }));
369
+ const candidate = read.evidence?.candidate;
370
+ if (read.evidence === undefined || candidate === undefined)
371
+ throw invalidReference('unknown-reference', 'no decline candidate of this store has that reference', { groupId, candidateId });
372
+ const { delivery, invite } = read.evidence;
373
+ const lastKnown = read.fenced || deps.sessionFenced(groupId);
374
+ const ledger = read.entry === undefined ? [] : [read.entry];
375
+ const hit = matchingCleanupRecord(read.records, read.entry, candidateId);
376
+ if (hit !== undefined) {
377
+ return { report: cleanupDispositionOf({ groupId, candidate, ledger, inFlight: { intentId: inFlightRootOf(hit, read.entry) }, lastKnown }) };
378
+ }
379
+ // Pure from here: the transactions are closed (the KeyPackage refs of lazy resolution hash outside them).
380
+ let anchor = delivery.anchor === undefined ? undefined : lineageAnchorOf(delivery.anchor);
381
+ let lazilyResolved = false;
382
+ if (anchor === undefined && candidate.status === 'actionable' && invite?.commitTag !== undefined && read.window !== undefined && read.tip !== undefined) {
383
+ anchor = await resolveLegacyAnchor({ window: read.window, tipState: read.tip, commitTag: invite.commitTag, commitEventId: invite.commitEventId, inviteeRef: delivery.inviteeRef });
384
+ lazilyResolved = anchor !== undefined;
385
+ }
386
+ // A legacy delivery's anchor is window-bound (AR-7), but once a cleanup accepted it the ledger target carries it, and D9 seeded its
387
+ // lineage: the Add leaving the window must not turn an attributed (or attributable) cleanup into `no-anchor`.
388
+ if (anchor === undefined && delivery.anchor === undefined)
389
+ anchor = read.entry?.target.anchor;
390
+ let admission;
391
+ let seedLegacyAnchor = false;
392
+ if (anchor !== undefined) {
393
+ const key = lineageKey(anchor);
394
+ const stored = read.lineage.find((r) => lineageKey(r.anchor) === key);
395
+ seedLegacyAnchor = lazilyResolved && stored === undefined;
396
+ const record = stored ?? { anchor };
397
+ admission =
398
+ read.window === undefined || read.tip === undefined
399
+ ? { occupancy: { kind: 'gap', reason: 'unprovable-root' }, provenance: 'transition', at: { tag: anchor.addTag, epoch: 0 } }
400
+ : deriveAdmission(record, read.window, read.tip);
401
+ }
402
+ const report = cleanupDispositionOf({
403
+ groupId,
404
+ candidate,
405
+ ...(anchor === undefined ? {} : { anchor }),
406
+ ...(admission === undefined ? {} : { admission }),
407
+ ledger,
408
+ lastKnown,
409
+ });
410
+ return { report, ...(anchor === undefined ? {} : { anchor }), ...(admission === undefined ? {} : { admission }), ...(seedLegacyAnchor ? { seedLegacyAnchor: true } : {}) };
411
+ }
412
+ // ---------------------------------------------------------------------------
413
+ // The confirm-time ledger write (S5; SC-5 I13) and the build-time lineage read (I15)
414
+ // ---------------------------------------------------------------------------
415
+ /** Whether the MLS commit message `bytes` carries an INLINE (by-value) Remove of `leafIndex`. Never throws. */
416
+ export function carriesInlineRemove(bytes, leafIndex) {
417
+ try {
418
+ const message = decode(mlsMessageDecoder, bytes);
419
+ if (message === undefined || message.wireformat !== wireformats.mls_public_message)
420
+ return false;
421
+ const content = message.publicMessage.content;
422
+ if (content.contentType !== contentTypes.commit)
423
+ return false;
424
+ return content.commit.proposals.some((entry) => entry.proposalOrRefType === proposalOrRefTypes.proposal && entry.proposal.proposalType === defaultProposalTypes.remove && 'remove' in entry.proposal && Number(entry.proposal.remove.removed) === leafIndex);
425
+ }
426
+ catch {
427
+ return false;
428
+ }
429
+ }
430
+ /**
431
+ * I13, in the confirming group transaction: when `record` is a scoped cleanup (an original, or a re-drive still owing its
432
+ * `admission-removed` change) and the confirmed commit carried an INLINE Remove of the target's position, `{digest, tag}` is appended
433
+ * to the candidate's ledger entry (created under `rootIntentId` if none was written — a record written before its entry existed).
434
+ * Idempotent: a digest already listed is not added again.
435
+ */
436
+ export async function recordCleanupConfirmation(tx, input) {
437
+ const target = cleanupTargetOf(input.record);
438
+ if (target === undefined || !carriesInlineRemove(input.commitMessage, target.anchor.leafIndex))
439
+ return;
440
+ const view = tx.extension(ADMISSION_CLEANUP_EXTENSION);
441
+ const entry = (await readCleanupLedgerEntry(view, target.candidateId)) ?? { v: 1, rootIntentId: input.rootIntentId, target, confirmed: [] };
442
+ if (entry.confirmed.some((c) => c.digest === input.digest))
443
+ return;
444
+ await writeCleanupLedgerEntry(view, { ...entry, confirmed: [...entry.confirmed, { digest: input.digest, tag: input.tag }] });
445
+ }
446
+ /**
447
+ * I15: what the selected path proves about `target`'s admission at the runtime's current tip — its stored lineage record (or the
448
+ * anchor alone) derived over the in-memory window. `undefined` when no tip state is at hand. Read on the group's queue.
449
+ */
450
+ export async function readCleanupTargetAdmission(rt, target) {
451
+ const record = await rt.guard.call(rt.groupId, 'store', () => readLineageRecord(rt.groupStore.extension(ADMISSION_LINEAGE_EXTENSION), lineageKey(target.anchor)));
452
+ return deriveAdmission(record ?? { anchor: target.anchor }, rt.window, rt.exposedState);
453
+ }
454
+ const sessionReports = new WeakMap();
455
+ function sessionOf(rt) {
456
+ let session = sessionReports.get(rt);
457
+ if (session === undefined) {
458
+ session = { candidates: new Map(), chain: Promise.resolve() };
459
+ sessionReports.set(rt, session);
460
+ }
461
+ return session;
462
+ }
463
+ /**
464
+ * Marks `candidateId` as one this runtime reports `cleanupDisposition` changes for: a cleanup this session submitted, confirmed or saw
465
+ * withdrawn. In memory only — the event is best effort; a consumer that missed one reads the disposition by reference (AC-REMOVE-21).
466
+ */
467
+ export function noteCleanupCandidate(rt, candidateId, report) {
468
+ const session = sessionOf(rt);
469
+ if (report !== undefined)
470
+ session.candidates.set(candidateId, JSON.stringify(report));
471
+ else if (!session.candidates.has(candidateId))
472
+ session.candidates.set(candidateId, undefined);
473
+ }
474
+ /**
475
+ * Re-derives the disposition of every candidate {@link noteCleanupCandidate} named and emits `cleanupDisposition` for each one whose
476
+ * report changed since the last emission. Detached: never awaited by the caller, never throws, and a failed read emits nothing (the
477
+ * read by reference recovers it). Reads only — no write, no transport call.
478
+ */
479
+ export function emitCleanupDispositions(rt) {
480
+ const session = sessionReports.get(rt);
481
+ if (session === undefined || session.candidates.size === 0)
482
+ return;
483
+ // Outside every re-entrancy frame of the caller (like `ctx.emit`): the reads below are this detached task's own.
484
+ session.chain = rt.guard.detached(() => session.chain.then(async () => {
485
+ if (rt.disposed || rt.ctx.isDisposed())
486
+ return;
487
+ session.account ??= await rt.guard.call(ACCOUNT_SCOPE, 'signer', () => rt.ctx.signer.getPublicKey());
488
+ for (const [candidateId, last] of [...session.candidates]) {
489
+ if (rt.disposed || rt.ctx.isDisposed())
490
+ return;
491
+ let report;
492
+ try {
493
+ report = (await deriveCleanupDisposition(runtimeReaderDeps(rt), { account: session.account, groupId: rt.groupId, candidateId })).report;
494
+ }
495
+ catch {
496
+ continue;
497
+ }
498
+ const key = JSON.stringify(report);
499
+ if (key === last)
500
+ continue;
501
+ session.candidates.set(candidateId, key);
502
+ rt.ctx.emit('cleanupDisposition', report);
503
+ }
504
+ })).catch(() => undefined);
505
+ }
506
+ function runtimeReaderDeps(rt) {
507
+ return { guard: rt.guard, account: rt.ctx.stores.account, groupStore: () => rt.groupStore, sessionFenced: () => rt.fence !== undefined };
508
+ }
509
+ // ---------------------------------------------------------------------------
510
+ // The removal ladder (S5; SC-11)
511
+ // ---------------------------------------------------------------------------
512
+ const REMOVE_OPERATION = 'removeAdmission';
513
+ function refusedReference(reason, message, details = {}) {
514
+ return new MarmotError('invalid-options', `${REMOVE_OPERATION}: ${message}`, { details: { reason, ...details } });
515
+ }
516
+ /** The credential account of the leaf at `leafIndex` of `state`, or `undefined` (blank leaf, undecodable credential). */
517
+ function accountAt(state, leafIndex) {
518
+ const node = state.ratchetTree[leafIndex * 2];
519
+ if (node?.nodeType !== nodeTypes.leaf)
520
+ return undefined;
521
+ try {
522
+ return getCredentialPubkey(node.leaf.credential);
523
+ }
524
+ catch {
525
+ return undefined;
526
+ }
527
+ }
528
+ /**
529
+ * `MarmotGroup.removeAdmission(ref)` on the group's queue: the SC-11 ladder, in total order. Phase P (P1–P5) is a pure-read prefix —
530
+ * no `preflight`, no `resumePending`, no write, no timer, no transport call — that ends in a coalesce: a cleanup already in flight for
531
+ * the candidate (I15a) resolves `pending` under its root intent id. Phase D then resumes pending work (`preflight`), applies the send
532
+ * gate, re-reads the disposition (anything but `eligible` resolves with that report), refuses the committer's own leaf (`self`), a
533
+ * non-admin, an admin coupling the account removal would refuse, another own commit pending and a staged proposal in the way — each
534
+ * refusal enqueues nothing — and finally writes the cleanup record and the candidate's ledger entry in ONE group transaction (I13).
535
+ * The commit is built and published in the background (the group's resume), re-checking the target on the actual parent (I15); the
536
+ * call resolves `pending` with the new root intent id.
537
+ */
538
+ export async function removeAdmissionIntent(rt, ref) {
539
+ const op = REMOVE_OPERATION;
540
+ // P1, P2: in memory.
541
+ assertNotDisposed(rt);
542
+ assertNotFenced(rt, op);
543
+ assertNotDisbanded(rt, op);
544
+ assertMember(rt, op);
545
+ // P3: the reference, against the signer's account (I9c) and this group.
546
+ const decoded = decodeCleanupReference(ref);
547
+ if (decoded === undefined)
548
+ throw refusedReference('malformed-reference', 'not a cleanup reference');
549
+ const account = await callSignerForGroup(rt, () => rt.ctx.signer.getPublicKey());
550
+ assertNotDisposed(rt);
551
+ if (decoded.account !== account)
552
+ throw refusedReference('foreign-reference', 'the reference names another account', { groupId: rt.groupId });
553
+ if (decoded.groupId !== rt.groupId)
554
+ throw refusedReference('foreign-reference', 'the reference names another group', { groupId: rt.groupId });
555
+ const { groupId, candidateId } = decoded;
556
+ // P4: a known candidate (read-only account transaction).
557
+ const known = await rt.guard.call(rt.groupId, 'store', () => rt.guard.call(ACCOUNT_SCOPE, 'store', () => rt.ctx.stores.account.transaction((tx) => cleanupCandidateExists(tx, { groupId, candidateId }))));
558
+ assertNotDisposed(rt);
559
+ if (!known)
560
+ throw refusedReference('unknown-reference', 'no decline candidate of this store has that reference', { groupId, candidateId });
561
+ // P5: coalesce (read-only group transaction over pendingIntents and the ledger).
562
+ const inFlight = await rt.guard.call(rt.groupId, 'store', () => rt.groupStore.transaction(async (tx) => {
563
+ const entry = await readCleanupLedgerEntry(tx.extension(ADMISSION_CLEANUP_EXTENSION), candidateId);
564
+ const hit = matchingCleanupRecord(await listPendingIntentRecords(tx.artifact('pendingIntents')), entry, candidateId);
565
+ return hit === undefined ? undefined : inFlightRootOf(hit, entry);
566
+ }));
567
+ assertNotDisposed(rt);
568
+ if (inFlight !== undefined)
569
+ return { groupId, candidateId, intentId: inFlight, disposition: 'pending', lastKnown: false };
570
+ // D1: resume pending work; a blocked confirmation refuses.
571
+ const remaining = await preflight(rt, op);
572
+ assertMember(rt, op);
573
+ // D2: the send gate.
574
+ assertSendGateOpen(rt, op);
575
+ // D3: the disposition, re-read (the same derivation as `cleanupDisposition`): anything but eligible resolves with it.
576
+ const derived = await deriveCleanupDisposition(runtimeReaderDeps(rt), { account, groupId, candidateId });
577
+ assertNotDisposed(rt);
578
+ if (derived.report.disposition !== 'eligible' || derived.anchor === undefined)
579
+ return derived.report;
580
+ const anchor = derived.anchor;
581
+ const state = rt.engine.state;
582
+ // D4: never the committer's own leaf (another device of the own account is a valid target).
583
+ if (Number(state.privatePath.leafIndex) === anchor.leafIndex) {
584
+ throw new MarmotError('invalid-options', `${op}: the target is the local leaf of group ${groupId}; use leave()`, { details: { groupId, reason: 'self' } });
585
+ }
586
+ // D5: the committer must be an admin.
587
+ assertLocalAdmin(rt, op, account);
588
+ // D6: the last leaf of an admin account — the account removal's admin coupling: the engine splices the removed admin out of the
589
+ // policy in the same commit; a staged admin-list change still naming it is refused as for removeMember.
590
+ const targetAccount = accountAt(state, anchor.leafIndex);
591
+ if (targetAccount === undefined) {
592
+ throw new MarmotError('send-rejected', `${op}: the target leaf of group ${groupId} carries no readable credential`, { details: { groupId, reason: 'admission-changed' } });
593
+ }
594
+ const view = getMarmotGroupView(state);
595
+ const lastAdminLeaf = view !== null && isActiveAdmin(state.ratchetTree, view.adminPubkeys, targetAccount) && getPubkeyLeafNodeIndexes(state, targetAccount).length === 1;
596
+ if (lastAdminLeaf && stagesComponentUpdate(state, GROUP_ADMIN_POLICY_COMPONENT_ID)) {
597
+ throw new MarmotError('send-rejected', `${op}: a staged admin-list change of group ${groupId} would still name the removed admin; commit it first (send({ type: 'commit' })) and retry`, {
598
+ details: { groupId, reason: 'staged-admin-policy-update', retryable: true },
599
+ });
600
+ }
601
+ // D7: one own commit at a time; then the proposal policy every own commit passes.
602
+ assertNoOwnCommitPending(rt, remaining, op);
603
+ await applyProposalPolicy(rt, op);
604
+ // D8: a staged proposal in the way (a Remove of the target would be carried by reference; an Add may refill the position).
605
+ const conflict = stagedCleanupConflict(rt.engine.state, anchor.leafIndex);
606
+ if (conflict !== undefined) {
607
+ throw new MarmotError('send-rejected', `${op}: a staged proposal of group ${groupId} conflicts with the cleanup (${conflict}); commit it first (send({ type: 'commit' })) and retry`, {
608
+ details: { groupId, reason: conflict, retryable: true },
609
+ });
610
+ }
611
+ // The leaf the read proved must be the one the commit would be built over (op boundary: engine == durable).
612
+ const refusal = cleanupTargetRefusal({ candidateId, anchor, acceptedAtTag: '', account: targetAccount }, derived.admission, rt.engine.state);
613
+ if (refusal !== undefined)
614
+ throw new MarmotError('send-rejected', `${op}: the target admission cannot be removed now (${refusal.reason})`, { details: { groupId, reason: refusal.reason, retryable: true } });
615
+ // D9: the record and the ledger entry, in ONE group transaction (I13); a new root replaces the entry's root, keeping `confirmed` (I15b).
616
+ const target = { candidateId, anchor, acceptedAtTag: tagOf(rt.engine.state), account: targetAccount };
617
+ const record = await recordIntent(rt, 'commit', { type: 'commit', removeAdmission: target }, 'pending-publish', rt.engine.state.groupContext.epoch, async (tx, written) => {
618
+ const ledgerView = tx.extension(ADMISSION_CLEANUP_EXTENSION);
619
+ const entry = await readCleanupLedgerEntry(ledgerView, candidateId);
620
+ await writeCleanupLedgerEntry(ledgerView, { v: 1, rootIntentId: written.intentId, target, confirmed: entry?.confirmed ?? [] });
621
+ // A lazily resolved legacy anchor (SC-3 I9b) has no lineage record: seed one at its Add node (in the window: D3 just resolved it
622
+ // there) so that recordTransition advances it like any confirmation-seeded record and attribution and settlement outlive the Add's
623
+ // node in the window. Idempotent: an existing record is never moved.
624
+ const addEpoch = rt.window.nodes.get(anchor.addTag)?.epoch;
625
+ if (derived.seedLegacyAnchor === true && addEpoch !== undefined) {
626
+ await seedLineageRecords(tx.extension(ADMISSION_LINEAGE_EXTENSION), new Map([[lineageKey(anchor), { anchor, candidateIds: [candidateId] }]]), addEpoch);
627
+ }
628
+ });
629
+ const report = { groupId, candidateId, intentId: record.intentId, disposition: 'pending', lastKnown: false };
630
+ noteCleanupCandidate(rt, candidateId, report);
631
+ rt.ctx.emit('cleanupDisposition', report);
632
+ // Built, published and confirmed by the group's resume, queued behind this operation.
633
+ resumePendingInBackground(rt);
634
+ return report;
635
+ }