openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
22 lines • 51.9 kB
JavaScript
import{l as normalizeOptionalString}from"./string-coerce-CpTFcSwY.mjs";import{D as parseStrictPositiveInteger,V as timestampMsToIsoString}from"./number-coercion-B3CfI447.mjs";import{a as extractErrorCode}from"./error-coercion-DlKnt6w-.mjs";import{l as isRecord,r as asNullableRecord}from"./record-coerce-BTbqdJ3-.mjs";import{b as uniqueStrings,f as normalizeStringEntries,l as normalizeSingleOrTrimmedStringList}from"./string-normalization-D_oBUpO3.mjs";import{r as truncateUtf16Safe}from"./utf16-slice-DA3Mllbx.mjs";import{o as getAsyncWorkSignal}from"./async-work-scope-DBcxYU4O.mjs";import{r as isPathInside}from"./path-guards-DGttsOJI.mjs";import{n as sanitizeTerminalText,r as terminalText}from"./safe-text-B_QTgn0s.mjs";import{m as readRegularFile,t as FsSafeError,w as statRegularFileSync,x as root}from"./fs-safe-Bxzu1j4h.mjs";import{_ as resolveDefaultAgentId}from"./agent-scope-config-CG9CFpGX.mjs";import{t as fromMarkdown}from"./lib-vtjvZm5r.mjs";import"./string-coerce-runtime-BYDH9Quw.mjs";import{n as callGatewayFromCli}from"./gateway-rpc-17pTfL8i.mjs";import"./file-access-runtime-Jlxwf1va.mjs";import"./security-runtime-Y28JTB1K.mjs";import"./text-utility-runtime-CDtGqkrl.mjs";import"./number-runtime-G0nhUVZu.mjs";import"./concurrency-runtime-A2TPGCdf.mjs";import{S as forEachMarkdownCodeRange,_ as slugifyWikiSegment,a as decodeWikiPageUtf8,b as WIKI_RELATED_END_MARKER,d as parseWikiMarkdown,f as preserveHumanNotesBlock,i as createWikiPageFilename,m as renderWikiMarkdown,n as HUMAN_START_MARKER,s as extractHumanNotesBlock,t as HUMAN_END_MARKER,w as walkMemoryWikiDirectory,x as WIKI_RELATED_START_MARKER}from"./markdown-CHgmVGaN.mjs";import{a as WIKI_SEARCH_MODES}from"./query-pages-YWEum8C0.mjs";import"./terminal-safe-text-Crgjdu4T.mjs";import"./gateway-runtime-CCd3DVdi.mjs";import"./memory-host-core-C8_amU_Q.mjs";import{n as withTrailingNewline,t as replaceManagedMarkdownBlock}from"./memory-host-markdown-DRjoaX2j.mjs";import{C as getMemoryWikiPage,D as withMemoryWikiVaultMutation,E as resolveMemoryWikiTimestamp,O as appendMemoryWikiLog,S as writeGuardedVaultPage,T as initializeMemoryWikiVault,a as renderMemoryWikiStatus,b as readExistingWikiPageUtf8,c as syncMemoryWikiImportedSources,d as assertOfficialObsidianCliSupported,f as probeObsidianCli,g as applyMemoryWikiMutation,h as ingestMemoryWikiSource,i as renderMemoryWikiDoctor,m as lintMemoryWikiVault,n as renderWikiSearchResults,o as resolveMemoryWikiStatus,p as runObsidianAction,r as buildMemoryWikiDoctorReport,t as renderWikiMutationSummary,u as OBSIDIAN_ACTIONS,v as compileMemoryWikiVault,w as searchMemoryWiki,x as readWikiPageStat,y as readExistingWikiPage}from"./presentation-DJR9pH8j.mjs";import{i as resolveMemoryWikiAgentConfig,n as WIKI_SEARCH_BACKENDS,r as WIKI_SEARCH_CORPORA}from"./config-CMqi2rIe.mjs";import{a as resolveMemoryWikiImportRunsDir,i as getMemoryWikiImportRunStateStore,t as MEMORY_WIKI_IMPORT_RUN_STATE_MAX_ENTRIES}from"./import-runs-state-EOrPpkgw.mjs";import path from"node:path";import{createHash,randomUUID}from"node:crypto";import fs from"node:fs/promises";import{isUtf8}from"node:buffer";
//!extensions/memory-wiki/src/chatgpt-import-recovery.ts
function recoverySlotPrefix(e){return`${e.kind}-${e.index}-${createHash(`sha256`).update(e.entry.path).digest(`hex`)}-`}function resolveContainedImportPath(e,t,n){if(!t||path.isAbsolute(t)||path.win32.isAbsolute(t))throw new Error(`${n} must be a relative path: ${t}`);const r=path.resolve(e);const i=path.resolve(r,t);if(!isPathInside(r,i))throw new Error(`${n} must stay inside ${r}: ${t}`);return i}function isFsSafeErrorCode(e,t){return e instanceof FsSafeError&&e.code===t}async function reserveRecoverySlot(e,t){await e.mkdir(`recovered`);const n=path.posix.join(`recovered`,`${recoverySlotPrefix(t)}${randomUUID()}`);await e.mkdir(n);return{slotRelativePath:n,contentRelativePath:path.posix.join(n,`content`)}}async function removeEmptyRecoverySlot(e,t){try{if((await e.list(t)).length>0)return;await e.remove(t)}catch(e){if(isFsSafeErrorCode(e,`not-found`))return;throw e}}async function moveTargetToRecovery(e){const t=resolveContainedImportPath(e.vaultRoot.rootReal,e.ref.entry.path,`Memory Wiki import page path`);for(;;){const n=await reserveRecoverySlot(e.runRoot,e.ref);const r=path.posix.join(e.runRelativePath,n.contentRelativePath);try{await e.vaultRoot.move(e.ref.entry.path,r,{assertBeforeMutation:()=>{let e;try{e=statRegularFileSync(t)}catch(e){if(extractErrorCode(e))throw e;throw new FsSafeError(`invalid-path`,`Memory Wiki rollback requires a regular file`,{cause:e})}if(e.missing)throw new FsSafeError(`not-found`,`Memory Wiki rollback target no longer exists`)}});return{ref:e.ref,...n}}catch(t){await removeEmptyRecoverySlot(e.runRoot,n.slotRelativePath);if(isFsSafeErrorCode(t,`not-found`))return null;if(isFsSafeErrorCode(t,`already-exists`))continue;throw t}}}
//!extensions/memory-wiki/src/chatgpt-import.ts
const CHATGPT_PREFERENCE_SIGNAL_RE=/\b(prefer|prefers|preference|want|wants|need|needs|avoid|avoids|hate|hates|love|loves|default to|should default to|always use|don't want|does not want|likes|dislikes)\b/i;const MAX_ROLLBACK_RECREATE_ATTEMPTS=32;const CHATGPT_RISK_RULES=[{label:`relationships`,pattern:/\b(relationship|dating|breakup|jealous|sex|intimacy|partner|apology|trust|boyfriend|girlfriend|husband|wife)\b/i},{label:`health`,pattern:/\b(supplement|medication|diagnosis|symptom|therapy|depression|anxiety|mri|migraine|injury|pain|cortisol|sleep)\b/i},{label:`legal_tax`,pattern:/\b(contract|tax|legal|law|lawsuit|visa|immigration|license|insurance|claim|non-residence|residency)\b/i},{label:`finance`,pattern:/\b(investment|invest|portfolio|dividend|yield|coupon|valuation|mortgage|loan|crypto|covered call|call option|put option)\b/i},{label:`drugs`,pattern:/\b(vape|weed|cannabis|nicotine|opioid|ketamine)\b/i}];function normalizeWhitespace(e){return e.trim().replace(/\s+/g,` `)}async function loadConversations(e){const t=path.resolve(e);const n=(await fs.stat(t)).isDirectory()?path.join(t,`conversations.json`):t;const{buffer:r}=await readRegularFile({filePath:await fs.realpath(n)});if(!isUtf8(r))throw new Error(`ChatGPT conversations export must be valid UTF-8: ${n}. Download a fresh ChatGPT export and retry the import.`);const i=JSON.parse(r.toString(`utf8`));const a=Array.isArray(i)?i:Object.values(asNullableRecord(i)??{}).find(Array.isArray);if(!a)throw new Error(`Unrecognized ChatGPT conversations export format: ${n}`);return{exportPath:t,conversationsPath:n,conversations:a.filter(isRecord)}}function isoFromUnix(e){if(typeof e!==`number`&&typeof e!==`string`)return;const t=Number(e);if(!Number.isFinite(t))return;return timestampMsToIsoString(t*1e3)}function cleanMessageText(e){const t=e.trim();if(t.startsWith(`{`)){let e;try{e=asNullableRecord(JSON.parse(t))}catch{return t}if(e?.content_type===`text`&&typeof e.text===`string`)return e.text.trim();if(e?.content_type===`image_asset_pointer`)return``}return t}function extractMessageText(e){const t=asNullableRecord(e.content);if(t){const e=t.parts;if(Array.isArray(e))return e.map(e=>{if(typeof e===`string`)return cleanMessageText(e);const t=asNullableRecord(e)?.text;return typeof t===`string`?t.trim():``}).filter(Boolean).join(`
`).trim();if(typeof t.text===`string`)return cleanMessageText(t.text)}return typeof e.text===`string`?cleanMessageText(e.text):``}function activeBranchMessages(e){const t=asNullableRecord(e.mapping);if(!t)return[];let n=typeof e.current_node===`string`?e.current_node:void 0;const r=/* @__PURE__ */ new Set;const i=[];while(n&&!r.has(n)){r.add(n);const e=asNullableRecord(t[n]);if(!e)break;const a=asNullableRecord(e.message);if(a){const e=asNullableRecord(a.author);const t=typeof e?.role===`string`?e.role:`unknown`;const n=extractMessageText(a);if(n)i.push({role:t,text:n})}n=typeof e.parent===`string`?e.parent:void 0}return i.toReversed()}function inferRisk(e,t){const n=`${e}\n${t}`.toLowerCase();const r=CHATGPT_RISK_RULES.filter(e=>e.pattern.test(n)).map(e=>e.label);if(r.length>0)return{level:`high`,reasons:uniqueStrings(r)};if(/\b(career|job|salary|interview|offer|resume|cover letter)\b/i.test(n))return{level:`medium`,reasons:[`work_career`]};return{level:`low`,reasons:[]}}function inferLabels(e,t){const n=`${e}\n${t}`.toLowerCase();const r=/* @__PURE__ */ new Set([`domain/personal`]);const addAreaTopic=(e,t=e)=>{r.add(`area/${e}`);r.add(`topic/${t}`)};if(/\b(translate|translation|traduc\w*|traducc\w*|traduç\w*|traducci[oó]n|traduccio|traducció|traduzione)\b/i.test(n))r.add(`topic/translation`);for(const[e,t]of[[`language-learning`,/\b(anki|flashcards?|grammar|conjugat\w*|declension|pronunciation|vocab(?:ular(?:y|io))?|lesson|tutor|teacher|jlpt|kanji|hiragana|katakana|study|learn|practice)\b/i],[`travel`,/\b(hike|trail|hotel|flight|trip|travel|airport|itinerary|booking|airbnb|train|stay)\b/i],[`cooking`,/\b(recipe|cook|cooking|bread|sourdough|pizza|espresso|coffee|mousse|cast iron|meatballs?)\b/i],[`gardening`,/\b(garden|orchard|plant|soil|compost|agroforestry|permaculture|mulch|beds?|irrigation|seeds?)\b/i],[`relationships`,/\b(dating|relationship|partner|jealous|breakup|trust)\b/i],[`finance`,/\b(investment|invest|portfolio|dividend|yield|coupon|valuation|return|mortgage|loan|kraken|crypto|covered call|call option|put option|option chain|bond|stocks?)\b/i],[`legal-tax`,/\b(contract|mou|tax|impuesto|legal|law|lawsuit|visa|immigration|license|licencia|dispute|claim|insurance|non-residence|residency)\b/i],[`health`,/\b(supplement|medication|diagnos(?:is|e)|symptom|therapy|depress(?:ion|ed)|anxiet(?:y|ies)|mri|migraine|injur(?:y|ies)|pain|cortisol|sleep|dentist|dermatolog(?:ist|y))\b/i],[`life-admin`,/\b(book (an )?appointment|rebook|open (a )?new account|driving test|exam|gestor(?:a)?|itv)\b/i]])if(t.test(n))addAreaTopic(e);if(/\b(frc|robot|robotics|wpilib|limelight|chiefdelphi)\b/i.test(n))addAreaTopic(`work`,`robotics`);else if(/\b(docker|git|python|node|npm|pip|sql|postgres|api|bug|stack trace|permission denied)\b/i.test(n))addAreaTopic(`work`,`software`);else if(/\b(job|interview|cover letter|resume|cv)\b/i.test(n))addAreaTopic(`work`,`career`);if(/\b(wifi|wi-fi|starlink|router|mesh|network|orbi|milesight|coverage)\b/i.test(n))addAreaTopic(`home`,`home-infrastructure`);if(/\b(p38|range rover|porsche|bmw|bobcat|excavator|auger|trailer|chainsaw|stihl)\b/i.test(n))addAreaTopic(`vehicles`);if(![...r].some(e=>e.startsWith(`area/`)))r.add(`area/other`);return[...r]}function collectPreferenceSignals(e){const t=[];const n=/* @__PURE__ */ new Set;for(const r of e.slice(0,25))for(const e of r.split(/\r?\n/)){const r=normalizeWhitespace(e);if(!r||!CHATGPT_PREFERENCE_SIGNAL_RE.test(r))continue;const i=r.toLowerCase();if(n.has(i))continue;n.add(i);t.push(r);if(t.length>=10)return t}return t}function buildTranscript(e){if(e.length===0)return`_No active-branch transcript could be reconstructed._`;return e.flatMap(e=>[`### ${e.role[0]?.toUpperCase()??`U`}${e.role.slice(1)}`,``,e.text,``]).join(`
`).trim()}function resolveConversationPagePath(e){const t=e.conversationId.replace(/[^a-zA-Z0-9]/g,``).toLowerCase();const n=`source.chatgpt.${t||createHash(`sha1`).update(e.conversationId).digest(`hex`).slice(0,12)}`;const r=e.createdAt?.slice(0,10)??`undated`;return{pageId:n,pagePath:path.join(`sources`,`chatgpt-${r}-${t||`export`}.md`).replace(/\\/g,`/`)}}function toConversationRecord(e,t){const n=typeof e.conversation_id===`string`?e.conversation_id.trim():``;if(!n)return null;const r=typeof e.title===`string`&&e.title.trim()?e.title.trim():`Untitled conversation`;const i=activeBranchMessages(e);const a=i.filter(e=>e.role===`user`).map(e=>e.text);const o=i.filter(e=>e.role===`assistant`);const s=a.slice(0,6).join(`
`);const c=isoFromUnix(e.create_time);const l=inferRisk(r,s);const u=inferLabels(r,s);const{pageId:d,pagePath:f}=resolveConversationPagePath({conversationId:n,createdAt:c});return{conversationId:n,title:r,createdAt:c,updatedAt:isoFromUnix(e.update_time)??c,sourcePath:t,pageId:d,pagePath:f,labels:u,risk:l,userMessageCount:a.length,assistantMessageCount:o.length,preferenceSignals:l.level===`low`?collectPreferenceSignals(a):[],firstUserLine:a[0]?.split(/\r?\n/)[0]?.trim(),lastUserLine:a.at(-1)?.split(/\r?\n/)[0]?.trim(),transcript:i}}function renderConversationPage(e){const t=e.risk.level===`low`?[`- User messages: ${e.userMessageCount}`,`- Assistant messages: ${e.assistantMessageCount}`,...e.firstUserLine?[`- First user line: ${e.firstUserLine}`]:[],...e.lastUserLine?[`- Last user line: ${e.lastUserLine}`]:[],...e.preferenceSignals.length>0?[`- Preference signals:`,...e.preferenceSignals.map(e=>` - ${e}`)]:[`- Preference signals: none detected`]]:[`- Auto digest withheld from durable-candidate generation until reviewed.`,`- Risk reasons: ${e.risk.reasons.length>0?e.risk.reasons.join(`, `):`none recorded`}`];return renderWikiMarkdown({frontmatter:{pageType:`source`,id:e.pageId,title:`ChatGPT Export: ${e.title}`,sourceType:`chatgpt-export`,sourceSystem:`chatgpt`,sourcePath:e.sourcePath,conversationId:e.conversationId,riskLevel:e.risk.level,riskReasons:e.risk.reasons,labels:e.labels,status:`draft`,...e.createdAt?{createdAt:e.createdAt}:{},...e.updatedAt?{updatedAt:e.updatedAt}:{}},body:[`# ChatGPT Export: ${e.title}`,``,`## Source`,`- Conversation id: \`${e.conversationId}\``,`- Export file: \`${e.sourcePath}\``,...e.createdAt?[`- Created: ${e.createdAt}`]:[],...e.updatedAt?[`- Updated: ${e.updatedAt}`]:[],``,`## Auto Triage`,`- Risk level: \`${e.risk.level}\``,`- Labels: ${e.labels.join(`, `)}`,`- Active-branch messages: ${e.transcript.length}`,``,`## Auto Digest`,...t,``,`## Active Branch Transcript`,buildTranscript(e.transcript),``,`## Notes`,HUMAN_START_MARKER,HUMAN_END_MARKER,``].join(`
`)})}const RELATED_BLOCK_BODY_PATTERN=new RegExp(`${WIKI_RELATED_START_MARKER}\\n?([\\s\\S]*?)\\n?${WIKI_RELATED_END_MARKER}`);function preserveExistingPageBlocks(e,t){if(!t.trim())return withTrailingNewline(e);const n=parseWikiMarkdown(t);const r=parseWikiMarkdown(e);let i=preserveHumanNotesBlock(r.body,n.body);const a=n.body.match(RELATED_BLOCK_BODY_PATTERN)?.[1]?.trim();if(a)i=replaceManagedMarkdownBlock({original:i,heading:`## Related`,startMarker:WIKI_RELATED_START_MARKER,endMarker:WIKI_RELATED_END_MARKER,body:a});return withTrailingNewline(renderWikiMarkdown({frontmatter:r.frontmatter,body:i}))}function buildRunId(e,t){const n=`${e}:${t}:${Math.random()}`;return`chatgpt-${createHash(`sha1`).update(n).digest(`hex`).slice(0,12)}`}function normalizeConversationActions(e,t){return e.map(e=>({conversationId:e.conversationId,title:e.title,pagePath:e.pagePath,operation:t.get(e.pagePath)??`skip`,riskLevel:e.risk.level,labels:e.labels,userMessageCount:e.userMessageCount,assistantMessageCount:e.assistantMessageCount,preferenceSignals:e.preferenceSignals}))}const MACHINE_RELATED_BLOCK_PATTERN=new RegExp(`(?:^|\\n\\n)## Related\\n${WIKI_RELATED_START_MARKER}\\n[\\s\\S]*?\\n${WIKI_RELATED_END_MARKER}`,`g`);function hashChatGptImportContent(e){const t=e.replace(MACHINE_RELATED_BLOCK_PATTERN,``);return createHash(`sha256`).update(t,`utf8`).digest(`hex`)}async function writeTrackedImportPage(e){const t=path.join(e.vaultRoot,e.relativePath);const n=hashChatGptImportContent(e.rendered);await fs.mkdir(path.dirname(t),{recursive:true});if(!e.existing){await fs.writeFile(t,e.rendered,`utf8`);e.record.createdPaths.push({path:e.relativePath,contentHash:n});return}const r=createHash(`sha1`).update(e.relativePath).digest(`hex`).slice(0,12);const i=path.join(`snapshots`,`${r}.md`).replace(/\\/g,`/`);const a=path.join(e.runDir,i);await fs.mkdir(path.dirname(a),{recursive:true});await fs.writeFile(a,e.existing,`utf8`);await fs.writeFile(t,e.rendered,`utf8`);e.record.updatedPaths.push({path:e.relativePath,snapshotPath:i,contentHash:n})}async function importChatGptConversations(e){return await withMemoryWikiVaultMutation(e.config.vault.path,async()=>{const{exportPath:t,conversationsPath:n,conversations:r}=await loadConversations(e.exportPath);await initializeMemoryWikiVault(e.config,{nowMs:e.nowMs});const i=r.map(e=>toConversationRecord(e,n)).filter(e=>e!==null).toSorted((e,t)=>e.pagePath.localeCompare(t.pagePath));const a=/* @__PURE__ */ new Map;let o;const s=resolveMemoryWikiTimestamp(e.nowMs);const c=[];for(const t of i){const n=renderConversationPage(t);const r=path.join(e.config.vault.path,t.pagePath);const i=await readExistingWikiPage(async()=>decodeWikiPageUtf8((await readRegularFile({filePath:await fs.realpath(r)})).buffer,r),e=>asNullableRecord(e)?.code===`ENOENT`);const o=preserveExistingPageBlocks(n,i);const s=i===o?`skip`:i?`update`:`create`;a.set(t.pagePath,s);c.push({relativePath:t.pagePath,existing:i,rendered:o,operation:s})}const l=c.filter(e=>e.operation===`create`).length;const u=c.filter(e=>e.operation===`update`).length;const d=c.length-l-u;const f=l+u;let p=[];if(!e.dryRun&&f>0){const r=1+f;const a=await getMemoryWikiImportRunStateStore().rowCount()+r;if(a>2e4)throw new Error(`Memory Wiki ChatGPT import exceeds SQLite import-run entry limit (${a}/${MEMORY_WIKI_IMPORT_RUN_STATE_MAX_ENTRIES})`);o=buildRunId(t,s);const m=path.join(resolveMemoryWikiImportRunsDir(e.config.vault.path),o);const h={version:1,runId:o,importType:`chatgpt`,exportPath:t,sourcePath:n,appliedAt:s,conversationCount:i.length,createdCount:l,updatedCount:u,skippedCount:d,createdPaths:[],updatedPaths:[]};for(const t of c){if(t.operation===`skip`)continue;await writeTrackedImportPage({vaultRoot:e.config.vault.path,runDir:m,relativePath:t.relativePath,existing:t.existing,rendered:t.rendered,record:h})}await getMemoryWikiImportRunStateStore().write(e.config.vault.path,h);p=(await compileMemoryWikiVault(e.config).catch(e=>{const t=e instanceof Error?e.message:String(e);throw new Error(`Memory Wiki ChatGPT import run ${h.runId} changed source pages, but vault compilation failed: ${t}. After fixing the compile error, run \`openclaw wiki chatgpt rollback ${h.runId}\` to restore the imported pages.`,{cause:e})})).updatedFiles;await appendMemoryWikiLog(e.config.vault.path,{type:`ingest`,timestamp:s,details:{sourceType:`chatgpt-export`,runId:h.runId,exportPath:t,sourcePath:n,conversationCount:i.length,createdCount:h.createdPaths.length,updatedCount:h.updatedPaths.length,skippedCount:d}})}return{dryRun:Boolean(e.dryRun),exportPath:t,sourcePath:n,conversationCount:i.length,createdCount:l,updatedCount:u,skippedCount:d,actions:normalizeConversationActions(i,a),pagePaths:i.map(e=>e.pagePath),...o?{runId:o}:{},indexUpdatedFiles:p}})}function toVaultRelativePath(e,t){return path.relative(e,t).replace(/\\/g,`/`)}function buildRollbackEntryRefs(e){return[...e.createdPaths.map((e,t)=>({entry:e,kind:`created`,index:t})),...e.updatedPaths.map((e,t)=>({entry:e,kind:`updated`,index:t}))]}function listPreservedPaths(e){return[...e.createdPaths,...e.updatedPaths].flatMap(e=>(e.recoveryPaths??[]).map(t=>({path:e.path,recoveryPath:t})))}async function scanRecoverySlots(e){const t=buildRollbackEntryRefs(e.record);const n=new Map(t.map(e=>[recoverySlotPrefix(e),e]));let r;try{r=await e.runRoot.list(`recovered`,{withFileTypes:true})}catch(e){if(isFsSafeErrorCode(e,`not-found`))return[];throw e}const i=[];for(const e of r){if(!e.isDirectory||e.isSymbolicLink)continue;const t=/^(?:created|updated)-\d+-[a-f0-9]{64}-/.exec(e.name)?.[0];const r=t?n.get(t):void 0;if(!r)continue;const a=path.posix.join(`recovered`,e.name);i.push({ref:r,slotRelativePath:a,contentRelativePath:path.posix.join(a,`content`)})}return i}async function classifyRecoverySlots(e){let t=false;for(const n of e.slots){const{entry:r}=n.ref;const i=toVaultRelativePath(e.vaultRoot,path.join(e.runRoot.rootDir,n.contentRelativePath));if(r.recoveryPaths?.includes(i))continue;let a=null;try{const t=await e.runRoot.stat(n.contentRelativePath);if(t.isFile&&!t.isSymbolicLink)a=hashChatGptImportContent(await e.runRoot.readText(n.contentRelativePath))}catch(t){if(isFsSafeErrorCode(t,`not-found`)){await removeEmptyRecoverySlot(e.runRoot,n.slotRelativePath);continue}throw t}if(r.contentHash&&a===r.contentHash){await e.runRoot.remove(n.contentRelativePath);await removeEmptyRecoverySlot(e.runRoot,n.slotRelativePath);continue}(r.recoveryPaths??=[]).push(i);t=true}return t}async function targetMatchesSnapshot(e,t,n){try{return hashChatGptImportContent(await e.readText(t))===hashChatGptImportContent(n)}catch(e){if(isFsSafeErrorCode(e,`not-found`))return false;throw e}}async function rollbackChatGptImportRun(e){return await withMemoryWikiVaultMutation(e.config.vault.path,async()=>{const t=e.config.vault.path;const n=await getMemoryWikiImportRunStateStore().read(t,e.runId);if(!n)throw new Error(`Memory Wiki import run not found: ${e.runId}`);const r=buildRollbackEntryRefs(n);const i=r.map(({entry:e})=>e.path).toSorted((e,t)=>e.localeCompare(t));if(n.rolledBackAt)return{runId:n.runId,removedCount:0,restoredCount:0,preservedPaths:listPreservedPaths(n),pagePaths:i,indexUpdatedFiles:[],alreadyRolledBack:true};const a=resolveMemoryWikiImportRunsDir(t);const o=resolveContainedImportPath(a,n.runId,`Memory Wiki import run id`);for(const e of r){resolveContainedImportPath(t,e.entry.path,`Memory Wiki import page path`);if(e.entry.snapshotPath)resolveContainedImportPath(o,e.entry.snapshotPath,`Memory Wiki import snapshot path`)}if(!n.rollbackStartedAt){n.rollbackStartedAt=(/* @__PURE__ */ new Date()).toISOString();await getMemoryWikiImportRunStateStore().write(t,n)}if(!n.rollbackTargetsFinalizedAt){await initializeMemoryWikiVault(e.config);const i=await root(t);const a=toVaultRelativePath(t,o);await i.mkdir(a);const s=await root(o);if(await classifyRecoverySlots({vaultRoot:t,runRoot:s,slots:await scanRecoverySlots({runRoot:s,record:n})}))await getMemoryWikiImportRunStateStore().write(t,n);for(const e of r){const{entry:r}=e;if(e.kind===`updated`&&!r.snapshotPath)continue;const o=e.kind===`updated`&&r.snapshotPath?await s.readText(r.snapshotPath):void 0;let c=false;for(let l=0;l<MAX_ROLLBACK_RECREATE_ATTEMPTS;l+=1){if(o!==void 0&&await targetMatchesSnapshot(i,r.path,o)){c=true;break}const l=await moveTargetToRecovery({vaultRoot:i,runRoot:s,runRelativePath:a,ref:e});if(l&&await classifyRecoverySlots({vaultRoot:t,runRoot:s,slots:[l]}))await getMemoryWikiImportRunStateStore().write(t,n);if(o===void 0){if(l)continue;c=true;break}try{await i.create(r.path,o,{encoding:`utf8`,mkdir:true});c=true;break}catch(e){if(!isFsSafeErrorCode(e,`already-exists`))throw e}}if(!c)throw new Error(`Memory Wiki rollback could not ${e.kind===`created`?`remove`:`restore`} ${r.path} after ${MAX_ROLLBACK_RECREATE_ATTEMPTS} concurrent recreations`)}n.rollbackTargetsFinalizedAt=(/* @__PURE__ */ new Date()).toISOString();await getMemoryWikiImportRunStateStore().write(t,n)}const s=await compileMemoryWikiVault(e.config,{sourcePageWrites:`preserve`});n.rolledBackAt=(/* @__PURE__ */ new Date()).toISOString();await getMemoryWikiImportRunStateStore().write(t,n);const c=listPreservedPaths(n);const l=n.createdPaths.length;const u=n.updatedPaths.filter(e=>e.snapshotPath).length;await appendMemoryWikiLog(t,{type:`ingest`,timestamp:n.rolledBackAt,details:{sourceType:`chatgpt-export`,runId:n.runId,rollback:true,removedCount:l,restoredCount:u,preservedCount:c.length}}).catch(()=>void 0);return{runId:n.runId,removedCount:l,restoredCount:u,preservedPaths:c,pagePaths:i,indexUpdatedFiles:s.updatedFiles,alreadyRolledBack:false}})}
//!extensions/memory-wiki/src/okf.ts
const OKF_RESERVED_FILENAMES=/* @__PURE__ */ new Set([`index.md`,`log.md`]);const OKF_RELATED_SECTION_PATTERN=new RegExp(`\\n+## Related\\n${WIKI_RELATED_START_MARKER}[\\s\\S]*?${WIKI_RELATED_END_MARKER}\\n?`,`g`);const OKF_VOLATILE_TIMESTAMP_LINE_PATTERN=/^(?:importedAt|updatedAt): .*\n/gm;const OKF_HASH_CHARS=8;function toPosixPath(e){return e.split(path.sep).join(`/`)}function createOkfBundleKey(e){const t=normalizeOptionalString(e.rootFrontmatter.id)??normalizeOptionalString(e.rootFrontmatter.okf_id);if(t)return slugifyWikiSegment(t);const n=normalizeOptionalString(e.rootFrontmatter.name)??normalizeOptionalString(e.rootFrontmatter.title)??e.bundleName;const r=createHash(`sha1`).update(e.bundlePath).digest(`hex`).slice(0,OKF_HASH_CHARS);return`${slugifyWikiSegment(n)}-${r}`}function createOkfPageIdentity(e,t){const n=slugifyWikiSegment(t.replace(/\//g,`-`));const r=createHash(`sha1`).update(t).digest(`hex`).slice(0,OKF_HASH_CHARS);const i=createWikiPageFilename(`okf-${e}-${n}-${r}`);return{pageId:`concept.${i.replace(/\.md$/i,``)}`,pagePath:`concepts/${i}`}}async function collectOkfMarkdownFiles(e,t){const n=await walkMemoryWikiDirectory(e,``,{entryFilter:e=>e.kind===`directory`&&[`.git`,`node_modules`].includes(path.basename(e.relativePath))?`skip-subtree`:`include`,onDirectoryError:`skip-and-report`});const r=[];for(const e of n){if(e.kind===`directory-error`){t.push({code:`unreadable-entry`,path:toPosixPath(e.relativePath)||`.`,message:e.error instanceof Error?e.error.message:`Unable to read OKF directory.`});continue}if(e.kind===`file`&&e.relativePath.endsWith(`.md`))r.push(toPosixPath(e.relativePath))}return r.toSorted((e,t)=>e.localeCompare(t))}function parseOkfMarkdown(e,t){const n=e.replace(/\r\n/g,`
`);try{return parseWikiMarkdown(n)}catch(e){return{frontmatter:{},body:n,warning:{code:`invalid-concept`,path:t,message:e instanceof Error?e.message:`Unable to parse OKF frontmatter.`}}}}async function readOkfTextFile(e){try{const t=await e.bundleRoot.readBytes(e.relativePath);if(!isUtf8(t))throw new Error(`OKF document must be valid UTF-8. Convert the source to UTF-8 and retry the import.`);return t.toString(`utf8`)}catch(t){e.warnings.push({code:`unreadable-entry`,path:e.relativePath,message:t instanceof FsSafeError&&t.code===`not-file`?`Refusing to import OKF concept through non-regular or hardlinked file.`:t instanceof Error?t.message:`Unable to read OKF concept.`});return null}}function resolveOkfMarkdownTarget(e,t){const n=t.trim();if(!n||n.startsWith(`#`)||/^[a-z][a-z0-9+.-]*:/i.test(n))return null;const r=n.split(`#`)[0]?.split(`?`)[0]?.replace(/\\/g,`/`).trim();const i=safeDecodeOkfLinkPath(r);if(!i||!i.endsWith(`.md`))return null;const a=(i.startsWith(`/`)?path.posix.normalize(i.slice(1)):path.posix.normalize(path.posix.join(path.posix.dirname(e),i))).replace(/\.md$/i,``);return a.startsWith(`../`)?null:a}function safeDecodeOkfLinkPath(e){if(!e)return``;try{return decodeURIComponent(e)}catch{return e}}function rewriteOkfMarkdownLinks(e){const t=/* @__PURE__ */ new Set;if(!e.body.includes(`[`))return{body:e.body,linkedPages:[]};const n=[];fromMarkdown(e.body,{mdastExtensions:[{beforeEnter(e){if(e.type!==`resourceDestinationString`)return;const t=this.stack.at(-1);if(t?.type===`link`||t?.type===`image`)n.push({start:e.start.offset,end:e.end.offset,link:t})}}]});const r=[];let i=0;for(const{start:a,end:o,link:s}of n){const n=resolveOkfMarkdownTarget(e.sourceRelativePath,s.url);const c=n?e.pageByConceptId.get(n):void 0;if(!c)continue;t.add(c);const l=`${path.posix.relative(path.posix.dirname(e.sourcePagePath),c.pagePath)}${s.url.match(/[?#].*$/s)?.[0]??``}`.replace(/[\\()<> &\t\r\n]/g,e=>/\s/u.test(e)?encodeURIComponent(e):`\\${e}`);r.push(e.body.slice(i,a),l);i=o}r.push(e.body.slice(i));return{body:r.join(``),linkedPages:[...t]}}function normalizeOkfRenderedPageForComparison(e){const t=e.replace(OKF_RELATED_SECTION_PATTERN,`
`);const n=t.match(/^---\n([\s\S]*?)\n---\n?/);if(!n)return t.trimEnd();const r=n[1]?.replace(OKF_VOLATILE_TIMESTAMP_LINE_PATTERN,``)??``;return`---\n${r.endsWith(`
`)?r:`${r}\n`}---\n${t.slice(n[0].length)}`.trimEnd()}function renderOkfBodyWithHumanNotes(e){const t=e.trimEnd();const n=`## Notes\n${HUMAN_START_MARKER}\n${HUMAN_END_MARKER}\n`;const r=t+`
`+n;const i=t.length+2;let a=``;forEachMarkdownCodeRange(r,(e,t)=>{if(e<=i&&i<t){a=/^ {0,3}(`{3,}|~{3,})/u.exec(r.slice(e))?.[1]??``;if(!a)throw new Error(`Close the producer Markdown fence before importing this OKF concept.`)}});return a?t+`
`+a+`
`+n:r}async function writeOkfConceptPage(e){const t=await root(e.vaultRoot);const n=await readWikiPageStat(t,e.pagePath);const r=n?await readExistingWikiPageUtf8(t,e.pagePath,()=>``):``;const i=preserveHumanNotesBlock(e.content,r,{producerMarkdown:true});if(r===i||normalizeOkfRenderedPageForComparison(r)===normalizeOkfRenderedPageForComparison(i))return{changed:false,created:!n};await writeGuardedVaultPage({vault:t,pagePath:e.pagePath,content:i,pageStat:n,pageLabel:`OKF concept page`});return{changed:true,created:!n}}async function removeStaleOkfConceptPages(e){const t=await root(e.vaultRoot);const n=await walkMemoryWikiDirectory(e.vaultRoot,`concepts`,{maxDepth:0,entryFilter:e=>e.kind===`directory`?`skip-subtree`:`include`,onDirectoryError:`skip-and-report`});const r=[];for(const i of n){const n=path.basename(i.relativePath);if(i.kind!==`file`||!n.endsWith(`.md`)||n===`index.md`)continue;const a=`concepts/${n}`;if(e.currentPagePaths.has(a))continue;const o=await readExistingWikiPageUtf8(t,a,()=>``);const s=parseWikiMarkdown(o);if(asNullableRecord(s.frontmatter.okf)?.bundleKey===e.bundleKey&&!extractHumanNotesBlock(o,{producerMarkdown:true})){await t.remove(a);r.push(a)}}return r}function formatOkfImportSummary(e){return terminalText`Imported ${e.importedCount} OKF concept${e.importedCount===1?``:`s`} from ${e.bundlePath} into memory wiki. Updated ${e.updatedCount}; removed ${e.removedCount}; skipped ${e.skippedCount}; refreshed ${e.indexUpdatedFiles.length} index file${e.indexUpdatedFiles.length===1?``:`s`}.`}async function importMemoryWikiOkfBundle(e){await initializeMemoryWikiVault(e.config,{nowMs:e.nowMs});const t=path.resolve(e.bundlePath);if(!(await fs.stat(t)).isDirectory())throw new Error(`wiki okf import expects an unpacked OKF bundle directory.`);const n=await root(t);const r=[];const i=await collectOkfMarkdownFiles(t,r);const a=[];let o;for(const e of i){if(e===`index.md`){const t=await readOkfTextFile({bundleRoot:n,relativePath:e,warnings:r});if(t===null)throw new Error(`Cannot read OKF bundle index.md: ${r.at(-1)?.message}`);o=t}if(OKF_RESERVED_FILENAMES.has(path.posix.basename(e)))continue;const t=await readOkfTextFile({bundleRoot:n,relativePath:e,warnings:r});if(t===null)continue;const i=parseOkfMarkdown(t,e);if(i.warning){r.push(i.warning);continue}const s=normalizeOptionalString(i.frontmatter.type);if(!s){r.push({code:`missing-type`,path:e,message:`OKF concept is missing required non-empty type frontmatter.`});continue}a.push({conceptId:e.replace(/\.md$/i,``),relativePath:e,frontmatter:i.frontmatter,body:i.body,type:s,title:normalizeOptionalString(i.frontmatter.title)??path.posix.basename(e,`.md`).replace(/[-_]+/g,` `).trim()})}const s=resolveMemoryWikiTimestamp(e.nowMs);const c=path.basename(t);const l=parseOkfMarkdown(o??``,`index.md`).frontmatter;const u=normalizeOptionalString(l.okf_version);const d=createOkfBundleKey({rootFrontmatter:l,bundleName:c,bundlePath:t});const f=a.map(e=>Object.assign({},e,createOkfPageIdentity(d,e.conceptId)));const p=new Map(f.map(e=>[e.conceptId,e]));const m=[];let h=0;await fs.mkdir(path.join(e.config.vault.path,`concepts`),{recursive:true});for(const n of f.toSorted((e,t)=>e.conceptId.localeCompare(t.conceptId))){const r=rewriteOkfMarkdownLinks({body:n.body,sourcePagePath:n.pagePath,sourceRelativePath:n.relativePath,pageByConceptId:p});const i=r.linkedPages.map(e=>({targetId:e.pageId,targetPath:e.pagePath,targetTitle:e.title,kind:`okf-link`,evidenceKind:`okf-markdown-link`}));const a=normalizeOptionalString(n.frontmatter.description);const o=normalizeOptionalString(n.frontmatter.resource);const l=normalizeSingleOrTrimmedStringList(n.frontmatter.tags);const f=normalizeOptionalString(n.frontmatter.timestamp);const g={type:n.type,pageType:`concept`,id:n.pageId,title:n.title,sourceType:`okf`,provenanceMode:`okf-import`,sourcePath:path.join(t,n.relativePath),okfConceptId:n.conceptId,okfType:n.type,sourceIds:[`source.okf.${d}`],importedAt:s,updatedAt:f??s,status:`active`,...a?{description:a}:{},...o?{resource:o}:{},...l.length>0?{tags:l}:{},...f?{okfTimestamp:f}:{},...i.length>0?{relationships:i}:{},okf:{...u?{version:u}:{},bundleName:c,bundleKey:d,conceptId:n.conceptId,sourceRelativePath:n.relativePath,frontmatter:n.frontmatter}};const _=await writeOkfConceptPage({vaultRoot:e.config.vault.path,pagePath:n.pagePath,content:renderWikiMarkdown({frontmatter:g,body:renderOkfBodyWithHumanNotes(r.body)})});if(!_.created&&_.changed)h++;m.push(n.pagePath)}const g=r.length===0?await removeStaleOkfConceptPages({vaultRoot:e.config.vault.path,bundleKey:d,currentPagePaths:new Set(m)}):[];await appendMemoryWikiLog(e.config.vault.path,{type:`okf-import`,timestamp:s,details:{bundlePath:t,bundleName:c,importedCount:m.length,updatedCount:h,removedCount:g.length,skippedCount:r.length,pagePaths:m,removedPagePaths:g}});const _=await compileMemoryWikiVault(e.config);return{bundlePath:t,bundleName:c,...u?{okfVersion:u}:{},importedCount:m.length,updatedCount:h,removedCount:g.length,skippedCount:r.length,pagePaths:m,removedPagePaths:g,warnings:r,indexUpdatedFiles:_.updatedFiles}}
//!extensions/memory-wiki/src/cli.ts
const WIKI_GATEWAY_TIMEOUT_MS=`30000`;const GATEWAY_TERMINAL_STRING_MAX_CHARS=2e3;const GATEWAY_RESPONSE_MAX_ARRAY_ITEMS=1e4;const GATEWAY_RESPONSE_MAX_STRING_CHARS=1e4;const GATEWAY_RESPONSE_MAX_CODE_CHARS=256;const ANSI_ESCAPE_SEQUENCE_PATTERN=new RegExp(String.raw`(?:\x1B\[[0-?]*[ -/]*[@-~]|\x1B[@-Z\\-_]|\x9B[0-?]*[ -/]*[@-~])`,`g`);const TERMINAL_CONTROL_CHARACTER_PATTERN=new RegExp(String.raw`[\x00-\x1F\x7F-\x9F]+`,`g`);const UNICODE_FORMAT_CONTROL_PATTERN=/[\u061C\u200B-\u200F\u202A-\u202E\u2060-\u206F\uFEFF]/g;function sanitizeGatewayStringForTerminal(e){const t=(e.length>GATEWAY_TERMINAL_STRING_MAX_CHARS?truncateUtf16Safe(e,GATEWAY_TERMINAL_STRING_MAX_CHARS):e).replace(ANSI_ESCAPE_SEQUENCE_PATTERN,``).replace(TERMINAL_CONTROL_CHARACTER_PATTERN,` `).replace(UNICODE_FORMAT_CONTROL_PATTERN,``);return e.length>GATEWAY_TERMINAL_STRING_MAX_CHARS?`${t}... [truncated]`:t}function escapeGatewayJsonForTerminal(e){return e.replace(UNICODE_FORMAT_CONTROL_PATTERN,e=>{const t=e.codePointAt(0);return typeof t===`number`?`\\u${t.toString(16).padStart(4,`0`)}`:``})}function writeOutput(e){process.stdout.write(e.endsWith(`
`)?e:`${e}\n`)}function shouldRouteBridgeRuntimeThroughGateway(e){return e.vaultMode===`bridge`&&e.bridge.enabled&&e.bridge.readMemoryArtifacts}function isBoundedGatewayString(e,t=GATEWAY_RESPONSE_MAX_STRING_CHARS){return typeof e===`string`&&e.length<=t}function isBoundedGatewayStringArray(e,t=GATEWAY_RESPONSE_MAX_STRING_CHARS){return Array.isArray(e)&&e.length<=GATEWAY_RESPONSE_MAX_ARRAY_ITEMS&&e.every(e=>isBoundedGatewayString(e,t))}function hasNumberFields(e,t){return t.every(t=>typeof e[t]===`number`)}function isWarningList(e){return Array.isArray(e)&&e.length<=GATEWAY_RESPONSE_MAX_ARRAY_ITEMS&&e.every(e=>isRecord(e)&&isBoundedGatewayString(e.code,GATEWAY_RESPONSE_MAX_CODE_CHARS)&&isBoundedGatewayString(e.message))}function isMemoryWikiStatus(e){if(!isRecord(e))return false;const t=e.bridge;const n=e.obsidianCli;const r=e.unsafeLocal;const i=e.pageCounts;const a=e.sourceCounts;return isBoundedGatewayString(e.vaultScope,GATEWAY_RESPONSE_MAX_CODE_CHARS)&&(isBoundedGatewayString(e.agentId,GATEWAY_RESPONSE_MAX_CODE_CHARS)||e.agentId===null)&&isBoundedGatewayString(e.vaultMode,GATEWAY_RESPONSE_MAX_CODE_CHARS)&&isBoundedGatewayString(e.renderMode,GATEWAY_RESPONSE_MAX_CODE_CHARS)&&isBoundedGatewayString(e.vaultPath)&&typeof e.vaultExists===`boolean`&&(typeof e.bridgePublicArtifactCount===`number`||e.bridgePublicArtifactCount===null)&&isRecord(t)&&typeof t.enabled===`boolean`&&isRecord(n)&&typeof n.enabled===`boolean`&&typeof n.requested===`boolean`&&typeof n.available===`boolean`&&(isBoundedGatewayString(n.command)||n.command===null)&&isRecord(r)&&typeof r.allowPrivateMemoryCoreAccess===`boolean`&&typeof r.pathCount===`number`&&isRecord(i)&&hasNumberFields(i,[`source`,`entity`,`concept`,`synthesis`,`report`])&&isRecord(a)&&hasNumberFields(a,[`native`,`bridge`,`bridgeEvents`,`unsafeLocal`,`other`])&&isWarningList(e.warnings)}function isMemoryWikiDoctorReport(e){return isRecord(e)&&typeof e.healthy===`boolean`&&typeof e.warningCount===`number`&&isMemoryWikiStatus(e.status)&&isWarningList(e.fixes)}function isMemoryWikiImportResult(e){return isRecord(e)&&hasNumberFields(e,[`importedCount`,`updatedCount`,`skippedCount`,`removedCount`,`artifactCount`,`workspaces`])&&isBoundedGatewayStringArray(e.pagePaths)&&typeof e.indexesRefreshed===`boolean`&&isBoundedGatewayStringArray(e.indexUpdatedFiles)&&isBoundedGatewayString(e.indexRefreshReason,GATEWAY_RESPONSE_MAX_CODE_CHARS)}async function callWikiGateway(e,t,n,r){const i=await callGatewayFromCli(e,{timeout:WIKI_GATEWAY_TIMEOUT_MS},n?{agentId:n}:void 0,{progress:false,signal:r});r?.throwIfAborted();if(t(i))return i;throw new Error(`Invalid Gateway response for ${e}.`)}function normalizeCliStringList(e){const t=uniqueStrings(normalizeStringEntries(e??[]));return t.length>0?t:void 0}function resolveCliMutationMetadata(e){const t=normalizeCliStringList(e.sourceId);const n=normalizeCliStringList(e.contradiction);const r=normalizeCliStringList(e.question);return{...t?{sourceIds:t}:{},...n?{contradictions:n}:{},...r?{questions:r}:{},...e.status?.trim()?{status:e.status.trim()}:{}}}function collectCliValues(e,t=[]){t.push(e);return t}function parseWikiSearchEnumOption(e,t,n){if(t.includes(e))return e;throw invalidCliArgument(`Invalid ${n}: ${e}. Expected one of: ${t.join(`, `)}`)}async function resolveWikiApplyBody(e){if(e.body?.trim())return e.body;if(e.bodyFile?.trim()){const{buffer:t}=await readRegularFile({filePath:await fs.realpath(e.bodyFile)}).catch(t=>{if(!(t instanceof Error)||`code`in t)throw t;throw new Error(`wiki apply synthesis --body-file could not be read: ${e.bodyFile}. ${t.message}. Supply a regular UTF-8 file (or use --body), then retry.`,{cause:t})});if(!isUtf8(t))throw new Error(`wiki apply synthesis --body-file must be valid UTF-8: ${e.bodyFile}. Save the file as UTF-8, then retry.`);const n=t.toString(`utf8`);if(!n.trim())throw new Error(`wiki apply synthesis --body-file is empty: ${e.bodyFile}. Supply nonempty UTF-8 text (or use --body), then retry.`);return n}throw new Error(`wiki apply synthesis requires --body or --body-file.`)}function formatJsonOrText(e,t,n){return t?JSON.stringify(e,null,2):n(e,sanitizeTerminalText)}function formatGatewayJsonOrText(e,t,n){return t?escapeGatewayJsonForTerminal(JSON.stringify(e,null,2)):sanitizeGatewayStringForTerminal(n(e))}function printWikiResult(e,t,n){writeOutput(formatJsonOrText(e,t,n));return e}function addWikiSearchConfigOptions(e){return e.option(`--backend <backend>`,`Search backend (${WIKI_SEARCH_BACKENDS.join(`, `)})`,e=>parseWikiSearchEnumOption(e,WIKI_SEARCH_BACKENDS,`backend`)).option(`--corpus <corpus>`,`Search corpus (${WIKI_SEARCH_CORPORA.join(`, `)})`,e=>parseWikiSearchEnumOption(e,WIKI_SEARCH_CORPORA,`corpus`))}function invalidCliArgument(e){return Object.assign(new Error(e),{name:`InvalidArgumentError`,code:`commander.invalidArgument`,exitCode:1})}function parseWikiConfidenceOption(e){const t=e.trim();const n=/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/.test(t)?Number(t):NaN;if(!Number.isFinite(n)||n<0||n>1)throw invalidCliArgument(`--confidence must be a number between 0 and 1.`);return n}function parseWikiPositiveIntegerOption(e,t){const n=parseStrictPositiveInteger(e);if(n===void 0)throw invalidCliArgument(`${t} must be a positive integer.`);return n}function addWikiApplyMutationOptions(e){return e.option(`--source-id <id>`,`Source id`,collectCliValues).option(`--contradiction <text>`,`Contradiction note`,collectCliValues).option(`--question <text>`,`Open question`,collectCliValues).option(`--confidence <n>`,`Confidence score between 0 and 1`,parseWikiConfidenceOption).option(`--status <status>`,`Page status`)}async function runWikiStatus(e){const t=shouldRouteBridgeRuntimeThroughGateway(e.config);let n;if(!t){await syncMemoryWikiImportedSources({config:e.config,appConfig:e.appConfig});n=await resolveMemoryWikiStatus(e.config,{appConfig:e.appConfig})}const r=t?formatGatewayJsonOrText:formatJsonOrText;const i=t?getAsyncWorkSignal():void 0;try{if(e.doctor){const t=n?buildMemoryWikiDoctorReport(n):await callWikiGateway(`wiki.doctor`,isMemoryWikiDoctorReport,e.agentId,i);if(!t.healthy)process.exitCode=1;writeOutput(r(t,e.json,renderMemoryWikiDoctor));return}writeOutput(r(n??await callWikiGateway(`wiki.status`,isMemoryWikiStatus,e.agentId,i),e.json,renderMemoryWikiStatus))}catch(e){if(!i?.aborted)throw e}}async function runWikiBridgeImport(e){const render=e=>terminalText`Bridge import synced ${e.artifactCount} artifacts across ${e.workspaces} workspaces (${e.importedCount} new, ${e.updatedCount} updated, ${e.skippedCount} unchanged, ${e.removedCount} removed). Indexes ${e.indexesRefreshed?`refreshed (${e.indexUpdatedFiles.length} files)`:`not refreshed (${e.indexRefreshReason})`}.`;if(shouldRouteBridgeRuntimeThroughGateway(e.config)){const t=await callWikiGateway(`wiki.bridge.import`,isMemoryWikiImportResult,e.agentId);writeOutput(formatGatewayJsonOrText(t,e.json,render));return t}return printWikiResult(await syncMemoryWikiImportedSources({config:e.config,appConfig:e.appConfig}),e.json,render)}function formatChatGptImportSummary(e){if(e.dryRun)return terminalText`ChatGPT import dry run scanned ${e.conversationCount} conversations (${e.createdCount} new, ${e.updatedCount} updated, ${e.skippedCount} unchanged).`;const t=e.runId?terminalText` Run id: ${e.runId}.`:``;return terminalText`ChatGPT import applied ${e.conversationCount} conversations (${e.createdCount} new, ${e.updatedCount} updated, ${e.skippedCount} unchanged). Refreshed ${e.indexUpdatedFiles.length} index file${e.indexUpdatedFiles.length===1?``:`s`}.${t}`}function formatChatGptRollbackSummary(e){const t=e.preservedPaths.length>0?terminalText` Preserved ${e.preservedPaths.length} page${e.preservedPaths.length===1?``:`s`} edited after import: ${e.preservedPaths.map(e=>e.recoveryPath).join(`, `)}.`:``;if(e.alreadyRolledBack)return terminalText`ChatGPT import run ${e.runId} was already rolled back.${t}`;return terminalText`Rolled back ChatGPT import run ${e.runId} (${e.removedCount} removed, ${e.restoredCount} restored).${t} Refreshed ${e.indexUpdatedFiles.length} index file${e.indexUpdatedFiles.length===1?``:`s`}.`}function registerWikiCli(e,t){const n=t.resolveConfig??((e,n)=>resolveMemoryWikiAgentConfig({config:t.config,appConfig:n,...e?{agentId:e}:{}}));let r;const requireCommandContext=()=>{if(!r)throw new Error(`Memory Wiki CLI agent context was not resolved.`);return r};const i=e.command(`wiki`).description(`Inspect and initialize the memory wiki vault`).option(`--agent <id>`,`Agent id for agent-scoped wiki vaults`);i.hook(`preAction`,(e,a)=>{const o=a.options.some(e=>e.long===`--agent`);const s=a.opts().agent?.trim()||i.opts().agent?.trim()||void 0;const c=t.getAppConfig?.();let l=s;if(o&&!l&&(t.config.vault.scope===`agent`||c))try{l=resolveDefaultAgentId(c??{})}catch{throw new Error("No default memory-wiki agent is configured. Pass --agent <id>, or add an agent with `openclaw agents add`.")}const u=o?n(l,c):t.config;l=u.agentId??l;r={config:u,...c?{appConfig:c}:{},...l?{agentId:l}:{}}});const vaultCommand=(e,t,n)=>e.command(t).description(n).option(`--agent <id>`,`Agent id (default: configured default agent)`);for(const[e,t]of[[`status`,`Show wiki vault status`],[`doctor`,`Audit wiki vault setup and report actionable fixes`]])vaultCommand(i,e,t).option(`--json`,`Print JSON`).action(async t=>{await runWikiStatus({...requireCommandContext(),json:t.json,doctor:e===`doctor`})});vaultCommand(i,`init`,`Initialize the wiki vault layout`).option(`--json`,`Print JSON`).action(async e=>{const{config:t}=requireCommandContext();printWikiResult(await initializeMemoryWikiVault(t),e.json,e=>terminalText`Initialized wiki vault at ${e.rootDir} (${e.createdDirectories.length} dirs, ${e.createdFiles.length} files).`)});vaultCommand(i,`compile`,`Refresh generated wiki indexes`).option(`--json`,`Print JSON`).action(async e=>{const{appConfig:t,config:n}=requireCommandContext();await syncMemoryWikiImportedSources({config:n,appConfig:t,deferIndexRefresh:true});printWikiResult(await compileMemoryWikiVault(n),e.json,e=>terminalText`Compiled wiki vault at ${e.vaultRoot} (${e.pages.length} pages, ${e.updatedFiles.length} indexes updated).`)});vaultCommand(i,`lint`,`Lint the wiki vault and write a report`).option(`--json`,`Print JSON`).action(async e=>{const{appConfig:t,config:n}=requireCommandContext();await syncMemoryWikiImportedSources({config:n,appConfig:t,deferIndexRefresh:true});printWikiResult(await lintMemoryWikiVault(n),e.json,e=>terminalText`Linted wiki vault at ${e.vaultRoot} (${e.issueCount} issues, report: ${e.reportPath}).`)});vaultCommand(i,`ingest`,`Ingest a local file into the wiki sources folder`).argument(`<path>`,`Local file path to ingest`).option(`--title <title>`,`Override the source title`).option(`--json`,`Print JSON`).action(async(e,t)=>{const{config:n}=requireCommandContext();printWikiResult(await ingestMemoryWikiSource({config:n,inputPath:e,title:t.title}),t.json,e=>terminalText`Ingested ${e.sourcePath} into ${e.pagePath}. Refreshed ${e.indexUpdatedFiles.length} index file${e.indexUpdatedFiles.length===1?``:`s`}.`)});vaultCommand(i.command(`okf`).description(`Import Open Knowledge Format bundles`),`import`,`Import an unpacked OKF bundle into wiki concept pages`).argument(`<path>`,`OKF bundle directory`).option(`--json`,`Print JSON`).action(async(e,t)=>{const{config:n}=requireCommandContext();printWikiResult(await importMemoryWikiOkfBundle({config:n,bundlePath:e}),t.json,formatOkfImportSummary)});addWikiSearchConfigOptions(vaultCommand(i,`search`,`Search wiki pages and, when configured, the active memory corpus`).argument(`<query>`,`Search query`).option(`--max-results <n>`,`Maximum results`,e=>parseWikiPositiveIntegerOption(e,`--max-results`)).option(`--mode <mode>`,`Search mode (${WIKI_SEARCH_MODES.join(`, `)})`)).option(`--json`,`Print JSON`).action(async(e,t)=>{const{agentId:n,appConfig:r,config:i}=requireCommandContext();if(t.mode&&!WIKI_SEARCH_MODES.includes(t.mode))throw new Error(`wiki search --mode must be one of: ${WIKI_SEARCH_MODES.join(`, `)}.`);await syncMemoryWikiImportedSources({config:i,appConfig:r});writeOutput(formatJsonOrText(await searchMemoryWiki({config:i,appConfig:r,...n?{agentId:n}:{},query:e,maxResults:t.maxResults,searchBackend:t.backend,searchCorpus:t.corpus,mode:t.mode}),t.json,renderWikiSearchResults))});addWikiSearchConfigOptions(vaultCommand(i,`get`,`Read a wiki page by id or relative path, with optional active-memory fallback`).argument(`<lookup>`,`Relative path or page id`).option(`--from <n>`,`Start line`,e=>parseWikiPositiveIntegerOption(e,`--from`)).option(`--lines <n>`,`Number of lines`,e=>parseWikiPositiveIntegerOption(e,`--lines`))).option(`--json`,`Print JSON`).action(async(e,t)=>{const{agentId:n,appConfig:r,config:i}=requireCommandContext();await syncMemoryWikiImportedSources({config:i,appConfig:r});const a=await getMemoryWikiPage({config:i,appConfig:r,...n?{agentId:n}:{},lookup:e,fromLine:t.from,lineCount:t.lines,searchBackend:t.backend,searchCorpus:t.corpus});writeOutput(t.json?JSON.stringify(a,null,2):a?.content??terminalText`Wiki page not found: ${e}`)});const a=i.command(`apply`).description(`Apply narrow wiki mutations`);addWikiApplyMutationOptions(vaultCommand(a,`synthesis`,`Create or refresh a synthesis page with managed summary content`).argument(`<title>`,`Synthesis title`).option(`--body <text>`,`Summary body text`).option(`--body-file <path>`,`Read summary body text from a file`)).option(`--json`,`Print JSON`).action(async(e,t)=>{const{appConfig:n,config:r}=requireCommandContext();const i=resolveCliMutationMetadata(t);const a=i.sourceIds;if(!a)throw new Error(`wiki apply synthesis requires at least one --source-id.`);const o=await resolveWikiApplyBody({body:t.body,bodyFile:t.bodyFile});await syncMemoryWikiImportedSources({config:r,appConfig:n});writeOutput(formatJsonOrText(await applyMemoryWikiMutation({config:r,mutation:{op:`create_synthesis`,title:e,body:o,...i,sourceIds:a,...typeof t.confidence===`number`?{confidence:t.confidence}:{}}}),t.json,renderWikiMutationSummary))});addWikiApplyMutationOptions(vaultCommand(a,`metadata`,`Update metadata on an existing page`).argument(`<lookup>`,`Relative path or page id`)).option(`--clear-confidence`,`Remove any stored confidence value`).option(`--json`,`Print JSON`).action(async(e,t)=>{const{appConfig:n,config:r}=requireCommandContext();await syncMemoryWikiImportedSources({config:r,appConfig:n});writeOutput(formatJsonOrText(await applyMemoryWikiMutation({config:r,mutation:{op:`update_metadata`,lookup:e,...resolveCliMutationMetadata(t),...t.clearConfidence?{confidence:null}:typeof t.confidence===`number`?{confidence:t.confidence}:{}}}),t.json,renderWikiMutationSummary))});vaultCommand(i.command(`bridge`).description(`Import public memory artifacts into the wiki vault`),`import`,`Sync bridge-backed memory artifacts into wiki source pages`).option(`--json`,`Print JSON`).action(async e=>{const{agentId:t,appConfig:n,config:r}=requireCommandContext();await runWikiBridgeImport({config:r,appConfig:n,agentId:t,json:e.json})});i.command(`unsafe-local`).description(`Import explicitly configured private local paths into wiki source pages`).command(`import`).description(`Sync unsafe-local configured paths into wiki source pages`).option(`--json`,`Print JSON`).action(async e=>{const{appConfig:t,config:n}=requireCommandContext();if(n.vault.scope===`agent`)throw new Error(`Unsafe-local import does not support memory-wiki vault.scope=agent.`);printWikiResult(await syncMemoryWikiImportedSources({config:n,appConfig:t}),e.json,e=>terminalText`Unsafe-local import synced ${e.artifactCount} artifacts (${e.importedCount} new, ${e.updatedCount} updated, ${e.skippedCount} unchanged, ${e.removedCount} removed). Indexes ${e.indexesRefreshed?`refreshed (${e.indexUpdatedFiles.length} files)`:`not refreshed (${e.indexRefreshReason})`}.`)});const o=i.command(`chatgpt`).description(`Import ChatGPT export history into wiki source pages`);o.command(`import`).description(`Import a ChatGPT export into draft wiki source pages`).requiredOption(`--export <path>`,`ChatGPT export directory or conversations.json path`).option(`--agent <id>`,`Agent id (default: configured default agent)`).option(`--dry-run`,`Preview changes without writing`,false).option(`--json`,`Print JSON`).action(async e=>{const{config:t}=requireCommandContext();printWikiResult(await importChatGptConversations({config:t,exportPath:e.export,dryRun:e.dryRun}),e.json,formatChatGptImportSummary)});vaultCommand(o,`rollback`,`Roll back a previously applied ChatGPT import run`).argument(`<run-id>`,`Import run id`).option(`--json`,`Print JSON`).action(async(e,t)=>{const{config:n}=requireCommandContext();printWikiResult(await rollbackChatGptImportRun({config:n,runId:e}),t.json,formatChatGptRollbackSummary)});const s=i.command(`obsidian`).description(`Run official Obsidian CLI helpers`);s.command(`status`).description(`Check the Obsidian CLI`).option(`--json`,`Print JSON`).action(async e=>{requireCommandContext();printWikiResult(await probeObsidianCli(),e.json,e=>e.available?terminalText`Obsidian CLI available at ${e.command}`:`Obsidian CLI is not available on PATH.`)});for(const e of OBSIDIAN_ACTIONS){const t=s.command(e.command).description(e.description);if(e.argument)t.argument(`<${e.argument.name}>`,e.argument.description);t.option(`--json`,`Print JSON`);const run=async(t,n)=>{const{config:r}=requireCommandContext();assertOfficialObsidianCliSupported(r);const i=await runObsidianAction({config:r,action:e,value:t});writeOutput(n.json?JSON.stringify(i,null,2):i.stdout.trim()||e.success)};if(e.argument)t.action((e,t)=>run(e,t));else t.action(e=>run(void 0,e))}}export{registerWikiCli};