openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
3 lines • 11.7 kB
JavaScript
import{r as isPathInside}from"./path-guards-DGttsOJI.mjs";import{r as resolveStateDir}from"./state-dir-BwIClCab.mjs";import"./paths-D_FOvGon.mjs";import{i as listAgentIds}from"./agent-roster-4XrgUgPK.mjs";import{r as isMigrationArchiveArtifactName}from"./artifacts-CxKxmpYV.mjs";import{a as resolveUnsuffixedSqliteTargetFromSessionStorePath}from"./session-sqlite-target-paths-CA4CNfL-.mjs";import{l as resolveSessionStorePathCore}from"./paths-CcxgiC3g.mjs";import"./agent-scope-config-CG9CFpGX.mjs";import{a as getActiveOpenClawStateDatabaseReadSnapshotAsync,d as withCurrentOpenClawStateReadScope,v as withOpenClawStateDatabaseReadSnapshot}from"./openclaw-state-db-readonly-Cd5_cxBs.mjs";import{a as withArtifactPreservingStateReads}from"./artifact-preserving-state-reads-CWuQPqxe.mjs";import{D as statMigrationPath,S as isPendingMigrationArtifactClaim,T as sameMigrationArtifact,a as collectRecordedConsumedArchives,d as listSessionSqliteMigrationManifestPaths,g as resolveSessionSqliteMigrationRunsDir,i as canonicalMigrationFilePath,l as hasSymbolicLinkInDirectoryPath,p as readSessionSqliteMigrationManifest,v as uniqueRestoreMoves}from"./session-sqlite-migration-manifest-1oxXdbak.mjs";import{n as isSessionSqliteMigrationWarning}from"./session-sqlite-migration-issues-DbtIl4bO.mjs";import{r as readCompletedUpdateHistory,t as collectUpdateCaptureInventory}from"./update-capture-cleanup-bmFSE6BC.mjs";import fs from"node:fs";import path from"node:path";
//!src/commands/doctor-session-sqlite-recovery-inventory.ts
function resolveRecoveryArtifact(e){return e.find(e=>e.move.artifact?.disposal.state===`pending-disposal`)?.move.artifact??e[0]?.move.artifact}function collectRecoveryInventory(e){const entries=t=>e.scan?.directory(t)??fs.readdirSync(t,{withFileTypes:true});const t=canonicalMigrationFilePath(path.join(resolveStateDir(e.env),`anchor`));const n=path.dirname(t);const r=/* @__PURE__ */ new Set;const i=/* @__PURE__ */ new Set;const a=new Set(listAgentIds(e.cfg));const o=path.join(n,`agents`);if(statMigrationPath(o)?.isDirectory()&&!hasSymbolicLinkInDirectoryPath(o)){for(const e of entries(o))if(e.isDirectory()){a.add(e.name);r.add(path.join(o,e.name,`sessions`,`sessions.json`))}}for(const t of a)r.add(canonicalMigrationFilePath(resolveSessionStorePathCore(e.cfg.session?.store,{agentId:t,env:e.env})));r.add(path.join(n,`sessions`,`sessions.json`));for(const e of r)if(isPathInside(n,e))i.add(path.join(path.dirname(path.dirname(e)),`session-sqlite-import-archive`));const s=/* @__PURE__ */ new Map;let c=[];const l=[];const u=/* @__PURE__ */ new Set;const protectUnmanifested=(e,t,n)=>{l.push({path:e,runs:[],bytes:t,outcome:`protected`,reason:n})};let d=0;const f=resolveSessionSqliteMigrationRunsDir(e.env);if(hasSymbolicLinkInDirectoryPath(f))l.push({path:f,runs:[],bytes:0,outcome:`blocked`,reason:`manifest-directory-alias`});else{c=e.scan?[...e.scan.directory(f)].filter(e=>e.name.endsWith(`.json`)&&!e.name.endsWith(`.failure.json`)).map(e=>path.join(f,e.name)):listSessionSqliteMigrationManifestPaths(e.env);for(const t of c){if(e.scan&&!e.scan.metadata(t))continue;const i=statMigrationPath(t);const a=i?.isFile()&&i.nlink===1?readSessionSqliteMigrationManifest(t):void 0;if(!a){l.push({path:t,runs:[],bytes:i?.size??0,outcome:`blocked`,reason:`unreadable-manifest`});continue}const o={manifest:a,manifestPath:t};const c=collectRecordedConsumedArchives(a);for(const t of a.targets){if(e.scan&&!e.scan.available())break;const i=resolveUnsuffixedSqliteTargetFromSessionStorePath(t.storePath);const a=isPathInside(n,t.sqlitePath)&&isPathInside(n,t.storePath)&&!hasSymbolicLinkInDirectoryPath(path.dirname(t.storePath))&&!hasSymbolicLinkInDirectoryPath(path.dirname(t.sqlitePath))&&(t.databaseIdentity||r.has(t.storePath)&&(i.agentId?t.sqlitePath===i.path&&t.agentId===i.agentId:path.dirname(t.sqlitePath)===path.dirname(i.path)));for(const e of uniqueRestoreMoves(t)){const n=s.get(e.archivePath)??[];n.push({run:o,target:t,move:e,trusted:Boolean(a),consumedByRestore:c.has(e.archivePath)});s.set(e.archivePath,n)}}}}if(e.readHistory!==false&&[...s.values()].some(e=>e.some(e=>e.target.databaseIdentity))){const t=readCompletedUpdateHistory(e.env);d=Math.max(t?.latestCompletedStartedAt??0,t?.latestVerifiedFinishedAt??0)}for(const[e,t]of s){const n=resolveRecoveryArtifact(t);const r=t.every(e=>e.trusted)?statMigrationPath(e,{bigint:true}):void 0;const i=t.every(e=>e.trusted)&&n?.disposal.state===`pending-disposal`?statMigrationPath(n.disposal.claimPath,{bigint:true}):void 0;const a=r??i;if(t.every(e=>e.trusted)&&!a&&n?.disposal.state!==`pending-disposal`)u.add(e);const o={path:e,runs:[...new Set(t.map(e=>e.run.manifest.runId))],bytes:a?.isFile()?Number(a.size):0,outcome:`candidate`,reason:`producer-verified-original`,consequence:`Permanently loses rollback to this original, including pre-repair branches and metadata.`};const classify=(e,t)=>{o.outcome=e;o.reason=t};if(t.some(e=>!e.trusted))classify(`protected`,`unsupported-target-ownership`);else if(t.every(e=>e.move.artifact?.disposal.state===`disposed`))classify(r?`protected`:`disposed`,r?`recreated-after-disposal`:`intentionally-disposed`);else if(t.some(e=>e.consumedByRestore))classify(`protected`,`archive-consumed-by-restore`);else if(hasSymbolicLinkInDirectoryPath(path.dirname(e))||r&&(!r.isFile()||r.nlink!==1n&&!isPendingMigrationArtifactClaim(e,n)))classify(`blocked`,`artifact-alias-or-nonregular`);else if(t.some(({run:e,target:t})=>!e.manifest.completedAt||t.validationBeforeArchive!==`passed`||t.issues.some(e=>!isSessionSqliteMigrationWarning(e))))classify(`protected`,`incomplete-recovery-operation`);else if(t.some(({move:e})=>e.artifact?.classification===`protected`))classify(`protected`,t.find(e=>e.move.artifact?.classification===`protected`).move.artifact.reason);else if(t.some(({target:e,run:t})=>e.databaseIdentity&&!(d>Date.parse(t.manifest.completedAt))))classify(`protected`,`awaiting-later-completed-update`);else if(t.some(({move:e})=>!e.artifact))classify(`verification-required`,`historical-manifest-without-import-proof`);else if(a&&n&&[`ino`,`mtimeNs`,`size`].some(e=>String(a[e])!==String(n.identity[e])))classify(`blocked`,`artifact-metadata-changed`);else if(t.some(({move:e})=>!sameMigrationArtifact(e.artifact.identity,n.identity)))classify(`blocked`,`conflicting-artifact-identities`);else if(t.some(({move:e})=>{const t=e.artifact?.disposal;return t?.state===`pending-disposal`&&n?.disposal.state===`pending-disposal`&&t.claimPath!==n.disposal.claimPath}))classify(`blocked`,`conflicting-disposal-claims`);else if(!r&&!t.every(({move:e})=>e.artifact?.disposal.state===`pending-disposal`||e.artifact?.disposal.state===`disposed`))classify(`blocked`,`unexpectedly-missing-artifact`);else if(t.some(({move:e})=>e.artifact?.disposal.state===`pending-disposal`))o.reason=`resume-pending-disposal`;l.push(o)}const p=/* @__PURE__ */ new Set([path.join(n,`state`),...[...r].flatMap(e=>[path.dirname(e),path.dirname(resolveUnsuffixedSqliteTargetFromSessionStorePath(e).path)]),...[...s.values()].flatMap(e=>e.filter(e=>e.trusted).map(e=>path.dirname(e.target.sqlitePath)))]);for(const e of p){if(!isPathInside(n,e)||!statMigrationPath(e)?.isDirectory()||hasSymbolicLinkInDirectoryPath(e))continue;for(const t of entries(e)){if(!isMigrationArchiveArtifactName(t.name)&&!t.name.includes(`.pre-doctor-`)&&!/^.+\.pre-startup-migration-.+\.bak$/.test(t.name)&&!(e===path.join(n,`state`)&&/^openclaw\.sqlite\.doctor-cron-\d{13}-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.bak$/.test(t.name)))continue;const r=path.join(e,t.name);if(s.has(r))continue;protectUnmanifested(r,t.isFile()?fs.lstatSync(r).size:0,`unmanifested-recovery-original`)}}const m=new Set(l.map(e=>e.path));const h=/* @__PURE__ */ new Set;for(const e of s.values())for(const{move:t}of e)if(t.artifact?.disposal.state===`pending-disposal`)h.add(t.artifact.disposal.claimPath);for(const e of i){if(!statMigrationPath(e)?.isDirectory()||hasSymbolicLinkInDirectoryPath(e))continue;for(const t of entries(e)){const n=path.join(e,t.name);if(m.has(n)||h.has(n))continue;m.add(n);protectUnmanifested(n,t.isFile()?fs.lstatSync(n).size:0,`unmanifested-artifact`)}}if(l.some(e=>e.reason===`unreadable-manifest`||e.reason===`manifest-directory-alias`)){for(const e of l)if(e.outcome===`candidate`||e.outcome===`verification-required`){e.outcome=`blocked`;e.reason=`unreadable-recovery-dependencies`}}if(e.scan?.incomplete){for(const e of l)if(e.outcome===`candidate`||e.outcome===`verification-required`){e.outcome=`protected`;e.reason=`incomplete-recovery-inventory`}}protectRecoveryDependencies(l,s);return{artifacts:l,references:s,manifestPaths:c,report:summarizeRecoveryCleanup(n,l.filter(e=>!u.has(e.path)),`preview`,u.size)}}function protectRecoveryDependencies(e,t,n){const active=e=>(!e.consumedByRestore||statMigrationPath(e.move.archivePath)!==void 0)&&e.move.artifact?.disposal.state!==`disposed`;const r=/* @__PURE__ */ new Map;const i=/* @__PURE__ */ new Map;for(const[e,n]of t)for(const t of n.filter(active)){const n=r.get(t.move.sourcePath)??[];n.push(e);r.set(t.move.sourcePath,n)}const connect=(e,t)=>{const n=i.get(e)??/* @__PURE__ */ new Set;n.add(t);i.set(e,n)};const a=/* @__PURE__ */ new Map;for(const[e,i]of t)for(const t of i.filter(active)){if(t.target.databaseIdentity){const n=a.get(t.run.manifestPath);if(n){connect(e,n);connect(n,e)}else a.set(t.run.manifestPath,e)}const i=(t.move.artifact??n?.get(t))?.dependencies??(t.move.kind===`legacy-store`?uniqueRestoreMoves(t.target).filter(e=>e.kind===`transcript`).map(e=>e.sourcePath):[]);for(const n of i)for(const i of r.get(n)??[]){connect(e,i);if(t.move.kind===`legacy-store`)connect(i,e)}}const o=new Map(e.map(e=>[e.path,e]));const s=e.filter(e=>e.outcome!==`candidate`&&e.outcome!==`verification-required`&&e.outcome!==`disposed`&&e.outcome!==`removed`);for(const e of s)for(const t of i.get(e.path)??[]){const e=o.get(t);if(e?.outcome!==`candidate`&&e?.outcome!==`verification-required`)continue;e.outcome=`protected`;e.reason=`retained-recovery-dependency`;s.push(e)}}function summarizeRecoveryCleanup(e,t,n,r=0){const i={candidateBytes:0,verificationRequiredBytes:0,protectedBytes:0,blockedBytes:0,removedBytes:0,removedFiles:0};const a={candidate:`candidateBytes`,"verification-required":`verificationRequiredBytes`,protected:`protectedBytes`,blocked:`blockedBytes`,failed:`blockedBytes`};for(const e of t){const t=a[e.outcome];if(t)i[t]+=e.bytes;if(e.removedBytes!==void 0){i.removedBytes+=e.removedBytes;i.removedFiles+=1}}return{stateDir:e,artifacts:t,totals:i,status:n,missingOriginals:r}}function readUpdateCleanupInventory(e){const t=collectRecoveryInventory(e);const n=collectUpdateCaptureInventory({stateDir:t.report.stateDir,env:e.env,scan:e.scan,readHistory:e.readHistory});return{...t,captureIdentities:n.identities,report:summarizeRecoveryCleanup(t.report.stateDir,[...t.report.artifacts,...n.artifacts],`preview`,t.report.missingOriginals)}}async function collectUpdateCleanupInventoryAsync(e){if(e.readHistory===false)return readUpdateCleanupInventory(e);const read=()=>withArtifactPreservingStateReads(()=>withOpenClawStateDatabaseReadSnapshot(async()=>{await getActiveOpenClawStateDatabaseReadSnapshotAsync({env:e.env});return readUpdateCleanupInventory(e)},{env:e.env}));return e.current?withCurrentOpenClawStateReadScope({env:e.env},read):read()}async function inspectSessionSqliteRecovery(e){return(await collectUpdateCleanupInventoryAsync({...e,current:true})).report}export{resolveRecoveryArtifact as a,protectRecoveryDependencies as i,collectUpdateCleanupInventoryAsync as n,summarizeRecoveryCleanup as o,inspectSessionSqliteRecovery as r,collectRecoveryInventory as t};