The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.
fix(opencode): preserve consent ownership through guarded install and repair
affaan-m923019d99f70
diff --cc scripts/lib/install-lifecycle.jsindex c50f29b88,7da0ae78a..8b8ce2ca7--- a/scripts/lib/install-lifecycle.js+++ b/scripts/lib/install-lifecycle.js@@@ -9,12 -9,9 +9,16 @@@ const { loadInstallManifests } = requirconst { readInstallState, validateInstallState } = require('./install-state');const { assertWithinTrustedRoot } = require('./path-safety');const { createInstallPlanFromRequest } = require('./install/runtime');+ const { assertNoNewUserOwnedFile, prepareUserOwnedFileGuard } = require('./install/ownership-guard');++const { writeFileNoFollow: guardedWriteFile } = require('./install/guarded-write');++const { withOpenCodeInstallLocks } = require('./install/opencode-install-lock');+ const { isCodexUserConfig } = require('./install/codex-user-config');-const { getRecordedHookConsent } = require('./install/hook-consent');+const {+ disableOpenCodeHookPluginRegistration,+ getDisabledOpenCodePluginContent,+ getRecordedHookConsent,+ withHookConsent,+} = require('./install/hook-consent');const {prepareClaudeSkillMigration,} = require('./install/claude-skill-migration');@@@ -459,66 -450,66 +463,15 @@@ function createChangedDestinationError();}--function getStableParentStat(filePath, action) {-- const parentStat = fs.lstatSync(path.dirname(filePath));-- if (!parentStat.isDirectory() || parentStat.isSymbolicLink()) {-- throw createChangedDestinationError(action);-- }-- return parentStat;--}----function assertPinnedWriteDestination(-- filePath,-- fileDescriptor,-- expectedParentStat,-- trustedRoot,-- action--) {-- const liveDestination = getManagedDestination(filePath, trustedRoot, action);-- if (path.resolve(liveDestination.managedPath) !== path.resolve(filePath)) {-- throw createChangedDestinationError(action);-- }---- const liveParentStat = getStableParentStat(filePath, action);-- if (!hasSameFileIdentity(expectedParentStat, liveParentStat)) {-- throw createChangedDestinationError(action);-- }---- const descriptorStat = fs.fstatSync(fileDescriptor);-- const livePathStat = fs.lstatSync(liveDestination.managedPath);-- if (-- !descriptorStat.isFile()-- || !livePathStat.isFile()-- || livePathStat.isSymbolicLink()-- || !hasSameFileIdentity(descriptorStat, livePathStat)-- ) {-- throw createChangedDestinationError(action);-- }--}----function writeFileNoFollow(filePath, content, mode, trustedRoot, action) {-- const expectedParentStat = getStableParentStat(filePath, action);-- const flags = fs.constants.O_WRONLY-- | fs.constants.O_CREAT-- | (fs.constants.O_NOFOLLOW || 0);-- const fileDescriptor = fs.openSync(filePath, flags, mode);---- try {-- assertPinnedWriteDestination(-- filePath,-- fileDescriptor,-- expectedParentStat,-- trustedRoot,-- action-- );-- fs.ftruncateSync(fileDescriptor, 0);-- fs.writeFileSync(fileDescriptor, content);-- if (mode !== undefined) {-- fs.fchmodSync(fileDescriptor, mode);-- }-- } finally {-- fs.closeSync(fileDescriptor);-- }++function writeFileNoFollow(filePath, content, mode, trustedRoot, action, writeOptions = {}) {++ return guardedWriteFile(filePath, content, {++ ...writeOptions,++ mode,++ action,++ validateDestination(destinationPath) {++ return getManagedDestination(destinationPath, trustedRoot, action).managedPath;++ },++ });}function readFileWithMetadataNoFollow(filePath, encoding) {@@@ -573,7 -564,7 +526,7 @@@ function assertClaudeSettingsDestinatioassertClaudeSettingsPath(operation.destinationPath, trustedRoot);}--function writeContainedFile(destinationPath, content, trustedRoot, action, mode) {++function writeContainedFile(destinationPath, content, trustedRoot, action, mode, writeOptions) {const preparedDestination = prepareContainedWriteDestination(destinationPath, trustedRoot, action);const finalDestination = getManagedDestination(preparedDestination,@@@ -585,7 -576,7 +538,8 @@@content,mode,trustedRoot,-- action++ action,++ writeOptions);return finalDestination;}@@@ -791,7 -782,7 +745,8 @@@ function executeRepairOperationtrustedRoot,linkIndex = null,target = null,-- settingsLockHeld = false++ settingsLockHeld = false,++ writeOptions = {}) {// Install-state is attacker-controllable; never write/delete outside the// adapter-derived trusted root, regardless of what the state file claims@@@ -809,7 -800,7 +764,8 @@@getExpectedCopyFileContent(operation, source.content, linkIndex),trustedRoot,'repair',-- source.mode & 0o777++ source.mode & 0o777,++ writeOptions);} else {copyContainedFile(sourcePath, operation.destinationPath, trustedRoot, 'repair');@@@ -1188,7 -1179,7 +1144,11 @@@ function inspectManagedOperation(repoRolet contentMatches;try {-- contentMatches = hasRecordedContentDigest(operation)++ // A deactivation transform changes the desired bytes. A historical++ // active-file digest proves ownership, not completion of that transition.++ const deactivatesOpenCode = operation.contentTransform === 'opencode-disable-ecc-hooks'++ || operation.contentTransform === 'opencode-disable-plugin-entrypoint';++ contentMatches = hasRecordedContentDigest(operation) && !deactivatesOpenCode? fileMatchesRecordedContent(inspectedPath, operation): operation.contentTransform || isMarkdownPath(operation.destinationPath)? readFileNoFollow(inspectedPath, 'utf8') === getExpectedCopyFileContent(@@@ -1902,6 -1881,19 +1862,22 @@@ function writeRefreshedInstallState(recif (!operation.destinationPath) {return { ...operation };}+ // Refreshing a ledger is not a file write. Keep the last installed digest- // for untouched shared configs so a concurrent user edit is never claimed.- if (isCodexUserConfig(record, operation)++ // for untouched shared configs and OpenCode activations so a concurrent++ // user edit is never claimed, even by a partial repair checkpoint.++ if ((isCodexUserConfig(record, operation)++ || (record.adapter.target === 'opencode'++ && require('./install/apply').getOpenCodeActivationKind(record, operation)))+ && !writtenPaths.some(writtenPath => path.relative(writtenPath, operation.destinationPath) === '')) {+ const previousOperation = (record.state.operations || []).find(previous => (+ previous.destinationPath+ && path.relative(previous.destinationPath, operation.destinationPath) === ''+ ));+ const { contentSha256: _plannedDigest, ...operationWithoutDigest } = operation;+ return previousOperation && previousOperation.contentSha256+ ? { ...operationWithoutDigest, contentSha256: previousOperation.contentSha256 }+ : operationWithoutDigest;+ }try {const contentSha256 = crypto.createHash('sha256').update(readFileNoFollow(operation.destinationPath))@@@ -1931,10 -1923,10 +1907,13 @@@ function prepareRepairMigration(plan, rinstallStatePath: record.installStatePath,statePreview: buildAdapterDerivedStatePreview(plan.statePreview, record),};- const skillMigration = prepareClaudeSkillMigration(trustedPlan);- const migration = record.adapter.id === 'codex-home'- ? prepareUserOwnedFileGuard(trustedPlan, skillMigration)- : skillMigration;+ const initialMigration = prepareClaudeSkillMigration(trustedPlan);- const migration = trustedPlan.target === 'opencode'- ? require('./install/apply').prepareHookConsentMigration(trustedPlan, initialMigration)++ 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: {@@@ -2015,105 -1965,103 +1994,157 @@@ function repairInstalledStates(options&& (!record.legacy || record.legacyLayout === 'opencode')));-- const results = records.map(record => {-- if (record.error) {-- return {-- adapter: record.adapter,-- status: 'error',-- installStatePath: record.installStatePath,-- repairedPaths: [],-- plannedRepairs: [],-- error: record.error-- };-- }---- let releaseSettingsLock = null;-- try {- preflightOpenCodeHookDeactivation(record, context);-- const settingsPathToLock = !options.dryRun-- && getManagedOperations(record.state || {}).some(-- operation => operation.kind === 'update-claude-settings'-- )-- ? getClaudeSettingsPath(record.targetRoot)-- : null;-- if (settingsPathToLock) {-- releaseSettingsLock = acquireSettingsLock(settingsPathToLock);++ const results = records.map(initialRecord => {++ let record = initialRecord;++ const performRepair = (opencodeLease) => {++ if (record.error) {++ return {++ adapter: record.adapter,++ status: 'error',++ installStatePath: record.installStatePath,++ repairedPaths: [],++ plannedRepairs: [],++ error: record.error++ };}-- const needsOpencodeBuild = record.adapter.target === 'opencode'-- && hasOpencodeBuildError(getOpencodeBuildValidationIssues(context));-- const opencodeBuildRepairPath = path.join(context.repoRoot, OPENCODE_BUILD_ARTIFACT);-- if (record.legacyLayout === 'opencode') {-- if (needsOpencodeBuild && !options.dryRun) {-- try {-- buildOpencodeRunner(context.repoRoot);-- } catch (error) {++ let releaseSettingsLock = null;++ try {++ preflightOpenCodeHookDeactivation(record, context);++ const settingsPathToLock = !options.dryRun++ && getManagedOperations(record.state || {}).some(++ operation => operation.kind === 'update-claude-settings'++ )++ ? getClaudeSettingsPath(record.targetRoot)++ : null;++ if (settingsPathToLock) {++ releaseSettingsLock = acquireSettingsLock(settingsPathToLock);++ }++ const needsOpencodeBuild = record.adapter.target === 'opencode'++ && hasOpencodeBuildError(getOpencodeBuildValidationIssues(context));++ const opencodeBuildRepairPath = path.join(context.repoRoot, OPENCODE_BUILD_ARTIFACT);++++ if (record.legacyLayout === 'opencode') {++ if (needsOpencodeBuild && !options.dryRun) {++ try {++ buildOpencodeRunner(context.repoRoot);++ } catch (error) {++ return {++ adapter: record.adapter,++ status: 'error',++ installStatePath: record.installStatePath,++ repairedPaths: [],++ plannedRepairs: [],++ error: formatBuildErrorMessage(error),++ };++ }++ }++++ const canonicalPlan = createRepairPlanFromRecord(record, context, {++ exemptValidationCodes: options.dryRun && needsOpencodeBuild++ ? [OPENCODE_PLUGIN_NOT_BUILT_CODE]++ : [],++ });++ assertOpenCodeRepairHookDeactivation(canonicalPlan);++ const plannedRepairs = [...new Set([++ ...(needsOpencodeBuild ? [opencodeBuildRepairPath] : []),++ ...canonicalPlan.operations.map(operation => operation.destinationPath),++ ...getManagedOperations(record.state).map(operation => operation.destinationPath),++ record.installStatePath,++ ])];++++ if (options.dryRun) {return {adapter: record.adapter,-- status: 'error',-- installStatePath: record.installStatePath,++ status: 'planned',++ installStatePath: canonicalPlan.installStatePath,repairedPaths: [],-- plannedRepairs: [],-- error: formatBuildErrorMessage(error),++ plannedRepairs,++ stateRefreshed: false,++ warnings: canonicalPlan.warnings,++ error: null,};}++++ // Load lazily to avoid a module cycle during install-lifecycle startup.++ const { applyInstallPlan } = require('./install/apply');++ const appliedPlan = applyInstallPlan(canonicalPlan, { opencodeLease });++ return {++ adapter: record.adapter,++ status: 'repaired',++ installStatePath: canonicalPlan.installStatePath,++ repairedPaths: [++ ...(needsOpencodeBuild ? [opencodeBuildRepairPath] : []),++ ...canonicalPlan.operations.map(operation => operation.destinationPath),++ ],++ plannedRepairs: [],++ stateRefreshed: true,++ warnings: appliedPlan.warnings,++ error: null,++ };}-- const canonicalPlan = createRepairPlanFromRecord(record, context, {-- exemptValidationCodes: options.dryRun && needsOpencodeBuild-- ? [OPENCODE_PLUGIN_NOT_BUILT_CODE]-- : [],-- });- assertOpenCodeRepairHookDeactivation(canonicalPlan);-- const plannedRepairs = [...new Set([-- ...(needsOpencodeBuild ? [opencodeBuildRepairPath] : []),-- ...canonicalPlan.operations.map(operation => operation.destinationPath),-- ...getManagedOperations(record.state).map(operation => operation.destinationPath),-- record.installStatePath,-- ])];++ if (needsOpencodeBuild && options.dryRun) {++ const rawPlan = createRepairPlanFromRecord(record, context, {++ exemptValidationCodes: [OPENCODE_PLUGIN_NOT_BUILT_CODE],++ });++ const { plan: desiredPlan } = prepareRepairMigration(rawPlan, record);++ const operationHealth = summarizeManagedOperationHealth(++ context.repoRoot,++ record.targetRoot,++ desiredPlan.operations,++ record.adapter.target++ );++ const unsafeOperationResult = getUnsafeOperationResult(++ record,++ operationHealth++ );++ if (unsafeOperationResult) {++ return unsafeOperationResult;++ }++ const repairOperations = [...operationHealth.missing.map(entry => ({ ...entry.operation })), ...operationHealth.drifted.map(entry => ({ ...entry.operation }))];++ const plannedRepairs = [opencodeBuildRepairPath, ...repairOperations.map(operation => operation.destinationPath)];-- if (options.dryRun) {return {adapter: record.adapter,status: 'planned',-- installStatePath: canonicalPlan.installStatePath,++ installStatePath: record.installStatePath,repairedPaths: [],plannedRepairs,stateRefreshed: false,-- warnings: canonicalPlan.warnings,-- error: null,++ warnings: desiredPlan.warnings,++ error: null};}-- // Load lazily to avoid a module cycle during install-lifecycle startup.-- const { applyInstallPlan } = require('./install/apply');-- const appliedPlan = applyInstallPlan(canonicalPlan);-- return {-- adapter: record.adapter,-- status: 'repaired',-- installStatePath: canonicalPlan.installStatePath,-- repairedPaths: [-- ...(needsOpencodeBuild ? [opencodeBuildRepairPath] : []),-- ...canonicalPlan.operations.map(operation => operation.destinationPath),-- ],-- plannedRepairs: [],-- stateRefreshed: true,-- warnings: appliedPlan.warnings,-- error: null,-- };-- }++ if (needsOpencodeBuild) {++ try {++ buildOpencodeRunner(context.repoRoot);++ } catch (error) {++ return {++ adapter: record.adapter,++ status: 'error',++ installStatePath: record.installStatePath,++ repairedPaths: [],++ plannedRepairs: [],++ error: formatBuildErrorMessage(error)++ };++ }++ }-- if (needsOpencodeBuild && options.dryRun) {-- const rawPlan = createRepairPlanFromRecord(record, context, {-- exemptValidationCodes: [OPENCODE_PLUGIN_NOT_BUILT_CODE],-- });-- const { plan: desiredPlan } = prepareRepairMigration(rawPlan, record);++ const rawPlan = createRepairPlanFromRecord(record, context);++ const {++ migration,++ plan: desiredPlan,++ } = prepareRepairMigration(rawPlan, record);++ const activationSnapshot = assertOpenCodeRepairHookDeactivation(desiredPlan);const operationHealth = summarizeManagedOperationHealth(context.repoRoot,record.targetRoot,desiredPlan.operations,record.adapter.target);++const unsafeOperationResult = getUnsafeOperationResult(record,operationHealth@@@ -2121,186 -2069,175 +2152,168 @@@if (unsafeOperationResult) {return unsafeOperationResult;}-- const repairOperations = [...operationHealth.missing.map(entry => ({ ...entry.operation })), ...operationHealth.drifted.map(entry => ({ ...entry.operation }))];-- const plannedRepairs = [opencodeBuildRepairPath, ...repairOperations.map(operation => operation.destinationPath)];-- return {-- adapter: record.adapter,-- status: 'planned',-- installStatePath: record.installStatePath,-- repairedPaths: [],-- plannedRepairs,-- stateRefreshed: false,-- warnings: desiredPlan.warnings,-- error: null-- };-- }---- if (needsOpencodeBuild) {-- try {-- buildOpencodeRunner(context.repoRoot);-- } catch (error) {++ if (operationHealth.missingSource.length > 0) {return {adapter: record.adapter,status: 'error',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 activationSnapshot = assertOpenCodeRepairHookDeactivation(desiredPlan);-- 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 plannedRepairs = [...new Set([++ ...(needsOpencodeBuild ? [opencodeBuildRepairPath] : []),++ ...repairOperations.map(operation => operation.destinationPath),++ ...legacyMigrationPaths,++ ])];-- 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 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 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);-- if (operationHealth.missingSource.length > 0) {return {adapter: record.adapter,-- status: 'error',++ status: (repairOperations.length > 0 || needsOpencodeBuild || hasLegacyMigration)++ ? 'repaired'++ : 'ok',installStatePath: record.installStatePath,-- repairedPaths: [],++ repairedPaths,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 plannedRepairs = [...new Set([-- ...(needsOpencodeBuild ? [opencodeBuildRepairPath] : []),-- ...repairOperations.map(operation => operation.destinationPath),-- ...legacyMigrationPaths,-- ])];---- 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;-- 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)-- );-- 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 } = require('./install/apply');++ const roots = getOpenCodeInstallRoots({ adapter, targetRoot, homeDir: context.homeDir });++ return withOpenCodeInstallLocks(roots, 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.');}-- }-- 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);- writeRefreshedInstallState(record, statePreviewToWrite, repairedPaths);---- return {-- adapter: record.adapter,-- status: (repairOperations.length > 0 || needsOpencodeBuild || hasLegacyMigration)-- ? 'repaired'-- : 'ok',-- installStatePath: record.installStatePath,-- repairedPaths,-- plannedRepairs: [],-- stateRefreshed: true,-- warnings: desiredPlan.warnings,-- error: null-- };++ repairResult = performRepair(lease);++ return repairResult;++ });} 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 };}});diff --cc scripts/lib/install/apply.jsindex f41cd4806,1776cb6ca..0f8b27f51--- a/scripts/lib/install/apply.js+++ b/scripts/lib/install/apply.js@@@ -42,7 -33,11 +42,13 @@@ constprepareUserOwnedFileGuard,preserveUnwrittenFiles,} = require('./ownership-guard');--const { cleanupLegacyOpencodeInstall } = require('./opencode-legacy-migration');++const { cleanupLegacyOpencodeInstall, getLegacyLocationForPlan } = require('./opencode-legacy-migration');++const { writeFileNoFollow } = require('./guarded-write');++const { withOpenCodeInstallLocks } = require('./opencode-install-lock');+ const {+ completeExcludedPathsReconciliation,+ prepareExcludedPathsReconciliation,+ } = require('./excluded-paths-reconciliation');const { buildInstallIndex, rewriteRelativeLinks } = require('./link-rewrite');const { adaptAntigravityAgent } = require('./antigravity-agent');@@@ -303,117 -292,6 +309,140 @@@ function comparablePath(filePath)return process.platform === 'win32' ? resolved.toLowerCase() : resolved;}- function openCodeActivationKind(plan, operation) {++function getOpenCodeActivationKind(plan, operation) {+ const relative = operation.destinationPath+ ? path.relative(plan.targetRoot, operation.destinationPath).split(path.sep).join('/').toLowerCase()+ : '';+ if (/^plugins\/(?:[^/]+\.(?:[cm]?js|ts)|[^/]+\/(?:index\.(?:[cm]?js|ts)|package\.json))$/.test(relative)) {+ return 'plugin';+ }+ if (relative === 'opencode.json') return 'config';+ if (isOpenCodePluginEntrypoint(operation)) return 'plugin';+ return isOpenCodeHookActivationOperation(operation) ? 'config' : null;+}++function openCodeActivationCandidates(plan, previousOperations) {+ const candidates = new Map();+ for (const operation of [...previousOperations, ...plan.operations]) {- if (openCodeActivationKind(plan, operation) && operation.destinationPath) {++ if (getOpenCodeActivationKind(plan, operation) && operation.destinationPath) {+ candidates.set(comparablePath(operation.destinationPath), operation);+ }+ }+ // Old installs can leave aliases that are absent from the new source tree.+ // Inspect only ECC's known entrypoint names, never unrelated user plugins.+ for (const name of ['ecc-hooks', 'index']) {+ for (const extension of ['ts', 'js', 'mjs', 'cjs']) {+ const destinationPath = path.join(plan.targetRoot, 'plugins', `${name}.${extension}`);+ const key = comparablePath(destinationPath);+ if (!candidates.has(key)) {+ candidates.set(key, {+ sourceRelativePath: `.opencode/plugins/${name}.${extension}`,+ destinationPath,+ });+ }+ }+ }+ return candidates;+}++function activationIsInactive(kind, operation, content) {+ if (kind === 'plugin') {+ return content.toString('utf8') === getDisabledOpenCodePluginContent();+ }- const config = JSON.parse(content.toString('utf8'));- // Validate the shape through the same transformer used by installation.- disableOpenCodeHookPluginRegistration(content.toString('utf8'), operation.sourceRelativePath);++ const text = content.toString('utf8');++ // Validate first so malformed JSON retains its source context.++ disableOpenCodeHookPluginRegistration(text, operation.sourceRelativePath || operation.destinationPath);++ const config = JSON.parse(text);+ return !Array.isArray(config.plugin) || !config.plugin.includes('./plugins');+}++function assertOpenCodeHookDeactivationReady(plan, options = {}) {+ if (!shouldDisableOpenCodeHooks(plan)) {+ return new Map();+ }+ assertSafeInstallOperation(plan, { destinationPath: plan.installStatePath });+ const previousState = readPreviousInstallState(plan);+ if (previousState && (+ previousState.target.id !== plan.adapter.id+ || comparablePath(previousState.target.root) !== comparablePath(plan.targetRoot)+ || comparablePath(previousState.target.installStatePath) !== comparablePath(plan.installStatePath)+ )) {+ throw new Error('Refusing OpenCode hook deactivation: install-state target mismatch.');+ }+ const previous = new Map(((previousState && previousState.operations) || [])+ .filter(operation => operation.ownership === 'managed' && operation.destinationPath)+ .map(operation => [comparablePath(operation.destinationPath), operation]));- const desired = new Map(plan.operations.filter(operation => openCodeActivationKind(plan, operation))++ const desired = new Map(plan.operations.filter(operation => getOpenCodeActivationKind(plan, operation))+ .map(operation => [comparablePath(operation.destinationPath), operation]));+ const snapshot = new Map();+ for (const [key, operation] of openCodeActivationCandidates(plan, [...previous.values()])) {- const kind = openCodeActivationKind(plan, operation);++ const kind = getOpenCodeActivationKind(plan, operation);+ const expectedTransform = kind === 'plugin'+ ? 'opencode-disable-plugin-entrypoint' : 'opencode-disable-ecc-hooks';+ const replacement = desired.get(key);+ // Validate planned activation even when its destination does not yet exist.+ // Recorded operations may name an unrelated source or use render-template.+ if (replacement && (replacement.kind !== 'copy-file'+ || replacement.contentTransform !== expectedTransform)) {+ throw new Error(`Refusing OpenCode hook deactivation: unsupported activation operation at ${operation.destinationPath}`);+ }+ const content = readInstalledFileNoFollow(plan, operation);+ if (content === null && fs.existsSync(operation.destinationPath)) {+ throw new Error(`Refusing OpenCode hook deactivation: non-file activation at ${operation.destinationPath}`);+ }+ const digest = content === null ? null : crypto.createHash('sha256').update(content).digest('hex');+ snapshot.set(key, digest);+ if (content === null) continue;+ const inactive = activationIsInactive(kind, operation, content);+ if (options.requireInactive) {+ if (!inactive) {+ throw new Error(`OpenCode hook activation remains active at ${operation.destinationPath}`);+ }+ continue;+ }+ if (kind === 'plugin' && inactive) continue;+ const recorded = previous.get(key);+ if (!replacement || replacement.kind !== 'copy-file'+ || replacement.contentTransform !== expectedTransform+ || !recorded || recorded.contentSha256 !== digest) {+ throw new Error(`Refusing OpenCode hook deactivation: user-owned, modified, unverifiable or stale activation at ${operation.destinationPath}`);+ }+ }+ return snapshot;+}++function assertOpenCodeActivationUnchanged(plan, operation, snapshot) {+ const key = comparablePath(operation.destinationPath);+ if (!snapshot.has(key)) return;+ const content = readInstalledFileNoFollow(plan, operation);+ const digest = content === null ? null : crypto.createHash('sha256').update(content).digest('hex');+ if (digest !== snapshot.get(key)) {+ throw new Error(`Refusing OpenCode hook deactivation: activation changed after preflight at ${operation.destinationPath}`);+ }+}+++function getOpenCodeActivationWriteOptions(operation, snapshot) {++ const key = comparablePath(operation.destinationPath);++ if (!snapshot.has(key)) return {};++ const digest = snapshot.get(key);++ return { expectedContent: Object.freeze(digest === null++ ? { kind: 'absent' } : { kind: 'sha256', digest }) };++}++++function getOpenCodeInstallRoots(plan) {++ const roots = [plan.targetRoot];++ const legacy = getLegacyLocationForPlan(plan);++ if (legacy) {++ try {++ fs.lstatSync(legacy.targetRoot);++ roots.push(legacy.targetRoot);++ } catch (error) {++ if (error.code !== 'ENOENT') throw error;++ }++ }++ return roots;++}++function findPreviousManagedHooks(previousState, plan, operation) {if (!previousState@@@ -573,6 -429,6 +602,14 @@@ function previewInstallPlan(plan)function applyInstallPlan(plan, dependencies = {}) {assertHookConsentReady(plan);++ if (plan.adapter?.target === 'opencode') {++ assertSafeInstallOperation(plan, { destinationPath: plan.installStatePath });++ return withOpenCodeInstallLocks(++ getOpenCodeInstallRoots(plan),++ () => applyInstallPlanLocked(plan, dependencies, false),++ dependencies.opencodeLease++ );++ }const isClaudeManualTarget = plan.adapter&& (plan.adapter.target === 'claude' || plan.adapter.target === 'claude-project');const settingsPathToLock = isClaudeManualTarget@@@ -597,10 -453,12 +634,13 @@@ function applyInstallPlanLocked(plan, dif (typeof beforeInstallStateRead === 'function') {beforeInstallStateRead({ plan });}+ const activationSnapshot = assertOpenCodeHookDeactivationReady(plan);- const migration = prepareHookConsentMigration(+ const migration = prepareExcludedPathsReconciliation(plan,- prepareUserOwnedFileGuard(plan, prepareClaudeSkillMigration(plan))+ prepareHookConsentMigration(+ plan,+ prepareUserOwnedFileGuard(plan, prepareClaudeSkillMigration(plan))+ ));const appliedPlan = {...plan,@@@ -640,8 -498,7 +680,8 @@@if (typeof beforeOperationWrite === 'function') {beforeOperationWrite({ plan: appliedPlan, operation });}- assertNoNewUserOwnedFile(migration, operation);+ assertNoNewUserOwnedFile(migration, operation, appliedPlan);+ assertOpenCodeActivationUnchanged(appliedPlan, operation, activationSnapshot);if (operation.kind === 'update-claude-settings'@@@ -728,7 -585,7 +768,20 @@@index: linkIndex,}): transformed;-- fs.writeFileSync(operation.destinationPath, installedContent, 'utf8');++ const writeOptions = getOpenCodeActivationWriteOptions(operation, activationSnapshot);++ if (writeOptions.expectedContent) {++ writeFileNoFollow(operation.destinationPath, installedContent, {++ ...writeOptions,++ action: 'install OpenCode activation',++ validateDestination(destinationPath) {++ assertSafeInstallOperation(appliedPlan, { destinationPath });++ assertSafeClaudeSkillOperation(appliedPlan, { destinationPath });++ return destinationPath;++ },++ });++ } else {++ fs.writeFileSync(operation.destinationPath, installedContent, 'utf8');++ }writtenDestinations.add(operation.destinationPath);continue;}@@@ -835,9 -705,6 +902,12 @@@module.exports = {applyInstallPlan,+ assertOpenCodeActivationUnchanged,+ assertOpenCodeHookDeactivationReady,++ getOpenCodeActivationKind,++ getOpenCodeActivationWriteOptions,++ getOpenCodeInstallRoots,assertSafeInstallOperation,+ prepareHookConsentMigration,previewInstallPlan,};diff --cc scripts/lib/install/claude-settings-lock.jsindex 75aa6a4f0,75aa6a4f0..164e887ec--- a/scripts/lib/install/claude-settings-lock.js+++ b/scripts/lib/install/claude-settings-lock.js@@@ -5,6 -5,6 +5,7 @@@ const fs = require('fs')const path = require('path');const INVALID_LOCK_STALE_MS = 5 * 60 * 1000;++const acquiredLockIdentities = new WeakMap();function sameFileIdentity(left, right) {if (left.ino !== right.ino) {@@@ -19,7 -19,7 +20,7 @@@return left.dev === right.dev;}--function createSettingsLock(lockPath) {++function createSettingsLock(lockPath, label = 'Claude settings') {const tempPath = `${lockPath}.create-${process.pid}-${crypto.randomBytes(8).toString('hex')}`;let descriptor;let ownedStats;@@@ -43,18 -43,18 +44,28 @@@fs.rmSync(tempPath, { force: true });let released = false;-- return () => {++ const release = () => {if (released) return;const quarantinePath = `${lockPath}.release-${process.pid}-${crypto.randomBytes(8).toString('hex')}`;fs.renameSync(lockPath, quarantinePath);const quarantinedStats = fs.lstatSync(quarantinePath, { bigint: true });if (!sameFileIdentity(quarantinedStats, ownedStats)) {if (!fs.existsSync(lockPath)) fs.renameSync(quarantinePath, lockPath);-- throw new Error(`Refusing to release a changed Claude settings lock: ${lockPath}`);++ throw new Error(`Refusing to release a changed ${label} lock: ${lockPath}`);}released = true;fs.rmSync(quarantinePath, { force: true });};++ // Retain the identity observed through the creation descriptor. A pathname++ // sampled after publication may already refer to a replacement lock.++ acquiredLockIdentities.set(release, Object.freeze({ dev: ownedStats.dev, ino: ownedStats.ino }));++ return release;++}++++function getSettingsLockIdentity(release) {++ const identity = acquiredLockIdentities.get(release);++ if (!identity) throw new Error('No acquired settings lock identity for this release function.');++ return identity;}function inspectSettingsLock(lockPath) {@@@ -91,7 -91,7 +102,7 @@@ function processIsAlive(pid)}}--function recoverSettingsLock(lockPath) {++function recoverSettingsLock(lockPath, label = 'Claude settings') {const recoveryPath = `${lockPath}.recover`;try {fs.mkdirSync(recoveryPath, { mode: 0o700 });@@@ -106,7 -106,7 +117,7 @@@try {inspected = inspectSettingsLock(lockPath);} catch (error) {-- if (error && error.code === 'ENOENT') return createSettingsLock(lockPath);++ if (error && error.code === 'ENOENT') return createSettingsLock(lockPath, label);throw error;}const validOwner = Number.isSafeInteger(inspected.metadata && inspected.metadata.pid)@@@ -123,27 -123,27 +134,27 @@@return null;}fs.rmSync(quarantinePath, { force: true });-- return createSettingsLock(lockPath);++ return createSettingsLock(lockPath, label);} finally {fs.rmSync(recoveryPath, { recursive: true, force: true });fs.rmSync(quarantinePath, { force: true });}}--function acquireSettingsLock(settingsPath) {++function acquireSettingsLock(settingsPath, { label = 'Claude settings' } = {}) {const lockPath = `${settingsPath}.ecc.lock`;fs.mkdirSync(path.dirname(settingsPath), { recursive: true });try {-- return createSettingsLock(lockPath);++ return createSettingsLock(lockPath, label);} catch (error) {if (!error || error.code !== 'EEXIST') {throw error;}}-- const recovered = recoverSettingsLock(lockPath);++ const recovered = recoverSettingsLock(lockPath, label);if (recovered) return recovered;throw new Error(-- `Another ECC process is updating Claude settings: ${settingsPath}. `++ `Another ECC process is updating ${label}: ${settingsPath}. `+ `If no ECC process is active, inspect and remove ${lockPath}.`);}@@@ -175,6 -175,6 +186,7 @@@ function runWithSettingsLock(settingsPamodule.exports = {acquireSettingsLock,++ getSettingsLockIdentity,runWithSettingsLock,sameFileIdentity,};diff --cc scripts/lib/install/guarded-write.jsindex 000000000,000000000..ac654f6f9new file mode 100644--- /dev/null+++ b/scripts/lib/install/guarded-write.js@@@ -1,0 -1,0 +1,115 @@@++'use strict';++++const crypto = require('crypto');++const fs = require('fs');++const path = require('path');++const { sameFileIdentity } = require('./claude-settings-lock');++++function snapshotExpectedContent(expectedContent) {++ if (expectedContent === undefined) return undefined;++ if (expectedContent && expectedContent.kind === 'absent') {++ return Object.freeze({ kind: 'absent' });++ }++ if (expectedContent && expectedContent.kind === 'sha256'++ && typeof expectedContent.digest === 'string' && /^[a-f0-9]{64}$/i.test(expectedContent.digest)) {++ return Object.freeze({ kind: 'sha256', digest: expectedContent.digest.toLowerCase() });++ }++ throw new TypeError('Invalid expectedContent for guarded write.');++}++++function changedDestination(action, filePath, expectedContent, cause) {++ const message = expectedContent++ ? `Refusing OpenCode hook deactivation: activation changed after preflight at ${filePath}`++ : `Refusing to ${action}: managed destination changed during the write.`;++ const error = new Error(message);++ if (cause) {++ error.cause = cause;++ if (cause.code) error.code = cause.code;++ }++ return error;++}++++function writeFileNoFollow(filePath, content, {++ mode,++ action = 'write managed file',++ validateDestination,++ expectedContent: requestedContent,++} = {}) {++ if (typeof validateDestination !== 'function') {++ throw new TypeError('writeFileNoFollow requires validateDestination.');++ }++ const destination = path.resolve(filePath);++ const expectedContent = snapshotExpectedContent(requestedContent);++ const bytes = typeof content === 'string' ? Buffer.from(content) : content;++ if (!Buffer.isBuffer(bytes)) throw new TypeError('Managed file content must be a string or Buffer.');++ const changed = cause => changedDestination(action, destination, expectedContent, cause);++ function validatePath() {++ const validated = validateDestination(destination);++ if (typeof validated !== 'string' || path.resolve(validated) !== destination) throw changed();++ }++ function parentStats() {++ const stats = fs.lstatSync(path.dirname(destination), { bigint: true });++ if (!stats.isDirectory() || stats.isSymbolicLink()) throw changed();++ return stats;++ }++ validatePath();++ const parent = parentStats();++ const flags = (expectedContent ? fs.constants.O_RDWR : fs.constants.O_WRONLY)++ | (!expectedContent || expectedContent.kind === 'absent' ? fs.constants.O_CREAT : 0)++ | (expectedContent && expectedContent.kind === 'absent' ? fs.constants.O_EXCL : 0)++ | (fs.constants.O_NOFOLLOW || 0);++ let descriptor;++ try {++ descriptor = fs.openSync(destination, flags, mode);++ } catch (error) {++ if (expectedContent) throw changed(error);++ throw error;++ }++ function assertPinned() {++ validatePath();++ const descriptorStat = fs.fstatSync(descriptor, { bigint: true });++ const liveStat = fs.lstatSync(destination, { bigint: true });++ if (!sameFileIdentity(parent, parentStats()) || !descriptorStat.isFile()++ || !liveStat.isFile() || liveStat.isSymbolicLink() || !sameFileIdentity(descriptorStat, liveStat)) {++ throw changed();++ }++ return descriptorStat;++ }++ let primaryError;++ try {++ const before = assertPinned();++ if (expectedContent && expectedContent.kind === 'absent' && before.size !== 0n) throw changed();++ if (expectedContent && expectedContent.kind === 'sha256') {++ const digest = crypto.createHash('sha256').update(fs.readFileSync(descriptor)).digest('hex');++ const after = assertPinned();++ if (!sameFileIdentity(before, after) || before.size !== after.size++ || before.mtimeNs !== after.mtimeNs || before.ctimeNs !== after.ctimeNs++ || digest !== expectedContent.digest) throw changed();++ }++ // Observed changes are rejected before truncation. This is not a CAS against++ // arbitrary editors: callers coordinate participating writers with a lease.++ fs.ftruncateSync(descriptor, 0);++ for (let offset = 0; offset < bytes.length;) {++ const written = fs.writeSync(descriptor, bytes, offset, bytes.length - offset, offset);++ if (!Number.isInteger(written) || written <= 0 || written > bytes.length - offset) {++ throw new Error(`Refusing to ${action}: file write made no valid progress.`);++ }++ offset += written;++ }++ if (mode !== undefined) fs.fchmodSync(descriptor, mode);++ } catch (error) {++ primaryError = error;++ } finally {++ try {++ fs.closeSync(descriptor);++ } catch (error) {++ if (primaryError) primaryError.closeError = error;++ else primaryError = error;++ }++ }++ // An exclusive creation that later fails is not unlinked: the pathname may++ // already belong to another writer. Keep the refusal visible to the caller.++ if (primaryError) throw primaryError;++}++++module.exports = { writeFileNoFollow };diff --cc scripts/lib/install/opencode-install-lock.jsindex 000000000,000000000..8b80e0b5cnew file mode 100644--- /dev/null+++ b/scripts/lib/install/opencode-install-lock.js@@@ -1,0 -1,0 +1,128 @@@++'use strict';++++const fs = require('fs');++const path = require('path');++const { realpathNearestExisting } = require('../path-safety');++const { acquireSettingsLock, getSettingsLockIdentity, sameFileIdentity } = require('./claude-settings-lock');++++const activeLeases = new WeakMap();++const STATE_FILENAME = 'ecc-install-state.json';++const comparablePath = value => process.platform === 'win32' ? value.toLowerCase() : value;++++function inspectEntry(filePath) {++ try { return fs.lstatSync(filePath, { bigint: true }); }++ catch (error) { if (error.code === 'ENOENT') return null; throw error; }++}++++function canonicalRoots(roots) {++ if (!Array.isArray(roots)) throw new TypeError('OpenCode install roots must be an array.');++ const deduplicated = new Map();++ for (const root of roots) {++ if (typeof root !== 'string' || !path.isAbsolute(root)) {++ throw new TypeError('OpenCode install root must be an absolute trusted path.');++ }++ const stats = inspectEntry(root);++ if (stats && (stats.isSymbolicLink() || !stats.isDirectory())) {++ throw new Error(`Refusing OpenCode install lock through a non-directory or symlink root: ${root}`);++ }++ const canonical = realpathNearestExisting(root);++ deduplicated.set(comparablePath(canonical), canonical);++ }++ return [...deduplicated.values()].sort((left, right) => {++ const a = comparablePath(left);++ const b = comparablePath(right);++ return a < b ? -1 : a > b ? 1 : 0;++ });++}++++function assertLockLocation(root, expectedRoot) {++ const stats = inspectEntry(root);++ if (!stats || !stats.isDirectory() || stats.isSymbolicLink()++ || comparablePath(fs.realpathSync(root)) !== comparablePath(root)++ || (expectedRoot && !sameFileIdentity(stats, expectedRoot))) {++ throw new Error(`Refusing changed OpenCode install lock root: ${root}`);++ }++ const lock = inspectEntry(path.join(root, `${STATE_FILENAME}.ecc.lock`));++ if (lock && (!lock.isFile() || lock.isSymbolicLink())) {++ throw new Error(`Refusing non-file or symlink OpenCode install lock: ${root}`);++ }++ return { root: stats, lock };++}++++function assertOwnedLock(owned) {++ const live = assertLockLocation(owned.root, owned.rootStats);++ if (!live.lock || !sameFileIdentity(live.lock, owned.lockStats)) {++ throw new Error(`Refusing changed OpenCode install lock: ${owned.root}`);++ }++}++++function releaseOwned(ownedLocks) {++ let primaryError;++ for (const owned of [...ownedLocks].reverse()) {++ try {++ assertOwnedLock(owned);++ owned.release();++ } catch (error) {++ if (!primaryError) primaryError = error;++ else (primaryError.releaseErrors ||= []).push(error);++ }++ }++ if (primaryError) throw primaryError;++}++++function acquireOpenCodeInstallLocks(roots, existingLease) {++ const orderedRoots = canonicalRoots(roots);++ if (existingLease !== undefined) {++ const existing = existingLease && typeof existingLease === 'object' && activeLeases.get(existingLease);++ if (!existing) throw new Error('Invalid or inactive OpenCode install lease.');++ const covered = new Set(existing.map(owned => comparablePath(owned.root)));++ if (orderedRoots.some(root => !covered.has(comparablePath(root)))) {++ throw new Error('OpenCode install lease does not cover every required root.');++ }++ existing.forEach(assertOwnedLock);++ return { lease: existingLease, release() {} };++ }++ const ownedLocks = [];++ try {++ for (const root of orderedRoots) {++ fs.mkdirSync(root, { recursive: true });++ const before = assertLockLocation(root);++ const release = acquireSettingsLock(path.join(root, STATE_FILENAME), { label: 'OpenCode installation' });++ // Bind descriptor-derived ownership before any path revalidation. Never++ // adopt the identity of a replacement published at the lock pathname.++ const owned = { root, rootStats: before.root, release,++ lockStats: getSettingsLockIdentity(release) };++ ownedLocks.push(owned);++ assertOwnedLock(owned);++ }++ } catch (error) {++ try { releaseOwned(ownedLocks); }++ catch (releaseError) { error.releaseError = releaseError; }++ throw error;++ }++ const lease = Object.freeze({});++ activeLeases.set(lease, ownedLocks);++ return {++ lease,++ release() {++ if (!activeLeases.has(lease)) return;++ activeLeases.delete(lease);++ releaseOwned(ownedLocks);++ },++ };++}++++function withOpenCodeInstallLocks(roots, callback, existingLease) {++ if (typeof callback !== 'function') throw new TypeError('OpenCode install lock callback must be a function.');++ const holder = acquireOpenCodeInstallLocks(roots, existingLease);++ let primaryError;++ let result;++ try { result = callback(holder.lease); }++ catch (error) { primaryError = error; }++ try { holder.release(); }++ catch (error) { if (primaryError) primaryError.releaseError = error; else primaryError = error; }++ if (primaryError) throw primaryError;++ return result;++}++++module.exports = { acquireOpenCodeInstallLocks, withOpenCodeInstallLocks };diff --cc scripts/lib/install/opencode-legacy-migration.jsindex baf3472f1,baf3472f1..485130eb4--- a/scripts/lib/install/opencode-legacy-migration.js+++ b/scripts/lib/install/opencode-legacy-migration.js@@@ -393,6 -393,6 +393,7 @@@ function cleanupLegacyOpencodeInstall(pmodule.exports = {cleanupLegacyOpencodeInstall,getLegacyOpencodeLocation,++ getLegacyLocationForPlan,inspectLegacyOpencodeState,removeVerifiedLegacyFile,};diff --cc tests/lib/guarded-write.test.jsindex 000000000,000000000..e3b163264new file mode 100644--- /dev/null+++ b/tests/lib/guarded-write.test.js@@@ -1,0 -1,0 +1,223 @@@++/** Focused descriptor-bound writes; every filesystem fixture is private. */++'use strict';++const assert = require('assert');++const crypto = require('crypto');++const fs = require('fs');++const os = require('os');++const path = require('path');++const { writeFileNoFollow } = require('../../scripts/lib/install/guarded-write');++const digest = value => crypto.createHash('sha256').update(value).digest('hex');++let passed = 0;++let failed = 0;++function test(name, callback) {++ const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-guarded-')));++ const file = path.join(root, 'entry.js');++ const options = { action: 'replace activation', validateDestination: value => value };++ try { callback({ root, file, options }); passed++; console.log(` PASS ${name}`); }++ catch (error) { failed++; console.error(` FAIL ${name}: ${error.stack}`); }++ finally { fs.rmSync(root, { recursive: true, force: true }); }++}++function replaceMethod(name, replacement, callback) {++ const original = fs[name];++ fs[name] = replacement(original);++ try { callback(); } finally { fs[name] = original; }++}++function existing(options, content = 'old activation bytes') {++ return { ...options, expectedContent: Object.freeze({ kind: 'sha256', digest: digest(content) }) };++}++test('hashing then writing shorter bytes starts at zero and preserves the requested mode', ({ file, options }) => {++ fs.writeFileSync(file, 'old activation bytes');++ writeFileNoFollow(file, 'off\n', { ...existing(options), mode: 0o600 });++ assert.deepStrictEqual(fs.readFileSync(file), Buffer.from('off\n'));++ assert.strictEqual(fs.statSync(file).size, 4);++ if (process.platform !== 'win32') assert.strictEqual(fs.statSync(file).mode & 0o777, 0o600);++});++test('short writes are completed at explicit positions', ({ file, options }) => {++ const positions = [];++ replaceMethod('writeSync', original => (fd, buffer, offset, length, position) => {++ positions.push(position);++ return original(fd, buffer, offset, Math.min(length, 2), position);++ }, () => writeFileNoFollow(file, 'abcdef', options));++ assert.deepStrictEqual(positions, [0, 2, 4]);++ assert.strictEqual(fs.readFileSync(file, 'utf8'), 'abcdef');++});++test('expected absence creates a new exact file', ({ file, options }) => {++ writeFileNoFollow(file, Buffer.from('inert'), { ...options, expectedContent: { kind: 'absent' } });++ assert.strictEqual(fs.readFileSync(file, 'utf8'), 'inert');++});++test('a competing file before exclusive open is preserved', ({ file, options }) => {++ replaceMethod('openSync', original => (...args) => {++ if (args[0] === file && typeof args[1] === 'number') fs.writeFileSync(file, 'user bytes');++ return original(...args);++ }, () => assert.throws(() => writeFileNoFollow(file, 'off', {++ ...options, expectedContent: { kind: 'absent' },++ }), /changed after preflight/));++ assert.strictEqual(fs.readFileSync(file, 'utf8'), 'user bytes');++});++test('existing content removed before open is never recreated', ({ file, options }) => {++ fs.writeFileSync(file, 'old activation bytes');++ replaceMethod('openSync', original => (...args) => {++ if (args[0] === file) fs.unlinkSync(file);++ return original(...args);++ }, () => assert.throws(() => writeFileNoFollow(file, 'off', existing(options)), /changed after preflight/));++ assert.strictEqual(fs.existsSync(file), false);++});++test('same-inode edit at the writable-open boundary refuses before truncate and closes once', ({ file, options }) => {++ fs.writeFileSync(file, 'old activation bytes');++ let descriptor;++ let closes = 0;++ let truncates = 0;++ const originalOpen = fs.openSync;++ const originalClose = fs.closeSync;++ const originalTruncate = fs.ftruncateSync;++ fs.openSync = (...args) => {++ const fd = originalOpen(...args);++ if (args[0] === file && typeof args[1] === 'number') {++ descriptor = fd;++ fs.writeFileSync(file, 'user edited activation');++ }++ return fd;++ };++ fs.closeSync = fd => { if (fd === descriptor) closes++; return originalClose(fd); };++ fs.ftruncateSync = (...args) => { truncates++; return originalTruncate(...args); };++ try { assert.throws(() => writeFileNoFollow(file, 'off', existing(options)), /changed after preflight/); }++ finally { fs.openSync = originalOpen; fs.closeSync = originalClose; fs.ftruncateSync = originalTruncate; }++ assert.strictEqual(closes, 1);++ assert.strictEqual(truncates, 0);++ assert.strictEqual(fs.readFileSync(file, 'utf8'), 'user edited activation');++});++test('a descriptor read concurrent edit is observed before truncation', ({ file, options }) => {++ fs.writeFileSync(file, 'old activation bytes');++ replaceMethod('readFileSync', original => (...args) => {++ const result = original(...args);++ if (typeof args[0] === 'number') fs.writeFileSync(file, 'raced during hash');++ return result;++ }, () => assert.throws(() => writeFileNoFollow(file, 'off', existing(options)), /changed after preflight/));++ assert.strictEqual(fs.readFileSync(file, 'utf8'), 'raced during hash');++});++test('a pathname replacement after opening preserves both original and replacement', ({ file, options }) => {++ fs.writeFileSync(file, 'old activation bytes');++ replaceMethod('openSync', original => (...args) => {++ const fd = original(...args);++ if (args[0] === file && typeof args[1] === 'number') {++ fs.renameSync(file, `${file}.old`);++ fs.writeFileSync(file, 'replacement');++ }++ return fd;++ }, () => assert.throws(() => writeFileNoFollow(file, 'off', existing(options)), /changed/));++ assert.strictEqual(fs.readFileSync(file, 'utf8'), 'replacement');++ assert.strictEqual(fs.readFileSync(`${file}.old`, 'utf8'), 'old activation bytes');++});++test('a directory destination is refused without writes', ({ file, options }) => {++ fs.mkdirSync(file);++ assert.throws(() => writeFileNoFollow(file, 'off', options));++ assert.ok(fs.statSync(file).isDirectory());++});++test('a parent replacement at open is refused', ({ root, options }) => {++ const parent = path.join(root, 'plugins');++ fs.mkdirSync(parent);++ const file = path.join(parent, 'entry.js');++ fs.writeFileSync(file, 'old activation bytes');++ replaceMethod('openSync', original => (...args) => {++ const fd = original(...args);++ if (args[0] === file && typeof args[1] === 'number') {++ fs.renameSync(parent, `${parent}.old`);++ fs.mkdirSync(parent);++ fs.writeFileSync(file, 'replacement');++ }++ return fd;++ }, () => assert.throws(() => writeFileNoFollow(file, 'off', existing(options)), /changed/));++ assert.strictEqual(fs.readFileSync(file, 'utf8'), 'replacement');++});++test('destination validator is mandatory and must return the same path', ({ file, options }) => {++ assert.throws(() => writeFileNoFollow(file, 'off', {}), /validateDestination/);++ assert.throws(() => writeFileNoFollow(file, 'off', { ...options, validateDestination: () => `${file}.other` }), /changed/);++ assert.strictEqual(fs.existsSync(file), false);++});++test('destination validation runs again after the descriptor hash', ({ file, options }) => {++ fs.writeFileSync(file, 'old activation bytes');++ let validations = 0;++ assert.throws(() => writeFileNoFollow(file, 'off', {++ ...existing(options), validateDestination: value => {++ validations++;++ if (validations === 3) throw new Error('containment changed');++ return value;++ },++ }), /containment changed/);++ assert.strictEqual(fs.readFileSync(file, 'utf8'), 'old activation bytes');++});++for (const method of ['readFileSync', 'ftruncateSync', 'writeSync', 'fchmodSync']) {++ test(`${method} failure closes once and preserves the primary error if close also fails`, ({ file, options }) => {++ fs.writeFileSync(file, 'old activation bytes');++ const primary = new Error(`${method} primary`);++ const secondary = new Error('close secondary');++ const original = fs[method];++ const close = fs.closeSync;++ let closes = 0;++ fs[method] = (...args) => { if (typeof args[0] === 'number') throw primary; return original(...args); };++ fs.closeSync = fd => { closes++; close(fd); throw secondary; };++ try {++ assert.throws(() => writeFileNoFollow(file, 'off', { ...existing(options), mode: 0o600 }), error => {++ assert.strictEqual(error, primary);++ assert.strictEqual(error.closeError, secondary);++ return true;++ });++ } finally { fs[method] = original; fs.closeSync = close; }++ assert.strictEqual(closes, 1);++ });++}++test('close failure after a successful write is reported', ({ file, options }) => {++ replaceMethod('closeSync', original => fd => { original(fd); throw new Error('close failed'); }, () => {++ assert.throws(() => writeFileNoFollow(file, 'off', options), /close failed/);++ });++ assert.strictEqual(fs.readFileSync(file, 'utf8'), 'off');++});++test('zero-progress writes refuse instead of spinning', ({ file, options }) => {++ replaceMethod('writeSync', () => () => 0, () => assert.throws(() => writeFileNoFollow(file, 'off', options), /progress/));++});++test('malformed expected-content guards fail before opening a destination', ({ file, options }) => {++ for (const expectedContent of [null, true, { kind: 'sha256', digest: 'bad' }, { kind: 'missing' }]) {++ assert.throws(() => writeFileNoFollow(file, 'off', { ...options, expectedContent }), /expectedContent/);++ }++ assert.strictEqual(fs.existsSync(file), false);++});++test('a new exclusive file changed through the owned descriptor is preserved', ({ file, options }) => {++ replaceMethod('openSync', original => (...args) => {++ const fd = original(...args);++ if (args[0] === file && typeof args[1] === 'number') fs.writeSync(fd, Buffer.from('raced creation'), 0, 14, 0);++ return fd;++ }, () => assert.throws(() => writeFileNoFollow(file, 'off', {++ ...options, expectedContent: { kind: 'absent' },++ }), /changed after preflight/));++ assert.strictEqual(fs.readFileSync(file, 'utf8'), 'raced creation');++});++test('the final pathname must remain a regular non-symlink even without O_NOFOLLOW support', ({ file, options }) => {++ fs.writeFileSync(file, 'old activation bytes');++ replaceMethod('lstatSync', original => (...args) => {++ const stats = original(...args);++ if (args[0] === file) {++ const simulatedSymlink = Object.create(stats);++ simulatedSymlink.isSymbolicLink = () => true;++ return simulatedSymlink;++ }++ return stats;++ }, () => assert.throws(() => writeFileNoFollow(file, 'off', existing(options)), /changed/));++ assert.strictEqual(fs.readFileSync(file, 'utf8'), 'old activation bytes');++});++test('the immutable preflight digest cannot be changed by a validator callback', ({ file, options }) => {++ fs.writeFileSync(file, 'user bytes');++ const expectedContent = { kind: 'sha256', digest: digest('old bytes') };++ assert.throws(() => writeFileNoFollow(file, 'off', {++ ...options, expectedContent, validateDestination: value => {++ expectedContent.digest = digest('user bytes');++ return value;++ },++ }), /changed after preflight/);++ assert.strictEqual(fs.readFileSync(file, 'utf8'), 'user bytes');++});++test('unexpected input fails without creating a file', ({ file, options }) => {++ assert.throws(() => writeFileNoFollow(file, {}, options), /content/);++ assert.strictEqual(fs.existsSync(file), false);++});++console.log(`Results: Passed: ${passed}, Failed: ${failed}`);++process.exitCode = failed ? 1 : 0;diff --cc tests/lib/install-lifecycle.test.jsindex 4377915b0,1eed5071b..c1862581c--- a/tests/lib/install-lifecycle.test.js+++ b/tests/lib/install-lifecycle.test.js@@@ -1956,341 -1935,6 +1956,342 @@@ function runTests()}})) passed++; else failed++;+ if (test('doctor dispatches the OpenCode hook-disable content transform consistently', () => {+ const projectRoot = createTempDir('install-lifecycle-opencode-transform-');++ try {+ const targetRoot = path.join(projectRoot, '.cursor');+ const installStatePath = path.join(targetRoot, 'ecc-install-state.json');+ const destinationPath = path.join(targetRoot, 'opencode.json');+ const sourceConfig = JSON.parse(fs.readFileSync(+ path.join(REPO_ROOT, '.opencode', 'opencode.json'),+ 'utf8'+ ));+ const expectedContent = `${JSON.stringify({+ ...sourceConfig,+ plugin: sourceConfig.plugin.filter(plugin => plugin !== './plugins'),+ }, null, 2)}\n`;+ fs.mkdirSync(targetRoot, { recursive: true });+ fs.writeFileSync(destinationPath, expectedContent, 'utf8');+ writeState(installStatePath, createCursorStateOptions(projectRoot, {+ targetRoot,+ installStatePath,+ operations: [{+ kind: 'copy-file',+ moduleId: 'platform-configs',+ sourceRelativePath: '.opencode/opencode.json',+ destinationPath,+ strategy: 'preserve-relative-path',+ ownership: 'managed',+ scaffoldOnly: false,+ contentTransform: 'opencode-disable-ecc-hooks',+ }],+ }));++ const report = buildDoctorReport({+ repoRoot: REPO_ROOT,+ homeDir: projectRoot,+ projectRoot,+ targets: ['cursor'],+ });++ assert.strictEqual(report.results.length, 1);+ assert.ok(!report.results[0].issues.some(issue => (+ issue.code === 'drifted-managed-files'+ || issue.code === 'unverified-managed-operations'+ )));+ } finally {+ cleanup(projectRoot);+ }+ })) passed++; else failed++;++ if (test('OpenCode doctor and repair keep auto-discovered plugin entrypoints inert after declined consent', () => {+ const homeDir = createTempDir('install-lifecycle-opencode-inert-');+ try {+ withTemporarilyMovedPath(path.join(REPO_ROOT, '.opencode', 'dist'), () => {+ const plan = createInstallPlanFromRequest({+ mode: 'manifest', target: 'opencode', profileId: null,+ moduleIds: ['platform-configs'], includeComponentIds: [], excludeComponentIds: [],+ legacyLanguages: [], hookConsent: 'declined',+ }, {+ sourceRoot: REPO_ROOT, homeDir, projectRoot: homeDir,+ exemptValidationCodes: ['opencode-plugin-not-built'],+ });+ applyInstallPlan(plan);+ const pluginPaths = ['ecc-hooks.ts', 'index.ts'].map(name => path.join(plan.targetRoot, 'plugins', name));+ for (const pluginPath of pluginPaths) {+ assert.strictEqual(fs.readFileSync(pluginPath, 'utf8'), 'export default async () => ({});\n');+ fs.unlinkSync(pluginPath);+ }+ const before = buildDoctorReport({ repoRoot: REPO_ROOT, homeDir, projectRoot: homeDir, targets: ['opencode'] });+ assert.ok(before.results[0].issues.some(issue => issue.code === 'missing-managed-files'));+ let buildCalls = 0;+ const repaired = repairInstalledStates({+ repoRoot: REPO_ROOT, homeDir, projectRoot: homeDir, targets: ['opencode'],+ buildOpencodePayload(repoRoot) {+ buildCalls += 1;+ const distDir = path.join(repoRoot, '.opencode', 'dist');+ fs.mkdirSync(path.join(distDir, 'plugins'), { recursive: true });+ fs.mkdirSync(path.join(distDir, 'tools'), { recursive: true });+ fs.writeFileSync(path.join(distDir, 'index.js'), 'module.exports = {};\n');+ },+ });+ assert.strictEqual(buildCalls, 1, 'Only the injected inert builder is used');+ assert.strictEqual(repaired.results[0].status, 'repaired');+ for (const pluginPath of pluginPaths) {+ assert.strictEqual(fs.readFileSync(pluginPath, 'utf8'), 'export default async () => ({});\n');+ }+ const state = readInstallState(plan.installStatePath);+ assert.strictEqual(state.request.hookConsent, 'declined');+ for (const pluginPath of pluginPaths) {+ const operation = state.operations.find(candidate => candidate.destinationPath === pluginPath);+ assert.strictEqual(operation.contentTransform, 'opencode-disable-plugin-entrypoint');+ }+ const after = buildDoctorReport({ repoRoot: REPO_ROOT, homeDir, projectRoot: homeDir, targets: ['opencode'] });+ assert.ok(!after.results[0].issues.some(issue => (+ ['missing-managed-files', 'drifted-managed-files', 'unverified-managed-operations'].includes(issue.code)+ )));+ });+ } finally {+ cleanup(homeDir);+ }+ })) passed++; else failed++;++ if (test('OpenCode repair disables older auto-discovered activation without inferring consent', () => {+ const homeDir = createTempDir('install-lifecycle-opencode-old-activation-');+ try {+ withTemporarilyMovedPath(path.join(REPO_ROOT, '.opencode', 'dist'), () => {+ const recorded = writeRecordedOpenCodeActivation(homeDir);+ const result = repairInstalledStates({+ repoRoot: REPO_ROOT, homeDir, projectRoot: homeDir, targets: ['opencode'],+ buildOpencodePayload(repoRoot) {+ const distDir = path.join(repoRoot, '.opencode', 'dist');+ fs.mkdirSync(path.join(distDir, 'plugins'), { recursive: true });+ fs.mkdirSync(path.join(distDir, 'tools'), { recursive: true });+ fs.writeFileSync(path.join(distDir, 'index.js'), 'module.exports = {};\n');+ },+ });+ assert.strictEqual(result.results[0].status, 'repaired');+ for (const name of ['ecc-hooks.ts', 'index.ts']) {+ assert.strictEqual(fs.readFileSync(path.join(recorded.targetRoot, 'plugins', name), 'utf8'), 'export default async () => ({});\n');+ }+ assert.ok(!JSON.parse(fs.readFileSync(path.join(recorded.targetRoot, 'opencode.json'), 'utf8')).plugin.includes('./plugins'));+ const state = readInstallState(recorded.installStatePath);+ assert.notStrictEqual(state.request.hookConsent, 'enabled');+ assert.ok(!state.resolution.selectedModules.includes('hooks-runtime'));+ for (const operation of state.operations.filter(operation => (+ ['.opencode/plugins/ecc-hooks.ts', '.opencode/plugins/index.ts'].includes(operation.sourceRelativePath)+ ))) {+ assert.strictEqual(operation.contentTransform, 'opencode-disable-plugin-entrypoint');+ }+ });+ } finally {+ cleanup(homeDir);+ }+ })) passed++; else failed++;++ if (test('OpenCode repair refuses modified activation before building or restoring missing files', () => {+ const homeDir = createTempDir('install-lifecycle-opencode-modified-activation-');+ try {+ withTemporarilyMovedPath(path.join(REPO_ROOT, '.opencode', 'dist'), () => {+ const recorded = writeRecordedOpenCodeActivation(homeDir);+ const pluginPath = path.join(recorded.targetRoot, 'plugins', 'ecc-hooks.ts');+ const missingPath = path.join(recorded.targetRoot, 'plugins', 'index.ts');+ const configPath = path.join(recorded.targetRoot, 'opencode.json');+ fs.appendFileSync(pluginPath, '// user custom hook\n');+ fs.unlinkSync(missingPath);+ const before = [pluginPath, configPath, recorded.installStatePath].map(filePath => fs.readFileSync(filePath));+ let buildCalls = 0;+ const result = repairInstalledStates({+ repoRoot: REPO_ROOT, homeDir, projectRoot: homeDir, targets: ['opencode'],+ buildOpencodePayload() {+ buildCalls += 1;+ throw new Error('Guard must run before the builder');+ },+ });+ assert.strictEqual(result.results[0].status, 'error');+ assert.match(result.results[0].error, /OpenCode hook|OpenCode.*activation|OpenCode.*plugin/i);+ assert.strictEqual(buildCalls, 0);+ assert.strictEqual(fs.existsSync(missingPath), false);+ assert.deepStrictEqual([pluginPath, configPath, recorded.installStatePath].map(filePath => fs.readFileSync(filePath)), before);+ assert.strictEqual(fs.existsSync(path.join(REPO_ROOT, '.opencode', 'dist')), false);+ });+ } finally {+ cleanup(homeDir);+ }+ })) passed++; else failed++;++ if (test('OpenCode repair rejects recorded non-plugin sources at missing activation destinations before building', () => {+ for (const kind of ['render-template', 'copy-file']) {+ const homeDir = createTempDir('install-lifecycle-opencode-disguised-');+ try {+ withTemporarilyMovedPath(path.join(REPO_ROOT, '.opencode', 'dist'), () => {+ const targetRoot = path.join(homeDir, '.config', 'opencode');+ const destinationPath = path.join(targetRoot, 'plugins', 'index.ts');+ const recorded = writeOpencodeState(homeDir, {+ request: { modules: ['platform-configs'], hookConsent: 'declined', legacyMode: true },+ resolution: { selectedModules: ['platform-configs'] },+ operations: [managedOperation(kind, destinationPath, {+ moduleId: 'platform-configs',+ sourceRelativePath: '.claude-plugin/plugin.json.template',+ ...(kind === 'render-template' ? { renderedContent: 'globalThis.unconsentedHook = true;\n' } : {}),+ })],+ });+ const stateBefore = fs.readFileSync(recorded.installStatePath);+ let buildCalls = 0;+ const result = repairInstalledStates({+ repoRoot: REPO_ROOT, homeDir, projectRoot: homeDir, targets: ['opencode'],+ buildOpencodePayload() { buildCalls += 1; throw new Error('Unsafe activation must fail before building'); },+ });+ assert.strictEqual(result.results[0].status, 'error', kind);+ assert.match(result.results[0].error, /OpenCode hook.*unsupported activation operation/i);+ assert.strictEqual(buildCalls, 0);+ assert.strictEqual(fs.existsSync(destinationPath), false);+ assert.strictEqual(fs.existsSync(path.dirname(destinationPath)), false);+ assert.strictEqual(fs.existsSync(path.join(REPO_ROOT, '.opencode', 'dist')), false);+ assert.strictEqual(crypto.createHash('sha256').update(fs.readFileSync(recorded.installStatePath)).digest('hex'), crypto.createHash('sha256').update(stateBefore).digest('hex'), 'Failed repair must not refresh install-state');+ });+ } finally {+ cleanup(homeDir);+ }+ }+ })) passed++; else failed++;++ if (test('OpenCode repair preserves activation bytes changed between health inspection and write', () => {+ const homeDir = createTempDir('install-lifecycle-opencode-health-race-');+ const originalOpenSync = fs.openSync;+ const originalReadFileSync = fs.readFileSync;+ const originalCloseSync = fs.closeSync;+ const descriptors = new Set();+ try {+ withTemporarilyMovedPath(path.join(REPO_ROOT, '.opencode', 'dist'), () => {+ const recorded = writeRecordedOpenCodeActivation(homeDir);+ const pluginPath = path.join(recorded.targetRoot, 'plugins', 'ecc-hooks.ts');+ const canonicalPluginPath = fs.realpathSync(pluginPath);+ const changedContent = 'globalThis.userChangedHook = true;\n';+ const stateBefore = fs.readFileSync(recorded.installStatePath);+ let changed = false;+ fs.openSync = function trackActivationDescriptor(candidate, ...args) {+ const descriptor = originalOpenSync.call(fs, candidate, ...args);+ if (typeof candidate === 'string' && [pluginPath, canonicalPluginPath].includes(path.resolve(candidate))) descriptors.add(descriptor);+ return descriptor;+ };+ fs.closeSync = function releaseActivationDescriptor(descriptor) {+ descriptors.delete(descriptor);+ return originalCloseSync.call(fs, descriptor);+ };+ fs.readFileSync = function mutateAfterHealthRead(candidate, ...args) {+ const content = originalReadFileSync.call(fs, candidate, ...args);+ // Lifecycle reads pass an encoding argument; the consent snapshot+ // reads the descriptor as raw bytes with no second argument.+ if (!changed && descriptors.has(candidate) && args.length > 0) {+ changed = true;+ fs.writeFileSync(pluginPath, changedContent);+ }+ return content;+ };+ let result;+ try {+ result = repairInstalledStates({+ repoRoot: REPO_ROOT, homeDir, projectRoot: homeDir, targets: ['opencode'],+ buildOpencodePayload(repoRoot) {+ const distDir = path.join(repoRoot, '.opencode', 'dist');+ fs.mkdirSync(path.join(distDir, 'plugins'), { recursive: true });+ fs.mkdirSync(path.join(distDir, 'tools'), { recursive: true });+ fs.writeFileSync(path.join(distDir, 'index.js'), 'module.exports = {};\n');+ },+ });+ } finally {+ fs.openSync = originalOpenSync;+ fs.readFileSync = originalReadFileSync;+ fs.closeSync = originalCloseSync;+ }+ assert.strictEqual(changed, true, 'The health-read boundary was exercised');+ assert.strictEqual(result.results[0].status, 'error');+ assert.match(result.results[0].error, /OpenCode hook.*changed after preflight/i);+ assert.strictEqual(fs.readFileSync(pluginPath, 'utf8'), changedContent);+ const previousState = JSON.parse(stateBefore.toString('utf8'));+ const checkpointState = readInstallState(recorded.installStatePath);+ const priorOperation = previousState.operations.find(operation => operation.destinationPath === pluginPath);+ const checkpointOperation = checkpointState.operations.find(operation => operation.destinationPath === pluginPath);+ assert.strictEqual(checkpointOperation.contentSha256, priorOperation.contentSha256, 'Failure checkpoint must not adopt raced activation bytes');+ assert.strictEqual(checkpointState.request.hookConsent, previousState.request.hookConsent);+ assert.notStrictEqual(result.results[0].stateRefreshed, true);+ });+ } finally {+ fs.openSync = originalOpenSync;+ fs.readFileSync = originalReadFileSync;+ fs.closeSync = originalCloseSync;+ cleanup(homeDir);+ }+ })) passed++; else failed++;++ if (test('OpenCode repair rejects an active alias introduced during writes before refreshing state', () => {+ const homeDir = createTempDir('install-lifecycle-opencode-alias-race-');+ const originalOpenSync = fs.openSync;+ const originalWriteFileSync = fs.writeFileSync;++ const originalWriteSync = fs.writeSync;+ const originalCloseSync = fs.closeSync;+ const descriptors = new Set();+ try {+ withTemporarilyMovedPath(path.join(REPO_ROOT, '.opencode', 'dist'), () => {+ const recorded = writeRecordedOpenCodeActivation(homeDir);+ const pluginPath = path.join(recorded.targetRoot, 'plugins', 'index.ts');+ const canonicalPluginPath = fs.realpathSync(pluginPath);+ const aliasPath = path.join(recorded.targetRoot, 'plugins', 'index.js');+ const aliasContent = 'globalThis.lateActiveAlias = true;\n';+ const stateBefore = fs.readFileSync(recorded.installStatePath);+ let inserted = false;+ fs.openSync = function trackPluginWriteDescriptor(candidate, ...args) {+ const descriptor = originalOpenSync.call(fs, candidate, ...args);+ if (typeof candidate === 'string' && [pluginPath, canonicalPluginPath].includes(path.resolve(candidate))) descriptors.add(descriptor);+ return descriptor;+ };+ fs.closeSync = function releasePluginWriteDescriptor(descriptor) {+ descriptors.delete(descriptor);+ return originalCloseSync.call(fs, descriptor);+ };- fs.writeFileSync = function insertAliasAfterPluginWrite(candidate, ...args) {- const result = originalWriteFileSync.call(fs, candidate, ...args);++ fs.writeSync = function insertAliasAfterPluginWrite(candidate, ...args) {++ const result = originalWriteSync.call(fs, candidate, ...args);+ if (!inserted && descriptors.has(candidate)) {+ inserted = true;+ originalWriteFileSync.call(fs, aliasPath, aliasContent);+ }+ return result;+ };+ let result;+ try {+ result = repairInstalledStates({+ repoRoot: REPO_ROOT, homeDir, projectRoot: homeDir, targets: ['opencode'],+ buildOpencodePayload(repoRoot) {+ const distDir = path.join(repoRoot, '.opencode', 'dist');+ fs.mkdirSync(path.join(distDir, 'plugins'), { recursive: true });+ fs.mkdirSync(path.join(distDir, 'tools'), { recursive: true });+ fs.writeFileSync(path.join(distDir, 'index.js'), 'module.exports = {};\n');+ },+ });+ } finally {+ fs.openSync = originalOpenSync;- fs.writeFileSync = originalWriteFileSync;++ fs.writeSync = originalWriteSync;+ fs.closeSync = originalCloseSync;+ }+ assert.strictEqual(inserted, true, 'The plugin-write boundary was exercised');+ assert.strictEqual(result.results[0].status, 'error');+ assert.match(result.results[0].error, /OpenCode hook activation remains active/i);+ assert.strictEqual(fs.readFileSync(aliasPath, 'utf8'), aliasContent);+ const checkpointState = readInstallState(recorded.installStatePath);+ assert.ok(!checkpointState.operations.some(operation => operation.destinationPath === aliasPath), 'Failed repair must not adopt the raced alias');+ assert.strictEqual(checkpointState.request.hookConsent, JSON.parse(stateBefore.toString('utf8')).request.hookConsent);+ assert.notStrictEqual(result.results[0].stateRefreshed, true);+ });+ } finally {+ fs.openSync = originalOpenSync;- fs.writeFileSync = originalWriteFileSync;++ fs.writeSync = originalWriteSync;+ fs.closeSync = originalCloseSync;+ cleanup(homeDir);+ }+ })) passed++; else failed++;+if (test('doctor infers enabled hooks from older manifest install-state records', () => {const homeDir = createTempDir('install-lifecycle-home-');const projectRoot = createTempDir('install-lifecycle-project-');diff --cc tests/lib/opencode-consent-legacy-lock.test.jsindex 000000000,000000000..259e86b9fnew file mode 100644--- /dev/null+++ b/tests/lib/opencode-consent-legacy-lock.test.js@@@ -1,0 -1,0 +1,196 @@@++/** Synthetic legacy migration: both install roots stay locked across build/apply. */++'use strict';++++const assert = require('assert');++const crypto = require('crypto');++const fs = require('fs');++const os = require('os');++const path = require('path');++const { applyInstallPlan } = require('../../scripts/lib/install/apply');++const { repairInstalledStates } = require('../../scripts/lib/install-lifecycle');++const { createInstallState, readInstallState, writeInstallState } = require('../../scripts/lib/install-state');++const { withOpenCodeInstallLocks } = require('../../scripts/lib/install/opencode-install-lock');++++const SOURCE_RELATIVE_PATH = path.join('skills', 'skill-comply', 'SKILL.md');++const SKILL_CONTENT = '---\nname: skill-comply\ndescription: Synthetic migration fixture.\n---\n\n# Inert fixture\n';++const sha256 = value => crypto.createHash('sha256').update(value).digest('hex');++const lockPath = root => path.join(root, 'ecc-install-state.json.ecc.lock');++++function writeJson(filePath, value) {++ fs.mkdirSync(path.dirname(filePath), { recursive: true });++ fs.writeFileSync(filePath, `${JSON.stringify(value, null, 2)}\n`);++}++++function privateFixture(callback) {++ const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-legacy-consent-lock-')));++ const sourceRoot = path.join(root, 'source');++ const homeDir = path.join(root, 'home');++ const legacyRoot = path.join(homeDir, '.opencode');++ const canonicalRoot = path.join(homeDir, '.config', 'opencode');++ const sourcePath = path.join(sourceRoot, SOURCE_RELATIVE_PATH);++ const legacyFile = path.join(legacyRoot, SOURCE_RELATIVE_PATH);++ const legacyStatePath = path.join(legacyRoot, 'ecc-install-state.json');++ const canonicalStatePath = path.join(canonicalRoot, 'ecc-install-state.json');++ const adapter = { id: 'opencode-home', target: 'opencode', kind: 'home' };++ try {++ writeJson(path.join(sourceRoot, 'package.json'), { name: 'synthetic-ecc-lock-fixture', version: '2.2.2' });++ writeJson(path.join(sourceRoot, 'manifests', 'install-modules.json'), {++ version: 1,++ modules: [{ id: 'workflow-quality', kind: 'skills', description: 'Inert test skill.',++ paths: [SOURCE_RELATIVE_PATH], targets: ['opencode'], dependencies: [],++ defaultInstall: false, cost: 'light', stability: 'stable' }],++ });++ writeJson(path.join(sourceRoot, 'manifests', 'install-profiles.json'), { version: 1, profiles: {} });++ writeJson(path.join(sourceRoot, 'manifests', 'install-components.json'), { version: 1, components: [] });++ for (const filePath of [sourcePath, legacyFile]) {++ fs.mkdirSync(path.dirname(filePath), { recursive: true });++ fs.writeFileSync(filePath, SKILL_CONTENT);++ }++ const operation = { kind: 'copy-file', moduleId: 'workflow-quality',++ sourceRelativePath: SOURCE_RELATIVE_PATH, destinationPath: legacyFile,++ strategy: 'preserve-relative-path', ownership: 'managed', scaffoldOnly: false,++ contentSha256: sha256(SKILL_CONTENT) };++ const stateOptions = {++ adapter,++ request: { profile: null, modules: ['workflow-quality'], includeComponents: [],++ excludeComponents: [], legacyLanguages: [], legacyMode: false, hookConsent: null },++ resolution: { selectedModules: ['workflow-quality'], skippedModules: [] },++ source: { repoVersion: '2.2.2', repoCommit: 'synthetic-legacy-lock-fixture', manifestVersion: 1 },++ };++ writeInstallState(legacyStatePath, createInstallState({ ...stateOptions,++ targetRoot: legacyRoot, installStatePath: legacyStatePath, operations: [operation] }));++ const canonicalOperation = { ...operation, sourcePath,++ destinationPath: path.join(canonicalRoot, SOURCE_RELATIVE_PATH) };++ const canonicalPlan = {++ target: 'opencode', adapter, sourceRoot, homeDir, targetRoot: canonicalRoot,++ installRoot: canonicalRoot, installStatePath: canonicalStatePath,++ selectedModuleIds: ['workflow-quality'], operations: [canonicalOperation], warnings: [],++ statePreview: createInstallState({ ...stateOptions, targetRoot: canonicalRoot,++ installStatePath: canonicalStatePath, operations: [canonicalOperation] }),++ };++ const sourceFiles = ['package.json', 'manifests/install-modules.json',++ 'manifests/install-profiles.json', 'manifests/install-components.json', SOURCE_RELATIVE_PATH];++ const sourceSnapshot = new Map(sourceFiles.map(relative => [relative,++ fs.readFileSync(path.join(sourceRoot, relative))]));++ callback({ root, homeDir, sourceRoot, sourcePath, sourceSnapshot, legacyRoot, canonicalRoot,++ legacyFile, legacyStatePath, canonicalStatePath, canonicalPlan });++ } finally {++ // The generated payload and all install paths are inside this fixture.++ // No repository assets, compiler output, real user home or providers are used.++ fs.rmSync(root, { recursive: true, force: true });++ }++}++++function repair(value, buildOpencodePayload) {++ return repairInstalledStates({ repoRoot: value.sourceRoot, homeDir: value.homeDir,++ projectRoot: value.homeDir, targets: ['opencode'], env: {}, buildOpencodePayload });++}++++function assertSourceUnchanged(value) {++ for (const [relative, bytes] of value.sourceSnapshot) {++ assert.deepStrictEqual(fs.readFileSync(path.join(value.sourceRoot, relative)), bytes, relative);++ }++}++++function assertHeldAndIndependentWritersRefused(value) {++ const lockBytes = [value.canonicalRoot, value.legacyRoot].map(targetRoot => {++ const bytes = fs.readFileSync(lockPath(targetRoot));++ assert.strictEqual(JSON.parse(bytes).pid, process.pid);++ return bytes;++ });++ const legacyBytes = fs.readFileSync(value.legacyStatePath);++ assert.throws(() => applyInstallPlan(value.canonicalPlan, {++ beforeInstallStateRead() { assert.fail('Independent apply reached state read while migration held both locks'); },++ }), /Another ECC process.*OpenCode/);++ let nestedBuilds = 0;++ const nested = repair(value, () => {++ nestedBuilds++;++ assert.fail('Independent repair reached build while migration held both locks');++ });++ assert.strictEqual(nested.results.length, 1, JSON.stringify(nested));++ assert.strictEqual(nested.results[0].status, 'error');++ assert.match(nested.results[0].error, /Another ECC process.*OpenCode/);++ assert.strictEqual(nestedBuilds, 0);++ assert.strictEqual(fs.existsSync(value.canonicalStatePath), false);++ assert.deepStrictEqual(fs.readFileSync(value.legacyStatePath), legacyBytes);++ [value.canonicalRoot, value.legacyRoot].forEach((targetRoot, index) => {++ assert.deepStrictEqual(fs.readFileSync(lockPath(targetRoot)), lockBytes[index]);++ });++}++++function assertBothLocksReleased(value) {++ for (const targetRoot of [value.canonicalRoot, value.legacyRoot]) {++ assert.strictEqual(fs.existsSync(lockPath(targetRoot)), false);++ }++ withOpenCodeInstallLocks([value.canonicalRoot, value.legacyRoot], () => {++ assert.ok(fs.existsSync(lockPath(value.canonicalRoot)));++ assert.ok(fs.existsSync(lockPath(value.legacyRoot)));++ });++ for (const targetRoot of [value.canonicalRoot, value.legacyRoot]) {++ assert.strictEqual(fs.existsSync(lockPath(targetRoot)), false);++ }++}++++function runTests() {++ let passed = 0;++ let failed = 0;++ function test(name, callback) {++ try { privateFixture(callback); passed++; console.log(` PASS ${name}`); }++ catch (error) { failed++; console.error(` FAIL ${name}: ${error.stack}`); }++ }++ test('legacy repair holds both roots before build and releases them after a throwing builder', value => {++ const beforeState = fs.readFileSync(value.legacyStatePath);++ let builds = 0;++ const result = repair(value, sourceRoot => {++ builds++;++ assert.strictEqual(sourceRoot, value.sourceRoot);++ assertHeldAndIndependentWritersRefused(value);++ throw new Error('Synthetic builder failure before any source mutation');++ });++ assert.strictEqual(builds, 1);++ assert.strictEqual(result.results.length, 1, JSON.stringify(result));++ assert.strictEqual(result.results[0].status, 'error');++ assert.match(result.results[0].error, /Synthetic builder failure before any source mutation/);++ assert.strictEqual(result.results[0].stateRefreshed, undefined);++ assert.deepStrictEqual(fs.readFileSync(value.legacyStatePath), beforeState);++ assert.strictEqual(fs.readFileSync(value.legacyFile, 'utf8'), SKILL_CONTENT);++ assert.strictEqual(fs.existsSync(value.canonicalStatePath), false);++ assert.strictEqual(fs.existsSync(path.join(value.sourceRoot, '.opencode', 'dist')), false);++ assertSourceUnchanged(value);++ assertBothLocksReleased(value);++ });++ test('legacy repair reuses its opaque lease for canonical apply after an inert synthetic build', value => {++ let builds = 0;++ const result = repair(value, sourceRoot => {++ builds++;++ assert.strictEqual(sourceRoot, value.sourceRoot);++ assertHeldAndIndependentWritersRefused(value);++ const dist = path.join(sourceRoot, '.opencode', 'dist');++ fs.mkdirSync(path.join(dist, 'plugins'), { recursive: true });++ fs.mkdirSync(path.join(dist, 'tools'), { recursive: true });++ fs.writeFileSync(path.join(dist, 'index.js'), 'module.exports = {};\n');++ });++ assert.strictEqual(builds, 1);++ assert.strictEqual(result.summary.errorCount, 0, JSON.stringify(result));++ assert.strictEqual(result.results.length, 1, JSON.stringify(result));++ assert.strictEqual(result.results[0].status, 'repaired');++ assert.strictEqual(result.results[0].stateRefreshed, true);++ assert.strictEqual(result.results[0].installStatePath, value.canonicalStatePath);++ const state = readInstallState(value.canonicalStatePath);++ assert.strictEqual(state.target.root, value.canonicalRoot);++ assert.deepStrictEqual(state.resolution.selectedModules, ['workflow-quality']);++ assert.notStrictEqual(state.request.hookConsent, 'enabled');++ assert.strictEqual(state.operations.length, 1);++ assert.strictEqual(state.operations[0].contentSha256, sha256(SKILL_CONTENT));++ assert.strictEqual(fs.readFileSync(path.join(value.canonicalRoot, SOURCE_RELATIVE_PATH), 'utf8'), SKILL_CONTENT);++ assert.strictEqual(fs.existsSync(value.legacyStatePath), false);++ assert.strictEqual(fs.existsSync(value.legacyFile), false);++ assertSourceUnchanged(value);++ assertBothLocksReleased(value);++ });++ console.log(`\nResults: Passed: ${passed}, Failed: ${failed}`);++ return { passed, failed };++}++++if (require.main === module) process.exitCode = runTests().failed ? 1 : 0;++module.exports = { runTests };diff --cc tests/lib/opencode-hook-consent-safety.test.jsindex 000000000,000000000..09b5a9fc7new file mode 100644--- /dev/null+++ b/tests/lib/opencode-hook-consent-safety.test.js@@@ -1,0 -1,0 +1,244 @@@++'use strict';++++const assert = require('assert');++const crypto = require('crypto');++const fs = require('fs');++const os = require('os');++const path = require('path');++const { applyInstallPlan } = require('../../scripts/lib/install/apply');++const { withHookConsent } = require('../../scripts/lib/install/hook-consent');++const { createInstallState, readInstallState, writeInstallState } = require('../../scripts/lib/install-state');++const { buildDoctorReport, repairInstalledStates } = require('../../scripts/lib/install-lifecycle');++++const REPO_ROOT = path.resolve(__dirname, '../..');++const sha256 = value => crypto.createHash('sha256').update(value).digest('hex');++++function fixture(callback, enabled = false) {++ const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-opencode-write-')));++ const homeDir = path.join(root, 'home');++ const sourceRoot = path.join(root, 'source');++ const targetRoot = path.join(homeDir, '.config', 'opencode');++ const adapter = { id: 'opencode-home', target: 'opencode', kind: 'home' };++ try {++ fs.mkdirSync(path.join(sourceRoot, 'manifests'), { recursive: true });++ for (const name of ['install-modules.json', 'install-components.json', 'install-profiles.json']) {++ fs.copyFileSync(path.join(REPO_ROOT, 'manifests', name), path.join(sourceRoot, 'manifests', name));++ }++ fs.copyFileSync(path.join(REPO_ROOT, 'package.json'), path.join(sourceRoot, 'package.json'));++ const operations = ['opencode.json', 'plugins/ecc-hooks.ts'].map(relativePath => {++ const sourceRelativePath = `.opencode/${relativePath}`;++ const sourcePath = path.join(sourceRoot, sourceRelativePath);++ const destinationPath = path.join(targetRoot, relativePath);++ const content = relativePath === 'opencode.json'++ ? '{"plugin":["./plugins"],"userSetting":true}\n'++ : 'export default async () => ({ "session.created": () => {} });\n';++ fs.mkdirSync(path.dirname(sourcePath), { recursive: true });++ fs.mkdirSync(path.dirname(destinationPath), { recursive: true });++ fs.writeFileSync(sourcePath, content);++ fs.writeFileSync(destinationPath, content);++ return { kind: 'copy-file', moduleId: 'platform-configs', sourceRelativePath, sourcePath,++ destinationPath, ownership: 'managed', scaffoldOnly: false,++ strategy: 'preserve-relative-path', contentSha256: sha256(content) };++ });++ const dist = path.join(sourceRoot, '.opencode', 'dist');++ fs.mkdirSync(path.join(dist, 'plugins'), { recursive: true });++ fs.mkdirSync(path.join(dist, 'tools'), { recursive: true });++ fs.writeFileSync(path.join(dist, 'index.js'), 'module.exports = {};\n');++ const installStatePath = path.join(targetRoot, 'ecc-install-state.json');++ const state = createInstallState({++ adapter, targetRoot, installStatePath,++ request: { modules: ['platform-configs'], legacyMode: true,++ hookConsent: enabled ? 'enabled' : null },++ resolution: { selectedModules: enabled ? ['platform-configs', 'hooks-runtime'] : ['platform-configs'],++ skippedModules: [] },++ operations, source: { repoVersion: '2.2.2', manifestVersion: 1 },++ });++ writeInstallState(installStatePath, state);++ const basePlan = { target: 'opencode', adapter, homeDir, sourceRoot, targetRoot,++ installRoot: targetRoot, installStatePath, operations, warnings: [],++ selectedModuleIds: state.resolution.selectedModules, statePreview: state };++ callback({ root, homeDir, sourceRoot, targetRoot, installStatePath, state, basePlan,++ declinePlan: withHookConsent(basePlan, 'declined') });++ } finally {++ fs.rmSync(root, { recursive: true, force: true });++ }++}++++function repair(value, extra = {}) {++ return repairInstalledStates({ repoRoot: value.sourceRoot, homeDir: value.homeDir,++ projectRoot: value.homeDir, targets: ['opencode'],++ buildOpencodePayload() { throw new Error('Unexpected compiler execution'); }, ...extra });++}++++function withWritableOpenMutation(filePath, mutate, callback) {++ const originalOpen = fs.openSync;++ const originalClose = fs.closeSync;++ let injected = false;++ const descriptors = new Set();++ fs.openSync = function (candidate, flags, ...rest) {++ const writable = typeof flags === 'number'++ ? Boolean(flags & (fs.constants.O_WRONLY | fs.constants.O_RDWR))++ : /[wa+]/.test(flags);++ const matches = typeof candidate === 'string' && path.resolve(candidate) === path.resolve(filePath);++ if (matches && writable && !injected) {++ injected = true;++ mutate();++ }++ const fd = originalOpen.call(fs, candidate, flags, ...rest);++ if (matches && writable) descriptors.add(fd);++ return fd;++ };++ fs.closeSync = function (fd) {++ descriptors.delete(fd);++ return originalClose.call(fs, fd);++ };++ try {++ callback();++ assert.ok(injected, 'The destination writable-open boundary must be exercised');++ assert.strictEqual(descriptors.size, 0, 'Every owned writable descriptor must close');++ } finally {++ fs.openSync = originalOpen;++ fs.closeSync = originalClose;++ }++}++++function assertPriorOwnership(value, filePath) {++ const after = readInstallState(value.installStatePath);++ const prior = value.state.operations.find(operation => operation.destinationPath === filePath);++ const current = after.operations.find(operation => operation.destinationPath === filePath);++ assert.strictEqual(current.contentSha256, prior.contentSha256, 'Do not adopt raced bytes');++ assert.strictEqual(after.request.hookConsent, value.state.request.hookConsent);++}++++function runTests() {++ let passed = 0;++ let failed = 0;++ const test = (name, callback) => {++ try { callback(); passed++; console.log(` PASS ${name}`); }++ catch (error) { failed++; console.error(` FAIL ${name}: ${error.stack}`); }++ };++ for (const relativePath of ['plugins/ecc-hooks.ts', 'opencode.json']) {++ for (const mode of ['apply', 'repair']) {++ test(`${mode} preserves a same-inode ${relativePath} edit at writable open`, () => fixture(value => {++ const destination = path.join(value.targetRoot, relativePath);++ const content = relativePath === 'opencode.json'++ ? '{"plugin":["./plugins"],"userEdit":"keep"}\n' : '// user edit: preserve this\n';++ withWritableOpenMutation(destination, () => fs.writeFileSync(destination, content), () => {++ if (mode === 'apply') {++ assert.throws(() => applyInstallPlan(value.declinePlan), /changed after preflight/i);++ } else {++ const result = repair(value).results[0];++ assert.strictEqual(result.status, 'error');++ assert.match(result.error, /changed after preflight/i);++ assert.notStrictEqual(result.stateRefreshed, true);++ }++ assert.strictEqual(fs.readFileSync(destination, 'utf8'), content);++ assertPriorOwnership(value, destination);++ });++ }, mode === 'apply'));++ }++ }++ for (const mode of ['apply', 'repair']) {++ test(`${mode} preserves a file created after expected absence`, () => fixture(value => {++ const destination = path.join(value.targetRoot, 'plugins/ecc-hooks.ts');++ fs.unlinkSync(destination);++ const content = '// newly created user file\n';++ withWritableOpenMutation(destination, () => fs.writeFileSync(destination, content), () => {++ if (mode === 'apply') assert.throws(() => applyInstallPlan(value.declinePlan), /EEXIST|changed after preflight/i);++ else assert.strictEqual(repair(value).results[0].status, 'error');++ assert.strictEqual(fs.readFileSync(destination, 'utf8'), content);++ assertPriorOwnership(value, destination);++ });++ }, mode === 'apply'));++ test(`${mode} does not recreate an expected existing file removed at open`, () => fixture(value => {++ const destination = path.join(value.targetRoot, 'opencode.json');++ withWritableOpenMutation(destination, () => fs.unlinkSync(destination), () => {++ if (mode === 'apply') assert.throws(() => applyInstallPlan(value.declinePlan), /ENOENT|changed after preflight/i);++ else assert.strictEqual(repair(value).results[0].status, 'error');++ assert.strictEqual(fs.existsSync(destination), false);++ assertPriorOwnership(value, destination);++ });++ }, mode === 'apply'));++ }++ for (const mode of ['apply', 'doctor', 'repair']) {++ test(`${mode} reports malformed activation config with source context`, () => fixture(value => {++ const destination = path.join(value.targetRoot, 'opencode.json');++ fs.writeFileSync(destination, '{ malformed');++ const before = fs.readFileSync(value.installStatePath);++ if (mode === 'apply') assert.throws(() => applyInstallPlan(value.declinePlan), /Failed to parse .*opencode\.json/);++ else if (mode === 'repair') assert.match(repair(value).results[0].error, /Failed to parse .*opencode\.json/);++ else {++ const result = buildDoctorReport({ repoRoot: value.sourceRoot, homeDir: value.homeDir,++ projectRoot: value.homeDir, targets: ['opencode'] }).results[0];++ assert.match(JSON.stringify(result.issues), /Failed to parse .*opencode\.json/);++ }++ assert.strictEqual(fs.readFileSync(destination, 'utf8'), '{ malformed');++ assert.deepStrictEqual(fs.readFileSync(value.installStatePath), before);++ }));++ }++ test('apply rejects another enabled writer and repair while holding its target lease', () => fixture(value => {++ let checked = false;++ applyInstallPlan(value.declinePlan, {++ beforeOperationWrite() {++ if (checked) return;++ checked = true;++ assert.throws(() => applyInstallPlan(withHookConsent(value.basePlan, 'enabled')), /Another ECC process|OpenCode.*lock/i);++ assert.strictEqual(repair(value).results[0].status, 'error');++ },++ });++ assert.ok(checked);++ assert.strictEqual(fs.existsSync(`${value.installStatePath}.ecc.lock`), false);++ assert.strictEqual(applyInstallPlan(value.declinePlan).applied, true);++ }));++ test('repair preserves ownership for a destination-classified activation with a recorded transform', () => fixture(value => {++ const operation = value.state.operations.find(entry => entry.sourceRelativePath.endsWith('ecc-hooks.ts'));++ const oldDestination = operation.destinationPath;++ operation.sourceRelativePath = '.opencode/tools/fixture.js';++ operation.contentTransform = 'opencode-disable-plugin-entrypoint';++ operation.destinationPath = path.join(value.targetRoot, 'plugins', 'custom.js');++ const source = path.join(value.sourceRoot, operation.sourceRelativePath);++ fs.mkdirSync(path.dirname(source), { recursive: true });++ fs.copyFileSync(oldDestination, source);++ fs.unlinkSync(oldDestination);++ writeInstallState(value.installStatePath, value.state);++ const content = '// preserve unowned new custom plugin\n';++ withWritableOpenMutation(operation.destinationPath, () => fs.writeFileSync(operation.destinationPath, content), () => {++ const result = repair(value).results[0];++ assert.strictEqual(result.status, 'error');++ assert.match(result.error, /changed after preflight/i);++ assert.strictEqual(fs.readFileSync(operation.destinationPath, 'utf8'), content);++ assertPriorOwnership(value, operation.destinationPath);++ });++ }));++ test('repair completes historical deactivation with exact inert bytes and releases its lock', () => fixture(value => {++ const result = repair(value).results[0];++ assert.strictEqual(result.status, 'repaired', result.error);++ assert.strictEqual(result.stateRefreshed, true);++ assert.strictEqual(fs.readFileSync(path.join(value.targetRoot, 'plugins/ecc-hooks.ts'), 'utf8'),++ 'export default async () => ({});\n');++ assert.deepStrictEqual(JSON.parse(fs.readFileSync(path.join(value.targetRoot, 'opencode.json'))),++ { plugin: [], userSetting: true });++ assert.strictEqual(fs.existsSync(`${value.installStatePath}.ecc.lock`), false);++ }));++ test('repair preserves the primary failure and replacement lock when release also fails', () => fixture(value => {++ const destination = path.join(value.targetRoot, 'opencode.json');++ const lock = `${value.installStatePath}.ecc.lock`;++ withWritableOpenMutation(destination, () => {++ fs.writeFileSync(destination, '{"userEdit":true}');++ fs.renameSync(lock, `${lock}.owned`);++ fs.writeFileSync(lock, 'replacement lock');++ }, () => {++ const result = repair(value).results[0];++ assert.strictEqual(result.status, 'error');++ assert.match(result.error, /changed after preflight/i);++ assert.match(result.releaseError, /changed OpenCode install lock/);++ assert.strictEqual(fs.readFileSync(lock, 'utf8'), 'replacement lock');++ assertPriorOwnership(value, destination);++ });++ }));++ console.log(`\nResults: Passed: ${passed}, Failed: ${failed}`);++ return { passed, failed };++}++++if (require.main === module) process.exitCode = runTests().failed ? 1 : 0;++module.exports = { runTests };diff --cc tests/lib/opencode-install-lock.test.jsindex 000000000,000000000..44e01569fnew file mode 100644--- /dev/null+++ b/tests/lib/opencode-install-lock.test.js@@@ -1,0 -1,0 +1,237 @@@++/** Cooperative OpenCode installation lock scopes, without child processes. */++'use strict';++const assert = require('assert');++const fs = require('fs');++const os = require('os');++const path = require('path');++const { acquireOpenCodeInstallLocks, withOpenCodeInstallLocks } = require('../../scripts/lib/install/opencode-install-lock');++const { acquireSettingsLock, getSettingsLockIdentity, sameFileIdentity } = require('../../scripts/lib/install/claude-settings-lock');++let passed = 0;++let failed = 0;++const lockPath = root => path.join(root, 'ecc-install-state.json.ecc.lock');++function test(name, callback) {++ const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-opencode-lock-')));++ try { callback(root); passed++; console.log(` PASS ${name}`); }++ catch (error) { failed++; console.error(` FAIL ${name}: ${error.stack}`); }++ finally { fs.rmSync(root, { recursive: true, force: true }); }++}++test('same target refuses an independent writer and releases on success', root => {++ assert.strictEqual(withOpenCodeInstallLocks([root], lease => {++ assert.ok(Object.isFrozen(lease));++ assert.ok(fs.existsSync(lockPath(root)));++ assert.throws(() => acquireOpenCodeInstallLocks([root]), /Another ECC process.*OpenCode/);++ return 'done';++ }), 'done');++ assert.strictEqual(fs.existsSync(lockPath(root)), false);++});++test('different roots can be held independently', root => {++ const other = path.join(root, 'other');++ withOpenCodeInstallLocks([root], () => withOpenCodeInstallLocks([other], () => {++ assert.ok(fs.existsSync(lockPath(root)) && fs.existsSync(lockPath(other)));++ }));++ assert.strictEqual(fs.existsSync(lockPath(other)), false);++});++test('roots are deduplicated, sorted and released in reverse order', root => {++ const a = path.join(root, 'a');++ const b = path.join(root, 'b');++ const linked = [];++ const renamed = [];++ const originalLink = fs.linkSync;++ const originalRename = fs.renameSync;++ fs.linkSync = (from, to) => { linked.push(to); return originalLink(from, to); };++ fs.renameSync = (from, to) => { renamed.push(from); return originalRename(from, to); };++ try { withOpenCodeInstallLocks([b, a, b], () => {}); }++ finally { fs.linkSync = originalLink; fs.renameSync = originalRename; }++ assert.deepStrictEqual(linked, [lockPath(a), lockPath(b)]);++ assert.deepStrictEqual(renamed, [lockPath(b), lockPath(a)]);++});++test('nested use requires a real active lease with full coverage', root => {++ const holder = acquireOpenCodeInstallLocks([root]);++ const nested = acquireOpenCodeInstallLocks([root], holder.lease);++ assert.strictEqual(nested.lease, holder.lease);++ nested.release();++ assert.ok(fs.existsSync(lockPath(root)));++ assert.throws(() => acquireOpenCodeInstallLocks([path.join(root, 'missing')], holder.lease), /cover/);++ assert.throws(() => acquireOpenCodeInstallLocks([root], true), /lease/);++ assert.throws(() => acquireOpenCodeInstallLocks([root], {}), /lease/);++ holder.release();++ holder.release();++ assert.throws(() => acquireOpenCodeInstallLocks([root], holder.lease), /lease/);++});++test('callback error retains identity and releases', root => {++ const primary = new Error('callback failure');++ assert.throws(() => withOpenCodeInstallLocks([root], () => { throw primary; }), error => error === primary);++ assert.strictEqual(fs.existsSync(lockPath(root)), false);++});++test('second lock failure releases the first without disturbing the other owner', root => {++ const a = path.join(root, 'a');++ const b = path.join(root, 'b');++ const other = acquireOpenCodeInstallLocks([b]);++ const bytes = fs.readFileSync(lockPath(b));++ try { assert.throws(() => acquireOpenCodeInstallLocks([b, a]), /Another ECC process/); }++ finally { assert.deepStrictEqual(fs.readFileSync(lockPath(b)), bytes); other.release(); }++ assert.strictEqual(fs.existsSync(lockPath(a)), false);++});++test('a replaced lock invalidates nested reuse and is preserved on release', root => {++ const holder = acquireOpenCodeInstallLocks([root]);++ fs.renameSync(lockPath(root), `${lockPath(root)}.owned`);++ fs.writeFileSync(lockPath(root), 'replacement');++ assert.throws(() => acquireOpenCodeInstallLocks([root], holder.lease), /changed/);++ assert.throws(() => holder.release(), /changed/);++ assert.strictEqual(fs.readFileSync(lockPath(root), 'utf8'), 'replacement');++});++test('release failure is attached without hiding the callback failure', root => {++ const primary = new Error('primary');++ assert.throws(() => withOpenCodeInstallLocks([root], () => {++ fs.renameSync(lockPath(root), `${lockPath(root)}.owned`);++ fs.writeFileSync(lockPath(root), 'replacement');++ throw primary;++ }), error => error === primary && /changed/.test(error.releaseError.message));++ assert.strictEqual(fs.readFileSync(lockPath(root), 'utf8'), 'replacement');++});++test('invalid root and non-file lock paths refuse before callback', root => {++ for (const roots of [null, ['relative'], [true], ['']]) {++ assert.throws(() => acquireOpenCodeInstallLocks(roots), /root/);++ }++ fs.mkdirSync(lockPath(root));++ assert.throws(() => withOpenCodeInstallLocks([root], () => assert.fail('must refuse')), /lock/);++});++test('lock engine still recovers a stale malformed lock', root => {++ fs.writeFileSync(lockPath(root), 'stale');++ const old = new Date(Date.now() - 600000);++ fs.utimesSync(lockPath(root), old, old);++ withOpenCodeInstallLocks([root], () => assert.match(fs.readFileSync(lockPath(root), 'utf8'), /"pid"/));++ assert.strictEqual(fs.existsSync(lockPath(root)), false);++});++test('a root or lock reported as a symlink refuses without callback or outside access', root => {++ for (const target of [root, lockPath(root)]) {++ if (target !== root) fs.writeFileSync(target, 'unrelated target');++ const original = fs.lstatSync;++ fs.lstatSync = (...args) => {++ const stats = original(...args);++ if (args[0] === target) {++ const symlink = Object.create(stats);++ symlink.isSymbolicLink = () => true;++ return symlink;++ }++ return stats;++ };++ try {++ assert.throws(() => withOpenCodeInstallLocks([root], () => assert.fail('must refuse')), /symlink/);++ } finally { fs.lstatSync = original; }++ if (target !== root) assert.strictEqual(fs.readFileSync(target, 'utf8'), 'unrelated target');++ }++});++test('permission errors remain permission errors', root => {++ const original = fs.lstatSync;++ const denied = Object.assign(new Error('permission denied'), { code: 'EACCES' });++ fs.lstatSync = (...args) => { if (args[0] === lockPath(root)) throw denied; return original(...args); };++ try { assert.throws(() => acquireOpenCodeInstallLocks([root]), error => error === denied); }++ finally { fs.lstatSync = original; }++ assert.strictEqual(fs.existsSync(lockPath(root)), false);++});++test('releasing all roots continues after one replaced lock and rejects later lease reuse', root => {++ const a = path.join(root, 'a');++ const b = path.join(root, 'b');++ const holder = acquireOpenCodeInstallLocks([a, b]);++ fs.renameSync(lockPath(b), `${lockPath(b)}.owned`);++ fs.writeFileSync(lockPath(b), 'replacement');++ assert.throws(() => holder.release(), /changed/);++ assert.strictEqual(fs.existsSync(lockPath(a)), false);++ assert.strictEqual(fs.readFileSync(lockPath(b), 'utf8'), 'replacement');++ assert.throws(() => acquireOpenCodeInstallLocks([a], holder.lease), /lease/);++});++test('a root replaced during a held scope is preserved while other roots release and the lease expires', root => {++ const a = path.join(root, 'a');++ const b = path.join(root, 'b');++ const movedRoot = path.join(root, 'b-original');++ const replacementState = path.join(b, 'ecc-install-state.json');++ let heldLease;++ let originalLockBytes;++ assert.throws(() => withOpenCodeInstallLocks([a, b], lease => {++ heldLease = lease;++ originalLockBytes = fs.readFileSync(lockPath(b));++ fs.renameSync(b, movedRoot);++ fs.mkdirSync(b);++ fs.writeFileSync(lockPath(b), 'replacement root lock');++ fs.writeFileSync(replacementState, 'replacement root state');++ return 'release must refuse instead of returning this result';++ }), /Refusing changed OpenCode install lock root/);++ assert.strictEqual(fs.existsSync(lockPath(a)), false);++ assert.strictEqual(fs.readFileSync(lockPath(b), 'utf8'), 'replacement root lock');++ assert.strictEqual(fs.readFileSync(replacementState, 'utf8'), 'replacement root state');++ assert.deepStrictEqual(fs.readdirSync(b).sort(), ['ecc-install-state.json', 'ecc-install-state.json.ecc.lock']);++ assert.deepStrictEqual(fs.readFileSync(lockPath(movedRoot)), originalLockBytes);++ assert.throws(() => acquireOpenCodeInstallLocks([a, b], heldLease), /Invalid or inactive OpenCode install lease/);++ withOpenCodeInstallLocks([a], () => assert.ok(fs.existsSync(lockPath(a))));++ assert.strictEqual(fs.existsSync(lockPath(a)), false);++});++test('an absent callback is rejected before a lock is created', root => {++ assert.throws(() => withOpenCodeInstallLocks([root], null), /callback/);++ assert.strictEqual(fs.existsSync(lockPath(root)), false);++});++test('a replacement immediately after lock publication cannot enter the protected callback', root => {++ const target = lockPath(root);++ const originalLink = fs.linkSync;++ let callbacks = 0;++ let replacements = 0;++ fs.linkSync = (from, to) => {++ originalLink(from, to);++ if (to === target) {++ replacements++;++ fs.renameSync(target, `${target}.owned`);++ fs.writeFileSync(target, 'replacement at acquisition boundary');++ }++ };++ try {++ assert.throws(() => withOpenCodeInstallLocks([root], () => { callbacks++; }), /changed .*lock/);++ } finally { fs.linkSync = originalLink; }++ assert.strictEqual(replacements, 1);++ assert.strictEqual(callbacks, 0, 'A pathname replacement must never become the acquired identity');++ assert.strictEqual(fs.readFileSync(target, 'utf8'), 'replacement at acquisition boundary');++ assert.strictEqual(JSON.parse(fs.readFileSync(`${target}.owned`, 'utf8')).pid, process.pid);++});++test('a transient post-acquisition validation failure releases authentic locks and preserves the primary error', root => {++ const a = path.join(root, 'a');++ const b = path.join(root, 'b');++ const primary = Object.assign(new Error('one-shot validation error'), { code: 'EIO' });++ const originalLink = fs.linkSync;++ const originalStat = fs.lstatSync;++ let published = false;++ let faults = 0;++ let callbacks = 0;++ let caught;++ fs.linkSync = (from, to) => {++ originalLink(from, to);++ if (to === lockPath(b)) published = true;++ };++ fs.lstatSync = (...args) => {++ if (published && args[0] === b && faults === 0) { faults++; throw primary; }++ return originalStat(...args);++ };++ try {++ try { withOpenCodeInstallLocks([a, b], () => { callbacks++; }); }++ catch (error) { caught = error; }++ } finally { fs.linkSync = originalLink; fs.lstatSync = originalStat; }++ assert.strictEqual(faults, 1);++ assert.strictEqual(callbacks, 0);++ assert.strictEqual(caught, primary);++ assert.strictEqual(caught.releaseError, undefined, 'Cleanup must not dereference a missing identity');++ assert.strictEqual(fs.existsSync(lockPath(a)), false);++ assert.strictEqual(fs.existsSync(lockPath(b)), false);++});++test('engine ownership metadata is immutable and derived from the acquired descriptor', root => {++ const settingsPath = path.join(root, 'settings.json');++ const release = acquireSettingsLock(settingsPath);++ try {++ const identity = getSettingsLockIdentity(release);++ assert.ok(Object.isFrozen(identity));++ assert.deepStrictEqual(Object.keys(identity).sort(), ['dev', 'ino']);++ assert.ok(sameFileIdentity(identity, fs.lstatSync(`${settingsPath}.ecc.lock`, { bigint: true })));++ assert.throws(() => { identity.ino = 0n; }, TypeError);++ assert.throws(() => getSettingsLockIdentity(() => {}), /identity/);++ } finally { release(); }++ assert.strictEqual(fs.existsSync(`${settingsPath}.ecc.lock`), false);++});++console.log(`Results: Passed: ${passed}, Failed: ${failed}`);++process.exitCode = failed ? 1 : 0;