diff --git a/.opencode/README.md b/.opencode/README.md index 2d76b7d92..dcf8fb5c2 100644 --- a/.opencode/README.md +++ b/.opencode/README.md @@ -224,7 +224,7 @@ Full configuration in `opencode.json`: ```json { "$schema": "https://opencode.ai/config.json", - "plugin": ["./plugins"], + "plugin": ["./plugins/ecc-hooks.ts"], "instructions": [ "skills/tdd-workflow/SKILL.md", "skills/security-review/SKILL.md" @@ -243,6 +243,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. -OpenCode automatically loads `plugins/ecc-hooks.ts`; loading the barrel as well -would initialize every ECC hook twice. The source and published package barrel -remain available for module imports. +OpenCode 2.x scans every root-level file in a plugins directory **and** loads the +directory through `index.ts`, so the config points directly at +`plugins/ecc-hooks.ts` and the barrel stays a distinct-id stub +(`ecc-hooks-entry`). Re-exporting the real definition from `index.ts` would +register the id `ecc-hooks` two-to-three times, and OpenCode marks every entry +after the first as failed (`Duplicate plugin ID`). The source and published +package barrel remain available for module imports. diff --git a/.opencode/index.ts b/.opencode/index.ts index 8ee800f80..06a99306b 100644 --- a/.opencode/index.ts +++ b/.opencode/index.ts @@ -37,4 +37,4 @@ // 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. -export { default } from "./plugins/index.ts" +export { default } from "./plugins/ecc-hooks.ts" diff --git a/.opencode/opencode.json b/.opencode/opencode.json index 9b525a2b4..c7860c28f 100644 --- a/.opencode/opencode.json +++ b/.opencode/opencode.json @@ -18,7 +18,7 @@ "skills/eval-harness/SKILL.md" ], "plugin": [ - "./plugins" + "./plugins/ecc-hooks.ts" ], "skills": { "paths": [ diff --git a/.opencode/plugins/ecc-hooks.ts b/.opencode/plugins/ecc-hooks.ts index 86eaa7cdf..0fcfdbc4c 100644 --- a/.opencode/plugins/ecc-hooks.ts +++ b/.opencode/plugins/ecc-hooks.ts @@ -1,33 +1,35 @@ /** - * ECC Plugin Hooks for OpenCode + * ECC Plugin Hooks for OpenCode (V2 plugin API) * - * This plugin translates Claude Code hooks to OpenCode's plugin system. - * OpenCode's plugin system is MORE sophisticated than Claude Code with 20+ events - * compared to Claude Code's 3 phases (PreToolUse, PostToolUse, Stop). + * Migrated from the OpenCode V1 plugin format for OpenCode 2.x. + * V1 plugins default-exported an async function that returned a map of + * string-keyed hooks; V2 requires a default-exported definition object with + * an `id` and a `setup(ctx)` function, and hooks are registered on their + * owning domain instead of being returned by key. * - * Hook Event Mapping: - * - PreToolUse → tool.execute.before - * - PostToolUse → tool.execute.after - * - Stop → session.idle / session.status - * - SessionStart → session.created - * - SessionEnd → session.deleted + * Hook Event Mapping (V1 -> V2): + * - tool.execute.before -> ctx.tool.hook("execute.before") + * - tool.execute.after -> ctx.tool.hook("execute.after") + * - file.edited / session.* / -> ctx.event.subscribe() filtered by type + * todo.updated / watcher + * - shell.env -> ctx.shell.hook("create.before") + * - experimental.session.compacting -> ctx.session.hook("compaction") + * - permission.ask -> ctx.permission.hook("evaluate") + * - tool map -> ctx.tool.transform(editor => editor.add) + * + * The Bun `$` shell helper is not part of the V2 context, so every command + * here runs through `child_process.spawn` instead, and the console.log audit + * uses `fs` + regex rather than `grep` so it works on Windows too. */ -import type { PluginInput } from "@opencode-ai/plugin" import * as fs from "fs" import * as path from "path" +import { spawn } from "child_process" import { fileURLToPath, pathToFileURL } from "url" -import changedFilesTool from "../tools/changed-files.ts" -import dependencyAnalyzerTool from "../tools/dependency-analyzer.ts" /** - * Directory of this module. - * - * The plugin is ESM: tsc compiles it to .opencode/dist/plugins/*.js and OpenCode - * loads the .ts directly, so `__dirname` is not defined there. Reading it used to - * throw inside a try/catch and silently degrade the reported ECC version to the - * default. `import.meta.url` is the ESM source of truth; the `__dirname` check is - * kept first only so a CJS consumer of this module still resolves correctly. + * Directory of this module. See the note in the V1 file: `import.meta.url` is + * the ESM source of truth; `__dirname` is kept first only for CJS consumers. */ function resolvePluginDir(): string { if (typeof __dirname === "string" && __dirname) return __dirname @@ -36,9 +38,9 @@ function resolvePluginDir(): string { const PLUGIN_DIR = resolvePluginDir() -/** - * Type definitions for better type safety - */ +/** Loose aliases: the runtime ctx/event shapes come from the server, not the pinned SDK. */ +type LooseRecord = Record + interface ToolArgs { filePath?: string file_path?: string @@ -47,38 +49,10 @@ interface ToolArgs { [key: string]: unknown } -interface ToolInput { - tool: string - callID?: string - args?: ToolArgs -} - -interface PermissionEvent { - tool: string - args: unknown -} - -interface FileEvent { - path: string - type?: string -} - -interface TodoEvent { - todos: Array<{ text: string; done: boolean }> -} - /** * Artifacts that identify an ECC root, one per capability this plugin needs. - * - * These are required runtime files, never optional content: `skills/` belongs to - * the optional `workflow-quality` module, so probing for a skill rejected - * supported modular installs (e.g. `platform-configs` + `hooks-runtime` without - * `workflow-quality`) that still ship both the plugin and the tracker — silently - * disabling skill telemetry and the shell root export for those users. - * * Each probe is the exact artifact the caller is about to use, so detection is - * layout detection rather than an authenticity control: a directory only - * qualifies because it contains what we are going to read. + * layout detection rather than an authenticity control. */ const ECC_ROOT_PROBES = { // scripts/lib/utils.js is the shared library every scripts/ module requires. @@ -86,23 +60,16 @@ const ECC_ROOT_PROBES = { // What the skill-run telemetry hook imports at runtime. skillTracker: [path.join("scripts", "hooks", "skill-run-tracker.js")], // What the resolver embedded in commands requires once they read - // CLAUDE_PLUGIN_ROOT, and the version lookup for shell.env. + // CLAUDE_PLUGIN_ROOT, and the version lookup for the shell env hook. resolver: [path.join("scripts", "lib", "resolve-ecc-root.js")], } as const /** * Walk upwards from `startDir` looking for an ancestor that contains every - * relative path in `probes`. - * - * The plugin ships in three layouts — `/plugins` (installed), `/dist/plugins` - * (compiled) and `/.opencode/plugins` (repo checkout) — so the number of - * levels back to the root is not fixed. Probing beats a hardcoded `..`: a wrong - * root would make every command resolve against a directory that has no scripts. - * - * The walk is bounded to 5 levels so it cannot wander into unrelated ancestors. - * - * Returns null when no ancestor qualifies, so callers can leave the capability - * disabled instead of advertising a root that does not hold the artifact. + * relative path in `probes`. The plugin ships in three layouts - + * `/plugins` (installed), `/dist/plugins` (compiled) and + * `/.opencode/plugins` (repo checkout) - so the walk is bounded to + * 5 levels. Returns null when no ancestor qualifies. */ function findEccRootDir(startDir: string, probes: readonly string[]): string | null { let current = startDir @@ -117,22 +84,9 @@ function findEccRootDir(startDir: string, probes: readonly string[]): string | n return null } -/** - * Read the ECC version from package.json. - * - * Candidates are tried in order — the resolved ECC root first, then the two - * plausible parent depths of the plugin — because the layout differs between an - * installed root (`/plugins`), the compiled bundle (`/dist/plugins`) - * and a repo checkout (`/.opencode/plugins`). Falls back to a default if - * no package.json can be read. - */ +/** Read the ECC version from package.json, trying the plausible root layouts. */ function getECCVersion(eccRootDir?: string | null): string { - const candidates = [ - eccRootDir, - path.resolve(PLUGIN_DIR, ".."), - path.resolve(PLUGIN_DIR, "..", ".."), - ] - + const candidates = [eccRootDir, path.resolve(PLUGIN_DIR, ".."), path.resolve(PLUGIN_DIR, "..", "..")] for (const candidate of candidates) { if (!candidate) continue try { @@ -144,388 +98,350 @@ function getECCVersion(eccRootDir?: string | null): string { // Try the next candidate. } } - return "2.0.0" } -type ECCHooksPluginFn = (input: PluginInput) => Promise> +/** Run a command, resolving with its output regardless of exit code. */ +function run( + command: string, + args: string[], + options: { cwd?: string; detached?: boolean } = {}, +): Promise<{ code: number; stdout: string; stderr: string }> { + return new Promise((resolve, reject) => { + // npx/npm are .cmd shims on Windows: resolve them through the shell. + const useShell = process.platform === "win32" && /^(npx|npm|pnpm|yarn|bun)(\.cmd)?$/i.test(command) + const child = spawn(command, args, { + cwd: options.cwd, + shell: useShell, + detached: options.detached === true, + stdio: options.detached === true ? "ignore" : ["ignore", "pipe", "pipe"], + }) + if (options.detached === true) { + child.unref() + resolve({ code: 0, stdout: "", stderr: "" }) + return + } + let stdout = "" + let stderr = "" + child.stdout?.on("data", (chunk) => (stdout += String(chunk))) + child.stderr?.on("data", (chunk) => (stderr += String(chunk))) + child.on("error", reject) + child.on("close", (code) => resolve({ code: code ?? 1, stdout, stderr })) + }) +} -export const ECCHooksPlugin: ECCHooksPluginFn = async ({ - client, - $, - directory, - worktree, -}: PluginInput) => { - type HookProfile = "minimal" | "standard" | "strict" +/** Count console.log occurrences in a file with fs+regex (cross-platform grep replacement). */ +async function countConsoleLogs(filePath: string): Promise { + const content = await fs.promises.readFile(filePath, "utf-8") + return (content.match(/console\.log\s*\(/g) ?? []).length +} - const worktreePath = worktree || directory +// A location loads plugins from both the global config dir and its own +// .opencode/plugins; OpenCode 2.x also treats plugins/index.ts and the +// directory entrypoint as separate load entries. The directory config now +// points at ecc-hooks.ts directly and plugins/index.ts is an inert +// distinct-id stub, but we keep a per-directory guard so the hook set is +// registered only once per process *and* per project directory even if a +// future layout double-instantiates this module. +const GUARD_KEY = Symbol.for("ecc.hooks.registered-directories") +const registeredDirectories: Set = + ((globalThis as any)[GUARD_KEY] as Set | undefined) ?? + ((globalThis as any)[GUARD_KEY] = new Set()) - const editedFiles = new Set() +type HookProfile = "minimal" | "standard" | "strict" - function resolvePath(p: string): string { - if (path.isAbsolute(p)) return p - return path.join(worktreePath, p) - } +export const ECCHooksPluginDefinition = { + id: "ecc-hooks", + async setup(ctx: any): Promise<() => void> { + const directory: string = ctx?.location?.directory ?? process.cwd() + const worktreePath: string = directory - function hasProjectFile(relativePath: string): boolean { + if (registeredDirectories.has(worktreePath)) { + return () => {} + } + registeredDirectories.add(worktreePath) + + const editedFiles = new Set() + const pendingToolChanges = new Map() + let writeCounter = 0 + + function resolvePath(p: string): string { + if (path.isAbsolute(p)) return p + return path.join(worktreePath, p) + } + + function hasProjectFile(relativePath: string): boolean { + try { + return fs.statSync(resolvePath(relativePath)).isFile() + } catch { + return false + } + } + + function getFilePath(args: ToolArgs | undefined): string | null { + if (!args) return null + const p = args.filePath ?? args.file_path ?? args.path + return typeof p === "string" && p.trim() ? p : null + } + + // V2 plugins have no client.app.log; console output is captured into the + // server log, which is where the old ECC messages ended up anyway. + const log = (level: "debug" | "info" | "warn" | "error", message: string) => { + try { + const line = `[ecc] ${message}` + if (level === "error") console.error(line) + else if (level === "warn") console.warn(line) + else if (level === "debug") console.debug(line) + else console.log(line) + } catch { + // Logging must never break a hook. + } + } + + const normalizeProfile = (value: string | undefined): HookProfile => { + if (value === "minimal" || value === "strict") return value + return "standard" + } + + const currentProfile = normalizeProfile(process.env.ECC_HOOK_PROFILE) + const disabledHooks = new Set( + (process.env.ECC_DISABLED_HOOKS || "") + .split(",") + .map((item) => item.trim()) + .filter(Boolean), + ) + + const profileOrder: Record = { minimal: 0, standard: 1, strict: 2 } + + const profileAllowed = (required: HookProfile | HookProfile[]): boolean => { + if (Array.isArray(required)) { + return required.some((entry) => profileOrder[currentProfile] >= profileOrder[entry]) + } + return profileOrder[currentProfile] >= profileOrder[required] + } + + const hookEnabled = (hookId: string, requiredProfile: HookProfile | HookProfile[] = "standard"): boolean => { + if (disabledHooks.has(hookId)) return false + return profileAllowed(requiredProfile) + } + + // ECC root detection (see ECC_ROOT_PROBES rationale above). + const trackerRoot = findEccRootDir(PLUGIN_DIR, ECC_ROOT_PROBES.skillTracker) + const eccRoot = findEccRootDir(PLUGIN_DIR, ECC_ROOT_PROBES.resolver) ?? findEccRootDir(PLUGIN_DIR, ECC_ROOT_PROBES.root) + const eccVersion = getECCVersion(eccRoot) + + // Lazy imports so a partial install disables one capability instead of + // crashing the plugin (and previously the session) at load time (#2530). + let changedFilesStore: + | { + initStore?: (dir: string) => void + recordChange?: (p: string, t: string) => void + clearChanges?: () => void + buildTree?: (f?: string) => unknown[] + getChangedPaths?: (f?: string) => { path: string; changeType: string }[] + hasChanges?: () => boolean + } + | undefined try { - return fs.statSync(resolvePath(relativePath)).isFile() + const store = (await import(pathToFileURL(path.join(PLUGIN_DIR, "lib", "changed-files-store.ts")).href)) as any + store.initStore?.(worktreePath) + changedFilesStore = store } catch { - return false - } - } - - const pendingToolChanges = new Map() - let writeCounter = 0 - - function getFilePath(args: ToolArgs | undefined): string | null { - if (!args) return null - const p = (args.filePath ?? args.file_path ?? args.path) as string | undefined - return typeof p === "string" && p.trim() ? p : null - } - - // Helper to call the SDK's log API with correct signature - const log = (level: "debug" | "info" | "warn" | "error", message: string) => - client.app.log({ body: { service: "ecc", level, message } }) - - // Loaded lazily (instead of via a top-level import) so that a missing or - // partially-installed `~/.opencode/plugins/lib` directory (e.g. an - // interrupted or partial ECC install on Termux/Android) only disables - // changed-files tracking, rather than throwing during module evaluation. - // This plugin is OpenCode's startup entry point, so a static import - // failure here previously crashed the whole plugin -- and with it, the - // entire OpenCode session -- before any hooks could load (see #2530). - let changedFilesStore: typeof import("./lib/changed-files-store.ts") | undefined - try { - const store = await import("./lib/changed-files-store.ts") - store.initStore(worktreePath) - changedFilesStore = store - } catch { - // Best-effort diagnostic only: deferred via .then() (rather than - // Promise.resolve(log(...))) so that even a *synchronous* throw inside - // log() -- not just an async rejection -- is caught here instead of - // escaping this catch block. The raw loader error is intentionally not - // included in the message since it can contain absolute filesystem - // paths; this whole block exists to guarantee startup resilience even - // when things go wrong. - Promise.resolve() - .then(() => - log( - "warn", - "[ECC] changed-files tracking disabled: could not load the changed-files store. " + - "Run `ecc repair --target opencode` to restore the missing files. Other ECC hooks are unaffected." - ) + log( + "warn", + "[ECC] changed-files tracking disabled: could not load the changed-files store. " + + "Run `ecc repair --target opencode` to restore the missing files. Other ECC hooks are unaffected.", ) - .catch(() => {}) - } + } - // Claude Code routes post:skill:track through - // scripts/hooks/posttooluse-dispatcher.js, which OpenCode never invokes. - // Without a caller here, nothing ever writes skill-runs.jsonl and - // `skills-health.js --dashboard` has no data to report on any skill (#2463). - // - // The tracker module is reused rather than reimplemented so its identifier - // validation, length bounds and "never persist prompt text" guarantees stay - // the ones that were written and audited for the Claude Code path. - // - // Loaded lazily, for the same reason as the store above: this file is - // OpenCode's startup entry point, and a static import of a missing module - // crashes the plugin -- and with it the whole session -- before any hook can - // run (#2530). A runtime file URL also keeps tsc from resolving a relative - // specifier that exists in no compiled layout. - type SkillRunTrackerModule = { run?: (payload: unknown) => void } - let recordSkillRun: ((payload: unknown) => void) | undefined - // Detection is scoped to the tracker itself, so a modular install that omits - // optional content still gets telemetry. - const trackerRoot = findEccRootDir(PLUGIN_DIR, ECC_ROOT_PROBES.skillTracker) - // The root advertised to commands is a different question: those commands - // require the resolver, so a root without it would break them again. - const eccRoot = - findEccRootDir(PLUGIN_DIR, ECC_ROOT_PROBES.resolver) ?? findEccRootDir(PLUGIN_DIR, ECC_ROOT_PROBES.root) - try { - const trackerPath = trackerRoot - ? path.join(trackerRoot, "scripts", "hooks", "skill-run-tracker.js") - : null - if (!trackerPath || !fs.existsSync(trackerPath)) { - throw new Error("skill-run-tracker.js not found") - } - // CJS module loaded from ESM: run() is on the namespace in Node/Bun, but a - // transpiled default export must stay supported. - const loaded = (await import(pathToFileURL(trackerPath).href)) as SkillRunTrackerModule & { - default?: SkillRunTrackerModule - } - const entry = typeof loaded.run === "function" ? loaded : loaded.default - if (!entry || typeof entry.run !== "function") { - throw new Error("skill-run-tracker.js exposes no run()") - } - recordSkillRun = entry.run - } catch { - // Same deferred-log rationale as the store above: guarantee that a - // telemetry failure can never escape this catch and abort startup. - Promise.resolve() - .then(() => - log( - "warn", - "[ECC] skill-run telemetry disabled: could not load scripts/hooks/skill-run-tracker.js. " + - "Run `ecc repair --target opencode` to restore the missing files. Other ECC hooks are unaffected." - ) + let recordSkillRun: ((payload: unknown) => void) | undefined + try { + const trackerPath = trackerRoot ? path.join(trackerRoot, "scripts", "hooks", "skill-run-tracker.js") : null + if (!trackerPath || !fs.existsSync(trackerPath)) { + throw new Error("skill-run-tracker.js not found") + } + // CJS module loaded from ESM: run() is on the namespace in Node/Bun, but + // a transpiled default export must stay supported. + const loaded = (await import(pathToFileURL(trackerPath).href)) as { run?: (p: unknown) => void; default?: { run?: (p: unknown) => void } } + const entry = typeof loaded.run === "function" ? loaded : loaded.default + if (!entry || typeof entry.run !== "function") { + throw new Error("skill-run-tracker.js exposes no run()") + } + recordSkillRun = entry.run + } catch { + log( + "warn", + "[ECC] skill-run telemetry disabled: could not load scripts/hooks/skill-run-tracker.js. " + + "Run `ecc repair --target opencode` to restore the missing files. Other ECC hooks are unaffected.", ) - .catch(() => {}) - } - - const normalizeProfile = (value: string | undefined): HookProfile => { - if (value === "minimal" || value === "strict") return value - return "standard" - } - - const currentProfile = normalizeProfile(process.env.ECC_HOOK_PROFILE) - const disabledHooks = new Set( - (process.env.ECC_DISABLED_HOOKS || "") - .split(",") - .map((item) => item.trim()) - .filter(Boolean) - ) - - const profileOrder: Record = { - minimal: 0, - standard: 1, - strict: 2, - } - - const profileAllowed = (required: HookProfile | HookProfile[]): boolean => { - if (Array.isArray(required)) { - return required.some((entry) => profileOrder[currentProfile] >= profileOrder[entry]) } - return profileOrder[currentProfile] >= profileOrder[required] - } - const hookEnabled = ( - hookId: string, - requiredProfile: HookProfile | HookProfile[] = "standard" - ): boolean => { - if (disabledHooks.has(hookId)) return false - return profileAllowed(requiredProfile) - } + // ------------------------------------------------------------------ + // Hook implementations (bodies preserved from the V1 plugin) + // ------------------------------------------------------------------ - return { - /** - * Prettier Auto-Format Hook - * Equivalent to Claude Code PostToolUse hook for prettier - * - * Triggers: After any JS/TS/JSX/TSX file is edited - * Action: Runs prettier --write on the file - */ - "file.edited": async (event: { path: string }) => { - editedFiles.add(event.path) - changedFilesStore?.recordChange(event.path, "modified") + /** Prettier auto-format + console.log warning + change tracking. */ + const onFileEdited = async (filePath: string) => { + try { + editedFiles.add(filePath) + changedFilesStore?.recordChange?.(filePath, "modified") - // Auto-format JS/TS files - if (hookEnabled("post:edit:format", ["strict"]) && event.path.match(/\.(ts|tsx|js|jsx)$/)) { - try { - await $`prettier --write ${event.path} 2>/dev/null` - log("info", `[ECC] Formatted: ${event.path}`) - } catch (error: unknown) { - // Prettier not installed or failed - log but continue - const errorMessage = error instanceof Error ? error.message : String(error) - log("debug", `[ECC] Prettier formatting failed for ${event.path}: ${errorMessage}`) - } - } - - // Console.log warning check - if (hookEnabled("post:edit:console-warn", ["standard", "strict"]) && event.path.match(/\.(ts|tsx|js|jsx)$/)) { - try { - const result = await $`grep -n "console\\.log" ${event.path} 2>/dev/null`.text() - if (result.trim()) { - const lines = result.trim().split("\n").length - log( - "warn", - `[ECC] console.log found in ${event.path} (${lines} occurrence${lines > 1 ? "s" : ""})` - ) - } - } catch { - // No console.log found (grep returns non-zero) - this is good - } - } - }, - - /** - * TypeScript Check Hook - * Equivalent to Claude Code PostToolUse hook for tsc - * - * Triggers: After edit tool completes on .ts/.tsx files - * Action: Runs tsc --noEmit to check for type errors - */ - "tool.execute.after": async ( - input: ToolInput, - output: unknown - ) => { - const filePath = getFilePath(input.args) - if (input.tool === "edit" && filePath) { - changedFilesStore?.recordChange(filePath, "modified") - } - if (input.tool === "write" && filePath) { - const key = input.callID ?? `write-${++writeCounter}-${filePath}` - const pending = pendingToolChanges.get(key) - if (pending) { - changedFilesStore?.recordChange(pending.path, pending.type) - pendingToolChanges.delete(key) - } else { - changedFilesStore?.recordChange(filePath, "modified") - } - } - - // Check if a TypeScript file was edited - if ( - hookEnabled("post:edit:typecheck", ["strict"]) && - input.tool === "edit" && - input.args?.filePath?.match(/\.tsx?$/) - ) { - try { - await $`npx tsc --noEmit 2>&1` - log("info", "[ECC] TypeScript check passed") - } catch (error: unknown) { - const err = error as { stdout?: string } - log("warn", "[ECC] TypeScript errors detected:") - if (err.stdout) { - // Log first few errors - const errors = err.stdout.split("\n").slice(0, 5) - errors.forEach((line: string) => log("warn", ` ${line}`)) - } - } - } - - // PR creation logging - if ( - hookEnabled("post:bash:pr-created", ["standard", "strict"]) && - input.tool === "bash" && - input.args?.toString().includes("gh pr create") - ) { - log("info", "[ECC] PR created - check GitHub Actions status") - } - - // Skill telemetry (#2463). OpenCode's tool is named `skill`, so the - // harness-side name is matched here (case-insensitively) and the payload - // is handed over in the shape the tracker already understands. - if ( - hookEnabled("post:skill:track", ["standard", "strict"]) && - typeof input.tool === "string" && - input.tool.trim().toLowerCase() === "skill" - ) { - try { - recordSkillRun?.({ - tool_name: "Skill", - tool_input: input.args ?? {}, - tool_response: output, - }) - } catch { - // Telemetry is best-effort; never let it affect the tool result. - } - } - }, - - /** - * Pre-Tool Security Check - * Equivalent to Claude Code PreToolUse hook - * - * Triggers: Before tool execution - * Action: Warns about potential security issues - */ - "tool.execute.before": async ( - input: ToolInput - ) => { - if (input.tool === "write") { - const filePath = getFilePath(input.args) - if (filePath) { - const absPath = resolvePath(filePath) - let type: "added" | "modified" = "modified" + if (hookEnabled("post:edit:format", ["strict"]) && /\.(ts|tsx|js|jsx)$/.test(filePath)) { try { - if (typeof fs.existsSync === "function") { - type = fs.existsSync(absPath) ? "modified" : "added" - } - } catch { - type = "modified" + await run("npx", ["prettier", "--write", filePath], { cwd: worktreePath }) + log("info", `[ECC] Formatted: ${filePath}`) + } catch (error: unknown) { + const errorMessage = error instanceof Error ? error.message : String(error) + log("debug", `[ECC] Prettier formatting failed for ${filePath}: ${errorMessage}`) } - const key = input.callID ?? `write-${++writeCounter}-${filePath}` - pendingToolChanges.set(key, { path: filePath, type }) } - } - // Git push review reminder - if ( - hookEnabled("pre:bash:git-push-reminder", "strict") && - input.tool === "bash" && - input.args?.toString().includes("git push") - ) { - log( - "info", - "[ECC] Remember to review changes before pushing: git diff origin/main...HEAD" - ) + if (hookEnabled("post:edit:console-warn", ["standard", "strict"]) && /\.(ts|tsx|js|jsx)$/.test(filePath)) { + const count = await countConsoleLogs(filePath).catch(() => 0) + if (count > 0) { + log("warn", `[ECC] console.log found in ${filePath} (${count} occurrence${count > 1 ? "s" : ""})`) + } + } + } catch (error: unknown) { + const errorMessage = error instanceof Error ? error.message : String(error) + log("debug", `[ECC] file.edited hook failed: ${errorMessage}`) } + } - // Block creation of unnecessary documentation files - if ( - hookEnabled("pre:write:doc-file-warning", ["standard", "strict"]) && - input.tool === "write" && - input.args?.filePath && - typeof input.args.filePath === "string" - ) { - const filePath = input.args.filePath + /** Pre-tool: change bookkeeping, git-push/tmux reminders, doc-file warning. */ + const onToolBefore = async (event: LooseRecord) => { + try { + const toolName: string = event.tool ?? event.name ?? "" + const args = (event.input ?? event.args) as ToolArgs | undefined + const callId: string | undefined = event.callID ?? event.id + + if (toolName === "write") { + const filePath = getFilePath(args) + if (filePath) { + const absPath = resolvePath(filePath) + let type: "added" | "modified" = "modified" + try { + type = fs.existsSync(absPath) ? "modified" : "added" + } catch { + type = "modified" + } + const key = callId ?? `write-${++writeCounter}-${filePath}` + pendingToolChanges.set(key, { path: filePath, type }) + } + } + + // Git push review reminder + if (hookEnabled("pre:bash:git-push-reminder", "strict") && toolName === "bash") { + const cmd = String(args?.command ?? args ?? "") + if (cmd.includes("git push")) { + log("info", "[ECC] Remember to review changes before pushing: git diff origin/main...HEAD") + } + } + + // Block creation of unnecessary documentation files + if (hookEnabled("pre:write:doc-file-warning", ["standard", "strict"]) && toolName === "write") { + const filePath = getFilePath(args) + if ( + filePath && + /\.(md|txt)$/i.test(filePath) && + !filePath.includes("README") && + !filePath.includes("CHANGELOG") && + !filePath.includes("LICENSE") && + !filePath.includes("CONTRIBUTING") + ) { + log("warn", `[ECC] Creating ${filePath} - consider if this documentation is necessary`) + } + } + + // Long-running command reminder + if (hookEnabled("pre:bash:tmux-reminder", "strict") && toolName === "bash") { + const cmd = String(args?.command ?? args ?? "") + if ( + cmd.match(/^(npm|pnpm|yarn|bun)\s+(install|build|test|run)/) || + cmd.match(/^cargo\s+(build|test|run)/) || + cmd.match(/^go\s+(build|test|run)/) + ) { + log("info", "[ECC] Long-running command detected - consider using background execution") + } + } + } catch (error: unknown) { + const errorMessage = error instanceof Error ? error.message : String(error) + log("debug", `[ECC] tool.execute.before hook failed: ${errorMessage}`) + } + } + + /** Post-tool: change recording, typecheck, PR log, skill telemetry. */ + const onToolAfter = async (event: LooseRecord) => { + try { + const toolName: string = event.tool ?? event.name ?? "" + const args = (event.input ?? event.args) as ToolArgs | undefined + const callId: string | undefined = event.callID ?? event.id + + const filePath = getFilePath(args) + if (toolName === "edit" && filePath) { + changedFilesStore?.recordChange?.(filePath, "modified") + } + if (toolName === "write" && filePath) { + const key = callId ?? `write-${++writeCounter}-${filePath}` + const pending = pendingToolChanges.get(key) + if (pending) { + changedFilesStore?.recordChange?.(pending.path, pending.type) + pendingToolChanges.delete(key) + } else { + changedFilesStore?.recordChange?.(filePath, "modified") + } + } + + // TypeScript check (strict profile only - it shells out to tsc). if ( - filePath.match(/\.(md|txt)$/i) && - !filePath.includes("README") && - !filePath.includes("CHANGELOG") && - !filePath.includes("LICENSE") && - !filePath.includes("CONTRIBUTING") + hookEnabled("post:edit:typecheck", ["strict"]) && + toolName === "edit" && + typeof args?.filePath === "string" && + /\.tsx?$/.test(args.filePath) ) { - log( - "warn", - `[ECC] Creating ${filePath} - consider if this documentation is necessary` - ) + const result = await run("npx", ["tsc", "--noEmit"], { cwd: worktreePath }).catch(() => null) + if (result && result.code === 0) { + log("info", "[ECC] TypeScript check passed") + } else if (result) { + log("warn", "[ECC] TypeScript errors detected:") + const out = (result.stdout || result.stderr || "").split("\n").slice(0, 5) + out.forEach((line) => line.trim() && log("warn", ` ${line}`)) + } } - } - // Long-running command reminder - if (hookEnabled("pre:bash:tmux-reminder", "strict") && input.tool === "bash") { - const cmd = String(input.args?.command || input.args || "") + // PR creation logging if ( - cmd.match(/^(npm|pnpm|yarn|bun)\s+(install|build|test|run)/) || - cmd.match(/^cargo\s+(build|test|run)/) || - cmd.match(/^go\s+(build|test|run)/) + hookEnabled("post:bash:pr-created", ["standard", "strict"]) && + toolName === "bash" && + String(args?.command ?? args ?? "").includes("gh pr create") ) { - log( - "info", - "[ECC] Long-running command detected - consider using background execution" - ) + log("info", "[ECC] PR created - check GitHub Actions status") } + + // Skill telemetry (#2463): OpenCode's tool is named `skill`. + if ( + hookEnabled("post:skill:track", ["standard", "strict"]) && + typeof toolName === "string" && + toolName.trim().toLowerCase() === "skill" + ) { + try { + recordSkillRun?.({ + tool_name: "Skill", + tool_input: args ?? {}, + tool_response: event.result ?? event.output, + }) + } catch { + // Telemetry is best-effort; never let it affect the tool result. + } + } + } catch (error: unknown) { + const errorMessage = error instanceof Error ? error.message : String(error) + log("debug", `[ECC] tool.execute.after hook failed: ${errorMessage}`) } - }, + } - /** - * Session Created Hook - * Equivalent to Claude Code SessionStart hook - * - * Triggers: When a new session starts - * Action: Loads context and displays welcome message - */ - "session.created": async () => { - if (!hookEnabled("session:start", ["minimal", "standard", "strict"])) return - - log("info", `[ECC] Session started - profile=${currentProfile}`) - - // Check for project-specific context files - if (hasProjectFile("CLAUDE.md")) { - log("info", "[ECC] Found CLAUDE.md - loading project context") - } - }, - - /** - * Session Idle Hook - * Equivalent to Claude Code Stop hook - * - * Triggers: When session becomes idle (task completed) - * Action: Runs console.log audit on all edited files - */ - "session.idle": async () => { + /** Session idle: console.log audit on edited files + desktop notification. */ + const onSessionIdle = async () => { if (!hookEnabled("stop:check-console-log", ["minimal", "standard", "strict"])) return if (editedFiles.size === 0) return @@ -535,119 +451,59 @@ export const ECCHooksPlugin: ECCHooksPluginFn = async ({ const filesWithConsoleLogs: string[] = [] for (const file of editedFiles) { - if (!file.match(/\.(ts|tsx|js|jsx)$/)) continue - - try { - const result = await $`grep -c "console\\.log" ${file} 2>/dev/null`.text() - const count = parseInt(result.trim(), 10) - if (count > 0) { - totalConsoleLogCount += count - filesWithConsoleLogs.push(file) - } - } catch { - // No console.log found + if (!/\.(ts|tsx|js|jsx)$/.test(file)) continue + const count = await countConsoleLogs(file).catch(() => 0) + if (count > 0) { + totalConsoleLogCount += count + filesWithConsoleLogs.push(file) } } if (totalConsoleLogCount > 0) { - log( - "warn", - `[ECC] Audit: ${totalConsoleLogCount} console.log statement(s) in ${filesWithConsoleLogs.length} file(s)` - ) - filesWithConsoleLogs.forEach((f) => - log("warn", ` - ${f}`) - ) + log("warn", `[ECC] Audit: ${totalConsoleLogCount} console.log statement(s) in ${filesWithConsoleLogs.length} file(s)`) + filesWithConsoleLogs.forEach((f) => log("warn", ` - ${f}`)) log("warn", "[ECC] Remove console.log statements before committing") } else { log("info", "[ECC] Audit passed: No console.log statements found") } - // Desktop notification (cross-platform) + // Desktop notification, best effort and never blocking: the V1 Windows + // path opened a modal MessageBox on the server; that was replaced with + // a fire-and-forget balloon tip. try { if (process.platform === "darwin") { - // macOS - await $`osascript -e 'display notification "Task completed!" with title "OpenCode ECC"' 2>/dev/null` + await run("osascript", ["-e", 'display notification "Task completed!" with title "OpenCode ECC"'], { detached: true }).catch(() => {}) } else if (process.platform === "win32") { - // Windows - PowerShell notification - await $`powershell -Command "Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.MessageBox]::Show('Task completed!', 'OpenCode ECC', 'OK', 'Information')" 2>/dev/null` + const ps = + "$ni = New-Object System.Windows.Forms.NotifyIcon; $ni.Icon = [System.Drawing.SystemIcons]::Information; " + + "$ni.Visible = $true; $ni.ShowBalloonTip('OpenCode ECC', 'Task completed!', 'Info'); " + + "Start-Sleep -Seconds 5; $ni.Dispose()" + await run("powershell", ["-NoProfile", "-WindowStyle", "Hidden", "-Command", `Add-Type -AssemblyName System.Windows.Forms; ${ps}`], { + detached: true, + }).catch(() => {}) } else if (process.platform === "linux") { - // Linux - notify-send (requires libnotify) - await $`notify-send "OpenCode ECC" "Task completed!" 2>/dev/null` + await run("notify-send", ["OpenCode ECC", "Task completed!"], { detached: true }).catch(() => {}) } } catch (error: unknown) { - // Notification not supported or failed - log but continue const errorMessage = error instanceof Error ? error.message : String(error) log("debug", `[ECC] Desktop notification failed: ${errorMessage}`) } - // Clear tracked files for next task editedFiles.clear() - }, + } - /** - * Session Deleted Hook - * Equivalent to Claude Code SessionEnd hook - * - * Triggers: When session ends - * Action: Final cleanup and state saving - */ - "session.deleted": async () => { - if (!hookEnabled("session:end-marker", ["minimal", "standard", "strict"])) return - log("info", "[ECC] Session ended - cleaning up") - editedFiles.clear() - changedFilesStore?.clearChanges() - pendingToolChanges.clear() - }, - - /** - * File Watcher Hook - * OpenCode-only feature - * - * Triggers: When file system changes are detected - * Action: Updates tracking - */ - "file.watcher.updated": async (event: { path: string; type: string }) => { - let changeType: "added" | "modified" | "deleted" = "modified" - if (event.type === "create" || event.type === "add") changeType = "added" - else if (event.type === "delete" || event.type === "remove") changeType = "deleted" - changedFilesStore?.recordChange(event.path, changeType) - if (event.type === "change" && event.path.match(/\.(ts|tsx|js|jsx)$/)) { - editedFiles.add(event.path) - } - }, - - /** - * Todo Updated Hook - * OpenCode-only feature - * - * Triggers: When todo list is updated - * Action: Logs progress - */ - "todo.updated": async (event: { todos: Array<{ text: string; done: boolean }> }) => { - const completed = event.todos.filter((t) => t.done).length - const total = event.todos.length - if (total > 0) { - log("info", `[ECC] Progress: ${completed}/${total} tasks completed`) - } - }, - - /** - * Shell Environment Hook - * OpenCode-specific: Inject environment variables into shell commands - * - * Triggers: Before shell command execution - * Action: Sets PROJECT_ROOT, PACKAGE_MANAGER, DETECTED_LANGUAGES, ECC_VERSION - */ - "shell.env": async (_input: { cwd: string }, output: { env: Record }) => { + /** Inject ECC environment variables into shell commands. */ + let cachedEnv: Record | undefined + function computeEccEnv(): Record { + if (cachedEnv) return cachedEnv const env: Record = { - ECC_VERSION: getECCVersion(eccRoot), + ECC_VERSION: eccVersion, ECC_PLUGIN: "true", ECC_HOOK_PROFILE: currentProfile, ECC_DISABLED_HOOKS: process.env.ECC_DISABLED_HOOKS || "", PROJECT_ROOT: worktreePath, } - // Detect package manager const lockfiles: Record = { "bun.lockb": "bun", "pnpm-lock.yaml": "pnpm", @@ -661,7 +517,6 @@ export const ECCHooksPlugin: ECCHooksPluginFn = async ({ } } - // Detect languages const langDetectors: Record = { "tsconfig.json": "typescript", "go.mod": "go", @@ -671,56 +526,32 @@ export const ECCHooksPlugin: ECCHooksPluginFn = async ({ } const detected: string[] = [] for (const [file, lang] of Object.entries(langDetectors)) { - if (hasProjectFile(file)) { - detected.push(lang) - } + if (hasProjectFile(file)) detected.push(lang) } if (detected.length > 0) { env.DETECTED_LANGUAGES = detected.join(",") env.PRIMARY_LANGUAGE = detected[0] } - // resolve-ecc-root.js only probes ~/.claude and Claude Code's plugin - // cache, so under OpenCode it fell back to ~/.claude and every command - // carrying the inlined resolver failed to find its scripts. That resolver - // reads CLAUDE_PLUGIN_ROOT first, so exporting the root here fixes them - // through the mechanism ECC already provides -- rather than editing the - // command files that embed the locator. - // - // Only set when a root actually exists, and never replace a root someone - // else already chose: neither the process environment (set by the user) - // nor `output.env` (set by an earlier plugin). The final merge below - // overwrites output.env, so checking it only in `env` would clobber it. - const rootAlreadySet = Boolean( - (process.env.CLAUDE_PLUGIN_ROOT || "").trim() || - (output.env?.CLAUDE_PLUGIN_ROOT || "").trim() - ) - if (eccRoot && !rootAlreadySet) { + // Commands embed resolve-ecc-root.js, which reads CLAUDE_PLUGIN_ROOT + // first; exporting the root here fixes them without editing command files. + // Never replace a root someone else already chose. + if (eccRoot && !(process.env.CLAUDE_PLUGIN_ROOT || "").trim()) { env.CLAUDE_PLUGIN_ROOT = eccRoot } - // OpenCode reads the supplied output object and ignores callback return values. - output.env = { ...output.env, ...env } - }, + cachedEnv = env + return env + } - /** - * Session Compacting Hook - * OpenCode-specific: Control context compaction behavior - * - * Triggers: Before context compaction - * Action: Push ECC context block and compaction guidance - */ - "experimental.session.compacting": async ( - _input: { sessionID: string }, - output: { context: string[]; prompt?: string } - ) => { + /** ECC context block preserved through compaction. */ + function buildCompactionContext(): string { const contextBlock = [ "# ECC Context (preserve across compaction)", "", - "## Active Plugin: ECC v2.2.3", - "- Hooks: file.edited, tool.execute.before/after, session.created/idle/deleted, shell.env, compacting, permission.ask", - "- Tools: run-tests, check-coverage, security-audit, format-code, lint-check, git-summary, changed-files", - "- Agents: 13 specialized (planner, architect, tdd-guide, code-reviewer, security-reviewer, build-error-resolver, e2e-runner, refactor-cleaner, doc-updater, go-reviewer, go-build-resolver, database-reviewer, python-reviewer)", + `## Active Plugin: ECC v${eccVersion}`, + "- Hooks: file.edited, tool.execute.before/after, session.created/idle/deleted, shell env, compaction, permission", + "- Tools: changed-files, dependency-analyzer", "", "## Key Principles", "- TDD: write tests first, 80%+ coverage", @@ -729,83 +560,242 @@ export const ECCHooksPlugin: ECCHooksPluginFn = async ({ "", ] - // Include recently edited files if (editedFiles.size > 0) { contextBlock.push("## Recently Edited Files") - for (const f of editedFiles) { - contextBlock.push(`- ${f}`) - } + for (const f of editedFiles) contextBlock.push(`- ${f}`) contextBlock.push("") } - const eccContext = [ - contextBlock.join("\n"), + contextBlock.push( "Focus on preserving: 1) Current task status and progress, 2) Key decisions made, 3) Files created/modified, 4) Remaining work items, 5) Any security concerns flagged. Discard: verbose tool outputs, intermediate exploration, redundant file listings.", - ] + ) + return contextBlock.join("\n") + } - // OpenCode requires output assignment and skips context when a prompt is set. - if (output.prompt !== undefined) { - output.prompt = [output.prompt, ...eccContext].join("\n\n") - } else { - output.context = [...output.context, ...eccContext] - } - }, - - /** - * Permission Auto-Approve Hook - * OpenCode-specific: Auto-approve safe operations - * - * Triggers: When permission is requested - * Action: Auto-approve reads, formatters, and test commands; log all for audit - */ - "permission.ask": async (event: PermissionEvent) => { - log("info", `[ECC] Permission requested for: ${event.tool}`) + /** Auto-approve safe operations on top of the configured rules. */ + const READ_ONLY_ACTIONS = ["read", "glob", "grep", "search", "list"] + const FORMATTER_RE = /^(npx )?(@biomejs\/biome|prettier|black|gofmt|rustfmt|swift-format)/ + const TEST_RE = /^(npm test|npx vitest|npx jest|pytest|go test|cargo test)/ + const onPermissionEvaluate = async (event: LooseRecord) => { try { - // Handle both string args and object args with command property - let cmd: string - if (typeof event.args === "string") { - cmd = event.args - } else if (event.args && typeof event.args === "object") { - cmd = String((event.args as Record).command || "") - } else { - cmd = String(event.args || "") - } + const action: string = String(event.action ?? "") + const resource: string = String(event.resources?.[0] ?? "") + log("debug", `[ECC] Permission evaluated: ${action} ${resource}`) - // Auto-approve: read/search tools - if (["read", "glob", "grep", "search", "list"].includes(event.tool)) { - log("debug", `[ECC] Auto-approved read-only tool: ${event.tool}`) - return { approved: true, reason: "Read-only operation" } + if (READ_ONLY_ACTIONS.includes(action)) { + event.effect = "allow" + event.message = "ECC: read-only operation" + return } - - // Auto-approve: formatters - if (event.tool === "bash" && /^(npx )?(@biomejs\/biome|prettier|black|gofmt|rustfmt|swift-format)/.test(cmd)) { - log("debug", `[ECC] Auto-approved formatter: ${cmd}`) - return { approved: true, reason: "Formatter execution" } + if ((action === "bash" || action === "shell" || action === "execute") && (FORMATTER_RE.test(resource) || TEST_RE.test(resource))) { + event.effect = "allow" + event.message = "ECC: formatter/test execution" + return } - - // Auto-approve: test execution - if (event.tool === "bash" && /^(npm test|npx vitest|npx jest|pytest|go test|cargo test)/.test(cmd)) { - log("debug", `[ECC] Auto-approved test execution: ${cmd}`) - return { approved: true, reason: "Test execution" } - } - - // Everything else: let user decide - log("debug", `[ECC] Permission requires user approval: ${event.tool}`) - return { approved: undefined } + // Everything else: leave the configured decision in place. } catch (error: unknown) { - // Error in permission handling - log and deny for safety + // On error, keep the configured behavior rather than denying outright. const errorMessage = error instanceof Error ? error.message : String(error) - log("error", `[ECC] Permission handling error for ${event.tool}: ${errorMessage}`) - return { approved: false, reason: `Error: ${errorMessage}` } + log("error", `[ECC] Permission handling error: ${errorMessage}`) } - }, + } - tool: { - "changed-files": changedFilesTool, - "dependency-analyzer": dependencyAnalyzerTool, - }, - } + // ------------------------------------------------------------------ + // Registration on the V2 domains (each guarded so a missing domain in an + // older 2.x runtime downgrades to "capability off", not "plugin crash"). + // ------------------------------------------------------------------ + + const registrations: { dispose?: () => Promise | void }[] = [] + + if (typeof ctx?.tool?.hook === "function") { + registrations.push(await ctx.tool.hook("execute.before", onToolBefore)) + registrations.push(await ctx.tool.hook("execute.after", onToolAfter)) + } + + if (typeof ctx?.shell?.hook === "function") { + registrations.push( + await ctx.shell.hook("create.before", (event: LooseRecord) => { + try { + const eccEnv = computeEccEnv() + event.env = { ...(event.env ?? {}) } + for (const [key, value] of Object.entries(eccEnv)) { + // Never replace values set by the user or an earlier plugin. + if (event.env[key] === undefined || event.env[key] === "") event.env[key] = value + } + } catch (error: unknown) { + const errorMessage = error instanceof Error ? error.message : String(error) + log("debug", `[ECC] shell env hook failed: ${errorMessage}`) + } + }), + ) + } + + if (typeof ctx?.session?.hook === "function") { + registrations.push( + await ctx.session.hook("compaction", (event: LooseRecord) => { + try { + event.system = event.system ?? [] + event.system.push({ type: "text", text: buildCompactionContext() }) + } catch (error: unknown) { + const errorMessage = error instanceof Error ? error.message : String(error) + log("debug", `[ECC] compaction hook failed: ${errorMessage}`) + } + }), + ) + } + + if (typeof ctx?.permission?.hook === "function") { + registrations.push(await ctx.permission.hook("evaluate", onPermissionEvaluate)) + } + + // Custom tools: registered through a transform, resolving the V1 tool + // modules lazily inside execute so a broken tools/ install only affects + // these two tools when actually invoked. + const toolModuleCache = new Map>() + async function loadV1Tool(name: string): Promise<{ execute: (args: any, context: any) => Promise }> { + let p = toolModuleCache.get(name) + if (!p) { + p = import(pathToFileURL(path.resolve(PLUGIN_DIR, "..", "tools", `${name}.ts`)).href) + .then((mod: any) => (typeof mod?.default === "function" ? { execute: mod.default } : mod.default)) + .catch((error: unknown) => { + toolModuleCache.delete(name) + throw new Error( + `${name} tool: could not load ECC tool module. Run \`ecc repair --target opencode\` to restore the missing files. (${ + error instanceof Error ? error.message : String(error) + })`, + ) + }) + toolModuleCache.set(name, p) + } + return p + } + + if (typeof ctx?.tool?.transform === "function") { + registrations.push( + await ctx.tool.transform((editor: any) => { + editor.add({ + name: "changed-files", + description: + "List files changed by agents in this session as a navigable tree. Shows added (+), modified (~), and deleted (-) indicators. Use filter to show only specific change types. Returns paths for git diff.", + input: { + type: "object", + properties: { + filter: { type: "string", enum: ["all", "added", "modified", "deleted"], description: "Filter by change type (default: all)" }, + format: { type: "string", enum: ["tree", "json"], description: "Output format: tree for terminal display, json for structured data (default: tree)" }, + }, + additionalProperties: false, + }, + execute: async (input: any, context: any) => { + const mod = await loadV1Tool("changed-files") + const result = await mod.execute(input ?? {}, context ?? { directory: worktreePath, worktree: worktreePath }) + return { content: String(result) } + }, + }) + editor.add({ + name: "dependency-analyzer", + description: + "Analyze project dependencies for outdated packages, security vulnerabilities, and unused dependencies. Supports npm, pnpm, yarn, and bun.", + input: { + type: "object", + properties: { + type: { type: "string", enum: ["all", "outdated", "security", "unused"], description: "Type of analysis to run (default: all)" }, + fix: { type: "boolean", description: "Attempt to fix issues automatically (default: false)" }, + depth: { type: "number", description: "Depth of dependency analysis (default: 1)" }, + }, + additionalProperties: false, + }, + execute: async (input: any, context: any) => { + const mod = await loadV1Tool("dependency-analyzer") + const result = await mod.execute(input ?? {}, context ?? { directory: worktreePath, worktree: worktreePath }) + return { content: String(result) } + }, + }) + }), + ) + } + + // Event-driven hooks: V1 returned keyed handlers; V2 delivers these as + // public server events on a subscription stream. + const controller = new AbortController() + if (typeof ctx?.event?.subscribe === "function") { + void (async () => { + try { + for await (const event of ctx.event.subscribe({ signal: controller.signal })) { + const type: string = event?.type ?? "" + const props: LooseRecord = event?.properties ?? event ?? {} + try { + switch (type) { + case "file.edited": { + const p = props.file ?? props.path ?? props.filePath + if (typeof p === "string") await onFileEdited(p) + break + } + case "file.watcher.updated": { + const p = props.file ?? props.path + if (typeof p !== "string") break + const changeType = props.type + let mapped: "added" | "modified" | "deleted" = "modified" + if (changeType === "create" || changeType === "add") mapped = "added" + else if (changeType === "delete" || changeType === "remove") mapped = "deleted" + changedFilesStore?.recordChange?.(p, mapped) + if (changeType === "change" && /\.(ts|tsx|js|jsx)$/.test(p)) editedFiles.add(p) + break + } + case "session.created": { + if (!hookEnabled("session:start", ["minimal", "standard", "strict"])) break + log("info", `[ECC] Session started - profile=${currentProfile}`) + if (hasProjectFile("CLAUDE.md")) log("info", "[ECC] Found CLAUDE.md - loading project context") + break + } + case "session.idle": { + await onSessionIdle() + break + } + case "session.deleted": { + if (!hookEnabled("session:end-marker", ["minimal", "standard", "strict"])) break + log("info", "[ECC] Session ended - cleaning up") + editedFiles.clear() + changedFilesStore?.clearChanges?.() + pendingToolChanges.clear() + break + } + case "todo.updated": { + const todos: { done: boolean }[] = Array.isArray(props.todos) ? props.todos : [] + if (todos.length > 0) { + const completed = todos.filter((t) => t.done).length + log("info", `[ECC] Progress: ${completed}/${todos.length} tasks completed`) + } + break + } + default: + break + } + } catch (error: unknown) { + const errorMessage = error instanceof Error ? error.message : String(error) + log("debug", `[ECC] event ${type} handler failed: ${errorMessage}`) + } + } + } catch { + // Subscription aborted during unload - expected. + } + })() + } + + log("info", `[ECC] hooks plugin v${eccVersion} loaded (profile=${currentProfile}, directory=${worktreePath})`) + + return () => { + controller.abort() + registeredDirectories.delete(worktreePath) + for (const registration of registrations) { + try { + void registration?.dispose?.() + } catch { + // Best-effort dispose. + } + } + } + }, } -export default ECCHooksPlugin +export default ECCHooksPluginDefinition diff --git a/.opencode/plugins/index.ts b/.opencode/plugins/index.ts index 3a98f0ba6..7db884e16 100644 --- a/.opencode/plugins/index.ts +++ b/.opencode/plugins/index.ts @@ -1,12 +1,27 @@ /** - * ECC Plugins for OpenCode + * ECC plugins directory entry for OpenCode 2.x. * - * This module exports all ECC plugins for OpenCode integration. - * Plugins provide hook-based automation that mirrors Claude Code's hook system - * while taking advantage of OpenCode's more sophisticated 20+ event types. + * This file is intentionally inert in normal installs. OpenCode 2.x loads + * every root-level `.ts` file in a plugins directory AND the directory + * itself through this entry point, so re-exporting the real plugin from + * here would register the id `ecc-hooks` twice and OpenCode would mark the + * extra entries `failed: Duplicate plugin ID` (shown in red in the TUI + * plugins panel). + * + * The configuration in `.opencode/opencode.json` therefore points directly + * at `./plugins/ecc-hooks.ts`. This stub keeps: + * - the file present for the installer/uninstall plan (`ecc repair`), and + * - a distinct id so a stray directory load can never collide with or + * shadow the real hooks plugin, and never throws the V2 schema error + * ("Plugin must export a default definition with an id and an effect or + * setup function") that a plain non-plugin module would cause. + * + * Do not add hook logic here; it belongs in `ecc-hooks.ts` only. */ -export { ECCHooksPlugin, default } from "./ecc-hooks.ts" - -// Re-export for named imports -export * from "./ecc-hooks.ts" +export default { + id: "ecc-hooks-entry", + setup() { + return () => {} + }, +} diff --git a/TROUBLESHOOTING.md b/TROUBLESHOOTING.md index 719415468..1ec2013e1 100644 --- a/TROUBLESHOOTING.md +++ b/TROUBLESHOOTING.md @@ -343,6 +343,86 @@ third-party [`oh-my-opencode-slim`](https://github.com/alvinunreal/oh-my-opencod plugin, not ECC — ECC never writes to `~/.config/opencode/`. Fix the model prefix (`opencode/...` instead of `openai/...`) there, or file it against that project. +### OpenCode 2.x: `PluginModule.LoadError` and red "Duplicate plugin ID" entries + +**Symptoms (two distinct failures, often in sequence):** + +1. Red startup banner / log lines: + + ``` + PluginModule.LoadError: Plugin must export a default definition with an id and + an effect or setup function. (cause: SchemaError(Expected object at ["default"])) + ``` + + reported against `plugins/ecc-hooks.ts` (global or project `.opencode/plugins/`). + +2. After a first fix attempt, the TUI plugins panel shows `ecc-hooks` multiple + times with red entries reading `Duplicate plugin ID: ecc-hooks`, even though + the hooks themselves are working. + +**Causes:** + +- **V1 plugin on a V2 runtime.** OpenCode 1.x plugins default-export an async + function returning a keyed hook map. OpenCode 2.x requires a definition object + `{ id, setup(ctx) }` and does not run V1 implementations (see + [migrate-v1](https://opencode.ai/v2/docs/build/plugins/migrate-v1)). Cause A + produces the `Expected object at ["default"]` schema error. +- **Triple registration.** OpenCode 2.x scans every root-level `.ts` file in a + plugins directory **and** loads the directory itself through its `index.ts`. + If `index.ts` re-exports the same definition (or points at `ecc-hooks.ts`), + the id `ecc-hooks` registers two-to-three times; all but the first entry are + marked `failed: Duplicate plugin ID`. + +**Fix layout (current design):** + +- `.opencode/plugins/ecc-hooks.ts` is the only file carrying hook logic. V1 → + V2 registration mapping: `tool.execute.before/after` → + `ctx.tool.hook(...)`, `shell.env` → `ctx.shell.hook("create.before", ...)`, + `permission.ask` → `ctx.permission.hook("evaluate", ...)` (mutate + `event.effect`), keyed event handlers (`file.edited`, `session:*`, + `todo.updated`) → `ctx.event.subscribe()` filtered on `event.type`. +- `opencode.json` lists `"plugin": ["./plugins/ecc-hooks.ts"]` — the exact + file, **not** `"./plugins"` — so the directory is never loaded as a second + package. +- `plugins/index.ts` is an inert stub with the distinct id + `ecc-hooks-entry`. Never make it re-export the real definition: that is + exactly what triggers the duplicate-id failures. It must keep a default + export with an id + setup (a plain non-plugin module in a loaded directory + would throw the schema error again), and it must remain present on disk for + the install/uninstall plans. + +**Diagnosing (do this before editing anything):** + +1. Read the server log, and check the `run=` id and timestamp of every error + line — TUI banners survive from a process that predates your fix, so match + errors against the *current* run only: + + ``` + ~/.local/share/opencode/log/opencode.log # Windows, Linux, Termux + ``` + +2. Ignore unrelated network noise when triaging plugins: `Failed to fetch + models.dev`, `failed to sync GitHub Copilot models: 403`, and + `update check failed` are connectivity/auth issues, not hook failures. + +3. Query the live plugin table — this is the ground truth behind the TUI + panel. The server port comes from `opencode service status`; credentials + are Basic auth with the `password` field of `~/.config/opencode/service.json`: + + ```bash + curl -s -u "opencode:$(sed -n 's/.*"password": "\(.*\)".*/\1/p' ~/.config/opencode/service.json)" \ + http://127.0.0.1:/api/plugin | jq '[.data[] | select(.state.status != "active")]' + ``` + +4. `opencode plugin list` shows each registered entry with its source path. + The same id appearing from two-plus sources predicts a duplicate-ID + rejection. + +**Environment-variable note:** `ECC_HOOK_PROFILE` / `ECC_DISABLED_HOOKS` are +read once at plugin setup. On Windows, `setx` affects only *new* processes, and +a service restarted from a terminal that predates the `setx` still inherits the +stale environment block — restart from a freshly opened terminal. + --- ## Performance Issues