Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(transcripts): Codex sub-agent rollouts no longer hold the --since last watermark (#6741)
garrytan2c1d5bb162f2
diff --git a/src/commands/transcripts.ts b/src/commands/transcripts.tsindex 6b8f9cdb4b..f502795728 100644--- a/src/commands/transcripts.ts+++ b/src/commands/transcripts.ts@@ -335,6 +335,7 @@ 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.subagentRollouts > 0) lines.push(`${r.subagentRollouts} sub-agent rollouts (no user turns by design)`);if (r.driftFiles > 0) {const userless = r.files.filter((f) => f.userTurnsMissing).length;const zero = r.driftFiles - userless;diff --git a/src/core/transcripts/codex.ts b/src/core/transcripts/codex.tsindex ca02c97019..2476759254 100644--- a/src/core/transcripts/codex.ts+++ b/src/core/transcripts/codex.ts@@ -12,7 +12,10 @@* (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'+ * wholesale. A sub-agent rollout (`session_meta` payload.source.subagent,+ * e.g. the guardian auto-reviewer) receives its task only as such injected+ * context, so it has assistant turns and no user turn by design: it reports+ * `subagentRollout`, never `userTurnsMissing` drift (#6741). Assistant text comes from `response_item` payload.type='message'* role='assistant' output_text blocks. reasoning / tool calls / token_count* and every other event kind are skipped — the archive records conversation* text only (lossy by design).@@ -51,8 +54,9 @@ export const CODEX_SPEC_TARGET: HostSpecTarget = {'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 " ++ "cli_version, source}; identity = payload.id (per-thread; session_id is the root " ++ "session shared by forked/subagent threads), first header wins. payload.source is a string ('cli', 'exec', ...) " ++ "or {subagent: ...} for a sub-agent thread, whose task arrives only as injected context. User turns: type 'event_msg' with payload.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 " +@@ -101,7 +105,7 @@ export function isRepeatedCodexUserTurn(previous: { role: string; text: string }* result rather than with an inferred one.*/export type CodexLineResult =- | { kind: 'session'; sessionId?: string; cwd?: string; startedAt?: string; cliVersion?: string; modelProvider?: string }+ | { kind: 'session'; sessionId?: string; cwd?: string; startedAt?: string; cliVersion?: string; modelProvider?: string; subagent?: true }| { kind: 'user'; message: TranscriptMessage }| { kind: 'assistant'; message: TranscriptMessage }| { kind: 'tool_call'; name: string; input: unknown }@@ -138,6 +142,7 @@ export function mapCodexLine(entry: unknown): CodexLineResult {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,+ ...(typeof payload.source === 'object' && payload.source !== null && 'subagent' in payload.source ? { subagent: true as const } : {}),};}if (e.type === 'compacted') return { kind: 'boundary' };@@ -234,6 +239,7 @@ export const codexAdapter: TranscriptAdapter = {let sessionId = '';let cwd: string | undefined;let startedAt = '';+ let subagent = false;const messages: TranscriptMessage[] = [];let rawMeta: Record<string, unknown> | undefined;@@ -255,6 +261,7 @@ export const codexAdapter: TranscriptAdapter = {if (mapped.sessionId) sessionId = mapped.sessionId;if (mapped.cwd) cwd = mapped.cwd;if (mapped.startedAt) startedAt = mapped.startedAt;+ subagent = mapped.subagent === true;rawMeta = {session_id: sessionId,cwd: cwd ?? null,@@ -274,6 +281,7 @@ export const codexAdapter: TranscriptAdapter = {// the consumer that keeps calls and boundary positions.}+ const userless = messages.length > 0 && !messages.some((m) => m.role === 'user');let sessions = 0;if (messages.length > 0) {sessions = 1;@@ -296,7 +304,8 @@ export const codexAdapter: TranscriptAdapter = {sessions,zeroSessionsReason: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,+ userTurnsMissing: userless && !subagent ? true : undefined,+ subagentRollout: userless && subagent ? true : undefined,};},};diff --git a/src/core/transcripts/ingest.ts b/src/core/transcripts/ingest.tsindex 511b024cdb..fb3495a0d4 100644--- a/src/core/transcripts/ingest.ts+++ b/src/core/transcripts/ingest.ts@@ -115,6 +115,8 @@ export interface IngestFileOutcome {drift: boolean;/** E-N4: assistant turns parsed with zero user turns (counted in driftFiles). */userTurnsMissing?: boolean;+ /** #6741: a Codex sub-agent rollout with no user turn by design (counted in subagentRollouts, not drift). */+ subagentRollout?: boolean;/** Adapter degraded to a bounded read (e.g. codex head+tail) — part of the file was never scanned. */truncated: boolean;error?: string;@@ -133,6 +135,8 @@ export interface TranscriptsIngestResult {imperatives: number;partsDeleted: number;driftFiles: number;+ /** #6741: Codex sub-agent rollouts with no user turns by design; understood, so they keep the scan clean. */+ subagentRollouts: number;/** Files whose adapter reported a truncated (partially-unscanned) read. */truncatedFiles: number;erroredFiles: number;@@ -188,6 +192,7 @@ export async function runTranscriptsIngest(imperatives: 0,partsDeleted: 0,driftFiles: 0,+ subagentRollouts: 0,truncatedFiles: 0,erroredFiles: 0,slugsTouched: [],@@ -558,6 +563,10 @@ function applyFileDiagnostics(diag: FileDiagnostics, fileOutcome: IngestFileOutcresult.driftFiles++;result.cleanScan = false;}+ if (diag.subagentRollout) {+ fileOutcome.subagentRollout = true;+ result.subagentRollouts++;+ }if (diag.skippedLines > 0) {// Malformed lines can be DROPPED RECORDS (an actively-appended// file read mid-write, corruption) — freeze the watermark so adiff --git a/src/core/transcripts/types.ts b/src/core/transcripts/types.tsindex 84d3e350bb..3c0011a8a5 100644--- a/src/core/transcripts/types.ts+++ b/src/core/transcripts/types.ts@@ -87,6 +87,12 @@ export interface FileDiagnostics {* ingest reports it as drift and holds the watermark.*/userTurnsMissing?: boolean;+ /**+ * #6741: a Codex sub-agent rollout with assistant turns and no user turn. Its+ * task arrives as injected context by design, so it is understood, not drift,+ * and does not hold the watermark.+ */+ subagentRollout?: boolean;}export interface ParseSessionsOpts {diff --git a/test/transcripts-codex-subagent.test.ts b/test/transcripts-codex-subagent.test.tsnew file mode 100644index 0000000000..0527c7fd2b--- /dev/null+++ b/test/transcripts-codex-subagent.test.ts@@ -0,0 +1,131 @@+/**+ * #6741 A: Codex sub-agent rollouts (`session_meta.payload.source = {subagent: ...}`,+ * e.g. the guardian auto-reviewer) carry their task only as injected+ * `response_item` role=user context, which the adapter skips by design. They are+ * understood, not host-format drift, so they must not hold the `--since last`+ * watermark; an ordinary rollout with assistant turns and no user turn still does.+ *+ * Fails when: a sub-agent rollout is reported as `userTurnsMissing` drift (the+ * watermark never advances and every daily run rescans everything), or when the+ * sub-agent exemption swallows a real drift file.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { codexAdapter } from '../src/core/transcripts/codex.ts';+import type { FileDiagnostics, ParsedSession } from '../src/core/transcripts/types.ts';+import type { TranscriptsIngestResult } from '../src/core/transcripts/ingest.ts';+import { fmtSummary, runTranscripts } from '../src/commands/transcripts.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv } from './helpers/with-env.ts';++let engine: PGLiteEngine;+let dir: string;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 120_000);++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await resetPgliteState(engine);+ dir = mkdtempSync(join(tmpdir(), 'gb-codex-subagent-'));+ return () => rmSync(dir, { recursive: true, force: true });+});++const line = (timestamp: string, type: string, payload: unknown) => JSON.stringify({ timestamp, type, payload });+const meta = (id: string, at: string, source?: unknown) =>+ line(at, 'session_meta', { id, session_id: 'root-session', timestamp: at, cwd: '/repo', cli_version: '0.159.3', ...(source === undefined ? {} : { source }) });+const injectedUser = (at: string, text: string) => line(at, 'response_item', { type: 'message', role: 'user', content: [{ type: 'input_text', text }] });+const assistant = (at: string, text: string) => line(at, 'response_item', { type: 'message', role: 'assistant', content: [{ type: 'output_text', text }] });+const typedUser = (at: string, text: string) => line(at, 'event_msg', { type: 'user_message', message: text });++function rollout(name: string, lines: string[]): string {+ const path = join(dir, name);+ writeFileSync(path, lines.join('\n') + '\n');+ return path;+}++/** The guardian shape from the report: the task arrives only as an injected response_item user row. */+const guardian = () => rollout('rollout-guardian.jsonl', [+ meta('r-guardian', '2026-10-01T09:00:00.000Z', { subagent: { other: 'guardian' } }),+ injectedUser('2026-10-01T09:00:01.000Z', 'Review the proposed command for safety.'),+ assistant('2026-10-01T09:00:02.000Z', 'The command is safe to run.'),+]);+const ordinary = () => rollout('rollout-ordinary.jsonl', [+ meta('r-ordinary', '2026-10-01T10:00:00.000Z'),+ typedUser('2026-10-01T10:00:01.000Z', 'Summarize the build log.'),+ assistant('2026-10-01T10:00:02.000Z', 'The build passed.'),+]);+const drifted = () => rollout('rollout-drift.jsonl', [+ meta('r-drift', '2026-10-01T11:00:00.000Z', 'cli'),+ assistant('2026-10-01T11:00:02.000Z', 'An answer whose user turn the parser no longer recognizes.'),+]);++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 };+}++async function ingestSinceLast(): Promise<TranscriptsIngestResult> {+ const out: string[] = [];+ const log = spyOn(console, 'log').mockImplementation((...args: unknown[]) => { out.push(args.map(String).join(' ')); });+ try {+ await withEnv({ GBRAIN_HOME: dir, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, () =>+ runTranscripts(engine, ['ingest', dir, '--format', 'codex', '--source', 'default', '--since', 'last', '--json', '--quiet']));+ } finally {+ log.mockRestore();+ }+ return JSON.parse(out.join('\n')) as TranscriptsIngestResult;+}++describe('#6741 A: Codex sub-agent rollouts are understood, not drift', () => {+ test('the adapter reports a sub-agent rollout instead of userTurnsMissing; the session still imports', async () => {+ const { sessions, diag } = await drain(codexAdapter.parse(guardian()));+ expect(sessions.map(s => s.messages.map(m => m.role))).toEqual([['assistant']]);+ expect(diag.userTurnsMissing).toBeUndefined();+ expect(diag.subagentRollout).toBe(true);+ });++ test('a non-sub-agent assistant-only rollout is still flagged userTurnsMissing', async () => {+ const { diag } = await drain(codexAdapter.parse(drifted()));+ expect(diag.userTurnsMissing).toBe(true);+ expect(diag.subagentRollout).toBeUndefined();+ });++ test('--since last advances past a sub-agent rollout, and a real drift file still holds it', async () => {+ guardian();+ ordinary();+ const first = await ingestSinceLast();+ expect(first).toMatchObject({ cleanScan: true, driftFiles: 0, subagentRollouts: 1, sessionsImported: 2 });+ expect(first.files.find(f => f.path.endsWith('rollout-guardian.jsonl'))).toMatchObject({ drift: false, subagentRollout: true });++ // The watermark advanced to the newest session, so a rescan filters both.+ const second = await ingestSinceLast();+ expect(second).toMatchObject({ sessionsFiltered: 2, sessionsImported: 0 });++ drifted();+ const third = await ingestSinceLast();+ expect(third).toMatchObject({ cleanScan: false, driftFiles: 1, subagentRollouts: 1 });+ // The drift file held the watermark: its newer session is read again, never skipped.+ const fourth = await ingestSinceLast();+ expect(fourth).toMatchObject({ sessionsFiltered: 2, sessionsImported: 1, cleanScan: false });+ }, 120_000);++ test('the scan summary reports sub-agent rollouts separately from drift', () => {+ const summary = fmtSummary({ files: [], pages: { imported: 0, skipped: 2, errored: 0, planned: 0 }, sessionsSeen: 2, sessionsImported: 2,+ sessionsFiltered: 0, sessionsErrored: 0, sessionsSkippedNoTimestamp: 0, redactions: 0, imperatives: 0, partsDeleted: 0, driftFiles: 0,+ subagentRollouts: 3, truncatedFiles: 0, erroredFiles: 0, slugsTouched: [], cleanScan: true, maxSessionTs: '' });+ expect(summary).toContain('3 sub-agent rollouts (no user turns by design)');+ expect(summary).not.toContain('DRIFT WARNING');+ });+});