UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

27 lines • 24.9 kB
import{a as asOptionalRecord}from"./record-coerce-BTbqdJ3-.mjs";import{r as resolveStateDir}from"./state-dir-BwIClCab.mjs";import"./paths-D_FOvGon.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{r as isIncognitoSessionKey}from"./session-key-DYtwLLn1.mjs";import{N as parseAgentSessionKey,l as resolveAgentIdFromSessionKey,w as isSubagentSessionKey}from"./session-key-BPgKfU2m.mjs";import{t as formatCliCommand}from"./command-format-D7KhNLP0.mjs";import{f as resolveAgentWorkspaceDir,r as resolveAgentConfig,x as resolveSessionAgentId}from"./agent-scope-config-CG9CFpGX.mjs";import{n as isPostgresSqlConnection}from"./sql-connection-nx8lLUJM.mjs";import{_ as sql,i as executeSqliteQuerySync}from"./kysely-sync-R08Pt8qn.mjs";import{a as getActiveOpenClawStateDatabaseReadSnapshotAsync}from"./openclaw-state-db-readonly-Cd5_cxBs.mjs";import{i as prepareArtifactPreservingSqliteRead}from"./sqlite-snapshot-source-DbIgYrJe.mjs";import{r as cloneEnvWithPlatformSemantics}from"./config-env-vars-DCDGIBtT.mjs";import"./agent-scope-Dw5XRSEh.mjs";import{a as normalizeExecSecurity,l as resolveExecModeFromPolicy,o as normalizeExecTarget,r as normalizeExecAsk}from"./exec-approvals-core-BZ6-zeZE.mjs";import{a as closeOpenClawAgentDatabaseByPathAsync}from"./openclaw-agent-db-lifecycle-CWZDU3Sk.mjs";import{n as withOpenClawAgentDatabaseReadOnly}from"./openclaw-agent-db-readonly-BQsAKuqV.mjs";import{r as isOpenClawAgentDatabaseOpen}from"./openclaw-agent-db-BUym2U31.mjs";import{t as SessionTranscriptColdError}from"./session-transcript-cold-error-BRL-ewLR.mjs";import{l as hasInterSessionUserProvenance}from"./input-provenance-TIcSrNt5.mjs";import{t as applyExecPolicyLayer}from"./exec-policy-uFwIYzyl.mjs";import{t as SESSION_PERMISSION_BY_EXEC_MODE}from"./session-permission-exec-mode-CZtu8XtF.mjs";import{r as resolveAgentMainSessionKey}from"./main-session-C6FGqx0x.mjs";import{i as toDatabaseOptions,t as getSessionKysely}from"./session-accessor.sqlite-scope-helpers-_Zyjm1vW.mjs";import{o as resolveSqliteScope}from"./session-accessor.sqlite-read-scope-CSiIGQT-.mjs";import"./session-accessor.sqlite-scope-BHH23mIq.mjs";import{i as INTERNAL_WAKE_TRANSCRIPT_PROMPTS}from"./heartbeat-D5m0I0bZ.mjs";import{n as projectSessionDisplayMessage}from"./session-display-projection-iqGs3vmJ.mjs";import{r as isSessionTranscriptProjectionUnavailableError}from"./session-transcript-projection-error-Dl5r5Bis.mjs";import{r as parseReadableSqliteSessionEntryRow}from"./session-accessor.sqlite-entry-read-DBsgM_K3.mjs";import{t as resolveAgentSessionDirs}from"./session-dirs-BtgdncNf.mjs";import{y as scanDoctorSessionEntriesTolerant}from"./session-accessor-CY8UYP4m.mjs";import"./session-accessor.sqlite-entry-store-Cxqr6m6F.mjs";import{i as patchSessionEntryCore}from"./session-accessor.sqlite-entry-CQTjQD5y.mjs";import{a as readSessionTranscriptMessageEventPage,i as readSessionTranscriptBoundedMessageTailPage}from"./session-accessor.sqlite-active-events-kN9XyaPe.mjs";import{t as deriveGoalSessionTitle}from"./derive-goal-session-title-BuUeW8o8.mjs";import{s as listRegistryWorktreesForMigration}from"./registry-CTo2PEDq.mjs";import{t as hasExplicitSessionName}from"./session-title-state-CV8qI-Qb.mjs";import{a as resolveExecTarget}from"./bash-tools.exec-target-CnAB4few.mjs";import{n as createLegacyStateMigrationStepReceipt}from"./state-migrations.messages-BurXA9TV.mjs";import{r as listExistingAgentDatabaseTargets}from"./session-sqlite-migration-readers-Cc_cphZg.mjs";import{n as repairAcpSessionMetaKeysForDoctor}from"./state-migrations.plugin-doctor-context-Di7kr6Ne.mjs";import{t as isHistoricalSessionSqliteMigrationIssue}from"./session-sqlite-migration-issues-DbtIl4bO.mjs";import{a as runPostSessionPluginDoctorStateRepairs}from"./state-migrations.plugin-doctor-B2U6Zptn.mjs";import{t as note}from"./note-e4DtVgg2.mjs";import{n as normalizeLegacyOpenAICodexTranscriptMetadata,r as selectActivePath,t as hasBrokenPromptRewriteBranch}from"./legacy-transcript-repair-CorMRh9Q.mjs";import{i as withDoctorSqliteMaintenanceLock,t as DoctorSqliteMaintenanceLockUnavailableError}from"./doctor-sqlite-maintenance-lock-De_t-lkq.mjs";import{a as resolveProjectRegistry}from"./project-registry-CrFzyaNY.mjs";import{n as formatSessionSqliteMigrationWarnings,t as collectSessionSqliteMigrationFindings}from"./doctor-session-sqlite-warnings-DO7AVNSX.mjs";import{n as repairReservedIncognitoSessionKeys}from"./doctor-session-incognito-key-repair-BDNs6Hmq.mjs";import{n as runDoctorAgentDatabaseOperationAsync,t as runDoctorAgentDatabaseOperation}from"./doctor-agent-database-operation-4mGxDZqU.mjs";import{t as repairCanonicalSessionKeys}from"./doctor-session-canonical-keys-DFifjwO7.mjs";import{i as repairLegacySessionEntryStates,n as repairCanonicalSessionEntries,r as repairCanonicalSessionResolvedSkills,t as repairCanonicalSessionDeliveryStates}from"./doctor-session-delivery-state-BgDWu2TJ.mjs";import{r as isInformationalMissingSessionIndex}from"./doctor-session-sqlite-types-BEW7E-JN.mjs";import path from"node:path";import fs from"node:fs/promises";import{walkDirectory}from"@openclaw/fs-safe/walk"; //!src/commands/doctor-session-dashboard-chat-type.ts function isUnstampedDashboardRoot(e,t,n){if(e.chatType!==void 0||e.createdVia!==`operator`)return false;const r=parseAgentSessionKey(t);if(!r?.rest.startsWith(`dashboard:`)||isIncognitoSessionKey(t))return false;if(e.incognito||e.spawnedBy||e.forkSource||e.pluginOwnerId)return false;if(e.delivery?.kind===`external`)return false;return e.parentSessionKey===resolveAgentMainSessionKey({cfg:n,agentId:r.agentId})}async function repairLegacyDashboardChatTypes(e){const t=[];const n=await repairCanonicalSessionEntries({...e,updateDeliveryProjection:false,transform(n,r,i){if(!isUnstampedDashboardRoot(n,r,e.cfg))return n;if(i===(e.apply?`repair`:`scan`))t.push(r);return{...n,chatType:`direct`}}});if(t.length>0){const n=e.apply?`Recorded`:`Would record`;note([`- ${n} ${t.length} dashboard chat(s) as direct chats so their linked automations can use memory:`,...t.map(e=>` - ${e}`),...e.apply?[]:[`- Run "openclaw doctor --fix" to record them.`]].join(` `),`Session chat type`)}return n} //!src/commands/doctor-session-exec-policy.ts async function repairLegacySessionExecPolicy(e){const t=[];await repairCanonicalSessionEntries({...e,updateDeliveryProjection:false,transform(n,r,i){const{execSecurity:a,execAsk:o,...s}=n;if(a===void 0&&o===void 0)return n;let c=normalizeExecAsk(o);if(!s.permissionMode){const t=resolveSessionAgentId({sessionKey:r,config:e.cfg});const i=e.cfg.tools?.exec;const o=resolveAgentConfig(e.cfg,t)?.tools?.exec;const{effectiveHost:l}=resolveExecTarget({configuredTarget:normalizeExecTarget(n.execHost)??o?.host??i?.host,elevatedRequested:false,sandboxRequired:n.sandbox===`required`,sandboxAvailable:true});const u=applyExecPolicyLayer(applyExecPolicyLayer({security:l===`sandbox`?`deny`:`full`,ask:`off`},i),o);c??=u.ask;const d=resolveExecModeFromPolicy({security:normalizeExecSecurity(a)??u.security,ask:c});s.permissionMode=c===`always`?`read-only`:d===`full`?void 0:SESSION_PERMISSION_BY_EXEC_MODE[d]}if(i===(e.apply?`repair`:`scan`)){const i=s.permissionMode?`${n.permissionMode?`kept`:`set`} permissionMode=${s.permissionMode}${c===`always`&&!n.permissionMode?` (ask=always has no mode equivalent; choose guarded or workspace to allow commands again)`:``}`:`config default applies; full permission mode was not granted`;t.push(`- ${r}: ${e.apply?`removed`:`would remove`} legacy exec policy; ${i}.`)}return s}});if(t.length>0){if(!e.apply)t.push(`- Run "openclaw doctor --fix" to migrate legacy session exec policy.`);note(t.join(` `),`Session exec policy`)}} //!src/commands/doctor-session-title-repair.ts function readLegacySessionTitle(e){try{const{totalMessages:t}=readSessionTranscriptMessageEventPage(e,{maxMessages:0,offset:0});if(!t)return;const n=readSessionTranscriptBoundedMessageTailPage(e,{maxMessages:100,maxBytes:65536,offset:Math.max(0,t-100)});if(n.totalMessages!==t||n.events.length!==n.scannedMessages)return;for(const e of n.events){const t=asOptionalRecord(asOptionalRecord(e.event)?.message);const n=projectSessionDisplayMessage(t);if(n?.role===`user`&&!hasInterSessionUserProvenance(t))return deriveGoalSessionTitle(n.text)||void 0}return}catch(e){if(isSessionTranscriptProjectionUnavailableError(e)||e instanceof SessionTranscriptColdError)return;throw e}}async function repairLegacySessionTitles(e){const t=e.authority;const assertRepairAuthority=()=>{if(!t)throw new Error(`Session title repair requires Doctor maintenance ownership.`);t.assertCurrent()};if(e.apply)assertRepairAuthority();const n={found:0,repaired:0,scannedStores:0,warnings:[]};await getActiveOpenClawStateDatabaseReadSnapshotAsync({env:e.env});for(const t of e.targets??listExistingAgentDatabaseTargets(e.cfg,e.env)){if(e.apply)assertRepairAuthority();n.scannedStores++;await prepareArtifactPreservingSqliteRead(t.sqlitePath);const r={agentId:t.agentId,storePath:t.storePath,env:e.env};const i=runDoctorAgentDatabaseOperation({agentId:t.agentId,path:t.sqlitePath,run:()=>{const e=[];scanDoctorSessionEntriesTolerant(r,({entry:t,sessionKey:n,recoveredFromProjections:r})=>{const i=Object.values(INTERNAL_WAKE_TRANSCRIPT_PROMPTS).some(e=>t.displayName===e);if(!r&&!t.incognito&&!isIncognitoSessionKey(n)&&!isSubagentSessionKey(n)&&!hasExplicitSessionName(i?{...t,displayName:void 0}:t))e.push({sessionKey:n,sessionId:t.sessionId,clearWakeTitle:i})});return e}});if(!i.ok)continue;for(const{sessionKey:t,sessionId:a,clearWakeTitle:o}of i.value){if(e.apply)assertRepairAuthority();try{const i={...r,sessionKey:t,sessionId:a};const s=readLegacySessionTitle(i);if(!s&&!o)continue;n.found++;if(!e.apply)continue;await patchSessionEntryCore(i,()=>({displayName:s}),{preserveActivity:true,skipMaintenance:true,assertCommitAllowed:assertRepairAuthority,onCommitted:()=>{n.repaired++}});assertRepairAuthority()}catch(r){if(e.apply)assertRepairAuthority();n.warnings.push(`Could not repair the title for ${t}: ${String(r)}`)}}}return n} //!src/config/sessions/worktree-workspace-migration.ts function isInside(e,t){const n=path.relative(e,t);return n===``||!n.startsWith(`..`)&&!path.isAbsolute(n)}async function resolveLegacyCanonicalWorkspace(e){const t=e.entry.worktree;if(!t||t.canonicalWorkspaceDir)return;const n=path.resolve(t.repoRoot);if(e.entry.projectId){const t=await resolveProjectRegistry(e.cfg,e.entry.projectId,{env:e.env});const r=t?path.resolve(t.repoRoot):void 0;return r&&isInside(n,r)?r:void 0}const r=e.worktrees.find(e=>e.id===t.id);const i=e.entry.spawnedCwd;if(r?.ownerKind===`session`&&r.ownerId===e.sessionKey&&i&&path.resolve(r.repoRoot)===path.resolve(t.repoRoot)){const e=path.relative(path.resolve(r.path),path.resolve(i));if(e===``||!e.startsWith(`..`)&&!path.isAbsolute(e))return path.resolve(n,e)}const a=path.resolve(resolveAgentWorkspaceDir(e.cfg,e.agentId,e.env));return a&&a===n?a:void 0}function listLegacyWorktreeSessionEntries(e){const t=resolveSqliteScope({...e,sessionKey:``});const n=withOpenClawAgentDatabaseReadOnly(e=>{const t=getSessionKysely(e.db);const n=isPostgresSqlConnection(e.db);return executeSqliteQuerySync(e.db,t.selectFrom(`session_nodes`).selectAll().$if(!n,e=>e.where(sql`session_nodes.entry_valid != 1 OR ( json_valid(session_nodes.entry_json) AND json_type(session_nodes.entry_json, '$.worktree') = 'object' AND ( json_type(session_nodes.entry_json, '$.worktree.canonicalWorkspaceDir') IS NULL OR json_extract(session_nodes.entry_json, '$.worktree.canonicalWorkspaceDir') = '' ) )`)).orderBy(`session_key`,`asc`)).rows.flatMap(t=>{const r=parseReadableSqliteSessionEntryRow(e,t);if(!r)return[];const i=r.worktree;const a=i!==null&&typeof i===`object`&&!Array.isArray(i)&&(i.canonicalWorkspaceDir===void 0||i.canonicalWorkspaceDir===``);return!n||t.entry_valid!==1||a?[{databasePath:e.path,entry:r,sessionKey:t.session_key}]:[]})},toDatabaseOptions(t));return n.found?n.value:[]}async function migrateManagedWorktreeCanonicalWorkspaces(e){const t=cloneEnvWithPlatformSemantics(e.env??process.env);t.OPENCLAW_STATE_DIR=resolveStateDir(t);const n=listLegacyWorktreeSessionEntries({agentId:e.agentId,env:t,storePath:e.storePath});if(e.mode!==`doctor-fix`||n.length===0)return{found:n.length,repaired:0};const r=listRegistryWorktreesForMigration(t);let i=0;for(const{databasePath:a,entry:o,sessionKey:s}of n){const n=resolveAgentIdFromSessionKey(s,e.agentId);const c=await resolveLegacyCanonicalWorkspace({agentId:n,cfg:e.cfg,entry:o,env:t,sessionKey:s,worktrees:r});if(!c)continue;if((await patchSessionEntryCore({agentId:n,env:t,sessionKey:s,storePath:a},e=>{if(!e.worktree||e.worktree.id!==o.worktree?.id||e.worktree.repoRoot!==o.worktree.repoRoot||e.projectId!==o.projectId||e.spawnedCwd!==o.spawnedCwd||e.worktree.canonicalWorkspaceDir)return null;return{worktree:{...e.worktree,canonicalWorkspaceDir:c}}},{preserveActivity:true,skipMaintenance:true}))?.worktree?.canonicalWorkspaceDir===c)i+=1}return{found:n.length,repaired:i}} //!src/commands/doctor-session-worktree-workspace.ts async function repairLegacySessionWorktreeWorkspaces(e){const t=e.targets??listExistingAgentDatabaseTargets(e.cfg,e.env);let n=0;let r=0;for(const i of t){const t=isOpenClawAgentDatabaseOpen(i.sqlitePath);try{const t=await runDoctorAgentDatabaseOperationAsync({agentId:i.agentId,path:i.sqlitePath,run:()=>migrateManagedWorktreeCanonicalWorkspaces({agentId:i.agentId,cfg:e.cfg,env:e.env,storePath:i.sqlitePath,mode:e.apply?`doctor-fix`:`detect`})});if(t.ok){n+=t.value.found;r+=t.value.repaired}}finally{if(!t)await closeOpenClawAgentDatabaseByPathAsync(i.sqlitePath)}}return{found:n,repaired:r,scannedStores:t.length}} //!src/commands/doctor-session-transcripts.ts const SESSION_TRANSCRIPTS_CHECK_ID=`core/doctor/session-transcripts`;function parseTranscriptEntries(e){const t=[];for(const n of e.split(/\r?\n/)){if(!n.trim())continue;try{const e=JSON.parse(n);if(e&&typeof e===`object`&&!Array.isArray(e))t.push(e)}catch{return[]}}return t}async function inspectSessionTranscriptFile(e){const t={filePath:e,broken:false,originalEntries:0,activeEntries:0,legacyOpenAICodexEntries:0};try{if((await fs.stat(e)).size>1048576){t.deferred=true;t.reason=`Detailed branch/provider classification deferred to offline staged import.`;return t}const n=parseTranscriptEntries(await fs.readFile(e,`utf-8`));t.originalEntries=n.length;t.legacyOpenAICodexEntries=normalizeLegacyOpenAICodexTranscriptMetadata(n);const r=selectActivePath(n);t.activeEntries=r?.entries.length??0;t.broken=(r?hasBrokenPromptRewriteBranch(n,r.entries):false)||t.legacyOpenAICodexEntries>0}catch{}return t}async function listSessionTranscriptFiles(e){const t=[];for(const n of e){const{entries:e}=await walkDirectory(n,{maxDepth:1,include:e=>e.kind===`file`&&e.name.endsWith(`.jsonl`)});for(const r of e)t.push(path.join(n,r.name))}return t.toSorted((e,t)=>e.localeCompare(t))}async function detectSessionTranscriptHealthIssues(){let e;try{e=await resolveAgentSessionDirs(resolveStateDir(process.env))}catch{return[]}const t=await listSessionTranscriptFiles(e);const n=[];for(const e of t){const t=await inspectSessionTranscriptFile(e);if(t.broken||t.deferred)n.push(t)}return n}function sessionTranscriptIssueToHealthFinding(e){const t=e.legacyOpenAICodexEntries>0?` ${e.legacyOpenAICodexEntries} legacy OpenAI Codex metadata entr${e.legacyOpenAICodexEntries===1?`y`:`ies`}`:``;return{checkId:SESSION_TRANSCRIPTS_CHECK_ID,severity:`info`,message:e.deferred?e.reason:`Session transcript has legacy branch or provider metadata that can be cleaned up.${t}`,path:e.filePath,fixHint:"Run `openclaw doctor --fix` to repair legacy transcripts during their staged import into SQLite."}}function sessionTranscriptIssueToRepairEffect(e){return{kind:`file`,action:`would-rewrite-session-transcript`,target:e.filePath,dryRunSafe:false}}async function noteSessionTranscriptHealth(e){const t={...e,env:e?.env??process.env,shouldRepair:e?.shouldRepair===true};const{hasRetainedDoctorSessionSources:n,runDoctorSessionSqlite:r}=await import(`./doctor-session-sqlite-DIzSb8mD.mjs`);let i;const recordPostSessionRefusal=e=>{if(!t.postSessionPluginMigration||i)return i;i=createLegacyStateMigrationStepReceipt({...t.postSessionPluginMigration.step,refusal:e},{changes:[],warnings:[e.message]});t.onStepReceipt?.(i);return i};const runSessionSqlite=async e=>{const a=t.shouldRepair?void 0:listExistingAgentDatabaseTargets(t.cfg??{},t.env);if(!t.shouldRepair){const e=await repairLegacySessionEntryStates({apply:false,cfg:t.cfg??{},env:t.env,targets:a});if(e.found>0)return{entryStateReport:e}}const o=await r({allAgents:true,...t.cfg?{cfg:t.cfg}:{},env:t.env,mode:t.shouldRepair?`import`:`dry-run`,integrityCheck:t.integrityCheck},e);const{migrateLegacyMainSessionKeys:s}=await import(`./legacy-main-session-migration-pPgnc_xT.mjs`);const c=await s({cfg:t.cfg??{},env:t.env,mode:t.shouldRepair?`doctor-fix`:`detect`});const l={apply:t.shouldRepair,cfg:t.cfg??{},env:t.env,integrityCheck:t.integrityCheck};const u=await repairCanonicalSessionKeys(l);const d={...l,targets:a??listExistingAgentDatabaseTargets(l.cfg,t.env)};const f=await repairCanonicalSessionResolvedSkills(d);const p=await repairReservedIncognitoSessionKeys(d);const m=await repairCanonicalSessionDeliveryStates(d);await repairLegacySessionExecPolicy(d);await repairLegacyDashboardChatTypes(d);const h={entryStateReport:void 0,report:o,legacyMainSessionResult:c,canonicalKeyReport:u,resolvedSkillsReport:f,reservedKeyReport:p,deliveryReport:m,acpKeyReport:await repairAcpSessionMetaKeysForDoctor({...d,authority:e,integrityCheck:t.integrityCheck}),titleReport:await repairLegacySessionTitles({...d,authority:e}),worktreeWorkspaceReport:await repairLegacySessionWorktreeWorkspaces({...d,apply:t.shouldRepair&&(!c.armed||c.complete)})};if(t.postSessionPluginMigrationPlanBound&&!t.postSessionPluginMigration)return h;if(t.postSessionPluginMigration?.step.requiredness===`not-required`){i=createLegacyStateMigrationStepReceipt(t.postSessionPluginMigration.step,{changes:[],warnings:[]});t.onStepReceipt?.(i);return h}if(!t.shouldRepair&&t.postSessionPluginMigration){recordPostSessionRefusal({code:`repair-not-authorized`,message:`Post-session plugin repair was planned but Doctor repair was not authorized.`});return h}let g;let _=t.postSessionPluginMigration?.step;try{g=await runPostSessionPluginDoctorStateRepairs({config:t.cfg??{},env:t.env,maintenanceAuthority:e,...e&&n(o)?{beforeCompletion:async(t,n)=>{const{settleRetainedDoctorSessionSources:r}=await import(`./doctor-session-sqlite-DIzSb8mD.mjs`);await r(o,t,e,n)}}:{},...t.postSessionPluginMigration?{plannedActions:t.postSessionPluginMigration.plannedActions,inventory:t.postSessionPluginMigration.inventory}:{}})}catch(e){const t=`Plugin session repair failed before the planned step completed: ${String(e)}`;g={changes:[],warnings:[t]};if(_)_={..._,refusal:{code:`step-threw`,message:t}}}if(_){i=createLegacyStateMigrationStepReceipt(_,g);t.onStepReceipt?.(i)}const v=[...g.changes,...g.warnings];if(v.length>0)note(v.join(` `),`Plugin session repair`);return h};let a;try{a=t.shouldRepair?await withDoctorSqliteMaintenanceLock({env:t.env,operation:`session SQLite import`,run:runSessionSqlite}):await runSessionSqlite()}catch(e){if(!(e instanceof DoctorSqliteMaintenanceLockUnavailableError)){recordPostSessionRefusal({code:`blocked-by-session-repair-failure`,message:`Post-session plugin repair was blocked because prerequisite session repair failed: ${String(e)}`});throw e}const n=formatErrorMessage(e);note(`- Skipped: ${n} Then run "${formatCliCommand(`openclaw doctor --fix`,t.env)}" for session-store maintenance.`,`Session SQLite`);recordPostSessionRefusal({code:`sqlite-maintenance-unavailable`,message:n});return i}if(a.entryStateReport){note(`- Found ${a.entryStateReport.found} durable session row(s) with legacy pending-delivery, fallback, or memory-flush state. Run "openclaw doctor --fix" before further session inspection.`,`Session SQLite`);return i}const{report:o,worktreeWorkspaceReport:s,acpKeyReport:c,titleReport:l,reservedKeyReport:u,canonicalKeyReport:d,deliveryReport:f,resolvedSkillsReport:p,legacyMainSessionResult:m}=a;const noteRepair=(e,t,n)=>{if(e>0)note(n(),t)};noteRepair(s.found,`Session worktrees`,()=>t.shouldRepair?`- Repaired saved workspace metadata for ${s.repaired} of ${s.found} managed-worktree session(s). Check project/worktree ownership for any remaining entries.`:`- Found ${s.found} managed-worktree session(s) missing saved workspace metadata. Run "openclaw doctor --fix" to repair them.`);if(c.found>0||c.warnings.length>0){t.onWarnings?.(c.warnings);note([t.shouldRepair?`- Repaired ${c.repaired} of ${c.found} legacy ACP metadata record(s).`:`- Found ${c.found} legacy ACP metadata record(s). Run "openclaw doctor --fix" to repair them.`,...(c.backups??[]).map(e=>`- Saved ACP metadata backup: ${e}`),...c.warnings].join(` `),`ACP session keys`)}if(l.found>0||l.warnings.length>0)note([t.shouldRepair?`- Repaired ${l.repaired} of ${l.found} missing or internal-wake session title(s) without changing activity.`:`- Found ${l.found} missing or internal-wake session title(s). Run "openclaw doctor --fix" to repair them.`,...l.warnings].join(` `),`Session titles`);noteRepair(u.found,`Session SQLite`,()=>t.shouldRepair?`- Renamed ${u.repaired} durable session key(s) that collided with the reserved incognito namespace.`:`- Found ${u.found} durable session key(s) that collide with the reserved incognito namespace. Run "openclaw doctor --fix" to rename them.`);noteRepair(d.foundGroups,`Session SQLite`,()=>t.shouldRepair?`- Canonicalized ${d.repairedGroups} session-key group(s) in ${d.repairBatches} transaction batch(es), removed ${d.removedRows} duplicate or alias row(s), and preserved cross-store history in ${d.archivedTranscriptDirectories.length} archive director${d.archivedTranscriptDirectories.length===1?`y`:`ies`}.`:`- Found ${d.foundGroups} outdated or duplicate session-key group(s). Run "openclaw doctor --fix" to preserve their history and update the rows to use the current keys.`);noteRepair(f.found,`Session SQLite`,()=>t.shouldRepair?`- Canonicalized delivery state for ${f.repaired} durable session row(s).`:`- Found ${f.found} durable session row(s) with legacy delivery fields. Run "openclaw doctor --fix" to canonicalize them.`);noteRepair(p.found,`Session SQLite`,()=>t.shouldRepair?`- Stripped the runtime-only skills catalog from ${p.repaired} durable session row(s). Logical SQLite pages are freed; shrinking the on-disk database requires "openclaw doctor --session-sqlite compact --session-sqlite-all-agents".`:`- Found ${p.found} durable session row(s) carrying a runtime-only skills catalog. Run "openclaw doctor --fix" to strip it.`);if(m.changes.length>0||m.warnings.length>0)note([...m.changes.map(e=>`- ${e}`),...m.warnings.map(e=>`- ${e}`)].join(` `),`Legacy main sessions`);if(o.totals.legacyEntries===0&&o.totals.unreferencedJsonlFiles===0&&o.totals.issues===0)return i;const h=o.targets.filter(isInformationalMissingSessionIndex);const g=o.targets.filter(e=>!isInformationalMissingSessionIndex(e));const _=g.reduce((e,t)=>e+t.issues.filter(e=>!isHistoricalSessionSqliteMigrationIssue(e)).length,0);const v=[`- Legacy entries: ${o.totals.legacyEntries}; SQLite entries: ${o.totals.sqliteEntries}.`,`- Transcript events: imported=${o.totals.importedTranscriptEvents}; validated=${o.totals.validatedTranscriptEvents}.`];for(const e of h)for(const t of e.issues)v.push(`- ${t.message}`);if(o.totals.archivedTranscriptFiles>0)v.push(`- Archived ${o.totals.archivedTranscriptFiles} legacy transcript artifact(s).`);if(o.totals.archivedUnreferencedJsonlFiles>0)v.push(`- Archived ${o.totals.archivedUnreferencedJsonlFiles} unreferenced JSONL artifact(s).`);const y=formatSessionSqliteMigrationWarnings(g,t.env);t.onWarnings?.(y);const b=collectSessionSqliteMigrationFindings(g,t.env);if(t.onFindings)t.onFindings(b);else for(const e of y)v.push(`- ${e}`);if(_>0)v.push(`- Found ${_} session SQLite issue(s). Inspect with "${formatCliCommand(`openclaw doctor --session-sqlite dry-run --session-sqlite-all-agents`,t.env)}".`);if(!t.shouldRepair&&g.some(e=>e.legacyEntries>0))v.push(`- Run "openclaw doctor --fix" to migrate legacy session metadata/transcripts to SQLite.`);if(t.shouldRepair&&o.migrationRun&&o.totals.archivedTranscriptFiles>0)v.push(`- After verifying the upgrade, preview rollback retirement with "${formatCliCommand(`openclaw update cleanup --dry-run`,t.env)}" for state ${resolveStateDir(t.env)}. Keep the same OPENCLAW_STATE_DIR and OPENCLAW_CONFIG_PATH overrides.`);note(v.join(` `),`Session SQLite`);return i}export{detectSessionTranscriptHealthIssues,noteSessionTranscriptHealth,sessionTranscriptIssueToHealthFinding,sessionTranscriptIssueToRepairEffect};