Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(#6007): reconcile in-batch links at the last page's publication; batch docs
garrytancd6e951748d7
diff --git a/docs/guides/remote-mcp.md b/docs/guides/remote-mcp.mdindex 0e4c0a0996..ae05692d70 100644--- a/docs/guides/remote-mcp.md+++ b/docs/guides/remote-mcp.md@@ -380,6 +380,42 @@ brain data. To end one client's access, follow the distinct preview/revisionflows for token invalidation, revocation, or deletion in[MCP administration](../mcp/ADMIN.md#invalidate-tokens-revoke-or-delete).+## Writing many pages++Say to your agent: *"When you save more than three pages to gbrain, use+put_pages with one request_id per batch and wait_ms 25000."*++- **`put_pages`** writes 1-50 complete pages (8 MB of content at most) in one+ call. Every page is an ordinary `put_page` write with the same fences,+ revision checks and receipts; the pages are admitted together, so the+ writer queue has room for the whole batch or the call refuses with+ `queue_capacity` and admits none of them. Keep 5-8 large pages per call:+ the model has to write every page into the tool arguments.+- **One receipt per batch.** The reply lists each page's state, revision or+ error (with its own `fix`), counts, and `next`: `done`, `poll` or+ `fix_pages`. A page refused for its own reason (an invalid slug, a slug+ outside the grant, a revision conflict) does not stop the others.+- **Replays and progress.** Replaying the identical call with the same+ `request_id` never writes twice. Calling `put_pages` with only the+ `request_id` reads the batch's progress without resending the pages. A+ replay with different pages refuses with `idempotency_conflict` and names+ the pages that changed.+- **`wait_ms`** (put_page and put_pages, 0-30000 ms) holds the reply until+ the commit. It is not part of the write, so changing it on a replay is+ safe. When a reply is still pending, follow `next` no sooner than+ `retry_after_ms`.+- **Links.** For remote writes, `[[wikilinks]]` in a page body that point at+ pages already in the same source become plain `mentions` links after the+ commit, and a batch links pages to each other once its last page commits.+ The batch receipt's `links` field shows when they have landed; agents do+ not add them by hand. Typed links still need `add_link`. Turn this off with+ `gbrain config set mcp.remote_auto_links false`.+- **Embedding** runs after the commit. New text is searchable by keyword+ immediately and by meaning once its embedding effect finishes.+- **Request size.** `gbrain serve --http` reads the whole request; the+ simpler HTTP transport caps a request at `GBRAIN_HTTP_MAX_BODY_BYTES`+ (1 MiB by default) and its 413 reply tells the agent to split the batch.+## PGLite brainsPGLite is single-writer. While the service runs, host-side commands that opendiff --git a/docs/mcp/TOOL_REFERENCE.md b/docs/mcp/TOOL_REFERENCE.mdindex 10ed2e610c..ca1c85193d 100644--- a/docs/mcp/TOOL_REFERENCE.md+++ b/docs/mcp/TOOL_REFERENCE.md@@ -264,7 +264,7 @@ List your currently authorized write receipts in one source, newest first. Usefu## `put_page`-Replace a complete canonical Markdown page. Read get_page with include_content:true and pass its revision as expected_revision; force explicitly overwrites the current revision. Omitting both permits creation only. Retain a UUID request_id and repeat identical arguments after transport failure or a pending receipt. Content, tags, sanitized text projections, versions and the committed receipt publish together; embedding and optional Git effects have separate status. Remote callers preserve protected facts/takes fences; automatic graph links are skipped for untrusted writes. A stdio `gbrain serve` sweeps them at startup + on idle; `gbrain serve --http` does not self-sweep — run `gbrain sweep --once` or use trusted local capture/put_page for inline link extraction. Remote callers receive write_through.warning when no repo is configured. For file input use gbrain capture --file PATH --slug SLUG.+Replace a complete canonical Markdown page. Read get_page with include_content:true and pass its revision as expected_revision; force explicitly overwrites the current revision. Omitting both permits creation only. Retain a UUID request_id and repeat identical arguments after transport failure or a pending receipt. Content, tags, sanitized text projections, versions and the committed receipt publish together; embedding and optional Git effects have separate status. Remote callers preserve protected facts/takes fences. For remote writes, `[[wikilinks]]` and markdown links in the body that point at pages already in the same source become plain `mentions` links after the commit (a journaled `links` effect; the receipt's `auto_links.mention_links` says it is queued; `mcp.remote_auto_links false` turns it off). Typed and frontmatter links are skipped for untrusted writes: a stdio `gbrain serve` sweeps them at startup + on idle; `gbrain serve --http` does not self-sweep — run `gbrain sweep --once` or use trusted local capture/put_page for inline link extraction. Pass `wait_ms` (up to 30000) to hold the reply until the commit instead of polling get_write_request. For more than 3 pages, use `put_pages` (full surface). Remote callers receive write_through.warning when no repo is configured. For file input use gbrain capture --file PATH --slug SLUG.| Parameter | Type | Guidance || --- | --- | --- |@@ -275,6 +275,7 @@ Replace a complete canonical Markdown page. Read get_page with include_content:t| `slug` (required) | string | Page slug || `content` (required) | string | Complete markdown content with YAML frontmatter. REPLACES the entire page; this is not a partial edit. Read the canonical page first with `get_page include_content:true` before modifying it. || `allow_empty` | boolean | Allow overwriting an existing non-empty page with empty/whitespace-only content (default: false). Without it, put_page rejects the empty overwrite — the empty-stdin failure class. |+| `wait_ms` | number | How long the reply waits for the commit, counted from arrival: 0-30000 ms, default 5000. Not part of the write's identity, so a replay with a different wait is still the same write. Out of range refuses with `invalid_write_wait` before anything is admitted. || `source_kind` | string | Ingestion channel taxonomy (capture-cli \| put_page \| webhook \| …). Remote callers: SERVER-STAMPED, client value ignored. || `source_uri` | string | Original URI/path/message-id the event carried. Remote callers: SERVER-STAMPED null. || `ingested_via` | string | Richer label paired with source_kind. Remote callers: SERVER-STAMPED. |diff --git a/src/core/persistence/effect-journal.ts b/src/core/persistence/effect-journal.tsindex f22487a471..1463edb72c 100644--- a/src/core/persistence/effect-journal.ts+++ b/src/core/persistence/effect-journal.ts@@ -13,6 +13,7 @@ import { loadConfig } from '../config.ts';import { resolveDefaultVisibility } from '../facts/visibility.ts';import { declarePersistenceProtocol, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';import { refreshFenceClear } from './worktree-refresh-schema.ts';+import { pageBatchChildRequestIds } from './page-batch-id.ts';/*** `snapshot` is the publication's final read of the page, including deleted rows, in this transaction.@@ -52,12 +53,28 @@ export async function queuePublicationEffects(tx: BrainEngine, row: EffectRequesON CONFLICT(request_id,kind) DO NOTHING RETURNING id`,[row.id, revision ?? null, JSON.stringify(data), row.source_id, row.source_incarnation, row.worktree_id, REMOTE_AUTO_LINKS_KEY]);if (queued.length) outcome.auto_links = { ...(outcome.auto_links as Record<string, unknown> | undefined), mention_links: 'queued' };+ await reconcileFinishedBatch(tx, row);}// #5876: the Life Chronicle decision is a ledger row, not an effect; the `chronicle` cycle phase executes it.await recordChronicleDecision(tx, row, snapshot, outcome);}}+/**+ * #6007: when the last unfinished page of a `put_pages` batch publishes, its+ * earlier pages' links effects may have run before this page existed; re-arm+ * them once so forward references inside the batch resolve, with no client poll.+ */+async function reconcileFinishedBatch(tx: BrainEngine, row: EffectRequest & Partial<Pick<WriteRequest, 'intent' | 'principal_kind' | 'principal_id'>>): Promise<void> {+ const batch = row.intent?.page_batch as { id?: unknown; size?: unknown } | undefined;+ if (!batch || typeof batch.id !== 'string' || typeof batch.size !== 'number' || batch.size < 2 || !row.principal_kind || !row.principal_id) return;+ const siblings = await tx.executeRaw<{ id: string; state: string }>(`SELECT id,state FROM persistence_requests+ WHERE principal_kind=$1 AND principal_id=$2 AND request_id=ANY($3::uuid[]) AND id<>$4::uuid AND intent->'page_batch'->>'id'=$5`,+ [row.principal_kind, row.principal_id, pageBatchChildRequestIds(batch.id, batch.size), row.id, batch.id]);+ if (siblings.some(sibling => !['committed', 'conflict', 'failed', 'cancelled'].includes(sibling.state))) return;+ await queueLinksReconcile(tx, { sourceId: row.source_id, requestIds: [row.id, ...siblings.filter(sibling => sibling.state === 'committed').map(sibling => sibling.id)] });+}+/*** Re-arm the `links` effects of requests published together (a batch), so each* page's mention links resolve against every page the batch created. Call itdiff --git a/src/core/persistence/page-batch-id.ts b/src/core/persistence/page-batch-id.tsnew file mode 100644index 0000000000..51ea91b571--- /dev/null+++ b/src/core/persistence/page-batch-id.ts@@ -0,0 +1,19 @@+/** #6007: deterministic request ids of `put_pages` children (page-batch.ts). */+import { createHash } from 'node:crypto';++/** RFC 4122 namespace for put_pages child request ids (fixed forever: changing it re-admits replays). */+const CHILD_NAMESPACE = Buffer.from('a7f4c2d0600742b8b1e95d3c8f0a6007', 'hex');++/** UUIDv5(namespace, "put_pages:v1:<batch>:<index>"). */+export function pageBatchChildRequestId(batchId: string, index: number): string {+ const hash = createHash('sha1').update(CHILD_NAMESPACE).update(`put_pages:v1:${batchId.toLowerCase()}:${index}`).digest();+ hash[6] = (hash[6]! & 0x0f) | 0x50;+ hash[8] = (hash[8]! & 0x3f) | 0x80;+ const hex = hash.subarray(0, 16).toString('hex');+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;+}++/** Every request id a batch can hold, in index order. */+export function pageBatchChildRequestIds(batchId: string, size: number): string[] {+ return Array.from({ length: size }, (_, index) => pageBatchChildRequestId(batchId, index));+}diff --git a/src/core/persistence/page-batch.ts b/src/core/persistence/page-batch.tsindex ff7fd47fbb..ba0c79b66a 100644--- a/src/core/persistence/page-batch.ts+++ b/src/core/persistence/page-batch.ts@@ -10,11 +10,13 @@* `put_pages` with only `request_id` reads the batch status without resending* any content.*/-import { createHash } from 'node:crypto';import type { OperationContext } from '../ops/contract.ts';import { OperationError, opError } from '../ops/contract.ts';import { admitWrites, type WriteAdmission } from './journal.ts';import { queueLinksReconcile } from './effect-journal.ts';+import { pageBatchChildRequestId, pageBatchChildRequestIds } from './page-batch-id.ts';++export { pageBatchChildRequestId };import { isTerminal, type WriteRequest } from './model.ts';import { estimatedRetryAfterMs, waitForWrites, writeResponse } from './service.ts';import { initializeLocalPersistence, pageMutationSource, preparePageAdmission, requestPrincipalForContext } from './page-mutations.ts';@@ -30,18 +32,6 @@ const PREPARE_CONCURRENCY = 4;/** Batch admission is one transaction over every page; it gets more than a single write's budget. */const BATCH_ADMISSION_BUDGET_MS = 30_000;const PAGE_KEYS = new Set(['slug', 'content', 'expected_revision', 'allow_empty']);-/** RFC 4122 namespace for put_pages child request ids (fixed forever: changing it re-admits replays). */-const CHILD_NAMESPACE = Buffer.from('a7f4c2d0600742b8b1e95d3c8f0a6007', 'hex');--/** UUIDv5(namespace, "put_pages:v1:<batch>:<index>"). */-export function pageBatchChildRequestId(batchId: string, index: number): string {- const hash = createHash('sha1').update(CHILD_NAMESPACE).update(`put_pages:v1:${batchId.toLowerCase()}:${index}`).digest();- hash[6] = (hash[6]! & 0x0f) | 0x50;- hash[8] = (hash[8]! & 0x3f) | 0x80;- const hex = hash.subarray(0, 16).toString('hex');- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;-}-interface BatchPage { slug: string; content: string; expected_revision?: unknown; allow_empty?: unknown }interface PageResult { index: number; slug: string; row?: WriteRequest; refusal?: OperationError; typeWarning?: PageTypeWarning | null }interface BatchMarker { id: string; index: number; size: number }@@ -82,7 +72,7 @@ function markerOf(row: WriteRequest): BatchMarker | null {async function readBatch(ctx: OperationContext, batchId: string): Promise<WriteRequest[]> {const principal = await requestPrincipalForContext(ctx);- const ids = Array.from({ length: PAGE_BATCH_MAX_PAGES }, (_, index) => pageBatchChildRequestId(batchId, index));+ const ids = pageBatchChildRequestIds(batchId, PAGE_BATCH_MAX_PAGES);const rows = await ctx.engine.executeRaw<WriteRequest>(`SELECT * FROM persistence_requestsWHERE principal_kind=$1 AND principal_id=$2 AND request_id=ANY($3::uuid[])`, [principal.kind, principal.id, ids]);return rows.filter(row => markerOf(row)?.id === batchId).sort((a, b) => markerOf(a)!.index - markerOf(b)!.index);diff --git a/test/put-pages-batch.test.ts b/test/put-pages-batch.test.tsindex c4fe670d57..d2b088926f 100644--- a/test/put-pages-batch.test.ts+++ b/test/put-pages-batch.test.ts@@ -117,6 +117,24 @@ describe('put_pages', () => {});});+describe('put_pages links', () => {+ test('forward references inside a batch become mention links without a status poll', async () => {+ const batch = randomUUID();+ const result = await putPages.handler(ctx(), { request_id: batch, pages: [+ page('notes/fwd-a', 'See [[notes/fwd-b]] for details.'), page('notes/fwd-b', 'Back to [[notes/fwd-a]].')] }) as any;+ expect(result.state).toBe('committed');+ const edges = async () => engine.executeRaw<{ edge: string }>(`SELECT f.slug || '>' || t.slug AS edge FROM links l+ JOIN pages f ON f.id=l.from_page_id JOIN pages t ON t.id=l.to_page_id WHERE l.link_source='mcp-remote-mention' ORDER BY 1`);+ const deadline = Date.now() + 15_000;+ while ((await edges()).length < 2 && Date.now() < deadline) await Bun.sleep(100);+ expect((await edges()).map(row => row.edge)).toEqual(['notes/fwd-a>notes/fwd-b', 'notes/fwd-b>notes/fwd-a']);+ // The last page's publication re-armed every page's links pass once, so an+ // earlier page whose pass ran before its target existed is linked anyway.+ const rearmed = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM persistence_effects WHERE kind='links' AND data ? 'batch_reconciled'");+ expect(rearmed[0]!.n).toBe(2);+ }, 30_000);+});+describe('put_page wait_ms', () => {test('is not part of the write identity: a replay with another wait is not a conflict', async () => {const request_id = randomUUID();