diff --git a/.opencode/README.md b/.opencode/README.md index 2fc58880d..d6a38b2dc 100644 --- a/.opencode/README.md +++ b/.opencode/README.md @@ -142,7 +142,7 @@ a pointer to this command if the build step is missing. | TypeScript | `tool.execute.after` | Check for type errors | | console.log | `file.edited` | Warn about debug statements | | Notification | `session.idle` | Desktop notification (cross-platform) | -| Security | `tool.execute.before` | Check for secrets | +| Tool reminders | `tool.execute.before` | Track writes and suggest review before pushing | | Git Push Reminder | `tool.execute.before` | Remind to review before pushing | | Doc File Warning | `tool.execute.before` | Warn about unnecessary documentation | | Long Command Reminder | `tool.execute.before` | Remind about long-running commands | @@ -154,6 +154,11 @@ a pointer to this command if the build step is missing. | Session Compacting | `experimental.session.compacting` | Preserve context across compaction | | Permission Auto-Approve | `permission.ask` | Auto-approve safe operations | +The tool-before callbacks provide bookkeeping and advisory reminders. They do +not run ECC's canonical Bash guards or reject commands such as +`git commit --no-verify`. Native OpenCode permission rules remain the execution +boundary; configured native denies take precedence over ECC read suggestions. + ### Custom Tools | Tool | Description | @@ -242,6 +247,10 @@ selection, and its subagents inherit the invoking primary agent's model. MIT Home-target installations keep `plugins/index.ts` inert even with hooks enabled. +The default plugin entry targets OpenCode 2.x. OpenCode 1.x's function-only +loader cannot load this entry; the retained named V1 factory is a migration +surface, not automatic V1 package compatibility. + OpenCode 2.x loads plugins by scanning every root-level file in a plugins directory; it does **not** accept configured file paths — an entry like `"./plugins/ecc-hooks.ts"` in the `plugin` array logs diff --git a/.opencode/index.ts b/.opencode/index.ts index 06a99306b..cbca2da5a 100644 --- a/.opencode/index.ts +++ b/.opencode/index.ts @@ -35,6 +35,7 @@ */ // Export the main plugin -// opencode's legacy plugin loader iterates every module export and throws if -// any is not a plugin function, so only the plugin function may be exported. +// The default package export targets OpenCode 2.x's definition loader. +// OpenCode 1.x's function-only loader cannot load this package entry. The +// named V1 factory in plugins/ecc-hooks.ts is retained for migration only. export { default } from "./plugins/ecc-hooks.ts" diff --git a/.opencode/plugins/ecc-hooks.ts b/.opencode/plugins/ecc-hooks.ts index 9de4289a7..a4993b1ac 100644 --- a/.opencode/plugins/ecc-hooks.ts +++ b/.opencode/plugins/ecc-hooks.ts @@ -11,10 +11,9 @@ * (kept in sync with package.json — enforced by tests/plugin-manifest.test.js) * * This module intentionally exposes BOTH surfaces: - * - `ECCHooksPlugin` (named): the V1 factory. Old OpenCode builds and the - * legacy discovery path (tests that scan `plugins/*.ts` and instantiate - * function exports) keep working, and the 18 behavioral hook tests run - * against real logic instead of a rewritten harness. + * - `ECCHooksPlugin` (named): the retained V1 factory used by behavioral + * tests and explicit migration callers. The default module is V2-only: + * OpenCode 1.x's function-only module loader cannot load this entry. * - default export: the V2 definition `{ id, setup(ctx) }` that OpenCode 2.x * actually loads. `setup` builds the same runtime once and adapts its hook * map onto the V2 domains. @@ -546,8 +545,8 @@ async function createEccRuntime(input: { } /** - * Pre-Tool Security Check (Equivalent to Claude Code PreToolUse hook): - * change bookkeeping, git-push/tmux reminders, doc-file warning. + * Advisory pre-tool callback: change bookkeeping, git-push/tmux reminders, + * and doc-file warnings. This does not invoke canonical ECC Bash guards. */ const onToolBefore = async (input: ToolInput) => { try { @@ -574,7 +573,7 @@ async function createEccRuntime(input: { } } - // Block creation of unnecessary documentation files + // Warn about potentially unnecessary documentation files if (hookEnabled("pre:write:doc-file-warning", ["standard", "strict"]) && input.tool === "write") { const filePath = getFilePath(input.args) if ( @@ -1045,7 +1044,9 @@ export const ECCHooksPluginDefinition = { // skill tracker reads error fields (isError/is_error/status/error) off // `tool_response` itself; a `{ result: … }` wrapper made failed skill // runs look like successes. - hooks["tool.execute.after"](toToolInput(event), event.result ?? event.output), + hooks["tool.execute.after"](toToolInput(event), event.status === "error" + ? { is_error: true } + : event.result ?? event.output), )), ) } diff --git a/scripts/lib/install/apply.js b/scripts/lib/install/apply.js index 4bc8ba9a6..000fea0d8 100644 --- a/scripts/lib/install/apply.js +++ b/scripts/lib/install/apply.js @@ -564,6 +564,10 @@ function assertOpenCodeHookDeactivationReady(plan, options = {}) { return destinationPath; }, }); + // Record only writes proven above. Never rehash unrelated retained files. + if (typeof options.onMigratedOperation === 'function') { + options.onMigratedOperation(operation); + } snapshot.set(key, crypto.createHash('sha256').update(current).digest('hex')); inactive = activationIsInactive(kind, operation, current, true); } @@ -886,6 +890,11 @@ function applyInstallPlanLocked(rawPlan, dependencies = {}, settingsLockHeld = f )).length; let completedHookRemovalCount = 0; const writtenDestinations = new Set(); + const migratedActivationOperations = []; + const digestPlan = () => ({ + ...appliedPlan, + operations: [...appliedPlan.operations, ...migratedActivationOperations], + }); if (migration.requiresBridgeState) { // Own every operation that may be written during a flat-skill migration // before the first copy. A later failure is retryable and uninstall can @@ -1030,19 +1039,25 @@ function applyInstallPlanLocked(rawPlan, dependencies = {}, settingsLockHeld = f } // Preserve main's activation safety gate before publishing ownership. - assertOpenCodeHookDeactivationReady(plan, { requireInactive: true }); + assertOpenCodeHookDeactivationReady(plan, { + requireInactive: true, + onMigratedOperation(operation) { + migratedActivationOperations.push(operation); + writtenDestinations.add(operation.destinationPath); + }, + }); // Stale records leave only the successful final state; the bridge and // failure checkpoint above keep them so a failed install retains ownership. finalState = stateWithContentDigests( withoutStaleOperations(migration.finalState, migration), - appliedPlan + digestPlan() ); if (typeof beforeInstallStateWrite === 'function') { beforeInstallStateWrite({ plan: appliedPlan, state: finalState }); } persistInstallState(plan.installStatePath, finalState); } catch (error) { - if (migration.requiresBridgeState) { + if (migration.requiresBridgeState || migratedActivationOperations.length > 0) { 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 @@ -1059,7 +1074,7 @@ function applyInstallPlanLocked(rawPlan, dependencies = {}, settingsLockHeld = f ), { ...appliedPlan, - operations: appliedPlan.operations.filter(operation => ( + operations: digestPlan().operations.filter(operation => ( writtenDestinations.has(operation.destinationPath) )), } diff --git a/tests/lib/install-lifecycle.test.js b/tests/lib/install-lifecycle.test.js index 5498189eb..98c4a8f37 100644 --- a/tests/lib/install-lifecycle.test.js +++ b/tests/lib/install-lifecycle.test.js @@ -2188,11 +2188,13 @@ function runTests() { for (const relative of ['.opencode/plugins/index.ts', '.opencode/plugins/ecc-hooks.ts']) { const operation = state.operations.find(candidate => comparableRelative(candidate) === relative); assert.strictEqual(operation.ownership, 'managed', 'migration must retain managed ownership'); + assert.strictEqual(operation.contentSha256, + crypto.createHash('sha256').update(fs.readFileSync(operation.destinationPath)).digest('hex'), + 'migrated bytes must have a matching uninstall receipt'); } - // Only planned destinations get refreshed digests, so the migrated - // retained files keep their historical record; the doctor must verify - // deactivation operations by transform content, not by that digest. + // Migrated retained files have current digests; untouched retained + // files keep their previous receipts. Doctor still verifies deactivation. const doctor = buildDoctorReport({ repoRoot: REPO_ROOT, homeDir, projectRoot: homeDir, targets: ['opencode'], }); @@ -2200,6 +2202,33 @@ function runTests() { ['missing-managed-files', 'drifted-managed-files', 'unverified-managed-operations'].includes(issue.code) ))); + // A failure after migration must checkpoint those actual writes too. + ageInstalledStubs(); + assert.throws(() => applyInstallPlan(createDeclinePlan(['commands-core']), { + beforeInstallStateWrite({ state: pending }) { + if (pending.operations.some(operation => { + if (!comparableRelative(operation).startsWith('.opencode/plugins/')) return false; + return operation.contentSha256 === crypto.createHash('sha256') + .update(fs.readFileSync(operation.destinationPath)).digest('hex'); + })) throw new Error('injected final-state failure'); + }, + }), /injected final-state failure/); + const checkpoint = readInstallState(basePlan.installStatePath); + for (const operation of checkpoint.operations.filter(operation => ( + comparableRelative(operation).startsWith('.opencode/plugins/') + ))) { + assert.strictEqual(operation.contentSha256, + crypto.createHash('sha256').update(fs.readFileSync(operation.destinationPath)).digest('hex'), + 'failure checkpoint must own migrated bytes'); + } + const removed = uninstallInstalledStates({ + repoRoot: REPO_ROOT, homeDir, projectRoot: homeDir, targets: ['opencode'], + }); + assert.strictEqual(removed.results[0].status, 'uninstalled'); + assert.ok(!fs.existsSync(path.join(pluginDir, 'index.ts'))); + assert.ok(!fs.existsSync(path.join(pluginDir, 'ecc-hooks.ts'))); + applyInstallPlan(createDeclinePlan(['platform-configs'])); + // Ownership is proven twice: identical legacy bytes alone never grant a // rewrite. A mis-recorded digest keeps the strict gate refusing. ageInstalledStubs(); @@ -2214,6 +2243,22 @@ function runTests() { ); assert.strictEqual(fs.readFileSync(path.join(pluginDir, 'index.ts'), 'utf8'), moduleStub, 'an unverifiable retained file must never be rewritten'); + for (const badDigest of [undefined, 'invalid']) { + ageInstalledStubs(); + const unverified = readInstallState(basePlan.installStatePath); + unverified.operations.find(operation => ( + comparableRelative(operation) === '.opencode/plugins/index.ts' + )).contentSha256 = badDigest; + if (badDigest === 'invalid') { + assert.throws(() => writeInstallState(basePlan.installStatePath, unverified), /SHA-256 hex digest/i); + } else { + writeInstallState(basePlan.installStatePath, unverified); + assert.throws(() => applyInstallPlan(createDeclinePlan(['commands-core'])), + /OpenCode hook activation remains active/i); + } + assert.strictEqual(fs.readFileSync(path.join(pluginDir, 'index.ts'), 'utf8'), moduleStub, + 'missing or invalid receipts must not authorize a migration'); + } }); } finally { cleanup(homeDir); diff --git a/tests/opencode-plugin-hooks.test.js b/tests/opencode-plugin-hooks.test.js index 6bb696f7f..abd2aace1 100644 --- a/tests/opencode-plugin-hooks.test.js +++ b/tests/opencode-plugin-hooks.test.js @@ -1023,6 +1023,14 @@ async function main() { const both = readRecordedRuns(skillHome) assert.strictEqual(both.length, 2) assert.strictEqual(both[1].outcome, "success", "clean responses still record as success") + // Actual OpenCode 2.x failures have status/error, no result/output. + await ctx.state.handlers["tool.execute.after"]({ + tool: "skill", id: "c4", input: { name: "code-review" }, + status: "error", error: { message: "native tool failed" }, + }) + const nativeRuns = readRecordedRuns(skillHome) + assert.strictEqual(nativeRuns.length, 3) + assert.strictEqual(nativeRuns[2].outcome, "failure", "native V2 errors must not become successes") } finally { restoreEnv({ HOME: previousHome, USERPROFILE: previousUserProfile }) fs.rmSync(skillHome, { recursive: true, force: true })