openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
8 lines • 8.13 kB
JavaScript
import{f as shortenHomePath}from"./utils-Dlk0IYAa.mjs";import{a as safeRealpathSync$1}from"./boundary-path-BeuXNL_4.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{m as statIfExists$1}from"./path-existence-BR9MXlgL.mjs";import{i as findGitRoot}from"./git-commit-Cb3n8ZQM.mjs";import{a as resolveCanonicalRootMemoryPath,n as LEGACY_ROOT_MEMORY_FILENAME,o as resolveLegacyRootMemoryPath,s as resolveRootMemoryRepairDir,t as CANONICAL_ROOT_MEMORY_FILENAME}from"./root-memory-files-D4maM5wF.mjs";import{t as DEFAULT_AGENTS_FILENAME}from"./workspace-bootstrap-policy-B71K4ysN.mjs";import"./workspace-1G3FI-0P.mjs";import{t as note}from"./note-e4DtVgg2.mjs";import fs from"node:fs";import path from"node:path";import{readRegularFile}from"@openclaw/fs-safe/advanced";import{safeStatSync}from"@openclaw/fs-safe/path";import{isUtf8}from"node:buffer";import{replaceFileAtomic}from"@openclaw/fs-safe/atomic";
//!src/commands/doctor-workspace.ts
const AGENTS_MD_MAX_BYTES=1048576;const ROOT_MEMORY_FILE_MAX_BYTES=8388608;const MEMORY_SYSTEM_PROMPT=[`Memory system not found in workspace.`,`Paste this into your agent:`,``,`Install the memory system by applying:`,`https://github.com/openclaw/openclaw/commit/9ffea23f31ca1df5183b25668f8f814bee0fb34e`,`https://github.com/openclaw/openclaw/commit/7d1fee70e76f2f634f1b41fca927ee663914183a`].join(`
`);function collectWorkspaceBackupTip(e){if(!safeStatSync(e)?.isDirectory())return null;const t=safeRealpathSync$1(e);if(!t||findGitRoot(t))return null;return`- Tip: back up the agent workspace in a private git repo; keep ~/.openclaw out of git (credentials, sessions). Details: /concepts/agent-workspace#git-backup-recommended-private`}async function shouldSuggestMemorySystem(e){if((await listWorkspaceEntries(e)).has(`MEMORY.md`))try{if((await fs.promises.stat(resolveCanonicalRootMemoryPath(e))).isFile())return false}catch{}const t=path.join(e,DEFAULT_AGENTS_FILENAME);try{const e=await fs.promises.realpath(t);const{buffer:n}=await readRegularFile({filePath:e,maxBytes:AGENTS_MD_MAX_BYTES});if(new RegExp(`\\b${`MEMORY.md`.replace(`.`,`\\.`)}\\b`).test(n.toString(`utf-8`)))return false}catch{}return true}async function statIfExists(e){const t=await statIfExists$1(e);return t?.isFile()?{exists:true,bytes:t.size}:{exists:false}}async function listWorkspaceEntries(e){try{return new Set(await fs.promises.readdir(e))}catch(e){if(e?.code===`ENOENT`)return/* @__PURE__ */ new Set;throw e}}async function detectRootMemoryFiles(e){const t=path.resolve(e);const n=resolveCanonicalRootMemoryPath(t);const r=resolveLegacyRootMemoryPath(t);const i=await listWorkspaceEntries(t);const inspect=e=>i.has(path.basename(e))?statIfExists(e):Promise.resolve({exists:false});const[a,o]=await Promise.all([inspect(n),inspect(r)]);return{workspaceDir:t,canonicalPath:n,legacyPath:r,canonicalExists:a.exists,legacyExists:o.exists,...typeof a.bytes===`number`?{canonicalBytes:a.bytes}:{},...typeof o.bytes===`number`?{legacyBytes:o.bytes}:{}}}function formatBytes(e){return typeof e===`number`?`${e} bytes`:`size unknown`}async function moveLegacyRootMemoryFileToArchive(e){const t=resolveRootMemoryRepairDir(e.workspaceDir);await fs.promises.mkdir(t,{recursive:true});const n=await fs.promises.mkdtemp(path.join(t,`${(/* @__PURE__ */ new Date()).toISOString().replaceAll(`:`,`-`).replaceAll(`.`,`-`)}-`));const r=path.join(n,LEGACY_ROOT_MEMORY_FILENAME);await fs.promises.rename(e.legacyPath,r);return r}function buildMergedLegacyRootMemorySection(e){return[``,`## Imported From Legacy Root ${LEGACY_ROOT_MEMORY_FILENAME}`,``,`<!-- openclaw-root-memory-merge source=${LEGACY_ROOT_MEMORY_FILENAME} archived=${e.archivedLegacyPath} -->`,`This content came from legacy root \`${LEGACY_ROOT_MEMORY_FILENAME}\`, which was shadowed by \`${CANONICAL_ROOT_MEMORY_FILENAME}\`.`,``,e.legacyText.trim(),``].join(`
`)}async function migrateLegacyRootMemoryFile(e){const t=await detectRootMemoryFiles(e);const n={changed:false,canonicalPath:t.canonicalPath,legacyPath:t.legacyPath,mergedLegacy:false};if(!t.canonicalExists||!t.legacyExists)return n;const skippedForReadFailure=e=>{const t=e instanceof Error?e.message:``;return{...n,skipReason:t.startsWith(`File exceeds`)?`a file exceeded the safe read limit`:t.startsWith(`File is not valid UTF-8:`)?t:`a file could not be read`}};const readMemoryFile=async e=>{const{buffer:t}=await readRegularFile({filePath:e,maxBytes:ROOT_MEMORY_FILE_MAX_BYTES});if(!isUtf8(t))throw new Error(`File is not valid UTF-8: ${e}; preserve its bytes and convert a copy to UTF-8 before retrying`);return t.toString(`utf-8`)};try{await Promise.all([readMemoryFile(t.canonicalPath),readMemoryFile(t.legacyPath)])}catch(e){return skippedForReadFailure(e)}let r;try{r=await moveLegacyRootMemoryFileToArchive({workspaceDir:t.workspaceDir,legacyPath:t.legacyPath})}catch{return{...n,skipReason:`legacy memory could not be archived atomically`}}let i;let a;try{[i,a]=await Promise.all([readMemoryFile(t.canonicalPath),readMemoryFile(r)])}catch(e){return{...skippedForReadFailure(e),changed:true,archivedLegacyPath:r}}let o;if(i!==a){const e=`${i.trimEnd()}\n${buildMergedLegacyRootMemorySection({legacyText:a,archivedLegacyPath:shortenHomePath(r)})}`;o=path.join(path.dirname(r),`${CANONICAL_ROOT_MEMORY_FILENAME}.pre-merge`);await fs.promises.copyFile(t.canonicalPath,o);const n=await fs.promises.realpath(t.workspaceDir);await replaceFileAtomic({filePath:path.join(n,CANONICAL_ROOT_MEMORY_FILENAME),content:e,dirMode:(await fs.promises.stat(n)).mode&4095,preserveExistingMode:true,tempPrefix:CANONICAL_ROOT_MEMORY_FILENAME,syncTempFile:true,syncParentDir:true,throwOnCleanupError:true})}return{...n,changed:true,mergedLegacy:i!==a,archivedLegacyPath:r,...o?{canonicalBackupPath:o}:{}}}async function noteWorkspaceMemoryHealth(e){try{const t=await detectRootMemoryFiles(e.workspaceDir);if(t.canonicalExists&&t.legacyExists){const n=[`Split root durable memory files detected:`,`- current: ${shortenHomePath(t.canonicalPath)} (${formatBytes(t.canonicalBytes)})`,`- legacy: ${shortenHomePath(t.legacyPath)} (${formatBytes(t.legacyBytes)})`,`OpenClaw uses ${CANONICAL_ROOT_MEMORY_FILENAME} as the current durable memory file.`,`Dreaming writes durable promotions to ${CANONICAL_ROOT_MEMORY_FILENAME}, so older facts in ${LEGACY_ROOT_MEMORY_FILENAME} can be shadowed.`,`Run "openclaw doctor --fix" to merge the legacy file into ${CANONICAL_ROOT_MEMORY_FILENAME} with a backup.`].join(`
`);note(`${e.labelAgent?`Agent "${e.agentId}":\n`:``}${n}`,`Workspace memory`)}}catch(t){const n=e.labelAgent?`Agent "${e.agentId}": `:``;note(`${n}Workspace memory audit could not be completed: ${formatErrorMessage(t)}`,`Doctor`)}}async function maybeRepairWorkspaceMemoryHealth(e){try{const t=e.scope.labelAgent?`Agent "${e.scope.agentId}": `:``;const n=await detectRootMemoryFiles(e.scope.workspaceDir);if(!n.canonicalExists||!n.legacyExists)return;if(!await e.prompter.confirmRuntimeRepair({message:`${t}Merge legacy root ${`memory.md`} into the current ${`MEMORY.md`} and remove the shadowed file?`,initialValue:true}))return;const r=await migrateLegacyRootMemoryFile(e.scope.workspaceDir);const i=r.skipReason;if(i){note([`${t}Workspace memory root repair skipped (${i}):`,`- current: ${r.canonicalPath}`,`- legacy: ${r.legacyPath}`,r.archivedLegacyPath?`- preserved archive: ${r.archivedLegacyPath}`:null].filter(e=>Boolean(e)).join(`
`),`Doctor changes`);return}if(!r.changed)return;const a=[`${t}Workspace memory root merged:`,`- current: ${r.canonicalPath}`,r.archivedLegacyPath?`- backup: ${r.archivedLegacyPath}`:null,r.canonicalBackupPath?`- pre-merge backup: ${r.canonicalBackupPath}`:null,r.mergedLegacy?`- merged legacy content from: ${r.legacyPath}`:null,`- removed legacy file: ${r.legacyPath}`].filter(Boolean);note(a.join(`
`),`Doctor changes`)}catch(t){const n=e.scope.labelAgent?`Agent "${e.scope.agentId}": `:``;note(`${n}Workspace memory repair could not be completed: ${formatErrorMessage(t)}`,`Doctor`)}}export{shouldSuggestMemorySystem as a,noteWorkspaceMemoryHealth as i,collectWorkspaceBackupTip as n,maybeRepairWorkspaceMemoryHealth as r,MEMORY_SYSTEM_PROMPT as t};