xonecas.io
62159
Sy

symb / commit ed28713

feat: only snapshot for undo befor and after a whole turn

xonecas2026-02-15 ed28713085fe23e56354c96a8a53bf806d806518 parent 2f2cde9

10 files changed

cmd/symb/main.go+1−1
@@ -189,7 +189,7 @@ func setupServices(cfg *config.Config, creds *config.Credentials) services {
189189
190190 // Shell tool — in-process POSIX interpreter with command blocking.
191191 sh := shell.New("", shell.DefaultBlockFuncs())
192- shellHandler := mcptools.NewShellHandler(sh, dt)
192+ shellHandler := mcptools.NewShellHandler(sh)
193193 proxy.RegisterTool(mcptools.NewShellTool(), shellHandler.Handle)
194194
195195 return services{
internal/delta/snapshot.go+82−0
@@ -0,0 +1,82 @@
1+package delta
2+
3+import (
4+ "io/fs"
5+ "os"
6+ "path/filepath"
7+ "time"
8+)
9+
10+// FileSnapshot holds mtime+size+content for change detection and undo.
11+type FileSnapshot struct {
12+ ModTime time.Time
13+ Size int64
14+ Content []byte // pre-read for undo; nil for large files
15+}
16+
17+// maxSnapshotFileSize is the max file size we pre-read for undo (1 MB).
18+const maxSnapshotFileSize = 1 << 20
19+
20+// skipDirs are directories skipped during snapshot walks.
21+var skipDirs = map[string]bool{
22+ ".git": true, "node_modules": true, "__pycache__": true,
23+ ".venv": true, "vendor": true, ".cache": true, ".next": true,
24+ "dist": true, "build": true, "target": true,
25+}
26+
27+// SnapshotDir walks root and returns a map of relative path -> FileSnapshot.
28+// Files under maxSnapshotFileSize have their content pre-read for undo.
29+func SnapshotDir(root string) map[string]FileSnapshot {
30+ snap := make(map[string]FileSnapshot)
31+ _ = filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
32+ if err != nil {
33+ return nil
34+ }
35+ if d.IsDir() {
36+ if skipDirs[d.Name()] {
37+ return filepath.SkipDir
38+ }
39+ return nil
40+ }
41+ rel, err := filepath.Rel(root, path)
42+ if err != nil {
43+ return nil
44+ }
45+ info, err := d.Info()
46+ if err != nil {
47+ return nil
48+ }
49+ fs := FileSnapshot{ModTime: info.ModTime(), Size: info.Size()}
50+ if info.Size() <= maxSnapshotFileSize {
51+ fs.Content, _ = os.ReadFile(path)
52+ }
53+ snap[rel] = fs
54+ return nil
55+ })
56+ return snap
57+}
58+
59+// RecordDeltas compares pre/post snapshots and records deltas for undo.
60+func RecordDeltas(dt *Tracker, root string, pre, post map[string]FileSnapshot) {
61+ // New or modified files.
62+ for rel, postInfo := range post {
63+ absPath := filepath.Join(root, rel)
64+ preInfo, existed := pre[rel]
65+ if !existed {
66+ dt.RecordCreate(absPath)
67+ continue
68+ }
69+ if preInfo.ModTime != postInfo.ModTime || preInfo.Size != postInfo.Size {
70+ dt.RecordModify(absPath, preInfo.Content)
71+ }
72+ }
73+ // Deleted files — existed in pre but not in post.
74+ for rel, preInfo := range pre {
75+ if _, exists := post[rel]; !exists {
76+ absPath := filepath.Join(root, rel)
77+ if preInfo.Content != nil {
78+ dt.RecordModify(absPath, preInfo.Content)
79+ }
80+ }
81+ }
82+}
internal/llm/anthropic.md+2−1
@@ -72,7 +72,8 @@ Search the web for documentation, APIs, libraries, or current information. Resul
7272 **Search before assuming** — when asked about external libraries, APIs, or current information, use WebSearch to verify rather than relying on potentially outdated knowledge.
7373
7474 ### `Shell` — Execute shell commands
75-Run commands in an in-process POSIX shell. State (cwd, env) persists across calls.
75+Run commands in an in-process POSIX shell. State (env) persists across calls.
76+The shell is anchored to the project root — you cannot cd outside it.
7677 Dangerous commands (network, sudo, package managers) are blocked.
7778
7879 - `{"command": "go build ./...", "description": "Build the project"}`
internal/llm/gemini.md+2−1
@@ -89,7 +89,8 @@ Search the web for documentation, APIs, libraries, or current information. Resul
8989 **Search before assuming** — when asked about external libraries, APIs, or current information, use WebSearch to verify rather than relying on potentially outdated knowledge.
9090
9191 ### `Shell` — Execute shell commands
92-Run commands in an in-process POSIX shell. State (cwd, env) persists across calls.
92+Run commands in an in-process POSIX shell. State (env) persists across calls.
93+The shell is anchored to the project root — you cannot cd outside it.
9394 Dangerous commands (network, sudo, package managers) are blocked.
9495
9596 ```json
internal/llm/gpt.md+2−1
@@ -89,7 +89,8 @@ Search the web for documentation, APIs, libraries, or current information. Resul
8989 **Search before assuming** — when asked about external libraries, APIs, or current information, use WebSearch to verify rather than relying on potentially outdated knowledge.
9090
9191 ### `Shell` — Execute shell commands
92-Run commands in an in-process POSIX shell. State (cwd, env) persists across calls.
92+Run commands in an in-process POSIX shell. State (env) persists across calls.
93+The shell is anchored to the project root — you cannot cd outside it.
9394 Dangerous commands (network, sudo, package managers) are blocked.
9495
9596 **Parameters:**
internal/llm/qwen.md+2−1
@@ -68,7 +68,8 @@ Search for docs, APIs, libraries, current info. Cached 24h.
6868 **Search before assuming** — use WebSearch to verify external APIs/libraries rather than guessing.
6969
7070 ### `Shell` — Execute shell commands
71-Run commands in an in-process POSIX shell. State (cwd, env) persists across calls.
71+Run commands in an in-process POSIX shell. State (env) persists across calls.
72+The shell is anchored to the project root — you cannot cd outside it.
7273 Dangerous commands (network, sudo, package managers) are blocked.
7374 ```json
7475 {"command": "go test -v ./...", "description": "Run tests verbosely", "timeout": 120}
internal/mcptools/shell.go+4−108
@@ -5,13 +5,9 @@ import (
55 "context"
66 "encoding/json"
77 "fmt"
8- "io/fs"
9- "os"
10- "path/filepath"
118 "strings"
129 "time"
1310
14- "github.com/xonecas/symb/internal/delta"
1511 "github.com/xonecas/symb/internal/mcp"
1612 "github.com/xonecas/symb/internal/shell"
1713 )
@@ -28,7 +24,7 @@ func NewShellTool() mcp.Tool {
2824 return mcp.Tool{
2925 Name: "Shell",
3026 Description: `Execute a shell command in an in-process POSIX interpreter.
31-Commands run inside the project working directory. Shell state (cwd, env vars) persists across calls within the same session.
27+Commands run inside the project working directory. The shell is anchored to the project root — you cannot cd outside it. Env vars persist across calls.
3228 Dangerous commands (network, sudo, package managers, system modification) are blocked.
3329 Use this for: running builds, tests, linters, git operations, file manipulation, and inspecting project state.`,
3430 InputSchema: json.RawMessage(`{
@@ -45,16 +41,15 @@ Use this for: running builds, tests, linters, git operations, file manipulation,
4541
4642 // ShellHandler handles Shell tool calls.
4743 type ShellHandler struct {
48- sh *shell.Shell
49- deltaTracker *delta.Tracker
44+ sh *shell.Shell
5045 // OnOutput is called with incremental output chunks for real-time streaming.
5146 // May be nil.
5247 OnOutput func(chunk string)
5348 }
5449
5550 // NewShellHandler creates a handler for the Shell tool.
56-func NewShellHandler(sh *shell.Shell, dt *delta.Tracker) *ShellHandler {
57- return &ShellHandler{sh: sh, deltaTracker: dt}
51+func NewShellHandler(sh *shell.Shell) *ShellHandler {
52+ return &ShellHandler{sh: sh}
5853 }
5954
6055 // Handle implements the mcp.ToolHandler interface.
@@ -78,15 +73,6 @@ func (h *ShellHandler) Handle(ctx context.Context, arguments json.RawMessage) (*
7873 ctx, cancel := context.WithTimeout(ctx, time.Duration(timeout)*time.Second)
7974 defer cancel()
8075
81- // Snapshot the shell's working directory for undo — only when the delta
82- // tracker is active (has a turn), to avoid expensive walks on read-only commands.
83- shellCwd := h.sh.Dir()
84- trackDeltas := h.deltaTracker != nil && h.deltaTracker.TurnID() > 0
85- var preSnap map[string]fileSnapshot
86- if trackDeltas {
87- preSnap = snapshotDir(shellCwd)
88- }
89-
9076 // Execute command with streaming output.
9177 var stdout, stderr bytes.Buffer
9278
@@ -98,14 +84,6 @@ func (h *ShellHandler) Handle(ctx context.Context, arguments json.RawMessage) (*
9884 execErr = h.sh.ExecStream(ctx, args.Command, &stdout, &stderr)
9985 }
10086
101- // Post-execution: diff the *original* cwd to record deltas for undo.
102- // Always use shellCwd (the pre-exec directory) for both snapshots so a
103- // `cd` inside the command doesn't cause a cross-directory mismatch.
104- if trackDeltas {
105- postSnap := snapshotDir(shellCwd)
106- recordDeltas(h.deltaTracker, shellCwd, preSnap, postSnap)
107- }
108-
10987 // Format result.
11088 exitCode := shell.ExitCode(execErr)
11189 output := formatShellOutput(stdout.String(), stderr.String(), exitCode, ctx.Err())
@@ -176,85 +154,3 @@ func truncateMiddle(s string, maxChars int) string {
176154 half := maxChars / 2
177155 return string(runes[:half]) + "\n\n... [truncated] ...\n\n" + string(runes[len(runes)-half:])
178156 }
179-
180-// ---------------------------------------------------------------------------
181-// CWD snapshot for undo
182-// ---------------------------------------------------------------------------
183-
184-// fileSnapshot holds mtime+size+content for change detection and undo.
185-type fileSnapshot struct {
186- modTime time.Time
187- size int64
188- content []byte // pre-read for undo; nil for large files
189-}
190-
191-// maxSnapshotFileSize is the max file size we pre-read for undo (1 MB).
192-const maxSnapshotFileSize = 1 << 20
193-
194-// skipDirs are directories skipped during snapshot walks.
195-var skipDirs = map[string]bool{
196- ".git": true, "node_modules": true, "__pycache__": true,
197- ".venv": true, "vendor": true, ".cache": true, ".next": true,
198- "dist": true, "build": true, "target": true,
199-}
200-
201-// snapshotDir walks root and returns a map of relative path -> fileSnapshot.
202-// Files under maxSnapshotFileSize have their content pre-read for undo.
203-func snapshotDir(root string) map[string]fileSnapshot {
204- snap := make(map[string]fileSnapshot)
205- _ = filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
206- if err != nil {
207- return nil
208- }
209- if d.IsDir() {
210- if skipDirs[d.Name()] {
211- return filepath.SkipDir
212- }
213- return nil
214- }
215- rel, err := filepath.Rel(root, path)
216- if err != nil {
217- return nil
218- }
219- info, err := d.Info()
220- if err != nil {
221- return nil
222- }
223- fs := fileSnapshot{modTime: info.ModTime(), size: info.Size()}
224- if info.Size() <= maxSnapshotFileSize {
225- fs.content, _ = os.ReadFile(path)
226- }
227- snap[rel] = fs
228- return nil
229- })
230- return snap
231-}
232-
233-// recordDeltas compares pre/post snapshots and records deltas for undo.
234-func recordDeltas(dt *delta.Tracker, root string, pre, post map[string]fileSnapshot) {
235- // New or modified files.
236- for rel, postInfo := range post {
237- absPath := filepath.Join(root, rel)
238- preInfo, existed := pre[rel]
239- if !existed {
240- dt.RecordCreate(absPath)
241- continue
242- }
243- if preInfo.modTime != postInfo.modTime || preInfo.size != postInfo.size {
244- // File was modified — use pre-read content for undo.
245- dt.RecordModify(absPath, preInfo.content)
246- }
247- }
248- // Deleted files — existed in pre but not in post.
249- for rel, preInfo := range pre {
250- if _, exists := post[rel]; !exists {
251- absPath := filepath.Join(root, rel)
252- if preInfo.content != nil {
253- // We have the original content; record as modify so undo restores it.
254- dt.RecordModify(absPath, preInfo.content)
255- }
256- // If content is nil (file was > maxSnapshotFileSize), we can't
257- // restore it. Skip rather than writing a 0-byte file on undo.
258- }
259- }
260-}
internal/shell/block.go+2−0
@@ -107,6 +107,8 @@ var BannedCommands = []string{
107107 // Network configuration
108108 "firewall-cmd", "ifconfig", "ip", "iptables", "netstat", "pfctl",
109109 "route", "ufw",
110+ // Directory traversal is handled by cwd clamping in updateFromRunner,
111+ // not by command blocking (cd is a shell builtin, invisible to ExecHandlers).
110112 }
111113
112114 // DefaultBlockFuncs returns the standard set of block functions.
internal/shell/shell.go+18−5
@@ -18,17 +18,20 @@ import (
1818 // Shell provides an in-process POSIX shell with persistent cwd/env across calls.
1919 type Shell struct {
2020 mu sync.Mutex
21+ root string // project root — shell is anchored here
2122 cwd string
2223 env []string
2324 blockFuncs []BlockFunc
2425 }
2526
2627 // New creates a Shell rooted at cwd with the given block functions.
28+// The shell is anchored to this directory — cd outside it is clamped back.
2729 func New(cwd string, blockers []BlockFunc) *Shell {
2830 if cwd == "" {
2931 cwd, _ = os.Getwd()
3032 }
3133 return &Shell{
34+ root: cwd,
3235 cwd: cwd,
3336 env: os.Environ(),
3437 blockFuncs: blockers,
@@ -67,7 +70,7 @@ func (s *Shell) execCommon(ctx context.Context, command string, stdout, stderr i
6770 err = fmt.Errorf("command execution panic: %v", r)
6871 }
6972 if runner != nil {
70- s.updateFromRunner(runner)
73+ s.updateFromRunner(runner, stderr)
7174 }
7275 }()
7376
@@ -111,10 +114,15 @@ func (s *Shell) blockHandler() func(next interp.ExecHandlerFunc) interp.ExecHand
111114 }
112115
113116 // updateFromRunner persists cwd and exported env vars after execution.
114-// Uses runner.Env.Each to preserve all inherited vars, not just those
115-// tracked in runner.Vars.
116-func (s *Shell) updateFromRunner(runner *interp.Runner) {
117- s.cwd = runner.Dir
117+// If the runner's cwd escaped the project root, it is clamped back and a
118+// warning is written to stderr so the LLM knows.
119+func (s *Shell) updateFromRunner(runner *interp.Runner, stderr io.Writer) {
120+ dir := runner.Dir
121+ if !isSubdir(dir, s.root) {
122+ fmt.Fprintf(stderr, "[cd rejected: you are anchored to %s]\n", s.root)
123+ dir = s.root
124+ }
125+ s.cwd = dir
118126 s.env = s.env[:0]
119127 runner.Env.Each(func(name string, vr expand.Variable) bool {
120128 if vr.Exported {
@@ -124,6 +132,11 @@ func (s *Shell) updateFromRunner(runner *interp.Runner) {
124132 })
125133 }
126134
135+// isSubdir reports whether dir is equal to or under root.
136+func isSubdir(dir, root string) bool {
137+ return dir == root || strings.HasPrefix(dir, root+string(os.PathSeparator))
138+}
139+
127140 // ExitCode extracts the exit code from an interpreter error.
128141 func ExitCode(err error) int {
129142 if err == nil {
internal/tui/messages.go+21−0
@@ -2,9 +2,11 @@ package tui
22
33 import (
44 "encoding/json"
5+ "os"
56 "time"
67
78 tea "charm.land/bubbletea/v2"
9+ "github.com/xonecas/symb/internal/delta"
810 "github.com/xonecas/symb/internal/llm"
911 "github.com/xonecas/symb/internal/mcp"
1012 "github.com/xonecas/symb/internal/provider"
@@ -94,9 +96,21 @@ func (m Model) processLLM() tea.Cmd {
9496 copy(history, m.history)
9597 ch := m.updateChan
9698 ctx := m.ctx
99+ dt := m.deltaTracker
97100
98101 return func() tea.Msg {
99102 go func() {
103+ // Snapshot the project directory before the turn for undo.
104+ // Capture cwd once so both pre/post snapshots use the same root.
105+ var preSnap map[string]delta.FileSnapshot
106+ var snapRoot string
107+ if dt != nil && dt.TurnID() > 0 {
108+ if cwd, err := os.Getwd(); err == nil {
109+ snapRoot = cwd
110+ preSnap = delta.SnapshotDir(snapRoot)
111+ }
112+ }
113+
100114 start := time.Now()
101115 err := llm.ProcessTurn(ctx, llm.ProcessTurnOptions{
102116 Provider: prov,
@@ -129,6 +143,13 @@ func (m Model) processLLM() tea.Cmd {
129143 }
130144 },
131145 })
146+
147+ // Post-turn snapshot: diff against pre to record deltas for undo.
148+ if preSnap != nil {
149+ postSnap := delta.SnapshotDir(snapRoot)
150+ delta.RecordDeltas(dt, snapRoot, preSnap, postSnap)
151+ }
152+
132153 if err != nil {
133154 ch <- llmErrorMsg{err: err}
134155 return