Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(context,facts): hot memory injected once per session; relink never attaches assistant facts to pages (#7023, #7026, #7270)

garrytanb5312dabd844
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8b28fa15ca..e738e52db1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,53 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+**Hot memory is injected once per session in Claude Code: assistant-attributed and external facts no longer come back on every prompt, and the first prompt no longer repeats the session-start block.** The per-prompt block wrote its own fact line, which dropped the `(assistant said)` prefix, so an assistant suggestion read as your own claim and never matched the dedupe key built from the shared line; an external fact's `<external-data>` wrapper broke the match the same way. Separately, Claude Code records `gbrain hook session-start` output as a SessionStart `hook_success` entry, which the user-prompt hook did not read, so every fact the session-start block showed came back on the first prompt. And `gbrain facts relink` attached the assistant's own report about a page, which the SessionEnd corpus sweep saves as an assistant-attributed fact, to that page as an entity fact on every run, core pages included.
+
+### What changed
+
+| Situation | Before | Now |
+|---|---|---|
+| An assistant-attributed hot fact in the per-prompt block | rendered without `(assistant said)`, and injected again on every prompt | rendered with `(assistant said)`, injected once per session |
+| An `external_untrusted` hot fact | injected again on every prompt | injected once per session |
+| The first prompt after session start in Claude Code | repeated every hot fact the session-start block showed | skips them; core memory printed before the gbrain envelope does not hide page pointers |
+| Another tool's SessionStart output | ignored | still ignored |
+| A fact the assistant or a third party said that names a page, at `gbrain facts relink` (plain or `--conversation`) | attached to that page as an entity fact, core pages included, on every run | left where it was saved and counted as `not_user_attributed`; recall still finds it |
+| Doctor `unlinked_facts` | counted those facts as waiting for a link | does not count them |
+
+### What to watch for after you upgrade
+
+- Nothing runs on upgrade. A session already open when you upgrade sees each assistant fact once more, because its earlier blocks were rendered without the prefix.
+- Assistant or third-party facts a relink already attached to a page stay attached. Remove one with `gbrain forget <fact-id>`.
+
+### Itemized changes
+
+- `render()` in `src/core/context/turn-context.ts` uses `renderFactLine`, and the cross-turn dedupe key is that rendered line (or its unlabeled form) without the confidence.
+- `entryToInjectedBlock` in `src/core/transcripts/claude-code-jsonl.ts` accepts a SessionStart `hook_success` attachment whose `content` holds the gbrain envelope, keeping the text from the envelope on.
+- `entityLinkable` / `ENTITY_LINKABLE_SQL` in `src/core/facts/attribution.ts` gate `gbrain facts relink` (new skip reason `not_user_attributed`), `gbrain facts relink --conversation` (page pick, plan and the locked update) and doctor `unlinked_facts`.
+
+### Duplicate facts
+
+**Recall stops returning the same fact many times, and conversation extraction stops saving it again.** A standing prompt or instruction repeated in every session was extracted and stored once per session, and recall, the entity card and search `saved_facts` returned every copy, so a few copies could fill the whole `limit` and push distinct facts out.
+
+#### What changed
+
+| Situation | Before | Now |
+|---|---|---|
+| Recall, entity card, search `saved_facts` over stored copies of one claim | one row per copy; copies counted against `limit` | one row per claim (newest copy) with `collapsed_count`, and `entity_slugs` when the merged copies sit on several entities; collapsed before `limit` and after visibility filters |
+| Conversation extraction of a claim the source already holds | stored again for every page or session | skipped (`skipped N fact(s) an active fact of the source already states`); re-extracting a page still replaces its own facts |
+| Copies already stored | no way to retire them | `gbrain repair duplicate-facts` (explicit, preview-bound) supersedes every copy with the oldest row; cross-entity groups only with `--include-cross-entity` |
+| One source the backfill should leave alone | turn the whole phase off | `cycle.conversation_facts_backfill.exclude_sources` |
+
+#### What to watch for after you upgrade
+
+- Nothing runs on upgrade and nothing stored changes. Recall output adds two optional fields; every existing field keeps its meaning.
+- 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.
+
+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.347.0] - 2026-10-21
**A model or dimension swap now finishes re-embedding on a large brain, and one overlong fact no longer stops the fact backfill.** After a swap, `gbrain embed --stale`, the background backfill and `gbrain migrate embeddings` mark every chunk from the old model for re-embedding. That marking was one statement over the whole brain, so on a large brain the statement timeout cancelled it, nothing was marked, and the next run hit the same timeout. Separately, before probing the embedder, every embed run counted drifted chunks with two full joins over every chunk. On a large drifted brain those counts timed out too, and the timeout was read as "no drift", so the swap was silently skipped.
diff --git a/docs/architecture/key-files/agent-bootstrap-continued.md b/docs/architecture/key-files/agent-bootstrap-continued.md
index 37434be875..1a8349d853 100644
--- a/docs/architecture/key-files/agent-bootstrap-continued.md
+++ b/docs/architecture/key-files/agent-bootstrap-continued.md
@@ -3,7 +3,7 @@
[Subsystem index](../KEY_FILES.md) · [Previous entries](agent-bootstrap.md).
- `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-memory facts whose rendered line (without the drifting confidence) already appears in `priorContextText` are not re-injected, the same cross-turn contract as volunteered pages (#5591). 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/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/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.
diff --git a/docs/architecture/key-files/agent-bootstrap.md b/docs/architecture/key-files/agent-bootstrap.md
index 1a2124ce5c..c09264c5d8 100644
--- a/docs/architecture/key-files/agent-bootstrap.md
+++ b/docs/architecture/key-files/agent-bootstrap.md
@@ -32,7 +32,7 @@ User-facing contract: `docs/guides/bootstrap.md`. Runbook the paste block fetche
- `src/core/bootstrap/harness.ts` — `gbrain bootstrap harness`: machine-level wiring of framework-spawned Claude Code/Codex/opencode sessions to a RUNNING `gbrain serve --http`, no `agent.json`. The opencode target mirrors the codex posture: forced-wire on explicit `--harness opencode` (the JSONC writer needs no CLI), one managed `mcp.<name>` remote entry with the inline bearer header (0600) via `opencode-json.ts`, rotation across a url change recognized through the PRIOR receipt's url, failed-smoke rollback restoring the run's UNIQUE backup or removing a fresh entry — guarded by a content compare against the exact text this run wrote, so a NEWER registration that landed after the lock released is never clobbered (rollback skips with a note; the fresh mint is revoked either way), with the backup unlinked once consumed or once the smoke verifies — `--remove` classifying against the receipt url (not-ours skips with a note), and `--status` bearer recovery via `parseOpencodeEntryBearer` (url-matched). An explicit private posture (file-plane `memory.visibility_posture`) prints a pre-consent WARNING outside registrar mode: the wired HTTP sessions read world facts only, so they cannot read back what they save as private. Consent block in the honesty register (reach as fact, transcript capture its own numbered item + `--no-capture`, off-ramps in the same breath), then `requireConsent` via `consentGate` (effects `persistent_install`, plus `credentials` when it mints the token; `--yes` approves; the TTY prompt runs only when `isInteractive()`, and EOF/decline or no human at the terminal writes nothing and exits 3 with the consent payload, whose argv never repeats `--token`); /health probe with a loopback guard on `--url` (remote brains are `gbrain connect`'s charter; `--token` makes it a pure registrar); mint-first rotation (previous token revoked BY ID only after every target confirms + the bearer smoke passes — clients are never dead mid-swap; revoke-by-name never happens); the smoke is canary-gated: a random same-format bearer must FAIL auth before the real token is sent, so a loopback impostor is caught whichever way it answers, and ANY failed smoke rolls back symmetrically — fresh registrations removed, replaced ones restored (an unrestorable replacement fails the target honestly), the freshly-added pre-approval stripped, and the fresh mint revoked immediately so nothing live stays pointed at an unverified endpoint; the `permissions.allow` pre-approval only lands after the MCP registration itself confirms; stale prior-target cleanup runs AFTER the smoke passes, so a run that failed to establish its replacement never unwires working prior wiring; write-ahead harness receipt (targets persist as `pending` at mint time and flip per-target, so a crash leaves consumable state); registration ownership checks (`--force` to replace a foreign-url server; `--remove` skips what it no longer owns); user-XOR-project hook scopes; `GBRAIN_HOOK_LANE=harness` on hook commands so `gbrain hook` yields to a workspace bootstrap install in the cwd (Claude Code merges settings scopes — same event must not fire twice); the hook `GBRAIN_SOURCE`, the receipt `source_id`, and the token grant bind to a validated `--source` (scalar write floor), else to the source `HarnessDeps.resolveHookSource` resolves through the SAME chain the serve's resolve-IPC binding runs (`resolveSourceWithTier`: env → dotfile → local_path → `sources.default` → sole populated non-default → seed default) with that source's federated read set as the grant, so the hooks' `turn_context` claim is never `source_mismatch`; a resolution landing on `default`/`__all__` is the federated floor. Lookup failures are NOT papered over with `default`: a typo'd `--source` or stale env/dotfile throws `SOURCE_UNRESOLVED` before any mint or receipt; an explicit `--source` with an unopenable engine binds unverified with a warning; a live PGLite serve (engine cannot open) refuses with `LIVE_SERVE` when no token was supplied, printing (and in `details.steps`) stop / `auth create` + `auth rescope --operations` with the harness grant / restart / `--token` (#6661) and, on the `--token` lane without `--source`, wires the hooks UNPINNED with a warning (an unpinned hook resolves through the live serve's own binding; the receipt records the federated floor `default` plus `source_pinned: false`); any other lookup failure throws `SOURCE_UNRESOLVED` naming `--source`; Postgres degradation + serve-version-skew honesty lines (`isServeOlderThanScopes` pinned to `SCOPES_MIN_SERVE_VERSION`, the first scope-aware release, so later CLI bumps never re-trigger the warning); `--status` probes the live truth with host-config token recovery (redacted; the Claude Code lane recovers a bearer ONLY from a registration whose URL matches the receipt — never another install's credential; the codex fallback reads OUR managed block at the receipt-recorded path, its `url` key not yet compared — TODOS.md; the opencode fallback IS url-compared inside `parseOpencodeEntryBearer`) and honest `verify: unavailable` degrades, with a cron-honest exit contract: 0 only when serve + token + every target verify and the rotation has converged (honest degrades count), 1 on an unreachable serve, a failed token verify, failed/pending targets, unconverged rotations, or a half-removed receipt (zero targets, minted token awaiting deferred revoke — also a doctor FAIL); no receipt prints honestly and exits 0 in plain mode, 2 under `--json`; `--json` on apply emits ONLY the final JSON document on stdout (prose → stderr); `--remove` is engine-free-first and defers the token revoke with exact instructions under a live PGLite serve; it removes hook entries that lost their marker when their command is this install's (`harness-hooks.ts`), keeps the hooks target failed on an unowned lookalike, and `--remove --dry-run` previews without a lock or any write. Hooks targets record `launcher` and `seat` on the receipt (the ownership identity for later runs); the permission target carries `mechanism: 'added'` forward from a prior confirmed receipt target so a re-run never relabels its own `mcp__<name>` as pre-existing, and the failed-smoke rollback removes only an entry added this run. Locks on the gbrain HOME, plus the host config dir around codex/opencode writes, removals, rollbacks, and stale cleanup (stale prior-target cleanup nests the codex/opencode config-dir lock inside the held claude config-dir lock — same claude-first ordering as apply/remove, same-dir skip — so its read-modify-write can't interleave with a concurrent config-dir-locked writer); `bootstrap uninstall` holds the HOME lock across the whole teardown and runs harness removal FIRST (revoke needs the DB alive; `--delete-brain` would destroy harness.json) and treats NO_RECEIPT/HOME_GUARD/RECEIPT_MISMATCH as "no workspace install" once harness wiring is cleared. Pinned by `test/bootstrap-harness.serial.test.ts` + `test/bootstrap-harness-lifecycle.serial.test.ts`. The production mint (`mintHarnessToken`, exported) rotates each host's token from the token it replaces via `carryLegacyGrant`. `--refresh-skills` (`src/core/bootstrap/harness-skills.ts`, `refreshHarnessSkills`) re-joins each live shared-skills entry under its recorded credential so the receipt and native router adopt the server's current enrollment epoch, with no token rotation; `localEnrollment` reads the adapter receipt epoch for `--status`, and `supersededEnrollments` is doctor's read-only comparison against `shared_skill_members` (`bootstrap_harness_health` warn, code `shared_skills_epoch_superseded`). Pinned by `test/harness-skills-epoch.test.ts`. The Codex SessionEnd capture hook obeys the same recorded consent as the Claude lane (`wireCodexCapture`: hooks on, capture accepted, never registrar mode) and is a numbered consent item when wired. #6661 option B: `harness-pending-verify.ts` (a `--token` run on PGLite with no serve answering ends `pending_verify`, exit 13, re-run as `fix`; `--status` partial until it passes).
- `src/core/token-mint.ts` — programmatic legacy-token mint/revoke for the harness lane: `mintLegacyToken` (scopes → the TEXT[] column; required `takesHolders` per-token allow-list, harness default `['world']`; optional `permissions.source_id` federation array mirroring the stdio lane's `localFederatedSourceIds` grant, element 0 = write floor, `[]` stored as the explicit no-source grant; `RETURNING id`) and `revokeLegacyTokenById` (never touches same-name siblings). `carryLegacyGrant` + `readActiveTokenPermissions` are the harness rotation carry-over: takes holders and the source grant carry as stored (explicit empty lists included; an explicit `--source` wins), a stored operation snapshot narrows to the run's snapshot plus only skills-policy-added operations, and newer operations are reported as withheld (pinned by `test/harness-rotation-grants.test.ts`). Exports `TOKEN_ID_RE`, the canonical token-id shape shared with the `auth revoke --id` CLI gate. Canonical `hashToken`/`generateToken` from `src/core/utils.ts`. Pinned by `test/token-mint.test.ts`. `insertUnifiedToken` (shared with `auth create`) births every token on the unified grant columns at revision 1 plus the `permissions` mirror; a brain whose schema predates the columns refuses with `migrations_pending` (fix: `gbrain apply-migrations --yes`) and nothing is written; `carryLegacyGrant` parses the prior grant from its JSONB through `tokenGrantFromPermissions`, so a drifted prior carries its JSON edit (the `--adopt-permissions` resolution).
- `src/commands/hook.ts` — engine-free `gbrain hook {session-start,user-prompt,stop,session-end,compact}` (zero engine modules in the import graph; a hook must NEVER contend for the PGLite writer lock). session-start's context pack goes through `src/core/context/session-start-pack.ts`: when `sessionStartAwaitsServe` holds (source `startup`/`resume`, harness claude-code, `claudeCodeSpawnsServe(cwd)`), the hook's deadline widens from `SESSION_START_DEADLINE_MS` (1.5s) to `SESSION_START_SERVE_WAIT_DEADLINE_MS` (4s, under the 5s harness timeout) and `requestSessionStartPack` retries every 100ms, re-resolving socket and secret, until the serve Claude Code spawned alongside SessionStart answers (Cat 41 first push: Claude Code 2.1.285 starts MCP servers in parallel with SessionStart and a fresh serve binds ~2s later); a wait that runs out records heartbeat `degraded`/`serve_not_ready`. Pinned by `test/hook-session-start-serve-wait.serial.test.ts`. When `GBRAIN_HOOK_LANE=harness` (set on harness-mode hook commands), each event PARSES the cwd's workspace settings carriers — `.claude/settings.local.json` AND the committed `.claude/settings.json` — and yields silently only when a live `bootstrap-v1` hook entry wires THAT event: the workspace install wins over user-scope harness wiring so the merged settings scopes can't fire the same event twice, unwired events still run, and a repo committing marker-lookalike strings in unrelated fields can't disable the machine-wide capture lane (fail-open — a read/parse hiccup means the event runs normally). user-prompt: stdin hook JSON → transcript-path confinement → last-4-turns window + cross-turn dedupe (the transcript's `hook_additional_context` attachments — the blocks WE previously injected — ride `priorContextText`, deduplicated and capped at `PRIOR_CONTEXT_MAX_BYTES` (32KB, so the advisory payload can never blow the IPC message cap; one oversized block is skipped without evicting smaller ones), so a page is volunteered once per session, not once per mention; structured extraction only, never raw-turn substring matching) → IPC turn_context (with a feedback-loop `channel`, `--harness <claude-code|codex>`, default claude-code) → `hookSpecificOutput.additionalContext` under an 800ms self-deadline; every path fails open (exit 0, empty stdout) with a typed reason in the heartbeat. Listed in cli.ts's `STARTUP_HOOK_SKIP_COMMANDS` (per-prompt invocations must never spawn a detached check-update child; membership is pinned by a source grep — the runtime path no-ops under NODE_ENV=test). session-start: file-plane digest (allowlisted MEMORY.md sections, push staleness, prior failures) + crashed-session recovery push gated on an initialized manifest. session-end: a transcript path or payload cwd carrying the claude-cli scratch fingerprint (`isClaudeCliSelfTranscriptPath`) is gbrain's own subprocess session — heartbeat `segment: self_transcript`, no parse, no corpus write; otherwise confined full-transcript parse → redacted corpus write (session-id filename dedup, retention prune via `gcCorpusTurnFiles`: an extracted `.txt` goes at `corpus_retention_days`, one with no `.ingested` sidecar only at `CORPUS_UNINGESTED_RETENTION_FACTOR` (3) times that, E-N1, pinned by `test/corpus-retention-uningested.serial.test.ts`; an assistant-only whole-file parse heartbeats `degraded`/`no_user_turns`, E-N4; the corpus scan runs highEntropy whenever the relay is on — the relay child derives its egress task line from the corpus text — and stays vendor-prefix-only otherwise) → parser-drift detection (`bytes>0 && turns==0` is loud) → best-effort workspace push. session-start recovery + session-end pushes run in a DETACHED child so the hook returns immediately (a synchronous inline push would block harness startup on a dirty tree); the corpus write is atomic and clears the stale ingested/in-progress sidecars so a resumed session re-ingests its appended transcript. Heartbeat JSONL is counters/reasons only by construction; `readHeartbeatTail` feeds doctor. `GBRAIN_HOOKS=0` kills all events. Session-end capture dispatches per harness through `captureSpecFor(io.harness)` (`src/core/transcripts/capture-spec.ts`): claude-code and codex each pin their OWN confinement root + parser; unknown/undefined/opencode resolve to the claude spec (golden-pinned). The codex lane confines to `codexSessionsDir()` + `codexArchivedSessionsDir()` (codex moves rollouts into the flat archived store), parses rollouts via `parseCodexHookTranscript`, and falls back to bounded id-matched discovery across both stores when the SessionEnd payload carries `transcript_path: null` or a path that no longer exists (`missing_path`; `unreadable` is reserved for EACCES/IO faults) — the fallback and prior-run relay failures are DEFERRED heartbeat reasons, applied after current-session reasons so they never mask one (first-degrade-wins). ONE gate covers the whole optional Memorable seam — `memorableGateAllowed(cfg)` in hook-heartbeat.ts: the config flag (`integrations.memorable.enabled === true`, file plane), the `GBRAIN_MEMORABLE` kill switch (any common negative spelling, trimmed; env can only ever disable), AND the gbrain-authored consent stamp (`memorable-consent.json` — see hook-heartbeat.ts). Off is the default: no tool-call collection, no receipt, no spawn. On, session-end runs the shared `redactedToolCallsJson` (span-filtered to the corpus window, highEntropy ALWAYS on — those args are the one artifact that leaves the machine) and `recordAndRelayReceipt` (receipt dedup by post-redaction content hash → CLI-side consent evidence → `resolveMemorableBin` → detached fire-and-forget `memorable record` spawn; both capture lanes trim memorable-relay.jsonl). Fail-closed egress guards: a scanner-import failure skips the receipt+relay entirely (`memorable_relay_skipped_unscanned` — parity with the openclaw lane), and a newest-mtime discovery GUESS (no session-id match) writes the local corpus but never relays (`memorable_relay_skipped_newest_guess` — the newest rollout can be a different, still-running session). A payload without session_id adopts the transcript's own id post-parse (never a shared unknown.txt corpus), and the gate answer is hoisted BEFORE the parse and collection is opt-in, so the default gate-off population never collects tool calls (`collectToolCalls: memorableAllowed`). Operator-facing doc: `docs/memorable-agents.md` (install is `npm i -g memorable-cli`; closed source, no source install, no embedding model to configure). `spawnDetachedPush` passes `env: process.env` explicitly so the detached push child inherits the parent's quarantined env view. `tryExecAsync` (the git wrapper behind `resolveBootstrapWorkspaceRoot` / `repoPhaseComplete`) also passes `env: process.env` so git sees the quarantined view, not Bun's startup snapshot; pinned by `test/hook-push-spawn-env.test.ts`. Seat identity (#4618): session-end (before any corpus write of the session), compact (before `bankCompactSegment`) and the stop hook's writeback bank (before `bankWritebackTurn`) record `<sessionId>.seat.json` through `context/seat.ts` — `GBRAIN_SEAT` when valid, else the hashed harness-home seat; `seat_label_invalid`, `seat_conflict` (first seat kept) and `seat_write_failed` are heartbeat reasons with a fixed `hint` (session-end applies them last, like the deferred reasons). `gcCorpusArtifacts` reaps a seat sidecar or session source record once no `.txt` of its session remains, after a 10-minute grace; session-end counts live sessions across the spool and the legacy top level (#6611). Pinned by `test/session-seat-capture.serial.test.ts`. `HOOK_EVENTS` is the router inventory from `src/cli/subcommands.ts`; `hook <event> --help` prints usage and never runs the event. `user-prompt` confines and parses `transcript_path` through `captureSpecFor(io.harness)`, so `--harness codex` reads the rollout under `CODEX_HOME/sessions` (the Claude projects root otherwise), and skips the Claude-only pressure notice for codex. #5941: the pack and user-prompt arms ask for `contextSourceId` (session-start-pack.ts): `GBRAIN_SOURCE`, else the session's frozen source record, else the cwd's `.gbrain-source` walk; a serve bound elsewhere answers `source_mismatch` (the heartbeat reason).
-- `src/core/transcripts/claude-code-jsonl.ts` — the Claude Code transcript parser as a dated spec-target (tool_use/tool_result/thinking/image/sidechain/summary/compact-boundary shapes; placeholders for non-text content). `recognizedOnly`: whole file read, every line parsed, no conversation message, some session scaffolding (session-end: `empty_session`). Both the hook-tail and full-session parsers skip root `isSidechain`, `isMeta`, or `isCompactSummary` exactly `true`; nested markers and truthy non-booleans do not exclude a turn. User text with a non-empty string root `origin.kind` other than `'human'` is excluded; missing, empty, or unstructured origins stay compatible, without guessing from message text. Assistant text and non-text placeholders remain eligible, while skipped metadata entries also contribute no collected tool calls. `test/claude-code-jsonl-origin.test.ts` uses synthetic fixtures, not new live-harness validation. `genuineUserTurnIndexes` separately records accepted user-role turns containing real text blocks (harness tags and paste blocks removed first), because Claude stores tool-result-only entries with `role:'user'`; archival consumers keep every placeholder while prompt-only consumers select by structure. Also extracts `injectedContextBlocks` — the `hook_additional_context` attachment lines a gbrain hook previously injected (verified live against claude CLI 2.1.224; marker-filtered, so a foreign hook's blocks are excluded and another tool's output can't suppress volunteering — a same-user mislabeling guard, not an authenticity check), the user-prompt hook's cross-turn dedupe input; `confineTranscriptPath` (contained under `~/.claude/projects`, `.jsonl`, lstat-rejects symlinks, byte cap; under WSL, a Windows drive-literal `transcript_path` — Claude Code on the Windows host invoking hooks via `wsl.exe` — is translated through `src/core/wsl-paths.ts` and then held to the SAME confinement, rooted Windows-side, so translation never widens what a hook may read). Fixtures: `test/fixtures/conversation-formats/claude-code.jsonl` (synthetic, privacy-guarded) + `test/fixtures/hook-transcript.jsonl` (real captured hook round-trip). `parseTranscript` additionally returns `toolCalls`, but collection is OPT-IN (`collectToolCalls: true`; the bare parse — every per-prompt lane — collects nothing, so tool INPUTS are never retained for users who never opted in): the tool name + input args for every `tool_use` block, oldest → newest, each joined to its `tool_result` outcome by `tool_use_id` and then stripped of that id so no transcript-internal identifier reaches a consumer; every STRING in a collected input is bounded to `TOOL_CALL_VALUE_MAX_CHARS` (32k) with an explicit `…[N chars omitted]` marker (`capToolCallInput`, shared with the codex lane — one receipt-size ceiling for every harness). It is a parallel extraction, never a change to the placeholder-only archival rendering, which is load-bearing for the token-budget-constrained ambient-recall path; existing callers that ignore the field see no behavior change.
+- `src/core/transcripts/claude-code-jsonl.ts` — the Claude Code transcript parser as a dated spec-target (tool_use/tool_result/thinking/image/sidechain/summary/compact-boundary shapes; placeholders for non-text content). `recognizedOnly`: whole file read, every line parsed, no conversation message, some session scaffolding (session-end: `empty_session`). Both the hook-tail and full-session parsers skip root `isSidechain`, `isMeta`, or `isCompactSummary` exactly `true`; nested markers and truthy non-booleans do not exclude a turn. User text with a non-empty string root `origin.kind` other than `'human'` is excluded; missing, empty, or unstructured origins stay compatible, without guessing from message text. Assistant text and non-text placeholders remain eligible, while skipped metadata entries also contribute no collected tool calls. `test/claude-code-jsonl-origin.test.ts` uses synthetic fixtures, not new live-harness validation. `genuineUserTurnIndexes` separately records accepted user-role turns containing real text blocks (harness tags and paste blocks removed first), because Claude stores tool-result-only entries with `role:'user'`; archival consumers keep every placeholder while prompt-only consumers select by structure. Also extracts `injectedContextBlocks` — the `hook_additional_context` attachment lines a gbrain hook previously injected (verified live against claude CLI 2.1.224), plus a SessionStart `hook_success` attachment's `content` from the gbrain envelope on (session-start stdout, #7026; marker-filtered, so a foreign hook's blocks are excluded and another tool's output can't suppress volunteering — a same-user mislabeling guard, not an authenticity check), the user-prompt hook's cross-turn dedupe input; `confineTranscriptPath` (contained under `~/.claude/projects`, `.jsonl`, lstat-rejects symlinks, byte cap; under WSL, a Windows drive-literal `transcript_path` — Claude Code on the Windows host invoking hooks via `wsl.exe` — is translated through `src/core/wsl-paths.ts` and then held to the SAME confinement, rooted Windows-side, so translation never widens what a hook may read). Fixtures: `test/fixtures/conversation-formats/claude-code.jsonl` (synthetic, privacy-guarded) + `test/fixtures/hook-transcript.jsonl` (real captured hook round-trip). `parseTranscript` additionally returns `toolCalls`, but collection is OPT-IN (`collectToolCalls: true`; the bare parse — every per-prompt lane — collects nothing, so tool INPUTS are never retained for users who never opted in): the tool name + input args for every `tool_use` block, oldest → newest, each joined to its `tool_result` outcome by `tool_use_id` and then stripped of that id so no transcript-internal identifier reaches a consumer; every STRING in a collected input is bounded to `TOOL_CALL_VALUE_MAX_CHARS` (32k) with an explicit `…[N chars omitted]` marker (`capToolCallInput`, shared with the codex lane — one receipt-size ceiling for every harness). It is a parallel extraction, never a change to the placeholder-only archival rendering, which is load-bearing for the token-budget-constrained ambient-recall path; existing callers that ignore the field see no behavior change.
- `src/core/transcripts/pasted-content.ts` — #5812, the ONE Claude Code paste detector (`<pasted_content id="…">…</pasted_content id="…">`, tag shape from a real 2.1.287 transcript; depends on that harness format). `stripPastedContent` removes closed blocks and an unclosed tail only when the opening tag has the exact harness shape, scanning with `indexOf` (no lazy regex); `stripPastedContentFromCorpus` strips inside each `[user]` block of the `toCorpusText` rendering, never across the flattened corpus, so an unclosed paste ends with its turn. Consumers: the writeback gate (banked text), `isGenuineUserText` in the parser (classification only; turn, corpus, segment and ingest text keep the paste), and `corpusTextForExtraction` (`corpus-segments.ts`: a `.wb-` file is one turn, other corpus files per block) used by the sweep, the checkpoint harvest and dream `extract_atoms`. `synthesize` keeps pastes. Tests: `test/transcripts-pasted-content.test.ts`, `test/facts/writeback-gate.test.ts`, `test/extract-atoms-pasted-content.test.ts`.
- `src/core/transcripts/grok.ts` — the Grok Build (grok CLI) transcript adapter: one session directory (`~/.grok/sessions/<url-encoded-cwd>/<uuid>/chat_history.jsonl`) = one session; `GROK_HOME` relocates the root. Turn selection is STRUCTURAL (`mapGrokLine`, exported so the dated `SPEC_TARGET` mapping is pinned): user turns are `type:'user'` text blocks WITHOUT `synthetic_reason` (injected system_reminder/task_completed rows are `typed`, i.e. intentionally text-free, as are tool_result-only user arrays); assistant turns need non-empty string `content` (tool-only rows — `content` ''/null WITH `tool_calls` — are `typed`); system/reasoning/tool_result/backend_tool_call rows are `typed`; unknown row types `skip`. A recognised HUMAN-turn row whose content this parser cannot decode (user `content` missing / non-string / non-array / an array holding non-block entries; assistant non-string `content` with no `tool_calls`) is `malformed` and counted as SKIPPED, never typed, so a file made only of such rows is never `expectedEmpty` — the ingest drift signal fires (`bytesRead > 0`, sessions 0, `cleanScan=false`, watermark frozen) and `zeroSessionsReason` names the malformed row count, instead of an upstream schema change silently advancing the watermark past whole conversations. `chat_history.jsonl` carries NO per-message timestamps: session times come from the sibling `summary.json` (`created_at`/`last_active_at`; a malformed summary is ignored, an unparseable date is never fabricated) and, because grok writes `summary.json` at session END, an in-progress session or partial rsync falls back to the log file's own mtime — a real filesystem time — with `raw.timestamp_source` stamped `'summary.json'` vs `'file_mtime'` so consumers can tell them apart (without the fallback the render refusal would freeze the `--since-last` watermark for the whole grok root). Every message carries the session bounds (last message = `last_active_at`, the rest = start). Session id: summary → UUID dir name → `stableIdFromPath` (a sha256 prefix of the log path, never the bare `chat_history` basename, which would collapse every such session onto one page). Sidecars (updates.jsonl, events.jsonl, rewind_points.jsonl, summary.json, prompt_history.jsonl) are not sessions — discover.ts's grok-sidecar filter is scoped to PROVEN grok trees and the head sniff rejects claude-family keys (grok detection runs after claude-code; an oversized system head still detects through the truncated-line sniff); a percent-encoded cwd segment that fails to decode yields `cwd` undefined with the session id intact.
- `src/core/transcripts/capture-spec.ts` + `codex-hook-lane.ts` — the per-harness session-end capture seam. `capture-spec.ts`: the satisfies-anchored `CAPTURE_SPECS` record ({confine, parse, discover?}) for the STDIN-DRIVEN lanes (claude-code, codex); `captureSpecFor()` resolves unknown/undefined/opencode to the claude spec (golden-pinned by `test/codex-hook-lane.test.ts`); openclaw is deliberately NOT a member (its lane is in-process, trusted-plane — see context-engine.ts). `codex-hook-lane.ts`: `confineCodexTranscriptPath` (the same S3#8 ladder as the claude root, pinned at BOTH `codexSessionsDir()` AND `codexArchivedSessionsDir()` — codex MOVES a rollout into the flat `archived_sessions` store on archive, so fencing only the live store refused a still-valid path; both CODEX_HOME-resolved since the spawner IS codex; an explicitly pinned test-seam `root` stays single-root; ENOENT/ENOTDIR on the path is `missing_path` — the rung hook.ts gates its discovery fallback on — while `unreadable` is reserved for EACCES/IO faults, so the codex session-end heartbeat reason for a nonexistent `transcript_path` after a failed discovery is `transcript_missing_path`, not `transcript_unreadable`; no WSL branch v1), `parseCodexHookTranscript` (ParsedTranscript shape over the adapter's exported `mapCodexLine`; same OPT-IN `collectToolCalls` contract as `parseTranscript`, and the same `capToolCallInput` bound on observed args; head+tail over budget so session_meta identity survives; `recognizedOnly` when every non-blank line parsed and was a session header, so hook.ts ends a Codex session opened and closed with no prompt as `ok`/`empty_session` (no status alert, no corpus file) while any unknown or torn record with zero turns stays `parser_drift`; tool calls from the OBSERVED args keys — `custom_tool_call.input` fixture-verified, `function_call.arguments` source-verified at rust-v0.147.0; tolerant JSON-string parse; NO `result` join — 0.147.0 persists no success flag on `*_output` rows; `compacted` rows become boundary positions), and `discoverNewestCodexRollout` (bounded newest-first walk over the dated live store, then a flat pass over the archived store under the SAME 4096 dirent cap — skipped once the cap trips; id-in-filename match, and an id-matched archived hit keeps `transcript_discovered` (never relabelled `_newest`, which hook.ts reads as a guess and bars from the relay); symlink-reject — the fallback for `transcript_path: null` or a moved rollout, and the seam for SIGKILL'd sessions, which never fire SessionEnd). Engine-free by construction; never imports discover.ts. Pinned by `test/codex-hook-lane.test.ts` + `test/codex-hook-lane-archived.test.ts` + the runHook-driven matrix in `test/memorable-relay.serial.test.ts`.
diff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.md
index fa89180284..79a184fb89 100644
--- a/docs/architecture/key-files/commands-2-continued.md
+++ b/docs/architecture/key-files/commands-2-continued.md
@@ -41,4 +41,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/doctor/checks/purge-parks.ts` — `purge_parked_pages` (#6741 C): names parked purges with their last error; fix `gbrain pages purge-deleted --retry-parked --yes` (preview `--dry-run --json`), consent destructive, ask_user.
-- `src/commands/doctor/checks/unlinked-facts.ts` — `unlinked_facts` (#5836), registered before `search_mode` and mirrored in `doctorReportRemote`: per the doctor's source scope (`--source`, else every source; the caller's grant remotely), the unlinked share of the newest 100,000 active facts per source (`idx_facts_since` LATERAL walk), the 7-day unlinked share of new facts, `no_subject` judgments and the 7-day `linked` tiers from `fact_relink_attempts`, fence-owned unlinked rows (row_num or source_markdown_slug set, conversation rows excluded), the conversation extractor's unlinked derived rows (`cli:extract-conversation-facts*`, #6764: count, origin `conversation`, and `details.conversation` naming the source with the most and its pages, most rows first, up to `CONVERSATION_FIX_SLUGS` = 50), origins (`conversation`, `mcp:put_page`, extraction, remember) and 7-day write-time inferred links by tier (`entity inferred from <tier>` context, bare or after ` — `). Warns when over 25% of at least 20 new facts are unlinked, facts judged `no_subject` and conversation rows memoized `conversation_unresolved` excluded (`new_7d.conversation_unresolved`); the fix is `gbrain facts relink --dry-run`; when conversation rows are unlinked the envelope `fix` (`details.conversation.fix`) is, for rows the free conversation relink has not tried, `gbrain facts relink --conversation --source <id> --slugs <csv>` (preview `--dry-run`, consent none, actor agent, host operator remotely; test `test/conversation-relink-6764.test.ts`) and, once only rows it memoized `conversation_unresolved` remain (a memo that a page created later re-arms unless the reason is memoized, `core/facts/conversation-memo.ts`), a bounded re-extraction of those pages not yet re-extracted on their current content (`gbrain extract-conversation-facts --source-id <id> --slugs <csv> --force --max-cost-usd <N>`, input `N` the approved USD, preview `--dry-run`, consent paid + egress, ask_user; test `test/conversation-facts-unlinked-6764.test.ts`), both verified by `gbrain doctor --only unlinked_facts --json`, because plain relink never examines derived rows; the remote report asks the brain host operator to run it. When only rows on pages already re-extracted on their current content remain, `details.conversation.fix` is `manual`: no envelope `fix`, and the message names linking by hand with `--entity` (test `test/conversation-memo-6764.test.ts`). Without `fact_relink_attempts` the relink figures are null and nothing is excluded. Tests: `test/doctor-unlinked-facts.test.ts`.
+- `src/commands/doctor/checks/unlinked-facts.ts` — `unlinked_facts` (#5836), registered before `search_mode` and mirrored in `doctorReportRemote`: per the doctor's source scope (`--source`, else every source; the caller's grant remotely), the unlinked share of the newest 100,000 active facts per source (`idx_facts_since` LATERAL walk), the 7-day unlinked share of new facts, `no_subject` judgments and the 7-day `linked` tiers from `fact_relink_attempts`, fence-owned unlinked rows (row_num or source_markdown_slug set, conversation rows excluded), the conversation extractor's unlinked derived rows (`cli:extract-conversation-facts*`, #6764: count, origin `conversation`, and `details.conversation` naming the source with the most and its pages, most rows first, up to `CONVERSATION_FIX_SLUGS` = 50), origins (`conversation`, `mcp:put_page`, extraction, remember) and 7-day write-time inferred links by tier (`entity inferred from <tier>` context, bare or after ` — `). Warns when over 25% of at least 20 new facts are unlinked, facts judged `no_subject` and conversation rows memoized `conversation_unresolved` excluded (`new_7d.conversation_unresolved`); the fix is `gbrain facts relink --dry-run`; when conversation rows are unlinked the envelope `fix` (`details.conversation.fix`) is, for rows the free conversation relink has not tried, `gbrain facts relink --conversation --source <id> --slugs <csv>` (preview `--dry-run`, consent none, actor agent, host operator remotely; test `test/conversation-relink-6764.test.ts`) and, once only rows it memoized `conversation_unresolved` remain (a memo that a page created later re-arms unless the reason is memoized, `core/facts/conversation-memo.ts`), a bounded re-extraction of those pages not yet re-extracted on their current content (`gbrain extract-conversation-facts --source-id <id> --slugs <csv> --force --max-cost-usd <N>`, input `N` the approved USD, preview `--dry-run`, consent paid + egress, ask_user; test `test/conversation-facts-unlinked-6764.test.ts`), both verified by `gbrain doctor --only unlinked_facts --json`, because plain relink never examines derived rows; the remote report asks the brain host operator to run it. When only rows on pages already re-extracted on their current content remain, `details.conversation.fix` is `manual`: no envelope `fix`, and the message names linking by hand with `--entity` (test `test/conversation-memo-6764.test.ts`). Without `fact_relink_attempts` the relink figures are null and nothing is excluded. Facts attributed to the assistant or a third party are not counted at all (`ENTITY_LINKABLE_SQL`, #7270: relink never links them). Tests: `test/doctor-unlinked-facts.test.ts`, `test/relink-attribution-7270.test.ts`.
diff --git a/docs/architecture/key-files/core-persistence-facts.md b/docs/architecture/key-files/core-persistence-facts.md
index 8219065785..b497579359 100644
--- a/docs/architecture/key-files/core-persistence-facts.md
+++ b/docs/architecture/key-files/core-persistence-facts.md
@@ -10,6 +10,6 @@ Managed facts extraction: the entity-intent preparer and publisher, conversation
- `src/core/facts/conversation-publication.ts` — managed conversation facts as database-only `managed_maintenance_conversation_facts` batch requests (`submitDatabaseMaintenanceIntent` on `ANCHOR_SLUG`, a dot-led slug no page can hold, dispatched from `prepareMaintenanceMutation`). Each page's frozen entry (`buildConversationPage`: `FrozenExtractedFact` rows, its generation and attempt, vectors only under the brain's facts embedding signature) joins the run's batch; `enqueueManagedPage` publishes it once `DEFAULT_BATCH_CAPS` is reached (25 pages, 10 with extracted facts, 8 MiB) and `flushManagedBatch` at the end of the run. The generation key (protocol, source incarnation, page id, revision, parser-input version token, `CONVERSATION_EXTRACTOR_VERSION`, selectors, newest extractor row id) is checked before model work by `startManagedPage` against `loadGenerationIndex` (the writer's unsettled and failed batches on the anchor, read once per run): a member of an unsettled batch waits and replays its receipt, a member of a retryably failed batch is resubmitted from its stored entry, a deterministic failure of a batch that held it alone or three failed batches block it (GBRA-130 A-51: `publishBatch` re-publishes a multi-page batch that failed deterministically in halves, so only the page that fails alone takes the code; `test/pathological/a-51-conversation-batch-booking.test.ts`); all without model calls. The batch request id digests its members' (generation, attempt) pairs. The preparer locks every member's key and applies each on its own (`applyEntry`): a deleted, replaced or moved page is skipped and reported, a page whose rows fail validation gets a durable `blocked:` not-extractable outcome, vectors under another signature are dropped; none fails the batch. `estimateConversationIntentBytes`/`conversationIntentByteLimit` skip a page whose largest entry cannot fit before any model call; `assertConversationAdmissionHeadroom` stops admitting at 80% of the writer's outstanding requests, reserved receipt bytes or lifetime ids (`maintenance_backpressure`, exit 12, naming the resource and a `--limit` that fits), up front for the run's planned batches and before each new batch. `publishConversationFacts` (the managed apply and the unmanaged writer) passes fact rows through the write gate at the page's derived tier and retires the prior batch only for a complete replacement (#7013: `full` scope, at least one fact, nothing held or rejected) or on a page with no active extractor facts, through `replaceConversationFacts`, which deletes the page's extractor rows (expiring referenced and keeping label-retired ones) and inserts the rows numbered above every remaining row, failing on a lost insert. Otherwise the prior facts stay: the outcome row replaces the page's prior outcome rows (so the page is not paid for again), a `window` run (`--since` dropped messages) adds its facts beside them, and a `partial` run (a `--segment-limit` cut, a page changed mid-run) publishes no facts over them. Each entry carries its `scope`; an entry frozen without one is `partial` without its outcome, `window` with a `--since` selector, else `full`. Tests: `test/pathological/h4-conversation-facts-zero-yield.test.ts` (managed and unmanaged, + Postgres arm). Tests: `test/conversation-facts-managed.test.ts` (+ Postgres arm), managed-connector contract cases `extract_conversation_facts*`.
- `src/core/facts/subject-infer.ts` — zero-LLM fact subject inference shared by the write paths (remember, the facts backstop) and `gbrain facts relink`. `inferFactSubject(engine, sourceId, { fact, pageSlug?, mode, excludePrivate? })` returns `{ slug, via: 'page' | 'mention' }` or a miss reason (`ambiguous`, `unverified_match`, `no_mention`, `no_page`). Page tier: the trusted page the fact came from, when it is a live fact-entity page. Mention tier: strong `extractCandidates` names plus slugs written in the text (lowercase Unicode page-slug letters without combining marks; a literal glued to further letters is not a literal), resolved through `resolveStrictEntityReference` (exact slug, unique basename, unique alias; `relink` mode adds the same-name trigram arm); exactly one entity links. Any other real name that does not resolve to the same entity (including names with no page and bare first names) vetoes the link; sentence-start capitals, weekdays/months and role terms (CEO, Q3) do not. `excludePrivate` removes private pages before uniqueness is counted. Also `appendContextNote`/`contextHead` (the `" — "` note convention), `recordedPageSlug` (page provenance of page-extraction rows only) and `isEntityInferenceEnabled` (`facts.entity_inference` kill switch for write-time inference; relink ignores it). `resolveStrictEntityReference` in `entities/resolve.ts` never guesses from a bare-name prefix and never slug-falls-back. Pinned by `test/facts-subject-infer.test.ts` (a 40+ fact labeled fixture: write precision >= 0.99, relink free tiers >= 0.95).
- `src/core/facts/conversation-subject-infer.ts` — #6764 write-time subject inference for `gbrain extract-conversation-facts` (both the classic and managed branches, trusted local only) and the free conversation relink. `inferConversationSubject` is the per-fact rule (a withdrawn claim misses as `withdrawn`); `inferConversationSubjects(engine, sourceId, visibility, rows)` gives each row the extractor left without an entity the slug `inferFactSubject` proves in `write` mode (mention tier; `excludePrivate` for world rows) plus the `entity inferred from <tier>` context note, unless `facts.entity_inference` is off or the claim was withdrawn. The row stays a derived row of the conversation page (`entity_slug` column only). Test: `test/conversation-facts-unlinked-6764.test.ts`.
-- `src/core/facts/conversation-relink.ts` — `gbrain facts relink --conversation [--source] [--slugs] [--dry-run] [--json]` (#6764, dispatched from `src/commands/facts.ts`): the free relink of the conversation extractor's unlinked derived rows, which plain relink never examines. Pages are the named `--slugs`, else the 50 with the most unlinked rows not yet tried (`conversationRelinkPages`). Each row runs `inferConversationSubject` (write mode, visibility-filtered, withdrawn claims skipped; no model). A page's links are one write: a managed brain publishes one database-only `managed_maintenance_conversation_relink` request on the anchor `.maintenance/conversation-relink` holding the page key (`prepareConversationRelink`, dispatched in `persistence/prepared-maintenance.ts`; the request id comes from the planned links, and a failed attempt retries under the next id), an unmanaged brain one `writeDerivedFacts` transaction. The write sets `entity_slug` and appends `entity relinked from <tier>` only on rows still exactly as planned (same claim, unlinked, active, target page live) and records a `linked` attempt; unresolved rows get a `conversation_unresolved` memo in `fact_relink_attempts` (reason the miss), which moves doctor `unlinked_facts` to the paid re-extraction fallback, and the report prints that command for their pages. Test: `test/conversation-relink-6764.test.ts`.
+- `src/core/facts/conversation-relink.ts` — `gbrain facts relink --conversation [--source] [--slugs] [--dry-run] [--json]` (#6764, dispatched from `src/commands/facts.ts`): the free relink of the conversation extractor's unlinked derived rows, which plain relink never examines. Pages are the named `--slugs`, else the 50 with the most unlinked rows not yet tried (`conversationRelinkPages`). Each row runs `inferConversationSubject` (write mode, visibility-filtered, withdrawn claims skipped; no model); a row the assistant or a third party said is never linked, never picks a page, and is counted as `not_user_attributed` (#7270). A page's links are one write: a managed brain publishes one database-only `managed_maintenance_conversation_relink` request on the anchor `.maintenance/conversation-relink` holding the page key (`prepareConversationRelink`, dispatched in `persistence/prepared-maintenance.ts`; the request id comes from the planned links, and a failed attempt retries under the next id), an unmanaged brain one `writeDerivedFacts` transaction. The write sets `entity_slug` and appends `entity relinked from <tier>` only on rows still exactly as planned (same claim, unlinked, active, target page live) and records a `linked` attempt; unresolved rows get a `conversation_unresolved` memo in `fact_relink_attempts` (reason the miss), which moves doctor `unlinked_facts` to the paid re-extraction fallback, and the report prints that command for their pages. Test: `test/conversation-relink-6764.test.ts`.
- `src/core/facts/conversation-memo.ts` — #6764 what makes free relink, then paid re-extraction, then linking by hand converge, all in `fact_relink_attempts`: `conversationTriedSql` (a `conversation_unresolved` memo, re-armed for the free relink by any page created in the source after it unless `RELINK_REASONS` memoizes the reason), `conversationPaidSql` and `recordReextractMemo` (tier `paid_reextract`, `target_slug` the page, `reason` its `content_hash`, keyed on the page's completion outcome row; written when an extraction of the page completes, unmanaged in `extract-conversation-facts.ts` and managed in `conversation-publication.ts` `applyEntry`). No schema change. Test: `test/conversation-memo-6764.test.ts`.
- `src/core/facts/conversation-relink-carry.ts` — #6764 how a free conversation relink survives a batch replacement: `clearConversationFacts` (conversation-publication.ts) expires the page's relinked rows (`RELINKED_DERIVED_ROW`: entity set and `entity relinked from` in the context) instead of deleting them, after deleting the previous clear's expired copies, and `inheritRelinkedEntities` gives each inserted row with no entity whose claim matches one of them that entity (live page only) and the relink note, in every insert `publishConversationFacts` makes (managed and unmanaged, replacement or addition) and in `insertGatedFacts`. One active copy, link kept. Test: `test/conversation-relink-6764.test.ts`.
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.md
index 8921fe50d4..70e4192579 100644
--- a/docs/architecture/key-files/graph-and-facts.md
+++ b/docs/architecture/key-files/graph-and-facts.md
@@ -88,7 +88,7 @@ rejection of serve-only flags before a brain opens.
- `src/core/facts/drain.ts` + `drain-scheduler.ts` + `src/core/cycle/facts-drain.ts` + `src/commands/doctor/checks/facts-drain.ts` — the automatic facts drain on PGLite (no job worker there). `runFactsDrain(engine, { owner, signal, wallClockMs })` runs queued `facts-absorb` jobs one at a time through the real handler (`withFactsAbsorbHaltCooldown(makeFactsAbsorbHandler)`), with `authorizeJobExecution`/`withSubmissionAuthority`, lock renewal, a 25 ms yield between jobs and the owner's AbortSignal forwarded into the handler. Spend runs inside one `BudgetTracker` (`facts:drain`) capped at min(`facts.drain_budget_usd` 1.00, the rest of `facts.drain_daily_budget_usd` 5.00 over a rolling 24 h); `capSource` is `user` once either cap is set, so an unpriced model warns and runs under the defaults and refuses with the `gbrain pricing set` fix under a user cap. Before each claim the job's worst case (8,000-char turn + `facts.extraction_max_tokens`) must fit; `facts.drain_max_jobs` (50) bounds a run. Every stop other than an empty queue is a deferral that leaves jobs queued with no attempt counted (`queue.deferJob`): `no_key`, `extraction_unavailable`, `budget_exhausted`, `daily_budget_exhausted`, `job_over_budget`, `no_pricing`, `provider_halted`, shutdown. Run records (newest 20, 48 h) and the first-run marker live in config `facts.drain_state`; `readFactsDrainStatus` feeds doctor `facts_drain` and the readiness capability `facts_drain`. The first run prints the backlog, estimated spend, caps and opt-out on stderr and queues a `facts_drain_first_run` notice; deferrals raise one `facts_drain_deferred` notice per reason per process (`takeFactsDrainNotice`, taken by stdio `dispatch.ts`). Never writes stdout. `startFactsDrainScheduler` owns one unref'd 10-minute timer: it runs when the owner saw no activity since the previous tick or 30 minutes passed since the last run, one run in flight, an owner veto per tick (`canRun`), the timer callback returns the tick's promise (a test awaits it), and `stop()` aborts and waits up to 5 s. Owners: stdio `serve` (`installFactsDrain`, stdin-data activity, delegated-sync veto, stopped first in the shutdown chain), `serve --http` (every tick; stopped before engine disconnect) and the cycle phase `facts_drain` (PGLite only; Postgres skips `not_applicable` for the drain). GBRA-130 C-9: before the drain, on every engine, the phase re-submits dead put_page `facts-absorb` jobs whose failure is retryable (`src/core/facts/dead-absorb-retry.ts`: provider or config class, once extraction is servable, at most hourly per key and `facts.absorb_retry.max_resubmits` times; set in config `facts.absorb_retry.state`); `gbrain facts retry-dead` lists, resets and clears it and doctor `facts_extraction_health` counts it. Test: `test/pathological/c-9-facts-absorb-dead.test.ts`. Opt-out: `facts.extraction_enabled false`. Tests: `test/facts-drain.test.ts`, `test/facts-drain-scheduler.test.ts`, `test/facts-absorb-keyless-deferral.test.ts`, the `facts_drain` row of `test/managed-phase-matrix.test.ts`.
- `src/core/facts/capture-dedup.ts` — the capture-lane (`hook:writeback`, `sweep:corpus`, `hook:compact`) duplicate policy (#5888). `cosineVerdict(source, score, claim, existing)` is the one cosine rule at every fact-write decision point (`backstop.ts` unmanaged loop, `single-prepare.ts` `decideSingleFact` and so `persistence/facts-prepare.ts` under its publication guard): explicit lanes drop at the embedding model's calibrated threshold (`supersession-threshold.ts`; none for an uncalibrated model); capture lanes never drop by cosine and return `near_duplicate` only at 0.92+ when `claimsDiverge` (negation, number, date or amount tokens) is false. `wouldDedupSamePage(ctx, existing, score, claim)` (#6333, shadow only) is the explicit-lane same-page rewording rule the backstop measures but never acts on: the nearest candidate shares the lane, `source_session` and visibility, sits at or above `SAME_PAGE_REWORDING_THRESHOLD` (0.85) and does not `claimsDiverge`; the backstop counts (`would_dedup_same_page`) and logs it, and inserts the fact as before. Its measured false positives (Lisbon→Porto) are pinned in `test/backstop-same-page-shadow-6333.test.ts` and are why no drop path ships. `dedupCapturedFacts` runs before the backstop's managed/unmanaged branch: one indexed read (`(source_id, visibility, gbrain_fact_fingerprint(fact))`, `LIMIT 50`) drops a candidate whose fingerprint matches an active fact on the same entity (or both none) or on an entity whose title/`page_aliases` the claim names (`claimNamesEntity`, whole words), visible where the candidate is (private sees world+private, world sees world), within 15 minutes of `ctx.turnAt` (else now) or written by a capture lane in the same `canonicalConversationKey` conversation (`sweep:corpus:<file>` and `.txt` stripped via `corpusFileSessionId`). Read failure keeps the candidate and warns with the lane; each drop logs lane, matched id and rule on stderr; drops and shadow near-duplicate counts append one `writeback_dedup` heartbeat event. Explicit `remember` never passes through it. `collapseHotFacts` groups hot-memory/delta rows by the SQL `fact_fingerprint` column (`FactListOpts.fingerprint`), merges different entities only when the claim names one, and keeps the newest row with `entity_slugs[]`. `collapseFactReads` (#7043) runs it per source and visibility for recall, entity cards and `saved_facts` before `limit`. The check is best-effort outside the publication transaction (two concurrent capture writers can both insert). Tests: `test/facts/capture-dedup-policy.test.ts`, `test/capture-dedup.test.ts` (unmanaged + coordinator-managed bound source; Postgres via `test/e2e/capture-dedup-postgres.test.ts`).
-- `src/core/facts/relink.ts` + `relink-publish.ts` + `relink-model.ts` + `relink-reasons.ts` + `relink-schema.ts` — `gbrain facts relink` (`src/commands/facts.ts`, CLI-only, host-only). Candidates are active database-only rows with `entity_slug IS NULL` (fence-owned subjectless rows are only counted), walked by id from `--after-id` over `idx_facts_unlinked_active`. Free tiers via `inferFactSubject`, then the model tier (`facts.extraction_model`, batches of 25, `--max-usd` BudgetTracker cap, private facts only with `--include-private`; an answer must quote the fact and pass the strict resolver). Publication is one coordinator request per entity page (`relink_facts`, dispatched from `persistence/service.ts`, managed or not): each fact's whole row is pinned by hash; prepare and the locked validation must classify identically; linked rows take fresh fence positions (row id, embedding and provenance kept, context gains `entity relinked from <tier>`) ahead of the page projection; exact duplicates retire expired and detached; nothing is superseded; withdrawn claims are skipped; attempt rows and the `decide_sweep_deferred` handoff (`enqueueRelinked`, when the conflict slot is not off) commit in the same transaction. Write target follows `persistence/fact-write-target.ts` (the remember rule): bound write-through publishes the file, write-through off or connector-database publishes the page body only, an unbound write-through source is refused as `unfenceable` (relink never claims an owner). `fact_relink_attempts` (migration v187) holds `linked`/`deduped` records and model verdict memos (`no_subject`, `ambiguous`, `unverified_match`) that stop reruns from paying again unless `--retry-model`. `RELINK_REASONS` is the one reason list (code, memoized flag, fix text) used by output, memo and the guide. Pinned by `test/facts-relink.test.ts` and `test/facts-relink-routing.test.ts` (+ `test/e2e/facts-relink-routing.test.ts`).
+- `src/core/facts/relink.ts` + `relink-publish.ts` + `relink-model.ts` + `relink-reasons.ts` + `relink-schema.ts` — `gbrain facts relink` (`src/commands/facts.ts`, CLI-only, host-only). Candidates are active database-only rows with `entity_slug IS NULL` (fence-owned subjectless rows are only counted), walked by id from `--after-id` over `idx_facts_unlinked_active`. Free tiers via `inferFactSubject`, then the model tier (`facts.extraction_model`, batches of 25, `--max-usd` cap, private facts only with `--include-private`; an answer must quote the fact and pass the strict resolver). Publication is one coordinator request per entity page (`relink_facts`, dispatched from `persistence/service.ts`, managed or not): each fact's whole row is pinned by hash; prepare and the locked validation must classify identically; linked rows take fresh fence positions (row id, embedding and provenance kept, context gains `entity relinked from <tier>`) ahead of the page projection; exact duplicates retire expired and detached; nothing is superseded; withdrawn claims and facts the user didn't say (`not_user_attributed`) are skipped; attempt rows and the `decide_sweep_deferred` handoff (`enqueueRelinked`, when the conflict slot is not off) commit in the same transaction. Write target follows `persistence/fact-write-target.ts` (the remember rule): bound write-through publishes the file, write-through off or connector-database publishes the page body only, an unbound write-through source is refused as `unfenceable` (relink never claims an owner). `fact_relink_attempts` (migration v187) holds `linked`/`deduped` records and model verdict memos (`no_subject`, `ambiguous`, `unverified_match`) stopping paid reruns unless `--retry-model`. `RELINK_REASONS` is the one reason list (code, memoized, fix) for output, memo, guide. Pinned by `test/facts-relink.test.ts` and `test/facts-relink-routing.test.ts` (+ `test/e2e/facts-relink-routing.test.ts`).
- `src/core/entity-identity.ts` + `src/core/ops/entity-identity.ts` — cross-source entity identity (cross-source federation). THE IDENTITY KEY IS `(source_id, slug)`: the same real-world entity routinely exists as a different page per mounted source, and nothing else in gbrain asserts "these pages are the same entity". The `entity_identities` table (migration v137) records that assertion explicitly — member pages grouped under an opaque `entity_id` handle (`validateEntityId`: slug-flavored, lowercase, max 128 chars), one optional canonical member per group, a page belongs to at most one identity (`UNIQUE (source_id, page_id)`; re-linking MOVES it). A link's canonical demotion and upsert run in one transaction, and re-linking with `canonical` omitted keeps the member's canonical flag within the same group (`canonical: false` demotes explicitly). Posture is MANUAL-ONLY by design: rows come exclusively from the `entity_identity_link` op — no auto-matching or name-similarity heuristics, because a wrong identity merge silently corrupts retrieval. Three ops: `entity_identity_link` / `entity_identity_unlink` (write, localOnly — merges change what retrieval unions across sources, too sharp for a remote surface) + `entity_identity_list` (read; restricts MEMBER visibility to a federated grant or remote scalar scope, while a trusted local caller sees the full cross-source group — cross-source IS the feature). Retrieval union is OFF by default behind the `entity_identity.union` config key; when on, get_links/get_backlinks merge edges from identity co-members (dedup'd), never widening past the caller's source grant. Same SQL text on both engines (parity by construction); pinned by the entity-identity test + the DATABASE_URL-gated engine-parity suite. Topology context: `docs/architecture/brains-and-sources.md`.
diff --git a/docs/guides/ambient-writeback.md b/docs/guides/ambient-writeback.md
index 61145b00db..6e3615c6b3 100644
--- a/docs/guides/ambient-writeback.md
+++ b/docs/guides/ambient-writeback.md
@@ -373,8 +373,17 @@ accordingly). Nothing is deleted or mutated; the doctor's
## Privacy and visibility
+- **What the assistant said** is saved as its own fact, never as yours. The
+ lanes that read session transcripts (the compaction harvest and the
+ SessionEnd corpus sweep) keep a claim the assistant made (a recommendation,
+ answer, plan or research result) phrased "Assistant said …" with
+ `attributed_to: assistant`, so recall can answer what the assistant told
+ you. `gbrain facts relink` never attaches such a fact, or a named third
+ party's, to an entity page, core pages included (#7270). Speaker
+ attribution is on by default; `gbrain config set facts.attribution false`
+ turns it off.
- **What is never saved:** greetings, acknowledgements, fact-free questions,
- the assistant's own inferences/diagnoses/speculation, tool output, quoted
+ the assistant's plan narration, tool output, quoted
third-party material, pasted/imported text (unless the user explicitly asks;
see [Pasted content](#pasted-content)), gbrain's own claude-cli calls,
raw transcripts, and — in every mode — secrets/credentials (banked turns are
diff --git a/docs/guides/facts-relink.md b/docs/guides/facts-relink.md
index 706cdcd0f0..e8b401c294 100644
--- a/docs/guides/facts-relink.md
+++ b/docs/guides/facts-relink.md
@@ -146,6 +146,11 @@ re-extraction for it: facts still unlinked there are listed for linking by
hand (forget each one and remember it again with `--entity`). Editing the
page's content offers the re-extraction again.
+Neither relink attaches what the assistant or a named third party said (a
+fact saved with `attributed_to` assistant or other) to an entity page. Such a
+fact is counted as `not_user_attributed` and left where it was saved: recall
+still finds it, and doctor `unlinked_facts` does not count it.
+
## Why a fact was not linked
| Reason | Remembered | What to do |
@@ -158,6 +163,7 @@ page's content offers the re-extraction again.
| `model_unavailable` | no | The extraction model could not be reached. Configure it with gbrain config set facts.extraction_model <provider:model>. To skip the model tier, run gbrain facts relink --no-llm. |
| `model_unparseable` | no | The model returned output relink could not read. Rerun; if it persists, set a different facts.extraction_model. |
| `withdrawn` | no | This claim was explicitly forgotten for that entity, so relink will not attach it there. |
+| `not_user_attributed` | no | The fact records what the assistant or a third party said, not your own claim, so relink never attaches it to an entity page. Nothing to fix: it stays saved and recall still finds it. |
| `page_file_missing` | no | The entity page exists in the database but its file is missing from the source tree. Restore the file or run gbrain sync, then rerun. |
| `unfenceable` | no | The source writes through to files but has no canonical owner. Bind the source (gbrain sources writer status <source> --json, then gbrain sources writer claim <source> --path <checkout> --admin-intent writer_claim --expected-state <admin_state>), then rerun. |
| `fence_malformed` | no | The entity page has a ## Facts fence that cannot be normalized. Preview the fence repair of that page (`repair fences --slug <entity-slug>` on the brain host; read-only, and it names the exact edit for anything it will not repair), apply it, then rerun. |
diff --git a/scripts/postgres-arm-weights.json b/scripts/postgres-arm-weights.json
index 2dacde56b8..870d273886 100644
--- a/scripts/postgres-arm-weights.json
+++ b/scripts/postgres-arm-weights.json
@@ -356,6 +356,7 @@
"test/recall-collapse-duplicates-7043.test.ts": 9000,
"test/recall-page-fill.test.ts": 7056,
"test/receipt-compaction-newest-sync-gbra130.test.ts": 6880,
+ "test/relink-attribution-7270.test.ts": 6564,
"test/remediation-manual-only.test.ts": 14638,
"test/repair-apply-pending-6543.test.ts": 51967,
"test/repair-duplicate-facts-7043.test.ts": 9000,
@@ -376,6 +377,7 @@
"test/search/rerank-gate-hybrid.test.ts": 5329,
"test/search/rerank-gate-telemetry.test.ts": 6264,
"test/serve-head-watcher-managed.serial.test.ts": 9589,
+ "test/session-start-hook-dedupe-7026.test.ts": 5265,
"test/shared-content-freshness.test.ts": 7925,
"test/shared-skills-catalog.test.ts": 69906,
"test/shared-skills-retention-capacity.test.ts": 9839,
@@ -430,6 +432,7 @@
"test/trust-guarded-supersession.test.ts": 14873,
"test/trust-held-removals.test.ts": 20034,
"test/trust-owner-actions.test.ts": 9037,
+ "test/turn-context-dedupe-attribution-7023.test.ts": 5917,
"test/unbound-source-6536.test.ts": 8308,
"test/unindexed-files.test.ts": 10784,
"test/vector-manifest-probe-bound.test.ts": 22324,
diff --git a/src/commands/doctor/checks/unlinked-facts.ts b/src/commands/doctor/checks/unlinked-facts.ts
index 9ab6ba0b92..2a419fd570 100644
--- a/src/commands/doctor/checks/unlinked-facts.ts
+++ b/src/commands/doctor/checks/unlinked-facts.ts
@@ -23,10 +23,13 @@
* unlinked. Every query is bounded by created_at
* through idx_facts_since (source_id, created_at DESC WHERE expired_at IS
* NULL) or by primary key; without fact_relink_attempts (a brain before
- * v187) the relink figures are omitted and nothing is excluded.
+ * v187) the relink figures are omitted and nothing is excluded. A fact the
+ * assistant or a third party said is never counted (#7270): relink never
+ * attaches it to an entity page, so it is not a fact waiting for a link.
*/
import type { BrainEngine } from '../../../core/engine.ts';
import { AUDIT_ROW_SOURCES } from '../../../core/facts/audit-sources.ts';
+import { ENTITY_LINKABLE_SQL } from '../../../core/facts/attribution.ts';
import type { Check } from '../../doctor.ts';
import type { Action } from '../../../core/agent-output.ts';
import { doctorVerify } from '../check-fix.ts';
@@ -61,7 +64,7 @@ export interface UnlinkedFactsStats {
relinked_7d: Record<string, number> | null;
}
-const ACTIVE = `f.expired_at IS NULL AND (f.valid_until IS NULL OR f.valid_until > now()) AND f.source <> ALL($2::text[])`;
+const ACTIVE = `f.expired_at IS NULL AND (f.valid_until IS NULL OR f.valid_until > now()) AND f.source <> ALL($2::text[]) AND ${ENTITY_LINKABLE_SQL}`;
const ORIGIN = `CASE WHEN ${DERIVED} THEN 'conversation' WHEN f.source = 'mcp:put_page' THEN 'mcp:put_page'
WHEN f.source LIKE 'mcp:%' OR f.source LIKE 'sync:%' OR f.source LIKE 'hook:%' OR f.source IN ('file_upload', 'code_import') THEN 'extraction'
ELSE 'remember' END`;
diff --git a/src/commands/facts.ts b/src/commands/facts.ts
index 53bd90cd6a..dae98f1781 100644
--- a/src/commands/facts.ts
+++ b/src/commands/facts.ts
@@ -152,6 +152,7 @@ export function formatRelinkReport(report: RelinkReport, args: string[]): string
export function formatConversationRelinkReport(r: ConversationRelinkReport, args: string[]): string {
const lines = [`${r.dry_run ? 'DRY RUN: would link' : 'Linked'} ${r.linked} conversation fact(s) on ${r.pages.length} page(s) in source ${r.source_id}`
+ ` (mention tier, no model call); ${r.unresolved} unresolved${r.changed ? `; ${r.changed} changed before the write (run again)` : ''}.`];
+ if (r.not_user_attributed) lines.push(` not_user_attributed: ${r.not_user_attributed}. ${RELINK_REASONS.not_user_attributed.fix}`);
for (const p of r.pages) lines.push(` ${p.slug}: ${p.linked} linked, ${p.unresolved} unresolved`);
if (r.dry_run && r.linked) lines.push(`Apply with:\n gbrain facts relink ${args.filter(a => a !== '--dry-run').join(' ')}`);
if (r.reextract_slugs.length) {
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 371127f62e..2396c9d8fe 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1078,6 +1078,12 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: 'TBD', text: 'New explicit repair `gbrain repair duplicate-facts` (#7043): it previews each group of active facts of one source, visibility and speaker that share a fingerprint and the oldest row it keeps, and after `--apply --expect <hash> --yes` marks every other copy superseded by that row (`expired_at` and `superseded_by`; never deleted or withdrawn). Groups spread over several entities are reported as `cross_entity` and retired only with `--include-cross-entity`. Fenced copies are struck in their page as `superseded by #N` through a revision-bound page write when the kept row shares the fence, and are reported as `fence_kept_elsewhere` otherwise; copies on a segmented page are kept and reported as `segmented_page`. Near duplicates are never touched, and nothing runs on upgrade.' },
{ since: 'TBD', text: 'New config key `cycle.conversation_facts_backfill.exclude_sources` (#7043): a JSON array or comma list of source ids the conversation facts backfill phase skips, so one source can be left out without turning the phase off. Unset (the default) skips nothing; the phase result reports `sources_excluded`.' },
{ since: '0.60.347.0', text: '`gbrain embed --facts` no longer fails a whole batch, and every later run, on one fact longer than the embedding input limit: that fact is skipped (never truncated), keeps its text and stays stale, and the result reports it (`refused_oversized`, `refused_samples` with fact ids, `refused_fix`) without counting it in `remaining` or against `--max-facts`. Doctor `fact_take_vectors` adds `facts.oversized`, and `gbrain embed --held` lists them. Shorten or split the fact, or withdraw it with `gbrain forget <fact-id>`, and the next run embeds it once it fits.' },
+ // #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.
+ { since: 'TBD', text: 'In Claude Code, the first prompt of a session no longer repeats the hot-memory facts the session-start block already showed: the user-prompt hook now reads the `gbrain hook session-start` output Claude Code records as a SessionStart `hook_success` entry, from the gbrain context envelope on, so core memory printed before it does not hide page pointers. SessionStart output from other tools is still ignored (#7026, reported by @benswinney).' },
+ // #7270 (GBRA-60). `since` is restamped at the merge slot.
+ { since: 'TBD', text: '`gbrain facts relink` and `gbrain facts relink --conversation` no longer attach a fact the assistant or a named third party said (`attributed_to` assistant or other) to an entity page, core pages included: such a fact is left where it was saved, recall still finds it, and the run counts it as `not_user_attributed`. Before, the SessionEnd corpus sweep saved the assistant\'s own report about a page, and every relink pinned it onto that page. Doctor `unlinked_facts` no longer counts these facts. Rows linked before this release stay linked; `gbrain forget <fact-id>` removes one (#7270, reported by @andrew-agents-bot).' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/context/turn-context.ts b/src/core/context/turn-context.ts
index 5092e1afd9..bdc7c693b5 100644
--- a/src/core/context/turn-context.ts
+++ b/src/core/context/turn-context.ts
@@ -408,11 +408,13 @@ export async function assembleTurnContext(
withheldFacts += hot?.suppressed?.withheld ?? 0;
const all = Array.isArray(hot?.facts) ? [...hot.facts] : [];
// Cross-turn dedupe, same contract as volunteered pages: a fact already
- // injected this session is not repeated. Matched without the trailing
- // confidence, which drifts as facts age.
+ // injected this session is not repeated. The key is the line render()
+ // emits (renderFactLine: attribution, label or data envelope included),
+ // without the trailing confidence, which drifts as facts age. Its
+ // unlabeled form still matches, so a fact injected before labels (or
+ // before its tier changed) stays injected.
const prior = opts.priorContextText;
- // The trust label is not part of the match: a fact injected before labels (or before its tier changed) stays injected.
- return prior ? all.filter((f) => !prior.includes(renderFactLine({ ...f, trust_tier: undefined }).replace(/ \([0-9.]+\)$/, ' (').slice(2))) : all;
+ return prior ? all.filter((f) => !factDedupeKeys(f).some((k) => prior.includes(k))) : all;
} catch {
return [];
}
@@ -505,13 +507,7 @@ function render(
lines.push(`- **${v.display}** → \`${v.slug}\` (${v.confidence.toFixed(2)}, ${v.rationale})${syn}`);
}
}
- if (facts.length) {
- lines.push('', '## Hot memory (recent facts)');
- for (const f of facts) {
- const ent = f.entity_slug ? ` [${f.entity_slug}]` : '';
- lines.push(`- ${f.trust_tier ? renderTrustedInline(neutralizeForPrompt(f.fact).text, labelOf(f)) : neutralizeForPrompt(f.fact).text}${ent} (${f.confidence.toFixed(2)})`);
- }
- }
+ if (facts.length) lines.push('', '## Hot memory (recent facts)', ...facts.map(renderFactLine));
return lines.join('\n');
}
@@ -918,6 +914,9 @@ export const renderThreadLine = (t: EntityOpenThread): string =>
`- [${t.kind}] ${labeled(t, t.text)}${t.date ? ` (${t.date})` : ''}`;
export const renderFactLine = (f: TurnContextFact): string =>
`- ${f.attributed_to === 'assistant' ? '(assistant said) ' : ''}${labeled(f, neutralizeForPrompt(f.fact).text)}${f.entity_slug ? ` [${f.entity_slug}]` : ''} (${f.confidence.toFixed(2)})`;
+/** #7023: the substrings that mark a fact as already injected: its rendered line, then its unlabeled form, each without the "- " bullet and the confidence. */
+const factDedupeKeys = (f: TurnContextFact): string[] =>
+ [f, { ...f, trust_tier: undefined }].map((g) => renderFactLine(g).slice(2).replace(/ \([0-9.]+\)$/, ' ('));
export const renderPageLine = (p: DeltaPage): string => `- **${labeled(p, p.title)}** → \`${p.slug}\` (${p.updated_at})`;
/** One card's newer-mentions block: a line naming the entity and its page date, then one line per page. [] when there are none. */
diff --git a/src/core/facts/attribution.ts b/src/core/facts/attribution.ts
index 72da49ea4f..b965de2e54 100644
--- a/src/core/facts/attribution.ts
+++ b/src/core/facts/attribution.ts
@@ -12,6 +12,15 @@
*/
import type { FactAttribution } from '../engine.ts';
+/**
+ * #7270: whether relink may attach a fact to an entity page. Only the user's
+ * own claim, or one with no recorded speaker, is linked; an assistant's or a
+ * named third party's claim stays where it was saved and is still recalled.
+ */
+export const entityLinkable = (a: FactAttribution | null | undefined): boolean => !a || a === 'user';
+/** `entityLinkable` as a SQL predicate on the facts alias `f`. */
+export const ENTITY_LINKABLE_SQL = `(f.attributed_to IS NULL OR f.attributed_to = 'user')`;
+
export function attributionCompatible(a: FactAttribution | null | undefined, b: FactAttribution | null | undefined): boolean {
return !a || !b || a === b;
}
diff --git a/src/core/facts/conversation-relink.ts b/src/core/facts/conversation-relink.ts
index 5ab794721c..88f4509ff7 100644
--- a/src/core/facts/conversation-relink.ts
+++ b/src/core/facts/conversation-relink.ts
@@ -20,9 +20,11 @@
* `fact_relink_attempts` (operational, like relink's model verdict memos), so
* doctor `unlinked_facts` offers it the paid re-extraction fallback instead
* of this relink again; conversation-memo.ts says which misses a new page
- * re-arms and how the paid attempt is remembered. Trusted local CLI only.
+ * re-arms and how the paid attempt is remembered. A row the assistant or a
+ * third party said is never linked (#7270): it is counted, left unlinked, and
+ * never picks a page for a run. Trusted local CLI only.
*/
-import type { BrainEngine } from '../engine.ts';
+import type { BrainEngine, FactAttribution } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
import type { PreparedMutation } from '../persistence/coordinator.ts';
import type { WriteRequest } from '../persistence/model.ts';
@@ -39,6 +41,7 @@ import { AUDIT_ROW_SOURCES } from './audit-sources.ts';
import { CONVERSATION_UNRESOLVED } from './relink-reasons.ts';
import { conversationTriedSql } from './conversation-memo.ts';
import { appendContextNote } from './subject-infer.ts';
+import { ENTITY_LINKABLE_SQL, entityLinkable } from './attribution.ts';
import { inferConversationSubject } from './conversation-subject-infer.ts';
export const CONVERSATION_RELINK_INTENT = 'managed_maintenance_conversation_relink';
@@ -51,13 +54,15 @@ export const derivedConversationRow = (audit: string) => `f.source LIKE 'cli:ext
const ACTIVE = 'f.entity_slug IS NULL AND f.expired_at IS NULL AND (f.valid_until IS NULL OR f.valid_until > now())';
export interface ConversationRelinkRow { id: number; fact: string; entity_slug: string; context: string }
-interface PagePlan { slug: string; link: ConversationRelinkRow[]; misses: Array<{ id: number; reason: string }> }
+interface PagePlan { slug: string; link: ConversationRelinkRow[]; misses: Array<{ id: number; reason: string }>; notUserAttributed: number }
export interface ConversationRelinkReport {
source_id: string;
dry_run: boolean;
- pages: Array<{ slug: string; linked: number; unresolved: number; changed: number }>;
+ pages: Array<{ slug: string; linked: number; unresolved: number; changed: number; not_user_attributed: number }>;
linked: number;
unresolved: number;
+ /** #7270: rows the assistant or a third party said, left unlinked (never attached to an entity page). */
+ not_user_attributed: number;
/** Planned links whose row moved before the write (left for the next run). */
changed: number;
/** Pages still holding unresolved rows: the paid re-extraction fallback names them. */
@@ -74,21 +79,22 @@ export async function conversationRelinkPages(engine: BrainEngine, sourceId: str
const untried = await hasAttemptsTable(engine)
? `AND NOT ${conversationTriedSql}` : '';
const rows = await engine.executeRaw<{ slug: string }>(
- `SELECT f.source_markdown_slug AS slug FROM facts f WHERE f.source_id = $1 AND f.source_markdown_slug IS NOT NULL AND ${ACTIVE}
+ `SELECT f.source_markdown_slug AS slug FROM facts f WHERE f.source_id = $1 AND f.source_markdown_slug IS NOT NULL AND ${ACTIVE} AND ${ENTITY_LINKABLE_SQL}
AND ${derivedConversationRow('$2')} ${untried}
GROUP BY f.source_markdown_slug ORDER BY COUNT(*) DESC, f.source_markdown_slug LIMIT $3`, [sourceId, [...AUDIT_ROW_SOURCES], limit]);
return rows.map(r => r.slug);
}
async function planPages(engine: BrainEngine, sourceId: string, slugs: string[]): Promise<PagePlan[]> {
- const rows = await engine.executeRaw<{ id: number | string; fact: string; context: string | null; visibility: FactVisibility; slug: string }>(
- `SELECT f.id, f.fact, f.context, f.visibility, f.source_markdown_slug AS slug FROM facts f
+ const rows = await engine.executeRaw<{ id: number | string; fact: string; context: string | null; visibility: FactVisibility; slug: string; attributed_to: FactAttribution | null }>(
+ `SELECT f.id, f.fact, f.context, f.visibility, f.source_markdown_slug AS slug, f.attributed_to FROM facts f
WHERE f.source_id = $1 AND f.source_markdown_slug = ANY($2::text[]) AND ${ACTIVE} AND ${derivedConversationRow('$3')}
ORDER BY f.source_markdown_slug, f.id`, [sourceId, slugs, [...AUDIT_ROW_SOURCES]]);
const pages = new Map<string, PagePlan>();
for (const row of rows) {
- const page = pages.get(row.slug) ?? { slug: row.slug, link: [], misses: [] };
+ const page = pages.get(row.slug) ?? { slug: row.slug, link: [], misses: [], notUserAttributed: 0 };
pages.set(row.slug, page);
+ if (!entityLinkable(row.attributed_to)) { page.notUserAttributed++; continue; }
const inferred = await inferConversationSubject(engine, sourceId, row.visibility, row.fact);
if (inferred.slug === null) page.misses.push({ id: Number(row.id), reason: inferred.reason });
else page.link.push({ id: Number(row.id), fact: row.fact, entity_slug: inferred.slug, context: appendContextNote(row.context, `entity relinked from ${inferred.via}`) });
@@ -103,7 +109,7 @@ async function linkRows(tx: BrainEngine, sourceId: string, slug: string, rows: C
for (const row of rows) {
const done = await tx.executeRaw<{ id: number | string }>(
`UPDATE facts f SET entity_slug = $4, context = $5 WHERE f.source_id = $1 AND f.id = $2 AND f.source_markdown_slug = $3 AND f.fact = $6
- AND ${ACTIVE} AND ${derivedConversationRow('$7')}
+ AND ${ACTIVE} AND ${ENTITY_LINKABLE_SQL} AND ${derivedConversationRow('$7')}
AND EXISTS (SELECT 1 FROM pages p WHERE p.source_id = $1 AND p.slug = $4 AND p.deleted_at IS NULL) RETURNING f.id`,
[sourceId, row.id, slug, row.entity_slug, row.context, row.fact, [...AUDIT_ROW_SOURCES]]);
if (!done.length) continue;
@@ -144,7 +150,7 @@ export async function runConversationRelink(engine: BrainEngine, config: GBrainC
opts: { sourceId: string; slugs?: string[]; dryRun?: boolean }): Promise<ConversationRelinkReport> {
const slugs = opts.slugs?.length ? opts.slugs : await conversationRelinkPages(engine, opts.sourceId);
const plans = await planPages(engine, opts.sourceId, slugs);
- const report: ConversationRelinkReport = { source_id: opts.sourceId, dry_run: !!opts.dryRun, pages: [], linked: 0, unresolved: 0, changed: 0, reextract_slugs: [] };
+ const report: ConversationRelinkReport = { source_id: opts.sourceId, dry_run: !!opts.dryRun, pages: [], linked: 0, unresolved: 0, not_user_attributed: 0, changed: 0, reextract_slugs: [] };
const authority = opts.dryRun ? null : await maintenancePreflight(engine, opts.sourceId);
const memo = !opts.dryRun && await hasAttemptsTable(engine);
for (const page of plans) {
@@ -159,9 +165,10 @@ export async function runConversationRelink(engine: BrainEngine, config: GBrainC
ON CONFLICT (source_id, fact_id) DO UPDATE SET outcome = EXCLUDED.outcome, reason = EXCLUDED.reason, tier = 'mention',
model = NULL, target_slug = NULL, run_id = NULL, attempted_at = EXCLUDED.attempted_at`, [opts.sourceId, miss.id, CONVERSATION_UNRESOLVED, miss.reason]);
const changed = page.link.length - linked;
- report.pages.push({ slug: page.slug, linked, unresolved: page.misses.length, changed });
+ report.pages.push({ slug: page.slug, linked, unresolved: page.misses.length, changed, not_user_attributed: page.notUserAttributed });
report.linked += linked;
report.unresolved += page.misses.length;
+ report.not_user_attributed += page.notUserAttributed;
report.changed += changed;
if (page.misses.length) report.reextract_slugs.push(page.slug);
}
diff --git a/src/core/facts/relink-reasons.ts b/src/core/facts/relink-reasons.ts
index c2662731d5..2cd4afacca 100644
--- a/src/core/facts/relink-reasons.ts
+++ b/src/core/facts/relink-reasons.ts
@@ -13,6 +13,7 @@ export const RELINK_REASONS = {
model_unavailable: { memoized: false, fix: 'The extraction model could not be reached. Configure it with gbrain config set facts.extraction_model <provider:model>. To skip the model tier, run gbrain facts relink --no-llm.' },
model_unparseable: { memoized: false, fix: 'The model returned output relink could not read. Rerun; if it persists, set a different facts.extraction_model.' },
withdrawn: { memoized: false, fix: 'This claim was explicitly forgotten for that entity, so relink will not attach it there.' },
+ not_user_attributed: { memoized: false, fix: 'The fact records what the assistant or a third party said, not your own claim, so relink never attaches it to an entity page. Nothing to fix: it stays saved and recall still finds it.' },
page_file_missing: { memoized: false, fix: 'The entity page exists in the database but its file is missing from the source tree. Restore the file or run gbrain sync, then rerun.' },
unfenceable: { memoized: false, fix: 'The source writes through to files but has no canonical owner. Bind the source (gbrain sources writer status <source> --json, then gbrain sources writer claim <source> --path <checkout> --admin-intent writer_claim --expected-state <admin_state>), then rerun.' },
fence_malformed: { memoized: false, fix: 'The entity page has a ## Facts fence that cannot be normalized. Preview the fence repair of that page (`repair fences --slug <entity-slug>` on the brain host; read-only, and it names the exact edit for anything it will not repair), apply it, then rerun.' },
diff --git a/src/core/facts/relink.ts b/src/core/facts/relink.ts
index 383e468766..59e10b760a 100644
--- a/src/core/facts/relink.ts
+++ b/src/core/facts/relink.ts
@@ -12,9 +12,10 @@
*/
import { randomUUID } from 'node:crypto';
-import type { BrainEngine } from '../engine.ts';
+import type { BrainEngine, FactAttribution } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
import { inferFactSubject, recordedPageSlug } from './subject-infer.ts';
+import { entityLinkable } from './attribution.ts';
import { RELINK_REASONS, type RelinkReason } from './relink-reasons.ts';
import { estimateModelTokens, judgeBatch, MODEL_BATCH_SIZE, type ModelVerdict } from './relink-model.ts';
import { relinkFactHash, submitRelinkGroup, type RelinkIntentFact } from './relink-publish.ts';
@@ -73,7 +74,7 @@ export interface RelinkReport {
examples: Record<string, Example[]>;
}
-interface Candidate { id: number; fact: string; visibility: 'private' | 'world'; context: string | null; source: string | null }
+interface Candidate { id: number; fact: string; visibility: 'private' | 'world'; context: string | null; source: string | null; attributed_to: FactAttribution | null }
interface Planned { id: number; slug: string; tier: RelinkTier; model: string | null }
const MODEL_VERDICT_SKIP = new Set<string>(['no_subject', 'ambiguous', 'unverified_match']);
@@ -90,7 +91,7 @@ function emptyReport(opts: RelinkOptions, runId: string): RelinkReport {
export async function loadRelinkCandidates(engine: BrainEngine, opts: RelinkOptions): Promise<{ rows: Candidate[]; hasMore: boolean }> {
const limit = opts.limit ?? RELINK_DEFAULT_LIMIT;
const rows = await engine.executeRaw<Candidate & { id: number | string }>(
- `SELECT id, fact, visibility, context, source FROM facts
+ `SELECT id, fact, visibility, context, source, attributed_to FROM facts
WHERE source_id = $1 AND entity_slug IS NULL AND expired_at IS NULL
AND row_num IS NULL AND source_markdown_slug IS NULL
AND (valid_until IS NULL OR valid_until > now())
@@ -130,6 +131,11 @@ export async function runFactsRelink(engine: BrainEngine, opts: RelinkOptions):
const leftovers: Array<Candidate & { freeReason: RelinkReason; resolved: string[] }> = [];
for (const [i, c] of rows.entries()) {
opts.signal?.throwIfAborted();
+ if (!entityLinkable(c.attributed_to)) {
+ skip('not_user_attributed', c);
+ opts.onProgress?.(i + 1, rows.length);
+ continue;
+ }
const r = await inferFactSubject(engine, opts.sourceId, { fact: c.fact, pageSlug: recordedPageSlug(c.context, c.source), mode: 'relink' });
if (r.slug !== null) planned.push({ id: c.id, slug: r.slug, tier: r.via, model: null });
else leftovers.push({ ...c, freeReason: r.reason, resolved: r.resolved });
diff --git a/src/core/transcripts/claude-code-jsonl.ts b/src/core/transcripts/claude-code-jsonl.ts
index da1cc7f972..5853d7ca31 100644
--- a/src/core/transcripts/claude-code-jsonl.ts
+++ b/src/core/transcripts/claude-code-jsonl.ts
@@ -222,10 +222,13 @@ export interface ParsedTranscript {
* newest. Claude Code records a UserPromptSubmit hook's additionalContext
* as a structured `{"type":"attachment","attachment":{"type":
* "hook_additional_context","content":[...]}}` line (verified live against
- * claude CLI 2.1.224). Selected structurally — never by substring matching
- * over raw turn text, which would over-suppress short slugs appearing in
- * tool payloads. The user-prompt hook feeds these back as priorContextText
- * so a page is volunteered once per session, not once per mention.
+ * claude CLI 2.1.224), and a SessionStart hook's stdout as an attachment
+ * `{"type":"hook_success","hookEvent":"SessionStart","content":"<stdout>"}`,
+ * kept from gbrain's envelope on (#7026). Selected structurally — never by
+ * substring matching over raw turn text, which would over-suppress short
+ * slugs appearing in tool payloads. The user-prompt hook feeds these back
+ * as priorContextText so a page is volunteered once per session, not once
+ * per mention.
*/
injectedContextBlocks: string[];
/** Bytes actually read (== min(file size, maxBytes)). */
@@ -444,7 +447,7 @@ const GBRAIN_BLOCK_MARKERS = [
/**
* One transcript line → a previously-injected GBRAIN context block, or null.
- * See ParsedTranscript.injectedContextBlocks for the recorded shape.
+ * See ParsedTranscript.injectedContextBlocks for the recorded shapes.
*/
function entryToInjectedBlock(entry: unknown): string | null {
if (typeof entry !== 'object' || entry === null) return null;
@@ -453,6 +456,15 @@ function entryToInjectedBlock(entry: unknown): string | null {
const att = e.attachment;
if (typeof att !== 'object' || att === null) return null;
const a = att as Record<string, unknown>;
+ // #7026: `gbrain hook session-start` prints plain stdout, recorded as a
+ // SessionStart hook_success whose `content` is that stdout. Only the part
+ // from gbrain's envelope on is an injected block: the core memory and
+ // digest printed before it must not suppress pointers for the session.
+ if (a.type === 'hook_success') {
+ if (a.hookEvent !== 'SessionStart' || typeof a.content !== 'string') return null;
+ const at = a.content.indexOf(GBRAIN_BLOCK_MARKERS[0]);
+ return at < 0 ? null : a.content.slice(at).trim();
+ }
if (a.type !== 'hook_additional_context' || !Array.isArray(a.content)) return null;
const text = (a.content as unknown[]).filter((c): c is string => typeof c === 'string').join('\n').trim();
if (!text) return null;
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 19d51d6d28..94292e25a3 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -374,6 +374,7 @@ test/purge-sync-tombstone-hold-7130.test.ts
test/recall-collapse-duplicates-7043.test.ts
test/recall-page-fill.test.ts
test/receipt-compaction-newest-sync-gbra130.test.ts
+test/relink-attribution-7270.test.ts
test/remediation-manual-only.test.ts
test/repair-apply-pending-6543.test.ts
test/repair-duplicate-facts-7043.test.ts
@@ -394,6 +395,7 @@ test/search/page-rank-cut.test.ts
test/search/rerank-gate-hybrid.test.ts
test/search/rerank-gate-telemetry.test.ts
test/serve-head-watcher-managed.serial.test.ts
+test/session-start-hook-dedupe-7026.test.ts
test/shared-content-freshness.test.ts
test/shared-skills-catalog.test.ts
test/shared-skills-retention-capacity.test.ts
@@ -452,6 +454,7 @@ test/trust-channel-writes.test.ts
test/trust-guarded-supersession.test.ts
test/trust-held-removals.test.ts
test/trust-owner-actions.test.ts
+test/turn-context-dedupe-attribution-7023.test.ts
test/unbound-source-6536.test.ts
test/unindexed-files.test.ts
test/vector-manifest-probe-bound.test.ts
diff --git a/test/relink-attribution-7270.test.ts b/test/relink-attribution-7270.test.ts
new file mode 100644
index 0000000000..b9b8f7ae5a
--- /dev/null
+++ b/test/relink-attribution-7270.test.ts
@@ -0,0 +1,105 @@
+/**
+ * #7270: relink never attaches what the assistant (or a named third party)
+ * said to an entity page. The SessionEnd corpus sweep saves the assistant's
+ * own report about a pinned core page as attributed facts; `gbrain facts
+ * relink` and `gbrain facts relink --conversation` used to link every one
+ * that named the page, so the core page filled up with the agent's
+ * commentary on every run. Such a row now stays where it was saved, is
+ * counted as not_user_attributed, and doctor unlinked_facts does not count it.
+ */
+import { afterAll, afterEach, 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 { GBrainConfig } from '../src/core/config.ts';
+import { persistencePostgresTemplate } from './helpers/persistence-postgres.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { runFactsRelink } from '../src/core/facts/relink.ts';
+import { runConversationRelink } from '../src/core/facts/conversation-relink.ts';
+import { unlinkedFactsStats } from '../src/commands/doctor/checks/unlinked-facts.ts';
+import { parseFactsFence } from '../src/core/facts-fence.ts';
+
+const CORE = 'core/current-focus';
+const MEETING = 'meetings/2026-10-20-focus-check';
+const config = { engine: 'pglite', embedding_disabled: true } as unknown as GBrainConfig;
+
+let engine: BrainEngine;
+
+async function seedCorePage() {
+ await importFromContent(engine, CORE, `---\ntitle: Current Focus\ntype: project\ncore: true\n---\n\n# Current Focus\n\nShip the launch.\n`, { noEmbed: true });
+}
+async function sweptFact(fact: string, attributed_to: 'user' | 'assistant' | 'other' | null): Promise<number> {
+ const r = await engine.insertFact({ fact, kind: 'fact', entity_slug: null, visibility: 'world', source: 'sweep:corpus', attributed_to } as never, { source_id: 'default' });
+ return r.id;
+}
+const factRow = async (id: number) => (await engine.executeRaw<{ entity_slug: string | null; source_markdown_slug: string | null; context: string | null }>(
+ 'SELECT entity_slug, source_markdown_slug, context FROM facts WHERE id = $1', [id]))[0]!;
+async function coreFenceClaims(): Promise<string[]> {
+ const page = await engine.getPage(CORE, { sourceId: 'default' });
+ return parseFactsFence(page!.compiled_truth).facts.map(f => f.claim);
+}
+
+for (const backend of testBackends()) {
+ describe(backend, () => {
+ let pglite: PGLiteEngine | undefined;
+ let template: Awaited<ReturnType<typeof persistencePostgresTemplate>> | undefined;
+ let close: (() => Promise<void>) | undefined;
+ beforeAll(async () => {
+ if (backend === 'postgres') template = await persistencePostgresTemplate(requirePostgresTestDatabase());
+ else { pglite = new PGLiteEngine(); await pglite.connect({}); await pglite.initSchema(); }
+ }, 120_000);
+ afterAll(async () => { await template?.dispose(); await pglite?.disconnect(); });
+ beforeEach(async () => {
+ if (pglite) { engine = pglite; await resetPgliteState(pglite); }
+ else { const c = await template!.clone(); engine = c.engine; close = c.close; }
+ await engine.setConfig('decide.slots.conflict.mode', 'off');
+ await seedCorePage();
+ }, 60_000);
+ afterEach(async () => { if (close) { await disposePersistenceConsumer(engine); await close(); close = undefined; } });
+
+ test('facts relink leaves assistant and third-party facts off the core page and counts them', async () => {
+ const assistant = await sweptFact(`${CORE} says the launch is the priority; I recommend keeping it`, 'assistant');
+ const other = await sweptFact(`Beta Example said ${CORE} should drop the launch`, 'other');
+ const user = await sweptFact(`${CORE} now includes the pricing review`, 'user');
+ const report = await runFactsRelink(engine, { sourceId: 'default', config, llm: false });
+
+ expect(await coreFenceClaims()).toEqual([`${CORE} now includes the pricing review`]);
+ for (const id of [assistant, other]) expect(await factRow(id)).toEqual({ entity_slug: null, source_markdown_slug: null, context: null });
+ expect((await factRow(user)).entity_slug).toBe(CORE);
+ expect(report.linked).toBe(1);
+ expect(report.skipped.not_user_attributed).toBe(2);
+
+ const again = await runFactsRelink(engine, { sourceId: 'default', config, llm: false });
+ expect(again.linked).toBe(0);
+ expect(await coreFenceClaims()).toEqual([`${CORE} now includes the pricing review`]);
+ });
+
+ test('conversation relink leaves an assistant-attributed derived row unlinked and counts it', async () => {
+ await engine.putPage(MEETING, { type: 'meeting' as never, title: 'Focus check', compiled_truth: 'notes', timeline: '', frontmatter: { date: '2026-10-20' } });
+ const row = (n: number, fact: string, attributed: string | null) => engine.executeRaw(
+ `INSERT INTO facts (source_id, entity_slug, fact, source, context, row_num, source_markdown_slug, created_at, valid_from, attributed_to)
+ VALUES ('default', NULL, $1, 'cli:extract-conversation-facts', $2, $3, $4, now(), now(), $5)`, [fact, `from ${MEETING} segment 2026-10-20`, n, MEETING, attributed]);
+ await row(0, `${CORE} is on track, the assistant reported`, 'assistant');
+ await row(1, `The owner moved ${CORE} to the pricing review`, 'user');
+ const report = await runConversationRelink(engine, config, { sourceId: 'default' });
+
+ const rows = await engine.executeRaw<{ fact: string; entity_slug: string | null }>(
+ 'SELECT fact, entity_slug FROM facts WHERE source_markdown_slug = $1 ORDER BY row_num', [MEETING]);
+ expect(rows.map(r => r.entity_slug)).toEqual([null, CORE]);
+ expect(report).toMatchObject({ linked: 1, unresolved: 0, not_user_attributed: 1 });
+
+ const rerun = await runConversationRelink(engine, config, { sourceId: 'default' });
+ expect(rerun.pages).toEqual([]);
+ });
+
+ test('doctor unlinked_facts does not count facts relink will never link', async () => {
+ await sweptFact(`${CORE} says the launch is the priority; I recommend keeping it`, 'assistant');
+ await sweptFact(`Beta Example said ${CORE} should drop the launch`, 'other');
+ await sweptFact('An unattributed note with no entity', null);
+ const stats = await unlinkedFactsStats(engine, ['default']);
+ expect(stats!.new_7d).toMatchObject({ facts: 1, unlinked: 1 });
+ });
+ });
+}
diff --git a/test/session-start-hook-dedupe-7026.test.ts b/test/session-start-hook-dedupe-7026.test.ts
new file mode 100644
index 0000000000..fb0769b3be
--- /dev/null
+++ b/test/session-start-hook-dedupe-7026.test.ts
@@ -0,0 +1,112 @@
+/**
+ * #7026 part 1: Claude Code records `gbrain hook session-start` stdout as a
+ * SessionStart `hook_success` attachment, not as hook_additional_context.
+ * The parser keeps that block (from gbrain's envelope on) as an injected
+ * block, so the first prompt's turn context does not repeat the facts the
+ * session-start pack already showed, and core memory printed before the
+ * envelope does not suppress pointers. Other tools' SessionStart output is
+ * never dedupe input.
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { persistencePostgresTemplate } from './helpers/persistence-postgres.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { parseTranscript } from '../src/core/transcripts/claude-code-jsonl.ts';
+import { assembleContextPack, assembleTurnContext, TURN_CONTEXT_ENVELOPE } from '../src/core/context/turn-context.ts';
+import { composeSessionStartOutput } from '../src/core/context/session-start-output.ts';
+import { __resetHotMemoryCacheForTests } from '../src/core/facts/meta-hook.ts';
+
+const CORE = '## Core memory\n- Bob Example owns the roadmap (people/bob-example)';
+const PACK = `${TURN_CONTEXT_ENVELOPE}\n\n## Hot memory (recent facts)\n- SESSION-FACT the deploy window is tuesday [companies/acme-example] (0.90)`;
+
+const sessionStartLine = (hookEvent: string, content: string) => JSON.stringify({
+ parentUuid: null, isSidechain: false, type: 'attachment', sessionId: 'sess-7026',
+ attachment: { type: 'hook_success', hookName: `${hookEvent}:startup`, toolUseID: 'tool-1', hookEvent, content, stdout: content, stderr: '', exitCode: 0, command: 'hook', durationMs: 12 },
+});
+const userLine = (text: string) => JSON.stringify({ type: 'user', message: { role: 'user', content: text } });
+
+let dir: string;
+beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'gb-7026-')); });
+afterEach(() => { rmSync(dir, { recursive: true, force: true }); });
+function transcript(lines: string[]): string {
+ const p = join(dir, 'session.jsonl');
+ writeFileSync(p, lines.join('\n') + '\n');
+ return p;
+}
+
+describe('#7026 SessionStart hook_success is an injected block', () => {
+ test('gbrain session-start output is kept from the envelope on; a foreign SessionStart output is excluded', () => {
+ const p = transcript([
+ sessionStartLine('SessionStart', 'project-sync: repo is 2 commits behind; see companies/acme-example'),
+ sessionStartLine('SessionStart', composeSessionStartOutput(CORE, ['MEMORY digest line', PACK])),
+ userLine('hello'),
+ ]);
+ const r = parseTranscript(p);
+ expect(r.injectedContextBlocks).toEqual([PACK]);
+ expect(r.turns.map((t) => t.text)).toEqual(['hello']);
+ });
+
+ test('a hook_success from another event carrying the envelope is not a session-start block', () => {
+ const p = transcript([sessionStartLine('PostToolUse', PACK), userLine('hello')]);
+ expect(parseTranscript(p).injectedContextBlocks).toEqual([]);
+ });
+});
+
+for (const backend of testBackends()) {
+ describe(`#7026 end to end (${backend})`, () => {
+ let engine: BrainEngine;
+ let pglite: PGLiteEngine | undefined;
+ let template: Awaited<ReturnType<typeof persistencePostgresTemplate>> | undefined;
+ let close: (() => Promise<void>) | undefined;
+ beforeAll(async () => {
+ if (backend === 'postgres') template = await persistencePostgresTemplate(requirePostgresTestDatabase());
+ else { pglite = new PGLiteEngine(); await pglite.connect({}); await pglite.initSchema(); }
+ }, 120_000);
+ afterAll(async () => { await template?.dispose(); await pglite?.disconnect(); });
+ beforeEach(async () => {
+ __resetHotMemoryCacheForTests();
+ // Targeted deletes, not resetPgliteState: that also empties trust_policy_state, and hot memory reads nothing without its row.
+ if (pglite) { engine = pglite; await engine.executeRaw('DELETE FROM facts'); await engine.executeRaw('DELETE FROM pages'); }
+ else { const c = await template!.clone(); engine = c.engine; close = c.close; }
+ }, 60_000);
+ afterEach(async () => { if (close) { await disposePersistenceConsumer(engine); await close(); close = undefined; } });
+
+ test('a fact the session-start pack showed is not rendered again by the first turn context', async () => {
+ await engine.executeRaw(
+ `INSERT INTO pages (slug, source_id, type, title, compiled_truth, timeline) VALUES ($1, 'default', 'person', $2, $3, '')`,
+ ['people/bob-example', 'Bob Example', 'Bob Example owns the roadmap at acme-example.'],
+ );
+ const fact = 'SESSION-FACT the deploy window is tuesday';
+ await engine.insertFact(
+ { fact, kind: 'fact', entity_slug: 'companies/acme-example', source: 'test', visibility: 'world' },
+ { source_id: 'default' },
+ );
+ const pack = await assembleContextPack(engine, { sourceId: 'default', sessionId: 'sess-7026' });
+ expect(pack.factsCount).toBe(1);
+ expect(pack.text).toContain(fact);
+
+ const p = transcript([
+ sessionStartLine('SessionStart', composeSessionStartOutput(CORE, ['MEMORY digest line', pack.text])),
+ userLine('what is Bob Example working on'),
+ ]);
+ const parsed = parseTranscript(p);
+ __resetHotMemoryCacheForTests();
+ const turn = await assembleTurnContext(engine, {
+ sourceId: 'default',
+ sessionId: 'sess-7026',
+ window: parsed.turns,
+ priorContextText: parsed.injectedContextBlocks.join('\n\n'),
+ });
+ expect(turn.factsCount).toBe(0);
+ expect(turn.text).not.toContain(fact);
+ // Core memory sits before the envelope, so its slug does not suppress the pointer.
+ expect(turn.pointers.map((x) => x.slug)).toContain('people/bob-example');
+ expect(parsed.injectedContextBlocks).toEqual([pack.text]);
+ });
+ });
+}
diff --git a/test/turn-context-dedupe-attribution-7023.test.ts b/test/turn-context-dedupe-attribution-7023.test.ts
new file mode 100644
index 0000000000..7a437c7d07
--- /dev/null
+++ b/test/turn-context-dedupe-attribution-7023.test.ts
@@ -0,0 +1,90 @@
+/**
+ * #7023: the per-turn block renders each hot fact with the shared
+ * renderFactLine, and the cross-turn dedupe key is that rendered line, so an
+ * assistant-attributed or external_untrusted fact injected once this session
+ * is not injected on every later prompt, and an assistant claim keeps its
+ * `(assistant said)` prefix instead of reading as the user's.
+ */
+import { afterAll, afterEach, 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 { persistencePostgresTemplate } from './helpers/persistence-postgres.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { assembleTurnContext, renderFactLine, type TurnContextFact } from '../src/core/context/turn-context.ts';
+import { __resetHotMemoryCacheForTests } from '../src/core/facts/meta-hook.ts';
+
+let engine: BrainEngine;
+
+const ASSISTANT_FACT = 'ASSISTANT-FACT the launch moves to acme-example week';
+const EXTERNAL_FACT = 'EXTERNAL-FACT the vendor invoice is due monthly';
+
+async function seedHotFacts() {
+ await engine.insertFact(
+ { fact: ASSISTANT_FACT, kind: 'fact', entity_slug: 'people/alice-example', source: 'test', visibility: 'world', attributed_to: 'assistant' },
+ { source_id: 'default' },
+ );
+ const ext = await engine.insertFact(
+ { fact: EXTERNAL_FACT, kind: 'fact', entity_slug: 'companies/acme-example', source: 'test', visibility: 'world' },
+ { source_id: 'default' },
+ );
+ await engine.executeRaw(`UPDATE facts SET trust_tier = 'external_untrusted' WHERE id = $1`, [ext.id]);
+}
+
+const factLines = (text: string) => text.split('\n').filter((l) => l.includes('-FACT '));
+
+for (const backend of testBackends()) {
+ describe(backend, () => {
+ let pglite: PGLiteEngine | undefined;
+ let template: Awaited<ReturnType<typeof persistencePostgresTemplate>> | undefined;
+ let close: (() => Promise<void>) | undefined;
+ beforeAll(async () => {
+ if (backend === 'postgres') template = await persistencePostgresTemplate(requirePostgresTestDatabase());
+ else { pglite = new PGLiteEngine(); await pglite.connect({}); await pglite.initSchema(); }
+ }, 120_000);
+ afterAll(async () => { await template?.dispose(); await pglite?.disconnect(); });
+ beforeEach(async () => {
+ __resetHotMemoryCacheForTests();
+ // Targeted deletes, not resetPgliteState: that also empties trust_policy_state, and hot memory reads nothing without its row.
+ if (pglite) { engine = pglite; await engine.executeRaw('DELETE FROM facts'); await engine.executeRaw('DELETE FROM pages'); }
+ else { const c = await template!.clone(); engine = c.engine; close = c.close; }
+ }, 60_000);
+ afterEach(async () => { if (close) { await disposePersistenceConsumer(engine); await close(); close = undefined; } });
+
+ test('the first block keeps the assistant prefix and wraps the external fact as data', async () => {
+ await seedHotFacts();
+ const first = await assembleTurnContext(engine, { sourceId: 'default', window: [] });
+ expect(first.factsCount).toBe(2);
+ const lines = factLines(first.text);
+ expect(lines.length).toBe(2);
+ expect(lines.find((l) => l.includes(ASSISTANT_FACT))!.startsWith('- (assistant said) ')).toBe(true);
+ const external = lines.find((l) => l.includes(EXTERNAL_FACT))!;
+ expect(external.startsWith('- <external-data trust="external_untrusted"')).toBe(true);
+ expect(external).toContain(`${EXTERNAL_FACT}</external-data> [companies/acme-example] (`);
+ });
+
+ test('assistant-attributed and external_untrusted facts injected once are not injected again', async () => {
+ await seedHotFacts();
+ const first = await assembleTurnContext(engine, { sourceId: 'default', window: [] });
+ expect(first.factsCount).toBe(2);
+ __resetHotMemoryCacheForTests();
+ const next = await assembleTurnContext(engine, {
+ sourceId: 'default',
+ window: [{ role: 'user', text: 'no entities here, just vibes' }],
+ priorContextText: first.text,
+ });
+ expect(next.factsCount).toBe(0);
+ expect(next.text).not.toContain(ASSISTANT_FACT);
+ expect(next.text).not.toContain(EXTERNAL_FACT);
+ });
+
+ test('a fact injected before labels existed still matches its unlabeled line', async () => {
+ await seedHotFacts();
+ const unlabeled = (fact: string, slug: string, attributed_to?: TurnContextFact['attributed_to']) =>
+ renderFactLine({ id: 0, fact, kind: 'fact', entity_slug: slug, confidence: 0.5, attributed_to });
+ const prior = [unlabeled(ASSISTANT_FACT, 'people/alice-example', 'assistant'), unlabeled(EXTERNAL_FACT, 'companies/acme-example')].join('\n');
+ const next = await assembleTurnContext(engine, { sourceId: 'default', window: [], priorContextText: prior });
+ expect(next.factsCount).toBe(0);
+ });
+ });
+}