Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/genie-commands/__tests__/session.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
*/

import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
import { mkdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
import { basename, join } from 'node:path';
import { buildClaudeCommand, getAgentsFilePath, sanitizeWindowName } from '../session.js';

Expand Down Expand Up @@ -94,7 +94,7 @@ describe('buildClaudeCommand', () => {
// ============================================================================

describe('getAgentsFilePath', () => {
const TEST_DIR = '/tmp/session-test-agents-md';
const TEST_DIR = `${realpathSync('/tmp')}/session-test-agents-md`;
let originalCwd: string;

beforeEach(() => {
Expand Down
4 changes: 4 additions & 0 deletions src/genie.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,11 @@ program
.description('Show compressed session history for an agent')
.option('--full', 'Show full conversation without compression')
.option('--since <n>', 'Show last N user/assistant exchanges', Number.parseInt)
.option('--last <n>', 'Show last N transcript entries', Number.parseInt)
.option('--type <role>', 'Filter by role (user, assistant, tool_call)')
.option('--after <timestamp>', 'Only entries after ISO timestamp')
.option('--json', 'Output as JSON')
.option('--ndjson', 'Output as newline-delimited JSON (pipeable to jq)')
.option('--raw', 'Output raw JSONL entries')
.option('--log-file <path>', 'Direct path to log file (for testing)')
.action(async (name: string, options: historyCmd.HistoryOptions) => {
Expand Down
96 changes: 93 additions & 3 deletions src/lib/claude-logs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@

import { access, readFile, readdir, stat } from 'node:fs/promises';
import { join } from 'node:path';
import type { Agent } from './agent-registry.js';
import type { TranscriptEntry, TranscriptProvider } from './transcript.js';

// ============================================================================
// Types
Expand Down Expand Up @@ -268,9 +270,9 @@ function populateAssistantFields(
}
if (raw.message.model) {
entry.model = raw.message.model;
if (raw.message.usage) {
entry.usage = raw.message.usage as { input_tokens: number; output_tokens: number };
}
}
if (raw.message.usage) {
entry.usage = raw.message.usage as { input_tokens: number; output_tokens: number };
}
}

Expand Down Expand Up @@ -399,3 +401,91 @@ export async function getLogsForPane(
projectDir: result.projectDir,
};
}

// ============================================================================
// Transcript Provider Adapter
// ============================================================================

/**
* Extract text content from a message content field.
*/
function extractText(content: unknown): string {
if (typeof content === 'string') return content;
if (!Array.isArray(content)) return '';
const parts: string[] = [];
for (const item of content) {
if (typeof item === 'string') parts.push(item);
else if (item && typeof item === 'object' && 'text' in item) parts.push(String(item.text));
}
return parts.join(' ');
}

type ClaudeBase = { provider: 'claude'; model?: string; raw: Record<string, unknown> };

function convertAssistant(entry: ClaudeLogEntry, base: ClaudeBase): TranscriptEntry[] {
const results: TranscriptEntry[] = [];
const text = entry.message ? extractText(entry.message.content) : '';

if (text) {
results.push({
...base,
role: 'assistant',
timestamp: entry.timestamp,
text,
usage: entry.usage ? { input: entry.usage.input_tokens, output: entry.usage.output_tokens } : undefined,
});
}

if (entry.toolCalls) {
for (const tc of entry.toolCalls) {
results.push({
...base,
role: 'tool_call',
timestamp: entry.timestamp,
text: `${tc.name}: ${JSON.stringify(tc.input).slice(0, 200)}`,
toolCall: { id: tc.id, name: tc.name, input: tc.input },
});
}
}

return results;
}

/**
* Convert a Claude log entry into normalized TranscriptEntry items.
* An assistant message with tool calls produces multiple entries.
*/
export function claudeEntryToTranscript(entry: ClaudeLogEntry): TranscriptEntry[] {
const base: ClaudeBase = { provider: 'claude', model: entry.model, raw: entry.raw };

if (entry.type === 'user' && entry.message) {
const text = extractText(entry.message.content);
return text ? [{ ...base, role: 'user', timestamp: entry.timestamp, text }] : [];
}

if (entry.type === 'assistant') return convertAssistant(entry, base);

if (entry.type === 'system' || entry.type === 'progress') {
const text = entry.message ? extractText(entry.message.content) : '';
return text ? [{ ...base, role: 'system', timestamp: entry.timestamp, text }] : [];
}

return [];
}

/**
* Claude Code transcript provider.
* Discovers logs via workspace path hash, reads JSONL session files.
*/
export const claudeTranscriptProvider: TranscriptProvider = {
async discoverLogPath(worker: Agent): Promise<string | null> {
const workspacePath = worker.worktree || worker.repoPath;
const result = await getLogsForPane(workspacePath);
return result?.logPath ?? null;
},

async readEntries(logPath: string): Promise<TranscriptEntry[]> {
const entries = await readLogFile(logPath);
return entries.flatMap(claudeEntryToTranscript);
},
};
114 changes: 114 additions & 0 deletions src/lib/claude-transcript.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
/**
* Tests for Claude Code transcript adapter
* Run with: bun test src/lib/claude-transcript.test.ts
*/

import { describe, expect, test } from 'bun:test';
import type { ClaudeLogEntry } from './claude-logs.js';
import { claudeEntryToTranscript } from './claude-logs.js';

function makeEntry(overrides: Partial<ClaudeLogEntry>): ClaudeLogEntry {
return {
type: 'user',
sessionId: 'test-session',
uuid: 'msg-1',
parentUuid: null,
timestamp: '2026-03-19T10:00:00.000Z',
cwd: '/tmp/test',
raw: {},
...overrides,
};
}

describe('claudeEntryToTranscript', () => {
test('converts user message', () => {
const entry = makeEntry({
type: 'user',
message: { role: 'user', content: 'hello' },
});
const result = claudeEntryToTranscript(entry);
expect(result).toHaveLength(1);
expect(result[0].role).toBe('user');
expect(result[0].text).toBe('hello');
expect(result[0].provider).toBe('claude');
});

test('converts assistant text message', () => {
const entry = makeEntry({
type: 'assistant',
message: { role: 'assistant', content: 'I can help with that' },
});
const result = claudeEntryToTranscript(entry);
expect(result).toHaveLength(1);
expect(result[0].role).toBe('assistant');
expect(result[0].text).toBe('I can help with that');
});

test('converts assistant message with tool calls', () => {
const entry = makeEntry({
type: 'assistant',
message: { role: 'assistant', content: [{ type: 'text', text: 'Let me read that' }] },
toolCalls: [
{ id: 'tc1', name: 'Read', input: { file_path: 'foo.ts' } },
{ id: 'tc2', name: 'Bash', input: { command: 'ls' } },
],
});
const result = claudeEntryToTranscript(entry);
// 1 assistant text + 2 tool calls
expect(result).toHaveLength(3);
expect(result[0].role).toBe('assistant');
expect(result[1].role).toBe('tool_call');
expect(result[1].toolCall?.name).toBe('Read');
expect(result[2].role).toBe('tool_call');
expect(result[2].toolCall?.name).toBe('Bash');
});

test('converts assistant with content array', () => {
const entry = makeEntry({
type: 'assistant',
message: {
role: 'assistant',
content: [
{ type: 'text', text: 'first part' },
{ type: 'text', text: 'second part' },
],
},
});
const result = claudeEntryToTranscript(entry);
expect(result).toHaveLength(1);
expect(result[0].text).toBe('first part second part');
});

test('skips file-history-snapshot', () => {
const entry = makeEntry({ type: 'file-history-snapshot' });
expect(claudeEntryToTranscript(entry)).toEqual([]);
});

test('skips user with empty content', () => {
const entry = makeEntry({
type: 'user',
message: { role: 'user', content: '' },
});
expect(claudeEntryToTranscript(entry)).toEqual([]);
});

test('converts system/progress entries', () => {
const entry = makeEntry({
type: 'system',
message: { role: 'system', content: 'session started' },
});
const result = claudeEntryToTranscript(entry);
expect(result).toHaveLength(1);
expect(result[0].role).toBe('system');
});

test('includes usage when present', () => {
const entry = makeEntry({
type: 'assistant',
message: { role: 'assistant', content: 'response' },
usage: { input_tokens: 100, output_tokens: 50 },
});
const result = claudeEntryToTranscript(entry);
expect(result[0].usage).toEqual({ input: 100, output: 50 });
});
});
Loading
Loading