Open History to see the last commit
1import type { SandboxFileEvent, SandboxFileHookEvent } from '@tanstack/ai'
2import type { InternalLogger } from '@tanstack/ai/adapter-internals'
3import type { SandboxHandle } from './contracts'
4
5/** Path relative to the repo/workspace root, POSIX form. */
6function relTo(root: string, path: string): string {
7 const prefix = root.endsWith('/') ? root : `${root}/`
8 return path.startsWith(prefix) ? path.slice(prefix.length) : path
9}
10
11/**
12 * POSIX single-quote escape for embedding a value in a shell command.
13 */
14function q(value: string): string {
15 return `'${value.replace(/'/g, `'\\''`)}'`
16}
17
18/**
19 * Unified add-patch for a brand-new file, closely following the shape `git
20 * diff` produces for an added file (`diff --git` header + `new file mode` +
21 * `--- /dev/null` + `+++ b/<rel>`), so synthesized `create` diffs align with
22 * the real `git diff` output emitted for `change` events. `rel` must be the
23 * repo-root-relative POSIX path (like git's). Reproduces git's `\ No newline
24 * at end of file` marker and the header-only form for a zero-byte file, so a
25 * consumer applying the patch reconstructs the file byte-for-byte. It is not
26 * byte-identical to git — it omits the `index <hash>..<hash>` line and always
27 * writes the `+1,N` hunk count (git omits `,1`) — but both are valid
28 * unified-diff and accepted by `git apply`/`patch`.
29 */
30function synthesizeAddPatch(rel: string, content: string): string {
31 const header = `diff --git a/${rel} b/${rel}\nnew file mode 100644\n`
32 // A zero-byte new file has no hunk in git's output — just the header.
33 if (content === '') return header
34 const hasFinalNewline = content.endsWith('\n')
35 const lines = content.replace(/\n$/, '').split('\n')
36 const body = lines.map((l) => `+${l}`).join('\n')
37 return (
38 header +
39 `--- /dev/null\n` +
40 `+++ b/${rel}\n` +
41 `@@ -0,0 +1,${lines.length} @@\n` +
42 body +
43 (hasFinalNewline ? '\n' : '\n\\ No newline at end of file\n')
44 )
45}
46
47/**
48 * Wrap a raw {@link SandboxFileEvent} with lazy git-backed accessors bound to
49 * the live handle. `baseSha` is the session baseline (`''` when the workspace
50 * isn't a git repo). Never throws — every git/fs failure falls back to `''`
51 * (or a synthesized add-patch), but is logged first via `logger` so a failure
52 * is observable instead of silently becoming empty data.
53 */
54export function buildFileHookEvent(
55 handle: SandboxHandle,
56 root: string,
57 baseSha: string,
58 event: SandboxFileEvent,
59 logger?: InternalLogger,
60): SandboxFileHookEvent {
61 const after = async (): Promise<string> => {
62 if (event.type === 'delete') return ''
63 try {
64 return await handle.fs.read(event.path)
65 } catch (error) {
66 logger?.warn('sandbox after() failed to read file', {
67 path: event.path,
68 error,
69 })
70 return ''
71 }
72 }
73 const before = async (): Promise<string> => {
74 if (baseSha === '') return ''
75 const rel = relTo(root, event.path)
76 try {
77 const res = await handle.process.exec(
78 `git show ${q(baseSha)}:${q(rel)}`,
79 { cwd: root },
80 )
81 if (res.exitCode === 0) return res.stdout
82 // Non-zero exit is EXPECTED when the file didn't exist at the baseline
83 // (a newly created file) — git exits 128 with "exists on disk, but not
84 // in <sha>". Log under `sandbox` (off by default) rather than warn so a
85 // create event's before() doesn't spam a warning on every new file.
86 logger?.sandbox('before() git show non-zero exit', {
87 path: event.path,
88 exitCode: res.exitCode,
89 stderr: res.stderr,
90 })
91 return ''
92 } catch (error) {
93 logger?.warn('sandbox before() git show failed', {
94 path: event.path,
95 error,
96 })
97 return ''
98 }
99 }
100 // Empty `git diff` fallback: `git diff <sha> -- <path>` shows nothing for a
101 // file git isn't tracking, so an untracked file (the common agent action —
102 // and every subsequent edit to it, which arrives as a `change`, not just the
103 // first `create`) yields empty stdout even though it has content. Synthesize
104 // an add-patch, but ONLY when the file is genuinely untracked at the
105 // baseline — an empty diff for a *tracked* file means "identical to
106 // baseline", a real no-op that must stay empty. Presence at `baseSha`
107 // distinguishes them, probed below via the `git show` EXIT CODE (NOT
108 // `before()`'s `''`, which also means "git show threw" — see the inline note).
109 // ponytail: reached only when `git diff` came back empty — the common case
110 // for an untracked file (and every edit to it), rare for a tracked one. It
111 // spends up to two extra subprocesses (`git check-ignore`, then `git show`)
112 // plus one `after()` read per such event; both verdicts are invariant per
113 // path across a run, but memoizing them would need cross-event state the
114 // per-event accessor doesn't hold. Add a per-path cache in the watcher if
115 // edit-burst latency matters.
116 const synthesizeIfUntracked = async (rel: string): Promise<string> => {
117 const content = await after()
118 if (content === '') return '' // deleted / empty / unreadable — nothing to add
119 // Don't expose the CONTENTS of a git-ignored file (`.env`, credentials,
120 // build artifacts, …) in the diff feed. The file event still fires so
121 // consumers are notified it changed — only its diff is withheld. A
122 // force-added, ignored-yet-TRACKED file produces a non-empty `git diff`
123 // above and never reaches here, so its real diff is unaffected.
124 try {
125 const ignored = await handle.process.exec(
126 `git check-ignore -q -- ${q(rel)}`,
127 { cwd: root },
128 )
129 // check-ignore: exit 0 ⇒ path is ignored; 1 ⇒ not ignored; 128 ⇒ error.
130 if (ignored.exitCode === 0) {
131 logger?.sandbox('sandbox diff() withheld for git-ignored file', {
132 path: event.path,
133 })
134 return ''
135 }
136 if (ignored.exitCode !== 1) {
137 // Not the expected "not ignored" (1) — a real check-ignore error (128:
138 // corrupt repo, bad invocation). Same anomaly class as the throw below,
139 // so `warn`. We still fall through and diff, so a broken probe never
140 // silently withholds; but log it, or an error here would look exactly
141 // like "not ignored" and could expose a would-be-withheld file's diff.
142 logger?.warn('sandbox diff() git check-ignore non-zero exit', {
143 path: event.path,
144 exitCode: ignored.exitCode,
145 stderr: ignored.stderr,
146 })
147 }
148 } catch (error) {
149 // check-ignore threw (git/exec broken) — same anomaly class as the other
150 // git execs here, so `warn`. We fall through and diff as usual rather
151 // than withhold, so a broken probe can't hide a legitimate diff.
152 logger?.warn('sandbox diff() git check-ignore failed', {
153 path: event.path,
154 error,
155 })
156 }
157 // Distinguish "absent at the baseline (untracked)" from "present at the
158 // baseline" by the git-show EXIT CODE, not by before()'s `''` — which also
159 // means "git show threw". Conflating a transient git-show failure with
160 // untracked would fabricate a full-file add-patch for an unchanged tracked
161 // file the agent never touched.
162 try {
163 const res = await handle.process.exec(
164 `git show ${q(baseSha)}:${q(rel)}`,
165 { cwd: root },
166 )
167 // exit 0 ⇒ tracked; `git diff` was already empty ⇒ identical to baseline
168 // ⇒ genuine no-op.
169 if (res.exitCode === 0) return ''
170 // Non-zero is the EXPECTED "absent at baseline ⇒ untracked" case (exit
171 // 128), but a genuine git-show error (bad object, corrupt repo, invalid
172 // sha) also exits non-zero and would silently fabricate a full-file
173 // add-patch. Log it under `sandbox` (like `before()` does) so a
174 // persistent probe error is greppable, then fall back to synthesize.
175 logger?.sandbox(
176 'sandbox diff() tracked-ness probe non-zero exit (treating as untracked)',
177 { path: event.path, exitCode: res.exitCode, stderr: res.stderr },
178 )
179 return synthesizeAddPatch(rel, content)
180 } catch (error) {
181 // Uncertain — don't fabricate a full-file add-patch on a probe failure.
182 logger?.warn('sandbox diff() tracked-ness probe failed', {
183 path: event.path,
184 error,
185 })
186 return ''
187 }
188 }
189 const diff = async (): Promise<string> => {
190 if (baseSha === '') {
191 if (event.type === 'delete') return ''
192 return synthesizeAddPatch(relTo(root, event.path), await after())
193 }
194 // Pathspec must be relative to `root` (like `before()` above) — a bare
195 // leading `/` (e.g. the virtual `/workspace/x.ts`) is resolved by git
196 // against the filesystem root, not the repo root, and fails with
197 // "fatal: Invalid path" whenever the real repo root differs from
198 // `/workspace` (e.g. every local-process sandbox).
199 const rel = relTo(root, event.path)
200 try {
201 const res = await handle.process.exec(
202 `git diff ${q(baseSha)} -- ${q(rel)}`,
203 {
204 cwd: root,
205 },
206 )
207 if (res.exitCode !== 0) {
208 logger?.warn('sandbox diff() git diff non-zero exit', {
209 path: event.path,
210 exitCode: res.exitCode,
211 stderr: res.stderr,
212 })
213 return ''
214 }
215 if (res.stdout !== '') return res.stdout
216 return synthesizeIfUntracked(rel)
217 } catch (error) {
218 logger?.warn('sandbox diff() git diff failed', {
219 path: event.path,
220 error,
221 })
222 return ''
223 }
224 }
225 return { ...event, before, after, diff }
226}
227
228export interface ResolvedFileEvents {
229 enabled: boolean
230 diff: boolean
231}
232
233/** Normalize the `fileEvents` option (`boolean | { diff?: boolean }`). */
234export function resolveFileEvents(
235 opt: boolean | { diff?: boolean } | undefined,
236): ResolvedFileEvents {
237 if (opt === false) return { enabled: false, diff: false }
238 if (opt === undefined || opt === true) return { enabled: true, diff: false }
239 return { enabled: true, diff: opt.diff === true }
240}