@941design/marmot 0.2.0-alpha.0 → 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 (63) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/dist/account/teardown.d.ts +66 -3
  3. package/dist/account/teardown.js +24 -2
  4. package/dist/client/admission-cleanup.d.ts +197 -0
  5. package/dist/client/admission-cleanup.js +635 -0
  6. package/dist/client/adoption-proof.d.ts +39 -0
  7. package/dist/client/adoption-proof.js +102 -0
  8. package/dist/client/before-publish-hooks.js +3 -1
  9. package/dist/client/commit-redrive.d.ts +28 -4
  10. package/dist/client/commit-redrive.js +54 -1
  11. package/dist/client/confirm-hooks.d.ts +6 -1
  12. package/dist/client/confirm-hooks.js +15 -0
  13. package/dist/client/create-client.d.ts +107 -3
  14. package/dist/client/create-client.js +114 -7
  15. package/dist/client/group-availability.d.ts +182 -0
  16. package/dist/client/group-availability.js +301 -0
  17. package/dist/client/group-history.d.ts +26 -0
  18. package/dist/client/group-history.js +77 -7
  19. package/dist/client/group-records.d.ts +39 -2
  20. package/dist/client/group-records.js +88 -5
  21. package/dist/client/group-runtime.d.ts +30 -3
  22. package/dist/client/group-runtime.js +131 -21
  23. package/dist/client/group-snapshot.d.ts +7 -1
  24. package/dist/client/group-snapshot.js +23 -2
  25. package/dist/client/index.d.ts +4 -1
  26. package/dist/client/ingest.js +47 -13
  27. package/dist/client/invitation-outcomes.d.ts +50 -0
  28. package/dist/client/invitation-outcomes.js +135 -0
  29. package/dist/client/opaque-candidates.d.ts +2 -1
  30. package/dist/client/opaque-candidates.js +2 -1
  31. package/dist/client/own-change-outbox.js +2 -0
  32. package/dist/client/pipeline.d.ts +30 -1
  33. package/dist/client/pipeline.js +142 -21
  34. package/dist/client/reentrancy-guard.d.ts +6 -0
  35. package/dist/client/reentrancy-guard.js +6 -0
  36. package/dist/history/admission-lineage.d.ts +186 -0
  37. package/dist/history/admission-lineage.js +589 -0
  38. package/dist/history/fencing.d.ts +41 -0
  39. package/dist/history/fencing.js +67 -7
  40. package/dist/history/index.d.ts +2 -1
  41. package/dist/history/index.js +2 -1
  42. package/dist/history/own-change.d.ts +13 -1
  43. package/dist/invitations/decline.d.ts +8 -2
  44. package/dist/invitations/decline.js +9 -3
  45. package/dist/invitations/delivery-evidence.d.ts +288 -0
  46. package/dist/invitations/delivery-evidence.js +766 -0
  47. package/dist/invitations/index.d.ts +4 -2
  48. package/dist/invitations/index.js +4 -2
  49. package/dist/invitations/invitation-outcome.d.ts +110 -0
  50. package/dist/invitations/invitation-outcome.js +210 -0
  51. package/dist/invitations/invite.d.ts +61 -6
  52. package/dist/invitations/invite.js +187 -51
  53. package/dist/invitations/welcome-processor.d.ts +20 -1
  54. package/dist/invitations/welcome-processor.js +81 -20
  55. package/dist/shared/errors.d.ts +7 -0
  56. package/dist/shared/errors.js +11 -0
  57. package/dist/shared/index.d.ts +1 -1
  58. package/dist/shared/index.js +1 -1
  59. package/dist/storage/index.d.ts +10 -0
  60. package/dist/storage/index.js +33 -1
  61. package/dist/storage/lease.d.ts +13 -0
  62. package/dist/storage/lease.js +51 -0
  63. package/package.json +2 -2
package/CHANGELOG.md CHANGED
@@ -1,5 +1,35 @@
1
1
  # @941design/marmot
2
2
 
3
+ ## 0.2.0-alpha.1
4
+
5
+ ### Minor Changes
6
+
7
+ - a7a483c: `client.invitations.cleanupDisposition(ref)` reads, by a decline candidate's `cleanupRef`, what the store's durable evidence proves about the admission that delivery made: `eligible` (the proven original admission is present), `absent` (`add-off-path`, `occupancy-ended`) or `insufficient-evidence` (`unresolved-selector`, `ambiguous-legacy`, `no-anchor`, `lineage-gap`), as `CleanupDispositionReport` `{ groupId, candidateId, disposition, cause?, lastKnown }`. An admission is the leaf one exact Add commit inserted, continuing through verified Updates and ending at the first Remove of that position; re-adding the same position, key or last-resort KeyPackage is a new admission. The read is offline and read-only (no runtime, no publication, no intent, no store write), answers on a fenced group with `lastKnown: true`, rejects `invalid-options` (`malformed-reference`, `foreign-reference`, `unknown-reference`) with no effect, and rejects `reentrant` synchronously from inside group hooks, consumer group-store calls and account-scope callbacks. New exported types: `CleanupDispositionReport`, `CleanupDisposition`, `CleanupDispositionCause`.
8
+
9
+ Admission lineage is kept per anchored delivery in the new group extension `marmot.admission-lineage`, advanced with every persisted transition, and carried by group snapshots (an additive optional payload field); `groups.restore` keeps only what the snapshot's own window proves and reads everything else as insufficient evidence until re-proven.
10
+
11
+ Behaviour change: cleanup references (and `DeclineCandidate.cleanupRef`) always carry the signer's account, never a custom `AccountStore.account` that differs from it.
12
+ - a7a483c: `client.invitations.declineCandidates({ after?, limit? })` recovers, offline and from the account store alone, every Welcome delivery its invitee's account declined, as stable candidates: `{ candidateId, groupId, recipient, inviteeRef, welcomeId, status: 'actionable' | 'ambiguous', basis: 'unqualified' | 'qualified' | 'legacy', rev, cleanupRef }`, in bounded pages with explicit completion. The new `declineCandidate` event reports each new candidate, late match and refinement after it is durable; register it before scanning and deduplicate by `(candidateId, rev)`. The scan is read-only: no publication, no intent, no pruning, no store write, no group opened. It rejects `reentrant` synchronously from inside an account-scope store, signer or verifier callback. New exported types: `DeclineCandidate`, `DeclineCandidatePage`, `CleanupReference`.
13
+
14
+ Every issued delivery now keeps small, payload-free evidence (new account extensions `marmot.delivery-evidence` and `marmot.decline-evidence`) that outlives `inviteRetentionMs` and is removed with the group or an account wipe, so a decline arriving after the retry payload was pruned still matches. Retained records of earlier releases are backfilled lazily.
15
+
16
+ Behaviour changes: `welcomeDeclined` gains `candidateId`. `invitations.decline(id, { declineRumor: true })` adds the consumed `keyPackageRef` to the v1 DECLINE rumor (older readers ignore it); an upgraded inviter then declines only that delivery, leaving a sibling device's delivery and retries untouched, and a present but invalid selector changes nothing. An unqualified decline of a Welcome shared by several devices of one account still declines every retained delivery, and its candidates stay `ambiguous` until a device qualifies its own.
17
+ - a7a483c: `MarmotGroup.observeAvailability(listener)` observes a group's availability without a subscription gap. Each `GroupAvailability` reports three independent facts: the fence (`clear` or `fenced` with a coarse `FenceCause`: `lost-path-secrets`, `invalid-stored-evidence` or `unknown`), the sync state (`syncing` / `synced`) and the membership (`member`, `membership-lost`, `disbanded`). It also reports `writable`. The current snapshot is delivered at once, then every change in order, with a strictly increasing `seq`. A fence is an ordinary observation: the subscription stays open, and within a client session no `clear` follows `fenced`, even when the fence marker could not be written. Exactly one `ended` closes a subscription. Its reason is `torn-down`, `restore-undone`, `disposed` or `no-lease`, and `final.writable` is `false`. After that, a new subscription gets the `ended` at once.
18
+
19
+ The storage port gains an optional `AccountStore.onLeaseEnded(listener)`. The built-in memory and IndexedDB backends fire it once when the lease is released, closed or stolen by another context. The client then ends every group's availability `no-lease` at once, without scheduling group work.
20
+
21
+ Behaviour change: a present but malformed fence marker now fences the group on load (`invalid-stored-evidence`) instead of being read as no fence. Fence markers now record their cause; a marker written before this release reads `unknown`. An ingest batch that reaches a fence verdict but fails to commit now fences the client session in memory (rolled back, no marker), where it used to leave the group unfenced.
22
+ - a7a483c: `client.invitations.outcome(id)` reports whether one exact Welcome caused this device to join its group: `pending`, `joining` (resumable), `unresolved` (a competing Welcome or a restore-deferred join still waiting), `joined` (`via: 'adoption'` or `'switch'`), `not-joined` (`declined`, `rejected` or `kept-out`, with the stored reason as `detail`), `unknown` (no record) or `indeterminate` (a record from an earlier release without invitation-specific evidence). The answer is read at one instant from durable evidence only: a new `marmot.adoption` proof written in the adoption's own group transaction, the existing branch-switch proof, an adoption stamp on the invitation record (written when the join completes and by teardown before the group is deleted), or, for records written before this release, the group index entry's `adoptedBy`. A `joined` outcome survives teardown, other invitations' branch switches and restarts. The read works before `inbox.start()`, runs behind the current inbox task, never publishes or writes, rejects `store-failed`/`no-lease` instead of guessing, and rejects `reentrant` synchronously when called from inside a hook, an inbox handler or another account-scope consumer surface. The new type `InvitationOutcome` is exported.
23
+
24
+ `invitations.accept(id)` is unchanged and can still resolve with the held group's handle for a Welcome that was kept out; `outcome(id)` is the authoritative read.
25
+
26
+ Behaviour change: tearing down a group whose join was interrupted after its group state committed (but before the `joined` record) now keeps that invitation `joined` (stamped) instead of turning it `rejected` with reason `abandoned`. A redelivered Welcome still answers `already-member` and does not bring the group back.
27
+ - a7a483c: `MarmotGroup.removeAdmission(ref)` removes exactly the one admission a declined delivery made — the leaf position the decline candidate's proven original Add put in the group — by the candidate's `cleanupRef`, re-deriving authority from durable evidence and lineage on every call. It resolves a `CleanupDispositionReport`: `pending` (root `intentId`) once the cleanup is durably accepted, or the current non-eligible disposition. A submit for a cleanup already in flight (lost reply, awaiting confirmation, a library re-drive of a withdrawn one, after a restart) coalesces before anything is resumed: no transport call, no store write, no new intent. Refusals enqueue nothing: `fenced`, `not-a-member`, `invalid-options` (`malformed-reference`, `foreign-reference`, `unknown-reference`, `self`, `not-admin`), `confirm-blocked`, `commit-pending` (retryable), `send-rejected` with `details.retryable` (`staged-add-conflict`, `staged-removal-of-target`, `staged-admin-policy-update`). The commit is an inline Remove of the target position, built in the background after re-checking the admission on the actual parent; if the admission changed, ended or can no longer be proven there (`admission-changed`, `admission-ended`, `admission-unproven`), nothing is removed and the intent fails `send-rejected` (`intentFailed`).
28
+
29
+ `invitations.cleanupDisposition(ref)` now also reports `pending`, `removed-revisable` and `removed-settled` (with `intentId` / `commitDigest`); attribution comes only from the cleanup's own confirmed inline Remove on the selected path, and settlement happens once `REWIND_HORIZON` later commits follow the Remove (it has left the retained window). New client event `cleanupDisposition` (best effort). New group extension `marmot.admission-cleanup`.
30
+
31
+ Behaviour change (pre-1.0 minor): the public `OwnChange` union gained `{ type: 'admission-removed'; account; leafKey; candidateId }`; exhaustive switches over it need the new case. A cleanup is never reported as `member-removed` and never re-driven as an account-wide removal.
32
+
3
33
  ## 0.2.0-alpha.0
4
34
 
5
35
  ### Minor Changes
@@ -1,3 +1,63 @@
1
+ /**
2
+ * Group teardown (S9; AC-ADMIN-3, -5, -6, -7, -10): `leave()`, `abandon()`,
3
+ * `destroy()` and `departAsAdmin()` as ONE durable intent per group, and the
4
+ * per-group `leave()` that `devices.forget(ownLeafKey)` runs on every held
5
+ * group.
6
+ *
7
+ * The intent is an account record (extension `marmot.teardown`, keyed by a
8
+ * random request id) written before any effect — the group store is exactly
9
+ * what the teardown deletes, so the record cannot live there. Its phases:
10
+ *
11
+ * 1. `leaving` (leave only): the local leaf's SelfRemove proposal goes out
12
+ * through the pipeline's durable intents (re-proposed whenever an epoch
13
+ * change drops it); a leaf that is its admin account's last first
14
+ * commits the account's demotion (`departAsAdmin`). The phase ends when
15
+ * the group's own state shows the leaf removed — a peer's confirmed
16
+ * commit, the engine's SelfRemove auto-commit on some other member —
17
+ * or at the absolute `deadline` (`leaveTimeoutMs` after the request, on
18
+ * the client clock; re-armed after a reload), or at once when the leaf
19
+ * is the group's only member (nothing is sent). A leaf that is (or
20
+ * becomes, while this runs) the last leaf of the group's last active
21
+ * admin cannot leave: the intent ends `last-admin` straight to `done`,
22
+ * WITHOUT the purge — the group keeps its admin and stays held.
23
+ * 2. `purging` (every kind — this IS `abandon()`): the group runtime is
24
+ * retired and every artifact of the group's `GroupStore` deleted
25
+ * (nothing is published), then ONE account transaction drops what the
26
+ * account keeps per group — `invites` (Welcome deliveries),
27
+ * `enrolmentManifests`, still-`pending` invitations, received KeyPackage
28
+ * offers, `keyPackageGroupRefs`, and the group's index entry — and, for
29
+ * `destroy()`, the retained (grace-window) init keys of the KeyPackages
30
+ * the group's Welcomes consumed.
31
+ * 3. `deleting` (destroy only): S4's `forget()` — a durable kind-5 on the
32
+ * KeyPackage's slot — for every KeyPackage the account minted for the
33
+ * group (captured when the destroy was requested, before the purge
34
+ * deleted the refs): `keyPackages.offer({ groupId })` KeyPackages and
35
+ * the per-group KeyPackages of an enrolment request.
36
+ *
37
+ * `abandon()` / `destroy()` requested while a `leave()` runs take the
38
+ * record over (outcome `abandoned`); a second `leave()` joins the running
39
+ * one. A request joins only a record still in `leaving` or `purging` — the
40
+ * group's FRONT intent, at most one per group. A record past its purge
41
+ * (`deleting`) no longer stands for the group: the state it deleted is gone,
42
+ * and a group held again was re-joined through a newer Welcome (S11's join
43
+ * barrier lets none through earlier), so a request records a FRESH intent
44
+ * beside it (`succeeds` names it) instead of resolving on the old one's
45
+ * progress (S16). The front intent runs on one driver per group; each
46
+ * past-purge record's kind-5 pass on its own driver — the two settle
47
+ * independently: the fresh intent never waits on the old destroy's signer or
48
+ * relays, and the old one's deletions are neither dropped nor issued twice
49
+ * (the fresh destroy's KeyPackage capture skips refs an older record of the
50
+ * group still deletes). A driver re-reads its record inside every
51
+ * transaction and never holds one across a group operation, signer or relay
52
+ * call. Failures a pass counts (not explicitly transient,
53
+ * `maintenanceFailureReason`) — each charged to the record its driver was
54
+ * driving — give that intent up after {@link MAX_MAINTENANCE_FAILURES}
55
+ * (`maintenanceFailed`, kind `teardown`); any work left is retried by a
56
+ * background pass, each driver at its own capped backoff, and the
57
+ * next inbox pass or `groups.list()/get()` resumes intents a reload
58
+ * interrupted.
59
+ */
60
+ import { type AdoptionProofs } from '../invitations/index.js';
1
61
  import type { AccountStoreTx } from '../storage/index.js';
2
62
  /** Account extension namespace of teardown intents. */
3
63
  export declare const TEARDOWN_EXTENSION = "marmot.teardown";
@@ -46,10 +106,13 @@ export interface TeardownGroupPort {
46
106
  /**
47
107
  * Retires the group runtime and deletes everything of the group's `GroupStore`; idempotent, publishes nothing.
48
108
  * Inside the ONE serialized group operation that clears the store — after every operation queued before it —
49
- * it first reads the epoch of the stored state and awaits `beforeClear(epoch)` (the watermark), then clears
50
- * (F2). `beforeClear` is not called when no state is stored any more.
109
+ * it first reads the epoch of the stored state and the group's adoption proofs, and awaits
110
+ * `beforeClear(epoch, proofs)` (the watermark, and the stamping of every invitation the proofs make `joined`:
111
+ * epic marmot-invitation-outcomes S2, A1), then clears (F2). `beforeClear` is not called when no state is stored
112
+ * any more. `proofs` is optional only for ports that hold no adoption proofs (test doubles); the client's port always
113
+ * passes them — without them A1 stamps nothing and the proofs' outcomes rest on A2 alone.
51
114
  */
52
- purge(groupId: string, beforeClear: (epoch: bigint) => Promise<void>): Promise<void>;
115
+ purge(groupId: string, beforeClear: (epoch: bigint, proofs?: AdoptionProofs) => Promise<void>): Promise<void>;
53
116
  /** Calls `listener` whenever the group's exposed state changes; returns the unsubscribe. */
54
117
  watch(groupId: string, listener: () => void): () => void;
55
118
  }
@@ -57,7 +57,7 @@
57
57
  * next inbox pass or `groups.list()/get()` resumes intents a reload
58
58
  * interrupted.
59
59
  */
60
- import { manifestRefsOfGroup, purgeGroupInvitations, purgeGroupInvites, purgeGroupManifests, purgeGroupOffers } from '../invitations/index.js';
60
+ import { indexEntryView, isMalformedRowError, manifestRefsOfGroup, purgeGroupInvitations, purgeGroupInvites, purgeGroupManifests, purgeGroupOffers, stampAdoptions } from '../invitations/index.js';
61
61
  import { maintenanceFailureReason } from '../inbox/index.js';
62
62
  import { keyPackageRefsOfGroup, purgeKeyPackageGroupRefs, purgeRetainedKeyPackageKeys } from '../key-packages/index.js';
63
63
  import { isMarmotError, MarmotError } from '../shared/index.js';
@@ -406,18 +406,40 @@ export function createTeardownService(deps) {
406
406
  return { wait: Math.min(deadline - now, backoffMs(failures)) };
407
407
  }
408
408
  }
409
+ /**
410
+ * The group's index entry as the outcome classification reads it. A corrupt entry — its payload or its storage
411
+ * envelope — is no adoption evidence: it is read as absent here, so it never blocks the purge that deletes it. A
412
+ * version mismatch or a backend failure still propagates.
413
+ */
414
+ async function indexEntryOf(t, groupId) {
415
+ try {
416
+ return indexEntryView(groupId, await t.extension(deps.groupIndexExtension).get(groupId));
417
+ }
418
+ catch (error) {
419
+ if (isMalformedRowError(error))
420
+ return undefined;
421
+ throw error;
422
+ }
423
+ }
409
424
  async function purgeStep(record) {
410
425
  // F2/F3: the epoch actually purged, committed before the clear — on the record and as the group's watermark.
411
- await deps.groups.purge(record.groupId, (epoch) => tx(async (view, t) => {
426
+ // Epic marmot-invitation-outcomes S2 (A1, ADR-019 D8): in the same transaction, every invitation the group's proofs
427
+ // (or the legacy index entry) make `joined` is stamped, before the clear deletes those proofs.
428
+ await deps.groups.purge(record.groupId, (epoch, proofs) => tx(async (view, t) => {
412
429
  const current = await readRecord(view, record.requestId);
413
430
  if (current?.phase === 'purging' && (current.purgedEpoch === undefined || current.purgedEpoch < epoch))
414
431
  await writeRecord(view, { ...current, purgedEpoch: epoch });
415
432
  await writeWatermark(t, record.groupId, epoch, deps.clock.now());
433
+ if (proofs !== undefined)
434
+ await stampAdoptions(t, record.groupId, proofs, await indexEntryOf(t, record.groupId), deps.clock.now());
416
435
  }));
417
436
  await tx(async (view, t) => {
418
437
  const current = await readRecord(view, record.requestId);
419
438
  if (current === undefined || current.phase !== 'purging' || !isActive(current))
420
439
  return;
440
+ // S2 (A2): stamped before the index entry (the legacy proof, rule 3) and the records' purge go — a group store
441
+ // a crash emptied before A1 ran (or a pre-upgrade purge) still keeps its adopter's outcome.
442
+ await stampAdoptions(t, current.groupId, 'no-group', await indexEntryOf(t, current.groupId), deps.clock.now());
421
443
  await purgeGroupInvites(t, current.groupId);
422
444
  await purgeGroupManifests(t, current.groupId);
423
445
  await purgeGroupInvitations(t, current.groupId);
@@ -0,0 +1,197 @@
1
+ import { type ClientState } from '@941design/marmot-engine/mls';
2
+ import { type AdmissionDerivation, type LineageAnchor, type RetainedWindow } from '../history/index.js';
3
+ import { type AddAnchor, type CleanupReference, type DeclineCandidate } from '../invitations/index.js';
4
+ import type { AccountStore, GroupStore, GroupStoreTx, KeyValueView, Storable } from '../storage/index.js';
5
+ import { type AdmissionTarget, type PendingIntentRecord } from './group-records.js';
6
+ import type { GroupRuntime } from './group-runtime.js';
7
+ import { type ReentrancyGuard } from './reentrancy-guard.js';
8
+ /** Where a candidate's cleanup stands (SC-12; the spec's disposition table). */
9
+ export type CleanupDisposition = 'eligible' | 'pending' | 'removed-revisable' | 'removed-settled' | 'absent' | 'insufficient-evidence';
10
+ /** Why a disposition is `absent` or `insufficient-evidence`. */
11
+ export type CleanupDispositionCause = 'add-off-path' | 'occupancy-ended' | 'lineage-gap' | 'unresolved-selector' | 'ambiguous-legacy' | 'no-anchor';
12
+ /** One read of a candidate's cleanup disposition (`invitations.cleanupDisposition`). */
13
+ export interface CleanupDispositionReport {
14
+ readonly groupId: string;
15
+ readonly candidateId: string;
16
+ /** The cleanup's root intent id (`pending`, `removed-*`). */
17
+ readonly intentId?: string;
18
+ readonly disposition: CleanupDisposition;
19
+ readonly cause?: CleanupDispositionCause;
20
+ /** The confirmed cleanup commit (`removed-*`). */
21
+ readonly commitDigest?: string;
22
+ /** `true` when the group is fenced: the disposition is the last one the store proved and no longer advances. */
23
+ readonly lastKnown: boolean;
24
+ }
25
+ export declare function lineageAnchorOf(anchor: AddAnchor): LineageAnchor;
26
+ /**
27
+ * The lineage seeds of one confirmed invite commit: its anchors (by KeyPackageRef) grouped by lineage key, each with
28
+ * the candidates (deliveries of invite `inviteId`) it admitted.
29
+ */
30
+ export declare function lineageSeedsOf(groupId: string, inviteId: string, anchors: ReadonlyMap<string, AddAnchor>): Map<string, {
31
+ readonly anchor: LineageAnchor;
32
+ readonly candidateIds: readonly string[];
33
+ }>;
34
+ export type { AdmissionTarget };
35
+ /** Group extension holding one {@link CleanupLedgerEntry} per candidate, keyed by `candidateId`. */
36
+ export declare const ADMISSION_CLEANUP_EXTENSION = "marmot.admission-cleanup";
37
+ /**
38
+ * SC-5: the cleanup ledger entry of one candidate. Written with the cleanup's `pendingIntents` record in ONE group transaction (I13);
39
+ * `rootIntentId` is the root of the cleanup currently responsible for the candidate, replaced only when a new root is created (I15b);
40
+ * `confirmed` lists every own commit that carried an INLINE Remove of the target and was confirmed — never shortened, so an earlier
41
+ * attribution survives a new root (AC-REMOVE-29).
42
+ */
43
+ export interface CleanupLedgerEntry {
44
+ readonly v: 1;
45
+ readonly rootIntentId: string;
46
+ readonly target: AdmissionTarget;
47
+ readonly confirmed: readonly {
48
+ readonly digest: string;
49
+ readonly tag: string;
50
+ }[];
51
+ }
52
+ /** The ledger as the disposition reads it (S4 named the read type; S5 gives it values). */
53
+ export type CleanupLedgerEntryView = CleanupLedgerEntry;
54
+ /** Strict decoder of the ledger row `key` (its candidate id). */
55
+ export declare function decodeCleanupLedgerEntry(key: string, raw: unknown): CleanupLedgerEntry;
56
+ export declare function encodeCleanupLedgerEntry(entry: CleanupLedgerEntry): Storable;
57
+ /**
58
+ * The ledger entry of `candidateId`, or `undefined`. A row that does not decode reads as none: no entry means no attribution and
59
+ * no in-flight root, which only ever makes the disposition LESS positive (fail closed); any other read error propagates.
60
+ */
61
+ export declare function readCleanupLedgerEntry(view: KeyValueView, candidateId: string): Promise<CleanupLedgerEntry | undefined>;
62
+ export declare function writeCleanupLedgerEntry(view: KeyValueView, entry: CleanupLedgerEntry): Promise<void>;
63
+ /** The cleanup target a pending record drives: an original's intent target, or a re-drive's (not yet lost) `admission-removed` change's. */
64
+ export declare function cleanupTargetOf(record: Pick<PendingIntentRecord, 'intent' | 'changes'>): AdmissionTarget | undefined;
65
+ /**
66
+ * I15a — the ONLY definition of "a cleanup for `cid` is in flight": the first `pendingIntents` record (in `records`' order, `seq`)
67
+ * that is (original) a `commit` record whose intent's `removeAdmission` names `cid`, in any state (`pending-confirm` included), or
68
+ * (re-drive) a record re-enqueued from the entry's root whose `changes` hold an `admission-removed` change of `cid`. Without an entry
69
+ * (none written yet, or a row that did not decode) a re-drive record naming `cid` still matches: coalescing never removes twice.
70
+ */
71
+ export declare function matchingCleanupRecord(records: readonly PendingIntentRecord[], entry: Pick<CleanupLedgerEntry, 'rootIntentId'> | undefined, cid: string): PendingIntentRecord | undefined;
72
+ export interface CleanupDispositionInput {
73
+ readonly groupId: string;
74
+ readonly candidate: Pick<DeclineCandidate, 'candidateId' | 'status' | 'basis'>;
75
+ /** The delivery's Add anchor, or the one lazy legacy resolution found; absent when neither names the admission. */
76
+ readonly anchor?: LineageAnchor;
77
+ /** What the selected path proves about that admission (required with `anchor`). */
78
+ readonly admission?: AdmissionDerivation;
79
+ /** The candidate's cleanup ledger entry (S5), when one was written: at most one, `target.candidateId` the candidate's. */
80
+ readonly ledger: readonly CleanupLedgerEntryView[];
81
+ /** S5 (I15a): the root intent id of the cleanup in flight for the candidate ({@link matchingCleanupRecord}), when one is. */
82
+ readonly inFlight?: {
83
+ readonly intentId: string;
84
+ };
85
+ readonly lastKnown: boolean;
86
+ }
87
+ /**
88
+ * SC-3 I9a: the disposition as a pure function of durable evidence and lineage. A cleanup in flight (I15a) is `pending`
89
+ * under its root intent id, whatever else holds (S5). An ambiguous candidate is insufficient evidence (`ambiguous-legacy`
90
+ * when only a pre-upgrade decline covers it, else `unresolved-selector`); an actionable one without an anchor is
91
+ * `no-anchor`; otherwise the admission's occupancy decides — `occupying` → `eligible`, `ended` → `removed-revisable` /
92
+ * `removed-settled` when the end is this candidate's own confirmed INLINE Remove (I14), else `absent`
93
+ * (`occupancy-ended`), `add-off-path` → `absent`, a `gap` → `lineage-gap`.
94
+ */
95
+ export declare function cleanupDispositionOf(input: CleanupDispositionInput): CleanupDispositionReport;
96
+ /**
97
+ * I9b: the anchor of a delivery recorded without one (a pre-upgrade or unanchorable delivery), found in the retained
98
+ * window. Succeeds only when the invite commit's node (`commitTag`) is still in the window with its link, its commit
99
+ * decodes as a framed PublicMessage commit, exactly one Add carried by value in it holds a KeyPackage whose ref is
100
+ * `inviteeRef`, and that KeyPackage's leaf is the unique new KeyPackage-sourced leaf of the commit's state (SC-1 I1).
101
+ * A pruned, absent, undecodable or by-reference commit, or zero or several matching Adds: `undefined` (`no-anchor`).
102
+ * Never throws.
103
+ */
104
+ export declare function resolveLegacyAnchor(input: {
105
+ readonly window: RetainedWindow;
106
+ readonly tipState: ClientState;
107
+ readonly commitTag: string;
108
+ readonly commitEventId: string;
109
+ readonly inviteeRef: string;
110
+ }): Promise<LineageAnchor | undefined>;
111
+ /**
112
+ * SC-9 for `invitations.cleanupDisposition`, evaluated synchronously: `reentrant` (naming the surface) inside any live
113
+ * account-scope frame other than an inbox surface (store, signer, verifier, …: the read's account transaction would
114
+ * queue behind it), inside a group-scope `onConfirm` / `onBeforePublish` / `verifier` / `onProposal` frame (its group
115
+ * transaction is open), or inside a group-scope consumer `store` frame. An inbox handler or `onApplicationRumor` frame
116
+ * holds no store transaction: the read proceeds from it, as from an event listener.
117
+ */
118
+ export declare function assertCleanupDispositionAllowed(guard: ReentrancyGuard): void;
119
+ export interface CleanupDispositionReaderDeps {
120
+ readonly guard: ReentrancyGuard;
121
+ readonly account: AccountStore;
122
+ /** The group's store (the same object for the same id: `WritableStores.groupFactory`). */
123
+ groupStore(groupId: string): GroupStore;
124
+ /** The signer's account (SC-3 I9c): a reference of any other account is foreign. */
125
+ accountKey(): Promise<string>;
126
+ /** Whether a fence of `groupId` was raised in this client session (its marker write may have failed). */
127
+ sessionFenced(groupId: string): boolean;
128
+ }
129
+ /**
130
+ * `invitations.cleanupDisposition(ref)`. The guard runs synchronously (a refused call returns an already rejected
131
+ * promise, before any store access). Then: a reference that does not decode → `invalid-options`
132
+ * `malformed-reference`; one of another account than the signer's → `foreign-reference` (I9c: the reference's
133
+ * account part is never trusted as authority); one naming no candidate of this store (an unknown or purged group
134
+ * included) → `unknown-reference`. None of them reads a group store, writes, publishes or resumes anything.
135
+ */
136
+ export declare function readCleanupDisposition(deps: CleanupDispositionReaderDeps, ref: CleanupReference | unknown): Promise<CleanupDispositionReport>;
137
+ /** What one disposition read derived: the report, and (when it got that far) the anchor and what the selected path proves of it. */
138
+ export interface DerivedCleanupDisposition {
139
+ readonly report: CleanupDispositionReport;
140
+ readonly anchor?: LineageAnchor;
141
+ readonly admission?: AdmissionDerivation;
142
+ /** The anchor came from lazy legacy resolution (SC-3 I9b) and no lineage record names it yet: D9 seeds one. */
143
+ readonly seedLegacyAnchor?: true;
144
+ }
145
+ /**
146
+ * The one-instant read behind {@link readCleanupDisposition} and the ladder's D3 (G9: the same derivation, so a submit's report equals
147
+ * the read's): one read-only group transaction (window, state, fence marker, lineage, the candidate's ledger entry, `pendingIntents`)
148
+ * awaiting one read-only account transaction (evidence); the derivation is pure, after both closed. `unknown-reference` when the
149
+ * evidence names no candidate. Runs no guard check of its own (the callers did).
150
+ */
151
+ export declare function deriveCleanupDisposition(deps: Pick<CleanupDispositionReaderDeps, 'guard' | 'account' | 'groupStore' | 'sessionFenced'>, scope: {
152
+ readonly account: string;
153
+ readonly groupId: string;
154
+ readonly candidateId: string;
155
+ }): Promise<DerivedCleanupDisposition>;
156
+ /** Whether the MLS commit message `bytes` carries an INLINE (by-value) Remove of `leafIndex`. Never throws. */
157
+ export declare function carriesInlineRemove(bytes: Uint8Array, leafIndex: number): boolean;
158
+ /**
159
+ * I13, in the confirming group transaction: when `record` is a scoped cleanup (an original, or a re-drive still owing its
160
+ * `admission-removed` change) and the confirmed commit carried an INLINE Remove of the target's position, `{digest, tag}` is appended
161
+ * to the candidate's ledger entry (created under `rootIntentId` if none was written — a record written before its entry existed).
162
+ * Idempotent: a digest already listed is not added again.
163
+ */
164
+ export declare function recordCleanupConfirmation(tx: Pick<GroupStoreTx, 'extension'>, input: {
165
+ readonly record: Pick<PendingIntentRecord, 'intent' | 'changes'>;
166
+ readonly rootIntentId: string;
167
+ readonly commitMessage: Uint8Array;
168
+ readonly digest: string;
169
+ readonly tag: string;
170
+ }): Promise<void>;
171
+ /**
172
+ * I15: what the selected path proves about `target`'s admission at the runtime's current tip — its stored lineage record (or the
173
+ * anchor alone) derived over the in-memory window. `undefined` when no tip state is at hand. Read on the group's queue.
174
+ */
175
+ export declare function readCleanupTargetAdmission(rt: GroupRuntime, target: AdmissionTarget): Promise<AdmissionDerivation | undefined>;
176
+ /**
177
+ * Marks `candidateId` as one this runtime reports `cleanupDisposition` changes for: a cleanup this session submitted, confirmed or saw
178
+ * withdrawn. In memory only — the event is best effort; a consumer that missed one reads the disposition by reference (AC-REMOVE-21).
179
+ */
180
+ export declare function noteCleanupCandidate(rt: GroupRuntime, candidateId: string, report?: CleanupDispositionReport): void;
181
+ /**
182
+ * Re-derives the disposition of every candidate {@link noteCleanupCandidate} named and emits `cleanupDisposition` for each one whose
183
+ * report changed since the last emission. Detached: never awaited by the caller, never throws, and a failed read emits nothing (the
184
+ * read by reference recovers it). Reads only — no write, no transport call.
185
+ */
186
+ export declare function emitCleanupDispositions(rt: GroupRuntime): void;
187
+ /**
188
+ * `MarmotGroup.removeAdmission(ref)` on the group's queue: the SC-11 ladder, in total order. Phase P (P1–P5) is a pure-read prefix —
189
+ * no `preflight`, no `resumePending`, no write, no timer, no transport call — that ends in a coalesce: a cleanup already in flight for
190
+ * the candidate (I15a) resolves `pending` under its root intent id. Phase D then resumes pending work (`preflight`), applies the send
191
+ * gate, re-reads the disposition (anything but `eligible` resolves with that report), refuses the committer's own leaf (`self`), a
192
+ * non-admin, an admin coupling the account removal would refuse, another own commit pending and a staged proposal in the way — each
193
+ * refusal enqueues nothing — and finally writes the cleanup record and the candidate's ledger entry in ONE group transaction (I13).
194
+ * The commit is built and published in the background (the group's resume), re-checking the target on the actual parent (I15); the
195
+ * call resolves `pending` with the new root intent id.
196
+ */
197
+ export declare function removeAdmissionIntent(rt: GroupRuntime, ref: unknown): Promise<CleanupDispositionReport>;