@nandoblanco/opencode-local-backup 0.0.0-stage → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js ADDED
@@ -0,0 +1,1466 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ import os from "node:os";
7
+ import { spawn } from "node:child_process";
8
+ import { fileURLToPath } from "node:url";
9
+
10
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
11
+ const cliName = "open" + "code";
12
+
13
+ const PROJECT_MARKERS = [
14
+ ".git",
15
+ "package.json",
16
+ "composer.json",
17
+ "Cargo.toml",
18
+ "pyproject.toml",
19
+ "go.mod",
20
+ ".opencode",
21
+ "opencode.jsonc",
22
+ "opencode.json",
23
+ "AGENTS.md"
24
+ ];
25
+
26
+ const EDIT_TOOLS = new Set(["edit", "write", "patch", "apply_patch", "multiedit"]);
27
+ const lastFileBackupMap = new Map();
28
+ const lastRootPruneMap = new Map();
29
+ const MAX_TRACKED_FILES = 1000;
30
+ const MAX_TRACKED_ROOTS = 256;
31
+ const PRUNE_INTERVAL_MS = 10 * 60 * 1000; // 10 minutes
32
+ const MAX_DIFF_FILE_BYTES = 512 * 1024; // 512 KB cap for synchronous TUI diff
33
+ let cachedSettingsPath = "";
34
+ let cachedSettingsMtime = -1;
35
+ let cachedSettingsValue = null;
36
+
37
+ // Config & Installer
38
+
39
+ function resolveConfigDir(customConfigDir) {
40
+ if (customConfigDir) {
41
+ if (customConfigDir.startsWith("~")) {
42
+ return path.join(os.homedir(), customConfigDir.slice(1));
43
+ }
44
+ return path.resolve(customConfigDir);
45
+ }
46
+ if (process.env.OPENCODE_CONFIG_DIR) {
47
+ return path.resolve(process.env.OPENCODE_CONFIG_DIR);
48
+ }
49
+ const configBase = process.env.XDG_CONFIG_HOME
50
+ ? path.resolve(process.env.XDG_CONFIG_HOME)
51
+ : path.join(os.homedir(), ".config");
52
+ return path.join(configBase, cliName);
53
+ }
54
+
55
+ function getSettingsFilePath(customConfigDir) {
56
+ return path.join(resolveConfigDir(customConfigDir), "auto-backup.json");
57
+ }
58
+
59
+ function readBackupSettings(customConfigDir) {
60
+ const filePath = getSettingsFilePath(customConfigDir);
61
+ const defaults = { retentionDays: 30, debounceMs: 0, rootDir: "", dialogWidth: "80%" };
62
+ let st;
63
+ try {
64
+ st = fs.statSync(filePath);
65
+ } catch {
66
+ return defaults;
67
+ }
68
+ if (cachedSettingsValue && cachedSettingsPath === filePath && cachedSettingsMtime === st.mtimeMs) {
69
+ return cachedSettingsValue;
70
+ }
71
+ try {
72
+ const parsed = JSON.parse(fs.readFileSync(filePath, "utf8"));
73
+ const result = {
74
+ retentionDays: typeof parsed.retentionDays === "number" && !Number.isNaN(parsed.retentionDays)
75
+ ? Math.max(0, Math.floor(parsed.retentionDays))
76
+ : 30,
77
+ debounceMs: typeof parsed.debounceMs === "number" && !Number.isNaN(parsed.debounceMs)
78
+ ? Math.max(0, Math.floor(parsed.debounceMs))
79
+ : 0,
80
+ rootDir: typeof parsed.rootDir === "string" ? parsed.rootDir.trim() : "",
81
+ dialogWidth: typeof parsed.dialogWidth === "string" && parsed.dialogWidth.trim()
82
+ ? parsed.dialogWidth.trim()
83
+ : typeof parsed.dialogWidth === "number" && Number.isFinite(parsed.dialogWidth) && parsed.dialogWidth > 0
84
+ ? (parsed.dialogWidth <= 100 ? Math.round(parsed.dialogWidth) + "%" : String(Math.round(parsed.dialogWidth)))
85
+ : "80%"
86
+ };
87
+ cachedSettingsPath = filePath;
88
+ cachedSettingsMtime = st.mtimeMs;
89
+ cachedSettingsValue = result;
90
+ return result;
91
+ } catch {
92
+ return defaults;
93
+ }
94
+ }
95
+
96
+ function writeBackupSettings(patch, customConfigDir) {
97
+ const configDir = resolveConfigDir(customConfigDir);
98
+ fs.mkdirSync(configDir, { recursive: true });
99
+ const current = readBackupSettings(customConfigDir);
100
+ const next = {
101
+ retentionDays: patch && typeof patch.retentionDays === "number" && !Number.isNaN(patch.retentionDays)
102
+ ? Math.max(0, Math.floor(patch.retentionDays))
103
+ : current.retentionDays,
104
+ debounceMs: patch && typeof patch.debounceMs === "number" && !Number.isNaN(patch.debounceMs)
105
+ ? Math.max(0, Math.floor(patch.debounceMs))
106
+ : current.debounceMs,
107
+ rootDir: patch && typeof patch.rootDir === "string"
108
+ ? patch.rootDir.trim()
109
+ : current.rootDir,
110
+ dialogWidth: patch && typeof patch.dialogWidth === "string" && patch.dialogWidth.trim()
111
+ ? patch.dialogWidth.trim()
112
+ : patch && typeof patch.dialogWidth === "number" && Number.isFinite(patch.dialogWidth) && patch.dialogWidth > 0
113
+ ? (patch.dialogWidth <= 100 ? Math.round(patch.dialogWidth) + "%" : String(Math.round(patch.dialogWidth)))
114
+ : current.dialogWidth
115
+ };
116
+ const filePath = path.join(configDir, "auto-backup.json");
117
+ fs.writeFileSync(filePath, JSON.stringify(next, null, 2) + "\n", "utf8");
118
+ cachedSettingsPath = "";
119
+ cachedSettingsMtime = -1;
120
+ cachedSettingsValue = null;
121
+ return { filePath: filePath, settings: next };
122
+ }
123
+
124
+ function resolveRetentionDays(explicitValue, customConfigDir) {
125
+ if (typeof explicitValue === "number" && !Number.isNaN(explicitValue)) {
126
+ return Math.max(0, Math.floor(explicitValue));
127
+ }
128
+ if (process.env.OPENCODE_BACKUP_RETENTION_DAYS !== undefined && process.env.OPENCODE_BACKUP_RETENTION_DAYS !== "") {
129
+ const envNum = Number(process.env.OPENCODE_BACKUP_RETENTION_DAYS);
130
+ if (!Number.isNaN(envNum)) return Math.max(0, Math.floor(envNum));
131
+ }
132
+ return readBackupSettings(customConfigDir).retentionDays;
133
+ }
134
+
135
+ function findPluginsArraySpan(raw) {
136
+ const keyRe = /"plugins"\s*:\s*\[/g;
137
+ const match = keyRe.exec(raw);
138
+ if (!match) return null;
139
+ const openBracketIdx = match.index + match[0].length - 1;
140
+ let depth = 0;
141
+ let inString = false;
142
+ let escaped = false;
143
+ for (let i = openBracketIdx; i < raw.length; i++) {
144
+ const ch = raw[i];
145
+ if (inString) {
146
+ if (escaped) {
147
+ escaped = false;
148
+ } else if (ch === "\\") {
149
+ escaped = true;
150
+ } else if (ch === '"') {
151
+ inString = false;
152
+ }
153
+ continue;
154
+ }
155
+ if (ch === "/" && raw[i + 1] === "/") {
156
+ const nl = raw.indexOf("\n", i + 2);
157
+ if (nl === -1) break;
158
+ i = nl;
159
+ continue;
160
+ }
161
+ if (ch === "/" && raw[i + 1] === "*") {
162
+ const endComment = raw.indexOf("*/", i + 2);
163
+ if (endComment === -1) break;
164
+ i = endComment + 1;
165
+ continue;
166
+ }
167
+ if (ch === '"') {
168
+ inString = true;
169
+ continue;
170
+ }
171
+ if (ch === "[") depth++;
172
+ else if (ch === "]") {
173
+ depth--;
174
+ if (depth === 0) {
175
+ return {
176
+ start: match.index,
177
+ openEnd: openBracketIdx + 1,
178
+ closeStart: i,
179
+ end: i + 1
180
+ };
181
+ }
182
+ }
183
+ }
184
+ return null;
185
+ }
186
+
187
+ function findLastCodeCharIndex(str) {
188
+ let lastIdx = -1;
189
+ let inString = false;
190
+ let escaped = false;
191
+ for (let i = 0; i < str.length; i++) {
192
+ const ch = str[i];
193
+ if (inString) {
194
+ lastIdx = i;
195
+ if (escaped) {
196
+ escaped = false;
197
+ } else if (ch === "\\") {
198
+ escaped = true;
199
+ } else if (ch === '"') {
200
+ inString = false;
201
+ }
202
+ continue;
203
+ }
204
+ if (ch === "/" && str[i + 1] === "/") {
205
+ const nl = str.indexOf("\n", i + 2);
206
+ if (nl === -1) break;
207
+ i = nl;
208
+ continue;
209
+ }
210
+ if (ch === "/" && str[i + 1] === "*") {
211
+ const endComment = str.indexOf("*/", i + 2);
212
+ if (endComment === -1) break;
213
+ i = endComment + 1;
214
+ continue;
215
+ }
216
+ if (ch === '"') {
217
+ inString = true;
218
+ lastIdx = i;
219
+ continue;
220
+ }
221
+ if (!/\s/.test(ch)) {
222
+ lastIdx = i;
223
+ }
224
+ }
225
+ return lastIdx;
226
+ }
227
+
228
+ function addPluginToJsoncFile(filePath, schemaUrl, pluginEntryStr, pkgName) {
229
+ if (!fs.existsSync(filePath)) {
230
+ const content = [
231
+ "{",
232
+ ' "$schema": "' + schemaUrl + '",',
233
+ ' "plugins": [',
234
+ " " + pluginEntryStr,
235
+ " ]",
236
+ "}",
237
+ ""
238
+ ].join("\n");
239
+ fs.writeFileSync(filePath, content, "utf8");
240
+ return "created";
241
+ }
242
+
243
+ const raw = fs.readFileSync(filePath, "utf8");
244
+ if (raw.includes(pkgName)) {
245
+ return "already-present";
246
+ }
247
+
248
+ const span = findPluginsArraySpan(raw);
249
+ if (span) {
250
+ const open = raw.slice(span.start, span.openEnd);
251
+ const body = raw.slice(span.openEnd, span.closeStart);
252
+ const close = raw.slice(span.closeStart, span.end);
253
+ const lastCodeIdx = findLastCodeCharIndex(body);
254
+ let replacement;
255
+ if (lastCodeIdx === -1) {
256
+ replacement = open + "\n " + pluginEntryStr + "\n " + close;
257
+ } else {
258
+ const needsComma = body[lastCodeIdx] !== ",";
259
+ const withComma = needsComma
260
+ ? body.slice(0, lastCodeIdx + 1) + "," + body.slice(lastCodeIdx + 1)
261
+ : body;
262
+ const trimmedBody = withComma.replace(/\s*$/, "");
263
+ replacement = open + trimmedBody + "\n " + pluginEntryStr + "\n " + close;
264
+ }
265
+ const updated = raw.slice(0, span.start) + replacement + raw.slice(span.end);
266
+ fs.writeFileSync(filePath, updated, "utf8");
267
+ return "updated";
268
+ }
269
+
270
+ const lastBraceIdx = raw.lastIndexOf("}");
271
+ if (lastBraceIdx !== -1) {
272
+ const beforeSlice = raw.slice(0, lastBraceIdx);
273
+ const lastCodeIdx = findLastCodeCharIndex(beforeSlice);
274
+ const lastChar = lastCodeIdx !== -1 ? beforeSlice[lastCodeIdx] : "{";
275
+ const needsComma = lastChar !== "{" && lastChar !== ",";
276
+ const withComma = (needsComma && lastCodeIdx !== -1)
277
+ ? beforeSlice.slice(0, lastCodeIdx + 1) + "," + beforeSlice.slice(lastCodeIdx + 1)
278
+ : beforeSlice;
279
+ const before = withComma.replace(/\s*$/, "");
280
+ const updated =
281
+ before +
282
+ '\n "plugins": [\n ' +
283
+ pluginEntryStr +
284
+ "\n ]\n}\n";
285
+ fs.writeFileSync(filePath, updated, "utf8");
286
+ return "updated";
287
+ }
288
+
289
+ return "skipped";
290
+ }
291
+
292
+ async function installPlugin(options) {
293
+ const opts = options || {};
294
+ const configDir = resolveConfigDir(opts.configDir);
295
+ fs.mkdirSync(configDir, { recursive: true });
296
+
297
+ const pkgName = "@nandoblanco/opencode-local-backup";
298
+ const matchKey = "opencode-local-backup";
299
+ const entryStr = opts.retentionDays
300
+ ? '["' + pkgName + '", { "retentionDays": ' + Number(opts.retentionDays) + " }]"
301
+ : '"' + pkgName + '"';
302
+
303
+ const jsoncPath = path.join(configDir, cliName + ".jsonc");
304
+ const jsonPath = path.join(configDir, cliName + ".json");
305
+ const serverConfigFile = fs.existsSync(jsoncPath)
306
+ ? jsoncPath
307
+ : fs.existsSync(jsonPath)
308
+ ? jsonPath
309
+ : jsoncPath;
310
+
311
+ const cliConfigFile = path.join(configDir, "cli.json");
312
+
313
+ const serverStatus = addPluginToJsoncFile(
314
+ serverConfigFile,
315
+ "https://" + cliName + ".ai/config.json",
316
+ entryStr,
317
+ matchKey
318
+ );
319
+ const cliStatus = addPluginToJsoncFile(
320
+ cliConfigFile,
321
+ "https://" + cliName + ".ai/v2/cli.json",
322
+ entryStr,
323
+ matchKey
324
+ );
325
+
326
+ return {
327
+ configDir: configDir,
328
+ serverConfigFile: serverConfigFile,
329
+ serverStatus: serverStatus,
330
+ cliConfigFile: cliConfigFile,
331
+ cliStatus: cliStatus
332
+ };
333
+ }
334
+
335
+ // Path & Project Root Resolution
336
+
337
+ function normalizeSlashes(p) {
338
+ return String(p || "").replace(/\\/g, "/");
339
+ }
340
+
341
+ function isSubPath(parentDir, childPath) {
342
+ const rel = path.relative(parentDir, childPath);
343
+ return Boolean(rel && !rel.startsWith("..") && !path.isAbsolute(rel)) || path.resolve(parentDir) === path.resolve(childPath);
344
+ }
345
+
346
+ function resolveProjectRoot(filePath, workspaceDir) {
347
+ const absFile = path.resolve(filePath);
348
+ const startDir = fs.existsSync(absFile) && fs.statSync(absFile).isDirectory()
349
+ ? absFile
350
+ : path.dirname(absFile);
351
+
352
+ const absWorkspace = workspaceDir ? path.resolve(workspaceDir) : "";
353
+ let current = startDir;
354
+
355
+ while (true) {
356
+ for (const marker of PROJECT_MARKERS) {
357
+ if (fs.existsSync(path.join(current, marker))) {
358
+ return current;
359
+ }
360
+ }
361
+ if (absWorkspace && path.resolve(current) === absWorkspace) {
362
+ return absWorkspace;
363
+ }
364
+ const parent = path.dirname(current);
365
+ if (!parent || parent === current) {
366
+ break;
367
+ }
368
+ if (absWorkspace && !isSubPath(absWorkspace, parent)) {
369
+ return absWorkspace;
370
+ }
371
+ current = parent;
372
+ }
373
+
374
+ if (absWorkspace && isSubPath(absWorkspace, startDir)) {
375
+ return absWorkspace;
376
+ }
377
+ return startDir;
378
+ }
379
+
380
+ function extractPatchedPaths(patchText) {
381
+ if (typeof patchText !== "string" || !patchText) return [];
382
+ const results = [];
383
+ const seen = new Set();
384
+ const re = /^\*\*\*\s+(?:Update|Delete|Move)\s+File:\s*(.+)$/gm;
385
+ let match;
386
+ while ((match = re.exec(patchText)) !== null) {
387
+ const raw = match[1].trim();
388
+ if (raw && !seen.has(raw)) {
389
+ seen.add(raw);
390
+ results.push(raw);
391
+ }
392
+ }
393
+ return results;
394
+ }
395
+
396
+ function extractTargetFiles(toolName, input, baseDir) {
397
+ if (!input || typeof input !== "object") return [];
398
+ const rawPaths = [];
399
+
400
+ if (typeof input.filePath === "string" && input.filePath.trim()) {
401
+ rawPaths.push(input.filePath.trim());
402
+ }
403
+ if (typeof input.path === "string" && input.path.trim()) {
404
+ rawPaths.push(input.path.trim());
405
+ }
406
+ if (typeof input.patchText === "string") {
407
+ const patched = extractPatchedPaths(input.patchText);
408
+ for (const p of patched) rawPaths.push(p);
409
+ }
410
+ if (typeof input.patch === "string") {
411
+ const patched = extractPatchedPaths(input.patch);
412
+ for (const p of patched) rawPaths.push(p);
413
+ }
414
+ if (Array.isArray(input.files)) {
415
+ for (const f of input.files) {
416
+ if (typeof f === "string" && f.trim()) rawPaths.push(f.trim());
417
+ else if (f && typeof f.filePath === "string") rawPaths.push(f.filePath.trim());
418
+ else if (f && typeof f.path === "string") rawPaths.push(f.path.trim());
419
+ }
420
+ }
421
+ if (Array.isArray(input.edits)) {
422
+ for (const e of input.edits) {
423
+ if (e && typeof e.filePath === "string") rawPaths.push(e.filePath.trim());
424
+ else if (e && typeof e.path === "string") rawPaths.push(e.path.trim());
425
+ }
426
+ }
427
+
428
+ const resolved = [];
429
+ const seen = new Set();
430
+ for (const raw of rawPaths) {
431
+ const abs = baseDir && !path.isAbsolute(raw)
432
+ ? path.resolve(baseDir, raw)
433
+ : path.resolve(raw);
434
+ if (!seen.has(abs)) {
435
+ seen.add(abs);
436
+ resolved.push(abs);
437
+ }
438
+ }
439
+ return resolved;
440
+ }
441
+
442
+ // Snapshot Creation & Pruning
443
+
444
+ function formatTimestamp(date) {
445
+ const d = date instanceof Date ? date : new Date();
446
+ const pad = function (n) { return String(n).padStart(2, "0"); };
447
+ return (
448
+ d.getFullYear() +
449
+ "-" +
450
+ pad(d.getMonth() + 1) +
451
+ "-" +
452
+ pad(d.getDate()) +
453
+ "_" +
454
+ pad(d.getHours()) +
455
+ "-" +
456
+ pad(d.getMinutes()) +
457
+ "-" +
458
+ pad(d.getSeconds())
459
+ );
460
+ }
461
+
462
+ function sanitizeSlug(name) {
463
+ const clean = String(name || "auto-backup")
464
+ .replace(/[^a-zA-Z0-9\-]+/g, "-")
465
+ .replace(/^-+|-+$/g, "")
466
+ .toLowerCase();
467
+ return clean || "auto-backup";
468
+ }
469
+
470
+ function parseFolderTimestamp(folderName) {
471
+ const m = String(folderName || "").match(/^(\d{4})-(\d{2})-(\d{2})_(\d{2})-(\d{2})-(\d{2})_(.+)$/);
472
+ if (!m) return null;
473
+ const dt = new Date(
474
+ Number(m[1]),
475
+ Number(m[2]) - 1,
476
+ Number(m[3]),
477
+ Number(m[4]),
478
+ Number(m[5]),
479
+ Number(m[6])
480
+ );
481
+ return {
482
+ timeMs: dt.getTime(),
483
+ iso: dt.toISOString(),
484
+ slug: m[7]
485
+ };
486
+ }
487
+
488
+ function pruneOldBackups(rootDir, retentionDays) {
489
+ const days = resolveRetentionDays(retentionDays);
490
+ const backupsDir = path.join(path.resolve(rootDir), ".backups");
491
+ if (days <= 0) {
492
+ return { removed: 0, disabled: true, retentionDays: 0, backupsDir: backupsDir };
493
+ }
494
+ if (!fs.existsSync(backupsDir)) {
495
+ return { removed: 0, disabled: false, retentionDays: days, backupsDir: backupsDir };
496
+ }
497
+
498
+ const cutoffMs = Date.now() - days * 24 * 60 * 60 * 1000;
499
+ let removed = 0;
500
+ const entries = fs.readdirSync(backupsDir, { withFileTypes: true });
501
+
502
+ for (const entry of entries) {
503
+ if (!entry.isDirectory()) continue;
504
+ const fullDir = path.join(backupsDir, entry.name);
505
+ let folderTimeMs = 0;
506
+ const parsed = parseFolderTimestamp(entry.name);
507
+ if (parsed && !Number.isNaN(parsed.timeMs)) {
508
+ folderTimeMs = parsed.timeMs;
509
+ } else {
510
+ try {
511
+ folderTimeMs = fs.statSync(fullDir).mtimeMs;
512
+ } catch {
513
+ continue;
514
+ }
515
+ }
516
+
517
+ if (folderTimeMs > 0 && folderTimeMs < cutoffMs) {
518
+ try {
519
+ fs.rmSync(fullDir, { recursive: true, force: true });
520
+ removed++;
521
+ } catch {
522
+ // Ignore locked folders
523
+ }
524
+ }
525
+ }
526
+
527
+ return { removed: removed, disabled: false, retentionDays: days, backupsDir: backupsDir };
528
+ }
529
+
530
+ function createBackupSnapshot(options) {
531
+ const opts = options || {};
532
+ const rawFiles = Array.isArray(opts.files) ? opts.files : [];
533
+ const workspaceDir = opts.workspaceDir || "";
534
+ const explicitRoot = opts.root ? path.resolve(opts.root) : "";
535
+ const slug = sanitizeSlug(opts.name || opts.slug || "auto-backup");
536
+ const toolName = String(opts.tool || "manual");
537
+ const debounceMs = typeof opts.debounceMs === "number" ? opts.debounceMs : 0;
538
+ const retentionDays = resolveRetentionDays(opts.retentionDays);
539
+ const now = Date.now();
540
+
541
+ const existingFiles = [];
542
+ for (const f of rawFiles) {
543
+ const abs = explicitRoot && !path.isAbsolute(f)
544
+ ? path.resolve(explicitRoot, f)
545
+ : path.resolve(f);
546
+ let st;
547
+ try {
548
+ st = fs.statSync(abs);
549
+ if (!st.isFile()) continue;
550
+ } catch {
551
+ continue;
552
+ }
553
+ if (debounceMs > 0 && !opts.force) {
554
+ const prev = lastFileBackupMap.get(abs) || 0;
555
+ if (now - prev < debounceMs) continue;
556
+ }
557
+ existingFiles.push({ abs: abs, size: st.size, mtimeMs: st.mtimeMs });
558
+ }
559
+
560
+ if (existingFiles.length === 0) {
561
+ return null;
562
+ }
563
+
564
+ const rootDir = explicitRoot || resolveProjectRoot(existingFiles[0].abs, workspaceDir);
565
+ const stamp = formatTimestamp(new Date(now));
566
+ const snapshotId = stamp + "_" + slug;
567
+ const backupsBase = path.join(rootDir, ".backups");
568
+ let snapshotDir = path.join(backupsBase, snapshotId);
569
+
570
+ let suffix = 2;
571
+ while (fs.existsSync(snapshotDir)) {
572
+ snapshotDir = path.join(backupsBase, snapshotId + "-" + suffix);
573
+ suffix++;
574
+ }
575
+
576
+ const backedUpFiles = [];
577
+ for (const item of existingFiles) {
578
+ const absFile = item.abs;
579
+ let relPath = path.relative(rootDir, absFile);
580
+ if (!relPath || relPath.startsWith("..") || path.isAbsolute(relPath)) {
581
+ relPath = path.basename(absFile);
582
+ }
583
+ const targetPath = path.join(snapshotDir, relPath);
584
+ fs.mkdirSync(path.dirname(targetPath), { recursive: true });
585
+ fs.copyFileSync(absFile, targetPath);
586
+ if (lastFileBackupMap.size >= MAX_TRACKED_FILES && !lastFileBackupMap.has(absFile)) {
587
+ const oldestKey = lastFileBackupMap.keys().next().value;
588
+ if (oldestKey !== undefined) lastFileBackupMap.delete(oldestKey);
589
+ }
590
+ lastFileBackupMap.set(absFile, now);
591
+ backedUpFiles.push({
592
+ relativePath: normalizeSlashes(relPath),
593
+ originalPath: absFile,
594
+ backupPath: targetPath,
595
+ size: item.size,
596
+ mtimeMs: item.mtimeMs
597
+ });
598
+ }
599
+
600
+ const meta = {
601
+ id: path.basename(snapshotDir),
602
+ timestamp: new Date(now).toISOString(),
603
+ timeMs: now,
604
+ slug: slug,
605
+ tool: toolName,
606
+ root: rootDir,
607
+ files: backedUpFiles.map(function (f) {
608
+ return {
609
+ relativePath: f.relativePath,
610
+ originalPath: f.originalPath,
611
+ size: f.size,
612
+ mtimeMs: f.mtimeMs
613
+ };
614
+ })
615
+ };
616
+
617
+ try {
618
+ fs.writeFileSync(path.join(snapshotDir, ".backup-meta.json"), JSON.stringify(meta, null, 2), "utf8");
619
+ } catch {
620
+ // Non-fatal if metadata write fails
621
+ }
622
+
623
+ const lastPrune = lastRootPruneMap.get(rootDir) || 0;
624
+ if (retentionDays > 0 && (opts.pruneNow || now - lastPrune >= PRUNE_INTERVAL_MS)) {
625
+ if (lastRootPruneMap.size >= MAX_TRACKED_ROOTS && !lastRootPruneMap.has(rootDir)) {
626
+ const oldestRoot = lastRootPruneMap.keys().next().value;
627
+ if (oldestRoot !== undefined) lastRootPruneMap.delete(oldestRoot);
628
+ }
629
+ lastRootPruneMap.set(rootDir, now);
630
+ pruneOldBackups(rootDir, retentionDays);
631
+ }
632
+
633
+ return {
634
+ id: meta.id,
635
+ root: rootDir,
636
+ snapshotDir: snapshotDir,
637
+ slug: slug,
638
+ tool: toolName,
639
+ timeMs: now,
640
+ files: backedUpFiles
641
+ };
642
+ }
643
+
644
+ // Listing, Diffing & Restoring Backups
645
+
646
+ function walkSnapshotFiles(dir, baseDir, out) {
647
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
648
+ for (const entry of entries) {
649
+ if (entry.name === ".backup-meta.json") continue;
650
+ const full = path.join(dir, entry.name);
651
+ if (entry.isDirectory()) {
652
+ walkSnapshotFiles(full, baseDir, out);
653
+ } else if (entry.isFile()) {
654
+ const rel = normalizeSlashes(path.relative(baseDir, full));
655
+ const st = fs.statSync(full);
656
+ out.push({
657
+ relativePath: rel,
658
+ backupPath: full,
659
+ size: st.size,
660
+ mtimeMs: st.mtimeMs
661
+ });
662
+ }
663
+ }
664
+ }
665
+
666
+ const SKIP_SCAN_DIRS = new Set([
667
+ "node_modules",
668
+ ".git",
669
+ ".screenshots",
670
+ "xampp",
671
+ "vendor",
672
+ ".next",
673
+ "dist",
674
+ "build",
675
+ ".cache",
676
+ "bower_components"
677
+ ]);
678
+
679
+ function resolveTopWorkspaceRoot(startDir) {
680
+ let current = path.resolve(startDir || process.cwd());
681
+ let topCandidate = current;
682
+
683
+ while (true) {
684
+ const parent = path.dirname(current);
685
+ if (!parent || parent === current) break;
686
+ // Do not climb into filesystem root (e.g. C:\ or /) or OS home directory
687
+ const grandParent = path.dirname(parent);
688
+ if (!grandParent || grandParent === parent || parent.toLowerCase() === os.homedir().toLowerCase()) {
689
+ break;
690
+ }
691
+ if (
692
+ fs.existsSync(path.join(parent, ".backups")) ||
693
+ fs.existsSync(path.join(parent, "AGENTS.md")) ||
694
+ fs.existsSync(path.join(parent, ".opencode"))
695
+ ) {
696
+ topCandidate = parent;
697
+ }
698
+ current = parent;
699
+ }
700
+
701
+ return topCandidate;
702
+ }
703
+
704
+ function resolveScanRootDir(startDir, customConfigDir) {
705
+ if (process.env.OPENCODE_BACKUP_ROOT_DIR && process.env.OPENCODE_BACKUP_ROOT_DIR.trim()) {
706
+ return path.resolve(process.env.OPENCODE_BACKUP_ROOT_DIR.trim());
707
+ }
708
+ const settings = readBackupSettings(customConfigDir);
709
+ if (settings.rootDir && fs.existsSync(settings.rootDir)) {
710
+ return path.resolve(settings.rootDir);
711
+ }
712
+ return resolveTopWorkspaceRoot(startDir);
713
+ }
714
+
715
+ function collectBackupRoots(startDir, includeSubprojects, maxDepth) {
716
+ const base = path.resolve(startDir || process.cwd());
717
+ const depthLimit = typeof maxDepth === "number" && maxDepth > 0 ? maxDepth : Infinity;
718
+ const roots = new Set();
719
+
720
+ const projectRoot = resolveProjectRoot(base, base);
721
+ if (fs.existsSync(path.join(projectRoot, ".backups"))) {
722
+ roots.add(projectRoot);
723
+ }
724
+ if (fs.existsSync(path.join(base, ".backups"))) {
725
+ roots.add(base);
726
+ }
727
+
728
+ const scanRoot = includeSubprojects ? resolveScanRootDir(base) : base;
729
+ if (fs.existsSync(path.join(scanRoot, ".backups"))) {
730
+ roots.add(scanRoot);
731
+ }
732
+ if (includeSubprojects && fs.existsSync(scanRoot)) {
733
+ const scanDir = function (dir, depth) {
734
+ if (depth > depthLimit) return;
735
+ let entries = [];
736
+ try {
737
+ entries = fs.readdirSync(dir, { withFileTypes: true });
738
+ } catch {
739
+ return;
740
+ }
741
+ for (const entry of entries) {
742
+ if (!entry.isDirectory()) continue;
743
+ if (SKIP_SCAN_DIRS.has(entry.name)) continue;
744
+ const full = path.join(dir, entry.name);
745
+ if (entry.name === ".backups") {
746
+ roots.add(dir);
747
+ continue;
748
+ }
749
+ if (!entry.name.startsWith(".")) {
750
+ scanDir(full, depth + 1);
751
+ }
752
+ }
753
+ };
754
+ scanDir(scanRoot, 0);
755
+ }
756
+
757
+ if (roots.size === 0) {
758
+ roots.add(projectRoot);
759
+ }
760
+ return Array.from(roots);
761
+ }
762
+
763
+ function listBackups(rootDir, options) {
764
+ const opts = options || {};
765
+ const roots = collectBackupRoots(rootDir, Boolean(opts.includeSubprojects), opts.maxDepth);
766
+ const items = [];
767
+
768
+ for (const r of roots) {
769
+ const backupsDir = path.join(r, ".backups");
770
+ if (!fs.existsSync(backupsDir)) continue;
771
+
772
+ let dirs = [];
773
+ try {
774
+ dirs = fs.readdirSync(backupsDir, { withFileTypes: true });
775
+ } catch {
776
+ continue;
777
+ }
778
+
779
+ for (const d of dirs) {
780
+ if (!d.isDirectory()) continue;
781
+ const snapDir = path.join(backupsDir, d.name);
782
+ const metaPath = path.join(snapDir, ".backup-meta.json");
783
+ const parsed = parseFolderTimestamp(d.name);
784
+ let timeMs = parsed ? parsed.timeMs : 0;
785
+ let slug = parsed ? parsed.slug : d.name;
786
+ let tool = "auto";
787
+
788
+ if (!timeMs) {
789
+ try {
790
+ timeMs = fs.statSync(snapDir).mtimeMs;
791
+ } catch {
792
+ timeMs = Date.now();
793
+ }
794
+ }
795
+
796
+ if (fs.existsSync(metaPath)) {
797
+ try {
798
+ const meta = JSON.parse(fs.readFileSync(metaPath, "utf8"));
799
+ if (meta.timeMs) timeMs = meta.timeMs;
800
+ if (meta.slug) slug = meta.slug;
801
+ if (meta.tool) tool = meta.tool;
802
+ if (Array.isArray(meta.files)) {
803
+ for (const f of meta.files) {
804
+ if (!f || typeof f.relativePath !== "string" || !f.relativePath) continue;
805
+ const bPath = path.resolve(snapDir, f.relativePath);
806
+ if (bPath === path.resolve(snapDir) || !isSubPath(snapDir, bPath)) continue;
807
+ if (!fs.existsSync(bPath)) continue;
808
+ const origPath = f.originalPath
809
+ ? path.resolve(String(f.originalPath))
810
+ : path.resolve(r, f.relativePath);
811
+ if (!isSubPath(r, origPath) || isSubPath(backupsDir, origPath)) continue;
812
+ items.push({
813
+ id: d.name + "::" + f.relativePath,
814
+ snapshotId: d.name,
815
+ root: r,
816
+ slug: slug,
817
+ tool: tool,
818
+ timeMs: timeMs,
819
+ relativePath: normalizeSlashes(path.relative(snapDir, bPath)),
820
+ fileName: path.basename(bPath),
821
+ backupPath: bPath,
822
+ originalPath: origPath,
823
+ size: typeof f.size === "number" ? f.size : fs.statSync(bPath).size
824
+ });
825
+ }
826
+ continue;
827
+ }
828
+ } catch {
829
+ // Fall back to directory walk
830
+ }
831
+ }
832
+
833
+ const walked = [];
834
+ try {
835
+ walkSnapshotFiles(snapDir, snapDir, walked);
836
+ } catch {
837
+ continue;
838
+ }
839
+ for (const f of walked) {
840
+ const origPath = path.join(r, f.relativePath);
841
+ items.push({
842
+ id: d.name + "::" + f.relativePath,
843
+ snapshotId: d.name,
844
+ root: r,
845
+ slug: slug,
846
+ tool: tool,
847
+ timeMs: timeMs,
848
+ relativePath: f.relativePath,
849
+ fileName: path.basename(f.relativePath),
850
+ backupPath: f.backupPath,
851
+ originalPath: origPath,
852
+ size: f.size
853
+ });
854
+ }
855
+ }
856
+ }
857
+
858
+ items.sort(function (a, b) {
859
+ return b.timeMs - a.timeMs;
860
+ });
861
+
862
+ if (typeof opts.limit === "number" && opts.limit > 0) {
863
+ return items.slice(0, opts.limit);
864
+ }
865
+ return items;
866
+ }
867
+
868
+ function readTextSafeForDiff(filePath) {
869
+ let st;
870
+ try {
871
+ st = fs.statSync(filePath);
872
+ } catch {
873
+ return { status: "missing" };
874
+ }
875
+ if (!st.isFile()) {
876
+ return { status: "binary" };
877
+ }
878
+ if (st.size > MAX_DIFF_FILE_BYTES) {
879
+ return { status: "too-large", size: st.size };
880
+ }
881
+ try {
882
+ const buf = fs.readFileSync(filePath);
883
+ const probeLen = Math.min(buf.length, 4096);
884
+ for (let i = 0; i < probeLen; i++) {
885
+ if (buf[i] === 0) {
886
+ return { status: "binary" };
887
+ }
888
+ }
889
+ return { status: "ok", text: buf.toString("utf8") };
890
+ } catch {
891
+ return { status: "binary" };
892
+ }
893
+ }
894
+
895
+ function computeUnifiedDiff(backupFilePath, currentFilePath, maxLines) {
896
+ const limit = typeof maxLines === "number" && maxLines > 0 ? maxLines : 160;
897
+ const backupRead = readTextSafeForDiff(backupFilePath);
898
+ if (backupRead.status === "missing") {
899
+ return { status: "missing-backup", summary: "Backup file missing", lines: [] };
900
+ }
901
+ if (backupRead.status === "too-large") {
902
+ return { status: "binary", summary: "File too large for inline diff (" + Math.round(backupRead.size / 1024) + " KB)", lines: [] };
903
+ }
904
+ if (backupRead.status !== "ok") {
905
+ return { status: "binary", summary: "Binary or unreadable file", lines: [] };
906
+ }
907
+ const backupText = backupRead.text;
908
+
909
+ const currentRead = readTextSafeForDiff(currentFilePath);
910
+ if (currentRead.status === "missing") {
911
+ const bLines = backupText.split(/\r?\n/);
912
+ return {
913
+ status: "deleted",
914
+ summary: "File was deleted on disk (restoring will recreate it)",
915
+ lines: bLines.slice(0, limit).map(function (l) {
916
+ return { type: "add", text: "+ " + l };
917
+ })
918
+ };
919
+ }
920
+ if (currentRead.status === "too-large") {
921
+ return { status: "binary", summary: "File too large for inline diff (" + Math.round(currentRead.size / 1024) + " KB)", lines: [] };
922
+ }
923
+ if (currentRead.status !== "ok") {
924
+ return { status: "binary", summary: "Binary or unreadable file", lines: [] };
925
+ }
926
+ const currentText = currentRead.text;
927
+
928
+ if (backupText === currentText) {
929
+ const sameLines = backupText.split(/\r?\n/).slice(0, 40);
930
+ return {
931
+ status: "identical",
932
+ summary: "Identical to current file on disk",
933
+ lines: sameLines.map(function (l) {
934
+ return { type: "context", text: " " + l };
935
+ })
936
+ };
937
+ }
938
+
939
+ const oldLines = currentText.split(/\r?\n/);
940
+ const newLines = backupText.split(/\r?\n/);
941
+ const rawOps = [];
942
+ let added = 0;
943
+ let removed = 0;
944
+
945
+ let i = 0;
946
+ let j = 0;
947
+
948
+ while (i < oldLines.length || j < newLines.length) {
949
+ if (i < oldLines.length && j < newLines.length && oldLines[i] === newLines[j]) {
950
+ rawOps.push({
951
+ type: "context",
952
+ oldLine: i + 1,
953
+ newLine: j + 1,
954
+ text: " " + String(i + 1).padStart(4, " ") + " │ " + oldLines[i]
955
+ });
956
+ i++;
957
+ j++;
958
+ continue;
959
+ }
960
+
961
+ let foundMatch = false;
962
+ for (let look = 1; look <= 25; look++) {
963
+ if (i + look < oldLines.length && oldLines[i + look] === newLines[j]) {
964
+ for (let k = 0; k < look; k++) {
965
+ removed++;
966
+ rawOps.push({
967
+ type: "del",
968
+ oldLine: i + k + 1,
969
+ newLine: j + 1,
970
+ text: "- " + String(i + k + 1).padStart(4, " ") + " │ " + oldLines[i + k]
971
+ });
972
+ }
973
+ i += look;
974
+ foundMatch = true;
975
+ break;
976
+ }
977
+ if (j + look < newLines.length && oldLines[i] === newLines[j + look]) {
978
+ for (let k = 0; k < look; k++) {
979
+ added++;
980
+ rawOps.push({
981
+ type: "add",
982
+ oldLine: i + 1,
983
+ newLine: j + k + 1,
984
+ text: "+ " + String(j + k + 1).padStart(4, " ") + " │ " + newLines[j + k]
985
+ });
986
+ }
987
+ j += look;
988
+ foundMatch = true;
989
+ break;
990
+ }
991
+ }
992
+
993
+ if (!foundMatch) {
994
+ if (i < oldLines.length) {
995
+ removed++;
996
+ rawOps.push({
997
+ type: "del",
998
+ oldLine: i + 1,
999
+ newLine: j + 1,
1000
+ text: "- " + String(i + 1).padStart(4, " ") + " │ " + oldLines[i]
1001
+ });
1002
+ i++;
1003
+ }
1004
+ if (j < newLines.length) {
1005
+ added++;
1006
+ rawOps.push({
1007
+ type: "add",
1008
+ oldLine: i + 1,
1009
+ newLine: j + 1,
1010
+ text: "+ " + String(j + 1).padStart(4, " ") + " │ " + newLines[j]
1011
+ });
1012
+ j++;
1013
+ }
1014
+ }
1015
+ }
1016
+
1017
+ // Keep only changed lines plus 3 lines of context around each change (hunks)
1018
+ const CONTEXT_RADIUS = 3;
1019
+ const includeIdx = new Uint8Array(rawOps.length);
1020
+ for (let idx = 0; idx < rawOps.length; idx++) {
1021
+ if (rawOps[idx].type !== "context") {
1022
+ const start = Math.max(0, idx - CONTEXT_RADIUS);
1023
+ const end = Math.min(rawOps.length - 1, idx + CONTEXT_RADIUS);
1024
+ for (let c = start; c <= end; c++) {
1025
+ includeIdx[c] = 1;
1026
+ }
1027
+ }
1028
+ }
1029
+
1030
+ const diffLines = [];
1031
+ let lastIncluded = -1;
1032
+ for (let idx = 0; idx < rawOps.length; idx++) {
1033
+ if (!includeIdx[idx]) continue;
1034
+ if (diffLines.length >= limit) break;
1035
+ if (lastIncluded === -1 || idx > lastIncluded + 1) {
1036
+ const op = rawOps[idx];
1037
+ diffLines.push({
1038
+ type: "hunk",
1039
+ text: "@@ current line " + op.oldLine + " / backup line " + op.newLine + " @@"
1040
+ });
1041
+ if (diffLines.length >= limit) break;
1042
+ }
1043
+ diffLines.push({
1044
+ type: rawOps[idx].type,
1045
+ text: rawOps[idx].text
1046
+ });
1047
+ lastIncluded = idx;
1048
+ }
1049
+
1050
+ return {
1051
+ status: "modified",
1052
+ summary: "Restoring will revert current file (+" + added + " / -" + removed + " lines)",
1053
+ lines: diffLines
1054
+ };
1055
+ }
1056
+
1057
+ function restoreBackupFile(entry, options) {
1058
+ const opts = options || {};
1059
+ if (!entry || !entry.backupPath || !fs.existsSync(entry.backupPath)) {
1060
+ throw new Error("Backup snapshot file not found: " + (entry ? entry.backupPath : "unknown"));
1061
+ }
1062
+ const absBackupPath = path.resolve(entry.backupPath);
1063
+ const rootDir = entry.root ? path.resolve(entry.root) : "";
1064
+ const rawTarget = entry.originalPath || (rootDir && entry.relativePath ? path.join(rootDir, entry.relativePath) : "");
1065
+ if (!rawTarget) {
1066
+ throw new Error("Invalid restore target path");
1067
+ }
1068
+ const targetPath = path.resolve(rawTarget);
1069
+ if (rootDir) {
1070
+ const backupsBase = path.join(rootDir, ".backups");
1071
+ if (!isSubPath(backupsBase, absBackupPath) || absBackupPath === backupsBase) {
1072
+ throw new Error("Refusing to restore from path outside project .backups directory: " + absBackupPath);
1073
+ }
1074
+ if (!isSubPath(rootDir, targetPath) || targetPath === rootDir || isSubPath(backupsBase, targetPath)) {
1075
+ throw new Error("Refusing to restore file outside project root: " + targetPath);
1076
+ }
1077
+ }
1078
+
1079
+ let safetySnapshot = null;
1080
+ if (!opts.skipSafetyBackup && fs.existsSync(targetPath)) {
1081
+ safetySnapshot = createBackupSnapshot({
1082
+ root: rootDir || entry.root,
1083
+ name: "pre-restore",
1084
+ tool: "restore",
1085
+ files: [targetPath],
1086
+ force: true
1087
+ });
1088
+ }
1089
+
1090
+ fs.mkdirSync(path.dirname(targetPath), { recursive: true });
1091
+ fs.copyFileSync(absBackupPath, targetPath);
1092
+
1093
+ return {
1094
+ restoredPath: targetPath,
1095
+ fromSnapshot: entry.snapshotId,
1096
+ safetySnapshot: safetySnapshot ? safetySnapshot.snapshotDir : null
1097
+ };
1098
+ }
1099
+
1100
+ function assertSafeWinShellPaths(paths) {
1101
+ if (process.platform !== "win32") return;
1102
+ for (const p of paths) {
1103
+ if (/[&|<>^%\r\n\0]/.test(p)) {
1104
+ throw new Error("Unsafe characters in file path for Windows shell launcher: " + p);
1105
+ }
1106
+ }
1107
+ }
1108
+
1109
+ function openBackupFile(filePath) {
1110
+ const absPath = path.resolve(filePath);
1111
+ if (!fs.existsSync(absPath)) {
1112
+ throw new Error("File not found: " + absPath);
1113
+ }
1114
+
1115
+ const customEditor = process.env.OPENCODE_BACKUP_EDITOR || process.env.VISUAL || process.env.EDITOR || "";
1116
+ if (customEditor) {
1117
+ assertSafeWinShellPaths([absPath]);
1118
+ const child = spawn(customEditor, [absPath], {
1119
+ detached: true,
1120
+ stdio: "ignore",
1121
+ shell: process.platform === "win32"
1122
+ });
1123
+ child.on("error", function () {});
1124
+ child.unref();
1125
+ return { openedPath: absPath, launcher: customEditor };
1126
+ }
1127
+
1128
+ if (process.platform === "win32") {
1129
+ const child = spawn("explorer.exe", [absPath], {
1130
+ detached: true,
1131
+ stdio: "ignore",
1132
+ windowsHide: true
1133
+ });
1134
+ child.on("error", function () {});
1135
+ child.unref();
1136
+ return { openedPath: absPath, launcher: "system-default (explorer.exe)" };
1137
+ }
1138
+
1139
+ const openCmd = process.platform === "darwin" ? "open" : "xdg-open";
1140
+ const child = spawn(openCmd, [absPath], {
1141
+ detached: true,
1142
+ stdio: "ignore"
1143
+ });
1144
+ child.on("error", function () {});
1145
+ child.unref();
1146
+ return { openedPath: absPath, launcher: openCmd };
1147
+ }
1148
+
1149
+ function openBackupDiff(backupFilePath, currentFilePath) {
1150
+ const absBackup = path.resolve(backupFilePath);
1151
+ const absCurrent = path.resolve(currentFilePath);
1152
+ if (!fs.existsSync(absBackup)) {
1153
+ throw new Error("Backup file not found: " + absBackup);
1154
+ }
1155
+ if (!fs.existsSync(absCurrent)) {
1156
+ throw new Error("Current file on disk not found: " + absCurrent);
1157
+ }
1158
+
1159
+ assertSafeWinShellPaths([absBackup, absCurrent]);
1160
+ const diffCmd = process.env.OPENCODE_BACKUP_DIFF_CMD || "code";
1161
+ const args = diffCmd === "code" ? ["--diff", absBackup, absCurrent] : [absBackup, absCurrent];
1162
+ const child = spawn(diffCmd, args, {
1163
+ detached: true,
1164
+ stdio: "ignore",
1165
+ shell: process.platform === "win32",
1166
+ windowsHide: true
1167
+ });
1168
+ child.on("error", function () {});
1169
+ child.unref();
1170
+ return { backupPath: absBackup, currentPath: absCurrent, launcher: diffCmd + " --diff" };
1171
+ }
1172
+
1173
+ // OpenCode Server Plugin
1174
+
1175
+ function createPluginDefinition() {
1176
+ return {
1177
+ id: "opencode-local-backup",
1178
+ async setup(ctx) {
1179
+ const opts = (ctx && ctx.options) || {};
1180
+ const customRoot = opts.backupRoot || process.env.OPENCODE_BACKUP_ROOT || "";
1181
+ const workspaceDir = (ctx && ctx.location && ctx.location.directory) ? ctx.location.directory : process.cwd();
1182
+
1183
+ const registrations = [];
1184
+
1185
+ if (ctx && ctx.tool && typeof ctx.tool.hook === "function") {
1186
+ const hookReg = await ctx.tool.hook("execute.before", function (event) {
1187
+ const toolName = String(event && event.tool ? event.tool : "");
1188
+ if (!EDIT_TOOLS.has(toolName)) return;
1189
+
1190
+ const targets = extractTargetFiles(toolName, event.input, workspaceDir);
1191
+ if (targets.length === 0) return;
1192
+
1193
+ const savedSettings = readBackupSettings();
1194
+ const debounceMs = typeof opts.debounceMs === "number"
1195
+ ? opts.debounceMs
1196
+ : process.env.OPENCODE_BACKUP_DEBOUNCE_MS !== undefined
1197
+ ? Number(process.env.OPENCODE_BACKUP_DEBOUNCE_MS)
1198
+ : savedSettings.debounceMs;
1199
+ const retentionDays = resolveRetentionDays(opts.retentionDays);
1200
+
1201
+ const byRoot = new Map();
1202
+ for (const absFile of targets) {
1203
+ if (!fs.existsSync(absFile)) continue;
1204
+ const root = customRoot
1205
+ ? path.resolve(customRoot)
1206
+ : resolveProjectRoot(absFile, workspaceDir);
1207
+ if (!byRoot.has(root)) byRoot.set(root, []);
1208
+ byRoot.get(root).push(absFile);
1209
+ }
1210
+
1211
+ for (const [root, files] of byRoot.entries()) {
1212
+ const firstBase = path.basename(files[0], path.extname(files[0]));
1213
+ const slug = files.length === 1
1214
+ ? sanitizeSlug("auto-" + toolName + "-" + firstBase)
1215
+ : sanitizeSlug("auto-" + toolName + "-" + files.length + "-files");
1216
+
1217
+ try {
1218
+ const snap = createBackupSnapshot({
1219
+ root: root,
1220
+ workspaceDir: workspaceDir,
1221
+ name: slug,
1222
+ tool: toolName,
1223
+ files: files,
1224
+ debounceMs: debounceMs,
1225
+ retentionDays: retentionDays
1226
+ });
1227
+ if (snap && typeof opts.onBackup === "function") {
1228
+ opts.onBackup(snap);
1229
+ }
1230
+ } catch {
1231
+ // Never block tool execution if backup encounters a transient filesystem lock
1232
+ }
1233
+ }
1234
+ });
1235
+ if (hookReg) registrations.push(hookReg);
1236
+ }
1237
+
1238
+ const toolTransform =
1239
+ ctx && ctx.tool
1240
+ ? typeof ctx.tool.transform === "function"
1241
+ ? ctx.tool.transform.bind(ctx.tool)
1242
+ : typeof ctx.tool.register === "function"
1243
+ ? ctx.tool.register.bind(ctx.tool)
1244
+ : null
1245
+ : null;
1246
+
1247
+ if (toolTransform) {
1248
+ const toolReg = await toolTransform(function (editor) {
1249
+ editor.add({
1250
+ name: "backup_list",
1251
+ description: "List recent automatic and manual file backup snapshots in .backups/ for the current project.",
1252
+ input: {
1253
+ type: "object",
1254
+ properties: {
1255
+ query: {
1256
+ type: "string",
1257
+ description: "Optional filename or slug filter"
1258
+ },
1259
+ limit: {
1260
+ type: "number",
1261
+ description: "Maximum entries to return (default: 20)"
1262
+ }
1263
+ },
1264
+ additionalProperties: false
1265
+ },
1266
+ execute: async function (input) {
1267
+ const all = listBackups(workspaceDir, { includeSubprojects: true });
1268
+ const q = String((input && input.query) || "").trim().toLowerCase();
1269
+ const filtered = q
1270
+ ? all.filter(function (item) {
1271
+ return (
1272
+ item.relativePath.toLowerCase().includes(q) ||
1273
+ item.snapshotId.toLowerCase().includes(q) ||
1274
+ item.slug.toLowerCase().includes(q)
1275
+ );
1276
+ })
1277
+ : all;
1278
+ const top = filtered.slice(0, (input && input.limit) || 20);
1279
+ if (top.length === 0) {
1280
+ return { content: "No backup snapshots found." };
1281
+ }
1282
+ const lines = top.map(function (item) {
1283
+ return (
1284
+ "[" +
1285
+ item.snapshotId +
1286
+ "] " +
1287
+ item.relativePath +
1288
+ " (" +
1289
+ item.size +
1290
+ " bytes, root: " +
1291
+ item.root +
1292
+ ")"
1293
+ );
1294
+ });
1295
+ return { content: lines.join("\n") };
1296
+ }
1297
+ });
1298
+
1299
+ editor.add({
1300
+ name: "backup_restore",
1301
+ description: "Restore a file from a .backups/ snapshot back to its original path (creates a pre-restore safety backup first).",
1302
+ input: {
1303
+ type: "object",
1304
+ properties: {
1305
+ snapshotId: {
1306
+ type: "string",
1307
+ description: "Snapshot folder name (e.g. 2026-10-25_12-30-00_auto-edit-index)"
1308
+ },
1309
+ relativePath: {
1310
+ type: "string",
1311
+ description: "Relative file path inside the snapshot"
1312
+ }
1313
+ },
1314
+ required: ["snapshotId"],
1315
+ additionalProperties: false
1316
+ },
1317
+ execute: async function (input) {
1318
+ const all = listBackups(workspaceDir, { includeSubprojects: true });
1319
+ const match = all.find(function (item) {
1320
+ if (item.snapshotId !== input.snapshotId) return false;
1321
+ if (input.relativePath && normalizeSlashes(input.relativePath) !== item.relativePath) return false;
1322
+ return true;
1323
+ });
1324
+ if (!match) {
1325
+ return { content: "Snapshot entry not found: " + input.snapshotId };
1326
+ }
1327
+ const res = restoreBackupFile(match);
1328
+ return {
1329
+ content:
1330
+ "Restored " +
1331
+ res.restoredPath +
1332
+ " from " +
1333
+ res.fromSnapshot +
1334
+ (res.safetySnapshot ? " (safety backup: " + res.safetySnapshot + ")" : "")
1335
+ };
1336
+ }
1337
+ });
1338
+ });
1339
+ if (toolReg) registrations.push(toolReg);
1340
+ }
1341
+
1342
+ return async function () {
1343
+ for (const reg of registrations) {
1344
+ if (reg && typeof reg.dispose === "function") {
1345
+ await reg.dispose();
1346
+ }
1347
+ }
1348
+ };
1349
+ }
1350
+ };
1351
+ }
1352
+
1353
+ const server = createPluginDefinition();
1354
+ export default server;
1355
+ export {
1356
+ server,
1357
+ resolveConfigDir,
1358
+ getSettingsFilePath,
1359
+ readBackupSettings,
1360
+ writeBackupSettings,
1361
+ resolveRetentionDays,
1362
+ resolveScanRootDir,
1363
+ installPlugin,
1364
+ resolveProjectRoot,
1365
+ extractPatchedPaths,
1366
+ extractTargetFiles,
1367
+ formatTimestamp,
1368
+ sanitizeSlug,
1369
+ parseFolderTimestamp,
1370
+ pruneOldBackups,
1371
+ createBackupSnapshot,
1372
+ listBackups,
1373
+ computeUnifiedDiff,
1374
+ restoreBackupFile,
1375
+ openBackupFile,
1376
+ openBackupDiff
1377
+ };
1378
+
1379
+ const isDirectRun = process.argv[1] && path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url));
1380
+ if (isDirectRun) {
1381
+ const cmd = process.argv[2] || "install";
1382
+
1383
+ if (cmd === "install" || cmd === "init" || cmd === "setup") {
1384
+ let customConfigDir = "";
1385
+ for (let i = 3; i < process.argv.length; i++) {
1386
+ if ((process.argv[i] === "--dir" || process.argv[i] === "-d") && process.argv[i + 1]) {
1387
+ customConfigDir = process.argv[i + 1];
1388
+ i++;
1389
+ }
1390
+ }
1391
+ installPlugin({ configDir: customConfigDir || undefined }).then(function (res) {
1392
+ const settingsInfo = writeBackupSettings({}, customConfigDir || undefined);
1393
+ console.log("opencode-local-backup installed:");
1394
+ console.log(" Server config: " + res.serverConfigFile + " (" + res.serverStatus + ")");
1395
+ console.log(" TUI config: " + res.cliConfigFile + " (" + res.cliStatus + ")");
1396
+ console.log(" Settings file: " + settingsInfo.filePath + " (retentionDays=" + settingsInfo.settings.retentionDays + ")");
1397
+ }).catch(function (err) {
1398
+ console.error("Install failed:", err);
1399
+ process.exit(1);
1400
+ });
1401
+ } else if (cmd === "retention" || cmd === "config") {
1402
+ const rawDays = process.argv[3];
1403
+ if (rawDays === undefined) {
1404
+ const s = readBackupSettings();
1405
+ const label = s.retentionDays === 0 ? "0 (never auto-prune)" : s.retentionDays + " days";
1406
+ console.log("Current auto-prune retention: " + label + " (" + getSettingsFilePath() + ")");
1407
+ } else {
1408
+ const days = Math.max(0, Math.floor(Number(rawDays)));
1409
+ if (Number.isNaN(days)) {
1410
+ console.error("Invalid number of days: " + rawDays);
1411
+ process.exit(1);
1412
+ }
1413
+ const res = writeBackupSettings({ retentionDays: days });
1414
+ const label = res.settings.retentionDays === 0 ? "0 (never auto-prune)" : res.settings.retentionDays + " days";
1415
+ console.log("Updated auto-prune retention to " + label + " in " + res.filePath);
1416
+ }
1417
+ } else if (cmd === "root") {
1418
+ const rawRoot = process.argv[3];
1419
+ if (rawRoot === undefined) {
1420
+ const s = readBackupSettings();
1421
+ const label = s.rootDir ? s.rootDir : "(auto-detect workspace root)";
1422
+ console.log("Current backup scan rootDir: " + label + " (" + getSettingsFilePath() + ")");
1423
+ } else if (rawRoot === "--clear" || rawRoot === "auto") {
1424
+ const res = writeBackupSettings({ rootDir: "" });
1425
+ console.log("Cleared rootDir (using auto-detect) in " + res.filePath);
1426
+ } else {
1427
+ const resolved = path.resolve(rawRoot);
1428
+ const res = writeBackupSettings({ rootDir: resolved });
1429
+ console.log("Updated backup scan rootDir to " + res.settings.rootDir + " in " + res.filePath);
1430
+ }
1431
+ } else if (cmd === "list") {
1432
+ const dir = process.argv[3] || process.cwd();
1433
+ const entries = listBackups(dir, { includeSubprojects: true, limit: 30 });
1434
+ if (entries.length === 0) {
1435
+ console.log("No backups found in " + dir);
1436
+ } else {
1437
+ for (const e of entries) {
1438
+ console.log("[" + e.snapshotId + "] " + e.relativePath + " (" + e.size + " B)");
1439
+ }
1440
+ }
1441
+ } else if (cmd === "backup") {
1442
+ const slug = process.argv[3] || "manual";
1443
+ const files = process.argv.slice(4);
1444
+ const snap = createBackupSnapshot({
1445
+ name: slug,
1446
+ tool: "cli",
1447
+ files: files,
1448
+ force: true
1449
+ });
1450
+ if (snap) {
1451
+ console.log("Backed up " + snap.files.length + " file(s) to " + snap.snapshotDir);
1452
+ } else {
1453
+ console.log("No existing files matched to back up.");
1454
+ }
1455
+ } else if (cmd === "prune") {
1456
+ const dir = process.argv[3] || process.cwd();
1457
+ const rawDays = process.argv[4];
1458
+ const days = rawDays !== undefined ? Number(rawDays) : resolveRetentionDays();
1459
+ const res = pruneOldBackups(dir, days);
1460
+ if (res.disabled) {
1461
+ console.log("Auto-prune is disabled (retentionDays = 0). Pass an explicit day count to prune manually.");
1462
+ } else {
1463
+ console.log("Pruned " + res.removed + " snapshot(s) older than " + res.retentionDays + " days in " + res.backupsDir);
1464
+ }
1465
+ }
1466
+ }