Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(hooks): Codex context hooks read the session's source from the payload cwd (#5941)

time-attack66dedca82da2
diff --git a/docs/architecture/key-files/agent-bootstrap.md b/docs/architecture/key-files/agent-bootstrap.md
index ad8b310d69..3e907bddb5 100644
--- a/docs/architecture/key-files/agent-bootstrap.md
+++ b/docs/architecture/key-files/agent-bootstrap.md
@@ -31,7 +31,7 @@ User-facing contract: `docs/guides/bootstrap.md`. Runbook the paste block fetche
- `src/core/bootstrap/atomic-write.ts` — the ONE atomic config-file writer for bootstrap host surfaces: symlink-target-resolving, mode-inheriting (`freshMode` for new files, `forceMode` for secret-bearing targets), random-suffix tmp + rename, tmp unlinked best-effort when write/chmod/rename throws (ENOSPC/EACCES never strand `.tmp-` litter), and the existsSync→realpathSync race falls back to fresh-path resolution instead of throwing raw ENOENT. hooks.ts (JSON), codex-toml.ts (TOML+EOL), and opencode-json.ts (JSONC) all swap through it; serialization and EOL policy stay caller-side.
- `src/core/bootstrap/harness.ts` — `gbrain bootstrap harness`: machine-level wiring of framework-spawned Claude Code/Codex/opencode sessions to a RUNNING `gbrain serve --http`, no `agent.json`. The opencode target mirrors the codex posture: forced-wire on explicit `--harness opencode` (the JSONC writer needs no CLI), one managed `mcp.<name>` remote entry with the inline bearer header (0600) via `opencode-json.ts`, rotation across a url change recognized through the PRIOR receipt's url, failed-smoke rollback restoring the run's UNIQUE backup or removing a fresh entry — guarded by a content compare against the exact text this run wrote, so a NEWER registration that landed after the lock released is never clobbered (rollback skips with a note; the fresh mint is revoked either way), with the backup unlinked once consumed or once the smoke verifies — `--remove` classifying against the receipt url (not-ours skips with a note), and `--status` bearer recovery via `parseOpencodeEntryBearer` (url-matched). An explicit private posture (file-plane `memory.visibility_posture`) prints a pre-consent WARNING outside registrar mode: the wired HTTP sessions read world facts only, so they cannot read back what they save as private. Consent block in the honesty register (reach as fact, transcript capture its own numbered item + `--no-capture`, off-ramps in the same breath), then `requireConsent` via `consentGate` (effects `persistent_install`, plus `credentials` when it mints the token; `--yes` approves; the TTY prompt runs only when `isInteractive()`, and EOF/decline or no human at the terminal writes nothing and exits 3 with the consent payload, whose argv never repeats `--token`); /health probe with a loopback guard on `--url` (remote brains are `gbrain connect`'s charter; `--token` makes it a pure registrar); mint-first rotation (previous token revoked BY ID only after every target confirms + the bearer smoke passes — clients are never dead mid-swap; revoke-by-name never happens); the smoke is canary-gated: a random same-format bearer must FAIL auth before the real token is sent, so a loopback impostor is caught whichever way it answers, and ANY failed smoke rolls back symmetrically — fresh registrations removed, replaced ones restored (an unrestorable replacement fails the target honestly), the freshly-added pre-approval stripped, and the fresh mint revoked immediately so nothing live stays pointed at an unverified endpoint; the `permissions.allow` pre-approval only lands after the MCP registration itself confirms; stale prior-target cleanup runs AFTER the smoke passes, so a run that failed to establish its replacement never unwires working prior wiring; write-ahead harness receipt (targets persist as `pending` at mint time and flip per-target, so a crash leaves consumable state); registration ownership checks (`--force` to replace a foreign-url server; `--remove` skips what it no longer owns); user-XOR-project hook scopes; `GBRAIN_HOOK_LANE=harness` on hook commands so `gbrain hook` yields to a workspace bootstrap install in the cwd (Claude Code merges settings scopes — same event must not fire twice); the hook `GBRAIN_SOURCE`, the receipt `source_id`, and the token grant bind to a validated `--source` (scalar write floor), else to the source `HarnessDeps.resolveHookSource` resolves through the SAME chain the serve's resolve-IPC binding runs (`resolveSourceWithTier`: env → dotfile → local_path → `sources.default` → sole populated non-default → seed default) with that source's federated read set as the grant, so the hooks' `turn_context` claim is never `source_mismatch`; a resolution landing on `default`/`__all__` is the federated floor. Lookup failures are NOT papered over with `default`: a typo'd `--source` or stale env/dotfile throws `SOURCE_UNRESOLVED` before any mint or receipt; an explicit `--source` with an unopenable engine binds unverified with a warning; a live PGLite serve (engine cannot open) refuses with `LIVE_SERVE` when no token was supplied, printing (and in `details.steps`) stop / `auth create` + `auth rescope --operations` with the harness grant / restart / `--token` (#6661) and, on the `--token` lane without `--source`, wires the hooks UNPINNED with a warning (an unpinned hook resolves through the live serve's own binding; the receipt records the federated floor `default` plus `source_pinned: false`); any other lookup failure throws `SOURCE_UNRESOLVED` naming `--source`; Postgres degradation + serve-version-skew honesty lines (`isServeOlderThanScopes` pinned to `SCOPES_MIN_SERVE_VERSION`, the first scope-aware release, so later CLI bumps never re-trigger the warning); `--status` probes the live truth with host-config token recovery (redacted; the Claude Code lane recovers a bearer ONLY from a registration whose URL matches the receipt — never another install's credential; the codex fallback reads OUR managed block at the receipt-recorded path, its `url` key not yet compared — TODOS.md; the opencode fallback IS url-compared inside `parseOpencodeEntryBearer`) and honest `verify: unavailable` degrades, with a cron-honest exit contract: 0 only when serve + token + every target verify and the rotation has converged (honest degrades count), 1 on an unreachable serve, a failed token verify, failed/pending targets, unconverged rotations, or a half-removed receipt (zero targets, minted token awaiting deferred revoke — also a doctor FAIL); no receipt prints honestly and exits 0 in plain mode, 2 under `--json`; `--json` on apply emits ONLY the final JSON document on stdout (prose → stderr); `--remove` is engine-free-first and defers the token revoke with exact instructions under a live PGLite serve; it removes hook entries that lost their marker when their command is this install's (`harness-hooks.ts`), keeps the hooks target failed on an unowned lookalike, and `--remove --dry-run` previews without a lock or any write. Hooks targets record `launcher` and `seat` on the receipt (the ownership identity for later runs); the permission target carries `mechanism: 'added'` forward from a prior confirmed receipt target so a re-run never relabels its own `mcp__<name>` as pre-existing, and the failed-smoke rollback removes only an entry added this run. Locks on the gbrain HOME, plus the host config dir around codex/opencode writes, removals, rollbacks, and stale cleanup (stale prior-target cleanup nests the codex/opencode config-dir lock inside the held claude config-dir lock — same claude-first ordering as apply/remove, same-dir skip — so its read-modify-write can't interleave with a concurrent config-dir-locked writer); `bootstrap uninstall` holds the HOME lock across the whole teardown and runs harness removal FIRST (revoke needs the DB alive; `--delete-brain` would destroy harness.json) and treats NO_RECEIPT/HOME_GUARD/RECEIPT_MISMATCH as "no workspace install" once harness wiring is cleared. Pinned by `test/bootstrap-harness.serial.test.ts` + `test/bootstrap-harness-lifecycle.serial.test.ts`. The production mint (`mintHarnessToken`, exported) rotates each host's token from the token it replaces via `carryLegacyGrant`. `--refresh-skills` (`src/core/bootstrap/harness-skills.ts`, `refreshHarnessSkills`) re-joins each live shared-skills entry under its recorded credential so the receipt and native router adopt the server's current enrollment epoch, with no token rotation; `localEnrollment` reads the adapter receipt epoch for `--status`, and `supersededEnrollments` is doctor's read-only comparison against `shared_skill_members` (`bootstrap_harness_health` warn, code `shared_skills_epoch_superseded`). Pinned by `test/harness-skills-epoch.test.ts`. The Codex SessionEnd capture hook obeys the same recorded consent as the Claude lane (`wireCodexCapture`: hooks on, capture accepted, never registrar mode) and is a numbered consent item when wired.
- `src/core/token-mint.ts` — programmatic legacy-token mint/revoke for the harness lane: `mintLegacyToken` (scopes → the TEXT[] column; required `takesHolders` per-token allow-list, harness default `['world']`; optional `permissions.source_id` federation array mirroring the stdio lane's `localFederatedSourceIds` grant, element 0 = write floor, `[]` stored as the explicit no-source grant; `RETURNING id`) and `revokeLegacyTokenById` (never touches same-name siblings). `carryLegacyGrant` + `readActiveTokenPermissions` are the harness rotation carry-over: takes holders and the source grant carry as stored (explicit empty lists included; an explicit `--source` wins), a stored operation snapshot narrows to the run's snapshot plus only skills-policy-added operations, and newer operations are reported as withheld (pinned by `test/harness-rotation-grants.test.ts`). Exports `TOKEN_ID_RE`, the canonical token-id shape shared with the `auth revoke --id` CLI gate. Canonical `hashToken`/`generateToken` from `src/core/utils.ts`. Pinned by `test/token-mint.test.ts`. `insertUnifiedToken` (shared with `auth create`) births every token on the unified grant columns at revision 1 plus the `permissions` mirror; a brain whose schema predates the columns refuses with `migrations_pending` (fix: `gbrain apply-migrations --yes`) and nothing is written; `carryLegacyGrant` parses the prior grant from its JSONB through `tokenGrantFromPermissions`, so a drifted prior carries its JSON edit (the `--adopt-permissions` resolution).
-- `src/commands/hook.ts` — engine-free `gbrain hook {session-start,user-prompt,stop,session-end,compact}` (zero engine modules in the import graph; a hook must NEVER contend for the PGLite writer lock). session-start's context pack goes through `src/core/context/session-start-pack.ts`: when `sessionStartAwaitsServe` holds (source `startup`/`resume`, harness claude-code, `claudeCodeSpawnsServe(cwd)`), the hook's deadline widens from `SESSION_START_DEADLINE_MS` (1.5s) to `SESSION_START_SERVE_WAIT_DEADLINE_MS` (4s, under the 5s harness timeout) and `requestSessionStartPack` retries every 100ms, re-resolving socket and secret, until the serve Claude Code spawned alongside SessionStart answers (Cat 41 first push: Claude Code 2.1.285 starts MCP servers in parallel with SessionStart and a fresh serve binds ~2s later); a wait that runs out records heartbeat `degraded`/`serve_not_ready`. Pinned by `test/hook-session-start-serve-wait.serial.test.ts`. When `GBRAIN_HOOK_LANE=harness` (set on harness-mode hook commands), each event PARSES the cwd's workspace settings carriers — `.claude/settings.local.json` AND the committed `.claude/settings.json` — and yields silently only when a live `bootstrap-v1` hook entry wires THAT event: the workspace install wins over user-scope harness wiring so the merged settings scopes can't fire the same event twice, unwired events still run, and a repo committing marker-lookalike strings in unrelated fields can't disable the machine-wide capture lane (fail-open — a read/parse hiccup means the event runs normally). user-prompt: stdin hook JSON → transcript-path confinement → last-4-turns window + cross-turn dedupe (the transcript's `hook_additional_context` attachments — the blocks WE previously injected — ride `priorContextText`, deduplicated and capped at `PRIOR_CONTEXT_MAX_BYTES` (32KB, so the advisory payload can never blow the IPC message cap; one oversized block is skipped without evicting smaller ones), so a page is volunteered once per session, not once per mention; structured extraction only, never raw-turn substring matching) → IPC turn_context (with a feedback-loop `channel`, `--harness <claude-code|codex>`, default claude-code) → `hookSpecificOutput.additionalContext` under an 800ms self-deadline; every path fails open (exit 0, empty stdout) with a typed reason in the heartbeat. Listed in cli.ts's `STARTUP_HOOK_SKIP_COMMANDS` (per-prompt invocations must never spawn a detached check-update child; membership is pinned by a source grep — the runtime path no-ops under NODE_ENV=test). session-start: file-plane digest (allowlisted MEMORY.md sections, push staleness, prior failures) + crashed-session recovery push gated on an initialized manifest. session-end: a transcript path or payload cwd carrying the claude-cli scratch fingerprint (`isClaudeCliSelfTranscriptPath`) is gbrain's own subprocess session — heartbeat `segment: self_transcript`, no parse, no corpus write; otherwise confined full-transcript parse → redacted corpus write (session-id filename dedup, retention prune via `gcCorpusTurnFiles`: an extracted `.txt` goes at `corpus_retention_days`, one with no `.ingested` sidecar only at `CORPUS_UNINGESTED_RETENTION_FACTOR` (3) times that, E-N1, pinned by `test/corpus-retention-uningested.serial.test.ts`; an assistant-only whole-file parse heartbeats `degraded`/`no_user_turns`, E-N4; the corpus scan runs highEntropy whenever the relay is on — the relay child derives its egress task line from the corpus text — and stays vendor-prefix-only otherwise) → parser-drift detection (`bytes>0 && turns==0` is loud) → best-effort workspace push. session-start recovery + session-end pushes run in a DETACHED child so the hook returns immediately (a synchronous inline push would block harness startup on a dirty tree); the corpus write is atomic and clears the stale ingested/in-progress sidecars so a resumed session re-ingests its appended transcript. Heartbeat JSONL is counters/reasons only by construction; `readHeartbeatTail` feeds doctor. `GBRAIN_HOOKS=0` kills all events. Session-end capture dispatches per harness through `captureSpecFor(io.harness)` (`src/core/transcripts/capture-spec.ts`): claude-code and codex each pin their OWN confinement root + parser; unknown/undefined/opencode resolve to the claude spec (golden-pinned). The codex lane confines to `codexSessionsDir()` + `codexArchivedSessionsDir()` (codex moves rollouts into the flat archived store), parses rollouts via `parseCodexHookTranscript`, and falls back to bounded id-matched discovery across both stores when the SessionEnd payload carries `transcript_path: null` or a path that no longer exists (`missing_path`; `unreadable` is reserved for EACCES/IO faults) — the fallback and prior-run relay failures are DEFERRED heartbeat reasons, applied after current-session reasons so they never mask one (first-degrade-wins). ONE gate covers the whole optional Memorable seam — `memorableGateAllowed(cfg)` in hook-heartbeat.ts: the config flag (`integrations.memorable.enabled === true`, file plane), the `GBRAIN_MEMORABLE` kill switch (any common negative spelling, trimmed; env can only ever disable), AND the gbrain-authored consent stamp (`memorable-consent.json` — see hook-heartbeat.ts). Off is the default: no tool-call collection, no receipt, no spawn. On, session-end runs the shared `redactedToolCallsJson` (span-filtered to the corpus window, highEntropy ALWAYS on — those args are the one artifact that leaves the machine) and `recordAndRelayReceipt` (receipt dedup by post-redaction content hash → CLI-side consent evidence → `resolveMemorableBin` → detached fire-and-forget `memorable record` spawn; both capture lanes trim memorable-relay.jsonl). Fail-closed egress guards: a scanner-import failure skips the receipt+relay entirely (`memorable_relay_skipped_unscanned` — parity with the openclaw lane), and a newest-mtime discovery GUESS (no session-id match) writes the local corpus but never relays (`memorable_relay_skipped_newest_guess` — the newest rollout can be a different, still-running session). A payload without session_id adopts the transcript's own id post-parse (never a shared unknown.txt corpus), and the gate answer is hoisted BEFORE the parse and collection is opt-in, so the default gate-off population never collects tool calls (`collectToolCalls: memorableAllowed`). Operator-facing doc: `docs/memorable-agents.md` (install is `npm i -g memorable-cli`; closed source, no source install, no embedding model to configure). `spawnDetachedPush` passes `env: process.env` explicitly so the detached push child inherits the parent's quarantined env view. `tryExecAsync` (the git wrapper behind `resolveBootstrapWorkspaceRoot` / `repoPhaseComplete`) also passes `env: process.env` so git sees the quarantined view, not Bun's startup snapshot; pinned by `test/hook-push-spawn-env.test.ts`. Seat identity (#4618): session-end (before any corpus write of the session), compact (before `bankCompactSegment`) and the stop hook's writeback bank (before `bankWritebackTurn`) record `<sessionId>.seat.json` through `context/seat.ts` — `GBRAIN_SEAT` when valid, else the hashed harness-home seat; `seat_label_invalid`, `seat_conflict` (first seat kept) and `seat_write_failed` are heartbeat reasons with a fixed `hint` (session-end applies them last, like the deferred reasons). `gcCorpusArtifacts` reaps a seat sidecar or session source record once no `.txt` of its session remains, after a 10-minute grace; session-end counts live sessions across the spool and the legacy top level (#6611). Pinned by `test/session-seat-capture.serial.test.ts`. `HOOK_EVENTS` is the router inventory from `src/cli/subcommands.ts`; `hook <event> --help` prints usage and never runs the event. `user-prompt` confines and parses `transcript_path` through `captureSpecFor(io.harness)`, so `--harness codex` reads the rollout under `CODEX_HOME/sessions` (the Claude projects root otherwise), and skips the Claude-only pressure notice for codex.
+- `src/commands/hook.ts` — engine-free `gbrain hook {session-start,user-prompt,stop,session-end,compact}` (zero engine modules in the import graph; a hook must NEVER contend for the PGLite writer lock). session-start's context pack goes through `src/core/context/session-start-pack.ts`: when `sessionStartAwaitsServe` holds (source `startup`/`resume`, harness claude-code, `claudeCodeSpawnsServe(cwd)`), the hook's deadline widens from `SESSION_START_DEADLINE_MS` (1.5s) to `SESSION_START_SERVE_WAIT_DEADLINE_MS` (4s, under the 5s harness timeout) and `requestSessionStartPack` retries every 100ms, re-resolving socket and secret, until the serve Claude Code spawned alongside SessionStart answers (Cat 41 first push: Claude Code 2.1.285 starts MCP servers in parallel with SessionStart and a fresh serve binds ~2s later); a wait that runs out records heartbeat `degraded`/`serve_not_ready`. Pinned by `test/hook-session-start-serve-wait.serial.test.ts`. When `GBRAIN_HOOK_LANE=harness` (set on harness-mode hook commands), each event PARSES the cwd's workspace settings carriers — `.claude/settings.local.json` AND the committed `.claude/settings.json` — and yields silently only when a live `bootstrap-v1` hook entry wires THAT event: the workspace install wins over user-scope harness wiring so the merged settings scopes can't fire the same event twice, unwired events still run, and a repo committing marker-lookalike strings in unrelated fields can't disable the machine-wide capture lane (fail-open — a read/parse hiccup means the event runs normally). user-prompt: stdin hook JSON → transcript-path confinement → last-4-turns window + cross-turn dedupe (the transcript's `hook_additional_context` attachments — the blocks WE previously injected — ride `priorContextText`, deduplicated and capped at `PRIOR_CONTEXT_MAX_BYTES` (32KB, so the advisory payload can never blow the IPC message cap; one oversized block is skipped without evicting smaller ones), so a page is volunteered once per session, not once per mention; structured extraction only, never raw-turn substring matching) → IPC turn_context (with a feedback-loop `channel`, `--harness <claude-code|codex>`, default claude-code) → `hookSpecificOutput.additionalContext` under an 800ms self-deadline; every path fails open (exit 0, empty stdout) with a typed reason in the heartbeat. Listed in cli.ts's `STARTUP_HOOK_SKIP_COMMANDS` (per-prompt invocations must never spawn a detached check-update child; membership is pinned by a source grep — the runtime path no-ops under NODE_ENV=test). session-start: file-plane digest (allowlisted MEMORY.md sections, push staleness, prior failures) + crashed-session recovery push gated on an initialized manifest. session-end: a transcript path or payload cwd carrying the claude-cli scratch fingerprint (`isClaudeCliSelfTranscriptPath`) is gbrain's own subprocess session — heartbeat `segment: self_transcript`, no parse, no corpus write; otherwise confined full-transcript parse → redacted corpus write (session-id filename dedup, retention prune via `gcCorpusTurnFiles`: an extracted `.txt` goes at `corpus_retention_days`, one with no `.ingested` sidecar only at `CORPUS_UNINGESTED_RETENTION_FACTOR` (3) times that, E-N1, pinned by `test/corpus-retention-uningested.serial.test.ts`; an assistant-only whole-file parse heartbeats `degraded`/`no_user_turns`, E-N4; the corpus scan runs highEntropy whenever the relay is on — the relay child derives its egress task line from the corpus text — and stays vendor-prefix-only otherwise) → parser-drift detection (`bytes>0 && turns==0` is loud) → best-effort workspace push. session-start recovery + session-end pushes run in a DETACHED child so the hook returns immediately (a synchronous inline push would block harness startup on a dirty tree); the corpus write is atomic and clears the stale ingested/in-progress sidecars so a resumed session re-ingests its appended transcript. Heartbeat JSONL is counters/reasons only by construction; `readHeartbeatTail` feeds doctor. `GBRAIN_HOOKS=0` kills all events. Session-end capture dispatches per harness through `captureSpecFor(io.harness)` (`src/core/transcripts/capture-spec.ts`): claude-code and codex each pin their OWN confinement root + parser; unknown/undefined/opencode resolve to the claude spec (golden-pinned). The codex lane confines to `codexSessionsDir()` + `codexArchivedSessionsDir()` (codex moves rollouts into the flat archived store), parses rollouts via `parseCodexHookTranscript`, and falls back to bounded id-matched discovery across both stores when the SessionEnd payload carries `transcript_path: null` or a path that no longer exists (`missing_path`; `unreadable` is reserved for EACCES/IO faults) — the fallback and prior-run relay failures are DEFERRED heartbeat reasons, applied after current-session reasons so they never mask one (first-degrade-wins). ONE gate covers the whole optional Memorable seam — `memorableGateAllowed(cfg)` in hook-heartbeat.ts: the config flag (`integrations.memorable.enabled === true`, file plane), the `GBRAIN_MEMORABLE` kill switch (any common negative spelling, trimmed; env can only ever disable), AND the gbrain-authored consent stamp (`memorable-consent.json` — see hook-heartbeat.ts). Off is the default: no tool-call collection, no receipt, no spawn. On, session-end runs the shared `redactedToolCallsJson` (span-filtered to the corpus window, highEntropy ALWAYS on — those args are the one artifact that leaves the machine) and `recordAndRelayReceipt` (receipt dedup by post-redaction content hash → CLI-side consent evidence → `resolveMemorableBin` → detached fire-and-forget `memorable record` spawn; both capture lanes trim memorable-relay.jsonl). Fail-closed egress guards: a scanner-import failure skips the receipt+relay entirely (`memorable_relay_skipped_unscanned` — parity with the openclaw lane), and a newest-mtime discovery GUESS (no session-id match) writes the local corpus but never relays (`memorable_relay_skipped_newest_guess` — the newest rollout can be a different, still-running session). A payload without session_id adopts the transcript's own id post-parse (never a shared unknown.txt corpus), and the gate answer is hoisted BEFORE the parse and collection is opt-in, so the default gate-off population never collects tool calls (`collectToolCalls: memorableAllowed`). Operator-facing doc: `docs/memorable-agents.md` (install is `npm i -g memorable-cli`; closed source, no source install, no embedding model to configure). `spawnDetachedPush` passes `env: process.env` explicitly so the detached push child inherits the parent's quarantined env view. `tryExecAsync` (the git wrapper behind `resolveBootstrapWorkspaceRoot` / `repoPhaseComplete`) also passes `env: process.env` so git sees the quarantined view, not Bun's startup snapshot; pinned by `test/hook-push-spawn-env.test.ts`. Seat identity (#4618): session-end (before any corpus write of the session), compact (before `bankCompactSegment`) and the stop hook's writeback bank (before `bankWritebackTurn`) record `<sessionId>.seat.json` through `context/seat.ts` — `GBRAIN_SEAT` when valid, else the hashed harness-home seat; `seat_label_invalid`, `seat_conflict` (first seat kept) and `seat_write_failed` are heartbeat reasons with a fixed `hint` (session-end applies them last, like the deferred reasons). `gcCorpusArtifacts` reaps a seat sidecar or session source record once no `.txt` of its session remains, after a 10-minute grace; session-end counts live sessions across the spool and the legacy top level (#6611). Pinned by `test/session-seat-capture.serial.test.ts`. `HOOK_EVENTS` is the router inventory from `src/cli/subcommands.ts`; `hook <event> --help` prints usage and never runs the event. `user-prompt` confines and parses `transcript_path` through `captureSpecFor(io.harness)`, so `--harness codex` reads the rollout under `CODEX_HOME/sessions` (the Claude projects root otherwise), and skips the Claude-only pressure notice for codex. #5941: the pack and user-prompt arms ask for `contextSourceId` (session-start-pack.ts): `GBRAIN_SOURCE`, else the session's frozen source record, else the cwd's `.gbrain-source` walk; a serve bound elsewhere answers `source_mismatch` (the heartbeat reason).
- `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.
diff --git a/docs/mcp/CODEX.md b/docs/mcp/CODEX.md
index 788d3474b3..08c864280f 100644
--- a/docs/mcp/CODEX.md
+++ b/docs/mcp/CODEX.md
@@ -247,7 +247,15 @@ codex mcp remove gbrain
`UserPromptSubmit`, `SessionEnd` in `$CODEX_HOME/hooks.json`, each trusted by
a `[hooks.state]` entry in config.toml); `gbrain setup codex` wires the two
read-context hooks so brain pages named in a prompt arrive as context without
- a tool call. Without those hooks (the plugin, `connect` or `--no-hooks`), use
+ a tool call. `hooks.json` is machine-wide, so those hooks name no source:
+ each session reads context from the source its capture uses, `GBRAIN_SOURCE`
+ first, else the `.gbrain-source` file found walking up from the session's
+ working directory (fixed for the session at its first hook). A repository's
+ committed `.gbrain-source` therefore picks which source Codex reads there,
+ the same as every `gbrain` command run in it. When that source has no serve
+ of its own, the shared serve refuses with `source_mismatch` (the hook
+ heartbeat's reason) and the session gets no context rather than another
+ source's (#5941). Without those hooks (the plugin, `connect` or `--no-hooks`), use
the pull path: at the start of a topical thread and after a compaction, call
`context_pack(entities, budget_tokens)` to warm the standing entities; on a
periodic wake call `delta(session_id, budget_tokens)` for "what changed since
diff --git a/src/commands/hook.ts b/src/commands/hook.ts
index 4c59a3c81a..4b9f7140ce 100644
--- a/src/commands/hook.ts
+++ b/src/commands/hook.ts
@@ -59,7 +59,7 @@ import {
type TurnContextResponse,
type ContextPackResponse,
} from '../core/context/resolve-ipc.ts';
-import { requestSessionStartPack, sessionStartAwaitsServe } from '../core/context/session-start-pack.ts';
+import { contextSourceId, requestSessionStartPack, sessionStartAwaitsServe } from '../core/context/session-start-pack.ts';
import type { WindowTurn } from '../core/context/entity-salience.ts';
import {
confineTranscriptPath,
@@ -555,8 +555,9 @@ async function hookSessionStart(io: HookIo): Promise<number> {
// the remaining deadline. Same session-id sanitizer as the compact
// banking path (a raw id would split the cursor key).
serveNotReady = awaitServe; // still true if the deadline fires mid-wait
+ const sourceId = await contextSource(io, cfg, j?.session_id, ws);
const res = await requestSessionStartPack(cfg, {
- sourceId: process.env.GBRAIN_SOURCE || undefined,
+ sourceId,
sessionId: sanitizeSessionId(j?.session_id),
trigger: typeof j?.source === 'string' ? `session-start:${j.source as string}` : 'session-start',
deadlineAt: t0 + deadlineMs,
@@ -564,6 +565,7 @@ async function hookSessionStart(io: HookIo): Promise<number> {
});
serveNotReady = res.serveNotReady;
const pack = res.pack;
+ if (pack && !pack.ok && pack.error === 'source_mismatch' && outcome === 'ok') { outcome = 'degraded'; reason = 'source_mismatch'; } // #5941
if (pack?.ok && pack.block?.text) out.push(pack.block.text);
if (pack?.ok && pack.block?.core && process.env.GBRAIN_CORE !== '0') coreBox.core = pack.block.core;
else if (pack?.ok && !pack.block?.core) coreBox.reason = 'stale_serve_no_core';
@@ -1175,15 +1177,15 @@ async function hookUserPrompt(io: HookIo): Promise<number> {
// Postgres off hash12(database_url) under ~/.gbrain/run. Null = no
// keying material at all (no config, thin-client remote) — ENGINE-FREE
// means no direct-engine fallback here; pull-mode covers it.
- const socketPath = await hookResolveSocketForConfig(cfg, process.env.GBRAIN_SOURCE);
+ const sessionId = typeof j.session_id === 'string' ? j.session_id : undefined;
+ const sourceId = await contextSource(io, cfg, sessionId, io.cwd ?? (typeof j.cwd === 'string' ? j.cwd : process.cwd()));
+ const socketPath = await hookResolveSocketForConfig(cfg, sourceId);
if (!socketPath) {
return { outcome: 'degraded', reason: 'no_pglite_path' };
}
const secret = readIpcSecretForConfig(cfg);
if (!secret) return { outcome: 'degraded', reason: 'no_serve' };
- const sessionId = typeof j.session_id === 'string' ? j.session_id : undefined;
- const sourceId = process.env.GBRAIN_SOURCE || undefined;
const res = await requestTurnContext(socketPath, {
secret,
window: turns,
@@ -1623,6 +1625,12 @@ async function corpusDir(cfg: GBrainConfig | null): Promise<string> {
const sessionCorpus = async (io: HookIo, cfg: GBrainConfig | null, sessionId: string, cwd: string) =>
openSessionCorpus(await corpusDir(cfg), sessionId, { cwd, harness: io.harness ?? 'claude-code' });
+/** #5941: the context arms' source (session-start-pack.ts `contextSourceId`): the session's frozen record when there is a session id. */
+const contextSource = (io: HookIo, cfg: GBrainConfig | null, rawSessionId: unknown, cwd: string) => {
+ const sid = sanitizeSessionId(rawSessionId);
+ return contextSourceId(sid !== 'unknown' ? () => sessionCorpus(io, cfg, sid, cwd) : null, cwd);
+};
+
function corpusRetentionDays(cfg: GBrainConfig | null): number {
// Key is plan-defined [G15] but not yet in the GBrainConfig type (config.ts
// is another lane's file) — read tolerantly.
diff --git a/src/core/bootstrap/host-specs.ts b/src/core/bootstrap/host-specs.ts
index c905bca761..1b41a172f3 100644
--- a/src/core/bootstrap/host-specs.ts
+++ b/src/core/bootstrap/host-specs.ts
@@ -437,17 +437,20 @@ export function codexAgentsOverridePath(): string {
return join(codexHome(), 'AGENTS.override.md');
}
-/** Codex hook events gbrain wires (v1: session-end capture only — a
- * SessionStart greeting lane is a filed follow-up). */
+/** Codex hook events the BOOTSTRAP lane wires: SessionEnd capture only. The
+ * SessionStart and UserPromptSubmit context hooks belong to `gbrain setup
+ * codex`'s hash-owned writer (codex-hooks.ts `CODEX_SETUP_EVENTS`); they bake
+ * no source, and `gbrain hook` resolves it per session from the payload cwd
+ * (#5941). */
export const CODEX_HOOK_EVENTS = ['SessionEnd'] as const;
/**
* Whether gbrain WIRES codex hooks. True as of the Memorable wave: bootstrap
* writes a SessionEnd entry into hooks.json plus its config.toml trust-state
* entry (codex-hooks.ts — the 0.147.0 trust gate makes an untrusted entry
- * silently inert). SESSION-END CAPTURE ONLY: per-turn context on codex
- * remains the pull-protocol AGENTS.md gates (plan D5); a SessionStart lane
- * is a filed follow-up.
+ * silently inert). The bootstrap lane wires SESSION-END CAPTURE ONLY;
+ * per-turn context comes from `gbrain setup codex`'s SessionStart and
+ * UserPromptSubmit hooks, or else the pull-protocol AGENTS.md gates (plan D5).
*/
export const CODEX_HAS_HOOKS = true;
diff --git a/src/core/context/session-start-pack.ts b/src/core/context/session-start-pack.ts
index cec667067e..4829f86ee9 100644
--- a/src/core/context/session-start-pack.ts
+++ b/src/core/context/session-start-pack.ts
@@ -76,3 +76,24 @@ export async function requestSessionStartPack(
await new Promise((r) => setTimeout(r, POLL_MS));
}
}
+
+/**
+ * #5941: the source the hook's context arms (session-start pack, user-prompt)
+ * ask for. `GBRAIN_SOURCE` wins; else, with a session, its frozen source
+ * record (the one capture stamps: env, then the payload cwd's
+ * `.gbrain-source` walk), so context and capture never disagree within a
+ * session; without one, the cwd walk itself. Undefined (the serve's own
+ * binding) when nothing names a source or anything fails. A named source with
+ * no live keyed serve reaches the legacy socket, whose serve answers
+ * `source_mismatch` (the heartbeat reason) instead of another source's context.
+ */
+export async function contextSourceId(openSession: (() => Promise<{ source?: string }>) | null, cwd: string): Promise<string | undefined> {
+ if (process.env.GBRAIN_SOURCE) return process.env.GBRAIN_SOURCE;
+ try {
+ if (openSession) return (await openSession()).source;
+ const { resolveSourceIdEngineFree } = await import('../source-resolver.ts');
+ return resolveSourceIdEngineFree(null, cwd) ?? undefined;
+ } catch {
+ return undefined;
+ }
+}
diff --git a/test/ambient-recall-hooks.serial.test.ts b/test/ambient-recall-hooks.serial.test.ts
index 3ba26f7cfc..074e0a435f 100644
--- a/test/ambient-recall-hooks.serial.test.ts
+++ b/test/ambient-recall-hooks.serial.test.ts
@@ -468,6 +468,41 @@ describe('hook session-start pack arm', () => {
expect(handlerHit).toBe(false);
});
+ test('no GBRAIN_SOURCE: the .gbrain-source walk from the payload cwd sets sourceId (#5941, PR #6409)', async () => {
+ const dataDir = join(tmp, 'data');
+ let seen: ContextPackRequest | undefined;
+ await startPackServer({ dataDir, blockText: null, onRequest: (r) => { seen = r; } });
+ writePgliteConfig(dataDir);
+ const repo = join(tmp, 'repo');
+ mkdirSync(join(repo, 'sub'), { recursive: true });
+ writeFileSync(join(repo, '.gbrain-source'), 'wiki\n');
+ const out = collectStdout();
+ await runHook(['session-start', '--harness', 'codex'], {
+ ...out.io,
+ stdin: JSON.stringify({ session_id: 'sess-src', source: 'startup', cwd: join(repo, 'sub') }),
+ });
+ expect(seen?.sourceId).toBe('wiki');
+ });
+
+ test('a dotfile source the bound serve does not serve: no pack, heartbeat reason source_mismatch (#5941)', async () => {
+ const dataDir = join(tmp, 'data');
+ mkdirSync(dataDir, { recursive: true });
+ const server = await startResolveIpcServer(resolveSocketPath(dataDir), {
+ resolve: async () => null,
+ context_pack: async () => ({ text: 'OTHER-SOURCE-PACK', pointers: [], factsCount: 0, mode: 'pack' as const }),
+ }, { secret: ensureIpcSecret(dataDir), boundSourceId: 'other-source' });
+ servers.push(server!);
+ writePgliteConfig(dataDir);
+ const repo = join(tmp, 'repo');
+ mkdirSync(repo, { recursive: true });
+ writeFileSync(join(repo, '.gbrain-source'), 'wiki\n');
+ const out = collectStdout();
+ await runHook(['session-start', '--harness', 'codex'], { ...out.io, stdin: JSON.stringify({ session_id: 'sess-mm', source: 'startup', cwd: repo }) });
+ expect(out.get()).not.toContain('OTHER-SOURCE-PACK');
+ const { readHeartbeatTail } = await import('../src/core/context/hook-heartbeat.ts');
+ expect((await readHeartbeatTail(1))[0]?.reason).toBe('source_mismatch');
+ });
+
test('trigger carries the SessionStart source discriminator', async () => {
const dataDir = join(tmp, 'data');
let seen: ContextPackRequest | undefined;
diff --git a/test/hook-command.serial.test.ts b/test/hook-command.serial.test.ts
index 6bd717740f..055e9aad43 100644
--- a/test/hook-command.serial.test.ts
+++ b/test/hook-command.serial.test.ts
@@ -125,6 +125,78 @@ async function startServer(opts: {
// ── Dispatch + kill switch ──────────────────────────────────────────────────
+describe('user-prompt source routing (#5941)', () => {
+ // Adapted from PR #6409 (@benswinney). Codex hooks.json is machine-global, so its context hooks bake no
+ // GBRAIN_SOURCE; the hook resolves the source the way capture does (the session's frozen record, then the cwd walk).
+ function repoWithDotfile(source: string): string {
+ const repo = join(tmp, 'repo');
+ mkdirSync(join(repo, 'sub'), { recursive: true });
+ writeFileSync(join(repo, '.gbrain-source'), `${source}\n`);
+ return join(repo, 'sub');
+ }
+
+ test('no GBRAIN_SOURCE: the .gbrain-source walk from the payload cwd sets sourceId', async () => {
+ const dataDir = join(tmp, 'data');
+ writePgliteConfig(dataDir);
+ const seen: TurnContextRequest[] = [];
+ await startServer({ dataDir, blockText: 'ok', onRequest: (r) => { seen.push(r); } });
+ const out = collectStdout();
+ await runHook(['user-prompt', '--harness', 'codex'], {
+ ...out.io,
+ stdin: JSON.stringify({ prompt: 'hello Acme', cwd: repoWithDotfile('wiki') }),
+ });
+ expect(seen).toHaveLength(1);
+ expect(seen[0].sourceId).toBe('wiki');
+ });
+
+ test('GBRAIN_SOURCE still wins over the dotfile', async () => {
+ const dataDir = join(tmp, 'data');
+ writePgliteConfig(dataDir);
+ const seen: TurnContextRequest[] = [];
+ await startServer({ dataDir, blockText: 'ok', onRequest: (r) => { seen.push(r); } });
+ process.env.GBRAIN_SOURCE = 'pinned';
+ const out = collectStdout();
+ await runHook(['user-prompt'], {
+ ...out.io,
+ stdin: JSON.stringify({ prompt: 'hello Acme', session_id: 'sess-env', cwd: repoWithDotfile('wiki') }),
+ });
+ expect(seen[0].sourceId).toBe('pinned');
+ });
+
+ test('with a session id, the source capture froze for the session wins over a later dotfile change', async () => {
+ const dataDir = join(tmp, 'data');
+ writePgliteConfig(dataDir);
+ const seen: TurnContextRequest[] = [];
+ await startServer({ dataDir, blockText: 'ok', onRequest: (r) => { seen.push(r); } });
+ const cwd = repoWithDotfile('wiki');
+ await runHook(['user-prompt', '--harness', 'codex'], { ...collectStdout().io, stdin: JSON.stringify({ prompt: 'hi', session_id: 'sess-frz', cwd }) });
+ writeFileSync(join(tmp, 'repo', '.gbrain-source'), 'notes\n');
+ await runHook(['user-prompt', '--harness', 'codex'], { ...collectStdout().io, stdin: JSON.stringify({ prompt: 'hi again', session_id: 'sess-frz', cwd }) });
+ expect(seen.map(r => r.sourceId)).toEqual(['wiki', 'wiki']);
+ });
+
+ test('no GBRAIN_SOURCE and no dotfile: no sourceId (the serve binding), as before', async () => {
+ const dataDir = join(tmp, 'data');
+ writePgliteConfig(dataDir);
+ const seen: TurnContextRequest[] = [];
+ await startServer({ dataDir, blockText: 'ok', onRequest: (r) => { seen.push(r); } });
+ const bare = join(tmp, 'bare');
+ mkdirSync(bare, { recursive: true });
+ await runHook(['user-prompt', '--harness', 'codex'], { ...collectStdout().io, stdin: JSON.stringify({ prompt: 'hi', session_id: 'sess-bare', cwd: bare }) });
+ expect(seen[0].sourceId).toBeUndefined();
+ });
+
+ test('a dotfile naming a source the bound serve does not serve degrades with source_mismatch, no other-source context', async () => {
+ const dataDir = join(tmp, 'data');
+ writePgliteConfig(dataDir);
+ await startServer({ dataDir, blockText: 'OTHER-SOURCE-CONTEXT', boundSourceId: 'other-source' });
+ const out = collectStdout();
+ await runHook(['user-prompt', '--harness', 'codex'], { ...out.io, stdin: JSON.stringify({ prompt: 'hi', cwd: repoWithDotfile('wiki') }) });
+ expect(out.get()).not.toContain('OTHER-SOURCE-CONTEXT');
+ expect((await lastHeartbeat())?.reason).toBe('source_mismatch');
+ });
+});
+
describe('dispatch', () => {
test('GBRAIN_HOOKS=0 short-circuits every event: exit 0, no output, no heartbeat', async () => {
process.env.GBRAIN_HOOKS = '0';