Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

context-pressure save notice (Claude Code user-prompt + OpenClaw), core/pressure config keys

garrytan6dbd5153a47a
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index c8d143f471..f1b9abd622 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -34,9 +34,9 @@ src/commands/sources.ts 2031 ratchet +5 #5988: sources status/retry-held help ro
src/core/link-extraction.ts 2158 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
src/core/embedding-migration.ts 1569 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
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 1903 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
+src/commands/hook.ts 1908 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; +6 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/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 1838 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)
+src/core/config.ts 1841 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 core memory: memory.core.* and memory.pressure.* known 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
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
src/core/ops/pages.ts 663 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts)
diff --git a/src/commands/config.ts b/src/commands/config.ts
index c761e7aaa1..be55800e8e 100644
--- a/src/commands/config.ts
+++ b/src/commands/config.ts
@@ -1041,6 +1041,14 @@ export async function runConfig(engine: BrainEngine, args: string[]) {
catch (error) { console.error(`[config] ${(error as Error).message}`); process.exit(1); }
}
+ // Core memory and pressure keys are read on every session/turn; reject bad values here.
+ if (key.startsWith('memory.core.') || key.startsWith('memory.pressure.')) {
+ const { validateCoreConfigValue } = await import('../core/core-memory.ts');
+ const { validatePressureConfigValue } = await import('../core/context/pressure.ts');
+ const problem = validateCoreConfigValue(key, value) ?? validatePressureConfigValue(key, value);
+ if (problem) { console.error(`[config] ${problem} Nothing was written.`); process.exit(1); }
+ }
+
// #5254: an unknown value would silently keep refusing unbound writes.
const { UNBOUND_WRITE_KEY, parseUnboundWriteValue } = await import('../core/persistence/unbound-source.ts');
if (key === UNBOUND_WRITE_KEY) {
diff --git a/src/commands/hook.ts b/src/commands/hook.ts
index acbe03e2fb..d3fb802440 100644
--- a/src/commands/hook.ts
+++ b/src/commands/hook.ts
@@ -87,6 +87,8 @@ import {
type HookHeartbeatEntry,
} from '../core/context/hook-heartbeat.ts';
import { CLAUDE_HOOK_OUTPUT_CAP_CHARS } from '../core/bootstrap/host-specs.ts';
+import { composeSessionStartOutput } from '../core/context/session-start-output.ts';
+import { claudeCodePressure } from '../core/context/pressure.ts';
import { readManifest, readReceipt, type InstallReceipt } from '../core/bootstrap/format.ts';
import { githubOwnerRepoString } from '../core/repo-visibility.ts';
import { detectExecutionEnvironment } from '../core/execution-env.ts';
@@ -478,7 +480,6 @@ async function hookSessionStart(io: HookIo): Promise<number> {
let outcome: HookHeartbeatEntry['outcome'] = 'ok';
let reason: string | undefined;
const out: string[] = [];
- // Boxed: assigned inside the deadline-raced closure (TS cannot see that write).
const coreBox: { core: { text: string; revision: string; chars_used: number } | null; reason?: string } = { core: null };
// Deferred nag records: fire ONLY after the digest actually reached stdout
// (record-after-write — a deadline-suppressed note must re-fire next time).
@@ -558,7 +559,6 @@ async function hookSessionStart(io: HookIo): Promise<number> {
if (res !== IPC_UNAVAILABLE && !('degraded' in res)) {
const pack = res as ContextPackResponse;
if (pack.ok && pack.block?.text) out.push(pack.block.text);
- // Always-loaded core rides the same response; an older serve omits it.
if (pack.ok && pack.block?.core && process.env.GBRAIN_CORE !== '0') coreBox.core = pack.block.core;
else if (pack.ok && !pack.block?.core) coreBox.reason = 'stale_serve_no_core';
}
@@ -575,8 +575,7 @@ async function hookSessionStart(io: HookIo): Promise<number> {
}
// Print whatever accumulated before the deadline — a partial digest
// beats an empty one (the deadline bounds latency, not usefulness).
- // Always-loaded core prints first; the digest/pack are trimmed (never
- // core) so the whole stdout stays under the harness cap.
+ // Always-loaded core first; digest/pack trimmed to the cap (session-start-output.ts).
const text = composeSessionStartOutput(coreBox.core?.text ?? '', out.filter(Boolean));
if (text) {
write(io, text + '\n');
@@ -603,33 +602,6 @@ async function hookSessionStart(io: HookIo): Promise<number> {
return 0;
}
-/** Marker printed when lower-priority parts were trimmed to keep core whole under the cap. */
-export const SESSION_START_TRIM_MARKER = '[gbrain: digest/pack trimmed to fit core memory]';
-
-/**
- * Session-start stdout: core first, then the other parts, all under
- * CLAUDE_HOOK_OUTPUT_CAP_CHARS (overflow would be diverted, never injected).
- * Trailing parts are dropped whole, then the last kept part is cut, before
- * core is ever touched; core itself is bounded by memory.core.max_chars.
- */
-export function composeSessionStartOutput(coreText: string, parts: string[]): string {
- const cap = CLAUDE_HOOK_OUTPUT_CAP_CHARS - 64;
- const head = coreText ? [coreText] : [];
- const kept: string[] = [];
- let trimmed = false;
- const size = (xs: string[]) => xs.join('\n\n').length;
- for (const part of parts) {
- if (size([...head, ...kept, part, SESSION_START_TRIM_MARKER]) <= cap) { kept.push(part); continue; }
- const room = cap - size([...head, ...kept, SESSION_START_TRIM_MARKER]) - 4;
- if (room > 200) kept.push(part.slice(0, room));
- trimmed = true;
- break;
- }
- const all = [...head, ...kept, ...(trimmed ? [SESSION_START_TRIM_MARKER] : [])];
- const text = all.join('\n\n');
- return text.length <= CLAUDE_HOOK_OUTPUT_CAP_CHARS ? text : text.slice(0, CLAUDE_HOOK_OUTPUT_CAP_CHARS);
-}
-
/**
* Extract the digest-eligible sections from MEMORY.md [A3]. Only headings in
* DIGEST_SECTIONS qualify — the template's security-boundary note and every
@@ -1110,6 +1082,7 @@ interface UserPromptOutcome {
outcome: HookHeartbeatEntry['outcome'];
reason?: string;
turns?: number;
+ pressure_pct?: number;
}
async function hookUserPrompt(io: HookIo): Promise<number> {
@@ -1141,6 +1114,7 @@ async function hookUserPrompt(io: HookIo): Promise<number> {
// path aborts the event (heartbeat + empty stdout), never "best effort".
let turns: WindowTurn[] = [];
let priorContextText: string | undefined;
+ let transcriptPath: string | undefined;
if (j.transcript_path !== undefined && j.transcript_path !== null) {
const conf = confineTranscriptPath(j.transcript_path, {
...(io.transcriptRoot ? { root: io.transcriptRoot } : {}),
@@ -1150,6 +1124,7 @@ async function hookUserPrompt(io: HookIo): Promise<number> {
allowOversize: true,
});
if (!conf.ok) return { outcome: 'degraded', reason: `transcript_${conf.reason}` };
+ transcriptPath = conf.path;
try {
const parsed = parseTranscript(conf.path, { maxBytes: USER_PROMPT_TRANSCRIPT_MAX_BYTES });
turns = parsed.turns.slice(-USER_PROMPT_WINDOW_TURNS);
@@ -1226,7 +1201,9 @@ async function hookUserPrompt(io: HookIo): Promise<number> {
if (!resp.ok) {
return { outcome: 'degraded', reason: reasonCode(resp.error ?? 'server_error'), turns: turns.length };
}
- const text = resp.block?.text ?? '';
+ // Context-pressure notice (pressure.ts) leads the block so the cap loop never trims it.
+ const pressure = transcriptPath ? claudeCodePressure(resp.block?.pressure, transcriptPath, sessionId) : null;
+ const text = [pressure?.notice, resp.block?.text].filter(Boolean).join('\n\n');
if (!text) return { outcome: 'ok', reason: 'empty_block', turns: turns.length };
// [ENG-1] The 10000-char harness cap applies to the WHOLE stdout payload;
@@ -1257,10 +1234,9 @@ async function hookUserPrompt(io: HookIo): Promise<number> {
// were never injected. Record it so the doctor's heartbeat reconciliation
// (and a future reconciler) can see the divergence — outcome stays ok
// (context WAS injected), the reason carries the signal.
- if (blockText.length < text.length) {
- return { outcome: 'ok', reason: 'trimmed', turns: turns.length };
- }
- return { outcome: 'ok', turns: turns.length };
+ const pct = pressure?.notice ? { pressure_pct: pressure.percent } : {};
+ if (blockText.length < text.length) return { outcome: 'ok', reason: 'trimmed', turns: turns.length, ...pct };
+ return { outcome: 'ok', turns: turns.length, ...pct };
})();
let result: UserPromptOutcome;
@@ -1298,6 +1274,7 @@ async function hookUserPrompt(io: HookIo): Promise<number> {
...(result.reason ? { reason: result.reason } : {}),
duration_ms: Date.now() - t0,
...(result.turns !== undefined ? { turns: result.turns } : {}),
+ ...(result.pressure_pct !== undefined ? { pressure_pct: result.pressure_pct } : {}),
});
return 0;
}
diff --git a/src/core/config.ts b/src/core/config.ts
index 60c1fb60d9..1e0493b8c5 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1437,6 +1437,9 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
// Fire-once sentinel for the ambient-writeback consent nudge (WP8):
// stamped 'true' after the init/post-upgrade ask has been shown once.
'memory.auto_writeback_notice_shown',
+ // Always-loaded core memory + context-pressure notice (docs/guides/core-memory.md#configuration).
+ 'memory.core.enabled', 'memory.core.max_chars', 'memory.core.remote_edit',
+ 'memory.pressure.enabled', 'memory.pressure.warn_ratio', 'memory.pressure.context_window',
// Declared brain audience: 'personal' | 'shared'. Set by the operator, by
// company-brainify's Phase-5 handoff (shared), or from the bootstrap
// interview. Declaration beats the conservative client-count heuristic in
diff --git a/src/core/context-engine.ts b/src/core/context-engine.ts
index 143d520ead..93d7eaa12f 100644
--- a/src/core/context-engine.ts
+++ b/src/core/context-engine.ts
@@ -17,6 +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';
// 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.
@@ -906,9 +907,10 @@ export function createGBrainContextEngine(ctx: {
// 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;
- let coreMemo: { at: number; text: string } | null = null;
- async function fetchCore(sessionId: string | null): Promise<string | null> {
- const work = (async (): Promise<string | null> => {
+ 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();
@@ -923,8 +925,8 @@ export function createGBrainContextEngine(ctx: {
...(sessionId ? { sessionId } : {}),
...(process.env.GBRAIN_SOURCE ? { sourceId: process.env.GBRAIN_SOURCE } : {}),
});
- if (res === ipc.IPC_UNAVAILABLE || !('ok' in res) || !res.ok || !res.block?.core) return null;
- return res.block.core.text;
+ 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);
@@ -932,7 +934,11 @@ export function createGBrainContextEngine(ctx: {
const { resolveSourceId } = await import('./source-resolver.ts');
const sourceId = await resolveSourceId(pg, null, workspaceDir);
const { loadCoreBlock } = await import('./core-memory.ts');
- return (await loadCoreBlock(pg, { sessionSourceId: sourceId, excludePrivate: true })).text;
+ 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;
}
@@ -942,15 +948,15 @@ export function createGBrainContextEngine(ctx: {
if (typeof (t as { unref?: () => void }).unref === 'function') (t as unknown as { unref: () => void }).unref();
})]);
}
- async function getCoreBlock(sessionId: string | null): Promise<string | null> {
- if (process.env.GBRAIN_CORE === '0') return null;
- if (coreMemo && Date.now() - coreMemo.at < CORE_MEMO_TTL_MS) return coreMemo.text || null;
- const text = await fetchCore(sessionId);
- // A failed fetch keeps the previous block for one more window rather than flapping.
- if (text !== null || !coreMemo) coreMemo = { at: Date.now(), text: text ?? '' };
- else coreMemo.at = Date.now();
- return coreMemo.text || null;
+ 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> {
@@ -1285,9 +1291,10 @@ export function createGBrainContextEngine(ctx: {
// output (pinned).
const parts = [contextBlock];
// Always-loaded core sits right after the live context block.
- let coreBlock: string | null = null;
- try { coreBlock = await getCoreBlock(sanitizeEngineSessionId(sessionId ?? sessionKey ?? null)); } catch { coreBlock = null; }
- if (coreBlock) parts.push(coreBlock);
+ 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);
if (checkpointBlock) parts.push(checkpointBlock);
if (memoryAddition) parts.push(memoryAddition);
if (reflexAddition) parts.push(reflexAddition);
@@ -1308,17 +1315,30 @@ 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: 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),
+ estimatedTokens,
systemPromptAddition: parts.join('\n\n'),
};
},
@@ -1326,6 +1346,8 @@ 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');
// 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/hook-heartbeat.ts b/src/core/context/hook-heartbeat.ts
index 2944ee49d5..140a1001ca 100644
--- a/src/core/context/hook-heartbeat.ts
+++ b/src/core/context/hook-heartbeat.ts
@@ -42,6 +42,8 @@ export interface HookHeartbeatEntry {
/** Always-loaded core: chars and revision delivered by session-start (counts/digests only). */
core_chars?: number;
core_revision?: string;
+ /** Context-pressure notice: the fill percent when the notice fired (number only). */
+ pressure_pct?: number;
/** Cathedral 5 — checkpoint-harvest fact counters (counts only) [S3#7].
* The ambient-writeback lane (`event: 'writeback'`) reports the same
* counters plus `superseded` — these are PERSISTED results from the
@@ -73,7 +75,7 @@ export interface HookHeartbeatEntry {
export const HEARTBEAT_ALLOWED_KEYS = [
'ts', 'event', 'outcome', 'reason', 'duration_ms', 'turns', 'bytes', 'redactions',
'segment', 'inserted', 'duplicate', 'superseded', 'near_duplicate', 'links', 'flush',
- 'pattern', 'fingerprint', 'hint',
+ 'pattern', 'fingerprint', 'hint', 'core_chars', 'core_revision', 'pressure_pct',
] as const;
/**
diff --git a/src/core/context/pressure.ts b/src/core/context/pressure.ts
new file mode 100644
index 0000000000..753166cf9a
--- /dev/null
+++ b/src/core/context/pressure.ts
@@ -0,0 +1,216 @@
+/**
+ * Context-pressure warning: when a session's context window is about 80%
+ * full, the next turn carries one notice telling the agent to save what
+ * matters now with `remember` + `items`, before compaction drops it.
+ *
+ * On by default (opt-out `memory.pressure.enabled=false`). Gates come from
+ * the serve (DB-plane config plus whether `remember` is callable on its
+ * surface); the harness side measures fill and fires at most once per
+ * compaction segment.
+ */
+import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, readSync, renameSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../engine.ts';
+import { resolveGbrainHome } from '../gbrain-home.ts';
+
+export const PRESSURE_CONFIG_KEYS = {
+ enabled: 'memory.pressure.enabled',
+ warnRatio: 'memory.pressure.warn_ratio',
+ contextWindow: 'memory.pressure.context_window',
+} as const;
+export const PRESSURE_DEFAULT_WARN_RATIO = 0.8;
+export const PRESSURE_DEFAULT_WINDOW = 200_000;
+export const PRESSURE_LARGE_WINDOW = 1_000_000;
+/** Tail read budget for the transcript scan (the newest assistant usage is near the end). */
+const TRANSCRIPT_TAIL_BYTES = 256 * 1024;
+
+/** Serve-sourced gate carried on the turn_context / context_pack response. */
+export interface PressureGate {
+ enabled: boolean;
+ warn_ratio: number;
+ context_window: number | null;
+ remember_callable: boolean;
+}
+
+function parseBool(raw: string | null | undefined): boolean | null {
+ const v = raw?.trim().toLowerCase();
+ if (v === 'true' || v === '1' || v === 'on' || v === 'yes') return true;
+ if (v === 'false' || v === '0' || v === 'off' || v === 'no') return false;
+ return null;
+}
+
+export function parseWarnRatio(raw: string | null | undefined): number | null {
+ if (raw == null || raw.trim() === '') return null;
+ const n = Number(raw);
+ return Number.isFinite(n) && n >= 0.5 && n <= 0.95 ? n : null;
+}
+
+export function parseContextWindow(raw: string | null | undefined): number | null {
+ if (raw == null || raw.trim() === '') return null;
+ const n = Number(raw);
+ return Number.isInteger(n) && n >= 8_000 && n <= 10_000_000 ? n : null;
+}
+
+/** Validation for `gbrain config set` on the pressure keys; null when valid. */
+export function validatePressureConfigValue(key: string, value: string): string | null {
+ if (key === PRESSURE_CONFIG_KEYS.enabled && parseBool(value) === null) return `${key} must be true or false (default true).`;
+ if (key === PRESSURE_CONFIG_KEYS.warnRatio && parseWarnRatio(value) === null) return `${key} must be a number from 0.5 to 0.95 (default ${PRESSURE_DEFAULT_WARN_RATIO}).`;
+ if (key === PRESSURE_CONFIG_KEYS.contextWindow && parseContextWindow(value) === null) return `${key} must be a whole number of tokens from 8000 to 10000000 (unset = detect).`;
+ return null;
+}
+
+export async function readPressureGate(engine: Pick<BrainEngine, 'getConfig'>, rememberCallable: boolean): Promise<PressureGate> {
+ const [enabled, ratio, window] = await Promise.all([
+ engine.getConfig(PRESSURE_CONFIG_KEYS.enabled).catch(() => null),
+ engine.getConfig(PRESSURE_CONFIG_KEYS.warnRatio).catch(() => null),
+ engine.getConfig(PRESSURE_CONFIG_KEYS.contextWindow).catch(() => null),
+ ]);
+ return {
+ enabled: parseBool(enabled) ?? true,
+ warn_ratio: parseWarnRatio(ratio) ?? PRESSURE_DEFAULT_WARN_RATIO,
+ context_window: parseContextWindow(window),
+ remember_callable: rememberCallable,
+ };
+}
+
+export interface TranscriptPressure {
+ /** Tokens the newest assistant turn consumed (input + cache creation + cache read). */
+ usedTokens: number;
+ /** Model id of that turn, when recorded. */
+ model: string | null;
+ /** uuid of the newest compact boundary inside the scanned tail, if any. */
+ boundary: string | null;
+}
+
+/** Parses the newest usage and compact boundary from Claude Code JSONL text (oldest → newest lines). */
+export function scanTranscriptPressure(text: string): TranscriptPressure | null {
+ const lines = text.split('\n');
+ let usage: { used: number; model: string | null } | null = null;
+ let boundary: string | null = null;
+ for (let i = lines.length - 1; i >= 0 && (!usage || !boundary); i--) {
+ const line = lines[i]!.trim();
+ if (!line.startsWith('{')) continue;
+ let row: Record<string, unknown>;
+ try { row = JSON.parse(line) as Record<string, unknown>; } catch { continue; }
+ if (!boundary && row.type === 'system' && row.subtype === 'compact_boundary' && typeof row.uuid === 'string') {
+ boundary = row.uuid;
+ if (!usage) return null; // nothing measured since the compaction: fill is unknown, so no warning
+ }
+ const msg = row.message as { usage?: Record<string, unknown>; model?: unknown; role?: unknown } | undefined;
+ if (!usage && row.type === 'assistant' && msg?.usage && typeof msg.usage === 'object') {
+ const n = (k: string) => (typeof msg.usage![k] === 'number' ? msg.usage![k] as number : 0);
+ const used = n('input_tokens') + n('cache_creation_input_tokens') + n('cache_read_input_tokens');
+ if (used > 0) usage = { used, model: typeof msg.model === 'string' ? msg.model : null };
+ }
+ }
+ return usage ? { usedTokens: usage.used, model: usage.model, boundary } : null;
+}
+
+/** Reads the transcript tail and scans it; null when unreadable or unmeasured. */
+export function readTranscriptPressure(path: string): TranscriptPressure | null {
+ let fd: number | null = null;
+ try {
+ fd = openSync(path, 'r');
+ const size = fstatSync(fd).size;
+ const len = Math.min(size, TRANSCRIPT_TAIL_BYTES);
+ const buf = Buffer.alloc(len);
+ readSync(fd, buf, 0, len, size - len);
+ const text = buf.toString('utf8');
+ // Drop the partial first line of a mid-file window.
+ return scanTranscriptPressure(size > len ? text.slice(text.indexOf('\n') + 1) : text);
+ } catch {
+ return null;
+ } finally {
+ if (fd !== null) try { closeSync(fd); } catch { /* noop */ }
+ }
+}
+
+/**
+ * Context window for the session: explicit config wins; then a 1M marker on
+ * the model id or the configured model; then an observed fill above the
+ * default window (only a large window could hold it); else the default.
+ */
+export function resolveContextWindow(opts: { configured: number | null; model: string | null; configuredModel?: string | null; maxSeen: number }): number {
+ if (opts.configured) return opts.configured;
+ const marker = /\[1m\]|-1m\b|1m-context/i;
+ if ((opts.model && marker.test(opts.model)) || (opts.configuredModel && marker.test(opts.configuredModel))) return PRESSURE_LARGE_WINDOW;
+ return opts.maxSeen > PRESSURE_DEFAULT_WINDOW ? PRESSURE_LARGE_WINDOW : PRESSURE_DEFAULT_WINDOW;
+}
+
+export function pressureNotice(percent: number): string {
+ return `[gbrain] This conversation's context is about ${percent}% full and will be compacted soon; details that exist only in this conversation will be lost. ` +
+ 'Before continuing, call remember once with items: [...] (up to 20 facts, each with a short provenance) for decisions, preferences, commitments and open threads worth keeping. ' +
+ '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 }
+
+function stateFile(dir: string, sessionKey: string): string {
+ return join(dir, `${sessionKey.replace(/[^A-Za-z0-9._-]/g, '-').slice(0, 120) || 'session'}.json`);
+}
+
+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;
+ } catch { return null; }
+}
+
+function writeState(path: string, dir: string, state: PressureState): void {
+ try {
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });
+ const tmp = `${path}.${process.pid}.tmp`;
+ writeFileSync(tmp, JSON.stringify(state), { mode: 0o600 });
+ renameSync(tmp, path);
+ } catch { /* best-effort: a lost state file can only re-fire one notice */ }
+}
+
+export interface PressureDecision { notice: string | null; percent: number; window: number; reason?: string }
+
+/**
+ * Decides whether this turn carries the notice. `segmentHint` is the newest
+ * compact boundary seen (null = none in view: the stored segment continues).
+ * Records state only when it changes. Pure apart from the state file.
+ */
+export function decidePressure(input: {
+ gate: PressureGate | null | undefined;
+ sessionKey: string;
+ stateDir: string;
+ usedTokens: number;
+ model: string | null;
+ boundary: string | null;
+ configuredModel?: string | null;
+ /** Kept for the OpenClaw lane, which knows its window exactly. */
+ windowOverride?: number;
+}): PressureDecision {
+ const gate = input.gate;
+ if (!gate) return { notice: null, percent: 0, window: 0, reason: 'no_gate' };
+ if (!gate.enabled) return { notice: null, percent: 0, window: 0, reason: 'disabled' };
+ if (!gate.remember_callable) return { notice: null, percent: 0, window: 0, reason: 'remember_unavailable' };
+ const path = stateFile(input.stateDir, input.sessionKey);
+ const prev = readState(path);
+ const segment = input.boundary ?? prev?.segment ?? 'start';
+ const sameSegment = prev?.segment === segment;
+ const maxSeen = Math.max(input.usedTokens, prev?.maxSeen ?? 0);
+ const window = input.windowOverride ?? resolveContextWindow({ configured: gate.context_window, model: input.model, configuredModel: input.configuredModel, maxSeen });
+ 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);
+ if (warned) return { notice: null, percent, window, reason: 'already_warned' };
+ return fire ? { notice: pressureNotice(percent), percent, window } : { notice: null, percent, window, reason: 'below_threshold' };
+}
+
+/** Claude Code user-prompt lane: measure the transcript and decide the notice for this turn. */
+export function claudeCodePressure(gate: PressureGate | null | undefined, transcriptPath: string, sessionId: string | undefined, stateDir?: string): PressureDecision | null {
+ if (!gate?.enabled || !gate.remember_callable || process.env.GBRAIN_PRESSURE === '0') return null;
+ const measured = readTranscriptPressure(transcriptPath);
+ if (!measured) return null;
+ return decidePressure({
+ gate, sessionKey: `claude-${sessionId ?? 'nosession'}`, stateDir: stateDir ?? join(resolveGbrainHome(), 'hooks', 'pressure'),
+ usedTokens: measured.usedTokens, model: measured.model, boundary: measured.boundary,
+ configuredModel: process.env.ANTHROPIC_MODEL ?? null,
+ });
+}
diff --git a/src/core/context/session-start-output.ts b/src/core/context/session-start-output.ts
new file mode 100644
index 0000000000..46526facda
--- /dev/null
+++ b/src/core/context/session-start-output.ts
@@ -0,0 +1,33 @@
+/**
+ * Claude Code session-start stdout composition: always-loaded core memory
+ * first, then the digest/pack parts, all under the harness hook-output cap
+ * (overflow is diverted to a file by the harness, never injected).
+ */
+import { CLAUDE_HOOK_OUTPUT_CAP_CHARS } from '../bootstrap/host-specs.ts';
+
+/** Marker printed when lower-priority parts were trimmed to keep core whole under the cap. */
+export const SESSION_START_TRIM_MARKER = '[gbrain: digest/pack trimmed to fit core memory]';
+
+/**
+ * Session-start stdout: core first, then the other parts, all under
+ * CLAUDE_HOOK_OUTPUT_CAP_CHARS (overflow would be diverted, never injected).
+ * Trailing parts are dropped whole, then the last kept part is cut, before
+ * core is ever touched; core itself is bounded by memory.core.max_chars.
+ */
+export function composeSessionStartOutput(coreText: string, parts: string[]): string {
+ const cap = CLAUDE_HOOK_OUTPUT_CAP_CHARS - 64;
+ const head = coreText ? [coreText] : [];
+ const kept: string[] = [];
+ let trimmed = false;
+ const size = (xs: string[]) => xs.join('\n\n').length;
+ for (const part of parts) {
+ if (size([...head, ...kept, part, SESSION_START_TRIM_MARKER]) <= cap) { kept.push(part); continue; }
+ const room = cap - size([...head, ...kept, SESSION_START_TRIM_MARKER]) - 4;
+ if (room > 200) kept.push(part.slice(0, room));
+ trimmed = true;
+ break;
+ }
+ const all = [...head, ...kept, ...(trimmed ? [SESSION_START_TRIM_MARKER] : [])];
+ const text = all.join('\n\n');
+ return text.length <= CLAUDE_HOOK_OUTPUT_CAP_CHARS ? text : text.slice(0, CLAUDE_HOOK_OUTPUT_CAP_CHARS);
+}
diff --git a/src/core/context/turn-context.ts b/src/core/context/turn-context.ts
index c227cd719f..e8a97db0e3 100644
--- a/src/core/context/turn-context.ts
+++ b/src/core/context/turn-context.ts
@@ -101,6 +101,8 @@ export interface TurnContextResult {
* requests; absent from older serves and from every other trigger.
*/
core?: { text: string; revision: string; chars_used: number; chars_limit: number; truncated: boolean };
+ /** Context-pressure gate (pressure.ts), serve-sourced; an older serve omits it and no notice fires. */
+ pressure?: import('./pressure.ts').PressureGate;
/** Reflex pointers that survived suppression + budget. */
pointers: ReflexPointer[];
/**
diff --git a/src/mcp/context-pack-handler.ts b/src/mcp/context-pack-handler.ts
index 786473aae4..503520774b 100644
--- a/src/mcp/context-pack-handler.ts
+++ b/src/mcp/context-pack-handler.ts
@@ -12,6 +12,7 @@
* stateless pack, never an error.
*/
+import { readPressureGate } from '../core/context/pressure.ts';
import { existsSync } from 'node:fs';
import { isAbsolute, join } from 'node:path';
import type { BrainEngine } from '../core/engine.ts';
@@ -75,7 +76,9 @@ export function makeContextPackIpcHandler(
const sessionSource = typeof req.sourceId === 'string' && req.sourceId.trim() ? req.sourceId : defaultSource;
if (req.coreOnly === true) {
const core = await coreForSession(engine, sessionSource);
- return { text: '', pointers: [], factsCount: 0, mode: 'pack' as const, ...(core ? { core } : {}) };
+ // The OpenClaw lane reads the pressure gate on the same fetch; it checks remember's availability itself.
+ const pressure = await readPressureGate(engine, true).catch(() => null);
+ return { text: '', pointers: [], factsCount: 0, mode: 'pack' as const, ...(core ? { core } : {}), ...(pressure ? { pressure } : {}) };
}
if (req.manifestOnly === true) {
const links = sessionId
diff --git a/src/mcp/resolve-ipc-binding.ts b/src/mcp/resolve-ipc-binding.ts
index c51e03de5c..f0aeef432a 100644
--- a/src/mcp/resolve-ipc-binding.ts
+++ b/src/mcp/resolve-ipc-binding.ts
@@ -18,6 +18,7 @@
*
* Best-effort by contract: failure to bind never blocks the serve.
*/
+import { readPressureGate } from '../core/context/pressure.ts';
import type { Server } from 'node:net';
import type { BrainEngine } from '../core/engine.ts';
import { loadConfig } from '../core/config.ts';
@@ -87,6 +88,7 @@ export async function bindResolveIpcForServe(
engine: BrainEngine,
defaultSource: string,
persistenceProvider?: PersistenceIpcProvider,
+ opts: { rememberCallable?: boolean } = {},
): Promise<ResolveIpcBinding> {
let persistence: PersistenceIpcBinding | null = null;
try {
@@ -193,8 +195,8 @@ export async function bindResolveIpcForServe(
// [CX2-10] Always assembles against the server's OWN registered
// source — cross-source requests are rejected in the IPC layer via
// boundSourceId below, and the handler never honors a caller source.
- turn_context: (req) =>
- assembleTurnContext(engine, {
+ turn_context: async (req) => ({
+ ...await assembleTurnContext(engine, {
sourceId: defaultSource,
window: req.window ?? [],
priorContextText: req.priorContextText,
@@ -204,6 +206,9 @@ export async function bindResolveIpcForServe(
// the resolve handler above (adversarial F3).
lexicalArms: lexicalArmsEnabled(loadConfig()),
}),
+ // Context-pressure gate for the harness hook (pressure.ts); a surface without remember never warns.
+ pressure: await readPressureGate(engine, opts.rememberCallable ?? true),
+ }),
// v0.45.7 ambient recall: boundary context pack. Extracted to
// context-pack-handler.ts (directly testable against a real engine);
// the runtime owns entity merge, banking, the since-cursor, and the
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index 14fc75f87d..63ae0b0057 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -420,7 +420,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
bootPhase('persistence_consumer');
const persistence = await createPersistenceIpcProvider(engine, residentPersistenceConfig(config) ?? { engine: engine.kind });
bootPhase('resolve_ipc_bind');
- ipcBinding = await bindResolveIpcForServe(engine, ipcSourceId, persistence);
+ ipcBinding = await bindResolveIpcForServe(engine, ipcSourceId, persistence, { rememberCallable: !allowedOps || allowedOps.has('remember') });
// v0.45.7 ambient recall: age out stale session cursors once per serve boot
// (7-day TTL, indexed DELETE). Best-effort — GC failure never blocks serve.
diff --git a/test/context-pressure.test.ts b/test/context-pressure.test.ts
new file mode 100644
index 0000000000..78372ec634
--- /dev/null
+++ b/test/context-pressure.test.ts
@@ -0,0 +1,84 @@
+import { afterEach, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import {
+ decidePressure, readTranscriptPressure, resolveContextWindow, scanTranscriptPressure, validatePressureConfigValue,
+ type PressureGate,
+} from '../src/core/context/pressure.ts';
+
+const gate: PressureGate = { enabled: true, warn_ratio: 0.8, context_window: null, remember_callable: true };
+const dirs: string[] = [];
+const tmp = () => { const d = mkdtempSync(join(tmpdir(), 'gbrain-pressure-')); dirs.push(d); return d; };
+afterEach(() => { for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }); });
+
+const assistant = (used: number, model = 'claude-sonnet-5-5') => JSON.stringify({
+ type: 'assistant', message: { role: 'assistant', model, usage: { input_tokens: used - 1000, cache_creation_input_tokens: 400, cache_read_input_tokens: 600, output_tokens: 50 } },
+});
+const boundary = (uuid: string) => JSON.stringify({ type: 'system', subtype: 'compact_boundary', uuid });
+
+describe('transcript scan', () => {
+ test('newest assistant usage sums input, cache creation and cache read', () => {
+ const r = scanTranscriptPressure([assistant(10_000), assistant(170_000)].join('\n'));
+ expect(r).toEqual({ usedTokens: 170_000, model: 'claude-sonnet-5-5', boundary: null });
+ });
+ test('the newest compact boundary keys the segment', () => {
+ const r = scanTranscriptPressure([assistant(190_000), boundary('b-1'), assistant(30_000)].join('\n'));
+ expect(r?.boundary).toBe('b-1');
+ expect(r?.usedTokens).toBe(30_000);
+ });
+ test('nothing measured since the last compaction means no reading', () => {
+ expect(scanTranscriptPressure([assistant(190_000), boundary('b-1')].join('\n'))).toBeNull();
+ });
+ test('reads only a bounded tail of a large file', () => {
+ const dir = tmp();
+ const path = join(dir, 't.jsonl');
+ writeFileSync(path, `${'x'.repeat(600 * 1024)}\n${assistant(120_000)}\n`);
+ expect(readTranscriptPressure(path)?.usedTokens).toBe(120_000);
+ });
+});
+
+describe('window and decision', () => {
+ test('window: config, then 1M marker, then observed fill, else 200k', () => {
+ expect(resolveContextWindow({ configured: 32_000, model: null, maxSeen: 0 })).toBe(32_000);
+ expect(resolveContextWindow({ configured: null, model: 'claude-sonnet-5-5[1m]', maxSeen: 0 })).toBe(1_000_000);
+ expect(resolveContextWindow({ configured: null, model: null, maxSeen: 250_000 })).toBe(1_000_000);
+ expect(resolveContextWindow({ configured: null, model: null, maxSeen: 50_000 })).toBe(200_000);
+ });
+
+ test('fires once per segment at the threshold, again after a new compaction', () => {
+ const stateDir = tmp();
+ const base = { gate, sessionKey: 's1', stateDir, model: null };
+ expect(decidePressure({ ...base, usedTokens: 100_000, boundary: null }).notice).toBeNull();
+ const first = decidePressure({ ...base, usedTokens: 165_000, boundary: null });
+ expect(first.notice).toContain('remember');
+ expect(first.notice).toContain('items');
+ expect(first.percent).toBe(83);
+ expect(decidePressure({ ...base, usedTokens: 175_000, boundary: null }).reason).toBe('already_warned');
+ expect(decidePressure({ ...base, usedTokens: 20_000, boundary: 'b-2' }).notice).toBeNull();
+ expect(decidePressure({ ...base, usedTokens: 170_000, boundary: 'b-2' }).notice).not.toBeNull();
+ });
+
+ test('a large observed fill keeps the 1M window for the session', () => {
+ const stateDir = tmp();
+ const base = { gate, sessionKey: 's2', stateDir, model: null, boundary: null };
+ expect(decidePressure({ ...base, usedTokens: 260_000 }).window).toBe(1_000_000);
+ expect(decidePressure({ ...base, usedTokens: 180_000 }).notice).toBeNull();
+ });
+
+ test('disabled, missing gate, or remember not callable never warn', () => {
+ const stateDir = tmp();
+ const base = { sessionKey: 's3', stateDir, model: null, boundary: null, usedTokens: 190_000 };
+ expect(decidePressure({ ...base, gate: { ...gate, enabled: false } }).reason).toBe('disabled');
+ expect(decidePressure({ ...base, gate: null }).reason).toBe('no_gate');
+ expect(decidePressure({ ...base, gate: { ...gate, remember_callable: false } }).reason).toBe('remember_unavailable');
+ });
+
+ test('config validation bounds', () => {
+ expect(validatePressureConfigValue('memory.pressure.warn_ratio', '0.8')).toBeNull();
+ expect(validatePressureConfigValue('memory.pressure.warn_ratio', '1.2')).toContain('0.5 to 0.95');
+ expect(validatePressureConfigValue('memory.pressure.context_window', '32000')).toBeNull();
+ expect(validatePressureConfigValue('memory.pressure.context_window', 'big')).not.toBeNull();
+ expect(validatePressureConfigValue('memory.pressure.enabled', 'maybe')).not.toBeNull();
+ });
+});