Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(writeback): explicit memory.auto_writeback off stops every ambient capture lane (#6091)

garrytan8105abac40a1
diff --git a/docs/architecture/key-files/agent-bootstrap-continued.md b/docs/architecture/key-files/agent-bootstrap-continued.md
index 5ed19b80b1..0dacfa5743 100644
--- a/docs/architecture/key-files/agent-bootstrap-continued.md
+++ b/docs/architecture/key-files/agent-bootstrap-continued.md
@@ -11,6 +11,7 @@
- **Ambient memory writeback cluster** (opt-in, `memory.auto_writeback = off|salient|all`, default off; guide `docs/guides/ambient-writeback.md`):
- `src/core/facts/ttl-parse.ts` — dependency-free TTL grammar leaf (`parseTtlShorthand` non-throwing typed results; `validateTtlConfig` — duration-shorthand-only, positive, ≤365d for the transient-TTL config). `ops/facts.ts`'s `parseTtlParam` wraps it with the byte-identical frozen verbError copy; the engine-free hook child shares the grammar without touching the gateway-reaching ops graph.
- `src/core/facts/writeback-config.ts` — config resolution, fail-closed OFF. `gbrain config set memory.*` DUAL-WRITES (file mirror first for the engine-free readers, then the AUTHORITATIVE DB plane; `src/commands/config.ts` MEMORY_DUAL_PLANE_KEYS branch, which also stamps the resolved `memory.visibility_posture` file mirror for the engine-free harness renderer — and a `facts.default_visibility` set/unset RE-STAMPS that mirror so installed blocks can always converge; a DB-write/delete failure on these keys exits NON-ZERO naming the unchanged runtime value, and `config get` reports them DB-first with a drift warn). MOUNT RULE: when the selected brain is not the host (`--brain`/GBRAIN_BRAIN_ID/.gbrain-mount), every dual-plane lane (set, unset, `unset --pattern`, the posture re-stamp) writes the DB row ONLY and says so — the machine-local mirror gates the HOST's Stop hook, and enabling a team mount must never opt the host's conversations into banking; an unresolvable brain selection also skips the mirror (fail toward not mutating host state). The engine path resolves mode/ttl from the DB ONLY — the machine-global file mirror never enables a per-brain gap (a mounted/selected brain can't inherit another brain's opt-in); a provided fileCfg serves drift detection (`plane_drift`: DB row ABSENT + file enabled; explicit DB 'off' is intent, never drift) and the LKG override (a file-mirror explicit 'off' beats a cached ENABLED bundle on read failure). `resolveWritebackConfig` caches a per-engine LAST-KNOWN-GOOD bundle ATOMICALLY (mode+ttl+visibility together; no LKG + read failure = OFF+`read_error`). `ambientOptsFrom(wb, {remember, extractFacts})` gates the section on the caller's ACTUAL callable set — no `remember` ⇒ no section (bound-client fences, clamped surfaces). `visibilityPostureFromRaw` owns the rule: unset → world, only explicit non-world → private.
+ - Capture gate (#6091, W2.1): `captureGateDecision(cfg, lane)` in `src/core/facts/writeback-config.ts` is the ONE truth table for the ambient capture lanes (`writeback` = `.wb-` Stop-hook turns, `compact` = PreCompact segments + OpenClaw compactions, `session_end` = SessionEnd `<sid>.txt`): explicit `off` retires every lane; unset retires `writeback` and extracts `compact`/`session_end` (the hooks are their opt-in); read error, plane drift, invalid mode, and (compact/session_end) a DB-absent file-mirror `off` (`off_unsynced`) hold. `captureLaneStates`/`captureLaneSummary`/`writebackOffMessage`/`writebackUnsetMessage`/`WRITEBACK_RESTART_AFTER_OFF` render it for `config set|unset|get` (stderr lane line), doctor `memory_writeback` (`details.capture_lanes`, `details.restart_after_off`) and the guide's truth table. `src/core/context/capture-consent.ts`: capture side `recordCaptureIfOff` (the PreCompact `bankCompactSegment` `beforeWrite` callback, the SessionEnd corpus write and the OpenClaw spool write `<file>.capture-off.json` — brain identity = hash of the resolved config dir, turn hashes via `corpus-turns.ts` — BEFORE the file lands; GC reaps an orphan record only after the seat grace); extraction side `resolveCaptureGate` + `applyCaptureGate` (hold / `retireCorpusFile` / fold this brain's record via `retireCorpusTurns`, retiring a file whose every turn was captured under off; foreign-brain records ignored), called under the claim before any provider call or receipt republish in `checkpoint-harvest.ts` (`runOne`, `runWritebackTurn`), `context-engine.ts` rung 3 and `sweep.ts` (including the keyless/extraction-disabled early returns). Publication side: `src/core/facts/capture-sources.ts` holds `FACTS_BACKSTOP_SOURCES` (`as const`; `FactsBackstopCtx['source']` derives from it), the ambient subset, `captureGateLaneForSource` and `assertAmbientCaptureAdmissible` (code `ambient_capture_off`), re-checked inside `admitManagedFactsBatch`'s transaction (`facts-maintenance.ts`; sessions and intents carry `captureSource` / `capture_source`, so #6048 follow-up batches are re-checked too) and before the unmanaged fence write in `backstop.ts`; requests admitted before `off` publish. Tests: `test/capture-consent-gate.serial.test.ts`, `test/capture-consent-admission.test.ts` (PGLite + Postgres), `test/capture-consent-inventory.test.ts`.
- `src/core/facts/writeback-instructions.ts` — the ONE ~15-line instruction-section builder feeding BOTH the MCP `instructions` composition and the bootstrap-managed harness blocks (surfaces structurally cannot drift). Mode-conditional candidate policy, literal resolved TTL, surface-honest extract_facts mention, visibility posture with the "world = agents on this brain, not the public internet / never widen" rule; the private posture states its consequence to the agent (it and every other MCP/HTTP session cannot recall or forget a fact it saves as private).
- `src/core/facts/writeback-gate.ts` — the engine-free zero-LLM Stop-hook salience gate: frozen skip-reason vocabulary (`empty`/`too_short` [CJK-aware 20→10 floor]/`ack_or_greeting`/`slash_command`/`question_only`/`quoted_or_tool_output`/`bulk_paste` >8KB/`pasted_content`), first hit wins; after the length checks every Claude Code paste block is stripped (`pasted-content.ts`) and the remaining rules plus the banked text see only the user's own words (a paste-only turn is `pasted_content`); ok returns the NFC/collapsed normalized text + sha256-hash24 — the turn's idempotency key (same turn ⇒ same `.wb-` filename ⇒ embedding-free dedup that works keyless).
- `src/core/facts/writeback-audience.ts` — personal-vs-shared classifier for the consent nudge. Declaration (`brain.audience`, stamped by company-brainify's Phase-5 handoff, the bootstrap interview's SURFACE_MULTIUSER answer — applied the moment `interview --set` records it, BEFORE the agent runs init — or the operator) BEATS the conservative heuristic (≥3 distinct non-automation MCP clients active 30d via `mcp-usage.ts`, `likely_automation` excluded); `reasons[]` always names the evidence. The machine-global file-mirror declaration speaks for the HOST brain only — a mounted/selected brain falls through to its own DB row or heuristic. Fail directions: config read failure → `unknown` (nudge stays silent), usage-read failure with a reachable DB → `personal` (missing multi-client infra is personal-shaped). Never enables anything.
@@ -21,7 +22,7 @@
- Diagnostics: `src/commands/doctor/checks/memory-writeback.ts` (`memory_writeback`, BRAIN category) — quiet-ok when off, but the OFF branch still probes receipt + canonical instruction paths and WARNS on a lingering block (off-but-still-instructing) with the converge command; plane-compare warns when the file mirror disagrees with the DB row (the Stop hook acting on the wrong truth) naming the re-sync; a read_error reports the state as UNKNOWN, never "off (default)"; resolved bundle + BOTH visibility postures + audience/reasons; on both branches an explicit private `facts.default_visibility` on a non-shared brain with remote readers (a harness receipt, or HTTP MCP clients active in 30d; listed in `private_default_remote_readers`) warns with the shared `PRIVATE_DEFAULT_REMOTE_CONSEQUENCE` text (`writeback-config.ts`), the same text `bootstrap harness` prints before consent; instruction blocks receipt-vs-live-probe-vs-drift compare (drift fix names the `config set` + `bootstrap harness` combo — the config set re-stamps the posture mirror so the re-render converges even after an out-of-band visibility flip) + AGENTS.override.md detection — and a receipt target in state `failed` is a STANDING warn regardless of the live probe (the one physical-survival path — a smoke-rollback strip that itself threw — leaves a current-looking block directing sessions at a rolled-back endpoint, and only the receipt state knows) naming the `bootstrap harness --yes` / `--remove` converge; validity-lapsed count; 7d counters (verbs usage sidecar's additive `remember_status` [stamped in `src/mcp/dispatch.ts`, ALL-MCP-callers semantics labeled honestly] + `writeback`/`writeback-bank` heartbeat events; `turns_banked` counts flush_skip_* — banked, enqueue declined); when at least 10 serve-side harvests finished (ok + error; a `writer_busy_requeued` retry is not finished) in those 7d and more than 20% failed, a warn names the failure count, the top error reason and the `gbrain sweep --once` recovery; `details.corpus_backlog` counts corpus files with no `.ingested` sidecar (pending, oldest age, past retention, deletion day) and, with writeback on, warns once one is past plain retention (E-N1) with the local/lossy disclosure. Null-engine runs report the file mirror honestly. `cross_lane_duplicates_7d` / `near_duplicates_shadow_7d` sum the `writeback_dedup` heartbeat events in both the on and off branches.
- Tests: `test/writeback-config.test.ts`, `test/mcp-instructions-writeback.test.ts`, `test/facts/writeback-gate.test.ts`, `test/hook-writeback-stop.serial.test.ts`, writeback-lane cases in `test/checkpoint-harvest.serial.test.ts`, `test/bootstrap-instructions-block.test.ts` + harness serial additions, `test/writeback-nudge.serial.test.ts`, `test/doctor-memory-writeback.test.ts`, the hermetic 5-step `test/ambient-writeback-lifecycle.serial.test.ts`, and the NON-GATING real-codex door (`test/e2e/bootstrap-real-codex.serial.test.ts`, ambient-writeback describe).
- `src/core/sweep.ts` + `src/commands/sweep.ts` — the serve-resident maintenance sweep (the lock owner closes the persistence loop): facts-fence reconciliation (zero-LLM, reuses the cycle extractor with a slug subset), deterministic link/timeline extraction over recent workspace pages (the same cores as `gbrain extract` — remote put_page deliberately skips these, the sweep is where the graph compounds), and spend-gated corpus ingest (skipped keyless; turn-boundary windows through `src/core/context/corpus-windows.ts`, at most `CORPUS_WINDOWS_PER_SWEEP` (8) per file and `CORPUS_WINDOWS_PER_SWEEP_TOTAL` (32, env `GBRAIN_CORPUS_WINDOWS_PER_SWEEP`) per sweep, each windowed file reported in `corpus_files[]` as `{file, windows_done, windows_remaining}`; `.ingested` is written when the last window of the current snapshot finishes, and a finished file re-enters when its stat no longer matches its `.progress`; writeback `.wb-` turn files stay one call; dream outputs and claude-cli self-captures classified by `isClaudeCliSelfSessionId` get a terminal `.ingested` sidecar with `skipped: dream_output` / `self_capture` (the shared `selfCaptureSidecarJson` writer) and are never extracted; the extractor input is `corpusTextForExtraction`, so pasted blocks never reach it). Bounded, fail-soft, never throws; the wall-clock budget stops the corpus pass between files and windows, never mid-extraction (an in-flight extraction finishes and writes its sidecar, E-N2, pinned by `test/sweep-budget-between-items.test.ts`); armed at serve startup (3s, best-effort) and on 10-min idle ticks through the injectable timer seam, everything unref'd; `serve --http` arms `armCorpusDrain` instead (X8: every `CORPUS_DRAIN_INTERVAL_MS`, 10 min, one sweep on a `CORPUS_DRAIN_BUDGET_MS` 60 s budget while a corpus `.txt` has no `.ingested` sidecar; never overlaps itself; pinned by `test/serve-http-corpus-drain.test.ts`); `GBRAIN_SWEEP=0` kills both. `gbrain sweep --once` is the trusted CLI seam `bootstrap verify` uses (CLI-only, never over MCP). The link pass threads the same `link_resolution.cross_source` opt-in and configured `sources.default` the CLI extract lanes pass into `resolveCandidateSources`, so an edge into another source is created (flag on) or counted as `cross_source_link` in `skipped` (flag off) — never silently dropped, and the reconcile never deletes a cross-source edge `extract links --source db` created. A corpus window's facts batch is keyed by its text (the sweep passes `reAdmitFileRefusals`), so when the canonical file check refused some of its entity requests, `resumeManagedFacts` admits their retained facts as a follow-up batch once every refused page passes that check again: no new extraction, the page's current revision, never wider than the current default visibility, committed requests reported rather than re-admitted, the stored and current writer grants re-checked, at most three follow-ups. Pinned by `test/managed-sweep-refused-window-retry.test.ts`.
-- `src/core/context/corpus-windows.ts` — windowed fact extraction of session-corpus files (#5887). `parseCorpusTurns` splits only at the exact `\n\n[user]\n` / `\n\n[assistant]\n` markers `toCorpusText` emits (text before the first marker is a header-less preamble); each user turn is paste-stripped whole before windowing; `planCorpusWindows` packs whole turns into windows of at most `MAX_TURN_TEXT_CHARS` (exported from `facts/extract.ts`) and splits a turn that cannot fit a fresh window at a newline or space, never inside a surrogate pair, repeating its `[role]` header on every piece. `<file>.progress` (suffix constants in `corpus-segments.ts`, GC'd by the session-end hook with the `.txt`, never deleted by its resume rewrite) holds `{version, generation, turns[{start,end,sha256}], continuation{turn_sha256, stripped_offset}|null, windows_done, finished(stat)|null, totals, entity_slugs, skipped_reason?, lease}`: `resumePoint` resumes at the first turn whose hash is unrecorded (appends, compaction remainders and same-size or shorter rewrites cost only their new turns). Every write is compare-and-set under the O_EXCL `<file>.progress.lock` (stale after 30 s): a window commits only when generation, last turn hash and lease owner still match and progress grows; the lease (stale after an hour, like the claim) stops a sweep whose `.in-progress` claim the hook deleted from extracting a window another extractor holds. `runCorpusWindows` returns `complete`/`partial`/`aborted`/`contended` with cumulative counts; an aborted window records nothing and transport errors release the lease and throw. `finishedCorpusFileState` decides `.ingested` files by stat compare (no rehash); `adoptFinishedCorpusFile` records a pre-window `.ingested` file at its current turns once (only when the sidecar is newer than the file). `checkpoint-harvest.ts` (`hook:compact`) extracts window 1 only: when more remains it publishes window 1's links, releases the receipt and leaves `.progress` for the sweep; an existing `.progress` means window 1 is done. Pinned by `test/corpus-windows.test.ts`, `test/sweep-corpus-windows.test.ts` and `test/managed-sweep-corpus-windows.test.ts` (managed coordinator, PGLite and Postgres).
+- `src/core/context/corpus-windows.ts` — windowed fact extraction of session-corpus files (#5887). `retireCorpusFile` / `retireCorpusTurns` (#6091) record a file or its off-period turns as finished without extracting (`skipped_reason`, a retire overrides another extractor's lease). `parseCorpusTurns` (defined in the provider-free `corpus-turns.ts`, re-exported here) splits only at the exact `\n\n[user]\n` / `\n\n[assistant]\n` markers `toCorpusText` emits (text before the first marker is a header-less preamble); each user turn is paste-stripped whole before windowing; `planCorpusWindows` packs whole turns into windows of at most `MAX_TURN_TEXT_CHARS` (exported from `facts/extract.ts`) and splits a turn that cannot fit a fresh window at a newline or space, never inside a surrogate pair, repeating its `[role]` header on every piece. `<file>.progress` (suffix constants in `corpus-segments.ts`, GC'd by the session-end hook with the `.txt`, never deleted by its resume rewrite) holds `{version, generation, turns[{start,end,sha256}], continuation{turn_sha256, stripped_offset}|null, windows_done, finished(stat)|null, totals, entity_slugs, skipped_reason?, lease}`: `resumePoint` resumes at the first turn whose hash is unrecorded (appends, compaction remainders and same-size or shorter rewrites cost only their new turns). Every write is compare-and-set under the O_EXCL `<file>.progress.lock` (stale after 30 s): a window commits only when generation, last turn hash and lease owner still match and progress grows; the lease (stale after an hour, like the claim) stops a sweep whose `.in-progress` claim the hook deleted from extracting a window another extractor holds. `runCorpusWindows` returns `complete`/`partial`/`aborted`/`contended` with cumulative counts; an aborted window records nothing and transport errors release the lease and throw. `finishedCorpusFileState` decides `.ingested` files by stat compare (no rehash); `adoptFinishedCorpusFile` records a pre-window `.ingested` file at its current turns once (only when the sidecar is newer than the file). `checkpoint-harvest.ts` (`hook:compact`) extracts window 1 only: when more remains it publishes window 1's links, releases the receipt and leaves `.progress` for the sweep; an existing `.progress` means window 1 is done. Pinned by `test/corpus-windows.test.ts`, `test/sweep-corpus-windows.test.ts` and `test/managed-sweep-corpus-windows.test.ts` (managed coordinator, PGLite and Postgres).
- `src/core/context/sync-ipc.ts` + `src/core/serve-sync-runner.ts` + `src/commands/sync-delegate.ts` — serve-delegated sync. `sync-ipc.ts` is the LEAF wire module: the `DELEGATED_SYNC_OPTION_FIELDS` table is the single source of truth for the validator, the CLI wire-builder, and the serve-side SyncOpts builder; `validateDelegatedSyncOptions` rejects unknown keys fail-closed (repoPath/skipLock/lockId/concurrency are unreachable from the socket), requires `timeoutSeconds` (0 = the explicit `--no-hard-deadline` unbounded encoding; everything else clamps to 24h), and `toWireSyncResult` truncates `pagesAffected` to 50 + a true total under the 256KB message cap. `serve-sync-runner.ts` is the serve-side module singleton: one job at a time (correctness still rests on the `gbrain-sync:<source>` row lock inside performSync), clientToken attach (a lost-ack retry finds its own running OR retained-terminal job instead of duplicate-running), per-job deadline timer, `[serve-sync]` lifecycle stderr lines, an idempotent shared `shutdownDelegatedSync()` both serve shutdown paths await BEFORE `engine.disconnect()` (the disconnect-mode drain is allowAbort:false after `_db` is nulled, so settle writes need the live engine; a registered drainer remains as backstop), and `maybeDrainDeferredEmbeds` (delegated jobs always run noEmbed — the cost gate lives in runSync — and the serve drains stale embeds afterwards via `runEmbedCore`, keyless-safe, cleared only when a drain finds nothing left; wire `noEmbed` records that the USER declined embeds and suppresses the drain). `sync-delegate.ts` is the CLI half: read-only holder probe (`probeLivePgliteHolder`), DEFAULT-DENY argv gate (any unclassified token refuses by name — a silently dropped `--exclude` would perform the wrong sync), engine-free source tiers (`resolveSourceIdEngineFree`), 1s poll loop tolerant of event-loop-blocked serves with a PID-probe backstop, `unknown_job` → serve-restarted resume hint, Ctrl-C → `sync_abort` (second Ctrl-C exits 130), and runSync's `pull_failed` verdict mirroring. Mounts and non-PGLite configs never delegate; opt-outs `--no-delegate` / `GBRAIN_SYNC_NO_DELEGATE=1` (client) and `GBRAIN_SERVE_SYNC_IPC=0` (serve). Pinned by `test/context/sync-ipc-validation.test.ts`, `test/sync-delegate-ladder.test.ts`, `test/serve-sync-runner.serial.test.ts`, `test/context/resolve-ipc-sync-kinds.test.ts`, and `test/e2e/sync-delegation-under-serve.serial.test.ts` (gating tier1 step).
- `src/core/capability.ts` — config-plane keyless/keyed detection + the honest capability report (per-provider keyless banner: OpenAI = semantic search + auto-extraction, Voyage = semantic search, Anthropic = auto-extraction) rendered by verify and the runbook. The extraction probe resolves through the SAME shared `resolveEffectiveChatModel` the gateway's reconfigure fallback uses (`GBRAIN_MODEL` > servable file pin > key-aware tier default), so a stale unservable pin degrades identically in the report and at runtime. Key/env fold comes from `mergedProviderEnv` (`src/core/ai/provider-env.ts`). Accepted limitation (documented in the module): DB-plane overrides (`models.default`, `facts.extraction_model`) are invisible to this engine-less probe; the runtime gate in `facts/extract.ts` and the engine-aware pre-enqueue gate in `facts/backstop.ts` are the backstops.
- `src/core/readiness.ts` — capability readiness (agent operator contract A7): `ReadinessEntry {capability, state, reason, why, fix, tier, asset?, http_visible}` for embeddings, chat_llm, writeback, tool_surface, sync, harness_wiring (config tier) and worker, backup per asset, migrations, sync (probed tier); each capability's reasons are a closed exported const (`EMBEDDINGS_REASONS`, …). `configReadiness(cfg, {transport})` is synchronous and memoized per (config object, transport); its only file read is one memoized `peekLock()` (none when this process holds the lock, via `heldLockFor`), plus one process-wide gbrain-binary PATH lookup on the CLI transport only. The HTTP view drops `http_visible:false` entries and passes the rest through `redactForTransport`. `probedReadiness(engine, {cache})` never calls `getStats`/`getHealth`; 60 s cache (`createReadinessCache()` per ServeHttpContext, process-wide otherwise), single-flight, 2 s per-probe bound, stale-while-revalidate; `readinessTail` is MCP initialize's best-effort 250 ms tail. `embeddingEnablement(cfg)` is the one "turn on embeddings" fix: resolves the datastore (PGLite path, Postgres, a mount from `--brain`/`GBRAIN_BRAIN_ID`) and the column width, picks a keyed provider that fits (or asks for a key with `inputs`), and emits in-place `init --force --embedding-model … --embedding-dimensions … [--path …]` or, for a mount, `embeddings enable --brain …`; it never rebuilds a column. `exclusiveFix` turns an exclusive fix into a two-step plan (actor `user` stops the owning serve named by `lock_owner`, `then` the command) unless the command delegates to the owner. A live status-only `serve --http` marker (`liveStatusMarkers`, config plane) makes CLI `harness_wiring` `serve_status_only` with `transport: 'http'` and the status reason's fix (`httpStatusServerEntry`, shared with doctor), never "start `gbrain serve --http`" on the port it holds. `harnessWiringEntry` builds harness-native stdio registration (absolute binary, `stdioServeArgv` with `REGISTRATION_SURFACE` = `starter`, or `input.surface` from `gbrain init --surface`; `configReadiness(cfg, {transport, surface})` skips the memo when a surface is passed), shared-HTTP `bootstrap harness`, or the MEMORY_VERBS install anchor, with effects and destinations disclosed. Consumers never coach on `disabled_by_choice`. Tests: `test/readiness.test.ts`, `test/readiness-http-cost.test.ts`, `test/readiness-advice-lint.test.ts` (no hand-written enablement advice outside this module; shrink-only baseline), `test/readiness-embedding-enablement.serial.test.ts` (the E2E matrix).
diff --git a/docs/guides/ambient-writeback.md b/docs/guides/ambient-writeback.md
index c8151b549f..2f9e02069c 100644
--- a/docs/guides/ambient-writeback.md
+++ b/docs/guides/ambient-writeback.md
@@ -46,7 +46,8 @@ default.
| `memory.auto_writeback` | What agents are told to save |
|---|---|
-| `off` (default) | Nothing — no instruction section, no backstop, no banking. |
+| unset (default) | Nothing — no instruction section, no Stop-hook backstop, no banking. The compaction harvest and SessionEnd transcripts still extract; see [Capture lanes and the off switch](#capture-lanes-and-the-off-switch). |
+| `off` | Nothing, and every ambient capture lane stops: the compaction harvest and SessionEnd transcripts too. |
| `salient` (recommended) | Durable, notable claims only: preferences, corrections, decisions, commitments, relationships, project-state changes. The backstop keeps medium+ notability facts. |
| `all` | Every direct factual user statement — still excluding operational chatter, assistant-generated content, secrets/credentials, and quoted third-party material. Precision rides the extractor's semantic skip rules (the second of the two filters); expect more low-value facts and more extraction spend. |
@@ -68,6 +69,63 @@ machine-local mirror gates the host's Stop hook, so enabling a team mount
never opts the host's own conversations into banking. A wrong-brain hook
bank remains harmless — the target serve's own DB gate decides.
+## Capture lanes and the off switch
+
+Three lanes turn captured session text into facts. Installing the harness
+hooks is the opt-in for the compaction and SessionEnd lanes, so they run while
+`memory.auto_writeback` is unset; the setting governs them once it is set
+explicitly. One gate (`captureGateDecision` in
+`src/core/facts/writeback-config.ts`) applies this table to every lane, under
+the file's claim and before any provider call:
+
+| `memory.auto_writeback` | Stop-hook turns (`.wb-` files, `hook:writeback`) | Compaction harvest (PreCompact segments and OpenClaw compactions, `hook:compact`) | SessionEnd transcripts (`<session>.txt`, `sweep:corpus`) |
+|---|---|---|---|
+| unset | retire | extract | extract |
+| `off` | retire | retire | retire |
+| `salient` / `all` | extract | extract | extract |
+| unrecognized value | hold | hold | hold |
+| DB row absent, file mirror on (plane drift) | hold | hold | hold |
+| DB row absent, file mirror `off` (a dual-write of off that never reached the DB) | retire | hold | hold |
+| config unreadable | hold | hold | hold |
+
+- **extract** runs the lane. **retire** records the file as finished without
+ extracting it (`.progress` holds its turn hashes and a `writeback_off`
+ `.ingested` sidecar names the reason), so a resumed session later extracts
+ only its new turns. **hold** leaves the file untouched until the config is
+ coherent again; `gbrain doctor` names the re-sync command.
+- **Capture time counts too.** When the brain's own file plane says `off`, the
+ PreCompact and SessionEnd hooks (and the OpenClaw compaction spool) write a
+ `<file>.capture-off.json` record naming the brain and the hashes of the turns
+ banked under off, before the file lands. Extraction applies the stricter of
+ that record and the current setting: a transcript banked under `off` is
+ never extracted, even after writeback is turned back on, and a resumed
+ session extracts only the turns banked under `on`. A record written by
+ another brain sharing the corpus directory is ignored.
+- **In-flight calls.** Facts from a capture lane carry their provenance into
+ the fact request, and admission re-checks the gate (code
+ `ambient_capture_off`). `off` applies to every capture-lane request admitted
+ after `config set` commits, including one whose provider call was already in
+ flight; requests admitted before it publish.
+- **What `off` does not stop:** facts already saved, explicit `remember` and
+ `extract_facts` calls, and fact extraction from pages written on purpose
+ (sync, `put_page`, imports). To review what the lanes already saved, run
+ `gbrain recall --since 30d --limit 500 --json` and look for rows whose
+ `source` is `hook:compact`, `hook:writeback` or `sweep:corpus`; forget a fact
+ only with the user's agreement (`gbrain forget <fact-id>`).
+- **Stopping capture entirely.** `off` stops extraction, but the hooks still
+ bank session text locally (it is retired, never extracted). To stop the
+ hooks themselves, SessionEnd included, run `gbrain bootstrap harness --remove`.
+- **Restart older workers.** Workers started on a gbrain older than this gate
+ don't run it: long-running `gbrain serve` processes (compaction harvest),
+ cron or autopilot sweeps (SessionEnd transcripts and the compaction
+ backstop), and any OpenClaw gateway hosting the gbrain context engine.
+ `gbrain config set memory.auto_writeback off` and `gbrain doctor`
+ (`details.restart_after_off`) list them; enforcement is incomplete until they
+ restart.
+- `gbrain config get memory.auto_writeback` prints the bare value on stdout and
+ each lane's effective action on the stderr `[config]` line; doctor's
+ `memory_writeback` row carries the same in `details.capture_lanes`.
+
## The three activation surfaces
1. **MCP `instructions` (all transports).** When enabled, the initialize
@@ -254,7 +312,7 @@ and reads `memory_writeback`).
| Harness | Real-time contract | Backstop |
|---|---|---|
| Claude Code | MCP instructions + managed user CLAUDE.md block | Stop-hook lane (above) |
-| Codex | MCP instructions + managed `$CODEX_HOME/AGENTS.md` block | **No per-turn hook exists** (SessionEnd only, 3s hard-kill). The existing SessionEnd capture → corpus → maintenance-sweep extraction lane is the delayed backstop — whole-session, next-sweep latency, governed by `facts.extraction_enabled` (it predates this feature). |
+| Codex | MCP instructions + managed `$CODEX_HOME/AGENTS.md` block | **No per-turn hook exists** (SessionEnd only, 3s hard-kill). The existing SessionEnd capture → corpus → maintenance-sweep extraction lane is the delayed backstop — whole-session, next-sweep latency. It runs while `memory.auto_writeback` is unset and stops on an explicit `off` ([Capture lanes and the off switch](#capture-lanes-and-the-off-switch)); `facts.extraction_enabled` stops it too. |
| Hermes | MCP instructions when connected | None wired. |
| opencode / OpenClaw / others | MCP instructions when connected | None wired — follow-ups filed. |
@@ -351,8 +409,10 @@ session or a compaction rewrite costs only its new turns. The compaction
harvest extracts the first window right away; the sweep does the rest. Set
`GBRAIN_CORPUS_WINDOWS_PER_SWEEP` to a positive integer in the environment of
the process that runs the sweep (`gbrain serve` or `gbrain sweep --once`) to
-change the 32-window total; the per-file cap of 8 is fixed. The off switch
-for all of this is the brain-wide `facts.extraction_enabled`. `gbrain sweep
+change the 32-window total; the per-file cap of 8 is fixed. An explicit
+`memory.auto_writeback off` stops all of this for session text
+([Capture lanes and the off switch](#capture-lanes-and-the-off-switch)); the
+brain-wide `facts.extraction_enabled` stops every fact extraction. `gbrain sweep
--once --json` lists `corpus_files[]` with `windows_done` and
`windows_remaining` per file. Transcripts marked done before windowed
extraction existed are not re-read; only turns added after the upgrade are
@@ -392,7 +452,10 @@ gbrain doctor | grep -A6 memory_writeback
# In a NEW agent session, say: "I prefer dark mode in every editor." Then:
gbrain recall --grep "dark mode"
gbrain sweep --once # drives the sweep backstop extraction immediately
-# Off switch (anytime; converge harness blocks with another bootstrap run):
+# Off switch (anytime; stops every capture lane, SessionEnd included;
+# converge harness blocks with another bootstrap run):
gbrain config set memory.auto_writeback off
gbrain bootstrap harness --yes
+# Stop the hooks from banking session text at all:
+gbrain bootstrap harness --remove
```
diff --git a/docs/guides/checkpoint-compaction.md b/docs/guides/checkpoint-compaction.md
index 1f97915f08..34890fdd35 100644
--- a/docs/guides/checkpoint-compaction.md
+++ b/docs/guides/checkpoint-compaction.md
@@ -57,6 +57,15 @@ happy path exactly-once and every failure path at-least-once (never loss):
| Session-end corpus + sweep pass 3 | SessionEnd hook + serve sweep | the post-last-boundary REMAINDER when segment coverage holds; the FULL transcript otherwise |
| `gbrain transcripts ingest --facts` | manual | whatever the operator points it at (operator's explicit choice) |
+The checkpoint harvest and the session-end lane run while
+`memory.auto_writeback` is unset (installing the harness hooks opted into
+them) and stop on an explicit `off`: banked segments and transcripts are
+retired, never extracted, and a capture made under `off` stays retired after
+writeback is turned back on. Read errors, plane drift and invalid values hold
+them untouched. The full truth table is in
+[ambient writeback](ambient-writeback.md#capture-lanes-and-the-off-switch).
+`gbrain transcripts ingest --facts` is an explicit choice and is never gated.
+
Coverage is decided by **exact-set hashes**, not counts: session-end
recomputes every boundary window's redacted hash from its own full parse and
requires each in the per-session ledger (`<session>.ledger.json`). A missed
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 4643e946af..5aad9b8b8f 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -72,6 +72,16 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c
More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-connect.md#troubleshooting)
+### ambient_capture_off
+
+<a id="ambient_capture_off"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| memory.auto_writeback no longer allows this ambient capture lane, so facts extracted from captured session text were dropped before admission. | An explicit off (or an incoherent setting) applies to every capture-lane fact request admitted after the change, including one whose provider call was already in flight; requests admitted earlier still publish. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/ambient-writeback.md#capture-lanes-and-the-off-switch](../../docs/guides/ambient-writeback.md#capture-lanes-and-the-off-switch)
+
### ambiguous_id
<a id="ambiguous_id"></a>
diff --git a/docs/guides/memory-boundaries.md b/docs/guides/memory-boundaries.md
index cec7ecc6e1..faeeb9d69d 100644
--- a/docs/guides/memory-boundaries.md
+++ b/docs/guides/memory-boundaries.md
@@ -21,7 +21,12 @@ instructions. Do not put secrets in memory pages. A durable decision about a
setup can be recorded without copying its credentials or assuming that setup is
active in another harness.
-Automatic capture is opt-in. Time-limited facts need an explicit TTL; ordinary
+Automatic capture is opt-in. Installing the harness hooks opts into the
+compaction and SessionEnd capture lanes; `gbrain config set
+memory.auto_writeback off` stops every capture lane, and `gbrain bootstrap
+harness --remove` stops the hooks from banking session text at all (see
+[ambient writeback](ambient-writeback.md#capture-lanes-and-the-off-switch)).
+Time-limited facts need an explicit TTL; ordinary
saved facts do not expire just because they describe a temporary situation.
`forget` withdraws a fact from active recall, not from all source material,
history, or private backups. See [ambient writeback](ambient-writeback.md).
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 86d6d9188e..a76e336d9d 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -34,7 +34,7 @@ src/commands/sources.ts 2042 ratchet +5 #5988: sources status/retry-held help ro
src/core/link-extraction.ts 2204 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge; links joined only by commas/conjunctions share the verb before the first (coordinated); board roles (BOARD_RE, BOARD_AFTER_RE) resolve to invested_in for an investor page and advises otherwise, never works_at
src/core/embedding-migration.ts 1587 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_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verify; +17 #5334: smoke check samples one representative chunk per distinct page (bounded index-ordered batch walk, longest chunk re-read under the page lock, title-prefixed bounded query); +1 #5334: the smoke-query length limits are shared with the worst-case budget
src/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 refresh
-src/commands/hook.ts 1916 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; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts)
+src/commands/hook.ts 1919 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; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts)
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 1896 ratchet +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +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); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS
src/core/bootstrap/harness.ts 2711 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); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env
diff --git a/src/commands/config.ts b/src/commands/config.ts
index dc61c9b86c..517a11ee77 100644
--- a/src/commands/config.ts
+++ b/src/commands/config.ts
@@ -777,7 +777,7 @@ export async function runConfig(engine: BrainEngine, args: string[]) {
if (fileHad || dbDeleted > 0) {
console.log(`Unset ${key} (${[fileHad ? 'file plane' : null, dbDeleted > 0 ? 'db plane' : null].filter(Boolean).join(' + ')})`);
if (key === 'memory.auto_writeback') {
- console.log('Ambient writeback resolves off while unset. If harness instruction blocks were installed, remove them: gbrain bootstrap harness --yes (converges on off).');
+ for (const line of (await import('../core/facts/writeback-config.ts')).writebackUnsetMessage()) console.log(line);
}
} else {
console.error(`Config key not found: ${key}`);
@@ -903,7 +903,7 @@ export async function runConfig(engine: BrainEngine, args: string[]) {
const out = typeof val === 'string' ? val : JSON.stringify(val);
console.log(rawFlag ? out : redactConfigValue(key, out));
if (dbAuthoritative) {
- console.error(`[config] source: ${dbVal !== null && dbVal !== undefined ? 'db plane (authoritative for this key)' : 'file mirror (no DB row)'}`);
+ console.error(`[config] source: ${dbVal !== null && dbVal !== undefined ? 'db plane (authoritative for this key)' : 'file mirror (no DB row)'}${await writebackLanesNote(engine, key)}`);
if (dbVal !== null && dbVal !== undefined && fileVal !== undefined && fileVal !== null && String(fileVal) !== String(dbVal)) {
console.error(`[config] WARN: file mirror disagrees ('${String(fileVal)}') — planes diverged; re-run: gbrain config set ${key} ${String(dbVal)}`);
}
@@ -1081,7 +1081,7 @@ export async function runConfig(engine: BrainEngine, args: string[]) {
// The off switch gates instructions + extraction immediately, but
// previously-installed harness instruction blocks keep directing new
// sessions until converged — say so (red-team review, this wave).
- console.log('Ambient writeback off. If harness instruction blocks were installed, remove them: gbrain bootstrap harness --yes (converges on off).');
+ for (const line of (await import('../core/facts/writeback-config.ts')).writebackOffMessage()) console.log(line);
}
return;
}
@@ -1461,3 +1461,10 @@ async function refuseSchemaSizingKey(key: 'embedding_model' | 'embedding_dimensi
console.error(`[config] No --force escape: silently writing a no-op preserves the bug class this rejection closes.`);
process.exit(1);
}
+
+/** #6091: the per-lane effective state of `memory.auto_writeback`, appended to `config get`'s stderr source line. */
+async function writebackLanesNote(engine: BrainEngine, key: string): Promise<string> {
+ if (key !== 'memory.auto_writeback') return '';
+ const { captureLaneSummary, resolveWritebackConfig } = await import('../core/facts/writeback-config.ts');
+ return `; capture lanes: ${captureLaneSummary(await resolveWritebackConfig(engine, loadConfig(), { gate: true }))}`;
+}
diff --git a/src/commands/doctor/checks/memory-writeback.ts b/src/commands/doctor/checks/memory-writeback.ts
index aa0c6a8ce5..ad638530ed 100644
--- a/src/commands/doctor/checks/memory-writeback.ts
+++ b/src/commands/doctor/checks/memory-writeback.ts
@@ -28,8 +28,10 @@ import type { Effect } from '../../../core/agent-output.ts';
import { loadConfig } from '../../../core/config.ts';
import { resolveGbrainHome } from '../../../core/gbrain-home.ts';
import {
+ captureLaneStates,
resolveWritebackConfig,
resolveWritebackConfigFromFile,
+ WRITEBACK_RESTART_AFTER_OFF,
AUTO_WRITEBACK_NOTICE_KEY,
PRIVATE_DEFAULT_REMOTE_CONSEQUENCE,
} from '../../../core/facts/writeback-config.ts';
@@ -163,6 +165,7 @@ export async function buildMemoryWritebackCheck(engine: BrainEngine | null): Pro
nudge_shown: nudgeShown === 'true',
...(wb.read_error ? { read_error: true } : {}),
...(wb.plane_drift ? { plane_drift: true } : {}),
+ capture_lanes: captureLaneStates(await resolveWritebackConfig(engine, fileCfg, { gate: true })),
counters_note: `local, append-only, loss-tolerant observability over the last ${COUNTER_WINDOW_DAYS}d — never a source of truth`,
};
@@ -224,12 +227,16 @@ export async function buildMemoryWritebackCheck(engine: BrainEngine | null): Pro
offProblems.push(`ambient writeback is off but instruction blocks are still installed for ${lingering.join(', ')} — new sessions keep saving. Remove: gbrain bootstrap harness --yes (converges on off)`);
}
if (privateRemoteProblem) offProblems.push(privateRemoteProblem);
+ const explicitOff = wb.raw_mode === 'off';
+ if (explicitOff) details.restart_after_off = WRITEBACK_RESTART_AFTER_OFF;
return {
name: MEMORY_WRITEBACK_CHECK_NAME,
status: offProblems.length ? 'warn' : 'ok',
message: offProblems.length
? `ambient writeback off: ${offProblems.join('; ')}`
- : 'ambient writeback off (default). Enable: gbrain config set memory.auto_writeback salient',
+ : explicitOff
+ ? 'ambient writeback off (explicit): every capture lane, SessionEnd transcripts included, retires banked session text. Enforcement is incomplete until workers started on an older gbrain restart (details.restart_after_off). Enable: gbrain config set memory.auto_writeback salient'
+ : 'ambient writeback off (default): Stop-hook turn capture is off, but the compaction harvest and SessionEnd transcripts still extract (installing the harness hooks opted into them; stop them: gbrain config set memory.auto_writeback off). Enable: gbrain config set memory.auto_writeback salient',
details,
};
}
diff --git a/src/commands/hook.ts b/src/commands/hook.ts
index 1c9cd86cc7..e5b1bb1c64 100644
--- a/src/commands/hook.ts
+++ b/src/commands/hook.ts
@@ -78,6 +78,7 @@ import {
import { hookLaneLabel, resolveSeat, seatReasonHint, writeSeatSidecar } from '../core/context/seat.ts';
import { gateWritebackTurn, WRITEBACK_SKIP_REASONS } from '../core/facts/writeback-gate.ts';
import { resolveWritebackConfigFromFile } from '../core/facts/writeback-config.ts';
+import { recordCaptureIfOff } from '../core/context/capture-consent.ts';
import { memorableGateAllowed, recordAndRelayReceipt, redactedToolCallsJson } from '../core/context/hook-heartbeat.ts';
import { captureSpecFor } from '../core/transcripts/capture-spec.ts';
import {
@@ -1371,6 +1372,7 @@ async function hookCompact(io: HookIo): Promise<number> {
remainingMs: remaining,
minScanMs: SEGMENT_MIN_BUDGET_MS,
minWriteMs: SEGMENT_WRITE_MIN_BUDGET_MS,
+ beforeWrite: (file, text) => { recordCaptureIfOff(cfg, file, text, process.env.GBRAIN_SOURCE); },
});
segment = banked.segment;
const flushCorpusFile = banked.flushCorpusFile;
@@ -1786,6 +1788,7 @@ async function hookSessionEnd(io: HookIo): Promise<number> {
// completion sidecar survived the overwrite).
const corpusFile = join(dir, `${sessionId}.txt`);
const tmpCorpus = `${corpusFile}.tmp-${process.pid}`;
+ recordCaptureIfOff(cfg, corpusFile, text, process.env.GBRAIN_SOURCE); // #6091, before the rename
writeFileSync(tmpCorpus, text, { mode: 0o600 });
renameSync(tmpCorpus, corpusFile);
// Additive signal for a local third-party consumer (never gbrain
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 449dee9b44..91edf1d383 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -257,6 +257,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.97.0', text: 'Google Calendar sync writes only events between `historyDays` back and 60 days ahead; `gbrain sync --full` removes pages for in-window events the calendar no longer lists (more than 200 is refused and reported partial).' },
{ since: '0.60.98.0', text: 'Managed sync now holds a file whose facts or takes fence cannot be imported (code `invalid_fence`; `gbrain sources status <id>` names the fence, section and rows) instead of blocking the whole source, and a source such a fence blocked before recovers on its next sync. Coordinated writes refuse such a fence with `invalid_fence` (wire `error` stays `invalid_params`, or `take_row_collision`). `gbrain config set sync.holds fail` keeps fail-closed blocking.' },
{ since: '0.60.99.0', text: 'Fixable facts and takes fences are now rewritten instead of held or refused: managed sync, put_page and the fact and take writers normalize a fence whose meaning is unambiguous (a missing end marker after the table, two-dash takes markers, zero or duplicate row numbers, header aliases, invented kinds and enum synonyms, assistant holders, percent confidences) without changing a claim or an existing row number, and managed sync commits the rewritten file. Results report `fences_normalized`; `gbrain sync --dry-run` lists `would_normalize`. `gbrain config set fences.normalize false` turns it off (such fences are then held or refused).' },
+ { since: '0.0.0-wave11', text: 'An explicit `memory.auto_writeback off` now stops every ambient capture lane: the compaction harvest (PreCompact segments and OpenClaw compactions) and SessionEnd transcripts stop extracting too, and session text banked under off is never extracted later, even after writeback is turned back on. Unset keeps both lanes running. An unreadable, drifted or unrecognized setting now holds them instead of extracting. Restart `gbrain serve`, cron or autopilot sweeps and OpenClaw gateways started on an older version; `gbrain bootstrap harness --remove` stops the hooks from banking session text at all.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/context-engine.ts b/src/core/context-engine.ts
index 4d4cfa38e0..5dcb6dd2a3 100644
--- a/src/core/context-engine.ts
+++ b/src/core/context-engine.ts
@@ -981,6 +981,7 @@ export function createGBrainContextEngine(ctx: {
const cfg = loadConfig();
const dir = await engineCorpusDir(cfg);
await recordOpenclawSeat(dir, sessionId, sessionFile);
+ (await import('./context/capture-consent.ts')).recordCaptureIfOff(cfg, `${dir}/${segs.segmentFileName(sessionId, segs.segmentHash(rendered.text))}`, rendered.text);
const w = segs.writeSegment(dir, sessionId, rendered.text);
const ordinal = segs.appendSegmentLedger(dir, sessionId, w.hash);
const memo = checkpointMemo.get(sessionId) ?? { links: [], polls: 0, expectSeg: null, settled: false };
@@ -1085,6 +1086,8 @@ export function createGBrainContextEngine(ctx: {
if (ingested(fullPath + sweep.CORPUS_INGESTED_SUFFIX)) {
return { status: 'banked', reason: 'already_ingested' };
}
+ const gate = await (await import('./context/capture-consent.ts')).gateCorpusFile(pg, fullPath, 'compact');
+ if (gate.action !== 'extract') return { status: 'banked', reason: gate.reason };
const { extractionAvailableForEngine } = await import('./facts/extraction-availability.ts');
if (!(await extractionAvailableForEngine(pg))) return { status: 'banked', reason: 'keyless' };
const { isFactsExtractionEnabled } = await import('./facts/extract.ts');
diff --git a/src/core/context/capture-consent.ts b/src/core/context/capture-consent.ts
new file mode 100644
index 0000000000..313c942225
--- /dev/null
+++ b/src/core/context/capture-consent.ts
@@ -0,0 +1,145 @@
+/**
+ * capture-consent.ts — #6091: `memory.auto_writeback off` applied to session
+ * text captured by the harness hooks, durably and per brain.
+ *
+ * Capture side (engine-free; the PreCompact and SessionEnd hooks and the
+ * OpenClaw compaction spool): when the brain's own file plane says an explicit
+ * `off`, the hook writes `<file>.capture-off.json` BEFORE the corpus file is
+ * renamed into place. The record names the brain (its config directory, which
+ * the hook command's GBRAIN_HOME selects) and the hashes of every turn banked
+ * under off. A resumed session that later rewrites `<sid>.txt` under `on`
+ * keeps the record, so those turns stay retired and only the new turns
+ * extract; a later `on` never revives them.
+ *
+ * Extraction side (serve harvest, OpenClaw rung 3, the sweep): under the claim,
+ * before any provider call, `applyCaptureGate` takes the current decision
+ * (`captureGateDecision`) and the stricter capture-time record together:
+ * - hold: nothing is touched;
+ * - retire: `.progress` finished at the current turns plus a `writeback_off`
+ * sidecar (`retireCorpusFile`);
+ * - extract: this brain's record folds its turns into `.progress`; a file
+ * whose every turn was captured under off is retired, otherwise extraction
+ * resumes past the retired turns. A record written by another brain (a
+ * shared corpus directory) is ignored.
+ *
+ * Publication side: `assertAmbientCaptureAdmissible` (facts/capture-sources.ts) re-checks the gate when a
+ * capture-lane fact request is admitted, so `off` applies to every ambient
+ * request admitted after `config set` commits, including one whose provider
+ * call was already in flight. Requests admitted before it publish.
+ */
+
+import { createHash } from 'node:crypto';
+import { readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
+import { readFile, writeFile } from 'node:fs/promises';
+import { basename } from 'node:path';
+import type { BrainEngine } from '../engine.ts';
+import type { GBrainConfig } from '../config.ts';
+import { configDir, loadConfig } from '../config.ts';
+import { captureGateDecision, fileCaptureIsOff, resolveWritebackConfig, type CaptureGateDecision, type CaptureGateLane, type WritebackMode } from '../facts/writeback-config.ts';
+import { parseCorpusTurns } from './corpus-turns.ts';
+import { CAPTURE_OFF_SUFFIX, parseSegmentFileName, parseWbFileName, writebackOffSidecarJson } from './corpus-segments.ts';
+
+export { CAPTURE_OFF_SUFFIX };
+
+interface CaptureOffRecord {
+ version: 1;
+ brain: string;
+ source: string | null;
+ at: string;
+ turns: string[];
+}
+
+/** This process's brain: a hash of its resolved config directory. */
+export function brainIdentity(): string {
+ const dir = configDir();
+ let resolved = dir;
+ try { resolved = realpathSync(dir); } catch { /* not created yet: the configured path is the identity */ }
+ return createHash('sha256').update(resolved).digest('hex').slice(0, 24);
+}
+
+/** The capture gate lane of a corpus file, from its name. */
+export function captureLaneForFile(name: string): CaptureGateLane {
+ if (parseWbFileName(name)) return 'writeback';
+ if (parseSegmentFileName(name)) return 'compact';
+ return 'session_end';
+}
+
+function readRecord(path: string): CaptureOffRecord | null {
+ try {
+ const r = JSON.parse(readFileSync(path, 'utf8')) as CaptureOffRecord;
+ return r && r.version === 1 && typeof r.brain === 'string' && Array.isArray(r.turns) ? r : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Capture side: when `cfg` (the brain's own file plane) says an explicit off,
+ * record every turn of `text` as captured under off for `file`. Call it before
+ * the corpus file is renamed into place. Throws on a write failure, so the
+ * caller banks nothing rather than banking text without its record.
+ */
+export function recordCaptureIfOff(cfg: GBrainConfig | null | undefined, file: string, text: string, source?: string | null): boolean {
+ if (!fileCaptureIsOff(cfg)) return false;
+ const path = file + CAPTURE_OFF_SUFFIX;
+ const brain = brainIdentity();
+ const prior = readRecord(path);
+ const turns = new Set(prior && prior.brain === brain ? prior.turns : []);
+ for (const t of parseCorpusTurns(text)) turns.add(t.sha256);
+ const record: CaptureOffRecord = { version: 1, brain, source: source ?? null, at: new Date().toISOString(), turns: [...turns] };
+ const tmp = `${path}.tmp-${process.pid}`;
+ writeFileSync(tmp, JSON.stringify(record) + '\n', { mode: 0o600 });
+ try {
+ renameSync(tmp, path);
+ } catch (e) {
+ rmSync(tmp, { force: true });
+ throw e;
+ }
+ return true;
+}
+
+/** The engine's gate decision for each lane, resolved once (DB plane authoritative, file mirror for drift). */
+export async function resolveCaptureGate(engine: BrainEngine): Promise<Record<CaptureGateLane, CaptureGateDecision> & { mode: WritebackMode }> {
+ const cfg = await resolveWritebackConfig(engine, loadConfig(), { gate: true });
+ return {
+ mode: cfg.mode,
+ writeback: captureGateDecision(cfg, 'writeback'),
+ compact: captureGateDecision(cfg, 'compact'),
+ session_end: captureGateDecision(cfg, 'session_end'),
+ };
+}
+
+export interface AppliedCaptureGate {
+ action: 'extract' | 'retire' | 'hold';
+ reason: string;
+}
+
+/**
+ * Extraction side, under the caller's claim and before any provider call:
+ * applies `decision` and this brain's capture-time record to `full`.
+ */
+export async function applyCaptureGate(full: string, decision: CaptureGateDecision): Promise<AppliedCaptureGate> {
+ if (decision.action === 'hold') return decision;
+ const name = basename(full);
+ const { retireCorpusFile, retireCorpusTurns } = await import('./corpus-windows.ts');
+ if (decision.action === 'retire') {
+ if (parseWbFileName(name)) {
+ await writeFile(full + '.ingested', writebackOffSidecarJson());
+ return decision;
+ }
+ return await retireCorpusFile(full) ? decision : { action: 'hold', reason: 'retire_deferred' };
+ }
+ const record = readRecord(full + CAPTURE_OFF_SUFFIX);
+ if (!record || record.brain !== brainIdentity()) return decision;
+ const retired = new Set(record.turns);
+ const current = parseCorpusTurns(await readFile(full, 'utf8'));
+ if (current.every((t) => retired.has(t.sha256))) {
+ return await retireCorpusFile(full) ? { action: 'retire', reason: 'captured_under_off' } : { action: 'hold', reason: 'retire_deferred' };
+ }
+ return await retireCorpusTurns(full, record.turns) ? decision : { action: 'hold', reason: 'retire_deferred' };
+}
+
+/** `resolveCaptureGate` + `applyCaptureGate` for one file of one lane. */
+export async function gateCorpusFile(engine: BrainEngine, full: string, lane: CaptureGateLane): Promise<AppliedCaptureGate> {
+ return applyCaptureGate(full, (await resolveCaptureGate(engine))[lane]);
+}
diff --git a/src/core/context/checkpoint-harvest.ts b/src/core/context/checkpoint-harvest.ts
index 03191875f6..ced6058b0f 100644
--- a/src/core/context/checkpoint-harvest.ts
+++ b/src/core/context/checkpoint-harvest.ts
@@ -277,6 +277,9 @@ function classifyHarvestFailure(job: HarvestJob, e: unknown): { outcome: 'degrad
if (job.lane === 'writeback' && isWriterBusy(e) && requeueWhileWriterBusy(job)) {
return { outcome: 'degraded', reason: 'writer_busy_requeued' };
}
+ // #6091: writeback turned off while the provider call was in flight; admission
+ // refused the facts and the next pass retires the file.
+ if (e instanceof OperationError && e.code === 'ambient_capture_off') return { outcome: 'degraded', reason: 'writeback_off_inflight' };
const reason = harvestErrorReason(e);
logFirstHarvestError(job, reason, e);
return { outcome: 'error', reason };
@@ -364,6 +367,16 @@ async function runOne(job: HarvestJob): Promise<{
if (job.lane === 'writeback') return await runWritebackTurn(job, full, ingestedPath);
+ // #6091: the capture gate runs under the claim before any provider call or
+ // receipt republication (serve compact lane and OpenClaw rung 2).
+ const { applyCaptureGate, resolveCaptureGate } = await import('./capture-consent.ts');
+ const gate = await applyCaptureGate(full, (await resolveCaptureGate(job.engine)).compact);
+ if (gate.action === 'hold') return { outcome: 'degraded', reason: gate.reason };
+ if (gate.action === 'retire') {
+ await rm(receiptPath, { force: true }).catch(() => {});
+ return { outcome: 'ok', reason: gate.reason };
+ }
+
// Receipt retry path (codex round 2): extraction already happened; the
// manifest publish failed transiently. Re-publish WITHOUT re-extracting.
let receipt = await readReceipt(receiptPath);
@@ -533,29 +546,21 @@ async function runWritebackTurn(job: HarvestJob, full: string, ingestedPath: str
await writeFile(ingestedPath, selfCaptureSidecarJson());
return { outcome: 'ok', reason: 'self_capture' };
}
- const { resolveWritebackConfig } = await import('../facts/writeback-config.ts');
- const { loadConfig } = await import('../config.ts');
- // Gate semantics ({gate:true}): a config READ FAILURE is OFF but NOT
- // terminal — skip with no sidecar (claim releases, sweep retries when the
- // DB returns). Same for PLANE DRIFT (DB row absent while the file mirror
- // says enabled — a failed dual-write is not operator intent) and for an
- // UNRECOGNIZED mode value (a typo is not a decision). Only a
- // genuinely-resolved OFF writes the terminal sidecar: that one is intent.
- // The gate resolves BEFORE the capability/kill-switch checks: an
- // operator's OFF must retire the banked turn even on a keyless or
- // extraction-disabled brain — otherwise the file lingers eligible and a
- // later re-enable would extract turns the operator already revoked
- // (codex re-review, this wave).
- const wb = await resolveWritebackConfig(job.engine, loadConfig(), { gate: true });
- if (wb.read_error) return { outcome: 'degraded', reason: 'gate_unreadable' };
- if (!wb.enabled && (wb.plane_drift || !wb.mode_valid)) {
- return { outcome: 'degraded', reason: wb.plane_drift ? 'writeback_plane_drift' : 'writeback_mode_invalid' };
- }
- if (!wb.enabled) {
- const { writebackOffSidecarJson } = await import('./corpus-segments.ts');
- await writeFile(ingestedPath, writebackOffSidecarJson());
- return { outcome: 'ok', reason: 'writeback_off' };
- }
+ // Gate semantics (captureGateDecision, resolved {gate:true}): a config READ
+ // FAILURE, PLANE DRIFT (DB row absent while the file mirror says enabled — a
+ // failed dual-write is not operator intent) and an UNRECOGNIZED mode value
+ // hold: no sidecar, the claim releases and the sweep retries once the config
+ // is coherent. Only a genuinely-resolved OFF (or unset: this lane is opt-in)
+ // writes the terminal sidecar. The gate resolves BEFORE the
+ // capability/kill-switch checks: an operator's OFF must retire the banked
+ // turn even on a keyless or extraction-disabled brain — otherwise the file
+ // lingers eligible and a later re-enable would extract turns the operator
+ // already revoked (codex re-review, this wave).
+ const { applyCaptureGate, resolveCaptureGate } = await import('./capture-consent.ts');
+ const gate = await resolveCaptureGate(job.engine);
+ const applied = await applyCaptureGate(full, gate.writeback);
+ if (applied.action === 'hold') return { outcome: 'degraded', reason: applied.reason };
+ if (applied.action === 'retire') return { outcome: 'ok', reason: applied.reason };
const { extractionAvailableForEngine } = await import('../facts/extraction-availability.ts');
if (!(await extractionAvailableForEngine(job.engine, job.capabilities))) {
return { outcome: 'degraded', reason: 'keyless' };
@@ -580,7 +585,7 @@ async function runWritebackTurn(job: HarvestJob, full: string, ingestedPath: str
mode: 'inline',
remote: false,
abortSignal: abort.signal,
- notabilityFilter: wb.mode === 'salient' ? 'medium-and-up' : 'all',
+ notabilityFilter: gate.mode === 'salient' ? 'medium-and-up' : 'all',
// visibility deliberately unset → resolveDefaultVisibility [ENG-8] —
// the backstop inherits extract_facts' contract, never widened (req 6).
});
diff --git a/src/core/context/corpus-segments.ts b/src/core/context/corpus-segments.ts
index be503a9db5..eb032ce267 100644
--- a/src/core/context/corpus-segments.ts
+++ b/src/core/context/corpus-segments.ts
@@ -94,6 +94,8 @@ const SEAT_ORPHAN_GRACE_MS = 10 * 60 * 1000;
* publish). Lives HERE so the engine-free hook lane can GC orphaned receipts
* without importing the engine-typed harvest module. */
export const HARVEST_RECEIPT_SUFFIX = '.receipt.json';
+/** #6091: capture-time consent record (capture-consent.ts); reaped with its corpus file after a grace period. */
+export const CAPTURE_OFF_SUFFIX = '.capture-off.json';
/** #5887 window-progress sidecar (context/corpus-windows.ts) and its CAS
* lock. Engine-free home so the hook's GC reaps both with the `.txt`; the
* hook's resume rewrite never deletes them. */
@@ -428,7 +430,11 @@ export async function bankCompactSegment(
sessionId: string,
allTurns: WindowTurn[],
boundaryTurnIndexes: number[],
- opts: { remainingMs: () => number; minScanMs: number; minWriteMs: number; maxTurns?: number },
+ opts: {
+ remainingMs: () => number; minScanMs: number; minWriteMs: number; maxTurns?: number;
+ /** #6091: runs before the segment is renamed into place (capture-time consent record); a throw banks nothing. */
+ beforeWrite?: (file: string, text: string) => void;
+ },
): Promise<{ segment: string; flushCorpusFile?: string; hash?: string; ordinal?: number }> {
try {
const windowTurns = sliceBoundaryWindow(allTurns, boundaryTurnIndexes, {
@@ -440,6 +446,7 @@ export async function bankCompactSegment(
if (!rendered) return { segment: 'scan_unavailable' };
if (!rendered.text.trim()) return { segment: 'empty_window' };
if (opts.remainingMs() < opts.minWriteMs) return { segment: 'deadline_write' };
+ opts.beforeWrite?.(join(dir, segmentFileName(sessionId, segmentHash(rendered.text))), rendered.text);
const w = writeSegment(dir, sessionId, rendered.text);
const ordinal = appendSegmentLedger(dir, sessionId, w.hash);
return {
@@ -580,6 +587,11 @@ export function gcCorpusArtifacts(
}
continue;
}
+ if (name.endsWith(CAPTURE_OFF_SUFFIX)) {
+ // Written BEFORE its corpus file lands: only an orphan past the grace period is reaped.
+ if (!existsSync(p.slice(0, -CAPTURE_OFF_SUFFIX.length)) && statSync(p).mtimeMs < Date.now() - SEAT_ORPHAN_GRACE_MS) rmSync(p, { force: true });
+ continue;
+ }
if (name.endsWith('.ledger.json')) {
if (statSync(p).mtimeMs < cutoff) rmSync(p, { force: true });
continue;
diff --git a/src/core/context/corpus-turns.ts b/src/core/context/corpus-turns.ts
new file mode 100644
index 0000000000..ce411cf673
--- /dev/null
+++ b/src/core/context/corpus-turns.ts
@@ -0,0 +1,68 @@
+/**
+ * corpus-turns.ts — the turn grammar of session-corpus files (`toCorpusText`
+ * output: `[user]` / `[assistant]` blocks separated by blank lines) and each
+ * turn's identity hash. Engine-free and provider-free, so the harness hooks can
+ * name the turns they bank (capture-consent.ts) without loading the extractor.
+ * corpus-windows.ts plans extraction windows over these turns.
+ */
+
+import { createHash } from 'node:crypto';
+import { stripPastedContent } from '../transcripts/pasted-content.ts';
+
+export interface CorpusTurn {
+ role: 'user' | 'assistant' | null;
+ /** UTF-8 byte offsets of the turn in the raw file (header included). */
+ start: number;
+ end: number;
+ /** SHA-256 of the raw turn text (trailing whitespace trimmed). */
+ sha256: string;
+ header: string;
+ /** Extractor-facing body: pastes stripped (user turns), trimmed. */
+ body: string;
+}
+
+const sha256 = (text: string): string => createHash('sha256').update(text).digest('hex');
+
+/** Split corpus text into turns at the exact `toCorpusText` markers. */
+export function parseCorpusTurns(raw: string): CorpusTurn[] {
+ const starts: Array<{ at: number; role: 'user' | 'assistant' }> = [];
+ if (raw.startsWith('[user]\n')) starts.push({ at: 0, role: 'user' });
+ else if (raw.startsWith('[assistant]\n')) starts.push({ at: 0, role: 'assistant' });
+ const USER = '\n\n[user]\n';
+ const ASSISTANT = '\n\n[assistant]\n';
+ let nextUser = raw.indexOf(USER);
+ let nextAssistant = raw.indexOf(ASSISTANT);
+ while (nextUser >= 0 || nextAssistant >= 0) {
+ const isUser = nextAssistant < 0 || (nextUser >= 0 && nextUser < nextAssistant);
+ const at = isUser ? nextUser : nextAssistant;
+ starts.push({ at: at + 2, role: isUser ? 'user' : 'assistant' });
+ if (isUser) nextUser = raw.indexOf(USER, at + 2);
+ else nextAssistant = raw.indexOf(ASSISTANT, at + 2);
+ }
+
+ let charAt = 0;
+ let byteAt = 0;
+ const bytes = (index: number): number => {
+ byteAt += Buffer.byteLength(raw.slice(charAt, index), 'utf8');
+ charAt = index;
+ return byteAt;
+ };
+ const turns: CorpusTurn[] = [];
+ const push = (role: CorpusTurn['role'], from: number, to: number): void => {
+ const span = raw.slice(from, to);
+ const header = role ? `[${role}]\n` : '';
+ const rawBody = span.slice(header.length);
+ const body = (role === 'user' ? stripPastedContent(rawBody).text : rawBody).trim();
+ const start = bytes(from);
+ turns.push({ role, start, end: bytes(to), sha256: sha256(span.trimEnd()), header, body });
+ };
+ const firstAt = starts.length ? starts[0].at : raw.length;
+ if (firstAt > 0) {
+ const preambleEnd = starts.length ? firstAt - 2 : raw.length;
+ if (raw.slice(0, preambleEnd).trim()) push(null, 0, preambleEnd);
+ }
+ for (let k = 0; k < starts.length; k++) {
+ push(starts[k].role, starts[k].at, k + 1 < starts.length ? starts[k + 1].at - 2 : raw.length);
+ }
+ return turns;
+}
diff --git a/src/core/context/corpus-windows.ts b/src/core/context/corpus-windows.ts
index e808156333..34b1dc1ac0 100644
--- a/src/core/context/corpus-windows.ts
+++ b/src/core/context/corpus-windows.ts
@@ -27,14 +27,16 @@
* `.in-progress` claim discipline; this module never touches claims.
*/
-import { createHash, randomUUID } from 'node:crypto';
+import { randomUUID } from 'node:crypto';
import { readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { MAX_TURN_TEXT_CHARS } from '../facts/extract.ts';
import type { runFactsPipeline } from '../facts/backstop.ts';
-import { stripPastedContent } from '../transcripts/pasted-content.ts';
+import { parseCorpusTurns, type CorpusTurn } from './corpus-turns.ts';
import { CORPUS_PROGRESS_LOCK_SUFFIX, CORPUS_PROGRESS_SUFFIX, parseWbFileName } from './corpus-segments.ts';
+export { parseCorpusTurns, type CorpusTurn };
+
/** Per-file window cap per sweep; longer files converge over later sweeps. */
export const CORPUS_WINDOWS_PER_SWEEP = 8;
/** Cross-file window total per sweep (override: GBRAIN_CORPUS_WINDOWS_PER_SWEEP). */
@@ -50,17 +52,6 @@ const MAX_ENTITY_SLUGS = 500;
type PipelineResult = Awaited<ReturnType<typeof runFactsPipeline>>;
-export interface CorpusTurn {
- role: 'user' | 'assistant' | null;
- /** UTF-8 byte offsets of the turn in the raw file (header included). */
- start: number;
- end: number;
- /** SHA-256 of the raw turn text (trailing whitespace trimmed). */
- sha256: string;
- header: string;
- /** Extractor-facing body: pastes stripped (user turns), trimmed. */
- body: string;
-}
export interface CorpusWindow {
text: string;
@@ -98,8 +89,6 @@ export interface CorpusWindowRun {
result: PipelineResult;
}
-const sha256 = (text: string): string => createHash('sha256').update(text).digest('hex');
-
let invalidKnobWarned = false;
/**
@@ -127,50 +116,6 @@ export function __resetCorpusWindowsWarningForTests(): void {
invalidKnobWarned = false;
}
-/** Split corpus text into turns at the exact `toCorpusText` markers. */
-export function parseCorpusTurns(raw: string): CorpusTurn[] {
- const starts: Array<{ at: number; role: 'user' | 'assistant' }> = [];
- if (raw.startsWith('[user]\n')) starts.push({ at: 0, role: 'user' });
- else if (raw.startsWith('[assistant]\n')) starts.push({ at: 0, role: 'assistant' });
- const USER = '\n\n[user]\n';
- const ASSISTANT = '\n\n[assistant]\n';
- let nextUser = raw.indexOf(USER);
- let nextAssistant = raw.indexOf(ASSISTANT);
- while (nextUser >= 0 || nextAssistant >= 0) {
- const isUser = nextAssistant < 0 || (nextUser >= 0 && nextUser < nextAssistant);
- const at = isUser ? nextUser : nextAssistant;
- starts.push({ at: at + 2, role: isUser ? 'user' : 'assistant' });
- if (isUser) nextUser = raw.indexOf(USER, at + 2);
- else nextAssistant = raw.indexOf(ASSISTANT, at + 2);
- }
-
- let charAt = 0;
- let byteAt = 0;
- const bytes = (index: number): number => {
- byteAt += Buffer.byteLength(raw.slice(charAt, index), 'utf8');
- charAt = index;
- return byteAt;
- };
- const turns: CorpusTurn[] = [];
- const push = (role: CorpusTurn['role'], from: number, to: number): void => {
- const span = raw.slice(from, to);
- const header = role ? `[${role}]\n` : '';
- const rawBody = span.slice(header.length);
- const body = (role === 'user' ? stripPastedContent(rawBody).text : rawBody).trim();
- const start = bytes(from);
- turns.push({ role, start, end: bytes(to), sha256: sha256(span.trimEnd()), header, body });
- };
- const firstAt = starts.length ? starts[0].at : raw.length;
- if (firstAt > 0) {
- const preambleEnd = starts.length ? firstAt - 2 : raw.length;
- if (raw.slice(0, preambleEnd).trim()) push(null, 0, preambleEnd);
- }
- for (let k = 0; k < starts.length; k++) {
- push(starts[k].role, starts[k].at, k + 1 < starts.length ? starts[k + 1].at - 2 : raw.length);
- }
- return turns;
-}
-
function isHigh(code: number): boolean { return code >= 0xd800 && code <= 0xdbff; }
function isLow(code: number): boolean { return code >= 0xdc00 && code <= 0xdfff; }
@@ -391,6 +336,54 @@ export async function adoptFinishedCorpusFile(full: string): Promise<boolean> {
return written !== null;
}
+/**
+ * #6091: record a corpus file as finished WITHOUT extracting it — the capture
+ * gate retired it (explicit `memory.auto_writeback off`). `.progress` is
+ * finished at the file's current stat with every current turn hash recorded
+ * and `skipped_reason`, then the `.ingested` sidecar names the reason. A
+ * retire overrides another extractor's lease (its next compare-and-set fails),
+ * and a later rewrite of the file (a resumed session) extracts only turns that
+ * are not recorded here. Returns false when the file changed mid-read or the
+ * progress lock stayed busy (the caller retries on its next pass).
+ */
+export async function retireCorpusFile(full: string, reason: string = 'writeback_off'): Promise<boolean> {
+ const st = corpusFileStat(await stat(full));
+ const raw = await readFile(full, 'utf8');
+ if (!sameCorpusFileStat(st, corpusFileStat(await stat(full)))) return false;
+ const written = await updateProgress(full, (cur) => ({
+ ...(cur ?? freshProgress()),
+ turns: mergeTurns(cur?.turns ?? [], parseCorpusTurns(raw)),
+ continuation: null,
+ finished: st,
+ skipped_reason: reason,
+ lease: null,
+ }));
+ if (!written) return false;
+ await writeFile(full + '.ingested', JSON.stringify({ ingested_at: new Date().toISOString(), skipped: reason }) + '\n');
+ return true;
+}
+
+/**
+ * #6091: record turns captured under explicit off as done, so extraction of
+ * this file resumes past them. Leaves `finished` alone: turns the file holds
+ * beyond these still extract. False when the progress lock stayed busy.
+ */
+export async function retireCorpusTurns(full: string, hashes: readonly string[]): Promise<boolean> {
+ const written = await updateProgress(full, (cur) => {
+ const known = new Set(cur?.turns.map((t) => t.sha256) ?? []);
+ const added = hashes.filter((h) => !known.has(h));
+ if (cur && added.length === 0) return null;
+ return { ...(cur ?? freshProgress()), turns: [...(cur?.turns ?? []), ...added.map((h) => ({ start: 0, end: 0, sha256: h }))].slice(-MAX_RECORDED_TURNS) };
+ });
+ return written !== null || (await readCorpusProgress(full)) !== null;
+}
+
+function mergeTurns(recorded: CorpusProgress['turns'], turns: CorpusTurn[]): CorpusProgress['turns'] {
+ const known = new Set(recorded.map((t) => t.sha256));
+ const added = turns.filter((t) => !known.has(t.sha256)).map(({ start, end, sha256: h }) => ({ start, end, sha256: h }));
+ return [...recorded, ...added].slice(-MAX_RECORDED_TURNS);
+}
+
/**
* Extract up to `maxWindows` non-empty windows of `raw` (the snapshot whose
* stat is `fileStat`), committing `.progress` after each one. `complete`
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index c035264c34..2929f26e3c 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -51,6 +51,7 @@ export const CODES = {
access_env_missing: { class: 'caller', summary: "Google connect credential error: access env missing.", docs: 'docs/guides/google-connect.md#troubleshooting' },
acknowledgment_unavailable: { class: 'unavailable', summary: "This batch is unknown or outside the retained replay window." },
admin_policy_enforced: { class: 'host_only', summary: "Google connect credential error: admin policy enforced.", docs: 'docs/guides/google-connect.md#troubleshooting' },
+ ambient_capture_off: { class: 'caller', summary: "memory.auto_writeback no longer allows this ambient capture lane, so facts extracted from captured session text were dropped before admission.", why: "An explicit off (or an incoherent setting) applies to every capture-lane fact request admitted after the change, including one whose provider call was already in flight; requests admitted earlier still publish.", docs: 'docs/guides/ambient-writeback.md#capture-lanes-and-the-off-switch' },
ambiguous_id: { class: 'caller', summary: "The legacy id matches multiple readable pages." },
ambiguous_ref: { class: 'caller', summary: "A page reference in a rating matches pages in more than one source of that answer.", docs: 'docs/guides/retrieval-feedback.md#ambiguous_ref' },
ambiguous_skill: { class: 'caller', summary: "This name belongs to multiple authorized sources." },
diff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.ts
index 7e6f990b96..1f18ef8808 100644
--- a/src/core/facts/backstop.ts
+++ b/src/core/facts/backstop.ts
@@ -49,6 +49,7 @@ import { isAvailable } from '../ai/gateway.ts';
import { withAIInvocationPreflight } from '../ai/invocation-guard.ts';
import { decideSingleFact } from './single-prepare.ts';
import { cosineVerdict, dedupCapturedFacts, withCaptureDrops } from './capture-dedup.ts';
+import { assertAmbientCaptureAdmissible, type FactsBackstopSource } from './capture-sources.ts';
import { appendContextNote, type InferredVia } from './subject-infer.ts';
import { inferenceNote, inferMissingSubjects } from './subject-infer-write.ts';
import { maintenanceTransaction } from '../persistence/attribution.ts';
@@ -105,9 +106,10 @@ export interface FactsBackstopCtx {
* - 'hook:compact' — compaction-boundary checkpoint harvest (cathedral 5)
* - 'hook:writeback' — ambient-writeback Stop-hook backstop (WP4)
* - 'sweep:corpus' — the sweep's session-corpus pass
- * The last three are capture lanes (capture-dedup.ts, #5888).
+ * The last three are capture lanes (capture-dedup.ts, #5888); the list is
+ * FACTS_BACKSTOP_SOURCES (capture-sources.ts).
*/
- source: 'sync:import' | 'mcp:put_page' | 'mcp:extract_facts' | 'file_upload' | 'code_import' | 'hook:compact' | 'hook:writeback' | 'sweep:corpus';
+ source: FactsBackstopSource;
/** Execution mode — D8. Default 'queue' (fire-and-forget). */
mode?: 'queue' | 'inline';
/** Notability filter — D4. Default 'all'; sync uses 'high-only'; the
@@ -680,6 +682,7 @@ async function runPipelineBodyInner(
const visibility = ctx.visibility ?? (await resolveDefaultVisibility(ctx.engine));
// #5888: one exact-duplicate check for the capture lanes, before either writer.
const { facts, dropped } = await dedupCapturedFacts(ctx, await inferMissingSubjects(ctx, outcome.facts, visibility, input.pageSlug, managed), visibility, resolveEntitySlugWithSource);
+ if (!managed) await assertAmbientCaptureAdmissible(ctx.engine, ctx.source);
if (managed) return withCaptureDrops(dropped, facts.length || !dropped.length ? await publishManagedFacts(ctx.engine, managed, ctx, facts, visibility, input.pageSlug) : null);
let inserted = 0;
diff --git a/src/core/facts/capture-sources.ts b/src/core/facts/capture-sources.ts
new file mode 100644
index 0000000000..e4c7ef912d
--- /dev/null
+++ b/src/core/facts/capture-sources.ts
@@ -0,0 +1,56 @@
+/**
+ * Every provenance tag the facts backstop writes into `facts.source`, as one
+ * runtime list (#6091). `FactsBackstopCtx['source']` derives from it, so a new
+ * writer is a one-line addition here, and the ambient subset (`hook:*`,
+ * `sweep:*`) — the lanes `memory.auto_writeback` governs — is derived rather
+ * than restated. test/capture-consent-inventory.test.ts pins the capture-lane
+ * lists in capture-dedup.ts and repair/captured-facts.ts to that subset.
+ */
+
+import type { BrainEngine } from '../engine.ts';
+import { loadConfig } from '../config.ts';
+import { opError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
+import { captureGateDecision, resolveWritebackConfig, type CaptureGateLane } from './writeback-config.ts';
+
+export const FACTS_BACKSTOP_SOURCES = [
+ 'sync:import',
+ 'mcp:put_page',
+ 'mcp:extract_facts',
+ 'file_upload',
+ 'code_import',
+ 'hook:compact',
+ 'hook:writeback',
+ 'sweep:corpus',
+] as const;
+export type FactsBackstopSource = (typeof FACTS_BACKSTOP_SOURCES)[number];
+
+export const AMBIENT_CAPTURE_SOURCES: readonly FactsBackstopSource[] = Object.freeze(
+ FACTS_BACKSTOP_SOURCES.filter((s) => s.startsWith('hook:') || s.startsWith('sweep:')),
+);
+
+/** The capture gate lane a provenance tag answers to; null for explicit writers. */
+export function captureGateLaneForSource(source: string | null | undefined): CaptureGateLane | null {
+ if (source === 'hook:writeback') return 'writeback';
+ if (source === 'hook:compact') return 'compact';
+ if (source === 'sweep:corpus') return 'session_end';
+ return null;
+}
+
+/**
+ * Publication side: refuses a capture-lane fact admission when the gate no
+ * longer extracts for that lane. Explicit writers (`remember`, `extract_facts`,
+ * page extraction) are never affected.
+ */
+export async function assertAmbientCaptureAdmissible(engine: BrainEngine, source: string | null | undefined): Promise<void> {
+ const lane = captureGateLaneForSource(source);
+ if (!lane) return;
+ const decision = captureGateDecision(await resolveWritebackConfig(engine, loadConfig(), { gate: true }), lane);
+ if (decision.action === 'extract') return;
+ throw opError('ambient_capture_off', 'Ambient capture is off for this brain; the captured facts were not saved.',
+ `memory.auto_writeback no longer allows the ${lane} capture lane (${decision.reason}), so facts extracted from captured session text were dropped before admission. Nothing needs to be done: this is the off switch working. Explicit remember and extract_facts calls are unaffected.`,
+ {
+ reason: decision.reason,
+ fix: readFix('Shows the setting and which capture lanes it stops, read-only.', { argv: ['gbrain', 'config', 'get', 'memory.auto_writeback'] }),
+ });
+}
diff --git a/src/core/facts/writeback-config.ts b/src/core/facts/writeback-config.ts
index 2824ec2159..a7969ca53c 100644
--- a/src/core/facts/writeback-config.ts
+++ b/src/core/facts/writeback-config.ts
@@ -107,6 +107,10 @@ export interface WritebackConfig extends WritebackFileConfig {
* says enabled — the planes diverged (see module header). Gate callers
* skip WITHOUT the terminal sidecar; doctor names the re-sync command. */
plane_drift?: true;
+ /** Present when the DB plane has NO row while the provided file mirror
+ * explicitly says 'off' — a dual-write of off that never reached the DB.
+ * The compact and SessionEnd lanes hold on it instead of extracting. */
+ off_unsynced?: true;
}
function normalizeMode(raw: unknown): Pick<WritebackFileConfig, 'mode' | 'mode_valid' | 'raw_mode'> {
@@ -205,7 +209,9 @@ export async function resolveWritebackConfig(
// Drift: the DB has NO row while the file mirror claims enabled. An
// explicit DB 'off' is operator intent — never drift.
const fileClaims = fileCfg?.memory?.auto_writeback;
- const drift = dbMode == null && fileClaims != null && normalizeMode(fileClaims).mode !== 'off';
+ const fileMode = fileClaims == null ? null : normalizeMode(fileClaims);
+ const drift = dbMode == null && fileMode != null && fileMode.mode !== 'off';
+ const offUnsynced = dbMode == null && fileMode?.raw_mode === 'off';
const bundle: WritebackConfig = {
...m,
enabled: m.mode !== 'off',
@@ -215,6 +221,7 @@ export async function resolveWritebackConfig(
visibility_explicit_private: posture.explicit_private,
visibility_posture: posture.visibility,
...(drift ? { plane_drift: true as const } : {}),
+ ...(offUnsynced ? { off_unsynced: true as const } : {}),
};
lkg.set(engine, bundle);
return bundle;
@@ -228,3 +235,95 @@ export async function resolveWritebackConfig(
return { ...OFF_BUNDLE, read_error: true };
}
}
+
+/**
+ * The ambient capture lanes (#6091). `writeback` is the Stop hook's `.wb-`
+ * turn files; `compact` is PreCompact segments and OpenClaw compactions;
+ * `session_end` is the SessionEnd `<sid>.txt` transcript. Installing the
+ * harness hooks is the opt-in for compact and SessionEnd capture, so those
+ * two extract while the setting is unset; the writeback lane never does.
+ */
+export const CAPTURE_GATE_LANES = Object.freeze(['writeback', 'compact', 'session_end'] as const);
+export type CaptureGateLane = (typeof CAPTURE_GATE_LANES)[number];
+
+export type CaptureGateReason =
+ | 'writeback_on' | 'writeback_unset' | 'writeback_off'
+ | 'writeback_gate_unreadable' | 'writeback_mode_invalid' | 'writeback_plane_drift' | 'writeback_off_unsynced';
+
+export interface CaptureGateDecision {
+ /** extract: run the lane; retire: record the file as finished, never extract it;
+ * hold: leave the file untouched until the config is coherent again. */
+ action: 'extract' | 'retire' | 'hold';
+ reason: CaptureGateReason;
+}
+
+/**
+ * The one capture gate every ambient lane applies under its claim, before any
+ * provider call or receipt republication. Resolve `cfg` with `{ gate: true }`
+ * (never a last-known-good enabled bundle) and the file mirror, so drift is
+ * visible. Explicit `off` retires on every lane; a read error, plane drift or
+ * an invalid mode holds; unset retires the writeback lane and extracts the
+ * compact and SessionEnd lanes, unless the file mirror says `off` while the DB
+ * has no row (a failed dual-write of off), which holds.
+ */
+export function captureGateDecision(cfg: WritebackConfig, lane: CaptureGateLane): CaptureGateDecision {
+ if (cfg.read_error) return { action: 'hold', reason: 'writeback_gate_unreadable' };
+ if (!cfg.mode_valid) return { action: 'hold', reason: 'writeback_mode_invalid' };
+ if (cfg.plane_drift) return { action: 'hold', reason: 'writeback_plane_drift' };
+ if (cfg.enabled) return { action: 'extract', reason: 'writeback_on' };
+ if (cfg.raw_mode === 'off' || lane === 'writeback') return { action: 'retire', reason: 'writeback_off' };
+ if (cfg.off_unsynced) return { action: 'hold', reason: 'writeback_off_unsynced' };
+ return { action: 'extract', reason: 'writeback_unset' };
+}
+
+/** Capture-time view for the engine-free hook children: the brain's own file
+ * plane says an explicit, valid `off`. Only this case is recorded at capture. */
+export function fileCaptureIsOff(cfg: GBrainConfig | null | undefined): boolean {
+ const f = resolveWritebackConfigFromFile(cfg);
+ return f.mode_valid && f.raw_mode === 'off';
+}
+
+/** Operator-facing lane names (config messages, doctor, docs truth table). */
+export const CAPTURE_LANE_LABELS: Readonly<Record<CaptureGateLane, string>> = Object.freeze({
+ writeback: 'Stop-hook turn capture',
+ compact: 'compaction harvest',
+ session_end: 'SessionEnd transcripts',
+});
+
+/** Each lane's effective action under `cfg` (resolve it with `{ gate: true }`). */
+export function captureLaneStates(cfg: WritebackConfig): Record<CaptureGateLane, CaptureGateDecision['action']> {
+ return Object.fromEntries(CAPTURE_GATE_LANES.map((lane) => [lane, captureGateDecision(cfg, lane).action])) as Record<CaptureGateLane, CaptureGateDecision['action']>;
+}
+
+/** One line: `Stop-hook turn capture: retire; compaction harvest: extract; …`. */
+export function captureLaneSummary(cfg: WritebackConfig): string {
+ const states = captureLaneStates(cfg);
+ return CAPTURE_GATE_LANES.map((lane) => `${CAPTURE_LANE_LABELS[lane]}: ${states[lane]}`).join('; ');
+}
+
+/** Workers that read the gate only from this version on; an older one keeps capturing until it restarts. */
+export const WRITEBACK_RESTART_AFTER_OFF: readonly string[] = Object.freeze([
+ 'long-running `gbrain serve` processes (compaction harvest; `gbrain sources writer status --json` consumer_version is a hint, not proof, because an idle old worker leaves no receipt)',
+ 'cron or autopilot sweeps (SessionEnd transcripts and the compaction backstop)',
+ 'any OpenClaw gateway hosting the gbrain context engine (compaction rungs 2 and 3)',
+]);
+
+/** What `gbrain config set memory.auto_writeback off` tells the operator. */
+export function writebackOffMessage(): string[] {
+ return [
+ 'Ambient writeback off. Stopped: Stop-hook turn capture, the compaction harvest (PreCompact segments and OpenClaw compactions) and SessionEnd transcript extraction. Session text banked from now on is retired, never extracted later, even if writeback is turned back on.',
+ 'Not stopped: facts already saved, explicit remember / extract_facts calls, and fact extraction from pages written on purpose.',
+ `Enforcement is incomplete until workers started on an older gbrain restart: ${WRITEBACK_RESTART_AFTER_OFF.join('; ')}.`,
+ 'Review facts these lanes already saved: `gbrain recall --since 30d --limit 500 --json` (rows whose source is hook:compact, hook:writeback or sweep:corpus); forget one only with the user\'s agreement: `gbrain forget <fact-id>`.',
+ 'To stop the hooks from banking session text at all, SessionEnd included: `gbrain bootstrap harness --remove`.',
+ 'If harness instruction blocks were installed, remove them: gbrain bootstrap harness --yes (converges on off).',
+ ];
+}
+
+/** What `gbrain config unset memory.auto_writeback` tells the operator. */
+export function writebackUnsetMessage(): string[] {
+ return [
+ 'Ambient writeback is unset: Stop-hook turn capture stays off, but the compaction harvest and SessionEnd transcripts extract again (installing the harness hooks opted into them). To stop every capture lane: `gbrain config set memory.auto_writeback off`.',
+ 'If harness instruction blocks were installed, remove them: gbrain bootstrap harness --yes (converges on off).',
+ ];
+}
diff --git a/src/core/onboard/writeback-nudge.ts b/src/core/onboard/writeback-nudge.ts
index 46653d7184..5c3ed92be9 100644
--- a/src/core/onboard/writeback-nudge.ts
+++ b/src/core/onboard/writeback-nudge.ts
@@ -90,7 +90,8 @@ export async function runWritebackNudge(
line('[gbrain] - saved facts are readable by agents authorized on THIS brain — not the');
line('[gbrain] public internet. Nothing new leaves your machine beyond your');
line('[gbrain] configured model provider calls.');
- line('[gbrain] Off switch (anytime): gbrain config set memory.auto_writeback off,');
+ line('[gbrain] Off switch (anytime): gbrain config set memory.auto_writeback off');
+ line('[gbrain] (it also stops the compaction harvest and SessionEnd transcript extraction),');
line('[gbrain] then gbrain bootstrap harness --yes to remove installed instruction blocks.');
line('═══════════════════════════════════════════════════════════════');
// Agent contract v1 (F7): the ask is a decision for the user; the
diff --git a/src/core/persistence/facts-maintenance.ts b/src/core/persistence/facts-maintenance.ts
index 6cff7dc029..22af5939a0 100644
--- a/src/core/persistence/facts-maintenance.ts
+++ b/src/core/persistence/facts-maintenance.ts
@@ -27,6 +27,7 @@ import { maintenancePublishWaitMs } from './maintenance-wait.ts';
import { digest, requireUuid, sha256 } from './digest.ts';
import { isTerminal, type WriteAuthority, type WriteRequest } from './model.ts';
import type { WriteReceipt } from './types.ts';
+import { assertAmbientCaptureAdmissible, captureGateLaneForSource } from '../facts/capture-sources.ts';
export interface ManagedFactsResult {
inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; write_requests: WriteReceipt[];
@@ -49,6 +50,8 @@ export interface ManagedFactIntent extends Record<string, unknown> {
*/
attribute_fallback?: true;
embedding?: FactEmbeddingSignature | null;
+ /** #6091: the ambient capture lane (`hook:*`, `sweep:*`) the facts came from; admission re-checks its gate. */
+ capture_source?: string;
}
export interface ManagedFactsSession {
authority: WriteAuthority; binding: WorktreeBinding | null; config: GBrainConfig;
@@ -57,6 +60,8 @@ export interface ManagedFactsSession {
embedding?: FactEmbeddingSignature | null;
/** #6048: the batch is keyed by its input alone and the caller asked to re-admit facts the canonical file check refused. */
fileRefusalRetry?: boolean;
+ /** #6091: set when the facts come from an ambient capture lane. */
+ captureSource?: string;
}
/** #6048: follow-up batches one input-keyed extraction may admit for file-check refusals. */
@@ -236,7 +241,8 @@ export async function prepareManagedFactsSession(ctx: FactsBackstopCtx,
const session: ManagedFactsSession = { authority, binding: writeThrough ? binding : null, config,
batchKey, inputDigest, origin, originalRequestId: ctx.persistenceRequestId ?? null,
completionRequestId: ctx.requestId ? requireUuid(ctx.requestId) : managedFactRequestId(batchKey, '__managed_facts_complete__'),
- fileRefusalRetry: ctx.reAdmitFileRefusals === true && seed === inputDigest };
+ fileRefusalRetry: ctx.reAdmitFileRefusals === true && seed === inputDigest,
+ ...(captureGateLaneForSource(ctx.source) ? { captureSource: ctx.source } : {}) };
const prior = await getWriteRequest(engine, authority.principal, session.completionRequestId);
if (prior) await validateManagedFactsCompletion(engine, session, prior);
return session;
@@ -384,6 +390,7 @@ export async function publishManagedFacts(engine: BrainEngine, session: ManagedF
inputDigest: session.inputDigest, origin: session.origin, originalRequestId: session.originalRequestId,
embedding: session.embedding ?? null, ...(options.supersede ? { supersede: true as const } : {}),
...(options.attributeFallback ? { attribute_fallback: true as const } : {}),
+ ...(session.captureSource ? { capture_source: session.captureSource } : {}),
...(snapshot ? { expected_revision: snapshot.revision } : {}), facts: group } });
}
return collectManagedFacts(engine, session, await admitManagedFactsBatch(engine, session, inputs, embedded, ctx.abortSignal));
@@ -396,12 +403,14 @@ async function admitManagedFactsBatch(engine: BrainEngine, session: ManagedFacts
embedded: boolean, signal?: AbortSignal): Promise<WriteRequest[]> {
const sourceId = session.authority.sourceId;
return engine.transaction(async tx => {
+ await assertAmbientCaptureAdmissible(tx, session.captureSource);
if (embedded) await assertManagedFactsEmbedding(tx, session.config, session.embedding, true);
const children: string[] = [];
const accepted: WriteRequest[] = [];
for (const input of [...inputs, { slug: '__managed_facts_complete__', pageId: null, intent: {
kind: 'managed_facts_complete', batchKey: session.batchKey, inputDigest: session.inputDigest,
- origin: session.origin, originalRequestId: session.originalRequestId, children } as ManagedFactIntent }]) {
+ origin: session.origin, originalRequestId: session.originalRequestId, children,
+ ...(session.captureSource ? { capture_source: session.captureSource } : {}) } as ManagedFactIntent }]) {
if (signal?.aborted) throw new DOMException('Fact extraction was aborted before admission.', 'AbortError');
await authorizePageVisibility(tx, session.authority, input.slug);
const requestId = input.intent.kind === 'managed_facts_complete' ? session.completionRequestId : managedFactRequestId(session.batchKey, input.slug);
diff --git a/src/core/sweep.ts b/src/core/sweep.ts
index ef921014e7..304f87ad5e 100644
--- a/src/core/sweep.ts
+++ b/src/core/sweep.ts
@@ -612,36 +612,27 @@ async function runCorpusIngestPass(
skip('already_ingested', alreadyIngested);
if (candidates.length === 0) return;
- // Ambient-writeback turn files (`.wb-` basenames) ride this pass as the
- // batch backstop when serve/IPC was away (OV2-11) — but they answer to the
- // AUTHORITATIVE `memory.auto_writeback` gate, resolved once per pass: off ⇒
- // terminal sidecar (operator intent beats a leftover hook-side bank), on ⇒
- // extracted with the lane's own provenance + salient notability filter.
- // Resolved BEFORE the keyless/kill-switch short-circuits so an operator's
- // OFF retires banked turns even when the brain cannot extract — otherwise
- // the files linger eligible and a later re-enable would extract turns the
- // operator already revoked (codex re-review, this wave).
- const { parseWbFileName, writebackOffSidecarJson, selfCaptureSidecarJson, corpusFileSessionId, corpusTextForExtraction } = await import('./context/corpus-segments.ts');
- const { resolveWritebackConfig } = await import('./facts/writeback-config.ts');
- const { loadConfig: loadFileCfg } = await import('./config.ts');
+ // #6091: every corpus file answers to the capture gate, resolved once per
+ // pass from the AUTHORITATIVE DB plane ({gate:true}: never a last-known-good
+ // enabled bundle) with the file mirror for drift. `.wb-` turn files (the
+ // Stop-hook backstop when serve/IPC was away, OV2-11) retire on off or unset;
+ // `.seg-` segments and SessionEnd `<sid>.txt` transcripts retire on an
+ // explicit off and extract while unset; a read error, plane drift or an
+ // invalid mode holds them untouched. Retirement runs BEFORE the
+ // keyless/kill-switch short-circuits so an operator's OFF retires banked
+ // files even when the brain cannot extract — otherwise they linger eligible
+ // and a later re-enable would extract text the operator already revoked.
+ const { parseWbFileName, selfCaptureSidecarJson, corpusFileSessionId, corpusTextForExtraction } = await import('./context/corpus-segments.ts');
+ const { applyCaptureGate, captureLaneForFile, resolveCaptureGate } = await import('./context/capture-consent.ts');
const { isValidSourceId } = await import('./source-id.ts');
- // Gate semantics: never extract on a last-known-good ENABLED bundle — an
- // operator's off wins even during a DB blip; read_error, plane drift (DB
- // row absent + file mirror enabled = failed dual-write, not intent), and
- // an unrecognized mode value all skip wb files WITHOUT a terminal sidecar
- // so the next sweep retries them once the config is coherent.
- const wbCfg = await resolveWritebackConfig(engine, loadFileCfg(), { gate: true });
- // Genuinely-resolved OFF: terminal-sidecar the wb candidates regardless of
- // extraction capability (idempotent one-line writes; a lost race with a
- // concurrent sweep writing the same sidecar is benign).
- const wbGenuinelyOff = !wbCfg.enabled && wbCfg.mode_valid && !wbCfg.plane_drift && !wbCfg.read_error;
- const retireWbCandidatesIfOff = async (): Promise<Set<string>> => {
+ const gate = await resolveCaptureGate(engine);
+ const retireCandidatesIfOff = async (): Promise<Set<string>> => {
const retired = new Set<string>();
- if (!wbGenuinelyOff) return retired;
for (const name of candidates) {
- if (!parseWbFileName(name)) continue;
+ const decision = gate[captureLaneForFile(name)];
+ if (decision.action !== 'retire') continue;
try {
- await writeFile(join(dir, name) + CORPUS_INGESTED_SUFFIX, writebackOffSidecarJson());
+ if ((await applyCaptureGate(join(dir, name), decision)).action !== 'retire') continue;
retired.add(name);
skip('writeback_off');
} catch { /* per-file best effort — the next sweep retries */ }
@@ -653,7 +644,7 @@ async function runCorpusIngestPass(
// whole pass. Agent-authored fences (pass 1) carry keyless memory.
const { extractionAvailableForEngine } = await import('./facts/extraction-availability.ts');
if (!(await extractionAvailableForEngine(engine, ctx.capabilities))) {
- const retired = await retireWbCandidatesIfOff();
+ const retired = await retireCandidatesIfOff();
skip('keyless', candidates.length - retired.size);
return;
}
@@ -662,7 +653,7 @@ async function runCorpusIngestPass(
// stop ALL fact extraction brain-wide (facts/extract.ts:43).
const { isFactsExtractionEnabled } = await import('./facts/extract.ts');
if (!(await isFactsExtractionEnabled(engine))) {
- const retired = await retireWbCandidatesIfOff();
+ const retired = await retireCandidatesIfOff();
skip('extraction_disabled', candidates.length - retired.size);
return;
}
@@ -715,23 +706,13 @@ async function runCorpusIngestPass(
continue;
}
- const wbMeta = parseWbFileName(name);
- if (wbMeta && wbCfg.read_error) {
- skip('writeback_gate_unreadable');
- continue; // no sidecar — retry next sweep once the config is readable
- }
- if (wbMeta && !wbCfg.enabled && (wbCfg.plane_drift || !wbCfg.mode_valid)) {
- // Diverged planes / unrecognized mode value ≠ operator intent: no
- // terminal sidecar — the file survives until the config re-coheres
- // (doctor names the re-sync command).
- skip(wbCfg.plane_drift ? 'writeback_plane_drift' : 'writeback_mode_invalid');
- continue;
- }
- if (wbMeta && !wbCfg.enabled) {
- await writeFile(full + CORPUS_INGESTED_SUFFIX, writebackOffSidecarJson());
- skip('writeback_off');
+ // #6091: the capture gate, under the claim, before any provider call.
+ const applied = await applyCaptureGate(full, gate[captureLaneForFile(name)]);
+ if (applied.action !== 'extract') {
+ skip(applied.reason);
continue;
}
+ const wbMeta = parseWbFileName(name);
const fileStat = windows.corpusFileStat(await stat(full));
const raw = await readFile(full, 'utf-8');
@@ -760,19 +741,17 @@ async function runCorpusIngestPass(
engine,
sourceId: wbMeta ? wbSourceId : sourceId,
sessionId: wbMeta ? wbMeta.sessionId : `sweep:corpus:${name}`,
- // Provenance tag outside FactsBackstopCtx's enumerated writers —
- // facts.source is free text at the DB layer; the cast only
- // side-steps the ctx union, which predates the sweep. Writeback turn
- // files keep their lane's provenance + salient notability filter so
- // batch-extracted turns are indistinguishable from prompt-harvested.
- source: wbMeta ? 'hook:writeback' : ('sweep:corpus' as FactsBackstopCtx['source']),
+ // Writeback turn files keep their lane's provenance + salient
+ // notability filter so batch-extracted turns are indistinguishable
+ // from prompt-harvested ones.
+ source: wbMeta ? 'hook:writeback' : 'sweep:corpus',
mode: 'inline',
remote: false,
abortSignal: signal,
// #5888: the file's write time anchors the capture dedup window, not the (possibly late) sweep.
turnAt: await stat(full).then(st => st.mtime, () => undefined),
reAdmitFileRefusals: true,
- ...(wbMeta && wbCfg.mode === 'salient' ? { notabilityFilter: 'medium-and-up' as const } : {}),
+ ...(wbMeta && gate.mode === 'salient' ? { notabilityFilter: 'medium-and-up' as const } : {}),
// visibility deliberately unset → resolveDefaultVisibility [ENG-8]
};
// #5812: pasted blocks never reach the extractor (file unchanged). A wb
@@ -863,6 +842,8 @@ async function runCorpusIngestPass(
if (e instanceof Error && e.name === 'AbortError') {
skip('budget_exhausted:corpus', candidates.length - i);
abortLoop = true;
+ } else if ((e as { code?: unknown }).code === 'ambient_capture_off') {
+ skip('writeback_off_inflight');
} else {
skip('corpus_file_error');
log(`[sweep] corpus ingest failed for ${name}: ${e instanceof Error ? e.message : String(e)}`);
diff --git a/test/capture-consent-admission.test.ts b/test/capture-consent-admission.test.ts
new file mode 100644
index 0000000000..7ba6671e1b
--- /dev/null
+++ b/test/capture-consent-admission.test.ts
@@ -0,0 +1,202 @@
+/**
+ * #6091 / W2.1 publication boundary on a managed brain: managed fact requests
+ * from an ambient capture lane carry their provenance, and admission re-checks
+ * the capture gate inside its transaction. The ordering contract: `off`
+ * applies to every ambient fact request admitted after `config set` commits;
+ * requests admitted before it publish.
+ *
+ * 1. Protects: a provider call in flight when off lands admits nothing; a
+ * request admitted before off still publishes; a stored batch admitted
+ * before off replays its result; a file-refusal follow-up batch (#6048)
+ * attempted after off is refused, with no new extraction.
+ * 2. Fails when: admission ignores the setting, or re-checks requests that
+ * were already admitted.
+ * 3. capture-consent-gate.serial.test.ts covers the lanes' own gates and the
+ * unmanaged fence-write boundary.
+ *
+ * Runs on PGLite; also on Postgres when DATABASE_URL is set (testBackends).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { appendFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { installFaultHook } from '../src/core/persistence/fault-points.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { runFactsPipeline, type FactsBackstopCtx } from '../src/core/facts/backstop.ts';
+import { configureGateway, resetGateway, __setChatTransportForTests, type ChatResult } from '../src/core/ai/gateway.ts';
+import { runMaintenanceSweep } from '../src/core/sweep.ts';
+import { toCorpusText } from '../src/core/transcripts/claude-code-jsonl.ts';
+import { parseCorpusTurns, planCorpusWindows } from '../src/core/context/corpus-windows.ts';
+import type { CapabilityReport } from '../src/core/capability.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { waitFor } from './helpers/wait-for.ts';
+
+const KEYED: CapabilityReport = { embeddings: { available: false }, extraction: { available: true, provider: 'anthropic' }, search: 'keyword-only', mode: 'keyed' };
+const COMPANY = { slug: 'companies/acme-example', title: 'Acme Example', type: 'company' };
+const SESSION = 'consent-session.txt';
+
+const engines: BrainEngine[] = [];
+const dbDir = mkdtempSync(join(tmpdir(), 'gbrain-consent-admission-db-'));
+let closePostgres: (() => Promise<void>) | undefined;
+let extractions = 0;
+let duringCall: (() => Promise<void>) | null = null;
+
+beforeAll(async () => {
+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536,
+ env: { ANTHROPIC_API_KEY: 'sk-ant-test', OPENAI_API_KEY: 'sk-test' } });
+ __setChatTransportForTests(async (): Promise<ChatResult> => {
+ extractions++;
+ if (duringCall) await duringCall();
+ const facts = [{ fact: `${COMPANY.title} ships the example roadmap`, kind: 'fact', entity: COMPANY.slug, confidence: 0.9, notability: 'high' }];
+ return { text: JSON.stringify({ facts }), blocks: [], stopReason: 'end', model: 'anthropic:claude-sonnet-4-6', providerId: 'anthropic',
+ usage: { input_tokens: 5, output_tokens: 5, cache_read_tokens: 0, cache_creation_tokens: 0 } };
+ });
+ for (const backend of testBackends()) {
+ if (backend === 'pglite') {
+ const engine = new PGLiteEngine();
+ await engine.connect({ database_path: dbDir });
+ await engine.initSchema();
+ engines.push(engine);
+ } else {
+ const isolated = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engines.push(isolated.engine);
+ closePostgres = isolated.close;
+ }
+ }
+}, 120_000);
+
+afterAll(async () => {
+ installFaultHook(undefined);
+ __setChatTransportForTests(null);
+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ await closePostgres?.();
+ resetGateway();
+ rmSync(dbDir, { recursive: true, force: true });
+});
+
+const transcript = () => toCorpusText([
+ { role: 'user', text: 'Planning notes for the example roadmap. '.repeat(40) },
+ { role: 'assistant', text: 'Summary of the example roadmap discussion. '.repeat(40) },
+]);
+
+/** A managed source holding a committed entity page and one corpus transcript, with writeback on. */
+async function managedCorpus(engine: BrainEngine, dir: string, opts: { drifted?: boolean } = {}) {
+ const root = join(dir, 'checkout'); mkdirSync(root);
+ const corpusDir = join(dir, 'sessions'); mkdirSync(corpusDir);
+ const sourceId = `consent-${randomUUID().slice(0, 8)}`;
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ for (const [key, value] of [['sync.write_through', 'true'], ['facts.extraction_enabled', 'true'], ['dream.synthesize.session_corpus_dir', corpusDir],
+ ['facts.default_visibility', 'world'], ['memory.auto_writeback', 'salient']]) await engine.setConfig(key, value);
+ await claimWorktree(engine, sourceId, root);
+ const ctx = { engine, sourceId, remote: false as const, config: { engine: engine.kind, embedding_disabled: true },
+ dryRun: false, logger: { info() {}, warn() {}, error() {} } } as unknown as OperationContext;
+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: COMPANY.slug, request_id: randomUUID(),
+ content: `---\ntitle: ${COMPANY.title}\ntype: ${COMPANY.type}\n---\n# ${COMPANY.title}\n` } });
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const pageFile = join(root, `${COMPANY.slug}.md`);
+ const pristine = readFileSync(pageFile);
+ if (opts.drifted) appendFileSync(pageFile, '\nA local edit nobody imported.\n');
+ const raw = transcript();
+ writeFileSync(join(corpusDir, SESSION), raw);
+ const quiet = () => waitFor(async () => (await engine.executeRaw<{ n: number }>(
+ `SELECT COUNT(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND state IN ('queued','running','recovering')`, [sourceId]))[0].n === 0,
+ { timeoutMs: 30_000, label: 'fact requests settled' });
+ const sweep = async () => {
+ await runMaintenanceSweep(engine, { sourceId, capabilities: KEYED, budgetMs: 120_000 });
+ await quiet();
+ };
+ const requests = async () => (await engine.executeRaw<{ n: number }>(
+ `SELECT COUNT(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND operation='extract_facts'`, [sourceId]))[0].n;
+ const facts = async () => (await engine.executeRaw<{ n: number }>(
+ `SELECT COUNT(*)::int AS n FROM facts WHERE source_id=$1 AND source='sweep:corpus' AND expired_at IS NULL`, [sourceId]))[0].n;
+ // The sweep's own window, for a worker that passed its gate before off landed.
+ const pipelineCtx: FactsBackstopCtx = { engine, sourceId, sessionId: `sweep:corpus:${SESSION}`, source: 'sweep:corpus', mode: 'inline',
+ remote: false, reAdmitFileRefusals: true };
+ const firstWindow = planCorpusWindows(parseCorpusTurns(raw), { turn: 0, offset: 0 })[0].text;
+ const replay = () => runFactsPipeline(firstWindow, pipelineCtx);
+ return { sourceId, sweep, quiet, requests, facts, replay, repair: () => writeFileSync(pageFile, pristine), off: () => engine.setConfig('memory.auto_writeback', 'off') };
+}
+
+async function onEachEngine(label: string, body: (engine: BrainEngine, dir: string) => Promise<void>) {
+ for (const engine of engines) {
+ const dir = mkdtempSync(join(tmpdir(), `gbrain-consent-admission-${label}-`));
+ extractions = 0;
+ duringCall = null;
+ try {
+ await withEnv({ GBRAIN_HOME: join(dir, 'home'), GBRAIN_AUDIT_DIR: join(dir, 'audit') }, () => body(engine, dir));
+ } finally {
+ installFaultHook(undefined);
+ duringCall = null;
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ rmSync(dir, { recursive: true, force: true });
+ }
+ }
+}
+
+describe('managed admission re-checks the capture gate (#6091)', () => {
+ test('off set while the provider call is in flight admits no fact request', async () => {
+ await onEachEngine('inflight', async (engine, dir) => {
+ const w = await managedCorpus(engine, dir);
+ duringCall = async () => { await w.off(); };
+ await w.sweep();
+ expect(extractions).toBe(1);
+ expect(await w.requests()).toBe(0);
+ expect(await w.facts()).toBe(0);
+ });
+ }, 180_000);
+
+ test('a request admitted before off still publishes', async () => {
+ await onEachEngine('queued', async (engine, dir) => {
+ const w = await managedCorpus(engine, dir);
+ let flipped = false;
+ installFaultHook(async (point, detail) => {
+ if (point === 'consumer:prepared' && detail.operation === 'extract_facts' && detail.sourceId === w.sourceId && !flipped) {
+ flipped = true;
+ await w.off();
+ }
+ });
+ await w.sweep();
+ expect(flipped).toBe(true);
+ expect(await w.facts()).toBe(1);
+ });
+ }, 180_000);
+
+ test('a stored batch admitted before off replays its result without a new provider call', async () => {
+ await onEachEngine('replay', async (engine, dir) => {
+ const w = await managedCorpus(engine, dir);
+ await w.sweep();
+ expect(await w.facts()).toBe(1);
+ await w.off();
+ const r = await w.replay();
+ expect(r.inserted).toBe(1);
+ expect(extractions).toBe(1);
+ });
+ }, 180_000);
+
+ test('a file-refusal follow-up batch attempted after off is refused, with no new extraction', async () => {
+ await onEachEngine('followup', async (engine, dir) => {
+ const w = await managedCorpus(engine, dir, { drifted: true });
+ await w.sweep();
+ const before = await w.requests();
+ expect(before).toBe(2);
+ w.repair();
+ await w.off();
+ await expect(w.replay()).rejects.toMatchObject({ code: 'ambient_capture_off' });
+ await w.quiet();
+ expect(await w.requests()).toBe(before);
+ expect(await w.facts()).toBe(0);
+ expect(extractions).toBe(1);
+ });
+ }, 180_000);
+});
diff --git a/test/capture-consent-gate.serial.test.ts b/test/capture-consent-gate.serial.test.ts
new file mode 100644
index 0000000000..86d5840b33
--- /dev/null
+++ b/test/capture-consent-gate.serial.test.ts
@@ -0,0 +1,322 @@
+/**
+ * #6091 / W2.1: an explicit `memory.auto_writeback off` stops every ambient
+ * capture lane — the serve compact harvest, the sweep's `.seg-` backstop and
+ * (D1) the SessionEnd `<sid>.txt` transcript lane — while an unset value keeps
+ * today's behavior for the compact and SessionEnd lanes. Read errors, plane
+ * drift and invalid modes hold (no extraction, nothing terminal). A file banked
+ * under explicit off is never extracted later, even after the operator turns
+ * writeback back on, and a resumed session extracts only its new turns.
+ *
+ * Serial: real PGLite engines, module-global harvest queue, GBRAIN_HOME env.
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { __setChatTransportForTests, resetGateway, type ChatResult } from '../src/core/ai/gateway.ts';
+import { __resetFactsQueueForTests } from '../src/core/facts/queue.ts';
+import type { CapabilityReport } from '../src/core/capability.ts';
+import { CORPUS_INGESTED_SUFFIX, runMaintenanceSweep } from '../src/core/sweep.ts';
+import { __drainCheckpointHarvestForTests, __resetCheckpointHarvestForTests, scheduleCheckpointHarvest } from '../src/core/context/checkpoint-harvest.ts';
+import { appendSegmentLedger, segmentFileName, writeSegment } from '../src/core/context/corpus-segments.ts';
+import { runHook } from '../src/commands/hook.ts';
+
+const KEYED: CapabilityReport = {
+ embeddings: { available: false },
+ extraction: { available: true, provider: 'anthropic' },
+ search: 'keyword-only',
+ mode: 'keyed',
+};
+
+let engine: PGLiteEngine;
+let homeDir: string;
+let corpusDir: string;
+let savedHome: string | undefined;
+const tmpDirs: string[] = [];
+let prompts: string[] = [];
+let onCall: (() => Promise<void>) | null = null;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 120_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+ for (const d of tmpDirs) rmSync(d, { recursive: true, force: true });
+});
+
+beforeEach(async () => {
+ __resetCheckpointHarvestForTests();
+ homeDir = mkdtempSync(join(tmpdir(), 'gb-consent-home-'));
+ tmpDirs.push(homeDir);
+ savedHome = process.env.GBRAIN_HOME;
+ process.env.GBRAIN_HOME = homeDir;
+ corpusDir = join(homeDir, '.gbrain', 'transcripts', 'corpus');
+ mkdirSync(corpusDir, { recursive: true });
+ await engine.setConfig('dream.synthesize.session_corpus_dir', corpusDir);
+ await engine.unsetConfig('memory.auto_writeback');
+ await engine.executeRaw('DELETE FROM facts').catch(() => {});
+ prompts = [];
+ onCall = null;
+ __setChatTransportForTests(async (opts): Promise<ChatResult> => {
+ prompts.push(JSON.stringify(opts));
+ if (onCall) await onCall();
+ return {
+ text: JSON.stringify({ facts: [{ fact: 'chose the blue deployment window', kind: 'decision', entity: null, confidence: 1, notability: 'high' }] }),
+ blocks: [],
+ stopReason: 'end',
+ usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'test:stub',
+ providerId: 'test',
+ };
+ });
+});
+
+afterEach(() => {
+ __setChatTransportForTests(null);
+ resetGateway();
+ __resetFactsQueueForTests();
+ if (savedHome === undefined) delete process.env.GBRAIN_HOME;
+ else process.env.GBRAIN_HOME = savedHome;
+});
+
+/** Both planes, the way `gbrain config set memory.auto_writeback <mode>` writes them. */
+async function setMode(mode: string | null, opts: { db?: boolean; file?: boolean } = {}): Promise<void> {
+ const cfgPath = join(homeDir, '.gbrain', 'config.json');
+ if (opts.file !== false) {
+ writeFileSync(cfgPath, JSON.stringify({ engine: 'pglite', ...(mode === null ? {} : { memory: { auto_writeback: mode } }) }) + '\n');
+ }
+ if (opts.db !== false) {
+ if (mode === null) await engine.unsetConfig('memory.auto_writeback');
+ else await engine.setConfig('memory.auto_writeback', mode);
+ }
+}
+
+function bankSegment(sessionId: string, text: string): string {
+ const w = writeSegment(corpusDir, sessionId, text);
+ appendSegmentLedger(corpusDir, sessionId, w.hash);
+ return segmentFileName(sessionId, w.hash);
+}
+
+async function factCount(source: string): Promise<number> {
+ const rows = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM facts WHERE source = $1`, [source]);
+ return Number(rows[0]?.n ?? 0);
+}
+
+function sidecar(name: string): Record<string, unknown> | null {
+ const p = join(corpusDir, name + CORPUS_INGESTED_SUFFIX);
+ return existsSync(p) ? JSON.parse(readFileSync(p, 'utf8')) : null;
+}
+
+async function harvest(file: string, sessionId: string): Promise<void> {
+ scheduleCheckpointHarvest({ engine, sourceId: 'default', sessionId, corpusDir, file, capabilities: KEYED });
+ await __drainCheckpointHarvestForTests();
+}
+
+const sweep = () => runMaintenanceSweep(engine, { sourceId: 'default', capabilities: KEYED, budgetMs: 30_000 });
+
+const corpusText = (turns: string[]): string =>
+ turns.map((t, i) => `${i % 2 === 0 ? '[user]' : '[assistant]'}\n${t}`).join('\n\n') + '\n';
+
+/** A Claude Code transcript + `gbrain hook session-end`, exactly as the harness runs it. */
+async function sessionEnd(sessionId: string, turns: string[]): Promise<void> {
+ const projects = join(homeDir, 'claude', 'projects', 'p1');
+ mkdirSync(projects, { recursive: true });
+ mkdirSync(join(homeDir, 'ws'), { recursive: true });
+ const transcript = join(projects, `${sessionId}.jsonl`);
+ writeFileSync(transcript, turns.map((t, i) => i % 2 === 0
+ ? JSON.stringify({ type: 'user', isSidechain: false, message: { role: 'user', content: t } })
+ : JSON.stringify({ type: 'assistant', isSidechain: false, message: { role: 'assistant', content: [{ type: 'text', text: t }] } }),
+ ).join('\n') + '\n');
+ expect(await runHook(['session-end'], {
+ stdin: JSON.stringify({ session_id: sessionId, transcript_path: transcript, cwd: join(homeDir, 'ws') }),
+ transcriptRoot: join(homeDir, 'claude', 'projects'),
+ spawnPush: () => {},
+ spawnBackupCheck: () => {},
+ })).toBe(0);
+}
+
+describe('explicit off stops every ambient lane (#6091)', () => {
+ test('serve compact harvest: zero provider calls, terminal writeback_off sidecar', async () => {
+ await setMode('off');
+ const file = bankSegment('sess-c1', 'User: we picked the blue deployment window.\n');
+ await harvest(file, 'sess-c1');
+ expect(prompts.length).toBe(0);
+ expect(await factCount('hook:compact')).toBe(0);
+ expect(sidecar(file)?.skipped).toBe('writeback_off');
+ });
+
+ test('sweep backstop on a .seg- segment: zero provider calls, sidecar written', async () => {
+ await setMode('off');
+ const file = bankSegment('sess-c2', 'User: we picked the blue deployment window.\n');
+ await sweep();
+ expect(prompts.length).toBe(0);
+ expect(await factCount('sweep:corpus')).toBe(0);
+ expect(sidecar(file)?.skipped).toBe('writeback_off');
+ });
+
+ test('D1: the SessionEnd <sid>.txt transcript lane stops under explicit off', async () => {
+ await setMode('off');
+ writeFileSync(join(corpusDir, 'sess-c3.txt'), corpusText(['we picked the blue deployment window', 'noted']));
+ await sweep();
+ expect(prompts.length).toBe(0);
+ expect(await factCount('sweep:corpus')).toBe(0);
+ expect(sidecar('sess-c3.txt')?.skipped).toBe('writeback_off');
+ });
+
+ test('explicit off retires even on a keyless brain', async () => {
+ await setMode('off');
+ writeFileSync(join(corpusDir, 'sess-c4.txt'), corpusText(['we picked the blue deployment window', 'noted']));
+ await runMaintenanceSweep(engine, {
+ sourceId: 'default', budgetMs: 30_000,
+ capabilities: { embeddings: { available: false }, extraction: { available: false }, search: 'keyword-only', mode: 'keyless' },
+ });
+ expect(sidecar('sess-c4.txt')?.skipped).toBe('writeback_off');
+ });
+});
+
+describe('unset keeps today\'s behavior for the compact and SessionEnd lanes', () => {
+ test('compact harvest extracts on unset', async () => {
+ await setMode(null);
+ const file = bankSegment('sess-u1', 'User: we picked the blue deployment window.\n');
+ await harvest(file, 'sess-u1');
+ expect(prompts.length).toBe(1);
+ expect(await factCount('hook:compact')).toBe(1);
+ });
+
+ test('SessionEnd transcript extracts on unset', async () => {
+ await setMode(null);
+ writeFileSync(join(corpusDir, 'sess-u2.txt'), corpusText(['we picked the blue deployment window', 'noted']));
+ await sweep();
+ expect(prompts.length).toBe(1);
+ expect(await factCount('sweep:corpus')).toBe(1);
+ });
+});
+
+describe('incoherent config holds: nothing extracted, nothing terminal', () => {
+ test('invalid mode value holds the compact and SessionEnd lanes', async () => {
+ await setMode('sometimes');
+ const seg = bankSegment('sess-h1', 'User: we picked the blue deployment window.\n');
+ writeFileSync(join(corpusDir, 'sess-h1.txt'), corpusText(['we picked the blue deployment window', 'noted']));
+ await harvest(seg, 'sess-h1');
+ await sweep();
+ expect(prompts.length).toBe(0);
+ expect(sidecar(seg)).toBeNull();
+ expect(sidecar('sess-h1.txt')).toBeNull();
+ });
+
+ test('plane drift (DB row absent, file mirror on) holds', async () => {
+ await setMode('salient', { db: false });
+ writeFileSync(join(corpusDir, 'sess-h2.txt'), corpusText(['we picked the blue deployment window', 'noted']));
+ await sweep();
+ expect(prompts.length).toBe(0);
+ expect(sidecar('sess-h2.txt')).toBeNull();
+ });
+
+ test('a failed dual-write of off (DB row absent, file mirror off) holds, never extracts', async () => {
+ await setMode('off', { db: false });
+ const seg = bankSegment('sess-h3', 'User: we picked the blue deployment window.\n');
+ await harvest(seg, 'sess-h3');
+ expect(prompts.length).toBe(0);
+ expect(sidecar(seg)).toBeNull();
+ });
+});
+
+describe('durable revocation: a capture under off never extracts later', () => {
+ test('off then on with the worker stopped: the off-period transcript is never extracted', async () => {
+ await setMode('off');
+ await sessionEnd('sess-r1', ['we picked the blue deployment window', 'noted']);
+ expect(existsSync(join(corpusDir, 'sess-r1.txt'))).toBe(true);
+ await setMode('salient');
+ await sweep();
+ expect(prompts.length).toBe(0);
+ expect(await factCount('sweep:corpus')).toBe(0);
+ });
+
+ test('resumed session: off-period turns stay retired, turns banked under on extract', async () => {
+ await setMode('off');
+ await sessionEnd('sess-r2', ['old secret plan alpha', 'ack alpha']);
+ await setMode('salient');
+ await sessionEnd('sess-r2', ['old secret plan alpha', 'ack alpha', 'new public plan beta', 'ack beta']);
+ await sweep();
+ expect(prompts.length).toBe(1);
+ expect(prompts[0]).toContain('new public plan beta');
+ expect(prompts[0]).not.toContain('old secret plan alpha');
+ });
+
+ test('appended turns after a worker-side retire: only the new turns extract', async () => {
+ await setMode('off');
+ const full = join(corpusDir, 'sess-r3.txt');
+ writeFileSync(full, corpusText(['old secret plan alpha', 'ack alpha']));
+ await sweep();
+ expect(sidecar('sess-r3.txt')?.skipped).toBe('writeback_off');
+ await setMode('salient');
+ writeFileSync(full, corpusText(['old secret plan alpha', 'ack alpha', 'new public plan beta', 'ack beta']));
+ rmSync(full + CORPUS_INGESTED_SUFFIX, { force: true });
+ await sweep();
+ expect(prompts.length).toBe(1);
+ expect(prompts[0]).toContain('new public plan beta');
+ expect(prompts[0]).not.toContain('old secret plan alpha');
+ });
+
+ test('off set while a provider call is in flight: nothing is published', async () => {
+ await setMode('salient');
+ writeFileSync(join(corpusDir, 'sess-r4.txt'), corpusText(['we picked the blue deployment window', 'noted']));
+ onCall = async () => { await setMode('off'); };
+ await sweep();
+ expect(prompts.length).toBe(1);
+ expect(await factCount('sweep:corpus')).toBe(0);
+ });
+});
+
+describe('two brains on one machine', () => {
+ let other: PGLiteEngine;
+ let homeB: string;
+ beforeAll(async () => {
+ other = new PGLiteEngine();
+ await other.connect({});
+ await other.initSchema();
+ }, 120_000);
+ afterAll(async () => { await other.disconnect(); });
+ beforeEach(async () => {
+ homeB = mkdtempSync(join(tmpdir(), 'gb-consent-homeB-'));
+ tmpDirs.push(homeB);
+ mkdirSync(join(homeB, '.gbrain', 'transcripts', 'corpus'), { recursive: true });
+ writeFileSync(join(homeB, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', memory: { auto_writeback: 'salient' } }) + '\n');
+ await other.setConfig('memory.auto_writeback', 'salient');
+ await other.executeRaw('DELETE FROM facts').catch(() => {});
+ });
+ const asBrainB = async <T>(fn: () => Promise<T>): Promise<T> => {
+ const homeA = process.env.GBRAIN_HOME;
+ process.env.GBRAIN_HOME = homeB;
+ try { return await fn(); } finally { process.env.GBRAIN_HOME = homeA; }
+ };
+
+ test('each brain applies its own mode to its own captures', async () => {
+ await setMode('off');
+ await sessionEnd('sess-m1', ['alpha said to brain A', 'ack']);
+ await asBrainB(async () => {
+ await other.setConfig('dream.synthesize.session_corpus_dir', join(homeB, '.gbrain', 'transcripts', 'corpus'));
+ await sessionEnd('sess-m2', ['beta said to brain B', 'ack']);
+ });
+ await sweep();
+ expect(prompts.length).toBe(0);
+ await asBrainB(() => runMaintenanceSweep(other, { sourceId: 'default', capabilities: KEYED, budgetMs: 30_000 }));
+ expect(prompts.length).toBe(1);
+ expect(prompts[0]).toContain('beta said to brain B');
+ });
+
+ test('pin: a capture record written by another brain in a shared corpus directory is ignored', async () => {
+ await setMode('off');
+ await sessionEnd('sess-m3', ['gamma in the shared directory', 'ack']);
+ await asBrainB(async () => {
+ await other.setConfig('dream.synthesize.session_corpus_dir', corpusDir);
+ await runMaintenanceSweep(other, { sourceId: 'default', capabilities: KEYED, budgetMs: 30_000 });
+ });
+ expect(prompts.length).toBe(1);
+ expect(prompts[0]).toContain('gamma in the shared directory');
+ });
+});
diff --git a/test/capture-consent-inventory.test.ts b/test/capture-consent-inventory.test.ts
new file mode 100644
index 0000000000..df3e8e34dd
--- /dev/null
+++ b/test/capture-consent-inventory.test.ts
@@ -0,0 +1,108 @@
+/**
+ * #6091 / W2.1: one capture gate with one truth table, and an inventory that
+ * fails when an ambient provenance tag is added without registering it.
+ *
+ * 1. Protects: the lane-specific unset semantics (writeback retires; compact
+ * and SessionEnd extract), explicit off retiring every lane, and holds on a
+ * read error, plane drift, an invalid mode or an off that reached only the
+ * file mirror; the capture-lane lists in capture-dedup.ts and
+ * repair/captured-facts.ts equal the ambient subset of the backstop's
+ * provenance tags, and each ambient tag maps to a gate lane.
+ * 2. Fails when: a lane extracts against an explicit off, an incoherent config
+ * extracts or retires, or a new `hook:*` / `sweep:*` tag is missing from a
+ * capture-lane list or from captureGateLaneForSource.
+ */
+import { describe, expect, test } from 'bun:test';
+import { captureGateDecision, CAPTURE_GATE_LANES, resolveWritebackConfig, type WritebackConfig } from '../src/core/facts/writeback-config.ts';
+import { AMBIENT_CAPTURE_SOURCES, captureGateLaneForSource, FACTS_BACKSTOP_SOURCES } from '../src/core/facts/capture-sources.ts';
+import { CAPTURE_LANES as DEDUP_LANES } from '../src/core/facts/capture-dedup.ts';
+import { CAPTURE_LANES as REPAIR_LANES } from '../src/core/repair/captured-facts.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { WRITEBACK_RESTART_AFTER_OFF, writebackOffMessage, writebackUnsetMessage } from '../src/core/facts/writeback-config.ts';
+import { flagRejection, gbrainInvocations, liveCliVerbs } from './helpers/cli-command-surface.ts';
+import type { GBrainConfig } from '../src/core/config.ts';
+
+function engineWith(db: Record<string, string | null>, opts: { throws?: boolean } = {}): BrainEngine {
+ return { getConfig: async (k: string) => { if (opts.throws) throw new Error('db down'); return db[k] ?? null; } } as unknown as BrainEngine;
+}
+const file = (mode?: string): GBrainConfig => ({ engine: 'pglite', ...(mode === undefined ? {} : { memory: { auto_writeback: mode } }) }) as GBrainConfig;
+async function cfgFor(dbMode: string | null, fileMode?: string, throws = false): Promise<WritebackConfig> {
+ return resolveWritebackConfig(engineWith({ 'memory.auto_writeback': dbMode }, { throws }), file(fileMode), { gate: true });
+}
+async function row(dbMode: string | null, fileMode?: string, throws = false): Promise<string[]> {
+ const cfg = await cfgFor(dbMode, fileMode, throws);
+ return CAPTURE_GATE_LANES.map((lane) => `${captureGateDecision(cfg, lane).action}:${captureGateDecision(cfg, lane).reason}`);
+}
+
+describe('captureGateDecision truth table (writeback, compact, session_end)', () => {
+ test('unset: writeback retires, compact and SessionEnd extract', async () => {
+ expect(await row(null)).toEqual(['retire:writeback_off', 'extract:writeback_unset', 'extract:writeback_unset']);
+ });
+ test('explicit off retires every lane', async () => {
+ expect(await row('off', 'off')).toEqual(['retire:writeback_off', 'retire:writeback_off', 'retire:writeback_off']);
+ });
+ test('salient and all extract on every lane', async () => {
+ for (const mode of ['salient', 'all']) {
+ expect(await row(mode, mode)).toEqual(['extract:writeback_on', 'extract:writeback_on', 'extract:writeback_on']);
+ }
+ });
+ test('an invalid mode holds every lane', async () => {
+ expect(await row('sometimes')).toEqual(Array(3).fill('hold:writeback_mode_invalid'));
+ });
+ test('plane drift (DB row absent, file mirror on) holds every lane', async () => {
+ expect(await row(null, 'salient')).toEqual(Array(3).fill('hold:writeback_plane_drift'));
+ });
+ test('a read error holds every lane, even with a cached enabled bundle', async () => {
+ expect(await row(null, undefined, true)).toEqual(Array(3).fill('hold:writeback_gate_unreadable'));
+ });
+ test('an off that reached only the file mirror holds compact and SessionEnd; writeback retires as on unset', async () => {
+ expect(await row(null, 'off')).toEqual(['retire:writeback_off', 'hold:writeback_off_unsynced', 'hold:writeback_off_unsynced']);
+ });
+ test('an explicit DB off beats a file mirror that still says on', async () => {
+ expect(await row('off', 'all')).toEqual(Array(3).fill('retire:writeback_off'));
+ });
+});
+
+describe('ambient capture inventory', () => {
+ test('the ambient subset is derived from the backstop provenance tags', () => {
+ expect([...AMBIENT_CAPTURE_SOURCES].sort()).toEqual(FACTS_BACKSTOP_SOURCES.filter((s) => /^(hook|sweep):/.test(s)).sort());
+ });
+ test('both capture-lane lists equal the ambient subset as sets', () => {
+ expect(new Set<string>(DEDUP_LANES)).toEqual(new Set<string>(AMBIENT_CAPTURE_SOURCES));
+ expect(new Set<string>(REPAIR_LANES)).toEqual(new Set<string>(AMBIENT_CAPTURE_SOURCES));
+ });
+ test('every ambient tag answers to a gate lane; explicit writers answer to none', () => {
+ for (const s of FACTS_BACKSTOP_SOURCES) {
+ expect(captureGateLaneForSource(s) !== null).toBe(AMBIENT_CAPTURE_SOURCES.includes(s));
+ }
+ });
+});
+
+describe('operator text names what stopped and only commands that exist', () => {
+ const commandsIn = (lines: readonly string[]) => [...lines.join(' ').matchAll(/`(gbrain [^`]+)`/g)].flatMap((m) => gbrainInvocations(m[1]));
+ test('config set off names the stopped lanes, what keeps working, the restart list, review and full-removal commands', () => {
+ const text = writebackOffMessage().join('\n');
+ for (const needle of ['Stop-hook turn capture', 'compaction harvest', 'SessionEnd transcript', 'Not stopped', 'remember / extract_facts',
+ 'gbrain serve', 'OpenClaw gateway', 'hook:compact', 'sweep:corpus', 'gbrain bootstrap harness --remove']) {
+ expect(text).toContain(needle);
+ }
+ });
+ test('every suggested command is a live verb whose flags the real CLI accepts', () => {
+ const invocations = commandsIn([...writebackOffMessage(), ...writebackUnsetMessage(), ...WRITEBACK_RESTART_AFTER_OFF]);
+ expect(invocations.length).toBeGreaterThanOrEqual(6);
+ const live = liveCliVerbs();
+ for (const inv of invocations) {
+ expect(live.has(inv.verb)).toBe(true);
+ expect(flagRejection(inv)).toBeNull();
+ }
+ });
+ test('the ambient_capture_off refusal carries a runnable read-only fix', async () => {
+ const { assertAmbientCaptureAdmissible } = await import('../src/core/facts/capture-sources.ts');
+ const err = await assertAmbientCaptureAdmissible(engineWith({ 'memory.auto_writeback': 'off' }), 'sweep:corpus').then(() => null, (e) => e);
+ expect(err?.code).toBe('ambient_capture_off');
+ const argv = err.fix.argv as string[];
+ expect(argv[0]).toBe('gbrain');
+ expect(flagRejection({ verb: argv[1], argv: argv.slice(1) })).toBeNull();
+ expect(await assertAmbientCaptureAdmissible(engineWith({ 'memory.auto_writeback': 'off' }), 'mcp:extract_facts')).toBeUndefined();
+ });
+});
diff --git a/test/capture-dedup.test.ts b/test/capture-dedup.test.ts
index 591daf1d84..02fb841fd4 100644
--- a/test/capture-dedup.test.ts
+++ b/test/capture-dedup.test.ts
@@ -136,6 +136,8 @@ beforeAll(async () => {
else { const pglite = new PGLiteEngine(); await pglite.connect({}); await pglite.initSchema(); engine = pglite; }
await engine.setConfig('embedding_model', MODEL);
await engine.setConfig('embedding_dimensions', String(DIM));
+ // #6091: capture-lane facts are admitted only while memory.auto_writeback allows the lane.
+ await engine.setConfig('memory.auto_writeback', 'all');
}, 120_000);
afterAll(async () => { await disposePersistenceConsumer(engine); if (close) await close(); else await engine.disconnect(); });
beforeEach(() => {
diff --git a/test/fixtures/goldens/doctor/early-stop-connection-failure.json b/test/fixtures/goldens/doctor/early-stop-connection-failure.json
index 240813711a..a13aa76d52 100644
--- a/test/fixtures/goldens/doctor/early-stop-connection-failure.json
+++ b/test/fixtures/goldens/doctor/early-stop-connection-failure.json
@@ -143,6 +143,11 @@
"no shared declaration; 0 non-automation client(s) active in 30d"
],
"backstop_visibility": "private",
+ "capture_lanes": {
+ "compact": "extract",
+ "session_end": "extract",
+ "writeback": "retire"
+ },
"counters_note": "local, append-only, loss-tolerant observability over the last 7d — never a source of truth",
"cross_lane_duplicates_7d": 0,
"instruction_visibility": "world",
@@ -154,7 +159,7 @@
"ttl_valid": true,
"visibility_note": "world = readable by agents authorized on THIS brain, not the public internet"
},
- "message": "ambient writeback off (default). Enable: gbrain config set memory.auto_writeback salient",
+ "message": "ambient writeback off (default): Stop-hook turn capture is off, but the compaction harvest and SessionEnd transcripts still extract (installing the harness hooks opted into them; stop them: gbrain config set memory.auto_writeback off). Enable: gbrain config set memory.auto_writeback salient",
"name": "memory_writeback",
"status": "ok"
},
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index 90fbd29064..6083d6bfd1 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -184,6 +184,11 @@
"no shared declaration; 0 non-automation client(s) active in 30d"
],
"backstop_visibility": "private",
+ "capture_lanes": {
+ "compact": "extract",
+ "session_end": "extract",
+ "writeback": "retire"
+ },
"counters_note": "local, append-only, loss-tolerant observability over the last 7d — never a source of truth",
"cross_lane_duplicates_7d": 0,
"instruction_visibility": "world",
@@ -195,7 +200,7 @@
"ttl_valid": true,
"visibility_note": "world = readable by agents authorized on THIS brain, not the public internet"
},
- "message": "ambient writeback off (default). Enable: gbrain config set memory.auto_writeback salient",
+ "message": "ambient writeback off (default): Stop-hook turn capture is off, but the compaction harvest and SessionEnd transcripts still extract (installing the harness hooks opted into them; stop them: gbrain config set memory.auto_writeback off). Enable: gbrain config set memory.auto_writeback salient",
"name": "memory_writeback",
"status": "ok"
},
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index 25392ee55a..8c150d87e1 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -187,6 +187,11 @@
"no shared declaration; 0 non-automation client(s) active in 30d"
],
"backstop_visibility": "private",
+ "capture_lanes": {
+ "compact": "extract",
+ "session_end": "extract",
+ "writeback": "retire"
+ },
"counters_note": "local, append-only, loss-tolerant observability over the last 7d — never a source of truth",
"cross_lane_duplicates_7d": 0,
"instruction_visibility": "world",
@@ -198,7 +203,7 @@
"ttl_valid": true,
"visibility_note": "world = readable by agents authorized on THIS brain, not the public internet"
},
- "message": "ambient writeback off (default). Enable: gbrain config set memory.auto_writeback salient",
+ "message": "ambient writeback off (default): Stop-hook turn capture is off, but the compaction harvest and SessionEnd transcripts still extract (installing the harness hooks opted into them; stop them: gbrain config set memory.auto_writeback off). Enable: gbrain config set memory.auto_writeback salient",
"name": "memory_writeback",
"status": "ok"
},
diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.json
index 28a76eba59..4b36f4a3e3 100644
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@ -174,6 +174,11 @@
"no shared declaration; 0 non-automation client(s) active in 30d"
],
"backstop_visibility": "private",
+ "capture_lanes": {
+ "compact": "extract",
+ "session_end": "extract",
+ "writeback": "retire"
+ },
"counters_note": "local, append-only, loss-tolerant observability over the last 7d — never a source of truth",
"cross_lane_duplicates_7d": 0,
"instruction_visibility": "world",
@@ -185,7 +190,7 @@
"ttl_valid": true,
"visibility_note": "world = readable by agents authorized on THIS brain, not the public internet"
},
- "message": "ambient writeback off (default). Enable: gbrain config set memory.auto_writeback salient",
+ "message": "ambient writeback off (default): Stop-hook turn capture is off, but the compaction harvest and SessionEnd transcripts still extract (installing the harness hooks opted into them; stop them: gbrain config set memory.auto_writeback off). Enable: gbrain config set memory.auto_writeback salient",
"name": "memory_writeback",
"status": "ok"
},