UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

25 lines • 65.7 kB
import{n as isTruthyEnvValue}from"./env-fLMEolk5.mjs";import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{o as measureGatewayBootstrapStep}from"./startup-trace-CnJbL2Y9.mjs";import{o as copyConfigResolutionFactsThroughRewrite}from"./resolution-facts-DYKtoyes.mjs";import{o as getAsyncWorkSignal}from"./async-work-scope-DBcxYU4O.mjs";import{a as getOpenClawDatabaseMaintenanceScope}from"./openclaw-state-maintenance-context-D-pYfco8.mjs";import"./openclaw-state-db-async-lifecycle-DlV0ztcV.mjs";import{a as resolveUpdateRehearsalRoot}from"./update-rehearsal-paths-C4qLj9oD.mjs";import{n as openClawIdAccessWarning,r as withOpenClawIdAccessAllowed,t as openClawIdAccessBlockReason}from"./access-plugin-C41HMCfK.mjs";import{a as writeConfigMachineState}from"./config-machine-state-write-y_DUumZ_.mjs";import{t as captureRuntimeConfig}from"./runtime-source-projection-DvPkX_nq.mjs";import{x as recordUpdateDoctorDeferredInspectionChecks}from"./update-doctor-result-B09W3zwf.mjs";import{t as ConfigWritePostCommitError}from"./io.write-errors-CQyW8lY6.mjs";import{a as resolveCommandProcessSignal}from"./exec-spawn-DNCbDcyJ.mjs";import{h as shouldDeferConfiguredPluginInstallRepair,l as isLegacyParentWritableUpdateDoctorPass}from"./update-phase-CCaxuca0.mjs";import{c as throwIfDoctorStateMigrationRefused,t as DoctorStateMigrationRefusalError}from"./state-migrations.messages-BurXA9TV.mjs";import{t as note}from"./note-e4DtVgg2.mjs";import{t as emitDoctorNotes}from"./emit-notes-DCY5wFZF.mjs";import{t as scrubDoctorErrorMessage}from"./doctor-error-message-Crthe8x4.mjs";import{i as resolveDoctorWorkspaceDir,n as noteDoctorRepairResult,o as shouldDeferPostActivationInspections,r as resolveDoctorMode,t as isUpdateDoctorRun}from"./doctor-health-contribution-utils-DsM0Tsf-.mjs";import{a as recordDoctorHealthWarnings,i as legacyOwnedRepair,n as createDoctorHealthContribution,o as renderStructuredHealthFindings,s as reportDoctorHealthFinding}from"./doctor-health-contribution-CiqEIP_B.mjs";import{i as runFinalConfigValidationHealth}from"./doctor-config-validation-findings-Bi3nFC6v.mjs";import{l as shouldManageGatewayService}from"./doctor-service-repair-policy-gYXaFNLg.mjs";import{p as withDoctorProgress}from"./doctor-health-startup-WrxcBhpP.mjs";import{n as inspectGogUpgrade,r as upgradeGog,t as inspectGog}from"./gmail-gog-BIDrAcJ7.mjs";import{t as hasActiveGatewayExecCredential}from"./doctor-gateway-exec-credential-CXt3PJ38.mjs";import{t as resolveDoctorWorkspaceSuggestionScopes}from"./doctor-workspace-suggestion-scopes-D5b1hi0E.mjs";import{t as normalizeHealthCheck}from"./health-check-adapter-CUvJkJ5D.mjs";import{n as resolveDoctorUpdateBudget,t as admitDoctorUpdateInspection}from"./doctor-update-budget-BM5nNTSl.mjs";import{n as noteBackupDoctorHint}from"./backup-health-CQzB3uKg.mjs";import{i as runStructuredHealthRepairs,n as runCoreContributionHealth,r as runCoreHealthFindingNote,t as runBundledHealthFindingNote}from"./doctor-health-contribution-core-Bd4sRzFa.mjs";import{i as runWriteConfigHealth,n as runInitialConfigWriteHealth,t as collectWriteConfigHealthFindings}from"./doctor-health-contribution-runners.config-cp-erA9Q.mjs";import{a as runDevicePairingHealth,c as runGitHubProjectHealth,d as runSecurityHealth,f as runStartupChannelMaintenanceHealth,i as runCommandOwnerHealth,l as runHostDesktopHealth,m as runWhatsappResponsivenessHealth,n as runBundleLspEnvHealth,o as runGatewayDaemonHealth,p as runWebFetchProxyHealth,r as runClaudeCliHealth,s as runGatewayServicesHealth,t as runBrowserHealth,u as runOpenAIOAuthTlsHealth}from"./doctor-health-contribution-runners.gateway-CdziqC7C.mjs";import{randomUUID}from"node:crypto";import{isDeepStrictEqual}from"node:util";
//!src/flows/doctor-auth-health.ts
async function runAuthProfileMigration(e){e.authProfileHealthReady=false;const t=e.configResult.stateMigrationStepReceipts?.find(e=>e.id===`shared-auth-store`);if(t?.outcome===`skipped`&&t.warnings.length>0){e.retirementOnly=false;return}const{repairAuthProfileMigration:n}=await import(`./auth-profile-repair-eRHqES_1.mjs`);const{maybeRepairLegacyOAuthProfileIds:r}=await import(`./doctor-auth-legacy-oauth-CZNAvMwQ.mjs`);const{maybeMigrateLegacyPluginModelCatalogs:i}=await import(`./doctor-plugin-model-catalog-Cvcagl1z.mjs`);const{buildGatewayConnectionDetails:a}=await import(`./call-CggG9h6i.mjs`);const{note:o}=await import(`./terminal-core/note.js`);if(e.configResult.openAICodexAuthProfileIdMap===void 0){const t=await n({cfg:e.cfg,env:e.env,prompter:e.prompter});if(t.config!==e.cfg||t.storeChanges.length>0||t.warnings.length>0||t.findings.length>0)e.retirementOnly=false;emitDoctorNotes({note:o,changeNotes:t.storeChanges,warningNotes:[]});recordDoctorHealthWarnings(e,[],t.warnings);renderStructuredHealthFindings(e,t.findings);e.cfg=t.config;e.configResult.openAICodexAuthProfileIdMap=t.profileIdMap;if(t.changes.length>0)e.configResult.pendingChangePanels=[...e.configResult.pendingChangePanels??[],t.changes.join(`
`)]}const migrationContext=()=>({cfg:e.cfg,...e.env?{env:e.env}:{},prompter:e.prompter,runtime:e.runtime,reportFindings:(t,n)=>{if(t.length>0||n?.length)e.retirementOnly=false;recordDoctorHealthWarnings(e,n?[]:t,n);renderStructuredHealthFindings(e,t)}});if(await i(migrationContext()))e.retirementOnly=false;const s=e.cfg.agents?.defaults?.models;const c=await r(e.cfg,e.prompter);if(c.config!==e.cfg||c.retiredProfileCleanupPlans.length>0||c.findings.length>0)e.retirementOnly=false;recordDoctorHealthWarnings(e,c.findings);renderStructuredHealthFindings(e,c.findings);e.cfg=c.config;if(c.retiredProfileCleanupPlans.length>0)e.configResult.retiredAuthProfileCleanupPlans=[...e.configResult.retiredAuthProfileCleanupPlans??[],...c.retiredProfileCleanupPlans];if(!isDeepStrictEqual(s,e.cfg.agents?.defaults?.models))e.configResult.explicitSetPaths=[...e.configResult.explicitSetPaths??[],[`agents`,`defaults`,`models`]];const{maybeMigrateModelCatalogCredentials:l}=await import(`./doctor-model-catalog-credentials-tepWCN8s.mjs`);const u=await l(migrationContext());if(u.detected>0||u.migrated>0||u.removed>0)e.retirementOnly=false;let d=true;if(e.configResult.retiredAuthProfileCleanupPlans?.length||e.configResult.openAICodexAuthProfileIdMap?.size){e.retirementOnly=false;const{runRetiredAuthProfileCleanup:t,runWriteConfigHealth:n}=await import(`./doctor-health-contribution-runners.config-VTxfc_wO.mjs`);d=await n(e,{runPostWriteRepairs:false})&&!e.configWriteRefusal&&isDeepStrictEqual(e.cfg,e.cfgForPersistence);if(d)await t(e)}e.authProfileHealthReady=d;e.gatewayDetails=a({config:e.cfg});if(e.gatewayDetails.remoteFallbackNote){e.retirementOnly=false;const t=[{checkId:`core/doctor/gateway-remote-config`,severity:`warning`,category:`fix-now`,message:`Gateway remote mode is configured without a remote Gateway URL; Doctor fell back to the local address.`,fixHint:`Set gateway.remote.url to your remote Gateway address, or set gateway.mode=local if this host owns the Gateway. Run openclaw gateway status after correcting the configuration.`,docsUrl:`https://docs.openclaw.ai/gateway/remote`}];recordDoctorHealthWarnings(e,[],[e.gatewayDetails.remoteFallbackNote]);renderStructuredHealthFindings(e,t)}}async function runAuthProfileDiagnostics(e){const{inspectAuthProfileHealth:t,collectCopilotAmbientTokenFindings:n,collectLegacyCodexProviderOverrideFindings:r,collectSharedAuthStoreFindings:i}=await import(`./doctor-auth-YLBK1oG8.mjs`);if(e.authProfileHealthReady!==false)renderStructuredHealthFindings(e,await t({cfg:e.cfg,prompter:e.prompter,allowKeychainPrompt:e.options.nonInteractive!==true&&process.stdin.isTTY}));renderStructuredHealthFindings(e,await r(e.cfg));renderStructuredHealthFindings(e,await i(e.env));renderStructuredHealthFindings(e,await n(e.cfg,e.env))}
//!src/flows/doctor-health-contribution-runners.workspace.ts
async function runMemorySearchHealthContribution(e){const t=captureRuntimeConfig(e.cfg);const{maybeRepairMemoryRecallHealth:n,noteMemoryRecallHealth:r}=await import(`./doctor-memory-recall-CW2-c4dB.mjs`);const{noteMemorySearchHealth:i}=await import(`./doctor-memory-search-CQVRAofO.mjs`);if(e.prompter.shouldRepair)await n({cfg:t,prompter:e.prompter});await i(t,{env:e.env,gatewayMemoryProbe:e.gatewayMemoryProbe??{checked:false,ready:false,skipped:false}});await r(t,e.options.deep===true)}
//!src/flows/doctor-health-contributions-final.ts
async function collectWorkspaceStatusPluginVersionReadiness(e){if(e.cfg.gateway?.mode===`remote`||!await shouldManageGatewayService())return;try{const{gatherDaemonStatus:t}=await import(`./status.gather-yw4ltMY-.mjs`);const n=await t({rpc:{timeout:e.options?.nonInteractive===true?`3000`:`10000`,json:true},probe:true,requireRpc:false,deep:e.options?.deep===true,allowExecSecretRefs:e.options?.allowExec===true,pluginVersionTarget:`restart`});if(n.pluginVersionRestartReadiness?.status===`resolved`){const{resolvePluginVersionDriftTargets:e}=await import(`./plugin-version-drift-DroYtZxn.mjs`);return{...n.pluginVersionRestartReadiness,report:await e(n.pluginVersionRestartReadiness.report)}}return n.pluginVersionRestartReadiness}catch{return}}const CHANNEL_PACKAGE_STATE_CAPABILITIES_CHECK_ID=`core/doctor/channel-package-state-capabilities`;async function runHeartbeatRetirementHealth(e){const{maybeMigrateHeartbeatCadenceToCron:t}=await import(`./doctor-heartbeat-retirement-CSbLpw57.mjs`);await t({cfg:e.configResult.heartbeatMigrationSource??e.cfg,shouldRepair:e.prompter.shouldRepair,env:e.env})}function resolveFinalDoctorHealthContributions(e){return[createDoctorHealthContribution(`doctor:gateway-services`,`Gateway services`,{healthCheckIds:[`core/doctor/gateway-services/extra`,`core/doctor/gateway-services/platform-notes`],run:runGatewayServicesHealth}),createDoctorHealthContribution(`doctor:host-desktop`,`Host desktop`,{healthChecks:{description:`Gateway-host desktop enablement, reachability, and RFB security state.`,defaultEnabled:false,async detect(e){const{collectHostDesktopHealthFindings:t}=await import(`./doctor-host-desktop-C5Xoqo9a.mjs`);return t(e.cfg)}},run:runHostDesktopHealth}),createDoctorHealthContribution(`doctor:default-account-routing`,`Default account routing`,{updateWork:{kind:`inspection`,scope:`run`},healthChecks:{description:`Multi-account channels have explicit default routing or complete bindings.`,defaultEnabled:false,async detect(e){const{collectMissingDefaultAccountBindingWarnings:t,collectMissingExplicitDefaultAccountWarnings:n}=await import(`./default-account-warnings-BiR2n0DZ.mjs`);return[...t(e.cfg),...n(e.cfg)].map(e=>({checkId:`core/doctor/default-account-routing`,severity:`warning`,message:e.replace(/^- /,``).trim()}))}}}),createDoctorHealthContribution(`doctor:channel-package-state-capabilities`,`Channel package-state capabilities`,{healthChecks:{id:CHANNEL_PACKAGE_STATE_CAPABILITIES_CHECK_ID,description:`Declared channel package-state checker modules must load.`,defaultEnabled:true,async detect(e){if(shouldDeferConfiguredPluginInstallRepair(e.env??process.env))return[];const{collectBundledChannelPackageStateLoadFailures:t}=await import(`./package-state-probes-Dio6odFC.mjs`);return t().map(e=>({checkId:CHANNEL_PACKAGE_STATE_CAPABILITIES_CHECK_ID,severity:`warning`,message:`Plugin ${e.pluginId} declared ${e.metadataKey}, but its checker failed to load: ${e.detail}`,target:e.pluginId,requirement:`declared-channel-package-state-capability-loadable`,fixHint:`Rebuild or reinstall plugin ${e.pluginId}, then rerun \`openclaw doctor\`.`}))}}}),createDoctorHealthContribution(`doctor:startup-channel-maintenance`,`Startup channel maintenance`,{healthChecks:[{id:`core/doctor/channel-plugin-blockers`,description:`Configured channels must have loadable backing channel plugins.`,defaultEnabled:false,async detect(e){const{channelPluginBlockerHitToHealthFinding:t,scanConfiguredChannelPluginBlockers:n}=await import(`./channel-plugin-blockers-Byrj-Kyb.mjs`);return n(e.cfg,process.env).map(t)}},{id:`core/doctor/channel-preview-warnings`,description:`Channel doctor preview warnings are captured as structured findings.`,defaultEnabled:false,async detect(e){const{collectChannelPreviewWarningHealthFindings:t}=await import(`./doctor-startup-channel-maintenance-CQxcCfKP.mjs`);return t({cfg:e.cfg,allowExec:e.allowExecSecretRefs===true})}}],run:runStartupChannelMaintenanceHealth}),createDoctorHealthContribution(`doctor:security`,`Security`,{updateWork:{kind:`inspection`,scope:`agent`},healthCheckIds:[`core/doctor/security`],run:runSecurityHealth}),createDoctorHealthContribution(`doctor:web-fetch-proxy`,`Web fetch proxy`,{updateWork:{kind:`inspection`,scope:`run`},run:runWebFetchProxyHealth}),createDoctorHealthContribution(`doctor:bundle-lsp-env`,`Bundle LSP environment`,{updateWork:{kind:`inspection`,scope:`agent`},run:runBundleLspEnvHealth}),createDoctorHealthContribution(`doctor:github-projects`,`GitHub projects`,{updateWork:{kind:`standalone`},run:runGitHubProjectHealth}),createDoctorHealthContribution(`doctor:browser`,`Browser`,{healthCheckIds:[`core/doctor/browser`],run:runBrowserHealth}),createDoctorHealthContribution(`doctor:oauth-tls`,`OAuth TLS`,{updateWork:{kind:`inspection`,scope:`run`},healthCheckIds:[`core/doctor/oauth-tls`],run:runOpenAIOAuthTlsHealth}),createDoctorHealthContribution(`doctor:hooks-model`,`Hooks model`,{updateWork:{kind:`inspection`,scope:`run`},healthCheckIds:[`core/doctor/hooks-model`],async run(e){const{collectHooksModelIssues:t}=await import(`./doctor-hooks-model-DvtwoJwI.mjs`);const n=await t(e.cfg);if(n.length===0)return;const{note:r}=await import(`./terminal-core/note.js`);r(n.map(({kind:e,model:t})=>e===`unresolved`?`- hooks.gmail.model "${t}" could not be resolved`:e===`not-allowed`?`- hooks.gmail.model "${t}" not allowed by agents.defaults.modelPolicy.allow (will use primary instead)`:`- hooks.gmail.model "${t}" not in the model catalog (may fail at runtime)`).join(`
`),`Hooks`)}}),createDoctorHealthContribution(`doctor:legacy-output-cap`,`Saved model output caps`,{updateWork:{kind:`inspection`,scope:`run`},healthCheckIds:[`core/doctor/legacy-output-cap`],run:e=>runCoreHealthFindingNote(e,`core/doctor/legacy-output-cap`,{infoNoteTitle:`Model output caps`})}),...[[`model-references`,`Model references`,`agent`],[`acp-agent-model`,`ACP agent model`,`agent`],[`provider-catalog-projection`,`Provider catalog projection`,`run`],[`local-audio-acceleration`,`Local audio acceleration`,`run`],[`runtime-tool-schemas`,`Runtime tool schemas`,`agent`]].map(([e,t,n])=>createDoctorHealthContribution(`doctor:${e}`,t,{updateWork:{kind:`inspection`,scope:n},healthCheckIds:[`core/doctor/${e}`],run:t=>runCoreHealthFindingNote(t,`core/doctor/${e}`)})),createDoctorHealthContribution(`doctor:skill-workshop-tool-policy`,`Skill Workshop tool policy`,{updateWork:{kind:`inspection`,scope:`agent`},run:e=>runBundledHealthFindingNote(e,`skill-workshop/tool-policy`)}),createDoctorHealthContribution(`doctor:systemd-linger`,`systemd linger`,{healthChecks:{description:`Disabled systemd user lingering is reported as a finding.`,defaultEnabled:false,detect:e.detectSystemdLingerFindings},run:e.runSystemdLingerHealth}),createDoctorHealthContribution(`doctor:workspace-status`,`Workspace status`,{updateWork:{kind:`inspection`,scope:`agent`},healthChecks:{description:`Workspace plugin/status diagnostics are exposed as findings.`,defaultEnabled:false,async detect(e){const{collectWorkspaceStatusHealthFindings:t}=await import(`./doctor-workspace-status-DmtMPFBV.mjs`);const n=await collectWorkspaceStatusPluginVersionReadiness({cfg:e.cfg,options:{nonInteractive:true,allowExec:e.allowExecSecretRefs===true}});const r=e.runWithPluginMetadataSnapshot;return t(e.cfg,{pluginVersionReadiness:n,...r?{runWithPluginMetadataSnapshot:r}:{}})}},async run(e){const t=await collectWorkspaceStatusPluginVersionReadiness({cfg:e.cfg,options:e.options});const{collectWorkspaceStatusHealthFindings:n}=await import(`./doctor-workspace-status-DmtMPFBV.mjs`);const r=n(e.cfg,{pluginVersionReadiness:t,...e.runWithPluginMetadataSnapshot?{runWithPluginMetadataSnapshot:e.runWithPluginMetadataSnapshot}:{}});recordDoctorHealthWarnings(e,r);renderStructuredHealthFindings(e,r)}}),createDoctorHealthContribution(`doctor:workspace-alias`,`Workspace alias`,{healthChecks:{description:`Persisted workspace aliases must resolve to the resolved target that owns their stored state.`,defaultEnabled:true,async detect(e){const{collectRepointedWorkspaceAliasFindings:t}=await import(`./doctor-workspace-alias-Bxfq3faH.mjs`);return t(e.cfg)}},async run(e){const{collectRepointedWorkspaceAliasFindings:t}=await import(`./doctor-workspace-alias-Bxfq3faH.mjs`);const n=await t(e.cfg);renderStructuredHealthFindings(e,n)}}),createDoctorHealthContribution(`doctor:skills`,`Skills`,{updateWork:{kind:`inspection`,scope:`agent`,repairs:true},healthCheckIds:[`core/doctor/skills-readiness`],async run(e){const{maybeRepairSkillReadiness:t}=await import(`./doctor-skills-DiEYRzy8.mjs`);e.cfg=await t({cfg:e.cfg,prompter:e.prompter,...e.runWithPluginMetadataSnapshot?{runWithPluginMetadataSnapshot:e.runWithPluginMetadataSnapshot}:{}})}}),createDoctorHealthContribution(`doctor:model-allowlist-wildcards`,`Model allowlist`,{updateWork:{kind:`standalone`},async run(e){const{maybeOfferModelAllowlistWildcards:t}=await import(`./legacy-runtime-model-policy-Cip9e-Xi.mjs`);const{config:n,changes:r}=await t({cfg:e.cfg,prompter:e.prompter});e.cfg=n;if(r.length>0)e.configResult.pendingChangePanels=[...e.configResult.pendingChangePanels??[],r.join(`
`)]}}),createDoctorHealthContribution(`doctor:bootstrap-size`,`Bootstrap size`,{updateWork:{kind:`standalone`},healthCheckIds:[`core/doctor/bootstrap-size`],async run(e){const{noteBootstrapFileSize:t}=await import(`./doctor-bootstrap-size-DHCkT0hs.mjs`);await t(e.cfg)}}),createDoctorHealthContribution(`doctor:memory-provenance`,`Memory provenance`,{healthChecks:{description:`Root MEMORY.md and USER.md with untrusted provenance are excluded from automatic context.`,defaultEnabled:true,async detect(e){const{collectMemoryProvenanceExclusionFindings:t}=await import(`./doctor-memory-provenance-BatXP0GP.mjs`);return t(e.cfg)}},async run(e){const{collectMemoryProvenanceExclusionFindings:t}=await import(`./doctor-memory-provenance-BatXP0GP.mjs`);renderStructuredHealthFindings(e,await t(e.cfg))}}),createDoctorHealthContribution(`doctor:heartbeat-cadence-migration`,`Heartbeat cadence migration`,{healthChecks:{description:`Heartbeat cadence config must be materialized in cron monitor rows.`,defaultEnabled:true,async detect(e){const{collectHeartbeatCadenceMigrationFindings:t}=await import(`./doctor-heartbeat-cadence-migration-DEFBF9rp.mjs`);return t(e.cfg,e.env)}},run:runHeartbeatRetirementHealth}),createDoctorHealthContribution(`doctor:heartbeat-scratch-migration`,`Heartbeat scratch migration`,{healthChecks:{description:`Workspace HEARTBEAT.md files must migrate into cron-owned scratch.`,defaultEnabled:true,async detect(e){const{collectHeartbeatScratchMigrationFindings:t}=await import(`./doctor-heartbeat-scratch-migration-CHCpkNtW.mjs`);return t(e.cfg,e.env)}},run:runHeartbeatRetirementHealth}),createDoctorHealthContribution(`doctor:tools-md-migration`,`TOOLS.md migration`,{healthChecks:{description:`Workspace TOOLS.md notes must migrate into the AGENTS.md Tools section.`,defaultEnabled:true,async detect(e){const{collectToolsMdMigrationFindings:t}=await import(`./doctor-tools-md-migration-D9ONWxhx.mjs`);return t(e.cfg)}},async run(e){const{maybeMigrateToolsMd:t}=await import(`./doctor-tools-md-migration-D9ONWxhx.mjs`);await t({cfg:e.cfg,shouldRepair:e.prompter.shouldRepair,env:e.env})}}),createDoctorHealthContribution(`doctor:heartbeat-task-cron-migration`,`Heartbeat task cron migration`,{healthChecks:{description:`Heartbeat scratch task blocks must migrate into automations.`,defaultEnabled:true,async detect(e){const{collectHeartbeatTaskMigrationFindings:t}=await import(`./doctor-heartbeat-task-migration-G-2RIm3r.mjs`);return t(e.cfg,e.env)}},async run(e){const{maybeMigrateHeartbeatTasksToCron:t}=await import(`./doctor-heartbeat-task-migration-G-2RIm3r.mjs`);await t({cfg:e.cfg,shouldRepair:e.prompter.shouldRepair,env:e.env})}}),createDoctorHealthContribution(`doctor:shell-completion`,`Shell completion`,{healthCheckIds:[`core/doctor/shell-completion`],run:e.runShellCompletionHealth}),createDoctorHealthContribution(`doctor:gateway-health`,`Gateway health`,{healthCheckIds:[`core/doctor/gateway-health`],run:e.runGatewayHealthChecks}),createDoctorHealthContribution(`doctor:whatsapp-responsiveness`,`WhatsApp responsiveness`,{updateWork:{kind:`inspection`,scope:`run`},healthChecks:{description:`Gateway pressure and local TUI observations when WhatsApp is enabled.`,defaultEnabled:false,async detect(e){const{collectWhatsappResponsivenessHealthFindings:t}=await import(`./doctor-whatsapp-responsiveness-Bd-Tm8ZZ.mjs`);const{bindAgentToolGatewayRequest:n}=await import(`./in-process-gateway-DxSLSn2a.mjs`);const r=n({hostedOnly:true});let i;if(!(await hasActiveGatewayExecCredential({cfg:e.cfg})&&e.allowExecSecretRefs!==true))i=await r({method:`status`,params:{includeChannelSummary:false},timeoutMs:3e3,config:e.cfg,deviceIdentity:null}).catch(()=>void 0);return t({cfg:e.cfg,status:i})}},run:runWhatsappResponsivenessHealth}),createDoctorHealthContribution(`doctor:memory-search`,`Memory search`,{updateWork:{kind:`inspection`,scope:`agent`,repairs:true},healthChecks:{description:`Memory search provider and backend readiness are captured as findings.`,defaultEnabled:false,async detect(e){const{collectMemorySearchHealthFindings:t}=await import(`./doctor-memory-search-CQVRAofO.mjs`);return t(e)}},run:runMemorySearchHealthContribution}),createDoctorHealthContribution(`doctor:device-pairing`,`Device pairing`,{healthChecks:{description:`Device pairing requests and stale device-auth records are findings.`,defaultEnabled:false,async detect(e){const{collectDevicePairingHealthFindings:t}=await import(`./doctor-device-pairing-Bix-yic_.mjs`);return t({cfg:e.cfg,healthOk:false,env:e.env})}},run:runDevicePairingHealth}),createDoctorHealthContribution(`doctor:gateway-daemon`,`Gateway daemon`,{healthCheckIds:[`core/doctor/gateway-daemon`],run:runGatewayDaemonHealth}),createDoctorHealthContribution(`doctor:write-config`,`Write config`,{updateWork:{kind:`finalize`},healthChecks:{description:`Config write blockers are findings before doctor repair writes.`,defaultEnabled:false,detect:collectWriteConfigHealthFindings},async run(e){await runWriteConfigHealth(e)}}),createDoctorHealthContribution(`doctor:workspace-suggestions`,`Workspace suggestions`,{updateWork:{kind:`standalone`},healthCheckIds:[`core/doctor/workspace-suggestions`],async run(e){if(e.options.workspaceSuggestions===false)return;const{collectWorkspaceSuggestionNotes:t}=await import(`./doctor-workspace-suggestions-DKPetcV6.mjs`);const{note:n}=await import(`./terminal-core/note.js`);for(const{agentId:r,workspaceDir:i,labelAgent:a}of resolveDoctorWorkspaceSuggestionScopes(e.cfg)){const e=a?`Agent "${r}": `:``;for await(const r of t(i))n(`${e}${r}`,`Workspace`)}}}),createDoctorHealthContribution(`doctor:final-config-validation`,`Final config validation`,{updateWork:{kind:`finalize`},healthCheckIds:[`core/doctor/final-config-validation`],run:runFinalConfigValidationHealth})]}
//!src/flows/doctor-gmail-gog-check.ts
const CHECK_ID$1=`core/doctor/gmail-gog`;const FIX_HINT="Upgrade Gog to v0.48.0 or newer using its installation owner, then restart the Gmail watcher or Gateway. Run `openclaw doctor --repair` to upgrade an eligible, unpinned Homebrew installation.";const gmailGogCheck={id:CHECK_ID$1,kind:`core`,source:`doctor`,description:`Configured Gmail watchers use Gog with child-only token environment sources.`,async detect(e){if(!e.cfg.hooks?.enabled||!e.cfg.hooks.gmail?.account)return[];const t=resolveCommandProcessSignal(getAsyncWorkSignal());const n=await inspectGog({env:e.env,signal:t});if(n.support===`supported`)return[];return[{checkId:CHECK_ID$1,severity:`warning`,category:`fix-now`,path:`hooks.gmail`,docsUrl:`https://docs.openclaw.ai/automation/cron-jobs/gmail`,message:!n.executable?`Gmail is configured, but gog could not be found on PATH.`:n.support===`unsupported`?`Selected Gog lacks child-only token environment sources. Gmail watcher tokens remain exposed in process arguments to other local users until Gog is upgraded.`:`Could not verify Gog support for child-only token environment sources. Gmail may use legacy token arguments, which expose watcher tokens to other local users.`,fixHint:n.executable?FIX_HINT:`Install Gog, then rerun Gmail setup or restart the Gateway. Gog v0.48.0 or newer supports child-only token environment sources.`,details:{executable:n.executable,support:n.support}}]},async repair(e){if(e.dryRun)return{changes:[]};if(isTruthyEnvValue(e.env?.OPENCLAW_UPDATE_IN_PROGRESS)||isTruthyEnvValue(process.env.OPENCLAW_UPDATE_IN_PROGRESS))return{status:`skipped`,reason:"Run `openclaw doctor --repair` separately to review the Gog upgrade.",changes:[]};const t=resolveCommandProcessSignal(getAsyncWorkSignal());t?.throwIfAborted();const n=await inspectGog({env:e.env,signal:t});if(n.support===`supported`)return{changes:[]};if(!n.executable)return{status:`skipped`,reason:`Install Gog using Gmail setup first.`,changes:[]};const r=await inspectGogUpgrade(n,{env:e.env,signal:t});if(!r.eligible)return{status:`skipped`,reason:r.reason,changes:[]};t?.throwIfAborted();const i=await upgradeGog(r,{env:e.env,signal:t});if(i.inspection.support!==`supported`)return{status:`failed`,reason:i.message,changes:[]};return{changes:[`Gog supports child-only token environment sources. Restart the Gmail watcher or Gateway to use them.`],effects:[{kind:`package`,action:`upgrade`,target:r.formula}]}}};
//!src/flows/doctor-health-contribution-runners.state.ts
async function runLegacyPluginManifestHealth(e){const{maybeRepairLegacyPluginManifestContracts:t}=await import(`./doctor-plugin-manifests--jwxda5D.mjs`);if(await t({config:e.cfg,env:process.env,runtime:e.runtime,prompter:e.prompter}))e.invalidatePluginMetadataSnapshot?.()}async function runAgentMemorySchemaHealth(e){const{noteDoctorAgentMemorySchemaHealth:t}=await import(`./doctor-agent-memory-schema-U7u0XOnf.mjs`);await t({env:e.env??process.env,shouldRepair:e.prompter.shouldRepair})}async function runCodexSessionRouteHealth(e){const{maybeRepairCodexSessionRoutes:t}=await import(`./codex-route-warnings-LxtRdH30.mjs`);const n=await t({cfg:e.cfg,modelReplacements:e.options.modelReplacements,...e.configResult.retiredModelRefConfig?{retiredModelRefConfig:e.configResult.retiredModelRefConfig}:{},env:e.env??process.env,...!e.prompter.shouldRepair&&e.configResult.providerRenames?.length?{providerRenames:e.configResult.providerRenames}:{},shouldRepair:e.prompter.shouldRepair,...e.configResult.blockedCodexModelIdentities?.length?{blockedModelIdentities:new Set(e.configResult.blockedCodexModelIdentities)}:{},...e.configResult.openAICodexAuthProfileIdMap?.size?{authProfileIdMap:e.configResult.openAICodexAuthProfileIdMap,...!e.prompter.shouldRepair?{authProfileOnly:true}:{}}:{}});if(n.requiresFullDoctor||n.warnings.length>0)e.retirementOnly=false;noteDoctorRepairResult(n)}async function runSessionTranscriptsHealth(e){const{noteSessionTranscriptHealth:t}=await import(`./doctor-session-transcripts-CblJ6RGu.mjs`);await t({cfg:e.cfg,env:e.env??process.env,shouldRepair:e.prompter.shouldRepair,integrityCheck:e.options.fullIntegrityCheck?`full`:`quick`,onWarnings:t=>recordDoctorHealthWarnings(e,[],t),onFindings:t=>renderStructuredHealthFindings(e,t),...e.configResult.postSessionPluginMigration?{postSessionPluginMigration:e.configResult.postSessionPluginMigration}:{},...e.configResult.postSessionPluginMigrationPlanBound?{postSessionPluginMigrationPlanBound:true}:{},onStepReceipt:t=>{e.configResult.stateMigrationStepReceipts??=[];e.configResult.stateMigrationStepReceipts.push(t);if(t.outcome===`deferred`||t.warnings.length>0)e.retirementOnly=false}})}async function runLegacyCronHealth(e){const{maybeRepairLegacyCronStore:t,noteLegacyWhatsAppCrontabHealthCheck:n}=await import(`./cron-CB4pgKfz.mjs`);await measureGatewayBootstrapStep(`doctor.legacy-cron.crontab`,()=>n());await measureGatewayBootstrapStep(`doctor.legacy-cron.store`,()=>t({cfg:e.cfg,options:e.options,prompter:e.prompter}));const{maybeRepairCronInferenceBindings:r}=await import(`./inference-binding-migration-DXzuqkKH.mjs`);const i=await measureGatewayBootstrapStep(`doctor.legacy-cron.inference`,()=>r({cfg:e.cfg,env:e.env,shouldRepair:e.prompter.shouldRepair,publishedStateDir:e.options.stateUpgradeLiveStateDir}));noteDoctorRepairResult(i);recordDoctorHealthWarnings(e,[],i.warnings);const{noteScheduledContextReport:a}=await import(`./execution-context-check-BuwTjneT.mjs`);await measureGatewayBootstrapStep(`doctor.legacy-cron.execution-context`,()=>a({cfg:e.cfg,env:e.env}))}
//!src/flows/doctor-native-status-check.ts
const CHECK_ID=`core/doctor/native-status`;const nativeStatusCheck={id:CHECK_ID,kind:`core`,source:`doctor`,description:`Native filesystem and process helpers are available for this runtime.`,async detect(){const[{getFsSafeNativeStatus:e},{getProcSafeNativeStatus:t},{isSupported:n}]=await Promise.all([import(`@openclaw/fs-safe`),import(`@openclaw/proc-safe`),import(`@openclaw/proc-safe/reaper`)]);const r=await Promise.all([e({probe:true}),t({probe:true})]);const i=process.platform!==`linux`||n();return r.map((e,t)=>{const n=t===0?`fs-safe`:`proc-safe`;const r=n===`proc-safe`&&process.platform===`linux`&&e.reason===`load-failed`;const a=n===`proc-safe`&&process.platform===`linux`&&!i;let o=``;if(r)try{const e=process.report.getReport();const t=isRecord(e)?e.header:void 0;if(isRecord(t)&&typeof t.glibcVersionRuntime===`string`)o=` (glibc ${t.glibcVersionRuntime})`}catch{}const s=`${n}: ${e.reason}${o}`;const c=r?`${e.guidance?`${e.guidance} `:``}Linux update ancestry can use /proc/<pid>/stat without the native helper. If ancestry remains unavailable, restore readable /proc or install a compatible process helper; after the recorded update driver exits, run \`openclaw update repair\`.`:e.guidance;return{checkId:CHECK_ID,severity:e.loaded||e.mode===`off`?`info`:`warning`,message:a?`${s}; native child reaping is unavailable; supervised service-child commands may fail before launch`:s,fixHint:a?`${c??``}${c?` `:``}Restore a compatible native process helper and rerun \`openclaw doctor\` before retrying service-child commands.`:c}})}};const appContainerSpawnCheck={id:`core/doctor/appcontainer-spawn`,kind:`core`,source:`doctor`,description:`The Windows runtime can create child pipes inside an AppContainer.`,async detect(){const{assertAppContainerSpawnSupported:e,AppContainerSpawnUnsupportedError:t}=await import(`./windows-appcontainer-spawn-F-mrNlro.mjs`);try{e();return[]}catch(e){if(!(e instanceof t))throw e;return[{checkId:`core/doctor/appcontainer-spawn`,severity:`error`,errorCode:e.code,message:e.message}]}}};
//!src/flows/doctor-openclaw-id-access.ts
const openClawIdAccessCheck={id:`core/doctor/openclaw-id-access`,kind:`core`,source:`doctor`,description:`OpenClaw ID Access page plugin policy.`,async detect({cfg:e}){const t=openClawIdAccessWarning(e);return t?[{checkId:`core/doctor/openclaw-id-access`,severity:`warning`,requirement:openClawIdAccessBlockReason(e)===`not in allowlist`?`allowlist`:`explicit-policy`,message:t,fixHint:`Doctor can add only openclaw-id-access to plugins.allow with consent; explicit disables and deny entries are never changed.`}]:[]}};async function runOpenClawIdAccessHealth(e){let t=await openClawIdAccessCheck.detect({mode:`doctor`,cfg:e.cfg,runtime:e.runtime});if(t.some(({requirement:e})=>e===`allowlist`)&&e.sourceConfigValid&&await e.prompter.confirmAutoFix({message:`Add openclaw-id-access to plugins.allow so the OpenClaw ID Access page can load? The config file is rewritten as JSON and comments are removed. All other plugin policy is preserved.`,initialValue:false})){const n=withOpenClawIdAccessAllowed(e.cfg);copyConfigResolutionFactsThroughRewrite(e.cfg,n);e.cfg=n;e.configResult.pendingChangePanels=[...e.configResult.pendingChangePanels??[],`Added openclaw-id-access to plugins.allow.`];t=[]}renderStructuredHealthFindings(e,t);recordDoctorHealthWarnings(e,t)}
//!src/flows/doctor-health-contributions-initial.ts
function coreHealthRunner(e){return async t=>{const{runCoreContributionHealth:n}=await import(`./doctor-health-contribution-core-DU9Ibu7i.mjs`);await n(t,[e])}}const runStaleRuntimeBuildHealth=coreHealthRunner(`core/doctor/stale-runtime-build`);const runTelegramGeneralTopicConversationHealth=coreHealthRunner(`core/doctor/telegram-general-topic-conversations`);function resolveInitialDoctorHealthContributions(e){return[createDoctorHealthContribution(`doctor:write-config-migrations`,`Write config migrations`,{required:true,run:runInitialConfigWriteHealth}),createDoctorHealthContribution(`doctor:agent-database-admission`,`Agent database admission`,{healthChecks:{description:`Agent databases with mismatched ownership are isolated until repaired.`,async detect(e){const{evaluateAgentDatabaseAdmissions:t}=await import(`./agent-database-admission-S1h6e7go.mjs`);return(e.agentDatabaseRefusals??await t(e.cfg,{env:e.env})).map(e=>({checkId:`core/doctor/agent-database-admission`,severity:`warning`,target:e.agentId,requirement:e.code,message:`Agent ${e.agentId} is degraded. ${e.reason}`,fixHint:e.repairHint}))}}}),createDoctorHealthContribution(`doctor:native-status`,`Native helpers and child pipes`,{healthChecks:[appContainerSpawnCheck,nativeStatusCheck]}),createDoctorHealthContribution(`doctor:node-runtime`,`Node runtime`,{healthCheckIds:[`core/doctor/node-runtime`],async run(e){const{runCoreHealthFindingNote:t}=await import(`./doctor-health-contribution-core-DU9Ibu7i.mjs`);await t(e,`core/doctor/node-runtime`)}}),createDoctorHealthContribution(`doctor:runtime-capabilities`,`Runtime capabilities`,{healthCheckIds:[`core/doctor/runtime-capabilities`],async run(){const{collectRuntimeCapabilities:e,formatRuntimeCapabilities:t}=await import(`./runtime-capabilities-SQFt5ZF4.mjs`);note(t(e()),`Runtime capabilities (Doctor process)`)}}),createDoctorHealthContribution(`doctor:gateway-config`,`Gateway config`,{healthCheckIds:[`core/doctor/gateway-config`],run:e.runGatewayConfigHealth}),createDoctorHealthContribution(`doctor:database-engine`,`Database engines`,{updateWork:{kind:`inspection`,scope:`agent`},healthChecks:{description:`Selected database engines, physical store health, and recovery guidance.`,async detect(e){const{collectDoctorDatabaseEngineHealthFindings:t}=await import(`./doctor-database-engine-qoWVOTE-.mjs`);return t(e.cfg,{env:e.env})}},async run(e){const{noteDatabaseEngines:t}=await import(`./doctor-database-engine-qoWVOTE-.mjs`);recordDoctorHealthWarnings(e,await t(e.cfg,{env:e.env}))}}),createDoctorHealthContribution(`doctor:auth-profile-migration`,`Auth profile migration`,{updateWork:{kind:`startup`},run:e.runAuthProfileMigration}),createDoctorHealthContribution(`doctor:auth-profiles`,`Auth profiles`,{updateWork:{kind:`inspection`,scope:`agent`,repairs:true},healthChecks:{description:`Auth profile cooldown, expiry, missing credential, and legacy override state`,defaultEnabled:false,async detect(e){const{collectAuthProfileHealthFindings:t}=await import(`./doctor-auth-YLBK1oG8.mjs`);return t({cfg:e.cfg,allowKeychainPrompt:false})}},run:e.runAuthProfileHealth}),createDoctorHealthContribution(`doctor:claude-cli`,`Claude CLI`,{updateWork:{kind:`inspection`,scope:`agent`},healthCheckIds:[`core/doctor/claude-cli`],run:runClaudeCliHealth}),createDoctorHealthContribution(`doctor:gmail-gog`,`Gmail Gog`,{updateWork:{kind:`inspection`,scope:`run`},healthChecks:gmailGogCheck}),createDoctorHealthContribution(`doctor:gateway-auth`,`Gateway auth`,{healthCheckIds:[`core/doctor/gateway-auth`],run:e.runGatewayAuthHealth}),createDoctorHealthContribution(`doctor:node-hosting-preconditions`,`Node hosting preconditions`,{healthChecks:{description:`Gateway config can authenticate and onboard node and worker hosts.`,async detect(e){const{collectNodeHostingPreconditionFindings:t}=await import(`./doctor-node-hosting-preconditions-AUt8V7mo.mjs`);const n=await t(e.cfg);return resolveUpdateRehearsalRoot(e.env??process.env)?n.filter(e=>e.requirement!==`node-onboarding-url`):n}}}),createDoctorHealthContribution(`doctor:command-owner`,`Command owner`,{updateWork:{kind:`inspection`,scope:`run`},healthCheckIds:[`core/doctor/command-owner`],run:runCommandOwnerHealth}),createDoctorHealthContribution(`doctor:structured-health-repairs`,`Plugin health inspection and repair`,{updateWork:{kind:`inspection`,scope:`agent`,repairs:true},run:e.runStructuredHealthRepairs}),createDoctorHealthContribution(`doctor:legacy-state`,`Legacy state`,{healthCheckIds:[`core/doctor/legacy-state`,`core/doctor/removed-workspaces-state`,`core/doctor/session-archive-read-cache`],run:e.runLegacyStateHealth}),createDoctorHealthContribution(`doctor:session-transcripts`,`Chat history`,{healthChecks:{description:`Legacy or branched chat history files are represented as findings.`,defaultEnabled:false,async detect(){const{detectSessionTranscriptHealthIssues:e,sessionTranscriptIssueToHealthFinding:t}=await import(`./doctor-session-transcripts-CblJ6RGu.mjs`);return(await e()).map(t)},repair:legacyOwnedRepair(async()=>{const{detectSessionTranscriptHealthIssues:e,sessionTranscriptIssueToRepairEffect:t}=await import(`./doctor-session-transcripts-CblJ6RGu.mjs`);return(await e()).map(t)},`legacy doctor session transcript contribution owns transcript rewrites`)},run:runSessionTranscriptsHealth}),createDoctorHealthContribution(`doctor:agent-memory-schema`,`Agent memory schema`,runAgentMemorySchemaHealth),createDoctorHealthContribution(`doctor:legacy-plugin-manifests`,`Legacy plugin manifests`,{healthChecks:{description:`Legacy plugin manifest capability keys are reported as findings.`,defaultEnabled:false,async detect(e){const{collectLegacyPluginManifestContractMigrations:t,legacyPluginManifestContractMigrationToHealthFinding:n}=await import(`./doctor-plugin-manifests--jwxda5D.mjs`);return t({config:e.cfg,env:process.env}).map(n)}},run:runLegacyPluginManifestHealth}),createDoctorHealthContribution(`doctor:legacy-plugin-dependencies`,`Legacy plugin dependencies`,{healthChecks:{description:`Deprecated shared plugin dependency cleanup check.`,defaultEnabled:false,async detect(){return[{checkId:`core/doctor/legacy-plugin-dependencies`,severity:`info`,message:`Deprecated check: Doctor preserves shared plugin runtime caches and no longer scans them for removal.`}]}},run:async()=>{}}),createDoctorHealthContribution(`doctor:stale-plugin-runtime-symlinks`,`Stale plugin runtime symlinks`,{healthChecks:{description:`Stale plugin-runtime symlinks are represented as findings.`,defaultEnabled:false,async detect(){const{collectStalePluginRuntimeSymlinkHealthFindings:e}=await import(`./plugin-runtime-symlinks-CIHUhM-R.mjs`);return e()}},run:async()=>{}}),createDoctorHealthContribution(`doctor:release-configured-plugin-installs`,`Configured plugin repair`,{healthChecks:{id:`core/doctor/configured-plugin-installs`,description:`Configured plugin install records and package payloads are repairable.`,defaultEnabled:false,async detect(e){const{detectConfiguredPluginInstallHealthIssues:t,configuredPluginInstallIssueToHealthFinding:n}=await import(`./missing-configured-plugin-install-X2BqeheS.mjs`);return(await t({cfg:e.cfg,env:process.env})).map(n)},repair:legacyOwnedRepair(async e=>{const{detectConfiguredPluginInstallHealthIssues:t,configuredPluginInstallIssueToRepairEffect:n}=await import(`./missing-configured-plugin-install-X2BqeheS.mjs`);return(await t({cfg:e.cfg,env:process.env})).map(n)},`legacy doctor configured plugin install repair owns package mutation`)},async run(e){if(!e.sourceConfigValid||!e.prompter.shouldRepair)return;const{maybeRunConfiguredPluginInstallReleaseStep:t}=await import(`./release-configured-plugin-installs-DgGEdjwr.mjs`);const{VERSION:n}=await import(`./version-Durg_CtO.mjs`);const r=await t({cfg:e.cfg,env:e.env??process.env,touchedVersion:e.configResult.sourceLastTouchedVersion??e.cfg.meta?.lastTouchedVersion});if(r.pluginInventoryChanged)e.invalidatePluginMetadataSnapshot?.();if(r.postInstallDoctorResult)e.postInstallDoctorResult=r.postInstallDoctorResult;noteDoctorRepairResult(r);if(!r.touchedConfig)return;const i=isLegacyParentWritableUpdateDoctorPass(e.env??process.env)?e.configResult.sourceLastTouchedVersion?.trim()||e.cfg.meta?.lastTouchedVersion||n:n;const a={...e.cfg,meta:{...e.cfg.meta,lastTouchedVersion:i}};copyConfigResolutionFactsThroughRewrite(e.cfg,a);e.cfg=a;writeConfigMachineState(`config.lastTouchedAt`,(/* @__PURE__ */ new Date()).toISOString())}}),createDoctorHealthContribution(`doctor:plugin-registry`,`Plugin registry`,{healthChecks:{description:`Plugin registry migration, stale shadow, and peer-link issues are findings.`,defaultEnabled:false,async detect(e){const{detectPluginRegistryHealthIssues:t,pluginRegistryIssueToHealthFinding:n}=await import(`./doctor-plugin-registry-CbS3r9UH.mjs`);return(await t({config:e.cfg,env:process.env,prompter:{shouldRepair:false}})).map(n)},repair:legacyOwnedRepair(async e=>{const{detectPluginRegistryHealthIssues:t,pluginRegistryIssueToRepairEffect:n}=await import(`./doctor-plugin-registry-CbS3r9UH.mjs`);return(await t({config:e.cfg,env:process.env,prompter:{shouldRepair:false}})).map(n)},`legacy doctor plugin registry contribution owns registry repairs`)},async run(e){const{maybeRepairPluginRegistryState:t}=await import(`./doctor-plugin-registry-CbS3r9UH.mjs`);const n=await t({config:e.cfg,env:process.env,prompter:e.prompter});e.cfg=n.config;if(n.pluginInventoryChanged)e.invalidatePluginMetadataSnapshot?.()}}),createDoctorHealthContribution(`doctor:legacy-plugin-source-captures`,`Legacy plugin captures`,{updateWork:{kind:`startup`},async run(e){const{noteLegacyPluginSourceCaptures:t}=await import(`./doctor-plugin-source-captures-DknLVqET.mjs`);await t(e.env??process.env,e.prompter.shouldRepair)}}),createDoctorHealthContribution(`doctor:retained-update-runtimes`,`Updater runtimes`,{updateWork:{kind:`startup`},async run(e){if(e.gatewayMaintenanceActive&&e.prompter.shouldRepair)return;const{prepareRetainedUpdateRuntimeCleanup:t}=await import(`./doctor-retained-runtime-BncOjlbh.mjs`);await(await t(e.env??process.env))(e.prompter.shouldRepair)}}),createDoctorHealthContribution(`doctor:update-snapshots`,`Retained update database snapshots`,{updateWork:{kind:`standalone`},healthChecks:{description:`Retained npm update database snapshots need operator review before removal.`,defaultEnabled:true,async detect(e){const{collectUpdateSnapshotHealthFindings:t}=await import(`./doctor-update-snapshots-DD_zxCve.mjs`);return t(e.env)}}}),createDoctorHealthContribution(`doctor:ui-protocol-freshness`,`UI protocol freshness`,{healthCheckIds:[`core/doctor/ui-protocol-freshness`],run:async()=>{}}),createDoctorHealthContribution(`doctor:stale-runtime-build`,`Stale runtime build`,{healthCheckIds:[`core/doctor/stale-runtime-build`],run:runStaleRuntimeBuildHealth}),createDoctorHealthContribution(`doctor:disk-space`,`Disk space`,{healthChecks:{description:`Low disk space around the OpenClaw state directory is a finding.`,defaultEnabled:false,async detect(e){const{collectDiskSpaceHealthFindings:t}=await import(`./doctor-disk-space-J8nSA3oC.mjs`);return t(e.env)}},async run(){const{noteDiskSpace:e}=await import(`./doctor-disk-space-J8nSA3oC.mjs`);e()}}),createDoctorHealthContribution(`doctor:project-clone-shape`,`Project clones`,{updateWork:{kind:`standalone`},healthChecks:{description:`Shallow registry-owned project clones need full history.`,defaultEnabled:false,async detect(e){const{collectProjectCloneShapeHealthFindings:t}=await import(`./doctor-project-clone-shape-CelY94S8.mjs`);return await t(e.cfg,{env:e.env})}},async run(e){const{noteProjectCloneShape:t}=await import(`./doctor-project-clone-shape-CelY94S8.mjs`);await t(e.cfg,{repair:e.options.repair,env:e.env})}}),createDoctorHealthContribution(`doctor:db-bloat`,`SQLite database size`,{updateWork:{kind:`standalone`},async run(){const{noteSqliteDatabaseBloat:e}=await import(`./doctor-db-bloat-ByufkzwR.mjs`);await e()}}),createDoctorHealthContribution(`doctor:channel-ingress-dead-letters`,`Channel ingress dead letters`,{updateWork:{kind:`inspection`,scope:`run`},async run(){const{noteChannelIngressDeadLetters:e}=await import(`./doctor-channel-ingress-QVUt6vH6.mjs`);await e()}}),createDoctorHealthContribution(`doctor:state-integrity`,`State integrity`,{healthChecks:{description:`State directory, config permission, and runtime state issues are findings.`,defaultEnabled:false,async detect(e){const{detectStateIntegrityHealthIssues:t,stateIntegrityIssueToHealthFinding:n}=await import(`./doctor-state-integrity-DU0RYl4D.mjs`);return t(e.cfg,{configPath:e.configPath,env:e.env??process.env}).map(n)},repair:legacyOwnedRepair(async e=>{const{detectStateIntegrityHealthIssues:t,stateIntegrityIssueToRepairEffect:n}=await import(`./doctor-state-integrity-DU0RYl4D.mjs`);return t(e.cfg,{configPath:e.configPath,env:e.env??process.env}).map(n)},`legacy doctor state integrity contribution owns state repairs`)},async run(e){const{noteDoctorAgentDatabasePathHealth:t}=await import(`./doctor-agent-database-paths-DIKw1_Tq.mjs`);const n=t({env:e.env??process.env,shouldRepair:e.prompter.shouldRepair});if(n.length>0){e.updateWarnings??=[];e.updateWarnings.push(...n)}const{noteStateIntegrity:r}=await import(`./doctor-state-integrity-DU0RYl4D.mjs`);await r(e.cfg,e.prompter,e.configPath,{stateDirExistedAtStart:e.stateDirExistedAtStart});await noteBackupDoctorHint(e.env??process.env,e.cfg);const{noteBackupScratchHealth:i}=await import(`./doctor-backup-scratch-B_tnBqTF.mjs`);await i(e.env??process.env,e.prompter.shouldRepair)}}),createDoctorHealthContribution(`doctor:codex-session-routes`,`Codex session routes`,{healthCheckIds:[`core/doctor/codex-session-routes`],run:runCodexSessionRouteHealth}),createDoctorHealthContribution(`doctor:telegram-general-topic-conversations`,`Telegram General-topic conversations`,{healthCheckIds:[`core/doctor/telegram-general-topic-conversations`],run:runTelegramGeneralTopicConversationHealth}),createDoctorHealthContribution(`doctor:session-transcript-headers`,`Chat history headers`,async e=>{const{noteSessionTranscriptHeaderHealth:t}=await import(`./doctor-session-transcript-headers-DtL9mfvc.mjs`);await t({cfg:e.cfg,env:e.env??process.env,shouldRepair:e.prompter.shouldRepair,integrityCheck:e.options.fullIntegrityCheck?`full`:`quick`})}),createDoctorHealthContribution(`doctor:session-transcript-labels`,`Chat history labels`,async e=>{const{noteSessionTranscriptLabelHealth:t}=await import(`./doctor-session-transcript-labels-z4YMFtyE.mjs`);await t({cfg:e.cfg,env:e.env??process.env,shouldRepair:e.prompter.shouldRepair,integrityCheck:e.options.fullIntegrityCheck?`full`:`quick`})}),createDoctorHealthContribution(`doctor:session-snapshots`,`Session snapshots`,{updateWork:{kind:`inspection`,scope:`agent`},healthChecks:{description:`Historical session snapshot paths are advisory findings; originals are preserved.`,defaultEnabled:false,async detect(e){const{detectSessionSnapshotHealthIssues:t,sessionSnapshotIssueToHealthFinding:n}=await import(`./doctor-session-snapshots-BFtpVqfo.mjs`);return(await t({cfg:e.cfg,env:process.env})).map(n)}},async run(e){const{noteSessionSnapshotHealth:t}=await import(`./doctor-session-snapshots-BFtpVqfo.mjs`);await t({cfg:e.cfg,env:e.env??process.env})}}),createDoctorHealthContribution(`doctor:config-audit-scrub`,`Config audit`,{healthChecks:{description:`Historical config-audit argv redaction gaps are represented as structured findings.`,defaultEnabled:false,async detect(){const{configAuditScrubToHealthFinding:e,detectConfigAuditScrubIssue:t}=await import(`./doctor-config-audit-scrub-DYYGUjEL.mjs`);const n=await t();return n.rewritten>0?[e(n)]:[]},repair:legacyOwnedRepair(async()=>{const{configAuditScrubToRepairEffect:e,detectConfigAuditScrubIssue:t}=await import(`./doctor-config-audit-scrub-DYYGUjEL.mjs`);const n=await t();return n.rewritten>0?[e(n)]:[]},`legacy doctor config audit contribution owns cleanup`)},async run(e){const{maybeRepairLegacyRuntimeFiles:t}=await import(`./doctor-usage-cost-cache-AroKw5Ok.mjs`);const n=await t(e.prompter.shouldRepair,e.env);recordDoctorHealthWarnings(e,[],n)}}),createDoctorHealthContribution(`doctor:legacy-cron`,`Legacy cron`,{healthCheckIds:[`core/doctor/legacy-whatsapp-crontab`,`core/doctor/legacy-cron-store`,`core/doctor/cron-inference-accounts`],run:runLegacyCronHealth}),createDoctorHealthContribution(`doctor:openclaw-id-access`,`OpenClaw ID Access`,{healthChecks:openClawIdAccessCheck,run:runOpenClawIdAccessHealth}),createDoctorHealthContribution(`doctor:sandbox`,`Sandbox`,{healthChecks:{id:`core/doctor/sandbox/registry-files`,description:`Legacy sandbox registry files are represented in SQLite registry storage.`,async detect(){const{detectLegacySandboxRegistryFileIssues:e,legacySandboxRegistryInspectionToHealthFinding:t}=await import(`./doctor-sandbox-CFvzTJbL.mjs`);return(await e()).map(t)},repair:legacyOwnedRepair(async()=>{const{detectLegacySandboxRegistryFileIssues:e,legacySandboxRegistryInspectionToRepairEffect:t}=await import(`./doctor-sandbox-CFvzTJbL.mjs`);return(await e()).map(t)},`legacy doctor sandbox contribution owns registry migration`)},async run(e){const{maybeRepairSandboxImages:t,maybeRepairSandboxRegistryFiles:n,noteSandboxScopeWarnings:r}=await import(`./doctor-sandbox-CFvzTJbL.mjs`);const i=getOpenClawDatabaseMaintenanceScope();await n(e.prompter,()=>{if(!i)throw new Error(`Retired sandbox registry repair requires exclusive maintenance ownership`);i.assertOwnerCurrent()});const a=await t(e.cfg,e.runtime,e.prompter);recordDoctorHealthWarnings(e,[],a);r(e.cfg)}}),createDoctorHealthContribution(`doctor:codex-bwrap`,`Codex bwrap sandbox`,{updateWork:{kind:`standalone`},async run(e){const{noteCodexBwrapNamespaceWarnings:t}=await import(`./doctor-sandbox-CFvzTJbL.mjs`);await t(e.cfg,{env:e.env,cwd:resolveDoctorWorkspaceDir(e.cfg,e.env)})}})]}
//!src/flows/doctor-health-contributions.ts
const MAX_DEFERRED_LEGACY_STATE_DETAILS=20;async function reportDeferredLegacyState(e){if(e.options.repair!==true&&e.options.yes!==true)return;const[{detectLegacyStateMigrations:t},{prepareLegacySessionSurfaces:n}]=await Promise.all([import(`./state-migrations.doctor-DVSvDgfM.mjs`),import(`./legacy-session-surfaces-BRnoZsX6.mjs`)]);const r=await t({cfg:e.cfg,doctorOnlyStateMigrations:true,...e.env?{env:e.env}:{},legacySessionSurfaces:await n({config:e.cfg})});const i=[...r.warnings.map(e=>e.startsWith(`- `)?e:`- ${e}`),...r.preview];if(i.length===0)return;const a=i.slice(0,MAX_DEFERRED_LEGACY_STATE_DETAILS);const o=i.length-a.length;const s=e.configWriteRefusal===`validation`?`Fix the config errors above.`:e.configWriteRefusal===`include-ownership`?`Repair the include boundary named above by hand.`:`Resolve the Gateway or cron-store condition above.`;note([`Pending owners and blockers:`,...a,...o>0?[`${o} additional pending entries were omitted from this report.`]:[],`No listed legacy source was removed.`,s].join(`
`),`Legacy state deferred`)}async function runGatewayConfigHealth(e){await runCoreHealthFindingNote(e,`core/doctor/gateway-config`)}async function runGatewayAuthHealth(e){if(!e.sourceConfigValid)return;const{detectGatewayAuthHealth:t}=await import(`./doctor-gateway-auth-CaKQfAYb.mjs`);const[n]=await t({cfg:e.cfg,env:e.env,allowExecSecretRefs:e.options.allowExec});const{resolveSecretInputRef:r}=await import(`./types.secrets-CngPo7DG.mjs`);const i=r({value:e.cfg.gateway?.auth?.token,defaults:e.cfg.secrets?.defaults}).ref;if(!n){if(i&&e.options.generateGatewayToken===true)note(`Gateway token generation skipped because gateway.auth.token is managed by SecretRef ${i.source}:${i.provider}:${i.id}. The referenced credential was left unchanged.`,`Gateway auth`);return}note([n.message,n.fixHint].filter(Boolean).join(`
`),`Gateway auth`);if(n.path!==`gateway.auth.token`){recordDoctorHealthWarnings(e,[n]);return}if(i){if(i.source===`store`&&n.requirement===`SECRET_REF_REDACTED_VALUE`&&(e.options.generateGatewayToken===true||e.options.repair===true||e.options.yes===true)){const{isRedactedSecretValue:t}=await import(`./redact-sentinel-Ajm_ef1u.mjs`);const{readSecretStoreValue:n,writeSecretStoreEntry:r}=await import(`./secret-store-BW6BT_kd.mjs`);const{createVerifiedSqliteSnapshot:a}=await import(`./sqlite-snapshot-C6LLrZkv.mjs`);const{resolveOpenClawStateSqlitePath:o}=await import(`./openclaw-state-db.paths-3UU_PbvT.mjs`);const{randomToken:s}=await import(`./onboard-helpers-Dx2uoGe6.mjs`);const c={env:e.env??process.env};const l={scope:{kind:`team`},name:i.id,database:c};try{const e=await n(l);if(!e.ok||!t(e.value)){note(`Secret store entry "${l.name}" changed; rerun Doctor to inspect it.`,`Gateway auth`);return}const i=o(c.env);const u=await a({sourcePath:i,targetPath:`${i}.doctor-gateway-token.${randomUUID()}.bak`,preserveRowIds:true});const d=s();await r({...l,value:d,expectedValue:e.value,kind:`secret`,updatedBy:`doctor`});note(`Regenerated Gateway token in secret store entry "${l.name}"; gateway.auth.token remains a SecretRef. Backup: ${u.path}\nRestart the Gateway, then reconnect or re-pair devices with the new token.`,`Gateway auth`)}catch(t){const n=`Could not repair Gateway token in secret store entry "${l.name}": ${scrubDoctorErrorMessage(t)}. Rerun \`openclaw doctor --fix\` after resolving the reported problem.`;note(n,`Gateway auth`);recordDoctorHealthWarnings(e,[],[n])}return}note(`${e.options.generateGatewayToken===true?`Gateway token generation skipped because a SecretRef is configured. `:``}Doctor will not overwrite gateway.auth.token with a plaintext value.`,`Gateway auth`);return}if(!(e.options.generateGatewayToken===true?true:e.options.nonInteractive===true?false:await e.prompter.confirmAutoFix({message:`Generate and configure a gateway token now?`,initialValue:true})))return;const{randomToken:a}=await import(`./onboard-helpers-Dx2uoGe6.mjs`);const o=a();const s={...e.cfg,gateway:{...e.cfg.gateway,auth:{...e.cfg.gateway?.auth,mode:`token`,token:o}}};copyConfigResolutionFactsThroughRewrite(e.cfg,s);e.cfg=s;note(`Gateway token configured.`,`Gateway auth`)}async function runLegacyStateHealth(e){await runCoreContributionHealth(e,[`core/doctor/removed-workspaces-state`,`core/doctor/session-archive-read-cache`]);const t=e.options.repair===true||e.options.yes===true;if(!t||!isDeepStrictEqual(e.configResult.preflightLegacyStateConfig,e.cfg)){const{detectLegacyStateMigrations:n,runLegacyStateMigrations:r}=await import(`./state-migrations.doctor-DVSvDgfM.mjs`);const{prepareLegacySessionSurfaces:i}=await import(`./legacy-session-surfaces-BRnoZsX6.mjs`);const a=await i({config:e.cfg});const o=await n({cfg:e.cfg,...t?{doctorOnlyStateMigrations:true}:{},legacySessionSurfaces:a});const s=e.configResult.stateMigrationStepReceipts?.find(e=>e.id===`migration-detection`);noteDoctorRepairResult({changes:[],warnings:o.warnings.filter(e=>!s?.warnings.includes(e)),notices:o.notices.filter(e=>!s?.notices?.includes(e))});if(o.preview.length>0){note(o.preview.join(`
`),`Legacy state detected`);if(e.options.nonInteractive===true||await e.prompter.confirm({message:`Migrate detected legacy state now?`,initialValue:true})){const t=await r({detected:o,integrityCheck:e.options.fullIntegrityCheck?`full`:`quick`,config:e.cfg,legacySessionSurfaces:a});recordDoctorHealthWarnings(e,[],t.stepReceipts.flatMap(e=>e.outcome===`warning`||e.outcome===`deferred`?e.warnings:[]));noteDoctorRepairResult(t)}}}if(!t)return;const{repairObsoleteGeneratedExecApprovals:n}=await import(`./exec-approvals-generated-migration-CRtxqSrH.mjs`);const{ExecApprovalsMigrationRequiredError:r}=await import(`./exec-approvals-migration-gate-CHZWOW1Z.mjs`);let i;try{i=n()}catch(e){if(e instanceof r)return;throw e}if(i>0)note(`Exec approvals updated: removed ${i} older generated ${i===1?`approval`:`approvals`} that were not tied to a working directory. Manual allowlist rules were not changed. Rerun affected workflows and choose "Always allow here" when prompted.`,`Doctor changes`)}async function shouldInspectSystemdLinger(e){if(process.platform!==`linux`||resolveDoctorMode(e.cfg)!==`local`||!await shouldManageGatewayService(e.env??process.env))return false;const t=e.env??process.env;const{findInstalledSystemdGatewayScope:n}=await import(`./systemd-99DISckf.mjs`);return(await n(t))?.scope===`user`}async function runSystemdLingerHealth(e){if(e.options.nonInteractive===true||!await shouldInspectSystemdLinger(e))return;const{readGatewayServiceState:t,resolveGatewayService:n}=await import(`./service-flxrucEo.mjs`);const{ensureSystemdUserLingerInteractive:r}=await import(`./systemd-linger-gtvLLLCV.mjs`);if((await t(n(),{env:process.env})).loadState.status!==`loaded`)return;await r({runtime:e.runtime,prompter:{confirm:async t=>e.prompter.confirm(t),note},reason:`Gateway runs as a systemd user service. Without lingering, systemd stops the user session on logout/idle and kills the Gateway.`,requireConfirm:true})}async function detectSystemdLingerFindings(e){if(!await shouldInspectSystemdLinger(e))return[];const{readGatewayServiceState:t,resolveGatewayService:n}=await import(`./service-flxrucEo.mjs`);if((await t(n(),{env:process.env})).loadState.status!==`loaded`)return[];const{isSystemdUserServiceAvailable:r,readSystemdUserLingerStatus:i,resolveSystemdUserServiceAccount:a}=await import(`./systemd-99DISckf.mjs`);if(!await r(process.env))return[];const o=a(process.env);if(!o)return[];const s=await i({env:process.env,user:o});if(!s||s.linger===`yes`)return[];return[{checkId:`core/doctor/systemd-linger`,severity:`warning`,source:`doctor`,message:`Systemd lingering is disabled for ${s.user}.`,target:`systemd.user.${s.user}`,requirement:`systemd user lingering enabled`,fixHint:`Run: sudo loginctl enable-linger ${s.user}`}]}async function runShellCompletionHealth(e){const{doctorShellCompletion:t}=await import(`./doctor-completion-B-jP6zjk.mjs`);await t(e.prompter,{nonInteractive:e.options.nonInteractive})}async function runGatewayHealthChecks(e){const t=e.gatewayMaintenanceActive?`Gateway health will be checked after Doctor repair.`:await hasActiveGatewayExecCredential(e)&&e.options.allowExec!==true?"Gateway health checks skipped because gateway credentials use an exec SecretRef. Run `openclaw doctor --allow-exec` to verify Gateway health with exec SecretRefs.":void 0;if(t){note(t,`Gateway`);e.gatewayHealthSkipped=true;e.gatewayMemoryProbe={checked:false,ready:false,skipped:true};return}const{checkGatewayHealth:n,probeGatewayMemoryStatus:r}=await import(`./doctor-gateway-health-mW87T3lC.mjs`);const{healthOk:i,authenticated:a,status:o}=await n({runtime:e.runtime,cfg:e.cfg,onFinding:t=>reportDoctorHealthFinding(e,t)});e.gatewayHealthSkipped=false;e.healthOk=i;e.gatewayStatus=o;e.gatewayMemoryProbe=a?await r({cfg:e.cfg}):{checked:false,ready:false,skipped:i}}function resolveDoctorHealthContributions(){return[...resolveInitialDoctorHealthContributions({runStructuredHealthRepairs:e=>runStructuredHealthRepairs(e,resolveDoctorContributionHealthChecks),runGatewayConfigHealth,runAuthProfileMigration,runAuthProfileHealth:runAuthProfileDiagnostics,runGatewayAuthHealth,runLegacyStateHealth}),...resolveFinalDoctorHealthContributions({runSystemdLingerHealth,detectSystemdLingerFindings,runShellCompletionHealth,runGatewayHealthChecks})]}async function loadCoreHealthChecksById(){const{createCoreHealthChecks:e}=await import(`./doctor-core-checks-C1FYawyt.mjs`);return new Map(e().map(e=>[e.id,e]))}function resolveContributionHealthChecks(e,t){if(e.healthChecks.length>0)return e.healthChecks.map(t=>({...normalizeHealthCheck(t),updateWork:e.updateWork}));return e.healthCheckIds.map(n=>{const r=t.get(n);if(r===void 0)throw new Error(`doctor contribution ${e.id} references unknown core health check ${n}`);return{...r,updateWork:e.updateWork}})}async function resolveDoctorContributionHealthChecks(){const e=await loadCoreHealthChecksById();return resolveDoctorHealthContributions().flatMap(t=>resolveContributionHealthChecks(t,e))}async function selectPostActivationInspections(e){const t=await loadCoreHealthChecksById();return e.flatMap(e=>{if(e.required||e.updateWork?.kind!==`inspection`||e.updateWork.repairs)return[];if(e.id===`doctor:session-snapshots`||e.id===`doctor:workspace-status`)return[];const n=resolveContributionHealthChecks(e,t);return n.length>0&&n.every(e=>e.updateReadiness===void 0&&e.repair===void 0)?[{contribution:e,checks:n}]:[]})}async function runDoctorHealthContributionList(e,t){const n=resolveCommandProcessSignal(getAsyncWorkSignal());const r=e.retirementOnly===true;n?.throwIfAborted();const i=e.runWithPluginMetadataSnapshot;throwIfDoctorStateMigrationRefused(e.configResult.stateMigrationStepReceipts);const a=e.env??process.env;e.updateBudget??=await resolveDoctorUpdateBudget({cfg:e.cfg,env:a,preparedAgentCount:e.preparedAgentCount});const o=isUpdateDoctorRun(a);const s=resolveUpdateRehearsalRoot(a);const c=new Set(s?t.filter(e=>!e.required&&e.updateWork?.kind===`inspection`&&!e.updateWork.repairs):[]);let l=shouldDeferPostActivationInspections(a)?recordUpdateDoctorDeferredInspectionChecks([]):void 0;const u=new Map(l?(await selectPostActivationInspections(t)).map(({contribution:e,checks:t})=>[e,t.map(e=>e.id)]):[]);const d=o?t.filter(e=>e.updateWork?.kind===`standalone`):[];if(d.length>0)note(`Omitted during update: ${d.map(e=>e.label).join(`, `)}.\nRun \`openclaw doctor\` after the update to inspect these diagnostics.`,`Update Doctor scope`);const f=e.updateBudget?[...t.filter(e=>e.updateWork===void 0||e.updateWork.kind===`startup`||e.updateWork.kind===`standalone`),...t.filter(e=>e.updateWork?.kind===`inspection`),...t.filter(e=>e.updateWork?.kind===`finalize`)]:t;try{for(const t of f){n?.throwIfAborted();const a=u.get(t);if(a){l=recordUpdateDoctorDeferredInspectionChecks(a);continue}if(c.has(t)||o&&t.updateWork?.kind===`standalone`)continue;if(t.updateWork?.kind===`inspection`&&!admitDoctorUpdateInspection(e.updateBudget,t.updateWork.scope,(t.healthCheckIds.length?t.healthCheckIds:[`core/doctor/${t.id.replace(/^doctor:/,``)}`]).map(e=>({id:e,label:t.label}))))continue;try{const run=async()=>{n?.throwIfAborted();try{await t.run(e)}finally{throwIfDoctorStateMigrationRefused(e.configResult.stateMigrationStepReceipts)}if(e.configWriteRefusal)await reportDeferredLegacyState(e)};await withDoctorProgress(t.label,()=>measureGatewayBootstrapStep(`doctor.contribution.${t.id}`,async()=>{if(!i)await run();else{const t=resolveDoctorWorkspaceDir(e.cfg,e.env);await i({config:e.cfg,workspaceDir:t},run)}}),e.options.json!==true);n?.throwIfAborted();if(r&&(e.healthFindings?.length||e.updateWarnings?.length))e.retirementOnly=false;if(e.configWriteRefusal)return;if(r&&!e.retirementOnly){e.runtime.error(`Retirement-only Doctor widened: ${t.id}`);return}}catch(i){n?.throwIfAborted();if(t.required||i instanceof DoctorStateMigrationRefusalError||i instanceof ConfigWritePostCommitError)throw i;const a=`${t.id} run failed: ${scrubDoctorErrorMessage(i)}`;renderStructuredHealthFindings(e,[{checkId:t.id,severity:`warning`,category:`fix-now`,message:`Doctor could not complete ${t.label}: ${scrubDoctorErrorMessage(i)}`,fixHint:`Resolve the reported inspection failure, then rerun openclaw doctor. This check could not establish its health.`}]);recordDoctorHealthWarnings(e,[],[a]);if(r){e.retirementOnly=false;e.runtime.error(`Retirement-only Doctor widened: ${t.id}.failed`);return}}}}finally{if(c.size>0)e.runtime.log(`Deferred advisory inspections during copied-state rehearsal: ${[...c].map(e=>e.id).join(`, `)}. The live post-swap Doctor retains these checks.`);if(l?.length)e.runtime.log(`Deferred advisory inspections until the restarted Gateway is ready: ${l.join(`, `)}. The updater runs their \`openclaw doctor --lint\` checks after restart.`);const t=[...e.updateBudget?.deferred.values()??[]];recordDoctorHealthWarnings(e,t,[],{prepend:true});for(const n of t)e.runtime.log(`[warning] ${n.checkId} [${n.errorCode}]: ${n.message}`);if(t.length>0)e.runtime.log("Run `openclaw doctor --fix` after activation to complete deferred checks and repairs.")}}async function runDoctorHealthContributions(e){const t=resolveDoctorHealthContributions();if(e.retirementOnly){const t=[...e.configResult.retirementOnly!==true?(e.configResult.retirementOnlyBlockers??[`preparation`]).map(e=>`config.${e}`):[],Boolean(e.agentDatabaseRefusals?.length)&&`agent-admission`,Boolean(e.healthFindings?.length)&&`startup-findings`,Boolean(e.updateWarnings?.length)&&`startup-warnings`].filter(e=>Boolean(e));if(t.length>0){e.retirementOnly=false;for(const n of t)e.runtime.error(`Retirement-only Doctor widened: ${n}`)}}if(e.retirementOnly){const n=/* @__PURE__ */ new Set([`doctor:write-config-migrations`,`doctor:auth-profile-migration`,`doctor:session-transcripts`,`doctor:codex-session-routes`,`doctor:write-config`,`doctor:final-config-validation`]);if(shouldDeferPostActivationInspections(e.env??process.env))for(const{contribution:e}of await selectPostActivationInspections(t))n.add(e.id);await runDoctorHealthContributionList(e,t.filter(e=>n.has(e.id)));if(e.retirementOnly||e.configWriteRefusal)return}await runDoctorHealthContributionList(e,t)}if(process.env.VITEST||false)globalThis[Symbol.for(`openclaw.doctorHealthContributionsTestApi`)]={resolveDoctorHealthContributions,runDoctorHealthContributionList};export{resolveDoctorContributionHealthChecks,runDoctorHealthContributions};