Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(hooks): a header-only Codex rollout ends empty_session, not parser_drift (#6399)
time-attack3477c5d68290
diff --git a/docs/architecture/key-files/agent-bootstrap.md b/docs/architecture/key-files/agent-bootstrap.mdindex d0ec4eee61..1fe7986cc8 100644--- a/docs/architecture/key-files/agent-bootstrap.md+++ b/docs/architecture/key-files/agent-bootstrap.md@@ -31,6 +31,6 @@ User-facing contract: `docs/guides/bootstrap.md`. Runbook the paste block fetche- `src/core/transcripts/claude-code-jsonl.ts` — the Claude Code transcript parser as a dated spec-target (tool_use/tool_result/thinking/image/sidechain/summary/compact-boundary shapes; placeholders for non-text content). Both the hook-tail and full-session parsers skip root `isSidechain`, `isMeta`, or `isCompactSummary` exactly `true`; nested markers and truthy non-booleans do not exclude a turn. User text with a non-empty string root `origin.kind` other than `'human'` is excluded; missing, empty, or unstructured origins stay compatible, without guessing from message text. Assistant text and non-text placeholders remain eligible, while skipped metadata entries also contribute no collected tool calls. `test/claude-code-jsonl-origin.test.ts` uses synthetic fixtures, not new live-harness validation. `genuineUserTurnIndexes` separately records accepted user-role turns containing real text blocks (harness tags and paste blocks removed first), because Claude stores tool-result-only entries with `role:'user'`; archival consumers keep every placeholder while prompt-only consumers select by structure. Also extracts `injectedContextBlocks` — the `hook_additional_context` attachment lines a gbrain hook previously injected (verified live against claude CLI 2.1.224; marker-filtered, so a foreign hook's blocks are excluded and another tool's output can't suppress volunteering — a same-user mislabeling guard, not an authenticity check), the user-prompt hook's cross-turn dedupe input; `confineTranscriptPath` (contained under `~/.claude/projects`, `.jsonl`, lstat-rejects symlinks, byte cap; under WSL, a Windows drive-literal `transcript_path` — Claude Code on the Windows host invoking hooks via `wsl.exe` — is translated through `src/core/wsl-paths.ts` and then held to the SAME confinement, rooted Windows-side, so translation never widens what a hook may read). Fixtures: `test/fixtures/conversation-formats/claude-code.jsonl` (synthetic, privacy-guarded) + `test/fixtures/hook-transcript.jsonl` (real captured hook round-trip). `parseTranscript` additionally returns `toolCalls`, but collection is OPT-IN (`collectToolCalls: true`; the bare parse — every per-prompt lane — collects nothing, so tool INPUTS are never retained for users who never opted in): the tool name + input args for every `tool_use` block, oldest → newest, each joined to its `tool_result` outcome by `tool_use_id` and then stripped of that id so no transcript-internal identifier reaches a consumer; every STRING in a collected input is bounded to `TOOL_CALL_VALUE_MAX_CHARS` (32k) with an explicit `…[N chars omitted]` marker (`capToolCallInput`, shared with the codex lane — one receipt-size ceiling for every harness). It is a parallel extraction, never a change to the placeholder-only archival rendering, which is load-bearing for the token-budget-constrained ambient-recall path; existing callers that ignore the field see no behavior change.- `src/core/transcripts/pasted-content.ts` — #5812, the ONE Claude Code paste detector (`<pasted_content id="…">…</pasted_content id="…">`, tag shape from a real 2.1.287 transcript; depends on that harness format). `stripPastedContent` removes closed blocks and an unclosed tail only when the opening tag has the exact harness shape, scanning with `indexOf` (no lazy regex); `stripPastedContentFromCorpus` strips inside each `[user]` block of the `toCorpusText` rendering, never across the flattened corpus, so an unclosed paste ends with its turn. Consumers: the writeback gate (banked text), `isGenuineUserText` in the parser (classification only; turn, corpus, segment and ingest text keep the paste), and `corpusTextForExtraction` (`corpus-segments.ts`: a `.wb-` file is one turn, other corpus files per block) used by the sweep, the checkpoint harvest and dream `extract_atoms`. `synthesize` keeps pastes. Tests: `test/transcripts-pasted-content.test.ts`, `test/facts/writeback-gate.test.ts`, `test/extract-atoms-pasted-content.test.ts`.- `src/core/transcripts/grok.ts` — the Grok Build (grok CLI) transcript adapter: one session directory (`~/.grok/sessions/<url-encoded-cwd>/<uuid>/chat_history.jsonl`) = one session; `GROK_HOME` relocates the root. Turn selection is STRUCTURAL (`mapGrokLine`, exported so the dated `SPEC_TARGET` mapping is pinned): user turns are `type:'user'` text blocks WITHOUT `synthetic_reason` (injected system_reminder/task_completed rows are `typed`, i.e. intentionally text-free, as are tool_result-only user arrays); assistant turns need non-empty string `content` (tool-only rows — `content` ''/null WITH `tool_calls` — are `typed`); system/reasoning/tool_result/backend_tool_call rows are `typed`; unknown row types `skip`. A recognised HUMAN-turn row whose content this parser cannot decode (user `content` missing / non-string / non-array / an array holding non-block entries; assistant non-string `content` with no `tool_calls`) is `malformed` and counted as SKIPPED, never typed, so a file made only of such rows is never `expectedEmpty` — the ingest drift signal fires (`bytesRead > 0`, sessions 0, `cleanScan=false`, watermark frozen) and `zeroSessionsReason` names the malformed row count, instead of an upstream schema change silently advancing the watermark past whole conversations. `chat_history.jsonl` carries NO per-message timestamps: session times come from the sibling `summary.json` (`created_at`/`last_active_at`; a malformed summary is ignored, an unparseable date is never fabricated) and, because grok writes `summary.json` at session END, an in-progress session or partial rsync falls back to the log file's own mtime — a real filesystem time — with `raw.timestamp_source` stamped `'summary.json'` vs `'file_mtime'` so consumers can tell them apart (without the fallback the render refusal would freeze the `--since-last` watermark for the whole grok root). Every message carries the session bounds (last message = `last_active_at`, the rest = start). Session id: summary → UUID dir name → `stableIdFromPath` (a sha256 prefix of the log path, never the bare `chat_history` basename, which would collapse every such session onto one page). Sidecars (updates.jsonl, events.jsonl, rewind_points.jsonl, summary.json, prompt_history.jsonl) are not sessions — discover.ts's grok-sidecar filter is scoped to PROVEN grok trees and the head sniff rejects claude-family keys (grok detection runs after claude-code; an oversized system head still detects through the truncated-line sniff); a percent-encoded cwd segment that fails to decode yields `cwd` undefined with the session id intact.-- `src/core/transcripts/capture-spec.ts` + `codex-hook-lane.ts` — the per-harness session-end capture seam. `capture-spec.ts`: the satisfies-anchored `CAPTURE_SPECS` record ({confine, parse, discover?}) for the STDIN-DRIVEN lanes (claude-code, codex); `captureSpecFor()` resolves unknown/undefined/opencode to the claude spec (golden-pinned by `test/codex-hook-lane.test.ts`); openclaw is deliberately NOT a member (its lane is in-process, trusted-plane — see context-engine.ts). `codex-hook-lane.ts`: `confineCodexTranscriptPath` (the same S3#8 ladder as the claude root, pinned at BOTH `codexSessionsDir()` AND `codexArchivedSessionsDir()` — codex MOVES a rollout into the flat `archived_sessions` store on archive, so fencing only the live store refused a still-valid path; both CODEX_HOME-resolved since the spawner IS codex; an explicitly pinned test-seam `root` stays single-root; ENOENT/ENOTDIR on the path is `missing_path` — the rung hook.ts gates its discovery fallback on — while `unreadable` is reserved for EACCES/IO faults, so the codex session-end heartbeat reason for a nonexistent `transcript_path` after a failed discovery is `transcript_missing_path`, not `transcript_unreadable`; no WSL branch v1), `parseCodexHookTranscript` (ParsedTranscript shape over the adapter's exported `mapCodexLine`; same OPT-IN `collectToolCalls` contract as `parseTranscript`, and the same `capToolCallInput` bound on observed args; head+tail over budget so session_meta identity survives; tool calls from the OBSERVED args keys — `custom_tool_call.input` fixture-verified, `function_call.arguments` source-verified at rust-v0.147.0; tolerant JSON-string parse; NO `result` join — 0.147.0 persists no success flag on `*_output` rows; `compacted` rows become boundary positions), and `discoverNewestCodexRollout` (bounded newest-first walk over the dated live store, then a flat pass over the archived store under the SAME 4096 dirent cap — skipped once the cap trips; id-in-filename match, and an id-matched archived hit keeps `transcript_discovered` (never relabelled `_newest`, which hook.ts reads as a guess and bars from the relay); symlink-reject — the fallback for `transcript_path: null` or a moved rollout, and the seam for SIGKILL'd sessions, which never fire SessionEnd). Engine-free by construction; never imports discover.ts. Pinned by `test/codex-hook-lane.test.ts` + `test/codex-hook-lane-archived.test.ts` + the runHook-driven matrix in `test/memorable-relay.serial.test.ts`.+- `src/core/transcripts/capture-spec.ts` + `codex-hook-lane.ts` — the per-harness session-end capture seam. `capture-spec.ts`: the satisfies-anchored `CAPTURE_SPECS` record ({confine, parse, discover?}) for the STDIN-DRIVEN lanes (claude-code, codex); `captureSpecFor()` resolves unknown/undefined/opencode to the claude spec (golden-pinned by `test/codex-hook-lane.test.ts`); openclaw is deliberately NOT a member (its lane is in-process, trusted-plane — see context-engine.ts). `codex-hook-lane.ts`: `confineCodexTranscriptPath` (the same S3#8 ladder as the claude root, pinned at BOTH `codexSessionsDir()` AND `codexArchivedSessionsDir()` — codex MOVES a rollout into the flat `archived_sessions` store on archive, so fencing only the live store refused a still-valid path; both CODEX_HOME-resolved since the spawner IS codex; an explicitly pinned test-seam `root` stays single-root; ENOENT/ENOTDIR on the path is `missing_path` — the rung hook.ts gates its discovery fallback on — while `unreadable` is reserved for EACCES/IO faults, so the codex session-end heartbeat reason for a nonexistent `transcript_path` after a failed discovery is `transcript_missing_path`, not `transcript_unreadable`; no WSL branch v1), `parseCodexHookTranscript` (ParsedTranscript shape over the adapter's exported `mapCodexLine`; same OPT-IN `collectToolCalls` contract as `parseTranscript`, and the same `capToolCallInput` bound on observed args; head+tail over budget so session_meta identity survives; `recognizedOnly` when every non-blank line parsed and was a session header, so hook.ts ends a Codex session opened and closed with no prompt as `ok`/`empty_session` (no status alert, no corpus file) while any unknown or torn record with zero turns stays `parser_drift`; tool calls from the OBSERVED args keys — `custom_tool_call.input` fixture-verified, `function_call.arguments` source-verified at rust-v0.147.0; tolerant JSON-string parse; NO `result` join — 0.147.0 persists no success flag on `*_output` rows; `compacted` rows become boundary positions), and `discoverNewestCodexRollout` (bounded newest-first walk over the dated live store, then a flat pass over the archived store under the SAME 4096 dirent cap — skipped once the cap trips; id-in-filename match, and an id-matched archived hit keeps `transcript_discovered` (never relabelled `_newest`, which hook.ts reads as a guess and bars from the relay); symlink-reject — the fallback for `transcript_path: null` or a moved rollout, and the seam for SIGKILL'd sessions, which never fire SessionEnd). Engine-free by construction; never imports discover.ts. Pinned by `test/codex-hook-lane.test.ts` + `test/codex-hook-lane-archived.test.ts` + the runHook-driven matrix in `test/memorable-relay.serial.test.ts`.[Continue this subsystem](agent-bootstrap-continued.md).diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex b4c7042717..1da52a8c1a 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -34,7 +34,7 @@ src/commands/sources.ts 2054 ratchet +5 #5988: sources status/retry-held help rosrc/core/link-extraction.ts 2358 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge; links joined only by commas/conjunctions share the verb before the first (coordinated); board roles (BOARD_RE, BOARD_AFTER_RE) resolve to invested_in for an investor page and advises otherwise, never works_at; +1 fix wave 11 #6191: imports targetTakesVerb (role-verb target guard lives in link-target-roles.ts); v0.60.105.0 merge: #5984 Phase 5 link preparation (+6) re-summed over wave 11 at 2211; +109 Q2 Track C: stable verb-rule ids, traceLinkType/explainLinkType (reasons for every typing decision), per-occurrence typer hoisted out of extractPageLinks (makeTypeFor); unit logic lives in core/link-typing-units.ts; +25 Q2 Track C: typing-unit verb rules and vetoes in attachedVerb/traceLinkType, validity stints in explainLinkType; +4 U3: board-seat rule split out of INVESTED_RE (same verb and precedence) and investor-prior/link offsets passed to unit vetoes; +11 U2: locateLink shared by attachedVerb and the U2 post-pass in traceLinkType; -11 lowered: Q2 verdict reverted U2 (locateLink and the post-pass)src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verify; +17 #5334: smoke check samples one representative chunk per distinct page (bounded index-ordered batch walk, longest chunk re-read under the page lock, title-prefixed bounded query); +1 #5334: the smoke-query length limits are shared with the worst-case budgetsrc/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh-src/commands/hook.ts 1926 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import+src/commands/hook.ts 1928 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_driftsrc/core/chunkers/code.ts 1598 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate)src/core/config.ts 1932 ratchet +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept)src/core/bootstrap/harness.ts 2610 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts)diff --git a/src/commands/hook.ts b/src/commands/hook.tsindex b2039d5834..1ca612e17f 100644--- a/src/commands/hook.ts+++ b/src/commands/hook.ts@@ -1725,7 +1725,9 @@ async function hookSessionEnd(io: HookIo): Promise<number> {}turnsN = parsed.turns.length;bytesN = parsed.bytesRead;- if (bytesN > 0 && turnsN === 0) {+ if (bytesN > 0 && turnsN === 0 && parsed.recognizedOnly) {+ reason = 'empty_session'; // opened and closed with no prompt: nothing to bank, not drift+ } else if (bytesN > 0 && turnsN === 0) {// [G3] LOUD: the host format drifted under us — heartbeat error +// status file surfaced at the next session-start.outcome = 'error';diff --git a/src/core/transcripts/claude-code-jsonl.ts b/src/core/transcripts/claude-code-jsonl.tsindex 32f1c4391b..bffbb16729 100644--- a/src/core/transcripts/claude-code-jsonl.ts+++ b/src/core/transcripts/claude-code-jsonl.ts@@ -257,6 +257,13 @@ export interface ParsedTranscript {* span. Kept alongside rather than on ToolCallRecord, which deliberately* carries no transcript-internal positions. */toolCallTurnIndexes: number[];+ /**+ * Set by a lane that can prove the read held only records it recognizes and+ * no conversation: the Codex lane sets it when every non-blank line parsed+ * and was a session header (a session opened and closed with no prompt).+ * Session-end reads it as an empty session instead of parser drift.+ */+ recognizedOnly?: boolean;}/**diff --git a/src/core/transcripts/codex-hook-lane.ts b/src/core/transcripts/codex-hook-lane.tsindex e71a57ee53..ca165be988 100644--- a/src/core/transcripts/codex-hook-lane.ts+++ b/src/core/transcripts/codex-hook-lane.ts@@ -153,6 +153,7 @@ export function parseCodexHookTranscript(let cwd: string | undefined;let parsedLines = 0;let skippedLines = 0;+ let headerLines = 0;for (const line of raw.split('\n')) {const t = line.trim();@@ -168,6 +169,7 @@ export function parseCodexHookTranscript(const mapped = mapCodexLine(entry);switch (mapped.kind) {case 'session':+ headerLines++;// #4981: first header wins (a forked rollout inherits its parent's header// later in the file); identity is payload.id, the id in the rollout filename.if (!sessionId && mapped.sessionId) sessionId = mapped.sessionId;@@ -214,6 +216,7 @@ export function parseCodexHookTranscript(toolCallTurnIndexes,sessionId,cwd,+ recognizedOnly: parsedLines > 0 && skippedLines === 0 && headerLines === parsedLines,};}diff --git a/test/codex-rollout-0154.serial.test.ts b/test/codex-rollout-0154.serial.test.tsindex 8a5c4be2de..143e6fb932 100644--- a/test/codex-rollout-0154.serial.test.ts+++ b/test/codex-rollout-0154.serial.test.ts@@ -16,7 +16,7 @@ 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 { hookStatusPath, 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';@@ -226,3 +226,41 @@ describe('E-N4: assistant turns with no user turn are flagged, never silent', ()});});});++describe('#6399: a header-only rollout (Codex opened and closed with no prompt)', () => {+ const bigHeader = JSON.stringify({+ timestamp: '2026-10-01T09:00:00.000Z',+ type: 'session_meta',+ payload: { id: 'r-empty', session_id: 'r-empty', timestamp: '2026-10-01T09:00:00.000Z', cwd: '/repo', cli_version: '0.159.3', base_instructions: { text: 'x'.repeat(19_000) } },+ });+ async function sessionEnd(id: string, lines: string[]) {+ 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-${id}.jsonl`);+ writeFileSync(rollout, lines.join('\n') + '\n');+ expect(await runHook(['session-end'], { harness: 'codex', stdin: JSON.stringify({ session_id: id, transcript_path: rollout, cwd: join(tmp, 'ws') }) })).toBe(0);+ return (await readHeartbeatTail(1))[0]!;+ }++ test('parser: only session headers → recognizedOnly; a header plus an unknown record or a torn line → not', () => {+ expect(parseCodexHookTranscript(writeRollout('h.jsonl', [bigHeader])).recognizedOnly).toBe(true);+ expect(parseCodexHookTranscript(writeRollout('hu.jsonl', [bigHeader, JSON.stringify({ type: 'brand_new_record', payload: {} })])).recognizedOnly).toBe(false);+ expect(parseCodexHookTranscript(writeRollout('ht.jsonl', [bigHeader, '{"type":"event_msg","payl'])).recognizedOnly).toBe(false);+ expect(parseCodexHookTranscript(FIXTURE_0154).recognizedOnly).toBe(false);+ });++ test('session-end: header-only ends ok/empty_session with no status alert and no corpus file', async () => {+ const hb = await sessionEnd('r-empty', [bigHeader]);+ expect(hb).toMatchObject({ event: 'session-end', outcome: 'ok', reason: 'empty_session', turns: 0 });+ expect(hb.bytes).toBeGreaterThan(19_000);+ expect(existsSync(await hookStatusPath())).toBe(false);+ expect(existsSync(join(tmp, '.gbrain', 'transcripts', 'corpus', 'r-empty.txt'))).toBe(false);+ });++ test('session-end: a header plus an unknown record stays parser_drift', async () => {+ const hb = await sessionEnd('r-drift', [bigHeader.replace(/r-empty/g, 'r-drift'), JSON.stringify({ type: 'brand_new_record', payload: { text: 'hi' } })]);+ expect(hb).toMatchObject({ event: 'session-end', outcome: 'error', reason: 'parser_drift' });+ });+});