Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(transcripts): offset timestamps round-trip exactly; adapters normalize to UTC (N12-2)
garrytane437fe3d1e27
diff --git a/src/core/transcripts/claude-code.ts b/src/core/transcripts/claude-code.tsindex 30bed43432..e886d8aca1 100644--- a/src/core/transcripts/claude-code.ts+++ b/src/core/transcripts/claude-code.ts@@ -13,7 +13,7 @@ import type {ParseSessionsOpts,TranscriptAdapter,} from './types.ts';-import { TRANSCRIPT_JSONL_HARD_CAP } from './types.ts';+import { TRANSCRIPT_JSONL_HARD_CAP, utcTimestamp } from './types.ts';import { parseClaudeSessionFile, SPEC_TARGET } from './claude-code-jsonl.ts';import { basename } from 'node:path';import { closeSync, openSync, readSync } from 'node:fs';@@ -183,12 +183,12 @@ export const claudeCodeAdapter: TranscriptAdapter = {harness: 'claude-code',sessionId,cwd: r.cwd,- startedAt: r.startedAt || undefined,+ startedAt: utcTimestamp(r.startedAt) || undefined,raw: { sessionId, cwd: r.cwd ?? null, source_path: path },},messages: r.turns.map((t) => ({role: t.role,- timestamp: t.timestamp,+ timestamp: utcTimestamp(t.timestamp),text: t.text,})),};diff --git a/src/core/transcripts/claude-export.ts b/src/core/transcripts/claude-export.tsindex bd59b47c16..04807e20d2 100644--- a/src/core/transcripts/claude-export.ts+++ b/src/core/transcripts/claude-export.ts@@ -20,6 +20,7 @@ import type {TranscriptMessage,} from './types.ts';import { loadExportConversations } from './export-json.ts';+import { utcTimestamp } from './types.ts';export const CLAUDE_EXPORT_SPEC_TARGET: HostSpecTarget = {id: 'claude-ai-export-2026-08',@@ -70,7 +71,7 @@ export const claudeExportAdapter: TranscriptAdapter = {if (!text) continue;messages.push({role,- timestamp: typeof r.created_at === 'string' ? r.created_at : '',+ timestamp: utcTimestamp(r.created_at),text,});}@@ -88,8 +89,7 @@ export const claudeExportAdapter: TranscriptAdapter = {harness: 'claude-export',sessionId,title: typeof c.name === 'string' && c.name ? c.name : undefined,- startedAt:- (typeof c.created_at === 'string' && c.created_at) || messages[0].timestamp || undefined,+ startedAt: utcTimestamp(c.created_at) || messages[0].timestamp || undefined,raw: {conversation_uuid: sessionId,name: typeof c.name === 'string' ? c.name : null,diff --git a/src/core/transcripts/codex.ts b/src/core/transcripts/codex.tsindex 8a79ad4873..5bc1dc35a8 100644--- a/src/core/transcripts/codex.ts+++ b/src/core/transcripts/codex.ts@@ -24,7 +24,7 @@ import type {TranscriptAdapter,TranscriptMessage,} from './types.ts';-import { TRANSCRIPT_JSONL_HARD_CAP } from './types.ts';+import { TRANSCRIPT_JSONL_HARD_CAP, utcTimestamp } from './types.ts';/*** Head window kept when a rollout exceeds the parse budget. Only needs to@@ -102,7 +102,7 @@ export function mapCodexLine(entry: unknown): CodexLineResult {if (typeof entry !== 'object' || entry === null) return { kind: 'skip' };const e = entry as Record<string, unknown>;const payload = (typeof e.payload === 'object' && e.payload !== null ? e.payload : {}) as Record<string, unknown>;- const lineTs = typeof e.timestamp === 'string' ? e.timestamp : '';+ const lineTs = utcTimestamp(e.timestamp);if (e.type === 'session_meta') {return {kind: 'session',@@ -115,7 +115,7 @@ export function mapCodexLine(entry: unknown): CodexLineResult {(typeof payload.session_id === 'string' && payload.session_id) ||undefined,cwd: typeof payload.cwd === 'string' ? payload.cwd : undefined,- startedAt: typeof payload.timestamp === 'string' ? payload.timestamp : lineTs || undefined,+ startedAt: typeof payload.timestamp === 'string' ? utcTimestamp(payload.timestamp) : lineTs || undefined,cliVersion: typeof payload.cli_version === 'string' ? payload.cli_version : undefined,modelProvider: typeof payload.model_provider === 'string' ? payload.model_provider : undefined,};diff --git a/src/core/transcripts/openclaw.ts b/src/core/transcripts/openclaw.tsindex f7fdc4d644..71aa55bdbf 100644--- a/src/core/transcripts/openclaw.ts+++ b/src/core/transcripts/openclaw.ts@@ -17,7 +17,7 @@ import type {TranscriptAdapter,TranscriptMessage,} from './types.ts';-import { TRANSCRIPT_JSONL_HARD_CAP } from './types.ts';+import { TRANSCRIPT_JSONL_HARD_CAP, utcTimestamp } from './types.ts';export const OPENCLAW_SPEC_TARGET: HostSpecTarget = {id: 'openclaw-session-2026-08',@@ -87,7 +87,7 @@ export function mapOpenclawLine(entry: unknown): OpenclawLineResult {kind: 'session',id: typeof e.id === 'string' ? e.id : undefined,cwd: typeof e.cwd === 'string' ? e.cwd : undefined,- startedAt: typeof e.timestamp === 'string' ? e.timestamp : undefined,+ startedAt: typeof e.timestamp === 'string' ? utcTimestamp(e.timestamp) : undefined,};}if (e.type === 'compaction') return { kind: 'boundary' };@@ -114,12 +114,7 @@ export function mapOpenclawLine(entry: unknown): OpenclawLineResult {}text = text.trim();if (!text) return toolCalls.length > 0 ? { kind: 'skip', toolCalls } : { kind: 'skip' };- const timestamp =- typeof m.timestamp === 'string' && m.timestamp- ? m.timestamp- : typeof e.timestamp === 'string'- ? e.timestamp- : '';+ const timestamp = utcTimestamp(typeof m.timestamp === 'string' && m.timestamp ? m.timestamp : e.timestamp);return { kind: 'message', message: { role, timestamp, text }, ...(toolCalls.length > 0 ? { toolCalls } : {}) };}diff --git a/src/core/transcripts/render.ts b/src/core/transcripts/render.tsindex 63fd2f2285..718fd53d6e 100644--- a/src/core/transcripts/render.ts+++ b/src/core/transcripts/render.ts@@ -37,7 +37,7 @@ import { sanitizeForJsonb } from '../batch-rows.ts';import { ensureWellFormed, truncateUtf8 } from '../text-safe.ts';import { BUILTIN_PATTERNS } from '../conversation-parser/builtins.ts';import type { ParsedSession, TranscriptMessage } from './types.ts';-import { buildTranscriptSlug, transcriptFullId } from './types.ts';+import { buildTranscriptSlug, transcriptFullId, utcTimestamp } from './types.ts';// ── Shared line format (imessage-slack builtin) ─────────────────────────────@@ -217,7 +217,7 @@ export function redactSession(/** `2026-08-01T10:00:05.000Z` → `(2026-08-01 10:00 AM)` (UTC), matching the builtin. */function anchorTimestamp(iso: string): string {const d = new Date(iso);- const day = iso.slice(0, 10);+ const day = Number.isNaN(d.getTime()) ? iso.slice(0, 10) : d.toISOString().slice(0, 10);let h = d.getUTCHours();const ampm = h >= 12 ? 'PM' : 'AM';h = h % 12 || 12;@@ -312,7 +312,7 @@ export function renderSessionParts(`session ${meta.sessionId} carries no timestamps — refusing to fabricate provenance`,);}- const dateIso = firstTs;+ const dateIso = utcTimestamp(firstTs);const baseSlug = buildTranscriptSlug(meta.harness, dateIso, {sessionId: meta.sessionId,title: meta.title,diff --git a/src/core/transcripts/types.ts b/src/core/transcripts/types.tsindex 789860b687..1b09669b64 100644--- a/src/core/transcripts/types.ts+++ b/src/core/transcripts/types.ts@@ -150,6 +150,21 @@ export function transcriptFullId(sourceId: string): string {/** Max slugified-title length inside an export slug (keeps slugs readable). */const TITLE_SLUG_MAX = 48;+/**+ * Normalize an adapter's source timestamp to UTC (gbrain-evals N12-2). A+ * string carrying an explicit offset ('2026-08-10T22:30:00-07:00') becomes+ * its UTC ISO instant, so the date and the hour downstream come from the+ * same instant. Everything else passes through unchanged: UTC strings stay+ * byte-identical (no churn for existing imports), and unparseable or+ * zone-less strings keep their current behavior. Non-strings become ''.+ */+export function utcTimestamp(v: unknown): string {+ if (typeof v !== 'string') return '';+ if (!/[+-]\d{2}:?\d{2}$/.test(v.trim())) return v;+ const ms = Date.parse(v);+ return Number.isNaN(ms) ? v : new Date(ms).toISOString();+}+/*** The one slug builder for every imported conversation page.*diff --git a/test/transcript-offset-timestamps.test.ts b/test/transcript-offset-timestamps.test.tsnew file mode 100644index 0000000000..15d99862bc--- /dev/null+++ b/test/transcript-offset-timestamps.test.ts@@ -0,0 +1,93 @@+/**+ * Offset-stamped source timestamps must round-trip exactly (gbrain-evals+ * N12-2). An adapter that copied '2026-08-10T22:30:00.000-07:00' verbatim+ * met a renderer that paired the local DATE (sliced from the string) with+ * the UTC HOUR, so the anchor read "2026-08-10 5:30 AM" and re-parsed one+ * day early. Adapters now normalize offset timestamps to UTC, and the+ * renderer takes date and hour from the same UTC instant.+ *+ * Synthetic data only.+ */+import { describe, test, expect, afterAll } from 'bun:test';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { claudeExportAdapter } from '../src/core/transcripts/claude-export.ts';+import { claudeCodeAdapter } from '../src/core/transcripts/claude-code.ts';+import { mapCodexLine } from '../src/core/transcripts/codex.ts';+import { mapOpenclawLine } from '../src/core/transcripts/openclaw.ts';+import { redactSession, renderSessionParts } from '../src/core/transcripts/render.ts';+import { parseConversation } from '../src/core/conversation-parser/parse.ts';+import type { ParsedSession } from '../src/core/transcripts/types.ts';++const OFFSET = '2026-08-10T22:30:00.000-07:00';+const INSTANT = '2026-08-11T05:30:00.000Z';++const dir = mkdtempSync(join(tmpdir(), 'n12-2-'));+afterAll(() => rmSync(dir, { recursive: true, force: true }));++async function first(gen: AsyncGenerator<ParsedSession, unknown>): Promise<ParsedSession> {+ const r = await gen.next();+ if (r.done) throw new Error('no session');+ return r.value;+}++function roundTrip(session: ParsedSession) {+ const part = renderSessionParts(redactSession(session, { patterns: [] }), { sourcePath: 'x' }).parts[0];+ const parsed = parseConversation(part.body, { noFallback: true, noPolish: true, page: { frontmatter: part.frontmatter } } as any);+ return { part, parsed };+}++describe('render round-trips offset timestamps exactly', () => {+ test('anchor carries the UTC date with the UTC hour; frontmatter date and slug use the UTC day', () => {+ const session: ParsedSession = {+ meta: { harness: 'claude-export', sessionId: 'c1', title: 'evening chat', startedAt: OFFSET },+ messages: [{ role: 'user', timestamp: OFFSET, text: 'hello' }],+ };+ const { part, parsed } = roundTrip(session);+ expect(part.body.split('\n')[0]).toBe('**User** (2026-08-11 5:30 AM): hello');+ expect(part.frontmatter.date).toBe('2026-08-11');+ expect(part.slug).toContain('/2026-08-11-');+ expect(Date.parse(parsed.messages[0].timestamp)).toBe(Date.parse(INSTANT));+ });+});++describe('adapters normalize offset timestamps to UTC', () => {+ test('claude-export (the N12-2 repro)', async () => {+ const p = join(dir, 'conversations.json');+ writeFileSync(p, JSON.stringify([{ uuid: 'c1', name: 'evening chat', created_at: OFFSET,+ chat_messages: [{ uuid: 'm1', sender: 'human', created_at: OFFSET, text: 'hello' }] }]));+ const s = await first(claudeExportAdapter.parse(p));+ expect(s.messages[0].timestamp).toBe(INSTANT);+ expect(s.meta.startedAt).toBe(INSTANT);+ expect(Date.parse(roundTrip(s).parsed.messages[0].timestamp)).toBe(Date.parse(INSTANT));+ });++ test('claude-code', async () => {+ const p = join(dir, 'session.jsonl');+ writeFileSync(p, JSON.stringify({ type: 'user', sessionId: 's1', uuid: 'u1', timestamp: OFFSET, message: { role: 'user', content: 'hello' } }) + '\n');+ const s = await first(claudeCodeAdapter.parse(p));+ expect(s.messages[0].timestamp).toBe(INSTANT);+ expect(s.meta.startedAt).toBe(INSTANT);+ });++ test('codex', () => {+ const session = mapCodexLine({ type: 'session_meta', timestamp: OFFSET, payload: { id: 's1', timestamp: OFFSET } });+ expect(session.kind === 'session' && session.startedAt).toBe(INSTANT);+ const user = mapCodexLine({ type: 'event_msg', timestamp: OFFSET, payload: { type: 'user_message', message: 'hello' } });+ expect(user.kind === 'user' && user.message.timestamp).toBe(INSTANT);+ });++ test('openclaw', () => {+ const session = mapOpenclawLine({ type: 'session', id: 's1', timestamp: OFFSET });+ expect(session.kind === 'session' && session.startedAt).toBe(INSTANT);+ const msg = mapOpenclawLine({ type: 'message', timestamp: OFFSET, message: { role: 'user', content: 'hello', timestamp: OFFSET } });+ expect(msg.kind === 'message' && msg.message.timestamp).toBe(INSTANT);+ });++ test('UTC timestamps pass through byte-identical (no churn for existing imports)', () => {+ const z = '2026-08-01T10:00:00Z';+ const user = mapCodexLine({ type: 'event_msg', timestamp: z, payload: { type: 'user_message', message: 'hello' } });+ expect(user.kind === 'user' && user.message.timestamp).toBe(z);+ });+});