UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

10 lines • 27.6 kB
import{l as isRecord}from"../../record-coerce-BTbqdJ3-.mjs";import{r as decodeUtf8Input,t as Utf8InputError}from"../../utf8-input-CiFSnxL0.mjs";import"../../string-coerce-runtime-BYDH9Quw.mjs";import{i as defineStrayPluginEntryConfigMigration}from"../../runtime-doctor-migrations-DjW1C-6Q.mjs";import{t as archiveLegacyStateSource}from"../../doctor-state-migration-fs-ZCrlIbiJ.mjs";import{a as REEF_AUDIT_MIGRATION_NAMESPACE,d as reefAuditEntryKey,f as verifyReefAuditWindow,i as REEF_AUDIT_MIGRATION_KEY,m as verifyChain,n as REEF_AUDIT_HEAD_NAMESPACE,o as REEF_AUDIT_NAMESPACE,r as REEF_AUDIT_MAX_ENTRIES,s as REEF_AUDIT_STORE_MAX_ENTRIES,t as REEF_AUDIT_HEAD_KEY,u as parseReefAuditHead}from"../../audit-state-format-TlRRP96X.mjs";import{a as REEF_KEYS_MIGRATION_NAMESPACE,b as parseReefSetupSession,c as REEF_REVIEWS_NAMESPACE,d as REEF_REGISTRATION_IDENTITY_KEY,f as REEF_REGISTRATION_NAMESPACE,i as REEF_KEYS_MIGRATION_KEY,l as parseReefKeys,n as REEF_DURABLE_MIGRATION_NAMESPACE,o as REEF_KEYS_NAMESPACE,p as REEF_REGISTRATION_SESSION_KEY,r as REEF_KEYS_KEY,s as REEF_REVIEWS_MAX_ENTRIES,t as REEF_DURABLE_MIGRATION_KEY,y as parseReefIdentityBinding}from"../../state-format-0Qjzduzr.mjs";import{c as parseVerdict}from"../../guard-C1kFJuP6.mjs";import{a as parseReefRelayUrl,i as normalizeReefTarget,n as ReefChannelConfigSchema}from"../../config-schema-C4_lwVNs.mjs";import{_ as REEF_REPLAY_MAX_ENTRIES,a as resolveLegacyReefStateDir,b as reefReplayStoreKey,d as REEF_DELIVERED_TTL_MS,i as listLegacyReefFiles,l as REEF_DELIVERED_MAX_ENTRIES,n as collectLegacyReefStateBackupResources,r as legacyReefFileExists,t as REEF_DURABLE_LEGACY_FILENAMES,u as REEF_DELIVERED_NAMESPACE,v as REEF_REPLAY_NAMESPACE,y as REEF_REPLAY_TTL_MS}from"../../doctor-state-paths-BZpEiSYd.mjs";import{r as ReefPeerTrustSchema}from"../../friend-types-BIQirGc6.mjs";import{C as resolveReefTrustStoreKey,i as REEF_TRUST_STORE_NAMESPACE,r as REEF_TRUST_STORE_MAX_ENTRIES}from"../../trust-store-format-c57VpnLg.mjs";import path from"node:path";import fs from"node:fs/promises"; //!extensions/reef/src/doctor-durable-state.ts const REEF_RUNTIME_LEGACY_FILENAMES=[`replay.jsonl`,`reviews.json`,`delivered.json`];function openReefIdentityMigrationStore(e){return e.openPluginStateKeyedStore({namespace:REEF_KEYS_MIGRATION_NAMESPACE,maxEntries:1,overflowPolicy:`reject-new`})}function openReefDurableMigrationStore(e){return e.openPluginStateKeyedStore({namespace:REEF_DURABLE_MIGRATION_NAMESPACE,maxEntries:1,overflowPolicy:`reject-new`})}function openReefAuditMigrationStore(e){return e.openPluginStateKeyedStore({namespace:REEF_AUDIT_MIGRATION_NAMESPACE,maxEntries:1,overflowPolicy:`reject-new`})}async function readLegacyReefAudit(e){const t=decodeUtf8Input(await fs.readFile(e),`Legacy Reef audit trail`).split(` `).filter(e=>e.length>0).map(e=>JSON.parse(e));if(!verifyChain(t))throw new Error(`invalid Reef audit chain`);return t}async function readStoredReefAudit(e,t){const n=await t.lookup(REEF_AUDIT_HEAD_KEY);if(!n)return[];const r=parseReefAuditHead(n);const i=[];let a=r.hash;for(let t=r.seq;t>0&&i.length<3e4;t--){const n=await e.lookup(reefAuditEntryKey(a));if(!n)break;if(n.entry.entryHash!==a||n.entry.event.seq!==t)throw new Error(`invalid Reef audit chain state`);i.push(n.entry);a=n.entry.prevHash}return verifyReefAuditWindow(i,r,REEF_AUDIT_MAX_ENTRIES)}function requireLegacyReplayString(e,t){const n=e[t];if(typeof n!==`string`||n.length===0)throw new Error(`invalid Reef replay ${t}`);return n}function parseLegacySignedReceipt(e){const t=requireLegacyReplayString(e,`id`);const n=requireLegacyReplayString(e,`bodyHash`);const r=requireLegacyReplayString(e,`auditHead`);const i=requireLegacyReplayString(e,`signature`);if(e.status!==`accepted`&&e.status!==`rejected`)throw new Error(`invalid Reef replay receipt status`);if(e.category!==void 0&&typeof e.category!==`string`)throw new Error(`invalid Reef replay receipt category`);return{id:t,bodyHash:n,auditHead:r,status:e.status,signature:i,...e.category!==void 0?{category:e.category}:{}}}function parseLegacyReviewRequest(e){const t=e.direction;if(t!==`inbound`&&t!==`outbound`)throw new Error(`invalid Reef review direction`);return{id:requireLegacyReplayString(e,`id`),from:requireLegacyReplayString(e,`from`),to:requireLegacyReplayString(e,`to`),direction:t,bodyHash:requireLegacyReplayString(e,`bodyHash`),approvalDigest:requireLegacyReplayString(e,`approvalDigest`),verdict:parseVerdict(e.verdict)}}function parseLegacyReefReplayLine(e){if(!isRecord(e))throw new Error(`invalid Reef replay record`);const t=requireLegacyReplayString(e,`peer`);const n=requireLegacyReplayString(e,`id`);if(e.op===`claim`)return{op:`claim`,peer:t,id:n,envelopeHash:requireLegacyReplayString(e,`envelopeHash`)};if(e.op===`consume`||e.op===`release`)return{op:e.op,peer:t,id:n};if(e.op!==`complete`||!isRecord(e.receipt))throw new Error(`invalid Reef replay operation`);const r=parseLegacySignedReceipt(e.receipt);if(r.id!==n)throw new Error(`invalid Reef replay receipt`);const i=e.body;if(r.status===`accepted`&&(!isRecord(i)||typeof i.enc!==`string`)||r.status===`rejected`&&i!==void 0)throw new Error(`invalid Reef replay completion`);return{op:`complete`,peer:t,id:n,receipt:r,...isRecord(i)&&typeof i.enc===`string`?{body:{enc:i.enc}}:{}}}async function readLegacyReefReplay(e){const t=decodeUtf8Input(await fs.readFile(e),`Legacy Reef replay state`);const n=t.split(` `).filter(e=>e.length>0);const r=/* @__PURE__ */ new Map;for(const[e,i]of n.entries()){let a;try{a=parseLegacyReefReplayLine(JSON.parse(i))}catch(r){if(e===n.length-1&&!t.endsWith(` `))break;throw r}const o=reefReplayStoreKey(a.peer,a.id);const s=r.get(o);let c;if(a.op===`claim`){if(s&&s.envelopeHash!==a.envelopeHash)throw new Error(`conflicting Reef replay binding`);c={peer:a.peer,id:a.id,envelopeHash:a.envelopeHash,state:`available`}}else{if(!s)throw new Error(`Reef replay ${a.op} lacks claim`);if(a.op===`complete`)c={...s,state:`completed`,receipt:a.receipt,...a.body?{body:a.body}:{}};else if(a.op===`consume`)c={peer:s.peer,id:s.id,envelopeHash:s.envelopeHash,state:`consumed`};else c={...s,state:`available`}}r.delete(o);r.set(o,c)}return[...r.values()]}async function readLegacyReefReviews(e){const t=JSON.parse(decodeUtf8Input(await fs.readFile(e),`Legacy Reef reviews`));if(!isRecord(t))throw new Error(`invalid Reef reviews file`);const n=/* @__PURE__ */ new Map;for(const[e,r]of Object.entries(t)){if(!isRecord(r)||!isRecord(r.review))throw new Error(`invalid Reef review ${e}`);const t=parseLegacyReviewRequest(r.review);if(t.approvalDigest!==e||r.approved!==void 0&&typeof r.approved!==`boolean`)throw new Error(`invalid Reef review ${e}`);n.set(e,{review:t,...typeof r.approved===`boolean`?{approved:r.approved}:{}})}return n}async function readLegacyReefDelivered(e){const t=JSON.parse(decodeUtf8Input(await fs.readFile(e),`Legacy Reef delivered markers`));if(!Array.isArray(t)||t.some(e=>typeof e!==`string`||e.length===0))throw new Error(`invalid Reef delivered file`);return[...new Set(t)]}async function importReefRuntimeRecords(e){const{store:t,records:n}=e;const r=await t.entries();const i=new Map(r.map(e=>[e.key,e.value]));for(const{key:t,value:r}of n){const n=i.get(t);if(n&&!e.matches(n,r))throw new Error(`current ${e.recordLabel} ${t} differs`)}const a=n.filter(({key:e})=>!i.has(e));if(i.size+a.length>e.maxEntries)throw new Error(`${i.size+a.length} ${e.capacityLabel} exceed plugin-state capacity`);for(const{key:n,value:r}of a)if(!await t.registerIfAbsent(n,r))throw new Error(e.persistedMismatch(n))}const reefAuditStateMigration={id:`reef-audit-jsonl-to-plugin-state`,label:`Reef audit trail`,collectBackupResources:collectLegacyReefStateBackupResources,async detectLegacyState(e){const t=path.join(resolveLegacyReefStateDir(e),`audit.jsonl`);const n=openReefAuditMigrationStore(e.context);const r=await legacyReefFileExists(t);const i=await n.lookup(REEF_AUDIT_MIGRATION_KEY);return r||i?{preview:[r?`- Reef audit trail -> plugin state (audit)`:`- Verify Reef audit migration marker`]}:null},async migrateLegacyState(e){const t=[];const n=[];const r=path.join(resolveLegacyReefStateDir(e),`audit.jsonl`);const i=openReefAuditMigrationStore(e.context);const a=openReefDurableMigrationStore(e.context);const o=e.context.openPluginStateKeyedStore({namespace:REEF_AUDIT_NAMESPACE,maxEntries:REEF_AUDIT_STORE_MAX_ENTRIES,overflowPolicy:`reject-new`});const s=e.context.openPluginStateKeyedStore({namespace:REEF_AUDIT_HEAD_NAMESPACE,maxEntries:1,overflowPolicy:`reject-new`});if(await legacyReefFileExists(r)||await i.lookup(`audit-jsonl`)||await a.lookup(`legacy-files`))await a.register(REEF_DURABLE_MIGRATION_KEY,{pending:true});if(!await legacyReefFileExists(r)){const e=await i.lookup(REEF_AUDIT_MIGRATION_KEY);if(!e)return{changes:t,warnings:n};try{const n=await readStoredReefAudit(o,s);if(e.expectedEntries===void 0?n.length===0:n.length!==e.expectedEntries)throw new Error(`saved audit trail does not match the verified import`);await i.delete(REEF_AUDIT_MIGRATION_KEY);t.push(`Verified Reef audit trail; cleared completed migration marker`)}catch(e){n.push(`Reef audit migration is incomplete and audit.jsonl is missing: ${String(e)}; left migration blocker in place`)}return{changes:t,warnings:n}}await i.register(REEF_AUDIT_MIGRATION_KEY,{pending:true});let c;try{c=await readLegacyReefAudit(r)}catch(e){if(e.code===`ENOENT`)return{changes:t,warnings:n};n.push(`Failed importing Reef audit trail: ${String(e)}; left source in place`);return{changes:t,warnings:n,...e instanceof Utf8InputError?{warningDisposition:`recoverable`}:{}}}let l;try{l=await readStoredReefAudit(o,s)}catch(e){n.push(`Failed reading saved Reef audit trail: ${String(e)}; left legacy source in place`);return{changes:t,warnings:n}}if(l.length>0&&JSON.stringify(l)!==JSON.stringify(c.slice(-l.length))){n.push(`Kept existing Reef audit trail; left differing legacy source in place`);return{changes:t,warnings:n}}const u=c.slice(-REEF_AUDIT_MAX_ENTRIES);if(l.length===0&&u.length>0)try{for(const[e,t]of u.entries()){const n=reefAuditEntryKey(t.entryHash);const r=u[e+1]?.entryHash;const i={kind:`entry`,entry:t,...r?{nextHash:r}:{}};const a=await o.lookup(n);if(a&&JSON.stringify(a)!==JSON.stringify(i))throw new Error(`conflicting audit entry ${t.entryHash}`);if(!a&&!await o.registerIfAbsent(n,i))throw new Error(`conflicting audit entry ${t.entryHash}`)}const e=u.at(-1);const t=u[0];if(!await s.registerIfAbsent(`head`,{kind:`head`,hash:e.entryHash,seq:e.event.seq,oldestHash:t.entryHash}))throw new Error(`audit head appeared during import`)}catch(e){n.push(`Failed importing Reef audit trail: ${String(e)}; left source in place`);return{changes:t,warnings:n}}t.push(`Migrated ${c.length} Reef audit ${c.length===1?`entry`:`entries`} -> plugin state`);await i.register(REEF_AUDIT_MIGRATION_KEY,{pending:true,expectedEntries:u.length});const d=n.length;await archiveLegacyStateSource({filePath:r,label:`Reef audit trail`,changes:t,warnings:n});if(u.length<c.length&&n.length===d)t.push(`Retained the newest ${u.length} Reef audit entries in SQLite; preserved the complete ${c.length}-entry chain in the archived legacy source`);if(n.length===d)await i.delete(REEF_AUDIT_MIGRATION_KEY);return{changes:t,warnings:n}}};const reefRuntimeStateMigration={id:`reef-runtime-files-to-plugin-state`,label:`Reef durable runtime state`,collectBackupResources:collectLegacyReefStateBackupResources,async detectLegacyState(e){const t=resolveLegacyReefStateDir(e);const n=await listLegacyReefFiles(t,REEF_RUNTIME_LEGACY_FILENAMES);const r=(await listLegacyReefFiles(t,REEF_DURABLE_LEGACY_FILENAMES)).length>0;const i=await openReefDurableMigrationStore(e.context).lookup(REEF_DURABLE_MIGRATION_KEY);return n.length>0||r||i?{preview:[n.length>0?`- Reef runtime state -> plugin state (${n.join(`, `)})`:r?`- Finalize Reef durable state migration barrier`:`- Verify Reef durable state migration barrier`]}:null},async migrateLegacyState(e){const t=[];const n=[];const r=[];let i=0;const a=resolveLegacyReefStateDir(e);const o=openReefDurableMigrationStore(e.context);const s=await o.lookup(REEF_DURABLE_MIGRATION_KEY);if((await listLegacyReefFiles(a,REEF_RUNTIME_LEGACY_FILENAMES)).length>0||s)await o.register(REEF_DURABLE_MIGRATION_KEY,{pending:true});const migrateFile=async(e,r,o)=>{const s=path.join(a,e);if(!await legacyReefFileExists(s))return;try{await o(s);await archiveLegacyStateSource({filePath:s,label:r,changes:t,warnings:n})}catch(e){n.push(`Failed importing ${r}: ${String(e)}; left source in place`);if(e instanceof Utf8InputError)i++}};await migrateFile(`replay.jsonl`,`Reef replay state`,async n=>{const r=await readLegacyReefReplay(n);await importReefRuntimeRecords({store:e.context.openPluginStateKeyedStore({namespace:REEF_REPLAY_NAMESPACE,maxEntries:REEF_REPLAY_MAX_ENTRIES,overflowPolicy:`reject-new`,defaultTtlMs:REEF_REPLAY_TTL_MS}),records:r.map(e=>({key:reefReplayStoreKey(e.peer,e.id),value:e})),maxEntries:REEF_REPLAY_MAX_ENTRIES,recordLabel:`replay state`,capacityLabel:`replay bindings`,matches:(e,t)=>JSON.stringify(e)===JSON.stringify(t),persistedMismatch:()=>`persisted replay state differs`});t.push(`Migrated ${r.length} Reef replay bindings -> plugin state`)});await migrateFile(`reviews.json`,`Reef reviews`,async n=>{const r=await readLegacyReefReviews(n);const i=[...r].filter(([,e])=>e.approved===void 0);if(i.length>2e3)throw new Error(`${i.length} pending reviews exceed plugin-state capacity`);const a=[...r].filter(([,e])=>e.approved!==void 0);const o=REEF_REVIEWS_MAX_ENTRIES-i.length;const s=o>0?a.slice(-o):[];const c=new Set([...i,...s].map(([e])=>e));const l=new Map([...r].filter(([e])=>c.has(e)));const u=e.context.openPluginStateKeyedStore({namespace:REEF_REVIEWS_NAMESPACE,maxEntries:REEF_REVIEWS_MAX_ENTRIES,overflowPolicy:`reject-new`});for(const[e,t]of l){const n=await u.lookup(e);if(n&&JSON.stringify(n)!==JSON.stringify(t))throw new Error(`saved review ${e} differs`);if(!n&&!await u.registerIfAbsent(e,t))throw new Error(`persisted review ${e} differs`)}t.push(`Migrated ${l.size} of ${r.size} Reef reviews -> plugin state`)});await migrateFile(`delivered.json`,`Reef delivered markers`,async n=>{const r=await readLegacyReefDelivered(n);await importReefRuntimeRecords({store:e.context.openPluginStateKeyedStore({namespace:REEF_DELIVERED_NAMESPACE,maxEntries:REEF_DELIVERED_MAX_ENTRIES,overflowPolicy:`reject-new`,defaultTtlMs:REEF_DELIVERED_TTL_MS}),records:r.map(e=>({key:e,value:{id:e}})),maxEntries:REEF_DELIVERED_MAX_ENTRIES,recordLabel:`delivered marker`,capacityLabel:`delivered markers`,matches:(e,t)=>e?.id===t.id,persistedMismatch:e=>`persisted delivered marker ${e} differs`});t.push(`Migrated ${r.length} Reef delivered markers -> plugin state`)});const c=await listLegacyReefFiles(a,REEF_DURABLE_LEGACY_FILENAMES);const l=openReefIdentityMigrationStore(e.context);const u=openReefAuditMigrationStore(e.context);if(c.length===0&&!await l.lookup(`keys-json`)&&!await u.lookup(`audit-jsonl`)){if(await o.delete(`legacy-files`))t.push(`Verified all Reef durable state; cleared migration barrier`)}else if(await o.lookup(`legacy-files`))r.push(`Reef durable state migration is incomplete; left migration blocker in place${c.length>0?` (${c.join(`, `)})`:``}`);return{changes:t,warnings:n,...r.length>0?{notices:r}:{},...i>0&&i===n.length?{warningDisposition:`recoverable`}:{}}}}; //!extensions/reef/config-doctor-api.ts function hasRetiredReefPolicyConfig(e){return isRecord(e)&&[`dmPolicy`,`allowFrom`].some(t=>Object.hasOwn(e,t))}const reefStrayEntryConfigMigration=defineStrayPluginEntryConfigMigration({pluginId:`reef`,channelId:`reef`,validateMergedChannelConfig:e=>ReefChannelConfigSchema.safeParse(e).success});const legacyConfigRules=[{path:[`channels`,`reef`],message:`channels.reef dmPolicy/allowFrom are legacy; run "openclaw doctor --fix" to remove them. Peer trust is SQLite-backed.`,match:hasRetiredReefPolicyConfig},reefStrayEntryConfigMigration.legacyConfigRule];function normalizeCompatibilityConfig({cfg:e}){const t=e.channels?.reef;let n=e;const r=[];if(hasRetiredReefPolicyConfig(t)){const t=structuredClone(e);const i=t.channels?.reef;if(isRecord(i)){for(const e of[`dmPolicy`,`allowFrom`])if(Object.hasOwn(i,e)){delete i[e];r.push(`Removed retired Reef ${e} field.`)}n=t}}const i=reefStrayEntryConfigMigration.normalizeConfig({cfg:n});return{config:i.config,changes:[...r,...i.changes]}} //!extensions/reef/doctor-contract-api.ts const RETIRED_REEF_CONFIG_KEYS=[`friends`,`dmPolicy`,`allowFrom`];const REEF_CONFIG_IMPORT_NAMESPACE=`peer-state-config-imports`;const LegacyReefFriendSchema=ReefPeerTrustSchema.omit({approvedAt:true});const ReefIdentityConfigSchema=ReefChannelConfigSchema.pick({handle:true,relayUrl:true});const REEF_LEGACY_REGISTRATION_SOURCES=[{filename:`identity.json`,key:REEF_REGISTRATION_IDENTITY_KEY,parse:parseReefIdentityBinding,label:`Reef identity binding`},{filename:`setup-session.json`,key:REEF_REGISTRATION_SESSION_KEY,parse:parseReefSetupSession,label:`Reef setup session`}];function configuredReefIdentityBinding(e){const t=e.channels?.reef;if(!isRecord(t)||!Object.hasOwn(t,`handle`)||t.handle===void 0)return{status:`absent`};const n=ReefIdentityConfigSchema.safeParse({handle:t.handle,relayUrl:t.relayUrl});if(!n.success||!n.data.handle)return{status:`invalid`};return{status:`valid`,binding:{handle:n.data.handle,relayUrl:parseReefRelayUrl(n.data.relayUrl)}}}function inspectLegacyReefFriends(e){const t=e.channels?.reef;if(!isRecord(t)||!Object.hasOwn(t,`friends`))return null;const n=isRecord(t.friends)?t.friends:null;const r={...t};for(const e of RETIRED_REEF_CONFIG_KEYS)delete r[e];const i=ReefChannelConfigSchema.safeParse(r);const a=i.success&&i.data.handle?i.data:null;const o=/* @__PURE__ */ new Map;let s=n?0:1;for(const[e,t]of Object.entries(n??{})){const n=LegacyReefFriendSchema.safeParse(t);if(normalizeReefTarget(e)!==e||!n.success){s++;continue}o.set(e,n.data)}return{config:a,friends:o,rejected:s,total:n?Object.keys(n).length:0}}const stateMigrations=[{id:`reef-keys-json-to-plugin-state`,label:`Reef identity keys`,collectBackupResources:collectLegacyReefStateBackupResources,async detectLegacyState(e){const t=resolveLegacyReefStateDir(e);const n=path.join(t,`keys.json`);const r=openReefIdentityMigrationStore(e.context);const i=openReefDurableMigrationStore(e.context);const a=await legacyReefFileExists(n);const o=await r.lookup(REEF_KEYS_MIGRATION_KEY);const s=(await listLegacyReefFiles(t,REEF_DURABLE_LEGACY_FILENAMES)).length>0;const c=await i.lookup(REEF_DURABLE_MIGRATION_KEY);return a||o||s||c?{preview:[a?`- Reef identity keys -> plugin state (identity)`:o?`- Verify Reef identity-key migration marker`:`- Prepare Reef durable state migration barrier`]}:null},async migrateLegacyState(e){const t=[];const n=[];const r=resolveLegacyReefStateDir(e);const i=path.join(r,`keys.json`);const a=openReefIdentityMigrationStore(e.context);const o=e.context.openPluginStateKeyedStore({namespace:REEF_KEYS_NAMESPACE,maxEntries:1,overflowPolicy:`reject-new`});const s=openReefDurableMigrationStore(e.context);const c=(await listLegacyReefFiles(r,REEF_DURABLE_LEGACY_FILENAMES)).length>0;const l=await s.lookup(REEF_DURABLE_MIGRATION_KEY);if(c||l)await s.register(REEF_DURABLE_MIGRATION_KEY,{pending:true});if(!await legacyReefFileExists(i)){const e=await a.lookup(REEF_KEYS_MIGRATION_KEY);if(!e)return{changes:t,warnings:n};try{parseReefKeys(await o.lookup(REEF_KEYS_KEY));if(!e?.identityBindingRequired){await a.delete(REEF_KEYS_MIGRATION_KEY);t.push(`Verified Reef identity keys; cleared completed migration marker`)}}catch{n.push(`Reef identity key migration is incomplete and keys.json is missing; left migration blocker in place`)}return{changes:t,warnings:n}}const u=await a.lookup(REEF_KEYS_MIGRATION_KEY);const d=configuredReefIdentityBinding(e.config);const f=u?.identityBindingRequired||await legacyReefFileExists(path.join(resolveLegacyReefStateDir(e),`identity.json`))||d.status!==`absent`;await a.register(REEF_KEYS_MIGRATION_KEY,{pending:true,identityBindingRequired:f});let p;try{p=parseReefKeys(JSON.parse(decodeUtf8Input(await fs.readFile(i),`Legacy Reef identity keys`)))}catch(e){if(e.code===`ENOENT`)return{changes:t,warnings:n};n.push(`Failed importing Reef identity keys: ${String(e)}; left source in place`);return{changes:t,warnings:n,...e instanceof Utf8InputError?{warningDisposition:`recoverable`}:{}}}const m=await o.lookup(REEF_KEYS_KEY);if(m&&JSON.stringify(m)!==JSON.stringify(p)){n.push(`Kept existing Reef identity keys; left differing legacy source in place`);return{changes:t,warnings:n}}if(!m)try{if(!await o.registerIfAbsent(`keys`,p))throw new Error(`Canonical state appeared during offline import.`)}catch(e){n.push(`Failed importing Reef identity keys: ${String(e)}; left source in place`);return{changes:t,warnings:n}}t.push(`Migrated Reef identity keys -> plugin state`);const h=n.length;await archiveLegacyStateSource({filePath:i,label:`Reef identity keys`,changes:t,warnings:n});if(n.length===h&&!f)await a.delete(REEF_KEYS_MIGRATION_KEY);return{changes:t,warnings:n}}},{id:`reef-registration-json-to-plugin-state`,label:`Reef registration state`,collectBackupResources:collectLegacyReefStateBackupResources,async detectLegacyState(e){const t=resolveLegacyReefStateDir(e);const n=openReefIdentityMigrationStore(e.context);const r=await listLegacyReefFiles(t,REEF_LEGACY_REGISTRATION_SOURCES.map(e=>e.filename));const i=await n.lookup(REEF_KEYS_MIGRATION_KEY);const a=configuredReefIdentityBinding(e.config).status!==`absent`&&await legacyReefFileExists(path.join(t,`keys.json`));return r.length>0||i?.identityBindingRequired||a?{preview:[r.length>0?`- Reef registration state -> plugin state (${r.join(`, `)})`:a?`- Reef configured identity binding -> plugin state`:`- Verify Reef identity binding migration marker`]}:null},async migrateLegacyState(e){const t=[];const n=[];const r=resolveLegacyReefStateDir(e);const i=e.context.openPluginStateKeyedStore({namespace:REEF_REGISTRATION_NAMESPACE,maxEntries:2,overflowPolicy:`reject-new`});const a=[];let o=0;const s=openReefIdentityMigrationStore(e.context);const c=openReefDurableMigrationStore(e.context);if((await listLegacyReefFiles(r,REEF_LEGACY_REGISTRATION_SOURCES.map(e=>e.filename))).length>0||await s.lookup(`keys-json`)||await c.lookup(`legacy-files`))await c.register(REEF_DURABLE_MIGRATION_KEY,{pending:true});for(const e of REEF_LEGACY_REGISTRATION_SOURCES){const a=path.join(r,e.filename);if(!await legacyReefFileExists(a))continue;let s;try{s=e.parse(JSON.parse(decodeUtf8Input(await fs.readFile(a),e.label)))}catch(e){if(e instanceof Utf8InputError){n.push(`${e.message} Left source in place`);o++;continue}}if(!s){n.push(`Failed importing ${e.label}: invalid JSON; left source in place`);continue}const c=await i.lookup(e.key);const l=e.parse(c);if(l&&JSON.stringify(l)!==JSON.stringify(s)){n.push(`Kept existing ${e.label}; left differing legacy source in place`);continue}if(!l)try{if(!await i.registerIfAbsent(e.key,s))throw new Error(`Canonical state appeared during offline import.`)}catch(t){n.push(`Failed importing ${e.label}: ${String(t)}; left source in place`);continue}t.push(`Migrated ${e.label} -> plugin state`);await archiveLegacyStateSource({filePath:a,label:e.label,changes:t,warnings:n})}const l=configuredReefIdentityBinding(e.config);const u=l.status===`valid`?l.binding:void 0;if(u){const e=parseReefIdentityBinding(await i.lookup(REEF_REGISTRATION_IDENTITY_KEY));if(e&&JSON.stringify(e)!==JSON.stringify(u))n.push(`Kept existing Reef identity binding; configured handle or relay differs`);else if(!e)try{if(!await i.registerIfAbsent(`identity`,u))throw new Error(`Canonical state appeared during offline import.`);t.push(`Migrated Reef identity binding from config -> plugin state`)}catch(e){n.push(`Failed importing Reef identity binding from config: ${String(e)}`)}}if((await s.lookup(`keys-json`))?.identityBindingRequired){const o=path.join(r,`keys.json`);const c=path.join(r,`identity.json`);if(await legacyReefFileExists(o)||await legacyReefFileExists(c))a.push(`Reef identity migration remains pending while legacy identity sources remain`);else try{parseReefKeys(await e.context.openPluginStateKeyedStore({namespace:REEF_KEYS_NAMESPACE,maxEntries:1,overflowPolicy:`reject-new`}).lookup(REEF_KEYS_KEY));const n=parseReefIdentityBinding(await i.lookup(REEF_REGISTRATION_IDENTITY_KEY));if(!n)throw new Error(`saved identity binding is missing`);if(l.status===`invalid`)throw new Error(`configured handle or relay is invalid`);if(u&&JSON.stringify(n)!==JSON.stringify(u))throw new Error(`configured handle or relay differs from saved identity binding`);await s.delete(REEF_KEYS_MIGRATION_KEY);t.push(`Verified Reef identity keys and binding; cleared migration marker`)}catch(e){n.push(`Reef identity migration is incomplete: ${String(e)}; left migration blocker in place`)}}return{changes:t,warnings:n,...a.length>0?{notices:a}:{},...o>0&&o===n.length?{warningDisposition:`recoverable`}:{}}}},reefAuditStateMigration,reefRuntimeStateMigration,{id:`reef-config-trust-to-plugin-state`,label:`Reef peer trust`,collectBackupResources:()=>[],async detectLegacyState({config:e,context:t}){const n=inspectLegacyReefFriends(e);const r=t.openPluginStateKeyedStore({namespace:REEF_CONFIG_IMPORT_NAMESPACE,maxEntries:REEF_TRUST_STORE_MAX_ENTRIES,overflowPolicy:`reject-new`});const i=new Set((await r.entries()).map(e=>e.key));const a=n?.config;const o=a?[...n.friends.keys()].filter(e=>!i.has(resolveReefTrustStoreKey(a,e))).length:n?.friends.size??0;const s=n?.rejected??0;return o>0||s>0?{preview:[`- Reef peer trust: config -> plugin state (${o} peer(s), ${s} invalid)`]}:null},async migrateLegacyState({config:e,context:t}){const n=inspectLegacyReefFriends(e);if(!n)return{changes:[],warnings:[]};const r=[];if(n.rejected>0)r.push(`Skipped ${n.rejected} invalid Reef peer trust row(s); left legacy friends config in place`);if(!n.config){if(n.total>0)r.push(`Skipped Reef peer trust migration because channels.reef needs a valid handle and the current config format; left legacy friends config in place`);return{changes:[],warnings:r}}const i=n.config;if(n.friends.size===0)return{changes:[],warnings:r};const a=t.openPluginStateKeyedStore({namespace:REEF_TRUST_STORE_NAMESPACE,maxEntries:REEF_TRUST_STORE_MAX_ENTRIES,overflowPolicy:`reject-new`});const o=t.openPluginStateKeyedStore({namespace:REEF_CONFIG_IMPORT_NAMESPACE,maxEntries:REEF_TRUST_STORE_MAX_ENTRIES,overflowPolicy:`reject-new`});const s=await a.entries();const c=new Set(s.map(e=>e.key));const l=await o.entries();const u=new Set(l.map(e=>e.key));const d=[...n.friends.keys()].map(e=>resolveReefTrustStoreKey(i,e)).filter(e=>!u.has(e));const f=d.filter(e=>!c.has(e));const p=Math.max(0,REEF_TRUST_STORE_MAX_ENTRIES-s.length);const m=Math.max(0,REEF_TRUST_STORE_MAX_ENTRIES-l.length);if(f.length>p||d.length>m){r.push(`Skipped Reef peer trust migration because plugin state has room for ${p} of ${f.length} trust row(s) and ${m} of ${d.length} import marker(s); left legacy friends config in place`);return{changes:[],warnings:r}}let h=0;let g=0;for(const[e,t]of n.friends){const n=resolveReefTrustStoreKey(i,e);if(u.has(n))continue;if(await a.registerIfAbsent(n,{revision:1,trust:{...t,approvedAt:0}}))h++;else g++;await o.registerIfAbsent(n,{version:1,importedAt:Date.now()})}if(h===0&&g===0)return{changes:[],warnings:r};return{changes:[`Migrated Reef peer trust -> plugin state (${h} imported, ${g} already present)`],warnings:r}}}];export{legacyConfigRules,normalizeCompatibilityConfig,stateMigrations};