Repository navigation
Expand file tree
/
Copy pathsnapshots.ts
More file actions
299 lines (258 loc) · 8.34 KB
/
Copy pathsnapshots.ts
File metadata and controls
299 lines (258 loc) · 8.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
// Per-session content snapshots for diff-aware re-read hints. When a file is read, a snapshot is captured. If edited later, a diff is computed.
import * as fs from 'node:fs'
import * as path from 'node:path'
import { fingerprintContent } from './fingerprint.js'
import { ensureDirSync, foldPath, normalizePath, atomicWriteBytes, sanitizeIdForFilename } from './util.js'
import { tokenGoatHome } from './disk_cache.js'
export const MAX_SNAPSHOTS_PER_SESSION = 150
export const MAX_SNAPSHOT_BYTES = 256 * 1024
export const SNAPSHOT_TRUNCATE_BYTES = 50 * 1024
export interface SnapshotResult {
path: string
content_sha: string
size_bytes: number
}
const KIND_READ = 'read'
const KIND_PREDICTIVE = 'predictive'
const VALID_KINDS = new Set([KIND_READ, KIND_PREDICTIVE])
function sessionDir(sessionId: string): string | null {
if (!sessionId) return null
const safe = sanitizeIdForFilename(sessionId, 64, 'anon')
const base = path.join(tokenGoatHome(), 'session_snapshots')
const candidate = path.join(base, safe)
try {
const rel = path.relative(base, candidate)
if (rel.startsWith('..')) return null
} catch {
return null
}
return candidate
}
function pathKey(filePath: string): string {
// Case-insensitive filesystems (Windows, macOS) resolve two differently-cased paths to the same physical file. normalizePath only lowercases the drive letter, so fold the whole string through foldPath (util.ts) -- matching the established convention from session.ts's read-dedup map key -- or a file read under two casings in one session gets two different snapshot files on disk, and load() silently fails to find the prior snapshot under the new casing.
return fingerprintContent(foldPath(normalizePath(filePath))).slice(0, 32)
}
export function snapshot_path(sessionId: string, filePath: string): string | null {
const d = sessionDir(sessionId)
if (!d) return null
return path.join(d, `${pathKey(filePath)}.bin`)
}
function kindSidecarPath(snapshotPath: string): string {
return snapshotPath + '.kind'
}
function readSnapshotKind(sidecarPath: string): string | null {
try {
if (!fs.existsSync(sidecarPath)) return null
const raw = fs.readFileSync(sidecarPath, 'utf8').trim()
return VALID_KINDS.has(raw) ? raw : null
} catch {
return null
}
}
function writeSnapshotKind(sidecarPath: string, kind: string): boolean {
try {
const safeKind = VALID_KINDS.has(kind) ? kind : KIND_READ
const dir = path.dirname(sidecarPath)
if (!fs.existsSync(dir)) {
ensureDirSync(dir)
}
fs.writeFileSync(sidecarPath, safeKind, 'utf8')
return true
} catch {
return false
}
}
function evictOldest(d: string, maxCount: number): number {
try {
const entries: Array<[string, number]> = []
const files = fs.readdirSync(d)
for (const file of files) {
const fullPath = path.join(d, file)
if (!file.endsWith('.bin')) continue
try {
const stat = fs.statSync(fullPath)
entries.push([fullPath, stat.mtimeMs])
} catch {
continue
}
}
if (entries.length <= maxCount) return 0
entries.sort((a, b) => a[1] - b[1])
let removed = 0
const over = entries.length - maxCount
for (const [p] of entries.slice(0, over)) {
try {
fs.unlinkSync(p)
removed++
try {
fs.unlinkSync(kindSidecarPath(p))
} catch {
// ignore sidecar unlink failure
}
} catch {
continue
}
}
return removed
} catch {
return 0
}
}
export function store(
sessionId: string,
filePath: string,
content: Buffer,
opts: { kind?: string } = {},
): SnapshotResult | null {
const kind = opts.kind ?? KIND_READ
const origLen = content.length
if (origLen > MAX_SNAPSHOT_BYTES) {
return null
}
let stored = content
if (origLen > SNAPSHOT_TRUNCATE_BYTES) {
const marker = Buffer.from(`\n<snapshot truncated at ${origLen} bytes>\n`)
stored = Buffer.concat([content.slice(0, SNAPSHOT_TRUNCATE_BYTES), marker])
}
const p = snapshot_path(sessionId, filePath)
if (!p) return null
const sha = fingerprintContent(stored)
try {
const isNewEntry = !fs.existsSync(p)
if (!isNewEntry) {
try {
const existing = fs.readFileSync(p)
if (Buffer.from(existing).equals(stored)) {
const sidecar = kindSidecarPath(p)
if (readSnapshotKind(sidecar) !== kind) writeSnapshotKind(sidecar, kind)
return {
path: p,
content_sha: sha,
size_bytes: stored.length,
}
}
} catch {
// continue with write
}
}
const dir = path.dirname(p)
if (!fs.existsSync(dir)) {
ensureDirSync(dir)
}
if (isNewEntry) {
evictOldest(dir, MAX_SNAPSHOTS_PER_SESSION - 1)
}
// Write atomically via shared helper: uses pid + hrtime for unique temp names (avoiding collisions between concurrent writers) and wraps rename in withRetryOnLock for Windows file-lock resilience.
atomicWriteBytes(p, stored)
const sidecar = kindSidecarPath(p)
writeSnapshotKind(sidecar, kind)
return {
path: p,
content_sha: sha,
size_bytes: stored.length,
}
} catch {
return null
}
}
export function load_kind(sessionId: string, filePath: string): string | null {
const p = snapshot_path(sessionId, filePath)
if (!p) return null
const sidecar = kindSidecarPath(p)
return readSnapshotKind(sidecar)
}
export function load(sessionId: string, filePath: string, opts: { expected_sha?: string } = {}): Buffer | null {
const p = snapshot_path(sessionId, filePath)
if (!p || !fs.existsSync(p)) return null
try {
const stat = fs.statSync(p)
if (stat.size > MAX_SNAPSHOT_BYTES) {
return null
}
} catch {
return null
}
try {
const data = fs.readFileSync(p)
if (opts.expected_sha) {
const actualSha = fingerprintContent(data)
if (actualSha.toLowerCase() !== opts.expected_sha.toLowerCase()) {
return null
}
}
return data
} catch {
return null
}
}
/** Removes `fullPath` if it's eligible: not a symlink (belt-and-suspenders -- see sessionDir's traversal-guard rationale), and (when `cutoff` is given, as cleanup_stale does) older than it. Returns true when the file was removed and counted as a snapshot (its name ends in `.bin`), matching both callers' existing removed-count semantics. Shared by cleanup_session and cleanup_stale, which previously duplicated this exact lstat/skip-symlink/unlink/count sequence. */
function removeEligibleSnapshotFile(fullPath: string, file: string, cutoff?: number): boolean {
const stat = fs.lstatSync(fullPath)
if ((stat.mode & 0o170000) === 0o120000) return false
if (cutoff !== undefined && stat.mtimeMs >= cutoff) return false
fs.unlinkSync(fullPath)
return file.endsWith('.bin')
}
export function cleanup_session(sessionId: string): number {
const d = sessionDir(sessionId)
if (!d || !fs.existsSync(d)) return 0
let removed = 0
try {
const files = fs.readdirSync(d)
for (const file of files) {
const fullPath = path.join(d, file)
try {
if (removeEligibleSnapshotFile(fullPath, file)) removed++
} catch {
continue
}
}
try {
fs.rmdirSync(d)
} catch {
// ignore: directory not empty is fine
}
} catch {
return removed
}
return removed
}
export function cleanup_stale(maxAgeHours: number = 24.0): number {
const base = path.join(tokenGoatHome(), 'session_snapshots')
if (!fs.existsSync(base)) return 0
const cutoff = Date.now() - maxAgeHours * 3600 * 1000
let removed = 0
try {
const sessionDirs = fs.readdirSync(base)
for (const sessionDir of sessionDirs) {
const sessionPath = path.join(base, sessionDir)
try {
const stat = fs.statSync(sessionPath)
if (!stat.isDirectory()) continue
} catch {
continue
}
try {
const files = fs.readdirSync(sessionPath)
for (const file of files) {
const fullPath = path.join(sessionPath, file)
try {
if (removeEligibleSnapshotFile(fullPath, file, cutoff)) removed++
} catch {
continue
}
}
try {
fs.rmdirSync(sessionPath)
} catch {
// ignore: directory not empty
}
} catch {
continue
}
}
} catch {
return removed
}
return removed
}