@witbitz/sdk 0.0.0-stage → 4.3.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 (217) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +20 -2
  3. package/a2aCore.js +200 -0
  4. package/a2aShared.js +27 -0
  5. package/accountErase.js +223 -0
  6. package/accountIndexDoc.js +122 -0
  7. package/accountOwner.js +59 -0
  8. package/accountRecord.js +90 -0
  9. package/accountScope.js +114 -0
  10. package/accountSeal.js +42 -0
  11. package/accountStores.js +173 -0
  12. package/acctV2App.js +619 -0
  13. package/acctV2Check.js +29 -0
  14. package/acctV2Client.js +382 -0
  15. package/acctV2Keys.js +43 -0
  16. package/acctV2Legacy.js +14 -0
  17. package/acctV2Switch.js +80 -0
  18. package/acctV2UiCore.js +857 -0
  19. package/acctV2WebAuthn.js +61 -0
  20. package/acctV2Wire.js +59 -0
  21. package/address.js +42 -0
  22. package/attestedBox.js +30 -0
  23. package/attestedRooms.js +78 -0
  24. package/awsKey.js +98 -0
  25. package/backupRecord.js +106 -0
  26. package/backupVault.js +97 -0
  27. package/blocks.js +115 -0
  28. package/blocksPush.js +64 -0
  29. package/browseSeal.js +103 -0
  30. package/cbor.js +225 -0
  31. package/changePush.js +75 -0
  32. package/chatLock.js +149 -0
  33. package/chatLockSw.js +13 -0
  34. package/cloudDeviceBuilds.js +11 -0
  35. package/cloudDevicePins.js +33 -0
  36. package/cloudDeviceSeal.js +53 -0
  37. package/codeBrowse.js +224 -0
  38. package/codeCloud.js +652 -0
  39. package/codeCloudKeys.js +112 -0
  40. package/codeCommands.js +167 -0
  41. package/codeComputers.js +388 -0
  42. package/codeEgress.js +123 -0
  43. package/codeFilesRoutes.js +17 -0
  44. package/codeMkdir.js +8 -0
  45. package/codeModes.js +57 -0
  46. package/codeOrphanKeys.js +42 -0
  47. package/codeOutputs.js +141 -0
  48. package/codeRelay.js +505 -0
  49. package/codeSentinel.js +86 -0
  50. package/codeTransport.js +295 -0
  51. package/codeUndo.js +48 -0
  52. package/compress.js +24 -0
  53. package/config.js +11 -0
  54. package/connCatalog.js +164 -0
  55. package/connDisp.js +76 -0
  56. package/connOtherWays.js +74 -0
  57. package/connPending.js +16 -0
  58. package/connWrap.js +53 -0
  59. package/connectionEntry.js +89 -0
  60. package/connections.js +562 -0
  61. package/credits.js +30 -0
  62. package/csAttest.js +112 -0
  63. package/decrypt.html +384 -0
  64. package/deviceAttest.js +521 -0
  65. package/deviceCall.js +54 -0
  66. package/deviceKeyCore.js +41 -0
  67. package/deviceSeal.js +59 -0
  68. package/e2ee.js +323 -0
  69. package/eat.js +103 -0
  70. package/emailFork.js +275 -0
  71. package/emailSignIn.js +81 -0
  72. package/emptySpaces.js +111 -0
  73. package/encSource.js +55 -0
  74. package/enclaveAccept.js +214 -0
  75. package/enclaveClaim.js +241 -0
  76. package/enclaveRoute.js +102 -0
  77. package/enclaveSnapshotMerge.js +44 -0
  78. package/entrySig.js +165 -0
  79. package/env.js +73 -0
  80. package/eraseFile.js +58 -0
  81. package/followImage.js +86 -0
  82. package/healNames.js +45 -0
  83. package/idb.js +97 -0
  84. package/idbSeal.js +119 -0
  85. package/indexGone.js +12 -0
  86. package/invite.js +51 -0
  87. package/inviteEnroll.js +67 -0
  88. package/inviteSend.js +68 -0
  89. package/jobAgents.js +87 -0
  90. package/keptMerge.js +84 -0
  91. package/l1-worker-src.js +2 -0
  92. package/l1-worker.js +831 -0
  93. package/laneConfig.js +57 -0
  94. package/laneLinkCore.js +177 -0
  95. package/ledgerView.js +64 -0
  96. package/manifest.json +220 -0
  97. package/mcpRecommended.js +25 -0
  98. package/memberChange.js +123 -0
  99. package/mkseal.js +101 -0
  100. package/nativePush.js +153 -0
  101. package/nitroVerify.js +220 -0
  102. package/noble-p256.js +27 -0
  103. package/notice.js +116 -0
  104. package/notifKey.js +58 -0
  105. package/offlineBundle.js +62 -0
  106. package/ohttp.js +177 -0
  107. package/opencodeWire.js +282 -0
  108. package/oprf.js +70 -0
  109. package/ownAgentLink.js +96 -0
  110. package/ownerPolicy.js +117 -0
  111. package/package.json +254 -4
  112. package/pollVerdict.js +33 -0
  113. package/prefetchPoll.js +60 -0
  114. package/protectedLocal.js +410 -0
  115. package/pushCore.js +42 -0
  116. package/recovery.js +107 -0
  117. package/regions.js +42 -0
  118. package/removedMessage.js +11 -0
  119. package/renameRefusal.js +9 -0
  120. package/replyQuote.js +34 -0
  121. package/reqEnvelope.js +126 -0
  122. package/roomDefaultPrefs.js +76 -0
  123. package/roomDelete.js +109 -0
  124. package/roomName.js +177 -0
  125. package/roomPass.js +256 -0
  126. package/roomRoster.js +289 -0
  127. package/roomSettings.js +61 -0
  128. package/roomState.js +58 -0
  129. package/roomStreamClient.js +115 -0
  130. package/rosterCount.js +49 -0
  131. package/rosterHash.js +13 -0
  132. package/rowSchema.js +113 -0
  133. package/safeMedia.js +116 -0
  134. package/safeMediaPins.js +17 -0
  135. package/schedulesDoc.js +78 -0
  136. package/sdkA2A.js +404 -0
  137. package/sdkAccount.js +470 -0
  138. package/sdkAccountDoc.js +81 -0
  139. package/sdkAccountSections.js +223 -0
  140. package/sdkAgui.js +141 -0
  141. package/sdkAttest.js +34 -0
  142. package/sdkBackup.js +480 -0
  143. package/sdkBackupV2.js +630 -0
  144. package/sdkBrowserPrivate.js +28 -0
  145. package/sdkBuilds.js +208 -0
  146. package/sdkCloudDevice.js +215 -0
  147. package/sdkComputers.js +480 -0
  148. package/sdkDictation.js +142 -0
  149. package/sdkErase.js +283 -0
  150. package/sdkExports.js +69 -0
  151. package/sdkInvitations.js +34 -0
  152. package/sdkKeptAgent.js +188 -0
  153. package/sdkLaneLink.js +205 -0
  154. package/sdkPlan.js +94 -0
  155. package/sdkProtect.js +228 -0
  156. package/sdkRedact.js +36 -0
  157. package/sdkRekey.js +307 -0
  158. package/sdkReport.js +68 -0
  159. package/sdkSafeMedia.js +255 -0
  160. package/sdkSchedules.js +39 -0
  161. package/sdkSpeech.js +54 -0
  162. package/sdkTurn.js +117 -0
  163. package/sdkVault.js +124 -0
  164. package/sealShare.js +18 -0
  165. package/sealedNames.js +64 -0
  166. package/sealedReceipt.js +17 -0
  167. package/sentinelRelease.js +154 -0
  168. package/shamir.js +85 -0
  169. package/sharedViews.js +38 -0
  170. package/sheetChrome.js +450 -0
  171. package/siri.js +171 -0
  172. package/spaceClient.js +1418 -0
  173. package/spaceConfig.js +81 -0
  174. package/spaceEmailGate.js +813 -0
  175. package/spaceExport.js +125 -0
  176. package/spaceFork.js +216 -0
  177. package/spaceLock.js +358 -0
  178. package/spacePasskey.js +180 -0
  179. package/speechOut.js +100 -0
  180. package/splitKeyClient.js +90 -0
  181. package/store.js +587 -0
  182. package/streamHint.js +36 -0
  183. package/sttCloud.js +220 -0
  184. package/sttWorklet.js +38 -0
  185. package/sw-notif-core.js +538 -0
  186. package/tempList.js +48 -0
  187. package/tinfoilVerifier.js +78 -0
  188. package/toolBooks.js +31 -0
  189. package/toolRules.js +52 -0
  190. package/turnCerts.js +254 -0
  191. package/turnFeed.js +58 -0
  192. package/turnVerdict.js +36 -0
  193. package/usageReceipts.js +176 -0
  194. package/usageSummary.js +90 -0
  195. package/util.js +181 -0
  196. package/vault-core.js +1958 -0
  197. package/vault-kit.mjs +354 -0
  198. package/vault-screens.js +263 -0
  199. package/vaultAtRest.js +177 -0
  200. package/vaultCoreLock.js +111 -0
  201. package/vaultCorePush.js +140 -0
  202. package/vaultDeviceKey.js +95 -0
  203. package/vaultEnclaveHandoff.js +114 -0
  204. package/vaultKeep.js +281 -0
  205. package/vaultSealedStore.js +77 -0
  206. package/vaultWorkerHost.js +98 -0
  207. package/vcWorker.js +34 -0
  208. package/voiceAttest.js +50 -0
  209. package/voiceCert.js +51 -0
  210. package/witbitz-admin.d.ts +135 -0
  211. package/witbitz-admin.js +529 -0
  212. package/witbitz-admin.mjs +1459 -0
  213. package/witbitz-sdk.d.ts +1106 -0
  214. package/witbitz-sdk.js +3835 -0
  215. package/workerClient.js +16 -0
  216. package/workerLiveness.js +21 -0
  217. package/x509.js +218 -0
package/sdkAccount.js ADDED
@@ -0,0 +1,470 @@
1
+ // spaces/public/sdkAccount.js — `wb.account`: the account's LIVE index for a builder's app (2026-10-03; the owner, on what
2
+ // the SDK lacked next to the Spaces app: "And what about the index room etc." → "Yes"). wb.backup puts the room list in
3
+ // the vault for a RESTORE on a new device; this keeps two LIVE devices in step, the way the app's own index room does:
4
+ // the rooms (with their links), what was archived or forgotten, and the devices — with sign-out from another device.
5
+ //
6
+ // WHERE IT LIVES: a Witbitz room whose id and key are DERIVED from the backup's master secret (HKDF), so every device that
7
+ // holds the account — by enable() or restore({ code }) — finds the same room, and two devices can never make two indexes.
8
+ // The index is one state doc in it ('index', the account-doc size cap), and its content is sealed ON THE DEVICE under a
9
+ // third derived key before it is sent: the room's key reaches the standard tier like any room's, but what it carries —
10
+ // every room link the account holds — never does.
11
+ //
12
+ // HOW DEVICES AGREE: per-entry last-writer-wins. Every room entry carries `at` (the last change made to it), a forgotten
13
+ // room leaves a tombstone `{ room, at }`, and a device keeps `seenAt` and, once signed out, `out`. Merging is a union
14
+ // that keeps the newer of each — commutative, so devices converge whatever order they sync in; a write lost to a race
15
+ // is re-sent by its device on the next sync, because that device still sees its entry missing.
16
+ // ★ THE INDEX-CLOBBER RULE (the app lost an account's room list this way once — a fresh device wrote its EMPTY list over
17
+ // the real one): nothing is written unless the read before it was DEFINITIVE — a 200 whose content opened, or a 200
18
+ // with no doc yet. A failed, slow or unopenable read writes nothing and the sync reports { ok: false }.
19
+ // INSTANT (2026-10-03): every write to the index is announced on the index room's stream (agent/spaceService.mjs
20
+ // announceWrite), and a device that holds a socket on it syncs at once — a room made on the phone is on the laptop in
21
+ // about a second. The minute poll stays as the backstop for a socket that is down. Needs connect-src
22
+ // wss://code-relay.witbitz.chat in the page's CSP, like the room streams; without it the poll does the work.
23
+ import { healNames, isUnnamed } from './healNames.js'
24
+ import { latestTitle, titleFromDoc } from './roomName.js'
25
+ import { findEmptySpaces, removeEmptySpaces } from './emptySpaces.js'
26
+ import { indexGoneStep } from './indexGone.js'
27
+ import { openRoomStream } from './roomStreamClient.js'
28
+ import { sealDoc, openDoc, appStoreKey } from './accountSeal.js'
29
+ // THE APP'S FORMAT TOO (docs/sdk-account-format-plan.md phase 3, 3.24.0): the same room also holds the Spaces app's `xindex`,
30
+ // sealed under the app's account-store key. A sync reads BOTH docs and writes BOTH — the old `index` stays for every older
31
+ // release (they read only it), so an old and a new device of one account stay in step. sdkAccountDoc.js translates.
32
+ import { APP_DOC, toAppIndex, fromAppIndex, sameAppIndex } from './sdkAccountDoc.js'
33
+ // THE APP'S OPTIONAL SECTIONS (phase 5): wb.account.contacts / .name / .roomDefaults, in the app's docs of this same room — opt-in
34
+ import { attachSections, refreshSections } from './sdkAccountSections.js'
35
+ import { normUsageKey, pickUsageKey, newUsageKey, collectUsage, usageTotals, docNameFor, monthOf } from './usageReceipts.js' // the account's usage key (receipts on every turn; wb.account.usage)
36
+
37
+ const enc = new TextEncoder(), dec = new TextDecoder()
38
+ const SALT = enc.encode('witbitz-sdk-account-v1')
39
+ const DOC = 'index' // the server's account-doc cap (agent/spaceService.mjs INDEX_MAX_BYTES), not the 32 KB widget cap
40
+ const MAX_TOMBS = 500, MAX_DEVICES = 50
41
+ const SEEN_EVERY = 60 * 60 * 1000 // a device refreshes its "last seen" hourly, so an idle sync writes nothing
42
+ const fail = (code, msg, extra = {}) => Object.assign(new Error('witbitz: ' + msg), { code, ...extra })
43
+
44
+ const ub64 = (s) => { const b = atob(String(s).replace(/-/g, '+').replace(/_/g, '/')); const u = new Uint8Array(b.length); for (let i = 0; i < b.length; i++) u[i] = b.charCodeAt(i); return u }
45
+ const b64url = (u8) => { let s = ''; for (let i = 0; i < u8.length; i++) s += String.fromCharCode(u8[i]); return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') }
46
+ async function hkdf(secret, info, len) {
47
+ const km = await crypto.subtle.importKey('raw', secret, 'HKDF', false, ['deriveBits'])
48
+ return new Uint8Array(await crypto.subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt: SALT, info: enc.encode(info) }, km, len * 8))
49
+ }
50
+ /** The index room every device of the account derives: { room, mk, key } — `room` in the shape spaceConfig mints. */
51
+ export async function indexRoomOf(masterB64) {
52
+ const master = ub64(masterB64)
53
+ const id = await hkdf(master, 'index-room', 8)
54
+ const room = 'sp-' + [].slice.call(id).map((x) => x.toString(36)).join('').slice(0, 12)
55
+ const mk = b64url(await hkdf(master, 'index-mk', 32))
56
+ const key = await crypto.subtle.importKey('raw', await hkdf(master, 'index-seal', 32), { name: 'AES-GCM' }, false, ['encrypt', 'decrypt'])
57
+ return { room, mk, key }
58
+ }
59
+
60
+ // sealDoc / openDoc: accountSeal.js — the same sealing the Spaces app's account stores use
61
+
62
+ const num = (x) => (Number.isFinite(x) && x > 0 ? x : 0)
63
+ /** The union of two index views, the newer of each entry kept. Pure — the whole agreement between devices is here. */
64
+ export function mergeIndex(a, b, maxRooms = 500) {
65
+ const tomb = new Map()
66
+ for (const t of [...(a.tomb || []), ...(b.tomb || [])]) if (t && t.room) tomb.set(t.room, Math.max(tomb.get(t.room) || 0, num(t.at)))
67
+ const rooms = new Map()
68
+ for (const r of [...(a.rooms || []), ...(b.rooms || [])]) {
69
+ if (!r || !r.room) continue
70
+ const prev = rooms.get(r.room)
71
+ const newer = !prev || num(r.at) > num(prev.at) ? r : prev
72
+ const pin = !prev || num(r.pinnedAt) > num(prev.pinnedAt) ? r : prev
73
+ rooms.set(r.room, pin.pinnedAt || pin.pinned ? { ...newer, pinned: !!pin.pinned, pinnedAt: num(pin.pinnedAt) } : newer)
74
+ }
75
+ for (const [room, r] of rooms) if (tomb.has(room) && tomb.get(room) >= num(r.at)) rooms.delete(room) // only a TOMBSTONE removes — an entry from a backup made before `at` existed has none
76
+ const devices = {}
77
+ for (const src of [a.devices || {}, b.devices || {}]) {
78
+ for (const [id, d] of Object.entries(src)) {
79
+ if (!d || typeof d !== 'object') continue
80
+ const p = devices[id]
81
+ devices[id] = !p ? { ...d } : { ...(num(d.seenAt) > num(p.seenAt) ? { ...p, ...d } : { ...d, ...p }), seenAt: Math.max(num(p.seenAt), num(d.seenAt)), ...((p.out || d.out) ? { out: Math.max(num(p.out), num(d.out)) } : {}) }
82
+ }
83
+ }
84
+ // LANE LINKS (lane.link): keyed by the pair, newest wins; an unlink is a `removed` entry, so it reaches every device too.
85
+ const links = new Map()
86
+ for (const l of [...(a.links || []), ...(b.links || [])]) {
87
+ if (!l || !l.a || !l.b) continue
88
+ const k = linkKey(l.a, l.b), prev = links.get(k)
89
+ if (!prev || num(l.at) > num(prev.at)) links.set(k, l)
90
+ }
91
+ const keepDevices = Object.entries(devices).sort((x, y) => num(y[1].seenAt) - num(x[1].seenAt)).slice(0, MAX_DEVICES)
92
+ return {
93
+ rooms: [...rooms.values()].sort((x, y) => num(x.at) - num(y.at)).slice(-maxRooms),
94
+ tomb: [...tomb.entries()].map(([room, at]) => ({ room, at })).sort((x, y) => x.at - y.at).slice(-MAX_TOMBS),
95
+ devices: Object.fromEntries(keepDevices),
96
+ links: [...links.values()].sort((x, y) => num(x.at) - num(y.at)).slice(-200),
97
+ }
98
+ }
99
+ const linkKey = (a, b) => (a < b ? a + '|' + b : b + '|' + a)
100
+ /** THE ACCOUNT'S USAGE KEY (the owner, 2026-10-23: a builder's app records the account's usage too — docs/usage-receipts.md).
101
+ * One per account, in the index every device shares: the smaller id wins (as the app's pickUsageKey), and a key that lost
102
+ * stays among the old ones so receipts addressed to it are still collected. → { usage, usageOld } */
103
+ export function mergeUsage(a, b) {
104
+ const win = pickUsageKey(a && a.usage, b && b.usage)
105
+ const old = new Map()
106
+ for (const k of [...((a && a.usageOld) || []), ...((b && b.usageOld) || []), a && a.usage, b && b.usage].map(normUsageKey)) if (k && (!win || k.id !== win.id)) old.set(k.id, k)
107
+ return { usage: win, usageOld: [...old.values()].slice(-5) }
108
+ }
109
+ const usageCanon = (x) => JSON.stringify([(normUsageKey(x && x.usage) || {}).id || '', ((x && x.usageOld) || []).map((k) => k && k.id).sort()])
110
+ const canon = (x) => JSON.stringify({ u: usageCanon(x),
111
+ rooms: [...(x.rooms || [])].sort((p, q) => (p.room < q.room ? -1 : 1)).map((r) => Object.fromEntries(Object.entries(r).sort())),
112
+ tomb: [...(x.tomb || [])].sort((p, q) => (p.room < q.room ? -1 : 1)),
113
+ links: [...(x.links || [])].sort((p, q) => (linkKey(p.a, p.b) < linkKey(q.a, q.b) ? -1 : 1)).map((l) => Object.fromEntries(Object.entries(l).sort())),
114
+ devices: Object.fromEntries(Object.entries(x.devices || {}).sort().map(([k, v]) => [k, Object.fromEntries(Object.entries(v).sort())])),
115
+ })
116
+
117
+ export class AccountIndex {
118
+ /** @param {object} o { backup: AccountBackup, client: () => spaceClient, deviceName?, viewer? } */
119
+ constructor({ backup, client, deviceName = '', viewer = '', live = () => null, openStream = openRoomStream, version = '' } = {}) {
120
+ this._version = String(version || '').slice(0, 40) // devices[].sdk: the release this device runs (plan § 4.2, decision 6)
121
+ this._live = live
122
+ this._openStream = openStream
123
+ this._stream = null
124
+ this._backup = backup
125
+ this._client = client
126
+ this._deviceName = String(deviceName || '').slice(0, 80)
127
+ this._viewer = viewer
128
+ this._devices = {}
129
+ this._loc = null // { master, room, mk, key } for the backup's current master
130
+ const cur = new Map(); this._usageCursor = { get: (k) => cur.get(k), set: (k, v) => { cur.set(k, v) } } // where each room's receipts were read up to (this page)
131
+ this._pushT = null
132
+ this._poll = null
133
+ this._running = null
134
+ /** Called after a sync changed what this device holds (rooms or devices). */
135
+ this.onChange = null
136
+ /** Called once when another device signed THIS one out: the SDK has dropped the account here — clear what your app keeps. */
137
+ this.onSignedOut = null
138
+ this.lastError = null
139
+ backup._onLocal = () => this._schedule()
140
+ // enable() / restore(): the account now exists on this device — a browser starts keeping it in step at once.
141
+ backup._onStart = () => { this._schedule(); if (typeof window !== 'undefined') this.start() }
142
+ attachSections(this) // this.contacts, this.name, this.roomDefaults: nothing is read until the app uses one
143
+ }
144
+
145
+ get enabled() { return this._backup.enabled }
146
+ /** This device's id in the account (stable while its state is kept). */
147
+ get deviceId() { return (this._backup._s && this._backup._s.device && this._backup._s.device.id) || '' }
148
+ /** The account's rooms: [{ room, link, kind, label?, shared?, archived? }] — archived ones included, so filter as you like. */
149
+ get rooms() { return this._backup.rooms }
150
+ /** The account's devices: [{ id, name, seenAt, signedOut, current }]. */
151
+ get devices() {
152
+ return Object.entries(this._devices).map(([id, d]) => ({ id, name: d.name || '', seenAt: num(d.seenAt), signedOut: !!d.out, current: id === this.deviceId, ...(typeof d.sdk === 'string' && d.sdk ? { sdk: d.sdk } : {}) }))
153
+ .sort((x, y) => y.seenAt - x.seenAt)
154
+ }
155
+
156
+ /** The member's linked lanes (lane.link), on every device: [{ a, b, cap? }] — two lane rooms. Links run where BOTH lanes
157
+ * are open, so a device that opens them links them again: `laneA.link(laneB)` for each pair listed here. */
158
+ get links() { return ((this._backup._s && this._backup._s.links) || []).filter((l) => !l.removed).map(({ a, b, cap }) => ({ a, b, ...(Number.isFinite(cap) ? { cap } : {}) })) }
159
+
160
+ /** @private the account's usage key (null until the index has given one) — and with the ones it replaced, for collecting. */
161
+ _usageKey() { const s = this._backup._s; return (s && normUsageKey(s.usage)) || null }
162
+ _usageKeys() { const s = this._backup._s; return s ? [normUsageKey(s.usage), ...((s.usageOld || []).map(normUsageKey))].filter(Boolean) : [] }
163
+
164
+ _noteLink(a, b, cap) {
165
+ const s = this._backup._s; if (!s) return
166
+ const k = linkKey(a, b)
167
+ const prev = (s.links || []).find((l) => linkKey(l.a, l.b) === k)
168
+ if (prev && !prev.removed && prev.cap === cap) return
169
+ s.links = [...(s.links || []).filter((l) => linkKey(l.a, l.b) !== k), { a, b, cap, at: Date.now() }].slice(-200)
170
+ this._backup._changed(); this._schedule()
171
+ }
172
+ _dropLink(a, b) {
173
+ const s = this._backup._s; if (!s) return
174
+ const k = linkKey(a, b)
175
+ s.links = [...(s.links || []).filter((l) => linkKey(l.a, l.b) !== k), { a, b, removed: true, at: Date.now() }].slice(-200)
176
+ this._backup._changed(); this._schedule()
177
+ }
178
+
179
+ /** Mark a room archived (or not) on every device. It stays in the account and in the backup. */
180
+ archive(room, on = true) { return this._edit(room, (r) => ({ ...r, archived: !!on })) }
181
+ pin(room, on = true) { return this._edit(room, (r) => ({ ...r, pinned: !!on, pinnedAt: Math.max(Date.now(), num(r.pinnedAt) + 1) })) }
182
+ /** Rename a room in the account (the label a restore and your list show). */
183
+ rename(room, label) { return this._edit(room, (r) => ({ ...r, label: String(label || '').slice(0, 120), renamed: true })) }
184
+ /** Drop a room from the account on EVERY device — the room itself is not deleted (that is wb.rooms.delete, for a
185
+ * tenant). Opening its link again later brings it back. */
186
+ forget(room) { this._backup.remove(room); return this }
187
+ async repairNames() { return this._repairNames(this._readName) }
188
+ async _repairNames(read) {
189
+ const state = this._backup._s
190
+ if (!state || !this.enabled) return 0
191
+ const rows = () => this._backup._s === state ? state.rooms : []
192
+ const view = r => ({ room: r.room, title: r.label, renamed: r.renamed })
193
+ return healNames({
194
+ rows: () => rows().map(view), latestTitle, titleFromDoc,
195
+ read: async room => {
196
+ const row = rows().find(r => r.room === room)
197
+ return row ? read(row) : null
198
+ },
199
+ apply: (room, title, manual) => {
200
+ const row = rows().find(r => r.room === room)
201
+ if (!row || !isUnnamed(view(row))) return false
202
+ this._edit(room, r => ({ ...r, label: title, renamed: manual }))
203
+ return true
204
+ },
205
+ }, new Set())
206
+ }
207
+ async previewEmptySpaces({ detailed = false } = {}) {
208
+ let unreadable = 0
209
+ const rooms = await findEmptySpaces({ onUnreadable: () => { unreadable++ } }, this._emptyHooks())
210
+ return detailed ? { rooms, unreadable } : rooms
211
+ }
212
+ async removeEmptySpaces({ rooms, confirm } = {}) {
213
+ if (confirm !== true || !Array.isArray(rooms) || rooms.some(id => typeof id !== 'string')) throw fail('confirmation_required', 'Pass the selected room ids and confirm: true')
214
+ const hooks = this._emptyHooks(), selected = new Set(rooms)
215
+ const candidates = hooks.rooms().filter(r => selected.has(r.room))
216
+ return removeEmptySpaces(candidates, hooks)
217
+ }
218
+ async listDevices() {
219
+ const b = this._backup, state = b._s
220
+ const rows = this.devices.map(d => ({ ...d, spk: this._devices[d.id]?.spk || null }))
221
+ if (!b._v2 || b.service !== 'account' || !b.enabled) return rows
222
+ const serviceRows = await b._v2.listDevices(b)
223
+ if (b._s !== state) throw fail('account_changed', 'The account changed while listing devices')
224
+ for (const d of serviceRows || []) {
225
+ if (!d || typeof d.spk !== 'string' || !d.spk) continue
226
+ const indexed = rows.find(r => r.spk === d.spk || (r.current && d.me))
227
+ const registration = { ...(typeof d.state === 'string' ? { state: d.state } : {}), ...(Number.isFinite(d.at) ? { addedAt: d.at * 1000 } : {}) }
228
+ if (indexed) { Object.assign(indexed, { spk: d.spk, ...registration }); continue }
229
+ rows.push({ id: 'service:' + d.spk, spk: d.spk, name: d.label || 'Device', seenAt: 0, ...registration, current: !!d.me, signedOut: false })
230
+ }
231
+ return rows
232
+ }
233
+ async signOutDevice(id, { getCode } = {}) {
234
+ const b = this._backup, state = b._s
235
+ const row = (await this.listDevices()).find(d => d.id === id)
236
+ if (!row || row.current || b._s !== state) throw fail('unknown_device', 'Choose another device currently on this account')
237
+ if (row.spk && b.service === 'account') await b._v2.signOutDevice(b, { spk: row.spk, getCode })
238
+ if (b._s !== state) throw fail('account_changed', 'The account changed during sign-out')
239
+ if (Object.hasOwn(this._devices, id)) this.signOut(id)
240
+ return { revoked: true }
241
+ }
242
+
243
+ /** Sign another device out: at its next sync it drops the account and your app is told (onSignedOut). */
244
+ signOut(deviceId, { reason } = {}) {
245
+ const d = this._devices[deviceId]
246
+ if (!d) throw fail('unknown_device', 'no such device in this account')
247
+ const at = Date.now()
248
+ this._devices[deviceId] = { ...d, out: at, ...(['erased', 'moved'].includes(reason) ? { outWhy: reason } : {}) }
249
+ // KEPT until the index carries it (pass 6, K#7): a sign-out lived only in memory — a page closed before the next write lost it
250
+ const s = this._backup._s
251
+ if (s) { s.outs = { ...(s.outs || {}), [deviceId]: at }; this._backup._changed() }
252
+ this._schedule()
253
+ return this
254
+ }
255
+
256
+ /** Pull the index, merge, push what this device knows that it lacks. → { ok, rooms, devices } — ok:false (nothing
257
+ * written) when the index could not be READ, so a failed read can never cost the account its list. */
258
+ /** WHAT THIS ACCOUNT USED in a month, across its rooms and whoever paid (docs/usage-receipts.md — the app's Settings → Your
259
+ * usage; the owner, 2026-10-23: a builder's app records it too). Every turn this account's devices send carries a
260
+ * receipt address; the server seals each reply's cost to it, in the room. This folds the new receipts into the account's
261
+ * monthly sidecar (kept in the index room, sealed like the index) and reads the month.
262
+ * @param {object} [o] { month?: 'YYYY-MM' } (default this month, UTC)
263
+ * → { month, replies, costMicros, costUsd, byPayer: { you, admin, app, witbitz } (micros), byDay, in, out } */
264
+ async usage({ month } = {}) {
265
+ if (!this.enabled) throw fail('not_enabled', 'turn the account on first (wb.backup.enable or restore)')
266
+ const m = month === undefined ? monthOf(Date.now()) : String(month)
267
+ if (!/^\d{4}-(0[1-9]|1[0-2])$/.test(m)) throw fail('invalid_argument', 'month is YYYY-MM')
268
+ await this.sync() // the usage key comes from the index (made by the first device that finds none)
269
+ const loc = await this._where(), c = this._client()
270
+ const vOf = new Map() // name → the version last read: a write lands only over it (sync sweep 11-08 #32); collectUsage reads back and retries
271
+ const readDoc = async (name) => {
272
+ const r = await c.state(loc.room, loc.mk, name)
273
+ if (!r || r.status !== 200) throw fail('unreadable', 'the usage record could not be read', { status: r && r.status })
274
+ if (Number.isInteger(r.v)) vOf.set(name, r.v); else vOf.delete(name)
275
+ const st = r.state
276
+ return st == null || (typeof st === 'object' && !Object.keys(st).length) ? null : openDoc(loc.key, st)
277
+ }
278
+ const writeDoc = async (name, doc) => {
279
+ const w = await c.state(loc.room, loc.mk, name, await sealDoc(loc.key, doc), 'usage', 'device', vOf.has(name) ? vOf.get(name) : undefined)
280
+ if (!w || w.status !== 200) throw fail('save_failed', 'the usage record could not be saved', { status: w && w.status })
281
+ }
282
+ if (typeof c.receipts === 'function') {
283
+ const rooms = this.rooms.map((r) => r.room)
284
+ for (const key of this._usageKeys()) await collectUsage({ key, rooms, read: (room, drop, since) => c.receipts(room, drop, since), ack: (room, drop, upTo) => c.receiptsAck(room, drop, upTo), readDoc, writeDoc, cursor: this._usageCursor }).catch(() => null)
285
+ }
286
+ const t = usageTotals(await readDoc(docNameFor(m)))
287
+ return { month: m, ...t, costUsd: t.costMicros / 1e6 }
288
+ }
289
+
290
+ async sync() {
291
+ if (!this._backup.enabled) throw fail('not_enabled', 'no account on this device — call wb.backup.enable() or restore({ code }) first')
292
+ // A CHANGE MADE WHILE A PASS IS OUT (pass 6, K#7): the running pass may have read and merged before it — it was left for
293
+ // the next sync (a minute). One more pass runs as soon as this one settles, and the caller waits for that one.
294
+ if (this._running) {
295
+ if (!this._again) this._again = this._running.catch(() => null).then(() => { this._again = null; return this.enabled ? this.sync() : { ok: false, rooms: this.rooms, devices: this.devices } })
296
+ return this._again
297
+ }
298
+ this._running = this._sync().finally(() => { this._running = null; this._syncSettled?.() })
299
+ return this._running
300
+ }
301
+
302
+ /** Keep in step on their own: a sync every `every` ms while the page is visible, and when it becomes visible. */
303
+ start({ every = 60_000 } = {}) {
304
+ this.stop()
305
+ if (typeof setInterval !== 'function') return this
306
+ const visible = () => typeof document === 'undefined' || document.visibilityState !== 'hidden'
307
+ this._poll = setInterval(() => { if (this.enabled && visible()) this.sync().catch((e) => { this.lastError = e }) }, Math.max(5_000, every))
308
+ if (typeof document !== 'undefined' && document.addEventListener) {
309
+ this._onVis = () => { if (this.enabled && visible()) this.sync().catch((e) => { this.lastError = e }) }
310
+ document.addEventListener('visibilitychange', this._onVis)
311
+ }
312
+ this._listen()
313
+ return this
314
+ }
315
+
316
+ // The socket on the index room's stream: any write to the index (another device's, or this one's) → sync now.
317
+ _listen() {
318
+ const l = this._live && this._live()
319
+ if (!l || !l.WebSocketImpl || this._stream || !this.enabled) return
320
+ const master = this._backup._s.master
321
+ this._where().then((loc) => {
322
+ if (this._stream || !this.enabled || this._backup._s.master !== master || !this._poll) return
323
+ this._stream = this._openStream({
324
+ mk: loc.mk, path: 's', WebSocketImpl: l.WebSocketImpl,
325
+ onEvent: (ev) => { if (ev && ev.k === 'poll' && this.enabled) this.sync().catch((e) => { this.lastError = e }) },
326
+ })
327
+ }).catch(() => { /* the poll still runs */ })
328
+ }
329
+ stop() {
330
+ if (this._poll) { clearInterval(this._poll); this._poll = null }
331
+ if (this._onVis && typeof document !== 'undefined') { document.removeEventListener('visibilitychange', this._onVis); this._onVis = null }
332
+ clearTimeout(this._pushT); this._pushT = null
333
+ if (this._stream) { try { this._stream.stop() } catch { /* */ } this._stream = null }
334
+ return this
335
+ }
336
+
337
+ // ── internals ───────────────────────────────────────────────────────────────────────────────────────────────────
338
+ _edit(room, fn) {
339
+ const s = this._backup._s
340
+ const i = s ? s.rooms.findIndex((r) => r.room === room) : -1
341
+ if (i < 0) throw fail('unknown_room', 'that room is not in this account')
342
+ s.rooms[i] = { ...fn(s.rooms[i]), at: Date.now() }
343
+ this._backup._schedule()
344
+ return this
345
+ }
346
+ _schedule() { if (!this.enabled) return; clearTimeout(this._pushT); this._pushT = setTimeout(() => { this._pushT = null; this.sync().catch((e) => { this.lastError = e }) }, 300) }
347
+
348
+ async _where() {
349
+ const master = this._backup._s.master
350
+ if (!this._loc || this._loc.master !== master) this._loc = { master, ...(await indexRoomOf(master)), app: await appStoreKey(ub64(master)) }
351
+ return this._loc
352
+ }
353
+ _me() {
354
+ const s = this._backup._s
355
+ if (!s.device || !s.device.id) { s.device = { id: 'd_' + b64url(crypto.getRandomValues(new Uint8Array(9))), name: this._deviceName }; this._backup._changed() }
356
+ if (this._deviceName && s.device.name !== this._deviceName) { s.device = { ...s.device, name: this._deviceName }; this._backup._changed() }
357
+ return s.device
358
+ }
359
+ async _read(loc, name = DOC, key = loc.key) {
360
+ const c = this._client()
361
+ let r
362
+ try { r = await c.state(loc.room, loc.mk, name) } catch { return { ok: false } }
363
+ if (!r || r.status !== 200) return { ok: false, status: r && r.status }
364
+ const st = r.state
365
+ const v = Number.isInteger(r.v) ? r.v : 0 // the version this read saw — the write is conditional on it
366
+ if (st == null || (typeof st === 'object' && !Object.keys(st).length)) return { ok: true, doc: null, v }
367
+ try { return { ok: true, doc: await openDoc(key, st), v } } catch { return { ok: false, unopenable: true } }
368
+ }
369
+ async _ensureRoom(loc) {
370
+ if (loc.made) return
371
+ try { await this._client().create({ room: loc.room, mk: loc.mk }, { base: this._viewer || undefined }) } catch (e) { if (!/409|exists/.test(String(e && e.message))) throw e }
372
+ loc.made = true
373
+ }
374
+ // Read → merge → write ONLY IF the index has not moved since the read (ifV); another device that wrote in between makes
375
+ // the server answer 409, and the merge runs again on what it wrote — two devices syncing at once both keep their rooms
376
+ // (a reviewer's finding, 2026-10-05; spaces/test/sdkAccountIndex.test.mjs).
377
+ async _sync() {
378
+ for (let i = 0; i < 5; i++) {
379
+ const r = await this._syncOnce()
380
+ if (!r.conflict) { if (r.ok && !r.signedOut) await refreshSections(this); return r } // a section in use: read again (its 'change' event)
381
+ await new Promise((res) => setTimeout(res, 20 + Math.floor(Math.random() * 80) * (i + 1)))
382
+ }
383
+ this.lastError = fail('save_failed', 'the account index kept changing under this device — try again', { status: 409 })
384
+ return { ok: false, rooms: this.rooms, devices: this.devices }
385
+ }
386
+ async _syncOnce() {
387
+ // ★ ONE ACCOUNT PER PASS (pass 6, docs/state-machines.md K#2): a vault switching accounts swaps the backup's state (_adopt,
388
+ // _drop, restore) while a pass awaits; the pass then merged account B's rooms into account A's index under A's key, and A's
389
+ // rooms into B's backup. The pass keeps the state it began with and stops the moment another is in its place.
390
+ const s0 = this._backup._s
391
+ const moved = () => this._backup._s !== s0
392
+ const stopped = () => ({ ok: false, rooms: this.rooms, devices: this.devices })
393
+ if (!s0) return stopped()
394
+ const loc = await this._where()
395
+ if (moved()) return stopped()
396
+ // CREATE BEFORE THE FIRST READ, once per device (an existing room answers 409). A read of an unknown room is not
397
+ // refused — the server adopts it with no owner — so waiting for a 404 would leave the index outside the app's tenant.
398
+ const me0 = this._me()
399
+ if (!me0.made) {
400
+ try { await this._ensureRoom(loc) } catch (e) { this.lastError = e; return { ok: false, rooms: this.rooms, devices: this.devices } }
401
+ if (moved()) return stopped()
402
+ this._backup._s.device = { ...me0, made: true }; this._backup._changed()
403
+ }
404
+ const got = await this._read(loc)
405
+ if (moved()) return stopped()
406
+ // THE ACCOUNT WAS DELETED while this device was away (sync sweep 2026-11-18 #11): its index answers 410 — twice, a minute apart,
407
+ // and this device signs itself out as erased, as the app does (indexGone.js, the one rule)
408
+ {
409
+ const s0 = this._backup._s || {}, g = indexGoneStep(s0.indexGoneAt || 0, got.ok ? 200 : got.status)
410
+ if ((s0.indexGoneAt || 0) !== g.first) { if (g.first) s0.indexGoneAt = g.first; else delete s0.indexGoneAt; this._backup._changed() }
411
+ if (g.erased) return this._signedOut('erased')
412
+ }
413
+ const gotX = got.ok ? await this._read(loc, APP_DOC, loc.app) : got // the app-format doc: the same clobber rule — unknown is not empty
414
+ if (moved()) return stopped()
415
+ if (!gotX.ok) { this.lastError = fail(gotX.unopenable ? 'unopenable' : 'unreadable', gotX.unopenable ? 'the account index could not be opened' : 'the account index could not be read', { status: gotX.status }); return { ok: false, rooms: this.rooms, devices: this.devices } }
416
+ const old = got.doc ? { rooms: got.doc.rooms || [], tomb: got.doc.tomb || [], links: got.doc.links || [], devices: got.doc.devices || {}, usage: normUsageKey(got.doc.usage), usageOld: (got.doc.usageOld || []).map(normUsageKey).filter(Boolean) } : { rooms: [], tomb: [], links: [], devices: {}, usage: null, usageOld: [] }
417
+ const fromApp = fromAppIndex(gotX.doc)
418
+ const remote = { ...mergeIndex(old, fromApp), ...mergeUsage(old, fromApp) } // READ-THROUGH: both docs, the newer of each entry (one rule, mergeIndex)
419
+ const s = this._backup._s
420
+ const me = this._me()
421
+ const mine = this._devices[me.id] || {}
422
+ // a sign-out this device made and kept (K#7): back into the list after a reload, until the index carries it
423
+ const outs = s.outs || {}
424
+ const localDevices = { ...this._devices }
425
+ for (const [id, at] of Object.entries(outs)) { const d = localDevices[id] || remote.devices[id]; if (d && num(d.out) < at) localDevices[id] = { ...d, out: at } }
426
+ const local = { rooms: s.rooms, tomb: s.tomb || [], links: s.links || [], devices: { ...localDevices, [me.id]: { ...mine, name: me.name || mine.name || '', seenAt: num(mine.seenAt), ...(typeof this._spk === 'string' && this._spk ? { spk: this._spk } : {}), ...(this._version ? { sdk: this._version } : {}) } } }
427
+ const merged = mergeIndex(local, remote)
428
+ // the usage key: made by the first device that finds none — only after this DEFINITIVE read, so two keys meet only in a race
429
+ Object.assign(merged, mergeUsage({ usage: s.usage, usageOld: s.usageOld }, remote))
430
+ if (!merged.usage) merged.usage = await newUsageKey()
431
+ if (moved()) return stopped()
432
+ const self = merged.devices[me.id]
433
+ if (self.out) return this._signedOut(['erased', 'moved'].includes(self.outWhy) ? self.outWhy : undefined)
434
+ if (Date.now() - num(self.seenAt) > SEEN_EVERY) merged.devices[me.id] = { ...self, seenAt: Date.now() }
435
+ const before = canon({ rooms: s.rooms, tomb: s.tomb || [], links: s.links || [], devices: this._devices, usage: s.usage, usageOld: s.usageOld })
436
+ const usageBefore = usageCanon(s)
437
+ const roomsBefore = canon({ rooms: s.rooms, tomb: s.tomb || [] })
438
+ this._devices = merged.devices
439
+ s.rooms = merged.rooms; s.tomb = merged.tomb; s.links = merged.links; s.usage = merged.usage; s.usageOld = merged.usageOld
440
+ const after = canon(merged)
441
+ // DUAL WRITE: the old doc for every older release, then the app's; each only when it differs from what it holds, each over
442
+ // the version read. A 409 on either re-reads both and merges again.
443
+ const appDoc = toAppIndex(merged, gotX.doc)
444
+ for (const [differs, name, key, body, v] of [[after !== canon(old), DOC, loc.key, { v: 1, rooms: merged.rooms, tomb: merged.tomb, links: merged.links, devices: merged.devices, usage: merged.usage, ...(merged.usageOld.length ? { usageOld: merged.usageOld } : {}) }, got.v],
445
+ [!sameAppIndex(appDoc, gotX.doc), APP_DOC, loc.app, { ...appDoc, at: Date.now() }, gotX.v]]) {
446
+ if (!differs) continue
447
+ const w = await this._client().state(loc.room, loc.mk, name, await sealDoc(key, body), 'account index', 'device', v)
448
+ if (w && w.status === 409) return { conflict: true } // the merged state is kept locally; the next pass re-reads and merges again
449
+ if (!w || w.status !== 200) { this.lastError = fail('save_failed', 'the account index could not be saved', { status: w && w.status }); return { ok: false, rooms: this.rooms, devices: this.devices } }
450
+ }
451
+ // the index now carries each kept sign-out (written above, or it already had it) — or the device is gone from it: let go
452
+ if (Object.keys(outs).length) {
453
+ const left = Object.fromEntries(Object.entries(outs).filter(([id, at]) => merged.devices[id] && num(merged.devices[id].out) < at))
454
+ if (Object.keys(left).length) s.outs = left; else delete s.outs
455
+ this._backup._changed()
456
+ }
457
+ if (canon({ rooms: merged.rooms, tomb: merged.tomb }) !== roomsBefore) this._backup._persist() // the vault copy holds rooms + tombs, not devices
458
+ if (usageCanon(merged) !== usageBefore) this._backup._changed() // this device keeps the account's usage key
459
+ if (after !== before) { if (canon({ links: merged.links }) !== canon({ links: local.links })) this._backup._changed(); if (typeof this.onChange === 'function') { try { this.onChange({ rooms: this.rooms, devices: this.devices }) } catch { /* the app's callback */ } } }
460
+ this.lastError = null
461
+ return { ok: true, rooms: this.rooms, devices: this.devices }
462
+ }
463
+ _signedOut(reason) {
464
+ this.stop()
465
+ this._devices = {}
466
+ this._backup._drop()
467
+ if (typeof this.onSignedOut === 'function') { try { this.onSignedOut(reason ? { reason } : undefined) } catch { /* the app's callback */ } }
468
+ return { ok: true, signedOut: true, rooms: [], devices: [], ...(reason ? { reason } : {}) }
469
+ }
470
+ }
@@ -0,0 +1,81 @@
1
+ // sdkAccountDoc.js — the SDK's live account index IN THE SPACES APP'S FORMAT (docs/sdk-account-format-plan.md phase 3; the
2
+ // owner, 2026-11-13: "yes. Do 1-5"). The SDK keeps its index in its DERIVED room (sdkAccount.js indexRoomOf), and there it now
3
+ // also keeps the app's `xindex` doc, built by the app's own rules (accountIndexDoc.js), sealed under the app's account-store
4
+ // key. Pure: the SDK's view ({ rooms[], tomb[], links[], devices{}, usage, usageOld }) ↔ the app's doc, both ways.
5
+ //
6
+ // TRANSLATE, DO NOT DROP (§4.1): a room's entry is the app's ({ mk, title, titleAt, manual, at, archived, archivedAt, pinned,
7
+ // pinnedAt }) plus what only the SDK reopens a room with — `link`, `kind`, a lane's `shared`, a label the app's title cannot
8
+ // hold, a split room's ASSEMBLED key (decision 5). A forgotten room is `forgot: <at>` — the SDK's RE-OPENABLE mark — never the
9
+ // app's final `deleted` (decision 4). Devices: { name, seenAt, out } ↔ { label, lastSeenAt } + `signouts`; `sdk` (the release a
10
+ // device runs) rides along. Entries the SDK cannot read (no link, no mark) are carried over as they were.
11
+ import { indexDoc, indexRoomEntry } from './accountIndexDoc.js'
12
+ import { keyInLink, roomPin } from './accountRecord.js'
13
+ import { normUsageKey } from './usageReceipts.js'
14
+
15
+ export const APP_DOC = 'xindex' // the app's sealed 'index' (accountStores.js SEALED)
16
+ const ERASED_MARK = '@erased' // = devices.js ERASED_MARK: Delete my account's pseudo-entry in the index's sign-outs
17
+ const MOVED_MARK = '@moved'
18
+ const num = (x) => (Number.isFinite(x) && x > 0 ? x : 0)
19
+ const obj = (x) => (x && typeof x === 'object' && !Array.isArray(x) ? x : {})
20
+
21
+ /** The SDK's view → the app's `xindex` doc. `prev`: the doc as read (its fields the SDK does not own are kept). */
22
+ export function toAppIndex ({ rooms = [], tomb = [], links = [], devices = {}, usage, usageOld = [] } = {}, prev = null) {
23
+ const p = obj(prev), map = {}
24
+ for (const r of rooms) {
25
+ if (!r || !r.room || typeof r.link !== 'string' || !r.link) continue
26
+ const mk = keyInLink(r.link) || (typeof r.mk === 'string' ? r.mk : '')
27
+ const at = num(r.at), e = indexRoomEntry({ room: r.room, title: r.label || '', titleAt: at, ...roomPin(r), renamed: typeof r.renamed === 'boolean' ? r.renamed : !!(r.label && r.label !== 'Space' && r.label !== r.room), at, archived: !!r.archived, archivedAt: at }, obj(p.rooms)[r.room] || undefined, mk ? { mk } : {}) // prev: the app's per-field rules, and the "always on" mark it keeps (sync sweep 2026-11-23 #13 — every SDK write dropped it)
28
+ map[r.room] = { ...e, link: r.link, kind: r.kind === 'lane' ? 'lane' : 'space', ...(r.kind === 'lane' && r.shared ? { shared: r.shared } : {}), ...(r.label && e.title !== r.label ? { label: r.label } : {}) }
29
+ }
30
+ for (const t of tomb) if (t && t.room) map[t.room] = { ...(map[t.room] || {}), forgot: Math.max(num(t.at), num((map[t.room] || {}).forgot)) || 1 }
31
+ for (const [room, e] of Object.entries(obj(p.rooms))) if (!(room in map) && e && typeof e === 'object' && !e.link && !e.forgot) map[room] = e
32
+ // SIGN-OUTS ARE CARRIED, NOT REBUILT (sync sweep 11-18): the app's marks ride here too — `@erased` (Delete my account: every other
33
+ // device signs out) and `@moved` — and a device the SDK's view does not list. Rebuilt from the SDK's devices alone, an SDK write
34
+ // between the app's mark and the index's deletion dropped it. A mark only grows (the later time wins).
35
+ // A DEVICE SIGNED OUT BECAUSE THE ACCOUNT WAS DELETED (`outWhy: 'erased'`) is the app's ERASED mark too (sync sweep 11-22 #8): the
36
+ // app reads only the mark (devices.js remoteSignoutReason — a stamp no newer than it is 'erased'), so an app device of an account
37
+ // deleted through the SDK said "signed out remotely".
38
+ const devs = {}, signouts = {}
39
+ let erasedAt = 0, movedAt = 0
40
+ for (const [id, at] of Object.entries(obj(p.signouts))) if (num(at)) signouts[id] = at
41
+ for (const [id, d] of Object.entries(obj(devices))) {
42
+ if (!d || typeof d !== 'object') continue
43
+ const { name, seenAt, out, ...rest } = d
44
+ devs[id] = { ...rest, ...(name !== undefined ? { label: name } : {}), ...(seenAt !== undefined ? { lastSeenAt: seenAt } : {}) }
45
+ if (num(out)) signouts[id] = Math.max(out, num(signouts[id]))
46
+ if (num(out) && rest.outWhy === 'erased') erasedAt = Math.max(erasedAt, signouts[id])
47
+ if (num(out) && rest.outWhy === 'moved') movedAt = Math.max(movedAt, signouts[id])
48
+ }
49
+ if (erasedAt) signouts[ERASED_MARK] = Math.max(erasedAt, num(signouts[ERASED_MARK]))
50
+ if (movedAt) signouts[MOVED_MARK] = Math.max(movedAt, num(signouts[MOVED_MARK]))
51
+ const u = normUsageKey(usage)
52
+ return { ...indexDoc({ rooms: map, devices: devs, signouts, name: typeof p.name === 'string' ? p.name : '', seen: p.seen, vseen: p.vseen, inviteKey: p.inviteKey, usageKey: u, usageKeysOld: (usageOld || []).map(normUsageKey).filter(Boolean), pipesRoom: p.pipesRoom, msgsRoom: p.msgsRoom }),
53
+ ...(Array.isArray(links) && links.length ? { links } : {}) }
54
+ }
55
+
56
+ /** The app's `xindex` doc (as the SDK wrote it) → the SDK's view; an empty view for none. */
57
+ export function fromAppIndex (doc) {
58
+ const d = obj(doc), rooms = [], tomb = []
59
+ for (const [room, e] of Object.entries(obj(d.rooms))) {
60
+ if (!e || typeof e !== 'object') continue
61
+ const deletedAt = Math.max(num(e.forgot), e.deleted ? num(e.at) : 0)
62
+ if (deletedAt) tomb.push({ room, at: deletedAt })
63
+ if (typeof e.link !== 'string' || !e.link || e.deleted) continue
64
+ const label = e.label !== undefined ? e.label : (e.title && e.title !== 'Space' && e.title !== room || e.manual ? e.title : undefined)
65
+ rooms.push({ room, ...roomPin(e), ...(num(e.at) ? { at: e.at } : {}), ...(e.archived ? { archived: true } : {}), link: e.link, kind: e.kind === 'lane' ? 'lane' : 'space',
66
+ ...(label ? { label } : {}), ...(label && !e.manual ? { renamed: false } : e.manual && (label === 'Space' || label === room) ? { renamed: true } : {}), ...(e.kind === 'lane' && e.shared ? { shared: e.shared } : {}), ...(typeof e.mk === 'string' && e.mk && e.mk !== keyInLink(e.link) ? { mk: e.mk } : {}) })
67
+ }
68
+ // …and the app's ERASED mark is the SDK's reason (#8): an SDK device whose stamp is no newer than the mark was signed out by Delete my
69
+ // account in the app — its onSignedOut hears { reason: 'erased' }, as when the SDK deleted it
70
+ const devices = {}, so = obj(d.signouts), erased = num(so[ERASED_MARK]), moved = num(so[MOVED_MARK])
71
+ for (const [id, e] of Object.entries(obj(d.devices))) {
72
+ if (!e || typeof e !== 'object') continue
73
+ const { label, lastSeenAt, ...rest } = e
74
+ devices[id] = { ...rest, ...(label !== undefined ? { name: label } : {}), ...(lastSeenAt !== undefined ? { seenAt: lastSeenAt } : {}), ...(num(so[id]) ? { out: so[id] } : {}), ...(num(so[id]) && erased >= so[id] ? { outWhy: 'erased' } : num(so[id]) && moved >= so[id] ? { outWhy: 'moved' } : {}) }
75
+ }
76
+ return { rooms, tomb, links: Array.isArray(d.links) ? d.links : [], devices, usage: normUsageKey(d.usageKey), usageOld: (Array.isArray(d.usageKeysOld) ? d.usageKeysOld : []).map(normUsageKey).filter(Boolean) }
77
+ }
78
+
79
+ const stable = (x) => (Array.isArray(x) ? '[' + x.map(stable).join(',') + ']' : x && typeof x === 'object' ? '{' + Object.keys(x).filter((k) => x[k] !== undefined).sort().map((k) => JSON.stringify(k) + ':' + stable(x[k])).join(',') + '}' : JSON.stringify(x))
80
+ /** The same doc, its write time and key order aside (the app's sameDoc rule) — an unknown doc is never the same. */
81
+ export const sameAppIndex = (a, b) => !!(a && b) && stable({ ...a, at: 0 }) === stable({ ...b, at: 0 })