Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(hook,doctor): first push reaches a fresh Claude Code session; a declined provider decision stops model discovery
garrytan4bbdb3e68252
diff --git a/docs/architecture/key-files/agent-bootstrap.md b/docs/architecture/key-files/agent-bootstrap.mdindex 738e9c8f3e..e4300a3b39 100644--- a/docs/architecture/key-files/agent-bootstrap.md+++ b/docs/architecture/key-files/agent-bootstrap.md@@ -19,6 +19,7 @@ User-facing contract: `docs/guides/bootstrap.md`. Runbook the paste block fetche- `src/core/bootstrap/hooks.ts` + `host-specs.ts` — host wiring. `host-specs.ts` is 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-HTTP `url` + `http_headers = { Authorization = "Bearer <t>" }` config shape (loads on codex-cli 0.147.x and 0.149.x; inline `bearer_token` is 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 private `claudeConfigBase()` (CLAUDE_CONFIG_DIR-else-$HOME-else-homedir(), the directory playing the role of `~/.claude` — NOT for `claudeUserMcpConfigPath`, whose default lives at the HOME level as `~/.claude.json`), which also feeds `claudeUserSkillsDir()`/`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 `.jsonc` name preferred for parity with `opencode 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 reconcile `mcp.<name>` across it because opencode merges both), and `OPENCODE_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`/`removeClaudeHooksAt` take an explicit settings file and a marker VALUE (workspace installs stamp `bootstrap-v1` in `.claude/settings.local.json`; harness installs stamp `bootstrap-harness-v1` in user-scope settings or a --project dir — the two coexist and each removal strips only its own; `refuseOnForeignGbrainMarker` blocks 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`/`removePermissionsAllowEntry` manage the harness lane's `mcp__<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 existing `permissions` key or `permissions.allow` carries 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`/`registerCodexMcp` build argv only (Claude Code takes `--scope`, project default; Codex has no scope flag — `codex mcp add` is always user-global; `-e`/`--env GBRAIN_SOURCE` so MCP writes land in the workspace source, and the serve argv from `stdioServeArgv` in `src/core/mcp-registration.ts`: `--surface starter` by default so a pre-existing `mcp_surface: verbs` config row can't narrow the registration, or the `surface` the caller passes — `bootstrap hooks --surface`, or an existing entry's form carried over on replacement, `null` meaning a bare `serve`). `bootstrap hooks` never narrows: a matching registration is kept, `verifyMcpTargetsWorkspace` returns the existing entry's surface (`registeredSurface`) and the mismatch re-add keeps it, and the opencode writer keeps the existing command's form unless `--surface` is given. The opencode workspace lane execs NOTHING — registration is the direct `opencode-json.ts` write with an INVERTED scope default (user-global; opencode spawns project-config servers with no trust prompt, so `MCP_SCOPE=project` is an explicit opt-in that writes the committed-candidate `opencode.json` with a PATH-resolved command and prints the sharing warning), verification is config parse-back + a best-effort `opencode mcp list --pure` probe — 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 list` is a code-execution surface), and on timeout actually kills the child (SIGTERM → SIGKILL, bounded pipe drain, code 124 into the could-not-confirm branch; `probeSpawn` is 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. `detectHarness` probes `OPENCODE`/`OPENCODE_PID` (set in opencode's bash-tool children, observed 1.18.18). `ClaudeHookEnv.GBRAIN_SEAT` (#4618) renders `GBRAIN_SEAT=<label>` into local-carrier hook commands (never the committed carrier); `writeClaudeHooksAt` keeps the seat a prior install of the same marker rendered when the caller passes none, and `''` clears it. `parseSeatFlags` validates `--seat <label>` / `--no-seat` for `bootstrap hooks` and `bootstrap harness` and returns a `note` where a seat cannot be rendered (codex, opencode, the cloud committed carrier). Pinned by `test/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, so `parseClaudeHookCommand` (the inverse of `buildClaudeHookCommand`: shellQuote-aware word split, env keys limited to the four the builder writes, each at most once, an absolute launcher, nothing after `hook <sub>`, and a re-render that must equal the input) feeds `classifyHarnessHook(entry, event, identity)` → `marked` / `command` (unmarked, exactly the harness hook for THAT event, launcher/source/seat inside a `HarnessHookIdentity`, 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 recorded `launcher`/`seat` and 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 notes `harness_hook_unowned` lookalikes; `removeClaudeHooksAt(path, marker, {identity, dryRun})` returns `unmarked` (event + why, never command text) and `unowned` events; `scanHarnessHookCarrier` is the read-only per-event census (doctor, `--status`, the cross-HOME guard with identity `'any'`); `groupsCarryGbrainHook` feeds `hook_carrier_overlap`. The workspace lane (bootstrap-v1) keys on the marker alone. Pinned by `test/bootstrap-harness-hook-ownership.test.ts`. `hookEntryHash` (sha256 over `type`, `command`, `timeout`; the marker excluded, so a dropped marker keeps the hash) backs the opt-in `ownedEntryHashes` option on both writers: with it a marker match alone never replaces or removes an entry, edited marked entries come back in `preserved`, 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 the `harness_hook_unowned` notice block with `next: tell_user_to_run` and throws so the target stays failed and `--remove` exits 1), `previewHarnessRemoval` (`--remove --dry-run`: every target's would-be action, nothing written, receipt untouched), `harnessHooksPresent` (the cross-HOME `--project` guard: marked, unmarked or edited-by-shape `unowned` entries, any install; W4.8) and `harnessHookCarrierStatus` (`--status` text line + `hook_carriers` JSON).- `src/core/setup/capabilities.ts` + `src/core/setup/claude-code.ts` — `gbrain setup`'s data and Claude Code writer. `capabilities.ts` is the versioned harness × transport table (`SETUP_CAPABILITY_TABLE_VERSION`; per row `setup`, `pull`, `push`, `read_events`, `capture_events`, `docs`); push is `native-pending` or `unsupported` on every row until an observed injected event proves it. `claude-code.ts` owns entries by exact hash through the connection receipt `.gbrain-connection-claude-code-<name>[-project-<hash>].json` beside `~/.claude.json` (`connection: 'local-stdio'`, `entry_hash`/`pending_entry_hash`, `hooks.{owned,pending,edited}`, `consent`, `gbrain_home`; a receipt with `client_id` is a hosted one and is never adopted). The MCP entry (`{type:'stdio', command, args, env}`, user scope `mcpServers` or project scope `projects[<dir>].mcpServers`) is written directly; hooks go through `writeClaudeHooksAt`/`removeClaudeHooksAt` with marker `GBRAIN_SETUP_MARKER_VALUE` and `ownedEntryHashes`. `applyClaudeSetup` (under the config-dir bootstrap lock) writes the receipt `prepared` first, then the brain (`beforeMcp`), the MCP entry, the hooks and `installed`, 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 is `edited`: preserved, reported, and skipped by later runs. `removeClaudeSetup` deletes only hash-matched entries (adopted entries stay), keeps a `removed` receipt when an edited entry survives, and otherwise deletes the receipt.+- `src/core/setup/local-receipts.ts` — read-only view of this install's live local-stdio setup receipts (`.gbrain-connection-*.json` beside `~/.claude.json` and in `CODEX_HOME`; kept only when `connection: 'local-stdio'`, a numeric `setup_receipt_version`, `gbrain_home === configDir()` and status `prepared`/`installed`). Engine-free, imports no harness writer. `providerDeclineRecord()` (a recorded `providers: 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 exactly `cwd`) tells the SessionStart hook that Claude Code is starting a stdio serve.- `src/core/bootstrap/plugin-lanes.ts` — plugin-lane detection (`codexPluginProvidesName`, `claudePluginProvidesName`, `codexAnyRegistrationExists`, `claudeAnyRegistrationExists`; re-exported from harness.ts) plus `enabledPluginLanes(name)`, the one list `plugin_lane_collision` and `harness_wiring` both read. Config, not health: an enabled plugin counts even if its launcher fails.- `src/core/bootstrap/codex-hooks.ts` — the codex `hooks.json` writer (SessionEnd capture lane), built entirely on the dated `CODEX_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 legal `description` slot + a command-substring token, never a `_gbrain` key); 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_hash` config.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.bak` so it never clobbers the MCP writer's `.bak` rollback anchor); SessionEnd handlers are hard-killed at 3s (the command captures stdin to a mktemp file and detaches a nohup grandchild running the real `gbrain hook session-end --harness codex` — live-verified end-to-end). Deliberately NO `GBRAIN_SOURCE` in 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-level `sh -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's `codex_hooks_never_fired` rung names. Pinned by `test/codex-hooks-writer.test.ts`.`writeCommittedClaudeHooks` is the second, COMMITTED hook carrier: it writes marker-keyed entries into the workspace's checked-in `.claude/settings.json` using `buildPortableClaudeHookCommand` (PATH-resolved `gbrain`, fail-open when the binary is absent) so teammates cloning the repo inherit the hooks; `committedHookEvents(ws)` feeds the local writer's `carriedEvents` so the two carriers never double-wire an event, and `removeClaudeHooks` strips both.@@ -29,7 +30,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 the `LIVE_SERVE` escape hatches when no token was supplied 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`.- `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). 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 once no `.txt` of its session remains, after a 10-minute grace. 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.+- `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 once no `.txt` of its session remains, after a 10-minute grace. 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.- `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/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.mdindex b9cedb4193..05d21ad928 100644--- a/docs/architecture/key-files/commands-2-continued.md+++ b/docs/architecture/key-files/commands-2-continued.md@@ -21,3 +21,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/doctor/checks/git-convergence.ts` — `git_convergence` (#5063, brain category, after `sync_freshness`): for every non-archived filesystem source root plus `sync.repo_path` (connector sources skipped), `git status --porcelain -z` and `rev-list --left-right --count @{u}...HEAD` against the local upstream ref, never a fetch, each call bounded at 5 s and at most 50 roots. Commits not on the upstream warn after 6 h and fail after 24 h (oldest unpushed commit time); uncommitted changes warn once the oldest changed file is older than 6 h; behind is reported, not judged. Emits nothing when no probed root has an upstream. The same entry emits `tracked_ownership_marker` (#5186): `git ls-files --cached` on each of those checkouts, warn when a path `isPhysicalRootMetadata` recognizes is in the index, with a user-run `git -C <root> rm --cached <paths>` fix (an ignore rule never un-tracks a file; the push deny list is the backstop), ok otherwise, nothing without a checkout. `bootstrap-checks.ts` `bootstrap_push_health` also warns, instead of `ok`, when a recent successful push leaves the receipt workspace ahead of `origin/<branch>`. `scripts/smoke-test.sh` accepts a configured database URL (`engine status` `db_url_source`) and trusts doctor `embedding_provider` over raw OpenAI/Voyage keys. Tests: `doctor-git-convergence-5063.test.ts`, `doctor-ownership-marker.test.ts`, `bootstrap-doctor-checks.test.ts`, `smoke-test-worker.test.ts`.- `src/commands/doctor/checks/image-embedding-coverage.ts` — `image_embedding_coverage` (#6529, brain category, after `image_assets`). Counts live image pages (`page_kind = 'image'`), those with no `embedding_image` chunk, those with a NULL `source_path`, and the `managed_image_sync_unsupported` holds per source, and reads `isMultimodalEnabled()`. Ok when the brain has no image pages, when every image page has an image vector and a `source_path` and nothing is held, or when multimodal embedding is off (the counts are then informational: image search is not expected to work). On a multimodal install it warns with the counts (text coverage counts those pages as embedded while image search does not see them) and names `gbrain embed --stale --images` and `gbrain sync --no-pull --source <id>` for the holds. Read-only; no paid call. Test: `test/doctor-image-embedding-coverage.test.ts`.+- `src/commands/doctor/checks/provider-consent.ts` — `provider_consent` (OPS, engine-free filesystem lane right after `embedding_key_source`; not in `doctorReportRemote`): the provider-use decision `gbrain setup` recorded for this install (`localSetupRecords` in `src/core/setup/local-receipts.ts`). A decline (any live receipt; opt-outs win) is `ok` + info `disabled_by_choice`, "skipped by consent", naming the provider key variables present (names only) and carrying `providerConsentFix`: `gbrain setup <harness> --providers` (+ `--name`/`--scope project`), actor `user`, consent `paid`+`egress`, so `next: tell_user_to_run`. Accepted is plain `ok`; no receipt is info `not_applicable`. The same fix rides `embedding_provider`'s `--probe` skip (`checks/embedding-health.ts`), and `probe-consent.ts` authorizes nothing when a decline is recorded. Reads files only; sends nothing. Pinned by `test/doctor-provider-consent.serial.test.ts` (request counter: zero outbound under a decline, controls prove discovery and the probe are seen otherwise).diff --git a/docs/architecture/key-files/core-ai.md b/docs/architecture/key-files/core-ai.mdindex 25fd4931ee..95f75efda1 100644--- a/docs/architecture/key-files/core-ai.md+++ b/docs/architecture/key-files/core-ai.md@@ -28,7 +28,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/ai/model-resolver.ts` — Recipe-touchpoint validator. `assertTouchpoint(recipe, touchpoint, modelId)` checks the PROVIDER's capability only (anthropic has no embedding touchpoint; voyage/ollama have no chat) and never gates on the model id. Recipe `models:` arrays are informational — default-model selection (`models[0]` for `--model <provider>` shorthand and env-ready pickers), guard-test fixtures for the repo's own hardcoded defaults, and `gbrain providers list` display — NOT a runtime allowlist, so frontier models newer than a recipe work without a recipe PR. A nonexistent id surfaces as the provider's own `model_not_found` at call time; `gbrain models doctor` live-probes the configured models for a pre-flight check. Exception: `gateway.rerank()` keeps its own model-list check because each listed reranker id maps to a known request/response wire shape. `embeddingDimsForModel` matches recipe `model_dims` keys exactly first, then case-insensitively with BOTH sides folded (configured ids arrive cased, and user-editable recipe tables can carry cased keys; without the fold a cased id would fall through to `default_dims` and `gbrain init` would build a wrong-width column), before falling back to `default_dims`.-- `src/core/ai/openai-latest.ts` — latest-model discovery: OpenAI defaults are NEVER pinned. `refreshLatestOpenAIModels()` (called from `reconfigureGatewayWithEngine`, TTL 24h, 3s-bounded, fail-open, `GBRAIN_MODEL_DISCOVERY=off|0` kill switch — the test preload sets it) fetches the account's own `GET /v1/models`, ranks ids through a conservative grammar (`parseOpenAIChatId`: bare family aliases `gpt-N.M` + known tier suffixes sol/pro/terra/luna/nano/mini; dated snapshots, `-chat` Instant-class, realtime/image and UNKNOWN future suffixes are ignored — rot degrades to newest-known-shape, never a wrong pick), and maps the newest family onto the tier ladder (utility→cheap, reasoning/subagent→mid, deep→top). ONLY ids with a canonical pricing row are eligible (`rankOpenAIChatModels`'s priced filter): BudgetTracker fails closed (`no_pricing`) under a cost cap, so an unpriced discovered default would brick budget-capped backfills — a newer-unpriced family warns once naming the missing `model-pricing.ts` row. Result lands in `<configDir()>/model-cache.json` (atomic tmp+rename); `latestOpenAITiers()` is the SYNC read (stale cache beats static fallback — TTL gates refresh, never use) consumed by `resolveTierDefault`'s openai entry and the dynamic `gpt` alias. Pinned by `test/openai-latest.serial.test.ts`.+- `src/core/ai/openai-latest.ts` — latest-model discovery: OpenAI defaults are NEVER pinned. `refreshLatestOpenAIModels()` (called from `reconfigureGatewayWithEngine`, TTL 24h, 3s-bounded, fail-open, `GBRAIN_MODEL_DISCOVERY=off|0` kill switch — the test preload sets it; skipped, even forced, when a `gbrain setup` receipt for this install recorded provider use as declined — `providerDeclineRecord` in `src/core/setup/local-receipts.ts`, an unreadable record fails closed) fetches the account's own `GET /v1/models`, ranks ids through a conservative grammar (`parseOpenAIChatId`: bare family aliases `gpt-N.M` + known tier suffixes sol/pro/terra/luna/nano/mini; dated snapshots, `-chat` Instant-class, realtime/image and UNKNOWN future suffixes are ignored — rot degrades to newest-known-shape, never a wrong pick), and maps the newest family onto the tier ladder (utility→cheap, reasoning/subagent→mid, deep→top). ONLY ids with a canonical pricing row are eligible (`rankOpenAIChatModels`'s priced filter): BudgetTracker fails closed (`no_pricing`) under a cost cap, so an unpriced discovered default would brick budget-capped backfills — a newer-unpriced family warns once naming the missing `model-pricing.ts` row. Result lands in `<configDir()>/model-cache.json` (atomic tmp+rename); `latestOpenAITiers()` is the SYNC read (stale cache beats static fallback — TTL gates refresh, never use) consumed by `resolveTierDefault`'s openai entry and the dynamic `gpt` alias. Pinned by `test/openai-latest.serial.test.ts`.- `src/core/ai/openrouter-families.ts` — single source of truth for which OpenRouter model families may drive the subagent (tool) loop: `OPENROUTER_SUBAGENT_FAMILIES` (currently `anthropic/` + `deepseek/`, each backed by a live abort/retry replay pin under `test/e2e/`) + `openrouterModelSupportsSubagentLoop(modelId)` (takes the bare OpenRouter id, no `openrouter:` prefix). Shared by the openrouter recipe's predicate and the subagent handler's auto-route so the two can never disagree; a new family gets its own live pin before joining the list.diff --git a/docs/guides/setup.md b/docs/guides/setup.mdindex 6b2bb4b8b6..c4b7c0fefc 100644--- a/docs/guides/setup.md+++ b/docs/guides/setup.md@@ -48,6 +48,17 @@ the recorded answers; a flag changes one.Provider keys in the environment do not change these defaults.+### Provider use declined++A declined provider decision holds even when provider keys sit in the+environment: gbrain sends no request to a model provider it was not asked to+use. OpenAI model discovery (`GET /v1/models` on engine connect) is skipped,+and `gbrain doctor --probe` does not probe the embedding provider. `gbrain+doctor` reports the decision as `provider_consent` ("skipped by consent").+Only the user changes it: `gbrain setup claude-code --providers` records+provider use as accepted for this install. A decline in any of this install's+setup receipts wins.+## StatesSetup reports how far the wiring is proven:@@ -59,6 +70,12 @@ Setup reports how far the wiring is proven:3. `native-pending`: no observed event has shown gbrain context reaching afresh Claude Code session yet. Open a new session (Claude Code reads itsconfig at session start) and check that `/mcp` lists gbrain.++In a new Claude Code session (SessionStart `startup` or `resume`) the+SessionStart hook waits up to 4 seconds for the stdio serve Claude Code starts+alongside it, then prints the context pack (recent world-visible facts; private+facts are never pushed). Without the wait a fresh session got nothing, because+the serve binds its socket about 2 seconds after spawn.4. `native-verified`: reserved for an observed injected event; this releasenever claims it.diff --git a/src/commands/doctor/checks/embedding-health.ts b/src/commands/doctor/checks/embedding-health.tsindex 50d280c0e8..186d67dcdb 100644--- a/src/commands/doctor/checks/embedding-health.ts+++ b/src/commands/doctor/checks/embedding-health.ts@@ -20,6 +20,8 @@ import { checkError, doctorVerify, infoCheck, keylessEnablementFix } from '../chimport { brainRoutingArgs } from '../../../core/brain-resolver.ts';import type { Action } from '../../../core/agent-output.ts';import { embeddingProviderIsFree } from '../../../core/embed-consent.ts';+import { providerDeclineRecord } from '../../../core/setup/local-receipts.ts';+import { providerConsentFix } from './provider-consent.ts';import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';/** The opt-in live probe: one ~9-token embedding request, so `paid` + `egress` (runs verbatim once approved). */@@ -148,6 +150,10 @@ async function runEmbeddingProvider(ctx: DoctorContext): Promise<Check[]> {details,});}+ } else if (!(await embeddingProviderIsFree(configuredModel)) && providerDeclineRecord()) {+ const fix = providerConsentFix(providerDeclineRecord()!);+ checks.push(infoCheck('embedding_provider', `Not probed: skipped by consent. gbrain setup recorded provider use as declined, so the probe sends nothing to ${configuredModel}. The user decides; to allow provider use they run: ${fix.argv!.join(' ')}`,+ 'disabled_by_choice', fix, { probed: false, model: configuredModel, dimensions: configuredDims }));} else {// Live embed testconst start = Date.now();diff --git a/src/commands/doctor/checks/provider-consent.ts b/src/commands/doctor/checks/provider-consent.tsnew file mode 100644index 0000000000..f9c241ebad--- /dev/null+++ b/src/commands/doctor/checks/provider-consent.ts@@ -0,0 +1,78 @@+/**+ * `provider_consent` doctor check (Cat 41 wave 2): the provider-use decision+ * `gbrain setup` recorded for this install, and what it does to provider+ * calls. A recorded `declined` means gbrain contacts no model provider it was+ * not asked to use, even with provider keys in the environment: OpenAI model+ * discovery is skipped (src/core/ai/openai-latest.ts) and the opt-in+ * embedding probe reports itself skipped by consent. This check only reads+ * the receipts (src/core/setup/local-receipts.ts) and names the environment+ * keys it sees, never their values; it sends nothing. Engine-free+ * filesystem-lane entry (also under `--fast`).+ */+import type { Action } from '../../../core/agent-output.ts';+import { CONFIG_API_KEY_ENV } from '../../../core/ai/provider-env.ts';+import { localSetupRecords, type LocalSetupRecord } from '../../../core/setup/local-receipts.ts';+import type { Check } from '../../doctor.ts';+import { checkError, doctorVerify, infoCheck } from '../check-fix.ts';+import type { DoctorContext, DoctorEntry } from '../context.ts';++const DOCS = 'docs/guides/setup.md#provider-use-declined';++/** The user's way back: re-run setup with `--providers`, which records provider use as accepted. */+export function providerConsentFix(record: LocalSetupRecord): Action {+ const argv = ['gbrain', 'setup', record.harness, '--providers',+ ...(record.name === 'gbrain' ? [] : ['--name', record.name]),+ ...(record.scope === 'project' ? ['--scope', 'project'] : [])];+ return {+ argv,+ consent: ['paid', 'egress'],+ actor: 'user',+ why: 'Setup recorded provider use as declined, so gbrain contacts no model provider. Re-running setup with --providers records it as accepted; provider calls then follow the configured keys.',+ user_message: `gbrain is not contacting any AI provider because you declined provider use at setup. To allow it, run \`${argv.join(' ')}\`${record.scope === 'project' ? ' in that project directory' : ''}.`,+ verify: doctorVerify('provider_consent'),+ docs: DOCS,+ requires_exclusive: false,+ };+}++/** Provider key variables set in `env` (names only). */+export function providerKeysInEnv(env: Record<string, string | undefined>): string[] {+ const names = [...CONFIG_API_KEY_ENV.map(([, name]) => name), 'GEMINI_API_KEY'];+ return [...new Set(names)].filter((name) => !!env[name]);+}++async function runProviderConsent(_ctx: DoctorContext): Promise<Check[]> {+ const checks: Check[] = [];+ let records: LocalSetupRecord[];+ try {+ records = localSetupRecords().filter((r) => r.providers !== undefined);+ } catch (e) {+ checks.push(checkError('provider_consent', 'read the gbrain setup receipts', e));+ return checks;+ }+ const keys = providerKeysInEnv(process.env);+ const declined = records.find((r) => r.providers === 'declined');+ if (declined) {+ const env = keys.length ? ` even though ${keys.join(', ')} ${keys.length === 1 ? 'is' : 'are'} set in this environment` : '';+ const fix = providerConsentFix(declined);+ checks.push(infoCheck('provider_consent',+ `Provider check skipped by consent: gbrain setup recorded provider use as declined (${declined.path}), so gbrain sends no request to a model provider${env}, model discovery and the embedding probe included. The user decides; to allow provider use they run: ${fix.argv!.join(' ')}`,+ 'disabled_by_choice', fix,+ { decision: 'declined', receipt: declined.path, harness: declined.harness, provider_env: keys, probed: false }));+ return checks;+ }+ if (records.length) {+ checks.push({ name: 'provider_consent', status: 'ok', message: `gbrain setup recorded provider use as accepted (${records[0]!.path}); provider calls follow the configured keys.`,+ details: { decision: 'accepted', receipt: records[0]!.path, harness: records[0]!.harness, provider_env: keys } });+ return checks;+ }+ checks.push(infoCheck('provider_consent', 'No gbrain setup receipt records a provider-use decision for this install; provider calls follow the configured keys.', 'not_applicable',+ undefined, { decision: null, provider_env: keys }));+ return checks;+}++export const providerConsentEntry: DoctorEntry = {+ name: 'provider_consent',+ emits: ['provider_consent'],+ run: runProviderConsent,+};diff --git a/src/commands/doctor/probe-consent.ts b/src/commands/doctor/probe-consent.tsindex 0eab294044..406126f351 100644--- a/src/commands/doctor/probe-consent.ts+++ b/src/commands/doctor/probe-consent.ts@@ -4,7 +4,8 @@* embedding provider as configured but not probed. The probe goes through the* consent matrix (`paid` + `egress`); an unauthorized non-TTY run exits 3* before any check. A local provider that bills nothing (ollama,- * llama-server, lmstudio) needs no consent.+ * llama-server, lmstudio) needs no consent. A provider-use decline recorded+ * by `gbrain setup` skips the probe outright (provider_consent).*/import type { BrainEngine } from '../../core/engine.ts';import { setCliExitVerdict } from '../../core/cli-force-exit.ts';@@ -16,6 +17,10 @@ const PROVIDER_PROBE_EST_USD = 0.0001;export async function authorizeProviderProbe(engine: BrainEngine | null, args: string[], json: boolean): Promise<boolean> {const { embeddingProviderIsFree } = await import('../../core/embed-consent.ts');if (await embeddingProviderIsFree()) return true;+ // Setup recorded provider use as declined: embedding_provider reports the+ // probe skipped by consent and sends nothing, so there is nothing to authorize.+ const { providerDeclineRecord } = await import('../../core/setup/local-receipts.ts');+ if (providerDeclineRecord()) return true;const { requireConsent, isConsentRefusal, printConsentRefusal } = await import('../../core/consent.ts');const end = args.indexOf('--');const argv = ['gbrain', 'doctor', ...(end >= 0 ? args.slice(0, end) : args).filter(a => a !== '--yes')];diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex dbefaed85c..78a9020c1f 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -105,6 +105,7 @@ import { trustSourcesUnclaimedEntry } from './checks/trust-sources-unclaimed.ts'import { harnessWiringDoctorEntry } from './checks/harness-wiring.ts';import { agentContractEntry } from './checks/agent-contract.ts';import { chatFallbackChainEntry } from './checks/chat-fallback.ts';+import { providerConsentEntry } from './checks/provider-consent.ts';import { behaviorChangesEntry } from './checks/behavior-changes.ts';import { fenceIntegrityEntry } from './checks/fence-integrity.ts';import { managedSyncMovementEntry } from './checks/managed-sync-movement.ts';@@ -128,6 +129,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [homeDirInWorktreeEntry,defaultSourcePathEntry,embeddingKeySourceEntry,+ providerConsentEntry,harnessWiringDoctorEntry,agentContractEntry,pgliteDataDirEntry,diff --git a/src/commands/hook.ts b/src/commands/hook.tsindex 943d69c2fc..af0ec3ca59 100644--- a/src/commands/hook.ts+++ b/src/commands/hook.ts@@ -24,7 +24,8 @@* doctor/status read surface.** Events:- * session-start digest to stdout from FILE reads only (≤1.5s) [A3,G4,B3,B4]+ * session-start digest to stdout from FILE reads only (≤1.5s; ≤4s while a+ * setup-wired harness's serve starts) [A3,G4,B3,B4]* user-prompt stdin hook JSON → IPC turn_context → additionalContext* JSON on stdout (≤800ms, ≤10000 chars) [ENG-1,S3#8,A9]* stop append to the per-session live buffer + 7-day GC [G15]@@ -55,10 +56,10 @@ import {requestTurnContext,requestContextPack,hookResolveSocketForConfig,- CONTEXT_PACK_CLIENT_TIMEOUT_MS,type TurnContextResponse,type ContextPackResponse,} from '../core/context/resolve-ipc.ts';+import { requestSessionStartPack, sessionStartAwaitsServe } from '../core/context/session-start-pack.ts';import type { WindowTurn } from '../core/context/entity-salience.ts';import {confineTranscriptPath,@@ -124,6 +125,8 @@ import { isManagedFilesystemPath } from '../core/persistence/filesystem-guard.ts/** session-start self-deadline (plan D5). */export const SESSION_START_DEADLINE_MS = 1500;+/** session-start self-deadline while the harness's serve starts (session-start-pack.ts); under the 5s harness timeout. */+export const SESSION_START_SERVE_WAIT_DEADLINE_MS = 4000;/** user-prompt hard self-deadline (plan D5/ENG-1). */export const USER_PROMPT_DEADLINE_MS = 800;/** MEMORY.md digest budget [A3]. */@@ -498,6 +501,9 @@ async function hookSessionStart(io: HookIo): Promise<number> {try {const j = await readStdinJson(io, 250);const ws = io.cwd ?? (typeof j?.cwd === 'string' ? (j.cwd as string) : process.cwd());+ const awaitServe = sessionStartAwaitsServe(j?.source, io.harness ?? 'claude-code', ws);+ const deadlineMs = awaitServe ? SESSION_START_SERVE_WAIT_DEADLINE_MS : SESSION_START_DEADLINE_MS;+ let serveNotReady = false;const work = (async () => {// 1. MEMORY.md digest — allowlisted sections only, ≤3KB [A3].@@ -545,44 +551,29 @@ async function hookSessionStart(io: HookIo): Promise<number> {const cfg = loadConfig();if (sanitizeSessionId(j?.session_id) !== 'unknown') await sessionCorpus(io, cfg, sanitizeSessionId(j?.session_id), ws); // #6268: freeze at start// Engine-uniform (#4245): same config-keyed socket/secret resolution- // as the user-prompt and compact arms (PGLite data dir; Postgres- // hash12(database_url) run-dir). Null → silent skip, as before.- const packSocket = await hookResolveSocketForConfig(cfg, process.env.GBRAIN_SOURCE);- if (packSocket) {- const secret = readIpcSecretForConfig(cfg);- if (secret) {- // Same sanitizer as the compact banking path — a raw vs sanitized- // id would split the cursor key and the warm pack would miss the- // banked entities (adversarial review).- const sessionId = sanitizeSessionId(j?.session_id);- const trigger = typeof j?.source === 'string' ? `session-start:${j.source as string}` : 'session-start';- // Clamp the IPC timeout to the REMAINING hook deadline (minus a- // 100ms write margin) so the pack call can never be the thing- // that blows SESSION_START_DEADLINE_MS.- const remaining = SESSION_START_DEADLINE_MS - (Date.now() - t0) - 100;- if (remaining > 100) {- const res = await requestContextPack(packSocket, {- secret,- ...(sessionId ? { sessionId } : {}),- ...(process.env.GBRAIN_SOURCE ? { sourceId: process.env.GBRAIN_SOURCE } : {}),- trigger,- }, { timeoutMs: Math.min(CONTEXT_PACK_CLIENT_TIMEOUT_MS, remaining) });- if (res !== IPC_UNAVAILABLE && !('degraded' in res)) {- const pack = res as ContextPackResponse;- 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';- }- }- }- }+ // as the user-prompt and compact arms; the IPC timeout is clamped to+ // 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 res = await requestSessionStartPack(cfg, {+ sourceId: process.env.GBRAIN_SOURCE || undefined,+ sessionId: sanitizeSessionId(j?.session_id),+ trigger: typeof j?.source === 'string' ? `session-start:${j.source as string}` : 'session-start',+ deadlineAt: t0 + deadlineMs,+ awaitServe,+ });+ serveNotReady = res.serveNotReady;+ const pack = res.pack;+ 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';} catch { /* fail-open: no pack, digest stands alone */ }})();- const res = await withDeadline(SESSION_START_DEADLINE_MS, work);- if (res === DEADLINE && outcome === 'ok') {+ const res = await withDeadline(deadlineMs, work);+ if ((res === DEADLINE || serveNotReady) && outcome === 'ok') {outcome = 'degraded';- reason = 'deadline';+ reason = serveNotReady ? 'serve_not_ready' : 'deadline';}// Print whatever accumulated before the deadline — a partial digest// beats an empty one (the deadline bounds latency, not usefulness).diff --git a/src/core/ai/openai-latest.ts b/src/core/ai/openai-latest.tsindex 2d8bef6c27..e85926fcfe 100644--- a/src/core/ai/openai-latest.ts+++ b/src/core/ai/openai-latest.ts@@ -45,6 +45,7 @@ import { createHash } from 'node:crypto';import { join, dirname } from 'node:path';import { configDir } from '../config.ts';import { canonicalLookup } from '../model-pricing.ts';+import { providerDeclineRecord } from '../setup/local-receipts.ts';// Type-only import — erased at compile, so no runtime cycle with// model-config.ts (which imports this module for the sync overlay).import type { ModelTier } from '../model-config.ts';@@ -322,7 +323,8 @@ export interface RefreshOpts {/*** Refresh the discovery cache from `GET /v1/models`, at most once per TTL.* Best-effort by contract: never throws, never blocks longer than- * FETCH_TIMEOUT_MS, no-ops without a key or with GBRAIN_MODEL_DISCOVERY=off.+ * FETCH_TIMEOUT_MS, no-ops without a key, with GBRAIN_MODEL_DISCOVERY=off, or+ * when a `gbrain setup` receipt recorded provider use as declined.* Call sites: reconfigureGatewayWithEngine (engine connect) and — through* it — the jobs worker's per-job gateway refresh.*/@@ -346,6 +348,10 @@ export async function refreshLatestOpenAIModels(opts: RefreshOpts = {}): Promise? Date.parse(cacheFile?.last_attempt_at ?? '') || 0 : 0;const moduleAttempt = _lastAttemptFp === fp ? _lastAttemptAt : 0;if (!opts.force && Date.now() - Math.max(moduleAttempt, persistedAttempt) < FAILURE_BACKOFF_MS) return;+ // A key in the environment is not consent: `gbrain setup` recorded provider+ // use as declined for this install, so discovery never contacts the account.+ // An unreadable record fails closed (no request).+ try { if (providerDeclineRecord()) return; } catch { return; }if (_refreshInFlight) {if (_refreshInFlightFp === fp) return _refreshInFlight;diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 8c984e1166..ade16fbb37 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -479,6 +479,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.185.0', text: 'gbrain\'s own brain-repo commits (page write-through, facts fences, takes, timeline, `lint --fix`, and `sources harden` scaffolding) now take the checkout\'s commit lock (write-through waits 2 seconds, then commits its one path without it), commit only their own paths, and include both sides of a staged `git mv` rename. Paths passed to the helper or `gbrain git commit-push` are literal: a quoted glob no longer expands and fails `commit_paths_invalid`; name the files.' },{ since: '0.60.185.0', text: 'The pull that `gbrain sources pull`, the pull cron, `sources harden` and the workspace push run no longer rebases: a branch whose local and remote sides diverged is merged in memory and the checkout fast-forwards to the merge, for `pull_strategy: rebase` as well as `merge` (`set-pull-strategy` is still accepted). `gbrain sync`\'s pull is now a fetch plus a fast-forward under the commit lock. `gbrain sources harden` sets `rebase.autoStash=false`, `merge.autoStash=false` and `pull.ff=only` in the checkout\'s local git config so a stray `git pull` refuses instead of autostashing. A conflict now stops with `integrate_conflict` (ask the user; resolve with `gbrain git commit-push --push-only --expect-remote <sha> --resolve <path>=ours|theirs`), and `put_page` reports an unresolved one for that checkout.' },{ since: '0.60.185.0', text: 'The committed `scripts/brain-commit-push.sh` written by `gbrain sources harden` needs a gbrain that knows `git commit-push` to integrate remote commits. Without one it does only a locked, path-scoped commit and a plain push, and a rejected push now fails loudly (exit 4, PUSH FAILED) instead of rebasing. A helper written by a newer gbrain (a higher `# gbrain-protocol:` line) is never downgraded by an older harden.' },+ // Cat 41 wave 2 findings (GBRA-60). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.+ { since: '0.60.185.0', text: 'In a fresh Claude Code session wired by `gbrain setup claude-code` (SessionStart source `startup` or `resume`), the SessionStart hook now waits up to 4 seconds for the stdio `gbrain serve` Claude Code is starting, then prints its context pack (recent world-visible facts). Before, it gave up at once and the session got no pack. Sessions without a setup receipt, and `clear`/`compact` sessions, do not wait; a serve that never answers ends the wait fail-open with heartbeat reason `serve_not_ready`.' },+ { since: '0.60.185.0', text: 'When `gbrain setup` recorded provider use as declined, gbrain no longer sends the OpenAI model-discovery request (`GET /v1/models`) on engine connect even if `OPENAI_API_KEY` is set, and `gbrain doctor --probe` skips the embedding probe. Doctor gains `provider_consent`, which reports the recorded decision; a decline shows as skipped by consent with the user-run fix `gbrain setup <harness> --providers`.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/context/session-start-pack.ts b/src/core/context/session-start-pack.tsnew file mode 100644index 0000000000..cec667067e--- /dev/null+++ b/src/core/context/session-start-pack.ts@@ -0,0 +1,78 @@+/**+ * The SessionStart context pack (hook.ts step 6), fetched from the serve over+ * its resolve-IPC socket. Engine-free: the hook never opens the brain, so a+ * live PGLite owner is never contended.+ *+ * Cat 41 first push: Claude Code spawns its MCP servers alongside SessionStart+ * (observed on 2.1.285: the server starts ~45ms before the hook, in parallel),+ * and a fresh stdio `gbrain serve` binds its socket about 2s later. Without a+ * wait the hook found no socket and a fresh session got no pack. When+ * `sessionStartAwaitsServe` says the harness is starting a serve for this+ * session, the request is retried until the serve answers or the deadline+ * nears; otherwise one attempt, as before.+ */+import {+ CONTEXT_PACK_CLIENT_TIMEOUT_MS,+ IPC_UNAVAILABLE,+ hookResolveSocketForConfig,+ readIpcSecretForConfig,+ requestContextPack,+ type ContextPackResponse,+ type IpcPathConfig,+} from './resolve-ipc.ts';+import { claudeCodeSpawnsServe } from '../setup/local-receipts.ts';++const POLL_MS = 100;+/** Kept free before the deadline for composing and writing stdout. */+const WRITE_MARGIN_MS = 100;++/**+ * True when this SessionStart belongs to a new Claude Code process (source+ * startup or resume; clear and compact run inside a process whose serve is+ * already up) and an installed `gbrain setup claude-code` receipt says that+ * process spawns a stdio serve for this directory. Fail-open: false.+ */+export function sessionStartAwaitsServe(source: unknown, harness: string, cwd: string): boolean {+ if (harness !== 'claude-code' || (source !== undefined && source !== 'startup' && source !== 'resume')) return false;+ try {+ return claudeCodeSpawnsServe(cwd);+ } catch {+ return false;+ }+}++export interface SessionStartPackResult {+ pack: ContextPackResponse | null;+ /** The wait ran out before a serve answered. */+ serveNotReady: boolean;+}++/**+ * One context_pack request, or (awaitServe) retries until the serve answers.+ * Socket and secret are re-resolved each round: a serve on a fresh brain+ * creates the secret, and on Postgres it binds a source-keyed socket. A stale+ * serve (no protocol echo) yields no pack.+ */+export async function requestSessionStartPack(+ cfg: IpcPathConfig | null,+ opts: { sourceId?: string; sessionId: string; trigger: string; deadlineAt: number; awaitServe: boolean },+): Promise<SessionStartPackResult> {+ for (;;) {+ const socket = await hookResolveSocketForConfig(cfg, opts.sourceId);+ if (!socket) return { pack: null, serveNotReady: false };+ const remaining = opts.deadlineAt - Date.now() - WRITE_MARGIN_MS;+ if (remaining <= WRITE_MARGIN_MS) return { pack: null, serveNotReady: opts.awaitServe };+ const secret = readIpcSecretForConfig(cfg);+ const res = secret+ ? await requestContextPack(socket, {+ secret,+ ...(opts.sessionId ? { sessionId: opts.sessionId } : {}),+ ...(opts.sourceId ? { sourceId: opts.sourceId } : {}),+ trigger: opts.trigger,+ }, { timeoutMs: Math.min(CONTEXT_PACK_CLIENT_TIMEOUT_MS, remaining) })+ : IPC_UNAVAILABLE;+ if (res !== IPC_UNAVAILABLE) return { pack: 'degraded' in res ? null : res as ContextPackResponse, serveNotReady: false };+ if (!opts.awaitServe) return { pack: null, serveNotReady: false };+ await new Promise((r) => setTimeout(r, POLL_MS));+ }+}diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex f5d52b5594..fb32d4162d 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -220,6 +220,8 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set(['chat_fallback_chain',// Agent operator wave: is an agent harness wired to this brain (registration read; --only adds the smoke test).'harness_wiring',+ // Cat 41: the provider-use decision gbrain setup recorded; declined = no provider request (discovery, probe).+ 'provider_consent','frontmatter_hook',// F4b: PGLite row-delta planner statistics / Postgres autovacuum ANALYZE lag on the hot tables.'planner_stats_stale',diff --git a/src/core/setup/local-receipts.ts b/src/core/setup/local-receipts.tsnew file mode 100644index 0000000000..3bc4a141c5--- /dev/null+++ b/src/core/setup/local-receipts.ts@@ -0,0 +1,93 @@+/**+ * Read-only view of the `gbrain setup` connection receipts that belong to+ * this install (D8). Each `gbrain setup <harness>` writes a local-stdio+ * receipt beside the harness config (`.gbrain-connection-<harness>-<name>*.json`,+ * src/core/setup/claude-code.ts) recording the three consent decisions and+ * whether the harness now spawns a stdio `gbrain serve`. Two readers outside+ * setup need that record:+ *+ * - provider use: a recorded `providers: declined` keeps gbrain from+ * contacting a provider it was not asked to use (model discovery, doctor),+ * even when provider keys sit in the environment. Opt-outs win: one live+ * receipt that declines is enough.+ * - the SessionStart hook: a Claude Code receipt means the harness starts a+ * stdio serve for every new session, so the hook may wait briefly for it.+ *+ * File reads only (engine-free, no harness code imported) so the hook and the+ * gateway can call it. A receipt that is unreadable, hosted (no+ * `connection: 'local-stdio'`), removed, or written for another install+ * (`gbrain_home`) is ignored.+ */+import { readdirSync, readFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { configDir } from '../config.ts';+import { claudeUserMcpConfigPath, codexConfigPath } from '../bootstrap/host-specs.ts';++export interface LocalSetupRecord {+ path: string;+ harness: string;+ name: string;+ status: 'prepared' | 'installed';+ scope?: 'user' | 'project';+ projectDir?: string;+ providers?: 'accepted' | 'declined';+}++const RECEIPT_FILE = /^\.gbrain-connection-.+\.json$/;++function parse(path: string, home: string): LocalSetupRecord | null {+ let raw: Record<string, unknown>;+ try {+ raw = JSON.parse(readFileSync(path, 'utf8')) as Record<string, unknown>;+ } catch {+ return null;+ }+ if (raw.connection !== 'local-stdio' || typeof raw.setup_receipt_version !== 'number') return null;+ if (raw.gbrain_home !== home || (raw.status !== 'prepared' && raw.status !== 'installed')) return null;+ if (typeof raw.harness !== 'string' || typeof raw.name !== 'string') return null;+ const providers = (raw.consent as { providers?: { value?: unknown } } | undefined)?.providers?.value;+ return {+ path,+ harness: raw.harness,+ name: raw.name,+ status: raw.status,+ ...(raw.scope === 'user' || raw.scope === 'project' ? { scope: raw.scope } : {}),+ ...(typeof raw.project_dir === 'string' ? { projectDir: raw.project_dir } : {}),+ ...(providers === 'accepted' || providers === 'declined' ? { providers } : {}),+ };+}++/** Every live local-stdio setup receipt this install (`configDir()`) wrote. */+export function localSetupRecords(home: string = configDir()): LocalSetupRecord[] {+ const dirs = [...new Set([dirname(claudeUserMcpConfigPath()), dirname(codexConfigPath())])];+ const records: LocalSetupRecord[] = [];+ for (const dir of dirs) {+ let names: string[];+ try {+ names = readdirSync(dir);+ } catch {+ continue;+ }+ for (const name of names.filter((n) => RECEIPT_FILE.test(n)).sort()) {+ const record = parse(join(dir, name), home);+ if (record) records.push(record);+ }+ }+ return records;+}++/** The receipt that recorded provider use as declined for this install, or null. */+export function providerDeclineRecord(home?: string): LocalSetupRecord | null {+ return localSetupRecords(home).find((r) => r.providers === 'declined') ?? null;+}++/**+ * True when an installed `gbrain setup claude-code` registration makes Claude+ * Code spawn a stdio serve for a session started in `cwd`: a user-scope+ * receipt, or a project-scope receipt for exactly that directory (Claude Code+ * keys project MCP entries by the session's directory).+ */+export function claudeCodeSpawnsServe(cwd: string, home?: string): boolean {+ return localSetupRecords(home).some((r) => r.harness === 'claude-code' && r.status === 'installed'+ && (r.scope !== 'project' || r.projectDir === cwd));+}diff --git a/test/doctor-provider-consent.serial.test.ts b/test/doctor-provider-consent.serial.test.tsnew file mode 100644index 0000000000..7ec8d43280--- /dev/null+++ b/test/doctor-provider-consent.serial.test.ts@@ -0,0 +1,148 @@+/**+ * Cat 41 wave 2 consent negative: with provider keys in the environment and+ * `gbrain setup`'s provider-use decision recorded as declined, `gbrain doctor`+ * sent one unbilled `GET /v1/models` with the user's key in every run. The+ * request was OpenAI model discovery, which runs on every engine connect+ * (src/core/ai/openai-latest.ts). Now a recorded decline stops discovery and+ * the opt-in embedding probe, and doctor reports `provider_consent` as+ * skipped by consent with the fix that records acceptance.+ *+ * Subprocess: `bun src/cli.ts` against a fresh PGLite home, OPENAI_BASE_URL+ * pointed at an in-process server that counts every request. The control runs+ * (no receipt) prove the counter sees the calls a decline must suppress.+ * Serial: spawns subprocesses, binds a port.+ */+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { CONFIG_API_KEY_ENV } from '../src/core/ai/provider-env.ts';++const REPO = join(import.meta.dir, '..');+const KEY = ['sk', 'test', 'provider', 'consent', 'example'].join('-');++let home: string;+let requests: string[] = [];+let server: ReturnType<typeof Bun.serve>;++function childEnv(extra: Record<string, string> = {}): Record<string, string> {+ const env: Record<string, string> = {};+ for (const [k, v] of Object.entries(process.env)) if (v !== undefined) env[k] = v;+ for (const [, name] of CONFIG_API_KEY_ENV) delete env[name];+ for (const k of ['GEMINI_API_KEY', 'GBRAIN_MODEL_DISCOVERY', 'GBRAIN_DATABASE_URL', 'DATABASE_URL', 'GBRAIN_EMBEDDING_MODEL', 'OPENAI_BASE_URL', 'CLAUDE_CONFIG_DIR', 'GBRAIN_SOURCE']) delete env[k];+ return { ...env, HOME: home, GBRAIN_HOME: home, CODEX_HOME: join(home, 'codex'), ...extra };+}++async function gbrain(args: string[], extra: Record<string, string> = {}): Promise<{ code: number; stdout: string; stderr: string }> {+ const proc = Bun.spawn([process.execPath, 'run', join(REPO, 'src', 'cli.ts'), ...args], {+ cwd: home, env: childEnv(extra), stdout: 'pipe', stderr: 'pipe', stdin: 'ignore',+ });+ const killer = setTimeout(() => proc.kill('SIGKILL'), 120_000);+ const [stdout, stderr, code] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);+ clearTimeout(killer);+ return { code, stdout, stderr };+}++const providerEnv = () => ({ OPENAI_API_KEY: KEY, OPENAI_BASE_URL: `http://127.0.0.1:${server.port}/v1` });++function checksOf(stdout: string): Array<Record<string, unknown>> {+ const doc = JSON.parse(stdout.slice(stdout.indexOf('{'))) as { checks: Array<Record<string, unknown>> };+ return doc.checks;+}++function setConfig(patch: Record<string, unknown>, drop: string[] = []): void {+ const path = join(home, '.gbrain', 'config.json');+ const cfg = JSON.parse(readFileSync(path, 'utf8')) as Record<string, unknown>;+ for (const k of drop) delete cfg[k];+ writeFileSync(path, JSON.stringify({ ...cfg, ...patch }));+}++/** What `gbrain setup claude-code` leaves beside ~/.claude.json. */+function writeReceipt(providers: 'accepted' | 'declined'): void {+ writeFileSync(join(home, '.gbrain-connection-claude-code-gbrain.json'), JSON.stringify({+ harness: 'claude-code', connection: 'local-stdio', setup_receipt_version: 1, status: 'installed', name: 'gbrain',+ gbrain_home: join(home, '.gbrain'), scope: 'user',+ consent: { providers: { value: providers, source: 'default' }, capture: { value: 'declined', source: 'default' } },+ }));+}++beforeAll(async () => {+ server = Bun.serve({+ port: 0,+ fetch(req) {+ requests.push(`${req.method} ${new URL(req.url).pathname}`);+ if (new URL(req.url).pathname.endsWith('/embeddings')) {+ return Response.json({ object: 'list', data: [{ object: 'embedding', index: 0, embedding: new Array(1536).fill(0.01) }], model: 'text-embedding-3-large', usage: { prompt_tokens: 1, total_tokens: 1 } });+ }+ return Response.json({ object: 'list', data: [{ id: 'gpt-4o-mini', object: 'model' }] });+ },+ });+ home = mkdtempSync(join(tmpdir(), 'gb-pc-'));+ mkdirSync(join(home, 'codex'), { recursive: true });+ const init = await gbrain(['init', '--pglite', '--no-embedding']);+ expect(init.code).toBe(0);+}, 180_000);++afterAll(() => {+ server.stop(true);+ rmSync(home, { recursive: true, force: true });+});++beforeEach(() => {+ requests = [];+ rmSync(join(home, '.gbrain', 'model-cache.json'), { force: true });+ rmSync(join(home, '.gbrain-connection-claude-code-gbrain.json'), { force: true });+ setConfig({ embedding_disabled: true }, ['embedding_model', 'embedding_dimensions']);+});++describe('doctor with provider keys present', () => {+ test('control: with no recorded decision, doctor contacts the provider (model discovery)', async () => {+ const run = await gbrain(['doctor', '--json'], providerEnv());+ expect(requests).toContain('GET /v1/models');+ const check = checksOf(run.stdout).find((c) => c.name === 'provider_consent');+ expect(check?.status).toBe('ok');+ expect(check?.readiness_state).toBe('not_applicable');+ }, 180_000);++ test('setup declined provider use: zero outbound requests, provider check skipped by consent with a fix', async () => {+ writeReceipt('declined');+ const run = await gbrain(['doctor', '--json'], providerEnv());+ expect(requests).toEqual([]);+ const check = checksOf(run.stdout).find((c) => c.name === 'provider_consent')!;+ expect(check.status).toBe('ok');+ expect(check.severity).toBe('info');+ expect(check.readiness_state).toBe('disabled_by_choice');+ expect(String(check.message)).toContain('skipped by consent');+ expect(String(check.message)).toContain('OPENAI_API_KEY');+ expect(String(check.message)).not.toContain(KEY);+ const fix = check.fix as { argv: string[]; next: string; consent: string[] };+ expect(fix.argv).toEqual(['gbrain', 'setup', 'claude-code', '--providers']);+ expect(fix.consent).toEqual(['paid', 'egress']);+ expect(fix.next).not.toBe('run');+ expect((check.details as { provider_env: string[] }).provider_env).toEqual(['OPENAI_API_KEY']);+ }, 180_000);++ test('control: the opt-in embedding probe contacts the provider when no decision is recorded', async () => {+ setConfig({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536 }, ['embedding_disabled']);+ await gbrain(['doctor', '--only', 'embedding_provider', '--probe', '--yes', '--json'], { ...providerEnv(), GBRAIN_MODEL_DISCOVERY: 'off' });+ expect(requests).toContain('POST /v1/embeddings');+ }, 180_000);++ test('setup declined provider use: even `--probe --yes` sends nothing and reports the probe skipped by consent', async () => {+ writeReceipt('declined');+ setConfig({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536 }, ['embedding_disabled']);+ const run = await gbrain(['doctor', '--only', 'embedding_provider', '--probe', '--yes', '--json'], providerEnv());+ expect(requests).toEqual([]);+ const check = checksOf(run.stdout).find((c) => c.name === 'embedding_provider')!;+ expect(check.readiness_state).toBe('disabled_by_choice');+ expect(String(check.message)).toContain('skipped by consent');+ expect((check.fix as { argv: string[] }).argv).toEqual(['gbrain', 'setup', 'claude-code', '--providers']);+ }, 180_000);++ test('setup accepted provider use: discovery runs as before', async () => {+ writeReceipt('accepted');+ const run = await gbrain(['doctor', '--json'], providerEnv());+ expect(requests).toContain('GET /v1/models');+ expect(checksOf(run.stdout).find((c) => c.name === 'provider_consent')?.details).toMatchObject({ decision: 'accepted' });+ }, 180_000);+});diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex e5514a7b78..f218018b3e 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -374,6 +374,18 @@"name": "embedding_key_source","status": "ok"},+ {+ "category": "ops",+ "details": {+ "decision": null,+ "provider_env": []+ },+ "message": "No gbrain setup receipt records a provider-use decision for this install; provider calls follow the configured keys.",+ "name": "provider_consent",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },{"category": "ops","details": {diff --git a/test/fixtures/goldens/doctor/json-pglite-fast.json b/test/fixtures/goldens/doctor/json-pglite-fast.jsonindex 8b8da128cd..c7b4947856 100644--- a/test/fixtures/goldens/doctor/json-pglite-fast.json+++ b/test/fixtures/goldens/doctor/json-pglite-fast.json@@ -273,6 +273,18 @@"name": "embedding_key_source","status": "ok"},+ {+ "category": "ops",+ "details": {+ "decision": null,+ "provider_env": []+ },+ "message": "No gbrain setup receipt records a provider-use decision for this install; provider calls follow the configured keys.",+ "name": "provider_consent",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },{"category": "ops","details": {diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex 436d9a5e97..2d0c2f26ad 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -377,6 +377,18 @@"name": "embedding_key_source","status": "ok"},+ {+ "category": "ops",+ "details": {+ "decision": null,+ "provider_env": []+ },+ "message": "No gbrain setup receipt records a provider-use decision for this install; provider calls follow the configured keys.",+ "name": "provider_consent",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },{"category": "ops","details": {diff --git a/test/fixtures/goldens/doctor/json-postgres-unreachable-fast.json b/test/fixtures/goldens/doctor/json-postgres-unreachable-fast.jsonindex a0c6b3c2f9..a7e7d0a91f 100644--- a/test/fixtures/goldens/doctor/json-postgres-unreachable-fast.json+++ b/test/fixtures/goldens/doctor/json-postgres-unreachable-fast.json@@ -225,6 +225,18 @@"name": "embedding_key_source","status": "ok"},+ {+ "category": "ops",+ "details": {+ "decision": null,+ "provider_env": []+ },+ "message": "No gbrain setup receipt records a provider-use decision for this install; provider calls follow the configured keys.",+ "name": "provider_consent",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },{"category": "ops","details": {diff --git a/test/fixtures/goldens/doctor/json-postgres-unreachable.json b/test/fixtures/goldens/doctor/json-postgres-unreachable.jsonindex 6a6a209b0c..c09b650421 100644--- a/test/fixtures/goldens/doctor/json-postgres-unreachable.json+++ b/test/fixtures/goldens/doctor/json-postgres-unreachable.json@@ -224,6 +224,18 @@"name": "embedding_key_source","status": "ok"},+ {+ "category": "ops",+ "details": {+ "decision": null,+ "provider_env": []+ },+ "message": "No gbrain setup receipt records a provider-use decision for this install; provider calls follow the configured keys.",+ "name": "provider_consent",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },{"category": "ops","details": {diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex 227972f87c..f0da7b89a1 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -213,6 +213,10 @@"category": "brain","name": "embedding_key_source"},+ {+ "category": "ops",+ "name": "provider_consent"+ },{"category": "ops","name": "harness_wiring"diff --git a/test/hook-session-start-serve-wait.serial.test.ts b/test/hook-session-start-serve-wait.serial.test.tsnew file mode 100644index 0000000000..b96df6b863--- /dev/null+++ b/test/hook-session-start-serve-wait.serial.test.ts@@ -0,0 +1,228 @@+/**+ * Cat 41 first push (wave 2): in a fresh Claude Code session the harness+ * spawns the stdio `gbrain serve` alongside SessionStart, and the serve binds+ * its IPC socket about 2s later. Before this fix the hook found no socket,+ * skipped the context pack, and printed nothing (3/3 runs). Now, for a fresh+ * process (source startup/resume) whose install has a `gbrain setup+ * claude-code` receipt, SessionStart waits for that serve within+ * SESSION_START_SERVE_WAIT_DEADLINE_MS.+ *+ * Hermetic: the "serve" is an in-process IPC listener bound after the hook+ * starts, answering with the real context_pack handler over an in-memory+ * PGLite brain (one owner: this process). Serial: env + sockets.+ */+import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import type net from 'node:net';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { runHook, readHeartbeatTail, SESSION_START_DEADLINE_MS, SESSION_START_SERVE_WAIT_DEADLINE_MS } from '../src/commands/hook.ts';+import {+ ensureIpcSecretForConfig,+ resolveSocketPathForConfig,+ startResolveIpcServer,+ type IpcPathConfig,+} from '../src/core/context/resolve-ipc.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { makeContextPackIpcHandler } from '../src/mcp/context-pack-handler.ts';+import { configDir } from '../src/core/config.ts';+import { __resetHotMemoryCacheForTests } from '../src/core/facts/meta-hook.ts';++const FACT = 'The team locker code is 4417-QX.';+const SERVE_DELAY_MS = 800;+/** Past SESSION_START_DEADLINE_MS: a hook that does not wait can never reach this serve. */+const LATE_SERVE_DELAY_MS = 2500;+const ENV_KEYS = ['GBRAIN_HOME', 'DATABASE_URL', 'GBRAIN_DATABASE_URL', 'GBRAIN_SOURCE', 'GBRAIN_HOOKS', 'GBRAIN_HOOK_LANE', 'CLAUDE_CONFIG_DIR', 'CODEX_HOME'] as const;++let engine: PGLiteEngine;+let tmp: string;+let ws: string;+let saved: Record<string, string | undefined>;+let servers: net.Server[] = [];+let timers: ReturnType<typeof setTimeout>[] = [];++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.insertFact({ fact: FACT, entity_slug: null, source: 'user told me, test', visibility: 'world', embedding: null } as never, { source_id: 'default' });+}, 120_000);++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(() => {+ __resetHotMemoryCacheForTests();+ tmp = mkdtempSync(join(tmpdir(), 'gb-ssw-'));+ saved = {};+ for (const k of ENV_KEYS) {+ saved[k] = process.env[k];+ delete process.env[k];+ }+ process.env.GBRAIN_HOME = tmp;+ process.env.CLAUDE_CONFIG_DIR = join(tmp, 'claude');+ process.env.CODEX_HOME = join(tmp, 'codex');+ mkdirSync(join(tmp, 'claude'), { recursive: true });+ ws = join(tmp, 'ws');+ mkdirSync(ws, { recursive: true });+});++afterEach(() => {+ for (const t of timers) clearTimeout(t);+ timers = [];+ for (const s of servers) {+ try { s.close(); } catch { /* noop */ }+ }+ servers = [];+ for (const k of ENV_KEYS) {+ if (saved[k] === undefined) delete process.env[k];+ else process.env[k] = saved[k];+ }+ rmSync(tmp, { recursive: true, force: true });+});++function writeConfig(cfg: IpcPathConfig): void {+ mkdirSync(join(tmp, '.gbrain'), { recursive: true });+ writeFileSync(join(tmp, '.gbrain', 'config.json'), JSON.stringify(cfg));+}++function pgliteConfig(): IpcPathConfig {+ const dataDir = join(tmp, 'db');+ mkdirSync(dataDir, { recursive: true });+ return { engine: 'pglite', database_path: dataDir };+}++/** What `gbrain setup claude-code` leaves beside ~/.claude.json. */+function writeSetupReceipt(overrides: Record<string, unknown> = {}): void {+ writeFileSync(join(tmp, 'claude', '.gbrain-connection-claude-code-gbrain.json'), JSON.stringify({+ harness: 'claude-code',+ connection: 'local-stdio',+ setup_receipt_version: 1,+ status: 'installed',+ name: 'gbrain',+ gbrain_home: configDir(),+ scope: 'user',+ consent: { providers: { value: 'declined', source: 'default' }, capture: { value: 'declined', source: 'default' } },+ ...overrides,+ }));+}++/** The serve the harness spawned: binds its socket (and secret) `delayMs` after the hook starts. */+function startServeLater(cfg: IpcPathConfig, delayMs: number, sourceId?: string): void {+ timers.push(setTimeout(async () => {+ const secret = ensureIpcSecretForConfig(cfg)!;+ const server = await startResolveIpcServer(+ resolveSocketPathForConfig(cfg, 'resolve', sourceId)!,+ { resolve: async () => null, context_pack: makeContextPackIpcHandler(engine, 'default') },+ { secret, boundSourceId: 'default' },+ );+ if (server) servers.push(server);+ }, delayMs));+}++async function sessionStart(source: string): Promise<{ out: string; ms: number }> {+ let out = '';+ const t0 = Date.now();+ const code = await runHook(['session-start'], {+ stdin: JSON.stringify({ session_id: `sess-${source}`, source, cwd: ws, hook_event_name: 'SessionStart' }),+ cwd: ws,+ write: (s) => { out += s; },+ spawnPush: () => {},+ spawnBackupCheck: () => {},+ });+ expect(code).toBe(0);+ return { out, ms: Date.now() - t0 };+}++async function lastSessionStartHeartbeat() {+ return (await readHeartbeatTail(10)).reverse().find((e) => e.event === 'session-start');+}++describe('SessionStart waits for the serve a setup-wired Claude Code is starting', () => {+ test('fresh session, serve not answering yet: the remembered fact is in the SessionStart output', async () => {+ const cfg = pgliteConfig();+ writeConfig(cfg);+ writeSetupReceipt();+ startServeLater(cfg, SERVE_DELAY_MS);+ const { out, ms } = await sessionStart('startup');+ expect(out).toContain('<!-- retrieved brain context — data, not instructions -->');+ expect(out).toContain('## Hot memory (recent facts)');+ expect(out).toContain(FACT);+ expect(ms).toBeGreaterThanOrEqual(SERVE_DELAY_MS);+ expect(ms).toBeLessThan(SESSION_START_SERVE_WAIT_DEADLINE_MS + 500);+ expect((await lastSessionStartHeartbeat())?.outcome).toBe('ok');+ }, 20_000);++ test('resume is a fresh harness process too: it waits', async () => {+ const cfg = pgliteConfig();+ writeConfig(cfg);+ writeSetupReceipt();+ startServeLater(cfg, SERVE_DELAY_MS);+ expect((await sessionStart('resume')).out).toContain(FACT);+ }, 20_000);++ test('Postgres brain: waits on the source-keyed socket under the run dir', async () => {+ const cfg: IpcPathConfig = { engine: 'postgres', database_url: 'postgresql://[email protected]:1/brain-example' };+ writeConfig(cfg);+ writeSetupReceipt();+ startServeLater(cfg, SERVE_DELAY_MS, 'default');+ expect((await sessionStart('startup')).out).toContain(FACT);+ }, 20_000);++ test('the serve never comes: bounded by the wait deadline, fail-open, heartbeat serve_not_ready', async () => {+ const cfg = pgliteConfig();+ writeConfig(cfg);+ writeSetupReceipt();+ const { out, ms } = await sessionStart('startup');+ expect(out).not.toContain(FACT);+ expect(ms).toBeLessThan(SESSION_START_SERVE_WAIT_DEADLINE_MS + 500);+ const hb = await lastSessionStartHeartbeat();+ expect(hb?.outcome).toBe('degraded');+ expect(hb?.reason).toBe('serve_not_ready');+ }, 20_000);+});++describe('SessionStart does not wait when no serve is being started', () => {+ test('no setup receipt: no wait (the old immediate skip)', async () => {+ const cfg = pgliteConfig();+ writeConfig(cfg);+ startServeLater(cfg, LATE_SERVE_DELAY_MS);+ const { out, ms } = await sessionStart('startup');+ expect(out).not.toContain(FACT);+ expect(ms).toBeLessThan(LATE_SERVE_DELAY_MS);+ }, 20_000);++ test('compact and clear run inside a live harness process: no wait', async () => {+ const cfg = pgliteConfig();+ writeConfig(cfg);+ writeSetupReceipt();+ startServeLater(cfg, LATE_SERVE_DELAY_MS);+ for (const source of ['compact', 'clear']) {+ const { out, ms } = await sessionStart(source);+ expect(out).not.toContain(FACT);+ expect(ms).toBeLessThan(LATE_SERVE_DELAY_MS);+ expect((await lastSessionStartHeartbeat())?.reason).not.toBe('serve_not_ready');+ }+ }, 20_000);++ test('a receipt from another install, a removed receipt, or a project receipt for another directory: no wait', async () => {+ const cfg = pgliteConfig();+ writeConfig(cfg);+ startServeLater(cfg, LATE_SERVE_DELAY_MS);+ for (const overrides of [{ gbrain_home: join(tmp, 'other-install') }, { status: 'removed' }, { scope: 'project', project_dir: join(tmp, 'elsewhere') }]) {+ writeSetupReceipt(overrides);+ const { out, ms } = await sessionStart('startup');+ expect(out).not.toContain(FACT);+ expect(ms).toBeLessThan(SESSION_START_DEADLINE_MS + 500);+ }+ }, 20_000);++ test('a project receipt for this directory waits', async () => {+ const cfg = pgliteConfig();+ writeConfig(cfg);+ writeSetupReceipt({ scope: 'project', project_dir: ws });+ startServeLater(cfg, SERVE_DELAY_MS);+ expect((await sessionStart('startup')).out).toContain(FACT);+ }, 20_000);+});diff --git a/test/openai-latest.serial.test.ts b/test/openai-latest.serial.test.tsindex 9fa2a9b48c..d213d3bf14 100644--- a/test/openai-latest.serial.test.ts+++ b/test/openai-latest.serial.test.ts@@ -25,8 +25,9 @@ import {_resetOpenAILatestForTests,} from '../src/core/ai/openai-latest.ts';import { resolveTierDefault, openaiStaticTierFallback } from '../src/core/model-config.ts';+import { configDir } from '../src/core/config.ts';-const PINNED = ['GBRAIN_HOME', 'GBRAIN_MODEL_DISCOVERY', 'OPENAI_API_KEY', 'ANTHROPIC_API_KEY'] as const;+const PINNED = ['GBRAIN_HOME', 'GBRAIN_MODEL_DISCOVERY', 'OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'CLAUDE_CONFIG_DIR'] as const;let saved: Record<string, string | undefined>;let tmpHome: string;@@ -195,6 +196,26 @@ describe('refresh + cache + resolution overlay', () => {expect(calls).toBe(2);});+ test('a provider-use decline recorded by gbrain setup stops discovery, even forced; acceptance does not', async () => {+ process.env.CLAUDE_CONFIG_DIR = tmpHome;+ const receipt = join(tmpHome, '.gbrain-connection-claude-code-gbrain.json');+ const write = (providers: string) => writeFileSync(receipt, JSON.stringify({+ harness: 'claude-code', connection: 'local-stdio', setup_receipt_version: 1, status: 'installed', name: 'gbrain',+ gbrain_home: configDir(), scope: 'user', consent: { providers: { value: providers, source: 'flag' } },+ }));+ let calls = 0;+ const counting = (async () => {+ calls++;+ return new Response(JSON.stringify({ data: [{ id: 'gpt-5.6' }] }), { status: 200 });+ }) as unknown as typeof fetch;+ write('declined');+ await refreshLatestOpenAIModels({ env: { OPENAI_API_KEY: 'k' }, fetchImpl: counting, force: true });+ expect(calls).toBe(0);+ write('accepted');+ await refreshLatestOpenAIModels({ env: { OPENAI_API_KEY: 'k' }, fetchImpl: counting, force: true });+ expect(calls).toBe(1);+ });+test('concurrent refreshes for the same identity share one fetch', async () => {let calls = 0;let release!: (response: Response) => void;