opencode-manager 0.3.1 → 0.4.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.
@@ -5,15 +5,47 @@ Overview
5
5
  --------
6
6
  - Purpose: Inspect, filter, and clean OpenCode metadata stored on disk.
7
7
  - Scope: Lists projects and sessions from local storage; supports filtering, search, interactive selection and deletion, and quick navigation between views.
8
- - UI: Terminal UI built with @opentui/react.
8
+ - Dual interface: Terminal UI (TUI) built with @opentui/react for interactive use, plus a Commander-based CLI for scripting and automation.
9
9
 
10
10
  Architecture
11
11
  ------------
12
- - Entry: `opencode/src/opencode-tui.tsx` main TUI app and panels.
13
- - Data layer: `opencode/src/lib/opencode-data.ts` — reads/writes metadata JSON, computes derived fields, formatting helpers.
14
- - Scripts: `opencode/package.json` → `bun run tui` runs the app.
15
- - CLI wrapper: `opencode/manage_opencode_projects.py` preserves the legacy entry point, resolves Bun (`--bun` overrides PATH), sets `--root` (defaults to `~/.local/share/opencode`), and forwards any extra args after `--` directly to the TUI.
16
- - Spec diff script: `opencode/opencode-gen.sh` shells out to `opencode generate`, saves the JSON spec under `~/repos/research/opencode/opencode-<version>-spec.json`, and diffs it against the previous snapshot (prefers `delta`, falls back to `diff`).
12
+ The codebase follows a dual-mode architecture with shared libraries:
13
+
14
+ ### Entry Points
15
+ - `src/bin/opencode-manager.ts` Main entrypoint; routes to CLI or TUI based on subcommand.
16
+ - CLI subcommands: `projects`, `sessions`, `chat`, `tokens` dynamic import of CLI module
17
+ - TUI mode: no subcommand, or explicit `tui` subcommand → dynamic import of TUI module
18
+
19
+ ### CLI Module (`src/cli/`)
20
+ - `index.ts` — Commander program with global options (`--root`, `--format`, `--limit`, `--sort`, `--yes`, `--dry-run`, `--quiet`, `--clipboard`, `--backup-dir`); exports `runCLI(args)`.
21
+ - `commands/` — Subcommand implementations:
22
+ - `projects.ts` — `list`, `delete` with dry-run/backup support
23
+ - `sessions.ts` — `list`, `delete`, `rename`, `move`, `copy`
24
+ - `chat.ts` — `list`, `show`, `search` with clipboard support
25
+ - `tokens.ts` — `session`, `project`, `global` token summaries
26
+ - `tui.ts` — Launches TUI from CLI context
27
+ - `formatters/` — Output formatters:
28
+ - `json.ts` — JSON with envelope (`{ok, data, meta}`)
29
+ - `ndjson.ts` — Newline-delimited JSON for streaming
30
+ - `table.ts` — Column-aligned tables with truncation
31
+ - `output.ts` — Format selector routing by `--format` flag
32
+ - `errors.ts` — Exit codes (0-4), error classes, validation helpers
33
+ - `resolvers.ts` — ID resolution with exact/prefix matching
34
+ - `backup.ts` — Pre-deletion backup to timestamped directories
35
+
36
+ ### TUI Module (`src/tui/`)
37
+ - `app.tsx` — Main TUI app with Projects, Sessions, Chat panels
38
+ - `index.tsx` — Exports `launchTUI(options)`, `bootstrap(args)`
39
+ - `args.ts` — TUI-specific arg parsing (`--root`, `--help`)
40
+
41
+ ### Shared Libraries (`src/lib/`)
42
+ - `opencode-data.ts` — Data layer: load/save metadata, compute tokens, filtering, formatting
43
+ - `search.ts` — Fuzzy search via fast-fuzzy (sessions) and tokenized search (projects)
44
+ - `clipboard.ts` — Cross-platform clipboard (`pbcopy`/`xclip`)
45
+
46
+ ### Other Files
47
+ - `manage_opencode_projects.py` — Legacy wrapper; routes CLI/TUI via `src/bin/opencode-manager.ts`
48
+ - `opencode-gen.sh` — Spec diff script for OpenCode JSON specs
17
49
 
18
50
  Metadata Layout & Helpers
19
51
  -------------------------
@@ -37,6 +69,8 @@ Key Features
37
69
  - Rename sessions inline (Shift+R) with validation.
38
70
  - Move sessions to another project (M) with project selector.
39
71
  - Copy sessions to another project (P) with new session ID generation.
72
+ - View chat history (V) with message navigation and clipboard support.
73
+ - Search chat content (F) across sessions with fuzzy matching.
40
74
  - Projects ↔ Sessions workflow
41
75
  - Pressing Enter on a project jumps to the Sessions tab with the project filter set; status text confirms the active filter.
42
76
  - `C` clears the filter (and notifies the user) so global searches go back to all sessions.
@@ -53,6 +87,7 @@ Key Features
53
87
 
54
88
  Work Completed
55
89
  --------------
90
+ ### TUI Features
56
91
  - Switched Projects list labels to show path instead of project ID; kept ID in the details panel.
57
92
  - Sessions list uses session title prominently; added title to details; updated onSelect/Enter status lines to show title and ID.
58
93
  - Redesigned Help screen into two columns with color-coded sections and key chips; removed wall-of-text effect.
@@ -69,36 +104,79 @@ Work Completed
69
104
  - Added session move feature (M): select target project, relocate session JSON, update projectID field.
70
105
  - Added session copy feature (P): select target project, create new session with generated ID, preserve original.
71
106
 
107
+ ### CLI Implementation (Phase 1-4)
108
+ - Created Commander-based CLI with global options and subcommand routing.
109
+ - Refactored entrypoint to route CLI vs TUI via dynamic imports.
110
+ - Extracted shared libraries (`clipboard.ts`, `search.ts`) from TUI for CLI reuse.
111
+ - Implemented output formatters: JSON with envelope, NDJSON for streaming, table with truncation.
112
+ - Projects commands: `list` (with `--missing-only`, `--search`), `delete` (with `--dry-run`, `--backup-dir`).
113
+ - Sessions commands: `list` (with `--project`, `--search`, fuzzy matching), `delete`, `rename`, `move`, `copy`.
114
+ - Chat commands: `list` (with `--include-parts`), `show` (by `--message` or `--index`, with `--clipboard`), `search`.
115
+ - Tokens commands: `session`, `project`, `global` summaries with breakdown tables.
116
+ - Error handling with typed exit codes (0-4) and consistent error formatting.
117
+ - ID resolution helpers with exact and prefix matching.
118
+ - Pre-deletion backup to timestamped directories.
119
+ - Comprehensive test suite: 350+ tests covering formatters, commands, resolvers, errors, exit codes.
120
+
72
121
  How To Run
73
122
  ----------
74
- - Zero-install via npm: `bunx opencode-manager [--root /path/to/storage]` (preferred).
75
- - Local dev: `bun run tui [-- --root /path/to/storage]`.
76
- - Legacy launcher: `./manage_opencode_projects.py [--root PATH] [--bun /path/to/bun] [-- ...extra TUI args]` keeps older automation working while delegating to Bun.
77
- - Keys:
78
- - Global: `Tab`/`1`/`2` switch tabs, `/` search, `X` clear search, `R` reload, `Q` quit, `?` help
79
- - Projects: `Space` select, `A` select all, `M` toggle missing, `D` delete, `Enter` view sessions
80
- - Sessions: `Space` select, `S` sort, `D` delete, `Y` copy ID, `Shift+R` rename, `M` move, `P` copy, `C` clear filter
81
- - Optional tmux usage (when permitted): `tmux new -s opencode-tui 'bun run tui'`
82
- - CLI help: `bun run tui -- --help` (or `bunx opencode-manager -- --help`, or `manage_opencode_projects.py -- --help`) prints the built-in usage block with key bindings.
123
+ ### TUI Mode (Interactive)
124
+ - Zero-install: `bunx opencode-manager [--root /path/to/storage]` (preferred)
125
+ - Local dev: `bun run tui [-- --root /path/to/storage]`
126
+ - Legacy launcher: `./manage_opencode_projects.py [--bun /path/to/bun]`
127
+ - TUI help: `bunx opencode-manager --help` shows key bindings
128
+
129
+ ### CLI Mode (Scripting)
130
+ - Projects: `bunx opencode-manager projects list --format json`
131
+ - Sessions: `bunx opencode-manager sessions list --project <id> --limit 10`
132
+ - Chat: `bunx opencode-manager chat search --query "fix bug" --format ndjson`
133
+ - Tokens: `bunx opencode-manager tokens global --format table`
134
+ - Delete with backup: `bunx opencode-manager sessions delete --session <id> --yes --backup-dir ./backups`
135
+ - Dry run: `bunx opencode-manager projects delete --id <id> --dry-run`
136
+
137
+ ### Global CLI Options
138
+ - `--root <path>` — Metadata store root (default: `~/.local/share/opencode`)
139
+ - `--format <json|ndjson|table>` — Output format (default: `table`)
140
+ - `--limit <n>` — Max records (default: 200)
141
+ - `--sort <updated|created>` — Sort order (default: `updated`)
142
+ - `--yes` — Skip confirmation for destructive ops
143
+ - `--dry-run` — Preview changes without executing
144
+ - `--quiet` — Suppress non-essential output
145
+ - `--clipboard` — Copy output to clipboard
146
+ - `--backup-dir <path>` — Backup before deletion
147
+
148
+ ### Exit Codes
149
+ - 0: Success
150
+ - 1: Internal error
151
+ - 2: Usage/validation error (missing `--yes`, bad args)
152
+ - 3: Resource not found (invalid project/session/message ID)
153
+ - 4: File operation error (backup/delete failure)
154
+
155
+ ### TUI Keys
156
+ - Global: `Tab`/`1`/`2` switch tabs, `/` search, `X` clear search, `R` reload, `Q` quit, `?/H` help
157
+ - Projects: `Space` select, `A` select all, `M` toggle missing, `D` delete, `Enter` view sessions, `Esc` clear selection
158
+ - Sessions: `Space` select, `A` select all, `S` sort, `V` view chat, `F` search chats, `Shift+R` rename, `M` move, `P` copy, `Y` copy ID, `C` clear filter, `D` delete, `Enter` details, `Esc` clear selection
159
+
160
+ ### Optional
161
+ - tmux: `tmux new -s opencode-manager 'bun run tui'`
83
162
 
84
163
  Packaging & Publish Checklist
85
164
  -----------------------------
86
- 1. Install dependencies with `bun install` (Bun v1.1+ only).
165
+ 1. Install dependencies with `bun install` (Bun v1.3+ only).
87
166
  2. Type-check via `bun run typecheck` (runs `tsc --noEmit`).
88
167
  3. Update the version in `package.json` as needed.
89
168
  4. Run `npm publish` (package exposes the Bun-native `opencode-manager` bin with public access).
90
169
 
91
170
  Outstanding Recommendations (Not Yet Implemented)
92
171
  -------------------------------------------------
93
- - UI polish
172
+ - TUI polish
94
173
  - Colorize project state in list labels (e.g., green for present, red for missing, gray for unknown).
95
174
  - Show a small timestamp snippet for Projects rows (created).
96
175
  - Add tiny icons or color accents to distinguish created vs updated descriptions in Sessions.
97
176
  - Add per-view mini legends with colored key chips under the panels (Projects/Sessions), consistent with the Help styling.
98
- - Show filtered counts (e.g., Showing X of Y).
177
+ - Show filtered counts (e.g., "Showing X of Y").
99
178
  - Search enhancements
100
- - Optional fuzzy matching; toggle to include/exclude `directory` in Sessions/Projects search for more control.
101
- - Persist search and sort preferences per tab (and optionally per project filter) during the app run.
179
+ - Optional fuzzy matching toggle in TUI; persist search and sort preferences per tab.
102
180
  - Save last-used search/sort to a small state file and restore on next launch.
103
181
  - Accessibility & layout
104
182
  - Ensure all active/inactive/focused states have adequate contrast and consistent highlight styles.
@@ -106,10 +184,12 @@ Outstanding Recommendations (Not Yet Implemented)
106
184
  - Performance
107
185
  - Debounce UI reactions to large search queries; short-circuit expensive filters when query is empty.
108
186
  - Testing
109
- - Add unit coverage for opencode-data helpers (formatting, parsing, sorting).
110
- - Add basic snapshot/E2E tests for rendering key panels and Help using a headless renderer (if available for @opentui).
111
- - Packaging/Docs
112
- - Add a README section specific to the TUI tool, with a short demo, common actions, and troubleshooting.
187
+ - Add integration tests for CLI commands with real fixture data.
188
+ - Add basic snapshot/E2E tests for TUI rendering (if headless renderer available for @opentui).
189
+ - CLI enhancements
190
+ - Shell completion scripts (bash/zsh/fish).
191
+ - `--json-lines` alias for `--format ndjson` compatibility.
192
+ - Template/profile support for common option combinations.
113
193
 
114
194
  Notes
115
195
  -----
package/README.md CHANGED
@@ -3,33 +3,48 @@
3
3
 
4
4
  # OpenCode Metadata Manager
5
5
 
6
- Terminal UI for inspecting, filtering, and pruning OpenCode metadata stored on disk. The app is written in TypeScript, runs on Bun, and renders with [`@opentui/react`](https://github.com/open-tui/opentui).
6
+ Terminal UI for inspecting, filtering, and pruning OpenCode metadata stored on disk. The app is written in TypeScript, runs on Bun, and renders with [`@opentui/react`](https://github.com/sst/opentui).
7
7
 
8
8
  ## Screenshots
9
9
 
10
10
  <p align="center">
11
- <img src="home-screen.png" alt="OpenCode Metadata Manager home screen showing projects and sessions" width="85%" />
11
+ <img src="oc-manager.png" alt="OpenCode Metadata Manager home screen showing projects and sessions" width="85%" />
12
12
  <br />
13
13
  <em>Main workspace with Projects (left) and Sessions (right) panels.</em>
14
14
  </p>
15
15
 
16
16
  <p align="center">
17
- <img src="help-screen.png" alt="OpenCode Metadata Manager help overlay" width="85%" />
17
+ <img src="oc-manager-home.png" alt="OpenCode Metadata Manager home screen alternate view" width="85%" />
18
18
  <br />
19
- <em>Contextual help overlay with key bindings and tips.</em>
19
+ <em>Alternate home view with project/session context.</em>
20
+ </p>
21
+
22
+ <p align="center">
23
+ <img src="oc-manager-search.png" alt="OpenCode Metadata Manager search view" width="85%" />
24
+ <br />
25
+ <em>Fuzzy search across sessions with ranked results.</em>
26
+ </p>
27
+
28
+ <p align="center">
29
+ <img src="oc-manager-cli.png" alt="OpenCode Metadata Manager CLI output" width="85%" />
30
+ <br />
31
+ <em>Scriptable CLI output for listing projects and sessions.</em>
20
32
  </p>
21
33
 
22
34
  ## Features
23
35
  - List both OpenCode projects and sessions from a local metadata root.
24
36
  - Filter by "missing only", bulk-select, and delete metadata safely.
25
37
  - Jump from a project directly to its sessions and keep contextual filters.
26
- - Global search bar (`/` to focus, `Enter` to apply, `Esc` or `X` to clear).
38
+ - **Fuzzy search** across session titles and metadata (`/` to focus, results ranked by relevance).
39
+ - **View session chat history** with full conversation context (`V` to open viewer).
40
+ - **Search across all chat content** in sessions within a project (`F` to search).
27
41
  - Rename sessions inline (`Shift+R`) with title validation.
28
42
  - Move sessions between projects (`M`) preserving session ID.
29
43
  - Copy sessions to other projects (`P`) with new session ID generation.
30
44
  - Rich help overlay with live key hints (`?` or `H`).
31
45
  - Zero-install via `bunx` so even CI shells can run it without cloning.
32
46
  - **Token counting**: View token usage per session, per project, and globally.
47
+ - **Experimental SQLite backend**: Faster queries for large stores via `--experimental-sqlite`.
33
48
 
34
49
  ## Token Counting
35
50
 
@@ -56,7 +71,7 @@ The TUI displays token telemetry from OpenCode's stored message data at three le
56
71
  - Large datasets are handled with lazy computation to avoid UI freezes.
57
72
 
58
73
  ## Requirements
59
- - [Bun](https://bun.sh) **1.1.0+** (developed/tested on 1.2.x).
74
+ - [Bun](https://bun.sh) **1.3.0+** (developed/tested on 1.3.x).
60
75
  - A node-compatible terminal (truecolor improves readability but is optional).
61
76
 
62
77
  ## Installation
@@ -73,6 +88,13 @@ bunx opencode-manager --help
73
88
  The repository ships with a focused `.gitignore`, keeping `node_modules/`, caches, and logs out of Git history.
74
89
 
75
90
  ## Usage
91
+
92
+ The manager provides both a Terminal UI (TUI) and a scriptable CLI interface.
93
+
94
+ ### Terminal UI (TUI)
95
+
96
+ The TUI is the default interface when no subcommand is provided:
97
+
76
98
  ```bash
77
99
  # Preferred: zero-install command
78
100
  bunx opencode-manager --root ~/.local/share/opencode
@@ -85,9 +107,363 @@ bun run tui -- --root ~/.local/share/opencode
85
107
  ```
86
108
 
87
109
  Keyboard reference:
88
- - **Global**: `Tab`/`1`/`2` switch tabs, `/` search, `X` clear search, `R` reload, `Q` quit, `?` help.
89
- - **Projects**: `Space` toggle selection, `A` select all, `M` missing-only filter, `D` delete, `Enter` jump to Sessions.
90
- - **Sessions**: `Space` select, `S` toggle sort, `D` delete, `Y` copy ID, `Shift+R` rename, `M` move to project, `P` copy to project, `C` clear filter.
110
+ - **Global**: `Tab`/`1`/`2` switch tabs, `/` search (fuzzy), `X` clear search, `R` reload, `Q` quit, `?/H` help.
111
+ - **Projects**: `Space` toggle selection, `A` select all, `M` missing-only filter, `D` delete, `Enter` jump to Sessions, `Esc` clear selection.
112
+ - **Sessions**: `Space` select, `A` select all, `S` toggle sort, `V` view chat, `F` search chats, `D` delete, `Y` copy ID, `Shift+R` rename, `M` move, `P` copy, `C` clear filter, `Enter` details, `Esc` clear selection.
113
+ - **Chat Search**: Type query + `Enter` to search, `Up/Down` navigate, `Enter` opens result, `Esc` close.
114
+ - **Chat Viewer**: `Esc` close, `Up/Down` navigate, `PgUp/PgDn` jump 10, `Home/End` first/last, `Y` copy message.
115
+
116
+ ### Command Line Interface (CLI)
117
+
118
+ The CLI provides scriptable access to all management operations. Use subcommands to list, search, and modify metadata.
119
+
120
+ #### Global Options
121
+
122
+ | Option | Default | Description |
123
+ |--------|---------|-------------|
124
+ | `-r, --root <path>` | `~/.local/share/opencode` | Root path to OpenCode metadata store |
125
+ | `-f, --format <fmt>` | `table` | Output format: `json`, `ndjson`, or `table` |
126
+ | `-l, --limit <n>` | `200` | Maximum number of records to return |
127
+ | `--sort <order>` | `updated` | Sort order: `updated` or `created` |
128
+ | `-y, --yes` | `false` | Skip confirmation prompts for destructive operations |
129
+ | `-n, --dry-run` | `false` | Preview changes without executing |
130
+ | `-q, --quiet` | `false` | Suppress non-essential output |
131
+ | `-c, --clipboard` | `false` | Copy output to clipboard |
132
+ | `--backup-dir <path>` | — | Directory for backup copies before deletion |
133
+ | `--experimental-sqlite` | `false` | Use SQLite database instead of JSONL files (experimental) |
134
+ | `--db <path>` | `~/.local/share/opencode/opencode.db` | Path to SQLite database (implies `--experimental-sqlite`) |
135
+ | `--sqlite-strict` | `false` | Fail on any SQLite warning or malformed data |
136
+ | `--force-write` | `false` | Wait for SQLite write locks to clear before failing |
137
+
138
+ #### Experimental SQLite Support
139
+
140
+ OpenCode can store metadata in SQLite databases. The CLI supports this mode with `--experimental-sqlite` or by pointing directly at a database with `--db <path>`.
141
+
142
+ Key behaviors:
143
+ - Read operations open SQLite in readonly mode by default.
144
+ - Write operations may fail if OpenCode has the database locked. Use `--force-write` to wait for the lock to clear.
145
+ - When malformed rows are encountered, the CLI logs a warning and returns partial results. Use `--sqlite-strict` to fail fast.
146
+
147
+ When to use SQLite vs JSONL:
148
+ - Use SQLite when your OpenCode installation no longer writes JSONL files or when you want faster list/search operations on large stores.
149
+ - Use JSONL when you need maximal compatibility with older OpenCode versions or when you want to avoid SQLite locking.
150
+
151
+ Known limitations and differences:
152
+ - Schema changes in OpenCode may break compatibility. The CLI validates required tables/columns and warns if the schema is incomplete.
153
+ - SQLite records use virtual file paths (e.g., `sqlite:project:proj_123`) instead of JSON file paths.
154
+ - Results may differ slightly from JSONL when extra SQLite-only rows exist.
155
+
156
+ Examples:
157
+ ```bash
158
+ # List projects using the default SQLite database
159
+ opencode-manager projects list --experimental-sqlite
160
+
161
+ # List sessions using an explicit SQLite database path
162
+ opencode-manager sessions list --db ~/.local/share/opencode/opencode.db
163
+
164
+ # Fail fast on malformed SQLite data
165
+ opencode-manager projects list --db ~/.local/share/opencode/opencode.db --sqlite-strict
166
+
167
+ # Wait for locks before destructive operations
168
+ opencode-manager projects delete --id proj_missing --db ~/.local/share/opencode/opencode.db --yes --force-write
169
+ ```
170
+
171
+ #### Commands Overview
172
+
173
+ ```
174
+ opencode-manager
175
+ ├── projects
176
+ │ ├── list List projects (--missing-only, --search)
177
+ │ └── delete Delete project metadata (--id, --yes, --dry-run, --backup-dir)
178
+ ├── sessions
179
+ │ ├── list List sessions (--project, --search)
180
+ │ ├── delete Delete session metadata (--session, --yes, --dry-run, --backup-dir)
181
+ │ ├── rename Rename a session (--session, --title)
182
+ │ ├── move Move session to another project (--session, --to)
183
+ │ └── copy Copy session to another project (--session, --to)
184
+ ├── chat
185
+ │ ├── list List messages in a session (--session, --include-parts)
186
+ │ ├── show Show a specific message (--session, --message or --index, --clipboard)
187
+ │ └── search Search chat content across sessions (--query, --project)
188
+ ├── tokens
189
+ │ ├── session Show token usage for a session (--session)
190
+ │ ├── project Show token usage for a project (--project)
191
+ │ └── global Show global token usage
192
+ └── tui Launch the Terminal UI
193
+ ```
194
+
195
+ #### TUI Subcommand
196
+
197
+ The `tui` subcommand explicitly launches the Terminal UI. This is equivalent to running `opencode-manager` with no subcommand:
198
+
199
+ ```bash
200
+ # These are equivalent:
201
+ opencode-manager
202
+ opencode-manager tui
203
+ opencode-manager tui --root ~/.local/share/opencode
204
+ ```
205
+
206
+ Use the explicit `tui` subcommand when you want to be clear about intent in scripts or when combining with other options. Note that `tui --help` shows the TUI help screen (key bindings), not Commander CLI help.
207
+
208
+ #### Help System
209
+
210
+ The manager uses a dual help system depending on context:
211
+
212
+ | Command | Help Type | Content |
213
+ |---------|-----------|---------|
214
+ | `opencode-manager --help` | TUI help | Key bindings and TUI usage |
215
+ | `opencode-manager -h` | TUI help | Same as `--help` |
216
+ | `opencode-manager tui --help` | TUI help | Key bindings (routes to TUI help) |
217
+ | `opencode-manager projects --help` | CLI help | Commander subcommand help |
218
+ | `opencode-manager sessions --help` | CLI help | Commander subcommand help |
219
+ | `opencode-manager chat --help` | CLI help | Commander subcommand help |
220
+ | `opencode-manager tokens --help` | CLI help | Commander subcommand help |
221
+
222
+ **Why?** The root command defaults to launching the TUI, so `--help` shows TUI-relevant information (key bindings). CLI subcommands use standard Commander.js help showing options and usage.
223
+
224
+ To see all CLI subcommands, use any subcommand with `--help`:
225
+
226
+ ```bash
227
+ # Shows TUI key bindings
228
+ opencode-manager --help
229
+
230
+ # Shows CLI subcommand help with options
231
+ opencode-manager projects --help
232
+ opencode-manager projects list --help
233
+ ```
234
+
235
+ #### Output Format Examples
236
+
237
+ The CLI supports three output formats via `--format`:
238
+
239
+ **Table (default)** — Human-readable columnar output:
240
+
241
+ ```bash
242
+ $ bunx opencode-manager projects list --limit 3
243
+
244
+ # State Path Project ID Created
245
+ ---- ----- -------------------------------------------------- ------------------------ ----------------
246
+ 1 ✓ /home/user/repos/my-app a1b2c3d4e5f6g7h8i9j0k1l2 2026-01-04 09:20
247
+ 2 ✓ /home/user/repos/api-server b2c3d4e5f6g7h8i9j0k1l2m3 2026-01-03 14:15
248
+ 3 ✗ /home/user/repos/deleted-project c3d4e5f6g7h8i9j0k1l2m3n4 2025-12-28 10:30
249
+ ```
250
+
251
+ **JSON** — Structured output with metadata envelope:
252
+
253
+ ```bash
254
+ $ bunx opencode-manager sessions list --project prj_abc123 --format json --limit 2
255
+
256
+ {
257
+ "ok": true,
258
+ "data": [
259
+ {
260
+ "index": 1,
261
+ "sessionId": "sess_xyz789",
262
+ "projectId": "prj_abc123",
263
+ "directory": "/home/user/repos/my-app",
264
+ "title": "Refactor auth module",
265
+ "version": "1.1.4",
266
+ "updatedAt": "2026-01-05T14:32:00.000Z",
267
+ "createdAt": "2026-01-03T09:15:00.000Z"
268
+ },
269
+ {
270
+ "index": 2,
271
+ "sessionId": "sess_uvw456",
272
+ "projectId": "prj_abc123",
273
+ "directory": "/home/user/repos/my-app",
274
+ "title": "Add unit tests",
275
+ "version": "1.1.4",
276
+ "updatedAt": "2026-01-04T16:45:00.000Z",
277
+ "createdAt": "2026-01-02T11:20:00.000Z"
278
+ }
279
+ ],
280
+ "meta": {
281
+ "count": 2,
282
+ "limit": 2
283
+ }
284
+ }
285
+ ```
286
+
287
+ JSON output auto-detects your terminal: pretty-printed with indentation when output goes to a TTY, compact single-line when piped to another command.
288
+
289
+ The `meta` object contains:
290
+ - `count` — Number of items in the `data` array
291
+ - `limit` — The limit that was applied (if `--limit` was specified)
292
+
293
+ **NDJSON** — Newline-delimited JSON for streaming/piping:
294
+
295
+ ```bash
296
+ $ bunx opencode-manager sessions list --format ndjson --limit 2
297
+
298
+ {"index":1,"sessionId":"ses_abc123","projectId":"prj_xyz789","title":"Feature implementation","createdAt":"2026-01-06T10:30:00.000Z"}
299
+ {"index":2,"sessionId":"ses_def456","projectId":"prj_xyz789","title":"Bug fix session","createdAt":"2026-01-06T11:15:00.000Z"}
300
+ ```
301
+
302
+ Each line is a complete JSON object, ideal for piping to `jq` or line-by-line processing. For single-record commands like `tokens global`, NDJSON outputs one line with the same structure as the JSON `data` field.
303
+
304
+ **Piping examples:**
305
+
306
+ ```bash
307
+ # Count sessions per project
308
+ bunx opencode-manager sessions list --format ndjson | jq -s 'group_by(.projectId) | map({project: .[0].projectId, count: length})'
309
+
310
+ # Get all session IDs as plain text
311
+ bunx opencode-manager sessions list --format json | jq -r '.data[].sessionId'
312
+
313
+ # Export chat history to file
314
+ bunx opencode-manager chat list --session sess_xyz789 --include-parts --format json > chat-export.json
315
+
316
+ # Dry-run delete to preview affected files
317
+ bunx opencode-manager projects delete --id prj_old --dry-run --format json
318
+ ```
319
+
320
+ #### Token Output Format
321
+
322
+ Token commands (`tokens session`, `tokens project`, `tokens global`) return structured summaries of token usage.
323
+
324
+ **Session tokens** — Single session summary with `kind` discriminator:
325
+
326
+ ```bash
327
+ $ bunx opencode-manager tokens session --session sess_xyz789 --format json
328
+
329
+ # When token data is available (kind: "known"):
330
+ {
331
+ "ok": true,
332
+ "data": {
333
+ "kind": "known",
334
+ "tokens": {
335
+ "input": 12500,
336
+ "output": 8750,
337
+ "reasoning": 2100,
338
+ "cacheRead": 4200,
339
+ "cacheWrite": 950,
340
+ "total": 28500
341
+ }
342
+ }
343
+ }
344
+
345
+ # When token data is unavailable (kind: "unknown"):
346
+ {
347
+ "ok": true,
348
+ "data": {
349
+ "kind": "unknown",
350
+ "reason": "no_messages"
351
+ }
352
+ }
353
+ ```
354
+
355
+ The `reason` field indicates why tokens are unavailable:
356
+ - `"missing"` — Session metadata file not found
357
+ - `"parse_error"` — Token data couldn't be parsed
358
+ - `"no_messages"` — Session has no messages with token data
359
+
360
+ **Project/Global tokens** — Aggregate summary across multiple sessions:
361
+
362
+ ```bash
363
+ $ bunx opencode-manager tokens project --project prj_abc123 --format json
364
+
365
+ {
366
+ "ok": true,
367
+ "data": {
368
+ "total": {
369
+ "kind": "known",
370
+ "tokens": { "input": 125000, "output": 98000, "reasoning": 32000, "cacheRead": 15000, "cacheWrite": 6500, "total": 276500 }
371
+ },
372
+ "knownOnly": { "input": 125000, "output": 98000, "reasoning": 32000, "cacheRead": 15000, "cacheWrite": 6500, "total": 276500 },
373
+ "unknownSessions": 2
374
+ }
375
+ }
376
+ ```
377
+
378
+ Aggregate summary fields:
379
+ - `total` — Combined `TokenSummary` (same structure as session tokens)
380
+ - `knownOnly` — Token breakdown from sessions with available data only (omitted if all unknown)
381
+ - `unknownSessions` — Count of sessions where token data was unavailable
382
+
383
+ **Note:** The `tokens` commands require exact IDs (no prefix matching). Use full session/project IDs as shown in `sessions list` or `projects list` output.
384
+
385
+ #### Exit Codes
386
+
387
+ | Code | Meaning |
388
+ |------|---------|
389
+ | 0 | Success |
390
+ | 1 | General error |
391
+ | 2 | Usage error (missing required options, invalid arguments) |
392
+ | 3 | Resource not found (invalid project/session/message ID) |
393
+ | 4 | File operation error (backup or delete failure) |
394
+
395
+ #### ID Resolution
396
+
397
+ Most commands accept ID prefixes for convenience. The CLI will match the prefix to a unique ID:
398
+
399
+ ```bash
400
+ # Full ID
401
+ opencode-manager sessions delete --session sess_01JGNPE16DT1JX1YA8KTPMDRW3
402
+
403
+ # Prefix match (if unique)
404
+ opencode-manager sessions delete --session sess_01JGN
405
+
406
+ # Ambiguous prefix (fails with error listing matches)
407
+ opencode-manager sessions delete --session sess_01
408
+ # Error: Multiple sessions match prefix 'sess_01': sess_01JGN..., sess_01ABC...
409
+ ```
410
+
411
+ **Commands supporting prefix matching:**
412
+ - `projects delete --id`
413
+ - `sessions delete --session`, `sessions rename --session`, `sessions move --session`, `sessions copy --session`
414
+ - `sessions move --to`, `sessions copy --to` (project ID)
415
+ - `chat list --session`, `chat show --session`
416
+ - `chat show --message` (also supports 1-based `--index`)
417
+
418
+ **Commands requiring exact IDs:**
419
+ - `tokens session --session` — requires full session ID
420
+ - `tokens project --project` — requires full project ID
421
+
422
+ #### Clipboard Support
423
+
424
+ The `--clipboard` flag (or `Y` key in the TUI) copies content to the system clipboard. Platform support:
425
+
426
+ | Platform | Tool Required | Notes |
427
+ |----------|---------------|-------|
428
+ | **macOS** | None | Uses built-in `pbcopy` |
429
+ | **Linux** | `xclip` | Install via `apt install xclip` or equivalent |
430
+ | **Windows** | — | Not currently supported |
431
+
432
+ On Linux, if `xclip` is not installed, clipboard operations will fail silently in the TUI or show an error message in the CLI.
433
+
434
+ #### Delete Semantics
435
+
436
+ Delete commands (`projects delete`, `sessions delete`) remove **metadata files only**:
437
+
438
+ | Command | Deletes | Preserves |
439
+ |---------|---------|-----------|
440
+ | `projects delete` | Project metadata (`storage/project/<id>.json`) | Sessions, messages, parts |
441
+ | `sessions delete` | Session metadata (`storage/sessions/<projectId>.json` entry) | Message and part files |
442
+
443
+ **Safety features:**
444
+
445
+ - **Confirmation required** — Destructive operations require `--yes` flag or interactive confirmation:
446
+ ```bash
447
+ # Will prompt for confirmation (interactive)
448
+ opencode-manager projects delete --id prj_abc123
449
+
450
+ # Skip confirmation (scripts)
451
+ opencode-manager projects delete --id prj_abc123 --yes
452
+ ```
453
+
454
+ - **Dry-run preview** — Use `--dry-run` to see what would be deleted without making changes:
455
+ ```bash
456
+ opencode-manager sessions delete --session sess_xyz789 --dry-run
457
+ # Output shows files that would be affected
458
+ ```
459
+
460
+ - **Backup before delete** — Use `--backup-dir` to copy files before deletion:
461
+ ```bash
462
+ opencode-manager projects delete --id prj_abc123 --backup-dir ./backups --yes
463
+ # Creates backup, then deletes original
464
+ ```
465
+
466
+ **Note:** Session deletion leaves associated chat message files intact. To fully remove a session's data, you would need to manually delete the message files from `storage/message/<sessionId>/`.
91
467
 
92
468
  ## Development Workflow
93
469
  1. Install dependencies with `bun install`.
@@ -98,11 +474,24 @@ Keyboard reference:
98
474
  ### Project Structure
99
475
  ```
100
476
  src/
101
- bin/opencode-manager.ts # Bun-native CLI shim exposed as the bin entry
102
- opencode-tui.tsx # Main TUI implementation (panels, search, help)
103
- manage_opencode_projects.py # Legacy Python launcher for backwards compatibility
104
- opencode-gen.sh # Spec snapshot helper script
105
- PROJECT-SUMMARY.md # Extended design notes & roadmap
477
+ bin/opencode-manager.ts # Bun-native CLI shim exposed as the bin entry
478
+ cli/
479
+ index.ts # Commander program with global options
480
+ commands/ # Subcommand implementations (projects, sessions, chat, tokens)
481
+ resolvers.ts # ID prefix resolution helpers
482
+ lib/
483
+ opencode-data.ts # JSONL file-based data access
484
+ opencode-data-sqlite.ts # SQLite backend (experimental)
485
+ opencode-data-provider.ts # Unified DataProvider abstraction
486
+ tui/
487
+ app.tsx # Main TUI implementation (panels, search, help)
488
+ index.tsx # TUI entrypoint with launchTUI(), parseArgs(), bootstrap()
489
+ tests/
490
+ fixtures/ # Test data (JSONL and SQLite fixtures)
491
+ lib/ # Unit tests for data modules
492
+ cli/ # CLI integration tests
493
+ manage_opencode_projects.py # Legacy Python launcher for backwards compatibility
494
+ PROJECT-SUMMARY.md # Extended design notes & roadmap
106
495
  ```
107
496
 
108
497
  ## Packaging & Publish