Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

OpenClaw core lane module, guard self-test fixtures, docs (core memory guide links, MEMORY_VERBS, CODEX, HERMES, KEY_FILES), TODOS, regenerated catalog and manifests

garrytan244d75929c0a
diff --git a/TODOS.md b/TODOS.md
index 47d9c605e6..531772f2f3 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -1,5 +1,18 @@
# TODOS
+## Always-loaded core memory follow-ups (filed 2026-10-04)
+
+Context: `docs/guides/core-memory.md`, `docs/architecture/key-files/core-memory.md`.
+
+- [ ] **P2 — Codex hook lane for core.** **What:** deliver core through a Codex SessionStart hook instead of the static `$CODEX_HOME/AGENTS.md` block. **Why:** the static block goes stale until `compile-context --target codex-global` reruns. **Fix:** register the session-start hook for Codex in `bootstrap harness` (hooks.json plus the trust hash) once the hook path is verified on the current Codex release. **Effort:** M.
+- [ ] **P2 — Hermes memory-provider plugin.** **What:** a provider whose `system_prompt_block()` returns the core block and whose `on_pre_compress` saves with `remember` + `items`. **Why:** `.hermes.md` is static and Hermes has no pre-compaction save. **Effort:** M.
+- [ ] **P2 — Compiled-file auto-refresh.** **What:** refresh the files recorded in `~/.gbrain/compiled-core.json` when the core revision changes. **Why:** doctor names stale copies but nothing refreshes them. **Effort:** S.
+- [ ] **P3 — Agent-proposed core edits.** **What:** let an agent propose adding or removing a core page as a pending item the owner approves. **Why:** marking is owner-only today; the agent can only tell the user the command. **Effort:** M.
+- [ ] **P3 — PostToolUse pressure lane.** **What:** run the pressure check after tool calls too. **Why:** a long tool-heavy turn can cross the threshold and compact before the next prompt. **Effort:** S.
+- [ ] **P2 — Writer-version fence for core.** **What:** refuse `gbrain core add` while an older gbrain writer that lacks the core guard is still registered on the brain. **Why:** an old serve publishes remote edits to core pages without the budget or owner-only checks. **Fix:** record a `core_guard_v1` capability per writer registration and check it in `core add` and the `core_memory` doctor check. **Effort:** M.
+- [ ] **P3 — Per-turn context drops core slugs.** **What:** the per-turn context (hook `turn_context`, OpenClaw reflex) still volunteers core pages that are already in the session. **Fix:** pass the core slugs as already-delivered. **Effort:** S.
+- [ ] **P3 — Pressure notice record-after-write.** **What:** the once-per-segment state is written before the hook's stdout lands; a deadline-expired turn loses that segment's notice. **Fix:** commit the state after the write, like the session-start deferred records. **Effort:** S.
+
## Held files follow-ups (filed 2026-10-04, follow-up from v0.60.47.0)
Context: `docs/guides/repair.md#held-files`, `docs/guides/write-refusals.md#held-files-and-content-refusals`.
diff --git a/docs/TOOL_CATALOG.md b/docs/TOOL_CATALOG.md
index 25ff219388..caa228b80d 100644
--- a/docs/TOOL_CATALOG.md
+++ b/docs/TOOL_CATALOG.md
@@ -138,12 +138,12 @@ Every non-localOnly operation on the MCP surface: 137 tools across 23 areas. **S
| Tool | Description | Scope | Starter | Gate |
|---|---|---|---|---|
-| `context_pack` | MEMORY VERB (v1): budget-packed cards, open threads and hot facts for up to 8 entities, zero LLM. | read | yes | |
+| `context_pack` | MEMORY VERB (v1): the always-loaded core block plus budget-packed cards, open threads and hot facts for up to 8 entities, zero LLM. | read | yes | |
| `delta` | MEMORY VERB (v1): what changed since a time (pages, facts, thread events), zero LLM. | read | yes | |
| `entity` | MEMORY VERB (v1): one known person/company/project card, zero LLM. | read | yes | |
| `forget` | MEMORY VERB (v1): expire a remembered fact by its fact_id (never a page slug). | write | yes | |
| `recall` | MEMORY VERB (v1): read saved facts by entity, since or session_id; `query` also searches pages. | read | yes | |
-| `remember` | MEMORY VERB (v1): save one fact; provenance required. | write | yes | |
+| `remember` | MEMORY VERB (v1): save one fact (or up to 20 with items); provenance required. | write | yes | |
| `synthesize` | [EXPENSIVE / SLOW: LLM calls, costs money] MEMORY VERB (v1): answer a broad question across pages with citations. | read | yes | |
## ontology
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.md
index 2efc5ebe76..3222cfdfce 100644
--- a/docs/architecture/KEY_FILES.md
+++ b/docs/architecture/KEY_FILES.md
@@ -72,6 +72,7 @@ boundary and add its link here rather than raising the cap.
| [Agent Bootstrap (continued)](key-files/agent-bootstrap-continued.md) | Remaining cross-file entries |
| [Google connector + open-loop engine (key files cluster)](key-files/google-and-loops.md) | Cross-file subsystem contract |
| [Google And Loops (continued)](key-files/google-and-loops-continued.md) | Remaining cross-file entries |
+| [Always-loaded core memory (key files cluster)](key-files/core-memory.md) | Core tier, write-path guard and lock order, delivery lanes, pressure notice |
## BrainBench — in a sibling repo
@@ -92,3 +93,7 @@ See [Agent bootstrap cluster (the paste-in desktop-agent install)](key-files/age
## Google connector + open-loop engine (key files cluster)
See [Google connector + open-loop engine (key files cluster)](key-files/google-and-loops.md).
+
+## Always-loaded core memory (key files cluster)
+
+See [Always-loaded core memory (key files cluster)](key-files/core-memory.md).
diff --git a/docs/architecture/key-files/core-memory.md b/docs/architecture/key-files/core-memory.md
new file mode 100644
index 0000000000..af2419b021
--- /dev/null
+++ b/docs/architecture/key-files/core-memory.md
@@ -0,0 +1,49 @@
+# Always-loaded core memory (key files cluster)
+
+[Subsystem index](../KEY_FILES.md).
+
+Owner-designated pages (`always_load: true`) rendered into every session,
+held to a brain-wide character budget on the write path, plus the
+save-before-compaction path (`remember` with `items`, the context-pressure
+notice). User guide: [core memory](../../guides/core-memory.md).
+
+- `src/core/core-memory.ts`: marking and priority normalization, settings
+ (`memory.core.*`), page rendering and budget accounting, `listCorePages`
+ (withdrawal-aware), `renderCoreBlock` (whole-page truncation, notice lines,
+ withheld lines), `coreRevision`, the delivery sensitivity policy
+ (`applyCoreSensitivity`: credential-like hits withhold, contact details and
+ private paths redact) and `loadCoreBlock`, which every delivery lane uses.
+- `src/core/persistence/core-guard.ts`: the write-path guard run from
+ `preparePageMutation`: owner-only marking (`core_mark_owner_only`,
+ `core_delete_owner_only`), the budget (`core_budget_exceeded`, re-checked in
+ the publish transaction), the remote-edit policy and `core_edit_notices`
+ rows, and `lockCoreSources`.
+- Lock order for a core-touching publish (`coordinator.ts`): worktree native
+ lock, then `guardOwnership` (`persistence_worktrees` FOR SHARE), then
+ `lockCoreSources` (`sources` rows FOR UPDATE, `ORDER BY id`, own source plus
+ `default`) in the source-exclusive slot, then `authorizeStoredRequest`
+ (`sources` FOR SHARE), then `lockCounters`. Topology and deactivation take
+ worktrees before sources and sources in id order, so the orders agree;
+ `test/e2e/core-memory-locks-postgres.test.ts` races them on Postgres.
+- `scripts/check-core-guard-coverage.mjs` (`bun run check:core-guard-coverage`,
+ in `verify`): every PreparedMutation builder routes through the guard or is
+ on its reviewed exemption list, and wrappers forward `exclusiveSources`.
+- Delivery: `src/commands/hook.ts` session-start (core first via
+ `src/core/context/session-start-output.ts`), `context_pack`
+ (`src/core/ops/facts.ts`, `src/mcp/context-pack-handler.ts`, including the
+ read-only `coreOnly` IPC arm), OpenClaw `assemble()` in
+ `src/core/context-engine.ts` (60 s memo), and `gbrain compile-context
+ --include-core` (`src/core/context/compile-view.ts`,
+ `src/core/context/compiled-core.ts` for git safety and the record doctor
+ reads).
+- Pressure notice: `src/core/context/pressure.ts` (gate read by serve, transcript
+ scan, window detection, once-per-segment state); wired in the user-prompt
+ hook and OpenClaw `assemble()`.
+- `src/core/remember-batch.ts`: `remember` with `items[]` (all-or-none
+ validation, deterministic child request ids, per-item status).
+- `src/commands/core.ts` (`gbrain core`), `src/commands/doctor/checks/core-memory.ts`
+ (`core_memory`), schema `src/core/core-memory-schema.ts` + migration v201.
+- Tests: `test/core-memory.test.ts`, `test/core-guard.test.ts`,
+ `test/core-cli.test.ts`, `test/compile-context-core.serial.test.ts`,
+ `test/context-pressure.test.ts`, `test/remember-batch.test.ts`,
+ `test/e2e/core-memory-locks-postgres.test.ts`.
diff --git a/docs/mcp/CODEX.md b/docs/mcp/CODEX.md
index 443ad41bd6..0edde19f43 100644
--- a/docs/mcp/CODEX.md
+++ b/docs/mcp/CODEX.md
@@ -158,6 +158,21 @@ Codex stores the env-var *name* (`GBRAIN_REMOTE_TOKEN`), not the token itself, a
reads the value when it launches the MCP server. Add the `export` line to your
`~/.zshrc` / `~/.bashrc` so it's set in every session.
+## Always-loaded core memory
+
+Codex does not put MCP server instructions in the prompt, so core memory
+([guide](../guides/core-memory.md)) reaches Codex through its user-global
+instruction file:
+
+```bash
+gbrain compile-context --target codex-global
+```
+
+This writes the default source's core block into a managed block in
+`$CODEX_HOME/AGENTS.md` (default `~/.codex/AGENTS.md`), which Codex loads in
+every session. Rerun it after core changes (`gbrain doctor` names a stale copy);
+`gbrain compile-context --target codex-global --remove-core` takes it out.
+
## Verify
In Codex, ask it to use the brain:
diff --git a/docs/mcp/HERMES.md b/docs/mcp/HERMES.md
index 6b6723c9be..635deea025 100644
--- a/docs/mcp/HERMES.md
+++ b/docs/mcp/HERMES.md
@@ -50,6 +50,19 @@ mcp_servers:
To remove gbrain, delete this block (or set `enabled: false` to disable
without losing the config).
+## Always-loaded core memory
+
+Hermes does not read MCP server instructions, so core memory
+([guide](../guides/core-memory.md)) reaches it through a project context file:
+
+```bash
+gbrain compile-context --target hermes --include-core
+```
+
+This writes `.hermes.md` at the git root and adds it to the repository's local
+exclude file (`.git/info/exclude`), so it is never committed. Rerun it after
+core changes; `gbrain doctor` names a stale copy.
+
## Verify
```bash
diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.md
index 548221f732..557bb5ae42 100644
--- a/docs/protocol/MEMORY_VERBS_v1.md
+++ b/docs/protocol/MEMORY_VERBS_v1.md
@@ -282,6 +282,26 @@ Optional response fields; clients must ignore any they do not know.
caller is never told about an entity it cannot read: that case is `NO_ENTITY`.
- `hint: string` — present with `warnings`; names the `entity` input.
+#### remember items: several facts in one call (additive)
+
+`items` (1 to 20 objects) replaces `fact` for a batch, typically right before
+context compaction. Each item takes `fact` plus optional `entity`, `kind`,
+`ttl`, `visibility`, `provenance` and `infer_entity`; top-level `provenance`,
+`kind`, `ttl`, `visibility` and `infer_entity` are the defaults. Passing both
+`fact` and `items` is `invalid_params`.
+
+Every item is validated before any is written: one invalid item refuses the
+whole call with `items[<i>]` in the message. Each item is then saved as its own
+write with a child `request_id` derived from the call's `request_id` and the
+item index, so replaying the same `request_id` replays each child's outcome and
+writes nothing twice.
+
+Response: `{ protocol_version, request_id, items[], saved, failed, partial,
+next? }`. Each `items[]` entry is the single-fact response plus `index` and its
+child `request_id`, or `{ index, request_id, status: "failed", error: { code,
+message } }`. `partial: true` means some items saved and some failed; resend
+only the failed items, in a new call with a new `request_id`.
+
### entity(name) — read, zero LLM, p99 < 100ms
One known person/company/project card. NEVER errors on a miss.
@@ -538,10 +558,18 @@ lockstep, and is honored ONLY for trusted-local callers (`remote === false`); a
remote caller never widens (fail-closed).
Response: `{ protocol_version, entities, cards[], open_threads[], facts[], text,
-degraded_reason?, budget_tokens?, budget_used?, dropped_count? }`. `text` is the
+degraded_reason?, budget_tokens?, budget_used?, dropped_count?, core? }`. `text` is the
pre-rendered, envelope-wrapped injectable block; with `budget_tokens` it is
rendered from the packed sets and never exceeds the declared budget.
+#### context_pack core memory (additive)
+
+`core: { text, revision, chars_used, chars_limit, pages, truncated }` carries the
+always-loaded core block (owner-designated pages loaded in every session,
+[core memory](../guides/core-memory.md)) when core memory is on and not empty.
+`text` starts with the core block, and core tokens count inside
+`budget_tokens`. `entities` may be omitted to fetch core alone.
+
### delta(since?, entities?, budget_tokens?, session_id?, include_private?) — read, zero LLM
"What changed since T" for heartbeats — pages updated after
diff --git a/scripts/check-core-guard-coverage.mjs b/scripts/check-core-guard-coverage.mjs
index 332f0e49a8..1981c1c216 100644
--- a/scripts/check-core-guard-coverage.mjs
+++ b/scripts/check-core-guard-coverage.mjs
@@ -17,7 +17,8 @@
import { readFileSync, readdirSync, statSync } from 'node:fs';
import { join, relative } from 'node:path';
-const ROOT = new URL('..', import.meta.url).pathname;
+// Fixture root for scripts/guard-self-test.sh: argv[2] or GBRAIN_GUARD_ROOT.
+const ROOT = process.argv[2] ?? process.env.GBRAIN_GUARD_ROOT ?? new URL('..', import.meta.url).pathname;
/** Reviewed: preparers that publish without the core guard, and why that is safe. */
const EXEMPT = {
diff --git a/scripts/guards-manifest.tsv b/scripts/guards-manifest.tsv
index bb21180917..611fc89c5a 100644
--- a/scripts/guards-manifest.tsv
+++ b/scripts/guards-manifest.tsv
@@ -80,6 +80,7 @@ check-structural-manifest.sh buildfresh exempt regenerate+diff of structural-sui
check-opencode-pin.sh repostate exempt pin-stamp drift check (OPENCODE-CLI-PIN.md stamps vs heavy-tests opencode-door env); own bun guard tests in test/check-bootstrap-guards.test.ts
check-pin-doc-privacy.sh repostate exempt PIN-doc placeholder discipline (no operator paths/key material/emails in docs/mcp/*-CLI-PIN.md); own bun guard tests in test/check-bootstrap-guards.test.ts
check-getpage-scoped-write.mjs scanner yes unscoped-getPage + write co-occurrence scanner (source-isolation bug class); argv root override; fixtures under test/fixtures/guards/; also in verify CHECKS
+check-core-guard-coverage.mjs scanner yes core memory write-path guard coverage: PreparedMutation builders route through preparePageMutation or a reasoned EXEMPT entry, wrappers forward exclusiveSources; argv/GBRAIN_GUARD_ROOT root override; in verify CHECKS
check-orphan-modules.mjs scanner yes runtime-reachability walk (static+dynamic relative imports) from cli/mcp/plugin/admin entrypoints + package.json exports; hard-fails untested orphans, requires a reasoned PERMITTED_TEST_ONLY entry per test-only module (stale entries fail); fixture root via argv/GBRAIN_GUARD_ROOT; knip v5 evaluated + rejected (crashes on repo layout — see script header)
check-test-placeholders.mjs scanner yes TypeScript AST (CallExpression) scan of test/**/*.test.ts for no-op expect(true)/expect(1) placeholders; path+test+count allowlist (disabled in fixture mode); fixture root via argv/GBRAIN_GUARD_ROOT; in verify CHECKS
check-test-discriminates.sh buildfresh exempt manual per-PR discrimination helper (#3665): reverts named source files to their pre-fix state and runs the named test file to prove it fails without the fix — the test run IS the check; not in verify CHECKS or CI
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index a11ae084a4..8be71c4439 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -77,6 +77,7 @@ test/codex-plugin-manifest.test.ts codex mcp.json 3 readFileSync
test/codex-plugin-manifest.test.ts curated tree membership + scanner guard 6 readFileSync
test/codex-plugin-manifest.test.ts generator negative fixtures (a guard that cannot fail is not coverage) 9 readFileSync
test/codex-plugin-manifest.test.ts variant ${def.plugin_name} (persona ${personaName}) 5 readFileSync
+test/compile-context-core.serial.test.ts compile-context core arm 5 readFileSync
test/compile-view.test.ts compileView — determinism 3 readFileSync
test/compile-view.test.ts compileView — source isolation + read errors 3 readFileSync
test/config.test.ts config source correctness 1 readFileSync
diff --git a/src/core/context-engine.ts b/src/core/context-engine.ts
index 93d7eaa12f..932fd39be4 100644
--- a/src/core/context-engine.ts
+++ b/src/core/context-engine.ts
@@ -17,7 +17,7 @@ import { readFileSync, existsSync, statSync } from 'fs';
import { join } from 'path';
import { buildReflexAddition, warmReflex, type ResolveEntitiesFn as ReflexResolveEntitiesFn } from './context/reflex.ts';
import { backupNagReadOnlyConsult, backupNoticeText, loadBackupStatus } from './backup/status-file.ts';
-import { pressureNotice, type PressureGate } from './context/pressure.ts';
+import { estimateMessageTokens, openClawCoreLane } from './context/openclaw-core.ts';
// Types inlined from openclaw/plugin-sdk to avoid hard dependency during development.
// At runtime inside OpenClaw, the real SDK is available; these types ensure build compat.
@@ -903,60 +903,6 @@ export function createGBrainContextEngine(ctx: {
]);
}
- // Always-loaded core (core-memory.ts): one read-only fetch per TTL window,
- // shared across sessions of this process (core is per brain + source, not
- // per session). Staleness of at most CORE_MEMO_TTL_MS is accepted.
- const CORE_MEMO_TTL_MS = 60_000;
- type CoreFetch = { text: string; pressure: PressureGate | null };
- let coreMemo: { at: number; value: CoreFetch } | null = null;
- async function fetchCore(sessionId: string | null): Promise<CoreFetch | null> {
- const work = (async (): Promise<CoreFetch | null> => {
- try {
- const { loadConfig } = await import('./config.ts');
- const cfg = loadConfig();
- if (cfg?.engine === 'pglite' && cfg.database_path) {
- const ipc = await import('./context/resolve-ipc.ts');
- const secret = ipc.readIpcSecret(cfg.database_path);
- if (!secret) return null;
- // bankOnly rides along for version skew: an older serve without the
- // coreOnly arm takes the no-op banking arm instead of assembling.
- const res = await ipc.requestContextPack(ipc.resolveSocketPath(cfg.database_path), {
- secret, coreOnly: true, bankOnly: true,
- ...(sessionId ? { sessionId } : {}),
- ...(process.env.GBRAIN_SOURCE ? { sourceId: process.env.GBRAIN_SOURCE } : {}),
- });
- if (res === ipc.IPC_UNAVAILABLE || !('ok' in res) || !res.ok || !res.block) return null;
- return { text: res.block.core?.text ?? '', pressure: res.block.pressure ?? null };
- }
- const { getDirectPostgresEngine } = await import('./context/reflex.ts');
- const pg = await getDirectPostgresEngine(cfg);
- if (!pg) return null;
- const { resolveSourceId } = await import('./source-resolver.ts');
- const sourceId = await resolveSourceId(pg, null, workspaceDir);
- const { loadCoreBlock } = await import('./core-memory.ts');
- const { readPressureGate } = await import('./context/pressure.ts');
- return {
- text: (await loadCoreBlock(pg, { sessionSourceId: sourceId, excludePrivate: true })).text,
- pressure: await readPressureGate(pg, true).catch(() => null),
- };
- } catch {
- return null;
- }
- })();
- return Promise.race([work, new Promise<null>((resolve) => {
- const t = setTimeout(() => resolve(null), CHECKPOINT_POLL_TIMEOUT_MS);
- if (typeof (t as { unref?: () => void }).unref === 'function') (t as unknown as { unref: () => void }).unref();
- })]);
- }
- async function getCore(sessionId: string | null): Promise<CoreFetch> {
- if (coreMemo && Date.now() - coreMemo.at < CORE_MEMO_TTL_MS) return coreMemo.value;
- const value = await fetchCore(sessionId);
- // A failed fetch keeps the previous value for one more window rather than flapping.
- coreMemo = { at: Date.now(), value: value ?? coreMemo?.value ?? { text: '', pressure: null } };
- return coreMemo.value;
- }
- /** Sessions already warned about context pressure since their last compaction. */
- const pressureWarned = new Set<string>();
/** assemble()-side: memo-first, hash-keyed polls, settle-and-render. */
async function getCheckpointBlock(sessionId: string): Promise<string | null> {
@@ -1289,12 +1235,9 @@ export function createGBrainContextEngine(ctx: {
// whether memory/reflex fire) + memory prompt + reflex pointers. No
// manifest ⇒ parts untouched ⇒ byte-identical to the pre-cathedral-5
// output (pinned).
- const parts = [contextBlock];
- // Always-loaded core sits right after the live context block.
- const coreSid = sanitizeEngineSessionId(sessionId ?? sessionKey ?? null);
- let core: CoreFetch = { text: '', pressure: null };
- try { core = await getCore(coreSid); } catch { /* fail-open */ }
- if (core.text && process.env.GBRAIN_CORE !== '0') parts.push(core.text);
+ // Always-loaded core + the context-pressure notice right after the live block (context/openclaw-core.ts).
+ const parts = [contextBlock, ...await openClawCoreLane(workspaceDir, CHECKPOINT_POLL_TIMEOUT_MS).additions({
+ sessionId: sanitizeEngineSessionId(sessionId ?? sessionKey ?? null), messages: msgs, tokenBudget, availableTools })];
if (checkpointBlock) parts.push(checkpointBlock);
if (memoryAddition) parts.push(memoryAddition);
if (reflexAddition) parts.push(reflexAddition);
@@ -1315,30 +1258,10 @@ export function createGBrainContextEngine(ctx: {
/* a notice must never break context assembly */
}
- const estimatedTokens = msgs.reduce((sum, m) => {
- const text = typeof m.content === 'string'
- ? m.content
- : JSON.stringify(m.content);
- // #2880: JSON.stringify(undefined) is undefined, not a string —
- // a content-less message counts 0 instead of throwing.
- return sum + (typeof text === 'string' ? Math.ceil(text.length / 4) : 0);
- }, 0);
-
- // Context-pressure notice (pressure.ts): once per compaction segment, only when remember is callable.
- const gate = core.pressure;
- const window = gate?.context_window ?? tokenBudget ?? 0;
- const pressureKey = coreSid ?? 'default';
- const rememberTool = [...(availableTools ?? [])].some((t) => /(^|[_.:-])remember$/.test(t));
- if (gate?.enabled && rememberTool && window > 0 && !pressureWarned.has(pressureKey)
- && process.env.GBRAIN_PRESSURE !== '0' && estimatedTokens / window >= gate.warn_ratio) {
- pressureWarned.add(pressureKey);
- parts.push(pressureNotice(Math.min(99, Math.round((estimatedTokens / window) * 100))));
- }
-
// 4. Pass through messages unchanged (legacy assembly)
return {
messages: msgs,
- estimatedTokens,
+ estimatedTokens: estimateMessageTokens(msgs),
systemPromptAddition: parts.join('\n\n'),
};
},
@@ -1346,8 +1269,7 @@ export function createGBrainContextEngine(ctx: {
async compact(params) {
// Lazy SDK load on first method call (was top-level await pre-L0-B).
await ensureSdkLoaded();
- // A new compaction segment may warn about context pressure again.
- pressureWarned.delete(sanitizeEngineSessionId(params?.sessionId ?? params?.sessionKey ?? null) ?? 'default');
+ openClawCoreLane(workspaceDir, CHECKPOINT_POLL_TIMEOUT_MS).compacted(sanitizeEngineSessionId(params?.sessionId ?? params?.sessionKey ?? null));
// Cathedral 5 — time-bounded, FAIL-OPEN checkpoint step BEFORE the
// delegate. A checkpoint failure/timeout must never break compaction.
// The deadline CANCELS the work (adversarial review): the race alone
diff --git a/src/core/context/openclaw-core.ts b/src/core/context/openclaw-core.ts
new file mode 100644
index 0000000000..9786db45c9
--- /dev/null
+++ b/src/core/context/openclaw-core.ts
@@ -0,0 +1,114 @@
+/**
+ * OpenClaw lane for always-loaded core memory and the context-pressure
+ * notice (core-memory.ts, pressure.ts). One read-only core fetch per TTL
+ * window, shared across sessions of the process (core is per brain + source,
+ * not per session); staleness of at most CORE_MEMO_TTL_MS is accepted. The
+ * pressure notice fires once per session until its next compaction, only
+ * when a remember tool is available.
+ */
+import { pressureNotice, type PressureGate } from './pressure.ts';
+
+export const CORE_MEMO_TTL_MS = 60_000;
+
+interface CoreFetch { text: string; pressure: PressureGate | null }
+
+/** The engine's token estimate for a message list (chars / 4 per message; content-less messages count 0, #2880). */
+export function estimateMessageTokens(msgs: ReadonlyArray<{ content?: unknown }>): number {
+ return msgs.reduce((sum, m) => {
+ const text = typeof m.content === 'string' ? m.content : JSON.stringify(m.content);
+ return sum + (typeof text === 'string' ? Math.ceil(text.length / 4) : 0);
+ }, 0);
+}
+
+export interface OpenClawCoreLane {
+ /** Parts to append after the live context block: the core block and, when due, the pressure notice. */
+ additions(input: { sessionId: string | null; messages: ReadonlyArray<{ content?: unknown }>; tokenBudget?: number; availableTools?: Set<string> }): Promise<string[]>;
+ /** A compaction starts a new segment: the session may be warned again. */
+ compacted(sessionId: string | null): void;
+}
+
+export function createOpenClawCoreLane(opts: { workspaceDir?: string; timeoutMs: number }): OpenClawCoreLane {
+ let memo: { at: number; value: CoreFetch } | null = null;
+ const warned = new Set<string>();
+
+ async function fetchCore(sessionId: string | null): Promise<CoreFetch | null> {
+ const work = (async (): Promise<CoreFetch | null> => {
+ try {
+ const { loadConfig } = await import('../config.ts');
+ const cfg = loadConfig();
+ if (cfg?.engine === 'pglite' && cfg.database_path) {
+ const ipc = await import('./resolve-ipc.ts');
+ const secret = ipc.readIpcSecret(cfg.database_path);
+ if (!secret) return null;
+ // bankOnly rides along for version skew: an older serve without the
+ // coreOnly arm takes the no-op banking arm instead of assembling.
+ const res = await ipc.requestContextPack(ipc.resolveSocketPath(cfg.database_path), {
+ secret, coreOnly: true, bankOnly: true,
+ ...(sessionId ? { sessionId } : {}),
+ ...(process.env.GBRAIN_SOURCE ? { sourceId: process.env.GBRAIN_SOURCE } : {}),
+ });
+ if (res === ipc.IPC_UNAVAILABLE || !('ok' in res) || !res.ok || !res.block) return null;
+ return { text: res.block.core?.text ?? '', pressure: res.block.pressure ?? null };
+ }
+ const { getDirectPostgresEngine } = await import('./reflex.ts');
+ const pg = await getDirectPostgresEngine(cfg);
+ if (!pg) return null;
+ const { resolveSourceId } = await import('../source-resolver.ts');
+ const sourceId = await resolveSourceId(pg, null, opts.workspaceDir);
+ const { loadCoreBlock } = await import('../core-memory.ts');
+ const { readPressureGate } = await import('./pressure.ts');
+ return {
+ text: (await loadCoreBlock(pg, { sessionSourceId: sourceId, excludePrivate: true })).text,
+ pressure: await readPressureGate(pg, true).catch(() => null),
+ };
+ } catch {
+ return null;
+ }
+ })();
+ return Promise.race([work, new Promise<null>((resolve) => {
+ const t = setTimeout(() => resolve(null), opts.timeoutMs);
+ (t as { unref?: () => void }).unref?.();
+ })]);
+ }
+
+ async function getCore(sessionId: string | null): Promise<CoreFetch> {
+ if (memo && Date.now() - memo.at < CORE_MEMO_TTL_MS) return memo.value;
+ const value = await fetchCore(sessionId);
+ // A failed fetch keeps the previous value for one more window rather than flapping.
+ memo = { at: Date.now(), value: value ?? memo?.value ?? { text: '', pressure: null } };
+ return memo.value;
+ }
+
+ return {
+ async additions({ sessionId, messages, tokenBudget, availableTools }) {
+ const estimatedTokens = estimateMessageTokens(messages);
+ let core: CoreFetch = { text: '', pressure: null };
+ try { core = await getCore(sessionId); } catch { /* fail-open */ }
+ const out: string[] = [];
+ if (core.text && process.env.GBRAIN_CORE !== '0') out.push(core.text);
+ const gate = core.pressure;
+ const window = gate?.context_window ?? tokenBudget ?? 0;
+ const key = sessionId ?? 'default';
+ const rememberTool = [...(availableTools ?? [])].some((t) => /(^|[_.:-])remember$/.test(t));
+ if (gate?.enabled && rememberTool && window > 0 && !warned.has(key)
+ && process.env.GBRAIN_PRESSURE !== '0' && estimatedTokens / window >= gate.warn_ratio) {
+ warned.add(key);
+ out.push(pressureNotice(Math.min(99, Math.round((estimatedTokens / window) * 100))));
+ }
+ return out;
+ },
+ compacted(sessionId) {
+ warned.delete(sessionId ?? 'default');
+ },
+ };
+}
+
+const lanes = new Map<string, OpenClawCoreLane>();
+
+/** One lane per engine workspace, so the memo and warned set outlive a single assemble() call. */
+export function openClawCoreLane(workspaceDir: string | undefined, timeoutMs: number): OpenClawCoreLane {
+ const key = workspaceDir ?? '';
+ let lane = lanes.get(key);
+ if (!lane) { lane = createOpenClawCoreLane({ workspaceDir, timeoutMs }); lanes.set(key, lane); }
+ return lane;
+}
diff --git a/test/compile-context-core.test.ts b/test/compile-context-core.serial.test.ts
similarity index 100%
rename from test/compile-context-core.test.ts
rename to test/compile-context-core.serial.test.ts
diff --git a/test/fixtures/guards/check-core-guard-coverage.mjs/bad-drop/src/core/persistence/wrap-prepare.ts b/test/fixtures/guards/check-core-guard-coverage.mjs/bad-drop/src/core/persistence/wrap-prepare.ts
new file mode 100644
index 0000000000..d54e6dbf5a
--- /dev/null
+++ b/test/fixtures/guards/check-core-guard-coverage.mjs/bad-drop/src/core/persistence/wrap-prepare.ts
@@ -0,0 +1,6 @@
+type PreparedMutation = { observedRevision: string | null };
+declare function preparePageMutation(engine: unknown, row: unknown): Promise<PreparedMutation>;
+export async function prepareWrap(engine: unknown, row: unknown): Promise<PreparedMutation> {
+ const page = await preparePageMutation(engine, row);
+ return { observedRevision: page.observedRevision };
+}
diff --git a/test/fixtures/guards/check-core-guard-coverage.mjs/bad/src/core/persistence/new-prepare.ts b/test/fixtures/guards/check-core-guard-coverage.mjs/bad/src/core/persistence/new-prepare.ts
new file mode 100644
index 0000000000..0ee306c832
--- /dev/null
+++ b/test/fixtures/guards/check-core-guard-coverage.mjs/bad/src/core/persistence/new-prepare.ts
@@ -0,0 +1,4 @@
+type PreparedMutation = { observedRevision: string | null };
+export async function prepareNew(): Promise<PreparedMutation> {
+ return { observedRevision: null };
+}
diff --git a/test/fixtures/guards/check-core-guard-coverage.mjs/good/src/core/persistence/wrap-prepare.ts b/test/fixtures/guards/check-core-guard-coverage.mjs/good/src/core/persistence/wrap-prepare.ts
new file mode 100644
index 0000000000..44e7f1e2c1
--- /dev/null
+++ b/test/fixtures/guards/check-core-guard-coverage.mjs/good/src/core/persistence/wrap-prepare.ts
@@ -0,0 +1,6 @@
+type PreparedMutation = { observedRevision: string | null; exclusiveSources?: string[] };
+declare function preparePageMutation(engine: unknown, row: unknown): Promise<PreparedMutation>;
+export async function prepareWrap(engine: unknown, row: unknown): Promise<PreparedMutation> {
+ const page = await preparePageMutation(engine, row);
+ return { ...page };
+}