Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
core memory delivery: session-start, context_pack, OpenClaw assemble; remember items[] batch; core-memory guide
garrytan1aa7e6a875a5
diff --git a/docs/guides/core-memory.md b/docs/guides/core-memory.mdnew file mode 100644index 0000000000..29e8ce7ce3--- /dev/null+++ b/docs/guides/core-memory.md@@ -0,0 +1,135 @@+# Core memory: always-loaded pages++Core memory is a small set of pages that every session sees without asking:+who the user is, how they like to work, the projects in flight. The agent does+not have to search for them, and they survive context compaction because they+are re-delivered at the start of each session.++Everything else in the brain stays on demand (search, `query`, `recall`,+per-turn context). Core is for the few facts an agent should never have to+look up.++## What makes a page core++A page is core when its frontmatter says so:++```yaml+---+title: Working preferences+always_load: true+core_priority: 10 # optional; lower renders first (default 100)+---+```++Only `always_load: true` counts; any other value means not core. Pages render+in `core_priority` order, then by source and slug. Each page renders as a+heading plus its compiled truth (the part above the timeline); timeline+entries never enter core.++A session sees the `default` source's core first, then the core of its own+source when that is a different source. Private pages and pages in sources a+caller cannot read never render. Withdrawn facts (`forget`) are removed from+the rendered text.++The easiest way to manage the set is the CLI:++```bash+gbrain core list # core pages, priority order, rendered size+gbrain core status --json # usage against the budget, largest pages+gbrain core add people/alice-example --priority 10+gbrain core remove people/alice-example+gbrain core show # the exact block a session receives+gbrain core suggest # read-only candidates; --apply marks them+gbrain core init # creates a starter profile page and marks it core+```++## Budget++Core enters every session's prompt in every connected harness, so its total+rendered size is capped brain-wide by `memory.core.max_chars` (default 4,000+characters; allowed 500 to 6,000), with at most 50 core pages. The count uses+the final rendered block, headings included.++A write that would grow core past the budget is refused with+`core_budget_exceeded`. The message gives the projected size, how far over it+is, and the largest core pages the caller can see. Writes that shrink core+always pass, so an over-budget brain can always be brought back under.++What to do when a write is refused: move the detail into a linked non-core+page and keep a one-line pointer in the core page, or ask the user to raise+the budget (`gbrain config set memory.core.max_chars 6000`). `gbrain core+status --json` shows where the characters go.++The owner's own git edits are never blocked: a sync that pushes core over+budget still succeeds, and `gbrain doctor` reports the overage until it is+fixed. Every other write, including local CLI writes, is held to the budget.++## Owner only++Only the brain owner (a local CLI or a git edit on the brain host) decides+which pages are core:++- A remote caller (MCP, HTTP) cannot add or remove `always_load` or change+ `core_priority`; that write is refused with `core_mark_owner_only`. A remote+ rewrite that leaves those keys out keeps the stored values, so ordinary edits+ never drop a page out of core by accident.+- A remote caller cannot delete a core page (`core_delete_owner_only`).++Both refusals mean the user has to act. Relay the command the message names+(for example `gbrain core add --source default notes/x` or `gbrain core remove+people/alice-example`) and let the user run it.++## Remote edits++Because core text reaches every session, edits to core pages by remote+callers follow `memory.core.remote_edit`:++| Value | Behavior |+|---|---|+| `notify` (default) | The edit is saved, and the next sessions show a short notice naming the page and revision until the owner runs `gbrain core ack <slug> --revision <token>`. `gbrain core diff <slug>` shows what changed. |+| `allow` | The edit is saved with no notice. |+| `refuse` | The edit is refused with `core_remote_edit_refused`. Make the edit on the brain host, or ask the user to switch the setting. |++## Where core is delivered++| Harness | How core arrives |+|---|---|+| Claude Code | The session-start hook prints the core block first, then the usual digest. The heartbeat records `core_chars` and `core_revision`. `GBRAIN_CORE=0` suppresses core for one session. |+| OpenClaw | The context engine adds the core block on every turn from a read-only fetch, refreshed at most once a minute. |+| Any MCP client | `context_pack` returns a `core` field and prepends the block to `text`; call it with no `entities` to get core alone. Core counts inside `budget_tokens`. |+| Static instruction files | `gbrain compile-context --include-core` writes core into the compiled file. Targets include `codex-global` (`$CODEX_HOME/AGENTS.md`) and `hermes` (`.hermes.md`, kept out of git). Core is never written into a git-tracked file; `--remove-core` recompiles without it. |++## Saving before compaction++Long sessions get compacted, and whatever was only in the conversation is lost.+Two pieces cover that:++- `remember` takes `items`: up to 20 facts in one call, each with the usual+ fields (`fact`, optional `entity`, `kind`, `ttl`, `visibility`,+ `provenance`). Every item is validated before anything is written; each item+ 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+ callable, and follows the capture policy (TTL, visibility, exclusions).+ Turn it off with `gbrain config set memory.pressure.enabled false`.++## Configuration++| Key | Default | Meaning |+|---|---|---|+| `memory.core.enabled` | `true` | Deliver core in sessions. |+| `memory.core.max_chars` | `4000` | Brain-wide rendered budget, 500 to 6,000. |+| `memory.core.remote_edit` | `notify` | `allow`, `notify` or `refuse` for remote edits to core pages. |+| `memory.pressure.enabled` | `true` | The save-before-compaction notice. |+| `memory.pressure.warn_ratio` | `0.80` | Context fill ratio that triggers the notice. |+| `memory.pressure.context_window` | unset | Override the detected context window, in tokens. |++## Troubleshooting++`gbrain doctor` runs a `core_memory` check: core over budget, out-of-range+settings, core pages that are deleted or withheld, compiled files carrying an+old core revision, and writers that predate the core guard. Each finding names+its fix.diff --git a/src/commands/hook.ts b/src/commands/hook.tsindex 5c40da8879..acbe03e2fb 100644--- a/src/commands/hook.ts+++ b/src/commands/hook.ts@@ -478,6 +478,8 @@ 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).const deferredRecords: Array<() => void> = [];@@ -556,6 +558,9 @@ 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';}}}@@ -570,7 +575,9 @@ 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).- const text = out.filter(Boolean).join('\n\n');+ // Always-loaded core prints first; the digest/pack are trimmed (never+ // core) so the whole stdout stays under the harness cap.+ const text = composeSessionStartOutput(coreBox.core?.text ?? '', out.filter(Boolean));if (text) {write(io, text + '\n');for (const record of deferredRecords) {@@ -589,12 +596,40 @@ async function hookSessionStart(io: HookIo): Promise<number> {ts: new Date().toISOString(),event: 'session-start',outcome,- ...(reason ? { reason } : {}),+ ...(reason ? { reason } : coreBox.reason ? { reason: coreBox.reason } : {}),duration_ms: Date.now() - t0,+ ...(coreBox.core ? { core_chars: coreBox.core.chars_used, core_revision: coreBox.core.revision } : {}),});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 everydiff --git a/src/core/context-engine.ts b/src/core/context-engine.tsindex 08b81b648e..143d520ead 100644--- a/src/core/context-engine.ts+++ b/src/core/context-engine.ts@@ -902,6 +902,56 @@ 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;+ let coreMemo: { at: number; text: string } | null = null;+ async function fetchCore(sessionId: string | null): Promise<string | null> {+ const work = (async (): Promise<string | 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?.core) return null;+ return res.block.core.text;+ }+ 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');+ return (await loadCoreBlock(pg, { sessionSourceId: sourceId, excludePrivate: true })).text;+ } 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 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;+ }+/** assemble()-side: memo-first, hash-keyed polls, settle-and-render. */async function getCheckpointBlock(sessionId: string): Promise<string | null> {let memo = checkpointMemo.get(sessionId);@@ -1234,6 +1284,10 @@ export function createGBrainContextEngine(ctx: {// 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.+ let coreBlock: string | null = null;+ try { coreBlock = await getCoreBlock(sanitizeEngineSessionId(sessionId ?? sessionKey ?? null)); } catch { coreBlock = null; }+ if (coreBlock) parts.push(coreBlock);if (checkpointBlock) parts.push(checkpointBlock);if (memoryAddition) parts.push(memoryAddition);if (reflexAddition) parts.push(reflexAddition);diff --git a/src/core/context/hook-heartbeat.ts b/src/core/context/hook-heartbeat.tsindex ec04efbbe7..2944ee49d5 100644--- a/src/core/context/hook-heartbeat.ts+++ b/src/core/context/hook-heartbeat.ts@@ -39,6 +39,9 @@ export interface HookHeartbeatEntry {* slugs/fact text [S3#7].*/segment?: string;+ /** Always-loaded core: chars and revision delivered by session-start (counts/digests only). */+ core_chars?: number;+ core_revision?: string;/** 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 thediff --git a/src/core/context/resolve-ipc.ts b/src/core/context/resolve-ipc.tsindex 7e39d722ca..99c85a5a73 100644--- a/src/core/context/resolve-ipc.ts+++ b/src/core/context/resolve-ipc.ts@@ -219,6 +219,12 @@ export interface ContextPackRequest {* OpenClaw assemble poll.*/manifestOnly?: boolean;+ /**+ * Always-loaded core (additive, read-only): return only the core block for+ * the session source — no assembly, no cursor advance, no banking. Used by+ * the OpenClaw assemble lane. An older serve ignores it and assembles.+ */+ coreOnly?: boolean;}export type IpcRequest =diff --git a/src/core/context/turn-context.ts b/src/core/context/turn-context.tsindex 8dfef2b9a9..c227cd719f 100644--- a/src/core/context/turn-context.ts+++ b/src/core/context/turn-context.ts@@ -96,6 +96,11 @@ export interface DeltaPage {export interface TurnContextResult {/** Rendered block ('' when there is nothing to inject). */text: string;+ /**+ * Always-loaded core block (core-memory.ts) on session-start and coreOnly+ * requests; absent from older serves and from every other trigger.+ */+ core?: { text: string; revision: string; chars_used: number; chars_limit: number; truncated: boolean };/** Reflex pointers that survived suppression + budget. */pointers: ReflexPointer[];/**diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.tsindex 397f4a794e..bf78775914 100644--- a/src/core/ops/facts.ts+++ b/src/core/ops/facts.ts@@ -612,9 +612,9 @@ const context_pack: Operation = {mutating: false,idempotent: true,outputRedaction: { retrieval: { localVerbatim: ['facts'] } },- description: 'MEMORY VERB (v1): budget-packed cards, open threads and hot facts for up to 8 entities, zero LLM. Call at session start and after compaction.',+ description: 'MEMORY VERB (v1): the always-loaded core block plus budget-packed cards, open threads and hot facts for up to 8 entities, zero LLM. Call at session start and after compaction; omit entities for core only.',params: {- entities: { type: 'string', required: true, description: 'Comma-separated names or slugs (max 8).' },+ entities: { type: 'string', description: 'Comma-separated names or slugs (max 8); omit for the core block only.' },budget_tokens: { type: 'number', description: 'Token budget; cards pack first.' },since: { type: 'string', description: 'Only open-thread events after this ISO time.' },session_id: { type: 'string', description: 'Opaque session id.' },@@ -649,14 +649,24 @@ const context_pack: Operation = {typeof p.budget_tokens === 'number' && Number.isFinite(p.budget_tokens) && p.budget_tokens > 0? Math.floor(p.budget_tokens): null;- const res = await assembleContextPack(ctx.engine, {- sourceId,- entities,- since,- sessionId: typeof p.session_id === 'string' ? p.session_id : undefined,- includePrivate,- maxEntities: PACK_DEFAULT_MAX_ENTITIES,- });+ const res = entities.length === 0+ ? { cards: [], facts: [], text: '', pointers: [], factsCount: 0 } as unknown as Awaited<ReturnType<typeof assembleContextPack>>+ : await assembleContextPack(ctx.engine, {+ sourceId,+ entities,+ since,+ sessionId: typeof p.session_id === 'string' ? p.session_id : undefined,+ includePrivate,+ maxEntities: PACK_DEFAULT_MAX_ENTITIES,+ });+ // Always-loaded core tier (core-memory.ts): owner-designated pages of+ // `default` plus this source, inside the caller's grant; it packs first.+ const { loadCoreBlock } = await import('../core-memory.ts');+ const allowed = ctx.auth?.allowedSources?.length ? ctx.auth.allowedSources : null;+ const core = await loadCoreBlock(ctx.engine, { sessionSourceId: sourceId, allowedSources: allowed, excludePrivate: !includePrivate })+ .catch(() => null);+ const coreText = core?.text ?? '';+ const coreTokens = estimateTokens(coreText);// Pack, price and render the redacted presentation sets (one echo// dictionary); local callers get the delivered facts back raw below.@@ -674,7 +684,7 @@ const context_pack: Operation = {if (budgetTokens !== null) {// #4761: reserve the envelope + headers, then price each card as its// rendered line plus its rendered (since-filtered) thread lines.- const itemBudget = budgetTokens - packHeaderCost();+ const itemBudget = budgetTokens - packHeaderCost() - coreTokens;const cardCost = (c: (typeof cards)[number]) =>lineCost(renderCardLine(c)) + threadsOf(c).reduce((n, t) => n + lineCost(renderThreadLine(t)), 0);const cardPack = itemBudget > 0 ? packToBudget(cards, cardCost, itemBudget) : dropAll(cards);@@ -689,7 +699,8 @@ const context_pack: Operation = {// `text` is what harnesses inject, so it must honor the same budget the// structured arrays report — the assembler's pre-budget rendering would// overrun the declared budget_tokens. budget_used reports that text.- const text = budgetTokens !== null ? renderPack(cards, open_threads, facts) : res.text;+ const packText = entities.length === 0 ? '' : budgetTokens !== null ? renderPack(cards, open_threads, facts) : res.text;+ const text = [coreText, packText].filter(Boolean).join('\n\n');const budgetUsed = budgetTokens !== null ? estimateTokens(text) : undefined;return {@@ -715,6 +726,8 @@ const context_pack: Operation = {confidence: f.confidence,})),text,+ ...(core && core.enabled ? { core: { text: core.text, chars_used: core.chars_used, chars_limit: core.chars_limit, pages: core.pages,+ truncated: core.truncated, revision: core.revision } } : {}),...(res.degradedReason ? { degraded_reason: res.degradedReason } : {}),...(budgetTokens !== null? { budget_tokens: budgetTokens, budget_used: budgetUsed, dropped_count: droppedCount }diff --git a/src/core/remember-batch.ts b/src/core/remember-batch.tsnew file mode 100644index 0000000000..ec06f1f3b6--- /dev/null+++ b/src/core/remember-batch.ts@@ -0,0 +1,92 @@+/**+ * `remember` with `items[]`: save several facts in one call (the+ * pre-compaction "save what matters" path). Additive to the frozen+ * MEMORY_VERBS v1 `remember` contract: a call without `items` is unchanged.+ *+ * Semantics:+ * - every item is validated (same rules as a single remember) before any is+ * admitted; one invalid item refuses the whole call and writes nothing;+ * - each item is then admitted as its own write request with a+ * deterministic child request_id derived from the caller's request_id and+ * the item index, so replaying the same request_id replays each child+ * (committed children return their receipt, nothing is written twice);+ * - publication is per item: the response reports each item's status and+ * `partial: true` when some failed. Replaying the same request_id returns+ * the same per-item outcomes; failed items are resubmitted in a new call+ * with a new request_id.+ */+import { createHash, randomUUID } from 'node:crypto';+import type { OperationContext } from './operations.ts';+import { OperationError } from './ops/contract.ts';++export const REMEMBER_BATCH_MAX = 20;+const ITEM_KEYS = new Set(['fact', 'provenance', 'entity', 'infer_entity', 'kind', 'ttl', 'visibility']);++/** Deterministic UUID for child `index` of a batch request (stable across replays). */+export function childRequestId(requestId: string, index: number): string {+ const h = createHash('sha256').update(`${requestId}\u0000remember-item\u0000${index}`).digest('hex');+ // RFC 4122 layout with version 5 / variant bits so it reads as a UUID everywhere.+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-5${h.slice(13, 16)}-${((parseInt(h.slice(16, 18), 16) & 0x3f) | 0x80).toString(16)}${h.slice(18, 20)}-${h.slice(20, 32)}`;+}++type Handler = (ctx: OperationContext, p: Record<string, unknown>) => Promise<unknown>;++export interface BatchItemResult {+ index: number;+ status: string;+ request_id: string;+ [key: string]: unknown;+}++/** Runs a remember batch through the single-item handler. */+export async function runRememberBatch(ctx: OperationContext, p: Record<string, unknown>, single: Handler,+ verbError: (code: string, message: string, suggestion: string) => Error): Promise<Record<string, unknown>> {+ const items = p.items;+ if (!Array.isArray(items) || items.length < 1 || items.length > REMEMBER_BATCH_MAX) {+ throw verbError('invalid_params', `items must be an array of 1 to ${REMEMBER_BATCH_MAX} facts.`,+ 'Pass items: [{ "fact": "...", "entity": "..." }, ...] with provenance on each item or once at the top level.');+ }+ if (typeof p.fact === 'string' && p.fact.trim()) {+ throw verbError('invalid_params', 'Pass either fact or items, not both.', 'Move the single fact into items, or drop items.');+ }+ const shared: Record<string, unknown> = {};+ for (const key of ['provenance', 'source_id', 'kind', 'ttl', 'visibility', 'infer_entity']) if (p[key] !== undefined) shared[key] = p[key];+ const normalized = items.map((raw, index) => {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {+ throw verbError('invalid_params', `items[${index}] must be an object.`, 'Each item is { "fact": "...", optional entity, kind, ttl, visibility, provenance }.');+ }+ const extra = Object.keys(raw).filter(k => !ITEM_KEYS.has(k));+ if (extra.length) throw verbError('invalid_params', `items[${index}] has unknown field(s): ${extra.join(', ')}.`, `Allowed item fields: ${[...ITEM_KEYS].join(', ')}.`);+ return { ...shared, ...(raw as Record<string, unknown>) };+ });+ // All-or-none validation before any admission.+ for (const [index, item] of normalized.entries()) {+ try { await single({ ...ctx, dryRun: true }, item); } catch (e) {+ if (e instanceof OperationError) e.message = `items[${index}]: ${e.message} Nothing was saved; fix that item and resend the whole batch.`;+ throw e;+ }+ }+ if (ctx.dryRun) return { dry_run: true, action: 'remember', items: normalized.length, protocol_version: 1 };+ const requestId = typeof p.request_id === 'string' && p.request_id ? p.request_id : randomUUID();+ const results: BatchItemResult[] = [];+ for (const [index, item] of normalized.entries()) {+ const child = childRequestId(requestId, index);+ try {+ const out = await single(ctx, { ...item, request_id: child }) as Record<string, unknown>;+ results.push({ ...out, index, request_id: child, status: String(out?.status ?? 'saved') });+ } catch (e) {+ if (!(e instanceof OperationError)) throw e;+ results.push({ index, request_id: child, status: 'failed', error: { code: e.code, message: e.message, ...(e.detail ? { detail: e.detail } : {}) } });+ }+ }+ const failed = results.filter(r => r.status === 'failed').length;+ return {+ protocol_version: 1,+ request_id: requestId,+ items: results,+ saved: results.length - failed,+ failed,+ partial: failed > 0 && failed < results.length,+ ...(failed > 0 ? { next: 'Fix each failed item as its error says, then send only the failed items in a new remember call with a new request_id; the saved items are already stored.' } : {}),+ };+}diff --git a/src/core/verbs.ts b/src/core/verbs.tsindex 1cd8c68b92..ecdbcfb316 100644--- a/src/core/verbs.ts+++ b/src/core/verbs.ts@@ -62,10 +62,23 @@ const remember: Operation = {name: 'remember',idempotent: true,outputRedaction: 'no_stored_text',- description: 'MEMORY VERB (v1): save one fact; provenance required. Set `entity` when the fact has a subject, or entity-scoped recall misses it. Branch on `status` (inserted|duplicate|superseded). write_pending carries a receipt: poll get_write_request.',+ description: 'MEMORY VERB (v1): save one fact (or up to 20 with items); provenance required. Set `entity` when the fact has a subject, or entity-scoped recall misses it. Branch on `status` (inserted|duplicate|superseded). write_pending carries a receipt: poll get_write_request.',params: {...PAGE_MUTATION_PARAMS,- fact: { type: 'string', description: 'One claim.', required: true },+ fact: { type: 'string', description: 'One claim (or use items).' },+ items: {+ type: 'array',+ description: 'Save up to 20 facts in one call (e.g. before context compaction); each item takes fact plus optional entity, kind, ttl, visibility, provenance (defaults to the top-level provenance). Use instead of fact.',+ items: { type: 'object', properties: {+ fact: { type: 'string', required: true, description: 'One claim.' },+ entity: { type: 'string', description: 'Who or what it is about.' },+ kind: { type: 'string', enum: ['event', 'preference', 'commitment', 'belief', 'fact'], description: 'Default fact.' },+ ttl: { type: 'string', description: '"30d", "12h" or ISO time.' },+ visibility: { type: 'string', enum: ['world', 'private'], description: 'Default world.' },+ provenance: { type: 'string', description: 'Overrides the top-level provenance.' },+ infer_entity: { type: 'boolean', description: 'Default true.' },+ } },+ },provenance: {type: 'string',required: true,@@ -99,6 +112,10 @@ const remember: Operation = {annotations: { title: 'remember (memory write)', idempotentHint: true },handler: async (ctx, p) => {const { verbError, parseTtlParam } = await import('./operations.ts');+ if (p.items !== undefined) {+ const { runRememberBatch } = await import('./remember-batch.ts');+ return runRememberBatch(ctx, p, remember.handler, (code, message, suggestion) => verbError(code as never, message, suggestion));+ }const fact = typeof p.fact === 'string' ? p.fact.trim() : '';if (!fact) {throw verbError(diff --git a/src/mcp/context-pack-handler.ts b/src/mcp/context-pack-handler.tsindex 0b0a81f074..786473aae4 100644--- a/src/mcp/context-pack-handler.ts+++ b/src/mcp/context-pack-handler.ts@@ -26,6 +26,8 @@ import {} from '../core/context/session-state.ts';import { scheduleCheckpointHarvest, type HarvestAck } from '../core/context/checkpoint-harvest.ts';import { parseWbFileName } from '../core/context/corpus-segments.ts';+import { loadCoreBlock } from '../core/core-memory.ts';+import type { TurnContextResult } from '../core/context/turn-context.ts';/** Tighter entity-card fan-out on the PUSH path (eng 4A): the server budget* can't absorb the pull path's 8-card ceiling on a cold cache. */@@ -47,6 +49,16 @@ async function serveCorpusDir(engine: BrainEngine): Promise<string> {return join(configDir(), 'transcripts', 'corpus');}+/** The session's core block for the push path; null on any failure (fail-open, never blocks a pack). */+async function coreForSession(engine: BrainEngine, sourceId: string): Promise<TurnContextResult['core'] | null> {+ try {+ const block = await loadCoreBlock(engine, { sessionSourceId: sourceId, excludePrivate: true });+ return { text: block.text, revision: block.revision, chars_used: block.chars_used, chars_limit: block.chars_limit, truncated: block.truncated };+ } catch {+ return null;+ }+}+export function makeContextPackIpcHandler(engine: BrainEngine,defaultSource: string,@@ -60,6 +72,11 @@ export function makeContextPackIpcHandler(// checkpointLinks field entirely — the engine's capability probe treats// that as "unavailable" and keeps its retry budget, whereas an empty// array is a CONFIRMED empty manifest and settles the poll.+ 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 } : {}) };+ }if (req.manifestOnly === true) {const links = sessionId? await getCheckpointManifest(engine, defaultSource, null, sessionId)@@ -145,6 +162,8 @@ export function makeContextPackIpcHandler(? { checkpointLinks: (await getCheckpointManifest(engine, defaultSource, null, sessionId)) ?? [] }: {}),});+ const core = typeof req.trigger === 'string' && req.trigger.startsWith('session-start') ? await coreForSession(engine, sessionSource) : null;+ if (core) result.core = core;if (sessionId) {// Bank the standing set; advance the wake cursor only on a COMPLETE// pack — a deadline-partial pack may have dropped the delta section,diff --git a/test/remember-batch.test.ts b/test/remember-batch.test.tsnew file mode 100644index 0000000000..566e12337a--- /dev/null+++ b/test/remember-batch.test.ts@@ -0,0 +1,65 @@+import { describe, expect, test } from 'bun:test';+import { childRequestId, runRememberBatch, REMEMBER_BATCH_MAX } from '../src/core/remember-batch.ts';+import { OperationError, verbError } from '../src/core/ops/contract.ts';+import type { OperationContext } from '../src/core/operations.ts';++const ctx = { remote: false } as unknown as OperationContext;+const ve = (code: string, message: string, suggestion: string) => verbError(code as never, message, suggestion);++function fakeSingle(opts: { failWrite?: (p: Record<string, unknown>) => boolean } = {}) {+ const writes: Record<string, unknown>[] = [];+ const handler = async (c: OperationContext, p: Record<string, unknown>) => {+ if (typeof p.fact !== 'string' || !p.fact) throw ve('invalid_params', 'fact must be a non-empty string.', 'x');+ if (typeof p.provenance !== 'string' || !p.provenance) throw ve('provenance_required', 'provenance is required.', 'x');+ if (c.dryRun) return { dry_run: true };+ if (opts.failWrite?.(p)) throw ve('internal_error', 'boom', 'x');+ writes.push(p);+ return { status: 'saved', id: writes.length };+ };+ return { handler, writes };+}++describe('remember items[] batch', () => {+ test('child request ids are deterministic UUIDs, distinct per index', () => {+ const a = childRequestId('11111111-1111-4111-8111-111111111111', 0);+ expect(a).toBe(childRequestId('11111111-1111-4111-8111-111111111111', 0));+ expect(a).not.toBe(childRequestId('11111111-1111-4111-8111-111111111111', 1));+ expect(a).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);+ });++ test('saves each item with shared provenance and child request ids', async () => {+ const { handler, writes } = fakeSingle();+ const out = await runRememberBatch(ctx, { request_id: 'r1', provenance: 'session', items: [{ fact: 'a' }, { fact: 'b', provenance: 'own' }] }, handler, ve);+ expect(out.saved).toBe(2);+ expect(out.partial).toBe(false);+ expect(writes.map(w => w.provenance)).toEqual(['session', 'own']);+ expect(writes[0].request_id).toBe(childRequestId('r1', 0));+ expect(writes[1].request_id).toBe(childRequestId('r1', 1));+ });++ test('one invalid item refuses the whole batch before any write', async () => {+ const { handler, writes } = fakeSingle();+ let err: unknown;+ try { await runRememberBatch(ctx, { provenance: 'p', items: [{ fact: 'ok' }, { fact: '' }] }, handler, ve); } catch (e) { err = e; }+ expect(err).toBeInstanceOf(OperationError);+ expect((err as Error).message).toContain('items[1]');+ expect(writes).toHaveLength(0);+ });++ test('per-item publication failure reports partial with the item error', async () => {+ const { handler, writes } = fakeSingle({ failWrite: p => p.fact === 'bad' });+ const out = await runRememberBatch(ctx, { provenance: 'p', items: [{ fact: 'ok' }, { fact: 'bad' }] }, handler, ve) as { items: { status: string }[]; partial: boolean; next?: string };+ expect(writes).toHaveLength(1);+ expect(out.partial).toBe(true);+ expect(out.items[1].status).toBe('failed');+ expect(out.next).toContain('new request_id');+ });++ test('rejects empty, oversized, unknown-field and fact+items calls', async () => {+ const { handler } = fakeSingle();+ const tooMany = Array.from({ length: REMEMBER_BATCH_MAX + 1 }, (_, i) => ({ fact: String(i) }));+ for (const p of [{ items: [] }, { items: tooMany }, { items: [{ fact: 'a', slug: 'x' }] }, { fact: 'x', items: [{ fact: 'a' }] }]) {+ await expect(runRememberBatch(ctx, { provenance: 'p', ...p }, handler, ve)).rejects.toBeInstanceOf(OperationError);+ }+ });+});