Files
zero/internal/tools/edit_file.go
KRATOS 06ea4f004b Edit safety: file read/write tracking, external-modification detection, post-apply hooks (#172)
* Edit safety: file version tracking, conflict detection, hook wiring

Phase 1 — FileTracker (internal/tools/file_tracker.go): per-session
map[absPath]{sha256, size, mtime}; CheckConflict flags drift only against
a known baseline, so first-touch writes are unaffected. nil = no-op.

Phase 2 — external-modification detection: read_file records the
whole-file baseline; edit_file and write_file --overwrite refuse to
clobber a file whose on-disk content drifted from it and tell the model
to re-read first, then re-baseline to what they wrote. apply_patch
forgets the files it rewrote (git apply has its own context guard).
Threaded via RunOptions/agent.Options FileTracker, built once per session
in the exec, spec, and TUI paths.

Phase 3 — post-apply validation via hooks: the dormant hooks.Dispatcher
is wired into executeToolCall. beforeTool hooks can veto a call
(DenialHookBlocked); afterTool hook output is scrubbed and surfaced to
the model. DispatchOutcome now collects hook stdout/stderr. Per-session
dispatcher built from merged user+project hooks.json; fails open and runs
nothing until a hook is configured.

* edit-safety: address review — fail closed on read, redact hook reason

- write_file overwrite: if a tracked file cannot be re-read to verify it,
  fail CLOSED (refuse the overwrite) instead of silently proceeding — the
  read error previously skipped the conflict check and could clobber an
  externally modified or replaced file.
- blockedByHookResult: scrub outcome.Reason through redaction before placing
  it in model-visible ToolResult.Output; this intercepted path bypassed the
  registry's normal output-redaction boundary.
- TestHashContentIsStableAndDistinguishing: compare separately stored hashes
  so the stability check is not a same-expression comparison (SA4000).

* edit-safety: flag ToolResult.Redacted when hook output is scrubbed

appendHookFeedback now reports whether scrubbing changed the afterTool
feedback, and blockedByHookResult reports whether it scrubbed the reason;
both set ToolResult.Redacted so the hook-intercepted paths match the
registry's redaction contract. Adds tests asserting a secret-bearing hook
reason/feedback is scrubbed and flips Redacted.
2026-06-11 20:34:35 +05:30

119 lines
4.6 KiB
Go

package tools
import (
"context"
"fmt"
"os"
"strings"
)
type editFileTool struct {
baseTool
workspaceRoot string
scope PathScope
}
func NewEditFileTool(workspaceRoot string) Tool {
return NewScopedEditFileTool(workspaceRoot, nil)
}
func NewScopedEditFileTool(workspaceRoot string, scope PathScope) Tool {
return editFileTool{
baseTool: baseTool{
name: "edit_file",
description: "Replace an exact string in an existing file with uniqueness protection by default.",
parameters: Schema{
Type: "object",
Properties: map[string]PropertySchema{
"path": {Type: "string", Description: "Path of the file to edit."},
"old_string": {Type: "string", Description: "Exact string to replace. Must match byte-for-byte."},
"new_string": {Type: "string", Description: "Replacement string. May be empty."},
"replace_all": {Type: "boolean", Description: "Replace every occurrence instead of requiring uniqueness.", Default: false},
},
Required: []string{"path", "old_string", "new_string"},
AdditionalProperties: false,
},
safety: promptSafety(SideEffectWrite, "Edits files in place."),
},
workspaceRoot: normalizeWorkspaceRoot(workspaceRoot),
scope: scope,
}
}
func (tool editFileTool) Run(ctx context.Context, args map[string]any) Result {
return tool.RunWithOptions(ctx, args, RunOptions{})
}
func (tool editFileTool) RunWithOptions(_ context.Context, args map[string]any, options RunOptions) Result {
requestedPath, err := aliasedStringArg(args, []string{"path", "file", "file_path", "filename"}, "", true, false)
if err != nil {
return errorResult("Error: Invalid arguments for edit_file: " + err.Error())
}
oldString, err := aliasedStringArg(args, []string{"old_string", "old", "search", "find", "old_str"}, "", true, false)
if err != nil {
return errorResult("Error: Invalid arguments for edit_file: " + err.Error())
}
newString, err := aliasedStringArg(args, []string{"new_string", "new", "replace", "replacement", "new_str"}, "", true, true)
if err != nil {
return errorResult("Error: Invalid arguments for edit_file: " + err.Error())
}
replaceAll, err := boolArg(args, "replace_all", false)
if err != nil {
return errorResult("Error: Invalid arguments for edit_file: " + err.Error())
}
absolutePath, relativePath, err := resolveScopedPath(tool.workspaceRoot, tool.scope, requestedPath)
if err != nil {
return errorResult("Error reading " + requestedPath + ": " + err.Error())
}
contentBytes, err := os.ReadFile(absolutePath)
if err != nil {
return errorResult("Error reading " + relativePath + ": " + err.Error())
}
// Refuse to edit a file that changed on disk outside Zero since it was last
// read: the model's old_string was formed against a stale view, so applying it
// now could silently corrupt the newer content.
if cerr := options.FileTracker.CheckConflict(absolutePath, contentBytes); cerr != nil {
return errorResult(fileConflictMessage(relativePath))
}
content := string(contentBytes)
occurrences := strings.Count(content, oldString)
if occurrences == 0 {
return errorResult("Error: Could not find the exact string to replace in " + relativePath + ". The old_string must match the file byte-for-byte.")
}
if !replaceAll && occurrences > 1 {
return errorResult(fmt.Sprintf("Error: old_string matches %d locations in %s. Either make old_string more specific, or pass replace_all: true to replace every occurrence.", occurrences, relativePath))
}
updated := strings.Replace(content, oldString, newString, 1)
replacedCount := 1
if replaceAll {
updated = strings.ReplaceAll(content, oldString, newString)
replacedCount = occurrences
}
if updated == content {
return okResult("No changes: new_string is identical to old_string.")
}
if err := recheckScopedWriteTarget(tool.workspaceRoot, tool.scope, requestedPath); err != nil {
return errorResult("Error writing " + relativePath + ": " + err.Error())
}
if err := os.WriteFile(absolutePath, []byte(updated), 0o644); err != nil {
return errorResult("Error writing " + relativePath + ": " + err.Error())
}
// Re-baseline to the content we just wrote so subsequent edits in this session
// compare against the current on-disk state, not the pre-edit version.
newInfo, _ := os.Stat(absolutePath)
options.FileTracker.Record(absolutePath, []byte(updated), newInfo)
suffix := ""
if replacedCount != 1 {
suffix = "s"
}
summary := fmt.Sprintf("Successfully edited %s (replaced %d occurrence%s).", relativePath, replacedCount, suffix)
result := okResult(summary)
result.ChangedFiles = []string{relativePath}
result.Display = Display{Summary: fmt.Sprintf("Edited %s", relativePath), Kind: "diff"}
return result
}