Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Agent bootstrap cluster (the paste-in desktop-agent install)
Normative docs: docs/designs/AGENT_BOOTSTRAP_DESIGN.md (scope) +
docs/designs/AGENT_BOOTSTRAP_PLAN.md (implementation, review-finding IDs inlined).
User-facing contract: docs/guides/bootstrap.md. Runbook the paste block fetches:
BOOTSTRAP_FOR_AGENTS.md (root; carries a version stamp CI pins to VERSION).
src/commands/bootstrap.ts— thegbrain bootstrap {status,interview,render,repo,hooks,verify,uninstall,attach,cloud-setup-script}dispatcher (plus the machine-levelharnesssubcommand — see thecore/bootstrap/harness.tsentry below). Engine-free everywhere exceptverify(which opens/closes its own engine — safe because verify runs with no live serve, before host registration).cloud-setup-scriptis a pure printer (printstemplates/bootstrap/cloud-setup-script.shfor the cloud environment's setup step) and is dispatched entirely BEFORE workspace resolution, so it works from any cwd, including $HOME. Every other subcommand resolves--workspace(default: cwd) throughresolveWorkspace, which refuses withBootstrapError('HOME_WORKSPACE')when the resolved path (realpath-compared, so a symlinked $HOME or cwd still matches) ISprocess.env.HOME(falling back toos.homedir()only when HOME is unset) — an unqualified run from a freshly-SSH'd shell must not silently stage a home-directory-scalegit add -Aover~/.ssh/and friends; the refusal is still appended to<home>/bootstrap/install.jsonl(keyed by the rejected candidate path) before returning.status,uninstall, andharnessare exempt from this guard (HOME_WORKSPACE_GUARD_EXEMPT):statusonly reads and prints a report,uninstallremoves exactlyreceipt.created_paths(each containment-checked) — never agit add/commit/push, never a workspace-wide scan — andharnessoperates only onhomeand never even receives awsargument (runHarness, machine-level wiring), so the valueresolveWorkspacereturns for it is used only forLogCtx.wsbookkeeping. Exemptingstatus/uninstallkeeps the recovery path reachable for the guard's own victims: someone who bootstrapped into$HOMEneedsstatusto see what's there anduninstallto remove it, both run with--workspacepointing AT $HOME; the refusal message for the still-guarded subcommands names that recovery path. Known gap: a process already launched with HOME pointed away from the real account home is not caught (Bun'sos.homedir()mirrors process-start HOME rather than doing an independent uid lookup, so it collapses to the same wrong value). Mutating subcommands run under the workspace bootstrap lock; render is gated on interviewcomplete && confirmedand hard-refuses when the workspace origin is a PUBLIC remote (identity files must never land in a public repo — the same template-door gatestatusenforces; unverifiable visibility warns and proceeds, treating the origin as public); the provider key routes to the 0600 config sink and never touches interview state; every MUTATING subcommand appends a line to<home>/bootstrap/install.jsonl(the read-onlystatusandcloud-setup-scriptdo not log).hookson Claude Code writes the committed carrier in a cloud sandbox (writeCommittedClaudeHooks) and the gitignored local file otherwise;uninstalltears down the durability wiring and removes this workspace's per-root push/debounce state, and its opencode teardown sweeps BOTH merged global filenames (under the opencode config-dir bootstrap lock) plus the projectopencode.json, expectation-keyed on this workspace's source id (skipOtherSource) — a gbrain entry from a different workspace is skipped with a note, never silently deleted. Consent answers resolve FAIL-CLOSED:consentAnswertreats a hand-edited/unusable interview value (non-string, empty) as declined — loudly, with a re-record note — never falling through to a permissive bank default;hookson Codex prints a corrective note when a persistedprojectMCP_SCOPE answer is found (raw state read, not the resolver —codex mcp addhas no scope flag, registrations are always user-global) with safe clear instructions.GBRAIN_BOOTSTRAP_ABORT_AFTERis the deterministic kill-mid-phase test seam.src/core/gbrain-bin.ts—resolveGbrainBin(): the absolute gbrain binary for harness registrations and hook commands (Bun.which('gbrain')when absolute, else this process's executable when it is the compiled binary, else null). A baregbrainis never registered because GUI hosts inherit no PATH. Used bybootstrapand readiness'sharness_wiringfix.src/core/bootstrap/format.ts—agent.jsonmanifest (format_version 1, provisional;initializedsentinel distinguishes a template clone from a bootstrapped workspace) + the machine-local install receipt (<home>/bootstrap/receipt.json) that proves THIS machine ran bootstrap; uninstall is keyed to the receipt, never the repo manifest. Atomic writes;readManifestnever throws (typed states incl. conflict markers).src/core/bootstrap/assets.ts— every template + the question bank embedded via Bunwith { type: 'file' }imports (the chunkers/code.ts pattern) so the compiled binary renders with no repo checkout;DERIVED_TOKENS(GITHUB_REPO_URL, CORPUS_RETENTION_DAYS) is the non-bank half of the template token set the CI bijection guard checks.templates/bootstrap/— the ten{{TOKEN}}identity templates (AGENTS/CLAUDE/SOUL/USER/MEMORY/HEARTBEAT/ACCESS_POLICY/GITHUB/memory-README/gitignore),questions.json(12 asked / 6 required; consent keys;persist:falsesink keys), andtemplate-repo/— the VENDORED deterministic render the release job diffs against before publishing the public template repo. Generic placeholder content only (privacy iron rule; CI-asserted).src/core/bootstrap/interview.ts— interview state at<ws>/state/interview.json(committed; multi-device re-render source). Read-back confirm hash:--confirmmust present the hash of the exact answer set shown to the human, and ANY later answer change clears the confirmation — the single-batch self-confirm attack is structurally impossible. Set-time enforcement: length caps, reject-lists, allowed-lists, control-char strip,{{escaping. Conflict-markered files return agent-readable errors, not stack traces.src/core/bootstrap/render.ts— token substitution with interview values treated as data (line-leading#/<!--/fence escaping), hard-fail on unresolved tokens, never-clobber + timestamped backups on--force, blank-line collapse, byte floors scaled to answered count.--minimalis the deterministic placeholder mode the template-repo generator uses (byte-identical across runs; leaves required tokens as literal fill-me markers; writesinitialized:false).--onlynever writes agent.json. OpenClaw renders HEARTBEAT.md as SCHEDULES.md (render-host.ts, #7470).src/core/bootstrap/lock.ts— the bootstrap-run mutex (atomic mkdir + pid liveness + age guard + ownership token; steal requires dead pid AND stale age) and the family's shared typedBootstrapError(GH_MISSING/GH_AUTH carry exit 2 = human action needed).src/core/bootstrap/repo.ts/attach.ts/uninstall.ts— private-repo lifecycle.createPrivateRepo: gh gates, slugified name probe,gh repo create --private --source --push, privacy verified viagh api .private(rate-limit/5xx is VERIFY_UNAVAILABLE, distinct from not-private) before any push, idempotency keyed off the remote URL. A pre-existing origin is adopted (disposition 'adopted') when the authed gh user owns it, there's no recordedrepo_url, and it is SAFE — empty or already carrying our history (assertAdoptableOrigin; a foreign-content repo is refusedORIGIN_NOT_EMPTY, never a silent no-op); this is the create-repo-first path. Org-owned origins and anything else are refused and pointed at attach. Repo-local git identity is set in both create and adopt paths before commit;repo_urlis recorded only after a successful push.attachWorkspace(machine two): requires aninitializedmanifest, writes this machine's receipt, returns structured wiring steps.uninstallWorkspace: receipt-keyed, refuses under a live serve (read-only lock probe — never opens the engine), removes exactly receipt-recorded paths + marker-keyed host entries, keeps the brain unless--delete-brainAND bootstrap created it; never wholesale-deletes the gbrain home. All gh/git through an injectable ExecRunner seam.src/core/bootstrap/hooks.ts+host-specs.ts— host wiring.host-specs.tsis the ONE module owning host-format assumptions (dated spec targets with verifiedAt + doc references: claude-code hooks/settings shapes incl. the 10,000-char hook-output cap and the five hook events; codex mcp-add argv, the streamable-HTTPurl+http_headers = { Authorization = "Bearer <t>" }config shape (loads on codex-cli 0.147.x and 0.149.x; inlinebearer_tokenis rejected at config load by >=0.149),codexConfigPath()honoring CODEX_HOME,claudeUserSettingsPath()honoring CLAUDE_CONFIG_DIR/$HOME explicitly — Bun's homedir() ignores a remapped HOME, which would point sandboxed writers at the operator's real settings; the shared resolution lives in the privateclaudeConfigBase()(CLAUDE_CONFIG_DIR-else-$HOME-else-homedir(), the directory playing the role of~/.claude— NOT forclaudeUserMcpConfigPath, whose default lives at the HOME level as~/.claude.json), which also feedsclaudeUserSkillsDir()/claudeProjectSkillsDir()(native SKILL.md discovery, the harness-bridge install targets; user scope attested, project scope provisional-from-docs) — and the opencode shapes:opencodeConfigDir/opencodeGlobalConfigPath(XDG-only resolution; the.jsoncname preferred for parity withopencode mcp add; OPENCODE_CONFIG/_CONFIG_DIR/_CONFIG_CONTENT deliberately NOT honored — observed INERT in opencode 1.18.18, honoring them would write registrations into a file opencode never reads),opencodeProjectConfigPath,opencodeGlobalSiblingPath(the OTHER member of the global filename pair — writers reconcilemcp.<name>across it because opencode merges both), andOPENCODE_HAS_HOOKS=false— 'gbrain does not wire opencode's plugin/event system yet', not 'opencode has no hooks'). The settings writers are path+marker parameterized:writeClaudeHooksAt/removeClaudeHooksAttake an explicit settings file and a marker VALUE (workspace installs stampbootstrap-v1in.claude/settings.local.json; harness installs stampbootstrap-harness-v1in user-scope settings or a --project dir — the two coexist and each removal strips only its own;refuseOnForeignGbrainMarkerblocks same-file double-wiring), fail-closed on broken JSON (a settings file that doesn't parse THROWS with the path — a writer must never relocate or overwrite a config it can't read), mode-preserving realpath-resolved atomic writes (dotfile symlinks survive), and fixed-or-timestamped backups.addPermissionsAllowEntry/removePermissionsAllowEntrymanage the harness lane'smcp__<name>headless pre-approval with set semantics and NO marker (ownership rides the harness receipt; foreign entries always survive); the add path fails CLOSED when an existingpermissionskey orpermissions.allowcarries a shape it doesn't understand (host security policy is never rewritten on a guess), while removal leaves shapes it can't read untouched and reports nothing-to-remove.registerClaudeMcp/registerCodexMcpbuild argv only (Claude Code takes--scope, project default; Codex has no scope flag —codex mcp addis always user-global;-e/--env GBRAIN_SOURCEso MCP writes land in the workspace source, and the serve argv fromstdioServeArgvinsrc/core/mcp-registration.ts:--surface starterby default so a pre-existingmcp_surface: verbsconfig row can't narrow the registration, or thesurfacethe caller passes —bootstrap hooks --surface, or an existing entry's form carried over on replacement,nullmeaning a bareserve).bootstrap hooksnever narrows: a matching registration is kept,verifyMcpTargetsWorkspacereturns the existing entry's surface (registeredSurface) and the mismatch re-add keeps it, and the opencode writer keeps the existing command's form unless--surfaceis given. The opencode workspace lane execs NOTHING — registration is the directopencode-json.tswrite with an INVERTED scope default (user-global; opencode spawns project-config servers with no trust prompt, soMCP_SCOPE=projectis an explicit opt-in that writes the committed-candidateopencode.jsonwith a PATH-resolved command and prints the sharing warning), verification is config parse-back + a best-effortopencode mcp list --pureprobe — the probe spawns via a held Bun.spawn handle from a fresh EMPTY temp-dir cwd (never the invoking cwd: opencode merges a project opencode.json from cwd and spawns its servers with no trust prompt), is SKIPPED entirely for project scope (printed note; parse-back is authoritative) and on plugin-bearing configs (mcp listis a code-execution surface), and on timeout actually kills the child (SIGTERM → SIGKILL, bounded pipe drain, code 124 into the could-not-confirm branch;probeSpawnis the injectable seam). User-scope writes also reconcile the SIBLING global filename first (ours → removed with a note; foreign → refuse naming both files) so a merge-shadow registration can never survive.detectHarnessprobesOPENCODE/OPENCODE_PID(set in opencode's bash-tool children, observed 1.18.18).ClaudeHookEnv.GBRAIN_SEAT(#4618) rendersGBRAIN_SEAT=<label>into local-carrier hook commands (never the committed carrier);writeClaudeHooksAtkeeps the seat a prior install of the same marker rendered when the caller passes none, and''clears it.parseSeatFlagsvalidates--seat <label>/--no-seatforbootstrap hooksandbootstrap harnessand returns anotewhere a seat cannot be rendered (codex, opencode, the cloud committed carrier). Pinned bytest/bootstrap-seat.serial.test.ts. Harness-lane hook ownership does not rest on the marker alone: Claude Code can drop unknown keys when it rewrites settings.json, soparseClaudeHookCommand(the inverse ofbuildClaudeHookCommand: shellQuote-aware word split, env keys limited to the four the builder writes, each at most once, an absolute launcher, nothing afterhook <sub>, and a re-render that must equal the input) feedsclassifyHarnessHook(entry, event, identity)→marked/command(unmarked, exactly the harness hook for THAT event, launcher/source/seat inside aHarnessHookIdentity, no GBRAIN_HOME) /unowned(harness-looking under a wired event but edited or another install's; never deleted) / null.harnessHookIdentity(receipt, target, current)merges the running install with the receipt's recordedlauncher/seatand source binding (seats constrain only when recorded).writeClaudeHooksAt({identity})replaces owned unmarked entries like marked ones (one entry per event on re-run, seat carried from marked then owned entries) and notesharness_hook_unownedlookalikes;removeClaudeHooksAt(path, marker, {identity, dryRun})returnsunmarked(event + why, never command text) andunownedevents;scanHarnessHookCarrieris the read-only per-event census (doctor,--status, the cross-HOME guard with identity'any');groupsCarryGbrainHookfeedshook_carrier_overlap. The workspace lane (bootstrap-v1) keys on the marker alone. Pinned bytest/bootstrap-harness-hook-ownership.test.ts.hookEntryHash(sha256 overtype,command,timeout; the marker excluded, so a dropped marker keeps the hash) backs the opt-inownedEntryHashesoption on both writers: with it a marker match alone never replaces or removes an entry, edited marked entries come back inpreserved, and unmarked entries with an owned hash are still ours (gbrain setup); without it every existing caller keeps marker-keyed ownership.src/core/bootstrap/harness-hooks.ts— the receipt-aware glue for harness hook entries without their marker:removeHarnessHooksTarget(one hooks target: owned marked + unmarked entries removed and listed by event; a surviving lookalike prints theharness_hook_unownednotice block withnext: tell_user_to_runand throws so the target stays failed and--removeexits 1),previewHarnessRemoval(--remove --dry-run: every target's would-be action, nothing written, receipt untouched),harnessHooksPresent(the cross-HOME--projectguard: marked, unmarked or edited-by-shapeunownedentries, any install; W4.8) andharnessHookCarrierStatus(--statustext line +hook_carriersJSON).src/core/setup/capabilities.ts+src/core/setup/claude-code.ts—gbrain setup's data and Claude Code writer.capabilities.tsis the versioned harness × transport table (SETUP_CAPABILITY_TABLE_VERSION; per rowsetup,pull,push,read_events,capture_events,docs); push isnative-pendingorunsupportedon every row until an observed injected event proves it.claude-code.tsowns entries by exact hash through the connection receipt.gbrain-connection-claude-code-<name>[-project-<hash>].jsonbeside~/.claude.json(connection: 'local-stdio',entry_hash/pending_entry_hash,hooks.{owned,pending,edited},consent,gbrain_home; a receipt withclient_idis a hosted one and is never adopted). The MCP entry ({type:'stdio', command, args, env}, user scopemcpServersor project scopeprojects[<dir>].mcpServers) is written directly; hooks go throughwriteClaudeHooksAt/removeClaudeHooksAtwith markerGBRAIN_SETUP_MARKER_VALUEandownedEntryHashes.applyClaudeSetup(under the config-dir bootstrap lock) writes the receiptpreparedfirst, then the brain (beforeMcp), the MCP entry, the hooks andinstalled, each step recording its hash so a resume never duplicates; an unchanged install writes nothing. An owned event whose recorded hash vanished while a marked entry remains isedited: preserved, reported, and skipped by later runs.removeClaudeSetupdeletes only hash-matched entries (adopted entries stay), keeps aremovedreceipt when an edited entry survives, and otherwise deletes the receipt. The codex row (table version 2) issupportedwithpush: 'native-verified'and apush_evidencestring (codex-cli 0.162.1, observed UserPromptSubmit injection into fresh native sessions, 3/3, with a--no-hookscontrol);entryHashisownedEntryFingerprintfrom adopted-connections.ts.src/core/setup/codex.ts—gbrain setup codex's writer. Owns three kinds of entry, each byownedEntryFingerprint(sha256 over canonical JSON of the exact parsed entry) recorded per entry in$CODEX_HOME/.gbrain-connection-codex-<name>.json(setup_receipt_version: 2: the claude-code receipt fields plushooks_path,gbrain_home_envandtrust.{owned,pending,edited}keyed by event as{key, hash}; aclient_idreceipt is hosted and never adopted): the stdio[mcp_servers.<name>]table (command,args, inlineenv), one hooks.json group per wanted event (codexSetupHookGroup), and one[hooks.state."<hooks.json>:<event>:<index>:0"]trust table per group.applyCodexSetup(under the CODEX_HOME bootstrap lock) writes in a crash-recoverable order: receiptprepared(the consent record and pending fingerprints) → brain (beforeMcp) → MCP table → hooks.json groups (inert until trusted) → stale owned trust tables removed, wanted ones appended (activation last) →installed; each step records its fingerprints so a resume never duplicates. Compare-and-swap everywhere: a group whose recorded hash vanished while a this-install setup-lane group remains isedited(preserved, reported, never trusted by setup); a trust table at setup's key with a different value is preserved (conflict/edited); an identical pre-existing MCP table ismcp_adoptedand kept on removal.removeCodexSetupruns trust → hooks → MCP → receipt and keeps aremovedreceipt when an edited entry survives. Both keep<file>.bak.<timestamp>of each existing config.toml or hooks.json they changed (also on a failed run) and name it in a note.GBRAIN_SETUP_ABORT_AFTER=receipt|mcp|hooks|trustis the crash seam. Pinned by the codex blocks oftest/setup.test.ts.src/core/setup/local-receipts.ts— read-only view of this install's live local-stdio setup receipts (.gbrain-connection-*.jsonbeside~/.claude.jsonand inCODEX_HOME; kept only whenconnection: 'local-stdio', a numericsetup_receipt_version,gbrain_home === configDir()and statusprepared/installed). Engine-free, imports no harness writer.providerDeclineRecord()(a recordedproviders: declined, opt-outs win) gates OpenAI model discovery and doctor's provider probe;claudeCodeSpawnsServe(cwd)(an installed claude-code receipt, user scope or a project receipt for exactlycwd) tells the SessionStart hook that Claude Code is starting a stdio serve.src/core/bootstrap/plugin-lanes.ts— plugin-lane detection (*PluginProvidesName,*AnyRegistrationExists, re-exported by harness.ts; variants count asgbrain) plusenabledPluginLanes(name), read byplugin_lane_collision/harness_wiring. Config, not health.pluginHookYields: yield to no-hooks consent, another lane (Codex: trusted, enabled), a higherGBRAIN_PLUGIN.src/core/bootstrap/codex-hooks.ts— the codexhooks.jsonwriter (SessionEnd capture lane), built entirely on the datedCODEX_HOOKS_SPEC_TARGET(verified 2026-08-25 against pinned codex-cli 0.147.0, live + tag-source evidence; re-run the observation gate on codex version bumps). The three load-bearing facts: hooks.json is TOP-LEVEL deny-unknown-fields (ownership rides the legaldescriptionslot + a command-substring token, never a_gbrainkey); user-layer hooks are TRUST-GATED and fail SILENTLY (the writer lands BOTH the hooks.json entry AND its[hooks.state."<path>:session_end:<g>:<h>"].trusted_hashconfig.toml entry — sha256 of the recursively-key-sorted compact canonical JSON of the normalized handler identity — inside a gbrain-managed marker block, backing config.toml up to.hooks.bakso it never clobbers the MCP writer's.bakrollback anchor); SessionEnd handlers are hard-killed at 3s (the command captures stdin to a mktemp file and detaches a nohup grandchild running the realgbrain hook session-end --harness codex— live-verified end-to-end). Deliberately NOGBRAIN_SOURCEin the command: hooks.json is user-global, so a baked source would stamp every codex session on the machine; session-end resolves everything from the payload. a fresh install APPENDS our group last while a re-run REPLACES it IN PLACE (a single well-formed install never shifts a foreign group's trust index; dropping DUPLICATE gbrain groups can shift foreign groups sitting after them — the writer prints a note naming the re-trust); the whole command is wrapped in a top-levelsh -c '…' <bin>so a non-POSIX $SHELL (fish/csh) never parses the POSIX script; the foreign-trust-entry guard is a tolerant [hooks.state…] header match (not byte-exact); a golden known-answer hash vector pins the canonical recipe; removal also deletes the gbrain description when byte-identical to ours and NOTES the inherent index shift for foreign groups that sat after ours; unparseable hooks.json is never touched, on write or removal; the residual stale-trust-index case (user reorders their own groups) degrades to silent non-execution, which doctor'scodex_hooks_never_firedrung names. Pinned bytest/codex-hooks-writer.test.ts.codexHookTrustHash(eventName, command, timeout)is the generalized recipe (re-read against openai/codex rust-v0.162.1hook_hash+version_for_toml; a known-answer vector from trust entries a live codex-cli 0.162.1 executed pins it intest/setup.test.ts). The setup lane (CODEX_SETUP_EVENTSSessionStart/UserPromptSubmit 15s, SessionEnd 3s) is hash-owned:codexSetupHookGrouprendersenv GBRAIN_HOOK_LANE=setup [GBRAIN_HOME=…] [GBRAIN_SOURCE=…] <bin> hook <sub> --harness codex(SessionEnd prefixes the detached capture command),codexHookCensusfingerprints every group and tags its lane,writeCodexSetupHooksreplaces owned groups in place / appends / drops only owned groups (notes any index shift), and the token-owned bootstrap writer'sisOurGroupskips groups carryingGBRAIN_HOOK_LANE=setup, so bootstrap never claims or strips setup's groups.writeCommittedClaudeHooksis the second, COMMITTED hook carrier: it writes marker-keyed entries into the workspace's checked-in.claude/settings.jsonusingbuildPortableClaudeHookCommand(PATH-resolvedgbrain, fail-open when the binary is absent) so teammates cloning the repo inherit the hooks;committedHookEvents(ws)feeds the local writer'scarriedEventsso the two carriers never double-wire an event, andremoveClaudeHooksstrips both.src/core/bootstrap/codex-toml.ts— the ONE direct codex-config writer (codex mcp addcannot express an inline credential, and framework-spawned codex inherits no shell profile for the env-var lane). One[mcp_servers.<name>]table between full-line markers carryingurl+http_headers = { Authorization = "Bearer <token>" }(NOT inlinebearer_token, which codex-cli >=0.149 rejects at config load;parseCodexBlockBearerin harness.ts keeps a legacybearer_tokenread fallback so existing tokens still recover); everything outside survives byte-for-byte. Foreign-server detection PARSES the config (Bun.TOML.parse, no dependency) with our block stripped — a header-only regex would false-negative inline-table/dotted/quoted spellings into a codex-bricking duplicate table; rewrites re-anchor at EOF; renders are parse-validated with an ours-keys-exactly assert before rename; damaged markers refuse; 0600 tmp/target/.bak (the .bak carries the previous token on re-runs); CRLF preserved, missing trailing newline repaired. Also exportsrenderCodexHttpServerBlock({name, url, bearerToken})— a MARKER-FREE, parse-validated[mcp_servers.<name>]TOML render for paste-into-config surfaces (gbrain agent register's codex block); rendering only, never writes a file. Pinned bytest/codex-toml.test.ts. Also the hash-owned single-table helpers forgbrain setup codex:readCodexTomlTable,appendCodexTomlTable(EOF append, refuses an existing table, parse-verifies the result is exactly the old document plus the table) andremoveCodexTomlTable(header through the line before the next header, keeping trailing comments/blank lines and a preceding# gbrain setupcomment;unlocatablewhen the edit would change anything but that table, e.g. a re-rendered subtable). No markers: codex may rewrite config.toml and drop comments.src/core/bootstrap/adopted-connections.ts+adopt-connection.ts— an operator-managed Codex PROJECT connection (<workspace>/.codex/config.toml[mcp_servers.<name>], streamable HTTP logged in withcodex mcp login, or stdio) is not a bootstrap-owned registration, so thewirephase instatus.tsreads it throughadoptedConnectionState:detected(the table exists, nothing proves it works) ispartialwith the adopt hint,adoptedisdone,drifted(fingerprint changed, table gone, file unparsable) ispartialwith a re-adopt hint,noneleaves the receipt/hook detectors' verdict (#4082). Evidence lives in the versioned, offline-readable sidecar<gbrain-home>/bootstrap/adopted-connections.json(version: 1, one row per workspace + harness + name;recordAdoptedConnectionreplaces, never appends twins), never in the install receipt, so uninstall does not tear down config bootstrap did not write. The fingerprint is sha256 over canonical JSON of transport, target (URL or command) and header NAMES; header values and tokens are never stored or printed, so a token rotation is not drift.adoptConnectionbacksgbrain bootstrap hooks --adopt --harness codex [--name <server>](dispatch insrc/commands/bootstrap.tsrunHooks, before the harness writers): Codex only, refuses without a passingbootstrap verifyrun newer than the config file's mtime, writes nothing to the Codex config and fabricates no receipt registration. Pinned bytest/bootstrap-adopted-connection.serial.test.ts.ownedEntryFingerprint(value)is the shared fingerprint (connectionFingerprintandgbrain setup's per-entry hashes both go through it).src/core/bootstrap/serve-health.ts— serve/healthprobe + scopes version-skew floor, re-exported byharness.ts.probeServeHealth(mcpUrl, fetchFn, timeoutMs=3000)GETs<base>/healthand returns{ok, version?, engine?, detail?}, never throws;fetchFnis an explicit argument (no ambient fetch, no engine, no config).isServeOlderThanScopes(v)compares against the PINNEDSCOPES_MIN_SERVE_VERSIONconstant — a comparison against the moving CLI VERSION would false-flag every scope-aware serve on the next release. An older serve verifies scoped tokens as FULL ACCESS, so callers print the floor line unconditionally.src/core/bootstrap/opencode-json.ts— the ONE direct opencode-config writer (workspace stdio lane, harness remote lane, connect--install). ALL edits ride jsonc-parsermodify/applyEdits(comments/formatting/EOLs survive byte-for-byte outside the edited range — opencode's ownmcp addpreserves comments, and JSONC is its effective grammar for BOTH.jsonand.jsoncfilenames, which MERGE when both exist). Ownership is a 4-state STRUCTURAL FINGERPRINT (opencodeEntryKind→ ours-same-source | ours-other-source | foreign | absent; GBRAIN_SOURCE EQUALITY for local entries, receipt-url match or the{env:GBRAIN_REMOTE_TOKEN}interpolation for remote), never a marker key (a future strict-schema flip must not brick the host). Distinct read-failure classes (ENOENT create / empty-as-{} / unreadable refuse); foreign refusal on write AND remove; post-render validation (our entry round-trips + every other key survives) keeps the original on failure; 0600 for inline-bearer targets; backups are UNIQUE per operation (<config>.bak-<hex>, returned in the result withwrittenText, the exact rendered bytes) so overlapping runs can never clobber each other's snapshot, and a backup is chmod'd 0600 whenever the COPIED content carries an inline bearer (write AND remove paths); the ours-other-source refusal is caller-appropriate (url +--forcewording on the remote/expect-url path, GBRAIN_SOURCE wording on the local path);removeOpencodeMcpEntrytakes a caller expectation + optionalskipOtherSource— the uninstall lane passes THIS workspace's source id so an ours-other-source match becomes a calm skip-with-note (another workspace's registration is never deleted; foreign still refuses);reconcileOpencodeSiblingGlobalclears a same-name gbrain entry from the OTHER global filename before a global write (foreign → refuse naming both files) — opencode merges both, so a leftover sibling entry is a shadow registration; the bun-run ownership lane is ANCHORED (an exactgbrain/gbrain-*path segment in some arg — a gbrainy-fork cli path is NOT ours, fail-closed);parseOpencodeEntryBearerrecovers the harness--statustoken url-matched only;opencodeRemoteEntryExistsis the stdio-lane ownership arbiter (codexBlockOwnsName analog). Callers holdacquireBootstrapLock(config-dir → opencode-dir ordering). Pinned bytest/opencode-json.test.ts(incl. the fingerprint truth-table suite).src/core/bootstrap/atomic-write.ts— the ONE atomic config-file writer for bootstrap host surfaces: symlink-target-resolving, mode-inheriting (freshModefor new files,forceModefor 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 RUNNINGgbrain serve --http, noagent.json. The opencode target mirrors the codex posture: forced-wire on explicit--harness opencode(the JSONC writer needs no CLI), one managedmcp.<name>remote entry with the inline bearer header (0600) viaopencode-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 —--removeclassifying against the receipt url (not-ours skips with a note), and--statusbearer recovery viaparseOpencodeEntryBearer(url-matched). An explicit private posture (file-planememory.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), thenrequireConsentviaconsentGate(effectspersistent_install, pluscredentialswhen it mints the token;--yesapproves; the TTY prompt runs only whenisInteractive(), 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 aregbrain connect's charter;--tokenmakes 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; thepermissions.allowpre-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 aspendingat mint time and flip per-target, so a crash leaves consumable state); registration ownership checks (--forceto replace a foreign-url server;--removeskips what it no longer owns); user-XOR-project hook scopes;GBRAIN_HOOK_LANE=harnesson hook commands sogbrain hookyields to a workspace bootstrap install in the cwd (Claude Code merges settings scopes — same event must not fire twice); the hookGBRAIN_SOURCE, the receiptsource_id, and the token grant bind to a validated--source(scalar write floor), else to the sourceHarnessDeps.resolveHookSourceresolves 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_contextclaim is neversource_mismatch; a resolution landing ondefault/__all__is the federated floor. Lookup failures are NOT papered over withdefault: a typo'd--sourceor stale env/dotfile throwsSOURCE_UNRESOLVEDbefore any mint or receipt; an explicit--sourcewith an unopenable engine binds unverified with a warning; a live PGLite serve (engine cannot open) refuses withLIVE_SERVEwhen no token was supplied, printing (and indetails.steps) stop /auth create+auth rescope --operationswith the harness grant / restart /--token(#6661) and, on the--tokenlane 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 floordefaultplussource_pinned: false); any other lookup failure throwsSOURCE_UNRESOLVEDnaming--source; Postgres degradation + serve-version-skew honesty lines (isServeOlderThanScopespinned toSCOPES_MIN_SERVE_VERSION, the first scope-aware release, so later CLI bumps never re-trigger the warning);--statusprobes 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, itsurlkey not yet compared — TODOS.md; the opencode fallback IS url-compared insideparseOpencodeEntryBearer) and honestverify: unavailabledegrades, 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;--jsonon apply emits ONLY the final JSON document on stdout (prose → stderr);--removeis 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-runpreviews without a lock or any write. Hooks targets recordlauncherandseaton the receipt (the ownership identity for later runs); the permission target carriesmechanism: 'added'forward from a prior confirmed receipt target so a re-run never relabels its ownmcp__<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 uninstallholds the HOME lock across the whole teardown and runs harness removal FIRST (revoke needs the DB alive;--delete-brainwould destroy harness.json) and treats NO_RECEIPT/HOME_GUARD/RECEIPT_MISMATCH as "no workspace install" once harness wiring is cleared. Pinned bytest/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 viacarryLegacyGrant.--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;localEnrollmentreads the adapter receipt epoch for--status, andsupersededEnrollmentsis doctor's read-only comparison againstshared_skill_members(bootstrap_harness_healthwarn, codeshared_skills_epoch_superseded). Pinned bytest/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. #6661 option B:harness-pending-verify.ts(a--tokenrun on PGLite with no serve answering endspending_verify, exit 13, re-run asfix;--statuspartial until it passes).src/core/token-mint.ts— legacy-token mint/revoke for the harness lane:mintLegacyToken(scopes → the TEXT[] column; requiredtakesHoldersper-token allow-list, harness default['world']; optionalpermissions.source_idfederation array mirroring the stdio lane'slocalFederatedSourceIdsgrant, element 0 = write floor,[]stored as the explicit no-source grant;RETURNING id) andrevokeLegacyTokenById(never touches same-name siblings).carryLegacyGrant+readActiveTokenPermissionsare the harness rotation carry-over: takes holders and the source grant carry as stored (explicit empty lists included; an explicit--sourcewins), a stored operation snapshot narrows to the run's snapshot plus only skills-policy-added operations, newer operations are reported as withheld, andprivate_pagesis never carried (readActiveTokenPrivatePages; the harness prints the rescope; pinned bytest/harness-rotation-grants.test.ts). ExportsTOKEN_ID_RE(shared with theauth revoke --idgate). Pinned bytest/token-mint.test.ts.insertUnifiedToken(shared withauth create) births every token on the unified grant columns at revision 1 plus thepermissionsmirror; a brain whose schema predates the columns refuses withmigrations_pending(fix:gbrain apply-migrations --yes) and nothing is written;carryLegacyGrantparses the prior grant from its JSONB throughtokenGrantFromPermissions, so a drifted prior carries its JSON edit (the--adopt-permissionsresolution).src/commands/hook.ts— engine-freegbrain 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 throughsrc/core/context/session-start-pack.ts: whensessionStartAwaitsServeholds (sourcestartup/resume, harness claude-code,claudeCodeSpawnsServe(cwd)), the hook's deadline widens fromSESSION_START_DEADLINE_MS(1.5s) toSESSION_START_SERVE_WAIT_DEADLINE_MS(4s, under the 5s harness timeout) andrequestSessionStartPackretries 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 heartbeatdegraded/serve_not_ready. Pinned bytest/hook-session-start-serve-wait.serial.test.ts. WhenGBRAIN_HOOK_LANE=harness(set on harness-mode hook commands), each event PARSES the cwd's workspace settings carriers —.claude/settings.local.jsonAND the committed.claude/settings.json— and yields silently only when a livebootstrap-v1hook 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'shook_additional_contextattachments — the blocks WE previously injected — ridepriorContextText, deduplicated and capped atPRIOR_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-loopchannel,--harness <claude-code|codex>, default claude-code) →hookSpecificOutput.additionalContextunder an 800ms self-deadline; every path fails open (exit 0, empty stdout) with a typed reason in the heartbeat. Listed in cli.ts'sSTARTUP_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 — heartbeatsegment: self_transcript, no parse, no corpus write; otherwise confined full-transcript parse → redacted corpus write (session-id filename dedup, retention prune viagcCorpusTurnFiles: an extracted.txtgoes atcorpus_retention_days, one with no.ingestedsidecar only atCORPUS_UNINGESTED_RETENTION_FACTOR(3) times that, E-N1, pinned bytest/corpus-retention-uningested.serial.test.ts; an assistant-only whole-file parse heartbeatsdegraded/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==0is 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;readHeartbeatTailfeeds doctor.GBRAIN_HOOKS=0kills all events. Session-end capture dispatches per harness throughcaptureSpecFor(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 tocodexSessionsDir()+codexArchivedSessionsDir()(codex moves rollouts into the flat archived store), parses rollouts viaparseCodexHookTranscript, and falls back to bounded id-matched discovery across both stores when the SessionEnd payload carriestranscript_path: nullor a path that no longer exists (missing_path;unreadableis 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), theGBRAIN_MEMORABLEkill 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 sharedredactedToolCallsJson(span-filtered to the corpus window, highEntropy ALWAYS on — those args are the one artifact that leaves the machine) andrecordAndRelayReceipt(receipt dedup by post-redaction content hash → CLI-side consent evidence →resolveMemorableBin→ detached fire-and-forgetmemorable recordspawn; 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 isnpm i -g memorable-cli; closed source, no source install, no embedding model to configure).spawnDetachedPushpassesenv: process.envexplicitly so the detached push child inherits the parent's quarantined env view.tryExecAsync(the git wrapper behindresolveBootstrapWorkspaceRoot/repoPhaseComplete) also passesenv: process.envso git sees the quarantined view, not Bun's startup snapshot; pinned bytest/hook-push-spawn-env.test.ts. Seat identity (#4618): session-end (before any corpus write of the session), compact (beforebankCompactSegment) and the stop hook's writeback bank (beforebankWritebackTurn) record<sessionId>.seat.jsonthroughcontext/seat.ts—GBRAIN_SEATwhen valid, else the hashed harness-home seat;seat_label_invalid,seat_conflict(first seat kept) andseat_write_failedare heartbeat reasons with a fixedhint(session-end applies them last, like the deferred reasons).gcCorpusArtifactsreaps a seat sidecar or session source record once no.txtof its session remains, after a 10-minute grace; session-end counts live sessions across the spool and the legacy top level (#6611). Pinned bytest/session-seat-capture.serial.test.ts.HOOK_EVENTSis the router inventory fromsrc/cli/subcommands.ts;hook <event> --helpprints usage and never runs the event.user-promptconfines and parsestranscript_paththroughcaptureSpecFor(io.harness), so--harness codexreads the rollout underCODEX_HOME/sessions(the Claude projects root otherwise), and skips the Claude-only pressure notice for codex. #5941: the pack and user-prompt arms ask forcontextSourceId(session-start-pack.ts):GBRAIN_SOURCE, else the session's frozen source record, else the cwd's.gbrain-sourcewalk; a serve bound elsewhere answerssource_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).recognizedOnly: whole file read, every line parsed, no conversation message, some session scaffolding (session-end:empty_session). Both the hook-tail and full-session parsers skip rootisSidechain,isMeta, orisCompactSummaryexactlytrue; nested markers and truthy non-booleans do not exclude a turn. User text with a non-empty string rootorigin.kindother 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.tsuses synthetic fixtures, not new live-harness validation.genuineUserTurnIndexesseparately records accepted user-role turns containing real text blocks (harness tags and paste blocks removed first), because Claude stores tool-result-only entries withrole:'user'; archival consumers keep every placeholder while prompt-only consumers select by structure. Also extractsinjectedContextBlocks— thehook_additional_contextattachment lines a gbrain hook previously injected (verified live against claude CLI 2.1.224), plus a SessionStarthook_successattachment'scontentfrom the gbrain envelope on (session-start stdout, #7026; 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-literaltranscript_path— Claude Code on the Windows host invoking hooks viawsl.exe— is translated throughsrc/core/wsl-paths.tsand 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).parseTranscriptadditionally returnstoolCalls, 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 everytool_useblock, oldest → newest, each joined to itstool_resultoutcome bytool_use_idand then stripped of that id so no transcript-internal identifier reaches a consumer; every STRING in a collected input is bounded toTOOL_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).stripPastedContentremoves closed blocks and an unclosed tail only when the opening tag has the exact harness shape, scanning withindexOf(no lazy regex);stripPastedContentFromCorpusstrips inside each[user]block of thetoCorpusTextrendering, never across the flattened corpus, so an unclosed paste ends with its turn. Consumers: the writeback gate (banked text),isGenuineUserTextin the parser (classification only; turn, corpus, segment and ingest text keep the paste), andcorpusTextForExtraction(corpus-segments.ts: a.wb-file is one turn, other corpus files per block) used by the sweep, the checkpoint harvest and dreamextract_atoms.synthesizekeeps 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_HOMErelocates the root. Turn selection is STRUCTURAL (mapGrokLine, exported so the datedSPEC_TARGETmapping is pinned): user turns aretype:'user'text blocks WITHOUTsynthetic_reason(injected system_reminder/task_completed rows aretyped, i.e. intentionally text-free, as are tool_result-only user arrays); assistant turns need non-empty stringcontent(tool-only rows —content''/null WITHtool_calls— aretyped); system/reasoning/tool_result/backend_tool_call rows aretyped; unknown row typesskip. A recognised HUMAN-turn row whose content this parser cannot decode (usercontentmissing / non-string / non-array / an array holding non-block entries; assistant non-stringcontentwith notool_calls) ismalformedand counted as SKIPPED, never typed, so a file made only of such rows is neverexpectedEmpty— the ingest drift signal fires (bytesRead > 0, sessions 0,cleanScan=false, watermark frozen) andzeroSessionsReasonnames the malformed row count, instead of an upstream schema change silently advancing the watermark past whole conversations.chat_history.jsonlcarries NO per-message timestamps: session times come from the siblingsummary.json(created_at/last_active_at; a malformed summary is ignored, an unparseable date is never fabricated) and, because grok writessummary.jsonat session END, an in-progress session or partial rsync falls back to the log file's own mtime — a real filesystem time — withraw.timestamp_sourcestamped'summary.json'vs'file_mtime'so consumers can tell them apart (without the fallback the render refusal would freeze the--since-lastwatermark 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 barechat_historybasename, 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 yieldscwdundefined with the session id intact.