@@ -1,61 +1,158 @@
11 ---
22 name: debug
33 description: Debug mini-coder issues by analyzing session logs and database entries. Access error logs, API call logs, and session history from the database.
4+allowed-tools: shell
45 ---
56
67 # debug
78
89 Use this skill when the user needs to debug mini-coder issues, investigate errors, or audit API logs and session history.
910
10-The `/debug` command provides access to:
11+## Database location
1112
12-- **Error logs** – exceptions and runtime errors from a session
13-- **API logs** – LLM API calls, model routing, context pruning, and provider events
14-- **Session data** – message history, model settings, and session metadata
13+```
14+~/.config/mini-coder/sessions.db
15+```
16+
17+SQLite database with a `logs` table keyed by `session_id`.
1518
16-## Commands
19+## Schema
1720
21+```sql
22+CREATE TABLE logs (
23+ id INTEGER PRIMARY KEY AUTOINCREMENT,
24+ session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
25+ level TEXT NOT NULL, -- "api" | "error"
26+ timestamp INTEGER NOT NULL, -- Unix ms
27+ data TEXT NOT NULL -- JSON: { event: string, data: object }
28+)
1829 ```
19-/debug [session-id] Show debug info for current or specified session
20-/debug errors [session-id] Show only error logs for a session
21-/debug api [session-id] Show only API logs for a session
22-/debug sessions List all sessions with metadata
30+
31+## Log levels
32+
33+| Level | When written |
34+| ------- | -------------------------------------------------- |
35+| `api` | Every LLM turn lifecycle event (see events below) |
36+| `error` | Caught exceptions, API failures, validation errors |
37+
38+## API event reference (post-v0.x)
39+
40+These are the events logged after the noise-reduction pass. Expect ~10 rows per turn:
41+
42+| Event | Key fields in `data` | Purpose |
43+| ---------------------------- | ------------------------------------------------------------ | --------------------------------- |
44+| `turn start` | `modelString`, `messageCount`, `reasoningSummaryRequested` | Start of a user→LLM turn |
45+| `turn complete` | `newMessagesCount`, `inputTokens`, `outputTokens` | End of turn with token usage |
46+| `turn error` | error fields (sanitized) | Turn failed |
47+| `turn context pre-prune` | `messageCount`, `totalBytes`, `roleBreakdown`, `toolResults` | Context snapshot before pruning |
48+| `turn context post-prune` | same shape as pre-prune | Context snapshot after pruning |
49+| `step finish` | `usage`, `finishReason`, `isContinued` | Each reasoning step within a turn |
50+| `stream chunk` (tool-call) | `type:"tool-call"`, `toolCallId`, `toolName`, `isError` | A tool was invoked |
51+| `stream chunk` (tool-result) | `type:"tool-result"`, `toolCallId`, `toolName`, `isError` | Tool result received |
52+
53+> Note: Older sessions in the DB may also contain `Provider Request`, `prompt caching configured`, and high-volume `stream chunk` events (`tool-input-delta`, `start-step`, etc.) — these were removed in a logging cleanup. The queries below filter for the current event set.
54+
55+## Useful shell queries
56+
57+**Recent sessions:**
58+
59+```bash
60+bun -e "
61+import { getDb } from './src/session/db/connection.ts';
62+const db = getDb();
63+db.prepare('SELECT id, created_at, updated_at FROM sessions ORDER BY updated_at DESC LIMIT 10').all().forEach(r => console.log(r));
64+"
65+```
66+
67+**Log counts per level for a session:**
68+
69+```bash
70+SESSION_ID=<id>
71+bun -e "
72+import { getDb } from './src/session/db/connection.ts';
73+const db = getDb();
74+const rows = db.prepare('SELECT level, COUNT(*) as n FROM logs WHERE session_id = ? GROUP BY level').all('$SESSION_ID');
75+console.log(rows);
76+"
77+```
78+
79+**All API events for current session (chronological):**
80+
81+```bash
82+bun -e "
83+import { getDb } from './src/session/db/connection.ts';
84+const db = getDb();
85+const rows = db.prepare('SELECT timestamp, data FROM logs WHERE session_id = ? AND level = ? ORDER BY timestamp ASC').all('<session-id>', 'api');
86+for (const r of rows) {
87+ const d = JSON.parse(r.data);
88+ console.log(new Date(r.timestamp).toISOString(), d.event, JSON.stringify(d.data));
89+}
90+"
2391 ```
2492
25-## Example usage
93+**Error logs only:**
2694
95+```bash
96+bun -e "
97+import { getDb } from './src/session/db/connection.ts';
98+const db = getDb();
99+const rows = db.prepare('SELECT timestamp, data FROM logs WHERE session_id = ? AND level = ? ORDER BY timestamp ASC').all('<session-id>', 'error');
100+rows.forEach(r => console.log(new Date(r.timestamp).toISOString(), JSON.parse(r.data)));
101+"
27102 ```
28-/debug # Show current session logs and metadata
29-/debug abc123 # Show logs for session abc123
30-/debug errors # Show only errors from current session
31-/debug api dev-session # Show API calls from dev-session
32-/debug sessions # List all sessions
103+
104+**Token usage across turns (current session):**
105+
106+```bash
107+bun -e "
108+import { getDb } from './src/session/db/connection.ts';
109+const db = getDb();
110+const rows = db.prepare(\"SELECT data FROM logs WHERE session_id = ? AND level = 'api' ORDER BY timestamp ASC\").all('<session-id>');
111+for (const r of rows) {
112+ const d = JSON.parse(r.data);
113+ if (d.event === 'turn complete') console.log(d.data);
114+}
115+"
33116 ```
34117
35-## What you'll see
118+**Context pressure (pre vs post prune):**
36119
37-**Error logs** include:
120+```bash
121+bun -e "
122+import { getDb } from './src/session/db/connection.ts';
123+const db = getDb();
124+const rows = db.prepare(\"SELECT timestamp, data FROM logs WHERE session_id = ? AND level = 'api' AND data LIKE '%prune%' ORDER BY timestamp ASC\").all('<session-id>');
125+rows.forEach(r => console.log(new Date(r.timestamp).toISOString(), JSON.parse(r.data)));
126+"
127+```
38128
39-- Caught exceptions with context
40-- API errors and retries
41-- Validation failures
42-- Uncaught exceptions
129+**Tool calls in a session:**
43130
44-**API logs** include:
131+```bash
132+bun -e "
133+import { getDb } from './src/session/db/connection.ts';
134+const db = getDb();
135+const rows = db.prepare(\"SELECT timestamp, data FROM logs WHERE session_id = ? AND level = 'api' AND data LIKE '%tool-call%' ORDER BY timestamp ASC\").all('<session-id>');
136+rows.forEach(r => { const d = JSON.parse(r.data); console.log(new Date(r.timestamp).toISOString(), d.data.toolName); });
137+"
138+```
45139
46-- Provider requests and responses
47-- Token usage and model routing
48-- Context pruning statistics
49-- Tool call handling
50-- Prompt caching events
140+## Finding the current session ID
51141
52-**Session metadata** shows:
142+The session ID is stored in the `settings` table or you can get the most recently active session:
53143
54-- Session ID, creation time, working directory
55-- Model and settings used
56-- Message count and turn history
57-- Last update time
144+```bash
145+bun -e "
146+import { getDb } from './src/session/db/connection.ts';
147+const db = getDb();
148+const s = db.prepare('SELECT id FROM sessions ORDER BY updated_at DESC LIMIT 1').get();
149+console.log(s?.id);
150+"
151+```
58152
59-## Integration with mini-coder
153+## Integration with mini-coder code
60154
61-The logging system stores all errors and API events in the SQLite database (`~/.config/mini-coder/sessions.db`) in the `logs` table, keyed by session ID. This allows persistent debugging and audit trails across multiple sessions.
155+- **`src/logging/context.ts`** — `logApiEvent(event, data)` and `logError(err, context)` write to the DB
156+- **`src/session/db/logs-repo.ts`** — `LogsRepo` class: `write()`, `getLogs()`, `deleteOldLogs()`, `deleteSessionLogs()`
157+- **`src/session/db/connection.ts`** — `getDb()` returns the singleton Bun SQLite instance
158+- Data is sanitized before write: strips `requestBodyValues`, `responseBody`, `responseHeaders`, `stack`