Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Ambient capture consent gate (key files cluster)
How memory.auto_writeback governs the ambient capture lanes (#6091): one
truth table, a capture-time record written by the hooks, a gate applied under
each lane's claim, and a re-check at fact admission. User guide:
ambient writeback.
Key files:
src/core/context/capture-consent.ts+src/core/facts/capture-sources.ts(+captureGateDecisioninsrc/core/facts/writeback-config.ts) —captureGateDecision(cfg, lane)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): explicitoffretires every lane; unset retireswritebackand extractscompact/session_end(the hooks are their opt-in); read error, plane drift, invalid mode, and (compact/session_end) a DB-absent file-mirroroff(off_unsynced) hold.captureLaneStates/captureLaneSummary/writebackOffMessage/writebackUnsetMessage/WRITEBACK_RESTART_AFTER_OFFrender it forconfig set|unset|get(stderr lane line), doctormemory_writeback(details.capture_lanes,details.restart_after_off) and the guide's truth table.src/core/context/capture-consent.ts: capture siderecordCaptureIfOff(the PreCompactbankCompactSegmentbeforeWritecallback, the SessionEnd corpus write and the OpenClaw spool write this brain's own<file>.capture-off.<brain>.json(captureOffRecordPath; brain identity = hash of the resolved config dir, turn hashes viacorpus-turns.ts) BEFORE the file lands, unioning a pre-wave-12 single<file>.capture-off.jsonthat names this brain, so two brains sharing a corpus directory never overwrite each other's off turns; GC (corpus-segments.ts,CAPTURE_OFF_INFIX) reaps any brain's orphan record only after the seat grace); extraction sideresolveCaptureGate+applyCaptureGate(hold /retireCorpusFile/ fold this brain's turns, own record plus a matching legacy record, viaretireCorpusTurns, retiring a file whose every turn was captured under off; foreign-brain records ignored; an unreadable or invalid record holdscapture_record_unreadableand makesrecordCaptureIfOffthrow, never reads as "no record"), called under the claim before any provider call or receipt republish incheckpoint-harvest.ts(runOne,runWritebackTurn),context-engine.tsrung 3 andsweep.ts(including the keyless/extraction-disabled early returns). Publication side:src/core/facts/capture-sources.tsholdsFACTS_BACKSTOP_SOURCES(as const;FactsBackstopCtx['source']derives from it), the ambient subset,captureGateLaneForSourceandassertAmbientCaptureAdmissible(codeambient_capture_off), re-checked insideadmitManagedFactsBatch's transaction (facts-maintenance.ts; sessions and intents carrycaptureSource/capture_source, so #6048 follow-up batches are re-checked too) and before the unmanaged fence write inbackstop.ts; requests admitted beforeoffpublish. Tests:test/capture-consent-gate.serial.test.ts,test/capture-consent-admission.test.ts(PGLite + Postgres),test/capture-consent-inventory.test.ts. Retired turn hashes also land in.progressretired_turns(retireCorpusFile,retireCorpusTurns);planCorpusWindowsskips them wherever a rewrite places them, andwithoutOffPeriodTurns(capture-consent.ts) strips them from whatdiscoverTranscriptshands dream synthesis.src/core/context-engine.ts+src/openclaw-context-engine.ts— the deterministic context engine OpenClaw loads on every turn (assemble()injects the Live Context block, zero-LLM).createGBrainContextEngine({workspaceDir, resolveEntities?})accepts an OPTIONAL host-injected resolver (ENGINE_API_VERSION0.3.0, additive — older hosts work unchanged; the plugin entry mapsctx.resolveEntities/ctx.brainQueryonto it). Checkpoint compaction:compact()runs a time-bounded (8s), fail-open, lazily-imported checkpoint step BEFORE delegating — spools the since-last-boundary window (openclaw tail reader over the exported adapter mapper, 40-turn cap = the no-prior-boundary fallback) as a content-addressed corpus segment + ledger entry, then rung 2 (PGLite: onebankOnly+flushCorpusFileIPC round trip to serve) or rung 3 (Postgres: inline harvest over the reflex ladder's exportedgetDirectPostgresEnginesingleton, under sweep claim fencing + capability/kill-switch gates, abort post-check) — and rides an additiveresult.gbrain_checkpointbag on the delegate's return (ownsCompactionstays false). After the segment is spooled, the Memorable receipt lane runs (gate + stamp viamemorableGateAllowed, span-filtered redacted tool calls,recordAndRelayReceiptwithharness: 'openclaw'— per-compaction capture, content-hash dedup on retries, fail-open for the checkpoint; the whole block is skipped once the host's compact() deadline has fired; the rendered segment text is re-scanned with highEntropy at receipt time and the relay REFUSED fail-closed on any hit — the segment rendering feeds the ledger hash and cannot change, so the next compaction window re-evaluates; this lane NEVER compacts the receipts file — the hook lane is the ONE compactor, single-rewriter rule — but DOES trim the relay file, since an openclaw-only host has no hook lane and converging newest-keeping trims make concurrent trims safe).assemble()consumessessionId ?? sessionKeyand splices a deterministic envelope-bearing Compaction-checkpoint block at parts[1] (after Live Context) from the banked manifest via an in-process memo + hash-keyed polls (≤5; stale manifests can't satisfy a poll for the new segment; no manifest ⇒ byte-identical output).assemble()runs the Retrieval Reflex after the Live Context block: extracts the current turn's user text, builds prior-context text (every message EXCEPT the current turn — suppression must not see the triggering mention), passes the rolling window (getWindowTurns, last 12 user/assistant turns; the reflex slices to its configuredretrieval_reflex_window_turns), and appends the pointer block.warmReflex()fires at construction. Current-host plugin factories may be called with zero arguments. The host workspace takes precedence; ambiguous/unbound legacy fallback warns and reads no source. The canonical slot ID isgbrain-context-engine;gbrain-contextremains a registry alias, not a current-host slot alias. The exclusive context-engine contract and no-write stateless admitted-turn acknowledgement are additive.assembleuses an authoritative separate prompt: sqlite transcript-storage metadata fences historic turns, whereas an identical final legacy user message already represents the current turn. Reflex-only synthesis leaves messages intact; absent prompt keeps message extraction. These contracts do not prove model recall.compact()records the session's seat sidecar (context/seat.ts, harnessopenclaw, seat keyed to the agent directory holdingsessions/) before spooling the segment; a failure never fails the checkpoint. A sub-agent session (isOpenClawSubagentKey:agent:<id>:subagent:<uuid>) is marked first with a speaker sidecar (agent-launched, #8080; nothing is banked when it cannot be written), and rung 3 passes the speaker to the facts pipeline. OpenClaw 2026.9.x callscompact()with asessionTargetand nosessionFile;readCompactTailthen reads the transcript through the host'sopenclaw/plugin-sdk/session-transcript-runtime(readSessionTranscriptEvents, lazily imported;__setTranscriptRuntimeLoaderForTestsis the seam) and maps the events with the JSONL mapper (readOpenclawEventsTailincorpus-segments.ts), keeping the file path for older hosts. Every compaction writes oneopenclaw-compactheartbeat (status and reason codes); doctormemory_writebackwarns when a week of compactions banked none (details.openclaw_compactions_7d). Pinned-host proof:test/openclaw-context-engine-native.serial.test.ts(gateway plusopenclaw sessions compact); fake runtime:test/openclaw-compact-transcript-runtime.serial.test.ts.src/commands/doctor/checks/agent-session-facts.ts—agent_session_facts(wave check, host-only, #8064): counts active owner-attributed capture-lane factsclassifyAgentSessionFactsclassesevidenced(speaker sidecar; no operator flags) orambiguous(repeated first user turn);excludedandunclassifiableare reported, never a finding. Namesgbrain repair agent-session-facts(explicit-only) and says the apply needs the user's agreement. Read-only; health unknown when the scan fails.src/core/repair/agent-session-facts.ts—gbrain repair agent-session-facts(#8064), explicit-only, preview-bound and destructive (--apply --expect <hash> --yes).classifyAgentSessionFacts(read-only; also doctoragent_session_facts) takes active capture-lane facts attributed touseror nobody and classes each by its session (captureSessionId):evidencedby a speaker sidecar (readSpeakerSidecarin the corpus dir, its spool dir or beside the session's files), an operator--session <id>, or a<sid>.source.jsoncwd under an operator--cwd <prefix>(realpath, path-boundary compare);ambiguouswhen the session's first user turn with owner text (head of its earliest retained file, Claude Code slash-command and caveat blocks dropped (#9390), whitespace-normalized, lowercased, at least 40 chars) shares its first 160 chars with 3+ other sessions;excluded:owner_also_saidwhen the claim and entity also have an active user-attributed row from a non-suspect session; no retained corpus, sidecar or record isunclassifiable.agentSessionTakeslists active, unresolved fact/self takes whose everyconsolidated_intofact is non-user once the approved facts are. Approved items, one write each: fact pages (phase 0; a page with database-only and fenced rows is two items, the fenced one after every fact page, so a pending database write never skips its fenced rows) then take pages (phase 1); one apply run builds the corpus index once (PageItem.indexes). The apply rechecks each row; fenced facts getattributed_to: otherandspeakerContextNote(principal)in the## Factsfence and fenced takes are struck in the takes fence, each by one revision-boundput_page; database-only facts and takes change through onemanaged_maintenance_agent_session_factsrequest per page on a managed brain (prepareAgentSessionFactsWrite, dispatched fromprepareMaintenanceMutation) or onemaintenanceTransactionotherwise (applyAgentSessionWriterechecks under the row lock). Nothing is deleted. Pinned bytest/repair-agent-session-facts.test.ts.