Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
10.6 KB
Raw Blame

Ambient capture consent gate (key files cluster)

Subsystem index.

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 (+ captureGateDecision in src/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): 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 this brain's own <file>.capture-off.<brain>.json (captureOffRecordPath; brain identity = hash of the resolved config dir, turn hashes via corpus-turns.ts) BEFORE the file lands, unioning a pre-wave-12 single <file>.capture-off.json that 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 side resolveCaptureGate + applyCaptureGate (hold / retireCorpusFile / fold this brain's turns, own record plus a matching legacy record, via retireCorpusTurns, retiring a file whose every turn was captured under off; foreign-brain records ignored; an unreadable or invalid record holds capture_record_unreadable and makes recordCaptureIfOff throw, never reads as "no record"), 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. Retired turn hashes also land in .progress retired_turns (retireCorpusFile, retireCorpusTurns); planCorpusWindows skips them wherever a rewrite places them, and withoutOffPeriodTurns (capture-consent.ts) strips them from what discoverTranscripts hands 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_VERSION 0.3.0, additive — older hosts work unchanged; the plugin entry maps ctx.resolveEntities/ctx.brainQuery onto 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: one bankOnly+flushCorpusFile IPC round trip to serve) or rung 3 (Postgres: inline harvest over the reflex ladder's exported getDirectPostgresEngine singleton, under sweep claim fencing + capability/kill-switch gates, abort post-check) — and rides an additive result.gbrain_checkpoint bag on the delegate's return (ownsCompaction stays false). After the segment is spooled, the Memorable receipt lane runs (gate + stamp via memorableGateAllowed, span-filtered redacted tool calls, recordAndRelayReceipt with harness: '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() consumes sessionId ?? sessionKey and 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 configured retrieval_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 is gbrain-context-engine; gbrain-context remains a registry alias, not a current-host slot alias. The exclusive context-engine contract and no-write stateless admitted-turn acknowledgement are additive. assemble uses 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, harness openclaw, seat keyed to the agent directory holding sessions/) 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 calls compact() with a sessionTarget and no sessionFile; readCompactTail then reads the transcript through the host's openclaw/plugin-sdk/session-transcript-runtime (readSessionTranscriptEvents, lazily imported; __setTranscriptRuntimeLoaderForTests is the seam) and maps the events with the JSONL mapper (readOpenclawEventsTail in corpus-segments.ts), keeping the file path for older hosts. Every compaction writes one openclaw-compact heartbeat (status and reason codes); doctor memory_writeback warns when a week of compactions banked none (details.openclaw_compactions_7d). Pinned-host proof: test/openclaw-context-engine-native.serial.test.ts (gateway plus openclaw 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 facts classifyAgentSessionFacts classes evidenced (speaker sidecar; no operator flags) or ambiguous (repeated first user turn); excluded and unclassifiable are reported, never a finding. Names gbrain 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 doctor agent_session_facts) takes active capture-lane facts attributed to user or nobody and classes each by its session (captureSessionId): evidenced by a speaker sidecar (readSpeakerSidecar in the corpus dir, its spool dir or beside the session's files), an operator --session <id>, or a <sid>.source.json cwd under an operator --cwd <prefix> (realpath, path-boundary compare); ambiguous when 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_said when the claim and entity also have an active user-attributed row from a non-suspect session; no retained corpus, sidecar or record is unclassifiable. agentSessionTakes lists active, unresolved fact/self takes whose every consolidated_into fact 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 get attributed_to: other and speakerContextNote(principal) in the ## Facts fence and fenced takes are struck in the takes fence, each by one revision-bound put_page; database-only facts and takes change through one managed_maintenance_agent_session_facts request per page on a managed brain (prepareAgentSessionFactsWrite, dispatched from prepareMaintenanceMutation) or one maintenanceTransaction otherwise (applyAgentSessionWrite rechecks under the row lock). Nothing is deleted. Pinned by test/repair-agent-session-facts.test.ts.