Skip to content

Commit 1d31743

Browse files
anandgupta42claude
andcommitted
fix: address all 10 CodeRabbit review comments
- Track loops by `(tool, inputHash)` not just tool name (#2) - Use "Failed after" narrative for error traces (#3) - Add keyboard accessibility to viewer tabs (role, tabindex, Enter/Space) (#4) - Use full command as dedup key, not `slice(0,60)` (#5) - Sort timeline events by time before rendering (#6) - Pass `tracesDir` to footer text in `listRecaps` (#7) - Increase `MAX_RECAPS` to 100, add eviction warning log (#8) - Resolve assistant `parentID` for recap enrichment (#9) - Remove unused `tracer` variable in test (#10) - Clarify `--no-trace` backward-compat flag in docs (#1) Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
1 parent 31487db commit 1d31743

7 files changed

Lines changed: 63 additions & 47 deletions

File tree

‎.github/meta/commit.txt‎

Lines changed: 11 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,14 @@
1-
feat: rename tracer to recap with loop detection, post-session summary, and enhanced viewer
1+
fix: address all 10 CodeRabbit review comments
22

3-
- Rename `Tracer` class to `Recap` with backward-compat aliases
4-
- Rename CLI command `trace` to `recap` (hidden `trace` alias preserved)
5-
- Add loop detection: flags repeated tool calls with same input (3+ in last 10)
6-
- Add post-session summary: `narrative`, `topTools`, `loops` in trace output
7-
- New Summary tab (default) in HTML viewer with:
8-
- Truncated prompt with expand toggle
9-
- Files changed with SQL diff previews
10-
- Tool-agnostic outcome extraction (dbt, pytest, Airflow, pip, SQL)
11-
- Deduped dbt commands with pass/fail status, clickable to waterfall
12-
- Smart command grouping (boring ls/cd collapsed, meaningful shown)
13-
- Error details with resolution tracking
14-
- Cost breakdown in collapsible section
15-
- Virality: Share Recap (self-contained HTML download), Copy Summary (markdown),
16-
Copy Link, branded footer
17-
- Fix XSS: timeline items escaped with `e()`
18-
- Fix memory leak: per-session `sessionUserMsgIds` with cleanup on eviction
19-
- Fix JS syntax: onclick quote escaping in collapsible section
20-
- Bound `toolCallHistory` to prevent unbounded growth (cap at 200)
21-
- Summary view wrapped in try-catch for visible error messages
22-
- Update all 13 test files for rename + 8 new adversarial viewer tests
23-
- Update docs: `tracing.md` → `recap.md`, CLI/TUI references updated
3+
- Track loops by `(tool, inputHash)` not just tool name (#2)
4+
- Use "Failed after" narrative for error traces (#3)
5+
- Add keyboard accessibility to viewer tabs (role, tabindex, Enter/Space) (#4)
6+
- Use full command as dedup key, not `slice(0,60)` (#5)
7+
- Sort timeline events by time before rendering (#6)
8+
- Pass `tracesDir` to footer text in `listRecaps` (#7)
9+
- Increase `MAX_RECAPS` to 100, add eviction warning log (#8)
10+
- Resolve assistant `parentID` for recap enrichment (#9)
11+
- Remove unused `tracer` variable in test (#10)
12+
- Clarify `--no-trace` backward-compat flag in docs (#1)
2413

2514
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

‎docs/docs/usage/cli.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,7 @@ altimate run --model anthropic/claude-sonnet-4-6 "optimize my warehouse"
149149
# Print logs for debugging
150150
altimate --print-logs --log-level DEBUG run "test query"
151151

152-
# Disable recap for a single run
152+
# Disable recap for a single run (--no-trace is the backward-compatible flag name)
153153
altimate run --no-trace "quick question"
154154
```
155155

‎packages/opencode/src/altimate/observability/tracing.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -303,7 +303,7 @@ export class Recap {
303303

304304
// altimate_change start — recap: loop detection state
305305
private toolCallHistory: Array<{ tool: string; inputHash: string; time: number }> = []
306-
private loopsDetected: Array<{ tool: string; count: number; firstSeen: number; lastSeen: number }> = []
306+
private loopsDetected: Array<{ tool: string; inputHash: string; count: number; firstSeen: number; lastSeen: number }> = []
307307
// altimate_change end
308308

309309
private metadata: TraceFile["metadata"] = {}
@@ -606,14 +606,15 @@ export class Recap {
606606
const recent = this.toolCallHistory.slice(-10)
607607
const matchCount = recent.filter((h) => h.tool === toolName && h.inputHash === inputHash).length
608608
if (matchCount >= 3) {
609-
const existing = this.loopsDetected.find((l) => l.tool === toolName)
609+
const existing = this.loopsDetected.find((l) => l.tool === toolName && l.inputHash === inputHash)
610610
if (existing) {
611611
existing.count = matchCount
612612
existing.lastSeen = now
613613
} else {
614614
const firstMatch = recent.find((h) => h.tool === toolName && h.inputHash === inputHash)
615615
this.loopsDetected.push({
616616
tool: toolName,
617+
inputHash,
617618
count: matchCount,
618619
firstSeen: firstMatch?.time ?? now,
619620
lastSeen: now,
@@ -867,8 +868,9 @@ export class Recap {
867868
if (this.loopsDetected.length > 0) {
868869
trace.summary.loops = this.loopsDetected.map((l) => ({
869870
tool: l.tool,
871+
inputHash: l.inputHash,
870872
count: l.count,
871-
description: `${l.tool} called ${l.count} times with same input`,
873+
description: `${l.tool} called ${l.count} times with same input (hash: ${l.inputHash})`,
872874
}))
873875
}
874876

@@ -880,7 +882,8 @@ export class Recap {
880882
? ` Warning: ${this.loopsDetected.length} loop(s) detected.`
881883
: ""
882884
const costStr = Number.isFinite(this.totalCost) ? `$${this.totalCost.toFixed(4)}` : "$0.0000"
883-
trace.summary.narrative = `Completed in ${dur}. Made ${this.generationCount} LLM calls${toolsStr}.${loopWarning} Total cost: ${costStr}.`
885+
const statusPrefix = error ? `Failed after ${dur}` : `Completed in ${dur}`
886+
trace.summary.narrative = `${statusPrefix}. Made ${this.generationCount} LLM calls${toolsStr}.${loopWarning} Total cost: ${costStr}.`
884887
} catch {
885888
// Narrative generation must never crash the recap
886889
}

‎packages/opencode/src/altimate/observability/viewer.ts‎

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -297,12 +297,12 @@ pre.io { background: var(--bg); border: 1px solid var(--border); border-radius:
297297
<div class="mini-timeline" id="mini-timeline"></div>
298298
<div id="prompt-area"></div>
299299
<div class="cards" id="cards"></div>
300-
<div class="tabs" id="tabs">
301-
<div class="tab active" data-view="summary">Summary</div>
302-
<div class="tab" data-view="waterfall">Waterfall</div>
303-
<div class="tab" data-view="tree">Tree</div>
304-
<div class="tab" data-view="chat">Chat</div>
305-
<div class="tab" data-view="log">Log</div>
300+
<div class="tabs" id="tabs" role="tablist">
301+
<div class="tab active" data-view="summary" role="tab" tabindex="0">Summary</div>
302+
<div class="tab" data-view="waterfall" role="tab" tabindex="0">Waterfall</div>
303+
<div class="tab" data-view="tree" role="tab" tabindex="0">Tree</div>
304+
<div class="tab" data-view="chat" role="tab" tabindex="0">Chat</div>
305+
<div class="tab" data-view="log" role="tab" tabindex="0">Log</div>
306306
</div>
307307
<div class="content">
308308
<div class="view active" id="v-summary"></div>
@@ -389,15 +389,25 @@ document.getElementById('cards').innerHTML = cardsData.filter(function(c) { retu
389389
})();
390390
391391
// --- Tab switching ---
392-
document.getElementById('tabs').addEventListener('click', function(ev) {
393-
var tab = ev.target.closest ? ev.target.closest('.tab') : ev.target;
392+
function activateTab(tab) {
394393
if (!tab || !tab.dataset || !tab.dataset.view) return;
395394
var view = tab.dataset.view;
396395
document.querySelectorAll('.tab').forEach(function(el) { el.classList.remove('active'); });
397396
document.querySelectorAll('.view').forEach(function(el) { el.classList.remove('active'); });
398397
tab.classList.add('active');
399398
document.getElementById('v-' + view).classList.add('active');
400399
document.getElementById('detail').innerHTML = '';
400+
}
401+
document.getElementById('tabs').addEventListener('click', function(ev) {
402+
var tab = ev.target.closest ? ev.target.closest('.tab') : ev.target;
403+
activateTab(tab);
404+
});
405+
document.getElementById('tabs').addEventListener('keydown', function(ev) {
406+
if (ev.key === 'Enter' || ev.key === ' ') {
407+
ev.preventDefault();
408+
var tab = ev.target.closest ? ev.target.closest('.tab') : ev.target;
409+
activateTab(tab);
410+
}
401411
});
402412
403413
// --- Jump to span (from Summary outcome links) ---
@@ -824,7 +834,7 @@ function showDetail(span) {
824834
// Deduplicate by command — group identical commands
825835
var outcomeMap = {};
826836
cmdOutcomes.forEach(function(o) {
827-
var key = o.command.slice(0, 60);
837+
var key = o.command;
828838
if (!outcomeMap[key]) {
829839
outcomeMap[key] = { command: o.command, result: o.result, status: o.status, spanId: o.spanId, count: 0 };
830840
}
@@ -1022,6 +1032,7 @@ function showDetail(span) {
10221032
timelineEvents.push({ type: 'gen', text: genSpans.length + ' LLM generation' + (genSpans.length > 1 ? 's' : '') + ' using ' + e(model), time: 0 });
10231033
}
10241034
1035+
timelineEvents.sort(function(a, b) { return (a.time || 0) - (b.time || 0); });
10251036
timelineEvents.forEach(function(item) {
10261037
html += '<div class="sum-timeline-item"><div class="sum-timeline-dot ' + item.type + '"></div><div class="sum-timeline-text">' + e(item.text) + '</div></div>';
10271038
});

‎packages/opencode/src/cli/cmd/trace.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ function truncate(str: string, len: number): string {
4949
}
5050

5151
// altimate_change start — recap: rename listTraces → listRecaps
52-
function listRecaps(traces: Array<{ sessionId: string; trace: TraceFile }>) {
52+
function listRecaps(traces: Array<{ sessionId: string; trace: TraceFile }>, tracesDir?: string) {
5353
if (traces.length === 0) {
5454
UI.println("No recaps found. Run a command with tracing enabled:")
5555
UI.println(" altimate-code run \"your prompt here\"")
@@ -97,7 +97,7 @@ function listRecaps(traces: Array<{ sessionId: string; trace: TraceFile }>) {
9797
}
9898

9999
UI.empty()
100-
UI.println(UI.Style.TEXT_DIM + `${traces.length} recap(s) in ${Recap.getTracesDir()}` + UI.Style.TEXT_NORMAL)
100+
UI.println(UI.Style.TEXT_DIM + `${traces.length} recap(s) in ${Recap.getTracesDir(tracesDir)}` + UI.Style.TEXT_NORMAL)
101101
UI.println(UI.Style.TEXT_DIM + "View a recap: altimate-code recap view <session-id>" + UI.Style.TEXT_NORMAL)
102102
}
103103
// altimate_change end
@@ -144,7 +144,7 @@ export const RecapCommand = cmd({
144144

145145
if (action === "list") {
146146
const traces = await Recap.listTraces(tracesDir)
147-
listRecaps(traces.slice(0, args.limit || 20))
147+
listRecaps(traces.slice(0, args.limit || 20), tracesDir)
148148
return
149149
}
150150

@@ -163,7 +163,7 @@ export const RecapCommand = cmd({
163163
if (!match) {
164164
UI.error(`Recap not found: ${args.id}`)
165165
UI.println("Available recaps:")
166-
listRecaps(traces.slice(0, 10))
166+
listRecaps(traces.slice(0, 10), tracesDir)
167167
process.exit(1)
168168
}
169169

‎packages/opencode/src/cli/cmd/tui/worker.ts‎

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ const eventStream = {
5050
// altimate_change start — recap: per-session recaps
5151
const sessionRecaps = new Map<string, Recap>()
5252
const sessionUserMsgIds = new Map<string, Set<string>>() // Per-session user message IDs (cleaned up on session end)
53-
const MAX_RECAPS = 50
53+
const MAX_RECAPS = 100
5454

5555
// Cached tracing config — loaded once at first use
5656
let tracingConfigLoaded = false
@@ -85,6 +85,7 @@ function getOrCreateRecap(sessionID: string): Recap | null {
8585
if (sessionRecaps.size >= MAX_RECAPS) {
8686
const oldest = sessionRecaps.keys().next().value
8787
if (oldest) {
88+
Log.Default.warn(`[tracing] Evicting recap for session ${oldest} — ${MAX_RECAPS} concurrent sessions reached`)
8889
sessionRecaps.get(oldest)?.endTrace().catch(() => {})
8990
sessionRecaps.delete(oldest)
9091
sessionUserMsgIds.delete(oldest)
@@ -147,21 +148,33 @@ const startEventStream = (input: { directory: string; workspaceID?: string }) =>
147148
try {
148149
if (event.type === "message.updated") {
149150
const info = (event as any).properties?.info
150-
if (info?.sessionID) {
151+
// Resolve sessionID: use info.sessionID directly, or fall back to
152+
// finding the session via info.parentID (assistant messages may only
153+
// carry the parent message ID, not the session ID).
154+
let resolvedSessionID = info?.sessionID as string | undefined
155+
if (!resolvedSessionID && info?.parentID) {
156+
for (const [sid, msgIds] of sessionUserMsgIds) {
157+
if (msgIds.has(info.parentID)) {
158+
resolvedSessionID = sid
159+
break
160+
}
161+
}
162+
}
163+
if (resolvedSessionID) {
151164
// Create recap eagerly on user message (arrives before part events)
152-
const recap = sessionRecaps.get(info.sessionID) ?? (info.role === "user" ? getOrCreateRecap(info.sessionID) : null)
165+
const recap = sessionRecaps.get(resolvedSessionID) ?? (info.role === "user" ? getOrCreateRecap(resolvedSessionID) : null)
153166
if (info.role === "user") {
154167
if (info.id) {
155-
if (!sessionUserMsgIds.has(info.sessionID)) sessionUserMsgIds.set(info.sessionID, new Set())
156-
sessionUserMsgIds.get(info.sessionID)!.add(info.id)
168+
if (!sessionUserMsgIds.has(resolvedSessionID)) sessionUserMsgIds.set(resolvedSessionID, new Set())
169+
sessionUserMsgIds.get(resolvedSessionID)!.add(info.id)
157170
}
158171
if (recap) {
159172
const title = (info as any).summary?.title || (info as any).summary?.body
160173
if (title) recap.setTitle(String(title).slice(0, 80), String(title))
161174
}
162175
}
163176
if (info.role === "assistant") {
164-
const r = recap ?? getOrCreateRecap(info.sessionID)
177+
const r = recap ?? getOrCreateRecap(resolvedSessionID)
165178
r?.enrichFromAssistant({
166179
modelID: info.modelID,
167180
providerID: info.providerID,

‎packages/opencode/test/altimate/tracing.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -699,7 +699,7 @@ describe("Recap — multiple exporters", () => {
699699
describe("Recap.withExporters — options", () => {
700700
test("maxFiles option is applied to FileExporter", async () => {
701701
const fileExporter = new FileExporter(tmpDir)
702-
const tracer = Recap.withExporters([fileExporter], { maxFiles: 2 })
702+
Recap.withExporters([fileExporter], { maxFiles: 2 })
703703

704704
// Write 4 traces
705705
for (let i = 0; i < 4; i++) {

0 commit comments

Comments
 (0)