@martian-engineering/lossless-claw 0.1.0

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/docs/tui.md ADDED
@@ -0,0 +1,437 @@
1
+ # TUI Reference
2
+
3
+ The Lossless Claw TUI (`lcm-tui`) is an interactive terminal application for inspecting, debugging, and maintaining the LCM database. It provides direct visibility into what the model sees (context assembly), how summaries are structured (DAG hierarchy), and tools for surgical repairs when things go wrong.
4
+
5
+ ## Installation
6
+
7
+ **From GitHub releases:**
8
+
9
+ Download the latest binary for your platform from [Releases](https://github.com/Martian-Engineering/lossless-claw/releases).
10
+
11
+ **Build from source:**
12
+
13
+ ```bash
14
+ cd tui
15
+ go build -o lcm-tui .
16
+ # or: make build
17
+ # or: go install github.com/Martian-Engineering/lossless-claw/tui@latest
18
+ ```
19
+
20
+ Requires Go 1.24+.
21
+
22
+ ## Quick Start
23
+
24
+ ```bash
25
+ lcm-tui # default: ~/.openclaw/lcm.db
26
+ lcm-tui --db /path/to/lcm.db # custom database path
27
+ ```
28
+
29
+ The TUI auto-discovers agent session directories from `~/.openclaw/agents/`.
30
+
31
+ ## Navigation Model
32
+
33
+ The TUI is organized as a drill-down hierarchy. You navigate deeper with Enter and back with `b`/Backspace.
34
+
35
+ ```
36
+ Agents → Sessions → Conversation → [Summary DAG | Context View | Large Files]
37
+ ```
38
+
39
+ ### Screen 1: Agent List
40
+
41
+ Lists all agents discovered under `~/.openclaw/agents/`. Select an agent to see its sessions.
42
+
43
+ | Key | Action |
44
+ |-----|--------|
45
+ | `↑`/`↓` or `k`/`j` | Move cursor |
46
+ | `Enter` | Open agent's sessions |
47
+ | `r` | Reload agent list |
48
+ | `q` | Quit |
49
+
50
+ ### Screen 2: Session List
51
+
52
+ Shows JSONL session files for the selected agent, sorted by last modified time. Each entry shows the filename, last update time, message count, conversation ID (if LCM-tracked), summary count, and large file count.
53
+
54
+ Sessions load in batches of 50. Scrolling near the bottom automatically loads more.
55
+
56
+ | Key | Action |
57
+ |-----|--------|
58
+ | `↑`/`↓` or `k`/`j` | Move cursor |
59
+ | `Enter` | Open conversation |
60
+ | `b`/`Backspace` | Back to agents |
61
+ | `r` | Reload sessions |
62
+ | `q` | Quit |
63
+
64
+ ### Screen 3: Conversation View
65
+
66
+ A scrollable, color-coded view of the raw session messages. Each message shows its timestamp, role (user/assistant/system/tool), and content. Roles are color-coded:
67
+
68
+ - **Green** — user messages
69
+ - **Blue** — assistant messages
70
+ - **Yellow** — system messages
71
+ - **Gray** — tool calls and results
72
+
73
+ This is the raw session data, not the LCM-managed context. Use it to understand what actually happened in the conversation.
74
+
75
+ | Key | Action |
76
+ |-----|--------|
77
+ | `↑`/`↓` or `k`/`j` | Scroll one line |
78
+ | `PgUp`/`PgDn` | Scroll half page |
79
+ | `g` | Jump to top |
80
+ | `G` | Jump to bottom |
81
+ | `l` | Open **Summary DAG** view |
82
+ | `c` | Open **Context** view |
83
+ | `f` | Open **Large Files** view |
84
+ | `b`/`Backspace` | Back to sessions |
85
+ | `r` | Reload messages |
86
+ | `q` | Quit |
87
+
88
+ ## Summary DAG View
89
+
90
+ The core inspection tool. Shows the full hierarchy of LCM summaries for a conversation as an expandable tree.
91
+
92
+ Each row shows:
93
+ ```
94
+ [marker] summary_id [kind, tokens] content preview
95
+ ```
96
+
97
+ - **Marker**: `>` (collapsed, has children), `v` (expanded), `-` (leaf, no children)
98
+ - **Kind**: `leaf` for depth-0 summaries, `d1`/`d2`/`d3` for condensed summaries at each depth
99
+ - **Tokens**: token count of the summary content
100
+
101
+ The bottom panel shows the detail view for the selected summary: full content text and source messages (the raw messages that were summarized to create this node).
102
+
103
+ ### When to Use
104
+
105
+ - **Verify summarization quality** — read what the model will actually see
106
+ - **Check DAG structure** — ensure the depth hierarchy is balanced
107
+ - **Find corrupted nodes** — look for suspiciously short content, "[LCM fallback summary]" markers, or raw tool output that leaked into summaries
108
+ - **Understand temporal coverage** — each summary's source messages show exactly which conversation segment it covers
109
+
110
+ ### Navigation
111
+
112
+ | Key | Action |
113
+ |-----|--------|
114
+ | `↑`/`↓` or `k`/`j` | Move cursor in list |
115
+ | `Enter`/`l`/`Space` | Expand/collapse node |
116
+ | `h` | Collapse current node |
117
+ | `g` | Jump to first summary |
118
+ | `G` | Jump to last summary |
119
+ | `Shift+J` | Scroll detail panel down |
120
+ | `Shift+K` | Scroll detail panel up |
121
+ | `w` | **Rewrite** selected summary |
122
+ | `W` | **Subtree rewrite** (selected + all descendants) |
123
+ | `d` | **Dissolve** selected condensed summary |
124
+ | `r` | Reload DAG |
125
+ | `b`/`Backspace` | Back to conversation |
126
+ | `q` | Quit |
127
+
128
+ ## Context View
129
+
130
+ Shows exactly what the model sees: the ordered list of context items (summaries + fresh tail messages) that LCM assembles for the next turn. This is the ground truth for "what does the agent know right now?"
131
+
132
+ Each row shows:
133
+ ```
134
+ ordinal kind [id, tokens] content_preview
135
+ ```
136
+
137
+ - **Summaries** show as `leaf`, `d1`, `d2`, etc. with their summary ID
138
+ - **Messages** show their role (user/assistant/system/tool) with message ID
139
+
140
+ The status bar shows totals: how many summaries, how many messages, total items, and total tokens.
141
+
142
+ ### When to Use
143
+
144
+ - **Debug context overflow** — see total token count and identify what's consuming the budget
145
+ - **Verify assembly order** — summaries should appear before fresh tail messages, ordered chronologically
146
+ - **Check after dissolve/rewrite** — confirm your changes are reflected in what the model sees
147
+ - **Compare with raw conversation** — the conversation view shows everything; the context view shows what survives compaction
148
+
149
+ | Key | Action |
150
+ |-----|--------|
151
+ | `↑`/`↓` or `k`/`j` | Move cursor |
152
+ | `g` | Jump to first item |
153
+ | `G` | Jump to last item |
154
+ | `Shift+J` | Scroll detail panel down |
155
+ | `Shift+K` | Scroll detail panel up |
156
+ | `r` | Reload context |
157
+ | `b`/`Backspace` | Back to conversation |
158
+ | `q` | Quit |
159
+
160
+ ## Large Files View
161
+
162
+ Lists files that exceeded the large file threshold (default 25k tokens) and were intercepted by LCM. Shows file ID, display name, MIME type, byte size, and creation time. The detail panel shows the exploration summary that was generated as a lightweight stand-in.
163
+
164
+ | Key | Action |
165
+ |-----|--------|
166
+ | `↑`/`↓` or `k`/`j` | Move cursor |
167
+ | `g`/`G` | Jump to first/last |
168
+ | `r` | Reload files |
169
+ | `b`/`Backspace` | Back to conversation |
170
+ | `q` | Quit |
171
+
172
+ ## Operations
173
+
174
+ ### Rewrite (`w`)
175
+
176
+ Re-summarizes a single summary node using the current depth-aware prompt templates. The process:
177
+
178
+ 1. **Preview** — shows the prompt that will be sent, including source material, target token count, previous context, and time range
179
+ 2. **API call** — sends to Anthropic's API (Claude Sonnet by default)
180
+ 3. **Review** — shows old and new content side-by-side with token delta. Toggle unified diff view with `d`. Scroll with `j`/`k`.
181
+
182
+ | Key (Preview) | Action |
183
+ |-----|--------|
184
+ | `Enter` | Send to API |
185
+ | `Esc` | Cancel |
186
+
187
+ | Key (Review) | Action |
188
+ |-----|--------|
189
+ | `y`/`Enter` | Apply rewrite to database |
190
+ | `n`/`Esc` | Discard |
191
+ | `d` | Toggle unified diff view |
192
+ | `j`/`k` | Scroll content |
193
+
194
+ **When to use:** A summary has poor quality (too verbose, missing key details, or was generated before the depth-aware prompts were implemented). Rewriting regenerates it from its original source material using the current prompts.
195
+
196
+ ### Subtree Rewrite (`W`)
197
+
198
+ Rewrites the selected summary and all its descendants, bottom-up. Leaves are rewritten first so that condensed parents pick up the improved content. Nodes are processed one at a time through the same preview→API→review cycle.
199
+
200
+ | Key (additional) | Action |
201
+ |-----|--------|
202
+ | `A` | **Auto-accept** — apply current and all remaining automatically |
203
+ | `n` | Skip current node, advance to next |
204
+ | `Esc` | Abort entire subtree rewrite |
205
+
206
+ The status bar shows progress as `[N/total]`. Auto-accept pauses on errors so you can inspect failures.
207
+
208
+ **When to use:** A whole branch of the DAG has outdated formatting (e.g., pre-depth-aware summaries). Subtree rewrite regenerates everything from the leaves up.
209
+
210
+ ### Dissolve (`d`)
211
+
212
+ Reverses a condensation: removes a condensed summary from the active context and restores its parent summaries in its place. This is a surgical undo of a compaction step.
213
+
214
+ The confirmation screen shows:
215
+ - The target summary (kind, depth, tokens, context ordinal)
216
+ - Token impact (condensed tokens → total restored parent tokens)
217
+ - Ordinal shift (how many items after the target will be renumbered)
218
+ - Parent summaries that will be restored (with previews)
219
+
220
+ | Key | Action |
221
+ |-----|--------|
222
+ | `y`/`Enter` | Execute dissolve |
223
+ | `n`/`Esc` | Cancel |
224
+
225
+ **When to use:**
226
+ - A condensed summary is too lossy — you want the original finer-grained summaries back
227
+ - A corrupted condensed node needs to be removed so its parents can be individually repaired
228
+ - You want to re-do a condensation after improving the leaf summaries
229
+
230
+ **Important:** Dissolving increases the number of context items and total token count. Check the context view afterward to verify you haven't exceeded the context window threshold.
231
+
232
+ ## CLI Subcommands
233
+
234
+ Each interactive operation also has a standalone CLI equivalent for scripting and batch operations.
235
+
236
+ ### `lcm-tui repair`
237
+
238
+ Finds and fixes corrupted summaries (those containing the `[LCM fallback summary]` marker from failed summarization attempts).
239
+
240
+ ```bash
241
+ # Scan a specific conversation (dry run)
242
+ lcm-tui repair 44
243
+
244
+ # Scan all conversations
245
+ lcm-tui repair --all
246
+
247
+ # Apply repairs
248
+ lcm-tui repair 44 --apply
249
+
250
+ # Repair a specific summary
251
+ lcm-tui repair 44 --summary-id sum_abc123 --apply
252
+ ```
253
+
254
+ The repair process:
255
+ 1. Identifies corrupted summaries by scanning for the fallback marker
256
+ 2. Orders them bottom-up: leaves first (in context ordinal order), then condensed nodes by ascending depth
257
+ 3. Reconstructs source material from linked messages (leaves) or child summaries (condensed)
258
+ 4. Resolves `previous_context` for each node (for deduplication in the prompt)
259
+ 5. Sends to Anthropic API with the appropriate depth prompt
260
+ 6. Updates the database in a single transaction
261
+
262
+ | Flag | Description |
263
+ |------|-------------|
264
+ | `--apply` | Write repairs to database (default: dry run) |
265
+ | `--all` | Scan all conversations |
266
+ | `--summary-id <id>` | Target a specific summary |
267
+ | `--verbose` | Show content hashes and previews |
268
+
269
+ ### `lcm-tui rewrite`
270
+
271
+ Re-summarizes summaries using current depth-aware prompts. Unlike repair, this works on any summary, not just corrupted ones.
272
+
273
+ ```bash
274
+ # Rewrite a single summary (dry run)
275
+ lcm-tui rewrite 44 --summary sum_abc123
276
+
277
+ # Rewrite all depth-0 summaries
278
+ lcm-tui rewrite 44 --depth 0 --apply
279
+
280
+ # Rewrite everything bottom-up
281
+ lcm-tui rewrite 44 --all --apply --diff
282
+
283
+ # Use custom prompt templates
284
+ lcm-tui rewrite 44 --all --apply --prompt-dir ~/.config/lcm-tui/prompts
285
+ ```
286
+
287
+ | Flag | Description |
288
+ |------|-------------|
289
+ | `--summary <id>` | Rewrite a single summary |
290
+ | `--depth <n>` | Rewrite all summaries at depth N |
291
+ | `--all` | Rewrite all summaries (bottom-up by depth, then timestamp) |
292
+ | `--apply` | Write changes to database |
293
+ | `--dry-run` | Show before/after without writing (default) |
294
+ | `--diff` | Show unified diff |
295
+ | `--model <model>` | Anthropic model (default: `claude-sonnet-4-20250514`) |
296
+ | `--prompt-dir <path>` | Custom prompt template directory |
297
+ | `--timestamps` | Inject timestamps into source text (default: true) |
298
+ | `--tz <timezone>` | Timezone for timestamps (default: system local) |
299
+
300
+ Exactly one of `--summary`, `--depth`, or `--all` is required.
301
+
302
+ ### `lcm-tui dissolve`
303
+
304
+ Reverses a condensation, restoring parent summaries to the active context.
305
+
306
+ ```bash
307
+ # Preview (dry run)
308
+ lcm-tui dissolve 44 --summary-id sum_abc123
309
+
310
+ # Execute
311
+ lcm-tui dissolve 44 --summary-id sum_abc123 --apply
312
+
313
+ # Keep the condensed summary record (don't purge from DB)
314
+ lcm-tui dissolve 44 --summary-id sum_abc123 --apply --purge=false
315
+ ```
316
+
317
+ | Flag | Description |
318
+ |------|-------------|
319
+ | `--summary-id <id>` | Condensed summary to dissolve (required) |
320
+ | `--apply` | Execute changes |
321
+ | `--purge` | Also delete the condensed summary record (default: true) |
322
+
323
+ ### `lcm-tui transplant`
324
+
325
+ Deep-copies a summary DAG from one conversation to another. Used when an agent gets a new conversation (session rollover) but you want to carry forward summaries from the old one.
326
+
327
+ ```bash
328
+ # Preview what would be copied
329
+ lcm-tui transplant 18 653
330
+
331
+ # Execute
332
+ lcm-tui transplant 18 653 --apply
333
+ ```
334
+
335
+ The transplant:
336
+ 1. Identifies all summary context items in the source conversation
337
+ 2. Recursively collects the full DAG (all ancestor summaries)
338
+ 3. Deep-copies every summary with new IDs, owned by the target conversation
339
+ 4. Deep-copies all linked messages and message_parts with new IDs
340
+ 5. Rewires summary_messages and summary_parents edges
341
+ 6. Prepends transplanted summaries to the target's context (existing items shift)
342
+ 7. Detects duplicates via content SHA256 and aborts if any match
343
+
344
+ Everything runs in a single transaction.
345
+
346
+ | Flag | Description |
347
+ |------|-------------|
348
+ | `--apply` | Execute transplant |
349
+ | `--dry-run` | Show what would be transplanted (default) |
350
+
351
+ ### `lcm-tui prompts`
352
+
353
+ Manage and inspect depth-aware prompt templates. Templates control how the LLM summarizes at each depth level.
354
+
355
+ ```bash
356
+ # List active template sources (embedded vs filesystem override)
357
+ lcm-tui prompts --list
358
+
359
+ # Export default templates to filesystem for customization
360
+ lcm-tui prompts --export # default: ~/.config/lcm-tui/prompts/
361
+ lcm-tui prompts --export /path/to/my/prompts
362
+
363
+ # Show a specific template's content
364
+ lcm-tui prompts --show leaf
365
+
366
+ # Diff a filesystem override against the embedded default
367
+ lcm-tui prompts --diff condensed-d1
368
+
369
+ # Render a template with test variables
370
+ lcm-tui prompts --render leaf --target-tokens 800
371
+ ```
372
+
373
+ | Flag | Description |
374
+ |------|-------------|
375
+ | `--list` | Show which templates are active and their source |
376
+ | `--export [dir]` | Export embedded defaults to filesystem |
377
+ | `--show <name>` | Print the active template content |
378
+ | `--diff <name>` | Unified diff between override and embedded default |
379
+ | `--render <name>` | Render template with provided variables |
380
+ | `--prompt-dir <dir>` | Custom prompt template directory |
381
+
382
+ **Template names:** `leaf`, `condensed-d1`, `condensed-d2`, `condensed-d3` (`.tmpl` suffix optional).
383
+
384
+ **Customization workflow:**
385
+ 1. `lcm-tui prompts --export` to get the defaults
386
+ 2. Edit the templates in `~/.config/lcm-tui/prompts/`
387
+ 3. `lcm-tui prompts --diff condensed-d1` to verify changes
388
+ 4. Templates are automatically picked up by rewrite/repair operations
389
+
390
+ ## Depth-Aware Prompt Templates
391
+
392
+ The TUI uses four distinct prompt templates, one per depth level. This matches the plugin's depth-dispatched summarization strategy:
393
+
394
+ | Template | Depth | Strategy | Receives `previous_context` |
395
+ |----------|-------|----------|-----------------------------|
396
+ | `leaf.tmpl` | d0 | Narrative preservation with timestamps, file tracking | Yes |
397
+ | `condensed-d1.tmpl` | d1 | Chronological session narrative, delta-oriented (avoids repeating previous context) | Yes |
398
+ | `condensed-d2.tmpl` | d2 | Arc-focused: goal → outcome → what carries forward. Self-contained. | No |
399
+ | `condensed-d3.tmpl` | d3+ | Maximum abstraction. Durable context only. Self-contained. | No |
400
+
401
+ **d0/d1** summaries receive `previous_context` (the content of the preceding summary at the same depth) so they can avoid repeating information. **d2+** summaries are self-contained — they're designed to be independently useful for `lcm_expand_query` retrieval without requiring sibling context.
402
+
403
+ All templates end with an `"Expand for details about:"` footer listing topics available for deeper retrieval via the agent tools.
404
+
405
+ ## Authentication
406
+
407
+ The TUI needs an Anthropic API key for rewrite and repair operations. It resolves credentials in this order:
408
+
409
+ 1. `ANTHROPIC_API_KEY` environment variable
410
+ 2. OpenClaw config (`~/.openclaw/openclaw.json`) — reads the `anthropic:default` auth profile mode
411
+ 3. OpenClaw env file
412
+ 4. `~/.zshrc` export
413
+ 5. Various credential file candidates under `~/.openclaw/`
414
+
415
+ If the auth profile mode is `oauth` (not `api_key`), the TUI cannot use it — set `ANTHROPIC_API_KEY` explicitly for repair/rewrite commands.
416
+
417
+ ## Database
418
+
419
+ The TUI operates directly on the SQLite database at `~/.openclaw/lcm.db`. All write operations (rewrite, dissolve, repair, transplant) use transactions. Changes take effect on the next conversation turn — the running OpenClaw instance picks up database changes automatically.
420
+
421
+ **Backup recommendation:** Before batch operations (repair `--all`, rewrite `--all`, transplant), copy the database:
422
+
423
+ ```bash
424
+ cp ~/.openclaw/lcm.db ~/.openclaw/lcm.db.bak-$(date +%Y%m%d)
425
+ ```
426
+
427
+ ## Troubleshooting
428
+
429
+ **"No LCM summaries found"** — The session may not have an associated conversation in the LCM database. Check that the `conv_id` column shows a non-zero value in the session list. Sessions without LCM tracking won't have summaries.
430
+
431
+ **Rewrite returns empty/bad content** — Check the API key is valid and the model is accessible. The TUI uses `claude-sonnet-4-20250514` by default; override with `--model` if needed.
432
+
433
+ **Dissolve fails with "not condensed"** — Only condensed summaries (depth > 0) can be dissolved. Leaf summaries have no parent summaries to restore.
434
+
435
+ **Transplant aborts with duplicates** — The target conversation already has summaries with identical content hashes. This prevents accidental double-transplants. If intentional, delete the duplicates from the target first.
436
+
437
+ **Token count discrepancies** — The TUI estimates tokens as `len(content) / 4`. This is a rough heuristic, not a precise tokenizer count. The plugin uses the same estimate for consistency.