Skip to content

armgit / ECC

Public Imported from GitHub
0

The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.

chore: preserve WIP home migration review fixes after upstream replacement

Dante9cccf7dca5a5
diff --cc scripts/hooks/plugin-hook-bootstrap.js
index 18ea385cb,233e32980..ce42872e0
--- a/scripts/hooks/plugin-hook-bootstrap.js
+++ b/scripts/hooks/plugin-hook-bootstrap.js
@@@ -4,18 -4,11 +4,11 @@@
const path = require('path');
const { spawnSync } = require('child_process');
const { ensureAgentDataHomeEnv } = require('../lib/agent-data-home');
+ const { normalizePluginRootForPlatform } = require('../lib/resolve-ecc-root');
+ const { readStdinRaw: readBoundedStdin, resolveMaxStdin } = require('./hook-input');
-const SHELL_PROBE_TIMEOUT_MS = 2000;
+const SHELL_PROBE_TIMEOUT_MS = 5000;
- function readStdinRaw() {
- try {
- return fs.readFileSync(0, 'utf8');
- } catch (_error) {
- return '';
- }
- }
-
function writeStderr(stderr) {
if ((typeof stderr === 'string' || Buffer.isBuffer(stderr)) && stderr.length > 0) {
process.stderr.write(stderr);
diff --cc scripts/lib/install-lifecycle.js
index b2f967b91,98abf8e20..5c98ddaf5
--- a/scripts/lib/install-lifecycle.js
+++ b/scripts/lib/install-lifecycle.js
@@@ -595,6 -556,6 +560,7 @@@ function copyContainedFile(sourcePath,
}
function removeContainedPath(destinationPath, trustedRoot, action, options = {}) {
++ const { verifyQuarantined, ...removeOptions } = options;
const existingDestination = getContainedExistingPath(
destinationPath,
trustedRoot,
@@@ -627,7 -588,7 +593,8 @@@
}
const quarantinedStat = fs.lstatSync(quarantinePath, { bigint: true });
-- if (!hasSameFileIdentity(expectedStat, quarantinedStat)) {
++ if (!hasSameFileIdentity(expectedStat, quarantinedStat)
++ || (verifyQuarantined && !verifyQuarantined(quarantinePath))) {
try {
fs.renameSync(quarantinePath, finalDestination);
fs.rmdirSync(quarantineDir);
@@@ -642,7 -603,7 +609,7 @@@
if (quarantinedStat.isDirectory() && !options.recursive) {
fs.rmdirSync(quarantinePath);
} else {
-- fs.rmSync(quarantinePath, options);
++ fs.rmSync(quarantinePath, removeOptions);
}
fs.rmdirSync(quarantineDir);
return finalDestination;
@@@ -1912,10 -1918,13 +1924,15 @@@ function prepareRepairMigration(plan, r
installStatePath: record.installStatePath,
statePreview: buildAdapterDerivedStatePreview(plan.statePreview, record),
};
- const migration = prepareLegacyAgentsMigration(
- trustedPlan,
- prepareClaudeSkillMigration(trustedPlan)
- const initialMigration = prepareClaudeSkillMigration(trustedPlan);
++ const initialMigration = prepareLegacyAgentsMigration(
++ trustedPlan, prepareClaudeSkillMigration(trustedPlan)
+ );
+ const guardedMigration = record.adapter.id === 'codex-home'
+ ? prepareUserOwnedFileGuard(trustedPlan, initialMigration)
+ : initialMigration;
+ const migration = trustedPlan.target === 'opencode'
+ ? require('./install/apply').prepareHookConsentMigration(trustedPlan, guardedMigration)
+ : guardedMigration;
return {
migration,
plan: {
@@@ -2083,156 -2179,161 +2187,172 @@@ function repairInstalledStates(options
installStatePath: record.installStatePath,
repairedPaths: [],
plannedRepairs: [],
- error: formatBuildErrorMessage(error)
+ warnings: desiredPlan.warnings,
+ error: `Missing source file(s): ${operationHealth.missingSource.map(entry => entry.sourcePath).join(', ')}`
};
}
- }
- const rawPlan = createRepairPlanFromRecord(record, context);
- const {
- migration,
- plan: desiredPlan,
- } = prepareRepairMigration(rawPlan, record);
- const operationHealth = summarizeManagedOperationHealth(
- context.repoRoot,
- record.targetRoot,
- desiredPlan.operations,
- record.adapter.target
- );
+ const repairOperations = [
+ ...operationHealth.missing.map(entry => ({ ...entry.operation })),
+ ...operationHealth.drifted.map(entry => ({ ...entry.operation })),
+ ...desiredPlan.operations
+ .filter(operation => (
+ operation.kind === 'update-claude-settings'
+ && operation.previousManagedHooks
+ && !isDeepStrictEqual(operation.previousManagedHooks, operation.managedHooks)
+ ))
+ .map(operation => ({ ...operation })),
+ ].filter((operation, index, items) => items.findIndex(candidate => (
+ candidate.kind === operation.kind
+ && candidate.destinationPath === operation.destinationPath
+ )) === index);
+ const repairLinkIndex = buildLinkIndexForOperations(desiredPlan.operations, record.targetRoot);
+ const legacyMigrationPaths = migration.legacyOperationsToRemove.map(
+ operation => operation.destinationPath
+ );
++ const legacyAgentsMigrationPaths = migration.legacyAgentsOperationsToRemove.map(
++ operation => operation.destinationPath
++ );
++ const hasLegacyAgentsStateMigration = migration.legacyAgentsOperationsToDetach.length > 0;
+ const plannedRepairs = [...new Set([
+ ...(needsOpencodeBuild ? [opencodeBuildRepairPath] : []),
+ ...repairOperations.map(operation => operation.destinationPath),
+ ...legacyMigrationPaths,
++ ...legacyAgentsMigrationPaths,
++ ...(hasLegacyAgentsStateMigration ? [record.installStatePath] : []),
+ ])];
- const unsafeOperationResult = getUnsafeOperationResult(
- record,
- operationHealth
- );
- if (unsafeOperationResult) {
- return unsafeOperationResult;
- }
+ if (options.dryRun) {
+ return {
+ adapter: record.adapter,
+ status: plannedRepairs.length > 0 ? 'planned' : 'ok',
+ installStatePath: record.installStatePath,
+ repairedPaths: [],
+ plannedRepairs,
+ stateRefreshed: plannedRepairs.length === 0,
+ warnings: desiredPlan.warnings,
+ error: null
+ };
+ }
+
- const hasLegacyMigration = migration.legacyOperationsToRemove.length > 0;
++ const hasLegacyMigration = migration.legacyOperationsToRemove.length > 0
++ || hasLegacyAgentsStateMigration;
+ const repairedPaths = needsOpencodeBuild ? [opencodeBuildRepairPath] : [];
+ if (desiredPlan.target === 'opencode') {
+ const { assertOpenCodeActivationUnchanged } = require('./install/apply');
+ // Health inspection must not let a changed activation become owned by
+ // a bridge checkpoint before the per-write check can reject it.
+ for (const destinationPath of activationSnapshot.keys()) {
+ assertOpenCodeActivationUnchanged(desiredPlan, { destinationPath }, activationSnapshot);
+ }
+ }
+ if (migration.requiresBridgeState && (repairOperations.length > 0 || hasLegacyMigration)) {
+ writeRefreshedInstallState(record, migration.bridgeState);
+ }
+
+ for (const operation of repairOperations) {
+ if (desiredPlan.target === 'opencode') {
+ const { assertOpenCodeActivationUnchanged } = require('./install/apply');
+ assertOpenCodeActivationUnchanged(desiredPlan, operation, activationSnapshot);
+ }
+ if (record.adapter.id === 'codex-home') {
+ assertNoNewUserOwnedFile(migration, operation, desiredPlan);
+ }
+ const repairedPath = executeRepairOperation(
+ context.repoRoot,
+ operation,
+ record.targetRoot,
+ repairLinkIndex,
+ record.adapter.target,
+ Boolean(releaseSettingsLock),
+ require('./install/apply').getOpenCodeActivationWriteOptions(operation, activationSnapshot)
+ );
+ if (repairedPath) {
+ repairedPaths.push(repairedPath);
+ }
+ }
+ if (hasLegacyMigration) {
+ for (const operation of migration.legacyOperationsToRemove) {
+ const removedPath = removeContainedPath(
+ operation.destinationPath,
+ record.targetRoot,
+ 'migrate managed Claude skill',
+ { force: true }
+ );
+ if (removedPath) {
+ repairedPaths.push(removedPath);
+ }
+ }
+ }
++ const legacyAgentsRepairedPaths = removeLegacyAgentsFiles(migration, record.targetRoot);
++ const allRepairedPaths = [...repairedPaths, ...legacyAgentsRepairedPaths];
+ const changedInstalledBytes = repairOperations.length > 0
+ || needsOpencodeBuild
+ || hasLegacyMigration;
+ const statePreviewToWrite = changedInstalledBytes
+ ? desiredPlan.statePreview
+ : {
+ ...desiredPlan.statePreview,
+ installedAt: record.state.installedAt,
+ source: { ...record.state.source },
+ };
+ assertOpenCodeRepairHookDeactivation(desiredPlan, { requireInactive: true });
- writeRefreshedInstallState(record, statePreviewToWrite, repairedPaths);
++ writeRefreshedInstallState(record, statePreviewToWrite, allRepairedPaths);
- if (operationHealth.missingSource.length > 0) {
return {
adapter: record.adapter,
- status: 'error',
+ status: (repairOperations.length > 0 || needsOpencodeBuild || hasLegacyMigration)
+ ? 'repaired'
+ : 'ok',
installStatePath: record.installStatePath,
- repairedPaths: [],
- repairedPaths,
++ repairedPaths: allRepairedPaths,
plannedRepairs: [],
+ stateRefreshed: true,
warnings: desiredPlan.warnings,
- error: `Missing source file(s): ${operationHealth.missingSource.map(entry => entry.sourcePath).join(', ')}`
+ error: null
};
- }
-
- const repairOperations = [
- ...operationHealth.missing.map(entry => ({ ...entry.operation })),
- ...operationHealth.drifted.map(entry => ({ ...entry.operation })),
- ...desiredPlan.operations
- .filter(operation => (
- operation.kind === 'update-claude-settings'
- && operation.previousManagedHooks
- && !isDeepStrictEqual(operation.previousManagedHooks, operation.managedHooks)
- ))
- .map(operation => ({ ...operation })),
- ].filter((operation, index, items) => items.findIndex(candidate => (
- candidate.kind === operation.kind
- && candidate.destinationPath === operation.destinationPath
- )) === index);
- const repairLinkIndex = buildLinkIndexForOperations(desiredPlan.operations, record.targetRoot);
- const legacyMigrationPaths = migration.legacyOperationsToRemove.map(
- operation => operation.destinationPath
- );
- const legacyAgentsMigrationPaths = migration.legacyAgentsOperationsToRemove.map(
- operation => operation.destinationPath
- );
- const hasLegacyAgentsStateMigration = migration.legacyAgentsOperationsToDetach.length > 0;
- const plannedRepairs = [...new Set([
- ...(needsOpencodeBuild ? [opencodeBuildRepairPath] : []),
- ...repairOperations.map(operation => operation.destinationPath),
- ...legacyMigrationPaths,
- ...legacyAgentsMigrationPaths,
- ...(hasLegacyAgentsStateMigration ? [record.installStatePath] : []),
- ])];
-
- if (options.dryRun) {
+ } catch (error) {
return {
adapter: record.adapter,
- status: plannedRepairs.length > 0 ? 'planned' : 'ok',
+ status: 'error',
installStatePath: record.installStatePath,
repairedPaths: [],
- plannedRepairs,
- stateRefreshed: plannedRepairs.length === 0,
- warnings: desiredPlan.warnings,
- error: null
+ plannedRepairs: [],
+ error: error.message
};
+ } finally {
+ if (releaseSettingsLock) releaseSettingsLock();
}
+
- const hasLegacyMigration = migration.legacyOperationsToRemove.length > 0
- || hasLegacyAgentsStateMigration;
- const repairedPaths = needsOpencodeBuild ? [opencodeBuildRepairPath] : [];
- if (migration.requiresBridgeState && (repairOperations.length > 0 || hasLegacyMigration)) {
- writeRefreshedInstallState(record, migration.bridgeState);
- }
-
- for (const operation of repairOperations) {
- const repairedPath = executeRepairOperation(
- context.repoRoot,
- operation,
- record.targetRoot,
- repairLinkIndex,
- record.adapter.target,
- Boolean(releaseSettingsLock)
- );
- if (repairedPath) {
- repairedPaths.push(repairedPath);
- }
- }
- if (hasLegacyMigration) {
- for (const operation of migration.legacyOperationsToRemove) {
- const removedPath = removeContainedPath(
- operation.destinationPath,
- record.targetRoot,
- 'migrate managed Claude skill',
- { force: true }
- );
- if (removedPath) {
- repairedPaths.push(removedPath);
- }
+ };
+ if (record.adapter.target !== 'opencode' || options.dryRun) return performRepair();
+ let repairResult;
+ try {
+ const adapter = getInstallTargetAdapter('opencode');
+ const targetRoot = adapter.resolveRoot({
+ homeDir: context.homeDir, projectRoot: context.projectRoot,
+ repoRoot: context.projectRoot, env: context.env,
+ });
+ const { getOpenCodeInstallRoots, assertOpenCodeLeaseCoverage } = require('./install/apply');
+ const roots = getOpenCodeInstallRoots({ adapter, targetRoot, homeDir: context.homeDir });
+ return withOpenCodeInstallLocks(roots, lease => {
+ assertOpenCodeLeaseCoverage({ adapter, targetRoot, homeDir: context.homeDir }, lease);
+ // Discovery precedes acquisition. Never repair from that stale state.
+ record = buildDiscoveryRecord(adapter, context, record.legacyLayout === 'opencode'
+ ? getLegacyOpencodeLocation(context.homeDir) : null);
+ if (!record.exists || record.error) {
+ throw new Error(record.error || 'OpenCode install-state disappeared before repair.');
}
- removeLegacyAgentsFiles(migration, record.targetRoot);
- repairedPaths.push(...legacyAgentsMigrationPaths.filter(filePath => !fs.existsSync(filePath)));
- }
- const changedInstalledBytes = repairOperations.length > 0
- || needsOpencodeBuild
- || hasLegacyMigration;
- const statePreviewToWrite = changedInstalledBytes
- ? desiredPlan.statePreview
- : {
- ...desiredPlan.statePreview,
- installedAt: record.state.installedAt,
- source: { ...record.state.source },
- };
- writeRefreshedInstallState(record, statePreviewToWrite);
+ repairResult = performRepair(lease);
+ return repairResult;
+ });
+
- return {
- adapter: record.adapter,
- status: (repairOperations.length > 0 || needsOpencodeBuild || hasLegacyMigration)
- ? 'repaired'
- : 'ok',
- installStatePath: record.installStatePath,
- repairedPaths,
- plannedRepairs: [],
- stateRefreshed: true,
- warnings: desiredPlan.warnings,
- error: null
- };
} catch (error) {
- return {
- adapter: record.adapter,
- status: 'error',
- installStatePath: record.installStatePath,
- repairedPaths: [],
- plannedRepairs: [],
- error: error.message
- };
- } finally {
- if (releaseSettingsLock) releaseSettingsLock();
+ if (repairResult?.status === 'error') {
+ return { ...repairResult, releaseError: error.message };
+ }
+ return { adapter: record.adapter, status: 'error', installStatePath: record.installStatePath,
+ repairedPaths: repairResult?.repairedPaths || [], plannedRepairs: [], error: error.message };
}
});
@@@ -2443,6 -2544,6 +2563,7 @@@ module.exports =
buildDoctorReport,
discoverInstalledStates,
normalizeTargets,
++ removeContainedPath,
repairInstalledStates,
uninstallInstalledStates
};
diff --cc scripts/lib/install-targets/claude-home.js
index a07de2835,2de35ec58..0a6cfea44
--- a/scripts/lib/install-targets/claude-home.js
+++ b/scripts/lib/install-targets/claude-home.js
@@@ -1,8 -1,10 +1,9 @@@
const path = require('path');
const {
+ HOME_INSTALL_EXCLUDED_SOURCE_PATHS,
createInstallTargetAdapter,
createRemappedOperation,
- isForeignPlatformPath,
normalizeRelativePath,
planClaudeHooksOperations,
} = require('./helpers');
@@@ -66,7 -68,7 +67,9 @@@ module.exports = createInstallTargetAda
return modules.flatMap(module => {
const paths = Array.isArray(module.paths) ? module.paths : [];
return paths
- .filter(p => !isForeignPlatformPath(p, adapter.target) && !adapter.excludesSourcePath(p))
++
+ .filter(adapter.supportsSourcePath)
++
.flatMap(sourceRelativePath => {
if (
module.id === 'hooks-runtime'
diff --cc scripts/lib/install-targets/codex-home.js
index f2423ef68,aff32c4c5..1556a3b3e
--- a/scripts/lib/install-targets/codex-home.js
+++ b/scripts/lib/install-targets/codex-home.js
@@@ -7,5 -7,5 +7,7 @@@ module.exports = createInstallTargetAda
rootSegments: ['.codex'],
installStatePathSegments: ['ecc-install-state.json'],
nativeRootRelativePath: '.codex',
- excludedSourcePaths: ['.agents'],
++
+ excludedSourcePaths: HOME_INSTALL_EXCLUDED_SOURCE_PATHS,
++
});
diff --cc scripts/lib/install-targets/helpers.js
index 4a37b5fec,5df5ae1c4..38b8038a7
--- a/scripts/lib/install-targets/helpers.js
+++ b/scripts/lib/install-targets/helpers.js
@@@ -364,7 -367,9 +380,13 @@@ function createInstallTargetAdapter(con
strategy: adapter.determineStrategy(normalizedSourcePath),
});
},
++
+ supportsSourcePath,
++
+ excludesSourcePath(sourceRelativePath) {
+ return isExcludedSourcePath(sourceRelativePath, config.excludedSourcePaths);
+ },
++
planOperations(input = {}) {
if (typeof config.planOperations === 'function') {
return config.planOperations(input, adapter);
@@@ -374,7 -379,7 +396,9 @@@
return input.modules.flatMap(module => {
const paths = Array.isArray(module.paths) ? module.paths : [];
return paths
- .filter(supportsSourcePath)
++
+ .filter(p => !isForeignPlatformPath(p, config.target) && !adapter.excludesSourcePath(p))
++
.map(sourceRelativePath => adapter.createScaffoldOperation(
module.id,
sourceRelativePath,
@@@ -386,7 -391,7 +410,9 @@@
const module = input.module || {};
const paths = Array.isArray(module.paths) ? module.paths : [];
return paths
- .filter(supportsSourcePath)
++
+ .filter(p => !isForeignPlatformPath(p, config.target) && !adapter.excludesSourcePath(p))
++
.map(sourceRelativePath => adapter.createScaffoldOperation(
module.id,
sourceRelativePath,
diff --cc scripts/lib/install/apply.js
index 7ecc05fa0,209e53784..10c63e987
--- a/scripts/lib/install/apply.js
+++ b/scripts/lib/install/apply.js
@@@ -400,12 -687,10 +691,13 @@@ function prepareHookConsentMigration(pl
}
function previewInstallPlan(plan) {
+ assertOpenCodeHookDeactivationReady(plan);
const migration = prepareHookConsentMigration(
plan,
- prepareUserOwnedFileGuard(plan, prepareClaudeSkillMigration(plan))
+ prepareUserOwnedFileGuard(
+ plan,
+ prepareLegacyAgentsMigration(plan, prepareClaudeSkillMigration(plan))
+ )
);
const appliedPlan = {
...plan,
@@@ -456,11 -749,14 +756,16 @@@ function applyInstallPlanLocked(plan, d
if (typeof beforeInstallStateRead === 'function') {
beforeInstallStateRead({ plan });
}
- const migration = prepareHookConsentMigration(
+ assertOpenCodeLeaseCoverage(plan, dependencies.opencodeLease);
+ const legacyActivation = inspectLegacyOpenCodeDeactivation(plan);
+ const activationSnapshot = assertOpenCodeHookDeactivationReady(plan);
+ const migration = prepareExcludedPathsReconciliation(
plan,
- prepareUserOwnedFileGuard(
+ prepareHookConsentMigration(
plan,
- prepareLegacyAgentsMigration(plan, prepareClaudeSkillMigration(plan))
- prepareUserOwnedFileGuard(plan, prepareClaudeSkillMigration(plan))
++ prepareUserOwnedFileGuard(
++ plan, prepareLegacyAgentsMigration(plan, prepareClaudeSkillMigration(plan))
++ )
)
);
const appliedPlan = {
diff --cc scripts/lib/install/legacy-agents-migration.js
index 1e613da83,000000000..aac983c54
mode 100644,000000..100644
--- a/scripts/lib/install/legacy-agents-migration.js
+++ b/scripts/lib/install/legacy-agents-migration.js
@@@ -1,172 -1,0 +1,182 @@@
+'use strict';
+
+const crypto = require('crypto');
+const fs = require('fs');
+const path = require('path');
+
+const { readInstallState } = require('../install-state');
+const { assertWithinTrustedRoot } = require('../path-safety');
+
+const HOME_TARGET_IDS = new Set(['claude-home', 'codex-home']);
+
+function comparablePath(filePath) {
+ const resolvedPath = path.resolve(filePath);
+ return process.platform === 'win32' ? resolvedPath.toLowerCase() : resolvedPath;
+}
+
+function normalizeRelativePath(relativePath) {
+ return String(relativePath || '').replace(/\\/g, '/');
+}
+
+function isLegacyAgentsOperation(plan, operation) {
+ if (
+ !operation
+ || operation.kind !== 'copy-file'
+ || operation.ownership !== 'managed'
+ || typeof operation.destinationPath !== 'string'
+ ) {
+ return false;
+ }
+
+ const sourceRelativePath = normalizeRelativePath(operation.sourceRelativePath);
- if (!sourceRelativePath.startsWith('.agents/')) {
++ if (!sourceRelativePath.startsWith('.agents/')
++ || sourceRelativePath.split('/').some(segment => !segment || segment === '.' || segment === '..')) {
+ return false;
+ }
+
+ const expectedDestination = path.join(
+ plan.targetRoot,
+ ...sourceRelativePath.split('/')
+ );
+ return comparablePath(operation.destinationPath) === comparablePath(expectedDestination);
+}
+
+function inspectLegacyAgentsOperation(plan, operation) {
- assertWithinTrustedRoot(
- operation.destinationPath,
- plan.targetRoot,
- 'inspect legacy managed .agents file'
- );
++ try {
++ assertWithinTrustedRoot(
++ operation.destinationPath, plan.targetRoot, 'inspect legacy managed .agents file'
++ );
++ } catch (error) {
++ return { removable: false, warning: `Preserved unsafe legacy .agents path ${operation.destinationPath}: ${error.message}` };
++ }
+
+ let stat;
+ try {
+ stat = fs.lstatSync(operation.destinationPath);
+ } catch (error) {
+ if (error && error.code === 'ENOENT') {
+ return { removable: false, warning: null };
+ }
+ throw error;
+ }
+
+ if (!stat.isFile() || stat.isSymbolicLink()) {
+ return {
+ removable: false,
+ warning: `Preserved legacy .agents path ${operation.destinationPath}: it is not a regular file.`,
+ };
+ }
+
+ if (!/^[a-f0-9]{64}$/i.test(operation.contentSha256 || '')) {
+ return {
+ removable: false,
+ warning: `Preserved legacy .agents file ${operation.destinationPath}: install-state has no verified content digest.`,
+ };
+ }
+
+ const contentSha256 = crypto.createHash('sha256')
+ .update(fs.readFileSync(operation.destinationPath))
+ .digest('hex');
+ if (contentSha256 !== operation.contentSha256.toLowerCase()) {
+ return {
+ removable: false,
+ warning: `Preserved modified legacy .agents file ${operation.destinationPath} and released it from ECC management.`,
+ };
+ }
+
+ return { removable: true, warning: null };
+}
+
+function prepareLegacyAgentsMigration(plan, migration) {
+ if (!HOME_TARGET_IDS.has(plan && plan.adapter && plan.adapter.id)) {
+ return {
+ ...migration,
+ legacyAgentsOperationsToDetach: [],
+ legacyAgentsOperationsToRemove: [],
+ };
+ }
+
+ const previousState = fs.existsSync(plan.installStatePath)
+ ? readInstallState(plan.installStatePath)
+ : null;
+ const legacyOperations = ((previousState && previousState.operations) || [])
+ .filter(operation => isLegacyAgentsOperation(plan, operation));
+ if (legacyOperations.length === 0) {
+ return {
+ ...migration,
+ legacyAgentsOperationsToDetach: [],
+ legacyAgentsOperationsToRemove: [],
+ };
+ }
+
+ const inspections = legacyOperations.map(operation => ({
+ operation,
+ ...inspectLegacyAgentsOperation(plan, operation),
+ }));
+ const legacyDestinations = new Set(
+ legacyOperations.map(operation => comparablePath(operation.destinationPath))
+ );
+ const withoutLegacyAgents = state => ({
+ ...state,
+ operations: (state.operations || []).filter(operation => (
+ !legacyDestinations.has(comparablePath(operation.destinationPath))
+ )),
+ });
+
+ return {
+ ...migration,
+ finalState: withoutLegacyAgents(migration.finalState),
+ legacyAgentsOperationsToDetach: legacyOperations,
+ legacyAgentsOperationsToRemove: inspections
+ .filter(inspection => inspection.removable)
+ .map(inspection => inspection.operation),
+ requiresBridgeState: true,
+ warnings: [
+ ...(migration.warnings || []),
+ ...inspections.map(inspection => inspection.warning).filter(Boolean),
+ ],
+ };
+}
+
+function cleanupEmptyAgentsParents(filePath, targetRoot) {
+ const agentsRoot = path.join(targetRoot, '.agents');
+ let currentPath = path.dirname(filePath);
+
+ while (comparablePath(currentPath) !== comparablePath(targetRoot)) {
+ assertWithinTrustedRoot(currentPath, targetRoot, 'clean legacy managed .agents directory');
+ if (!fs.existsSync(currentPath) || fs.readdirSync(currentPath).length > 0) {
+ return;
+ }
+ fs.rmdirSync(currentPath);
+ if (comparablePath(currentPath) === comparablePath(agentsRoot)) {
+ return;
+ }
+ currentPath = path.dirname(currentPath);
+ }
+}
+
+function removeLegacyAgentsFiles(migration, targetRoot) {
- for (const operation of migration.legacyAgentsOperationsToRemove || []) {
- const latestInspection = inspectLegacyAgentsOperation(
- { targetRoot },
- operation
++ // Load lazily: lifecycle also uses this migration during repair.
++ const { removeContainedPath } = require('../install-lifecycle');
++ return (migration.legacyAgentsOperationsToRemove || []).flatMap(operation => {
++ const latestInspection = inspectLegacyAgentsOperation({ targetRoot }, operation);
++ if (!latestInspection.removable) return [];
++ const removedPath = removeContainedPath(
++ operation.destinationPath, targetRoot, 'remove legacy managed .agents file',
++ { force: true, verifyQuarantined: quarantinedPath => {
++ const stat = fs.lstatSync(quarantinedPath);
++ return stat.isFile() && !stat.isSymbolicLink()
++ && crypto.createHash('sha256').update(fs.readFileSync(quarantinedPath)).digest('hex')
++ === operation.contentSha256.toLowerCase();
++ } }
+ );
- if (!latestInspection.removable) {
- continue;
- }
- fs.rmSync(operation.destinationPath, { force: true });
- cleanupEmptyAgentsParents(operation.destinationPath, targetRoot);
- }
++ if (!removedPath) return [];
++ cleanupEmptyAgentsParents(removedPath, targetRoot);
++ return [removedPath];
++ });
+}
+
+module.exports = {
+ prepareLegacyAgentsMigration,
+ removeLegacyAgentsFiles,
+};
diff --cc tests/lib/legacy-agents-migration.test.js
index 000000000,000000000..41ed1e5c9
new file mode 100644
--- /dev/null
+++ b/tests/lib/legacy-agents-migration.test.js
@@@ -1,0 -1,0 +1,98 @@@
++'use strict';
++const assert = require('assert');
++const crypto = require('crypto');
++const fs = require('fs');
++const os = require('os');
++const path = require('path');
++const { test } = require('node:test');
++const { createInstallState } = require('../../scripts/lib/install-state');
++const { prepareLegacyAgentsMigration, removeLegacyAgentsFiles } = require('../../scripts/lib/install/legacy-agents-migration');
++function fixture(fn) {
++ const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-agents-migration-')));
++ try { fn(root); } finally { fs.rmSync(root, { recursive: true, force: true }); }
++}
++function prepare(root, source = '.agents/skills/demo.md', destination = path.join(root, source)) {
++ const operation = { moduleId: 'legacy', strategy: 'preserve-relative-path', scaffoldOnly: false, kind: 'copy-file', ownership: 'managed', sourceRelativePath: source,
++ destinationPath: destination, contentSha256: crypto.createHash('sha256').update('managed').digest('hex') };
++ const statePath = path.join(root, 'state.json');
++ fs.writeFileSync(statePath, JSON.stringify(createInstallState({ adapter: { id: 'codex-home' }, targetRoot: root, installStatePath: statePath, operations: [operation], request: {}, resolution: {}, source: { manifestVersion: 1 } })));
++ return prepareLegacyAgentsMigration({ adapter: { id: 'codex-home' }, targetRoot: root,
++ installStatePath: statePath }, { finalState: { operations: [operation] }, warnings: [] });
++}
++function write(file, content = 'managed') { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, content); }
++test('removes verified legacy files and returns actual removed paths', () => fixture(root => {
++ const file = path.join(root, '.agents/skills/demo.md'); write(file);
++ assert.deepStrictEqual(removeLegacyAgentsFiles(prepare(root), root), [file]);
++ assert.ok(!fs.existsSync(file));
++}));
++test('rejects dot and parent traversal without detaching unrelated files', () => fixture(root => {
++ for (const source of ['.agents/../settings.json', '.agents/./demo.md', '.agents/skills/../../settings.json']) {
++ const file = path.join(root, source); write(file);
++ const migration = prepare(root, source);
++ assert.strictEqual(migration.legacyAgentsOperationsToDetach.length, 0);
++ removeLegacyAgentsFiles(migration, root); assert.ok(fs.existsSync(file));
++ }
++}));
++test('unsafe ancestor produces warning and preserves outside content', () => fixture(root => {
++ const outside = path.join(root, 'outside'); write(path.join(outside, 'demo.md'));
++ const home = path.join(root, 'home'); fs.mkdirSync(home);
++ fs.symlinkSync(outside, path.join(home, '.agents'), 'dir');
++ const migration = prepare(home, '.agents/demo.md');
++ assert.strictEqual(migration.legacyAgentsOperationsToRemove.length, 0);
++ assert.ok(migration.warnings.length); assert.ok(fs.existsSync(path.join(outside, 'demo.md')));
++}));
++test('preserves content changed after preparation', () => fixture(root => {
++ const file = path.join(root, '.agents/skills/demo.md'); write(file);
++ const migration = prepare(root); fs.writeFileSync(file, 'changed');
++ assert.deepStrictEqual(removeLegacyAgentsFiles(migration, root), []);
++ assert.strictEqual(fs.readFileSync(file, 'utf8'), 'changed');
++}));
++test('quarantine identity check preserves replacement during ancestor swap', () => fixture(root => {
++ const file = path.join(root, '.agents/skills/demo.md'); write(file);
++ const migration = prepare(root); const outside = path.join(root, 'outside'); write(path.join(outside, 'demo.md'), 'user');
++ const rename = fs.renameSync; let swapped = false;
++ fs.renameSync = (source, destination) => {
++ if (source === file && !swapped) {
++ swapped = true; rename(path.dirname(file), path.join(root, 'saved-skills'));
++ fs.symlinkSync(outside, path.dirname(file), 'dir');
++ }
++ return rename(source, destination);
++ };
++ try { assert.throws(() => removeLegacyAgentsFiles(migration, root), /changed/); }
++ finally { fs.renameSync = rename; }
++ assert.strictEqual(fs.readFileSync(path.join(outside, 'demo.md'), 'utf8'), 'user');
++}));
++test('ignores non-home migrations and empty legacy state', () => fixture(root => {
++ const migration = { finalState: { operations: [] }, warnings: [] };
++ const result = prepareLegacyAgentsMigration({ adapter: { id: 'cursor-project' } }, migration);
++ assert.deepStrictEqual(removeLegacyAgentsFiles(result, root), []);
++ const empty = prepareLegacyAgentsMigration({ adapter: { id: 'codex-home' },
++ targetRoot: root, installStatePath: path.join(root, 'missing.json') }, migration);
++ assert.deepStrictEqual(empty.legacyAgentsOperationsToDetach, []);
++}));
++test('preserves missing, symbolic, modified and unverifiable legacy files', () => fixture(root => {
++ const file = path.join(root, '.agents/skills/demo.md');
++ assert.strictEqual(prepare(root).legacyAgentsOperationsToRemove.length, 0);
++ write(file, 'changed'); assert.ok(prepare(root).warnings.length);
++ fs.unlinkSync(file); write(path.join(root, 'user.md'));
++ fs.symlinkSync(path.join(root, 'user.md'), file);
++ assert.ok(prepare(root).warnings.length); fs.unlinkSync(file); write(file);
++ prepare(root);
++ const statePath = path.join(root, 'state.json');
++ const state = JSON.parse(fs.readFileSync(statePath, 'utf8'));
++ delete state.operations[0].contentSha256; fs.writeFileSync(statePath, JSON.stringify(state));
++ const migration = prepareLegacyAgentsMigration({ adapter: { id: 'codex-home' }, targetRoot: root,
++ installStatePath: statePath }, { finalState: state, warnings: [] });
++ assert.ok(migration.warnings[0].includes('no verified content digest'));
++}));
++test('digest revalidation preserves same-inode content changed during quarantine', () => fixture(root => {
++ const file = path.join(root, '.agents/skills/demo.md'); write(file);
++ const migration = prepare(root); const rename = fs.renameSync; let changed = false;
++ fs.renameSync = (source, destination) => {
++ if (source === file && !changed) { changed = true; fs.writeFileSync(source, 'changed during rename'); }
++ return rename(source, destination);
++ };
++ try { assert.throws(() => removeLegacyAgentsFiles(migration, root), /changed/); }
++ finally { fs.renameSync = rename; }
++ assert.strictEqual(fs.readFileSync(file, 'utf8'), 'changed during rename');
++}));