openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
20 lines • 32.7 kB
JavaScript
import{c as normalizeOptionalLowercaseString,l as normalizeOptionalString,u as normalizeOptionalStringifiedId}from"./string-coerce-CpTFcSwY.mjs";import{s as asFiniteNumber}from"./number-coercion-B3CfI447.mjs";import{r as collectErrorGraphCandidates}from"./error-coercion-DlKnt6w-.mjs";import{a as asOptionalRecord,l as isRecord,r as asNullableRecord}from"./record-coerce-BTbqdJ3-.mjs";import{t as parseJsonWithJson5Fallback}from"./parse-json-compat-BEbcOl-a.mjs";import{f as syncDirectoryIfSupported}from"./directory-durability-o_aQCRBZ.mjs";import{f as shortenHomePath}from"./utils-Dlk0IYAa.mjs";import{t as hasErrnoCode}from"./errno-DUBt6SQQ.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{N as parseAgentSessionKey}from"./session-key-BPgKfU2m.mjs";import{t as formatCliCommand}from"./command-format-D7KhNLP0.mjs";import{O as tryResolveAmbientOwnerAgentId}from"./agent-scope-config-CG9CFpGX.mjs";import{a as isSqliteSchemaVersionError}from"./sqlite-user-version-DaJ6mdUV.mjs";import{m as withExistingOpenClawStateDatabaseArtifactPreservingReadOnlyAsync}from"./openclaw-state-db-readonly-Cd5_cxBs.mjs";import{r as isUpdateRehearsalReadOnlyPath}from"./update-rehearsal-paths-C4qLj9oD.mjs";import{a as isStatePostgres}from"./openclaw-state-db-engine-DiCia3Ut.mjs";import{t as captureOpenClawStateReadContext}from"./openclaw-state-worker-context-Dx8YjqO2.mjs";import{r as decodeUtf8Input}from"./utf8-input-CiFSnxL0.mjs";import{r as TASK_SUGGESTION_TOOL_NAME_MIGRATION,t as IMAGE_INSPECTION_TOOL_NAME_MIGRATION}from"./legacy-tool-name-migration-B172AYxM.mjs";import{r as prepareProviderModelPolicySurfaces}from"./provider-model-routes-D-c2AdKe.mjs";import{c as resolveCronStoreKeyInDatabase,r as resolveCronJobsStorePath}from"./paths-BFxu7LPC.mjs";import{t as coerceFiniteScheduleNumber}from"./schedule-number-C2vuwNBB.mjs";import{t as normalizeCronStaggerMs}from"./stagger-D1kYvF8-.mjs";import{t as decodeStoredCronJobConfig}from"./job-config-codec-6VGrf8_h.mjs";import{i as fingerprintCronJobRows}from"./row-codec-xXb-6VXO.mjs";import{t as normalizeHttpWebhookUrl}from"./webhook-url-C0O6ZHvQ.mjs";import{i as listExistingRetiredStateFiles}from"./state-migrations.retired-files-C6JkM7xQ.mjs";import{t as backupLegacyStateSource}from"./state-migrations.source-backup-BVz4KXlm.mjs";import{t as CronJobsStoreChangedError}from"./save-error-BJMhCOwK.mjs";import{r as loadCronJobsStoreWithConfigJobsReadOnly,t as assertCronStateReadSchemaReadOnly}from"./read-only-CWdlWw2g.mjs";import{_ as loadCronQuarantinedJobs,f as saveCronJobsStore,i as loadCronJobsStoreWithConfigJobs,p as saveCronJobsStoreChanges,t as assertCronJobsStoreUnchanged,v as saveCronQuarantinedJobs}from"./store-GnAg_zUK.mjs";import{l as inspectCronOwnerRowsForDoctor,n as inspectCronJobOwnersForDoctor,t as backupCronStoreForDoctor}from"./store-repair-CIGQuno0.mjs";import{n as readCronStoreSelectionForDoctor}from"./default-store-selection-ScyOOxHE.mjs";import{n as importRetiredStateSource}from"./state-migrations.retired-archive-CdFHLDbj.mjs";import{t as listRetiredCronStateFiles}from"./state-migrations.retired-cron-files-CObv_AEu.mjs";import{t as countLabel}from"./doctor-state-integrity-format-2pYQQBOH.mjs";import{a as repairModelRefAuthProfile,m as rewriteModelReferenceSlot,r as repairRetiredModelSlots,t as createRetiredModelRefRepairResolver}from"./retired-model-ref-repair-DEPRKNGf.mjs";import{t as createModelAliasCanonicalizer}from"./model-alias-canonicalization-B9DfKNbD.mjs";import{a as recoverValidQuarantinedCronScheduleJobs,i as normalizeStoredCronJobs,n as collectStoredCronCodexRuntimePolicyTargets,r as cronCodexRuntimePolicyTargetKey,t as canRepairCronDeliveryForDoctor}from"./store-migration-C4AFuxtV.mjs";import{t as planCronCodexRefRewriteAgainstPersistedConfig}from"./runtime-policy-migration-COcRcsLL.mjs";import path from"node:path";import{createHash}from"node:crypto";import fs from"node:fs/promises";import{isDeepStrictEqual}from"node:util";
//!src/commands/doctor/cron/legacy-json-shapes.ts
function parseCronStateFile(e){try{const t=parseJsonWithJson5Fallback(decodeUtf8Input(e,`Legacy cron runtime state`));if(!isRecord(t)||t.version!==1||!isRecord(t.jobs))return null;return t.jobs}catch{return null}}function legacySchedulePayloadFromRecord(e){const t=normalizeOptionalString(e.kind)?.toLowerCase();const n=normalizeOptionalString(e.expr)??normalizeOptionalString(e.cron);const r=normalizeOptionalString(e.at);const i=coerceFiniteScheduleNumber(e.atMs);const a=coerceFiniteScheduleNumber(e.everyMs);const o=coerceFiniteScheduleNumber(e.anchorMs);const s=normalizeOptionalString(e.tz);const c=normalizeCronStaggerMs(e.staggerMs);const l=t===`at`||t===`every`||t===`cron`?t:r||i!==void 0?`at`:a!==void 0?`every`:n?`cron`:void 0;if(l===`at`)return r?{kind:`at`,at:r}:i!==void 0?{kind:`at`,at:String(i)}:void 0;if(l===`every`&&a!==void 0)return{kind:`every`,everyMs:a,anchorMs:o};if(l===`cron`&&n)return{kind:`cron`,expr:n,tz:s,staggerMs:c}}function tryLegacyCronScheduleIdentity(e){const t=legacySchedulePayloadFromRecord(isRecord(e.schedule)?e.schedule:e);if(!t)return;return JSON.stringify({version:1,enabled:typeof e.enabled===`boolean`?e.enabled:true,schedule:t})}function ensureJobStateObject(e){if(!isRecord(e.state))e.state={}}function backfillMissingRuntimeFields(e){ensureJobStateObject(e);if(typeof e.updatedAtMs!==`number`)e.updatedAtMs=typeof e.createdAtMs===`number`?e.createdAtMs:Date.now()}function mergeStateFileEntry(e,t){if(!isRecord(t)){backfillMissingRuntimeFields(e);return}e.updatedAtMs=asFiniteNumber(t.updatedAtMs)??asFiniteNumber(e.updatedAtMs)??asFiniteNumber(e.createdAtMs)??Date.now();const n=isRecord(t.state)?t.state:{};e.state=n;if(typeof t.scheduleIdentity===`string`&&t.scheduleIdentity!==tryLegacyCronScheduleIdentity(e))n.nextRunAtMs=void 0}function parseLegacyCronJobs(e,t){const n=parseJsonWithJson5Fallback(decodeUtf8Input(e,`Legacy cron job store`));const r=Array.isArray(n)?n:isRecord(n)?n.jobs:void 0;if(!Array.isArray(r))throw new Error(`Unrecognized legacy cron job store; expected an array or a jobs array`);const i=[];const a=[];for(const[e,t]of r.entries()){if(!isRecord(t)){a.push(`Cron row ${e} is not an object and remains available in the archive.`);continue}t.id=normalizeOptionalStringifiedId(t.id)??normalizeOptionalStringifiedId(t.jobId)??`cron-migrated-${e}-${createHash(`sha256`).update(JSON.stringify(t)).digest(`hex`)}`;if(isRecord(t.createdActor)&&t.createdActor.type===`human`)t.createdActor={...t.createdActor,source:`unknown`};i.push(t)}const o=t?parseCronStateFile(t):null;if(t&&!o)a.push(`Unrecognized legacy cron runtime state remains available in the archive.`);const s=!o&&i.some(e=>isRecord(e.state)&&Object.keys(e.state).length>0);for(const e of i)if(o)mergeStateFileEntry(e,o[String(e.id)]);else if(s)ensureJobStateObject(e);else backfillMissingRuntimeFields(e);return{jobs:i,warnings:a}}
//!src/commands/doctor/cron/legacy-notify.ts
function migrateLegacyNotifyFallback(e){let t=false;const n=[];const r=normalizeOptionalString(e.legacyWebhook);const i=r?normalizeHttpWebhookUrl(r):void 0;for(const a of e.jobs){if(!(`notify`in a))continue;const e=normalizeOptionalString(a.name)??normalizeOptionalString(a.id)??`<unnamed>`;if(a.notify!==true){delete a.notify;t=true;continue}const o=asNullableRecord(a.delivery);const s=normalizeOptionalLowercaseString(o?.mode);const c=normalizeOptionalString(o?.to);const l=c?normalizeHttpWebhookUrl(c):void 0;const u=s===void 0&&o!==null&&(normalizeOptionalString(o.channel)!==void 0||normalizeOptionalString(o.accountId)!==void 0||`threadId`in o||c!==void 0&&!l);const d=asNullableRecord(o?.completionDestination);const f=normalizeOptionalLowercaseString(d?.mode);const p=normalizeOptionalString(d?.to);const m=p?normalizeHttpWebhookUrl(p):void 0;if(s===`webhook`&&l||f===`webhook`&&m){delete a.notify;t=true;continue}if(r&&!i){n.push(`Automation "${e}" still uses legacy notify fallback, but cron.webhook is not a valid HTTP(S) URL so doctor cannot migrate it automatically.`);continue}if(i&&(s===void 0&&!u||s===`none`||s===`webhook`))a.delivery={...o,mode:`webhook`,to:s===`none`?i:l??i};else if(i)a.delivery={...o,...u?{mode:`announce`}:{},completionDestination:{...d,mode:`webhook`,to:i}};delete a.notify;t=true}return{changed:t,warnings:n}}
//!src/commands/doctor/cron/legacy-quarantine-migration.ts
async function loadLegacyCronQuarantineForMigration(e){const t=`${e.endsWith(`.json`)?e.slice(0,-5):e}-quarantine.json`;let n;try{n=decodeUtf8Input(await fs.readFile(t),t)}catch(e){if(e.code===`ENOENT`)return;throw e}const r=parseJsonWithJson5Fallback(n);if(!isRecord(r)||r.version!==1||!Array.isArray(r.jobs))throw new Error(`Unsupported cron quarantine file shape at ${t}`);const i=r.jobs.map((e,n)=>{if(!isRecord(e)||typeof e.reason!==`string`||!isRecord(e.job)&&!(`raw`in e))throw new Error(`Unsupported cron quarantine entry at ${t} index ${n}`);const r={quarantinedAtMs:asFiniteNumber(e.quarantinedAtMs)??Date.now(),sourceIndex:typeof e.sourceIndex===`number`?e.sourceIndex:-1,reason:e.reason};if(isRecord(e.job))r.job=e.job;if(`raw`in e)r.raw=e.raw;if(isRecord(e.state))r.state=e.state;if(typeof e.updatedAtMs===`number`&&Number.isFinite(e.updatedAtMs))r.updatedAtMs=e.updatedAtMs;if(typeof e.scheduleIdentity===`string`)r.scheduleIdentity=e.scheduleIdentity;return r});return{path:t,sourceSha256:createHash(`sha256`).update(n).digest(`hex`),jobs:i}}
//!src/commands/doctor/cron/legacy-repair-admission.ts
function captureLegacyCronRepairAdmission(e){const t=captureOpenClawStateReadContext();const assertCurrent=()=>{t.admission.assertCurrent();t.maintenanceScope?.assertDatabaseAccess(t.admission.databasePath)};const assertRowsUnchanged=t=>{assertCurrent();e.legacyImport?.assertCurrent();if(!isDeepStrictEqual(inspectCronOwnerRowsForDoctor(t,resolveCronStoreKeyInDatabase(t,e.storePath)),e.ownerRows))throw new CronJobsStoreChangedError(e.storePath);if(e.jobsFingerprint!==void 0)assertCronJobsStoreUnchanged(t,e.storePath,e.jobsFingerprint)};return{assertCurrent,assertRowsUnchanged}}
//!src/commands/doctor/cron/quarantine-archive.ts
const LEGACY_CRON_ARCHIVE_SUFFIX=`.migrated`;async function legacyCronFileExists(e){try{await fs.access(e);return true}catch(e){if(hasErrnoCode(e,`ENOENT`))return false;throw e}}async function sha256File(e){return createHash(`sha256`).update(await fs.readFile(e)).digest(`hex`)}async function restoreArchivedSource(e,t,n){try{if(await legacyCronFileExists(t))return{ok:false,reason:`archive remains at ${e} because a new source exists at ${t}`}}catch(t){return{ok:false,reason:`archive remains at ${e} because the source path could not be checked: ${formatErrorMessage(t)}`}}try{await fs.rename(e,t)}catch(r){if(hasErrnoCode(r,`EXDEV`)){const r=await copyLegacyCronFileAcrossDevices(e,t,n,false);return r.ok?{ok:true}:r}return{ok:false,reason:`archive remains at ${e} because restoration failed: ${formatErrorMessage(r)}`}}try{await syncDirectoryIfSupported(path.dirname(t));return{ok:true}}catch(e){return{ok:false,reason:`the source was restored, but rollback directory sync failed: ${formatErrorMessage(e)}`}}}async function copyLegacyCronFileAcrossDevices(e,t,n,r=true){let i=t;let a=false;let o=false;try{const t=await fs.stat(e);if(!t.isFile())throw new Error(`legacy cron source is not a regular file`);if(n&&await sha256File(e)!==n)throw new Error(`legacy cron source changed after it was imported; refusing to archive it`);const s=t.mode&511;for(let t=2;;t+=1)try{const e=await fs.open(i,`wx`,s|384);a=true;await e.close();break}catch(n){if(!hasErrnoCode(n,`EEXIST`)||!r)throw n;i=`${e}${LEGACY_CRON_ARCHIVE_SUFFIX}.${t}`}await fs.copyFile(e,i);if(n&&await sha256File(i)!==n)throw new Error(`copied legacy cron archive does not match the imported source`);await fs.chmod(i,s|384);const c=await fs.open(i,`r+`);try{await c.chmod(s);await c.utimes(t.atime,t.mtime);await c.sync()}finally{await c.close()}await syncDirectoryIfSupported(path.dirname(i));const l=await fs.stat(e);if(l.dev!==t.dev||l.ino!==t.ino||n&&await sha256File(e)!==n)throw new Error(`legacy cron source changed during archival; refusing to remove it`);await fs.unlink(e);o=true;await syncDirectoryIfSupported(path.dirname(e));return{ok:true,archivePath:i}}catch(e){if(o)return{ok:false,reason:`${formatErrorMessage(e)}; the durable archive is preserved at ${i} because the source was already removed`};let t=``;if(a){let e=false;try{try{await fs.unlink(i)}catch(e){if(!hasErrnoCode(e,`ENOENT`))throw e}e=true;await syncDirectoryIfSupported(path.dirname(i))}catch(n){t=e?`; the partial archive was removed, but cleanup directory sync failed: ${formatErrorMessage(n)}`:`; partial archive remains at ${i} because cleanup failed: ${formatErrorMessage(n)}`}}return{ok:false,reason:`${formatErrorMessage(e)}${t}`}}}async function archiveLegacyCronFile(e,t){let n=`${e}${LEGACY_CRON_ARCHIVE_SUFFIX}`;try{if(!await legacyCronFileExists(e))return{ok:true};for(let t=2;await legacyCronFileExists(n);t+=1)n=`${e}${LEGACY_CRON_ARCHIVE_SUFFIX}.${t}`}catch(e){return{ok:false,reason:formatErrorMessage(e)}}if(isUpdateRehearsalReadOnlyPath(e,process.env))return{ok:false,deferred:true,reason:`Update rehearsal retained legacy cron source at ${e}; Doctor will archive it during the live update.`};try{await fs.rename(e,n)}catch(r){if(!hasErrnoCode(r,`EXDEV`))return{ok:false,reason:formatErrorMessage(r)};return await copyLegacyCronFileAcrossDevices(e,n,t)}try{if(t&&await sha256File(n)!==t)throw new Error(`legacy cron source changed after it was imported; refusing to archive it`);await syncDirectoryIfSupported(path.dirname(e));if(await legacyCronFileExists(e))return{ok:false,reason:`the imported source was archived, but a new legacy cron source now exists at ${e}`};return{ok:true,archivePath:n}}catch(r){const i=await restoreArchivedSource(n,e,t);return{ok:false,reason:i.ok?formatErrorMessage(r):`${formatErrorMessage(r)}; ${i.reason}`}}}
//!src/commands/doctor/cron/repair-plan.ts
function formatJobNameList(e){const t=e.slice(0,5).map(e=>`\`${e}\``);const n=e.length-t.length;return`: ${t.join(`, `)}${n>0?` (+${n} more)`:``}`}function formatUnresolvedPromptAdvisory(e,t){if(e.length===0)return null;const n=e.length===1;return(t===`command`?[`${countLabel(e.length,`isolated automation`)} ${n?`describes`:`describe`} a shell command in the agent prompt but ${n?`lacks`:`lack`} shell/process tool access${formatJobNameList(e)}.`,`- This is not the supported shell-tool prompt shape, so doctor cannot prove the job will execute the requested command.`,'- Recreate it as a command automation (`openclaw automations add ... --command "<shell>"`) or grant explicit shell/process tool access before relying on it.']:[`${countLabel(e.length,`isolated automation`)} ${n?`drives`:`drive`} shell/process tools from the agent prompt and ${n?`keeps`:`keep`} running as-is${formatJobNameList(e)}.`,`- This is a supported shape, not a legacy store row, so the doctor fix path cannot convert it and the finding is informational only.`,'- For a run without a model, recreate it as a command automation (`openclaw automations add ... --command "<shell>"`).']).join(`
`)}function formatScheduledToolPolicyAdvisory(e){const t=[];if(e.legacyJobs.length>0)t.push(`${countLabel(e.legacyJobs.length,`tool-bearing cron job`)} ${e.legacyJobs.length===1?`keeps`:`keep`} legacy sender-policy resolution because an explicit tool cap or provable stored account identity is missing${formatJobNameList(e.legacyJobs)}.`);if(e.invalidJobs.length>0)t.push(`${countLabel(e.invalidJobs.length,`tool-bearing cron job`)} ${e.invalidJobs.length===1?`has`:`have`} invalid or inconsistent scheduled authority provenance${formatJobNameList(e.invalidJobs)}.`);if(t.length===0)return null;t.push(`- These jobs continue through restrictive sender-policy resolution; doctor will not infer authority from delivery or current configuration.`,"- Recreate the job from a fresh authenticated creator turn, or reauthorize its complete tool cap from a trusted operator shell: `openclaw automations edit <id> --tools <tool,...>`.");return t.join(`
`)}function formatLegacyGatewayExecAdvisory(e){if(e.length===0)return null;return[`${countLabel(e.length,`automation`)} ${e.length===1?`grants`:`grant`} the retired \`gateway_exec\` alias${formatJobNameList(e)}.`,"- Doctor will not convert this alias to `exec` because the stored name does not prove its original producer or approval restrictions.",`- Recreate the automation from a fresh authenticated creator turn, or explicitly reauthorize its complete tool cap from a trusted operator shell.`].join(`
`)}function formatLegacyIssuePreview(e){const t={jobId:"still uses legacy `jobId`",missingId:"is missing a string `id`",nonStringId:"stores `id` as a non-string value",legacyScheduleString:`stores schedule as a bare string`,legacyScheduleCron:"still uses `schedule.cron`",legacyScheduleKind:"stores a outdated schedule `kind` or stream `mode` that will be normalized",legacyPayloadKind:`needs payload kind normalization`,legacyPayloadCodexModel:"still uses legacy `openai-codex/*` cron model refs",legacyTaskSuggestionToolName:`still grants legacy tool \`${TASK_SUGGESTION_TOOL_NAME_MIGRATION.legacyName}\`; doctor will rename it to \`${TASK_SUGGESTION_TOOL_NAME_MIGRATION.canonicalName}\``,legacyImageInspectionToolName:`still relies on legacy \`${IMAGE_INSPECTION_TOOL_NAME_MIGRATION.legacyName}\` coverage; doctor will preserve equivalent \`${IMAGE_INSPECTION_TOOL_NAME_MIGRATION.canonicalName}\` access`,legacyAgentTurnCommandPayload:`uses an agent prompt to run a shell command`,legacyPayloadProvider:"still uses payload `provider` as a delivery alias",legacyTopLevelPayloadFields:`still uses top-level payload fields`,legacyTopLevelDeliveryFields:`still uses top-level delivery fields`,legacyDeliveryMode:"still uses delivery mode `deliver`",migratedScheduledToolPolicy:`can recover scheduled account authority from persisted owner identity`,reconciledOwnerAccount:`can reconcile its owner account from persisted creator identity without changing tool permissions`,invalidSchedule:`has an invalid persisted schedule and will be removed`,invalidPayload:`has an invalid persisted payload and will be removed`};return Object.entries(t).flatMap(([t,n])=>{const r=e[t];return r?[`- ${countLabel(r,`job`)} ${n}`]:[]})}function mergeRuntimeEntryIntoConfigJob(e){return{...decodeStoredCronJobConfig(e.job),...e.runtimeEntry?.updatedAtMs!==void 0?{updatedAtMs:e.runtimeEntry.updatedAtMs}:{},...e.runtimeEntry?.state?{state:structuredClone(e.runtimeEntry.state)}:{}}}
//!src/commands/doctor/cron/schema-safety.ts
async function assertCronStateSchemaSupportedAsync(e){if(isStatePostgres()){await assertCronStateReadSchemaReadOnly(e);return}await withExistingOpenClawStateDatabaseArtifactPreservingReadOnlyAsync(()=>void 0,{env:e})}function rethrowSqliteSchemaVersionError(e){if(isSqliteSchemaVersionError(e))throw e}
//!src/commands/doctor/cron/legacy-repair.ts
function readLegacyCronStorePath(e){return e.cron?.store}function projectCronOwner(e,t){const n=normalizeOptionalString(e.agentId)??parseAgentSessionKey(normalizeOptionalString(e.sessionKey))?.agentId;if(n)return{kind:`explicit`,agentId:n};return t?{kind:`runtime-default`,agentId:t}:{kind:`unresolved`}}async function loadLegacyCronRepairState(e){const t=e.storePath??resolveCronJobsStorePath(readLegacyCronStorePath(e.cfg),e.env);await assertCronStateSchemaSupportedAsync(e.env);const n=await loadLegacyCronQuarantineForMigration(t);if(e.onlyIfLegacyDetected&&!n)return null;const r=await loadCronQuarantinedJobs(t,e.env);const i=e.readOnly?await loadCronJobsStoreWithConfigJobsReadOnly(t,e.env):await loadCronJobsStoreWithConfigJobs(t);const a=tryResolveAmbientOwnerAgentId(e.cfg);const o=new Map(i.store.jobs.map(e=>[e.id,projectCronOwner(e,a)]));const s=await inspectCronJobOwnersForDoctor({env:e.env??process.env},t);if(i.jobsFingerprint!==void 0&&fingerprintCronJobRows(s)!==i.jobsFingerprint)throw new CronJobsStoreChangedError(t);const c=new Map(s.flatMap(e=>{const t=normalizeOptionalString(e.agent_id);return t?[[e.job_id,t]]:[]}));for(const[e,t]of c)if(o.get(e)?.kind!==`explicit`)o.set(e,{kind:`explicit`,agentId:t});const l=[...i.invalidConfigRows];const u=i.configJobs.length>0?i.configJobs.map((e,t)=>mergeRuntimeEntryIntoConfigJob({job:e,runtimeEntry:i.configJobRuntimeEntries[t]})):i.store.jobs;for(const e of u){const t=normalizeOptionalString(e.id)??normalizeOptionalString(e.jobId);const n=t?c.get(t):void 0;if(n&&canRepairCronDeliveryForDoctor(e.delivery)&&projectCronOwner(e,void 0).kind===`unresolved`)e.agentId=n}return{storePath:t,legacyQuarantine:n,invalidConfigRows:l,persistedQuarantine:r,projectedOwnersByJobId:o,rawJobs:u,jobsFingerprint:i.jobsFingerprint,ownerRows:s}}async function applyLegacyCronStoreRepair(e){await assertCronStateSchemaSupportedAsync();await prepareProviderModelPolicySurfaces();const{state:t}=e;const n=[];const r=[];const i=e.repairRetiredModelRefs===true?createRetiredModelRefRepairResolver({cfg:e.cfg,modelReplacements:e.modelReplacements,checkModelPolicy:true,retiredModelRefConfig:e.retiredModelRefConfig,authProfileIdMap:e.authProfileIdMap,warnings:r}):e.authProfileIdMap?.size?({modelRef:t})=>repairModelRefAuthProfile(t,e.authProfileIdMap):void 0;const a=e.recoverQuarantinedScheduleJobs===true?[...t.persistedQuarantine,...t.legacyQuarantine?.jobs??[]]:[];const o=new Set(t.persistedQuarantine);const s=recoverValidQuarantinedCronScheduleJobs(a,new Set(t.rawJobs.map(e=>normalizeOptionalStringifiedId(e.id)).filter(e=>e!==void 0)));if(s.recoveredJobs.length>0)t.rawJobs.push(...s.recoveredJobs);const c=e.migrateCodexModelRefs===true?planCronCodexRefRewriteAgainstPersistedConfig({cfg:e.cfg,targets:collectStoredCronCodexRuntimePolicyTargets(t.rawJobs),blockedModelIdentities:e.blockedModelIdentities,resolveFinalModelRef:i}):void 0;r.push(...c?.warnings??[]);const l=new Set((c?.blockedTargets??[]).map(cronCodexRuntimePolicyTargetKey));const u=e.normalized&&s.recoveredJobs.length===0?e.normalized:normalizeStoredCronJobs(t.rawJobs,{migrateCodexModelRefs:e.migrateCodexModelRefs,shouldMigrateCodexRuntimePolicyTarget:e=>!l.has(cronCodexRuntimePolicyTargetKey(e))});r.push(...u.unsupportedLegacyTriggerScriptJobs.map(e=>`Cron trigger script for ${e} uses legacy Code Mode APIs that cannot be safely converted; inspect the automation and update its trigger script manually to use direct tool calls.`));r.push(...u.unsupportedDeliveryModeJobs.map(e=>`Cron job ${e} has an unsupported delivery mode. Review its intended delivery and set mode to "none", "announce", or "webhook"; Doctor cannot infer the intended route.`));const d=normalizeOptionalString(e.cfg.cron?.webhook);const f=migrateLegacyNotifyFallback({jobs:t.rawJobs.filter(e=>canRepairCronDeliveryForDoctor(e.delivery)),legacyWebhook:d});r.push(...f.warnings);const p=[];if(i)for(const n of t.rawJobs){if(!canRepairCronDeliveryForDoctor(n.delivery))continue;const a=asOptionalRecord(n.payload);const o=normalizeOptionalStringifiedId(n.id);if(!a||!o)continue;const s=t.projectedOwnersByJobId.get(o);const c=normalizeOptionalString(n.agentId)??(s&&s.kind!==`unresolved`?s.agentId:tryResolveAmbientOwnerAgentId(e.cfg));if(!c&&e.repairRetiredModelRefs)r.push(`Skipped retired model repair for cron job "${o}": select its owning agent, then rerun openclaw doctor --fix.`);const l=p.length;repairRetiredModelSlots({owner:a,path:`cron.${o}.payload`,agentId:c,authProfileOnly:!c,resolve:i,changes:p});if(p.length>l&&asOptionalRecord(n.state)?.autoDisabled){const e=normalizeOptionalString(n.name)??o;p.push(`Automation "${e}" remains auto-disabled. Run openclaw automations enable ${o} to resume it after this repair.`)}}const m=(t.legacyImport?.count??0)>0||p.length>0||t.invalidConfigRows.length>0||u.mutated||f.changed||s.recoveredJobs.length>0;if(!(t.legacyQuarantine!==void 0||m)&&r.length===0)return{changes:n,warnings:r};const h=[...e.recoverQuarantinedScheduleJobs===true?s.retainedEntries.filter(e=>!o.has(e)):t.legacyQuarantine?.jobs??[],...t.invalidConfigRows,...u.removedJobs.map(e=>({sourceIndex:e.sourceIndex,reason:e.reason,job:e.job}))];const g=h.length>0?{entries:h,nowMs:Date.now()}:void 0;const _=s.recoveredEntries.filter(e=>o.has(e));if(m||g)try{if(m){const e={version:1,jobs:t.rawJobs};const{assertCurrent:i,assertRowsUnchanged:a}=captureLegacyCronRepairAdmission(t);const o={...g?{quarantine:g}:{},..._.length>0?{deleteQuarantineEntries:_}:{},preserveRuntimeState:true};if(t.ownerRows.length>0||t.persistedQuarantine.length>0){const o=await backupCronStoreForDoctor({env:process.env},{plan:[`legacy`,t.storePath,t.ownerRows,t.jobsFingerprint,t.persistedQuarantine,e,h,_],assertCurrent:i,assertRowsUnchanged:a});n.push(`Saved pre-repair cron backup: ${o.backupPath}`);r.push(...o.warnings)}await saveCronJobsStore(t.storePath,e,{...o,transactionHooks:{beforeWrite:a}})}else if(g)await saveCronQuarantinedJobs({storePath:t.storePath,...g})}catch(e){rethrowSqliteSchemaVersionError(e);if(t.legacyImport)throw e;const i=collectErrorGraphCandidates(e,e=>[e.cause]).some(e=>e instanceof CronJobsStoreChangedError)?`Cron store at ${shortenHomePath(t.storePath)} changed while doctor was waiting, so no rows were rewritten; re-run ${formatCliCommand(`openclaw doctor --fix`)} to repair from a fresh snapshot.`:`Failed writing migrated cron store at ${shortenHomePath(t.storePath)}: ${formatErrorMessage(e)}`;return{changes:n,warnings:[...r,i]}}n.push(...p);if(u.issues.reconciledOwnerAccount)n.push(`Reconciled ${countLabel(u.issues.reconciledOwnerAccount,`cron job owner account`)} from persisted creator identity; existing tool permissions were preserved.`);if(s.recoveredJobs.length>0)n.push(`Recovered ${countLabel(s.recoveredJobs.length,`quarantined automation`)} after current schedule validation passed.`);if(t.legacyQuarantine){const e=await archiveLegacyCronFile(t.legacyQuarantine.path,t.legacyQuarantine.sourceSha256);if(e.ok)n.push(`Cron quarantine migrated to SQLite from ${shortenHomePath(t.legacyQuarantine.path)}.`);else r.push(e.deferred?e.reason:`Migrated quarantined automations to SQLite but could not archive the legacy cron file at ${shortenHomePath(t.legacyQuarantine.path)}: ${e.reason}. Remove it manually or rerun ${formatCliCommand(`openclaw doctor --fix`)} to retry.`)}if(m)n.push(`Cron store normalized at ${shortenHomePath(t.storePath)}.`);if(u.legacyTriggerScriptJobs.length>0)n.push(`Rewrote ${countLabel(u.legacyTriggerScriptJobs.length,`legacy cron trigger script`)} to direct tool calls: ${u.legacyTriggerScriptJobs.join(`, `)}.`);return{changes:n,warnings:r,codexRuntimePolicyTargets:u.codexRuntimePolicyTargets}}async function repairLegacyCronStoreWithoutPrompt(e){const t=await readCronStoreSelectionForDoctor(e.cfg);if(t.status===`unresolved`)return{changes:[],warnings:[t.message]};const n=await migrateRetiredCronState(e);const r=resolveCronJobsStorePath(normalizeOptionalString(readLegacyCronStorePath(e.cfg)));let i;try{i=await loadLegacyCronRepairState({cfg:e.cfg,onlyIfLegacyDetected:true})}catch(e){rethrowSqliteSchemaVersionError(e);return{changes:[],warnings:[`Failed reading legacy cron storage at ${shortenHomePath(r)}: ${formatErrorMessage(e)}`]}}if(!i)return n;const a=await applyLegacyCronStoreRepair({...e,state:i});return{...a,changes:[...n.changes,...a.changes],warnings:[...n.warnings,...a.warnings]}}async function migrateRetiredCronState(e){const t=e.env??process.env;await assertCronStateSchemaSupportedAsync(t);const n=resolveCronJobsStorePath(readLegacyCronStorePath(e.cfg),t);const r=await listRetiredCronStateFiles(n);const i=r[1];const a=captureOpenClawStateReadContext();const assertCurrent=()=>{a.admission.assertCurrent();a.maintenanceScope?.assertDatabaseAccess(a.admission.databasePath)};const o=/* @__PURE__ */ new Map;for(const e of listExistingRetiredStateFiles(r))o.set(e,await backupLegacyStateSource({filePath:e,assertCurrent}));const s={changes:[],warnings:[]};const c=o.get(n);if(c)await importRetiredStateSource({source:c,label:`legacy cron jobs`,parse:e=>parseLegacyCronJobs(e,o.get(i)?.bytes),recoveryInstructions:`Recover job definitions from ${c.backupPath} with openclaw automations add.`,result:s,commit:async r=>{s.warnings.push(...r.warnings);const a=await loadLegacyCronRepairState({cfg:e.cfg,storePath:n,env:t});if(!a)throw new Error(`Cron repair snapshot unavailable`);const l=new Set(a.rawJobs.map(e=>normalizeOptionalStringifiedId(e.id)));const u=r.jobs.filter(e=>{const t=normalizeOptionalStringifiedId(e.id);if(l.has(t))return false;l.add(t);return true});if(u.length){a.rawJobs.push(...u);a.legacyImport={count:u.length,assertCurrent:()=>{c.assertUnchanged();o.get(i)?.assertUnchanged()}};const t=await applyLegacyCronStoreRepair({cfg:e.cfg,state:a});s.changes.push(...t.changes);s.warnings.push(...t.warnings);s.changes.push(`Imported ${u.length} legacy cron job(s) into SQLite.`)}}});for(const[e,t]of o){if(e===n)continue;assertCurrent();t.removeSource(()=>void 0);s.warnings.push(`Archived retired cron state to ${t.backupPath}. ${e.endsWith(`.jsonl`)?`Historical runs remain readable as JSONL in this archive; current runs use SQLite task history.`:`Original job definitions and runtime state remain available in this archive.`}`)}return s}async function collectCronCodexRuntimePolicyTargetsReadOnly(e){const t=resolveCronJobsStorePath(normalizeOptionalString(readLegacyCronStorePath(e.cfg)));try{const t=await loadLegacyCronRepairState({cfg:e.cfg,readOnly:true});return{targets:t?collectStoredCronCodexRuntimePolicyTargets(t.rawJobs):[],warnings:[]}}catch(e){rethrowSqliteSchemaVersionError(e);return{targets:[],warnings:[`Failed reading cron storage at ${shortenHomePath(t)} while planning Codex model migration: ${formatErrorMessage(e)}`]}}}async function repairCronCodexModelRefsAfterConfigWrite(e){const t=resolveCronJobsStorePath(normalizeOptionalString(readLegacyCronStorePath(e.cfg)));try{if(!e.migrateCodexModelRefs&&!e.repairRetiredModelRefs){const n=await loadCronJobsStoreWithConfigJobsReadOnly(t);const{store:r}=n;const i={...r,jobs:[...r.jobs]};const a=[];for(const[t,r]of i.jobs.entries()){const{runtimeAuthority:o,runtimeAuthorityRecoveryRequired:s,...c}=n.configJobs[t];const l=Object.assign(structuredClone(r),mergeRuntimeEntryIntoConfigJob({job:structuredClone(c),runtimeEntry:n.configJobRuntimeEntries[t]}));const u=a.length;repairRetiredModelSlots({owner:l.payload,path:`cron.${r.id}.payload`,authProfileOnly:true,resolve:({modelRef:t})=>repairModelRefAuthProfile(t,e.authProfileIdMap),changes:a});if(a.length>u)i.jobs[t]=l}await saveCronJobsStoreChanges(t,r,i);return{changes:a,warnings:[]}}const n=await loadLegacyCronRepairState({cfg:e.cfg});return n?await applyLegacyCronStoreRepair({...e,state:n}):{changes:[],warnings:[]}}catch(e){rethrowSqliteSchemaVersionError(e);return{changes:[],warnings:[`Failed reading cron storage at ${shortenHomePath(t)} while committing Codex model migration: ${formatErrorMessage(e)}`]}}}async function canonicalizeCronModelReplacementAliases(e){const t=await readCronStoreSelectionForDoctor(e.cfg,e.env??process.env);if(t.status!==`ready`)return{changes:[],warnings:[`Cannot prepare model aliases until the cron partition is selected.`]};const n=await loadCronJobsStoreWithConfigJobsReadOnly(t.storePath);const r=n.store;const i={...r,jobs:[...r.jobs]};const a=createModelAliasCanonicalizer(e.cfg,e.modelReplacements);const o=[];for(const[t,s]of r.jobs.entries()){const{runtimeAuthority:r,runtimeAuthorityRecoveryRequired:c,...l}=n.configJobs[t];const u=Object.assign(structuredClone(s),mergeRuntimeEntryIntoConfigJob({job:structuredClone(l),runtimeEntry:n.configJobRuntimeEntries[t]}));const d=u.agentId??parseAgentSessionKey(u.sessionKey)?.agentId??tryResolveAmbientOwnerAgentId(e.cfg);if(!d)continue;const rewrite=e=>a(e,d);const f=asOptionalRecord(u.payload);const p=JSON.stringify(f);rewriteModelReferenceSlot({container:f,key:`model`,path:`model`,resolve:rewrite});rewriteModelReferenceSlot({container:{selector:f},key:`selector`,path:`payload`,resolve:rewrite});if(JSON.stringify(f)!==p){i.jobs[t]=u;o.push(`Preserved old model alias identity for cron job "`+s.id+`" before config migration.`)}}await saveCronJobsStoreChanges(t.storePath,r,i);return{changes:o,warnings:[]}}export{migrateRetiredCronState as a,repairLegacyCronStoreWithoutPrompt as c,formatLegacyIssuePreview as d,formatScheduledToolPolicyAdvisory as f,loadLegacyCronRepairState as i,rethrowSqliteSchemaVersionError as l,canonicalizeCronModelReplacementAliases as n,readLegacyCronStorePath as o,formatUnresolvedPromptAdvisory as p,collectCronCodexRuntimePolicyTargetsReadOnly as r,repairCronCodexModelRefsAfterConfigWrite as s,applyLegacyCronStoreRepair as t,formatLegacyGatewayExecAdvisory as u};