feat(write-existing-file-guard): add hook to prevent write tool from overwriting existing files

Adds a PreToolUse hook that intercepts write operations and throws an error
if the target file already exists, guiding users to use the edit tool instead.

- Throws error: 'File already exists. Use edit tool instead.'
- Hook is enabled by default, can be disabled via disabled_hooks
- Includes comprehensive test suite with BDD-style comments
This commit is contained in:
YeonGyu-Kim
2026-02-04 16:05:00 +09:00
parent 8049ceb947
commit ddf878e53c
5 changed files with 246 additions and 0 deletions
@@ -0,0 +1,33 @@
import type { Hooks, PluginInput } from "@opencode-ai/plugin"
import { existsSync } from "fs"
import { resolve, isAbsolute } from "path"
import { log } from "../../shared"
export function createWriteExistingFileGuardHook(ctx: PluginInput): Hooks {
return {
"tool.execute.before": async (input, output) => {
const toolName = input.tool?.toLowerCase()
if (toolName !== "write") {
return
}
const args = output.args as { filePath?: string; path?: string; file_path?: string } | undefined
const filePath = args?.filePath ?? args?.path ?? args?.file_path
if (!filePath) {
return
}
const resolvedPath = isAbsolute(filePath) ? filePath : resolve(ctx.directory, filePath)
if (existsSync(resolvedPath)) {
log("[write-existing-file-guard] Blocking write to existing file", {
sessionID: input.sessionID,
filePath,
resolvedPath,
})
throw new Error("File already exists. Use edit tool instead.")
}
},
}
}