Skip to content

armgit / ECC

Public Imported from GitHub
0

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

fix(install): reconcile OpenCode hook consent with current main

affaan-m4be4eb4cf33f
diff --cc scripts/lib/install-lifecycle.js
index 1bc36fe6e,ec9cb1d80..c50f29b88
--- a/scripts/lib/install-lifecycle.js
+++ b/scripts/lib/install-lifecycle.js
@@@ -8,10 -9,7 +9,12 @@@ const { loadInstallManifests } = requir
const { readInstallState, validateInstallState } = require('./install-state');
const { assertWithinTrustedRoot } = require('./path-safety');
const { createInstallPlanFromRequest } = require('./install/runtime');
-const { getRecordedHookConsent } = require('./install/hook-consent');
+const {
+ disableOpenCodeHookPluginRegistration,
++ getDisabledOpenCodePluginContent,
+ getRecordedHookConsent,
++ withHookConsent,
+} = require('./install/hook-consent');
const {
prepareClaudeSkillMigration,
} = require('./install/claude-skill-migration');
@@@ -220,9 -230,6 +235,12 @@@ function transformCopyFileContent(opera
if (operation.contentTransform === 'antigravity-agent-frontmatter') {
return adaptAntigravityAgent(content, operation.sourceRelativePath);
}
+ if (operation.contentTransform === 'opencode-disable-ecc-hooks') {
+ return disableOpenCodeHookPluginRegistration(content, operation.sourceRelativePath);
+ }
++ if (operation.contentTransform === 'opencode-disable-plugin-entrypoint') {
++ return getDisabledOpenCodePluginContent();
++ }
throw new Error(`Unknown install content transform: ${operation.contentTransform}`);
}
@@@ -1447,6 -1627,6 +1638,14 @@@ function analyzeRecord(record, context
};
}
++ if (record.adapter.target === 'opencode') {
++ try {
++ preflightOpenCodeHookDeactivation(record, context, { requireInactive: true });
++ } catch (error) {
++ issues.push(buildIssue('error', 'opencode-hook-consent-violation', error.message));
++ }
++ }
++
if (!fs.existsSync(state.target.root)) {
issues.push(buildIssue('error', 'missing-target-root', `Target root does not exist: ${state.target.root}`));
}
@@@ -1620,10 -1812,14 +1831,14 @@@ function createRepairPlanFromRecord(rec
record.legacyLayout !== 'opencode'
&& (state.request.legacyMode || shouldRepairFromRecordedOperations(state))
) {
- const operations = hydrateRecordedOperations(context.repoRoot, getManagedOperations(state));
+ const operations = hydrateRecordedOperations(
+ context.repoRoot,
+ getManagedOperations(state),
+ record.targetRoot
+ );
const statePreview = buildRecordedStatePreview(state, context, operations);
-- return {
++ const recordedPlan = {
mode: state.request.legacyMode ? 'legacy' : 'recorded',
target: record.adapter.target,
adapter: record.adapter,
@@@ -1632,9 -1828,9 +1847,13 @@@
installStatePath: state.target.installStatePath,
warnings: [],
languages: Array.isArray(state.request.legacyLanguages) ? [...state.request.legacyLanguages] : [],
++ selectedModuleIds: [...(state.resolution.selectedModules || [])],
operations,
statePreview
};
++ return record.adapter.target === 'opencode'
++ ? withHookConsent(recordedPlan, getRecordedHookConsent(state))
++ : recordedPlan;
}
const desiredPlan = resolveRecordedManifestPlan(record, context, options);
@@@ -1712,7 -1908,7 +1931,10 @@@ function prepareRepairMigration(plan, r
installStatePath: record.installStatePath,
statePreview: buildAdapterDerivedStatePreview(plan.statePreview, record),
};
-- const migration = prepareClaudeSkillMigration(trustedPlan);
++ const initialMigration = prepareClaudeSkillMigration(trustedPlan);
++ const migration = trustedPlan.target === 'opencode'
++ ? require('./install/apply').prepareHookConsentMigration(trustedPlan, initialMigration)
++ : initialMigration;
return {
migration,
plan: {
@@@ -1727,6 -1923,6 +1949,48 @@@
};
}
++function assertOpenCodeRepairHookDeactivation(plan, options = {}) {
++ if (plan.target !== 'opencode') {
++ return new Map();
++ }
++ // The installer imports lifecycle helpers. Resolve this shared read-only
++ // guard lazily so both paths enforce the same discovery/ownership boundary.
++ const { assertOpenCodeHookDeactivationReady } = require('./install/apply');
++ return assertOpenCodeHookDeactivationReady(plan, options);
++}
++
++function preflightOpenCodeHookDeactivation(record, context, options = {}) {
++ if (record.adapter.target !== 'opencode') {
++ return;
++ }
++ const rawPlan = createRepairPlanFromRecord(record, context, {
++ // Planning must reject unsafe existing activations before a repair build
++ // writes compiled files. Missing payload is still validated/built later.
++ exemptValidationCodes: [OPENCODE_PLUGIN_NOT_BUILT_CODE],
++ });
++ if (record.legacyLayout === 'opencode') {
++ const state = record.state;
++ const legacyPlan = withHookConsent({
++ target: 'opencode',
++ adapter: record.adapter,
++ targetRoot: record.targetRoot,
++ installRoot: record.targetRoot,
++ installStatePath: record.installStatePath,
++ selectedModuleIds: [...(state.resolution.selectedModules || [])],
++ operations: getManagedOperations(state),
++ statePreview: buildAdapterDerivedStatePreview(state, record),
++ }, getRecordedHookConsent(state));
++ // Migration does not replay operations into the old root. Inspect existing
++ // activations there, without treating historical merge-json records as new
++ // writes; the canonical destination is validated separately below.
++ assertOpenCodeRepairHookDeactivation({ ...legacyPlan, operations: [] }, { requireInactive: true });
++ assertOpenCodeRepairHookDeactivation(rawPlan, options);
++ return;
++ }
++ const { plan } = prepareRepairMigration(rawPlan, record);
++ assertOpenCodeRepairHookDeactivation(plan, options);
++}
++
function repairInstalledStates(options = {}) {
const repoRoot = options.repoRoot || DEFAULT_REPO_ROOT;
const manifests = loadInstallManifests({ repoRoot });
@@@ -1763,7 -1959,17 +2027,18 @@@
};
}
+ 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);
@@@ -1789,6 -1995,6 +2064,7 @@@
? [OPENCODE_PLUGIN_NOT_BUILT_CODE]
: [],
});
++ assertOpenCodeRepairHookDeactivation(canonicalPlan);
const plannedRepairs = [...new Set([
...(needsOpencodeBuild ? [opencodeBuildRepairPath] : []),
...canonicalPlan.operations.map(operation => operation.destinationPath),
@@@ -1879,6 -2086,6 +2156,7 @@@
migration,
plan: desiredPlan,
} = prepareRepairMigration(rawPlan, record);
++ const activationSnapshot = assertOpenCodeRepairHookDeactivation(desiredPlan);
const operationHealth = summarizeManagedOperationHealth(
context.repoRoot,
record.targetRoot,
@@@ -1931,11 -2152,11 +2223,23 @@@
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);
++ }
const repairedPath = executeRepairOperation(
context.repoRoot,
operation,
@@@ -1969,6 -2192,6 +2275,7 @@@
installedAt: record.state.installedAt,
source: { ...record.state.source },
};
++ assertOpenCodeRepairHookDeactivation(desiredPlan, { requireInactive: true });
writeRefreshedInstallState(record, statePreviewToWrite);
return {
diff --cc scripts/lib/install/apply.js
index d5870feaf,fbab1293b..f41cd4806
--- a/scripts/lib/install/apply.js
+++ b/scripts/lib/install/apply.js
@@@ -8,12 -8,18 +8,27 @@@ const
hasExplicitCommitAttributionPreference,
withCommitAttributionDisabled,
} = require('../claude-commit-attribution');
- const { writeInstallState } = require('../install-state');
+ const { readInstallState, writeInstallState } = require('../install-state');
-const { assertHookConsentReady, planMaterializesHookRuntime } = require('./hook-consent');
+const {
+ assertHookConsentReady,
+ disableOpenCodeHookPluginRegistration,
++ getDisabledOpenCodePluginContent,
++ getRecordedHookConsent,
++ isOpenCodeHookActivationOperation,
++ isOpenCodePluginEntrypoint,
+ planMaterializesHookRuntime,
++ shouldDisableOpenCodeHooks,
+} = require('./hook-consent');
+ const {
+ getClaudeSettingsPath,
+ mergeManagedHooks,
+ readSettings,
+ runWithSettingsLock,
+ uninstallManagedHooks,
+ updateSettingsAtomic,
+ validateManagedHooks,
+ validateRecordedManagedHooks,
+ } = require('./claude-settings');
const { filterMcpConfig, parseDisabledMcpServers } = require('../mcp-config');
const { assertWithinTrustedRoot } = require('../path-safety');
const {
@@@ -37,9 -48,6 +57,12 @@@ function transformInstallContent(operat
if (operation.contentTransform === 'antigravity-agent-frontmatter') {
return adaptAntigravityAgent(content, operation.sourceRelativePath);
}
+ if (operation.contentTransform === 'opencode-disable-ecc-hooks') {
+ return disableOpenCodeHookPluginRegistration(content, operation.sourceRelativePath);
+ }
++ if (operation.contentTransform === 'opencode-disable-plugin-entrypoint') {
++ return getDisabledOpenCodePluginContent();
++ }
throw new Error(`Unknown install content transform: ${operation.contentTransform}`);
}
@@@ -309,40 -276,135 +291,268 @@@ function assertSafeInstallOperation(pla
}
}
- function buildResolvedClaudeHooks(plan) {
- if (!plan.adapter || (plan.adapter.target !== 'claude' && plan.adapter.target !== 'claude-project')) {
+ function readPreviousInstallState(plan) {
+ if (!fs.existsSync(plan.installStatePath)) {
return null;
}
+ return readInstallState(plan.installStatePath);
+ }
+
+ function comparablePath(filePath) {
+ const resolved = path.resolve(filePath);
+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
+ }
+
++function openCodeActivationKind(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) {
++ 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);
++ 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))
++ .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 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;
++}
+
- const pluginRoot = plan.targetRoot;
- const hooksDestinationPath = path.join(plan.targetRoot, 'hooks', 'hooks.json');
- const hooksOperation = findHooksOperation(plan, hooksDestinationPath);
- if (!hooksOperation) {
++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 findPreviousManagedHooks(previousState, plan, operation) {
+ if (
+ !previousState
+ || previousState.target.id !== plan.adapter.id
+ || comparablePath(previousState.target.root) !== comparablePath(plan.targetRoot)
+ || comparablePath(previousState.target.installStatePath) !== comparablePath(plan.installStatePath)
+ ) {
return null;
}
- const hooksSourcePath = hooksOperation.sourcePath;
- if (!fs.existsSync(hooksSourcePath)) {
+
+ const previousOperation = (previousState.operations || []).find(candidate => (
+ candidate.kind === operation.kind
+ && comparablePath(candidate.destinationPath) === comparablePath(operation.destinationPath)
+ ));
+ if (!previousOperation || !previousOperation.managedHooks) {
return null;
}
- const hooksConfig = readJsonObject(hooksSourcePath, 'hooks config');
- const resolvedHooks = replacePluginRootPlaceholders(hooksConfig.hooks, pluginRoot);
- if (!resolvedHooks || typeof resolvedHooks !== 'object' || Array.isArray(resolvedHooks)) {
- throw new Error(`Invalid hooks config at ${hooksSourcePath}: expected "hooks" to be a JSON object`);
+ return validateRecordedManagedHooks(
+ previousOperation.managedHooks,
+ 'previous managed hooks'
+ );
+ }
+
+ function preflightClaudeSettingsOperations(plan) {
+ const settingsOperations = plan.operations.filter(operation => (
+ operation.kind === 'update-claude-settings'
+ || operation.kind === 'remove-claude-settings-hooks'
+ ));
+ if (settingsOperations.length === 0) {
+ return new Map();
}
+ const previousState = readPreviousInstallState(plan);
+ return new Map(settingsOperations.map(operation => {
+ assertSafeInstallOperation(plan, operation);
+ const managedHooks = validateManagedHooks(operation.managedHooks);
+ const settings = readSettings(operation.destinationPath);
+ const previousManagedHooks = findPreviousManagedHooks(previousState, plan, operation);
+ if (operation.kind === 'remove-claude-settings-hooks') {
+ const removal = uninstallManagedHooks(settings, managedHooks);
+ if (removal.retained.length > 0) {
+ throw new Error(
+ `Refusing to disable modified Claude hooks in ${operation.destinationPath}; `
+ + 'run the ECC uninstaller to review retained entries.'
+ );
+ }
+ } else {
+ mergeManagedHooks(settings, managedHooks, { previousManagedHooks });
+ }
+ return [operation, { managedHooks, previousManagedHooks }];
+ }));
+ }
+
+ function prepareHookConsentMigration(plan, migration) {
++ if (shouldDisableOpenCodeHooks(plan) && migration.requiresBridgeState) {
++ const previousState = readPreviousInstallState(plan);
++ if (previousState) {
++ const previousConsent = getRecordedHookConsent(previousState);
++ return {
++ ...migration,
++ // A checkpoint is not a completed consent transition. On failure,
++ // retain the previous decision until every activation is inactive.
++ bridgeState: {
++ ...migration.bridgeState,
++ request: { ...migration.bridgeState.request, hookConsent: previousConsent },
++ resolution: {
++ ...migration.bridgeState.resolution,
++ selectedModules: previousConsent === 'enabled'
++ ? [...new Set([...migration.bridgeState.resolution.selectedModules, 'hooks-runtime'])]
++ : migration.bridgeState.resolution.selectedModules,
++ },
++ },
++ };
++ }
++ }
+ if (plan.hookConsent !== 'declined') {
+ return migration;
+ }
+ const previousState = readPreviousInstallState(plan);
+ if (!previousState) {
+ return migration;
+ }
+
+ const removals = (previousState.operations || [])
+ .filter(operation => operation.kind === 'update-claude-settings')
+ .map(operation => ({
+ ...operation,
+ kind: 'remove-claude-settings-hooks',
+ strategy: 'remove-hook-ids',
+ scaffoldOnly: false,
+ }));
+ if (removals.length === 0) {
+ return migration;
+ }
+ const removalDestinations = new Set(removals.map(operation => comparablePath(
+ operation.destinationPath
+ )));
return {
- hooksOperation,
- hooksDestinationPath,
- resolvedHooksConfig: {
- ...hooksConfig,
- hooks: resolvedHooks,
+ ...migration,
+ // Disable hooks only after every ordinary install operation succeeds so a
+ // partial reinstall cannot silently revoke working hooks before failing.
+ appliedOperations: [...migration.appliedOperations, ...removals],
+ finalState: {
+ ...migration.finalState,
+ operations: migration.finalState.operations.filter(operation => !(
+ operation.kind === 'update-claude-settings'
+ && removalDestinations.has(comparablePath(operation.destinationPath))
+ )),
+ },
+ bridgeState: {
+ ...migration.bridgeState,
+ request: {
+ ...migration.bridgeState.request,
+ hookConsent: 'enabled',
+ },
+ resolution: {
+ ...migration.bridgeState.resolution,
+ selectedModules: [...new Set([
+ ...migration.bridgeState.resolution.selectedModules,
+ 'hooks-runtime',
+ ])],
+ },
},
+ requiresBridgeState: true,
};
}
function previewInstallPlan(plan) {
- const migration = prepareClaudeSkillMigration(plan);
++ assertOpenCodeHookDeactivationReady(plan);
+ const migration = prepareHookConsentMigration(
+ plan,
+ prepareUserOwnedFileGuard(plan, prepareClaudeSkillMigration(plan))
+ );
+ const appliedPlan = {
+ ...plan,
+ operations: migration.appliedOperations,
+ };
+ preflightClaudeSettingsOperations(appliedPlan);
const hookConsentWarnings = planMaterializesHookRuntime(plan) && plan.hookConsent !== 'enabled'
? ['Applying this plan requires an explicit hook decision: --enable-hooks or --no-hooks.']
: [];
@@@ -370,7 -449,10 +597,11 @@@ function applyInstallPlanLocked(plan, d
if (typeof beforeInstallStateRead === 'function') {
beforeInstallStateRead({ plan });
}
- const migration = prepareClaudeSkillMigration(plan);
++ const activationSnapshot = assertOpenCodeHookDeactivationReady(plan);
+ const migration = prepareHookConsentMigration(
+ plan,
+ prepareUserOwnedFileGuard(plan, prepareClaudeSkillMigration(plan))
+ );
const appliedPlan = {
...plan,
operations: migration.appliedOperations,
@@@ -405,6 -491,44 +640,45 @@@
if (typeof beforeOperationWrite === 'function') {
beforeOperationWrite({ plan: appliedPlan, operation });
}
+ assertNoNewUserOwnedFile(migration, operation);
++ assertOpenCodeActivationUnchanged(appliedPlan, operation, activationSnapshot);
+
+ if (
+ operation.kind === 'update-claude-settings'
+ || operation.kind === 'remove-claude-settings-hooks'
+ ) {
+ // Re-read at the write boundary so unrelated settings added after
+ // planning are preserved. A same-ID change still fails closed.
+ const prepared = preparedClaudeSettings.get(operation);
+ assertSafeInstallOperation(appliedPlan, operation);
+ updateSettingsAtomic(operation.destinationPath, latestSettings => {
+ const merged = operation.kind === 'remove-claude-settings-hooks'
+ ? uninstallManagedHooks(latestSettings, prepared.managedHooks)
+ : mergeManagedHooks(latestSettings, prepared.managedHooks, {
+ previousManagedHooks: prepared.previousManagedHooks,
+ });
+ if (
+ operation.kind === 'remove-claude-settings-hooks'
+ && merged.retained.length > 0
+ ) {
+ throw new Error(
+ `Refusing to disable modified Claude hooks in ${operation.destinationPath}; `
+ + 'run the ECC uninstaller to review retained entries.'
+ );
+ }
+ return merged;
+ }, {
+ lockHeld: settingsLockHeld,
+ beforeCommit() {
+ assertSafeInstallOperation(appliedPlan, operation);
+ },
+ });
+ writtenDestinations.add(operation.destinationPath);
+ if (operation.kind === 'remove-claude-settings-hooks') {
+ completedHookRemovalCount += 1;
+ }
+ continue;
+ }
if (operation.kind === 'merge-json') {
const payload = cloneJsonValue(operation.mergePayload);
@@@ -457,55 -584,59 +734,60 @@@
}
fs.copyFileSync(operation.sourcePath, operation.destinationPath);
- }
-
- if (resolvedClaudeHooksPlan) {
- assertSafeInstallOperation(appliedPlan, resolvedClaudeHooksPlan.hooksOperation);
- fs.mkdirSync(path.dirname(resolvedClaudeHooksPlan.hooksDestinationPath), { recursive: true });
- assertSafeInstallOperation(appliedPlan, resolvedClaudeHooksPlan.hooksOperation);
- if (typeof beforeOperationWrite === 'function') {
- beforeOperationWrite({ plan: appliedPlan, operation: resolvedClaudeHooksPlan.hooksOperation });
+ writtenDestinations.add(operation.destinationPath);
}
- fs.writeFileSync(
- resolvedClaudeHooksPlan.hooksDestinationPath,
- JSON.stringify(resolvedClaudeHooksPlan.resolvedHooksConfig, null, 2) + '\n',
- 'utf8'
- );
- }
-
- if (hasLegacyMigration) {
- removeLegacyClaudeSkillFiles(migration, plan.targetRoot);
- }
- if (shouldSetClaudeCommitAttributionPreference(appliedPlan)) {
- writeClaudeCommitAttributionPreference(path.join(plan.targetRoot, 'settings.json'));
- }
+ if (hasLegacyMigration) {
+ removeLegacyClaudeSkillFiles(migration, plan.targetRoot);
+ }
- finalState = stateWithContentDigests(migration.finalState, appliedPlan);
- if (typeof beforeInstallStateWrite === 'function') {
- beforeInstallStateWrite({ plan: appliedPlan, state: finalState });
- }
- persistInstallState(plan.installStatePath, finalState);
- } catch (error) {
- if (migration.requiresBridgeState) {
- try {
- // The bridge was committed before any writes. Refresh it with hashes of
- // files that now exist so uninstall can remove only bytes this attempt
- // actually installed while preserving user changes.
- persistInstallState(
- plan.installStatePath,
- stateWithContentDigests(migration.bridgeState, appliedPlan)
- );
- } catch (checkpointError) {
- throw new Error(
- `${error.message} Install-state checkpoint also failed: ${checkpointError.message}`,
- { cause: error }
+ if (shouldSetClaudeCommitAttributionPreference(appliedPlan)) {
+ writeClaudeCommitAttributionPreference(
+ getClaudeSettingsPath(plan.targetRoot),
+ { lockHeld: settingsLockHeld }
);
}
+
++ assertOpenCodeHookDeactivationReady(appliedPlan, { requireInactive: true });
+ finalState = stateWithContentDigests(migration.finalState, appliedPlan);
+ if (typeof beforeInstallStateWrite === 'function') {
+ beforeInstallStateWrite({ plan: appliedPlan, state: finalState });
+ }
+ persistInstallState(plan.installStatePath, finalState);
+ } catch (error) {
+ if (migration.requiresBridgeState) {
+ try {
+ // The bridge was committed before any writes. Refresh it with hashes of
+ // files that now exist so uninstall can remove only bytes this attempt
+ // actually installed while preserving user changes.
+ persistInstallState(
+ plan.installStatePath,
+ stateWithContentDigests(
+ preserveUnwrittenFiles(
+ hookRemovalCount > 0 && completedHookRemovalCount === hookRemovalCount
+ ? migration.finalState
+ : migration.bridgeState,
+ migration,
+ writtenDestinations
+ ),
+ {
+ ...appliedPlan,
+ operations: appliedPlan.operations.filter(operation => (
+ writtenDestinations.has(operation.destinationPath)
+ )),
+ }
+ )
+ );
+ } catch (checkpointError) {
+ throw new Error(
+ `${error.message} Install-state checkpoint also failed: ${checkpointError.message}`,
+ { cause: error }
+ );
+ }
+ }
+ throw error;
}
- throw error;
- }
- let antigravityMigrationWarnings = [];
+ let antigravityMigrationWarnings = [];
try {
const antigravityMigration = cleanupLegacyAntigravityInstall(appliedPlan);
if (antigravityMigration.detected && !antigravityMigration.complete) {
@@@ -553,6 -684,6 +835,9 @@@
module.exports = {
applyInstallPlan,
++ assertOpenCodeActivationUnchanged,
++ assertOpenCodeHookDeactivationReady,
assertSafeInstallOperation,
++ prepareHookConsentMigration,
previewInstallPlan,
};
diff --cc scripts/lib/install/hook-consent.js
index ea382af1d,883c121d7..e29c01bf5
--- a/scripts/lib/install/hook-consent.js
+++ b/scripts/lib/install/hook-consent.js
@@@ -38,52 -38,19 +38,71 @@@ const HOOK_CAPABILITY_GROUPS = Object.f
const HOOK_CONSENT_DECISIONS = Object.freeze(['enabled', 'declined']);
const HOOK_RUNTIME_MODULE_ID = 'hooks-runtime';
+const OPENCODE_DISABLE_ECC_HOOKS_TRANSFORM = 'opencode-disable-ecc-hooks';
++const OPENCODE_DISABLE_PLUGIN_TRANSFORM = 'opencode-disable-plugin-entrypoint';
function normalizeOperationPath(value) {
return String(value || '').replace(/\\/g, '/').toLowerCase();
}
+function disableOpenCodeHookPluginRegistration(content, sourceRelativePath) {
+ let config;
+ try {
+ config = JSON.parse(content);
+ } catch (error) {
+ throw new Error(`Failed to parse ${sourceRelativePath}: ${error.message}`);
+ }
+ if (!config || typeof config !== 'object' || Array.isArray(config)) {
+ throw new Error(`Invalid ${sourceRelativePath}: expected a JSON object`);
+ }
+ if (config.plugin !== undefined && !Array.isArray(config.plugin)) {
+ throw new Error(`Invalid ${sourceRelativePath}: plugin must be an array`);
+ }
+
+ if (!Array.isArray(config.plugin)) {
+ return `${JSON.stringify(config, null, 2)}\n`;
+ }
+
+ return `${JSON.stringify({
+ ...config,
+ plugin: config.plugin.filter(plugin => plugin !== './plugins'),
+ }, null, 2)}\n`;
+}
+
++function isOpenCodePluginEntrypoint(operation = {}) {
++ return /^\.opencode\/(?:dist\/)?plugins\/[^/]+\.(?:[cm]?js|ts)$/.test(
++ normalizeOperationPath(operation.sourceRelativePath)
++ );
++}
++
++function getDisabledOpenCodePluginContent() {
++ // OpenCode discovers plugins independently of opencode.json registration.
++ // Do not import the original module: even module initialization has effects.
++ return 'export default async () => ({});\n';
++}
++
+function isOpenCodeHookActivationOperation(operation = {}) {
- return normalizeOperationPath(operation.sourceRelativePath) === '.opencode/opencode.json';
++ return normalizeOperationPath(operation.sourceRelativePath) === '.opencode/opencode.json'
++ || isOpenCodePluginEntrypoint(operation);
+}
+
function isHookRuntimeOperation(operation = {}) {
- if (operation.moduleId === HOOK_RUNTIME_MODULE_ID) {
+ if (
+ operation.kind === 'update-claude-settings'
+ || operation.moduleId === HOOK_RUNTIME_MODULE_ID
+ ) {
return true;
}
+ if (isOpenCodeHookActivationOperation(operation)) {
+ return !(
+ operation.kind === 'copy-file'
- && operation.contentTransform === OPENCODE_DISABLE_ECC_HOOKS_TRANSFORM
++ && operation.contentTransform === (isOpenCodePluginEntrypoint(operation)
++ ? OPENCODE_DISABLE_PLUGIN_TRANSFORM
++ : OPENCODE_DISABLE_ECC_HOOKS_TRANSFORM)
+ );
+ }
+
const source = normalizeOperationPath(operation.sourceRelativePath);
const destination = normalizeOperationPath(operation.destinationPath);
return (
@@@ -126,50 -93,6 +145,57 @@@ function withoutHookRuntimeId(values)
return (Array.isArray(values) ? values : []).filter(value => value !== HOOK_RUNTIME_MODULE_ID);
}
+function withoutOpenCodeHookActivation(operation) {
+ if (
+ !isOpenCodeHookActivationOperation(operation)
+ || operation.kind !== 'copy-file'
+ ) {
+ return operation;
+ }
+ return {
+ ...operation,
- contentTransform: OPENCODE_DISABLE_ECC_HOOKS_TRANSFORM,
++ contentTransform: isOpenCodePluginEntrypoint(operation)
++ ? OPENCODE_DISABLE_PLUGIN_TRANSFORM
++ : OPENCODE_DISABLE_ECC_HOOKS_TRANSFORM,
+ };
+}
+
+function transformOpenCodeHookActivationOperations(operations) {
+ return (Array.isArray(operations) ? operations : []).map(withoutOpenCodeHookActivation);
+}
+
+function planSelectsHookRuntime(plan = {}) {
+ return (
+ Array.isArray(plan.selectedModuleIds)
+ && plan.selectedModuleIds.includes(HOOK_RUNTIME_MODULE_ID)
+ ) || (
+ Array.isArray(plan.operations)
+ && plan.operations.some(operation => operation.moduleId === HOOK_RUNTIME_MODULE_ID)
+ );
+}
+
+function disableUnselectedOpenCodeHooks(plan) {
+ if (plan.target !== 'opencode' || planSelectsHookRuntime(plan)) {
+ return plan;
+ }
+
+ return {
+ ...plan,
+ operations: transformOpenCodeHookActivationOperations(plan.operations),
+ statePreview: plan.statePreview
+ ? {
+ ...plan.statePreview,
+ operations: transformOpenCodeHookActivationOperations(plan.statePreview.operations),
+ }
+ : plan.statePreview,
+ };
+}
+
++function shouldDisableOpenCodeHooks(plan = {}) {
++ return plan.target === 'opencode'
++ && (plan.hookConsent === 'declined' || !planSelectsHookRuntime(plan));
++}
++
function setStatePreviewHookConsent(statePreview, hookConsent) {
if (!statePreview || !statePreview.request) {
return statePreview;
@@@ -200,7 -123,7 +226,11 @@@ function getRecordedHookConsent(state
return 'enabled';
}
-- if (planMaterializesHookRuntime(state)) {
++ // Older OpenCode installs copied activation files without asking for consent.
++ // Their presence cannot establish that the user opted in to automatic hooks.
++ if ((Array.isArray(state.operations) ? state.operations : []).some(operation => (
++ !isOpenCodeHookActivationOperation(operation) && isHookRuntimeOperation(operation)
++ ))) {
return 'enabled';
}
@@@ -277,12 -193,10 +307,16 @@@ function assertHookConsentReady(plan =
module.exports = {
HOOK_CAPABILITY_GROUPS,
assertHookConsentReady,
+ disableUnselectedOpenCodeHooks,
+ disableOpenCodeHookPluginRegistration,
++ getDisabledOpenCodePluginContent,
formatHookCapabilityDisclosure,
getRecordedHookConsent,
isHookRuntimeOperation,
++ isOpenCodeHookActivationOperation,
++ isOpenCodePluginEntrypoint,
planMaterializesHookRuntime,
resolveHookConsentFlags,
++ shouldDisableOpenCodeHooks,
withHookConsent,
};
diff --cc scripts/lib/install/plan.js
index 1d7738c77,1400557c7..afcb4f06b
--- a/scripts/lib/install/plan.js
+++ b/scripts/lib/install/plan.js
@@@ -7,7 -7,10 +7,11 @@@ const { execFileSync } = require('child
const { resolveInstallPlan } = require('../install-manifests');
const { getInstallTargetAdapter } = require('../install-targets/registry');
const { resolveInvocationEnvironment } = require('../invocation-environment');
+const { disableUnselectedOpenCodeHooks } = require('./hook-consent');
+ const { readHooksConfig } = require('../hooks-config');
+ const {
+ materializeManagedHooks,
+ } = require('./claude-settings');
const EXCLUDED_GENERATED_SOURCE_SUFFIXES = ['/ecc-install-state.json', '/ecc/install-state.json'];
const IGNORED_DIRECTORY_NAMES = new Set([
diff --cc tests/lib/hook-consent.test.js
index f3f0e6d9a,2f44361e2..691dbceaa
--- a/tests/lib/hook-consent.test.js
+++ b/tests/lib/hook-consent.test.js
@@@ -7,8 -7,7 +7,9 @@@ const assert = require('assert')
const {
HOOK_CAPABILITY_GROUPS,
assertHookConsentReady,
+ disableOpenCodeHookPluginRegistration,
formatHookCapabilityDisclosure,
++ getRecordedHookConsent,
isHookRuntimeOperation,
planMaterializesHookRuntime,
resolveHookConsentFlags,
@@@ -79,25 -98,8 +100,25 @@@ function runTests()
sourceRelativePath: '.opencode/plugins/ecc-hooks.ts',
destinationPath: '/root/.config/opencode/plugins/ecc-hooks.ts',
}),
-- false
++ true
);
+ assert.strictEqual(isHookRuntimeOperation({
+ kind: 'copy-file',
+ moduleId: 'platform-configs',
+ sourceRelativePath: '.opencode/opencode.json',
+ }), true);
+ assert.strictEqual(isHookRuntimeOperation({
+ kind: 'copy-file',
+ moduleId: 'platform-configs',
+ sourceRelativePath: '.opencode/opencode.json',
+ contentTransform: 'opencode-disable-ecc-hooks',
+ }), false);
+ assert.strictEqual(isHookRuntimeOperation({
+ kind: 'merge-json',
+ moduleId: 'platform-configs',
+ sourceRelativePath: '.opencode/opencode.json',
+ contentTransform: 'opencode-disable-ecc-hooks',
+ }), true);
assert.strictEqual(isHookRuntimeOperation({ sourceRelativePath: 'rules/common.md' }), false);
assert.strictEqual(
isHookRuntimeOperation({ sourceRelativePath: 'skills/webhooks-guide.md' }),
@@@ -105,6 -107,6 +126,41 @@@
);
})) passed++; else failed++;
++ if (test('OpenCode auto-discovered entrypoints require selected runtime and consent', () => {
++ const entrypoints = ['.opencode/plugins/ecc-hooks.ts', '.opencode/plugins/index.ts'];
++ const operations = entrypoints.map(sourceRelativePath => ({
++ kind: 'copy-file', moduleId: 'platform-configs', sourceRelativePath,
++ }));
++ const base = {
++ target: 'opencode', operations, selectedModuleIds: ['platform-configs'],
++ statePreview: { operations, request: {}, resolution: { selectedModules: ['platform-configs'] } },
++ };
++ for (const decision of [null, 'enabled', 'declined']) {
++ const plan = withHookConsent(base, decision);
++ for (const operation of [...plan.operations, ...plan.statePreview.operations]) {
++ assert.strictEqual(operation.contentTransform, 'opencode-disable-plugin-entrypoint');
++ assert.strictEqual(isHookRuntimeOperation(operation), false);
++ }
++ assert.doesNotThrow(() => assertHookConsentReady(plan));
++ }
++ const selected = { ...base, selectedModuleIds: ['platform-configs', 'hooks-runtime'] };
++ const pending = withHookConsent(selected, null);
++ assert.throws(() => assertHookConsentReady(pending), /automatic hook runtime/);
++ const enabled = withHookConsent(selected, 'enabled');
++ assert.ok(enabled.operations.every(operation => operation.contentTransform === undefined));
++ assert.doesNotThrow(() => assertHookConsentReady(enabled));
++ const declined = withHookConsent(selected, 'declined');
++ assert.strictEqual(declined.operations.length, 2);
++ assert.ok(declined.operations.every(operation => (
++ operation.contentTransform === 'opencode-disable-plugin-entrypoint'
++ )));
++ assert.ok(operations.every(operation => operation.contentTransform === undefined), 'Input plan stays unchanged');
++ assert.strictEqual(isHookRuntimeOperation({
++ kind: 'copy-file', moduleId: 'platform-configs',
++ sourceRelativePath: '.opencode/plugins/helpers/readme.md',
++ }), false);
++ })) passed++; else failed++;
++
if (test('detects hook materialization from plan operations only', () => {
assert.strictEqual(planMaterializesHookRuntime(buildHookPlan()), true);
assert.strictEqual(planMaterializesHookRuntime({
@@@ -114,23 -116,6 +170,38 @@@
assert.strictEqual(planMaterializesHookRuntime({}), false);
})) passed++; else failed++;
+ if (test('removes only ECC hook activation from OpenCode config', () => {
+ const transformed = disableOpenCodeHookPluginRegistration(JSON.stringify({
+ plugin: ['./plugins', 'example-plugin'],
+ instructions: ['AGENTS.md'],
+ }), '.opencode/opencode.json');
+ assert.deepStrictEqual(JSON.parse(transformed), {
+ plugin: ['example-plugin'],
+ instructions: ['AGENTS.md'],
+ });
+ assert.deepStrictEqual(JSON.parse(disableOpenCodeHookPluginRegistration(
+ JSON.stringify({ instructions: ['AGENTS.md'] }),
+ '.opencode/opencode.json'
+ )), {
+ instructions: ['AGENTS.md'],
+ });
+ })) passed++; else failed++;
+
++ if (test('historical OpenCode activation bytes alone do not imply hook consent', () => {
++ const state = {
++ request: {}, resolution: { selectedModules: ['platform-configs'] },
++ operations: [
++ { kind: 'copy-file', moduleId: 'platform-configs', sourceRelativePath: '.opencode/opencode.json' },
++ { kind: 'copy-file', moduleId: 'platform-configs', sourceRelativePath: '.opencode/plugins/ecc-hooks.ts' },
++ ],
++ };
++ assert.strictEqual(getRecordedHookConsent(state), null);
++ assert.strictEqual(getRecordedHookConsent({ ...state, request: { hookConsent: 'declined' } }), 'declined');
++ assert.strictEqual(getRecordedHookConsent({ ...state, request: { hookConsent: 'enabled' } }), 'enabled');
++ assert.strictEqual(getRecordedHookConsent({ ...state, resolution: { selectedModules: ['hooks-runtime'] } }), 'enabled');
++ assert.strictEqual(getRecordedHookConsent({ operations: [{ kind: 'update-claude-settings' }] }), 'enabled');
++ })) passed++; else failed++;
++
if (test('formats one numbered disclosure line per capability group', () => {
const disclosure = formatHookCapabilityDisclosure();
const lines = disclosure.split('\n');
diff --cc tests/lib/install-executor.test.js
index e9f43d5b3,6f64b540c..d39c14628
--- a/tests/lib/install-executor.test.js
+++ b/tests/lib/install-executor.test.js
@@@ -19,8 -20,7 +20,9 @@@ const
listAvailableLanguages,
} = require('../../scripts/lib/install-executor');
const { applyInstallPlan: applyInstallPlanDirect } = require('../../scripts/lib/install/apply');
+const { normalizeInstallRequest } = require('../../scripts/lib/install/request');
+const { createInstallPlanFromRequest } = require('../../scripts/lib/install/runtime');
+ const { withHookConsent } = require('../../scripts/lib/install/hook-consent');
const REPO_ROOT = path.resolve(__dirname, '..', '..');
@@@ -50,6 -50,6 +52,40 @@@ function operationFor(plan, suffix)
));
}
++const INERT_OPENCODE_PLUGIN = 'export default async () => ({});\n';
++const OPENCODE_ENTRYPOINTS = ['ecc-hooks.ts', 'index.ts'];
++
++function snapshotFiles(root) {
++ const entries = [];
++ function visit(directory, prefix = '') {
++ if (!fs.existsSync(directory)) return;
++ for (const entry of fs.readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
++ const relativePath = path.join(prefix, entry.name);
++ const fullPath = path.join(directory, entry.name);
++ if (entry.isDirectory()) {
++ entries.push([relativePath, 'directory']);
++ visit(fullPath, relativePath);
++ } else {
++ entries.push([relativePath, fs.readFileSync(fullPath).toString('base64')]);
++ }
++ }
++ }
++ visit(root);
++ return entries;
++}
++
++function createOpenCodePlan(homeDir, hookConsent = null, enabledRuntime = false) {
++ return createInstallPlanFromRequest(normalizeInstallRequest({
++ target: 'opencode',
++ moduleIds: enabledRuntime ? ['platform-configs', 'hooks-runtime'] : ['platform-configs'],
++ enableHooks: hookConsent === 'enabled',
++ noHooks: hookConsent === 'declined',
++ }), {
++ sourceRoot: REPO_ROOT, homeDir, projectRoot: homeDir,
++ exemptValidationCodes: ['opencode-plugin-not-built'],
++ });
++}
++
function writeLegacySourceFixture(root) {
writeJson(root, 'package.json', { version: '9.8.7' });
writeFile(root, path.join('rules', 'common', 'coding-style.md'), '# Common\n');
@@@ -641,106 -842,6 +878,220 @@@ function runTests()
cleanup(tempDir);
}
})) passed++; else failed++;
+
+ if (test('OpenCode profile keeps plugin source dormant until hook opt-in is consented', () => {
+ const homeDir = createTempDir('install-executor-opencode-boundary-');
+ try {
+ const planOptions = {
+ sourceRoot: REPO_ROOT,
+ homeDir,
+ projectRoot: homeDir,
+ exemptValidationCodes: ['opencode-plugin-not-built'],
+ };
+ const rawDefaultPlan = createManifestInstallPlan({
+ ...planOptions,
+ target: 'opencode',
+ profileId: 'opencode',
+ });
+ assert.strictEqual(
+ rawDefaultPlan.operations.find(operation => (
+ operation.sourceRelativePath.split(path.sep).join('/') === '.opencode/opencode.json'
+ )).contentTransform,
+ 'opencode-disable-ecc-hooks'
+ );
+ const defaultPlan = createInstallPlanFromRequest(
+ normalizeInstallRequest({ target: 'opencode', profileId: 'opencode' }),
+ planOptions
+ );
+ const defaultConfig = defaultPlan.operations.find(operation => (
+ operation.sourceRelativePath.split(path.sep).join('/') === '.opencode/opencode.json'
+ ));
+ const defaultStateConfig = defaultPlan.statePreview.operations.find(operation => (
+ operation.sourceRelativePath.split(path.sep).join('/') === '.opencode/opencode.json'
+ ));
+
+ assert.strictEqual(defaultConfig.contentTransform, 'opencode-disable-ecc-hooks');
+ assert.strictEqual(defaultStateConfig.contentTransform, 'opencode-disable-ecc-hooks');
+ assert.ok(defaultPlan.operations.some(operation => (
+ operation.sourceRelativePath.split(path.sep).join('/') === '.opencode/plugins/ecc-hooks.ts'
+ )), 'Default plan should still copy dormant plugin source');
+
- applyInstallPlanDirect(defaultPlan, { writeInstallState() {} });
++ for (const name of OPENCODE_ENTRYPOINTS) {
++ for (const operations of [defaultPlan.operations, defaultPlan.statePreview.operations]) {
++ const operation = operations.find(candidate => (
++ candidate.sourceRelativePath.split(path.sep).join('/') === `.opencode/plugins/${name}`
++ ));
++ assert.ok(operation, `Plan includes ${name}`);
++ assert.strictEqual(operation.contentTransform, 'opencode-disable-plugin-entrypoint');
++ }
++ }
++ applyInstallPlanDirect(defaultPlan);
++ for (const name of OPENCODE_ENTRYPOINTS) {
++ assert.strictEqual(fs.readFileSync(path.join(homeDir, '.config', 'opencode', 'plugins', name), 'utf8'), INERT_OPENCODE_PLUGIN);
++ }
+ const installedConfig = JSON.parse(fs.readFileSync(
+ path.join(homeDir, '.config', 'opencode', 'opencode.json'),
+ 'utf8'
+ ));
+ assert.ok(!installedConfig.plugin.includes('./plugins'));
+
+ const enabledWithoutRuntime = createInstallPlanFromRequest(
+ normalizeInstallRequest({
+ target: 'opencode',
+ profileId: 'opencode',
+ enableHooks: true,
+ }),
+ planOptions
+ );
+ assert.strictEqual(
+ enabledWithoutRuntime.operations.find(operation => (
+ operation.sourceRelativePath.split(path.sep).join('/') === '.opencode/opencode.json'
+ )).contentTransform,
+ 'opencode-disable-ecc-hooks'
+ );
+
+ const declinedPlan = createInstallPlanFromRequest(
+ normalizeInstallRequest({ target: 'opencode', profileId: 'core', noHooks: true }),
+ planOptions
+ );
+ assert.strictEqual(
+ declinedPlan.operations.find(operation => (
+ operation.sourceRelativePath.split(path.sep).join('/') === '.opencode/opencode.json'
+ )).contentTransform,
+ 'opencode-disable-ecc-hooks'
+ );
+ assert.ok(!declinedPlan.operations.some(operation => operation.moduleId === 'hooks-runtime'));
+
+ const pendingPlan = createInstallPlanFromRequest(
+ normalizeInstallRequest({
+ target: 'opencode',
+ moduleIds: ['platform-configs', 'hooks-runtime'],
+ }),
+ planOptions
+ );
+ assert.throws(
+ () => applyInstallPlanDirect(pendingPlan, { writeInstallState() {} }),
+ /automatic hook runtime/
+ );
+
+ const enabledPlan = createInstallPlanFromRequest(
+ normalizeInstallRequest({
+ target: 'opencode',
+ moduleIds: ['platform-configs', 'hooks-runtime'],
+ enableHooks: true,
+ }),
+ planOptions
+ );
+ const enabledConfig = enabledPlan.operations.find(operation => (
+ operation.sourceRelativePath.split(path.sep).join('/') === '.opencode/opencode.json'
+ ));
+ assert.strictEqual(enabledConfig.contentTransform, undefined);
++ applyInstallPlanDirect(enabledPlan);
++ for (const name of OPENCODE_ENTRYPOINTS) {
++ assert.strictEqual(
++ fs.readFileSync(path.join(homeDir, '.config', 'opencode', 'plugins', name), 'utf8'),
++ fs.readFileSync(path.join(REPO_ROOT, '.opencode', 'plugins', name), 'utf8')
++ );
++ }
++ applyInstallPlanDirect(declinedPlan);
++ const declinedState = JSON.parse(fs.readFileSync(declinedPlan.installStatePath, 'utf8'));
++ assert.strictEqual(declinedState.request.hookConsent, 'declined');
++ assert.ok(!declinedState.resolution.selectedModules.includes('hooks-runtime'));
++ assert.ok(!JSON.parse(fs.readFileSync(path.join(declinedPlan.targetRoot, 'opencode.json'), 'utf8')).plugin.includes('./plugins'));
++ for (const name of OPENCODE_ENTRYPOINTS) {
++ const destinationPath = path.join(homeDir, '.config', 'opencode', 'plugins', name);
++ assert.strictEqual(fs.readFileSync(destinationPath, 'utf8'), INERT_OPENCODE_PLUGIN);
++ const operation = declinedState.operations.find(candidate => candidate.destinationPath === destinationPath);
++ assert.strictEqual(operation.contentTransform, 'opencode-disable-plugin-entrypoint');
++ assert.strictEqual(operation.contentSha256, crypto.createHash('sha256').update(INERT_OPENCODE_PLUGIN).digest('hex'));
++ }
++ } finally {
++ cleanup(homeDir);
++ }
++ })) passed++; else failed++;
++
++ if (test('OpenCode disabled install refuses user-owned activation files before any writes', () => {
++ for (const relativePath of ['opencode.json', path.join('plugins', 'ecc-hooks.ts'), path.join('plugins', 'index.ts')]) {
++ const homeDir = createTempDir('install-opencode-user-owned-');
++ try {
++ const plan = createOpenCodePlan(homeDir, 'declined');
++ writeFile(plan.targetRoot, relativePath, relativePath === 'opencode.json'
++ ? '{"plugin":["./plugins"],"theme":"user-owned"}\n'
++ : 'globalThis.userOwnedPlugin = true; export default async () => ({});\n');
++ const before = snapshotFiles(homeDir);
++ assert.throws(() => applyInstallPlanDirect(plan), /OpenCode hook|OpenCode.*activation|OpenCode.*plugin/i);
++ assert.deepStrictEqual(snapshotFiles(homeDir), before, `No writes when ${relativePath} is user-owned`);
++ } finally {
++ cleanup(homeDir);
++ }
++ }
++ })) passed++; else failed++;
++
++ if (test('OpenCode disabled install refuses modified or unverifiable managed activation files before writes', () => {
++ for (const scenario of ['modified-plugin', 'modified-config', 'missing-digest', 'stale-entrypoint']) {
++ const homeDir = createTempDir('install-opencode-managed-guard-');
++ try {
++ const enabledPlan = createOpenCodePlan(homeDir, 'enabled', true);
++ applyInstallPlanDirect(enabledPlan);
++ const state = JSON.parse(fs.readFileSync(enabledPlan.installStatePath, 'utf8'));
++ const pluginPath = path.join(enabledPlan.targetRoot, 'plugins', 'ecc-hooks.ts');
++ if (scenario === 'modified-plugin') {
++ fs.appendFileSync(pluginPath, '// user modification\n');
++ } else if (scenario === 'modified-config') {
++ fs.appendFileSync(path.join(enabledPlan.targetRoot, 'opencode.json'), ' \n');
++ } else if (scenario === 'missing-digest') {
++ delete state.operations.find(operation => operation.destinationPath === pluginPath).contentSha256;
++ writeJson(homeDir, path.relative(homeDir, enabledPlan.installStatePath), state);
++ } else {
++ const stalePath = writeFile(enabledPlan.targetRoot, path.join('plugins', 'legacy-hooks.js'), 'globalThis.legacyHook = true;\n');
++ state.operations.push({
++ kind: 'copy-file', moduleId: 'platform-configs', ownership: 'managed', scaffoldOnly: false,
++ sourceRelativePath: '.opencode/plugins/legacy-hooks.js', destinationPath: stalePath,
++ strategy: 'preserve-relative-path',
++ contentSha256: crypto.createHash('sha256').update(fs.readFileSync(stalePath)).digest('hex'),
++ });
++ writeJson(homeDir, path.relative(homeDir, enabledPlan.installStatePath), state);
++ }
++ const declinedPlan = createOpenCodePlan(homeDir, 'declined');
++ const before = snapshotFiles(homeDir);
++ assert.throws(() => applyInstallPlanDirect(declinedPlan), /OpenCode hook|OpenCode.*activation|OpenCode.*plugin/i);
++ assert.deepStrictEqual(snapshotFiles(homeDir), before, `No writes for ${scenario}`);
++ } finally {
++ cleanup(homeDir);
++ }
++ }
++ })) passed++; else failed++;
++
++ if (test('OpenCode decline preserves activation changed at the install write boundary', () => {
++ const homeDir = createTempDir('install-opencode-write-race-');
++ try {
++ const enabledPlan = createOpenCodePlan(homeDir, 'enabled', true);
++ applyInstallPlanDirect(enabledPlan);
++ const pluginPath = path.join(enabledPlan.targetRoot, 'plugins', 'ecc-hooks.ts');
++ const changedContent = 'globalThis.userChangedHook = true;\n';
++ const stateBefore = fs.readFileSync(enabledPlan.installStatePath);
++ let changed = false;
++ const declinedPlan = createOpenCodePlan(homeDir, 'declined');
++ assert.throws(() => applyInstallPlanDirect(declinedPlan, {
++ beforeOperationWrite({ operation }) {
++ if (operation.destinationPath === pluginPath) {
++ changed = true;
++ fs.writeFileSync(pluginPath, changedContent);
++ }
++ },
++ }), /OpenCode hook.*changed after preflight/i);
++ assert.strictEqual(changed, true);
++ assert.strictEqual(fs.readFileSync(pluginPath, 'utf8'), changedContent);
++ const previousState = JSON.parse(stateBefore.toString('utf8'));
++ const checkpointState = JSON.parse(fs.readFileSync(enabledPlan.installStatePath, 'utf8'));
++ 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, 'enabled', 'Failed decline must retain the prior enabled decision');
+ } finally {
+ cleanup(homeDir);
+ }
+ })) passed++; else failed++;
if (test('Claude hooks install refuses a symlinked hooks destination', () => {
if (process.platform === 'win32') return;
diff --cc tests/lib/install-lifecycle.test.js
index 4f362d158,1eed5071b..4377915b0
--- a/tests/lib/install-lifecycle.test.js
+++ b/tests/lib/install-lifecycle.test.js
@@@ -142,6 -206,6 +206,27 @@@ function writeOpencodeState(homeDir, ov
};
}
++function writeRecordedOpenCodeActivation(homeDir) {
++ const targetRoot = path.join(homeDir, '.config', 'opencode');
++ const operations = ['opencode.json', 'plugins/ecc-hooks.ts', 'plugins/index.ts'].map(relativePath => {
++ const sourceRelativePath = `.opencode/${relativePath}`;
++ const content = fs.readFileSync(path.join(REPO_ROOT, sourceRelativePath));
++ const destinationPath = path.join(targetRoot, relativePath);
++ fs.mkdirSync(path.dirname(destinationPath), { recursive: true });
++ fs.writeFileSync(destinationPath, content);
++ return {
++ kind: 'copy-file', moduleId: 'platform-configs', sourceRelativePath, destinationPath,
++ ownership: 'managed', scaffoldOnly: false, strategy: 'preserve-relative-path',
++ contentSha256: crypto.createHash('sha256').update(content).digest('hex'),
++ };
++ });
++ return writeOpencodeState(homeDir, {
++ request: { modules: ['platform-configs'], hookConsent: null },
++ resolution: { selectedModules: ['platform-configs'] },
++ operations,
++ });
++}
++
function withTemporarilyMovedPath(filePath, callback) {
if (!fs.existsSync(filePath)) {
try {
@@@ -1869,55 -1935,6 +1956,341 @@@ 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 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);
++ 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.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.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-');