From 3b7a9aea2db668367425223cd199d83be9212cec Mon Sep 17 00:00:00 2001 From: Christopher Tso Date: Thu, 26 Nov 2026 13:19:43 +1100 Subject: [PATCH 1/4] feat(cli): rename declared and installed profiles safely --- docs/src/content/docs/docs/reference/cli.mdx | 24 +- src/cli/commands/profile.ts | 77 ++- src/cli/metadata/profile.ts | 35 + src/cli/structured-help.ts | 2 + src/core/mcp-servers.ts | 90 +-- src/core/profile/adapters/claude.ts | 1 + src/core/profile/adapters/codex.ts | 17 + src/core/profile/adapters/opencode.ts | 1 + src/core/profile/manager.ts | 22 + src/core/profile/plan.ts | 2 + src/core/profile/rename-transaction.ts | 259 ++++++++ src/core/profile/rename.ts | 644 +++++++++++++++++++ src/core/profile/types.ts | 7 + src/utils/workspace-config-lock.ts | 100 +++ src/utils/workspace-source-editor.ts | 7 +- src/utils/workspace-writer.ts | 29 +- tests/e2e/profile-rename.test.ts | 253 ++++++++ tests/unit/cli/profile-command.test.ts | 1 + 18 files changed, 1478 insertions(+), 93 deletions(-) create mode 100644 src/core/profile/rename-transaction.ts create mode 100644 src/core/profile/rename.ts create mode 100644 src/utils/workspace-config-lock.ts create mode 100644 tests/e2e/profile-rename.test.ts diff --git a/docs/src/content/docs/docs/reference/cli.mdx b/docs/src/content/docs/docs/reference/cli.mdx index 73a93340..f35a3ee6 100644 --- a/docs/src/content/docs/docs/reference/cli.mdx +++ b/docs/src/content/docs/docs/reference/cli.mdx @@ -113,10 +113,11 @@ allagents profile install [--yes] [--dry-run] [--offline] allagents profile list allagents profile status [name] allagents profile remove [--yes] [--dry-run] [--offline] +allagents profile rename [--yes] [--dry-run] ``` -Profile declarations exist only in `~/.allagents/workspace.yaml`. `install` -and `remove` display a complete plan before mutation and require confirmation; +Profile declarations exist only in `~/.allagents/workspace.yaml`. `install`, +`remove`, and `rename` display a complete plan before mutation and require confirmation; scripts and JSON mode must pass `--yes`. `--dry-run` emits the same resolved plan without writing profile state, client files, native package state, or launchers. @@ -138,6 +139,25 @@ retains modified, shared, failed, or uncorroborated resources for inspection and retry. There is intentionally no `allagents profile update`; use repeatable `allagents update --profile `. +`rename` changes the declaration key and keeps any configured launcher names. +For installed Claude Code, Codex, and OpenCode profiles, it can move a complete, +file-only installation with its isolated client files, session data, and stored +credentials. OpenCode data shared outside the profile stays where OpenCode keeps +it. Uninstalled declarations can be renamed regardless of client. + +Close clients using the profile before applying. Rename stops on a destination +collision, native plugin data, a symbolic link in the profile tree, a modified +launcher, or generated settings that embed a profile selector or the old root. +Codex session databases contain absolute paths and require a separate migration, +as do installed Copilot, Pi, and OMP profiles and installations with partial +state. External references, including T3 provider config +or home paths and custom scripts, need to be updated separately. + +If rename is interrupted after it starts moving files, rerun the same +`allagents profile rename --yes` command to resume. Keep the recovery +record beside `workspace.yaml` and wait until rename completes before editing +the workspace or starting the affected clients. + ### status Show the sync status of all configured plugins and skills. diff --git a/src/cli/commands/profile.ts b/src/cli/commands/profile.ts index ae77a7cb..38ef410d 100644 --- a/src/cli/commands/profile.ts +++ b/src/cli/commands/profile.ts @@ -32,9 +32,11 @@ import { profileInstallMeta, profileListMeta, profileRemoveMeta, + profileRenameMeta, profileStatusMeta, } from '../metadata/profile.js'; import { terminalSafe } from '../terminal-output.js'; +import { applyProfileRename, planProfileRename } from '../../core/profile/rename.js'; export interface ProfileCommandDependencies { readonly planProfileOperation: ( @@ -331,6 +333,58 @@ async function executeList( return success ? 0 : 1; } +async function executeRename( + args: { profile: string; newProfile: string; yes: boolean; dryRun: boolean }, + runtime: ProfileCommandRuntime, +): Promise { + const plan = await planProfileRename(args.profile, args.newProfile, runtimeOptions(args)); + const command = 'profile rename'; + if (!runtime.isJson()) { + const action = plan.recovering ? 'Resume renaming' : 'Rename'; + runtime.print(`${action} profile '${plan.profile}' to '${plan.newProfile}'`); + for (const { kind, from, to } of plan.steps) { + runtime.print(` ${kind}: ${terminalSafe(from)}${from === to ? '' : ` → ${terminalSafe(to)}`}`); + } + for (const warning of plan.warnings) runtime.print(warning); + } + if (args.dryRun) { + if (runtime.isJson()) runtime.printJson({ success: true, command, data: { ...plan } }); + else runtime.print('Dry run; no changes applied.'); + return 0; + } + if (!args.yes) { + if (!runtime.isInteractive() || runtime.isJson()) { + throw new ProfileCommandError( + 'profile rename requires confirmation; rerun with --yes in non-interactive and JSON modes', + 2, + { ...plan, status: 'failed', plan }, + ); + } + const confirmed = await runtime.confirm({ + message: `Rename profile '${plan.profile}' to '${plan.newProfile}' using this plan?`, + }); + if (confirmed !== true) { + runtime.print('Profile rename cancelled.'); + return 0; + } + } + try { + await applyProfileRename(plan); + } catch (error) { + throw new ProfileCommandError( + error instanceof Error ? error.message : String(error), + 1, + { ...plan, status: 'failed', plan }, + ); + } + if (runtime.isJson()) { + runtime.printJson({ success: true, command, data: { ...plan, status: 'renamed', plan } }); + } else { + runtime.print(`Renamed profile '${plan.profile}' to '${plan.newProfile}'.`); + } + return 0; +} + async function executeStatus( name: string | undefined, dependencies: ProfileCommandDependencies, @@ -458,14 +512,35 @@ export function createProfileCommand( ), }); + const renameCmd = command({ + name: 'rename', + description: buildDescription(profileRenameMeta), + args: { + profile: positional({ type: string, displayName: 'old' }), + newProfile: positional({ type: string, displayName: 'new' }), + yes: flag({ + long: 'yes', + short: 'y', + description: 'Apply without asking for confirmation', + }), + dryRun: flag({ + long: 'dry-run', + description: 'Display the plan without making changes', + }), + }, + handler: (args) => + handleCommand('profile rename', runtime, () => executeRename(args, runtime)), + }); + return conciseSubcommands({ name: 'profile', - description: 'Manage global Pi and OMP profiles', + description: 'Manage global agent profiles', cmds: { install: installCmd, list: listCmd, status: statusCmd, remove: removeCmd, + rename: renameCmd, }, }); } diff --git a/src/cli/metadata/profile.ts b/src/cli/metadata/profile.ts index 23524b62..572c990f 100644 --- a/src/cli/metadata/profile.ts +++ b/src/cli/metadata/profile.ts @@ -228,3 +228,38 @@ export const profileRemoveMeta: AgentCommandMeta = { }, jsonFields: profileMutationJsonFields, }; + +const profileRenamePlanOutput = { + profile: 'string', + newProfile: 'string', + operation: 'rename', + status: 'planned', + installed: 'boolean', + recovering: 'boolean', + steps: [{ kind: 'workspace | root | settings | launcher | state', from: 'string', to: 'string' }], + warnings: ['string'], +}; + +export const profileRenameMeta: AgentCommandMeta = { + command: 'profile rename', + description: 'Rename a declared profile and relocate a supported installation', + whenToUse: 'When you want to change a global profile name while keeping its launcher names and session data', + examples: [ + 'allagents profile rename work office --dry-run', + 'allagents --json profile rename work office --yes', + ], + expectedOutput: 'Shows the declaration, client directory, settings, state, and launcher changes before confirmation.', + positionals: [ + { name: 'old', type: 'string', required: true, description: 'Current declared profile name.' }, + { name: 'new', type: 'string', required: true, description: 'New profile name.' }, + ], + options: mutationOptions.slice(0, 2), + outputSchema: { + ...profileRenamePlanOutput, + status: 'planned | renamed | failed', + plan: profileRenamePlanOutput, + error: 'string?', + }, + jsonFields: ['profile', 'newProfile', 'operation', 'status', 'installed', 'recovering', 'plan', 'steps', 'warnings', 'error'], + skipUpdateCheck: true, +}; diff --git a/src/cli/structured-help.ts b/src/cli/structured-help.ts index 190f38f3..3cbb32a6 100644 --- a/src/cli/structured-help.ts +++ b/src/cli/structured-help.ts @@ -39,6 +39,7 @@ import { profileInstallMeta, profileListMeta, profileRemoveMeta, + profileRenameMeta, profileStatusMeta, } from './metadata/profile.js'; import { updateMeta } from './metadata/self.js'; @@ -119,6 +120,7 @@ const registeredCommands: RegisteredCommand[] = [ { command: 'profile list', meta: profileListMeta }, { command: 'profile status', meta: profileStatusMeta }, { command: 'profile remove', meta: profileRemoveMeta }, + { command: 'profile rename', meta: profileRenameMeta }, ]; const groupDescriptions: Readonly> = { diff --git a/src/core/mcp-servers.ts b/src/core/mcp-servers.ts index 823f1f7e..0c912559 100644 --- a/src/core/mcp-servers.ts +++ b/src/core/mcp-servers.ts @@ -2,8 +2,6 @@ import { randomUUID } from 'node:crypto'; import { existsSync } from 'node:fs'; import { lstat, - mkdir, - readFile, rename, rm, stat, @@ -32,8 +30,10 @@ import { validateProjectWorkspaceConfig, validateUserWorkspaceConfig, } from '../utils/workspace-parser.js'; +import { withWorkspaceConfigLock } from '../utils/workspace-config-lock.js'; import { serializeWorkspaceConfigFile } from '../utils/workspace-writer.js'; import { flattenZodIssues } from '../utils/zod-issues.js'; +import { assertNoPendingProfileRename } from './profile/rename-transaction.js'; import { ensureUserWorkspace, getUserWorkspaceConfigPath, @@ -99,86 +99,6 @@ type EditableMcpContainer = { mcpProxy?: EditableMcpProxy; }; -const LOCK_TIMEOUT_MS = 5_000; -const STALE_LOCK_MS = 30_000; - -async function readLockOwner(lockPath: string): Promise { - return readFile(join(lockPath, 'owner'), 'utf8').catch(() => null); -} - -async function withDestinationLock( - configPath: string, - mutate: () => Promise, -): Promise { - const lockPath = `${configPath}.lock`; - const breakPath = `${lockPath}.break`; - const token = `${process.pid}:${randomUUID()}`; - const deadline = Date.now() + LOCK_TIMEOUT_MS; - let acquired = false; - while (!acquired) { - let created = false; - try { - await mkdir(lockPath, { mode: 0o700 }); - created = true; - await writeFile(join(lockPath, 'owner'), token, { - encoding: 'utf8', - mode: 0o600, - }); - acquired = true; - } catch (error) { - if (created) { - await rm(lockPath, { recursive: true, force: true }).catch( - () => undefined, - ); - } - if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error; - const lockStats = await lstat(lockPath).catch(() => null); - if (lockStats && Date.now() - lockStats.mtimeMs > STALE_LOCK_MS) { - let breaker = false; - try { - await mkdir(breakPath, { mode: 0o700 }); - breaker = true; - const currentStats = await lstat(lockPath).catch(() => null); - if ( - currentStats && - Date.now() - currentStats.mtimeMs > STALE_LOCK_MS - ) { - await rm(lockPath, { recursive: true, force: true }); - } - } catch (breakError) { - if ((breakError as NodeJS.ErrnoException).code !== 'EEXIST') { - throw breakError; - } - } finally { - if (breaker) { - await rm(breakPath, { recursive: true, force: true }).catch( - () => undefined, - ); - } - } - if (Date.now() >= deadline) { - throw new Error(`Timed out waiting to update ${configPath}`); - } - await new Promise((resolve) => setTimeout(resolve, 25)); - continue; - } - if (Date.now() >= deadline) { - throw new Error(`Timed out waiting to update ${configPath}`); - } - await new Promise((resolve) => setTimeout(resolve, 25)); - } - } - try { - return await mutate(); - } finally { - if ((await readLockOwner(lockPath)) === token) { - await rm(lockPath, { recursive: true, force: true }).catch( - () => undefined, - ); - } - } -} - type EditableMcpDocument = WorkspaceConfig | EditableUserWorkspaceConfig; function getConfigPath(workspacePath: string): string { @@ -409,7 +329,8 @@ export async function addMcpServer( } await ensureDestinationForAdd(destination); - return await withDestinationLock(destination.configPath, async () => { + return await withWorkspaceConfigLock(destination.configPath, async () => { + await assertNoPendingProfileRename(destination.configPath); const document = await readDestinationConfig(destination); const container = selectDestinationContainer(destination, document); container.mcpServers ??= {}; @@ -450,7 +371,8 @@ export async function removeMcpServer( }; } - return await withDestinationLock(destination.configPath, async () => { + return await withWorkspaceConfigLock(destination.configPath, async () => { + await assertNoPendingProfileRename(destination.configPath); const document = await readDestinationConfig(destination); const container = selectDestinationContainer(destination, document); if (!container.mcpServers || !(name in container.mcpServers)) { diff --git a/src/core/profile/adapters/claude.ts b/src/core/profile/adapters/claude.ts index b496dcff..a8072146 100644 --- a/src/core/profile/adapters/claude.ts +++ b/src/core/profile/adapters/claude.ts @@ -131,6 +131,7 @@ function serializeClaudeMcp( export class ClaudeProfileAdapter implements NativeProfileAdapter { readonly client = 'claude' as const; + readonly rename = { nativeLocations: ['plugins'] }; readonly capabilities = CAPABILITIES; readonly nativeClient = new ClaudeNativeClient({ minimumVersion: CLAUDE_MINIMUM_VERSION, diff --git a/src/core/profile/adapters/codex.ts b/src/core/profile/adapters/codex.ts index 57ed37eb..2df4c30f 100644 --- a/src/core/profile/adapters/codex.ts +++ b/src/core/profile/adapters/codex.ts @@ -1,3 +1,4 @@ +import { readFile, readdir } from 'node:fs/promises'; import { isAbsolute, join, resolve } from 'node:path'; import { CodexProfileSettingsSchema, @@ -187,6 +188,22 @@ function serializeCodexMcp( export class CodexProfileAdapter implements NativeProfileAdapter { readonly client = 'codex' as const; + readonly rename = { + nativeLocations: ['plugins', 'marketplaces', '.tmp/marketplaces'], + namedFiles: (profile: string) => [`${profile}.config.toml`], + async assertRelocatable(context: ProfileClientContext): Promise { + const entries = await readdir(context.root); + const config = entries.includes('config.toml') + ? await readFile(join(context.root, 'config.toml'), 'utf8') + : ''; + if (process.env.CODEX_SQLITE_HOME || context.operationContext.env?.CODEX_SQLITE_HOME || + /^[\t ]*["']?sqlite_home["']?[\t ]*=/m.test(config) || + entries.some((entry) => /^state(?:_\d+)?\.sqlite(?:-(?:wal|shm|journal))?$/i.test(entry))) { + // Codex thread indexes store absolute rollout paths into CODEX_HOME. + throw new Error('Codex installations with a session database require a separate migration.'); + } + }, + }; readonly capabilities = CAPABILITIES; readonly nativeClient = new CodexNativeClient({ minimumVersion: CODEX_MINIMUM_VERSION, diff --git a/src/core/profile/adapters/opencode.ts b/src/core/profile/adapters/opencode.ts index 4fff37b6..0e21d065 100644 --- a/src/core/profile/adapters/opencode.ts +++ b/src/core/profile/adapters/opencode.ts @@ -95,6 +95,7 @@ function serializeOpenCodeMcp( export class OpenCodeProfileAdapter implements FileOnlyProfileAdapter { readonly client = 'opencode' as const; + readonly rename = {}; readonly capabilities = CAPABILITIES; resolveContext( diff --git a/src/core/profile/manager.ts b/src/core/profile/manager.ts index 42b47312..0a2533cc 100644 --- a/src/core/profile/manager.ts +++ b/src/core/profile/manager.ts @@ -1,6 +1,7 @@ import { randomUUID } from 'node:crypto'; import { lstat, mkdir, readdir, rm, rmdir } from 'node:fs/promises'; import { basename, dirname, join, resolve } from 'node:path'; +import { isDeepStrictEqual } from 'node:util'; import type { ProfileResourceRelationship, ProfileState, @@ -12,6 +13,7 @@ import { getPluginClients, resolveInstallMode, } from '../../models/workspace-config.js'; +import { withWorkspaceConfigLock } from '../../utils/workspace-config-lock.js'; import { getProfileAdapter } from './adapters/registry.js'; import { assertSafeProfilePath, @@ -42,6 +44,7 @@ import { readProfileWorkspace, resolveProfileRuntimeOptions, } from './plan.js'; +import { assertNoPendingProfileRename } from './rename-transaction.js'; import { checkpointProfileResource, createProfileState, @@ -511,6 +514,25 @@ export async function applyProfilePlan( ): Promise { const internal = getInternalProfilePlan(plan); if (options.dryRun || internal.runtime.dryRun) return dryRunResult(internal); + return withWorkspaceConfigLock(internal.runtime.userConfigPath, async () => { + await assertNoPendingProfileRename(internal.runtime.userConfigPath); + const workspace = await readOptionalProfileWorkspace(internal.runtime, dependencies); + const profileRoot = getProfileRoot(internal.runtime, plan.profile); + const state = await loadProfileState(profileRoot); + if (!isDeepStrictEqual(workspace.profiles?.[plan.profile], internal.declaration) || + state.status === 'malformed' || + !isDeepStrictEqual(state.status === 'loaded' ? state.state : null, internal.priorState)) { + throw new Error('The profile changed after preview. Rerun the command to see the updated plan.'); + } + return applyProfilePlanLocked(internal, dependencies); + }); +} + +async function applyProfilePlanLocked( + internal: InternalProfilePlan, + dependencies: ProfileManagerDependencies, +): Promise { + const plan = internal.public; const profileRoot = getProfileRoot(internal.runtime, plan.profile); let state: ProfileState; try { diff --git a/src/core/profile/plan.ts b/src/core/profile/plan.ts index 557a706e..d6c868f3 100644 --- a/src/core/profile/plan.ts +++ b/src/core/profile/plan.ts @@ -50,6 +50,7 @@ import type { ProfileStepKind, } from './index.js'; import { renderProfileLaunchers } from './launcher.js'; +import { assertNoPendingProfileRename } from './rename-transaction.js'; import { resolveProfileFileSource, type ResolvedProfileFileSource } from './source.js'; import { hashProfileDeclaration, @@ -675,6 +676,7 @@ export async function planProfileOperation( ): Promise { ProfileNameSchema.parse(profile); const runtime = resolveProfileRuntimeOptions(options); + await assertNoPendingProfileRename(runtime.userConfigPath); const workspace = operation === 'remove' ? await readOptionalProfileWorkspace(runtime, dependencies) diff --git a/src/core/profile/rename-transaction.ts b/src/core/profile/rename-transaction.ts new file mode 100644 index 00000000..877feeef --- /dev/null +++ b/src/core/profile/rename-transaction.ts @@ -0,0 +1,259 @@ +import { randomUUID } from 'node:crypto'; +import { + link, + lstat, + open, + readFile, + rename, + rm, + unlink, +} from 'node:fs/promises'; +import { basename, dirname, isAbsolute, join, relative, sep } from 'node:path'; +import { z } from 'zod'; +import { ProfileSha256Schema } from '../../models/profile-state.js'; +import { ProfileNameSchema } from '../../models/workspace-config.js'; +import { + assertSafeProfilePath, + fingerprintProfileFile, + sha256Fingerprint, +} from './files.js'; +import { getProfileStatePath } from './state.js'; + +const RelativePath = z + .string() + .refine( + (path) => + !isAbsolute(path) && + path + .split(sep) + .every((part) => part !== '' && part !== '.' && part !== '..'), + ); +const Replacement = z.object({ + before: ProfileSha256Schema, + content: z.string(), +}); +export const RenameRecordSchema = z.object({ + version: z.literal(1), + id: z.uuid(), + profile: ProfileNameSchema, + newProfile: ProfileNameSchema, + workspaceBefore: ProfileSha256Schema, + workspaceAfter: ProfileSha256Schema, + root: z + .object({ + device: z.string(), + inode: z.string(), + namedFiles: z.array( + z.object({ + from: RelativePath, + to: RelativePath, + fingerprint: ProfileSha256Schema, + }), + ), + state: Replacement.optional(), + }) + .optional(), + launchers: z.array( + Replacement.extend({ + name: z.string().regex(/^[a-z0-9][a-z0-9._-]{0,67}$/), + mode: z.number().int().min(0).max(0o777), + }), + ), +}); + +export type RenameRecord = z.infer; + +export function profileRenameRecordPath(workspacePath: string): string { + return `${workspacePath}.profile-rename.json`; +} + +export async function profileRenameStats(path: string) { + return lstat(path).catch((error) => { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; + throw error; + }); +} + +export async function assertNoPendingProfileRename( + workspacePath: string, +): Promise { + if (await profileRenameStats(profileRenameRecordPath(workspacePath))) { + throw new Error( + 'A profile rename is incomplete. Rerun the same profile rename with --yes before changing profiles.', + ); + } +} + +export async function readProfileRenameRecord( + path: string, +): Promise { + await assertSafeProfilePath(dirname(path), path); + const stats = await profileRenameStats(path); + if (!stats) return null; + if (!stats.isFile()) + throw new Error( + `Profile rename recovery record is not a regular file: ${path}`, + ); + const text = await readFile(path, 'utf8'); + const result = RenameRecordSchema.safeParse(JSON.parse(text)); + if (!result.success) { + throw new Error(`Invalid profile rename recovery record at ${path}`); + } + return result.data; +} + +/** Publish one replacement atomically. The recovery record tracks either version. */ +export async function publishRenameFile( + path: string, + content: string, + previous: string | null, + mode: number, + transactionId?: string, +): Promise { + const parent = dirname(path); + await assertSafeProfilePath(parent, path); + const temporary = join( + parent, + `.${basename(path)}.profile-rename-${transactionId ?? randomUUID()}.tmp`, + ); + if (transactionId) { + // A previous process may have exited while staging this transaction's file. + await assertSafeProfilePath(parent, temporary); + await rm(temporary, { force: true }); + } + const handle = await open(temporary, 'wx', mode); + try { + await handle.writeFile(content, 'utf8'); + await handle.chmod(mode); + await handle.sync(); + await handle.close(); + await assertSafeProfilePath(parent, path); + if (previous === null) { + await link(temporary, path); + } else { + const current = await fingerprintProfileFile(path); + if (current === sha256Fingerprint(content)) return; + if (current !== previous) throw changed(path); + await rename(temporary, path); + } + } finally { + await handle.close(); + await rm(temporary, { force: true }); + } +} + +function changed(path: string): Error { + return new Error(`Profile rename found a missing or changed file at ${path}`); +} + +export async function getRenameRootIdentity(path: string) { + return lstat(path, { bigint: true }).then( + (stats) => { + if (!stats.isDirectory()) + throw new Error(`Profile root is not a directory: ${path}`); + return { device: String(stats.dev), inode: String(stats.ino) }; + }, + (error) => { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; + throw error; + }, + ); +} + +export function relativeRenamePath(root: string, path: string): string { + return RelativePath.parse(relative(root, path)); +} + +/** + * Validate the complete current layout before touching it. Every checkpoint can + * be recognized by file hash or inode, including a stop between link and unlink. + */ +export async function inspectRenameProgress( + record: RenameRecord, + oldRoot: string, + newRoot: string, + binDir: string, +) { + await assertSafeProfilePath(dirname(oldRoot), oldRoot); + await assertSafeProfilePath(dirname(newRoot), newRoot); + const oldIdentity = await getRenameRootIdentity(oldRoot); + const newIdentity = await getRenameRootIdentity(newRoot); + const identity = oldIdentity ?? newIdentity; + if (newIdentity && (!record.root || oldIdentity)) { + throw new Error(`Profile destination already exists: ${newRoot}`); + } + if ( + identity?.inode !== record.root?.inode || + identity?.device !== record.root?.device + ) { + throw new Error(`Profile directory changed during rename: ${oldRoot}`); + } + const currentRoot = newIdentity ? newRoot : oldRoot; + const moves = []; + for (const move of record.root?.namedFiles ?? []) { + const from = join(currentRoot, move.from); + const to = join(currentRoot, move.to); + await assertSafeProfilePath(currentRoot, from); + await assertSafeProfilePath(currentRoot, to); + const source = await fingerprintProfileFile(from); + const destination = await fingerprintProfileFile(to); + if (destination !== null) { + const sourceStats = await profileRenameStats(from); + const targetStats = await profileRenameStats(to); + if ( + oldIdentity || + destination !== move.fingerprint || + (sourceStats && + (sourceStats.ino !== targetStats?.ino || + sourceStats.dev !== targetStats.dev)) + ) { + throw new Error(`Profile file destination already exists: ${to}`); + } + } + if (source !== null ? source !== move.fingerprint : destination === null) { + throw changed(from); + } + moves.push({ ...move, source, destination }); + } + const replacements = record.launchers.map(({ name, ...entry }) => ({ + ...entry, + path: join(binDir, name), + })); + if (record.root?.state) { + replacements.push({ + ...record.root.state, + mode: 0o600, + path: getProfileStatePath(currentRoot), + }); + } + for (const entry of replacements) { + await assertSafeProfilePath(dirname(entry.path), entry.path); + const fingerprint = await fingerprintProfileFile(entry.path); + if ( + fingerprint !== entry.before && + fingerprint !== sha256Fingerprint(entry.content) + ) { + throw changed(entry.path); + } + } + return { moveRoot: oldIdentity !== null, moves }; +} + +export async function moveNamedProfileFile( + root: string, + move: Awaited>['moves'][number], +): Promise { + if (move.source === null) return; + const from = join(root, move.from); + const to = join(root, move.to); + await assertSafeProfilePath(root, from); + await assertSafeProfilePath(root, to); + if ((await fingerprintProfileFile(from)) !== move.fingerprint) + throw changed(from); + if (move.destination === null) await link(from, to); + const source = await lstat(from, { bigint: true }); + const destination = await lstat(to, { bigint: true }); + if (source.ino !== destination.ino || source.dev !== destination.dev) + throw changed(to); + await unlink(from); +} diff --git a/src/core/profile/rename.ts b/src/core/profile/rename.ts new file mode 100644 index 00000000..2e28586b --- /dev/null +++ b/src/core/profile/rename.ts @@ -0,0 +1,644 @@ +import { randomUUID } from 'node:crypto'; +import { lstat, readFile, readdir, rename, unlink } from 'node:fs/promises'; +import { dirname, join } from 'node:path'; +import { isDeepStrictEqual } from 'node:util'; +import type { + ProfileResourceRelationship, + ProfileState, +} from '../../models/profile-state.js'; +import { + type ProfileDeclaration, + ProfileNameSchema, +} from '../../models/workspace-config.js'; +import { withWorkspaceConfigLock } from '../../utils/workspace-config-lock.js'; +import { validateUserWorkspaceConfig } from '../../utils/workspace-parser.js'; +import { serializeWorkspaceConfig } from '../../utils/workspace-writer.js'; +import { loadYaml } from '../../utils/yaml.js'; +import { getProfileAdapter } from './adapters/registry.js'; +import { + assertSafeProfilePath, + fingerprintProfileFile, + sha256Fingerprint, +} from './files.js'; +import type { ProfileRuntimeOptions } from './index.js'; +import { renderProfileLaunchers } from './launcher.js'; +import { + getProfileRoot, + type ResolvedProfileRuntime, + resolveProfileRuntimeOptions, +} from './plan.js'; +import { + getRenameRootIdentity, + inspectRenameProgress, + moveNamedProfileFile, + profileRenameRecordPath, + profileRenameStats, + publishRenameFile, + readProfileRenameRecord, + relativeRenamePath, + type RenameRecord, +} from './rename-transaction.js'; +import { + getProfileStatePath, + hashProfileDeclaration, + loadProfileState, + sanitizeProfileError, + sanitizeProfileState, +} from './state.js'; + +export interface ProfileRenamePlan { + readonly profile: string; + readonly newProfile: string; + readonly operation: 'rename'; + readonly status: 'planned'; + readonly installed: boolean; + readonly recovering: boolean; + readonly steps: readonly { + readonly kind: 'workspace' | 'root' | 'settings' | 'launcher' | 'state'; + readonly from: string; + readonly to: string; + }[]; + readonly warnings: readonly string[]; +} + +interface RenamePlanDetails { + readonly runtime: ResolvedProfileRuntime; + readonly record: RenameRecord; + readonly workspaceContent: string; + readonly workspaceMode: number; +} + +const plans = new WeakMap(); + +async function checkProfileTree(root: string): Promise { + for (const item of await readdir(root, { withFileTypes: true })) { + const path = join(root, item.name); + if (item.isDirectory()) await checkProfileTree(path); + else if (!item.isFile()) throw new Error(`Unsafe profile entry: ${path}`); + } +} + +function replaceDeclaration( + content: string, + workspacePath: string, + profile: string, + newProfile: string, +) { + const config = loadYaml(content) as { profiles?: Record }; + const { profiles } = validateUserWorkspaceConfig(config, workspacePath); + if (!profiles || !Object.hasOwn(profiles, profile)) { + throw new Error(`Profile '${profile}' is not declared`); + } + if (Object.hasOwn(profiles, newProfile)) { + throw new Error(`Profile '${newProfile}' is already declared`); + } + const updated = { + ...config, + profiles: Object.fromEntries( + Object.entries(config.profiles ?? {}).map(([name, value]) => [ + name === profile ? newProfile : name, + value, + ]), + ), + }; + validateUserWorkspaceConfig(updated, workspacePath); + return { + declaration: profiles[profile] as ProfileDeclaration, + content: serializeWorkspaceConfig(updated, content, { + renamedProfile: { from: profile, to: newProfile }, + }), + }; +} + +function relocateResource( + resource: ProfileResourceRelationship, + path: string, +): ProfileResourceRelationship { + return { + ...resource, + path, + identity: path, + key: `${resource.kind}:${resource.client}:${sha256Fingerprint(path)}`, + }; +} + +async function planInstalledRename( + runtime: ResolvedProfileRuntime, + profile: string, + newProfile: string, + declaration: ProfileDeclaration, + state: ProfileState, + stateFingerprint: string, +): Promise< + Pick & + Pick, 'namedFiles' | 'state'> +> { + const oldRoot = getProfileRoot(runtime, profile); + const newRoot = getProfileRoot(runtime, newProfile); + if (JSON.stringify(declaration).includes(JSON.stringify(oldRoot).slice(1, -1))) { + throw new Error('The profile declaration contains a path inside the old profile directory. Update it before renaming.'); + } + if ( + state.profile !== profile || + state.status !== 'installed' || + !state.operation.completedAt || + state.operation.kind === 'remove' || + state.declarationDigest !== hashProfileDeclaration(declaration) + ) { + throw new Error( + 'The profile must have a complete installation matching its current declaration before rename.', + ); + } + const active = state.resources.filter( + (entry) => entry.transition !== 'removed', + ); + if ( + active.some( + (entry) => + entry.kind === 'native' || + entry.kind === 'marketplace' || + !['installed', 'updated', 'referenced'].includes(entry.transition), + ) + ) { + throw new Error( + 'Profile rename requires file-only resources and a complete installation.', + ); + } + const clientDirectory = join(oldRoot, 'clients'); + const clientEntries = await readdir(clientDirectory); + if ( + clientEntries.some( + (entry) => !state.clients.some((client) => client === entry), + ) + ) { + throw new Error( + `Profile contains an unrecognized client directory: ${clientDirectory}`, + ); + } + + const launchers: RenameRecord['launchers'] = []; + const namedFiles: NonNullable['namedFiles'] = []; + const resources = new Map(); + for (const { name: client, launcher } of declaration.clients) { + const adapter = getProfileAdapter(client); + if (!adapter?.rename) { + throw new Error( + `Installed profile rename is unsupported for '${client}'`, + ); + } + const before = adapter.resolveContext(profile, runtime); + const after = adapter.resolveContext(newProfile, runtime); + const beforeLocations = Object.values(before.operationContext.roots ?? {}); + const afterLocations = Object.values(after.operationContext.roots ?? {}); + for (const [index, location] of [ + before.root, + ...beforeLocations, + ].entries()) { + if ( + relativeRenamePath(oldRoot, location) !== + relativeRenamePath( + newRoot, + [after.root, ...afterLocations][index] ?? newRoot, + ) + ) { + throw new Error( + `Profile client '${client}' has a non-relocatable directory layout`, + ); + } + } + const managedRoot = before.operationContext.roots?.config ?? before.root; + const clientResources = active.filter((entry) => entry.client === client); + if ( + !clientResources.some( + (entry) => + entry.kind === 'root' && + entry.path === managedRoot && + entry.ownership === 'managed', + ) || + !(await profileRenameStats(managedRoot))?.isDirectory() + ) { + throw new Error( + `Profile client directory is missing or unowned: ${managedRoot}`, + ); + } + await adapter.rename.assertRelocatable?.(before); + for (const name of adapter.rename.nativeLocations ?? []) { + const path = join(before.root, name); + await assertSafeProfilePath(before.root, path); + const stats = await profileRenameStats(path); + if (stats && (!stats.isDirectory() || (await readdir(path)).length > 0)) { + throw new Error( + `Profile client '${client}' has native data in ${path}`, + ); + } + } + + const namedChanges = new Map(); + for (const [index, name] of ( + adapter.rename.namedFiles?.(profile) ?? [] + ).entries()) { + const from = join(before.root, name); + const replacement = adapter.rename.namedFiles?.(newProfile)[index]; + if (!replacement) + throw new Error( + `Profile client '${client}' did not resolve a settings destination`, + ); + const to = join(before.root, replacement); + const tracked = clientResources.find( + (entry) => entry.kind === 'settings' && entry.path === from, + ); + if ( + tracked?.ownership !== 'managed' || + !tracked.fingerprint || + tracked.fingerprint !== (await fingerprintProfileFile(from)) + ) { + throw new Error( + `Profile settings are missing, modified, or unowned: ${from}`, + ); + } + namedFiles.push({ + from: relativeRenamePath(oldRoot, from), + to: relativeRenamePath(oldRoot, to), + fingerprint: tracked.fingerprint, + }); + namedChanges.set(from, relativeRenamePath(oldRoot, to)); + } + + const rendered = launcher + ? renderProfileLaunchers(launcher, after.launcher).filter((entry) => + runtime.platform === 'win32' + ? entry.companion !== 'posix' + : entry.companion === 'posix', + ) + : []; + const launcherResources = clientResources.filter( + (entry) => entry.kind === 'launcher', + ); + if (rendered.length !== launcherResources.length) { + throw new Error( + `Profile launchers for '${client}' differ from the installed declaration`, + ); + } + for (const entry of rendered) { + const path = join(runtime.binDir, entry.fileName); + const owner = launcherResources.find( + (resource) => resource.path === path && resource.identity === path, + ); + await assertSafeProfilePath(runtime.binDir, path); + const actual = await fingerprintProfileFile(path); + if ( + !actual || + owner?.ownership !== 'managed' || + owner.fingerprint !== actual + ) { + throw new Error( + `Profile launcher is missing, modified, or unowned: ${path}`, + ); + } + launchers.push({ + name: entry.fileName, + before: actual, + content: entry.content, + mode: entry.mode, + }); + resources.set(owner.key, { + ...owner, + fingerprint: sha256Fingerprint(entry.content), + }); + } + + for (const resource of clientResources) { + if (resource.kind === 'launcher') continue; + if ( + !resource.path || + resource.path !== resource.identity || + (resource.kind === 'root' && resource.path !== managedRoot) + ) { + throw new Error( + `Profile client '${client}' has an unexpected resource identity`, + ); + } + await assertSafeProfilePath( + resource.kind === 'root' ? oldRoot : before.root, + resource.path, + ); + if (resource.kind === 'mcp' || resource.kind === 'settings') { + const content = await readFile(resource.path, 'utf8').catch((error) => { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return ''; + throw error; + }); + if ( + content.includes('--profile') || + content.includes(oldRoot) || + content.includes(JSON.stringify(oldRoot).slice(1, -1)) + ) { + throw new Error( + `Profile-bound configuration cannot be relocated safely: ${resource.path}`, + ); + } + } + resources.set( + resource.key, + relocateResource( + resource, + join( + newRoot, + namedChanges.get(resource.path) ?? + relativeRenamePath(oldRoot, resource.path), + ), + ), + ); + } + } + const newState = sanitizeProfileState({ + ...state, + profile: newProfile, + resources: active.map(({ key }) => { + const moved = resources.get(key); + if (!moved) + throw new Error( + 'The installed client set differs from the declaration', + ); + return moved; + }), + }); + return { + namedFiles, + launchers, + state: { + before: stateFingerprint, + content: `${JSON.stringify(newState, null, 2)}\n`, + }, + }; +} + +async function prepareRename( + profile: string, + newProfile: string, + runtime: ResolvedProfileRuntime, + id: string = randomUUID(), +): Promise< + RenamePlanDetails & { + readonly installed: boolean; + readonly recovering: boolean; + } +> { + const workspacePath = runtime.userConfigPath; + await assertSafeProfilePath(dirname(workspacePath), workspacePath); + const workspaceStats = await lstat(workspacePath); + if (!workspaceStats.isFile()) + throw new Error(`Workspace is not a regular file: ${workspacePath}`); + const workspaceMode = workspaceStats.mode & 0o777; + const original = await readFile(workspacePath); + const current = original.toString('utf8'); + const fingerprint = sha256Fingerprint(original); + if (sha256Fingerprint(current) !== fingerprint) { + throw new Error(`Workspace is not valid UTF-8: ${workspacePath}`); + } + const oldRoot = getProfileRoot(runtime, profile); + const newRoot = getProfileRoot(runtime, newProfile); + const existing = await readProfileRenameRecord( + profileRenameRecordPath(workspacePath), + ); + if (existing) { + if (existing.profile !== profile || existing.newProfile !== newProfile) { + throw new Error( + `Profile rename is incomplete. Rerun 'allagents profile rename ${existing.profile} ${existing.newProfile} --yes'.`, + ); + } + const updated = + fingerprint === existing.workspaceAfter + ? current + : fingerprint === existing.workspaceBefore + ? replaceDeclaration(current, workspacePath, profile, newProfile) + .content + : undefined; + if ( + updated === undefined || + sha256Fingerprint(updated) !== existing.workspaceAfter + ) { + throw new Error( + 'The workspace changed during profile rename. Restore either recorded workspace version before retrying.', + ); + } + await inspectRenameProgress(existing, oldRoot, newRoot, runtime.binDir); + return { + runtime, + record: existing, + workspaceContent: updated, + workspaceMode, + installed: !!existing.root?.state, + recovering: true, + }; + } + + const updated = replaceDeclaration( + current, + workspacePath, + profile, + newProfile, + ); + await assertSafeProfilePath(dirname(oldRoot), oldRoot); + await assertSafeProfilePath(dirname(newRoot), newRoot); + if (await profileRenameStats(newRoot)) { + throw new Error(`Profile destination already exists: ${newRoot}`); + } + const identity = await getRenameRootIdentity(oldRoot); + const stateFingerprint = await fingerprintProfileFile( + getProfileStatePath(oldRoot), + ); + const loaded = await loadProfileState(oldRoot); + if (loaded.status === 'malformed') { + throw new Error( + `Refusing profile rename because state is malformed: ${loaded.error}`, + ); + } + if (identity) await checkProfileTree(oldRoot); + if (identity && loaded.status === 'missing') { + const entries = await readdir(oldRoot); + if ( + entries.some((entry) => entry !== 'oauth-proxy') || + (entries.length && + !( + await profileRenameStats(join(oldRoot, 'oauth-proxy')) + )?.isDirectory()) + ) { + throw new Error( + `Profile directory exists without installation state: ${oldRoot}`, + ); + } + } + const installed = loaded.status === 'loaded'; + if (installed && !stateFingerprint) + throw new Error('Profile state appeared during rename planning'); + const assets = + loaded.status === 'loaded' && stateFingerprint + ? await planInstalledRename( + runtime, + profile, + newProfile, + updated.declaration, + loaded.state, + stateFingerprint, + ) + : { namedFiles: [], launchers: [], state: undefined }; + const record: RenameRecord = { + version: 1, + id, + profile, + newProfile, + workspaceBefore: fingerprint, + workspaceAfter: sha256Fingerprint(updated.content), + ...(identity && { + root: { ...identity, namedFiles: assets.namedFiles, state: assets.state }, + }), + launchers: assets.launchers, + }; + await inspectRenameProgress(record, oldRoot, newRoot, runtime.binDir); + return { + runtime, + record, + workspaceContent: updated.content, + workspaceMode, + installed, + recovering: false, + }; +} + +export async function planProfileRename( + profile: string, + newProfile: string, + options: ProfileRuntimeOptions = {}, +): Promise { + ProfileNameSchema.parse(profile); + ProfileNameSchema.parse(newProfile); + if (profile === newProfile) + throw new Error('Choose a different profile name.'); + const runtime = resolveProfileRuntimeOptions(options); + const details = await prepareRename(profile, newProfile, runtime); + const { record, installed, recovering } = details; + const steps: ProfileRenamePlan['steps'][number][] = []; + const oldRoot = getProfileRoot(runtime, profile); + const newRoot = getProfileRoot(runtime, newProfile); + if (record.root) { + steps.push({ kind: 'root', from: oldRoot, to: newRoot }); + for (const file of record.root.namedFiles) { + steps.push({ + kind: 'settings', + from: join(oldRoot, file.from), + to: join(newRoot, file.to), + }); + } + } + for (const file of record.launchers) { + const path = join(runtime.binDir, file.name); + steps.push({ kind: 'launcher', from: path, to: path }); + } + if (record.root?.state) { + steps.push({ + kind: 'state', + from: getProfileStatePath(oldRoot), + to: getProfileStatePath(newRoot), + }); + } + steps.push({ + kind: 'workspace', + from: runtime.userConfigPath, + to: runtime.userConfigPath, + }); + const plan: ProfileRenamePlan = { + profile, + newProfile, + installed, + recovering, + steps, + operation: 'rename', + status: 'planned', + warnings: installed + ? [ + 'Close clients using this profile before applying. Update external references such as T3 provider paths after the rename.', + ] + : [], + }; + plans.set(plan, details); + return plan; +} + +export async function applyProfileRename( + plan: ProfileRenamePlan, +): Promise { + const initial = plans.get(plan); + if (!initial || initial.runtime.dryRun) + throw new Error('A fresh apply plan is required.'); + const { runtime } = initial; + const workspace = runtime.userConfigPath; + const journal = profileRenameRecordPath(workspace); + await withWorkspaceConfigLock(workspace, async () => { + const current = await prepareRename( + plan.profile, + plan.newProfile, + runtime, + initial.record.id, + ); + const { record } = current; + if (!isDeepStrictEqual(initial.record, record)) { + throw new Error( + 'The profile changed after preview. Rerun the rename to see the updated plan.', + ); + } + const oldRoot = getProfileRoot(runtime, record.profile); + const newRoot = getProfileRoot(runtime, record.newProfile); + if (!current.recovering) + await publishRenameFile(journal, JSON.stringify(record), null, 0o600); + try { + const progress = await inspectRenameProgress( + record, + oldRoot, + newRoot, + runtime.binDir, + ); + if (progress.moveRoot) { + if (await profileRenameStats(newRoot)) + throw new Error(`Profile destination already exists: ${newRoot}`); + await rename(oldRoot, newRoot); + } + for (const move of progress.moves) + await moveNamedProfileFile(newRoot, move); + for (const { name, content, before, mode } of record.launchers) { + await publishRenameFile( + join(runtime.binDir, name), + content, + before, + mode, + record.id, + ); + } + if (record.root?.state) { + const { before, content } = record.root.state; + await publishRenameFile( + getProfileStatePath(newRoot), + content, + before, + 0o600, + record.id, + ); + } + await publishRenameFile( + workspace, + current.workspaceContent, + record.workspaceBefore, + current.workspaceMode, + record.id, + ); + await unlink(journal); + } catch (error) { + const message = sanitizeProfileError( + error instanceof Error ? error.message : String(error), + ); + throw new Error( + `${message}. Rerun 'allagents profile rename ${record.profile} ${record.newProfile} --yes' to resume.`, + { cause: error }, + ); + } + }); +} diff --git a/src/core/profile/types.ts b/src/core/profile/types.ts index 2b304e4e..ad48e490 100644 --- a/src/core/profile/types.ts +++ b/src/core/profile/types.ts @@ -153,6 +153,13 @@ interface ProfileAdapterBase { stepOrder?(kind: ProfileStepKind, operation: ProfileOperationKind): number; readonly mcpPrerequisite?: ProfileMcpPrerequisite; + /** Opt in to moving an isolated file-only installation. Paths are relative to its client root. */ + readonly rename?: { + readonly nativeLocations?: readonly string[]; + readonly namedFiles?: (profile: string) => readonly string[]; + assertRelocatable?(context: ProfileClientContext): Promise; + }; + serializeSettings( context: ProfileClientContext, input: ProfileSerializationInput, diff --git a/src/utils/workspace-config-lock.ts b/src/utils/workspace-config-lock.ts new file mode 100644 index 00000000..4765bf69 --- /dev/null +++ b/src/utils/workspace-config-lock.ts @@ -0,0 +1,100 @@ +import { randomUUID } from 'node:crypto'; +import { lstat, mkdir, readFile, rm, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; + +const LOCK_TIMEOUT_MS = 5_000; +const STALE_LOCK_MS = 30_000; + +async function readLockOwner(lockPath: string): Promise { + return readFile(join(lockPath, 'owner'), 'utf8').catch(() => null); +} + +async function isStaleLock( + lockPath: string, + modifiedAt: number, +): Promise { + const owner = await readLockOwner(lockPath); + const pid = Number(owner?.split(':')[0]); + if (!Number.isSafeInteger(pid) || pid <= 0) { + return Date.now() - modifiedAt > STALE_LOCK_MS; + } + try { + process.kill(pid, 0); + return false; + } catch (error) { + return (error as NodeJS.ErrnoException).code === 'ESRCH'; + } +} + +export async function withWorkspaceConfigLock( + configPath: string, + mutate: () => Promise, +): Promise { + const lockPath = `${configPath}.lock`; + const breakPath = `${lockPath}.break`; + const token = `${process.pid}:${randomUUID()}`; + const deadline = Date.now() + LOCK_TIMEOUT_MS; + let acquired = false; + while (!acquired) { + let created = false; + try { + await mkdir(lockPath, { mode: 0o700 }); + created = true; + await writeFile(join(lockPath, 'owner'), token, { + encoding: 'utf8', + mode: 0o600, + }); + acquired = true; + } catch (error) { + if (created) { + await rm(lockPath, { recursive: true, force: true }).catch( + () => undefined, + ); + } + if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error; + const lockStats = await lstat(lockPath).catch(() => null); + if (lockStats && (await isStaleLock(lockPath, lockStats.mtimeMs))) { + let breaker = false; + try { + await mkdir(breakPath, { mode: 0o700 }); + breaker = true; + const currentStats = await lstat(lockPath).catch(() => null); + if ( + currentStats && + (await isStaleLock(lockPath, currentStats.mtimeMs)) + ) { + await rm(lockPath, { recursive: true, force: true }); + } + } catch (breakError) { + if ((breakError as NodeJS.ErrnoException).code !== 'EEXIST') { + throw breakError; + } + } finally { + if (breaker) { + await rm(breakPath, { recursive: true, force: true }).catch( + () => undefined, + ); + } + } + if (Date.now() >= deadline) { + throw new Error(`Timed out waiting to update ${configPath}`); + } + await new Promise((resolve) => setTimeout(resolve, 25)); + continue; + } + if (Date.now() >= deadline) { + throw new Error(`Timed out waiting to update ${configPath}`); + } + await new Promise((resolve) => setTimeout(resolve, 25)); + } + } + try { + return await mutate(); + } finally { + if ((await readLockOwner(lockPath)) === token) { + await rm(lockPath, { recursive: true, force: true }).catch( + () => undefined, + ); + } + } +} diff --git a/src/utils/workspace-source-editor.ts b/src/utils/workspace-source-editor.ts index b75cd59f..ee09b7a3 100644 --- a/src/utils/workspace-source-editor.ts +++ b/src/utils/workspace-source-editor.ts @@ -328,7 +328,12 @@ export function workspaceSourceEditor(document: Document, original: string) { (start.endsWith('\n') ? '' : newline) + ' '.repeat(token.indent + indentWidth); } - const key = !implicitMap && source.key ? CST.stringify(source.key) : ''; + const keyNode = isMap(node) ? (item as Pair).key : undefined; + const key = !implicitMap && source.key + ? old && isScalar(keyNode) && !unchanged(keyNode) + ? renderScalar(keyNode, source.key, flow) + : CST.stringify(source.key) + : ''; let sep = implicitMap ? '' : text(source.sep); let body: string; let trailing = entry?.trailing ?? ''; diff --git a/src/utils/workspace-writer.ts b/src/utils/workspace-writer.ts index 5089169c..d03d4c7f 100644 --- a/src/utils/workspace-writer.ts +++ b/src/utils/workspace-writer.ts @@ -21,6 +21,8 @@ import { workspaceSourceEditor } from './workspace-source-editor.js'; interface WorkspaceWriteOptions { /** Disambiguate removal of declarations whose values are identical. */ removedPluginIndexes?: readonly number[]; + /** Preserve the original YAML entry when renaming a profile key. */ + renamedProfile?: { readonly from: string; readonly to: string }; } function isRecord(value: unknown): value is Record { @@ -59,17 +61,34 @@ export function serializeWorkspaceConfig( let plugins = document.get('plugins', true); if (isAlias(plugins)) plugins = plugins.resolve(document); const removedPlugins = new Set(options.removedPluginIndexes); + const profiles = document.get('profiles', true); function update(node: unknown, previous: unknown, next: unknown): Node { if (isNode(node) && isDeepStrictEqual(previous, next)) return node; if (isMap(node) && isRecord(previous) && isRecord(next)) { + let previousMap = previous; + const rename = options.renamedProfile; + if (node === profiles && rename) { + const key = node.items.find( + (pair) => isScalar(pair.key) && String(pair.key.value) === rename.from, + )?.key; + if (isScalar(key) && !node.has(rename.to)) { + key.value = rename.to; + previousMap = Object.fromEntries( + Object.entries(previous).map(([name, value]) => [ + name === rename.from ? rename.to : name, + value, + ]), + ); + } + } const keyFor = (key: string) => node.items.find( (pair) => isScalar(pair.key) && String(pair.key.value) === key, )?.key ?? key; // An inherited key cannot be deleted while its merge still supplies it. if ( - Object.keys(previous).some( + Object.keys(previousMap).some( (key) => next[key] === undefined && !node.has(keyFor(key)), ) ) { @@ -79,21 +98,21 @@ export function serializeWorkspaceConfig( typeof pair.key.value !== 'symbol' || pair.key.value.description !== '<<', ); - for (const [key, value] of Object.entries(previous)) { + for (const [key, value] of Object.entries(previousMap)) { if (!node.has(keyFor(key)) && next[key] !== undefined) node.set(key, document.createNode(value)); } } - for (const key of Object.keys(previous)) { + for (const key of Object.keys(previousMap)) { if (next[key] === undefined) node.delete(keyFor(key)); } for (const [key, value] of Object.entries(next)) { - if (value === undefined || isDeepStrictEqual(previous[key], value)) + if (value === undefined || isDeepStrictEqual(previousMap[key], value)) continue; const yamlKey = keyFor(key); node.set( yamlKey, - update(node.get(yamlKey, true), previous[key], value), + update(node.get(yamlKey, true), previousMap[key], value), ); } return node; diff --git a/tests/e2e/profile-rename.test.ts b/tests/e2e/profile-rename.test.ts new file mode 100644 index 00000000..58e51eab --- /dev/null +++ b/tests/e2e/profile-rename.test.ts @@ -0,0 +1,253 @@ +import { afterEach, beforeAll, beforeEach, expect, test } from 'bun:test'; +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + readdirSync, + rmSync, + symlinkSync, + writeFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; + +const repo = join(import.meta.dir, '../..'); +const cli = join(repo, 'dist/index.js'); +const fixtureTimeout = 30_000; +const fixtureYaml = [ + '# User workspace', + 'profiles:', + " 'work': # Keep this declaration comment", + ' clients:', + ' - name: codex', + ' launcher: run-codex', + ' - name: opencode', + ' launcher: run-opencode', + ' spare: {clients: [{name: omp}]} # Leave this syntax alone', + '', +].join('\n'); + +let root: string; +let home: string; +let workspace: string; +let profiles: string; +let project: string; +let bin: string; +let env: NodeJS.ProcessEnv; + +function read(path: string) { + return readFileSync(path, 'utf8'); +} + +function run(args: string[], overrides: NodeJS.ProcessEnv = {}) { + return Bun.spawnSync(['node', cli, ...args], { + cwd: project, + env: { ...env, ...overrides }, + stdin: 'ignore', + stdout: 'pipe', + stderr: 'pipe', + }); +} + +function json(args: string[], exitCode = 0) { + const result = run(['--json', ...args]); + expect(result.exitCode, result.stdout.toString() + result.stderr.toString()).toBe(exitCode); + return JSON.parse(result.stdout.toString()); +} + +function seedFile(path: string, content: string) { + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, content); +} + +beforeAll(() => { + const result = Bun.spawnSync(['bun', 'run', 'build'], { cwd: repo }); + if (result.exitCode !== 0) throw new Error(result.stderr.toString()); +}); + +beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'allagents-profile-rename-')); + home = join(root, 'home'); + workspace = join(home, '.allagents', 'workspace.yaml'); + profiles = join(home, '.allagents', 'profiles'); + project = join(root, 'project'); + bin = join(home, '.local', 'bin'); + mkdirSync(project); + mkdirSync(bin, { recursive: true }); + // The version probe and generated launcher invoke the local fixture executable. + writeFileSync(join(bin, 'codex'), [ + '#!/bin/sh', + 'if [ "$1" = "--version" ]; then echo "codex-cli 99.0.0"; exit; fi', + 'if [ "$1" = "plugin" ]; then echo "add list marketplace remove"; exit; fi', + 'printf "%s\\n" "$CODEX_HOME" "$@"', + '', + ].join('\n'), { mode: 0o755 }); + writeFileSync(join(bin, 'copilot'), '#!/bin/sh\necho "GitHub Copilot CLI 99.0.0"\n', { mode: 0o755 }); + env = { + ...process.env, + ALLAGENTS_TEST_HOME: home, + HOME: home, + USERPROFILE: home, + PATH: `${bin}${process.platform === 'win32' ? ';' : ':'}${process.env.PATH}`, + CI: '1', + }; + seedFile(workspace, fixtureYaml); +}); + +afterEach(() => rmSync(root, { recursive: true, force: true })); + +test('previews a declared-only rename and requires confirmation before changing YAML', () => { + const dryRun = json(['profile', 'rename', 'spare', 'backup', '--dry-run']); + expect(dryRun.data).toMatchObject({ + status: 'planned', + profile: 'spare', + newProfile: 'backup', + installed: false, + steps: [{ kind: 'workspace', from: workspace, to: workspace }], + }); + expect(json(['profile', 'rename', 'spare', 'backup'], 2).error).toContain('--yes'); + expect(read(workspace)).toBe(fixtureYaml); + expect(existsSync(profiles)).toBe(false); + expect(existsSync(`${workspace}.profile-rename.json`)).toBe(false); + + expect(json(['profile', 'rename', 'spare', 'backup', '--yes']).data.status).toBe('renamed'); + expect(read(workspace)).toBe(fixtureYaml.replace(' spare:', ' backup:')); + expect(existsSync(profiles)).toBe(false); +}, fixtureTimeout); + +test.skipIf(process.platform === 'win32')('moves installed data and updates state and the stable launcher through the built CLI', () => { + expect(json(['profile', 'install', 'work', '--yes', '--offline']).success).toBe(true); + const oldRoot = join(profiles, 'work'); + const newRoot = join(profiles, 'office'); + const oldClient = join(oldRoot, 'clients', 'codex', 'home'); + const newClient = join(newRoot, 'clients', 'codex', 'home'); + seedFile(join(oldClient, 'sessions/rollout.jsonl'), 'session history'); + seedFile(join(oldClient, 'auth.json'), 'auth fixture'); + seedFile(join(oldRoot, 'oauth-proxy/service/tokens.json'), 'proxy auth fixture'); + seedFile(join(oldRoot, 'clients/opencode/config/user-notes.txt'), 'user notes'); + const oldSettings = read(join(oldClient, 'work.config.toml')); + const launcher = join(bin, 'run-codex'); + const oldLauncher = read(launcher); + const oldState = read(join(oldRoot, 'state.json')); + + const preview = json(['profile', 'rename', 'work', 'office', '--dry-run']); + expect(preview.data.installed).toBe(true); + expect(preview.data.steps.map((step: { kind: string }) => step.kind)) + .toEqual(['root', 'settings', 'launcher', 'launcher', 'state', 'workspace']); + expect(existsSync(newRoot)).toBe(false); + expect(read(launcher)).toBe(oldLauncher); + expect(read(join(oldRoot, 'state.json'))).toBe(oldState); + expect(read(workspace)).toBe(fixtureYaml); + + expect(json(['profile', 'rename', 'work', 'office', '--yes']).data.status).toBe('renamed'); + expect(existsSync(oldRoot)).toBe(false); + expect(read(workspace)).toBe(fixtureYaml.replace("'work':", "'office':")); + expect(read(join(newClient, 'office.config.toml'))).toBe(oldSettings); + expect(existsSync(join(newClient, 'work.config.toml'))).toBe(false); + expect(read(join(newClient, 'sessions/rollout.jsonl'))).toBe('session history'); + expect(read(join(newClient, 'auth.json'))).toBe('auth fixture'); + expect(read(join(newRoot, 'oauth-proxy/service/tokens.json'))).toBe('proxy auth fixture'); + expect(read(join(newRoot, 'clients/opencode/config/user-notes.txt'))).toBe('user notes'); + const launched = Bun.spawnSync([launcher, 'user-arg'], { env }); + expect(launched.exitCode).toBe(0); + expect(launched.stdout.toString().trim().split('\n')).toEqual([newClient, '--profile', 'office', 'user-arg']); + expect(read(join(bin, 'run-opencode'))).toContain(join(newRoot, 'clients/opencode/config')); + expect(json(['profile', 'status', 'office']).data.status).toBe('installed'); + expect(json(['update', '--profile', 'office', '--offline']).success).toBe(true); + expect(read(join(newClient, 'sessions/rollout.jsonl'))).toBe('session history'); +}, fixtureTimeout); + +test.skipIf(process.platform === 'win32')('refuses on declaration, directory, settings, launcher, or symlink conflicts before moving data', () => { + json(['profile', 'install', 'work', '--yes', '--offline']); + const oldRoot = join(profiles, 'work'); + const newRoot = join(profiles, 'office'); + const client = join(oldRoot, 'clients/codex/home'); + const state = read(join(oldRoot, 'state.json')); + const firstLauncher = join(bin, 'run-codex'); + const secondLauncher = join(bin, 'run-opencode'); + const firstLauncherContent = read(firstLauncher); + function reject(error: string) { + expect(json(['profile', 'rename', 'work', 'office', '--yes'], 1).error).toContain(error); + expect(read(workspace)).toBe(fixtureYaml); + expect(read(join(oldRoot, 'state.json'))).toBe(state); + expect(read(firstLauncher)).toBe(firstLauncherContent); + expect(existsSync(`${workspace}.profile-rename.json`)).toBe(false); + } + + expect(json(['profile', 'rename', 'work', 'spare', '--yes'], 1).error).toContain('already declared'); + mkdirSync(newRoot); + reject('destination already exists'); + rmSync(newRoot, { recursive: true }); + + const conflictingSettings = join(client, 'office.config.toml'); + seedFile(conflictingSettings, 'user settings'); + reject('destination already exists'); + expect(read(conflictingSettings)).toBe('user settings'); + rmSync(conflictingSettings); + + symlinkSync(workspace, join(client, 'link')); + reject('Unsafe profile entry'); + rmSync(join(client, 'link')); + + seedFile(join(client, 'state_5.sqlite'), 'session database fixture'); + reject('session database require a separate migration'); + rmSync(join(client, 'state_5.sqlite')); + + seedFile(join(client, 'plugins/registry.toml'), 'native registry fixture'); + reject('has native data'); + rmSync(join(client, 'plugins'), { recursive: true }); + + seedFile(secondLauncher, 'user launcher'); + reject('modified'); + expect(read(secondLauncher)).toBe('user launcher'); + expect(existsSync(newRoot)).toBe(false); +}, fixtureTimeout); + +test.skipIf(process.platform === 'win32')('rejects an installed client without a rename implementation', () => { + const config = 'profiles: {work: {clients: [{name: copilot}]}}\n'; + seedFile(workspace, config); + json(['profile', 'install', 'work', '--yes', '--offline']); + expect(json(['profile', 'rename', 'work', 'office', '--yes'], 1).error) + .toContain("Installed profile rename is unsupported for 'copilot'"); + expect(read(workspace)).toBe(config); + expect(existsSync(join(profiles, 'work', 'state.json'))).toBe(true); + expect(existsSync(join(profiles, 'office'))).toBe(false); +}, fixtureTimeout); + +test.skipIf(process.platform === 'win32')('resumes after a process stop before publishing the declaration', () => { + json(['profile', 'install', 'work', '--yes', '--offline']); + const oldRoot = join(profiles, 'work'); + const newRoot = join(profiles, 'office'); + const journal = `${workspace}.profile-rename.json`; + const session = 'clients/codex/home/sessions/recover.jsonl'; + seedFile(join(oldRoot, session), 'keep me'); + const preload = join(root, 'stop-before-workspace.cjs'); + writeFileSync(preload, [ + 'const fs = require("node:fs/promises");', + 'const rename = fs.rename;', + 'fs.rename = (from, to) => to === process.env.TEST_WORKSPACE', + ' ? process.kill(process.pid, "SIGKILL") : rename(from, to);', + 'require("node:module").syncBuiltinESMExports();', + ].join('\n')); + const interrupted = run(['--json', 'profile', 'rename', 'work', 'office', '--yes'], { + NODE_OPTIONS: `--require="${preload}"`, + TEST_WORKSPACE: workspace, + }); + expect(interrupted.signalCode).toBe('SIGKILL'); + expect(read(workspace)).toBe(fixtureYaml); + expect(existsSync(journal)).toBe(true); + expect(existsSync(oldRoot)).toBe(false); + expect(read(join(newRoot, session))).toBe('keep me'); + expect(json(['profile', 'install', 'work', '--yes'], 1).error).toContain('rename is incomplete'); + + const preview = json(['profile', 'rename', 'work', 'office', '--dry-run']); + expect(preview.data.recovering).toBe(true); + expect(read(workspace)).toBe(fixtureYaml); + expect(json(['profile', 'rename', 'work', 'office', '--yes']).data.recovering).toBe(true); + expect(read(workspace)).toBe(fixtureYaml.replace("'work':", "'office':")); + expect(read(join(newRoot, session))).toBe('keep me'); + expect(existsSync(journal)).toBe(false); + expect(readdirSync(dirname(workspace)).sort()).toEqual(['profiles', 'workspace.yaml']); + expect(json(['profile', 'status', 'office']).data.status).toBe('installed'); +}, fixtureTimeout); diff --git a/tests/unit/cli/profile-command.test.ts b/tests/unit/cli/profile-command.test.ts index 8dda2b0a..44142e4a 100644 --- a/tests/unit/cli/profile-command.test.ts +++ b/tests/unit/cli/profile-command.test.ts @@ -859,6 +859,7 @@ describe('profile root registration', () => { 'profile list', 'profile status', 'profile remove', + 'profile rename', ]); }); From 7a92dc0a23b50f7714bc6cc8d6805c4032e0bef6 Mon Sep 17 00:00:00 2001 From: Christopher Tso Date: Thu, 26 Nov 2026 13:33:01 +1100 Subject: [PATCH 2/4] fix(cli): preserve intervening edits and make profile rename recoverable --- docs/src/content/docs/docs/reference/cli.mdx | 34 +- src/cli/commands/profile.ts | 10 +- src/core/mcp-oauth-storage.ts | 229 +----- src/core/mcp-servers.ts | 7 +- src/core/profile/adapters/claude.ts | 9 +- src/core/profile/manager.ts | 3 +- src/core/profile/plan.ts | 2 +- src/core/profile/rename-transaction.ts | 244 ++++-- src/core/profile/rename.ts | 156 +++- src/core/profile/types.ts | 2 +- src/core/prune.ts | 20 +- src/core/user-workspace.ts | 736 ++++++++++--------- src/core/workspace-modify.ts | 6 +- src/core/workspace.ts | 8 +- src/utils/filesystem-lock.ts | 234 ++++++ src/utils/workspace-config-lock.ts | 111 +-- tests/e2e/profile-rename.test.ts | 78 +- tests/unit/core/user-workspace.test.ts | 13 + 18 files changed, 1102 insertions(+), 800 deletions(-) create mode 100644 src/utils/filesystem-lock.ts diff --git a/docs/src/content/docs/docs/reference/cli.mdx b/docs/src/content/docs/docs/reference/cli.mdx index f35a3ee6..f2298814 100644 --- a/docs/src/content/docs/docs/reference/cli.mdx +++ b/docs/src/content/docs/docs/reference/cli.mdx @@ -113,11 +113,10 @@ allagents profile install [--yes] [--dry-run] [--offline] allagents profile list allagents profile status [name] allagents profile remove [--yes] [--dry-run] [--offline] -allagents profile rename [--yes] [--dry-run] ``` -Profile declarations exist only in `~/.allagents/workspace.yaml`. `install`, -`remove`, and `rename` display a complete plan before mutation and require confirmation; +Profile declarations exist only in `~/.allagents/workspace.yaml`. `install` +and `remove` display a complete plan before mutation and require confirmation; scripts and JSON mode must pass `--yes`. `--dry-run` emits the same resolved plan without writing profile state, client files, native package state, or launchers. @@ -139,24 +138,35 @@ retains modified, shared, failed, or uncorroborated resources for inspection and retry. There is intentionally no `allagents profile update`; use repeatable `allagents update --profile `. +#### profile rename + +```bash +allagents profile rename [--yes] [--dry-run] +``` + `rename` changes the declaration key and keeps any configured launcher names. -For installed Claude Code, Codex, and OpenCode profiles, it can move a complete, -file-only installation with its isolated client files, session data, and stored -credentials. OpenCode data shared outside the profile stays where OpenCode keeps -it. Uninstalled declarations can be renamed regardless of client. +The command previews the changes and asks for confirmation. Pass `--yes` in +scripts and JSON mode. `--dry-run` prints the plan without changing files. +Rename can move complete file-only installations for Claude Code on Linux or +Windows, Codex, and OpenCode. It moves isolated client files, session data, and +file-based credentials. Shared OpenCode data stays in its original location. +Uninstalled declarations can be renamed regardless of client. Close clients using the profile before applying. Rename stops on a destination collision, native plugin data, a symbolic link in the profile tree, a modified launcher, or generated settings that embed a profile selector or the old root. -Codex session databases contain absolute paths and require a separate migration, -as do installed Copilot, Pi, and OMP profiles and installations with partial -state. External references, including T3 provider config -or home paths and custom scripts, need to be updated separately. +Codex session databases contain absolute paths, and Claude Code on macOS uses +Keychain credentials. These cases require a separate migration, as do installed +Copilot, Pi, and OMP profiles and installations with partial state. External +references, including T3 provider config or home paths and custom scripts, need +to be updated separately. If rename is interrupted after it starts moving files, rerun the same `allagents profile rename --yes` command to resume. Keep the recovery record beside `workspace.yaml` and wait until rename completes before editing -the workspace or starting the affected clients. +the workspace or starting the affected clients. If a conflict is reported, move +the conflicting file or directory aside before retrying. If the error reports a +preserved edit, keep that file and reconcile its contents before resuming. ### status diff --git a/src/cli/commands/profile.ts b/src/cli/commands/profile.ts index 38ef410d..952f6083 100644 --- a/src/cli/commands/profile.ts +++ b/src/cli/commands/profile.ts @@ -342,8 +342,16 @@ async function executeRename( if (!runtime.isJson()) { const action = plan.recovering ? 'Resume renaming' : 'Rename'; runtime.print(`${action} profile '${plan.profile}' to '${plan.newProfile}'`); + const labels = { + root: 'Move profile data', + settings: 'Move client settings', + launcher: 'Retarget launcher', + state: 'Transfer installation state', + workspace: 'Update workspace declaration', + }; for (const { kind, from, to } of plan.steps) { - runtime.print(` ${kind}: ${terminalSafe(from)}${from === to ? '' : ` → ${terminalSafe(to)}`}`); + runtime.print(` ${labels[kind]}: ${terminalSafe(from)}`); + if (from !== to) runtime.print(` → ${terminalSafe(to)}`); } for (const warning of plan.warnings) runtime.print(warning); } diff --git a/src/core/mcp-oauth-storage.ts b/src/core/mcp-oauth-storage.ts index 98efb2ce..9b8a2e0c 100644 --- a/src/core/mcp-oauth-storage.ts +++ b/src/core/mcp-oauth-storage.ts @@ -1,223 +1,16 @@ -import { AsyncLocalStorage } from 'node:async_hooks'; import { randomUUID } from 'node:crypto'; import { - chmod, - mkdir, - open, - readdir, - readFile, - rename, - rm, -} from 'node:fs/promises'; -import { dirname, join, resolve } from 'node:path'; - -export async function readOAuthJson(path: string): Promise { - try { - return JSON.parse(await readFile(path, 'utf8')) as T; - } catch (error) { - if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined; - throw error; - } -} - -export async function writeOAuthFile( - path: string, - content: string, -): Promise { - await mkdir(dirname(path), { recursive: true, mode: 0o700 }); - await chmod(dirname(path), 0o700); - const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`; - try { - const handle = await open(temporary, 'wx', 0o600); - try { - await handle.writeFile(content, 'utf8'); - await handle.sync(); - } finally { - await handle.close(); - } - await rename(temporary, path); - } finally { - await rm(temporary, { force: true }); - } -} - -export function waitForOAuth( - milliseconds: number, - signal: AbortSignal, -): Promise { - signal.throwIfAborted(); - return new Promise((resolve, reject) => { - const abort = () => { - clearTimeout(timer); - reject(signal.reason); - }; - const timer = setTimeout(() => { - signal.removeEventListener('abort', abort); - resolve(); - }, milliseconds); - signal.addEventListener('abort', abort, { once: true }); - }); -} - -interface LockRecord { - pid: number; - nonce: string; - choosing: boolean; - ticket: number; -} - -interface LocalLease { - active: boolean; - children: number; - waiters: Set<() => void>; -} - -async function drainLease(lease: LocalLease): Promise { - while (lease.children > 0) - await new Promise((resolve) => lease.waiters.add(resolve)); - lease.active = false; -} - -async function waitForLeaseDrain( - drain: Promise, - signal: AbortSignal, -): Promise { - signal.throwIfAborted(); - await new Promise((resolve, reject) => { - const abort = () => reject(signal.reason); - signal.addEventListener('abort', abort, { once: true }); - void drain - .then(resolve, reject) - .finally(() => signal.removeEventListener('abort', abort)); - }); -} -const localLeases = new AsyncLocalStorage>(); - -function ownerIsAlive(pid: number): boolean { - try { - process.kill(pid, 0); - return true; - } catch (error) { - return (error as NodeJS.ErrnoException).code !== 'ESRCH'; - } -} - -/** - * A filesystem bakery lock: each contender publishes its own choosing flag and - * ticket, then waits for lower tickets (UUID breaks ties). Records are atomic; - * release and dead-owner recovery only unlink that owner's unique filename. - * The shared directory stays put, so a stale follower cannot retire a new lock. - */ -export async function withOAuthLock( - path: string, - signal: AbortSignal, - timeoutMs: number, - operation: () => Promise, -): Promise { - signal.throwIfAborted(); - const lockPath = resolve(path); - const parentLease = localLeases.getStore()?.get(lockPath); - if (parentLease?.active) { - parentLease.children++; - try { - return await operation(); - } finally { - parentLease.children--; - if (parentLease.children === 0) { - for (const resolve of parentLease.waiters) resolve(); - parentLease.waiters.clear(); - } - } - } - await mkdir(lockPath, { recursive: true, mode: 0o700 }); - const deadline = Date.now() + timeoutMs; - const owner: LockRecord = { - pid: process.pid, - nonce: randomUUID(), - choosing: true, - ticket: 0, - }; - const filename = `${owner.pid}-${owner.nonce}.json`; - const ownerPath = join(lockPath, filename); - let lease: LocalLease | undefined; - const records = async (): Promise< - Array<{ filename: string; owner: LockRecord }> - > => { - const result: Array<{ filename: string; owner: LockRecord }> = []; - for (const name of await readdir(lockPath)) { - if (!/^\d+-[a-f0-9-]+\.json$/.test(name)) continue; - const recordPath = join(lockPath, name); - const record = await readOAuthJson(recordPath); - if (!record) continue; - if ( - name !== `${record.pid}-${record.nonce}.json` || - !Number.isSafeInteger(record.pid) || - record.pid <= 0 || - !Number.isSafeInteger(record.ticket) || - record.ticket < 0 || - typeof record.choosing !== 'boolean' - ) - throw new Error('Invalid OAuth lock owner record'); - if (!ownerIsAlive(record.pid)) { - await rm(recordPath, { force: true }); - continue; - } - result.push({ filename: name, owner: record }); - } - return result; - }; - let outcome: { value: T } | { error: unknown }; - try { - await writeOAuthFile(ownerPath, JSON.stringify(owner)); - const contenders = await records(); - owner.ticket = - 1 + Math.max(0, ...contenders.map((record) => record.owner.ticket)); - owner.choosing = false; - await writeOAuthFile(ownerPath, JSON.stringify(owner)); - while (true) { - signal.throwIfAborted(); - const blocked = (await records()).some( - (record) => - record.filename !== filename && - (record.owner.choosing || - record.owner.ticket < owner.ticket || - (record.owner.ticket === owner.ticket && - record.filename < filename)), - ); - if (!blocked) break; - if (Date.now() >= deadline) - throw new Error( - 'Timed out waiting for another OAuth authorization operation', - ); - await waitForOAuth(Math.min(25, deadline - Date.now()), signal); - } - signal.throwIfAborted(); - lease = { active: true, children: 0, waiters: new Set() }; - const inherited = new Map(localLeases.getStore()); - inherited.set(lockPath, lease); - outcome = { value: await localLeases.run(inherited, operation) }; - } catch (error) { - outcome = { error }; - } - const release = async () => { - const current = await readOAuthJson(ownerPath); - if (current?.nonce === owner.nonce) await rm(ownerPath, { force: true }); - }; - if (lease) { - const drain = drainLease(lease); - try { - await waitForLeaseDrain(drain, signal); - } catch (error) { - // Cancellation returns promptly, but an already running child retains - // ownership until it finishes. Releasing early would permit cache races. - void drain.then(release).catch(() => {}); - throw error; - } - } - await release(); - if ('error' in outcome) throw outcome.error; - return outcome.value; -} + readPrivateJson as readOAuthJson, + withFilesystemLock as withOAuthLock, + writePrivateFile as writeOAuthFile, +} from '../utils/filesystem-lock.js'; + +export { + readPrivateJson as readOAuthJson, + waitForLock as waitForOAuth, + withFilesystemLock as withOAuthLock, + writePrivateFile as writeOAuthFile, +} from '../utils/filesystem-lock.js'; export function oauthAuthorizationLockPath(cacheDir: string): string { return `${cacheDir}.authorization.lock`; diff --git a/src/core/mcp-servers.ts b/src/core/mcp-servers.ts index 0c912559..e4afa24a 100644 --- a/src/core/mcp-servers.ts +++ b/src/core/mcp-servers.ts @@ -30,10 +30,9 @@ import { validateProjectWorkspaceConfig, validateUserWorkspaceConfig, } from '../utils/workspace-parser.js'; -import { withWorkspaceConfigLock } from '../utils/workspace-config-lock.js'; +import { assertNoPendingProfileRename, withWorkspaceConfigLock } from '../utils/workspace-config-lock.js'; import { serializeWorkspaceConfigFile } from '../utils/workspace-writer.js'; import { flattenZodIssues } from '../utils/zod-issues.js'; -import { assertNoPendingProfileRename } from './profile/rename-transaction.js'; import { ensureUserWorkspace, getUserWorkspaceConfigPath, @@ -330,7 +329,7 @@ export async function addMcpServer( await ensureDestinationForAdd(destination); return await withWorkspaceConfigLock(destination.configPath, async () => { - await assertNoPendingProfileRename(destination.configPath); + if (destination.kind !== 'project') await assertNoPendingProfileRename(destination.configPath); const document = await readDestinationConfig(destination); const container = selectDestinationContainer(destination, document); container.mcpServers ??= {}; @@ -372,7 +371,7 @@ export async function removeMcpServer( } return await withWorkspaceConfigLock(destination.configPath, async () => { - await assertNoPendingProfileRename(destination.configPath); + if (destination.kind !== 'project') await assertNoPendingProfileRename(destination.configPath); const document = await readDestinationConfig(destination); const container = selectDestinationContainer(destination, document); if (!container.mcpServers || !(name in container.mcpServers)) { diff --git a/src/core/profile/adapters/claude.ts b/src/core/profile/adapters/claude.ts index a8072146..2a8a2e3e 100644 --- a/src/core/profile/adapters/claude.ts +++ b/src/core/profile/adapters/claude.ts @@ -131,7 +131,14 @@ function serializeClaudeMcp( export class ClaudeProfileAdapter implements NativeProfileAdapter { readonly client = 'claude' as const; - readonly rename = { nativeLocations: ['plugins'] }; + readonly rename = { + nativeLocations: ['plugins'], + async assertRelocatable(_context: ProfileClientContext, options: ProfileContextOptions): Promise { + if (options.platform === 'darwin') { + throw new Error('Installed Claude Code profiles on macOS require a separate Keychain migration.'); + } + }, + }; readonly capabilities = CAPABILITIES; readonly nativeClient = new ClaudeNativeClient({ minimumVersion: CLAUDE_MINIMUM_VERSION, diff --git a/src/core/profile/manager.ts b/src/core/profile/manager.ts index 0a2533cc..ce869bf0 100644 --- a/src/core/profile/manager.ts +++ b/src/core/profile/manager.ts @@ -13,7 +13,7 @@ import { getPluginClients, resolveInstallMode, } from '../../models/workspace-config.js'; -import { withWorkspaceConfigLock } from '../../utils/workspace-config-lock.js'; +import { assertNoPendingProfileRename, withWorkspaceConfigLock } from '../../utils/workspace-config-lock.js'; import { getProfileAdapter } from './adapters/registry.js'; import { assertSafeProfilePath, @@ -44,7 +44,6 @@ import { readProfileWorkspace, resolveProfileRuntimeOptions, } from './plan.js'; -import { assertNoPendingProfileRename } from './rename-transaction.js'; import { checkpointProfileResource, createProfileState, diff --git a/src/core/profile/plan.ts b/src/core/profile/plan.ts index d6c868f3..586359d8 100644 --- a/src/core/profile/plan.ts +++ b/src/core/profile/plan.ts @@ -50,7 +50,7 @@ import type { ProfileStepKind, } from './index.js'; import { renderProfileLaunchers } from './launcher.js'; -import { assertNoPendingProfileRename } from './rename-transaction.js'; +import { assertNoPendingProfileRename } from '../../utils/workspace-config-lock.js'; import { resolveProfileFileSource, type ResolvedProfileFileSource } from './source.js'; import { hashProfileDeclaration, diff --git a/src/core/profile/rename-transaction.ts b/src/core/profile/rename-transaction.ts index 877feeef..d71a0656 100644 --- a/src/core/profile/rename-transaction.ts +++ b/src/core/profile/rename-transaction.ts @@ -2,8 +2,10 @@ import { randomUUID } from 'node:crypto'; import { link, lstat, + mkdir, open, readFile, + readdir, rename, rm, unlink, @@ -32,27 +34,25 @@ const Replacement = z.object({ before: ProfileSha256Schema, content: z.string(), }); +const DirectoryIdentity = z.object({ device: z.string(), inode: z.string() }); export const RenameRecordSchema = z.object({ version: z.literal(1), id: z.uuid(), profile: ProfileNameSchema, newProfile: ProfileNameSchema, + declarationDigest: ProfileSha256Schema, workspaceBefore: ProfileSha256Schema, - workspaceAfter: ProfileSha256Schema, - root: z - .object({ - device: z.string(), - inode: z.string(), - namedFiles: z.array( - z.object({ - from: RelativePath, - to: RelativePath, - fingerprint: ProfileSha256Schema, - }), - ), - state: Replacement.optional(), - }) - .optional(), + root: DirectoryIdentity.extend({ + reservation: DirectoryIdentity.optional(), + namedFiles: z.array( + z.object({ + from: RelativePath, + to: RelativePath, + fingerprint: ProfileSha256Schema, + }), + ), + state: Replacement.optional(), + }).optional(), launchers: z.array( Replacement.extend({ name: z.string().regex(/^[a-z0-9][a-z0-9._-]{0,67}$/), @@ -63,10 +63,6 @@ export const RenameRecordSchema = z.object({ export type RenameRecord = z.infer; -export function profileRenameRecordPath(workspacePath: string): string { - return `${workspacePath}.profile-rename.json`; -} - export async function profileRenameStats(path: string) { return lstat(path).catch((error) => { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; @@ -74,16 +70,6 @@ export async function profileRenameStats(path: string) { }); } -export async function assertNoPendingProfileRename( - workspacePath: string, -): Promise { - if (await profileRenameStats(profileRenameRecordPath(workspacePath))) { - throw new Error( - 'A profile rename is incomplete. Rerun the same profile rename with --yes before changing profiles.', - ); - } -} - export async function readProfileRenameRecord( path: string, ): Promise { @@ -102,14 +88,23 @@ export async function readProfileRenameRecord( return result.data; } -/** Publish one replacement atomically. The recovery record tracks either version. */ -export async function publishRenameFile( +export function capturedRenameFile( + path: string, + transactionId: string, +): string { + return join( + dirname(path), + `.${basename(path)}.profile-rename-${transactionId}.previous`, + ); +} + +async function stageRenameFile( path: string, content: string, - previous: string | null, mode: number, - transactionId?: string, -): Promise { + transactionId: string | undefined, + publish: (temporary: string) => Promise, +): Promise { const parent = dirname(path); await assertSafeProfilePath(parent, path); const temporary = join( @@ -128,20 +123,114 @@ export async function publishRenameFile( await handle.sync(); await handle.close(); await assertSafeProfilePath(parent, path); - if (previous === null) { - await link(temporary, path); - } else { - const current = await fingerprintProfileFile(path); - if (current === sha256Fingerprint(content)) return; - if (current !== previous) throw changed(path); - await rename(temporary, path); - } + return await publish(temporary); } finally { await handle.close(); await rm(temporary, { force: true }); } } +export async function writeRenameRecord( + path: string, + record: RenameRecord, + replace = false, +): Promise { + await stageRenameFile( + path, + JSON.stringify(record), + 0o600, + undefined, + (temporary) => (replace ? rename(temporary, path) : link(temporary, path)), + ); +} + +export async function inspectReplacement( + path: string, + before: string, + after: string, + transactionId: string, +) { + const capture = capturedRenameFile(path, transactionId); + await assertSafeProfilePath(dirname(path), capture); + const [current, previous] = await Promise.all([ + fingerprintProfileFile(path), + fingerprintProfileFile(capture), + ]); + if (previous !== null && previous !== before) { + throw new Error( + `Profile rename found an intervening edit preserved at ${capture}`, + ); + } + if ( + current !== before && + current !== after && + !(current === null && previous !== null) + ) { + throw changed(path); + } + return { current, capture, captured: previous !== null }; +} + +/** Capture before replacing so a concurrent edit can win without losing bytes. */ +export async function publishRenameFile( + path: string, + content: string, + before: string, + mode: number, + transactionId: string, +): Promise { + const after = sha256Fingerprint(content); + await stageRenameFile( + path, + content, + mode, + transactionId, + async (temporary) => { + const { current, capture, captured } = await inspectReplacement( + path, + before, + after, + transactionId, + ); + if (current === after) { + if (captured) await unlink(capture); + return; + } + if (!captured) await rename(path, capture); + else if (current !== null) { + const [source, previous] = await Promise.all([ + lstat(path, { bigint: true }), + lstat(capture, { bigint: true }), + ]); + if (source.ino !== previous.ino || source.dev !== previous.dev) + throw changed(path); + await unlink(path); + } + + if ((await fingerprintProfileFile(capture)) !== before) { + // Restore the captured edit only if the original pathname is still free. + try { + await link(capture, path); + await unlink(capture); + } catch (error) { + throw new Error( + `Profile rename preserved a concurrent edit at ${capture}`, + { cause: error }, + ); + } + throw changed(path); + } + await link(temporary, path); + if ((await fingerprintProfileFile(capture)) !== before) { + throw new Error( + `Profile rename preserved a concurrent edit at ${capture}`, + ); + } + await unlink(capture); + }, + ); +} + function changed(path: string): Error { return new Error(`Profile rename found a missing or changed file at ${path}`); } @@ -160,6 +249,48 @@ export async function getRenameRootIdentity(path: string) { ); } +function sameDirectory( + left: z.infer | null | undefined, + right: z.infer | null | undefined, +): boolean { + return left?.device === right?.device && left?.inode === right?.inode; +} + +export async function moveProfileRoot( + record: RenameRecord, + journal: string, + oldRoot: string, + newRoot: string, +): Promise { + if (!record.root) throw changed(oldRoot); + if (process.platform !== 'win32') { + // POSIX rename can replace an empty directory. Exclusively reserve our + // destination and only replace an empty directory with the recorded inode. + let reservation = record.root.reservation; + if (!(await profileRenameStats(newRoot))) { + await mkdir(newRoot, { mode: 0o700 }); + reservation = (await getRenameRootIdentity(newRoot)) ?? undefined; + if (!reservation) throw changed(newRoot); + await writeRenameRecord( + journal, + { ...record, root: { ...record.root, reservation } }, + true, + ); + } + if ( + !sameDirectory(reservation, await getRenameRootIdentity(newRoot)) || + (await readdir(newRoot)).length > 0 + ) { + throw new Error(`Profile destination already exists: ${newRoot}`); + } + } else if (await profileRenameStats(newRoot)) { + throw new Error(`Profile destination already exists: ${newRoot}`); + } + if (!sameDirectory(await getRenameRootIdentity(oldRoot), record.root)) + throw changed(oldRoot); + await rename(oldRoot, newRoot); +} + export function relativeRenamePath(root: string, path: string): string { return RelativePath.parse(relative(root, path)); } @@ -179,16 +310,20 @@ export async function inspectRenameProgress( const oldIdentity = await getRenameRootIdentity(oldRoot); const newIdentity = await getRenameRootIdentity(newRoot); const identity = oldIdentity ?? newIdentity; - if (newIdentity && (!record.root || oldIdentity)) { - throw new Error(`Profile destination already exists: ${newRoot}`); - } if ( - identity?.inode !== record.root?.inode || - identity?.device !== record.root?.device + newIdentity && + (!record.root || + (oldIdentity && !sameDirectory(newIdentity, record.root.reservation))) ) { + throw new Error(`Profile destination already exists: ${newRoot}`); + } + if (!sameDirectory(identity, record.root)) { throw new Error(`Profile directory changed during rename: ${oldRoot}`); } - const currentRoot = newIdentity ? newRoot : oldRoot; + if (oldIdentity && newIdentity && (await readdir(newRoot)).length > 0) { + throw new Error(`Profile destination already exists: ${newRoot}`); + } + const currentRoot = oldIdentity ? oldRoot : newRoot; const moves = []; for (const move of record.root?.namedFiles ?? []) { const from = join(currentRoot, move.from); @@ -228,13 +363,12 @@ export async function inspectRenameProgress( } for (const entry of replacements) { await assertSafeProfilePath(dirname(entry.path), entry.path); - const fingerprint = await fingerprintProfileFile(entry.path); - if ( - fingerprint !== entry.before && - fingerprint !== sha256Fingerprint(entry.content) - ) { - throw changed(entry.path); - } + await inspectReplacement( + entry.path, + entry.before, + sha256Fingerprint(entry.content), + record.id, + ); } return { moveRoot: oldIdentity !== null, moves }; } diff --git a/src/core/profile/rename.ts b/src/core/profile/rename.ts index 2e28586b..d79112d4 100644 --- a/src/core/profile/rename.ts +++ b/src/core/profile/rename.ts @@ -1,5 +1,5 @@ import { randomUUID } from 'node:crypto'; -import { lstat, readFile, readdir, rename, unlink } from 'node:fs/promises'; +import { readFile, readdir, unlink } from 'node:fs/promises'; import { dirname, join } from 'node:path'; import { isDeepStrictEqual } from 'node:util'; import type { @@ -10,7 +10,10 @@ import { type ProfileDeclaration, ProfileNameSchema, } from '../../models/workspace-config.js'; -import { withWorkspaceConfigLock } from '../../utils/workspace-config-lock.js'; +import { + profileRenameRecordPath, + withWorkspaceConfigLock, +} from '../../utils/workspace-config-lock.js'; import { validateUserWorkspaceConfig } from '../../utils/workspace-parser.js'; import { serializeWorkspaceConfig } from '../../utils/workspace-writer.js'; import { loadYaml } from '../../utils/yaml.js'; @@ -28,15 +31,18 @@ import { resolveProfileRuntimeOptions, } from './plan.js'; import { + capturedRenameFile, getRenameRootIdentity, inspectRenameProgress, + inspectReplacement, moveNamedProfileFile, - profileRenameRecordPath, + moveProfileRoot, profileRenameStats, publishRenameFile, readProfileRenameRecord, relativeRenamePath, type RenameRecord, + writeRenameRecord, } from './rename-transaction.js'; import { getProfileStatePath, @@ -65,6 +71,7 @@ interface RenamePlanDetails { readonly runtime: ResolvedProfileRuntime; readonly record: RenameRecord; readonly workspaceContent: string; + readonly workspaceBefore: string; readonly workspaceMode: number; } @@ -135,8 +142,12 @@ async function planInstalledRename( > { const oldRoot = getProfileRoot(runtime, profile); const newRoot = getProfileRoot(runtime, newProfile); - if (JSON.stringify(declaration).includes(JSON.stringify(oldRoot).slice(1, -1))) { - throw new Error('The profile declaration contains a path inside the old profile directory. Update it before renaming.'); + if ( + JSON.stringify(declaration).includes(JSON.stringify(oldRoot).slice(1, -1)) + ) { + throw new Error( + 'The profile declaration contains a path inside the old profile directory. Update it before renaming.', + ); } if ( state.profile !== profile || @@ -221,7 +232,7 @@ async function planInstalledRename( `Profile client directory is missing or unowned: ${managedRoot}`, ); } - await adapter.rename.assertRelocatable?.(before); + await adapter.rename.assertRelocatable?.(before, runtime); for (const name of adapter.rename.nativeLocations ?? []) { const path = join(before.root, name); await assertSafeProfilePath(before.root, path); @@ -385,11 +396,36 @@ async function prepareRename( > { const workspacePath = runtime.userConfigPath; await assertSafeProfilePath(dirname(workspacePath), workspacePath); - const workspaceStats = await lstat(workspacePath); - if (!workspaceStats.isFile()) - throw new Error(`Workspace is not a regular file: ${workspacePath}`); - const workspaceMode = workspaceStats.mode & 0o777; - const original = await readFile(workspacePath); + const existing = await readProfileRenameRecord( + profileRenameRecordPath(workspacePath), + ); + if ( + existing && + (existing.profile !== profile || existing.newProfile !== newProfile) + ) { + throw new Error( + `Profile rename is incomplete. Rerun 'allagents profile rename ${existing.profile} ${existing.newProfile} --yes'.`, + ); + } + const capturedPath = existing + ? capturedRenameFile(workspacePath, existing.id) + : undefined; + if (capturedPath) + await assertSafeProfilePath(dirname(workspacePath), capturedPath); + const workspaceStats = await profileRenameStats(workspacePath); + const capturedStats = capturedPath + ? await profileRenameStats(capturedPath) + : null; + const selected = workspaceStats ?? capturedStats; + if (!selected?.isFile() || (capturedStats && !capturedStats.isFile())) { + throw new Error( + `Workspace is unavailable or is not a regular file: ${workspacePath}`, + ); + } + const workspaceMode = selected.mode & 0o777; + const original = await readFile( + workspaceStats ? workspacePath : (capturedPath ?? workspacePath), + ); const current = original.toString('utf8'); const fingerprint = sha256Fingerprint(original); if (sha256Fingerprint(current) !== fingerprint) { @@ -397,35 +433,74 @@ async function prepareRename( } const oldRoot = getProfileRoot(runtime, profile); const newRoot = getProfileRoot(runtime, newProfile); - const existing = await readProfileRenameRecord( - profileRenameRecordPath(workspacePath), - ); + if (existing) { - if (existing.profile !== profile || existing.newProfile !== newProfile) { - throw new Error( - `Profile rename is incomplete. Rerun 'allagents profile rename ${existing.profile} ${existing.newProfile} --yes'.`, - ); - } - const updated = - fingerprint === existing.workspaceAfter - ? current - : fingerprint === existing.workspaceBefore - ? replaceDeclaration(current, workspacePath, profile, newProfile) - .content - : undefined; + const { profiles } = validateUserWorkspaceConfig( + loadYaml(current), + workspacePath, + ); + const oldDeclaration = + profiles && Object.hasOwn(profiles, profile) + ? profiles[profile] + : undefined; + const newDeclaration = + profiles && Object.hasOwn(profiles, newProfile) + ? profiles[newProfile] + : undefined; + let workspaceContent = current; + let workspaceBefore = existing.workspaceBefore; if ( - updated === undefined || - sha256Fingerprint(updated) !== existing.workspaceAfter + oldDeclaration && + !newDeclaration && + hashProfileDeclaration(oldDeclaration) === existing.declarationDigest ) { + workspaceContent = replaceDeclaration( + current, + workspacePath, + profile, + newProfile, + ).content; + workspaceBefore = fingerprint; + } else if ( + !oldDeclaration && + newDeclaration && + hashProfileDeclaration(newDeclaration) === existing.declarationDigest + ) { + if (capturedPath && capturedStats) { + const captured = await readFile(capturedPath, 'utf8'); + const previous = replaceDeclaration( + captured, + workspacePath, + profile, + newProfile, + ); + if ( + hashProfileDeclaration(previous.declaration) !== + existing.declarationDigest + ) { + throw new Error( + `Profile rename preserved an intervening declaration edit at ${capturedPath}`, + ); + } + workspaceBefore = sha256Fingerprint(captured); + } + } else { throw new Error( - 'The workspace changed during profile rename. Restore either recorded workspace version before retrying.', + 'The profile declaration changed during rename. Restore it before retrying.', ); } + await inspectReplacement( + workspacePath, + workspaceBefore, + sha256Fingerprint(workspaceContent), + existing.id, + ); await inspectRenameProgress(existing, oldRoot, newRoot, runtime.binDir); return { runtime, record: existing, - workspaceContent: updated, + workspaceContent, + workspaceBefore, workspaceMode, installed: !!existing.root?.state, recovering: true, @@ -487,8 +562,8 @@ async function prepareRename( id, profile, newProfile, + declarationDigest: hashProfileDeclaration(updated.declaration), workspaceBefore: fingerprint, - workspaceAfter: sha256Fingerprint(updated.content), ...(identity && { root: { ...identity, namedFiles: assets.namedFiles, state: assets.state }, }), @@ -499,6 +574,7 @@ async function prepareRename( runtime, record, workspaceContent: updated.content, + workspaceBefore: fingerprint, workspaceMode, installed, recovering: false, @@ -581,15 +657,18 @@ export async function applyProfileRename( initial.record.id, ); const { record } = current; - if (!isDeepStrictEqual(initial.record, record)) { + if ( + !isDeepStrictEqual(initial.record, record) || + initial.workspaceBefore !== current.workspaceBefore || + initial.workspaceContent !== current.workspaceContent + ) { throw new Error( 'The profile changed after preview. Rerun the rename to see the updated plan.', ); } const oldRoot = getProfileRoot(runtime, record.profile); const newRoot = getProfileRoot(runtime, record.newProfile); - if (!current.recovering) - await publishRenameFile(journal, JSON.stringify(record), null, 0o600); + if (!current.recovering) await writeRenameRecord(journal, record); try { const progress = await inspectRenameProgress( record, @@ -597,11 +676,8 @@ export async function applyProfileRename( newRoot, runtime.binDir, ); - if (progress.moveRoot) { - if (await profileRenameStats(newRoot)) - throw new Error(`Profile destination already exists: ${newRoot}`); - await rename(oldRoot, newRoot); - } + if (progress.moveRoot) + await moveProfileRoot(record, journal, oldRoot, newRoot); for (const move of progress.moves) await moveNamedProfileFile(newRoot, move); for (const { name, content, before, mode } of record.launchers) { @@ -626,7 +702,7 @@ export async function applyProfileRename( await publishRenameFile( workspace, current.workspaceContent, - record.workspaceBefore, + current.workspaceBefore, current.workspaceMode, record.id, ); diff --git a/src/core/profile/types.ts b/src/core/profile/types.ts index ad48e490..84ab4b8b 100644 --- a/src/core/profile/types.ts +++ b/src/core/profile/types.ts @@ -157,7 +157,7 @@ interface ProfileAdapterBase { readonly rename?: { readonly nativeLocations?: readonly string[]; readonly namedFiles?: (profile: string) => readonly string[]; - assertRelocatable?(context: ProfileClientContext): Promise; + assertRelocatable?(context: ProfileClientContext, options: ProfileContextOptions): Promise; }; serializeSettings( diff --git a/src/core/prune.ts b/src/core/prune.ts index 1428afb8..e61cb547 100644 --- a/src/core/prune.ts +++ b/src/core/prune.ts @@ -1,4 +1,5 @@ import { writeWorkspaceConfig } from '../utils/workspace-writer.js'; +import { withWorkspaceConfigMutation } from '../utils/workspace-config-lock.js'; import { existsSync } from 'node:fs'; import { join } from 'node:path'; import { CONFIG_DIR, WORKSPACE_CONFIG_FILE } from '../constants.js'; @@ -87,16 +88,17 @@ export async function pruneOrphanedPlugins( keptEntries: [], }; const userConfigPath = getUserWorkspaceConfigPath(); - const userConfig = existsSync(userConfigPath) - ? await parseUserWorkspaceConfigForEdit(userConfigPath) - : null; - if (userConfig) { - userResult = await prunePlugins(userConfig.plugins); + if (existsSync(userConfigPath)) { + userResult = await withWorkspaceConfigMutation(userConfigPath, async () => { + const userConfig = await parseUserWorkspaceConfigForEdit(userConfigPath); + const result = await prunePlugins(userConfig.plugins); - if (userResult.removed.length > 0) { - userConfig.plugins = userResult.keptEntries; - await writeWorkspaceConfig(userConfigPath, userConfig); - } + if (result.removed.length > 0) { + userConfig.plugins = result.keptEntries; + await writeWorkspaceConfig(userConfigPath, userConfig); + } + return result; + }); } return { diff --git a/src/core/user-workspace.ts b/src/core/user-workspace.ts index 24d930ab..bcec5ed6 100644 --- a/src/core/user-workspace.ts +++ b/src/core/user-workspace.ts @@ -1,6 +1,7 @@ +import { withWorkspaceConfigMutation } from '../utils/workspace-config-lock.js'; import { writeWorkspaceConfig } from '../utils/workspace-writer.js'; import { existsSync } from 'node:fs'; -import { mkdir, readFile } from 'node:fs/promises'; +import { readFile } from 'node:fs/promises'; import { join, resolve } from 'node:path'; import { fetchPlugin, type FetchOptions } from './plugin.js'; import { CONFIG_DIR, WORKSPACE_CONFIG_FILE } from '../constants.js'; @@ -101,8 +102,9 @@ export async function ensureUserWorkspace( clients: clients ? [...clients] : [...DEFAULT_USER_CLIENTS], }; - await mkdir(getAllagentsDir(), { recursive: true }); - await writeWorkspaceConfig(configPath, defaultConfig); + await withWorkspaceConfigMutation(configPath, async () => { + if (!existsSync(configPath)) await writeWorkspaceConfig(configPath, defaultConfig); + }); } /** @@ -277,58 +279,60 @@ export async function removeUserPlugin(plugin: string, configurationIndex?: numb const configPath = getUserWorkspaceConfigPath(); try { - const config = await parseUserWorkspaceConfigForEdit(configPath); + return await withWorkspaceConfigMutation(configPath, async (): Promise => { + const config = await parseUserWorkspaceConfigForEdit(configPath); - if (configurationIndex !== undefined) { - const selected = config.plugins[configurationIndex]; - if (!selected || getPluginSource(selected) !== plugin) { - return { success: false, error: 'Selected plugin declaration changed. Reopen Plugins before removing.' }; + if (configurationIndex !== undefined) { + const selected = config.plugins[configurationIndex]; + if (!selected || getPluginSource(selected) !== plugin) { + return { success: false, error: 'Selected plugin declaration changed. Reopen Plugins before removing.' }; + } } - } - // Indexed TUI selections never fall back to a different declaration. - let index = configurationIndex ?? config.plugins.findIndex( - (entry) => getPluginSource(entry) === plugin, - ); + // Indexed TUI selections never fall back to a different declaration. + let index = configurationIndex ?? config.plugins.findIndex( + (entry) => getPluginSource(entry) === plugin, + ); - // Partial match: plugin name without marketplace suffix - if (index === -1) { - index = config.plugins.findIndex((entry) => { - const source = getPluginSource(entry); - return source.startsWith(`${plugin}@`) || source === plugin; - }); - } + // Partial match: plugin name without marketplace suffix + if (index === -1) { + index = config.plugins.findIndex((entry) => { + const source = getPluginSource(entry); + return source.startsWith(`${plugin}@`) || source === plugin; + }); + } - // Semantic match: same GitHub repo under a different format - if (index === -1) { - const identity = await resolveGitHubIdentity(plugin); - if (identity) { - for (let i = 0; i < config.plugins.length; i++) { - const p = config.plugins[i]; - if (!p) continue; - const existing = await resolveGitHubIdentity(getPluginSource(p)); - if (existing === identity) { - index = i; - break; + // Semantic match: same GitHub repo under a different format + if (index === -1) { + const identity = await resolveGitHubIdentity(plugin); + if (identity) { + for (let i = 0; i < config.plugins.length; i++) { + const p = config.plugins[i]; + if (!p) continue; + const existing = await resolveGitHubIdentity(getPluginSource(p)); + if (existing === identity) { + index = i; + break; + } } } } - } - if (index === -1) { - return { - success: false, - error: `Plugin not found in user config: ${plugin}`, - }; - } + if (index === -1) { + return { + success: false, + error: `Plugin not found in user config: ${plugin}`, + }; + } - const removedEntry = getPluginSource(config.plugins[index] as PluginEntry); - config.plugins.splice(index, 1); - if (!config.plugins.some((entry) => getPluginSource(entry) === removedEntry)) { - pruneDisabledSkillsForPlugin(config, removedEntry); - pruneEnabledSkillsForPlugin(config, removedEntry); - } - await writeWorkspaceConfig(configPath, config, { removedPluginIndexes: [index] }); - return { success: true }; + const removedEntry = getPluginSource(config.plugins[index] as PluginEntry); + config.plugins.splice(index, 1); + if (!config.plugins.some((entry) => getPluginSource(entry) === removedEntry)) { + pruneDisabledSkillsForPlugin(config, removedEntry); + pruneEnabledSkillsForPlugin(config, removedEntry); + } + await writeWorkspaceConfig(configPath, config, { removedPluginIndexes: [index] }); + return { success: true }; + }); } catch (error) { return { success: false, @@ -363,18 +367,20 @@ export async function removeUserPluginsForMarketplace( ): Promise { const configPath = getUserWorkspaceConfigPath(); if (!existsSync(configPath)) return []; - const config = await parseUserWorkspaceConfigForEdit(configPath); + return withWorkspaceConfigMutation(configPath, async () => { + const config = await parseUserWorkspaceConfigForEdit(configPath); - const matching = config.plugins.filter((entry) => { - const parsed = parsePluginSpec(getPluginSource(entry)); - return parsed?.marketplaceName === marketplaceName; - }); + const matching = config.plugins.filter((entry) => { + const parsed = parsePluginSpec(getPluginSource(entry)); + return parsed?.marketplaceName === marketplaceName; + }); - if (matching.length === 0) return []; + if (matching.length === 0) return []; - config.plugins = config.plugins.filter((entry) => !matching.includes(entry)); - await writeWorkspaceConfig(configPath, config); - return matching.map((entry) => getPluginSource(entry)); + config.plugins = config.plugins.filter((entry) => !matching.includes(entry)); + await writeWorkspaceConfig(configPath, config); + return matching.map((entry) => getPluginSource(entry)); + }); } /** @@ -389,89 +395,93 @@ async function addPluginToUserConfig( initialConfig?: WorkspaceConfig, ): Promise { try { - const config = - initialConfig ?? (await parseUserWorkspaceConfigForEdit(configPath)); - const source = getPluginSource(plugin); - const exactIndex = config.plugins.findIndex( - (entry) => getPluginSource(entry) === source, - ); - if (exactIndex !== -1 && !force) { - return { - success: false, - error: `Plugin already exists in user config: ${source}`, - }; - } + return await withWorkspaceConfigMutation(configPath, async (): Promise => { + const config = + initialConfig && !existsSync(configPath) + ? initialConfig + : await parseUserWorkspaceConfigForEdit(configPath); + const source = getPluginSource(plugin); + const exactIndex = config.plugins.findIndex( + (entry) => getPluginSource(entry) === source, + ); + if (exactIndex !== -1 && !force) { + return { + success: false, + error: `Plugin already exists in user config: ${source}`, + }; + } - let semanticIndex = -1; - const newIdentity = await resolveGitHubIdentity(source); - if (newIdentity) { - for (let i = 0; i < config.plugins.length; i++) { - if (i === exactIndex) continue; - const existing = config.plugins[i]; - if (!existing) continue; - if ( - (await resolveGitHubIdentity(getPluginSource(existing))) === - newIdentity - ) { - semanticIndex = i; - break; + let semanticIndex = -1; + const newIdentity = await resolveGitHubIdentity(source); + if (newIdentity) { + for (let i = 0; i < config.plugins.length; i++) { + if (i === exactIndex) continue; + const existing = config.plugins[i]; + if (!existing) continue; + if ( + (await resolveGitHubIdentity(getPluginSource(existing))) === + newIdentity + ) { + semanticIndex = i; + break; + } } } - } - if (semanticIndex !== -1 && !force) { - const existingSource = getPluginSource( - config.plugins[semanticIndex] as PluginEntry, - ); - return { - success: false, - error: `Plugin duplicates existing entry '${existingSource}': both resolve to ${newIdentity}`, - }; - } + if (semanticIndex !== -1 && !force) { + const existingSource = getPluginSource( + config.plugins[semanticIndex] as PluginEntry, + ); + return { + success: false, + error: `Plugin duplicates existing entry '${existingSource}': both resolve to ${newIdentity}`, + }; + } - let targetedReplaceIndex = -1; - if (targetedDependencies !== undefined) { - targetedReplaceIndex = exactIndex !== -1 ? exactIndex : semanticIndex; - const nextEntry = mergeTargetedPluginEntry( - targetedReplaceIndex === -1 - ? undefined - : config.plugins[targetedReplaceIndex], - plugin, - source, - config.clients, - ); - if (targetedReplaceIndex === -1) config.plugins.push(nextEntry); - else config.plugins[targetedReplaceIndex] = nextEntry; - await writeWorkspaceConfigAtomically( - configPath, - config, - 'user', - targetedDependencies, - ); - } else { - if (exactIndex !== -1) config.plugins.splice(exactIndex, 1); - const adjustedSemanticIndex = - exactIndex !== -1 && semanticIndex > exactIndex - ? semanticIndex - 1 - : semanticIndex; - if (adjustedSemanticIndex !== -1) { - config.plugins.splice(adjustedSemanticIndex, 1); + let targetedReplaceIndex = -1; + if (targetedDependencies !== undefined) { + targetedReplaceIndex = exactIndex !== -1 ? exactIndex : semanticIndex; + const nextEntry = mergeTargetedPluginEntry( + targetedReplaceIndex === -1 + ? undefined + : config.plugins[targetedReplaceIndex], + plugin, + source, + config.clients, + ); + if (targetedReplaceIndex === -1) config.plugins.push(nextEntry); + else config.plugins[targetedReplaceIndex] = nextEntry; + await writeWorkspaceConfigAtomically( + configPath, + config, + 'user', + targetedDependencies, + ); + } else { + if (exactIndex !== -1) config.plugins.splice(exactIndex, 1); + const adjustedSemanticIndex = + exactIndex !== -1 && semanticIndex > exactIndex + ? semanticIndex - 1 + : semanticIndex; + if (adjustedSemanticIndex !== -1) { + config.plugins.splice(adjustedSemanticIndex, 1); + } + config.plugins.push(plugin); + await writeWorkspaceConfig(configPath, config); } - config.plugins.push(plugin); - await writeWorkspaceConfig(configPath, config); - } - return { - success: true, - ...(autoRegistered && { autoRegistered }), - normalizedPlugin: source, - ...(force && { - replaced: - targetedDependencies !== undefined - ? targetedReplaceIndex !== -1 - : exactIndex !== -1, - }), - }; + return { + success: true, + ...(autoRegistered && { autoRegistered }), + normalizedPlugin: source, + ...(force && { + replaced: + targetedDependencies !== undefined + ? targetedReplaceIndex !== -1 + : exactIndex !== -1, + }), + }; + }); } catch (error) { return { success: false, @@ -504,10 +514,12 @@ export async function setUserClients( const configPath = getUserWorkspaceConfigPath(); try { - const config = await parseUserWorkspaceConfigForEdit(configPath); - config.clients = clients; - await writeWorkspaceConfig(configPath, config); - return { success: true }; + return await withWorkspaceConfigMutation(configPath, async (): Promise => { + const config = await parseUserWorkspaceConfigForEdit(configPath); + config.clients = clients; + await writeWorkspaceConfig(configPath, config); + return { success: true }; + }); } catch (error) { return { success: false, @@ -582,36 +594,38 @@ export async function addUserDisabledSkill( const { pluginName, skillName } = parsed; try { - const config = await parseUserWorkspaceConfigForEdit(configPath); - - const index = findPluginEntryByName(config, pluginName); - if (index === -1) { - return { - success: false, - error: `Plugin '${pluginName}' not found in user workspace config`, - }; - } + return await withWorkspaceConfigMutation(configPath, async (): Promise => { + const config = await parseUserWorkspaceConfigForEdit(configPath); + + const index = findPluginEntryByName(config, pluginName); + if (index === -1) { + return { + success: false, + error: `Plugin '${pluginName}' not found in user workspace config`, + }; + } - const entry = ensureObjectPluginEntry(config, index); + const entry = ensureObjectPluginEntry(config, index); - if (Array.isArray(entry.skills)) { - return { - success: false, - error: `Plugin '${pluginName}' is in allowlist mode; use removeUserEnabledSkill to disable a skill`, - }; - } + if (Array.isArray(entry.skills)) { + return { + success: false, + error: `Plugin '${pluginName}' is in allowlist mode; use removeUserEnabledSkill to disable a skill`, + }; + } - const existing = entry.skills?.exclude ?? []; - if (existing.includes(skillName)) { - return { - success: false, - error: `Skill '${skillKey}' is already disabled`, - }; - } + const existing = entry.skills?.exclude ?? []; + if (existing.includes(skillName)) { + return { + success: false, + error: `Skill '${skillKey}' is already disabled`, + }; + } - entry.skills = { exclude: [...existing, skillName] }; - await writeWorkspaceConfig(configPath, config); - return { success: true }; + entry.skills = { exclude: [...existing, skillName] }; + await writeWorkspaceConfig(configPath, config); + return { success: true }; + }); } catch (error) { return { success: false, @@ -640,46 +654,48 @@ export async function removeUserDisabledSkill( const { pluginName, skillName } = parsed; try { - const config = await parseUserWorkspaceConfigForEdit(configPath); - - const index = findPluginEntryByName(config, pluginName); - if (index === -1) { - return { - success: false, - error: `Plugin '${pluginName}' not found in user workspace config`, - }; - } + return await withWorkspaceConfigMutation(configPath, async (): Promise => { + const config = await parseUserWorkspaceConfigForEdit(configPath); + + const index = findPluginEntryByName(config, pluginName); + if (index === -1) { + return { + success: false, + error: `Plugin '${pluginName}' not found in user workspace config`, + }; + } - const entry = config.plugins[index]; - if (!entry) { - return { - success: false, - error: `Plugin '${pluginName}' not found in user workspace config`, - }; - } - if ( - typeof entry === 'string' || - !entry.skills || - Array.isArray(entry.skills) - ) { - return { - success: false, - error: `Skill '${skillKey}' is already enabled`, - }; - } + const entry = config.plugins[index]; + if (!entry) { + return { + success: false, + error: `Plugin '${pluginName}' not found in user workspace config`, + }; + } + if ( + typeof entry === 'string' || + !entry.skills || + Array.isArray(entry.skills) + ) { + return { + success: false, + error: `Skill '${skillKey}' is already enabled`, + }; + } - if (!entry.skills.exclude.includes(skillName)) { - return { - success: false, - error: `Skill '${skillKey}' is already enabled`, - }; - } + if (!entry.skills.exclude.includes(skillName)) { + return { + success: false, + error: `Skill '${skillKey}' is already enabled`, + }; + } - const newExclude = entry.skills.exclude.filter((s) => s !== skillName); - entry.skills = newExclude.length > 0 ? { exclude: newExclude } : undefined; + const newExclude = entry.skills.exclude.filter((s) => s !== skillName); + entry.skills = newExclude.length > 0 ? { exclude: newExclude } : undefined; - await writeWorkspaceConfig(configPath, config); - return { success: true }; + await writeWorkspaceConfig(configPath, config); + return { success: true }; + }); } catch (error) { return { success: false, @@ -737,36 +753,38 @@ export async function addUserEnabledSkill( const { pluginName, skillName } = parsed; try { - const config = await parseUserWorkspaceConfigForEdit(configPath); - - const index = findPluginEntryByName(config, pluginName); - if (index === -1) { - return { - success: false, - error: `Plugin '${pluginName}' not found in user workspace config`, - }; - } + return await withWorkspaceConfigMutation(configPath, async (): Promise => { + const config = await parseUserWorkspaceConfigForEdit(configPath); + + const index = findPluginEntryByName(config, pluginName); + if (index === -1) { + return { + success: false, + error: `Plugin '${pluginName}' not found in user workspace config`, + }; + } - const entry = ensureObjectPluginEntry(config, index); + const entry = ensureObjectPluginEntry(config, index); - if (entry.skills && !Array.isArray(entry.skills)) { - return { - success: false, - error: `Plugin '${pluginName}' is in blocklist mode; use removeUserDisabledSkill to enable a skill`, - }; - } + if (entry.skills && !Array.isArray(entry.skills)) { + return { + success: false, + error: `Plugin '${pluginName}' is in blocklist mode; use removeUserDisabledSkill to enable a skill`, + }; + } - const existing = (entry.skills as string[] | undefined) ?? []; - if (existing.includes(skillName)) { - return { - success: false, - error: `Skill '${skillKey}' is already enabled`, - }; - } + const existing = (entry.skills as string[] | undefined) ?? []; + if (existing.includes(skillName)) { + return { + success: false, + error: `Skill '${skillKey}' is already enabled`, + }; + } - entry.skills = [...existing, skillName]; - await writeWorkspaceConfig(configPath, config); - return { success: true }; + entry.skills = [...existing, skillName]; + await writeWorkspaceConfig(configPath, config); + return { success: true }; + }); } catch (error) { return { success: false, @@ -795,46 +813,48 @@ export async function removeUserEnabledSkill( const { pluginName, skillName } = parsed; try { - const config = await parseUserWorkspaceConfigForEdit(configPath); - - const index = findPluginEntryByName(config, pluginName); - if (index === -1) { - return { - success: false, - error: `Plugin '${pluginName}' not found in user workspace config`, - }; - } + return await withWorkspaceConfigMutation(configPath, async (): Promise => { + const config = await parseUserWorkspaceConfigForEdit(configPath); + + const index = findPluginEntryByName(config, pluginName); + if (index === -1) { + return { + success: false, + error: `Plugin '${pluginName}' not found in user workspace config`, + }; + } - const entry = config.plugins[index]; - if (!entry) { - return { - success: false, - error: `Plugin '${pluginName}' not found in user workspace config`, - }; - } - if ( - typeof entry === 'string' || - !entry.skills || - !Array.isArray(entry.skills) - ) { - return { - success: false, - error: `Skill '${skillKey}' is already disabled`, - }; - } + const entry = config.plugins[index]; + if (!entry) { + return { + success: false, + error: `Plugin '${pluginName}' not found in user workspace config`, + }; + } + if ( + typeof entry === 'string' || + !entry.skills || + !Array.isArray(entry.skills) + ) { + return { + success: false, + error: `Skill '${skillKey}' is already disabled`, + }; + } - if (!entry.skills.includes(skillName)) { - return { - success: false, - error: `Skill '${skillKey}' is already disabled`, - }; - } + if (!entry.skills.includes(skillName)) { + return { + success: false, + error: `Skill '${skillKey}' is already disabled`, + }; + } - const newSkills = entry.skills.filter((s) => s !== skillName); - entry.skills = newSkills; + const newSkills = entry.skills.filter((s) => s !== skillName); + entry.skills = newSkills; - await writeWorkspaceConfig(configPath, config); - return { success: true }; + await writeWorkspaceConfig(configPath, config); + return { success: true }; + }); } catch (error) { return { success: false, @@ -860,29 +880,31 @@ export async function setUserPluginSkillsMode( const configPath = getUserWorkspaceConfigPath(); try { - const config = await parseUserWorkspaceConfigForEdit(configPath); - - const index = findPluginEntryByName(config, pluginName); - if (index === -1) { - return { - success: false, - error: `Plugin '${pluginName}' not found in user workspace config`, - }; - } + return await withWorkspaceConfigMutation(configPath, async (): Promise => { + const config = await parseUserWorkspaceConfigForEdit(configPath); + + const index = findPluginEntryByName(config, pluginName); + if (index === -1) { + return { + success: false, + error: `Plugin '${pluginName}' not found in user workspace config`, + }; + } - const entry = ensureObjectPluginEntry(config, index); + const entry = ensureObjectPluginEntry(config, index); - if (mode === 'allowlist') { - // Always set the array to preserve allowlist mode, even if empty - entry.skills = [...skillNames]; - } else { - // For blocklist, clear the field if no exclusions (= all enabled) - entry.skills = - skillNames.length > 0 ? { exclude: [...skillNames] } : undefined; - } + if (mode === 'allowlist') { + // Always set the array to preserve allowlist mode, even if empty + entry.skills = [...skillNames]; + } else { + // For blocklist, clear the field if no exclusions (= all enabled) + entry.skills = + skillNames.length > 0 ? { exclude: [...skillNames] } : undefined; + } - await writeWorkspaceConfig(configPath, config); - return { success: true }; + await writeWorkspaceConfig(configPath, config); + return { success: true }; + }); } catch (error) { return { success: false, @@ -903,16 +925,18 @@ export async function setUserPluginMcpServersExcluded( } try { - const config = await parseUserWorkspaceConfigForEdit(configPath); - const result = setPluginMcpServersExcludedInConfig( - config, - source, - excludedNames, - configurationIndex, - ); - if (!result.success) return result; - await writeWorkspaceConfig(configPath, config); - return result; + return await withWorkspaceConfigMutation(configPath, async (): Promise => { + const config = await parseUserWorkspaceConfigForEdit(configPath); + const result = setPluginMcpServersExcludedInConfig( + config, + source, + excludedNames, + configurationIndex, + ); + if (!result.success) return result; + await writeWorkspaceConfig(configPath, config); + return result; + }); } catch (error) { return { success: false, @@ -929,16 +953,18 @@ export async function upsertUserGitHubPluginSourceAllowlist( const configPath = getUserWorkspaceConfigPath(); try { - const config = await parseUserWorkspaceConfigForEdit(configPath); - const result = await upsertGitHubPluginSourceAllowlistInConfig( - config, - source, - skillNames, - ); - if (!result.success) return result; + return await withWorkspaceConfigMutation(configPath, async (): Promise => { + const config = await parseUserWorkspaceConfigForEdit(configPath); + const result = await upsertGitHubPluginSourceAllowlistInConfig( + config, + source, + skillNames, + ); + if (!result.success) return result; - await writeWorkspaceConfig(configPath, config); - return result; + await writeWorkspaceConfig(configPath, config); + return result; + }); } catch (error) { return { success: false, @@ -1056,70 +1082,72 @@ export async function migrateUserWorkspaceSkillsV1toV2(): Promise { const configPath = getUserWorkspaceConfigPath(); if (!existsSync(configPath)) return; - const config = await parseUserWorkspaceConfigForEdit(configPath); - - if (!config || (config.version !== undefined && config.version >= 2)) return; + await withWorkspaceConfigMutation(configPath, async () => { + const config = await parseUserWorkspaceConfigForEdit(configPath); - const enabledSkills: string[] = config.enabledSkills ?? []; - const disabledSkills: string[] = config.disabledSkills ?? []; + if (!config || (config.version !== undefined && config.version >= 2)) return; - const enabledByPlugin = new Map(); - for (const skillKey of enabledSkills) { - const colonIdx = skillKey.indexOf(':'); - if (colonIdx === -1) continue; - const pluginName = skillKey.slice(0, colonIdx); - const skillName = skillKey.slice(colonIdx + 1); - const list = enabledByPlugin.get(pluginName) ?? []; - list.push(skillName); - enabledByPlugin.set(pluginName, list); - } + const enabledSkills: string[] = config.enabledSkills ?? []; + const disabledSkills: string[] = config.disabledSkills ?? []; - const disabledByPlugin = new Map(); - for (const skillKey of disabledSkills) { - const colonIdx = skillKey.indexOf(':'); - if (colonIdx === -1) continue; - const pluginName = skillKey.slice(0, colonIdx); - const skillName = skillKey.slice(colonIdx + 1); - const list = disabledByPlugin.get(pluginName) ?? []; - list.push(skillName); - disabledByPlugin.set(pluginName, list); - } + const enabledByPlugin = new Map(); + for (const skillKey of enabledSkills) { + const colonIdx = skillKey.indexOf(':'); + if (colonIdx === -1) continue; + const pluginName = skillKey.slice(0, colonIdx); + const skillName = skillKey.slice(colonIdx + 1); + const list = enabledByPlugin.get(pluginName) ?? []; + list.push(skillName); + enabledByPlugin.set(pluginName, list); + } - for (const [pluginName, skillNames] of enabledByPlugin) { - const index = findPluginEntryByName(config, pluginName); - if (index === -1) { - console.warn( - `[migrate v1→v2] No user plugin found for '${pluginName}', skipping`, - ); - continue; + const disabledByPlugin = new Map(); + for (const skillKey of disabledSkills) { + const colonIdx = skillKey.indexOf(':'); + if (colonIdx === -1) continue; + const pluginName = skillKey.slice(0, colonIdx); + const skillName = skillKey.slice(colonIdx + 1); + const list = disabledByPlugin.get(pluginName) ?? []; + list.push(skillName); + disabledByPlugin.set(pluginName, list); } - const entry = ensureObjectPluginEntry(config, index); - entry.skills = skillNames; - } - for (const [pluginName, skillNames] of disabledByPlugin) { - const index = findPluginEntryByName(config, pluginName); - if (index === -1) { - console.warn( - `[migrate v1→v2] No user plugin found for '${pluginName}', skipping`, - ); - continue; + for (const [pluginName, skillNames] of enabledByPlugin) { + const index = findPluginEntryByName(config, pluginName); + if (index === -1) { + console.warn( + `[migrate v1→v2] No user plugin found for '${pluginName}', skipping`, + ); + continue; + } + const entry = ensureObjectPluginEntry(config, index); + entry.skills = skillNames; } - const entry = ensureObjectPluginEntry(config, index); - if (!Array.isArray(entry.skills)) { - entry.skills = { exclude: skillNames }; + + for (const [pluginName, skillNames] of disabledByPlugin) { + const index = findPluginEntryByName(config, pluginName); + if (index === -1) { + console.warn( + `[migrate v1→v2] No user plugin found for '${pluginName}', skipping`, + ); + continue; + } + const entry = ensureObjectPluginEntry(config, index); + if (!Array.isArray(entry.skills)) { + entry.skills = { exclude: skillNames }; + } } - } - config.enabledSkills = undefined; - config.disabledSkills = undefined; - config.version = 2; + config.enabledSkills = undefined; + config.disabledSkills = undefined; + config.version = 2; - try { - await writeWorkspaceConfig(configPath, config); - } catch (error) { - console.warn( - `[migrate v1→v2] Failed to write migrated user config: ${error instanceof Error ? error.message : String(error)}`, - ); - } + try { + await writeWorkspaceConfig(configPath, config); + } catch (error) { + console.warn( + `[migrate v1→v2] Failed to write migrated user config: ${error instanceof Error ? error.message : String(error)}`, + ); + } + }); } diff --git a/src/core/workspace-modify.ts b/src/core/workspace-modify.ts index 038e9993..8d83139a 100644 --- a/src/core/workspace-modify.ts +++ b/src/core/workspace-modify.ts @@ -27,6 +27,7 @@ import type { } from '../models/workspace-config.js'; import { parseClientEntry, getClientTypes, getEffectivePluginSource, getPluginSource, getPluginClients, normalizeClientEntry, resolveInstallMode } from '../models/workspace-config.js'; import { parseMarketplaceManifest } from '../utils/marketplace-manifest-parser.js'; +import { withWorkspaceConfigMutation } from '../utils/workspace-config-lock.js'; import { parseWorkspaceConfigForEdit, validateProjectWorkspaceConfig, @@ -285,8 +286,9 @@ export async function ensureWorkspace( clients: clients ?? [...DEFAULT_PROJECT_CLIENTS], }; - await mkdir(configDir, { recursive: true }); - await writeWorkspaceConfig(configPath, defaultConfig); + await withWorkspaceConfigMutation(configPath, async () => { + if (!existsSync(configPath)) await writeWorkspaceConfig(configPath, defaultConfig); + }); } /** diff --git a/src/core/workspace.ts b/src/core/workspace.ts index 68bae76a..2f253d33 100644 --- a/src/core/workspace.ts +++ b/src/core/workspace.ts @@ -2,6 +2,7 @@ import { cp, mkdir, readFile, writeFile, copyFile } from 'node:fs/promises'; import { existsSync } from 'node:fs'; import { join, resolve, dirname, relative, sep, isAbsolute } from 'node:path'; import { fileURLToPath } from 'node:url'; +import { withWorkspaceConfigMutation } from '../utils/workspace-config-lock.js'; import { serializeWorkspaceConfig } from '../utils/workspace-writer.js'; import { syncWorkspace, type SyncResult, type SyncOptions } from './sync.js'; import { ensureWorkspaceRules } from './transform.js'; @@ -231,7 +232,12 @@ export async function initWorkspace( : input, configPath, ); - await writeFile(configPath, workspaceYamlContent, 'utf-8'); + await withWorkspaceConfigMutation(configPath, async () => { + if (existsSync(configPath) && !options.force) { + throw new Error(`Workspace already exists: ${absoluteTarget}`); + } + await writeFile(configPath, workspaceYamlContent, 'utf-8'); + }); // Inspect the validated config for post-write template work. const clients = parsed.clients; diff --git a/src/utils/filesystem-lock.ts b/src/utils/filesystem-lock.ts new file mode 100644 index 00000000..2649fdf3 --- /dev/null +++ b/src/utils/filesystem-lock.ts @@ -0,0 +1,234 @@ +import { AsyncLocalStorage } from 'node:async_hooks'; +import { randomUUID } from 'node:crypto'; +import { + chmod, + lstat, + mkdir, + open, + readdir, + readFile, + rename, + rm, +} from 'node:fs/promises'; +import { dirname, join, resolve } from 'node:path'; + +export async function readPrivateJson(path: string): Promise { + try { + return JSON.parse(await readFile(path, 'utf8')) as T; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined; + throw error; + } +} + +export async function writePrivateFile( + path: string, + content: string, +): Promise { + await mkdir(dirname(path), { recursive: true, mode: 0o700 }); + await chmod(dirname(path), 0o700); + const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`; + try { + const handle = await open(temporary, 'wx', 0o600); + try { + await handle.writeFile(content, 'utf8'); + await handle.sync(); + } finally { + await handle.close(); + } + await rename(temporary, path); + } finally { + await rm(temporary, { force: true }); + } +} + +export function waitForLock( + milliseconds: number, + signal: AbortSignal, +): Promise { + signal.throwIfAborted(); + return new Promise((resolve, reject) => { + const abort = () => { + clearTimeout(timer); + reject(signal.reason); + }; + const timer = setTimeout(() => { + signal.removeEventListener('abort', abort); + resolve(); + }, milliseconds); + signal.addEventListener('abort', abort, { once: true }); + }); +} + +interface LockRecord { + pid: number; + nonce: string; + choosing: boolean; + ticket: number; +} + +interface LocalLease { + active: boolean; + children: number; + waiters: Set<() => void>; +} + +async function drainLease(lease: LocalLease): Promise { + while (lease.children > 0) + await new Promise((resolve) => lease.waiters.add(resolve)); + lease.active = false; +} + +async function waitForLeaseDrain( + drain: Promise, + signal: AbortSignal, +): Promise { + signal.throwIfAborted(); + await new Promise((resolve, reject) => { + const abort = () => reject(signal.reason); + signal.addEventListener('abort', abort, { once: true }); + void drain + .then(resolve, reject) + .finally(() => signal.removeEventListener('abort', abort)); + }); +} +const localLeases = new AsyncLocalStorage>(); + +function ownerIsAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch (error) { + return (error as NodeJS.ErrnoException).code !== 'ESRCH'; + } +} + +/** + * A filesystem bakery lock: each contender publishes its own choosing flag and + * ticket, then waits for lower tickets (UUID breaks ties). Records are atomic; + * release and dead-owner recovery only unlink that owner's unique filename. + * An empty directory can be removed between operations. A contender retries + * registration if a concurrent empty-directory cleanup wins that race. + */ +export async function withFilesystemLock( + path: string, + signal: AbortSignal, + timeoutMs: number, + operation: () => Promise, +): Promise { + signal.throwIfAborted(); + const lockPath = resolve(path); + const parentLease = localLeases.getStore()?.get(lockPath); + if (parentLease?.active) { + parentLease.children++; + try { + return await operation(); + } finally { + parentLease.children--; + if (parentLease.children === 0) { + for (const resolve of parentLease.waiters) resolve(); + parentLease.waiters.clear(); + } + } + } + const deadline = Date.now() + timeoutMs; + const owner: LockRecord = { + pid: process.pid, + nonce: randomUUID(), + choosing: true, + ticket: 0, + }; + const filename = `${owner.pid}-${owner.nonce}.json`; + const ownerPath = join(lockPath, filename); + const register = async () => { + while (true) { + signal.throwIfAborted(); + try { + await mkdir(lockPath, { recursive: true, mode: 0o700 }); + if (!(await lstat(lockPath)).isDirectory()) { + throw new Error(`Filesystem lock path is not a directory: ${lockPath}`); + } + await writePrivateFile(ownerPath, JSON.stringify(owner)); + return; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT' || Date.now() >= deadline) throw error; + } + } + }; + let lease: LocalLease | undefined; + const records = async (): Promise< + Array<{ filename: string; owner: LockRecord }> + > => { + const result: Array<{ filename: string; owner: LockRecord }> = []; + for (const name of await readdir(lockPath)) { + if (!/^\d+-[a-f0-9-]+\.json$/.test(name)) continue; + const recordPath = join(lockPath, name); + const record = await readPrivateJson(recordPath); + if (!record) continue; + if ( + name !== `${record.pid}-${record.nonce}.json` || + !Number.isSafeInteger(record.pid) || + record.pid <= 0 || + !Number.isSafeInteger(record.ticket) || + record.ticket < 0 || + typeof record.choosing !== 'boolean' + ) + throw new Error('Invalid filesystem lock owner record'); + if (!ownerIsAlive(record.pid)) { + await rm(recordPath, { force: true }); + continue; + } + result.push({ filename: name, owner: record }); + } + return result; + }; + let outcome: { value: T } | { error: unknown }; + try { + await register(); + const contenders = await records(); + owner.ticket = + 1 + Math.max(0, ...contenders.map((record) => record.owner.ticket)); + owner.choosing = false; + await writePrivateFile(ownerPath, JSON.stringify(owner)); + while (true) { + signal.throwIfAborted(); + const blocked = (await records()).some( + (record) => + record.filename !== filename && + (record.owner.choosing || + record.owner.ticket < owner.ticket || + (record.owner.ticket === owner.ticket && + record.filename < filename)), + ); + if (!blocked) break; + if (Date.now() >= deadline) + throw new Error(`Timed out waiting to acquire ${lockPath}`); + await waitForLock(Math.min(25, deadline - Date.now()), signal); + } + signal.throwIfAborted(); + lease = { active: true, children: 0, waiters: new Set() }; + const inherited = new Map(localLeases.getStore()); + inherited.set(lockPath, lease); + outcome = { value: await localLeases.run(inherited, operation) }; + } catch (error) { + outcome = { error }; + } + const release = async () => { + const current = await readPrivateJson(ownerPath); + if (current?.nonce === owner.nonce) await rm(ownerPath, { force: true }); + }; + if (lease) { + const drain = drainLease(lease); + try { + await waitForLeaseDrain(drain, signal); + } catch (error) { + // Cancellation returns promptly, but an already running child retains + // ownership until it finishes. Releasing early would permit cache races. + void drain.then(release).catch(() => {}); + throw error; + } + } + await release(); + if ('error' in outcome) throw outcome.error; + return outcome.value; +} diff --git a/src/utils/workspace-config-lock.ts b/src/utils/workspace-config-lock.ts index 4765bf69..dd7edf94 100644 --- a/src/utils/workspace-config-lock.ts +++ b/src/utils/workspace-config-lock.ts @@ -1,100 +1,43 @@ -import { randomUUID } from 'node:crypto'; -import { lstat, mkdir, readFile, rm, writeFile } from 'node:fs/promises'; -import { join } from 'node:path'; +import { lstat, rmdir } from 'node:fs/promises'; +import { withFilesystemLock } from './filesystem-lock.js'; -const LOCK_TIMEOUT_MS = 5_000; -const STALE_LOCK_MS = 30_000; - -async function readLockOwner(lockPath: string): Promise { - return readFile(join(lockPath, 'owner'), 'utf8').catch(() => null); +export function profileRenameRecordPath(workspacePath: string): string { + return `${workspacePath}.profile-rename.json`; } -async function isStaleLock( - lockPath: string, - modifiedAt: number, -): Promise { - const owner = await readLockOwner(lockPath); - const pid = Number(owner?.split(':')[0]); - if (!Number.isSafeInteger(pid) || pid <= 0) { - return Date.now() - modifiedAt > STALE_LOCK_MS; - } +export async function assertNoPendingProfileRename( + workspacePath: string, +): Promise { try { - process.kill(pid, 0); - return false; + await lstat(profileRenameRecordPath(workspacePath)); } catch (error) { - return (error as NodeJS.ErrnoException).code === 'ESRCH'; + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return; + throw error; } + throw new Error( + 'A profile rename is incomplete. Rerun the same profile rename with --yes before changing the workspace.', + ); } export async function withWorkspaceConfigLock( configPath: string, mutate: () => Promise, ): Promise { - const lockPath = `${configPath}.lock`; - const breakPath = `${lockPath}.break`; - const token = `${process.pid}:${randomUUID()}`; - const deadline = Date.now() + LOCK_TIMEOUT_MS; - let acquired = false; - while (!acquired) { - let created = false; - try { - await mkdir(lockPath, { mode: 0o700 }); - created = true; - await writeFile(join(lockPath, 'owner'), token, { - encoding: 'utf8', - mode: 0o600, - }); - acquired = true; - } catch (error) { - if (created) { - await rm(lockPath, { recursive: true, force: true }).catch( - () => undefined, - ); - } - if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error; - const lockStats = await lstat(lockPath).catch(() => null); - if (lockStats && (await isStaleLock(lockPath, lockStats.mtimeMs))) { - let breaker = false; - try { - await mkdir(breakPath, { mode: 0o700 }); - breaker = true; - const currentStats = await lstat(lockPath).catch(() => null); - if ( - currentStats && - (await isStaleLock(lockPath, currentStats.mtimeMs)) - ) { - await rm(lockPath, { recursive: true, force: true }); - } - } catch (breakError) { - if ((breakError as NodeJS.ErrnoException).code !== 'EEXIST') { - throw breakError; - } - } finally { - if (breaker) { - await rm(breakPath, { recursive: true, force: true }).catch( - () => undefined, - ); - } - } - if (Date.now() >= deadline) { - throw new Error(`Timed out waiting to update ${configPath}`); - } - await new Promise((resolve) => setTimeout(resolve, 25)); - continue; - } - if (Date.now() >= deadline) { - throw new Error(`Timed out waiting to update ${configPath}`); - } - await new Promise((resolve) => setTimeout(resolve, 25)); - } - } + const lockPath = `${configPath}.write-lock`; try { - return await mutate(); + return await withFilesystemLock(lockPath, new AbortController().signal, 5000, mutate); } finally { - if ((await readLockOwner(lockPath)) === token) { - await rm(lockPath, { recursive: true, force: true }).catch( - () => undefined, - ); - } + // Non-empty directories belong to active contenders or interrupted owners. + await rmdir(lockPath).catch(() => undefined); } } + +export function withWorkspaceConfigMutation( + configPath: string, + mutate: () => Promise, +): Promise { + return withWorkspaceConfigLock(configPath, async () => { + await assertNoPendingProfileRename(configPath); + return mutate(); + }); +} diff --git a/tests/e2e/profile-rename.test.ts b/tests/e2e/profile-rename.test.ts index 58e51eab..2323605e 100644 --- a/tests/e2e/profile-rename.test.ts +++ b/tests/e2e/profile-rename.test.ts @@ -6,6 +6,7 @@ import { readFileSync, readdirSync, rmSync, + statSync, symlinkSync, writeFileSync, } from 'node:fs'; @@ -14,7 +15,7 @@ import { dirname, join } from 'node:path'; const repo = join(import.meta.dir, '../..'); const cli = join(repo, 'dist/index.js'); -const fixtureTimeout = 30_000; +const fixtureTimeout = 60_000; const fixtureYaml = [ '# User workspace', 'profiles:', @@ -56,6 +57,20 @@ function json(args: string[], exitCode = 0) { return JSON.parse(result.stdout.toString()); } +function interruptibleRename(hook: string[], variables: NodeJS.ProcessEnv = {}) { + const preload = join(root, 'rename-hook.cjs'); + writeFileSync(preload, [ + 'const fs = require("node:fs/promises");', + ...hook, + 'require("node:module").syncBuiltinESMExports();', + ].join('\n')); + return run(['--json', 'profile', 'rename', 'work', 'office', '--yes'], { + NODE_OPTIONS: `--require="${preload}"`, + TEST_WORKSPACE: workspace, + ...variables, + }); +} + function seedFile(path: string, content: string) { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, content); @@ -222,20 +237,13 @@ test.skipIf(process.platform === 'win32')('resumes after a process stop before p const journal = `${workspace}.profile-rename.json`; const session = 'clients/codex/home/sessions/recover.jsonl'; seedFile(join(oldRoot, session), 'keep me'); - const preload = join(root, 'stop-before-workspace.cjs'); - writeFileSync(preload, [ - 'const fs = require("node:fs/promises");', - 'const rename = fs.rename;', - 'fs.rename = (from, to) => to === process.env.TEST_WORKSPACE', - ' ? process.kill(process.pid, "SIGKILL") : rename(from, to);', - 'require("node:module").syncBuiltinESMExports();', - ].join('\n')); - const interrupted = run(['--json', 'profile', 'rename', 'work', 'office', '--yes'], { - NODE_OPTIONS: `--require="${preload}"`, - TEST_WORKSPACE: workspace, - }); + const interrupted = interruptibleRename([ + 'const link = fs.link;', + 'fs.link = (from, to) => to === process.env.TEST_WORKSPACE', + ' ? process.kill(process.pid, "SIGKILL") : link(from, to);', + ]); expect(interrupted.signalCode).toBe('SIGKILL'); - expect(read(workspace)).toBe(fixtureYaml); + expect(existsSync(workspace)).toBe(false); expect(existsSync(journal)).toBe(true); expect(existsSync(oldRoot)).toBe(false); expect(read(join(newRoot, session))).toBe('keep me'); @@ -243,7 +251,7 @@ test.skipIf(process.platform === 'win32')('resumes after a process stop before p const preview = json(['profile', 'rename', 'work', 'office', '--dry-run']); expect(preview.data.recovering).toBe(true); - expect(read(workspace)).toBe(fixtureYaml); + expect(existsSync(workspace)).toBe(false); expect(json(['profile', 'rename', 'work', 'office', '--yes']).data.recovering).toBe(true); expect(read(workspace)).toBe(fixtureYaml.replace("'work':", "'office':")); expect(read(join(newRoot, session))).toBe('keep me'); @@ -251,3 +259,43 @@ test.skipIf(process.platform === 'win32')('resumes after a process stop before p expect(readdirSync(dirname(workspace)).sort()).toEqual(['profiles', 'workspace.yaml']); expect(json(['profile', 'status', 'office']).data.status).toBe('installed'); }, fixtureTimeout); + + +test.skipIf(process.platform === 'win32')('preserves an edit arriving at workspace publication and resumes with the edit', () => { + json(['profile', 'install', 'work', '--yes', '--offline']); + const edited = fixtureYaml + '# edit while rename was publishing\n'; + const blocked = interruptibleRename([ + 'const rename = fs.rename;', + 'fs.rename = async (from, to) => {', + ' if (from === process.env.TEST_WORKSPACE) await fs.appendFile(from, "# edit while rename was publishing\\n");', + ' return rename(from, to);', + '};', + ]); + expect(blocked.exitCode, blocked.stdout.toString() + blocked.stderr.toString()).toBe(1); + expect(read(workspace)).toBe(edited); + expect(json(['profile', 'rename', 'work', 'office', '--yes']).data.status).toBe('renamed'); + expect(read(workspace)).toBe(edited.replace("'work':", "'office':")); +}, fixtureTimeout); + +test.skipIf(process.platform === 'win32')('does not replace a directory created at destination reservation', () => { + json(['profile', 'install', 'work', '--yes', '--offline']); + const oldRoot = join(profiles, 'work'); + const newRoot = join(profiles, 'office'); + const blocked = interruptibleRename([ + 'const mkdir = fs.mkdir;', + 'fs.mkdir = async (target, options) => {', + ' if (target === process.env.TEST_DESTINATION) {', + ' await mkdir(target, options);', + ' await fs.writeFile(process.env.TEST_ID, String((await fs.stat(target)).ino));', + ' }', + ' return mkdir(target, options);', + '};', + ], { TEST_DESTINATION: newRoot, TEST_ID: join(root, 'collision-inode') }); + expect(blocked.exitCode, blocked.stdout.toString() + blocked.stderr.toString()).toBe(1); + expect(String(statSync(newRoot).ino)).toBe(read(join(root, 'collision-inode'))); + expect(readdirSync(newRoot)).toEqual([]); + expect(existsSync(join(oldRoot, 'state.json'))).toBe(true); + expect(read(workspace)).toBe(fixtureYaml); + rmSync(newRoot, { recursive: true }); + expect(json(['profile', 'rename', 'work', 'office', '--yes']).data.status).toBe('renamed'); +}, fixtureTimeout); diff --git a/tests/unit/core/user-workspace.test.ts b/tests/unit/core/user-workspace.test.ts index dbc4e8e9..86259d2b 100644 --- a/tests/unit/core/user-workspace.test.ts +++ b/tests/unit/core/user-workspace.test.ts @@ -181,6 +181,19 @@ describe('user-workspace', () => { expect(result.success).toBe(false); expect(await readFile(configPath, 'utf-8')).toBe(invalid); }); + + test('leaves the user workspace alone while a profile rename is pending', async () => { + await ensureUserWorkspace(); + const path = getUserWorkspaceConfigPath(); + const original = await readFile(path, 'utf-8'); + await writeFile(`${path}.profile-rename.json`, '{}'); + + const result = await setUserClients(['omp']); + + expect(result.success).toBe(false); + expect(result.error).toContain('profile rename is incomplete'); + expect(await readFile(path, 'utf-8')).toBe(original); + }); }); describe('addUserPlugin', () => { From 5077dea7713700208af0946e5d553916c110eef3 Mon Sep 17 00:00:00 2001 From: Christopher Tso Date: Thu, 26 Nov 2026 17:11:20 +1100 Subject: [PATCH 3/4] fix(cli): preserve edits across profile rename recovery --- docs/src/content/docs/docs/reference/cli.mdx | 14 +- src/cli/metadata/profile.ts | 1 + src/core/marketplace.ts | 27 +++- src/core/profile/rename-transaction.ts | 96 ++++++++----- src/core/profile/rename.ts | 49 +++---- src/core/prune.ts | 33 +++-- src/core/user-workspace.ts | 2 + tests/e2e/profile-rename.test.ts | 129 ++++++++++++++++++ .../core/marketplace-remove-cascade.test.ts | 21 +++ tests/unit/core/prune.test.ts | 16 +++ tests/unit/core/user-workspace.test.ts | 12 ++ 11 files changed, 316 insertions(+), 84 deletions(-) diff --git a/docs/src/content/docs/docs/reference/cli.mdx b/docs/src/content/docs/docs/reference/cli.mdx index f2298814..aba46528 100644 --- a/docs/src/content/docs/docs/reference/cli.mdx +++ b/docs/src/content/docs/docs/reference/cli.mdx @@ -164,9 +164,17 @@ to be updated separately. If rename is interrupted after it starts moving files, rerun the same `allagents profile rename --yes` command to resume. Keep the recovery record beside `workspace.yaml` and wait until rename completes before editing -the workspace or starting the affected clients. If a conflict is reported, move -the conflicting file or directory aside before retrying. If the error reports a -preserved edit, keep that file and reconcile its contents before resuming. +the workspace or either profile directory, or starting the affected clients. +Run workspace writers from the same host and PID namespace when they share a +workspace. + +If the destination already exists, move it aside before retrying. This includes +an empty directory left by an interruption before the reservation was recorded. +If the command has published a replacement and reports a preserved edit, move +the reported capture file out of its recovery path, resume the rename, and then +reconcile the saved edit with the published file. If `workspace.yaml` is missing +and its capture contains a pending workspace edit, move the capture back to +`workspace.yaml` before retrying. ### status diff --git a/src/cli/metadata/profile.ts b/src/cli/metadata/profile.ts index 572c990f..90091516 100644 --- a/src/cli/metadata/profile.ts +++ b/src/cli/metadata/profile.ts @@ -254,6 +254,7 @@ export const profileRenameMeta: AgentCommandMeta = { { name: 'new', type: 'string', required: true, description: 'New profile name.' }, ], options: mutationOptions.slice(0, 2), + interaction: 'conditional', outputSchema: { ...profileRenamePlanOutput, status: 'planned | renamed | failed', diff --git a/src/core/marketplace.ts b/src/core/marketplace.ts index 87331215..18000ebc 100644 --- a/src/core/marketplace.ts +++ b/src/core/marketplace.ts @@ -18,6 +18,7 @@ import { resolvePluginSourcePath, } from '../utils/marketplace-manifest-parser.js'; import { normalizeGitRef } from '../utils/git-source.js'; +import { withWorkspaceConfigMutation } from '../utils/workspace-config-lock.js'; import { isFilesystemRoot, parseGitHubUrl, @@ -1103,6 +1104,13 @@ async function removeMarketplaceRegistration( } } +interface MarketplaceRemovalOptions { + cascade?: boolean; + scope?: MarketplaceScope | 'all'; + workspacePath?: string; + userRegistryPath?: string; +} + /** * Remove a marketplace from the registry and delete its files. * @@ -1118,12 +1126,7 @@ async function removeMarketplaceRegistration( */ export async function removeMarketplace( name: string, - options: { - cascade?: boolean; - scope?: MarketplaceScope | 'all'; - workspacePath?: string; - userRegistryPath?: string; - } = {}, + options: MarketplaceRemovalOptions = {}, deps: Partial = {}, ): Promise { const scope = options.scope ?? 'all'; @@ -1143,6 +1146,18 @@ export async function removeMarketplace( // scope === 'all' without workspacePath: fall back to user-only removal } + const remove = () => removeRegisteredMarketplace(name, scope, options, deps); + if (!options.cascade) return remove(); + const { getUserWorkspaceConfigPath } = await import('./user-workspace.js'); + return withWorkspaceConfigMutation(getUserWorkspaceConfigPath(), remove); +} + +async function removeRegisteredMarketplace( + name: string, + scope: MarketplaceScope | 'all', + options: MarketplaceRemovalOptions, + deps: Partial, +): Promise { const userRegPath = options.userRegistryPath ?? getRegistryPath(); let removedEntry: MarketplaceEntry | undefined; const warnings: string[] = []; diff --git a/src/core/profile/rename-transaction.ts b/src/core/profile/rename-transaction.ts index d71a0656..f09afc4d 100644 --- a/src/core/profile/rename-transaction.ts +++ b/src/core/profile/rename-transaction.ts @@ -62,6 +62,7 @@ export const RenameRecordSchema = z.object({ }); export type RenameRecord = z.infer; +type NamedFileMove = NonNullable['namedFiles'][number]; export async function profileRenameStats(path: string) { return lstat(path).catch((error) => { @@ -324,31 +325,14 @@ export async function inspectRenameProgress( throw new Error(`Profile destination already exists: ${newRoot}`); } const currentRoot = oldIdentity ? oldRoot : newRoot; - const moves = []; - for (const move of record.root?.namedFiles ?? []) { - const from = join(currentRoot, move.from); - const to = join(currentRoot, move.to); - await assertSafeProfilePath(currentRoot, from); - await assertSafeProfilePath(currentRoot, to); - const source = await fingerprintProfileFile(from); - const destination = await fingerprintProfileFile(to); - if (destination !== null) { - const sourceStats = await profileRenameStats(from); - const targetStats = await profileRenameStats(to); - if ( - oldIdentity || - destination !== move.fingerprint || - (sourceStats && - (sourceStats.ino !== targetStats?.ino || - sourceStats.dev !== targetStats.dev)) - ) { - throw new Error(`Profile file destination already exists: ${to}`); - } - } - if (source !== null ? source !== move.fingerprint : destination === null) { - throw changed(from); - } - moves.push({ ...move, source, destination }); + const moves = record.root?.namedFiles ?? []; + for (const move of moves) { + await inspectNamedFileMove( + currentRoot, + move, + record.id, + oldIdentity !== null, + ); } const replacements = record.launchers.map(({ name, ...entry }) => ({ ...entry, @@ -373,21 +357,63 @@ export async function inspectRenameProgress( return { moveRoot: oldIdentity !== null, moves }; } -export async function moveNamedProfileFile( +async function inspectNamedFileMove( root: string, - move: Awaited>['moves'][number], -): Promise { - if (move.source === null) return; + move: NamedFileMove, + transactionId: string, + atOldRoot = false, +) { const from = join(root, move.from); const to = join(root, move.to); + const capture = capturedRenameFile(from, transactionId); await assertSafeProfilePath(root, from); await assertSafeProfilePath(root, to); - if ((await fingerprintProfileFile(from)) !== move.fingerprint) + await assertSafeProfilePath(root, capture); + const [source, destination, captured] = await Promise.all([ + fingerprintProfileFile(from), + fingerprintProfileFile(to), + fingerprintProfileFile(capture), + ]); + if (captured !== null && (atOldRoot || captured !== move.fingerprint)) { + throw new Error( + `Profile rename found an intervening edit preserved at ${capture}`, + ); + } + if (source !== null && (captured !== null || source !== move.fingerprint)) { + throw changed(from); + } + if (destination !== null) { + if (atOldRoot || destination !== move.fingerprint) { + throw new Error(`Profile file destination already exists: ${to}`); + } + if (source !== null || captured !== null) { + const previous = await lstat(source !== null ? from : capture, { + bigint: true, + }); + const current = await lstat(to, { bigint: true }); + if (previous.ino !== current.ino || previous.dev !== current.dev) { + throw new Error(`Profile file destination already exists: ${to}`); + } + } + } + if (source === null && destination === null && captured === null) throw changed(from); - if (move.destination === null) await link(from, to); - const source = await lstat(from, { bigint: true }); - const destination = await lstat(to, { bigint: true }); - if (source.ino !== destination.ino || source.dev !== destination.dev) + return { from, to, capture, source, destination, captured }; +} + +export async function moveNamedProfileFile( + root: string, + move: NamedFileMove, + transactionId: string, +): Promise { + const { from, to, capture, source, destination, captured } = + await inspectNamedFileMove(root, move, transactionId); + if (source === null && captured === null) return; + if (destination === null) await link(source === null ? capture : from, to); + // Capture the entry first. An editor can replace its pathname after link(). + if (source !== null) await rename(from, capture); + const published = await inspectNamedFileMove(root, move, transactionId); + if (published.destination === null || published.captured === null) throw changed(to); - await unlink(from); + await unlink(capture); } diff --git a/src/core/profile/rename.ts b/src/core/profile/rename.ts index d79112d4..1fe2e8ec 100644 --- a/src/core/profile/rename.ts +++ b/src/core/profile/rename.ts @@ -233,6 +233,12 @@ async function planInstalledRename( ); } await adapter.rename.assertRelocatable?.(before, runtime); + for (const path of launcher ? (before.launcher.requiredFiles ?? []) : []) { + await assertSafeProfilePath(before.root, path); + if (!(await profileRenameStats(path))?.isFile()) { + throw new Error(`Profile launcher requires a regular file at ${path}`); + } + } for (const name of adapter.rename.nativeLocations ?? []) { const path = join(before.root, name); await assertSafeProfilePath(before.root, path); @@ -460,31 +466,12 @@ async function prepareRename( profile, newProfile, ).content; - workspaceBefore = fingerprint; + if (workspaceStats && !capturedStats) workspaceBefore = fingerprint; } else if ( - !oldDeclaration && - newDeclaration && - hashProfileDeclaration(newDeclaration) === existing.declarationDigest + oldDeclaration || + !newDeclaration || + hashProfileDeclaration(newDeclaration) !== existing.declarationDigest ) { - if (capturedPath && capturedStats) { - const captured = await readFile(capturedPath, 'utf8'); - const previous = replaceDeclaration( - captured, - workspacePath, - profile, - newProfile, - ); - if ( - hashProfileDeclaration(previous.declaration) !== - existing.declarationDigest - ) { - throw new Error( - `Profile rename preserved an intervening declaration edit at ${capturedPath}`, - ); - } - workspaceBefore = sha256Fingerprint(captured); - } - } else { throw new Error( 'The profile declaration changed during rename. Restore it before retrying.', ); @@ -656,9 +643,12 @@ export async function applyProfileRename( runtime, initial.record.id, ); - const { record } = current; + const record = { + ...current.record, + workspaceBefore: current.workspaceBefore, + }; if ( - !isDeepStrictEqual(initial.record, record) || + !isDeepStrictEqual(initial.record, current.record) || initial.workspaceBefore !== current.workspaceBefore || initial.workspaceContent !== current.workspaceContent ) { @@ -668,8 +658,13 @@ export async function applyProfileRename( } const oldRoot = getProfileRoot(runtime, record.profile); const newRoot = getProfileRoot(runtime, record.newProfile); - if (!current.recovering) await writeRenameRecord(journal, record); try { + if ( + !current.recovering || + record.workspaceBefore !== current.record.workspaceBefore + ) { + await writeRenameRecord(journal, record, current.recovering); + } const progress = await inspectRenameProgress( record, oldRoot, @@ -679,7 +674,7 @@ export async function applyProfileRename( if (progress.moveRoot) await moveProfileRoot(record, journal, oldRoot, newRoot); for (const move of progress.moves) - await moveNamedProfileFile(newRoot, move); + await moveNamedProfileFile(newRoot, move, record.id); for (const { name, content, before, mode } of record.launchers) { await publishRenameFile( join(runtime.binDir, name), diff --git a/src/core/prune.ts b/src/core/prune.ts index e61cb547..48690651 100644 --- a/src/core/prune.ts +++ b/src/core/prune.ts @@ -1,7 +1,7 @@ import { writeWorkspaceConfig } from '../utils/workspace-writer.js'; import { withWorkspaceConfigMutation } from '../utils/workspace-config-lock.js'; import { existsSync } from 'node:fs'; -import { join } from 'node:path'; +import { dirname, join } from 'node:path'; import { CONFIG_DIR, WORKSPACE_CONFIG_FILE } from '../constants.js'; import { isPluginSpec, parsePluginSpec, getMarketplace } from './marketplace.js'; import { getUserWorkspaceConfigPath, isUserConfigPath } from './user-workspace.js'; @@ -66,6 +66,18 @@ async function prunePlugins(plugins: PluginEntry[]): Promise { + const userConfigPath = getUserWorkspaceConfigPath(); + // A pending rename can temporarily leave workspace.yaml at its capture path. + if (!existsSync(dirname(userConfigPath))) return pruneScopes(workspacePath); + return withWorkspaceConfigMutation(userConfigPath, () => + pruneScopes(workspacePath, userConfigPath), + ); +} + +async function pruneScopes( + workspacePath: string, + userConfigPath?: string, ): Promise { // Prune project-level plugins let projectResult: InternalPruneScopeResult = { removed: [], kept: [], keptEntries: [] }; @@ -87,18 +99,13 @@ export async function pruneOrphanedPlugins( kept: [], keptEntries: [], }; - const userConfigPath = getUserWorkspaceConfigPath(); - if (existsSync(userConfigPath)) { - userResult = await withWorkspaceConfigMutation(userConfigPath, async () => { - const userConfig = await parseUserWorkspaceConfigForEdit(userConfigPath); - const result = await prunePlugins(userConfig.plugins); - - if (result.removed.length > 0) { - userConfig.plugins = result.keptEntries; - await writeWorkspaceConfig(userConfigPath, userConfig); - } - return result; - }); + if (userConfigPath && existsSync(userConfigPath)) { + const userConfig = await parseUserWorkspaceConfigForEdit(userConfigPath); + userResult = await prunePlugins(userConfig.plugins); + if (userResult.removed.length > 0) { + userConfig.plugins = userResult.keptEntries; + await writeWorkspaceConfig(userConfigPath, userConfig); + } } return { diff --git a/src/core/user-workspace.ts b/src/core/user-workspace.ts index bcec5ed6..0cf62c87 100644 --- a/src/core/user-workspace.ts +++ b/src/core/user-workspace.ts @@ -1081,6 +1081,8 @@ export async function getInstalledProjectPlugins( export async function migrateUserWorkspaceSkillsV1toV2(): Promise { const configPath = getUserWorkspaceConfigPath(); if (!existsSync(configPath)) return; + const current = await parseUserWorkspaceConfigForEdit(configPath); + if ((current.version ?? 0) >= 2) return; await withWorkspaceConfigMutation(configPath, async () => { const config = await parseUserWorkspaceConfigForEdit(configPath); diff --git a/tests/e2e/profile-rename.test.ts b/tests/e2e/profile-rename.test.ts index 2323605e..8b75426f 100644 --- a/tests/e2e/profile-rename.test.ts +++ b/tests/e2e/profile-rename.test.ts @@ -5,6 +5,7 @@ import { mkdtempSync, readFileSync, readdirSync, + renameSync, rmSync, statSync, symlinkSync, @@ -112,6 +113,10 @@ beforeEach(() => { afterEach(() => rmSync(root, { recursive: true, force: true })); +test('structured help declares conditional confirmation', () => { + expect(json(['profile', 'rename', '--help']).interaction).toBe('conditional'); +}); + test('previews a declared-only rename and requires confirmation before changing YAML', () => { const dryRun = json(['profile', 'rename', 'spare', 'backup', '--dry-run']); expect(dryRun.data).toMatchObject({ @@ -230,6 +235,27 @@ test.skipIf(process.platform === 'win32')('rejects an installed client without a expect(existsSync(join(profiles, 'office'))).toBe(false); }, fixtureTimeout); +test.skipIf(process.platform === 'win32' || process.platform === 'darwin')('refuses to retarget a launcher whose required MCP file is missing', () => { + const yaml = 'profiles: {work: {clients: [{name: claude, launcher: run-claude}]}}\n'; + seedFile(workspace, yaml); + writeFileSync(join(bin, 'claude'), [ + '#!/bin/sh', + 'if [ "$1" = "--version" ]; then echo "99.0.0 (Claude Code)"; exit; fi', + 'echo "install list marketplace uninstall update"', + ].join('\n'), { mode: 0o755 }); + json(['profile', 'install', 'work', '--yes', '--offline']); + const required = join(profiles, 'work', 'clients/claude/config/allagents.mcp.json'); + const launcher = join(bin, 'run-claude'); + const original = read(launcher); + rmSync(required); + + expect(json(['profile', 'rename', 'work', 'office', '--yes'], 1).error).toContain(required); + expect(read(workspace)).toBe(yaml); + expect(read(launcher)).toBe(original); + expect(existsSync(join(profiles, 'office'))).toBe(false); + expect(existsSync(`${workspace}.profile-rename.json`)).toBe(false); +}, fixtureTimeout); + test.skipIf(process.platform === 'win32')('resumes after a process stop before publishing the declaration', () => { json(['profile', 'install', 'work', '--yes', '--offline']); const oldRoot = join(profiles, 'work'); @@ -273,10 +299,98 @@ test.skipIf(process.platform === 'win32')('preserves an edit arriving at workspa ]); expect(blocked.exitCode, blocked.stdout.toString() + blocked.stderr.toString()).toBe(1); expect(read(workspace)).toBe(edited); + const interrupted = interruptibleRename([ + 'const link = fs.link;', + 'fs.link = (from, to) => to === process.env.TEST_WORKSPACE', + ' ? process.kill(process.pid, "SIGKILL") : link(from, to);', + ]); + expect(interrupted.signalCode).toBe('SIGKILL'); expect(json(['profile', 'rename', 'work', 'office', '--yes']).data.status).toBe('renamed'); expect(read(workspace)).toBe(edited.replace("'work':", "'office':")); }, fixtureTimeout); +test.skipIf(process.platform === 'win32').each(['workspace', 'launcher'])('retains an edit through an open %s handle across a retry', (asset) => { + json(['profile', 'install', 'work', '--yes', '--offline']); + const target = asset === 'workspace' ? workspace : join(bin, 'run-codex'); + const original = read(target); + const edited = original + '# saved through an open handle\n'; + const blocked = interruptibleRename([ + 'let editor;', + 'const { rename, link } = fs;', + 'fs.rename = async (from, to) => {', + ' if (from === process.env.TEST_TARGET) editor = await fs.open(from, "a");', + ' return rename(from, to);', + '};', + 'fs.link = async (from, to) => {', + ' await link(from, to);', + ' if (to === process.env.TEST_TARGET && editor) {', + ' await editor.writeFile("# saved through an open handle\\n");', + ' await editor.close();', + ' }', + '};', + ], { TEST_TARGET: target }); + expect(blocked.exitCode, blocked.stdout.toString()).toBe(1); + const error = JSON.parse(blocked.stdout.toString()).error as string; + const captureName = readdirSync(dirname(target)).find((name) => name.endsWith('.previous')); + expect(captureName).toBeDefined(); + const capture = join(dirname(target), captureName as string); + expect(error).toContain(capture); + expect(read(capture)).toBe(edited); + expect(json(['profile', 'rename', 'work', 'office', '--yes'], 1).error).toContain(capture); + expect(read(capture)).toBe(edited); + + const saved = join(root, 'saved-edit'); + renameSync(capture, saved); + expect(json(['profile', 'rename', 'work', 'office', '--yes']).data.status).toBe('renamed'); + expect(read(saved)).toBe(edited); +}, fixtureTimeout); + +test.skipIf(process.platform === 'win32')('keeps a named settings edit that replaces the old entry after linking', () => { + json(['profile', 'install', 'work', '--yes', '--offline']); + const client = join(profiles, 'office', 'clients/codex/home'); + const from = join(client, 'work.config.toml'); + const original = read(join(profiles, 'work', 'clients/codex/home/work.config.toml')); + const edited = 'model = "custom"\n'; + const blocked = interruptibleRename([ + 'const { rename, unlink } = fs;', + 'async function saveEdit(path) {', + ' if (path !== process.env.TEST_SETTINGS) return;', + ' await fs.writeFile(path + ".editor", \'model = "custom"\\n\');', + ' await rename(path + ".editor", path);', + '}', + 'fs.unlink = async (path) => { await saveEdit(path); return unlink(path); };', + 'fs.rename = async (from, to) => { await saveEdit(from); return rename(from, to); };', + ], { TEST_SETTINGS: from }); + expect(blocked.exitCode, blocked.stdout.toString()).toBe(1); + expect(read(join(client, 'office.config.toml'))).toBe(original); + const captureName = readdirSync(client).find((name) => name.endsWith('.previous')); + expect(captureName).toBeDefined(); + const capture = join(client, captureName as string); + expect(read(capture)).toBe(edited); + const saved = join(root, 'saved-settings'); + renameSync(capture, saved); + expect(json(['profile', 'rename', 'work', 'office', '--yes']).data.status).toBe('renamed'); + expect(read(saved)).toBe(edited); +}, fixtureTimeout); + +test.skipIf(process.platform === 'win32')('resumes after capturing linked settings and before cleaning up the old entry', () => { + json(['profile', 'install', 'work', '--yes', '--offline']); + const client = join(profiles, 'office', 'clients/codex/home'); + const original = read(join(profiles, 'work', 'clients/codex/home/work.config.toml')); + const stopped = interruptibleRename([ + 'const rename = fs.rename;', + 'fs.rename = async (from, to) => {', + ' await rename(from, to);', + ' if (from === process.env.TEST_SETTINGS) process.kill(process.pid, "SIGKILL");', + '};', + ], { TEST_SETTINGS: join(client, 'work.config.toml') }); + expect(stopped.signalCode).toBe('SIGKILL'); + expect(read(join(client, 'office.config.toml'))).toBe(original); + expect(json(['profile', 'rename', 'work', 'office', '--yes']).data.recovering).toBe(true); + expect(read(join(client, 'office.config.toml'))).toBe(original); + expect(readdirSync(client)).toEqual(['office.config.toml']); +}, fixtureTimeout); + test.skipIf(process.platform === 'win32')('does not replace a directory created at destination reservation', () => { json(['profile', 'install', 'work', '--yes', '--offline']); const oldRoot = join(profiles, 'work'); @@ -297,5 +411,20 @@ test.skipIf(process.platform === 'win32')('does not replace a directory created expect(existsSync(join(oldRoot, 'state.json'))).toBe(true); expect(read(workspace)).toBe(fixtureYaml); rmSync(newRoot, { recursive: true }); + + const interrupted = interruptibleRename([ + 'const mkdir = fs.mkdir;', + 'fs.mkdir = async (path, options) => {', + ' const result = await mkdir(path, options);', + ' if (path === process.env.TEST_DESTINATION) process.kill(process.pid, "SIGKILL");', + ' return result;', + '};', + ], { TEST_DESTINATION: newRoot }); + expect(interrupted.signalCode).toBe('SIGKILL'); + expect(json(['profile', 'rename', 'work', 'office', '--yes'], 1).error).toContain('destination already exists'); + expect(existsSync(join(oldRoot, 'state.json'))).toBe(true); + const saved = join(root, 'empty-reservation'); + renameSync(newRoot, saved); expect(json(['profile', 'rename', 'work', 'office', '--yes']).data.status).toBe('renamed'); + expect(readdirSync(saved)).toEqual([]); }, fixtureTimeout); diff --git a/tests/unit/core/marketplace-remove-cascade.test.ts b/tests/unit/core/marketplace-remove-cascade.test.ts index 2c25a0e3..c48a8334 100644 --- a/tests/unit/core/marketplace-remove-cascade.test.ts +++ b/tests/unit/core/marketplace-remove-cascade.test.ts @@ -206,6 +206,27 @@ describe('removeMarketplace cascade', () => { expect(result.retainedUserPlugins).toBeUndefined(); }); + it('preserves the registration when a pending rename blocks a cascade', async () => { + await writeRegistry({ + 'my-marketplace': { + name: 'my-marketplace', + source: { type: 'local', location: '/tmp/mp' }, + path: '/tmp/mp', + }, + }); + await writeUserConfig({ repositories: [], clients: [], plugins: ['plugin@my-marketplace'] }); + const journal = join(testDir, '.allagents', `${WORKSPACE_CONFIG_FILE}.profile-rename.json`); + await writeFile(journal, '{}'); + + await expect(removeMarketplace('my-marketplace', { cascade: true })).rejects.toThrow('profile rename is incomplete'); + expect((await readUserConfig()).plugins).toEqual(['plugin@my-marketplace']); + + await rm(journal); + const result = await removeMarketplace('my-marketplace', { cascade: true }); + expect(result.success).toBe(true); + expect(result.removedUserPlugins).toEqual(['plugin@my-marketplace']); + }); + it('should delete the marketplace directory when it exists', async () => { const marketplacePath = join(testDir, '.allagents', 'plugins', 'marketplaces', 'my-marketplace'); await mkdir(marketplacePath, { recursive: true }); diff --git a/tests/unit/core/prune.test.ts b/tests/unit/core/prune.test.ts index 4c550337..67eab65a 100644 --- a/tests/unit/core/prune.test.ts +++ b/tests/unit/core/prune.test.ts @@ -166,6 +166,22 @@ describe('pruneOrphanedPlugins', () => { expect(result.user.removed).toEqual([]); }); + it('preserves project declarations when a pending rename blocks user pruning', async () => { + const projectDir = join(testDir, 'project'); + const projectConfig = join(projectDir, CONFIG_DIR, WORKSPACE_CONFIG_FILE); + const userConfig = join(testDir, CONFIG_DIR, WORKSPACE_CONFIG_FILE); + const yaml = 'repositories: []\nclients: []\nplugins: [plugin@missing-marketplace]\n'; + await mkdir(join(projectDir, CONFIG_DIR), { recursive: true }); + await mkdir(join(testDir, CONFIG_DIR), { recursive: true }); + await writeFile(projectConfig, yaml); + await writeFile(userConfig, yaml); + await writeFile(`${userConfig}.profile-rename.json`, '{}'); + + await expect(pruneOrphanedPlugins(projectDir)).rejects.toThrow('profile rename is incomplete'); + expect(await readFile(projectConfig, 'utf-8')).toBe(yaml); + expect(await readFile(userConfig, 'utf-8')).toBe(yaml); + }); + it('should skip non-marketplace plugins (local paths, GitHub URLs)', async () => { await writeRegistry({}); diff --git a/tests/unit/core/user-workspace.test.ts b/tests/unit/core/user-workspace.test.ts index 86259d2b..e3a70058 100644 --- a/tests/unit/core/user-workspace.test.ts +++ b/tests/unit/core/user-workspace.test.ts @@ -30,6 +30,7 @@ import { getUserWorkspaceConfigPath, getInstalledUserPlugins, getInstalledProjectPlugins, + migrateUserWorkspaceSkillsV1toV2, setUserClients, } from '../../../src/core/user-workspace.js'; import * as git from '../../../src/core/git.js'; @@ -194,6 +195,17 @@ describe('user-workspace', () => { expect(result.error).toContain('profile rename is incomplete'); expect(await readFile(path, 'utf-8')).toBe(original); }); + + test('skips an already current skills migration during a pending rename', async () => { + await ensureUserWorkspace(); + const path = getUserWorkspaceConfigPath(); + const current = 'version: 2\nclients: []\n'; + await writeFile(path, current); + await writeFile(`${path}.profile-rename.json`, '{}'); + + await migrateUserWorkspaceSkillsV1toV2(); + expect(await readFile(path, 'utf-8')).toBe(current); + }); }); describe('addUserPlugin', () => { From f02b527da805b8273483776c9459b70ea9c78b1e Mon Sep 17 00:00:00 2001 From: Christopher Tso Date: Thu, 26 Nov 2026 17:16:13 +1100 Subject: [PATCH 4/4] fix(cli): recheck launcher files when resuming profile rename --- src/core/profile/rename.ts | 63 ++++++++++++++++++++------------ tests/e2e/profile-rename.test.ts | 45 +++++++++++++++++++---- 2 files changed, 77 insertions(+), 31 deletions(-) diff --git a/src/core/profile/rename.ts b/src/core/profile/rename.ts index 1fe2e8ec..2a2a8a29 100644 --- a/src/core/profile/rename.ts +++ b/src/core/profile/rename.ts @@ -51,6 +51,7 @@ import { sanitizeProfileError, sanitizeProfileState, } from './state.js'; +import type { ProfileClientContext } from './types.js'; export interface ProfileRenamePlan { readonly profile: string; @@ -70,6 +71,7 @@ export interface ProfileRenamePlan { interface RenamePlanDetails { readonly runtime: ResolvedProfileRuntime; readonly record: RenameRecord; + readonly declaration: ProfileDeclaration; readonly workspaceContent: string; readonly workspaceBefore: string; readonly workspaceMode: number; @@ -77,6 +79,17 @@ interface RenamePlanDetails { const plans = new WeakMap(); +async function assertLauncherFiles( + context: ProfileClientContext, +): Promise { + for (const path of context.launcher.requiredFiles ?? []) { + await assertSafeProfilePath(context.root, path); + if (!(await profileRenameStats(path))?.isFile()) { + throw new Error(`Profile launcher requires a regular file at ${path}`); + } + } +} + async function checkProfileTree(root: string): Promise { for (const item of await readdir(root, { withFileTypes: true })) { const path = join(root, item.name); @@ -233,12 +246,7 @@ async function planInstalledRename( ); } await adapter.rename.assertRelocatable?.(before, runtime); - for (const path of launcher ? (before.launcher.requiredFiles ?? []) : []) { - await assertSafeProfilePath(before.root, path); - if (!(await profileRenameStats(path))?.isFile()) { - throw new Error(`Profile launcher requires a regular file at ${path}`); - } - } + if (launcher) await assertLauncherFiles(before); for (const name of adapter.rename.nativeLocations ?? []) { const path = join(before.root, name); await assertSafeProfilePath(before.root, path); @@ -453,29 +461,23 @@ async function prepareRename( profiles && Object.hasOwn(profiles, newProfile) ? profiles[newProfile] : undefined; - let workspaceContent = current; - let workspaceBefore = existing.workspaceBefore; + const declaration = oldDeclaration ?? newDeclaration; if ( - oldDeclaration && - !newDeclaration && - hashProfileDeclaration(oldDeclaration) === existing.declarationDigest - ) { - workspaceContent = replaceDeclaration( - current, - workspacePath, - profile, - newProfile, - ).content; - if (workspaceStats && !capturedStats) workspaceBefore = fingerprint; - } else if ( - oldDeclaration || - !newDeclaration || - hashProfileDeclaration(newDeclaration) !== existing.declarationDigest + !declaration || + (oldDeclaration && newDeclaration) || + hashProfileDeclaration(declaration) !== existing.declarationDigest ) { throw new Error( 'The profile declaration changed during rename. Restore it before retrying.', ); } + const workspaceContent = oldDeclaration + ? replaceDeclaration(current, workspacePath, profile, newProfile).content + : current; + const workspaceBefore = + oldDeclaration && workspaceStats && !capturedStats + ? fingerprint + : existing.workspaceBefore; await inspectReplacement( workspacePath, workspaceBefore, @@ -486,6 +488,7 @@ async function prepareRename( return { runtime, record: existing, + declaration, workspaceContent, workspaceBefore, workspaceMode, @@ -560,6 +563,7 @@ async function prepareRename( return { runtime, record, + declaration: updated.declaration, workspaceContent: updated.content, workspaceBefore: fingerprint, workspaceMode, @@ -675,6 +679,19 @@ export async function applyProfileRename( await moveProfileRoot(record, journal, oldRoot, newRoot); for (const move of progress.moves) await moveNamedProfileFile(newRoot, move, record.id); + if (record.launchers.length) { + for (const { name, launcher } of current.declaration.clients) { + if (!launcher) continue; + const adapter = getProfileAdapter(name); + if (!adapter?.rename) + throw new Error( + `Installed profile rename is unsupported for '${name}'`, + ); + await assertLauncherFiles( + adapter.resolveContext(record.newProfile, runtime), + ); + } + } for (const { name, content, before, mode } of record.launchers) { await publishRenameFile( join(runtime.binDir, name), diff --git a/tests/e2e/profile-rename.test.ts b/tests/e2e/profile-rename.test.ts index 8b75426f..d0456cff 100644 --- a/tests/e2e/profile-rename.test.ts +++ b/tests/e2e/profile-rename.test.ts @@ -77,6 +77,16 @@ function seedFile(path: string, content: string) { writeFileSync(path, content); } +function installClaudeFixture() { + seedFile(workspace, 'profiles: {work: {clients: [{name: claude, launcher: run-claude}]}}\n'); + writeFileSync(join(bin, 'claude'), [ + '#!/bin/sh', + 'if [ "$1" = "--version" ]; then echo "99.0.0 (Claude Code)"; exit; fi', + 'echo "install list marketplace uninstall update"', + ].join('\n'), { mode: 0o755 }); + json(['profile', 'install', 'work', '--yes', '--offline']); +} + beforeAll(() => { const result = Bun.spawnSync(['bun', 'run', 'build'], { cwd: repo }); if (result.exitCode !== 0) throw new Error(result.stderr.toString()); @@ -236,14 +246,8 @@ test.skipIf(process.platform === 'win32')('rejects an installed client without a }, fixtureTimeout); test.skipIf(process.platform === 'win32' || process.platform === 'darwin')('refuses to retarget a launcher whose required MCP file is missing', () => { - const yaml = 'profiles: {work: {clients: [{name: claude, launcher: run-claude}]}}\n'; - seedFile(workspace, yaml); - writeFileSync(join(bin, 'claude'), [ - '#!/bin/sh', - 'if [ "$1" = "--version" ]; then echo "99.0.0 (Claude Code)"; exit; fi', - 'echo "install list marketplace uninstall update"', - ].join('\n'), { mode: 0o755 }); - json(['profile', 'install', 'work', '--yes', '--offline']); + installClaudeFixture(); + const yaml = read(workspace); const required = join(profiles, 'work', 'clients/claude/config/allagents.mcp.json'); const launcher = join(bin, 'run-claude'); const original = read(launcher); @@ -256,6 +260,31 @@ test.skipIf(process.platform === 'win32' || process.platform === 'darwin')('refu expect(existsSync(`${workspace}.profile-rename.json`)).toBe(false); }, fixtureTimeout); +test.skipIf(process.platform === 'win32' || process.platform === 'darwin')('keeps recovery pending until a relocated launcher prerequisite is restored', () => { + installClaudeFixture(); + const destination = join(profiles, 'office'); + const launcher = join(bin, 'run-claude'); + const original = read(launcher); + const stopped = interruptibleRename([ + 'const rename = fs.rename;', + 'fs.rename = async (from, to) => {', + ' await rename(from, to);', + ' if (to === process.env.TEST_DESTINATION) process.kill(process.pid, "SIGKILL");', + '};', + ], { TEST_DESTINATION: destination }); + expect(stopped.signalCode).toBe('SIGKILL'); + const required = join(destination, 'clients/claude/config/allagents.mcp.json'); + const contents = read(required); + rmSync(required); + + expect(json(['profile', 'rename', 'work', 'office', '--yes'], 1).error).toContain(required); + expect(read(launcher)).toBe(original); + expect(existsSync(`${workspace}.profile-rename.json`)).toBe(true); + seedFile(required, contents); + expect(json(['profile', 'rename', 'work', 'office', '--yes']).data.status).toBe('renamed'); + expect(read(launcher)).toContain(required); +}, fixtureTimeout); + test.skipIf(process.platform === 'win32')('resumes after a process stop before publishing the declaration', () => { json(['profile', 'install', 'work', '--yes', '--offline']); const oldRoot = join(profiles, 'work');