Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(context,chronicle): opt-in session-only hot memory; bounded malformed-proposal diagnostics (#7026, #7234)
garrytan54f6af915273
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ae5185cfed..f0a50beb3e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -55,6 +55,24 @@ identifiers and attribution are available in the pre-removal Git revision- Preview with `gbrain repair duplicate-facts`, then run the printed `--apply --expect <hash> --yes` after you agree. Retired copies get `expired_at` and `superseded_by`; they are never deleted or withdrawn.- Near duplicates (different wording) are never merged or retired.+### Opt-in session-only hot memory and chronicle diagnostics++**Two small fixes: hot memory can stay inside the current session, and a refused chronicle answer says which check failed (#7026, #7234).**++#### What changed++| Situation | Before | Now |+|---|---|---|+| A session with no facts of its own asks for hot memory (turn hook, session-start pack) | it gets the source's newest facts from the last 24 hours, which can come from other sessions | unchanged by default; with `gbrain config set context.hot_memory.session_only true` it gets none, and a session with facts of its own gets only those |+| The chronicle phase refuses a judge answer as `malformed_proposal` | only the reason code, so nobody could tell which check failed without the proposal itself | one warning line and a `malformed` field on the outcome name a fixed code (`missing_field`, `wrong_type`, `when_unparseable`, ...), the schema field, the JSON type found and counts; never a value, the prompt or the raw response |++**Spend effect:** none. No new model calls, no default or cap changes. Nothing is rewritten on upgrade.++#### Itemized changes++- New DB-plane key `context.hot_memory.session_only` (default false), read per request by the `turn_context` and `context_pack` IPC handlers and passed to both hot-fact reads; it is part of the hot-memory cache key, so the fallback and session-only answers never share an entry. MCP `_meta.brain_hot_memory` and the IPC wire format are unchanged. Guide: [ambient writeback](docs/guides/ambient-writeback.md#hot-memory-and-other-sessions). Reported by @benswinney in #7026.+- Chronicle `malformed_proposal` refusals carry bounded diagnostics (`src/core/chronicle/proposal-diagnostics.ts`): at most 50 proposals, 50 `who` entries and 256 characters per string are inspected, nested values are typed and never walked, and a defect past those bounds reads `beyond_bounds`. Refusal, retry/backoff, writes and admission are unchanged. Reported by @Masashi-Ono0611 in #7234.+Duplicate facts reported by @mikez93 (#7043). Hot-memory dedupe reported by @benswinney (#7023). Session-start re-injection reported by @benswinney (#7026). Assistant facts relinked onto core pages reported by @andrew-agents-bot (#7270).## [0.60.349.0] - 2026-10-21diff --git a/docs/architecture/key-files/agent-bootstrap-continued.md b/docs/architecture/key-files/agent-bootstrap-continued.mdindex 1a8349d853..75747019dd 100644--- a/docs/architecture/key-files/agent-bootstrap-continued.md+++ b/docs/architecture/key-files/agent-bootstrap-continued.md@@ -5,7 +5,7 @@- `src/core/wsl-paths.ts` — WSL Windows-drive path translation shared by the doctor asset checks (`src/commands/doctor-asset-paths.ts`) and hook-transcript confinement (`confineTranscriptPath` above). Exports `WINDOWS_DRIVE_PATH_RE`, `translateWindowsPath(p, mountRoot)` (`C:\Users\x\file` → `<mountRoot>/c/Users/x/file`; null for non-drive input so callers keep the original untouched), `parseWslAutomountRoot(conf)` (the `/etc/wsl.conf` `[automount] root` value, default `/mnt`), and `detectWslMountRoot()` (null off-WSL). Mechanical detection + translation only — POLICY stays with callers (skip vs stat vs confine): the hook lane confines the translated path to the known Claude config tree, doctor decides skip-vs-stat. Pinned by the WSL cases in `test/claude-code-jsonl.test.ts`.- `src/core/context/turn-context.ts` — server-side per-turn assembly: reflex pointers + volunteered pages (≤3) + hot facts (always `visibility=['world']` — the IPC path never widens what MCP would return) under a "data, not instructions" envelope, trimmed to ≤8KB (the harness caps hook output at 10,000 chars). The ambient `context_pack` and `delta` modes are world-only across every arm by default; only an explicit trusted-local `include_private` widens entity cards, changed pages, threads, and facts together. The result exposes `pointers` AND post-trim `volunteered` — exactly what the rendered text carries — so the IPC delivery point can log the feedback loop without ever counting a trimmed-out page. Reuses the hot-memory cache keyed by typed sessionId. Engine-agnostic. Hot facts render through the shared `renderFactLine` (speaker prefix, trust label or data envelope), and a fact whose rendered line or unlabeled line (without the drifting confidence) already appears in `priorContextText` is not re-injected, the same cross-turn contract as volunteered pages (#5591, #7023). In turn mode, System One S6 (`recall_needed`, `src/core/context/recall-needed.ts`) runs concurrently with the reflex arms; the reflex block is rendered first and S6 may only replace its pointer/volunteer window (fire or suppress) when it finishes inside its own deadline, reported as `decide.recall_needed` on the result only when the slot is not off.- `src/core/context/resolve-ipc.ts` (IPC v2) — discriminated-union requests (absent `kind` = legacy resolve; `turn_context` carries `protocol: 2` + a shared secret from a 0600 file in the data dir, plus an additive `channel` for feedback-loop attribution — wire channel claims are validated to the harness channels at the logging site, anything else logs as the default hook channel), handler map, named response types, per-kind timeouts/size caps, socket + parent dir permissions set before exposure, server-side source binding (cross-source requests rejected), protocol echo (a response without it = stale serve → loud degradation). Bind policy: `startResolveIpcServer` connect-probes the path first — a live owner makes it return null (that serve stays the IPC provider; a transient serve never unlinks a live socket), only a dead/absent owner's entry is unlinked (unconditionally, since Bun on win32 cannot stat the AF_UNIX socket file it leaves behind) before listen. The connection handler processes exactly ONE request per connection (trailing bytes mid-await never double-process a line or double-log a delivery); the client clamps a too-big request below the message cap by dropping the advisory `priorContextText` BEFORE any conversation turn. Delivery seams: `onDelivered` (resolve kind) and `onTurnContextDelivered` (turn_context kind) both fire ONLY after the response write succeeds — a block abandoned before the serve responded is never counted (serve's callback logs the delivered block's volunteered pages + pointers to `context_volunteer_events` under the request channel); write-accept still isn't proof of injection (the client can trim/drop after receipt), which is why the `volunteer_channels` doctor check reconciles counts against the hook heartbeat. v1 clients and servers interoperate untouched. Serve-delegated sync rides the same socket as three additive secret-gated kinds (`sync_start`/`sync_status`/`sync_abort`, wire shapes + fail-closed option validation in `src/core/context/sync-ipc.ts`): start+poll, one line per connection, O(1) handlers with no server budget race; a pre-delegation serve answers `unknown_kind:*` without the protocol echo and the client degrades to the typed stale-serve refusal.-- `src/core/context/turn-context.ts` — server-side per-turn assembly: reflex pointers + volunteered pages (≤3) + hot facts (always `visibility=['world']` — the IPC path never widens what MCP would return) under a "data, not instructions" envelope, trimmed to ≤8KB (the harness caps hook output at 10,000 chars). `delta` pages carry `updated_at` from `Page.updated_at_iso` (the column's microseconds, projected by `listPages`), so `next_cursor.since` and the session `last_wake_at` (read back via `to_char` in `session-state.ts`) resume from the exact row — a millisecond-rounded cursor re-delivers same-millisecond pages on the next wake; the `delta` op keeps an already-canonical 6-digit ISO `since` verbatim instead of re-rounding it through a JS Date. The ambient `context_pack` and `delta` modes are world-only across every arm by default; only an explicit trusted-local `include_private` widens entity cards, changed pages, threads, and facts together. The result exposes `pointers` AND post-trim `volunteered` — exactly what the rendered text carries — so the IPC delivery point can log the feedback loop without ever counting a trimmed-out page. Reuses the hot-memory cache keyed by typed sessionId. Engine-agnostic. In turn mode, System One S6 (`recall_needed`, `src/core/context/recall-needed.ts`) runs concurrently with the reflex arms; the reflex block is rendered first and S6 may only replace its pointer/volunteer window (fire or suppress) when it finishes inside its own deadline, reported as `decide.recall_needed` on the result only when the slot is not off. Pack cards resolve over `sources` (home first) plus source-qualified `entityRefs`, are deduplicated by `(source_id, slug)`, and each card's activation verdict and newer mentions read its OWN source, never a same-slug page in another source; a card outside the home source renders `(source <id>)`. delta's arms publish their results in one assignment each and the verb reads `deltaArms` (`ok`/`failed`/`unknown`) from the same snapshot as the arrays, so a deadline can never pair a stale flag with a half-filled arm; the facts arm reads `listFactsKeyset` (ascending `(created_at, id)`, limit+1 probe) and returns the raw rows with their collapsed representative (`deltaFactsRaw`); a thread-builder throw marks `threads` failed. `session-state.ts` distinguishes absent, loaded and unavailable (`readDeltaSessionState`), stores the facts keyset and the degraded-wake counter (migration v208), and binds timestamps as `$n::text::timestamptz` so postgres.js cannot truncate them to milliseconds.+- `src/core/context/turn-context.ts` — server-side per-turn assembly: reflex pointers + volunteered pages (≤3) + hot facts (always `visibility=['world']` — the IPC path never widens what MCP would return) under a "data, not instructions" envelope, trimmed to ≤8KB (the harness caps hook output at 10,000 chars). `delta` pages carry `updated_at` from `Page.updated_at_iso` (the column's microseconds, projected by `listPages`), so `next_cursor.since` and the session `last_wake_at` (read back via `to_char` in `session-state.ts`) resume from the exact row — a millisecond-rounded cursor re-delivers same-millisecond pages on the next wake; the `delta` op keeps an already-canonical 6-digit ISO `since` verbatim instead of re-rounding it through a JS Date. The ambient `context_pack` and `delta` modes are world-only across every arm by default; only an explicit trusted-local `include_private` widens entity cards, changed pages, threads, and facts together. The result exposes `pointers` AND post-trim `volunteered` — exactly what the rendered text carries — so the IPC delivery point can log the feedback loop without ever counting a trimmed-out page. Reuses the hot-memory cache keyed by typed sessionId; `sessionOnly` (from the IPC handlers) reaches both hot-fact reads (turn mode and `fetchHotFacts` for pack), so a session with no facts of its own gets none. Engine-agnostic. In turn mode, System One S6 (`recall_needed`, `src/core/context/recall-needed.ts`) runs concurrently with the reflex arms; the reflex block is rendered first and S6 may only replace its pointer/volunteer window (fire or suppress) when it finishes inside its own deadline, reported as `decide.recall_needed` on the result only when the slot is not off. Pack cards resolve over `sources` (home first) plus source-qualified `entityRefs`, are deduplicated by `(source_id, slug)`, and each card's activation verdict and newer mentions read its OWN source, never a same-slug page in another source; a card outside the home source renders `(source <id>)`. delta's arms publish their results in one assignment each and the verb reads `deltaArms` (`ok`/`failed`/`unknown`) from the same snapshot as the arrays, so a deadline can never pair a stale flag with a half-filled arm; the facts arm reads `listFactsKeyset` (ascending `(created_at, id)`, limit+1 probe) and returns the raw rows with their collapsed representative (`deltaFactsRaw`); a thread-builder throw marks `threads` failed. `session-state.ts` distinguishes absent, loaded and unavailable (`readDeltaSessionState`), stores the facts keyset and the degraded-wake counter (migration v208), and binds timestamps as `$n::text::timestamptz` so postgres.js cannot truncate them to milliseconds.- `src/core/context/resolve-ipc.ts` (IPC v2) — discriminated-union requests (absent `kind` = legacy resolve; `turn_context` carries `protocol: 2` + a shared secret from a 0600 file in the data dir, plus an additive `channel` for feedback-loop attribution — wire channel claims are validated to the harness channels at the logging site, anything else logs as the default hook channel), handler map, named response types, per-kind timeouts/size caps, socket + parent dir permissions set before exposure, server-side source binding (cross-source requests rejected), protocol echo (a response without it = stale serve → loud degradation). The connection handler processes exactly ONE request per connection (trailing bytes mid-await never double-process a line or double-log a delivery); the client clamps a too-big request below the message cap by dropping the advisory `priorContextText` BEFORE any conversation turn. Delivery seams: `onDelivered` (resolve kind) and `onTurnContextDelivered` (turn_context kind) both fire ONLY after the response write succeeds — a block abandoned before the serve responded is never counted (serve's callback logs the delivered block's volunteered pages + pointers to `context_volunteer_events` under the request channel); write-accept still isn't proof of injection (the client can trim/drop after receipt), which is why the `volunteer_channels` doctor check reconciles counts against the hook heartbeat. v1 clients and servers interoperate untouched. Serve-delegated sync rides the same socket as three additive secret-gated kinds (`sync_start`/`sync_status`/`sync_abort`, wire shapes + fail-closed option validation in `src/core/context/sync-ipc.ts`): start+poll, one line per connection, O(1) handlers with no server budget race; a pre-delegation serve answers `unknown_kind:*` without the protocol echo and the client degrades to the typed stale-serve refusal.- `src/core/facts/visibility.ts` — `resolveDefaultVisibility(engine)` / `resolveVisibilityParam`: the ONE resolver behind all four facts-visibility default sites (`facts.default_visibility` config key; explicit caller value always wins; invalid values fail closed to private). Bootstrap sets the workspace brain's default to `world` so the principal's own sessions can recall their facts — a documented, security-relevant knob. NOTE the deliberate asymmetry with the ambient-writeback TEMPLATE resolver (writeback-config.ts below): this READ/extract default fail-closes UNSET to private; write GUIDANCE treats unset as world (the `remember` verb's own default) because telling agents to write private-by-default on a default install makes their facts invisible to their own later remote sessions.- **Ambient memory writeback cluster** (opt-in, `memory.auto_writeback = off|salient|all`, default off; guide `docs/guides/ambient-writeback.md`):diff --git a/docs/architecture/key-files/core-services-1.md b/docs/architecture/key-files/core-services-1.mdindex 812f222c59..cb748ca53a 100644--- a/docs/architecture/key-files/core-services-1.md+++ b/docs/architecture/key-files/core-services-1.md@@ -31,7 +31,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/budget/cap-flag.ts` — the one USD cost-cap flag parser (D19): `parseCapFlag(flag, raw, { zero })` returns `{ flag, usd }` (`usd: null` for `off`/`unlimited`/`none`) or throws `CapFlagError`; a bare `0` is refused unless the command declares it (`zero: 'off'` for skillopt's legacy `--max-cost-usd 0`, `'cap'` for eval longmemeval's $0 judge cap); `mergeCapFlag` refuses two disagreeing cap flags; `capNotice` renders the one `cap: $X (source; how to remove)` line. Used by brainstorm/lsd, skillopt, enrich, onboard and eval longmemeval. Pinned by `test/budget/cap-flag.test.ts`.- `src/core/budget/no-pricing.ts` — the one `no_pricing` refusal builder. `noPricingGuidance(model, kind)` returns the structured fields (`code`, `model`, `provider`, `kind`, `units`, `lookup`, `register_command`, `register_scope: 'local_cli'`, `docs` = the `ERROR_CATALOGUE.no_pricing` anchor); `noPricingMessage` renders the one-line cause plus `noPricingSteps` (look up the provider's price, run the `gbrain pricing set` command on the brain host, retry; remote MCP callers ask the operator); `pricingSetCommand` gives the command alone for warnings (chat: `--input`/`--output`, other kinds: `--rate`), rendered from `pricingSetArgv`; `noPricingFix(guidance, transport)` is the agent-contract `fix` for a user-cap refusal (the registration argv with `inputs` for each rate and the pricing page). Used by BudgetTracker, enrich, conversation facts (CLI and cycle phase), skillopt receipts, the embedding migration authorization and the extract-atoms, budget-meter, embed-backfill and conversation-budget warnings. Pinned by `test/budget/no-pricing-registration.test.ts`.-- `src/core/chronicle/{contract,eligibility,config,reasons,ledger,ledger-stats,execute,publish,event-identity,invite-projection,backfill,campaign,job,upgrade-notice,extract-events,ontology,narrative}.ts` + `src/core/cycle/chronicle.ts` + `src/eval/chronicle/harness.ts` + `src/commands/eval-chronicle.ts` — Life Chronicle: the temporal spine. `contract.ts` holds the ledger columns, the extractor version (part of the ledger key: a bump makes extracted content new to discovery and backfill), the phase bounds and the phase result details. `reasons.ts` is the one reason table (`CHRONICLE_REASONS`: stage, meaning, stored fix Action with argv/preview_argv/consent/actor, never a stored `next`; `auto_chronicle_off` has no fix because it is off by choice) and builds the `chronicle_backstop` receipt field (`{pending:'next_cycle', daily_remaining}` or `{skipped, stage, why, fix}`, omitted for pages that are not chronicle-shaped); `docs/guides/life-chronicle.md` renders its table from it. `eligibility.isChronicleEligible` is the one eligibility function (meeting/conversation/calendar-event + directory rescue; diary and event pages NEVER eligible — privacy + anti-loop); with a time policy it also applies the invite end (`not_yet_happened`), the recency window on the page's own date (an authored `effective_date`, else frontmatter `date`/`start`; a `fallback` date counts as undated) and the settle window. `config.ts` owns the switch and knobs: `autoChronicleSetting` reads `auto_chronicle` as on when unset, on/off for true/false words, and `invalid` (off) for any other word; `chronicleSettings` reads `chronicle.job_budget_usd`/`auto_daily_limit`/`auto_recent_days`/`auto_settle_seconds`/`judge_max_tokens`/`max_events_per_page` (#5329, default 25) with ranges (`CHRONICLE_NUMERIC_KEYS`, enforced by `config set`; a malformed stored row falls back and is listed in `invalid`) and `chronicle.activated_at` (stamped by the first write decision or phase run; earlier revisions are history); `autoChronicleNeedsAcknowledgement` is true while on and `chronicle.default_on_acknowledged` is unset (stamped by `config set auto_chronicle`). The opt-out is `gbrain config set auto_chronicle false` everywhere. `ledger.ts` owns `chronicle_page_state` (one row per source/page/content hash/extractor version: state, reason, trigger, deciding writer and request, `no_extract`, attempts, `next_attempt_at`, cost/unpriced, event slugs and hashes): `recordChronicleDecision` runs inside every coordinated publication that imports a page (from `queuePublicationEffects`), applies the shared writer-confinement predicate, `--no-extract`, the opt-out and eligibility, and puts `chronicle_backstop` on the outcome through `reasons.ts`; `reserveChronicleSlot` is the rolling 24 h reservation under a transaction advisory lock. `ledger-stats.ts` rolls up the ledger and reservations for doctor and the advisor. `upgrade-notice.ts` is the one-shot post-upgrade notice (`chronicle.default_on_notice_shown`). The global `chronicle` cycle phase (`cycle/chronicle.ts`) supersedes rows whose content is no longer live, discovers pages changed since activation with no row (unmanaged brains decide there; managed ones record `no_write_decision`), and executes settled rows round-robin across sources (≤50 judged items and a wall-time bound per run; automatic rows only while `auto_chronicle` is on, backfill rows always); no chat provider → no calls; the extract_atoms cost gate refuses an explicit cap on an unpriced model. `execute.ts` runs one row: live-content check, time rules, the reservation (automatic rows; attempts count), the judge in a `chronicle:<trigger>` BudgetTracker scope with the per-page cap and an explicit post-call cap check, failure classes (chat_error/budget → failed with backoff, no provider/no_pricing → failed until config changes, refused → skipped, only a parsed `[]` is `no_events`). `invite-projection.ts` stands in for the judge on an ended calendar invite (slug under `calendar/`/`cal/` or type `calendar-event`, with a title, `start` and `end`): one `Scheduled: <title>` event (`kind: meeting`, `captured_via: life-chronicle:invite`, not proof of attendance) with no chat call, no daily reservation and zero cost, through the same publication and ledger path. `publish.ts` publishes one generation against the pinned depth snapshot: each event write re-validates the depth revision, content hash, source incarnation, privacy and the deciding writer's grant (events also read as private when their `event.depth` origin is private by field or declared lineage, or missing, `search/private-visibility.ts`) (`managed_maintenance_chronicle_event`/`_retire` intents on managed brains, one transaction per event otherwise), stamps the depth's visibility, never overwrites an operator-edited event (live hash not in the ledger) or resurrects an operator-deleted one, and retires the previous generation's owned events it did not reproduce (`retired_by: life-chronicle`; restored when produced again) only when the caller passes `replaces`: `execute.ts` and `runChronicleExtract` pass it for a complete judged generation (`extract-events.replacesPreviousGeneration`: at least one event, no proposal dropped by the date screen or the per-page cap, and a body no longer than the JUDGE_BODY_CHARS the judge reads; a segmented page's truth lead is read one character past it to tell) and for an ineligible revision's empty generation, so an empty or partial generation publishes what it has, retires nothing and still records its ledger outcome (#7013). `event-identity.ts` assigns final slugs before publication: events sharing a base slug `life/events/<day>-<hash8>` (who, what, depth) are told apart by instant, `where` and `kind`; one keeps the base slug and the rest get `-<hash6>` (identical copies `-2`…); assignment reads the pages already at the candidate slugs, so it is order-independent, keeps a page's existing slug across corrections and re-extractions, and a page extracted before disambiguation keeps its base slug. `extract-events.runChronicleExtract` is the direct-caller body over the same snapshot and publication path: deterministic when/who, injectable judge (default = chat gateway; output cap 4000 tokens by default, operator override `chronicle.judge_max_tokens`), an ALL-or-nothing parse barrier (`isValidProposal` requires a real parseable date), then `screenChronicleProposals` drops, never writes, each proposal without a day (`date_imprecise`: `when` is a year or month) or dated after the page's own day (`future_dated`: `chronicleEventCutoff` is the latest of the page's own date, a meeting's `end` and a conversation's last parsed message, as a day in `chronicle.tz`, capped at today), then keeps at most `chronicle.max_events_per_page` of the survivors in the judge's order (#5329, the rest `over_cap`, no model call to count); drops are counted in `events_dropped` (phase details, row outcome, direct result) and a page whose every proposal was dropped records the drop reason on its extracted ledger row instead of `no_events`; content-addressed `life/events/` pages + a `timeline_entries` projection. An unusable judge response is never recorded as `no_events`: truncation, unparseable output, a provider error and a refusal surface as `judge_truncated`/`judge_parse_failed`/`judge_chat_error`/`judge_refused`. `backfill.ts` (`chronicle_backfill`) queues `trigger='backfill'` ledger rows, exempt from the daily limit and recency (unless `--recent`), across types and rescue prefixes under one global `--limit`; `--since` is the update date, `--dated-since` the page date; a dry run reports `estimated_usd` and skip reasons; a live run needs `--yes`; content already extracted or queued is never re-queued, even after `gbrain jobs prune`. `--max-usd` (#6199, `campaign.ts`) is a queue-time bound: a page queues only while queued × (per-attempt cap + `chronicleCallCeilingUsd`) × max attempts fits, rows are stamped (`campaign_id`, `attempt_cap_usd`, `max_attempts`, `pricing_policy`, `campaign_max_usd`; migration `chronicle_campaign_stamps`) and `queueCampaignRow` never takes a row another backfill queued or an executor holds; an unpriced model under the cap refuses with `no_pricing`. Executors obey the stamp: `claimChronicleRow` consumes a campaign row's attempt with the lease and refuses it past `max_attempts`, the tracker uses the stamped cap, `finish` sums spend per attempt (`cost_attempts`, so a replay adds nothing) and applies the outcome only while its attempt is the latest (a stale completion is fenced), and `failExhaustedCampaignRows` fails a crashed row whose attempts are spent as `campaign_exhausted`; any other ledger write clears the stamp. `job.ts` drains `chronicle_extract` jobs from older releases through the same executor. `ontology.ts` carries the deterministic pieces of the bi-temporal per-entity ontology that RIDES THE `facts` TABLE (migration v122 adds `dimension`/`value`/`value_hash`/`dim_status`): `valueHash` (normalized, timestamp-free; the v188 dedup index adds the stint's `valid_from`, so a crash-retry conflicts while a same-provenance return to an earlier value records a new interval), `normalizeDimension` (seed alias lexicon), `isNovelDimension` (novel → quarantined, excluded from resolution/context until confirmed). The engine methods (`mergeOntologyFact` — corroborate on same value (noop when the same provenance already observed it during the current stint), forward-supersede via `valid_until`+`superseded_by` on a new value, backdated conflicts kept + flagged; `getOntology` with `--asof` valid-time travel; `discoverOntologyDimensions`; `findOntologyConflicts` — currently-open rows only) live in BOTH engines; both engines are on the R8 `valid_until` write allow-list (engine-layer, `dimension IS NOT NULL` rows only). Chronicle reads (`getTimelineForDate`/`getSince`/`getLastSeen`/`getOnThisDay`) JOIN the depth page (`deleted_at IS NULL`), hide soft-deleted event projections at READ time, and order by event `effective_date` for intra-day sequence. Ops: `chronicle_day`/`chronicle_since`/`chronicle_last_seen`/`chronicle_on_this_day`/`ontology_*`/`volunteer_chronicle` (agent orientation via `src/core/context/chronicle-context.ts`)/`chronicle_backfill` (admin, localOnly). Diary privacy: fail-closed for `ctx.remote !== false` callers — diary-sourced ontology + conflict values are redacted, the four timeline read ops (`chronicle_day`/`chronicle_since`/`chronicle_on_this_day` + `volunteer_chronicle`'s `recent_timeline`) drop rows whose depth page, event page, or `source` provenance lives under `life/diary/`, and `chronicle_last_seen` answers the never-seen shape (`last_date`/`last_event_slug`/`days_ago` all null) when the latest sighting is diary-sourced or a diary page is queried as the entity. Remote callers read only `visibility = 'world'` observations, like recall: `getOntology`/`findOntologyConflicts` take a `visibility` filter applied before resolution and the conflict HAVING. `ontology_propose` commits through `coordinatedDatabaseWrite` on a managed brain. Page visibility rides the same policy: `ontology_get`/`ontology_conflicts`/`volunteer_chronicle`'s ontologies resolve through `readPolicyOpts`, and both engines' `getOntology`/`findOntologyConflicts` apply `privateProvenanceFilterFragment` (an observation whose provenance page, looked up in the fact's own source, is `visibility: private` is dropped BEFORE per-dimension resolution and before the conflict HAVING, so an untrusted caller resolves the newest value they may see rather than a private value or a hole). The chronicle reads' event-page LEFT JOIN carries the caller's source scope in BOTH engines, so a scoped read can't surface another source's event pages through the join. Search: `applyChronicleTypeBoost` in `search/hybrid.ts` (bounded [1.0,1.25], fires only inside the `recency !== 'off'` post-fusion branch → non-temporal search bit-for-bit unchanged). Advisor collector `collect-chronicle.ts` (conflicts; coverage gap with a scoped `chronicle-backfill --since <date> --limit 50 --dry-run`; `auto_chronicle_default_on` ask_user until acknowledged; `auto_chronicle_invalid`; `chronicle_chat_unavailable`; `chronicle_extraction_failing`; `chronicle_daily_limit`); doctor `chronicle_projection_health` and `auto_chronicle` (`checks/auto-chronicle.ts`; BRAIN category). Eval: `gbrain eval chronicle` — deterministic, own in-memory PGLite, 6 gold tasks (day order, last-seen, supersession, asof, conflict, isolation), exit 0 iff 6/6. Tests: `test/chronicle-*.test.ts` (automatic path: `chronicle-auto-{decision,phase,unmanaged}`, `chronicle-date-quality`, `chronicle-event-privacy`, `chronicle-event-identity`, `chronicle-invite-projection`, `chronicle-backfill`, `chronicle-backfill-max-usd`, `chronicle-reasons-5876`, `chronicle-max-events-5329`; Postgres arms in `test/e2e/chronicle-*-postgres.test.ts`), `test/eval-chronicle.test.ts`, `test/auto-chronicle-surfaces-5876.test.ts`.+- `src/core/chronicle/{contract,eligibility,config,reasons,ledger,ledger-stats,execute,publish,event-identity,invite-projection,backfill,campaign,job,upgrade-notice,extract-events,proposal-diagnostics,ontology,narrative}.ts` + `src/core/cycle/chronicle.ts` + `src/eval/chronicle/harness.ts` + `src/commands/eval-chronicle.ts` — Life Chronicle: the temporal spine. `contract.ts` holds the ledger columns, the extractor version (part of the ledger key: a bump makes extracted content new to discovery and backfill), the phase bounds and the phase result details. `reasons.ts` is the one reason table (`CHRONICLE_REASONS`: stage, meaning, stored fix Action with argv/preview_argv/consent/actor, never a stored `next`; `auto_chronicle_off` has no fix because it is off by choice) and builds the `chronicle_backstop` receipt field (`{pending:'next_cycle', daily_remaining}` or `{skipped, stage, why, fix}`, omitted for pages that are not chronicle-shaped); `docs/guides/life-chronicle.md` renders its table from it. `eligibility.isChronicleEligible` is the one eligibility function (meeting/conversation/calendar-event + directory rescue; diary and event pages NEVER eligible — privacy + anti-loop); with a time policy it also applies the invite end (`not_yet_happened`), the recency window on the page's own date (an authored `effective_date`, else frontmatter `date`/`start`; a `fallback` date counts as undated) and the settle window. `config.ts` owns the switch and knobs: `autoChronicleSetting` reads `auto_chronicle` as on when unset, on/off for true/false words, and `invalid` (off) for any other word; `chronicleSettings` reads `chronicle.job_budget_usd`/`auto_daily_limit`/`auto_recent_days`/`auto_settle_seconds`/`judge_max_tokens`/`max_events_per_page` (#5329, default 25) with ranges (`CHRONICLE_NUMERIC_KEYS`, enforced by `config set`; a malformed stored row falls back and is listed in `invalid`) and `chronicle.activated_at` (stamped by the first write decision or phase run; earlier revisions are history); `autoChronicleNeedsAcknowledgement` is true while on and `chronicle.default_on_acknowledged` is unset (stamped by `config set auto_chronicle`). The opt-out is `gbrain config set auto_chronicle false` everywhere. `ledger.ts` owns `chronicle_page_state` (one row per source/page/content hash/extractor version: state, reason, trigger, deciding writer and request, `no_extract`, attempts, `next_attempt_at`, cost/unpriced, event slugs and hashes): `recordChronicleDecision` runs inside every coordinated publication that imports a page (from `queuePublicationEffects`), applies the shared writer-confinement predicate, `--no-extract`, the opt-out and eligibility, and puts `chronicle_backstop` on the outcome through `reasons.ts`; `reserveChronicleSlot` is the rolling 24 h reservation under a transaction advisory lock. `ledger-stats.ts` rolls up the ledger and reservations for doctor and the advisor. `upgrade-notice.ts` is the one-shot post-upgrade notice (`chronicle.default_on_notice_shown`). The global `chronicle` cycle phase (`cycle/chronicle.ts`) supersedes rows whose content is no longer live, discovers pages changed since activation with no row (unmanaged brains decide there; managed ones record `no_write_decision`), and executes settled rows round-robin across sources (≤50 judged items and a wall-time bound per run; automatic rows only while `auto_chronicle` is on, backfill rows always); no chat provider → no calls; the extract_atoms cost gate refuses an explicit cap on an unpriced model. `execute.ts` runs one row: live-content check, time rules, the reservation (automatic rows; attempts count), the judge in a `chronicle:<trigger>` BudgetTracker scope with the per-page cap and an explicit post-call cap check, failure classes (chat_error/budget → failed with backoff, no provider/no_pricing → failed until config changes, refused → skipped, only a parsed `[]` is `no_events`). `invite-projection.ts` stands in for the judge on an ended calendar invite (slug under `calendar/`/`cal/` or type `calendar-event`, with a title, `start` and `end`): one `Scheduled: <title>` event (`kind: meeting`, `captured_via: life-chronicle:invite`, not proof of attendance) with no chat call, no daily reservation and zero cost, through the same publication and ledger path. `publish.ts` publishes one generation against the pinned depth snapshot: each event write re-validates the depth revision, content hash, source incarnation, privacy and the deciding writer's grant (events also read as private when their `event.depth` origin is private by field or declared lineage, or missing, `search/private-visibility.ts`) (`managed_maintenance_chronicle_event`/`_retire` intents on managed brains, one transaction per event otherwise), stamps the depth's visibility, never overwrites an operator-edited event (live hash not in the ledger) or resurrects an operator-deleted one, and retires the previous generation's owned events it did not reproduce (`retired_by: life-chronicle`; restored when produced again) only when the caller passes `replaces`: `execute.ts` and `runChronicleExtract` pass it for a complete judged generation (`extract-events.replacesPreviousGeneration`: at least one event, no proposal dropped by the date screen or the per-page cap, and a body no longer than the JUDGE_BODY_CHARS the judge reads; a segmented page's truth lead is read one character past it to tell) and for an ineligible revision's empty generation, so an empty or partial generation publishes what it has, retires nothing and still records its ledger outcome (#7013). `event-identity.ts` assigns final slugs before publication: events sharing a base slug `life/events/<day>-<hash8>` (who, what, depth) are told apart by instant, `where` and `kind`; one keeps the base slug and the rest get `-<hash6>` (identical copies `-2`…); assignment reads the pages already at the candidate slugs, so it is order-independent, keeps a page's existing slug across corrections and re-extractions, and a page extracted before disambiguation keeps its base slug. `extract-events.runChronicleExtract` is the direct-caller body over the same snapshot and publication path: deterministic when/who, injectable judge (default = chat gateway; output cap 4000 tokens by default, operator override `chronicle.judge_max_tokens`), an ALL-or-nothing parse barrier (`isValidProposal` requires a real parseable date; a refused batch carries `proposal-diagnostics.diagnoseMalformedProposals`: a fixed code, the schema field and JSON type found, and counts, never a value, from at most 50 proposals, 50 `who` entries and 256 characters per string, on the direct result's `malformed`, the row outcome and the phase's warning line), then `screenChronicleProposals` drops, never writes, each proposal without a day (`date_imprecise`: `when` is a year or month) or dated after the page's own day (`future_dated`: `chronicleEventCutoff` is the latest of the page's own date, a meeting's `end` and a conversation's last parsed message, as a day in `chronicle.tz`, capped at today), then keeps at most `chronicle.max_events_per_page` of the survivors in the judge's order (#5329, the rest `over_cap`, no model call to count); drops are counted in `events_dropped` (phase details, row outcome, direct result) and a page whose every proposal was dropped records the drop reason on its extracted ledger row instead of `no_events`; content-addressed `life/events/` pages + a `timeline_entries` projection. An unusable judge response is never recorded as `no_events`: truncation, unparseable output, a provider error and a refusal surface as `judge_truncated`/`judge_parse_failed`/`judge_chat_error`/`judge_refused`. `backfill.ts` (`chronicle_backfill`) queues `trigger='backfill'` ledger rows, exempt from the daily limit and recency (unless `--recent`), across types and rescue prefixes under one global `--limit`; `--since` is the update date, `--dated-since` the page date; a dry run reports `estimated_usd` and skip reasons; a live run needs `--yes`; content already extracted or queued is never re-queued, even after `gbrain jobs prune`. `--max-usd` (#6199, `campaign.ts`) is a queue-time bound: a page queues only while queued × (per-attempt cap + `chronicleCallCeilingUsd`) × max attempts fits, rows are stamped (`campaign_id`, `attempt_cap_usd`, `max_attempts`, `pricing_policy`, `campaign_max_usd`; migration `chronicle_campaign_stamps`) and `queueCampaignRow` never takes a row another backfill queued or an executor holds; an unpriced model under the cap refuses with `no_pricing`. Executors obey the stamp: `claimChronicleRow` consumes a campaign row's attempt with the lease and refuses it past `max_attempts`, the tracker uses the stamped cap, `finish` sums spend per attempt (`cost_attempts`, so a replay adds nothing) and applies the outcome only while its attempt is the latest (a stale completion is fenced), and `failExhaustedCampaignRows` fails a crashed row whose attempts are spent as `campaign_exhausted`; any other ledger write clears the stamp. `job.ts` drains `chronicle_extract` jobs from older releases through the same executor. `ontology.ts` carries the deterministic pieces of the bi-temporal per-entity ontology that RIDES THE `facts` TABLE (migration v122 adds `dimension`/`value`/`value_hash`/`dim_status`): `valueHash` (normalized, timestamp-free; the v188 dedup index adds the stint's `valid_from`, so a crash-retry conflicts while a same-provenance return to an earlier value records a new interval), `normalizeDimension` (seed alias lexicon), `isNovelDimension` (novel → quarantined, excluded from resolution/context until confirmed). The engine methods (`mergeOntologyFact` — corroborate on same value (noop when the same provenance already observed it during the current stint), forward-supersede via `valid_until`+`superseded_by` on a new value, backdated conflicts kept + flagged; `getOntology` with `--asof` valid-time travel; `discoverOntologyDimensions`; `findOntologyConflicts` — currently-open rows only) live in BOTH engines; both engines are on the R8 `valid_until` write allow-list (engine-layer, `dimension IS NOT NULL` rows only). Chronicle reads (`getTimelineForDate`/`getSince`/`getLastSeen`/`getOnThisDay`) JOIN the depth page (`deleted_at IS NULL`), hide soft-deleted event projections at READ time, and order by event `effective_date` for intra-day sequence. Ops: `chronicle_day`/`chronicle_since`/`chronicle_last_seen`/`chronicle_on_this_day`/`ontology_*`/`volunteer_chronicle` (agent orientation via `src/core/context/chronicle-context.ts`)/`chronicle_backfill` (admin, localOnly). Diary privacy: fail-closed for `ctx.remote !== false` callers — diary-sourced ontology + conflict values are redacted, the four timeline read ops (`chronicle_day`/`chronicle_since`/`chronicle_on_this_day` + `volunteer_chronicle`'s `recent_timeline`) drop rows whose depth page, event page, or `source` provenance lives under `life/diary/`, and `chronicle_last_seen` answers the never-seen shape (`last_date`/`last_event_slug`/`days_ago` all null) when the latest sighting is diary-sourced or a diary page is queried as the entity. Remote callers read only `visibility = 'world'` observations, like recall: `getOntology`/`findOntologyConflicts` take a `visibility` filter applied before resolution and the conflict HAVING. `ontology_propose` commits through `coordinatedDatabaseWrite` on a managed brain. Page visibility rides the same policy: `ontology_get`/`ontology_conflicts`/`volunteer_chronicle`'s ontologies resolve through `readPolicyOpts`, and both engines' `getOntology`/`findOntologyConflicts` apply `privateProvenanceFilterFragment` (an observation whose provenance page, looked up in the fact's own source, is `visibility: private` is dropped BEFORE per-dimension resolution and before the conflict HAVING, so an untrusted caller resolves the newest value they may see rather than a private value or a hole). The chronicle reads' event-page LEFT JOIN carries the caller's source scope in BOTH engines, so a scoped read can't surface another source's event pages through the join. Search: `applyChronicleTypeBoost` in `search/hybrid.ts` (bounded [1.0,1.25], fires only inside the `recency !== 'off'` post-fusion branch → non-temporal search bit-for-bit unchanged). Advisor collector `collect-chronicle.ts` (conflicts; coverage gap with a scoped `chronicle-backfill --since <date> --limit 50 --dry-run`; `auto_chronicle_default_on` ask_user until acknowledged; `auto_chronicle_invalid`; `chronicle_chat_unavailable`; `chronicle_extraction_failing`; `chronicle_daily_limit`); doctor `chronicle_projection_health` and `auto_chronicle` (`checks/auto-chronicle.ts`; BRAIN category). Eval: `gbrain eval chronicle` — deterministic, own in-memory PGLite, 6 gold tasks (day order, last-seen, supersession, asof, conflict, isolation), exit 0 iff 6/6. Tests: `test/chronicle-*.test.ts` (automatic path: `chronicle-auto-{decision,phase,unmanaged}`, `chronicle-date-quality`, `chronicle-event-privacy`, `chronicle-event-identity`, `chronicle-invite-projection`, `chronicle-backfill`, `chronicle-backfill-max-usd`, `chronicle-reasons-5876`, `chronicle-max-events-5329`; Postgres arms in `test/e2e/chronicle-*-postgres.test.ts`), `test/eval-chronicle.test.ts`, `test/auto-chronicle-surfaces-5876.test.ts`.- `src/core/chunkers/` — markdown chunking (`recursive.ts`) and code chunking. `code.ts` is a tree-sitter-based semantic chunker for 30 languages (plus SQL via DerekStride/tree-sitter-sql) with embedded-asset WASMs (`src/assets/wasm/`), `@dqbd/tiktoken` cl100k_base tokenizer, small-sibling merging. `CHUNKER_VERSION` is folded into `importCodeFile`'s `content_hash` so chunker shape changes force clean re-chunks across releases; `GRAMMAR_REVISIONS` (per-language chunker revisions: `lua: 1` after the tree-sitter-grammars v0.3.0 swap that ended the `gbrain serve` Lua-fence hang; `typescript`/`tsx`/`javascript`/`python`/`ruby: 1` for the #5001 `__module__` chunks) folds into that language's hash only, and `chunkerStamp()` (`8;lua=1;typescript=1;…`) is the `sources.chunker_version` gate value every sync path reads and writes, so a per-language change walks each source once and re-imports only that language's files while the cost gate (`grammarOnlyDrift`, `grammar_drift`) prices those files alone. Top-level statements that contain a call (`describe(...)`, `app.use(...)`, `print(f())`, Ruby `RSpec.describe ... do`) are chunked through `code-module-chunks.ts` (below) so their call edges have a chunk to hang on. Grammar provenance and the vendoring scripts: `src/assets/wasm/README.md`; pinned by `test/chunkers/code-lua.test.ts`. `extractSymbolName` has an inline SQL branch (`extractSqlSymbolName`) diving through DerekStride's `statement` wrapper into the inner DDL child (`create_table`/`create_function`/`create_view`/`create_index`/`create_procedure`/`create_type`/`create_schema`/`create_database`/`create_trigger`/`alter_table`/`alter_view`) and extracting the target identifier via the `name` field with identifier-shaped fallback; DML kinds (`select`/`insert`/`update`/`delete`/`merge`/`with`) deliberately return null so chunks emit unnamed (code-def is a DDL signal). `normalizeSymbolType` has parallel SQL branches mapping `create_table → 'table'`, `create_view → 'view'`, etc. `DEF_TYPES` (owned by `src/core/chunkers/def-types.ts`, re-exported by `src/commands/code-def.ts` — see that entry) carries the SQL kinds (`'table' | 'view' | 'index' | 'procedure' | 'schema' | 'database' | 'trigger'`) so the new chunks surface in `gbrain code-def <name>` queries.diff --git a/docs/architecture/key-files/mcp.md b/docs/architecture/key-files/mcp.mdindex 11a648c181..5b758dc080 100644--- a/docs/architecture/key-files/mcp.md+++ b/docs/architecture/key-files/mcp.md@@ -3,7 +3,7 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `src/mcp/dispatch.ts` — shared tool-call dispatch consumed by both stdio (`server.ts`) and HTTP transports. Exports `dispatchToolCall(engine, name, params, opts)` (a read op (`mutating === false`) runs inside `withRequestConfigSnapshot`, a write op under `withoutRequestConfigSnapshot`; `src/core/config-snapshot.ts`), `buildOperationContext(engine, params, opts)`, and re-exports `normalizeOptionalParams`/`validateParams` from `src/mcp/validate-params.ts` (the validation module — call order normalize → validate → findUnknownParams is load-bearing). Single source of truth for `(ctx, params)` handler arg order and the `OperationContext` shape. Defaults `remote: true` (untrusted); local CLI callers pass `remote: false`. Deny layers, in order: `opts.allowedOps` surface enforcement (hidden op → `unknownToolEnvelope`, byte-identical to a nonexistent op; did-you-mean candidates drawn ONLY from the caller's visible surface minus localOnly minus gated names), unknown op, the localOnly transport backstop (`op.localOnly && transport !== 'stdio'` → same envelope; stdio IS the local surface), param validation, strict/warn unknown-arg handling (reject mode returns `invalid_params` with suggestions; warn mode attaches `_meta.warnings` + a model-visible notice block), then `enforceBoundClientOpAllowList` (the bound-client fence) inside the handler try. `_meta` assembly per docs/protocol/MCP_META_CHANNELS.md: handler-emitted keys via `ctx.emitResponseMeta` (retrieval, warnings) attach first and independently of the `metaHook` (`brain_hot_memory`, built by `src/core/facts/meta-hook.ts` — its 30s cache is keyed by ENGINE IDENTITY + source + visibility tier + session + allow-list hash, so a process hosting multiple engines can never serve one brain's cached facts into another's envelope; each entry's deadline is additionally CLAMPED to the earliest retained `valid_until`, so a fact expiring inside the window never outlives its read-time TTL by cache staleness; every mutating op, successful or not, drops the engine's entries via `invalidateHotMemoryForEngine`, a build that raced it is not stored, each hit revalidates the source's `fact_withdrawals` watermark so a forget from any process is never served, the key folds the effective read eligibility and each hit revalidates the trust policy generation (`src/core/eligibility/generation.ts`, migration v230: deferred triggers bump `trust_policy_state` on tier changes, quarantine transitions, read floor and `trust.%` config changes, purges and `needs_rederive`), read before the rows; an unreadable generation delivers nothing; facts read through the `hot_memory` proactive eligibility and `partitionForActivation`, carry `trust_tier` and `origin`, and the payload's `suppressed` counts what activation control withheld), each producer isolated so one failure never drops another's key; A successful result's content[0] is compact `JSON.stringify(result)` (error envelopes stay indented); `opts.resultRows` threads the transport's row-shape choice into `OperationContext.resultRows`. empty retrieval results get a SECOND model-visible content block via `buildEmptyRetrievalBlock`. `retrievalNoticeBlocks` caps the saved-facts block at 1,500 characters and the other-names block at 400 (header included) with whole items only: the first item always shows, later items that would cross the ceiling are counted in a `(+N more…)` marker (pinned by `test/mcp-notice-ceilings.test.ts`). Exports `isListLevelDenialEnvelope(parsed)` — the honest-catalog metric classifier: true for op-level denials the tools/list filter should have prevented (`detail: 'config_key=...'` publish-gate backstop, `detail: 'fence=op'` fence op-level deny), false for argument-level denials; serve-http logs matches as `status='denied_after_list'`. Exports `requestLogStatusForResult(result)` — the ONE request-log status decision (`success` / `success_with_warnings` / `accepted_pending` (a `write_pending` with an admitted non-terminal receipt, kept out of the admin error rate; `acceptedPendingReceipt` returns its receipt so serve-http logs the opaque `write_request_id`) / `denied_after_list` / `error`); BOTH HTTP transports (serve-http.ts and the legacy-bearer http-transport.ts) route every tools/call row through it so the honest-catalog metric sees all HTTP traffic (pinned by test/denied-after-list.test.ts + test/http-transport.test.ts). Also exports `summarizeMcpParams(opName, params)` — privacy-preserving redactor for `mcp_request_log` and the admin SSE feed, returns `{redacted, kind, declared_keys, unknown_key_count, approx_bytes}`. Intersects submitted top-level keys against the operation's declared `params` allow-list (declared keys preserved sorted; unknown keys counted but never named, closing the attacker-controlled-key-name leak). Byte counts bucketed up to nearest 1KB so an attacker can't binary-search secret-content sizes by probing. Raw payload visibility is opt-in via `gbrain serve --http --log-full-params` (loud stderr warning). Logging paths route through this helper, not `JSON.stringify(params)`. Agent contract v1: every failure (unknown tool, source guard, validation, strict params, missing source scope, handler throws) goes through `errorResult` → `toAgentError` → exactly one content block; handlers emit advice through `ctx.emitNotice` and the empty-retrieval, unknown-param and backup-coverage blocks ride that channel (prefixed `[gbrain notice <code> kind=<kind>]` blocks + `_meta.gbrain_notices`), filtered by the notice ledger (`opts.noticeLedger` on HTTP). `dispatchRenderContext` binds `isCallable` for fixes; `unknownToolEnvelope(name, opts, 'unknown_operation')` keeps serve-http's frozen value; `localCallErrorEnvelope` is `gbrain call`'s envelope. `sessionSafetyNotices` adds the one-time `behavior_changes` disclosure (stdio: once per brain; HTTP: once per authenticated client, remote view) and, on stdio only, the queued `chat_fallback_hop` notice, on success and failure results alike. `requestMetaSessionId(request.params)` is the one reader of the request-level `_meta.session_id` (beside `arguments`); stdio (`server.ts`) and HTTP (`serve-http-mcp.ts`) both pass it as `opts.sessionId`, which wins over an arguments-level `_meta` and is clamped to `SESSION_ID_MAX_CHARS` (256). Caches keyed on it stay bounded: the hot-memory cache at `HOT_MEMORY_CACHE_MAX_ENTRIES` (1000) and the facts queue's per-session counter, deleted at zero. `retrievalNoticeBlocks` also appends the rate line for a rateable answer (`_meta.retrieval.answer_id` with `feedback.rateable`): `Rate after use: rate_answer { answer_id, rating: 1-5 }`, or the fuller wording when `how_to_rate` fired, capped at `RATE_LINE_MAX_CHARS` = 160 (#6192; `test/mcp-feedback-visible-answer-id.test.ts`). Large pages: after a read's result is assembled (notices and `_meta` included), `frameOverCap` measures the final encoded frame against the connection's cap and replaces an oversized read with `result_too_large` (writes are never replaced); `DispatchOpts.thinClient` (from `X-Gbrain-Client` on both HTTP transports) reaches `OperationContext.thinClient`, a default-body-mode hint, never authority.+- `src/mcp/dispatch.ts` — shared tool-call dispatch consumed by both stdio (`server.ts`) and HTTP transports. Exports `dispatchToolCall(engine, name, params, opts)` (a read op (`mutating === false`) runs inside `withRequestConfigSnapshot`, a write op under `withoutRequestConfigSnapshot`; `src/core/config-snapshot.ts`), `buildOperationContext(engine, params, opts)`, and re-exports `normalizeOptionalParams`/`validateParams` from `src/mcp/validate-params.ts` (the validation module — call order normalize → validate → findUnknownParams is load-bearing). Single source of truth for `(ctx, params)` handler arg order and the `OperationContext` shape. Defaults `remote: true` (untrusted); local CLI callers pass `remote: false`. Deny layers, in order: `opts.allowedOps` surface enforcement (hidden op → `unknownToolEnvelope`, byte-identical to a nonexistent op; did-you-mean candidates drawn ONLY from the caller's visible surface minus localOnly minus gated names), unknown op, the localOnly transport backstop (`op.localOnly && transport !== 'stdio'` → same envelope; stdio IS the local surface), param validation, strict/warn unknown-arg handling (reject mode returns `invalid_params` with suggestions; warn mode attaches `_meta.warnings` + a model-visible notice block), then `enforceBoundClientOpAllowList` (the bound-client fence) inside the handler try. `_meta` assembly per docs/protocol/MCP_META_CHANNELS.md: handler-emitted keys via `ctx.emitResponseMeta` (retrieval, warnings) attach first and independently of the `metaHook` (`brain_hot_memory`, built by `src/core/facts/meta-hook.ts` — its 30s cache is keyed by ENGINE IDENTITY + source + visibility tier + session + allow-list hash + eligibility + the `sessionOnly` scope (a session with no facts of its own falls back to the source's newest 24h facts unless the caller passes `sessionOnly`, which the IPC handlers do when `context.hot_memory.session_only` is on; MCP callers never pass it), so a process hosting multiple engines can never serve one brain's cached facts into another's envelope; each entry's deadline is additionally CLAMPED to the earliest retained `valid_until`, so a fact expiring inside the window never outlives its read-time TTL by cache staleness; every mutating op, successful or not, drops the engine's entries via `invalidateHotMemoryForEngine`, a build that raced it is not stored, each hit revalidates the source's `fact_withdrawals` watermark so a forget from any process is never served, the key folds the effective read eligibility and each hit revalidates the trust policy generation (`src/core/eligibility/generation.ts`, migration v230: deferred triggers bump `trust_policy_state` on tier changes, quarantine transitions, read floor and `trust.%` config changes, purges and `needs_rederive`), read before the rows; an unreadable generation delivers nothing; facts read through the `hot_memory` proactive eligibility and `partitionForActivation`, carry `trust_tier` and `origin`, and the payload's `suppressed` counts what activation control withheld), each producer isolated so one failure never drops another's key; A successful result's content[0] is compact `JSON.stringify(result)` (error envelopes stay indented); `opts.resultRows` threads the transport's row-shape choice into `OperationContext.resultRows`. empty retrieval results get a SECOND model-visible content block via `buildEmptyRetrievalBlock`. `retrievalNoticeBlocks` caps the saved-facts block at 1,500 characters and the other-names block at 400 (header included) with whole items only: the first item always shows, later items that would cross the ceiling are counted in a `(+N more…)` marker (pinned by `test/mcp-notice-ceilings.test.ts`). Exports `isListLevelDenialEnvelope(parsed)` — the honest-catalog metric classifier: true for op-level denials the tools/list filter should have prevented (`detail: 'config_key=...'` publish-gate backstop, `detail: 'fence=op'` fence op-level deny), false for argument-level denials; serve-http logs matches as `status='denied_after_list'`. Exports `requestLogStatusForResult(result)` — the ONE request-log status decision (`success` / `success_with_warnings` / `accepted_pending` (a `write_pending` with an admitted non-terminal receipt, kept out of the admin error rate; `acceptedPendingReceipt` returns its receipt so serve-http logs the opaque `write_request_id`) / `denied_after_list` / `error`); BOTH HTTP transports (serve-http.ts and the legacy-bearer http-transport.ts) route every tools/call row through it so the honest-catalog metric sees all HTTP traffic (pinned by test/denied-after-list.test.ts + test/http-transport.test.ts). Also exports `summarizeMcpParams(opName, params)` — privacy-preserving redactor for `mcp_request_log` and the admin SSE feed, returns `{redacted, kind, declared_keys, unknown_key_count, approx_bytes}`. Intersects submitted top-level keys against the operation's declared `params` allow-list (declared keys preserved sorted; unknown keys counted but never named, closing the attacker-controlled-key-name leak). Byte counts bucketed up to nearest 1KB so an attacker can't binary-search secret-content sizes by probing. Raw payload visibility is opt-in via `gbrain serve --http --log-full-params` (loud stderr warning). Logging paths route through this helper, not `JSON.stringify(params)`. Agent contract v1: every failure (unknown tool, source guard, validation, strict params, missing source scope, handler throws) goes through `errorResult` → `toAgentError` → exactly one content block; handlers emit advice through `ctx.emitNotice` and the empty-retrieval, unknown-param and backup-coverage blocks ride that channel (prefixed `[gbrain notice <code> kind=<kind>]` blocks + `_meta.gbrain_notices`), filtered by the notice ledger (`opts.noticeLedger` on HTTP). `dispatchRenderContext` binds `isCallable` for fixes; `unknownToolEnvelope(name, opts, 'unknown_operation')` keeps serve-http's frozen value; `localCallErrorEnvelope` is `gbrain call`'s envelope. `sessionSafetyNotices` adds the one-time `behavior_changes` disclosure (stdio: once per brain; HTTP: once per authenticated client, remote view) and, on stdio only, the queued `chat_fallback_hop` notice, on success and failure results alike. `requestMetaSessionId(request.params)` is the one reader of the request-level `_meta.session_id` (beside `arguments`); stdio (`server.ts`) and HTTP (`serve-http-mcp.ts`) both pass it as `opts.sessionId`, which wins over an arguments-level `_meta` and is clamped to `SESSION_ID_MAX_CHARS` (256). Caches keyed on it stay bounded: the hot-memory cache at `HOT_MEMORY_CACHE_MAX_ENTRIES` (1000) and the facts queue's per-session counter, deleted at zero. `retrievalNoticeBlocks` also appends the rate line for a rateable answer (`_meta.retrieval.answer_id` with `feedback.rateable`): `Rate after use: rate_answer { answer_id, rating: 1-5 }`, or the fuller wording when `how_to_rate` fired, capped at `RATE_LINE_MAX_CHARS` = 160 (#6192; `test/mcp-feedback-visible-answer-id.test.ts`). Large pages: after a read's result is assembled (notices and `_meta` included), `frameOverCap` measures the final encoded frame against the connection's cap and replaces an oversized read with `result_too_large` (writes are never replaced); `DispatchOpts.thinClient` (from `X-Gbrain-Client` on both HTTP transports) reaches `OperationContext.thinClient`, a default-body-mode hint, never authority.- `src/core/egress-budget.ts` — the per-connection result cap: `resultByteCap` (Infinity for the trusted local CLI; else `mcp.max_result_bytes_stdio` 4 MiB / `mcp.max_result_bytes_http` 1 MiB, DB plane then file plane, clamped to 256 KiB–9 MiB), `encodedFrameBytes` (the complete JSON-RPC frame plus a framing reserve), and the dispatcher backstop pair `frameOverCap` / `resultTooLargeError`.- `src/mcp/instructions.ts` — canonical MCP initialize-time agent operating contract, compile-time source text (no runtime filesystem dependency) shared by the stdio SDK server, the OAuth HTTP SDK server and the legacy raw HTTP initialize path. `buildMcpInstructions({writeback?, tools?})` GENERATES the contract from the caller's callable set (`tools.callable`, the tools/list predicate): a clause naming a tool (search/query/get_page, skills catalog, put_page, whoami, join/sync skills, put/delete skill, the memory loop's `context_pack`/`volunteer_context`/`remember`/`forget`) appears only when that tool is listed, so every tool named is in that surface's tools/list (`test/mcp-initialize-instructions.test.ts`). When callable tools are left out of the listed set (`hiddenCallable`) and `request_tools` is callable, the hidden-tool sentence leads the contract, inside the 2,048 characters capped harnesses read (D1). It always carries the error protocol (follow `fix.next`, then `fix.verify`) and the notice prefix, then the optional status-only line (F4), the opt-in ambient-writeback section (`src/core/facts/writeback-instructions.ts`) and the readiness tail (top two `missing`/`degraded` gaps among embeddings, chat_llm, migrations, worker — never a by-choice state). With no `tools` and no writeback it equals `GBRAIN_MCP_INSTRUCTIONS` (the every-tool rendering bootstrap writes to GBRAIN-INSTRUCTIONS.md). `resolveMcpInstructions(config, env?, opts)` appends the operator-set deployment identity LAST under `Deployment identity:` (`GBRAIN_MCP_INSTRUCTIONS` env when non-blank, else file-plane `mcp.instructions`). `installInstructionsResolver(server, compute)` swaps the SDK Server's initialize handler so the stdio and OAuth servers compute the contract (callable set + readiness tail via `src/mcp/initialize-context.ts`) when the client initializes; the constructor value stays the fallback on a throw. The legacy bearer transport builds it inline per initialize. Transport tests compare against the contract for that connection's own tools/list (`test/helpers/instructions-parity.ts`): `test/serve-stdio-roundtrip.test.ts`, `test/http-transport.test.ts`, `test/connect-bearer.test.ts`, `test/mcp-instructions-writeback.test.ts`; identity composition in `test/mcp-server-identity.test.ts` + `test/config-set-mcp-instructions.test.ts`. #6170: `contractClauses(c, writeback)` puts the short `Ambient writeback is ON (<mode>)` line (with `visibility "private"` under a private posture) in the memory clause when writeback is on, follows the data-not-instructions clause with the shortened error protocol and moves the forget caveat after the scope clause, so the writeback line, `Follow \`fix.next\``, `[gbrain notice`, `context_pack`, `put_page REPLACES` and `Writing:` end inside the first 2,048 characters on every surface (pinned per surface × mode × extract_facts × visibility in `test/mcp-initialize-instructions.test.ts`); the full writeback section stays appended last. Cat 40's measured "Answering from the brain" clause is verbatim; the change needs the D12 Cat 40 smoke before merge. The brief clause puts the `referenced_by` walk on the single-name `entity` card and names only the fields compact `names` rows carry on the brain (`references: {namesRow, records}`, read at every per-initialize call site by `readInstructionContent` from `src/core/entity-references-config.ts`; the static contract is the defaults rendering; `test/mcp-instructions-references.test.ts`). Instruction 7's governing rule (`mcp.instructions_governing_rule`: `in_effect` default, `newest` the earlier recency sentence) leads the answering clause so it ends inside the first 2,048 characters (`test/mcp-instructions-governing-rule.test.ts` records its offset per surface).@@ -14,7 +14,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/mcp/result-rows.ts` — the transport side of the `search`/`query` row shape. `resolveResultRowsMode(engine, config)`: dual-plane `mcp.result_rows` (DB > file > 'lean'; a failed DB read falls to the file plane). `resultRowsForRequest(header, hostMode)`: the `X-Gbrain-Client` header naming `gbrain-remote-cli` (sent by `src/core/mcp-client.ts`) selects full rows, otherwise the host mode. The OAuth HTTP transport resolves both per request, the legacy bearer transport per tools/call, and stdio once at start (file plane only when the engine is degraded). The header is unverified and selects a row shape only; it must never gate anything security-relevant. Pinned by `test/mcp-result-rows-skew.test.ts`.-- `src/mcp/resolve-ipc-binding.ts` — shared resolve-IPC listener wiring for BOTH serve transports. `bindResolveIpcForServe(engine, defaultSource)` binds the retrieval-reflex `resolve`, `turn_context`, and `context_pack` kinds (on Postgres the socket is keyed by `hash12(database_url)` plus `hash12(source)` of the serve's bound source under `~/.gbrain/run`, and the legacy URL-only socket is also bound when free; hooks pick theirs with `hookResolveSocketForConfig` — own source first, legacy fallback; the secret stays URL-keyed and the persistence socket brain-keyed; the bound-source posture rejects requests naming any other source; pinned by `test/resolve-ipc-source-keyed.test.ts`) plus the serve-delegated sync (`sync_start`/`sync_status`/`sync_abort` → `src/core/serve-sync-runner.ts`) and maintenance-sweep (`sweep_start`/`sweep_status` → `src/core/serve-sweep-runner.ts`) kinds — each delegation family in its OWN try/catch, so a runner failure logs `[serve-sync]`/`[serve-sweep] handlers unavailable` and the core kinds still start; both families share the `GBRAIN_SERVE_SYNC_IPC=0` kill switch. Engine-uniform: Postgres brains listen too (the hook lane is engine-free by design, so IPC through a serve is its only DB path there). Best-effort by contract — a bind failure never blocks the serve, and a socket already owned by a live or unresponsive listener (another serve) is left to it (that serve is the IPC provider, #4896). Each socket the serve could not bind (its source socket, the legacy socket, also when only the persistence listener came up) is retried on its own unref'd timer (`RESOLVE_IPC_REBIND_INTERVAL_MS` = 30 s plus up to 5 s jitter, `rebindDelayMs` injectable) through the same `startResolveIpcServer`, so a surviving serve takes over once the owner probes dead and logs `[resolve-ipc] took over <path>`; bind attempts are serialized per serve, `close()` clears the timers and closes a bind that lands after it, and persistence is never re-set-up (#6647, pinned by `test/resolve-ipc-rebind.serial.test.ts`). Reflex-channel event logging fires at DELIVERY (`onDelivered`/`onTurnContextDelivered`), never inside the resolver. Pinned by `test/resolve-ipc-binding.test.ts`.+- `src/mcp/resolve-ipc-binding.ts` — shared resolve-IPC listener wiring for BOTH serve transports. `bindResolveIpcForServe(engine, defaultSource)` binds the retrieval-reflex `resolve`, `turn_context`, and `context_pack` kinds (on Postgres the socket is keyed by `hash12(database_url)` plus `hash12(source)` of the serve's bound source under `~/.gbrain/run`, and the legacy URL-only socket is also bound when free; hooks pick theirs with `hookResolveSocketForConfig` — own source first, legacy fallback; the secret stays URL-keyed and the persistence socket brain-keyed; the bound-source posture rejects requests naming any other source; pinned by `test/resolve-ipc-source-keyed.test.ts`) plus the serve-delegated sync (`sync_start`/`sync_status`/`sync_abort` → `src/core/serve-sync-runner.ts`) and maintenance-sweep (`sweep_start`/`sweep_status` → `src/core/serve-sweep-runner.ts`) kinds — each delegation family in its OWN try/catch, so a runner failure logs `[serve-sync]`/`[serve-sweep] handlers unavailable` and the core kinds still start; both families share the `GBRAIN_SERVE_SYNC_IPC=0` kill switch. Engine-uniform: Postgres brains listen too (the hook lane is engine-free by design, so IPC through a serve is its only DB path there). Best-effort by contract — a bind failure never blocks the serve, and a socket already owned by a live or unresponsive listener (another serve) is left to it (that serve is the IPC provider, #4896). Each socket the serve could not bind (its source socket, the legacy socket, also when only the persistence listener came up) is retried on its own unref'd timer (`RESOLVE_IPC_REBIND_INTERVAL_MS` = 30 s plus up to 5 s jitter, `rebindDelayMs` injectable) through the same `startResolveIpcServer`, so a surviving serve takes over once the owner probes dead and logs `[resolve-ipc] took over <path>`; bind attempts are serialized per serve, `close()` clears the timers and closes a bind that lands after it, and persistence is never re-set-up (#6647, pinned by `test/resolve-ipc-rebind.serial.test.ts`). Reflex-channel event logging fires at DELIVERY (`onDelivered`/`onTurnContextDelivered`), never inside the resolver. `turn_context` and `context_pack` (`context-pack-handler.ts`) read `context.hot_memory.session_only` per request (`readHotMemorySessionOnly`) and pass it as `sessionOnly` to the assembler (pinned by `test/hot-memory-session-only-7026.test.ts`). Pinned by `test/resolve-ipc-binding.test.ts`.- `src/mcp/server.ts` — MCP stdio server. initialize and tools/list are built from `OPERATION_MANIFEST` (`src/core/operation-manifest.generated.ts`, every op minus its handler) so the handler graph behind `src/core/operations.ts` stays unloaded until it is needed; byte-identity with the eager registry across surfaces, strict params, read-only access, publish gates and the advertised surface is pinned by `test/mcp-tool-list-snapshot.test.ts`. Engine-dependent boot (`bootEngineDependents`: source scope, persistence consumer, resolve-IPC bind, startup sweep) and the dispatch/hot-memory imports wait for the handshake (`deferredBoot`, boot phase `initialize_wait`): they start when the first tools/list is answered, `BOOT_LIST_GRACE_MS` after initialize with no tools/list in flight, or `BOOT_WITHOUT_INITIALIZE_MS` after connect for a client that never initializes. Every tools/call and skill resource read awaits that boot, and a boot failure rejects them with the boot error while `startMcpServer` still rejects with it. Status-only mode (F4, `src/mcp/status-mode.ts`): over a status engine it lists only `gbrain_status`, answers other tools with one `serve_status_only` block, and every tool call re-probes and may recover in place (then `tools/list_changed`). `gbrain://capabilities` carries readiness[], the probed worker status (`stdioCapabilityReadiness`), and `surface`/`surface_source`. One `StdioSurfaceState` (`createStdioSurfaceState` in `surface.ts`) per process is the allow-set tools/list, dispatch (`allowedOps`, `stdioSurface`), skill resources and `gbrain_status` read; `request_tools {surface}` widens it for the session (stderr `surface_widened` audit line, then `tools/list_changed`), and `mcp.allow_session_widen` is resolved at boot. An ignored `GBRAIN_SURFACE` (`invalidSurfaceEnv`) adds one `surface_env_invalid` notice to the first successful tool result. After the engine boots it starts the onboarding cache (`startOnboardingRefresher` from `src/core/onboard/mcp-onboarding.ts`) with an idle gate on the in-flight RPC counter. `startMcpServer`'s optional `onBootPhase` reports each boot phase (`source_preflight` … `startup_sweep`) so `serve`'s boot-deadline line can name the one that never finished. Its SDK `Server` is initialized with the shared contract from `src/mcp/instructions.ts`, so a real client's `getInstructions()` is populated during the initialize handshake. `createDefaultWriteAdvisory(engine, {enabled, write?})` is the stdio lane's once-per-process unscoped-default-write advisory: on a mutating call whose source resolved to tier `seed_default` it runs `assessUnscopedDefaultWrite` (`src/core/source-resolver.ts`) and prints the warning to stderr; it latches on the first SUCCESSFUL assessment whatever the verdict (the aggregate is expensive and its inputs are process-stable), never latches on a failed one (fail-open for that write; the next mutating seed_default call retries), coalesces concurrent calls onto one in-flight assessment, and never blocks a write (a throwing writer still counts as assessed). Non-mutating calls and non-seed tiers return early without latching. Tool-call handler delegates to `dispatchToolCall` from `src/mcp/dispatch.ts` so stdio + HTTP transports share one validation, context-build, and error-format path. Stdin `'end'` / `'close'` shutdown hooks are skipped when `process.env.MCP_STDIO === '1'` — gateway-piped stdio MCP wrappers (OpenClaw's `bundle-mcp`) pipe the handshake then close their stdin half, which would otherwise kill the server before the first tool call; signal handlers (SIGTERM/SIGINT/SIGHUP) + the parent-process watchdog still cover legitimate disconnects. `src/commands/serve.ts` exposes `ServeOptions.mcpStdio?: boolean` as a test seam so the guard is exercisable without process.env mutation. The resolve-IPC listener (retrieval-reflex resolve / turn_context / context_pack + the serve-delegated sync and sweep kinds) binds through `src/mcp/resolve-ipc-binding.ts` (next entry) on BOTH serve transports — stdio here and `gbrain serve --http`; the shutdown chain awaits `shutdownDelegatedSync()` before `engine.disconnect()`. Pinned by `test/serve-stdio-lifecycle.test.ts` and `test/serve-stdio-roundtrip.test.ts`.diff --git a/docs/guides/ambient-writeback.md b/docs/guides/ambient-writeback.mdindex 6e3615c6b3..8e491234a1 100644--- a/docs/guides/ambient-writeback.md+++ b/docs/guides/ambient-writeback.md@@ -371,6 +371,28 @@ active set on the first read after the migration (facts-health counts stepaccordingly). Nothing is deleted or mutated; the doctor's`validity_lapsed_facts` count sizes the shift.+## Hot memory and other sessions++Hot memory (the recent facts the turn hook and the session-start pack inject)+reads the current session's own facts first. A session with no facts of its+own gets the source's newest facts from the last 24 hours instead, and those+can come from other sessions. To keep each session to its own facts, turn on+`context.hot_memory.session_only` (DB plane, off by default):++```bash+gbrain config set context.hot_memory.session_only true+```++**Say to your agent:** *"Only show me facts from this session in hot memory."*+Your agent runs the command above.++The serve reads the key on every `turn_context` and `context_pack` request, so+the change applies on the next turn without a restart. With it on, a session+with no facts of its own, or a request with no session id, gets no hot facts;+entity cards, volunteered pages and `recall` are unchanged, and so is the+`_meta.brain_hot_memory` block on MCP tool calls. `gbrain config unset+context.hot_memory.session_only` restores the fallback.+## Privacy and visibility- **What the assistant said** is saved as its own fact, never as yours. Thediff --git a/docs/guides/life-chronicle.md b/docs/guides/life-chronicle.mdindex 614506d689..7f555a951c 100644--- a/docs/guides/life-chronicle.md+++ b/docs/guides/life-chronicle.md@@ -277,6 +277,19 @@ brackets are filled in with real values on each surface.| `no_chat_provider` | phase | No chat provider is configured on the brain host, so the chronicle phase made no calls. | — | user | credentials |<!-- chronicle-reasons:end -->+A `malformed_proposal` refusal also says which check failed, without the+proposal itself. The chronicle phase prints one warning line per refused page+(`code=when_unparseable field=when; proposal 2 of 7; 1 of 7 inspected invalid`),+and the extractor result carries the same fields under `malformed`: `code`+(`not_object`, `missing_field`, `wrong_type`, `when_too_short`,+`when_unparseable`, `what_blank`, `who_item_not_string`, or `beyond_bounds`+when the defect lies past what was inspected), the schema `field`, the JSON+`shape` found there, and counts. It never contains a value, a key the model+invented, the prompt or the raw response. At most 50 proposals, 50 `who`+entries each and 256 characters per string are inspected, and nested values+are never walked. The refusal itself, its retry with backoff and the ledger+row are unchanged.+Don't hand-write `life/events/` pages: extraction owns them and retires eventsthe page no longer supports. Edit the meeting page instead. Only a completere-extraction retires events: one that finds no events, drops or caps adiff --git a/docs/guides/push-context.md b/docs/guides/push-context.mdindex 2eaea84f40..1bdf5e0641 100644--- a/docs/guides/push-context.md+++ b/docs/guides/push-context.md@@ -210,6 +210,7 @@ used?"* — your agent runs `gbrain volunteer-context --stats`.| `retrieval_reflex_volunteer` | true | the reflex volunteer arm (Arm 2) — the incident kill switch for volunteered pages on the OpenClaw lane (env: `GBRAIN_RETRIEVAL_REFLEX_VOLUNTEER`, env above config) || `retrieval_reflex_max_pointers` | 3 | pointer cap per turn || `retrieval_reflex_lexical_arms` | true | the lowercase-alias + surname recall arms (env: `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS`); off = disables both arms |+| `context.hot_memory.session_only` | off | hot facts on the turn and session-start hooks come from the current session only, with no fallback to other sessions' recent facts (DB-plane; see [ambient writeback](ambient-writeback.md#hot-memory-and-other-sessions)) || `context.proactive_brief` | off | the proactive brief ("Before you start") on the SessionStart and UserPromptSubmit hooks (DB-plane: `gbrain config set context.proactive_brief true`) |Per-call knobs: `max_pages` + `min_confidence` on both the op and `gbrain watch`diff --git a/llms-full.txt b/llms-full.txtindex f568860bf9..ccd425f18f 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -8527,6 +8527,7 @@ used?"* — your agent runs `gbrain volunteer-context --stats`.| `retrieval_reflex_volunteer` | true | the reflex volunteer arm (Arm 2) — the incident kill switch for volunteered pages on the OpenClaw lane (env: `GBRAIN_RETRIEVAL_REFLEX_VOLUNTEER`, env above config) || `retrieval_reflex_max_pointers` | 3 | pointer cap per turn || `retrieval_reflex_lexical_arms` | true | the lowercase-alias + surname recall arms (env: `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS`); off = disables both arms |+| `context.hot_memory.session_only` | off | hot facts on the turn and session-start hooks come from the current session only, with no fallback to other sessions' recent facts (DB-plane; see [ambient writeback](ambient-writeback.md#hot-memory-and-other-sessions)) || `context.proactive_brief` | off | the proactive brief ("Before you start") on the SessionStart and UserPromptSubmit hooks (DB-plane: `gbrain config set context.proactive_brief true`) |Per-call knobs: `max_pages` + `min_confidence` on both the op and `gbrain watch`diff --git a/scripts/postgres-arm-weights.json b/scripts/postgres-arm-weights.jsonindex 870d273886..9297f63509 100644--- a/scripts/postgres-arm-weights.json+++ b/scripts/postgres-arm-weights.json@@ -23,6 +23,7 @@"test/capture-consent-admission.test.ts": 6155,"test/capture-dispatch-provenance-6524.test.ts": 7080,"test/chronicle-backfill-max-usd.test.ts": 5122,+ "test/chronicle-malformed-diagnostics-7234.test.ts": 12000,"test/claim-fifo-foreground-waiting.test.ts": 5269,"test/claim-lease-holder-only-6712.test.ts": 5143,"test/claude-cli-output-cap.test.ts": 4568,@@ -72,6 +73,7 @@"test/harness-skills-epoch.test.ts": 4703,"test/held-read-signals.test.ts": 8640,"test/hold-action-chain-6712.test.ts": 27253,+ "test/hot-memory-session-only-7026.test.ts": 9000,"test/import-file-result-callback-gbra130.test.ts": 7418,"test/import-frontmatter-key-order-5158.test.ts": 4924,"test/import-inline-chunk-keep.test.ts": 5735,diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 6a45e54727..73480bd13c 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1085,6 +1085,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.348.0', text: 'A `gbrain jobs work` worker running two or more jobs at once (the supervisor and autopilot default is 2) now keeps one slot free of long jobs: autopilot-cycle, autopilot-global-maintenance, embed-backfill, connector-sync, extract and doctor-refresh run in at most concurrency minus one slots, so short jobs such as facts-absorb no longer wait behind them. Long jobs can take longer to start when one is already running. `gbrain config set minions.short_job_reserved_slots 0` restores the old behavior; `minions.long_job_names` adds job names to the long set.' },// #7263 (a background doctor refresh held a one-job worker for up to 2 h).{ since: '0.60.348.0', text: 'The background `doctor-refresh` job now queues behind sync, the autopilot cycles, global maintenance, embed backfill and loops extract (priority 10), and measures for at most 10 minutes: past that it starts no further check, records what it finished and completes, and the rest stays unknown until the next hourly refresh. Its timeout drops from 2 hours to 15 minutes. `gbrain config set doctor.background_refresh false` stops doctor from queueing it.' },+ // GBRA-60 small-items wave (#7026 part 2, #7234). `since` is stamped at the merge slot.+ { since: 'TBD', text: 'New opt-in `context.hot_memory.session_only`, off by default (#7026): with `gbrain config set context.hot_memory.session_only true`, the hot facts the turn hook and the session-start pack inject come from the current session only, so a session with no facts of its own gets none instead of the source\'s newest facts from the last 24 hours, which can belong to other sessions. MCP `_meta.brain_hot_memory` is unchanged.' },+ { since: 'TBD', text: 'When the chronicle phase refuses a judge answer as `malformed_proposal`, it now prints one warning line naming the check that failed (a fixed code such as `when_unparseable`, the field, the JSON type found there and counts, never a value), and the direct extractor result carries the same fields under `malformed` (#7234). The refusal, its retry with backoff and the ledger row are unchanged.' },// #7023 (GBRA-60). `since` is restamped at the merge slot.{ since: 'TBD', text: 'The per-prompt context block now renders each hot-memory fact the same way the session-start pack does: a fact the assistant said keeps its `(assistant said)` prefix instead of reading as your own claim, and a fact injected once in a session is not injected again on later prompts, whatever its trust label or speaker. Before, assistant-attributed and external (`<external-data>`) facts came back on every prompt; a session already open when you upgrade sees each assistant fact once more (#7023, reported by @benswinney).' },// #7026 (GBRA-60). `since` is restamped at the merge slot.diff --git a/src/core/chronicle/execute.ts b/src/core/chronicle/execute.tsindex d7797e1d73..4227e44b2b 100644--- a/src/core/chronicle/execute.ts+++ b/src/core/chronicle/execute.ts@@ -39,6 +39,7 @@ import { endedInviteProposal, markInviteEvents } from './invite-projection.ts';import { RETIRE_REASONS, reserveChronicleSlot } from './ledger.ts';import { CAMPAIGN_PRICING_POLICY, rowMaxAttempts } from './campaign.ts';import { pinDepth, publishChronicleGeneration, type ChronicleDepthPin } from './publish.ts';+import { describeMalformedProposals, diagnoseMalformedProposals, type MalformedProposalDiagnostics } from './proposal-diagnostics.ts';export interface ChronicleExecContext {engine: BrainEngine;@@ -59,7 +60,9 @@ export type ChronicleRowOutcome =| { kind: 'waiting'; reason: string }| { kind: 'deferred'; reason: 'daily_limit' }| { kind: 'done'; state: ChronicleLedgerRow['state']; reason: string | null; judged: boolean;- written: number; retired: number; costUsd: number | null; unpriced: boolean; dropped: ChronicleDropCounts };+ written: number; retired: number; costUsd: number | null; unpriced: boolean; dropped: ChronicleDropCounts;+ /** #7234: which check refused a `malformed_proposal` batch (fixed codes and counts, never values). */+ malformed?: MalformedProposalDiagnostics };const CONFIG_BLOCKED = new Set(['judge_llm_unavailable', 'no_pricing']);const LEASE_MS = 15 * 60_000;@@ -134,8 +137,10 @@ function propagateSpend(parent: BudgetTracker | null, child: BudgetTracker): voi}}+type JudgeFailure = { state: 'failed' | 'skipped'; reason: ChronicleReasonCode; malformed?: MalformedProposalDiagnostics };+/** Classify a judge result or throw into the ledger vocabulary (E2/D5). */-function classifyJudge(result: ChronicleJudgeResult | null, thrown: unknown): { state: 'failed' | 'skipped'; reason: ChronicleReasonCode } | null {+function classifyJudge(result: ChronicleJudgeResult | null, thrown: unknown): JudgeFailure | null {if (thrown) {const budget = thrown as { tag?: string; reason?: string };if (budget.tag === 'BUDGET_EXHAUSTED') return { state: 'failed', reason: budget.reason === 'no_pricing' ? 'no_pricing' : 'budget_exhausted' };@@ -150,7 +155,7 @@ function classifyJudge(result: ChronicleJudgeResult | null, thrown: unknown): {case 'parse_failed': return { state: 'failed', reason: 'judge_parse_failed' };}const events = Array.isArray(result?.events) ? result!.events : [];- if (!events.every(isValidProposal)) return { state: 'failed', reason: 'malformed_proposal' };+ if (!events.every(isValidProposal)) return { state: 'failed', reason: 'malformed_proposal', malformed: diagnoseMalformedProposals(events) };return null;}@@ -240,11 +245,13 @@ export async function executeChronicleRow(ctx: ChronicleExecContext, row: Chroni// E4: gateway accounting defers a breach to the next reservation; check the cap explicitly.const overCap = tracker.cap !== undefined && tracker.totalSpent > tracker.cap;- const failure = overCap && !thrown ? { state: 'failed' as const, reason: 'budget_exhausted' as const } : classifyJudge(result, thrown);+ const failure: JudgeFailure | null = overCap && !thrown ? { state: 'failed', reason: 'budget_exhausted' } : classifyJudge(result, thrown);if (failure) {const next = failure.state === 'skipped' || CONFIG_BLOCKED.has(failure.reason) ? null : backoff(attempts, now, maxAttempts);await finish(engine, row, attempts, { state: failure.state, reason: failure.reason, nextAttemptAt: next, ...spend });- return done(failure.state, failure.reason, judged);+ if (!failure.malformed) return done(failure.state, failure.reason, judged);+ console.warn(`[chronicle] ${row.slug}: the judge's events failed validation (malformed_proposal: ${describeMalformedProposals(failure.malformed)}); nothing was written${next ? ' and the row retries with backoff' : ''}.`);+ return done(failure.state, failure.reason, { ...judged, malformed: failure.malformed });}const proposals = result?.events ?? [];diff --git a/src/core/chronicle/extract-events.ts b/src/core/chronicle/extract-events.tsindex 2d5837b107..f41562d1cb 100644--- a/src/core/chronicle/extract-events.ts+++ b/src/core/chronicle/extract-events.ts@@ -17,6 +17,7 @@ import { isSegmentedPage } from '../page-body/page-shape.ts';import { chroniclePageDate } from './eligibility.ts';import { chronicleSettings } from './config.ts';import { buildChronicleEvent, pinDepth, publishChronicleGeneration, type BuiltChronicleEvent } from './publish.ts';+import { diagnoseMalformedProposals, type MalformedProposalDiagnostics } from './proposal-diagnostics.ts';export interface ChronicleEventProposal {when: string; // ISO datetime or YYYY-MM-DD@@ -68,6 +69,8 @@ export interface ChronicleExtractResult {events_retired?: number;/** Proposals refused before publication, by reason. */events_dropped?: ChronicleDropCounts;+ /** #7234: on `malformed_proposal`, which check refused the batch (fixed codes and counts, never values). */+ malformed?: MalformedProposalDiagnostics;}const KIND_VOCAB = new Set([@@ -284,7 +287,7 @@ export async function runChronicleExtract(const proposals = Array.isArray(result?.events) ? result.events : [];// PARSE BARRIER — reject the WHOLE batch on any malformed proposal; no partial writes.if (!proposals.every(isValidProposal)) {- return { slug: opts.slug, status: 'skipped', events_written: 0, reason: 'malformed_proposal' };+ return { slug: opts.slug, status: 'skipped', events_written: 0, reason: 'malformed_proposal', malformed: diagnoseMalformedProposals(proposals) };}const pin = pinDepth(snapshot);const built = buildChronicleEvents(proposals, ctx, { slug: pin.slug, visibility: pin.visibility, contentHash: pin.contentHash },diff --git a/src/core/chronicle/proposal-diagnostics.ts b/src/core/chronicle/proposal-diagnostics.tsnew file mode 100644index 0000000000..269fe89385--- /dev/null+++ b/src/core/chronicle/proposal-diagnostics.ts@@ -0,0 +1,121 @@+/**+ * #7234: bounded diagnostics for a `malformed_proposal` refusal.+ *+ * The parse barrier (`isValidProposal`) rejects a judge response whose events+ * fail validation, and the refusal alone does not say which check failed.+ * `diagnoseMalformedProposals` names it with a fixed reason code, the required+ * field it concerns (from the proposal schema, never a key read from the+ * input) and the JSON type found there, plus counts. It never copies a value,+ * a key the judge invented, the prompt or the raw response, so the result is+ * safe to log and to return.+ *+ * Inspection is bounded and flat: at most MAX_INSPECTED_PROPOSALS proposals,+ * MAX_INSPECTED_WHO_ITEMS `who` entries each, and strings are read only up to+ * MAX_INSPECTED_CHARS; nested values are typed, never walked. A check past a+ * bound is skipped rather than guessed, so every reported defect is one the+ * barrier also rejects; a proposal whose defect lies past every bound is left+ * out of `invalid`, and when no defect is found at all the code is+ * `beyond_bounds`.+ */++export const MAX_INSPECTED_PROPOSALS = 50;+export const MAX_INSPECTED_WHO_ITEMS = 50;+export const MAX_INSPECTED_CHARS = 256;++export type MalformedProposalCode =+ | 'not_object'+ | 'missing_field'+ | 'wrong_type'+ | 'when_too_short'+ | 'when_unparseable'+ | 'what_blank'+ | 'who_item_not_string'+ | 'beyond_bounds';++export type ProposalField = 'when' | 'what' | 'who' | 'kind';+export type ValueShape = 'string' | 'number' | 'boolean' | 'null' | 'array' | 'object' | 'other';++interface Defect { code: Exclude<MalformedProposalCode, 'beyond_bounds'>; field?: ProposalField; shape?: ValueShape }++export interface MalformedProposalDiagnostics {+ /** The first defect found, or `beyond_bounds` when none was found within the bounds. */+ code: MalformedProposalCode;+ field?: ProposalField;+ /** The JSON type found at `field` (for `not_object`, the proposal's; for `who_item_not_string`, the entry's). */+ shape?: ValueShape;+ /** Zero-based position of the first defective proposal; absent with `beyond_bounds`. */+ index?: number;+ /** Proposals in the response. */+ events: number;+ /** Proposals inspected (at most MAX_INSPECTED_PROPOSALS). */+ inspected: number;+ /** Inspected proposals with a defect found. */+ invalid: number;+ /** Defects found, by code. */+ codes: Partial<Record<MalformedProposalCode, number>>;+}++function shapeOf(v: unknown): ValueShape {+ if (v === null) return 'null';+ if (Array.isArray(v)) return 'array';+ const t = typeof v;+ return t === 'string' || t === 'number' || t === 'boolean' || t === 'object' ? t : 'other';+}++function stringField(o: Record<string, unknown>, field: ProposalField): Defect | string {+ const v = o[field];+ if (v === undefined) return { code: 'missing_field', field };+ if (typeof v !== 'string') return { code: 'wrong_type', field, shape: shapeOf(v) };+ return v;+}++/** The first failing check of `isValidProposal`, in its order, within the bounds; null when none was found. */+function proposalDefect(e: unknown): Defect | null {+ if (!e || typeof e !== 'object' || Array.isArray(e)) return { code: 'not_object', shape: shapeOf(e) };+ const o = e as Record<string, unknown>;+ const when = stringField(o, 'when');+ if (typeof when !== 'string') return when;+ if (when.length < 4) return { code: 'when_too_short', field: 'when' };+ if (when.length <= MAX_INSPECTED_CHARS && Number.isNaN(new Date(when).getTime())) return { code: 'when_unparseable', field: 'when' };+ const what = stringField(o, 'what');+ if (typeof what !== 'string') return what;+ if (what.length <= MAX_INSPECTED_CHARS && what.trim().length === 0) return { code: 'what_blank', field: 'what' };+ const who = o.who;+ if (who === undefined) return { code: 'missing_field', field: 'who' };+ if (!Array.isArray(who)) return { code: 'wrong_type', field: 'who', shape: shapeOf(who) };+ const items = Math.min(who.length, MAX_INSPECTED_WHO_ITEMS);+ for (let i = 0; i < items; i++) {+ if (typeof who[i] !== 'string') return { code: 'who_item_not_string', field: 'who', shape: shapeOf(who[i]) };+ }+ const kind = stringField(o, 'kind');+ return typeof kind === 'string' ? null : kind;+}++export function diagnoseMalformedProposals(events: readonly unknown[]): MalformedProposalDiagnostics {+ const inspected = Math.min(events.length, MAX_INSPECTED_PROPOSALS);+ const codes: MalformedProposalDiagnostics['codes'] = {};+ let first: (Defect & { index: number }) | null = null;+ let invalid = 0;+ for (let i = 0; i < inspected; i++) {+ const defect = proposalDefect(events[i]);+ if (!defect) continue;+ invalid++;+ codes[defect.code] = (codes[defect.code] ?? 0) + 1;+ first ??= { ...defect, index: i };+ }+ if (!first) return { code: 'beyond_bounds', events: events.length, inspected, invalid, codes };+ return {+ code: first.code,+ ...(first.field ? { field: first.field } : {}),+ ...(first.shape ? { shape: first.shape } : {}),+ index: first.index, events: events.length, inspected, invalid, codes,+ };+}++/** One log clause built only from the fixed vocabulary and counts above. */+export function describeMalformedProposals(d: MalformedProposalDiagnostics): string {+ const where = d.index === undefined ? 'no defect within the inspection bounds' : `proposal ${d.index + 1} of ${d.events}`;+ const field = d.field ? ` field=${d.field}` : '';+ const shape = d.shape ? ` shape=${d.shape}` : '';+ return `code=${d.code}${field}${shape}; ${where}; ${d.invalid} of ${d.inspected} inspected invalid`;+}diff --git a/src/core/config-runtime-keys.ts b/src/core/config-runtime-keys.tsindex 26eff6323c..d218cccf6a 100644--- a/src/core/config-runtime-keys.ts+++ b/src/core/config-runtime-keys.ts@@ -16,5 +16,6 @@ export const RUNTIME_READER_CONFIG_KEYS: readonly string[] = ['skillopt.capture_enabled', // skillopt/held-out.ts production rollout capture, default off'entity_identity.union', // entity-identity.ts: links/backlinks union across identity co-members, default off'writer.lint_on_put_page', // output/post-write.ts lint after put_page, default off+ 'context.hot_memory.session_only', // facts/meta-hook.ts, read by the turn_context and context_pack IPC handlers: hot memory never falls back to other sessions' facts, default off'serve.cli_socket', // config.ts loadConfigWithEngine (snapshot only) → serve.ts: a Postgres serve answers CLI reads over a private Unix socket, default off];diff --git a/src/core/context/turn-context.ts b/src/core/context/turn-context.tsindex bdc7c693b5..73fe4f05fa 100644--- a/src/core/context/turn-context.ts+++ b/src/core/context/turn-context.ts@@ -228,6 +228,12 @@ export interface AssembleTurnContextOpts {priorContextText?: string;/** Opaque session identity — keys the hot-memory cache (CX2-11). */sessionId?: string;+ /**+ * `context.hot_memory.session_only`, read by the IPC handlers: hot facts+ * come from this session only, never from the source's newest 24h facts+ * when the session has none of its own.+ */+ sessionOnly?: boolean;maxBytes?: number;/** v0.46.15: lexical-arms kill switch — see ResolvePointersOpts.lexicalArms. */lexicalArms?: boolean;@@ -403,7 +409,7 @@ export async function assembleTurnContext(takesHoldersAllowList: ['world'],...(policy.floor ? { auth: { minTrust: policy.floor } as OperationContext['auth'] } : {}),};- const meta = await getBrainHotMemoryMeta('turn_context', metaCtx);+ const meta = await getBrainHotMemoryMeta('turn_context', metaCtx, { sessionOnly: opts.sessionOnly });const hot = meta?.brain_hot_memory as { facts?: TurnContextFact[]; suppressed?: SuppressionSummary } | undefined;withheldFacts += hot?.suppressed?.withheld ?? 0;const all = Array.isArray(hot?.facts) ? [...hot.facts] : [];@@ -578,7 +584,7 @@ async function fetchHotFacts(// #5575 CEO-18: the calling connection's floor keys and filters hot memory too....(floor ? { auth: { minTrust: floor } as OperationContext['auth'] } : {}),};- const meta = await getBrainHotMemoryMeta('turn_context', metaCtx);+ const meta = await getBrainHotMemoryMeta('turn_context', metaCtx, { sessionOnly: opts.sessionOnly });const hot = meta?.brain_hot_memory as { facts?: TurnContextFact[]; suppressed?: SuppressionSummary } | undefined;const facts = Array.isArray(hot?.facts) ? hot.facts.filter(f => !floor || admitsTrust(f.trust_tier ?? 'unknown', floor)) : [];return { facts, withheld: hot?.suppressed?.withheld ?? 0 };diff --git a/src/core/facts/meta-hook.ts b/src/core/facts/meta-hook.tsindex 3f23507c04..68b951844e 100644--- a/src/core/facts/meta-hook.ts+++ b/src/core/facts/meta-hook.ts@@ -25,13 +25,17 @@* `trust_tier` and `origin`. The payload's `suppressed` field counts what* activation control withheld, never its content (DX-10).* - Cap at top-K facts per response so the injection stays lean.+ * - A session with no facts of its own falls back to the source's newest+ * 24h facts unless the caller passes `sessionOnly` (the IPC handlers do+ * when `context.hot_memory.session_only` is on); the flag is part of the+ * cache key, so the two answers never share an entry.** Both stdio and HTTP MCP transports pass this hook into dispatchToolCall* so the felt-memory feature works on every transport.*/import type { OperationContext } from './../operations.ts';-import type { FactRow } from './../engine.ts';+import type { BrainEngine, FactRow } from './../engine.ts';import { effectiveConfidence } from './decay.ts';import { collapseHotFacts } from './capture-dedup.ts';import { proactiveEligibility } from '../eligibility/registry.ts';@@ -39,6 +43,7 @@ import { partitionForActivation, suppressionSummary } from '../eligibility/activimport { trustFields } from '../eligibility/labels.ts';import { eligibilityCacheField, readTrustGeneration } from '../eligibility/generation.ts';import { resolveExcludePrivatePages } from '../search/private-visibility.ts';+import { isConfigTruthy } from '../config.ts';const DEFAULT_TTL_MS = 30_000;const DEFAULT_TOP_K = 10;@@ -53,6 +58,14 @@ const DEFAULT_TOP_K = 10;*/export const HOT_MEMORY_CACHE_MAX_ENTRIES = 1000;+/** DB-plane, default false: hot memory never falls back to other sessions' facts. */+export const HOT_MEMORY_SESSION_ONLY_KEY = 'context.hot_memory.session_only';++/** The serve-side reading of `context.hot_memory.session_only`; an unreadable value keeps the default (false). */+export async function readHotMemorySessionOnly(engine: Pick<BrainEngine, 'getConfig'>): Promise<boolean> {+ return isConfigTruthy(await engine.getConfig(HOT_MEMORY_SESSION_ONLY_KEY).catch(() => null));+}+interface CacheEntry {expiresAt: number;payload: Record<string, unknown> | undefined;@@ -114,7 +127,7 @@ function cacheSet(key: string, entry: CacheEntry): void {export async function getBrainHotMemoryMeta(name: string,ctx: OperationContext,- opts: { topK?: number; ttlMs?: number } = {},+ opts: { topK?: number; ttlMs?: number; sessionOnly?: boolean } = {},): Promise<Record<string, unknown> | undefined> {// Don't inject on tool calls that themselves manipulate hot memory —// the agent doesn't need the brain's hot memory wrapped around its own@@ -149,6 +162,7 @@ export async function getBrainHotMemoryMeta(// — a cached entry from brain A served to brain B's caller is a cross-brain// fact leak through the cache, not through any query.const ttl = Math.max(1000, opts.ttlMs ?? DEFAULT_TTL_MS);+ const sessionOnly = opts.sessionOnly === true;const topK = Math.max(1, Math.min(opts.topK ?? DEFAULT_TOP_K, 25));// The watermark and the trust generation are read before the rows, so a@@ -167,7 +181,7 @@ export async function getBrainHotMemoryMeta(}// The effective eligibility is part of the key: two connections with// different floors never share an entry.- const cacheKey = `${engineCacheField(ctx.engine)}::${encodeCacheField(sourceId)}::${tier}::${encodeCacheField(sessionId ?? '_')}::${allowListHash}::${encodeCacheField(eligibilityCacheField(policy))}`;+ const cacheKey = `${engineCacheField(ctx.engine)}::${encodeCacheField(sourceId)}::${tier}::${encodeCacheField(sessionId ?? '_')}::${allowListHash}::${encodeCacheField(eligibilityCacheField(policy))}::${sessionOnly ? 'session-only' : 'fallback'}`;// Cache hit?const cached = _cache.get(cacheKey);@@ -198,8 +212,9 @@ export async function getBrainHotMemoryMeta(activeOnly: true, limit: topK * 3, visibility, excludePrivate, fingerprint: true, eligibility,});}- // If no session-scoped rows, fall back to recent across the source.- if (fetched.length === 0) {+ // If no session-scoped rows, fall back to recent across the source, unless+ // the caller asked for this session's facts only.+ if (fetched.length === 0 && !sessionOnly) {fetched = await ctx.engine.listFactsSince(sourceId, new Date(Date.now() - 24 * 60 * 60 * 1000), {activeOnly: true, limit: topK * 3, visibility, excludePrivate, fingerprint: true, eligibility,});@@ -271,7 +286,7 @@ export async function getBrainHotMemoryMeta(export function bumpHotMemoryCache(sourceId: string, sessionId: string | null): void {// Walk the cache and prune any entry matching this source+session// regardless of visibility tier, allow-list hash, OR engine — key layout is- // engine::encField(source)::tier::encField(session)::allowHash. Pruning+ // engine::encField(source)::tier::encField(session)::allowHash::eligibility::scope. Pruning// across engines is deliberate over-invalidation: a bump is a freshness// signal and a stale-drop on a sibling engine costs one rebuild, never a// leak. Components are ':'-encoded, so split('::') slices cleanly evendiff --git a/src/mcp/context-pack-handler.ts b/src/mcp/context-pack-handler.tsindex 4c8f8999f7..ba6134246b 100644--- a/src/mcp/context-pack-handler.ts+++ b/src/mcp/context-pack-handler.ts@@ -34,6 +34,7 @@ import { coreTrustIdentity } from '../core/context/openclaw-core.ts';import type { TurnContextResult } from '../core/context/turn-context.ts';import { attachBrief, briefEnabled, resetBriefLedger, sessionStartBrief, SESSION_BRIEF_CUTOFF_MS, withBriefDeadline } from '../core/context/proactive-brief.ts';import { proactiveEligibility } from '../core/eligibility/registry.ts';+import { readHotMemorySessionOnly } from '../core/facts/meta-hook.ts';/** Tighter entity-card fan-out on the PUSH path (eng 4A): the server budget* can't absorb the pull path's 8-card ceiling on a cold cache. */@@ -190,6 +191,7 @@ export function makeContextPackIpcHandler(sourceId: sessionSource,entities,sessionId: sessionId ?? undefined,+ sessionOnly: await readHotMemorySessionOnly(engine),since: state?.last_wake_at ?? undefined,maxEntities: PUSH_PACK_MAX_ENTITIES,deadlineMs: CONTEXT_PACK_SERVER_BUDGET_MS,diff --git a/src/mcp/resolve-ipc-binding.ts b/src/mcp/resolve-ipc-binding.tsindex e4f0f919be..90fd664483 100644--- a/src/mcp/resolve-ipc-binding.ts+++ b/src/mcp/resolve-ipc-binding.ts@@ -36,6 +36,7 @@ import { VOLUNTEER_MAX_PAGES_CAP } from '../core/context/volunteer.ts';import { assembleTurnContext, TURN_CONTEXT_DEFAULT_MAX_BYTES, type TurnContextResult } from '../core/context/turn-context.ts';import { attachBrief, briefEnabled, BRIEF_MAX_BYTES, recordBriefDelivered, turnBrief, TURN_BRIEF_CUTOFF_MS, withBriefDeadline } from '../core/context/proactive-brief.ts';import { proactiveEligibility } from '../core/eligibility/registry.ts';+import { readHotMemorySessionOnly } from '../core/facts/meta-hook.ts';import { makeContextPackIpcHandler } from './context-pack-handler.ts';import { logBriefDeliveryFireAndForget, logTurnContextDeliveryFireAndForget } from '../core/context/volunteer-events.ts';import { persistenceSocketPathForConfig, startPersistenceIpcServer, type PersistenceIpcProvider, type PersistenceIpcBinding } from '../core/persistence/ipc.ts';@@ -80,6 +81,7 @@ export async function turnContextWithBrief(engine: BrainEngine, sourceId: stringwindow: req.window ?? [],priorContextText: req.priorContextText,sessionId: req.sessionId,+ sessionOnly: await readHotMemorySessionOnly(engine),maxBytes: briefOn ? Math.max(1024, (req.maxBytes ?? TURN_CONTEXT_DEFAULT_MAX_BYTES) - BRIEF_MAX_BYTES - 2) : req.maxBytes,// Per-request config read: `gbrain serve` is long-running, and the// lexical-arms switch reverts a false-fire regression on the NEXT turndiff --git a/test/chronicle-malformed-diagnostics-7234.test.ts b/test/chronicle-malformed-diagnostics-7234.test.tsnew file mode 100644index 0000000000..eed1d47d81--- /dev/null+++ b/test/chronicle-malformed-diagnostics-7234.test.ts@@ -0,0 +1,198 @@+/**+ * #7234: a malformed_proposal refusal carries bounded, value-free diagnostics.+ *+ * The parse barrier rejects a judge batch with an invalid event and records+ * only "malformed_proposal". The refusal now also names which check failed: a+ * fixed reason code, the schema field it concerns, the JSON type found there+ * and counts, on the cycle outcome, the direct extractor result and the+ * phase's warning line. Never a value, a key the judge invented, the prompt or+ * the raw response. Inspection is bounded by proposal count, who entries and+ * string length, and never walks nested values. Refusal, ledger state,+ * retry/backoff and writes stay exactly as they were.+ *+ * Reported by @Masashi-Ono0611. The phase cases run on PGLite, and on Postgres+ * when DATABASE_URL is set.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { runPhaseChronicle } from '../src/core/cycle/chronicle.ts';+import { isValidProposal, runChronicleExtract, type ChronicleJudge } from '../src/core/chronicle/extract-events.ts';+import {+ diagnoseMalformedProposals,+ MAX_INSPECTED_CHARS,+ MAX_INSPECTED_PROPOSALS,+ MAX_INSPECTED_WHO_ITEMS,+} from '../src/core/chronicle/proposal-diagnostics.ts';+import { testBackends } from './helpers/test-backends.ts';+import { persistencePostgresTemplate } from './helpers/persistence-postgres.ts';++const today = new Date().toISOString().slice(0, 10);+const BODY = 'Alice and Bob reviewed the launch plan and agreed on the next steps for the beta. '.repeat(3);+const ok = { when: today, who: ['people/alice-example'], what: 'Alice agreed to ship the beta', kind: 'commitment' };+const SECRET = 'sk-live-7234' + 'Q9x'.repeat(12);+const SECRET_KEY = 'ghp_7234' + 'Zt4'.repeat(10);++describe('diagnoseMalformedProposals: fixed codes', () => {+ test.each([+ ['what missing', { when: today, who: [], kind: 'x' }, { code: 'missing_field', field: 'what' }],+ ['when a number', { ...ok, when: 20260618 }, { code: 'wrong_type', field: 'when', shape: 'number' }],+ ['when too short', { ...ok, when: '26' }, { code: 'when_too_short', field: 'when' }],+ ['when not a date', { ...ok, when: 'not-a-date' }, { code: 'when_unparseable', field: 'when' }],+ ['what blank', { ...ok, what: ' ' }, { code: 'what_blank', field: 'what' }],+ ['who a string', { ...ok, who: 'people/alice-example' }, { code: 'wrong_type', field: 'who', shape: 'string' }],+ ['who entry an object', { ...ok, who: ['people/alice-example', { slug: 'x' }] }, { code: 'who_item_not_string', field: 'who', shape: 'object' }],+ ['kind missing', { when: today, who: [], what: 'x' }, { code: 'missing_field', field: 'kind' }],+ ['kind null', { ...ok, kind: null }, { code: 'wrong_type', field: 'kind', shape: 'null' }],+ ['a string proposal', 'Alice agreed', { code: 'not_object', shape: 'string' }],+ ['a null proposal', null, { code: 'not_object', shape: 'null' }],+ ['an array proposal', [ok], { code: 'not_object', shape: 'array' }],+ ])('%s', (_name, proposal, expected) => {+ expect(isValidProposal(proposal)).toBe(false);+ expect<unknown>(diagnoseMalformedProposals([proposal])).toEqual({ ...expected, index: 0, events: 1, inspected: 1, invalid: 1, codes: { [expected.code]: 1 } });+ });++ test('the first defect leads; every defect is counted', () => {+ expect(diagnoseMalformedProposals([ok, { ...ok, what: undefined }, ok, { ...ok, when: 1 }, { ...ok, when: 2 }])).toEqual({+ code: 'missing_field', field: 'what', index: 1, events: 5, inspected: 5, invalid: 3, codes: { missing_field: 1, wrong_type: 2 },+ });+ });+});++describe('diagnoseMalformedProposals: no values, bounded inspection', () => {+ const poisoned = { [SECRET_KEY]: SECRET, when: SECRET, who: [SECRET], what: SECRET, where: SECRET, kind: SECRET };++ test('a secret-looking value or key never reaches the diagnostics', () => {+ const d = diagnoseMalformedProposals([poisoned]);+ expect(d).toMatchObject({ code: 'when_unparseable', field: 'when' });+ const text = JSON.stringify(d);+ expect(text).not.toContain(SECRET);+ expect(text).not.toContain(SECRET_KEY);+ });++ test('event count: at most MAX_INSPECTED_PROPOSALS are read', () => {+ const many = Array.from({ length: 10_000 }, () => ({ ...ok, kind: 7 }));+ expect(diagnoseMalformedProposals(many)).toMatchObject({ code: 'wrong_type', events: 10_000, inspected: MAX_INSPECTED_PROPOSALS, invalid: MAX_INSPECTED_PROPOSALS });+ // The barrier rejects a defect past the bound; the diagnostics say they did not reach it instead of guessing.+ const late = [...Array.from({ length: 10_000 }, () => ok), { ...ok, kind: 7 }];+ expect(late.every(isValidProposal)).toBe(false);+ expect(diagnoseMalformedProposals(late)).toEqual({ code: 'beyond_bounds', events: 10_001, inspected: MAX_INSPECTED_PROPOSALS, invalid: 0, codes: {} });+ });++ test('who entries: at most MAX_INSPECTED_WHO_ITEMS are read', () => {+ const who = (bad: number) => Array.from({ length: 100_000 }, (_, i) => (i === bad ? 7 : 'people/alice-example'));+ expect(diagnoseMalformedProposals([{ ...ok, who: who(MAX_INSPECTED_WHO_ITEMS - 1) }])).toMatchObject({ code: 'who_item_not_string', shape: 'number' });+ expect(diagnoseMalformedProposals([{ ...ok, who: who(MAX_INSPECTED_WHO_ITEMS) }])).toMatchObject({ code: 'beyond_bounds', invalid: 0 });+ });++ test('field size: a string past MAX_INSPECTED_CHARS is never parsed or trimmed', () => {+ const huge = 'x'.repeat(1_000_000);+ expect(isValidProposal({ ...ok, when: huge })).toBe(false);+ expect(diagnoseMalformedProposals([{ ...ok, when: huge }])).toMatchObject({ code: 'beyond_bounds' });+ expect(diagnoseMalformedProposals([{ ...ok, when: 'x'.repeat(MAX_INSPECTED_CHARS) }])).toMatchObject({ code: 'when_unparseable' });+ expect(diagnoseMalformedProposals([{ ...ok, what: ' '.repeat(MAX_INSPECTED_CHARS + 1) }])).toMatchObject({ code: 'beyond_bounds' });+ });++ test('deep input is typed, never walked', () => {+ let deep: unknown = SECRET;+ for (let i = 0; i < 100_000; i++) deep = [deep];+ // Deep enough that any recursive walk (JSON.stringify included) overflows the stack.+ expect(() => JSON.stringify(deep)).toThrow(RangeError);+ const d = diagnoseMalformedProposals([{ ...ok, who: [deep] }, { ...ok, what: { nested: deep } }]);+ expect(d).toMatchObject({ code: 'who_item_not_string', field: 'who', shape: 'array', invalid: 2, codes: { who_item_not_string: 1, wrong_type: 1 } });+ expect(JSON.stringify(d).length).toBeLessThan(400);+ });+});++describe('runChronicleExtract (direct callers)', () => {+ let engine: PGLiteEngine;+ beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);+ afterAll(async () => { await engine.disconnect(); });++ test('the refusal is unchanged and carries the diagnostics, never the values', async () => {+ await engine.putPage('meetings/direct', { type: 'meeting', title: 'Direct', compiled_truth: BODY, frontmatter: { date: today } });+ const r = await runChronicleExtract(engine, { slug: 'meetings/direct', judge: async () => ({ events: [ok, poisonedEvent()] as never }) });+ expect(r).toEqual({+ slug: 'meetings/direct', status: 'skipped', events_written: 0, reason: 'malformed_proposal',+ malformed: { code: 'when_unparseable', field: 'when', index: 1, events: 2, inspected: 2, invalid: 1, codes: { when_unparseable: 1 } },+ });+ expect(JSON.stringify(r)).not.toContain(SECRET);+ expect((await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM pages WHERE type='event'"))[0].n).toBe(0);+ });+});++function poisonedEvent() {+ return { [SECRET_KEY]: SECRET, when: SECRET, who: [SECRET], what: SECRET, kind: 'meeting' };+}++describe('the chronicle phase', () => {+ const backends = testBackends();+ let template: Awaited<ReturnType<typeof persistencePostgresTemplate>> | undefined;+ beforeAll(async () => {+ if (backends.includes('postgres')) template = await persistencePostgresTemplate(process.env.DATABASE_URL!);+ }, 120_000);+ afterAll(async () => { await template?.dispose(); });++ async function fresh(backend: string): Promise<{ engine: BrainEngine; close: () => Promise<void> }> {+ if (backend === 'postgres') return template!.clone();+ const engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ return { engine, close: () => engine.disconnect() };+ }++ async function capture<T>(run: () => Promise<T>): Promise<{ value: T; logged: string }> {+ const lines: string[] = [];+ const saved = { log: console.log, info: console.info, warn: console.warn, error: console.error };+ for (const m of ['log', 'info', 'warn', 'error'] as const) console[m] = (...args: unknown[]) => { lines.push(args.map(String).join(' ')); };+ try { return { value: await run(), logged: lines.join('\n') }; }+ finally { Object.assign(console, saved); }+ }++ const row = (engine: BrainEngine) => engine.executeRaw<{ state: string; reason: string | null; attempts: number; next_attempt_at: Date | string | null }>(+ 'SELECT state, reason, attempts, next_attempt_at FROM chronicle_page_state');+ const minutesUntil = (at: Date | string | null) => (new Date(at as string).getTime() - Date.now()) / 60_000;++ test('refusal, ledger, backoff and writes are unchanged; the outcome and log say which check failed', async () => {+ for (const backend of backends) {+ const { engine, close } = await fresh(backend);+ try {+ await engine.setConfig('chronicle.auto_settle_seconds', '0');+ await engine.setConfig('chronicle.activated_at', new Date(Date.now() - 1000).toISOString());+ await engine.putPage('meetings/sync', { type: 'meeting', title: 'Sync', compiled_truth: BODY, frontmatter: { date: today } });+ let calls = 0;+ const malformed: ChronicleJudge = async () => { calls++; return { events: [ok, poisonedEvent()] as never }; };++ const first = await capture(() => runPhaseChronicle(engine, { judge: malformed }));+ expect([backend, calls]).toEqual([backend, 1]);+ expect(first.value.details).toMatchObject({ judged: 1, failed: 1, extracted: 0, events_written: 0, reasons: { malformed_proposal: 1 } });+ const [r1] = await row(engine);+ expect([backend, r1.state, r1.reason, r1.attempts]).toEqual([backend, 'failed', 'malformed_proposal', 1]);+ expect(minutesUntil(r1.next_attempt_at)).toBeGreaterThan(4);+ expect(minutesUntil(r1.next_attempt_at)).toBeLessThanOrEqual(5);+ expect(first.logged).toContain('meetings/sync: the judge\'s events failed validation (malformed_proposal: code=when_unparseable field=when; proposal 2 of 2; 1 of 2 inspected invalid); nothing was written and the row retries with backoff.');+ for (const text of [first.logged, JSON.stringify(first.value), JSON.stringify(await row(engine))]) {+ expect(text).not.toContain(SECRET);+ expect(text).not.toContain(SECRET_KEY);+ }+ expect((await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM pages WHERE type='event'"))[0].n).toBe(0);++ // Not due yet: no call. Due again: the second attempt backs off twice as long.+ await runPhaseChronicle(engine, { judge: malformed });+ expect([backend, calls]).toEqual([backend, 1]);+ await engine.executeRaw("UPDATE chronicle_page_state SET next_attempt_at=now()-interval '1 second'");+ await capture(() => runPhaseChronicle(engine, { judge: malformed }));+ const [r2] = await row(engine);+ expect([backend, calls, r2.state, r2.reason, r2.attempts]).toEqual([backend, 2, 'failed', 'malformed_proposal', 2]);+ expect(minutesUntil(r2.next_attempt_at)).toBeGreaterThan(9);+ expect(minutesUntil(r2.next_attempt_at)).toBeLessThanOrEqual(10);++ // A valid answer on the next attempt writes as before.+ await engine.executeRaw("UPDATE chronicle_page_state SET next_attempt_at=now()-interval '1 second'");+ const last = await runPhaseChronicle(engine, { judge: async () => ({ events: [ok] }) });+ expect(last.details).toMatchObject({ extracted: 1, events_written: 1 });+ expect((await row(engine)).map((r) => [r.state, r.reason, r.attempts])).toEqual([['extracted', null, 3]]);+ } finally { await close(); }+ }+ }, 120_000);+});diff --git a/test/hot-memory-session-only-7026.test.ts b/test/hot-memory-session-only-7026.test.tsnew file mode 100644index 0000000000..e266d675f5--- /dev/null+++ b/test/hot-memory-session-only-7026.test.ts@@ -0,0 +1,157 @@+/**+ * #7026 part 2: `context.hot_memory.session_only` (DB plane, default false).+ *+ * Hot memory for a session with no facts of its own falls back to the+ * source's newest 24h facts, which can come from other sessions. With the key+ * on, the turn_context and context_pack IPC handlers ask for this session's+ * facts only, so such a session gets no hot facts at all. The flag is part of+ * the hot-memory cache key, so a fallback payload is never served to a+ * session-only read and the reverse.+ *+ * Runs on PGLite, and on Postgres when DATABASE_URL is set.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/operations.ts';+import type { GBrainConfig } from '../src/core/config.ts';+import { KNOWN_CONFIG_KEYS } from '../src/core/config.ts';+import { getBrainHotMemoryMeta, __resetHotMemoryCacheForTests } from '../src/core/facts/meta-hook.ts';+import { turnContextWithBrief } from '../src/mcp/resolve-ipc-binding.ts';+import { makeContextPackIpcHandler } from '../src/mcp/context-pack-handler.ts';+import { testBackends } from './helpers/test-backends.ts';+import { persistencePostgresTemplate } from './helpers/persistence-postgres.ts';++const KEY = 'context.hot_memory.session_only';+const OTHER_FACT = 'OTHER-SESSION-FACT prefers async standups';+const OWN_FACT = 'OWN-SESSION-FACT prefers written agendas';+const noop = { info: () => {}, warn: () => {}, error: () => {} };++const backends = testBackends();+const arms: Array<{ name: string; engine: BrainEngine; close: () => Promise<void> }> = [];+let template: Awaited<ReturnType<typeof persistencePostgresTemplate>> | undefined;++beforeAll(async () => {+ if (backends.includes('pglite')) {+ const engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ arms.push({ name: 'pglite', engine, close: () => engine.disconnect() });+ }+ if (backends.includes('postgres')) {+ template = await persistencePostgresTemplate(process.env.DATABASE_URL!);+ const pg = await template.clone();+ arms.push({ name: 'postgres', engine: pg.engine, close: pg.close });+ }+}, 120_000);++afterAll(async () => {+ for (const arm of arms) await arm.close();+ await template?.dispose();+});++beforeEach(async () => {+ __resetHotMemoryCacheForTests();+ for (const { engine } of arms) {+ await engine.executeRaw('DELETE FROM facts');+ await engine.unsetConfig(KEY);+ }+});++async function seedFact(engine: BrainEngine, fact: string, session: string): Promise<void> {+ await engine.insertFact(+ { fact, kind: 'fact', entity_slug: 'people/alice-example', source: 'test', visibility: 'world', source_session: session },+ { source_id: 'default' },+ );+}++function metaCtx(engine: BrainEngine, sessionId: string): OperationContext {+ return {+ engine, config: {} as GBrainConfig, logger: noop, dryRun: false, remote: true,+ sourceId: 'default', sessionId, takesHoldersAllowList: ['world'],+ } as OperationContext;+}++const hotFacts = (meta: Record<string, unknown> | undefined): string[] =>+ ((meta?.brain_hot_memory as { facts?: Array<{ fact: string }> } | undefined)?.facts ?? []).map((f) => f.fact);++describe('getBrainHotMemoryMeta sessionOnly', () => {+ test('off: a session with no facts of its own still falls back to other sessions', async () => {+ for (const { name, engine } of arms) {+ await seedFact(engine, OTHER_FACT, 'sess-other');+ expect([name, hotFacts(await getBrainHotMemoryMeta('turn_context', metaCtx(engine, 'sess-new')))]).toEqual([name, [OTHER_FACT]]);+ }+ });++ test('on: a session with no facts of its own gets nothing', async () => {+ for (const { name, engine } of arms) {+ await seedFact(engine, OTHER_FACT, 'sess-other');+ const meta = await getBrainHotMemoryMeta('turn_context', metaCtx(engine, 'sess-new'), { sessionOnly: true });+ expect([name, meta]).toEqual([name, undefined]);+ }+ });++ test('on: a session with facts of its own gets only its own', async () => {+ for (const { name, engine } of arms) {+ await seedFact(engine, OTHER_FACT, 'sess-other');+ await seedFact(engine, OWN_FACT, 'sess-own');+ const meta = await getBrainHotMemoryMeta('turn_context', metaCtx(engine, 'sess-own'), { sessionOnly: true });+ expect([name, hotFacts(meta)]).toEqual([name, [OWN_FACT]]);+ }+ });++ test('the cache keeps the two answers apart in both orders', async () => {+ for (const { name, engine } of arms) {+ await seedFact(engine, OTHER_FACT, 'sess-other');+ // Fallback first: its cached payload is never served to the session-only read.+ expect([name, hotFacts(await getBrainHotMemoryMeta('turn_context', metaCtx(engine, 'sess-a')))]).toEqual([name, [OTHER_FACT]]);+ expect([name, await getBrainHotMemoryMeta('turn_context', metaCtx(engine, 'sess-a'), { sessionOnly: true })]).toEqual([name, undefined]);+ // Session-only first: its cached empty answer is never served to the fallback read.+ expect([name, await getBrainHotMemoryMeta('turn_context', metaCtx(engine, 'sess-b'), { sessionOnly: true })]).toEqual([name, undefined]);+ expect([name, hotFacts(await getBrainHotMemoryMeta('turn_context', metaCtx(engine, 'sess-b')))]).toEqual([name, [OTHER_FACT]]);+ }+ });+});++describe('IPC handlers read context.hot_memory.session_only', () => {+ const turn = (engine: BrainEngine, sessionId: string) => turnContextWithBrief(engine, 'default',+ { kind: 'turn_context', protocol: 2, secret: 'x', sessionId, window: [{ role: 'user', text: 'what should I prepare for today' }] });+ const pack = (engine: BrainEngine, sessionId: string) => makeContextPackIpcHandler(engine, 'default')(+ { kind: 'context_pack', protocol: 2, secret: 'x', sessionId });++ test('turn_context: unset keeps the fallback, true drops other sessions\' facts', async () => {+ for (const { name, engine } of arms) {+ await seedFact(engine, OTHER_FACT, 'sess-other');+ const off = await turn(engine, 'sess-turn');+ expect([name, off.factsCount, off.text.includes(OTHER_FACT)]).toEqual([name, 1, true]);+ await engine.setConfig(KEY, 'true');+ const on = await turn(engine, 'sess-turn');+ expect([name, on.factsCount, on.text.includes(OTHER_FACT)]).toEqual([name, 0, false]);+ }+ });++ test('context_pack: unset keeps the fallback, true drops other sessions\' facts', async () => {+ for (const { name, engine } of arms) {+ await seedFact(engine, OTHER_FACT, 'sess-other');+ const off = await pack(engine, 'sess-pack');+ expect([name, (off?.facts ?? []).map((f) => f.fact)]).toEqual([name, [OTHER_FACT]]);+ await engine.setConfig(KEY, 'true');+ const on = await pack(engine, 'sess-pack');+ expect([name, (on?.facts ?? []).map((f) => f.fact), on?.text.includes(OTHER_FACT)]).toEqual([name, [], false]);+ }+ });++ test('context_pack with the key on still carries the session\'s own facts', async () => {+ for (const { name, engine } of arms) {+ await seedFact(engine, OTHER_FACT, 'sess-other');+ await seedFact(engine, OWN_FACT, 'sess-pack-own');+ await engine.setConfig(KEY, 'true');+ const on = await pack(engine, 'sess-pack-own');+ expect([name, (on?.facts ?? []).map((f) => f.fact)]).toEqual([name, [OWN_FACT]]);+ }+ });+});++test('the key is registered, so gbrain config set accepts it', () => {+ expect(KNOWN_CONFIG_KEYS).toContain(KEY);+});diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 94292e25a3..c6bc3972aa 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -35,6 +35,7 @@ test/capacity-bounded-read-6803.test.tstest/capture-consent-admission.test.tstest/capture-dispatch-provenance-6524.test.tstest/chronicle-backfill-max-usd.test.ts+test/chronicle-malformed-diagnostics-7234.test.tstest/claim-fifo-foreground-waiting.test.tstest/claim-lease-holder-only-6712.test.tstest/claude-cli-output-cap.test.ts@@ -86,6 +87,7 @@ test/grandfather-managed.test.tstest/harness-skills-epoch.test.tstest/held-read-signals.test.tstest/hold-action-chain-6712.test.ts+test/hot-memory-session-only-7026.test.tstest/import-file-result-callback-gbra130.test.tstest/import-frontmatter-key-order-5158.test.tstest/import-inline-chunk-keep.test.ts