openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
9 lines • 15.6 kB
JavaScript
import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{r as isPathInside}from"./path-guards-DGttsOJI.mjs";import{r as resolveStateDir}from"./state-dir-BwIClCab.mjs";import{l as pathExists,x as root}from"./fs-safe-Bxzu1j4h.mjs";import{i as isMissingPathError}from"./errno-DUBt6SQQ.mjs";import"./paths-D_FOvGon.mjs";import"./errors-D37BJTfI.mjs";import{n as normalizeAgentId}from"./agent-id-cOfqmfln.mjs";import{N as parseAgentSessionKey}from"./session-key-BPgKfU2m.mjs";import{i as listAgentIds}from"./agent-roster-4XrgUgPK.mjs";import{f as resolveAgentWorkspaceDir}from"./agent-scope-config-CG9CFpGX.mjs";import{a as getOpenClawDatabaseMaintenanceScope}from"./openclaw-state-maintenance-context-D-pYfco8.mjs";import{n as isPostgresSqlConnection}from"./sql-connection-nx8lLUJM.mjs";import{D as requireNativeDatabaseFile}from"./sqlite-schema-facts-CWOeTpUB.mjs";import{a as tableExists}from"./openclaw-state-db-schema-helpers-rYTimzjJ.mjs";import{n as listDirectoryTreeStrict}from"./directory-walk-DnlcJ5Lu.mjs";import"./openclaw-state-db-async-lifecycle-DlV0ztcV.mjs";import{n as sha256Hex}from"./node-crypto-DPk8agfR.mjs";import"./crypto-digest-T8X5EZni.mjs";import{s as resolveCanonicalWorkspacePath}from"./workspace-state-identity-D-_UPy3C.mjs";import{r as isUpdateRehearsalReadOnlyPath}from"./update-rehearsal-paths-C4qLj9oD.mjs";import{l as dropRetiredSkillWorkshopProposalTables}from"./openclaw-state-db-schema-repair-DvOvTgL6.mjs";import{l as runOpenClawStateWriteTransaction,n as openOpenClawStateDatabase}from"./openclaw-state-db-BlgxYkYw.mjs";import{r as decodeUtf8Input}from"./utf8-input-CiFSnxL0.mjs";import{r as acquireGatewayLock}from"./gateway-lock-CQoO1usb.mjs";import{r as resolveAgentSkillsRoot}from"./skill-paths-DEQTiKUZ.mjs";import{a as readWorkspaceSkillFile,i as prepareWorkspaceSkillRestoration,o as readWorkspaceSupportFile,s as restoreWorkspaceSkillMutation}from"./workspace-skill-write-CTBSBMqG.mjs";import{rmSync}from"node:fs";import path from"node:path";import fs$1 from"node:fs/promises";
//!src/commands/doctor-skill-workshop-retire-proposals.ts
function resolveWorkshopSkillsDir(e,t,n=process.env){return resolveAgentSkillsRoot({config:e,agentId:t,dirName:`workshop-skills`,env:n})}function resolveWorkshopDraftsDir(e,t,n){return path.join(resolveWorkshopSkillsDir(e,t,n),`.drafts`)}const LEGACY_PROPOSALS_DIR=path.join(`skill-workshop`,`proposals`);const LEGACY_PROPOSALS_MANIFEST=path.join(`skill-workshop`,`proposals.json`);const PROPOSAL_ID_PATTERN=/^[a-z0-9][a-z0-9-]{5,120}$/u;const DRAFT_FILE_PATTERN=/^(?:generations\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/)?PROPOSAL\.md$/u;const MAX_EXPORT_FILE_BYTES=8388608;const MAX_ROLLBACK_BYTES=134217728;const EXPORTED_STATUSES=/* @__PURE__ */ new Set([`pending`,`quarantined`]);const EARLIER_EXPORT_DIR=path.join(`.archive`,`.retired-proposals`);function parseRetiredProposal(e,t,n){if(!isRecord(t))throw new Error(`proposal record is not an object`);const{draftFile:r=`PROPOSAL.md`,supportFiles:i=[]}=t;if(typeof r!==`string`||!DRAFT_FILE_PATTERN.test(r))throw new Error(`proposal record has an invalid draft path`);if(!Array.isArray(i))throw new Error(`proposal record has invalid support files`);return{id:e,ownerAgentId:n,draftFile:r,supportFiles:i.map(e=>{const t=isRecord(e)?e.path:void 0;if(typeof t!==`string`||path.posix.isAbsolute(t)||t.split(`/`).some(e=>!e||e===`.`||e===`..`)||t===`SKILL.md`)throw new Error(`proposal record has an invalid support file path`);return t})}}function parseUnfinishedApply(e,t,n){const r=isRecord(t)&&isRecord(t.target)?t.target:{};const i=n.targetSkillFile;if(typeof i!==`string`||!path.isAbsolute(i)||path.basename(i)!==`SKILL.md`||r.skillFile!==i)throw new Error(`rollback does not match its proposal target`);const a=new Map((isRecord(t)&&Array.isArray(t.supportFiles)?t.supportFiles:[]).filter(isRecord).map(e=>[e.path,e.hash]));const o=n.supportFiles??[];if(!Array.isArray(o))throw new Error(`rollback has invalid support files`);const s=o.map(e=>{const t=isRecord(e)?e.path:void 0;const n=a.get(t);const r=isRecord(e)&&e.existed===true?e.previousContent:null;if(typeof t!==`string`||typeof n!==`string`||r!==null&&typeof r!==`string`)throw new Error(`rollback has an invalid support file`);return{path:t,previousContent:r,proposedContentHash:n}});const c=n.previousContent??null;if(c!==null&&typeof c!==`string`)throw new Error(`rollback has invalid previous content`);return{proposalId:e,skillFile:i,previousContent:c,supportFiles:s}}function readDatabaseProposals(e,t){const{db:n}=openOpenClawStateDatabase({env:t});const r=[`skill_workshop_proposals`,`skill_workshop_proposal_events`,`skill_workshop_proposal_rollbacks`,`skill_workshop_collection_reviews`].some(e=>tableExists(n,e));const i=[];const a=[];const o=/* @__PURE__ */ new Set;const s=[];const c={proposals:i,unfinishedApplies:a,recordedIds:o,failures:s,hasTables:r};if(!tableExists(n,`skill_workshop_proposals`))return c;const l=n.prepare(`SELECT proposal_id, record_json, owner_agent_id, status FROM skill_workshop_proposals
ORDER BY proposal_id`).all();for(const n of l){const r=String(n.proposal_id);o.add(r);if(!EXPORTED_STATUSES.has(String(n.status)))continue;try{const a=JSON.parse(String(n.record_json));const o=typeof n.owner_agent_id===`string`?normalizeAgentId(n.owner_agent_id):void 0;const s=o!==void 0?listAgentIds(e).includes(o)?o:void 0:isRecord(a)?inferOwnerAgentId(a,e,t):void 0;i.push(parseRetiredProposal(r,a,s))}catch(e){s.push(`Could not read Skill Workshop proposal ${r}: ${String(e)}`)}}const u=tableExists(n,`skill_workshop_proposal_rollbacks`)?n.prepare(`SELECT r.proposal_id, r.target_skill_file, r.previous_content, r.support_files_json,
p.record_json
FROM skill_workshop_proposal_rollbacks r
JOIN skill_workshop_proposals p USING (proposal_id)
WHERE p.status != 'applied'
ORDER BY r.proposal_id`).all():[];for(const e of u){const t=String(e.proposal_id);try{a.push(parseUnfinishedApply(t,JSON.parse(String(e.record_json)),{targetSkillFile:e.target_skill_file,previousContent:e.previous_content,supportFiles:typeof e.support_files_json===`string`?JSON.parse(e.support_files_json):[]}))}catch(e){s.push(`Could not read the unfinished apply of Skill Workshop proposal ${t}: ${String(e)}`)}}return c}function inferOwnerAgentId(e,t,n){const r=listAgentIds(t);const i=r.length===1?r[0]:void 0;const a=isRecord(e.origin)?e.origin:{};const o=typeof a.agentId===`string`&&a.agentId.trim()||(typeof a.sessionKey===`string`?parseAgentSessionKey(a.sessionKey)?.agentId:void 0);if(o){const e=normalizeAgentId(o);return r.includes(e)?e:void 0}const s=isRecord(e.target)?e.target:{};if(typeof s.skillDir!==`string`)return i;const c=resolveCanonicalWorkspacePath(path.resolve(s.skillDir));const l=r.flatMap(e=>{const r=resolveCanonicalWorkspacePath(resolveAgentWorkspaceDir(t,e,n));return[path.join(r,`skills`),path.join(r,`.agents`,`skills`),resolveCanonicalWorkspacePath(resolveWorkshopSkillsDir(t,e,n))].filter(e=>isPathInside(e,c)).map(t=>({agentId:e,skillsRoot:t}))});const u=Math.max(...l.map(({skillsRoot:e})=>e.length));const d=new Set(l.filter(({skillsRoot:e})=>e.length===u).map(({agentId:e})=>e));return d.size===1?[...d][0]:d.size===0?i:void 0}async function appendLegacyJsonProposals(e){const{proposals:t,unfinishedApplies:n,failures:r,recordedIds:i}=e.inventory;const a=await root(e.stateDir);const o={hardlinks:`reject`,symlinks:`reject`};for(const s of await a.list(LEGACY_PROPOSALS_DIR,{withFileTypes:true})){if(!s.isDirectory||!PROPOSAL_ID_PATTERN.test(s.name)||i.has(s.name))continue;const c=path.join(e.stateDir,LEGACY_PROPOSALS_DIR,s.name);try{const r=await a.read(`${LEGACY_PROPOSALS_DIR}/${s.name}/proposal.json`,{...o,maxBytes:MAX_EXPORT_FILE_BYTES});const i=JSON.parse(decodeUtf8Input(r.buffer,`Skill Workshop proposal ${s.name}`));if(!isRecord(i)||typeof i.status!==`string`)throw new Error(`proposal record has no status`);if(i.status!==`applied`){const e=await a.read(`${LEGACY_PROPOSALS_DIR}/${s.name}/rollback.json`,{...o,maxBytes:MAX_ROLLBACK_BYTES}).catch(e=>{if(isMissingPathError(e))return;throw e});if(e){const t=JSON.parse(decodeUtf8Input(e.buffer,`Skill Workshop rollback ${s.name}`));if(!isRecord(t))throw new Error(`rollback is not an object`);n.push(parseUnfinishedApply(s.name,i,t))}}if(!EXPORTED_STATUSES.has(i.status))continue;t.push(parseRetiredProposal(s.name,i,inferOwnerAgentId(i,e.config,e.env)))}catch(e){r.push(isMissingPathError(e)?`Skill Workshop proposal ${s.name} has no record; kept ${c}. Copy anything worth keeping, delete that directory, then rerun openclaw doctor --fix.`:`Could not read Skill Workshop proposal ${s.name}: ${String(e)}`)}}}async function undoUnfinishedApply(e){const t=path.dirname(e.skillFile);const n=await Promise.all(e.supportFiles.map(async e=>({...e,current:await readWorkspaceSupportFile({skillDir:t,relativePath:e.path})})));if(await readWorkspaceSkillFile(e.skillFile)!==e.previousContent){if(n.every(({current:e,proposedContentHash:t})=>e!==null&&sha256Hex(e)===t))return false;throw new Error(`SKILL.md is past its pre-apply content but its support files are not`)}if(n.every(({current:e,previousContent:t})=>e===t))return false;const r=await prepareWorkspaceSkillRestoration({skillsRoot:path.dirname(t),skillDir:t,skillFile:e.skillFile,previousContent:e.previousContent,proposedContentHash:``,supportFiles:e.supportFiles,mode:`update`});await restoreWorkspaceSkillMutation(r);if(e.previousContent===null){if((await listDirectoryTreeStrict(t)).every(({dirent:e})=>e.isDirectory()))await fs$1.rm(t,{recursive:true})}return true}async function exportProposal(e,t,n){const r=path.join(n,e.id);if(await pathExists(r))return`existing`;const i=path.join(t,LEGACY_PROPOSALS_DIR,e.id,path.posix.dirname(e.draftFile));const a={hardlinks:`reject`,maxBytes:MAX_EXPORT_FILE_BYTES,symlinks:`reject`};let o;try{const t=await root(i);o=[[`SKILL.md`,(await t.read(`PROPOSAL.md`,a)).buffer]];for(const n of e.supportFiles)o.push([n,(await t.read(n,a)).buffer])}catch(e){if(isMissingPathError(e)&&!await pathExists(path.join(i,`PROPOSAL.md`)))return`missing-draft`;throw e}const s=path.join(n,`.${e.id}.partial`);await fs$1.rm(s,{recursive:true,force:true});for(const[e,t]of o){const n=path.join(s,...e.split(`/`));await fs$1.mkdir(path.dirname(n),{recursive:true});await fs$1.writeFile(n,t,{flag:`wx`})}await fs$1.rename(s,r);return`exported`}async function moveEarlierExports(e,t,n){const r=[];const i=[];for(const a of listAgentIds(e)){const o=path.join(resolveWorkshopSkillsDir(e,a,t),EARLIER_EXPORT_DIR);if(isUpdateRehearsalReadOnlyPath(o,t))continue;let s;try{s=await fs$1.readdir(o)}catch(e){if(isMissingPathError(e))continue;throw e}const c=resolveWorkshopDraftsDir(e,a,t);await fs$1.mkdir(c,{recursive:true});let l=0;for(const e of s.filter(e=>!e.startsWith(`.`))){n();if(await pathExists(path.join(c,e))){i.push(`Kept Skill Workshop proposal export ${path.join(o,e)}: a draft with the same id already exists in ${c}. Compare the two, keep the one you want in ${c}, and delete the other.`);continue}await fs$1.rename(path.join(o,e),path.join(c,e));l+=1}await fs$1.rmdir(o).catch(()=>void 0);if(l>0)r.push(`Moved ${l} exported Skill Workshop proposal draft${l===1?``:`s`} from ${o} to ${c}; review them with /learn drafts.`)}return{changes:r,warnings:i}}async function retireProposals(e){const{config:t,env:n,assertCurrent:r}=e;const i=resolveStateDir(n);const a=await pathExists(path.join(i,LEGACY_PROPOSALS_DIR));const o=readDatabaseProposals(t,n);const s=await moveEarlierExports(t,n,r);const c=s.changes;const withEarlierWarnings=e=>{const t=[...e,...s.warnings];return{changes:c,warnings:t,...t.length>0?{warningDisposition:`recoverable`}:{}}};if(!o.hasTables&&!a)return withEarlierWarnings([]);if(a)await appendLegacyJsonProposals({stateDir:i,inventory:o,config:t,env:n});const l=o.failures;let u=l.length>0;const migrationResult=()=>withEarlierWarnings(l);for(const e of o.unfinishedApplies){r();const t=path.dirname(e.skillFile);if(isUpdateRehearsalReadOnlyPath(t,n)){u=true;continue}try{if(await undoUnfinishedApply(e))c.push(`Restored ${t} from the unfinished apply of Skill Workshop proposal ${e.proposalId}.`)}catch(n){u=true;const r=n instanceof AggregateError?n.errors:[n];l.push(`Could not undo the unfinished apply of Skill Workshop proposal ${e.proposalId} in ${t}: ${r.map(String).join(`; `)}. Its proposal tables and files are kept with the recorded pre-apply contents; restore those files by hand, then rerun openclaw doctor --fix.`)}}const d=/* @__PURE__ */ new Set;const f=/* @__PURE__ */ new Map;for(const e of o.proposals){r();const a=path.join(i,LEGACY_PROPOSALS_DIR,e.id);if(!await pathExists(a)){l.push(`Skill Workshop proposal ${e.id} has no draft left to export; retired its record.`);d.add(e.id);continue}if(!e.ownerAgentId){u=true;l.push(`No configured agent owns Skill Workshop proposal ${e.id}; kept ${a}. To keep it, add its agent back to your config and rerun openclaw doctor --fix, or have an agent save that whole directory (draft and support files) with /learn and then delete the directory; otherwise delete the directory and rerun openclaw doctor --fix.`);continue}const o=resolveWorkshopDraftsDir(t,e.ownerAgentId,n);if(isUpdateRehearsalReadOnlyPath(o,n)){u=true;continue}try{await fs$1.mkdir(o,{recursive:true});const t=await exportProposal(e,i,o);if(t===`missing-draft`){u=true;l.push(`Skill Workshop proposal ${e.id} has no draft; kept ${a}. Copy anything worth keeping, delete that directory, then rerun openclaw doctor --fix.`);continue}if(t===`exported`)f.set(o,(f.get(o)??0)+1);d.add(e.id)}catch(t){u=true;l.push(`Could not export Skill Workshop proposal ${e.id} to ${o}: ${String(t)}. Its proposal tables and files are kept; rerun openclaw doctor --fix after fixing the cause.`)}}for(const[e,t]of f)c.push(`Exported ${t} pending Skill Workshop proposal draft${t===1?``:`s`} to ${e}${path.sep}; review them with /learn drafts.`);if(u)return migrationResult();r();const p=runOpenClawStateWriteTransaction(({db:e})=>{if(isPostgresSqlConnection(e))requireNativeDatabaseFile(`postgres`,`repair`);r();if((tableExists(e,`skill_workshop_proposals`)?e.prepare(`SELECT proposal_id FROM skill_workshop_proposals WHERE status IN ('pending', 'quarantined')`).all():[]).some(e=>!d.has(String(e.proposal_id))))return;if(a){rmSync(path.join(i,LEGACY_PROPOSALS_DIR),{recursive:true,force:true});rmSync(path.join(i,LEGACY_PROPOSALS_MANIFEST),{force:true})}return dropRetiredSkillWorkshopProposalTables(e)},{env:n},{operationLabel:`doctor.skill-workshop.retire-proposals`});if(p===void 0){l.push(`Skill Workshop proposals changed during export; rerun openclaw doctor --fix to finish retiring the proposal tables.`);return migrationResult()}if(p)c.push(`Retired the Skill Workshop proposal tables.`);if(a)c.push(`Removed retired Skill Workshop proposal files from ${path.join(i,LEGACY_PROPOSALS_DIR)}.`);return migrationResult()}async function retireSkillWorkshopProposals(e){const t=e.env??process.env;const n=getOpenClawDatabaseMaintenanceScope();if(n?.ownsSchemaMaintenance)return await n.run(()=>retireProposals({config:e.config,env:t,assertCurrent:()=>n.assertOwnerCurrent()}));const r=await acquireGatewayLock({env:t,role:`sqlite-maintenance`,allowInTests:true});if(!r)throw new Error(`Skill Workshop proposal retirement requires exclusive state ownership`);try{return await r.run(()=>retireProposals({config:e.config,env:t,assertCurrent:()=>r.assertCurrent()}))}finally{await r.release()}}export{retireSkillWorkshopProposals};