mirror of
https://github.com/Twigpine/zero.git
synced 2026-11-11 18:00:54 -10:00
* Improve harness context efficiency
* Address harness efficiency review findings
* Make recaps idle and cancellable
Delay recap generation until the session has been inactive, orient it around the active goal and next task, cancel stale work on activity, and render the result ephemerally above the composer.
Also strengthen the formatter safety regression to exercise formatter-modified edit output.
* Track every replace-all edit span
Translate each replacement into its post-edit line range, including cumulative shifts from earlier replacements, so follow-up edits remain authorized for every model-supplied change.
* Make review regressions cross-platform
Verify replace-all tracking through the canonical edit tool path instead of a platform-sensitive temp path, and cover cancellation when recaps are disabled during generation.
* fix(tools): derive SeenWhole from the recorded ranges
SeenWhole was a flag set only by a SINGLE read covering the file, while
SeenRange judged coverage from the accumulated ranges. The two then
disagreed about identical reads: after reading lines 1-50 and 51-100 of a
100-line file, SeenRange(1,100) was true and SeenWhole was false.
That matters because write_file gates overwrites on SeenWhole. A file past
the read byte budget cannot be read whole in one call — the read is
truncated and RecordSeenRange is correctly skipped, since the model did not
see those lines — so no sequence of reads could ever set the flag, and the
overwrite was refused permanently with:
the intended change depends on content that has not been read exactly
in this session. Read the affected lines with read_file, then retry.
Advice that could not change the answer. edit_file was unaffected because it
gates on SeenRange, so the escape was to edit rather than rewrite, but a
model following the error text would loop.
SeenWhole is now computed from the ranges against the file's recorded line
count, so scoped reads that together cover a file make it writable and the
error text becomes actionable. The observation carries that line count, and
a read reporting a different one clears the accumulated ranges: they
describe a shape the file no longer has.
Coverage is judged by merging sorted ranges rather than walking every line
against every range, which the previous SeenRange did — same answer, and it
no longer scans line-by-line over a large file.
Co-Authored-By: Claude Opus 5 <[email protected]>
* test(tools): key the large-file test on the resolved path
read_file resolves the workspace root through EvalSymlinks before recording
anything, so the tracker is keyed on the resolved path. The test asserted
against the raw t.TempDir() path, which is the same string on Windows and a
different one on macOS, where the temp dir sits under /var — a symlink to
/private/var. The SeenWhole assertions would have looked up a key that never
existed: passing here, failing on macOS CI.
Also switches the line generator to fmt.Fprintf (staticcheck QF1012).
Both from CodeRabbit on #842.
Co-Authored-By: Claude Opus 5 <[email protected]>
* test(tools): actually switch the line generator to fmt.Fprintf
The previous commit's message claimed this was done. It was not: the edit
silently did not apply and I reported it fixed without re-reading the file,
so builder.WriteString(fmt.Sprintf(...)) survived at the head — caught by
@anandh8x, not by me.
Verified this time by running the linter rather than by reading the diff:
golangci-lint --enable-only unused,ineffassign,staticcheck ./internal/tools/
reports 0 issues.
* fix: keep exact-read workflows recoverable
* test: cover permission normalization wiring
* fix: commit file observations after output budgeting
* fix: defer file observations across retries
* test: normalize patch line endings
---------
Co-authored-by: Vasanthdev2004 <[email protected]>
Co-authored-by: Claude Opus 5 <[email protected]>
159 lines
6.4 KiB
Go
159 lines
6.4 KiB
Go
package tools
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
)
|
|
|
|
type writeFileTool struct {
|
|
baseTool
|
|
workspaceRoot string
|
|
scope PathScope
|
|
}
|
|
|
|
func NewScopedWriteFileTool(workspaceRoot string, scope PathScope) Tool {
|
|
return writeFileTool{
|
|
baseTool: baseTool{
|
|
name: "write_file",
|
|
description: "Create a new file, refusing to overwrite existing files unless overwrite is true.",
|
|
parameters: Schema{
|
|
Type: "object",
|
|
Properties: map[string]PropertySchema{
|
|
"path": {Type: "string", Description: "Absolute or relative path of the file to write."},
|
|
"content": {Type: "string", Description: "Full file contents to write."},
|
|
"overwrite": {Type: "boolean", Description: "Whether to allow overwriting an existing file.", Default: false},
|
|
},
|
|
Required: []string{"path", "content"},
|
|
AdditionalProperties: false,
|
|
},
|
|
safety: promptSafety(SideEffectWrite, "Creates or overwrites files."),
|
|
capabilities: ToolCapabilities{Effect: EffectWorkspaceWrite, ThreadSafe: false, ResourceKeys: fileResourceKeys},
|
|
},
|
|
workspaceRoot: normalizeWorkspaceRoot(workspaceRoot),
|
|
scope: scope,
|
|
}
|
|
}
|
|
|
|
func (tool writeFileTool) Run(ctx context.Context, args map[string]any) Result {
|
|
return tool.RunWithOptions(ctx, args, RunOptions{})
|
|
}
|
|
|
|
func (tool writeFileTool) RunWithOptions(ctx 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 write_file: " + err.Error())
|
|
}
|
|
content, err := fileContentArg(args)
|
|
if err != nil {
|
|
return errorResult("Error: Invalid arguments for write_file: " + err.Error())
|
|
}
|
|
overwrite, err := boolArg(args, "overwrite", false)
|
|
if err != nil {
|
|
return errorResult("Error: Invalid arguments for write_file: " + err.Error())
|
|
}
|
|
|
|
absolutePath, relativePath, err := resolveScopedTargetPath(tool.workspaceRoot, tool.scope, requestedPath)
|
|
if err != nil {
|
|
return errorResult("Error writing file " + requestedPath + ": " + err.Error())
|
|
}
|
|
|
|
existed := false
|
|
if _, err := os.Stat(absolutePath); err == nil {
|
|
existed = true
|
|
if !overwrite {
|
|
return errorResult("Error: " + relativePath + " already exists. Pass overwrite: true to replace it.")
|
|
}
|
|
} else if !os.IsNotExist(err) {
|
|
return errorResult("Error writing file " + relativePath + ": " + err.Error())
|
|
}
|
|
|
|
// On overwrite, refuse to clobber a tracked file that changed on disk outside
|
|
// Zero since it was last read — the new content was likely composed against a
|
|
// stale view. Only read current bytes when there is a baseline to compare,
|
|
// so a first-touch create/overwrite stays a single write with no extra read.
|
|
if existed {
|
|
if options.FileTracker != nil && !options.FileTracker.SeenWhole(absolutePath) {
|
|
return errorResult(fileUnseenMessage(relativePath))
|
|
}
|
|
if _, tracked := options.FileTracker.Version(absolutePath); tracked {
|
|
// Fail CLOSED: if the tracked file can't be re-read to verify it, refuse
|
|
// the overwrite rather than clobbering a file whose current state is
|
|
// unknown (it may have been replaced or removed out from under us).
|
|
current, rerr := os.ReadFile(absolutePath)
|
|
if rerr != nil {
|
|
return errorResult(fileConflictMessage(relativePath))
|
|
}
|
|
if cerr := options.FileTracker.CheckConflict(absolutePath, current); cerr != nil {
|
|
return errorResult(fileConflictMessage(relativePath))
|
|
}
|
|
}
|
|
}
|
|
|
|
// Capture the prior content (before we replace it) so an overwrite can show a
|
|
// real diff; a fresh create stays "" and previews as all-additions.
|
|
priorContent := ""
|
|
if existed {
|
|
if prev, rerr := os.ReadFile(absolutePath); rerr == nil {
|
|
priorContent = string(prev)
|
|
}
|
|
}
|
|
|
|
if err := os.MkdirAll(filepath.Dir(absolutePath), 0o755); err != nil {
|
|
return errorResult("Error writing file " + relativePath + ": " + err.Error())
|
|
}
|
|
if err := recheckScopedWriteTarget(tool.workspaceRoot, tool.scope, requestedPath); err != nil {
|
|
return errorResult("Error writing file " + relativePath + ": " + err.Error())
|
|
}
|
|
if err := os.WriteFile(absolutePath, []byte(content), 0o644); err != nil {
|
|
return errorResult("Error writing file " + relativePath + ": " + err.Error())
|
|
}
|
|
modelKnownContent := content
|
|
// Optional format-on-write (ZERO_FORMAT_ON_WRITE). Must run BEFORE the
|
|
// FileTracker baseline: recording pre-format content would make the very
|
|
// next edit look like an external modification and trip the conflict guard.
|
|
content = maybeFormatWrittenFile(ctx, absolutePath, content)
|
|
// Baseline the freshly written content so a later edit/overwrite in this
|
|
// session compares against what is now on disk.
|
|
newInfo, _ := os.Stat(absolutePath)
|
|
options.FileTracker.Record(absolutePath, []byte(content), newInfo)
|
|
if content == modelKnownContent {
|
|
options.FileTracker.RecordSeenRange(absolutePath, 1, lineCount(content), lineCount(content))
|
|
}
|
|
if !existed {
|
|
options.FileTracker.RecordCreated(absolutePath)
|
|
}
|
|
|
|
verb := "Created"
|
|
if existed {
|
|
verb = "Overwrote"
|
|
}
|
|
// Report line count (not bytes): "Wrote 282 lines" reads as real work at a
|
|
// glance, where a byte total is opaque noise.
|
|
lines := strings.Count(content, "\n")
|
|
if content != "" && !strings.HasSuffix(content, "\n") {
|
|
lines++
|
|
}
|
|
summary := fmt.Sprintf("%s %s (%d lines).", verb, relativePath, lines)
|
|
summary += inlineDiagnostics(ctx, options, absolutePath, relativePath)
|
|
result := okResult(summary)
|
|
result.ChangedFiles = []string{relativePath}
|
|
// Card-only preview: a real unified diff (all-green for a create, red/green for
|
|
// an overwrite) on Display.Preview. Output stays the summary, so the model never
|
|
// re-reads the file — the rich preview costs zero model tokens.
|
|
result.Display = Display{Summary: summary, Kind: "file", Preview: boundedUnifiedDiff(relativePath, priorContent, content)}
|
|
return result
|
|
}
|
|
|
|
// fileContentArg reads the file body from "content" or a common alias that weaker
|
|
// models sometimes use instead (contents/text/body/data/file_content). It
|
|
// delegates to the shared aliasedStringArg so the present-but-non-string type
|
|
// error ("content must be a string") and the required-but-missing error
|
|
// ("content is required") stay consistent with every other tool. An empty string
|
|
// is allowed (writing an empty file), so allowEmpty is true.
|
|
func fileContentArg(args map[string]any) (string, error) {
|
|
return aliasedStringArg(args, []string{"content", "contents", "text", "body", "data", "file_content"}, "", true, true)
|
|
}
|