openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
6 lines • 17.3 kB
JavaScript
import{o as getAsyncWorkSignal}from"./async-work-scope-DBcxYU4O.mjs";import{r as resolveStateDir}from"./state-dir-BwIClCab.mjs";import{m as resolveConfigPath}from"./paths-D_FOvGon.mjs";import{t as applyProcessEnvKeys}from"./process-env-BMQKxoSL.mjs";import{u as tryResolveDefaultAgentId}from"./agent-roster-4XrgUgPK.mjs";import{f as resolveAgentWorkspaceDir}from"./agent-scope-config-CG9CFpGX.mjs";import{a as SqliteSnapshotCleanupError}from"./sqlite-lifecycle-errors-DMaudCZS.mjs";import{s as resolveOpenClawStateSqlitePath}from"./openclaw-state-db.paths-CbgXfEg1.mjs";import{f as withDisposableOpenClawStateReads,r as forkActiveOpenClawStateDatabaseReadSnapshot,v as withOpenClawStateDatabaseReadSnapshot}from"./openclaw-state-db-readonly-Cd5_cxBs.mjs";import{a as withArtifactPreservingStateReads,t as artifactPreservingReads}from"./artifact-preserving-state-reads-CWuQPqxe.mjs";import{a as prepareSqliteReadOnlyLocation}from"./sqlite-snapshot-source-DbIgYrJe.mjs";import{_ as withSqliteReadOnlyWorkerScope}from"./sqlite-readonly-worker-C1mJaAX6.mjs";import{a as resolveUpdateRehearsalRoot}from"./update-rehearsal-paths-C4qLj9oD.mjs";import{l as closeOpenClawStateDatabaseByPathAsync}from"./openclaw-state-db-cache-uycu-8uy.mjs";import{a as withPluginInstallRoots,i as resolvePluginInstallRoots}from"./install-root-context-CqAZmMOW.mjs";import{o as withPluginSourceCaptureStorage,t as getPluginSourceCaptureStorage}from"./plugin-source-capture-context-BdWCXhar.mjs";import{d as loadPinnedRuntimeConfigAsync}from"./runtime-snapshot-Bg5K4JNu.mjs";import{l as readDeferredPluginMigrations}from"./deferred-plugin-migrations-D_BIDN9_.mjs";import"./agent-scope-Dw5XRSEh.mjs";import{t as captureRuntimeConfig}from"./runtime-source-projection-DvPkX_nq.mjs";import{i as validateConfigObjectWithPlugins}from"./validation-CGAl0yU4.mjs";import{o as maybeLoadDotEnvForConfig,t as createConfigIO}from"./io.factory-y6nIrp_4.mjs";import{s as readConfigFileSnapshot,u as readConfigFileSnapshotWithPluginMetadata}from"./io.runtime-BvSeVFIY.mjs";import{a as resolveCommandProcessSignal}from"./exec-spawn-DNCbDcyJ.mjs";import"./sqlite-y_WDH-Xr.mjs";import{r as closeAuthProfileReadPool}from"./sqlite-read-pool-YeZ4G2Ax.mjs";import"./config-DkZ8y8Gv.mjs";import{f as isUpdateDoctorLintPass,u as isPostCoreConvergencePass}from"./update-phase-CCaxuca0.mjs";import{t as UPDATE_DOCTOR_DISPOSAL_WARNING_PREFIX}from"./update-doctor-lint-DRIG9Kdy.mjs";import{t as scrubDoctorErrorMessage}from"./doctor-error-message-Crthe8x4.mjs";import{n as configValidationIssuesToHealthFindings}from"./doctor-config-validation-findings-Bi3nFC6v.mjs";import{n as listExtensionHealthChecksForDoctor}from"./health-check-registry-qx2G8L6q.mjs";import{i as parseHealthFindingSeverity,n as healthFindingMeetsSeverity,r as isHealthCheckEnabledByDefault}from"./health-checks-bdwCtNe-.mjs";import{i as stateSchemaHealthCheck,n as runDoctorLintChecks,r as selectUpdateReadinessChecks,t as exitCodeFromFindings}from"./doctor-lint-flow-nrUDzyxR.mjs";import{i as resolveLegacyHeartbeatAgents,l as tryProjectRetiredHeartbeatConfig}from"./doctor-heartbeat-legacy-DItu0_B3.mjs";import{i as detectDoctorLintOutputMode,n as createStateSnapshotFailureExecution,o as writeJsonResult,r as createStateSnapshotFailureFinding,t as createDeferredInspectionExecution}from"./doctor-lint-output-BaL-hIUO.mjs";import{n as resolveDoctorUpdateBudget,t as admitDoctorUpdateInspection}from"./doctor-update-budget-BM5nNTSl.mjs";import{n as formatRecoveryDiskUsage,t as collectRecoveryDiskUsage}from"./recovery-disk-usage-n0MT5avi.mjs";import fs from"node:fs";import path from"node:path";import os from"node:os";import{isDeepStrictEqual}from"node:util";
//!src/commands/doctor-lint-state-snapshot.ts
var DoctorLintStateSnapshotError=class extends Error{constructor(e){super(`Doctor lint could not prepare a private plugin-state snapshot: ${scrubDoctorErrorMessage(e)}`,{cause:e});this.name=`DoctorLintStateSnapshotError`}};async function withReadOnlyPluginStateSnapshot(e,t,n){let r;let i;let a;try{a={ok:true,value:await t(async t=>{i??=await(r??=prepareReadOnlyPluginStateSnapshot(e,n));return i.run(t)})}}catch(e){a={ok:false,error:e}}try{await i?.close()}catch(e){throw new DoctorLintStateSnapshotError(a.ok?e:new AggregateError([a.error,e],`${scrubDoctorErrorMessage(a.error)}; ${scrubDoctorErrorMessage(e)}`))}if(!a.ok)throw a.error;return a.value}async function prepareReadOnlyPluginStateSnapshot(e,t){const n=resolveOpenClawStateSqlitePath(e);const r={stateDir:getPluginSourceCaptureStorage()?.stateDir??resolveStateDir(e),placement:`temporary`};const i=resolvePluginInstallRoots(e);let cleanup;let a;let o;try{if(fs.existsSync(n)){o=await forkActiveOpenClawStateDatabaseReadSnapshot({env:e})??await prepareSqliteReadOnlyLocation(n,{preserveSourceArtifacts:true,shared:false});a=path.dirname(o.location);cleanup=o.cleanupAsync}else{a=fs.mkdtempSync(path.join(os.tmpdir(),`openclaw-doctor-lint-state-`));cleanup=async()=>{try{await fs.promises.rm(a,{force:true,recursive:true});return true}catch{return false}}}}catch(e){throw new DoctorLintStateSnapshotError(e)}const s=path.join(a,`openclaw-state`);const c=artifactPreservingReads.getStore();if(c)c.privateRoots.add(s);const l=resolveOpenClawStateSqlitePath({...e,OPENCLAW_STATE_DIR:s});const u={...e,OPENCLAW_CONFIG_PATH:resolveConfigPath(e,resolveStateDir(e)),OPENCLAW_STATE_DIR:s};const close=()=>withDoctorLintStateEnv(u,async()=>{const e=[];try{closeAuthProfileReadPool({kind:`root`,rootPath:s})}catch(t){e.push(t)}try{await closeOpenClawStateDatabaseByPathAsync(l)}catch(t){e.push(t)}if(e.length>0)throw new AggregateError(e,e.map(e=>scrubDoctorErrorMessage(e)).join(`; `));if(!await cleanup()){const e=`Temporary doctor lint state snapshot cleanup did not complete.`;if(!t)throw new Error(e);recordSnapshotCleanupWarning(t)}});try{fs.mkdirSync(path.dirname(l),{recursive:true,mode:448});if(o)for(const e of[``,`-journal`,`-shm`,`-wal`]){const t=`${o.location}${e}`;if(fs.existsSync(t))fs.renameSync(t,`${l}${e}`)}}catch(e){try{await close()}catch(t){throw new DoctorLintStateSnapshotError(new AggregateError([e,t],`${scrubDoctorErrorMessage(e)}; ${scrubDoctorErrorMessage(t)}`))}throw new DoctorLintStateSnapshotError(e)}return{close,run:e=>withDoctorLintStateEnv(u,()=>withPluginSourceCaptureStorage(r,()=>withDisposableOpenClawStateReads(l,()=>withPluginInstallRoots({...i,stateDir:s},()=>e(u)))))}}function recordSnapshotCleanupWarning(e){e.push({checkId:`core/doctor/lint-state-inspection`,severity:`warning`,requirement:`temporary-snapshot-cleanup`,message:`Temporary doctor lint state snapshot cleanup did not complete.`,fixHint:"Rerun `openclaw doctor --lint` after the update to check snapshot cleanup."})}async function withDoctorLintStateEnv(e,t,n=`resolved`){const r=resolveStateDir(e);const i=n===`captured`?{OPENCLAW_CONFIG_PATH:e.OPENCLAW_CONFIG_PATH,OPENCLAW_STATE_DIR:e.OPENCLAW_STATE_DIR}:{OPENCLAW_CONFIG_PATH:resolveConfigPath(e,r),OPENCLAW_STATE_DIR:r};const a=Object.keys(i);const o=Object.fromEntries(a.map(e=>[e,process.env[e]]));applyProcessEnvKeys(a,i);try{return await t()}finally{applyProcessEnvKeys(a,o)}}
//!src/commands/doctor-lint-runner.ts
const RUNTIME_TOOL_SCHEMA_CHECK_ID=`core/doctor/runtime-tool-schemas`;const PROJECT_CLONE_SHAPE_CHECK_ID=`core/doctor/project-clone-shape`;const SKILLS_READINESS_CHECK_ID=`core/doctor/skills-readiness`;const HEARTBEAT_SOURCE_CHECK_IDS=/* @__PURE__ */ new Set([`core/doctor/heartbeat-cadence-migration`,`core/doctor/heartbeat-scratch-migration`]);const SOURCE_STATE_CHECK_IDS=/* @__PURE__ */ new Set([`core/doctor/auth-profiles`,`core/doctor/device-pairing`,`core/doctor/gateway-health`,...HEARTBEAT_SOURCE_CHECK_IDS]);async function runDoctorLintCliInProcess(e,t,n){let r;const report=e=>{e.writeOutput();r=e};try{const i=resolveCommandProcessSignal(getAsyncWorkSignal());const a=await withSqliteReadOnlyWorkerScope(()=>withArtifactPreservingStateReads(()=>prepareDoctorLintExecution(e,t,n?report:void 0,n?.commandStartedAtMs),{agentDatabases:true}),i?{signal:i,deadlineOwnedByCaller:false}:void 0);if(!r)report(a);else for(const t of a.cleanupWarnings??[])e.error(`${UPDATE_DOCTOR_DISPOSAL_WARNING_PREFIX}: ${t.message}`);return a.exitCode}catch(t){if(!r)throw t;e.error(`${UPDATE_DOCTOR_DISPOSAL_WARNING_PREFIX}: ${scrubDoctorErrorMessage(t)}`);return r.exitCode}}async function collectDoctorFindings(e){const t=resolveCommandProcessSignal(getAsyncWorkSignal());return(await withSqliteReadOnlyWorkerScope(()=>withArtifactPreservingStateReads(()=>prepareDoctorLintExecution(e,{severityMin:`info`}),{agentDatabases:true}),t?{signal:t,deadlineOwnedByCaller:false}:void 0)).findings}async function prepareDoctorLintExecution(e,t,n,r){const i=t.severityMin===void 0?`warning`:parseHealthFindingSeverity(t.severityMin);if(i===null)throw new Error(`Invalid --severity-min value. Expected one of: info, warning, error.`);maybeLoadDotEnvForConfig(process.env);const a={...process.env};if(resolveUpdateRehearsalRoot(a)&&!t.onlyIds?.length){const n=await createConfigIO({env:a,observe:false,pluginValidation:`core-only`}).readConfigFileSnapshot();if(n.valid){const i=await resolveDoctorUpdateBudget({cfg:n.config,env:a,commandStartedAtMs:r});if(i&&!admitDoctorUpdateInspection(i,`agent`,[{id:`core/doctor/lint-inspection`,label:`Doctor lint inspection`}]))return createDeferredInspectionExecution(e,t,[...i.deferred.values()])}}const o=isUpdateDoctorLintPass(a)?[]:void 0;const runStateChecks=async()=>{const r=isPostCoreConvergencePass(a)?`post-plugin`:void 0;const s=r?{...t,updateReadiness:r}:t;const{resolveBundledHealthCheckPluginStateMode:c}=await import(`./bundled-health-checks-BqAz6lgJ.mjs`);const l=c(s);let u;const d=/* @__PURE__ */ new Set;if(resolveUpdateRehearsalRoot(a)&&!r&&!t.onlyIds?.length){const{resolveDoctorContributionHealthChecks:e}=await import(`./doctor-health-contributions-qricxMBI.mjs`);u=await e();for(const e of u)if((e.updateWork?.kind===`inspection`||e.updateWork?.kind===`standalone`)&&(t.includeAllChecks===true||isHealthCheckEnabledByDefault(e))&&!t.skipIds?.includes(e.id))d.add(e.id)}const f=!d.has(RUNTIME_TOOL_SCHEMA_CHECK_ID)&&(l===`isolated`||!s.onlyIds?.length||s.onlyIds.includes(RUNTIME_TOOL_SCHEMA_CHECK_ID));const readConfigSnapshot=async e=>{const t=l===`direct`?{readConfigFileSnapshot,readConfigFileSnapshotWithPluginMetadata}:createConfigIO({env:a,configPath:resolveConfigPath(a,resolveStateDir(a)),observe:false,pluginValidation:l===`deferred`?`core-only`:void 0,deferredPluginMigrations:e});return l===`deferred`||!f?t.readConfigFileSnapshot({observe:false}):(await t.readConfigFileSnapshotWithPluginMetadata({observe:false,prepareValidation:`runtime`})).snapshot};let p=false;let m;try{return await withReadOnlyPluginStateSnapshot(a,async t=>{const r={coreChecks:u,deferredCheckIds:d,cleanupWarnings:o,pluginMetadataEnv:a,sourceEnv:a,readConfigSnapshot,runWithPluginStateSnapshot:t};if(l!==`isolated`&&!n)return m=await executeDoctorLint(e,s,i,r);return await r.runWithPluginStateSnapshot(async t=>{const a=readDeferredPluginMigrations({env:t});const o=[];try{const c=await executeDoctorLint(e,s,i,{...r,pluginMetadataEnv:t,readConfigSnapshot:()=>readConfigSnapshot(a),runWithPluginStateSnapshot:async e=>e(t),deferInspectionDisposal:n?e=>o.push(e):void 0});m=c;n?.(c);p=n!==void 0;return c}finally{for(const t of o)try{await t()}catch(t){e.error(`${UPDATE_DOCTOR_DISPOSAL_WARNING_PREFIX}: ${scrubDoctorErrorMessage(t)}`)}}})},o)}catch(t){if(p||!(t instanceof DoctorLintStateSnapshotError))throw t;return createStateSnapshotFailureExecution(e,s,i,t,m)}};let s;try{return await withOpenClawStateDatabaseReadSnapshot(async()=>s=await runStateChecks(),{env:a,lazy:Boolean(t.onlyIds?.length),preferLiveOwner:true})}catch(e){if(!s||!o||!(e instanceof SqliteSnapshotCleanupError))throw e;recordSnapshotCleanupWarning(o);return s}}async function executeDoctorLint(e,t,n,r){const i=await r.readConfigSnapshot();const a=i.exists&&!i.valid?tryProjectRetiredHeartbeatConfig(i.sourceConfig):void 0;const o=a&&(resolveLegacyHeartbeatAgents(i.sourceConfig).some(e=>e.heartbeat!==void 0)||!isDeepStrictEqual(i.sourceConfig.channels,a.channels))?a:void 0;const s=o?validateConfigObjectWithPlugins(o,{env:r.pluginMetadataEnv,sourceRaw:o}):void 0;if(i.exists&&!i.valid&&!s?.ok){const{collectNodeRuntimeFindings:a}=await import(`./node-runtime-diagnostics-BU175c1b.mjs`);const o=await a(r.sourceEnv);const s=[...configValidationIssuesToHealthFindings(i.issues),...o];const c=s.filter(e=>healthFindingMeetsSeverity(e,n));return{checksRun:1,checksSkipped:0,exitCode:exitCodeFromFindings(s,n),findings:c,cleanupWarnings:r.cleanupWarnings,writeOutput(){if(detectDoctorLintOutputMode(t)===`json`){writeJsonResult({ok:false,checksRun:1,checksSkipped:0,findings:c,warnings:r.cleanupWarnings});return}e.error(`doctor --lint: config file exists but does not parse cleanly.`);for(const t of i.issues){const n=t.path||`<root>`;e.error(`- ${n}: ${t.message}`)}for(const t of o.filter(e=>healthFindingMeetsSeverity(e,n)))e.error(t.fixHint?`${t.message}\n${t.fixHint}`:t.message);for(const t of r.cleanupWarnings??[])e.error(`${UPDATE_DOCTOR_DISPOSAL_WARNING_PREFIX}: ${t.message}`)}}}const c=s?.ok?s.config:i.config;const l=s?.ok?{exists:i.exists,issues:[],warnings:s.warnings}:i;const u=s?.ok?i.sourceConfig:void 0;await loadPinnedRuntimeConfigAsync(async()=>({config:c}));const d=captureRuntimeConfig(c);const f={...r.sourceEnv};const p=tryResolveDefaultAgentId(d);const m={mode:`lint`,runtime:e,cfg:d,cwd:p?resolveAgentWorkspaceDir(d,p):process.cwd(),env:f,allowExecSecretRefs:t.allowExec===true,...i.path!==void 0?{configPath:i.path}:{}};const{registerBundledHealthChecks:h}=await import(`./bundled-health-checks-BqAz6lgJ.mjs`);const g=h({cfg:d,cwd:m.cwd,env:r.pluginMetadataEnv,runWithPluginStateSnapshot:r.runWithPluginStateSnapshot,updateReadiness:t.updateReadiness});const _=listExtensionHealthChecksForDoctor([],g);const v=t.onlyIds!==void 0&&t.onlyIds.length>0&&t.onlyIds.every(e=>_.some(t=>t.id===e));let y=v?[]:r.coreChecks;if(!y){const{resolveDoctorContributionHealthChecks:e}=await import(`./doctor-health-contributions-qricxMBI.mjs`);y=await e()}const b=v?_:listExtensionHealthChecksForDoctor(y,g);const runWithPrivateStateSnapshot=async e=>await r.runWithPluginStateSnapshot(async()=>await e());const runWithSourceState=async e=>t.updateReadiness?e():withDoctorLintStateEnv(f,e,`captured`);const x={...m,env:t.updateReadiness?r.pluginMetadataEnv:f,lintConfigSnapshot:l,deep:t.deep===true,runWithPrivateStateSnapshot,runWithSourceState,deferInspectionDisposal:r.deferInspectionDisposal};const S=[stateSchemaHealthCheck,...y.map(e=>{const t=u&&HEARTBEAT_SOURCE_CHECK_IDS.has(e.id)?{...x,cfg:u}:x;return{...e,detect(n,r){const detect=async()=>[...await e.detect(t,r),...g.filter(t=>t.checkId===e.id)];const inspectPrivate=async e=>{let n;try{return await t.runWithPrivateStateSnapshot(async()=>n=await e())}catch(e){if(!n?.length||!(e instanceof DoctorLintStateSnapshotError))throw e;return[...n,createStateSnapshotFailureFinding(e)]}};if(e.id===SKILLS_READINESS_CHECK_ID)return inspectPrivate(()=>t.runWithSourceState(detect));if(e.id===RUNTIME_TOOL_SCHEMA_CHECK_ID||e.id===PROJECT_CLONE_SHAPE_CHECK_ID)return inspectPrivate(detect);return SOURCE_STATE_CHECK_IDS.has(e.id)?t.runWithSourceState(detect):detect()}}}),...b];const C={checks:t.updateReadiness&&t.includeAllChecks!==true?selectUpdateReadinessChecks(S,t.updateReadiness):S,includeAllChecks:t.updateReadiness!==void 0||t.includeAllChecks===true,skipIds:[...t.skipIds??[],...r.deferredCheckIds??[]],...t.onlyIds&&t.onlyIds.length>0?{onlyIds:t.onlyIds}:{}};const w=await runDoctorLintChecks(m,C);const T=new Set(y.filter(e=>e.updateWork?.kind===`inspection`||e.updateWork?.kind===`standalone`).map(e=>e.id));const E=isUpdateDoctorLintPass(r.sourceEnv)?w.findings.map(e=>e.severity===`error`&&T.has(e.checkId)?{...e,severity:`warning`}:e):w.findings;const D=E.flatMap(e=>e.checkId===`core/doctor/database-engine`&&e.details?[e.details]:[]);const O=E.filter(e=>healthFindingMeetsSeverity(e,n));const k=E.filter(e=>!healthFindingMeetsSeverity(e,n)&&(e.errorCode===`OPENCLAW_STATE_LEASE_ABORTED`||isUpdateDoctorLintPass(r.sourceEnv)&&e.severity===`warning`));const A=exitCodeFromFindings(E,n);const j=await collectRecoveryDiskUsage({cfg:d,env:r.sourceEnv});return{checksRun:w.checksRun,checksSkipped:w.checksSkipped,exitCode:A,findings:O,databaseStores:D,recoveryCopies:j,warnings:k,cleanupWarnings:r.cleanupWarnings,writeOutput(){if(detectDoctorLintOutputMode(t)===`json`){writeJsonResult({ok:A===0,checksRun:w.checksRun,checksSkipped:w.checksSkipped,findings:O,databaseStores:D.length?D:void 0,recoveryCopies:j,warnings:[...k,...r.cleanupWarnings??[]]});return}process.stdout.write(`Recovery copies (read-only): ${formatRecoveryDiskUsage(j)}\n`);const e=[...O,...k,...r.cleanupWarnings??[]];process.stdout.write(`doctor --lint: ran ${w.checksRun} check(s), ${e.length} finding(s)\n`);if(e.length===0){process.stdout.write(` no findings
`);return}for(const t of e){const e=t.path!==void 0?` ${t.path}`:``;const n=t.line!==void 0?`:${t.line}`:``;process.stdout.write(` [${t.severity}] ${t.checkId}${e}${n} - ${t.message}\n`);if(t.fixHint!==void 0)process.stdout.write(` fix: ${t.fixHint}\n`)}}}}export{collectDoctorFindings,runDoctorLintCliInProcess};