diff --git a/docs/src/content/docs/docs/guides/mcp-proxy.mdx b/docs/src/content/docs/docs/guides/mcp-proxy.mdx index cf18ee36..33fd6091 100644 --- a/docs/src/content/docs/docs/guides/mcp-proxy.mdx +++ b/docs/src/content/docs/docs/guides/mcp-proxy.mdx @@ -404,9 +404,10 @@ the authored URL remains its identity. Changing a tenant header selects a separate grant. A declaration with headers may need one new sign-in when upgrading from a version that did not partition its cache by headers. -Removing an installed or declared-only profile removes its OAuth subtree with -its other profile-owned runtime state. Cleanup rejects symbolic-link or -non-directory OAuth roots and retains retryable state on failure. +`allagents profile remove ` keeps the profile's OAuth subtree. Add +`--purge-session-data` to delete it for an installed or declared-only profile. +Purge rejects symbolic-link or non-directory OAuth roots and retains retryable +state on failure. ## Prerequisites diff --git a/docs/src/content/docs/docs/reference/cli.mdx b/docs/src/content/docs/docs/reference/cli.mdx index 73a93340..082f5c8c 100644 --- a/docs/src/content/docs/docs/reference/cli.mdx +++ b/docs/src/content/docs/docs/reference/cli.mdx @@ -112,7 +112,7 @@ use [`self update`](#self-update). allagents profile install [--yes] [--dry-run] [--offline] allagents profile list allagents profile status [name] -allagents profile remove [--yes] [--dry-run] [--offline] +allagents profile remove [--yes] [--dry-run] [--offline] [--purge-session-data] ``` Profile declarations exist only in `~/.allagents/workspace.yaml`. `install` @@ -132,10 +132,21 @@ installed, missing, drifted, partial, unsupported, and declaration-missing resources. Omitting the name opens a selector only on an interactive terminal; non-interactive and JSON callers must provide it. -Removal works from ownership state even after the declaration is deleted. It -deletes only unchanged managed resources, releases referenced resources, and -retains modified, shared, failed, or uncorroborated resources for inspection -and retry. There is intentionally no `allagents profile update`; use repeatable +Removal uninstalls owned launchers, plugins, and generated configuration where +ownership can be verified. It works from ownership state even after the +declaration is deleted and leaves `workspace.yaml` unchanged. Client runtime +directories, session data, and profile OAuth credentials are retained by +default, including with `--yes`. + +Pass `--purge-session-data` to recursively delete eligible owned client roots +and remove the profile's OAuth state. This can delete untracked files inside +those owned roots. Roots with referenced or modified managed resources are +retained. Preview either plan with `--dry-run`, including in JSON mode. +`--yes` skips confirmation for the selected plan. + +For an intentional purge, select the flag when uninstalling or when retrying a +failed purge. Successful removal releases ownership of retained client roots. +There is intentionally no `allagents profile update`; use repeatable `allagents update --profile `. ### status diff --git a/docs/src/content/docs/docs/reference/clients.mdx b/docs/src/content/docs/docs/reference/clients.mdx index 952cc84d..4458074c 100644 --- a/docs/src/content/docs/docs/reference/clients.mdx +++ b/docs/src/content/docs/docs/reference/clients.mdx @@ -150,9 +150,9 @@ remote MCP declarations share the generated `opencode.json`; portable resolved only by the runtime. Profile cleanup removes unchanged managed files and OpenCode's exact -runtime-generated `.gitignore`. A modified `.gitignore` or any unrelated file -retains the root and reports a partial removal instead of recursively deleting -unknown content. +runtime-generated `.gitignore` inside an owned profile root. The configuration +directory, modified files, and other runtime data are retained, including with +`--purge-session-data`. ### GitHub Copilot CLI @@ -230,11 +230,12 @@ inventory inspection but are not treated as AllAgents-managed user or project plugins. The isolated root also holds Claude-managed credentials, sessions, trust state, -plugin caches, and runtime metadata. Removing an AllAgents-created profile -intentionally removes that isolated runtime state after native cleanup. Ambient -`~/.claude`, project files, and platform credential stores remain outside the -filesystem cleanup boundary; inherited authentication environment variables -can still override the selected profile login. +plugin caches, and runtime metadata. Profile removal retains that runtime state +by default. Use `--purge-session-data` to recursively clean up an eligible owned +root after native cleanup. Ambient `~/.claude`, project files, and platform +credential stores remain outside the filesystem cleanup boundary. Inherited +authentication environment variables can still override the selected profile +login. ### Codex @@ -263,10 +264,10 @@ Isolated profile file installation does not currently translate hook declarations; use native installation when a profile plugin requires them. `CODEX_HOME` also contains Codex credentials, sessions, logs, and caches. -Recursive cleanup is limited to a client root AllAgents created for this -profile; removing that profile intentionally removes its isolated runtime -state. Ambient `~/.codex`, project files, and operating-system keyrings remain -outside the cleanup boundary. +Profile removal retains this runtime state by default. With +`--purge-session-data`, recursive cleanup is limited to an eligible owned +client root for the selected profile. Ambient `~/.codex`, project files, and +operating-system keyrings remain outside the cleanup boundary. ### Pi diff --git a/docs/src/content/docs/docs/reference/configuration.mdx b/docs/src/content/docs/docs/reference/configuration.mdx index f42f4790..e4c8b65a 100644 --- a/docs/src/content/docs/docs/reference/configuration.mdx +++ b/docs/src/content/docs/docs/reference/configuration.mdx @@ -348,8 +348,8 @@ never written to plans, launchers, profile state, or generated configuration. Profile MCP is materialized inside the profile root. Codex writes `clients/codex/home/.config.toml`; Copilot writes `clients/copilot/home/mcp-config.json`. Proxied HTTP servers share OAuth only -inside that profile, under `oauth-proxy/`. Removing the profile removes -that profile-owned OAuth state. +inside that profile, under `oauth-proxy/`. Profile removal retains +that OAuth state by default. Pass `--purge-session-data` to delete it. OpenCode profile settings accept `model`, `small_model`, `default_agent`, `username`, `share`, `autoupdate`, `snapshot`, `subagent_depth`, `logLevel`, diff --git a/src/cli/commands/profile.ts b/src/cli/commands/profile.ts index ae77a7cb..40abfaac 100644 --- a/src/cli/commands/profile.ts +++ b/src/cli/commands/profile.ts @@ -119,10 +119,12 @@ type ProfileSelectionKind = 'install' | 'status' | 'remove'; function runtimeOptions(flags: { readonly offline?: boolean; readonly dryRun?: boolean; + readonly purgeSessionData?: boolean; }): ProfileRuntimeOptions { return { ...(flags.offline ? { offline: true } : {}), ...(flags.dryRun ? { dryRun: true } : {}), + ...(flags.purgeSessionData ? { purgeSessionData: true } : {}), }; } @@ -240,6 +242,7 @@ async function executeMutation( readonly yes: boolean; readonly dryRun: boolean; readonly offline: boolean; + readonly purgeSessionData?: boolean; }, dependencies: ProfileCommandDependencies, runtime: ProfileCommandRuntime, @@ -443,6 +446,10 @@ export function createProfileCommand( short: 'y', description: 'Apply without asking for confirmation', }), + purgeSessionData: flag({ + long: 'purge-session-data', + description: 'Also delete session data in owned profile runtime roots', + }), dryRun: flag({ long: 'dry-run', description: 'Display the plan without making changes', diff --git a/src/cli/metadata/profile.ts b/src/cli/metadata/profile.ts index 23524b62..16f5a24a 100644 --- a/src/cli/metadata/profile.ts +++ b/src/cli/metadata/profile.ts @@ -204,17 +204,25 @@ export const profileRemoveMeta: AgentCommandMeta = { command: 'profile remove', description: 'Remove an installed or declared global profile safely', whenToUse: - 'When you want AllAgents to remove resources and profile-owned OAuth credentials for one installed or declared user profile while retaining referenced resources', + 'When you want to uninstall one profile and keep its session data. Use --purge-session-data to also delete eligible owned runtime data.', examples: [ 'allagents profile remove work', 'allagents profile remove work --dry-run', 'allagents profile remove work --yes', - 'allagents --json profile remove work --yes', + 'allagents --json profile remove work --purge-session-data --yes', ], expectedOutput: - 'Displays a redacted deterministic removal plan, asks before applying unless --yes is supplied, removes profile-owned OAuth credentials even for a declared-only profile, and reports removed, retained, unchanged, or failed resources.', + 'Displays which resources and runtime roots will be removed or retained and asks before applying unless --yes is supplied. Keeps session data and profile OAuth credentials by default.', positionals: profileNamePositional, - options: mutationOptions, + options: [ + ...mutationOptions, + { + flag: '--purge-session-data', + type: 'boolean', + description: + 'Also delete eligible owned client runtime roots and profile OAuth state. Omit to keep session data.', + }, + ], outputSchema: { profile: 'string', operation: 'remove', diff --git a/src/core/profile/adapters/opencode.ts b/src/core/profile/adapters/opencode.ts index 4fff37b6..a12f2784 100644 --- a/src/core/profile/adapters/opencode.ts +++ b/src/core/profile/adapters/opencode.ts @@ -4,7 +4,7 @@ import { ProfileNameSchema, } from '../../../models/workspace-config.js'; import type { FileOnlyProfileAdapter } from '../types.js'; -import { removeManagedFile, sha256Fingerprint } from '../files.js'; +import { sha256Fingerprint } from '../files.js'; import type { ProfileClientContext, ProfileContextOptions, @@ -181,14 +181,12 @@ export class OpenCodeProfileAdapter implements FileOnlyProfileAdapter { return null; } - async prepareRootCleanup(context: ProfileClientContext): Promise { + rootCleanupFile(context: ProfileClientContext) { assertOpenCodeContext(context); - await removeManagedFile({ - root: context.root, + return { path: join(context.root, '.gitignore'), - ownership: 'managed', - expectedFingerprint: sha256Fingerprint(GENERATED_GITIGNORE), - }); + fingerprint: sha256Fingerprint(GENERATED_GITIGNORE), + }; } } diff --git a/src/core/profile/index.ts b/src/core/profile/index.ts index 90d1d151..43f42041 100644 --- a/src/core/profile/index.ts +++ b/src/core/profile/index.ts @@ -11,6 +11,7 @@ export interface ProfileRuntimeOptions { readonly platform?: NodeJS.Platform; readonly offline?: boolean; readonly dryRun?: boolean; + readonly purgeSessionData?: boolean; } export type ProfileStepKind = @@ -66,7 +67,7 @@ export interface ProfilePlanClient { export interface ProfilePlanStep { - readonly client: ClientType; + readonly client: ClientType | 'profile'; readonly kind: ProfileStepKind; /** Display-safe native identity or absolute filesystem path. */ readonly identity: string; @@ -97,7 +98,7 @@ export type ProfileApplyStepStatus = | 'failed'; export interface ProfileApplyStep { - readonly client: ClientType; + readonly client: ProfilePlanStep['client']; readonly kind: ProfileStepKind; readonly identity: string; readonly status: ProfileApplyStepStatus; diff --git a/src/core/profile/manager.ts b/src/core/profile/manager.ts index 42b47312..5dca8507 100644 --- a/src/core/profile/manager.ts +++ b/src/core/profile/manager.ts @@ -26,6 +26,7 @@ import type { ProfileApplyStepStatus, ProfilePlan, ProfilePlanAction, + ProfilePlanStep, ProfileRuntimeOptions, ProfileStatusResult, } from './index.js'; @@ -83,14 +84,14 @@ function resultStatus(action: ProfilePlanAction): ProfileApplyStepStatus { } function appliedStep( - step: InternalProfilePlanStep, + step: ProfilePlanStep, status: ProfileApplyStepStatus, error?: string, ): ProfileApplyStep { return { - client: step.public.client, - kind: step.public.kind, - identity: step.public.identity, + client: step.client, + kind: step.kind, + identity: step.identity, status, ...(error && { error }), }; @@ -184,6 +185,10 @@ async function removeEmptyManagedRoot(root: string): Promise { if (!entry.isDirectory() || entry.isSymbolicLink()) continue; await removeEmptyManagedRoot(join(root, entry.name)); } + return removeEmptyDirectory(root); +} + +async function removeEmptyDirectory(root: string): Promise { try { await rmdir(root); return true; @@ -194,23 +199,6 @@ async function removeEmptyManagedRoot(root: string): Promise { } } -async function removeProfileOAuthProxyRoot(profileRoot: string): Promise { - const oauthProxyRoot = join(profileRoot, 'oauth-proxy'); - await assertSafeProfilePath(profileRoot, oauthProxyRoot); - const stats = await lstat(oauthProxyRoot).catch((error) => { - if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; - throw error; - }); - if (!stats) return; - if (stats.isSymbolicLink() || !stats.isDirectory()) { - throw new Error( - `Profile OAuth proxy root is not a real directory: ${oauthProxyRoot}`, - ); - } - await assertSafeProfilePath(profileRoot, oauthProxyRoot); - await rm(oauthProxyRoot, { recursive: true, force: true }); -} - async function removeOwnedManagedRoot( root: string, expectedRoot: string, @@ -229,6 +217,7 @@ async function removeOwnedManagedRoot( if (stats.isSymbolicLink() || !stats.isDirectory()) { throw new Error(`Managed profile root is not a real directory: ${root}`); } + await assertSafeProfilePath(expectedRoot, root); await rm(root, { recursive: true, force: true }); } @@ -271,7 +260,15 @@ async function applyOneStep( return { status: 'removed' }; } await assertSafeProfilePath(expectedRoot, step.path); - await adapter.prepareRootCleanup?.(step.context); + const generated = adapter.rootCleanupFile?.(step.context); + if (generated) { + await removeManagedFile({ + root: step.context.root, + path: generated.path, + ownership: 'managed', + expectedFingerprint: generated.fingerprint, + }); + } return { status: (await removeEmptyManagedRoot(step.path)) ? 'removed' @@ -497,8 +494,8 @@ function dryRunResult(internal: InternalProfilePlan): ProfileApplyResult { operation: internal.public.operation, status: internal.public.operation === 'remove' ? 'removed' : 'installed', success: true, - steps: internal.steps.map((step) => - appliedStep(step, resultStatus(step.public.action)), + steps: internal.public.steps.map((step) => + appliedStep(step, resultStatus(step.action)), ), warnings: internal.public.warnings, }; @@ -570,7 +567,7 @@ export async function applyProfilePlan( internal.public.operation === 'remove', ); state = await checkpoint(internal, state, completed, dependencies); - results.push(appliedStep(step, applied.status)); + results.push(appliedStep(step.public, applied.status)); } catch (error) { const message = safeError(error); const failureTransition = @@ -587,7 +584,7 @@ export async function applyProfilePlan( const checkpointMessage = safeError(checkpointError); results.push( appliedStep( - step, + step.public, 'failed', `${message}; state checkpoint failed: ${checkpointMessage}`, ), @@ -602,7 +599,7 @@ export async function applyProfilePlan( error: `${message}; state checkpoint failed: ${checkpointMessage}`, }; } - results.push(appliedStep(step, 'failed', message)); + results.push(appliedStep(step.public, 'failed', message)); return { profile: plan.profile, operation: plan.operation, @@ -624,8 +621,31 @@ export async function applyProfilePlan( ); if (plan.operation === 'remove') { if (!retainedManaged) { + const oauth = internal.oauthCleanup; + if (oauth?.action === 'remove') { + try { + await removeOwnedManagedRoot( + oauth.identity, + join(profileRoot, 'oauth-proxy'), + ); + results.push(appliedStep(oauth, 'removed')); + } catch (error) { + const message = safeError(error); + results.push(appliedStep(oauth, 'failed', message)); + return { + profile: plan.profile, + operation: plan.operation, + status: 'partial', + success: false, + steps: results, + warnings: plan.warnings, + error: message, + }; + } + } else if (oauth) { + results.push(appliedStep(oauth, 'retained')); + } try { - await removeProfileOAuthProxyRoot(profileRoot); const statePath = getProfileStatePath(profileRoot); await assertSafeProfilePath(profileRoot, statePath); await rm(statePath, { force: true }); @@ -643,7 +663,8 @@ export async function applyProfilePlan( } const warnings = [...plan.warnings]; try { - await removeEmptyManagedRoot(profileRoot); + // Retained roots and even empty runtime directories may be user data. + await removeEmptyDirectory(profileRoot); } catch (error) { warnings.push( `Profile resources were removed, but the empty profile directory could not be pruned: ${safeError(error)}`, diff --git a/src/core/profile/plan.ts b/src/core/profile/plan.ts index 557a706e..903501fc 100644 --- a/src/core/profile/plan.ts +++ b/src/core/profile/plan.ts @@ -74,6 +74,7 @@ export interface ResolvedProfileRuntime { readonly platform: NodeJS.Platform; readonly offline: boolean; readonly dryRun: boolean; + readonly purgeSessionData: boolean; } export interface ProfilePlanDependencies { @@ -82,7 +83,7 @@ export interface ProfilePlanDependencies { } export interface InternalProfilePlanStep { - readonly public: ProfilePlanStep; + readonly public: ProfilePlanStep & { readonly client: ClientType }; readonly relationship: ProfileResourceRelationship; readonly root?: string; readonly path?: string; @@ -106,6 +107,7 @@ export interface InternalProfilePlan { readonly adapters: ReadonlyMap; readonly priorState: ProfileState | null; readonly steps: readonly InternalProfilePlanStep[]; + readonly oauthCleanup?: ProfilePlanStep; } const INTERNAL_PLANS = new WeakMap(); @@ -127,6 +129,7 @@ export function resolveProfileRuntimeOptions( platform: options.platform ?? process.platform, offline: options.offline ?? false, dryRun: options.dryRun ?? false, + purgeSessionData: options.purgeSessionData ?? false, }); } @@ -283,14 +286,14 @@ function relationship(input: { }; } -function publicStep( - client: ClientType, +function publicStep( + client: Client, kind: ProfileStepKind, identity: string, action: ProfilePlanAction, refs: { requestedRef?: string; resolvedRef?: string } = {}, detail?: ProfilePlanStepDetail, -): ProfilePlanStep { +): ProfilePlanStep & { readonly client: Client } { return Object.freeze({ client, kind, @@ -722,6 +725,7 @@ export async function planProfileOperation( const warnings: string[] = []; const steps: InternalProfilePlanStep[] = []; + let oauthCleanup: ProfilePlanStep | undefined; const desiredKeys = new Set(); const inspections = new Map(); const inspectionFor = async (client: ClientType) => { @@ -843,8 +847,43 @@ export async function planProfileOperation( context, }); } else if (resource.kind === 'root') { + const rootPath = resource.path ?? resource.identity; + const generated = + resource.ownership === 'managed' && + resolve(rootPath) === resolve(managedContextRoot(context)) + ? adapter.rootCleanupFile?.(context) + : undefined; + if ( + generated && + !previousResource(priorState, 'file', resource.client, generated.path) + ) { + await assertSafeProfilePath(context.root, generated.path); + const fingerprint = await fingerprintProfileFile(generated.path); + if (fingerprint !== null) { + const file = relationship({ + kind: 'file', + client: resource.client, + identity: generated.path, + path: generated.path, + ownership: 'managed', + cleanup: 'file', + fingerprint: generated.fingerprint, + }); + steps.push(staleFileStep(file, fingerprint, context.root, context)); + } + } + const retainedResource = steps.some( + (step) => + step.public.client === resource.client && + step.public.action === 'retain', + ); const action: ProfilePlanAction = - resource.ownership === 'managed' ? 'remove' : 'retain'; + runtime.purgeSessionData && + resource.ownership === 'managed' && + adapter.capabilities.recursiveRootCleanup && + !retainedResource + ? 'remove' + : 'retain'; steps.push({ public: publicStep( resource.client, @@ -854,7 +893,7 @@ export async function planProfileOperation( ), relationship: resource, root: resource.path ?? managedContextRoot(context), - path: resource.path ?? resource.identity, + path: rootPath, context, }); } else { @@ -870,6 +909,19 @@ export async function planProfileOperation( }); } } + const oauthRoot = join(profileRoot, 'oauth-proxy'); + const oauthExists = await lstat(oauthRoot).catch((error) => { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; + throw error; + }); + if (oauthExists) { + oauthCleanup = publicStep( + 'profile', + 'root', + oauthRoot, + runtime.purgeSessionData ? 'remove' : 'retain', + ); + } } else if (declaration) { for (const declaredClient of declaration.clients) { const client = declaredClient.name; @@ -1588,7 +1640,10 @@ export async function planProfileOperation( operation, declarationDigest: digest, clients: Object.freeze(plannedClients), - steps: Object.freeze(orderedSteps.map((step) => step.public)), + steps: Object.freeze([ + ...orderedSteps.map((step) => step.public), + ...(oauthCleanup ? [oauthCleanup] : []), + ]), warnings: Object.freeze( warnings.map( (warning) => @@ -1605,6 +1660,7 @@ export async function planProfileOperation( adapters, priorState, steps: Object.freeze(orderedSteps), + ...(oauthCleanup && { oauthCleanup }), }); INTERNAL_PLANS.set(result, internal); return result; diff --git a/src/core/profile/types.ts b/src/core/profile/types.ts index 2b304e4e..a0bfcb0f 100644 --- a/src/core/profile/types.ts +++ b/src/core/profile/types.ts @@ -163,8 +163,11 @@ interface ProfileAdapterBase { input: ProfileSerializationInput, ): ProfilePlannedFile | null; - /** Remove adapter-known generated files before generic empty-directory cleanup. */ - prepareRootCleanup?(context: ProfileClientContext): Promise; + /** Identify a generated file whose exact contents corroborate cleanup ownership. */ + rootCleanupFile?(context: ProfileClientContext): { + readonly path: string; + readonly fingerprint: string; + }; } export interface NativeProfileAdapter extends ProfileAdapterBase { diff --git a/tests/unit/cli/profile-command.test.ts b/tests/unit/cli/profile-command.test.ts index 8dda2b0a..ed4a1880 100644 --- a/tests/unit/cli/profile-command.test.ts +++ b/tests/unit/cli/profile-command.test.ts @@ -880,6 +880,23 @@ describe('profile root registration', () => { expect(proc.stderr.toString()).toContain('Unknown arguments'); }); + test('advertises the explicit purge only on remove help', () => { + for (const operation of ['install', 'remove']) { + const proc = Bun.spawnSync( + ['bun', 'run', cliEntry, '--json', 'profile', operation, '--help'], + { stdout: 'pipe', stderr: 'pipe' }, + ); + expect(proc.exitCode).toBe(0); + const help = JSON.parse(proc.stdout.toString()) as { + options: Array<{ flag: string }>; + }; + const hasPurge = help.options.some( + ({ flag }) => flag === '--purge-session-data', + ); + expect(hasPurge).toBe(operation === 'remove'); + } + }); + test('does not register a profile update command', () => { const proc = Bun.spawnSync( ['bun', 'run', cliEntry, '--json', 'profile', 'update'], diff --git a/tests/unit/core/profile/manager.test.ts b/tests/unit/core/profile/manager.test.ts index 7489ab56..1f6b840b 100644 --- a/tests/unit/core/profile/manager.test.ts +++ b/tests/unit/core/profile/manager.test.ts @@ -1186,8 +1186,9 @@ describe('profile lifecycle manager', () => { root.path = unrelated; await writeFile(statePath, `${JSON.stringify(state, null, 2)}\n`, 'utf8'); - const removal = await planProfileOperation('work', 'remove', test.options, deps); - const result = await applyProfilePlan(removal, test.options, deps); + const options = { ...test.options, purgeSessionData: true }; + const removal = await planProfileOperation('work', 'remove', options, deps); + const result = await applyProfilePlan(removal, options, deps); expect(result.success).toBe(false); expect(result.error).toContain('outside the selected client root'); expect(await readFile(sentinel, 'utf8')).toBe('owned by user'); @@ -1206,8 +1207,12 @@ describe('profile lifecycle manager', () => { const destination = install.steps.find((step) => step.kind === 'file') ?.identity as string; await writeFile(destination, 'modified', 'utf8'); - const removal = await planProfileOperation('work', 'remove', test.options, deps); - const result = await applyProfilePlan(removal, test.options, deps); + const options = { ...test.options, purgeSessionData: true }; + const removal = await planProfileOperation('work', 'remove', options, deps); + expect(removal.steps.find((step) => step.kind === 'root')?.action).toBe( + 'retain', + ); + const result = await applyProfilePlan(removal, options, deps); expect(result.status).toBe('removed'); expect(result.success).toBe(true); expect(await readFile(destination, 'utf8')).toBe('modified'); @@ -1237,9 +1242,6 @@ describe('profile lifecycle manager', () => { const removed = await applyProfilePlan(removePlan, test.options, deps); expect(removed.status).toBe('removed'); await expect(stat(join(test.home, '.allagents', 'profiles', 'work', 'state.json'))).rejects.toThrow(); - await expect( - stat(join(test.home, '.allagents', 'profiles', 'work')), - ).rejects.toThrow(); }); it('excludes empty and invalid profile directories without losing declared or installed profiles', async () => { @@ -1293,7 +1295,78 @@ describe('profile lifecycle manager', () => { ]); }); - it('removes runtime artifacts inside an AllAgents-owned profile root', async () => { + it('retains runtime data while uninstalling owned launchers and files by default', async () => { + const test = await fixture(); + const local = await pluginFixture(test.workspaceDirectory); + await writeWorkspace(test.userConfigPath, { + work: { + clients: [{ name: 'omp', launcher: 'omp-work' }], + plugins: [local], + mcpServers: { demo: { command: 'fixture-mcp' } }, + }, + }); + const deps = dependencies(new MemoryProfileAdapter('omp', test.home)); + const install = await planProfileOperation( + 'work', + 'install', + test.options, + deps, + ); + expect((await applyProfilePlan(install, test.options, deps)).success).toBe( + true, + ); + const clientRoot = install.clients[0]?.root as string; + const sessions = join(clientRoot, 'sessions'); + const history = join(sessions, 'current.jsonl'); + const empty = join(sessions, 'empty'); + const oauthToken = join( + test.home, + '.allagents', + 'profiles', + 'work', + 'oauth-proxy', + 'tokens.json', + ); + await mkdir(empty, { recursive: true }); + await mkdir(dirname(oauthToken), { recursive: true }); + await writeFile(history, 'session history', 'utf8'); + await writeFile(oauthToken, '{}', 'utf8'); + const owned = install.steps.filter((step) => step.kind !== 'root'); + expect(owned.map((step) => step.kind)).toEqual(['file', 'mcp', 'launcher']); + + const removal = await planProfileOperation( + 'work', + 'remove', + test.options, + deps, + ); + const plannedRoots = removal.steps.filter((step) => step.kind === 'root'); + expect(plannedRoots.map((step) => step.action)).toEqual([ + 'retain', + 'retain', + ]); + const result = await applyProfilePlan( + removal, + { ...test.options, purgeSessionData: true }, + deps, + ); + expect(result.status).toBe('removed'); + const appliedRoots = result.steps.filter((step) => step.kind === 'root'); + expect(appliedRoots.map((step) => step.status)).toEqual([ + 'retained', + 'retained', + ]); + for (const step of owned) { + await expect(stat(step.identity)).rejects.toThrow(); + } + expect(await readFile(history, 'utf8')).toBe('session history'); + expect((await stat(empty)).isDirectory()).toBe(true); + expect(await readFile(oauthToken, 'utf8')).toBe('{}'); + const status = await getProfileStatus('work', test.options, deps); + expect(status.installed).toBe(false); + }); + + it('purges runtime artifacts inside an AllAgents-owned profile root when requested', async () => { const test = await fixture(); await writeWorkspace(test.userConfigPath, { work: { clients: [{ name: 'pi' }], plugins: [] }, @@ -1306,13 +1379,44 @@ describe('profile lifecycle manager', () => { await mkdir(join(clientRoot, 'logs'), { recursive: true }); await writeFile(join(clientRoot, 'logs', 'runtime.log'), 'runtime state', 'utf8'); - const removal = await planProfileOperation('work', 'remove', test.options, deps); + const options = { ...test.options, purgeSessionData: true }; + const removal = await planProfileOperation('work', 'remove', options, deps); expect((await applyProfilePlan(removal, test.options, deps)).status).toBe( 'removed', ); await expect(stat(clientRoot)).rejects.toThrow(); }); + it('preserves an existing unowned client root even with an explicit purge', async () => { + const test = await fixture(); + await writeWorkspace(test.userConfigPath, { + work: { clients: [{ name: 'pi' }], plugins: [] }, + }); + const pi = new MemoryProfileAdapter('pi', test.home); + const deps = dependencies(pi); + const root = pi.resolveContext('work', test.options).root; + const sessions = join(root, 'sessions'); + await mkdir(sessions, { recursive: true }); + const install = await planProfileOperation( + 'work', + 'install', + test.options, + deps, + ); + expect((await applyProfilePlan(install, test.options, deps)).success).toBe( + true, + ); + + const options = { ...test.options, purgeSessionData: true }; + const removal = await planProfileOperation('work', 'remove', options, deps); + expect(removal.steps.find((step) => step.identity === root)?.action).toBe( + 'retain', + ); + const result = await applyProfilePlan(removal, options, deps); + expect(result.status).toBe('removed'); + expect((await stat(sessions)).isDirectory()).toBe(true); + }); + it('removes profile-owned OAuth state while preserving unrelated residue', async () => { const test = await fixture(); await writeWorkspace(test.userConfigPath, { @@ -1336,15 +1440,17 @@ describe('profile lifecycle manager', () => { await writeFile(join(oauthRoot, 'server', 'tokens.json'), '{}', 'utf8'); await writeFile(residue, 'keep', 'utf8'); - const removal = await planProfileOperation( - 'work', - 'remove', - test.options, - deps, - ); - const result = await applyProfilePlan(removal, test.options, deps); + const options = { ...test.options, purgeSessionData: true }; + const removal = await planProfileOperation('work', 'remove', options, deps); + expect( + removal.steps.find((step) => step.identity === oauthRoot)?.action, + ).toBe('remove'); + const result = await applyProfilePlan(removal, options, deps); expect(result.status).toBe('removed'); + expect( + result.steps.find((step) => step.identity === oauthRoot)?.status, + ).toBe('removed'); await expect(stat(oauthRoot)).rejects.toThrow(); expect(await readFile(residue, 'utf8')).toBe('keep'); await expect(stat(join(profileRoot, 'state.json'))).rejects.toThrow(); @@ -1361,13 +1467,9 @@ describe('profile lifecycle manager', () => { await mkdir(join(oauthRoot, 'server'), { recursive: true }); await writeFile(join(oauthRoot, 'server', 'tokens.json'), '{}', 'utf8'); - const removal = await planProfileOperation( - 'work', - 'remove', - test.options, - deps, - ); - const result = await applyProfilePlan(removal, test.options, deps); + const options = { ...test.options, purgeSessionData: true }; + const removal = await planProfileOperation('work', 'remove', options, deps); + const result = await applyProfilePlan(removal, options, deps); expect(result.status).toBe('removed'); await expect(stat(oauthRoot)).rejects.toThrow(); @@ -1397,13 +1499,9 @@ describe('profile lifecycle manager', () => { await writeFile(externalToken, 'keep', 'utf8'); await symlink(externalRoot, oauthRoot, 'dir'); - const removal = await planProfileOperation( - 'work', - 'remove', - test.options, - deps, - ); - const result = await applyProfilePlan(removal, test.options, deps); + const options = { ...test.options, purgeSessionData: true }; + const removal = await planProfileOperation('work', 'remove', options, deps); + const result = await applyProfilePlan(removal, options, deps); expect(result.status).toBe('partial'); expect(result.success).toBe(false); @@ -1412,15 +1510,9 @@ describe('profile lifecycle manager', () => { expect((await stat(join(profileRoot, 'state.json'))).isFile()).toBe(true); await unlink(oauthRoot); - const retry = await planProfileOperation( - 'work', - 'remove', - test.options, - deps, - ); - expect((await applyProfilePlan(retry, test.options, deps)).status).toBe( - 'removed', - ); + const retry = await planProfileOperation('work', 'remove', options, deps); + const retried = await applyProfilePlan(retry, options, deps); + expect(retried.status).toBe('removed'); }); it('inspects replaced managed roots for state-only clients', async () => { diff --git a/tests/unit/core/profile/opencode.test.ts b/tests/unit/core/profile/opencode.test.ts index b6cc0fa8..8672dd9c 100644 --- a/tests/unit/core/profile/opencode.test.ts +++ b/tests/unit/core/profile/opencode.test.ts @@ -3,6 +3,10 @@ import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { OpenCodeProfileAdapter } from '../../../../src/core/profile/adapters/opencode.js'; +import { + applyProfilePlan, + planProfileOperation, +} from '../../../../src/core/profile/index.js'; import { isNativeProfileAdapter } from '../../../../src/core/profile/types.js'; describe('OpenCode profile adapter', () => { @@ -119,27 +123,90 @@ describe('OpenCode profile adapter', () => { expect('discloseNativeCommands' in adapter).toBe(false); }); - it('removes only the exact runtime-generated gitignore during root cleanup', async () => { - const home = await mkdtemp(join(tmpdir(), 'allagents-opencode-profile-')); - try { - const adapter = new OpenCodeProfileAdapter(); - const context = adapter.resolveContext('review', { - homeDir: home, - workspaceDirectory: home, - }); - await mkdir(context.root, { recursive: true }); - const generatedPath = join(context.root, '.gitignore'); - const generated = - 'node_modules\npackage.json\npackage-lock.json\nbun.lock\n.gitignore'; - await writeFile(generatedPath, generated, 'utf8'); - await adapter.prepareRootCleanup?.(context); - await expect(stat(generatedPath)).rejects.toThrow(); + it.each([ + { + mode: 'default removal', + purgeSessionData: false, + modifyAfterPlan: false, + }, + { mode: 'explicit purge', purgeSessionData: true, modifyAfterPlan: false }, + { + mode: 'file edited after planning', + purgeSessionData: true, + modifyAfterPlan: true, + }, + ])( + 'protects runtime directories and checks the generated gitignore in $mode', + async ({ purgeSessionData, modifyAfterPlan }) => { + const home = await mkdtemp(join(tmpdir(), 'allagents-opencode-profile-')); + try { + const adapter = new OpenCodeProfileAdapter(); + const options = { + homeDir: home, + workspaceDirectory: home, + purgeSessionData, + }; + const workspace = join(home, '.allagents'); + await mkdir(workspace, { recursive: true }); + await writeFile( + join(workspace, 'workspace.yaml'), + [ + 'profiles:', + ' review:', + ' clients:', + ' - name: opencode', + ' settings:', + ' model: demo/model', + '', + ].join('\n'), + ); + const install = await planProfileOperation( + 'review', + 'install', + options, + ); + expect((await applyProfilePlan(install, options)).success).toBe(true); + const { root } = adapter.resolveContext('review', options); + const generatedPath = join(root, '.gitignore'); + const sessions = join(root, 'unknown-runtime', 'empty'); + await mkdir(sessions, { recursive: true }); + const generated = + 'node_modules\npackage.json\npackage-lock.json\nbun.lock\n.gitignore'; - await writeFile(generatedPath, `${generated}\nuser-entry`, 'utf8'); - await adapter.prepareRootCleanup?.(context); - expect(await readFile(generatedPath, 'utf8')).toContain('user-entry'); - } finally { - await rm(home, { recursive: true, force: true }); - } - }); + const modified = `${generated}\nuser-entry`; + await writeFile(generatedPath, modified, 'utf8'); + const modifiedPlan = await planProfileOperation( + 'review', + 'remove', + options, + ); + expect( + modifiedPlan.steps.find((step) => step.identity === generatedPath) + ?.action, + ).toBe('retain'); + + await writeFile(generatedPath, generated, 'utf8'); + const removal = await planProfileOperation('review', 'remove', options); + expect( + removal.steps.find((step) => step.identity === generatedPath)?.action, + ).toBe('remove'); + expect( + removal.steps.find((step) => step.identity === root)?.action, + ).toBe('retain'); + + if (modifyAfterPlan) await writeFile(generatedPath, modified, 'utf8'); + const result = await applyProfilePlan(removal, options); + expect(result.status).toBe('removed'); + if (modifyAfterPlan) { + expect(await readFile(generatedPath, 'utf8')).toBe(modified); + } else { + await expect(stat(generatedPath)).rejects.toThrow(); + } + await expect(stat(join(root, 'opencode.json'))).rejects.toThrow(); + expect((await stat(sessions)).isDirectory()).toBe(true); + } finally { + await rm(home, { recursive: true, force: true }); + } + }, + ); });