Skip to content

fix(codex): validate rollouts structurally instead of by originator - #881

Merged
iamtoruk merged 1 commit into
getagentseal:mainfrom
ozymandiashh:fix/873-codex-originator-structural
Aug 3, 2026
Merged

iamtoruk merged 1 commit into
getagentseal:mainfrom
ozymandiashh:fix/873-codex-originator-structural

Conversation

@ozymandiashh

Copy link
Copy Markdown
Collaborator

Fixes #873
Fixes #626

The bug

Codex rollout discovery gated on session_meta.payload.originator:

const valid = entry.type === 'session_meta' &&
  typeof entry.payload?.originator === 'string' &&
  entry.payload.originator.toLowerCase().startsWith('codex')

But originator is a free-form client identity, not a format marker. Anything driving codex app-server writes structurally identical rollouts under ~/.codex/sessions/ with its own value, and those were dropped silently. This has now bitten three originators in a row: Codex Desktop (#50, fixed by relaxing exact-match to a prefix), JetBrains.IntelliJ IDEA (#626, still open), and t3code_desktop (#873). Each fix admitted one more spelling; the next frontend breaks it again.

Reproduced with three structurally identical rollouts differing only in originator:

$ ls sessions/2026/08/03/
rollout-...-aaaa.jsonl   originator: codex-tui
rollout-...-bbbb.jsonl   originator: t3code_desktop
rollout-...-cccc.jsonl   originator: JetBrains.IntelliJ IDEA

discovered: 1
 - rollout-...-aaaa.jsonl

The fix

Validate structurally, never by string-matching a client name:

const payload: unknown = entry.payload
const valid = entry.type === 'session_meta' &&
  typeof payload === 'object' && payload !== null && !Array.isArray(payload)

That is signal enough. The walker only visits rollout-*.jsonl under the strict YYYY/MM/DD regex path or archived_sessions/, and codex.ts is the only provider that reads ~/.codex — so directory ownership, not originator content, decides the provider. Foreign files (wrong entry type, missing or non-object payload, malformed JSON) are still rejected; the existing negative test still passes. No new originator allowlist, so this class of issue closes permanently rather than one spelling at a time.

No double-counting. Subagent rollouts are already handled by the existing token_count cumulative dedup and the fork-replay cutoff, not by the originator gate. The #873 reporter independently verified a parent thread's cumulative token_count excludes its child threads.

Two things the naive version got wrong

1. The daily cache would have made the fix invisible

usage-aggregator serves every day before today from daily-cache, ensureCacheHydrated only re-parses the gap after lastComputedDate, and retention is 3650 days. Newly-admitted rollouts were rejected before they were ever parsed, so nothing downstream can notice on its own. An upgrading user with a warm cache would have kept pre-fix history forever, while the session list disagreed with the headline:

scenario cost calls sessions
main @ b8c92bf, fresh cache 4.55 1 1
this branch without the bump, reusing main's warm cache 4.55 1 2
this branch, reusing that same warm cache 18.2 2 2
this branch, fresh cache (ground truth) 18.2 2 2

Row 2 is what every existing user would have gotten: the session count moves because discovery now works, but cost and calls stay frozen — the fix looks broken and the undercount is permanent. Row 3 now matches ground truth.

So DAILY_CACHE_VERSION and MIN_SUPPORTED_VERSION go 15 -> 16, with a version-history entry in the established style. This rides the v14 carry-forward, so it is lossless: days whose sources are gone are preserved and marked carried, and there is a test pinning that.

CODEX_CACHE_VERSION and PROVIDER_PARSE_VERSIONS.codex deliberately do not move. Verified both statically and empirically: codex-results.json is only written after a source is discovered and parsed, so a file rejected at discovery never had an entry in either cache. After warming the fixture on main, both cache files contained exactly one key — the first-party rollout — with the third-party one absent. Bumping them would force a needless full re-parse of already-correct sessions.

2. A malformed cwd zeroed out the entire provider

discoverSessionFile did meta.payload?.cwd ?? 'unknown' and passed it to sanitizeProject, which calls .replace(). A rollout with a non-string cwd throws TypeError: cwd.replace is not a function; the throw escapes discoverSessions() and safeDiscoverSessions catches it into [] for all of Codex after one stderr line. Every Codex report reads zero.

This crash exists on main, but only for files already claiming a codex* originator. Relaxing the gate is exactly what makes it reachable from arbitrary third-party clients whose schema conformance is, by this PR's own argument, unverified — so it belongs here. Guarded on both the discovery path and the parse path (sessionCwd flows into projectPath/workingDirectory, and src/parser.ts calls .trim()/.replace()/.toLowerCase() on those).

Tests

Nine new cases, all of which fail without the corresponding fix:

✓ accepts a third-party frontend originator (t3code_desktop)
✓ accepts the JetBrains plugin originator (issue #626)
✓ accepts a rollout with no originator field at all
✓ accepts an archived rollout from a third-party frontend
✓ still rejects foreign and malformed first lines regardless of originator
✓ survives a non-string cwd instead of zeroing out the whole provider
✓ does not leak a non-string cwd into projectPath/workingDirectory
✓ re-derives a warm v15 cache instead of serving its pre-fix rollups
✓ carries a v15 day forward when its sources can no longer re-derive it

Reverting only the two source files gives, verbatim:

× re-derives a warm v15 cache...            → expected +0 to be 1
× carries a v15 day forward...              → expected 4.55 to be 18.2
× survives a non-string cwd...              → cwd.replace is not a function
× does not leak a non-string cwd...         → cwd.replace is not a function

npx vitest run tests/providers/codex.test.ts tests/codex-cache-invalidation.test.ts tests/daily-cache.test.ts tests/daily-cache-carry-forward.test.ts tests/daily-cache-degraded-completeness.test.ts tests/cache-persistence-coldstart.test.ts -> 6 files, 111 tests passed.

npx tsc --noEmit clean.

Full suite, honestly

Branch and pristine main fail the same count on this machine but a rotating cast: the stable core is parser.test.ts (2), cli-status-menubar.test.ts (5), cache-refresh-lock.test.ts (10). The remainder are subprocess-spawning CLI suites timing out under parallel load — they rotate run to run and all pass in isolation (cli-emitters, cli-json-daily, spend-flow, cli-status-menubar -> 4 files, 27 tests passed). I re-ran main in the same session to confirm rather than assuming, since it did not match the baseline I started from.

Docs

docs/providers/codex.md documented the old rule verbatim ("The first line must be a session_meta entry with payload.originator starting with codex") and now describes structural validation.

Codex session discovery required `payload.originator` to start with
"codex" (case-insensitive). `originator` is a free-form client identity
string, not a format marker: any tool driving `codex app-server` writes
structurally identical rollouts under ~/.codex/sessions with its own
value ("t3code_desktop", "JetBrains.IntelliJ IDEA", ...). Those sessions
were silently dropped from every report, and each past fix only admitted
one more spelling.

Gate on structure instead: a first line that parses as JSON, has
type === "session_meta", and carries a plain-object payload. Foreign and
malformed files are still rejected. Directory ownership decides the
provider — codex.ts is the only provider that reads ~/.codex, and the
walk only visits rollout-*.jsonl under the strict YYYY/MM/DD path or
archived_sessions/ — so no double counting is possible. `originator` is
still parsed onto the meta entry; nothing downstream reads it.

Bump the daily cache to v16. Historical days are served from that cache
(usage-aggregator only recomputes today) and retention is ten years, so
without a bump an upgrading user with a warm cache keeps the pre-fix
rollups forever: discovery reruns, so the session COUNT moves, while
cost and calls stay frozen — a self-contradicting report that reads as
"fixed". Measured on a fixture with two same-day rollouts, one
codex-cli and one t3code_desktop:

  pristine main, fresh cache      cost 4.55  calls 1  sessions 1
  this branch, main's warm cache  cost 4.55  calls 1  sessions 2  (was)
  this branch, main's warm cache  cost 18.2  calls 2  sessions 2  (now)
  this branch, fresh cache        cost 18.2  calls 2  sessions 2  (truth)

CODEX_CACHE_VERSION and PROVIDER_PARSE_VERSIONS.codex deliberately stay
put: both caches are keyed per file path and are written only after a
successful parse, so a file rejected at discovery has no entry to
invalidate. Verified on the fixture above — main's codex-results.json
and session-cache.v7.json hold only the first-party rollout, and reusing
them unchanged still yields the correct total.

Harden `payload.cwd` while admitting unverified clients. It is declared
`string` but comes straight off JSON.parse, and a number/object/array
threw "cwd.replace is not a function" out of sanitizeProject; the throw
escaped discoverSessions into safeDiscoverSessions, which returns [] for
the WHOLE provider, so one malformed file made every Codex report read
zero. Guarded in discovery (falls back to the `unknown` project) and on
the parse side, where a non-string cwd would otherwise ride into
projectPath/workingDirectory and reach the parser's path helpers.

Closes getagentseal#873, closes getagentseal#626.

@iamtoruk iamtoruk left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed in depth on the merged tree (current main), fixes #873 and #626.

Verification:

  • Structural validation is a strict superset of the old originator gate, so no previously-counted session changes and third-party frontends (t3code_desktop, JetBrains, no-originator, archived) are now discovered. Mutation-checked: reverting to the originator gate fails the four admission tests.
  • The two non-string-cwd guards prevent a malformed third-party rollout from throwing out of discovery and zeroing the whole codex provider. Mutation-checked: reverting both fails the "survives / does not leak a non-string cwd" tests.
  • DAILY_CACHE_VERSION and MIN_SUPPORTED_VERSION 15->16 force the one-time re-derivation so a warm cache does not serve pre-fix rollups forever; it rides the v14 carry-forward, so v15 days whose sources are gone are preserved and marked carried (no data loss). Mutation-checked: reverting to 15 fails the re-derive and carry-forward tests.
  • Not bumping CODEX_CACHE_VERSION is correct: a discovery-rejected file never had a codex-results.json entry, so newly-admitted rollouts parse fresh on the v16 re-derivation while first-party sessions are served unchanged.
  • No double-count: admission is a superset and the seenKeys / basename / fork-replay dedup layers are untouched.
  • tsc clean; 62 codex + daily-cache tests pass; full suite green apart from the two standing parser.test.ts failures (reproduce on main) and known parallel-load flakes that pass in isolation.

Independent adversarial review confirmed the money invariants (conservation, cache correctness, no data loss). One bounded, non-regressive follow-up: extend the same guard rationale to entry.timestamp (fork-cutoff Date math) and a non-string model, so a malformed third-party rollout is counted rather than silently reading zero for that one session. Tracking that as a small follow-up. Good to merge.

@iamtoruk
iamtoruk merged commit 733003d into getagentseal:main Aug 3, 2026
4 checks passed
pull Bot pushed a commit to nagyist/codeburn that referenced this pull request Aug 3, 2026
Follow-up to getagentseal#881. Structural discovery admits third-party rollouts whose
schema is unverified. Two unchecked JSON.parse fields still reached string ops
on the parse path: an unparseable timestamp threw RangeError out of the
fork-cutoff Date math, and a non-string model threw TypeError from calculateCost
(.replace). Either sank that session's usage to zero. Skip the fork cutoff for
an unparseable timestamp, and only adopt a string model (falling back to a real
model otherwise) so the session is counted instead of silently reading zero.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Codex discovery drops any rollout whose originator doesn't start with "codex" Codex provider skips JetBrains IntelliJ Codex ACP rollout sessions

2 participants