openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
39 lines • 52 kB
JavaScript
import{c as resolveUserPath}from"./home-dir-DEN5DisQ.mjs";import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{l as syncDirectory,s as requireDirectorySync}from"./directory-durability-o_aQCRBZ.mjs";import{r as isPathInside}from"./path-guards-DGttsOJI.mjs";import{c as readFileDescriptorBoundedSync}from"./boundary-file-read-bB9An35K.mjs";import{n as resolveRealpathOrAbsolute,t as resolvePathViaExistingAncestorSync}from"./boundary-path-BeuXNL_4.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{i as isPrimarySessionTranscriptFileName}from"./transcript-file-names-eSXc53rr.mjs";import{d as resolveTrajectoryPointerPath,u as resolveTrajectoryPath}from"./artifacts-CxKxmpYV.mjs";import{a as resolveUnsuffixedSqliteTargetFromSessionStorePath}from"./session-sqlite-target-paths-CA4CNfL-.mjs";import{a as executeSqliteQueryTakeFirstSync,c as iterateSqliteQuerySync}from"./kysely-sync-R08Pt8qn.mjs";import{n as openNodeSqliteDatabase}from"./node-sqlite-DXyF1fBG.mjs";import{y as withSynchronousArtifactPreservingStateSnapshot}from"./openclaw-state-db-readonly-Cd5_cxBs.mjs";import{a as sameFileMutationFingerprint}from"./file-descriptor-CRkf5tcV.mjs";import{u as createPrivateSqliteTempDirectorySync}from"./sqlite-snapshot-staging-DUZ7pEYA.mjs";import{a as resolveSqliteDatabaseFilePaths,t as SQLITE_SIDECAR_SUFFIXES}from"./sqlite-files-731tEtYd.mjs";import{o as readSqliteFileGenerationSync}from"./openclaw-quarantine-store-CpeLVmlE.mjs";import{m as assertOpenClawStateWriteAllowedAtPath}from"./openclaw-state-db-BlgxYkYw.mjs";import{c as inspectUpdateRecoveries}from"./update-run-recovery-store-k_2_R9pM.mjs";import{i as isUpdateRecoveryPending}from"./update-run-recovery-schema-CreOtwf8.mjs";import{n as withOpenClawAgentDatabaseReadOnly}from"./openclaw-agent-db-readonly-BQsAKuqV.mjs";import{T as migrateLegacySessionCreator}from"./openclaw-agent-db-schema-helpers-BwxRsv20.mjs";import"./openclaw-agent-db-BUym2U31.mjs";import{t as attachSessionEntrySnapshots}from"./session-entry-snapshot-values-CO8WwasI.mjs";import{n as sessionEntrySnapshotColumns}from"./session-entry-snapshots-DapkAXVl.mjs";import{a as isIndexedSessionEntry,r as equivalentLegacySessionHeaders}from"./session-entry-codec-aa6Rsx0o.mjs";import"./transcript-payload-XgNI1bf4.mjs";import{r as transcriptEventJsonSql}from"./transcript-payload-read-aAg-1-ep.mjs";import{t as inspectOpenClawAgentDatabaseOwner}from"./openclaw-agent-db-owner-read-DgWlHTZS.mjs";import{a as normalizeStoreSessionKey}from"./store-entry-DbH6jRLn.mjs";import{t as getSessionKysely}from"./session-accessor.sqlite-scope-helpers-_Zyjm1vW.mjs";import"./session-accessor.sqlite-scope-BHH23mIq.mjs";import{c as scanSessionTranscriptNavigation,n as isSessionTranscriptLeafControl,t as isCanonicalSessionTranscriptEntry}from"./transcript-tree-Dwc2Zlw1.mjs";import{i as resolveAllAgentSessionStoreCandidateTargetsSync}from"./targets-DZpbOEi4.mjs";import{n as collectSessionStateIdsForEntry}from"./session-accessor.sqlite-references-B7aXsOVx.mjs";import{t as projectTranscriptNavigationFields}from"./transcript-navigation-fields-CXlYkMaa.mjs";import{t as canonicalizeTranscriptEventMedia}from"./transcript-event-media-CD-wafrn.mjs";import"./update-run-recovery-oivDmH0_.mjs";import{a as readLegacyPrimaryTranscriptIdentity,c as readSessionImportValidationSnapshot,f as resolveTargetSqlitePath,n as createTranscriptEventReader,s as readOnlySqliteValidationSnapshot,t as countTranscriptEventsForPath,u as readTranscriptFingerprint}from"./session-sqlite-migration-readers-Cc_cphZg.mjs";import{a as shouldFilterLegacySessionRecordsByTarget,i as resolveLegacyTranscriptPaths,n as listLegacySessionTranscriptFiles,r as readLegacySessionStoreEntries,t as isLegacySessionRecordOwnedByTarget}from"./legacy-store-inspection-CVPBQ67e.mjs";import{C as moveMigrationArtifact,D as statMigrationPath,S as isPendingMigrationArtifactClaim,T as sameMigrationArtifact,_ as sessionSqliteMigrationTargetKey,b as writeSessionSqliteMigrationManifest,f as migrationMoveKey,i as canonicalMigrationFilePath,l as hasSymbolicLinkInDirectoryPath,n as assertSafeSessionSqliteMigrationDirectory,t as HISTORICAL_IMPORT_REASON,v as uniqueRestoreMoves,w as readMigrationArtifactIdentity}from"./session-sqlite-migration-manifest-1oxXdbak.mjs";import{n as isSessionSqliteMigrationWarning}from"./session-sqlite-migration-issues-DbtIl4bO.mjs";import{i as retireUpdateCaptures}from"./update-capture-cleanup-bmFSE6BC.mjs";import{a as resolveRecoveryArtifact,i as protectRecoveryDependencies,n as collectUpdateCleanupInventoryAsync,o as summarizeRecoveryCleanup,t as collectRecoveryInventory}from"./doctor-session-sqlite-recovery-inventory-CSHyVWB7.mjs";import{n as normalizeLegacySessionEntryDelivery}from"./state-migrations.legacy-session-store-BJo6a9mB.mjs";import{r as normalizeLegacyInboundContextLabelsJson}from"./legacy-inbound-context-labels-Bm1DlRAz.mjs";import{i as transcriptRepairUserKey,n as normalizeLegacyOpenAICodexTranscriptMetadata}from"./legacy-transcript-repair-CorMRh9Q.mjs";import{i as withDoctorSqliteMaintenanceLock,n as assertDoctorSqliteMaintenancePathsNotAliased}from"./doctor-sqlite-maintenance-lock-De_t-lkq.mjs";import fs from"node:fs";import path from"node:path";import{hash,randomUUID}from"node:crypto";import os from"node:os";import{setImmediate}from"node:timers/promises";
//!src/commands/doctor-session-sqlite-discovery.ts
function collectHistoricalArchiveSources(e){const t=/* @__PURE__ */ new Map;const n=collectRecoveryInventory(e);const r=/* @__PURE__ */ new Map;const i=/* @__PURE__ */ new Map;for(const e of n.references.values()){if(e.some(e=>!e.trusted||e.consumedByRestore))continue;const n=e[0];if(!e.every(({target:e,move:t})=>e.agentId===n.target.agentId&&e.storePath===n.target.storePath&&e.sqlitePath===n.target.sqlitePath&&t.sourcePath===n.move.sourcePath))continue;if(n.move.kind!==`legacy-store`&&(n.move.kind!==`unreferenced-jsonl`||!isPrimarySessionTranscriptFileName(path.basename(n.move.sourcePath))))continue;if(!e.every(({move:e})=>e.artifact&&(e.kind===`legacy-store`||e.artifact.classification===`protected`)&&sameMigrationArtifact(e.artifact.identity,n.move.artifact.identity)))continue;if(n.move.kind===`unreferenced-jsonl`){const t=n.move.artifact.identity;const i=JSON.stringify([n.target.agentId,n.target.storePath,n.target.sqlitePath,n.move.sourcePath,t.size,t.sha256]);const a=r.get(i)??[];a.push(e);r.set(i,a)}if(e.some(e=>e.move.artifact?.disposal.state!==`retained`))continue;if(e.some(({target:e,move:t})=>{if(t.artifact?.reason!==`indexed-historical-primary`)return false;let n=i.get(e);if(!n){n=new Set(e.completedMoves.map(e=>e.archivePath));i.set(e,n)}return n.has(t.archivePath)}))continue;const a=t.get(n.target.storePath)??{transcripts:[],stores:[]};(n.move.kind===`legacy-store`?a.stores:a.transcripts).push(n.move);t.set(n.target.storePath,a)}if(n.report.artifacts.some(e=>[`unreadable-manifest`,`manifest-directory-alias`].includes(e.reason)))r.clear();return{sources:t,claims:[...r.values()].filter(e=>e.length>1),inventory:n}}function readArchivedSessionOwnership(e,t,n){const r=[];let i=true;for(const a of t){if(!fs.existsSync(a.archivePath))continue;const t=[];try{const n=readMigrationArtifactIdentity(a.archivePath);if(!sameMigrationArtifact(n,a.artifact.identity,{ignoreDevice:true}))throw new Error(`Archived session registry no longer matches its migration receipt (file metadata or contents changed).`);for(const n of readLegacySessionRecords(e,t,{sourcePath:a.archivePath}))r.push(n);if(t.length||!sameMigrationArtifact(readMigrationArtifactIdentity(a.archivePath),n))throw new Error(`Archived session registry changed during verification or contains invalid entries.`)}catch(e){i=false;n.push({code:`historical_transcript_deferred`,message:`${a.archivePath}: ${formatErrorMessage(e)} Historical transcript import skipped for this store; originals retained. This archive warning does not indicate SQLite corruption. No action is needed if all expected conversations are present. If history is missing, preserve the archive and migration manifests and follow https://docs.openclaw.ai/cli/doctor/sqlite-maintenance#changed-archived-registry`})}}return i?r:void 0}async function discoverLegacyHistoricalTranscripts(e){const t=path.dirname(canonicalMigrationFilePath(e.target.storePath));assertSafeSessionSqliteMigrationDirectory(t);const n=/* @__PURE__ */ new Map;const r=new Set(e.records.flatMap(e=>e.transcriptPath?[canonicalMigrationFilePath(e.transcriptPath)]:[]));for(const i of listLegacySessionTranscriptFiles(t))if((!e.verifiedSourcePaths||e.verifiedSourcePaths.has(i))&&!r.has(canonicalMigrationFilePath(i))&&!e.referencedPaths?.has(canonicalMigrationFilePath(i)))n.set(i,{path:i,originalPath:i});const i=new Set((e.ownershipRecords??[]).flatMap(e=>e.transcriptDependencies.map(canonicalMigrationFilePath)));for(const t of e.archiveSources??[]){if(i.has(canonicalMigrationFilePath(t.sourcePath)))continue;n.set(t.archivePath,{path:t.archivePath,originalPath:t.sourcePath,archiveMove:t})}const a=/* @__PURE__ */ new Map;try{for(const t of[...e.records,...e.ownershipRecords??[]])for(const e of collectSessionStateIdsForEntry(t.entry)){const n=a.get(e)??/* @__PURE__ */ new Set;n.add(t.sessionKey);a.set(e,n)}}catch(t){e.issues.push({code:`historical_transcript_deferred`,message:`${e.target.storePath}: invalid legacy lineage; originals retained: ${String(t)}`});return[]}const o=new Set([...a].filter(([,e])=>e.size>1).map(([e])=>e));const s=[];const c=/* @__PURE__ */ new Map;for(const t of n.values()){await setImmediate();try{const n=readMigrationArtifactIdentity(t.path);if(t.archiveMove&&!sameMigrationArtifact(n,t.archiveMove.artifact.identity,{ignoreDevice:true}))throw new Error(`Archived original changed since migration; retained without importing`);const r=readLegacyPrimaryTranscriptIdentity(t.path,t.originalPath,t.archiveMove?o:void 0);if(!r)continue;if(!sameMigrationArtifact(n,readMigrationArtifactIdentity(t.path)))throw new Error(`Primary transcript changed during discovery`);if(r.sessionId!==r.filenameId)e.issues.push({code:`transcript_filename_mismatch`,message:`${t.originalPath}: Header session ID ${r.sessionId} differs from filename ID ${r.filenameId}; using the header identity and preserving the original.`});if(e.records.some(e=>e.entry.sessionId===r.sessionId&&e.transcriptPath&&fs.existsSync(e.transcriptPath)))throw new Error(`A registered primary already claims this identity; extra original retained`);const i=e.snapshot.sessionKeysBySessionId.get(r.sessionId);const s=a.get(r.sessionId);if(s&&(s.size!==1||i&&!s.has(i)))throw new Error(`Conflicting logical owners; retained without importing`);const l=i??s?.values().next().value;const u=resolveUnsuffixedSqliteTargetFromSessionStorePath(e.target.storePath).agentId;if(!l&&u!==e.target.agentId)throw new Error(`No unambiguous agent owner for unregistered history`);const d={sessionKey:l??`agent:${e.target.agentId}:recovered:${r.sessionId}`,entry:{sessionId:r.sessionId,updatedAt:r.updatedAt,archivedAt:r.updatedAt||1},transcriptPath:t.path,transcriptDependencies:[t.originalPath],historical:{originalPath:t.originalPath,identity:n,...t.archiveMove?{archiveMove:t.archiveMove}:{}}};const f=c.get(r.sessionId)??[];f.push(d);c.set(r.sessionId,f)}catch(n){e.issues.push({code:`historical_transcript_deferred`,message:`${t.originalPath}: ${String(n)}`})}}for(const[t,n]of c){const r=n[0];const i=n.every(e=>e.historical?.archiveMove&&e.historical.originalPath===r.historical.originalPath&&e.historical.identity.size===r.historical.identity.size&&e.historical.identity.sha256===r.historical.identity.sha256);if(n.length>1&&!i)e.issues.push({code:`historical_transcript_deferred`,message:`${t}: multiple primary files claim this identity; originals retained without importing: ${n.map(e=>e.historical.originalPath).join(`, `)}`});else s.push(r)}return s}function gatherLegacyArchiveCoverage(e,t,n,r=resolveAllAgentSessionStoreCandidateTargetsSync(e,{env:t})){const i=/* @__PURE__ */ new Set;const a=/* @__PURE__ */ new Set;const o=/* @__PURE__ */ new Set;const s=/* @__PURE__ */ new Set;const c=/* @__PURE__ */ new Set;const l=/* @__PURE__ */ new Map;const u=/* @__PURE__ */ new Map;for(const e of n){const t=canonicalMigrationFilePath(e.storePath);u.set(t,[...u.get(t)??[],e])}const d=new Set([...u.keys()].map(e=>path.dirname(e)));const f=new Map([...r,...n].map(e=>[canonicalMigrationFilePath(e.storePath),e]));for(const[t,n]of f){if(t.endsWith(`.sqlite`)||!d.has(path.dirname(t))||!fs.existsSync(t))continue;const r=u.get(t)??[];const f=[];let p;try{assertSafeSessionSqliteMigrationDirectory(path.dirname(t));l.set(t,readMigrationArtifactIdentity(t));p=readLegacySessionRecords(n,f)}catch(e){if(r.length>0)throw e;s.add(path.dirname(t));c.add(path.dirname(t));continue}const m=[...p.map(e=>e.sessionKey),...f.flatMap(e=>e.sessionKey?[e.sessionKey]:[])];const h=r.length>0&&f.every(isSessionSqliteMigrationWarning)&&m.every(t=>r.some(n=>!shouldFilterLegacySessionRecordsByTarget(n)||isLegacySessionRecordOwnedByTarget(e,n,t)));if(f.length>0){s.add(path.dirname(t));if(!h)c.add(path.dirname(t))}if(h)i.add(t);for(const e of p){if(!e.transcriptPath)continue;for(const t of[e.transcriptPath,resolveTrajectoryPath(e.transcriptPath),resolveTrajectoryPointerPath(e.transcriptPath)]){if(!t)continue;const e=canonicalMigrationFilePath(t);a.add(e);if(!h)o.add(e)}}}for(const[e,t]of u)if(!fs.existsSync(e)&&t.every(e=>!shouldFilterLegacySessionRecordsByTarget(e)))i.add(e);return{knownTargets:r,selectedStorePaths:i,referencedPaths:a,retainedPaths:o,incompleteDirectories:s,retainedDirectories:c,indexIdentities:l}}function readLegacySessionRecords(e,t,n={}){return readLegacySessionStoreEntries(e,t,n).entries.map(({entry:t,sessionKey:r})=>{const{transcriptPath:i,transcriptDependencies:a}=resolveLegacyTranscriptPaths(e,t,n.verifiedSourcePaths);return{entry:migrateLegacySessionCreator(normalizeLegacySessionEntryDelivery(t)),sessionKey:r,transcriptPath:i,transcriptDependencies:a}})}function listUnreferencedJsonlFiles(e,t){const n=path.dirname(e);let r;try{r=fs.readdirSync(n)}catch{return[]}const i=new Set(t.map(e=>resolveRealpathOrAbsolute(e)));return r.filter(e=>e.endsWith(`.jsonl`)).map(e=>path.join(n,e)).filter(e=>!i.has(resolveRealpathOrAbsolute(e))).toSorted((e,t)=>e.localeCompare(t))}async function appendLegacyHistoricalTranscripts(e){const{allRecords:t,retainedImport:n,sourceConflicts:r,issues:i}=e;const a=e.historicalArchives?.get(canonicalMigrationFilePath(e.target.storePath));const o=readArchivedSessionOwnership(e.target,n?[]:a?.stores??[],i);const s=readOnlySqliteValidationSnapshot(e.target);if(s.ok&&o){const c=await discoverLegacyHistoricalTranscripts({target:e.target,records:t,ownershipRecords:o,referencedPaths:e.referencedPaths,archiveSources:!n?a?.transcripts:[],verifiedSourcePaths:n?new Set(n.sources.filter(e=>!r.has(e.path)).map(e=>e.path)):void 0,snapshot:s.snapshot,issues:i});for(const e of c){const n=t.find(t=>t.sessionKey===e.sessionKey&&t.entry.sessionId===e.entry.sessionId&&(!t.transcriptPath||!fs.existsSync(t.transcriptPath)));if(n){n.transcriptPath=e.transcriptPath;n.transcriptDependencies.push(...e.transcriptDependencies);n.historical=e.historical}else t.push(e)}}else if(!s.ok)i.push({code:`sqlite_read_failed`,message:String(s.error)})}
//!src/commands/doctor-session-sqlite-migration-coalesce.ts
function coalesceSessionSqliteArchiveReferences(e,t){const n=/* @__PURE__ */ new Map;const r=/* @__PURE__ */ new Set;const i=/* @__PURE__ */ new Map;for(const[t,n]of e)for(const e of[t,n.archivePath]){const n=i.get(e)??[];n.push(t);i.set(e,n)}for(const a of t)for(const t of a.manifest.targets){const o=/* @__PURE__ */ new Set;for(const e of uniqueRestoreMoves(t))for(const t of i.get(e.archivePath)??[])o.add(t);if(o.size===0)continue;const s=sessionSqliteMigrationTargetKey(t);const c=n.get(s)??{target:t,archives:/* @__PURE__ */ new Set,issues:[{code:`historical_duplicate_settled`,message:``}]};n.set(s,c);o.forEach(e=>c.archives.add(e));t.issues.push(...c.issues);for(const n of[`plannedMoves`,`completedMoves`]){const r=/* @__PURE__ */ new Map;for(const i of t[n]){const t=e.get(i.archivePath);if(t&&i.artifact){i.archivePath=t.archivePath;i.artifact={...i.artifact,identity:t.artifact.identity,disposal:{state:`retained`}}}const n=migrationMoveKey(i);if(r.get(n)?.artifact?.reason!==`indexed-historical-primary`)r.set(n,i)}t[n]=[...r.values()]}r.add(a)}for(const{archives:e,issues:t}of n.values())t[0].message=`Retired ${e.size} byte-identical duplicate archive(s); rollback references now use the verified surviving originals.`;for(const e of r)writeSessionSqliteMigrationManifest(e);return[...n.values()].map(({target:e,issues:t})=>({target:e,issues:t}))}
//!src/config/sessions/session-accessor.sqlite-import-stage.ts
function withSqliteSessionImportStage(e){const t=createPrivateSqliteTempDirectorySync(os.tmpdir(),`openclaw-session-import-`);let n;try{const r=path.join(t,`transcripts.sqlite`);fs.closeSync(fs.openSync(r,`wx`,384));n=openNodeSqliteDatabase(r);n.exec(`
PRAGMA cache_size = -2048;
PRAGMA temp_store = FILE;
CREATE TABLE rows (
source INTEGER NOT NULL, seq INTEGER NOT NULL, event_json TEXT NOT NULL,
PRIMARY KEY (source, seq)
) WITHOUT ROWID;
CREATE TABLE seen (hash BLOB NOT NULL, event_json TEXT NOT NULL);
CREATE INDEX seen_hash ON seen(hash);
CREATE TABLE tree (id TEXT PRIMARY KEY, node_json TEXT NOT NULL) WITHOUT ROWID;
CREATE TABLE tree_sets (kind TEXT NOT NULL, id TEXT NOT NULL, PRIMARY KEY(kind, id)) WITHOUT ROWID;
CREATE TABLE selected (id TEXT PRIMARY KEY, seq INTEGER NOT NULL, parent_id TEXT, visible INTEGER NOT NULL) WITHOUT ROWID;
CREATE TABLE user_keys (id TEXT PRIMARY KEY, visible_key TEXT, stripped_key TEXT) WITHOUT ROWID;
CREATE INDEX user_keys_visible ON user_keys(visible_key);
BEGIN;
`);return e(new SqliteSessionImportStage(n))}finally{try{n?.close()}finally{fs.rmSync(t,{recursive:true,force:true})}}}var SqliteSessionImportStage=class{constructor(e){this.database=e;this.rejected=false;this.insert=e.prepare(`INSERT INTO rows VALUES (?, ?, ?)`);this.read=e.prepare(`SELECT seq, event_json AS eventJson FROM rows WHERE source = ? ORDER BY seq`);this.findSeen=e.prepare(`SELECT 1 FROM seen WHERE hash = ? AND event_json = ? LIMIT 1`);this.insertSeen=e.prepare(`INSERT INTO seen VALUES (?, ?)`)}append(e,t,n){this.insert.run(e,t,n)}rows(e){return this.read.iterate(e)}resetSeen(){this.database.exec(`DELETE FROM seen`);this.rejected=false}*iterateUnseenEvents(e){for(const t of this.rows(e)){const e=hash(`sha256`,t.eventJson,`buffer`);if(this.findSeen.get(e,t.eventJson)!==void 0)continue;if(yield JSON.parse(t.eventJson))this.insertSeen.run(e,t.eventJson);else this.rejected=true}}contains(e){return this.findSeen.get(hash(`sha256`,e,`buffer`),e)!==void 0}get complete(){return!this.rejected}addSeen(e,t=false){const n=t?JSON.parse(e):void 0;const r=isRecord(n)&&normalizeLegacyOpenAICodexTranscriptMetadata([n])>0?JSON.stringify(n):e;this.insertSeen.run(hash(`sha256`,r,`buffer`),r);return n}repairLegacyTranscript(e){this.database.exec(`DELETE FROM tree; DELETE FROM tree_sets; DELETE FROM selected; DELETE FROM user_keys;`);const t=this.database.prepare(`INSERT OR REPLACE INTO tree VALUES (?, ?)`);const n=this.database.prepare(`SELECT node_json FROM tree WHERE id = ?`);const lookup=e=>{const t=n.get(e);return t?JSON.parse(String(t.node_json)):void 0};const r=this.database.prepare(`INSERT OR IGNORE INTO tree_sets VALUES (?, ?)`);const i=this.database.prepare(`SELECT 1 FROM tree_sets WHERE kind = ? AND id = ?`);const a=this.database.prepare(`DELETE FROM tree_sets WHERE kind = ?`);const diskSet=e=>({add:t=>{r.run(e,t)},has:t=>i.get(e,t)!==void 0,clear:()=>{a.run(e)}});const o=diskSet(`repeated`);const s=this.database.prepare(`INSERT OR REPLACE INTO user_keys VALUES (?, ?, ?)`);const c=this.database.prepare(`SELECT event_json FROM rows WHERE source = ? AND seq = ?`);const l=this.database.prepare(`UPDATE rows SET event_json = ? WHERE source = ? AND seq = ?`);const u=diskSet(`normalized`);const storedEventJson=t=>{const n=c.get(e,t);if(!n)return;const r=String(n.event_json);if(!u.has(String(t)))return r;const i=JSON.parse(r);if(!isRecord(i))return r;normalizeLegacyOpenAICodexTranscriptMetadata([i]);return JSON.stringify(i)};let d=false;let f=true;let p;let m;let h;let g;const _=this.rows(e);function*entries(){for(const e of _){const t=JSON.parse(e.eventJson);let n=e.eventJson;if(!isRecord(t)){f=false;continue}if(t.type===`session`){if(m&&equivalentLegacySessionHeaders(m,t)){o.add(String(e.seq));d=true;continue}if(p!==void 0||typeof t.id!==`string`)f=false;p??=e.seq;m??=t;continue}if(normalizeLegacyOpenAICodexTranscriptMetadata([t])>0){n=JSON.stringify(t);u.add(String(e.seq));d=true}const r=transcriptRepairUserKey(t,false);const i=transcriptRepairUserKey(t,true);if(typeof t.id===`string`&&(r||i))s.run(t.id,r?.slice(r.indexOf(`\0`)+1)??null,i??null);const a=isIndexedSessionEntry(t);const c=isSessionTranscriptLeafControl(t);if(!a&&!c)f=false;if(typeof t.id===`string`&&(a||c)){const r=lookup(t.id);if(r){if(storedEventJson(Number(r.entry.importSeq))===n){o.add(String(e.seq));d=true;continue}}}const l=projectTranscriptNavigationFields(t);h=l;yield{...l,importSeq:e.seq}}}const v=scanSessionTranscriptNavigation(entries(),{byId:{get:lookup,has:e=>n.get(e)!==void 0,set:(e,r)=>{if(n.get(e))f=false;t.run(e,JSON.stringify(r))}},addNode:e=>{if(e.leafId!==void 0)g=isSessionTranscriptLeafControl(e.entry)?e:void 0},resetDescendantIds:diskSet(`reset`),invalidLeafControlIds:diskSet(`invalid`)});for(const t of this.database.prepare(`SELECT id FROM tree_sets WHERE kind = 'normalized'`).iterate()){const n=Number(t.id);const r=storedEventJson(n);if(r!==void 0)l.run(r,e,n)}this.database.prepare(`DELETE FROM rows WHERE source = ? AND CAST(seq AS TEXT) IN (
SELECT id FROM tree_sets WHERE kind = 'repeated'
)`).run(e);const y=this.database.prepare(`INSERT OR REPLACE INTO selected VALUES (?, ?, ?, ?)`);const b=this.database.prepare(`SELECT 1 FROM selected WHERE id = ?`);const walk=(e,t)=>{const n=diskSet(`walk`);n.clear();let r=e;let i;while(r!==null){if(n.has(r))return false;n.add(r);const e=lookup(r);if(!e){f=false;break}if(!t&&(b.get(r)||isCanonicalSessionTranscriptEntry(e.entry)))break;if(!isSessionTranscriptLeafControl(e.entry)){if(i)y.run(i.id,Number(i.entry.importSeq),e.id,t?1:0);i=e}r=v.hasExplicitLeafUpdate?e.parentId:typeof e.entry.parentId===`string`&&e.entry.parentId.trim()?e.entry.parentId:null}if(i)y.run(i.id,Number(i.entry.importSeq),t?null:v.leafId,t?1:0);return true};const x=walk(v.hasExplicitLeafUpdate?v.leafId:typeof h?.id===`string`?h.id:null,true);const S=x&&this.database.prepare(`
SELECT 1 FROM user_keys inactive
JOIN user_keys active
JOIN selected s ON s.id = active.id AND s.visible = 1
AND inactive.stripped_key = COALESCE(s.parent_id, '') || char(0) || active.visible_key
WHERE NOT EXISTS (SELECT 1 FROM selected WHERE id = inactive.id) LIMIT 1
`).get()!==void 0;if(S&&p!==void 0){if(v.hasExplicitLeafUpdate){if(!walk(v.appendParentId,false))f=false}const t=this.database.prepare(`SELECT seq, parent_id FROM selected ORDER BY seq`);for(const n of t.iterate()){const t=c.get(e,n.seq);const r=JSON.parse(String(t.event_json));if(v.hasExplicitLeafUpdate)r.parentId=n.parent_id;l.run(JSON.stringify(r),e,n.seq)}let n=null;if(g){n=Number(g.entry.importSeq);const t=this.database.prepare(`SELECT id FROM selected ORDER BY seq DESC LIMIT 1`).get();const r=c.get(e,n);const i=JSON.parse(String(r.event_json));i.parentId=t?.id??null;i.appendParentId=v.appendParentId===null?null:b.get(v.appendParentId)?v.appendParentId:t?.id??null;l.run(JSON.stringify(i),e,n);const a=this.database.prepare(`SELECT MAX(seq) + 1 AS seq FROM rows WHERE source = ?`).get(e);this.database.prepare(`UPDATE rows SET seq = ? WHERE source = ? AND seq = ?`).run(a.seq,e,n);n=Number(a.seq)}this.database.prepare(`DELETE FROM rows WHERE source = ? AND seq <> ?
AND (? IS NULL OR seq <> ?) AND seq NOT IN (SELECT seq FROM selected)`).run(e,p,n,n);d=true}if(!x||v.hasInvalidLeafControl||p===void 0)f=false;const C=this.database.prepare(`SELECT COUNT(*) AS count FROM rows WHERE source = ?`).get(e);return{repaired:d,branchRepaired:S,events:Number(C.count),recognized:f}}};
//!src/infra/session-sqlite-transcript-verification.ts
function verifyTranscriptEvents(e,t,n=`ordered`){return withSqliteSessionImportStage(r=>{let i=0;const a=createTranscriptEventReader(t.path,t.sessionId,false,readTranscriptFingerprint(t.path),t.originalPath)(e=>r.append(0,i++,normalizeLegacyInboundContextLabelsJson(JSON.stringify(canonicalizeTranscriptEventMedia(e)))));const o=r.repairLegacyTranscript(0);if(n===`ordered`&&(o.repaired||!o.recognized)||o.branchRepaired&&!o.recognized)return;const s=getSessionKysely(e);const c=executeSqliteQueryTakeFirstSync(e,s.selectFrom(`transcript_events`).select(e=>e.fn.countAll().as(`count`)).where(`session_id`,`=`,t.sessionId)).count;const l=r.rows(0)[Symbol.iterator]();let u=l.next();try{for(const i of iterateSqliteQuerySync(e,s.selectFrom(`transcript_events`).select(transcriptEventJsonSql(e).as(`event_json`)).where(`session_id`,`=`,t.sessionId).orderBy(`seq`,`asc`))){const e=normalizeLegacyInboundContextLabelsJson(i.event_json);if(n!==`ordered`){const t=r.addSeen(e,true);if(isRecord(t)&&typeof t.id===`string`)r.addSeen(`id\0${t.id}`)}if(!u.done&&e===u.value.eventJson){u=l.next();if(u.done)break}}}finally{l.return?.()}if(n===`ordered`||u.done){a();return u.done?{events:o.events,missingEvents:0,sqliteEvents:c}:void 0}let d=0;let f;for(const e of r.rows(0)){const t=JSON.parse(e.eventJson);const i=isRecord(t)&&typeof t.id===`string`?t.id:`row ${e.seq+1}`;if(r.contains(e.eventJson)){if(f!==void 0)throw new Error(`Missing legacy event ${f} precedes existing event ${i}; only a missing suffix can be appended`);continue}if(n!==`appendable`)return;if(r.contains(`id\0${i}`))throw new Error(`Legacy event ${i} conflicts with the SQLite event of the same identity`);f??=i;d+=1}if(d>0&&(o.branchRepaired||!o.recognized))return;a();return{events:o.events,missingEvents:d,sqliteEvents:c}})}function verifyCanonicalSessionTranscriptSources(e){const t=withOpenClawAgentDatabaseReadOnly(t=>{let n=0;let r=0;let i=0;for(const a of e.sources){const o=verifyTranscriptEvents(t.db,{...a,originalPath:a.originalPath??a.path},e.mode);if(!o)return;n+=o.events;r+=o.missingEvents;i+=o.sqliteEvents}return{entries:e.sources.length,events:n,missingEvents:r,sqliteEvents:i}},{agentId:e.target.agentId,path:e.target.sqlitePath,env:e.env});return t.found?t.value:void 0}
//!src/commands/doctor-session-sqlite-verification.ts
function isOriginalBesideDestination(e,t,n){const r=e.kind===`database-backup`?e.artifact:void 0;const i=r?.disposal.state===`pending-disposal`&&!statMigrationPath(e.archivePath)?r.disposal.claimPath:e.archivePath;const a=statMigrationPath(i,{bigint:true});return Boolean(r&&path.dirname(i)===path.dirname(t)&&a?.isFile()&&a.dev===n.dev&&String(a.ino)===r.identity.ino&&String(a.mtimeNs)===r.identity.mtimeNs&&a.size===BigInt(r.identity.size))}function createRecoveryDestinationVerifier(e,t,n={}){const r=/* @__PURE__ */ new Map;return i=>{for(const{target:a,run:o,move:s}of i){const i=s.artifact?.disposal;if(i?.state===`pending-disposal`&&!statMigrationPath(s.archivePath)&&!statMigrationPath(i.claimPath))continue;const c=resolveSqliteDatabaseFilePaths(a.sqlitePath);assertDoctorSqliteMaintenancePathsNotAliased(`update recovery cleanup`,c,[e]);const l=r.get(a.sqlitePath);let u=l?.agentId;if(!l){const e=inspectOpenClawAgentDatabaseOwner(a.sqlitePath);u=e.status===`owned`?e.agentId:void 0}if(!a.databaseIdentity&&u!==a.agentId)throw new Error(`destination database ownership cannot be verified`);const d=c.map(e=>fs.lstatSync(e,{bigint:true,throwIfNoEntry:false}));if(!d[0]?.isFile()||a.databaseIdentity&&String(d[0]?.ino)!==a.databaseIdentity.ino||d.some(e=>e&&(!e.isFile()||e.nlink!==1n))||l&&[`dev`,`ino`].some(e=>d[0]?.[e]!==l.files[0]?.[e])||l&&!n.allowOwnedMutation&&d.some((e,t)=>(t===0?[`ctimeNs`,`mtimeNs`,`size`]:[`dev`,`ino`,`size`]).some(n=>e?.[n]!==l.files[t]?.[n])))throw new Error(`Recovery destination database changed; preview cleanup again.`);const f=a.databaseIdentity;const p=f!==void 0&&f.dev!==String(d[0].dev);const m=p&&isOriginalBesideDestination(s,a.sqlitePath,d[0]);const h=n.allowOwnedMutation&&(!p||m)?void 0:readSqliteFileGenerationSync(a.sqlitePath);if(h&&[[`database`,0],[`wal`,1],[`journal`,3]].some(([e,t])=>h[e]?.dev!==d[t]?.dev||h[e]?.ino!==d[t]?.ino||h[e]?.size!==d[t]?.size||l&&!n.allowOwnedMutation&&h[e]?.sha256!==l.generation?.[e]?.sha256))throw new Error(`Recovery destination database changed; preview cleanup again.`);if(f&&p){const e=s.kind===`database-backup`&&s.sourcePath===a.sqlitePath&&!s.archivePath.endsWith(`.scoped.bak`)&&s.artifact?.classification===`repair-original`?s.artifact.identity:void 0;if(!m&&(!h||(h.wal?.size??0n)>32n||(h.journal?.size??0n)>0n||h.database.sha256!==(f.sha256??e?.sha256)))throw new Error(`Recovery destination device changed from ${f.dev} to ${d[0].dev}; destination contents could not be verified against recorded recovery evidence. Originals retained. Run openclaw doctor --fix to check current state; retain the originals for manual verification.`);t();a.databaseIdentity={...f,dev:String(d[0].dev),...h&&!m&&{sha256:h.database.sha256}};writeSessionSqliteMigrationManifest(o)}r.set(a.sqlitePath,{agentId:u,files:d,generation:h})}}}function verifyHistoricalMigrationArtifact(e){const{target:t,move:n,env:r}=e;if(n.kind!==`legacy-store`&&n.kind!==`transcript`)return;const i=readMigrationArtifactIdentity(n.archivePath);const a=n.kind===`legacy-store`?n:uniqueRestoreMoves(t).find(e=>e.kind===`legacy-store`);if(!a)return;readMigrationArtifactIdentity(a.archivePath);const o=fs.openSync(a.archivePath,fs.constants.O_RDONLY|(fs.constants.O_NOFOLLOW??0));let s;try{s=JSON.parse(readFileDescriptorBoundedSync(o,fs.fstatSync(o).size).toString(`utf8`))}finally{fs.closeSync(o)}if(!isRecord(s))return;const c=n.kind===`legacy-store`?Object.entries(s):n.sessionKey?[[n.sessionKey,s[n.sessionKey]]]:[];if(n.kind===`transcript`&&c.length!==1)return;const l=new Set(n.kind===`legacy-store`?uniqueRestoreMoves(t).filter(e=>e.kind===`transcript`).map(e=>e.sourcePath):[]);const u=withOpenClawAgentDatabaseReadOnly(e=>{const r=getSessionKysely(e.db);for(const[i,a]of c){if(typeof i!==`string`||!isRecord(a)||typeof a.sessionId!==`string`||!a.sessionId.trim()||typeof a.updatedAt!==`number`)return false;const o=a.sessionId;const s=executeSqliteQueryTakeFirstSync(e.db,r.selectFrom(`session_nodes`).select([`current_session_id`,`entry_json`]).select(sessionEntrySnapshotColumns).where(`session_key`,`=`,i));if(!s||s.current_session_id!==a.sessionId)return false;const c=JSON.parse(s.entry_json);if(!isRecord(c))return false;attachSessionEntrySnapshots(c,s);const u={...a,sessionId:o,updatedAt:a.updatedAt};const d=migrateLegacySessionCreator(normalizeLegacySessionEntryDelivery(u));if(Object.entries(d).some(([e,t])=>e!==`sessionFile`&&JSON.stringify(c[e])!==JSON.stringify(t)))return false;if(n.kind!==`transcript`){for(const e of resolveLegacyTranscriptPaths(t,u).transcriptDependencies)l.add(canonicalMigrationFilePath(e));continue}if(!verifyTranscriptEvents(e.db,{path:n.archivePath,originalPath:n.sourcePath,sessionId:o}))return false}return true},{agentId:t.agentId,path:t.sqlitePath,env:r});if(!u.found||!u.value)return;return{identity:i,classification:`imported`,reason:`verified-historical-import`,dependencies:[...l],disposal:{state:`retained`}}}function validateLegacySessionRecords(e,t,n,r,i){if(n.issues.some(e=>e.code===`legacy_import_deferred`&&!e.sessionKey))return false;if(r===`before-archive`&&t.length===0)return true;const a=n.issues.length;const o=readSessionImportValidationSnapshot(e,i);if(!o.ok){n.issues.push({code:`sqlite_read_failed`,message:`Session validation read failed: ${String(o.error)}`});return false}for(const e of t)validateLegacySessionRecord(e,n,o.snapshot,r,i);return n.issues.length===a}function validateLegacySessionRecord(e,t,n,r,i){const a=r===`before-archive`;const hasIssue=n=>t.issues.some(t=>t.code===n&&t.sessionKey===e.sessionKey);const recordIssue=(n,r)=>t.issues.push({code:n,message:r,sessionKey:e.sessionKey});const o=a?e.sessionKey:normalizeStoreSessionKey(e.sessionKey);const s=e.historical||e.preserveCurrentSession?n.sessionKeysBySessionId.get(e.entry.sessionId)===o?e.entry.sessionId:void 0:n.sessionIdsBySessionKey.get(o);if(!s){recordIssue(`sqlite_entry_missing`,`Session entry is missing for ${o}.`);return}if(s!==e.entry.sessionId){recordIssue(`sqlite_entry_mismatch`,`Stored sessionId ${s} does not match ${e.entry.sessionId}.`);return}if(a&&e.preserveCurrentSession&&hasIssue(`legacy_import_deferred`))return;if(!a)t.validatedEntries+=1;const c=countTranscriptEventsForPath(e.transcriptPath);if(c.status===`missing`){if(!a)t.validatedTranscriptEvents+=n.transcriptEventCountsBySessionId.get(e.entry.sessionId)??0;return}if(c.status!==`ok`){if(!hasIssue(`transcript_malformed`))recordIssue(`transcript_malformed`,c.message);return}const l=n.transcriptEventCountsBySessionId.get(e.entry.sessionId)??0;const u=a?e.recovery?.sqliteEvents??e.recovery?.events??c.events:c.events;if(!(a||!e.transcriptPath?l>=u:verifyCanonicalSessionTranscriptSources({target:t,mode:`contained`,sources:[{path:e.transcriptPath,sessionId:e.entry.sessionId,originalPath:e.historical?.originalPath}],env:i}))){recordIssue(`sqlite_transcript_count_mismatch`,a?`Stored transcript has ${l} events; verified import expects ${u}.`:`Stored transcript has ${l} events; source has ${c.events}, but its events are not all present with matching content. Run openclaw doctor --session-sqlite recover to import a missing suffix or identify conflicting events.`);return}if(!a)t.validatedTranscriptEvents+=l}
//!src/commands/update-cleanup-unmanifested.ts
function overlaps(e,t){const n=resolvePathViaExistingAncestorSync(t);return isPathInside(e,n)||isPathInside(n,e)}function pendingRecoveryRoots(e){return inspectUpdateRecoveries({env:e}).filter(({record:e})=>isUpdateRecoveryPending(e)).flatMap(({record:t})=>{return[t.preimages?.ref.manifestPath,t.checkpoint?.ref.manifestPath,t.checkpoint?.preimageRef?.manifestPath,t.restore?.planPath,...(t.afterImages??[]).flatMap(e=>[e.checkpointRef.manifestPath,e.afterUpdate.ref.manifestPath,e.afterUpdate.preimageRef?.manifestPath])].filter(e=>Boolean(e)).map(e=>path.dirname(resolvePathViaExistingAncestorSync(e))).concat(absolutePaths(t.package,e),t.effects.flatMap(t=>absolutePaths(t.package,e)),t.effects.map(e=>e.resourceId).filter(e=>path.isAbsolute(e)))})}function absolutePaths(e,t){if(typeof e===`string`)return path.isAbsolute(e)||e.startsWith(`~/`)?[resolveUserPath(e,t)]:[];if(!e||typeof e!==`object`)return[];return Object.values(e).flatMap(e=>absolutePaths(e,t))}function activePaths(e,t,n){return[path.join(n.report.stateDir,`state`,`openclaw.sqlite`),...absolutePaths(e,t),...resolveAllAgentSessionStoreCandidateTargetsSync(e,{env:t}).flatMap(e=>[e.storePath,resolveTargetSqlitePath(e,t)]),...[...n.references.values()].flatMap(e=>e.flatMap(({target:e})=>[e.storePath,e.sqlitePath]))].flatMap(e=>{const t=path.resolve(e);const n=fs.existsSync(t)?fs.realpathSync(t):t;return resolveSqliteDatabaseFilePaths(t).concat(resolveSqliteDatabaseFilePaths(n))})}function assertNotDatabase(e,t){if(t.some(t=>isPathInside(e,t))||SQLITE_SIDECAR_SUFFIXES.some(t=>e.endsWith(t))||SQLITE_SIDECAR_SUFFIXES.some(t=>fs.lstatSync(`${e}${t}`,{throwIfNoEntry:false})))throw new Error(`Active database path or database sidecar; keep the database family intact.`)}function inspectSelection(e,t){const n=/* @__PURE__ */ new Map;if(hasSymbolicLinkInDirectoryPath(path.dirname(e.path))||fs.realpathSync(e.path)!==e.path)throw new Error(`Recovery path is aliased.`);const r=[e.path];while(r.length>0){const i=r.pop();const a=fs.lstatSync(i,{bigint:true});assertNotDatabase(i,t);if(a.isDirectory()&&e.kind===`update-capture`){n.set(i,{stat:a});for(const e of fs.readdirSync(i).toSorted().toReversed())r.push(path.join(i,e))}else if(a.isFile()&&a.nlink===1n){if(e.kind!==`update-capture`&&/\.(?:sqlite(?:3)?|db)$/iu.test(i))throw new Error(`Live database filename is not an unmanifested recovery original.`);n.set(i,{stat:a,sha256:readMigrationArtifactIdentity(i).sha256})}else throw new Error(`Recovery selection contains a symlink, hardlink, or nonregular file.`)}return n}function selectUnmanifestedRecovery(e){const t=/* @__PURE__ */ new Map;if(!e.paths?.length)return t;const{inventory:n}=e;const r=[...new Set(e.paths.map(e=>path.resolve(e)))];withSynchronousArtifactPreservingStateSnapshot(()=>{const i=pendingRecoveryRoots(e.env);const a=activePaths(e.cfg,e.env,n);for(const e of r){const r=n.report.artifacts.find(t=>t.path===e);if(!r||r.outcome!==`protected`||![`unmanifested-recovery-original`,`orphan-update-capture`,`superseded-unsealed-capture`].includes(r.reason))throw new Error(`Cannot include unmanifested path ${e}: not an eligible known recovery original or orphan capture.`);if(n.report.artifacts.some(e=>[`unreadable-manifest`,`manifest-directory-alias`].includes(e.reason)))throw new Error(`Cannot include unmanifested recovery with unreadable recovery dependencies.`);if(i.some(t=>overlaps(e,t))||[...n.references.values()].some(t=>t.some(({move:t})=>[t.sourcePath,t.archivePath,...t.artifact?.dependencies??[],...t.artifact?.disposal.state===`pending-disposal`?[t.artifact.disposal.claimPath]:[]].some(t=>overlaps(e,t)))))throw new Error(`Cannot include ${e}: pending or retained recovery references this path.`);t.set(e,inspectSelection(r,a))}},{current:{env:e.env}});for(const[e,r]of t){const t=n.report.artifacts.find(t=>t.path===e);const{stat:i}=r.get(e);t.outcome=`candidate`;t.reason=`explicit-unmanifested-selection`;t.bytes=[...r.values()].reduce((e,{stat:t})=>e+(t.isFile()?Number(t.size):0),0);t.modifiedAt=new Date(Number(i.mtimeMs)).toISOString();t.detail=`Explicitly selected with --include-unmanifested. No import or rollback proof is inferred.`;t.consequence=t.kind===`update-capture`?`Permanently deletes this orphan original-state capture and all recovery generations inside it.`:`Permanently deletes this unmanifested original; pre-repair history, branches, and metadata may be unrecoverable.`}n.report=summarizeRecoveryCleanup(n.report.stateDir,n.report.artifacts,`preview`,n.report.missingOriginals);return t}function assertUnmanifestedSelectionCurrent(e,t){for(const[n,r]of e){const e=t.get(n);if(!e||r.size!==e.size||[...r].some(([t,{stat:n,sha256:r}])=>{const i=e.get(t);return!i||!sameFileMutationFingerprint(n,i.stat)||r!==i.sha256}))throw new Error(`Explicit recovery selection changed: ${n}; preview cleanup again.`)}}async function retireUnmanifestedRecovery(e){for(const[t,n]of e.selected.entries())try{e.onProgress?.(n,t);e.assertCurrent();await e.assertReferences(n);e.assertCurrent();const r=e.identities.get(n.path);const i=inspectSelection(n,[]);assertUnmanifestedSelectionCurrent(/* @__PURE__ */ new Map([[n.path,r]]),/* @__PURE__ */ new Map([[n.path,i]]));for(const[t,{stat:i,sha256:a}]of[...r].toReversed()){e.assertCurrent();if(hasSymbolicLinkInDirectoryPath(path.dirname(t)))throw new Error(`Recovery directory changed before removal.`);const r=fs.lstatSync(t,{bigint:true});if(i.isDirectory()){if(!r.isDirectory()||r.dev!==i.dev||r.ino!==i.ino)throw new Error(`Recovery directory changed before removal.`);fs.rmdirSync(t)}else{if(!r.isFile()||r.nlink!==1n||!sameFileMutationFingerprint(i,r)||readMigrationArtifactIdentity(t).sha256!==a)throw new Error(`Recovery original changed before removal.`);assertNotDatabase(t,[]);fs.unlinkSync(t);n.removedBytes=(n.removedBytes??0)+Number(i.size)}}n.outcome=`removed`;n.reason=`explicit-unmanifested-retired`;requireDirectorySync(await syncDirectory(path.dirname(n.path)),`Explicit recovery retirement`)}catch(r){n.outcome=`failed`;n.reason=`explicit-unmanifested-retirement-failed`;n.detail=String(r);for(const n of e.selected.slice(t+1)){n.outcome=`blocked`;n.reason=`retirement-stopped`}break}}
//!src/commands/doctor-session-sqlite-retirement.ts
function assertRecoveryOriginal(e,t,n){const r=statMigrationPath(e)?e:t.disposal.state===`pending-disposal`?t.disposal.claimPath:e;if(!statMigrationPath(r)){if(t.disposal.state===`pending-disposal`)return;throw new Error(`artifact is unexpectedly missing`)}const i=isPendingMigrationArtifactClaim(e,t)?2n:1n;const a=readMigrationArtifactIdentity(r,i,void 0,n);if(!sameMigrationArtifact(a,t.identity,{ignoreDevice:true}))throw new Error(`artifact identity or contents changed`);return a}async function settleDuplicateSessionSqliteArchives(e){const{claims:t,inventory:{artifacts:n,references:r}}=collectHistoricalArchiveSources(e);const i=[];const recordFailure=(e,t)=>{i.push({target:e,issues:[{code:`historical_transcript_deferred`,message:`${t}; original retained.`}]})};const a=[];const o=/* @__PURE__ */ new Map;for(const e of n)if(!o.has(e.path))o.set(e.path,e);const s=/* @__PURE__ */ new Map;const assertSurvivor=e=>{const t=s.get(e[0].move.archivePath);if(hasSymbolicLinkInDirectoryPath(path.dirname(t.archivePath)))throw new Error(`Retained duplicate archive directory changed.`);assertRecoveryOriginal(t.archivePath,t.artifact)};for(const n of t){const t=n[0][0].target;if(!e.targets.some(e=>e.agentId===t.agentId&&e.storePath===t.storePath&&e.sqlitePath===t.sqlitePath))continue;const r=n.find(e=>e.every(e=>e.move.artifact.disposal.state===`retained`)&&statMigrationPath(e[0].move.archivePath));if(!r)continue;for(const e of n.filter(e=>e!==r)){const n=o.get(e[0].move.archivePath);s.set(n.path,r[0].move);try{assertSurvivor(e);const t=resolveRecoveryArtifact(e);if(e.some(e=>e.move.artifact.disposal.state===`disposed`)&&statMigrationPath(n.path))throw new Error(`Archive was recreated after disposal.`);if(t.disposal.state===`pending-disposal`||t.disposal.state===`retained`&&statMigrationPath(n.path)){assertRecoveryOriginal(n.path,t);n.outcome=`candidate`;a.push(n)}}catch(e){s.delete(n.path);recordFailure(t,`${n.path}: ${String(e)}`)}}}await disposeRecoveryArtifacts({selected:a,references:r,assertDestinations:assertSurvivor});for(const[e]of s){const t=r.get(e);if(t.every(e=>e.move.artifact.disposal.state===`disposed`)||t.every(e=>e.move.artifact.disposal.state===`retained`)&&!statMigrationPath(e))assertSurvivor(t);else{s.delete(e);const n=o.get(e);recordFailure(t[0].target,`${e}: ${n.detail??n.reason}`)}}return[...i,...coalesceSessionSqliteArchiveReferences(s,[...new Set([...r.values()].flatMap(e=>e.map(e=>e.run)))])]}function assertRecoveryStateWriteAllowed(e,t){return assertOpenClawStateWriteAllowedAtPath({databasePath:path.join(e,`state`,`openclaw.sqlite`),env:t,recoverOrphanedSidecars:false})}async function retireSessionSqliteRecovery(e){await assertRecoveryStateWriteAllowed(e.preview.stateDir,e.env);return withDoctorSqliteMaintenanceLock({env:e.env,operation:`update recovery cleanup`,run:t=>retireOwnedSessionSqliteRecovery(e,t)})}async function retireOwnedSessionSqliteRecovery(e,t){t.assertCurrent();const n=await e.readConfig();const r=await collectUpdateCleanupInventoryAsync({cfg:n,env:e.env,current:true});t.assertCurrent();const i=selectUnmanifestedRecovery({inventory:r,cfg:n,env:e.env,paths:e.includeUnmanifested});const{report:a,references:o,manifestPaths:s,captureIdentities:c}=r;t.assertCurrent();if(a.stateDir!==e.preview.stateDir||JSON.stringify(a.artifacts)!==JSON.stringify(e.preview.artifacts))throw new Error(`Recovery selection changed; preview cleanup again.`);await assertRecoveryStateWriteAllowed(a.stateDir,e.env);const l=/* @__PURE__ */ new Map;const u=/* @__PURE__ */ new Map;const d=createRecoveryDestinationVerifier(a.stateDir,()=>t.assertCurrent(),{allowOwnedMutation:e.allowOwnedDestinationMutation});const f=a.artifacts.filter(e=>e.kind!==`update-capture`&&!i.has(e.path)&&(e.outcome===`candidate`||e.outcome===`verification-required`));const p=e.verifyHistorical===false&&a.artifacts.some(e=>o.get(e.path)?.some(e=>!e.move.artifact));for(const[t,n]of f.entries()){e.onProgress?.({phase:`verifying`,path:n.path,index:t+1,total:f.length,bytes:n.bytes});if(p){if(n.outcome===`candidate`)n.reason=`historical-recovery-dependencies-unverified`;n.outcome=`protected`;continue}if(n.outcome===`verification-required`){const t=o.get(n.path);try{for(const n of t){if(n.move.artifact)continue;const t=verifyHistoricalMigrationArtifact({target:n.target,move:n.move,env:e.env});if(!t)throw new Error(`historical-import-proof-unavailable`);l.set(n,t)}n.outcome=`candidate`;n.reason=`verified-historical-import`}catch(e){n.outcome=`protected`;n.reason=`historical-import-proof-unavailable`;n.detail=String(e)}}if(n.outcome!==`candidate`)continue;try{const e=o.get(n.path);const t=resolveRecoveryArtifact(e)??l.get(e[0]);assertRecoveryOriginal(n.path,t,u)}catch(e){n.outcome=`blocked`;n.reason=`artifact-verification-failed`;n.detail=String(e)}}for(const e of a.artifacts){if(e.outcome!==`candidate`||e.kind===`update-capture`||i.has(e.path))continue;try{d(o.get(e.path))}catch(t){e.outcome=`blocked`;e.reason=`destination-verification-failed`;e.detail=String(t)}}protectRecoveryDependencies(a.artifacts,o,l);const m=summarizeRecoveryCleanup(a.stateDir,a.artifacts,`preview`,a.missingOriginals);const h=m.artifacts.filter(e=>e.outcome===`candidate`);const g=h.filter(e=>i.has(e.path));const _=h.filter(e=>e.kind!==`update-capture`&&!i.has(e.path));const v=h.filter(e=>e.kind===`update-capture`&&!i.has(e.path));if(!await e.confirm(m))return{...m,status:`refused`};t.assertCurrent();const y=await e.readConfig();const b=await collectUpdateCleanupInventoryAsync({cfg:y,env:e.env,current:true});t.assertCurrent();const x=selectUnmanifestedRecovery({inventory:b,cfg:y,env:e.env,paths:e.includeUnmanifested});t.assertCurrent();assertUnmanifestedSelectionCurrent(i,x);if(b.report.stateDir!==a.stateDir||JSON.stringify(b.manifestPaths)!==JSON.stringify(s)||JSON.stringify(b.report.artifacts)!==JSON.stringify(e.preview.artifacts))throw new Error(`Recovery selection changed during confirmation; preview again.`);const manifests=e=>new Map([...e.values()].flat().map(({run:e})=>[e.manifestPath,e.manifest]));const S=manifests(b.references);for(const[e,t]of manifests(o))if(JSON.stringify(S.get(e))!==JSON.stringify(t))throw new Error(`Recovery manifest changed during confirmation; preview again.`);for(const e of[...o.values()].flat())if(!(b.references.get(e.move.archivePath)??[]).some(t=>t.trusted===e.trusted&&t.target.storePath===e.target.storePath&&t.target.sqlitePath===e.target.sqlitePath))throw new Error(`Recovery target changed during confirmation; preview again.`);await assertRecoveryStateWriteAllowed(a.stateDir,e.env);t.assertCurrent();for(const e of _){const t=o.get(e.path);d(t);assertRecoveryOriginal(e.path,resolveRecoveryArtifact(t)??l.get(t[0]),u)}for(const[e,t]of l){if(!_.some(t=>t.path===e.move.archivePath))continue;if(e.run.manifest.manifestVersion!==4)e.run.manifest.manifestVersion=3;for(const n of[...e.target.plannedMoves,...e.target.completedMoves])if(n.archivePath===e.move.archivePath)n.artifact=t}await disposeRecoveryArtifacts({selected:_,references:o,assertDestinations:d,assertCurrent:()=>t.assertCurrent(),verification:u,onProgress:e.onProgress});await retireUpdateCaptures({selected:v,identities:c,assertCurrent:()=>t.assertCurrent(),onProgress:(t,n)=>e.onProgress?.({phase:`removing-capture`,path:t.path,index:n+1,total:v.length,bytes:t.bytes})});await retireUnmanifestedRecovery({selected:g,identities:i,assertCurrent:()=>t.assertCurrent(),assertReferences:async n=>{const r=await e.readConfig();t.assertCurrent();const a=await collectUpdateCleanupInventoryAsync({cfg:r,env:e.env,current:true});t.assertCurrent();const o=selectUnmanifestedRecovery({inventory:a,cfg:r,env:e.env,paths:[n.path]});t.assertCurrent();assertUnmanifestedSelectionCurrent(/* @__PURE__ */ new Map([[n.path,i.get(n.path)]]),o)},onProgress:(t,n)=>e.onProgress?.({phase:`removing-unmanifested`,path:t.path,index:n+1,total:g.length,bytes:t.bytes})});return summarizeRecoveryCleanup(a.stateDir,a.artifacts,a.artifacts.some(e=>e.outcome===`failed`||e.outcome===`blocked`)?`blocked`:`complete`,a.missingOriginals)}async function disposeRecoveryArtifacts({selected:e,references:t,assertDestinations:n,assertCurrent:r,verification:i,onProgress:a}){const o=/* @__PURE__ */ new Set;const s=/* @__PURE__ */ new Map;const movesFor=(e,t)=>{let n=s.get(e.target);if(!n){n=/* @__PURE__ */ new Map;for(const t of[...e.target.plannedMoves,...e.target.completedMoves])if(t.artifact){const e=n.get(t.archivePath)??[];e.push(t);n.set(t.archivePath,e)}s.set(e.target,n)}return n.get(t)??[]};for(const n of e){const e=t.get(n.path);const r=e.map(({move:e})=>e.artifact.disposal).find(e=>e.state===`pending-disposal`)??{state:`pending-disposal`,intendedAt:(/* @__PURE__ */ new Date()).toISOString(),phase:`intent`,claimPath:path.join(path.dirname(n.path),`.cleanup-${randomUUID()}`)};for(const t of e){for(const e of movesFor(t,n.path))e.artifact.disposal=r;o.add(t.run)}}for(const e of o){r?.();writeSessionSqliteMigrationManifest(e)}let c;const l=e.map(e=>{const n=t.get(e.path);const r=n[0].move.artifact;const i=r.disposal;if(i.state!==`pending-disposal`||path.dirname(i.claimPath)!==path.dirname(e.path)||!path.basename(i.claimPath).startsWith(`.cleanup-`))throw new Error(`invalid disposal claim`);return{item:e,refs:n,artifact:r,disposal:i,present:false}});try{for(const[e,t]of l.entries()){const{item:o,refs:s,artifact:u,disposal:d}=t;c=o;a?.({phase:`claiming`,path:o.path,index:e+1,total:l.length,bytes:o.bytes});r?.();n(s);if(hasSymbolicLinkInDirectoryPath(path.dirname(o.path)))throw new Error(`archive directory changed`);if(statMigrationPath(o.path)){if(d.phase===`unlink-pending`)throw new Error(`archive was recreated after claim`);const e=assertRecoveryOriginal(o.path,u,i);if(!e)throw new Error(`artifact is unexpectedly missing`);await moveMigrationArtifact(o.path,d.claimPath,e,()=>{r?.()},void 0,i)}r?.();n(s);assertRecoveryOriginal(o.path,u,i);t.present=statMigrationPath(d.claimPath)!==void 0;d.phase=`unlink-pending`}for(const e of o){r?.();writeSessionSqliteMigrationManifest(e)}for(const{item:e,artifact:t,disposal:n,present:r}of l){c=e;if(hasSymbolicLinkInDirectoryPath(path.dirname(e.path)))throw new Error(`archive directory changed`);if(statMigrationPath(e.path))throw new Error(`archive was recreated after claim`);assertRecoveryOriginal(e.path,t,i);if(r!==(statMigrationPath(n.claimPath)!==void 0))throw new Error(`disposal claim changed after intent`)}r?.();for(const{item:e,refs:t}of l){c=e;n(t)}for(const{item:e,artifact:t,disposal:n}of l){c=e;const i=statMigrationPath(n.claimPath);if(i){r?.();fs.unlinkSync(n.claimPath);e.removedBytes=t.identity.size}e.outcome=i?`removed`:`disposed`;e.bytes=i?t.identity.size:0;e.reason=i?`rollback-original-retired`:`completed-interrupted-disposal`}const e=/* @__PURE__ */ new Set;for(const{item:t,refs:i}of l){c=t;const a=path.dirname(t.path);if(t.outcome===`removed`&&!e.has(a)){requireDirectorySync(await syncDirectory(a),`Recovery artifact removal`);e.add(a)}r?.();n(i);for(const e of i)for(const n of movesFor(e,t.path))n.artifact.disposal={state:`disposed`,disposedAt:(/* @__PURE__ */ new Date()).toISOString()}}for(const e of o){r?.();writeSessionSqliteMigrationManifest(e)}}catch(t){if(c){c.outcome=`failed`;c.reason=`artifact-retirement-failed`;c.detail=String(t)}for(const t of e)if(t.outcome===`candidate`){t.outcome=`blocked`;t.reason=`retirement-stopped`}}}export{validateLegacySessionRecords as a,appendLegacyHistoricalTranscripts as c,listUnreferencedJsonlFiles as d,readLegacySessionRecords as f,selectUnmanifestedRecovery as i,collectHistoricalArchiveSources as l,retireSessionSqliteRecovery as n,verifyCanonicalSessionTranscriptSources as o,settleDuplicateSessionSqliteArchives as r,withSqliteSessionImportStage as s,retireOwnedSessionSqliteRecovery as t,gatherLegacyArchiveCoverage as u};