tracebox 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/LICENSE +21 -0
- package/README.md +85 -0
- package/dist/atf.js +23 -0
- package/dist/browser.js +21 -0
- package/dist/cli.js +102 -0
- package/dist/collector.js +31 -0
- package/dist/commands/install.js +50 -0
- package/dist/commands/list.js +14 -0
- package/dist/commands/show.js +32 -0
- package/dist/commands/stats.js +12 -0
- package/dist/commands/ui.js +35 -0
- package/dist/format.js +10 -0
- package/dist/ingest/hooks.js +80 -0
- package/dist/ingest/ingest.js +84 -0
- package/dist/ingest/transcripts.js +58 -0
- package/dist/paths.js +26 -0
- package/dist/server/server.js +94 -0
- package/dist/server/static.js +35 -0
- package/dist/server/store-api.js +52 -0
- package/dist/store.js +159 -0
- package/dist/version.js +1 -0
- package/dist/web/assets/index-CieliPte.css +1 -0
- package/dist/web/assets/index-zGenkbJL.js +49 -0
- package/dist/web/index.html +20 -0
- package/package.json +64 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Victor LG
|
|
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
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
# tracebox
|
|
2
|
+
|
|
3
|
+
**See what your coding agent actually did.** tracebox records every Claude Code
|
|
4
|
+
session — tools called, files touched, commands run, tokens spent — into an
|
|
5
|
+
auditable timeline, and flags where the agent *claimed* an edit that never
|
|
6
|
+
landed.
|
|
7
|
+
|
|
8
|
+
[](https://www.npmjs.com/package/tracebox)
|
|
9
|
+
[](./LICENSE)
|
|
10
|
+

|
|
11
|
+
|
|
12
|
+
100% local. Zero telemetry. Your session data never leaves your machine.
|
|
13
|
+
|
|
14
|
+

|
|
15
|
+
|
|
16
|
+
## Install
|
|
17
|
+
|
|
18
|
+
Requires Node.js ≥ 20.
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
npm install -g tracebox
|
|
22
|
+
|
|
23
|
+
tracebox install # registers hooks in ~/.claude/settings.json
|
|
24
|
+
tracebox list # your past sessions are already there
|
|
25
|
+
tracebox ui # open the web UI
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Or run without installing:
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
npx tracebox list
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
### From source
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
git clone https://github.com/VictorLG98/tracebox.git && cd tracebox
|
|
38
|
+
npm install && npm run build && npm link
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Commands
|
|
42
|
+
|
|
43
|
+
| Command | What it does |
|
|
44
|
+
|---|---|
|
|
45
|
+
| `tracebox install` | Register collection hooks (Claude Code) |
|
|
46
|
+
| `tracebox list` | Recent sessions: project, started, events, tokens |
|
|
47
|
+
| `tracebox show <id>` | Timeline of one session |
|
|
48
|
+
| `tracebox stats` | Token usage by day and by project |
|
|
49
|
+
| `tracebox ui` | Open the local web UI (Ctrl-C to stop) |
|
|
50
|
+
|
|
51
|
+
## Web UI
|
|
52
|
+
|
|
53
|
+
`tracebox ui` ingests the latest data, starts a local server on `127.0.0.1`
|
|
54
|
+
(no auth, no network — it binds loopback only), and opens your browser. It
|
|
55
|
+
serves a small single-page app with two views:
|
|
56
|
+
|
|
57
|
+
- **Session list** — project, date, duration, tokens, files touched, and a
|
|
58
|
+
badge on sessions with a claims-vs-reality discrepancy.
|
|
59
|
+
- **Session view** — three zones: a summary header, a filterable/searchable
|
|
60
|
+
timeline (subagent events nested), and a **claims-vs-reality** panel.
|
|
61
|
+
|
|
62
|
+
### Claims vs. reality
|
|
63
|
+
|
|
64
|
+
For each file the agent tried to edit, the panel shows whether the edit
|
|
65
|
+
**succeeded** (✓), **failed** (✗), or was **attempted** with no recorded
|
|
66
|
+
outcome (⚠). This is a structural, deterministic comparison — attempts come
|
|
67
|
+
from the agent's `Edit`/`Write` calls, outcomes come from the hook results.
|
|
68
|
+
No text analysis, no guessing.
|
|
69
|
+
|
|
70
|
+
The "reality" signal requires hooks (`tracebox install`). Sessions recorded
|
|
71
|
+
before hooks were installed still show attempted edits, marked ⚠ with a
|
|
72
|
+
"hooks not installed" note — never a blank screen.
|
|
73
|
+
|
|
74
|
+
## How it works
|
|
75
|
+
|
|
76
|
+
Claude Code hooks append raw events to `~/.tracebox/raw/` (the collector
|
|
77
|
+
never fails and never slows your session). Transcripts under
|
|
78
|
+
`~/.claude/projects/` are parsed on demand for token usage — which is why
|
|
79
|
+
sessions from before you installed tracebox show up too. Everything is
|
|
80
|
+
normalized into SQLite at `~/.tracebox/db.sqlite`.
|
|
81
|
+
|
|
82
|
+
## Status
|
|
83
|
+
|
|
84
|
+
MVP: Claude Code only. The ingestion layer is adapter-based — other agents
|
|
85
|
+
are on the roadmap.
|
package/dist/atf.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
export function makeUniqKey(...parts) {
|
|
3
|
+
return createHash('sha1').update(parts.join('|')).digest('hex');
|
|
4
|
+
}
|
|
5
|
+
export function classifyTool(toolName, input) {
|
|
6
|
+
const inp = (input ?? {});
|
|
7
|
+
switch (toolName) {
|
|
8
|
+
case 'Bash':
|
|
9
|
+
return { type: 'command', detail: String(inp.command ?? '') };
|
|
10
|
+
case 'Read':
|
|
11
|
+
return { type: 'file_touch', detail: String(inp.file_path ?? ''), touch: { path: String(inp.file_path ?? ''), action: 'read' } };
|
|
12
|
+
case 'Edit':
|
|
13
|
+
case 'NotebookEdit':
|
|
14
|
+
return { type: 'file_touch', detail: String(inp.file_path ?? inp.notebook_path ?? ''), touch: { path: String(inp.file_path ?? inp.notebook_path ?? ''), action: 'edit' } };
|
|
15
|
+
case 'Write':
|
|
16
|
+
return { type: 'file_touch', detail: String(inp.file_path ?? ''), touch: { path: String(inp.file_path ?? ''), action: 'write' } };
|
|
17
|
+
case 'Task':
|
|
18
|
+
case 'Agent':
|
|
19
|
+
return { type: 'subagent_spawn', detail: String(inp.description ?? String(inp.prompt ?? '').slice(0, 80)) };
|
|
20
|
+
default:
|
|
21
|
+
return { type: 'tool_call', detail: JSON.stringify(inp).slice(0, 120) };
|
|
22
|
+
}
|
|
23
|
+
}
|
package/dist/browser.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
export function browserOpenCommand(platform, url) {
|
|
3
|
+
if (platform === 'darwin')
|
|
4
|
+
return { cmd: 'open', args: [url] };
|
|
5
|
+
if (platform === 'win32')
|
|
6
|
+
return { cmd: 'cmd', args: ['/c', 'start', '', url] };
|
|
7
|
+
return { cmd: 'xdg-open', args: [url] };
|
|
8
|
+
}
|
|
9
|
+
/** Best-effort browser open. Never throws — a failed spawn is swallowed so the
|
|
10
|
+
* command still prints the URL and stays up. */
|
|
11
|
+
export function openBrowser(url) {
|
|
12
|
+
try {
|
|
13
|
+
const { cmd, args } = browserOpenCommand(process.platform, url);
|
|
14
|
+
const child = spawn(cmd, args, { stdio: 'ignore', detached: true });
|
|
15
|
+
child.on('error', () => { });
|
|
16
|
+
child.unref();
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
/* ignore */
|
|
20
|
+
}
|
|
21
|
+
}
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { collect } from './collector.js';
|
|
3
|
+
import { cmdList } from './commands/list.js';
|
|
4
|
+
import { cmdShow } from './commands/show.js';
|
|
5
|
+
import { cmdStats } from './commands/stats.js';
|
|
6
|
+
import { cmdInstall } from './commands/install.js';
|
|
7
|
+
import { cmdUi } from './commands/ui.js';
|
|
8
|
+
import { dbPath, traceboxHome } from './paths.js';
|
|
9
|
+
import { VERSION } from './version.js';
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import { realpathSync } from 'node:fs';
|
|
12
|
+
import { fileURLToPath } from 'node:url';
|
|
13
|
+
const HELP = `tracebox ${VERSION} — local trace recorder for coding agent sessions
|
|
14
|
+
|
|
15
|
+
Usage:
|
|
16
|
+
tracebox install register hooks in ~/.claude/settings.json
|
|
17
|
+
tracebox list recent sessions
|
|
18
|
+
tracebox show <id> session timeline
|
|
19
|
+
tracebox stats token usage aggregates
|
|
20
|
+
tracebox ui open the local web UI (Ctrl-C to stop)
|
|
21
|
+
tracebox collect (internal) hook entry point, reads stdin
|
|
22
|
+
`;
|
|
23
|
+
async function withStore(fn) {
|
|
24
|
+
const [{ openStore }, { runIngest }] = await Promise.all([
|
|
25
|
+
import('./store.js'),
|
|
26
|
+
import('./ingest/ingest.js'),
|
|
27
|
+
]);
|
|
28
|
+
fs.mkdirSync(traceboxHome(), { recursive: true });
|
|
29
|
+
const store = openStore(dbPath());
|
|
30
|
+
try {
|
|
31
|
+
runIngest(store);
|
|
32
|
+
return fn(store);
|
|
33
|
+
}
|
|
34
|
+
finally {
|
|
35
|
+
store.close();
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
export async function main(argv) {
|
|
39
|
+
const [cmd] = argv;
|
|
40
|
+
switch (cmd) {
|
|
41
|
+
case 'collect':
|
|
42
|
+
await collect(process.stdin);
|
|
43
|
+
return 0; // contract: never non-zero
|
|
44
|
+
case 'install':
|
|
45
|
+
return cmdInstall();
|
|
46
|
+
case 'list':
|
|
47
|
+
await withStore((s) => cmdList(s));
|
|
48
|
+
return 0;
|
|
49
|
+
case 'show': {
|
|
50
|
+
const idPrefix = argv[1];
|
|
51
|
+
if (!idPrefix) {
|
|
52
|
+
console.error('Usage: tracebox show <session-id-prefix>');
|
|
53
|
+
return 1;
|
|
54
|
+
}
|
|
55
|
+
return await withStore((s) => cmdShow(s, idPrefix));
|
|
56
|
+
}
|
|
57
|
+
case 'stats':
|
|
58
|
+
await withStore((s) => cmdStats(s));
|
|
59
|
+
return 0;
|
|
60
|
+
case 'ui':
|
|
61
|
+
return await cmdUi();
|
|
62
|
+
case '--version':
|
|
63
|
+
case '-v':
|
|
64
|
+
console.log(VERSION);
|
|
65
|
+
return 0;
|
|
66
|
+
case 'help':
|
|
67
|
+
case '--help':
|
|
68
|
+
case undefined:
|
|
69
|
+
console.log(HELP);
|
|
70
|
+
return 0;
|
|
71
|
+
default:
|
|
72
|
+
console.error(`Unknown command: ${cmd}\n\n${HELP}`);
|
|
73
|
+
return 1;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
// Detect direct execution robustly, including when invoked via a symlinked bin
|
|
77
|
+
// (npm install / npm link put a symlink on PATH, so argv[1] is the link path
|
|
78
|
+
// while import.meta.url is the resolved real path — a bare string compare fails).
|
|
79
|
+
const isDirectRun = (() => {
|
|
80
|
+
const entry = process.argv[1];
|
|
81
|
+
if (!entry)
|
|
82
|
+
return false;
|
|
83
|
+
const self = fileURLToPath(import.meta.url);
|
|
84
|
+
try {
|
|
85
|
+
return realpathSync(entry) === self;
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
return entry === self;
|
|
89
|
+
}
|
|
90
|
+
})();
|
|
91
|
+
if (isDirectRun) {
|
|
92
|
+
main(process.argv.slice(2))
|
|
93
|
+
.then((code) => {
|
|
94
|
+
process.exitCode = code;
|
|
95
|
+
})
|
|
96
|
+
.catch((err) => {
|
|
97
|
+
const isCollect = process.argv[2] === 'collect';
|
|
98
|
+
if (!isCollect)
|
|
99
|
+
console.error(err instanceof Error ? err.message : String(err));
|
|
100
|
+
process.exitCode = isCollect ? 0 : 1;
|
|
101
|
+
});
|
|
102
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { rawLogDir } from './paths.js';
|
|
4
|
+
const MAX_RAW_BYTES = 1_000_000;
|
|
5
|
+
export async function collect(stdin) {
|
|
6
|
+
try {
|
|
7
|
+
const chunks = [];
|
|
8
|
+
for await (const c of stdin)
|
|
9
|
+
chunks.push(Buffer.from(c));
|
|
10
|
+
const text = Buffer.concat(chunks).toString('utf8').trim();
|
|
11
|
+
if (!text)
|
|
12
|
+
return;
|
|
13
|
+
let payload;
|
|
14
|
+
try {
|
|
15
|
+
payload = JSON.parse(text);
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
payload = { unparsed: text.slice(0, MAX_RAW_BYTES) };
|
|
19
|
+
}
|
|
20
|
+
const isoNow = new Date().toISOString();
|
|
21
|
+
const line = JSON.stringify({ received_at: isoNow, payload }) + '\n';
|
|
22
|
+
const dir = rawLogDir();
|
|
23
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
24
|
+
const file = path.join(dir, `hooks-${isoNow.slice(0, 10)}.jsonl`);
|
|
25
|
+
fs.appendFileSync(file, line);
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
// Contract: the collector runs inside the user's agent session.
|
|
29
|
+
// It must never throw, never block, never break the session.
|
|
30
|
+
}
|
|
31
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { claudeSettingsPath, traceboxHome } from '../paths.js';
|
|
4
|
+
const HOOK_EVENTS = ['SessionStart', 'PreToolUse', 'PostToolUse', 'Stop'];
|
|
5
|
+
const COLLECT_ENTRY = { hooks: [{ type: 'command', command: 'tracebox collect' }] };
|
|
6
|
+
export function buildHookConfig(settings) {
|
|
7
|
+
const out = structuredClone(settings);
|
|
8
|
+
const hooks = out.hooks ?? {};
|
|
9
|
+
out.hooks = hooks;
|
|
10
|
+
for (const ev of HOOK_EVENTS) {
|
|
11
|
+
const entries = Array.isArray(hooks[ev]) ? hooks[ev] : [];
|
|
12
|
+
hooks[ev] = entries;
|
|
13
|
+
if (!JSON.stringify(entries).includes('tracebox collect')) {
|
|
14
|
+
entries.push(structuredClone(COLLECT_ENTRY));
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
return out;
|
|
18
|
+
}
|
|
19
|
+
export function cmdInstall() {
|
|
20
|
+
try {
|
|
21
|
+
fs.mkdirSync(traceboxHome(), { recursive: true });
|
|
22
|
+
const file = claudeSettingsPath();
|
|
23
|
+
let settings = {};
|
|
24
|
+
try {
|
|
25
|
+
const raw = fs.readFileSync(file, 'utf8');
|
|
26
|
+
try {
|
|
27
|
+
settings = JSON.parse(raw);
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
console.error(`install aborted: ${file} exists but is not valid JSON — fix or remove it first`);
|
|
31
|
+
return 1;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
catch (e) {
|
|
35
|
+
if (e.code !== 'ENOENT')
|
|
36
|
+
throw e;
|
|
37
|
+
// file missing: proceed with empty settings
|
|
38
|
+
}
|
|
39
|
+
const updated = buildHookConfig(settings);
|
|
40
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
41
|
+
fs.writeFileSync(file, JSON.stringify(updated, null, 2) + '\n');
|
|
42
|
+
console.log(`tracebox hooks registered in ${file}`);
|
|
43
|
+
console.log('Past sessions are already visible: try `tracebox list`');
|
|
44
|
+
return 0;
|
|
45
|
+
}
|
|
46
|
+
catch (err) {
|
|
47
|
+
console.error(`install failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
48
|
+
return 1;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { formatTokens, pad } from '../format.js';
|
|
3
|
+
export function cmdList(store) {
|
|
4
|
+
const rows = store.listSessions();
|
|
5
|
+
console.log(`${pad('SESSION', 10)}${pad('PROJECT', 22)}${pad('STARTED', 18)}${pad('EVENTS', 8)}TOKENS`);
|
|
6
|
+
for (const r of rows) {
|
|
7
|
+
const started = (r.started_at ?? '').slice(0, 16).replace('T', ' ');
|
|
8
|
+
const project = r.project_dir ? path.basename(r.project_dir) : '(unknown)';
|
|
9
|
+
console.log(`${pad(r.id.slice(0, 8), 10)}${pad(project, 22)}${pad(started, 18)}${pad(String(r.event_count), 8)}${formatTokens(r.total_tokens)}`);
|
|
10
|
+
}
|
|
11
|
+
if (rows.length === 0) {
|
|
12
|
+
console.log('(no sessions yet — run some agent sessions or check ~/.claude/projects)');
|
|
13
|
+
}
|
|
14
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { formatTokens, pad } from '../format.js';
|
|
2
|
+
function duration(start, end) {
|
|
3
|
+
if (!start || !end)
|
|
4
|
+
return '?';
|
|
5
|
+
const ms = new Date(end).getTime() - new Date(start).getTime();
|
|
6
|
+
if (Number.isNaN(ms) || ms < 0)
|
|
7
|
+
return '?';
|
|
8
|
+
const mins = Math.round(ms / 60_000);
|
|
9
|
+
return mins >= 60 ? `${Math.floor(mins / 60)}h${mins % 60}m` : `${mins}m`;
|
|
10
|
+
}
|
|
11
|
+
export function cmdShow(store, idPrefix) {
|
|
12
|
+
const s = store.findSession(idPrefix);
|
|
13
|
+
if (!s) {
|
|
14
|
+
console.error(`No session matching '${idPrefix}'. Try: tracebox list`);
|
|
15
|
+
return 1;
|
|
16
|
+
}
|
|
17
|
+
const tokens = store.sessionTokens(s.id);
|
|
18
|
+
console.log(`session ${s.id}`);
|
|
19
|
+
console.log(`project ${s.project_dir ?? '(unknown)'}`);
|
|
20
|
+
console.log(`model ${s.model ?? '(unknown)'}`);
|
|
21
|
+
console.log(`duration ${duration(s.started_at, s.ended_at)}`);
|
|
22
|
+
console.log(`tokens ${formatTokens(tokens.input + tokens.output)} (in ${formatTokens(tokens.input)} / out ${formatTokens(tokens.output)} / cache-read ${formatTokens(tokens.cacheRead)})`);
|
|
23
|
+
console.log(`files ${store.fileTouchCount(s.id)} touched`);
|
|
24
|
+
console.log('');
|
|
25
|
+
for (const e of store.eventsForSession(s.id)) {
|
|
26
|
+
const time = e.ts.slice(11, 19);
|
|
27
|
+
const prefix = e.sidechain ? ' ↳ ' : '';
|
|
28
|
+
const tool = e.toolName ? `${e.toolName} ` : '';
|
|
29
|
+
console.log(`${time} ${prefix}${pad(e.type, 15)}${tool}${e.detail}`);
|
|
30
|
+
}
|
|
31
|
+
return 0;
|
|
32
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { formatTokens, pad } from '../format.js';
|
|
2
|
+
export function cmdStats(store) {
|
|
3
|
+
console.log('TOKENS BY DAY (last 14)');
|
|
4
|
+
for (const r of store.statsByDay()) {
|
|
5
|
+
console.log(` ${pad(r.day, 12)}${formatTokens(r.tokens)}`);
|
|
6
|
+
}
|
|
7
|
+
console.log('');
|
|
8
|
+
console.log('TOKENS BY PROJECT');
|
|
9
|
+
for (const r of store.statsByProject()) {
|
|
10
|
+
console.log(` ${pad(r.project, 40)}${formatTokens(r.tokens)}`);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import { dbPath, traceboxHome } from '../paths.js';
|
|
3
|
+
export function runUi(deps) {
|
|
4
|
+
return new Promise((resolve) => {
|
|
5
|
+
deps.ingest();
|
|
6
|
+
deps.start().then(({ url, close }) => {
|
|
7
|
+
deps.log(`tracebox UI running at ${url} — press Ctrl-C to stop`);
|
|
8
|
+
deps.open(url);
|
|
9
|
+
deps.onStop(() => {
|
|
10
|
+
close();
|
|
11
|
+
resolve(0);
|
|
12
|
+
});
|
|
13
|
+
});
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
export async function cmdUi() {
|
|
17
|
+
const [{ openStore }, { runIngest }, { startServer }, { openBrowser }] = await Promise.all([
|
|
18
|
+
import('../store.js'),
|
|
19
|
+
import('../ingest/ingest.js'),
|
|
20
|
+
import('../server/server.js'),
|
|
21
|
+
import('../browser.js'),
|
|
22
|
+
]);
|
|
23
|
+
fs.mkdirSync(traceboxHome(), { recursive: true });
|
|
24
|
+
const store = openStore(dbPath());
|
|
25
|
+
return runUi({
|
|
26
|
+
ingest: () => runIngest(store),
|
|
27
|
+
start: async () => {
|
|
28
|
+
const { server, url } = await startServer(store);
|
|
29
|
+
return { url, close: () => { server.close(); store.close(); } };
|
|
30
|
+
},
|
|
31
|
+
open: (url) => openBrowser(url),
|
|
32
|
+
onStop: (fn) => process.once('SIGINT', fn),
|
|
33
|
+
log: (msg) => console.log(msg),
|
|
34
|
+
});
|
|
35
|
+
}
|
package/dist/format.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export function formatTokens(n) {
|
|
2
|
+
if (n >= 1_000_000)
|
|
3
|
+
return `${(n / 1_000_000).toFixed(1)}M`;
|
|
4
|
+
if (n >= 1_000)
|
|
5
|
+
return `${(n / 1_000).toFixed(1)}K`;
|
|
6
|
+
return String(n);
|
|
7
|
+
}
|
|
8
|
+
export function pad(s, w) {
|
|
9
|
+
return s.length >= w ? s.slice(0, w) : s.padEnd(w);
|
|
10
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { classifyTool, makeUniqKey } from '../atf.js';
|
|
2
|
+
export function classifyOutcomeSuccess(toolResponse) {
|
|
3
|
+
if (toolResponse == null)
|
|
4
|
+
return null;
|
|
5
|
+
if (typeof toolResponse === 'string') {
|
|
6
|
+
if (toolResponse.trim() === '')
|
|
7
|
+
return null;
|
|
8
|
+
return /^\s*error/i.test(toolResponse) ? false : true;
|
|
9
|
+
}
|
|
10
|
+
if (typeof toolResponse === 'object') {
|
|
11
|
+
const obj = toolResponse;
|
|
12
|
+
if ('error' in obj && obj.error)
|
|
13
|
+
return false;
|
|
14
|
+
return Object.keys(obj).length === 0 ? null : true;
|
|
15
|
+
}
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
export function normalizeHookLine(line) {
|
|
19
|
+
let rec;
|
|
20
|
+
try {
|
|
21
|
+
rec = JSON.parse(line);
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return null;
|
|
25
|
+
}
|
|
26
|
+
const p = rec?.payload;
|
|
27
|
+
const sessionId = p?.session_id;
|
|
28
|
+
const ts = rec?.received_at;
|
|
29
|
+
if (typeof sessionId !== 'string' || typeof ts !== 'string')
|
|
30
|
+
return null;
|
|
31
|
+
const base = { sessionId, ts, source: 'hook', sidechain: false };
|
|
32
|
+
const key = (...extra) => makeUniqKey(ts, sessionId, ...extra);
|
|
33
|
+
switch (p.hook_event_name) {
|
|
34
|
+
case 'SessionStart':
|
|
35
|
+
return {
|
|
36
|
+
events: [{ ...base, type: 'session_start', toolName: null, detail: String(p.cwd ?? ''), uniqKey: key('session_start') }],
|
|
37
|
+
touches: [],
|
|
38
|
+
session: { id: sessionId, ...(p.cwd ? { projectDir: String(p.cwd) } : {}), startedAt: ts },
|
|
39
|
+
};
|
|
40
|
+
case 'Stop':
|
|
41
|
+
return {
|
|
42
|
+
events: [{ ...base, type: 'session_end', toolName: null, detail: '', uniqKey: key('session_end') }],
|
|
43
|
+
touches: [],
|
|
44
|
+
session: { id: sessionId, endedAt: ts },
|
|
45
|
+
};
|
|
46
|
+
case 'PreToolUse': {
|
|
47
|
+
const toolName = String(p.tool_name ?? 'unknown');
|
|
48
|
+
const c = classifyTool(toolName, p.tool_input);
|
|
49
|
+
const uniqKey = key('pre', toolName, JSON.stringify(p.tool_input ?? null));
|
|
50
|
+
const events = [{ ...base, type: c.type, toolName, detail: c.detail, uniqKey }];
|
|
51
|
+
const touches = c.touch
|
|
52
|
+
? [{ sessionId, path: c.touch.path, action: c.touch.action, ts, uniqKey: makeUniqKey(uniqKey, 'touch') }]
|
|
53
|
+
: [];
|
|
54
|
+
return { events, touches, session: { id: sessionId } };
|
|
55
|
+
}
|
|
56
|
+
case 'PostToolUse': {
|
|
57
|
+
const toolName = String(p.tool_name ?? 'unknown');
|
|
58
|
+
const c = classifyTool(toolName, p.tool_input);
|
|
59
|
+
// Only file-mutating tools carry a claims-relevant outcome.
|
|
60
|
+
const isFileMutation = c.touch && (c.touch.action === 'edit' || c.touch.action === 'write');
|
|
61
|
+
if (!isFileMutation) {
|
|
62
|
+
return { events: [], touches: [], session: { id: sessionId } };
|
|
63
|
+
}
|
|
64
|
+
const rawResponse = JSON.stringify(p.tool_response ?? null).slice(0, 2000);
|
|
65
|
+
const uniqKey = makeUniqKey(ts, sessionId, 'post', toolName, c.touch.path);
|
|
66
|
+
const outcome = {
|
|
67
|
+
sessionId,
|
|
68
|
+
path: c.touch.path,
|
|
69
|
+
toolName,
|
|
70
|
+
success: classifyOutcomeSuccess(p.tool_response),
|
|
71
|
+
rawResponse,
|
|
72
|
+
ts,
|
|
73
|
+
uniqKey,
|
|
74
|
+
};
|
|
75
|
+
return { events: [], touches: [], session: { id: sessionId }, outcome };
|
|
76
|
+
}
|
|
77
|
+
default:
|
|
78
|
+
return { events: [], touches: [], session: { id: sessionId } };
|
|
79
|
+
}
|
|
80
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { rawLogDir, claudeProjectsDir } from '../paths.js';
|
|
4
|
+
import { normalizeHookLine } from './hooks.js';
|
|
5
|
+
import { normalizeTranscriptLine } from './transcripts.js';
|
|
6
|
+
function readLines(file) {
|
|
7
|
+
try {
|
|
8
|
+
return fs.readFileSync(file, 'utf8').split('\n').filter(Boolean);
|
|
9
|
+
}
|
|
10
|
+
catch {
|
|
11
|
+
return [];
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
function listFiles(dir, ext) {
|
|
15
|
+
try {
|
|
16
|
+
return fs.readdirSync(dir).filter((f) => f.endsWith(ext)).map((f) => path.join(dir, f));
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return [];
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
function ingestHooks(store) {
|
|
23
|
+
for (const file of listFiles(rawLogDir(), '.jsonl')) {
|
|
24
|
+
for (const line of readLines(file)) {
|
|
25
|
+
const norm = normalizeHookLine(line);
|
|
26
|
+
if (!norm)
|
|
27
|
+
continue;
|
|
28
|
+
if (norm.session)
|
|
29
|
+
store.upsertSession(norm.session);
|
|
30
|
+
for (const e of norm.events)
|
|
31
|
+
store.insertEvent(e);
|
|
32
|
+
for (const t of norm.touches)
|
|
33
|
+
store.insertFileTouch(t);
|
|
34
|
+
if (norm.outcome)
|
|
35
|
+
store.insertToolOutcome(norm.outcome);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
function ingestTranscripts(store) {
|
|
40
|
+
const projectDirs = (() => {
|
|
41
|
+
try {
|
|
42
|
+
const root = claudeProjectsDir();
|
|
43
|
+
return fs
|
|
44
|
+
.readdirSync(root, { withFileTypes: true })
|
|
45
|
+
.filter((d) => d.isDirectory())
|
|
46
|
+
.map((d) => path.join(root, d.name));
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
return [];
|
|
50
|
+
}
|
|
51
|
+
})();
|
|
52
|
+
for (const dir of projectDirs) {
|
|
53
|
+
for (const file of listFiles(dir, '.jsonl')) {
|
|
54
|
+
const norms = readLines(file)
|
|
55
|
+
.map(normalizeTranscriptLine)
|
|
56
|
+
.filter((n) => n !== null);
|
|
57
|
+
if (norms.length === 0)
|
|
58
|
+
continue;
|
|
59
|
+
for (const n of norms) {
|
|
60
|
+
if (n.session)
|
|
61
|
+
store.upsertSession(n.session);
|
|
62
|
+
if (n.usage)
|
|
63
|
+
store.insertTokenUsage(n.usage);
|
|
64
|
+
}
|
|
65
|
+
// Hook events are the primary source; transcripts only backfill sessions
|
|
66
|
+
// recorded before tracebox was installed. Claude Code writes one session
|
|
67
|
+
// per transcript file, so gating on the first found is safe. Events without
|
|
68
|
+
// a session are dropped (unattributable without a session).
|
|
69
|
+
const sessionId = norms.find((n) => n.session)?.session?.id;
|
|
70
|
+
if (sessionId && store.hookEventCount(sessionId) === 0) {
|
|
71
|
+
for (const n of norms) {
|
|
72
|
+
for (const e of n.events)
|
|
73
|
+
store.insertEvent(e);
|
|
74
|
+
for (const t of n.touches)
|
|
75
|
+
store.insertFileTouch(t);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
export function runIngest(store) {
|
|
82
|
+
ingestHooks(store);
|
|
83
|
+
ingestTranscripts(store);
|
|
84
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { classifyTool, makeUniqKey } from '../atf.js';
|
|
2
|
+
export function normalizeTranscriptLine(line) {
|
|
3
|
+
let obj;
|
|
4
|
+
try {
|
|
5
|
+
obj = JSON.parse(line);
|
|
6
|
+
}
|
|
7
|
+
catch {
|
|
8
|
+
return null;
|
|
9
|
+
}
|
|
10
|
+
const sessionId = obj?.sessionId;
|
|
11
|
+
const ts = obj?.timestamp;
|
|
12
|
+
if (typeof sessionId !== 'string' || typeof ts !== 'string')
|
|
13
|
+
return null;
|
|
14
|
+
const session = { id: sessionId, startedAt: ts, endedAt: ts };
|
|
15
|
+
if (typeof obj.cwd === 'string')
|
|
16
|
+
session.projectDir = obj.cwd;
|
|
17
|
+
const out = { events: [], touches: [], session };
|
|
18
|
+
if (obj.type !== 'assistant' || !obj.message)
|
|
19
|
+
return out;
|
|
20
|
+
const msg = obj.message;
|
|
21
|
+
if (typeof msg.model === 'string')
|
|
22
|
+
session.model = msg.model;
|
|
23
|
+
if (msg.usage && typeof obj.uuid === 'string') {
|
|
24
|
+
out.usage = {
|
|
25
|
+
sessionId,
|
|
26
|
+
messageUuid: obj.uuid,
|
|
27
|
+
model: typeof msg.model === 'string' ? msg.model : null,
|
|
28
|
+
ts,
|
|
29
|
+
inputTokens: msg.usage.input_tokens ?? 0,
|
|
30
|
+
outputTokens: msg.usage.output_tokens ?? 0,
|
|
31
|
+
cacheReadTokens: msg.usage.cache_read_input_tokens ?? 0,
|
|
32
|
+
cacheCreationTokens: msg.usage.cache_creation_input_tokens ?? 0,
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
const content = Array.isArray(msg.content) ? msg.content : [];
|
|
36
|
+
content.forEach((block, i) => {
|
|
37
|
+
if (block?.type !== 'tool_use' || typeof block.name !== 'string')
|
|
38
|
+
return;
|
|
39
|
+
const c = classifyTool(block.name, block.input);
|
|
40
|
+
out.events.push({
|
|
41
|
+
sessionId,
|
|
42
|
+
ts,
|
|
43
|
+
type: c.type,
|
|
44
|
+
toolName: block.name,
|
|
45
|
+
detail: c.detail,
|
|
46
|
+
source: 'transcript',
|
|
47
|
+
sidechain: !!obj.isSidechain,
|
|
48
|
+
uniqKey: makeUniqKey('transcript', String(obj.uuid ?? ts), String(i), block.name),
|
|
49
|
+
});
|
|
50
|
+
if (c.touch) {
|
|
51
|
+
out.touches.push({
|
|
52
|
+
sessionId, path: c.touch.path, action: c.touch.action, ts,
|
|
53
|
+
uniqKey: makeUniqKey('transcript-touch', String(obj.uuid ?? ts), String(i), block.name),
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
return out;
|
|
58
|
+
}
|