Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(transcripts): keep codex 0.153+ item_completed UserMessage turns; flag assistant-only sessions (#5163, E-N4)

time-attack5572bbd4151a
diff --git a/docs/architecture/key-files/core-services-3.md b/docs/architecture/key-files/core-services-3.md
index a504374cd8..e7f70a0a74 100644
--- a/docs/architecture/key-files/core-services-3.md
+++ b/docs/architecture/key-files/core-services-3.md
@@ -7,7 +7,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/think/intent.ts` + `src/core/think/entity-extract.ts` — pure `classifyIntent(question)` returns `'temporal' | 'knowledge_update' | 'other'` (regex-first, no LLM, `'other'` fast path short-circuits with zero SQL). `extractCandidateEntities(question, retrievedSlugs)` pulls high-precision candidates from retrieved entity-prefix slugs (`people/`, `companies/`, `organizations/`) and medium-precision noun phrases. Stop-word boundaries + leading-verb stripper handle "When did I last meet Marco" → `marco`. Both consumed by `runThink` and the LongMemEval harness so the two paths cannot drift. Pinned by `test/think-intent.test.ts` and `test/think-entity-extract.test.ts`.
-- `src/core/transcripts/` (directory) — the transcript-adapter seam. `types.ts`: the `TranscriptAdapter` contract — `parse(path): AsyncGenerator<ParsedSession, FileDiagnostics>` (one FILE may hold many sessions; the generator RETURN value carries bytes/skipped-lines/zero-session diagnostics so an empty file explains itself), format-specific byte caps (JSONL 50MB hard cap — the 10MB default in `claude-code-jsonl.ts` belongs to the hook-lane tail reader, not imports; monolithic export JSON rejects-not-truncates at 200MB), and the ONE `buildTranscriptSlug` helper (per-provider dirs matching the conversation-archive layout; id suffixes are sha256 prefixes of the session id — hash12 in slugs, hash16 for the dedup identity — never a cleaned prefix of the source id, which would let same-prefix session ids collide). `detect.ts`: adapter registry + head-sample detection (explicit format wins; symlinks lstat-rejected) + injectable `harnessRoots` (the confined discovery surface). Adapters, each with a DATED `SPEC_TARGET` + scrubbed fixture + `bytes>0 && sessions==0` drift alarm: `claude-code.ts` (thin wrapper over the shipped `claude-code-jsonl.ts`, which also exposes the full-file `parseClaudeSessionFile` with real per-message timestamps — hook-lane `parseTranscript` output is pinned byte-identical; owns `isClaudeCodeSubagentFile` (a literal `subagents` path segment at ANY depth + `agent-*.jsonl` basename — both `<session>/subagents/agent-*.jsonl` and the workflow-nested `<session>/subagents/workflows/<wf>/agent-*.jsonl` are all-sidechain, zero-turn files carrying the PARENT session id; a project slug containing "subagents" is one segment and never matches) and `isClaudeCodeWorkflowArtifactFile` (everything under `<session>/subagents/workflows/<wf>/` — the agent logs plus the `journal.jsonl` run log that matches no adapter format; a UUID-named session directly under `subagents/` stays discoverable); `discover.ts` and the CLI's `expandPaths` skip both, so they never read as gap-table backlog, drift, or `unknown format` errors that hold the since-last watermark frozen; the adapter sets `expectedEmpty` when zero accepted turn-shaped records and zero skipped lines remain after root metadata/sidechain and explicit non-human user-text filtering. Metadata-only, non-human-text-only, and all-subagent files are understood empties and do not freeze the watermark; accepted turn records that yield no text and unparseable lines still signal drift. Pinned by `test/claude-code-jsonl-origin.test.ts`), `codex.ts` (turn selection is STRUCTURAL: user turns from `event_msg` user_message, assistant from `response_item` output_text; role user/developer response_items are injected preambles and never leak; identity is `payload.id` — the per-thread id codex embeds in the rollout filename — with `payload.session_id` (the ROOT session shared by every forked/subagent thread) only as the legacy fallback, and the FIRST `session_meta` header wins because a child rollout carries its inherited parent header later in the file; the hook lane's `parseCodexHookTranscript` follows the same two rules), `openclaw.ts` (session header + message lines; `.checkpoint.*.jsonl` snapshots rejected), `hermes.ts` (COPY-THEN-READ of state.db + wal/shm sidecars — readonly WAL opens need -shm write access and lock against a live writer; schema from the installed hermes-agent source; PROVISIONAL), `grok.ts` (Grok Build session dirs — structural turn selection, sidecar-aware discovery; see its own entry), `chatgpt-export.ts` (the `mapping`-tree current_node walk; branches dropped by design, orphaned parents terminate quietly, latest-leaf fallback; extracted conversations.json only) + `claude-export.ts` (flat chat_messages); both export adapters load through the shared `export-json.ts` (monolithic JSON over the cap REJECTS with a split hint; a zip or wrong-shape file gets the unzip-first hint) and give id-less conversations content-derived fallback ids so two id-less exports cannot dedup-skip or overwrite each other. `render.ts`: session → part pages — imessage-slack line format with the regex IMPORTED from `conversation-parser/builtins.ts` (round-trip pinned), REAL timestamps (missing ones carry forward; zero-timestamp sessions refused — provenance is never fabricated), anchor-shaped BODY lines backslash-escaped (hostile message content cannot forge speakers), quoted facts/takes fence-marker tokens backslash-escaped at the same per-message seam (`gbrain\:facts:begin` — a session that read another page cannot plant a live or unbalanced fence on the transcript page; every fence consumer is a substring matcher, so the escape lands inside the token), fail-closed redaction (secret-scan + `harvest-private-patterns.txt` user patterns, slack-channel default excluded because it eats issue refs; imperatives COUNTED into hash-covered `transcript_import` frontmatter, never content_flag), message-boundary splitting at `PART_TARGET_BYTES` = 45,000 bytes (0.9 × the 50,000-byte content-sanity warn line, so no part takes the oversize-warn branch; far under the embed-skip threshold) with 2-message overlap, part 1 keeps the base slug, `frontmatter.id` unique per part. `ingest.ts`: the engine-facing core — a session whose part-1 `frontmatter.id` already has a live page imports at that page's slug (a renamed or re-dated conversation updates in place instead of being skipped as a cross-slug duplicate), SESSION atomicity (failed sessions skip; integrity failures abort the run), stale-part reconciliation (deletes `part > of` leftovers), session metadata banked in the base page's raw_data as the REDACTED copy and healed by content-compare even on hash-skipped re-runs (a run that died before `putRawData`, or a private pattern added after first import, repairs on the next pass), `cleanScan`/`maxSessionTs` for the watermark. `ingest-facts.ts`: ONE `runExtractConversationFactsCore` invocation (batch `slugs` selector) inside ONE `withBudgetTracker`, `isFactsExtractionEnabled` pre-checked. Pinned by `test/transcript-adapters.test.ts`, `test/transcript-render.test.ts`, `test/transcripts-retitle.test.ts`, `test/transcripts-ingest-pglite.test.ts`, `test/e2e/transcripts-writeback-fidelity.test.ts` (raw files through the adapters into the gold-extractor facts path).
+- `src/core/transcripts/` (directory) — the transcript-adapter seam. `types.ts`: the `TranscriptAdapter` contract — `parse(path): AsyncGenerator<ParsedSession, FileDiagnostics>` (one FILE may hold many sessions; the generator RETURN value carries bytes/skipped-lines/zero-session diagnostics so an empty file explains itself), format-specific byte caps (JSONL 50MB hard cap — the 10MB default in `claude-code-jsonl.ts` belongs to the hook-lane tail reader, not imports; monolithic export JSON rejects-not-truncates at 200MB), and the ONE `buildTranscriptSlug` helper (per-provider dirs matching the conversation-archive layout; id suffixes are sha256 prefixes of the session id — hash12 in slugs, hash16 for the dedup identity — never a cleaned prefix of the source id, which would let same-prefix session ids collide). `detect.ts`: adapter registry + head-sample detection (explicit format wins; symlinks lstat-rejected) + injectable `harnessRoots` (the confined discovery surface). Adapters, each with a DATED `SPEC_TARGET` + scrubbed fixture + `bytes>0 && sessions==0` drift alarm: `claude-code.ts` (thin wrapper over the shipped `claude-code-jsonl.ts`, which also exposes the full-file `parseClaudeSessionFile` with real per-message timestamps — hook-lane `parseTranscript` output is pinned byte-identical; owns `isClaudeCodeSubagentFile` (a literal `subagents` path segment at ANY depth + `agent-*.jsonl` basename — both `<session>/subagents/agent-*.jsonl` and the workflow-nested `<session>/subagents/workflows/<wf>/agent-*.jsonl` are all-sidechain, zero-turn files carrying the PARENT session id; a project slug containing "subagents" is one segment and never matches) and `isClaudeCodeWorkflowArtifactFile` (everything under `<session>/subagents/workflows/<wf>/` — the agent logs plus the `journal.jsonl` run log that matches no adapter format; a UUID-named session directly under `subagents/` stays discoverable); `discover.ts` and the CLI's `expandPaths` skip both, so they never read as gap-table backlog, drift, or `unknown format` errors that hold the since-last watermark frozen; the adapter sets `expectedEmpty` when zero accepted turn-shaped records and zero skipped lines remain after root metadata/sidechain and explicit non-human user-text filtering. Metadata-only, non-human-text-only, and all-subagent files are understood empties and do not freeze the watermark; accepted turn records that yield no text and unparseable lines still signal drift. Pinned by `test/claude-code-jsonl-origin.test.ts`), `codex.ts` (turn selection is STRUCTURAL: user turns from `event_msg` user_message (through 0.152) or `event_msg` item_completed with item.type UserMessage, text blocks only (0.153+, #5163; a turn recorded in both shapes is kept once, other item types incl. AgentMessage skipped), assistant from `response_item` output_text; a file with assistant turns and zero user turns sets `FileDiagnostics.userTurnsMissing` (codex and claude-code; E-N4), which ingest counts as drift and the session-end hook heartbeats as `degraded`/`no_user_turns` on whole-file reads (pinned by `test/codex-rollout-0154.serial.test.ts`); role user/developer response_items are injected preambles and never leak; identity is `payload.id` — the per-thread id codex embeds in the rollout filename — with `payload.session_id` (the ROOT session shared by every forked/subagent thread) only as the legacy fallback, and the FIRST `session_meta` header wins because a child rollout carries its inherited parent header later in the file; the hook lane's `parseCodexHookTranscript` follows the same two rules), `openclaw.ts` (session header + message lines; `.checkpoint.*.jsonl` snapshots rejected), `hermes.ts` (COPY-THEN-READ of state.db + wal/shm sidecars — readonly WAL opens need -shm write access and lock against a live writer; schema from the installed hermes-agent source; PROVISIONAL), `grok.ts` (Grok Build session dirs — structural turn selection, sidecar-aware discovery; see its own entry), `chatgpt-export.ts` (the `mapping`-tree current_node walk; branches dropped by design, orphaned parents terminate quietly, latest-leaf fallback; extracted conversations.json only) + `claude-export.ts` (flat chat_messages); both export adapters load through the shared `export-json.ts` (monolithic JSON over the cap REJECTS with a split hint; a zip or wrong-shape file gets the unzip-first hint) and give id-less conversations content-derived fallback ids so two id-less exports cannot dedup-skip or overwrite each other. `render.ts`: session → part pages — imessage-slack line format with the regex IMPORTED from `conversation-parser/builtins.ts` (round-trip pinned), REAL timestamps (missing ones carry forward; zero-timestamp sessions refused — provenance is never fabricated), anchor-shaped BODY lines backslash-escaped (hostile message content cannot forge speakers), quoted facts/takes fence-marker tokens backslash-escaped at the same per-message seam (`gbrain\:facts:begin` — a session that read another page cannot plant a live or unbalanced fence on the transcript page; every fence consumer is a substring matcher, so the escape lands inside the token), fail-closed redaction (secret-scan + `harvest-private-patterns.txt` user patterns, slack-channel default excluded because it eats issue refs; imperatives COUNTED into hash-covered `transcript_import` frontmatter, never content_flag), message-boundary splitting at `PART_TARGET_BYTES` = 45,000 bytes (0.9 × the 50,000-byte content-sanity warn line, so no part takes the oversize-warn branch; far under the embed-skip threshold) with 2-message overlap, part 1 keeps the base slug, `frontmatter.id` unique per part. `ingest.ts`: the engine-facing core — a session whose part-1 `frontmatter.id` already has a live page imports at that page's slug (a renamed or re-dated conversation updates in place instead of being skipped as a cross-slug duplicate), SESSION atomicity (failed sessions skip; integrity failures abort the run), stale-part reconciliation (deletes `part > of` leftovers), session metadata banked in the base page's raw_data as the REDACTED copy and healed by content-compare even on hash-skipped re-runs (a run that died before `putRawData`, or a private pattern added after first import, repairs on the next pass), `cleanScan`/`maxSessionTs` for the watermark. `ingest-facts.ts`: ONE `runExtractConversationFactsCore` invocation (batch `slugs` selector) inside ONE `withBudgetTracker`, `isFactsExtractionEnabled` pre-checked. Pinned by `test/transcript-adapters.test.ts`, `test/transcript-render.test.ts`, `test/transcripts-retitle.test.ts`, `test/transcripts-ingest-pglite.test.ts`, `test/e2e/transcripts-writeback-fidelity.test.ts` (raw files through the adapters into the gold-extractor facts path).
- `src/core/verbs/conformance.ts` + `src/core/verbs/conformance-fixtures.ts` — the conformance runner core (transport-agnostic: minimal `ConformanceClient` = list_tools + call_tool) and the embedded fixture set. Deterministic by construction: shape/enum/behavior/round-trip checks only, never ranking quality. Validation is NON-STRICT on extra fields (additive-forever means unknown fields are always legal). Entity-card cases seed via put_page when the target exposes it and skip honestly on verbs-only targets; synthesize is cost-gated behind --synthesize. `validateAgainstSchema` is a minimal JSON-Schema-subset validator (type unions, required, properties, enum, const, items). Fixtures mirror to `test/fixtures/memory-verbs/cases.json` (BrainBench seeds; drift-guarded by the conformance test). The negative self-test (test/memory-verbs-conformance.test.ts) proves the runner FAILS a lying server.
diff --git a/src/commands/hook.ts b/src/commands/hook.ts
index 5c40da8879..6d4e11c7b7 100644
--- a/src/commands/hook.ts
+++ b/src/commands/hook.ts
@@ -1720,6 +1720,12 @@ async function hookSessionEnd(io: HookIo): Promise<number> {
/* status telemetry best-effort */
}
} else if (turnsN > 0) {
+ // E-N4: assistant turns with not one user turn is how #5163 (a host
+ // renamed its user-turn record) banked half-sessions silently. The
+ // corpus is still written; the heartbeat says the human side is gone.
+ // Whole-file reads only: a bounded tail of a long agentic run can
+ // legitimately hold assistant turns alone.
+ if (parsed.genuineUserTurnIndexes.length === 0 && bytesN >= conf.size) degrade('no_user_turns');
const dir = await corpusDir(cfg);
// #4618: the seat is recorded BEFORE any corpus file of this session
// is renamed into place, so a sweep never sees one without its seat.
diff --git a/src/commands/transcripts.ts b/src/commands/transcripts.ts
index 3337d325d8..275a5a21f5 100644
--- a/src/commands/transcripts.ts
+++ b/src/commands/transcripts.ts
@@ -332,8 +332,14 @@ export function fmtSummary(r: TranscriptsIngestResult): string {
if (r.redactions > 0) lines.push(`redactions: ${r.redactions} secrets/patterns redacted before write`);
if (r.imperatives > 0) lines.push(`flagged: ${r.imperatives} agent-directed imperative(s) noted in frontmatter`);
if (r.driftFiles > 0) {
+ const userless = r.files.filter((f) => f.userTurnsMissing).length;
+ const zero = r.driftFiles - userless;
+ const shapes = [
+ zero > 0 ? `${zero} parsed to zero sessions` : '',
+ userless > 0 ? `${userless} parsed to assistant turns with no user turns` : '',
+ ].filter(Boolean).join(', ');
lines.push(
- `DRIFT WARNING: ${r.driftFiles} file(s) parsed to zero sessions — the host ` +
+ `DRIFT WARNING: ${r.driftFiles} file(s) drifted (${shapes}) — the host ` +
`format may have changed; see the adapter SPEC_TARGET runbook`,
);
}
diff --git a/src/core/transcripts/claude-code.ts b/src/core/transcripts/claude-code.ts
index 389e2a7db9..60ac0df0e3 100644
--- a/src/core/transcripts/claude-code.ts
+++ b/src/core/transcripts/claude-code.ts
@@ -228,6 +228,7 @@ export const claudeCodeAdapter: TranscriptAdapter = {
? 'no turn records in file (title/metadata-only, non-human text only, or all-subagent)'
: 'no user or assistant turns in file'
: undefined,
+ userTurnsMissing: r.turns.length > 0 && !r.turns.some((t) => t.role === 'user') ? true : undefined,
};
},
};
diff --git a/src/core/transcripts/codex-hook-lane.ts b/src/core/transcripts/codex-hook-lane.ts
index cf7620145e..e71a57ee53 100644
--- a/src/core/transcripts/codex-hook-lane.ts
+++ b/src/core/transcripts/codex-hook-lane.ts
@@ -38,7 +38,7 @@ import { isPathContained } from '../path-confine.ts';
import type { ConfineTranscriptResult, ParsedTranscript, ToolCallRecord } from './claude-code-jsonl.ts';
import { capToolCallInput, TRANSCRIPT_HARD_CAP_BYTES, TRANSCRIPT_MAX_BYTES_DEFAULT } from './claude-code-jsonl.ts';
import type { WindowTurn } from '../context/entity-salience.ts';
-import { mapCodexLine } from './codex.ts';
+import { isRepeatedCodexUserTurn, mapCodexLine } from './codex.ts';
/** Head window kept on over-budget reads: session_meta is byte 0 of a rollout
* and carries the identity a pure tail read would lose (codex.ts rationale). */
@@ -174,6 +174,7 @@ export function parseCodexHookTranscript(
if (!cwd && mapped.cwd) cwd = mapped.cwd;
break;
case 'user':
+ if (isRepeatedCodexUserTurn(turns.at(-1), mapped.message.text)) break;
genuineUserTurnIndexes.push(turns.length);
turns.push({ role: mapped.message.role, text: mapped.message.text });
break;
diff --git a/src/core/transcripts/codex.ts b/src/core/transcripts/codex.ts
index 5bc1dc35a8..ca02c97019 100644
--- a/src/core/transcripts/codex.ts
+++ b/src/core/transcripts/codex.ts
@@ -5,7 +5,11 @@
* Verified against a live local rollout 2026-08-14 (see SPEC_TARGET).
*
* TURN SELECTION IS STRUCTURAL, not heuristic: the human's typed text is
- * recorded as `event_msg` payload.type='user_message' (payload.message);
+ * recorded as `event_msg` payload.type='user_message' (payload.message) up to
+ * codex 0.152, and as `event_msg` payload.type='item_completed' with
+ * item.type='UserMessage' (text content blocks) from 0.153 on (#5163); a
+ * rollout carrying both shapes for one turn keeps it once
+ * (isRepeatedCodexUserTurn);
* `response_item` rows with role user/developer are INJECTED context
* (app-context, plugin lists, instruction preambles) and are skipped
* wholesale. Assistant text comes from `response_item` payload.type='message'
@@ -34,19 +38,26 @@ import { TRANSCRIPT_JSONL_HARD_CAP, utcTimestamp } from './types.ts';
const CODEX_HEAD_WINDOW_BYTES = 256 * 1024;
export const CODEX_SPEC_TARGET: HostSpecTarget = {
- id: 'codex-rollout-2026-08',
+ id: 'codex-rollout-2026-10',
status: 'verified',
- verifiedAt: '2026-08-14',
+ verifiedAt: '2026-10-05',
references: [
'local ~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl (codex CLI, live sample 2026-08-14)',
+ 'codex-cli 0.154.0 and 0.159.3 rollout line shapes quoted in garrytan/gbrain#5163 (observed 2026-10-05)',
'test/fixtures/transcripts/codex-rollout.jsonl',
+ 'test/fixtures/transcripts/codex-rollout-0154.jsonl',
],
note:
- 'One JSON object per line: {timestamp: ISO, type, payload}. type ' +
+ 'One JSON object per line: {timestamp: ISO, type, payload}; 0.159 adds ' +
+ 'ordinal/started_at_ms/completed_at_ms, ignored. type ' +
"'session_meta' header carries payload.{id, session_id, cwd, timestamp, " +
"cli_version}; identity = payload.id (per-thread; session_id is the root " +
"session shared by forked/subagent threads), first header wins. User turns: type 'event_msg' with payload.type " +
- "'user_message' (payload.message = typed text). Assistant turns: type " +
+ "'user_message' (payload.message = typed text) through 0.152; from 0.153 " +
+ "type 'event_msg' with payload.type 'item_completed' and " +
+ "payload.item.{type:'UserMessage', content:[{type:'text', text}]} (other " +
+ 'item types, AgentMessage included, skipped; non-text blocks skipped; ' +
+ 'both shapes for one turn kept once). Assistant turns: type ' +
"'response_item' with payload.{type:'message', role:'assistant', " +
"content:[{type:'output_text', text}]}. response_item rows with role " +
'user/developer are injected context and are skipped. reasoning, ' +
@@ -65,6 +76,15 @@ function textFromBlocks(content: unknown, blockType: string): string {
return parts.join('\n').trim();
}
+/**
+ * #5163: a rollout written across the 0.152 -> 0.153 change can record one
+ * typed turn as both `user_message` and `item_completed` UserMessage. The
+ * second copy is the same text with no assistant turn between them.
+ */
+export function isRepeatedCodexUserTurn(previous: { role: string; text: string } | undefined, text: string): boolean {
+ return previous?.role === 'user' && previous.text === text;
+}
+
/**
* One parsed codex rollout line, classified (mirrors openclaw.ts's
* mapOpenclawLine precedent: the hook lane's tail-capable parser reuses the
@@ -125,6 +145,15 @@ export function mapCodexLine(entry: unknown): CodexLineResult {
const text = typeof payload.message === 'string' ? payload.message.trim() : '';
return text ? { kind: 'user', message: { role: 'user', timestamp: lineTs, text } } : { kind: 'skip' };
}
+ if (e.type === 'event_msg' && payload.type === 'item_completed') {
+ // #5163: codex >= 0.153 records the typed turn only as an item_completed
+ // UserMessage. Every other item type is skipped: AgentMessage duplicates
+ // the response_item output_text row, command/tool items are not text.
+ const item = (typeof payload.item === 'object' && payload.item !== null ? payload.item : {}) as Record<string, unknown>;
+ if (item.type !== 'UserMessage') return { kind: 'skip' };
+ const text = textFromBlocks(item.content, 'text');
+ return text ? { kind: 'user', message: { role: 'user', timestamp: lineTs, text } } : { kind: 'skip' };
+ }
if (e.type === 'response_item' && payload.type === 'message' && payload.role === 'assistant') {
const text = textFromBlocks(payload.content, 'output_text');
return text ? { kind: 'assistant', message: { role: 'assistant', timestamp: lineTs, text } } : { kind: 'skip' };
@@ -235,6 +264,7 @@ export const codexAdapter: TranscriptAdapter = {
};
continue;
}
+ if (mapped.kind === 'user' && isRepeatedCodexUserTurn(messages.at(-1), mapped.message.text)) continue;
if (mapped.kind === 'user' || mapped.kind === 'assistant') {
messages.push(mapped.message);
continue;
@@ -265,7 +295,8 @@ export const codexAdapter: TranscriptAdapter = {
truncated,
sessions,
zeroSessionsReason:
- sessions === 0 ? 'no user_message events or assistant message items in rollout' : undefined,
+ sessions === 0 ? 'no user turns (user_message or item_completed UserMessage) or assistant message items in rollout' : undefined,
+ userTurnsMissing: messages.length > 0 && !messages.some((m) => m.role === 'user') ? true : undefined,
};
},
};
diff --git a/src/core/transcripts/ingest.ts b/src/core/transcripts/ingest.ts
index efda0d6f9c..b7c2f0f097 100644
--- a/src/core/transcripts/ingest.ts
+++ b/src/core/transcripts/ingest.ts
@@ -103,6 +103,8 @@ export interface IngestFileOutcome {
sessions: IngestSessionOutcome[];
skippedLines: number;
drift: boolean;
+ /** E-N4: assistant turns parsed with zero user turns (counted in driftFiles). */
+ userTurnsMissing?: boolean;
/** Adapter degraded to a bounded read (e.g. codex head+tail) — part of the file was never scanned. */
truncated: boolean;
error?: string;
@@ -447,6 +449,16 @@ export async function runTranscriptsIngest(
// tool/reasoning-only session) is understood, not drifted.
result.cleanScan = false;
}
+ if (diag.userTurnsMissing && !fileOutcome.drift) {
+ // E-N4: assistant turns parsed but not one user turn — the shape
+ // #5163 hid behind (a host renamed its user-turn record). The
+ // session still imports, but the file is drift: the watermark holds
+ // so a fixed parser re-reads it.
+ fileOutcome.drift = true;
+ fileOutcome.userTurnsMissing = true;
+ result.driftFiles++;
+ result.cleanScan = false;
+ }
if (diag.skippedLines > 0) {
// Malformed lines can be DROPPED RECORDS (an actively-appended
// file read mid-write, corruption) — freeze the watermark so a
diff --git a/src/core/transcripts/types.ts b/src/core/transcripts/types.ts
index 1b09669b64..84d3e350bb 100644
--- a/src/core/transcripts/types.ts
+++ b/src/core/transcripts/types.ts
@@ -81,6 +81,12 @@ export interface FileDiagnostics {
* drift — ingest must not freeze the watermark.
*/
expectedEmpty?: boolean;
+ /**
+ * E-N4: the file yielded assistant turns but not one user turn. The usual
+ * cause is a host format change the parser no longer recognizes (#5163), so
+ * ingest reports it as drift and holds the watermark.
+ */
+ userTurnsMissing?: boolean;
}
export interface ParseSessionsOpts {
diff --git a/test/codex-rollout-0154.serial.test.ts b/test/codex-rollout-0154.serial.test.ts
new file mode 100644
index 0000000000..a957d4377d
--- /dev/null
+++ b/test/codex-rollout-0154.serial.test.ts
@@ -0,0 +1,217 @@
+/**
+ * #5163 + E-N4: codex >= 0.153 records the typed turn only as an
+ * `event_msg`/`item_completed` UserMessage. Both the import adapter and the
+ * SessionEnd hook lane must keep it; an assistant-only parse must be loud.
+ *
+ * The fixture copies the line shapes quoted in #5163 (0.154.0 and the 0.159.3
+ * `ordinal`/`started_at_ms` extras) with synthetic text.
+ *
+ * SERIAL: mutates GBRAIN_HOME / CODEX_HOME for the hook-lane cases.
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { codexAdapter, mapCodexLine } from '../src/core/transcripts/codex.ts';
+import { parseCodexHookTranscript } from '../src/core/transcripts/codex-hook-lane.ts';
+import { claudeCodeAdapter } from '../src/core/transcripts/claude-code.ts';
+import type { FileDiagnostics, ParsedSession } from '../src/core/transcripts/types.ts';
+import { readHeartbeatTail, runHook } from '../src/commands/hook.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { runTranscriptsIngest } from '../src/core/transcripts/ingest.ts';
+
+const FIXTURE_0154 = join(import.meta.dir, 'fixtures', 'transcripts', 'codex-rollout-0154.jsonl');
+
+async function drain(gen: AsyncGenerator<ParsedSession, FileDiagnostics>) {
+ const sessions: ParsedSession[] = [];
+ let step = await gen.next();
+ while (!step.done) {
+ sessions.push(step.value);
+ step = await gen.next();
+ }
+ return { sessions, diag: step.value };
+}
+
+const ENV_KEYS = ['GBRAIN_HOME', 'CODEX_HOME', 'GBRAIN_SEAT', 'GBRAIN_MEMORABLE', 'GBRAIN_HOOKS'] as const;
+let tmp: string;
+let saved: Record<string, string | undefined>;
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), 'gb-cdx154-'));
+ saved = {};
+ for (const k of ENV_KEYS) {
+ saved[k] = process.env[k];
+ delete process.env[k];
+ }
+ process.env.GBRAIN_HOME = tmp;
+ mkdirSync(join(tmp, 'ws'), { recursive: true });
+});
+afterEach(() => {
+ for (const k of ENV_KEYS) {
+ if (saved[k] === undefined) delete process.env[k];
+ else process.env[k] = saved[k];
+ }
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+const meta = JSON.stringify({
+ timestamp: '2026-10-01T09:00:00.000Z',
+ type: 'session_meta',
+ payload: { id: 'r-154', session_id: 'r-154', timestamp: '2026-10-01T09:00:00.000Z', cwd: '/repo', cli_version: '0.154.0' },
+});
+const userMessageItem = (text: string, ts = '2026-10-01T09:00:01.000Z') =>
+ JSON.stringify({
+ timestamp: ts,
+ type: 'event_msg',
+ payload: { type: 'item_completed', thread_id: 'th', turn_id: 'tu', item: { type: 'UserMessage', id: 'i', content: [{ type: 'text', text, text_elements: [] }] } },
+ });
+const legacyUser = (text: string, ts = '2026-10-01T09:00:01.000Z') =>
+ JSON.stringify({ timestamp: ts, type: 'event_msg', payload: { type: 'user_message', message: text } });
+const assistant = (text: string, ts = '2026-10-01T09:00:02.000Z') =>
+ JSON.stringify({ timestamp: ts, type: 'response_item', payload: { type: 'message', role: 'assistant', content: [{ type: 'output_text', text }] } });
+
+function writeRollout(name: string, lines: string[]): string {
+ const p = join(tmp, name);
+ writeFileSync(p, lines.join('\n') + '\n');
+ return p;
+}
+
+describe('#5163 import adapter: item_completed UserMessage is a user turn', () => {
+ test('a 0.154 rollout parses to its user and assistant turns; injected rows, other items and non-text blocks stay out', async () => {
+ const { sessions, diag } = await drain(codexAdapter.parse(FIXTURE_0154));
+ expect(sessions).toHaveLength(1);
+ const s = sessions[0]!;
+ expect(s.messages.map((m) => [m.role, m.text])).toEqual([
+ ['user', 'Which fund led the widget-co seed round?'],
+ ['assistant', 'fund-a led the widget-co seed.'],
+ ['user', 'Note that the bridge check-in is every Thursday.'],
+ ['assistant', 'Noted: bridge check-in every Thursday.'],
+ ]);
+ expect(s.messages[0]!.timestamp).toBe('2026-10-01T09:00:03.000Z');
+ const all = s.messages.map((m) => m.text).join('\n');
+ for (const leak of ['PREAMBLE-ONLY-TEXT', 'ENV-CONTEXT-ONLY-TEXT', 'IMAGE-BLOCK-ONLY', 'COMMAND-OUTPUT-ONLY-TEXT']) {
+ expect(all).not.toContain(leak);
+ }
+ expect(diag.userTurnsMissing).toBeUndefined();
+ });
+
+ test('a failed exec (user turn, no assistant reply) still yields its one user turn', async () => {
+ const p = writeRollout('failed-exec.jsonl', [meta, userMessageItem('run the migration')]);
+ const { sessions, diag } = await drain(codexAdapter.parse(p));
+ expect(diag.sessions).toBe(1);
+ expect(sessions[0]!.messages.map((m) => [m.role, m.text])).toEqual([['user', 'run the migration']]);
+ });
+
+ test('a rollout that records one turn in both shapes keeps it once; a genuine repeat after a reply stays', async () => {
+ const p = writeRollout('both-shapes.jsonl', [
+ meta,
+ legacyUser('same turn'),
+ userMessageItem('same turn'),
+ assistant('reply'),
+ userMessageItem('same turn'),
+ assistant('second reply'),
+ ]);
+ const { sessions } = await drain(codexAdapter.parse(p));
+ expect(sessions[0]!.messages.map((m) => m.role)).toEqual(['user', 'assistant', 'user', 'assistant']);
+ });
+
+ test('mapCodexLine: AgentMessage, other item types and empty or non-text UserMessage content are skipped', () => {
+ const item = (it: unknown) => ({ type: 'event_msg', payload: { type: 'item_completed', item: it } });
+ expect(mapCodexLine(item({ type: 'AgentMessage', content: [{ type: 'text', text: 'dup' }] })).kind).toBe('skip');
+ expect(mapCodexLine(item({ type: 'CommandExecution', command: 'ls' })).kind).toBe('skip');
+ expect(mapCodexLine(item({ type: 'UserMessage', content: [{ type: 'image', image_url: 'x' }] })).kind).toBe('skip');
+ expect(mapCodexLine(item({ type: 'UserMessage', content: [{ type: 'text', text: ' ' }] })).kind).toBe('skip');
+ expect(mapCodexLine(item(null)).kind).toBe('skip');
+ expect(mapCodexLine({ type: 'response_item', payload: { type: 'message', role: 'user', content: [{ type: 'input_text', text: 'injected' }] } }).kind).toBe('skip');
+ });
+});
+
+describe('#5163 hook lane: the SessionEnd parser keeps the typed turn', () => {
+ test('parseCodexHookTranscript yields user turns from item_completed UserMessage, deduped across shapes', () => {
+ const parsed = parseCodexHookTranscript(FIXTURE_0154);
+ expect(parsed.turns.map((t) => t.role)).toEqual(['user', 'assistant', 'user', 'assistant']);
+ expect(parsed.genuineUserTurnIndexes).toEqual([0, 2]);
+ const both = writeRollout('both.jsonl', [meta, legacyUser('one'), userMessageItem('one'), assistant('two')]);
+ expect(parseCodexHookTranscript(both).turns.map((t) => t.text)).toEqual(['one', 'two']);
+ });
+
+ test('session-end banks a corpus file with the user turn', async () => {
+ const codexHome = join(tmp, 'codex');
+ process.env.CODEX_HOME = codexHome;
+ const day = join(codexHome, 'sessions', '2026', '10', '01');
+ mkdirSync(day, { recursive: true });
+ const rollout = join(day, 'rollout-2026-10-01T09-00-00-r-154.jsonl');
+ writeFileSync(rollout, readFileSync(FIXTURE_0154));
+ expect(await runHook(['session-end'], {
+ harness: 'codex',
+ stdin: JSON.stringify({ session_id: 'r-154', transcript_path: rollout, cwd: join(tmp, 'ws') }),
+ })).toBe(0);
+ const corpus = join(tmp, '.gbrain', 'transcripts', 'corpus', 'r-154.txt');
+ expect(existsSync(corpus)).toBe(true);
+ const text = readFileSync(corpus, 'utf8');
+ expect(text).toContain('[user]');
+ expect(text).toContain('Which fund led the widget-co seed round?');
+ const hb = (await readHeartbeatTail(1))[0]!;
+ expect(hb.event).toBe('session-end');
+ expect(hb.reason).not.toBe('no_user_turns');
+ });
+});
+
+describe('E-N4: assistant turns with no user turn are flagged, never silent', () => {
+ test('codex adapter: an assistant-only rollout reports userTurnsMissing', async () => {
+ const p = writeRollout('assistant-only.jsonl', [meta, assistant('ok')]);
+ const { sessions, diag } = await drain(codexAdapter.parse(p));
+ expect(sessions).toHaveLength(1);
+ expect(diag.userTurnsMissing).toBe(true);
+ });
+
+ test('claude-code adapter: an assistant-only session reports userTurnsMissing', async () => {
+ const p = writeRollout('claude-assistant-only.jsonl', [
+ JSON.stringify({ type: 'assistant', sessionId: 's-1', isSidechain: false, timestamp: '2026-10-01T09:00:00.000Z', message: { role: 'assistant', content: [{ type: 'text', text: 'ok' }] } }),
+ ]);
+ const { diag } = await drain(claudeCodeAdapter.parse(p));
+ expect(diag.sessions).toBe(1);
+ expect(diag.userTurnsMissing).toBe(true);
+ });
+
+ test('session-end heartbeats degraded:no_user_turns for an assistant-only rollout and still banks the corpus', async () => {
+ const codexHome = join(tmp, 'codex');
+ process.env.CODEX_HOME = codexHome;
+ const day = join(codexHome, 'sessions', '2026', '10', '01');
+ mkdirSync(day, { recursive: true });
+ const rollout = join(day, 'rollout-2026-10-01T09-00-00-r-ao.jsonl');
+ writeFileSync(rollout, [meta.replace('r-154', 'r-ao'), assistant('ok')].join('\n') + '\n');
+ expect(await runHook(['session-end'], {
+ harness: 'codex',
+ stdin: JSON.stringify({ session_id: 'r-ao', transcript_path: rollout, cwd: join(tmp, 'ws') }),
+ })).toBe(0);
+ const hb = (await readHeartbeatTail(1))[0]!;
+ expect(hb).toMatchObject({ event: 'session-end', outcome: 'degraded', reason: 'no_user_turns' });
+ expect(existsSync(join(tmp, '.gbrain', 'transcripts', 'corpus', 'r-ao.txt'))).toBe(true);
+ });
+
+ describe('ingest', () => {
+ let engine: PGLiteEngine;
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ });
+ afterAll(async () => {
+ await engine.disconnect();
+ });
+
+ test('an assistant-only file imports but counts as drift and holds the watermark', async () => {
+ await resetPgliteState(engine);
+ const p = writeRollout('assistant-only.jsonl', [meta, assistant('ok')]);
+ const r = await runTranscriptsIngest(engine, { paths: [p], sourceId: 'default', userPatternsPath: '/nonexistent-patterns.txt' });
+ expect(r.sessionsImported).toBe(1);
+ expect(r.driftFiles).toBe(1);
+ expect(r.files[0]!.userTurnsMissing).toBe(true);
+ expect(r.cleanScan).toBe(false);
+ const ok = await runTranscriptsIngest(engine, { paths: [FIXTURE_0154], sourceId: 'default', userPatternsPath: '/nonexistent-patterns.txt' });
+ expect(ok.driftFiles).toBe(0);
+ expect(ok.cleanScan).toBe(true);
+ });
+ });
+});
diff --git a/test/fixtures/transcripts/codex-rollout-0154.jsonl b/test/fixtures/transcripts/codex-rollout-0154.jsonl
new file mode 100644
index 0000000000..9973e3f516
--- /dev/null
+++ b/test/fixtures/transcripts/codex-rollout-0154.jsonl
@@ -0,0 +1,12 @@
+{"timestamp":"2026-10-01T09:00:00.000Z","type":"session_meta","payload":{"id":"01a0a325-0407-7fe2-867a-c98e6e63a000","session_id":"01a0a325-0407-7fe2-867a-c98e6e63a000","timestamp":"2026-10-01T09:00:00.000Z","cwd":"/home/alice-example/agent-workspace","cli_version":"0.154.0","model_provider":"provider-example","source":"exec"}}
+{"timestamp":"2026-10-01T09:00:01.000Z","type":"response_item","payload":{"type":"message","role":"developer","content":[{"type":"input_text","text":"PREAMBLE-ONLY-TEXT: injected instructions that must never reach the archive"}]}}
+{"timestamp":"2026-10-01T09:00:01.500Z","type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"ENV-CONTEXT-ONLY-TEXT: injected environment context that must never reach the archive"}]}}
+{"timestamp":"2026-10-01T09:00:02.000Z","type":"event_msg","payload":{"type":"task_started","turn_id":"turn-1"}}
+{"timestamp":"2026-10-01T09:00:03.000Z","type":"event_msg","payload":{"type":"item_completed","thread_id":"thread-1","turn_id":"turn-1","item":{"type":"UserMessage","id":"item-1","content":[{"type":"text","text":"Which fund led the widget-co seed round?","text_elements":[]},{"type":"image","image_url":"IMAGE-BLOCK-ONLY: never archived"}]}}}
+{"timestamp":"2026-10-01T09:00:04.000Z","type":"response_item","payload":{"type":"reasoning","summary":[]}}
+{"timestamp":"2026-10-01T09:00:05.000Z","type":"event_msg","payload":{"type":"item_completed","thread_id":"thread-1","turn_id":"turn-1","item":{"type":"CommandExecution","id":"item-2","command":"ls","aggregated_output":"COMMAND-OUTPUT-ONLY-TEXT: never archived"}}}
+{"timestamp":"2026-10-01T09:00:06.000Z","type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"fund-a led the widget-co seed."}]}}
+{"timestamp":"2026-10-01T09:00:06.500Z","type":"event_msg","payload":{"type":"item_completed","thread_id":"thread-1","turn_id":"turn-1","item":{"type":"AgentMessage","id":"item-3","content":[{"type":"text","text":"fund-a led the widget-co seed."}]}}}
+{"timestamp":"2026-10-01T09:00:07.000Z","type":"event_msg","payload":{"type":"task_complete","turn_id":"turn-1"}}
+{"timestamp":"2026-10-01T09:00:08.000Z","ordinal":0,"type":"event_msg","payload":{"type":"item_completed","thread_id":"thread-1","turn_id":"turn-2","item":{"type":"UserMessage","id":"item-4","content":[{"type":"text","text":"Note that the bridge check-in is every Thursday.","text_elements":[]}]},"started_at_ms":0,"completed_at_ms":0}}
+{"timestamp":"2026-10-01T09:00:09.000Z","type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"Noted: bridge check-in every Thursday."}]}}