mirror of
https://github.com/Twigpine/zero.git
synced 2026-11-10 05:01:28 -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]>
168 lines
7.0 KiB
Go
168 lines
7.0 KiB
Go
package tools
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"github.com/Gitlawb/zero/internal/lsp"
|
|
)
|
|
|
|
// lspNavigateTool exposes LSP code navigation (jump-to-definition, find-all-
|
|
// references, find-implementations, workspace symbol search) as a read-only,
|
|
// model-callable tool. It answers "where is X defined / who calls X / what
|
|
// implements this interface" semantically, where grep collides on names or
|
|
// misses indirect references. Degrades to a clear "unavailable" message when no
|
|
// language server is installed for the file's type — LSP is opportunistic.
|
|
type lspNavigateTool struct {
|
|
baseTool
|
|
workspaceRoot string
|
|
scope PathScope
|
|
manager *lsp.Manager
|
|
}
|
|
|
|
// NewScopedLSPNavigateTool builds the tool with its own lazily-started LSP
|
|
// manager (servers spin up on first use and are reused across calls within a
|
|
// session). The model-supplied path is resolved through the same scoped
|
|
// confinement the sibling read-only tools use, so a `..` or absolute path
|
|
// cannot read or open a file outside the workspace (or an extra granted root).
|
|
func NewScopedLSPNavigateTool(workspaceRoot string, scope PathScope) Tool {
|
|
root := normalizeWorkspaceRoot(workspaceRoot)
|
|
return lspNavigateTool{
|
|
baseTool: baseTool{
|
|
name: "lsp_navigate",
|
|
deferred: true,
|
|
description: "Navigate code semantically via the language server: jump to a symbol's " +
|
|
"definition, find all references, find implementations of an interface/method, or " +
|
|
"search workspace symbols by name. Use this instead of grep when you need precise " +
|
|
"definition/reference/implementation results. Returns file:line:col locations.",
|
|
parameters: Schema{
|
|
Type: "object",
|
|
Properties: map[string]PropertySchema{
|
|
"op": {
|
|
Type: "string",
|
|
Description: "Operation: definition, references, implementation, or workspace_symbol.",
|
|
Enum: []string{"definition", "references", "implementation", "workspace_symbol"},
|
|
},
|
|
"path": {Type: "string", Description: "File to anchor the query (required for all ops; for workspace_symbol it selects the language server)."},
|
|
"line": {Type: "integer", Description: "1-based line of the symbol (definition/references/implementation).", Minimum: intPtr(1)},
|
|
"character": {Type: "integer", Description: "1-based column of the symbol (definition/references/implementation).", Minimum: intPtr(1)},
|
|
"query": {Type: "string", Description: "Symbol name to search for (workspace_symbol)."},
|
|
},
|
|
Required: []string{"op", "path"},
|
|
AdditionalProperties: false,
|
|
},
|
|
safety: readOnlySafety("Queries the language server for code navigation; reads files, modifies nothing."),
|
|
capabilities: ToolCapabilities{Effect: EffectReadOnly, ThreadSafe: false, ResourceKeys: fileResourceKeys},
|
|
},
|
|
workspaceRoot: root,
|
|
scope: scope,
|
|
manager: lsp.NewManager(root),
|
|
}
|
|
}
|
|
|
|
func (tool lspNavigateTool) Run(ctx context.Context, args map[string]any) Result {
|
|
opRaw, err := stringArg(args, "op", "", true)
|
|
if err != nil {
|
|
return errorResult("Error: Invalid arguments for lsp_navigate: " + err.Error())
|
|
}
|
|
op := lsp.NavOp(strings.ToLower(strings.TrimSpace(opRaw)))
|
|
|
|
requestedPath, err := aliasedStringArg(args, []string{"path", "file", "file_path"}, "", true, false)
|
|
if err != nil {
|
|
return errorResult("Error: Invalid arguments for lsp_navigate: " + err.Error())
|
|
}
|
|
|
|
// Confine the model-supplied path to the workspace (or an extra granted root)
|
|
// BEFORE reading it or handing it to the language server — a `..` or absolute
|
|
// path must not read/open a file outside the boundary the sibling read-only
|
|
// tools enforce. Errors echo only the relative path, never an absolute one.
|
|
absPath, relPath, scopeErr := resolveScopedReadPath(tool.workspaceRoot, tool.scope, requestedPath)
|
|
if scopeErr != nil {
|
|
return errorResult("Error: lsp_navigate " + scopeErr.Error())
|
|
}
|
|
|
|
text, readErr := readWorkspaceFile(absPath)
|
|
if readErr != nil && op != lsp.NavWorkspaceSymbol {
|
|
return errorResult("Error: lsp_navigate could not read " + relPath + ": " + readErr.Error())
|
|
}
|
|
|
|
// Hand the LSP manager the resolved absolute path so it opens only the
|
|
// confined file (not the raw, possibly-escaping, model input).
|
|
req := lsp.NavRequest{Op: op, Path: absPath, Text: text}
|
|
switch op {
|
|
case lsp.NavWorkspaceSymbol:
|
|
query, qErr := stringArg(args, "query", "", true)
|
|
if qErr != nil {
|
|
return errorResult("Error: lsp_navigate workspace_symbol requires a query.")
|
|
}
|
|
req.Query = strings.TrimSpace(query)
|
|
case lsp.NavDefinition, lsp.NavReferences, lsp.NavImplementation:
|
|
line, lErr := intArg(args, "line", 0, 1, 0)
|
|
col, cErr := intArg(args, "character", 1, 1, 0)
|
|
if lErr != nil || cErr != nil || line == 0 {
|
|
return errorResult("Error: lsp_navigate " + string(op) + " requires 1-based line and character.")
|
|
}
|
|
req.Line = line
|
|
req.Character = col
|
|
req.IncludeDeclaration = true
|
|
default:
|
|
return errorResult("Error: lsp_navigate unknown op " + string(op) + " (use definition, references, implementation, or workspace_symbol).")
|
|
}
|
|
|
|
locations, symbols, ok, navErr := tool.manager.Navigate(ctx, req)
|
|
if navErr != nil {
|
|
return errorResult("Error: lsp_navigate failed: " + navErr.Error())
|
|
}
|
|
if !ok {
|
|
return okResult(fmt.Sprintf("No language server available for %s — lsp_navigate is unavailable for this file type. Fall back to grep/read_file.", filepath.Base(relPath)))
|
|
}
|
|
|
|
return okResult(tool.formatResult(op, locations, symbols))
|
|
}
|
|
|
|
// readWorkspaceFile reads an already-confined absolute path (resolved by
|
|
// resolveScopedReadPath). Returns "" + error when the file can't be read.
|
|
func readWorkspaceFile(absPath string) (string, error) {
|
|
data, err := os.ReadFile(absPath)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return string(data), nil
|
|
}
|
|
|
|
func (tool lspNavigateTool) formatResult(op lsp.NavOp, locations []lsp.Location, symbols []lsp.SymbolResult) string {
|
|
if op == lsp.NavWorkspaceSymbol {
|
|
if len(symbols) == 0 {
|
|
return "No matching symbols."
|
|
}
|
|
lines := make([]string, 0, len(symbols)+1)
|
|
lines = append(lines, fmt.Sprintf("%d symbol(s):", len(symbols)))
|
|
for _, s := range symbols {
|
|
lines = append(lines, fmt.Sprintf(" %s %s — %s", s.Kind, s.Name, tool.formatLocation(s.Location)))
|
|
}
|
|
return strings.Join(lines, "\n")
|
|
}
|
|
if len(locations) == 0 {
|
|
return "No " + string(op) + " results."
|
|
}
|
|
lines := make([]string, 0, len(locations)+1)
|
|
lines = append(lines, fmt.Sprintf("%d %s result(s):", len(locations), op))
|
|
for _, l := range locations {
|
|
lines = append(lines, " "+tool.formatLocation(l))
|
|
}
|
|
return strings.Join(lines, "\n")
|
|
}
|
|
|
|
// formatLocation renders a location as a workspace-relative file:line:col
|
|
// (1-based for the user, converting from LSP's 0-based positions).
|
|
func (tool lspNavigateTool) formatLocation(l lsp.Location) string {
|
|
path := lsp.URIToPath(l.URI)
|
|
if rel, err := filepath.Rel(tool.workspaceRoot, path); err == nil && !strings.HasPrefix(rel, "..") {
|
|
path = filepath.ToSlash(rel)
|
|
}
|
|
return fmt.Sprintf("%s:%d:%d", path, l.Range.Start.Line+1, l.Range.Start.Character+1)
|
|
}
|