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

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Fernando Blanco
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,342 @@
1
- # Temporary Holding Version
1
+ # opencode-local-backup
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Local-first, automatic pre-edit file backup plugin for OpenCode**: snapshots files automatically in the engine pipeline before any edit tool runs, with zero token usage, smart project-root resolution, retention auto-pruning, and an interactive `/backups` diff and restore TUI popup.
4
+
5
+ ![opencode-local-backup TUI preview](./assets/screenshot.png)
6
+
7
+ ## Background
8
+
9
+ This plugin started as a PowerShell script (`backup.ps1`) paired with a rule in `AGENTS.md` instructing the model to run a shell backup command before editing any file. In daily use, that approach had three drawbacks:
10
+
11
+ 1. **Every backup cost a tool call and model tokens**: The agent had to remember the rule, invoke the shell tool before editing, and wait for a child process to spawn.
12
+ 2. **Prompt rules can be skipped after context compaction**: If the model forgot the instruction on a long turn, the file was edited without a snapshot.
13
+ 3. **Subfolder pollution**: Passing a file's parent directory created `.backups/` folders inside nested subdirectories (`src/components/.backups/`, `api/.backups/`) instead of keeping all snapshots at the project root.
14
+
15
+ `opencode-local-backup` moves pre-edit backups into OpenCode's tool execution pipeline:
16
+
17
+ 1. **Engine-level `execute.before` hook**: Intercepts `edit`, `write`, `patch`, `apply_patch`, and `multiedit` calls in pure Node.js before the tool touches disk, with zero prompt rules or LLM tokens.
18
+ 2. **Smart project-root resolution**: Walks upward from the target file to the nearest project root marker so every snapshot lands in `<project-root>/.backups/`.
19
+ 3. **Zero-token `/backups` TUI modal**: Filter snapshots, inspect a live hunk diff against the current file on disk, open a full side-by-side diff in VS Code, adjust auto-prune retention, and restore files with `Enter`.
20
+
21
+ ## Features
22
+
23
+ | Feature | Details |
24
+ | :--- | :--- |
25
+ | Engine-level `execute.before` hook | Automatically snapshots existing files before `edit`, `write`, `patch`, `apply_patch`, or `multiedit` tool calls run |
26
+ | Local-first, zero-token execution | Pure local Node.js filesystem snapshots and TUI diff/restore with zero LLM token usage, zero prompt rules, and zero cloud dependencies |
27
+ | Smart project-root resolution | Walks upward to find `.git`, `package.json`, `composer.json`, `Cargo.toml`, `pyproject.toml`, `go.mod`, `.opencode`, `AGENTS.md`, `opencode.jsonc`, or `opencode.json` so all backups stay in `<project-root>/.backups/` instead of polluting nested subfolders |
28
+ | Preserved relative paths | Stores `<project-root>/.backups/<YYYY-MM-DD_HH-mm-ss>_<slug>/<relative-path>` plus `.backup-meta.json` |
29
+ | Multi-file patch support | Extracts every `*** Update File:`, `*** Delete File:`, and `*** Move File:` entry in a patch |
30
+ | Interactive `/backups` TUI modal | Wide (`80%` default, configurable via `dialogWidth`) split-pane browser with colored filter pills (`^t` tool, `^g` date, `^r` retention, `^d` prune), parent backup path under each item, hunk-filtered unified diff preview with line numbers, and a 3-option `Enter` action popup (**[1] Restore file**, **[2] Open backup file**, or **[3] Open diff in editor**) |
31
+ | Instant hunk diff + external editor diff | Right-hand pane immediately renders changed hunks (`±3` context lines + line numbers), while action `[3]` (`D`) launches `code --diff <backup> <current>` (or `$OPENCODE_BACKUP_DIFF_CMD`) for a full side-by-side comparison |
32
+ | Unlimited workspace discovery (`rootDir`) | Scans all `.backups/` folders across your workspace with no depth cap (`Infinity`) and no snapshot count cap, configurable via `rootDir` in `~/.config/opencode/auto-backup.json` or automatic workspace-root detection |
33
+ | Pre-restore safety snapshot | Restoring a file automatically backs up the current file on disk first (`pre-restore`) |
34
+ | Configurable auto-prune (`retentionDays`) | Defaults to `30` days; set to `5`, `7`, `14`, or `0` (never auto-prune) via `~/.config/opencode/auto-backup.json`, `/backups` (`Ctrl+R`), CLI, or plugin options |
35
+
36
+ ## Installation
37
+
38
+ ### Option 1: One-Command Install (Recommended)
39
+
40
+ Run the built-in installer to automatically register the server and TUI plugins in `~/.config/opencode/opencode.jsonc` and `~/.config/opencode/cli.json`:
41
+
42
+ ```sh
43
+ npx @nandoblanco/opencode-local-backup install
44
+ ```
45
+
46
+ Or set a custom workspace root directory for `.backups/` discovery during setup:
47
+
48
+ ```sh
49
+ npx @nandoblanco/opencode-local-backup root "C:\MAMPFiles"
50
+ ```
51
+
52
+ You can also install with OpenCode's native plugin CLI (because `package.json` exports both `.` and `./tui`, OpenCode loads both the server plugin and `/backups` TUI popup automatically):
53
+
54
+ ```sh
55
+ opencode plugin add @nandoblanco/opencode-local-backup
56
+ # or directly from GitHub:
57
+ opencode plugin add github:nandoblanco/opencode-local-backup
58
+ ```
59
+
60
+ ### Option 2: Manual Configuration
61
+
62
+ Add `@nandoblanco/opencode-local-backup` to `~/.config/opencode/opencode.jsonc` and `~/.config/opencode/cli.json`:
63
+
64
+ ```jsonc
65
+ {
66
+ "plugins": [
67
+ {
68
+ "package": "@nandoblanco/opencode-local-backup",
69
+ "options": {
70
+ "retentionDays": 30,
71
+ "debounceMs": 0,
72
+ "rootDir": "C:\\MAMPFiles",
73
+ "dialogWidth": "80%"
74
+ }
75
+ }
76
+ ]
77
+ }
78
+ ```
79
+
80
+ ### From a Local Directory
81
+
82
+ Clone this repository and run `node ./index.js install` (or reference `"file:///path/to/opencode-local-backup"` in `opencode.jsonc` and `cli.json`):
83
+
84
+ ```json
85
+ {
86
+ "plugins": ["file:///path/to/opencode-local-backup"]
87
+ }
88
+ ```
89
+
90
+ ## Usage
91
+
92
+ ### Automatic Pre-Edit Backups (Server Hook & Tools)
93
+
94
+ Once enabled, the plugin snapshots files automatically during normal coding sessions:
95
+
96
+ - **Automatic Pre-Edit Snapshots (`execute.before` hook)**: Before `edit`, `write`, `patch`, `apply_patch`, or `multiedit` modifies an existing file on disk, the plugin copies the unmodified file into `<project-root>/.backups/<YYYY-MM-DD_HH-mm-ss>_<slug>/<relative-path>`.
97
+ - **Agent Tools (`backup_list` & `backup_restore`)**: You can also ask the agent in chat to list or restore recent backups if needed.
98
+
99
+ ### Zero-Token TUI Commands
100
+
101
+ 1. **Interactive `/backups` popup**: Run `/backups` (aliases: `/backup`, `/restore`, `/snapshots`) or `/backups <query>` to open the split-pane snapshot browser.
102
+ 2. **Command palette**: Press `Ctrl+P` and select `Browse & restore file backups (0 tokens)...`.
103
+ 3. **Custom keybind**: Bind `auto.backup.browse` in `~/.config/opencode/cli.json` (the one-command installer binds `ctrl+alt+b` by default):
104
+
105
+ ```json
106
+ {
107
+ "keybinds": {
108
+ "auto.backup.browse": "ctrl+alt+b"
109
+ }
110
+ }
111
+ ```
112
+
113
+ ## TUI Query Syntax (`/backups`)
114
+
115
+ Type search terms in the search bar to filter across all discovered snapshots, or combine them with the interactive filter pills (`^t` tool, `^g` date, `^r` retention).
116
+
117
+ | Syntax | Description | Example |
118
+ | :--- | :--- | :--- |
119
+ | `term1 term2` | Multi-term AND substring match across relative file path, `.backups` folder path, original path, project root, snapshot ID, and slug | `butte index.html` |
120
+ | `<filename>` | Filter snapshots for a specific file name or extension | `tui.ts` |
121
+ | `<project-folder>` | Filter snapshots belonging to a specific project or client subfolder | `winnipeg` |
122
+ | `auto-edit` / `pre-restore` | Filter snapshots by slug or tool prefix (or press `Ctrl+T` to cycle the `tool:` pill) | `pre-restore` |
123
+
124
+ ## Keyboard Shortcuts (`/backups`)
125
+
126
+ | Key | Action |
127
+ | :--- | :--- |
128
+ | `Enter` | Open the 3-option Action Popup for the selected snapshot: **[1] Restore file**, **[2] Open backup file**, or **[3] Open diff in editor** |
129
+ | `1` / `R` *(in action popup)* | Restore selected snapshot to disk (creates a `pre-restore` safety backup first) |
130
+ | `2` / `O` *(in action popup)* | Open the snapshot file in your default OS editor (or `$OPENCODE_BACKUP_EDITOR` / `$VISUAL` / `$EDITOR`) |
131
+ | `3` / `D` *(in action popup)* | Open a side-by-side diff (`backup` vs `current` on disk) in VS Code (`code --diff`) or `$OPENCODE_BACKUP_DIFF_CMD` |
132
+ | `Up` / `Down` or `Ctrl+K` / `Ctrl+J` | Select snapshot (or scroll diff by 2 lines when Preview pane is focused; `j`/`k` also work in List and Preview panes) |
133
+ | `PageUp` / `PageDown` | Jump 6 snapshots up/down (or scroll diff by 8 lines in Preview pane) |
134
+ | `Tab` / `Shift+Tab` | Switch focus between Search Input, Snapshots List, and Diff Preview Pane |
135
+ | `Ctrl+T` | Cycle tool filter pill (`all` -> `edit` -> `write` -> `patch` -> `pre-restore`) |
136
+ | `Ctrl+G` | Cycle date filter pill (`all` -> `24h` -> `7d` -> `30d`) |
137
+ | `Ctrl+R` | Cycle auto-prune retention pill (`30d` -> `14d` -> `7d` -> `5d` -> `0d (Never)`) |
138
+ | `Ctrl+D` | Prune snapshots older than current `retentionDays` |
139
+ | `Ctrl+U` | Clear the active search query and reset tool/date filters |
140
+ | `Esc` | Close action popup or modal |
141
+
142
+ ## How It Works (Architecture & Internals)
143
+
144
+ ### 1. Pre-Edit Interception & Target File Extraction (`execute.before` & `extractTargetFiles`)
145
+
146
+ During server plugin setup (`createPluginDefinition()`), `ctx.tool.hook("execute.before")` registers a synchronous-fast listener that checks `event.tool` against `EDIT_TOOLS`:
147
+
148
+ ```js
149
+ const EDIT_TOOLS = new Set(["edit", "write", "patch", "apply_patch", "multiedit"]);
150
+ ```
151
+
152
+ When one of those tools is about to run, `extractTargetFiles(toolName, event.input, workspaceDir)` normalizes and deduplicates every target file path across OpenCode's different tool schemas:
153
+
154
+ - **Single-file fields**: `input.filePath` and `input.path`
155
+ - **Multi-file arrays**: `input.files[]` and `input.edits[]` (accepting raw path strings or objects with `.filePath` / `.path`)
156
+ - **Unified patch payloads**: `input.patchText` and `input.patch`, parsed by `extractPatchedPaths()` using `/^\*\*\*\s+(?:Update|Delete|Move)\s+File:\s*(.+)$/gm` so every updated, deleted, or moved file in a multi-file patch is captured before the patch applies
157
+
158
+ Only files that already exist on disk (`fs.existsSync(abs)` and `st.isFile()`) are snapshotted. Newly created files are ignored, and the entire backup call is wrapped in a `try / catch` so a transient filesystem lock never blocks tool execution.
159
+
160
+ ### 2. Smart Project-Root Resolution (`resolveProjectRoot`)
161
+
162
+ Rather than placing `.backups/` inside the edited file's immediate parent folder, `resolveProjectRoot(filePath, workspaceDir)` walks upward from `path.dirname(absFile)` toward `workspaceDir`:
163
+
164
+ 1. At each directory level, it checks `PROJECT_MARKERS` in order:
165
+ ```js
166
+ const PROJECT_MARKERS = [
167
+ ".git",
168
+ "package.json",
169
+ "composer.json",
170
+ "Cargo.toml",
171
+ "pyproject.toml",
172
+ "go.mod",
173
+ ".opencode",
174
+ "AGENTS.md",
175
+ "opencode.jsonc",
176
+ "opencode.json",
177
+ ];
178
+ ```
179
+ 2. As soon as a directory contains any marker in `PROJECT_MARKERS`, that directory is selected as the project root (`<project-root>/.backups/`).
180
+ 3. **Workspace boundary guard (`isSubPath`)**: The upward walk stops if it reaches `workspaceDir` or if the next parent directory would step outside `workspaceDir`, preventing stray `.backups/` folders in parent directories above the active workspace.
181
+ 4. **Monorepo grouping**: If a single multi-file patch or `multiedit` call touches files across multiple subprojects, the `execute.before` hook groups the target files by their resolved root (`byRoot` map) and writes one snapshot per subproject root.
182
+
183
+ ### 3. Snapshot Layout, Relative Paths & Per-File Debouncing (`createBackupSnapshot`)
184
+
185
+ For each resolved root, `createBackupSnapshot()` builds a timestamped snapshot folder `<YYYY-MM-DD_HH-mm-ss>_<slug>`:
186
+
187
+ - **Slug naming**: Single-file hook backups use `auto-<tool>-<basename>` (for example, `2026-10-26_14-22-05_auto-edit-index`), while multi-file hook backups use `auto-<tool>-<N>-files` (`2026-10-26_14-22-05_auto-apply-patch-3-files`). If another snapshot occurred within the same second, it appends `-2`, `-3`, etc.
188
+ - **Preserved relative tree**: Each file's path relative to `rootDir` (`path.relative(rootDir, absFile)`) is recreated inside the snapshot folder (`<project-root>/.backups/<snapshotId>/src/components/Button.tsx`) and copied with `fs.copyFileSync()`.
189
+ - **Per-file debounce (`lastFileBackupMap`)**: An in-memory `Map<absFilePath, timestampMs>` tracks when each file was last backed up. When `debounceMs > 0` and `force` is not set, edits to the same file within `debounceMs` skip creating redundant snapshots. Manual CLI backups and `pre-restore` snapshots pass `force: true` to bypass debounce.
190
+ - **Metadata manifest (`.backup-meta.json`)**: Writes a JSON manifest alongside the copied files recording the snapshot `id`, ISO `timestamp`, epoch `timeMs`, `slug`, `tool`, `root`, and the `files[]` array (`relativePath`, `originalPath`, `size`, `mtimeMs`).
191
+
192
+ ### 4. Throttled Auto-Pruning & Settings Precedence (`pruneOldBackups` & `resolveRetentionDays`)
193
+
194
+ `resolveRetentionDays()` determines the active retention window using a three-step precedence order:
195
+
196
+ 1. Explicit `retentionDays` option passed to the plugin in `opencode.jsonc` or CLI argument
197
+ 2. `OPENCODE_BACKUP_RETENTION_DAYS` environment variable
198
+ 3. Persistent settings file `~/.config/opencode/auto-backup.json` (or `$XDG_CONFIG_HOME/opencode/auto-backup.json`), read and updated via `readBackupSettings()` and `writeBackupSettings()` (defaults to `{ "retentionDays": 30, "debounceMs": 0 }`)
199
+
200
+ To avoid scanning `.backups/` on every edit, `createBackupSnapshot()` throttles automatic pruning per project root using `lastRootPruneMap` and `PRUNE_INTERVAL_MS` (`10 * 60 * 1000`, or once every 10 minutes per root).
201
+
202
+ When pruning runs (`pruneOldBackups(rootDir, retentionDays)`):
203
+
204
+ - If `retentionDays <= 0`, auto-pruning is disabled (`disabled: true`) and all snapshots are kept indefinitely.
205
+ - Otherwise, it computes `cutoffMs = Date.now() - days * 86400000` and inspects each subdirectory in `.backups/`.
206
+ - Snapshot age is parsed directly from the folder name prefix via `parseFolderTimestamp()` (`/^(\d{4})-(\d{2})-(\d{2})_(\d{2})-(\d{2})-(\d{2})_(.+)$/`), falling back to `fs.statSync(fullDir).mtimeMs` for custom folder names, and expired folders are removed with `fs.rmSync(fullDir, { recursive: true, force: true })`.
207
+
208
+ ### 5. Multi-Root Discovery, Hunk-Filtered Unified Diff, Safe Restore & Editor Launch (`listBackups`, `computeUnifiedDiff`, `restoreBackupFile`, `openBackupFile`, `openBackupDiff`)
209
+
210
+ 1. **Workspace & subproject discovery (`resolveScanRootDir`, `resolveTopWorkspaceRoot`, `collectBackupRoots`, `listBackups`)**:
211
+ - Determines the starting scan root via `resolveScanRootDir()`: checks `OPENCODE_BACKUP_ROOT_DIR`, then `rootDir` in `~/.config/opencode/auto-backup.json`, and otherwise walks upward (`resolveTopWorkspaceRoot`) to the highest workspace ancestor containing `.backups`, `AGENTS.md`, or `.opencode`.
212
+ - When `includeSubprojects: true` is enabled (used by `/backups` and `backup_list`), recursively scans from the scan root with no depth cap (`Infinity` by default, while skipping `node_modules`, `.git`, `.screenshots`, `xampp`, `vendor`, `.next`, `dist`, `build`, `.cache`, `bower_components`, and dot-directories) and no default snapshot count limit (`limit: 0`) so every `.backups/` folder across deeply nested client and project directories is indexed.
213
+ - Reads `.backup-meta.json` when present and falls back to `walkSnapshotFiles()` so snapshots created by older scripts without `.backup-meta.json` still appear in `/backups`.
214
+ 2. **Zero-dependency hunk-filtered unified diff (`computeUnifiedDiff`)**:
215
+ - Compares the backup file against the live file on disk (`originalPath`) and classifies the state as `identical`, `modified`, `deleted` (file was removed from disk after the backup), `binary`, or `missing-backup`.
216
+ - For modified files, runs a 25-line lookahead window (`for (let look = 1; look <= 25; look++)`) comparing `oldLines` (current file on disk) and `newLines` (backup snapshot) to produce a full `rawOps` stream (`same`, `add`, `del`) with 1-based line numbers (`oldLine`, `newLine`).
217
+ - Instead of emitting unchanged lines from line 1 of the file, `computeUnifiedDiff` marks only changed indices (`add` / `del`) plus a `±3` line context window (`contextLines = 3`), inserting `@@ current line X / backup line Y @@` hunk headers between non-contiguous change regions and formatting each line with its padded line number (` 42 │ ...`, `+ 42 │ ...`, `- 42 │ ...`).
218
+ 3. **Pre-restore safety backup (`restoreBackupFile`)**:
219
+ - Before copying the selected backup file back to `originalPath`, `restoreBackupFile()` checks whether `targetPath` currently exists on disk and automatically creates a `pre-restore` snapshot (`tool: "restore", force: true`). If you restore the wrong snapshot, the state from right before the restore is immediately available at the top of `/backups`.
220
+ 4. **Open backup file in external editor (`openBackupFile`)**:
221
+ - Launches the raw snapshot file from `.backups/` as a detached process using `OPENCODE_BACKUP_EDITOR`, `$VISUAL`, or `$EDITOR` when set, or falls back to the OS default file handler (`cmd /c start ""` on Windows, `open` on macOS, `xdg-open` on Linux).
222
+ 5. **Open side-by-side diff in external editor (`openBackupDiff`)**:
223
+ - Launches a side-by-side comparison of `backupFilePath` vs `currentFilePath` as a detached process using `OPENCODE_BACKUP_DIFF_CMD` when configured, or `code --diff <backup> <current>` (VS Code) by default (`cmd /c code --diff ...` on Windows).
224
+
225
+ ### 6. Interactive OpenTUI `/backups` Modal Architecture (`tui.ts`)
226
+
227
+ 1. **Wide modal layout (`applyDialogWidth` & `dialog.set`)**:
228
+ - Calls `context.ui.dialog.show(...)` followed by `context.ui.dialog.set({ size: "xlarge", centered: true })` (calling `dialog.set` after `dialog.show` prevents `dialog.show` from resetting the dialog size to default).
229
+ - Inside `onMount` and `createEffect`, `applyDialogWidth()` walks upward from `rootRef` to the outer `absolute`-positioned dialog container to set `width: "80%"` (or your configured `dialogWidth`), `maxWidth: "80%"`, and `minWidth: 76`.
230
+ 2. **Filter pills & multi-pane navigation**:
231
+ - Renders interactive `Pill` components beneath the search input for `tool:<filter>` (`^t`), `date:<filter>` (`^g`), `prune:<days>` (`^r`), and `prune now` (`^d`), clickable by mouse or keyboard shortcut.
232
+ - Splits the main body into a 44%-width left snapshot list (showing `relativePath`, colored `[tool]` badge, relative age, and `↳ <project>/.backups/<snapshotId>` parent path) and a 56%-width right preview pane (left-bordered metadata card + syntax-colored hunk diff lines with search-term highlighting).
233
+ 3. **`@opentui/solid` `Show` isolation for the 3-option Action Popup**:
234
+ - Pressing `Enter` on a snapshot opens the inline Action Confirmation Sub-Popup (`[1] Restore file`, `[2] Open backup file`, `[3] Open diff in editor`).
235
+ - In `@opentui/solid`, placing a reactive `createComponent(Show, ...)` directly inside a multi-child parent via `insert(node, child)` (without a marker node) causes `cleanChildren()` to clear all sibling children when `Show` transitions from `true` back to `false`. Wrapping `Show` inside its own dedicated single-child container `el("box", { flexDirection: "column", flexShrink: 0 }, createComponent(Show, ...))` ensures closing the sub-popup only clears that inner wrapper box.
236
+
237
+ ### 7. Agent Tools Registered by the Server Plugin
238
+
239
+ | Tool Name | Required Inputs | Optional Inputs | Behavior |
240
+ | :--- | :--- | :--- | :--- |
241
+ | `backup_list` | *(none)* | `query`, `limit` (default `20`) | Scans the workspace and subprojects (`includeSubprojects: true`), filters by `relativePath`, `snapshotId`, or `slug`, and returns matching entries sorted newest-first. |
242
+ | `backup_restore` | `snapshotId` | `relativePath` | Creates a `pre-restore` safety snapshot of the current file on disk, then copies the snapshot file back to its original path. |
243
+
244
+ ### 8. Token Usage Breakdown
245
+
246
+ Normal backup, diff preview, and restore operations use zero LLM tokens:
247
+
248
+ | Operation | Token Cost | Why |
249
+ | :--- | :--- | :--- |
250
+ | Automatic pre-edit backups (`execute.before` hook) | **0 tokens** | Runs in plain Node.js inside OpenCode before `edit`, `write`, `patch`, `apply_patch`, or `multiedit` touches disk; injects no system prompt rules and appends nothing to chat |
251
+ | Interactive `/backups` TUI modal (`Ctrl+Alt+B`) | **0 tokens** | Filtering snapshots, computing hunk diffs (`computeUnifiedDiff`), restoring files (`1`), opening files/diffs (`2`/`3`), cycling retention (`Ctrl+R`), and pruning (`Ctrl+D`) run directly on disk without an LLM request |
252
+ | Standalone CLI (`npx @nandoblanco/opencode-local-backup ...`) | **0 tokens** | Runs directly in Node.js outside the model turn |
253
+ | Agent tools (`backup_list`, `backup_restore`) | **~120 schema tokens** (+ turn tokens only if called) | Tool definitions are registered with the server so you can ask the agent to list or restore a snapshot in chat; using `/backups` instead avoids calling these tools |
254
+
255
+ ## Directory Structure
256
+
257
+ ```text
258
+ <project-root>/
259
+ └── .backups/
260
+ ├── 2026-10-26_14-22-05_auto-edit-index/
261
+ │ ├── .backup-meta.json
262
+ │ └── src/
263
+ │ └── index.js
264
+ └── 2026-10-26_14-35-12_pre-restore/
265
+ ├── .backup-meta.json
266
+ └── src/
267
+ └── index.js
268
+ ```
269
+
270
+ Each snapshot's `.backup-meta.json` stores the file manifest used by `/backups` and `backup_list`:
271
+
272
+ ```json
273
+ {
274
+ "id": "2026-10-26_14-22-05_auto-edit-index",
275
+ "timestamp": "2026-10-26T19:22:05.118Z",
276
+ "timeMs": 1793052125118,
277
+ "slug": "auto-edit-index",
278
+ "tool": "edit",
279
+ "root": "/path/to/project",
280
+ "files": [
281
+ {
282
+ "relativePath": "src/index.js",
283
+ "originalPath": "/path/to/project/src/index.js",
284
+ "size": 4820,
285
+ "mtimeMs": 1793051900412.5
286
+ }
287
+ ]
288
+ }
289
+ ```
290
+
291
+ ## CLI Commands
292
+
293
+ ```sh
294
+ # Install into OpenCode server + TUI config
295
+ npx @nandoblanco/opencode-local-backup install
296
+
297
+ # List recent backups in the current project
298
+ npx @nandoblanco/opencode-local-backup list
299
+
300
+ # Create a manual snapshot of specific files
301
+ npx @nandoblanco/opencode-local-backup backup my-change-slug src/index.js src/config.js
302
+
303
+ # View or set auto-prune retention days (0 = never auto-prune, default = 30)
304
+ npx @nandoblanco/opencode-local-backup retention
305
+ npx @nandoblanco/opencode-local-backup retention 5
306
+ npx @nandoblanco/opencode-local-backup retention 0
307
+
308
+ # View, set, or clear the starting root directory for scanning .backups/ folders
309
+ npx @nandoblanco/opencode-local-backup root
310
+ npx @nandoblanco/opencode-local-backup root "C:\MAMPFiles"
311
+ npx @nandoblanco/opencode-local-backup root --clear
312
+
313
+ # Prune snapshots older than 30 days
314
+ npx @nandoblanco/opencode-local-backup prune . 30
315
+ ```
316
+
317
+ ## Configuration Options
318
+
319
+ Settings are stored in `~/.config/opencode/auto-backup.json` (created automatically with `"retentionDays": 30, "debounceMs": 0, "rootDir": "", "dialogWidth": "80%"`) and can also be passed via `opencode.jsonc` / `cli.json` plugin options or environment variables:
320
+
321
+ ```json
322
+ {
323
+ "retentionDays": 30,
324
+ "debounceMs": 0,
325
+ "rootDir": "C:\\MAMPFiles",
326
+ "dialogWidth": "80%"
327
+ }
328
+ ```
329
+
330
+ | Option | Env Variable | Default | Description |
331
+ | :--- | :--- | :--- | :--- |
332
+ | `retentionDays` | `OPENCODE_BACKUP_RETENTION_DAYS` | `30` | Days to keep backup snapshots before auto-pruning (`0` = never auto-prune) |
333
+ | `debounceMs` | `OPENCODE_BACKUP_DEBOUNCE_MS` | `0` | Minimum milliseconds between automatic snapshots of the same file (`0` = every single edit) |
334
+ | `rootDir` | `OPENCODE_BACKUP_ROOT_DIR` | `""` *(auto-detect)* | Starting root directory for discovering all `.backups/` folders across subprojects (`npx @nandoblanco/opencode-local-backup root <path>`) |
335
+ | `backupRoot` | `OPENCODE_BACKUP_ROOT` | *(auto)* | Optional fixed destination directory where new `.backups/` snapshots are written instead of per-project root detection |
336
+ | `dialogWidth` | `OPENCODE_BACKUP_DIALOG_WIDTH` | `"80%"` | Width of the centered `/backups` TUI modal (`"80%"` or column count like `120`; also respects `OPENCODE_DIALOG_WIDTH`) |
337
+ | *(editor)* | `OPENCODE_BACKUP_EDITOR` | `$VISUAL` / `$EDITOR` / OS default | Command used when choosing **[2] Open backup file** in the `/backups` action popup |
338
+ | *(diff cmd)* | `OPENCODE_BACKUP_DIFF_CMD` | `code --diff` | Command used when choosing **[3] Open diff in editor** (`backup` vs `current` on disk) |
339
+
340
+ ## License
341
+
342
+ MIT
Binary file