UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

5 lines • 11.9 kB
import{a as resolveRequiredHomeDir}from"./home-dir-DEN5DisQ.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{N as parseAgentSessionKey}from"./session-key-BPgKfU2m.mjs";import{i as listAgentIds}from"./agent-roster-4XrgUgPK.mjs";import{o as isSameOpenClawAgentDatabasePath}from"./openclaw-agent-db.paths-SkzMsgQ0.mjs";import{a as resolveUnsuffixedSqliteTargetFromSessionStorePath}from"./session-sqlite-target-paths-CA4CNfL-.mjs";import{l as resolveSessionStorePathCore}from"./paths-CcxgiC3g.mjs";import{a as getOpenClawDatabaseMaintenanceScope}from"./openclaw-state-maintenance-context-D-pYfco8.mjs";import{m as readDatabasePathIdentitySync}from"./sqlite-worker-identity-CikEUuqF.mjs";import{a as executeSqliteQueryTakeFirstSync,i as executeSqliteQuerySync,s as getNodeSqliteKysely}from"./kysely-sync-R08Pt8qn.mjs";import{s as resolveOpenClawStateSqlitePath}from"./openclaw-state-db.paths-CbgXfEg1.mjs";import"./openclaw-state-db-async-lifecycle-DlV0ztcV.mjs";import{n as sha256Hex}from"./node-crypto-DPk8agfR.mjs";import{n as hasOrphanedSqliteSidecars}from"./sqlite-files-731tEtYd.mjs";import{a as resolveUpdateRehearsalRoot,r as isUpdateRehearsalReadOnlyPath}from"./update-rehearsal-paths-C4qLj9oD.mjs";import{t as readConfigMachineState}from"./config-machine-state-XW0lvLg7.mjs";import{a as writeConfigMachineState}from"./config-machine-state-write-y_DUumZ_.mjs";import{n as resolveSessionStoreCompatibilityAgentId}from"./legacy.default-agent-owner-DUgZJ5NH.mjs";import{t as DoctorMaintenanceRefusalError}from"./update-doctor-result-B09W3zwf.mjs";import{c as listOpenClawRegisteredAgentDatabases}from"./openclaw-agent-db-registry-listing-Bnnfy4SV.mjs";import{n as withOpenClawAgentDatabaseReadOnly}from"./openclaw-agent-db-readonly-BQsAKuqV.mjs";import{n as unregisterOpenClawAgentDatabase}from"./openclaw-agent-db-registry-C_AtQAwX.mjs";import{o as resolveSqliteTargetFromSessionStorePath}from"./session-sqlite-target-fDZeQkPI.mjs";import{t as getSessionKysely}from"./session-accessor.sqlite-scope-helpers-_Zyjm1vW.mjs";import"./session-accessor.sqlite-scope-BHH23mIq.mjs";import"./targets-DZpbOEi4.mjs";import{n as readSessionDeliveryRepairInventory,r as resolveSqliteCanonicalRepairLookupKeys}from"./session-accessor.sqlite-delivery-repair-CZN_Gzmj.mjs";import{a as readSessionTranscriptArchiveResetInventory}from"./session-accessor.sqlite-archive-store-kernel-CD-ksLSt.mjs";import{n as listSessionMembersInDatabase}from"./session-sharing-store.kernel-MAfBm2oT.mjs";import{n as resolveRelativeSessionStoreMigrationTargets}from"./doctor-relative-session-store-paths-C_JVBvXk.mjs";import{i as claimFullyCopied,n as copySessionClaimForRepair,o as claimsMatch,s as readClaim,t as restoreColdSessionClaims}from"./legacy-main-session-migration-restore-xai-BwB2.mjs";import{n as backupDoctorSqliteDatabases}from"./doctor-migration-backup-BYwdxiJ7.mjs";import fs from"node:fs";import path from"node:path"; //!src/commands/doctor-relative-session-store-preservation.ts function readRelativeStorePreservationState(e,t,n){const r=getNodeSqliteKysely(e.db);if(executeSqliteQueryTakeFirstSync(e.db,r.selectFrom(`context_engine_turn_outbox`).select(`advancement_key`).limit(1)))n(`pending context-engine advancements need to drain through their original Gateway before recovery`);const i=executeSqliteQueryTakeFirstSync(e.db,r.selectFrom(`session_goal_operations`).select(`expires_at`).where(`expires_at`,`>`,Date.now()).orderBy(`expires_at`,`desc`).limit(1));if(i)n(`goal-operation receipts prevent delayed goal recreation until ${new Date(i.expires_at).toISOString()}; retain the old store until that time before retrying`);if(readSessionTranscriptArchiveResetInventory(e).length>0)n(`retained transcript archives require explicit recovery from the original store; automatic archive relocation is unsupported`);const a=readSessionDeliveryRepairInventory(e);if(a.deliveries.some(e=>[`created`,`queued`,`unknown`].includes(e.status)))n(`pending conversation deliveries must settle through their original Gateway and queue before recovery`);const o=new Set(t.flatMap(e=>resolveSqliteCanonicalRepairLookupKeys(e,[e])));if(a.deliveries.some(e=>e.source_session_key===null||!o.has(e.source_session_key)))n(`delivery receipts without a retained session require explicit recovery from the original store`);const s=new Set(a.deliveries.map(e=>e.operation_id));if(a.progress.some(e=>!s.has(e.key)))n(`conversation progress without its delivery receipt requires explicit recovery from the original store`);return a} //!src/commands/doctor-relative-session-store.ts function refuse(e){throw new DoctorMaintenanceRefusalError(`Cannot merge the old relative session.store: ${e}. Original stores and existing backups are retained. Resolve the reported conflict before retrying Doctor or the update.`,{kind:`data-at-risk`,reason:`incomplete-migration`})}function discoverStoreMoves(e,t,n){const r=e.session?.store;if(!r||r.startsWith(`~`)||path.isAbsolute(r))return[];const i=[...new Map([...n,...listOpenClawRegisteredAgentDatabases({env:t,includeIncompatibleSchemaVersions:true})].map(e=>[`${e.agentId}\n${e.path}`,e])).values()];const a=resolveRelativeSessionStoreMigrationTargets(e,t,i);const o=resolveSessionStoreCompatibilityAgentId(e);const s=resolveUpdateRehearsalRoot(t);const c=/* @__PURE__ */ new Map;for(const n of listAgentIds(e)){const e=r.replaceAll(`{agentId}`,n);const l=resolveSessionStorePathCore(r,{agentId:n,env:t});const u=resolveUnsuffixedSqliteTargetFromSessionStorePath(l).path;if(isUpdateRehearsalReadOnlyPath(u,t))refuse(`the new destination ${u} is outside the copied update state; run openclaw doctor --fix against the original state directory outside the update rehearsal first`);const d=resolveSqliteTargetFromSessionStorePath(l,{agentId:n,defaultAgentId:o,env:t,registeredDatabases:i});const f=[];if(!s)for(const r of/* @__PURE__ */ new Set([process.cwd(),resolveRequiredHomeDir(t)]))f.push({storePath:path.resolve(r,e),owner:n});f.push(...a.filter(e=>e.configuredAgentId===n).map(e=>({storePath:e.storePath,path:e.path,owner:e.agentId})));for(const e of f){if(e.storePath===l||e.path===d.path)continue;const r=resolveUnsuffixedSqliteTargetFromSessionStorePath(e.storePath);if(isUpdateRehearsalReadOnlyPath(e.path??r.path,t))refuse(`the recorded source ${e.path??r.path} was not copied for rehearsal; run openclaw doctor --fix against the original state directory outside the update rehearsal first`);const a=e.path?{path:e.path,agentId:e.owner}:resolveSqliteTargetFromSessionStorePath(e.storePath,{agentId:n,defaultAgentId:o,env:t,registeredDatabases:i});const s=fs.existsSync(a.path);if(!s&&hasOrphanedSqliteSidecars(a.path))refuse(`SQLite sidecars at ${a.path} need their matching main database restored`);if(!s&&!fs.existsSync(e.storePath))continue;if(isSameOpenClawAgentDatabasePath(a.path,d.path))continue;const u=s?readDatabasePathIdentitySync(a.path):void 0;const f=a.agentId??e.owner;const p=`${u?.key??a.path}\n${d.path}`;if(!c.has(p))c.set(p,{source:{path:u?.canonicalPath??a.path,ownerStorePath:a.path,databaseAgentId:f},destination:{path:d.path,ownerStorePath:d.path,databaseAgentId:d.agentId??f},aliases:i.filter(e=>e.agentId===f&&!isUpdateRehearsalReadOnlyPath(e.path,t)&&isSameOpenClawAgentDatabasePath(e.path,a.path)).map(e=>e.path),legacyStorePath:e.storePath})}}return[...c.values()]}function readStoreSnapshot(e,t,n=false){const r=withOpenClawAgentDatabaseReadOnly(t=>{const r=executeSqliteQuerySync(t.db,getSessionKysely(t.db).selectFrom(`session_nodes`).select(`session_key`).orderBy(`session_key`)).rows.map(({session_key:n})=>{const r=readClaim(t,e,n,n);if(!r)refuse(`source session ${n} could not be read from ${e.path}`);return r});return{claims:r,memberIds:new Map(r.map(e=>[e.key,listSessionMembersInDatabase(t,e.key).map(e=>e.identityId)])),deliveryInventory:n?readRelativeStorePreservationState(t,r.map(e=>e.key),t=>refuse(`${e.path}: ${t}`)):void 0}},{agentId:e.databaseAgentId,path:e.path,env:t});return r.found?r.value:{claims:[],memberIds:/* @__PURE__ */ new Map,deliveryInventory:void 0}}function sourceFingerprint(e,t){return sha256Hex(JSON.stringify([readDatabasePathIdentitySync(e.path),t.claims.map(e=>[e.key,e.entry,e.nodeArtifactFingerprint,e.generations.map(e=>e.fingerprint)]),t.deliveryInventory]))}async function repairRelativeSessionStores(e){const t=[];const n=[];let r;try{r=discoverStoreMoves(e.cfg,e.env,e.registeredDatabases??[])}catch(e){if(e instanceof DoctorMaintenanceRefusalError)throw e;refuse(`store discovery failed: ${formatErrorMessage(e)}`)}if(r.length===0)return{changes:t,warnings:n};const i=getOpenClawDatabaseMaintenanceScope();if(!i?.ownsSchemaMaintenance)refuse(`repair requires Doctor maintenance ownership`);const a={assertCurrent:()=>i.assertAdmission()};for(const{source:i,destination:o,aliases:s,legacyStorePath:c}of r)try{a.assertCurrent();const r=`sessions.relative-store.v1.${sha256Hex(JSON.stringify([i.path,o.path]))}`;const l=readConfigMachineState(r,{env:e.env});let u;let d;if(l===void 0){const s=[i.path,o.path,resolveOpenClawStateSqlitePath(e.env)].filter(e=>fs.existsSync(e));const l=await backupDoctorSqliteDatabases({env:e.env,pendingDatabasePaths:s,databasePaths:s,authority:a,requireSnapshots:true});t.push(...l.changes);n.push(...l.warnings);if(!c.endsWith(`.sqlite`)&&fs.existsSync(c)){const{runDoctorSessionSqlite:t}=await import(`./doctor-session-sqlite-DIzSb8mD.mjs`);const{countBlockingSessionSqliteIssues:n}=await import(`./doctor-session-sqlite-types-Du6ClsP7.mjs`);if((await t({cfg:e.cfg,env:e.env,mode:`import`,agent:i.databaseAgentId,store:c},a)).targets.some(e=>n(e)>0))refuse(`legacy JSON at ${c} has unresolved Doctor import issues`)}if(!fs.existsSync(i.path))continue;const f=readStoreSnapshot(i,e.env,true);u=f.claims;await restoreColdSessionClaims(u,e.env,a.assertCurrent);d=sourceFingerprint(i,{...f,claims:u});const p=readStoreSnapshot(o,e.env);const m=new Map(p.claims.map(e=>[e.key,e]));const prepareCanonical=async t=>{const n=m.get(t);if(!n)return;const r=[n];await restoreColdSessionClaims(r,e.env,a.assertCurrent);m.set(t,r[0]);return r[0]};for(const t of u){a.assertCurrent();let n=t.key;let r=await prepareCanonical(n);const s=f.memberIds.get(t.key);const sameMembers=e=>JSON.stringify(s)===JSON.stringify(p.memberIds.get(e)??[]);if(r&&(!claimsMatch(t,r)||!sameMembers(n))){n=`agent:${parseAgentSessionKey(t.key)?.agentId??i.databaseAgentId}:relative-store-recovery-${sha256Hex(`${i.path}\n${t.key}`).slice(0,24)}`;r=await prepareCanonical(n);if(r&&!sameMembers(n))refuse(`recovered session ${n} already has different sharing permissions`)}const c={...t,canonicalKey:n};const l=await copySessionClaimForRepair({source:c,destination:o,canonicalKey:n,...r?{expectedDestination:r}:{},mode:`store-relocation`,env:e.env,beforePersistentApply:a.assertCurrent});if(!l||!claimFullyCopied(c,l))refuse(`conflicting session generations or sharing in ${i.path} and ${o.path}; preserve the originals and their pre-migration backups for recovery`);m.set(n,l);p.memberIds.set(n,s)}a.assertCurrent();const h=readStoreSnapshot(i,e.env,true);u=h.claims;if(sourceFingerprint(i,h)!==d)refuse(`source ${i.path} changed during the copy`);writeConfigMachineState(r,d,{env:e.env});t.push(`Merged ${u.length} session(s) from ${i.path} into ${o.path}; retained the original store and its pre-migration backup for recovery.`)}else{const t=readStoreSnapshot(i,e.env,true);u=t.claims;d=sourceFingerprint(i,t);if(l!==d||!c.endsWith(`.sqlite`)&&fs.existsSync(c))refuse(`the retired source ${i.path} changed; preserve it for explicit recovery without replaying deleted conversations`)}a.assertCurrent();for(const t of/* @__PURE__ */ new Set([i.path,...s]))unregisterOpenClawAgentDatabase({agentId:i.databaseAgentId,path:t,env:e.env})}catch(e){if(e instanceof DoctorMaintenanceRefusalError)throw e;refuse(`${i.path}: ${formatErrorMessage(e)}`)}return{changes:t,warnings:n}}export{repairRelativeSessionStores};