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