Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
pressure notice: also warn when the context is growing fast enough to reach the compaction point within two turns (Claude Code and OpenClaw lanes)
garrytan7c0db9f5d4ab
diff --git a/docs/guides/core-memory.md b/docs/guides/core-memory.mdindex 29e8ce7ce3..8491c161d1 100644--- a/docs/guides/core-memory.md+++ b/docs/guides/core-memory.md@@ -110,9 +110,10 @@ Two pieces cover that:is then saved as its own write and reported with its own status, and`partial: true` marks a batch where some items failed. Replaying the same`request_id` replays the same per-item outcomes.-- When a session's context is about 80% full, the next prompt carries one- notice telling the agent to save what matters now with `remember` and- `items`. It fires once per compaction segment, only when `remember` is+- When a session's context is about 80% full, or sooner when it is growing+ fast (two more turns the size of the last one would reach the automatic+ compaction point), the next prompt carries one notice telling the agent to+ save what matters now with `remember` and `items`. It fires once per compaction segment, only when `remember` iscallable, and follows the capture policy (TTL, visibility, exclusions).Turn it off with `gbrain config set memory.pressure.enabled false`.diff --git a/src/core/context/openclaw-core.ts b/src/core/context/openclaw-core.tsindex 9786db45c9..d8c72eb8cd 100644--- a/src/core/context/openclaw-core.ts+++ b/src/core/context/openclaw-core.ts@@ -3,10 +3,11 @@* 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.+ * pressure notice fires once per session until its next compaction (at the+ * warn ratio, or earlier when the context grows fast), only when a remember+ * tool is available.*/-import { pressureNotice, type PressureGate } from './pressure.ts';+import { pressureNotice, shouldWarn, type PressureGate } from './pressure.ts';export const CORE_MEMO_TTL_MS = 60_000;@@ -30,6 +31,7 @@ export interface OpenClawCoreLane {export function createOpenClawCoreLane(opts: { workspaceDir?: string; timeoutMs: number }): OpenClawCoreLane {let memo: { at: number; value: CoreFetch } | null = null;const warned = new Set<string>();+ const lastTokens = new Map<string, number>();async function fetchCore(sessionId: string | null): Promise<CoreFetch | null> {const work = (async (): Promise<CoreFetch | null> => {@@ -90,8 +92,10 @@ export function createOpenClawCoreLane(opts: { workspaceDir?: string; timeoutMs: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) {+ const growth = Math.max(0, estimatedTokens - (lastTokens.get(key) ?? estimatedTokens));+ lastTokens.set(key, estimatedTokens);+ if (gate?.enabled && rememberTool && window > 0 && !warned.has(key) && process.env.GBRAIN_PRESSURE !== '0'+ && shouldWarn({ used: estimatedTokens, window, warnRatio: gate.warn_ratio, growth })) {warned.add(key);out.push(pressureNotice(Math.min(99, Math.round((estimatedTokens / window) * 100))));}@@ -99,6 +103,7 @@ export function createOpenClawCoreLane(opts: { workspaceDir?: string; timeoutMs:},compacted(sessionId) {warned.delete(sessionId ?? 'default');+ lastTokens.delete(sessionId ?? 'default');},};}diff --git a/src/core/context/pressure.ts b/src/core/context/pressure.tsindex 753166cf9a..3cd3221121 100644--- a/src/core/context/pressure.ts+++ b/src/core/context/pressure.ts@@ -143,7 +143,7 @@ export function pressureNotice(percent: number): string {'Skip anything already saved, secrets, and anything the user asked not to keep. This notice appears once per compaction.';}-interface PressureState { segment: string; warned: boolean; maxSeen: number }+interface PressureState { segment: string; warned: boolean; maxSeen: number; lastUsed: number }function stateFile(dir: string, sessionKey: string): string {return join(dir, `${sessionKey.replace(/[^A-Za-z0-9._-]/g, '-').slice(0, 120) || 'session'}.json`);@@ -152,7 +152,7 @@ function stateFile(dir: string, sessionKey: string): string {function readState(path: string): PressureState | null {try {const s = JSON.parse(readFileSync(path, 'utf8')) as Partial<PressureState>;- return typeof s.segment === 'string' ? { segment: s.segment, warned: s.warned === true, maxSeen: Number(s.maxSeen) || 0 } : null;+ return typeof s.segment === 'string' ? { segment: s.segment, warned: s.warned === true, maxSeen: Number(s.maxSeen) || 0, lastUsed: Number(s.lastUsed) || 0 } : null;} catch { return null; }}@@ -165,6 +165,22 @@ function writeState(path: string, dir: string, state: PressureState): void {} catch { /* best-effort: a lost state file can only re-fire one notice */ }}+/** Fill at which harnesses compact automatically (Claude Code compacts a little before the window is full). */+export const AUTO_COMPACT_RATIO = 0.92;+/** Turns of headroom the notice leaves: warn when this many more turns like the last one would reach the compaction point. */+export const HEADROOM_TURNS = 2;++/**+ * Warn at `warnRatio` fill, or earlier when the context grows fast: when+ * HEADROOM_TURNS more turns of the size just seen would reach the automatic+ * compaction point, the next turn may already be compacted.+ */+export function shouldWarn(o: { used: number; window: number; warnRatio: number; growth: number }): boolean {+ if (o.window <= 0) return false;+ if (o.used / o.window >= o.warnRatio) return true;+ return o.growth > 0 && (o.used + HEADROOM_TURNS * o.growth) / o.window >= AUTO_COMPACT_RATIO;+}+export interface PressureDecision { notice: string | null; percent: number; window: number; reason?: string }/**@@ -196,9 +212,10 @@ export function decidePressure(input: {const ratio = input.usedTokens / window;const percent = Math.min(99, Math.round(ratio * 100));const warned = sameSegment && prev?.warned === true;- const fire = ratio >= gate.warn_ratio && !warned;- const next: PressureState = { segment, warned: warned || fire, maxSeen };- if (!prev || prev.segment !== next.segment || prev.warned !== next.warned || prev.maxSeen !== next.maxSeen) writeState(path, input.stateDir, next);+ const growth = sameSegment && prev ? Math.max(0, input.usedTokens - prev.lastUsed) : 0;+ const fire = shouldWarn({ used: input.usedTokens, window, warnRatio: gate.warn_ratio, growth }) && !warned;+ const next: PressureState = { segment, warned: warned || fire, maxSeen, lastUsed: input.usedTokens };+ if (!prev || prev.segment !== next.segment || prev.warned !== next.warned || prev.maxSeen !== next.maxSeen || prev.lastUsed !== next.lastUsed) writeState(path, input.stateDir, next);if (warned) return { notice: null, percent, window, reason: 'already_warned' };return fire ? { notice: pressureNotice(percent), percent, window } : { notice: null, percent, window, reason: 'below_threshold' };}diff --git a/test/context-pressure.test.ts b/test/context-pressure.test.tsindex 78372ec634..f0472a2d1f 100644--- a/test/context-pressure.test.ts+++ b/test/context-pressure.test.ts@@ -3,7 +3,7 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import {- decidePressure, readTranscriptPressure, resolveContextWindow, scanTranscriptPressure, validatePressureConfigValue,+ decidePressure, readTranscriptPressure, resolveContextWindow, scanTranscriptPressure, shouldWarn, validatePressureConfigValue,type PressureGate,} from '../src/core/context/pressure.ts';@@ -82,3 +82,29 @@ describe('window and decision', () => {expect(validatePressureConfigValue('memory.pressure.enabled', 'maybe')).not.toBeNull();});});++describe('growth-aware trigger', () => {+ test('warns before the ratio when two more turns of the last size would reach the compaction point', () => {+ const stateDir = tmp();+ const base = { gate, sessionKey: 'g1', stateDir, model: null, boundary: null };+ expect(decidePressure({ ...base, usedTokens: 100_000 }).notice).toBeNull();+ // +40k in one turn: 140k + 2 x 40k = 220k >= 0.92 x 200k, though 140k is only 70% full.+ const early = decidePressure({ ...base, usedTokens: 140_000 });+ expect(early.notice).not.toBeNull();+ expect(early.percent).toBe(70);+ });++ test('slow growth below the ratio stays quiet', () => {+ const stateDir = tmp();+ const base = { gate, sessionKey: 'g2', stateDir, model: null, boundary: null };+ decidePressure({ ...base, usedTokens: 100_000 });+ expect(decidePressure({ ...base, usedTokens: 105_000 }).notice).toBeNull();+ });++ test('shouldWarn bounds', () => {+ expect(shouldWarn({ used: 160, window: 200, warnRatio: 0.8, growth: 0 })).toBe(true);+ expect(shouldWarn({ used: 100, window: 200, warnRatio: 0.8, growth: 0 })).toBe(false);+ expect(shouldWarn({ used: 100, window: 200, warnRatio: 0.8, growth: 42 })).toBe(true);+ expect(shouldWarn({ used: 10, window: 0, warnRatio: 0.8, growth: 99 })).toBe(false);+ });+});