Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
docs+guards: lane A notes, KEY_FILES entries, size ratchets; N8 tests on both engines
garrytan269a97c5622f
diff --git a/docs/architecture/conversation-parser-patterns.md b/docs/architecture/conversation-parser-patterns.mdindex 22dca7e57c..23b06093b1 100644--- a/docs/architecture/conversation-parser-patterns.md+++ b/docs/architecture/conversation-parser-patterns.md@@ -137,7 +137,7 @@ formats:- `**Speaker** (09:15): text` uses `bold-paren-time`.- `**Speaker** (9:15 AM): text` uses `bold-paren-time-12h`.-- `**Speaker:** text` uses `bold-name-no-time`.+- `**Speaker:** text` uses `bold-name-no-time`. Its `repeat_speaker_min_turns: 3` structure gate returns no_match when three or more turns never repeat a speaker — a status note's `**Status:**`/`**Owner:**`/`**Next step:**` labels are not a conversation (gbrain-evals N12-1).- `**Speaker** (2026-04-09 9:15 AM): text` uses `imessage-slack`.Keeping these examples in both `test_negative` and parser regression tests makesdiff --git a/docs/architecture/key-files/core-services-1.md b/docs/architecture/key-files/core-services-1.mdindex 0c84c7c7d9..72aacbea87 100644--- a/docs/architecture/key-files/core-services-1.md+++ b/docs/architecture/key-files/core-services-1.md@@ -41,6 +41,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/connectors/` (directory) — the LIVE chat-history connector layer (front-end to the transcripts pipeline). `types.ts`: the `ChatHistoryProvider` contract (mirror of `TranscriptAdapter` — leaf module per provider; `spoolFormat` names the adapter that parses its output; dated `HostSpecTarget`). `credentials.ts`: file-plane store at `~/.gbrain/connectors/<provider>.json` (0600, dir 0700, atomic tmp+rename), env-above-file `resolveCredential` returning `{cred, source}`; credentials NEVER touch the DB / `sources.config` / config planes / op payloads. `classify.ts`: the pure §2A/§2B response classifier — distinguishes a Cloudflare-fingerprint 403 (`forbidden_fingerprint`, dead-end) from an auth-expired 403 (`auth_required`, re-auth) and flags a parses-but-no-`items` body as `drift`. `client.ts`: `ConnectorClient` modeled on `GitHubClient` (plain fetch against a hardcoded ORIGIN + off-origin guard so the cookie/bearer never leaks, browser UA, refresh-once-on-401, Retry-After backoff; `fetchImpl`/`sleep`/`now` injectable — NOT `fetchWithSSRFGuard`, which breaks SNI on Cloudflare hosts). `providers/chatgpt.ts` + `providers/claude.ts` (registry in `registry.ts`; Perplexity deliberately absent — no adapter): offset/updated pagination with a per-pass 500-page cap and a `stopBefore` watermark break, epoch/ISO normalization, ChatGPT's `is_archived` second pass, Claude's `chat_conversations` paged with `limit`/`offset` across every chat-capable org (conversations fetched from the org that listed them; timestamps normalized with ChatGPT's `toIso`), a ChatGPT walk that steps back when `total` shrinks mid-walk (a removal shifts later items to lower offsets) and yields each id once across both passes, content-block text assembly for Claude, and a `refreshAccessToken` (ChatGPT re-mints from the cookie via `/api/auth/session`; Claude's cookie is terminal). `spool.ts`: writes fetched conversations in native-export shape (0600, batched, pruned in the orchestrator `finally`). `sync.ts`: `runConnectorSync` — resolve credential → probe → read the **per-(provider, source) config-scalar watermark** `connectors.<p>.source.<id>.watermark_iso` (NOT op_checkpoint, whose 7-day GC would wipe it → full re-fetch) → list to `watermark − windowDays` → skip stubs whose `updatedAt` the source's `synced` ledger already holds and stubs quarantined in its `failed` ledger (after `QUARANTINE_ATTEMPTS` = 3 fetch OR ingest failures at one `updatedAt`; ingest outcomes are attributed per conversation by session id, a spool-file-level failure fails the batch; an edit or `--full` retries) BEFORE the `--limit` cap, so capped runs progress → fetch → spool → `runTranscriptsIngest` → record each successfully ingested conversation as synced → advance the watermark ONLY on a clean run (quarantined ids no longer block it; ledger entries older than the next list window are pruned) → `logIngest` receipt → stamp per-source `last_sync_at` → engine-branched embed kickoff (`maybeKickoffEmbed`: Postgres `submitEmbedBackfill`, PGLite `runEmbedCore` inline — NEVER `submitEmbedBackfill`, which refuses `no_worker_surface`). `config-keys.ts`: the `connectors.` key builders (sync progress keyed by `(provider, source)`; `auth_error_at` stays per provider because it describes the shared credential), `readConnectorState`/`writeConnectorState` (a legacy per-provider `watermark_iso`/`last_sync_at` is honored only for the scheduled `connectors.source_id` source until that source writes its own key, which retires it), and the pure `isConnectorSyncStale(last, now, floor)` dispatch gate. Status, doctor and the autopilot gate read the scheduled source's state. `oauth-pkce.ts`: dependency-free S256 PKCE loopback (`Bun.serve`, timing-safe state) — best-effort `--try-oauth` only. Surfaces: the `connectors_status`/`connector_sync` ops (`src/core/ops/connectors.ts`, both `localOnly`), the `gbrain connectors` command family (`src/commands/connectors/` peeled dir), the `connector-sync` minion handler (`src/core/minions/handlers/connector-sync.ts`, single-flight lock), the autopilot `maybeDispatchConnectorSyncs` gate, and the `connectors` doctor check. Pinned by `test/connectors-*.test.ts` + `test/e2e/connectors-sync-checkpoints-pglite.test.ts` (per-source watermark, `--limit` progress, quarantine, retitle) + `test/e2e/connectors-sync-pglite.test.ts` (full pipeline against a `Bun.serve` fixture backend, keyless) + `test/e2e/connector-sync-handler-pglite.test.ts` + `test/e2e/doctor-connectors-pglite.test.ts`.-- `src/core/context/` — Retrieval Reflex (Layer 1). `entity-salience.ts`: pure, zero-LLM, precision-biased `extractCandidates(text)` (capitalized runs + `@handles`, STOPWORDS + soft COMMON_WORDS + sentence-start guard, deterministic, capped; a lowercase weak pass additionally emits `weak: true` candidates — lowercase words ≥3 chars on a separate `MAX_WEAK_CANDIDATES=32` budget that never evicts strong candidates — which downstream may resolve through the alias arm ONLY) + `extractCandidatesFromWindow(turns)` (merges per-turn extraction across the last N turns by normalizeAlias form with occurrence/newest-turn/user-mention metadata; salience-ordered — recency > frequency > user-role — so the cap drops stale assistant chatter first). `retrieval-reflex.ts`: `resolveEntitiesToPointers(engine, sourceId, candidates, opts)` — alias arm (`resolveAliases`, caught per-arm for pre-v110 brains) + exact title/slug-suffix arm (real slugs are namespaced `people/x` but `slugify` drops the prefix) + two lexical identity arms behind `opts.lexicalArms` (kill switch: config `retrieval_reflex_lexical_arms` / env `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS`, default on): weak lowercase candidates probe the ALIAS arm ONLY (never title/slug-suffix, where ordinary lowercase words would fabricate pointers) and require GLOBAL uniqueness across all sources in play; the surname arm resolves a strong single capitalized token ≥3 chars via a `lower(title) LIKE '% <token>'` predicate on the same query, with exact-arm precedence and ambiguity counted over ALL person rows carrying the surname — ambiguity in either arm injects nothing; pointers carry `source_id`/`arm`/`confidence`/`matchedNorm` (`ARM_CONFIDENCE` alias 0.9 / title 0.8 / title-surname 0.72 (deliberately above the volunteer layer's 0.70 gate, below title) / slug-suffix 0.6 lives next to the arm definitions; arm-2 provenance classified in JS since the combined OR can't report which predicate matched); opts: `sourceIds?` federated scope (alias arm loops per source, arm 2 uses `source_id = ANY`), `suppression?` ('slug-and-title' default; 'slug-only' REQUIRED under windowing — the title rule would suppress every entity merely mentioned in a prior window turn), ambient-channel event logging is DELIVERY-side, not in-resolver — `logDeliveredReflexPointers(engine, pointers)` fires only once a block is actually handed to the consumer (serve's resolve-IPC `onDelivered` hook post-write; `buildReflexAddition` post-timeout on the direct rung), so abandoned/timed-out blocks never pollute the volunteered-vs-used stats; its event write is registered synchronously before return so the CLI background-work drain cannot miss it; synopsis runs through `stripTakesFence`/`stripFactsFence` (the same privacy boundary `get_page` applies) so private facts never reach the prompt; capped at `MAX_POINTERS`. `reflex.ts`: the orchestrator + engine-aware resolver ladder (host `resolveEntities` → PGLite serve IPC → Postgres cached process-singleton → disabled), zero-candidate fast path, fail-open + timeout, heartbeat write for the doctor check, `reflexEnabled(cfg)` (file/env gate, default ON; DB-plane does NOT gate — `assemble()` is sync); windowed extraction when `windowTurns` present and `retrieval_reflex_window_turns` (default 4; 1 = single-turn behavior) > 1 — switches suppression to slug-only; accept-side reflex-channel logging fires after the per-turn timeout admits the block (direct-Postgres rung only — IPC logs server-side at delivery; host-injected resolvers are a documented gap). `resolve-ipc.ts`: local unix-socket resolve protocol (client + server) so PGLite resolves through the single connection `gbrain serve` holds (a second opener would hit the exclusive lock; a subprocess would force-steal it past the 5-min staleness window and crash). Wired into both serve transports via `src/mcp/resolve-ipc-binding.ts` (engine-uniform; socket + secret keyed off `hash12(database_url)` under `~/.gbrain/run`, cleaned up on shutdown). Doctor surface: `retrieval_reflex_health` in `src/commands/doctor/checks/verbs-reflex.ts` (reads the heartbeat for truthful runtime status; categorized in `doctor-categories.ts`) + `volunteer_channels` (engine-aware sibling: groups `context_volunteer_events` by channel over 7 days so operators see which push channels — reflex/op/watch/claude-code/codex — actually fire; info-only; the LOCAL doctor runs it brain-wide while the remote report path threads the caller's source scope, so a source-bound token never sees other sources' activity counts/timestamps; counts are reconciled against the hook heartbeat over the same 7-day window — a mostly-degraded week gets a CAUTION note, since a server-side delivery count isn't proof of injection; quiet-channel guidance is engine-aware — Postgres brains are told the hook lane is quiet by design rather than to chase registration — and walks both quiet classes (installed-but-unregistered vs registered-but-quiet; the check can't inspect registration itself); pre-v117 tolerant, and transient DB errors are reported as such, never as an old schema; pinned by `test/doctor-volunteer-channels.test.ts`). Config: `retrieval_reflex` + `retrieval_reflex_max_pointers` + `retrieval_reflex_window_turns` + `retrieval_reflex_lexical_arms` in `src/core/config.ts` (env `GBRAIN_RETRIEVAL_REFLEX_WINDOW_TURNS`, `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS`). `volunteer.ts`: `parseWindow` (lenient `user:`/`assistant:` prefixes, unprefixed → one user turn), `volunteerContext` (extract → resolve → +0.05 multi-turn/newest-turn boost → `min_confidence` 0.7 gate → cap 3/5; deterministic rationale strings, never raw conversation text; slug-only suppression), `volunteerUsageStats` (per-arm/channel precision from the `pages.last_retrieved_at > volunteered_at` join — APPROXIMATE: the 5-min last-retrieved throttle causes false negatives, unrelated reads false positives). `volunteer-events.ts`: `insertVolunteerEvents` (ONE multi-row parameterized INSERT), `logVolunteerEventsFireAndForget` + bounded drain registered as the `volunteer-events` background-work sink (order 4), `purgeStaleVolunteerEvents` (90-day GC, called from the dream cycle's purge phase). Policy layer ships as the `retrieval-reflex` recipe (`recipes/retrieval-reflex/`). Pinned by `test/context/entity-salience.test.ts`, `test/retrieval-reflex.test.ts`, `test/retrieval-reflex-pre-v110.test.ts`, `test/context/resolve-ipc.test.ts`, `test/doctor-retrieval-reflex.test.ts`, `test/volunteer-context.test.ts`, `test/e2e/volunteer-context-postgres.test.ts`. Checkpoint-compaction modules in this dir: `corpus-segments.ts` — engine-free content-addressed compaction segments (`<session>.seg-<hash24>.txt`, idempotent by name; parsers accept 12–64 hex), the hash-keyed per-session ledger (atomic tmp+rename, fail-open, entry order = the only ordinal), `sliceBoundaryWindow`/`splitByBoundaries`, the redacted `renderSegmentText` (a segment is NEVER written unscanned — unlike the session-end full write, which degrades-and-writes), exact-set `coverageComplete`/`decideCorpusMode` (count equality can be fooled by a duplicated boundary), the compact-time `bankCompactSegment` step (per-step deadline degrades, segment-then-ledger crash order), the openclaw tail boundary reader (`readOpenclawBoundaryTail`, delegates mapping to the adapter's exported `mapOpenclawLine`; also returns turn-stamped `toolCalls`/`toolCallTurnIndexes` for the Memorable receipt — name-only v1, `input: null` by design until an observation run characterizes OpenClaw's args field), and orphan-sidecar/aged-ledger GC — pinned by `test/corpus-segments.test.ts`. `checkpoint-harvest.ts` — the serve-side prompt harvest of a segment: bounded FIFO (cap 8, 60s abort), sweep-shared claim fencing, capability-then-kill-switch gates, `signal.aborted` POST-check (the pipeline returns partials on abort; an aborted run writes nothing and stays retryable), receipt sidecar before idempotent manifest publish (source-scoped `getPage` verification — a link that resolves to nothing is never banked), `.ingested` last, explicit `shutdownCheckpointHarvest()` called by serve BEFORE `engine.disconnect()` (the background-work drain is CLI-exit-only by contract) — pinned by `test/checkpoint-harvest.serial.test.ts`. `hook-heartbeat.ts` — the hooks telemetry JSONL extracted from hook.ts (hook.ts re-exports; serve-side writers never import the command module); allowlist carries the checkpoint `segment`/`inserted`/`duplicate`/`links` count-only fields. `session-state.ts` also carries the v132 `checkpoint_manifest` helpers (`getCheckpointManifest`/`appendCheckpointManifest`: newest-first, dedup-by-slug, cap 20, seg-hash completion key, fail-open on pre-v132 schema) — pinned by `test/checkpoint-manifest.test.ts`. `sensitivity-scan.ts` + `compile-view.ts` — the compile-context stack: composed detector (secret-scan + ordered `PII_PATTERNS` + path/blocklist families + operator pattern file; uniform `.gbrain-scan-allow` fingerprint escape hatch; CONTENT hits drop an entry, CONFIG/loader failures THROW so the caller aborts without writing) and the deterministic compiled-view builder (recency decay anchored to the newest candidate `updated_at`, never wall-clock; total-order (score desc, slug asc); source-scoped listPages/getPage reads that skip op-layer write-backs; whole-file `packToBudget` math that never passes a <=0 budget) — pinned by `test/sensitivity-scan.test.ts` + `test/compile-view.test.ts` + `test/e2e/compile-context-pglite.test.ts`; the CLI shell is `src/commands/compile-context.ts` (targets claude-code|codex|openclaw, AGENTS.md managed-marker splice that throws on damaged markers, atomic writes, `--check` recompile-and-compare exit codes; the guide is `docs/guides/checkpoint-compaction.md`). It also owns the whole Memorable seam's engine-free plumbing: the session-receipt JSONL (`session-receipts.jsonl`, `appendSessionReceipt` — dedup by post-redaction `content_hash` so a resumed session neither duplicates its receipt nor re-fires the relay; tail-rewrite compaction triggered by the 32 MB byte ceiling alone — the read fires exactly when the pass will act, with the 2000-line budget enforced inside the pass — and a `skipCompaction` seam the openclaw compact() lane sets unconditionally: the hook lane is the ONE receipts compactor, so two processes can never race the read-filter-rename rewrite); ONE bounded adaptive `readJsonlTail` reader shared by `lastReceiptMatches`, `lastRelayResult` and `readSessionReceiptsTail` (a receipt line can exceed the 1 MB window — the window doubles rather than reading "empty"); `maybeTrimRelayResults` (BOTH capture lanes trim the child-appended `memorable-relay.jsonl` — an openclaw-only host has no hook lane, and converging newest-keeping trims make concurrent trims safe: mtime-stale preferred, hard 8 MB force backstop, line-boundary cut keeping the newest lines — the child appends open-by-path, so the residual loss window is one in-flight write); the CONSENT STAMP (`memorable-consent.json`, 0600, written ONLY by config-set's disclosure flow — deliberately outside config.json, which the external CLI full-file-rewrites; scope-bound to the disclosure sha256 + `MEMORABLE_CAPTURE_HARNESSES`, so widening the capture surface invalidates old stamps); `memorableGateAllowed(cfg)` ({allowed, reason: kill_switch|disabled|disclosure_missing} — one reason vocabulary for hook, context-engine and doctor); `memorableConsentEvidence()` (the CLI-side opt-in read fail-closed from ~/.memorable/config.json, dated provisional spec note, GBRAIN_MEMORABLE_CONFIG test seam); `redactedToolCallsJson` (the security-load-bearing span-filter + highEntropy redaction, ONE implementation for both capture lanes; string LEAVES are redacted raw before serialization — scanning the serialized JSON would let quoted secrets through via \" escaping — with a post-serialization re-scan as belt-and-braces); `recordAndRelayReceipt` (per-receipt harness scope-binding first — a harness outside `MEMORABLE_CAPTURE_HARNESSES` is refused with `memorable_harness_undisclosed` → receipt → prior-run outcome surfacing with the child's reason clamped via the shared `clampRelayCause` (32 chars, so the 16-char prefix keeps composites inside the 48-char reason bound) and appended LAST → consent evidence → `resolveMemorableBin` → detached spawn; never throws; `spawnFn` test seam); and `priorRelayFailure`, which surfaces the PREVIOUS relay run's self-reported exit status so a relay that records nothing is never reported healthy. `resolveMemorableBin` does the pre-spawn PATH/`MEMORABLE_BIN` resolution so a missing CLI is a named heartbeat reason rather than a silent async ENOENT.+- `src/core/context/` — Retrieval Reflex (Layer 1). `entity-salience.ts`: pure, zero-LLM, precision-biased `extractCandidates(text)` (capitalized runs + `@handles`, STOPWORDS + soft COMMON_WORDS + sentence-start guard, deterministic, capped; a lowercase weak pass additionally emits `weak: true` candidates — lowercase words ≥3 chars on a separate `MAX_WEAK_CANDIDATES=32` budget that never evicts strong candidates — which downstream may resolve through the alias arm ONLY) + `extractCandidatesFromWindow(turns)` (merges per-turn extraction across the last N turns by normalizeAlias form with occurrence/newest-turn/user-mention metadata; salience-ordered — recency > frequency > user-role — so the cap drops stale assistant chatter first). `retrieval-reflex.ts`: `resolveEntitiesToPointers(engine, sourceId, candidates, opts)` — alias arm (`resolveAliases`, caught per-arm for pre-v110 brains) + exact title/slug-suffix arm (real slugs are namespaced `people/x` but `slugify` drops the prefix) + two lexical identity arms behind `opts.lexicalArms` (kill switch: config `retrieval_reflex_lexical_arms` / env `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS`, default on): weak lowercase candidates probe the ALIAS arm ONLY (never title/slug-suffix, where ordinary lowercase words would fabricate pointers) and require GLOBAL uniqueness across all sources in play; the surname arm resolves a strong single capitalized token ≥3 chars via a `lower(title) LIKE '% <token>'` predicate on the same query, with exact-arm precedence and ambiguity counted over ALL person rows carrying the surname — ambiguity in either arm injects nothing; pointers carry `source_id`/`arm`/`confidence`/`matchedNorm` (`ARM_CONFIDENCE` alias 0.9 / title 0.8 / title-surname 0.72 (deliberately above the volunteer layer's 0.70 gate, below title) / slug-suffix 0.6 lives next to the arm definitions; arm-2 provenance classified in JS since the combined OR can't report which predicate matched); opts: `sourceIds?` federated scope (alias arm loops per source, arm 2 uses `source_id = ANY`), `suppression?` ('slug-and-title' default; 'slug-only' REQUIRED under windowing — the title rule would suppress every entity merely mentioned in a prior window turn), ambient-channel event logging is DELIVERY-side, not in-resolver — `logDeliveredReflexPointers(engine, pointers)` fires only once a block is actually handed to the consumer (serve's resolve-IPC `onDelivered` hook post-write; `buildReflexAddition` post-timeout on the direct rung), so abandoned/timed-out blocks never pollute the volunteered-vs-used stats; its event write is registered synchronously before return so the CLI background-work drain cannot miss it; synopsis runs through `stripTakesFence`/`stripFactsFence` (the same privacy boundary `get_page` applies) so private facts never reach the prompt; `visibility: private` (and derived-private) pages never resolve on any arm unless the caller passes `excludePrivate: false` (default true, the remote-search predicate `privatePagesFilterFragment`; only `volunteer_context` widens, via `resolveExcludePrivatePages` for a trusted local caller — gbrain-evals N8-1/N8-2, pinned by `test/reflex-private-visibility.test.ts`); capped at `MAX_POINTERS`. `reflex.ts`: the orchestrator + engine-aware resolver ladder (host `resolveEntities` → PGLite serve IPC → Postgres cached process-singleton → disabled), zero-candidate fast path, fail-open + timeout, heartbeat write for the doctor check, `reflexEnabled(cfg)` (file/env gate, default ON; DB-plane does NOT gate — `assemble()` is sync); windowed extraction when `windowTurns` present and `retrieval_reflex_window_turns` (default 4; 1 = single-turn behavior) > 1 — switches suppression to slug-only; accept-side reflex-channel logging fires after the per-turn timeout admits the block (direct-Postgres rung only — IPC logs server-side at delivery; host-injected resolvers are a documented gap). `resolve-ipc.ts`: local unix-socket resolve protocol (client + server) so PGLite resolves through the single connection `gbrain serve` holds (a second opener would hit the exclusive lock; a subprocess would force-steal it past the 5-min staleness window and crash). Wired into both serve transports via `src/mcp/resolve-ipc-binding.ts` (engine-uniform; socket + secret keyed off `hash12(database_url)` under `~/.gbrain/run`, cleaned up on shutdown). Doctor surface: `retrieval_reflex_health` in `src/commands/doctor/checks/verbs-reflex.ts` (reads the heartbeat for truthful runtime status; categorized in `doctor-categories.ts`) + `volunteer_channels` (engine-aware sibling: groups `context_volunteer_events` by channel over 7 days so operators see which push channels — reflex/op/watch/claude-code/codex — actually fire; info-only; the LOCAL doctor runs it brain-wide while the remote report path threads the caller's source scope, so a source-bound token never sees other sources' activity counts/timestamps; counts are reconciled against the hook heartbeat over the same 7-day window — a mostly-degraded week gets a CAUTION note, since a server-side delivery count isn't proof of injection; quiet-channel guidance is engine-aware — Postgres brains are told the hook lane is quiet by design rather than to chase registration — and walks both quiet classes (installed-but-unregistered vs registered-but-quiet; the check can't inspect registration itself); pre-v117 tolerant, and transient DB errors are reported as such, never as an old schema; pinned by `test/doctor-volunteer-channels.test.ts`). Config: `retrieval_reflex` + `retrieval_reflex_max_pointers` + `retrieval_reflex_window_turns` + `retrieval_reflex_lexical_arms` in `src/core/config.ts` (env `GBRAIN_RETRIEVAL_REFLEX_WINDOW_TURNS`, `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS`). `volunteer.ts`: `parseWindow` (lenient `user:`/`assistant:` prefixes, unprefixed → one user turn), `volunteerContext` (extract → resolve → +0.05 multi-turn/newest-turn boost → `min_confidence` 0.7 gate → cap 3/5; deterministic rationale strings, never raw conversation text; slug-only suppression), `volunteerUsageStats` (per-arm/channel precision from the `pages.last_retrieved_at > volunteered_at` join — APPROXIMATE: the 5-min last-retrieved throttle causes false negatives, unrelated reads false positives). `volunteer-events.ts`: `insertVolunteerEvents` (ONE multi-row parameterized INSERT), `logVolunteerEventsFireAndForget` + bounded drain registered as the `volunteer-events` background-work sink (order 4), `purgeStaleVolunteerEvents` (90-day GC, called from the dream cycle's purge phase). Policy layer ships as the `retrieval-reflex` recipe (`recipes/retrieval-reflex/`). Pinned by `test/context/entity-salience.test.ts`, `test/retrieval-reflex.test.ts`, `test/retrieval-reflex-pre-v110.test.ts`, `test/context/resolve-ipc.test.ts`, `test/doctor-retrieval-reflex.test.ts`, `test/volunteer-context.test.ts`, `test/e2e/volunteer-context-postgres.test.ts`. Checkpoint-compaction modules in this dir: `corpus-segments.ts` — engine-free content-addressed compaction segments (`<session>.seg-<hash24>.txt`, idempotent by name; parsers accept 12–64 hex), the hash-keyed per-session ledger (atomic tmp+rename, fail-open, entry order = the only ordinal), `sliceBoundaryWindow`/`splitByBoundaries`, the redacted `renderSegmentText` (a segment is NEVER written unscanned — unlike the session-end full write, which degrades-and-writes), exact-set `coverageComplete`/`decideCorpusMode` (count equality can be fooled by a duplicated boundary), the compact-time `bankCompactSegment` step (per-step deadline degrades, segment-then-ledger crash order), the openclaw tail boundary reader (`readOpenclawBoundaryTail`, delegates mapping to the adapter's exported `mapOpenclawLine`; also returns turn-stamped `toolCalls`/`toolCallTurnIndexes` for the Memorable receipt — name-only v1, `input: null` by design until an observation run characterizes OpenClaw's args field), and orphan-sidecar/aged-ledger GC — pinned by `test/corpus-segments.test.ts`. `checkpoint-harvest.ts` — the serve-side prompt harvest of a segment: bounded FIFO (cap 8, 60s abort), sweep-shared claim fencing, capability-then-kill-switch gates, `signal.aborted` POST-check (the pipeline returns partials on abort; an aborted run writes nothing and stays retryable), receipt sidecar before idempotent manifest publish (source-scoped `getPage` verification — a link that resolves to nothing is never banked), `.ingested` last, explicit `shutdownCheckpointHarvest()` called by serve BEFORE `engine.disconnect()` (the background-work drain is CLI-exit-only by contract) — pinned by `test/checkpoint-harvest.serial.test.ts`. `hook-heartbeat.ts` — the hooks telemetry JSONL extracted from hook.ts (hook.ts re-exports; serve-side writers never import the command module); allowlist carries the checkpoint `segment`/`inserted`/`duplicate`/`links` count-only fields. `session-state.ts` also carries the v132 `checkpoint_manifest` helpers (`getCheckpointManifest`/`appendCheckpointManifest`: newest-first, dedup-by-slug, cap 20, seg-hash completion key, fail-open on pre-v132 schema) — pinned by `test/checkpoint-manifest.test.ts`. `sensitivity-scan.ts` + `compile-view.ts` — the compile-context stack: composed detector (secret-scan + ordered `PII_PATTERNS` + path/blocklist families + operator pattern file; uniform `.gbrain-scan-allow` fingerprint escape hatch; CONTENT hits drop an entry, CONFIG/loader failures THROW so the caller aborts without writing) and the deterministic compiled-view builder (recency decay anchored to the newest candidate `updated_at`, never wall-clock; total-order (score desc, slug asc); source-scoped listPages/getPage reads that skip op-layer write-backs and pass `excludePrivate: true` on every arm, so private pages never reach the compiled file; whole-file `packToBudget` math that never passes a <=0 budget) — pinned by `test/sensitivity-scan.test.ts` + `test/compile-view.test.ts` + `test/e2e/compile-context-pglite.test.ts`; the CLI shell is `src/commands/compile-context.ts` (targets claude-code|codex|openclaw, AGENTS.md managed-marker splice that throws on damaged markers, atomic writes, `--check` recompile-and-compare exit codes; the guide is `docs/guides/checkpoint-compaction.md`). It also owns the whole Memorable seam's engine-free plumbing: the session-receipt JSONL (`session-receipts.jsonl`, `appendSessionReceipt` — dedup by post-redaction `content_hash` so a resumed session neither duplicates its receipt nor re-fires the relay; tail-rewrite compaction triggered by the 32 MB byte ceiling alone — the read fires exactly when the pass will act, with the 2000-line budget enforced inside the pass — and a `skipCompaction` seam the openclaw compact() lane sets unconditionally: the hook lane is the ONE receipts compactor, so two processes can never race the read-filter-rename rewrite); ONE bounded adaptive `readJsonlTail` reader shared by `lastReceiptMatches`, `lastRelayResult` and `readSessionReceiptsTail` (a receipt line can exceed the 1 MB window — the window doubles rather than reading "empty"); `maybeTrimRelayResults` (BOTH capture lanes trim the child-appended `memorable-relay.jsonl` — an openclaw-only host has no hook lane, and converging newest-keeping trims make concurrent trims safe: mtime-stale preferred, hard 8 MB force backstop, line-boundary cut keeping the newest lines — the child appends open-by-path, so the residual loss window is one in-flight write); the CONSENT STAMP (`memorable-consent.json`, 0600, written ONLY by config-set's disclosure flow — deliberately outside config.json, which the external CLI full-file-rewrites; scope-bound to the disclosure sha256 + `MEMORABLE_CAPTURE_HARNESSES`, so widening the capture surface invalidates old stamps); `memorableGateAllowed(cfg)` ({allowed, reason: kill_switch|disabled|disclosure_missing} — one reason vocabulary for hook, context-engine and doctor); `memorableConsentEvidence()` (the CLI-side opt-in read fail-closed from ~/.memorable/config.json, dated provisional spec note, GBRAIN_MEMORABLE_CONFIG test seam); `redactedToolCallsJson` (the security-load-bearing span-filter + highEntropy redaction, ONE implementation for both capture lanes; string LEAVES are redacted raw before serialization — scanning the serialized JSON would let quoted secrets through via \" escaping — with a post-serialization re-scan as belt-and-braces); `recordAndRelayReceipt` (per-receipt harness scope-binding first — a harness outside `MEMORABLE_CAPTURE_HARNESSES` is refused with `memorable_harness_undisclosed` → receipt → prior-run outcome surfacing with the child's reason clamped via the shared `clampRelayCause` (32 chars, so the 16-char prefix keeps composites inside the 48-char reason bound) and appended LAST → consent evidence → `resolveMemorableBin` → detached spawn; never throws; `spawnFn` test seam); and `priorRelayFailure`, which surfaces the PREVIOUS relay run's self-reported exit status so a relay that records nothing is never reported healthy. `resolveMemorableBin` does the pre-spawn PATH/`MEMORABLE_BIN` resolution so a missing CLI is a named heartbeat reason rather than a silent async ENOENT.- `src/core/context/ipc-path.ts` — engine-free local socket discovery and private Unix fallback when the complete role-specific address exceeds 103 UTF8 bytes. Hashes the physical parent plus basename under a fixed OS temporary root, verifies ownership/0700 directory/0600 client socket without following fallback symlinks, and retains a native binding claim through actual server close. Existing Unix socket accessibility is rechecked even when a runtime reports ENOENT; permission/resource probe failures never authorize stale takeover; Windows named pipes retain a native Global mutex through actual close; `windows-ipc.ts` normalizes namespace prefixes while native Windows Unicode casing defines the mutex identity. `test/local-ipc-path.test.ts` covers concurrent real processes, SIGKILL recovery, active-connection shutdown, aliases and unsafe paths. The published CLI smoke also uses a long Unicode datastore path.diff --git a/docs/architecture/key-files/google-and-loops.md b/docs/architecture/key-files/google-and-loops.mdindex c1edd7c7b7..0dc62cc414 100644--- a/docs/architecture/key-files/google-and-loops.md+++ b/docs/architecture/key-files/google-and-loops.md@@ -24,7 +24,7 @@ Historical Gmail repair selects explicit nested MIME metadata fields, excluding- `src/core/google/google-clients.ts` — hand-rolled Gmail/Calendar/People REST clients (house style, no googleapis dependency): auth via any `GoogleAccessProvider` (vault-backed `GoogleTokenProvider` by default), 401 → forceRefresh + single retry, Retry-After honored (delta-seconds AND http-date), 403 accessNotConfigured → `api_not_enabled` carrying the exact enable deep link (project number extracted from the client id), uniform pageToken pagination with a safety cap, `fetchImpl` injectable for tests. `extractCalendarMethod(part)` walks the MIME tree for a `text/calendar`/`application/ics` part and reads the iCalendar `method=` parameter from the PART's own `Content-Type` header (`headers[]` on nested parts with `format=full` — Gmail's `MessagePart.mimeType` is the BARE media type, so a mimeType-only parse would read '' for every real invite and silently downgrade the structural signal to the subject fallback); a mimeType that still carries params is the fallback parse; a bare `.ics` filename with a non-calendar MIME type claims nothing. `CalendarClient.listEvents({calendarId})` sweeps one calendar (default `DEFAULT_CALENDAR_ID`). A People request with a nonempty `syncToken` maps HTTP 400 to `GoogleCursorExpiredError` only for typed `google.rpc.ErrorInfo` reason `EXPIRED_SYNC_TOKEN` or a message beginning `Sync token [is] expired`; unrelated 400s, initial-list requests, and other APIs remain upstream failures. The contacts sweep uses its existing bounded full re-list recovery without restarting Gmail. Pinned by injected-response tests in `test/google-clients.test.ts` and `test/google-source-reconcile.test.ts`, not live-provider validation.- `src/core/google/google-render.ts` — pure render functions (`{relPath, markdown}` out; no I/O, no engine): thread pages under `emails/YYYY/MM/` (type email), events under `calendar/YYYY/MM/` (type meeting), contacts under `people/` (type person). Gmail deep links are code-generated via the typed `emailCitation` scaffold, never LLM-composed. The noise/signature rules `recipes/email-to-brain.md` specifies as prose for agent-authored collectors are implemented here — keep the recipe and this module in sync. `isCalendarSystemMail({calendarMethod, subject})` gates BOTH loop detectors: the PRIMARY signal is a `calendarMethod` in the `CALENDAR_METHODS` allowlist (RFC 5546 — REQUEST, REPLY, CANCEL, PUBLISH, COUNTER, DECLINECOUNTER, REFRESH, ADD; case-insensitive); an empty or unrecognised method is NOT a stamp and falls to the subject fallback, which is anchored to the start of the subject, refuses any Re:/Fwd: prefix, and matches only Calendar's OWN localised headers (`Invitation:`, `Updated invitation:`, `Accepted:`, `Declined:`, `Tentative:`, `Canceled event:` + localised equivalents) — a generic word like `Notification:` is a human/vendor subject and never matches. `renderThreadPage` stamps `participants:` (every address on the thread) AND `senders:` (sorted unique message AUTHORS only — the list `loops mute sender` gates on, so muting one person cannot silence a whole group thread). Pinned by `test/google-render.test.ts`.- `src/core/google/google-source.ts` — the Google API source sweep. Unmanaged mode materializes Markdown under the source directory and imports through the standard chunks/aliases/links pipeline; managed mode uses journaled connector admission. Sweep order contacts → calendar → gmail: alias rows must exist before the loop detector resolves counterparties. Per-service independent cursors: contacts/calendar syncToken commits only after that service's fully-successful sweep (410 GONE drops the token and re-runs windowed); gmail delta rides history.list with an expired-history windowed fallback; the INITIAL backfill drains newest→oldest with a batch-committed floor cursor so a killed 50k-message backfill resumes at the floor instead of restarting, and the historyId anchor is captured BEFORE the backfill so the delta lane takes over with zero gap (overlap re-renders are idempotent). Emits the `sync.google_materialize` progress phase (docs/progress-events.md). Access resolves per source config: the vault (default), a token-printing command (`g_access: command` — gog/gcloud/gateway; identity entry synthesized, scope preflight trusts the configured services, send-as aliases fetched live best-effort), or a named env var (`g_access: env`). Secrets never land in `sources.config` (the command/env NAME is config; tokens are not). Honesty invariants: `last_sync_at` is gated on the GMAIL sweep's success (it feeds `gbrain waiting`'s trust-critical staleness gate, which protects loop freshness — a gmail sweep with real thread failures must not advance it); contacts/calendar failures mark the run `partial` but do not block the stamp, and a source without gmail in its services stamps unconditionally. A thread whose fetch fails on consecutive sweeps lands in the poison ledger and is skipped (steady-state runs honor the ledger; `--full` retries with a fresh one), so one bad thread can't wedge the sync while a poison-skip alone doesn't count as failure. Contact reconcile resolves by contact resourceName (DB lookup by contact id FIRST): deletion tombstones carry only `resourceName + deleted` (no names — slug derivation yields null) and a renamed contact derives a DIFFERENT slug, so both must land on the existing page by id, never by slug. The calendar sweep binds its sync token to its calendar: `sweepCalendar` compares `state.calendar_id` (legacy state without it is treated as primary's) with the configured `calendarId`; on a mismatch it logs `[google] calendar changed (<old> → <new>)`, discards the token and takes the windowed first-sync path (no `syncToken` on the wire), and a freshly banked token stores the calendar id beside it — pairing a re-pointed source with the previous calendar's cursor would import a foreign delta. Pages from the previous calendar are not reconciled on the switch (logged; a filed follow-up). `enqueueLoopsExtraction` enqueues EVERY eligible thread (newest first) under a waiting-depth budget `LOOPS_EXTRACT_ENQUEUE_CEILING − waiting` that counts only THIS source's waiting `loops_extract` jobs (`data->>'sourceId'`), so one account's stalled backlog cannot pin another source's budget at 0; overflow is a logged deferral (a deferred thread re-candidates when it changes) and a failed probe fails open. The budget probe counts PENDING rows — `status IN ('waiting','delayed','active')` — so a retry backlog parked in `delayed` during a flapping provider cannot stack past the ceiling. With no chat provider available (`isAvailable('chat')` false) the enqueue is skipped entirely and one stderr line per sweep names the reason and the count; pages still import and the threads re-candidate on their next touch or a `--full` sweep. Managed Google API sync uses journaled connector checkpoints; an unbound source is explicitly `connector_database`, while a bound source publishes canonical files. Identity-query storage failures do not become successful absence or advance the checkpoint. Unsupported Git/dry-run flags refuse before credentials/network; legacy materialization remains the unmanaged path.-- `src/core/google/loop-detect.ts` — the zero-LLM thread-state machine: last substantive message inbound + user in To: + unanswered ≥24h → `unanswered_inbound`; last outbound + contains a question + unanswered ≥72h → `unanswered_outbound`; a reply closes the loop (`closed_by: reply_detected`). Precision IS the product: noise senders, list mail (List-Unsubscribe), CC-only delivery, FYI/forwards without a question, self-threads, and muted senders/threads never open loops — pinned by the labeled fixture corpus in `test/google-loop-detect.test.ts` (every false-positive class gets a fixture before its fix). Pure verdict function + a thin apply step called per touched thread from the sync; the apply step must never fail the sync.+- `src/core/google/loop-detect.ts` — the zero-LLM thread-state machine: last substantive message inbound + user in To: + unanswered ≥24h → `unanswered_inbound`; last outbound + contains a question + unanswered ≥72h → `unanswered_outbound` (both grace windows measured from the oldest owed message in the trailing run since the last turn flip, so a nudge or follow-up never restarts the clock — gbrain-evals N7-1); a reply closes the loop (`closed_by: reply_detected`). Precision IS the product: noise senders, list mail (List-Unsubscribe), CC-only delivery, FYI/forwards without a question, self-threads, and muted senders/threads never open loops — pinned by the labeled fixture corpus in `test/google-loop-detect.test.ts` (every false-positive class gets a fixture before its fix). Pure verdict function + a thin apply step called per touched thread from the sync; the apply step must never fail the sync.- `src/core/google/loops-extract.ts` — the LLM half of the open-loop engine: ONE extractor per recent thread page projects each commitment into THREE substrates in the same pass — the `open_loops` row (dedup `commit:<sha8>`), a facts row via writeSingleFact (kind=commitment, fence-first, deduped; its id lands on `open_loops.fact_id` so entity cards / recall / context_pack see the commitment through existing read paths with zero new read code), and a typed edge thread-page → person-page (`owes_to` / `awaiting_reply_from`) for relational search. `extract_facts` never runs separately on google-source email pages. Guardrails: injection-hardened input, ALL-or-nothing parse barrier (a malformed model response writes NOTHING), a structural eligibility gate (`loopExtractionEligibility` — Gmail labels, `List-Unsubscribe`, calendar part, who wrote the message; no vendor lists) plus the per-source waiting-depth enqueue budget (`LOOPS_EXTRACT_ENQUEUE_CEILING`, a spend backstop — see `google-source.ts`), only the last `LOOPS_EXTRACT_WINDOW_DAYS` (30) of mail (the deep backfill is never extracted), kill switch `loops.extraction_enabled` (default ON for google sources). Suppressions gate the lane before any model/facts/edge write: a muted thread id, or a muted SENDER — `fm.from` ∪ `fm.senders`, every address that AUTHORED a message, so a muted counterparty who wrote earlier in the thread still suppresses — returns `reason: 'suppressed'`; recipients/CC never count (muting one person must not hide everyone else's commitments in a group thread, and an outside sender must not be able to dodge extraction by CC'ing a muted address). Pages without a `senders:` field fall back to `fm.from` alone until their next re-render. Eligibility computes the substantive (non-noise, non-calendar) message set FIRST and `owner_participated` requires the owner to have written a SUBSTANTIVE message — a pure-calendar thread the owner RSVP'd to stays `no_substantive_messages`. When the chat provider is unavailable, `runLoopsExtract` throws `LoopsExtractRetryableError` (reason `llm_unavailable`) rather than returning a skipped result: a completed no-work row would hold the revision-keyed idempotency slot forever, while a retried-then-dead row frees it so the same revision re-enqueues on the next sweep. On a managed brain `managedFactWritePreflight` checks the managed fact authority and canonical owner before chat (an unaccepted writer refuses with `writer_coordinator_required`), and the commitment fact publishes through writeSingleFact's coordinator path; disabled, missing-page and suppressed cases retain their existing no-work outcomes.- `src/core/loops/loops-store.ts` — SQL accessors for the `open_loops` + `loop_suppressions` tables over `engine.executeRaw` with IDENTICAL SQL text on both engines (parity by construction, the sources-ops.ts pattern — no per-engine method twins). JSONB discipline: evidence binds through `$N::text::jsonb`, never a bare `::jsonb` cast over JSON.stringify. Loops close by state transition, never delete: reply-driven auto-close flips status to `done` and stamps `closed_by`, keeping the audit trail. The upsert's DO UPDATE carries a manual-close guard in its WHERE: a closed row (done/dropped/stale) only reopens on GENUINELY newer activity, so a routine sweep re-seeing the same thread never resurrects a hand-closed loop, and the staleness auto-close (`closed_by: 'staleness'`) is likewise guarded against the upsert's reopen. `removeSuppression(engine, sourceId, kind, value)` is the exact inverse of the mute write — deletes the one `(source_id, kind, value)` row with the same lower-casing, returns `{removed: boolean}` (false = was not muted, callers treat it as a no-op success), and never reopens loops: suppressions gate NEW detection only.- `src/core/ops/loops.ts` — the op surface: `open_loops` (read), `loops_close` (write), `loops_mute` (write). `open_loops` is deliberately NOT localOnly (hosted serves it over HTTP to the authenticated owner); instead it applies fail-closed evidence redaction for `ctx.remote !== false` — counts, counterparty, summary, due date only; verbatim quotes, Gmail deep links, and the injectable `text` digest are trusted-local only. The result carries the google sources' last-successful-sync ages + a `stale` flag (>24h) so callers can refuse stale-but-confident output on a trust-critical surface. Per-call scope params `source_id`/`all_sources` resolve through `resolveRequestedScope` (an MCP client bound to another source can reach the google source's loops; remote callers stay in-grant, out-of-grant `source_id` is denied); a scope with NO google source returns `no_google_sources: true` and the digest says the engine has nothing to read instead of a false "You are clean". Scope is fail-closed too: an UNSCOPED remote `open_loops` read is refused outright (the op must not rely on transports to enforce it — an unscoped remote read would span every source), and the write ops (`loops_close`, `loops_mute`, `loops_unmute`) require a single-source remote scope that matches the caller's grants — trusting a caller-supplied `source_id` for a remote write would let any remote client plant (or lift) suppression rows cross-source; `loops_unmute` reverses a suppression via `removeSuppression` and reports `{removed}` honestly.diff --git a/docs/fix-wave-notes/capy-evalwave-fixes-a.md b/docs/fix-wave-notes/capy-evalwave-fixes-a.mdnew file mode 100644index 0000000000..682976b686--- /dev/null+++ b/docs/fix-wave-notes/capy-evalwave-fixes-a.md@@ -0,0 +1,118 @@+# Eval-category wave, fix lane A (`capy/evalwave-fixes-a`)++Bugs from gbrain-evals (branches `capy/wave-n7-n8` and `capy/wave-n12-n13`,+ledger `docs/benchmarks/2026-10-01-wave-bugs.md`). Every item has a failing+test first (the ported repro), then a root-cause fix. No version bump or+CHANGELOG entry: the integrator owns those.++## N8-1 / N8-2 — private pages in ambient recall (privacy)++`resolveEntitiesToPointers` (`src/core/context/retrieval-reflex.ts`) queried+`pages` with no visibility predicate, so `volunteer_context` returned a+`visibility: private` page's title and synopsis to remote callers, and the+turn hook block (`assembleTurnContext`, turn mode) injected it.++- The resolver now takes `excludePrivate` (default **true**, fail-closed) and+ applies `privatePagesFilterFragment` — the remote-search predicate,+ including derived-private atoms and concepts — on every arm: the alias+ liveness check (so a hidden page also stops counting toward alias+ uniqueness), the title/slug/surname query, alias hydration and the CJK arm.+- `volunteer_context` passes `resolveExcludePrivatePages(ctx.engine,+ ctx.remote)`: remote callers on stdio and HTTP are filtered (honouring the+ operator's `search.remote_private_pages` opt-out exactly like search); the+ trusted local CLI still sees private pages.+- `assembleTurnContext` turn mode passes `excludePrivate: true` explicitly+ for pointers and volunteered pages (documented world-only posture).+- Audit of the other context/reflex paths: the serve IPC `resolve` handler,+ the direct-Postgres reflex rung, `gbrain watch` and the BrainBench adapters+ all call the resolver without the option, so they inherit the world-only+ default. `pack`/`delta` modes were already filtered (entity cards and+ `listPages({excludePrivate})`). `recall-needed.ts` already passed+ `excludePrivate: true`. **`compile-context` had the same gap**: it listed+ pages without a visibility filter and wrote private titles and excerpts+ into `.claude/gbrain-context.md` / `AGENTS.md`; every `listPages` arm in+ `compile-view.ts` now passes `excludePrivate: true`.+- Tests: `test/reflex-private-visibility.test.ts` (title, alias, surname and+ derived-atom windows; stdio and HTTP remote callers; local presence+ control; turn block; resolver default vs explicit widen), run on PGLite and+ on Postgres via `test/e2e/reflex-private-visibility-postgres.test.ts`;+ `test/compile-view.test.ts` private-page case.++## N7-1 — a nudge hid an overdue request on first sight++`detectThreadLoop` measured the 24h/72h grace windows from the last message.+They now run from the oldest message in the trailing run (substantive+messages since the last turn flip) that carries the obligation: the first+inbound message with me in To:, or my first outbound question. A fresh run+stays inside grace; a run that started after my reply restarts the clock;+CC-only mail does not start it. Corpus cases added to+`test/google-loop-detect.test.ts`; `docs/guides/open-loops.md` states the rule.++## N12-1 — bold labels parsed as a conversation++New `PatternEntry.repeat_speaker_min_turns`, set to 3 on `bold-name-no-time`:+when the parsed body has at least three turns and no speaker ever speaks+twice, the orchestrator returns `no_match`. Density scoring cannot see this+shape (3 of 26 lines clears the 0.05 floor). All 61 conversation-format+fixtures (`test/fixtures/conversation-formats/*.jsonl`) give the same result+before and after; single-line and two-turn bodies are unaffected.++## N12-2 — offset timestamps re-parsed one day early++`renderSessionParts`' `anchorTimestamp` paired the date sliced from the raw+string with the UTC hour. It now takes both from the same UTC instant, and the+session date (slug, frontmatter `date`) is normalized too. The claude-export,+claude-code, codex and openclaw adapters normalize offset-bearing timestamps+to UTC through the shared `utcTimestamp` helper (`transcripts/types.ts`);+UTC strings pass through byte-identical, so existing imports do not churn.+Test: `test/transcript-offset-timestamps.test.ts`.++## N13-1 — short `const f = () =>` functions lost their names++`mergeSmallSiblings` treated a function-valued `lexical declaration` as a+mergeable const run. `declaresFunctionValue` (`chunkers/def-types.ts`) marks+TS/JS declarations whose declarator value is an arrow function, function+expression or generator; the chunker stamps `definesFunction` and the merge+guard protects those chunks. Plain const value runs still merge.+`CHUNKER_VERSION` 7 → 8 so existing indexes re-chunk (version-pin tests+updated). Tests in `test/chunkers/code-merge-defs.test.ts`.++## N13-2 — `resolved: false` on resolved edges++The shared row mapper (`engine-sql/code-edges.ts`, now also used by the+PGLite `getEdgesByChunk`) reports `resolved: true` for a `code_edges_symbol`+row the resolver stamped with `edge_metadata.resolved_chunk_id`.+`to_chunk_id` still reports the stored column, so two-pass retrieval is+unchanged.++## N13-3 — language gate picked an arbitrary namesake++`runRecursiveWalk` read the language of one arbitrary chunk carrying the+qualified name. It now reads every defining chunk's language and refuses only+when none is supported. When an unsupported-language namesake shares the+name, edges whose origin chunk is not in a supported language are dropped,+so a Python walk does not list the Go callers. Tests:+`test/code-intel/n13-edge-resolution.test.ts` (PGLite) and+`test/e2e/code-intel-n13-postgres.test.ts`.++Overlap note: open community PR #5835 also edits+`src/core/code-intel/recursive-walk.ts` (remote read policy); expect a small+textual merge there.++## N12-7 — legacy pack attendance++Handed to lane B (owns `link-extraction.ts` attendance and direction); not+touched here.++## Repro results (gbrain-evals scripts against this checkout)++| Item | Before (3a284ae) | After |+|---|---|---|+| N8-1 | private page + synopsis returned to remote caller | `[]` |+| N8-2 | block lists the private page and synopsis | `""` |+| N7-1 | `open=[]` | `open=[["unanswered_inbound","[email protected]"]]` |+| N12-1 | exit 1, 3 fake speakers | exit 0, `no_match` |+| N12-2 | exit 1, re-parsed `2026-08-10T05:30Z` | exit 0, `2026-08-11T05:30Z` |+| N13-1 | exit 1, `code_def_count: 0` | exit 0, `src/sample.ts:3` |+| N13-2 | exit 1, `resolved: false` | exit 0, `resolved: true` |+| N13-3 | exit 1, `unsupported_language` | exit 0, `ok` |diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex dee1654df5..9239d10827 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -35,7 +35,7 @@ src/core/link-extraction.ts 2133 ratchet grown v0.46.26.0 megawave: link-aware tsrc/core/embedding-migration.ts 1525 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embedsrc/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refreshsrc/commands/hook.ts 1903 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read-src/core/chunkers/code.ts 1582 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES+src/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts)src/core/config.ts 1806 ratchet +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1)src/core/bootstrap/harness.ts 2674 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts)src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl optiondiff --git a/src/core/chunkers/code.ts b/src/core/chunkers/code.tsindex 6bdf77c562..7bda4e454c 100644--- a/src/core/chunkers/code.ts+++ b/src/core/chunkers/code.ts@@ -20,7 +20,7 @@import { chunkText as recursiveChunk } from './recursive.ts';import { buildQualifiedName } from './qualified-names.ts';-import { MERGE_PROTECTED_SYMBOL_TYPES } from './def-types.ts';+import { MERGE_PROTECTED_SYMBOL_TYPES, declaresFunctionValue } from './def-types.ts';import { estimateTokens, estimateEmbedTokens, estimateEmbedTokensCeiling, DEFAULT_MAX_CHUNK_TOKENS } from './token-estimate.ts';import { safeSplitIndex } from '../text-safe.ts';import {@@ -140,11 +140,7 @@ import G_ZIG from '../../assets/wasm/grammars/tree-sitter-zig.wasm' with { type:// top-level defs indexed to ZERO symbols). Chunk boundaries change for every// previously-merged file, so the bump forces a re-chunk that recovers the// erased symbols.-//-// v8 (gbrain-evals N13-1): short `const f = () => …` / `let g = function …`-// definitions no longer fold into anonymous merged chunks (code-def missed 9-// of 50 pathe functions). The bump re-chunks files whose merged runs held-// function-valued declarations.+// v8 (N13-1): `const f = () => …` definitions keep their own named chunk.export const CHUNKER_VERSION = 8;// Lazy-loaded tree-sitter module (v0.22.x API: Parser is default export)@@ -189,12 +185,7 @@ export interface CodeChunkMetadata {* Null when symbolName is missing (merged chunks, module-level fallback).*/symbolNameQualified?: string | null;- /**- * gbrain-evals N13-1: set on a const/let/var declaration whose value is a- * function (`const f = () => …`, `let g = function () {…}`). Its symbol- * type is a mergeable run form, but it is a named function definition, so- * mergeSmallSiblings must keep it (and its symbol_name) on its own chunk.- */+ /** N13-1: a const/let/var whose value is a function — merge-protected (def-types.ts). */definesFunction?: boolean;}@@ -1473,20 +1464,6 @@ function extractSymbolName(node: any): string | null {return null;}-const FUNCTION_VALUE_TYPES = new Set(['arrow_function', 'function_expression', 'function', 'generator_function']);--/**- * N13-1: a TS/JS `lexical_declaration` / `variable_declaration` whose- * declarator value is a function — a named function definition wearing a- * mergeable run type (see CodeChunkMetadata.definesFunction).- */-function declaresFunctionValue(node: any): boolean {- if (node.type !== 'lexical_declaration' && node.type !== 'variable_declaration') return false;- return node.namedChildren.some(- (child: any) => child.type === 'variable_declarator' && FUNCTION_VALUE_TYPES.has(child.childForFieldName('value')?.type),- );-}-// See the wrapper dive in extractSymbolName (#3789).const NAME_WRAPPER_TYPES = new Set(['variable_declaration', 'variable_declarator', 'init_declarator',diff --git a/src/core/chunkers/def-types.ts b/src/core/chunkers/def-types.tsindex fbf3254405..028a71ce2f 100644--- a/src/core/chunkers/def-types.ts+++ b/src/core/chunkers/def-types.ts@@ -78,3 +78,20 @@ export const MERGE_PROTECTED_SYMBOL_TYPES: ReadonlySet<string> = new Set(['export statement','decorated definition',]);++const FUNCTION_VALUE_TYPES = new Set(['arrow_function', 'function_expression', 'function', 'generator_function']);++/**+ * gbrain-evals N13-1: a TS/JS `lexical_declaration` / `variable_declaration`+ * whose declarator value is a function (`const f = () => …`, `let g =+ * function () {…}`) is a named function definition wearing a mergeable run+ * type. The chunker stamps it `definesFunction` so mergeSmallSiblings keeps+ * it (and its symbol_name, which code-def resolves) on its own chunk, while+ * plain const/let value runs still merge. Takes a tree-sitter node.+ */+export function declaresFunctionValue(node: any): boolean {+ if (node.type !== 'lexical_declaration' && node.type !== 'variable_declaration') return false;+ return node.namedChildren.some(+ (child: any) => child.type === 'variable_declarator' && FUNCTION_VALUE_TYPES.has(child.childForFieldName('value')?.type),+ );+}diff --git a/src/core/context/retrieval-reflex.ts b/src/core/context/retrieval-reflex.tsindex 8bc5d16dd8..bb2cd6a26e 100644--- a/src/core/context/retrieval-reflex.ts+++ b/src/core/context/retrieval-reflex.ts@@ -180,8 +180,7 @@ export async function resolveEntitiesToPointers(const maxPointers = opts.maxPointers ?? DEFAULT_MAX_POINTERS;const priorLc = (opts.priorContextText ?? '').toLowerCase();- // v0.46.15 identity wave: the two new lexical arms (weak-alias + surname)- // share one kill switch. Default ON; `false` reproduces pre-wave behavior.+ // v0.46.15: weak-alias + surname arms share one kill switch (default ON).const lexicalArms = opts.lexicalArms !== false;const privacySql = opts.excludePrivate === false ? '' : `AND ${privatePagesFilterFragment('p')}`;diff --git a/src/core/types.ts b/src/core/types.tsindex 2f7ac5e175..e0470d5050 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -1411,11 +1411,9 @@ export interface CodeEdgeInput {/*** v0.20.0 Cathedral II: result row from code edge queries (getCallersOf,- * getCalleesOf, getEdgesByChunk). `resolved=true` means the target chunk is- * known: the row came from code_edges_chunk (to_chunk_id set), or it is a- * code_edges_symbol row the resolver stamped with- * edge_metadata.resolved_chunk_id (to_chunk_id stays null). `resolved=false`- * means an unresolved code_edges_symbol row.+ * getCalleesOf, getEdgesByChunk). `resolved=true`: a code_edges_chunk row, or a+ * code_edges_symbol row stamped with edge_metadata.resolved_chunk_id (N13-2).+ * `resolved=false`: an unresolved code_edges_symbol row (to_chunk_id null).*/export interface CodeEdgeResult {id: number;diff --git a/test/e2e/reflex-private-visibility-postgres.test.ts b/test/e2e/reflex-private-visibility-postgres.test.tsnew file mode 100644index 0000000000..31b01db4f8--- /dev/null+++ b/test/e2e/reflex-private-visibility-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../reflex-private-visibility.test.ts'));diff --git a/test/reflex-private-visibility.test.ts b/test/reflex-private-visibility.test.tsindex 2db505bb23..29e0798c7f 100644--- a/test/reflex-private-visibility.test.ts+++ b/test/reflex-private-visibility.test.ts@@ -6,114 +6,129 @@* mode) injected the same page. Remote callers on every transport, the* turn block and the reflex resolver's default now hide private and* derived-private pages; the trusted local caller still sees them.+ * PGLite always; Postgres when a safe DATABASE_URL is set and in the E2E+ * lane through test/e2e/reflex-private-visibility-postgres.test.ts.** Synthetic data only.*/import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { dispatchToolCall } from '../src/mcp/dispatch.ts';import { assembleTurnContext } from '../src/core/context/turn-context.ts';import { resolveEntitiesToPointers } from '../src/core/context/retrieval-reflex.ts';import { extractCandidatesFromWindow } from '../src/core/context/entity-salience.ts';import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';++for (const kind of testBackends()) {+describe(`reflex private visibility (${kind})`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ const config = { engine: kind } as any;++ const put = (slug: string, content: string) =>+ dispatchToolCall(engine, 'put_page', { slug, content }, { remote: false, sourceId: 'default', config });++ const page = (title: string, type: string, visibility: string | null, aliases: string[], body: string) =>+ `---\ntype: ${type}\ntitle: ${JSON.stringify(title)}\n${visibility ? `visibility: ${visibility}\n` : ''}aliases: ${JSON.stringify(aliases)}\n---\n\n${body}\n`;++ beforeAll(async () => {+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else {+ const pglite = new PGLiteEngine();+ await pglite.connect({});+ await pglite.initSchema();+ engine = pglite;+ close = () => pglite.disconnect();+ }+ __resetPrivateVisibilityCacheForTests();+ await put('people/zora-quillfeather', page('Zora Quillfeather', 'person', 'private', ['Zee'], 'Zora Quillfeather is a confidential contact, code PRIVMARK1.'));+ await put('atoms/velmora-claim', page('Velmora Claim', 'atom', null, [], 'Velmora Claim derived ATOMMARK1 statement.'));+ await put('companies/harbor-logistics', page('Harbor Logistics', 'company', 'world', ['Harbor'], 'Harbor Logistics is a shipping partner WORLDMARK1.'));+ }, 120_000);++ afterAll(async () => {+ await close?.();+ });-let engine: PGLiteEngine;-const config = { engine: 'pglite' } as any;--const put = (slug: string, content: string) =>- dispatchToolCall(engine, 'put_page', { slug, content }, { remote: false, sourceId: 'default', config });--const page = (title: string, type: string, visibility: string | null, aliases: string[], body: string) =>- `---\ntype: ${type}\ntitle: ${JSON.stringify(title)}\n${visibility ? `visibility: ${visibility}\n` : ''}aliases: ${JSON.stringify(aliases)}\n---\n\n${body}\n`;--beforeAll(async () => {- engine = new PGLiteEngine();- await engine.connect({});- await engine.initSchema();- __resetPrivateVisibilityCacheForTests();- await put('people/zora-quillfeather', page('Zora Quillfeather', 'person', 'private', ['Zee'], 'Zora Quillfeather is a confidential contact, code PRIVMARK1.'));- await put('atoms/velmora-claim', page('Velmora Claim', 'atom', null, [], 'Velmora Claim derived ATOMMARK1 statement.'));- await put('companies/harbor-logistics', page('Harbor Logistics', 'company', 'world', ['Harbor'], 'Harbor Logistics is a shipping partner WORLDMARK1.'));-});--afterAll(async () => {- await engine.disconnect();-});--const HIDDEN = ['people/zora-quillfeather', 'PRIVMARK1', 'Zora Quillfeather', 'atoms/velmora-claim', 'ATOMMARK1'];--const WINDOWS = [- 'user: Lunch with Zora Quillfeather and Harbor Logistics went well.',- 'user: Zee called about Harbor Logistics again.',- 'user: Did Quillfeather reply? Harbor Logistics is waiting.',- 'user: The Velmora Claim came up while reviewing Harbor Logistics.',-];--const remoteCallers = {- stdio: { remote: true, transport: 'stdio' as const, sourceId: 'default', takesHoldersAllowList: ['world'], config },- http: {- remote: true,- transport: 'http' as const,- sourceId: 'default',- takesHoldersAllowList: ['world'],- config,- auth: { token: 't', clientId: 'c', scopes: ['read'], allowedSources: ['default'] } as any,- },-};--async function volunteer(window: string, opts: Record<string, unknown>) {- const r = await dispatchToolCall(engine, 'volunteer_context', { window, min_confidence: 0.5 }, opts as any);- expect(r.isError).toBeFalsy();- return r.content[0].text;-}+ const HIDDEN = ['people/zora-quillfeather', 'PRIVMARK1', 'Zora Quillfeather', 'atoms/velmora-claim', 'ATOMMARK1'];++ const WINDOWS = [+ 'user: Lunch with Zora Quillfeather and Harbor Logistics went well.',+ 'user: Zee called about Harbor Logistics again.',+ 'user: Did Quillfeather reply? Harbor Logistics is waiting.',+ 'user: The Velmora Claim came up while reviewing Harbor Logistics.',+ ];++ const remoteCallers = {+ stdio: { remote: true, transport: 'stdio' as const, sourceId: 'default', takesHoldersAllowList: ['world'], config },+ http: {+ remote: true,+ transport: 'http' as const,+ sourceId: 'default',+ takesHoldersAllowList: ['world'],+ config,+ auth: { token: 't', clientId: 'c', scopes: ['read'], allowedSources: ['default'] } as any,+ },+ };++ async function volunteer(window: string, opts: Record<string, unknown>) {+ const r = await dispatchToolCall(engine, 'volunteer_context', { window, min_confidence: 0.5 }, opts as any);+ expect(r.isError).toBeFalsy();+ return r.content[0].text;+ }-describe('volunteer_context hides private pages from remote callers', () => {- for (const [name, opts] of Object.entries(remoteCallers)) {- for (const window of WINDOWS) {- test(`${name}: ${window}`, async () => {- const text = await volunteer(window, opts);- for (const marker of HIDDEN) expect(text).not.toContain(marker);- expect(text).toContain('companies/harbor-logistics');+ describe(`volunteer_context hides private pages from remote callers`, () => {+ for (const [name, opts] of Object.entries(remoteCallers)) {+ for (const window of WINDOWS) {+ test(`${name}: ${window}`, async () => {+ const text = await volunteer(window, opts);+ for (const marker of HIDDEN) expect(text).not.toContain(marker);+ expect(text).toContain('companies/harbor-logistics');+ });+ }++ test(`${name}: remote search agrees (no private hit)`, async () => {+ const r = await dispatchToolCall(engine, 'search', { query: 'Zora Quillfeather' }, opts as any);+ expect(r.content[0].text).not.toContain('PRIVMARK1');});}- test(`${name}: remote search agrees (no private hit)`, async () => {- const r = await dispatchToolCall(engine, 'search', { query: 'Zora Quillfeather' }, opts as any);- expect(r.content[0].text).not.toContain('PRIVMARK1');+ test('local trusted caller still sees the private page', async () => {+ const text = await volunteer(WINDOWS[0], { remote: false, sourceId: 'default', config });+ expect(text).toContain('people/zora-quillfeather');+ expect(text).toContain('companies/harbor-logistics');});- }-- test('local trusted caller still sees the private page', async () => {- const text = await volunteer(WINDOWS[0], { remote: false, sourceId: 'default', config });- expect(text).toContain('people/zora-quillfeather');- expect(text).toContain('companies/harbor-logistics');});-});-describe('turn-context block never injects private pages', () => {- for (const window of WINDOWS) {- test(window, async () => {- const r = await assembleTurnContext(engine, {- sourceId: 'default',- window: [{ role: 'user', text: window.replace(/^user: /, '') }],+ describe(`turn-context block never injects private pages`, () => {+ for (const window of WINDOWS) {+ test(window, async () => {+ const r = await assembleTurnContext(engine, {+ sourceId: 'default',+ window: [{ role: 'user', text: window.replace(/^user: /, '') }],+ });+ for (const marker of HIDDEN) expect(r.text).not.toContain(marker);+ expect(r.text).toContain('companies/harbor-logistics');});- for (const marker of HIDDEN) expect(r.text).not.toContain(marker);- expect(r.text).toContain('companies/harbor-logistics');- });- }-});+ }+ });-describe('resolveEntitiesToPointers is world-only unless a caller widens it', () => {- const candidates = () =>- extractCandidatesFromWindow([{ role: 'user', text: 'Zora Quillfeather met Harbor Logistics.' }]);+ describe(`resolveEntitiesToPointers is world-only unless a caller widens it`, () => {+ const candidates = () =>+ extractCandidatesFromWindow([{ role: 'user', text: 'Zora Quillfeather met Harbor Logistics.' }]);- test('default excludes private pages (the ambient reflex and IPC resolve posture)', async () => {- const block = await resolveEntitiesToPointers(engine, 'default', candidates());- expect(block?.pointers.map((p) => p.slug)).toEqual(['companies/harbor-logistics']);- });+ test('default excludes private pages (the ambient reflex and IPC resolve posture)', async () => {+ const block = await resolveEntitiesToPointers(engine, 'default', candidates());+ expect(block?.pointers.map((p) => p.slug)).toEqual(['companies/harbor-logistics']);+ });- test('excludePrivate: false (trusted local) keeps the private page', async () => {- const block = await resolveEntitiesToPointers(engine, 'default', candidates(), { excludePrivate: false });- expect(block?.pointers.map((p) => p.slug).sort()).toEqual(['companies/harbor-logistics', 'people/zora-quillfeather']);+ test('excludePrivate: false (trusted local) keeps the private page', async () => {+ const block = await resolveEntitiesToPointers(engine, 'default', candidates(), { excludePrivate: false });+ expect(block?.pointers.map((p) => p.slug).sort()).toEqual(['companies/harbor-logistics', 'people/zora-quillfeather']);+ });});});+}