@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/store.js ADDED
@@ -0,0 +1,587 @@
1
+ // store.js — local data-persistence layer (Verified-Client Phase 1). Recents, contacts, the hidden
2
+ // room pointers (pipes/index/invite), the name, and lanes flags — all localStorage. saveRecents's
3
+ // durability+sync side effects (queueBackup/scheduleIndexPush) are INJECTED via setRecentsSaveHook.
4
+ import { lsGet } from './util.js'
5
+ import { normA2A, mergeA2ARecords } from './a2aCore.js'
6
+ import { unionMarks, mergeSiriRooms, siriKeyOf, siriDefaultOf, mergeByMarks, canon } from './keptMerge.js' // Siri's and the connection keys' merge rules, shared with the vault keep (C3)
7
+ import { state, isTempRoom } from './roomState.js'
8
+
9
+ let _onSave = () => {}
10
+ export const setRecentsSaveHook = (fn) => { _onSave = fn }
11
+
12
+ export const RECENTS_KEY = 'space:recents'
13
+ // MEMORY-FIRST (2026-08-31): iOS can kill the storage process behind a LIVE PWA (memory pressure / low power) — from
14
+ // that moment localStorage reads return EMPTY while the page keeps running, and the drawer 'vanished' mid-session
15
+ // (relaunch reads fine again). Once we've seen data, memory is the source of truth; writes write-through. An empty
16
+ // read can never erase a populated in-memory list.
17
+ // ⛔ BUT MEMORY MUST NOT HIDE ANOTHER WRITER (e2e 2026-11-24: a second direct chat vanished from the list). The list has more than one
18
+ // writer — the app's other pages (the Assistant panel, `?panel=1`, runs its own copy of this module), a second copy of this module
19
+ // under another address, the hosted app's store — and memory-first returned THIS copy's old list for good: its next mutateRecent
20
+ // saved it back, and a Space another writer had just added was gone. So the stored text is checked on every read: unchanged → the
21
+ // same objects (callers that hold a row still see edits to it); changed → read again. Memory answers only when storage cannot be
22
+ // read, or reads back EMPTY while memory has rooms — the dead storage process this was made for.
23
+ let _recMem = null, _recRaw = null
24
+ export const loadRecents = () => {
25
+ let raw = null
26
+ try { raw = localStorage.getItem(RECENTS_KEY) } catch { return _recMem || [] }
27
+ if (raw !== null && raw === _recRaw && _recMem) return _recMem
28
+ let v = null
29
+ try { v = JSON.parse(raw || '[]') } catch { return _recMem || [] }
30
+ if (!Array.isArray(v)) return _recMem || []
31
+ if (!v.length) return _recMem || v // empty while memory has rooms: the storage process died (above) — never an erase
32
+ _recMem = v; _recRaw = raw
33
+ return v
34
+ }
35
+ // ★★ THE LIST IS THE WHOLE ROSTER, NOT A "RECENTS" MENU (the owner, 2026-10-06: "Why do we have the cap?"). It began as a
36
+ // most-recently-opened list (24, then 60 — hidden lanes and negotiations ate 2–3 slots per Space), and then the drawer
37
+ // became where every Space lives while the index room became the account's roster of ALL of them. The two disagreed:
38
+ // the roster knew 204 rooms, the drawer could show 60, and the index sync re-added the other ~144 every 10 s only for
39
+ // this slice to cut them again (a drawer redraw and an index push each time). A room outside the cap came back as a
40
+ // fresh entry without its flags, and the first-message heuristic renamed it (roomTitle.js). Every chat app keeps the
41
+ // full conversation list locally and lets the VIEW handle size; an entry here is ~200 bytes, so a thousand rooms are
42
+ // ~200 KB in a 5 MB store. RECENTS_MAX is a bound against runaway growth, not a menu length — the vault's room-list
43
+ // seed (vault-loader.js) uses the same number.
44
+ export const RECENTS_MAX = 1000
45
+ export const saveRecents = (l) => { _recMem = l.slice(0, RECENTS_MAX); _recRaw = JSON.stringify(_recMem); try { localStorage.setItem(RECENTS_KEY, _recRaw) } catch { /* private mode / dead storage process — memory carries the session */ } _onSave() /* blob = durability; index room = live cross-device sync */ }
46
+ export const recentOf = (r) => loadRecents().find((x) => x.room === r) || null
47
+ // Edit ONE recents entry in place and persist — the single write path for pin/archive/title/lineage stamps.
48
+ export function mutateRecent(r, fn) { const list = loadRecents(); const it = list.find((x) => x.room === r); if (it) { fn(it); saveRecents(list) } }
49
+ // Durable "this invite was already processed" set — the dedup the append-only invite inbox needs. loadRecents can't
50
+ // be that dedup (the cap evicts old rooms) and l1.hasMk can't either (the worker's presence mirror races a cold
51
+ // realm's boot), so without this every poll re-added evicted rooms + re-announced them ("New Space from an invite").
52
+ // Per-device, like recents: a fresh device's empty set correctly lets all its invites materialize once.
53
+ export const INV_SEEN_KEY = 'space:inv-seen'
54
+ export const invSeen = (room) => { try { return JSON.parse(localStorage.getItem(INV_SEEN_KEY) || '[]').includes(room) } catch { return false } }
55
+ export const markInvSeen = (room) => { try { const a = JSON.parse(localStorage.getItem(INV_SEEN_KEY) || '[]'); if (!a.includes(room)) { a.push(room); localStorage.setItem(INV_SEEN_KEY, JSON.stringify(a.slice(-500))) } } catch { /* private mode */ } }
56
+ export const PIPES_ROOM_KEY = 'space:pipes-room'
57
+ export const pipesRoomPtr = () => { try { return JSON.parse(localStorage.getItem(PIPES_ROOM_KEY) || 'null') } catch { return null } }
58
+ export const setPipesRoomPtr = (p) => { try { localStorage.setItem(PIPES_ROOM_KEY, JSON.stringify(p)) } catch { /* */ } }
59
+ // THE MESSAGE ROOM (docs/room-messages.md): the account's third hidden room, beside the index and the pipes rooms —
60
+ // where one room leaves a message for another, for whichever of your devices runs it (roomMail.js).
61
+ export const MSGS_ROOM_KEY = 'space:msgs-room'
62
+ export const msgsRoomPtr = () => { try { return JSON.parse(localStorage.getItem(MSGS_ROOM_KEY) || 'null') } catch { return null } }
63
+ export const setMsgsRoomPtr = (p) => { try { localStorage.setItem(MSGS_ROOM_KEY, JSON.stringify(p)) } catch { /* */ } }
64
+ export const MAIL_HANDLED_KEY = 'space:mail-handled' // the message ids THIS device ran (roomMail dedupe), newest last
65
+ export const INDEX_ROOM_KEY = 'space:index-room'
66
+ export const indexRoomPtr = () => { try { return JSON.parse(localStorage.getItem(INDEX_ROOM_KEY) || 'null') } catch { return null } }
67
+ export const setIndexRoomPtr = (p) => { try { localStorage.setItem(INDEX_ROOM_KEY, JSON.stringify(p)) } catch { /* */ } }
68
+ export const INVITE_KEY = 'space:invitekey'
69
+ export const inviteKeyPtr = () => { try { return JSON.parse(localStorage.getItem(INVITE_KEY) || 'null') } catch { return null } }
70
+ export const setInviteKey = (v) => { try { localStorage.setItem(INVITE_KEY, JSON.stringify(v)) } catch { /* */ } }
71
+ // The ACCOUNT SIGNING KEY (device-key access groundwork). ONE keypair per account: its private half signs a short-lived
72
+ // certificate for each enrolled device, and the server holds only the PUBLIC half (gate record `acct_pk`) — so the
73
+ // server can verify a certificate from ANY device while holding no device list and no device count. Rides the backup
74
+ // blob exactly like inviteKey (which already carries boxPriv), so it restores with the account and every device that
75
+ // restores can mint certificates. Nothing verifies these yet.
76
+ // BACKUP PAUSED (vault only): the equivalent of the non-vault app's "turn off backup on this device" — this device STOPS
77
+ // pushing its account state (index/pipes rooms) to the server while keeping the master + keys, so Spaces still work; new
78
+ // changes stay local until backup is turned back on. Room CONTENT (messages) is the room mechanism, not backup, so it
79
+ // keeps syncing. Per-device flag on the app origin (the app is what gates the pushes); the vault's B&R sheet toggles it.
80
+ export const BACKUP_PAUSED_KEY = 'space:backup-paused'
81
+ export const backupPaused = () => { try { return localStorage.getItem(BACKUP_PAUSED_KEY) === '1' } catch { return false } }
82
+ export const setBackupPausedFlag = (on) => { try { on ? localStorage.setItem(BACKUP_PAUSED_KEY, '1') : localStorage.removeItem(BACKUP_PAUSED_KEY) } catch { /* */ } }
83
+ export const ACCT_KEY = 'space:acctkey'
84
+ export const acctKey = () => { try { return JSON.parse(localStorage.getItem(ACCT_KEY) || 'null') } catch { return null } }
85
+ export const setAcctKey = (v) => { try { localStorage.setItem(ACCT_KEY, JSON.stringify(v)) } catch { /* */ } }
86
+ export const lanesKey = (r) => 'space:lanes:' + r
87
+ // THE SPACES THE CLOUD DEVICE KEEPS ALWAYS ON — a fact of the ACCOUNT (the owner, 2026-11-22: "We need to know in every device which
88
+ // rooms are always on"): the Space's own row in the account's room list carries it (`alwaysOn`, with its clock `alwaysOnAt`; synced by
89
+ // accountIndexDoc.js like a pin). The device of yours that hands a Space to the cloud device, or takes it back, sets it; every device
90
+ // refuses what a kept Space cannot have — people, private rooms, links — and the Spaces list shows it. It used to be a list on ONE device
91
+ // (`space:cd-kept`, from the card's last answer): another device could link a kept Space. That list is dropped when the card next reads
92
+ // what the device runs (adoptCloudKept, below).
93
+ const CD_KEPT_OLD = 'space:cd-kept'
94
+ export const isCloudKept = (r) => !!r && !!((recentOf(r) || {}).alwaysOn)
95
+ /** Set or clear a Space's always-on mark in the account's room list (→ synced to every device). Only a change is written. */
96
+ export function setAlwaysOn (r, on, now = Date.now()) {
97
+ if (!r || isCloudKept(r) === !!on) return false
98
+ mutateRecent(r, (it) => { it.alwaysOn = !!on; it.alwaysOnAt = now })
99
+ return isCloudKept(r) === !!on
100
+ }
101
+ /** The cloud device was signed out (here, or from the hosted vault's account screen): no Space is kept any more. */
102
+ export function clearAlwaysOn (now = Date.now()) { for (const r of loadRecents()) if (r && r.alwaysOn) setAlwaysOn(r.room, false, now) }
103
+ /** The cloud device answered which Spaces it holds (its card): a Space it runs is kept, so its mark is set (a Space kept before the
104
+ * mark existed arrives here). A Space it does NOT hold keeps its mark: that is the card's warning to show (the device let it go, or
105
+ * was signed out) — never a silent change. The old one-device list is dropped. */
106
+ export function adoptCloudKept (rooms, now = Date.now()) {
107
+ for (const r of new Set((rooms || []).filter((x) => typeof x === 'string'))) setAlwaysOn(r, true, now)
108
+ try { localStorage.removeItem(CD_KEPT_OLD) } catch { /* */ }
109
+ }
110
+ export const KEPT_NO_LINKS = 'Your cloud device keeps this Space always on, and it takes only a Space with no private lane of its own. Stop keeping it always on first (⋯ → Assistant → Always on).'
111
+ export const KEPT_NO_PEOPLE = 'Your cloud device keeps this Space always on, and it takes only a Space that is yours alone. Stop keeping it always on first (⋯ → Assistant → Always on).'
112
+ export const wantsLanes = (r) => { try { return localStorage.getItem(lanesKey(r)) === '1' } catch { return false } }
113
+ export const CONTACTS_KEY = 'space:contacts'
114
+ export function normContact(c) {
115
+ if (!c || typeof c !== 'object') return null
116
+ if (c.kind === 'agent') {
117
+ const id = String(c.id || '').trim().slice(0, 64); const fn = String(c.fn || c.name || '').trim().slice(0, 80)
118
+ if (!id || !fn) return null
119
+ return { kind: 'agent', id, fn, persona: String(c.persona || '').slice(0, 4000), agentName: String(c.agentName || fn).trim().slice(0, 80), ...(c.model ? { model: String(c.model).slice(0, 40) } : {}), ...(c.color ? { color: String(c.color).slice(0, 16) } : {}), ...(c.at ? { at: +c.at || 0 } : {}), deleted: !!c.deleted } // `deleted` = a TOMBSTONE for a removed assistant; ALWAYS present so the LWW merge (Object.assign) can clear it on a revive
120
+ }
121
+ // A PERSON is addressed by an email, a public "@username" (docs/spaces-usernames.md §5), or both. The username is
122
+ // stored WITHOUT the "@" and only when it is one; a row with neither address is not a contact.
123
+ const email = (typeof c.email === 'string' && c.email.indexOf('@') > 0) ? c.email.trim().toLowerCase() : ''
124
+ const username = (typeof c.username === 'string' && /^[a-z0-9][a-z0-9_]{2,29}$/.test(String(c.username).trim().toLowerCase().replace(/^@/, ''))) ? String(c.username).trim().toLowerCase().replace(/^@/, '') : ''
125
+ if (!email && !username) return null
126
+ return { kind: 'person', fn: typeof c.fn === 'string' ? c.fn.trim().slice(0, 80) : '', ...(email ? { email } : {}), ...(username ? { username } : {}), ...(typeof c.handle === 'string' && /^[A-Za-z0-9_-]{43}$/.test(c.handle) ? { handle: c.handle } : {}), ...(c.tel ? { tel: String(c.tel).slice(0, 40) } : {}), ...(c.at ? { at: +c.at || 0 } : {}), deleted: !!c.deleted } // `deleted` = a TOMBSTONE for a removed person; `at` gives persons LWW so a delete/edit survives the union merge
127
+ }
128
+ // The one key a contact is deduped and merged by: an agent by id, a person by email, else by "@username".
129
+ export const contactKey = (c) => c && (c.kind === 'agent' ? 'a:' + c.id : (c.email || (c.username ? '@' + c.username : undefined)))
130
+ // ONE PERSON, ONE ROW (the owner, 2026-10-25: "I have duplicated contact of <a person>" — "@alice" twice and
131
+ // "alice@example.com · @alice"). A row is keyed by ONE address (contactKey: the email, else the @username), so a copy
132
+ // that knew only the @username — another device's, or one an edit re-keyed without a tombstone — came back as a second row on
133
+ // every sync. Rows that share an email or a username are one person: every address any of them knew (rememberContacts' rule),
134
+ // the newest edit's name and phone (an older one fills a gap), deleted only when the newest of them is a deletion. Read and
135
+ // write both pass through it, so a stored duplicate heals and a synced one never lands.
136
+ export function dedupePeople(list) {
137
+ if (!Array.isArray(list)) return []
138
+ const idx = [], parent = []
139
+ list.forEach((c, i) => { if (c && c.kind === 'person') { idx.push(i); parent[i] = i } })
140
+ if (idx.length < 2) return list
141
+ const find = (i) => { while (parent[i] !== i) { parent[i] = parent[parent[i]]; i = parent[i] } return i }
142
+ const owner = new Map()
143
+ for (const i of idx) {
144
+ const c = list[i]
145
+ for (const k of [c.email && 'e:' + c.email, c.username && 'u:' + c.username]) {
146
+ if (!k) continue
147
+ if (owner.has(k)) parent[find(i)] = find(owner.get(k)); else owner.set(k, i)
148
+ }
149
+ }
150
+ const groups = new Map()
151
+ for (const i of idx) { const r = find(i); if (!groups.has(r)) groups.set(r, []); groups.get(r).push(list[i]) }
152
+ if (groups.size === idx.length) return list
153
+ const merged = new Map() // group root → the one row
154
+ for (const [r, g] of groups) {
155
+ if (g.length === 1) { merged.set(r, g[0]); continue }
156
+ const by = g.slice().sort((a, b) => (b.at || 0) - (a.at || 0)) // newest first
157
+ const pick = (f) => (by.find((c) => c[f]) || {})[f]
158
+ const out = { kind: 'person', fn: pick('fn') || '' }
159
+ for (const f of ['email', 'username', 'handle', 'tel']) { const v = pick(f); if (v) out[f] = v }
160
+ const at = by[0].at || 0; if (at) out.at = at
161
+ out.deleted = !!by[0].deleted
162
+ merged.set(r, out)
163
+ }
164
+ const out = [], placed = new Set()
165
+ list.forEach((c, i) => {
166
+ if (!(c && c.kind === 'person')) { out.push(c); return }
167
+ const r = find(i); if (placed.has(r)) return
168
+ placed.add(r); out.push(merged.get(r)) // the person where its first row was
169
+ })
170
+ return out
171
+ }
172
+ export function loadContacts() { try { const a = JSON.parse(lsGet(CONTACTS_KEY) || '[]'); return Array.isArray(a) ? dedupePeople(a.map(normContact).filter(Boolean)) : [] } catch { return [] } }
173
+ export function saveContacts(list) {
174
+ try { localStorage.setItem(CONTACTS_KEY, JSON.stringify(dedupePeople(list).slice(0, 1000))) } catch { /* private mode */ }
175
+ try { dispatchEvent(new Event('wb-contacts-changed')) } catch { /* no window */ } // the names on messages follow People (senderNames.js)
176
+ }
177
+ // ── CODE-section settings (opencode server URL, password, model, agent) — a per-account personal component, synced in the
178
+ // sealed 'index2' doc of the account's index room exactly like contacts (roomSync.js), so every device of the account
179
+ // connects to the same local server. The password rides too, end-to-end encrypted (owner's decision, 2026-09-12).
180
+ // Last-writer-wins on `mod`: only an edit someone MADE stamps it, so a device that merely holds a copy never outranks it.
181
+ export const CODE_KEY = 'space:code'
182
+ const CODE_FIELDS = ['base', 'pass', 'model', 'agent']
183
+ // `models`: the model chosen for each PAIRED COMPUTER, {computerId: ref}. `model` above is the single direct server's; with
184
+ // computers each has its own (a model one of them lacks fails every turn there), and this map is how that choice follows
185
+ // the account to its other devices. Omitted when empty, so settings from before it are byte-identical.
186
+ const CODE_MODEL_ID = /^[A-Za-z0-9_-]{1,64}$/
187
+ function normCodeModels(m) {
188
+ if (!m || typeof m !== 'object' || Array.isArray(m)) return null
189
+ const o = {}
190
+ for (const [k, v] of Object.entries(m)) {
191
+ if (Object.keys(o).length >= 32) break
192
+ if (CODE_MODEL_ID.test(k) && typeof v === 'string' && v && v.length <= 256) o[k] = v
193
+ }
194
+ return Object.keys(o).length ? o : null
195
+ }
196
+ export function normCodeSettings(s) {
197
+ if (!s || typeof s !== 'object') return null
198
+ const o = {}
199
+ for (const f of CODE_FIELDS) o[f] = typeof s[f] === 'string' ? s[f].slice(0, 2048) : ''
200
+ const models = normCodeModels(s.models)
201
+ if (models) o.models = models
202
+ o.mod = Number.isFinite(+s.mod) ? +s.mod : 0
203
+ return o
204
+ }
205
+ export function loadCodeSettings() { try { return normCodeSettings(JSON.parse(lsGet(CODE_KEY) || 'null')) } catch { return null } }
206
+ export function saveCodeSettings(s) { const n = normCodeSettings(s); if (!n) return null; try { localStorage.setItem(CODE_KEY, JSON.stringify(n)) } catch { /* private mode */ } return n }
207
+ /** The synced copy to adopt over `cur` (normalised), only when it is strictly NEWER — else null. Pure; mergeCodeSettings stores it. */
208
+ export function newerCodeSettings(cur, incoming) {
209
+ const inc = normCodeSettings(incoming)
210
+ if (!inc || !inc.mod) return null
211
+ if (cur && cur.mod >= inc.mod) return null
212
+ return inc
213
+ }
214
+ /** Adopt a synced copy only if it is strictly NEWER. Returns true when the local settings changed. */
215
+ export function mergeCodeSettings(incoming) {
216
+ const inc = newerCodeSettings(loadCodeSettings(), incoming)
217
+ if (!inc) return false
218
+ saveCodeSettings(inc)
219
+ return true
220
+ }
221
+ /** Same values (mod ignored; the model map compared by content, not key order) — so re-saving what is already there never
222
+ * stamps a new edit or pushes, while a different model for one computer does. */
223
+ const codeModelsKey = (m) => JSON.stringify(Object.entries(normCodeModels(m) || {}).sort(([x], [y]) => (x < y ? -1 : x > y ? 1 : 0)))
224
+ export const sameCodeSettings = (a, b) => !!a && !!b && CODE_FIELDS.every((f) => (a[f] || '') === (b[f] || '')) && codeModelsKey(a.models) === codeModelsKey(b.models)
225
+
226
+ // ── Connection callKeys (docs/standing-sentinel.md §3.8): { [id]: { callKey, label, host, account } } — the page's half of
227
+ // a connection the account attached. NEVER the secret (that is inside the Sentinel; normalisation drops any other field).
228
+ // They ride the ACCOUNT the way contacts do — the index2 doc across live devices, the blob backup for a restore — so a
229
+ // second phone can add an attached connection to a Space without re-attaching. Union by id, LOCAL WINS: ids are random
230
+ // per attach, so a detached id is simply dead (the sheet lists from the Sentinel and uses a key only for an id it still
231
+ // has) — harmless at the Sentinel, but the dead key came back on every device (below).
232
+ // ⛔ A DETACH IS RECORDED (the C3 review, 2026-11-13; the owner: "an added optional field, not a format change"). With no mark,
233
+ // a device still holding a detached key put it back: the index push's pre-read merged the remote copy in before writing, a
234
+ // restore filled it, and every device had it again. Now `connGone: { id: at }` rides NEXT TO the keys — `space:connectionKeys:gone`
235
+ // here, a field of its own in index2 and the backup — and an entry may carry `at` (when it was attached here). The keep's rule
236
+ // (keptMerge.js mergeByMarks): an entry is off when a mark is as new or newer (an entry with no `at` is older than any mark);
237
+ // a re-attach after the mark wins. An older app ignores both: its normalisation keeps four fields and never reads `connGone`.
238
+ // No marks (no one has detached since) → exactly the old union.
239
+ export const CONNKEYS_KEY = 'space:connectionKeys'
240
+ export const CONNGONE_KEY = 'space:connectionKeys:gone' // under the keys' own prefix: durable in the hosted app (durableStore.js) as they are
241
+ const CONN_ID = /^[A-Za-z0-9_-]{1,64}$/
242
+ // ⚑ IN THE HOSTED APP THE VAULT HOLDS THE CALLKEYS (docs/vault-core-convergence-review.md §7.5; the owner, 2026-11-13, decision 3):
243
+ // the app keeps a STUB per connection — { callKey: '', label, host, account, at?, held: 1 } — and the vault (vaultConnKeys.js)
244
+ // fills a grant or an index2 write by id. A stub only ever comes from the vault, and only for an id it then holds.
245
+ const isHeldStub = (k) => (k.held === 1 || k.held === true) && (k.callKey == null || k.callKey === '')
246
+ function vaultConnStore () { try { const s = globalThis.__wbAppStoreState; return s && s.active && s.connKeys && typeof s.ask === 'function' ? s : null } catch { return null } }
247
+ export function connKeysInVault () { return !!vaultConnStore() }
248
+ export function normConnectionKeys(o) {
249
+ if (!o || typeof o !== 'object' || Array.isArray(o)) return {}
250
+ const out = {}
251
+ const s = (v) => (typeof v === 'string' ? v.slice(0, 256) : '')
252
+ for (const [id, k] of Object.entries(o)) {
253
+ if (Object.keys(out).length >= 64) break
254
+ if (!CONN_ID.test(id) || !k || typeof k !== 'object') continue
255
+ const held = isHeldStub(k)
256
+ if (!held && (typeof k.callKey !== 'string' || !k.callKey || k.callKey.length > 256)) continue
257
+ const at = Number(k.at)
258
+ out[id] = { callKey: held ? '' : k.callKey, label: s(k.label), host: s(k.host), account: s(k.account), ...(Number.isFinite(at) && at > 0 ? { at } : {}), ...(held ? { held: 1 } : {}) }
259
+ }
260
+ return out
261
+ }
262
+ /** The whole keys only (no stub). */
263
+ export const fullConnectionKeys = (o) => Object.fromEntries(Object.entries(normConnectionKeys(o)).filter(([, k]) => !!k.callKey))
264
+ /** Each id `held` holds under the SAME callKey (or a stub already) → a stub; everything else as it is. Pure. */
265
+ export function stubConnectionKeys (o, held = {}) {
266
+ const out = {}
267
+ for (const [id, k] of Object.entries(normConnectionKeys(o))) {
268
+ const h = held && held[id]
269
+ out[id] = h && h.callKey && (!k.callKey || k.callKey === h.callKey) ? { ...k, callKey: '', held: 1 } : k
270
+ }
271
+ return normConnectionKeys(out)
272
+ }
273
+ export function loadConnectionKeys() { try { return normConnectionKeys(JSON.parse(lsGet(CONNKEYS_KEY) || 'null')) } catch { return {} } }
274
+ export function saveConnectionKeys(o) { const n = normConnectionKeys(o); try { localStorage.setItem(CONNKEYS_KEY, JSON.stringify(n)) } catch { /* private mode */ } if (vaultConnStore() && Object.values(n).some((k) => k.callKey)) setTimeout(() => { holdConnectionKeysInVault() }, 0); return n }
275
+ // THE HOSTED APP'S HALF: the vault said it keeps the callKeys (appStore.js: its `appLsRes` carried `connKeys`) — then a key written
276
+ // here WHOLE (an attach, a key from an older vault) is asked into the vault, and stubbed only for the ids it answers it holds.
277
+ // An older vault (no `connKeys`), a vault that does not answer, or none: the keys stay whole, as before. Never lost.
278
+ let _holding = null
279
+ export function holdConnectionKeysInVault (ms = 8000) {
280
+ const s = vaultConnStore(); if (!s) return Promise.resolve(0)
281
+ if (_holding) return _holding
282
+ const full = fullConnectionKeys(loadConnectionKeys()); if (!Object.keys(full).length) return Promise.resolve(0)
283
+ _holding = s.ask('connKeysHold', { keys: full }, null, ms).then((r) => {
284
+ const held = {}; for (const id of (Array.isArray(r && r.held) ? r.held : [])) if (full[id]) held[id] = full[id]
285
+ if (!Object.keys(held).length) return 0
286
+ const cur = loadConnectionKeys(); const next = stubConnectionKeys(cur, held) // only an entry still under the key the vault took
287
+ const n = Object.keys(held).filter((id) => cur[id] && cur[id].callKey === held[id].callKey).length
288
+ if (n) { try { localStorage.setItem(CONNKEYS_KEY, JSON.stringify(next)) } catch { /* the whole key stays */ } }
289
+ return n
290
+ }, () => 0).finally(() => { _holding = null })
291
+ return _holding
292
+ }
293
+ /** The keys with their callKeys, for a use that needs them in hand (the Code bridge, codeConnectionsBridge.js): a stub's key is
294
+ * asked of the vault, kept in memory only. */
295
+ export async function connectionKeysForUse (ms = 8000) {
296
+ const cur = loadConnectionKeys(), s = vaultConnStore()
297
+ const want = Object.keys(cur).filter((id) => !cur[id].callKey)
298
+ if (!s || !want.length) return cur
299
+ try {
300
+ const r = await s.ask('connKeysGet', { ids: want }, null, ms); const got = fullConnectionKeys(r && r.keys)
301
+ const out = { ...cur }; for (const id of want) if (got[id]) { const { held: _h, ...k } = cur[id]; out[id] = { ...k, callKey: got[id].callKey } }
302
+ return out
303
+ } catch { return cur }
304
+ }
305
+ /** Ask the vault to hold these whole keys ({ id: { callKey, label, host, account } }) → the ids it now holds under THAT key (only
306
+ * those may be stubbed). No vault that keeps them → []. */
307
+ export async function holdCallKeysInVault (keys, ms = 8000) {
308
+ const s = vaultConnStore(), full = fullConnectionKeys(keys); if (!s || !Object.keys(full).length) return []
309
+ try { const r = await s.ask('connKeysHold', { keys: full }, null, ms); return (Array.isArray(r && r.held) ? r.held : []).filter((id) => full[id]) } catch { return [] }
310
+ }
311
+ /** Just these ids' whole keys, for a use that needs them in hand for a moment (a create that seals a room's settings in this page,
312
+ * a cloud computer's grant) — asked of the vault, never stored here. Not held there → not in the answer. */
313
+ export async function heldCallKeys (ids, ms = 8000) {
314
+ const s = vaultConnStore(); const want = [...new Set((Array.isArray(ids) ? ids : []).filter((x) => typeof x === 'string' && CONN_ID.test(x)))].slice(0, 64)
315
+ if (!s || !want.length) return {}
316
+ try { const r = await s.ask('connKeysGet', { ids: want }, null, ms); return fullConnectionKeys(r && r.keys) } catch { return {} }
317
+ }
318
+ /** A room's settings about to be sealed IN THIS PAGE (a create — space.js createRoom): each entry with no callKey (a stub the vault
319
+ * answered a settings read with) takes the vault's key, by id. One it cannot fill is LEFT OUT (as fillIndex does): a dead entry is
320
+ * never sealed into a new room. Pure when nothing is a stub. */
321
+ export async function fillHeldConnections (cfg) {
322
+ const list = cfg && Array.isArray(cfg.connections) ? cfg.connections : null
323
+ const want = list ? list.filter((e) => e && !e.callKey && typeof e.id === 'string').map((e) => e.id) : []
324
+ if (!want.length) return cfg
325
+ const got = await heldCallKeys(want)
326
+ const next = list.map((e) => { if (e && !e.callKey && got[e.id]) { const { held: _h, ...rest } = e; return { ...rest, callKey: got[e.id].callKey } } return e }).filter((e) => !e || e.callKey)
327
+ const { connections: _c, ...rest } = cfg
328
+ return next.length ? { ...rest, connections: next } : rest
329
+ }
330
+ // THE VAULT MINTS A NEW CONNECTION'S CALLKEY (connections.js setCallKeyMinter; vaultConnKeys.js mint/settle/adopt): only where the
331
+ // vault said `connMint`. null from seal → the page mints its own, as before.
332
+ const b64bytes = (u8) => btoa(String.fromCharCode(...new Uint8Array(u8)))
333
+ export const vaultCallKeyMinter = {
334
+ async seal ({ spki, nonce, payload, id, rec }) {
335
+ const s = vaultConnStore(); if (!s || !s.connMint) return null
336
+ let r = null; try { r = await s.ask('connSeal', { conn: id, spki: b64bytes(spki), nonce: b64bytes(nonce), payload, rec: rec || {} }, null, 8000) } catch { return null }
337
+ if (!r || !r.sealed || typeof r.sealed.ct !== 'string') return null
338
+ return { sealed: r.sealed, settle: (ok, as = {}) => s.ask('connSettle', { conn: id, ok: !!ok, as }, null, 8000).then((x) => !!(x && x.held)) }
339
+ },
340
+ /** Move 3 (connWrap.js): a connection whose key the vault holds is locked at the Sentinel — the vault answers the proof and the
341
+ * sealed key; the key itself never enters this frame. → { mac, keySealed } | null */
342
+ async wrapProof ({ id, nonce, spki }) {
343
+ const s = vaultConnStore(); if (!s || !s.connMint) return null
344
+ let r = null; try { r = await s.ask('connWrap', { conn: id, nonce, spki: b64bytes(spki) }, null, 8000) } catch { return null }
345
+ return r && r.ok && typeof r.mac === 'string' && r.keySealed && typeof r.keySealed.ct === 'string' ? { mac: r.mac, keySealed: r.keySealed } : null
346
+ },
347
+ /** The account's list was read: the vault adopts the pending keys it shows → [[id, { label, host, account }]] (the page keeps stubs). */
348
+ async adopt (ids) {
349
+ const s = vaultConnStore(); if (!s || !s.connMint) return []
350
+ try { const r = await s.ask('connAdopt', { ids: (ids || []).slice(0, 256) }, null, 8000); return Array.isArray(r && r.adopted) ? r.adopted.filter((x) => Array.isArray(x) && typeof x[0] === 'string') : [] } catch { return [] }
351
+ },
352
+ }
353
+ // a launch whose copy still holds whole keys (written before this, or while the vault was away): asked in once, after the launch
354
+ try { if (vaultConnStore()) setTimeout(() => { holdConnectionKeysInVault() }, 3000) } catch { /* */ }
355
+ /** The removal marks { id: at } — valid ids, the newest MAX_MARKS (keptMerge.js unionMarks). */
356
+ export function normConnGone(o) {
357
+ if (!o || typeof o !== 'object' || Array.isArray(o)) return {}
358
+ return unionMarks(Object.fromEntries(Object.entries(o).filter(([id]) => CONN_ID.test(id))), null)
359
+ }
360
+ export function loadConnGone() { try { return normConnGone(JSON.parse(lsGet(CONNGONE_KEY) || 'null')) } catch { return {} } }
361
+ export function saveConnGone(o) { const n = normConnGone(o); try { if (Object.keys(n).length) localStorage.setItem(CONNGONE_KEY, JSON.stringify(n)); else localStorage.removeItem(CONNGONE_KEY) } catch { /* private mode */ } return n }
362
+ /** The marks as a doc's added field — `{ connGone }`, or nothing while no one has detached (index2 and the backup unchanged). */
363
+ export const connGoneField = (g = loadConnGone()) => (Object.keys(g).length ? { connGone: g } : {})
364
+ /** Two copies ({ keys, gone }) into one — `cur` (this device's) wins what both hold while it outlives the marks; the marks of
365
+ * both, the newer per id. Pure; mergeConnectionKeys and backupMerge.js use it. */
366
+ export function mergeConnectionRecords(cur, inc) {
367
+ const gone = unionMarks(normConnGone(cur && cur.gone), normConnGone(inc && inc.gone))
368
+ const keys = normConnectionKeys(mergeByMarks(normConnectionKeys(cur && cur.keys), normConnectionKeys(inc && inc.keys), gone))
369
+ return { keys, gone }
370
+ }
371
+ // A call key whose grant / finish answer is still out (connections.js postWithPendingKey — state machines pass 9, N#7): this device's
372
+ // alone (never synced — the device that sent it is the one that can adopt it), sealed on a protected device (protectedLocal.js).
373
+ export const CONN_PENDING_KEY = 'space:connPending'
374
+ export function loadPendingConnectionKeys() { try { const o = JSON.parse(lsGet(CONN_PENDING_KEY) || '{}'); return o && typeof o === 'object' && !Array.isArray(o) ? o : {} } catch { return {} } }
375
+ export function savePendingConnectionKeys(o) { try { if (o && Object.keys(o).length) localStorage.setItem(CONN_PENDING_KEY, JSON.stringify(o)); else localStorage.removeItem(CONN_PENDING_KEY) } catch { /* private mode */ } }
376
+ // stamped `at`: newer than a mark this device holds for the id, so a re-attach after a detach wins everywhere
377
+ export function rememberConnectionKey(id, k, now = Date.now()) { return saveConnectionKeys({ ...loadConnectionKeys(), [id]: { ...k, at: Math.max(now, (loadConnGone()[id] || 0) + 1) } }) }
378
+
379
+ // ── The Siri inbox (docs/siri-inbox.md): { token, defaultRoom, rooms: { [room]: { alias, label, pub:{x,y}, priv:{jwk}, at } } }.
380
+ // The TOKEN is the Shortcut's key (its hash is what the Sentinel holds); each opted-in Space's INBOX KEYPAIR lives here
381
+ // and nowhere else — the public half goes to the Sentinel, the private half opens the drops on this account's devices.
382
+ // It rides the ACCOUNT exactly as the connection keys do (index2 across live devices, the blob backup for a restore):
383
+ // union by room, the NEWER entry (its `at`) winning a Space both copies hold; the token follows `rev`, the default the merge's rule
384
+ // (keptMerge.js mergeSiriRooms; sync sweep 2026-11-14 P8).
385
+ export const SIRI_KEY = 'space:siri'
386
+ const SIRI_ROOM = /^[A-Za-z0-9_:.-]{4,120}$/, JWK_COORD = /^[A-Za-z0-9_-]{43}$/
387
+ export const normSiriAlias = (a) => String(a == null ? '' : a).replace(/\s+/g, ' ').trim().toLowerCase().slice(0, 32)
388
+ export function normSiri(o) {
389
+ if (!o || typeof o !== 'object' || Array.isArray(o)) return { token: '', defaultRoom: '', rooms: {} }
390
+ const s = (v, n) => (typeof v === 'string' ? v.slice(0, n) : '')
391
+ const rooms = {}
392
+ // ⛔ A REMOVAL IS RECORDED (state machines pass 9, K#3): `gone: { [room]: at }` — a Space taken off Siri — and `rev`, bumped
393
+ // by "Delete Siri setup". Union-with-local-wins brought both back from the account's other device, and the next push
394
+ // restored the deleted Shortcut key with every alias.
395
+ const gone = Object.fromEntries(Object.entries(o.gone && typeof o.gone === 'object' && !Array.isArray(o.gone) ? o.gone : {}).filter(([r, at]) => SIRI_ROOM.test(r) && Number(at) > 0).map(([r, at]) => [r, Number(at)]).sort((x, y) => y[1] - x[1]).slice(0, 64))
396
+ for (const [room, r] of Object.entries(o.rooms && typeof o.rooms === 'object' ? o.rooms : {})) {
397
+ if (Object.keys(rooms).length >= 64) break
398
+ if (!SIRI_ROOM.test(room) || !r || typeof r !== 'object') continue
399
+ const alias = normSiriAlias(r.alias), pub = r.pub && typeof r.pub === 'object' ? r.pub : null, priv = r.priv && typeof r.priv === 'object' ? r.priv : null
400
+ // a HELD room (the hosted vault keeps its private half — vaultAcctSecrets.js, review § 7.6): no priv here, `held: 1`
401
+ const held = !priv && (r.held === 1 || r.held === true)
402
+ if (!alias || !pub || !JWK_COORD.test(String(pub.x)) || !JWK_COORD.test(String(pub.y)) || (!held && (!priv || !JWK_COORD.test(String(priv.d))))) continue
403
+ const at = Number(r.at) || 0
404
+ if (gone[room] && at <= gone[room]) continue // taken off Siri after this entry was made (K#3)
405
+ rooms[room] = { alias, label: s(r.label, 80), pub: { x: pub.x, y: pub.y }, ...(held ? { held: 1 } : { priv: { kty: 'EC', crv: 'P-256', x: pub.x, y: pub.y, d: priv.d } }), at }
406
+ }
407
+ const token = /^[A-Za-z0-9_-]{20,200}$/.test(String(o.token || '')) ? String(o.token) : ''
408
+ const tokenHash = !token && /^[A-Za-z0-9+/]{43}=$/.test(String(o.tokenHash || '')) ? String(o.tokenHash) : '' // the vault holds the Shortcut key itself
409
+ const defaultRoom = typeof o.defaultRoom === 'string' && rooms[o.defaultRoom] ? o.defaultRoom : ''
410
+ const rev = Number.isInteger(o.rev) && o.rev > 0 ? o.rev : 0
411
+ return { token, ...(tokenHash ? { tokenHash } : {}), defaultRoom, rooms, ...(Object.keys(gone).length ? { gone } : {}), ...(rev ? { rev } : {}) }
412
+ }
413
+ /** Two copies of the record into one — the NEWER entry wins a Space both hold (a tie: `cur`, this device's); a REMOVAL in either wins (pass 9, K#3):
414
+ * a Space taken off Siri (`gone[room]`, newer than the entry) and a deleted setup (`rev`: the copy with the higher one
415
+ * decides the Shortcut key, an empty one included). Pure; mergeSiri and backupMerge.js both use it. */
416
+ export function mergeSiriRecords(cur, inc) {
417
+ // the rules are the vault keep's too (keptMerge.js, vault-core convergence C3); this function keeps only the app's format
418
+ const a = normSiri(cur), b = normSiri(inc)
419
+ const gone = unionMarks(a.gone, b.gone, Infinity) // normSiri keeps the newest 64
420
+ const token = siriKeyOf(a, b)
421
+ const tokenHash = token ? '' : siriKeyOf({ rev: a.rev, token: a.tokenHash }, { rev: b.rev, token: b.tokenHash })
422
+ const rooms = mergeSiriRooms(a.rooms, b.rooms, gone) // the newer entry (a tie: local) — and never one a mark took off
423
+ // a held stub never beats a whole copy of the SAME key (an older device's record still carries it)
424
+ for (const [r, e] of Object.entries(rooms)) { const o = [a.rooms[r], b.rooms[r]].find((x) => x && x.priv && x.pub.x === e.pub.x && x.pub.y === e.pub.y); if (e.held && o) rooms[r] = o }
425
+ // the other copy's default when this one's is gone (C3 — the keep's rule: it was blanked)
426
+ return normSiri({ token, tokenHash, defaultRoom: siriDefaultOf(rooms, a.defaultRoom, b.defaultRoom), rooms, gone, rev: Math.max(a.rev || 0, b.rev || 0) })
427
+ }
428
+ export function loadSiri() { try { return normSiri(JSON.parse(lsGet(SIRI_KEY) || 'null')) } catch { return normSiri(null) } }
429
+ export function saveSiri(o) { const n = normSiri(o); try { localStorage.setItem(SIRI_KEY, JSON.stringify(n)) } catch { /* private mode */ } try { dispatchEvent(new CustomEvent('wb-siri-changed')) } catch { /* no window (the SDK, tests) */ } return n } // the change event: the iPhone app's Siri list follows (siriHeld.js syncSiriToNative)
430
+ export const siriConfigured = (o = loadSiri()) => !!((o.token || o.tokenHash) && Object.keys(o.rooms).length)
431
+ /** Union a synced/restored copy in — the newer entry per Space (mergeSiriRecords). Returns true on a change. */
432
+ export function mergeSiri(incoming) {
433
+ const inc = normSiri(incoming); if (!inc.token && !Object.keys(inc.rooms).length && !inc.gone && !inc.rev) return false
434
+ const cur = loadSiri()
435
+ const next = mergeSiriRecords(cur, inc)
436
+ if (JSON.stringify(next) === JSON.stringify(cur)) return false
437
+ saveSiri(next); return true
438
+ }
439
+ // ── A2A into a member's private lanes (docs/a2a-lanes.md): { lanes: { [laneRoom]: { handle, name, description, pub:{x,y},
440
+ // priv:{jwk}, peers: [{ id, name, tokenHash, reply, created }] } } }. Each lane's INBOX KEYPAIR lives here and nowhere else
441
+ // (the public half goes to the Sentinel, the private half opens what outside agents sent); a peer's TOKEN is shown once and
442
+ // only its hash is kept. It rides the ACCOUNT exactly as the Siri record does: union by lane, the NEWER copy leading (a2aCore.js).
443
+ export const A2A_KEY = 'space:a2a'
444
+ export { normA2A } // a2aCore.js — the record's rules, shared with the SDK (docs/sdk-convergence.md 8c)
445
+ export function loadA2A() { try { return normA2A(JSON.parse(lsGet(A2A_KEY) || 'null')) } catch { return normA2A(null) } }
446
+ export function saveA2A(o) { const n = normA2A(o); try { localStorage.setItem(A2A_KEY, JSON.stringify(n)) } catch { /* private mode */ } return n }
447
+ export const a2aConfigured = (o = loadA2A()) => Object.keys(o.lanes).length > 0
448
+ /** Union a synced/restored copy in — the NEWER copy leads per lane (a tie: local), and a lane both copies hold (the same inbox, `handle`) gains the
449
+ * agents only the other copy has. ★ Agents were never merged (the owner, 2026-10-19: Grok Bot's results "I did not receive
450
+ * it"): an agent let in on one device never reached a device that already had the lane, and that device dropped its
451
+ * messages as a removed agent's. An agent removed on one device can come back from an older copy — inert: removing it
452
+ * revoked its token at the Sentinel and its intake address. Returns true on a change. */
453
+ export function mergeA2A(incoming) {
454
+ const inc = normA2A(incoming); if (!Object.keys(inc.lanes).length && !inc.gone) return false
455
+ const cur = loadA2A()
456
+ const next = mergeA2ARecords(cur, inc) // a2aCore.js: union, the newer copy leads, and a REMOVAL in either copy wins over a listing in the other (pass 9, K#3)
457
+ if (JSON.stringify(next) === JSON.stringify(cur)) return false
458
+ saveA2A(next); return true
459
+ }
460
+ /** A DETACH (connectionsSheet.js drop, after the Sentinel revoked it): the mark first — newer than the entry, and recorded even
461
+ * when this device never held the key (attached elsewhere) — then the key. */
462
+ export function forgetConnectionKey(id, now = Date.now()) {
463
+ const cur = loadConnectionKeys()
464
+ if (CONN_ID.test(String(id))) saveConnGone(unionMarks(loadConnGone(), { [id]: Math.max(now, ((cur[id] && cur[id].at) || 0) + 1) }))
465
+ if (!(id in cur)) return cur; const rest = { ...cur }; delete rest[id]; return saveConnectionKeys(rest)
466
+ }
467
+ /** Merge a synced/restored copy in (index2's `connections` + `connGone`, the backup's `connectionKeys` + `connGone`) — LOCAL WINS
468
+ * per id, and a mark from either copy takes off an older entry. Returns true when anything changed. With no marks on either
469
+ * side this is the old union: true exactly when a new id landed. */
470
+ export function mergeConnectionKeys(incoming, incomingGone) {
471
+ const cur = loadConnectionKeys(), curGone = loadConnGone()
472
+ // a stub is usable only beside the vault that holds its key (the hosted app): anywhere else one that slipped into a synced copy is left out
473
+ const inc = connKeysInVault() ? incoming : fullConnectionKeys(incoming)
474
+ const next = mergeConnectionRecords({ keys: cur, gone: curGone }, { keys: inc, gone: incomingGone })
475
+ const keysMoved = canon(next.keys) !== canon(cur), goneMoved = canon(next.gone) !== canon(curGone)
476
+ if (goneMoved) saveConnGone(next.gone) // the marks before the keys: a stop between leaves a mark, never a revived key
477
+ if (keysMoved) saveConnectionKeys(next.keys)
478
+ return keysMoved || goneMoved
479
+ }
480
+ /** Another copy of the address book folded into `list` — union by address (contactKey); a newer edit or tombstone wins
481
+ * (assistants on equal time too); an older copy only fills a missing name. Pure: → { list (new rows), changed }. */
482
+ export function mergeContactLists(list, incoming) {
483
+ const out = list.map((c) => (c && typeof c === 'object' ? { ...c } : c)); const byKey = new Map(out.map((c) => [contactKey(c), c])); let changed = false
484
+ for (const raw of Array.isArray(incoming) ? incoming : []) {
485
+ const c = normContact(raw); if (!c) continue; const k = contactKey(c); const ex = byKey.get(k)
486
+ if (!ex) { out.push(c); byKey.set(k, c); changed = true }
487
+ else if (c.kind === 'agent') { if ((c.at || 0) >= (ex.at || 0)) { Object.assign(ex, c); changed = true } } // adopt a newer saved-assistant edit (LWW)
488
+ else if ((c.at || 0) > (ex.at || 0)) { Object.assign(ex, c); changed = true } // person LWW: a newer edit / tombstone wins (equal-or-older at-less persons fall through to fill-name)
489
+ else if (c.fn && !ex.fn) { ex.fn = c.fn; changed = true } // learned a name for a known address
490
+ }
491
+ return { list: out, changed }
492
+ }
493
+ export function mergeContacts(incoming) { // restore/merge from a backup/index room — union; also fills missing names
494
+ if (!Array.isArray(incoming) || !incoming.length) return
495
+ const { list, changed } = mergeContactLists(loadContacts(), incoming)
496
+ if (changed) saveContacts(list)
497
+ }
498
+ // Fold a fork chain (membership changes = epochs of ONE Space, docs/spaces-membership-fork.md) into a single entry — the
499
+ // LATEST epoch. Rooms with no epochRoot (originals / un-forked) pass through unchanged. Older epochs drop out of the list
500
+ // (reachable later via "earlier versions"); the newest carries the Space forward.
501
+ export function foldEpochs(list) {
502
+ const best = new Map(); const singles = []
503
+ for (const r of (Array.isArray(list) ? list : [])) {
504
+ if (r == null) continue
505
+ if (r.epochRoot == null) { singles.push(r); continue }
506
+ const prev = best.get(r.epochRoot)
507
+ if (!prev || (r.epoch || 0) > (prev.epoch || 0)) best.set(r.epochRoot, r)
508
+ }
509
+ return [...singles, ...best.values()]
510
+ }
511
+ // ── PERSONAL AGENT — JOINT LEDGER (docs/spaces-personal-agent.md) ─────────────────────────────────────────────────────
512
+ // The set of YOUR rooms whose agents share ONE memory. On a turn in any of them this device attaches the OTHER set-rooms'
513
+ // keys ({room,mk,label}) so the runtime folds their recent entries into the agent's context (server-gated by
514
+ // PERSONAL_AGENT_LINKS). Inert until you add ≥2 rooms; the reply still needs your approval. `space:pa`=1 reveals the toggle.
515
+ export const AGENT_LINKS_KEY = 'space:agentlinks'
516
+ export const personalAgentUI = () => { try { return localStorage.getItem('space:pa') === '1' } catch { return false } }
517
+ export const agentLinks = () => { try { const a = JSON.parse(localStorage.getItem(AGENT_LINKS_KEY) || '[]'); return Array.isArray(a) ? a : [] } catch { return [] } }
518
+ export const inAgentLinks = (r) => agentLinks().includes(r)
519
+ export const toggleAgentLink = (r) => { const s = new Set(agentLinks()); s.has(r) ? s.delete(r) : s.add(r); try { localStorage.setItem(AGENT_LINKS_KEY, JSON.stringify([...s].slice(0, 24))) } catch { /* */ } }
520
+ export const saveName = (n) => { state.myName = String(n || '').trim().slice(0, 24); try { localStorage.setItem('space:myname', state.myName) } catch { /* */ } }
521
+ /** A name learned from the account — the backup or the account's room list — not typed here: saved, and a "What's your name?"
522
+ * already waiting is answered with it (nameGate.nameArrived, wired in space.js; the owner, 2026-10-25: "Why is your name still
523
+ * required after restore?"). */
524
+ export const adoptName = (n) => {
525
+ const v = String(n || '').trim(); if (!v || state.myName) return false
526
+ saveName(v)
527
+ try { if (typeof dispatchEvent === 'function' && typeof CustomEvent === 'function') dispatchEvent(new CustomEvent('wb-name-arrived', { detail: { name: state.myName } })) } catch { /* */ }
528
+ return true
529
+ }
530
+
531
+ // The offline chat cache's per-room key (moved from space.js, verified-client split step 50).
532
+ export const chatKey = (r) => 'chat:' + r
533
+ // Put a room at the top of recents (URL/title kept if not given); temp rooms never enter durable recents (moved, step 50).
534
+ // ★ EVERYTHING ELSE ON THE ENTRY IS KEPT. This rebuilt the entry as {room, url, title, at} on every room open, dropping
535
+ // titleAt / titled / llmTitled / archived / pinned and their stamps: a rename lost its time (so the index sync's
536
+ // last-writer-wins let any other device's older name win — the rename "never" arrived) and its llmTitled flag (so the
537
+ // auto-titler ran again on open and overwrote the rename seconds later). The owner: "The rename sometimes appears only
538
+ // after a few seconds and sometimes never at all — the name in the header."
539
+ export function upsertRecent({ room, url, title, at = Date.now() }) {
540
+ if (!room || isTempRoom(room)) return // temp rooms are NOT in durable recents — they live in the shreddable temp INDEX room (the durable index holds only a pointer). This is what stops a wiped temp room resuming as a BLANK.
541
+ const list = loadRecents()
542
+ const prev = list.find((r) => r.room === room)
543
+ const rest = list.filter((r) => r.room !== room)
544
+ rest.unshift({ ...(prev || {}), room, url: url || (prev && prev.url) || (location.pathname + location.search + location.hash), title: title || (prev && prev.title) || 'Space', at })
545
+ saveRecents(rest)
546
+ }
547
+ // This device's member id for widgets that want to skip "navigate to yourself" (localStorage, minted once; moved, step 50).
548
+ export function meId() {
549
+ try { let id = localStorage.getItem('space:me'); if (!id) { id = 'm-' + Math.random().toString(36).slice(2, 10); localStorage.setItem('space:me', id) } return id } catch { return 'm-anon' }
550
+ }
551
+
552
+ // A crossing that is APPROVED comes back to the lane through the mirror, as an ordinary "from the shared room"
553
+ // entry. That is the "draft replaced by the sent message" behaviour for free — but it arrives indistinguishable from
554
+ // anything else said in the room, when it is the one message you authored. Remember what crossed so the mirrored
555
+ // copy can be rendered as the crossing it is. Per-room, capped, and text-keyed because the mirror re-ids entries.
556
+ export const crossedKey = (r) => 'space:crossed:' + r
557
+ export const crossedList = (r) => { try { return JSON.parse(localStorage.getItem(crossedKey(r)) || '[]') } catch { return [] } }
558
+ // The server sends the crossing as PLAIN prose (agent/spaceBridge.mjs toPlainProse — this is a copy, held equal by
559
+ // spaces/test/crossedPlain.test.mjs), so a draft with Markdown or a link came back as different text and was never
560
+ // recognised as yours (sync sweep, 2026-10-10). Both sides are compared in that form.
561
+ export function plainProse(s) {
562
+ return String(s == null ? '' : s)
563
+ .replace(/```([\s\S]*?)```/g, '$1')
564
+ .replace(/`([^`]+)`/g, '$1')
565
+ .replace(/^\s{0,3}#{1,6}[ \t]+/gm, '')
566
+ .replace(/\*\*([^*\n]+)\*\*/g, '$1')
567
+ .replace(/__([^_\n]+)__/g, '$1')
568
+ .replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, '$1 ($2)')
569
+ .trim()
570
+ }
571
+ export const rememberCrossed = (r, text) => {
572
+ const t = plainProse(text); if (!t) return
573
+ try { localStorage.setItem(crossedKey(r), JSON.stringify([...crossedList(r).filter((x) => x !== t), t].slice(-50))) } catch { /* */ }
574
+ }
575
+ export const wasCrossed = (r, text) => { const t = plainProse(text); return !!t && crossedList(r).some((x) => x === t || plainProse(x) === t) }
576
+
577
+ // ── deleted-Space tombstones ────────────────────────────────────────────────────────────────────────────────────────
578
+ // A delete is a TOMBSTONE, not a local forget: it rides the index doc to your other devices (roomSync publishes
579
+ // `{deleted:true}`, which wins over any live entry) and it BLOCKS RESURRECTION — a stale device, an old backup or a
580
+ // late sync must never bring a deleted Space back. It lives HERE rather than in roomSync because backup.js needs it
581
+ // too and roomSync already imports backup.js; reading it from the lower layer avoids the cycle.
582
+ const TOMBSTONE_KEY = 'space:tombstones'
583
+ export const loadTombstones = () => { try { return JSON.parse(localStorage.getItem(TOMBSTONE_KEY) || '{}') } catch { return {} } }
584
+ export const saveTombstones = (t) => { try { localStorage.setItem(TOMBSTONE_KEY, JSON.stringify(t)) } catch { /* private mode */ } }
585
+ export const tombstoneRoom = (r) => { const t = loadTombstones(); if (!t[r]) { t[r] = Date.now(); saveTombstones(t) } }
586
+ export const isTombstoned = (r) => { try { return !!loadTombstones()[r] } catch { return false } }
587
+