diff --git a/CLAUDE.md b/CLAUDE.md index 4bc690e..0b18e71 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## Project Overview -MicroClaw is a Windows desktop application that packages the OpenClaw open-source Agent framework. It includes an Electron chat UI, a local OpenClaw Gateway, 52+ built-in skills, 7 managed skills, a native Windows Node + MXC tool sandbox, a WeChat plugin, and a Teams bot integration. MXC Full/Limited are the only sandbox modes; Off deliberately runs tools unsandboxed. The retired AppContainerLauncher backend, preload hooks, provisioning, and controls must not be reintroduced. +MicroClaw is a Windows desktop application that packages the OpenClaw open-source Agent framework. It includes an Electron chat UI, a local OpenClaw Gateway, 52+ built-in skills, 7 managed skills, a native Windows Node + MXC tool sandbox, a WeChat plugin, and a Teams bot integration. MXC Full is the only supported sandbox mode; Off deliberately runs tools unsandboxed. Legacy Limited selections migrate to Full. The retired AppContainerLauncher backend, preload hooks, provisioning, and controls must not be reintroduced. ## Build & Development Commands diff --git a/desktop/src/agent-personas.test.ts b/desktop/src/agent-personas.test.ts index 5108b6b..96b6a07 100644 --- a/desktop/src/agent-personas.test.ts +++ b/desktop/src/agent-personas.test.ts @@ -1,6 +1,8 @@ import * as fs from "fs"; import * as os from "os"; import * as path from "path"; +import { runInNewContext } from "node:vm"; +import ts from "typescript"; import { afterEach, describe, expect, it } from "vitest"; import { getAgentSkills, matchesSkill, resolveSkillFilterNames } from "./agent-catalog"; import { @@ -17,10 +19,15 @@ import { OFFICE_ARTISAN_ARTIFACT_BOUNDARY_SECTION, removeConfiguredAgent, resolveAgentPersonaWorkspace, + seedAgentPersonaWorkspace, seedAgentPersonaWorkspaces, + synchronizeAgentWindowsNodeInstructions, } from "./agent-personas"; import { readAgentRoster } from "./agent-roster"; -import { WINDOWS_NODE_ACCESS_INSTRUCTIONS } from "./windows-node-command-instructions"; +import { + updateWindowsNodeInstructions, + WINDOWS_NODE_ACCESS_INSTRUCTIONS, +} from "./windows-node-command-instructions"; const tempDirs: string[] = []; @@ -350,11 +357,191 @@ My custom transport guidance. expect(updated).toContain(soulPath); expect(soul).toContain("My custom folder guidance."); expect(soul).toContain("My custom transport guidance."); + expect(soul).toContain("## MXC filesystem and executable recovery"); expect(soul).toContain("## PowerShell command quoting"); + expect(soul).toContain("## PowerShell filesystem operations in MXC"); expect(soul).not.toContain("## PowerShell deletion in MXC"); } }); + it("keeps MXC guidance synchronized across main, specialist, and newly added agents", () => { + const stateDir = createStateDir(); + const config = { agents: {} }; + const main = getAgentPersona("main")!; + const specialist = getAgentPersona("code-geek")!; + const legacy = "Legacy generated appendix"; + ensureAgentPersonasConfig(config, stateDir, [...DEFAULT_AGENT_PERSONAS, specialist]); + seedAgentPersonaWorkspaces( + config, + stateDir, + WINDOWS_NODE_ACCESS_INSTRUCTIONS, + {}, + undefined, + undefined, + legacy, + false, + ); + const paths = [main, specialist].map((persona) => + path.join(resolveAgentPersonaWorkspace(config, stateDir, persona), "SOUL.md"), + ); + for (const file of paths) { + expect(fs.readFileSync(file, "utf-8")).not.toMatch(/\bMXC\b|\[declare-access\]/); + fs.appendFileSync(file, "\n## User notes\nPreserve these.\n"); + } + + expect( + synchronizeAgentWindowsNodeInstructions(config, stateDir, legacy, true).updatedFiles, + ).toEqual(expect.arrayContaining(paths)); + for (const file of paths) { + const soul = fs.readFileSync(file, "utf-8"); + expect(soul).toContain("## MXC filesystem and executable recovery"); + expect(soul).toContain("## PowerShell filesystem operations in MXC"); + expect(soul).toContain("## User notes\nPreserve these."); + } + expect( + synchronizeAgentWindowsNodeInstructions(config, stateDir, legacy, false).updatedFiles, + ).toEqual(expect.arrayContaining(paths)); + for (const file of paths) { + const soul = fs.readFileSync(file, "utf-8"); + expect(soul).not.toMatch(/\bMXC\b|\[declare-access\]/); + expect(soul).toContain("## User notes\nPreserve these."); + expect(soul).toContain("## Memory recall before filesystem tools"); + } + expect( + synchronizeAgentWindowsNodeInstructions(config, stateDir, legacy, false).updatedFiles, + ).toEqual([]); + + const added = getAgentPersona("master-archive")!; + ensureAgentPersonasConfig(config, stateDir, [...DEFAULT_AGENT_PERSONAS, specialist, added]); + seedAgentPersonaWorkspace( + config, + stateDir, + added, + WINDOWS_NODE_ACCESS_INSTRUCTIONS, + {}, + undefined, + undefined, + legacy, + false, + ); + const addedSoul = fs.readFileSync( + path.join(resolveAgentPersonaWorkspace(config, stateDir, added), "SOUL.md"), + "utf-8", + ); + expect(addedSoul).not.toMatch(/\bMXC\b|\[declare-access\]/); + expect(addedSoul).toContain("## Windows Node command transport"); + }); + + it("does not partially update agent instructions if a workspace cannot be read", () => { + const stateDir = createStateDir(); + const config = { agents: {} }; + const main = getAgentPersona("main")!; + const specialist = getAgentPersona("code-geek")!; + const legacy = "Legacy generated appendix"; + ensureAgentPersonasConfig(config, stateDir, [...DEFAULT_AGENT_PERSONAS, specialist]); + seedAgentPersonaWorkspaces( + config, + stateDir, + WINDOWS_NODE_ACCESS_INSTRUCTIONS, + {}, + undefined, + undefined, + legacy, + false, + ); + const mainPath = path.join(resolveAgentPersonaWorkspace(config, stateDir, main), "SOUL.md"); + const before = fs.readFileSync(mainPath, "utf-8"); + fs.unlinkSync(path.join(resolveAgentPersonaWorkspace(config, stateDir, specialist), "SOUL.md")); + + expect(() => synchronizeAgentWindowsNodeInstructions(config, stateDir, legacy, true)).toThrow(); + expect(fs.readFileSync(mainPath, "utf-8")).toBe(before); + }); + + it("restores earlier SOUL files if a later workspace write fails", () => { + const stateDir = createStateDir(); + const config = { agents: {} }; + const main = getAgentPersona("main")!; + const specialist = getAgentPersona("code-geek")!; + const legacy = "Legacy generated appendix"; + ensureAgentPersonasConfig(config, stateDir, [...DEFAULT_AGENT_PERSONAS, specialist]); + seedAgentPersonaWorkspaces( + config, + stateDir, + WINDOWS_NODE_ACCESS_INSTRUCTIONS, + {}, + undefined, + undefined, + legacy, + false, + ); + const mainPath = path.join(resolveAgentPersonaWorkspace(config, stateDir, main), "SOUL.md"); + const specialistPath = path.join( + resolveAgentPersonaWorkspace(config, stateDir, specialist), + "SOUL.md", + ); + const before = fs.readFileSync(mainPath, "utf-8"); + const source = fs.readFileSync(path.join(__dirname, "agent-personas.ts"), "utf-8"); + const ast = ts.createSourceFile("agent-personas.ts", source, ts.ScriptTarget.Latest, true); + const declaration = ast.statements.find( + (statement) => + ts.isFunctionDeclaration(statement) && + statement.name?.text === "synchronizeAgentWindowsNodeInstructions", + ); + if (!declaration) throw new Error("Cannot locate agent instruction synchronization"); + const js = ts.transpileModule( + `exports.sync = ${declaration.getText(ast).replace(/^export\s+/, "")}`, + { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }, + ).outputText; + const exported: { sync?: typeof synchronizeAgentWindowsNodeInstructions } = {}; + runInNewContext(js, { + exports: exported, + fs: { + readFileSync: fs.readFileSync, + writeFileSync: (file: string, data: string) => { + if (file === specialistPath) throw new Error("SOUL write failed"); + fs.writeFileSync(file, data, "utf-8"); + }, + }, + os, + path, + process, + AGENT_PERSONAS, + listConfiguredAgents, + resolveAgentPersonaWorkspace, + updateWindowsNodeInstructions, + }); + expect(() => exported.sync!(config, stateDir, legacy, true)).toThrow("SOUL write failed"); + expect(fs.readFileSync(mainPath, "utf-8")).toBe(before); + }); + + it("rolls back a mode update without overwriting subsequent user edits", () => { + const stateDir = createStateDir(); + const config = { agents: {} }; + const main = getAgentPersona("main")!; + const specialist = getAgentPersona("code-geek")!; + const legacy = "Legacy generated appendix"; + ensureAgentPersonasConfig(config, stateDir, [...DEFAULT_AGENT_PERSONAS, specialist]); + seedAgentPersonaWorkspaces( + config, + stateDir, + WINDOWS_NODE_ACCESS_INSTRUCTIONS, + {}, + undefined, + undefined, + legacy, + false, + ); + const mainPath = path.join(resolveAgentPersonaWorkspace(config, stateDir, main), "SOUL.md"); + const before = fs.readFileSync(mainPath, "utf-8"); + + synchronizeAgentWindowsNodeInstructions(config, stateDir, legacy, true).rollback(); + expect(fs.readFileSync(mainPath, "utf-8")).toBe(before); + const update = synchronizeAgentWindowsNodeInstructions(config, stateDir, legacy, true); + fs.appendFileSync(mainPath, "\nUser edited during the update.\n"); + expect(update.rollback).toThrow("Failed to restore agent instructions"); + expect(fs.readFileSync(mainPath, "utf-8")).toContain("User edited during the update."); + }); + it("seeds the Intel Analyst workspace with its research context", () => { const stateDir = createStateDir(); const config = { agents: {} }; diff --git a/desktop/src/agent-personas.ts b/desktop/src/agent-personas.ts index 4ecc26b..5c45251 100644 --- a/desktop/src/agent-personas.ts +++ b/desktop/src/agent-personas.ts @@ -1133,6 +1133,7 @@ export function seedAgentPersonaWorkspaces( homeDir = os.homedir(), cwd = process.cwd(), legacySoulAppendix = "", + mxcEnabled = true, ): string[] { const updatedFiles: string[] = []; const configuredIds = new Set(listConfiguredAgents(config).map((agent) => agent.id)); @@ -1149,6 +1150,7 @@ export function seedAgentPersonaWorkspaces( homeDir, cwd, legacySoulAppendix, + mxcEnabled, ), ); } @@ -1165,10 +1167,14 @@ export function seedAgentPersonaWorkspace( homeDir = os.homedir(), cwd = process.cwd(), legacySoulAppendix = "", + mxcEnabled = true, ): string[] { if (!persona.workspaceFiles) return []; const updatedFiles: string[] = []; const workspaceDir = resolveAgentPersonaWorkspace(config, stateDir, persona, env, homeDir, cwd); + const effectiveSoulAppendix = legacySoulAppendix + ? updateWindowsNodeInstructions(soulAppendix, legacySoulAppendix, mxcEnabled) + : soulAppendix; fs.mkdirSync(workspaceDir, { recursive: true }); for (const [filename, source] of Object.entries(persona.workspaceFiles)) { @@ -1183,7 +1189,7 @@ export function seedAgentPersonaWorkspace( if (fs.existsSync(filePath)) { let existing = fs.readFileSync(filePath, "utf-8"); if (filename === "SOUL.md" && legacySoulAppendix) { - const updated = updateWindowsNodeInstructions(existing, legacySoulAppendix); + const updated = updateWindowsNodeInstructions(existing, legacySoulAppendix, mxcEnabled); if (updated !== existing) { fs.writeFileSync(filePath, updated, "utf-8"); updatedFiles.push(filePath); @@ -1245,14 +1251,14 @@ export function seedAgentPersonaWorkspace( if (requiredMarker && !existing.includes(requiredMarker)) { sections.push(requiredSection.trim()); } - const appendixMarker = markdownSectionMarker(soulAppendix); + const appendixMarker = markdownSectionMarker(effectiveSoulAppendix); if ( filename === "SOUL.md" && - soulAppendix.trim() && + effectiveSoulAppendix.trim() && appendixMarker && !existing.includes(appendixMarker) ) { - sections.push(soulAppendix.trim()); + sections.push(effectiveSoulAppendix.trim()); } if (sections.length > 0) { fs.appendFileSync(filePath, `\n${sections.join("\n\n")}\n`, "utf-8"); @@ -1267,14 +1273,14 @@ export function seedAgentPersonaWorkspace( if (requiredMarker && !existing.includes(requiredMarker)) { sections.push(OFFICE_ARTISAN_ARTIFACT_BOUNDARY_SECTION.trim()); } - const appendixMarker = markdownSectionMarker(soulAppendix); + const appendixMarker = markdownSectionMarker(effectiveSoulAppendix); if ( filename === "SOUL.md" && - soulAppendix.trim() && + effectiveSoulAppendix.trim() && appendixMarker && !existing.includes(appendixMarker) ) { - sections.push(soulAppendix.trim()); + sections.push(effectiveSoulAppendix.trim()); } if (sections.length > 0) { fs.appendFileSync(filePath, `\n${sections.join("\n\n")}\n`, "utf-8"); @@ -1292,9 +1298,9 @@ export function seedAgentPersonaWorkspace( sections.push(workspaceSource.trim()); existing += `\n${workspaceSource.trim()}\n`; } - const appendixMarker = markdownSectionMarker(soulAppendix); - if (soulAppendix.trim() && appendixMarker && !existing.includes(appendixMarker)) { - sections.push(soulAppendix.trim()); + const appendixMarker = markdownSectionMarker(effectiveSoulAppendix); + if (effectiveSoulAppendix.trim() && appendixMarker && !existing.includes(appendixMarker)) { + sections.push(effectiveSoulAppendix.trim()); } if (sections.length > 0) { fs.appendFileSync(filePath, `\n${sections.join("\n\n")}\n`, "utf-8"); @@ -1304,14 +1310,14 @@ export function seedAgentPersonaWorkspace( continue; } - const appendixMarker = markdownSectionMarker(soulAppendix); + const appendixMarker = markdownSectionMarker(effectiveSoulAppendix); const shouldAppendSoulSection = filename === "SOUL.md" && - soulAppendix.trim() && + effectiveSoulAppendix.trim() && appendixMarker && !workspaceSource.includes(appendixMarker); const content = shouldAppendSoulSection - ? `${workspaceSource.trimEnd()}\n\n${soulAppendix.trim()}\n` + ? `${workspaceSource.trimEnd()}\n\n${effectiveSoulAppendix.trim()}\n` : `${workspaceSource.trimEnd()}\n`; fs.writeFileSync(filePath, content, "utf-8"); updatedFiles.push(filePath); @@ -1320,6 +1326,70 @@ export function seedAgentPersonaWorkspace( return [...new Set(updatedFiles)]; } +export function synchronizeAgentWindowsNodeInstructions( + config: AgentRosterConfig, + stateDir: string, + legacySoulAppendix: string, + mxcEnabled: boolean, + env: NodeJS.ProcessEnv = process.env, + homeDir = os.homedir(), + cwd = process.cwd(), +): { updatedFiles: string[]; rollback: () => void } { + const configuredIds = new Set(listConfiguredAgents(config).map((agent) => agent.id)); + const seen = new Set(); + const changes: Array<{ filePath: string; before: string; after: string }> = []; + for (const persona of AGENT_PERSONAS) { + if (!persona.workspaceFiles?.["SOUL.md"] || !configuredIds.has(persona.id)) continue; + const workspace = resolveAgentPersonaWorkspace(config, stateDir, persona, env, homeDir, cwd); + const filePath = path.join(workspace, "SOUL.md"); + const key = process.platform === "win32" ? filePath.toLowerCase() : filePath; + if (seen.has(key)) continue; + seen.add(key); + const before = fs.readFileSync(filePath, "utf-8"); + const after = updateWindowsNodeInstructions(before, legacySoulAppendix, mxcEnabled); + if (after !== before) changes.push({ filePath, before, after }); + } + + const applied: typeof changes = []; + const rollback = () => { + const errors: unknown[] = []; + for (let index = applied.length - 1; index >= 0; index -= 1) { + const change = applied[index]; + try { + if (fs.readFileSync(change.filePath, "utf-8") !== change.after) { + throw new Error(`Agent SOUL.md changed during rollback: ${change.filePath}`); + } + fs.writeFileSync(change.filePath, change.before, "utf-8"); + applied.splice(index, 1); + } catch (error) { + errors.push(error); + } + } + if (errors.length) throw new AggregateError(errors, "Failed to restore agent instructions"); + }; + try { + for (const change of changes) { + if (fs.readFileSync(change.filePath, "utf-8") !== change.before) { + throw new Error(`Agent SOUL.md changed during mode update: ${change.filePath}`); + } + fs.writeFileSync(change.filePath, change.after, "utf-8"); + applied.push(change); + } + } catch (error) { + try { + rollback(); + } catch (rollbackError) { + throw new AggregateError( + [error, rollbackError], + "Failed to update and restore agent instructions", + { cause: rollbackError }, + ); + } + throw error; + } + return { updatedFiles: changes.map((change) => change.filePath), rollback }; +} + function markdownSectionMarker(contents: string): string { return contents.split(/\r?\n/).find((line) => line.startsWith("## ")) ?? contents.trim(); } diff --git a/desktop/src/agent-workspaces-startup.test.ts b/desktop/src/agent-workspaces-startup.test.ts index 0c29bc9..876190d 100644 --- a/desktop/src/agent-workspaces-startup.test.ts +++ b/desktop/src/agent-workspaces-startup.test.ts @@ -1,12 +1,14 @@ -import { readFileSync } from "node:fs"; +import * as fs from "node:fs"; +import * as os from "node:os"; import * as path from "node:path"; import { createContext, runInContext } from "node:vm"; import ts from "typescript"; import { describe, expect, it, vi } from "vitest"; import { planDefaultWorkspaceFolderGrant } from "./agent-workspaces"; +import { updateWindowsNodeInstructions } from "./windows-node-command-instructions"; import { canonicalizeApprovedCwd } from "./windows-node-mxc"; -const source = readFileSync(path.join(__dirname, "main.ts"), "utf8"); +const source = fs.readFileSync(path.join(__dirname, "main.ts"), "utf8"); const ast = ts.createSourceFile("main.ts", source, ts.ScriptTarget.Latest, true); function mainFunction(name: string) { const declaration = ast.statements.find( @@ -15,6 +17,17 @@ function mainFunction(name: string) { if (!declaration) throw new Error(`Missing main function ${name}`); return declaration.getText(ast); } +function mainVariable(name: string) { + const statement = ast.statements.find( + (node) => + ts.isVariableStatement(node) && + node.declarationList.declarations.some( + (declaration) => ts.isIdentifier(declaration.name) && declaration.name.text === name, + ), + ); + if (!statement) throw new Error(`Missing main variable ${name}`); + return statement.getText(ast); +} const parent = "C:\\Users\\alice\\OpenClawWorkspaces"; function grantHarness() { @@ -121,6 +134,62 @@ describe("workspace startup wiring", () => { expect(seeder).toContain("resolveAgentPersonaWorkspace("); expect(seeder).not.toContain('path.join(stateDir, "workspace")'); expect(mainFunction("captureAgentWorkspace")).toContain('"BOOTSTRAP.md"'); + expect(startup).toContain("const mxcEnabledForInstructions = isWindowsNodeMxcDesired()"); + expect(startup).toContain("mxcEnabledForInstructions,"); + }); + + it("seeds and migrates the actual main SOUL for the current sandbox mode", () => { + const workspace = fs.mkdtempSync(path.join(os.tmpdir(), "microclaw-main-soul-")); + try { + const context = createContext({ + exports: {} as { + seed?: ( + state: string, + config: object, + env: object, + cwd: string, + enabled: boolean, + ) => void; + defaultSoul?: string; + }, + fs, + path, + os, + updateWindowsNodeInstructions, + MAIN_PLATFORM_IDENTITY_SECTION: "## Platform Identity\n\nKeep the identity.", + resolveAgentPersonaWorkspace: () => workspace, + getAgentPersona: () => ({ id: "main" }), + console: { log: vi.fn(), warn: vi.fn() }, + }); + runInContext( + ts.transpileModule( + `${mainVariable("DEFAULT_SOUL_MD")} + ${mainVariable("DECLARE_ACCESS_SECTION")} + exports.seed = ${mainFunction("seedWorkspaceFiles")}; + exports.defaultSoul = DEFAULT_SOUL_MD;`, + { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }, + ).outputText, + context, + ); + const seed = context.exports.seed!; + const soulPath = path.join(workspace, "SOUL.md"); + seed(workspace, {}, {}, workspace, false); + expect(fs.readFileSync(soulPath, "utf-8")).not.toMatch(/\bMXC\b|\[declare-access\]/); + + fs.writeFileSync(soulPath, `${context.exports.defaultSoul}\n## User notes\nKeep these.\n`); + seed(workspace, {}, {}, workspace, false); + expect(fs.readFileSync(soulPath, "utf-8")).not.toMatch(/\bMXC\b|\[declare-access\]/); + seed(workspace, {}, {}, workspace, true); + expect(fs.readFileSync(soulPath, "utf-8")).toContain( + "## MXC filesystem and executable recovery", + ); + seed(workspace, {}, {}, workspace, false); + const off = fs.readFileSync(soulPath, "utf-8"); + expect(off).not.toMatch(/\bMXC\b|\[declare-access\]/); + expect(off).toContain("## User notes\nKeep these."); + } finally { + fs.rmSync(workspace, { recursive: true, force: true }); + } }); it("applies the same layout when adding an agent without creating per-agent grants", () => { @@ -132,5 +201,6 @@ describe("workspace startup wiring", () => { add.indexOf("captureAgentWorkspace("), ); expect(add).not.toContain("windowsNodeMxcFolders"); + expect(add).toContain("isWindowsNodeMxcDesired()"); }); }); diff --git a/desktop/src/main.ts b/desktop/src/main.ts index 4a5135d..0298445 100644 --- a/desktop/src/main.ts +++ b/desktop/src/main.ts @@ -196,6 +196,7 @@ import { resolveAgentPersonaWorkspace, seedAgentPersonaWorkspace, seedAgentPersonaWorkspaces, + synchronizeAgentWindowsNodeInstructions, type AgentPersona, type AgentRosterConfig, } from "./agent-personas"; @@ -1837,6 +1838,7 @@ function seedWorkspaceFiles( config: AgentRosterConfig, gatewayEnvironment: NodeJS.ProcessEnv, cwd: string, + mxcEnabled: boolean, ): void { const workspaceDir = resolveAgentPersonaWorkspace( config, @@ -1849,11 +1851,9 @@ function seedWorkspaceFiles( const soulPath = path.join(workspaceDir, "SOUL.md"); if (fs.existsSync(soulPath)) { - // SOUL.md exists — ensure the declare-access section is present. - // This patches existing SOUL.md files from older versions that lack it. try { const existing = fs.readFileSync(soulPath, "utf-8"); - const updated = updateWindowsNodeInstructions(existing, DECLARE_ACCESS_SECTION); + const updated = updateWindowsNodeInstructions(existing, DECLARE_ACCESS_SECTION, mxcEnabled); if (updated !== existing) { fs.writeFileSync(soulPath, updated, "utf-8"); console.log("[seed] Updated generated Windows Node command instructions"); @@ -1868,7 +1868,7 @@ function seedWorkspaceFiles( } fs.writeFileSync( soulPath, - updateWindowsNodeInstructions(DEFAULT_SOUL_MD, DECLARE_ACCESS_SECTION), + updateWindowsNodeInstructions(DEFAULT_SOUL_MD, DECLARE_ACCESS_SECTION, mxcEnabled), "utf-8", ); console.log(`[seed] Created default SOUL.md at ${soulPath}`); @@ -3126,9 +3126,23 @@ async function changeWindowsNodeMxcMode(params: { }, release: async () => { assertCurrent(requestedMode); - releaseWindowsNodeMxcIngress(generation); - windowsNodeMxcActivationInProgress = false; - setWindowsNodeMxcLifecycleState(requestedMode === "full" ? "active" : "idle"); + const instructions = synchronizeWindowsNodeInstructionsForMode(requestedMode === "full"); + try { + releaseWindowsNodeMxcIngress(generation); + windowsNodeMxcActivationInProgress = false; + setWindowsNodeMxcLifecycleState(requestedMode === "full" ? "active" : "idle"); + } catch (error) { + try { + instructions.rollback(); + } catch (rollbackError) { + throw new AggregateError( + [error, rollbackError], + "Sandbox mode change and agent instruction rollback failed", + { cause: rollbackError }, + ); + } + throw error; + } }, failClosed: async (error) => { closeWindowsNodeMxcIngress(); @@ -3145,7 +3159,11 @@ async function changeWindowsNodeMxcMode(params: { }, }), { - beforeStart: () => beginWindowsNodeMxcLifecycleOperation(requestedMode === "off"), + beforeStart: () => { + if (agentRosterChangeInProgress) + throw new Error("Wait for the current agent roster change to finish"); + beginWindowsNodeMxcLifecycleOperation(requestedMode === "off"); + }, afterSettled: () => { if (!locked && windowsNodeMxcLifecycleState === "validating") setWindowsNodeMxcLifecycleState(previousMode === "off" ? "idle" : "active"); @@ -4707,6 +4725,7 @@ function seedSpecialistAgentWorkspaces( stateDir: string, entryPath: string, gatewayEnvironment: Record, + mxcEnabled: boolean, ): string[] { const seededFiles = seedAgentPersonaWorkspaces( config, @@ -4716,6 +4735,7 @@ function seedSpecialistAgentWorkspaces( os.homedir(), path.dirname(entryPath), DECLARE_ACCESS_SECTION, + mxcEnabled, ); if (seededFiles.length > 0) { console.log(`[seed] Created specialist agent workspace files: ${seededFiles.join(", ")}`); @@ -4723,6 +4743,30 @@ function seedSpecialistAgentWorkspaces( return seededFiles; } +function synchronizeWindowsNodeInstructionsForMode(mxcEnabled: boolean): { + updatedFiles: string[]; + rollback: () => void; +} { + const config = readConfig(); + if (!config) throw new Error("OpenClaw configuration is unavailable"); + const stateDir = getOpenClawStateDir(); + const result = synchronizeAgentWindowsNodeInstructions( + config, + stateDir, + DECLARE_ACCESS_SECTION, + mxcEnabled, + loadGatewayEnvironment(stateDir), + os.homedir(), + path.dirname(resolveOpenClawEntry()), + ); + if (result.updatedFiles.length > 0) { + console.log( + `[seed] Updated Windows Node guidance in ${result.updatedFiles.length} workspace(s)`, + ); + } + return result; +} + interface WorkspaceSnapshot { directory: string; directoryExisted: boolean; @@ -4920,6 +4964,7 @@ async function addCatalogAgent( os.homedir(), path.dirname(entryPath), DECLARE_ACCESS_SECTION, + isWindowsNodeMxcDesired(), ); assertAgentRosterHotReloadAvailable( config, @@ -6349,17 +6394,20 @@ async function runGatewayStartup( } if (preparedPersonas && !externallyManagedGateway) { agentSkillTransactionPending = true; + const mxcEnabledForInstructions = isWindowsNodeMxcDesired(); seedWorkspaceFiles( stateDir, preparedPersonas.config, gatewayEnvironment, path.dirname(entryPath), + mxcEnabledForInstructions, ); seedSpecialistAgentWorkspaces( preparedPersonas.config, stateDir, entryPath, gatewayEnvironment, + mxcEnabledForInstructions, ); } } catch (error) { diff --git a/desktop/src/windows-node-command-instructions.test.ts b/desktop/src/windows-node-command-instructions.test.ts index 4fdcfbd..578c881 100644 --- a/desktop/src/windows-node-command-instructions.test.ts +++ b/desktop/src/windows-node-command-instructions.test.ts @@ -4,6 +4,8 @@ import { WINDOWS_NODE_ACCESS_INSTRUCTIONS, WINDOWS_NODE_GIT_INSTRUCTIONS, WINDOWS_NODE_MEMORY_INSTRUCTIONS, + WINDOWS_NODE_MXC_FILESYSTEM_INSTRUCTIONS, + WINDOWS_NODE_MXC_POWERSHELL_OPERATIONS_INSTRUCTIONS, WINDOWS_NODE_PERMISSION_DENIED_INSTRUCTIONS, WINDOWS_NODE_POWERSHELL_QUOTING_INSTRUCTIONS, WINDOWS_NODE_POWERSHELL_SCRATCH_INSTRUCTIONS, @@ -27,17 +29,66 @@ Windows Node decides whether a command can be remembered. CMD built-ins and inline PowerShell generally require one-use approval; do not rewrite commands to bypass this. MXC folder grants remain independent of command consent. `; + const previousMxcTransport = `## Windows Node command transport - it("replaces a recognized generated section without changing surrounding content", () => { - const source = `# Personality\n\nKeep my voice.\n\n${legacy}\n## Custom guidance\n\nKeep this too.\n`; - const updated = updateWindowsNodeInstructions(source, legacy); +The exec tool uses OpenClaw's Windows Node transport: cmd.exe /d /s /c. +Use CMD syntax, not bare PowerShell cmdlets. For example, use \`dir\`, \`type\`, +or \`git status\`. Invoke powershell.exe explicitly when PowerShell is necessary. +Command consent applies to exec in both regular and MXC modes. Gateway-native +file tools remain available in both modes, but run outside MXC and bypass exec +consent and MXC folder grants. Use an appropriate native file tool when its +boundary is acceptable; use contained exec when the user requests containment. +Route by the tools available now, not by a previous mode or the last successful +action. Do not retry a denied or failed native operation through exec unless the +user authorizes that fallback. +Windows Node decides whether a command can be remembered. CMD built-ins and +quoted or dynamic PowerShell may require one-use approval. Never change an +approved command to bypass consent. MXC folder grants remain independent. +`; + const previousGeneratedAccess = `## Pre-declaring File System Access - expect(updated).toContain("# Personality\n\nKeep my voice."); - expect(updated).toContain("## Custom guidance\n\nKeep this too."); - expect(updated).not.toContain("Get-ChildItem"); - expect(updated).toContain(WINDOWS_NODE_ACCESS_INSTRUCTIONS.trim()); - expect(updateWindowsNodeInstructions(updated, legacy)).toBe(updated); - }); +For exec commands that access files outside the workspace in MXC mode, put +a declaration on the first line and the actual CMD command on the next line. +The host removes the declaration before execution. Use literal absolute Windows +directory paths, with ro for reading or rw for creating, changing, or deleting. +Do not use variables in declarations or submit a declaration without a command. + +MXC can switch live. In Off mode, do not add declarations or request MXC +folder grants; host execution remains subject to command-consent settings. + +\`\`\` +REM [declare-access]ro:C:\\Users\\alice\\Desktop[/declare-access] +dir "C:\\Users\\alice\\Desktop" +\`\`\` + +\`\`\` +REM [declare-access]rw:C:\\Users\\alice\\Desktop;rw:C:\\Users\\alice\\Documents[/declare-access] +move "C:\\Users\\alice\\Desktop\\report.xlsx" "C:\\Users\\alice\\Documents\\" +\`\`\` + +Declare only the directories actually needed, never a drive root or all users. +A declaration requests access; it does not grant it. Missing MXC folder grants +and command approval are presented together in one prompt. +`; + + it.each(["\n", "\r\n"])( + "replaces a recognized generated section without changing surrounding content", + (lineEnding) => { + const source = + `# Personality\n\nKeep my voice.\n\n${legacy}\n## Custom guidance\n\nKeep this too.\n`.replace( + /\n/g, + lineEnding, + ); + const updated = updateWindowsNodeInstructions(source, legacy); + const normalized = updated.replace(/\r\n/g, "\n"); + + expect(normalized).toContain("# Personality\n\nKeep my voice."); + expect(normalized).toContain("## Custom guidance\n\nKeep this too."); + expect(updated).not.toContain("Get-ChildItem"); + expect(normalized).toContain(WINDOWS_NODE_ACCESS_INSTRUCTIONS.trim()); + expect(updateWindowsNodeInstructions(updated, legacy)).toBe(updated); + }, + ); it("preserves a customized access section and adds the transport instructions once", () => { const source = "## Pre-declaring File System Access\n\nMy custom rules.\n"; @@ -56,12 +107,77 @@ to bypass this. MXC folder grants remain independent of command consent. expect(updateWindowsNodeInstructions(updated, legacy)).toBe(updated); }); + it("adds only mode-independent instructions when MXC is off", () => { + const updated = updateWindowsNodeInstructions("# My agent\n", legacy, false); + + expect(updated).toContain("## Memory recall before filesystem tools"); + expect(updated).toContain("## Windows Node command transport"); + expect(updated).toContain("## PowerShell command quoting"); + expect(updated).not.toMatch(/\bMXC\b|\[declare-access\]/); + expect(updateWindowsNodeInstructions(updated, legacy, false)).toBe(updated); + }); + + it.each(["\n", "\r\n"])( + "removes generated MXC guidance when disabled and restores it when enabled", + (lineEnding) => { + const source = + `# My agent\n\n${previousGeneratedAccess}\n${previousMxcTransport}\n## Notes\nKeep these.\n`.replace( + /\n/g, + lineEnding, + ); + const off = updateWindowsNodeInstructions(source, legacy, false); + expect(off).toContain(`## Notes${lineEnding}Keep these.`); + expect(off).not.toMatch(/\bMXC\b|\[declare-access\]/); + if (lineEnding === "\r\n") expect(off.replace(/\r\n/g, "")).not.toContain("\n"); + expect(updateWindowsNodeInstructions(off, legacy, false)).toBe(off); + + const on = updateWindowsNodeInstructions(off, legacy, true); + expect(on).toContain("## MXC filesystem and executable recovery"); + expect(on).toContain("## PowerShell filesystem operations in MXC"); + expect(on).toContain(`## Notes${lineEnding}Keep these.`); + expect(on.match(/## Windows Node command transport/g)).toHaveLength(1); + if (lineEnding === "\r\n") expect(on.replace(/\r\n/g, "")).not.toContain("\n"); + expect(updateWindowsNodeInstructions(on, legacy, true)).toBe(on); + + const offAgain = updateWindowsNodeInstructions(on, legacy, false); + expect(offAgain).not.toMatch(/\bMXC\b|\[declare-access\]/); + expect(offAgain).toContain(`## Notes${lineEnding}Keep these.`); + expect(updateWindowsNodeInstructions(offAgain, legacy, false)).toBe(offAgain); + }, + ); + + it("preserves user-modified guidance when MXC is disabled", () => { + const edited = WINDOWS_NODE_MXC_FILESYSTEM_INSTRUCTIONS.replace( + "When MXC is On", + "My custom rule: when MXC is On", + ); + const appended = `${WINDOWS_NODE_POWERSHELL_SCRATCH_INSTRUCTIONS.trim()}\n\nMy own note.\n`; + const source = `# My agent\n\n${edited}\n${appended}\n## Notes\nKeep these.\n`; + const updated = updateWindowsNodeInstructions(source, legacy, false); + + expect(updated).toContain(edited.trim()); + expect(updated).toContain(appended.trim()); + expect(updated).toContain("## Notes\nKeep these."); + expect(updateWindowsNodeInstructions(updated, legacy, false)).toBe(updated); + }); + + it("removes the original generated access section when starting in Off mode", () => { + const updated = updateWindowsNodeInstructions( + `# My agent\n\n${legacy}\n## Notes\nKeep these.\n`, + legacy, + false, + ); + expect(updated).not.toContain("Legacy PowerShell examples."); + expect(updated).not.toMatch(/\bMXC\b|\[declare-access\]/); + expect(updated).toContain("## Notes\nKeep these."); + }); + it("upgrades generated access guidance to distinguish Off mode without changing user notes", () => { const previous = WINDOWS_NODE_ACCESS_INSTRUCTIONS.replace( "MXC can switch live. In Off mode, do not add declarations or request MXC\n" + "folder grants; host execution remains subject to command-consent settings.\n\n", "", - ); + ).replace('type "C:\\Users\\alice\\Desktop\\notes.txt"', 'dir "C:\\Users\\alice\\Desktop"'); const updated = updateWindowsNodeInstructions( `# Agent\n\n${previous}\n## Notes\nKeep these.\n`, legacy, @@ -72,6 +188,103 @@ to bypass this. MXC folder grants remain independent of command consent. expect(updateWindowsNodeInstructions(updated, legacy)).toBe(updated); }); + it.each([ + { hasOffGuidance: true, lineEnding: "\n" }, + { hasOffGuidance: false, lineEnding: "\n" }, + { hasOffGuidance: true, lineEnding: "\r\n" }, + { hasOffGuidance: false, lineEnding: "\r\n" }, + ])( + "upgrades the previously generated instructions without changing user notes (%o)", + ({ hasOffGuidance, lineEnding }) => { + const access = hasOffGuidance + ? previousGeneratedAccess + : previousGeneratedAccess.replace( + "MXC can switch live. In Off mode, do not add declarations or request MXC\n" + + "folder grants; host execution remains subject to command-consent settings.\n\n", + "", + ); + const original = + `# My agent\n\n${access}\n${previousMxcTransport}\n## Notes\nKeep these.\n`.replace( + /\n/g, + lineEnding, + ); + const updated = updateWindowsNodeInstructions(original, legacy); + + expect(updated).toContain(`## Notes${lineEnding}Keep these.`); + expect(updated).toContain('type "C:\\Users\\alice\\Desktop\\notes.txt"'); + expect(updated).not.toContain('dir "C:\\Users\\alice\\Desktop"'); + expect(updated).not.toContain("For example, use `dir`, `type`"); + const normalized = updated.replace(/\r\n/g, "\n"); + expect(normalized).toContain(WINDOWS_NODE_MXC_FILESYSTEM_INSTRUCTIONS.trim()); + expect(normalized).toContain(WINDOWS_NODE_MXC_POWERSHELL_OPERATIONS_INSTRUCTIONS.trim()); + expect(updated.match(/## Windows Node command transport/g)).toHaveLength(1); + expect(updated.match(/## MXC filesystem and executable recovery/g)).toHaveLength(1); + expect(updated.match(/## PowerShell filesystem operations in MXC/g)).toHaveLength(1); + expect(updateWindowsNodeInstructions(updated, legacy)).toBe(updated); + }, + ); + + it("adds recovery guidance without replacing customized access and transport sections", () => { + const customizedAccess = previousGeneratedAccess.replace( + "Declare only the directories actually needed", + "My custom rule: declare only the directories actually needed", + ); + const customizedTransport = previousMxcTransport.replace( + "Use CMD syntax", + "My custom rule: use CMD syntax", + ); + const source = `${customizedAccess}\n${customizedTransport}\n## Notes\nKeep these.\n`; + const updated = updateWindowsNodeInstructions(source, legacy); + + expect(updated).toContain(customizedAccess.trim()); + expect(updated).toContain(customizedTransport.trim()); + expect(updated).toContain("## Notes\nKeep these."); + expect(updated).toContain(WINDOWS_NODE_MXC_FILESYSTEM_INSTRUCTIONS.trim()); + expect(updated).toContain(WINDOWS_NODE_MXC_POWERSHELL_OPERATIONS_INSTRUCTIONS.trim()); + expect(updateWindowsNodeInstructions(updated, legacy)).toBe(updated); + }); + + it("guides Gateway tool routing, scoped executable discovery, and existing declarations", () => { + const guidance = updateWindowsNodeInstructions("# My agent\n", legacy); + + expect(guidance).toMatch(/Gateway-native file tools: use `ls`.*`read`/); + expect(guidance).toContain("run outside MXC"); + expect(guidance).toContain("bypass a denied operation or a user's requirement for containment"); + expect(guidance).toMatch(/set `workdir` to an existing approved directory/); + expect(guidance).toContain("does not fix every metadata failure"); + expect(guidance).toContain("a contained `where` can miss a program"); + expect(guidance).toContain("C:\\Program Files"); + expect(guidance).toContain("C:\\Program Files (x86)"); + expect(guidance).toContain("Inspect the candidate folder to confirm the"); + expect(guidance).toContain("follow listing pagination"); + expect(guidance).toContain("smallest existing, permitted installation"); + expect(guidance).toContain("Discovery is not authorization"); + expect(guidance).toContain("must be an existing local directory"); + expect(guidance).toContain("declare the smallest appropriate existing parent as rw"); + expect(guidance).toContain("Never declare a drive root or protected folder"); + expect(guidance).toMatch(/check the declared directories as well as\s+`workdir`/); + }); + + it("guides safe PowerShell splitting and same-invocation initialization", () => { + const guidance = updateWindowsNodeInstructions("# My agent\n", legacy); + + for (const command of ["Remove-Item", "Move-Item", "Rename-Item"]) { + expect(guidance).toContain(`\`${command}\``); + } + expect(guidance).toContain("prefer one operation"); + expect(guidance).toContain("when splitting preserves the requested behavior"); + expect(guidance).toContain("literal absolute paths and `-LiteralPath`"); + expect(guidance).toMatch( + /rw entries covering the source and destination even if\s+their existing directories are already approved or in the workspace/, + ); + expect(guidance).toContain("initializer matches each target against these declarations"); + expect(guidance).toContain("not all command forms qualify"); + expect(guidance).toContain("Do not split a complex script"); + expect(guidance).toContain("initialization and the operation in the same correctly quoted"); + expect(guidance).toContain("Initialization in a separate exec does not"); + expect(guidance).toContain("fresh approval"); + }); + it("upgrades the prior generated transport guidance without changing user notes", () => { const source = `${legacy}\n${previousTransport}\n## User notes\n\nPreserve my instructions.\n`; const updated = updateWindowsNodeInstructions(source, legacy); @@ -111,29 +324,38 @@ to bypass this. MXC folder grants remain independent of command consent. ); }); - it("removes the previous generated deletion workaround while preserving adjacent user notes", () => { - const previous = - "## PowerShell deletion in MXC\n\n" + - "When using Remove-Item in MXC mode, include a scoped filesystem-drive setup in\n" + - "your own PowerShell script before the deletion. This avoids a PowerShell provider\n" + - "initialization failure without changing the OpenClaw command transport. For a\n" + - "literal file, for example:\n\n" + - "```\nREM [declare-access]rw:C:\\work[/declare-access]\n" + - "powershell.exe -NoProfile -Command \"New-PSDrive -Name MicroClawCwd -PSProvider FileSystem -Root ([Environment]::CurrentDirectory) -Scope Script -ErrorAction Stop | Out-Null; Set-Location -LiteralPath 'MicroClawCwd:\\' -ErrorAction Stop; Remove-Item -LiteralPath 'C:\\work\\notes.txt' -Force -ErrorAction Stop\"\n" + - "```\n\n" + - "Declare only the folder needed for the requested operation. Do not broaden\n" + - "folder grants or add recursive deletion unless the user requested it. Keep the\n" + - "script quotes and escape values correctly for CMD and PowerShell. This compound\n" + - "command may require one-use approval; do not alter it to bypass consent.\n"; - const updated = updateWindowsNodeInstructions( - `# My agent\n\n${previous}\n## My notes\nKeep these.\n`, - legacy, - ); - expect(updated).toContain("## My notes\nKeep these."); - expect(updated).not.toContain("## PowerShell deletion in MXC"); - expect(updated).toContain(WINDOWS_NODE_POWERSHELL_SCRATCH_INSTRUCTIONS.trim()); - expect(updateWindowsNodeInstructions(updated, legacy)).toBe(updated); - }); + it.each(["\n", "\r\n"])( + "removes the previous generated deletion workaround while preserving adjacent user notes", + (lineEnding) => { + const previous = + "## PowerShell deletion in MXC\n\n" + + "When using Remove-Item in MXC mode, include a scoped filesystem-drive setup in\n" + + "your own PowerShell script before the deletion. This avoids a PowerShell provider\n" + + "initialization failure without changing the OpenClaw command transport. For a\n" + + "literal file, for example:\n\n" + + "```\nREM [declare-access]rw:C:\\work[/declare-access]\n" + + "powershell.exe -NoProfile -Command \"New-PSDrive -Name MicroClawCwd -PSProvider FileSystem -Root ([Environment]::CurrentDirectory) -Scope Script -ErrorAction Stop | Out-Null; Set-Location -LiteralPath 'MicroClawCwd:\\' -ErrorAction Stop; Remove-Item -LiteralPath 'C:\\work\\notes.txt' -Force -ErrorAction Stop\"\n" + + "```\n\n" + + "Declare only the folder needed for the requested operation. Do not broaden\n" + + "folder grants or add recursive deletion unless the user requested it. Keep the\n" + + "script quotes and escape values correctly for CMD and PowerShell. This compound\n" + + "command may require one-use approval; do not alter it to bypass consent.\n"; + const source = `# My agent\n\n${previous}\n## My notes\nKeep these.\n`.replace( + /\n/g, + lineEnding, + ); + const updated = updateWindowsNodeInstructions(source, legacy); + expect(updated).toContain(`## My notes${lineEnding}Keep these.`); + expect(updated).not.toContain("## PowerShell deletion in MXC"); + expect(updated.replace(/\r\n/g, "\n")).toContain( + WINDOWS_NODE_POWERSHELL_SCRATCH_INSTRUCTIONS.trim(), + ); + expect(updateWindowsNodeInstructions(updated, legacy)).toBe(updated); + const off = updateWindowsNodeInstructions(source, legacy, false); + expect(off).toContain(`## My notes${lineEnding}Keep these.`); + expect(off).not.toMatch(/\bMXC\b|\[declare-access\]/); + }, + ); it("preserves customized deletion guidance and does not add a duplicate", () => { const source = "## PowerShell deletion in MXC\n\nMy custom deletion instructions.\n"; diff --git a/desktop/src/windows-node-command-instructions.ts b/desktop/src/windows-node-command-instructions.ts index 6443dd8..8b142cc 100644 --- a/desktop/src/windows-node-command-instructions.ts +++ b/desktop/src/windows-node-command-instructions.ts @@ -17,6 +17,16 @@ than claiming there are no memories or silently falling back to exec. Reading memory does not authorize editing it or changing any folder permissions. `; +const WINDOWS_NODE_OFF_MEMORY_INSTRUCTIONS = WINDOWS_NODE_MEMORY_INSTRUCTIONS.replace( + "In both regular and MXC modes, use memory tools", + "Use memory tools", +).replace( + "sources and session privacy rules. It runs in the Gateway, independently of MXC\n" + + "folder grants; it is not general filesystem permission.", + "sources and session privacy rules. It runs in the Gateway; it is not general\n" + + "filesystem permission.", +); + const PRE_MEMORY_TRANSPORT_INSTRUCTIONS = `## Windows Node command transport The exec tool uses OpenClaw's Windows Node transport: cmd.exe /d /s /c. @@ -41,7 +51,7 @@ const PRE_RESTORED_FILE_ROUTING_TRANSPORT_INSTRUCTIONS = PRE_MEMORY_TRANSPORT_IN "native operation through exec unless the user authorizes that fallback.", ); -const WINDOWS_NODE_TRANSPORT_INSTRUCTIONS = `## Windows Node command transport +const PREVIOUS_MXC_TRANSPORT_INSTRUCTIONS = `## Windows Node command transport The exec tool uses OpenClaw's Windows Node transport: cmd.exe /d /s /c. Use CMD syntax, not bare PowerShell cmdlets. For example, use \`dir\`, \`type\`, @@ -58,12 +68,76 @@ quoted or dynamic PowerShell may require one-use approval. Never change an approved command to bypass consent. MXC folder grants remain independent. `; +const WINDOWS_NODE_TRANSPORT_INSTRUCTIONS = PREVIOUS_MXC_TRANSPORT_INSTRUCTIONS.replace( + "Use CMD syntax, not bare PowerShell cmdlets. For example, use `dir`, `type`,\n" + + "or `git status`. Invoke powershell.exe explicitly when PowerShell is necessary.", + "Use CMD syntax, not bare PowerShell cmdlets. For example, use `type` or\n" + + "`git status`. Invoke powershell.exe explicitly when PowerShell is necessary.", +); + +const WINDOWS_NODE_OFF_TRANSPORT_INSTRUCTIONS = `## Windows Node command transport + +The exec tool uses OpenClaw's Windows Node transport: cmd.exe /d /s /c. +Use CMD syntax, not bare PowerShell cmdlets. For example, use \`type\` or +\`git status\`. Invoke powershell.exe explicitly when PowerShell is necessary. +Command consent applies to exec. Gateway-native file tools run outside exec +and bypass command consent. Use an appropriate native file tool when its +boundary is acceptable; choose exec for shell workflows or operations without +a suitable native tool. Route by the tools available now, not by a previous +mode or the last successful action. Do not retry a denied or failed native +operation through exec unless the user authorizes that fallback. +Windows Node decides whether a command can be remembered. CMD built-ins and +quoted or dynamic PowerShell may require one-use approval. Never change an +approved command to bypass consent. +`; + const PRE_FILE_ROUTING_TRANSPORT_INSTRUCTIONS = PRE_MEMORY_TRANSPORT_INSTRUCTIONS.replace( "native file tools are unavailable; choose an exec command for file operations.", "native file tools are unavailable; use scoped memory tools for memory recall\n" + "and contained exec for other file operations.", ); +export const WINDOWS_NODE_MXC_FILESYSTEM_INSTRUCTIONS = `## MXC filesystem and executable recovery + +When MXC is On and host-side access is acceptable, prefer available +Gateway-native file tools: use \`ls\` to list directories and \`read\` to read +files instead of running directory-listing commands through exec. Gateway tools +run outside MXC and do not use its folder grants or command consent. Do not use +them to bypass a denied operation or a user's requirement for containment. +If they are unavailable or their boundary is unacceptable, keep the operation +contained and report failures rather than silently switching. + +For exec, set \`workdir\` to an existing approved directory instead of using +\`cd /d\` where practical. CMD \`dir\` can fail because of volume-root +metadata, and absolute \`cd\` has also failed in approved directories. Setting +\`workdir\` avoids the extra \`cd\` but does not fix every metadata failure. + +If an executable such as \`node\` or \`python\` is not found, do not assume +it is uninstalled: a contained \`where\` can miss a program whose folder is not +granted even when PATH is correct. When Gateway \`ls\` is available and its +host-side boundary is acceptable, inspect relevant installation locations, +such as \`C:\\Program Files\`, \`C:\\Program Files (x86)\`, user-local or +otherwise known locations. Inspect the candidate folder to confirm the +executable and follow listing pagination when needed. Do not recursively scan +whole drives or profiles. If the location cannot be established, ask for it +or report the limitation instead of guessing or requesting broad access. +For contained execution, declare the smallest existing, permitted installation +directory as ro, submit the actual command for normal approval, and use the +discovered executable's absolute path. Discovery is not authorization. A PATH +issue or metadata failure can remain after approval; do not broaden access +repeatedly or bypass a denial. + +A [declare-access] path must be an existing local directory, not a destination +the command will create. For a new child such as a Git clone destination, +declare the smallest appropriate existing parent as rw and obtain normal +approval if needed. If the immediate parent is missing, use an appropriately +scoped existing ancestor. Never declare a drive root or protected folder; if no +appropriate ancestor can be approved, ask for another location or report the +limitation. Do not create a directory outside MXC just to obtain a grant. +If \`cwd-not-found\` occurs, check the declared directories as well as +\`workdir\`; a missing declaration can produce the same error. +`; + export const WINDOWS_NODE_POWERSHELL_QUOTING_INSTRUCTIONS = `## PowerShell command quoting For a simple PowerShell command, prefer leaving the entire -Command script @@ -88,6 +162,34 @@ initialized script as a new command for fresh consent. Do not silently change an approved command or broaden folder grants to work around the error. `; +export const WINDOWS_NODE_MXC_POWERSHELL_OPERATIONS_INSTRUCTIONS = `## PowerShell filesystem operations in MXC + +For \`Remove-Item\`, \`Move-Item\`, and \`Rename-Item\`, prefer one operation +per exec when splitting preserves the requested behavior. Use the full cmdlet +name, literal absolute paths and \`-LiteralPath\` where supported; for +\`Rename-Item\`, use a literal new name. For MXC On, include explicit +\`[declare-access]\` rw entries covering the source and destination even if +their existing directories are already approved or in the workspace: the +initializer matches each target against these declarations. A declaration is +not a grant; missing access and command consent require normal approval. +Avoid aliases, variables, wildcards, loops, pipelines, and compound scripts for +these simple operations. +For example, only when the user requested this deletion: + +\`\`\` +REM [declare-access]rw:C:\\work[/declare-access] +powershell.exe -NoProfile -Command Remove-Item -LiteralPath 'C:\\work\\old.txt' +\`\`\` + +The host can initialize the PowerShell filesystem provider for eligible exact +literal commands; not all command forms qualify. Do not split a complex script +if doing so changes its semantics. If it needs provider initialization, +include both the initialization and the operation in the same correctly quoted +PowerShell script, as described in PowerShell in MXC scratch, and submit the +complete command for fresh approval. Initialization in a separate exec does not +carry over. Do not change the requested effects or bypass consent. +`; + const PREVIOUS_MXC_POWERSHELL_DELETE_INSTRUCTIONS = `## PowerShell deletion in MXC When using Remove-Item in MXC mode, include a scoped filesystem-drive setup in @@ -108,10 +210,12 @@ command may require one-use approval; do not alter it to bypass consent. export const WINDOWS_NODE_SHELL_INSTRUCTIONS = `${WINDOWS_NODE_MEMORY_INSTRUCTIONS} ${WINDOWS_NODE_TRANSPORT_INSTRUCTIONS} +${WINDOWS_NODE_MXC_FILESYSTEM_INSTRUCTIONS} ${WINDOWS_NODE_POWERSHELL_QUOTING_INSTRUCTIONS} -${WINDOWS_NODE_POWERSHELL_SCRATCH_INSTRUCTIONS}`; +${WINDOWS_NODE_POWERSHELL_SCRATCH_INSTRUCTIONS} +${WINDOWS_NODE_MXC_POWERSHELL_OPERATIONS_INSTRUCTIONS}`; -const WINDOWS_NODE_ACCESS_SECTION = `## Pre-declaring File System Access +const PREVIOUS_WINDOWS_NODE_ACCESS_SECTION = `## Pre-declaring File System Access For exec commands that access files outside the workspace in MXC mode, put a declaration on the first line and the actual CMD command on the next line. @@ -137,7 +241,12 @@ A declaration requests access; it does not grant it. Missing MXC folder grants and command approval are presented together in one prompt. `; -const PREVIOUS_WINDOWS_NODE_ACCESS_SECTION = WINDOWS_NODE_ACCESS_SECTION.replace( +const WINDOWS_NODE_ACCESS_SECTION = PREVIOUS_WINDOWS_NODE_ACCESS_SECTION.replace( + 'dir "C:\\Users\\alice\\Desktop"', + 'type "C:\\Users\\alice\\Desktop\\notes.txt"', +); + +const LEGACY_WINDOWS_NODE_ACCESS_SECTION = PREVIOUS_WINDOWS_NODE_ACCESS_SECTION.replace( "MXC can switch live. In Off mode, do not add declarations or request MXC\n" + "folder grants; host execution remains subject to command-consent settings.\n\n", "", @@ -206,13 +315,61 @@ const PREVIOUS_TRANSPORT_INSTRUCTIONS_SHORT_GRANT_COPY = "MXC folder grants remain independent.", ); -export function updateWindowsNodeInstructions(content: string, legacySection: string): string { - let updated = content - .replace(`${PREVIOUS_MXC_POWERSHELL_DELETE_INSTRUCTIONS.trim()}\n\n`, "") - .replace(PREVIOUS_MXC_POWERSHELL_DELETE_INSTRUCTIONS.trim(), "") - .replace(PREVIOUS_WINDOWS_NODE_ACCESS_SECTION.trim(), WINDOWS_NODE_ACCESS_SECTION.trim()); +function replaceGeneratedSection(content: string, previous: string, replacement: string): string { + const before = previous.trim(); + const after = replacement.trim(); + if (!before) return content; + let updated = content; + for (const lineEnding of ["\n", "\r\n"]) { + const candidate = before.replace(/\n/g, lineEnding); + const next = after.replace(/\n/g, lineEnding); + let cursor = 0; + while (true) { + const start = updated.indexOf(candidate, cursor); + if (start < 0) break; + const end = start + candidate.length; + const following = updated.slice(end).trimStart(); + if ( + (start > 0 && updated[start - 1] !== "\n") || + (following && !/^#{1,2}(?:\s|$)/.test(following)) + ) { + cursor = end; + continue; + } + const prefix = updated.slice(0, start); + const suffix = updated.slice(end); + if (next) { + updated = prefix + next + suffix; + cursor = prefix.length + next.length; + } else if (!prefix.trim()) { + updated = suffix.replace(/^(?:[ \t]*\r?\n)+/, ""); + cursor = 0; + } else if (!suffix.trim()) { + updated = prefix.replace(/(?:\r?\n)+$/, lineEnding); + cursor = updated.length; + } else { + updated = prefix + suffix.replace(/^(?:[ \t]*\r?\n)+/, ""); + cursor = prefix.length; + } + } + } + return updated; +} + +export function updateWindowsNodeInstructions( + content: string, + legacySection: string, + mxcEnabled = true, +): string { + let updated = replaceGeneratedSection(content, PREVIOUS_MXC_POWERSHELL_DELETE_INSTRUCTIONS, ""); + for (const previous of [ + LEGACY_WINDOWS_NODE_ACCESS_SECTION, + PREVIOUS_WINDOWS_NODE_ACCESS_SECTION, + ]) { + updated = replaceGeneratedSection(updated, previous, WINDOWS_NODE_ACCESS_SECTION); + } const legacy = legacySection.trim(); - if (legacy && updated.includes(legacy)) { + if (legacy && (updated.includes(legacy) || updated.includes(legacy.replace(/\n/g, "\r\n")))) { const replacements = [WINDOWS_NODE_ACCESS_SECTION.trim()]; if (!updated.includes("## Permission-denied recovery in MXC")) { replacements.push(WINDOWS_NODE_PERMISSION_DENIED_INSTRUCTIONS.trim()); @@ -226,13 +383,19 @@ export function updateWindowsNodeInstructions(content: string, legacySection: st if (!updated.includes("## Windows Node command transport")) { replacements.push(WINDOWS_NODE_TRANSPORT_INSTRUCTIONS.trim()); } + if (!updated.includes("## MXC filesystem and executable recovery")) { + replacements.push(WINDOWS_NODE_MXC_FILESYSTEM_INSTRUCTIONS.trim()); + } if (!updated.includes("## PowerShell command quoting")) { replacements.push(WINDOWS_NODE_POWERSHELL_QUOTING_INSTRUCTIONS.trim()); } if (!updated.includes("## PowerShell in MXC scratch")) { replacements.push(WINDOWS_NODE_POWERSHELL_SCRATCH_INSTRUCTIONS.trim()); } - updated = updated.replace(legacy, replacements.join("\n\n")); + if (!updated.includes("## PowerShell filesystem operations in MXC")) { + replacements.push(WINDOWS_NODE_MXC_POWERSHELL_OPERATIONS_INSTRUCTIONS.trim()); + } + updated = replaceGeneratedSection(updated, legacy, replacements.join("\n\n")); } for (const previous of [ PREVIOUS_TRANSPORT_INSTRUCTIONS, @@ -241,11 +404,16 @@ export function updateWindowsNodeInstructions(content: string, legacySection: st PRE_MEMORY_TRANSPORT_INSTRUCTIONS, PRE_FILE_ROUTING_TRANSPORT_INSTRUCTIONS, PRE_RESTORED_FILE_ROUTING_TRANSPORT_INSTRUCTIONS, + PREVIOUS_MXC_TRANSPORT_INSTRUCTIONS, + WINDOWS_NODE_OFF_TRANSPORT_INSTRUCTIONS, ]) { - if (updated.includes(previous.trim())) { - updated = updated.replace(previous.trim(), WINDOWS_NODE_TRANSPORT_INSTRUCTIONS.trim()); - } + updated = replaceGeneratedSection(updated, previous, WINDOWS_NODE_TRANSPORT_INSTRUCTIONS); } + updated = replaceGeneratedSection( + updated, + WINDOWS_NODE_OFF_MEMORY_INSTRUCTIONS, + WINDOWS_NODE_MEMORY_INSTRUCTIONS, + ); const missing: string[] = []; if (!updated.includes("## Pre-declaring File System Access")) { missing.push(WINDOWS_NODE_ACCESS_SECTION.trim()); @@ -262,11 +430,46 @@ export function updateWindowsNodeInstructions(content: string, legacySection: st if (!updated.includes("## Windows Node command transport")) { missing.push(WINDOWS_NODE_TRANSPORT_INSTRUCTIONS.trim()); } + if (!updated.includes("## MXC filesystem and executable recovery")) { + missing.push(WINDOWS_NODE_MXC_FILESYSTEM_INSTRUCTIONS.trim()); + } if (!updated.includes("## PowerShell command quoting")) { missing.push(WINDOWS_NODE_POWERSHELL_QUOTING_INSTRUCTIONS.trim()); } if (!updated.includes("## PowerShell in MXC scratch")) { missing.push(WINDOWS_NODE_POWERSHELL_SCRATCH_INSTRUCTIONS.trim()); } - return missing.length ? `${updated.trimEnd()}\n\n${missing.join("\n\n")}\n` : updated; + if (!updated.includes("## PowerShell filesystem operations in MXC")) { + missing.push(WINDOWS_NODE_MXC_POWERSHELL_OPERATIONS_INSTRUCTIONS.trim()); + } + if (missing.length) { + const lineEnding = updated.includes("\r\n") ? "\r\n" : "\n"; + const additions = missing + .map((section) => section.replace(/\n/g, lineEnding)) + .join(`${lineEnding}${lineEnding}`); + updated = `${updated.trimEnd()}${lineEnding}${lineEnding}${additions}${lineEnding}`; + } + if (!mxcEnabled) { + for (const section of [ + WINDOWS_NODE_ACCESS_SECTION, + WINDOWS_NODE_PERMISSION_DENIED_INSTRUCTIONS, + WINDOWS_NODE_GIT_INSTRUCTIONS, + WINDOWS_NODE_MXC_FILESYSTEM_INSTRUCTIONS, + WINDOWS_NODE_POWERSHELL_SCRATCH_INSTRUCTIONS, + WINDOWS_NODE_MXC_POWERSHELL_OPERATIONS_INSTRUCTIONS, + ]) { + updated = replaceGeneratedSection(updated, section, ""); + } + updated = replaceGeneratedSection( + updated, + WINDOWS_NODE_MEMORY_INSTRUCTIONS, + WINDOWS_NODE_OFF_MEMORY_INSTRUCTIONS, + ); + updated = replaceGeneratedSection( + updated, + WINDOWS_NODE_TRANSPORT_INSTRUCTIONS, + WINDOWS_NODE_OFF_TRANSPORT_INSTRUCTIONS, + ); + } + return updated; } diff --git a/desktop/src/windows-node-mxc-live-mode.test.ts b/desktop/src/windows-node-mxc-live-mode.test.ts index 2d4e806..895f60d 100644 --- a/desktop/src/windows-node-mxc-live-mode.test.ts +++ b/desktop/src/windows-node-mxc-live-mode.test.ts @@ -1,6 +1,25 @@ +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { runInNewContext } from "node:vm"; +import ts from "typescript"; import { describe, expect, it, vi } from "vitest"; import { applyLiveSandboxMode, type LiveSandboxModeHooks } from "./windows-node-mxc-live-mode"; +const mainSource = readFileSync(resolve(process.cwd(), "src", "main.ts"), "utf8"); +const transitionStart = mainSource.indexOf("async function changeWindowsNodeMxcMode("); +const transitionEnd = mainSource.indexOf( + "async function applyRunningWindowsNodeMxcFolders(", + transitionStart, +); +if (transitionStart < 0 || transitionEnd < 0) { + throw new Error("Cannot locate the live sandbox mode transition"); +} +const transitionJs = ts.transpileModule( + `${mainSource.slice(transitionStart, transitionEnd)} + globalThis.testChangeWindowsNodeMxcMode = changeWindowsNodeMxcMode;`, + { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } }, +).outputText; + function hooks() { const calls: string[] = []; const step = (name: string) => @@ -68,4 +87,157 @@ describe("live sandbox mode transaction", () => { cause: recoveryError, }); }); + + function modeReleaseHarness(previousMode: "off" | "full") { + const events: string[] = []; + const generation = "gateway-generation"; + const proof = { + gatewayGeneration: generation, + nodeId: "node", + secretBase64: "secret", + readinessTransitionId: "transition", + policyFingerprint: "policy", + }; + const hostStatus = { + processRunning: true, + processId: 321, + gatewayGeneration: generation, + requestedStrength: previousMode as "off" | "full", + policyFingerprint: proof.policyFingerprint, + }; + const rollback = vi.fn(() => events.push("instructions:rollback")); + const synchronize = vi.fn((enabled: boolean) => { + events.push(`instructions:${enabled}`); + return { updatedFiles: [], rollback }; + }); + const release = vi.fn(() => events.push("ingress:release")); + let captured: LiveSandboxModeHooks | undefined; + const context = { + testChangeWindowsNodeMxcMode: undefined as + | ((params: { enabled: boolean }) => Promise) + | undefined, + windowsNodeMxcUnsupportedWindows: null, + getWindowsNodeMxcSelection: () => ({ requestedMode: previousMode }), + getWindowsNodeMxcRequestedMode: () => previousMode, + isApplicationServiceReady: () => true, + gwClient: { connected: true, connectionGeneration: 7 }, + gatewayProcess: { pid: 123 }, + gatewayGenerationId: generation, + gatewayHttpReadyGeneration: generation, + gatewaySpawnedByUs: true, + isManagedGatewayProcessAlive: () => true, + bundledWindowsNodeGeneration: 4, + bundledWindowsNodeHost: { status: () => hostStatus }, + windowsNodeMxcApprovalProofContext: proof, + settingsStore: { get: () => ({}) }, + migrateWeixinRemoteApprovalConfiguration: () => ({}), + agentRosterChangeInProgress: false, + windowsNodeMxcLifecycleState: "idle", + windowsNodeMxcActivationInProgress: true, + beginWindowsNodeMxcLifecycleOperation: vi.fn(), + endWindowsNodeMxcLifecycleOperation: vi.fn(), + notifyRendererApplicationReady: vi.fn(), + windowsNodeMxcLifecycleOperations: { + run: async ( + _descriptor: unknown, + operation: () => Promise, + hooks: { beforeStart: () => void; afterSettled: () => void }, + ) => { + hooks.beforeStart(); + try { + return await operation(); + } finally { + hooks.afterSettled(); + } + }, + }, + applyLiveSandboxMode: async (hooks: LiveSandboxModeHooks) => { + captured = hooks; + return null; + }, + synchronizeWindowsNodeInstructionsForMode: synchronize, + releaseWindowsNodeMxcIngress: release, + setWindowsNodeMxcLifecycleState: (phase: string) => events.push(`phase:${phase}`), + }; + runInNewContext(transitionJs, context); + return { + context, + events, + hostStatus, + synchronize, + release, + rollback, + async capture(enabled: boolean) { + await context.testChangeWindowsNodeMxcMode!({ enabled }); + if (!captured) throw new Error("Mode transition hooks were not captured"); + hostStatus.requestedStrength = enabled ? "full" : "off"; + return captured; + }, + }; + } + + describe("live sandbox mode guidance", () => { + it.each([ + { previous: "off" as const, enabled: true }, + { previous: "full" as const, enabled: false }, + ])("synchronizes guidance before reopening ingress when enabled=$enabled", async (params) => { + const fixture = modeReleaseHarness(params.previous); + const transition = await fixture.capture(params.enabled); + await transition.release(null); + + expect(fixture.events).toEqual([ + `instructions:${params.enabled}`, + "ingress:release", + `phase:${params.enabled ? "active" : "idle"}`, + ]); + expect(fixture.synchronize).toHaveBeenCalledExactlyOnceWith(params.enabled); + expect(fixture.rollback).not.toHaveBeenCalled(); + }); + + it("does not reopen ingress if synchronizing instructions fails", async () => { + const fixture = modeReleaseHarness("full"); + const transition = await fixture.capture(false); + fixture.synchronize.mockImplementationOnce(() => { + throw new Error("SOUL update failed"); + }); + await expect(transition.release(null)).rejects.toThrow("SOUL update failed"); + expect(fixture.release).not.toHaveBeenCalled(); + }); + + it("rolls instructions back if reopening ingress fails", async () => { + const fixture = modeReleaseHarness("off"); + const transition = await fixture.capture(true); + fixture.release.mockImplementationOnce(() => { + throw new Error("ingress failed"); + }); + await expect(transition.release(null)).rejects.toThrow("ingress failed"); + expect(fixture.rollback).toHaveBeenCalledOnce(); + }); + + it("surfaces both ingress and instruction rollback failures", async () => { + const fixture = modeReleaseHarness("off"); + const transition = await fixture.capture(true); + const ingressError = new Error("ingress failed"); + const rollbackError = new Error("rollback failed"); + fixture.release.mockImplementationOnce(() => { + throw ingressError; + }); + fixture.rollback.mockImplementationOnce(() => { + throw rollbackError; + }); + await expect(transition.release(null)).rejects.toMatchObject({ + errors: [ingressError, rollbackError], + cause: rollbackError, + }); + }); + + it("rejects a mode change while an agent roster change is in progress", async () => { + const fixture = modeReleaseHarness("off"); + fixture.context.agentRosterChangeInProgress = true; + await expect(fixture.capture(true)).rejects.toThrow( + "Wait for the current agent roster change to finish", + ); + expect(fixture.synchronize).not.toHaveBeenCalled(); + }); + }); }); diff --git a/desktop/src/windows-node-mxc-powershell-scope.test.ts b/desktop/src/windows-node-mxc-powershell-scope.test.ts index 280d026..f37cb34 100644 --- a/desktop/src/windows-node-mxc-powershell-scope.test.ts +++ b/desktop/src/windows-node-mxc-powershell-scope.test.ts @@ -6,6 +6,7 @@ import { POWERSHELL_FILESYSTEM_INITIALIZER, validatePowerShellFilesystemInitialization, } from "./windows-node-mxc-powershell-scope"; +import { WINDOWS_NODE_MXC_POWERSHELL_OPERATIONS_INSTRUCTIONS } from "./windows-node-command-instructions"; import { normalizeWindowsNodeMxcGatewayApproval } from "./windows-node-mxc"; import { normalizeWeixinRemoteApprovalOwner, @@ -38,6 +39,23 @@ function preview(payload: string) { } describe("exact contained PowerShell prepared initialization", () => { + it("initializes the exact single-operation example in agent guidance", () => { + const example = WINDOWS_NODE_MXC_POWERSHELL_OPERATIONS_INSTRUCTIONS.match( + /```\nREM \[declare-access\]rw:(.+?)\[\/declare-access\]\n(.+)\n```/, + ); + if (!example) throw new Error("Missing declared PowerShell guidance example"); + const exampleAccess = [{ access: "rw" as const, path: example[1] }]; + const argv = [cmd, "/d", "/s", "/c", example[2]]; + const initialization = createPowerShellFilesystemInitialization(argv, cmd, exampleAccess); + + expect(createPowerShellFilesystemInitialization(argv, cmd, [])).toBeNull(); + expect(initialization?.form).toBe("cmd"); + expect(initialization?.originalArgv).toEqual(argv); + expect(initialization?.finalArgv.at(-1)).toContain( + `${POWERSHELL_FILESYSTEM_INITIALIZER}Remove-Item -LiteralPath 'C:\\work\\old.txt'`, + ); + }); + it.each([false, true])( "retains original literal bytes and independently regenerates form nested=%s", (nested) => { diff --git a/docs/experimental-windows-node-mxc.md b/docs/experimental-windows-node-mxc.md index 6a91223..78c6860 100644 --- a/docs/experimental-windows-node-mxc.md +++ b/docs/experimental-windows-node-mxc.md @@ -90,13 +90,43 @@ enforce those grants. If a conversation contains a stale declaration, its contents remain bound to command consent but are not checked as MXC folder paths and do not restrict host execution. -Generated agent guidance also covers permission-denied recovery: when contained -`exec` fails with a filesystem permission error, the agent should use the +MicroClaw seeds managed agents' `SOUL.md` files according to the sandbox mode +at startup and when an agent is added. A successful live mode change also +updates those files before reopening ingress. Full mode includes the generated +MXC guidance; Off mode removes recognized, unmodified MXC sections while keeping +mode-independent guidance. User-customized sections are preserved and may +still mention MXC in Off mode. The Gateway refreshes bootstrap files for +subsequent turns when it injects them; an in-progress turn and existing +conversation history are not rewritten. + +The Full-mode guidance covers permission-denied recovery: when contained `exec` +fails with a filesystem permission error, the agent should use the reported path to request the smallest necessary directory with `[declare-access]` and fresh consent. It must check for partial effects before retrying, ask when the path is unclear, and never broaden grants repeatedly or bypass MXC. This is -agent guidance, not automatic command rewriting or permission granting; existing -workspaces receive the new section on startup without replacing custom guidance. +agent guidance, not automatic command rewriting or permission granting. + +For ordinary file discovery, the generated guidance prefers available +Gateway-native tools such as `ls` and `read` when their host-side boundary is +acceptable. Those tools run outside MXC; they are not a way to bypass a denied +operation or a request for containment. For contained commands it recommends an +approved `workdir` instead of an absolute CMD `cd`, without claiming that this +fixes other volume-root metadata failures. For missing executables, it suggests +finding the actual installation directory with Gateway `ls` where permitted, +then requesting only that existing directory read-only for a contained command. +An inaccessible listing or an absent sandboxed `where` result does not prove a +program is uninstalled. + +Declarations must name existing directories: to create a new destination, the +guidance selects an appropriately scoped existing parent rather than the missing +child, and checks both declarations and the working directory after +`cwd-not-found`. For PowerShell `Remove-Item`, `Move-Item`, and `Rename-Item`, +it prefers separate literal-path operations where semantics permit, so eligible +commands can use the existing scoped initialization. The initializer requires +explicit RW declarations covering each target even when its directory is +already approved; declaring it does not itself grant access. Complex scripts +that need initialization must include it in the same approved PowerShell +invocation; a separate invocation does not retain the initialized drive. **Ask when needed** uses the upstream Windows Node command allowlist and asks for commands that are not already permitted. **Allow always** disables those